Context stringlengths 227 76.5k | target stringlengths 0 11.6k | file_name stringlengths 21 79 | start int64 14 3.67k | end int64 16 3.69k |
|---|---|---|---|---|
/-
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 Mathlib.Order.Filter.SmallSets
import Mathlib.Topology.UniformSpace.Defs
import Mathlib.Topology.ContinuousOn
/-!
# Basic results on uniform spaces
Uniform spaces are a generalization of metric spaces and topological groups.
## Main definitions
In this file we define a complete lattice structure on the type `UniformSpace X`
of uniform structures on `X`, as well as the pullback (`UniformSpace.comap`) of uniform structures
coming from the pullback of filters.
Like distance functions, uniform structures cannot be pushed forward in general.
## Notations
Localized in `Uniformity`, we have the notation `𝓤 X` for the uniformity on a uniform space `X`,
and `○` for composition of relations, seen as terms with type `Set (X × X)`.
## References
The formalization uses the books:
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
But it makes a more systematic use of the filter library.
-/
open Set Filter Topology
universe u v ua ub uc ud
/-!
### Relations, seen as `Set (α × α)`
-/
variable {α : Type ua} {β : Type ub} {γ : Type uc} {δ : Type ud} {ι : Sort*}
open Uniformity
section UniformSpace
variable [UniformSpace α]
/-- If `s ∈ 𝓤 α`, then for any natural `n`, for a subset `t` of a sufficiently small set in `𝓤 α`,
we have `t ○ t ○ ... ○ t ⊆ s` (`n` compositions). -/
theorem eventually_uniformity_iterate_comp_subset {s : Set (α × α)} (hs : s ∈ 𝓤 α) (n : ℕ) :
∀ᶠ t in (𝓤 α).smallSets, (t ○ ·)^[n] t ⊆ s := by
suffices ∀ᶠ t in (𝓤 α).smallSets, t ⊆ s ∧ (t ○ ·)^[n] t ⊆ s from (eventually_and.1 this).2
induction n generalizing s with
| zero => simpa
| succ _ ihn =>
rcases comp_mem_uniformity_sets hs with ⟨t, htU, hts⟩
refine (ihn htU).mono fun U hU => ?_
rw [Function.iterate_succ_apply']
exact
⟨hU.1.trans <| (subset_comp_self <| refl_le_uniformity htU).trans hts,
(compRel_mono hU.1 hU.2).trans hts⟩
/-- If `s ∈ 𝓤 α`, then for a subset `t` of a sufficiently small set in `𝓤 α`,
we have `t ○ t ⊆ s`. -/
theorem eventually_uniformity_comp_subset {s : Set (α × α)} (hs : s ∈ 𝓤 α) :
∀ᶠ t in (𝓤 α).smallSets, t ○ t ⊆ s :=
eventually_uniformity_iterate_comp_subset hs 1
/-!
### Balls in uniform spaces
-/
namespace UniformSpace
open UniformSpace (ball)
lemma isOpen_ball (x : α) {V : Set (α × α)} (hV : IsOpen V) : IsOpen (ball x V) :=
hV.preimage <| .prodMk_right _
lemma isClosed_ball (x : α) {V : Set (α × α)} (hV : IsClosed V) : IsClosed (ball x V) :=
hV.preimage <| .prodMk_right _
/-!
### Neighborhoods in uniform spaces
-/
theorem hasBasis_nhds_prod (x y : α) :
HasBasis (𝓝 (x, y)) (fun s => s ∈ 𝓤 α ∧ IsSymmetricRel s) fun s => ball x s ×ˢ ball y s := by
rw [nhds_prod_eq]
apply (hasBasis_nhds x).prod_same_index (hasBasis_nhds y)
rintro U V ⟨U_in, U_symm⟩ ⟨V_in, V_symm⟩
exact
⟨U ∩ V, ⟨(𝓤 α).inter_sets U_in V_in, U_symm.inter V_symm⟩, ball_inter_left x U V,
ball_inter_right y U V⟩
end UniformSpace
open UniformSpace
theorem nhds_eq_uniformity_prod {a b : α} :
𝓝 (a, b) =
(𝓤 α).lift' fun s : Set (α × α) => { y : α | (y, a) ∈ s } ×ˢ { y : α | (b, y) ∈ s } := by
rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift']
· exact fun s => monotone_const.set_prod monotone_preimage
· refine fun t => Monotone.set_prod ?_ monotone_const
exact monotone_preimage (f := fun y => (y, a))
theorem nhdset_of_mem_uniformity {d : Set (α × α)} (s : Set (α × α)) (hd : d ∈ 𝓤 α) :
∃ t : Set (α × α), IsOpen t ∧ s ⊆ t ∧
t ⊆ { p | ∃ x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d } := by
let cl_d := { p : α × α | ∃ x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d }
have : ∀ p ∈ s, ∃ t, t ⊆ cl_d ∧ IsOpen t ∧ p ∈ t := fun ⟨x, y⟩ hp =>
mem_nhds_iff.mp <|
show cl_d ∈ 𝓝 (x, y) by
rw [nhds_eq_uniformity_prod, mem_lift'_sets]
· exact ⟨d, hd, fun ⟨a, b⟩ ⟨ha, hb⟩ => ⟨x, y, ha, hp, hb⟩⟩
· exact fun _ _ h _ h' => ⟨h h'.1, h h'.2⟩
choose t ht using this
exact ⟨(⋃ p : α × α, ⋃ h : p ∈ s, t p h : Set (α × α)),
isOpen_iUnion fun p : α × α => isOpen_iUnion fun hp => (ht p hp).right.left,
fun ⟨a, b⟩ hp => by
simp only [mem_iUnion, Prod.exists]; exact ⟨a, b, hp, (ht (a, b) hp).right.right⟩,
iUnion_subset fun p => iUnion_subset fun hp => (ht p hp).left⟩
/-- Entourages are neighborhoods of the diagonal. -/
theorem nhds_le_uniformity (x : α) : 𝓝 (x, x) ≤ 𝓤 α := by
intro V V_in
rcases comp_symm_mem_uniformity_sets V_in with ⟨w, w_in, w_symm, w_sub⟩
have : ball x w ×ˢ ball x w ∈ 𝓝 (x, x) := by
rw [nhds_prod_eq]
exact prod_mem_prod (ball_mem_nhds x w_in) (ball_mem_nhds x w_in)
apply mem_of_superset this
rintro ⟨u, v⟩ ⟨u_in, v_in⟩
exact w_sub (mem_comp_of_mem_ball w_symm u_in v_in)
/-- Entourages are neighborhoods of the diagonal. -/
theorem iSup_nhds_le_uniformity : ⨆ x : α, 𝓝 (x, x) ≤ 𝓤 α :=
iSup_le nhds_le_uniformity
/-- Entourages are neighborhoods of the diagonal. -/
theorem nhdsSet_diagonal_le_uniformity : 𝓝ˢ (diagonal α) ≤ 𝓤 α :=
(nhdsSet_diagonal α).trans_le iSup_nhds_le_uniformity
section
variable (α)
theorem UniformSpace.has_seq_basis [IsCountablyGenerated <| 𝓤 α] :
∃ V : ℕ → Set (α × α), HasAntitoneBasis (𝓤 α) V ∧ ∀ n, IsSymmetricRel (V n) :=
let ⟨U, hsym, hbasis⟩ := (@UniformSpace.hasBasis_symmetric α _).exists_antitone_subbasis
⟨U, hbasis, fun n => (hsym n).2⟩
end
/-!
### Closure and interior in uniform spaces
-/
theorem closure_eq_uniformity (s : Set <| α × α) :
closure s = ⋂ V ∈ { V | V ∈ 𝓤 α ∧ IsSymmetricRel V }, V ○ s ○ V := by
ext ⟨x, y⟩
simp +contextual only
[mem_closure_iff_nhds_basis (UniformSpace.hasBasis_nhds_prod x y), mem_iInter, mem_setOf_eq,
and_imp, mem_comp_comp, exists_prop, ← mem_inter_iff, inter_comm, Set.Nonempty]
theorem uniformity_hasBasis_closed :
HasBasis (𝓤 α) (fun V : Set (α × α) => V ∈ 𝓤 α ∧ IsClosed V) id := by
refine Filter.hasBasis_self.2 fun t h => ?_
rcases comp_comp_symm_mem_uniformity_sets h with ⟨w, w_in, w_symm, r⟩
refine ⟨closure w, mem_of_superset w_in subset_closure, isClosed_closure, ?_⟩
refine Subset.trans ?_ r
rw [closure_eq_uniformity]
apply iInter_subset_of_subset
apply iInter_subset
exact ⟨w_in, w_symm⟩
theorem uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure :=
Eq.symm <| uniformity_hasBasis_closed.lift'_closure_eq_self fun _ => And.right
theorem Filter.HasBasis.uniformity_closure {p : ι → Prop} {U : ι → Set (α × α)}
(h : (𝓤 α).HasBasis p U) : (𝓤 α).HasBasis p fun i => closure (U i) :=
(@uniformity_eq_uniformity_closure α _).symm ▸ h.lift'_closure
/-- Closed entourages form a basis of the uniformity filter. -/
theorem uniformity_hasBasis_closure : HasBasis (𝓤 α) (fun V : Set (α × α) => V ∈ 𝓤 α) closure :=
(𝓤 α).basis_sets.uniformity_closure
theorem closure_eq_inter_uniformity {t : Set (α × α)} : closure t = ⋂ d ∈ 𝓤 α, d ○ (t ○ d) :=
calc
closure t = ⋂ (V) (_ : V ∈ 𝓤 α ∧ IsSymmetricRel V), V ○ t ○ V := closure_eq_uniformity t
_ = ⋂ V ∈ 𝓤 α, V ○ t ○ V :=
Eq.symm <|
UniformSpace.hasBasis_symmetric.biInter_mem fun _ _ hV =>
compRel_mono (compRel_mono hV Subset.rfl) hV
_ = ⋂ V ∈ 𝓤 α, V ○ (t ○ V) := by simp only [compRel_assoc]
theorem uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior :=
le_antisymm
(le_iInf₂ fun d hd => by
let ⟨s, hs, hs_comp⟩ := comp3_mem_uniformity hd
let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs
have : s ⊆ interior d :=
calc
s ⊆ t := hst
_ ⊆ interior d :=
ht.subset_interior_iff.mpr fun x (hx : x ∈ t) =>
let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp hx
hs_comp ⟨x, h₁, y, h₂, h₃⟩
have : interior d ∈ 𝓤 α := by filter_upwards [hs] using this
simp [this])
fun _ hs => ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset
theorem interior_mem_uniformity {s : Set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by
rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs
theorem mem_uniformity_isClosed {s : Set (α × α)} (h : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, IsClosed t ∧ t ⊆ s :=
let ⟨t, ⟨ht_mem, htc⟩, hts⟩ := uniformity_hasBasis_closed.mem_iff.1 h
⟨t, ht_mem, htc, hts⟩
theorem isOpen_iff_isOpen_ball_subset {s : Set α} :
IsOpen s ↔ ∀ x ∈ s, ∃ V ∈ 𝓤 α, IsOpen V ∧ ball x V ⊆ s := by
rw [isOpen_iff_ball_subset]
constructor <;> intro h x hx
· obtain ⟨V, hV, hV'⟩ := h x hx
exact
⟨interior V, interior_mem_uniformity hV, isOpen_interior,
(ball_mono interior_subset x).trans hV'⟩
· obtain ⟨V, hV, -, hV'⟩ := h x hx
exact ⟨V, hV, hV'⟩
@[deprecated (since := "2024-11-18")] alias
isOpen_iff_open_ball_subset := isOpen_iff_isOpen_ball_subset
/-- The uniform neighborhoods of all points of a dense set cover the whole space. -/
theorem Dense.biUnion_uniformity_ball {s : Set α} {U : Set (α × α)} (hs : Dense s) (hU : U ∈ 𝓤 α) :
⋃ x ∈ s, ball x U = univ := by
refine iUnion₂_eq_univ_iff.2 fun y => ?_
rcases hs.inter_nhds_nonempty (mem_nhds_right y hU) with ⟨x, hxs, hxy : (x, y) ∈ U⟩
exact ⟨x, hxs, hxy⟩
/-- The uniform neighborhoods of all points of a dense indexed collection cover the whole space. -/
lemma DenseRange.iUnion_uniformity_ball {ι : Type*} {xs : ι → α}
(xs_dense : DenseRange xs) {U : Set (α × α)} (hU : U ∈ uniformity α) :
⋃ i, UniformSpace.ball (xs i) U = univ := by
rw [← biUnion_range (f := xs) (g := fun x ↦ UniformSpace.ball x U)]
exact Dense.biUnion_uniformity_ball xs_dense hU
/-!
### Uniformity bases
-/
/-- Open elements of `𝓤 α` form a basis of `𝓤 α`. -/
theorem uniformity_hasBasis_open : HasBasis (𝓤 α) (fun V : Set (α × α) => V ∈ 𝓤 α ∧ IsOpen V) id :=
hasBasis_self.2 fun s hs =>
⟨interior s, interior_mem_uniformity hs, isOpen_interior, interior_subset⟩
theorem Filter.HasBasis.mem_uniformity_iff {p : β → Prop} {s : β → Set (α × α)}
(h : (𝓤 α).HasBasis p s) {t : Set (α × α)} :
t ∈ 𝓤 α ↔ ∃ i, p i ∧ ∀ a b, (a, b) ∈ s i → (a, b) ∈ t :=
h.mem_iff.trans <| by simp only [Prod.forall, subset_def]
/-- Open elements `s : Set (α × α)` of `𝓤 α` such that `(x, y) ∈ s ↔ (y, x) ∈ s` form a basis
of `𝓤 α`. -/
theorem uniformity_hasBasis_open_symmetric :
HasBasis (𝓤 α) (fun V : Set (α × α) => V ∈ 𝓤 α ∧ IsOpen V ∧ IsSymmetricRel V) id := by
simp only [← and_assoc]
refine uniformity_hasBasis_open.restrict fun s hs => ⟨symmetrizeRel s, ?_⟩
exact
⟨⟨symmetrize_mem_uniformity hs.1, IsOpen.inter hs.2 (hs.2.preimage continuous_swap)⟩,
symmetric_symmetrizeRel s, symmetrizeRel_subset_self s⟩
theorem comp_open_symm_mem_uniformity_sets {s : Set (α × α)} (hs : s ∈ 𝓤 α) :
∃ t ∈ 𝓤 α, IsOpen t ∧ IsSymmetricRel t ∧ t ○ t ⊆ s := by
obtain ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs
obtain ⟨u, ⟨hu₁, hu₂, hu₃⟩, hu₄ : u ⊆ t⟩ := uniformity_hasBasis_open_symmetric.mem_iff.mp ht₁
exact ⟨u, hu₁, hu₂, hu₃, (compRel_mono hu₄ hu₄).trans ht₂⟩
end UniformSpace
open uniformity
section Constructions
instance : PartialOrder (UniformSpace α) :=
PartialOrder.lift (fun u => 𝓤[u]) fun _ _ => UniformSpace.ext
protected theorem UniformSpace.le_def {u₁ u₂ : UniformSpace α} : u₁ ≤ u₂ ↔ 𝓤[u₁] ≤ 𝓤[u₂] := Iff.rfl
instance : InfSet (UniformSpace α) :=
⟨fun s =>
UniformSpace.ofCore
{ uniformity := ⨅ u ∈ s, 𝓤[u]
refl := le_iInf fun u => le_iInf fun _ => u.toCore.refl
symm := le_iInf₂ fun u hu =>
le_trans (map_mono <| iInf_le_of_le _ <| iInf_le _ hu) u.symm
comp := le_iInf₂ fun u hu =>
le_trans (lift'_mono (iInf_le_of_le _ <| iInf_le _ hu) <| le_rfl) u.comp }⟩
protected theorem UniformSpace.sInf_le {tt : Set (UniformSpace α)} {t : UniformSpace α}
(h : t ∈ tt) : sInf tt ≤ t :=
show ⨅ u ∈ tt, 𝓤[u] ≤ 𝓤[t] from iInf₂_le t h
protected theorem UniformSpace.le_sInf {tt : Set (UniformSpace α)} {t : UniformSpace α}
(h : ∀ t' ∈ tt, t ≤ t') : t ≤ sInf tt :=
show 𝓤[t] ≤ ⨅ u ∈ tt, 𝓤[u] from le_iInf₂ h
instance : Top (UniformSpace α) :=
⟨@UniformSpace.mk α ⊤ ⊤ le_top le_top fun x ↦ by simp only [nhds_top, comap_top]⟩
instance : Bot (UniformSpace α) :=
⟨{ toTopologicalSpace := ⊥
uniformity := 𝓟 idRel
symm := by simp [Tendsto]
comp := lift'_le (mem_principal_self _) <| principal_mono.2 id_compRel.subset
nhds_eq_comap_uniformity := fun s => by
let _ : TopologicalSpace α := ⊥; have := discreteTopology_bot α
simp [idRel] }⟩
instance : Min (UniformSpace α) :=
⟨fun u₁ u₂ =>
{ uniformity := 𝓤[u₁] ⊓ 𝓤[u₂]
symm := u₁.symm.inf u₂.symm
comp := (lift'_inf_le _ _ _).trans <| inf_le_inf u₁.comp u₂.comp
toTopologicalSpace := u₁.toTopologicalSpace ⊓ u₂.toTopologicalSpace
nhds_eq_comap_uniformity := fun _ ↦ by
rw [@nhds_inf _ u₁.toTopologicalSpace _, @nhds_eq_comap_uniformity _ u₁,
@nhds_eq_comap_uniformity _ u₂, comap_inf] }⟩
instance : CompleteLattice (UniformSpace α) :=
{ inferInstanceAs (PartialOrder (UniformSpace α)) with
sup := fun a b => sInf { x | a ≤ x ∧ b ≤ x }
le_sup_left := fun _ _ => UniformSpace.le_sInf fun _ ⟨h, _⟩ => h
le_sup_right := fun _ _ => UniformSpace.le_sInf fun _ ⟨_, h⟩ => h
sup_le := fun _ _ _ h₁ h₂ => UniformSpace.sInf_le ⟨h₁, h₂⟩
inf := (· ⊓ ·)
le_inf := fun a _ _ h₁ h₂ => show a.uniformity ≤ _ from le_inf h₁ h₂
inf_le_left := fun a _ => show _ ≤ a.uniformity from inf_le_left
inf_le_right := fun _ b => show _ ≤ b.uniformity from inf_le_right
top := ⊤
le_top := fun a => show a.uniformity ≤ ⊤ from le_top
bot := ⊥
bot_le := fun u => u.toCore.refl
sSup := fun tt => sInf { t | ∀ t' ∈ tt, t' ≤ t }
le_sSup := fun _ _ h => UniformSpace.le_sInf fun _ h' => h' _ h
sSup_le := fun _ _ h => UniformSpace.sInf_le h
sInf := sInf
le_sInf := fun _ _ hs => UniformSpace.le_sInf hs
sInf_le := fun _ _ ha => UniformSpace.sInf_le ha }
theorem iInf_uniformity {ι : Sort*} {u : ι → UniformSpace α} : 𝓤[iInf u] = ⨅ i, 𝓤[u i] :=
iInf_range
theorem inf_uniformity {u v : UniformSpace α} : 𝓤[u ⊓ v] = 𝓤[u] ⊓ 𝓤[v] := rfl
lemma bot_uniformity : 𝓤[(⊥ : UniformSpace α)] = 𝓟 idRel := rfl
lemma top_uniformity : 𝓤[(⊤ : UniformSpace α)] = ⊤ := rfl
instance inhabitedUniformSpace : Inhabited (UniformSpace α) :=
⟨⊥⟩
instance inhabitedUniformSpaceCore : Inhabited (UniformSpace.Core α) :=
⟨@UniformSpace.toCore _ default⟩
instance [Subsingleton α] : Unique (UniformSpace α) where
uniq u := bot_unique <| le_principal_iff.2 <| by
rw [idRel, ← diagonal, diagonal_eq_univ]; exact univ_mem
/-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f`
is the inverse image in the filter sense of the induced function `α × α → β × β`.
See note [reducible non-instances]. -/
abbrev UniformSpace.comap (f : α → β) (u : UniformSpace β) : UniformSpace α where
uniformity := 𝓤[u].comap fun p : α × α => (f p.1, f p.2)
symm := by
simp only [tendsto_comap_iff, Prod.swap, (· ∘ ·)]
exact tendsto_swap_uniformity.comp tendsto_comap
comp := le_trans
(by
rw [comap_lift'_eq, comap_lift'_eq2]
· exact lift'_mono' fun s _ ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩ => ⟨f x, h₁, h₂⟩
· exact monotone_id.compRel monotone_id)
(comap_mono u.comp)
toTopologicalSpace := u.toTopologicalSpace.induced f
nhds_eq_comap_uniformity x := by
simp only [nhds_induced, nhds_eq_comap_uniformity, comap_comap, Function.comp_def]
theorem uniformity_comap {_ : UniformSpace β} (f : α → β) :
𝓤[UniformSpace.comap f ‹_›] = comap (Prod.map f f) (𝓤 β) :=
rfl
lemma ball_preimage {f : α → β} {U : Set (β × β)} {x : α} :
UniformSpace.ball x (Prod.map f f ⁻¹' U) = f ⁻¹' UniformSpace.ball (f x) U := by
ext : 1
simp only [UniformSpace.ball, mem_preimage, Prod.map_apply]
@[simp]
theorem uniformSpace_comap_id {α : Type*} : UniformSpace.comap (id : α → α) = id := by
ext : 2
rw [uniformity_comap, Prod.map_id, comap_id]
theorem UniformSpace.comap_comap {α β γ} {uγ : UniformSpace γ} {f : α → β} {g : β → γ} :
UniformSpace.comap (g ∘ f) uγ = UniformSpace.comap f (UniformSpace.comap g uγ) := by
ext1
simp only [uniformity_comap, Filter.comap_comap, Prod.map_comp_map]
theorem UniformSpace.comap_inf {α γ} {u₁ u₂ : UniformSpace γ} {f : α → γ} :
(u₁ ⊓ u₂).comap f = u₁.comap f ⊓ u₂.comap f :=
UniformSpace.ext Filter.comap_inf
theorem UniformSpace.comap_iInf {ι α γ} {u : ι → UniformSpace γ} {f : α → γ} :
(⨅ i, u i).comap f = ⨅ i, (u i).comap f := by
ext : 1
simp [uniformity_comap, iInf_uniformity]
theorem UniformSpace.comap_mono {α γ} {f : α → γ} :
Monotone fun u : UniformSpace γ => u.comap f := fun _ _ hu =>
Filter.comap_mono hu
theorem uniformContinuous_iff {α β} {uα : UniformSpace α} {uβ : UniformSpace β} {f : α → β} :
UniformContinuous f ↔ uα ≤ uβ.comap f :=
Filter.map_le_iff_le_comap
theorem le_iff_uniformContinuous_id {u v : UniformSpace α} :
u ≤ v ↔ @UniformContinuous _ _ u v id := by
rw [uniformContinuous_iff, uniformSpace_comap_id, id]
theorem uniformContinuous_comap {f : α → β} [u : UniformSpace β] :
@UniformContinuous α β (UniformSpace.comap f u) u f :=
tendsto_comap
theorem uniformContinuous_comap' {f : γ → β} {g : α → γ} [v : UniformSpace β] [u : UniformSpace α]
(h : UniformContinuous (f ∘ g)) : @UniformContinuous α γ u (UniformSpace.comap f v) g :=
tendsto_comap_iff.2 h
namespace UniformSpace
theorem to_nhds_mono {u₁ u₂ : UniformSpace α} (h : u₁ ≤ u₂) (a : α) :
@nhds _ (@UniformSpace.toTopologicalSpace _ u₁) a ≤
@nhds _ (@UniformSpace.toTopologicalSpace _ u₂) a := by
rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact lift'_mono h le_rfl
theorem toTopologicalSpace_mono {u₁ u₂ : UniformSpace α} (h : u₁ ≤ u₂) :
@UniformSpace.toTopologicalSpace _ u₁ ≤ @UniformSpace.toTopologicalSpace _ u₂ :=
le_of_nhds_le_nhds <| to_nhds_mono h
theorem toTopologicalSpace_comap {f : α → β} {u : UniformSpace β} :
@UniformSpace.toTopologicalSpace _ (UniformSpace.comap f u) =
TopologicalSpace.induced f (@UniformSpace.toTopologicalSpace β u) :=
rfl
lemma uniformSpace_eq_bot {u : UniformSpace α} : u = ⊥ ↔ idRel ∈ 𝓤[u] :=
le_bot_iff.symm.trans le_principal_iff
protected lemma _root_.Filter.HasBasis.uniformSpace_eq_bot {ι p} {s : ι → Set (α × α)}
{u : UniformSpace α} (h : 𝓤[u].HasBasis p s) :
u = ⊥ ↔ ∃ i, p i ∧ Pairwise fun x y : α ↦ (x, y) ∉ s i := by
simp [uniformSpace_eq_bot, h.mem_iff, subset_def, Pairwise, not_imp_not]
theorem toTopologicalSpace_bot : @UniformSpace.toTopologicalSpace α ⊥ = ⊥ := rfl
theorem toTopologicalSpace_top : @UniformSpace.toTopologicalSpace α ⊤ = ⊤ := rfl
theorem toTopologicalSpace_iInf {ι : Sort*} {u : ι → UniformSpace α} :
(iInf u).toTopologicalSpace = ⨅ i, (u i).toTopologicalSpace :=
TopologicalSpace.ext_nhds fun a ↦ by simp only [@nhds_eq_comap_uniformity _ (iInf u), nhds_iInf,
iInf_uniformity, @nhds_eq_comap_uniformity _ (u _), Filter.comap_iInf]
theorem toTopologicalSpace_sInf {s : Set (UniformSpace α)} :
(sInf s).toTopologicalSpace = ⨅ i ∈ s, @UniformSpace.toTopologicalSpace α i := by
rw [sInf_eq_iInf]
simp only [← toTopologicalSpace_iInf]
theorem toTopologicalSpace_inf {u v : UniformSpace α} :
(u ⊓ v).toTopologicalSpace = u.toTopologicalSpace ⊓ v.toTopologicalSpace :=
rfl
end UniformSpace
theorem UniformContinuous.continuous [UniformSpace α] [UniformSpace β] {f : α → β}
(hf : UniformContinuous f) : Continuous f :=
continuous_iff_le_induced.mpr <| UniformSpace.toTopologicalSpace_mono <|
uniformContinuous_iff.1 hf
/-- Uniform space structure on `ULift α`. -/
instance ULift.uniformSpace [UniformSpace α] : UniformSpace (ULift α) :=
UniformSpace.comap ULift.down ‹_›
/-- Uniform space structure on `αᵒᵈ`. -/
instance OrderDual.instUniformSpace [UniformSpace α] : UniformSpace (αᵒᵈ) :=
‹UniformSpace α›
section UniformContinuousInfi
-- TODO: add an `iff` lemma?
theorem UniformContinuous.inf_rng {f : α → β} {u₁ : UniformSpace α} {u₂ u₃ : UniformSpace β}
(h₁ : UniformContinuous[u₁, u₂] f) (h₂ : UniformContinuous[u₁, u₃] f) :
UniformContinuous[u₁, u₂ ⊓ u₃] f :=
tendsto_inf.mpr ⟨h₁, h₂⟩
theorem UniformContinuous.inf_dom_left {f : α → β} {u₁ u₂ : UniformSpace α} {u₃ : UniformSpace β}
(hf : UniformContinuous[u₁, u₃] f) : UniformContinuous[u₁ ⊓ u₂, u₃] f :=
tendsto_inf_left hf
theorem UniformContinuous.inf_dom_right {f : α → β} {u₁ u₂ : UniformSpace α} {u₃ : UniformSpace β}
(hf : UniformContinuous[u₂, u₃] f) : UniformContinuous[u₁ ⊓ u₂, u₃] f :=
tendsto_inf_right hf
theorem uniformContinuous_sInf_dom {f : α → β} {u₁ : Set (UniformSpace α)} {u₂ : UniformSpace β}
{u : UniformSpace α} (h₁ : u ∈ u₁) (hf : UniformContinuous[u, u₂] f) :
UniformContinuous[sInf u₁, u₂] f := by
delta UniformContinuous
rw [sInf_eq_iInf', iInf_uniformity]
exact tendsto_iInf' ⟨u, h₁⟩ hf
theorem uniformContinuous_sInf_rng {f : α → β} {u₁ : UniformSpace α} {u₂ : Set (UniformSpace β)} :
UniformContinuous[u₁, sInf u₂] f ↔ ∀ u ∈ u₂, UniformContinuous[u₁, u] f := by
delta UniformContinuous
rw [sInf_eq_iInf', iInf_uniformity, tendsto_iInf, SetCoe.forall]
theorem uniformContinuous_iInf_dom {f : α → β} {u₁ : ι → UniformSpace α} {u₂ : UniformSpace β}
{i : ι} (hf : UniformContinuous[u₁ i, u₂] f) : UniformContinuous[iInf u₁, u₂] f := by
delta UniformContinuous
rw [iInf_uniformity]
exact tendsto_iInf' i hf
theorem uniformContinuous_iInf_rng {f : α → β} {u₁ : UniformSpace α} {u₂ : ι → UniformSpace β} :
UniformContinuous[u₁, iInf u₂] f ↔ ∀ i, UniformContinuous[u₁, u₂ i] f := by
delta UniformContinuous
rw [iInf_uniformity, tendsto_iInf]
end UniformContinuousInfi
/-- A uniform space with the discrete uniformity has the discrete topology. -/
theorem discreteTopology_of_discrete_uniformity [hα : UniformSpace α] (h : uniformity α = 𝓟 idRel) :
DiscreteTopology α :=
⟨(UniformSpace.ext h.symm : ⊥ = hα) ▸ rfl⟩
instance : UniformSpace Empty := ⊥
instance : UniformSpace PUnit := ⊥
instance : UniformSpace Bool := ⊥
instance : UniformSpace ℕ := ⊥
instance : UniformSpace ℤ := ⊥
section
variable [UniformSpace α]
open Additive Multiplicative
instance : UniformSpace (Additive α) := ‹UniformSpace α›
instance : UniformSpace (Multiplicative α) := ‹UniformSpace α›
theorem uniformContinuous_ofMul : UniformContinuous (ofMul : α → Additive α) :=
uniformContinuous_id
theorem uniformContinuous_toMul : UniformContinuous (toMul : Additive α → α) :=
uniformContinuous_id
theorem uniformContinuous_ofAdd : UniformContinuous (ofAdd : α → Multiplicative α) :=
uniformContinuous_id
theorem uniformContinuous_toAdd : UniformContinuous (toAdd : Multiplicative α → α) :=
uniformContinuous_id
theorem uniformity_additive : 𝓤 (Additive α) = (𝓤 α).map (Prod.map ofMul ofMul) := rfl
theorem uniformity_multiplicative : 𝓤 (Multiplicative α) = (𝓤 α).map (Prod.map ofAdd ofAdd) := rfl
end
instance instUniformSpaceSubtype {p : α → Prop} [t : UniformSpace α] : UniformSpace (Subtype p) :=
UniformSpace.comap Subtype.val t
theorem uniformity_subtype {p : α → Prop} [UniformSpace α] :
𝓤 (Subtype p) = comap (fun q : Subtype p × Subtype p => (q.1.1, q.2.1)) (𝓤 α) :=
rfl
theorem uniformity_setCoe {s : Set α} [UniformSpace α] :
𝓤 s = comap (Prod.map ((↑) : s → α) ((↑) : s → α)) (𝓤 α) :=
rfl
theorem map_uniformity_set_coe {s : Set α} [UniformSpace α] :
map (Prod.map (↑) (↑)) (𝓤 s) = 𝓤 α ⊓ 𝓟 (s ×ˢ s) := by
rw [uniformity_setCoe, map_comap, range_prodMap, Subtype.range_val]
theorem uniformContinuous_subtype_val {p : α → Prop} [UniformSpace α] :
UniformContinuous (Subtype.val : { a : α // p a } → α) :=
uniformContinuous_comap
theorem UniformContinuous.subtype_mk {p : α → Prop} [UniformSpace α] [UniformSpace β] {f : β → α}
(hf : UniformContinuous f) (h : ∀ x, p (f x)) :
UniformContinuous (fun x => ⟨f x, h x⟩ : β → Subtype p) :=
uniformContinuous_comap' hf
theorem uniformContinuousOn_iff_restrict [UniformSpace α] [UniformSpace β] {f : α → β} {s : Set α} :
UniformContinuousOn f s ↔ UniformContinuous (s.restrict f) := by
delta UniformContinuousOn UniformContinuous
rw [← map_uniformity_set_coe, tendsto_map'_iff]; rfl
theorem tendsto_of_uniformContinuous_subtype [UniformSpace α] [UniformSpace β] {f : α → β}
{s : Set α} {a : α} (hf : UniformContinuous fun x : s => f x.val) (ha : s ∈ 𝓝 a) :
Tendsto f (𝓝 a) (𝓝 (f a)) := by
rw [(@map_nhds_subtype_coe_eq_nhds α _ s a (mem_of_mem_nhds ha) ha).symm]
exact tendsto_map' hf.continuous.continuousAt
theorem UniformContinuousOn.continuousOn [UniformSpace α] [UniformSpace β] {f : α → β} {s : Set α}
(h : UniformContinuousOn f s) : ContinuousOn f s := by
rw [uniformContinuousOn_iff_restrict] at h
rw [continuousOn_iff_continuous_restrict]
exact h.continuous
@[to_additive]
instance [UniformSpace α] : UniformSpace αᵐᵒᵖ :=
UniformSpace.comap MulOpposite.unop ‹_›
@[to_additive]
theorem uniformity_mulOpposite [UniformSpace α] :
𝓤 αᵐᵒᵖ = comap (fun q : αᵐᵒᵖ × αᵐᵒᵖ => (q.1.unop, q.2.unop)) (𝓤 α) :=
rfl
@[to_additive (attr := simp)]
theorem comap_uniformity_mulOpposite [UniformSpace α] :
comap (fun p : α × α => (MulOpposite.op p.1, MulOpposite.op p.2)) (𝓤 αᵐᵒᵖ) = 𝓤 α := by
simpa [uniformity_mulOpposite, comap_comap, (· ∘ ·)] using comap_id
namespace MulOpposite
@[to_additive]
theorem uniformContinuous_unop [UniformSpace α] : UniformContinuous (unop : αᵐᵒᵖ → α) :=
uniformContinuous_comap
@[to_additive]
theorem uniformContinuous_op [UniformSpace α] : UniformContinuous (op : α → αᵐᵒᵖ) :=
uniformContinuous_comap' uniformContinuous_id
end MulOpposite
section Prod
open UniformSpace
/- a similar product space is possible on the function space (uniformity of pointwise convergence),
but we want to have the uniformity of uniform convergence on function spaces -/
instance instUniformSpaceProd [u₁ : UniformSpace α] [u₂ : UniformSpace β] : UniformSpace (α × β) :=
u₁.comap Prod.fst ⊓ u₂.comap Prod.snd
-- check the above produces no diamond for `simp` and typeclass search
example [UniformSpace α] [UniformSpace β] :
(instTopologicalSpaceProd : TopologicalSpace (α × β)) = UniformSpace.toTopologicalSpace := by
with_reducible_and_instances rfl
theorem uniformity_prod [UniformSpace α] [UniformSpace β] :
𝓤 (α × β) =
((𝓤 α).comap fun p : (α × β) × α × β => (p.1.1, p.2.1)) ⊓
(𝓤 β).comap fun p : (α × β) × α × β => (p.1.2, p.2.2) :=
rfl
instance [UniformSpace α] [IsCountablyGenerated (𝓤 α)]
[UniformSpace β] [IsCountablyGenerated (𝓤 β)] : IsCountablyGenerated (𝓤 (α × β)) := by
rw [uniformity_prod]
infer_instance
theorem uniformity_prod_eq_comap_prod [UniformSpace α] [UniformSpace β] :
𝓤 (α × β) =
comap (fun p : (α × β) × α × β => ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ˢ 𝓤 β) := by
simp_rw [uniformity_prod, prod_eq_inf, Filter.comap_inf, Filter.comap_comap, Function.comp_def]
theorem uniformity_prod_eq_prod [UniformSpace α] [UniformSpace β] :
𝓤 (α × β) = map (fun p : (α × α) × β × β => ((p.1.1, p.2.1), (p.1.2, p.2.2))) (𝓤 α ×ˢ 𝓤 β) := by
rw [map_swap4_eq_comap, uniformity_prod_eq_comap_prod]
theorem mem_uniformity_of_uniformContinuous_invariant [UniformSpace α] [UniformSpace β]
{s : Set (β × β)} {f : α → α → β} (hf : UniformContinuous fun p : α × α => f p.1 p.2)
(hs : s ∈ 𝓤 β) : ∃ u ∈ 𝓤 α, ∀ a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := by
rw [UniformContinuous, uniformity_prod_eq_prod, tendsto_map'_iff] at hf
rcases mem_prod_iff.1 (mem_map.1 <| hf hs) with ⟨u, hu, v, hv, huvt⟩
exact ⟨u, hu, fun a b c hab => @huvt ((_, _), (_, _)) ⟨hab, refl_mem_uniformity hv⟩⟩
/-- An entourage of the diagonal in `α` and an entourage in `β` yield an entourage in `α × β`
once we permute coordinates. -/
def entourageProd (u : Set (α × α)) (v : Set (β × β)) : Set ((α × β) × α × β) :=
{((a₁, b₁),(a₂, b₂)) | (a₁, a₂) ∈ u ∧ (b₁, b₂) ∈ v}
theorem mem_entourageProd {u : Set (α × α)} {v : Set (β × β)} {p : (α × β) × α × β} :
p ∈ entourageProd u v ↔ (p.1.1, p.2.1) ∈ u ∧ (p.1.2, p.2.2) ∈ v := Iff.rfl
theorem entourageProd_mem_uniformity [t₁ : UniformSpace α] [t₂ : UniformSpace β] {u : Set (α × α)}
{v : Set (β × β)} (hu : u ∈ 𝓤 α) (hv : v ∈ 𝓤 β) :
entourageProd u v ∈ 𝓤 (α × β) := by
rw [uniformity_prod]; exact inter_mem_inf (preimage_mem_comap hu) (preimage_mem_comap hv)
theorem ball_entourageProd (u : Set (α × α)) (v : Set (β × β)) (x : α × β) :
ball x (entourageProd u v) = ball x.1 u ×ˢ ball x.2 v := by
ext p; simp only [ball, entourageProd, Set.mem_setOf_eq, Set.mem_prod, Set.mem_preimage]
lemma IsSymmetricRel.entourageProd {u : Set (α × α)} {v : Set (β × β)}
(hu : IsSymmetricRel u) (hv : IsSymmetricRel v) :
IsSymmetricRel (entourageProd u v) :=
Set.ext fun _ ↦ and_congr hu.mk_mem_comm hv.mk_mem_comm
theorem Filter.HasBasis.uniformity_prod {ιa ιb : Type*} [UniformSpace α] [UniformSpace β]
{pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → Set (α × α)} {sb : ιb → Set (β × β)}
(ha : (𝓤 α).HasBasis pa sa) (hb : (𝓤 β).HasBasis pb sb) :
(𝓤 (α × β)).HasBasis (fun i : ιa × ιb ↦ pa i.1 ∧ pb i.2)
(fun i ↦ entourageProd (sa i.1) (sb i.2)) :=
(ha.comap _).inf (hb.comap _)
theorem entourageProd_subset [UniformSpace α] [UniformSpace β]
{s : Set ((α × β) × α × β)} (h : s ∈ 𝓤 (α × β)) :
∃ u ∈ 𝓤 α, ∃ v ∈ 𝓤 β, entourageProd u v ⊆ s := by
rcases (((𝓤 α).basis_sets.uniformity_prod (𝓤 β).basis_sets).mem_iff' s).1 h with ⟨w, hw⟩
use w.1, hw.1.1, w.2, hw.1.2, hw.2
theorem tendsto_prod_uniformity_fst [UniformSpace α] [UniformSpace β] :
Tendsto (fun p : (α × β) × α × β => (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) :=
le_trans (map_mono inf_le_left) map_comap_le
theorem tendsto_prod_uniformity_snd [UniformSpace α] [UniformSpace β] :
Tendsto (fun p : (α × β) × α × β => (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) :=
le_trans (map_mono inf_le_right) map_comap_le
theorem uniformContinuous_fst [UniformSpace α] [UniformSpace β] :
UniformContinuous fun p : α × β => p.1 :=
tendsto_prod_uniformity_fst
theorem uniformContinuous_snd [UniformSpace α] [UniformSpace β] :
UniformContinuous fun p : α × β => p.2 :=
tendsto_prod_uniformity_snd
variable [UniformSpace α] [UniformSpace β] [UniformSpace γ]
theorem UniformContinuous.prodMk {f₁ : α → β} {f₂ : α → γ} (h₁ : UniformContinuous f₁)
(h₂ : UniformContinuous f₂) : UniformContinuous fun a => (f₁ a, f₂ a) := by
rw [UniformContinuous, uniformity_prod]
exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩
@[deprecated (since := "2025-03-10")]
alias UniformContinuous.prod_mk := UniformContinuous.prodMk
theorem UniformContinuous.prodMk_left {f : α × β → γ} (h : UniformContinuous f) (b) :
UniformContinuous fun a => f (a, b) :=
h.comp (uniformContinuous_id.prodMk uniformContinuous_const)
@[deprecated (since := "2025-03-10")]
alias UniformContinuous.prod_mk_left := UniformContinuous.prodMk_left
theorem UniformContinuous.prodMk_right {f : α × β → γ} (h : UniformContinuous f) (a) :
UniformContinuous fun b => f (a, b) :=
h.comp (uniformContinuous_const.prodMk uniformContinuous_id)
@[deprecated (since := "2025-03-10")]
alias UniformContinuous.prod_mk_right := UniformContinuous.prodMk_right
theorem UniformContinuous.prodMap [UniformSpace δ] {f : α → γ} {g : β → δ}
(hf : UniformContinuous f) (hg : UniformContinuous g) : UniformContinuous (Prod.map f g) :=
(hf.comp uniformContinuous_fst).prodMk (hg.comp uniformContinuous_snd)
theorem toTopologicalSpace_prod {α} {β} [u : UniformSpace α] [v : UniformSpace β] :
@UniformSpace.toTopologicalSpace (α × β) instUniformSpaceProd =
@instTopologicalSpaceProd α β u.toTopologicalSpace v.toTopologicalSpace :=
rfl
/-- A version of `UniformContinuous.inf_dom_left` for binary functions -/
theorem uniformContinuous_inf_dom_left₂ {α β γ} {f : α → β → γ} {ua1 ua2 : UniformSpace α}
{ub1 ub2 : UniformSpace β} {uc1 : UniformSpace γ}
(h : by haveI := ua1; haveI := ub1; exact UniformContinuous fun p : α × β => f p.1 p.2) : by
haveI := ua1 ⊓ ua2; haveI := ub1 ⊓ ub2
exact UniformContinuous fun p : α × β => f p.1 p.2 := by
-- proof essentially copied from `continuous_inf_dom_left₂`
have ha := @UniformContinuous.inf_dom_left _ _ id ua1 ua2 ua1 (@uniformContinuous_id _ (id _))
have hb := @UniformContinuous.inf_dom_left _ _ id ub1 ub2 ub1 (@uniformContinuous_id _ (id _))
have h_unif_cont_id :=
@UniformContinuous.prodMap _ _ _ _ (ua1 ⊓ ua2) (ub1 ⊓ ub2) ua1 ub1 _ _ ha hb
exact @UniformContinuous.comp _ _ _ (id _) (id _) _ _ _ h h_unif_cont_id
/-- A version of `UniformContinuous.inf_dom_right` for binary functions -/
theorem uniformContinuous_inf_dom_right₂ {α β γ} {f : α → β → γ} {ua1 ua2 : UniformSpace α}
{ub1 ub2 : UniformSpace β} {uc1 : UniformSpace γ}
(h : by haveI := ua2; haveI := ub2; exact UniformContinuous fun p : α × β => f p.1 p.2) : by
haveI := ua1 ⊓ ua2; haveI := ub1 ⊓ ub2
exact UniformContinuous fun p : α × β => f p.1 p.2 := by
-- proof essentially copied from `continuous_inf_dom_right₂`
have ha := @UniformContinuous.inf_dom_right _ _ id ua1 ua2 ua2 (@uniformContinuous_id _ (id _))
have hb := @UniformContinuous.inf_dom_right _ _ id ub1 ub2 ub2 (@uniformContinuous_id _ (id _))
have h_unif_cont_id :=
@UniformContinuous.prodMap _ _ _ _ (ua1 ⊓ ua2) (ub1 ⊓ ub2) ua2 ub2 _ _ ha hb
exact @UniformContinuous.comp _ _ _ (id _) (id _) _ _ _ h h_unif_cont_id
/-- A version of `uniformContinuous_sInf_dom` for binary functions -/
theorem uniformContinuous_sInf_dom₂ {α β γ} {f : α → β → γ} {uas : Set (UniformSpace α)}
{ubs : Set (UniformSpace β)} {ua : UniformSpace α} {ub : UniformSpace β} {uc : UniformSpace γ}
(ha : ua ∈ uas) (hb : ub ∈ ubs) (hf : UniformContinuous fun p : α × β => f p.1 p.2) : by
haveI := sInf uas; haveI := sInf ubs
exact @UniformContinuous _ _ _ uc fun p : α × β => f p.1 p.2 := by
-- proof essentially copied from `continuous_sInf_dom`
let _ : UniformSpace (α × β) := instUniformSpaceProd
have ha := uniformContinuous_sInf_dom ha uniformContinuous_id
have hb := uniformContinuous_sInf_dom hb uniformContinuous_id
have h_unif_cont_id := @UniformContinuous.prodMap _ _ _ _ (sInf uas) (sInf ubs) ua ub _ _ ha hb
exact @UniformContinuous.comp _ _ _ (id _) (id _) _ _ _ hf h_unif_cont_id
end Prod
section
open UniformSpace Function
variable {δ' : Type*} [UniformSpace α] [UniformSpace β] [UniformSpace γ] [UniformSpace δ]
[UniformSpace δ']
local notation f " ∘₂ " g => Function.bicompr f g
/-- Uniform continuity for functions of two variables. -/
def UniformContinuous₂ (f : α → β → γ) :=
UniformContinuous (uncurry f)
theorem uniformContinuous₂_def (f : α → β → γ) :
UniformContinuous₂ f ↔ UniformContinuous (uncurry f) :=
Iff.rfl
theorem UniformContinuous₂.uniformContinuous {f : α → β → γ} (h : UniformContinuous₂ f) :
UniformContinuous (uncurry f) :=
h
theorem uniformContinuous₂_curry (f : α × β → γ) :
UniformContinuous₂ (Function.curry f) ↔ UniformContinuous f := by
rw [UniformContinuous₂, uncurry_curry]
theorem UniformContinuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : UniformContinuous g)
(hf : UniformContinuous₂ f) : UniformContinuous₂ (g ∘₂ f) :=
hg.comp hf
theorem UniformContinuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β}
(hf : UniformContinuous₂ f) (hga : UniformContinuous ga) (hgb : UniformContinuous gb) :
UniformContinuous₂ (bicompl f ga gb) :=
hf.uniformContinuous.comp (hga.prodMap hgb)
end
theorem toTopologicalSpace_subtype [u : UniformSpace α] {p : α → Prop} :
@UniformSpace.toTopologicalSpace (Subtype p) instUniformSpaceSubtype =
@instTopologicalSpaceSubtype α p u.toTopologicalSpace :=
rfl
section Sum
variable [UniformSpace α] [UniformSpace β]
open Sum
-- Obsolete auxiliary definitions and lemmas
/-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained
by taking independently an entourage of the diagonal in the first part, and an entourage of
the diagonal in the second part. -/
instance Sum.instUniformSpace : UniformSpace (α ⊕ β) where
uniformity := map (fun p : α × α => (inl p.1, inl p.2)) (𝓤 α) ⊔
map (fun p : β × β => (inr p.1, inr p.2)) (𝓤 β)
symm := fun _ hs ↦ ⟨symm_le_uniformity hs.1, symm_le_uniformity hs.2⟩
comp := fun s hs ↦ by
rcases comp_mem_uniformity_sets hs.1 with ⟨tα, htα, Htα⟩
rcases comp_mem_uniformity_sets hs.2 with ⟨tβ, htβ, Htβ⟩
filter_upwards [mem_lift' (union_mem_sup (image_mem_map htα) (image_mem_map htβ))]
rintro ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩
exacts [@Htα (_, _) ⟨b, hab, hbc⟩, @Htβ (_, _) ⟨b, hab, hbc⟩]
nhds_eq_comap_uniformity x := by
ext
cases x <;> simp [mem_comap', -mem_comap, nhds_inl, nhds_inr, nhds_eq_comap_uniformity,
Prod.ext_iff]
/-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage
of the diagonal. -/
theorem union_mem_uniformity_sum {a : Set (α × α)} (ha : a ∈ 𝓤 α) {b : Set (β × β)} (hb : b ∈ 𝓤 β) :
Prod.map inl inl '' a ∪ Prod.map inr inr '' b ∈ 𝓤 (α ⊕ β) :=
union_mem_sup (image_mem_map ha) (image_mem_map hb)
theorem Sum.uniformity : 𝓤 (α ⊕ β) = map (Prod.map inl inl) (𝓤 α) ⊔ map (Prod.map inr inr) (𝓤 β) :=
rfl
lemma uniformContinuous_inl : UniformContinuous (Sum.inl : α → α ⊕ β) := le_sup_left
lemma uniformContinuous_inr : UniformContinuous (Sum.inr : β → α ⊕ β) := le_sup_right
instance [IsCountablyGenerated (𝓤 α)] [IsCountablyGenerated (𝓤 β)] :
IsCountablyGenerated (𝓤 (α ⊕ β)) := by
rw [Sum.uniformity]
infer_instance
end Sum
end Constructions
/-!
### Expressing continuity properties in uniform spaces
We reformulate the various continuity properties of functions taking values in a uniform space
in terms of the uniformity in the target. Since the same lemmas (essentially with the same names)
also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or
the edistance in the target), we put them in a namespace `Uniform` here.
In the metric and emetric space setting, there are also similar lemmas where one assumes that
both the source and the target are metric spaces, reformulating things in terms of the distance
on both sides. These lemmas are generally written without primes, and the versions where only
the target is a metric space is primed. We follow the same convention here, thus giving lemmas
with primes.
-/
namespace Uniform
variable [UniformSpace α]
theorem tendsto_nhds_right {f : Filter β} {u : β → α} {a : α} :
Tendsto u f (𝓝 a) ↔ Tendsto (fun x => (a, u x)) f (𝓤 α) := by
rw [nhds_eq_comap_uniformity, tendsto_comap_iff]; rfl
theorem tendsto_nhds_left {f : Filter β} {u : β → α} {a : α} :
Tendsto u f (𝓝 a) ↔ Tendsto (fun x => (u x, a)) f (𝓤 α) := by
rw [nhds_eq_comap_uniformity', tendsto_comap_iff]; rfl
theorem continuousAt_iff'_right [TopologicalSpace β] {f : β → α} {b : β} :
ContinuousAt f b ↔ Tendsto (fun x => (f b, f x)) (𝓝 b) (𝓤 α) := by
rw [ContinuousAt, tendsto_nhds_right]
theorem continuousAt_iff'_left [TopologicalSpace β] {f : β → α} {b : β} :
ContinuousAt f b ↔ Tendsto (fun x => (f x, f b)) (𝓝 b) (𝓤 α) := by
rw [ContinuousAt, tendsto_nhds_left]
theorem continuousAt_iff_prod [TopologicalSpace β] {f : β → α} {b : β} :
ContinuousAt f b ↔ Tendsto (fun x : β × β => (f x.1, f x.2)) (𝓝 (b, b)) (𝓤 α) :=
⟨fun H => le_trans (H.prodMap' H) (nhds_le_uniformity _), fun H =>
continuousAt_iff'_left.2 <| H.comp <| tendsto_id.prodMk_nhds tendsto_const_nhds⟩
theorem continuousWithinAt_iff'_right [TopologicalSpace β] {f : β → α} {b : β} {s : Set β} :
ContinuousWithinAt f s b ↔ Tendsto (fun x => (f b, f x)) (𝓝[s] b) (𝓤 α) := by
rw [ContinuousWithinAt, tendsto_nhds_right]
theorem continuousWithinAt_iff'_left [TopologicalSpace β] {f : β → α} {b : β} {s : Set β} :
ContinuousWithinAt f s b ↔ Tendsto (fun x => (f x, f b)) (𝓝[s] b) (𝓤 α) := by
rw [ContinuousWithinAt, tendsto_nhds_left]
theorem continuousOn_iff'_right [TopologicalSpace β] {f : β → α} {s : Set β} :
ContinuousOn f s ↔ ∀ b ∈ s, Tendsto (fun x => (f b, f x)) (𝓝[s] b) (𝓤 α) := by
simp [ContinuousOn, continuousWithinAt_iff'_right]
theorem continuousOn_iff'_left [TopologicalSpace β] {f : β → α} {s : Set β} :
ContinuousOn f s ↔ ∀ b ∈ s, Tendsto (fun x => (f x, f b)) (𝓝[s] b) (𝓤 α) := by
simp [ContinuousOn, continuousWithinAt_iff'_left]
theorem continuous_iff'_right [TopologicalSpace β] {f : β → α} :
Continuous f ↔ ∀ b, Tendsto (fun x => (f b, f x)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuousAt.trans <| forall_congr' fun _ => tendsto_nhds_right
theorem continuous_iff'_left [TopologicalSpace β] {f : β → α} :
Continuous f ↔ ∀ b, Tendsto (fun x => (f x, f b)) (𝓝 b) (𝓤 α) :=
continuous_iff_continuousAt.trans <| forall_congr' fun _ => tendsto_nhds_left
/-- Consider two functions `f` and `g` which coincide on a set `s` and are continuous there.
Then there is an open neighborhood of `s` on which `f` and `g` are uniformly close. -/
lemma exists_is_open_mem_uniformity_of_forall_mem_eq
[TopologicalSpace β] {r : Set (α × α)} {s : Set β}
{f g : β → α} (hf : ∀ x ∈ s, ContinuousAt f x) (hg : ∀ x ∈ s, ContinuousAt g x)
(hfg : s.EqOn f g) (hr : r ∈ 𝓤 α) :
∃ t, IsOpen t ∧ s ⊆ t ∧ ∀ x ∈ t, (f x, g x) ∈ r := by
have A : ∀ x ∈ s, ∃ t, IsOpen t ∧ x ∈ t ∧ ∀ z ∈ t, (f z, g z) ∈ r := by
intro x hx
obtain ⟨t, ht, htsymm, htr⟩ := comp_symm_mem_uniformity_sets hr
have A : {z | (f x, f z) ∈ t} ∈ 𝓝 x := (hf x hx).preimage_mem_nhds (mem_nhds_left (f x) ht)
have B : {z | (g x, g z) ∈ t} ∈ 𝓝 x := (hg x hx).preimage_mem_nhds (mem_nhds_left (g x) ht)
rcases _root_.mem_nhds_iff.1 (inter_mem A B) with ⟨u, hu, u_open, xu⟩
refine ⟨u, u_open, xu, fun y hy ↦ ?_⟩
have I1 : (f y, f x) ∈ t := (htsymm.mk_mem_comm).2 (hu hy).1
have I2 : (g x, g y) ∈ t := (hu hy).2
rw [hfg hx] at I1
exact htr (prodMk_mem_compRel I1 I2)
choose! t t_open xt ht using A
refine ⟨⋃ x ∈ s, t x, isOpen_biUnion t_open, fun x hx ↦ mem_biUnion hx (xt x hx), ?_⟩
rintro x hx
simp only [mem_iUnion, exists_prop] at hx
rcases hx with ⟨y, ys, hy⟩
exact ht y ys x hy
end Uniform
theorem Filter.Tendsto.congr_uniformity {α β} [UniformSpace β] {f g : α → β} {l : Filter α} {b : β}
(hf : Tendsto f l (𝓝 b)) (hg : Tendsto (fun x => (f x, g x)) l (𝓤 β)) : Tendsto g l (𝓝 b) :=
Uniform.tendsto_nhds_right.2 <| (Uniform.tendsto_nhds_right.1 hf).uniformity_trans hg
theorem Uniform.tendsto_congr {α β} [UniformSpace β] {f g : α → β} {l : Filter α} {b : β}
(hfg : Tendsto (fun x => (f x, g x)) l (𝓤 β)) : Tendsto f l (𝓝 b) ↔ Tendsto g l (𝓝 b) :=
⟨fun h => h.congr_uniformity hfg, fun h => h.congr_uniformity hfg.uniformity_symm⟩
| Mathlib/Topology/UniformSpace/Basic.lean | 1,588 | 1,590 | |
/-
Copyright (c) 2023 Jz Pan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jz Pan
-/
import Mathlib.FieldTheory.SplittingField.Construction
import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure
import Mathlib.FieldTheory.Separable
import Mathlib.FieldTheory.Normal.Closure
import Mathlib.RingTheory.AlgebraicIndependent.Adjoin
import Mathlib.RingTheory.AlgebraicIndependent.TranscendenceBasis
import Mathlib.RingTheory.Polynomial.SeparableDegree
import Mathlib.RingTheory.Polynomial.UniqueFactorization
/-!
# Separable degree
This file contains basics about the separable degree of a field extension.
## Main definitions
- `Field.Emb F E`: the type of `F`-algebra homomorphisms from `E` to the algebraic closure of `E`
(the algebraic closure of `F` is usually used in the literature, but our definition has the
advantage that `Field.Emb F E` lies in the same universe as `E` rather than the maximum over `F`
and `E`). Usually denoted by $\operatorname{Emb}_F(E)$ in textbooks.
- `Field.finSepDegree F E`: the (finite) separable degree $[E:F]_s$ of an extension `E / F`
of fields, defined to be the number of `F`-algebra homomorphisms from `E` to the algebraic
closure of `E`, as a natural number. It is zero if `Field.Emb F E` is not finite.
Note that if `E / F` is not algebraic, then this definition makes no mathematical sense.
**Remark:** the `Cardinal`-valued, potentially infinite separable degree `Field.sepDegree F E`
for a general algebraic extension `E / F` is defined to be the degree of `L / F`, where `L` is
the separable closure of `F` in `E`, which is not defined in this file yet. Later we
will show that (`Field.finSepDegree_eq`), if `Field.Emb F E` is finite, then these two
definitions coincide. If `E / F` is algebraic with infinite separable degree, we have
`#(Field.Emb F E) = 2 ^ Field.sepDegree F E` instead.
(See `Field.Emb.cardinal_eq_two_pow_sepDegree` in another file.) For example, if
$F = \mathbb{Q}$ and $E = \mathbb{Q}( \mu_{p^\infty} )$, then $\operatorname{Emb}_F (E)$
is in bijection with $\operatorname{Gal}(E/F)$, which is isomorphic to
$\mathbb{Z}_p^\times$, which is uncountable, whereas $ [E:F] $ is countable.
- `Polynomial.natSepDegree`: the separable degree of a polynomial is a natural number,
defined to be the number of distinct roots of it over its splitting field.
## Main results
- `Field.embEquivOfEquiv`, `Field.finSepDegree_eq_of_equiv`:
a random bijection between `Field.Emb F E` and `Field.Emb F K` when `E` and `K` are isomorphic
as `F`-algebras. In particular, they have the same cardinality (so their
`Field.finSepDegree` are equal).
- `Field.embEquivOfAdjoinSplits`,
`Field.finSepDegree_eq_of_adjoin_splits`: a random bijection between `Field.Emb F E` and
`E →ₐ[F] K` if `E = F(S)` such that every element `s` of `S` is integral (= algebraic) over `F`
and whose minimal polynomial splits in `K`. In particular, they have the same cardinality.
- `Field.embEquivOfIsAlgClosed`,
`Field.finSepDegree_eq_of_isAlgClosed`: a random bijection between `Field.Emb F E` and
`E →ₐ[F] K` when `E / F` is algebraic and `K / F` is algebraically closed.
In particular, they have the same cardinality.
- `Field.embProdEmbOfIsAlgebraic`, `Field.finSepDegree_mul_finSepDegree_of_isAlgebraic`:
if `K / E / F` is a field extension tower, such that `K / E` is algebraic,
then there is a non-canonical bijection `Field.Emb F E × Field.Emb E K ≃ Field.Emb F K`.
In particular, the separable degrees satisfy the tower law: $[E:F]_s [K:E]_s = [K:F]_s$
(see also `Module.finrank_mul_finrank`).
- `Field.infinite_emb_of_transcendental`: `Field.Emb` is infinite for transcendental extensions.
- `Polynomial.natSepDegree_le_natDegree`: the separable degree of a polynomial is smaller than
its degree.
- `Polynomial.natSepDegree_eq_natDegree_iff`: the separable degree of a non-zero polynomial is
equal to its degree if and only if it is separable.
- `Polynomial.natSepDegree_eq_of_splits`: if a polynomial splits over `E`, then its separable degree
is equal to the number of distinct roots of it over `E`.
- `Polynomial.natSepDegree_eq_of_isAlgClosed`: the separable degree of a polynomial is equal to
the number of distinct roots of it over any algebraically closed field.
- `Polynomial.natSepDegree_expand`: if a field `F` is of exponential characteristic
`q`, then `Polynomial.expand F (q ^ n) f` and `f` have the same separable degree.
- `Polynomial.HasSeparableContraction.natSepDegree_eq`: if a polynomial has separable
contraction, then its separable degree is equal to its separable contraction degree.
- `Irreducible.natSepDegree_dvd_natDegree`: the separable degree of an irreducible
polynomial divides its degree.
- `IntermediateField.finSepDegree_adjoin_simple_eq_natSepDegree`: the separable degree of
`F⟮α⟯ / F` is equal to the separable degree of the minimal polynomial of `α` over `F`.
- `IntermediateField.finSepDegree_adjoin_simple_eq_finrank_iff`: if `α` is algebraic over `F`, then
the separable degree of `F⟮α⟯ / F` is equal to the degree of `F⟮α⟯ / F` if and only if `α` is a
separable element.
- `Field.finSepDegree_dvd_finrank`: the separable degree of any field extension `E / F` divides
the degree of `E / F`.
- `Field.finSepDegree_le_finrank`: the separable degree of a finite extension `E / F` is smaller
than the degree of `E / F`.
- `Field.finSepDegree_eq_finrank_iff`: if `E / F` is a finite extension, then its separable degree
is equal to its degree if and only if it is a separable extension.
- `IntermediateField.isSeparable_adjoin_simple_iff_isSeparable`: `F⟮x⟯ / F` is a separable extension
if and only if `x` is a separable element.
- `Algebra.IsSeparable.trans`: if `E / F` and `K / E` are both separable, then `K / F` is also
separable.
## Tags
separable degree, degree, polynomial
-/
open Module Polynomial IntermediateField Field
noncomputable section
universe u v w
variable (F : Type u) (E : Type v) [Field F] [Field E] [Algebra F E]
variable (K : Type w) [Field K] [Algebra F K]
namespace Field
/-- `Field.Emb F E` is the type of `F`-algebra homomorphisms from `E` to the algebraic closure
of `E`. -/
abbrev Emb := E →ₐ[F] AlgebraicClosure E
/-- If `E / F` is an algebraic extension, then the (finite) separable degree of `E / F`
is the number of `F`-algebra homomorphisms from `E` to the algebraic closure of `E`,
as a natural number. It is defined to be zero if there are infinitely many of them.
Note that if `E / F` is not algebraic, then this definition makes no mathematical sense. -/
def finSepDegree : ℕ := Nat.card (Emb F E)
instance instInhabitedEmb : Inhabited (Emb F E) := ⟨IsScalarTower.toAlgHom F E _⟩
instance instNeZeroFinSepDegree [FiniteDimensional F E] : NeZero (finSepDegree F E) :=
⟨Nat.card_ne_zero.2 ⟨inferInstance, Fintype.finite <| minpoly.AlgHom.fintype _ _ _⟩⟩
/-- A random bijection between `Field.Emb F E` and `Field.Emb F K` when `E` and `K` are isomorphic
as `F`-algebras. -/
def embEquivOfEquiv (i : E ≃ₐ[F] K) :
Emb F E ≃ Emb F K := AlgEquiv.arrowCongr i <| AlgEquiv.symm <| by
let _ : Algebra E K := i.toAlgHom.toRingHom.toAlgebra
have : Algebra.IsAlgebraic E K := by
constructor
intro x
have h := isAlgebraic_algebraMap (R := E) (A := K) (i.symm.toAlgHom x)
rw [show ∀ y : E, (algebraMap E K) y = i.toAlgHom y from fun y ↦ rfl] at h
simpa only [AlgEquiv.toAlgHom_eq_coe, AlgHom.coe_coe, AlgEquiv.apply_symm_apply] using h
apply AlgEquiv.restrictScalars (R := F) (S := E)
exact IsAlgClosure.equivOfAlgebraic E K (AlgebraicClosure K) (AlgebraicClosure E)
/-- If `E` and `K` are isomorphic as `F`-algebras, then they have the same `Field.finSepDegree`
over `F`. -/
theorem finSepDegree_eq_of_equiv (i : E ≃ₐ[F] K) :
finSepDegree F E = finSepDegree F K := Nat.card_congr (embEquivOfEquiv F E K i)
@[simp]
theorem finSepDegree_self : finSepDegree F F = 1 := by
have : Cardinal.mk (Emb F F) = 1 := le_antisymm
(Cardinal.le_one_iff_subsingleton.2 AlgHom.subsingleton)
(Cardinal.one_le_iff_ne_zero.2 <| Cardinal.mk_ne_zero _)
rw [finSepDegree, Nat.card, this, Cardinal.one_toNat]
end Field
namespace IntermediateField
@[simp]
theorem finSepDegree_bot : finSepDegree F (⊥ : IntermediateField F E) = 1 := by
rw [finSepDegree_eq_of_equiv _ _ _ (botEquiv F E), finSepDegree_self]
section Tower
variable {F}
variable [Algebra E K] [IsScalarTower F E K]
@[simp]
theorem finSepDegree_bot' : finSepDegree F (⊥ : IntermediateField E K) = finSepDegree F E :=
finSepDegree_eq_of_equiv _ _ _ ((botEquiv E K).restrictScalars F)
@[simp]
theorem finSepDegree_top : finSepDegree F (⊤ : IntermediateField E K) = finSepDegree F K :=
finSepDegree_eq_of_equiv _ _ _ ((topEquiv (F := E) (E := K)).restrictScalars F)
end Tower
end IntermediateField
namespace Field
/-- A random bijection between `Field.Emb F E` and `E →ₐ[F] K` if `E = F(S)` such that every
element `s` of `S` is integral (= algebraic) over `F` and whose minimal polynomial splits in `K`.
Combined with `Field.instInhabitedEmb`, it can be viewed as a stronger version of
`IntermediateField.nonempty_algHom_of_adjoin_splits`. -/
def embEquivOfAdjoinSplits {S : Set E} (hS : adjoin F S = ⊤)
(hK : ∀ s ∈ S, IsIntegral F s ∧ Splits (algebraMap F K) (minpoly F s)) :
Emb F E ≃ (E →ₐ[F] K) :=
have : Algebra.IsAlgebraic F (⊤ : IntermediateField F E) :=
(hS ▸ isAlgebraic_adjoin (S := S) fun x hx ↦ (hK x hx).1)
have halg := (topEquiv (F := F) (E := E)).isAlgebraic
Classical.choice <| Function.Embedding.antisymm
(halg.algHomEmbeddingOfSplits (fun _ ↦ splits_of_mem_adjoin F E (S := S) hK (hS ▸ mem_top)) _)
(halg.algHomEmbeddingOfSplits (fun _ ↦ IsAlgClosed.splits_codomain _) _)
/-- The `Field.finSepDegree F E` is equal to the cardinality of `E →ₐ[F] K`
if `E = F(S)` such that every element
`s` of `S` is integral (= algebraic) over `F` and whose minimal polynomial splits in `K`. -/
theorem finSepDegree_eq_of_adjoin_splits {S : Set E} (hS : adjoin F S = ⊤)
(hK : ∀ s ∈ S, IsIntegral F s ∧ Splits (algebraMap F K) (minpoly F s)) :
finSepDegree F E = Nat.card (E →ₐ[F] K) := Nat.card_congr (embEquivOfAdjoinSplits F E K hS hK)
/-- A random bijection between `Field.Emb F E` and `E →ₐ[F] K` when `E / F` is algebraic
and `K / F` is algebraically closed. -/
def embEquivOfIsAlgClosed [Algebra.IsAlgebraic F E] [IsAlgClosed K] :
Emb F E ≃ (E →ₐ[F] K) :=
embEquivOfAdjoinSplits F E K (adjoin_univ F E) fun s _ ↦
⟨Algebra.IsIntegral.isIntegral s, IsAlgClosed.splits_codomain _⟩
/-- The `Field.finSepDegree F E` is equal to the cardinality of `E →ₐ[F] K` as a natural number,
when `E / F` is algebraic and `K / F` is algebraically closed. -/
@[stacks 09HJ "We use `finSepDegree` to state a more general result."]
theorem finSepDegree_eq_of_isAlgClosed [Algebra.IsAlgebraic F E] [IsAlgClosed K] :
finSepDegree F E = Nat.card (E →ₐ[F] K) := Nat.card_congr (embEquivOfIsAlgClosed F E K)
/-- If `K / E / F` is a field extension tower, such that `K / E` is algebraic,
then there is a non-canonical bijection
`Field.Emb F E × Field.Emb E K ≃ Field.Emb F K`. A corollary of `algHomEquivSigma`. -/
def embProdEmbOfIsAlgebraic [Algebra E K] [IsScalarTower F E K] [Algebra.IsAlgebraic E K] :
Emb F E × Emb E K ≃ Emb F K :=
let e : ∀ f : E →ₐ[F] AlgebraicClosure K,
@AlgHom E K _ _ _ _ _ f.toRingHom.toAlgebra ≃ Emb E K := fun f ↦
(@embEquivOfIsAlgClosed E K _ _ _ _ _ f.toRingHom.toAlgebra).symm
(algHomEquivSigma (A := F) (B := E) (C := K) (D := AlgebraicClosure K) |>.trans
(Equiv.sigmaEquivProdOfEquiv e) |>.trans <| Equiv.prodCongrLeft <|
fun _ : Emb E K ↦ AlgEquiv.arrowCongr (@AlgEquiv.refl F E _ _ _) <|
(IsAlgClosure.equivOfAlgebraic E K (AlgebraicClosure K)
(AlgebraicClosure E)).restrictScalars F).symm
/-- If the field extension `E / F` is transcendental, then `Field.Emb F E` is infinite. -/
instance infinite_emb_of_transcendental [H : Algebra.Transcendental F E] : Infinite (Emb F E) := by
obtain ⟨ι, x, hx⟩ := exists_isTranscendenceBasis' F E
have := hx.isAlgebraic_field
rw [← (embProdEmbOfIsAlgebraic F (adjoin F (Set.range x)) E).infinite_iff]
refine @Prod.infinite_of_left _ _ ?_ _
rw [← (embEquivOfEquiv _ _ _ hx.1.aevalEquivField).infinite_iff]
obtain ⟨i⟩ := hx.nonempty_iff_transcendental.2 H
let K := FractionRing (MvPolynomial ι F)
let i1 := IsScalarTower.toAlgHom F (MvPolynomial ι F) (AlgebraicClosure K)
have hi1 : Function.Injective i1 := by
rw [IsScalarTower.coe_toAlgHom', IsScalarTower.algebraMap_eq _ K]
exact (algebraMap K (AlgebraicClosure K)).injective.comp (IsFractionRing.injective _ _)
let f (n : ℕ) : Emb F K := IsFractionRing.liftAlgHom
(g := i1.comp <| MvPolynomial.aeval fun i : ι ↦ MvPolynomial.X i ^ (n + 1)) <| hi1.comp <| by
simpa [algebraicIndependent_iff_injective_aeval] using
MvPolynomial.algebraicIndependent_polynomial_aeval_X _
fun i : ι ↦ (Polynomial.transcendental_X F).pow n.succ_pos
refine Infinite.of_injective f fun m n h ↦ ?_
replace h : (MvPolynomial.X i) ^ (m + 1) = (MvPolynomial.X i) ^ (n + 1) := hi1 <| by
simpa [f, -map_pow] using congr($h (algebraMap _ K (MvPolynomial.X (R := F) i)))
simpa using congr(MvPolynomial.totalDegree $h)
|
/-- If the field extension `E / F` is transcendental, then `Field.finSepDegree F E = 0`, which
actually means that `Field.Emb F E` is infinite (see `Field.infinite_emb_of_transcendental`). -/
theorem finSepDegree_eq_zero_of_transcendental [Algebra.Transcendental F E] :
| Mathlib/FieldTheory/SeparableDegree.lean | 270 | 273 |
/-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import Mathlib.Algebra.Order.Ring.Abs
/-!
# Lemmas about units in `ℤ`, which interact with the order structure.
-/
namespace Int
theorem isUnit_iff_abs_eq {x : ℤ} : IsUnit x ↔ abs x = 1 := by
rw [isUnit_iff_natAbs_eq, abs_eq_natAbs, ← Int.ofNat_one, natCast_inj]
theorem isUnit_sq {a : ℤ} (ha : IsUnit a) : a ^ 2 = 1 := by rw [sq, isUnit_mul_self ha]
@[simp]
theorem units_sq (u : ℤˣ) : u ^ 2 = 1 := by
rw [Units.ext_iff, Units.val_pow_eq_pow_val, Units.val_one, isUnit_sq u.isUnit]
alias units_pow_two := units_sq
@[simp]
theorem units_mul_self (u : ℤˣ) : u * u = 1 := by rw [← sq, units_sq]
@[simp]
theorem units_inv_eq_self (u : ℤˣ) : u⁻¹ = u := by rw [inv_eq_iff_mul_eq_one, units_mul_self]
theorem units_div_eq_mul (u₁ u₂ : ℤˣ) : u₁ / u₂ = u₁ * u₂ := by
rw [div_eq_mul_inv, units_inv_eq_self]
-- `Units.val_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further
@[simp]
| theorem units_coe_mul_self (u : ℤˣ) : (u * u : ℤ) = 1 := by
| Mathlib/Data/Int/Order/Units.lean | 37 | 37 |
/-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import Mathlib.Data.List.Cycle
import Mathlib.GroupTheory.Perm.Cycle.Type
import Mathlib.GroupTheory.Perm.List
/-!
# Properties of cyclic permutations constructed from lists/cycles
In the following, `{α : Type*} [Fintype α] [DecidableEq α]`.
## Main definitions
* `Cycle.formPerm`: the cyclic permutation created by looping over a `Cycle α`
* `Equiv.Perm.toList`: the list formed by iterating application of a permutation
* `Equiv.Perm.toCycle`: the cycle formed by iterating application of a permutation
* `Equiv.Perm.isoCycle`: the equivalence between cyclic permutations `f : Perm α`
and the terms of `Cycle α` that correspond to them
* `Equiv.Perm.isoCycle'`: the same equivalence as `Equiv.Perm.isoCycle`
but with evaluation via choosing over fintypes
* The notation `c[1, 2, 3]` to emulate notation of cyclic permutations `(1 2 3)`
* A `Repr` instance for any `Perm α`, by representing the `Finset` of
`Cycle α` that correspond to the cycle factors.
## Main results
* `List.isCycle_formPerm`: a nontrivial list without duplicates, when interpreted as
a permutation, is cyclic
* `Equiv.Perm.IsCycle.existsUnique_cycle`: there is only one nontrivial `Cycle α`
corresponding to each cyclic `f : Perm α`
## Implementation details
The forward direction of `Equiv.Perm.isoCycle'` uses `Fintype.choose` of the uniqueness
result, relying on the `Fintype` instance of a `Cycle.Nodup` subtype.
It is unclear if this works faster than the `Equiv.Perm.toCycle`, which relies
on recursion over `Finset.univ`.
-/
open Equiv Equiv.Perm List
variable {α : Type*}
namespace List
variable [DecidableEq α] {l l' : List α}
theorem formPerm_disjoint_iff (hl : Nodup l) (hl' : Nodup l') (hn : 2 ≤ l.length)
(hn' : 2 ≤ l'.length) : Perm.Disjoint (formPerm l) (formPerm l') ↔ l.Disjoint l' := by
rw [disjoint_iff_eq_or_eq, List.Disjoint]
constructor
· rintro h x hx hx'
specialize h x
rw [formPerm_apply_mem_eq_self_iff _ hl _ hx, formPerm_apply_mem_eq_self_iff _ hl' _ hx'] at h
omega
· intro h x
by_cases hx : x ∈ l
on_goal 1 => by_cases hx' : x ∈ l'
· exact (h hx hx').elim
all_goals have := formPerm_eq_self_of_not_mem _ _ ‹_›; tauto
theorem isCycle_formPerm (hl : Nodup l) (hn : 2 ≤ l.length) : IsCycle (formPerm l) := by
rcases l with - | ⟨x, l⟩
· norm_num at hn
induction' l with y l generalizing x
· norm_num at hn
· use x
constructor
· rwa [formPerm_apply_mem_ne_self_iff _ hl _ mem_cons_self]
· intro w hw
have : w ∈ x::y::l := mem_of_formPerm_ne_self _ _ hw
obtain ⟨k, hk, rfl⟩ := getElem_of_mem this
use k
simp only [zpow_natCast, formPerm_pow_apply_head _ _ hl k, Nat.mod_eq_of_lt hk]
theorem pairwise_sameCycle_formPerm (hl : Nodup l) (hn : 2 ≤ l.length) :
Pairwise l.formPerm.SameCycle l :=
Pairwise.imp_mem.mpr
(pairwise_of_forall fun _ _ hx hy =>
(isCycle_formPerm hl hn).sameCycle ((formPerm_apply_mem_ne_self_iff _ hl _ hx).mpr hn)
((formPerm_apply_mem_ne_self_iff _ hl _ hy).mpr hn))
theorem cycleOf_formPerm (hl : Nodup l) (hn : 2 ≤ l.length) (x) :
cycleOf l.attach.formPerm x = l.attach.formPerm :=
have hn : 2 ≤ l.attach.length := by rwa [← length_attach] at hn
have hl : l.attach.Nodup := by rwa [← nodup_attach] at hl
(isCycle_formPerm hl hn).cycleOf_eq
((formPerm_apply_mem_ne_self_iff _ hl _ (mem_attach _ _)).mpr hn)
theorem cycleType_formPerm (hl : Nodup l) (hn : 2 ≤ l.length) :
cycleType l.attach.formPerm = {l.length} := by
rw [← length_attach] at hn
rw [← nodup_attach] at hl
rw [cycleType_eq [l.attach.formPerm]]
· simp only [map, Function.comp_apply]
rw [support_formPerm_of_nodup _ hl, card_toFinset, dedup_eq_self.mpr hl]
· simp
· intro x h
simp [h, Nat.succ_le_succ_iff] at hn
· simp
· simpa using isCycle_formPerm hl hn
· simp
theorem formPerm_apply_mem_eq_next (hl : Nodup l) (x : α) (hx : x ∈ l) :
formPerm l x = next l x hx := by
obtain ⟨k, hk, rfl⟩ := getElem_of_mem hx
rw [next_getElem _ hl, formPerm_apply_getElem _ hl]
end List
namespace Cycle
variable [DecidableEq α] (s : Cycle α)
/-- A cycle `s : Cycle α`, given `Nodup s` can be interpreted as an `Equiv.Perm α`
where each element in the list is permuted to the next one, defined as `formPerm`.
-/
def formPerm : ∀ s : Cycle α, Nodup s → Equiv.Perm α :=
fun s => Quotient.hrecOn s (fun l _ => List.formPerm l) fun l₁ l₂ (h : l₁ ~r l₂) => by
apply Function.hfunext
· ext
exact h.nodup_iff
· intro h₁ h₂ _
exact heq_of_eq (formPerm_eq_of_isRotated h₁ h)
@[simp]
theorem formPerm_coe (l : List α) (hl : l.Nodup) : formPerm (l : Cycle α) hl = l.formPerm :=
rfl
theorem formPerm_subsingleton (s : Cycle α) (h : Subsingleton s) : formPerm s h.nodup = 1 := by
induction' s using Quot.inductionOn with s
simp only [formPerm_coe, mk_eq_coe]
simp only [length_subsingleton_iff, length_coe, mk_eq_coe] at h
obtain - | ⟨hd, tl⟩ := s
· simp
· simp only [length_eq_zero_iff, add_le_iff_nonpos_left, List.length, nonpos_iff_eq_zero] at h
simp [h]
theorem isCycle_formPerm (s : Cycle α) (h : Nodup s) (hn : Nontrivial s) :
IsCycle (formPerm s h) := by
induction s using Quot.inductionOn
exact List.isCycle_formPerm h (length_nontrivial hn)
theorem support_formPerm [Fintype α] (s : Cycle α) (h : Nodup s) (hn : Nontrivial s) :
support (formPerm s h) = s.toFinset := by
induction' s using Quot.inductionOn with s
refine support_formPerm_of_nodup s h ?_
rintro _ rfl
simpa [Nat.succ_le_succ_iff] using length_nontrivial hn
theorem formPerm_eq_self_of_not_mem (s : Cycle α) (h : Nodup s) (x : α) (hx : x ∉ s) :
formPerm s h x = x := by
induction s using Quot.inductionOn
simpa using List.formPerm_eq_self_of_not_mem _ _ hx
theorem formPerm_apply_mem_eq_next (s : Cycle α) (h : Nodup s) (x : α) (hx : x ∈ s) :
formPerm s h x = next s h x hx := by
induction s using Quot.inductionOn
simpa using List.formPerm_apply_mem_eq_next h _ (by simp_all)
nonrec theorem formPerm_reverse (s : Cycle α) (h : Nodup s) :
formPerm s.reverse (nodup_reverse_iff.mpr h) = (formPerm s h)⁻¹ := by
induction s using Quot.inductionOn
simpa using formPerm_reverse _
nonrec theorem formPerm_eq_formPerm_iff {α : Type*} [DecidableEq α] {s s' : Cycle α} {hs : s.Nodup}
{hs' : s'.Nodup} :
s.formPerm hs = s'.formPerm hs' ↔ s = s' ∨ s.Subsingleton ∧ s'.Subsingleton := by
rw [Cycle.length_subsingleton_iff, Cycle.length_subsingleton_iff]
revert s s'
intro s s'
apply @Quotient.inductionOn₂' _ _ _ _ _ s s'
intro l l' hl hl'
simpa using formPerm_eq_formPerm_iff hl hl'
end Cycle
namespace Equiv.Perm
section Fintype
variable [Fintype α] [DecidableEq α] (p : Equiv.Perm α) (x : α)
/-- `Equiv.Perm.toList (f : Perm α) (x : α)` generates the list `[x, f x, f (f x), ...]`
until looping. That means when `f x = x`, `toList f x = []`.
-/
def toList : List α :=
List.iterate p x (cycleOf p x).support.card
@[simp]
theorem toList_one : toList (1 : Perm α) x = [] := by simp [toList, cycleOf_one]
@[simp]
theorem toList_eq_nil_iff {p : Perm α} {x} : toList p x = [] ↔ x ∉ p.support := by simp [toList]
@[simp]
theorem length_toList : length (toList p x) = (cycleOf p x).support.card := by simp [toList]
theorem toList_ne_singleton (y : α) : toList p x ≠ [y] := by
intro H
simpa [card_support_ne_one] using congr_arg length H
theorem two_le_length_toList_iff_mem_support {p : Perm α} {x : α} :
2 ≤ length (toList p x) ↔ x ∈ p.support := by simp
theorem length_toList_pos_of_mem_support (h : x ∈ p.support) : 0 < length (toList p x) :=
zero_lt_two.trans_le (two_le_length_toList_iff_mem_support.mpr h)
theorem getElem_toList (n : ℕ) (hn : n < length (toList p x)) :
(toList p x)[n] = (p ^ n) x := by simp [toList]
@[deprecated getElem_toList (since := "2025-02-17")]
theorem get_toList (n : ℕ) (hn : n < length (toList p x)) :
(toList p x).get ⟨n, hn⟩ = (p ^ n) x := by simp [toList]
theorem toList_getElem_zero (h : x ∈ p.support) :
(toList p x)[0]'(length_toList_pos_of_mem_support _ _ h) = x := by simp [toList]
@[deprecated toList_getElem_zero (since := "2025-02-17")]
theorem toList_get_zero (h : x ∈ p.support) :
(toList p x).get ⟨0, (length_toList_pos_of_mem_support _ _ h)⟩ = x := by simp [toList]
variable {p} {x}
theorem mem_toList_iff {y : α} : y ∈ toList p x ↔ SameCycle p x y ∧ x ∈ p.support := by
simp only [toList, mem_iterate, iterate_eq_pow, eq_comm (a := y)]
constructor
· rintro ⟨n, hx, rfl⟩
refine ⟨⟨n, rfl⟩, ?_⟩
contrapose! hx
rw [← support_cycleOf_eq_nil_iff] at hx
simp [hx]
· rintro ⟨h, hx⟩
simpa using h.exists_pow_eq_of_mem_support hx
theorem nodup_toList (p : Perm α) (x : α) : Nodup (toList p x) := by
by_cases hx : p x = x
· rw [← not_mem_support, ← toList_eq_nil_iff] at hx
simp [hx]
have hc : IsCycle (cycleOf p x) := isCycle_cycleOf p hx
rw [nodup_iff_injective_getElem]
intro ⟨n, hn⟩ ⟨m, hm⟩
rw [length_toList, ← hc.orderOf] at hm hn
rw [← cycleOf_apply_self, ← Ne, ← mem_support] at hx
simp only [Fin.mk.injEq]
rw [getElem_toList, getElem_toList, ← cycleOf_pow_apply_self p x n, ←
cycleOf_pow_apply_self p x m]
rcases n with - | n <;> rcases m with - | m
· simp
· rw [← hc.support_pow_of_pos_of_lt_orderOf m.zero_lt_succ hm, mem_support,
cycleOf_pow_apply_self] at hx
simp [hx.symm]
· rw [← hc.support_pow_of_pos_of_lt_orderOf n.zero_lt_succ hn, mem_support,
cycleOf_pow_apply_self] at hx
simp [hx]
intro h
have hn' : ¬orderOf (p.cycleOf x) ∣ n.succ := Nat.not_dvd_of_pos_of_lt n.zero_lt_succ hn
have hm' : ¬orderOf (p.cycleOf x) ∣ m.succ := Nat.not_dvd_of_pos_of_lt m.zero_lt_succ hm
rw [← hc.support_pow_eq_iff] at hn' hm'
rw [← Nat.mod_eq_of_lt hn, ← Nat.mod_eq_of_lt hm, ← pow_inj_mod]
refine support_congr ?_ ?_
· rw [hm', hn']
· rw [hm']
intro y hy
obtain ⟨k, rfl⟩ := hc.exists_pow_eq (mem_support.mp hx) (mem_support.mp hy)
rw [← mul_apply, (Commute.pow_pow_self _ _ _).eq, mul_apply, h, ← mul_apply, ← mul_apply,
(Commute.pow_pow_self _ _ _).eq]
theorem next_toList_eq_apply (p : Perm α) (x y : α) (hy : y ∈ toList p x) :
next (toList p x) y hy = p y := by
rw [mem_toList_iff] at hy
obtain ⟨k, hk, hk'⟩ := hy.left.exists_pow_eq_of_mem_support hy.right
rw [← getElem_toList p x k (by simpa using hk)] at hk'
simp_rw [← hk']
rw [next_getElem _ (nodup_toList _ _), getElem_toList, getElem_toList, ← mul_apply, ← pow_succ']
simp_rw [length_toList]
rw [← pow_mod_orderOf_cycleOf_apply p (k + 1), IsCycle.orderOf]
exact isCycle_cycleOf _ (mem_support.mp hy.right)
theorem toList_pow_apply_eq_rotate (p : Perm α) (x : α) (k : ℕ) :
p.toList ((p ^ k) x) = (p.toList x).rotate k := by
apply ext_getElem
· simp only [length_toList, cycleOf_self_apply_pow, length_rotate]
· intro n hn hn'
rw [getElem_toList, getElem_rotate, getElem_toList, length_toList,
pow_mod_card_support_cycleOf_self_apply, pow_add, mul_apply]
theorem SameCycle.toList_isRotated {f : Perm α} {x y : α} (h : SameCycle f x y) :
toList f x ~r toList f y := by
by_cases hx : x ∈ f.support
· obtain ⟨_ | k, _, hy⟩ := h.exists_pow_eq_of_mem_support hx
· simp only [coe_one, id, pow_zero] at hy
-- Porting note: added `IsRotated.refl`
simp [hy, IsRotated.refl]
use k.succ
rw [← toList_pow_apply_eq_rotate, hy]
· rw [toList_eq_nil_iff.mpr hx, isRotated_nil_iff', eq_comm, toList_eq_nil_iff]
rwa [← h.mem_support_iff]
theorem pow_apply_mem_toList_iff_mem_support {n : ℕ} : (p ^ n) x ∈ p.toList x ↔ x ∈ p.support := by
rw [mem_toList_iff, and_iff_right_iff_imp]
refine fun _ => SameCycle.symm ?_
rw [sameCycle_pow_left]
theorem toList_formPerm_nil (x : α) : toList (formPerm ([] : List α)) x = [] := by simp
theorem toList_formPerm_singleton (x y : α) : toList (formPerm [x]) y = [] := by simp
theorem toList_formPerm_nontrivial (l : List α) (hl : 2 ≤ l.length) (hn : Nodup l) :
toList (formPerm l) (l.get ⟨0, (zero_lt_two.trans_le hl)⟩) = l := by
have hc : l.formPerm.IsCycle := List.isCycle_formPerm hn hl
have hs : l.formPerm.support = l.toFinset := by
refine support_formPerm_of_nodup _ hn ?_
rintro _ rfl
simp [Nat.succ_le_succ_iff] at hl
rw [toList, hc.cycleOf_eq (mem_support.mp _), hs, card_toFinset, dedup_eq_self.mpr hn]
· refine ext_getElem (by simp) fun k hk hk' => ?_
simp only [get_eq_getElem, getElem_iterate, iterate_eq_pow, formPerm_pow_apply_getElem _ hn,
zero_add, Nat.mod_eq_of_lt hk']
· simp [hs]
theorem toList_formPerm_isRotated_self (l : List α) (hl : 2 ≤ l.length) (hn : Nodup l) (x : α)
(hx : x ∈ l) : toList (formPerm l) x ~r l := by
obtain ⟨k, hk, rfl⟩ := get_of_mem hx
have hr : l ~r l.rotate k := ⟨k, rfl⟩
rw [formPerm_eq_of_isRotated hn hr]
rw [get_eq_get_rotate l k k]
simp only [Nat.mod_eq_of_lt k.2, tsub_add_cancel_of_le (le_of_lt k.2), Nat.mod_self]
rw [toList_formPerm_nontrivial]
· simp
· simpa using hl
· simpa using hn
theorem formPerm_toList (f : Perm α) (x : α) : formPerm (toList f x) = f.cycleOf x := by
by_cases hx : f x = x
· rw [(cycleOf_eq_one_iff f).mpr hx, toList_eq_nil_iff.mpr (not_mem_support.mpr hx),
formPerm_nil]
ext y
by_cases hy : SameCycle f x y
· obtain ⟨k, _, rfl⟩ := hy.exists_pow_eq_of_mem_support (mem_support.mpr hx)
rw [cycleOf_apply_apply_pow_self, List.formPerm_apply_mem_eq_next (nodup_toList f x),
next_toList_eq_apply, pow_succ', mul_apply]
rw [mem_toList_iff]
exact ⟨⟨k, rfl⟩, mem_support.mpr hx⟩
· rw [cycleOf_apply_of_not_sameCycle hy, formPerm_apply_of_not_mem]
simp [mem_toList_iff, hy]
/-- Given a cyclic `f : Perm α`, generate the `Cycle α` in the order
of application of `f`. Implemented by finding an element `x : α`
in the support of `f` in `Finset.univ`, and iterating on using
`Equiv.Perm.toList f x`.
| -/
def toCycle (f : Perm α) (hf : IsCycle f) : Cycle α :=
Multiset.recOn (Finset.univ : Finset α).val (Quot.mk _ [])
(fun x _ l => if f x = x then l else toList f x)
(by
intro x y _ s
refine heq_of_eq ?_
split_ifs with hx hy hy <;> try rfl
have hc : SameCycle f x y := IsCycle.sameCycle hf hx hy
exact Quotient.sound' hc.toList_isRotated)
theorem toCycle_eq_toList (f : Perm α) (hf : IsCycle f) (x : α) (hx : f x ≠ x) :
| Mathlib/GroupTheory/Perm/Cycle/Concrete.lean | 358 | 369 |
/-
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, Mario Carneiro
-/
import Mathlib.Algebra.Field.IsField
import Mathlib.Data.Fin.VecNotation
import Mathlib.Data.Nat.Choose.Sum
import Mathlib.LinearAlgebra.Finsupp.LinearCombination
import Mathlib.RingTheory.Ideal.Maximal
import Mathlib.Tactic.FinCases
/-!
# Ideals over a ring
This file contains an assortment of definitions and results for `Ideal R`,
the type of (left) ideals over a ring `R`.
Note that over commutative rings, left ideals and two-sided ideals are equivalent.
## Implementation notes
`Ideal R` is implemented using `Submodule R R`, where `•` is interpreted as `*`.
## TODO
Support right ideals, and two-sided ideals over non-commutative rings.
-/
variable {ι α β F : Type*}
open Set Function
open Pointwise
section Semiring
namespace Ideal
variable {α : ι → Type*} [Π i, Semiring (α i)] (I : Π i, Ideal (α i))
section Pi
/-- `Πᵢ Iᵢ` as an ideal of `Πᵢ Rᵢ`. -/
def pi : Ideal (Π i, α i) where
carrier := { x | ∀ i, x i ∈ I i }
zero_mem' i := (I i).zero_mem
add_mem' ha hb i := (I i).add_mem (ha i) (hb i)
smul_mem' a _b hb i := (I i).mul_mem_left (a i) (hb i)
theorem mem_pi (x : Π i, α i) : x ∈ pi I ↔ ∀ i, x i ∈ I i :=
Iff.rfl
instance (priority := low) [∀ i, (I i).IsTwoSided] : (pi I).IsTwoSided :=
⟨fun _b hb i ↦ mul_mem_right _ _ (hb i)⟩
end Pi
section Commute
variable {α : Type*} [Semiring α] (I : Ideal α) {a b : α}
theorem add_pow_mem_of_pow_mem_of_le_of_commute {m n k : ℕ}
(ha : a ^ m ∈ I) (hb : b ^ n ∈ I) (hk : m + n ≤ k + 1)
(hab : Commute a b) :
(a + b) ^ k ∈ I := by
simp_rw [hab.add_pow, ← Nat.cast_comm]
apply I.sum_mem
intro c _
apply mul_mem_left
by_cases h : m ≤ c
· rw [hab.pow_pow]
exact I.mul_mem_left _ (I.pow_mem_of_pow_mem ha h)
· refine I.mul_mem_left _ (I.pow_mem_of_pow_mem hb ?_)
omega
theorem add_pow_add_pred_mem_of_pow_mem_of_commute {m n : ℕ}
(ha : a ^ m ∈ I) (hb : b ^ n ∈ I) (hab : Commute a b) :
(a + b) ^ (m + n - 1) ∈ I :=
I.add_pow_mem_of_pow_mem_of_le_of_commute ha hb (by rw [← Nat.sub_le_iff_le_add]) hab
end Commute
end Ideal
end Semiring
section CommSemiring
variable {a b : α}
-- A separate namespace definition is needed because the variables were historically in a different
-- order.
namespace Ideal
variable [CommSemiring α] (I : Ideal α)
theorem add_pow_mem_of_pow_mem_of_le {m n k : ℕ}
(ha : a ^ m ∈ I) (hb : b ^ n ∈ I) (hk : m + n ≤ k + 1) :
(a + b) ^ k ∈ I :=
I.add_pow_mem_of_pow_mem_of_le_of_commute ha hb hk (Commute.all ..)
theorem add_pow_add_pred_mem_of_pow_mem {m n : ℕ}
(ha : a ^ m ∈ I) (hb : b ^ n ∈ I) :
(a + b) ^ (m + n - 1) ∈ I :=
I.add_pow_add_pred_mem_of_pow_mem_of_commute ha hb (Commute.all ..)
theorem pow_multiset_sum_mem_span_pow [DecidableEq α] (s : Multiset α) (n : ℕ) :
s.sum ^ (Multiset.card s * n + 1) ∈
span ((s.map fun (x : α) ↦ x ^ (n + 1)).toFinset : Set α) := by
induction' s using Multiset.induction_on with a s hs
· simp
simp only [Finset.coe_insert, Multiset.map_cons, Multiset.toFinset_cons, Multiset.sum_cons,
Multiset.card_cons, add_pow]
refine Submodule.sum_mem _ ?_
intro c _hc
rw [mem_span_insert]
by_cases h : n + 1 ≤ c
· refine ⟨a ^ (c - (n + 1)) * s.sum ^ ((Multiset.card s + 1) * n + 1 - c) *
((Multiset.card s + 1) * n + 1).choose c, 0, Submodule.zero_mem _, ?_⟩
rw [mul_comm _ (a ^ (n + 1))]
simp_rw [← mul_assoc]
rw [← pow_add, add_zero, add_tsub_cancel_of_le h]
· use 0
simp_rw [zero_mul, zero_add]
refine ⟨_, ?_, rfl⟩
replace h : c ≤ n := Nat.lt_succ_iff.mp (not_le.mp h)
have : (Multiset.card s + 1) * n + 1 - c = Multiset.card s * n + 1 + (n - c) := by
rw [add_mul, one_mul, add_assoc, add_comm n 1, ← add_assoc, add_tsub_assoc_of_le h]
rw [this, pow_add]
simp_rw [mul_assoc, mul_comm (s.sum ^ (Multiset.card s * n + 1)), ← mul_assoc]
exact mul_mem_left _ _ hs
theorem sum_pow_mem_span_pow {ι} (s : Finset ι) (f : ι → α) (n : ℕ) :
(∑ i ∈ s, f i) ^ (s.card * n + 1) ∈ span ((fun i => f i ^ (n + 1)) '' s) := by
classical
simpa only [Multiset.card_map, Multiset.map_map, comp_apply, Multiset.toFinset_map,
Finset.coe_image, Finset.val_toFinset] using pow_multiset_sum_mem_span_pow (s.1.map f) n
theorem span_pow_eq_top (s : Set α) (hs : span s = ⊤) (n : ℕ) :
span ((fun (x : α) => x ^ n) '' s) = ⊤ := by
rw [eq_top_iff_one]
rcases n with - | n
· obtain rfl | ⟨x, hx⟩ := eq_empty_or_nonempty s
· rw [Set.image_empty, hs]
trivial
· exact subset_span ⟨_, hx, pow_zero _⟩
rw [eq_top_iff_one, span, Finsupp.mem_span_iff_linearCombination] at hs
rcases hs with ⟨f, hf⟩
have hf : (f.support.sum fun a => f a * a) = 1 := hf -- Porting note: was `change ... at hf`
have := sum_pow_mem_span_pow f.support (fun a => f a * a) n
rw [hf, one_pow] at this
refine span_le.mpr ?_ this
rintro _ hx
simp_rw [Set.mem_image] at hx
rcases hx with ⟨x, _, rfl⟩
have : span ({(x : α) ^ (n + 1)} : Set α) ≤ span ((fun x : α => x ^ (n + 1)) '' s) := by
rw [span_le, Set.singleton_subset_iff]
exact subset_span ⟨x, x.prop, rfl⟩
refine this ?_
rw [mul_pow, mem_span_singleton]
exact ⟨f x ^ (n + 1), mul_comm _ _⟩
theorem span_range_pow_eq_top (s : Set α) (hs : span s = ⊤) (n : s → ℕ) :
span (Set.range fun x ↦ x.1 ^ n x) = ⊤ := by
have ⟨t, hts, mem⟩ := Submodule.mem_span_finite_of_mem_span ((eq_top_iff_one _).mp hs)
refine top_unique ((span_pow_eq_top _ ((eq_top_iff_one _).mpr mem) <|
t.attach.sup fun x ↦ n ⟨x, hts x.2⟩).ge.trans <| span_le.mpr ?_)
rintro _ ⟨x, hxt, rfl⟩
rw [← Nat.sub_add_cancel (Finset.le_sup <| t.mem_attach ⟨x, hxt⟩)]
simp_rw [pow_add]
exact mul_mem_left _ _ (subset_span ⟨_, rfl⟩)
theorem prod_mem {ι : Type*} {f : ι → α} {s : Finset ι}
(I : Ideal α) {i : ι} (hi : i ∈ s) (hfi : f i ∈ I) :
∏ i ∈ s, f i ∈ I := by
classical
rw [Finset.prod_eq_prod_diff_singleton_mul hi]
exact Ideal.mul_mem_left _ _ hfi
end Ideal
| end CommSemiring
section DivisionSemiring
| Mathlib/RingTheory/Ideal/Basic.lean | 184 | 187 |
/-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis
-/
import Mathlib.Algebra.BigOperators.Field
import Mathlib.Analysis.Complex.Basic
import Mathlib.Analysis.InnerProductSpace.Defs
import Mathlib.GroupTheory.MonoidLocalization.Basic
/-!
# Properties of inner product spaces
This file proves many basic properties of inner product spaces (real or complex).
## Main results
- `inner_mul_inner_self_le`: the Cauchy-Schwartz inequality (one of many variants).
- `norm_inner_eq_norm_iff`: the equality criteion in the Cauchy-Schwartz inequality (also in many
variants).
- `inner_eq_sum_norm_sq_div_four`: the polarization identity.
## Tags
inner product space, Hilbert space, norm
-/
noncomputable section
open RCLike Real Filter Topology ComplexConjugate Finsupp
open LinearMap (BilinForm)
variable {𝕜 E F : Type*} [RCLike 𝕜]
section BasicProperties_Seminormed
open scoped InnerProductSpace
variable [SeminormedAddCommGroup E] [InnerProductSpace 𝕜 E]
variable [SeminormedAddCommGroup F] [InnerProductSpace ℝ F]
local notation "⟪" x ", " y "⟫" => @inner 𝕜 _ _ x y
local postfix:90 "†" => starRingEnd _
export InnerProductSpace (norm_sq_eq_re_inner)
@[simp]
theorem inner_conj_symm (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ :=
InnerProductSpace.conj_inner_symm _ _
theorem real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ :=
@inner_conj_symm ℝ _ _ _ _ x y
theorem inner_eq_zero_symm {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := by
rw [← inner_conj_symm]
exact star_eq_zero
@[simp]
theorem inner_self_im (x : E) : im ⟪x, x⟫ = 0 := by rw [← @ofReal_inj 𝕜, im_eq_conj_sub]; simp
theorem inner_add_left (x y z : E) : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ :=
InnerProductSpace.add_left _ _ _
theorem inner_add_right (x y z : E) : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by
rw [← inner_conj_symm, inner_add_left, RingHom.map_add]
simp only [inner_conj_symm]
theorem inner_re_symm (x y : E) : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [← inner_conj_symm, conj_re]
theorem inner_im_symm (x y : E) : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [← inner_conj_symm, conj_im]
section Algebra
variable {𝕝 : Type*} [CommSemiring 𝕝] [StarRing 𝕝] [Algebra 𝕝 𝕜] [Module 𝕝 E]
[IsScalarTower 𝕝 𝕜 E] [StarModule 𝕝 𝕜]
/-- See `inner_smul_left` for the common special when `𝕜 = 𝕝`. -/
lemma inner_smul_left_eq_star_smul (x y : E) (r : 𝕝) : ⟪r • x, y⟫ = r† • ⟪x, y⟫ := by
rw [← algebraMap_smul 𝕜 r, InnerProductSpace.smul_left, starRingEnd_apply, starRingEnd_apply,
← algebraMap_star_comm, ← smul_eq_mul, algebraMap_smul]
/-- Special case of `inner_smul_left_eq_star_smul` when the acting ring has a trivial star
(eg `ℕ`, `ℤ`, `ℚ≥0`, `ℚ`, `ℝ`). -/
lemma inner_smul_left_eq_smul [TrivialStar 𝕝] (x y : E) (r : 𝕝) : ⟪r • x, y⟫ = r • ⟪x, y⟫ := by
rw [inner_smul_left_eq_star_smul, starRingEnd_apply, star_trivial]
/-- See `inner_smul_right` for the common special when `𝕜 = 𝕝`. -/
lemma inner_smul_right_eq_smul (x y : E) (r : 𝕝) : ⟪x, r • y⟫ = r • ⟪x, y⟫ := by
rw [← inner_conj_symm, inner_smul_left_eq_star_smul, starRingEnd_apply, starRingEnd_apply,
star_smul, star_star, ← starRingEnd_apply, inner_conj_symm]
end Algebra
/-- See `inner_smul_left_eq_star_smul` for the case of a general algebra action. -/
theorem inner_smul_left (x y : E) (r : 𝕜) : ⟪r • x, y⟫ = r† * ⟪x, y⟫ :=
inner_smul_left_eq_star_smul ..
theorem real_inner_smul_left (x y : F) (r : ℝ) : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ :=
inner_smul_left _ _ _
theorem inner_smul_real_left (x y : E) (r : ℝ) : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by
rw [inner_smul_left, conj_ofReal, Algebra.smul_def]
/-- See `inner_smul_right_eq_smul` for the case of a general algebra action. -/
theorem inner_smul_right (x y : E) (r : 𝕜) : ⟪x, r • y⟫ = r * ⟪x, y⟫ :=
inner_smul_right_eq_smul ..
theorem real_inner_smul_right (x y : F) (r : ℝ) : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ :=
inner_smul_right _ _ _
theorem inner_smul_real_right (x y : E) (r : ℝ) : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by
rw [inner_smul_right, Algebra.smul_def]
/-- The inner product as a sesquilinear form.
Note that in the case `𝕜 = ℝ` this is a bilinear form. -/
@[simps!]
def sesqFormOfInner : E →ₗ[𝕜] E →ₗ⋆[𝕜] 𝕜 :=
LinearMap.mk₂'ₛₗ (RingHom.id 𝕜) (starRingEnd _) (fun x y => ⟪y, x⟫)
(fun _x _y _z => inner_add_right _ _ _) (fun _r _x _y => inner_smul_right _ _ _)
(fun _x _y _z => inner_add_left _ _ _) fun _r _x _y => inner_smul_left _ _ _
/-- The real inner product as a bilinear form.
Note that unlike `sesqFormOfInner`, this does not reverse the order of the arguments. -/
@[simps!]
def bilinFormOfRealInner : BilinForm ℝ F := sesqFormOfInner.flip
/-- An inner product with a sum on the left. -/
theorem sum_inner {ι : Type*} (s : Finset ι) (f : ι → E) (x : E) :
⟪∑ i ∈ s, f i, x⟫ = ∑ i ∈ s, ⟪f i, x⟫ :=
map_sum (sesqFormOfInner (𝕜 := 𝕜) (E := E) x) _ _
/-- An inner product with a sum on the right. -/
theorem inner_sum {ι : Type*} (s : Finset ι) (f : ι → E) (x : E) :
⟪x, ∑ i ∈ s, f i⟫ = ∑ i ∈ s, ⟪x, f i⟫ :=
map_sum (LinearMap.flip sesqFormOfInner x) _ _
/-- An inner product with a sum on the left, `Finsupp` version. -/
protected theorem Finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) :
⟪l.sum fun (i : ι) (a : 𝕜) => a • v i, x⟫ = l.sum fun (i : ι) (a : 𝕜) => conj a • ⟪v i, x⟫ := by
convert sum_inner (𝕜 := 𝕜) l.support (fun a => l a • v a) x
simp only [inner_smul_left, Finsupp.sum, smul_eq_mul]
/-- An inner product with a sum on the right, `Finsupp` version. -/
protected theorem Finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) :
⟪x, l.sum fun (i : ι) (a : 𝕜) => a • v i⟫ = l.sum fun (i : ι) (a : 𝕜) => a • ⟪x, v i⟫ := by
convert inner_sum (𝕜 := 𝕜) l.support (fun a => l a • v a) x
simp only [inner_smul_right, Finsupp.sum, smul_eq_mul]
protected theorem DFinsupp.sum_inner {ι : Type*} [DecidableEq ι] {α : ι → Type*}
[∀ i, AddZeroClass (α i)] [∀ (i) (x : α i), Decidable (x ≠ 0)] (f : ∀ i, α i → E)
(l : Π₀ i, α i) (x : E) : ⟪l.sum f, x⟫ = l.sum fun i a => ⟪f i a, x⟫ := by
simp +contextual only [DFinsupp.sum, sum_inner, smul_eq_mul]
protected theorem DFinsupp.inner_sum {ι : Type*} [DecidableEq ι] {α : ι → Type*}
[∀ i, AddZeroClass (α i)] [∀ (i) (x : α i), Decidable (x ≠ 0)] (f : ∀ i, α i → E)
(l : Π₀ i, α i) (x : E) : ⟪x, l.sum f⟫ = l.sum fun i a => ⟪x, f i a⟫ := by
simp +contextual only [DFinsupp.sum, inner_sum, smul_eq_mul]
@[simp]
theorem inner_zero_left (x : E) : ⟪0, x⟫ = 0 := by
rw [← zero_smul 𝕜 (0 : E), inner_smul_left, RingHom.map_zero, zero_mul]
theorem inner_re_zero_left (x : E) : re ⟪0, x⟫ = 0 := by
simp only [inner_zero_left, AddMonoidHom.map_zero]
@[simp]
theorem inner_zero_right (x : E) : ⟪x, 0⟫ = 0 := by
rw [← inner_conj_symm, inner_zero_left, RingHom.map_zero]
theorem inner_re_zero_right (x : E) : re ⟪x, 0⟫ = 0 := by
simp only [inner_zero_right, AddMonoidHom.map_zero]
theorem inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ :=
PreInnerProductSpace.toCore.re_inner_nonneg x
theorem real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ :=
@inner_self_nonneg ℝ F _ _ _ x
@[simp]
theorem inner_self_ofReal_re (x : E) : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ :=
((RCLike.is_real_TFAE (⟪x, x⟫ : 𝕜)).out 2 3).2 (inner_self_im (𝕜 := 𝕜) x)
theorem inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (‖x‖ : 𝕜) ^ 2 := by
rw [← inner_self_ofReal_re, ← norm_sq_eq_re_inner, ofReal_pow]
theorem inner_self_re_eq_norm (x : E) : re ⟪x, x⟫ = ‖⟪x, x⟫‖ := by
conv_rhs => rw [← inner_self_ofReal_re]
symm
exact norm_of_nonneg inner_self_nonneg
theorem inner_self_ofReal_norm (x : E) : (‖⟪x, x⟫‖ : 𝕜) = ⟪x, x⟫ := by
rw [← inner_self_re_eq_norm]
exact inner_self_ofReal_re _
theorem real_inner_self_abs (x : F) : |⟪x, x⟫_ℝ| = ⟪x, x⟫_ℝ :=
@inner_self_ofReal_norm ℝ F _ _ _ x
theorem norm_inner_symm (x y : E) : ‖⟪x, y⟫‖ = ‖⟪y, x⟫‖ := by rw [← inner_conj_symm, norm_conj]
@[simp]
theorem inner_neg_left (x y : E) : ⟪-x, y⟫ = -⟪x, y⟫ := by
rw [← neg_one_smul 𝕜 x, inner_smul_left]
simp
@[simp]
theorem inner_neg_right (x y : E) : ⟪x, -y⟫ = -⟪x, y⟫ := by
rw [← inner_conj_symm, inner_neg_left]; simp only [RingHom.map_neg, inner_conj_symm]
theorem inner_neg_neg (x y : E) : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp
theorem inner_self_conj (x : E) : ⟪x, x⟫† = ⟪x, x⟫ := inner_conj_symm _ _
theorem inner_sub_left (x y z : E) : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by
simp [sub_eq_add_neg, inner_add_left]
theorem inner_sub_right (x y z : E) : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by
simp [sub_eq_add_neg, inner_add_right]
theorem inner_mul_symm_re_eq_norm (x y : E) : re (⟪x, y⟫ * ⟪y, x⟫) = ‖⟪x, y⟫ * ⟪y, x⟫‖ := by
rw [← inner_conj_symm, mul_comm]
exact re_eq_norm_of_mul_conj (inner y x)
/-- Expand `⟪x + y, x + y⟫` -/
theorem inner_add_add_self (x y : E) : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by
simp only [inner_add_left, inner_add_right]; ring
/-- Expand `⟪x + y, x + y⟫_ℝ` -/
theorem real_inner_add_add_self (x y : F) :
⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := by
have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [← inner_conj_symm]; rfl
simp only [inner_add_add_self, this, add_left_inj]
ring
-- Expand `⟪x - y, x - y⟫`
theorem inner_sub_sub_self (x y : E) : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by
simp only [inner_sub_left, inner_sub_right]; ring
/-- Expand `⟪x - y, x - y⟫_ℝ` -/
theorem real_inner_sub_sub_self (x y : F) :
⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := by
have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [← inner_conj_symm]; rfl
simp only [inner_sub_sub_self, this, add_left_inj]
ring
/-- Parallelogram law -/
theorem parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by
simp only [inner_add_add_self, inner_sub_sub_self]
ring
/-- **Cauchy–Schwarz inequality**. -/
theorem inner_mul_inner_self_le (x y : E) : ‖⟪x, y⟫‖ * ‖⟪y, x⟫‖ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ :=
letI cd : PreInnerProductSpace.Core 𝕜 E := PreInnerProductSpace.toCore
InnerProductSpace.Core.inner_mul_inner_self_le x y
/-- Cauchy–Schwarz inequality for real inner products. -/
theorem real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ :=
calc
⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ‖⟪x, y⟫_ℝ‖ * ‖⟪y, x⟫_ℝ‖ := by
rw [real_inner_comm y, ← norm_mul]
exact le_abs_self _
_ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := @inner_mul_inner_self_le ℝ _ _ _ _ x y
end BasicProperties_Seminormed
section BasicProperties
variable [NormedAddCommGroup E] [InnerProductSpace 𝕜 E]
variable [NormedAddCommGroup F] [InnerProductSpace ℝ F]
local notation "⟪" x ", " y "⟫" => @inner 𝕜 _ _ x y
export InnerProductSpace (norm_sq_eq_re_inner)
@[simp]
theorem inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := by
rw [inner_self_eq_norm_sq_to_K, sq_eq_zero_iff, ofReal_eq_zero, norm_eq_zero]
theorem inner_self_ne_zero {x : E} : ⟪x, x⟫ ≠ 0 ↔ x ≠ 0 :=
inner_self_eq_zero.not
variable (𝕜)
theorem ext_inner_left {x y : E} (h : ∀ v, ⟪v, x⟫ = ⟪v, y⟫) : x = y := by
rw [← sub_eq_zero, ← @inner_self_eq_zero 𝕜, inner_sub_right, sub_eq_zero, h (x - y)]
theorem ext_inner_right {x y : E} (h : ∀ v, ⟪x, v⟫ = ⟪y, v⟫) : x = y := by
rw [← sub_eq_zero, ← @inner_self_eq_zero 𝕜, inner_sub_left, sub_eq_zero, h (x - y)]
variable {𝕜}
@[simp]
theorem re_inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := by
rw [← norm_sq_eq_re_inner, (sq_nonneg _).le_iff_eq, sq_eq_zero_iff, norm_eq_zero]
@[simp]
lemma re_inner_self_pos {x : E} : 0 < re ⟪x, x⟫ ↔ x ≠ 0 := by
simpa [-re_inner_self_nonpos] using re_inner_self_nonpos (𝕜 := 𝕜) (x := x).not
@[deprecated (since := "2025-04-22")] alias inner_self_nonpos := re_inner_self_nonpos
@[deprecated (since := "2025-04-22")] alias inner_self_pos := re_inner_self_pos
open scoped InnerProductSpace in
theorem real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := re_inner_self_nonpos (𝕜 := ℝ)
open scoped InnerProductSpace in
theorem real_inner_self_pos {x : F} : 0 < ⟪x, x⟫_ℝ ↔ x ≠ 0 := re_inner_self_pos (𝕜 := ℝ)
/-- A family of vectors is linearly independent if they are nonzero
and orthogonal. -/
theorem linearIndependent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0)
(ho : Pairwise fun i j => ⟪v i, v j⟫ = 0) : LinearIndependent 𝕜 v := by
rw [linearIndependent_iff']
intro s g hg i hi
have h' : g i * inner (v i) (v i) = inner (v i) (∑ j ∈ s, g j • v j) := by
rw [inner_sum]
symm
convert Finset.sum_eq_single (M := 𝕜) i ?_ ?_
· rw [inner_smul_right]
· intro j _hj hji
rw [inner_smul_right, ho hji.symm, mul_zero]
· exact fun h => False.elim (h hi)
simpa [hg, hz] using h'
end BasicProperties
section Norm_Seminormed
open scoped InnerProductSpace
variable [SeminormedAddCommGroup E] [InnerProductSpace 𝕜 E]
variable [SeminormedAddCommGroup F] [InnerProductSpace ℝ F]
local notation "⟪" x ", " y "⟫" => @inner 𝕜 _ _ x y
local notation "IK" => @RCLike.I 𝕜 _
theorem norm_eq_sqrt_re_inner (x : E) : ‖x‖ = √(re ⟪x, x⟫) :=
calc
‖x‖ = √(‖x‖ ^ 2) := (sqrt_sq (norm_nonneg _)).symm
_ = √(re ⟪x, x⟫) := congr_arg _ (norm_sq_eq_re_inner _)
@[deprecated (since := "2025-04-22")] alias norm_eq_sqrt_inner := norm_eq_sqrt_re_inner
theorem norm_eq_sqrt_real_inner (x : F) : ‖x‖ = √⟪x, x⟫_ℝ :=
@norm_eq_sqrt_re_inner ℝ _ _ _ _ x
theorem inner_self_eq_norm_mul_norm (x : E) : re ⟪x, x⟫ = ‖x‖ * ‖x‖ := by
rw [@norm_eq_sqrt_re_inner 𝕜, ← sqrt_mul inner_self_nonneg (re ⟪x, x⟫),
sqrt_mul_self inner_self_nonneg]
theorem inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ‖x‖ ^ 2 := by
rw [pow_two, inner_self_eq_norm_mul_norm]
theorem real_inner_self_eq_norm_mul_norm (x : F) : ⟪x, x⟫_ℝ = ‖x‖ * ‖x‖ := by
have h := @inner_self_eq_norm_mul_norm ℝ F _ _ _ x
simpa using h
theorem real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ‖x‖ ^ 2 := by
rw [pow_two, real_inner_self_eq_norm_mul_norm]
/-- Expand the square -/
theorem norm_add_sq (x y : E) : ‖x + y‖ ^ 2 = ‖x‖ ^ 2 + 2 * re ⟪x, y⟫ + ‖y‖ ^ 2 := by
repeat' rw [sq (M := ℝ), ← @inner_self_eq_norm_mul_norm 𝕜]
rw [inner_add_add_self, two_mul]
simp only [add_assoc, add_left_inj, add_right_inj, AddMonoidHom.map_add]
rw [← inner_conj_symm, conj_re]
alias norm_add_pow_two := norm_add_sq
/-- Expand the square -/
theorem norm_add_sq_real (x y : F) : ‖x + y‖ ^ 2 = ‖x‖ ^ 2 + 2 * ⟪x, y⟫_ℝ + ‖y‖ ^ 2 := by
have h := @norm_add_sq ℝ _ _ _ _ x y
simpa using h
alias norm_add_pow_two_real := norm_add_sq_real
/-- Expand the square -/
theorem norm_add_mul_self (x y : E) :
‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + 2 * re ⟪x, y⟫ + ‖y‖ * ‖y‖ := by
repeat' rw [← sq (M := ℝ)]
exact norm_add_sq _ _
/-- Expand the square -/
theorem norm_add_mul_self_real (x y : F) :
‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + 2 * ⟪x, y⟫_ℝ + ‖y‖ * ‖y‖ := by
have h := @norm_add_mul_self ℝ _ _ _ _ x y
simpa using h
/-- Expand the square -/
theorem norm_sub_sq (x y : E) : ‖x - y‖ ^ 2 = ‖x‖ ^ 2 - 2 * re ⟪x, y⟫ + ‖y‖ ^ 2 := by
rw [sub_eq_add_neg, @norm_add_sq 𝕜 _ _ _ _ x (-y), norm_neg, inner_neg_right, map_neg, mul_neg,
sub_eq_add_neg]
alias norm_sub_pow_two := norm_sub_sq
/-- Expand the square -/
theorem norm_sub_sq_real (x y : F) : ‖x - y‖ ^ 2 = ‖x‖ ^ 2 - 2 * ⟪x, y⟫_ℝ + ‖y‖ ^ 2 :=
@norm_sub_sq ℝ _ _ _ _ _ _
alias norm_sub_pow_two_real := norm_sub_sq_real
/-- Expand the square -/
theorem norm_sub_mul_self (x y : E) :
‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ - 2 * re ⟪x, y⟫ + ‖y‖ * ‖y‖ := by
repeat' rw [← sq (M := ℝ)]
exact norm_sub_sq _ _
/-- Expand the square -/
theorem norm_sub_mul_self_real (x y : F) :
‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ - 2 * ⟪x, y⟫_ℝ + ‖y‖ * ‖y‖ := by
have h := @norm_sub_mul_self ℝ _ _ _ _ x y
simpa using h
/-- Cauchy–Schwarz inequality with norm -/
theorem norm_inner_le_norm (x y : E) : ‖⟪x, y⟫‖ ≤ ‖x‖ * ‖y‖ := by
rw [norm_eq_sqrt_re_inner (𝕜 := 𝕜) x, norm_eq_sqrt_re_inner (𝕜 := 𝕜) y]
letI : PreInnerProductSpace.Core 𝕜 E := PreInnerProductSpace.toCore
exact InnerProductSpace.Core.norm_inner_le_norm x y
theorem nnnorm_inner_le_nnnorm (x y : E) : ‖⟪x, y⟫‖₊ ≤ ‖x‖₊ * ‖y‖₊ :=
norm_inner_le_norm x y
theorem re_inner_le_norm (x y : E) : re ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ :=
le_trans (re_le_norm (inner x y)) (norm_inner_le_norm x y)
/-- Cauchy–Schwarz inequality with norm -/
theorem abs_real_inner_le_norm (x y : F) : |⟪x, y⟫_ℝ| ≤ ‖x‖ * ‖y‖ :=
(Real.norm_eq_abs _).ge.trans (norm_inner_le_norm x y)
/-- Cauchy–Schwarz inequality with norm -/
theorem real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ‖x‖ * ‖y‖ :=
le_trans (le_abs_self _) (abs_real_inner_le_norm _ _)
lemma inner_eq_zero_of_left {x : E} (y : E) (h : ‖x‖ = 0) : ⟪x, y⟫_𝕜 = 0 := by
rw [← norm_eq_zero]
refine le_antisymm ?_ (by positivity)
exact norm_inner_le_norm _ _ |>.trans <| by simp [h]
lemma inner_eq_zero_of_right (x : E) {y : E} (h : ‖y‖ = 0) : ⟪x, y⟫_𝕜 = 0 := by
rw [inner_eq_zero_symm, inner_eq_zero_of_left _ h]
variable (𝕜)
include 𝕜 in
theorem parallelogram_law_with_norm (x y : E) :
‖x + y‖ * ‖x + y‖ + ‖x - y‖ * ‖x - y‖ = 2 * (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) := by
simp only [← @inner_self_eq_norm_mul_norm 𝕜]
rw [← re.map_add, parallelogram_law, two_mul, two_mul]
simp only [re.map_add]
include 𝕜 in
theorem parallelogram_law_with_nnnorm (x y : E) :
‖x + y‖₊ * ‖x + y‖₊ + ‖x - y‖₊ * ‖x - y‖₊ = 2 * (‖x‖₊ * ‖x‖₊ + ‖y‖₊ * ‖y‖₊) :=
Subtype.ext <| parallelogram_law_with_norm 𝕜 x y
variable {𝕜}
/-- Polarization identity: The real part of the inner product, in terms of the norm. -/
theorem re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) :
re ⟪x, y⟫ = (‖x + y‖ * ‖x + y‖ - ‖x‖ * ‖x‖ - ‖y‖ * ‖y‖) / 2 := by
rw [@norm_add_mul_self 𝕜]
ring
/-- Polarization identity: The real part of the inner product, in terms of the norm. -/
theorem re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) :
re ⟪x, y⟫ = (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - ‖x - y‖ * ‖x - y‖) / 2 := by
rw [@norm_sub_mul_self 𝕜]
ring
/-- Polarization identity: The real part of the inner product, in terms of the norm. -/
theorem re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) :
re ⟪x, y⟫ = (‖x + y‖ * ‖x + y‖ - ‖x - y‖ * ‖x - y‖) / 4 := by
rw [@norm_add_mul_self 𝕜, @norm_sub_mul_self 𝕜]
ring
/-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/
theorem im_inner_eq_norm_sub_i_smul_mul_self_sub_norm_add_i_smul_mul_self_div_four (x y : E) :
im ⟪x, y⟫ = (‖x - IK • y‖ * ‖x - IK • y‖ - ‖x + IK • y‖ * ‖x + IK • y‖) / 4 := by
simp only [@norm_add_mul_self 𝕜, @norm_sub_mul_self 𝕜, inner_smul_right, I_mul_re]
ring
/-- Polarization identity: The inner product, in terms of the norm. -/
theorem inner_eq_sum_norm_sq_div_four (x y : E) :
⟪x, y⟫ = ((‖x + y‖ : 𝕜) ^ 2 - (‖x - y‖ : 𝕜) ^ 2 +
((‖x - IK • y‖ : 𝕜) ^ 2 - (‖x + IK • y‖ : 𝕜) ^ 2) * IK) / 4 := by
rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four,
im_inner_eq_norm_sub_i_smul_mul_self_sub_norm_add_i_smul_mul_self_div_four]
push_cast
simp only [sq, ← mul_div_right_comm, ← add_div]
/-- Polarization identity: The real inner product, in terms of the norm. -/
theorem real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) :
⟪x, y⟫_ℝ = (‖x + y‖ * ‖x + y‖ - ‖x‖ * ‖x‖ - ‖y‖ * ‖y‖) / 2 :=
re_to_real.symm.trans <|
re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y
/-- Polarization identity: The real inner product, in terms of the norm. -/
theorem real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) :
⟪x, y⟫_ℝ = (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - ‖x - y‖ * ‖x - y‖) / 2 :=
re_to_real.symm.trans <|
re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y
/-- Pythagorean theorem, if-and-only-if vector inner product form. -/
theorem norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) :
‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ = 0 := by
rw [@norm_add_mul_self ℝ, add_right_cancel_iff, add_eq_left, mul_eq_zero]
norm_num
/-- Pythagorean theorem, if-and-if vector inner product form using square roots. -/
theorem norm_add_eq_sqrt_iff_real_inner_eq_zero {x y : F} :
‖x + y‖ = √(‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) ↔ ⟪x, y⟫_ℝ = 0 := by
rw [← norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, eq_comm, sqrt_eq_iff_mul_self_eq,
eq_comm] <;> positivity
/-- Pythagorean theorem, vector inner product form. -/
theorem norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) :
‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := by
rw [@norm_add_mul_self 𝕜, add_right_cancel_iff, add_eq_left, mul_eq_zero]
apply Or.inr
simp only [h, zero_re']
/-- Pythagorean theorem, vector inner product form. -/
theorem norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) :
‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ :=
(norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h
/-- Pythagorean theorem, subtracting vectors, if-and-only-if vector
inner product form. -/
theorem norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) :
‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ = 0 := by
rw [@norm_sub_mul_self ℝ, add_right_cancel_iff, sub_eq_add_neg, add_eq_left, neg_eq_zero,
mul_eq_zero]
norm_num
/-- Pythagorean theorem, subtracting vectors, if-and-if vector inner product form using square
roots. -/
theorem norm_sub_eq_sqrt_iff_real_inner_eq_zero {x y : F} :
‖x - y‖ = √(‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) ↔ ⟪x, y⟫_ℝ = 0 := by
rw [← norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, eq_comm, sqrt_eq_iff_mul_self_eq,
eq_comm] <;> positivity
/-- Pythagorean theorem, subtracting vectors, vector inner product
form. -/
theorem norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) :
‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ :=
(norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h
/-- The sum and difference of two vectors are orthogonal if and only
if they have the same norm. -/
theorem real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ‖x‖ = ‖y‖ := by
conv_rhs => rw [← mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _)]
simp only [← @inner_self_eq_norm_mul_norm ℝ, inner_add_left, inner_sub_right, real_inner_comm y x,
sub_eq_zero, re_to_real]
constructor
· intro h
rw [add_comm] at h
linarith
· intro h
linarith
/-- Given two orthogonal vectors, their sum and difference have equal norms. -/
theorem norm_sub_eq_norm_add {v w : E} (h : ⟪v, w⟫ = 0) : ‖w - v‖ = ‖w + v‖ := by
rw [← mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _)]
simp only [h, ← @inner_self_eq_norm_mul_norm 𝕜, sub_neg_eq_add, sub_zero, map_sub, zero_re',
zero_sub, add_zero, map_add, inner_add_right, inner_sub_left, inner_sub_right, inner_re_symm,
zero_add]
/-- The real inner product of two vectors, divided by the product of their
norms, has absolute value at most 1. -/
theorem abs_real_inner_div_norm_mul_norm_le_one (x y : F) : |⟪x, y⟫_ℝ / (‖x‖ * ‖y‖)| ≤ 1 := by
rw [abs_div, abs_mul, abs_norm, abs_norm]
exact div_le_one_of_le₀ (abs_real_inner_le_norm x y) (by positivity)
/-- The inner product of a vector with a multiple of itself. -/
theorem real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (‖x‖ * ‖x‖) := by
rw [real_inner_smul_left, ← real_inner_self_eq_norm_mul_norm]
/-- The inner product of a vector with a multiple of itself. -/
theorem real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (‖x‖ * ‖x‖) := by
rw [inner_smul_right, ← real_inner_self_eq_norm_mul_norm]
/-- The inner product of two weighted sums, where the weights in each
sum add to 0, in terms of the norms of pairwise differences. -/
theorem inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : Finset ι₁} {w₁ : ι₁ → ℝ}
(v₁ : ι₁ → F) (h₁ : ∑ i ∈ s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : Finset ι₂} {w₂ : ι₂ → ℝ}
(v₂ : ι₂ → F) (h₂ : ∑ i ∈ s₂, w₂ i = 0) :
⟪∑ i₁ ∈ s₁, w₁ i₁ • v₁ i₁, ∑ i₂ ∈ s₂, w₂ i₂ • v₂ i₂⟫_ℝ =
(-∑ i₁ ∈ s₁, ∑ i₂ ∈ s₂, w₁ i₁ * w₂ i₂ * (‖v₁ i₁ - v₂ i₂‖ * ‖v₁ i₁ - v₂ i₂‖)) / 2 := by
simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ← div_sub_div_same,
← div_add_div_same, mul_sub_left_distrib, left_distrib, Finset.sum_sub_distrib,
Finset.sum_add_distrib, ← Finset.mul_sum, ← Finset.sum_mul, h₁, h₂, zero_mul,
mul_zero, Finset.sum_const_zero, zero_add, zero_sub, Finset.mul_sum, neg_div,
Finset.sum_div, mul_div_assoc, mul_assoc]
end Norm_Seminormed
section Norm
open scoped InnerProductSpace
variable [NormedAddCommGroup E] [InnerProductSpace 𝕜 E]
variable [NormedAddCommGroup F] [InnerProductSpace ℝ F]
variable {ι : Type*}
local notation "⟪" x ", " y "⟫" => @inner 𝕜 _ _ x y
/-- Formula for the distance between the images of two nonzero points under an inversion with center
zero. See also `EuclideanGeometry.dist_inversion_inversion` for inversions around a general
point. -/
theorem dist_div_norm_sq_smul {x y : F} (hx : x ≠ 0) (hy : y ≠ 0) (R : ℝ) :
dist ((R / ‖x‖) ^ 2 • x) ((R / ‖y‖) ^ 2 • y) = R ^ 2 / (‖x‖ * ‖y‖) * dist x y :=
calc
dist ((R / ‖x‖) ^ 2 • x) ((R / ‖y‖) ^ 2 • y) =
√(‖(R / ‖x‖) ^ 2 • x - (R / ‖y‖) ^ 2 • y‖ ^ 2) := by
rw [dist_eq_norm, sqrt_sq (norm_nonneg _)]
_ = √((R ^ 2 / (‖x‖ * ‖y‖)) ^ 2 * ‖x - y‖ ^ 2) :=
congr_arg sqrt <| by
field_simp [sq, norm_sub_mul_self_real, norm_smul, real_inner_smul_left, inner_smul_right,
Real.norm_of_nonneg (mul_self_nonneg _)]
ring
_ = R ^ 2 / (‖x‖ * ‖y‖) * dist x y := by
rw [sqrt_mul, sqrt_sq, sqrt_sq, dist_eq_norm] <;> positivity
/-- The inner product of a nonzero vector with a nonzero multiple of
itself, divided by the product of their norms, has absolute value
1. -/
theorem norm_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0)
(hr : r ≠ 0) : ‖⟪x, r • x⟫‖ / (‖x‖ * ‖r • x‖) = 1 := by
have hx' : ‖x‖ ≠ 0 := by simp [hx]
have hr' : ‖r‖ ≠ 0 := by simp [hr]
rw [inner_smul_right, norm_mul, ← inner_self_re_eq_norm, inner_self_eq_norm_mul_norm, norm_smul]
rw [← mul_assoc, ← div_div, mul_div_cancel_right₀ _ hx', ← div_div, mul_comm,
mul_div_cancel_right₀ _ hr', div_self hx']
/-- The inner product of a nonzero vector with a nonzero multiple of
itself, divided by the product of their norms, has absolute value
1. -/
theorem abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ}
(hx : x ≠ 0) (hr : r ≠ 0) : |⟪x, r • x⟫_ℝ| / (‖x‖ * ‖r • x‖) = 1 :=
norm_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr
/-- The inner product of a nonzero vector with a positive multiple of
itself, divided by the product of their norms, has value 1. -/
theorem real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0)
(hr : 0 < r) : ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = 1 := by
rw [real_inner_smul_self_right, norm_smul, Real.norm_eq_abs, ← mul_assoc ‖x‖, mul_comm _ |r|,
mul_assoc, abs_of_nonneg hr.le, div_self]
exact mul_ne_zero hr.ne' (mul_self_ne_zero.2 (norm_ne_zero_iff.2 hx))
/-- The inner product of a nonzero vector with a negative multiple of
itself, divided by the product of their norms, has value -1. -/
theorem real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0)
(hr : r < 0) : ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = -1 := by
rw [real_inner_smul_self_right, norm_smul, Real.norm_eq_abs, ← mul_assoc ‖x‖, mul_comm _ |r|,
mul_assoc, abs_of_neg hr, neg_mul, div_neg_eq_neg_div, div_self]
exact mul_ne_zero hr.ne (mul_self_ne_zero.2 (norm_ne_zero_iff.2 hx))
theorem norm_inner_eq_norm_tfae (x y : E) :
List.TFAE [‖⟪x, y⟫‖ = ‖x‖ * ‖y‖,
x = 0 ∨ y = (⟪x, y⟫ / ⟪x, x⟫) • x,
x = 0 ∨ ∃ r : 𝕜, y = r • x,
x = 0 ∨ y ∈ 𝕜 ∙ x] := by
tfae_have 1 → 2 := by
refine fun h => or_iff_not_imp_left.2 fun hx₀ => ?_
have : ‖x‖ ^ 2 ≠ 0 := pow_ne_zero _ (norm_ne_zero_iff.2 hx₀)
rw [← sq_eq_sq₀, mul_pow, ← mul_right_inj' this, eq_comm, ← sub_eq_zero, ← mul_sub] at h <;>
try positivity
simp only [@norm_sq_eq_re_inner 𝕜] at h
letI : InnerProductSpace.Core 𝕜 E := InnerProductSpace.toCore
erw [← InnerProductSpace.Core.cauchy_schwarz_aux (𝕜 := 𝕜) (F := E)] at h
rw [InnerProductSpace.Core.normSq_eq_zero, sub_eq_zero] at h
rw [div_eq_inv_mul, mul_smul, h, inv_smul_smul₀]
rwa [inner_self_ne_zero]
tfae_have 2 → 3 := fun h => h.imp_right fun h' => ⟨_, h'⟩
tfae_have 3 → 1 := by
rintro (rfl | ⟨r, rfl⟩) <;>
simp [inner_smul_right, norm_smul, inner_self_eq_norm_sq_to_K, inner_self_eq_norm_mul_norm,
sq, mul_left_comm]
tfae_have 3 ↔ 4 := by simp only [Submodule.mem_span_singleton, eq_comm]
tfae_finish
/-- If the inner product of two vectors is equal to the product of their norms, then the two vectors
are multiples of each other. One form of the equality case for Cauchy-Schwarz.
Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ‖x‖ * ‖y‖`. -/
theorem norm_inner_eq_norm_iff {x y : E} (hx₀ : x ≠ 0) (hy₀ : y ≠ 0) :
‖⟪x, y⟫‖ = ‖x‖ * ‖y‖ ↔ ∃ r : 𝕜, r ≠ 0 ∧ y = r • x :=
calc
‖⟪x, y⟫‖ = ‖x‖ * ‖y‖ ↔ x = 0 ∨ ∃ r : 𝕜, y = r • x :=
(@norm_inner_eq_norm_tfae 𝕜 _ _ _ _ x y).out 0 2
_ ↔ ∃ r : 𝕜, y = r • x := or_iff_right hx₀
_ ↔ ∃ r : 𝕜, r ≠ 0 ∧ y = r • x :=
⟨fun ⟨r, h⟩ => ⟨r, fun hr₀ => hy₀ <| h.symm ▸ smul_eq_zero.2 <| Or.inl hr₀, h⟩,
fun ⟨r, _hr₀, h⟩ => ⟨r, h⟩⟩
/-- The inner product of two vectors, divided by the product of their
norms, has absolute value 1 if and only if they are nonzero and one is
a multiple of the other. One form of equality case for Cauchy-Schwarz. -/
theorem norm_inner_div_norm_mul_norm_eq_one_iff (x y : E) :
‖⟪x, y⟫ / (‖x‖ * ‖y‖)‖ = 1 ↔ x ≠ 0 ∧ ∃ r : 𝕜, r ≠ 0 ∧ y = r • x := by
constructor
· intro h
have hx₀ : x ≠ 0 := fun h₀ => by simp [h₀] at h
have hy₀ : y ≠ 0 := fun h₀ => by simp [h₀] at h
refine ⟨hx₀, (norm_inner_eq_norm_iff hx₀ hy₀).1 <| eq_of_div_eq_one ?_⟩
simpa using h
· rintro ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩
simp only [norm_div, norm_mul, norm_ofReal, abs_norm]
exact norm_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr
/-- The inner product of two vectors, divided by the product of their
norms, has absolute value 1 if and only if they are nonzero and one is
a multiple of the other. One form of equality case for Cauchy-Schwarz. -/
theorem abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) :
|⟪x, y⟫_ℝ / (‖x‖ * ‖y‖)| = 1 ↔ x ≠ 0 ∧ ∃ r : ℝ, r ≠ 0 ∧ y = r • x :=
@norm_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ _ x y
theorem inner_eq_norm_mul_iff_div {x y : E} (h₀ : x ≠ 0) :
⟪x, y⟫ = (‖x‖ : 𝕜) * ‖y‖ ↔ (‖y‖ / ‖x‖ : 𝕜) • x = y := by
have h₀' := h₀
rw [← norm_ne_zero_iff, Ne, ← @ofReal_eq_zero 𝕜] at h₀'
constructor <;> intro h
· have : x = 0 ∨ y = (⟪x, y⟫ / ⟪x, x⟫ : 𝕜) • x :=
((@norm_inner_eq_norm_tfae 𝕜 _ _ _ _ x y).out 0 1).1 (by simp [h])
rw [this.resolve_left h₀, h]
simp [norm_smul, inner_self_ofReal_norm, mul_div_cancel_right₀ _ h₀']
· conv_lhs => rw [← h, inner_smul_right, inner_self_eq_norm_sq_to_K]
field_simp [sq, mul_left_comm]
/-- If the inner product of two vectors is equal to the product of their norms (i.e.,
`⟪x, y⟫ = ‖x‖ * ‖y‖`), then the two vectors are nonnegative real multiples of each other. One form
of the equality case for Cauchy-Schwarz.
Compare `norm_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ‖x‖ * ‖y‖`. -/
theorem inner_eq_norm_mul_iff {x y : E} :
⟪x, y⟫ = (‖x‖ : 𝕜) * ‖y‖ ↔ (‖y‖ : 𝕜) • x = (‖x‖ : 𝕜) • y := by
rcases eq_or_ne x 0 with (rfl | h₀)
· simp
· rw [inner_eq_norm_mul_iff_div h₀, div_eq_inv_mul, mul_smul, inv_smul_eq_iff₀]
rwa [Ne, ofReal_eq_zero, norm_eq_zero]
/-- If the inner product of two vectors is equal to the product of their norms (i.e.,
`⟪x, y⟫ = ‖x‖ * ‖y‖`), then the two vectors are nonnegative real multiples of each other. One form
of the equality case for Cauchy-Schwarz.
Compare `norm_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ‖x‖ * ‖y‖`. -/
theorem inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ‖x‖ * ‖y‖ ↔ ‖y‖ • x = ‖x‖ • y :=
inner_eq_norm_mul_iff
/-- The inner product of two vectors, divided by the product of their
norms, has value 1 if and only if they are nonzero and one is
a positive multiple of the other. -/
theorem real_inner_div_norm_mul_norm_eq_one_iff (x y : F) :
⟪x, y⟫_ℝ / (‖x‖ * ‖y‖) = 1 ↔ x ≠ 0 ∧ ∃ r : ℝ, 0 < r ∧ y = r • x := by
constructor
· intro h
have hx₀ : x ≠ 0 := fun h₀ => by simp [h₀] at h
have hy₀ : y ≠ 0 := fun h₀ => by simp [h₀] at h
refine ⟨hx₀, ‖y‖ / ‖x‖, div_pos (norm_pos_iff.2 hy₀) (norm_pos_iff.2 hx₀), ?_⟩
exact ((inner_eq_norm_mul_iff_div hx₀).1 (eq_of_div_eq_one h)).symm
· rintro ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩
exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr
/-- The inner product of two vectors, divided by the product of their
norms, has value -1 if and only if they are nonzero and one is
a negative multiple of the other. -/
theorem real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) :
⟪x, y⟫_ℝ / (‖x‖ * ‖y‖) = -1 ↔ x ≠ 0 ∧ ∃ r : ℝ, r < 0 ∧ y = r • x := by
rw [← neg_eq_iff_eq_neg, ← neg_div, ← inner_neg_right, ← norm_neg y,
real_inner_div_norm_mul_norm_eq_one_iff, (@neg_surjective ℝ _).exists]
refine Iff.rfl.and (exists_congr fun r => ?_)
rw [neg_pos, neg_smul, neg_inj]
/-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of
the equality case for Cauchy-Schwarz. -/
theorem inner_eq_one_iff_of_norm_one {x y : E} (hx : ‖x‖ = 1) (hy : ‖y‖ = 1) :
⟪x, y⟫ = 1 ↔ x = y := by
convert inner_eq_norm_mul_iff (𝕜 := 𝕜) (E := E) using 2 <;> simp [hx, hy]
theorem inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ‖x‖ * ‖y‖ ↔ ‖y‖ • x ≠ ‖x‖ • y :=
calc
⟪x, y⟫_ℝ < ‖x‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ ≠ ‖x‖ * ‖y‖ :=
⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩
_ ↔ ‖y‖ • x ≠ ‖x‖ • y := not_congr inner_eq_norm_mul_iff_real
/-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are
distinct. One form of the equality case for Cauchy-Schwarz. -/
theorem inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ‖x‖ = 1) (hy : ‖y‖ = 1) :
⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by convert inner_lt_norm_mul_iff_real (F := F) <;> simp [hx, hy]
/-- The sphere of radius `r = ‖y‖` is tangent to the plane `⟪x, y⟫ = ‖y‖ ^ 2` at `x = y`. -/
theorem eq_of_norm_le_re_inner_eq_norm_sq {x y : E} (hle : ‖x‖ ≤ ‖y‖) (h : re ⟪x, y⟫ = ‖y‖ ^ 2) :
x = y := by
suffices H : re ⟪x - y, x - y⟫ ≤ 0 by rwa [re_inner_self_nonpos, sub_eq_zero] at H
have H₁ : ‖x‖ ^ 2 ≤ ‖y‖ ^ 2 := by gcongr
have H₂ : re ⟪y, x⟫ = ‖y‖ ^ 2 := by rwa [← inner_conj_symm, conj_re]
simpa [inner_sub_left, inner_sub_right, ← norm_sq_eq_re_inner, h, H₂] using H₁
end Norm
section RCLike
local notation "⟪" x ", " y "⟫" => @inner 𝕜 _ _ x y
/-- A field `𝕜` satisfying `RCLike` is itself a `𝕜`-inner product space. -/
instance RCLike.innerProductSpace : InnerProductSpace 𝕜 𝕜 where
inner x y := y * conj x
norm_sq_eq_re_inner x := by simp only [inner, mul_conj, ← ofReal_pow, ofReal_re]
conj_inner_symm x y := by simp only [mul_comm, map_mul, starRingEnd_self_apply]
add_left x y z := by simp only [mul_add, map_add]
smul_left x y z := by simp only [mul_comm (conj z), mul_assoc, smul_eq_mul, map_mul]
@[simp]
theorem RCLike.inner_apply (x y : 𝕜) : ⟪x, y⟫ = y * conj x :=
rfl
/-- A version of `RCLike.inner_apply` that swaps the order of multiplication. -/
theorem RCLike.inner_apply' (x y : 𝕜) : ⟪x, y⟫ = conj x * y := mul_comm _ _
end RCLike
section RCLikeToReal
open scoped InnerProductSpace
variable {G : Type*}
variable (𝕜 E)
variable [SeminormedAddCommGroup E] [InnerProductSpace 𝕜 E]
local notation "⟪" x ", " y "⟫" => @inner 𝕜 _ _ x y
/-- A general inner product implies a real inner product. This is not registered as an instance
since `𝕜` does not appear in the return type `Inner ℝ E`. -/
def Inner.rclikeToReal : Inner ℝ E where inner x y := re ⟪x, y⟫
/-- A general inner product space structure implies a real inner product structure.
This is not registered as an instance since
* `𝕜` does not appear in the return type `InnerProductSpace ℝ E`,
* It is likely to create instance diamonds, as it builds upon the diamond-prone
`NormedSpace.restrictScalars`.
However, it can be used in a proof to obtain a real inner product space structure from a given
`𝕜`-inner product space structure. -/
-- See note [reducible non instances]
abbrev InnerProductSpace.rclikeToReal : InnerProductSpace ℝ E :=
{ Inner.rclikeToReal 𝕜 E,
NormedSpace.restrictScalars ℝ 𝕜
E with
norm_sq_eq_re_inner := norm_sq_eq_re_inner
conj_inner_symm := fun _ _ => inner_re_symm _ _
add_left := fun x y z => by
change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫
simp only [inner_add_left, map_add]
smul_left := fun x y r => by
change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫
simp only [inner_smul_left, conj_ofReal, re_ofReal_mul] }
variable {E}
theorem real_inner_eq_re_inner (x y : E) :
@Inner.inner ℝ E (Inner.rclikeToReal 𝕜 E) x y = re ⟪x, y⟫ :=
rfl
theorem real_inner_I_smul_self (x : E) :
@Inner.inner ℝ E (Inner.rclikeToReal 𝕜 E) x ((I : 𝕜) • x) = 0 := by
simp [real_inner_eq_re_inner 𝕜, inner_smul_right]
/-- A complex inner product implies a real inner product. This cannot be an instance since it
creates a diamond with `PiLp.innerProductSpace` because `re (sum i, inner (x i) (y i))` and
`sum i, re (inner (x i) (y i))` are not defeq. -/
def InnerProductSpace.complexToReal [SeminormedAddCommGroup G] [InnerProductSpace ℂ G] :
InnerProductSpace ℝ G :=
InnerProductSpace.rclikeToReal ℂ G
instance : InnerProductSpace ℝ ℂ := InnerProductSpace.complexToReal
@[simp]
protected theorem Complex.inner (w z : ℂ) : ⟪w, z⟫_ℝ = (z * conj w).re :=
rfl
end RCLikeToReal
/-- An `RCLike` field is a real inner product space. -/
noncomputable instance RCLike.toInnerProductSpaceReal : InnerProductSpace ℝ 𝕜 where
__ := Inner.rclikeToReal 𝕜 𝕜
norm_sq_eq_re_inner := norm_sq_eq_re_inner
conj_inner_symm x y := inner_re_symm ..
add_left x y z :=
show re (_ * _) = re (_ * _) + re (_ * _) by simp only [map_add, mul_re, conj_re, conj_im]; ring
smul_left x y r :=
show re (_ * _) = _ * re (_ * _) by
simp only [mul_re, conj_re, conj_im, conj_trivial, smul_re, smul_im]; ring
-- The instance above does not create diamonds for concrete `𝕜`:
example : (innerProductSpace : InnerProductSpace ℝ ℝ) = RCLike.toInnerProductSpaceReal := rfl
example :
(instInnerProductSpaceRealComplex : InnerProductSpace ℝ ℂ) = RCLike.toInnerProductSpaceReal := rfl
| Mathlib/Analysis/InnerProductSpace/Basic.lean | 1,142 | 1,145 | |
/-
Copyright (c) 2024 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.CategoryTheory.Localization.LocalizerMorphism
import Mathlib.CategoryTheory.HomCongr
/-!
# Bijections between morphisms in two localized categories
Given two localization functors `L₁ : C ⥤ D₁` and `L₂ : C ⥤ D₂` for the same
class of morphisms `W : MorphismProperty C`, we define a bijection
`Localization.homEquiv W L₁ L₂ : (L₁.obj X ⟶ L₁.obj Y) ≃ (L₂.obj X ⟶ L₂.obj Y)`
between the types of morphisms in the two localized categories.
More generally, given a localizer morphism `Φ : LocalizerMorphism W₁ W₂`, we define a map
`Φ.homMap L₁ L₂ : (L₁.obj X ⟶ L₁.obj Y) ⟶ (L₂.obj (Φ.functor.obj X) ⟶ L₂.obj (Φ.functor.obj Y))`.
The definition `Localization.homEquiv` is obtained by applying the construction
to the identity localizer morphism.
-/
namespace CategoryTheory
open Category
variable {C C₁ C₂ C₃ D₁ D₂ D₃ : Type*} [Category C]
[Category C₁] [Category C₂] [Category C₃]
[Category D₁] [Category D₂] [Category D₃]
namespace LocalizerMorphism
variable {W₁ : MorphismProperty C₁} {W₂ : MorphismProperty C₂} {W₃ : MorphismProperty C₃}
(Φ : LocalizerMorphism W₁ W₂) (Ψ : LocalizerMorphism W₂ W₃)
(L₁ : C₁ ⥤ D₁) [L₁.IsLocalization W₁]
(L₂ : C₂ ⥤ D₂) [L₂.IsLocalization W₂]
(L₃ : C₃ ⥤ D₃) [L₃.IsLocalization W₃]
{X Y Z : C₁}
/-- If `Φ : LocalizerMorphism W₁ W₂` is a morphism of localizers, `L₁` and `L₂`
are localization functors for `W₁` and `W₂`, then this is the induced map
`(L₁.obj X ⟶ L₁.obj Y) ⟶ (L₂.obj (Φ.functor.obj X) ⟶ L₂.obj (Φ.functor.obj Y))`
for all objects `X` and `Y`. -/
noncomputable def homMap (f : L₁.obj X ⟶ L₁.obj Y) :
L₂.obj (Φ.functor.obj X) ⟶ L₂.obj (Φ.functor.obj Y) :=
Iso.homCongr ((CatCommSq.iso _ _ _ _).symm.app _) ((CatCommSq.iso _ _ _ _).symm.app _)
((Φ.localizedFunctor L₁ L₂).map f)
@[simp]
lemma homMap_map (f : X ⟶ Y) :
Φ.homMap L₁ L₂ (L₁.map f) = L₂.map (Φ.functor.map f) := by
dsimp [homMap]
erw [← NatTrans.naturality_assoc]
simp
variable (X) in
@[simp]
lemma homMap_id :
Φ.homMap L₁ L₂ (𝟙 (L₁.obj X)) = 𝟙 (L₂.obj (Φ.functor.obj X)) := by
simpa using Φ.homMap_map L₁ L₂ (𝟙 X)
@[reassoc]
lemma homMap_comp (f : L₁.obj X ⟶ L₁.obj Y) (g : L₁.obj Y ⟶ L₁.obj Z) :
Φ.homMap L₁ L₂ (f ≫ g) = Φ.homMap L₁ L₂ f ≫ Φ.homMap L₁ L₂ g := by
simp [homMap]
@[reassoc]
lemma homMap_apply (G : D₁ ⥤ D₂) (e : Φ.functor ⋙ L₂ ≅ L₁ ⋙ G) (f : L₁.obj X ⟶ L₁.obj Y) :
Φ.homMap L₁ L₂ f = e.hom.app X ≫ G.map f ≫ e.inv.app Y := by
let G' := Φ.localizedFunctor L₁ L₂
let e' := CatCommSq.iso Φ.functor L₁ L₂ G'
change e'.hom.app X ≫ G'.map f ≫ e'.inv.app Y = _
letI : Localization.Lifting L₁ W₁ (Φ.functor ⋙ L₂) G := ⟨e.symm⟩
let α : G' ≅ G := Localization.liftNatIso L₁ W₁ (L₁ ⋙ G') (Φ.functor ⋙ L₂) _ _ e'.symm
have : e = e' ≪≫ isoWhiskerLeft _ α := by
ext X
dsimp [α]
rw [Localization.liftNatTrans_app]
erw [id_comp]
rw [Iso.hom_inv_id_app_assoc]
rfl
simp [this]
| @[simp]
lemma id_homMap (f : L₁.obj X ⟶ L₁.obj Y) :
(id W₁).homMap L₁ L₁ f = f := by
simpa using (id W₁).homMap_apply L₁ L₁ (𝟭 D₁) (Iso.refl _) f
| Mathlib/CategoryTheory/Localization/HomEquiv.lean | 86 | 89 |
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import Mathlib.Order.PropInstances
import Mathlib.Order.GaloisConnection.Defs
/-!
# Heyting algebras
This file defines Heyting, co-Heyting and bi-Heyting algebras.
A Heyting algebra is a bounded distributive lattice with an implication operation `⇨` such that
`a ≤ b ⇨ c ↔ a ⊓ b ≤ c`. It also comes with a pseudo-complement `ᶜ`, such that `aᶜ = a ⇨ ⊥`.
Co-Heyting algebras are dual to Heyting algebras. They have a difference `\` and a negation `¬`
such that `a \ b ≤ c ↔ a ≤ b ⊔ c` and `¬a = ⊤ \ a`.
Bi-Heyting algebras are Heyting algebras that are also co-Heyting algebras.
From a logic standpoint, Heyting algebras precisely model intuitionistic logic, whereas boolean
algebras model classical logic.
Heyting algebras are the order theoretic equivalent of cartesian-closed categories.
## Main declarations
* `GeneralizedHeytingAlgebra`: Heyting algebra without a top element (nor negation).
* `GeneralizedCoheytingAlgebra`: Co-Heyting algebra without a bottom element (nor complement).
* `HeytingAlgebra`: Heyting algebra.
* `CoheytingAlgebra`: Co-Heyting algebra.
* `BiheytingAlgebra`: bi-Heyting algebra.
## References
* [Francis Borceux, *Handbook of Categorical Algebra III*][borceux-vol3]
## Tags
Heyting, Brouwer, algebra, implication, negation, intuitionistic
-/
assert_not_exists RelIso
open Function OrderDual
universe u
variable {ι α β : Type*}
/-! ### Notation -/
section
variable (α β)
instance Prod.instHImp [HImp α] [HImp β] : HImp (α × β) :=
⟨fun a b => (a.1 ⇨ b.1, a.2 ⇨ b.2)⟩
instance Prod.instHNot [HNot α] [HNot β] : HNot (α × β) :=
⟨fun a => (¬a.1, ¬a.2)⟩
instance Prod.instSDiff [SDiff α] [SDiff β] : SDiff (α × β) :=
⟨fun a b => (a.1 \ b.1, a.2 \ b.2)⟩
instance Prod.instHasCompl [HasCompl α] [HasCompl β] : HasCompl (α × β) :=
⟨fun a => (a.1ᶜ, a.2ᶜ)⟩
end
@[simp]
theorem fst_himp [HImp α] [HImp β] (a b : α × β) : (a ⇨ b).1 = a.1 ⇨ b.1 :=
rfl
@[simp]
theorem snd_himp [HImp α] [HImp β] (a b : α × β) : (a ⇨ b).2 = a.2 ⇨ b.2 :=
rfl
@[simp]
theorem fst_hnot [HNot α] [HNot β] (a : α × β) : (¬a).1 = ¬a.1 :=
rfl
@[simp]
theorem snd_hnot [HNot α] [HNot β] (a : α × β) : (¬a).2 = ¬a.2 :=
rfl
@[simp]
theorem fst_sdiff [SDiff α] [SDiff β] (a b : α × β) : (a \ b).1 = a.1 \ b.1 :=
rfl
@[simp]
theorem snd_sdiff [SDiff α] [SDiff β] (a b : α × β) : (a \ b).2 = a.2 \ b.2 :=
rfl
@[simp]
theorem fst_compl [HasCompl α] [HasCompl β] (a : α × β) : aᶜ.1 = a.1ᶜ :=
rfl
@[simp]
theorem snd_compl [HasCompl α] [HasCompl β] (a : α × β) : aᶜ.2 = a.2ᶜ :=
rfl
namespace Pi
variable {π : ι → Type*}
instance [∀ i, HImp (π i)] : HImp (∀ i, π i) :=
⟨fun a b i => a i ⇨ b i⟩
instance [∀ i, HNot (π i)] : HNot (∀ i, π i) :=
⟨fun a i => ¬a i⟩
theorem himp_def [∀ i, HImp (π i)] (a b : ∀ i, π i) : a ⇨ b = fun i => a i ⇨ b i :=
rfl
theorem hnot_def [∀ i, HNot (π i)] (a : ∀ i, π i) : ¬a = fun i => ¬a i :=
rfl
@[simp]
theorem himp_apply [∀ i, HImp (π i)] (a b : ∀ i, π i) (i : ι) : (a ⇨ b) i = a i ⇨ b i :=
rfl
@[simp]
theorem hnot_apply [∀ i, HNot (π i)] (a : ∀ i, π i) (i : ι) : (¬a) i = ¬a i :=
rfl
end Pi
/-- A generalized Heyting algebra is a lattice with an additional binary operation `⇨` called
Heyting implication such that `(a ⇨ ·)` is right adjoint to `(a ⊓ ·)`.
This generalizes `HeytingAlgebra` by not requiring a bottom element. -/
class GeneralizedHeytingAlgebra (α : Type*) extends Lattice α, OrderTop α, HImp α where
/-- `(a ⇨ ·)` is right adjoint to `(a ⊓ ·)` -/
le_himp_iff (a b c : α) : a ≤ b ⇨ c ↔ a ⊓ b ≤ c
/-- A generalized co-Heyting algebra is a lattice with an additional binary
difference operation `\` such that `(· \ a)` is left adjoint to `(· ⊔ a)`.
This generalizes `CoheytingAlgebra` by not requiring a top element. -/
class GeneralizedCoheytingAlgebra (α : Type*) extends Lattice α, OrderBot α, SDiff α where
/-- `(· \ a)` is left adjoint to `(· ⊔ a)` -/
sdiff_le_iff (a b c : α) : a \ b ≤ c ↔ a ≤ b ⊔ c
/-- A Heyting algebra is a bounded lattice with an additional binary operation `⇨` called Heyting
implication such that `(a ⇨ ·)` is right adjoint to `(a ⊓ ·)`. -/
class HeytingAlgebra (α : Type*) extends GeneralizedHeytingAlgebra α, OrderBot α, HasCompl α where
/-- `aᶜ` is defined as `a ⇨ ⊥` -/
himp_bot (a : α) : a ⇨ ⊥ = aᶜ
/-- A co-Heyting algebra is a bounded lattice with an additional binary difference operation `\`
such that `(· \ a)` is left adjoint to `(· ⊔ a)`. -/
class CoheytingAlgebra (α : Type*) extends GeneralizedCoheytingAlgebra α, OrderTop α, HNot α where
/-- `⊤ \ a` is `¬a` -/
top_sdiff (a : α) : ⊤ \ a = ¬a
/-- A bi-Heyting algebra is a Heyting algebra that is also a co-Heyting algebra. -/
class BiheytingAlgebra (α : Type*) extends HeytingAlgebra α, SDiff α, HNot α where
/-- `(· \ a)` is left adjoint to `(· ⊔ a)` -/
sdiff_le_iff (a b c : α) : a \ b ≤ c ↔ a ≤ b ⊔ c
/-- `⊤ \ a` is `¬a` -/
top_sdiff (a : α) : ⊤ \ a = ¬a
-- See note [lower instance priority]
attribute [instance 100] GeneralizedHeytingAlgebra.toOrderTop
attribute [instance 100] GeneralizedCoheytingAlgebra.toOrderBot
-- See note [lower instance priority]
instance (priority := 100) HeytingAlgebra.toBoundedOrder [HeytingAlgebra α] : BoundedOrder α :=
{ bot_le := ‹HeytingAlgebra α›.bot_le }
-- See note [lower instance priority]
instance (priority := 100) CoheytingAlgebra.toBoundedOrder [CoheytingAlgebra α] : BoundedOrder α :=
{ ‹CoheytingAlgebra α› with }
-- See note [lower instance priority]
instance (priority := 100) BiheytingAlgebra.toCoheytingAlgebra [BiheytingAlgebra α] :
CoheytingAlgebra α :=
{ ‹BiheytingAlgebra α› with }
-- See note [reducible non-instances]
/-- Construct a Heyting algebra from the lattice structure and Heyting implication alone. -/
abbrev HeytingAlgebra.ofHImp [DistribLattice α] [BoundedOrder α] (himp : α → α → α)
(le_himp_iff : ∀ a b c, a ≤ himp b c ↔ a ⊓ b ≤ c) : HeytingAlgebra α :=
{ ‹DistribLattice α›, ‹BoundedOrder α› with
himp,
compl := fun a => himp a ⊥,
le_himp_iff,
himp_bot := fun _ => rfl }
-- See note [reducible non-instances]
/-- Construct a Heyting algebra from the lattice structure and complement operator alone. -/
abbrev HeytingAlgebra.ofCompl [DistribLattice α] [BoundedOrder α] (compl : α → α)
(le_himp_iff : ∀ a b c, a ≤ compl b ⊔ c ↔ a ⊓ b ≤ c) : HeytingAlgebra α where
himp := (compl · ⊔ ·)
compl := compl
le_himp_iff := le_himp_iff
himp_bot _ := sup_bot_eq _
-- See note [reducible non-instances]
/-- Construct a co-Heyting algebra from the lattice structure and the difference alone. -/
abbrev CoheytingAlgebra.ofSDiff [DistribLattice α] [BoundedOrder α] (sdiff : α → α → α)
(sdiff_le_iff : ∀ a b c, sdiff a b ≤ c ↔ a ≤ b ⊔ c) : CoheytingAlgebra α :=
{ ‹DistribLattice α›, ‹BoundedOrder α› with
sdiff,
hnot := fun a => sdiff ⊤ a,
sdiff_le_iff,
top_sdiff := fun _ => rfl }
-- See note [reducible non-instances]
/-- Construct a co-Heyting algebra from the difference and Heyting negation alone. -/
abbrev CoheytingAlgebra.ofHNot [DistribLattice α] [BoundedOrder α] (hnot : α → α)
(sdiff_le_iff : ∀ a b c, a ⊓ hnot b ≤ c ↔ a ≤ b ⊔ c) : CoheytingAlgebra α where
sdiff a b := a ⊓ hnot b
hnot := hnot
sdiff_le_iff := sdiff_le_iff
top_sdiff _ := top_inf_eq _
/-! In this section, we'll give interpretations of these results in the Heyting algebra model of
intuitionistic logic,- where `≤` can be interpreted as "validates", `⇨` as "implies", `⊓` as "and",
`⊔` as "or", `⊥` as "false" and `⊤` as "true". Note that we confuse `→` and `⊢` because those are
the same in this logic.
See also `Prop.heytingAlgebra`. -/
section GeneralizedHeytingAlgebra
variable [GeneralizedHeytingAlgebra α] {a b c d : α}
/-- `p → q → r ↔ p ∧ q → r` -/
@[simp]
theorem le_himp_iff : a ≤ b ⇨ c ↔ a ⊓ b ≤ c :=
GeneralizedHeytingAlgebra.le_himp_iff _ _ _
/-- `p → q → r ↔ q ∧ p → r` -/
theorem le_himp_iff' : a ≤ b ⇨ c ↔ b ⊓ a ≤ c := by rw [le_himp_iff, inf_comm]
/-- `p → q → r ↔ q → p → r` -/
theorem le_himp_comm : a ≤ b ⇨ c ↔ b ≤ a ⇨ c := by rw [le_himp_iff, le_himp_iff']
/-- `p → q → p` -/
theorem le_himp : a ≤ b ⇨ a :=
le_himp_iff.2 inf_le_left
/-- `p → p → q ↔ p → q` -/
theorem le_himp_iff_left : a ≤ a ⇨ b ↔ a ≤ b := by rw [le_himp_iff, inf_idem]
/-- `p → p` -/
@[simp]
theorem himp_self : a ⇨ a = ⊤ :=
top_le_iff.1 <| le_himp_iff.2 inf_le_right
/-- `(p → q) ∧ p → q` -/
theorem himp_inf_le : (a ⇨ b) ⊓ a ≤ b :=
le_himp_iff.1 le_rfl
/-- `p ∧ (p → q) → q` -/
theorem inf_himp_le : a ⊓ (a ⇨ b) ≤ b := by rw [inf_comm, ← le_himp_iff]
/-- `p ∧ (p → q) ↔ p ∧ q` -/
@[simp]
theorem inf_himp (a b : α) : a ⊓ (a ⇨ b) = a ⊓ b :=
le_antisymm (le_inf inf_le_left <| by rw [inf_comm, ← le_himp_iff]) <| inf_le_inf_left _ le_himp
/-- `(p → q) ∧ p ↔ q ∧ p` -/
@[simp]
theorem himp_inf_self (a b : α) : (a ⇨ b) ⊓ a = b ⊓ a := by rw [inf_comm, inf_himp, inf_comm]
/-- The **deduction theorem** in the Heyting algebra model of intuitionistic logic:
an implication holds iff the conclusion follows from the hypothesis. -/
@[simp]
theorem himp_eq_top_iff : a ⇨ b = ⊤ ↔ a ≤ b := by rw [← top_le_iff, le_himp_iff, top_inf_eq]
/-- `p → true`, `true → p ↔ p` -/
@[simp]
theorem himp_top : a ⇨ ⊤ = ⊤ :=
himp_eq_top_iff.2 le_top
@[simp]
theorem top_himp : ⊤ ⇨ a = a :=
eq_of_forall_le_iff fun b => by rw [le_himp_iff, inf_top_eq]
/-- `p → q → r ↔ p ∧ q → r` -/
theorem himp_himp (a b c : α) : a ⇨ b ⇨ c = a ⊓ b ⇨ c :=
eq_of_forall_le_iff fun d => by simp_rw [le_himp_iff, inf_assoc]
/-- `(q → r) → (p → q) → q → r` -/
theorem himp_le_himp_himp_himp : b ⇨ c ≤ (a ⇨ b) ⇨ a ⇨ c := by
rw [le_himp_iff, le_himp_iff, inf_assoc, himp_inf_self, ← inf_assoc, himp_inf_self, inf_assoc]
exact inf_le_left
@[simp]
theorem himp_inf_himp_inf_le : (b ⇨ c) ⊓ (a ⇨ b) ⊓ a ≤ c := by
simpa using @himp_le_himp_himp_himp
/-- `p → q → r ↔ q → p → r` -/
theorem himp_left_comm (a b c : α) : a ⇨ b ⇨ c = b ⇨ a ⇨ c := by simp_rw [himp_himp, inf_comm]
@[simp]
theorem himp_idem : b ⇨ b ⇨ a = b ⇨ a := by rw [himp_himp, inf_idem]
theorem himp_inf_distrib (a b c : α) : a ⇨ b ⊓ c = (a ⇨ b) ⊓ (a ⇨ c) :=
eq_of_forall_le_iff fun d => by simp_rw [le_himp_iff, le_inf_iff, le_himp_iff]
theorem sup_himp_distrib (a b c : α) : a ⊔ b ⇨ c = (a ⇨ c) ⊓ (b ⇨ c) :=
eq_of_forall_le_iff fun d => by
rw [le_inf_iff, le_himp_comm, sup_le_iff]
simp_rw [le_himp_comm]
theorem himp_le_himp_left (h : a ≤ b) : c ⇨ a ≤ c ⇨ b :=
le_himp_iff.2 <| himp_inf_le.trans h
theorem himp_le_himp_right (h : a ≤ b) : b ⇨ c ≤ a ⇨ c :=
le_himp_iff.2 <| (inf_le_inf_left _ h).trans himp_inf_le
theorem himp_le_himp (hab : a ≤ b) (hcd : c ≤ d) : b ⇨ c ≤ a ⇨ d :=
| (himp_le_himp_right hab).trans <| himp_le_himp_left hcd
| Mathlib/Order/Heyting/Basic.lean | 316 | 317 |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.FinsetOps
import Mathlib.Data.Multiset.Fold
/-!
# Lattice operations on multisets
-/
namespace Multiset
variable {α : Type*}
/-! ### sup -/
section Sup
-- can be defined with just `[Bot α]` where some lemmas hold without requiring `[OrderBot α]`
variable [SemilatticeSup α] [OrderBot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : Multiset α) : α :=
s.fold (· ⊔ ·) ⊥
@[simp]
theorem sup_coe (l : List α) : sup (l : Multiset α) = l.foldr (· ⊔ ·) ⊥ :=
rfl
@[simp]
theorem sup_zero : (0 : Multiset α).sup = ⊥ :=
fold_zero _ _
@[simp]
theorem sup_cons (a : α) (s : Multiset α) : (a ::ₘ s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp]
theorem sup_singleton {a : α} : ({a} : Multiset α).sup = a := sup_bot_eq _
@[simp]
theorem sup_add (s₁ s₂ : Multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
Eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
@[simp]
theorem sup_le {s : Multiset α} {a : α} : s.sup ≤ a ↔ ∀ b ∈ s, b ≤ a :=
Multiset.induction_on s (by simp)
(by simp +contextual [or_imp, forall_and])
theorem le_sup {s : Multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 le_rfl _ h
@[gcongr]
theorem sup_mono {s₁ s₂ : Multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 fun _ hb => le_sup (h hb)
variable [DecidableEq α]
@[simp]
theorem sup_dedup (s : Multiset α) : (dedup s).sup = s.sup :=
fold_dedup_idem _ _ _
@[simp]
theorem sup_ndunion (s₁ s₂ : Multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by
rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_add]; simp
@[simp]
theorem sup_union (s₁ s₂ : Multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by
rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_add]; simp
@[simp]
theorem sup_ndinsert (a : α) (s : Multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by
rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_cons]; simp
theorem nodup_sup_iff {α : Type*} [DecidableEq α] {m : Multiset (Multiset α)} :
m.sup.Nodup ↔ ∀ a : Multiset α, a ∈ m → a.Nodup := by
induction m using Multiset.induction_on with
| empty => simp
| cons _ _ h => simp [h]
end Sup
/-! ### inf -/
section Inf
-- can be defined with just `[Top α]` where some lemmas hold without requiring `[OrderTop α]`
variable [SemilatticeInf α] [OrderTop α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : Multiset α) : α :=
s.fold (· ⊓ ·) ⊤
@[simp]
theorem inf_coe (l : List α) : inf (l : Multiset α) = l.foldr (· ⊓ ·) ⊤ :=
rfl
@[simp]
theorem inf_zero : (0 : Multiset α).inf = ⊤ :=
fold_zero _ _
@[simp]
theorem inf_cons (a : α) (s : Multiset α) : (a ::ₘ s).inf = a ⊓ s.inf :=
fold_cons_left _ _ _ _
@[simp]
theorem inf_singleton {a : α} : ({a} : Multiset α).inf = a := inf_top_eq _
@[simp]
theorem inf_add (s₁ s₂ : Multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
Eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
@[simp]
theorem le_inf {s : Multiset α} {a : α} : a ≤ s.inf ↔ ∀ b ∈ s, a ≤ b :=
Multiset.induction_on s (by simp)
(by simp +contextual [or_imp, forall_and])
theorem inf_le {s : Multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 le_rfl _ h
@[gcongr]
theorem inf_mono {s₁ s₂ : Multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 fun _ hb => inf_le (h hb)
variable [DecidableEq α]
@[simp]
theorem inf_dedup (s : Multiset α) : (dedup s).inf = s.inf :=
fold_dedup_idem _ _ _
@[simp]
theorem inf_ndunion (s₁ s₂ : Multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by
rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_add]; simp
@[simp]
theorem inf_union (s₁ s₂ : Multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by
rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_add]; simp
@[simp]
theorem inf_ndinsert (a : α) (s : Multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by
rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_cons]; simp
end Inf
end Multiset
| Mathlib/Data/Multiset/Lattice.lean | 173 | 174 | |
/-
Copyright (c) 2020 Jalex Stark. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jalex Stark, Kim Morrison, Eric Wieser, Oliver Nash, Wen Yang
-/
import Mathlib.Data.Matrix.Basic
/-!
# Matrices with a single non-zero element.
This file provides `Matrix.stdBasisMatrix`. The matrix `Matrix.stdBasisMatrix i j c` has `c`
at position `(i, j)`, and zeroes elsewhere.
-/
assert_not_exists Matrix.trace
variable {l m n o : Type*}
variable {R α β : Type*}
namespace Matrix
variable [DecidableEq l] [DecidableEq m] [DecidableEq n] [DecidableEq o]
section Zero
variable [Zero α]
/-- `stdBasisMatrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column,
and zeroes elsewhere.
-/
def stdBasisMatrix (i : m) (j : n) (a : α) : Matrix m n α :=
of <| fun i' j' => if i = i' ∧ j = j' then a else 0
theorem stdBasisMatrix_eq_of_single_single (i : m) (j : n) (a : α) :
stdBasisMatrix i j a = Matrix.of (Pi.single i (Pi.single j a)) := by
ext a b
unfold stdBasisMatrix
by_cases hi : i = a <;> by_cases hj : j = b <;> simp [*]
@[simp]
theorem of_symm_stdBasisMatrix (i : m) (j : n) (a : α) :
of.symm (stdBasisMatrix i j a) = Pi.single i (Pi.single j a) :=
congr_arg of.symm <| stdBasisMatrix_eq_of_single_single i j a
@[simp]
theorem smul_stdBasisMatrix [SMulZeroClass R α] (r : R) (i : m) (j : n) (a : α) :
r • stdBasisMatrix i j a = stdBasisMatrix i j (r • a) := by
unfold stdBasisMatrix
ext
simp [smul_ite]
@[simp]
theorem stdBasisMatrix_zero (i : m) (j : n) : stdBasisMatrix i j (0 : α) = 0 := by
unfold stdBasisMatrix
ext
simp
@[simp]
lemma transpose_stdBasisMatrix (i : m) (j : n) (a : α) :
(stdBasisMatrix i j a)ᵀ = stdBasisMatrix j i a := by
aesop (add unsafe unfold stdBasisMatrix)
@[simp]
lemma map_stdBasisMatrix (i : m) (j : n) (a : α) {β : Type*} [Zero β]
{F : Type*} [FunLike F α β] [ZeroHomClass F α β] (f : F) :
(stdBasisMatrix i j a).map f = stdBasisMatrix i j (f a) := by
aesop (add unsafe unfold stdBasisMatrix)
end Zero
theorem stdBasisMatrix_add [AddZeroClass α] (i : m) (j : n) (a b : α) :
stdBasisMatrix i j (a + b) = stdBasisMatrix i j a + stdBasisMatrix i j b := by
ext
simp only [stdBasisMatrix, of_apply]
split_ifs with h <;> simp [h]
theorem mulVec_stdBasisMatrix [NonUnitalNonAssocSemiring α] [Fintype m]
(i : n) (j : m) (c : α) (x : m → α) :
mulVec (stdBasisMatrix i j c) x = Function.update (0 : n → α) i (c * x j) := by
ext i'
simp [stdBasisMatrix, mulVec, dotProduct]
rcases eq_or_ne i i' with rfl|h
· simp
simp [h, h.symm]
theorem matrix_eq_sum_stdBasisMatrix [AddCommMonoid α] [Fintype m] [Fintype n] (x : Matrix m n α) :
x = ∑ i : m, ∑ j : n, stdBasisMatrix i j (x i j) := by
ext i j
rw [← Fintype.sum_prod_type']
simp [stdBasisMatrix, Matrix.sum_apply, Matrix.of_apply, ← Prod.mk_inj]
theorem stdBasisMatrix_eq_single_vecMulVec_single [MulZeroOneClass α] (i : m) (j : n) :
stdBasisMatrix i j (1 : α) = vecMulVec (Pi.single i 1) (Pi.single j 1) := by
ext i' j'
simp [-mul_ite, stdBasisMatrix, vecMulVec, ite_and, Pi.single_apply, eq_comm]
-- todo: the old proof used fintypes, I don't know `Finsupp` but this feels generalizable
@[elab_as_elim]
protected theorem induction_on'
[AddCommMonoid α] [Finite m] [Finite n] {P : Matrix m n α → Prop} (M : Matrix m n α)
(h_zero : P 0) (h_add : ∀ p q, P p → P q → P (p + q))
(h_std_basis : ∀ (i : m) (j : n) (x : α), P (stdBasisMatrix i j x)) : P M := by
cases nonempty_fintype m; cases nonempty_fintype n
rw [matrix_eq_sum_stdBasisMatrix M, ← Finset.sum_product']
apply Finset.sum_induction _ _ h_add h_zero
· intros
apply h_std_basis
@[elab_as_elim]
protected theorem induction_on
[AddCommMonoid α] [Finite m] [Finite n] [Nonempty m] [Nonempty n]
{P : Matrix m n α → Prop} (M : Matrix m n α) (h_add : ∀ p q, P p → P q → P (p + q))
(h_std_basis : ∀ i j x, P (stdBasisMatrix i j x)) : P M :=
Matrix.induction_on' M
(by
inhabit m
inhabit n
simpa using h_std_basis default default 0)
h_add h_std_basis
/-- `Matrix.stdBasisMatrix` as a bundled additive map. -/
@[simps]
def stdBasisMatrixAddMonoidHom [AddCommMonoid α] (i : m) (j : n) : α →+ Matrix m n α where
toFun := stdBasisMatrix i j
map_zero' := stdBasisMatrix_zero _ _
map_add' _ _ := stdBasisMatrix_add _ _ _ _
variable (R)
/-- `Matrix.stdBasisMatrix` as a bundled linear map. -/
@[simps!]
def stdBasisMatrixLinearMap [Semiring R] [AddCommMonoid α] [Module R α] (i : m) (j : n) :
α →ₗ[R] Matrix m n α where
__ := stdBasisMatrixAddMonoidHom i j
map_smul' _ _:= smul_stdBasisMatrix _ _ _ _ |>.symm
section ext
/-- Additive maps from finite matrices are equal if they agree on the standard basis.
See note [partially-applied ext lemmas]. -/
@[local ext]
theorem ext_addMonoidHom
[Finite m] [Finite n] [AddCommMonoid α] [AddCommMonoid β] ⦃f g : Matrix m n α →+ β⦄
(h : ∀ i j, f.comp (stdBasisMatrixAddMonoidHom i j) = g.comp (stdBasisMatrixAddMonoidHom i j)) :
f = g := by
cases nonempty_fintype m
cases nonempty_fintype n
ext x
rw [matrix_eq_sum_stdBasisMatrix x]
simp_rw [map_sum]
congr! 2
exact DFunLike.congr_fun (h _ _) _
/-- Linear maps from finite matrices are equal if they agree on the standard basis.
See note [partially-applied ext lemmas]. -/
@[local ext]
theorem ext_linearMap
[Finite m] [Finite n] [Semiring R] [AddCommMonoid α] [AddCommMonoid β] [Module R α] [Module R β]
⦃f g : Matrix m n α →ₗ[R] β⦄
(h : ∀ i j, f ∘ₗ stdBasisMatrixLinearMap R i j = g ∘ₗ stdBasisMatrixLinearMap R i j) :
f = g :=
LinearMap.toAddMonoidHom_injective <| ext_addMonoidHom fun i j =>
congrArg LinearMap.toAddMonoidHom <| h i j
end ext
namespace StdBasisMatrix
section
variable [Zero α] (i : m) (j : n) (c : α) (i' : m) (j' : n)
@[simp]
theorem apply_same : stdBasisMatrix i j c i j = c :=
if_pos (And.intro rfl rfl)
@[simp]
theorem apply_of_ne (h : ¬(i = i' ∧ j = j')) : stdBasisMatrix i j c i' j' = 0 := by
simp only [stdBasisMatrix, and_imp, ite_eq_right_iff, of_apply]
tauto
@[simp]
theorem apply_of_row_ne {i i' : m} (hi : i ≠ i') (j j' : n) (a : α) :
stdBasisMatrix i j a i' j' = 0 := by simp [hi]
@[simp]
theorem apply_of_col_ne (i i' : m) {j j' : n} (hj : j ≠ j') (a : α) :
stdBasisMatrix i j a i' j' = 0 := by simp [hj]
end
section
variable [Zero α] (i j : n) (c : α)
@[simp]
theorem diag_zero (h : j ≠ i) : diag (stdBasisMatrix i j c) = 0 :=
funext fun _ => if_neg fun ⟨e₁, e₂⟩ => h (e₂.trans e₁.symm)
@[simp]
theorem diag_same : diag (stdBasisMatrix i i c) = Pi.single i c := by
ext j
by_cases hij : i = j <;> (try rw [hij]) <;> simp [hij]
end
section mul
variable [Fintype m] [NonUnitalNonAssocSemiring α] (c : α)
omit [DecidableEq n] in
@[simp]
theorem mul_left_apply_same (i : l) (j : m) (b : n) (M : Matrix m n α) :
(stdBasisMatrix i j c * M) i b = c * M j b := by simp [mul_apply, stdBasisMatrix]
omit [DecidableEq l] in
@[simp]
theorem mul_right_apply_same (i : m) (j : n) (a : l) (M : Matrix l m α) :
(M * stdBasisMatrix i j c) a j = M a i * c := by simp [mul_apply, stdBasisMatrix, mul_comm]
omit [DecidableEq n] in
@[simp]
theorem mul_left_apply_of_ne (i : l) (j : m) (a : l) (b : n) (h : a ≠ i) (M : Matrix m n α) :
(stdBasisMatrix i j c * M) a b = 0 := by simp [mul_apply, h.symm]
omit [DecidableEq l] in
@[simp]
theorem mul_right_apply_of_ne (i : m) (j : n) (a : l) (b : n) (hbj : b ≠ j) (M : Matrix l m α) :
(M * stdBasisMatrix i j c) a b = 0 := by simp [mul_apply, hbj.symm]
@[simp]
theorem mul_same (i : l) (j : m) (k : n) (d : α) :
stdBasisMatrix i j c * stdBasisMatrix j k d = stdBasisMatrix i k (c * d) := by
ext a b
simp only [mul_apply, stdBasisMatrix, boole_mul]
by_cases h₁ : i = a <;> by_cases h₂ : k = b <;> simp [h₁, h₂]
@[simp]
theorem stdBasisMatrix_mul_mul_stdBasisMatrix [Fintype n]
(i : l) (i' : m) (j' : n) (j : o) (a : α) (x : Matrix m n α) (b : α) :
stdBasisMatrix i i' a * x * stdBasisMatrix j' j b = stdBasisMatrix i j (a * x i' j' * b) := by
ext i'' j''
simp only [mul_apply, stdBasisMatrix, boole_mul]
by_cases h₁ : i = i'' <;> by_cases h₂ : j = j'' <;> simp [h₁, h₂]
@[simp]
theorem mul_of_ne (i : l) (j k : m) {l : n} (h : j ≠ k) (d : α) :
stdBasisMatrix i j c * stdBasisMatrix k l d = 0 := by
ext a b
simp only [mul_apply, boole_mul, stdBasisMatrix, of_apply]
by_cases h₁ : i = a
· simp [h₁, h, Finset.sum_eq_zero]
· simp [h₁]
end mul
end StdBasisMatrix
section Commute
variable [Fintype n] [Semiring α]
theorem row_eq_zero_of_commute_stdBasisMatrix {i j k : n} {M : Matrix n n α}
(hM : Commute (stdBasisMatrix i j 1) M) (hkj : k ≠ j) : M j k = 0 := by
have := ext_iff.mpr hM i k
aesop
|
theorem col_eq_zero_of_commute_stdBasisMatrix {i j k : n} {M : Matrix n n α}
(hM : Commute (stdBasisMatrix i j 1) M) (hki : k ≠ i) : M k i = 0 := by
have := ext_iff.mpr hM k j
aesop
| Mathlib/Data/Matrix/Basis.lean | 265 | 269 |
/-
Copyright (c) 2020 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Kim Morrison
-/
import Mathlib.Algebra.Category.Ring.Colimits
import Mathlib.Algebra.Category.Ring.Instances
import Mathlib.Algebra.Category.Ring.Limits
import Mathlib.Algebra.Ring.Subring.Basic
import Mathlib.RingTheory.Localization.AtPrime
import Mathlib.RingTheory.Spectrum.Prime.Topology
import Mathlib.Topology.Sheaves.LocalPredicate
/-!
# The structure sheaf on `PrimeSpectrum R`.
We define the structure sheaf on `TopCat.of (PrimeSpectrum R)`, for a commutative ring `R` and prove
basic properties about it. We define this as a subsheaf of the sheaf of dependent functions into the
localizations, cut out by the condition that the function must be locally equal to a ratio of
elements of `R`.
Because the condition "is equal to a fraction" passes to smaller open subsets,
the subset of functions satisfying this condition is automatically a subpresheaf.
Because the condition "is locally equal to a fraction" is local,
it is also a subsheaf.
(It may be helpful to refer back to `Mathlib/Topology/Sheaves/SheafOfFunctions.lean`,
where we show that dependent functions into any type family form a sheaf,
and also `Mathlib/Topology/Sheaves/LocalPredicate.lean`, where we characterise the predicates
which pick out sub-presheaves and sub-sheaves of these sheaves.)
We also set up the ring structure, obtaining
`structureSheaf : Sheaf CommRingCat (PrimeSpectrum.Top R)`.
We then construct two basic isomorphisms, relating the structure sheaf to the underlying ring `R`.
First, `StructureSheaf.stalkIso` gives an isomorphism between the stalk of the structure sheaf
at a point `p` and the localization of `R` at the prime ideal `p`. Second,
`StructureSheaf.basicOpenIso` gives an isomorphism between the structure sheaf on `basicOpen f`
and the localization of `R` at the submonoid of powers of `f`.
## References
* [Robin Hartshorne, *Algebraic Geometry*][Har77]
-/
universe u
noncomputable section
variable (R : Type u) [CommRing R]
open TopCat
open TopologicalSpace
open CategoryTheory
open Opposite
namespace AlgebraicGeometry
/-- The prime spectrum, just as a topological space.
-/
def PrimeSpectrum.Top : TopCat :=
TopCat.of (PrimeSpectrum R)
namespace StructureSheaf
/-- The type family over `PrimeSpectrum R` consisting of the localization over each point.
-/
def Localizations (P : PrimeSpectrum.Top R) : Type u :=
Localization.AtPrime P.asIdeal
instance commRingLocalizations (P : PrimeSpectrum.Top R) : CommRing <| Localizations R P :=
inferInstanceAs <| CommRing <| Localization.AtPrime P.asIdeal
instance localRingLocalizations (P : PrimeSpectrum.Top R) : IsLocalRing <| Localizations R P :=
inferInstanceAs <| IsLocalRing <| Localization.AtPrime P.asIdeal
instance (P : PrimeSpectrum.Top R) : Inhabited (Localizations R P) :=
⟨1⟩
instance (U : Opens (PrimeSpectrum.Top R)) (x : U) : Algebra R (Localizations R x) :=
inferInstanceAs <| Algebra R (Localization.AtPrime x.1.asIdeal)
instance (U : Opens (PrimeSpectrum.Top R)) (x : U) :
IsLocalization.AtPrime (Localizations R x) (x : PrimeSpectrum.Top R).asIdeal :=
Localization.isLocalization
variable {R}
/-- The predicate saying that a dependent function on an open `U` is realised as a fixed fraction
`r / s` in each of the stalks (which are localizations at various prime ideals).
-/
def IsFraction {U : Opens (PrimeSpectrum.Top R)} (f : ∀ x : U, Localizations R x) : Prop :=
∃ r s : R, ∀ x : U, ¬s ∈ x.1.asIdeal ∧ f x * algebraMap _ _ s = algebraMap _ _ r
theorem IsFraction.eq_mk' {U : Opens (PrimeSpectrum.Top R)} {f : ∀ x : U, Localizations R x}
(hf : IsFraction f) :
∃ r s : R,
∀ x : U,
∃ hs : s ∉ x.1.asIdeal,
f x =
IsLocalization.mk' (Localization.AtPrime _) r
| (⟨s, hs⟩ : (x : PrimeSpectrum.Top R).asIdeal.primeCompl) := by
rcases hf with ⟨r, s, h⟩
refine ⟨r, s, fun x => ⟨(h x).1, (IsLocalization.mk'_eq_iff_eq_mul.mpr ?_).symm⟩⟩
exact (h x).2.symm
variable (R)
/-- The predicate `IsFraction` is "prelocal",
in the sense that if it holds on `U` it holds on any open subset `V` of `U`.
-/
def isFractionPrelocal : PrelocalPredicate (Localizations R) where
| Mathlib/AlgebraicGeometry/StructureSheaf.lean | 108 | 118 |
/-
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
-/
import Mathlib.MeasureTheory.Integral.Lebesgue.Basic
import Mathlib.MeasureTheory.Integral.Lebesgue.Countable
import Mathlib.MeasureTheory.Integral.Lebesgue.MeasurePreserving
import Mathlib.MeasureTheory.Integral.Lebesgue.Norm
deprecated_module (since := "2025-04-13")
| Mathlib/MeasureTheory/Integral/Lebesgue.lean | 361 | 365 | |
/-
Copyright (c) 2023 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import Mathlib.Data.Set.Image
import Mathlib.Topology.Bases
import Mathlib.Topology.Inseparable
import Mathlib.Topology.Compactness.Exterior
/-!
# Alexandrov-discrete topological spaces
This file defines Alexandrov-discrete spaces, aka finitely generated spaces.
A space is Alexandrov-discrete if the (arbitrary) intersection of open sets is open. As such,
the intersection of all neighborhoods of a set is a neighborhood itself. Hence every set has a
minimal neighborhood, which we call the *exterior* of the set.
## Main declarations
* `AlexandrovDiscrete`: Prop-valued typeclass for a topological space to be Alexandrov-discrete
## Notes
The "minimal neighborhood of a set" construction is not named in the literature. We chose the name
"exterior" with analogy to the interior. `interior` and `exterior` have the same properties up to
## TODO
Finite product of Alexandrov-discrete spaces is Alexandrov-discrete.
## Tags
Alexandroff, discrete, finitely generated, fg space
-/
open Filter Set TopologicalSpace Topology
/-- A topological space is **Alexandrov-discrete** or **finitely generated** if the intersection of
a family of open sets is open. -/
class AlexandrovDiscrete (α : Type*) [TopologicalSpace α] : Prop where
/-- The intersection of a family of open sets is an open set. Use `isOpen_sInter` in the root
namespace instead. -/
protected isOpen_sInter : ∀ S : Set (Set α), (∀ s ∈ S, IsOpen s) → IsOpen (⋂₀ S)
variable {ι : Sort*} {κ : ι → Sort*} {α β : Type*}
section
variable [TopologicalSpace α] [TopologicalSpace β]
instance DiscreteTopology.toAlexandrovDiscrete [DiscreteTopology α] : AlexandrovDiscrete α where
isOpen_sInter _ _ := isOpen_discrete _
instance Finite.toAlexandrovDiscrete [Finite α] : AlexandrovDiscrete α where
isOpen_sInter S := (toFinite S).isOpen_sInter
section AlexandrovDiscrete
variable [AlexandrovDiscrete α] {S : Set (Set α)} {f : ι → Set α}
lemma isOpen_sInter : (∀ s ∈ S, IsOpen s) → IsOpen (⋂₀ S) := AlexandrovDiscrete.isOpen_sInter _
lemma isOpen_iInter (hf : ∀ i, IsOpen (f i)) : IsOpen (⋂ i, f i) :=
isOpen_sInter <| forall_mem_range.2 hf
lemma isOpen_iInter₂ {f : ∀ i, κ i → Set α} (hf : ∀ i j, IsOpen (f i j)) :
IsOpen (⋂ i, ⋂ j, f i j) :=
isOpen_iInter fun _ ↦ isOpen_iInter <| hf _
lemma isClosed_sUnion (hS : ∀ s ∈ S, IsClosed s) : IsClosed (⋃₀ S) := by
simp only [← isOpen_compl_iff, compl_sUnion] at hS ⊢; exact isOpen_sInter <| forall_mem_image.2 hS
lemma isClosed_iUnion (hf : ∀ i, IsClosed (f i)) : IsClosed (⋃ i, f i) :=
isClosed_sUnion <| forall_mem_range.2 hf
lemma isClosed_iUnion₂ {f : ∀ i, κ i → Set α} (hf : ∀ i j, IsClosed (f i j)) :
IsClosed (⋃ i, ⋃ j, f i j) :=
isClosed_iUnion fun _ ↦ isClosed_iUnion <| hf _
lemma isClopen_sInter (hS : ∀ s ∈ S, IsClopen s) : IsClopen (⋂₀ S) :=
⟨isClosed_sInter fun s hs ↦ (hS s hs).1, isOpen_sInter fun s hs ↦ (hS s hs).2⟩
lemma isClopen_iInter (hf : ∀ i, IsClopen (f i)) : IsClopen (⋂ i, f i) :=
⟨isClosed_iInter fun i ↦ (hf i).1, isOpen_iInter fun i ↦ (hf i).2⟩
lemma isClopen_iInter₂ {f : ∀ i, κ i → Set α} (hf : ∀ i j, IsClopen (f i j)) :
IsClopen (⋂ i, ⋂ j, f i j) :=
isClopen_iInter fun _ ↦ isClopen_iInter <| hf _
lemma isClopen_sUnion (hS : ∀ s ∈ S, IsClopen s) : IsClopen (⋃₀ S) :=
⟨isClosed_sUnion fun s hs ↦ (hS s hs).1, isOpen_sUnion fun s hs ↦ (hS s hs).2⟩
lemma isClopen_iUnion (hf : ∀ i, IsClopen (f i)) : IsClopen (⋃ i, f i) :=
⟨isClosed_iUnion fun i ↦ (hf i).1, isOpen_iUnion fun i ↦ (hf i).2⟩
lemma isClopen_iUnion₂ {f : ∀ i, κ i → Set α} (hf : ∀ i j, IsClopen (f i j)) :
IsClopen (⋃ i, ⋃ j, f i j) :=
isClopen_iUnion fun _ ↦ isClopen_iUnion <| hf _
lemma interior_iInter (f : ι → Set α) : interior (⋂ i, f i) = ⋂ i, interior (f i) :=
(interior_maximal (iInter_mono fun _ ↦ interior_subset) <| isOpen_iInter fun _ ↦
isOpen_interior).antisymm' <| subset_iInter fun _ ↦ interior_mono <| iInter_subset _ _
lemma interior_sInter (S : Set (Set α)) : interior (⋂₀ S) = ⋂ s ∈ S, interior s := by
simp_rw [sInter_eq_biInter, interior_iInter]
lemma closure_iUnion (f : ι → Set α) : closure (⋃ i, f i) = ⋃ i, closure (f i) :=
compl_injective <| by
simpa only [← interior_compl, compl_iUnion] using interior_iInter fun i ↦ (f i)ᶜ
lemma closure_sUnion (S : Set (Set α)) : closure (⋃₀ S) = ⋃ s ∈ S, closure s := by
simp_rw [sUnion_eq_biUnion, closure_iUnion]
end AlexandrovDiscrete
lemma Topology.IsInducing.alexandrovDiscrete [AlexandrovDiscrete α] {f : β → α} (h : IsInducing f) :
AlexandrovDiscrete β where
isOpen_sInter S hS := by
simp_rw [h.isOpen_iff] at hS ⊢
choose U hU htU using hS
refine ⟨_, isOpen_iInter₂ hU, ?_⟩
simp_rw [preimage_iInter, htU, sInter_eq_biInter]
@[deprecated (since := "2024-10-28")]
alias Inducing.alexandrovDiscrete := IsInducing.alexandrovDiscrete
end
lemma AlexandrovDiscrete.sup {t₁ t₂ : TopologicalSpace α} (_ : @AlexandrovDiscrete α t₁)
(_ : @AlexandrovDiscrete α t₂) :
@AlexandrovDiscrete α (t₁ ⊔ t₂) :=
@AlexandrovDiscrete.mk α (t₁ ⊔ t₂) fun _S hS ↦
⟨@isOpen_sInter _ t₁ _ _ fun _s hs ↦ (hS _ hs).1, isOpen_sInter fun _s hs ↦ (hS _ hs).2⟩
lemma alexandrovDiscrete_iSup {t : ι → TopologicalSpace α} (_ : ∀ i, @AlexandrovDiscrete α (t i)) :
@AlexandrovDiscrete α (⨆ i, t i) :=
@AlexandrovDiscrete.mk α (⨆ i, t i)
fun _S hS ↦ isOpen_iSup_iff.2
fun i ↦ @isOpen_sInter _ (t i) _ _
fun _s hs ↦ isOpen_iSup_iff.1 (hS _ hs) _
section
variable [TopologicalSpace α] [TopologicalSpace β] [AlexandrovDiscrete α] [AlexandrovDiscrete β]
{s t : Set α} {a : α}
@[simp] lemma isOpen_exterior : IsOpen (exterior s) := by
rw [exterior_def]; exact isOpen_sInter fun _ ↦ And.left
lemma exterior_mem_nhdsSet : exterior s ∈ 𝓝ˢ s := isOpen_exterior.mem_nhdsSet.2 subset_exterior
@[simp] lemma exterior_eq_iff_isOpen : exterior s = s ↔ IsOpen s :=
⟨fun h ↦ h ▸ isOpen_exterior, IsOpen.exterior_eq⟩
@[simp] lemma exterior_subset_iff_isOpen : exterior s ⊆ s ↔ IsOpen s := by
simp only [exterior_eq_iff_isOpen.symm, Subset.antisymm_iff, subset_exterior, and_true]
lemma exterior_subset_iff : exterior s ⊆ t ↔ ∃ U, IsOpen U ∧ s ⊆ U ∧ U ⊆ t :=
⟨fun h ↦ ⟨exterior s, isOpen_exterior, subset_exterior, h⟩,
fun ⟨_U, hU, hsU, hUt⟩ ↦ (exterior_minimal hsU hU).trans hUt⟩
lemma exterior_subset_iff_mem_nhdsSet : exterior s ⊆ t ↔ t ∈ 𝓝ˢ s :=
exterior_subset_iff.trans mem_nhdsSet_iff_exists.symm
lemma exterior_singleton_subset_iff_mem_nhds : exterior {a} ⊆ t ↔ t ∈ 𝓝 a := by
simp [exterior_subset_iff_mem_nhdsSet]
lemma gc_exterior_interior : GaloisConnection (exterior : Set α → Set α) interior :=
fun s t ↦ by simp [exterior_subset_iff, subset_interior_iff]
@[simp] lemma principal_exterior (s : Set α) : 𝓟 (exterior s) = 𝓝ˢ s := by
rw [← nhdsSet_exterior, isOpen_exterior.nhdsSet_eq]
lemma isOpen_iff_forall_specializes : IsOpen s ↔ ∀ x y, x ⤳ y → y ∈ s → x ∈ s := by
simp only [← exterior_subset_iff_isOpen, Set.subset_def, mem_exterior_iff_specializes, exists_imp,
and_imp, @forall_swap (_ ⤳ _)]
lemma alexandrovDiscrete_coinduced {β : Type*} {f : α → β} :
@AlexandrovDiscrete β (coinduced f ‹_›) :=
@AlexandrovDiscrete.mk β (coinduced f ‹_›) fun S hS ↦ by
rw [isOpen_coinduced, preimage_sInter]; exact isOpen_iInter₂ hS
instance AlexandrovDiscrete.toFirstCountable : FirstCountableTopology α where
nhds_generated_countable a := ⟨{exterior {a}}, countable_singleton _, by simp⟩
instance AlexandrovDiscrete.toLocallyCompactSpace : LocallyCompactSpace α where
local_compact_nhds a _U hU := ⟨exterior {a},
isOpen_exterior.mem_nhds <| subset_exterior <| mem_singleton _,
exterior_singleton_subset_iff_mem_nhds.2 hU, isCompact_singleton.exterior⟩
instance Subtype.instAlexandrovDiscrete {p : α → Prop} : AlexandrovDiscrete {a // p a} :=
IsInducing.subtypeVal.alexandrovDiscrete
instance Quotient.instAlexandrovDiscrete {s : Setoid α} : AlexandrovDiscrete (Quotient s) :=
alexandrovDiscrete_coinduced
instance Sum.instAlexandrovDiscrete : AlexandrovDiscrete (α ⊕ β) :=
alexandrovDiscrete_coinduced.sup alexandrovDiscrete_coinduced
instance Sigma.instAlexandrovDiscrete {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)]
[∀ i, AlexandrovDiscrete (π i)] : AlexandrovDiscrete (Σ i, π i) :=
alexandrovDiscrete_iSup fun _ ↦ alexandrovDiscrete_coinduced
end
| Mathlib/Topology/AlexandrovDiscrete.lean | 225 | 230 | |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Logic.Encodable.Pi
import Mathlib.Logic.Function.Iterate
/-!
# The primitive recursive functions
The primitive recursive functions are the least collection of functions
`ℕ → ℕ` which are closed under projections (using the `pair`
pairing function), composition, zero, successor, and primitive recursion
(i.e. `Nat.rec` where the motive is `C n := ℕ`).
We can extend this definition to a large class of basic types by
using canonical encodings of types as natural numbers (Gödel numbering),
which we implement through the type class `Encodable`. (More precisely,
we need that the composition of encode with decode yields a
primitive recursive function, so we have the `Primcodable` type class
for this.)
In the above, the pairing function is primitive recursive by definition.
This deviates from the textbook definition of primitive recursive functions,
which instead work with *`n`-ary* functions. We formalize the textbook
definition in `Nat.Primrec'`. `Nat.Primrec'.prim_iff` then proves it is
equivalent to our chosen formulation. For more discussionn of this and
other design choices in this formalization, see [carneiro2019].
## Main definitions
- `Nat.Primrec f`: `f` is primitive recursive, for functions `f : ℕ → ℕ`
- `Primrec f`: `f` is primitive recursive, for functions between `Primcodable` types
- `Primcodable α`: well-behaved encoding of `α` into `ℕ`, i.e. one such that roundtripping through
the encoding functions adds no computational power
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open List (Vector)
open Denumerable Encodable Function
namespace Nat
/-- Calls the given function on a pair of entries `n`, encoded via the pairing function. -/
@[simp, reducible]
def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α :=
f n.unpair.1 n.unpair.2
/-- The primitive recursive functions `ℕ → ℕ`. -/
protected inductive Primrec : (ℕ → ℕ) → Prop
| zero : Nat.Primrec fun _ => 0
| protected succ : Nat.Primrec succ
| left : Nat.Primrec fun n => n.unpair.1
| right : Nat.Primrec fun n => n.unpair.2
| pair {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => pair (f n) (g n)
| comp {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => f (g n)
| prec {f g} :
Nat.Primrec f →
Nat.Primrec g →
Nat.Primrec (unpaired fun z n => n.rec (f z) fun y IH => g <| pair z <| pair y IH)
namespace Primrec
theorem of_eq {f g : ℕ → ℕ} (hf : Nat.Primrec f) (H : ∀ n, f n = g n) : Nat.Primrec g :=
(funext H : f = g) ▸ hf
theorem const : ∀ n : ℕ, Nat.Primrec fun _ => n
| 0 => zero
| n + 1 => Primrec.succ.comp (const n)
protected theorem id : Nat.Primrec id :=
(left.pair right).of_eq fun n => by simp
theorem prec1 {f} (m : ℕ) (hf : Nat.Primrec f) :
Nat.Primrec fun n => n.rec m fun y IH => f <| Nat.pair y IH :=
((prec (const m) (hf.comp right)).comp (zero.pair Primrec.id)).of_eq fun n => by simp
theorem casesOn1 {f} (m : ℕ) (hf : Nat.Primrec f) : Nat.Primrec (Nat.casesOn · m f) :=
(prec1 m (hf.comp left)).of_eq <| by simp
-- Porting note: `Nat.Primrec.casesOn` is already declared as a recursor.
theorem casesOn' {f g} (hf : Nat.Primrec f) (hg : Nat.Primrec g) :
Nat.Primrec (unpaired fun z n => n.casesOn (f z) fun y => g <| Nat.pair z y) :=
(prec hf (hg.comp (pair left (left.comp right)))).of_eq fun n => by simp
protected theorem swap : Nat.Primrec (unpaired (swap Nat.pair)) :=
(pair right left).of_eq fun n => by simp
theorem swap' {f} (hf : Nat.Primrec (unpaired f)) : Nat.Primrec (unpaired (swap f)) :=
(hf.comp .swap).of_eq fun n => by simp
theorem pred : Nat.Primrec pred :=
(casesOn1 0 Primrec.id).of_eq fun n => by cases n <;> simp [*]
theorem add : Nat.Primrec (unpaired (· + ·)) :=
(prec .id ((Primrec.succ.comp right).comp right)).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.add_assoc]
theorem sub : Nat.Primrec (unpaired (· - ·)) :=
(prec .id ((pred.comp right).comp right)).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.sub_add_eq]
theorem mul : Nat.Primrec (unpaired (· * ·)) :=
(prec zero (add.comp (pair left (right.comp right)))).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, mul_succ, add_comm _ (unpair p).fst]
theorem pow : Nat.Primrec (unpaired (· ^ ·)) :=
(prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.pow_succ]
end Primrec
end Nat
/-- A `Primcodable` type is, essentially, an `Encodable` type for which
the encode/decode functions are primitive recursive.
However, such a definition is circular.
Instead, we ask that the composition of `decode : ℕ → Option α` with
`encode : Option α → ℕ` is primitive recursive. Said composition is
the identity function, restricted to the image of `encode`.
Thus, in a way, the added requirement ensures that no predicates
can be smuggled in through a cunning choice of the subset of `ℕ` into
which the type is encoded. -/
class Primcodable (α : Type*) extends Encodable α where
-- Porting note: was `prim [] `.
-- This means that `prim` does not take the type explicitly in Lean 4
prim : Nat.Primrec fun n => Encodable.encode (decode n)
namespace Primcodable
open Nat.Primrec
instance (priority := 10) ofDenumerable (α) [Denumerable α] : Primcodable α :=
⟨Nat.Primrec.succ.of_eq <| by simp⟩
/-- Builds a `Primcodable` instance from an equivalence to a `Primcodable` type. -/
def ofEquiv (α) {β} [Primcodable α] (e : β ≃ α) : Primcodable β :=
{ __ := Encodable.ofEquiv α e
prim := (@Primcodable.prim α _).of_eq fun n => by
rw [decode_ofEquiv]
cases (@decode α _ n) <;>
simp [encode_ofEquiv] }
instance empty : Primcodable Empty :=
⟨zero⟩
instance unit : Primcodable PUnit :=
⟨(casesOn1 1 zero).of_eq fun n => by cases n <;> simp⟩
instance option {α : Type*} [h : Primcodable α] : Primcodable (Option α) :=
⟨(casesOn1 1 ((casesOn1 0 (.comp .succ .succ)).comp (@Primcodable.prim α _))).of_eq fun n => by
cases n with
| zero => rfl
| succ n =>
rw [decode_option_succ]
cases H : @decode α _ n <;> simp [H]⟩
instance bool : Primcodable Bool :=
⟨(casesOn1 1 (casesOn1 2 zero)).of_eq fun n => match n with
| 0 => rfl
| 1 => rfl
| (n + 2) => by rw [decode_ge_two] <;> simp⟩
end Primcodable
/-- `Primrec f` means `f` is primitive recursive (after
encoding its input and output as natural numbers). -/
def Primrec {α β} [Primcodable α] [Primcodable β] (f : α → β) : Prop :=
Nat.Primrec fun n => encode ((@decode α _ n).map f)
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
open Nat.Primrec
protected theorem encode : Primrec (@encode α _) :=
(@Primcodable.prim α _).of_eq fun n => by cases @decode α _ n <;> rfl
protected theorem decode : Primrec (@decode α _) :=
Nat.Primrec.succ.comp (@Primcodable.prim α _)
theorem dom_denumerable {α β} [Denumerable α] [Primcodable β] {f : α → β} :
Primrec f ↔ Nat.Primrec fun n => encode (f (ofNat α n)) :=
⟨fun h => (pred.comp h).of_eq fun n => by simp, fun h =>
(Nat.Primrec.succ.comp h).of_eq fun n => by simp⟩
theorem nat_iff {f : ℕ → ℕ} : Primrec f ↔ Nat.Primrec f :=
dom_denumerable
theorem encdec : Primrec fun n => encode (@decode α _ n) :=
nat_iff.2 Primcodable.prim
theorem option_some : Primrec (@some α) :=
((casesOn1 0 (Nat.Primrec.succ.comp .succ)).comp (@Primcodable.prim α _)).of_eq fun n => by
cases @decode α _ n <;> simp
theorem of_eq {f g : α → σ} (hf : Primrec f) (H : ∀ n, f n = g n) : Primrec g :=
(funext H : f = g) ▸ hf
theorem const (x : σ) : Primrec fun _ : α => x :=
((casesOn1 0 (.const (encode x).succ)).comp (@Primcodable.prim α _)).of_eq fun n => by
cases @decode α _ n <;> rfl
protected theorem id : Primrec (@id α) :=
(@Primcodable.prim α).of_eq <| by simp
theorem comp {f : β → σ} {g : α → β} (hf : Primrec f) (hg : Primrec g) : Primrec fun a => f (g a) :=
((casesOn1 0 (.comp hf (pred.comp hg))).comp (@Primcodable.prim α _)).of_eq fun n => by
cases @decode α _ n <;> simp [encodek]
theorem succ : Primrec Nat.succ :=
nat_iff.2 Nat.Primrec.succ
theorem pred : Primrec Nat.pred :=
nat_iff.2 Nat.Primrec.pred
theorem encode_iff {f : α → σ} : (Primrec fun a => encode (f a)) ↔ Primrec f :=
⟨fun h => Nat.Primrec.of_eq h fun n => by cases @decode α _ n <;> rfl, Primrec.encode.comp⟩
theorem ofNat_iff {α β} [Denumerable α] [Primcodable β] {f : α → β} :
Primrec f ↔ Primrec fun n => f (ofNat α n) :=
dom_denumerable.trans <| nat_iff.symm.trans encode_iff
protected theorem ofNat (α) [Denumerable α] : Primrec (ofNat α) :=
ofNat_iff.1 Primrec.id
theorem option_some_iff {f : α → σ} : (Primrec fun a => some (f a)) ↔ Primrec f :=
⟨fun h => encode_iff.1 <| pred.comp <| encode_iff.2 h, option_some.comp⟩
theorem of_equiv {β} {e : β ≃ α} :
haveI := Primcodable.ofEquiv α e
Primrec e :=
letI : Primcodable β := Primcodable.ofEquiv α e
encode_iff.1 Primrec.encode
theorem of_equiv_symm {β} {e : β ≃ α} :
haveI := Primcodable.ofEquiv α e
Primrec e.symm :=
letI := Primcodable.ofEquiv α e
encode_iff.1 (show Primrec fun a => encode (e (e.symm a)) by simp [Primrec.encode])
theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} :
haveI := Primcodable.ofEquiv α e
(Primrec fun a => e (f a)) ↔ Primrec f :=
letI := Primcodable.ofEquiv α e
⟨fun h => (of_equiv_symm.comp h).of_eq fun a => by simp, of_equiv.comp⟩
theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} :
haveI := Primcodable.ofEquiv α e
(Primrec fun a => e.symm (f a)) ↔ Primrec f :=
letI := Primcodable.ofEquiv α e
⟨fun h => (of_equiv.comp h).of_eq fun a => by simp, of_equiv_symm.comp⟩
end Primrec
namespace Primcodable
open Nat.Primrec
instance prod {α β} [Primcodable α] [Primcodable β] : Primcodable (α × β) :=
⟨((casesOn' zero ((casesOn' zero .succ).comp (pair right ((@Primcodable.prim β).comp left)))).comp
(pair right ((@Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1; · simp
cases @decode β _ n.unpair.2 <;> simp⟩
end Primcodable
namespace Primrec
variable {α : Type*} [Primcodable α]
open Nat.Primrec
theorem fst {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.fst α β) :=
((casesOn' zero
((casesOn' zero (Nat.Primrec.succ.comp left)).comp
(pair right ((@Primcodable.prim β).comp left)))).comp
(pair right ((@Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1 <;> simp
cases @decode β _ n.unpair.2 <;> simp
theorem snd {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.snd α β) :=
((casesOn' zero
((casesOn' zero (Nat.Primrec.succ.comp right)).comp
(pair right ((@Primcodable.prim β).comp left)))).comp
(pair right ((@Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1 <;> simp
cases @decode β _ n.unpair.2 <;> simp
theorem pair {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {f : α → β} {g : α → γ}
(hf : Primrec f) (hg : Primrec g) : Primrec fun a => (f a, g a) :=
((casesOn1 0
(Nat.Primrec.succ.comp <|
.pair (Nat.Primrec.pred.comp hf) (Nat.Primrec.pred.comp hg))).comp
(@Primcodable.prim α _)).of_eq
fun n => by cases @decode α _ n <;> simp [encodek]
theorem unpair : Primrec Nat.unpair :=
(pair (nat_iff.2 .left) (nat_iff.2 .right)).of_eq fun n => by simp
theorem list_getElem?₁ : ∀ l : List α, Primrec (l[·]? : ℕ → Option α)
| [] => dom_denumerable.2 zero
| a :: l =>
dom_denumerable.2 <|
(casesOn1 (encode a).succ <| dom_denumerable.1 <| list_getElem?₁ l).of_eq fun n => by
cases n <;> simp
@[deprecated (since := "2025-02-14")] alias list_get?₁ := list_getElem?₁
end Primrec
/-- `Primrec₂ f` means `f` is a binary primitive recursive function.
This is technically unnecessary since we can always curry all
the arguments together, but there are enough natural two-arg
functions that it is convenient to express this directly. -/
def Primrec₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] (f : α → β → σ) :=
Primrec fun p : α × β => f p.1 p.2
/-- `PrimrecPred p` means `p : α → Prop` is a (decidable)
primitive recursive predicate, which is to say that
`decide ∘ p : α → Bool` is primitive recursive. -/
def PrimrecPred {α} [Primcodable α] (p : α → Prop) [DecidablePred p] :=
Primrec fun a => decide (p a)
/-- `PrimrecRel p` means `p : α → β → Prop` is a (decidable)
primitive recursive relation, which is to say that
`decide ∘ p : α → β → Bool` is primitive recursive. -/
def PrimrecRel {α β} [Primcodable α] [Primcodable β] (s : α → β → Prop)
[∀ a b, Decidable (s a b)] :=
Primrec₂ fun a b => decide (s a b)
namespace Primrec₂
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem mk {f : α → β → σ} (hf : Primrec fun p : α × β => f p.1 p.2) : Primrec₂ f := hf
theorem of_eq {f g : α → β → σ} (hg : Primrec₂ f) (H : ∀ a b, f a b = g a b) : Primrec₂ g :=
(by funext a b; apply H : f = g) ▸ hg
theorem const (x : σ) : Primrec₂ fun (_ : α) (_ : β) => x :=
Primrec.const _
protected theorem pair : Primrec₂ (@Prod.mk α β) :=
Primrec.pair .fst .snd
theorem left : Primrec₂ fun (a : α) (_ : β) => a :=
.fst
theorem right : Primrec₂ fun (_ : α) (b : β) => b :=
.snd
theorem natPair : Primrec₂ Nat.pair := by simp [Primrec₂, Primrec]; constructor
theorem unpaired {f : ℕ → ℕ → α} : Primrec (Nat.unpaired f) ↔ Primrec₂ f :=
⟨fun h => by simpa using h.comp natPair, fun h => h.comp Primrec.unpair⟩
theorem unpaired' {f : ℕ → ℕ → ℕ} : Nat.Primrec (Nat.unpaired f) ↔ Primrec₂ f :=
Primrec.nat_iff.symm.trans unpaired
theorem encode_iff {f : α → β → σ} : (Primrec₂ fun a b => encode (f a b)) ↔ Primrec₂ f :=
Primrec.encode_iff
theorem option_some_iff {f : α → β → σ} : (Primrec₂ fun a b => some (f a b)) ↔ Primrec₂ f :=
Primrec.option_some_iff
theorem ofNat_iff {α β σ} [Denumerable α] [Denumerable β] [Primcodable σ] {f : α → β → σ} :
Primrec₂ f ↔ Primrec₂ fun m n : ℕ => f (ofNat α m) (ofNat β n) :=
(Primrec.ofNat_iff.trans <| by simp).trans unpaired
theorem uncurry {f : α → β → σ} : Primrec (Function.uncurry f) ↔ Primrec₂ f := by
rw [show Function.uncurry f = fun p : α × β => f p.1 p.2 from funext fun ⟨a, b⟩ => rfl]; rfl
theorem curry {f : α × β → σ} : Primrec₂ (Function.curry f) ↔ Primrec f := by
rw [← uncurry, Function.uncurry_curry]
end Primrec₂
section Comp
variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ]
theorem Primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun a b => f (g a b) :=
hf.comp hg
theorem Primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : Primrec₂ f) (hg : Primrec g)
(hh : Primrec h) : Primrec fun a => f (g a) (h a) :=
Primrec.comp hf (hg.pair hh)
theorem Primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : Primrec₂ f)
(hg : Primrec₂ g) (hh : Primrec₂ h) : Primrec₂ fun a b => f (g a b) (h a b) :=
hf.comp hg hh
theorem PrimrecPred.comp {p : β → Prop} [DecidablePred p] {f : α → β} :
PrimrecPred p → Primrec f → PrimrecPred fun a => p (f a) :=
Primrec.comp
theorem PrimrecRel.comp {R : β → γ → Prop} [∀ a b, Decidable (R a b)] {f : α → β} {g : α → γ} :
PrimrecRel R → Primrec f → Primrec g → PrimrecPred fun a => R (f a) (g a) :=
Primrec₂.comp
theorem PrimrecRel.comp₂ {R : γ → δ → Prop} [∀ a b, Decidable (R a b)] {f : α → β → γ}
{g : α → β → δ} :
PrimrecRel R → Primrec₂ f → Primrec₂ g → PrimrecRel fun a b => R (f a b) (g a b) :=
PrimrecRel.comp
end Comp
theorem PrimrecPred.of_eq {α} [Primcodable α] {p q : α → Prop} [DecidablePred p] [DecidablePred q]
(hp : PrimrecPred p) (H : ∀ a, p a ↔ q a) : PrimrecPred q :=
Primrec.of_eq hp fun a => Bool.decide_congr (H a)
theorem PrimrecRel.of_eq {α β} [Primcodable α] [Primcodable β] {r s : α → β → Prop}
[∀ a b, Decidable (r a b)] [∀ a b, Decidable (s a b)] (hr : PrimrecRel r)
(H : ∀ a b, r a b ↔ s a b) : PrimrecRel s :=
Primrec₂.of_eq hr fun a b => Bool.decide_congr (H a b)
namespace Primrec₂
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
open Nat.Primrec
theorem swap {f : α → β → σ} (h : Primrec₂ f) : Primrec₂ (swap f) :=
h.comp₂ Primrec₂.right Primrec₂.left
theorem nat_iff {f : α → β → σ} : Primrec₂ f ↔ Nat.Primrec
(.unpaired fun m n => encode <| (@decode α _ m).bind fun a => (@decode β _ n).map (f a)) := by
have :
∀ (a : Option α) (b : Option β),
Option.map (fun p : α × β => f p.1 p.2)
(Option.bind a fun a : α => Option.map (Prod.mk a) b) =
Option.bind a fun a => Option.map (f a) b := fun a b => by
cases a <;> cases b <;> rfl
simp [Primrec₂, Primrec, this]
theorem nat_iff' {f : α → β → σ} :
Primrec₂ f ↔
Primrec₂ fun m n : ℕ => (@decode α _ m).bind fun a => Option.map (f a) (@decode β _ n) :=
nat_iff.trans <| unpaired'.trans encode_iff
end Primrec₂
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem to₂ {f : α × β → σ} (hf : Primrec f) : Primrec₂ fun a b => f (a, b) :=
hf.of_eq fun _ => rfl
theorem nat_rec {f : α → β} {g : α → ℕ × β → β} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun a (n : ℕ) => n.rec (motive := fun _ => β) (f a) fun n IH => g a (n, IH) :=
Primrec₂.nat_iff.2 <|
((Nat.Primrec.casesOn' .zero <|
(Nat.Primrec.prec hf <|
.comp hg <|
Nat.Primrec.left.pair <|
(Nat.Primrec.left.comp .right).pair <|
Nat.Primrec.pred.comp <| Nat.Primrec.right.comp .right).comp <|
Nat.Primrec.right.pair <| Nat.Primrec.right.comp Nat.Primrec.left).comp <|
Nat.Primrec.id.pair <| (@Primcodable.prim α).comp Nat.Primrec.left).of_eq
fun n => by
simp only [Nat.unpaired, id_eq, Nat.unpair_pair, decode_prod_val, decode_nat,
Option.some_bind, Option.map_map, Option.map_some']
rcases @decode α _ n.unpair.1 with - | a; · rfl
simp only [Nat.pred_eq_sub_one, encode_some, Nat.succ_eq_add_one, encodek, Option.map_some',
Option.some_bind, Option.map_map]
induction' n.unpair.2 with m <;> simp [encodek]
simp [*, encodek]
theorem nat_rec' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β}
(hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) :
Primrec fun a => (f a).rec (motive := fun _ => β) (g a) fun n IH => h a (n, IH) :=
(nat_rec hg hh).comp .id hf
theorem nat_rec₁ {f : ℕ → α → α} (a : α) (hf : Primrec₂ f) : Primrec (Nat.rec a f) :=
nat_rec' .id (const a) <| comp₂ hf Primrec₂.right
theorem nat_casesOn' {f : α → β} {g : α → ℕ → β} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun a (n : ℕ) => (n.casesOn (f a) (g a) : β) :=
nat_rec hf <| hg.comp₂ Primrec₂.left <| comp₂ fst Primrec₂.right
theorem nat_casesOn {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : Primrec f) (hg : Primrec g)
(hh : Primrec₂ h) : Primrec fun a => ((f a).casesOn (g a) (h a) : β) :=
(nat_casesOn' hg hh).comp .id hf
theorem nat_casesOn₁ {f : ℕ → α} (a : α) (hf : Primrec f) :
Primrec (fun (n : ℕ) => (n.casesOn a f : α)) :=
nat_casesOn .id (const a) (comp₂ hf .right)
theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : Primrec f) (hg : Primrec g)
(hh : Primrec₂ h) : Primrec fun a => (h a)^[f a] (g a) :=
(nat_rec' hf hg (hh.comp₂ Primrec₂.left <| snd.comp₂ Primrec₂.right)).of_eq fun a => by
induction f a <;> simp [*, -Function.iterate_succ, Function.iterate_succ']
theorem option_casesOn {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : Primrec o)
(hf : Primrec f) (hg : Primrec₂ g) :
@Primrec _ σ _ _ fun a => Option.casesOn (o a) (f a) (g a) :=
encode_iff.1 <|
(nat_casesOn (encode_iff.2 ho) (encode_iff.2 hf) <|
pred.comp₂ <|
Primrec₂.encode_iff.2 <|
(Primrec₂.nat_iff'.1 hg).comp₂ ((@Primrec.encode α _).comp fst).to₂
Primrec₂.right).of_eq
fun a => by rcases o a with - | b <;> simp [encodek]
theorem option_bind {f : α → Option β} {g : α → β → Option σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec fun a => (f a).bind (g a) :=
(option_casesOn hf (const none) hg).of_eq fun a => by cases f a <;> rfl
theorem option_bind₁ {f : α → Option σ} (hf : Primrec f) : Primrec fun o => Option.bind o f :=
option_bind .id (hf.comp snd).to₂
theorem option_map {f : α → Option β} {g : α → β → σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec fun a => (f a).map (g a) :=
(option_bind hf (option_some.comp₂ hg)).of_eq fun x => by cases f x <;> rfl
theorem option_map₁ {f : α → σ} (hf : Primrec f) : Primrec (Option.map f) :=
option_map .id (hf.comp snd).to₂
theorem option_iget [Inhabited α] : Primrec (@Option.iget α _) :=
(option_casesOn .id (const <| @default α _) .right).of_eq fun o => by cases o <;> rfl
theorem option_isSome : Primrec (@Option.isSome α) :=
(option_casesOn .id (const false) (const true).to₂).of_eq fun o => by cases o <;> rfl
theorem option_getD : Primrec₂ (@Option.getD α) :=
Primrec.of_eq (option_casesOn Primrec₂.left Primrec₂.right .right) fun ⟨o, a⟩ => by
cases o <;> rfl
theorem bind_decode_iff {f : α → β → Option σ} :
(Primrec₂ fun a n => (@decode β _ n).bind (f a)) ↔ Primrec₂ f :=
⟨fun h => by simpa [encodek] using h.comp fst ((@Primrec.encode β _).comp snd), fun h =>
option_bind (Primrec.decode.comp snd) <| h.comp (fst.comp fst) snd⟩
theorem map_decode_iff {f : α → β → σ} :
(Primrec₂ fun a n => (@decode β _ n).map (f a)) ↔ Primrec₂ f := by
simp only [Option.map_eq_bind]
exact bind_decode_iff.trans Primrec₂.option_some_iff
theorem nat_add : Primrec₂ ((· + ·) : ℕ → ℕ → ℕ) :=
Primrec₂.unpaired'.1 Nat.Primrec.add
theorem nat_sub : Primrec₂ ((· - ·) : ℕ → ℕ → ℕ) :=
Primrec₂.unpaired'.1 Nat.Primrec.sub
theorem nat_mul : Primrec₂ ((· * ·) : ℕ → ℕ → ℕ) :=
Primrec₂.unpaired'.1 Nat.Primrec.mul
theorem cond {c : α → Bool} {f : α → σ} {g : α → σ} (hc : Primrec c) (hf : Primrec f)
(hg : Primrec g) : Primrec fun a => bif (c a) then (f a) else (g a) :=
(nat_casesOn (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq fun a => by cases c a <;> rfl
theorem ite {c : α → Prop} [DecidablePred c] {f : α → σ} {g : α → σ} (hc : PrimrecPred c)
(hf : Primrec f) (hg : Primrec g) : Primrec fun a => if c a then f a else g a := by
simpa [Bool.cond_decide] using cond hc hf hg
theorem nat_le : PrimrecRel ((· ≤ ·) : ℕ → ℕ → Prop) :=
(nat_casesOn nat_sub (const true) (const false).to₂).of_eq fun p => by
dsimp [swap]
rcases e : p.1 - p.2 with - | n
· simp [Nat.sub_eq_zero_iff_le.1 e]
· simp [not_le.2 (Nat.lt_of_sub_eq_succ e)]
theorem nat_min : Primrec₂ (@min ℕ _) :=
ite nat_le fst snd
theorem nat_max : Primrec₂ (@max ℕ _) :=
ite (nat_le.comp fst snd) snd fst
theorem dom_bool (f : Bool → α) : Primrec f :=
(cond .id (const (f true)) (const (f false))).of_eq fun b => by cases b <;> rfl
theorem dom_bool₂ (f : Bool → Bool → α) : Primrec₂ f :=
(cond fst ((dom_bool (f true)).comp snd) ((dom_bool (f false)).comp snd)).of_eq fun ⟨a, b⟩ => by
cases a <;> rfl
protected theorem not : Primrec not :=
dom_bool _
protected theorem and : Primrec₂ and :=
dom_bool₂ _
protected theorem or : Primrec₂ or :=
dom_bool₂ _
theorem _root_.PrimrecPred.not {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) :
PrimrecPred fun a => ¬p a :=
(Primrec.not.comp hp).of_eq fun n => by simp
theorem _root_.PrimrecPred.and {p q : α → Prop} [DecidablePred p] [DecidablePred q]
(hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a ∧ q a :=
(Primrec.and.comp hp hq).of_eq fun n => by simp
theorem _root_.PrimrecPred.or {p q : α → Prop} [DecidablePred p] [DecidablePred q]
(hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a ∨ q a :=
(Primrec.or.comp hp hq).of_eq fun n => by simp
protected theorem beq [DecidableEq α] : Primrec₂ (@BEq.beq α _) :=
have : PrimrecRel fun a b : ℕ => a = b :=
(PrimrecPred.and nat_le nat_le.swap).of_eq fun a => by simp [le_antisymm_iff]
(this.comp₂ (Primrec.encode.comp₂ Primrec₂.left) (Primrec.encode.comp₂ Primrec₂.right)).of_eq
fun _ _ => encode_injective.eq_iff
protected theorem eq [DecidableEq α] : PrimrecRel (@Eq α) := Primrec.beq
theorem nat_lt : PrimrecRel ((· < ·) : ℕ → ℕ → Prop) :=
(nat_le.comp snd fst).not.of_eq fun p => by simp
theorem option_guard {p : α → β → Prop} [∀ a b, Decidable (p a b)] (hp : PrimrecRel p) {f : α → β}
(hf : Primrec f) : Primrec fun a => Option.guard (p a) (f a) :=
ite (hp.comp Primrec.id hf) (option_some_iff.2 hf) (const none)
theorem option_orElse : Primrec₂ ((· <|> ·) : Option α → Option α → Option α) :=
(option_casesOn fst snd (fst.comp fst).to₂).of_eq fun ⟨o₁, o₂⟩ => by cases o₁ <;> cases o₂ <;> rfl
protected theorem decode₂ : Primrec (decode₂ α) :=
option_bind .decode <|
option_guard (Primrec.beq.comp₂ (by exact encode_iff.mpr snd) (by exact fst.comp fst)) snd
theorem list_findIdx₁ {p : α → β → Bool} (hp : Primrec₂ p) :
∀ l : List β, Primrec fun a => l.findIdx (p a)
| [] => const 0
| a :: l => (cond (hp.comp .id (const a)) (const 0) (succ.comp (list_findIdx₁ hp l))).of_eq fun n =>
by simp [List.findIdx_cons]
theorem list_idxOf₁ [DecidableEq α] (l : List α) : Primrec fun a => l.idxOf a :=
list_findIdx₁ (.swap .beq) l
@[deprecated (since := "2025-01-30")] alias list_indexOf₁ := list_idxOf₁
theorem dom_fintype [Finite α] (f : α → σ) : Primrec f :=
let ⟨l, _, m⟩ := Finite.exists_univ_list α
option_some_iff.1 <| by
haveI := decidableEqOfEncodable α
refine ((list_getElem?₁ (l.map f)).comp (list_idxOf₁ l)).of_eq fun a => ?_
rw [List.getElem?_map, List.getElem?_idxOf (m a), Option.map_some']
-- Porting note: These are new lemmas
-- I added it because it actually simplified the proofs
-- and because I couldn't understand the original proof
/-- A function is `PrimrecBounded` if its size is bounded by a primitive recursive function -/
def PrimrecBounded (f : α → β) : Prop :=
∃ g : α → ℕ, Primrec g ∧ ∀ x, encode (f x) ≤ g x
theorem nat_findGreatest {f : α → ℕ} {p : α → ℕ → Prop} [∀ x n, Decidable (p x n)]
(hf : Primrec f) (hp : PrimrecRel p) : Primrec fun x => (f x).findGreatest (p x) :=
(nat_rec' (h := fun x nih => if p x (nih.1 + 1) then nih.1 + 1 else nih.2)
hf (const 0) (ite (hp.comp fst (snd |> fst.comp |> succ.comp))
(snd |> fst.comp |> succ.comp) (snd.comp snd))).of_eq fun x => by
induction f x <;> simp [Nat.findGreatest, *]
/-- To show a function `f : α → ℕ` is primitive recursive, it is enough to show that the function
is bounded by a primitive recursive function and that its graph is primitive recursive -/
theorem of_graph {f : α → ℕ} (h₁ : PrimrecBounded f)
(h₂ : PrimrecRel fun a b => f a = b) : Primrec f := by
rcases h₁ with ⟨g, pg, hg : ∀ x, f x ≤ g x⟩
refine (nat_findGreatest pg h₂).of_eq fun n => ?_
exact (Nat.findGreatest_spec (P := fun b => f n = b) (hg n) rfl).symm
-- We show that division is primitive recursive by showing that the graph is
theorem nat_div : Primrec₂ ((· / ·) : ℕ → ℕ → ℕ) := by
refine of_graph ⟨_, fst, fun p => Nat.div_le_self _ _⟩ ?_
have : PrimrecRel fun (a : ℕ × ℕ) (b : ℕ) => (a.2 = 0 ∧ b = 0) ∨
(0 < a.2 ∧ b * a.2 ≤ a.1 ∧ a.1 < (b + 1) * a.2) :=
PrimrecPred.or
(.and (const 0 |> Primrec.eq.comp (fst |> snd.comp)) (const 0 |> Primrec.eq.comp snd))
(.and (nat_lt.comp (const 0) (fst |> snd.comp)) <|
.and (nat_le.comp (nat_mul.comp snd (fst |> snd.comp)) (fst |> fst.comp))
(nat_lt.comp (fst.comp fst) (nat_mul.comp (Primrec.succ.comp snd) (snd.comp fst))))
refine this.of_eq ?_
rintro ⟨a, k⟩ q
if H : k = 0 then simp [H, eq_comm]
else
have : q * k ≤ a ∧ a < (q + 1) * k ↔ q = a / k := by
rw [le_antisymm_iff, ← (@Nat.lt_succ _ q), Nat.le_div_iff_mul_le (Nat.pos_of_ne_zero H),
Nat.div_lt_iff_lt_mul (Nat.pos_of_ne_zero H)]
simpa [H, zero_lt_iff, eq_comm (b := q)]
theorem nat_mod : Primrec₂ ((· % ·) : ℕ → ℕ → ℕ) :=
(nat_sub.comp fst (nat_mul.comp snd nat_div)).to₂.of_eq fun m n => by
apply Nat.sub_eq_of_eq_add
simp [add_comm (m % n), Nat.div_add_mod]
theorem nat_bodd : Primrec Nat.bodd :=
(Primrec.beq.comp (nat_mod.comp .id (const 2)) (const 1)).of_eq fun n => by
cases H : n.bodd <;> simp [Nat.mod_two_of_bodd, H]
theorem nat_div2 : Primrec Nat.div2 :=
(nat_div.comp .id (const 2)).of_eq fun n => n.div2_val.symm
theorem nat_double : Primrec (fun n : ℕ => 2 * n) :=
nat_mul.comp (const _) Primrec.id
theorem nat_double_succ : Primrec (fun n : ℕ => 2 * n + 1) :=
nat_double |> Primrec.succ.comp
end Primrec
section
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
variable (H : Nat.Primrec fun n => Encodable.encode (@decode (List β) _ n))
open Primrec
private def prim : Primcodable (List β) := ⟨H⟩
private theorem list_casesOn' {f : α → List β} {g : α → σ} {h : α → β × List β → σ}
(hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) :
@Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) :=
letI := prim H
have :
@Primrec _ (Option σ) _ _ fun a =>
(@decode (Option (β × List β)) _ (encode (f a))).map fun o => Option.casesOn o (g a) (h a) :=
((@map_decode_iff _ (Option (β × List β)) _ _ _ _ _).2 <|
to₂ <|
option_casesOn snd (hg.comp fst) (hh.comp₂ (fst.comp₂ Primrec₂.left) Primrec₂.right)).comp
.id (encode_iff.2 hf)
option_some_iff.1 <| this.of_eq fun a => by rcases f a with - | ⟨b, l⟩ <;> simp [encodek]
private theorem list_foldl' {f : α → List β} {g : α → σ} {h : α → σ × β → σ}
(hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) :
Primrec fun a => (f a).foldl (fun s b => h a (s, b)) (g a) := by
letI := prim H
let G (a : α) (IH : σ × List β) : σ × List β := List.casesOn IH.2 IH fun b l => (h a (IH.1, b), l)
have hG : Primrec₂ G := list_casesOn' H (snd.comp snd) snd <|
to₂ <|
pair (hh.comp (fst.comp fst) <| pair ((fst.comp snd).comp fst) (fst.comp snd))
(snd.comp snd)
let F := fun (a : α) (n : ℕ) => (G a)^[n] (g a, f a)
have hF : Primrec fun a => (F a (encode (f a))).1 :=
(fst.comp <|
nat_iterate (encode_iff.2 hf) (pair hg hf) <|
hG)
suffices ∀ a n, F a n = (((f a).take n).foldl (fun s b => h a (s, b)) (g a), (f a).drop n) by
refine hF.of_eq fun a => ?_
rw [this, List.take_of_length_le (length_le_encode _)]
introv
dsimp only [F]
generalize f a = l
generalize g a = x
induction n generalizing l x with
| zero => rfl
| succ n IH =>
simp only [iterate_succ, comp_apply]
rcases l with - | ⟨b, l⟩ <;> simp [G, IH]
private theorem list_cons' : (haveI := prim H; Primrec₂ (@List.cons β)) :=
letI := prim H
encode_iff.1 (succ.comp <| Primrec₂.natPair.comp (encode_iff.2 fst) (encode_iff.2 snd))
private theorem list_reverse' :
haveI := prim H
Primrec (@List.reverse β) :=
letI := prim H
(list_foldl' H .id (const []) <| to₂ <| ((list_cons' H).comp snd fst).comp snd).of_eq
(suffices ∀ l r, List.foldl (fun (s : List β) (b : β) => b :: s) r l = List.reverseAux l r from
fun l => this l []
fun l => by induction l <;> simp [*, List.reverseAux])
end
namespace Primcodable
variable {α : Type*} {β : Type*}
variable [Primcodable α] [Primcodable β]
open Primrec
instance sum : Primcodable (α ⊕ β) :=
⟨Primrec.nat_iff.1 <|
(encode_iff.2
(cond nat_bodd
(((@Primrec.decode β _).comp nat_div2).option_map <|
to₂ <| nat_double_succ.comp (Primrec.encode.comp snd))
(((@Primrec.decode α _).comp nat_div2).option_map <|
to₂ <| nat_double.comp (Primrec.encode.comp snd)))).of_eq
fun n =>
show _ = encode (decodeSum n) by
simp only [decodeSum, Nat.boddDiv2_eq]
cases Nat.bodd n <;> simp [decodeSum]
· cases @decode α _ n.div2 <;> rfl
· cases @decode β _ n.div2 <;> rfl⟩
instance list : Primcodable (List α) :=
⟨letI H := @Primcodable.prim (List ℕ) _
have : Primrec₂ fun (a : α) (o : Option (List ℕ)) => o.map (List.cons (encode a)) :=
option_map snd <| (list_cons' H).comp ((@Primrec.encode α _).comp (fst.comp fst)) snd
have :
Primrec fun n =>
(ofNat (List ℕ) n).reverse.foldl
(fun o m => (@decode α _ m).bind fun a => o.map (List.cons (encode a))) (some []) :=
list_foldl' H ((list_reverse' H).comp (.ofNat (List ℕ))) (const (some []))
(Primrec.comp₂ (bind_decode_iff.2 <| .swap this) Primrec₂.right)
nat_iff.1 <|
(encode_iff.2 this).of_eq fun n => by
rw [List.foldl_reverse]
apply Nat.case_strong_induction_on n; · simp
intro n IH; simp
rcases @decode α _ n.unpair.1 with - | a; · rfl
simp only [decode_eq_ofNat, Option.some.injEq, Option.some_bind, Option.map_some']
suffices ∀ (o : Option (List ℕ)) (p), encode o = encode p →
encode (Option.map (List.cons (encode a)) o) = encode (Option.map (List.cons a) p) from
this _ _ (IH _ (Nat.unpair_right_le n))
intro o p IH
cases o <;> cases p
· rfl
· injection IH
· injection IH
· exact congr_arg (fun k => (Nat.pair (encode a) k).succ.succ) (Nat.succ.inj IH)⟩
end Primcodable
namespace Primrec
variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ]
theorem sumInl : Primrec (@Sum.inl α β) :=
encode_iff.1 <| nat_double.comp Primrec.encode
theorem sumInr : Primrec (@Sum.inr α β) :=
encode_iff.1 <| nat_double_succ.comp Primrec.encode
@[deprecated (since := "2025-02-21")] alias sum_inl := Primrec.sumInl
@[deprecated (since := "2025-02-21")] alias sum_inr := Primrec.sumInr
theorem sumCasesOn {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : Primrec f)
(hg : Primrec₂ g) (hh : Primrec₂ h) : @Primrec _ σ _ _ fun a => Sum.casesOn (f a) (g a) (h a) :=
option_some_iff.1 <|
(cond (nat_bodd.comp <| encode_iff.2 hf)
(option_map (Primrec.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hh)
(option_map (Primrec.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hg)).of_eq
fun a => by rcases f a with b | c <;> simp [Nat.div2_val, encodek]
@[deprecated (since := "2025-02-21")] alias sum_casesOn := Primrec.sumCasesOn
theorem list_cons : Primrec₂ (@List.cons α) :=
list_cons' Primcodable.prim
theorem list_casesOn {f : α → List β} {g : α → σ} {h : α → β × List β → σ} :
Primrec f →
Primrec g →
Primrec₂ h → @Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) :=
list_casesOn' Primcodable.prim
theorem list_foldl {f : α → List β} {g : α → σ} {h : α → σ × β → σ} :
Primrec f →
Primrec g → Primrec₂ h → Primrec fun a => (f a).foldl (fun s b => h a (s, b)) (g a) :=
list_foldl' Primcodable.prim
theorem list_reverse : Primrec (@List.reverse α) :=
list_reverse' Primcodable.prim
theorem list_foldr {f : α → List β} {g : α → σ} {h : α → β × σ → σ} (hf : Primrec f)
(hg : Primrec g) (hh : Primrec₂ h) :
Primrec fun a => (f a).foldr (fun b s => h a (b, s)) (g a) :=
(list_foldl (list_reverse.comp hf) hg <| to₂ <| hh.comp fst <| (pair snd fst).comp snd).of_eq
fun a => by simp [List.foldl_reverse]
theorem list_head? : Primrec (@List.head? α) :=
(list_casesOn .id (const none) (option_some_iff.2 <| fst.comp snd).to₂).of_eq fun l => by
cases l <;> rfl
theorem list_headI [Inhabited α] : Primrec (@List.headI α _) :=
(option_iget.comp list_head?).of_eq fun l => l.head!_eq_head?.symm
theorem list_tail : Primrec (@List.tail α) :=
(list_casesOn .id (const []) (snd.comp snd).to₂).of_eq fun l => by cases l <;> rfl
theorem list_rec {f : α → List β} {g : α → σ} {h : α → β × List β × σ → σ} (hf : Primrec f)
(hg : Primrec g) (hh : Primrec₂ h) :
@Primrec _ σ _ _ fun a => List.recOn (f a) (g a) fun b l IH => h a (b, l, IH) :=
let F (a : α) := (f a).foldr (fun (b : β) (s : List β × σ) => (b :: s.1, h a (b, s))) ([], g a)
have : Primrec F :=
list_foldr hf (pair (const []) hg) <|
to₂ <| pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh
(snd.comp this).of_eq fun a => by
suffices F a = (f a, List.recOn (f a) (g a) fun b l IH => h a (b, l, IH)) by rw [this]
dsimp [F]
induction' f a with b l IH <;> simp [*]
theorem list_getElem? : Primrec₂ ((·[·]? : List α → ℕ → Option α)) :=
let F (l : List α) (n : ℕ) :=
l.foldl
(fun (s : ℕ ⊕ α) (a : α) =>
Sum.casesOn s (@Nat.casesOn (fun _ => ℕ ⊕ α) · (Sum.inr a) Sum.inl) Sum.inr)
(Sum.inl n)
have hF : Primrec₂ F :=
(list_foldl fst (sumInl.comp snd)
((sumCasesOn fst (nat_casesOn snd (sumInr.comp <| snd.comp fst) (sumInl.comp snd).to₂).to₂
(sumInr.comp snd).to₂).comp
snd).to₂).to₂
have :
@Primrec _ (Option α) _ _ fun p : List α × ℕ => Sum.casesOn (F p.1 p.2) (fun _ => none) some :=
sumCasesOn hF (const none).to₂ (option_some.comp snd).to₂
this.to₂.of_eq fun l n => by
dsimp; symm
induction' l with a l IH generalizing n; · rfl
rcases n with - | n
· dsimp [F]
clear IH
induction' l with _ l IH <;> simp_all
· simpa using IH ..
@[deprecated (since := "2025-02-14")] alias list_get? := list_getElem?
theorem list_getD (d : α) : Primrec₂ fun l n => List.getD l n d := by
simp only [List.getD_eq_getElem?_getD]
exact option_getD.comp₂ list_getElem? (const _)
theorem list_getI [Inhabited α] : Primrec₂ (@List.getI α _) :=
list_getD _
theorem list_append : Primrec₂ ((· ++ ·) : List α → List α → List α) :=
(list_foldr fst snd <| to₂ <| comp (@list_cons α _) snd).to₂.of_eq fun l₁ l₂ => by
induction l₁ <;> simp [*]
theorem list_concat : Primrec₂ fun l (a : α) => l ++ [a] :=
list_append.comp fst (list_cons.comp snd (const []))
theorem list_map {f : α → List β} {g : α → β → σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec fun a => (f a).map (g a) :=
(list_foldr hf (const []) <|
to₂ <| list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq
fun a => by induction f a <;> simp [*]
theorem list_range : Primrec List.range :=
(nat_rec' .id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq fun n => by
simp; induction n <;> simp [*, List.range_succ]
theorem list_flatten : Primrec (@List.flatten α) :=
(list_foldr .id (const []) <| to₂ <| comp (@list_append α _) snd).of_eq fun l => by
dsimp; induction l <;> simp [*]
theorem list_flatMap {f : α → List β} {g : α → β → List σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec (fun a => (f a).flatMap (g a)) := list_flatten.comp (list_map hf hg)
theorem optionToList : Primrec (Option.toList : Option α → List α) :=
(option_casesOn Primrec.id (const [])
((list_cons.comp Primrec.id (const [])).comp₂ Primrec₂.right)).of_eq
(fun o => by rcases o <;> simp)
theorem listFilterMap {f : α → List β} {g : α → β → Option σ}
(hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).filterMap (g a) :=
(list_flatMap hf (comp₂ optionToList hg)).of_eq
fun _ ↦ Eq.symm <| List.filterMap_eq_flatMap_toList _ _
theorem list_length : Primrec (@List.length α) :=
(list_foldr (@Primrec.id (List α) _) (const 0) <| to₂ <| (succ.comp <| snd.comp snd).to₂).of_eq
fun l => by dsimp; induction l <;> simp [*]
theorem list_findIdx {f : α → List β} {p : α → β → Bool}
(hf : Primrec f) (hp : Primrec₂ p) : Primrec fun a => (f a).findIdx (p a) :=
(list_foldr hf (const 0) <|
to₂ <| cond (hp.comp fst <| fst.comp snd) (const 0) (succ.comp <| snd.comp snd)).of_eq
fun a => by dsimp; induction f a <;> simp [List.findIdx_cons, *]
theorem list_idxOf [DecidableEq α] : Primrec₂ (@List.idxOf α _) :=
to₂ <| list_findIdx snd <| Primrec.beq.comp₂ snd.to₂ (fst.comp fst).to₂
@[deprecated (since := "2025-01-30")] alias list_indexOf := list_idxOf
theorem nat_strong_rec (f : α → ℕ → σ) {g : α → List σ → Option σ} (hg : Primrec₂ g)
(H : ∀ a n, g a ((List.range n).map (f a)) = some (f a n)) : Primrec₂ f :=
suffices Primrec₂ fun a n => (List.range n).map (f a) from
Primrec₂.option_some_iff.1 <|
(list_getElem?.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq fun a n => by
simp [List.getElem?_range (Nat.lt_succ_self n)]
Primrec₂.option_some_iff.1 <|
(nat_rec (const (some []))
(to₂ <|
option_bind (snd.comp snd) <|
to₂ <|
option_map (hg.comp (fst.comp fst) snd)
(to₂ <| list_concat.comp (snd.comp fst) snd))).of_eq
fun a n => by
induction n with
| zero => rfl
| succ n IH => simp [IH, H, List.range_succ]
theorem listLookup [DecidableEq α] : Primrec₂ (List.lookup : α → List (α × β) → Option β) :=
(to₂ <| list_rec snd (const none) <|
to₂ <|
cond (Primrec.beq.comp (fst.comp fst) (fst.comp <| fst.comp snd))
(option_some.comp <| snd.comp <| fst.comp snd)
(snd.comp <| snd.comp snd)).of_eq
fun a ps => by
induction' ps with p ps ih <;> simp [List.lookup, *]
cases ha : a == p.1 <;> simp [ha]
theorem nat_omega_rec' (f : β → σ) {m : β → ℕ} {l : β → List β} {g : β → List σ → Option σ}
(hm : Primrec m) (hl : Primrec l) (hg : Primrec₂ g)
(Ord : ∀ b, ∀ b' ∈ l b, m b' < m b)
(H : ∀ b, g b ((l b).map f) = some (f b)) : Primrec f := by
haveI : DecidableEq β := Encodable.decidableEqOfEncodable β
let mapGraph (M : List (β × σ)) (bs : List β) : List σ := bs.flatMap (Option.toList <| M.lookup ·)
let bindList (b : β) : ℕ → List β := fun n ↦ n.rec [b] fun _ bs ↦ bs.flatMap l
let graph (b : β) : ℕ → List (β × σ) := fun i ↦ i.rec [] fun i ih ↦
(bindList b (m b - i)).filterMap fun b' ↦ (g b' <| mapGraph ih (l b')).map (b', ·)
have mapGraph_primrec : Primrec₂ mapGraph :=
to₂ <| list_flatMap snd <| optionToList.comp₂ <| listLookup.comp₂ .right (fst.comp₂ .left)
have bindList_primrec : Primrec₂ (bindList) :=
nat_rec' snd
(list_cons.comp fst (const []))
(to₂ <| list_flatMap (snd.comp snd) (hl.comp₂ .right))
have graph_primrec : Primrec₂ (graph) :=
to₂ <| nat_rec' snd (const []) <|
to₂ <| listFilterMap
(bindList_primrec.comp
(fst.comp fst)
(nat_sub.comp (hm.comp <| fst.comp fst) (fst.comp snd))) <|
to₂ <| option_map
(hg.comp snd (mapGraph_primrec.comp (snd.comp <| snd.comp fst) (hl.comp snd)))
(Primrec₂.pair.comp₂ (snd.comp₂ .left) .right)
have : Primrec (fun b => (graph b (m b + 1))[0]?.map Prod.snd) :=
option_map (list_getElem?.comp (graph_primrec.comp Primrec.id (succ.comp hm)) (const 0))
(snd.comp₂ Primrec₂.right)
exact option_some_iff.mp <| this.of_eq <| fun b ↦ by
have graph_eq_map_bindList (i : ℕ) (hi : i ≤ m b + 1) :
graph b i = (bindList b (m b + 1 - i)).map fun x ↦ (x, f x) := by
have bindList_eq_nil : bindList b (m b + 1) = [] :=
have bindList_m_lt (k : ℕ) : ∀ b' ∈ bindList b k, m b' < m b + 1 - k := by
induction' k with k ih <;> simp [bindList]
intro a₂ a₁ ha₁ ha₂
have : k ≤ m b :=
Nat.lt_succ.mp (by simpa using Nat.add_lt_of_lt_sub <| Nat.zero_lt_of_lt (ih a₁ ha₁))
have : m a₁ ≤ m b - k :=
Nat.lt_succ.mp (by rw [← Nat.succ_sub this]; simpa using ih a₁ ha₁)
exact lt_of_lt_of_le (Ord a₁ a₂ ha₂) this
List.eq_nil_iff_forall_not_mem.mpr
(by intro b' ha'; by_contra; simpa using bindList_m_lt (m b + 1) b' ha')
have mapGraph_graph {bs bs' : List β} (has : bs' ⊆ bs) :
mapGraph (bs.map <| fun x => (x, f x)) bs' = bs'.map f := by
induction' bs' with b bs' ih <;> simp [mapGraph]
· have : b ∈ bs ∧ bs' ⊆ bs := by simpa using has
rcases this with ⟨ha, has'⟩
simpa [List.lookup_graph f ha] using ih has'
have graph_succ : ∀ i, graph b (i + 1) =
(bindList b (m b - i)).filterMap fun b' =>
(g b' <| mapGraph (graph b i) (l b')).map (b', ·) := fun _ => rfl
have bindList_succ : ∀ i, bindList b (i + 1) = (bindList b i).flatMap l := fun _ => rfl
induction' i with i ih
· symm; simpa [graph] using bindList_eq_nil
· simp only [graph_succ, ih (Nat.le_of_lt hi), Nat.succ_sub (Nat.lt_succ.mp hi),
Nat.succ_eq_add_one, bindList_succ, Nat.reduceSubDiff]
apply List.filterMap_eq_map_iff_forall_eq_some.mpr
intro b' ha'; simp; rw [mapGraph_graph]
· exact H b'
· exact (List.infix_flatMap_of_mem ha' l).subset
simp [graph_eq_map_bindList (m b + 1) (Nat.le_refl _), bindList]
theorem nat_omega_rec (f : α → β → σ) {m : α → β → ℕ}
{l : α → β → List β} {g : α → β × List σ → Option σ}
(hm : Primrec₂ m) (hl : Primrec₂ l) (hg : Primrec₂ g)
(Ord : ∀ a b, ∀ b' ∈ l a b, m a b' < m a b)
(H : ∀ a b, g a (b, (l a b).map (f a)) = some (f a b)) : Primrec₂ f :=
Primrec₂.uncurry.mp <|
nat_omega_rec' (Function.uncurry f)
(Primrec₂.uncurry.mpr hm)
(list_map (hl.comp fst snd) (Primrec₂.pair.comp₂ (fst.comp₂ .left) .right))
(hg.comp₂ (fst.comp₂ .left) (Primrec₂.pair.comp₂ (snd.comp₂ .left) .right))
(by simpa using Ord) (by simpa [Function.comp] using H)
end Primrec
namespace Primcodable
variable {α : Type*} [Primcodable α]
open Primrec
/-- A subtype of a primitive recursive predicate is `Primcodable`. -/
def subtype {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) : Primcodable (Subtype p) :=
⟨have : Primrec fun n => (@decode α _ n).bind fun a => Option.guard p a :=
option_bind .decode (option_guard (hp.comp snd).to₂ snd)
nat_iff.1 <| (encode_iff.2 this).of_eq fun n =>
show _ = encode ((@decode α _ n).bind fun _ => _) by
rcases @decode α _ n with - | a; · rfl
dsimp [Option.guard]
by_cases h : p a <;> simp [h]; rfl⟩
instance fin {n} : Primcodable (Fin n) :=
@ofEquiv _ _ (subtype <| nat_lt.comp .id (const n)) Fin.equivSubtype
instance vector {n} : Primcodable (List.Vector α n) :=
subtype ((@Primrec.eq ℕ _ _).comp list_length (const _))
instance finArrow {n} : Primcodable (Fin n → α) :=
ofEquiv _ (Equiv.vectorEquivFin _ _).symm
section ULower
attribute [local instance] Encodable.decidableRangeEncode Encodable.decidableEqOfEncodable
theorem mem_range_encode : PrimrecPred (fun n => n ∈ Set.range (encode : α → ℕ)) :=
have : PrimrecPred fun n => Encodable.decode₂ α n ≠ none :=
.not
(Primrec.eq.comp
(.option_bind .decode
(.ite (Primrec.eq.comp (Primrec.encode.comp .snd) .fst)
(Primrec.option_some.comp .snd) (.const _)))
(.const _))
this.of_eq fun _ => decode₂_ne_none_iff
instance ulower : Primcodable (ULower α) :=
Primcodable.subtype mem_range_encode
end ULower
end Primcodable
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem subtype_val {p : α → Prop} [DecidablePred p] {hp : PrimrecPred p} :
haveI := Primcodable.subtype hp
Primrec (@Subtype.val α p) := by
letI := Primcodable.subtype hp
refine (@Primcodable.prim (Subtype p)).of_eq fun n => ?_
rcases @decode (Subtype p) _ n with (_ | ⟨a, h⟩) <;> rfl
theorem subtype_val_iff {p : β → Prop} [DecidablePred p] {hp : PrimrecPred p} {f : α → Subtype p} :
haveI := Primcodable.subtype hp
(Primrec fun a => (f a).1) ↔ Primrec f := by
letI := Primcodable.subtype hp
refine ⟨fun h => ?_, fun hf => subtype_val.comp hf⟩
refine Nat.Primrec.of_eq h fun n => ?_
rcases @decode α _ n with - | a; · rfl
simp; rfl
theorem subtype_mk {p : β → Prop} [DecidablePred p] {hp : PrimrecPred p} {f : α → β}
{h : ∀ a, p (f a)} (hf : Primrec f) :
haveI := Primcodable.subtype hp
Primrec fun a => @Subtype.mk β p (f a) (h a) :=
subtype_val_iff.1 hf
theorem option_get {f : α → Option β} {h : ∀ a, (f a).isSome} :
Primrec f → Primrec fun a => (f a).get (h a) := by
intro hf
refine (Nat.Primrec.pred.comp hf).of_eq fun n => ?_
generalize hx : @decode α _ n = x
cases x <;> simp
theorem ulower_down : Primrec (ULower.down : α → ULower α) :=
letI : ∀ a, Decidable (a ∈ Set.range (encode : α → ℕ)) := decidableRangeEncode _
subtype_mk .encode
theorem ulower_up : Primrec (ULower.up : ULower α → α) :=
letI : ∀ a, Decidable (a ∈ Set.range (encode : α → ℕ)) := decidableRangeEncode _
option_get (Primrec.decode₂.comp subtype_val)
theorem fin_val_iff {n} {f : α → Fin n} : (Primrec fun a => (f a).1) ↔ Primrec f := by
letI : Primcodable { a // id a < n } := Primcodable.subtype (nat_lt.comp .id (const _))
exact (Iff.trans (by rfl) subtype_val_iff).trans (of_equiv_iff _)
theorem fin_val {n} : Primrec (fun (i : Fin n) => (i : ℕ)) :=
fin_val_iff.2 .id
theorem fin_succ {n} : Primrec (@Fin.succ n) :=
fin_val_iff.1 <| by simp [succ.comp fin_val]
theorem vector_toList {n} : Primrec (@List.Vector.toList α n) :=
subtype_val
theorem vector_toList_iff {n} {f : α → List.Vector β n} :
(Primrec fun a => (f a).toList) ↔ Primrec f :=
subtype_val_iff
theorem vector_cons {n} : Primrec₂ (@List.Vector.cons α n) :=
vector_toList_iff.1 <| by simpa using list_cons.comp fst (vector_toList_iff.2 snd)
theorem vector_length {n} : Primrec (@List.Vector.length α n) :=
const _
theorem vector_head {n} : Primrec (@List.Vector.head α n) :=
option_some_iff.1 <| (list_head?.comp vector_toList).of_eq fun ⟨_ :: _, _⟩ => rfl
theorem vector_tail {n} : Primrec (@List.Vector.tail α n) :=
vector_toList_iff.1 <| (list_tail.comp vector_toList).of_eq fun ⟨l, h⟩ => by cases l <;> rfl
theorem vector_get {n} : Primrec₂ (@List.Vector.get α n) :=
option_some_iff.1 <|
(list_getElem?.comp (vector_toList.comp fst) (fin_val.comp snd)).of_eq fun a => by
simp [Vector.get_eq_get_toList]
theorem list_ofFn :
∀ {n} {f : Fin n → α → σ}, (∀ i, Primrec (f i)) → Primrec fun a => List.ofFn fun i => f i a
| 0, _, _ => by simp only [List.ofFn_zero]; exact const []
| n + 1, f, hf => by
simpa [List.ofFn_succ] using list_cons.comp (hf 0) (list_ofFn fun i => hf i.succ)
theorem vector_ofFn {n} {f : Fin n → α → σ} (hf : ∀ i, Primrec (f i)) :
Primrec fun a => List.Vector.ofFn fun i => f i a :=
vector_toList_iff.1 <| by simp [list_ofFn hf]
theorem vector_get' {n} : Primrec (@List.Vector.get α n) :=
of_equiv_symm
theorem vector_ofFn' {n} : Primrec (@List.Vector.ofFn α n) :=
of_equiv
theorem fin_app {n} : Primrec₂ (@id (Fin n → σ)) :=
(vector_get.comp (vector_ofFn'.comp fst) snd).of_eq fun ⟨v, i⟩ => by simp
theorem fin_curry₁ {n} {f : Fin n → α → σ} : Primrec₂ f ↔ ∀ i, Primrec (f i) :=
⟨fun h i => h.comp (const i) .id, fun h =>
(vector_get.comp ((vector_ofFn h).comp snd) fst).of_eq fun a => by simp⟩
theorem fin_curry {n} {f : α → Fin n → σ} : Primrec f ↔ Primrec₂ f :=
⟨fun h => fin_app.comp (h.comp fst) snd, fun h =>
(vector_get'.comp
(vector_ofFn fun i => show Primrec fun a => f a i from h.comp .id (const i))).of_eq
fun a => by funext i; simp⟩
end Primrec
namespace Nat
open List.Vector
/-- An alternative inductive definition of `Primrec` which
does not use the pairing function on ℕ, and so has to
work with n-ary functions on ℕ instead of unary functions.
We prove that this is equivalent to the regular notion
in `to_prim` and `of_prim`. -/
inductive Primrec' : ∀ {n}, (List.Vector ℕ n → ℕ) → Prop
| zero : @Primrec' 0 fun _ => 0
| succ : @Primrec' 1 fun v => succ v.head
| get {n} (i : Fin n) : Primrec' fun v => v.get i
| comp {m n f} (g : Fin n → List.Vector ℕ m → ℕ) :
Primrec' f → (∀ i, Primrec' (g i)) → Primrec' fun a => f (List.Vector.ofFn fun i => g i a)
| prec {n f g} :
@Primrec' n f →
@Primrec' (n + 2) g →
Primrec' fun v : List.Vector ℕ (n + 1) =>
v.head.rec (f v.tail) fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)
end Nat
namespace Nat.Primrec'
open List.Vector Primrec
theorem to_prim {n f} (pf : @Nat.Primrec' n f) : Primrec f := by
induction pf with
| zero => exact .const 0
| succ => exact _root_.Primrec.succ.comp .vector_head
| get i => exact Primrec.vector_get.comp .id (.const i)
| comp _ _ _ hf hg => exact hf.comp (.vector_ofFn fun i => hg i)
| @prec n f g _ _ hf hg =>
exact
.nat_rec' .vector_head (hf.comp Primrec.vector_tail)
(hg.comp <|
Primrec.vector_cons.comp (Primrec.fst.comp .snd) <|
Primrec.vector_cons.comp (Primrec.snd.comp .snd) <|
(@Primrec.vector_tail _ _ (n + 1)).comp .fst).to₂
theorem of_eq {n} {f g : List.Vector ℕ n → ℕ} (hf : Primrec' f) (H : ∀ i, f i = g i) :
Primrec' g :=
(funext H : f = g) ▸ hf
theorem const {n} : ∀ m, @Primrec' n fun _ => m
| 0 => zero.comp Fin.elim0 fun i => i.elim0
| m + 1 => succ.comp _ fun _ => const m
theorem head {n : ℕ} : @Primrec' n.succ head :=
(get 0).of_eq fun v => by simp [get_zero]
theorem tail {n f} (hf : @Primrec' n f) : @Primrec' n.succ fun v => f v.tail :=
(hf.comp _ fun i => @get _ i.succ).of_eq fun v => by
rw [← ofFn_get v.tail]; congr; funext i; simp
/-- A function from vectors to vectors is primitive recursive when all of its projections are. -/
def Vec {n m} (f : List.Vector ℕ n → List.Vector ℕ m) : Prop :=
∀ i, Primrec' fun v => (f v).get i
protected theorem nil {n} : @Vec n 0 fun _ => nil := fun i => i.elim0
protected theorem cons {n m f g} (hf : @Primrec' n f) (hg : @Vec n m g) :
Vec fun v => f v ::ᵥ g v := fun i => Fin.cases (by simp [*]) (fun i => by simp [hg i]) i
theorem idv {n} : @Vec n n id :=
get
theorem comp' {n m f g} (hf : @Primrec' m f) (hg : @Vec n m g) : Primrec' fun v => f (g v) :=
(hf.comp _ hg).of_eq fun v => by simp
theorem comp₁ (f : ℕ → ℕ) (hf : @Primrec' 1 fun v => f v.head) {n g} (hg : @Primrec' n g) :
Primrec' fun v => f (g v) :=
| hf.comp _ fun _ => hg
theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @Primrec' 2 fun v => f v.head v.tail.head) {n g h}
(hg : @Primrec' n g) (hh : @Primrec' n h) : Primrec' fun v => f (g v) (h v) := by
simpa using hf.comp' (hg.cons <| hh.cons Primrec'.nil)
| Mathlib/Computability/Primrec.lean | 1,313 | 1,318 |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Logic.Encodable.Pi
import Mathlib.Logic.Function.Iterate
/-!
# The primitive recursive functions
The primitive recursive functions are the least collection of functions
`ℕ → ℕ` which are closed under projections (using the `pair`
pairing function), composition, zero, successor, and primitive recursion
(i.e. `Nat.rec` where the motive is `C n := ℕ`).
We can extend this definition to a large class of basic types by
using canonical encodings of types as natural numbers (Gödel numbering),
which we implement through the type class `Encodable`. (More precisely,
we need that the composition of encode with decode yields a
primitive recursive function, so we have the `Primcodable` type class
for this.)
In the above, the pairing function is primitive recursive by definition.
This deviates from the textbook definition of primitive recursive functions,
which instead work with *`n`-ary* functions. We formalize the textbook
definition in `Nat.Primrec'`. `Nat.Primrec'.prim_iff` then proves it is
equivalent to our chosen formulation. For more discussionn of this and
other design choices in this formalization, see [carneiro2019].
## Main definitions
- `Nat.Primrec f`: `f` is primitive recursive, for functions `f : ℕ → ℕ`
- `Primrec f`: `f` is primitive recursive, for functions between `Primcodable` types
- `Primcodable α`: well-behaved encoding of `α` into `ℕ`, i.e. one such that roundtripping through
the encoding functions adds no computational power
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open List (Vector)
open Denumerable Encodable Function
namespace Nat
/-- Calls the given function on a pair of entries `n`, encoded via the pairing function. -/
@[simp, reducible]
def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α :=
f n.unpair.1 n.unpair.2
/-- The primitive recursive functions `ℕ → ℕ`. -/
protected inductive Primrec : (ℕ → ℕ) → Prop
| zero : Nat.Primrec fun _ => 0
| protected succ : Nat.Primrec succ
| left : Nat.Primrec fun n => n.unpair.1
| right : Nat.Primrec fun n => n.unpair.2
| pair {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => pair (f n) (g n)
| comp {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => f (g n)
| prec {f g} :
Nat.Primrec f →
Nat.Primrec g →
Nat.Primrec (unpaired fun z n => n.rec (f z) fun y IH => g <| pair z <| pair y IH)
namespace Primrec
theorem of_eq {f g : ℕ → ℕ} (hf : Nat.Primrec f) (H : ∀ n, f n = g n) : Nat.Primrec g :=
(funext H : f = g) ▸ hf
theorem const : ∀ n : ℕ, Nat.Primrec fun _ => n
| 0 => zero
| n + 1 => Primrec.succ.comp (const n)
protected theorem id : Nat.Primrec id :=
(left.pair right).of_eq fun n => by simp
theorem prec1 {f} (m : ℕ) (hf : Nat.Primrec f) :
Nat.Primrec fun n => n.rec m fun y IH => f <| Nat.pair y IH :=
((prec (const m) (hf.comp right)).comp (zero.pair Primrec.id)).of_eq fun n => by simp
theorem casesOn1 {f} (m : ℕ) (hf : Nat.Primrec f) : Nat.Primrec (Nat.casesOn · m f) :=
(prec1 m (hf.comp left)).of_eq <| by simp
-- Porting note: `Nat.Primrec.casesOn` is already declared as a recursor.
theorem casesOn' {f g} (hf : Nat.Primrec f) (hg : Nat.Primrec g) :
Nat.Primrec (unpaired fun z n => n.casesOn (f z) fun y => g <| Nat.pair z y) :=
(prec hf (hg.comp (pair left (left.comp right)))).of_eq fun n => by simp
protected theorem swap : Nat.Primrec (unpaired (swap Nat.pair)) :=
(pair right left).of_eq fun n => by simp
theorem swap' {f} (hf : Nat.Primrec (unpaired f)) : Nat.Primrec (unpaired (swap f)) :=
(hf.comp .swap).of_eq fun n => by simp
theorem pred : Nat.Primrec pred :=
(casesOn1 0 Primrec.id).of_eq fun n => by cases n <;> simp [*]
theorem add : Nat.Primrec (unpaired (· + ·)) :=
(prec .id ((Primrec.succ.comp right).comp right)).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.add_assoc]
theorem sub : Nat.Primrec (unpaired (· - ·)) :=
(prec .id ((pred.comp right).comp right)).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.sub_add_eq]
theorem mul : Nat.Primrec (unpaired (· * ·)) :=
(prec zero (add.comp (pair left (right.comp right)))).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, mul_succ, add_comm _ (unpair p).fst]
theorem pow : Nat.Primrec (unpaired (· ^ ·)) :=
(prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq fun p => by
simp; induction p.unpair.2 <;> simp [*, Nat.pow_succ]
end Primrec
end Nat
/-- A `Primcodable` type is, essentially, an `Encodable` type for which
the encode/decode functions are primitive recursive.
However, such a definition is circular.
Instead, we ask that the composition of `decode : ℕ → Option α` with
`encode : Option α → ℕ` is primitive recursive. Said composition is
the identity function, restricted to the image of `encode`.
Thus, in a way, the added requirement ensures that no predicates
can be smuggled in through a cunning choice of the subset of `ℕ` into
which the type is encoded. -/
class Primcodable (α : Type*) extends Encodable α where
-- Porting note: was `prim [] `.
-- This means that `prim` does not take the type explicitly in Lean 4
prim : Nat.Primrec fun n => Encodable.encode (decode n)
namespace Primcodable
open Nat.Primrec
instance (priority := 10) ofDenumerable (α) [Denumerable α] : Primcodable α :=
⟨Nat.Primrec.succ.of_eq <| by simp⟩
/-- Builds a `Primcodable` instance from an equivalence to a `Primcodable` type. -/
def ofEquiv (α) {β} [Primcodable α] (e : β ≃ α) : Primcodable β :=
{ __ := Encodable.ofEquiv α e
prim := (@Primcodable.prim α _).of_eq fun n => by
rw [decode_ofEquiv]
cases (@decode α _ n) <;>
simp [encode_ofEquiv] }
instance empty : Primcodable Empty :=
⟨zero⟩
instance unit : Primcodable PUnit :=
⟨(casesOn1 1 zero).of_eq fun n => by cases n <;> simp⟩
instance option {α : Type*} [h : Primcodable α] : Primcodable (Option α) :=
⟨(casesOn1 1 ((casesOn1 0 (.comp .succ .succ)).comp (@Primcodable.prim α _))).of_eq fun n => by
cases n with
| zero => rfl
| succ n =>
rw [decode_option_succ]
cases H : @decode α _ n <;> simp [H]⟩
instance bool : Primcodable Bool :=
⟨(casesOn1 1 (casesOn1 2 zero)).of_eq fun n => match n with
| 0 => rfl
| 1 => rfl
| (n + 2) => by rw [decode_ge_two] <;> simp⟩
end Primcodable
/-- `Primrec f` means `f` is primitive recursive (after
encoding its input and output as natural numbers). -/
def Primrec {α β} [Primcodable α] [Primcodable β] (f : α → β) : Prop :=
Nat.Primrec fun n => encode ((@decode α _ n).map f)
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
open Nat.Primrec
protected theorem encode : Primrec (@encode α _) :=
(@Primcodable.prim α _).of_eq fun n => by cases @decode α _ n <;> rfl
protected theorem decode : Primrec (@decode α _) :=
Nat.Primrec.succ.comp (@Primcodable.prim α _)
theorem dom_denumerable {α β} [Denumerable α] [Primcodable β] {f : α → β} :
Primrec f ↔ Nat.Primrec fun n => encode (f (ofNat α n)) :=
⟨fun h => (pred.comp h).of_eq fun n => by simp, fun h =>
(Nat.Primrec.succ.comp h).of_eq fun n => by simp⟩
theorem nat_iff {f : ℕ → ℕ} : Primrec f ↔ Nat.Primrec f :=
dom_denumerable
theorem encdec : Primrec fun n => encode (@decode α _ n) :=
nat_iff.2 Primcodable.prim
theorem option_some : Primrec (@some α) :=
((casesOn1 0 (Nat.Primrec.succ.comp .succ)).comp (@Primcodable.prim α _)).of_eq fun n => by
cases @decode α _ n <;> simp
theorem of_eq {f g : α → σ} (hf : Primrec f) (H : ∀ n, f n = g n) : Primrec g :=
(funext H : f = g) ▸ hf
theorem const (x : σ) : Primrec fun _ : α => x :=
((casesOn1 0 (.const (encode x).succ)).comp (@Primcodable.prim α _)).of_eq fun n => by
cases @decode α _ n <;> rfl
protected theorem id : Primrec (@id α) :=
(@Primcodable.prim α).of_eq <| by simp
theorem comp {f : β → σ} {g : α → β} (hf : Primrec f) (hg : Primrec g) : Primrec fun a => f (g a) :=
((casesOn1 0 (.comp hf (pred.comp hg))).comp (@Primcodable.prim α _)).of_eq fun n => by
cases @decode α _ n <;> simp [encodek]
theorem succ : Primrec Nat.succ :=
nat_iff.2 Nat.Primrec.succ
theorem pred : Primrec Nat.pred :=
nat_iff.2 Nat.Primrec.pred
theorem encode_iff {f : α → σ} : (Primrec fun a => encode (f a)) ↔ Primrec f :=
⟨fun h => Nat.Primrec.of_eq h fun n => by cases @decode α _ n <;> rfl, Primrec.encode.comp⟩
theorem ofNat_iff {α β} [Denumerable α] [Primcodable β] {f : α → β} :
Primrec f ↔ Primrec fun n => f (ofNat α n) :=
dom_denumerable.trans <| nat_iff.symm.trans encode_iff
protected theorem ofNat (α) [Denumerable α] : Primrec (ofNat α) :=
ofNat_iff.1 Primrec.id
theorem option_some_iff {f : α → σ} : (Primrec fun a => some (f a)) ↔ Primrec f :=
⟨fun h => encode_iff.1 <| pred.comp <| encode_iff.2 h, option_some.comp⟩
theorem of_equiv {β} {e : β ≃ α} :
haveI := Primcodable.ofEquiv α e
Primrec e :=
letI : Primcodable β := Primcodable.ofEquiv α e
encode_iff.1 Primrec.encode
theorem of_equiv_symm {β} {e : β ≃ α} :
haveI := Primcodable.ofEquiv α e
Primrec e.symm :=
letI := Primcodable.ofEquiv α e
encode_iff.1 (show Primrec fun a => encode (e (e.symm a)) by simp [Primrec.encode])
theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} :
haveI := Primcodable.ofEquiv α e
(Primrec fun a => e (f a)) ↔ Primrec f :=
letI := Primcodable.ofEquiv α e
⟨fun h => (of_equiv_symm.comp h).of_eq fun a => by simp, of_equiv.comp⟩
theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} :
haveI := Primcodable.ofEquiv α e
(Primrec fun a => e.symm (f a)) ↔ Primrec f :=
letI := Primcodable.ofEquiv α e
⟨fun h => (of_equiv.comp h).of_eq fun a => by simp, of_equiv_symm.comp⟩
end Primrec
namespace Primcodable
open Nat.Primrec
instance prod {α β} [Primcodable α] [Primcodable β] : Primcodable (α × β) :=
⟨((casesOn' zero ((casesOn' zero .succ).comp (pair right ((@Primcodable.prim β).comp left)))).comp
(pair right ((@Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1; · simp
cases @decode β _ n.unpair.2 <;> simp⟩
end Primcodable
namespace Primrec
variable {α : Type*} [Primcodable α]
open Nat.Primrec
theorem fst {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.fst α β) :=
((casesOn' zero
((casesOn' zero (Nat.Primrec.succ.comp left)).comp
(pair right ((@Primcodable.prim β).comp left)))).comp
(pair right ((@Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1 <;> simp
cases @decode β _ n.unpair.2 <;> simp
theorem snd {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.snd α β) :=
((casesOn' zero
((casesOn' zero (Nat.Primrec.succ.comp right)).comp
(pair right ((@Primcodable.prim β).comp left)))).comp
(pair right ((@Primcodable.prim α).comp left))).of_eq
fun n => by
simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val]
cases @decode α _ n.unpair.1 <;> simp
cases @decode β _ n.unpair.2 <;> simp
theorem pair {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {f : α → β} {g : α → γ}
(hf : Primrec f) (hg : Primrec g) : Primrec fun a => (f a, g a) :=
((casesOn1 0
(Nat.Primrec.succ.comp <|
.pair (Nat.Primrec.pred.comp hf) (Nat.Primrec.pred.comp hg))).comp
(@Primcodable.prim α _)).of_eq
fun n => by cases @decode α _ n <;> simp [encodek]
theorem unpair : Primrec Nat.unpair :=
(pair (nat_iff.2 .left) (nat_iff.2 .right)).of_eq fun n => by simp
theorem list_getElem?₁ : ∀ l : List α, Primrec (l[·]? : ℕ → Option α)
| [] => dom_denumerable.2 zero
| a :: l =>
dom_denumerable.2 <|
(casesOn1 (encode a).succ <| dom_denumerable.1 <| list_getElem?₁ l).of_eq fun n => by
cases n <;> simp
@[deprecated (since := "2025-02-14")] alias list_get?₁ := list_getElem?₁
end Primrec
/-- `Primrec₂ f` means `f` is a binary primitive recursive function.
This is technically unnecessary since we can always curry all
the arguments together, but there are enough natural two-arg
functions that it is convenient to express this directly. -/
def Primrec₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] (f : α → β → σ) :=
Primrec fun p : α × β => f p.1 p.2
/-- `PrimrecPred p` means `p : α → Prop` is a (decidable)
primitive recursive predicate, which is to say that
`decide ∘ p : α → Bool` is primitive recursive. -/
def PrimrecPred {α} [Primcodable α] (p : α → Prop) [DecidablePred p] :=
Primrec fun a => decide (p a)
/-- `PrimrecRel p` means `p : α → β → Prop` is a (decidable)
primitive recursive relation, which is to say that
`decide ∘ p : α → β → Bool` is primitive recursive. -/
def PrimrecRel {α β} [Primcodable α] [Primcodable β] (s : α → β → Prop)
[∀ a b, Decidable (s a b)] :=
Primrec₂ fun a b => decide (s a b)
namespace Primrec₂
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem mk {f : α → β → σ} (hf : Primrec fun p : α × β => f p.1 p.2) : Primrec₂ f := hf
theorem of_eq {f g : α → β → σ} (hg : Primrec₂ f) (H : ∀ a b, f a b = g a b) : Primrec₂ g :=
(by funext a b; apply H : f = g) ▸ hg
theorem const (x : σ) : Primrec₂ fun (_ : α) (_ : β) => x :=
Primrec.const _
protected theorem pair : Primrec₂ (@Prod.mk α β) :=
Primrec.pair .fst .snd
theorem left : Primrec₂ fun (a : α) (_ : β) => a :=
.fst
theorem right : Primrec₂ fun (_ : α) (b : β) => b :=
.snd
theorem natPair : Primrec₂ Nat.pair := by simp [Primrec₂, Primrec]; constructor
theorem unpaired {f : ℕ → ℕ → α} : Primrec (Nat.unpaired f) ↔ Primrec₂ f :=
⟨fun h => by simpa using h.comp natPair, fun h => h.comp Primrec.unpair⟩
theorem unpaired' {f : ℕ → ℕ → ℕ} : Nat.Primrec (Nat.unpaired f) ↔ Primrec₂ f :=
Primrec.nat_iff.symm.trans unpaired
theorem encode_iff {f : α → β → σ} : (Primrec₂ fun a b => encode (f a b)) ↔ Primrec₂ f :=
Primrec.encode_iff
theorem option_some_iff {f : α → β → σ} : (Primrec₂ fun a b => some (f a b)) ↔ Primrec₂ f :=
Primrec.option_some_iff
theorem ofNat_iff {α β σ} [Denumerable α] [Denumerable β] [Primcodable σ] {f : α → β → σ} :
Primrec₂ f ↔ Primrec₂ fun m n : ℕ => f (ofNat α m) (ofNat β n) :=
(Primrec.ofNat_iff.trans <| by simp).trans unpaired
theorem uncurry {f : α → β → σ} : Primrec (Function.uncurry f) ↔ Primrec₂ f := by
rw [show Function.uncurry f = fun p : α × β => f p.1 p.2 from funext fun ⟨a, b⟩ => rfl]; rfl
theorem curry {f : α × β → σ} : Primrec₂ (Function.curry f) ↔ Primrec f := by
rw [← uncurry, Function.uncurry_curry]
end Primrec₂
section Comp
variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ]
theorem Primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun a b => f (g a b) :=
hf.comp hg
theorem Primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : Primrec₂ f) (hg : Primrec g)
(hh : Primrec h) : Primrec fun a => f (g a) (h a) :=
Primrec.comp hf (hg.pair hh)
theorem Primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : Primrec₂ f)
(hg : Primrec₂ g) (hh : Primrec₂ h) : Primrec₂ fun a b => f (g a b) (h a b) :=
hf.comp hg hh
theorem PrimrecPred.comp {p : β → Prop} [DecidablePred p] {f : α → β} :
PrimrecPred p → Primrec f → PrimrecPred fun a => p (f a) :=
Primrec.comp
theorem PrimrecRel.comp {R : β → γ → Prop} [∀ a b, Decidable (R a b)] {f : α → β} {g : α → γ} :
PrimrecRel R → Primrec f → Primrec g → PrimrecPred fun a => R (f a) (g a) :=
Primrec₂.comp
theorem PrimrecRel.comp₂ {R : γ → δ → Prop} [∀ a b, Decidable (R a b)] {f : α → β → γ}
{g : α → β → δ} :
PrimrecRel R → Primrec₂ f → Primrec₂ g → PrimrecRel fun a b => R (f a b) (g a b) :=
PrimrecRel.comp
end Comp
theorem PrimrecPred.of_eq {α} [Primcodable α] {p q : α → Prop} [DecidablePred p] [DecidablePred q]
(hp : PrimrecPred p) (H : ∀ a, p a ↔ q a) : PrimrecPred q :=
Primrec.of_eq hp fun a => Bool.decide_congr (H a)
theorem PrimrecRel.of_eq {α β} [Primcodable α] [Primcodable β] {r s : α → β → Prop}
[∀ a b, Decidable (r a b)] [∀ a b, Decidable (s a b)] (hr : PrimrecRel r)
(H : ∀ a b, r a b ↔ s a b) : PrimrecRel s :=
Primrec₂.of_eq hr fun a b => Bool.decide_congr (H a b)
namespace Primrec₂
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
open Nat.Primrec
theorem swap {f : α → β → σ} (h : Primrec₂ f) : Primrec₂ (swap f) :=
h.comp₂ Primrec₂.right Primrec₂.left
theorem nat_iff {f : α → β → σ} : Primrec₂ f ↔ Nat.Primrec
(.unpaired fun m n => encode <| (@decode α _ m).bind fun a => (@decode β _ n).map (f a)) := by
have :
∀ (a : Option α) (b : Option β),
Option.map (fun p : α × β => f p.1 p.2)
(Option.bind a fun a : α => Option.map (Prod.mk a) b) =
Option.bind a fun a => Option.map (f a) b := fun a b => by
cases a <;> cases b <;> rfl
simp [Primrec₂, Primrec, this]
theorem nat_iff' {f : α → β → σ} :
Primrec₂ f ↔
Primrec₂ fun m n : ℕ => (@decode α _ m).bind fun a => Option.map (f a) (@decode β _ n) :=
nat_iff.trans <| unpaired'.trans encode_iff
end Primrec₂
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem to₂ {f : α × β → σ} (hf : Primrec f) : Primrec₂ fun a b => f (a, b) :=
hf.of_eq fun _ => rfl
theorem nat_rec {f : α → β} {g : α → ℕ × β → β} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun a (n : ℕ) => n.rec (motive := fun _ => β) (f a) fun n IH => g a (n, IH) :=
Primrec₂.nat_iff.2 <|
((Nat.Primrec.casesOn' .zero <|
(Nat.Primrec.prec hf <|
.comp hg <|
Nat.Primrec.left.pair <|
(Nat.Primrec.left.comp .right).pair <|
Nat.Primrec.pred.comp <| Nat.Primrec.right.comp .right).comp <|
Nat.Primrec.right.pair <| Nat.Primrec.right.comp Nat.Primrec.left).comp <|
Nat.Primrec.id.pair <| (@Primcodable.prim α).comp Nat.Primrec.left).of_eq
fun n => by
simp only [Nat.unpaired, id_eq, Nat.unpair_pair, decode_prod_val, decode_nat,
Option.some_bind, Option.map_map, Option.map_some']
rcases @decode α _ n.unpair.1 with - | a; · rfl
simp only [Nat.pred_eq_sub_one, encode_some, Nat.succ_eq_add_one, encodek, Option.map_some',
Option.some_bind, Option.map_map]
induction' n.unpair.2 with m <;> simp [encodek]
simp [*, encodek]
theorem nat_rec' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β}
(hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) :
Primrec fun a => (f a).rec (motive := fun _ => β) (g a) fun n IH => h a (n, IH) :=
(nat_rec hg hh).comp .id hf
theorem nat_rec₁ {f : ℕ → α → α} (a : α) (hf : Primrec₂ f) : Primrec (Nat.rec a f) :=
nat_rec' .id (const a) <| comp₂ hf Primrec₂.right
theorem nat_casesOn' {f : α → β} {g : α → ℕ → β} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec₂ fun a (n : ℕ) => (n.casesOn (f a) (g a) : β) :=
nat_rec hf <| hg.comp₂ Primrec₂.left <| comp₂ fst Primrec₂.right
theorem nat_casesOn {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : Primrec f) (hg : Primrec g)
(hh : Primrec₂ h) : Primrec fun a => ((f a).casesOn (g a) (h a) : β) :=
(nat_casesOn' hg hh).comp .id hf
theorem nat_casesOn₁ {f : ℕ → α} (a : α) (hf : Primrec f) :
Primrec (fun (n : ℕ) => (n.casesOn a f : α)) :=
nat_casesOn .id (const a) (comp₂ hf .right)
theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : Primrec f) (hg : Primrec g)
(hh : Primrec₂ h) : Primrec fun a => (h a)^[f a] (g a) :=
(nat_rec' hf hg (hh.comp₂ Primrec₂.left <| snd.comp₂ Primrec₂.right)).of_eq fun a => by
induction f a <;> simp [*, -Function.iterate_succ, Function.iterate_succ']
theorem option_casesOn {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : Primrec o)
(hf : Primrec f) (hg : Primrec₂ g) :
@Primrec _ σ _ _ fun a => Option.casesOn (o a) (f a) (g a) :=
encode_iff.1 <|
(nat_casesOn (encode_iff.2 ho) (encode_iff.2 hf) <|
pred.comp₂ <|
Primrec₂.encode_iff.2 <|
(Primrec₂.nat_iff'.1 hg).comp₂ ((@Primrec.encode α _).comp fst).to₂
Primrec₂.right).of_eq
fun a => by rcases o a with - | b <;> simp [encodek]
theorem option_bind {f : α → Option β} {g : α → β → Option σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec fun a => (f a).bind (g a) :=
(option_casesOn hf (const none) hg).of_eq fun a => by cases f a <;> rfl
theorem option_bind₁ {f : α → Option σ} (hf : Primrec f) : Primrec fun o => Option.bind o f :=
option_bind .id (hf.comp snd).to₂
theorem option_map {f : α → Option β} {g : α → β → σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec fun a => (f a).map (g a) :=
(option_bind hf (option_some.comp₂ hg)).of_eq fun x => by cases f x <;> rfl
theorem option_map₁ {f : α → σ} (hf : Primrec f) : Primrec (Option.map f) :=
option_map .id (hf.comp snd).to₂
theorem option_iget [Inhabited α] : Primrec (@Option.iget α _) :=
(option_casesOn .id (const <| @default α _) .right).of_eq fun o => by cases o <;> rfl
theorem option_isSome : Primrec (@Option.isSome α) :=
(option_casesOn .id (const false) (const true).to₂).of_eq fun o => by cases o <;> rfl
theorem option_getD : Primrec₂ (@Option.getD α) :=
Primrec.of_eq (option_casesOn Primrec₂.left Primrec₂.right .right) fun ⟨o, a⟩ => by
cases o <;> rfl
theorem bind_decode_iff {f : α → β → Option σ} :
(Primrec₂ fun a n => (@decode β _ n).bind (f a)) ↔ Primrec₂ f :=
⟨fun h => by simpa [encodek] using h.comp fst ((@Primrec.encode β _).comp snd), fun h =>
option_bind (Primrec.decode.comp snd) <| h.comp (fst.comp fst) snd⟩
theorem map_decode_iff {f : α → β → σ} :
(Primrec₂ fun a n => (@decode β _ n).map (f a)) ↔ Primrec₂ f := by
simp only [Option.map_eq_bind]
exact bind_decode_iff.trans Primrec₂.option_some_iff
theorem nat_add : Primrec₂ ((· + ·) : ℕ → ℕ → ℕ) :=
Primrec₂.unpaired'.1 Nat.Primrec.add
theorem nat_sub : Primrec₂ ((· - ·) : ℕ → ℕ → ℕ) :=
Primrec₂.unpaired'.1 Nat.Primrec.sub
theorem nat_mul : Primrec₂ ((· * ·) : ℕ → ℕ → ℕ) :=
Primrec₂.unpaired'.1 Nat.Primrec.mul
theorem cond {c : α → Bool} {f : α → σ} {g : α → σ} (hc : Primrec c) (hf : Primrec f)
(hg : Primrec g) : Primrec fun a => bif (c a) then (f a) else (g a) :=
(nat_casesOn (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq fun a => by cases c a <;> rfl
theorem ite {c : α → Prop} [DecidablePred c] {f : α → σ} {g : α → σ} (hc : PrimrecPred c)
(hf : Primrec f) (hg : Primrec g) : Primrec fun a => if c a then f a else g a := by
simpa [Bool.cond_decide] using cond hc hf hg
theorem nat_le : PrimrecRel ((· ≤ ·) : ℕ → ℕ → Prop) :=
(nat_casesOn nat_sub (const true) (const false).to₂).of_eq fun p => by
dsimp [swap]
rcases e : p.1 - p.2 with - | n
· simp [Nat.sub_eq_zero_iff_le.1 e]
· simp [not_le.2 (Nat.lt_of_sub_eq_succ e)]
theorem nat_min : Primrec₂ (@min ℕ _) :=
ite nat_le fst snd
theorem nat_max : Primrec₂ (@max ℕ _) :=
ite (nat_le.comp fst snd) snd fst
theorem dom_bool (f : Bool → α) : Primrec f :=
(cond .id (const (f true)) (const (f false))).of_eq fun b => by cases b <;> rfl
theorem dom_bool₂ (f : Bool → Bool → α) : Primrec₂ f :=
(cond fst ((dom_bool (f true)).comp snd) ((dom_bool (f false)).comp snd)).of_eq fun ⟨a, b⟩ => by
cases a <;> rfl
protected theorem not : Primrec not :=
dom_bool _
protected theorem and : Primrec₂ and :=
dom_bool₂ _
protected theorem or : Primrec₂ or :=
dom_bool₂ _
theorem _root_.PrimrecPred.not {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) :
PrimrecPred fun a => ¬p a :=
(Primrec.not.comp hp).of_eq fun n => by simp
theorem _root_.PrimrecPred.and {p q : α → Prop} [DecidablePred p] [DecidablePred q]
(hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a ∧ q a :=
(Primrec.and.comp hp hq).of_eq fun n => by simp
theorem _root_.PrimrecPred.or {p q : α → Prop} [DecidablePred p] [DecidablePred q]
(hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a ∨ q a :=
(Primrec.or.comp hp hq).of_eq fun n => by simp
protected theorem beq [DecidableEq α] : Primrec₂ (@BEq.beq α _) :=
have : PrimrecRel fun a b : ℕ => a = b :=
(PrimrecPred.and nat_le nat_le.swap).of_eq fun a => by simp [le_antisymm_iff]
(this.comp₂ (Primrec.encode.comp₂ Primrec₂.left) (Primrec.encode.comp₂ Primrec₂.right)).of_eq
fun _ _ => encode_injective.eq_iff
protected theorem eq [DecidableEq α] : PrimrecRel (@Eq α) := Primrec.beq
theorem nat_lt : PrimrecRel ((· < ·) : ℕ → ℕ → Prop) :=
(nat_le.comp snd fst).not.of_eq fun p => by simp
theorem option_guard {p : α → β → Prop} [∀ a b, Decidable (p a b)] (hp : PrimrecRel p) {f : α → β}
(hf : Primrec f) : Primrec fun a => Option.guard (p a) (f a) :=
ite (hp.comp Primrec.id hf) (option_some_iff.2 hf) (const none)
theorem option_orElse : Primrec₂ ((· <|> ·) : Option α → Option α → Option α) :=
(option_casesOn fst snd (fst.comp fst).to₂).of_eq fun ⟨o₁, o₂⟩ => by cases o₁ <;> cases o₂ <;> rfl
protected theorem decode₂ : Primrec (decode₂ α) :=
option_bind .decode <|
option_guard (Primrec.beq.comp₂ (by exact encode_iff.mpr snd) (by exact fst.comp fst)) snd
theorem list_findIdx₁ {p : α → β → Bool} (hp : Primrec₂ p) :
∀ l : List β, Primrec fun a => l.findIdx (p a)
| [] => const 0
| a :: l => (cond (hp.comp .id (const a)) (const 0) (succ.comp (list_findIdx₁ hp l))).of_eq fun n =>
by simp [List.findIdx_cons]
theorem list_idxOf₁ [DecidableEq α] (l : List α) : Primrec fun a => l.idxOf a :=
list_findIdx₁ (.swap .beq) l
@[deprecated (since := "2025-01-30")] alias list_indexOf₁ := list_idxOf₁
theorem dom_fintype [Finite α] (f : α → σ) : Primrec f :=
let ⟨l, _, m⟩ := Finite.exists_univ_list α
option_some_iff.1 <| by
haveI := decidableEqOfEncodable α
refine ((list_getElem?₁ (l.map f)).comp (list_idxOf₁ l)).of_eq fun a => ?_
rw [List.getElem?_map, List.getElem?_idxOf (m a), Option.map_some']
-- Porting note: These are new lemmas
-- I added it because it actually simplified the proofs
-- and because I couldn't understand the original proof
/-- A function is `PrimrecBounded` if its size is bounded by a primitive recursive function -/
def PrimrecBounded (f : α → β) : Prop :=
∃ g : α → ℕ, Primrec g ∧ ∀ x, encode (f x) ≤ g x
theorem nat_findGreatest {f : α → ℕ} {p : α → ℕ → Prop} [∀ x n, Decidable (p x n)]
(hf : Primrec f) (hp : PrimrecRel p) : Primrec fun x => (f x).findGreatest (p x) :=
(nat_rec' (h := fun x nih => if p x (nih.1 + 1) then nih.1 + 1 else nih.2)
hf (const 0) (ite (hp.comp fst (snd |> fst.comp |> succ.comp))
(snd |> fst.comp |> succ.comp) (snd.comp snd))).of_eq fun x => by
induction f x <;> simp [Nat.findGreatest, *]
/-- To show a function `f : α → ℕ` is primitive recursive, it is enough to show that the function
is bounded by a primitive recursive function and that its graph is primitive recursive -/
theorem of_graph {f : α → ℕ} (h₁ : PrimrecBounded f)
(h₂ : PrimrecRel fun a b => f a = b) : Primrec f := by
rcases h₁ with ⟨g, pg, hg : ∀ x, f x ≤ g x⟩
refine (nat_findGreatest pg h₂).of_eq fun n => ?_
exact (Nat.findGreatest_spec (P := fun b => f n = b) (hg n) rfl).symm
-- We show that division is primitive recursive by showing that the graph is
theorem nat_div : Primrec₂ ((· / ·) : ℕ → ℕ → ℕ) := by
refine of_graph ⟨_, fst, fun p => Nat.div_le_self _ _⟩ ?_
have : PrimrecRel fun (a : ℕ × ℕ) (b : ℕ) => (a.2 = 0 ∧ b = 0) ∨
(0 < a.2 ∧ b * a.2 ≤ a.1 ∧ a.1 < (b + 1) * a.2) :=
PrimrecPred.or
(.and (const 0 |> Primrec.eq.comp (fst |> snd.comp)) (const 0 |> Primrec.eq.comp snd))
(.and (nat_lt.comp (const 0) (fst |> snd.comp)) <|
.and (nat_le.comp (nat_mul.comp snd (fst |> snd.comp)) (fst |> fst.comp))
(nat_lt.comp (fst.comp fst) (nat_mul.comp (Primrec.succ.comp snd) (snd.comp fst))))
refine this.of_eq ?_
rintro ⟨a, k⟩ q
if H : k = 0 then simp [H, eq_comm]
else
have : q * k ≤ a ∧ a < (q + 1) * k ↔ q = a / k := by
rw [le_antisymm_iff, ← (@Nat.lt_succ _ q), Nat.le_div_iff_mul_le (Nat.pos_of_ne_zero H),
Nat.div_lt_iff_lt_mul (Nat.pos_of_ne_zero H)]
simpa [H, zero_lt_iff, eq_comm (b := q)]
theorem nat_mod : Primrec₂ ((· % ·) : ℕ → ℕ → ℕ) :=
(nat_sub.comp fst (nat_mul.comp snd nat_div)).to₂.of_eq fun m n => by
apply Nat.sub_eq_of_eq_add
simp [add_comm (m % n), Nat.div_add_mod]
theorem nat_bodd : Primrec Nat.bodd :=
(Primrec.beq.comp (nat_mod.comp .id (const 2)) (const 1)).of_eq fun n => by
cases H : n.bodd <;> simp [Nat.mod_two_of_bodd, H]
theorem nat_div2 : Primrec Nat.div2 :=
(nat_div.comp .id (const 2)).of_eq fun n => n.div2_val.symm
theorem nat_double : Primrec (fun n : ℕ => 2 * n) :=
nat_mul.comp (const _) Primrec.id
theorem nat_double_succ : Primrec (fun n : ℕ => 2 * n + 1) :=
nat_double |> Primrec.succ.comp
end Primrec
section
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
variable (H : Nat.Primrec fun n => Encodable.encode (@decode (List β) _ n))
open Primrec
private def prim : Primcodable (List β) := ⟨H⟩
private theorem list_casesOn' {f : α → List β} {g : α → σ} {h : α → β × List β → σ}
(hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) :
@Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) :=
letI := prim H
have :
@Primrec _ (Option σ) _ _ fun a =>
(@decode (Option (β × List β)) _ (encode (f a))).map fun o => Option.casesOn o (g a) (h a) :=
((@map_decode_iff _ (Option (β × List β)) _ _ _ _ _).2 <|
to₂ <|
option_casesOn snd (hg.comp fst) (hh.comp₂ (fst.comp₂ Primrec₂.left) Primrec₂.right)).comp
.id (encode_iff.2 hf)
option_some_iff.1 <| this.of_eq fun a => by rcases f a with - | ⟨b, l⟩ <;> simp [encodek]
private theorem list_foldl' {f : α → List β} {g : α → σ} {h : α → σ × β → σ}
(hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) :
Primrec fun a => (f a).foldl (fun s b => h a (s, b)) (g a) := by
letI := prim H
let G (a : α) (IH : σ × List β) : σ × List β := List.casesOn IH.2 IH fun b l => (h a (IH.1, b), l)
have hG : Primrec₂ G := list_casesOn' H (snd.comp snd) snd <|
to₂ <|
pair (hh.comp (fst.comp fst) <| pair ((fst.comp snd).comp fst) (fst.comp snd))
(snd.comp snd)
let F := fun (a : α) (n : ℕ) => (G a)^[n] (g a, f a)
have hF : Primrec fun a => (F a (encode (f a))).1 :=
(fst.comp <|
nat_iterate (encode_iff.2 hf) (pair hg hf) <|
hG)
suffices ∀ a n, F a n = (((f a).take n).foldl (fun s b => h a (s, b)) (g a), (f a).drop n) by
refine hF.of_eq fun a => ?_
rw [this, List.take_of_length_le (length_le_encode _)]
introv
dsimp only [F]
generalize f a = l
generalize g a = x
induction n generalizing l x with
| zero => rfl
| succ n IH =>
simp only [iterate_succ, comp_apply]
rcases l with - | ⟨b, l⟩ <;> simp [G, IH]
private theorem list_cons' : (haveI := prim H; Primrec₂ (@List.cons β)) :=
letI := prim H
encode_iff.1 (succ.comp <| Primrec₂.natPair.comp (encode_iff.2 fst) (encode_iff.2 snd))
private theorem list_reverse' :
haveI := prim H
Primrec (@List.reverse β) :=
letI := prim H
(list_foldl' H .id (const []) <| to₂ <| ((list_cons' H).comp snd fst).comp snd).of_eq
(suffices ∀ l r, List.foldl (fun (s : List β) (b : β) => b :: s) r l = List.reverseAux l r from
fun l => this l []
fun l => by induction l <;> simp [*, List.reverseAux])
end
namespace Primcodable
variable {α : Type*} {β : Type*}
variable [Primcodable α] [Primcodable β]
open Primrec
instance sum : Primcodable (α ⊕ β) :=
⟨Primrec.nat_iff.1 <|
(encode_iff.2
(cond nat_bodd
(((@Primrec.decode β _).comp nat_div2).option_map <|
to₂ <| nat_double_succ.comp (Primrec.encode.comp snd))
(((@Primrec.decode α _).comp nat_div2).option_map <|
to₂ <| nat_double.comp (Primrec.encode.comp snd)))).of_eq
fun n =>
show _ = encode (decodeSum n) by
simp only [decodeSum, Nat.boddDiv2_eq]
cases Nat.bodd n <;> simp [decodeSum]
· cases @decode α _ n.div2 <;> rfl
· cases @decode β _ n.div2 <;> rfl⟩
instance list : Primcodable (List α) :=
⟨letI H := @Primcodable.prim (List ℕ) _
have : Primrec₂ fun (a : α) (o : Option (List ℕ)) => o.map (List.cons (encode a)) :=
option_map snd <| (list_cons' H).comp ((@Primrec.encode α _).comp (fst.comp fst)) snd
have :
Primrec fun n =>
(ofNat (List ℕ) n).reverse.foldl
(fun o m => (@decode α _ m).bind fun a => o.map (List.cons (encode a))) (some []) :=
list_foldl' H ((list_reverse' H).comp (.ofNat (List ℕ))) (const (some []))
(Primrec.comp₂ (bind_decode_iff.2 <| .swap this) Primrec₂.right)
nat_iff.1 <|
(encode_iff.2 this).of_eq fun n => by
rw [List.foldl_reverse]
apply Nat.case_strong_induction_on n; · simp
intro n IH; simp
rcases @decode α _ n.unpair.1 with - | a; · rfl
simp only [decode_eq_ofNat, Option.some.injEq, Option.some_bind, Option.map_some']
suffices ∀ (o : Option (List ℕ)) (p), encode o = encode p →
encode (Option.map (List.cons (encode a)) o) = encode (Option.map (List.cons a) p) from
this _ _ (IH _ (Nat.unpair_right_le n))
intro o p IH
cases o <;> cases p
· rfl
· injection IH
· injection IH
· exact congr_arg (fun k => (Nat.pair (encode a) k).succ.succ) (Nat.succ.inj IH)⟩
end Primcodable
namespace Primrec
variable {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable σ]
theorem sumInl : Primrec (@Sum.inl α β) :=
encode_iff.1 <| nat_double.comp Primrec.encode
theorem sumInr : Primrec (@Sum.inr α β) :=
encode_iff.1 <| nat_double_succ.comp Primrec.encode
@[deprecated (since := "2025-02-21")] alias sum_inl := Primrec.sumInl
@[deprecated (since := "2025-02-21")] alias sum_inr := Primrec.sumInr
theorem sumCasesOn {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : Primrec f)
(hg : Primrec₂ g) (hh : Primrec₂ h) : @Primrec _ σ _ _ fun a => Sum.casesOn (f a) (g a) (h a) :=
option_some_iff.1 <|
(cond (nat_bodd.comp <| encode_iff.2 hf)
(option_map (Primrec.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hh)
(option_map (Primrec.decode.comp <| nat_div2.comp <| encode_iff.2 hf) hg)).of_eq
fun a => by rcases f a with b | c <;> simp [Nat.div2_val, encodek]
@[deprecated (since := "2025-02-21")] alias sum_casesOn := Primrec.sumCasesOn
theorem list_cons : Primrec₂ (@List.cons α) :=
list_cons' Primcodable.prim
theorem list_casesOn {f : α → List β} {g : α → σ} {h : α → β × List β → σ} :
Primrec f →
Primrec g →
Primrec₂ h → @Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) :=
list_casesOn' Primcodable.prim
theorem list_foldl {f : α → List β} {g : α → σ} {h : α → σ × β → σ} :
Primrec f →
Primrec g → Primrec₂ h → Primrec fun a => (f a).foldl (fun s b => h a (s, b)) (g a) :=
list_foldl' Primcodable.prim
theorem list_reverse : Primrec (@List.reverse α) :=
list_reverse' Primcodable.prim
theorem list_foldr {f : α → List β} {g : α → σ} {h : α → β × σ → σ} (hf : Primrec f)
(hg : Primrec g) (hh : Primrec₂ h) :
Primrec fun a => (f a).foldr (fun b s => h a (b, s)) (g a) :=
(list_foldl (list_reverse.comp hf) hg <| to₂ <| hh.comp fst <| (pair snd fst).comp snd).of_eq
fun a => by simp [List.foldl_reverse]
theorem list_head? : Primrec (@List.head? α) :=
(list_casesOn .id (const none) (option_some_iff.2 <| fst.comp snd).to₂).of_eq fun l => by
cases l <;> rfl
theorem list_headI [Inhabited α] : Primrec (@List.headI α _) :=
(option_iget.comp list_head?).of_eq fun l => l.head!_eq_head?.symm
theorem list_tail : Primrec (@List.tail α) :=
(list_casesOn .id (const []) (snd.comp snd).to₂).of_eq fun l => by cases l <;> rfl
theorem list_rec {f : α → List β} {g : α → σ} {h : α → β × List β × σ → σ} (hf : Primrec f)
(hg : Primrec g) (hh : Primrec₂ h) :
@Primrec _ σ _ _ fun a => List.recOn (f a) (g a) fun b l IH => h a (b, l, IH) :=
let F (a : α) := (f a).foldr (fun (b : β) (s : List β × σ) => (b :: s.1, h a (b, s))) ([], g a)
have : Primrec F :=
list_foldr hf (pair (const []) hg) <|
to₂ <| pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh
(snd.comp this).of_eq fun a => by
suffices F a = (f a, List.recOn (f a) (g a) fun b l IH => h a (b, l, IH)) by rw [this]
dsimp [F]
induction' f a with b l IH <;> simp [*]
theorem list_getElem? : Primrec₂ ((·[·]? : List α → ℕ → Option α)) :=
let F (l : List α) (n : ℕ) :=
l.foldl
(fun (s : ℕ ⊕ α) (a : α) =>
Sum.casesOn s (@Nat.casesOn (fun _ => ℕ ⊕ α) · (Sum.inr a) Sum.inl) Sum.inr)
(Sum.inl n)
have hF : Primrec₂ F :=
(list_foldl fst (sumInl.comp snd)
((sumCasesOn fst (nat_casesOn snd (sumInr.comp <| snd.comp fst) (sumInl.comp snd).to₂).to₂
(sumInr.comp snd).to₂).comp
snd).to₂).to₂
have :
@Primrec _ (Option α) _ _ fun p : List α × ℕ => Sum.casesOn (F p.1 p.2) (fun _ => none) some :=
sumCasesOn hF (const none).to₂ (option_some.comp snd).to₂
this.to₂.of_eq fun l n => by
dsimp; symm
induction' l with a l IH generalizing n; · rfl
rcases n with - | n
· dsimp [F]
clear IH
induction' l with _ l IH <;> simp_all
· simpa using IH ..
@[deprecated (since := "2025-02-14")] alias list_get? := list_getElem?
theorem list_getD (d : α) : Primrec₂ fun l n => List.getD l n d := by
simp only [List.getD_eq_getElem?_getD]
exact option_getD.comp₂ list_getElem? (const _)
theorem list_getI [Inhabited α] : Primrec₂ (@List.getI α _) :=
list_getD _
theorem list_append : Primrec₂ ((· ++ ·) : List α → List α → List α) :=
(list_foldr fst snd <| to₂ <| comp (@list_cons α _) snd).to₂.of_eq fun l₁ l₂ => by
induction l₁ <;> simp [*]
theorem list_concat : Primrec₂ fun l (a : α) => l ++ [a] :=
list_append.comp fst (list_cons.comp snd (const []))
theorem list_map {f : α → List β} {g : α → β → σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec fun a => (f a).map (g a) :=
(list_foldr hf (const []) <|
to₂ <| list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq
fun a => by induction f a <;> simp [*]
theorem list_range : Primrec List.range :=
(nat_rec' .id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq fun n => by
simp; induction n <;> simp [*, List.range_succ]
theorem list_flatten : Primrec (@List.flatten α) :=
(list_foldr .id (const []) <| to₂ <| comp (@list_append α _) snd).of_eq fun l => by
dsimp; induction l <;> simp [*]
theorem list_flatMap {f : α → List β} {g : α → β → List σ} (hf : Primrec f) (hg : Primrec₂ g) :
Primrec (fun a => (f a).flatMap (g a)) := list_flatten.comp (list_map hf hg)
theorem optionToList : Primrec (Option.toList : Option α → List α) :=
(option_casesOn Primrec.id (const [])
((list_cons.comp Primrec.id (const [])).comp₂ Primrec₂.right)).of_eq
(fun o => by rcases o <;> simp)
theorem listFilterMap {f : α → List β} {g : α → β → Option σ}
(hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).filterMap (g a) :=
(list_flatMap hf (comp₂ optionToList hg)).of_eq
fun _ ↦ Eq.symm <| List.filterMap_eq_flatMap_toList _ _
theorem list_length : Primrec (@List.length α) :=
(list_foldr (@Primrec.id (List α) _) (const 0) <| to₂ <| (succ.comp <| snd.comp snd).to₂).of_eq
fun l => by dsimp; induction l <;> simp [*]
theorem list_findIdx {f : α → List β} {p : α → β → Bool}
(hf : Primrec f) (hp : Primrec₂ p) : Primrec fun a => (f a).findIdx (p a) :=
(list_foldr hf (const 0) <|
to₂ <| cond (hp.comp fst <| fst.comp snd) (const 0) (succ.comp <| snd.comp snd)).of_eq
fun a => by dsimp; induction f a <;> simp [List.findIdx_cons, *]
theorem list_idxOf [DecidableEq α] : Primrec₂ (@List.idxOf α _) :=
to₂ <| list_findIdx snd <| Primrec.beq.comp₂ snd.to₂ (fst.comp fst).to₂
@[deprecated (since := "2025-01-30")] alias list_indexOf := list_idxOf
theorem nat_strong_rec (f : α → ℕ → σ) {g : α → List σ → Option σ} (hg : Primrec₂ g)
(H : ∀ a n, g a ((List.range n).map (f a)) = some (f a n)) : Primrec₂ f :=
suffices Primrec₂ fun a n => (List.range n).map (f a) from
Primrec₂.option_some_iff.1 <|
(list_getElem?.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq fun a n => by
simp [List.getElem?_range (Nat.lt_succ_self n)]
Primrec₂.option_some_iff.1 <|
(nat_rec (const (some []))
(to₂ <|
option_bind (snd.comp snd) <|
to₂ <|
option_map (hg.comp (fst.comp fst) snd)
(to₂ <| list_concat.comp (snd.comp fst) snd))).of_eq
fun a n => by
induction n with
| zero => rfl
| succ n IH => simp [IH, H, List.range_succ]
theorem listLookup [DecidableEq α] : Primrec₂ (List.lookup : α → List (α × β) → Option β) :=
(to₂ <| list_rec snd (const none) <|
to₂ <|
cond (Primrec.beq.comp (fst.comp fst) (fst.comp <| fst.comp snd))
(option_some.comp <| snd.comp <| fst.comp snd)
(snd.comp <| snd.comp snd)).of_eq
fun a ps => by
induction' ps with p ps ih <;> simp [List.lookup, *]
cases ha : a == p.1 <;> simp [ha]
theorem nat_omega_rec' (f : β → σ) {m : β → ℕ} {l : β → List β} {g : β → List σ → Option σ}
(hm : Primrec m) (hl : Primrec l) (hg : Primrec₂ g)
(Ord : ∀ b, ∀ b' ∈ l b, m b' < m b)
(H : ∀ b, g b ((l b).map f) = some (f b)) : Primrec f := by
haveI : DecidableEq β := Encodable.decidableEqOfEncodable β
let mapGraph (M : List (β × σ)) (bs : List β) : List σ := bs.flatMap (Option.toList <| M.lookup ·)
let bindList (b : β) : ℕ → List β := fun n ↦ n.rec [b] fun _ bs ↦ bs.flatMap l
let graph (b : β) : ℕ → List (β × σ) := fun i ↦ i.rec [] fun i ih ↦
(bindList b (m b - i)).filterMap fun b' ↦ (g b' <| mapGraph ih (l b')).map (b', ·)
have mapGraph_primrec : Primrec₂ mapGraph :=
to₂ <| list_flatMap snd <| optionToList.comp₂ <| listLookup.comp₂ .right (fst.comp₂ .left)
have bindList_primrec : Primrec₂ (bindList) :=
nat_rec' snd
(list_cons.comp fst (const []))
(to₂ <| list_flatMap (snd.comp snd) (hl.comp₂ .right))
have graph_primrec : Primrec₂ (graph) :=
to₂ <| nat_rec' snd (const []) <|
to₂ <| listFilterMap
(bindList_primrec.comp
(fst.comp fst)
(nat_sub.comp (hm.comp <| fst.comp fst) (fst.comp snd))) <|
to₂ <| option_map
(hg.comp snd (mapGraph_primrec.comp (snd.comp <| snd.comp fst) (hl.comp snd)))
(Primrec₂.pair.comp₂ (snd.comp₂ .left) .right)
have : Primrec (fun b => (graph b (m b + 1))[0]?.map Prod.snd) :=
option_map (list_getElem?.comp (graph_primrec.comp Primrec.id (succ.comp hm)) (const 0))
(snd.comp₂ Primrec₂.right)
exact option_some_iff.mp <| this.of_eq <| fun b ↦ by
have graph_eq_map_bindList (i : ℕ) (hi : i ≤ m b + 1) :
graph b i = (bindList b (m b + 1 - i)).map fun x ↦ (x, f x) := by
have bindList_eq_nil : bindList b (m b + 1) = [] :=
have bindList_m_lt (k : ℕ) : ∀ b' ∈ bindList b k, m b' < m b + 1 - k := by
induction' k with k ih <;> simp [bindList]
intro a₂ a₁ ha₁ ha₂
have : k ≤ m b :=
Nat.lt_succ.mp (by simpa using Nat.add_lt_of_lt_sub <| Nat.zero_lt_of_lt (ih a₁ ha₁))
have : m a₁ ≤ m b - k :=
Nat.lt_succ.mp (by rw [← Nat.succ_sub this]; simpa using ih a₁ ha₁)
exact lt_of_lt_of_le (Ord a₁ a₂ ha₂) this
List.eq_nil_iff_forall_not_mem.mpr
(by intro b' ha'; by_contra; simpa using bindList_m_lt (m b + 1) b' ha')
have mapGraph_graph {bs bs' : List β} (has : bs' ⊆ bs) :
mapGraph (bs.map <| fun x => (x, f x)) bs' = bs'.map f := by
induction' bs' with b bs' ih <;> simp [mapGraph]
· have : b ∈ bs ∧ bs' ⊆ bs := by simpa using has
rcases this with ⟨ha, has'⟩
simpa [List.lookup_graph f ha] using ih has'
have graph_succ : ∀ i, graph b (i + 1) =
(bindList b (m b - i)).filterMap fun b' =>
(g b' <| mapGraph (graph b i) (l b')).map (b', ·) := fun _ => rfl
have bindList_succ : ∀ i, bindList b (i + 1) = (bindList b i).flatMap l := fun _ => rfl
induction' i with i ih
· symm; simpa [graph] using bindList_eq_nil
· simp only [graph_succ, ih (Nat.le_of_lt hi), Nat.succ_sub (Nat.lt_succ.mp hi),
Nat.succ_eq_add_one, bindList_succ, Nat.reduceSubDiff]
apply List.filterMap_eq_map_iff_forall_eq_some.mpr
intro b' ha'; simp; rw [mapGraph_graph]
· exact H b'
· exact (List.infix_flatMap_of_mem ha' l).subset
simp [graph_eq_map_bindList (m b + 1) (Nat.le_refl _), bindList]
theorem nat_omega_rec (f : α → β → σ) {m : α → β → ℕ}
{l : α → β → List β} {g : α → β × List σ → Option σ}
(hm : Primrec₂ m) (hl : Primrec₂ l) (hg : Primrec₂ g)
(Ord : ∀ a b, ∀ b' ∈ l a b, m a b' < m a b)
(H : ∀ a b, g a (b, (l a b).map (f a)) = some (f a b)) : Primrec₂ f :=
Primrec₂.uncurry.mp <|
nat_omega_rec' (Function.uncurry f)
(Primrec₂.uncurry.mpr hm)
(list_map (hl.comp fst snd) (Primrec₂.pair.comp₂ (fst.comp₂ .left) .right))
(hg.comp₂ (fst.comp₂ .left) (Primrec₂.pair.comp₂ (snd.comp₂ .left) .right))
(by simpa using Ord) (by simpa [Function.comp] using H)
end Primrec
namespace Primcodable
variable {α : Type*} [Primcodable α]
open Primrec
/-- A subtype of a primitive recursive predicate is `Primcodable`. -/
def subtype {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) : Primcodable (Subtype p) :=
⟨have : Primrec fun n => (@decode α _ n).bind fun a => Option.guard p a :=
option_bind .decode (option_guard (hp.comp snd).to₂ snd)
nat_iff.1 <| (encode_iff.2 this).of_eq fun n =>
show _ = encode ((@decode α _ n).bind fun _ => _) by
rcases @decode α _ n with - | a; · rfl
dsimp [Option.guard]
by_cases h : p a <;> simp [h]; rfl⟩
instance fin {n} : Primcodable (Fin n) :=
@ofEquiv _ _ (subtype <| nat_lt.comp .id (const n)) Fin.equivSubtype
instance vector {n} : Primcodable (List.Vector α n) :=
subtype ((@Primrec.eq ℕ _ _).comp list_length (const _))
instance finArrow {n} : Primcodable (Fin n → α) :=
ofEquiv _ (Equiv.vectorEquivFin _ _).symm
section ULower
attribute [local instance] Encodable.decidableRangeEncode Encodable.decidableEqOfEncodable
theorem mem_range_encode : PrimrecPred (fun n => n ∈ Set.range (encode : α → ℕ)) :=
have : PrimrecPred fun n => Encodable.decode₂ α n ≠ none :=
.not
(Primrec.eq.comp
(.option_bind .decode
(.ite (Primrec.eq.comp (Primrec.encode.comp .snd) .fst)
(Primrec.option_some.comp .snd) (.const _)))
(.const _))
this.of_eq fun _ => decode₂_ne_none_iff
instance ulower : Primcodable (ULower α) :=
Primcodable.subtype mem_range_encode
end ULower
end Primcodable
namespace Primrec
variable {α : Type*} {β : Type*} {σ : Type*}
variable [Primcodable α] [Primcodable β] [Primcodable σ]
theorem subtype_val {p : α → Prop} [DecidablePred p] {hp : PrimrecPred p} :
haveI := Primcodable.subtype hp
Primrec (@Subtype.val α p) := by
letI := Primcodable.subtype hp
refine (@Primcodable.prim (Subtype p)).of_eq fun n => ?_
rcases @decode (Subtype p) _ n with (_ | ⟨a, h⟩) <;> rfl
theorem subtype_val_iff {p : β → Prop} [DecidablePred p] {hp : PrimrecPred p} {f : α → Subtype p} :
haveI := Primcodable.subtype hp
(Primrec fun a => (f a).1) ↔ Primrec f := by
letI := Primcodable.subtype hp
refine ⟨fun h => ?_, fun hf => subtype_val.comp hf⟩
refine Nat.Primrec.of_eq h fun n => ?_
rcases @decode α _ n with - | a; · rfl
simp; rfl
theorem subtype_mk {p : β → Prop} [DecidablePred p] {hp : PrimrecPred p} {f : α → β}
{h : ∀ a, p (f a)} (hf : Primrec f) :
haveI := Primcodable.subtype hp
Primrec fun a => @Subtype.mk β p (f a) (h a) :=
subtype_val_iff.1 hf
theorem option_get {f : α → Option β} {h : ∀ a, (f a).isSome} :
Primrec f → Primrec fun a => (f a).get (h a) := by
intro hf
refine (Nat.Primrec.pred.comp hf).of_eq fun n => ?_
generalize hx : @decode α _ n = x
cases x <;> simp
theorem ulower_down : Primrec (ULower.down : α → ULower α) :=
letI : ∀ a, Decidable (a ∈ Set.range (encode : α → ℕ)) := decidableRangeEncode _
subtype_mk .encode
theorem ulower_up : Primrec (ULower.up : ULower α → α) :=
letI : ∀ a, Decidable (a ∈ Set.range (encode : α → ℕ)) := decidableRangeEncode _
option_get (Primrec.decode₂.comp subtype_val)
theorem fin_val_iff {n} {f : α → Fin n} : (Primrec fun a => (f a).1) ↔ Primrec f := by
letI : Primcodable { a // id a < n } := Primcodable.subtype (nat_lt.comp .id (const _))
exact (Iff.trans (by rfl) subtype_val_iff).trans (of_equiv_iff _)
theorem fin_val {n} : Primrec (fun (i : Fin n) => (i : ℕ)) :=
fin_val_iff.2 .id
theorem fin_succ {n} : Primrec (@Fin.succ n) :=
fin_val_iff.1 <| by simp [succ.comp fin_val]
theorem vector_toList {n} : Primrec (@List.Vector.toList α n) :=
subtype_val
theorem vector_toList_iff {n} {f : α → List.Vector β n} :
(Primrec fun a => (f a).toList) ↔ Primrec f :=
subtype_val_iff
theorem vector_cons {n} : Primrec₂ (@List.Vector.cons α n) :=
vector_toList_iff.1 <| by simpa using list_cons.comp fst (vector_toList_iff.2 snd)
theorem vector_length {n} : Primrec (@List.Vector.length α n) :=
const _
theorem vector_head {n} : Primrec (@List.Vector.head α n) :=
option_some_iff.1 <| (list_head?.comp vector_toList).of_eq fun ⟨_ :: _, _⟩ => rfl
theorem vector_tail {n} : Primrec (@List.Vector.tail α n) :=
vector_toList_iff.1 <| (list_tail.comp vector_toList).of_eq fun ⟨l, h⟩ => by cases l <;> rfl
theorem vector_get {n} : Primrec₂ (@List.Vector.get α n) :=
option_some_iff.1 <|
(list_getElem?.comp (vector_toList.comp fst) (fin_val.comp snd)).of_eq fun a => by
simp [Vector.get_eq_get_toList]
theorem list_ofFn :
∀ {n} {f : Fin n → α → σ}, (∀ i, Primrec (f i)) → Primrec fun a => List.ofFn fun i => f i a
| 0, _, _ => by simp only [List.ofFn_zero]; exact const []
| n + 1, f, hf => by
simpa [List.ofFn_succ] using list_cons.comp (hf 0) (list_ofFn fun i => hf i.succ)
theorem vector_ofFn {n} {f : Fin n → α → σ} (hf : ∀ i, Primrec (f i)) :
Primrec fun a => List.Vector.ofFn fun i => f i a :=
vector_toList_iff.1 <| by simp [list_ofFn hf]
theorem vector_get' {n} : Primrec (@List.Vector.get α n) :=
of_equiv_symm
theorem vector_ofFn' {n} : Primrec (@List.Vector.ofFn α n) :=
of_equiv
theorem fin_app {n} : Primrec₂ (@id (Fin n → σ)) :=
(vector_get.comp (vector_ofFn'.comp fst) snd).of_eq fun ⟨v, i⟩ => by simp
theorem fin_curry₁ {n} {f : Fin n → α → σ} : Primrec₂ f ↔ ∀ i, Primrec (f i) :=
⟨fun h i => h.comp (const i) .id, fun h =>
(vector_get.comp ((vector_ofFn h).comp snd) fst).of_eq fun a => by simp⟩
theorem fin_curry {n} {f : α → Fin n → σ} : Primrec f ↔ Primrec₂ f :=
⟨fun h => fin_app.comp (h.comp fst) snd, fun h =>
(vector_get'.comp
(vector_ofFn fun i => show Primrec fun a => f a i from h.comp .id (const i))).of_eq
fun a => by funext i; simp⟩
end Primrec
namespace Nat
open List.Vector
/-- An alternative inductive definition of `Primrec` which
does not use the pairing function on ℕ, and so has to
work with n-ary functions on ℕ instead of unary functions.
We prove that this is equivalent to the regular notion
in `to_prim` and `of_prim`. -/
inductive Primrec' : ∀ {n}, (List.Vector ℕ n → ℕ) → Prop
| zero : @Primrec' 0 fun _ => 0
| succ : @Primrec' 1 fun v => succ v.head
| get {n} (i : Fin n) : Primrec' fun v => v.get i
| comp {m n f} (g : Fin n → List.Vector ℕ m → ℕ) :
Primrec' f → (∀ i, Primrec' (g i)) → Primrec' fun a => f (List.Vector.ofFn fun i => g i a)
| prec {n f g} :
@Primrec' n f →
@Primrec' (n + 2) g →
Primrec' fun v : List.Vector ℕ (n + 1) =>
v.head.rec (f v.tail) fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)
end Nat
namespace Nat.Primrec'
open List.Vector Primrec
theorem to_prim {n f} (pf : @Nat.Primrec' n f) : Primrec f := by
induction pf with
| zero => exact .const 0
| succ => exact _root_.Primrec.succ.comp .vector_head
| get i => exact Primrec.vector_get.comp .id (.const i)
| comp _ _ _ hf hg => exact hf.comp (.vector_ofFn fun i => hg i)
| @prec n f g _ _ hf hg =>
exact
.nat_rec' .vector_head (hf.comp Primrec.vector_tail)
(hg.comp <|
Primrec.vector_cons.comp (Primrec.fst.comp .snd) <|
Primrec.vector_cons.comp (Primrec.snd.comp .snd) <|
(@Primrec.vector_tail _ _ (n + 1)).comp .fst).to₂
theorem of_eq {n} {f g : List.Vector ℕ n → ℕ} (hf : Primrec' f) (H : ∀ i, f i = g i) :
Primrec' g :=
(funext H : f = g) ▸ hf
theorem const {n} : ∀ m, @Primrec' n fun _ => m
| 0 => zero.comp Fin.elim0 fun i => i.elim0
| m + 1 => succ.comp _ fun _ => const m
theorem head {n : ℕ} : @Primrec' n.succ head :=
(get 0).of_eq fun v => by simp [get_zero]
theorem tail {n f} (hf : @Primrec' n f) : @Primrec' n.succ fun v => f v.tail :=
(hf.comp _ fun i => @get _ i.succ).of_eq fun v => by
rw [← ofFn_get v.tail]; congr; funext i; simp
/-- A function from vectors to vectors is primitive recursive when all of its projections are. -/
def Vec {n m} (f : List.Vector ℕ n → List.Vector ℕ m) : Prop :=
∀ i, Primrec' fun v => (f v).get i
protected theorem nil {n} : @Vec n 0 fun _ => nil := fun i => i.elim0
protected theorem cons {n m f g} (hf : @Primrec' n f) (hg : @Vec n m g) :
Vec fun v => f v ::ᵥ g v := fun i => Fin.cases (by simp [*]) (fun i => by simp [hg i]) i
theorem idv {n} : @Vec n n id :=
get
theorem comp' {n m f g} (hf : @Primrec' m f) (hg : @Vec n m g) : Primrec' fun v => f (g v) :=
(hf.comp _ hg).of_eq fun v => by simp
theorem comp₁ (f : ℕ → ℕ) (hf : @Primrec' 1 fun v => f v.head) {n g} (hg : @Primrec' n g) :
Primrec' fun v => f (g v) :=
hf.comp _ fun _ => hg
theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @Primrec' 2 fun v => f v.head v.tail.head) {n g h}
(hg : @Primrec' n g) (hh : @Primrec' n h) : Primrec' fun v => f (g v) (h v) := by
simpa using hf.comp' (hg.cons <| hh.cons Primrec'.nil)
theorem prec' {n f g h} (hf : @Primrec' n f) (hg : @Primrec' n g) (hh : @Primrec' (n + 2) h) :
@Primrec' n fun v => (f v).rec (g v) fun y IH : ℕ => h (y ::ᵥ IH ::ᵥ v) := by
simpa using comp' (prec hg hh) (hf.cons idv)
theorem pred : @Primrec' 1 fun v => v.head.pred :=
(prec' head (const 0) head).of_eq fun v => by simp; cases v.head <;> rfl
theorem add : @Primrec' 2 fun v => v.head + v.tail.head :=
(prec head (succ.comp₁ _ (tail head))).of_eq fun v => by
simp; induction v.head <;> simp [*, Nat.succ_add]
theorem sub : @Primrec' 2 fun v => v.head - v.tail.head := by
have : @Primrec' 2 fun v ↦ (fun a b ↦ b - a) v.head v.tail.head := by
refine (prec head (pred.comp₁ _ (tail head))).of_eq fun v => ?_
simp; induction v.head <;> simp [*, Nat.sub_add_eq]
simpa using comp₂ (fun a b => b - a) this (tail head) head
theorem mul : @Primrec' 2 fun v => v.head * v.tail.head :=
(prec (const 0) (tail (add.comp₂ _ (tail head) head))).of_eq fun v => by
simp; induction v.head <;> simp [*, Nat.succ_mul]; rw [add_comm]
theorem if_lt {n a b f g} (ha : @Primrec' n a) (hb : @Primrec' n b) (hf : @Primrec' n f)
(hg : @Primrec' n g) : @Primrec' n fun v => if a v < b v then f v else g v :=
(prec' (sub.comp₂ _ hb ha) hg (tail <| tail hf)).of_eq fun v => by
cases e : b v - a v
· simp [not_lt.2 (Nat.sub_eq_zero_iff_le.mp e)]
· simp [Nat.lt_of_sub_eq_succ e]
theorem natPair : @Primrec' 2 fun v => v.head.pair v.tail.head :=
if_lt head (tail head) (add.comp₂ _ (tail <| mul.comp₂ _ head head) head)
(add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head))
protected theorem encode : ∀ {n}, @Primrec' n encode
| 0 => (const 0).of_eq fun v => by rw [v.eq_nil]; rfl
| _ + 1 =>
(succ.comp₁ _ (natPair.comp₂ _ head (tail Primrec'.encode))).of_eq fun ⟨_ :: _, _⟩ => rfl
theorem sqrt : @Primrec' 1 fun v => v.head.sqrt := by
suffices H : ∀ n : ℕ, n.sqrt =
n.rec 0 fun x y => if x.succ < y.succ * y.succ then y else y.succ by
simp only [H, succ_eq_add_one]
have :=
@prec' 1 _ _
(fun v => by
have x := v.head; have y := v.tail.head
exact if x.succ < y.succ * y.succ then y else y.succ)
head (const 0) ?_
· exact this
have x1 : @Primrec' 3 fun v => v.head.succ := succ.comp₁ _ head
have y1 : @Primrec' 3 fun v => v.tail.head.succ := succ.comp₁ _ (tail head)
exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1
introv; symm
induction' n with n IH; · simp
dsimp; rw [IH]; split_ifs with h
· exact le_antisymm (Nat.sqrt_le_sqrt (Nat.le_succ _)) (Nat.lt_succ_iff.1 <| Nat.sqrt_lt.2 h)
· exact
Nat.eq_sqrt.2 ⟨not_lt.1 h, Nat.sqrt_lt.1 <| Nat.lt_succ_iff.2 <| Nat.sqrt_succ_le_succ_sqrt _⟩
theorem unpair₁ {n f} (hf : @Primrec' n f) : @Primrec' n fun v => (f v).unpair.1 := by
have s := sqrt.comp₁ _ hf
have fss := sub.comp₂ _ hf (mul.comp₂ _ s s)
refine (if_lt fss s fss s).of_eq fun v => ?_
simp [Nat.unpair]; split_ifs <;> rfl
theorem unpair₂ {n f} (hf : @Primrec' n f) : @Primrec' n fun v => (f v).unpair.2 := by
have s := sqrt.comp₁ _ hf
have fss := sub.comp₂ _ hf (mul.comp₂ _ s s)
refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq fun v => ?_
simp [Nat.unpair]; split_ifs <;> rfl
theorem of_prim {n f} : Primrec f → @Primrec' n f :=
suffices ∀ f, Nat.Primrec f → @Primrec' 1 fun v => f v.head from fun hf =>
(pred.comp₁ _ <|
(this _ hf).comp₁ (fun m => Encodable.encode <| (@decode (List.Vector ℕ n) _ m).map f)
Primrec'.encode).of_eq
fun i => by simp [encodek]
fun f hf => by
induction hf with
| zero => exact const 0
| succ => exact succ
| left => exact unpair₁ head
| right => exact unpair₂ head
| pair _ _ hf hg => exact natPair.comp₂ _ hf hg
| comp _ _ hf hg => exact hf.comp₁ _ hg
| prec _ _ hf hg =>
simpa using
prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head))
(hg.comp₁ _ <|
natPair.comp₂ _ (unpair₁ <| tail <| tail head) (natPair.comp₂ _ head (tail head)))
theorem prim_iff {n f} : @Primrec' n f ↔ Primrec f :=
⟨to_prim, of_prim⟩
theorem prim_iff₁ {f : ℕ → ℕ} : (@Primrec' 1 fun v => f v.head) ↔ Primrec f :=
prim_iff.trans
⟨fun h => (h.comp <| .vector_ofFn fun _ => .id).of_eq fun v => by simp, fun h =>
h.comp .vector_head⟩
theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : (@Primrec' 2 fun v => f v.head v.tail.head) ↔ Primrec₂ f :=
prim_iff.trans
⟨fun h => (h.comp <| Primrec.vector_cons.comp .fst <|
Primrec.vector_cons.comp .snd (.const nil)).of_eq fun v => by simp,
fun h => h.comp .vector_head (Primrec.vector_head.comp .vector_tail)⟩
theorem vec_iff {m n f} : @Vec m n f ↔ Primrec f :=
⟨fun h => by simpa using Primrec.vector_ofFn fun i => to_prim (h i), fun h i =>
of_prim <| Primrec.vector_get.comp h (.const i)⟩
end Nat.Primrec'
theorem Primrec.nat_sqrt : Primrec Nat.sqrt :=
Nat.Primrec'.prim_iff₁.1 Nat.Primrec'.sqrt
| Mathlib/Computability/Primrec.lean | 1,577 | 1,596 | |
/-
Copyright (c) 2022 David Loeffler. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Loeffler, Yaël Dillies, Bhavik Mehta
-/
import Mathlib.Analysis.Convex.SpecificFunctions.Deriv
import Mathlib.Analysis.SpecialFunctions.Trigonometric.ArctanDeriv
/-!
# Polynomial bounds for trigonometric functions
## Main statements
This file contains upper and lower bounds for real trigonometric functions in terms
of polynomials. See `Trigonometric.Basic` for more elementary inequalities, establishing
the ranges of these functions, and their monotonicity in suitable intervals.
Here we prove the following:
* `sin_lt`: for `x > 0` we have `sin x < x`.
* `sin_gt_sub_cube`: For `0 < x ≤ 1` we have `x - x ^ 3 / 4 < sin x`.
* `lt_tan`: for `0 < x < π/2` we have `x < tan x`.
* `cos_le_one_div_sqrt_sq_add_one` and `cos_lt_one_div_sqrt_sq_add_one`: for
`-3 * π / 2 ≤ x ≤ 3 * π / 2`, we have `cos x ≤ 1 / sqrt (x ^ 2 + 1)`, with strict inequality if
`x ≠ 0`. (This bound is not quite optimal, but not far off)
## Tags
sin, cos, tan, angle
-/
open Set
namespace Real
variable {x : ℝ}
/-- For 0 < x, we have sin x < x. -/
theorem sin_lt (h : 0 < x) : sin x < x := by
rcases lt_or_le 1 x with h' | h'
· exact (sin_le_one x).trans_lt h'
have hx : |x| = x := abs_of_nonneg h.le
have := le_of_abs_le (sin_bound <| show |x| ≤ 1 by rwa [hx])
rw [sub_le_iff_le_add', hx] at this
apply this.trans_lt
rw [sub_add, sub_lt_self_iff, sub_pos, div_eq_mul_inv (x ^ 3)]
refine mul_lt_mul' ?_ (by norm_num) (by norm_num) (pow_pos h 3)
apply pow_le_pow_of_le_one h.le h'
norm_num
lemma sin_le (hx : 0 ≤ x) : sin x ≤ x := by
obtain rfl | hx := hx.eq_or_lt
· simp
· exact (sin_lt hx).le
lemma lt_sin (hx : x < 0) : x < sin x := by simpa using sin_lt <| neg_pos.2 hx
lemma le_sin (hx : x ≤ 0) : x ≤ sin x := by simpa using sin_le <| neg_nonneg.2 hx
theorem lt_sin_mul {x : ℝ} (hx : 0 < x) (hx' : x < 1) : x < sin (π / 2 * x) := by
simpa [mul_comm x] using
strictConcaveOn_sin_Icc.2 ⟨le_rfl, pi_pos.le⟩ ⟨pi_div_two_pos.le, half_le_self pi_pos.le⟩
pi_div_two_pos.ne (sub_pos.2 hx') hx
theorem le_sin_mul {x : ℝ} (hx : 0 ≤ x) (hx' : x ≤ 1) : x ≤ sin (π / 2 * x) := by
simpa [mul_comm x] using
strictConcaveOn_sin_Icc.concaveOn.2 ⟨le_rfl, pi_pos.le⟩
⟨pi_div_two_pos.le, half_le_self pi_pos.le⟩ (sub_nonneg.2 hx') hx
theorem mul_lt_sin {x : ℝ} (hx : 0 < x) (hx' : x < π / 2) : 2 / π * x < sin x := by
rw [← inv_div]
simpa [-inv_div, mul_inv_cancel_left₀ pi_div_two_pos.ne'] using @lt_sin_mul ((π / 2)⁻¹ * x)
(mul_pos (inv_pos.2 pi_div_two_pos) hx) (by rwa [← div_eq_inv_mul, div_lt_one pi_div_two_pos])
/-- One half of **Jordan's inequality**.
In the range `[0, π / 2]`, we have a linear lower bound on `sin`. The other half is given by
`Real.sin_le`.
-/
theorem mul_le_sin {x : ℝ} (hx : 0 ≤ x) (hx' : x ≤ π / 2) : 2 / π * x ≤ sin x := by
rw [← inv_div]
simpa [-inv_div, mul_inv_cancel_left₀ pi_div_two_pos.ne'] using @le_sin_mul ((π / 2)⁻¹ * x)
(mul_nonneg (inv_nonneg.2 pi_div_two_pos.le) hx)
(by rwa [← div_eq_inv_mul, div_le_one pi_div_two_pos])
/-- Half of **Jordan's inequality** for negative values. -/
lemma sin_le_mul (hx : -(π / 2) ≤ x) (hx₀ : x ≤ 0) : sin x ≤ 2 / π * x := by
simpa using mul_le_sin (neg_nonneg.2 hx₀) (neg_le.2 hx)
/-- Half of **Jordan's inequality** for absolute values. -/
lemma mul_abs_le_abs_sin (hx : |x| ≤ π / 2) : 2 / π * |x| ≤ |sin x| := by
wlog hx₀ : 0 ≤ x
case inr => simpa using this (by rwa [abs_neg]) <| neg_nonneg.2 <| le_of_not_le hx₀
rw [abs_of_nonneg hx₀] at hx ⊢
exact (mul_le_sin hx₀ hx).trans (le_abs_self _)
lemma sin_sq_lt_sq (hx : x ≠ 0) : sin x ^ 2 < x ^ 2 := by
wlog hx₀ : 0 < x
case inr =>
simpa using this (neg_ne_zero.2 hx) <| neg_pos_of_neg <| hx.lt_of_le <| le_of_not_lt hx₀
rcases le_or_lt x 1 with hxπ | hxπ
case inl =>
exact pow_lt_pow_left₀ (sin_lt hx₀)
(sin_nonneg_of_nonneg_of_le_pi hx₀.le (by linarith [two_le_pi])) (by simp)
case inr =>
exact (sin_sq_le_one _).trans_lt (by rwa [one_lt_sq_iff₀ hx₀.le])
lemma sin_sq_le_sq : sin x ^ 2 ≤ x ^ 2 := by
rcases eq_or_ne x 0 with rfl | hx
case inl => simp
case inr => exact (sin_sq_lt_sq hx).le
lemma abs_sin_lt_abs (hx : x ≠ 0) : |sin x| < |x| := sq_lt_sq.1 (sin_sq_lt_sq hx)
lemma abs_sin_le_abs : |sin x| ≤ |x| := sq_le_sq.1 sin_sq_le_sq
lemma one_sub_sq_div_two_lt_cos (hx : x ≠ 0) : 1 - x ^ 2 / 2 < cos x := by
have := (sin_sq_lt_sq (by positivity)).trans_eq' (sin_sq_eq_half_sub (x / 2)).symm
ring_nf at this
linarith
lemma one_sub_sq_div_two_le_cos : 1 - x ^ 2 / 2 ≤ cos x := by
rcases eq_or_ne x 0 with rfl | hx
case inl => simp
case inr => exact (one_sub_sq_div_two_lt_cos hx).le
/-- Half of **Jordan's inequality** for `cos`. -/
lemma one_sub_mul_le_cos (hx₀ : 0 ≤ x) (hx : x ≤ π / 2) : 1 - 2 / π * x ≤ cos x := by
simpa [sin_pi_div_two_sub, mul_sub, div_mul_div_comm, mul_comm π, pi_pos.ne']
using mul_le_sin (x := π / 2 - x) (by simpa) (by simpa)
/-- Half of **Jordan's inequality** for `cos` and negative values. -/
lemma one_add_mul_le_cos (hx₀ : -(π / 2) ≤ x) (hx : x ≤ 0) : 1 + 2 / π * x ≤ cos x := by
simpa using one_sub_mul_le_cos (x := -x) (by linarith) (by linarith)
lemma cos_le_one_sub_mul_cos_sq (hx : |x| ≤ π) : cos x ≤ 1 - 2 / π ^ 2 * x ^ 2 := by
wlog hx₀ : 0 ≤ x
case inr => simpa using this (by rwa [abs_neg]) <| neg_nonneg.2 <| le_of_not_le hx₀
rw [abs_of_nonneg hx₀] at hx
have : x / π ≤ sin (x / 2) := by simpa using mul_le_sin (x := x / 2) (by positivity) (by linarith)
have := (pow_le_pow_left₀ (by positivity) this 2).trans_eq (sin_sq_eq_half_sub _)
ring_nf at this ⊢
linarith
/-- For 0 < x ≤ 1 we have x - x ^ 3 / 4 < sin x.
This is also true for x > 1, but it's nontrivial for x just above 1. This inequality is not
tight; the tighter inequality is sin x > x - x ^ 3 / 6 for all x > 0, but this inequality has
a simpler proof. -/
theorem sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x := by
have hx : |x| = x := abs_of_nonneg h.le
have := neg_le_of_abs_le (sin_bound <| show |x| ≤ 1 by rwa [hx])
rw [le_sub_iff_add_le, hx] at this
refine lt_of_lt_of_le ?_ this
have : x ^ 3 / ↑4 - x ^ 3 / ↑6 = x ^ 3 * 12⁻¹ := by norm_num [div_eq_mul_inv, ← mul_sub]
rw [add_comm, sub_add, sub_neg_eq_add, sub_lt_sub_iff_left, ← lt_sub_iff_add_lt', this]
refine mul_lt_mul' ?_ (by norm_num) (by norm_num) (pow_pos h 3)
apply pow_le_pow_of_le_one h.le h'
norm_num
/-- The derivative of `tan x - x` is `1/(cos x)^2 - 1` away from the zeroes of cos. -/
theorem deriv_tan_sub_id (x : ℝ) (h : cos x ≠ 0) :
deriv (fun y : ℝ => tan y - y) x = 1 / cos x ^ 2 - 1 :=
HasDerivAt.deriv <| by simpa using (hasDerivAt_tan h).add (hasDerivAt_id x).neg
/-- For all `0 < x < π/2` we have `x < tan x`.
This is proved by checking that the function `tan x - x` vanishes
at zero and has non-negative derivative. -/
theorem lt_tan {x : ℝ} (h1 : 0 < x) (h2 : x < π / 2) : x < tan x := by
let U := Ico 0 (π / 2)
have intU : interior U = Ioo 0 (π / 2) := interior_Ico
have half_pi_pos : 0 < π / 2 := div_pos pi_pos two_pos
have cos_pos {y : ℝ} (hy : y ∈ U) : 0 < cos y := by
exact cos_pos_of_mem_Ioo (Ico_subset_Ioo_left (neg_lt_zero.mpr half_pi_pos) hy)
have sin_pos {y : ℝ} (hy : y ∈ interior U) : 0 < sin y := by
rw [intU] at hy
exact sin_pos_of_mem_Ioo (Ioo_subset_Ioo_right (div_le_self pi_pos.le one_le_two) hy)
have tan_cts_U : ContinuousOn tan U := by
apply ContinuousOn.mono continuousOn_tan
intro z hz
simp only [mem_setOf_eq]
exact (cos_pos hz).ne'
have tan_minus_id_cts : ContinuousOn (fun y : ℝ => tan y - y) U := tan_cts_U.sub continuousOn_id
have deriv_pos (y : ℝ) (hy : y ∈ interior U) : 0 < deriv (fun y' : ℝ => tan y' - y') y := by
have := cos_pos (interior_subset hy)
simp only [deriv_tan_sub_id y this.ne', one_div, gt_iff_lt, sub_pos]
norm_cast
have bd2 : cos y ^ 2 < 1 := by
apply lt_of_le_of_ne y.cos_sq_le_one
rw [cos_sq']
simpa only [Ne, sub_eq_self, sq_eq_zero_iff] using (sin_pos hy).ne'
rwa [lt_inv_comm₀, inv_one]
· exact zero_lt_one
simpa only [sq, mul_self_pos] using this.ne'
have mono := strictMonoOn_of_deriv_pos (convex_Ico 0 (π / 2)) tan_minus_id_cts deriv_pos
have zero_in_U : (0 : ℝ) ∈ U := by rwa [left_mem_Ico]
have x_in_U : x ∈ U := ⟨h1.le, h2⟩
simpa only [tan_zero, sub_zero, sub_pos] using mono zero_in_U x_in_U h1
theorem le_tan {x : ℝ} (h1 : 0 ≤ x) (h2 : x < π / 2) : x ≤ tan x := by
rcases eq_or_lt_of_le h1 with (rfl | h1')
· rw [tan_zero]
· exact le_of_lt (lt_tan h1' h2)
|
theorem cos_lt_one_div_sqrt_sq_add_one {x : ℝ} (hx1 : -(3 * π / 2) ≤ x) (hx2 : x ≤ 3 * π / 2)
(hx3 : x ≠ 0) : cos x < (1 / √(x ^ 2 + 1) : ℝ) := by
suffices ∀ {y : ℝ}, 0 < y → y ≤ 3 * π / 2 → cos y < 1 / sqrt (y ^ 2 + 1) by
rcases lt_or_lt_iff_ne.mpr hx3.symm with ⟨h⟩
· exact this h hx2
· convert this (by linarith : 0 < -x) (by linarith) using 1
· rw [cos_neg]
· rw [neg_sq]
intro y hy1 hy2
have hy3 : ↑0 < y ^ 2 + 1 := by linarith [sq_nonneg y]
rcases lt_or_le y (π / 2) with (hy2' | hy1')
· -- Main case : `0 < y < π / 2`
have hy4 : 0 < cos y := cos_pos_of_mem_Ioo ⟨by linarith, hy2'⟩
rw [← abs_of_nonneg (cos_nonneg_of_mem_Icc ⟨by linarith, hy2'.le⟩), ←
abs_of_nonneg (one_div_nonneg.mpr (sqrt_nonneg _)), ← sq_lt_sq, div_pow, one_pow,
sq_sqrt hy3.le, lt_one_div (pow_pos hy4 _) hy3, ← inv_one_add_tan_sq hy4.ne', one_div,
inv_inv, add_comm, add_lt_add_iff_left, sq_lt_sq, abs_of_pos hy1,
abs_of_nonneg (tan_nonneg_of_nonneg_of_le_pi_div_two hy1.le hy2'.le)]
exact Real.lt_tan hy1 hy2'
· -- Easy case : `π / 2 ≤ y ≤ 3 * π / 2`
refine lt_of_le_of_lt ?_ (one_div_pos.mpr <| sqrt_pos_of_pos hy3)
| Mathlib/Analysis/SpecialFunctions/Trigonometric/Bounds.lean | 202 | 223 |
/-
Copyright (c) 2024 David Kurniadi Angdinata. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Kurniadi Angdinata
-/
import Mathlib.AlgebraicGeometry.EllipticCurve.Group
import Mathlib.NumberTheory.EllipticDivisibilitySequence
/-!
# Division polynomials of Weierstrass curves
This file defines certain polynomials associated to division polynomials of Weierstrass curves.
These are defined in terms of the auxiliary sequences for normalised elliptic divisibility sequences
(EDS) as defined in `Mathlib.NumberTheory.EllipticDivisibilitySequence`.
## Mathematical background
Let `W` be a Weierstrass curve over a commutative ring `R`. The sequence of `n`-division polynomials
`ψₙ ∈ R[X, Y]` of `W` is the normalised EDS with initial values
* `ψ₀ := 0`,
* `ψ₁ := 1`,
* `ψ₂ := 2Y + a₁X + a₃`,
* `ψ₃ := 3X⁴ + b₂X³ + 3b₄X² + 3b₆X + b₈`, and
* `ψ₄ := ψ₂ ⬝ (2X⁶ + b₂X⁵ + 5b₄X⁴ + 10b₆X³ + 10b₈X² + (b₂b₈ - b₄b₆)X + (b₄b₈ - b₆²))`.
Furthermore, define the associated sequences `φₙ, ωₙ ∈ R[X, Y]` by
* `φₙ := Xψₙ² - ψₙ₊₁ ⬝ ψₙ₋₁`, and
* `ωₙ := (ψ₂ₙ / ψₙ - ψₙ ⬝ (a₁φₙ + a₃ψₙ²)) / 2`.
Note that `ωₙ` is always well-defined as a polynomial in `R[X, Y]`. As a start, it can be shown by
induction that `ψₙ` always divides `ψ₂ₙ` in `R[X, Y]`, so that `ψ₂ₙ / ψₙ` is always well-defined as
a polynomial, while division by `2` is well-defined when `R` has characteristic different from `2`.
In general, it can be shown that `2` always divides the polynomial `ψ₂ₙ / ψₙ - ψₙ ⬝ (a₁φₙ + a₃ψₙ²)`
in the characteristic `0` universal ring `𝓡[X, Y] := ℤ[A₁, A₂, A₃, A₄, A₆][X, Y]` of `W`, where the
`Aᵢ` are indeterminates. Then `ωₙ` can be equivalently defined as the image of this division under
the associated universal morphism `𝓡[X, Y] → R[X, Y]` mapping `Aᵢ` to `aᵢ`.
Now, in the coordinate ring `R[W]`, note that `ψ₂²` is congruent to the polynomial
`Ψ₂Sq := 4X³ + b₂X² + 2b₄X + b₆ ∈ R[X]`. As such, the recurrences of a normalised EDS show that
`ψₙ / ψ₂` are congruent to certain polynomials in `R[W]`. In particular, define `preΨₙ ∈ R[X]` as
the auxiliary sequence for a normalised EDS with extra parameter `Ψ₂Sq²` and initial values
* `preΨ₀ := 0`,
* `preΨ₁ := 1`,
* `preΨ₂ := 1`,
* `preΨ₃ := ψ₃`, and
* `preΨ₄ := ψ₄ / ψ₂`.
The corresponding normalised EDS `Ψₙ ∈ R[X, Y]` is then given by
* `Ψₙ := preΨₙ ⬝ ψ₂` if `n` is even, and
* `Ψₙ := preΨₙ` if `n` is odd.
Furthermore, define the associated sequences `ΨSqₙ, Φₙ ∈ R[X]` by
* `ΨSqₙ := preΨₙ² ⬝ Ψ₂Sq` if `n` is even,
* `ΨSqₙ := preΨₙ²` if `n` is odd,
* `Φₙ := XΨSqₙ - preΨₙ₊₁ ⬝ preΨₙ₋₁` if `n` is even, and
* `Φₙ := XΨSqₙ - preΨₙ₊₁ ⬝ preΨₙ₋₁ ⬝ Ψ₂Sq` if `n` is odd.
With these definitions, `ψₙ ∈ R[X, Y]` and `φₙ ∈ R[X, Y]` are congruent in `R[W]` to `Ψₙ ∈ R[X, Y]`
and `Φₙ ∈ R[X]` respectively, which are defined in terms of `Ψ₂Sq ∈ R[X]` and `preΨₙ ∈ R[X]`.
## Main definitions
* `WeierstrassCurve.preΨ`: the univariate polynomials `preΨₙ`.
* `WeierstrassCurve.ΨSq`: the univariate polynomials `ΨSqₙ`.
* `WeierstrassCurve.Ψ`: the bivariate polynomials `Ψₙ`.
* `WeierstrassCurve.Φ`: the univariate polynomials `Φₙ`.
* `WeierstrassCurve.ψ`: the bivariate `n`-division polynomials `ψₙ`.
* `WeierstrassCurve.φ`: the bivariate polynomials `φₙ`.
* TODO: the bivariate polynomials `ωₙ`.
## Implementation notes
Analogously to `Mathlib.NumberTheory.EllipticDivisibilitySequence`, the bivariate polynomials
`Ψₙ` are defined in terms of the univariate polynomials `preΨₙ`. This is done partially to avoid
ring division, but more crucially to allow the definition of `ΨSqₙ` and `Φₙ` as univariate
polynomials without needing to work under the coordinate ring, and to allow the computation of their
leading terms without ambiguity. Furthermore, evaluating these polynomials at a rational point on
`W` recovers their original definition up to linear combinations of the Weierstrass equation of `W`,
hence also avoiding the need to work in the coordinate ring.
TODO: implementation notes for the definition of `ωₙ`.
## References
[J Silverman, *The Arithmetic of Elliptic Curves*][silverman2009]
## Tags
elliptic curve, division polynomial, torsion point
-/
open Polynomial
open scoped Polynomial.Bivariate
local macro "C_simp" : tactic =>
`(tactic| simp only [map_ofNat, C_0, C_1, C_neg, C_add, C_sub, C_mul, C_pow])
local macro "map_simp" : tactic =>
`(tactic| simp only [map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow, map_div₀,
Polynomial.map_ofNat, Polynomial.map_one, map_C, map_X, Polynomial.map_neg, Polynomial.map_add,
Polynomial.map_sub, Polynomial.map_mul, Polynomial.map_pow, Polynomial.map_div, coe_mapRingHom,
apply_ite <| mapRingHom _, WeierstrassCurve.map])
universe r s u v
namespace WeierstrassCurve
variable {R : Type r} {S : Type s} [CommRing R] [CommRing S] (W : WeierstrassCurve R)
section Ψ₂Sq
/-! ### The univariate polynomial `Ψ₂Sq` -/
/-- The `2`-division polynomial `ψ₂ = Ψ₂`. -/
noncomputable def ψ₂ : R[X][Y] :=
W.toAffine.polynomialY
/-- The univariate polynomial `Ψ₂Sq` congruent to `ψ₂²`. -/
noncomputable def Ψ₂Sq : R[X] :=
C 4 * X ^ 3 + C W.b₂ * X ^ 2 + C (2 * W.b₄) * X + C W.b₆
lemma C_Ψ₂Sq : C W.Ψ₂Sq = W.ψ₂ ^ 2 - 4 * W.toAffine.polynomial := by
rw [Ψ₂Sq, ψ₂, b₂, b₄, b₆, Affine.polynomialY, Affine.polynomial]
C_simp
ring1
lemma ψ₂_sq : W.ψ₂ ^ 2 = C W.Ψ₂Sq + 4 * W.toAffine.polynomial := by
rw [C_Ψ₂Sq, sub_add_cancel]
lemma Affine.CoordinateRing.mk_ψ₂_sq : mk W W.ψ₂ ^ 2 = mk W (C W.Ψ₂Sq) := by
rw [C_Ψ₂Sq, map_sub, map_mul, AdjoinRoot.mk_self, mul_zero, sub_zero, map_pow]
-- TODO: remove `twoTorsionPolynomial` in favour of `Ψ₂Sq`
lemma Ψ₂Sq_eq : W.Ψ₂Sq = W.twoTorsionPolynomial.toPoly :=
rfl
end Ψ₂Sq
section preΨ'
/-! ### The univariate polynomials `preΨₙ` for `n ∈ ℕ` -/
/-- The `3`-division polynomial `ψ₃ = Ψ₃`. -/
noncomputable def Ψ₃ : R[X] :=
3 * X ^ 4 + C W.b₂ * X ^ 3 + 3 * C W.b₄ * X ^ 2 + 3 * C W.b₆ * X + C W.b₈
/-- The univariate polynomial `preΨ₄`, which is auxiliary to the 4-division polynomial
`ψ₄ = Ψ₄ = preΨ₄ψ₂`. -/
noncomputable def preΨ₄ : R[X] :=
2 * X ^ 6 + C W.b₂ * X ^ 5 + 5 * C W.b₄ * X ^ 4 + 10 * C W.b₆ * X ^ 3 + 10 * C W.b₈ * X ^ 2 +
C (W.b₂ * W.b₈ - W.b₄ * W.b₆) * X + C (W.b₄ * W.b₈ - W.b₆ ^ 2)
/-- The univariate polynomials `preΨₙ` for `n ∈ ℕ`, which are auxiliary to the bivariate polynomials
`Ψₙ` congruent to the bivariate `n`-division polynomials `ψₙ`. -/
noncomputable def preΨ' (n : ℕ) : R[X] :=
preNormEDS' (W.Ψ₂Sq ^ 2) W.Ψ₃ W.preΨ₄ n
@[simp]
lemma preΨ'_zero : W.preΨ' 0 = 0 :=
preNormEDS'_zero ..
@[simp]
lemma preΨ'_one : W.preΨ' 1 = 1 :=
preNormEDS'_one ..
@[simp]
lemma preΨ'_two : W.preΨ' 2 = 1 :=
preNormEDS'_two ..
@[simp]
lemma preΨ'_three : W.preΨ' 3 = W.Ψ₃ :=
preNormEDS'_three ..
@[simp]
lemma preΨ'_four : W.preΨ' 4 = W.preΨ₄ :=
preNormEDS'_four ..
lemma preΨ'_even (m : ℕ) : W.preΨ' (2 * (m + 3)) =
W.preΨ' (m + 2) ^ 2 * W.preΨ' (m + 3) * W.preΨ' (m + 5) -
W.preΨ' (m + 1) * W.preΨ' (m + 3) * W.preΨ' (m + 4) ^ 2 :=
preNormEDS'_even ..
lemma preΨ'_odd (m : ℕ) : W.preΨ' (2 * (m + 2) + 1) =
W.preΨ' (m + 4) * W.preΨ' (m + 2) ^ 3 * (if Even m then W.Ψ₂Sq ^ 2 else 1) -
W.preΨ' (m + 1) * W.preΨ' (m + 3) ^ 3 * (if Even m then 1 else W.Ψ₂Sq ^ 2) :=
preNormEDS'_odd ..
end preΨ'
section preΨ
/-! ### The univariate polynomials `preΨₙ` for `n ∈ ℤ` -/
/-- The univariate polynomials `preΨₙ` for `n ∈ ℤ`, which are auxiliary to the bivariate polynomials
`Ψₙ` congruent to the bivariate `n`-division polynomials `ψₙ`. -/
noncomputable def preΨ (n : ℤ) : R[X] :=
preNormEDS (W.Ψ₂Sq ^ 2) W.Ψ₃ W.preΨ₄ n
@[simp]
lemma preΨ_ofNat (n : ℕ) : W.preΨ n = W.preΨ' n :=
preNormEDS_ofNat ..
@[simp]
lemma preΨ_zero : W.preΨ 0 = 0 :=
preNormEDS_zero ..
@[simp]
lemma preΨ_one : W.preΨ 1 = 1 :=
preNormEDS_one ..
@[simp]
lemma preΨ_two : W.preΨ 2 = 1 :=
preNormEDS_two ..
@[simp]
lemma preΨ_three : W.preΨ 3 = W.Ψ₃ :=
preNormEDS_three ..
@[simp]
lemma preΨ_four : W.preΨ 4 = W.preΨ₄ :=
preNormEDS_four ..
lemma preΨ_even_ofNat (m : ℕ) : W.preΨ (2 * (m + 3)) =
W.preΨ (m + 2) ^ 2 * W.preΨ (m + 3) * W.preΨ (m + 5) -
W.preΨ (m + 1) * W.preΨ (m + 3) * W.preΨ (m + 4) ^ 2 :=
preNormEDS_even_ofNat ..
lemma preΨ_odd_ofNat (m : ℕ) : W.preΨ (2 * (m + 2) + 1) =
W.preΨ (m + 4) * W.preΨ (m + 2) ^ 3 * (if Even m then W.Ψ₂Sq ^ 2 else 1) -
W.preΨ (m + 1) * W.preΨ (m + 3) ^ 3 * (if Even m then 1 else W.Ψ₂Sq ^ 2) :=
preNormEDS_odd_ofNat ..
@[simp]
lemma preΨ_neg (n : ℤ) : W.preΨ (-n) = -W.preΨ n :=
preNormEDS_neg ..
lemma preΨ_even (m : ℤ) : W.preΨ (2 * m) =
W.preΨ (m - 1) ^ 2 * W.preΨ m * W.preΨ (m + 2) -
W.preΨ (m - 2) * W.preΨ m * W.preΨ (m + 1) ^ 2 :=
preNormEDS_even ..
lemma preΨ_odd (m : ℤ) : W.preΨ (2 * m + 1) =
W.preΨ (m + 2) * W.preΨ m ^ 3 * (if Even m then W.Ψ₂Sq ^ 2 else 1) -
W.preΨ (m - 1) * W.preΨ (m + 1) ^ 3 * (if Even m then 1 else W.Ψ₂Sq ^ 2) :=
preNormEDS_odd ..
end preΨ
section ΨSq
/-! ### The univariate polynomials `ΨSqₙ` -/
/-- The univariate polynomials `ΨSqₙ` congruent to `ψₙ²`. -/
noncomputable def ΨSq (n : ℤ) : R[X] :=
W.preΨ n ^ 2 * if Even n then W.Ψ₂Sq else 1
@[simp]
lemma ΨSq_ofNat (n : ℕ) : W.ΨSq n = W.preΨ' n ^ 2 * if Even n then W.Ψ₂Sq else 1 := by
simp only [ΨSq, preΨ_ofNat, Int.even_coe_nat]
@[simp]
lemma ΨSq_zero : W.ΨSq 0 = 0 := by
rw [← Nat.cast_zero, ΨSq_ofNat, preΨ'_zero, zero_pow two_ne_zero, zero_mul]
@[simp]
lemma ΨSq_one : W.ΨSq 1 = 1 := by
rw [← Nat.cast_one, ΨSq_ofNat, preΨ'_one, one_pow, one_mul, if_neg Nat.not_even_one]
@[simp]
lemma ΨSq_two : W.ΨSq 2 = W.Ψ₂Sq := by
rw [← Nat.cast_two, ΨSq_ofNat, preΨ'_two, one_pow, one_mul, if_pos even_two]
@[simp]
lemma ΨSq_three : W.ΨSq 3 = W.Ψ₃ ^ 2 := by
| rw [← Nat.cast_three, ΨSq_ofNat, preΨ'_three, if_neg <| by decide, mul_one]
@[simp]
lemma ΨSq_four : W.ΨSq 4 = W.preΨ₄ ^ 2 * W.Ψ₂Sq := by
| Mathlib/AlgebraicGeometry/EllipticCurve/DivisionPolynomial/Basic.lean | 275 | 278 |
/-
Copyright (c) 2023 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang, Junyan Xu
-/
import Mathlib.Algebra.Category.ModuleCat.Basic
import Mathlib.Algebra.Category.Grp.Injective
import Mathlib.Topology.Instances.AddCircle
import Mathlib.LinearAlgebra.Isomorphisms
/-!
# Character module of a module
For commutative ring `R` and an `R`-module `M` and an injective module `D`, its character module
`M⋆` is defined to be `R`-linear maps `M ⟶ D`.
`M⋆` also has an `R`-module structure given by `(r • f) m = f (r • m)`.
## Main results
- `CharacterModuleFunctor` : the contravariant functor of `R`-modules where `M ↦ M⋆` and
an `R`-linear map `l : M ⟶ N` induces an `R`-linear map `l⋆ : f ↦ f ∘ l` where `f : N⋆`.
- `LinearMap.dual_surjective_of_injective` : If `l` is injective then `l⋆` is surjective,
in another word taking character module as a functor sends monos to epis.
- `CharacterModule.homEquiv` : there is a bijection between linear map `Hom(N, M⋆)` and
`(N ⊗ M)⋆` given by `curry` and `uncurry`.
-/
open CategoryTheory
universe uR uA uB
variable (R : Type uR) [CommRing R]
variable (A : Type uA) [AddCommGroup A]
variable (A' : Type*) [AddCommGroup A']
variable (B : Type uB) [AddCommGroup B]
/--
The character module of an abelian group `A` in the unit rational circle is `A⋆ := Hom_ℤ(A, ℚ ⧸ ℤ)`.
-/
def CharacterModule : Type uA := A →+ AddCircle (1 : ℚ)
namespace CharacterModule
instance : FunLike (CharacterModule A) A (AddCircle (1 : ℚ)) where
coe c := c.toFun
coe_injective' _ _ _ := by aesop
instance : LinearMapClass (CharacterModule A) ℤ A (AddCircle (1 : ℚ)) where
map_add _ _ _ := by rw [AddMonoidHom.map_add]
map_smulₛₗ _ _ _ := by rw [AddMonoidHom.map_zsmul, RingHom.id_apply]
instance : AddCommGroup (CharacterModule A) :=
inferInstanceAs (AddCommGroup (A →+ _))
@[ext] theorem ext {c c' : CharacterModule A} (h : ∀ x, c x = c' x) : c = c' := DFunLike.ext _ _ h
section module
variable [Module R A] [Module R A'] [Module R B]
instance : Module R (CharacterModule A) :=
Module.compHom (A →+ _) (RingEquiv.toOpposite _ |>.toRingHom : R →+* Rᵈᵐᵃ)
variable {R A B}
@[simp] lemma smul_apply (c : CharacterModule A) (r : R) (a : A) : (r • c) a = c (r • a) := rfl
/--
Given an abelian group homomorphism `f : A → B`, `f⋆(L) := L ∘ f` defines a linear map
from `B⋆` to `A⋆`.
-/
@[simps] def dual (f : A →ₗ[R] B) : CharacterModule B →ₗ[R] CharacterModule A where
toFun L := L.comp f.toAddMonoidHom
map_add' := by aesop
map_smul' r c := by ext x; exact congr(c $(f.map_smul r x)).symm
@[simp]
lemma dual_zero : dual (0 : A →ₗ[R] B) = 0 := by
ext f
exact map_zero f
lemma dual_comp {C : Type*} [AddCommGroup C] [Module R C] (f : A →ₗ[R] B) (g : B →ₗ[R] C) :
dual (g.comp f) = (dual f).comp (dual g) := by
ext
rfl
lemma dual_injective_of_surjective (f : A →ₗ[R] B) (hf : Function.Surjective f) :
Function.Injective (dual f) := by
intro φ ψ eq
ext x
obtain ⟨y, rfl⟩ := hf x
change (dual f) φ _ = (dual f) ψ _
rw [eq]
lemma dual_surjective_of_injective (f : A →ₗ[R] B) (hf : Function.Injective f) :
Function.Surjective (dual f) :=
(Module.Baer.of_divisible _).extension_property_addMonoidHom _ hf
/--
Two isomorphic modules have isomorphic character modules.
-/
def congr (e : A ≃ₗ[R] B) : CharacterModule A ≃ₗ[R] CharacterModule B :=
.ofLinear (dual e.symm) (dual e)
(by ext c _; exact congr(c $(e.right_inv _)))
(by ext c _; exact congr(c $(e.left_inv _)))
open TensorProduct
/--
Any linear map `L : A → B⋆` induces a character in `(A ⊗ B)⋆` by `a ⊗ b ↦ L a b`.
-/
@[simps] noncomputable def uncurry :
(A →ₗ[R] CharacterModule B) →ₗ[R] CharacterModule (A ⊗[R] B) where
toFun c := TensorProduct.liftAddHom c.toAddMonoidHom fun r a b ↦ congr($(c.map_smul r a) b)
map_add' c c' := DFunLike.ext _ _ fun x ↦ by refine x.induction_on ?_ ?_ ?_ <;> aesop
map_smul' r c := DFunLike.ext _ _ fun x ↦ x.induction_on
(by simp_rw [map_zero]) (fun a b ↦ congr($(c.map_smul r a) b).symm) (by aesop)
/--
Any character `c` in `(A ⊗ B)⋆` induces a linear map `A → B⋆` by `a ↦ b ↦ c (a ⊗ b)`.
-/
@[simps] noncomputable def curry :
CharacterModule (A ⊗[R] B) →ₗ[R] (A →ₗ[R] CharacterModule B) where
toFun c :=
{ toFun := (c.comp <| TensorProduct.mk R A B ·)
map_add' := fun _ _ ↦ DFunLike.ext _ _ fun b ↦
congr(c <| $(map_add (mk R A B) _ _) b).trans (c.map_add _ _)
map_smul' := fun r a ↦ by ext; exact congr(c $(TensorProduct.tmul_smul _ _ _)).symm }
map_add' _ _ := rfl
map_smul' r c := by ext; exact congr(c $(TensorProduct.tmul_smul _ _ _)).symm
/--
Linear maps into a character module are exactly characters of the tensor product.
-/
@[simps!] noncomputable def homEquiv :
(A →ₗ[R] CharacterModule B) ≃ₗ[R] CharacterModule (A ⊗[R] B) :=
.ofLinear uncurry curry (by ext _ z; refine z.induction_on ?_ ?_ ?_ <;> aesop) (by aesop)
theorem dual_rTensor_conj_homEquiv (f : A →ₗ[R] A') :
homEquiv.symm.toLinearMap ∘ₗ dual (f.rTensor B) ∘ₗ homEquiv.toLinearMap = f.lcomp R _ := rfl
end module
/--
`ℤ⋆`, the character module of `ℤ` in the unit rational circle.
-/
protected abbrev int : Type := CharacterModule ℤ
/-- Given `n : ℕ`, the map `m ↦ m / n`. -/
protected abbrev int.divByNat (n : ℕ) : CharacterModule.int :=
LinearMap.toSpanSingleton ℤ _ (QuotientAddGroup.mk (n : ℚ)⁻¹) |>.toAddMonoidHom
protected lemma int.divByNat_self (n : ℕ) :
int.divByNat n n = 0 := by
obtain rfl | h0 := eq_or_ne n 0
· apply map_zero
exact (AddCircle.coe_eq_zero_iff _).mpr
⟨1, by simp [mul_inv_cancel₀ (Nat.cast_ne_zero (R := ℚ).mpr h0)]⟩
variable {A}
/-- The `ℤ`-submodule spanned by a single element `a` is isomorphic to the quotient of `ℤ`
by the ideal generated by the order of `a`. -/
@[simps!] noncomputable def intSpanEquivQuotAddOrderOf (a : A) :
(ℤ ∙ a) ≃ₗ[ℤ] ℤ ⧸ Ideal.span {(addOrderOf a : ℤ)} :=
LinearEquiv.ofEq _ _ (LinearMap.span_singleton_eq_range ℤ A a) ≪≫ₗ
(LinearMap.quotKerEquivRange <| LinearMap.toSpanSingleton ℤ A a).symm ≪≫ₗ
Submodule.quotEquivOfEq _ _ (by
ext1 x
rw [Ideal.mem_span_singleton, addOrderOf_dvd_iff_zsmul_eq_zero, LinearMap.mem_ker,
LinearMap.toSpanSingleton_apply])
lemma intSpanEquivQuotAddOrderOf_apply_self (a : A) :
intSpanEquivQuotAddOrderOf a ⟨a, Submodule.mem_span_singleton_self a⟩ =
Submodule.Quotient.mk 1 :=
(LinearEquiv.eq_symm_apply _).mp <| Subtype.ext (one_zsmul _).symm
/--
For an abelian group `A` and an element `a ∈ A`, there is a character `c : ℤ ∙ a → ℚ ⧸ ℤ` given by
`m • a ↦ m / n` where `n` is the smallest positive integer such that `n • a = 0` and when such `n`
does not exist, `c` is defined by `m • a ↦ m / 2`.
-/
noncomputable def ofSpanSingleton (a : A) : CharacterModule (ℤ ∙ a) :=
let l : ℤ ⧸ Ideal.span {(addOrderOf a : ℤ)} →ₗ[ℤ] AddCircle (1 : ℚ) :=
Submodule.liftQSpanSingleton _
(CharacterModule.int.divByNat <|
if addOrderOf a = 0 then 2 else addOrderOf a).toIntLinearMap <| by
split_ifs with h
· rw [h, Nat.cast_zero, map_zero]
· apply CharacterModule.int.divByNat_self
l ∘ₗ intSpanEquivQuotAddOrderOf a |>.toAddMonoidHom
lemma eq_zero_of_ofSpanSingleton_apply_self (a : A)
(h : ofSpanSingleton a ⟨a, Submodule.mem_span_singleton_self a⟩ = 0) : a = 0 := by
erw [ofSpanSingleton, LinearMap.toAddMonoidHom_coe, LinearMap.comp_apply,
intSpanEquivQuotAddOrderOf_apply_self, Submodule.liftQSpanSingleton_apply,
| AddMonoidHom.coe_toIntLinearMap, int.divByNat, LinearMap.toSpanSingleton_one,
AddCircle.coe_eq_zero_iff] at h
| Mathlib/Algebra/Module/CharacterModule.lean | 200 | 201 |
/-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import Mathlib.Data.List.Cycle
import Mathlib.GroupTheory.Perm.Cycle.Type
import Mathlib.GroupTheory.Perm.List
/-!
# Properties of cyclic permutations constructed from lists/cycles
In the following, `{α : Type*} [Fintype α] [DecidableEq α]`.
## Main definitions
* `Cycle.formPerm`: the cyclic permutation created by looping over a `Cycle α`
* `Equiv.Perm.toList`: the list formed by iterating application of a permutation
* `Equiv.Perm.toCycle`: the cycle formed by iterating application of a permutation
* `Equiv.Perm.isoCycle`: the equivalence between cyclic permutations `f : Perm α`
and the terms of `Cycle α` that correspond to them
* `Equiv.Perm.isoCycle'`: the same equivalence as `Equiv.Perm.isoCycle`
but with evaluation via choosing over fintypes
* The notation `c[1, 2, 3]` to emulate notation of cyclic permutations `(1 2 3)`
* A `Repr` instance for any `Perm α`, by representing the `Finset` of
`Cycle α` that correspond to the cycle factors.
## Main results
* `List.isCycle_formPerm`: a nontrivial list without duplicates, when interpreted as
a permutation, is cyclic
* `Equiv.Perm.IsCycle.existsUnique_cycle`: there is only one nontrivial `Cycle α`
corresponding to each cyclic `f : Perm α`
## Implementation details
The forward direction of `Equiv.Perm.isoCycle'` uses `Fintype.choose` of the uniqueness
result, relying on the `Fintype` instance of a `Cycle.Nodup` subtype.
It is unclear if this works faster than the `Equiv.Perm.toCycle`, which relies
on recursion over `Finset.univ`.
-/
open Equiv Equiv.Perm List
variable {α : Type*}
namespace List
variable [DecidableEq α] {l l' : List α}
theorem formPerm_disjoint_iff (hl : Nodup l) (hl' : Nodup l') (hn : 2 ≤ l.length)
(hn' : 2 ≤ l'.length) : Perm.Disjoint (formPerm l) (formPerm l') ↔ l.Disjoint l' := by
rw [disjoint_iff_eq_or_eq, List.Disjoint]
constructor
· rintro h x hx hx'
specialize h x
rw [formPerm_apply_mem_eq_self_iff _ hl _ hx, formPerm_apply_mem_eq_self_iff _ hl' _ hx'] at h
omega
· intro h x
by_cases hx : x ∈ l
on_goal 1 => by_cases hx' : x ∈ l'
· exact (h hx hx').elim
all_goals have := formPerm_eq_self_of_not_mem _ _ ‹_›; tauto
theorem isCycle_formPerm (hl : Nodup l) (hn : 2 ≤ l.length) : IsCycle (formPerm l) := by
rcases l with - | ⟨x, l⟩
· norm_num at hn
induction' l with y l generalizing x
· norm_num at hn
· use x
constructor
· rwa [formPerm_apply_mem_ne_self_iff _ hl _ mem_cons_self]
· intro w hw
have : w ∈ x::y::l := mem_of_formPerm_ne_self _ _ hw
obtain ⟨k, hk, rfl⟩ := getElem_of_mem this
use k
simp only [zpow_natCast, formPerm_pow_apply_head _ _ hl k, Nat.mod_eq_of_lt hk]
theorem pairwise_sameCycle_formPerm (hl : Nodup l) (hn : 2 ≤ l.length) :
Pairwise l.formPerm.SameCycle l :=
Pairwise.imp_mem.mpr
(pairwise_of_forall fun _ _ hx hy =>
(isCycle_formPerm hl hn).sameCycle ((formPerm_apply_mem_ne_self_iff _ hl _ hx).mpr hn)
((formPerm_apply_mem_ne_self_iff _ hl _ hy).mpr hn))
theorem cycleOf_formPerm (hl : Nodup l) (hn : 2 ≤ l.length) (x) :
cycleOf l.attach.formPerm x = l.attach.formPerm :=
have hn : 2 ≤ l.attach.length := by rwa [← length_attach] at hn
have hl : l.attach.Nodup := by rwa [← nodup_attach] at hl
(isCycle_formPerm hl hn).cycleOf_eq
((formPerm_apply_mem_ne_self_iff _ hl _ (mem_attach _ _)).mpr hn)
theorem cycleType_formPerm (hl : Nodup l) (hn : 2 ≤ l.length) :
cycleType l.attach.formPerm = {l.length} := by
rw [← length_attach] at hn
rw [← nodup_attach] at hl
rw [cycleType_eq [l.attach.formPerm]]
· simp only [map, Function.comp_apply]
rw [support_formPerm_of_nodup _ hl, card_toFinset, dedup_eq_self.mpr hl]
· simp
· intro x h
| simp [h, Nat.succ_le_succ_iff] at hn
· simp
· simpa using isCycle_formPerm hl hn
· simp
theorem formPerm_apply_mem_eq_next (hl : Nodup l) (x : α) (hx : x ∈ l) :
formPerm l x = next l x hx := by
obtain ⟨k, hk, rfl⟩ := getElem_of_mem hx
rw [next_getElem _ hl, formPerm_apply_getElem _ hl]
end List
namespace Cycle
| Mathlib/GroupTheory/Perm/Cycle/Concrete.lean | 105 | 117 |
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon
-/
import Mathlib.Algebra.Notation.Defs
import Mathlib.Data.Set.Subsingleton
import Mathlib.Logic.Equiv.Defs
/-!
# Partial values of a type
This file defines `Part α`, the partial values of a type.
`o : Part α` carries a proposition `o.Dom`, its domain, along with a function `get : o.Dom → α`, its
value. The rule is then that every partial value has a value but, to access it, you need to provide
a proof of the domain.
`Part α` behaves the same as `Option α` except that `o : Option α` is decidably `none` or `some a`
for some `a : α`, while the domain of `o : Part α` doesn't have to be decidable. That means you can
translate back and forth between a partial value with a decidable domain and an option, and
`Option α` and `Part α` are classically equivalent. In general, `Part α` is bigger than `Option α`.
In current mathlib, `Part ℕ`, aka `PartENat`, is used to move decidability of the order to
decidability of `PartENat.find` (which is the smallest natural satisfying a predicate, or `∞` if
there's none).
## Main declarations
`Option`-like declarations:
* `Part.none`: The partial value whose domain is `False`.
* `Part.some a`: The partial value whose domain is `True` and whose value is `a`.
* `Part.ofOption`: Converts an `Option α` to a `Part α` by sending `none` to `none` and `some a` to
`some a`.
* `Part.toOption`: Converts a `Part α` with a decidable domain to an `Option α`.
* `Part.equivOption`: Classical equivalence between `Part α` and `Option α`.
Monadic structure:
* `Part.bind`: `o.bind f` has value `(f (o.get _)).get _` (`f o` morally) and is defined when `o`
and `f (o.get _)` are defined.
* `Part.map`: Maps the value and keeps the same domain.
Other:
* `Part.restrict`: `Part.restrict p o` replaces the domain of `o : Part α` by `p : Prop` so long as
`p → o.Dom`.
* `Part.assert`: `assert p f` appends `p` to the domains of the values of a partial function.
* `Part.unwrap`: Gets the value of a partial value regardless of its domain. Unsound.
## Notation
For `a : α`, `o : Part α`, `a ∈ o` means that `o` is defined and equal to `a`. Formally, it means
`o.Dom` and `o.get _ = a`.
-/
assert_not_exists RelIso
open Function
/-- `Part α` is the type of "partial values" of type `α`. It
is similar to `Option α` except the domain condition can be an
arbitrary proposition, not necessarily decidable. -/
structure Part.{u} (α : Type u) : Type u where
/-- The domain of a partial value -/
Dom : Prop
/-- Extract a value from a partial value given a proof of `Dom` -/
get : Dom → α
namespace Part
variable {α : Type*} {β : Type*} {γ : Type*}
/-- Convert a `Part α` with a decidable domain to an option -/
def toOption (o : Part α) [Decidable o.Dom] : Option α :=
if h : Dom o then some (o.get h) else none
@[simp] lemma toOption_isSome (o : Part α) [Decidable o.Dom] : o.toOption.isSome ↔ o.Dom := by
by_cases h : o.Dom <;> simp [h, toOption]
@[simp] lemma toOption_eq_none (o : Part α) [Decidable o.Dom] : o.toOption = none ↔ ¬o.Dom := by
by_cases h : o.Dom <;> simp [h, toOption]
/-- `Part` extensionality -/
theorem ext' : ∀ {o p : Part α}, (o.Dom ↔ p.Dom) → (∀ h₁ h₂, o.get h₁ = p.get h₂) → o = p
| ⟨od, o⟩, ⟨pd, p⟩, H1, H2 => by
have t : od = pd := propext H1
cases t; rw [show o = p from funext fun p => H2 p p]
/-- `Part` eta expansion -/
@[simp]
theorem eta : ∀ o : Part α, (⟨o.Dom, fun h => o.get h⟩ : Part α) = o
| ⟨_, _⟩ => rfl
/-- `a ∈ o` means that `o` is defined and equal to `a` -/
protected def Mem (o : Part α) (a : α) : Prop :=
∃ h, o.get h = a
instance : Membership α (Part α) :=
⟨Part.Mem⟩
theorem mem_eq (a : α) (o : Part α) : (a ∈ o) = ∃ h, o.get h = a :=
rfl
theorem dom_iff_mem : ∀ {o : Part α}, o.Dom ↔ ∃ y, y ∈ o
| ⟨_, f⟩ => ⟨fun h => ⟨f h, h, rfl⟩, fun ⟨_, h, rfl⟩ => h⟩
theorem get_mem {o : Part α} (h) : get o h ∈ o :=
⟨_, rfl⟩
@[simp]
theorem mem_mk_iff {p : Prop} {o : p → α} {a : α} : a ∈ Part.mk p o ↔ ∃ h, o h = a :=
Iff.rfl
/-- `Part` extensionality -/
@[ext]
theorem ext {o p : Part α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p :=
(ext' ⟨fun h => ((H _).1 ⟨h, rfl⟩).fst, fun h => ((H _).2 ⟨h, rfl⟩).fst⟩) fun _ _ =>
((H _).2 ⟨_, rfl⟩).snd
/-- The `none` value in `Part` has a `False` domain and an empty function. -/
def none : Part α :=
⟨False, False.rec⟩
instance : Inhabited (Part α) :=
⟨none⟩
@[simp]
theorem not_mem_none (a : α) : a ∉ @none α := fun h => h.fst
/-- The `some a` value in `Part` has a `True` domain and the
function returns `a`. -/
def some (a : α) : Part α :=
⟨True, fun _ => a⟩
@[simp]
theorem some_dom (a : α) : (some a).Dom :=
trivial
theorem mem_unique : ∀ {a b : α} {o : Part α}, a ∈ o → b ∈ o → a = b
| _, _, ⟨_, _⟩, ⟨_, rfl⟩, ⟨_, rfl⟩ => rfl
theorem mem_right_unique : ∀ {a : α} {o p : Part α}, a ∈ o → a ∈ p → o = p
| _, _, _, ⟨ho, _⟩, ⟨hp, _⟩ => ext' (iff_of_true ho hp) (by simp [*])
theorem Mem.left_unique : Relator.LeftUnique ((· ∈ ·) : α → Part α → Prop) := fun _ _ _ =>
mem_unique
theorem Mem.right_unique : Relator.RightUnique ((· ∈ ·) : α → Part α → Prop) := fun _ _ _ =>
mem_right_unique
theorem get_eq_of_mem {o : Part α} {a} (h : a ∈ o) (h') : get o h' = a :=
mem_unique ⟨_, rfl⟩ h
protected theorem subsingleton (o : Part α) : Set.Subsingleton { a | a ∈ o } := fun _ ha _ hb =>
mem_unique ha hb
@[simp]
theorem get_some {a : α} (ha : (some a).Dom) : get (some a) ha = a :=
rfl
theorem mem_some (a : α) : a ∈ some a :=
⟨trivial, rfl⟩
@[simp]
theorem mem_some_iff {a b} : b ∈ (some a : Part α) ↔ b = a :=
⟨fun ⟨_, e⟩ => e.symm, fun e => ⟨trivial, e.symm⟩⟩
theorem eq_some_iff {a : α} {o : Part α} : o = some a ↔ a ∈ o :=
⟨fun e => e.symm ▸ mem_some _, fun ⟨h, e⟩ => e ▸ ext' (iff_true_intro h) fun _ _ => rfl⟩
theorem eq_none_iff {o : Part α} : o = none ↔ ∀ a, a ∉ o :=
⟨fun e => e.symm ▸ not_mem_none, fun h => ext (by simpa)⟩
theorem eq_none_iff' {o : Part α} : o = none ↔ ¬o.Dom :=
⟨fun e => e.symm ▸ id, fun h => eq_none_iff.2 fun _ h' => h h'.fst⟩
@[simp]
theorem not_none_dom : ¬(none : Part α).Dom :=
id
@[simp]
theorem some_ne_none (x : α) : some x ≠ none := by
intro h
exact true_ne_false (congr_arg Dom h)
@[simp]
theorem none_ne_some (x : α) : none ≠ some x :=
(some_ne_none x).symm
theorem ne_none_iff {o : Part α} : o ≠ none ↔ ∃ x, o = some x := by
constructor
· rw [Ne, eq_none_iff', not_not]
exact fun h => ⟨o.get h, eq_some_iff.2 (get_mem h)⟩
· rintro ⟨x, rfl⟩
apply some_ne_none
theorem eq_none_or_eq_some (o : Part α) : o = none ∨ ∃ x, o = some x :=
or_iff_not_imp_left.2 ne_none_iff.1
theorem some_injective : Injective (@Part.some α) := fun _ _ h =>
congr_fun (eq_of_heq (Part.mk.inj h).2) trivial
@[simp]
theorem some_inj {a b : α} : Part.some a = some b ↔ a = b :=
some_injective.eq_iff
@[simp]
theorem some_get {a : Part α} (ha : a.Dom) : Part.some (Part.get a ha) = a :=
Eq.symm (eq_some_iff.2 ⟨ha, rfl⟩)
theorem get_eq_iff_eq_some {a : Part α} {ha : a.Dom} {b : α} : a.get ha = b ↔ a = some b :=
⟨fun h => by simp [h.symm], fun h => by simp [h]⟩
theorem get_eq_get_of_eq (a : Part α) (ha : a.Dom) {b : Part α} (h : a = b) :
a.get ha = b.get (h ▸ ha) := by
congr
theorem get_eq_iff_mem {o : Part α} {a : α} (h : o.Dom) : o.get h = a ↔ a ∈ o :=
⟨fun H => ⟨h, H⟩, fun ⟨_, H⟩ => H⟩
theorem eq_get_iff_mem {o : Part α} {a : α} (h : o.Dom) : a = o.get h ↔ a ∈ o :=
eq_comm.trans (get_eq_iff_mem h)
@[simp]
theorem none_toOption [Decidable (@none α).Dom] : (none : Part α).toOption = Option.none :=
dif_neg id
@[simp]
theorem some_toOption (a : α) [Decidable (some a).Dom] : (some a).toOption = Option.some a :=
dif_pos trivial
instance noneDecidable : Decidable (@none α).Dom :=
instDecidableFalse
instance someDecidable (a : α) : Decidable (some a).Dom :=
instDecidableTrue
/-- Retrieves the value of `a : Part α` if it exists, and return the provided default value
otherwise. -/
def getOrElse (a : Part α) [Decidable a.Dom] (d : α) :=
if ha : a.Dom then a.get ha else d
theorem getOrElse_of_dom (a : Part α) (h : a.Dom) [Decidable a.Dom] (d : α) :
getOrElse a d = a.get h :=
dif_pos h
theorem getOrElse_of_not_dom (a : Part α) (h : ¬a.Dom) [Decidable a.Dom] (d : α) :
getOrElse a d = d :=
dif_neg h
@[simp]
theorem getOrElse_none (d : α) [Decidable (none : Part α).Dom] : getOrElse none d = d :=
none.getOrElse_of_not_dom not_none_dom d
@[simp]
theorem getOrElse_some (a : α) (d : α) [Decidable (some a).Dom] : getOrElse (some a) d = a :=
(some a).getOrElse_of_dom (some_dom a) d
-- `simp`-normal form is `toOption_eq_some_iff`.
theorem mem_toOption {o : Part α} [Decidable o.Dom] {a : α} : a ∈ toOption o ↔ a ∈ o := by
unfold toOption
by_cases h : o.Dom <;> simp [h]
· exact ⟨fun h => ⟨_, h⟩, fun ⟨_, h⟩ => h⟩
· exact mt Exists.fst h
@[simp]
theorem toOption_eq_some_iff {o : Part α} [Decidable o.Dom] {a : α} :
toOption o = Option.some a ↔ a ∈ o := by
rw [← Option.mem_def, mem_toOption]
protected theorem Dom.toOption {o : Part α} [Decidable o.Dom] (h : o.Dom) : o.toOption = o.get h :=
dif_pos h
theorem toOption_eq_none_iff {a : Part α} [Decidable a.Dom] : a.toOption = Option.none ↔ ¬a.Dom :=
Ne.dite_eq_right_iff fun _ => Option.some_ne_none _
@[simp]
theorem elim_toOption {α β : Type*} (a : Part α) [Decidable a.Dom] (b : β) (f : α → β) :
a.toOption.elim b f = if h : a.Dom then f (a.get h) else b := by
split_ifs with h
· rw [h.toOption]
rfl
· rw [Part.toOption_eq_none_iff.2 h]
rfl
/-- Converts an `Option α` into a `Part α`. -/
@[coe]
def ofOption : Option α → Part α
| Option.none => none
| Option.some a => some a
@[simp]
theorem mem_ofOption {a : α} : ∀ {o : Option α}, a ∈ ofOption o ↔ a ∈ o
| Option.none => ⟨fun h => h.fst.elim, fun h => Option.noConfusion h⟩
| Option.some _ => ⟨fun h => congr_arg Option.some h.snd, fun h => ⟨trivial, Option.some.inj h⟩⟩
@[simp]
theorem ofOption_dom {α} : ∀ o : Option α, (ofOption o).Dom ↔ o.isSome
| Option.none => by simp [ofOption, none]
| Option.some a => by simp [ofOption]
theorem ofOption_eq_get {α} (o : Option α) : ofOption o = ⟨_, @Option.get _ o⟩ :=
Part.ext' (ofOption_dom o) fun h₁ h₂ => by
cases o
· simp at h₂
· rfl
instance : Coe (Option α) (Part α) :=
⟨ofOption⟩
theorem mem_coe {a : α} {o : Option α} : a ∈ (o : Part α) ↔ a ∈ o :=
mem_ofOption
@[simp]
theorem coe_none : (@Option.none α : Part α) = none :=
rfl
@[simp]
theorem coe_some (a : α) : (Option.some a : Part α) = some a :=
rfl
@[elab_as_elim]
protected theorem induction_on {P : Part α → Prop} (a : Part α) (hnone : P none)
(hsome : ∀ a : α, P (some a)) : P a :=
(Classical.em a.Dom).elim (fun h => Part.some_get h ▸ hsome _) fun h =>
(eq_none_iff'.2 h).symm ▸ hnone
instance ofOptionDecidable : ∀ o : Option α, Decidable (ofOption o).Dom
| Option.none => Part.noneDecidable
| Option.some a => Part.someDecidable a
@[simp]
theorem to_ofOption (o : Option α) : toOption (ofOption o) = o := by cases o <;> rfl
@[simp]
theorem of_toOption (o : Part α) [Decidable o.Dom] : ofOption (toOption o) = o :=
ext fun _ => mem_ofOption.trans mem_toOption
/-- `Part α` is (classically) equivalent to `Option α`. -/
noncomputable def equivOption : Part α ≃ Option α :=
haveI := Classical.dec
⟨fun o => toOption o, ofOption, fun o => of_toOption o, fun o =>
Eq.trans (by dsimp; congr) (to_ofOption o)⟩
/-- We give `Part α` the order where everything is greater than `none`. -/
instance : PartialOrder (Part
α) where
le x y := ∀ i, i ∈ x → i ∈ y
le_refl _ _ := id
le_trans _ _ _ f g _ := g _ ∘ f _
le_antisymm _ _ f g := Part.ext fun _ => ⟨f _, g _⟩
instance : OrderBot (Part α) where
bot := none
bot_le := by rintro x _ ⟨⟨_⟩, _⟩
theorem le_total_of_le_of_le {x y : Part α} (z : Part α) (hx : x ≤ z) (hy : y ≤ z) :
x ≤ y ∨ y ≤ x := by
rcases Part.eq_none_or_eq_some x with (h | ⟨b, h₀⟩)
· rw [h]
left
apply OrderBot.bot_le _
right; intro b' h₁
rw [Part.eq_some_iff] at h₀
have hx := hx _ h₀; have hy := hy _ h₁
have hx := Part.mem_unique hx hy; subst hx
exact h₀
/-- `assert p f` is a bind-like operation which appends an additional condition
`p` to the domain and uses `f` to produce the value. -/
def assert (p : Prop) (f : p → Part α) : Part α :=
⟨∃ h : p, (f h).Dom, fun ha => (f ha.fst).get ha.snd⟩
/-- The bind operation has value `g (f.get)`, and is defined when all the
parts are defined. -/
protected def bind (f : Part α) (g : α → Part β) : Part β :=
assert (Dom f) fun b => g (f.get b)
/-- The map operation for `Part` just maps the value and maintains the same domain. -/
@[simps]
def map (f : α → β) (o : Part α) : Part β :=
⟨o.Dom, f ∘ o.get⟩
theorem mem_map (f : α → β) {o : Part α} : ∀ {a}, a ∈ o → f a ∈ map f o
| _, ⟨_, rfl⟩ => ⟨_, rfl⟩
@[simp]
theorem mem_map_iff (f : α → β) {o : Part α} {b} : b ∈ map f o ↔ ∃ a ∈ o, f a = b :=
⟨fun hb => match b, hb with
| _, ⟨_, rfl⟩ => ⟨_, ⟨_, rfl⟩, rfl⟩,
fun ⟨_, h₁, h₂⟩ => h₂ ▸ mem_map f h₁⟩
@[simp]
theorem map_none (f : α → β) : map f none = none :=
eq_none_iff.2 fun a => by simp
@[simp]
theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) :=
eq_some_iff.2 <| mem_map f <| mem_some _
theorem mem_assert {p : Prop} {f : p → Part α} : ∀ {a} (h : p), a ∈ f h → a ∈ assert p f
| _, x, ⟨h, rfl⟩ => ⟨⟨x, h⟩, rfl⟩
@[simp]
theorem mem_assert_iff {p : Prop} {f : p → Part α} {a} : a ∈ assert p f ↔ ∃ h : p, a ∈ f h :=
⟨fun ha => match a, ha with
| _, ⟨_, rfl⟩ => ⟨_, ⟨_, rfl⟩⟩,
fun ⟨_, h⟩ => mem_assert _ h⟩
theorem assert_pos {p : Prop} {f : p → Part α} (h : p) : assert p f = f h := by
dsimp [assert]
cases h' : f h
simp only [h', mk.injEq, h, exists_prop_of_true, true_and]
apply Function.hfunext
· simp only [h, h', exists_prop_of_true]
· simp
theorem assert_neg {p : Prop} {f : p → Part α} (h : ¬p) : assert p f = none := by
dsimp [assert, none]; congr
· simp only [h, not_false_iff, exists_prop_of_false]
· apply Function.hfunext
· simp only [h, not_false_iff, exists_prop_of_false]
simp at *
theorem mem_bind {f : Part α} {g : α → Part β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g
| _, _, ⟨h, rfl⟩, ⟨h₂, rfl⟩ => ⟨⟨h, h₂⟩, rfl⟩
@[simp]
theorem mem_bind_iff {f : Part α} {g : α → Part β} {b} : b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a :=
⟨fun hb => match b, hb with
| _, ⟨⟨_, _⟩, rfl⟩ => ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩,
fun ⟨_, h₁, h₂⟩ => mem_bind h₁ h₂⟩
protected theorem Dom.bind {o : Part α} (h : o.Dom) (f : α → Part β) : o.bind f = f (o.get h) := by
ext b
simp only [Part.mem_bind_iff, exists_prop]
refine ⟨?_, fun hb => ⟨o.get h, Part.get_mem _, hb⟩⟩
rintro ⟨a, ha, hb⟩
rwa [Part.get_eq_of_mem ha]
theorem Dom.of_bind {f : α → Part β} {a : Part α} (h : (a.bind f).Dom) : a.Dom :=
h.1
@[simp]
theorem bind_none (f : α → Part β) : none.bind f = none :=
eq_none_iff.2 fun a => by simp
@[simp]
theorem bind_some (a : α) (f : α → Part β) : (some a).bind f = f a :=
ext <| by simp
theorem bind_of_mem {o : Part α} {a : α} (h : a ∈ o) (f : α → Part β) : o.bind f = f a := by
rw [eq_some_iff.2 h, bind_some]
theorem bind_some_eq_map (f : α → β) (x : Part α) : x.bind (fun y => some (f y)) = map f x :=
ext <| by simp [eq_comm]
theorem bind_toOption (f : α → Part β) (o : Part α) [Decidable o.Dom] [∀ a, Decidable (f a).Dom]
[Decidable (o.bind f).Dom] :
(o.bind f).toOption = o.toOption.elim Option.none fun a => (f a).toOption := by
by_cases h : o.Dom
· simp_rw [h.toOption, h.bind]
rfl
· rw [Part.toOption_eq_none_iff.2 h]
exact Part.toOption_eq_none_iff.2 fun ho => h ho.of_bind
theorem bind_assoc {γ} (f : Part α) (g : α → Part β) (k : β → Part γ) :
(f.bind g).bind k = f.bind fun x => (g x).bind k :=
ext fun a => by
simp only [mem_bind_iff]
exact ⟨fun ⟨_, ⟨_, h₁, h₂⟩, h₃⟩ => ⟨_, h₁, _, h₂, h₃⟩,
fun ⟨_, h₁, _, h₂, h₃⟩ => ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩
@[simp]
theorem bind_map {γ} (f : α → β) (x) (g : β → Part γ) :
(map f x).bind g = x.bind fun y => g (f y) := by rw [← bind_some_eq_map, bind_assoc]; simp
@[simp]
theorem map_bind {γ} (f : α → Part β) (x : Part α) (g : β → γ) :
map g (x.bind f) = x.bind fun y => map g (f y) := by
rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map]
theorem map_map (g : β → γ) (f : α → β) (o : Part α) : map g (map f o) = map (g ∘ f) o := by
simp [map, Function.comp_assoc]
instance : Monad Part where
pure := @some
map := @map
bind := @Part.bind
instance : LawfulMonad
Part where
bind_pure_comp := @bind_some_eq_map
id_map f := by cases f; rfl
pure_bind := @bind_some
bind_assoc := @bind_assoc
map_const := by simp [Functor.mapConst, Functor.map]
--Porting TODO : In Lean3 these were automatic by a tactic
seqLeft_eq x y := ext'
(by simp [SeqLeft.seqLeft, Part.bind, assert, Seq.seq, const, (· <$> ·), and_comm])
(fun _ _ => rfl)
seqRight_eq x y := ext'
(by simp [SeqRight.seqRight, Part.bind, assert, Seq.seq, const, (· <$> ·), and_comm])
(fun _ _ => rfl)
pure_seq x y := ext'
(by simp [Seq.seq, Part.bind, assert, (· <$> ·), pure])
(fun _ _ => rfl)
bind_map x y := ext'
(by simp [(· >>= ·), Part.bind, assert, Seq.seq, get, (· <$> ·)] )
(fun _ _ => rfl)
theorem map_id' {f : α → α} (H : ∀ x : α, f x = x) (o) : map f o = o := by
rw [show f = id from funext H]; exact id_map o
@[simp]
theorem bind_some_right (x : Part α) : x.bind some = x := by
rw [bind_some_eq_map]
simp [map_id']
@[simp]
theorem pure_eq_some (a : α) : pure a = some a :=
rfl
|
@[simp]
| Mathlib/Data/Part.lean | 512 | 513 |
/-
Copyright (c) 2023 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.Algebra.Group.Nat.Defs
import Mathlib.CategoryTheory.Category.Preorder
import Mathlib.CategoryTheory.EqToHom
import Mathlib.CategoryTheory.Functor.Const
import Mathlib.Order.Fin.Basic
import Mathlib.Tactic.FinCases
import Mathlib.Tactic.SuppressCompilation
/-!
# Composable arrows
If `C` is a category, the type of `n`-simplices in the nerve of `C` identifies
to the type of functors `Fin (n + 1) ⥤ C`, which can be thought as families of `n` composable
arrows in `C`. In this file, we introduce and study this category `ComposableArrows C n`
of `n` composable arrows in `C`.
If `F : ComposableArrows C n`, we define `F.left` as the leftmost object, `F.right` as the
rightmost object, and `F.hom : F.left ⟶ F.right` is the canonical map.
The most significant definition in this file is the constructor
`F.precomp f : ComposableArrows C (n + 1)` for `F : ComposableArrows C n` and `f : X ⟶ F.left`:
"it shifts `F` towards the right and inserts `f` on the left". This `precomp` has
good definitional properties.
In the namespace `CategoryTheory.ComposableArrows`, we provide constructors
like `mk₁ f`, `mk₂ f g`, `mk₃ f g h` for `ComposableArrows C n` for small `n`.
TODO (@joelriou):
* redefine `Arrow C` as `ComposableArrow C 1`?
* construct some elements in `ComposableArrows m (Fin (n + 1))` for small `n`
the precomposition with which shall induce functors
`ComposableArrows C n ⥤ ComposableArrows C m` which correspond to simplicial operations
(specifically faces) with good definitional properties (this might be necessary for
up to `n = 7` in order to formalize spectral sequences following Verdier)
-/
/-!
New `simprocs` that run even in `dsimp` have caused breakages in this file.
(e.g. `dsimp` can now simplify `2 + 3` to `5`)
For now, we just turn off simprocs in this file.
We'll soon provide finer grained options here, e.g. to turn off simprocs only in `dsimp`, etc.
*However*, hopefully it is possible to refactor the material here so that no backwards compatibility
`set_option`s are required at all
-/
set_option simprocs false
namespace CategoryTheory
open Category
variable (C : Type*) [Category C]
/-- `ComposableArrows C n` is the type of functors `Fin (n + 1) ⥤ C`. -/
abbrev ComposableArrows (n : ℕ) := Fin (n + 1) ⥤ C
namespace ComposableArrows
variable {C} {n m : ℕ}
variable (F G : ComposableArrows C n)
/-- A wrapper for `omega` which prefaces it with some quick and useful attempts -/
macro "valid" : tactic =>
`(tactic| first | assumption | apply zero_le | apply le_rfl | transitivity <;> assumption | omega)
/-- The `i`th object (with `i : ℕ` such that `i ≤ n`) of `F : ComposableArrows C n`. -/
@[simp]
abbrev obj' (i : ℕ) (hi : i ≤ n := by valid) : C := F.obj ⟨i, by omega⟩
/-- The map `F.obj' i ⟶ F.obj' j` when `F : ComposableArrows C n`, and `i` and `j`
are natural numbers such that `i ≤ j ≤ n`. -/
@[simp]
abbrev map' (i j : ℕ) (hij : i ≤ j := by valid) (hjn : j ≤ n := by valid) :
F.obj ⟨i, by omega⟩ ⟶ F.obj ⟨j, by omega⟩ := F.map (homOfLE (by
simp only [Fin.mk_le_mk]
valid))
lemma map'_self (i : ℕ) (hi : i ≤ n := by valid) :
F.map' i i = 𝟙 _ := F.map_id _
lemma map'_comp (i j k : ℕ) (hij : i ≤ j := by valid)
(hjk : j ≤ k := by valid) (hk : k ≤ n := by valid) :
F.map' i k = F.map' i j ≫ F.map' j k :=
F.map_comp _ _
/-- The leftmost object of `F : ComposableArrows C n`. -/
abbrev left := obj' F 0
/-- The rightmost object of `F : ComposableArrows C n`. -/
abbrev right := obj' F n
/-- The canonical map `F.left ⟶ F.right` for `F : ComposableArrows C n`. -/
abbrev hom : F.left ⟶ F.right := map' F 0 n
variable {F G}
/-- The map `F.obj' i ⟶ G.obj' i` induced on `i`th objects by a morphism `F ⟶ G`
in `ComposableArrows C n` when `i` is a natural number such that `i ≤ n`. -/
@[simp]
abbrev app' (φ : F ⟶ G) (i : ℕ) (hi : i ≤ n := by valid) :
F.obj' i ⟶ G.obj' i := φ.app _
@[reassoc]
lemma naturality' (φ : F ⟶ G) (i j : ℕ) (hij : i ≤ j := by valid)
(hj : j ≤ n := by valid) :
F.map' i j ≫ app' φ j = app' φ i ≫ G.map' i j :=
φ.naturality _
/-- Constructor for `ComposableArrows C 0`. -/
@[simps!]
def mk₀ (X : C) : ComposableArrows C 0 := (Functor.const (Fin 1)).obj X
namespace Mk₁
variable (X₀ X₁ : C)
/-- The map which sends `0 : Fin 2` to `X₀` and `1` to `X₁`. -/
@[simp]
def obj : Fin 2 → C
| ⟨0, _⟩ => X₀
| ⟨1, _⟩ => X₁
variable {X₀ X₁}
variable (f : X₀ ⟶ X₁)
/-- The obvious map `obj X₀ X₁ i ⟶ obj X₀ X₁ j` whenever `i j : Fin 2` satisfy `i ≤ j`. -/
@[simp]
def map : ∀ (i j : Fin 2) (_ : i ≤ j), obj X₀ X₁ i ⟶ obj X₀ X₁ j
| ⟨0, _⟩, ⟨0, _⟩, _ => 𝟙 _
| ⟨0, _⟩, ⟨1, _⟩, _ => f
| ⟨1, _⟩, ⟨1, _⟩, _ => 𝟙 _
lemma map_id (i : Fin 2) : map f i i (by simp) = 𝟙 _ :=
match i with
| 0 => rfl
| 1 => rfl
lemma map_comp {i j k : Fin 2} (hij : i ≤ j) (hjk : j ≤ k) :
map f i k (hij.trans hjk) = map f i j hij ≫ map f j k hjk := by
obtain rfl | rfl : i = j ∨ j = k := by omega
· rw [map_id, id_comp]
· rw [map_id, comp_id]
end Mk₁
/-- Constructor for `ComposableArrows C 1`. -/
@[simps]
def mk₁ {X₀ X₁ : C} (f : X₀ ⟶ X₁) : ComposableArrows C 1 where
obj := Mk₁.obj X₀ X₁
map g := Mk₁.map f _ _ (leOfHom g)
map_id := Mk₁.map_id f
map_comp g g' := Mk₁.map_comp f (leOfHom g) (leOfHom g')
/-- Constructor for morphisms `F ⟶ G` in `ComposableArrows C n` which takes as inputs
a family of morphisms `F.obj i ⟶ G.obj i` and the naturality condition only for the
maps in `Fin (n + 1)` given by inequalities of the form `i ≤ i + 1`. -/
@[simps]
def homMk {F G : ComposableArrows C n} (app : ∀ i, F.obj i ⟶ G.obj i)
(w : ∀ (i : ℕ) (hi : i < n), F.map' i (i + 1) ≫ app _ = app _ ≫ G.map' i (i + 1)) :
F ⟶ G where
app := app
naturality := by
suffices ∀ (k i j : ℕ) (hj : i + k = j) (hj' : j ≤ n),
F.map' i j ≫ app _ = app _ ≫ G.map' i j by
rintro ⟨i, hi⟩ ⟨j, hj⟩ hij
have hij' := leOfHom hij
simp only [Fin.mk_le_mk] at hij'
obtain ⟨k, hk⟩ := Nat.le.dest hij'
exact this k i j hk (by valid)
intro k
induction' k with k hk
· intro i j hj hj'
simp only [add_zero] at hj
obtain rfl := hj
rw [F.map'_self i, G.map'_self i, id_comp, comp_id]
· intro i j hj hj'
rw [← add_assoc] at hj
subst hj
rw [F.map'_comp i (i + k) (i + k + 1), G.map'_comp i (i + k) (i + k + 1), assoc,
w (i + k) (by valid), reassoc_of% (hk i (i + k) rfl (by valid))]
/-- Constructor for isomorphisms `F ≅ G` in `ComposableArrows C n` which takes as inputs
a family of isomorphisms `F.obj i ≅ G.obj i` and the naturality condition only for the
maps in `Fin (n + 1)` given by inequalities of the form `i ≤ i + 1`. -/
@[simps]
def isoMk {F G : ComposableArrows C n} (app : ∀ i, F.obj i ≅ G.obj i)
(w : ∀ (i : ℕ) (hi : i < n),
F.map' i (i + 1) ≫ (app _).hom = (app _).hom ≫ G.map' i (i + 1)) :
F ≅ G where
hom := homMk (fun i => (app i).hom) w
inv := homMk (fun i => (app i).inv) (fun i hi => by
dsimp only
rw [← cancel_epi ((app _).hom), ← reassoc_of% (w i hi), Iso.hom_inv_id, comp_id,
Iso.hom_inv_id_assoc])
lemma ext {F G : ComposableArrows C n} (h : ∀ i, F.obj i = G.obj i)
(w : ∀ (i : ℕ) (hi : i < n), F.map' i (i + 1) =
eqToHom (h _) ≫ G.map' i (i + 1) ≫ eqToHom (h _).symm) : F = G :=
Functor.ext_of_iso
(isoMk (fun i => eqToIso (h i)) (fun i hi => by simp [w i hi])) h (fun _ => rfl)
/-- Constructor for morphisms in `ComposableArrows C 0`. -/
@[simps!]
def homMk₀ {F G : ComposableArrows C 0} (f : F.obj' 0 ⟶ G.obj' 0) : F ⟶ G :=
homMk (fun i => match i with
| ⟨0, _⟩ => f) (fun i hi => by simp at hi)
@[ext]
lemma hom_ext₀ {F G : ComposableArrows C 0} {φ φ' : F ⟶ G}
(h : app' φ 0 = app' φ' 0) :
φ = φ' := by
ext i
fin_cases i
exact h
/-- Constructor for isomorphisms in `ComposableArrows C 0`. -/
@[simps!]
def isoMk₀ {F G : ComposableArrows C 0} (e : F.obj' 0 ≅ G.obj' 0) : F ≅ G where
hom := homMk₀ e.hom
inv := homMk₀ e.inv
lemma ext₀ {F G : ComposableArrows C 0} (h : F.obj' 0 = G.obj 0) : F = G :=
ext (fun i => match i with
| ⟨0, _⟩ => h) (fun i hi => by simp at hi)
lemma mk₀_surjective (F : ComposableArrows C 0) : ∃ (X : C), F = mk₀ X :=
⟨F.obj' 0, ext₀ rfl⟩
/-- Constructor for morphisms in `ComposableArrows C 1`. -/
@[simps!]
def homMk₁ {F G : ComposableArrows C 1}
(left : F.obj' 0 ⟶ G.obj' 0) (right : F.obj' 1 ⟶ G.obj' 1)
(w : F.map' 0 1 ≫ right = left ≫ G.map' 0 1 := by aesop_cat) :
F ⟶ G :=
homMk (fun i => match i with
| ⟨0, _⟩ => left
| ⟨1, _⟩ => right) (by
intro i hi
obtain rfl : i = 0 := by simpa using hi
exact w)
@[ext]
lemma hom_ext₁ {F G : ComposableArrows C 1} {φ φ' : F ⟶ G}
(h₀ : app' φ 0 = app' φ' 0) (h₁ : app' φ 1 = app' φ' 1) :
φ = φ' := by
ext i
match i with
| 0 => exact h₀
| 1 => exact h₁
/-- Constructor for isomorphisms in `ComposableArrows C 1`. -/
@[simps!]
def isoMk₁ {F G : ComposableArrows C 1}
(left : F.obj' 0 ≅ G.obj' 0) (right : F.obj' 1 ≅ G.obj' 1)
(w : F.map' 0 1 ≫ right.hom = left.hom ≫ G.map' 0 1 := by aesop_cat) :
F ≅ G where
hom := homMk₁ left.hom right.hom w
inv := homMk₁ left.inv right.inv (by
rw [← cancel_mono right.hom, assoc, assoc, w, right.inv_hom_id, left.inv_hom_id_assoc]
apply comp_id)
lemma map'_eq_hom₁ (F : ComposableArrows C 1) : F.map' 0 1 = F.hom := rfl
lemma ext₁ {F G : ComposableArrows C 1}
(left : F.left = G.left) (right : F.right = G.right)
(w : F.hom = eqToHom left ≫ G.hom ≫ eqToHom right.symm) : F = G :=
Functor.ext_of_iso (isoMk₁ (eqToIso left) (eqToIso right) (by simp [map'_eq_hom₁, w]))
(fun i => by fin_cases i <;> assumption)
(fun i => by fin_cases i <;> rfl)
lemma mk₁_surjective (X : ComposableArrows C 1) : ∃ (X₀ X₁ : C) (f : X₀ ⟶ X₁), X = mk₁ f :=
⟨_, _, X.map' 0 1, ext₁ rfl rfl (by simp)⟩
variable (F)
namespace Precomp
variable (X : C)
/-- The map `Fin (n + 1 + 1) → C` which "shifts" `F.obj'` to the right and inserts `X` in
the zeroth position. -/
def obj : Fin (n + 1 + 1) → C
| ⟨0, _⟩ => X
| ⟨i + 1, hi⟩ => F.obj' i
@[simp]
lemma obj_zero : obj F X 0 = X := rfl
@[simp]
lemma obj_one : obj F X 1 = F.obj' 0 := rfl
@[simp]
lemma obj_succ (i : ℕ) (hi : i + 1 < n + 1 + 1) : obj F X ⟨i + 1, hi⟩ = F.obj' i := rfl
variable {X} (f : X ⟶ F.left)
/-- Auxiliary definition for the action on maps of the functor `F.precomp f`.
It sends `0 ≤ 1` to `f` and `i + 1 ≤ j + 1` to `F.map' i j`. -/
def map : ∀ (i j : Fin (n + 1 + 1)) (_ : i ≤ j), obj F X i ⟶ obj F X j
| ⟨0, _⟩, ⟨0, _⟩, _ => 𝟙 X
| ⟨0, _⟩, ⟨1, _⟩, _ => f
| ⟨0, _⟩, ⟨j + 2, hj⟩, _ => f ≫ F.map' 0 (j + 1)
| ⟨i + 1, hi⟩, ⟨j + 1, hj⟩, hij => F.map' i j (by simpa using hij)
@[simp]
lemma map_zero_zero : map F f 0 0 (by simp) = 𝟙 X := rfl
@[simp]
lemma map_one_one : map F f 1 1 (by simp) = F.map (𝟙 _) := rfl
@[simp]
lemma map_zero_one : map F f 0 1 (by simp) = f := rfl
@[simp]
lemma map_zero_one' : map F f 0 ⟨0 + 1, by simp⟩ (by simp) = f := rfl
@[simp]
lemma map_zero_succ_succ (j : ℕ) (hj : j + 2 < n + 1 + 1) :
map F f 0 ⟨j + 2, hj⟩ (by simp) = f ≫ F.map' 0 (j+1) := rfl
@[simp]
lemma map_succ_succ (i j : ℕ) (hi : i + 1 < n + 1 + 1) (hj : j + 1 < n + 1 + 1)
(hij : i + 1 ≤ j + 1) :
map F f ⟨i + 1, hi⟩ ⟨j + 1, hj⟩ hij = F.map' i j := rfl
@[simp]
lemma map_one_succ (j : ℕ) (hj : j + 1 < n + 1 + 1) :
map F f 1 ⟨j + 1, hj⟩ (by simp [Fin.le_def]) = F.map' 0 j := rfl
lemma map_id (i : Fin (n + 1 + 1)) : map F f i i (by simp) = 𝟙 _ := by
obtain ⟨_|_, hi⟩ := i <;> simp
lemma map_comp {i j k : Fin (n + 1 + 1)} (hij : i ≤ j) (hjk : j ≤ k) :
map F f i k (hij.trans hjk) = map F f i j hij ≫ map F f j k hjk := by
obtain ⟨i, hi⟩ := i
obtain ⟨j, hj⟩ := j
obtain ⟨k, hk⟩ := k
cases i
· obtain _ | _ | j := j
· dsimp
| rw [id_comp]
· obtain _ | _ | k := k
· simp [Nat.succ.injEq] at hjk
· simp
· rfl
· obtain _ | _ | k := k
· simp [Fin.ext_iff] at hjk
· simp [Fin.le_def] at hjk
omega
· dsimp
rw [assoc, ← F.map_comp, homOfLE_comp]
· obtain _ | j := j
· simp [Fin.ext_iff] at hij
· obtain _ | k := k
· simp [Fin.ext_iff] at hjk
· dsimp
rw [← F.map_comp, homOfLE_comp]
end Precomp
/-- "Precomposition" of `F : ComposableArrows C n` by a morphism `f : X ⟶ F.left`. -/
@[simps]
def precomp {X : C} (f : X ⟶ F.left) : ComposableArrows C (n + 1) where
obj := Precomp.obj F X
map g := Precomp.map F f _ _ (leOfHom g)
| Mathlib/CategoryTheory/ComposableArrows.lean | 349 | 373 |
/-
Copyright (c) 2023 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import Mathlib.Computability.AkraBazzi.GrowsPolynomially
import Mathlib.Analysis.Calculus.Deriv.Inv
import Mathlib.Analysis.SpecialFunctions.Pow.Deriv
/-!
# Divide-and-conquer recurrences and the Akra-Bazzi theorem
A divide-and-conquer recurrence is a function `T : ℕ → ℝ` that satisfies a recurrence relation of
the form `T(n) = ∑_{i=0}^{k-1} a_i T(r_i(n)) + g(n)` for large enough `n`, where `r_i(n)` is some
function where `‖r_i(n) - b_i n‖ ∈ o(n / (log n)^2)` for every `i`, the `a_i`'s are some positive
coefficients, and the `b_i`'s are reals `∈ (0,1)`. (Note that this can be improved to
`O(n / (log n)^(1+ε))`, this is left as future work.) These recurrences arise mainly in the
analysis of divide-and-conquer algorithms such as mergesort or Strassen's algorithm for matrix
multiplication. This class of algorithms works by dividing an instance of the problem of size `n`,
into `k` smaller instances, where the `i`'th instance is of size roughly `b_i n`, and calling itself
recursively on those smaller instances. `T(n)` then represents the running time of the algorithm,
and `g(n)` represents the running time required to actually divide up the instance and process the
answers that come out of the recursive calls. Since virtually all such algorithms produce instances
that are only approximately of size `b_i n` (they have to round up or down at the very least), we
allow the instance sizes to be given by some function `r_i(n)` that approximates `b_i n`.
The Akra-Bazzi theorem gives the asymptotic order of such a recurrence: it states that
`T(n) ∈ Θ(n^p (1 + ∑_{u=0}^{n-1} g(n) / u^{p+1}))`,
where `p` is the unique real number such that `∑ a_i b_i^p = 1`.
## Main definitions and results
* `AkraBazziRecurrence T g a b r`: the predicate stating that `T : ℕ → ℝ` satisfies an Akra-Bazzi
recurrence with parameters `g`, `a`, `b` and `r` as above.
* `GrowsPolynomially`: The growth condition that `g` must satisfy for the theorem to apply.
It roughly states that
`c₁ g(n) ≤ g(u) ≤ c₂ g(n)`, for u between b*n and n for any constant `b ∈ (0,1)`.
* `sumTransform`: The transformation which turns a function `g` into
`n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p+1)`.
* `asympBound`: The asymptotic bound satisfied by an Akra-Bazzi recurrence, namely
`n^p (1 + ∑ g(u) / u^(p+1))`
* `isTheta_asympBound`: The main result stating that
`T(n) ∈ Θ(n^p (1 + ∑_{u=0}^{n-1} g(n) / u^{p+1}))`
## Implementation
Note that the original version of the theorem has an integral rather than a sum in the above
expression, and first considers the `T : ℝ → ℝ` case before moving on to `ℕ → ℝ`. We prove the
above version with a sum, as it is simpler and more relevant for algorithms.
## TODO
* Specialize this theorem to the very common case where the recurrence is of the form
`T(n) = ℓT(r_i(n)) + g(n)`
where `g(n) ∈ Θ(n^t)` for some `t`. (This is often called the "master theorem" in the literature.)
* Add the original version of the theorem with an integral instead of a sum.
## References
* Mohamad Akra and Louay Bazzi, On the solution of linear recurrence equations
* Tom Leighton, Notes on better master theorems for divide-and-conquer recurrences
* Manuel Eberl, Asymptotic reasoning in a proof assistant
-/
open Finset Real Filter Asymptotics
open scoped Topology
/-!
#### Definition of Akra-Bazzi recurrences
This section defines the predicate `AkraBazziRecurrence T g a b r` which states that `T`
satisfies the recurrence
`T(n) = ∑_{i=0}^{k-1} a_i T(r_i(n)) + g(n)`
with appropriate conditions on the various parameters.
-/
/-- An Akra-Bazzi recurrence is a function that satisfies the recurrence
`T n = (∑ i, a i * T (r i n)) + g n`. -/
structure AkraBazziRecurrence {α : Type*} [Fintype α] [Nonempty α]
(T : ℕ → ℝ) (g : ℝ → ℝ) (a : α → ℝ) (b : α → ℝ) (r : α → ℕ → ℕ) where
/-- Point below which the recurrence is in the base case -/
n₀ : ℕ
/-- `n₀` is always `> 0` -/
n₀_gt_zero : 0 < n₀
/-- The `a`'s are nonzero -/
a_pos : ∀ i, 0 < a i
/-- The `b`'s are nonzero -/
b_pos : ∀ i, 0 < b i
/-- The b's are less than 1 -/
b_lt_one : ∀ i, b i < 1
/-- `g` is nonnegative -/
g_nonneg : ∀ x ≥ 0, 0 ≤ g x
/-- `g` grows polynomially -/
g_grows_poly : AkraBazziRecurrence.GrowsPolynomially g
/-- The actual recurrence -/
h_rec (n : ℕ) (hn₀ : n₀ ≤ n) : T n = (∑ i, a i * T (r i n)) + g n
/-- Base case: `T(n) > 0` whenever `n < n₀` -/
T_gt_zero' (n : ℕ) (hn : n < n₀) : 0 < T n
/-- The `r`'s always reduce `n` -/
r_lt_n : ∀ i n, n₀ ≤ n → r i n < n
/-- The `r`'s approximate the `b`'s -/
dist_r_b : ∀ i, (fun n => (r i n : ℝ) - b i * n) =o[atTop] fun n => n / (log n) ^ 2
namespace AkraBazziRecurrence
section min_max
variable {α : Type*} [Finite α] [Nonempty α]
/-- Smallest `b i` -/
noncomputable def min_bi (b : α → ℝ) : α :=
Classical.choose <| Finite.exists_min b
/-- Largest `b i` -/
noncomputable def max_bi (b : α → ℝ) : α :=
Classical.choose <| Finite.exists_max b
@[aesop safe apply]
lemma min_bi_le {b : α → ℝ} (i : α) : b (min_bi b) ≤ b i :=
Classical.choose_spec (Finite.exists_min b) i
@[aesop safe apply]
lemma max_bi_le {b : α → ℝ} (i : α) : b i ≤ b (max_bi b) :=
Classical.choose_spec (Finite.exists_max b) i
end min_max
lemma isLittleO_self_div_log_id :
(fun (n : ℕ) => n / log n ^ 2) =o[atTop] (fun (n : ℕ) => (n : ℝ)) := by
calc (fun (n : ℕ) => (n : ℝ) / log n ^ 2) = fun (n : ℕ) => (n : ℝ) * ((log n) ^ 2)⁻¹ := by
simp_rw [div_eq_mul_inv]
_ =o[atTop] fun (n : ℕ) => (n : ℝ) * 1⁻¹ := by
refine IsBigO.mul_isLittleO (isBigO_refl _ _) ?_
refine IsLittleO.inv_rev ?main ?zero
case zero => simp
case main => calc
_ = (fun (_ : ℕ) => ((1 : ℝ) ^ 2)) := by simp
_ =o[atTop] (fun (n : ℕ) => (log n)^2) :=
IsLittleO.pow (IsLittleO.natCast_atTop
<| isLittleO_const_log_atTop) (by norm_num)
_ = (fun (n : ℕ) => (n : ℝ)) := by ext; simp
variable {α : Type*} [Fintype α] {T : ℕ → ℝ} {g : ℝ → ℝ} {a b : α → ℝ} {r : α → ℕ → ℕ}
variable [Nonempty α] (R : AkraBazziRecurrence T g a b r)
section
include R
lemma dist_r_b' : ∀ᶠ n in atTop, ∀ i, ‖(r i n : ℝ) - b i * n‖ ≤ n / log n ^ 2 := by
rw [Filter.eventually_all]
intro i
simpa using IsLittleO.eventuallyLE (R.dist_r_b i)
lemma eventually_b_le_r : ∀ᶠ (n : ℕ) in atTop, ∀ i, (b i : ℝ) * n - (n / log n ^ 2) ≤ r i n := by
filter_upwards [R.dist_r_b'] with n hn
intro i
have h₁ : 0 ≤ b i := le_of_lt <| R.b_pos _
rw [sub_le_iff_le_add, add_comm, ← sub_le_iff_le_add]
calc (b i : ℝ) * n - r i n = ‖b i * n‖ - ‖(r i n : ℝ)‖ := by
simp only [norm_mul, RCLike.norm_natCast, sub_left_inj,
Nat.cast_eq_zero, Real.norm_of_nonneg h₁]
_ ≤ ‖(b i * n : ℝ) - r i n‖ := norm_sub_norm_le _ _
_ = ‖(r i n : ℝ) - b i * n‖ := norm_sub_rev _ _
_ ≤ n / log n ^ 2 := hn i
lemma eventually_r_le_b : ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n ≤ (b i : ℝ) * n + (n / log n ^ 2) := by
filter_upwards [R.dist_r_b'] with n hn
intro i
calc r i n = b i * n + (r i n - b i * n) := by ring
_ ≤ b i * n + ‖r i n - b i * n‖ := by gcongr; exact Real.le_norm_self _
_ ≤ b i * n + n / log n ^ 2 := by gcongr; exact hn i
lemma eventually_r_lt_n : ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n < n := by
filter_upwards [eventually_ge_atTop R.n₀] with n hn
exact fun i => R.r_lt_n i n hn
lemma eventually_bi_mul_le_r : ∀ᶠ (n : ℕ) in atTop, ∀ i, (b (min_bi b) / 2) * n ≤ r i n := by
have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b)
have hlo := isLittleO_self_div_log_id
rw [Asymptotics.isLittleO_iff] at hlo
have hlo' := hlo (by positivity : 0 < b (min_bi b) / 2)
filter_upwards [hlo', R.eventually_b_le_r] with n hn hn'
intro i
simp only [Real.norm_of_nonneg (by positivity : 0 ≤ (n : ℝ))] at hn
calc b (min_bi b) / 2 * n = b (min_bi b) * n - b (min_bi b) / 2 * n := by ring
_ ≤ b (min_bi b) * n - ‖n / log n ^ 2‖ := by gcongr
_ ≤ b i * n - ‖n / log n ^ 2‖ := by gcongr; aesop
_ = b i * n - n / log n ^ 2 := by
congr
exact Real.norm_of_nonneg <| by positivity
_ ≤ r i n := hn' i
lemma bi_min_div_two_lt_one : b (min_bi b) / 2 < 1 := by
have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b)
calc b (min_bi b) / 2 < b (min_bi b) := by aesop (add safe apply div_two_lt_of_pos)
_ < 1 := R.b_lt_one _
lemma bi_min_div_two_pos : 0 < b (min_bi b) / 2 := div_pos (R.b_pos _) (by norm_num)
lemma exists_eventually_const_mul_le_r :
∃ c ∈ Set.Ioo (0 : ℝ) 1, ∀ᶠ (n : ℕ) in atTop, ∀ i, c * n ≤ r i n := by
have gt_zero : 0 < b (min_bi b) := R.b_pos (min_bi b)
exact ⟨b (min_bi b) / 2, ⟨⟨by positivity, R.bi_min_div_two_lt_one⟩, R.eventually_bi_mul_le_r⟩⟩
lemma eventually_r_ge (C : ℝ) : ∀ᶠ (n : ℕ) in atTop, ∀ i, C ≤ r i n := by
obtain ⟨c, hc_mem, hc⟩ := R.exists_eventually_const_mul_le_r
filter_upwards [eventually_ge_atTop ⌈C / c⌉₊, hc] with n hn₁ hn₂
have h₁ := hc_mem.1
intro i
calc C = c * (C / c) := by
rw [← mul_div_assoc]
exact (mul_div_cancel_left₀ _ (by positivity)).symm
_ ≤ c * ⌈C / c⌉₊ := by gcongr; simp [Nat.le_ceil]
_ ≤ c * n := by gcongr
_ ≤ r i n := hn₂ i
lemma tendsto_atTop_r (i : α) : Tendsto (r i) atTop atTop := by
rw [tendsto_atTop]
intro b
have := R.eventually_r_ge b
rw [Filter.eventually_all] at this
exact_mod_cast this i
lemma tendsto_atTop_r_real (i : α) : Tendsto (fun n => (r i n : ℝ)) atTop atTop :=
Tendsto.comp tendsto_natCast_atTop_atTop (R.tendsto_atTop_r i)
lemma exists_eventually_r_le_const_mul :
∃ c ∈ Set.Ioo (0 : ℝ) 1, ∀ᶠ (n : ℕ) in atTop, ∀ i, r i n ≤ c * n := by
let c := b (max_bi b) + (1 - b (max_bi b)) / 2
have h_max_bi_pos : 0 < b (max_bi b) := R.b_pos _
have h_max_bi_lt_one : 0 < 1 - b (max_bi b) := by
have : b (max_bi b) < 1 := R.b_lt_one _
linarith
have hc_pos : 0 < c := by positivity
have h₁ : 0 < (1 - b (max_bi b)) / 2 := by positivity
have hc_lt_one : c < 1 :=
calc b (max_bi b) + (1 - b (max_bi b)) / 2 = b (max_bi b) * (1 / 2) + 1 / 2 := by ring
_ < 1 * (1 / 2) + 1 / 2 := by
gcongr
exact R.b_lt_one _
_ = 1 := by norm_num
refine ⟨c, ⟨hc_pos, hc_lt_one⟩, ?_⟩
have hlo := isLittleO_self_div_log_id
rw [Asymptotics.isLittleO_iff] at hlo
have hlo' := hlo h₁
filter_upwards [hlo', R.eventually_r_le_b] with n hn hn'
intro i
rw [Real.norm_of_nonneg (by positivity)] at hn
simp only [Real.norm_of_nonneg (by positivity : 0 ≤ (n : ℝ))] at hn
calc r i n ≤ b i * n + n / log n ^ 2 := by exact hn' i
_ ≤ b i * n + (1 - b (max_bi b)) / 2 * n := by gcongr
_ = (b i + (1 - b (max_bi b)) / 2) * n := by ring
_ ≤ (b (max_bi b) + (1 - b (max_bi b)) / 2) * n := by gcongr; exact max_bi_le _
lemma eventually_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < r i n := by
rw [Filter.eventually_all]
exact fun i => (R.tendsto_atTop_r i).eventually_gt_atTop 0
lemma eventually_log_b_mul_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < log (b i * n) := by
rw [Filter.eventually_all]
intro i
have h : Tendsto (fun (n : ℕ) => log (b i * n)) atTop atTop :=
Tendsto.comp tendsto_log_atTop
<| Tendsto.const_mul_atTop (b_pos R i) tendsto_natCast_atTop_atTop
exact h.eventually_gt_atTop 0
@[aesop safe apply] lemma T_pos (n : ℕ) : 0 < T n := by
induction n using Nat.strongRecOn with
| ind n h_ind =>
cases lt_or_le n R.n₀ with
| inl hn => exact R.T_gt_zero' n hn -- n < R.n₀
| inr hn => -- R.n₀ ≤ n
rw [R.h_rec n hn]
have := R.g_nonneg
refine add_pos_of_pos_of_nonneg (Finset.sum_pos ?sum_elems univ_nonempty) (by aesop)
exact fun i _ => mul_pos (R.a_pos i) <| h_ind _ (R.r_lt_n i _ hn)
@[aesop safe apply]
lemma T_nonneg (n : ℕ) : 0 ≤ T n := le_of_lt <| R.T_pos n
end
/-!
#### Smoothing function
We define `ε` as the "smoothing function" `fun n => 1 / log n`, which will be used in the form of a
factor of `1 ± ε n` needed to make the induction step go through.
This is its own definition to make it easier to switch to a different smoothing function.
For example, choosing `1 / log n ^ δ` for a suitable choice of `δ` leads to a slightly tighter
theorem at the price of a more complicated proof.
This part of the file then proves several properties of this function that will be needed later in
the proof.
-/
/-- The "smoothing function" is defined as `1 / log n`. This is defined as an `ℝ → ℝ` function
as opposed to `ℕ → ℝ` since this is more convenient for the proof, where we need to e.g. take
derivatives. -/
noncomputable def smoothingFn (n : ℝ) : ℝ := 1 / log n
local notation "ε" => smoothingFn
lemma one_add_smoothingFn_le_two {x : ℝ} (hx : exp 1 ≤ x) : 1 + ε x ≤ 2 := by
simp only [smoothingFn, ← one_add_one_eq_two]
gcongr
have : 1 < x := by
calc 1 = exp 0 := by simp
_ < exp 1 := by simp
_ ≤ x := hx
rw [div_le_one (log_pos this)]
calc 1 = log (exp 1) := by simp
_ ≤ log x := log_le_log (exp_pos _) hx
lemma isLittleO_smoothingFn_one : ε =o[atTop] (fun _ => (1 : ℝ)) := by
unfold smoothingFn
refine isLittleO_of_tendsto (fun _ h => False.elim <| one_ne_zero h) ?_
simp only [one_div, div_one]
exact Tendsto.inv_tendsto_atTop Real.tendsto_log_atTop
lemma isEquivalent_one_add_smoothingFn_one : (fun x => 1 + ε x) ~[atTop] (fun _ => (1 : ℝ)) :=
IsEquivalent.add_isLittleO IsEquivalent.refl isLittleO_smoothingFn_one
lemma isEquivalent_one_sub_smoothingFn_one : (fun x => 1 - ε x) ~[atTop] (fun _ => (1 : ℝ)) :=
IsEquivalent.sub_isLittleO IsEquivalent.refl isLittleO_smoothingFn_one
lemma growsPolynomially_one_sub_smoothingFn : GrowsPolynomially fun x => 1 - ε x :=
GrowsPolynomially.of_isEquivalent_const isEquivalent_one_sub_smoothingFn_one
lemma growsPolynomially_one_add_smoothingFn : GrowsPolynomially fun x => 1 + ε x :=
GrowsPolynomially.of_isEquivalent_const isEquivalent_one_add_smoothingFn_one
lemma eventually_one_sub_smoothingFn_gt_const_real (c : ℝ) (hc : c < 1) :
∀ᶠ (x : ℝ) in atTop, c < 1 - ε x := by
have h₁ : Tendsto (fun x => 1 - ε x) atTop (𝓝 1) := by
rw [← isEquivalent_const_iff_tendsto one_ne_zero]
exact isEquivalent_one_sub_smoothingFn_one
rw [tendsto_order] at h₁
exact h₁.1 c hc
lemma eventually_one_sub_smoothingFn_gt_const (c : ℝ) (hc : c < 1) :
∀ᶠ (n : ℕ) in atTop, c < 1 - ε n :=
Eventually.natCast_atTop (p := fun n => c < 1 - ε n)
<| eventually_one_sub_smoothingFn_gt_const_real c hc
lemma eventually_one_sub_smoothingFn_pos_real : ∀ᶠ (x : ℝ) in atTop, 0 < 1 - ε x :=
eventually_one_sub_smoothingFn_gt_const_real 0 zero_lt_one
lemma eventually_one_sub_smoothingFn_pos : ∀ᶠ (n : ℕ) in atTop, 0 < 1 - ε n :=
(eventually_one_sub_smoothingFn_pos_real).natCast_atTop
lemma eventually_one_sub_smoothingFn_nonneg : ∀ᶠ (n : ℕ) in atTop, 0 ≤ 1 - ε n := by
filter_upwards [eventually_one_sub_smoothingFn_pos] with n hn; exact le_of_lt hn
include R in
lemma eventually_one_sub_smoothingFn_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < 1 - ε (r i n) := by
rw [Filter.eventually_all]
exact fun i => (R.tendsto_atTop_r_real i).eventually eventually_one_sub_smoothingFn_pos_real
@[aesop safe apply]
lemma differentiableAt_smoothingFn {x : ℝ} (hx : 1 < x) : DifferentiableAt ℝ ε x := by
have : log x ≠ 0 := Real.log_ne_zero_of_pos_of_ne_one (by positivity) (ne_of_gt hx)
show DifferentiableAt ℝ (fun z => 1 / log z) x
simp_rw [one_div]
exact DifferentiableAt.inv (differentiableAt_log (by positivity)) this
@[aesop safe apply]
lemma differentiableAt_one_sub_smoothingFn {x : ℝ} (hx : 1 < x) :
DifferentiableAt ℝ (fun z => 1 - ε z) x :=
DifferentiableAt.sub (differentiableAt_const _) <| differentiableAt_smoothingFn hx
lemma differentiableOn_one_sub_smoothingFn : DifferentiableOn ℝ (fun z => 1 - ε z) (Set.Ioi 1) :=
fun _ hx => (differentiableAt_one_sub_smoothingFn hx).differentiableWithinAt
@[aesop safe apply]
lemma differentiableAt_one_add_smoothingFn {x : ℝ} (hx : 1 < x) :
DifferentiableAt ℝ (fun z => 1 + ε z) x :=
DifferentiableAt.add (differentiableAt_const _) <| differentiableAt_smoothingFn hx
lemma differentiableOn_one_add_smoothingFn : DifferentiableOn ℝ (fun z => 1 + ε z) (Set.Ioi 1) :=
fun _ hx => (differentiableAt_one_add_smoothingFn hx).differentiableWithinAt
lemma deriv_smoothingFn {x : ℝ} (hx : 1 < x) : deriv ε x = -x⁻¹ / (log x ^ 2) := by
have : log x ≠ 0 := Real.log_ne_zero_of_pos_of_ne_one (by positivity) (ne_of_gt hx)
show deriv (fun z => 1 / log z) x = -x⁻¹ / (log x ^ 2)
rw [deriv_div] <;> aesop
lemma isLittleO_deriv_smoothingFn : deriv ε =o[atTop] fun x => x⁻¹ := calc
deriv ε =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 1] with x hx
rw [deriv_smoothingFn hx]
_ = fun x => (-x * log x ^ 2)⁻¹ := by
simp_rw [neg_div, div_eq_mul_inv, ← mul_inv, neg_inv, neg_mul]
_ =o[atTop] fun x => (x * 1)⁻¹ := by
refine IsLittleO.inv_rev ?_ ?_
· refine IsBigO.mul_isLittleO
(by rw [isBigO_neg_right]; aesop (add safe isBigO_refl)) ?_
rw [isLittleO_one_left_iff]
exact Tendsto.comp tendsto_norm_atTop_atTop
<| Tendsto.comp (tendsto_pow_atTop (by norm_num)) tendsto_log_atTop
· exact Filter.Eventually.of_forall (fun x hx => by rw [mul_one] at hx; simp [hx])
_ = fun x => x⁻¹ := by simp
lemma eventually_deriv_one_sub_smoothingFn :
deriv (fun x => 1 - ε x) =ᶠ[atTop] fun x => x⁻¹ / (log x ^ 2) := calc
deriv (fun x => 1 - ε x) =ᶠ[atTop] -(deriv ε) := by
filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_sub] <;> aesop
_ =ᶠ[atTop] fun x => x⁻¹ / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 1] with x hx
simp [deriv_smoothingFn hx, neg_div]
lemma eventually_deriv_one_add_smoothingFn :
deriv (fun x => 1 + ε x) =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) := calc
deriv (fun x => 1 + ε x) =ᶠ[atTop] deriv ε := by
filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_add] <;> aesop
_ =ᶠ[atTop] fun x => -x⁻¹ / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 1] with x hx
simp [deriv_smoothingFn hx]
lemma isLittleO_deriv_one_sub_smoothingFn :
deriv (fun x => 1 - ε x) =o[atTop] fun (x : ℝ) => x⁻¹ := calc
deriv (fun x => 1 - ε x) =ᶠ[atTop] fun z => -(deriv ε z) := by
filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_sub] <;> aesop
_ =o[atTop] fun x => x⁻¹ := by rw [isLittleO_neg_left]; exact isLittleO_deriv_smoothingFn
lemma isLittleO_deriv_one_add_smoothingFn :
deriv (fun x => 1 + ε x) =o[atTop] fun (x : ℝ) => x⁻¹ := calc
deriv (fun x => 1 + ε x) =ᶠ[atTop] fun z => deriv ε z := by
filter_upwards [eventually_gt_atTop 1] with x hx; rw [deriv_add] <;> aesop
_ =o[atTop] fun x => x⁻¹ := isLittleO_deriv_smoothingFn
lemma eventually_one_add_smoothingFn_pos : ∀ᶠ (n : ℕ) in atTop, 0 < 1 + ε n := by
have h₁ := isLittleO_smoothingFn_one
rw [isLittleO_iff] at h₁
refine Eventually.natCast_atTop (p := fun n => 0 < 1 + ε n) ?_
filter_upwards [h₁ (by norm_num : (0 : ℝ) < 1/2), eventually_gt_atTop 1] with x _ hx'
have : 0 < log x := Real.log_pos hx'
show 0 < 1 + 1 / log x
positivity
include R in
lemma eventually_one_add_smoothingFn_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < 1 + ε (r i n) := by
rw [Filter.eventually_all]
exact fun i => (R.tendsto_atTop_r i).eventually (f := r i) eventually_one_add_smoothingFn_pos
lemma eventually_one_add_smoothingFn_nonneg : ∀ᶠ (n : ℕ) in atTop, 0 ≤ 1 + ε n := by
filter_upwards [eventually_one_add_smoothingFn_pos] with n hn; exact le_of_lt hn
lemma strictAntiOn_smoothingFn : StrictAntiOn ε (Set.Ioi 1) := by
show StrictAntiOn (fun x => 1 / log x) (Set.Ioi 1)
simp_rw [one_div]
refine StrictAntiOn.comp_strictMonoOn inv_strictAntiOn ?log fun _ hx => log_pos hx
refine StrictMonoOn.mono strictMonoOn_log (fun x hx => ?_)
exact Set.Ioi_subset_Ioi zero_le_one hx
lemma strictMonoOn_one_sub_smoothingFn :
StrictMonoOn (fun (x : ℝ) => (1 : ℝ) - ε x) (Set.Ioi 1) := by
simp_rw [sub_eq_add_neg]
exact StrictMonoOn.const_add (StrictAntiOn.neg <| strictAntiOn_smoothingFn) 1
lemma strictAntiOn_one_add_smoothingFn : StrictAntiOn (fun (x : ℝ) => (1 : ℝ) + ε x) (Set.Ioi 1) :=
StrictAntiOn.const_add strictAntiOn_smoothingFn 1
section
include R
lemma isEquivalent_smoothingFn_sub_self (i : α) :
(fun (n : ℕ) => ε (b i * n) - ε n) ~[atTop] fun n => -log (b i) / (log n)^2 := by
calc (fun (n : ℕ) => 1 / log (b i * n) - 1 / log n)
=ᶠ[atTop] fun (n : ℕ) => (log n - log (b i * n)) / (log (b i * n) * log n) := by
filter_upwards [eventually_gt_atTop 1, R.eventually_log_b_mul_pos] with n hn hn'
have h_log_pos : 0 < log n := Real.log_pos <| by aesop
simp only [one_div]
rw [inv_sub_inv (by have := hn' i; positivity) (by aesop)]
_ =ᶠ[atTop] (fun (n : ℕ) ↦ (log n - log (b i) - log n) / ((log (b i) + log n) * log n)) := by
filter_upwards [eventually_ne_atTop 0] with n hn
have : 0 < b i := R.b_pos i
rw [log_mul (by positivity) (by aesop), sub_add_eq_sub_sub]
_ = (fun (n : ℕ) => -log (b i) / ((log (b i) + log n) * log n)) := by ext; congr; ring
_ ~[atTop] (fun (n : ℕ) => -log (b i) / (log n * log n)) := by
refine IsEquivalent.div (IsEquivalent.refl) <| IsEquivalent.mul ?_ (IsEquivalent.refl)
have : (fun (n : ℕ) => log (b i) + log n) = fun (n : ℕ) => log n + log (b i) := by
ext; simp [add_comm]
rw [this]
exact IsEquivalent.add_isLittleO IsEquivalent.refl
<| IsLittleO.natCast_atTop (f := fun (_ : ℝ) => log (b i))
isLittleO_const_log_atTop
_ = (fun (n : ℕ) => -log (b i) / (log n)^2) := by ext; congr 1; rw [← pow_two]
lemma isTheta_smoothingFn_sub_self (i : α) :
(fun (n : ℕ) => ε (b i * n) - ε n) =Θ[atTop] fun n => 1 / (log n)^2 := by
calc (fun (n : ℕ) => ε (b i * n) - ε n) =Θ[atTop] fun n => (-log (b i)) / (log n)^2 := by
exact (R.isEquivalent_smoothingFn_sub_self i).isTheta
_ = fun (n : ℕ) => (-log (b i)) * 1 / (log n)^2 := by simp only [mul_one]
_ = fun (n : ℕ) => -log (b i) * (1 / (log n)^2) := by simp_rw [← mul_div_assoc]
_ =Θ[atTop] fun (n : ℕ) => 1 / (log n)^2 := by
have : -log (b i) ≠ 0 := by
rw [neg_ne_zero]
exact Real.log_ne_zero_of_pos_of_ne_one
(R.b_pos i) (ne_of_lt <| R.b_lt_one i)
rw [← isTheta_const_mul_right this]
/-!
#### Akra-Bazzi exponent `p`
Every Akra-Bazzi recurrence has an associated exponent, denoted by `p : ℝ`, such that
`∑ a_i b_i^p = 1`. This section shows the existence and uniqueness of this exponent `p` for any
`R : AkraBazziRecurrence`, and defines `R.asympBound` to be the asymptotic bound satisfied by `R`,
namely `n^p (1 + ∑_{u < n} g(u) / u^(p+1))`. -/
@[continuity]
lemma continuous_sumCoeffsExp : Continuous (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by
refine continuous_finset_sum Finset.univ fun i _ => Continuous.mul (by fun_prop) ?_
exact Continuous.rpow continuous_const continuous_id (fun x => Or.inl (ne_of_gt (R.b_pos i)))
lemma strictAnti_sumCoeffsExp : StrictAnti (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by
rw [← Finset.sum_fn]
refine Finset.sum_induction_nonempty _ _ (fun _ _ => StrictAnti.add) univ_nonempty ?terms
refine fun i _ => StrictAnti.const_mul ?_ (R.a_pos i)
exact Real.strictAnti_rpow_of_base_lt_one (R.b_pos i) (R.b_lt_one i)
lemma tendsto_zero_sumCoeffsExp : Tendsto (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) atTop (𝓝 0) := by
have h₁ : Finset.univ.sum (fun _ : α => (0 : ℝ)) = 0 := by simp
rw [← h₁]
refine tendsto_finset_sum (univ : Finset α) (fun i _ => ?_)
rw [← mul_zero (a i)]
refine Tendsto.mul (by simp) <| tendsto_rpow_atTop_of_base_lt_one _ ?_ (R.b_lt_one i)
have := R.b_pos i
linarith
lemma tendsto_atTop_sumCoeffsExp : Tendsto (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) atBot atTop := by
have h₁ : Tendsto (fun p : ℝ => (a (max_bi b) : ℝ) * b (max_bi b) ^ p) atBot atTop :=
Tendsto.const_mul_atTop (R.a_pos (max_bi b)) <| tendsto_rpow_atBot_of_base_lt_one _
(by have := R.b_pos (max_bi b); linarith) (R.b_lt_one _)
refine tendsto_atTop_mono (fun p => ?_) h₁
refine Finset.single_le_sum (f := fun i => (a i : ℝ) * b i ^ p) (fun i _ => ?_) (mem_univ _)
have h₁ : 0 < a i := R.a_pos i
have h₂ : 0 < b i := R.b_pos i
positivity
lemma one_mem_range_sumCoeffsExp : 1 ∈ Set.range (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) := by
refine mem_range_of_exists_le_of_exists_ge R.continuous_sumCoeffsExp ?le_one ?ge_one
case le_one =>
exact R.tendsto_zero_sumCoeffsExp.eventually_le_const zero_lt_one |>.exists
case ge_one =>
exact R.tendsto_atTop_sumCoeffsExp.eventually_ge_atTop _ |>.exists
/-- The function x ↦ ∑ a_i b_i^x is injective. This implies the uniqueness of `p`. -/
lemma injective_sumCoeffsExp : Function.Injective (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) :=
R.strictAnti_sumCoeffsExp.injective
end
variable (a b) in
/-- The exponent `p` associated with a particular Akra-Bazzi recurrence. -/
noncomputable irreducible_def p : ℝ := Function.invFun (fun (p : ℝ) => ∑ i, a i * (b i) ^ p) 1
include R in
@[simp]
lemma sumCoeffsExp_p_eq_one : ∑ i, a i * (b i) ^ p a b = 1 := by
simp only [p]
exact Function.invFun_eq (by rw [← Set.mem_range]; exact R.one_mem_range_sumCoeffsExp)
/-!
#### The sum transform
This section defines the "sum transform" of a function `g` as
`∑ u ∈ Finset.Ico n₀ n, g u / u^(p+1)`,
and uses it to define `asympBound` as the bound satisfied by an Akra-Bazzi recurrence.
Several properties of the sum transform are then proven.
-/
/-- The transformation which turns a function `g` into
`n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p+1)`. -/
noncomputable def sumTransform (p : ℝ) (g : ℝ → ℝ) (n₀ n : ℕ) :=
n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p + 1)
lemma sumTransform_def {p : ℝ} {g : ℝ → ℝ} {n₀ n : ℕ} :
sumTransform p g n₀ n = n^p * ∑ u ∈ Finset.Ico n₀ n, g u / u^(p + 1) := rfl
variable (g) (a) (b)
/-- The asymptotic bound satisfied by an Akra-Bazzi recurrence, namely
`n^p (1 + ∑_{u < n} g(u) / u^(p+1))`. -/
noncomputable def asympBound (n : ℕ) : ℝ := n ^ p a b + sumTransform (p a b) g 0 n
lemma asympBound_def {α} [Fintype α] (a b : α → ℝ) {n : ℕ} :
asympBound g a b n = n ^ p a b + sumTransform (p a b) g 0 n := rfl
variable {g} {a} {b}
lemma asympBound_def' {α} [Fintype α] (a b : α → ℝ) {n : ℕ} :
asympBound g a b n = n ^ p a b * (1 + (∑ u ∈ range n, g u / u ^ (p a b + 1))) := by
simp [asympBound_def, sumTransform, mul_add, mul_one, Finset.sum_Ico_eq_sum_range]
section
include R
lemma asympBound_pos (n : ℕ) (hn : 0 < n) : 0 < asympBound g a b n := by
calc 0 < (n : ℝ) ^ p a b * (1 + 0) := by aesop (add safe Real.rpow_pos_of_pos)
_ ≤ asympBound g a b n := by
simp only [asympBound_def']
gcongr n^p a b * (1 + ?_)
have := R.g_nonneg
aesop (add safe Real.rpow_nonneg,
safe div_nonneg,
safe Finset.sum_nonneg)
lemma eventually_asympBound_pos : ∀ᶠ (n : ℕ) in atTop, 0 < asympBound g a b n := by
filter_upwards [eventually_gt_atTop 0] with n hn
exact R.asympBound_pos n hn
lemma eventually_asympBound_r_pos : ∀ᶠ (n : ℕ) in atTop, ∀ i, 0 < asympBound g a b (r i n) := by
rw [Filter.eventually_all]
exact fun i => (R.tendsto_atTop_r i).eventually R.eventually_asympBound_pos
lemma eventually_atTop_sumTransform_le :
∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ i, sumTransform (p a b) g (r i n) n ≤ c * g n := by
obtain ⟨c₁, hc₁_mem, hc₁⟩ := R.exists_eventually_const_mul_le_r
obtain ⟨c₂, hc₂_mem, hc₂⟩ := R.g_grows_poly.eventually_atTop_le_nat hc₁_mem
have hc₁_pos : 0 < c₁ := hc₁_mem.1
refine ⟨max c₂ (c₂ / c₁ ^ (p a b + 1)), by positivity, ?_⟩
filter_upwards [hc₁, hc₂, R.eventually_r_pos, R.eventually_r_lt_n, eventually_gt_atTop 0]
with n hn₁ hn₂ hrpos hr_lt_n hn_pos
intro i
have hrpos_i := hrpos i
have g_nonneg : 0 ≤ g n := R.g_nonneg n (by positivity)
cases le_or_lt 0 (p a b + 1) with
| inl hp => -- 0 ≤ p a b + 1
calc sumTransform (p a b) g (r i n) n
= n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := by rfl
_ ≤ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by
gcongr with u hu
rw [Finset.mem_Ico] at hu
have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by omega⟩
refine hn₂ u ?_
rw [Set.mem_Icc]
refine ⟨?_, by norm_cast; omega⟩
calc c₁ * n ≤ r i n := by exact hn₁ i
_ ≤ u := by exact_mod_cast hu'.1
_ ≤ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / (r i n) ^ ((p a b) + 1)) := by
gcongr with u hu; rw [Finset.mem_Ico] at hu; exact hu.1
_ ≤ n ^ p a b * #(Ico (r i n) n) • (c₂ * g n / r i n ^ (p a b + 1)) := by
gcongr; exact Finset.sum_le_card_nsmul _ _ _ (fun x _ => by rfl)
_ = n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / r i n ^ (p a b + 1)) := by
rw [nsmul_eq_mul, mul_assoc]
_ = n ^ (p a b) * (n - r i n) * (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by
congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)]
_ ≤ n ^ (p a b) * n * (c₂ * g n / (r i n) ^ ((p a b) + 1)) := by
gcongr; simp only [tsub_le_iff_right, le_add_iff_nonneg_right, Nat.cast_nonneg]
_ ≤ n ^ (p a b) * n * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by
gcongr; exact hn₁ i
_ = c₂ * g n * n ^ ((p a b) + 1) / (c₁ * n) ^ ((p a b) + 1) := by
rw [← Real.rpow_add_one (by positivity) (p a b)]; ring
_ = c₂ * g n * n ^ ((p a b) + 1) / (n ^ ((p a b) + 1) * c₁ ^ ((p a b) + 1)) := by
rw [mul_comm c₁, Real.mul_rpow (by positivity) (by positivity)]
_ = c₂ * g n * (n ^ ((p a b) + 1) / (n ^ ((p a b) + 1))) / c₁ ^ ((p a b) + 1) := by ring
_ = c₂ * g n / c₁ ^ ((p a b) + 1) := by rw [div_self (by positivity), mul_one]
_ = (c₂ / c₁ ^ ((p a b) + 1)) * g n := by ring
_ ≤ max c₂ (c₂ / c₁ ^ ((p a b) + 1)) * g n := by gcongr; exact le_max_right _ _
| inr hp => -- p a b + 1 < 0
calc sumTransform (p a b) g (r i n) n
= n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := by rfl
_ ≤ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by
gcongr with u hu
rw [Finset.mem_Ico] at hu
have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by omega⟩
refine hn₂ u ?_
rw [Set.mem_Icc]
refine ⟨?_, by norm_cast; omega⟩
calc c₁ * n ≤ r i n := by exact hn₁ i
_ ≤ u := by exact_mod_cast hu'.1
_ ≤ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / n ^ ((p a b) + 1)) := by
gcongr n ^ (p a b) * (Finset.Ico (r i n) n).sum (fun _ => c₂ * g n / ?_) with u hu
rw [Finset.mem_Ico] at hu
have : 0 < u := calc
0 < r i n := by exact hrpos_i
_ ≤ u := by exact hu.1
exact rpow_le_rpow_of_exponent_nonpos (by positivity)
(by exact_mod_cast (le_of_lt hu.2)) (le_of_lt hp)
_ ≤ n ^ p a b * #(Ico (r i n) n) • (c₂ * g n / n ^ (p a b + 1)) := by
gcongr; exact Finset.sum_le_card_nsmul _ _ _ (fun x _ => by rfl)
_ = n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / n ^ (p a b + 1)) := by
rw [nsmul_eq_mul, mul_assoc]
_ = n ^ (p a b) * (n - r i n) * (c₂ * g n / n ^ ((p a b) + 1)) := by
congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)]
_ ≤ n ^ (p a b) * n * (c₂ * g n / n ^ ((p a b) + 1)) := by
gcongr; simp only [tsub_le_iff_right, le_add_iff_nonneg_right, Nat.cast_nonneg]
_ = c₂ * (n^((p a b) + 1) / n ^ ((p a b) + 1)) * g n := by
rw [← Real.rpow_add_one (by positivity) (p a b)]; ring
_ = c₂ * g n := by rw [div_self (by positivity), mul_one]
_ ≤ max c₂ (c₂ / c₁ ^ ((p a b) + 1)) * g n := by gcongr; exact le_max_left _ _
lemma eventually_atTop_sumTransform_ge :
∃ c > 0, ∀ᶠ (n : ℕ) in atTop, ∀ i, c * g n ≤ sumTransform (p a b) g (r i n) n := by
obtain ⟨c₁, hc₁_mem, hc₁⟩ := R.exists_eventually_const_mul_le_r
obtain ⟨c₂, hc₂_mem, hc₂⟩ := R.g_grows_poly.eventually_atTop_ge_nat hc₁_mem
obtain ⟨c₃, hc₃_mem, hc₃⟩ := R.exists_eventually_r_le_const_mul
have hc₁_pos : 0 < c₁ := hc₁_mem.1
have hc₃' : 0 < (1 - c₃) := by have := hc₃_mem.2; linarith
refine ⟨min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁^((p a b) + 1)), by positivity, ?_⟩
filter_upwards [hc₁, hc₂, hc₃, R.eventually_r_pos, R.eventually_r_lt_n, eventually_gt_atTop 0]
with n hn₁ hn₂ hn₃ hrpos hr_lt_n hn_pos
intro i
have hrpos_i := hrpos i
have g_nonneg : 0 ≤ g n := R.g_nonneg n (by positivity)
cases le_or_gt 0 (p a b + 1) with
| inl hp => -- 0 ≤ (p a b) + 1
calc sumTransform (p a b) g (r i n) n
= n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1)) := rfl
_ ≥ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u^((p a b) + 1)) := by
gcongr with u hu
rw [Finset.mem_Ico] at hu
have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by omega⟩
refine hn₂ u ?_
rw [Set.mem_Icc]
refine ⟨?_, by norm_cast; omega⟩
calc c₁ * n ≤ r i n := by exact hn₁ i
_ ≤ u := by exact_mod_cast hu'.1
_ ≥ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / n ^ ((p a b) + 1)) := by
gcongr with u hu
· rw [Finset.mem_Ico] at hu
have := calc 0 < r i n := hrpos_i
_ ≤ u := hu.1
positivity
· rw [Finset.mem_Ico] at hu
exact le_of_lt hu.2
_ ≥ n ^ p a b * #(Ico (r i n) n) • (c₂ * g n / n ^ (p a b + 1)) := by
gcongr; exact Finset.card_nsmul_le_sum _ _ _ (fun x _ => by rfl)
_ = n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / n ^ (p a b + 1)) := by
rw [nsmul_eq_mul, mul_assoc]
_ = n ^ (p a b) * (n - r i n) * (c₂ * g n / n ^ ((p a b) + 1)) := by
congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)]
_ ≥ n ^ (p a b) * (n - c₃ * n) * (c₂ * g n / n ^ ((p a b) + 1)) := by
gcongr; exact hn₃ i
_ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / n ^ ((p a b) + 1)) := by ring
_ = c₂ * (1 - c₃) * g n * (n ^ ((p a b) + 1) / n ^ ((p a b) + 1)) := by
rw [← Real.rpow_add_one (by positivity) (p a b)]; ring
_ = c₂ * (1 - c₃) * g n := by rw [div_self (by positivity), mul_one]
_ ≥ min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁ ^ ((p a b) + 1)) * g n := by
gcongr; exact min_le_left _ _
| inr hp => -- (p a b) + 1 < 0
calc sumTransform (p a b) g (r i n) n
= n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u^((p a b) + 1)) := by rfl
_ ≥ n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, c₂ * g n / u ^ ((p a b) + 1)) := by
gcongr with u hu
rw [Finset.mem_Ico] at hu
have hu' : u ∈ Set.Icc (r i n) n := ⟨hu.1, by omega⟩
refine hn₂ u ?_
rw [Set.mem_Icc]
refine ⟨?_, by norm_cast; omega⟩
calc c₁ * n ≤ r i n := by exact hn₁ i
_ ≤ u := by exact_mod_cast hu'.1
_ ≥ n ^ (p a b) * (∑ _u ∈ Finset.Ico (r i n) n, c₂ * g n / (r i n) ^ ((p a b) + 1)) := by
gcongr n^(p a b) * (Finset.Ico (r i n) n).sum (fun _ => c₂ * g n / ?_) with u hu
· rw [Finset.mem_Ico] at hu
have := calc 0 < r i n := hrpos_i
_ ≤ u := hu.1
positivity
· rw [Finset.mem_Ico] at hu
exact rpow_le_rpow_of_exponent_nonpos (by positivity)
(by exact_mod_cast hu.1) (le_of_lt hp)
_ ≥ n ^ p a b * #(Ico (r i n) n) • (c₂ * g n / r i n ^ (p a b + 1)) := by
gcongr; exact Finset.card_nsmul_le_sum _ _ _ (fun x _ => by rfl)
_ = n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / r i n ^ (p a b + 1)) := by
rw [nsmul_eq_mul, mul_assoc]
_ ≥ n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / (c₁ * n) ^ (p a b + 1)) := by
gcongr n ^ p a b * #(Ico (r i n) n) * (c₂ * g n / ?_)
exact rpow_le_rpow_of_exponent_nonpos (by positivity) (hn₁ i) (le_of_lt hp)
_ = n ^ (p a b) * (n - r i n) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by
congr; rw [Nat.card_Ico, Nat.cast_sub (le_of_lt <| hr_lt_n i)]
_ ≥ n ^ (p a b) * (n - c₃ * n) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by
gcongr; exact hn₃ i
_ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / (c₁ * n) ^ ((p a b) + 1)) := by ring
_ = n ^ (p a b) * n * (1 - c₃) * (c₂ * g n / (c₁ ^ ((p a b) + 1) * n ^ ((p a b) + 1))) := by
rw [Real.mul_rpow (by positivity) (by positivity)]
_ = (n ^ ((p a b) + 1) / n ^ ((p a b) + 1)) * (1 - c₃) * c₂ * g n / c₁ ^ ((p a b) + 1) := by
rw [← Real.rpow_add_one (by positivity) (p a b)]; ring
_ = (1 - c₃) * c₂ / c₁ ^ ((p a b) + 1) * g n := by
rw [div_self (by positivity), one_mul]; ring
_ ≥ min (c₂ * (1 - c₃)) ((1 - c₃) * c₂ / c₁ ^ ((p a b) + 1)) * g n := by
gcongr; exact min_le_right _ _
end
/-!
#### Technical lemmas
The next several lemmas are technical lemmas leading up to `rpow_p_mul_one_sub_smoothingFn_le` and
`rpow_p_mul_one_add_smoothingFn_ge`, which are key steps in the main proof.
-/
lemma eventually_deriv_rpow_p_mul_one_sub_smoothingFn (p : ℝ) :
deriv (fun z => z ^ p * (1 - ε z))
=ᶠ[atTop] fun z => p * z ^ (p-1) * (1 - ε z) + z ^ (p-1) / (log z ^ 2) := calc
deriv (fun x => x ^ p * (1 - ε x))
=ᶠ[atTop] fun x => deriv (· ^ p) x * (1 - ε x) + x ^ p * deriv (1 - ε ·) x := by
filter_upwards [eventually_gt_atTop 1] with x hx
rw [deriv_mul]
· exact differentiableAt_rpow_const_of_ne _ (by positivity)
· exact differentiableAt_one_sub_smoothingFn hx
_ =ᶠ[atTop] fun x => p * x ^ (p-1) * (1 - ε x) + x ^ p * (x⁻¹ / (log x ^ 2)) := by
filter_upwards [eventually_gt_atTop 1, eventually_deriv_one_sub_smoothingFn]
with x hx hderiv
rw [hderiv, Real.deriv_rpow_const (Or.inl <| by positivity)]
_ =ᶠ[atTop] fun x => p * x ^ (p-1) * (1 - ε x) + x ^ (p-1) / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 0] with x hx
rw [mul_div, ← Real.rpow_neg_one, ← Real.rpow_add (by positivity), sub_eq_add_neg]
lemma eventually_deriv_rpow_p_mul_one_add_smoothingFn (p : ℝ) :
deriv (fun z => z ^ p * (1 + ε z))
=ᶠ[atTop] fun z => p * z ^ (p-1) * (1 + ε z) - z ^ (p-1) / (log z ^ 2) := calc
deriv (fun x => x ^ p * (1 + ε x))
=ᶠ[atTop] fun x => deriv (· ^ p) x * (1 + ε x) + x ^ p * deriv (1 + ε ·) x := by
filter_upwards [eventually_gt_atTop 1] with x hx
rw [deriv_mul]
· exact differentiableAt_rpow_const_of_ne _ (by positivity)
· exact differentiableAt_one_add_smoothingFn hx
_ =ᶠ[atTop] fun x => p * x ^ (p-1) * (1 + ε x) - x ^ p * (x⁻¹ / (log x ^ 2)) := by
filter_upwards [eventually_gt_atTop 1, eventually_deriv_one_add_smoothingFn]
with x hx hderiv
simp [hderiv, Real.deriv_rpow_const (Or.inl <| by positivity), neg_div, sub_eq_add_neg]
_ =ᶠ[atTop] fun x => p * x ^ (p-1) * (1 + ε x) - x ^ (p-1) / (log x ^ 2) := by
filter_upwards [eventually_gt_atTop 0] with x hx
simp [mul_div, ← Real.rpow_neg_one, ← Real.rpow_add (by positivity), sub_eq_add_neg]
lemma isEquivalent_deriv_rpow_p_mul_one_sub_smoothingFn {p : ℝ} (hp : p ≠ 0) :
deriv (fun z => z ^ p * (1 - ε z)) ~[atTop] fun z => p * z ^ (p-1) := calc
deriv (fun z => z ^ p * (1 - ε z))
=ᶠ[atTop] fun z => p * z ^ (p-1) * (1 - ε z) + z^(p-1) / (log z ^ 2) :=
eventually_deriv_rpow_p_mul_one_sub_smoothingFn p
_ ~[atTop] fun z => p * z ^ (p-1) := by
refine IsEquivalent.add_isLittleO ?one ?two
case one => calc
(fun z => p * z ^ (p-1) * (1 - ε z)) ~[atTop] fun z => p * z ^ (p-1) * 1 :=
IsEquivalent.mul IsEquivalent.refl isEquivalent_one_sub_smoothingFn_one
_ = fun z => p * z ^ (p-1) := by ext; ring
case two => calc
(fun z => z ^ (p-1) / (log z ^ 2)) =o[atTop] fun z => z ^ (p-1) / 1 := by
simp_rw [div_eq_mul_inv]
refine IsBigO.mul_isLittleO (isBigO_refl _ _)
(IsLittleO.inv_rev ?_ (by simp))
rw [isLittleO_const_left]
refine Or.inr <| Tendsto.comp tendsto_norm_atTop_atTop ?_
exact Tendsto.comp (g := fun z => z ^ 2)
(tendsto_pow_atTop (by norm_num)) tendsto_log_atTop
_ = fun z => z ^ (p-1) := by ext; simp
_ =Θ[atTop] fun z => p * z ^ (p-1) := by
exact IsTheta.const_mul_right hp <| isTheta_refl _ _
lemma isEquivalent_deriv_rpow_p_mul_one_add_smoothingFn {p : ℝ} (hp : p ≠ 0) :
deriv (fun z => z ^ p * (1 + ε z)) ~[atTop] fun z => p * z ^ (p-1) := calc
deriv (fun z => z ^ p * (1 + ε z))
=ᶠ[atTop] fun z => p * z ^ (p-1) * (1 + ε z) - z ^ (p-1) / (log z ^ 2) :=
eventually_deriv_rpow_p_mul_one_add_smoothingFn p
_ ~[atTop] fun z => p * z ^ (p-1) := by
refine IsEquivalent.add_isLittleO ?one ?two
case one => calc
(fun z => p * z ^ (p-1) * (1 + ε z)) ~[atTop] fun z => p * z ^ (p-1) * 1 :=
IsEquivalent.mul IsEquivalent.refl isEquivalent_one_add_smoothingFn_one
_ = fun z => p * z ^ (p-1) := by ext; ring
case two => calc
(fun z => -(z ^ (p-1) / (log z ^ 2))) =o[atTop] fun z => z ^ (p-1) / 1 := by
simp_rw [isLittleO_neg_left, div_eq_mul_inv]
refine IsBigO.mul_isLittleO (isBigO_refl _ _)
(IsLittleO.inv_rev ?_ (by simp))
rw [isLittleO_const_left]
refine Or.inr <| Tendsto.comp tendsto_norm_atTop_atTop ?_
exact Tendsto.comp (g := fun z => z ^ 2)
(tendsto_pow_atTop (by norm_num)) tendsto_log_atTop
_ = fun z => z ^ (p-1) := by ext; simp
_ =Θ[atTop] fun z => p * z ^ (p-1) := by
exact IsTheta.const_mul_right hp <| isTheta_refl _ _
lemma isTheta_deriv_rpow_p_mul_one_sub_smoothingFn {p : ℝ} (hp : p ≠ 0) :
(fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖) =Θ[atTop] fun z => z ^ (p-1) := by
refine IsTheta.norm_left ?_
calc (fun x => deriv (fun z => z ^ p * (1 - ε z)) x) =Θ[atTop] fun z => p * z ^ (p-1) :=
(isEquivalent_deriv_rpow_p_mul_one_sub_smoothingFn hp).isTheta
_ =Θ[atTop] fun z => z ^ (p-1) :=
IsTheta.const_mul_left hp <| isTheta_refl _ _
lemma isTheta_deriv_rpow_p_mul_one_add_smoothingFn {p : ℝ} (hp : p ≠ 0) :
(fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖) =Θ[atTop] fun z => z ^ (p-1) := by
refine IsTheta.norm_left ?_
calc (fun x => deriv (fun z => z ^ p * (1 + ε z)) x) =Θ[atTop] fun z => p * z ^ (p-1) :=
(isEquivalent_deriv_rpow_p_mul_one_add_smoothingFn hp).isTheta
_ =Θ[atTop] fun z => z ^ (p-1) :=
IsTheta.const_mul_left hp <| isTheta_refl _ _
lemma growsPolynomially_deriv_rpow_p_mul_one_sub_smoothingFn (p : ℝ) :
GrowsPolynomially fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖ := by
cases eq_or_ne p 0 with
| inl hp => -- p = 0
have h₁ : (fun x => ‖deriv (fun z => z ^ p * (1 - ε z)) x‖)
=ᶠ[atTop] fun z => z⁻¹ / (log z ^ 2) := by
filter_upwards [eventually_deriv_one_sub_smoothingFn, eventually_gt_atTop 1] with x hx hx_pos
have : 0 ≤ x⁻¹ / (log x ^ 2) := by
have hlog : 0 < log x := Real.log_pos hx_pos
positivity
simp only [hp, Real.rpow_zero, one_mul, differentiableAt_const, hx, Real.norm_of_nonneg this]
refine GrowsPolynomially.congr_of_eventuallyEq h₁ ?_
refine GrowsPolynomially.div (GrowsPolynomially.inv growsPolynomially_id)
(GrowsPolynomially.pow 2 growsPolynomially_log ?_)
filter_upwards [eventually_ge_atTop 1] with _ hx
exact log_nonneg hx
| inr hp => -- p ≠ 0
refine GrowsPolynomially.of_isTheta (growsPolynomially_rpow (p-1))
(isTheta_deriv_rpow_p_mul_one_sub_smoothingFn hp) ?_
filter_upwards [eventually_gt_atTop 0] with _ _
positivity
lemma growsPolynomially_deriv_rpow_p_mul_one_add_smoothingFn (p : ℝ) :
GrowsPolynomially fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖ := by
cases eq_or_ne p 0 with
| inl hp => -- p = 0
have h₁ : (fun x => ‖deriv (fun z => z ^ p * (1 + ε z)) x‖)
=ᶠ[atTop] fun z => z⁻¹ / (log z ^ 2) := by
filter_upwards [eventually_deriv_one_add_smoothingFn, eventually_gt_atTop 1] with x hx hx_pos
have : 0 ≤ x⁻¹ / (log x ^ 2) := by
have hlog : 0 < log x := Real.log_pos hx_pos
positivity
simp only [neg_div, norm_neg, hp, Real.rpow_zero,
one_mul, differentiableAt_const, hx, Real.norm_of_nonneg this]
refine GrowsPolynomially.congr_of_eventuallyEq h₁ ?_
refine GrowsPolynomially.div (GrowsPolynomially.inv growsPolynomially_id)
(GrowsPolynomially.pow 2 growsPolynomially_log ?_)
filter_upwards [eventually_ge_atTop 1] with x hx
exact log_nonneg hx
| inr hp => -- p ≠ 0
refine GrowsPolynomially.of_isTheta (growsPolynomially_rpow (p-1))
(isTheta_deriv_rpow_p_mul_one_add_smoothingFn hp) ?_
filter_upwards [eventually_gt_atTop 0] with _ _
positivity
include R
lemma isBigO_apply_r_sub_b (q : ℝ → ℝ) (hq_diff : DifferentiableOn ℝ q (Set.Ioi 1))
(hq_poly : GrowsPolynomially fun x => ‖deriv q x‖) (i : α) :
(fun n => q (r i n) - q (b i * n)) =O[atTop] fun n => (deriv q n) * (r i n - b i * n) := by
let b' := b (min_bi b) / 2
have hb_pos : 0 < b' := by have := R.b_pos (min_bi b); positivity
have hb_lt_one : b' < 1 := calc
b (min_bi b) / 2 < b (min_bi b) := by exact div_two_lt_of_pos (R.b_pos (min_bi b))
_ < 1 := R.b_lt_one (min_bi b)
have hb : b' ∈ Set.Ioo 0 1 := ⟨hb_pos, hb_lt_one⟩
have hb' : ∀ i, b' ≤ b i := fun i => calc
b (min_bi b) / 2 ≤ b i / 2 := by gcongr; aesop
_ ≤ b i := by exact le_of_lt <| div_two_lt_of_pos (R.b_pos i)
| obtain ⟨c₁, _, c₂, _, hq_poly⟩ := hq_poly b' hb
rw [isBigO_iff]
refine ⟨c₂, ?_⟩
have h_tendsto : Tendsto (fun x => b' * x) atTop atTop :=
Tendsto.const_mul_atTop hb_pos tendsto_id
filter_upwards [hq_poly.natCast_atTop, R.eventually_bi_mul_le_r, eventually_ge_atTop R.n₀,
eventually_gt_atTop 0, (h_tendsto.eventually_gt_atTop 1).natCast_atTop] with
n hn h_bi_le_r h_ge_n₀ h_n_pos h_bn
rw [norm_mul, ← mul_assoc]
refine Convex.norm_image_sub_le_of_norm_deriv_le
(s := Set.Icc (b'*n) n) (fun z hz => ?diff) (fun z hz => (hn z hz).2)
(convex_Icc _ _) ?mem_Icc <| ⟨h_bi_le_r i, by exact_mod_cast (le_of_lt (R.r_lt_n i n h_ge_n₀))⟩
case diff =>
refine hq_diff.differentiableAt (Ioi_mem_nhds ?_)
calc 1 < b' * n := by exact h_bn
_ ≤ z := hz.1
case mem_Icc =>
refine ⟨by gcongr; exact hb' i, ?_⟩
calc b i * n ≤ 1 * n := by gcongr; exact le_of_lt <| R.b_lt_one i
_ = n := by simp
lemma rpow_p_mul_one_sub_smoothingFn_le :
∀ᶠ (n : ℕ) in atTop, ∀ i, (r i n) ^ (p a b) * (1 - ε (r i n))
≤ (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) := by
rw [Filter.eventually_all]
intro i
let q : ℝ → ℝ := fun x => x ^ (p a b) * (1 - ε x)
have h_diff_q : DifferentiableOn ℝ q (Set.Ioi 1) := by
refine DifferentiableOn.mul
(DifferentiableOn.mono (differentiableOn_rpow_const _) fun z hz => ?_)
differentiableOn_one_sub_smoothingFn
rw [Set.mem_compl_singleton_iff]
rw [Set.mem_Ioi] at hz
exact ne_of_gt <| zero_lt_one.trans hz
have h_deriv_q : deriv q =O[atTop] fun x => x ^ ((p a b) - 1) := calc
deriv q = deriv fun x => (fun z => z ^ (p a b)) x * (fun z => 1 - ε z) x := by rfl
_ =ᶠ[atTop] fun x => deriv (fun z => z ^ (p a b)) x * (1 - ε x) +
x ^ (p a b) * deriv (fun z => 1 - ε z) x := by
filter_upwards [eventually_ne_atTop 0, eventually_gt_atTop 1] with x hx hx'
rw [deriv_mul] <;> aesop
_ =O[atTop] fun x => x ^ ((p a b) - 1) := by
refine IsBigO.add ?left ?right
case left => calc
(fun x => deriv (fun z => z ^ (p a b)) x * (1 - ε x))
=O[atTop] fun x => x ^ ((p a b) - 1) * (1 - ε x) := by
exact IsBigO.mul (isBigO_deriv_rpow_const_atTop (p a b)) (isBigO_refl _ _)
_ =O[atTop] fun x => x ^ ((p a b) - 1) * 1 := by
refine IsBigO.mul (isBigO_refl _ _)
isEquivalent_one_sub_smoothingFn_one.isBigO
_ = fun x => x ^ ((p a b) - 1) := by ext; rw [mul_one]
case right => calc
(fun x => x ^ (p a b) * deriv (fun z => 1 - ε z) x)
=O[atTop] (fun x => x ^ (p a b) * x⁻¹) := by
exact IsBigO.mul (isBigO_refl _ _) isLittleO_deriv_one_sub_smoothingFn.isBigO
_ =ᶠ[atTop] fun x => x ^ ((p a b) - 1) := by
filter_upwards [eventually_gt_atTop 0] with x hx
rw [← Real.rpow_neg_one, ← Real.rpow_add hx, ← sub_eq_add_neg]
have h_main_norm : (fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖)
≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ := by
refine IsLittleO.eventuallyLE ?_
calc
(fun (n : ℕ) => q (r i n) - q (b i * n))
=O[atTop] fun n => (deriv q n) * (r i n - b i * n) := by
exact R.isBigO_apply_r_sub_b q h_diff_q
(growsPolynomially_deriv_rpow_p_mul_one_sub_smoothingFn (p a b)) i
_ =o[atTop] fun n => (deriv q n) * (n / log n ^ 2) := by
exact IsBigO.mul_isLittleO (isBigO_refl _ _) (R.dist_r_b i)
_ =O[atTop] fun n => n^((p a b) - 1) * (n / log n ^ 2) := by
exact IsBigO.mul (IsBigO.natCast_atTop h_deriv_q) (isBigO_refl _ _)
_ =ᶠ[atTop] fun n => n^(p a b) / (log n) ^ 2 := by
filter_upwards [eventually_ne_atTop 0] with n hn
have hn' : (n : ℝ) ≠ 0 := by positivity
simp [← mul_div_assoc, ← Real.rpow_add_one hn']
_ = fun (n : ℕ) => (n : ℝ) ^ (p a b) * (1 / (log n)^2) := by
simp_rw [mul_div, mul_one]
_ =Θ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (1 / (log n)^2) := by
refine IsTheta.symm ?_
simp_rw [mul_assoc]
refine IsTheta.const_mul_left ?_ (isTheta_refl _ _)
have := R.b_pos i; positivity
_ =Θ[atTop] fun (n : ℕ) => (b i)^(p a b) * n^(p a b) * (ε (b i * n) - ε n) := by
exact IsTheta.symm <| IsTheta.mul (isTheta_refl _ _)
<| R.isTheta_smoothingFn_sub_self i
have h_main : (fun (n : ℕ) => q (r i n) - q (b i * n))
≤ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by
calc (fun (n : ℕ) => q (r i n) - q (b i * n))
≤ᶠ[atTop] fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖ := by
filter_upwards with _; exact le_norm_self _
_ ≤ᶠ[atTop] fun (n : ℕ) => ‖(b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)‖ :=
h_main_norm
_ =ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by
filter_upwards [eventually_gt_atTop ⌈(b i)⁻¹⌉₊, eventually_gt_atTop 1] with n hn hn'
refine norm_of_nonneg ?_
have h₁ := R.b_pos i
| Mathlib/Computability/AkraBazzi/AkraBazzi.lean | 953 | 1,046 |
/-
Copyright (c) 2024 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Stoll
-/
import Mathlib.Analysis.InnerProductSpace.Basic
import Mathlib.Analysis.Normed.Ring.InfiniteSum
import Mathlib.NumberTheory.ArithmeticFunction
import Mathlib.NumberTheory.LSeries.Convergence
/-!
# Dirichlet convolution of sequences and products of L-series
We define the *Dirichlet convolution* `f ⍟ g` of two sequences `f g : ℕ → R` with values in a
semiring `R` by `(f ⍟ g) n = ∑ (k * m = n), f k * g m` when `n ≠ 0` and `(f ⍟ g) 0 = 0`.
Technically, this is done by transporting the existing definition for `ArithmeticFunction R`;
see `LSeries.convolution`. We show that these definitions agree (`LSeries.convolution_def`).
We then consider the case `R = ℂ` and show that `L (f ⍟ g) = L f * L g` on the common domain
of convergence of the L-series `L f` and `L g` of `f` and `g`; see `LSeries_convolution`
and `LSeries_convolution'`.
-/
open scoped LSeries.notation
open Complex LSeries
/-!
### Dirichlet convolution of two functions
-/
open Nat
/-- We turn any function `ℕ → R` into an `ArithmeticFunction R` by setting its value at `0`
to be zero. -/
def toArithmeticFunction {R : Type*} [Zero R] (f : ℕ → R) : ArithmeticFunction R where
toFun n := if n = 0 then 0 else f n
map_zero' := rfl
lemma toArithmeticFunction_congr {R : Type*} [Zero R] {f f' : ℕ → R}
(h : ∀ {n}, n ≠ 0 → f n = f' n) :
toArithmeticFunction f = toArithmeticFunction f' := by
ext
simp_all [toArithmeticFunction]
/-- If we consider an arithmetic function just as a function and turn it back into an
arithmetic function, it is the same as before. -/
| @[simp]
lemma ArithmeticFunction.toArithmeticFunction_eq_self {R : Type*} [Zero R]
(f : ArithmeticFunction R) :
toArithmeticFunction f = f := by
ext n
simp +contextual [toArithmeticFunction]
/-- Dirichlet convolution of two sequences.
| Mathlib/NumberTheory/LSeries/Convolution.lean | 48 | 55 |
/-
Copyright (c) 2021 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, David Kurniadi Angdinata
-/
import Mathlib.Algebra.CharP.Defs
import Mathlib.Algebra.CubicDiscriminant
import Mathlib.RingTheory.Nilpotent.Defs
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.LinearCombination
/-!
# Weierstrass equations of elliptic curves
This file defines the structure of an elliptic curve as a nonsingular Weierstrass curve given by a
Weierstrass equation, which is mathematically accurate in many cases but also good for computation.
## Mathematical background
Let `S` be a scheme. The actual category of elliptic curves over `S` is a large category, whose
objects are schemes `E` equipped with a map `E → S`, a section `S → E`, and some axioms (the map is
smooth and proper and the fibres are geometrically-connected one-dimensional group varieties). In
the special case where `S` is the spectrum of some commutative ring `R` whose Picard group is zero
(this includes all fields, all PIDs, and many other commutative rings) it can be shown (using a lot
of algebro-geometric machinery) that every elliptic curve `E` is a projective plane cubic isomorphic
to a Weierstrass curve given by the equation `Y² + a₁XY + a₃Y = X³ + a₂X² + a₄X + a₆` for some `aᵢ`
in `R`, and such that a certain quantity called the discriminant of `E` is a unit in `R`. If `R` is
a field, this quantity divides the discriminant of a cubic polynomial whose roots over a splitting
field of `R` are precisely the `X`-coordinates of the non-zero 2-torsion points of `E`.
## Main definitions
* `WeierstrassCurve`: a Weierstrass curve over a commutative ring.
* `WeierstrassCurve.Δ`: the discriminant of a Weierstrass curve.
* `WeierstrassCurve.map`: the Weierstrass curve mapped over a ring homomorphism.
* `WeierstrassCurve.twoTorsionPolynomial`: the 2-torsion polynomial of a Weierstrass curve.
* `WeierstrassCurve.IsElliptic`: typeclass asserting that a Weierstrass curve is an elliptic curve.
* `WeierstrassCurve.j`: the j-invariant of an elliptic curve.
## Main statements
* `WeierstrassCurve.twoTorsionPolynomial_disc`: the discriminant of a Weierstrass curve is a
constant factor of the cubic discriminant of its 2-torsion polynomial.
## Implementation notes
The definition of elliptic curves in this file makes sense for all commutative rings `R`, but it
only gives a type which can be beefed up to a category which is equivalent to the category of
elliptic curves over the spectrum `Spec(R)` of `R` in the case that `R` has trivial Picard group
`Pic(R)` or, slightly more generally, when its 12-torsion is trivial. The issue is that for a
general ring `R`, there might be elliptic curves over `Spec(R)` in the sense of algebraic geometry
which are not globally defined by a cubic equation valid over the entire base.
## References
* [N Katz and B Mazur, *Arithmetic Moduli of Elliptic Curves*][katz_mazur]
* [P Deligne, *Courbes Elliptiques: Formulaire (d'après J. Tate)*][deligne_formulaire]
* [J Silverman, *The Arithmetic of Elliptic Curves*][silverman2009]
## Tags
elliptic curve, weierstrass equation, j invariant
-/
local macro "map_simp" : tactic =>
`(tactic| simp only [map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow])
universe s u v w
/-! ## Weierstrass curves -/
/-- A Weierstrass curve `Y² + a₁XY + a₃Y = X³ + a₂X² + a₄X + a₆` with parameters `aᵢ`. -/
@[ext]
structure WeierstrassCurve (R : Type u) where
/-- The `a₁` coefficient of a Weierstrass curve. -/
a₁ : R
/-- The `a₂` coefficient of a Weierstrass curve. -/
a₂ : R
/-- The `a₃` coefficient of a Weierstrass curve. -/
a₃ : R
/-- The `a₄` coefficient of a Weierstrass curve. -/
a₄ : R
/-- The `a₆` coefficient of a Weierstrass curve. -/
a₆ : R
namespace WeierstrassCurve
instance {R : Type u} [Inhabited R] : Inhabited <| WeierstrassCurve R :=
⟨⟨default, default, default, default, default⟩⟩
variable {R : Type u} [CommRing R] (W : WeierstrassCurve R)
section Quantity
/-! ### Standard quantities -/
/-- The `b₂` coefficient of a Weierstrass curve. -/
def b₂ : R :=
W.a₁ ^ 2 + 4 * W.a₂
/-- The `b₄` coefficient of a Weierstrass curve. -/
def b₄ : R :=
2 * W.a₄ + W.a₁ * W.a₃
/-- The `b₆` coefficient of a Weierstrass curve. -/
def b₆ : R :=
W.a₃ ^ 2 + 4 * W.a₆
/-- The `b₈` coefficient of a Weierstrass curve. -/
def b₈ : R :=
W.a₁ ^ 2 * W.a₆ + 4 * W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 - W.a₄ ^ 2
lemma b_relation : 4 * W.b₈ = W.b₂ * W.b₆ - W.b₄ ^ 2 := by
simp only [b₂, b₄, b₆, b₈]
ring1
/-- The `c₄` coefficient of a Weierstrass curve. -/
def c₄ : R :=
W.b₂ ^ 2 - 24 * W.b₄
/-- The `c₆` coefficient of a Weierstrass curve. -/
def c₆ : R :=
-W.b₂ ^ 3 + 36 * W.b₂ * W.b₄ - 216 * W.b₆
/-- The discriminant `Δ` of a Weierstrass curve. If `R` is a field, then this polynomial vanishes
if and only if the cubic curve cut out by this equation is singular. Sometimes only defined up to
sign in the literature; we choose the sign used by the LMFDB. For more discussion, see
[the LMFDB page on discriminants](https://www.lmfdb.org/knowledge/show/ec.discriminant). -/
def Δ : R :=
-W.b₂ ^ 2 * W.b₈ - 8 * W.b₄ ^ 3 - 27 * W.b₆ ^ 2 + 9 * W.b₂ * W.b₄ * W.b₆
lemma c_relation : 1728 * W.Δ = W.c₄ ^ 3 - W.c₆ ^ 2 := by
simp only [b₂, b₄, b₆, b₈, c₄, c₆, Δ]
ring1
section CharTwo
variable [CharP R 2]
lemma b₂_of_char_two : W.b₂ = W.a₁ ^ 2 := by
rw [b₂]
linear_combination 2 * W.a₂ * CharP.cast_eq_zero R 2
lemma b₄_of_char_two : W.b₄ = W.a₁ * W.a₃ := by
rw [b₄]
linear_combination W.a₄ * CharP.cast_eq_zero R 2
lemma b₆_of_char_two : W.b₆ = W.a₃ ^ 2 := by
rw [b₆]
linear_combination 2 * W.a₆ * CharP.cast_eq_zero R 2
lemma b₈_of_char_two :
W.b₈ = W.a₁ ^ 2 * W.a₆ + W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 + W.a₄ ^ 2 := by
rw [b₈]
linear_combination (2 * W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ - W.a₄ ^ 2) * CharP.cast_eq_zero R 2
lemma c₄_of_char_two : W.c₄ = W.a₁ ^ 4 := by
rw [c₄, b₂_of_char_two]
linear_combination -12 * W.b₄ * CharP.cast_eq_zero R 2
lemma c₆_of_char_two : W.c₆ = W.a₁ ^ 6 := by
rw [c₆, b₂_of_char_two]
linear_combination (18 * W.a₁ ^ 2 * W.b₄ - 108 * W.b₆ - W.a₁ ^ 6) * CharP.cast_eq_zero R 2
lemma Δ_of_char_two : W.Δ = W.a₁ ^ 4 * W.b₈ + W.a₃ ^ 4 + W.a₁ ^ 3 * W.a₃ ^ 3 := by
rw [Δ, b₂_of_char_two, b₄_of_char_two, b₆_of_char_two]
linear_combination (-W.a₁ ^ 4 * W.b₈ - 14 * W.a₃ ^ 4) * CharP.cast_eq_zero R 2
lemma b_relation_of_char_two : W.b₂ * W.b₆ = W.b₄ ^ 2 := by
linear_combination -W.b_relation + 2 * W.b₈ * CharP.cast_eq_zero R 2
lemma c_relation_of_char_two : W.c₄ ^ 3 = W.c₆ ^ 2 := by
linear_combination -W.c_relation + 864 * W.Δ * CharP.cast_eq_zero R 2
end CharTwo
section CharThree
variable [CharP R 3]
lemma b₂_of_char_three : W.b₂ = W.a₁ ^ 2 + W.a₂ := by
rw [b₂]
linear_combination W.a₂ * CharP.cast_eq_zero R 3
lemma b₄_of_char_three : W.b₄ = -W.a₄ + W.a₁ * W.a₃ := by
rw [b₄]
linear_combination W.a₄ * CharP.cast_eq_zero R 3
lemma b₆_of_char_three : W.b₆ = W.a₃ ^ 2 + W.a₆ := by
rw [b₆]
linear_combination W.a₆ * CharP.cast_eq_zero R 3
lemma b₈_of_char_three :
W.b₈ = W.a₁ ^ 2 * W.a₆ + W.a₂ * W.a₆ - W.a₁ * W.a₃ * W.a₄ + W.a₂ * W.a₃ ^ 2 - W.a₄ ^ 2 := by
rw [b₈]
linear_combination W.a₂ * W.a₆ * CharP.cast_eq_zero R 3
lemma c₄_of_char_three : W.c₄ = W.b₂ ^ 2 := by
rw [c₄]
linear_combination -8 * W.b₄ * CharP.cast_eq_zero R 3
lemma c₆_of_char_three : W.c₆ = -W.b₂ ^ 3 := by
rw [c₆]
linear_combination (12 * W.b₂ * W.b₄ - 72 * W.b₆) * CharP.cast_eq_zero R 3
lemma Δ_of_char_three : W.Δ = -W.b₂ ^ 2 * W.b₈ - 8 * W.b₄ ^ 3 := by
rw [Δ]
linear_combination (-9 * W.b₆ ^ 2 + 3 * W.b₂ * W.b₄ * W.b₆) * CharP.cast_eq_zero R 3
lemma b_relation_of_char_three : W.b₈ = W.b₂ * W.b₆ - W.b₄ ^ 2 := by
linear_combination W.b_relation - W.b₈ * CharP.cast_eq_zero R 3
lemma c_relation_of_char_three : W.c₄ ^ 3 = W.c₆ ^ 2 := by
linear_combination -W.c_relation + 576 * W.Δ * CharP.cast_eq_zero R 3
end CharThree
end Quantity
section BaseChange
/-! ### Maps and base changes -/
variable {A : Type v} [CommRing A] (f : R →+* A)
/-- The Weierstrass curve mapped over a ring homomorphism `f : R →+* A`. -/
@[simps]
def map : WeierstrassCurve A :=
⟨f W.a₁, f W.a₂, f W.a₃, f W.a₄, f W.a₆⟩
variable (A) in
/-- The Weierstrass curve base changed to an algebra `A` over `R`. -/
abbrev baseChange [Algebra R A] : WeierstrassCurve A :=
W.map <| algebraMap R A
@[simp]
lemma map_b₂ : (W.map f).b₂ = f W.b₂ := by
simp only [b₂, map_a₁, map_a₂]
map_simp
@[simp]
lemma map_b₄ : (W.map f).b₄ = f W.b₄ := by
simp only [b₄, map_a₁, map_a₃, map_a₄]
map_simp
@[simp]
lemma map_b₆ : (W.map f).b₆ = f W.b₆ := by
simp only [b₆, map_a₃, map_a₆]
map_simp
@[simp]
lemma map_b₈ : (W.map f).b₈ = f W.b₈ := by
simp only [b₈, map_a₁, map_a₂, map_a₃, map_a₄, map_a₆]
map_simp
@[simp]
lemma map_c₄ : (W.map f).c₄ = f W.c₄ := by
simp only [c₄, map_b₂, map_b₄]
map_simp
@[simp]
lemma map_c₆ : (W.map f).c₆ = f W.c₆ := by
simp only [c₆, map_b₂, map_b₄, map_b₆]
map_simp
@[simp]
lemma map_Δ : (W.map f).Δ = f W.Δ := by
simp only [Δ, map_b₂, map_b₄, map_b₆, map_b₈]
map_simp
@[simp]
lemma map_id : W.map (RingHom.id R) = W :=
rfl
lemma map_map {B : Type w} [CommRing B] (g : A →+* B) : (W.map f).map g = W.map (g.comp f) :=
rfl
@[simp]
lemma map_baseChange {S : Type s} [CommRing S] [Algebra R S] {A : Type v} [CommRing A] [Algebra R A]
[Algebra S A] [IsScalarTower R S A] {B : Type w} [CommRing B] [Algebra R B] [Algebra S B]
[IsScalarTower R S B] (g : A →ₐ[S] B) : (W.baseChange A).map g = W.baseChange B :=
congr_arg W.map <| g.comp_algebraMap_of_tower R
lemma map_injective {f : R →+* A} (hf : Function.Injective f) :
Function.Injective <| map (f := f) := fun _ _ h => by
rcases mk.inj h with ⟨_, _, _, _, _⟩
ext <;> apply_fun _ using hf <;> assumption
end BaseChange
section TorsionPolynomial
/-! ### 2-torsion polynomials -/
/-- A cubic polynomial whose discriminant is a multiple of the Weierstrass curve discriminant. If
`W` is an elliptic curve over a field `R` of characteristic different from 2, then its roots over a
splitting field of `R` are precisely the `X`-coordinates of the non-zero 2-torsion points of `W`. -/
def twoTorsionPolynomial : Cubic R :=
⟨4, W.b₂, 2 * W.b₄, W.b₆⟩
lemma twoTorsionPolynomial_disc : W.twoTorsionPolynomial.disc = 16 * W.Δ := by
simp only [b₂, b₄, b₆, b₈, Δ, twoTorsionPolynomial, Cubic.disc]
ring1
section CharTwo
variable [CharP R 2]
lemma twoTorsionPolynomial_of_char_two : W.twoTorsionPolynomial = ⟨0, W.b₂, 0, W.b₆⟩ := by
rw [twoTorsionPolynomial]
ext <;> dsimp
· linear_combination 2 * CharP.cast_eq_zero R 2
· linear_combination W.b₄ * CharP.cast_eq_zero R 2
lemma twoTorsionPolynomial_disc_of_char_two : W.twoTorsionPolynomial.disc = 0 := by
linear_combination W.twoTorsionPolynomial_disc + 8 * W.Δ * CharP.cast_eq_zero R 2
end CharTwo
section CharThree
variable [CharP R 3]
lemma twoTorsionPolynomial_of_char_three : W.twoTorsionPolynomial = ⟨1, W.b₂, -W.b₄, W.b₆⟩ := by
rw [twoTorsionPolynomial]
ext <;> dsimp
· linear_combination CharP.cast_eq_zero R 3
· linear_combination W.b₄ * CharP.cast_eq_zero R 3
lemma twoTorsionPolynomial_disc_of_char_three : W.twoTorsionPolynomial.disc = W.Δ := by
linear_combination W.twoTorsionPolynomial_disc + 5 * W.Δ * CharP.cast_eq_zero R 3
end CharThree
-- TODO: change to `[IsUnit ...]` once #17458 is merged
lemma twoTorsionPolynomial_disc_isUnit (hu : IsUnit (2 : R)) :
IsUnit W.twoTorsionPolynomial.disc ↔ IsUnit W.Δ := by
rw [twoTorsionPolynomial_disc, IsUnit.mul_iff, show (16 : R) = 2 ^ 4 by norm_num1]
exact and_iff_right <| hu.pow 4
-- TODO: change to `[IsUnit ...]` once #17458 is merged
-- TODO: In this case `IsUnit W.Δ` is just `W.IsElliptic`, consider removing/rephrasing this result
lemma twoTorsionPolynomial_disc_ne_zero [Nontrivial R] (hu : IsUnit (2 : R)) (hΔ : IsUnit W.Δ) :
W.twoTorsionPolynomial.disc ≠ 0 :=
((W.twoTorsionPolynomial_disc_isUnit hu).mpr hΔ).ne_zero
end TorsionPolynomial
/-! ## Elliptic curves -/
-- TODO: change to `protected abbrev IsElliptic := IsUnit W.Δ` once #17458 is merged
/-- `WeierstrassCurve.IsElliptic` is a typeclass which asserts that a Weierstrass curve is an
elliptic curve: that its discriminant is a unit. Note that this definition is only mathematically
accurate for certain rings whose Picard group has trivial 12-torsion, such as a field or a PID. -/
@[mk_iff]
protected class IsElliptic : Prop where
isUnit : IsUnit W.Δ
variable [W.IsElliptic]
lemma isUnit_Δ : IsUnit W.Δ := IsElliptic.isUnit
/-- The discriminant `Δ'` of an elliptic curve over `R`, which is given as a unit in `R`.
Note that to prove two equal elliptic curves have the same `Δ'`, you need to use `simp_rw`,
as `rw` cannot transfer instance `WeierstrassCurve.IsElliptic` automatically. -/
noncomputable def Δ' : Rˣ :=
W.isUnit_Δ.unit
/-- The discriminant `Δ'` of an elliptic curve is equal to the
discriminant `Δ` of it as a Weierstrass curve. -/
@[simp]
lemma coe_Δ' : W.Δ' = W.Δ :=
rfl
/-- The j-invariant `j` of an elliptic curve, which is invariant under isomorphisms over `R`.
Note that to prove two equal elliptic curves have the same `j`, you need to use `simp_rw`,
as `rw` cannot transfer instance `WeierstrassCurve.IsElliptic` automatically. -/
noncomputable def j : R :=
W.Δ'⁻¹ * W.c₄ ^ 3
/-- A variant of `WeierstrassCurve.j_eq_zero_iff` without assuming a reduced ring. -/
lemma j_eq_zero_iff' : W.j = 0 ↔ W.c₄ ^ 3 = 0 := by
rw [j, Units.mul_right_eq_zero]
lemma j_eq_zero (h : W.c₄ = 0) : W.j = 0 := by
rw [j_eq_zero_iff', h, zero_pow three_ne_zero]
lemma j_eq_zero_iff [IsReduced R] : W.j = 0 ↔ W.c₄ = 0 := by
rw [j_eq_zero_iff', IsReduced.pow_eq_zero_iff three_ne_zero]
section CharTwo
variable [CharP R 2]
lemma j_of_char_two : W.j = W.Δ'⁻¹ * W.a₁ ^ 12 := by
rw [j, W.c₄_of_char_two, ← pow_mul]
/-- A variant of `WeierstrassCurve.j_eq_zero_iff_of_char_two` without assuming a reduced ring. -/
lemma j_eq_zero_iff_of_char_two' : W.j = 0 ↔ W.a₁ ^ 12 = 0 := by
rw [j_of_char_two, Units.mul_right_eq_zero]
lemma j_eq_zero_of_char_two (h : W.a₁ = 0) : W.j = 0 := by
rw [j_eq_zero_iff_of_char_two', h, zero_pow (Nat.succ_ne_zero _)]
lemma j_eq_zero_iff_of_char_two [IsReduced R] : W.j = 0 ↔ W.a₁ = 0 := by
rw [j_eq_zero_iff_of_char_two', IsReduced.pow_eq_zero_iff (Nat.succ_ne_zero _)]
end CharTwo
section CharThree
variable [CharP R 3]
lemma j_of_char_three : W.j = W.Δ'⁻¹ * W.b₂ ^ 6 := by
rw [j, W.c₄_of_char_three, ← pow_mul]
/-- A variant of `WeierstrassCurve.j_eq_zero_iff_of_char_three` without assuming a reduced ring. -/
lemma j_eq_zero_iff_of_char_three' : W.j = 0 ↔ W.b₂ ^ 6 = 0 := by
rw [j_of_char_three, Units.mul_right_eq_zero]
lemma j_eq_zero_of_char_three (h : W.b₂ = 0) : W.j = 0 := by
rw [j_eq_zero_iff_of_char_three', h, zero_pow (Nat.succ_ne_zero _)]
lemma j_eq_zero_iff_of_char_three [IsReduced R] : W.j = 0 ↔ W.b₂ = 0 := by
rw [j_eq_zero_iff_of_char_three', IsReduced.pow_eq_zero_iff (Nat.succ_ne_zero _)]
end CharThree
-- TODO: this is defeq to `twoTorsionPolynomial_disc_ne_zero` once #17458 is merged,
-- TODO: consider removing/rephrasing this result
lemma twoTorsionPolynomial_disc_ne_zero_of_isElliptic [Nontrivial R] (hu : IsUnit (2 : R)) :
W.twoTorsionPolynomial.disc ≠ 0 :=
W.twoTorsionPolynomial_disc_ne_zero hu W.isUnit_Δ
section BaseChange
/-! ### Maps and base changes -/
variable {A : Type v} [CommRing A] (f : R →+* A)
instance : (W.map f).IsElliptic := by
simp only [isElliptic_iff, map_Δ, W.isUnit_Δ.map]
set_option linter.docPrime false in
lemma coe_map_Δ' : (W.map f).Δ' = f W.Δ' := by
rw [coe_Δ', map_Δ, coe_Δ']
set_option linter.docPrime false in
@[simp]
lemma map_Δ' : (W.map f).Δ' = Units.map f W.Δ' := by
ext
exact W.coe_map_Δ' f
set_option linter.docPrime false in
lemma coe_inv_map_Δ' : (W.map f).Δ'⁻¹ = f ↑W.Δ'⁻¹ := by
simp
set_option linter.docPrime false in
lemma inv_map_Δ' : (W.map f).Δ'⁻¹ = Units.map f W.Δ'⁻¹ := by
simp
@[simp]
lemma map_j : (W.map f).j = f W.j := by
rw [j, coe_inv_map_Δ', map_c₄, j, map_mul, map_pow]
end BaseChange
end WeierstrassCurve
| Mathlib/AlgebraicGeometry/EllipticCurve/Weierstrass.lean | 670 | 675 | |
/-
Copyright (c) 2024 Raghuram Sundararajan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Raghuram Sundararajan
-/
import Mathlib.Algebra.Ring.Defs
import Mathlib.Algebra.Group.Ext
/-!
# Extensionality lemmas for rings and similar structures
In this file we prove extensionality lemmas for the ring-like structures defined in
`Mathlib/Algebra/Ring/Defs.lean`, ranging from `NonUnitalNonAssocSemiring` to `CommRing`. These
extensionality lemmas take the form of asserting that two algebraic structures on a type are equal
whenever the addition and multiplication defined by them are both the same.
## Implementation details
We follow `Mathlib/Algebra/Group/Ext.lean` in using the term `(letI := i; HMul.hMul : R → R → R)` to
refer to the multiplication specified by a typeclass instance `i` on a type `R` (and similarly for
addition). We abbreviate these using some local notations.
Since `Mathlib/Algebra/Group/Ext.lean` proved several injectivity lemmas, we do so as well — even if
sometimes we don't need them to prove extensionality.
## Tags
semiring, ring, extensionality
-/
local macro:max "local_hAdd[" type:term ", " inst:term "]" : term =>
`(term| (letI := $inst; HAdd.hAdd : $type → $type → $type))
local macro:max "local_hMul[" type:term ", " inst:term "]" : term =>
`(term| (letI := $inst; HMul.hMul : $type → $type → $type))
universe u
variable {R : Type u}
/-! ### Distrib -/
namespace Distrib
@[ext] theorem ext ⦃inst₁ inst₂ : Distrib R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_mul : local_hMul[R, inst₁] = local_hMul[R, inst₂]) :
inst₁ = inst₂ := by
-- Split into `add` and `mul` functions and properties.
rcases inst₁ with @⟨⟨⟩, ⟨⟩⟩
rcases inst₂ with @⟨⟨⟩, ⟨⟩⟩
-- Prove equality of parts using function extensionality.
congr
end Distrib
/-! ### NonUnitalNonAssocSemiring -/
namespace NonUnitalNonAssocSemiring
@[ext] theorem ext ⦃inst₁ inst₂ : NonUnitalNonAssocSemiring R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_mul : local_hMul[R, inst₁] = local_hMul[R, inst₂]) :
inst₁ = inst₂ := by
-- Split into `AddMonoid` instance, `mul` function and properties.
rcases inst₁ with @⟨_, ⟨⟩⟩
rcases inst₂ with @⟨_, ⟨⟩⟩
-- Prove equality of parts using already-proved extensionality lemmas.
congr; ext : 1; assumption
theorem toDistrib_injective : Function.Injective (@toDistrib R) := by
intro _ _ h
ext x y
· exact congrArg (·.toAdd.add x y) h
· exact congrArg (·.toMul.mul x y) h
end NonUnitalNonAssocSemiring
/-! ### NonUnitalSemiring -/
namespace NonUnitalSemiring
theorem toNonUnitalNonAssocSemiring_injective :
Function.Injective (@toNonUnitalNonAssocSemiring R) := by
rintro ⟨⟩ ⟨⟩ _; congr
@[ext] theorem ext ⦃inst₁ inst₂ : NonUnitalSemiring R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_mul : local_hMul[R, inst₁] = local_hMul[R, inst₂]) :
inst₁ = inst₂ :=
toNonUnitalNonAssocSemiring_injective <|
NonUnitalNonAssocSemiring.ext h_add h_mul
end NonUnitalSemiring
/-! ### NonAssocSemiring and its ancestors
This section also includes results for `AddMonoidWithOne`, `AddCommMonoidWithOne`, etc.
as these are considered implementation detail of the ring classes.
TODO consider relocating these lemmas.
-/
/- TODO consider relocating these lemmas. -/
@[ext] theorem AddMonoidWithOne.ext ⦃inst₁ inst₂ : AddMonoidWithOne R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_one : (letI := inst₁; One.one : R) = (letI := inst₂; One.one : R)) :
inst₁ = inst₂ := by
have h_monoid : inst₁.toAddMonoid = inst₂.toAddMonoid := by ext : 1; exact h_add
have h_zero' : inst₁.toZero = inst₂.toZero := congrArg (·.toZero) h_monoid
have h_one' : inst₁.toOne = inst₂.toOne :=
congrArg One.mk h_one
have h_natCast : inst₁.toNatCast.natCast = inst₂.toNatCast.natCast := by
funext n; induction n with
| zero => rewrite [inst₁.natCast_zero, inst₂.natCast_zero]
exact congrArg (@Zero.zero R) h_zero'
| succ n h => rw [inst₁.natCast_succ, inst₂.natCast_succ, h_add]
exact congrArg₂ _ h h_one
rcases inst₁ with @⟨⟨⟩⟩; rcases inst₂ with @⟨⟨⟩⟩
congr
theorem AddCommMonoidWithOne.toAddMonoidWithOne_injective :
Function.Injective (@AddCommMonoidWithOne.toAddMonoidWithOne R) := by
rintro ⟨⟩ ⟨⟩ _; congr
@[ext] theorem AddCommMonoidWithOne.ext ⦃inst₁ inst₂ : AddCommMonoidWithOne R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_one : (letI := inst₁; One.one : R) = (letI := inst₂; One.one : R)) :
inst₁ = inst₂ :=
AddCommMonoidWithOne.toAddMonoidWithOne_injective <|
AddMonoidWithOne.ext h_add h_one
namespace NonAssocSemiring
/- The best place to prove that the `NatCast` is determined by the other operations is probably in
an extensionality lemma for `AddMonoidWithOne`, in which case we may as well do the typeclasses
defined in `Mathlib/Algebra/GroupWithZero/Defs.lean` as well. -/
@[ext] theorem ext ⦃inst₁ inst₂ : NonAssocSemiring R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_mul : local_hMul[R, inst₁] = local_hMul[R, inst₂]) :
inst₁ = inst₂ := by
have h : inst₁.toNonUnitalNonAssocSemiring = inst₂.toNonUnitalNonAssocSemiring := by
ext : 1 <;> assumption
have h_zero : (inst₁.toMulZeroClass).toZero.zero = (inst₂.toMulZeroClass).toZero.zero :=
congrArg (fun inst => (inst.toMulZeroClass).toZero.zero) h
have h_one' : (inst₁.toMulZeroOneClass).toMulOneClass.toOne
= (inst₂.toMulZeroOneClass).toMulOneClass.toOne :=
congrArg (@MulOneClass.toOne R) <| by ext : 1; exact h_mul
have h_one : (inst₁.toMulZeroOneClass).toMulOneClass.toOne.one
= (inst₂.toMulZeroOneClass).toMulOneClass.toOne.one :=
congrArg (@One.one R) h_one'
have : inst₁.toAddCommMonoidWithOne = inst₂.toAddCommMonoidWithOne := by
ext : 1 <;> assumption
have : inst₁.toNatCast = inst₂.toNatCast :=
congrArg (·.toNatCast) this
-- Split into `NonUnitalNonAssocSemiring`, `One` and `natCast` instances.
cases inst₁; cases inst₂
congr
theorem toNonUnitalNonAssocSemiring_injective :
Function.Injective (@toNonUnitalNonAssocSemiring R) := by
intro _ _ _
ext <;> congr
end NonAssocSemiring
/-! ### NonUnitalNonAssocRing -/
namespace NonUnitalNonAssocRing
@[ext] theorem ext ⦃inst₁ inst₂ : NonUnitalNonAssocRing R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_mul : local_hMul[R, inst₁] = local_hMul[R, inst₂]) :
inst₁ = inst₂ := by
-- Split into `AddCommGroup` instance, `mul` function and properties.
rcases inst₁ with @⟨_, ⟨⟩⟩; rcases inst₂ with @⟨_, ⟨⟩⟩
congr; (ext : 1; assumption)
theorem toNonUnitalNonAssocSemiring_injective :
Function.Injective (@toNonUnitalNonAssocSemiring R) := by
intro _ _ h
-- Use above extensionality lemma to prove injectivity by showing that `h_add` and `h_mul` hold.
ext x y
· exact congrArg (·.toAdd.add x y) h
· exact congrArg (·.toMul.mul x y) h
end NonUnitalNonAssocRing
/-! ### NonUnitalRing -/
namespace NonUnitalRing
@[ext] theorem ext ⦃inst₁ inst₂ : NonUnitalRing R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_mul : local_hMul[R, inst₁] = local_hMul[R, inst₂]) :
inst₁ = inst₂ := by
have : inst₁.toNonUnitalNonAssocRing = inst₂.toNonUnitalNonAssocRing := by
ext : 1 <;> assumption
-- Split into fields and prove they are equal using the above.
cases inst₁; cases inst₂
congr
theorem toNonUnitalSemiring_injective :
Function.Injective (@toNonUnitalSemiring R) := by
intro _ _ h
ext x y
· exact congrArg (·.toAdd.add x y) h
· exact congrArg (·.toMul.mul x y) h
theorem toNonUnitalNonAssocring_injective :
Function.Injective (@toNonUnitalNonAssocRing R) := by
intro _ _ _
ext <;> congr
end NonUnitalRing
/-! ### NonAssocRing and its ancestors
This section also includes results for `AddGroupWithOne`, `AddCommGroupWithOne`, etc.
as these are considered implementation detail of the ring classes.
TODO consider relocating these lemmas. -/
@[ext] theorem AddGroupWithOne.ext ⦃inst₁ inst₂ : AddGroupWithOne R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_one : (letI := inst₁; One.one : R) = (letI := inst₂; One.one)) :
inst₁ = inst₂ := by
have : inst₁.toAddMonoidWithOne = inst₂.toAddMonoidWithOne :=
AddMonoidWithOne.ext h_add h_one
have : inst₁.toNatCast = inst₂.toNatCast := congrArg (·.toNatCast) this
have h_group : inst₁.toAddGroup = inst₂.toAddGroup := by ext : 1; exact h_add
-- Extract equality of necessary substructures from h_group
injection h_group with h_group; injection h_group
have : inst₁.toIntCast.intCast = inst₂.toIntCast.intCast := by
funext n; cases n with
| ofNat n => rewrite [Int.ofNat_eq_coe, inst₁.intCast_ofNat, inst₂.intCast_ofNat]; congr
| negSucc n => rewrite [inst₁.intCast_negSucc, inst₂.intCast_negSucc]; congr
rcases inst₁ with @⟨⟨⟩⟩; rcases inst₂ with @⟨⟨⟩⟩
congr
@[ext] theorem AddCommGroupWithOne.ext ⦃inst₁ inst₂ : AddCommGroupWithOne R⦄
(h_add : local_hAdd[R, inst₁] = local_hAdd[R, inst₂])
(h_one : (letI := inst₁; One.one : R) = (letI := inst₂; One.one)) :
inst₁ = inst₂ := by
have : inst₁.toAddCommGroup = inst₂.toAddCommGroup :=
AddCommGroup.ext h_add
| have : inst₁.toAddGroupWithOne = inst₂.toAddGroupWithOne :=
AddGroupWithOne.ext h_add h_one
injection this with _ h_addMonoidWithOne; injection h_addMonoidWithOne
cases inst₁; cases inst₂
congr
| Mathlib/Algebra/Ring/Ext.lean | 236 | 240 |
/-
Copyright (c) 2022 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import Mathlib.Topology.MetricSpace.HausdorffDistance
/-!
# Topological study of spaces `Π (n : ℕ), E n`
When `E n` are topological spaces, the space `Π (n : ℕ), E n` is naturally a topological space
(with the product topology). When `E n` are uniform spaces, it also inherits a uniform structure.
However, it does not inherit a canonical metric space structure of the `E n`. Nevertheless, one
can put a noncanonical metric space structure (or rather, several of them). This is done in this
file.
## Main definitions and results
One can define a combinatorial distance on `Π (n : ℕ), E n`, as follows:
* `PiNat.cylinder x n` is the set of points `y` with `x i = y i` for `i < n`.
* `PiNat.firstDiff x y` is the first index at which `x i ≠ y i`.
* `PiNat.dist x y` is equal to `(1/2) ^ (firstDiff x y)`. It defines a distance
on `Π (n : ℕ), E n`, compatible with the topology when the `E n` have the discrete topology.
* `PiNat.metricSpace`: the metric space structure, given by this distance. Not registered as an
instance. This space is a complete metric space.
* `PiNat.metricSpaceOfDiscreteUniformity`: the same metric space structure, but adjusting the
uniformity defeqness when the `E n` already have the discrete uniformity. Not registered as an
instance
* `PiNat.metricSpaceNatNat`: the particular case of `ℕ → ℕ`, not registered as an instance.
These results are used to construct continuous functions on `Π n, E n`:
* `PiNat.exists_retraction_of_isClosed`: given a nonempty closed subset `s` of `Π (n : ℕ), E n`,
there exists a retraction onto `s`, i.e., a continuous map from the whole space to `s`
restricting to the identity on `s`.
* `exists_nat_nat_continuous_surjective_of_completeSpace`: given any nonempty complete metric
space with second-countable topology, there exists a continuous surjection from `ℕ → ℕ` onto
this space.
One can also put distances on `Π (i : ι), E i` when the spaces `E i` are metric spaces (not discrete
in general), and `ι` is countable.
* `PiCountable.dist` is the distance on `Π i, E i` given by
`dist x y = ∑' i, min (1/2)^(encode i) (dist (x i) (y i))`.
* `PiCountable.metricSpace` is the corresponding metric space structure, adjusted so that
the uniformity is definitionally the product uniformity. Not registered as an instance.
-/
noncomputable section
open Topology TopologicalSpace Set Metric Filter Function
attribute [local simp] pow_le_pow_iff_right₀ one_lt_two inv_le_inv₀ zero_le_two zero_lt_two
variable {E : ℕ → Type*}
namespace PiNat
/-! ### The firstDiff function -/
open Classical in
/-- In a product space `Π n, E n`, then `firstDiff x y` is the first index at which `x` and `y`
differ. If `x = y`, then by convention we set `firstDiff x x = 0`. -/
irreducible_def firstDiff (x y : ∀ n, E n) : ℕ :=
if h : x ≠ y then Nat.find (ne_iff.1 h) else 0
theorem apply_firstDiff_ne {x y : ∀ n, E n} (h : x ≠ y) :
x (firstDiff x y) ≠ y (firstDiff x y) := by
rw [firstDiff_def, dif_pos h]
classical
exact Nat.find_spec (ne_iff.1 h)
theorem apply_eq_of_lt_firstDiff {x y : ∀ n, E n} {n : ℕ} (hn : n < firstDiff x y) : x n = y n := by
rw [firstDiff_def] at hn
split_ifs at hn with h
· convert Nat.find_min (ne_iff.1 h) hn
simp
· exact (not_lt_zero' hn).elim
theorem firstDiff_comm (x y : ∀ n, E n) : firstDiff x y = firstDiff y x := by
classical
simp only [firstDiff_def, ne_comm]
theorem min_firstDiff_le (x y z : ∀ n, E n) (h : x ≠ z) :
min (firstDiff x y) (firstDiff y z) ≤ firstDiff x z := by
by_contra! H
rw [lt_min_iff] at H
refine apply_firstDiff_ne h ?_
calc
x (firstDiff x z) = y (firstDiff x z) := apply_eq_of_lt_firstDiff H.1
_ = z (firstDiff x z) := apply_eq_of_lt_firstDiff H.2
/-! ### Cylinders -/
/-- In a product space `Π n, E n`, the cylinder set of length `n` around `x`, denoted
`cylinder x n`, is the set of sequences `y` that coincide with `x` on the first `n` symbols, i.e.,
such that `y i = x i` for all `i < n`.
-/
def cylinder (x : ∀ n, E n) (n : ℕ) : Set (∀ n, E n) :=
{ y | ∀ i, i < n → y i = x i }
theorem cylinder_eq_pi (x : ∀ n, E n) (n : ℕ) :
cylinder x n = Set.pi (Finset.range n : Set ℕ) fun i : ℕ => {x i} := by
ext y
simp [cylinder]
@[simp]
theorem cylinder_zero (x : ∀ n, E n) : cylinder x 0 = univ := by simp [cylinder_eq_pi]
theorem cylinder_anti (x : ∀ n, E n) {m n : ℕ} (h : m ≤ n) : cylinder x n ⊆ cylinder x m :=
fun _y hy i hi => hy i (hi.trans_le h)
@[simp]
theorem mem_cylinder_iff {x y : ∀ n, E n} {n : ℕ} : y ∈ cylinder x n ↔ ∀ i < n, y i = x i :=
Iff.rfl
theorem self_mem_cylinder (x : ∀ n, E n) (n : ℕ) : x ∈ cylinder x n := by simp
theorem mem_cylinder_iff_eq {x y : ∀ n, E n} {n : ℕ} :
y ∈ cylinder x n ↔ cylinder y n = cylinder x n := by
constructor
· intro hy
apply Subset.antisymm
· intro z hz i hi
rw [← hy i hi]
exact hz i hi
· intro z hz i hi
rw [hy i hi]
exact hz i hi
· intro h
rw [← h]
exact self_mem_cylinder _ _
theorem mem_cylinder_comm (x y : ∀ n, E n) (n : ℕ) : y ∈ cylinder x n ↔ x ∈ cylinder y n := by
simp [mem_cylinder_iff_eq, eq_comm]
theorem mem_cylinder_iff_le_firstDiff {x y : ∀ n, E n} (hne : x ≠ y) (i : ℕ) :
x ∈ cylinder y i ↔ i ≤ firstDiff x y := by
constructor
· intro h
by_contra!
exact apply_firstDiff_ne hne (h _ this)
· intro hi j hj
exact apply_eq_of_lt_firstDiff (hj.trans_le hi)
theorem mem_cylinder_firstDiff (x y : ∀ n, E n) : x ∈ cylinder y (firstDiff x y) := fun _i hi =>
apply_eq_of_lt_firstDiff hi
theorem cylinder_eq_cylinder_of_le_firstDiff (x y : ∀ n, E n) {n : ℕ} (hn : n ≤ firstDiff x y) :
cylinder x n = cylinder y n := by
rw [← mem_cylinder_iff_eq]
intro i hi
exact apply_eq_of_lt_firstDiff (hi.trans_le hn)
theorem iUnion_cylinder_update (x : ∀ n, E n) (n : ℕ) :
⋃ k, cylinder (update x n k) (n + 1) = cylinder x n := by
ext y
simp only [mem_cylinder_iff, mem_iUnion]
constructor
· rintro ⟨k, hk⟩ i hi
simpa [hi.ne] using hk i (Nat.lt_succ_of_lt hi)
· intro H
refine ⟨y n, fun i hi => ?_⟩
rcases Nat.lt_succ_iff_lt_or_eq.1 hi with (h'i | rfl)
· simp [H i h'i, h'i.ne]
· simp
theorem update_mem_cylinder (x : ∀ n, E n) (n : ℕ) (y : E n) : update x n y ∈ cylinder x n :=
mem_cylinder_iff.2 fun i hi => by simp [hi.ne]
section Res
variable {α : Type*}
open List
/-- In the case where `E` has constant value `α`,
the cylinder `cylinder x n` can be identified with the element of `List α`
consisting of the first `n` entries of `x`. See `cylinder_eq_res`.
We call this list `res x n`, the restriction of `x` to `n`. -/
def res (x : ℕ → α) : ℕ → List α
| 0 => nil
| Nat.succ n => x n :: res x n
@[simp]
theorem res_zero (x : ℕ → α) : res x 0 = @nil α :=
rfl
@[simp]
theorem res_succ (x : ℕ → α) (n : ℕ) : res x n.succ = x n :: res x n :=
rfl
@[simp]
theorem res_length (x : ℕ → α) (n : ℕ) : (res x n).length = n := by induction n <;> simp [*]
/-- The restrictions of `x` and `y` to `n` are equal if and only if `x m = y m` for all `m < n`. -/
theorem res_eq_res {x y : ℕ → α} {n : ℕ} :
res x n = res y n ↔ ∀ ⦃m⦄, m < n → x m = y m := by
constructor <;> intro h
· induction n with
| zero => simp
| succ n ih =>
intro m hm
rw [Nat.lt_succ_iff_lt_or_eq] at hm
simp only [res_succ, cons.injEq] at h
rcases hm with hm | hm
· exact ih h.2 hm
rw [hm]
exact h.1
· induction n with
| zero => simp
| succ n ih =>
simp only [res_succ, cons.injEq]
refine ⟨h (Nat.lt_succ_self _), ih fun m hm => ?_⟩
exact h (hm.trans (Nat.lt_succ_self _))
theorem res_injective : Injective (@res α) := by
intro x y h
ext n
apply res_eq_res.mp _ (Nat.lt_succ_self _)
rw [h]
/-- `cylinder x n` is equal to the set of sequences `y` with the same restriction to `n` as `x`. -/
theorem cylinder_eq_res (x : ℕ → α) (n : ℕ) :
cylinder x n = { y | res y n = res x n } := by
ext y
dsimp [cylinder]
rw [res_eq_res]
end Res
/-!
### A distance function on `Π n, E n`
We define a distance function on `Π n, E n`, given by `dist x y = (1/2)^n` where `n` is the first
index at which `x` and `y` differ. When each `E n` has the discrete topology, this distance will
define the right topology on the product space. We do not record a global `Dist` instance nor
a `MetricSpace` instance, as other distances may be used on these spaces, but we register them as
local instances in this section.
-/
open Classical in
/-- The distance function on a product space `Π n, E n`, given by `dist x y = (1/2)^n` where `n` is
the first index at which `x` and `y` differ. -/
protected def dist : Dist (∀ n, E n) :=
⟨fun x y => if x ≠ y then (1 / 2 : ℝ) ^ firstDiff x y else 0⟩
attribute [local instance] PiNat.dist
theorem dist_eq_of_ne {x y : ∀ n, E n} (h : x ≠ y) : dist x y = (1 / 2 : ℝ) ^ firstDiff x y := by
simp [dist, h]
protected theorem dist_self (x : ∀ n, E n) : dist x x = 0 := by simp [dist]
protected theorem dist_comm (x y : ∀ n, E n) : dist x y = dist y x := by
classical
simp [dist, @eq_comm _ x y, firstDiff_comm]
protected theorem dist_nonneg (x y : ∀ n, E n) : 0 ≤ dist x y := by
rcases eq_or_ne x y with (rfl | h)
· simp [dist]
· simp [dist, h, zero_le_two]
theorem dist_triangle_nonarch (x y z : ∀ n, E n) : dist x z ≤ max (dist x y) (dist y z) := by
rcases eq_or_ne x z with (rfl | hxz)
· simp [PiNat.dist_self x, PiNat.dist_nonneg]
rcases eq_or_ne x y with (rfl | hxy)
· simp
rcases eq_or_ne y z with (rfl | hyz)
· simp
simp only [dist_eq_of_ne, hxz, hxy, hyz, inv_le_inv₀, one_div, inv_pow, zero_lt_two, Ne,
not_false_iff, le_max_iff, pow_le_pow_iff_right₀, one_lt_two, pow_pos,
min_le_iff.1 (min_firstDiff_le x y z hxz)]
protected theorem dist_triangle (x y z : ∀ n, E n) : dist x z ≤ dist x y + dist y z :=
calc
dist x z ≤ max (dist x y) (dist y z) := dist_triangle_nonarch x y z
_ ≤ dist x y + dist y z := max_le_add_of_nonneg (PiNat.dist_nonneg _ _) (PiNat.dist_nonneg _ _)
protected theorem eq_of_dist_eq_zero (x y : ∀ n, E n) (hxy : dist x y = 0) : x = y := by
rcases eq_or_ne x y with (rfl | h); · rfl
simp [dist_eq_of_ne h] at hxy
theorem mem_cylinder_iff_dist_le {x y : ∀ n, E n} {n : ℕ} :
y ∈ cylinder x n ↔ dist y x ≤ (1 / 2) ^ n := by
rcases eq_or_ne y x with (rfl | hne)
· simp [PiNat.dist_self]
suffices (∀ i : ℕ, i < n → y i = x i) ↔ n ≤ firstDiff y x by simpa [dist_eq_of_ne hne]
constructor
· intro hy
by_contra! H
exact apply_firstDiff_ne hne (hy _ H)
· intro h i hi
exact apply_eq_of_lt_firstDiff (hi.trans_le h)
theorem apply_eq_of_dist_lt {x y : ∀ n, E n} {n : ℕ} (h : dist x y < (1 / 2) ^ n) {i : ℕ}
(hi : i ≤ n) : x i = y i := by
rcases eq_or_ne x y with (rfl | hne)
· rfl
have : n < firstDiff x y := by
simpa [dist_eq_of_ne hne, inv_lt_inv₀, pow_lt_pow_iff_right₀, one_lt_two] using h
exact apply_eq_of_lt_firstDiff (hi.trans_lt this)
/-- A function to a pseudo-metric-space is `1`-Lipschitz if and only if points in the same cylinder
of length `n` are sent to points within distance `(1/2)^n`.
Not expressed using `LipschitzWith` as we don't have a metric space structure -/
theorem lipschitz_with_one_iff_forall_dist_image_le_of_mem_cylinder {α : Type*}
[PseudoMetricSpace α] {f : (∀ n, E n) → α} :
(∀ x y : ∀ n, E n, dist (f x) (f y) ≤ dist x y) ↔
∀ x y n, y ∈ cylinder x n → dist (f x) (f y) ≤ (1 / 2) ^ n := by
constructor
· intro H x y n hxy
apply (H x y).trans
rw [PiNat.dist_comm]
exact mem_cylinder_iff_dist_le.1 hxy
· intro H x y
rcases eq_or_ne x y with (rfl | hne)
· simp [PiNat.dist_nonneg]
rw [dist_eq_of_ne hne]
apply H x y (firstDiff x y)
rw [firstDiff_comm]
exact mem_cylinder_firstDiff _ _
variable (E)
variable [∀ n, TopologicalSpace (E n)] [∀ n, DiscreteTopology (E n)]
theorem isOpen_cylinder (x : ∀ n, E n) (n : ℕ) : IsOpen (cylinder x n) := by
rw [PiNat.cylinder_eq_pi]
exact isOpen_set_pi (Finset.range n).finite_toSet fun a _ => isOpen_discrete _
theorem isTopologicalBasis_cylinders :
IsTopologicalBasis { s : Set (∀ n, E n) | ∃ (x : ∀ n, E n) (n : ℕ), s = cylinder x n } := by
apply isTopologicalBasis_of_isOpen_of_nhds
· rintro u ⟨x, n, rfl⟩
apply isOpen_cylinder
· intro x u hx u_open
obtain ⟨v, ⟨U, F, -, rfl⟩, xU, Uu⟩ :
∃ v ∈ { S : Set (∀ i : ℕ, E i) | ∃ (U : ∀ i : ℕ, Set (E i)) (F : Finset ℕ),
(∀ i : ℕ, i ∈ F → U i ∈ { s : Set (E i) | IsOpen s }) ∧ S = (F : Set ℕ).pi U },
x ∈ v ∧ v ⊆ u :=
(isTopologicalBasis_pi fun n : ℕ => isTopologicalBasis_opens).exists_subset_of_mem_open hx
u_open
rcases Finset.bddAbove F with ⟨n, hn⟩
refine ⟨cylinder x (n + 1), ⟨x, n + 1, rfl⟩, self_mem_cylinder _ _, Subset.trans ?_ Uu⟩
intro y hy
suffices ∀ i : ℕ, i ∈ F → y i ∈ U i by simpa
intro i hi
have : y i = x i := mem_cylinder_iff.1 hy i ((hn hi).trans_lt (lt_add_one n))
rw [this]
simp only [Set.mem_pi, Finset.mem_coe] at xU
exact xU i hi
variable {E}
theorem isOpen_iff_dist (s : Set (∀ n, E n)) :
IsOpen s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s := by
constructor
· intro hs x hx
obtain ⟨v, ⟨y, n, rfl⟩, h'x, h's⟩ :
∃ v ∈ { s | ∃ (x : ∀ n : ℕ, E n) (n : ℕ), s = cylinder x n }, x ∈ v ∧ v ⊆ s :=
(isTopologicalBasis_cylinders E).exists_subset_of_mem_open hx hs
rw [← mem_cylinder_iff_eq.1 h'x] at h's
exact
⟨(1 / 2 : ℝ) ^ n, by simp, fun y hy => h's fun i hi => (apply_eq_of_dist_lt hy hi.le).symm⟩
· intro h
refine (isTopologicalBasis_cylinders E).isOpen_iff.2 fun x hx => ?_
rcases h x hx with ⟨ε, εpos, hε⟩
obtain ⟨n, hn⟩ : ∃ n : ℕ, (1 / 2 : ℝ) ^ n < ε := exists_pow_lt_of_lt_one εpos one_half_lt_one
refine ⟨cylinder x n, ⟨x, n, rfl⟩, self_mem_cylinder x n, fun y hy => hε y ?_⟩
rw [PiNat.dist_comm]
exact (mem_cylinder_iff_dist_le.1 hy).trans_lt hn
/-- Metric space structure on `Π (n : ℕ), E n` when the spaces `E n` have the discrete topology,
where the distance is given by `dist x y = (1/2)^n`, where `n` is the smallest index where `x` and
`y` differ. Not registered as a global instance by default.
Warning: this definition makes sure that the topology is defeq to the original product topology,
but it does not take care of a possible uniformity. If the `E n` have a uniform structure, then
there will be two non-defeq uniform structures on `Π n, E n`, the product one and the one coming
from the metric structure. In this case, use `metricSpaceOfDiscreteUniformity` instead. -/
protected def metricSpace : MetricSpace (∀ n, E n) :=
MetricSpace.ofDistTopology dist PiNat.dist_self PiNat.dist_comm PiNat.dist_triangle
isOpen_iff_dist PiNat.eq_of_dist_eq_zero
/-- Metric space structure on `Π (n : ℕ), E n` when the spaces `E n` have the discrete uniformity,
where the distance is given by `dist x y = (1/2)^n`, where `n` is the smallest index where `x` and
`y` differ. Not registered as a global instance by default. -/
protected def metricSpaceOfDiscreteUniformity {E : ℕ → Type*} [∀ n, UniformSpace (E n)]
(h : ∀ n, uniformity (E n) = 𝓟 idRel) : MetricSpace (∀ n, E n) :=
haveI : ∀ n, DiscreteTopology (E n) := fun n => discreteTopology_of_discrete_uniformity (h n)
{ dist_triangle := PiNat.dist_triangle
dist_comm := PiNat.dist_comm
dist_self := PiNat.dist_self
eq_of_dist_eq_zero := PiNat.eq_of_dist_eq_zero _ _
toUniformSpace := Pi.uniformSpace _
uniformity_dist := by
simp only [Pi.uniformity, h, idRel, comap_principal, preimage_setOf_eq]
apply le_antisymm
· simp only [le_iInf_iff, le_principal_iff]
intro ε εpos
obtain ⟨n, hn⟩ : ∃ n, (1 / 2 : ℝ) ^ n < ε := exists_pow_lt_of_lt_one εpos (by norm_num)
apply
@mem_iInf_of_iInter _ _ _ _ _ (Finset.range n).finite_toSet fun i =>
{ p : (∀ n : ℕ, E n) × ∀ n : ℕ, E n | p.fst i = p.snd i }
· simp only [mem_principal, setOf_subset_setOf, imp_self, imp_true_iff]
· rintro ⟨x, y⟩ hxy
simp only [Finset.mem_coe, Finset.mem_range, iInter_coe_set, mem_iInter, mem_setOf_eq]
at hxy
apply lt_of_le_of_lt _ hn
rw [← mem_cylinder_iff_dist_le, mem_cylinder_iff]
exact hxy
· simp only [le_iInf_iff, le_principal_iff]
intro n
refine mem_iInf_of_mem ((1 / 2) ^ n : ℝ) ?_
refine mem_iInf_of_mem (by positivity) ?_
simp only [mem_principal, setOf_subset_setOf, Prod.forall]
intro x y hxy
exact apply_eq_of_dist_lt hxy le_rfl }
/-- Metric space structure on `ℕ → ℕ` where the distance is given by `dist x y = (1/2)^n`,
where `n` is the smallest index where `x` and `y` differ.
Not registered as a global instance by default. -/
def metricSpaceNatNat : MetricSpace (ℕ → ℕ) :=
PiNat.metricSpaceOfDiscreteUniformity fun _ => rfl
attribute [local instance] PiNat.metricSpace
protected theorem completeSpace : CompleteSpace (∀ n, E n) := by
refine Metric.complete_of_convergent_controlled_sequences (fun n => (1 / 2) ^ n) (by simp) ?_
intro u hu
refine ⟨fun n => u n n, tendsto_pi_nhds.2 fun i => ?_⟩
refine tendsto_const_nhds.congr' ?_
filter_upwards [Filter.Ici_mem_atTop i] with n hn
exact apply_eq_of_dist_lt (hu i i n le_rfl hn) le_rfl
/-!
### Retractions inside product spaces
We show that, in a space `Π (n : ℕ), E n` where each `E n` is discrete, there is a retraction on
any closed nonempty subset `s`, i.e., a continuous map `f` from the whole space to `s` restricting
to the identity on `s`. The map `f` is defined as follows. For `x ∈ s`, let `f x = x`. Otherwise,
consider the longest prefix `w` that `x` shares with an element of `s`, and let `f x = z_w`
where `z_w` is an element of `s` starting with `w`.
-/
theorem exists_disjoint_cylinder {s : Set (∀ n, E n)} (hs : IsClosed s) {x : ∀ n, E n}
(hx : x ∉ s) : ∃ n, Disjoint s (cylinder x n) := by
rcases eq_empty_or_nonempty s with (rfl | hne)
· exact ⟨0, by simp⟩
have A : 0 < infDist x s := (hs.not_mem_iff_infDist_pos hne).1 hx
obtain ⟨n, hn⟩ : ∃ n, (1 / 2 : ℝ) ^ n < infDist x s := exists_pow_lt_of_lt_one A one_half_lt_one
refine ⟨n, disjoint_left.2 fun y ys hy => ?_⟩
apply lt_irrefl (infDist x s)
calc
infDist x s ≤ dist x y := infDist_le_dist_of_mem ys
_ ≤ (1 / 2) ^ n := by
rw [mem_cylinder_comm] at hy
exact mem_cylinder_iff_dist_le.1 hy
_ < infDist x s := hn
open Classical in
/-- Given a point `x` in a product space `Π (n : ℕ), E n`, and `s` a subset of this space, then
`shortestPrefixDiff x s` if the smallest `n` for which there is no element of `s` having the same
prefix of length `n` as `x`. If there is no such `n`, then use `0` by convention. -/
def shortestPrefixDiff {E : ℕ → Type*} (x : ∀ n, E n) (s : Set (∀ n, E n)) : ℕ :=
if h : ∃ n, Disjoint s (cylinder x n) then Nat.find h else 0
theorem firstDiff_lt_shortestPrefixDiff {s : Set (∀ n, E n)} (hs : IsClosed s) {x y : ∀ n, E n}
(hx : x ∉ s) (hy : y ∈ s) : firstDiff x y < shortestPrefixDiff x s := by
have A := exists_disjoint_cylinder hs hx
rw [shortestPrefixDiff, dif_pos A]
classical
have B := Nat.find_spec A
contrapose! B
rw [not_disjoint_iff_nonempty_inter]
refine ⟨y, hy, ?_⟩
rw [mem_cylinder_comm]
exact cylinder_anti y B (mem_cylinder_firstDiff x y)
theorem shortestPrefixDiff_pos {s : Set (∀ n, E n)} (hs : IsClosed s) (hne : s.Nonempty)
{x : ∀ n, E n} (hx : x ∉ s) : 0 < shortestPrefixDiff x s := by
rcases hne with ⟨y, hy⟩
exact (zero_le _).trans_lt (firstDiff_lt_shortestPrefixDiff hs hx hy)
/-- Given a point `x` in a product space `Π (n : ℕ), E n`, and `s` a subset of this space, then
`longestPrefix x s` if the largest `n` for which there is an element of `s` having the same
prefix of length `n` as `x`. If there is no such `n`, use `0` by convention. -/
def longestPrefix {E : ℕ → Type*} (x : ∀ n, E n) (s : Set (∀ n, E n)) : ℕ :=
shortestPrefixDiff x s - 1
theorem firstDiff_le_longestPrefix {s : Set (∀ n, E n)} (hs : IsClosed s) {x y : ∀ n, E n}
(hx : x ∉ s) (hy : y ∈ s) : firstDiff x y ≤ longestPrefix x s := by
rw [longestPrefix, le_tsub_iff_right]
· exact firstDiff_lt_shortestPrefixDiff hs hx hy
· exact shortestPrefixDiff_pos hs ⟨y, hy⟩ hx
theorem inter_cylinder_longestPrefix_nonempty {s : Set (∀ n, E n)} (hs : IsClosed s)
(hne : s.Nonempty) (x : ∀ n, E n) : (s ∩ cylinder x (longestPrefix x s)).Nonempty := by
by_cases hx : x ∈ s
· exact ⟨x, hx, self_mem_cylinder _ _⟩
have A := exists_disjoint_cylinder hs hx
have B : longestPrefix x s < shortestPrefixDiff x s :=
Nat.pred_lt (shortestPrefixDiff_pos hs hne hx).ne'
rw [longestPrefix, shortestPrefixDiff, dif_pos A] at B ⊢
classical
obtain ⟨y, ys, hy⟩ : ∃ y : ∀ n : ℕ, E n, y ∈ s ∧ x ∈ cylinder y (Nat.find A - 1) := by
simpa only [not_disjoint_iff, mem_cylinder_comm] using Nat.find_min A B
refine ⟨y, ys, ?_⟩
rw [mem_cylinder_iff_eq] at hy ⊢
rw [hy]
theorem disjoint_cylinder_of_longestPrefix_lt {s : Set (∀ n, E n)} (hs : IsClosed s) {x : ∀ n, E n}
(hx : x ∉ s) {n : ℕ} (hn : longestPrefix x s < n) : Disjoint s (cylinder x n) := by
contrapose! hn
rcases not_disjoint_iff_nonempty_inter.1 hn with ⟨y, ys, hy⟩
apply le_trans _ (firstDiff_le_longestPrefix hs hx ys)
apply (mem_cylinder_iff_le_firstDiff (ne_of_mem_of_not_mem ys hx).symm _).1
rwa [mem_cylinder_comm]
/-- If two points `x, y` coincide up to length `n`, and the longest common prefix of `x` with `s`
is strictly shorter than `n`, then the longest common prefix of `y` with `s` is the same, and both
cylinders of this length based at `x` and `y` coincide. -/
theorem cylinder_longestPrefix_eq_of_longestPrefix_lt_firstDiff {x y : ∀ n, E n}
{s : Set (∀ n, E n)} (hs : IsClosed s) (hne : s.Nonempty)
(H : longestPrefix x s < firstDiff x y) (xs : x ∉ s) (ys : y ∉ s) :
cylinder x (longestPrefix x s) = cylinder y (longestPrefix y s) := by
have l_eq : longestPrefix y s = longestPrefix x s := by
rcases lt_trichotomy (longestPrefix y s) (longestPrefix x s) with (L | L | L)
· have Ax : (s ∩ cylinder x (longestPrefix x s)).Nonempty :=
inter_cylinder_longestPrefix_nonempty hs hne x
have Z := disjoint_cylinder_of_longestPrefix_lt hs ys L
rw [firstDiff_comm] at H
rw [cylinder_eq_cylinder_of_le_firstDiff _ _ H.le] at Z
exact (Ax.not_disjoint Z).elim
| · exact L
· have Ay : (s ∩ cylinder y (longestPrefix y s)).Nonempty :=
inter_cylinder_longestPrefix_nonempty hs hne y
have A'y : (s ∩ cylinder y (longestPrefix x s).succ).Nonempty :=
Ay.mono (inter_subset_inter_right s (cylinder_anti _ L))
| Mathlib/Topology/MetricSpace/PiNat.lean | 535 | 539 |
/-
Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import Mathlib.Algebra.Order.Group.Unbundled.Int
import Mathlib.Algebra.Order.Nonneg.Basic
import Mathlib.Algebra.Order.Ring.Unbundled.Rat
import Mathlib.Algebra.Ring.Rat
import Mathlib.Data.Set.Operations
import Mathlib.Order.Bounds.Defs
import Mathlib.Order.GaloisConnection.Defs
/-!
# Nonnegative rationals
This file defines the nonnegative rationals as a subtype of `Rat` and provides its basic algebraic
order structure.
Note that `NNRat` is not declared as a `Semifield` here. See `Mathlib.Algebra.Field.Rat` for that
instance.
We also define an instance `CanLift ℚ ℚ≥0`. This instance can be used by the `lift` tactic to
replace `x : ℚ` and `hx : 0 ≤ x` in the proof context with `x : ℚ≥0` while replacing all occurrences
of `x` with `↑x`. This tactic also works for a function `f : α → ℚ` with a hypothesis
`hf : ∀ x, 0 ≤ f x`.
## Notation
`ℚ≥0` is notation for `NNRat` in locale `NNRat`.
## Huge warning
Whenever you state a lemma about the coercion `ℚ≥0 → ℚ`, check that Lean inserts `NNRat.cast`, not
`Subtype.val`. Else your lemma will never apply.
-/
assert_not_exists CompleteLattice OrderedCommMonoid
library_note "specialised high priority simp lemma" /--
It sometimes happens that a `@[simp]` lemma declared early in the library can be proved by `simp`
using later, more general simp lemmas. In that case, the following reasons might be arguments for
the early lemma to be tagged `@[simp high]` (rather than `@[simp, nolint simpNF]` or
un``@[simp]``ed):
1. There is a significant portion of the library which needs the early lemma to be available via
`simp` and which doesn't have access to the more general lemmas.
2. The more general lemmas have more complicated typeclass assumptions, causing rewrites with them
to be slower.
-/
open Function
instance Rat.instZeroLEOneClass : ZeroLEOneClass ℚ where
zero_le_one := rfl
instance Rat.instPosMulMono : PosMulMono ℚ where
elim := fun r p q h => by
simp only [mul_comm]
simpa [sub_mul, sub_nonneg] using Rat.mul_nonneg (sub_nonneg.2 h) r.2
deriving instance CommSemiring for NNRat
deriving instance LinearOrder for NNRat
deriving instance Sub for NNRat
deriving instance Inhabited for NNRat
namespace NNRat
variable {p q : ℚ≥0}
instance instNontrivial : Nontrivial ℚ≥0 where exists_pair_ne := ⟨1, 0, by decide⟩
instance instOrderBot : OrderBot ℚ≥0 where
bot := 0
bot_le q := q.2
@[simp] lemma val_eq_cast (q : ℚ≥0) : q.1 = q := rfl
instance instCharZero : CharZero ℚ≥0 where
cast_injective a b hab := by simpa using congr_arg num hab
instance canLift : CanLift ℚ ℚ≥0 (↑) fun q ↦ 0 ≤ q where
prf q hq := ⟨⟨q, hq⟩, rfl⟩
@[ext]
theorem ext : (p : ℚ) = (q : ℚ) → p = q :=
Subtype.ext
protected theorem coe_injective : Injective ((↑) : ℚ≥0 → ℚ) :=
Subtype.coe_injective
-- See note [specialised high priority simp lemma]
@[simp high, norm_cast]
theorem coe_inj : (p : ℚ) = q ↔ p = q :=
Subtype.coe_inj
theorem ne_iff {x y : ℚ≥0} : (x : ℚ) ≠ (y : ℚ) ↔ x ≠ y :=
NNRat.coe_inj.not
-- TODO: We have to write `NNRat.cast` explicitly, else the statement picks up `Subtype.val` instead
@[simp, norm_cast] lemma coe_mk (q : ℚ) (hq) : NNRat.cast ⟨q, hq⟩ = q := rfl
lemma «forall» {p : ℚ≥0 → Prop} : (∀ q, p q) ↔ ∀ q hq, p ⟨q, hq⟩ := Subtype.forall
lemma «exists» {p : ℚ≥0 → Prop} : (∃ q, p q) ↔ ∃ q hq, p ⟨q, hq⟩ := Subtype.exists
/-- Reinterpret a rational number `q` as a non-negative rational number. Returns `0` if `q ≤ 0`. -/
def _root_.Rat.toNNRat (q : ℚ) : ℚ≥0 :=
⟨max q 0, le_max_right _ _⟩
theorem _root_.Rat.coe_toNNRat (q : ℚ) (hq : 0 ≤ q) : (q.toNNRat : ℚ) = q :=
max_eq_left hq
theorem _root_.Rat.le_coe_toNNRat (q : ℚ) : q ≤ q.toNNRat :=
le_max_left _ _
open Rat (toNNRat)
@[simp]
theorem coe_nonneg (q : ℚ≥0) : (0 : ℚ) ≤ q :=
q.2
@[simp, norm_cast] lemma coe_zero : ((0 : ℚ≥0) : ℚ) = 0 := rfl
@[simp] lemma num_zero : num 0 = 0 := rfl
@[simp] lemma den_zero : den 0 = 1 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : ℚ≥0) : ℚ) = 1 := rfl
@[simp] lemma num_one : num 1 = 1 := rfl
@[simp] lemma den_one : den 1 = 1 := rfl
@[simp, norm_cast]
theorem coe_add (p q : ℚ≥0) : ((p + q : ℚ≥0) : ℚ) = p + q :=
rfl
@[simp, norm_cast]
theorem coe_mul (p q : ℚ≥0) : ((p * q : ℚ≥0) : ℚ) = p * q :=
rfl
@[simp, norm_cast] lemma coe_pow (q : ℚ≥0) (n : ℕ) : (↑(q ^ n) : ℚ) = (q : ℚ) ^ n :=
rfl
@[simp] lemma num_pow (q : ℚ≥0) (n : ℕ) : (q ^ n).num = q.num ^ n := by simp [num, Int.natAbs_pow]
@[simp] lemma den_pow (q : ℚ≥0) (n : ℕ) : (q ^ n).den = q.den ^ n := rfl
@[simp, norm_cast]
theorem coe_sub (h : q ≤ p) : ((p - q : ℚ≥0) : ℚ) = p - q :=
max_eq_left <| le_sub_comm.2 <| by rwa [sub_zero]
-- See note [specialised high priority simp lemma]
@[simp high]
theorem coe_eq_zero : (q : ℚ) = 0 ↔ q = 0 := by norm_cast
theorem coe_ne_zero : (q : ℚ) ≠ 0 ↔ q ≠ 0 :=
coe_eq_zero.not
@[norm_cast]
theorem coe_le_coe : (p : ℚ) ≤ q ↔ p ≤ q :=
Iff.rfl
@[norm_cast]
theorem coe_lt_coe : (p : ℚ) < q ↔ p < q :=
Iff.rfl
@[norm_cast]
theorem coe_pos : (0 : ℚ) < q ↔ 0 < q :=
Iff.rfl
theorem coe_mono : Monotone ((↑) : ℚ≥0 → ℚ) :=
fun _ _ ↦ coe_le_coe.2
theorem toNNRat_mono : Monotone toNNRat :=
fun _ _ h ↦ max_le_max h le_rfl
@[simp]
theorem toNNRat_coe (q : ℚ≥0) : toNNRat q = q :=
ext <| max_eq_left q.2
@[simp]
theorem toNNRat_coe_nat (n : ℕ) : toNNRat n = n :=
ext <| by simp only [Nat.cast_nonneg', Rat.coe_toNNRat]; rfl
/-- `toNNRat` and `(↑) : ℚ≥0 → ℚ` form a Galois insertion. -/
protected def gi : GaloisInsertion toNNRat (↑) :=
GaloisInsertion.monotoneIntro coe_mono toNNRat_mono Rat.le_coe_toNNRat toNNRat_coe
/-- Coercion `ℚ≥0 → ℚ` as a `RingHom`. -/
def coeHom : ℚ≥0 →+* ℚ where
toFun := (↑)
map_one' := coe_one
map_mul' := coe_mul
map_zero' := coe_zero
map_add' := coe_add
@[simp, norm_cast] lemma coe_natCast (n : ℕ) : (↑(↑n : ℚ≥0) : ℚ) = n := rfl
@[simp]
theorem mk_natCast (n : ℕ) : @Eq ℚ≥0 (⟨(n : ℚ), Nat.cast_nonneg' n⟩ : ℚ≥0) n :=
rfl
@[simp]
theorem coe_coeHom : ⇑coeHom = ((↑) : ℚ≥0 → ℚ) :=
rfl
@[norm_cast]
theorem nsmul_coe (q : ℚ≥0) (n : ℕ) : ↑(n • q) = n • (q : ℚ) :=
coeHom.toAddMonoidHom.map_nsmul _ _
theorem bddAbove_coe {s : Set ℚ≥0} : BddAbove ((↑) '' s : Set ℚ) ↔ BddAbove s :=
⟨fun ⟨b, hb⟩ ↦
⟨toNNRat b, fun ⟨y, _⟩ hys ↦
show y ≤ max b 0 from (hb <| Set.mem_image_of_mem _ hys).trans <| le_max_left _ _⟩,
fun ⟨b, hb⟩ ↦ ⟨b, fun _ ⟨_, hx, Eq⟩ ↦ Eq ▸ hb hx⟩⟩
theorem bddBelow_coe (s : Set ℚ≥0) : BddBelow (((↑) : ℚ≥0 → ℚ) '' s) :=
⟨0, fun _ ⟨q, _, h⟩ ↦ h ▸ q.2⟩
@[norm_cast]
theorem coe_max (x y : ℚ≥0) : ((max x y : ℚ≥0) : ℚ) = max (x : ℚ) (y : ℚ) :=
coe_mono.map_max
@[norm_cast]
theorem coe_min (x y : ℚ≥0) : ((min x y : ℚ≥0) : ℚ) = min (x : ℚ) (y : ℚ) :=
coe_mono.map_min
theorem sub_def (p q : ℚ≥0) : p - q = toNNRat (p - q) :=
rfl
@[simp]
theorem abs_coe (q : ℚ≥0) : |(q : ℚ)| = q :=
abs_of_nonneg q.2
-- See note [specialised high priority simp lemma]
@[simp high]
theorem nonpos_iff_eq_zero (q : ℚ≥0) : q ≤ 0 ↔ q = 0 :=
⟨fun h => le_antisymm h q.2, fun h => h.symm ▸ q.2⟩
end NNRat
open NNRat
namespace Rat
variable {p q : ℚ}
@[simp]
theorem toNNRat_zero : toNNRat 0 = 0 := rfl
@[simp]
theorem toNNRat_one : toNNRat 1 = 1 := rfl
@[simp]
theorem toNNRat_pos : 0 < toNNRat q ↔ 0 < q := by simp [toNNRat, ← coe_lt_coe]
@[simp]
theorem toNNRat_eq_zero : toNNRat q = 0 ↔ q ≤ 0 := by
simpa [-toNNRat_pos] using (@toNNRat_pos q).not
alias ⟨_, toNNRat_of_nonpos⟩ := toNNRat_eq_zero
@[simp]
theorem toNNRat_le_toNNRat_iff (hp : 0 ≤ p) : toNNRat q ≤ toNNRat p ↔ q ≤ p := by
simp [← coe_le_coe, toNNRat, hp]
@[simp]
theorem toNNRat_lt_toNNRat_iff' : toNNRat q < toNNRat p ↔ q < p ∧ 0 < p := by
simp [← coe_lt_coe, toNNRat, lt_irrefl]
theorem toNNRat_lt_toNNRat_iff (h : 0 < p) : toNNRat q < toNNRat p ↔ q < p :=
toNNRat_lt_toNNRat_iff'.trans (and_iff_left h)
theorem toNNRat_lt_toNNRat_iff_of_nonneg (hq : 0 ≤ q) : toNNRat q < toNNRat p ↔ q < p :=
toNNRat_lt_toNNRat_iff'.trans ⟨And.left, fun h ↦ ⟨h, hq.trans_lt h⟩⟩
@[simp]
theorem toNNRat_add (hq : 0 ≤ q) (hp : 0 ≤ p) : toNNRat (q + p) = toNNRat q + toNNRat p :=
NNRat.ext <| by simp [toNNRat, hq, hp, add_nonneg]
theorem toNNRat_add_le : toNNRat (q + p) ≤ toNNRat q + toNNRat p :=
coe_le_coe.1 <| max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) <| coe_nonneg _
theorem toNNRat_le_iff_le_coe {p : ℚ≥0} : toNNRat q ≤ p ↔ q ≤ ↑p :=
NNRat.gi.gc q p
theorem le_toNNRat_iff_coe_le {q : ℚ≥0} (hp : 0 ≤ p) : q ≤ toNNRat p ↔ ↑q ≤ p := by
rw [← coe_le_coe, Rat.coe_toNNRat p hp]
theorem le_toNNRat_iff_coe_le' {q : ℚ≥0} (hq : 0 < q) : q ≤ toNNRat p ↔ ↑q ≤ p :=
(le_or_lt 0 p).elim le_toNNRat_iff_coe_le fun hp ↦ by
simp only [(hp.trans_le q.coe_nonneg).not_le, toNNRat_eq_zero.2 hp.le, hq.not_le]
theorem toNNRat_lt_iff_lt_coe {p : ℚ≥0} (hq : 0 ≤ q) : toNNRat q < p ↔ q < ↑p := by
rw [← coe_lt_coe, Rat.coe_toNNRat q hq]
theorem lt_toNNRat_iff_coe_lt {q : ℚ≥0} : q < toNNRat p ↔ ↑q < p :=
NNRat.gi.gc.lt_iff_lt
theorem toNNRat_mul (hp : 0 ≤ p) : toNNRat (p * q) = toNNRat p * toNNRat q := by
rcases le_total 0 q with hq | hq
· ext; simp [toNNRat, hp, hq, max_eq_left, mul_nonneg]
· have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq
rw [toNNRat_eq_zero.2 hq, toNNRat_eq_zero.2 hpq, mul_zero]
end Rat
/-- The absolute value on `ℚ` as a map to `ℚ≥0`. -/
@[pp_nodot]
def Rat.nnabs (x : ℚ) : ℚ≥0 :=
⟨abs x, abs_nonneg x⟩
@[norm_cast, simp]
theorem Rat.coe_nnabs (x : ℚ) : (Rat.nnabs x : ℚ) = abs x := rfl
/-! ### Numerator and denominator -/
namespace NNRat
variable {p q : ℚ≥0}
@[norm_cast] lemma num_coe (q : ℚ≥0) : (q : ℚ).num = q.num := by
simp only [num, Int.natCast_natAbs, Rat.num_nonneg, coe_nonneg, abs_of_nonneg]
theorem natAbs_num_coe : (q : ℚ).num.natAbs = q.num := rfl
@[norm_cast] lemma den_coe : (q : ℚ).den = q.den := rfl
@[simp] lemma num_ne_zero : q.num ≠ 0 ↔ q ≠ 0 := by simp [num]
@[simp] lemma num_pos : 0 < q.num ↔ 0 < q := by
simpa [num, -nonpos_iff_eq_zero] using nonpos_iff_eq_zero _ |>.not.symm
@[simp] lemma den_pos (q : ℚ≥0) : 0 < q.den := Rat.den_pos _
@[simp] lemma den_ne_zero (q : ℚ≥0) : q.den ≠ 0 := Rat.den_ne_zero _
lemma coprime_num_den (q : ℚ≥0) : q.num.Coprime q.den := by simpa [num, den] using Rat.reduced _
-- TODO: Rename `Rat.coe_nat_num`, `Rat.intCast_den`, `Rat.ofNat_num`, `Rat.ofNat_den`
@[simp, norm_cast] lemma num_natCast (n : ℕ) : num n = n := rfl
@[simp, norm_cast] lemma den_natCast (n : ℕ) : den n = 1 := rfl
@[simp] lemma num_ofNat (n : ℕ) [n.AtLeastTwo] : num ofNat(n) = OfNat.ofNat n :=
rfl
@[simp] lemma den_ofNat (n : ℕ) [n.AtLeastTwo] : den ofNat(n) = 1 := rfl
theorem ext_num_den (hn : p.num = q.num) (hd : p.den = q.den) : p = q := by
refine ext <| Rat.ext ?_ hd
simpa [num_coe]
theorem ext_num_den_iff : p = q ↔ p.num = q.num ∧ p.den = q.den :=
⟨by rintro rfl; exact ⟨rfl, rfl⟩, fun h ↦ ext_num_den h.1 h.2⟩
/-- Form the quotient `n / d` where `n d : ℕ`.
See also `Rat.divInt` and `mkRat`. -/
def divNat (n d : ℕ) : ℚ≥0 :=
⟨.divInt n d, Rat.divInt_nonneg (Int.ofNat_zero_le n) (Int.ofNat_zero_le d)⟩
variable {n₁ n₂ d₁ d₂ : ℕ}
@[simp, norm_cast] lemma coe_divNat (n d : ℕ) : (divNat n d : ℚ) = .divInt n d := rfl
lemma mk_divInt (n d : ℕ) :
⟨.divInt n d, Rat.divInt_nonneg (Int.ofNat_zero_le n) (Int.ofNat_zero_le d)⟩ = divNat n d := rfl
lemma divNat_inj (h₁ : d₁ ≠ 0) (h₂ : d₂ ≠ 0) : divNat n₁ d₁ = divNat n₂ d₂ ↔ n₁ * d₂ = n₂ * d₁ := by
rw [← coe_inj]; simp [Rat.mkRat_eq_iff, h₁, h₂]; norm_cast
@[simp] lemma divNat_zero (n : ℕ) : divNat n 0 = 0 := by simp [divNat]; rfl
@[simp] lemma num_divNat_den (q : ℚ≥0) : divNat q.num q.den = q :=
ext <| by rw [← (q : ℚ).mkRat_num_den']; simp [num_coe, den_coe]
lemma natCast_eq_divNat (n : ℕ) : (n : ℚ≥0) = divNat n 1 := (num_divNat_den _).symm
lemma divNat_mul_divNat (n₁ n₂ : ℕ) {d₁ d₂} (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) :
divNat n₁ d₁ * divNat n₂ d₂ = divNat (n₁ * n₂) (d₁ * d₂) := by
ext; push_cast; exact Rat.divInt_mul_divInt _ _ (mod_cast hd₁) (mod_cast hd₂)
lemma divNat_mul_left {a : ℕ} (ha : a ≠ 0) (n d : ℕ) : divNat (a * n) (a * d) = divNat n d := by
ext; push_cast; exact Rat.divInt_mul_left (mod_cast ha)
lemma divNat_mul_right {a : ℕ} (ha : a ≠ 0) (n d : ℕ) : divNat (n * a) (d * a) = divNat n d := by
ext; push_cast; exact Rat.divInt_mul_right (mod_cast ha)
@[simp] lemma mul_den_eq_num (q : ℚ≥0) : q * q.den = q.num := by
ext
push_cast
rw [← Int.cast_natCast, ← den_coe, ← Int.cast_natCast q.num, ← num_coe]
exact Rat.mul_den_eq_num _
@[simp] lemma den_mul_eq_num (q : ℚ≥0) : q.den * q = q.num := by rw [mul_comm, mul_den_eq_num]
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with nonnegative rational
numbers of the form `n / d` with `d ≠ 0` and `n`, `d` coprime. -/
@[elab_as_elim]
def numDenCasesOn.{u} {C : ℚ≥0 → Sort u} (q) (H : ∀ n d, d ≠ 0 → n.Coprime d → C (divNat n d)) :
C q := by rw [← q.num_divNat_den]; exact H _ _ q.den_ne_zero q.coprime_num_den
lemma add_def (q r : ℚ≥0) : q + r = divNat (q.num * r.den + r.num * q.den) (q.den * r.den) := by
ext; simp [Rat.add_def', Rat.mkRat_eq_divInt, num_coe, den_coe]
lemma mul_def (q r : ℚ≥0) : q * r = divNat (q.num * r.num) (q.den * r.den) := by
ext; simp [Rat.mul_eq_mkRat, Rat.mkRat_eq_divInt, num_coe, den_coe]
theorem lt_def {p q : ℚ≥0} : p < q ↔ p.num * q.den < q.num * p.den := by
rw [← NNRat.coe_lt_coe, Rat.lt_def]; norm_cast
theorem le_def {p q : ℚ≥0} : p ≤ q ↔ p.num * q.den ≤ q.num * p.den := by
rw [← NNRat.coe_le_coe, Rat.le_def]; norm_cast
end NNRat
namespace Mathlib.Tactic.Qify
| Mathlib/Data/NNRat/Defs.lean | 409 | 409 | |
/-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Yaël Dillies
-/
import Mathlib.Order.Interval.Set.Defs
import Mathlib.Order.Monotone.Basic
import Mathlib.Tactic.Bound.Attribute
import Mathlib.Tactic.Contrapose
import Mathlib.Tactic.Monotonicity.Attr
/-!
# Natural number logarithms
This file defines two `ℕ`-valued analogs of the logarithm of `n` with base `b`:
* `log b n`: Lower logarithm, or floor **log**. Greatest `k` such that `b^k ≤ n`.
* `clog b n`: Upper logarithm, or **c**eil **log**. Least `k` such that `n ≤ b^k`.
These are interesting because, for `1 < b`, `Nat.log b` and `Nat.clog b` are respectively right and
left adjoints of `Nat.pow b`. See `pow_le_iff_le_log` and `le_pow_iff_clog_le`.
-/
assert_not_exists OrderTop
namespace Nat
/-! ### Floor logarithm -/
/-- `log b n`, is the logarithm of natural number `n` in base `b`. It returns the largest `k : ℕ`
such that `b^k ≤ n`, so if `b^k = n`, it returns exactly `k`. -/
@[pp_nodot]
def log (b : ℕ) : ℕ → ℕ
| n => if h : b ≤ n ∧ 1 < b then log b (n / b) + 1 else 0
decreasing_by
-- putting this in the def triggers the `unusedHavesSuffices` linter:
-- https://github.com/leanprover-community/batteries/issues/428
have : n / b < n := div_lt_self ((Nat.zero_lt_one.trans h.2).trans_le h.1) h.2
decreasing_trivial
@[simp]
theorem log_eq_zero_iff {b n : ℕ} : log b n = 0 ↔ n < b ∨ b ≤ 1 := by
rw [log, dite_eq_right_iff]
simp only [Nat.add_eq_zero_iff, Nat.one_ne_zero, and_false, imp_false, not_and_or, not_le, not_lt]
theorem log_of_lt {b n : ℕ} (hb : n < b) : log b n = 0 :=
log_eq_zero_iff.2 (Or.inl hb)
theorem log_of_left_le_one {b : ℕ} (hb : b ≤ 1) (n) : log b n = 0 :=
log_eq_zero_iff.2 (Or.inr hb)
@[simp]
theorem log_pos_iff {b n : ℕ} : 0 < log b n ↔ b ≤ n ∧ 1 < b := by
rw [Nat.pos_iff_ne_zero, Ne, log_eq_zero_iff, not_or, not_lt, not_le]
@[bound]
theorem log_pos {b n : ℕ} (hb : 1 < b) (hbn : b ≤ n) : 0 < log b n :=
log_pos_iff.2 ⟨hbn, hb⟩
theorem log_of_one_lt_of_le {b n : ℕ} (h : 1 < b) (hn : b ≤ n) : log b n = log b (n / b) + 1 := by
rw [log]
exact if_pos ⟨hn, h⟩
@[simp] lemma log_zero_left : ∀ n, log 0 n = 0 := log_of_left_le_one <| Nat.zero_le _
@[simp]
theorem log_zero_right (b : ℕ) : log b 0 = 0 :=
log_eq_zero_iff.2 (le_total 1 b)
@[simp]
theorem log_one_left : ∀ n, log 1 n = 0 :=
log_of_left_le_one le_rfl
@[simp]
theorem log_one_right (b : ℕ) : log b 1 = 0 :=
log_eq_zero_iff.2 (lt_or_le _ _)
/-- `pow b` and `log b` (almost) form a Galois connection. See also `Nat.pow_le_of_le_log` and
`Nat.le_log_of_pow_le` for individual implications under weaker assumptions. -/
theorem pow_le_iff_le_log {b : ℕ} (hb : 1 < b) {x y : ℕ} (hy : y ≠ 0) :
b ^ x ≤ y ↔ x ≤ log b y := by
induction y using Nat.strong_induction_on generalizing x with | h y ih => ?_
cases x with
| zero => dsimp; omega
| succ x =>
rw [log]; split_ifs with h
· have b_pos : 0 < b := lt_of_succ_lt hb
rw [Nat.add_le_add_iff_right, ← ih (y / b) (div_lt_self
(Nat.pos_iff_ne_zero.2 hy) hb) (Nat.div_pos h.1 b_pos).ne', le_div_iff_mul_le b_pos,
pow_succ', Nat.mul_comm]
· exact iff_of_false (fun hby => h ⟨(le_self_pow x.succ_ne_zero _).trans hby, hb⟩)
(not_succ_le_zero _)
theorem lt_pow_iff_log_lt {b : ℕ} (hb : 1 < b) {x y : ℕ} (hy : y ≠ 0) : y < b ^ x ↔ log b y < x :=
lt_iff_lt_of_le_iff_le (pow_le_iff_le_log hb hy)
theorem pow_le_of_le_log {b x y : ℕ} (hy : y ≠ 0) (h : x ≤ log b y) : b ^ x ≤ y := by
refine (le_or_lt b 1).elim (fun hb => ?_) fun hb => (pow_le_iff_le_log hb hy).2 h
rw [log_of_left_le_one hb, Nat.le_zero] at h
rwa [h, Nat.pow_zero, one_le_iff_ne_zero]
theorem le_log_of_pow_le {b x y : ℕ} (hb : 1 < b) (h : b ^ x ≤ y) : x ≤ log b y := by
rcases ne_or_eq y 0 with (hy | rfl)
exacts [(pow_le_iff_le_log hb hy).1 h, (h.not_lt (Nat.pow_pos (Nat.zero_lt_one.trans hb))).elim]
theorem pow_log_le_self (b : ℕ) {x : ℕ} (hx : x ≠ 0) : b ^ log b x ≤ x :=
pow_le_of_le_log hx le_rfl
theorem log_lt_of_lt_pow {b x y : ℕ} (hy : y ≠ 0) : y < b ^ x → log b y < x :=
lt_imp_lt_of_le_imp_le (pow_le_of_le_log hy)
theorem lt_pow_of_log_lt {b x y : ℕ} (hb : 1 < b) : log b y < x → y < b ^ x :=
lt_imp_lt_of_le_imp_le (le_log_of_pow_le hb)
lemma log_lt_self (b : ℕ) {x : ℕ} (hx : x ≠ 0) : log b x < x :=
match le_or_lt b 1 with
| .inl h => log_of_left_le_one h x ▸ Nat.pos_iff_ne_zero.2 hx
| .inr h => log_lt_of_lt_pow hx <| Nat.lt_pow_self h
lemma log_le_self (b x : ℕ) : log b x ≤ x :=
if hx : x = 0 then by simp [hx]
else (log_lt_self b hx).le
theorem lt_pow_succ_log_self {b : ℕ} (hb : 1 < b) (x : ℕ) : x < b ^ (log b x).succ :=
lt_pow_of_log_lt hb (lt_succ_self _)
theorem log_eq_iff {b m n : ℕ} (h : m ≠ 0 ∨ 1 < b ∧ n ≠ 0) :
log b n = m ↔ b ^ m ≤ n ∧ n < b ^ (m + 1) := by
rcases em (1 < b ∧ n ≠ 0) with (⟨hb, hn⟩ | hbn)
· rw [le_antisymm_iff, ← Nat.lt_succ_iff, ← pow_le_iff_le_log, ← lt_pow_iff_log_lt,
and_comm] <;> assumption
have hm : m ≠ 0 := h.resolve_right hbn
rw [not_and_or, not_lt, Ne, not_not] at hbn
rcases hbn with (hb | rfl)
· obtain rfl | rfl := le_one_iff_eq_zero_or_eq_one.1 hb
any_goals
simp only [ne_eq, zero_eq, reduceSucc, lt_self_iff_false, not_lt_zero, false_and, or_false]
at h
simp [h, eq_comm (a := 0), Nat.zero_pow (Nat.pos_iff_ne_zero.2 _)] <;> omega
· simp [@eq_comm _ 0, hm]
theorem log_eq_of_pow_le_of_lt_pow {b m n : ℕ} (h₁ : b ^ m ≤ n) (h₂ : n < b ^ (m + 1)) :
log b n = m := by
rcases eq_or_ne m 0 with (rfl | hm)
· rw [Nat.pow_one] at h₂
exact log_of_lt h₂
· exact (log_eq_iff (Or.inl hm)).2 ⟨h₁, h₂⟩
theorem log_pow {b : ℕ} (hb : 1 < b) (x : ℕ) : log b (b ^ x) = x :=
log_eq_of_pow_le_of_lt_pow le_rfl (Nat.pow_lt_pow_right hb x.lt_succ_self)
theorem log_eq_one_iff' {b n : ℕ} : log b n = 1 ↔ b ≤ n ∧ n < b * b := by
rw [log_eq_iff (Or.inl Nat.one_ne_zero), Nat.pow_add, Nat.pow_one]
theorem log_eq_one_iff {b n : ℕ} : log b n = 1 ↔ n < b * b ∧ 1 < b ∧ b ≤ n :=
log_eq_one_iff'.trans
⟨fun h => ⟨h.2, lt_mul_self_iff.1 (h.1.trans_lt h.2), h.1⟩, fun h => ⟨h.2.2, h.1⟩⟩
theorem log_mul_base {b n : ℕ} (hb : 1 < b) (hn : n ≠ 0) : log b (n * b) = log b n + 1 := by
apply log_eq_of_pow_le_of_lt_pow <;> rw [pow_succ', Nat.mul_comm b]
exacts [Nat.mul_le_mul_right _ (pow_log_le_self _ hn),
(Nat.mul_lt_mul_right (Nat.zero_lt_one.trans hb)).2 (lt_pow_succ_log_self hb _)]
theorem pow_log_le_add_one (b : ℕ) : ∀ x, b ^ log b x ≤ x + 1
| 0 => by rw [log_zero_right, Nat.pow_zero]
| x + 1 => (pow_log_le_self b x.succ_ne_zero).trans (x + 1).le_succ
theorem log_monotone {b : ℕ} : Monotone (log b) := by
refine monotone_nat_of_le_succ fun n => ?_
rcases le_or_lt b 1 with hb | hb
· rw [log_of_left_le_one hb]
exact zero_le _
· exact le_log_of_pow_le hb (pow_log_le_add_one _ _)
@[mono]
theorem log_mono_right {b n m : ℕ} (h : n ≤ m) : log b n ≤ log b m :=
log_monotone h
@[mono]
theorem log_anti_left {b c n : ℕ} (hc : 1 < c) (hb : c ≤ b) : log b n ≤ log c n := by
rcases eq_or_ne n 0 with (rfl | hn); · rw [log_zero_right, log_zero_right]
apply le_log_of_pow_le hc
calc
c ^ log b n ≤ b ^ log b n := Nat.pow_le_pow_left hb _
_ ≤ n := pow_log_le_self _ hn
theorem log_antitone_left {n : ℕ} : AntitoneOn (fun b => log b n) (Set.Ioi 1) := fun _ hc _ _ hb =>
log_anti_left (Set.mem_Iio.1 hc) hb
@[simp]
theorem log_div_base (b n : ℕ) : log b (n / b) = log b n - 1 := by
rcases le_or_lt b 1 with hb | hb
· rw [log_of_left_le_one hb, log_of_left_le_one hb, Nat.zero_sub]
rcases lt_or_le n b with h | h
· rw [div_eq_of_lt h, log_of_lt h, log_zero_right]
rw [log_of_one_lt_of_le hb h, Nat.add_sub_cancel_right]
@[simp]
theorem log_div_mul_self (b n : ℕ) : log b (n / b * b) = log b n := by
rcases le_or_lt b 1 with hb | hb
· rw [log_of_left_le_one hb, log_of_left_le_one hb]
rcases lt_or_le n b with h | h
· rw [div_eq_of_lt h, Nat.zero_mul, log_zero_right, log_of_lt h]
rw [log_mul_base hb (Nat.div_pos h (by omega)).ne', log_div_base,
Nat.sub_add_cancel (succ_le_iff.2 <| log_pos hb h)]
theorem add_pred_div_lt {b n : ℕ} (hb : 1 < b) (hn : 2 ≤ n) : (n + b - 1) / b < n := by
rw [div_lt_iff_lt_mul (by omega), ← succ_le_iff, ← pred_eq_sub_one,
succ_pred_eq_of_pos (by omega)]
exact Nat.add_le_mul hn hb
lemma log2_eq_log_two {n : ℕ} : Nat.log2 n = Nat.log 2 n := by
rcases eq_or_ne n 0 with rfl | hn
· rw [log2_zero, log_zero_right]
apply eq_of_forall_le_iff
intro m
rw [Nat.le_log2 hn, ← Nat.pow_le_iff_le_log Nat.one_lt_two hn]
| /-! ### Ceil logarithm -/
/-- `clog b n`, is the upper logarithm of natural number `n` in base `b`. It returns the smallest
`k : ℕ` such that `n ≤ b^k`, so if `b^k = n`, it returns exactly `k`. -/
@[pp_nodot]
def clog (b : ℕ) : ℕ → ℕ
| Mathlib/Data/Nat/Log.lean | 219 | 225 |
/-
Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import Mathlib.Algebra.Field.ZMod
import Mathlib.NumberTheory.Padics.PadicIntegers
import Mathlib.RingTheory.LocalRing.ResidueField.Defs
import Mathlib.RingTheory.ZMod
/-!
# Relating `ℤ_[p]` to `ZMod (p ^ n)`, aka `ℤ/p^nℤ`.
In this file we establish connections between the `p`-adic integers `ℤ_[p]`
and the integers modulo powers of `p`, `ℤ/p^nℤ`, implemented as `ZMod (p^n)`.
## Main declarations
We show that `ℤ_[p]` has a ring homomorphism to `ℤ/p^nℤ` for each `n`.
The case for `n = 1` is handled separately, since it is used in the general construction
and we may want to use it without the `^1` getting in the way.
* `PadicInt.toZMod`: ring homomorphism to `ℤ/pℤ`, implemented as `ZMod p`.
* `PadicInt.toZModPow`: ring homomorphism to `ℤ/p^nℤ`, implemented as `ZMod (p^n)`.
* `PadicInt.ker_toZMod` / `PadicInt.ker_toZModPow`: the kernels of these maps are the ideals
generated by `p^n`
* `PadicInt.residueField` shows that the residue field of `ℤ_[p]` is isomorhic to ``ℤ/pℤ`.
We also establish the universal property of `ℤ_[p]` as a projective limit.
Given a family of compatible ring homomorphisms `f_k : R → ℤ/p^nℤ`,
there is a unique limit `R → ℤ_[p]`
* `PadicInt.lift`: the limit function
* `PadicInt.lift_spec` / `PadicInt.lift_unique`: the universal property
## Implementation notes
The constructions of the ring homomorphisms go through an auxiliary constructor
`PadicInt.toZModHom`, which removes some boilerplate code.
-/
noncomputable section
open Nat IsLocalRing Padic
namespace PadicInt
variable {p : ℕ} [hp_prime : Fact p.Prime]
section RingHoms
/-! ### Ring homomorphisms to `ZMod p` and `ZMod (p ^ n)` -/
variable (p) (r : ℚ)
/-- `modPart p r` is an integer that satisfies
`‖(r - modPart p r : ℚ_[p])‖ < 1` when `‖(r : ℚ_[p])‖ ≤ 1`,
see `PadicInt.norm_sub_modPart`.
It is the unique non-negative integer that is `< p` with this property.
(Note that this definition assumes `r : ℚ`.
See `PadicInt.zmodRepr` for a version that takes values in `ℕ`
and works for arbitrary `x : ℤ_[p]`.) -/
def modPart : ℤ :=
r.num * gcdA r.den p % p
variable {p}
theorem modPart_lt_p : modPart p r < p := by
convert Int.emod_lt_abs _ _
· simp
· exact mod_cast hp_prime.1.ne_zero
theorem modPart_nonneg : 0 ≤ modPart p r :=
Int.emod_nonneg _ <| mod_cast hp_prime.1.ne_zero
theorem isUnit_den (r : ℚ) (h : ‖(r : ℚ_[p])‖ ≤ 1) : IsUnit (r.den : ℤ_[p]) := by
rw [isUnit_iff]
apply le_antisymm (r.den : ℤ_[p]).2
rw [← not_lt, coe_natCast]
intro norm_denom_lt
have hr : ‖(r * r.den : ℚ_[p])‖ = ‖(r.num : ℚ_[p])‖ := by
congr
rw_mod_cast [@Rat.mul_den_eq_num r]
rw [padicNormE.mul] at hr
have key : ‖(r.num : ℚ_[p])‖ < 1 := by
calc
_ = _ := hr.symm
_ < 1 * 1 := mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one
_ = 1 := mul_one 1
have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.den := by
simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padicInt]
exact ⟨key, norm_denom_lt⟩
apply hp_prime.1.not_dvd_one
rwa [← r.reduced.gcd_eq_one, Nat.dvd_gcd_iff, ← Int.natCast_dvd, ← Int.natCast_dvd_natCast]
theorem norm_sub_modPart_aux (r : ℚ) (h : ‖(r : ℚ_[p])‖ ≤ 1) :
↑p ∣ r.num - r.num * r.den.gcdA p % p * ↑r.den := by
rw [← ZMod.intCast_zmod_eq_zero_iff_dvd]
simp only [Int.cast_natCast, ZMod.natCast_mod, Int.cast_mul, Int.cast_sub]
have := congr_arg (fun x => x % p : ℤ → ZMod p) (gcd_eq_gcd_ab r.den p)
simp only [Int.cast_natCast, CharP.cast_eq_zero, EuclideanDomain.mod_zero, Int.cast_add,
Int.cast_mul, zero_mul, add_zero] at this
push_cast
rw [mul_right_comm, mul_assoc, ← this]
suffices rdcp : r.den.Coprime p by
rw [rdcp.gcd_eq_one]
simp only [mul_one, cast_one, sub_self]
apply Coprime.symm
apply (coprime_or_dvd_of_prime hp_prime.1 _).resolve_right
rw [← Int.natCast_dvd_natCast, ← norm_int_lt_one_iff_dvd, not_lt]
apply ge_of_eq
rw [← isUnit_iff]
exact isUnit_den r h
theorem norm_sub_modPart (h : ‖(r : ℚ_[p])‖ ≤ 1) : ‖(⟨r, h⟩ - modPart p r : ℤ_[p])‖ < 1 := by
let n := modPart p r
rw [norm_lt_one_iff_dvd, ← (isUnit_den r h).dvd_mul_right]
suffices ↑p ∣ r.num - n * r.den by
convert (Int.castRingHom ℤ_[p]).map_dvd this
simp only [n, sub_mul, Int.cast_natCast, eq_intCast, Int.cast_mul, sub_left_inj,
Int.cast_sub]
apply Subtype.coe_injective
simp only [coe_mul, Subtype.coe_mk, coe_natCast]
rw_mod_cast [@Rat.mul_den_eq_num r]
rfl
exact norm_sub_modPart_aux r h
theorem exists_mem_range_of_norm_rat_le_one (h : ‖(r : ℚ_[p])‖ ≤ 1) :
∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ‖(⟨r, h⟩ - n : ℤ_[p])‖ < 1 :=
⟨modPart p r, modPart_nonneg _, modPart_lt_p _, norm_sub_modPart _ h⟩
theorem zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ)
(ha : x - a ∈ (Ideal.span {(p : ℤ_[p]) ^ n}))
(hb : x - b ∈ (Ideal.span {(p : ℤ_[p]) ^ n})) : (a : ZMod (p ^ n)) = b := by
rw [Ideal.mem_span_singleton] at ha hb
rw [← sub_eq_zero, ← Int.cast_sub, ZMod.intCast_zmod_eq_zero_iff_dvd, Int.natCast_pow]
rw [← dvd_neg, neg_sub] at ha
have := dvd_add ha hb
rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ←
Int.cast_sub, pow_p_dvd_int_iff] at this
theorem zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ)
(ha : x - a ∈ (Ideal.span {(p : ℤ_[p]) ^ n}))
(hb : x - b ∈ (Ideal.span {(p : ℤ_[p]) ^ n})) : (a : ZMod (p ^ n)) = b := by
simpa using zmod_congr_of_sub_mem_span_aux n x a b ha hb
theorem zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximalIdeal ℤ_[p])
(hn : x - n ∈ maximalIdeal ℤ_[p]) : (m : ZMod p) = n := by
rw [maximalIdeal_eq_span_p] at hm hn
have := zmod_congr_of_sub_mem_span_aux 1 x m n
simp only [pow_one] at this
specialize this hm hn
apply_fun ZMod.castHom (show p ∣ p ^ 1 by rw [pow_one]) (ZMod p) at this
simp only [map_intCast] at this
simpa only [Int.cast_natCast] using this
variable (x : ℤ_[p])
theorem exists_mem_range : ∃ n : ℕ, n < p ∧ x - n ∈ maximalIdeal ℤ_[p] := by
simp only [maximalIdeal_eq_span_p, Ideal.mem_span_singleton, ← norm_lt_one_iff_dvd]
obtain ⟨r, hr⟩ := rat_dense p (x : ℚ_[p]) zero_lt_one
have H : ‖(r : ℚ_[p])‖ ≤ 1 := by
rw [norm_sub_rev] at hr
calc
_ = ‖(r : ℚ_[p]) - x + x‖ := by ring_nf
_ ≤ _ := padicNormE.nonarchimedean _ _
_ ≤ _ := max_le (le_of_lt hr) x.2
obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H
lift n to ℕ using hzn
use n
constructor
· exact mod_cast hnp
simp only [norm_def, coe_sub, Subtype.coe_mk, coe_natCast] at hn ⊢
rw [show (x - n : ℚ_[p]) = x - r + (r - n) by ring]
apply lt_of_le_of_lt (padicNormE.nonarchimedean _ _)
apply max_lt hr
simpa using hn
theorem existsUnique_mem_range : ∃! n : ℕ, n < p ∧ x - n ∈ maximalIdeal ℤ_[p] := by
obtain ⟨n, hn₁, hn₂⟩ := exists_mem_range x
use n, ⟨hn₁, hn₂⟩, fun m ⟨hm₁, hm₂⟩ ↦ ?_
have := (zmod_congr_of_sub_mem_max_ideal x n m hn₂ hm₂).symm
rwa [ZMod.natCast_eq_natCast_iff, ModEq, mod_eq_of_lt hn₁, mod_eq_of_lt hm₁] at this
@[deprecated (since := "2024-12-17")] alias exists_unique_mem_range := existsUnique_mem_range
/-- `zmodRepr x` is the unique natural number smaller than `p`
satisfying `‖(x - zmodRepr x : ℤ_[p])‖ < 1`.
-/
def zmodRepr : ℕ :=
Classical.choose (existsUnique_mem_range x).exists
theorem zmodRepr_spec : zmodRepr x < p ∧ x - zmodRepr x ∈ maximalIdeal ℤ_[p] :=
Classical.choose_spec (existsUnique_mem_range x).exists
theorem zmodRepr_unique (y : ℕ) (hy₁ : y < p) (hy₂ : x - y ∈ maximalIdeal ℤ_[p]) : y = zmodRepr x :=
have h := (Classical.choose_spec (existsUnique_mem_range x)).right
(h y ⟨hy₁, hy₂⟩).trans (h (zmodRepr x) (zmodRepr_spec x)).symm
theorem zmodRepr_lt_p : zmodRepr x < p :=
(zmodRepr_spec _).1
theorem sub_zmodRepr_mem : x - zmodRepr x ∈ maximalIdeal ℤ_[p] :=
(zmodRepr_spec _).2
/-- `toZModHom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `ZMod v`.
-/
def toZModHom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (Ideal.span {↑v} : Ideal ℤ_[p]))
(f_congr :
∀ (x : ℤ_[p]) (a b : ℕ),
x - a ∈ (Ideal.span {↑v} : Ideal ℤ_[p]) →
x - b ∈ (Ideal.span {↑v} : Ideal ℤ_[p]) → (a : ZMod v) = b) :
ℤ_[p] →+* ZMod v where
toFun x := f x
map_zero' := by
rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero]
· exact f_spec _
· simp only [sub_zero, cast_zero, Submodule.zero_mem]
map_one' := by
rw [f_congr (1 : ℤ_[p]) _ 1, cast_one]
· exact f_spec _
· simp only [sub_self, cast_one, Submodule.zero_mem]
map_add' := by
intro x y
rw [f_congr (x + y) _ (f x + f y), cast_add]
· exact f_spec _
· convert Ideal.add_mem _ (f_spec x) (f_spec y) using 1
rw [cast_add]
ring
map_mul' := by
intro x y
rw [f_congr (x * y) _ (f x * f y), cast_mul]
· exact f_spec _
· let I : Ideal ℤ_[p] := Ideal.span {↑v}
convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right ↑(f y) (f_spec x)) using 1
rw [cast_mul]
ring
/-- `toZMod` is a ring hom from `ℤ_[p]` to `ZMod p`,
with the equality `toZMod x = (zmodRepr x : ZMod p)`.
-/
def toZMod : ℤ_[p] →+* ZMod p :=
toZModHom p zmodRepr
(by
rw [← maximalIdeal_eq_span_p]
exact sub_zmodRepr_mem)
(by
rw [← maximalIdeal_eq_span_p]
exact zmod_congr_of_sub_mem_max_ideal)
/-- `z - (toZMod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`.
The coercion from `ZMod p` to `ℤ_[p]` is `ZMod.cast`,
which coerces `ZMod p` into arbitrary rings.
This is unfortunate, but a consequence of the fact that we allow `ZMod p`
to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`.
This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides
`p`. While this is not the case here we can still make use of the coercion.
-/
theorem toZMod_spec : x - (ZMod.cast (toZMod x) : ℤ_[p]) ∈ maximalIdeal ℤ_[p] := by
convert sub_zmodRepr_mem x using 2
dsimp [toZMod, toZModHom]
rcases Nat.exists_eq_add_of_lt hp_prime.1.pos with ⟨p', rfl⟩
change ↑((_ : ZMod (0 + p' + 1)).val) = (_ : ℤ_[0 + p' + 1])
rw [Nat.cast_inj]
apply mod_eq_of_lt
simpa only [zero_add] using zmodRepr_lt_p x
theorem ker_toZMod : RingHom.ker (toZMod : ℤ_[p] →+* ZMod p) = maximalIdeal ℤ_[p] := by
ext x
rw [RingHom.mem_ker]
constructor
· intro h
simpa only [h, ZMod.cast_zero, sub_zero] using toZMod_spec x
· intro h
rw [← sub_zero x] at h
dsimp [toZMod, toZModHom]
convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h
· norm_cast
· apply sub_zmodRepr_mem
/-- The equivalence between the residue field of the `p`-adic integers and `ℤ/pℤ` -/
def residueField : IsLocalRing.ResidueField ℤ_[p] ≃+* ZMod p :=
(Ideal.quotEquivOfEq PadicInt.ker_toZMod.symm).trans <|
RingHom.quotientKerEquivOfSurjective (ZMod.ringHom_surjective PadicInt.toZMod)
open scoped Classical in
/-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`.
See `appr_spec`. -/
noncomputable def appr : ℤ_[p] → ℕ → ℕ
| _x, 0 => 0
| x, n + 1 =>
let y := x - appr x n
if hy : y = 0 then appr x n
else
let u := (unitCoeff hy : ℤ_[p])
appr x n + p ^ n * (toZMod ((u * (p : ℤ_[p]) ^ (y.valuation - n : ℤ).natAbs) : ℤ_[p])).val
theorem appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := by
induction n generalizing x with
| zero => simp only [appr, zero_eq, _root_.pow_zero, zero_lt_one]
| succ n ih =>
simp only [appr, map_natCast, ZMod.natCast_self, RingHom.map_pow, Int.natAbs, RingHom.map_mul]
have hp : p ^ n < p ^ (n + 1) := by apply Nat.pow_lt_pow_right hp_prime.1.one_lt n.lt_add_one
split_ifs with h
· apply lt_trans (ih _) hp
· calc
_ < p ^ n + p ^ n * (p - 1) := ?_
_ = p ^ (n + 1) := ?_
· apply add_lt_add_of_lt_of_le (ih _)
apply Nat.mul_le_mul_left
apply le_pred_of_lt
apply ZMod.val_lt
· rw [mul_tsub, mul_one, ← _root_.pow_succ]
apply add_tsub_cancel_of_le (le_of_lt hp)
theorem appr_mono (x : ℤ_[p]) : Monotone x.appr := by
apply monotone_nat_of_le_succ
intro n
dsimp [appr]
split_ifs; · rfl
apply Nat.le_add_right
theorem dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := by
obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le h; clear h
induction k with
| zero =>
simp only [zero_eq, add_zero, le_refl, tsub_eq_zero_of_le, ne_eq, Nat.isUnit_iff, dvd_zero]
| succ k ih =>
rw [← add_assoc]
dsimp [appr]
split_ifs with h
· exact ih
rw [add_comm, add_tsub_assoc_of_le (appr_mono _ (Nat.le_add_right m k))]
apply dvd_add _ ih
apply dvd_mul_of_dvd_left
apply pow_dvd_pow _ (Nat.le_add_right m k)
theorem appr_spec (n : ℕ) : ∀ x : ℤ_[p], x - appr x n ∈ Ideal.span {(p : ℤ_[p]) ^ n} := by
simp only [Ideal.mem_span_singleton]
induction n with
| zero => simp only [zero_eq, _root_.pow_zero, isUnit_one, IsUnit.dvd, forall_const]
| succ n ih =>
intro x
dsimp only [appr]
split_ifs with h
· rw [h]
apply dvd_zero
push_cast
rw [sub_add_eq_sub_sub]
obtain ⟨c, hc⟩ := ih x
simp only [map_natCast, ZMod.natCast_self, RingHom.map_pow, RingHom.map_mul, ZMod.natCast_val]
have hc' : c ≠ 0 := by
rintro rfl
simp only [mul_zero] at hc
contradiction
conv_rhs =>
congr
simp only [hc]
rw [show (x - (appr x n : ℤ_[p])).valuation = ((p : ℤ_[p]) ^ n * c).valuation by rw [hc]]
rw [valuation_p_pow_mul _ _ hc', Nat.cast_add, add_sub_cancel_left, _root_.pow_succ, ← mul_sub]
apply mul_dvd_mul_left
obtain hc0 | hc0 := eq_or_ne c.valuation 0
· simp only [hc0, mul_one, _root_.pow_zero, Nat.cast_zero, Int.natAbs_zero]
rw [mul_comm, unitCoeff_spec h] at hc
suffices c = unitCoeff h by
rw [← this, ← Ideal.mem_span_singleton, ← maximalIdeal_eq_span_p]
apply toZMod_spec
lift c to ℤ_[p]ˣ using by simp [isUnit_iff, norm_eq_zpow_neg_valuation hc', hc0]
rw [IsDiscreteValuationRing.unit_mul_pow_congr_unit _ _ _ _ _ hc]
exact irreducible_p
· simp only [Int.natAbs_natCast, zero_pow hc0, sub_zero, ZMod.cast_zero, mul_zero]
rw [unitCoeff_spec hc']
exact (dvd_pow_self (p : ℤ_[p]) hc0).mul_left _
/-- A ring hom from `ℤ_[p]` to `ZMod (p^n)`, with underlying function `PadicInt.appr n`. -/
def toZModPow (n : ℕ) : ℤ_[p] →+* ZMod (p ^ n) :=
toZModHom (p ^ n) (fun x => appr x n)
(by
intros
rw [Nat.cast_pow]
exact appr_spec n _)
(by
intro x a b ha hb
apply zmod_congr_of_sub_mem_span n x a b
· simpa using ha
· simpa using hb)
theorem ker_toZModPow (n : ℕ) :
RingHom.ker (toZModPow n : ℤ_[p] →+* ZMod (p ^ n)) = Ideal.span {(p : ℤ_[p]) ^ n} := by
ext x
rw [RingHom.mem_ker]
constructor
· intro h
suffices x.appr n = 0 by
convert appr_spec n x
simp only [this, sub_zero, cast_zero]
dsimp [toZModPow, toZModHom] at h
rw [ZMod.natCast_zmod_eq_zero_iff_dvd] at h
apply eq_zero_of_dvd_of_lt h (appr_lt _ _)
· intro h
rw [← sub_zero x] at h
dsimp [toZModPow, toZModHom]
rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero]
apply appr_spec
-- This is not a simp lemma; simp can't match the LHS.
theorem zmod_cast_comp_toZModPow (m n : ℕ) (h : m ≤ n) :
(ZMod.castHom (pow_dvd_pow p h) (ZMod (p ^ m))).comp (@toZModPow p _ n) = @toZModPow p _ m := by
apply ZMod.ringHom_eq_of_ker_eq
ext x
rw [RingHom.mem_ker, RingHom.mem_ker]
simp only [Function.comp_apply, ZMod.castHom_apply, RingHom.coe_comp]
simp only [toZModPow, toZModHom, RingHom.coe_mk]
dsimp
rw [ZMod.cast_natCast (pow_dvd_pow p h),
zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)]
· rw [sub_self]
apply Ideal.zero_mem _
· rw [Ideal.mem_span_singleton]
rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩
use c
rw [← Nat.cast_sub (appr_mono _ h), hc, Nat.cast_mul, Nat.cast_pow]
@[simp]
theorem cast_toZModPow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) :
ZMod.cast (toZModPow n x) = toZModPow m x := by
rw [← zmod_cast_comp_toZModPow _ _ h]
rfl
theorem denseRange_natCast : DenseRange (Nat.cast : ℕ → ℤ_[p]) := by
intro x
rw [Metric.mem_closure_range_iff]
intro ε hε
obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε
use x.appr n
rw [dist_eq_norm]
apply lt_of_le_of_lt _ hn
rw [norm_le_pow_iff_mem_span_pow]
apply appr_spec
theorem denseRange_intCast : DenseRange (Int.cast : ℤ → ℤ_[p]) := by
intro x
refine DenseRange.induction_on denseRange_natCast x ?_ ?_
· exact isClosed_closure
· intro a
apply subset_closure
exact Set.mem_range_self _
end RingHoms
section lift
/-! ### Universal property as projective limit -/
open CauSeq PadicSeq
variable {R : Type*} [NonAssocSemiring R] {p : Nat} (f : ∀ k : ℕ, R →+* ZMod (p ^ k))
/-- Given a family of ring homs `f : Π n : ℕ, R →+* ZMod (p ^ n)`,
`nthHom f r` is an integer-valued sequence
whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n`
and `f n r = (k : ZMod (p ^ n))`.
-/
def nthHom (r : R) : ℕ → ℤ := fun n => (f n r : ZMod (p ^ n)).val
@[simp]
theorem nthHom_zero : nthHom f 0 = 0 := by
simp +unfoldPartialApp [nthHom]
rfl
variable {f}
variable [hp_prime : Fact p.Prime]
section
variable
(f_compat : ∀ (k1 k2) (hk : k1 ≤ k2), (ZMod.castHom (pow_dvd_pow p hk) _).comp (f k2) = f k1)
include f_compat
theorem pow_dvd_nthHom_sub (r : R) (i j : ℕ) (h : i ≤ j) :
(p : ℤ) ^ i ∣ nthHom f r j - nthHom f r i := by
specialize f_compat i j h
rw [← Int.natCast_pow, ← ZMod.intCast_zmod_eq_zero_iff_dvd, Int.cast_sub]
dsimp [nthHom]
rw [← f_compat, RingHom.comp_apply]
simp only [ZMod.cast_id, ZMod.castHom_apply, sub_self, ZMod.natCast_val, ZMod.intCast_cast]
theorem isCauSeq_nthHom (r : R) : IsCauSeq (padicNorm p) fun n => nthHom f r n := by
intro ε hε
obtain ⟨k, hk⟩ : ∃ k : ℕ, (p : ℚ) ^ (-((k : ℕ) : ℤ)) < ε := exists_pow_neg_lt_rat p hε
use k
intro j hj
refine lt_of_le_of_lt ?_ hk
-- Need to do beta reduction first, as `norm_cast` doesn't.
-- Added to adapt to https://github.com/leanprover/lean4/pull/2734.
beta_reduce
norm_cast
rw [← padicNorm.dvd_iff_norm_le]
exact mod_cast pow_dvd_nthHom_sub f_compat r k j hj
/-- `nthHomSeq f_compat r` bundles `PadicInt.nthHom f r`
as a Cauchy sequence of rationals with respect to the `p`-adic norm.
The `n`th value of the sequence is `((f n r).val : ℚ)`.
-/
def nthHomSeq (r : R) : PadicSeq p :=
⟨fun n => nthHom f r n, isCauSeq_nthHom f_compat r⟩
-- this lemma ran into issues after changing to `NeZero` and I'm not sure why.
theorem nthHomSeq_one : nthHomSeq f_compat 1 ≈ 1 := by
intro ε hε
change _ < _ at hε
use 1
intro j hj
haveI : Fact (1 < p ^ j) := ⟨Nat.one_lt_pow (by omega) hp_prime.1.one_lt⟩
suffices (ZMod.cast (1 : ZMod (p ^ j)) : ℚ) = 1 by simp [nthHomSeq, nthHom, this, hε]
rw [ZMod.cast_eq_val, ZMod.val_one, Nat.cast_one]
theorem nthHomSeq_add (r s : R) :
nthHomSeq f_compat (r + s) ≈ nthHomSeq f_compat r + nthHomSeq f_compat s := by
intro ε hε
obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε
use n
intro j hj
dsimp [nthHomSeq]
apply lt_of_le_of_lt _ hn
rw [← Int.cast_add, ← Int.cast_sub, ← padicNorm.dvd_iff_norm_le, ←
ZMod.intCast_zmod_eq_zero_iff_dvd]
dsimp [nthHom]
simp only [ZMod.natCast_val, RingHom.map_add, Int.cast_sub, ZMod.intCast_cast, Int.cast_add]
rw [ZMod.cast_add (show p ^ n ∣ p ^ j from pow_dvd_pow _ hj)]
simp only [cast_add, ZMod.natCast_val, Int.cast_add, ZMod.intCast_cast, sub_self]
theorem nthHomSeq_mul (r s : R) :
nthHomSeq f_compat (r * s) ≈ nthHomSeq f_compat r * nthHomSeq f_compat s := by
intro ε hε
obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε
use n
intro j hj
dsimp [nthHomSeq]
apply lt_of_le_of_lt _ hn
rw [← Int.cast_mul, ← Int.cast_sub, ← padicNorm.dvd_iff_norm_le, ←
ZMod.intCast_zmod_eq_zero_iff_dvd]
dsimp [nthHom]
simp only [ZMod.natCast_val, RingHom.map_mul, Int.cast_sub, ZMod.intCast_cast, Int.cast_mul]
rw [ZMod.cast_mul (show p ^ n ∣ p ^ j from pow_dvd_pow _ hj), sub_self]
/--
`limNthHom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* ZMod (p^k)`.
This is itself a ring hom: see `PadicInt.lift`.
-/
def limNthHom (r : R) : ℤ_[p] :=
ofIntSeq (nthHom f r) (isCauSeq_nthHom f_compat r)
theorem limNthHom_spec (r : R) :
∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ‖limNthHom f_compat r - nthHom f r n‖ < ε := by
intro ε hε
obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε
norm_cast at hε'0
obtain ⟨N, hN⟩ := padicNormE.defn (nthHomSeq f_compat r) hε'0
use N
intro n hn
apply _root_.lt_trans _ hε'
change (padicNormE _ : ℝ) < _
norm_cast
exact hN _ hn
theorem limNthHom_zero : limNthHom f_compat 0 = 0 := by simp [limNthHom]; rfl
theorem limNthHom_one : limNthHom f_compat 1 = 1 :=
Subtype.ext <| Quot.sound <| nthHomSeq_one f_compat
theorem limNthHom_add (r s : R) :
limNthHom f_compat (r + s) = limNthHom f_compat r + limNthHom f_compat s :=
Subtype.ext <| Quot.sound <| nthHomSeq_add f_compat _ _
theorem limNthHom_mul (r s : R) :
limNthHom f_compat (r * s) = limNthHom f_compat r * limNthHom f_compat s :=
Subtype.ext <| Quot.sound <| nthHomSeq_mul f_compat _ _
-- TODO: generalize this to arbitrary complete discrete valuation rings
/-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* ZMod (p^k)`,
with the equality `lift f_compat r = PadicInt.limNthHom f_compat r`.
-/
def lift : R →+* ℤ_[p] where
toFun := limNthHom f_compat
map_one' := limNthHom_one f_compat
map_mul' := limNthHom_mul f_compat
map_zero' := limNthHom_zero f_compat
map_add' := limNthHom_add f_compat
theorem lift_sub_val_mem_span (r : R) (n : ℕ) :
lift f_compat r - (f n r).val ∈ (Ideal.span {(p : ℤ_[p]) ^ n}) := by
obtain ⟨k, hk⟩ :=
limNthHom_spec f_compat r _
(show (0 : ℝ) < (p : ℝ) ^ (-n : ℤ) from zpow_pos (mod_cast hp_prime.1.pos) _)
have := le_of_lt (hk (max n k) (le_max_right _ _))
rw [norm_le_pow_iff_mem_span_pow] at this
dsimp [lift]
rw [sub_eq_sub_add_sub (limNthHom f_compat r) _ ↑(nthHom f r (max n k))]
apply Ideal.add_mem _ _ this
rw [Ideal.mem_span_singleton]
convert
(Int.castRingHom ℤ_[p]).map_dvd (pow_dvd_nthHom_sub f_compat r n (max n k) (le_max_left _ _))
· rw [map_pow]; rfl
· rw [map_sub]; rfl
/-- One part of the universal property of `ℤ_[p]` as a projective limit.
See also `PadicInt.lift_unique`.
-/
theorem lift_spec (n : ℕ) : (toZModPow n).comp (lift f_compat) = f n := by
ext r
rw [RingHom.comp_apply, ← ZMod.natCast_zmod_val (f n r), ← map_natCast <| toZModPow n, ←
sub_eq_zero, ← RingHom.map_sub, ← RingHom.mem_ker, ker_toZModPow]
apply lift_sub_val_mem_span
/-- One part of the universal property of `ℤ_[p]` as a projective limit.
See also `PadicInt.lift_spec`.
-/
theorem lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (toZModPow n).comp g = f n) :
lift f_compat = g := by
| ext1 r
apply eq_of_forall_dist_le
intro ε hε
obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε
apply le_trans _ (le_of_lt hn)
rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_toZModPow, RingHom.mem_ker,
RingHom.map_sub, ← RingHom.comp_apply, ← RingHom.comp_apply, lift_spec, hg, sub_self]
end
@[simp]
theorem lift_self (z : ℤ_[p]) : lift zmod_cast_comp_toZModPow z = z := by
show _ = RingHom.id _ z
rw [lift_unique zmod_cast_comp_toZModPow (RingHom.id ℤ_[p])]
intro; rw [RingHom.comp_id]
| Mathlib/NumberTheory/Padics/RingHoms.lean | 629 | 643 |
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov
-/
import Mathlib.LinearAlgebra.Quotient.Basic
/-!
# Isomorphism theorems for modules.
* The Noether's first, second, and third isomorphism theorems for modules are proved as
`LinearMap.quotKerEquivRange`, `LinearMap.quotientInfEquivSupQuotient` and
`Submodule.quotientQuotientEquivQuotient`.
-/
universe u v
variable {R M M₂ M₃ : Type*}
variable [Ring R] [AddCommGroup M] [AddCommGroup M₂] [AddCommGroup M₃]
variable [Module R M] [Module R M₂] [Module R M₃]
variable (f : M →ₗ[R] M₂)
/-! The first and second isomorphism theorems for modules. -/
namespace LinearMap
open Submodule
section IsomorphismLaws
/-- 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 quotKerEquivRange : (M ⧸ LinearMap.ker f) ≃ₗ[R] LinearMap.range f :=
(LinearEquiv.ofInjective ((LinearMap.ker f).liftQ f <| le_rfl) <|
ker_eq_bot.mp <| Submodule.ker_liftQ_eq_bot _ _ _ (le_refl (LinearMap.ker f))).trans
(LinearEquiv.ofEq _ _ <| Submodule.range_liftQ _ _ _)
/-- The **first isomorphism theorem for surjective linear maps**. -/
noncomputable def quotKerEquivOfSurjective (f : M →ₗ[R] M₂) (hf : Function.Surjective f) :
(M ⧸ LinearMap.ker f) ≃ₗ[R] M₂ :=
f.quotKerEquivRange.trans <| .ofTop (LinearMap.range f) <| range_eq_top.2 hf
@[simp]
theorem quotKerEquivRange_apply_mk (x : M) :
(f.quotKerEquivRange (Submodule.Quotient.mk x) : M₂) = f x :=
rfl
@[simp]
theorem quotKerEquivRange_symm_apply_image (x : M) (h : f x ∈ LinearMap.range f) :
f.quotKerEquivRange.symm ⟨f x, h⟩ = (LinearMap.ker f).mkQ x :=
f.quotKerEquivRange.symm_apply_apply ((LinearMap.ker f).mkQ x)
/-- Linear map from `p` to `p+p'/p'` where `p p'` are submodules of `R` -/
abbrev subToSupQuotient (p p' : Submodule R M) :
{ x // x ∈ p } →ₗ[R] { x // x ∈ p ⊔ p' } ⧸ comap (Submodule.subtype (p ⊔ p')) p' :=
(comap (p ⊔ p').subtype p').mkQ.comp (Submodule.inclusion le_sup_left)
theorem comap_leq_ker_subToSupQuotient (p p' : Submodule R M) :
comap (Submodule.subtype p) (p ⊓ p') ≤ ker (subToSupQuotient p p') := by
rw [LinearMap.ker_comp, Submodule.inclusion, comap_codRestrict, ker_mkQ, map_comap_subtype]
exact comap_mono (inf_le_inf_right _ le_sup_left)
/-- 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.
Note that in the following declaration the type of the domain is expressed using
``comap p.subtype p ⊓ comap p.subtype p'`
instead of
`comap p.subtype (p ⊓ p')`
because the former is the simp normal form (see also `Submodule.comap_inf`). -/
def quotientInfToSupQuotient (p p' : Submodule R M) :
(↥p) ⧸ (comap p.subtype p ⊓ comap p.subtype p') →ₗ[R]
(↥(p ⊔ p')) ⧸ (comap (p ⊔ p').subtype p') :=
(comap p.subtype (p ⊓ p')).liftQ (subToSupQuotient p p') (comap_leq_ker_subToSupQuotient p p')
theorem quotientInfEquivSupQuotient_injective (p p' : Submodule R M) :
Function.Injective (quotientInfToSupQuotient p p') := by
rw [← ker_eq_bot, quotientInfToSupQuotient, ker_liftQ_eq_bot]
rw [ker_comp, ker_mkQ]
exact fun ⟨x, hx1⟩ hx2 => ⟨hx1, hx2⟩
theorem quotientInfEquivSupQuotient_surjective (p p' : Submodule R M) :
Function.Surjective (quotientInfToSupQuotient p p') := by
rw [← range_eq_top, quotientInfToSupQuotient, range_liftQ, eq_top_iff']
rintro ⟨x, hx⟩; rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩
use ⟨y, hy⟩; apply (Submodule.Quotient.eq _).2
simp only [mem_comap, map_sub, coe_subtype, coe_inclusion, sub_add_cancel_left, neg_mem_iff, hz]
/--
Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism.
Note that in the following declaration the type of the domain is expressed using
``comap p.subtype p ⊓ comap p.subtype p'`
instead of
`comap p.subtype (p ⊓ p')`
because the former is the simp normal form (see also `Submodule.comap_inf`). -/
noncomputable def quotientInfEquivSupQuotient (p p' : Submodule R M) :
(p ⧸ comap p.subtype p ⊓ comap p.subtype p') ≃ₗ[R] _ ⧸ comap (p ⊔ p').subtype p' :=
LinearEquiv.ofBijective (quotientInfToSupQuotient p p')
⟨quotientInfEquivSupQuotient_injective p p', quotientInfEquivSupQuotient_surjective p p'⟩
@[simp]
theorem coe_quotientInfToSupQuotient (p p' : Submodule R M) :
⇑(quotientInfToSupQuotient p p') = quotientInfEquivSupQuotient p p' :=
rfl
theorem quotientInfEquivSupQuotient_apply_mk (p p' : Submodule R M) (x : p) :
let map := inclusion (le_sup_left : p ≤ p ⊔ p')
quotientInfEquivSupQuotient p p' (Submodule.Quotient.mk x) =
@Submodule.Quotient.mk R (p ⊔ p' : Submodule R M) _ _ _ (comap (p ⊔ p').subtype p') (map x) :=
rfl
theorem quotientInfEquivSupQuotient_symm_apply_left (p p' : Submodule R M) (x : ↥(p ⊔ p'))
(hx : (x : M) ∈ p) :
(quotientInfEquivSupQuotient p p').symm (Submodule.Quotient.mk x) =
Submodule.Quotient.mk ⟨x, hx⟩ :=
(LinearEquiv.symm_apply_eq _).2 <| by
rw [quotientInfEquivSupQuotient_apply_mk, inclusion_apply]
|
theorem quotientInfEquivSupQuotient_symm_apply_eq_zero_iff {p p' : Submodule R M} {x : ↥(p ⊔ p')} :
(quotientInfEquivSupQuotient p p').symm (Submodule.Quotient.mk x) = 0 ↔ (x : M) ∈ p' :=
(LinearEquiv.symm_apply_eq _).trans <| by simp
theorem quotientInfEquivSupQuotient_symm_apply_right (p p' : Submodule R M) {x : ↥(p ⊔ p')}
(hx : (x : M) ∈ p') : (quotientInfEquivSupQuotient p p').symm (Submodule.Quotient.mk x)
| Mathlib/LinearAlgebra/Isomorphisms.lean | 121 | 127 |
/-
Copyright (c) 2024 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import Mathlib.Algebra.MvPolynomial.Monad
import Mathlib.LinearAlgebra.Charpoly.ToMatrix
import Mathlib.LinearAlgebra.FreeModule.StrongRankCondition
import Mathlib.LinearAlgebra.Matrix.Charpoly.Univ
import Mathlib.RingTheory.TensorProduct.Finite
import Mathlib.RingTheory.TensorProduct.Free
/-!
# Characteristic polynomials of linear families of endomorphisms
The coefficients of the characteristic polynomials of a linear family of endomorphisms
are homogeneous polynomials in the parameters.
This result is used in Lie theory
to establish the existence of regular elements and Cartan subalgebras,
and ultimately a well-defined notion of rank for Lie algebras.
In this file we prove this result about characteristic polynomials.
Let `L` and `M` be modules over a nontrivial commutative ring `R`,
and let `φ : L →ₗ[R] Module.End R M` be a linear map.
Let `b` be a basis of `L`, indexed by `ι`.
Then we define a multivariate polynomial with variables indexed by `ι`
that evaluates on elements `x` of `L` to the characteristic polynomial of `φ x`.
## Main declarations
* `Matrix.toMvPolynomial M i`: the family of multivariate polynomials that evaluates on `c : n → R`
to the dot product of the `i`-th row of `M` with `c`.
`Matrix.toMvPolynomial M i` is the sum of the monomials `C (M i j) * X j`.
* `LinearMap.toMvPolynomial b₁ b₂ f`: a version of `Matrix.toMvPolynomial` for linear maps `f`
with respect to bases `b₁` and `b₂` of the domain and codomain.
* `LinearMap.polyCharpoly`: the multivariate polynomial that evaluates on elements `x` of `L`
to the characteristic polynomial of `φ x`.
* `LinearMap.polyCharpoly_map_eq_charpoly`: the evaluation of `polyCharpoly` on elements `x` of `L`
is the characteristic polynomial of `φ x`.
* `LinearMap.polyCharpoly_coeff_isHomogeneous`: the coefficients of `polyCharpoly`
are homogeneous polynomials in the parameters.
* `LinearMap.nilRank`: the smallest index at which `polyCharpoly` has a non-zero coefficient,
which is independent of the choice of basis for `L`.
* `LinearMap.IsNilRegular`: an element `x` of `L` is *nil-regular* with respect to `φ`
if the `n`-th coefficient of the characteristic polynomial of `φ x` is non-zero,
where `n` denotes the nil-rank of `φ`.
## Implementation details
We show that `LinearMap.polyCharpoly` does not depend on the choice of basis of the target module.
This is done via `LinearMap.polyCharpoly_eq_polyCharpolyAux`
and `LinearMap.polyCharpolyAux_basisIndep`.
The latter is proven by considering
the base change of the `R`-linear map `φ : L →ₗ[R] End R M`
to the multivariate polynomial ring `MvPolynomial ι R`,
and showing that `polyCharpolyAux φ` is equal to the characteristic polynomial of this base change.
The proof concludes because characteristic polynomials are independent of the chosen basis.
## References
* [barnes1967]: "On Cartan subalgebras of Lie algebras" by D.W. Barnes.
-/
open scoped Matrix
namespace Matrix
variable {m n o R S : Type*}
variable [Fintype n] [Fintype o] [CommSemiring R] [CommSemiring S]
open MvPolynomial
/-- Let `M` be an `(m × n)`-matrix over `R`.
Then `Matrix.toMvPolynomial M` is the family (indexed by `i : m`)
of multivariate polynomials in `n` variables over `R` that evaluates on `c : n → R`
to the dot product of the `i`-th row of `M` with `c`:
`Matrix.toMvPolynomial M i` is the sum of the monomials `C (M i j) * X j`. -/
noncomputable
def toMvPolynomial (M : Matrix m n R) (i : m) : MvPolynomial n R :=
∑ j, monomial (.single j 1) (M i j)
lemma toMvPolynomial_eval_eq_apply (M : Matrix m n R) (i : m) (c : n → R) :
eval c (M.toMvPolynomial i) = (M *ᵥ c) i := by
simp only [toMvPolynomial, map_sum, eval_monomial, pow_zero, Finsupp.prod_single_index, pow_one,
mulVec, dotProduct]
lemma toMvPolynomial_map (f : R →+* S) (M : Matrix m n R) (i : m) :
(M.map f).toMvPolynomial i = MvPolynomial.map f (M.toMvPolynomial i) := by
simp only [toMvPolynomial, map_apply, map_sum, map_monomial]
lemma toMvPolynomial_isHomogeneous (M : Matrix m n R) (i : m) :
(M.toMvPolynomial i).IsHomogeneous 1 := by
apply MvPolynomial.IsHomogeneous.sum
rintro j -
apply MvPolynomial.isHomogeneous_monomial _ _
simp [Finsupp.degree, Finsupp.support_single_ne_zero _ one_ne_zero, Finset.sum_singleton,
Finsupp.single_eq_same]
lemma toMvPolynomial_totalDegree_le (M : Matrix m n R) (i : m) :
(M.toMvPolynomial i).totalDegree ≤ 1 := by
apply (toMvPolynomial_isHomogeneous _ _).totalDegree_le
@[simp]
lemma toMvPolynomial_constantCoeff (M : Matrix m n R) (i : m) :
constantCoeff (M.toMvPolynomial i) = 0 := by
simp only [toMvPolynomial, ← C_mul_X_eq_monomial, map_sum, map_mul, constantCoeff_X,
mul_zero, Finset.sum_const_zero]
@[simp]
lemma toMvPolynomial_zero : (0 : Matrix m n R).toMvPolynomial = 0 := by
ext; simp only [toMvPolynomial, zero_apply, map_zero, Finset.sum_const_zero, Pi.zero_apply]
@[simp]
lemma toMvPolynomial_one [DecidableEq n] : (1 : Matrix n n R).toMvPolynomial = X := by
ext i : 1
rw [toMvPolynomial, Finset.sum_eq_single i]
· simp only [one_apply_eq, ← C_mul_X_eq_monomial, C_1, one_mul]
· rintro j - hj
simp only [one_apply_ne hj.symm, map_zero]
· intro h
exact (h (Finset.mem_univ _)).elim
lemma toMvPolynomial_add (M N : Matrix m n R) :
(M + N).toMvPolynomial = M.toMvPolynomial + N.toMvPolynomial := by
ext i : 1
simp only [toMvPolynomial, add_apply, map_add, Finset.sum_add_distrib, Pi.add_apply]
lemma toMvPolynomial_mul (M : Matrix m n R) (N : Matrix n o R) (i : m) :
(M * N).toMvPolynomial i = bind₁ N.toMvPolynomial (M.toMvPolynomial i) := by
simp only [toMvPolynomial, mul_apply, map_sum, Finset.sum_comm (γ := o), bind₁, aeval,
AlgHom.coe_mk, coe_eval₂Hom, eval₂_monomial, algebraMap_apply, Algebra.id.map_eq_id,
RingHom.id_apply, C_apply, pow_zero, Finsupp.prod_single_index, pow_one, Finset.mul_sum,
monomial_mul, zero_add]
end Matrix
namespace LinearMap
open MvPolynomial
section
variable {R M₁ M₂ ι₁ ι₂ : Type*}
variable [CommRing R] [AddCommGroup M₁] [AddCommGroup M₂]
variable [Module R M₁] [Module R M₂]
variable [Fintype ι₁] [Finite ι₂]
variable [DecidableEq ι₁]
variable (b₁ : Basis ι₁ R M₁) (b₂ : Basis ι₂ R M₂)
/-- Let `f : M₁ →ₗ[R] M₂` be an `R`-linear map
between modules `M₁` and `M₂` with bases `b₁` and `b₂` respectively.
Then `LinearMap.toMvPolynomial b₁ b₂ f` is the family of multivariate polynomials over `R`
that evaluates on an element `x` of `M₁` (represented on the basis `b₁`)
to the element `f x` of `M₂` (represented on the basis `b₂`). -/
noncomputable
def toMvPolynomial (f : M₁ →ₗ[R] M₂) (i : ι₂) :
MvPolynomial ι₁ R :=
(toMatrix b₁ b₂ f).toMvPolynomial i
lemma toMvPolynomial_eval_eq_apply (f : M₁ →ₗ[R] M₂) (i : ι₂) (c : ι₁ →₀ R) :
eval c (f.toMvPolynomial b₁ b₂ i) = b₂.repr (f (b₁.repr.symm c)) i := by
rw [toMvPolynomial, Matrix.toMvPolynomial_eval_eq_apply,
← LinearMap.toMatrix_mulVec_repr b₁ b₂, LinearEquiv.apply_symm_apply]
open Algebra.TensorProduct in
lemma toMvPolynomial_baseChange (f : M₁ →ₗ[R] M₂) (i : ι₂) (A : Type*) [CommRing A] [Algebra R A] :
(f.baseChange A).toMvPolynomial (basis A b₁) (basis A b₂) i =
MvPolynomial.map (algebraMap R A) (f.toMvPolynomial b₁ b₂ i) := by
simp only [toMvPolynomial, toMatrix_baseChange, Matrix.toMvPolynomial_map]
lemma toMvPolynomial_isHomogeneous (f : M₁ →ₗ[R] M₂) (i : ι₂) :
(f.toMvPolynomial b₁ b₂ i).IsHomogeneous 1 :=
Matrix.toMvPolynomial_isHomogeneous _ _
lemma toMvPolynomial_totalDegree_le (f : M₁ →ₗ[R] M₂) (i : ι₂) :
(f.toMvPolynomial b₁ b₂ i).totalDegree ≤ 1 :=
Matrix.toMvPolynomial_totalDegree_le _ _
@[simp]
lemma toMvPolynomial_constantCoeff (f : M₁ →ₗ[R] M₂) (i : ι₂) :
constantCoeff (f.toMvPolynomial b₁ b₂ i) = 0 :=
Matrix.toMvPolynomial_constantCoeff _ _
@[simp]
lemma toMvPolynomial_zero : (0 : M₁ →ₗ[R] M₂).toMvPolynomial b₁ b₂ = 0 := by
unfold toMvPolynomial; simp only [map_zero, Matrix.toMvPolynomial_zero]
@[simp]
lemma toMvPolynomial_id : (id : M₁ →ₗ[R] M₁).toMvPolynomial b₁ b₁ = X := by
unfold toMvPolynomial; simp only [toMatrix_id, Matrix.toMvPolynomial_one]
lemma toMvPolynomial_add (f g : M₁ →ₗ[R] M₂) :
(f + g).toMvPolynomial b₁ b₂ = f.toMvPolynomial b₁ b₂ + g.toMvPolynomial b₁ b₂ := by
unfold toMvPolynomial; simp only [map_add, Matrix.toMvPolynomial_add]
end
variable {R M₁ M₂ M₃ ι₁ ι₂ ι₃ : Type*}
variable [CommRing R] [AddCommGroup M₁] [AddCommGroup M₂] [AddCommGroup M₃]
variable [Module R M₁] [Module R M₂] [Module R M₃]
variable [Fintype ι₁] [Fintype ι₂] [Finite ι₃]
variable [DecidableEq ι₁] [DecidableEq ι₂]
variable (b₁ : Basis ι₁ R M₁) (b₂ : Basis ι₂ R M₂) (b₃ : Basis ι₃ R M₃)
lemma toMvPolynomial_comp (g : M₂ →ₗ[R] M₃) (f : M₁ →ₗ[R] M₂) (i : ι₃) :
(g ∘ₗ f).toMvPolynomial b₁ b₃ i =
bind₁ (f.toMvPolynomial b₁ b₂) (g.toMvPolynomial b₂ b₃ i) := by
simp only [toMvPolynomial, toMatrix_comp b₁ b₂ b₃, Matrix.toMvPolynomial_mul]
rfl
end LinearMap
variable {R L M n ι ι' ιM : Type*}
variable [CommRing R] [AddCommGroup L] [Module R L] [AddCommGroup M] [Module R M]
variable (φ : L →ₗ[R] Module.End R M)
variable [Fintype ι] [Fintype ι'] [Fintype ιM] [DecidableEq ι] [DecidableEq ι']
namespace LinearMap
section aux
variable [DecidableEq ιM] (b : Basis ι R L) (bₘ : Basis ιM R M)
open Matrix
/-- (Implementation detail, see `LinearMap.polyCharpoly`.)
Let `L` and `M` be finite free modules over `R`,
and let `φ : L →ₗ[R] Module.End R M` be a linear map.
Let `b` be a basis of `L` and `bₘ` a basis of `M`.
Then `LinearMap.polyCharpolyAux φ b bₘ` is the polynomial that evaluates on elements `x` of `L`
to the characteristic polynomial of `φ x` acting on `M`.
This definition does not depend on the choice of `bₘ`
(see `LinearMap.polyCharpolyAux_basisIndep`). -/
noncomputable
def polyCharpolyAux : Polynomial (MvPolynomial ι R) :=
(charpoly.univ R ιM).map <| MvPolynomial.bind₁ (φ.toMvPolynomial b bₘ.end)
open Algebra.TensorProduct MvPolynomial in
lemma polyCharpolyAux_baseChange (A : Type*) [CommRing A] [Algebra R A] :
polyCharpolyAux (tensorProduct _ _ _ _ ∘ₗ φ.baseChange A) (basis A b) (basis A bₘ) =
(polyCharpolyAux φ b bₘ).map (MvPolynomial.map (algebraMap R A)) := by
simp only [polyCharpolyAux]
rw [← charpoly.univ_map_map _ (algebraMap R A)]
simp only [Polynomial.map_map]
congr 1
apply ringHom_ext
· intro r
simp only [RingHom.coe_comp, RingHom.coe_coe, Function.comp_apply, map_C, bind₁_C_right]
· rintro ij
simp only [RingHom.coe_comp, RingHom.coe_coe, Function.comp_apply, map_X, bind₁_X_right]
classical
rw [toMvPolynomial_comp _ (basis A (Basis.end bₘ)), ← toMvPolynomial_baseChange]
suffices toMvPolynomial (M₂ := (Module.End A (TensorProduct R A M)))
(basis A bₘ.end) (basis A bₘ).end (tensorProduct R A M M) ij = X ij by
rw [this, bind₁_X_right]
simp only [toMvPolynomial, Matrix.toMvPolynomial]
suffices ∀ kl,
(toMatrix (basis A bₘ.end) (basis A bₘ).end) (tensorProduct R A M M) ij kl =
if kl = ij then 1 else 0 by
rw [Finset.sum_eq_single ij]
· rw [this, if_pos rfl, X]
· rintro kl - H
rw [this, if_neg H, map_zero]
· intro h
exact (h (Finset.mem_univ _)).elim
intro kl
rw [toMatrix_apply, tensorProduct, TensorProduct.AlgebraTensorModule.lift_apply,
basis_apply, TensorProduct.lift.tmul, coe_restrictScalars]
dsimp only [coe_mk, AddHom.coe_mk, smul_apply, baseChangeHom_apply]
rw [one_smul, Basis.baseChange_end, Basis.repr_self_apply]
open LinearMap in
lemma polyCharpolyAux_map_eq_toMatrix_charpoly (x : L) :
(polyCharpolyAux φ b bₘ).map (MvPolynomial.eval (b.repr x)) =
(toMatrix bₘ bₘ (φ x)).charpoly := by
rw [polyCharpolyAux, Polynomial.map_map, ← MvPolynomial.eval₂Hom_C_eq_bind₁,
MvPolynomial.comp_eval₂Hom, charpoly.univ_map_eval₂Hom]
congr
ext
rw [of_apply, Function.curry_apply, toMvPolynomial_eval_eq_apply, LinearEquiv.symm_apply_apply]
rfl
open LinearMap in
lemma polyCharpolyAux_eval_eq_toMatrix_charpoly_coeff (x : L) (i : ℕ) :
MvPolynomial.eval (b.repr x) ((polyCharpolyAux φ b bₘ).coeff i) =
(toMatrix bₘ bₘ (φ x)).charpoly.coeff i := by
simp [← polyCharpolyAux_map_eq_toMatrix_charpoly φ b bₘ x]
@[simp]
lemma polyCharpolyAux_map_eq_charpoly [Module.Finite R M] [Module.Free R M]
(x : L) :
(polyCharpolyAux φ b bₘ).map (MvPolynomial.eval (b.repr x)) = (φ x).charpoly := by
nontriviality R
rw [polyCharpolyAux_map_eq_toMatrix_charpoly, LinearMap.charpoly_toMatrix]
@[simp]
lemma polyCharpolyAux_coeff_eval [Module.Finite R M] [Module.Free R M] (x : L) (i : ℕ) :
MvPolynomial.eval (b.repr x) ((polyCharpolyAux φ b bₘ).coeff i) = (φ x).charpoly.coeff i := by
nontriviality R
rw [← polyCharpolyAux_map_eq_charpoly φ b bₘ x, Polynomial.coeff_map]
lemma polyCharpolyAux_map_eval [Module.Finite R M] [Module.Free R M]
(x : ι → R) :
(polyCharpolyAux φ b bₘ).map (MvPolynomial.eval x) =
(φ (b.repr.symm (Finsupp.equivFunOnFinite.symm x))).charpoly := by
simp only [← polyCharpolyAux_map_eq_charpoly φ b bₘ, LinearEquiv.apply_symm_apply,
Finsupp.equivFunOnFinite, Equiv.coe_fn_symm_mk, Finsupp.coe_mk]
open Algebra.TensorProduct TensorProduct in
lemma polyCharpolyAux_map_aeval
(A : Type*) [CommRing A] [Algebra R A] [Module.Finite A (A ⊗[R] M)] [Module.Free A (A ⊗[R] M)]
(x : ι → A) :
(polyCharpolyAux φ b bₘ).map (MvPolynomial.aeval x).toRingHom =
LinearMap.charpoly ((tensorProduct R A M M).comp (baseChange A φ)
((basis A b).repr.symm (Finsupp.equivFunOnFinite.symm x))) := by
rw [← polyCharpolyAux_map_eval (tensorProduct R A M M ∘ₗ baseChange A φ) _ (basis A bₘ),
polyCharpolyAux_baseChange, Polynomial.map_map]
congr
exact DFunLike.ext _ _ fun f ↦ (MvPolynomial.eval_map (algebraMap R A) x f).symm
open Algebra.TensorProduct MvPolynomial in
/-- `LinearMap.polyCharpolyAux` is independent of the choice of basis of the target module.
Proof strategy:
1. Rewrite `polyCharpolyAux` as the (honest, ordinary) characteristic polynomial
of the basechange of `φ` to the multivariate polynomial ring `MvPolynomial ι R`.
2. Use that the characteristic polynomial of a linear map is independent of the choice of basis.
This independence result is used transitively via
`LinearMap.polyCharpolyAux_map_aeval` and `LinearMap.polyCharpolyAux_map_eq_charpoly`. -/
lemma polyCharpolyAux_basisIndep {ιM' : Type*} [Fintype ιM'] [DecidableEq ιM']
(bₘ' : Basis ιM' R M) :
polyCharpolyAux φ b bₘ = polyCharpolyAux φ b bₘ' := by
let f : Polynomial (MvPolynomial ι R) → Polynomial (MvPolynomial ι R) :=
Polynomial.map (MvPolynomial.aeval X).toRingHom
have hf : Function.Injective f := by
simp only [f, aeval_X_left, AlgHom.toRingHom_eq_coe, AlgHom.id_toRingHom, Polynomial.map_id]
exact Polynomial.map_injective (RingHom.id _) Function.injective_id
apply hf
let _h1 : Module.Finite (MvPolynomial ι R) (TensorProduct R (MvPolynomial ι R) M) :=
Module.Finite.of_basis (basis (MvPolynomial ι R) bₘ)
let _h2 : Module.Free (MvPolynomial ι R) (TensorProduct R (MvPolynomial ι R) M) :=
Module.Free.of_basis (basis (MvPolynomial ι R) bₘ)
simp only [f, polyCharpolyAux_map_aeval, polyCharpolyAux_map_aeval]
end aux
open Module Matrix
variable [Module.Free R M] [Module.Finite R M] (b : Basis ι R L)
/-- Let `L` and `M` be finite free modules over `R`,
and let `φ : L →ₗ[R] Module.End R M` be a linear family of endomorphisms.
Let `b` be a basis of `L` and `bₘ` a basis of `M`.
Then `LinearMap.polyCharpoly φ b` is the polynomial that evaluates on elements `x` of `L`
to the characteristic polynomial of `φ x` acting on `M`. -/
noncomputable
def polyCharpoly : Polynomial (MvPolynomial ι R) :=
φ.polyCharpolyAux b (Module.Free.chooseBasis R M)
lemma polyCharpoly_eq_of_basis [DecidableEq ιM] (bₘ : Basis ιM R M) :
polyCharpoly φ b =
(charpoly.univ R ιM).map (MvPolynomial.bind₁ (φ.toMvPolynomial b bₘ.end)) := by
rw [polyCharpoly, φ.polyCharpolyAux_basisIndep b (Module.Free.chooseBasis R M) bₘ,
polyCharpolyAux]
lemma polyCharpoly_monic : (polyCharpoly φ b).Monic :=
(charpoly.univ_monic R _).map _
lemma polyCharpoly_ne_zero [Nontrivial R] : (polyCharpoly φ b) ≠ 0 :=
(polyCharpoly_monic _ _).ne_zero
@[simp]
lemma polyCharpoly_natDegree [Nontrivial R] :
(polyCharpoly φ b).natDegree = finrank R M := by
rw [polyCharpoly, polyCharpolyAux, (charpoly.univ_monic _ _).natDegree_map,
charpoly.univ_natDegree, finrank_eq_card_chooseBasisIndex]
lemma polyCharpoly_coeff_isHomogeneous (i j : ℕ) (hij : i + j = finrank R M) [Nontrivial R] :
((polyCharpoly φ b).coeff i).IsHomogeneous j := by
rw [finrank_eq_card_chooseBasisIndex] at hij
rw [polyCharpoly, polyCharpolyAux, Polynomial.coeff_map, ← one_mul j]
apply (charpoly.univ_coeff_isHomogeneous _ _ _ _ hij).eval₂
· exact fun r ↦ MvPolynomial.isHomogeneous_C _ _
· exact LinearMap.toMvPolynomial_isHomogeneous _ _ _
open Algebra.TensorProduct MvPolynomial in
lemma polyCharpoly_baseChange (A : Type*) [CommRing A] [Algebra R A] :
polyCharpoly (tensorProduct _ _ _ _ ∘ₗ φ.baseChange A) (basis A b) =
(polyCharpoly φ b).map (MvPolynomial.map (algebraMap R A)) := by
unfold polyCharpoly
rw [← φ.polyCharpolyAux_baseChange]
apply polyCharpolyAux_basisIndep
@[simp]
lemma polyCharpoly_map_eq_charpoly (x : L) :
(polyCharpoly φ b).map (MvPolynomial.eval (b.repr x)) = (φ x).charpoly := by
rw [polyCharpoly, polyCharpolyAux_map_eq_charpoly]
@[simp]
lemma polyCharpoly_coeff_eval (x : L) (i : ℕ) :
MvPolynomial.eval (b.repr x) ((polyCharpoly φ b).coeff i) = (φ x).charpoly.coeff i := by
rw [polyCharpoly, polyCharpolyAux_coeff_eval]
lemma polyCharpoly_coeff_eq_zero_of_basis (b : Basis ι R L) (b' : Basis ι' R L) (k : ℕ)
(H : (polyCharpoly φ b).coeff k = 0) :
(polyCharpoly φ b').coeff k = 0 := by
rw [polyCharpoly, polyCharpolyAux, Polynomial.coeff_map] at H ⊢
set B := (Module.Free.chooseBasis R M).end
set g := toMvPolynomial b' b LinearMap.id
apply_fun (MvPolynomial.bind₁ g) at H
have : toMvPolynomial b' B φ = fun i ↦ (MvPolynomial.bind₁ g) (toMvPolynomial b B φ i) :=
funext <| toMvPolynomial_comp b' b B φ LinearMap.id
rwa [map_zero, RingHom.coe_coe, MvPolynomial.bind₁_bind₁, ← this] at H
lemma polyCharpoly_coeff_eq_zero_iff_of_basis (b : Basis ι R L) (b' : Basis ι' R L) (k : ℕ) :
(polyCharpoly φ b).coeff k = 0 ↔ (polyCharpoly φ b').coeff k = 0 := by
constructor <;> apply polyCharpoly_coeff_eq_zero_of_basis
section aux
/-- (Implementation detail, see `LinearMap.nilRank`.)
Let `L` and `M` be finite free modules over `R`,
and let `φ : L →ₗ[R] Module.End R M` be a linear family of endomorphisms.
Then `LinearMap.nilRankAux φ b` is the smallest index
at which `LinearMap.polyCharpoly φ b` has a non-zero coefficient.
This number does not depend on the choice of `b`, see `nilRankAux_basis_indep`. -/
noncomputable
def nilRankAux (φ : L →ₗ[R] Module.End R M) (b : Basis ι R L) : ℕ :=
(polyCharpoly φ b).natTrailingDegree
lemma polyCharpoly_coeff_nilRankAux_ne_zero [Nontrivial R] :
(polyCharpoly φ b).coeff (nilRankAux φ b) ≠ 0 := by
apply Polynomial.trailingCoeff_nonzero_iff_nonzero.mpr
apply polyCharpoly_ne_zero
lemma nilRankAux_le [Nontrivial R] (b : Basis ι R L) (b' : Basis ι' R L) :
nilRankAux φ b ≤ nilRankAux φ b' := by
apply Polynomial.natTrailingDegree_le_of_ne_zero
rw [Ne, (polyCharpoly_coeff_eq_zero_iff_of_basis φ b b' _).not]
apply polyCharpoly_coeff_nilRankAux_ne_zero
lemma nilRankAux_basis_indep [Nontrivial R] (b : Basis ι R L) (b' : Basis ι' R L) :
nilRankAux φ b = (polyCharpoly φ b').natTrailingDegree := by
apply le_antisymm <;> apply nilRankAux_le
end aux
variable [Module.Finite R L] [Module.Free R L]
/-- Let `L` and `M` be finite free modules over `R`,
and let `φ : L →ₗ[R] Module.End R M` be a linear family of endomorphisms.
Then `LinearMap.nilRank φ b` is the smallest index
at which `LinearMap.polyCharpoly φ b` has a non-zero coefficient.
This number does not depend on the choice of `b`,
see `LinearMap.nilRank_eq_polyCharpoly_natTrailingDegree`. -/
noncomputable
def nilRank (φ : L →ₗ[R] Module.End R M) : ℕ :=
nilRankAux φ (Module.Free.chooseBasis R L)
section
variable [Nontrivial R]
lemma nilRank_eq_polyCharpoly_natTrailingDegree (b : Basis ι R L) :
nilRank φ = (polyCharpoly φ b).natTrailingDegree := by
apply nilRankAux_basis_indep
lemma polyCharpoly_coeff_nilRank_ne_zero :
(polyCharpoly φ b).coeff (nilRank φ) ≠ 0 := by
rw [nilRank_eq_polyCharpoly_natTrailingDegree _ b]
apply polyCharpoly_coeff_nilRankAux_ne_zero
open Module Module.Free
lemma nilRank_le_card {ι : Type*} [Fintype ι] (b : Basis ι R M) : nilRank φ ≤ Fintype.card ι := by
apply Polynomial.natTrailingDegree_le_of_ne_zero
rw [← Module.finrank_eq_card_basis b, ← polyCharpoly_natDegree φ (chooseBasis R L),
Polynomial.coeff_natDegree, (polyCharpoly_monic _ _).leadingCoeff]
apply one_ne_zero
lemma nilRank_le_finrank : nilRank φ ≤ finrank R M := by
simpa only [finrank_eq_card_chooseBasisIndex R M] using nilRank_le_card φ (chooseBasis R M)
lemma nilRank_le_natTrailingDegree_charpoly (x : L) :
nilRank φ ≤ (φ x).charpoly.natTrailingDegree := by
apply Polynomial.natTrailingDegree_le_of_ne_zero
intro h
apply_fun (MvPolynomial.eval ((chooseBasis R L).repr x)) at h
rw [polyCharpoly_coeff_eval, map_zero] at h
apply Polynomial.trailingCoeff_nonzero_iff_nonzero.mpr _ h
apply (LinearMap.charpoly_monic _).ne_zero
end
/-- Let `L` and `M` be finite free modules over `R`,
and let `φ : L →ₗ[R] Module.End R M` be a linear family of endomorphisms,
and denote `n := nilRank φ`.
An element `x : L` is *nil-regular* with respect to `φ`
if the `n`-th coefficient of the characteristic polynomial of `φ x` is non-zero. -/
def IsNilRegular (x : L) : Prop :=
Polynomial.coeff (φ x).charpoly (nilRank φ) ≠ 0
variable (x : L)
lemma isNilRegular_def :
IsNilRegular φ x ↔ (Polynomial.coeff (φ x).charpoly (nilRank φ) ≠ 0) := Iff.rfl
lemma isNilRegular_iff_coeff_polyCharpoly_nilRank_ne_zero :
IsNilRegular φ x ↔
MvPolynomial.eval (b.repr x)
((polyCharpoly φ b).coeff (nilRank φ)) ≠ 0 := by
rw [IsNilRegular, polyCharpoly_coeff_eval]
| lemma isNilRegular_iff_natTrailingDegree_charpoly_eq_nilRank [Nontrivial R] :
IsNilRegular φ x ↔ (φ x).charpoly.natTrailingDegree = nilRank φ := by
rw [isNilRegular_def]
constructor
· intro h
exact le_antisymm
(Polynomial.natTrailingDegree_le_of_ne_zero h)
(nilRank_le_natTrailingDegree_charpoly φ x)
· intro h
rw [← h]
apply Polynomial.trailingCoeff_nonzero_iff_nonzero.mpr
apply (LinearMap.charpoly_monic _).ne_zero
| Mathlib/Algebra/Module/LinearMap/Polynomial.lean | 520 | 531 |
/-
Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import Mathlib.Combinatorics.SimpleGraph.Path
import Mathlib.Combinatorics.SimpleGraph.Operations
import Mathlib.Data.Finset.Pairwise
import Mathlib.Data.Fintype.Pigeonhole
import Mathlib.Data.Fintype.Powerset
import Mathlib.Data.Nat.Lattice
import Mathlib.SetTheory.Cardinal.Finite
/-!
# Graph cliques
This file defines cliques in simple graphs.
A clique is a set of vertices that are pairwise adjacent.
## Main declarations
* `SimpleGraph.IsClique`: Predicate for a set of vertices to be a clique.
* `SimpleGraph.IsNClique`: Predicate for a set of vertices to be an `n`-clique.
* `SimpleGraph.cliqueFinset`: Finset of `n`-cliques of a graph.
* `SimpleGraph.CliqueFree`: Predicate for a graph to have no `n`-cliques.
-/
open Finset Fintype Function SimpleGraph.Walk
namespace SimpleGraph
variable {α β : Type*} (G H : SimpleGraph α)
/-! ### Cliques -/
section Clique
variable {s t : Set α}
/-- A clique in a graph is a set of vertices that are pairwise adjacent. -/
abbrev IsClique (s : Set α) : Prop :=
s.Pairwise G.Adj
theorem isClique_iff : G.IsClique s ↔ s.Pairwise G.Adj :=
Iff.rfl
/-- A clique is a set of vertices whose induced graph is complete. -/
theorem isClique_iff_induce_eq : G.IsClique s ↔ G.induce s = ⊤ := by
rw [isClique_iff]
constructor
· intro h
ext ⟨v, hv⟩ ⟨w, hw⟩
simp only [comap_adj, Subtype.coe_mk, top_adj, Ne, Subtype.mk_eq_mk]
exact ⟨Adj.ne, h hv hw⟩
· intro h v hv w hw hne
have h2 : (G.induce s).Adj ⟨v, hv⟩ ⟨w, hw⟩ = _ := rfl
conv_lhs at h2 => rw [h]
simp only [top_adj, ne_eq, Subtype.mk.injEq, eq_iff_iff] at h2
exact h2.1 hne
instance [DecidableEq α] [DecidableRel G.Adj] {s : Finset α} : Decidable (G.IsClique s) :=
decidable_of_iff' _ G.isClique_iff
variable {G H} {a b : α}
lemma isClique_empty : G.IsClique ∅ := by simp
lemma isClique_singleton (a : α) : G.IsClique {a} := by simp
theorem IsClique.of_subsingleton {G : SimpleGraph α} (hs : s.Subsingleton) : G.IsClique s :=
hs.pairwise G.Adj
lemma isClique_pair : G.IsClique {a, b} ↔ a ≠ b → G.Adj a b := Set.pairwise_pair_of_symmetric G.symm
@[simp]
lemma isClique_insert : G.IsClique (insert a s) ↔ G.IsClique s ∧ ∀ b ∈ s, a ≠ b → G.Adj a b :=
Set.pairwise_insert_of_symmetric G.symm
lemma isClique_insert_of_not_mem (ha : a ∉ s) :
G.IsClique (insert a s) ↔ G.IsClique s ∧ ∀ b ∈ s, G.Adj a b :=
Set.pairwise_insert_of_symmetric_of_not_mem G.symm ha
lemma IsClique.insert (hs : G.IsClique s) (h : ∀ b ∈ s, a ≠ b → G.Adj a b) :
G.IsClique (insert a s) := hs.insert_of_symmetric G.symm h
theorem IsClique.mono (h : G ≤ H) : G.IsClique s → H.IsClique s := Set.Pairwise.mono' h
theorem IsClique.subset (h : t ⊆ s) : G.IsClique s → G.IsClique t := Set.Pairwise.mono h
@[simp]
theorem isClique_bot_iff : (⊥ : SimpleGraph α).IsClique s ↔ (s : Set α).Subsingleton :=
Set.pairwise_bot_iff
alias ⟨IsClique.subsingleton, _⟩ := isClique_bot_iff
protected theorem IsClique.map (h : G.IsClique s) {f : α ↪ β} : (G.map f).IsClique (f '' s) := by
rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ hab
exact ⟨a, b, h ha hb <| ne_of_apply_ne _ hab, rfl, rfl⟩
theorem isClique_map_iff_of_nontrivial {f : α ↪ β} {t : Set β} (ht : t.Nontrivial) :
(G.map f).IsClique t ↔ ∃ (s : Set α), G.IsClique s ∧ f '' s = t := by
refine ⟨fun h ↦ ⟨f ⁻¹' t, ?_, ?_⟩, by rintro ⟨x, hs, rfl⟩; exact hs.map⟩
· rintro x (hx : f x ∈ t) y (hy : f y ∈ t) hne
obtain ⟨u,v, huv, hux, hvy⟩ := h hx hy (by simpa)
rw [EmbeddingLike.apply_eq_iff_eq] at hux hvy
rwa [← hux, ← hvy]
rw [Set.image_preimage_eq_iff]
intro x hxt
obtain ⟨y,hyt, hyne⟩ := ht.exists_ne x
obtain ⟨u,v, -, rfl, rfl⟩ := h hyt hxt hyne
exact Set.mem_range_self _
theorem isClique_map_iff {f : α ↪ β} {t : Set β} :
(G.map f).IsClique t ↔ t.Subsingleton ∨ ∃ (s : Set α), G.IsClique s ∧ f '' s = t := by
obtain (ht | ht) := t.subsingleton_or_nontrivial
· simp [IsClique.of_subsingleton, ht]
simp [isClique_map_iff_of_nontrivial ht, ht.not_subsingleton]
@[simp] theorem isClique_map_image_iff {f : α ↪ β} :
(G.map f).IsClique (f '' s) ↔ G.IsClique s := by
rw [isClique_map_iff, f.injective.subsingleton_image_iff]
obtain (hs | hs) := s.subsingleton_or_nontrivial
· simp [hs, IsClique.of_subsingleton]
simp [or_iff_right hs.not_subsingleton, Set.image_eq_image f.injective]
variable {f : α ↪ β} {t : Finset β}
theorem isClique_map_finset_iff_of_nontrivial (ht : t.Nontrivial) :
(G.map f).IsClique t ↔ ∃ (s : Finset α), G.IsClique s ∧ s.map f = t := by
constructor
· rw [isClique_map_iff_of_nontrivial (by simpa)]
rintro ⟨s, hs, hst⟩
obtain ⟨s, rfl⟩ := Set.Finite.exists_finset_coe <|
(show s.Finite from Set.Finite.of_finite_image (by simp [hst]) f.injective.injOn)
exact ⟨s,hs, Finset.coe_inj.1 (by simpa)⟩
rintro ⟨s, hs, rfl⟩
simpa using hs.map (f := f)
theorem isClique_map_finset_iff :
(G.map f).IsClique t ↔ #t ≤ 1 ∨ ∃ (s : Finset α), G.IsClique s ∧ s.map f = t := by
obtain (ht | ht) := le_or_lt #t 1
· simp only [ht, true_or, iff_true]
exact IsClique.of_subsingleton <| card_le_one.1 ht
rw [isClique_map_finset_iff_of_nontrivial, ← not_lt]
· simp [ht, Finset.map_eq_image]
exact Finset.one_lt_card_iff_nontrivial.mp ht
protected theorem IsClique.finsetMap {f : α ↪ β} {s : Finset α} (h : G.IsClique s) :
(G.map f).IsClique (s.map f) := by
simpa
/-- If a set of vertices `A` is a clique in subgraph of `G` induced by a superset of `A`,
its embedding is a clique in `G`. -/
theorem IsClique.of_induce {S : Subgraph G} {F : Set α} {A : Set F}
(c : (S.induce F).coe.IsClique A) : G.IsClique (Subtype.val '' A) := by
simp only [Set.Pairwise, Set.mem_image, Subtype.exists, exists_and_right, exists_eq_right]
intro _ ⟨_, ainA⟩ _ ⟨_, binA⟩ anb
exact S.adj_sub (c ainA binA (Subtype.coe_ne_coe.mp anb)).2.2
lemma IsClique.sdiff_of_sup_edge {v w : α} {s : Set α} (hc : (G ⊔ edge v w).IsClique s) :
G.IsClique (s \ {v}) := by
intro _ hx _ hy hxy
have := hc hx.1 hy.1 hxy
simp_all [sup_adj, edge_adj]
lemma isClique_sup_edge_of_ne_sdiff {v w : α} {s : Set α} (h : v ≠ w ) (hv : G.IsClique (s \ {v}))
(hw : G.IsClique (s \ {w})) : (G ⊔ edge v w).IsClique s := by
intro x hx y hy hxy
by_cases h' : x ∈ s \ {v} ∧ y ∈ s \ {v} ∨ x ∈ s \ {w} ∧ y ∈ s \ {w}
· obtain (⟨hx, hy⟩ | ⟨hx, hy⟩) := h'
· exact hv.mono le_sup_left hx hy hxy
· exact hw.mono le_sup_left hx hy hxy
· exact Or.inr ⟨by by_cases x = v <;> aesop, hxy⟩
lemma isClique_sup_edge_of_ne_iff {v w : α} {s : Set α} (h : v ≠ w) :
(G ⊔ edge v w).IsClique s ↔ G.IsClique (s \ {v}) ∧ G.IsClique (s \ {w}) :=
⟨fun h' ↦ ⟨h'.sdiff_of_sup_edge, (edge_comm .. ▸ h').sdiff_of_sup_edge⟩,
fun h' ↦ isClique_sup_edge_of_ne_sdiff h h'.1 h'.2⟩
end Clique
/-! ### `n`-cliques -/
section NClique
variable {n : ℕ} {s : Finset α}
/-- An `n`-clique in a graph is a set of `n` vertices which are pairwise connected. -/
structure IsNClique (n : ℕ) (s : Finset α) : Prop where
isClique : G.IsClique s
card_eq : #s = n
theorem isNClique_iff : G.IsNClique n s ↔ G.IsClique s ∧ #s = n :=
⟨fun h ↦ ⟨h.1, h.2⟩, fun h ↦ ⟨h.1, h.2⟩⟩
instance [DecidableEq α] [DecidableRel G.Adj] {n : ℕ} {s : Finset α} :
Decidable (G.IsNClique n s) :=
decidable_of_iff' _ G.isNClique_iff
variable {G H} {a b c : α}
@[simp] lemma isNClique_empty : G.IsNClique n ∅ ↔ n = 0 := by simp [isNClique_iff, eq_comm]
@[simp]
lemma isNClique_singleton : G.IsNClique n {a} ↔ n = 1 := by simp [isNClique_iff, eq_comm]
theorem IsNClique.mono (h : G ≤ H) : G.IsNClique n s → H.IsNClique n s := by
simp_rw [isNClique_iff]
exact And.imp_left (IsClique.mono h)
protected theorem IsNClique.map (h : G.IsNClique n s) {f : α ↪ β} :
(G.map f).IsNClique n (s.map f) :=
⟨by rw [coe_map]; exact h.1.map, (card_map _).trans h.2⟩
theorem isNClique_map_iff (hn : 1 < n) {t : Finset β} {f : α ↪ β} :
(G.map f).IsNClique n t ↔ ∃ s : Finset α, G.IsNClique n s ∧ s.map f = t := by
rw [isNClique_iff, isClique_map_finset_iff, or_and_right,
or_iff_right (by rintro ⟨h', rfl⟩; exact h'.not_lt hn)]
constructor
· rintro ⟨⟨s, hs, rfl⟩, rfl⟩
simp [isNClique_iff, hs]
rintro ⟨s, hs, rfl⟩
simp [hs.card_eq, hs.isClique]
@[simp]
theorem isNClique_bot_iff : (⊥ : SimpleGraph α).IsNClique n s ↔ n ≤ 1 ∧ #s = n := by
rw [isNClique_iff, isClique_bot_iff]
refine and_congr_left ?_
rintro rfl
exact card_le_one.symm
@[simp]
theorem isNClique_zero : G.IsNClique 0 s ↔ s = ∅ := by
simp only [isNClique_iff, Finset.card_eq_zero, and_iff_right_iff_imp]; rintro rfl; simp
@[simp]
theorem isNClique_one : G.IsNClique 1 s ↔ ∃ a, s = {a} := by
simp only [isNClique_iff, card_eq_one, and_iff_right_iff_imp]; rintro ⟨a, rfl⟩; simp
section DecidableEq
variable [DecidableEq α]
protected theorem IsNClique.insert (hs : G.IsNClique n s) (h : ∀ b ∈ s, G.Adj a b) :
G.IsNClique (n + 1) (insert a s) := by
| constructor
· push_cast
exact hs.1.insert fun b hb _ => h _ hb
· rw [card_insert_of_not_mem fun ha => (h _ ha).ne rfl, hs.2]
lemma IsNClique.erase_of_mem (hs : G.IsNClique n s) (ha : a ∈ s) :
| Mathlib/Combinatorics/SimpleGraph/Clique.lean | 248 | 253 |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Bhavik Mehta, Stuart Presnell
-/
import Mathlib.Data.Nat.Factorial.Basic
import Mathlib.Order.Monotone.Defs
/-!
# Binomial coefficients
This file defines binomial coefficients and proves simple lemmas (i.e. those not
requiring more imports).
For the lemma that `n.choose k` counts the `k`-element-subsets of an `n`-element set,
see `Fintype.card_powersetCard` in `Mathlib.Data.Finset.Powerset`.
## Main definition and results
* `Nat.choose`: binomial coefficients, defined inductively
* `Nat.choose_eq_factorial_div_factorial`: a proof that `choose n k = n! / (k! * (n - k)!)`
* `Nat.choose_symm`: symmetry of binomial coefficients
* `Nat.choose_le_succ_of_lt_half_left`: `choose n k` is increasing for small values of `k`
* `Nat.choose_le_middle`: `choose n r` is maximised when `r` is `n/2`
* `Nat.descFactorial_eq_factorial_mul_choose`: Relates binomial coefficients to the descending
factorial. This is used to prove `Nat.choose_le_pow` and variants. We provide similar statements
for the ascending factorial.
* `Nat.multichoose`: whereas `choose` counts combinations, `multichoose` counts multicombinations.
The fact that this is indeed the correct counting function for multisets is proved in
`Sym.card_sym_eq_multichoose` in `Data.Sym.Card`.
* `Nat.multichoose_eq` : a proof that `multichoose n k = (n + k - 1).choose k`.
This is central to the "stars and bars" technique in informal mathematics, where we switch between
counting multisets of size `k` over an alphabet of size `n` to counting strings of `k` elements
("stars") separated by `n-1` dividers ("bars"). See `Data.Sym.Card` for more detail.
## Tags
binomial coefficient, combination, multicombination, stars and bars
-/
open Nat
namespace Nat
/-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial
coefficients. For the fact that this is the number of `k`-element-subsets of an `n`-element
set, see `Fintype.card_powersetCard`. -/
def choose : ℕ → ℕ → ℕ
| _, 0 => 1
| 0, _ + 1 => 0
| n + 1, k + 1 => choose n k + choose n (k + 1)
@[simp]
theorem choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n <;> rfl
@[simp]
theorem choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 :=
rfl
theorem choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) :=
rfl
theorem choose_succ_succ' (n k : ℕ) : choose (n + 1) (k + 1) = choose n k + choose n (k + 1) :=
rfl
theorem choose_succ_left (n k : ℕ) (hk : 0 < k) :
choose (n + 1) k = choose n (k - 1) + choose n k := by
obtain ⟨l, rfl⟩ : ∃ l, k = l + 1 := Nat.exists_eq_add_of_le' hk
rfl
theorem choose_succ_right (n k : ℕ) (hn : 0 < n) :
choose n (k + 1) = choose (n - 1) k + choose (n - 1) (k + 1) := by
obtain ⟨l, rfl⟩ : ∃ l, n = l + 1 := Nat.exists_eq_add_of_le' hn
rfl
theorem choose_eq_choose_pred_add {n k : ℕ} (hn : 0 < n) (hk : 0 < k) :
choose n k = choose (n - 1) (k - 1) + choose (n - 1) k := by
obtain ⟨l, rfl⟩ : ∃ l, k = l + 1 := Nat.exists_eq_add_of_le' hk
rw [choose_succ_right _ _ hn, Nat.add_one_sub_one]
theorem choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0
| _, 0, hk => absurd hk (Nat.not_lt_zero _)
| 0, _ + 1, _ => choose_zero_succ _
| n + 1, k + 1, hk => by
have hnk : n < k := lt_of_succ_lt_succ hk
have hnk1 : n < k + 1 := lt_of_succ_lt hk
rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1]
@[simp]
theorem choose_self (n : ℕ) : choose n n = 1 := by
induction n <;> simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)]
@[simp]
theorem choose_succ_self (n : ℕ) : choose n (succ n) = 0 :=
choose_eq_zero_of_lt (lt_succ_self _)
@[simp]
lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n <;> simp [*, choose, Nat.add_comm]
-- The `n+1`-st triangle number is `n` more than the `n`-th triangle number
theorem triangle_succ (n : ℕ) : (n + 1) * (n + 1 - 1) / 2 = n * (n - 1) / 2 + n := by
rw [← add_mul_div_left, Nat.mul_comm 2 n, ← Nat.mul_add, Nat.add_sub_cancel, Nat.mul_comm]
cases n <;> rfl; apply zero_lt_succ
/-- `choose n 2` is the `n`-th triangle number. -/
theorem choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := by
induction' n with n ih
· simp
· rw [triangle_succ n, choose, ih]
simp [Nat.add_comm]
theorem choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k
| 0, _, hk => by rw [Nat.eq_zero_of_le_zero hk]; decide
| n + 1, 0, _ => by simp
| _ + 1, _ + 1, hk => Nat.add_pos_left (choose_pos (le_of_succ_le_succ hk)) _
theorem choose_eq_zero_iff {n k : ℕ} : n.choose k = 0 ↔ n < k :=
⟨fun h => lt_of_not_ge (mt Nat.choose_pos h.symm.not_lt), Nat.choose_eq_zero_of_lt⟩
theorem succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k
| 0, 0 => by decide
| 0, k + 1 => by simp [choose]
| n + 1, 0 => by simp [choose, mul_succ, Nat.add_comm]
| n + 1, k + 1 => by
| rw [choose_succ_succ (succ n) (succ k), Nat.add_mul, ← succ_mul_choose_eq n, mul_succ, ←
succ_mul_choose_eq n, Nat.add_right_comm, ← Nat.mul_add, ← choose_succ_succ, ← succ_mul]
theorem choose_mul_factorial_mul_factorial : ∀ {n k}, k ≤ n → choose n k * k ! * (n - k)! = n !
| 0, _, hk => by simp [Nat.eq_zero_of_le_zero hk]
| n + 1, 0, _ => by simp
| n + 1, succ k, hk => by
rcases lt_or_eq_of_le hk with hk₁ | hk₁
· have h : choose n k * k.succ ! * (n - k)! = (k + 1) * n ! := by
rw [← choose_mul_factorial_mul_factorial (le_of_succ_le_succ hk)]
simp [factorial_succ, Nat.mul_comm, Nat.mul_left_comm, Nat.mul_assoc]
have h₁ : (n - k)! = (n - k) * (n - k.succ)! := by
rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), factorial_succ]
have h₂ : choose n (succ k) * k.succ ! * ((n - k) * (n - k.succ)!) = (n - k) * n ! := by
rw [← choose_mul_factorial_mul_factorial (le_of_lt_succ hk₁)]
simp [factorial_succ, Nat.mul_comm, Nat.mul_left_comm, Nat.mul_assoc]
have h₃ : k * n ! ≤ n * n ! := Nat.mul_le_mul_right _ (le_of_succ_le_succ hk)
rw [choose_succ_succ, Nat.add_mul, Nat.add_mul, succ_sub_succ, h, h₁, h₂, Nat.add_mul,
| Mathlib/Data/Nat/Choose/Basic.lean | 125 | 142 |
/-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Patrick Massot, Sébastien Gouëzel
-/
import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic
import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus
import Mathlib.MeasureTheory.Integral.IntervalIntegral.IntegrationByParts
deprecated_module (since := "2025-04-13")
| Mathlib/MeasureTheory/Integral/IntervalIntegral.lean | 981 | 986 | |
/-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Eric Rodriguez
-/
import Mathlib.Algebra.GroupWithZero.Action.Center
import Mathlib.GroupTheory.ClassEquation
import Mathlib.RingTheory.Polynomial.Cyclotomic.Eval
/-!
# Wedderburn's Little Theorem
This file proves Wedderburn's Little Theorem.
## Main Declarations
* `littleWedderburn`: a finite division ring is a field.
## Future work
A couple simple generalisations are possible:
* A finite ring is commutative iff all its nilpotents lie in the center.
[Chintala, Vineeth, *Sorry, the Nilpotents Are in the Center*][chintala2020]
* A ring is commutative if all its elements have finite order.
[Dolan, S. W., *A Proof of Jacobson's Theorem*][dolan1975]
When alternativity is added to Mathlib, one could formalise the Artin-Zorn theorem, which states
that any finite alternative division ring is in fact a field.
https://en.wikipedia.org/wiki/Artin%E2%80%93Zorn_theorem
If interested, generalisations to semifields could be explored. The theory of semi-vector spaces is
not clear, but assuming that such a theory could be found where every module considered in the
below proof is free, then the proof works nearly verbatim.
-/
open scoped Polynomial
open Fintype
/-! Everything in this namespace is internal to the proof of Wedderburn's little theorem. -/
namespace LittleWedderburn
variable (D : Type*) [DivisionRing D]
private def InductionHyp : Prop :=
∀ {R : Subring D}, R < ⊤ → ∀ ⦃x y⦄, x ∈ R → y ∈ R → x * y = y * x
namespace InductionHyp
open Module Polynomial
variable {D}
private def field (hD : InductionHyp D) {R : Subring D} (hR : R < ⊤)
[Fintype D] [DecidableEq D] [DecidablePred (· ∈ R)] :
Field R :=
{ show DivisionRing R from Fintype.divisionRingOfIsDomain R with
mul_comm := fun x y ↦ Subtype.ext <| hD hR x.2 y.2 }
/-- We prove that if every subring of `D` is central, then so is `D`. -/
private theorem center_eq_top [Finite D] (hD : InductionHyp D) : Subring.center D = ⊤ := by
classical
cases nonempty_fintype D
set Z := Subring.center D
-- We proceed by contradiction; that is, we assume the center is strictly smaller than `D`.
by_contra! hZ
letI : Field Z := hD.field hZ.lt_top
set q := card Z with card_Z
have hq : 1 < q := by rw [card_Z]; exact one_lt_card
let n := finrank Z D
have card_D : card D = q ^ n := Module.card_eq_pow_finrank
have h1qn : 1 ≤ q ^ n := by rw [← card_D]; exact card_pos
-- We go about this by looking at the class equation for `Dˣ`:
-- `q ^ n - 1 = q - 1 + ∑ x : conjugacy classes (D ∖ Dˣ), |x|`.
-- The next few lines gets the equation into basically this form over `ℤ`.
have key := Group.card_center_add_sum_card_noncenter_eq_card (Dˣ)
rw [card_congr (show _ ≃* Zˣ from Subgroup.centerUnitsEquivUnitsCenter D).toEquiv,
card_units, ← card_Z, card_units, card_D] at key
-- By properties of the cyclotomic function, we have that `Φₙ(q) ∣ q ^ n - 1`; however, when
-- `n ≠ 1`, then `¬Φₙ(q) | q - 1`; so if the sum over the conjugacy classes is divisible by
-- `Φₙ(q)`, then `n = 1`, and therefore the vector space is trivial, as desired.
let Φₙ := cyclotomic n ℤ
apply_fun (Nat.cast : ℕ → ℤ) at key
rw [Nat.cast_add, Nat.cast_sub h1qn, Nat.cast_sub hq.le, Nat.cast_one, Nat.cast_pow] at key
suffices Φₙ.eval ↑q ∣ ↑(∑ x ∈ (ConjClasses.noncenter Dˣ).toFinset, x.carrier.toFinset.card) by
have contra : Φₙ.eval _ ∣ _ := eval_dvd (cyclotomic.dvd_X_pow_sub_one n ℤ) (x := (q : ℤ))
rw [eval_sub, eval_pow, eval_X, eval_one, ← key, Int.dvd_add_left this] at contra
refine (Nat.le_of_dvd ?_ ?_).not_lt (sub_one_lt_natAbs_cyclotomic_eval (n := n) ?_ hq.ne')
· exact tsub_pos_of_lt hq
· convert Int.natAbs_dvd_natAbs.mpr contra
clear_value q
simp only [eq_comm, Int.natAbs_eq_iff, Nat.cast_sub hq.le, Nat.cast_one, neg_sub, true_or]
· by_contra! h
obtain ⟨x, hx⟩ := finrank_le_one_iff.mp h
refine not_le_of_lt hZ.lt_top (fun y _ ↦ Subring.mem_center_iff.mpr fun z ↦ ?_)
obtain ⟨r, rfl⟩ := hx y
obtain ⟨s, rfl⟩ := hx z
rw [smul_mul_smul_comm, smul_mul_smul_comm, mul_comm]
rw [Nat.cast_sum]
apply Finset.dvd_sum
rintro ⟨x⟩ hx
simp -zeta only [ConjClasses.quot_mk_eq_mk, Set.mem_toFinset] at hx ⊢
set Zx := Subring.centralizer ({↑x} : Set D)
-- The key thing is then to note that for all conjugacy classes `x`, `|x|` is given by
-- `|Dˣ| / |Zxˣ|`, where `Zx` is the centralizer of `x`; but `Zx` is an algebra over `Z`, and
-- therefore `|Zxˣ| = q ^ d - 1`, where `d` is the dimension of `D` as a vector space over `Z`.
-- We therefore get that `|x| = (q ^ n - 1) / (q ^ d - 1)`, and as `d` is a strict divisor of `n`,
-- we do have that `Φₙ(q) | (q ^ n - 1) / (q ^ d - 1)`; extending this over the whole sum
-- gives us the desired contradiction..
rw [Set.toFinset_card, ConjClasses.card_carrier, ← card_congr
(show Zxˣ ≃* _ from unitsCentralizerEquiv _ x).toEquiv, card_units, card_D]
have hZx : Zx ≠ ⊤ := by
by_contra! hZx
refine (ConjClasses.mk_bijOn (Dˣ)).mapsTo (Set.subset_center_units ?_) hx
exact Subring.centralizer_eq_top_iff_subset.mp hZx <| Set.mem_singleton _
letI : Field Zx := hD.field hZx.lt_top
letI : Algebra Z Zx := (Subring.inclusion <| Subring.center_le_centralizer {(x : D)}).toAlgebra
let d := finrank Z Zx
have card_Zx : card Zx = q ^ d := Module.card_eq_pow_finrank
have h1qd : 1 ≤ q ^ d := by rw [← card_Zx]; exact card_pos
haveI : IsScalarTower Z Zx D := ⟨fun x y z ↦ mul_assoc _ _ _⟩
rw [card_units, card_Zx, Int.natCast_div, Nat.cast_sub h1qd, Nat.cast_sub h1qn, Nat.cast_one,
Nat.cast_pow, Nat.cast_pow]
apply Int.dvd_div_of_mul_dvd
have aux : ∀ {k : ℕ}, ((X : ℤ[X]) ^ k - 1).eval ↑q = (q : ℤ) ^ k - 1 := by
simp only [eval_X, eval_one, eval_pow, eval_sub, eq_self_iff_true, forall_const]
rw [← aux, ← aux, ← eval_mul]
refine (evalRingHom ↑q).map_dvd (X_pow_sub_one_mul_cyclotomic_dvd_X_pow_sub_one_of_dvd ℤ ?_)
refine Nat.mem_properDivisors.mpr ⟨⟨_, (finrank_mul_finrank Z Zx D).symm⟩, ?_⟩
rw [← Nat.pow_lt_pow_iff_right hq, ← card_D, ← card_Zx]
obtain ⟨b, -, hb⟩ := SetLike.exists_of_lt hZx.lt_top
refine card_lt_of_injective_of_not_mem _ Subtype.val_injective (?_ : b ∉ _)
rintro ⟨b, rfl⟩
exact hb b.2
end InductionHyp
| private theorem center_eq_top [Finite D] : Subring.center D = ⊤ := by
classical
cases nonempty_fintype D
induction' hn : Fintype.card D using Nat.strong_induction_on with n IH generalizing D
apply InductionHyp.center_eq_top
intro R hR x y hx hy
suffices (⟨y, hy⟩ : R) ∈ Subring.center R by
rw [Subring.mem_center_iff] at this
simpa using this ⟨x, hx⟩
let R_dr : DivisionRing R := Fintype.divisionRingOfIsDomain R
rw [IH (Fintype.card R) _ R inferInstance rfl]
· trivial
rw [← hn, ← Subring.card_top D]
convert Set.card_lt_card hR
| Mathlib/RingTheory/LittleWedderburn.lean | 138 | 151 |
/-
Copyright (c) 2021 David Wärn,. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn, Kim Morrison
-/
import Mathlib.Combinatorics.Quiver.Prefunctor
import Mathlib.Logic.Lemmas
import Batteries.Data.List.Basic
/-!
# Paths in quivers
Given a quiver `V`, we define the type of paths from `a : V` to `b : V` as an inductive
family. We define composition of paths and the action of prefunctors on paths.
-/
open Function
universe v v₁ v₂ v₃ u u₁ u₂ u₃
namespace Quiver
/-- `Path a b` is the type of paths from `a` to `b` through the arrows of `G`. -/
inductive Path {V : Type u} [Quiver.{v} V] (a : V) : V → Sort max (u + 1) v
| nil : Path a a
| cons : ∀ {b c : V}, Path a b → (b ⟶ c) → Path a c
-- See issue https://github.com/leanprover/lean4/issues/2049
compile_inductive% Path
/-- An arrow viewed as a path of length one. -/
def Hom.toPath {V} [Quiver V] {a b : V} (e : a ⟶ b) : Path a b :=
Path.nil.cons e
namespace Path
variable {V : Type u} [Quiver V] {a b c d : V}
lemma nil_ne_cons (p : Path a b) (e : b ⟶ a) : Path.nil ≠ p.cons e :=
fun h => by injection h
lemma cons_ne_nil (p : Path a b) (e : b ⟶ a) : p.cons e ≠ Path.nil :=
fun h => by injection h
lemma obj_eq_of_cons_eq_cons {p : Path a b} {p' : Path a c}
{e : b ⟶ d} {e' : c ⟶ d} (h : p.cons e = p'.cons e') : b = c := by injection h
lemma heq_of_cons_eq_cons {p : Path a b} {p' : Path a c}
{e : b ⟶ d} {e' : c ⟶ d} (h : p.cons e = p'.cons e') : HEq p p' := by injection h
lemma hom_heq_of_cons_eq_cons {p : Path a b} {p' : Path a c}
{e : b ⟶ d} {e' : c ⟶ d} (h : p.cons e = p'.cons e') : HEq e e' := by injection h
/-- The length of a path is the number of arrows it uses. -/
def length {a : V} : ∀ {b : V}, Path a b → ℕ
| _, nil => 0
| _, cons p _ => p.length + 1
instance {a : V} : Inhabited (Path a a) :=
⟨nil⟩
@[simp]
theorem length_nil {a : V} : (nil : Path a a).length = 0 :=
rfl
@[simp]
theorem length_cons (a b c : V) (p : Path a b) (e : b ⟶ c) : (p.cons e).length = p.length + 1 :=
rfl
theorem eq_of_length_zero (p : Path a b) (hzero : p.length = 0) : a = b := by
cases p
· rfl
· cases Nat.succ_ne_zero _ hzero
theorem eq_nil_of_length_zero (p : Path a a) (hzero : p.length = 0) : p = nil := by
cases p
· rfl
· simp at hzero
/-- Composition of paths. -/
def comp {a b : V} : ∀ {c}, Path a b → Path b c → Path a c
| _, p, nil => p
| _, p, cons q e => (p.comp q).cons e
@[simp]
theorem comp_cons {a b c d : V} (p : Path a b) (q : Path b c) (e : c ⟶ d) :
p.comp (q.cons e) = (p.comp q).cons e :=
rfl
@[simp]
theorem comp_nil {a b : V} (p : Path a b) : p.comp Path.nil = p :=
rfl
@[simp]
theorem nil_comp {a : V} : ∀ {b} (p : Path a b), Path.nil.comp p = p
| _, nil => rfl
| _, cons p _ => by rw [comp_cons, nil_comp p]
@[simp]
theorem comp_assoc {a b c : V} :
∀ {d} (p : Path a b) (q : Path b c) (r : Path c d), (p.comp q).comp r = p.comp (q.comp r)
| _, _, _, nil => rfl
| _, p, q, cons r _ => by rw [comp_cons, comp_cons, comp_cons, comp_assoc p q r]
@[simp]
theorem length_comp (p : Path a b) : ∀ {c} (q : Path b c), (p.comp q).length = p.length + q.length
| _, nil => rfl
| _, cons _ _ => congr_arg Nat.succ (length_comp _ _)
theorem comp_inj {p₁ p₂ : Path a b} {q₁ q₂ : Path b c} (hq : q₁.length = q₂.length) :
p₁.comp q₁ = p₂.comp q₂ ↔ p₁ = p₂ ∧ q₁ = q₂ := by
refine ⟨fun h => ?_, by rintro ⟨rfl, rfl⟩; rfl⟩
induction q₁ with
| nil =>
rcases q₂ with _ | ⟨q₂, f₂⟩
· exact ⟨h, rfl⟩
· cases hq
| cons q₁ f₁ ih =>
rcases q₂ with _ | ⟨q₂, f₂⟩
· cases hq
· simp only [comp_cons, cons.injEq] at h
obtain rfl := h.1
| obtain ⟨rfl, rfl⟩ := ih (Nat.succ.inj hq) h.2.1.eq
rw [h.2.2.eq]
exact ⟨rfl, rfl⟩
theorem comp_inj' {p₁ p₂ : Path a b} {q₁ q₂ : Path b c} (h : p₁.length = p₂.length) :
p₁.comp q₁ = p₂.comp q₂ ↔ p₁ = p₂ ∧ q₁ = q₂ :=
⟨fun h_eq => (comp_inj <| Nat.add_left_cancel (n := p₂.length) <|
by simpa [h] using congr_arg length h_eq).1 h_eq,
by rintro ⟨rfl, rfl⟩; rfl⟩
theorem comp_injective_left (q : Path b c) : Injective fun p : Path a b => p.comp q :=
fun _ _ h => ((comp_inj rfl).1 h).1
| Mathlib/Combinatorics/Quiver/Path.lean | 123 | 134 |
/-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Filippo A. E. Nuccio
-/
import Mathlib.Algebra.EuclideanDomain.Basic
import Mathlib.RingTheory.FractionalIdeal.Basic
import Mathlib.RingTheory.IntegralClosure.IsIntegral.Basic
import Mathlib.RingTheory.LocalRing.Basic
import Mathlib.RingTheory.PrincipalIdealDomain
import Mathlib.Tactic.FieldSimp
/-!
# More operations on fractional ideals
## Main definitions
* `map` is the pushforward of a fractional ideal along an algebra morphism
Let `K` be the localization of `R` at `R⁰ = R \ {0}` (i.e. the field of fractions).
* `FractionalIdeal R⁰ K` is the type of fractional ideals in the field of fractions
* `Div (FractionalIdeal R⁰ K)` instance:
the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined)
## Main statement
* `isNoetherian` states that every fractional ideal of a noetherian integral domain is noetherian
## References
* https://en.wikipedia.org/wiki/Fractional_ideal
## Tags
fractional ideal, fractional ideals, invertible ideal
-/
open IsLocalization Pointwise nonZeroDivisors
namespace FractionalIdeal
open Set Submodule
variable {R : Type*} [CommRing R] {S : Submonoid R} {P : Type*} [CommRing P]
variable [Algebra R P]
section
variable {P' : Type*} [CommRing P'] [Algebra R P']
variable {P'' : Type*} [CommRing P''] [Algebra R P'']
theorem _root_.IsFractional.map (g : P →ₐ[R] P') {I : Submodule R P} :
IsFractional S I → IsFractional S (Submodule.map g.toLinearMap I)
| ⟨a, a_nonzero, hI⟩ =>
⟨a, a_nonzero, fun b hb => by
obtain ⟨b', b'_mem, hb'⟩ := Submodule.mem_map.mp hb
rw [AlgHom.toLinearMap_apply] at hb'
obtain ⟨x, hx⟩ := hI b' b'_mem
use x
rw [← g.commutes, hx, map_smul, hb']⟩
/-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/
def map (g : P →ₐ[R] P') : FractionalIdeal S P → FractionalIdeal S P' := fun I =>
⟨Submodule.map g.toLinearMap I, I.isFractional.map g⟩
@[simp, norm_cast]
theorem coe_map (g : P →ₐ[R] P') (I : FractionalIdeal S P) :
↑(map g I) = Submodule.map g.toLinearMap I :=
rfl
@[simp]
theorem mem_map {I : FractionalIdeal S P} {g : P →ₐ[R] P'} {y : P'} :
y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y :=
Submodule.mem_map
variable (I J : FractionalIdeal S P) (g : P →ₐ[R] P')
@[simp]
theorem map_id : I.map (AlgHom.id _ _) = I :=
coeToSubmodule_injective (Submodule.map_id (I : Submodule R P))
@[simp]
theorem map_comp (g' : P' →ₐ[R] P'') : I.map (g'.comp g) = (I.map g).map g' :=
coeToSubmodule_injective (Submodule.map_comp g.toLinearMap g'.toLinearMap I)
@[simp, norm_cast]
theorem map_coeIdeal (I : Ideal R) : (I : FractionalIdeal S P).map g = I := by
ext x
simp only [mem_coeIdeal]
constructor
· rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩
exact ⟨y, hy, (g.commutes y).symm⟩
· rintro ⟨y, hy, rfl⟩
exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩
@[simp]
protected theorem map_one : (1 : FractionalIdeal S P).map g = 1 :=
map_coeIdeal g ⊤
@[simp]
protected theorem map_zero : (0 : FractionalIdeal S P).map g = 0 :=
map_coeIdeal g 0
@[simp]
protected theorem map_add : (I + J).map g = I.map g + J.map g :=
coeToSubmodule_injective (Submodule.map_sup _ _ _)
@[simp]
protected theorem map_mul : (I * J).map g = I.map g * J.map g := by
simp only [mul_def]
exact coeToSubmodule_injective (Submodule.map_mul _ _ _)
@[simp]
theorem map_map_symm (g : P ≃ₐ[R] P') : (I.map (g : P →ₐ[R] P')).map (g.symm : P' →ₐ[R] P) = I := by
rw [← map_comp, g.symm_comp, map_id]
@[simp]
theorem map_symm_map (I : FractionalIdeal S P') (g : P ≃ₐ[R] P') :
(I.map (g.symm : P' →ₐ[R] P)).map (g : P →ₐ[R] P') = I := by
rw [← map_comp, g.comp_symm, map_id]
theorem map_mem_map {f : P →ₐ[R] P'} (h : Function.Injective f) {x : P} {I : FractionalIdeal S P} :
f x ∈ map f I ↔ x ∈ I :=
mem_map.trans ⟨fun ⟨_, hx', x'_eq⟩ => h x'_eq ▸ hx', fun h => ⟨x, h, rfl⟩⟩
theorem map_injective (f : P →ₐ[R] P') (h : Function.Injective f) :
Function.Injective (map f : FractionalIdeal S P → FractionalIdeal S P') := fun _ _ hIJ =>
ext fun _ => (map_mem_map h).symm.trans (hIJ.symm ▸ map_mem_map h)
/-- If `g` is an equivalence, `map g` is an isomorphism -/
def mapEquiv (g : P ≃ₐ[R] P') : FractionalIdeal S P ≃+* FractionalIdeal S P' where
toFun := map g
invFun := map g.symm
map_add' I J := FractionalIdeal.map_add I J _
map_mul' I J := FractionalIdeal.map_mul I J _
left_inv I := by rw [← map_comp, AlgEquiv.symm_comp, map_id]
right_inv I := by rw [← map_comp, AlgEquiv.comp_symm, map_id]
@[simp]
theorem coeFun_mapEquiv (g : P ≃ₐ[R] P') :
(mapEquiv g : FractionalIdeal S P → FractionalIdeal S P') = map g :=
rfl
@[simp]
theorem mapEquiv_apply (g : P ≃ₐ[R] P') (I : FractionalIdeal S P) : mapEquiv g I = map (↑g) I :=
rfl
@[simp]
theorem mapEquiv_symm (g : P ≃ₐ[R] P') :
((mapEquiv g).symm : FractionalIdeal S P' ≃+* _) = mapEquiv g.symm :=
rfl
@[simp]
theorem mapEquiv_refl : mapEquiv AlgEquiv.refl = RingEquiv.refl (FractionalIdeal S P) :=
RingEquiv.ext fun x => by simp
theorem isFractional_span_iff {s : Set P} :
IsFractional S (span R s) ↔ ∃ a ∈ S, ∀ b : P, b ∈ s → IsInteger R (a • b) :=
⟨fun ⟨a, a_mem, h⟩ => ⟨a, a_mem, fun b hb => h b (subset_span hb)⟩, fun ⟨a, a_mem, h⟩ =>
⟨a, a_mem, fun _ hb =>
span_induction (hx := hb) h
(by
rw [smul_zero]
exact isInteger_zero)
(fun x y _ _ hx hy => by
rw [smul_add]
exact isInteger_add hx hy)
fun s x _ hx => by
rw [smul_comm]
exact isInteger_smul hx⟩⟩
theorem isFractional_of_fg [IsLocalization S P] {I : Submodule R P} (hI : I.FG) :
IsFractional S I := by
rcases hI with ⟨I, rfl⟩
rcases exist_integer_multiples_of_finset S I with ⟨⟨s, hs1⟩, hs⟩
rw [isFractional_span_iff]
exact ⟨s, hs1, hs⟩
theorem mem_span_mul_finite_of_mem_mul {I J : FractionalIdeal S P} {x : P} (hx : x ∈ I * J) :
∃ T T' : Finset P, (T : Set P) ⊆ I ∧ (T' : Set P) ⊆ J ∧ x ∈ span R (T * T' : Set P) :=
Submodule.mem_span_mul_finite_of_mem_mul (by simpa using mem_coe.mpr hx)
variable (S) in
theorem coeIdeal_fg (inj : Function.Injective (algebraMap R P)) (I : Ideal R) :
FG ((I : FractionalIdeal S P) : Submodule R P) ↔ I.FG :=
coeSubmodule_fg _ inj _
theorem fg_unit (I : (FractionalIdeal S P)ˣ) : FG (I : Submodule R P) :=
Submodule.fg_unit <| Units.map (coeSubmoduleHom S P).toMonoidHom I
theorem fg_of_isUnit (I : FractionalIdeal S P) (h : IsUnit I) : FG (I : Submodule R P) :=
fg_unit h.unit
theorem _root_.Ideal.fg_of_isUnit (inj : Function.Injective (algebraMap R P)) (I : Ideal R)
(h : IsUnit (I : FractionalIdeal S P)) : I.FG := by
rw [← coeIdeal_fg S inj I]
exact FractionalIdeal.fg_of_isUnit (R := R) I h
variable (S P P')
variable [IsLocalization S P] [IsLocalization S P']
/-- `canonicalEquiv f f'` is the canonical equivalence between the fractional
ideals in `P` and in `P'`, which are both localizations of `R` at `S`. -/
noncomputable irreducible_def canonicalEquiv : FractionalIdeal S P ≃+* FractionalIdeal S P' :=
mapEquiv
{ ringEquivOfRingEquiv P P' (RingEquiv.refl R)
(show S.map _ = S by rw [RingEquiv.toMonoidHom_refl, Submonoid.map_id]) with
commutes' := fun _ => ringEquivOfRingEquiv_eq _ _ }
@[simp]
theorem mem_canonicalEquiv_apply {I : FractionalIdeal S P} {x : P'} :
x ∈ canonicalEquiv S P P' I ↔
∃ y ∈ I,
IsLocalization.map P' (RingHom.id R) (fun y (hy : y ∈ S) => show RingHom.id R y ∈ S from hy)
(y : P) =
x := by
rw [canonicalEquiv, mapEquiv_apply, mem_map]
exact ⟨fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩, fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩⟩
@[simp]
theorem canonicalEquiv_symm : (canonicalEquiv S P P').symm = canonicalEquiv S P' P :=
RingEquiv.ext fun I =>
SetLike.ext_iff.mpr fun x => by
rw [mem_canonicalEquiv_apply, canonicalEquiv, mapEquiv_symm, mapEquiv_apply,
mem_map]
exact ⟨fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩, fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩⟩
theorem canonicalEquiv_flip (I) : canonicalEquiv S P P' (canonicalEquiv S P' P I) = I := by
rw [← canonicalEquiv_symm, RingEquiv.symm_apply_apply]
@[simp]
theorem canonicalEquiv_canonicalEquiv (P'' : Type*) [CommRing P''] [Algebra R P'']
[IsLocalization S P''] (I : FractionalIdeal S P) :
canonicalEquiv S P' P'' (canonicalEquiv S P P' I) = canonicalEquiv S P P'' I := by
ext
simp only [IsLocalization.map_map, RingHomInvPair.comp_eq₂, mem_canonicalEquiv_apply,
exists_prop, exists_exists_and_eq_and]
theorem canonicalEquiv_trans_canonicalEquiv (P'' : Type*) [CommRing P''] [Algebra R P'']
[IsLocalization S P''] :
(canonicalEquiv S P P').trans (canonicalEquiv S P' P'') = canonicalEquiv S P P'' :=
RingEquiv.ext (canonicalEquiv_canonicalEquiv S P P' P'')
@[simp]
theorem canonicalEquiv_coeIdeal (I : Ideal R) : canonicalEquiv S P P' I = I := by
ext
simp [IsLocalization.map_eq]
@[simp]
theorem canonicalEquiv_self : canonicalEquiv S P P = RingEquiv.refl _ := by
rw [← canonicalEquiv_trans_canonicalEquiv S P P]
convert (canonicalEquiv S P P).symm_trans_self
exact (canonicalEquiv_symm S P P).symm
end
section IsFractionRing
/-!
### `IsFractionRing` section
This section concerns fractional ideals in the field of fractions,
i.e. the type `FractionalIdeal R⁰ K` where `IsFractionRing R K`.
-/
variable {K K' : Type*} [Field K] [Field K']
variable [Algebra R K] [IsFractionRing R K] [Algebra R K'] [IsFractionRing R K']
variable {I J : FractionalIdeal R⁰ K} (h : K →ₐ[R] K')
/-- Nonzero fractional ideals contain a nonzero integer. -/
theorem exists_ne_zero_mem_isInteger [Nontrivial R] (hI : I ≠ 0) :
∃ x, x ≠ 0 ∧ algebraMap R K x ∈ I := by
obtain ⟨y : K, y_mem, y_not_mem⟩ :=
SetLike.exists_of_lt (by simpa only using bot_lt_iff_ne_bot.mpr hI)
have y_ne_zero : y ≠ 0 := by simpa using y_not_mem
obtain ⟨z, ⟨x, hx⟩⟩ := exists_integer_multiple R⁰ y
refine ⟨x, ?_, ?_⟩
· rw [Ne, ← @IsFractionRing.to_map_eq_zero_iff R _ K, hx, Algebra.smul_def]
exact mul_ne_zero (IsFractionRing.to_map_ne_zero_of_mem_nonZeroDivisors z.2) y_ne_zero
· rw [hx]
exact smul_mem _ _ y_mem
theorem map_ne_zero [Nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 := by
obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_isInteger hI
contrapose! x_ne_zero with map_eq_zero
refine IsFractionRing.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr ?_))
exact ⟨algebraMap R K x, hx, h.commutes x⟩
@[simp]
theorem map_eq_zero_iff [Nontrivial R] : I.map h = 0 ↔ I = 0 :=
⟨not_imp_not.mp (map_ne_zero _), fun hI => hI.symm ▸ FractionalIdeal.map_zero h⟩
theorem coeIdeal_injective : Function.Injective (fun (I : Ideal R) ↦ (I : FractionalIdeal R⁰ K)) :=
coeIdeal_injective' le_rfl
theorem coeIdeal_inj {I J : Ideal R} :
(I : FractionalIdeal R⁰ K) = (J : FractionalIdeal R⁰ K) ↔ I = J :=
coeIdeal_inj' le_rfl
@[simp]
theorem coeIdeal_eq_zero {I : Ideal R} : (I : FractionalIdeal R⁰ K) = 0 ↔ I = ⊥ :=
coeIdeal_eq_zero' le_rfl
theorem coeIdeal_ne_zero {I : Ideal R} : (I : FractionalIdeal R⁰ K) ≠ 0 ↔ I ≠ ⊥ :=
coeIdeal_ne_zero' le_rfl
@[simp]
theorem coeIdeal_eq_one {I : Ideal R} : (I : FractionalIdeal R⁰ K) = 1 ↔ I = 1 := by
simpa only [Ideal.one_eq_top] using coeIdeal_inj
theorem coeIdeal_ne_one {I : Ideal R} : (I : FractionalIdeal R⁰ K) ≠ 1 ↔ I ≠ 1 :=
not_iff_not.mpr coeIdeal_eq_one
theorem num_eq_zero_iff [Nontrivial R] {I : FractionalIdeal R⁰ K} : I.num = 0 ↔ I = 0 :=
⟨fun h ↦ zero_of_num_eq_bot zero_not_mem_nonZeroDivisors h,
fun h ↦ h ▸ num_zero_eq (IsFractionRing.injective R K)⟩
end IsFractionRing
section Quotient
/-!
### `quotient` section
This section defines the ideal quotient of fractional ideals.
In this section we need that each non-zero `y : R` has an inverse in
the localization, i.e. that the localization is a field. We satisfy this
assumption by taking `S = nonZeroDivisors R`, `R`'s localization at which
is a field because `R` is a domain.
-/
variable {R₁ : Type*} [CommRing R₁] {K : Type*} [Field K]
variable [Algebra R₁ K]
instance : Nontrivial (FractionalIdeal R₁⁰ K) :=
⟨⟨0, 1, fun h =>
have this : (1 : K) ∈ (0 : FractionalIdeal R₁⁰ K) := by
rw [← (algebraMap R₁ K).map_one]
simpa only [h] using coe_mem_one R₁⁰ 1
one_ne_zero ((mem_zero_iff _).mp this)⟩⟩
theorem ne_zero_of_mul_eq_one (I J : FractionalIdeal R₁⁰ K) (h : I * J = 1) : I ≠ 0 := fun hI =>
zero_ne_one' (FractionalIdeal R₁⁰ K)
(by
convert h
simp [hI])
variable [IsFractionRing R₁ K] [IsDomain R₁]
theorem _root_.IsFractional.div_of_nonzero {I J : Submodule R₁ K} :
IsFractional R₁⁰ I → IsFractional R₁⁰ J → J ≠ 0 → IsFractional R₁⁰ (I / J)
| ⟨aI, haI, hI⟩, ⟨aJ, haJ, hJ⟩, h => by
obtain ⟨y, mem_J, not_mem_zero⟩ :=
SetLike.exists_of_lt (show 0 < J by simpa only using bot_lt_iff_ne_bot.mpr h)
obtain ⟨y', hy'⟩ := hJ y mem_J
use aI * y'
constructor
· apply (nonZeroDivisors R₁).mul_mem haI (mem_nonZeroDivisors_iff_ne_zero.mpr _)
intro y'_eq_zero
have : algebraMap R₁ K aJ * y = 0 := by
rw [← Algebra.smul_def, ← hy', y'_eq_zero, RingHom.map_zero]
have y_zero :=
(mul_eq_zero.mp this).resolve_left
(mt ((injective_iff_map_eq_zero (algebraMap R₁ K)).1 (IsFractionRing.injective _ _) _)
(mem_nonZeroDivisors_iff_ne_zero.mp haJ))
apply not_mem_zero
simpa
intro b hb
convert hI _ (hb _ (Submodule.smul_mem _ aJ mem_J)) using 1
rw [← hy', mul_comm b, ← Algebra.smul_def, mul_smul]
theorem fractional_div_of_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) :
IsFractional R₁⁰ (I / J : Submodule R₁ K) :=
I.isFractional.div_of_nonzero J.isFractional fun H =>
h <| coeToSubmodule_injective <| H.trans coe_zero.symm
open Classical in
noncomputable instance : Div (FractionalIdeal R₁⁰ K) :=
⟨fun I J => if h : J = 0 then 0 else ⟨I / J, fractional_div_of_nonzero h⟩⟩
variable {I J : FractionalIdeal R₁⁰ K}
@[simp]
theorem div_zero {I : FractionalIdeal R₁⁰ K} : I / 0 = 0 :=
dif_pos rfl
theorem div_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) :
I / J = ⟨I / J, fractional_div_of_nonzero h⟩ :=
dif_neg h
@[simp]
theorem coe_div {I J : FractionalIdeal R₁⁰ K} (hJ : J ≠ 0) :
(↑(I / J) : Submodule R₁ K) = ↑I / (↑J : Submodule R₁ K) :=
congr_arg _ (dif_neg hJ)
theorem mem_div_iff_of_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) {x} :
x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := by
rw [div_nonzero h]
exact Submodule.mem_div_iff_forall_mul_mem
theorem mul_one_div_le_one {I : FractionalIdeal R₁⁰ K} : I * (1 / I) ≤ 1 := by
by_cases hI : I = 0
· rw [hI, div_zero, mul_zero]
exact zero_le 1
· rw [← coe_le_coe, coe_mul, coe_div hI, coe_one]
apply Submodule.mul_one_div_le_one
theorem le_self_mul_one_div {I : FractionalIdeal R₁⁰ K} (hI : I ≤ (1 : FractionalIdeal R₁⁰ K)) :
I ≤ I * (1 / I) := by
by_cases hI_nz : I = 0
· rw [hI_nz, div_zero, mul_zero]
· rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one]
rw [← coe_le_coe, coe_one] at hI
exact Submodule.le_self_mul_one_div hI
theorem le_div_iff_of_nonzero {I J J' : FractionalIdeal R₁⁰ K} (hJ' : J' ≠ 0) :
I ≤ J / J' ↔ ∀ x ∈ I, ∀ y ∈ J', x * y ∈ J :=
⟨fun h _ hx => (mem_div_iff_of_nonzero hJ').mp (h hx), fun h x hx =>
(mem_div_iff_of_nonzero hJ').mpr (h x hx)⟩
theorem le_div_iff_mul_le {I J J' : FractionalIdeal R₁⁰ K} (hJ' : J' ≠ 0) :
I ≤ J / J' ↔ I * J' ≤ J := by
rw [div_nonzero hJ']
-- Porting note: this used to be { convert; rw }, flipped the order.
rw [← coe_le_coe (I := I * J') (J := J), coe_mul]
exact Submodule.le_div_iff_mul_le
@[simp]
theorem div_one {I : FractionalIdeal R₁⁰ K} : I / 1 = I := by
rw [div_nonzero (one_ne_zero' (FractionalIdeal R₁⁰ K))]
ext
constructor <;> intro h
· simpa using mem_div_iff_forall_mul_mem.mp h 1 ((algebraMap R₁ K).map_one ▸ coe_mem_one R₁⁰ 1)
· apply mem_div_iff_forall_mul_mem.mpr
rintro y ⟨y', _, rfl⟩
-- Porting note: this used to be { convert; rw }, flipped the order.
rw [mul_comm, Algebra.linearMap_apply, ← Algebra.smul_def]
exact Submodule.smul_mem _ y' h
theorem eq_one_div_of_mul_eq_one_right (I J : FractionalIdeal R₁⁰ K) (h : I * J = 1) :
J = 1 / I := by
have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h
suffices h' : I * (1 / I) = 1 from
congr_arg Units.inv <| @Units.ext _ _ (Units.mkOfMulEqOne _ _ h) (Units.mkOfMulEqOne _ _ h') rfl
apply le_antisymm
· apply mul_le.mpr _
intro x hx y hy
rw [mul_comm]
exact (mem_div_iff_of_nonzero hI).mp hy x hx
rw [← h]
apply mul_left_mono I
apply (le_div_iff_of_nonzero hI).mpr _
intro y hy x hx
rw [mul_comm]
exact mul_mem_mul hy hx
theorem mul_div_self_cancel_iff {I : FractionalIdeal R₁⁰ K} : I * (1 / I) = 1 ↔ ∃ J, I * J = 1 :=
⟨fun h => ⟨1 / I, h⟩, fun ⟨J, hJ⟩ => by rwa [← eq_one_div_of_mul_eq_one_right I J hJ]⟩
variable {K' : Type*} [Field K'] [Algebra R₁ K'] [IsFractionRing R₁ K']
@[simp]
protected theorem map_div (I J : FractionalIdeal R₁⁰ K) (h : K ≃ₐ[R₁] K') :
(I / J).map (h : K →ₐ[R₁] K') = I.map h / J.map h := by
by_cases H : J = 0
· rw [H, div_zero, FractionalIdeal.map_zero, div_zero]
· -- Porting note: `simp` wouldn't apply these lemmas so do them manually using `rw`
rw [← coeToSubmodule_inj, div_nonzero H, div_nonzero (map_ne_zero _ H)]
simp [Submodule.map_div]
-- Porting note: doesn't need to be @[simp] because this follows from `map_one` and `map_div`
theorem map_one_div (I : FractionalIdeal R₁⁰ K) (h : K ≃ₐ[R₁] K') :
(1 / I).map (h : K →ₐ[R₁] K') = 1 / I.map h := by
rw [FractionalIdeal.map_div, FractionalIdeal.map_one]
end Quotient
section Field
variable {R₁ K L : Type*} [CommRing R₁] [Field K] [Field L]
variable [Algebra R₁ K] [IsFractionRing R₁ K] [Algebra K L] [IsFractionRing K L]
theorem eq_zero_or_one (I : FractionalIdeal K⁰ L) : I = 0 ∨ I = 1 := by
| rw [or_iff_not_imp_left]
intro hI
simp_rw [@SetLike.ext_iff _ _ _ I 1, mem_one_iff]
intro x
constructor
· intro x_mem
obtain ⟨n, d, rfl⟩ := IsLocalization.mk'_surjective K⁰ x
refine ⟨n / d, ?_⟩
rw [map_div₀, IsFractionRing.mk'_eq_div]
· rintro ⟨x, rfl⟩
| Mathlib/RingTheory/FractionalIdeal/Operations.lean | 487 | 496 |
/-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Chris Hughes, Daniel Weber
-/
import Batteries.Data.Nat.Gcd
import Mathlib.Algebra.GroupWithZero.Associated
import Mathlib.Algebra.Ring.Divisibility.Basic
import Mathlib.Algebra.Ring.Int.Defs
import Mathlib.Data.ENat.Basic
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
/-!
# Multiplicity of a divisor
For a commutative monoid, this file introduces the notion of multiplicity of a divisor and proves
several basic results on it.
## Main definitions
* `emultiplicity a b`: for two elements `a` and `b` of a commutative monoid returns the largest
number `n` such that `a ^ n ∣ b` or infinity, written `⊤`, if `a ^ n ∣ b` for all natural numbers
`n`.
* `multiplicity a b`: a `ℕ`-valued version of `multiplicity`, defaulting for `1` instead of `⊤`.
The reason for using `1` as a default value instead of `0` is to have `multiplicity_eq_zero_iff`.
* `FiniteMultiplicity a b`: a predicate denoting that the multiplicity of `a` in `b` is finite.
-/
assert_not_exists Field
variable {α β : Type*}
open Nat
/-- `multiplicity.Finite a b` indicates that the multiplicity of `a` in `b` is finite. -/
abbrev FiniteMultiplicity [Monoid α] (a b : α) : Prop :=
∃ n : ℕ, ¬a ^ (n + 1) ∣ b
@[deprecated (since := "2024-11-30")] alias multiplicity.Finite := FiniteMultiplicity
open scoped Classical in
/-- `emultiplicity a b` returns the largest natural number `n` such that
`a ^ n ∣ b`, as an `ℕ∞`. If `∀ n, a ^ n ∣ b` then it returns `⊤`. -/
noncomputable def emultiplicity [Monoid α] (a b : α) : ℕ∞ :=
if h : FiniteMultiplicity a b then Nat.find h else ⊤
/-- A `ℕ`-valued version of `emultiplicity`, returning `1` instead of `⊤`. -/
noncomputable def multiplicity [Monoid α] (a b : α) : ℕ :=
(emultiplicity a b).untopD 1
section Monoid
variable [Monoid α] [Monoid β] {a b : α}
@[simp]
theorem emultiplicity_eq_top :
emultiplicity a b = ⊤ ↔ ¬FiniteMultiplicity a b := by
simp [emultiplicity]
theorem emultiplicity_lt_top {a b : α} : emultiplicity a b < ⊤ ↔ FiniteMultiplicity a b := by
simp [lt_top_iff_ne_top, emultiplicity_eq_top]
theorem finiteMultiplicity_iff_emultiplicity_ne_top :
FiniteMultiplicity a b ↔ emultiplicity a b ≠ ⊤ := by simp
@[deprecated (since := "2024-11-30")]
alias finite_iff_emultiplicity_ne_top := finiteMultiplicity_iff_emultiplicity_ne_top
alias ⟨FiniteMultiplicity.emultiplicity_ne_top, _⟩ := finite_iff_emultiplicity_ne_top
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.emultiplicity_ne_top := FiniteMultiplicity.emultiplicity_ne_top
@[deprecated (since := "2024-11-08")]
alias Finite.emultiplicity_ne_top := FiniteMultiplicity.emultiplicity_ne_top
theorem finiteMultiplicity_of_emultiplicity_eq_natCast {n : ℕ} (h : emultiplicity a b = n) :
FiniteMultiplicity a b := by
by_contra! nh
rw [← emultiplicity_eq_top, h] at nh
trivial
@[deprecated (since := "2024-11-30")]
alias finite_of_emultiplicity_eq_natCast := finiteMultiplicity_of_emultiplicity_eq_natCast
theorem multiplicity_eq_of_emultiplicity_eq_some {n : ℕ} (h : emultiplicity a b = n) :
multiplicity a b = n := by
simp [multiplicity, h]
rfl
theorem emultiplicity_ne_of_multiplicity_ne {n : ℕ} :
multiplicity a b ≠ n → emultiplicity a b ≠ n :=
mt multiplicity_eq_of_emultiplicity_eq_some
theorem FiniteMultiplicity.emultiplicity_eq_multiplicity (h : FiniteMultiplicity a b) :
emultiplicity a b = multiplicity a b := by
cases hm : emultiplicity a b
· simp [h] at hm
rw [multiplicity_eq_of_emultiplicity_eq_some hm]
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.emultiplicity_eq_multiplicity :=
FiniteMultiplicity.emultiplicity_eq_multiplicity
theorem FiniteMultiplicity.emultiplicity_eq_iff_multiplicity_eq {n : ℕ}
(h : FiniteMultiplicity a b) : emultiplicity a b = n ↔ multiplicity a b = n := by
simp [h.emultiplicity_eq_multiplicity]
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.emultiplicity_eq_iff_multiplicity_eq :=
FiniteMultiplicity.emultiplicity_eq_iff_multiplicity_eq
theorem emultiplicity_eq_iff_multiplicity_eq_of_ne_one {n : ℕ} (h : n ≠ 1) :
emultiplicity a b = n ↔ multiplicity a b = n := by
constructor
· exact multiplicity_eq_of_emultiplicity_eq_some
· intro h₂
simpa [multiplicity, WithTop.untopD_eq_iff, h] using h₂
theorem emultiplicity_eq_zero_iff_multiplicity_eq_zero :
emultiplicity a b = 0 ↔ multiplicity a b = 0 :=
emultiplicity_eq_iff_multiplicity_eq_of_ne_one zero_ne_one
@[simp]
theorem multiplicity_eq_one_of_not_finiteMultiplicity (h : ¬FiniteMultiplicity a b) :
multiplicity a b = 1 := by
simp [multiplicity, emultiplicity_eq_top.2 h]
@[deprecated (since := "2024-11-30")]
alias multiplicity_eq_one_of_not_finite :=
multiplicity_eq_one_of_not_finiteMultiplicity
@[simp]
theorem multiplicity_le_emultiplicity :
multiplicity a b ≤ emultiplicity a b := by
by_cases hf : FiniteMultiplicity a b
· simp [hf.emultiplicity_eq_multiplicity]
· simp [hf, emultiplicity_eq_top.2]
@[simp]
theorem multiplicity_eq_of_emultiplicity_eq {c d : β}
(h : emultiplicity a b = emultiplicity c d) : multiplicity a b = multiplicity c d := by
unfold multiplicity
rw [h]
theorem multiplicity_le_of_emultiplicity_le {n : ℕ} (h : emultiplicity a b ≤ n) :
multiplicity a b ≤ n := by
exact_mod_cast multiplicity_le_emultiplicity.trans h
theorem FiniteMultiplicity.emultiplicity_le_of_multiplicity_le (hfin : FiniteMultiplicity a b)
{n : ℕ} (h : multiplicity a b ≤ n) : emultiplicity a b ≤ n := by
rw [emultiplicity_eq_multiplicity hfin]
assumption_mod_cast
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.emultiplicity_le_of_multiplicity_le :=
FiniteMultiplicity.emultiplicity_le_of_multiplicity_le
theorem le_emultiplicity_of_le_multiplicity {n : ℕ} (h : n ≤ multiplicity a b) :
n ≤ emultiplicity a b := by
exact_mod_cast (WithTop.coe_mono h).trans multiplicity_le_emultiplicity
theorem FiniteMultiplicity.le_multiplicity_of_le_emultiplicity (hfin : FiniteMultiplicity a b)
{n : ℕ} (h : n ≤ emultiplicity a b) : n ≤ multiplicity a b := by
rw [emultiplicity_eq_multiplicity hfin] at h
assumption_mod_cast
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.le_multiplicity_of_le_emultiplicity :=
FiniteMultiplicity.le_multiplicity_of_le_emultiplicity
theorem multiplicity_lt_of_emultiplicity_lt {n : ℕ} (h : emultiplicity a b < n) :
multiplicity a b < n := by
exact_mod_cast multiplicity_le_emultiplicity.trans_lt h
theorem FiniteMultiplicity.emultiplicity_lt_of_multiplicity_lt (hfin : FiniteMultiplicity a b)
{n : ℕ} (h : multiplicity a b < n) : emultiplicity a b < n := by
rw [emultiplicity_eq_multiplicity hfin]
assumption_mod_cast
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.emultiplicity_lt_of_multiplicity_lt :=
FiniteMultiplicity.emultiplicity_lt_of_multiplicity_lt
theorem lt_emultiplicity_of_lt_multiplicity {n : ℕ} (h : n < multiplicity a b) :
n < emultiplicity a b := by
exact_mod_cast (WithTop.coe_strictMono h).trans_le multiplicity_le_emultiplicity
theorem FiniteMultiplicity.lt_multiplicity_of_lt_emultiplicity (hfin : FiniteMultiplicity a b)
{n : ℕ} (h : n < emultiplicity a b) : n < multiplicity a b := by
rw [emultiplicity_eq_multiplicity hfin] at h
assumption_mod_cast
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.lt_multiplicity_of_lt_emultiplicity :=
FiniteMultiplicity.lt_multiplicity_of_lt_emultiplicity
theorem emultiplicity_pos_iff :
0 < emultiplicity a b ↔ 0 < multiplicity a b := by
simp [pos_iff_ne_zero, pos_iff_ne_zero, emultiplicity_eq_zero_iff_multiplicity_eq_zero]
theorem FiniteMultiplicity.def : FiniteMultiplicity a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b :=
Iff.rfl
@[deprecated (since := "2024-11-30")] alias multiplicity.Finite.def := FiniteMultiplicity.def
theorem FiniteMultiplicity.not_dvd_of_one_right : FiniteMultiplicity a 1 → ¬a ∣ 1 :=
fun ⟨n, hn⟩ ⟨d, hd⟩ => hn ⟨d ^ (n + 1), (pow_mul_pow_eq_one (n + 1) hd.symm).symm⟩
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.not_dvd_of_one_right := FiniteMultiplicity.not_dvd_of_one_right
@[norm_cast]
theorem Int.natCast_emultiplicity (a b : ℕ) :
emultiplicity (a : ℤ) (b : ℤ) = emultiplicity a b := by
unfold emultiplicity FiniteMultiplicity
congr! <;> norm_cast
@[norm_cast]
theorem Int.natCast_multiplicity (a b : ℕ) : multiplicity (a : ℤ) (b : ℤ) = multiplicity a b :=
multiplicity_eq_of_emultiplicity_eq (natCast_emultiplicity a b)
theorem FiniteMultiplicity.not_iff_forall : ¬FiniteMultiplicity a b ↔ ∀ n : ℕ, a ^ n ∣ b :=
⟨fun h n =>
Nat.casesOn n
(by
rw [_root_.pow_zero]
exact one_dvd _)
(by simpa [FiniteMultiplicity] using h),
by simp [FiniteMultiplicity, multiplicity]; tauto⟩
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.not_iff_forall := FiniteMultiplicity.not_iff_forall
theorem FiniteMultiplicity.not_unit (h : FiniteMultiplicity a b) : ¬IsUnit a :=
let ⟨n, hn⟩ := h
hn ∘ IsUnit.dvd ∘ IsUnit.pow (n + 1)
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.not_unit := FiniteMultiplicity.not_unit
theorem FiniteMultiplicity.mul_left {c : α} :
FiniteMultiplicity a (b * c) → FiniteMultiplicity a b := fun ⟨n, hn⟩ =>
⟨n, fun h => hn (h.trans (dvd_mul_right _ _))⟩
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.mul_left := FiniteMultiplicity.mul_left
theorem pow_dvd_of_le_emultiplicity {k : ℕ} (hk : k ≤ emultiplicity a b) :
a ^ k ∣ b := by classical
cases k
· simp
unfold emultiplicity at hk
split at hk
· norm_cast at hk
simpa using (Nat.find_min _ (lt_of_succ_le hk))
· apply FiniteMultiplicity.not_iff_forall.mp ‹_›
theorem pow_dvd_of_le_multiplicity {k : ℕ} (hk : k ≤ multiplicity a b) :
a ^ k ∣ b := pow_dvd_of_le_emultiplicity (le_emultiplicity_of_le_multiplicity hk)
@[simp]
theorem pow_multiplicity_dvd (a b : α) : a ^ (multiplicity a b) ∣ b :=
pow_dvd_of_le_multiplicity le_rfl
theorem not_pow_dvd_of_emultiplicity_lt {m : ℕ} (hm : emultiplicity a b < m) :
¬a ^ m ∣ b := fun nh => by
unfold emultiplicity at hm
split at hm
· simp only [cast_lt, find_lt_iff] at hm
obtain ⟨n, hn1, hn2⟩ := hm
exact hn2 ((pow_dvd_pow _ hn1).trans nh)
· simp at hm
theorem FiniteMultiplicity.not_pow_dvd_of_multiplicity_lt (hf : FiniteMultiplicity a b) {m : ℕ}
(hm : multiplicity a b < m) : ¬a ^ m ∣ b := by
apply not_pow_dvd_of_emultiplicity_lt
rw [hf.emultiplicity_eq_multiplicity]
norm_cast
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.not_pow_dvd_of_multiplicity_lt :=
FiniteMultiplicity.not_pow_dvd_of_multiplicity_lt
theorem multiplicity_pos_of_dvd (hdiv : a ∣ b) : 0 < multiplicity a b := by
refine Nat.pos_iff_ne_zero.2 fun h => ?_
simpa [hdiv] using FiniteMultiplicity.not_pow_dvd_of_multiplicity_lt
(by by_contra! nh; simp [nh] at h) (lt_one_iff.mpr h)
theorem emultiplicity_pos_of_dvd (hdiv : a ∣ b) : 0 < emultiplicity a b :=
lt_emultiplicity_of_lt_multiplicity (multiplicity_pos_of_dvd hdiv)
theorem emultiplicity_eq_of_dvd_of_not_dvd {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) :
emultiplicity a b = k := by classical
have : FiniteMultiplicity a b := ⟨k, hsucc⟩
simp only [emultiplicity, this, ↓reduceDIte, Nat.cast_inj, find_eq_iff, hsucc, not_false_eq_true,
Decidable.not_not, true_and]
exact fun n hn ↦ (pow_dvd_pow _ hn).trans hk
theorem multiplicity_eq_of_dvd_of_not_dvd {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) :
multiplicity a b = k :=
multiplicity_eq_of_emultiplicity_eq_some (emultiplicity_eq_of_dvd_of_not_dvd hk hsucc)
theorem le_emultiplicity_of_pow_dvd {k : ℕ} (hk : a ^ k ∣ b) :
k ≤ emultiplicity a b :=
le_of_not_gt fun hk' => not_pow_dvd_of_emultiplicity_lt hk' hk
theorem FiniteMultiplicity.le_multiplicity_of_pow_dvd (hf : FiniteMultiplicity a b)
{k : ℕ} (hk : a ^ k ∣ b) : k ≤ multiplicity a b :=
hf.le_multiplicity_of_le_emultiplicity (le_emultiplicity_of_pow_dvd hk)
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.le_multiplicity_of_pow_dvd :=
FiniteMultiplicity.le_multiplicity_of_pow_dvd
theorem pow_dvd_iff_le_emultiplicity {k : ℕ} :
a ^ k ∣ b ↔ k ≤ emultiplicity a b :=
⟨le_emultiplicity_of_pow_dvd, pow_dvd_of_le_emultiplicity⟩
theorem FiniteMultiplicity.pow_dvd_iff_le_multiplicity (hf : FiniteMultiplicity a b) {k : ℕ} :
a ^ k ∣ b ↔ k ≤ multiplicity a b := by
exact_mod_cast hf.emultiplicity_eq_multiplicity ▸ pow_dvd_iff_le_emultiplicity
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.pow_dvd_iff_le_multiplicity :=
FiniteMultiplicity.pow_dvd_iff_le_multiplicity
theorem emultiplicity_lt_iff_not_dvd {k : ℕ} :
emultiplicity a b < k ↔ ¬a ^ k ∣ b := by rw [pow_dvd_iff_le_emultiplicity, not_le]
theorem FiniteMultiplicity.multiplicity_lt_iff_not_dvd {k : ℕ} (hf : FiniteMultiplicity a b) :
multiplicity a b < k ↔ ¬a ^ k ∣ b := by rw [hf.pow_dvd_iff_le_multiplicity, not_le]
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.multiplicity_lt_iff_not_dvd :=
FiniteMultiplicity.multiplicity_lt_iff_not_dvd
theorem emultiplicity_eq_coe {n : ℕ} :
emultiplicity a b = n ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := by
constructor
· intro h
constructor
· apply pow_dvd_of_le_emultiplicity
simp [h]
· apply not_pow_dvd_of_emultiplicity_lt
rw [h]
norm_cast
simp
· rw [and_imp]
apply emultiplicity_eq_of_dvd_of_not_dvd
theorem FiniteMultiplicity.multiplicity_eq_iff (hf : FiniteMultiplicity a b) {n : ℕ} :
multiplicity a b = n ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := by
simp [← emultiplicity_eq_coe, hf.emultiplicity_eq_multiplicity]
theorem emultiplicity_eq_ofNat {a b n : ℕ} [n.AtLeastTwo] :
emultiplicity a b = (ofNat(n) : ℕ∞) ↔ a ^ ofNat(n) ∣ b ∧ ¬a ^ (ofNat(n) + 1) ∣ b :=
emultiplicity_eq_coe
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.multiplicity_eq_iff := FiniteMultiplicity.multiplicity_eq_iff
@[simp]
theorem FiniteMultiplicity.not_of_isUnit_left (b : α) (ha : IsUnit a) : ¬FiniteMultiplicity a b :=
(·.not_unit ha)
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.not_of_isUnit_left := FiniteMultiplicity.not_of_isUnit_left
theorem FiniteMultiplicity.not_of_one_left (b : α) : ¬ FiniteMultiplicity 1 b := by simp
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.not_of_one_left := FiniteMultiplicity.not_of_one_left
@[simp]
theorem emultiplicity_one_left (b : α) : emultiplicity 1 b = ⊤ :=
emultiplicity_eq_top.2 (FiniteMultiplicity.not_of_one_left _)
@[simp]
theorem FiniteMultiplicity.one_right (ha : FiniteMultiplicity a 1) : multiplicity a 1 = 0 := by
simp [ha.multiplicity_eq_iff, ha.not_dvd_of_one_right]
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.one_right := FiniteMultiplicity.one_right
theorem FiniteMultiplicity.not_of_unit_left (a : α) (u : αˣ) : ¬ FiniteMultiplicity (u : α) a :=
FiniteMultiplicity.not_of_isUnit_left a u.isUnit
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.not_of_unit_left := FiniteMultiplicity.not_of_unit_left
theorem emultiplicity_eq_zero :
emultiplicity a b = 0 ↔ ¬a ∣ b := by
by_cases hf : FiniteMultiplicity a b
· rw [← ENat.coe_zero, emultiplicity_eq_coe]
simp
· simpa [emultiplicity_eq_top.2 hf] using FiniteMultiplicity.not_iff_forall.1 hf 1
theorem multiplicity_eq_zero :
multiplicity a b = 0 ↔ ¬a ∣ b :=
(emultiplicity_eq_iff_multiplicity_eq_of_ne_one zero_ne_one).symm.trans emultiplicity_eq_zero
theorem emultiplicity_ne_zero :
emultiplicity a b ≠ 0 ↔ a ∣ b := by
simp [emultiplicity_eq_zero]
theorem multiplicity_ne_zero :
multiplicity a b ≠ 0 ↔ a ∣ b := by
simp [multiplicity_eq_zero]
theorem FiniteMultiplicity.exists_eq_pow_mul_and_not_dvd (hfin : FiniteMultiplicity a b) :
∃ c : α, b = a ^ multiplicity a b * c ∧ ¬a ∣ c := by
obtain ⟨c, hc⟩ := pow_multiplicity_dvd a b
refine ⟨c, hc, ?_⟩
rintro ⟨k, hk⟩
rw [hk, ← mul_assoc, ← _root_.pow_succ] at hc
have h₁ : a ^ (multiplicity a b + 1) ∣ b := ⟨k, hc⟩
exact (hfin.multiplicity_eq_iff.1 (by simp)).2 h₁
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.exists_eq_pow_mul_and_not_dvd :=
FiniteMultiplicity.exists_eq_pow_mul_and_not_dvd
theorem emultiplicity_le_emultiplicity_iff {c d : β} :
emultiplicity a b ≤ emultiplicity c d ↔ ∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d := by classical
constructor
· exact fun h n hab ↦ pow_dvd_of_le_emultiplicity (le_trans (le_emultiplicity_of_pow_dvd hab) h)
· intro h
unfold emultiplicity
-- aesop? says
split
next h_1 =>
obtain ⟨w, h_1⟩ := h_1
split
next h_2 =>
simp_all only [cast_le, le_find_iff, lt_find_iff, Decidable.not_not, le_refl,
not_true_eq_false, not_false_eq_true, implies_true]
next h_2 => simp_all only [not_exists, Decidable.not_not, le_top]
next h_1 =>
simp_all only [not_exists, Decidable.not_not, not_true_eq_false, top_le_iff,
dite_eq_right_iff, ENat.coe_ne_top, imp_false, not_false_eq_true, implies_true]
theorem FiniteMultiplicity.multiplicity_le_multiplicity_iff {c d : β} (hab : FiniteMultiplicity a b)
(hcd : FiniteMultiplicity c d) :
multiplicity a b ≤ multiplicity c d ↔ ∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d := by
rw [← WithTop.coe_le_coe, ENat.some_eq_coe, ← hab.emultiplicity_eq_multiplicity,
← hcd.emultiplicity_eq_multiplicity]
apply emultiplicity_le_emultiplicity_iff
@[deprecated (since := "2024-11-30")]
alias multiplicity.Finite.multiplicity_le_multiplicity_iff :=
FiniteMultiplicity.multiplicity_le_multiplicity_iff
theorem emultiplicity_eq_emultiplicity_iff {c d : β} :
emultiplicity a b = emultiplicity c d ↔ ∀ n : ℕ, a ^ n ∣ b ↔ c ^ n ∣ d :=
⟨fun h n =>
⟨emultiplicity_le_emultiplicity_iff.1 h.le n, emultiplicity_le_emultiplicity_iff.1 h.ge n⟩,
fun h => le_antisymm (emultiplicity_le_emultiplicity_iff.2 fun n => (h n).mp)
(emultiplicity_le_emultiplicity_iff.2 fun n => (h n).mpr)⟩
theorem le_emultiplicity_map {F : Type*} [FunLike F α β] [MonoidHomClass F α β]
(f : F) {a b : α} :
emultiplicity a b ≤ emultiplicity (f a) (f b) :=
| emultiplicity_le_emultiplicity_iff.2 fun n ↦ by rw [← map_pow]; exact map_dvd f
theorem emultiplicity_map_eq {F : Type*} [EquivLike F α β] [MulEquivClass F α β]
(f : F) {a b : α} : emultiplicity (f a) (f b) = emultiplicity a b := by
simp [emultiplicity_eq_emultiplicity_iff, ← map_pow, map_dvd_iff]
theorem multiplicity_map_eq {F : Type*} [EquivLike F α β] [MulEquivClass F α β]
(f : F) {a b : α} : multiplicity (f a) (f b) = multiplicity a b :=
| Mathlib/RingTheory/Multiplicity.lean | 464 | 471 |
/-
Copyright (c) 2021 Arthur Paulino. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Arthur Paulino, Kyle Miller
-/
import Mathlib.Combinatorics.SimpleGraph.Clique
import Mathlib.Data.ENat.Lattice
import Mathlib.Data.Nat.Lattice
import Mathlib.Data.Setoid.Partition
import Mathlib.Order.Antichain
import Mathlib.Data.Nat.Cast.Order.Ring
/-!
# Graph Coloring
This module defines colorings of simple graphs (also known as proper colorings in the literature).
A graph coloring is the attribution of "colors" to all of its vertices such that adjacent vertices
have different colors.
A coloring can be represented as a homomorphism into a complete graph, whose vertices represent
the colors.
## Main definitions
* `G.Coloring α` is the type of `α`-colorings of a simple graph `G`,
with `α` being the set of available colors. The type is defined to
be homomorphisms from `G` into the complete graph on `α`, and
colorings have a coercion to `V → α`.
* `G.Colorable n` is the proposition that `G` is `n`-colorable, which
is whether there exists a coloring with at most *n* colors.
* `G.chromaticNumber` is the minimal `n` such that `G` is `n`-colorable,
or `⊤` if it cannot be colored with finitely many colors.
(Cardinal-valued chromatic numbers are more niche, so we stick to `ℕ∞`.)
We write `G.chromaticNumber ≠ ⊤` to mean a graph is colorable with finitely many colors.
* `C.colorClass c` is the set of vertices colored by `c : α` in the coloring `C : G.Coloring α`.
* `C.colorClasses` is the set containing all color classes.
## TODO
* Gather material from:
* https://github.com/leanprover-community/mathlib/blob/simple_graph_matching/src/combinatorics/simple_graph/coloring.lean
* https://github.com/kmill/lean-graphcoloring/blob/master/src/graph.lean
* Trees
* Planar graphs
* Chromatic polynomials
* develop API for partial colorings, likely as colorings of subgraphs (`H.coe.Coloring α`)
-/
assert_not_exists Field
open Fintype Function
universe u v
namespace SimpleGraph
variable {V : Type u} (G : SimpleGraph V) {n : ℕ}
/-- An `α`-coloring of a simple graph `G` is a homomorphism of `G` into the complete graph on `α`.
This is also known as a proper coloring.
-/
abbrev Coloring (α : Type v) := G →g (⊤ : SimpleGraph α)
variable {G}
variable {α β : Type*} (C : G.Coloring α)
theorem Coloring.valid {v w : V} (h : G.Adj v w) : C v ≠ C w :=
C.map_rel h
/-- Construct a term of `SimpleGraph.Coloring` using a function that
assigns vertices to colors and a proof that it is as proper coloring.
(Note: this is a definitionally the constructor for `SimpleGraph.Hom`,
but with a syntactically better proper coloring hypothesis.)
-/
@[match_pattern]
def Coloring.mk (color : V → α) (valid : ∀ {v w : V}, G.Adj v w → color v ≠ color w) :
G.Coloring α :=
⟨color, @valid⟩
/-- The color class of a given color.
-/
def Coloring.colorClass (c : α) : Set V := { v : V | C v = c }
/-- The set containing all color classes. -/
def Coloring.colorClasses : Set (Set V) := (Setoid.ker C).classes
theorem Coloring.mem_colorClass (v : V) : v ∈ C.colorClass (C v) := rfl
theorem Coloring.colorClasses_isPartition : Setoid.IsPartition C.colorClasses :=
Setoid.isPartition_classes (Setoid.ker C)
theorem Coloring.mem_colorClasses {v : V} : C.colorClass (C v) ∈ C.colorClasses :=
⟨v, rfl⟩
theorem Coloring.colorClasses_finite [Finite α] : C.colorClasses.Finite :=
Setoid.finite_classes_ker _
theorem Coloring.card_colorClasses_le [Fintype α] [Fintype C.colorClasses] :
Fintype.card C.colorClasses ≤ Fintype.card α := by
simp only [colorClasses]
convert Setoid.card_classes_ker_le C
theorem Coloring.not_adj_of_mem_colorClass {c : α} {v w : V} (hv : v ∈ C.colorClass c)
(hw : w ∈ C.colorClass c) : ¬G.Adj v w := fun h => C.valid h (Eq.trans hv (Eq.symm hw))
theorem Coloring.color_classes_independent (c : α) : IsAntichain G.Adj (C.colorClass c) :=
fun _ hv _ hw _ => C.not_adj_of_mem_colorClass hv hw
-- TODO make this computable
noncomputable instance [Fintype V] [Fintype α] : Fintype (Coloring G α) := by
classical
change Fintype (RelHom G.Adj (⊤ : SimpleGraph α).Adj)
apply Fintype.ofInjective _ RelHom.coe_fn_injective
variable (G)
/-- Whether a graph can be colored by at most `n` colors. -/
def Colorable (n : ℕ) : Prop := Nonempty (G.Coloring (Fin n))
/-- The coloring of an empty graph. -/
def coloringOfIsEmpty [IsEmpty V] : G.Coloring α :=
Coloring.mk isEmptyElim fun {v} => isEmptyElim v
theorem colorable_of_isEmpty [IsEmpty V] (n : ℕ) : G.Colorable n :=
⟨G.coloringOfIsEmpty⟩
theorem isEmpty_of_colorable_zero (h : G.Colorable 0) : IsEmpty V := by
constructor
intro v
obtain ⟨i, hi⟩ := h.some v
exact Nat.not_lt_zero _ hi
@[simp]
lemma colorable_zero_iff : G.Colorable 0 ↔ IsEmpty V :=
⟨G.isEmpty_of_colorable_zero, fun _ ↦ G.colorable_of_isEmpty 0⟩
/-- The "tautological" coloring of a graph, using the vertices of the graph as colors. -/
def selfColoring : G.Coloring V := Coloring.mk id fun {_ _} => G.ne_of_adj
/-- The chromatic number of a graph is the minimal number of colors needed to color it.
This is `⊤` (infinity) iff `G` isn't colorable with finitely many colors.
If `G` is colorable, then `ENat.toNat G.chromaticNumber` is the `ℕ`-valued chromatic number. -/
noncomputable def chromaticNumber : ℕ∞ := ⨅ n ∈ setOf G.Colorable, (n : ℕ∞)
lemma chromaticNumber_eq_biInf {G : SimpleGraph V} :
G.chromaticNumber = ⨅ n ∈ setOf G.Colorable, (n : ℕ∞) := rfl
lemma chromaticNumber_eq_iInf {G : SimpleGraph V} :
G.chromaticNumber = ⨅ n : {m | G.Colorable m}, (n : ℕ∞) := by
rw [chromaticNumber, iInf_subtype]
lemma Colorable.chromaticNumber_eq_sInf {G : SimpleGraph V} {n} (h : G.Colorable n) :
G.chromaticNumber = sInf {n' : ℕ | G.Colorable n'} := by
rw [ENat.coe_sInf, chromaticNumber]
exact ⟨_, h⟩
/-- Given an embedding, there is an induced embedding of colorings. -/
def recolorOfEmbedding {α β : Type*} (f : α ↪ β) : G.Coloring α ↪ G.Coloring β where
toFun C := (Embedding.completeGraph f).toHom.comp C
inj' := by -- this was strangely painful; seems like missing lemmas about embeddings
intro C C' h
dsimp only at h
ext v
apply (Embedding.completeGraph f).inj'
change ((Embedding.completeGraph f).toHom.comp C) v = _
rw [h]
rfl
@[simp] lemma coe_recolorOfEmbedding (f : α ↪ β) :
⇑(G.recolorOfEmbedding f) = (Embedding.completeGraph f).toHom.comp := rfl
/-- Given an equivalence, there is an induced equivalence between colorings. -/
def recolorOfEquiv {α β : Type*} (f : α ≃ β) : G.Coloring α ≃ G.Coloring β where
toFun := G.recolorOfEmbedding f.toEmbedding
invFun := G.recolorOfEmbedding f.symm.toEmbedding
left_inv C := by
ext v
apply Equiv.symm_apply_apply
right_inv C := by
ext v
apply Equiv.apply_symm_apply
@[simp] lemma coe_recolorOfEquiv (f : α ≃ β) :
⇑(G.recolorOfEquiv f) = (Embedding.completeGraph f).toHom.comp := rfl
/-- There is a noncomputable embedding of `α`-colorings to `β`-colorings if
`β` has at least as large a cardinality as `α`. -/
noncomputable def recolorOfCardLE {α β : Type*} [Fintype α] [Fintype β]
(hn : Fintype.card α ≤ Fintype.card β) : G.Coloring α ↪ G.Coloring β :=
G.recolorOfEmbedding <| (Function.Embedding.nonempty_of_card_le hn).some
@[simp] lemma coe_recolorOfCardLE [Fintype α] [Fintype β] (hαβ : card α ≤ card β) :
⇑(G.recolorOfCardLE hαβ) =
(Embedding.completeGraph (Embedding.nonempty_of_card_le hαβ).some).toHom.comp := rfl
variable {G}
theorem Colorable.mono {n m : ℕ} (h : n ≤ m) (hc : G.Colorable n) : G.Colorable m :=
⟨G.recolorOfCardLE (by simp [h]) hc.some⟩
theorem Coloring.colorable [Fintype α] (C : G.Coloring α) : G.Colorable (Fintype.card α) :=
⟨G.recolorOfCardLE (by simp) C⟩
theorem colorable_of_fintype (G : SimpleGraph V) [Fintype V] : G.Colorable (Fintype.card V) :=
G.selfColoring.colorable
/-- Noncomputably get a coloring from colorability. -/
noncomputable def Colorable.toColoring [Fintype α] {n : ℕ} (hc : G.Colorable n)
(hn : n ≤ Fintype.card α) : G.Coloring α := by
rw [← Fintype.card_fin n] at hn
exact G.recolorOfCardLE hn hc.some
theorem Colorable.of_embedding {V' : Type*} {G' : SimpleGraph V'} (f : G ↪g G') {n : ℕ}
(h : G'.Colorable n) : G.Colorable n :=
⟨(h.toColoring (by simp)).comp f⟩
theorem colorable_iff_exists_bdd_nat_coloring (n : ℕ) :
G.Colorable n ↔ ∃ C : G.Coloring ℕ, ∀ v, C v < n := by
constructor
· rintro hc
have C : G.Coloring (Fin n) := hc.toColoring (by simp)
let f := Embedding.completeGraph (@Fin.valEmbedding n)
use f.toHom.comp C
intro v
exact Fin.is_lt (C.1 v)
· rintro ⟨C, Cf⟩
refine ⟨Coloring.mk ?_ ?_⟩
· exact fun v => ⟨C v, Cf v⟩
· rintro v w hvw
simp only [Fin.mk_eq_mk, Ne]
exact C.valid hvw
theorem colorable_set_nonempty_of_colorable {n : ℕ} (hc : G.Colorable n) :
{ n : ℕ | G.Colorable n }.Nonempty :=
⟨n, hc⟩
theorem chromaticNumber_bddBelow : BddBelow { n : ℕ | G.Colorable n } :=
⟨0, fun _ _ => zero_le _⟩
theorem Colorable.chromaticNumber_le {n : ℕ} (hc : G.Colorable n) : G.chromaticNumber ≤ n := by
rw [hc.chromaticNumber_eq_sInf]
norm_cast
apply csInf_le chromaticNumber_bddBelow
exact hc
theorem chromaticNumber_ne_top_iff_exists : G.chromaticNumber ≠ ⊤ ↔ ∃ n, G.Colorable n := by
rw [chromaticNumber]
convert_to ⨅ n : {m | G.Colorable m}, (n : ℕ∞) ≠ ⊤ ↔ _
· rw [iInf_subtype]
rw [← lt_top_iff_ne_top, ENat.iInf_coe_lt_top]
simp
theorem chromaticNumber_le_iff_colorable {n : ℕ} : G.chromaticNumber ≤ n ↔ G.Colorable n := by
refine ⟨fun h ↦ ?_, Colorable.chromaticNumber_le⟩
have : G.chromaticNumber ≠ ⊤ := (trans h (WithTop.coe_lt_top n)).ne
rw [chromaticNumber_ne_top_iff_exists] at this
obtain ⟨m, hm⟩ := this
rw [hm.chromaticNumber_eq_sInf, Nat.cast_le] at h
have := Nat.sInf_mem (⟨m, hm⟩ : {n' | G.Colorable n'}.Nonempty)
rw [Set.mem_setOf_eq] at this
exact this.mono h
theorem colorable_chromaticNumber {m : ℕ} (hc : G.Colorable m) :
G.Colorable (ENat.toNat G.chromaticNumber) := by
classical
rw [hc.chromaticNumber_eq_sInf, Nat.sInf_def]
· apply Nat.find_spec
· exact colorable_set_nonempty_of_colorable hc
theorem colorable_chromaticNumber_of_fintype (G : SimpleGraph V) [Finite V] :
G.Colorable (ENat.toNat G.chromaticNumber) := by
cases nonempty_fintype V
exact colorable_chromaticNumber G.colorable_of_fintype
theorem chromaticNumber_le_one_of_subsingleton (G : SimpleGraph V) [Subsingleton V] :
G.chromaticNumber ≤ 1 := by
rw [← Nat.cast_one, chromaticNumber_le_iff_colorable]
refine ⟨Coloring.mk (fun _ => 0) ?_⟩
intros v w
cases Subsingleton.elim v w
simp
theorem chromaticNumber_eq_zero_of_isempty (G : SimpleGraph V) [IsEmpty V] :
G.chromaticNumber = 0 := by
rw [← nonpos_iff_eq_zero, ← Nat.cast_zero, chromaticNumber_le_iff_colorable]
apply colorable_of_isEmpty
theorem isEmpty_of_chromaticNumber_eq_zero (G : SimpleGraph V) [Finite V]
(h : G.chromaticNumber = 0) : IsEmpty V := by
have h' := G.colorable_chromaticNumber_of_fintype
rw [h] at h'
exact G.isEmpty_of_colorable_zero h'
theorem chromaticNumber_pos [Nonempty V] {n : ℕ} (hc : G.Colorable n) : 0 < G.chromaticNumber := by
rw [hc.chromaticNumber_eq_sInf, Nat.cast_pos]
apply le_csInf (colorable_set_nonempty_of_colorable hc)
intro m hm
by_contra h'
simp only [not_le] at h'
obtain ⟨i, hi⟩ := hm.some (Classical.arbitrary V)
have h₁ : i < 0 := lt_of_lt_of_le hi (Nat.le_of_lt_succ h')
exact Nat.not_lt_zero _ h₁
theorem colorable_of_chromaticNumber_ne_top (h : G.chromaticNumber ≠ ⊤) :
G.Colorable (ENat.toNat G.chromaticNumber) := by
rw [chromaticNumber_ne_top_iff_exists] at h
obtain ⟨n, hn⟩ := h
exact colorable_chromaticNumber hn
theorem Colorable.mono_left {G' : SimpleGraph V} (h : G ≤ G') {n : ℕ} (hc : G'.Colorable n) :
G.Colorable n :=
⟨hc.some.comp (.ofLE h)⟩
theorem chromaticNumber_le_of_forall_imp {V' : Type*} {G' : SimpleGraph V'}
(h : ∀ n, G'.Colorable n → G.Colorable n) :
G.chromaticNumber ≤ G'.chromaticNumber := by
rw [chromaticNumber, chromaticNumber]
simp only [Set.mem_setOf_eq, le_iInf_iff]
intro m hc
have := h _ hc
rw [← chromaticNumber_le_iff_colorable] at this
exact this
theorem chromaticNumber_mono (G' : SimpleGraph V)
(h : G ≤ G') : G.chromaticNumber ≤ G'.chromaticNumber :=
chromaticNumber_le_of_forall_imp fun _ => Colorable.mono_left h
theorem chromaticNumber_mono_of_embedding {V' : Type*} {G' : SimpleGraph V'}
(f : G ↪g G') : G.chromaticNumber ≤ G'.chromaticNumber :=
chromaticNumber_le_of_forall_imp fun _ => Colorable.of_embedding f
lemma card_le_chromaticNumber_iff_forall_surjective [Fintype α] :
card α ≤ G.chromaticNumber ↔ ∀ C : G.Coloring α, Surjective C := by
refine ⟨fun h C ↦ ?_, fun h ↦ ?_⟩
· rw [C.colorable.chromaticNumber_eq_sInf, Nat.cast_le] at h
intro i
by_contra! hi
let D : G.Coloring {a // a ≠ i} := ⟨fun v ↦ ⟨C v, hi v⟩, (C.valid · <| congr_arg Subtype.val ·)⟩
classical
exact Nat.not_mem_of_lt_sInf ((Nat.sub_one_lt_of_lt <| card_pos_iff.2 ⟨i⟩).trans_le h)
⟨G.recolorOfEquiv (equivOfCardEq <| by simp [Nat.pred_eq_sub_one]) D⟩
· simp only [chromaticNumber, Set.mem_setOf_eq, le_iInf_iff, Nat.cast_le, exists_prop]
rintro i ⟨C⟩
contrapose! h
refine ⟨G.recolorOfCardLE (by simpa using h.le) C, fun hC ↦ ?_⟩
dsimp at hC
simpa [h.not_le] using Fintype.card_le_of_surjective _ hC.of_comp
lemma le_chromaticNumber_iff_forall_surjective :
n ≤ G.chromaticNumber ↔ ∀ C : G.Coloring (Fin n), Surjective C := by
simp [← card_le_chromaticNumber_iff_forall_surjective]
lemma chromaticNumber_eq_card_iff_forall_surjective [Fintype α] (hG : G.Colorable (card α)) :
G.chromaticNumber = card α ↔ ∀ C : G.Coloring α, Surjective C := by
rw [← hG.chromaticNumber_le.ge_iff_eq, card_le_chromaticNumber_iff_forall_surjective]
lemma chromaticNumber_eq_iff_forall_surjective (hG : G.Colorable n) :
G.chromaticNumber = n ↔ ∀ C : G.Coloring (Fin n), Surjective C := by
rw [← hG.chromaticNumber_le.ge_iff_eq, le_chromaticNumber_iff_forall_surjective]
theorem chromaticNumber_bot [Nonempty V] : (⊥ : SimpleGraph V).chromaticNumber = 1 := by
have : (⊥ : SimpleGraph V).Colorable 1 := ⟨.mk 0 <| by simp⟩
exact this.chromaticNumber_le.antisymm <| Order.one_le_iff_pos.2 <| chromaticNumber_pos this
@[simp]
theorem chromaticNumber_top [Fintype V] : (⊤ : SimpleGraph V).chromaticNumber = Fintype.card V := by
rw [chromaticNumber_eq_card_iff_forall_surjective (selfColoring _).colorable]
intro C
rw [← Finite.injective_iff_surjective]
intro v w
contrapose
intro h
exact C.valid h
theorem chromaticNumber_top_eq_top_of_infinite (V : Type*) [Infinite V] :
(⊤ : SimpleGraph V).chromaticNumber = ⊤ := by
by_contra hc
rw [← Ne, chromaticNumber_ne_top_iff_exists] at hc
obtain ⟨n, ⟨hn⟩⟩ := hc
exact not_injective_infinite_finite _ hn.injective_of_top_hom
/-- The bicoloring of a complete bipartite graph using whether a vertex
is on the left or on the right. -/
def CompleteBipartiteGraph.bicoloring (V W : Type*) : (completeBipartiteGraph V W).Coloring Bool :=
Coloring.mk (fun v => v.isRight)
(by
intro v w
cases v <;> cases w <;> simp)
theorem CompleteBipartiteGraph.chromaticNumber {V W : Type*} [Nonempty V] [Nonempty W] :
(completeBipartiteGraph V W).chromaticNumber = 2 := by
rw [← Nat.cast_two, chromaticNumber_eq_iff_forall_surjective
(by simpa using (CompleteBipartiteGraph.bicoloring V W).colorable)]
intro C b
have v := Classical.arbitrary V
have w := Classical.arbitrary W
have h : (completeBipartiteGraph V W).Adj (Sum.inl v) (Sum.inr w) := by simp
by_cases he : C (Sum.inl v) = b
· exact ⟨_, he⟩
by_cases he' : C (Sum.inr w) = b
· exact ⟨_, he'⟩
· simpa using two_lt_card_iff.2 ⟨_, _, _, C.valid h, he, he'⟩
/-! ### Cliques -/
theorem IsClique.card_le_of_coloring {s : Finset V} (h : G.IsClique s) [Fintype α]
(C : G.Coloring α) : s.card ≤ Fintype.card α := by
rw [isClique_iff_induce_eq] at h
have f : G.induce ↑s ↪g G := Embedding.comap (Function.Embedding.subtype fun x => x ∈ ↑s) G
rw [h] at f
convert Fintype.card_le_of_injective _ (C.comp f.toHom).injective_of_top_hom using 1
simp
theorem IsClique.card_le_of_colorable {s : Finset V} (h : G.IsClique s) {n : ℕ}
(hc : G.Colorable n) : s.card ≤ n := by
convert h.card_le_of_coloring hc.some
simp
theorem IsClique.card_le_chromaticNumber {s : Finset V} (h : G.IsClique s) :
s.card ≤ G.chromaticNumber := by
obtain (hc | hc) := eq_or_ne G.chromaticNumber ⊤
· rw [hc]
exact le_top
· have hc' := hc
rw [chromaticNumber_ne_top_iff_exists] at hc'
obtain ⟨n, c⟩ := hc'
rw [← ENat.coe_toNat_eq_self] at hc
rw [← hc, Nat.cast_le]
exact h.card_le_of_colorable (colorable_chromaticNumber c)
protected theorem Colorable.cliqueFree {n m : ℕ} (hc : G.Colorable n) (hm : n < m) :
G.CliqueFree m := by
by_contra h
simp only [CliqueFree, isNClique_iff, not_forall, Classical.not_not] at h
obtain ⟨s, h, rfl⟩ := h
exact Nat.lt_le_asymm hm (h.card_le_of_colorable hc)
theorem cliqueFree_of_chromaticNumber_lt {n : ℕ} (hc : G.chromaticNumber < n) :
G.CliqueFree n := by
have hne : G.chromaticNumber ≠ ⊤ := hc.ne_top
obtain ⟨m, hc'⟩ := chromaticNumber_ne_top_iff_exists.mp hne
have := colorable_chromaticNumber hc'
refine this.cliqueFree ?_
rw [← ENat.coe_toNat_eq_self] at hne
rw [← hne] at hc
simpa using hc
namespace completeMultipartiteGraph
variable {ι : Type*} (V : ι → Type*)
/-- The canonical `ι`-coloring of a `completeMultipartiteGraph` with parts indexed by `ι` -/
def coloring : (completeMultipartiteGraph V).Coloring ι := Coloring.mk (fun v ↦ v.1) (by simp)
lemma colorable [Fintype ι] : (completeMultipartiteGraph V).Colorable (Fintype.card ι) :=
(coloring V).colorable
theorem chromaticNumber [Fintype ι] (f : ∀ (i : ι), V i) :
(completeMultipartiteGraph V).chromaticNumber = Fintype.card ι := by
apply le_antisymm (colorable V).chromaticNumber_le
by_contra! h
exact not_cliqueFree_of_le_card V f le_rfl <| cliqueFree_of_chromaticNumber_lt h
theorem colorable_of_cliqueFree (f : ∀ (i : ι), V i)
(hc : (completeMultipartiteGraph V).CliqueFree n) :
(completeMultipartiteGraph V).Colorable (n - 1) := by
| cases n with
| zero => exact absurd hc not_cliqueFree_zero
| succ n =>
have : Fintype ι := fintypeOfNotInfinite
| Mathlib/Combinatorics/SimpleGraph/Coloring.lean | 476 | 479 |
/-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import Mathlib.Topology.Constructions
/-!
# Neighborhoods and continuity relative to a subset
This file develops API on the relative versions
* `nhdsWithin` of `nhds`
* `ContinuousOn` of `Continuous`
* `ContinuousWithinAt` of `ContinuousAt`
related to continuity, which are defined in previous definition files.
Their basic properties studied in this file include the relationships between
these restricted notions and the corresponding notions for the subtype
equipped with the subspace topology.
## Notation
* `𝓝 x`: the filter of neighborhoods of a point `x`;
* `𝓟 s`: the principal filter of a set `s`;
* `𝓝[s] x`: the filter `nhdsWithin x s` of neighborhoods of a point `x` within a set `s`.
-/
open Set Filter Function Topology Filter
variable {α β γ δ : Type*}
variable [TopologicalSpace α]
/-!
## Properties of the neighborhood-within filter
-/
@[simp]
theorem nhds_bind_nhdsWithin {a : α} {s : Set α} : ((𝓝 a).bind fun x => 𝓝[s] x) = 𝓝[s] a :=
bind_inf_principal.trans <| congr_arg₂ _ nhds_bind_nhds rfl
@[simp]
theorem eventually_nhds_nhdsWithin {a : α} {s : Set α} {p : α → Prop} :
(∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x :=
Filter.ext_iff.1 nhds_bind_nhdsWithin { x | p x }
theorem eventually_nhdsWithin_iff {a : α} {s : Set α} {p : α → Prop} :
(∀ᶠ x in 𝓝[s] a, p x) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → p x :=
eventually_inf_principal
theorem frequently_nhdsWithin_iff {z : α} {s : Set α} {p : α → Prop} :
(∃ᶠ x in 𝓝[s] z, p x) ↔ ∃ᶠ x in 𝓝 z, p x ∧ x ∈ s :=
frequently_inf_principal.trans <| by simp only [and_comm]
theorem mem_closure_ne_iff_frequently_within {z : α} {s : Set α} :
z ∈ closure (s \ {z}) ↔ ∃ᶠ x in 𝓝[≠] z, x ∈ s := by
simp [mem_closure_iff_frequently, frequently_nhdsWithin_iff]
@[simp]
theorem eventually_eventually_nhdsWithin {a : α} {s : Set α} {p : α → Prop} :
(∀ᶠ y in 𝓝[s] a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := by
refine ⟨fun h => ?_, fun h => (eventually_nhds_nhdsWithin.2 h).filter_mono inf_le_left⟩
simp only [eventually_nhdsWithin_iff] at h ⊢
exact h.mono fun x hx hxs => (hx hxs).self_of_nhds hxs
@[simp]
theorem eventually_mem_nhdsWithin_iff {x : α} {s t : Set α} :
(∀ᶠ x' in 𝓝[s] x, t ∈ 𝓝[s] x') ↔ t ∈ 𝓝[s] x :=
eventually_eventually_nhdsWithin
theorem nhdsWithin_eq (a : α) (s : Set α) :
𝓝[s] a = ⨅ t ∈ { t : Set α | a ∈ t ∧ IsOpen t }, 𝓟 (t ∩ s) :=
((nhds_basis_opens a).inf_principal s).eq_biInf
@[simp] lemma nhdsWithin_univ (a : α) : 𝓝[Set.univ] a = 𝓝 a := by
rw [nhdsWithin, principal_univ, inf_top_eq]
theorem nhdsWithin_hasBasis {ι : Sort*} {p : ι → Prop} {s : ι → Set α} {a : α}
(h : (𝓝 a).HasBasis p s) (t : Set α) : (𝓝[t] a).HasBasis p fun i => s i ∩ t :=
h.inf_principal t
theorem nhdsWithin_basis_open (a : α) (t : Set α) :
(𝓝[t] a).HasBasis (fun u => a ∈ u ∧ IsOpen u) fun u => u ∩ t :=
nhdsWithin_hasBasis (nhds_basis_opens a) t
theorem mem_nhdsWithin {t : Set α} {a : α} {s : Set α} :
t ∈ 𝓝[s] a ↔ ∃ u, IsOpen u ∧ a ∈ u ∧ u ∩ s ⊆ t := by
simpa only [and_assoc, and_left_comm] using (nhdsWithin_basis_open a s).mem_iff
theorem mem_nhdsWithin_iff_exists_mem_nhds_inter {t : Set α} {a : α} {s : Set α} :
t ∈ 𝓝[s] a ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t :=
(nhdsWithin_hasBasis (𝓝 a).basis_sets s).mem_iff
theorem diff_mem_nhdsWithin_compl {x : α} {s : Set α} (hs : s ∈ 𝓝 x) (t : Set α) :
s \ t ∈ 𝓝[tᶜ] x :=
diff_mem_inf_principal_compl hs t
theorem diff_mem_nhdsWithin_diff {x : α} {s t : Set α} (hs : s ∈ 𝓝[t] x) (t' : Set α) :
s \ t' ∈ 𝓝[t \ t'] x := by
rw [nhdsWithin, diff_eq, diff_eq, ← inf_principal, ← inf_assoc]
exact inter_mem_inf hs (mem_principal_self _)
theorem nhds_of_nhdsWithin_of_nhds {s t : Set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ 𝓝[s] a) :
t ∈ 𝓝 a := by
rcases mem_nhdsWithin_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩
exact (𝓝 a).sets_of_superset ((𝓝 a).inter_sets Hw h1) hw
theorem mem_nhdsWithin_iff_eventually {s t : Set α} {x : α} :
t ∈ 𝓝[s] x ↔ ∀ᶠ y in 𝓝 x, y ∈ s → y ∈ t :=
eventually_inf_principal
theorem mem_nhdsWithin_iff_eventuallyEq {s t : Set α} {x : α} :
t ∈ 𝓝[s] x ↔ s =ᶠ[𝓝 x] (s ∩ t : Set α) := by
simp_rw [mem_nhdsWithin_iff_eventually, eventuallyEq_set, mem_inter_iff, iff_self_and]
theorem nhdsWithin_eq_iff_eventuallyEq {s t : Set α} {x : α} : 𝓝[s] x = 𝓝[t] x ↔ s =ᶠ[𝓝 x] t :=
set_eventuallyEq_iff_inf_principal.symm
theorem nhdsWithin_le_iff {s t : Set α} {x : α} : 𝓝[s] x ≤ 𝓝[t] x ↔ t ∈ 𝓝[s] x :=
set_eventuallyLE_iff_inf_principal_le.symm.trans set_eventuallyLE_iff_mem_inf_principal
theorem preimage_nhdsWithin_coinduced' {π : α → β} {s : Set β} {t : Set α} {a : α} (h : a ∈ t)
(hs : s ∈ @nhds β (.coinduced (fun x : t => π x) inferInstance) (π a)) :
π ⁻¹' s ∈ 𝓝[t] a := by
lift a to t using h
replace hs : (fun x : t => π x) ⁻¹' s ∈ 𝓝 a := preimage_nhds_coinduced hs
rwa [← map_nhds_subtype_val, mem_map]
theorem mem_nhdsWithin_of_mem_nhds {s t : Set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ 𝓝[t] a :=
mem_inf_of_left h
theorem self_mem_nhdsWithin {a : α} {s : Set α} : s ∈ 𝓝[s] a :=
mem_inf_of_right (mem_principal_self s)
theorem eventually_mem_nhdsWithin {a : α} {s : Set α} : ∀ᶠ x in 𝓝[s] a, x ∈ s :=
self_mem_nhdsWithin
theorem inter_mem_nhdsWithin (s : Set α) {t : Set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ 𝓝[s] a :=
inter_mem self_mem_nhdsWithin (mem_inf_of_left h)
theorem pure_le_nhdsWithin {a : α} {s : Set α} (ha : a ∈ s) : pure a ≤ 𝓝[s] a :=
le_inf (pure_le_nhds a) (le_principal_iff.2 ha)
theorem mem_of_mem_nhdsWithin {a : α} {s t : Set α} (ha : a ∈ s) (ht : t ∈ 𝓝[s] a) : a ∈ t :=
pure_le_nhdsWithin ha ht
theorem Filter.Eventually.self_of_nhdsWithin {p : α → Prop} {s : Set α} {x : α}
(h : ∀ᶠ y in 𝓝[s] x, p y) (hx : x ∈ s) : p x :=
mem_of_mem_nhdsWithin hx h
theorem tendsto_const_nhdsWithin {l : Filter β} {s : Set α} {a : α} (ha : a ∈ s) :
Tendsto (fun _ : β => a) l (𝓝[s] a) :=
tendsto_const_pure.mono_right <| pure_le_nhdsWithin ha
theorem nhdsWithin_restrict'' {a : α} (s : Set α) {t : Set α} (h : t ∈ 𝓝[s] a) :
𝓝[s] a = 𝓝[s ∩ t] a :=
le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem self_mem_nhdsWithin h)))
(inf_le_inf_left _ (principal_mono.mpr Set.inter_subset_left))
theorem nhdsWithin_restrict' {a : α} (s : Set α) {t : Set α} (h : t ∈ 𝓝 a) : 𝓝[s] a = 𝓝[s ∩ t] a :=
nhdsWithin_restrict'' s <| mem_inf_of_left h
theorem nhdsWithin_restrict {a : α} (s : Set α) {t : Set α} (h₀ : a ∈ t) (h₁ : IsOpen t) :
𝓝[s] a = 𝓝[s ∩ t] a :=
nhdsWithin_restrict' s (IsOpen.mem_nhds h₁ h₀)
theorem nhdsWithin_le_of_mem {a : α} {s t : Set α} (h : s ∈ 𝓝[t] a) : 𝓝[t] a ≤ 𝓝[s] a :=
nhdsWithin_le_iff.mpr h
theorem nhdsWithin_le_nhds {a : α} {s : Set α} : 𝓝[s] a ≤ 𝓝 a := by
rw [← nhdsWithin_univ]
apply nhdsWithin_le_of_mem
exact univ_mem
theorem nhdsWithin_eq_nhdsWithin' {a : α} {s t u : Set α} (hs : s ∈ 𝓝 a) (h₂ : t ∩ s = u ∩ s) :
𝓝[t] a = 𝓝[u] a := by rw [nhdsWithin_restrict' t hs, nhdsWithin_restrict' u hs, h₂]
theorem nhdsWithin_eq_nhdsWithin {a : α} {s t u : Set α} (h₀ : a ∈ s) (h₁ : IsOpen s)
(h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by
rw [nhdsWithin_restrict t h₀ h₁, nhdsWithin_restrict u h₀ h₁, h₂]
@[simp] theorem nhdsWithin_eq_nhds {a : α} {s : Set α} : 𝓝[s] a = 𝓝 a ↔ s ∈ 𝓝 a :=
inf_eq_left.trans le_principal_iff
theorem IsOpen.nhdsWithin_eq {a : α} {s : Set α} (h : IsOpen s) (ha : a ∈ s) : 𝓝[s] a = 𝓝 a :=
nhdsWithin_eq_nhds.2 <| h.mem_nhds ha
theorem preimage_nhds_within_coinduced {π : α → β} {s : Set β} {t : Set α} {a : α} (h : a ∈ t)
(ht : IsOpen t)
(hs : s ∈ @nhds β (.coinduced (fun x : t => π x) inferInstance) (π a)) :
π ⁻¹' s ∈ 𝓝 a := by
rw [← ht.nhdsWithin_eq h]
exact preimage_nhdsWithin_coinduced' h hs
@[simp]
theorem nhdsWithin_empty (a : α) : 𝓝[∅] a = ⊥ := by rw [nhdsWithin, principal_empty, inf_bot_eq]
theorem nhdsWithin_union (a : α) (s t : Set α) : 𝓝[s ∪ t] a = 𝓝[s] a ⊔ 𝓝[t] a := by
delta nhdsWithin
rw [← inf_sup_left, sup_principal]
theorem nhds_eq_nhdsWithin_sup_nhdsWithin (b : α) {I₁ I₂ : Set α} (hI : Set.univ = I₁ ∪ I₂) :
nhds b = nhdsWithin b I₁ ⊔ nhdsWithin b I₂ := by
rw [← nhdsWithin_univ b, hI, nhdsWithin_union]
/-- If `L` and `R` are neighborhoods of `b` within sets whose union is `Set.univ`, then
`L ∪ R` is a neighborhood of `b`. -/
theorem union_mem_nhds_of_mem_nhdsWithin {b : α}
{I₁ I₂ : Set α} (h : Set.univ = I₁ ∪ I₂)
{L : Set α} (hL : L ∈ nhdsWithin b I₁)
{R : Set α} (hR : R ∈ nhdsWithin b I₂) : L ∪ R ∈ nhds b := by
rw [← nhdsWithin_univ b, h, nhdsWithin_union]
exact ⟨mem_of_superset hL (by simp), mem_of_superset hR (by simp)⟩
/-- Writing a punctured neighborhood filter as a sup of left and right filters. -/
lemma punctured_nhds_eq_nhdsWithin_sup_nhdsWithin [LinearOrder α] {x : α} :
𝓝[≠] x = 𝓝[<] x ⊔ 𝓝[>] x := by
rw [← Iio_union_Ioi, nhdsWithin_union]
/-- Obtain a "predictably-sided" neighborhood of `b` from two one-sided neighborhoods. -/
theorem nhds_of_Ici_Iic [LinearOrder α] {b : α}
{L : Set α} (hL : L ∈ 𝓝[≤] b)
{R : Set α} (hR : R ∈ 𝓝[≥] b) : L ∩ Iic b ∪ R ∩ Ici b ∈ 𝓝 b :=
union_mem_nhds_of_mem_nhdsWithin Iic_union_Ici.symm
(inter_mem hL self_mem_nhdsWithin) (inter_mem hR self_mem_nhdsWithin)
theorem nhdsWithin_biUnion {ι} {I : Set ι} (hI : I.Finite) (s : ι → Set α) (a : α) :
𝓝[⋃ i ∈ I, s i] a = ⨆ i ∈ I, 𝓝[s i] a := by
induction I, hI using Set.Finite.induction_on with
| empty => simp
| insert _ _ hT => simp only [hT, nhdsWithin_union, iSup_insert, biUnion_insert]
theorem nhdsWithin_sUnion {S : Set (Set α)} (hS : S.Finite) (a : α) :
𝓝[⋃₀ S] a = ⨆ s ∈ S, 𝓝[s] a := by
rw [sUnion_eq_biUnion, nhdsWithin_biUnion hS]
theorem nhdsWithin_iUnion {ι} [Finite ι] (s : ι → Set α) (a : α) :
𝓝[⋃ i, s i] a = ⨆ i, 𝓝[s i] a := by
rw [← sUnion_range, nhdsWithin_sUnion (finite_range s), iSup_range]
theorem nhdsWithin_inter (a : α) (s t : Set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓝[t] a := by
delta nhdsWithin
rw [inf_left_comm, inf_assoc, inf_principal, ← inf_assoc, inf_idem]
theorem nhdsWithin_inter' (a : α) (s t : Set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓟 t := by
delta nhdsWithin
rw [← inf_principal, inf_assoc]
theorem nhdsWithin_inter_of_mem {a : α} {s t : Set α} (h : s ∈ 𝓝[t] a) : 𝓝[s ∩ t] a = 𝓝[t] a := by
rw [nhdsWithin_inter, inf_eq_right]
exact nhdsWithin_le_of_mem h
theorem nhdsWithin_inter_of_mem' {a : α} {s t : Set α} (h : t ∈ 𝓝[s] a) : 𝓝[s ∩ t] a = 𝓝[s] a := by
rw [inter_comm, nhdsWithin_inter_of_mem h]
@[simp]
theorem nhdsWithin_singleton (a : α) : 𝓝[{a}] a = pure a := by
rw [nhdsWithin, principal_singleton, inf_eq_right.2 (pure_le_nhds a)]
@[simp]
theorem nhdsWithin_insert (a : α) (s : Set α) : 𝓝[insert a s] a = pure a ⊔ 𝓝[s] a := by
rw [← singleton_union, nhdsWithin_union, nhdsWithin_singleton]
theorem mem_nhdsWithin_insert {a : α} {s t : Set α} : t ∈ 𝓝[insert a s] a ↔ a ∈ t ∧ t ∈ 𝓝[s] a := by
simp
theorem insert_mem_nhdsWithin_insert {a : α} {s t : Set α} (h : t ∈ 𝓝[s] a) :
insert a t ∈ 𝓝[insert a s] a := by simp [mem_of_superset h]
theorem insert_mem_nhds_iff {a : α} {s : Set α} : insert a s ∈ 𝓝 a ↔ s ∈ 𝓝[≠] a := by
simp only [nhdsWithin, mem_inf_principal, mem_compl_iff, mem_singleton_iff, or_iff_not_imp_left,
insert_def]
@[simp]
theorem nhdsNE_sup_pure (a : α) : 𝓝[≠] a ⊔ pure a = 𝓝 a := by
rw [← nhdsWithin_singleton, ← nhdsWithin_union, compl_union_self, nhdsWithin_univ]
@[deprecated (since := "2025-03-02")]
alias nhdsWithin_compl_singleton_sup_pure := nhdsNE_sup_pure
@[simp]
| theorem pure_sup_nhdsNE (a : α) : pure a ⊔ 𝓝[≠] a = 𝓝 a := by rw [← sup_comm, nhdsNE_sup_pure]
| Mathlib/Topology/ContinuousOn.lean | 285 | 286 |
/-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne, Kexing Ying
-/
import Mathlib.Probability.Notation
import Mathlib.Probability.Process.Stopping
/-!
# Martingales
A family of functions `f : ι → Ω → E` is a martingale with respect to a filtration `ℱ` if every
`f i` is integrable, `f` is adapted with respect to `ℱ` and for all `i ≤ j`,
`μ[f j | ℱ i] =ᵐ[μ] f i`. On the other hand, `f : ι → Ω → E` is said to be a supermartingale
with respect to the filtration `ℱ` if `f i` is integrable, `f` is adapted with resepct to `ℱ`
and for all `i ≤ j`, `μ[f j | ℱ i] ≤ᵐ[μ] f i`. Finally, `f : ι → Ω → E` is said to be a
submartingale with respect to the filtration `ℱ` if `f i` is integrable, `f` is adapted with
resepct to `ℱ` and for all `i ≤ j`, `f i ≤ᵐ[μ] μ[f j | ℱ i]`.
The definitions of filtration and adapted can be found in `Probability.Process.Stopping`.
### Definitions
* `MeasureTheory.Martingale f ℱ μ`: `f` is a martingale with respect to filtration `ℱ` and
measure `μ`.
* `MeasureTheory.Supermartingale f ℱ μ`: `f` is a supermartingale with respect to
filtration `ℱ` and measure `μ`.
* `MeasureTheory.Submartingale f ℱ μ`: `f` is a submartingale with respect to filtration `ℱ` and
measure `μ`.
### Results
* `MeasureTheory.martingale_condExp f ℱ μ`: the sequence `fun i => μ[f | ℱ i, ℱ.le i])` is a
martingale with respect to `ℱ` and `μ`.
-/
open TopologicalSpace Filter
open scoped NNReal ENNReal MeasureTheory ProbabilityTheory
namespace MeasureTheory
variable {Ω E ι : Type*} [Preorder ι] {m0 : MeasurableSpace Ω} {μ : Measure Ω}
[NormedAddCommGroup E] [NormedSpace ℝ E] [CompleteSpace E] {f g : ι → Ω → E} {ℱ : Filtration ι m0}
/-- A family of functions `f : ι → Ω → E` is a martingale with respect to a filtration `ℱ` if `f`
is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] =ᵐ[μ] f i`. -/
def Martingale (f : ι → Ω → E) (ℱ : Filtration ι m0) (μ : Measure Ω) : Prop :=
Adapted ℱ f ∧ ∀ i j, i ≤ j → μ[f j|ℱ i] =ᵐ[μ] f i
/-- A family of integrable functions `f : ι → Ω → E` is a supermartingale with respect to a
filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`,
`μ[f j | ℱ.le i] ≤ᵐ[μ] f i`. -/
def Supermartingale [LE E] (f : ι → Ω → E) (ℱ : Filtration ι m0) (μ : Measure Ω) : Prop :=
Adapted ℱ f ∧ (∀ i j, i ≤ j → μ[f j|ℱ i] ≤ᵐ[μ] f i) ∧ ∀ i, Integrable (f i) μ
/-- A family of integrable functions `f : ι → Ω → E` is a submartingale with respect to a
filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`,
`f i ≤ᵐ[μ] μ[f j | ℱ.le i]`. -/
def Submartingale [LE E] (f : ι → Ω → E) (ℱ : Filtration ι m0) (μ : Measure Ω) : Prop :=
Adapted ℱ f ∧ (∀ i j, i ≤ j → f i ≤ᵐ[μ] μ[f j|ℱ i]) ∧ ∀ i, Integrable (f i) μ
theorem martingale_const (ℱ : Filtration ι m0) (μ : Measure Ω) [IsFiniteMeasure μ] (x : E) :
Martingale (fun _ _ => x) ℱ μ :=
⟨adapted_const ℱ _, fun i j _ => by rw [condExp_const (ℱ.le _)]⟩
theorem martingale_const_fun [OrderBot ι] (ℱ : Filtration ι m0) (μ : Measure Ω) [IsFiniteMeasure μ]
{f : Ω → E} (hf : StronglyMeasurable[ℱ ⊥] f) (hfint : Integrable f μ) :
Martingale (fun _ => f) ℱ μ := by
refine ⟨fun i => hf.mono <| ℱ.mono bot_le, fun i j _ => ?_⟩
rw [condExp_of_stronglyMeasurable (ℱ.le _) (hf.mono <| ℱ.mono bot_le) hfint]
variable (E) in
theorem martingale_zero (ℱ : Filtration ι m0) (μ : Measure Ω) : Martingale (0 : ι → Ω → E) ℱ μ :=
⟨adapted_zero E ℱ, fun i j _ => by rw [Pi.zero_apply, condExp_zero]; simp⟩
namespace Martingale
protected theorem adapted (hf : Martingale f ℱ μ) : Adapted ℱ f :=
hf.1
protected theorem stronglyMeasurable (hf : Martingale f ℱ μ) (i : ι) :
StronglyMeasurable[ℱ i] (f i) :=
hf.adapted i
theorem condExp_ae_eq (hf : Martingale f ℱ μ) {i j : ι} (hij : i ≤ j) : μ[f j|ℱ i] =ᵐ[μ] f i :=
hf.2 i j hij
@[deprecated (since := "2025-01-21")] alias condexp_ae_eq := condExp_ae_eq
protected theorem integrable (hf : Martingale f ℱ μ) (i : ι) : Integrable (f i) μ :=
integrable_condExp.congr (hf.condExp_ae_eq (le_refl i))
theorem setIntegral_eq [SigmaFiniteFiltration μ ℱ] (hf : Martingale f ℱ μ) {i j : ι} (hij : i ≤ j)
{s : Set Ω} (hs : MeasurableSet[ℱ i] s) : ∫ ω in s, f i ω ∂μ = ∫ ω in s, f j ω ∂μ := by
rw [← setIntegral_condExp (ℱ.le i) (hf.integrable j) hs]
refine setIntegral_congr_ae (ℱ.le i s hs) ?_
filter_upwards [hf.2 i j hij] with _ heq _ using heq.symm
theorem add (hf : Martingale f ℱ μ) (hg : Martingale g ℱ μ) : Martingale (f + g) ℱ μ := by
refine ⟨hf.adapted.add hg.adapted, fun i j hij => ?_⟩
exact (condExp_add (hf.integrable j) (hg.integrable j) _).trans
((hf.2 i j hij).add (hg.2 i j hij))
theorem neg (hf : Martingale f ℱ μ) : Martingale (-f) ℱ μ :=
⟨hf.adapted.neg, fun i j hij => (condExp_neg ..).trans (hf.2 i j hij).neg⟩
theorem sub (hf : Martingale f ℱ μ) (hg : Martingale g ℱ μ) : Martingale (f - g) ℱ μ := by
rw [sub_eq_add_neg]; exact hf.add hg.neg
theorem smul (c : ℝ) (hf : Martingale f ℱ μ) : Martingale (c • f) ℱ μ := by
refine ⟨hf.adapted.smul c, fun i j hij => ?_⟩
refine (condExp_smul ..).trans ((hf.2 i j hij).mono fun x hx => ?_)
simp only [Pi.smul_apply, hx]
theorem supermartingale [Preorder E] (hf : Martingale f ℱ μ) : Supermartingale f ℱ μ :=
⟨hf.1, fun i j hij => (hf.2 i j hij).le, fun i => hf.integrable i⟩
theorem submartingale [Preorder E] (hf : Martingale f ℱ μ) : Submartingale f ℱ μ :=
⟨hf.1, fun i j hij => (hf.2 i j hij).symm.le, fun i => hf.integrable i⟩
end Martingale
theorem martingale_iff [PartialOrder E] :
Martingale f ℱ μ ↔ Supermartingale f ℱ μ ∧ Submartingale f ℱ μ :=
⟨fun hf => ⟨hf.supermartingale, hf.submartingale⟩, fun ⟨hf₁, hf₂⟩ =>
⟨hf₁.1, fun i j hij => (hf₁.2.1 i j hij).antisymm (hf₂.2.1 i j hij)⟩⟩
theorem martingale_condExp (f : Ω → E) (ℱ : Filtration ι m0) (μ : Measure Ω)
[SigmaFiniteFiltration μ ℱ] : Martingale (fun i => μ[f|ℱ i]) ℱ μ :=
⟨fun _ => stronglyMeasurable_condExp, fun _ j hij => condExp_condExp_of_le (ℱ.mono hij) (ℱ.le j)⟩
@[deprecated (since := "2025-01-21")] alias martingale_condexp := martingale_condExp
namespace Supermartingale
protected theorem adapted [LE E] (hf : Supermartingale f ℱ μ) : Adapted ℱ f :=
hf.1
protected theorem stronglyMeasurable [LE E] (hf : Supermartingale f ℱ μ) (i : ι) :
StronglyMeasurable[ℱ i] (f i) :=
hf.adapted i
protected theorem integrable [LE E] (hf : Supermartingale f ℱ μ) (i : ι) : Integrable (f i) μ :=
hf.2.2 i
theorem condExp_ae_le [LE E] (hf : Supermartingale f ℱ μ) {i j : ι} (hij : i ≤ j) :
μ[f j|ℱ i] ≤ᵐ[μ] f i :=
hf.2.1 i j hij
@[deprecated (since := "2025-01-21")] alias condexp_ae_le := condExp_ae_le
theorem setIntegral_le [SigmaFiniteFiltration μ ℱ] {f : ι → Ω → ℝ} (hf : Supermartingale f ℱ μ)
{i j : ι} (hij : i ≤ j) {s : Set Ω} (hs : MeasurableSet[ℱ i] s) :
∫ ω in s, f j ω ∂μ ≤ ∫ ω in s, f i ω ∂μ := by
rw [← setIntegral_condExp (ℱ.le i) (hf.integrable j) hs]
refine setIntegral_mono_ae integrable_condExp.integrableOn (hf.integrable i).integrableOn ?_
filter_upwards [hf.2.1 i j hij] with _ heq using heq
theorem add [Preorder E] [AddLeftMono E] (hf : Supermartingale f ℱ μ)
(hg : Supermartingale g ℱ μ) : Supermartingale (f + g) ℱ μ := by
refine ⟨hf.1.add hg.1, fun i j hij => ?_, fun i => (hf.2.2 i).add (hg.2.2 i)⟩
refine (condExp_add (hf.integrable j) (hg.integrable j) _).le.trans ?_
filter_upwards [hf.2.1 i j hij, hg.2.1 i j hij]
intros
refine add_le_add ?_ ?_ <;> assumption
theorem add_martingale [Preorder E] [AddLeftMono E]
(hf : Supermartingale f ℱ μ) (hg : Martingale g ℱ μ) : Supermartingale (f + g) ℱ μ :=
hf.add hg.supermartingale
theorem neg [Preorder E] [AddLeftMono E] (hf : Supermartingale f ℱ μ) :
Submartingale (-f) ℱ μ := by
refine ⟨hf.1.neg, fun i j hij => ?_, fun i => (hf.2.2 i).neg⟩
refine EventuallyLE.trans ?_ (condExp_neg ..).symm.le
filter_upwards [hf.2.1 i j hij] with _ _
simpa
end Supermartingale
namespace Submartingale
protected theorem adapted [LE E] (hf : Submartingale f ℱ μ) : Adapted ℱ f :=
hf.1
protected theorem stronglyMeasurable [LE E] (hf : Submartingale f ℱ μ) (i : ι) :
StronglyMeasurable[ℱ i] (f i) :=
hf.adapted i
protected theorem integrable [LE E] (hf : Submartingale f ℱ μ) (i : ι) : Integrable (f i) μ :=
hf.2.2 i
theorem ae_le_condExp [LE E] (hf : Submartingale f ℱ μ) {i j : ι} (hij : i ≤ j) :
f i ≤ᵐ[μ] μ[f j|ℱ i] :=
hf.2.1 i j hij
@[deprecated (since := "2025-01-21")] alias ae_le_condexp := ae_le_condExp
theorem add [Preorder E] [AddLeftMono E] (hf : Submartingale f ℱ μ)
(hg : Submartingale g ℱ μ) : Submartingale (f + g) ℱ μ := by
refine ⟨hf.1.add hg.1, fun i j hij => ?_, fun i => (hf.2.2 i).add (hg.2.2 i)⟩
refine EventuallyLE.trans ?_ (condExp_add (hf.integrable j) (hg.integrable j) _).symm.le
filter_upwards [hf.2.1 i j hij, hg.2.1 i j hij]
intros
refine add_le_add ?_ ?_ <;> assumption
theorem add_martingale [Preorder E] [AddLeftMono E] (hf : Submartingale f ℱ μ)
(hg : Martingale g ℱ μ) : Submartingale (f + g) ℱ μ :=
hf.add hg.submartingale
theorem neg [Preorder E] [AddLeftMono E] (hf : Submartingale f ℱ μ) :
Supermartingale (-f) ℱ μ := by
refine ⟨hf.1.neg, fun i j hij => (condExp_neg ..).le.trans ?_, fun i => (hf.2.2 i).neg⟩
filter_upwards [hf.2.1 i j hij] with _ _
simpa
/-- The converse of this lemma is `MeasureTheory.submartingale_of_setIntegral_le`. -/
theorem setIntegral_le [SigmaFiniteFiltration μ ℱ] {f : ι → Ω → ℝ} (hf : Submartingale f ℱ μ)
{i j : ι} (hij : i ≤ j) {s : Set Ω} (hs : MeasurableSet[ℱ i] s) :
∫ ω in s, f i ω ∂μ ≤ ∫ ω in s, f j ω ∂μ := by
rw [← neg_le_neg_iff, ← integral_neg, ← integral_neg]
exact Supermartingale.setIntegral_le hf.neg hij hs
theorem sub_supermartingale [Preorder E] [AddLeftMono E]
(hf : Submartingale f ℱ μ) (hg : Supermartingale g ℱ μ) : Submartingale (f - g) ℱ μ := by
rw [sub_eq_add_neg]; exact hf.add hg.neg
theorem sub_martingale [Preorder E] [AddLeftMono E] (hf : Submartingale f ℱ μ)
(hg : Martingale g ℱ μ) : Submartingale (f - g) ℱ μ :=
hf.sub_supermartingale hg.supermartingale
protected theorem sup {f g : ι → Ω → ℝ} (hf : Submartingale f ℱ μ) (hg : Submartingale g ℱ μ) :
Submartingale (f ⊔ g) ℱ μ := by
refine ⟨fun i => @StronglyMeasurable.sup _ _ _ _ (ℱ i) _ _ _ (hf.adapted i) (hg.adapted i),
fun i j hij => ?_, fun i => Integrable.sup (hf.integrable _) (hg.integrable _)⟩
refine EventuallyLE.sup_le ?_ ?_
· exact EventuallyLE.trans (hf.2.1 i j hij)
(condExp_mono (hf.integrable _) (Integrable.sup (hf.integrable j) (hg.integrable j))
(Eventually.of_forall fun x => le_max_left _ _))
· exact EventuallyLE.trans (hg.2.1 i j hij)
(condExp_mono (hg.integrable _) (Integrable.sup (hf.integrable j) (hg.integrable j))
(Eventually.of_forall fun x => le_max_right _ _))
protected theorem pos {f : ι → Ω → ℝ} (hf : Submartingale f ℱ μ) : Submartingale (f⁺) ℱ μ :=
hf.sup (martingale_zero _ _ _).submartingale
end Submartingale
section Submartingale
theorem submartingale_of_setIntegral_le [IsFiniteMeasure μ] {f : ι → Ω → ℝ} (hadp : Adapted ℱ f)
(hint : ∀ i, Integrable (f i) μ) (hf : ∀ i j : ι,
i ≤ j → ∀ s : Set Ω, MeasurableSet[ℱ i] s → ∫ ω in s, f i ω ∂μ ≤ ∫ ω in s, f j ω ∂μ) :
Submartingale f ℱ μ := by
refine ⟨hadp, fun i j hij => ?_, hint⟩
suffices f i ≤ᵐ[μ.trim (ℱ.le i)] μ[f j|ℱ i] by exact ae_le_of_ae_le_trim this
suffices 0 ≤ᵐ[μ.trim (ℱ.le i)] μ[f j|ℱ i] - f i by
filter_upwards [this] with x hx
rwa [← sub_nonneg]
refine ae_nonneg_of_forall_setIntegral_nonneg
((integrable_condExp.sub (hint i)).trim _ (stronglyMeasurable_condExp.sub <| hadp i))
fun s hs _ => ?_
specialize hf i j hij s hs
rwa [← setIntegral_trim _ (stronglyMeasurable_condExp.sub <| hadp i) hs,
integral_sub' integrable_condExp.integrableOn (hint i).integrableOn, sub_nonneg,
setIntegral_condExp (ℱ.le i) (hint j) hs]
theorem submartingale_of_condExp_sub_nonneg [IsFiniteMeasure μ] {f : ι → Ω → ℝ} (hadp : Adapted ℱ f)
(hint : ∀ i, Integrable (f i) μ) (hf : ∀ i j, i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i|ℱ i]) :
Submartingale f ℱ μ := by
refine ⟨hadp, fun i j hij => ?_, hint⟩
rw [← condExp_of_stronglyMeasurable (ℱ.le _) (hadp _) (hint _), ← eventually_sub_nonneg]
exact EventuallyLE.trans (hf i j hij) (condExp_sub (hint _) (hint _) _).le
@[deprecated (since := "2025-01-21")]
alias submartingale_of_condexp_sub_nonneg := submartingale_of_condExp_sub_nonneg
theorem Submartingale.condExp_sub_nonneg {f : ι → Ω → ℝ} (hf : Submartingale f ℱ μ) {i j : ι}
(hij : i ≤ j) : 0 ≤ᵐ[μ] μ[f j - f i|ℱ i] := by
by_cases h : SigmaFinite (μ.trim (ℱ.le i))
swap; · rw [condExp_of_not_sigmaFinite (ℱ.le i) h]
refine EventuallyLE.trans ?_ (condExp_sub (hf.integrable _) (hf.integrable _) _).symm.le
rw [eventually_sub_nonneg,
condExp_of_stronglyMeasurable (ℱ.le _) (hf.adapted _) (hf.integrable _)]
exact hf.2.1 i j hij
@[deprecated (since := "2025-01-21")]
alias Submartingale.condexp_sub_nonneg := Submartingale.condExp_sub_nonneg
theorem submartingale_iff_condExp_sub_nonneg [IsFiniteMeasure μ] {f : ι → Ω → ℝ} :
Submartingale f ℱ μ ↔
Adapted ℱ f ∧ (∀ i, Integrable (f i) μ) ∧ ∀ i j, i ≤ j → 0 ≤ᵐ[μ] μ[f j - f i|ℱ i] :=
⟨fun h => ⟨h.adapted, h.integrable, fun _ _ => h.condExp_sub_nonneg⟩, fun ⟨hadp, hint, h⟩ =>
submartingale_of_condExp_sub_nonneg hadp hint h⟩
@[deprecated (since := "2025-01-21")]
alias submartingale_iff_condexp_sub_nonneg := submartingale_iff_condExp_sub_nonneg
end Submartingale
namespace Supermartingale
theorem sub_submartingale [Preorder E] [AddLeftMono E]
(hf : Supermartingale f ℱ μ) (hg : Submartingale g ℱ μ) : Supermartingale (f - g) ℱ μ := by
rw [sub_eq_add_neg]; exact hf.add hg.neg
theorem sub_martingale [Preorder E] [AddLeftMono E]
(hf : Supermartingale f ℱ μ) (hg : Martingale g ℱ μ) : Supermartingale (f - g) ℱ μ :=
hf.sub_submartingale hg.submartingale
section
variable {F : Type*} [NormedAddCommGroup F] [Lattice F] [NormedSpace ℝ F] [CompleteSpace F]
[OrderedSMul ℝ F]
| theorem smul_nonneg {f : ι → Ω → F} {c : ℝ} (hc : 0 ≤ c) (hf : Supermartingale f ℱ μ) :
Supermartingale (c • f) ℱ μ := by
refine ⟨hf.1.smul c, fun i j hij => ?_, fun i => (hf.2.2 i).smul c⟩
filter_upwards [condExp_smul c (f j) (ℱ i), hf.2.1 i j hij] with ω hω hle
simpa only [hω, Pi.smul_apply] using smul_le_smul_of_nonneg_left hle hc
| Mathlib/Probability/Martingale/Basic.lean | 318 | 323 |
/-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import Mathlib.MeasureTheory.MeasurableSpace.Basic
import Mathlib.MeasureTheory.Measure.MeasureSpaceDef
/-!
# Sequence of measurable functions associated to a sequence of a.e.-measurable functions
We define here tools to prove statements about limits (infi, supr...) of sequences of
`AEMeasurable` functions.
Given a sequence of a.e.-measurable functions `f : ι → α → β` with hypothesis
`hf : ∀ i, AEMeasurable (f i) μ`, and a pointwise property `p : α → (ι → β) → Prop` such that we
have `hp : ∀ᵐ x ∂μ, p x (fun n ↦ f n x)`, we define a sequence of measurable functions `aeSeq hf p`
and a measurable set `aeSeqSet hf p`, such that
* `μ (aeSeqSet hf p)ᶜ = 0`
* `x ∈ aeSeqSet hf p → ∀ i : ι, aeSeq hf hp i x = f i x`
* `x ∈ aeSeqSet hf p → p x (fun n ↦ f n x)`
-/
open MeasureTheory
variable {ι : Sort*} {α β γ : Type*} [MeasurableSpace α] [MeasurableSpace β] {f : ι → α → β}
{μ : Measure α} {p : α → (ι → β) → Prop}
/-- If we have the additional hypothesis `∀ᵐ x ∂μ, p x (fun n ↦ f n x)`, this is a measurable set
whose complement has measure 0 such that for all `x ∈ aeSeqSet`, `f i x` is equal to
`(hf i).mk (f i) x` for all `i` and we have the pointwise property `p x (fun n ↦ f n x)`. -/
def aeSeqSet (hf : ∀ i, AEMeasurable (f i) μ) (p : α → (ι → β) → Prop) : Set α :=
(toMeasurable μ { x | (∀ i, f i x = (hf i).mk (f i) x) ∧ p x fun n => f n x }ᶜ)ᶜ
open Classical in
/-- A sequence of measurable functions that are equal to `f` and verify property `p` on the
measurable set `aeSeqSet hf p`. -/
noncomputable def aeSeq (hf : ∀ i, AEMeasurable (f i) μ) (p : α → (ι → β) → Prop) : ι → α → β :=
fun i x => ite (x ∈ aeSeqSet hf p) ((hf i).mk (f i) x) (⟨f i x⟩ : Nonempty β).some
namespace aeSeq
section MemAESeqSet
theorem mk_eq_fun_of_mem_aeSeqSet (hf : ∀ i, AEMeasurable (f i) μ) {x : α} (hx : x ∈ aeSeqSet hf p)
(i : ι) : (hf i).mk (f i) x = f i x :=
haveI h_ss : aeSeqSet hf p ⊆ { x | ∀ i, f i x = (hf i).mk (f i) x } := by
rw [aeSeqSet, ← compl_compl { x | ∀ i, f i x = (hf i).mk (f i) x }, Set.compl_subset_compl]
refine Set.Subset.trans (Set.compl_subset_compl.mpr fun x h => ?_) (subset_toMeasurable _ _)
exact h.1
(h_ss hx i).symm
theorem aeSeq_eq_mk_of_mem_aeSeqSet (hf : ∀ i, AEMeasurable (f i) μ) {x : α}
(hx : x ∈ aeSeqSet hf p) (i : ι) : aeSeq hf p i x = (hf i).mk (f i) x := by
simp only [aeSeq, hx, if_true]
theorem aeSeq_eq_fun_of_mem_aeSeqSet (hf : ∀ i, AEMeasurable (f i) μ) {x : α}
(hx : x ∈ aeSeqSet hf p) (i : ι) : aeSeq hf p i x = f i x := by
simp only [aeSeq_eq_mk_of_mem_aeSeqSet hf hx i, mk_eq_fun_of_mem_aeSeqSet hf hx i]
theorem prop_of_mem_aeSeqSet (hf : ∀ i, AEMeasurable (f i) μ) {x : α} (hx : x ∈ aeSeqSet hf p) :
p x fun n => aeSeq hf p n x := by
simp only [aeSeq, hx, if_true]
rw [funext fun n => mk_eq_fun_of_mem_aeSeqSet hf hx n]
have h_ss : aeSeqSet hf p ⊆ { x | p x fun n => f n x } := by
rw [← compl_compl { x | p x fun n => f n x }, aeSeqSet, Set.compl_subset_compl]
refine Set.Subset.trans (Set.compl_subset_compl.mpr ?_) (subset_toMeasurable _ _)
exact fun x hx => hx.2
| have hx' := Set.mem_of_subset_of_mem h_ss hx
exact hx'
theorem fun_prop_of_mem_aeSeqSet (hf : ∀ i, AEMeasurable (f i) μ) {x : α} (hx : x ∈ aeSeqSet hf p) :
p x fun n => f n x := by
have h_eq : (fun n => f n x) = fun n => aeSeq hf p n x :=
funext fun n => (aeSeq_eq_fun_of_mem_aeSeqSet hf hx n).symm
rw [h_eq]
exact prop_of_mem_aeSeqSet hf hx
| Mathlib/MeasureTheory/Function/AEMeasurableSequence.lean | 69 | 78 |
/-
Copyright (c) 2024 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.Algebra.Homology.Embedding.IsSupported
import Mathlib.Algebra.Homology.Additive
import Mathlib.Algebra.Homology.Opposite
/-!
# The extension of a homological complex by an embedding of complex shapes
Given an embedding `e : Embedding c c'` of complex shapes,
and `K : HomologicalComplex C c`, we define `K.extend e : HomologicalComplex C c'`, and this
leads to a functor `e.extendFunctor C : HomologicalComplex C c ⥤ HomologicalComplex C c'`.
This construction first appeared in the Liquid Tensor Experiment.
-/
open CategoryTheory Category Limits ZeroObject
variable {ι ι' : Type*} {c : ComplexShape ι} {c' : ComplexShape ι'}
namespace HomologicalComplex
variable {C : Type*} [Category C] [HasZeroObject C]
section
variable [HasZeroMorphisms C] (K L M : HomologicalComplex C c)
(φ : K ⟶ L) (φ' : L ⟶ M) (e : c.Embedding c')
namespace extend
/-- Auxiliary definition for the `X` field of `HomologicalComplex.extend`. -/
noncomputable def X : Option ι → C
| some x => K.X x
| | none => 0
/-- The isomorphism `X K i ≅ K.X j` when `i = some j`. -/
noncomputable def XIso {i : Option ι} {j : ι} (hj : i = some j) :
| Mathlib/Algebra/Homology/Embedding/Extend.lean | 39 | 42 |
/-
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
-/
import Mathlib.MeasureTheory.Integral.Lebesgue.Basic
import Mathlib.MeasureTheory.Integral.Lebesgue.Countable
import Mathlib.MeasureTheory.Integral.Lebesgue.MeasurePreserving
import Mathlib.MeasureTheory.Integral.Lebesgue.Norm
deprecated_module (since := "2025-04-13")
| Mathlib/MeasureTheory/Integral/Lebesgue.lean | 833 | 837 | |
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Peter Nelson
-/
import Mathlib.Order.Antichain
/-!
# Minimality and Maximality
This file proves basic facts about minimality and maximality
of an element with respect to a predicate `P` on an ordered type `α`.
## Implementation Details
This file underwent a refactor from a version where minimality and maximality were defined using
sets rather than predicates, and with an unbundled order relation rather than a `LE` instance.
A side effect is that it has become less straightforward to state that something is minimal
with respect to a relation that is *not* defeq to the default `LE`.
One possible way would be with a type synonym,
and another would be with an ad hoc `LE` instance and `@` notation.
This was not an issue in practice anywhere in mathlib at the time of the refactor,
but it may be worth re-examining this to make it easier in the future; see the TODO below.
## TODO
* In the linearly ordered case, versions of lemmas like `minimal_mem_image` will hold with
`MonotoneOn`/`AntitoneOn` assumptions rather than the stronger `x ≤ y ↔ f x ≤ f y` assumptions.
* `Set.maximal_iff_forall_insert` and `Set.minimal_iff_forall_diff_singleton` will generalize to
lemmas about covering in the case of an `IsStronglyAtomic`/`IsStronglyCoatomic` order.
* `Finset` versions of the lemmas about sets.
* API to allow for easily expressing min/maximality with respect to an arbitrary non-`LE` relation.
* API for `MinimalFor`/`MaximalFor`
-/
assert_not_exists CompleteLattice
open Set OrderDual
variable {α : Type*} {P Q : α → Prop} {a x y : α}
section LE
variable [LE α]
@[simp] theorem minimal_toDual : Minimal (fun x ↦ P (ofDual x)) (toDual x) ↔ Maximal P x :=
Iff.rfl
alias ⟨Minimal.of_dual, Minimal.dual⟩ := minimal_toDual
@[simp] theorem maximal_toDual : Maximal (fun x ↦ P (ofDual x)) (toDual x) ↔ Minimal P x :=
Iff.rfl
alias ⟨Maximal.of_dual, Maximal.dual⟩ := maximal_toDual
@[simp] theorem minimal_false : ¬ Minimal (fun _ ↦ False) x := by
simp [Minimal]
@[simp] theorem maximal_false : ¬ Maximal (fun _ ↦ False) x := by
simp [Maximal]
@[simp] theorem minimal_true : Minimal (fun _ ↦ True) x ↔ IsMin x := by
simp [IsMin, Minimal]
@[simp] theorem maximal_true : Maximal (fun _ ↦ True) x ↔ IsMax x :=
minimal_true (α := αᵒᵈ)
@[simp] theorem minimal_subtype {x : Subtype Q} :
Minimal (fun x ↦ P x.1) x ↔ Minimal (P ⊓ Q) x := by
obtain ⟨x, hx⟩ := x
simp only [Minimal, Subtype.forall, Subtype.mk_le_mk, Pi.inf_apply, inf_Prop_eq]
tauto
@[simp] theorem maximal_subtype {x : Subtype Q} :
Maximal (fun x ↦ P x.1) x ↔ Maximal (P ⊓ Q) x :=
minimal_subtype (α := αᵒᵈ)
theorem maximal_true_subtype {x : Subtype P} : Maximal (fun _ ↦ True) x ↔ Maximal P x := by
obtain ⟨x, hx⟩ := x
simp [Maximal, hx]
theorem minimal_true_subtype {x : Subtype P} : Minimal (fun _ ↦ True) x ↔ Minimal P x := by
obtain ⟨x, hx⟩ := x
simp [Minimal, hx]
@[simp] theorem minimal_minimal : Minimal (Minimal P) x ↔ Minimal P x :=
⟨fun h ↦ h.prop, fun h ↦ ⟨h, fun _ hy hyx ↦ h.le_of_le hy.prop hyx⟩⟩
@[simp] theorem maximal_maximal : Maximal (Maximal P) x ↔ Maximal P x :=
minimal_minimal (α := αᵒᵈ)
/-- If `P` is down-closed, then minimal elements satisfying `P` are exactly the globally minimal
elements satisfying `P`. -/
theorem minimal_iff_isMin (hP : ∀ ⦃x y⦄, P y → x ≤ y → P x) : Minimal P x ↔ P x ∧ IsMin x :=
⟨fun h ↦ ⟨h.prop, fun _ h' ↦ h.le_of_le (hP h.prop h') h'⟩, fun h ↦ ⟨h.1, fun _ _ h' ↦ h.2 h'⟩⟩
/-- If `P` is up-closed, then maximal elements satisfying `P` are exactly the globally maximal
elements satisfying `P`. -/
theorem maximal_iff_isMax (hP : ∀ ⦃x y⦄, P y → y ≤ x → P x) : Maximal P x ↔ P x ∧ IsMax x :=
⟨fun h ↦ ⟨h.prop, fun _ h' ↦ h.le_of_ge (hP h.prop h') h'⟩, fun h ↦ ⟨h.1, fun _ _ h' ↦ h.2 h'⟩⟩
theorem Minimal.mono (h : Minimal P x) (hle : Q ≤ P) (hQ : Q x) : Minimal Q x :=
⟨hQ, fun y hQy ↦ h.le_of_le (hle y hQy)⟩
theorem Maximal.mono (h : Maximal P x) (hle : Q ≤ P) (hQ : Q x) : Maximal Q x :=
⟨hQ, fun y hQy ↦ h.le_of_ge (hle y hQy)⟩
theorem Minimal.and_right (h : Minimal P x) (hQ : Q x) : Minimal (fun x ↦ P x ∧ Q x) x :=
h.mono (fun _ ↦ And.left) ⟨h.prop, hQ⟩
theorem Minimal.and_left (h : Minimal P x) (hQ : Q x) : Minimal (fun x ↦ (Q x ∧ P x)) x :=
h.mono (fun _ ↦ And.right) ⟨hQ, h.prop⟩
theorem Maximal.and_right (h : Maximal P x) (hQ : Q x) : Maximal (fun x ↦ (P x ∧ Q x)) x :=
h.mono (fun _ ↦ And.left) ⟨h.prop, hQ⟩
theorem Maximal.and_left (h : Maximal P x) (hQ : Q x) : Maximal (fun x ↦ (Q x ∧ P x)) x :=
h.mono (fun _ ↦ And.right) ⟨hQ, h.prop⟩
@[simp] theorem minimal_eq_iff : Minimal (· = y) x ↔ x = y := by
simp +contextual [Minimal]
@[simp] theorem maximal_eq_iff : Maximal (· = y) x ↔ x = y := by
simp +contextual [Maximal]
theorem not_minimal_iff (hx : P x) : ¬ Minimal P x ↔ ∃ y, P y ∧ y ≤ x ∧ ¬ (x ≤ y) := by
simp [Minimal, hx]
theorem not_maximal_iff (hx : P x) : ¬ Maximal P x ↔ ∃ y, P y ∧ x ≤ y ∧ ¬ (y ≤ x) :=
not_minimal_iff (α := αᵒᵈ) hx
theorem Minimal.or (h : Minimal (fun x ↦ P x ∨ Q x) x) : Minimal P x ∨ Minimal Q x := by
obtain ⟨h | h, hmin⟩ := h
· exact .inl ⟨h, fun y hy hyx ↦ hmin (Or.inl hy) hyx⟩
exact .inr ⟨h, fun y hy hyx ↦ hmin (Or.inr hy) hyx⟩
theorem Maximal.or (h : Maximal (fun x ↦ P x ∨ Q x) x) : Maximal P x ∨ Maximal Q x :=
Minimal.or (α := αᵒᵈ) h
theorem minimal_and_iff_right_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) :
Minimal (fun x ↦ P x ∧ Q x) x ↔ (Minimal P x) ∧ Q x := by
simp_rw [and_iff_left_of_imp (fun x ↦ hPQ x), iff_self_and]
exact fun h ↦ hPQ h.prop
theorem minimal_and_iff_left_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) :
Minimal (fun x ↦ Q x ∧ P x) x ↔ Q x ∧ (Minimal P x) := by
simp_rw [iff_comm, and_comm, minimal_and_iff_right_of_imp hPQ, and_comm]
theorem maximal_and_iff_right_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) :
Maximal (fun x ↦ P x ∧ Q x) x ↔ (Maximal P x) ∧ Q x :=
minimal_and_iff_right_of_imp (α := αᵒᵈ) hPQ
theorem maximal_and_iff_left_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) :
Maximal (fun x ↦ Q x ∧ P x) x ↔ Q x ∧ (Maximal P x) :=
minimal_and_iff_left_of_imp (α := αᵒᵈ) hPQ
end LE
section Preorder
variable [Preorder α]
theorem minimal_iff_forall_lt : Minimal P x ↔ P x ∧ ∀ ⦃y⦄, y < x → ¬ P y := by
simp [Minimal, lt_iff_le_not_le, not_imp_not, imp.swap]
theorem maximal_iff_forall_gt : Maximal P x ↔ P x ∧ ∀ ⦃y⦄, x < y → ¬ P y :=
minimal_iff_forall_lt (α := αᵒᵈ)
theorem Minimal.not_prop_of_lt (h : Minimal P x) (hlt : y < x) : ¬ P y :=
(minimal_iff_forall_lt.1 h).2 hlt
theorem Maximal.not_prop_of_gt (h : Maximal P x) (hlt : x < y) : ¬ P y :=
(maximal_iff_forall_gt.1 h).2 hlt
theorem Minimal.not_lt (h : Minimal P x) (hy : P y) : ¬ (y < x) :=
fun hlt ↦ h.not_prop_of_lt hlt hy
theorem Maximal.not_gt (h : Maximal P x) (hy : P y) : ¬ (x < y) :=
fun hlt ↦ h.not_prop_of_gt hlt hy
@[simp] theorem minimal_le_iff : Minimal (· ≤ y) x ↔ x ≤ y ∧ IsMin x :=
minimal_iff_isMin (fun _ _ h h' ↦ h'.trans h)
@[simp] theorem maximal_ge_iff : Maximal (y ≤ ·) x ↔ y ≤ x ∧ IsMax x :=
minimal_le_iff (α := αᵒᵈ)
@[simp] theorem minimal_lt_iff : Minimal (· < y) x ↔ x < y ∧ IsMin x :=
minimal_iff_isMin (fun _ _ h h' ↦ h'.trans_lt h)
@[simp] theorem maximal_gt_iff : Maximal (y < ·) x ↔ y < x ∧ IsMax x :=
minimal_lt_iff (α := αᵒᵈ)
theorem not_minimal_iff_exists_lt (hx : P x) : ¬ Minimal P x ↔ ∃ y, y < x ∧ P y := by
simp_rw [not_minimal_iff hx, lt_iff_le_not_le, and_comm]
alias ⟨exists_lt_of_not_minimal, _⟩ := not_minimal_iff_exists_lt
theorem not_maximal_iff_exists_gt (hx : P x) : ¬ Maximal P x ↔ ∃ y, x < y ∧ P y :=
| not_minimal_iff_exists_lt (α := αᵒᵈ) hx
alias ⟨exists_gt_of_not_maximal, _⟩ := not_maximal_iff_exists_gt
end Preorder
| Mathlib/Order/Minimal.lean | 203 | 208 |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Kim Morrison, Jens Wagemaker
-/
import Mathlib.Algebra.MonoidAlgebra.Degree
import Mathlib.Algebra.Order.Ring.WithTop
import Mathlib.Algebra.Polynomial.Basic
import Mathlib.Data.Nat.Cast.WithTop
import Mathlib.Data.Nat.SuccPred
import Mathlib.Order.SuccPred.WithBot
/-!
# Degree of univariate polynomials
## Main definitions
* `Polynomial.degree`: the degree of a polynomial, where `0` has degree `⊥`
* `Polynomial.natDegree`: the degree of a polynomial, where `0` has degree `0`
* `Polynomial.leadingCoeff`: the leading coefficient of a polynomial
* `Polynomial.Monic`: a polynomial is monic if its leading coefficient is 0
* `Polynomial.nextCoeff`: the next coefficient after the leading coefficient
## Main results
* `Polynomial.degree_eq_natDegree`: the degree and natDegree coincide for nonzero polynomials
-/
noncomputable section
open Finsupp Finset
open Polynomial
namespace Polynomial
universe u v
variable {R : Type u} {S : Type v} {a b c d : R} {n m : ℕ}
section Semiring
variable [Semiring R] {p q r : R[X]}
/-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`.
`degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise
`degree 0 = ⊥`. -/
def degree (p : R[X]) : WithBot ℕ :=
p.support.max
/-- `natDegree p` forces `degree p` to ℕ, by defining `natDegree 0 = 0`. -/
def natDegree (p : R[X]) : ℕ :=
(degree p).unbotD 0
/-- `leadingCoeff p` gives the coefficient of the highest power of `X` in `p`. -/
def leadingCoeff (p : R[X]) : R :=
coeff p (natDegree p)
/-- a polynomial is `Monic` if its leading coefficient is 1 -/
def Monic (p : R[X]) :=
leadingCoeff p = (1 : R)
theorem Monic.def : Monic p ↔ leadingCoeff p = 1 :=
Iff.rfl
instance Monic.decidable [DecidableEq R] : Decidable (Monic p) := by unfold Monic; infer_instance
@[simp]
theorem Monic.leadingCoeff {p : R[X]} (hp : p.Monic) : leadingCoeff p = 1 :=
hp
theorem Monic.coeff_natDegree {p : R[X]} (hp : p.Monic) : p.coeff p.natDegree = 1 :=
hp
@[simp]
theorem degree_zero : degree (0 : R[X]) = ⊥ :=
rfl
@[simp]
theorem natDegree_zero : natDegree (0 : R[X]) = 0 :=
rfl
@[simp]
theorem coeff_natDegree : coeff p (natDegree p) = leadingCoeff p :=
rfl
@[simp]
theorem degree_eq_bot : degree p = ⊥ ↔ p = 0 :=
⟨fun h => support_eq_empty.1 (Finset.max_eq_bot.1 h), fun h => h.symm ▸ rfl⟩
theorem degree_ne_bot : degree p ≠ ⊥ ↔ p ≠ 0 := degree_eq_bot.not
theorem degree_eq_natDegree (hp : p ≠ 0) : degree p = (natDegree p : WithBot ℕ) := by
let ⟨n, hn⟩ := not_forall.1 (mt Option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp))
have hn : degree p = some n := Classical.not_not.1 hn
rw [natDegree, hn]; rfl
theorem degree_eq_iff_natDegree_eq {p : R[X]} {n : ℕ} (hp : p ≠ 0) :
p.degree = n ↔ p.natDegree = n := by rw [degree_eq_natDegree hp]; exact WithBot.coe_eq_coe
theorem degree_eq_iff_natDegree_eq_of_pos {p : R[X]} {n : ℕ} (hn : 0 < n) :
p.degree = n ↔ p.natDegree = n := by
obtain rfl|h := eq_or_ne p 0
· simp [hn.ne]
· exact degree_eq_iff_natDegree_eq h
theorem natDegree_eq_of_degree_eq_some {p : R[X]} {n : ℕ} (h : degree p = n) : natDegree p = n := by
rw [natDegree, h, Nat.cast_withBot, WithBot.unbotD_coe]
theorem degree_ne_of_natDegree_ne {n : ℕ} : p.natDegree ≠ n → degree p ≠ n :=
mt natDegree_eq_of_degree_eq_some
@[simp]
theorem degree_le_natDegree : degree p ≤ natDegree p :=
WithBot.giUnbotDBot.gc.le_u_l _
theorem natDegree_eq_of_degree_eq [Semiring S] {q : S[X]} (h : degree p = degree q) :
natDegree p = natDegree q := by unfold natDegree; rw [h]
theorem le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : WithBot ℕ) ≤ degree p := by
rw [Nat.cast_withBot]
exact Finset.le_sup (mem_support_iff.2 h)
theorem degree_mono [Semiring S] {f : R[X]} {g : S[X]} (h : f.support ⊆ g.support) :
f.degree ≤ g.degree :=
Finset.sup_mono h
theorem degree_le_degree (h : coeff q (natDegree p) ≠ 0) : degree p ≤ degree q := by
by_cases hp : p = 0
· rw [hp, degree_zero]
exact bot_le
· rw [degree_eq_natDegree hp]
exact le_degree_of_ne_zero h
theorem natDegree_le_iff_degree_le {n : ℕ} : natDegree p ≤ n ↔ degree p ≤ n :=
WithBot.unbotD_le_iff (fun _ ↦ bot_le)
theorem natDegree_lt_iff_degree_lt (hp : p ≠ 0) : p.natDegree < n ↔ p.degree < ↑n :=
WithBot.unbotD_lt_iff (absurd · (degree_eq_bot.not.mpr hp))
alias ⟨degree_le_of_natDegree_le, natDegree_le_of_degree_le⟩ := natDegree_le_iff_degree_le
theorem natDegree_le_natDegree [Semiring S] {q : S[X]} (hpq : p.degree ≤ q.degree) :
p.natDegree ≤ q.natDegree :=
WithBot.giUnbotDBot.gc.monotone_l hpq
@[simp]
theorem degree_C (ha : a ≠ 0) : degree (C a) = (0 : WithBot ℕ) := by
rw [degree, ← monomial_zero_left, support_monomial 0 ha, max_eq_sup_coe, sup_singleton,
WithBot.coe_zero]
theorem degree_C_le : degree (C a) ≤ 0 := by
by_cases h : a = 0
· rw [h, C_0]
exact bot_le
· rw [degree_C h]
theorem degree_C_lt : degree (C a) < 1 :=
degree_C_le.trans_lt <| WithBot.coe_lt_coe.mpr zero_lt_one
theorem degree_one_le : degree (1 : R[X]) ≤ (0 : WithBot ℕ) := by rw [← C_1]; exact degree_C_le
@[simp]
theorem natDegree_C (a : R) : natDegree (C a) = 0 := by
by_cases ha : a = 0
· have : C a = 0 := by rw [ha, C_0]
rw [natDegree, degree_eq_bot.2 this, WithBot.unbotD_bot]
· rw [natDegree, degree_C ha, WithBot.unbotD_zero]
@[simp]
theorem natDegree_one : natDegree (1 : R[X]) = 0 :=
natDegree_C 1
@[simp]
theorem natDegree_natCast (n : ℕ) : natDegree (n : R[X]) = 0 := by
simp only [← C_eq_natCast, natDegree_C]
@[simp]
theorem natDegree_ofNat (n : ℕ) [Nat.AtLeastTwo n] :
natDegree (ofNat(n) : R[X]) = 0 :=
natDegree_natCast _
theorem degree_natCast_le (n : ℕ) : degree (n : R[X]) ≤ 0 := degree_le_of_natDegree_le (by simp)
@[simp]
theorem degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := by
rw [degree, support_monomial n ha, max_singleton, Nat.cast_withBot]
@[simp]
theorem degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by
rw [C_mul_X_pow_eq_monomial, degree_monomial n ha]
theorem degree_C_mul_X (ha : a ≠ 0) : degree (C a * X) = 1 := by
simpa only [pow_one] using degree_C_mul_X_pow 1 ha
theorem degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n :=
letI := Classical.decEq R
if h : a = 0 then by rw [h, (monomial n).map_zero, degree_zero]; exact bot_le
else le_of_eq (degree_monomial n h)
theorem degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := by
rw [C_mul_X_pow_eq_monomial]
apply degree_monomial_le
theorem degree_C_mul_X_le (a : R) : degree (C a * X) ≤ 1 := by
simpa only [pow_one] using degree_C_mul_X_pow_le 1 a
@[simp]
theorem natDegree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : natDegree (C a * X ^ n) = n :=
natDegree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha)
@[simp]
theorem natDegree_C_mul_X (a : R) (ha : a ≠ 0) : natDegree (C a * X) = 1 := by
simpa only [pow_one] using natDegree_C_mul_X_pow 1 a ha
@[simp]
theorem natDegree_monomial [DecidableEq R] (i : ℕ) (r : R) :
natDegree (monomial i r) = if r = 0 then 0 else i := by
split_ifs with hr
· simp [hr]
· rw [← C_mul_X_pow_eq_monomial, natDegree_C_mul_X_pow i r hr]
theorem natDegree_monomial_le (a : R) {m : ℕ} : (monomial m a).natDegree ≤ m := by
classical
rw [Polynomial.natDegree_monomial]
split_ifs
exacts [Nat.zero_le _, le_rfl]
theorem natDegree_monomial_eq (i : ℕ) {r : R} (r0 : r ≠ 0) : (monomial i r).natDegree = i :=
letI := Classical.decEq R
Eq.trans (natDegree_monomial _ _) (if_neg r0)
theorem coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := fun h =>
mem_support_iff.mp (mem_of_max hn) h
theorem degree_X_pow_le (n : ℕ) : degree (X ^ n : R[X]) ≤ n := by
simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1 : R)
theorem degree_X_le : degree (X : R[X]) ≤ 1 :=
degree_monomial_le _ _
theorem natDegree_X_le : (X : R[X]).natDegree ≤ 1 :=
natDegree_le_of_degree_le degree_X_le
theorem withBotSucc_degree_eq_natDegree_add_one (h : p ≠ 0) : p.degree.succ = p.natDegree + 1 := by
rw [degree_eq_natDegree h]
exact WithBot.succ_coe p.natDegree
end Semiring
section NonzeroSemiring
variable [Semiring R] [Nontrivial R] {p q : R[X]}
@[simp]
theorem degree_one : degree (1 : R[X]) = (0 : WithBot ℕ) :=
degree_C one_ne_zero
@[simp]
theorem degree_X : degree (X : R[X]) = 1 :=
degree_monomial _ one_ne_zero
@[simp]
theorem natDegree_X : (X : R[X]).natDegree = 1 :=
natDegree_eq_of_degree_eq_some degree_X
end NonzeroSemiring
section Ring
variable [Ring R]
@[simp]
theorem degree_neg (p : R[X]) : degree (-p) = degree p := by unfold degree; rw [support_neg]
theorem degree_neg_le_of_le {a : WithBot ℕ} {p : R[X]} (hp : degree p ≤ a) : degree (-p) ≤ a :=
p.degree_neg.le.trans hp
@[simp]
theorem natDegree_neg (p : R[X]) : natDegree (-p) = natDegree p := by simp [natDegree]
theorem natDegree_neg_le_of_le {p : R[X]} (hp : natDegree p ≤ m) : natDegree (-p) ≤ m :=
(natDegree_neg p).le.trans hp
@[simp]
theorem natDegree_intCast (n : ℤ) : natDegree (n : R[X]) = 0 := by
rw [← C_eq_intCast, natDegree_C]
theorem degree_intCast_le (n : ℤ) : degree (n : R[X]) ≤ 0 := degree_le_of_natDegree_le (by simp)
@[simp]
theorem leadingCoeff_neg (p : R[X]) : (-p).leadingCoeff = -p.leadingCoeff := by
rw [leadingCoeff, leadingCoeff, natDegree_neg, coeff_neg]
end Ring
section Semiring
variable [Semiring R] {p : R[X]}
/-- The second-highest coefficient, or 0 for constants -/
def nextCoeff (p : R[X]) : R :=
if p.natDegree = 0 then 0 else p.coeff (p.natDegree - 1)
lemma nextCoeff_eq_zero :
p.nextCoeff = 0 ↔ p.natDegree = 0 ∨ 0 < p.natDegree ∧ p.coeff (p.natDegree - 1) = 0 := by
simp [nextCoeff, or_iff_not_imp_left, pos_iff_ne_zero]; aesop
lemma nextCoeff_ne_zero : p.nextCoeff ≠ 0 ↔ p.natDegree ≠ 0 ∧ p.coeff (p.natDegree - 1) ≠ 0 := by
simp [nextCoeff]
@[simp]
theorem nextCoeff_C_eq_zero (c : R) : nextCoeff (C c) = 0 := by
rw [nextCoeff]
simp
theorem nextCoeff_of_natDegree_pos (hp : 0 < p.natDegree) :
nextCoeff p = p.coeff (p.natDegree - 1) := by
rw [nextCoeff, if_neg]
contrapose! hp
simpa
variable {p q : R[X]} {ι : Type*}
theorem degree_add_le (p q : R[X]) : degree (p + q) ≤ max (degree p) (degree q) := by
simpa only [degree, ← support_toFinsupp, toFinsupp_add]
using AddMonoidAlgebra.sup_support_add_le _ _ _
theorem degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : degree p ≤ n) (hq : degree q ≤ n) :
degree (p + q) ≤ n :=
(degree_add_le p q).trans <| max_le hp hq
theorem degree_add_le_of_le {a b : WithBot ℕ} (hp : degree p ≤ a) (hq : degree q ≤ b) :
degree (p + q) ≤ max a b :=
(p.degree_add_le q).trans <| max_le_max ‹_› ‹_›
theorem natDegree_add_le (p q : R[X]) : natDegree (p + q) ≤ max (natDegree p) (natDegree q) := by
rcases le_max_iff.1 (degree_add_le p q) with h | h <;> simp [natDegree_le_natDegree h]
theorem natDegree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : natDegree p ≤ n)
(hq : natDegree q ≤ n) : natDegree (p + q) ≤ n :=
(natDegree_add_le p q).trans <| max_le hp hq
theorem natDegree_add_le_of_le (hp : natDegree p ≤ m) (hq : natDegree q ≤ n) :
natDegree (p + q) ≤ max m n :=
(p.natDegree_add_le q).trans <| max_le_max ‹_› ‹_›
@[simp]
theorem leadingCoeff_zero : leadingCoeff (0 : R[X]) = 0 :=
rfl
@[simp]
theorem leadingCoeff_eq_zero : leadingCoeff p = 0 ↔ p = 0 :=
⟨fun h =>
Classical.by_contradiction fun hp =>
mt mem_support_iff.1 (Classical.not_not.2 h) (mem_of_max (degree_eq_natDegree hp)),
fun h => h.symm ▸ leadingCoeff_zero⟩
theorem leadingCoeff_ne_zero : leadingCoeff p ≠ 0 ↔ p ≠ 0 := by rw [Ne, leadingCoeff_eq_zero]
theorem leadingCoeff_eq_zero_iff_deg_eq_bot : leadingCoeff p = 0 ↔ degree p = ⊥ := by
rw [leadingCoeff_eq_zero, degree_eq_bot]
theorem natDegree_C_mul_X_pow_le (a : R) (n : ℕ) : natDegree (C a * X ^ n) ≤ n :=
natDegree_le_iff_degree_le.2 <| degree_C_mul_X_pow_le _ _
theorem degree_erase_le (p : R[X]) (n : ℕ) : degree (p.erase n) ≤ degree p := by
rcases p with ⟨p⟩
simp only [erase_def, degree, coeff, support]
apply sup_mono
rw [Finsupp.support_erase]
apply Finset.erase_subset
theorem degree_erase_lt (hp : p ≠ 0) : degree (p.erase (natDegree p)) < degree p := by
apply lt_of_le_of_ne (degree_erase_le _ _)
rw [degree_eq_natDegree hp, degree, support_erase]
exact fun h => not_mem_erase _ _ (mem_of_max h)
theorem degree_update_le (p : R[X]) (n : ℕ) (a : R) : degree (p.update n a) ≤ max (degree p) n := by
classical
rw [degree, support_update]
split_ifs
· exact (Finset.max_mono (erase_subset _ _)).trans (le_max_left _ _)
· rw [max_insert, max_comm]
exact le_rfl
theorem degree_sum_le (s : Finset ι) (f : ι → R[X]) :
degree (∑ i ∈ s, f i) ≤ s.sup fun b => degree (f b) :=
Finset.cons_induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl])
fun a s has ih =>
calc
degree (∑ i ∈ cons a s has, f i) ≤ max (degree (f a)) (degree (∑ i ∈ s, f i)) := by
rw [Finset.sum_cons]; exact degree_add_le _ _
_ ≤ _ := by rw [sup_cons]; exact max_le_max le_rfl ih
theorem degree_mul_le (p q : R[X]) : degree (p * q) ≤ degree p + degree q := by
simpa only [degree, ← support_toFinsupp, toFinsupp_mul]
using AddMonoidAlgebra.sup_support_mul_le (WithBot.coe_add _ _).le _ _
theorem degree_mul_le_of_le {a b : WithBot ℕ} (hp : degree p ≤ a) (hq : degree q ≤ b) :
degree (p * q) ≤ a + b :=
(p.degree_mul_le _).trans <| add_le_add ‹_› ‹_›
theorem degree_pow_le (p : R[X]) : ∀ n : ℕ, degree (p ^ n) ≤ n • degree p
| 0 => by rw [pow_zero, zero_nsmul]; exact degree_one_le
| n + 1 =>
calc
degree (p ^ (n + 1)) ≤ degree (p ^ n) + degree p := by
rw [pow_succ]; exact degree_mul_le _ _
_ ≤ _ := by rw [succ_nsmul]; exact add_le_add_right (degree_pow_le _ _) _
theorem degree_pow_le_of_le {a : WithBot ℕ} (b : ℕ) (hp : degree p ≤ a) :
degree (p ^ b) ≤ b * a := by
induction b with
| zero => simp [degree_one_le]
| succ n hn =>
rw [Nat.cast_succ, add_mul, one_mul, pow_succ]
exact degree_mul_le_of_le hn hp
@[simp]
theorem leadingCoeff_monomial (a : R) (n : ℕ) : leadingCoeff (monomial n a) = a := by
classical
by_cases ha : a = 0
· simp only [ha, (monomial n).map_zero, leadingCoeff_zero]
· rw [leadingCoeff, natDegree_monomial, if_neg ha, coeff_monomial]
simp
theorem leadingCoeff_C_mul_X_pow (a : R) (n : ℕ) : leadingCoeff (C a * X ^ n) = a := by
rw [C_mul_X_pow_eq_monomial, leadingCoeff_monomial]
theorem leadingCoeff_C_mul_X (a : R) : leadingCoeff (C a * X) = a := by
simpa only [pow_one] using leadingCoeff_C_mul_X_pow a 1
@[simp]
theorem leadingCoeff_C (a : R) : leadingCoeff (C a) = a :=
leadingCoeff_monomial a 0
theorem leadingCoeff_X_pow (n : ℕ) : leadingCoeff ((X : R[X]) ^ n) = 1 := by
simpa only [C_1, one_mul] using leadingCoeff_C_mul_X_pow (1 : R) n
theorem leadingCoeff_X : leadingCoeff (X : R[X]) = 1 := by
simpa only [pow_one] using @leadingCoeff_X_pow R _ 1
@[simp]
theorem monic_X_pow (n : ℕ) : Monic (X ^ n : R[X]) :=
leadingCoeff_X_pow n
@[simp]
theorem monic_X : Monic (X : R[X]) :=
leadingCoeff_X
theorem leadingCoeff_one : leadingCoeff (1 : R[X]) = 1 :=
leadingCoeff_C 1
@[simp]
theorem monic_one : Monic (1 : R[X]) :=
leadingCoeff_C _
theorem Monic.ne_zero {R : Type*} [Semiring R] [Nontrivial R] {p : R[X]} (hp : p.Monic) :
p ≠ 0 := by
rintro rfl
simp [Monic] at hp
theorem Monic.ne_zero_of_ne (h : (0 : R) ≠ 1) {p : R[X]} (hp : p.Monic) : p ≠ 0 := by
nontriviality R
exact hp.ne_zero
theorem Monic.ne_zero_of_polynomial_ne {r} (hp : Monic p) (hne : q ≠ r) : p ≠ 0 :=
haveI := Nontrivial.of_polynomial_ne hne
hp.ne_zero
theorem natDegree_mul_le {p q : R[X]} : natDegree (p * q) ≤ natDegree p + natDegree q := by
apply natDegree_le_of_degree_le
apply le_trans (degree_mul_le p q)
rw [Nat.cast_add]
apply add_le_add <;> apply degree_le_natDegree
theorem natDegree_mul_le_of_le (hp : natDegree p ≤ m) (hg : natDegree q ≤ n) :
natDegree (p * q) ≤ m + n :=
natDegree_mul_le.trans <| add_le_add ‹_› ‹_›
theorem natDegree_pow_le {p : R[X]} {n : ℕ} : (p ^ n).natDegree ≤ n * p.natDegree := by
induction n with
| zero => simp
| succ i hi =>
rw [pow_succ, Nat.succ_mul]
apply le_trans natDegree_mul_le (add_le_add_right hi _)
theorem natDegree_pow_le_of_le (n : ℕ) (hp : natDegree p ≤ m) :
natDegree (p ^ n) ≤ n * m :=
natDegree_pow_le.trans (Nat.mul_le_mul le_rfl ‹_›)
theorem natDegree_eq_zero_iff_degree_le_zero : p.natDegree = 0 ↔ p.degree ≤ 0 := by
rw [← nonpos_iff_eq_zero, natDegree_le_iff_degree_le, Nat.cast_zero]
theorem degree_zero_le : degree (0 : R[X]) ≤ 0 := natDegree_eq_zero_iff_degree_le_zero.mp rfl
theorem degree_le_iff_coeff_zero (f : R[X]) (n : WithBot ℕ) :
degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := by
simp only [degree, Finset.max, Finset.sup_le_iff, mem_support_iff, Ne, ← not_le,
not_imp_comm, Nat.cast_withBot]
theorem degree_lt_iff_coeff_zero (f : R[X]) (n : ℕ) :
degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 := by
simp only [degree, Finset.sup_lt_iff (WithBot.bot_lt_coe n), mem_support_iff,
WithBot.coe_lt_coe, ← @not_le ℕ, max_eq_sup_coe, Nat.cast_withBot, Ne, not_imp_not]
theorem natDegree_pos_iff_degree_pos : 0 < natDegree p ↔ 0 < degree p :=
lt_iff_lt_of_le_iff_le natDegree_le_iff_degree_le
end Semiring
section NontrivialSemiring
variable [Semiring R] [Nontrivial R] {p q : R[X]} (n : ℕ)
@[simp]
theorem degree_X_pow : degree ((X : R[X]) ^ n) = n := by
rw [X_pow_eq_monomial, degree_monomial _ (one_ne_zero' R)]
@[simp]
theorem natDegree_X_pow : natDegree ((X : R[X]) ^ n) = n :=
natDegree_eq_of_degree_eq_some (degree_X_pow n)
end NontrivialSemiring
section Ring
variable [Ring R] {p q : R[X]}
theorem degree_sub_le (p q : R[X]) : degree (p - q) ≤ max (degree p) (degree q) := by
simpa only [degree_neg q] using degree_add_le p (-q)
theorem degree_sub_le_of_le {a b : WithBot ℕ} (hp : degree p ≤ a) (hq : degree q ≤ b) :
degree (p - q) ≤ max a b :=
(p.degree_sub_le q).trans <| max_le_max ‹_› ‹_›
theorem natDegree_sub_le (p q : R[X]) : natDegree (p - q) ≤ max (natDegree p) (natDegree q) := by
simpa only [← natDegree_neg q] using natDegree_add_le p (-q)
theorem natDegree_sub_le_of_le (hp : natDegree p ≤ m) (hq : natDegree q ≤ n) :
natDegree (p - q) ≤ max m n :=
(p.natDegree_sub_le q).trans <| max_le_max ‹_› ‹_›
theorem degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0)
(hlc : leadingCoeff p = leadingCoeff q) : degree (p - q) < degree p :=
have hp : monomial (natDegree p) (leadingCoeff p) + p.erase (natDegree p) = p :=
monomial_add_erase _ _
have hq : monomial (natDegree q) (leadingCoeff q) + q.erase (natDegree q) = q :=
monomial_add_erase _ _
have hd' : natDegree p = natDegree q := by unfold natDegree; rw [hd]
have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0)
calc
degree (p - q) = degree (erase (natDegree q) p + -erase (natDegree q) q) := by
conv =>
lhs
rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]
_ ≤ max (degree (erase (natDegree q) p)) (degree (erase (natDegree q) q)) :=
(degree_neg (erase (natDegree q) q) ▸ degree_add_le _ _)
_ < degree p := max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩
theorem degree_X_sub_C_le (r : R) : (X - C r).degree ≤ 1 :=
(degree_sub_le _ _).trans (max_le degree_X_le (degree_C_le.trans zero_le_one))
theorem natDegree_X_sub_C_le (r : R) : (X - C r).natDegree ≤ 1 :=
natDegree_le_iff_degree_le.2 <| degree_X_sub_C_le r
end Ring
end Polynomial
| Mathlib/Algebra/Polynomial/Degree/Definitions.lean | 1,385 | 1,385 | |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Kim Morrison, Jens Wagemaker
-/
import Mathlib.Algebra.Order.Group.Finset
import Mathlib.Algebra.Polynomial.Derivative
import Mathlib.Algebra.Polynomial.Eval.SMul
import Mathlib.Algebra.Polynomial.Roots
import Mathlib.RingTheory.EuclideanDomain
import Mathlib.RingTheory.UniqueFactorizationDomain.NormalizedFactors
/-!
# Theory of univariate polynomials
This file starts looking like the ring theory of $R[X]$
-/
noncomputable section
open Polynomial
namespace Polynomial
universe u v w y z
variable {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ}
section CommRing
variable [CommRing R]
theorem rootMultiplicity_sub_one_le_derivative_rootMultiplicity_of_ne_zero
(p : R[X]) (t : R) (hnezero : derivative p ≠ 0) :
p.rootMultiplicity t - 1 ≤ p.derivative.rootMultiplicity t :=
(le_rootMultiplicity_iff hnezero).2 <|
pow_sub_one_dvd_derivative_of_pow_dvd (p.pow_rootMultiplicity_dvd t)
theorem derivative_rootMultiplicity_of_root_of_mem_nonZeroDivisors
{p : R[X]} {t : R} (hpt : Polynomial.IsRoot p t)
(hnzd : (p.rootMultiplicity t : R) ∈ nonZeroDivisors R) :
(derivative p).rootMultiplicity t = p.rootMultiplicity t - 1 := by
by_cases h : p = 0
· simp only [h, map_zero, rootMultiplicity_zero]
obtain ⟨g, hp, hndvd⟩ := p.exists_eq_pow_rootMultiplicity_mul_and_not_dvd h t
set m := p.rootMultiplicity t
have hm : m - 1 + 1 = m := Nat.sub_add_cancel <| (rootMultiplicity_pos h).2 hpt
have hndvd : ¬(X - C t) ^ m ∣ derivative p := by
rw [hp, derivative_mul, dvd_add_left (dvd_mul_right _ _),
derivative_X_sub_C_pow, ← hm, pow_succ, hm, mul_comm (C _), mul_assoc,
dvd_cancel_left_mem_nonZeroDivisors (monic_X_sub_C t |>.pow _ |>.mem_nonZeroDivisors)]
rw [dvd_iff_isRoot, IsRoot] at hndvd ⊢
rwa [eval_mul, eval_C, mul_left_mem_nonZeroDivisors_eq_zero_iff hnzd]
have hnezero : derivative p ≠ 0 := fun h ↦ hndvd (by rw [h]; exact dvd_zero _)
exact le_antisymm (by rwa [rootMultiplicity_le_iff hnezero, hm])
(rootMultiplicity_sub_one_le_derivative_rootMultiplicity_of_ne_zero _ t hnezero)
theorem isRoot_iterate_derivative_of_lt_rootMultiplicity {p : R[X]} {t : R} {n : ℕ}
(hn : n < p.rootMultiplicity t) : (derivative^[n] p).IsRoot t :=
dvd_iff_isRoot.mp <| (dvd_pow_self _ <| Nat.sub_ne_zero_of_lt hn).trans
(pow_sub_dvd_iterate_derivative_of_pow_dvd _ <| p.pow_rootMultiplicity_dvd t)
open Finset in
theorem eval_iterate_derivative_rootMultiplicity {p : R[X]} {t : R} :
(derivative^[p.rootMultiplicity t] p).eval t =
(p.rootMultiplicity t).factorial • (p /ₘ (X - C t) ^ p.rootMultiplicity t).eval t := by
set m := p.rootMultiplicity t with hm
conv_lhs => rw [← p.pow_mul_divByMonic_rootMultiplicity_eq t, ← hm]
rw [iterate_derivative_mul, eval_finset_sum, sum_eq_single_of_mem _ (mem_range.mpr m.succ_pos)]
· rw [m.choose_zero_right, one_smul, eval_mul, m.sub_zero, iterate_derivative_X_sub_pow_self,
eval_natCast, nsmul_eq_mul]; rfl
· intro b hb hb0
rw [iterate_derivative_X_sub_pow, eval_smul, eval_mul, eval_smul, eval_pow,
Nat.sub_sub_self (mem_range_succ_iff.mp hb), eval_sub, eval_X, eval_C, sub_self,
zero_pow hb0, smul_zero, zero_mul, smul_zero]
theorem lt_rootMultiplicity_of_isRoot_iterate_derivative_of_mem_nonZeroDivisors
{p : R[X]} {t : R} {n : ℕ} (h : p ≠ 0)
(hroot : ∀ m ≤ n, (derivative^[m] p).IsRoot t)
(hnzd : (n.factorial : R) ∈ nonZeroDivisors R) :
n < p.rootMultiplicity t := by
by_contra! h'
replace hroot := hroot _ h'
simp only [IsRoot, eval_iterate_derivative_rootMultiplicity] at hroot
obtain ⟨q, hq⟩ := Nat.cast_dvd_cast (α := R) <| Nat.factorial_dvd_factorial h'
rw [hq, mul_mem_nonZeroDivisors] at hnzd
rw [nsmul_eq_mul, mul_left_mem_nonZeroDivisors_eq_zero_iff hnzd.1] at hroot
exact eval_divByMonic_pow_rootMultiplicity_ne_zero t h hroot
theorem lt_rootMultiplicity_of_isRoot_iterate_derivative_of_mem_nonZeroDivisors'
{p : R[X]} {t : R} {n : ℕ} (h : p ≠ 0)
(hroot : ∀ m ≤ n, (derivative^[m] p).IsRoot t)
(hnzd : ∀ m ≤ n, m ≠ 0 → (m : R) ∈ nonZeroDivisors R) :
n < p.rootMultiplicity t := by
apply lt_rootMultiplicity_of_isRoot_iterate_derivative_of_mem_nonZeroDivisors h hroot
clear hroot
induction n with
| zero =>
simp only [Nat.factorial_zero, Nat.cast_one]
exact Submonoid.one_mem _
| succ n ih =>
rw [Nat.factorial_succ, Nat.cast_mul, mul_mem_nonZeroDivisors]
exact ⟨hnzd _ le_rfl n.succ_ne_zero, ih fun m h ↦ hnzd m (h.trans n.le_succ)⟩
theorem lt_rootMultiplicity_iff_isRoot_iterate_derivative_of_mem_nonZeroDivisors
{p : R[X]} {t : R} {n : ℕ} (h : p ≠ 0)
(hnzd : (n.factorial : R) ∈ nonZeroDivisors R) :
n < p.rootMultiplicity t ↔ ∀ m ≤ n, (derivative^[m] p).IsRoot t :=
⟨fun hn _ hm ↦ isRoot_iterate_derivative_of_lt_rootMultiplicity <| hm.trans_lt hn,
fun hr ↦ lt_rootMultiplicity_of_isRoot_iterate_derivative_of_mem_nonZeroDivisors h hr hnzd⟩
theorem lt_rootMultiplicity_iff_isRoot_iterate_derivative_of_mem_nonZeroDivisors'
{p : R[X]} {t : R} {n : ℕ} (h : p ≠ 0)
(hnzd : ∀ m ≤ n, m ≠ 0 → (m : R) ∈ nonZeroDivisors R) :
n < p.rootMultiplicity t ↔ ∀ m ≤ n, (derivative^[m] p).IsRoot t :=
⟨fun hn _ hm ↦ isRoot_iterate_derivative_of_lt_rootMultiplicity <| Nat.lt_of_le_of_lt hm hn,
fun hr ↦ lt_rootMultiplicity_of_isRoot_iterate_derivative_of_mem_nonZeroDivisors' h hr hnzd⟩
theorem one_lt_rootMultiplicity_iff_isRoot_iterate_derivative
{p : R[X]} {t : R} (h : p ≠ 0) :
1 < p.rootMultiplicity t ↔ ∀ m ≤ 1, (derivative^[m] p).IsRoot t :=
| lt_rootMultiplicity_iff_isRoot_iterate_derivative_of_mem_nonZeroDivisors h
(by rw [Nat.factorial_one, Nat.cast_one]; exact Submonoid.one_mem _)
theorem one_lt_rootMultiplicity_iff_isRoot
{p : R[X]} {t : R} (h : p ≠ 0) :
1 < p.rootMultiplicity t ↔ p.IsRoot t ∧ (derivative p).IsRoot t := by
rw [one_lt_rootMultiplicity_iff_isRoot_iterate_derivative h]
| Mathlib/Algebra/Polynomial/FieldDivision.lean | 124 | 130 |
/-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import Mathlib.Data.Set.Insert
/-!
# Subsingleton
Defines the predicate `Subsingleton s : Prop`, saying that `s` has at most one element.
Also defines `Nontrivial s : Prop` : the predicate saying that `s` has at least two distinct
elements.
-/
assert_not_exists RelIso
open Function
universe u v
namespace Set
/-! ### Subsingleton -/
section Subsingleton
variable {α : Type u} {a : α} {s t : Set α}
/-- A set `s` is a `Subsingleton` if it has at most one element. -/
protected def Subsingleton (s : Set α) : Prop :=
∀ ⦃x⦄ (_ : x ∈ s) ⦃y⦄ (_ : y ∈ s), x = y
theorem Subsingleton.anti (ht : t.Subsingleton) (hst : s ⊆ t) : s.Subsingleton := fun _ hx _ hy =>
ht (hst hx) (hst hy)
theorem Subsingleton.eq_singleton_of_mem (hs : s.Subsingleton) {x : α} (hx : x ∈ s) : s = {x} :=
ext fun _ => ⟨fun hy => hs hx hy ▸ mem_singleton _, fun hy => (eq_of_mem_singleton hy).symm ▸ hx⟩
@[simp]
theorem subsingleton_empty : (∅ : Set α).Subsingleton := fun _ => False.elim
@[simp]
theorem subsingleton_singleton {a} : ({a} : Set α).Subsingleton := fun _ hx _ hy =>
(eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl
theorem subsingleton_of_subset_singleton (h : s ⊆ {a}) : s.Subsingleton :=
subsingleton_singleton.anti h
theorem subsingleton_of_forall_eq (a : α) (h : ∀ b ∈ s, b = a) : s.Subsingleton := fun _ hb _ hc =>
(h _ hb).trans (h _ hc).symm
theorem subsingleton_iff_singleton {x} (hx : x ∈ s) : s.Subsingleton ↔ s = {x} :=
⟨fun h => h.eq_singleton_of_mem hx, fun h => h.symm ▸ subsingleton_singleton⟩
theorem Subsingleton.eq_empty_or_singleton (hs : s.Subsingleton) : s = ∅ ∨ ∃ x, s = {x} :=
s.eq_empty_or_nonempty.elim Or.inl fun ⟨x, hx⟩ => Or.inr ⟨x, hs.eq_singleton_of_mem hx⟩
theorem Subsingleton.induction_on {p : Set α → Prop} (hs : s.Subsingleton) (he : p ∅)
(h₁ : ∀ x, p {x}) : p s := by
rcases hs.eq_empty_or_singleton with (rfl | ⟨x, rfl⟩)
exacts [he, h₁ _]
theorem subsingleton_univ [Subsingleton α] : (univ : Set α).Subsingleton := fun x _ y _ =>
Subsingleton.elim x y
theorem subsingleton_of_univ_subsingleton (h : (univ : Set α).Subsingleton) : Subsingleton α :=
⟨fun a b => h (mem_univ a) (mem_univ b)⟩
@[simp]
theorem subsingleton_univ_iff : (univ : Set α).Subsingleton ↔ Subsingleton α :=
⟨subsingleton_of_univ_subsingleton, fun h => @subsingleton_univ _ h⟩
lemma Subsingleton.inter_singleton : (s ∩ {a}).Subsingleton :=
Set.subsingleton_of_subset_singleton Set.inter_subset_right
lemma Subsingleton.singleton_inter : ({a} ∩ s).Subsingleton :=
Set.subsingleton_of_subset_singleton Set.inter_subset_left
theorem subsingleton_of_subsingleton [Subsingleton α] {s : Set α} : Set.Subsingleton s :=
subsingleton_univ.anti (subset_univ s)
theorem subsingleton_isTop (α : Type*) [PartialOrder α] : Set.Subsingleton { x : α | IsTop x } :=
fun x hx _ hy => hx.isMax.eq_of_le (hy x)
theorem subsingleton_isBot (α : Type*) [PartialOrder α] : Set.Subsingleton { x : α | IsBot x } :=
fun x hx _ hy => hx.isMin.eq_of_ge (hy x)
theorem exists_eq_singleton_iff_nonempty_subsingleton :
(∃ a : α, s = {a}) ↔ s.Nonempty ∧ s.Subsingleton := by
refine ⟨?_, fun h => ?_⟩
· rintro ⟨a, rfl⟩
exact ⟨singleton_nonempty a, subsingleton_singleton⟩
· exact h.2.eq_empty_or_singleton.resolve_left h.1.ne_empty
/-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/
| @[simp, norm_cast]
theorem subsingleton_coe (s : Set α) : Subsingleton s ↔ s.Subsingleton := by
constructor
· refine fun h => fun a ha b hb => ?_
exact SetCoe.ext_iff.2 (@Subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩)
· exact fun h => Subsingleton.intro fun a b => SetCoe.ext (h a.property b.property)
| Mathlib/Data/Set/Subsingleton.lean | 99 | 104 |
/-
Copyright (c) 2024 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.CategoryTheory.Comma.StructuredArrow.Basic
import Mathlib.CategoryTheory.Limits.Shapes.Equivalence
import Mathlib.CategoryTheory.Limits.Preserves.Shapes.Terminal
/-!
# Kan extensions
The basic definitions for Kan extensions of functors is introduced in this file. Part of API
is parallel to the definitions for bicategories (see `CategoryTheory.Bicategory.Kan.IsKan`).
(The bicategory API cannot be used directly here because it would not allow the universe
polymorphism which is necessary for some applications.)
Given a natural transformation `α : L ⋙ F' ⟶ F`, we define the property
`F'.IsRightKanExtension α` which expresses that `(F', α)` is a right Kan
extension of `F` along `L`, i.e. that it is a terminal object in a
category `RightExtension L F` of costructured arrows. The condition
`F'.IsLeftKanExtension α` for `α : F ⟶ L ⋙ F'` is defined similarly.
We also introduce typeclasses `HasRightKanExtension L F` and `HasLeftKanExtension L F`
which assert the existence of a right or left Kan extension, and chosen Kan extensions
are obtained as `leftKanExtension L F` and `rightKanExtension L F`.
## References
* https://ncatlab.org/nlab/show/Kan+extension
-/
namespace CategoryTheory
open Category Limits
namespace Functor
variable {C C' H D D' : Type*} [Category C] [Category C'] [Category H] [Category D] [Category D']
/-- Given two functors `L : C ⥤ D` and `F : C ⥤ H`, this is the category of functors
`F' : H ⥤ D` equipped with a natural transformation `L ⋙ F' ⟶ F`. -/
abbrev RightExtension (L : C ⥤ D) (F : C ⥤ H) :=
CostructuredArrow ((whiskeringLeft C D H).obj L) F
/-- Given two functors `L : C ⥤ D` and `F : C ⥤ H`, this is the category of functors
`F' : H ⥤ D` equipped with a natural transformation `F ⟶ L ⋙ F'`. -/
abbrev LeftExtension (L : C ⥤ D) (F : C ⥤ H) :=
StructuredArrow F ((whiskeringLeft C D H).obj L)
/-- Constructor for objects of the category `Functor.RightExtension L F`. -/
@[simps!]
def RightExtension.mk (F' : D ⥤ H) {L : C ⥤ D} {F : C ⥤ H} (α : L ⋙ F' ⟶ F) :
RightExtension L F :=
CostructuredArrow.mk α
/-- Constructor for objects of the category `Functor.LeftExtension L F`. -/
@[simps!]
def LeftExtension.mk (F' : D ⥤ H) {L : C ⥤ D} {F : C ⥤ H} (α : F ⟶ L ⋙ F') :
LeftExtension L F :=
StructuredArrow.mk α
section
variable (F' : D ⥤ H) {L : C ⥤ D} {F : C ⥤ H} (α : L ⋙ F' ⟶ F)
/-- Given `α : L ⋙ F' ⟶ F`, the property `F'.IsRightKanExtension α` asserts that
`(F', α)` is a terminal object in the category `RightExtension L F`, i.e. that `(F', α)`
is a right Kan extension of `F` along `L`. -/
class IsRightKanExtension : Prop where
nonempty_isUniversal : Nonempty (RightExtension.mk F' α).IsUniversal
variable [F'.IsRightKanExtension α]
/-- If `(F', α)` is a right Kan extension of `F` along `L`, then `(F', α)` is a terminal object
in the category `RightExtension L F`. -/
noncomputable def isUniversalOfIsRightKanExtension : (RightExtension.mk F' α).IsUniversal :=
IsRightKanExtension.nonempty_isUniversal.some
/-- If `(F', α)` is a right Kan extension of `F` along `L` and `β : L ⋙ G ⟶ F` is
a natural transformation, this is the induced morphism `G ⟶ F'`. -/
noncomputable def liftOfIsRightKanExtension (G : D ⥤ H) (β : L ⋙ G ⟶ F) : G ⟶ F' :=
(F'.isUniversalOfIsRightKanExtension α).lift (RightExtension.mk G β)
@[reassoc (attr := simp)]
lemma liftOfIsRightKanExtension_fac (G : D ⥤ H) (β : L ⋙ G ⟶ F) :
whiskerLeft L (F'.liftOfIsRightKanExtension α G β) ≫ α = β :=
(F'.isUniversalOfIsRightKanExtension α).fac (RightExtension.mk G β)
@[reassoc (attr := simp)]
lemma liftOfIsRightKanExtension_fac_app (G : D ⥤ H) (β : L ⋙ G ⟶ F) (X : C) :
(F'.liftOfIsRightKanExtension α G β).app (L.obj X) ≫ α.app X = β.app X :=
NatTrans.congr_app (F'.liftOfIsRightKanExtension_fac α G β) X
lemma hom_ext_of_isRightKanExtension {G : D ⥤ H} (γ₁ γ₂ : G ⟶ F')
(hγ : whiskerLeft L γ₁ ≫ α = whiskerLeft L γ₂ ≫ α) : γ₁ = γ₂ :=
(F'.isUniversalOfIsRightKanExtension α).hom_ext hγ
/-- If `(F', α)` is a right Kan extension of `F` along `L`, then this
is the induced bijection `(G ⟶ F') ≃ (L ⋙ G ⟶ F)` for all `G`. -/
noncomputable def homEquivOfIsRightKanExtension (G : D ⥤ H) :
(G ⟶ F') ≃ (L ⋙ G ⟶ F) where
toFun β := whiskerLeft _ β ≫ α
invFun β := liftOfIsRightKanExtension _ α _ β
left_inv β := Functor.hom_ext_of_isRightKanExtension _ α _ _ (by simp)
right_inv := by aesop_cat
lemma isRightKanExtension_of_iso {F' F'' : D ⥤ H} (e : F' ≅ F'') {L : C ⥤ D} {F : C ⥤ H}
(α : L ⋙ F' ⟶ F) (α' : L ⋙ F'' ⟶ F) (comm : whiskerLeft L e.hom ≫ α' = α)
[F'.IsRightKanExtension α] : F''.IsRightKanExtension α' where
nonempty_isUniversal := ⟨IsTerminal.ofIso (F'.isUniversalOfIsRightKanExtension α)
(CostructuredArrow.isoMk e comm)⟩
lemma isRightKanExtension_iff_of_iso {F' F'' : D ⥤ H} (e : F' ≅ F'') {L : C ⥤ D} {F : C ⥤ H}
(α : L ⋙ F' ⟶ F) (α' : L ⋙ F'' ⟶ F) (comm : whiskerLeft L e.hom ≫ α' = α) :
F'.IsRightKanExtension α ↔ F''.IsRightKanExtension α' := by
constructor
· intro
exact isRightKanExtension_of_iso e α α' comm
· intro
refine isRightKanExtension_of_iso e.symm α' α ?_
rw [← comm, ← whiskerLeft_comp_assoc, Iso.symm_hom, e.inv_hom_id, whiskerLeft_id', id_comp]
/-- Right Kan extensions of isomorphic functors are isomorphic. -/
@[simps]
noncomputable def rightKanExtensionUniqueOfIso {G : C ⥤ H} (i : F ≅ G) (G' : D ⥤ H)
(β : L ⋙ G' ⟶ G) [G'.IsRightKanExtension β] : F' ≅ G' where
hom := liftOfIsRightKanExtension _ β F' (α ≫ i.hom)
inv := liftOfIsRightKanExtension _ α G' (β ≫ i.inv)
hom_inv_id := F'.hom_ext_of_isRightKanExtension α _ _ (by simp)
inv_hom_id := G'.hom_ext_of_isRightKanExtension β _ _ (by simp)
/-- Two right Kan extensions are (canonically) isomorphic. -/
@[simps!]
noncomputable def rightKanExtensionUnique
(F'' : D ⥤ H) (α' : L ⋙ F'' ⟶ F) [F''.IsRightKanExtension α'] : F' ≅ F'' :=
rightKanExtensionUniqueOfIso F' α (Iso.refl _) F'' α'
lemma isRightKanExtension_iff_isIso {F' : D ⥤ H} {F'' : D ⥤ H} (φ : F'' ⟶ F')
{L : C ⥤ D} {F : C ⥤ H} (α : L ⋙ F' ⟶ F) (α' : L ⋙ F'' ⟶ F)
(comm : whiskerLeft L φ ≫ α = α') [F'.IsRightKanExtension α] :
F''.IsRightKanExtension α' ↔ IsIso φ := by
constructor
· intro
rw [F'.hom_ext_of_isRightKanExtension α φ (rightKanExtensionUnique _ α' _ α).hom
(by simp [comm])]
infer_instance
· intro
rw [isRightKanExtension_iff_of_iso (asIso φ) α' α comm]
infer_instance
end
section
variable (F' : D ⥤ H) {L : C ⥤ D} {F : C ⥤ H} (α : F ⟶ L ⋙ F')
/-- Given `α : F ⟶ L ⋙ F'`, the property `F'.IsLeftKanExtension α` asserts that
`(F', α)` is an initial object in the category `LeftExtension L F`, i.e. that `(F', α)`
is a left Kan extension of `F` along `L`. -/
class IsLeftKanExtension : Prop where
nonempty_isUniversal : Nonempty (LeftExtension.mk F' α).IsUniversal
variable [F'.IsLeftKanExtension α]
/-- If `(F', α)` is a left Kan extension of `F` along `L`, then `(F', α)` is an initial object
in the category `LeftExtension L F`. -/
noncomputable def isUniversalOfIsLeftKanExtension : (LeftExtension.mk F' α).IsUniversal :=
IsLeftKanExtension.nonempty_isUniversal.some
/-- If `(F', α)` is a left Kan extension of `F` along `L` and `β : F ⟶ L ⋙ G` is
a natural transformation, this is the induced morphism `F' ⟶ G`. -/
noncomputable def descOfIsLeftKanExtension (G : D ⥤ H) (β : F ⟶ L ⋙ G) : F' ⟶ G :=
(F'.isUniversalOfIsLeftKanExtension α).desc (LeftExtension.mk G β)
@[reassoc (attr := simp)]
lemma descOfIsLeftKanExtension_fac (G : D ⥤ H) (β : F ⟶ L ⋙ G) :
α ≫ whiskerLeft L (F'.descOfIsLeftKanExtension α G β) = β :=
(F'.isUniversalOfIsLeftKanExtension α).fac (LeftExtension.mk G β)
@[reassoc (attr := simp)]
lemma descOfIsLeftKanExtension_fac_app (G : D ⥤ H) (β : F ⟶ L ⋙ G) (X : C) :
α.app X ≫ (F'.descOfIsLeftKanExtension α G β).app (L.obj X) = β.app X :=
NatTrans.congr_app (F'.descOfIsLeftKanExtension_fac α G β) X
lemma hom_ext_of_isLeftKanExtension {G : D ⥤ H} (γ₁ γ₂ : F' ⟶ G)
(hγ : α ≫ whiskerLeft L γ₁ = α ≫ whiskerLeft L γ₂) : γ₁ = γ₂ :=
(F'.isUniversalOfIsLeftKanExtension α).hom_ext hγ
/-- If `(F', α)` is a left Kan extension of `F` along `L`, then this
is the induced bijection `(F' ⟶ G) ≃ (F ⟶ L ⋙ G)` for all `G`. -/
noncomputable def homEquivOfIsLeftKanExtension (G : D ⥤ H) :
(F' ⟶ G) ≃ (F ⟶ L ⋙ G) where
toFun β := α ≫ whiskerLeft _ β
invFun β := descOfIsLeftKanExtension _ α _ β
left_inv β := Functor.hom_ext_of_isLeftKanExtension _ α _ _ (by simp)
right_inv := by aesop_cat
lemma isLeftKanExtension_of_iso {F' : D ⥤ H} {F'' : D ⥤ H} (e : F' ≅ F'')
{L : C ⥤ D} {F : C ⥤ H} (α : F ⟶ L ⋙ F') (α' : F ⟶ L ⋙ F'')
(comm : α ≫ whiskerLeft L e.hom = α') [F'.IsLeftKanExtension α] :
F''.IsLeftKanExtension α' where
nonempty_isUniversal := ⟨IsInitial.ofIso (F'.isUniversalOfIsLeftKanExtension α)
(StructuredArrow.isoMk e comm)⟩
lemma isLeftKanExtension_iff_of_iso {F' F'' : D ⥤ H} (e : F' ≅ F'')
{L : C ⥤ D} {F : C ⥤ H} (α : F ⟶ L ⋙ F') (α' : F ⟶ L ⋙ F'')
(comm : α ≫ whiskerLeft L e.hom = α') :
F'.IsLeftKanExtension α ↔ F''.IsLeftKanExtension α' := by
constructor
· intro
exact isLeftKanExtension_of_iso e α α' comm
· intro
refine isLeftKanExtension_of_iso e.symm α' α ?_
rw [← comm, assoc, ← whiskerLeft_comp, Iso.symm_hom, e.hom_inv_id, whiskerLeft_id', comp_id]
/-- Left Kan extensions of isomorphic functors are isomorphic. -/
@[simps]
noncomputable def leftKanExtensionUniqueOfIso {G : C ⥤ H} (i : F ≅ G) (G' : D ⥤ H)
| (β : G ⟶ L ⋙ G') [G'.IsLeftKanExtension β] : F' ≅ G' where
hom := descOfIsLeftKanExtension _ α G' (i.hom ≫ β)
inv := descOfIsLeftKanExtension _ β F' (i.inv ≫ α)
hom_inv_id := F'.hom_ext_of_isLeftKanExtension α _ _ (by simp)
inv_hom_id := G'.hom_ext_of_isLeftKanExtension β _ _ (by simp)
/-- Two left Kan extensions are (canonically) isomorphic. -/
@[simps!]
noncomputable def leftKanExtensionUnique
(F'' : D ⥤ H) (α' : F ⟶ L ⋙ F'') [F''.IsLeftKanExtension α'] : F' ≅ F'' :=
leftKanExtensionUniqueOfIso F' α (Iso.refl _) F'' α'
| Mathlib/CategoryTheory/Functor/KanExtension/Basic.lean | 220 | 230 |
/-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import Mathlib.Order.ConditionallyCompleteLattice.Basic
import Mathlib.Order.Cover
import Mathlib.Order.Iterate
/-!
# Successor and predecessor
This file defines successor and predecessor orders. `succ a`, the successor of an element `a : α` is
the least element greater than `a`. `pred a` is the greatest element less than `a`. Typical examples
include `ℕ`, `ℤ`, `ℕ+`, `Fin n`, but also `ENat`, the lexicographic order of a successor/predecessor
order...
## Typeclasses
* `SuccOrder`: Order equipped with a sensible successor function.
* `PredOrder`: Order equipped with a sensible predecessor function.
## Implementation notes
Maximal elements don't have a sensible successor. Thus the naïve typeclass
```lean
class NaiveSuccOrder (α : Type*) [Preorder α] where
(succ : α → α)
(succ_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b)
(lt_succ_iff : ∀ {a b}, a < succ b ↔ a ≤ b)
```
can't apply to an `OrderTop` because plugging in `a = b = ⊤` into either of `succ_le_iff` and
`lt_succ_iff` yields `⊤ < ⊤` (or more generally `m < m` for a maximal element `m`).
The solution taken here is to remove the implications `≤ → <` and instead require that `a < succ a`
for all non maximal elements (enforced by the combination of `le_succ` and the contrapositive of
`max_of_succ_le`).
The stricter condition of every element having a sensible successor can be obtained through the
combination of `SuccOrder α` and `NoMaxOrder α`.
-/
open Function OrderDual Set
variable {α β : Type*}
/-- Order equipped with a sensible successor function. -/
@[ext]
class SuccOrder (α : Type*) [Preorder α] where
/-- Successor function -/
succ : α → α
/-- Proof of basic ordering with respect to `succ` -/
le_succ : ∀ a, a ≤ succ a
/-- Proof of interaction between `succ` and maximal element -/
max_of_succ_le {a} : succ a ≤ a → IsMax a
/-- Proof that `succ a` is the least element greater than `a` -/
succ_le_of_lt {a b} : a < b → succ a ≤ b
/-- Order equipped with a sensible predecessor function. -/
@[ext]
class PredOrder (α : Type*) [Preorder α] where
/-- Predecessor function -/
pred : α → α
/-- Proof of basic ordering with respect to `pred` -/
pred_le : ∀ a, pred a ≤ a
/-- Proof of interaction between `pred` and minimal element -/
min_of_le_pred {a} : a ≤ pred a → IsMin a
/-- Proof that `pred b` is the greatest element less than `b` -/
le_pred_of_lt {a b} : a < b → a ≤ pred b
instance [Preorder α] [SuccOrder α] :
PredOrder αᵒᵈ where
pred := toDual ∘ SuccOrder.succ ∘ ofDual
pred_le := by
simp only [comp, OrderDual.forall, ofDual_toDual, toDual_le_toDual,
SuccOrder.le_succ, implies_true]
min_of_le_pred h := by apply SuccOrder.max_of_succ_le h
le_pred_of_lt := by intro a b h; exact SuccOrder.succ_le_of_lt h
instance [Preorder α] [PredOrder α] :
SuccOrder αᵒᵈ where
succ := toDual ∘ PredOrder.pred ∘ ofDual
le_succ := by
simp only [comp, OrderDual.forall, ofDual_toDual, toDual_le_toDual,
PredOrder.pred_le, implies_true]
max_of_succ_le h := by apply PredOrder.min_of_le_pred h
succ_le_of_lt := by intro a b h; exact PredOrder.le_pred_of_lt h
section Preorder
variable [Preorder α]
/-- A constructor for `SuccOrder α` usable when `α` has no maximal element. -/
def SuccOrder.ofSuccLeIff (succ : α → α) (hsucc_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b) :
SuccOrder α :=
{ succ
le_succ := fun _ => (hsucc_le_iff.1 le_rfl).le
max_of_succ_le := fun ha => (lt_irrefl _ <| hsucc_le_iff.1 ha).elim
succ_le_of_lt := fun h => hsucc_le_iff.2 h }
/-- A constructor for `PredOrder α` usable when `α` has no minimal element. -/
def PredOrder.ofLePredIff (pred : α → α) (hle_pred_iff : ∀ {a b}, a ≤ pred b ↔ a < b) :
PredOrder α :=
{ pred
pred_le := fun _ => (hle_pred_iff.1 le_rfl).le
min_of_le_pred := fun ha => (lt_irrefl _ <| hle_pred_iff.1 ha).elim
le_pred_of_lt := fun h => hle_pred_iff.2 h }
end Preorder
section LinearOrder
variable [LinearOrder α]
/-- A constructor for `SuccOrder α` for `α` a linear order. -/
@[simps]
def SuccOrder.ofCore (succ : α → α) (hn : ∀ {a}, ¬IsMax a → ∀ b, a < b ↔ succ a ≤ b)
(hm : ∀ a, IsMax a → succ a = a) : SuccOrder α :=
{ succ
succ_le_of_lt := fun {a b} =>
by_cases (fun h hab => (hm a h).symm ▸ hab.le) fun h => (hn h b).mp
le_succ := fun a =>
by_cases (fun h => (hm a h).symm.le) fun h => le_of_lt <| by simpa using (hn h a).not
max_of_succ_le := fun {a} => not_imp_not.mp fun h => by simpa using (hn h a).not }
/-- A constructor for `PredOrder α` for `α` a linear order. -/
@[simps]
def PredOrder.ofCore (pred : α → α)
(hn : ∀ {a}, ¬IsMin a → ∀ b, b ≤ pred a ↔ b < a) (hm : ∀ a, IsMin a → pred a = a) :
PredOrder α :=
{ pred
le_pred_of_lt := fun {a b} =>
by_cases (fun h hab => (hm b h).symm ▸ hab.le) fun h => (hn h a).mpr
pred_le := fun a =>
by_cases (fun h => (hm a h).le) fun h => le_of_lt <| by simpa using (hn h a).not
min_of_le_pred := fun {a} => not_imp_not.mp fun h => by simpa using (hn h a).not }
variable (α)
open Classical in
/-- A well-order is a `SuccOrder`. -/
noncomputable def SuccOrder.ofLinearWellFoundedLT [WellFoundedLT α] : SuccOrder α :=
ofCore (fun a ↦ if h : (Ioi a).Nonempty then wellFounded_lt.min _ h else a)
(fun ha _ ↦ by
rw [not_isMax_iff] at ha
simp_rw [Set.Nonempty, mem_Ioi, dif_pos ha]
exact ⟨(wellFounded_lt.min_le · ha), lt_of_lt_of_le (wellFounded_lt.min_mem _ ha)⟩)
fun _ ha ↦ dif_neg (not_not_intro ha <| not_isMax_iff.mpr ·)
/-- A linear order with well-founded greater-than relation is a `PredOrder`. -/
noncomputable def PredOrder.ofLinearWellFoundedGT (α) [LinearOrder α] [WellFoundedGT α] :
PredOrder α := letI := SuccOrder.ofLinearWellFoundedLT αᵒᵈ; inferInstanceAs (PredOrder αᵒᵈᵒᵈ)
end LinearOrder
/-! ### Successor order -/
namespace Order
section Preorder
variable [Preorder α] [SuccOrder α] {a b : α}
/-- The successor of an element. If `a` is not maximal, then `succ a` is the least element greater
than `a`. If `a` is maximal, then `succ a = a`. -/
def succ : α → α :=
SuccOrder.succ
theorem le_succ : ∀ a : α, a ≤ succ a :=
SuccOrder.le_succ
theorem max_of_succ_le {a : α} : succ a ≤ a → IsMax a :=
SuccOrder.max_of_succ_le
theorem succ_le_of_lt {a b : α} : a < b → succ a ≤ b :=
SuccOrder.succ_le_of_lt
alias _root_.LT.lt.succ_le := succ_le_of_lt
@[simp]
theorem succ_le_iff_isMax : succ a ≤ a ↔ IsMax a :=
⟨max_of_succ_le, fun h => h <| le_succ _⟩
alias ⟨_root_.IsMax.of_succ_le, _root_.IsMax.succ_le⟩ := succ_le_iff_isMax
@[simp]
theorem lt_succ_iff_not_isMax : a < succ a ↔ ¬IsMax a :=
⟨not_isMax_of_lt, fun ha => (le_succ a).lt_of_not_le fun h => ha <| max_of_succ_le h⟩
alias ⟨_, lt_succ_of_not_isMax⟩ := lt_succ_iff_not_isMax
theorem wcovBy_succ (a : α) : a ⩿ succ a :=
⟨le_succ a, fun _ hb => (succ_le_of_lt hb).not_lt⟩
theorem covBy_succ_of_not_isMax (h : ¬IsMax a) : a ⋖ succ a :=
(wcovBy_succ a).covBy_of_lt <| lt_succ_of_not_isMax h
theorem lt_succ_of_le_of_not_isMax (hab : b ≤ a) (ha : ¬IsMax a) : b < succ a :=
hab.trans_lt <| lt_succ_of_not_isMax ha
theorem succ_le_iff_of_not_isMax (ha : ¬IsMax a) : succ a ≤ b ↔ a < b :=
⟨(lt_succ_of_not_isMax ha).trans_le, succ_le_of_lt⟩
lemma succ_lt_succ_of_not_isMax (h : a < b) (hb : ¬ IsMax b) : succ a < succ b :=
lt_succ_of_le_of_not_isMax (succ_le_of_lt h) hb
@[simp, mono, gcongr]
theorem succ_le_succ (h : a ≤ b) : succ a ≤ succ b := by
by_cases hb : IsMax b
· by_cases hba : b ≤ a
· exact (hb <| hba.trans <| le_succ _).trans (le_succ _)
· exact succ_le_of_lt ((h.lt_of_not_le hba).trans_le <| le_succ b)
· rw [succ_le_iff_of_not_isMax fun ha => hb <| ha.mono h]
apply lt_succ_of_le_of_not_isMax h hb
theorem succ_mono : Monotone (succ : α → α) := fun _ _ => succ_le_succ
/-- See also `Order.succ_eq_of_covBy`. -/
lemma le_succ_of_wcovBy (h : a ⩿ b) : b ≤ succ a := by
obtain hab | ⟨-, hba⟩ := h.covBy_or_le_and_le
· by_contra hba
exact h.2 (lt_succ_of_not_isMax hab.lt.not_isMax) <| hab.lt.succ_le.lt_of_not_le hba
· exact hba.trans (le_succ _)
alias _root_.WCovBy.le_succ := le_succ_of_wcovBy
theorem le_succ_iterate (k : ℕ) (x : α) : x ≤ succ^[k] x :=
id_le_iterate_of_id_le le_succ _ _
theorem isMax_iterate_succ_of_eq_of_lt {n m : ℕ} (h_eq : succ^[n] a = succ^[m] a)
(h_lt : n < m) : IsMax (succ^[n] a) := by
refine max_of_succ_le (le_trans ?_ h_eq.symm.le)
rw [← iterate_succ_apply' succ]
have h_le : n + 1 ≤ m := Nat.succ_le_of_lt h_lt
exact Monotone.monotone_iterate_of_le_map succ_mono (le_succ a) h_le
theorem isMax_iterate_succ_of_eq_of_ne {n m : ℕ} (h_eq : succ^[n] a = succ^[m] a)
(h_ne : n ≠ m) : IsMax (succ^[n] a) := by
rcases le_total n m with h | h
· exact isMax_iterate_succ_of_eq_of_lt h_eq (lt_of_le_of_ne h h_ne)
· rw [h_eq]
exact isMax_iterate_succ_of_eq_of_lt h_eq.symm (lt_of_le_of_ne h h_ne.symm)
theorem Iic_subset_Iio_succ_of_not_isMax (ha : ¬IsMax a) : Iic a ⊆ Iio (succ a) :=
fun _ => (lt_succ_of_le_of_not_isMax · ha)
theorem Ici_succ_of_not_isMax (ha : ¬IsMax a) : Ici (succ a) = Ioi a :=
Set.ext fun _ => succ_le_iff_of_not_isMax ha
theorem Icc_subset_Ico_succ_right_of_not_isMax (hb : ¬IsMax b) : Icc a b ⊆ Ico a (succ b) := by
rw [← Ici_inter_Iio, ← Ici_inter_Iic]
gcongr
intro _ h
apply lt_succ_of_le_of_not_isMax h hb
theorem Ioc_subset_Ioo_succ_right_of_not_isMax (hb : ¬IsMax b) : Ioc a b ⊆ Ioo a (succ b) := by
rw [← Ioi_inter_Iio, ← Ioi_inter_Iic]
gcongr
intro _ h
apply Iic_subset_Iio_succ_of_not_isMax hb h
theorem Icc_succ_left_of_not_isMax (ha : ¬IsMax a) : Icc (succ a) b = Ioc a b := by
rw [← Ici_inter_Iic, Ici_succ_of_not_isMax ha, Ioi_inter_Iic]
theorem Ico_succ_left_of_not_isMax (ha : ¬IsMax a) : Ico (succ a) b = Ioo a b := by
rw [← Ici_inter_Iio, Ici_succ_of_not_isMax ha, Ioi_inter_Iio]
section NoMaxOrder
variable [NoMaxOrder α]
theorem lt_succ (a : α) : a < succ a :=
lt_succ_of_not_isMax <| not_isMax a
@[simp]
theorem lt_succ_of_le : a ≤ b → a < succ b :=
(lt_succ_of_le_of_not_isMax · <| not_isMax b)
@[simp]
theorem succ_le_iff : succ a ≤ b ↔ a < b :=
succ_le_iff_of_not_isMax <| not_isMax a
@[gcongr] theorem succ_lt_succ (hab : a < b) : succ a < succ b := by simp [hab]
theorem succ_strictMono : StrictMono (succ : α → α) := fun _ _ => succ_lt_succ
theorem covBy_succ (a : α) : a ⋖ succ a :=
covBy_succ_of_not_isMax <| not_isMax a
theorem Iic_subset_Iio_succ (a : α) : Iic a ⊆ Iio (succ a) := by simp
@[simp]
theorem Ici_succ (a : α) : Ici (succ a) = Ioi a :=
Ici_succ_of_not_isMax <| not_isMax _
@[simp]
theorem Icc_subset_Ico_succ_right (a b : α) : Icc a b ⊆ Ico a (succ b) :=
Icc_subset_Ico_succ_right_of_not_isMax <| not_isMax _
@[simp]
theorem Ioc_subset_Ioo_succ_right (a b : α) : Ioc a b ⊆ Ioo a (succ b) :=
Ioc_subset_Ioo_succ_right_of_not_isMax <| not_isMax _
@[simp]
theorem Icc_succ_left (a b : α) : Icc (succ a) b = Ioc a b :=
Icc_succ_left_of_not_isMax <| not_isMax _
|
@[simp]
theorem Ico_succ_left (a b : α) : Ico (succ a) b = Ioo a b :=
Ico_succ_left_of_not_isMax <| not_isMax _
end NoMaxOrder
| Mathlib/Order/SuccPred/Basic.lean | 306 | 312 |
/-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import Mathlib.Algebra.GroupWithZero.Hom
import Mathlib.Algebra.GroupWithZero.Units.Basic
import Mathlib.Algebra.Ring.Defs
import Mathlib.Data.Nat.Lattice
/-!
# Definition of nilpotent elements
This file defines the notion of a nilpotent element and proves the immediate consequences.
For results that require further theory, see `Mathlib.RingTheory.Nilpotent.Basic`
and `Mathlib.RingTheory.Nilpotent.Lemmas`.
## Main definitions
* `IsNilpotent`
* `Commute.isNilpotent_mul_left`
* `Commute.isNilpotent_mul_right`
* `nilpotencyClass`
-/
universe u v
open Function Set
variable {R S : Type*} {x y : R}
/-- An element is said to be nilpotent if some natural-number-power of it equals zero.
Note that we require only the bare minimum assumptions for the definition to make sense. Even
`MonoidWithZero` is too strong since nilpotency is important in the study of rings that are only
power-associative. -/
def IsNilpotent [Zero R] [Pow R ℕ] (x : R) : Prop :=
∃ n : ℕ, x ^ n = 0
theorem IsNilpotent.mk [Zero R] [Pow R ℕ] (x : R) (n : ℕ) (e : x ^ n = 0) : IsNilpotent x :=
⟨n, e⟩
@[simp] lemma isNilpotent_of_subsingleton [Zero R] [Pow R ℕ] [Subsingleton R] : IsNilpotent x :=
⟨0, Subsingleton.elim _ _⟩
@[simp] theorem IsNilpotent.zero [MonoidWithZero R] : IsNilpotent (0 : R) :=
⟨1, pow_one 0⟩
theorem not_isNilpotent_one [MonoidWithZero R] [Nontrivial R] :
¬ IsNilpotent (1 : R) := fun ⟨_, H⟩ ↦ zero_ne_one (H.symm.trans (one_pow _))
lemma IsNilpotent.pow_succ (n : ℕ) {S : Type*} [MonoidWithZero S] {x : S}
(hx : IsNilpotent x) : IsNilpotent (x ^ n.succ) := by
obtain ⟨N, hN⟩ := hx
use N
rw [← pow_mul, Nat.succ_mul, pow_add, hN, mul_zero]
theorem IsNilpotent.of_pow [MonoidWithZero R] {x : R} {m : ℕ}
(h : IsNilpotent (x ^ m)) : IsNilpotent x := by
obtain ⟨n, h⟩ := h
use m * n
rw [← h, pow_mul x m n]
lemma IsNilpotent.pow_of_pos {n} {S : Type*} [MonoidWithZero S] {x : S}
(hx : IsNilpotent x) (hn : n ≠ 0) : IsNilpotent (x ^ n) := by
cases n with
| zero => contradiction
| succ => exact IsNilpotent.pow_succ _ hx
@[simp]
lemma IsNilpotent.pow_iff_pos {n} {S : Type*} [MonoidWithZero S] {x : S} (hn : n ≠ 0) :
IsNilpotent (x ^ n) ↔ IsNilpotent x :=
⟨of_pow, (pow_of_pos · hn)⟩
theorem IsNilpotent.map [MonoidWithZero R] [MonoidWithZero S] {r : R} {F : Type*}
[FunLike F R S] [MonoidWithZeroHomClass F R S] (hr : IsNilpotent r) (f : F) :
IsNilpotent (f r) := by
use hr.choose
rw [← map_pow, hr.choose_spec, map_zero]
lemma IsNilpotent.map_iff [MonoidWithZero R] [MonoidWithZero S] {r : R} {F : Type*}
[FunLike F R S] [MonoidWithZeroHomClass F R S] {f : F} (hf : Function.Injective f) :
IsNilpotent (f r) ↔ IsNilpotent r :=
⟨fun ⟨k, hk⟩ ↦ ⟨k, (map_eq_zero_iff f hf).mp <| by rwa [map_pow]⟩, fun h ↦ h.map f⟩
theorem IsUnit.isNilpotent_mul_unit_of_commute_iff [MonoidWithZero R] {r u : R}
(hu : IsUnit u) (h_comm : Commute r u) :
IsNilpotent (r * u) ↔ IsNilpotent r :=
exists_congr fun n ↦ by rw [h_comm.mul_pow, (hu.pow n).mul_left_eq_zero]
theorem IsUnit.isNilpotent_unit_mul_of_commute_iff [MonoidWithZero R] {r u : R}
(hu : IsUnit u) (h_comm : Commute r u) :
IsNilpotent (u * r) ↔ IsNilpotent r :=
h_comm ▸ hu.isNilpotent_mul_unit_of_commute_iff h_comm
section NilpotencyClass
section ZeroPow
variable [Zero R] [Pow R ℕ]
variable (x) in
/-- If `x` is nilpotent, the nilpotency class is the smallest natural number `k` such that
`x ^ k = 0`. If `x` is not nilpotent, the nilpotency class takes the junk value `0`. -/
noncomputable def nilpotencyClass : ℕ := sInf {k | x ^ k = 0}
@[simp] lemma nilpotencyClass_eq_zero_of_subsingleton [Subsingleton R] :
nilpotencyClass x = 0 := by
let s : Set ℕ := {k | x ^ k = 0}
suffices s = univ by change sInf _ = 0; simp [s] at this; simp [this]
exact eq_univ_iff_forall.mpr fun k ↦ Subsingleton.elim _ _
lemma isNilpotent_of_pos_nilpotencyClass (hx : 0 < nilpotencyClass x) :
IsNilpotent x := by
let s : Set ℕ := {k | x ^ k = 0}
change s.Nonempty
change 0 < sInf s at hx
by_contra contra
simp [not_nonempty_iff_eq_empty.mp contra] at hx
lemma pow_nilpotencyClass (hx : IsNilpotent x) : x ^ (nilpotencyClass x) = 0 :=
Nat.sInf_mem hx
end ZeroPow
section MonoidWithZero
variable [MonoidWithZero R]
lemma nilpotencyClass_eq_succ_iff {k : ℕ} :
nilpotencyClass x = k + 1 ↔ x ^ (k + 1) = 0 ∧ x ^ k ≠ 0 := by
let s : Set ℕ := {k | x ^ k = 0}
have : ∀ k₁ k₂ : ℕ, k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s := fun k₁ k₂ h_le hk₁ ↦ pow_eq_zero_of_le h_le hk₁
simp [s, nilpotencyClass, Nat.sInf_upward_closed_eq_succ_iff this]
@[simp] lemma nilpotencyClass_zero [Nontrivial R] :
nilpotencyClass (0 : R) = 1 :=
nilpotencyClass_eq_succ_iff.mpr <| by constructor <;> simp
@[simp] lemma pos_nilpotencyClass_iff [Nontrivial R] :
0 < nilpotencyClass x ↔ IsNilpotent x := by
refine ⟨isNilpotent_of_pos_nilpotencyClass, fun hx ↦ Nat.pos_of_ne_zero fun hx' ↦ ?_⟩
replace hx := pow_nilpotencyClass hx
rw [hx', pow_zero] at hx
exact one_ne_zero hx
lemma pow_pred_nilpotencyClass [Nontrivial R] (hx : IsNilpotent x) :
x ^ (nilpotencyClass x - 1) ≠ 0 :=
(nilpotencyClass_eq_succ_iff.mp <| Nat.eq_add_of_sub_eq (pos_nilpotencyClass_iff.mpr hx) rfl).2
lemma eq_zero_of_nilpotencyClass_eq_one (hx : nilpotencyClass x = 1) :
x = 0 := by
have : IsNilpotent x := isNilpotent_of_pos_nilpotencyClass (hx ▸ Nat.one_pos)
rw [← pow_nilpotencyClass this, hx, pow_one]
@[simp] lemma nilpotencyClass_eq_one [Nontrivial R] :
nilpotencyClass x = 1 ↔ x = 0 :=
⟨eq_zero_of_nilpotencyClass_eq_one, fun hx ↦ hx ▸ nilpotencyClass_zero⟩
end MonoidWithZero
end NilpotencyClass
/-- A structure that has zero and pow is reduced if it has no nonzero nilpotent elements. -/
@[mk_iff]
class IsReduced (R : Type*) [Zero R] [Pow R ℕ] : Prop where
/-- A reduced structure has no nonzero nilpotent elements. -/
eq_zero : ∀ x : R, IsNilpotent x → x = 0
namespace IsReduced
theorem pow_eq_zero [Zero R] [Pow R ℕ] [IsReduced R] {n : ℕ} (h : x ^ n = 0) :
x = 0 := IsReduced.eq_zero x ⟨n, h⟩
@[simp]
theorem pow_eq_zero_iff [MonoidWithZero R] [IsReduced R] {n : ℕ} (hn : n ≠ 0) :
x ^ n = 0 ↔ x = 0 := ⟨pow_eq_zero, fun h ↦ h.symm ▸ zero_pow hn⟩
theorem pow_ne_zero_iff [MonoidWithZero R] [IsReduced R] {n : ℕ} (hn : n ≠ 0) :
x ^ n ≠ 0 ↔ x ≠ 0 := not_congr (pow_eq_zero_iff hn)
theorem pow_ne_zero [Zero R] [Pow R ℕ] [IsReduced R] (n : ℕ) (h : x ≠ 0) :
x ^ n ≠ 0 := fun H ↦ h (pow_eq_zero H)
/-- A variant of `IsReduced.pow_eq_zero_iff` assuming `R` is not trivial. -/
@[simp]
theorem pow_eq_zero_iff' [MonoidWithZero R] [IsReduced R] [Nontrivial R] {n : ℕ} :
x ^ n = 0 ↔ x = 0 ∧ n ≠ 0 := by
cases n <;> simp
end IsReduced
instance (priority := 900) isReduced_of_noZeroDivisors [MonoidWithZero R] [NoZeroDivisors R] :
IsReduced R :=
⟨fun _ ⟨_, hn⟩ => pow_eq_zero hn⟩
|
instance (priority := 900) isReduced_of_subsingleton [Zero R] [Pow R ℕ] [Subsingleton R] :
IsReduced R :=
⟨fun _ _ => Subsingleton.elim _ _⟩
theorem IsNilpotent.eq_zero [Zero R] [Pow R ℕ] [IsReduced R] (h : IsNilpotent x) : x = 0 :=
IsReduced.eq_zero x h
@[simp]
| Mathlib/RingTheory/Nilpotent/Defs.lean | 197 | 205 |
/-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import Mathlib.Order.OmegaCompletePartialOrder
import Mathlib.Topology.Order.ScottTopology
/-!
# Scott Topological Spaces
A type of topological spaces whose notion
of continuity is equivalent to continuity in ωCPOs.
## Reference
* https://ncatlab.org/nlab/show/Scott+topology
-/
open Set OmegaCompletePartialOrder
universe u
open Topology.IsScott in
@[simp] lemma Topology.IsScott.ωscottContinuous_iff_continuous {α : Type*}
[OmegaCompletePartialOrder α] [TopologicalSpace α]
[Topology.IsScott α (Set.range fun c : Chain α => Set.range c)] {f : α → Prop} :
ωScottContinuous f ↔ Continuous f := by
rw [ωScottContinuous, scottContinuous_iff_continuous (fun a b hab => by
use Chain.pair a b hab; exact OmegaCompletePartialOrder.Chain.range_pair a b hab)]
-- "Scott", "ωSup"
namespace Scott
/-- `x` is an `ω`-Sup of a chain `c` if it is the least upper bound of the range of `c`. -/
def IsωSup {α : Type u} [Preorder α] (c : Chain α) (x : α) : Prop :=
(∀ i, c i ≤ x) ∧ ∀ y, (∀ i, c i ≤ y) → x ≤ y
theorem isωSup_iff_isLUB {α : Type u} [Preorder α] {c : Chain α} {x : α} :
| IsωSup c x ↔ IsLUB (range c) x := by
simp [IsωSup, IsLUB, IsLeast, upperBounds, lowerBounds]
| Mathlib/Topology/OmegaCompletePartialOrder.lean | 41 | 43 |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Computability.Tape
import Mathlib.Data.Fintype.Option
import Mathlib.Data.Fintype.Prod
import Mathlib.Data.Fintype.Pi
import Mathlib.Data.PFun
import Mathlib.Computability.PostTuringMachine
/-!
# Turing machines
The files `PostTuringMachine.lean` and `TuringMachine.lean` define
a sequence of simple machine languages, starting with Turing machines and working
up to more complex languages based on Wang B-machines.
`PostTuringMachine.lean` covers the TM0 model and TM1 model;
`TuringMachine.lean` adds the TM2 model.
## Naming conventions
Each model of computation in this file shares a naming convention for the elements of a model of
computation. These are the parameters for the language:
* `Γ` is the alphabet on the tape.
* `Λ` is the set of labels, or internal machine states.
* `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and
later models achieve this by mixing it into `Λ`.
* `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks.
All of these variables denote "essentially finite" types, but for technical reasons it is
convenient to allow them to be infinite anyway. When using an infinite type, we will be interested
to prove that only finitely many values of the type are ever interacted with.
Given these parameters, there are a few common structures for the model that arise:
* `Stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is
finite, and for later models it is an infinite inductive type representing "possible program
texts".
* `Cfg` is the set of instantaneous configurations, that is, the state of the machine together with
its environment.
* `Machine` is the set of all machines in the model. Usually this is approximately a function
`Λ → Stmt`, although different models have different ways of halting and other actions.
* `step : Cfg → Option Cfg` is the function that describes how the state evolves over one step.
If `step c = none`, then `c` is a terminal state, and the result of the computation is read off
from `c`. Because of the type of `step`, these models are all deterministic by construction.
* `init : Input → Cfg` sets up the initial state. The type `Input` depends on the model;
in most cases it is `List Γ`.
* `eval : Machine → Input → Part Output`, given a machine `M` and input `i`, starts from
`init i`, runs `step` until it reaches an output, and then applies a function `Cfg → Output` to
the final state to obtain the result. The type `Output` depends on the model.
* `Supports : Machine → Finset Λ → Prop` asserts that a machine `M` starts in `S : Finset Λ`, and
can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input
cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when
convenient, and prove that only finitely many of these states are actually accessible. This
formalizes "essentially finite" mentioned above.
-/
assert_not_exists MonoidWithZero
open List (Vector)
open Relation
open Nat (iterate)
open Function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply'
iterate_zero_apply)
namespace Turing
/-!
## The TM2 model
The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite)
collection of stacks, each with elements of different types (the alphabet of stack `k : K` is
`Γ k`). The statements are:
* `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`.
* `pop k (f : σ → Option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, and removes this element from the stack, then does `q`.
* `peek k (f : σ → Option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, then does `q`.
* `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`.
* `branch (f : σ → Bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`.
* `goto (f : σ → Λ)` jumps to label `f a`.
* `halt` halts on the next step.
The configuration is a tuple `(l, var, stk)` where `l : Option Λ` is the current label to run or
`none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, List (Γ k)`
is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not
`ListBlank`s, they have definite ends that can be detected by the `pop` command.)
Given a designated stack `k` and a value `L : List (Γ k)`, the initial configuration has all the
stacks empty except the designated "input" stack; in `eval` this designated stack also functions
as the output stack.
-/
namespace TM2
variable {K : Type*}
-- Index type of stacks
variable (Γ : K → Type*)
-- Type of stack elements
variable (Λ : Type*)
-- Type of function labels
variable (σ : Type*)
-- Type of variable settings
/-- The TM2 model removes the tape entirely from the TM1 model,
replacing it with an arbitrary (finite) collection of stacks.
The operation `push` puts an element on one of the stacks,
and `pop` removes an element from a stack (and modifying the
internal state based on the result). `peek` modifies the
internal state but does not remove an element. -/
inductive Stmt
| push : ∀ k, (σ → Γ k) → Stmt → Stmt
| peek : ∀ k, (σ → Option (Γ k) → σ) → Stmt → Stmt
| pop : ∀ k, (σ → Option (Γ k) → σ) → Stmt → Stmt
| load : (σ → σ) → Stmt → Stmt
| branch : (σ → Bool) → Stmt → Stmt → Stmt
| goto : (σ → Λ) → Stmt
| halt : Stmt
open Stmt
instance Stmt.inhabited : Inhabited (Stmt Γ Λ σ) :=
⟨halt⟩
/-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of
local variables, and the stacks. (Note that the stacks are not `ListBlank`s, they have a definite
size.) -/
structure Cfg where
/-- The current label to run (or `none` for the halting state) -/
l : Option Λ
/-- The internal state -/
var : σ
/-- The (finite) collection of internal stacks -/
stk : ∀ k, List (Γ k)
instance Cfg.inhabited [Inhabited σ] : Inhabited (Cfg Γ Λ σ) :=
⟨⟨default, default, default⟩⟩
variable {Γ Λ σ}
section
variable [DecidableEq K]
/-- The step function for the TM2 model. -/
def stepAux : Stmt Γ Λ σ → σ → (∀ k, List (Γ k)) → Cfg Γ Λ σ
| push k f q, v, S => stepAux q v (update S k (f v :: S k))
| peek k f q, v, S => stepAux q (f v (S k).head?) S
| pop k f q, v, S => stepAux q (f v (S k).head?) (update S k (S k).tail)
| load a q, v, S => stepAux q (a v) S
| branch f q₁ q₂, v, S => cond (f v) (stepAux q₁ v S) (stepAux q₂ v S)
| goto f, v, S => ⟨some (f v), v, S⟩
| halt, v, S => ⟨none, v, S⟩
/-- The step function for the TM2 model. -/
def step (M : Λ → Stmt Γ Λ σ) : Cfg Γ Λ σ → Option (Cfg Γ Λ σ)
| ⟨none, _, _⟩ => none
| ⟨some l, v, S⟩ => some (stepAux (M l) v S)
attribute [simp] stepAux.eq_1 stepAux.eq_2 stepAux.eq_3
stepAux.eq_4 stepAux.eq_5 stepAux.eq_6 stepAux.eq_7 step.eq_1 step.eq_2
/-- The (reflexive) reachability relation for the TM2 model. -/
def Reaches (M : Λ → Stmt Γ Λ σ) : Cfg Γ Λ σ → Cfg Γ Λ σ → Prop :=
ReflTransGen fun a b ↦ b ∈ step M a
end
/-- Given a set `S` of states, `SupportsStmt S q` means that `q` only jumps to states in `S`. -/
def SupportsStmt (S : Finset Λ) : Stmt Γ Λ σ → Prop
| push _ _ q => SupportsStmt S q
| peek _ _ q => SupportsStmt S q
| pop _ _ q => SupportsStmt S q
| load _ q => SupportsStmt S q
| branch _ q₁ q₂ => SupportsStmt S q₁ ∧ SupportsStmt S q₂
| goto l => ∀ v, l v ∈ S
| halt => True
section
open scoped Classical in
/-- The set of subtree statements in a statement. -/
noncomputable def stmts₁ : Stmt Γ Λ σ → Finset (Stmt Γ Λ σ)
| Q@(push _ _ q) => insert Q (stmts₁ q)
| Q@(peek _ _ q) => insert Q (stmts₁ q)
| Q@(pop _ _ q) => insert Q (stmts₁ q)
| Q@(load _ q) => insert Q (stmts₁ q)
| Q@(branch _ q₁ q₂) => insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q@(goto _) => {Q}
| Q@halt => {Q}
theorem stmts₁_self {q : Stmt Γ Λ σ} : q ∈ stmts₁ q := by
cases q <;> simp only [Finset.mem_insert_self, Finset.mem_singleton_self, stmts₁]
theorem stmts₁_trans {q₁ q₂ : Stmt Γ Λ σ} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := by
classical
intro h₁₂ q₀ h₀₁
induction q₂ with (
simp only [stmts₁] at h₁₂ ⊢
simp only [Finset.mem_insert, Finset.mem_singleton, Finset.mem_union] at h₁₂)
| branch f q₁ q₂ IH₁ IH₂ =>
rcases h₁₂ with (rfl | h₁₂ | h₁₂)
· unfold stmts₁ at h₀₁
exact h₀₁
· exact Finset.mem_insert_of_mem (Finset.mem_union_left _ (IH₁ h₁₂))
· exact Finset.mem_insert_of_mem (Finset.mem_union_right _ (IH₂ h₁₂))
| goto l => subst h₁₂; exact h₀₁
| halt => subst h₁₂; exact h₀₁
| load _ q IH | _ _ _ q IH =>
rcases h₁₂ with (rfl | h₁₂)
· unfold stmts₁ at h₀₁
exact h₀₁
· exact Finset.mem_insert_of_mem (IH h₁₂)
theorem stmts₁_supportsStmt_mono {S : Finset Λ} {q₁ q₂ : Stmt Γ Λ σ} (h : q₁ ∈ stmts₁ q₂)
(hs : SupportsStmt S q₂) : SupportsStmt S q₁ := by
induction q₂ with
simp only [stmts₁, SupportsStmt, Finset.mem_insert, Finset.mem_union, Finset.mem_singleton]
at h hs
| branch f q₁ q₂ IH₁ IH₂ => rcases h with (rfl | h | h); exacts [hs, IH₁ h hs.1, IH₂ h hs.2]
| goto l => subst h; exact hs
| halt => subst h; trivial
| load _ _ IH | _ _ _ _ IH => rcases h with (rfl | h) <;> [exact hs; exact IH h hs]
open scoped Classical in
/-- The set of statements accessible from initial set `S` of labels. -/
noncomputable def stmts (M : Λ → Stmt Γ Λ σ) (S : Finset Λ) : Finset (Option (Stmt Γ Λ σ)) :=
Finset.insertNone (S.biUnion fun q ↦ stmts₁ (M q))
theorem stmts_trans {M : Λ → Stmt Γ Λ σ} {S : Finset Λ} {q₁ q₂ : Stmt Γ Λ σ} (h₁ : q₁ ∈ stmts₁ q₂) :
some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by
simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq,
forall_eq', exists_imp, and_imp]
exact fun l ls h₂ ↦ ⟨_, ls, stmts₁_trans h₂ h₁⟩
end
variable [Inhabited Λ]
/-- Given a TM2 machine `M` and a set `S` of states, `Supports M S` means that all states in
`S` jump only to other states in `S`. -/
def Supports (M : Λ → Stmt Γ Λ σ) (S : Finset Λ) :=
default ∈ S ∧ ∀ q ∈ S, SupportsStmt S (M q)
theorem stmts_supportsStmt {M : Λ → Stmt Γ Λ σ} {S : Finset Λ} {q : Stmt Γ Λ σ}
(ss : Supports M S) : some q ∈ stmts M S → SupportsStmt S q := by
simp only [stmts, Finset.mem_insertNone, Finset.mem_biUnion, Option.mem_def, Option.some.injEq,
forall_eq', exists_imp, and_imp]
exact fun l ls h ↦ stmts₁_supportsStmt_mono h (ss.2 _ ls)
variable [DecidableEq K]
theorem step_supports (M : Λ → Stmt Γ Λ σ) {S : Finset Λ} (ss : Supports M S) :
∀ {c c' : Cfg Γ Λ σ}, c' ∈ step M c → c.l ∈ Finset.insertNone S → c'.l ∈ Finset.insertNone S
| ⟨some l₁, v, T⟩, c', h₁, h₂ => by
replace h₂ := ss.2 _ (Finset.some_mem_insertNone.1 h₂)
simp only [step, Option.mem_def, Option.some.injEq] at h₁; subst c'
revert h₂; induction M l₁ generalizing v T with intro hs
| branch p q₁' q₂' IH₁ IH₂ =>
unfold stepAux; cases p v
· exact IH₂ _ _ hs.2
· exact IH₁ _ _ hs.1
| goto => exact Finset.some_mem_insertNone.2 (hs _)
| halt => apply Multiset.mem_cons_self
| load _ _ IH | _ _ _ _ IH => exact IH _ _ hs
variable [Inhabited σ]
/-- The initial state of the TM2 model. The input is provided on a designated stack. -/
def init (k : K) (L : List (Γ k)) : Cfg Γ Λ σ :=
⟨some default, default, update (fun _ ↦ []) k L⟩
/-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/
def eval (M : Λ → Stmt Γ Λ σ) (k : K) (L : List (Γ k)) : Part (List (Γ k)) :=
(Turing.eval (step M) (init k L)).map fun c ↦ c.stk k
end TM2
/-!
## TM2 emulator in TM1
To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a
TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of
stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack
1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this:
```
bottom: ... | _ | T | _ | _ | _ | _ | ...
stack 1: ... | _ | b | a | _ | _ | _ | ...
stack 2: ... | _ | f | e | d | c | _ | ...
```
where a tape element is a vertical slice through the diagram. Here the alphabet is
`Γ' := Bool × ∀ k, Option (Γ k)`, where:
* `bottom : Bool` is marked only in one place, the initial position of the TM, and represents the
tail of all stacks. It is never modified.
* `stk k : Option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is
the blank value). Note that the head of the stack is at the far end; this is so that push and pop
don't have to do any shifting.
In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions,
it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the
end of the appropriate stack, make its changes, and then return to the bottom. So the states are:
* `normal (l : Λ)`: waiting at `bottom` to execute function `l`
* `go k (s : StAct k) (q : Stmt₂)`: travelling to the right to get to the end of stack `k` in
order to perform stack action `s`, and later continue with executing `q`
* `ret (q : Stmt₂)`: travelling to the left after having performed a stack action, and executing
`q` once we arrive
Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the
length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)`
steps to run when emulated in TM1, where `m` is the length of the input.
-/
namespace TM2to1
-- A displaced lemma proved in unnecessary generality
theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : ListBlank (∀ k, Option (Γ k))} {k S} (n)
(hL : ListBlank.map (proj k) L = ListBlank.mk (List.map some S).reverse) :
L.nth n k = S.reverse[n]? := by
rw [← proj_map_nth, hL, ← List.map_reverse, ListBlank.nth_mk,
List.getI_eq_iget_getElem?, List.getElem?_map]
cases S.reverse[n]? <;> rfl
variable (K : Type*)
variable (Γ : K → Type*)
variable {Λ σ : Type*}
/-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom,
plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/
def Γ' :=
Bool × ∀ k, Option (Γ k)
variable {K Γ}
instance Γ'.inhabited : Inhabited (Γ' K Γ) :=
⟨⟨false, fun _ ↦ none⟩⟩
instance Γ'.fintype [DecidableEq K] [Fintype K] [∀ k, Fintype (Γ k)] : Fintype (Γ' K Γ) :=
instFintypeProd _ _
/-- The bottom marker is fixed throughout the calculation, so we use the `addBottom` function
to express the program state in terms of a tape with only the stacks themselves. -/
def addBottom (L : ListBlank (∀ k, Option (Γ k))) : ListBlank (Γ' K Γ) :=
ListBlank.cons (true, L.head) (L.tail.map ⟨Prod.mk false, rfl⟩)
theorem addBottom_map (L : ListBlank (∀ k, Option (Γ k))) :
(addBottom L).map ⟨Prod.snd, by rfl⟩ = L := by
simp only [addBottom, ListBlank.map_cons]
convert ListBlank.cons_head_tail L
generalize ListBlank.tail L = L'
refine L'.induction_on fun l ↦ ?_; simp
theorem addBottom_modifyNth (f : (∀ k, Option (Γ k)) → ∀ k, Option (Γ k))
(L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) :
(addBottom L).modifyNth (fun a ↦ (a.1, f a.2)) n = addBottom (L.modifyNth f n) := by
cases n <;>
simp only [addBottom, ListBlank.head_cons, ListBlank.modifyNth, ListBlank.tail_cons]
congr; symm; apply ListBlank.map_modifyNth; intro; rfl
theorem addBottom_nth_snd (L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) :
((addBottom L).nth n).2 = L.nth n := by
conv => rhs; rw [← addBottom_map L, ListBlank.nth_map]
theorem addBottom_nth_succ_fst (L : ListBlank (∀ k, Option (Γ k))) (n : ℕ) :
((addBottom L).nth (n + 1)).1 = false := by
rw [ListBlank.nth_succ, addBottom, ListBlank.tail_cons, ListBlank.nth_map]
theorem addBottom_head_fst (L : ListBlank (∀ k, Option (Γ k))) : (addBottom L).head.1 = true := by
rw [addBottom, ListBlank.head_cons]
variable (K Γ σ) in
/-- A stack action is a command that interacts with the top of a stack. Our default position
is at the bottom of all the stacks, so we have to hold on to this action while going to the end
to modify the stack. -/
inductive StAct (k : K)
| push : (σ → Γ k) → StAct k
| peek : (σ → Option (Γ k) → σ) → StAct k
| pop : (σ → Option (Γ k) → σ) → StAct k
instance StAct.inhabited {k : K} : Inhabited (StAct K Γ σ k) :=
⟨StAct.peek fun s _ ↦ s⟩
section
open StAct
/-- The TM2 statement corresponding to a stack action. -/
def stRun {k : K} : StAct K Γ σ k → TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ σ
| push f => TM2.Stmt.push k f
| peek f => TM2.Stmt.peek k f
| pop f => TM2.Stmt.pop k f
/-- The effect of a stack action on the local variables, given the value of the stack. -/
def stVar {k : K} (v : σ) (l : List (Γ k)) : StAct K Γ σ k → σ
| push _ => v
| peek f => f v l.head?
| pop f => f v l.head?
/-- The effect of a stack action on the stack. -/
def stWrite {k : K} (v : σ) (l : List (Γ k)) : StAct K Γ σ k → List (Γ k)
| push f => f v :: l
| peek _ => l
| pop _ => l.tail
/-- We have partitioned the TM2 statements into "stack actions", which require going to the end
of the stack, and all other actions, which do not. This is a modified recursor which lumps the
stack actions into one. -/
@[elab_as_elim]
def stmtStRec.{l} {motive : TM2.Stmt Γ Λ σ → Sort l}
(run : ∀ (k) (s : StAct K Γ σ k) (q) (_ : motive q), motive (stRun s q))
(load : ∀ (a q) (_ : motive q), motive (TM2.Stmt.load a q))
(branch : ∀ (p q₁ q₂) (_ : motive q₁) (_ : motive q₂), motive (TM2.Stmt.branch p q₁ q₂))
(goto : ∀ l, motive (TM2.Stmt.goto l)) (halt : motive TM2.Stmt.halt) : ∀ n, motive n
| TM2.Stmt.push _ f q => run _ (push f) _ (stmtStRec run load branch goto halt q)
| TM2.Stmt.peek _ f q => run _ (peek f) _ (stmtStRec run load branch goto halt q)
| TM2.Stmt.pop _ f q => run _ (pop f) _ (stmtStRec run load branch goto halt q)
| TM2.Stmt.load _ q => load _ _ (stmtStRec run load branch goto halt q)
| TM2.Stmt.branch _ q₁ q₂ =>
branch _ _ _ (stmtStRec run load branch goto halt q₁) (stmtStRec run load branch goto halt q₂)
| TM2.Stmt.goto _ => goto _
| TM2.Stmt.halt => halt
theorem supports_run (S : Finset Λ) {k : K} (s : StAct K Γ σ k) (q : TM2.Stmt Γ Λ σ) :
TM2.SupportsStmt S (stRun s q) ↔ TM2.SupportsStmt S q := by
cases s <;> rfl
end
variable (K Γ Λ σ)
/-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the
next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and
return to the bottom, respectively. -/
inductive Λ'
| normal : Λ → Λ'
| go (k : K) : StAct K Γ σ k → TM2.Stmt Γ Λ σ → Λ'
| ret : TM2.Stmt Γ Λ σ → Λ'
variable {K Γ Λ σ}
open Λ'
instance Λ'.inhabited [Inhabited Λ] : Inhabited (Λ' K Γ Λ σ) :=
⟨normal default⟩
open TM1.Stmt
section
variable [DecidableEq K]
/-- The program corresponding to state transitions at the end of a stack. Here we start out just
after the top of the stack, and should end just after the new top of the stack. -/
def trStAct {k : K} (q : TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ) :
StAct K Γ σ k → TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ
| StAct.push f => (write fun a s ↦ (a.1, update a.2 k <| some <| f s)) <| move Dir.right q
| StAct.peek f => move Dir.left <| (load fun a s ↦ f s (a.2 k)) <| move Dir.right q
| StAct.pop f =>
branch (fun a _ ↦ a.1) (load (fun _ s ↦ f s none) q)
(move Dir.left <|
(load fun a s ↦ f s (a.2 k)) <| write (fun a _ ↦ (a.1, update a.2 k none)) q)
/-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty
except for the input stack, and the stack bottom mark is set at the head. -/
def trInit (k : K) (L : List (Γ k)) : List (Γ' K Γ) :=
let L' : List (Γ' K Γ) := L.reverse.map fun a ↦ (false, update (fun _ ↦ none) k (some a))
(true, L'.headI.2) :: L'.tail
theorem step_run {k : K} (q : TM2.Stmt Γ Λ σ) (v : σ) (S : ∀ k, List (Γ k)) : ∀ s : StAct K Γ σ k,
TM2.stepAux (stRun s q) v S = TM2.stepAux q (stVar v (S k) s) (update S k (stWrite v (S k) s))
| StAct.push _ => rfl
| StAct.peek f => by unfold stWrite; rw [Function.update_eq_self]; rfl
| StAct.pop _ => rfl
end
/-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents,
but stack actions are deferred by going to the corresponding `go` state, so that we can find the
appropriate stack top. -/
def trNormal : TM2.Stmt Γ Λ σ → TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ
| TM2.Stmt.push k f q => goto fun _ _ ↦ go k (StAct.push f) q
| TM2.Stmt.peek k f q => goto fun _ _ ↦ go k (StAct.peek f) q
| TM2.Stmt.pop k f q => goto fun _ _ ↦ go k (StAct.pop f) q
| TM2.Stmt.load a q => load (fun _ ↦ a) (trNormal q)
| TM2.Stmt.branch f q₁ q₂ => branch (fun _ ↦ f) (trNormal q₁) (trNormal q₂)
| TM2.Stmt.goto l => goto fun _ s ↦ normal (l s)
| TM2.Stmt.halt => halt
theorem trNormal_run {k : K} (s : StAct K Γ σ k) (q : TM2.Stmt Γ Λ σ) :
trNormal (stRun s q) = goto fun _ _ ↦ go k s q := by
cases s <;> rfl
section
open scoped Classical in
/-- The set of machine states accessible from an initial TM2 statement. -/
noncomputable def trStmts₁ : TM2.Stmt Γ Λ σ → Finset (Λ' K Γ Λ σ)
| TM2.Stmt.push k f q => {go k (StAct.push f) q, ret q} ∪ trStmts₁ q
| TM2.Stmt.peek k f q => {go k (StAct.peek f) q, ret q} ∪ trStmts₁ q
| TM2.Stmt.pop k f q => {go k (StAct.pop f) q, ret q} ∪ trStmts₁ q
| TM2.Stmt.load _ q => trStmts₁ q
| TM2.Stmt.branch _ q₁ q₂ => trStmts₁ q₁ ∪ trStmts₁ q₂
| _ => ∅
theorem trStmts₁_run {k : K} {s : StAct K Γ σ k} {q : TM2.Stmt Γ Λ σ} :
open scoped Classical in
trStmts₁ (stRun s q) = {go k s q, ret q} ∪ trStmts₁ q := by
cases s <;> simp only [trStmts₁, stRun]
theorem tr_respects_aux₂ [DecidableEq K] {k : K} {q : TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ} {v : σ}
{S : ∀ k, List (Γ k)} {L : ListBlank (∀ k, Option (Γ k))}
(hL : ∀ k, L.map (proj k) = ListBlank.mk ((S k).map some).reverse) (o : StAct K Γ σ k) :
let v' := stVar v (S k) o
let Sk' := stWrite v (S k) o
let S' := update S k Sk'
∃ L' : ListBlank (∀ k, Option (Γ k)),
(∀ k, L'.map (proj k) = ListBlank.mk ((S' k).map some).reverse) ∧
TM1.stepAux (trStAct q o) v
((Tape.move Dir.right)^[(S k).length] (Tape.mk' ∅ (addBottom L))) =
TM1.stepAux q v' ((Tape.move Dir.right)^[(S' k).length] (Tape.mk' ∅ (addBottom L'))) := by
simp only [Function.update_self]; cases o with simp only [stWrite, stVar, trStAct, TM1.stepAux]
| push f =>
have := Tape.write_move_right_n fun a : Γ' K Γ ↦ (a.1, update a.2 k (some (f v)))
refine
⟨_, fun k' ↦ ?_, by
-- Porting note: `rw [...]` to `erw [...]; rfl`.
-- https://github.com/leanprover-community/mathlib4/issues/5164
rw [Tape.move_right_n_head, List.length, Tape.mk'_nth_nat, this]
erw [addBottom_modifyNth fun a ↦ update a k (some (f v))]
rw [Nat.add_one, iterate_succ']
rfl⟩
refine ListBlank.ext fun i ↦ ?_
rw [ListBlank.nth_map, ListBlank.nth_modifyNth, proj, PointedMap.mk_val]
by_cases h' : k' = k
· subst k'
split_ifs with h
<;> simp only [List.reverse_cons, Function.update_self, ListBlank.nth_mk, List.map]
· rw [List.getI_eq_getElem _, List.getElem_append_right] <;>
simp only [List.length_append, List.length_reverse, List.length_map, ← h,
Nat.sub_self, List.length_singleton, List.getElem_singleton,
le_refl, Nat.lt_succ_self]
rw [← proj_map_nth, hL, ListBlank.nth_mk]
rcases lt_or_gt_of_ne h with h | h
· rw [List.getI_append]
simpa only [List.length_map, List.length_reverse] using h
· rw [gt_iff_lt] at h
rw [List.getI_eq_default, List.getI_eq_default] <;>
simp only [Nat.add_one_le_iff, h, List.length, le_of_lt, List.length_reverse,
List.length_append, List.length_map]
· split_ifs <;> rw [Function.update_of_ne h', ← proj_map_nth, hL]
rw [Function.update_of_ne h']
| peek f =>
rw [Function.update_eq_self]
use L, hL; rw [Tape.move_left_right]; congr
cases e : S k; · rfl
rw [List.length_cons, iterate_succ', Function.comp, Tape.move_right_left,
Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_snd, stk_nth_val _ (hL k), e,
List.reverse_cons, ← List.length_reverse, List.getElem?_concat_length]
rfl
| pop f =>
rcases e : S k with - | ⟨hd, tl⟩
· simp only [Tape.mk'_head, ListBlank.head_cons, Tape.move_left_mk', List.length,
Tape.write_mk', List.head?, iterate_zero_apply, List.tail_nil]
rw [← e, Function.update_eq_self]
exact ⟨L, hL, by rw [addBottom_head_fst, cond]⟩
· refine
⟨_, fun k' ↦ ?_, by
erw [List.length_cons, Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_succ_fst,
cond_false, iterate_succ', Function.comp, Tape.move_right_left, Tape.move_right_n_head,
Tape.mk'_nth_nat, Tape.write_move_right_n fun a : Γ' K Γ ↦ (a.1, update a.2 k none),
addBottom_modifyNth fun a ↦ update a k none, addBottom_nth_snd,
stk_nth_val _ (hL k), e,
show (List.cons hd tl).reverse[tl.length]? = some hd by
rw [List.reverse_cons, ← List.length_reverse, List.getElem?_concat_length],
List.head?, List.tail]⟩
refine ListBlank.ext fun i ↦ ?_
rw [ListBlank.nth_map, ListBlank.nth_modifyNth, proj, PointedMap.mk_val]
by_cases h' : k' = k
· subst k'
split_ifs with h <;> simp only [Function.update_self, ListBlank.nth_mk, List.tail]
· rw [List.getI_eq_default]
· rfl
rw [h, List.length_reverse, List.length_map]
rw [← proj_map_nth, hL, ListBlank.nth_mk, e, List.map, List.reverse_cons]
rcases lt_or_gt_of_ne h with h | h
· rw [List.getI_append]
simpa only [List.length_map, List.length_reverse] using h
· rw [gt_iff_lt] at h
rw [List.getI_eq_default, List.getI_eq_default] <;>
simp only [Nat.add_one_le_iff, h, List.length, le_of_lt, List.length_reverse,
List.length_append, List.length_map]
· split_ifs <;> rw [Function.update_of_ne h', ← proj_map_nth, hL]
rw [Function.update_of_ne h']
end
variable [DecidableEq K]
variable (M : Λ → TM2.Stmt Γ Λ σ)
/-- The TM2 emulator machine states written as a TM1 program.
This handles the `go` and `ret` states, which shuttle to and from a stack top. -/
def tr : Λ' K Γ Λ σ → TM1.Stmt (Γ' K Γ) (Λ' K Γ Λ σ) σ
| normal q => trNormal (M q)
| go k s q =>
branch (fun a _ ↦ (a.2 k).isNone) (trStAct (goto fun _ _ ↦ ret q) s)
(move Dir.right <| goto fun _ _ ↦ go k s q)
| ret q => branch (fun a _ ↦ a.1) (trNormal q) (move Dir.left <| goto fun _ _ ↦ ret q)
/-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/
inductive TrCfg : TM2.Cfg Γ Λ σ → TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ → Prop
| mk {q : Option Λ} {v : σ} {S : ∀ k, List (Γ k)} (L : ListBlank (∀ k, Option (Γ k))) :
(∀ k, L.map (proj k) = ListBlank.mk ((S k).map some).reverse) →
TrCfg ⟨q, v, S⟩ ⟨q.map normal, v, Tape.mk' ∅ (addBottom L)⟩
theorem tr_respects_aux₁ {k} (o q v) {S : List (Γ k)} {L : ListBlank (∀ k, Option (Γ k))}
(hL : L.map (proj k) = ListBlank.mk (S.map some).reverse) (n) (H : n ≤ S.length) :
Reaches₀ (TM1.step (tr M)) ⟨some (go k o q), v, Tape.mk' ∅ (addBottom L)⟩
⟨some (go k o q), v, (Tape.move Dir.right)^[n] (Tape.mk' ∅ (addBottom L))⟩ := by
induction' n with n IH; · rfl
apply (IH (le_of_lt H)).tail
rw [iterate_succ_apply']
simp only [TM1.step, TM1.stepAux, tr, Tape.mk'_nth_nat, Tape.move_right_n_head,
addBottom_nth_snd, Option.mem_def]
rw [stk_nth_val _ hL, List.getElem?_eq_getElem]
· rfl
· rwa [List.length_reverse]
theorem tr_respects_aux₃ {q v} {L : ListBlank (∀ k, Option (Γ k))} (n) : Reaches₀ (TM1.step (tr M))
⟨some (ret q), v, (Tape.move Dir.right)^[n] (Tape.mk' ∅ (addBottom L))⟩
⟨some (ret q), v, Tape.mk' ∅ (addBottom L)⟩ := by
induction' n with n IH; · rfl
refine Reaches₀.head ?_ IH
simp only [Option.mem_def, TM1.step]
rw [Option.some_inj, tr, TM1.stepAux, Tape.move_right_n_head, Tape.mk'_nth_nat,
addBottom_nth_succ_fst, TM1.stepAux, iterate_succ', Function.comp_apply, Tape.move_right_left]
rfl
theorem tr_respects_aux {q v T k} {S : ∀ k, List (Γ k)}
(hT : ∀ k, ListBlank.map (proj k) T = ListBlank.mk ((S k).map some).reverse)
(o : StAct K Γ σ k)
(IH : ∀ {v : σ} {S : ∀ k : K, List (Γ k)} {T : ListBlank (∀ k, Option (Γ k))},
(∀ k, ListBlank.map (proj k) T = ListBlank.mk ((S k).map some).reverse) →
∃ b, TrCfg (TM2.stepAux q v S) b ∧
Reaches (TM1.step (tr M)) (TM1.stepAux (trNormal q) v (Tape.mk' ∅ (addBottom T))) b) :
∃ b, TrCfg (TM2.stepAux (stRun o q) v S) b ∧ Reaches (TM1.step (tr M))
(TM1.stepAux (trNormal (stRun o q)) v (Tape.mk' ∅ (addBottom T))) b := by
simp only [trNormal_run, step_run]
have hgo := tr_respects_aux₁ M o q v (hT k) _ le_rfl
obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ (Λ := Λ) hT o
have := hgo.tail' rfl
rw [tr, TM1.stepAux, Tape.move_right_n_head, Tape.mk'_nth_nat, addBottom_nth_snd,
stk_nth_val _ (hT k), List.getElem?_eq_none (le_of_eq List.length_reverse),
Option.isNone, cond, hrun, TM1.stepAux] at this
obtain ⟨c, gc, rc⟩ := IH hT'
refine ⟨c, gc, (this.to₀.trans (tr_respects_aux₃ M _) c (TransGen.head' rfl ?_)).to_reflTransGen⟩
rw [tr, TM1.stepAux, Tape.mk'_head, addBottom_head_fst]
exact rc
attribute [local simp] Respects TM2.step TM2.stepAux trNormal
theorem tr_respects : Respects (TM2.step M) (TM1.step (tr M)) TrCfg := by
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/12129): additional beta reduction needed
intro c₁ c₂ h
obtain @⟨- | l, v, S, L, hT⟩ := h; · constructor
rsuffices ⟨b, c, r⟩ : ∃ b, _ ∧ Reaches (TM1.step (tr M)) _ _
· exact ⟨b, c, TransGen.head' rfl r⟩
simp only [tr]
generalize M l = N
induction N using stmtStRec generalizing v S L hT with
| run k s q IH => exact tr_respects_aux M hT s @IH
| load a _ IH => exact IH _ hT
| branch p q₁ q₂ IH₁ IH₂ =>
unfold TM2.stepAux trNormal TM1.stepAux
beta_reduce
cases p v <;> [exact IH₂ _ hT; exact IH₁ _ hT]
| goto => exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩
| halt => exact ⟨_, ⟨_, hT⟩, ReflTransGen.refl⟩
section
variable [Inhabited Λ] [Inhabited σ]
theorem trCfg_init (k) (L : List (Γ k)) : TrCfg (TM2.init k L)
(TM1.init (trInit k L) : TM1.Cfg (Γ' K Γ) (Λ' K Γ Λ σ) σ) := by
rw [(_ : TM1.init _ = _)]
· refine ⟨ListBlank.mk (L.reverse.map fun a ↦ update default k (some a)), fun k' ↦ ?_⟩
refine ListBlank.ext fun i ↦ ?_
rw [ListBlank.map_mk, ListBlank.nth_mk, List.getI_eq_iget_getElem?, List.map_map]
have : ((proj k').f ∘ fun a => update (β := fun k => Option (Γ k)) default k (some a))
= fun a => (proj k').f (update (β := fun k => Option (Γ k)) default k (some a)) := rfl
rw [this, List.getElem?_map, proj, PointedMap.mk_val]
simp only []
by_cases h : k' = k
· subst k'
simp only [Function.update_self]
rw [ListBlank.nth_mk, List.getI_eq_iget_getElem?, ← List.map_reverse, List.getElem?_map]
· simp only [Function.update_of_ne h]
rw [ListBlank.nth_mk, List.getI_eq_iget_getElem?, List.map, List.reverse_nil]
cases L.reverse[i]? <;> rfl
· rw [trInit, TM1.init]
congr <;> cases L.reverse <;> try rfl
simp only [List.map_map, List.tail_cons, List.map]
rfl
theorem tr_eval_dom (k) (L : List (Γ k)) :
(TM1.eval (tr M) (trInit k L)).Dom ↔ (TM2.eval M k L).Dom :=
Turing.tr_eval_dom (tr_respects M) (trCfg_init k L)
theorem tr_eval (k) (L : List (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval (tr M) (trInit k L))
(H₂ : L₂ ∈ TM2.eval M k L) :
∃ (S : ∀ k, List (Γ k)) (L' : ListBlank (∀ k, Option (Γ k))),
addBottom L' = L₁ ∧
(∀ k, L'.map (proj k) = ListBlank.mk ((S k).map some).reverse) ∧ S k = L₂ := by
obtain ⟨c₁, h₁, rfl⟩ := (Part.mem_map_iff _).1 H₁
obtain ⟨c₂, h₂, rfl⟩ := (Part.mem_map_iff _).1 H₂
obtain ⟨_, ⟨L', hT⟩, h₃⟩ := Turing.tr_eval (tr_respects M) (trCfg_init k L) h₂
cases Part.mem_unique h₁ h₃
exact ⟨_, L', by simp only [Tape.mk'_right₀], hT, rfl⟩
end
section
variable [Inhabited Λ]
open scoped Classical in
/-- The support of a set of TM2 states in the TM2 emulator. -/
noncomputable def trSupp (S : Finset Λ) : Finset (Λ' K Γ Λ σ) :=
S.biUnion fun l ↦ insert (normal l) (trStmts₁ (M l))
open scoped Classical in
theorem tr_supports {S} (ss : TM2.Supports M S) : TM1.Supports (tr M) (trSupp M S) :=
⟨Finset.mem_biUnion.2 ⟨_, ss.1, Finset.mem_insert.2 <| Or.inl rfl⟩, fun l' h ↦ by
suffices ∀ (q) (_ : TM2.SupportsStmt S q) (_ : ∀ x ∈ trStmts₁ q, x ∈ trSupp M S),
TM1.SupportsStmt (trSupp M S) (trNormal q) ∧
∀ l' ∈ trStmts₁ q, TM1.SupportsStmt (trSupp M S) (tr M l') by
rcases Finset.mem_biUnion.1 h with ⟨l, lS, h⟩
have :=
this _ (ss.2 l lS) fun x hx ↦ Finset.mem_biUnion.2 ⟨_, lS, Finset.mem_insert_of_mem hx⟩
rcases Finset.mem_insert.1 h with (rfl | h) <;> [exact this.1; exact this.2 _ h]
clear h l'
refine stmtStRec ?_ ?_ ?_ ?_ ?_
· intro _ s _ IH ss' sub -- stack op
rw [TM2to1.supports_run] at ss'
simp only [TM2to1.trStmts₁_run, Finset.mem_union, Finset.mem_insert, Finset.mem_singleton]
at sub
have hgo := sub _ (Or.inl <| Or.inl rfl)
have hret := sub _ (Or.inl <| Or.inr rfl)
obtain ⟨IH₁, IH₂⟩ := IH ss' fun x hx ↦ sub x <| Or.inr hx
refine ⟨by simp only [trNormal_run, TM1.SupportsStmt]; intros; exact hgo, fun l h ↦ ?_⟩
rw [trStmts₁_run] at h
simp only [TM2to1.trStmts₁_run, Finset.mem_union, Finset.mem_insert, Finset.mem_singleton]
at h
rcases h with (⟨rfl | rfl⟩ | h)
· cases s
· exact ⟨fun _ _ ↦ hret, fun _ _ ↦ hgo⟩
· exact ⟨fun _ _ ↦ hret, fun _ _ ↦ hgo⟩
· exact ⟨⟨fun _ _ ↦ hret, fun _ _ ↦ hret⟩, fun _ _ ↦ hgo⟩
· unfold TM1.SupportsStmt TM2to1.tr
exact ⟨IH₁, fun _ _ ↦ hret⟩
· exact IH₂ _ h
· intro _ _ IH ss' sub -- load
unfold TM2to1.trStmts₁ at sub ⊢
exact IH ss' sub
· intro _ _ _ IH₁ IH₂ ss' sub -- branch
unfold TM2to1.trStmts₁ at sub
obtain ⟨IH₁₁, IH₁₂⟩ := IH₁ ss'.1 fun x hx ↦ sub x <| Finset.mem_union_left _ hx
obtain ⟨IH₂₁, IH₂₂⟩ := IH₂ ss'.2 fun x hx ↦ sub x <| Finset.mem_union_right _ hx
refine ⟨⟨IH₁₁, IH₂₁⟩, fun l h ↦ ?_⟩
rw [trStmts₁] at h
rcases Finset.mem_union.1 h with (h | h) <;> [exact IH₁₂ _ h; exact IH₂₂ _ h]
· intro _ ss' _ -- goto
simp only [trStmts₁, Finset.not_mem_empty]; refine ⟨?_, fun _ ↦ False.elim⟩
exact fun _ v ↦ Finset.mem_biUnion.2 ⟨_, ss' v, Finset.mem_insert_self _ _⟩
· intro _ _ -- halt
simp only [trStmts₁, Finset.not_mem_empty]
exact ⟨trivial, fun _ ↦ False.elim⟩⟩
end
end TM2to1
end Turing
| Mathlib/Computability/TuringMachine.lean | 2,395 | 2,397 | |
/-
Copyright (c) 2020 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison
-/
import Mathlib.Algebra.Category.ModuleCat.Adjunctions
import Mathlib.Algebra.Category.ModuleCat.EpiMono
import Mathlib.Algebra.Category.ModuleCat.Limits
import Mathlib.Algebra.Category.ModuleCat.Colimits
import Mathlib.Algebra.Category.ModuleCat.Monoidal.Symmetric
import Mathlib.CategoryTheory.Elementwise
import Mathlib.CategoryTheory.Action.Monoidal
import Mathlib.RepresentationTheory.Basic
/-!
# `Rep k G` is the category of `k`-linear representations of `G`.
If `V : Rep k G`, there is a coercion that allows you to treat `V` as a type,
and this type comes equipped with a `Module k V` instance.
Also `V.ρ` gives the homomorphism `G →* (V →ₗ[k] V)`.
Conversely, given a homomorphism `ρ : G →* (V →ₗ[k] V)`,
you can construct the bundled representation as `Rep.of ρ`.
We construct the categorical equivalence `Rep k G ≌ ModuleCat (MonoidAlgebra k G)`.
We verify that `Rep k G` is a `k`-linear abelian symmetric monoidal category with all (co)limits.
-/
suppress_compilation
universe u
open CategoryTheory
open CategoryTheory.Limits
/-- The category of `k`-linear representations of a monoid `G`. -/
abbrev Rep (k G : Type u) [Ring k] [Monoid G] :=
Action (ModuleCat.{u} k) G
instance (k G : Type u) [CommRing k] [Monoid G] : Linear k (Rep k G) := by infer_instance
namespace Rep
variable {k G : Type u} [CommRing k]
section
variable [Monoid G]
instance : CoeSort (Rep k G) (Type u) :=
⟨fun V => V.V⟩
instance (V : Rep k G) : AddCommGroup V := by
change AddCommGroup ((forget₂ (Rep k G) (ModuleCat k)).obj V); infer_instance
instance (V : Rep k G) : Module k V := by
change Module k ((forget₂ (Rep k G) (ModuleCat k)).obj V)
infer_instance
/-- Specialize the existing `Action.ρ`, changing the type to `Representation k G V`.
-/
def ρ (V : Rep k G) : Representation k G V :=
-- Porting note: was `V.ρ`
(ModuleCat.endRingEquiv V.V).toMonoidHom.comp (Action.ρ V)
/-- Lift an unbundled representation to `Rep`. -/
abbrev of {V : Type u} [AddCommGroup V] [Module k V] (ρ : G →* V →ₗ[k] V) : Rep k G :=
⟨ModuleCat.of k V, (ModuleCat.endRingEquiv _).symm.toMonoidHom.comp ρ⟩
theorem coe_of {V : Type u} [AddCommGroup V] [Module k V] (ρ : G →* V →ₗ[k] V) :
(of ρ : Type u) = V :=
rfl
@[simp]
theorem of_ρ {V : Type u} [AddCommGroup V] [Module k V] (ρ : G →* V →ₗ[k] V) : (of ρ).ρ = ρ :=
rfl
theorem Action_ρ_eq_ρ {A : Rep k G} :
Action.ρ A = (ModuleCat.endRingEquiv _).symm.toMonoidHom.comp A.ρ :=
rfl
@[simp]
lemma ρ_hom {X : Rep k G} (g : G) : (Action.ρ X g).hom = X.ρ g := rfl
@[simp]
lemma ofHom_ρ {X : Rep k G} (g : G) : ModuleCat.ofHom (X.ρ g) = Action.ρ X g := rfl
@[simp]
theorem ρ_inv_self_apply {G : Type u} [Group G] (A : Rep k G) (g : G) (x : A) :
A.ρ g⁻¹ (A.ρ g x) = x :=
show (A.ρ g⁻¹ * A.ρ g) x = x by rw [← map_mul, inv_mul_cancel, map_one, Module.End.one_apply]
@[simp]
theorem ρ_self_inv_apply {G : Type u} [Group G] {A : Rep k G} (g : G) (x : A) :
A.ρ g (A.ρ g⁻¹ x) = x :=
show (A.ρ g * A.ρ g⁻¹) x = x by rw [← map_mul, mul_inv_cancel, map_one, Module.End.one_apply]
theorem hom_comm_apply {A B : Rep k G} (f : A ⟶ B) (g : G) (x : A) :
f.hom (A.ρ g x) = B.ρ g (f.hom x) :=
LinearMap.ext_iff.1 (ModuleCat.hom_ext_iff.mp (f.comm g)) x
variable (k G)
/-- The trivial `k`-linear `G`-representation on a `k`-module `V.` -/
abbrev trivial (V : Type u) [AddCommGroup V] [Module k V] : Rep k G :=
Rep.of (Representation.trivial k G V)
variable {k G}
theorem trivial_def {V : Type u} [AddCommGroup V] [Module k V] (g : G) :
(trivial k G V).ρ g = LinearMap.id :=
rfl
/-- A predicate for representations that fix every element. -/
abbrev IsTrivial (A : Rep k G) := A.ρ.IsTrivial
instance {V : Type u} [AddCommGroup V] [Module k V] :
IsTrivial (Rep.trivial k G V) where
instance {V : Type u} [AddCommGroup V] [Module k V] (ρ : Representation k G V) [ρ.IsTrivial] :
IsTrivial (Rep.of ρ) where
-- Porting note: the two following instances were found automatically in mathlib3
noncomputable instance : PreservesLimits (forget₂ (Rep k G) (ModuleCat.{u} k)) :=
Action.preservesLimits_forget.{u} _ _
noncomputable instance : PreservesColimits (forget₂ (Rep k G) (ModuleCat.{u} k)) :=
Action.preservesColimits_forget.{u} _ _
theorem epi_iff_surjective {A B : Rep k G} (f : A ⟶ B) : Epi f ↔ Function.Surjective f.hom :=
⟨fun _ => (ModuleCat.epi_iff_surjective ((forget₂ _ _).map f)).1 inferInstance,
fun h => (forget₂ _ _).epi_of_epi_map ((ModuleCat.epi_iff_surjective <|
(forget₂ _ _).map f).2 h)⟩
theorem mono_iff_injective {A B : Rep k G} (f : A ⟶ B) : Mono f ↔ Function.Injective f.hom :=
⟨fun _ => (ModuleCat.mono_iff_injective ((forget₂ _ _).map f)).1 inferInstance,
fun h => (forget₂ _ _).mono_of_mono_map ((ModuleCat.mono_iff_injective <|
(forget₂ _ _).map f).2 h)⟩
open MonoidalCategory in
@[simp]
theorem tensor_ρ {A B : Rep k G} : (A ⊗ B).ρ = A.ρ.tprod B.ρ := rfl
@[simp]
lemma res_obj_ρ {H : Type u} [Monoid H] (f : G →* H) (A : Rep k H) (g : G) :
DFunLike.coe (F := G →* (A →ₗ[k] A)) (ρ ((Action.res _ f).obj A)) g = A.ρ (f g) := rfl
section Linearization
variable (k G)
/-- The monoidal functor sending a type `H` with a `G`-action to the induced `k`-linear
`G`-representation on `k[H].` -/
noncomputable def linearization : (Action (Type u) G) ⥤ (Rep k G) :=
(ModuleCat.free k).mapAction G
instance : (linearization k G).Monoidal := by
dsimp only [linearization]
infer_instance
variable {k G}
@[simp]
theorem linearization_obj_ρ (X : Action (Type u) G) (g : G) (x : X.V →₀ k) :
((linearization k G).obj X).ρ g x = Finsupp.lmapDomain k k (X.ρ g) x :=
rfl
theorem linearization_of (X : Action (Type u) G) (g : G) (x : X.V) :
((linearization k G).obj X).ρ g (Finsupp.single x (1 : k))
= Finsupp.single (X.ρ g x) (1 : k) := by
rw [linearization_obj_ρ, Finsupp.lmapDomain_apply, Finsupp.mapDomain_single]
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): helps fixing `linearizationTrivialIso` since change in behaviour of `ext`.
theorem linearization_single (X : Action (Type u) G) (g : G) (x : X.V) (r : k) :
((linearization k G).obj X).ρ g (Finsupp.single x r) = Finsupp.single (X.ρ g x) r := by
rw [linearization_obj_ρ, Finsupp.lmapDomain_apply, Finsupp.mapDomain_single]
variable {X Y : Action (Type u) G} (f : X ⟶ Y)
@[simp]
theorem linearization_map_hom : ((linearization k G).map f).hom =
ModuleCat.ofHom (Finsupp.lmapDomain k k f.hom) :=
rfl
theorem linearization_map_hom_single (x : X.V) (r : k) :
((linearization k G).map f).hom (Finsupp.single x r) = Finsupp.single (f.hom x) r :=
Finsupp.mapDomain_single
open Functor.LaxMonoidal Functor.OplaxMonoidal Functor.Monoidal
| @[simp]
theorem linearization_μ_hom (X Y : Action (Type u) G) :
(μ (linearization k G) X Y).hom =
ModuleCat.ofHom (finsuppTensorFinsupp' k X.V Y.V).toLinearMap :=
| Mathlib/RepresentationTheory/Rep.lean | 192 | 195 |
/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import Mathlib.Algebra.BigOperators.Group.Finset.Indicator
import Mathlib.Algebra.Module.BigOperators
import Mathlib.LinearAlgebra.AffineSpace.AffineSubspace.Basic
import Mathlib.LinearAlgebra.Finsupp.LinearCombination
import Mathlib.Tactic.FinCases
/-!
# Affine combinations of points
This file defines affine combinations of points.
## Main definitions
* `weightedVSubOfPoint` is a general weighted combination of
subtractions with an explicit base point, yielding a vector.
* `weightedVSub` uses an arbitrary choice of base point and is intended
to be used when the sum of weights is 0, in which case the result is
independent of the choice of base point.
* `affineCombination` adds the weighted combination to the arbitrary
base point, yielding a point rather than a vector, and is intended
to be used when the sum of weights is 1, in which case the result is
independent of the choice of base point.
These definitions are for sums over a `Finset`; versions for a
`Fintype` may be obtained using `Finset.univ`, while versions for a
`Finsupp` may be obtained using `Finsupp.support`.
## References
* https://en.wikipedia.org/wiki/Affine_space
-/
noncomputable section
open Affine
namespace Finset
theorem univ_fin2 : (univ : Finset (Fin 2)) = {0, 1} := by
ext x
fin_cases x <;> simp
variable {k : Type*} {V : Type*} {P : Type*} [Ring k] [AddCommGroup V] [Module k V]
variable [S : AffineSpace V P]
variable {ι : Type*} (s : Finset ι)
variable {ι₂ : Type*} (s₂ : Finset ι₂)
/-- A weighted sum of the results of subtracting a base point from the
given points, as a linear map on the weights. The main cases of
interest are where the sum of the weights is 0, in which case the sum
is independent of the choice of base point, and where the sum of the
weights is 1, in which case the sum added to the base point is
independent of the choice of base point. -/
def weightedVSubOfPoint (p : ι → P) (b : P) : (ι → k) →ₗ[k] V :=
∑ i ∈ s, (LinearMap.proj i : (ι → k) →ₗ[k] k).smulRight (p i -ᵥ b)
@[simp]
theorem weightedVSubOfPoint_apply (w : ι → k) (p : ι → P) (b : P) :
s.weightedVSubOfPoint p b w = ∑ i ∈ s, w i • (p i -ᵥ b) := by
simp [weightedVSubOfPoint, LinearMap.sum_apply]
/-- The value of `weightedVSubOfPoint`, where the given points are equal. -/
@[simp (high)]
theorem weightedVSubOfPoint_apply_const (w : ι → k) (p : P) (b : P) :
s.weightedVSubOfPoint (fun _ => p) b w = (∑ i ∈ s, w i) • (p -ᵥ b) := by
rw [weightedVSubOfPoint_apply, sum_smul]
lemma weightedVSubOfPoint_vadd (s : Finset ι) (w : ι → k) (p : ι → P) (b : P) (v : V) :
s.weightedVSubOfPoint (v +ᵥ p) b w = s.weightedVSubOfPoint p (-v +ᵥ b) w := by
simp [vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, add_comm]
lemma weightedVSubOfPoint_smul {G : Type*} [Group G] [DistribMulAction G V] [SMulCommClass G k V]
(s : Finset ι) (w : ι → k) (p : ι → V) (b : V) (a : G) :
s.weightedVSubOfPoint (a • p) b w = a • s.weightedVSubOfPoint p (a⁻¹ • b) w := by
simp [smul_sum, smul_sub, smul_comm a (w _)]
/-- `weightedVSubOfPoint` gives equal results for two families of weights and two families of
points that are equal on `s`. -/
theorem weightedVSubOfPoint_congr {w₁ w₂ : ι → k} (hw : ∀ i ∈ s, w₁ i = w₂ i) {p₁ p₂ : ι → P}
(hp : ∀ i ∈ s, p₁ i = p₂ i) (b : P) :
s.weightedVSubOfPoint p₁ b w₁ = s.weightedVSubOfPoint p₂ b w₂ := by
simp_rw [weightedVSubOfPoint_apply]
refine sum_congr rfl fun i hi => ?_
rw [hw i hi, hp i hi]
/-- Given a family of points, if we use a member of the family as a base point, the
`weightedVSubOfPoint` does not depend on the value of the weights at this point. -/
theorem weightedVSubOfPoint_eq_of_weights_eq (p : ι → P) (j : ι) (w₁ w₂ : ι → k)
(hw : ∀ i, i ≠ j → w₁ i = w₂ i) :
s.weightedVSubOfPoint p (p j) w₁ = s.weightedVSubOfPoint p (p j) w₂ := by
simp only [Finset.weightedVSubOfPoint_apply]
congr
ext i
rcases eq_or_ne i j with h | h
· simp [h]
· simp [hw i h]
/-- The weighted sum is independent of the base point when the sum of
the weights is 0. -/
theorem weightedVSubOfPoint_eq_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i ∈ s, w i = 0)
(b₁ b₂ : P) : s.weightedVSubOfPoint p b₁ w = s.weightedVSubOfPoint p b₂ w := by
apply eq_of_sub_eq_zero
rw [weightedVSubOfPoint_apply, weightedVSubOfPoint_apply, ← sum_sub_distrib]
conv_lhs =>
congr
· skip
· ext
rw [← smul_sub, vsub_sub_vsub_cancel_left]
rw [← sum_smul, h, zero_smul]
/-- The weighted sum, added to the base point, is independent of the
base point when the sum of the weights is 1. -/
theorem weightedVSubOfPoint_vadd_eq_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i ∈ s, w i = 1)
(b₁ b₂ : P) : s.weightedVSubOfPoint p b₁ w +ᵥ b₁ = s.weightedVSubOfPoint p b₂ w +ᵥ b₂ := by
rw [weightedVSubOfPoint_apply, weightedVSubOfPoint_apply, ← @vsub_eq_zero_iff_eq V,
vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ← add_sub_assoc, add_comm, add_sub_assoc, ←
sum_sub_distrib]
conv_lhs =>
congr
· skip
· congr
· skip
· ext
rw [← smul_sub, vsub_sub_vsub_cancel_left]
rw [← sum_smul, h, one_smul, vsub_add_vsub_cancel, vsub_self]
/-- The weighted sum is unaffected by removing the base point, if
present, from the set of points. -/
@[simp (high)]
theorem weightedVSubOfPoint_erase [DecidableEq ι] (w : ι → k) (p : ι → P) (i : ι) :
(s.erase i).weightedVSubOfPoint p (p i) w = s.weightedVSubOfPoint p (p i) w := by
rw [weightedVSubOfPoint_apply, weightedVSubOfPoint_apply]
apply sum_erase
rw [vsub_self, smul_zero]
/-- The weighted sum is unaffected by adding the base point, whether
or not present, to the set of points. -/
@[simp (high)]
theorem weightedVSubOfPoint_insert [DecidableEq ι] (w : ι → k) (p : ι → P) (i : ι) :
(insert i s).weightedVSubOfPoint p (p i) w = s.weightedVSubOfPoint p (p i) w := by
rw [weightedVSubOfPoint_apply, weightedVSubOfPoint_apply]
apply sum_insert_zero
rw [vsub_self, smul_zero]
/-- The weighted sum is unaffected by changing the weights to the
corresponding indicator function and adding points to the set. -/
theorem weightedVSubOfPoint_indicator_subset (w : ι → k) (p : ι → P) (b : P) {s₁ s₂ : Finset ι}
(h : s₁ ⊆ s₂) :
s₁.weightedVSubOfPoint p b w = s₂.weightedVSubOfPoint p b (Set.indicator (↑s₁) w) := by
rw [weightedVSubOfPoint_apply, weightedVSubOfPoint_apply]
exact Eq.symm <|
sum_indicator_subset_of_eq_zero w (fun i wi => wi • (p i -ᵥ b : V)) h fun i => zero_smul k _
/-- A weighted sum, over the image of an embedding, equals a weighted
sum with the same points and weights over the original
`Finset`. -/
theorem weightedVSubOfPoint_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) (b : P) :
(s₂.map e).weightedVSubOfPoint p b w = s₂.weightedVSubOfPoint (p ∘ e) b (w ∘ e) := by
simp_rw [weightedVSubOfPoint_apply]
exact Finset.sum_map _ _ _
/-- A weighted sum of pairwise subtractions, expressed as a subtraction of two
`weightedVSubOfPoint` expressions. -/
theorem sum_smul_vsub_eq_weightedVSubOfPoint_sub (w : ι → k) (p₁ p₂ : ι → P) (b : P) :
(∑ i ∈ s, w i • (p₁ i -ᵥ p₂ i)) =
s.weightedVSubOfPoint p₁ b w - s.weightedVSubOfPoint p₂ b w := by
simp_rw [weightedVSubOfPoint_apply, ← sum_sub_distrib, ← smul_sub, vsub_sub_vsub_cancel_right]
/-- A weighted sum of pairwise subtractions, where the point on the right is constant,
expressed as a subtraction involving a `weightedVSubOfPoint` expression. -/
theorem sum_smul_vsub_const_eq_weightedVSubOfPoint_sub (w : ι → k) (p₁ : ι → P) (p₂ b : P) :
(∑ i ∈ s, w i • (p₁ i -ᵥ p₂)) = s.weightedVSubOfPoint p₁ b w - (∑ i ∈ s, w i) • (p₂ -ᵥ b) := by
rw [sum_smul_vsub_eq_weightedVSubOfPoint_sub, weightedVSubOfPoint_apply_const]
/-- A weighted sum of pairwise subtractions, where the point on the left is constant,
expressed as a subtraction involving a `weightedVSubOfPoint` expression. -/
theorem sum_smul_const_vsub_eq_sub_weightedVSubOfPoint (w : ι → k) (p₂ : ι → P) (p₁ b : P) :
(∑ i ∈ s, w i • (p₁ -ᵥ p₂ i)) = (∑ i ∈ s, w i) • (p₁ -ᵥ b) - s.weightedVSubOfPoint p₂ b w := by
rw [sum_smul_vsub_eq_weightedVSubOfPoint_sub, weightedVSubOfPoint_apply_const]
/-- A weighted sum may be split into such sums over two subsets. -/
theorem weightedVSubOfPoint_sdiff [DecidableEq ι] {s₂ : Finset ι} (h : s₂ ⊆ s) (w : ι → k)
(p : ι → P) (b : P) :
(s \ s₂).weightedVSubOfPoint p b w + s₂.weightedVSubOfPoint p b w =
s.weightedVSubOfPoint p b w := by
simp_rw [weightedVSubOfPoint_apply, sum_sdiff h]
/-- A weighted sum may be split into a subtraction of such sums over two subsets. -/
theorem weightedVSubOfPoint_sdiff_sub [DecidableEq ι] {s₂ : Finset ι} (h : s₂ ⊆ s) (w : ι → k)
(p : ι → P) (b : P) :
(s \ s₂).weightedVSubOfPoint p b w - s₂.weightedVSubOfPoint p b (-w) =
s.weightedVSubOfPoint p b w := by
rw [map_neg, sub_neg_eq_add, s.weightedVSubOfPoint_sdiff h]
/-- A weighted sum over `s.subtype pred` equals one over `{x ∈ s | pred x}`. -/
theorem weightedVSubOfPoint_subtype_eq_filter (w : ι → k) (p : ι → P) (b : P) (pred : ι → Prop)
[DecidablePred pred] :
((s.subtype pred).weightedVSubOfPoint (fun i => p i) b fun i => w i) =
{x ∈ s | pred x}.weightedVSubOfPoint p b w := by
rw [weightedVSubOfPoint_apply, weightedVSubOfPoint_apply, ← sum_subtype_eq_sum_filter]
/-- A weighted sum over `{x ∈ s | pred x}` equals one over `s` if all the weights at indices in `s`
not satisfying `pred` are zero. -/
theorem weightedVSubOfPoint_filter_of_ne (w : ι → k) (p : ι → P) (b : P) {pred : ι → Prop}
[DecidablePred pred] (h : ∀ i ∈ s, w i ≠ 0 → pred i) :
{x ∈ s | pred x}.weightedVSubOfPoint p b w = s.weightedVSubOfPoint p b w := by
rw [weightedVSubOfPoint_apply, weightedVSubOfPoint_apply, sum_filter_of_ne]
intro i hi hne
refine h i hi ?_
intro hw
simp [hw] at hne
/-- A constant multiplier of the weights in `weightedVSubOfPoint` may be moved outside the
sum. -/
theorem weightedVSubOfPoint_const_smul (w : ι → k) (p : ι → P) (b : P) (c : k) :
s.weightedVSubOfPoint p b (c • w) = c • s.weightedVSubOfPoint p b w := by
simp_rw [weightedVSubOfPoint_apply, smul_sum, Pi.smul_apply, smul_smul, smul_eq_mul]
/-- A weighted sum of the results of subtracting a default base point
from the given points, as a linear map on the weights. This is
intended to be used when the sum of the weights is 0; that condition
is specified as a hypothesis on those lemmas that require it. -/
def weightedVSub (p : ι → P) : (ι → k) →ₗ[k] V :=
s.weightedVSubOfPoint p (Classical.choice S.nonempty)
/-- Applying `weightedVSub` with given weights. This is for the case
where a result involving a default base point is OK (for example, when
that base point will cancel out later); a more typical use case for
`weightedVSub` would involve selecting a preferred base point with
`weightedVSub_eq_weightedVSubOfPoint_of_sum_eq_zero` and then
using `weightedVSubOfPoint_apply`. -/
theorem weightedVSub_apply (w : ι → k) (p : ι → P) :
s.weightedVSub p w = ∑ i ∈ s, w i • (p i -ᵥ Classical.choice S.nonempty) := by
simp [weightedVSub, LinearMap.sum_apply]
/-- `weightedVSub` gives the sum of the results of subtracting any
base point, when the sum of the weights is 0. -/
theorem weightedVSub_eq_weightedVSubOfPoint_of_sum_eq_zero (w : ι → k) (p : ι → P)
(h : ∑ i ∈ s, w i = 0) (b : P) : s.weightedVSub p w = s.weightedVSubOfPoint p b w :=
s.weightedVSubOfPoint_eq_of_sum_eq_zero w p h _ _
/-- The value of `weightedVSub`, where the given points are equal and the sum of the weights
is 0. -/
@[simp]
theorem weightedVSub_apply_const (w : ι → k) (p : P) (h : ∑ i ∈ s, w i = 0) :
s.weightedVSub (fun _ => p) w = 0 := by
rw [weightedVSub, weightedVSubOfPoint_apply_const, h, zero_smul]
/-- The `weightedVSub` for an empty set is 0. -/
@[simp]
theorem weightedVSub_empty (w : ι → k) (p : ι → P) : (∅ : Finset ι).weightedVSub p w = (0 : V) := by
simp [weightedVSub_apply]
lemma weightedVSub_vadd {s : Finset ι} {w : ι → k} (h : ∑ i ∈ s, w i = 0) (p : ι → P) (v : V) :
s.weightedVSub (v +ᵥ p) w = s.weightedVSub p w := by
rw [weightedVSub, weightedVSubOfPoint_vadd,
weightedVSub_eq_weightedVSubOfPoint_of_sum_eq_zero _ _ _ h]
lemma weightedVSub_smul {G : Type*} [Group G] [DistribMulAction G V] [SMulCommClass G k V]
{s : Finset ι} {w : ι → k} (h : ∑ i ∈ s, w i = 0) (p : ι → V) (a : G) :
s.weightedVSub (a • p) w = a • s.weightedVSub p w := by
| rw [weightedVSub, weightedVSubOfPoint_smul,
weightedVSub_eq_weightedVSubOfPoint_of_sum_eq_zero _ _ _ h]
| Mathlib/LinearAlgebra/AffineSpace/Combination.lean | 271 | 273 |
/-
Copyright (c) 2022 Moritz Firsching. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Firsching, Fabian Kruse, Nikolas Kuhn
-/
import Mathlib.Analysis.PSeries
import Mathlib.Data.Real.Pi.Wallis
import Mathlib.Tactic.AdaptationNote
/-!
# Stirling's formula
This file proves Stirling's formula for the factorial.
It states that $n!$ grows asymptotically like $\sqrt{2\pi n}(\frac{n}{e})^n$.
## Proof outline
The proof follows: <https://proofwiki.org/wiki/Stirling%27s_Formula>.
We proceed in two parts.
**Part 1**: We consider the sequence $a_n$ of fractions $\frac{n!}{\sqrt{2n}(\frac{n}{e})^n}$
and prove that this sequence converges to a real, positive number $a$. For this the two main
ingredients are
- taking the logarithm of the sequence and
- using the series expansion of $\log(1 + x)$.
**Part 2**: We use the fact that the series defined in part 1 converges against a real number $a$
and prove that $a = \sqrt{\pi}$. Here the main ingredient is the convergence of Wallis' product
formula for `π`.
-/
open scoped Topology Real Nat Asymptotics
open Finset Filter Nat Real
namespace Stirling
/-!
### Part 1
https://proofwiki.org/wiki/Stirling%27s_Formula#Part_1
-/
/-- Define `stirlingSeq n` as $\frac{n!}{\sqrt{2n}(\frac{n}{e})^n}$.
Stirling's formula states that this sequence has limit $\sqrt(π)$.
-/
noncomputable def stirlingSeq (n : ℕ) : ℝ :=
n ! / (√(2 * n : ℝ) * (n / exp 1) ^ n)
@[simp]
theorem stirlingSeq_zero : stirlingSeq 0 = 0 := by
rw [stirlingSeq, cast_zero, mul_zero, Real.sqrt_zero, zero_mul, div_zero]
@[simp]
theorem stirlingSeq_one : stirlingSeq 1 = exp 1 / √2 := by
rw [stirlingSeq, pow_one, factorial_one, cast_one, mul_one, mul_one_div, one_div_div]
theorem log_stirlingSeq_formula (n : ℕ) :
log (stirlingSeq n) = Real.log n ! - 1 / 2 * Real.log (2 * n) - n * log (n / exp 1) := by
cases n
· simp
· rw [stirlingSeq, log_div, log_mul, sqrt_eq_rpow, log_rpow, Real.log_pow, tsub_tsub]
<;> positivity
/-- The sequence `log (stirlingSeq (m + 1)) - log (stirlingSeq (m + 2))` has the series expansion
`∑ 1 / (2 * (k + 1) + 1) * (1 / 2 * (m + 1) + 1)^(2 * (k + 1))`
-/
theorem log_stirlingSeq_diff_hasSum (m : ℕ) :
HasSum (fun k : ℕ => (1 : ℝ) / (2 * ↑(k + 1) + 1) * ((1 / (2 * ↑(m + 1) + 1)) ^ 2) ^ ↑(k + 1))
(log (stirlingSeq (m + 1)) - log (stirlingSeq (m + 2))) := by
let f (k : ℕ) := (1 : ℝ) / (2 * k + 1) * ((1 / (2 * ↑(m + 1) + 1)) ^ 2) ^ k
change HasSum (fun k => f (k + 1)) _
rw [hasSum_nat_add_iff]
convert (hasSum_log_one_add_inv m.cast_add_one_pos).mul_left ((↑(m + 1) : ℝ) + 1 / 2) using 1
· ext k
dsimp only [f]
rw [← pow_mul, pow_add]
push_cast
field_simp
ring
· have h : ∀ x ≠ (0 : ℝ), 1 + x⁻¹ = (x + 1) / x := fun x hx ↦ by field_simp [hx]
simp (disch := positivity) only [log_stirlingSeq_formula, log_div, log_mul, log_exp,
factorial_succ, cast_mul, cast_succ, cast_zero, range_one, sum_singleton, h]
ring
/-- The sequence `log ∘ stirlingSeq ∘ succ` is monotone decreasing -/
theorem log_stirlingSeq'_antitone : Antitone (Real.log ∘ stirlingSeq ∘ succ) :=
antitone_nat_of_succ_le fun n =>
sub_nonneg.mp <| (log_stirlingSeq_diff_hasSum n).nonneg fun m => by positivity
/-- We have a bound for successive elements in the sequence `log (stirlingSeq k)`.
-/
theorem log_stirlingSeq_diff_le_geo_sum (n : ℕ) :
log (stirlingSeq (n + 1)) - log (stirlingSeq (n + 2)) ≤
((1 : ℝ) / (2 * ↑(n + 1) + 1)) ^ 2 / (1 - ((1 : ℝ) / (2 * ↑(n + 1) + 1)) ^ 2) := by
have h_nonneg : (0 : ℝ) ≤ ((1 : ℝ) / (2 * ↑(n + 1) + 1)) ^ 2 := sq_nonneg _
have g : HasSum (fun k : ℕ => (((1 : ℝ) / (2 * ↑(n + 1) + 1)) ^ 2) ^ ↑(k + 1))
(((1 : ℝ) / (2 * ↑(n + 1) + 1)) ^ 2 / (1 - ((1 : ℝ) / (2 * ↑(n + 1) + 1)) ^ 2)) := by
have := (hasSum_geometric_of_lt_one h_nonneg ?_).mul_left (((1 : ℝ) / (2 * ↑(n + 1) + 1)) ^ 2)
· simp_rw [← _root_.pow_succ'] at this
exact this
rw [one_div, inv_pow]
exact inv_lt_one_of_one_lt₀ (one_lt_pow₀ (lt_add_of_pos_left _ <| by positivity) two_ne_zero)
have hab (k : ℕ) : (1 : ℝ) / (2 * ↑(k + 1) + 1) * ((1 / (2 * ↑(n + 1) + 1)) ^ 2) ^ ↑(k + 1) ≤
(((1 : ℝ) / (2 * ↑(n + 1) + 1)) ^ 2) ^ ↑(k + 1) := by
refine mul_le_of_le_one_left (pow_nonneg h_nonneg ↑(k + 1)) ?_
rw [one_div]
exact inv_le_one_of_one_le₀ (le_add_of_nonneg_left <| by positivity)
exact hasSum_le hab (log_stirlingSeq_diff_hasSum n) g
/-- We have the bound `log (stirlingSeq n) - log (stirlingSeq (n+1))` ≤ 1/(4 n^2)
-/
theorem log_stirlingSeq_sub_log_stirlingSeq_succ (n : ℕ) :
log (stirlingSeq (n + 1)) - log (stirlingSeq (n + 2)) ≤ 1 / (4 * (↑(n + 1) : ℝ) ^ 2) := by
have h₁ : (0 : ℝ) < 4 * ((n : ℝ) + 1) ^ 2 := by positivity
have h₃ : (0 : ℝ) < (2 * ((n : ℝ) + 1) + 1) ^ 2 := by positivity
have h₂ : (0 : ℝ) < 1 - (1 / (2 * ((n : ℝ) + 1) + 1)) ^ 2 := by
rw [← mul_lt_mul_right h₃]
have H : 0 < (2 * ((n : ℝ) + 1) + 1) ^ 2 - 1 := by nlinarith [cast_nonneg (α := ℝ) n]
convert H using 1 <;> field_simp [h₃.ne']
refine (log_stirlingSeq_diff_le_geo_sum n).trans ?_
push_cast
rw [div_le_div_iff₀ h₂ h₁]
field_simp [h₃.ne']
rw [div_le_div_iff_of_pos_right h₃]
ring_nf
norm_cast
omega
/-- For any `n`, we have `log_stirlingSeq 1 - log_stirlingSeq n ≤ 1/4 * ∑' 1/k^2` -/
theorem log_stirlingSeq_bounded_aux :
∃ c : ℝ, ∀ n : ℕ, log (stirlingSeq 1) - log (stirlingSeq (n + 1)) ≤ c := by
let d : ℝ := ∑' k : ℕ, (1 : ℝ) / (↑(k + 1) : ℝ) ^ 2
use 1 / 4 * d
let log_stirlingSeq' : ℕ → ℝ := fun k => log (stirlingSeq (k + 1))
intro n
have h₁ k : log_stirlingSeq' k - log_stirlingSeq' (k + 1) ≤ 1 / 4 * (1 / (↑(k + 1) : ℝ) ^ 2) := by
convert log_stirlingSeq_sub_log_stirlingSeq_succ k using 1; field_simp
have h₂ : (∑ k ∈ range n, 1 / (↑(k + 1) : ℝ) ^ 2) ≤ d := by
have := (summable_nat_add_iff 1).mpr <| Real.summable_one_div_nat_pow.mpr one_lt_two
exact this.sum_le_tsum (range n) (fun k _ => by positivity)
calc
log (stirlingSeq 1) - log (stirlingSeq (n + 1)) = log_stirlingSeq' 0 - log_stirlingSeq' n :=
rfl
_ = ∑ k ∈ range n, (log_stirlingSeq' k - log_stirlingSeq' (k + 1)) := by
rw [← sum_range_sub' log_stirlingSeq' n]
_ ≤ ∑ k ∈ range n, 1 / 4 * (1 / ↑((k + 1)) ^ 2) := sum_le_sum fun k _ => h₁ k
_ = 1 / 4 * ∑ k ∈ range n, 1 / ↑((k + 1)) ^ 2 := by rw [mul_sum]
_ ≤ 1 / 4 * d := by gcongr
/-- The sequence `log_stirlingSeq` is bounded below for `n ≥ 1`. -/
theorem log_stirlingSeq_bounded_by_constant : ∃ c, ∀ n : ℕ, c ≤ log (stirlingSeq (n + 1)) := by
obtain ⟨d, h⟩ := log_stirlingSeq_bounded_aux
exact ⟨log (stirlingSeq 1) - d, fun n => sub_le_comm.mp (h n)⟩
/-- The sequence `stirlingSeq` is positive for `n > 0` -/
theorem stirlingSeq'_pos (n : ℕ) : 0 < stirlingSeq (n + 1) := by unfold stirlingSeq; positivity
/-- The sequence `stirlingSeq` has a positive lower bound.
-/
theorem stirlingSeq'_bounded_by_pos_constant : ∃ a, 0 < a ∧ ∀ n : ℕ, a ≤ stirlingSeq (n + 1) := by
obtain ⟨c, h⟩ := log_stirlingSeq_bounded_by_constant
refine ⟨exp c, exp_pos _, fun n => ?_⟩
rw [← le_log_iff_exp_le (stirlingSeq'_pos n)]
exact h n
/-- The sequence `stirlingSeq ∘ succ` is monotone decreasing -/
theorem stirlingSeq'_antitone : Antitone (stirlingSeq ∘ succ) := fun n m h =>
(log_le_log_iff (stirlingSeq'_pos m) (stirlingSeq'_pos n)).mp (log_stirlingSeq'_antitone h)
/-- The limit `a` of the sequence `stirlingSeq` satisfies `0 < a` -/
theorem stirlingSeq_has_pos_limit_a : ∃ a : ℝ, 0 < a ∧ Tendsto stirlingSeq atTop (𝓝 a) := by
obtain ⟨x, x_pos, hx⟩ := stirlingSeq'_bounded_by_pos_constant
have hx' : x ∈ lowerBounds (Set.range (stirlingSeq ∘ succ)) := by simpa [lowerBounds] using hx
refine ⟨_, lt_of_lt_of_le x_pos (le_csInf (Set.range_nonempty _) hx'), ?_⟩
rw [← Filter.tendsto_add_atTop_iff_nat 1]
exact tendsto_atTop_ciInf stirlingSeq'_antitone ⟨x, hx'⟩
/-!
### Part 2
https://proofwiki.org/wiki/Stirling%27s_Formula#Part_2
-/
/-- The sequence `n / (2 * n + 1)` tends to `1/2` -/
theorem tendsto_self_div_two_mul_self_add_one :
Tendsto (fun n : ℕ => (n : ℝ) / (2 * n + 1)) atTop (𝓝 (1 / 2)) := by
conv =>
congr
· skip
· skip
| rw [one_div, ← add_zero (2 : ℝ)]
refine (((tendsto_const_div_atTop_nhds_zero_nat 1).const_add (2 : ℝ)).inv₀
((add_zero (2 : ℝ)).symm ▸ two_ne_zero)).congr' (eventually_atTop.mpr ⟨1, fun n hn => ?_⟩)
rw [add_div' (1 : ℝ) 2 n (cast_ne_zero.mpr (one_le_iff_ne_zero.mp hn)), inv_div]
/-- For any `n ≠ 0`, we have the identity
| Mathlib/Analysis/SpecialFunctions/Stirling.lean | 194 | 199 |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson
-/
import Mathlib.Order.Monotone.Odd
import Mathlib.Analysis.Calculus.LogDeriv
import Mathlib.Analysis.SpecialFunctions.ExpDeriv
import Mathlib.Analysis.SpecialFunctions.Trigonometric.Basic
import Mathlib.Analysis.Calculus.Deriv.MeanValue
/-!
# Differentiability of trigonometric functions
## Main statements
The differentiability of the usual trigonometric functions is proved, and their derivatives are
computed.
## Tags
sin, cos, tan, angle
-/
noncomputable section
open scoped Topology Filter
open Set
namespace Complex
/-- The complex sine function is everywhere strictly differentiable, with the derivative `cos x`. -/
theorem hasStrictDerivAt_sin (x : ℂ) : HasStrictDerivAt sin (cos x) x := by
simp only [cos, div_eq_mul_inv]
convert ((((hasStrictDerivAt_id x).neg.mul_const I).cexp.sub
((hasStrictDerivAt_id x).mul_const I).cexp).mul_const I).mul_const (2 : ℂ)⁻¹ using 1
simp only [Function.comp, id]
rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc,
I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm]
/-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/
theorem hasDerivAt_sin (x : ℂ) : HasDerivAt sin (cos x) x :=
(hasStrictDerivAt_sin x).hasDerivAt
theorem contDiff_sin {n} : ContDiff ℂ n sin :=
(((contDiff_neg.mul contDiff_const).cexp.sub (contDiff_id.mul contDiff_const).cexp).mul
contDiff_const).div_const _
@[simp]
theorem differentiable_sin : Differentiable ℂ sin := fun x => (hasDerivAt_sin x).differentiableAt
@[simp]
theorem differentiableAt_sin {x : ℂ} : DifferentiableAt ℂ sin x :=
differentiable_sin x
@[simp]
theorem deriv_sin : deriv sin = cos :=
funext fun x => (hasDerivAt_sin x).deriv
/-- The complex cosine function is everywhere strictly differentiable, with the derivative
`-sin x`. -/
theorem hasStrictDerivAt_cos (x : ℂ) : HasStrictDerivAt cos (-sin x) x := by
simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul]
convert (((hasStrictDerivAt_id x).mul_const I).cexp.add
((hasStrictDerivAt_id x).neg.mul_const I).cexp).mul_const (2 : ℂ)⁻¹ using 1
simp only [Function.comp, id]
ring
/-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/
theorem hasDerivAt_cos (x : ℂ) : HasDerivAt cos (-sin x) x :=
(hasStrictDerivAt_cos x).hasDerivAt
theorem contDiff_cos {n} : ContDiff ℂ n cos :=
((contDiff_id.mul contDiff_const).cexp.add (contDiff_neg.mul contDiff_const).cexp).div_const _
@[simp]
theorem differentiable_cos : Differentiable ℂ cos := fun x => (hasDerivAt_cos x).differentiableAt
@[simp]
theorem differentiableAt_cos {x : ℂ} : DifferentiableAt ℂ cos x :=
differentiable_cos x
theorem deriv_cos {x : ℂ} : deriv cos x = -sin x :=
(hasDerivAt_cos x).deriv
@[simp]
theorem deriv_cos' : deriv cos = fun x => -sin x :=
funext fun _ => deriv_cos
/-- The complex hyperbolic sine function is everywhere strictly differentiable, with the derivative
`cosh x`. -/
theorem hasStrictDerivAt_sinh (x : ℂ) : HasStrictDerivAt sinh (cosh x) x := by
simp only [cosh, div_eq_mul_inv]
convert ((hasStrictDerivAt_exp x).sub (hasStrictDerivAt_id x).neg.cexp).mul_const (2 : ℂ)⁻¹
using 1
rw [id, mul_neg_one, sub_eq_add_neg, neg_neg]
/-- The complex hyperbolic sine function is everywhere differentiable, with the derivative
`cosh x`. -/
theorem hasDerivAt_sinh (x : ℂ) : HasDerivAt sinh (cosh x) x :=
(hasStrictDerivAt_sinh x).hasDerivAt
| theorem contDiff_sinh {n} : ContDiff ℂ n sinh :=
(contDiff_exp.sub contDiff_neg.cexp).div_const _
@[simp]
theorem differentiable_sinh : Differentiable ℂ sinh := fun x => (hasDerivAt_sinh x).differentiableAt
| Mathlib/Analysis/SpecialFunctions/Trigonometric/Deriv.lean | 103 | 107 |
/-
Copyright (c) 2023 Yaël Dillies, Chenyi Li. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chenyi Li, Ziyu Wang, Yaël Dillies
-/
import Mathlib.Analysis.Convex.Function
import Mathlib.Analysis.InnerProductSpace.Basic
/-!
# Uniformly and strongly convex functions
In this file, we define uniformly convex functions and strongly convex functions.
For a real normed space `E`, a uniformly convex function with modulus `φ : ℝ → ℝ` is a function
`f : E → ℝ` such that `f (t • x + (1 - t) • y) ≤ t • f x + (1 - t) • f y - t * (1 - t) * φ ‖x - y‖`
for all `t ∈ [0, 1]`.
A `m`-strongly convex function is a uniformly convex function with modulus `fun r ↦ m / 2 * r ^ 2`.
If `E` is an inner product space, this is equivalent to `x ↦ f x - m / 2 * ‖x‖ ^ 2` being convex.
## TODO
Prove derivative properties of strongly convex functions.
-/
open Real
variable {E : Type*} [NormedAddCommGroup E]
section NormedSpace
variable [NormedSpace ℝ E] {φ ψ : ℝ → ℝ} {s : Set E} {m : ℝ} {f g : E → ℝ}
/-- A function `f` from a real normed space is uniformly convex with modulus `φ` if
`f (t • x + (1 - t) • y) ≤ t • f x + (1 - t) • f y - t * (1 - t) * φ ‖x - y‖` for all `t ∈ [0, 1]`.
`φ` is usually taken to be a monotone function such that `φ r = 0 ↔ r = 0`. -/
def UniformConvexOn (s : Set E) (φ : ℝ → ℝ) (f : E → ℝ) : Prop :=
Convex ℝ s ∧ ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
f (a • x + b • y) ≤ a • f x + b • f y - a * b * φ ‖x - y‖
/-- A function `f` from a real normed space is uniformly concave with modulus `φ` if
`t • f x + (1 - t) • f y + t * (1 - t) * φ ‖x - y‖ ≤ f (t • x + (1 - t) • y)` for all `t ∈ [0, 1]`.
`φ` is usually taken to be a monotone function such that `φ r = 0 ↔ r = 0`. -/
def UniformConcaveOn (s : Set E) (φ : ℝ → ℝ) (f : E → ℝ) : Prop :=
Convex ℝ s ∧ ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
a • f x + b • f y + a * b * φ ‖x - y‖ ≤ f (a • x + b • y)
@[simp] lemma uniformConvexOn_zero : UniformConvexOn s 0 f ↔ ConvexOn ℝ s f := by
simp [UniformConvexOn, ConvexOn]
@[simp] lemma uniformConcaveOn_zero : UniformConcaveOn s 0 f ↔ ConcaveOn ℝ s f := by
simp [UniformConcaveOn, ConcaveOn]
protected alias ⟨_, ConvexOn.uniformConvexOn_zero⟩ := uniformConvexOn_zero
protected alias ⟨_, ConcaveOn.uniformConcaveOn_zero⟩ := uniformConcaveOn_zero
lemma UniformConvexOn.mono (hψφ : ψ ≤ φ) (hf : UniformConvexOn s φ f) : UniformConvexOn s ψ f :=
⟨hf.1, fun x hx y hy a b ha hb hab ↦ (hf.2 hx hy ha hb hab).trans <| by gcongr; apply hψφ⟩
lemma UniformConcaveOn.mono (hψφ : ψ ≤ φ) (hf : UniformConcaveOn s φ f) : UniformConcaveOn s ψ f :=
⟨hf.1, fun x hx y hy a b ha hb hab ↦ (hf.2 hx hy ha hb hab).trans' <| by gcongr; apply hψφ⟩
lemma UniformConvexOn.convexOn (hf : UniformConvexOn s φ f) (hφ : 0 ≤ φ) : ConvexOn ℝ s f := by
simpa using hf.mono hφ
lemma UniformConcaveOn.concaveOn (hf : UniformConcaveOn s φ f) (hφ : 0 ≤ φ) : ConcaveOn ℝ s f := by
simpa using hf.mono hφ
lemma UniformConvexOn.strictConvexOn (hf : UniformConvexOn s φ f) (hφ : ∀ r, r ≠ 0 → 0 < φ r) :
StrictConvexOn ℝ s f := by
refine ⟨hf.1, fun x hx y hy hxy a b ha hb hab ↦ (hf.2 hx hy ha.le hb.le hab).trans_lt <|
sub_lt_self _ ?_⟩
rw [← sub_ne_zero, ← norm_pos_iff] at hxy
have := hφ _ hxy.ne'
positivity
lemma UniformConcaveOn.strictConcaveOn (hf : UniformConcaveOn s φ f) (hφ : ∀ r, r ≠ 0 → 0 < φ r) :
StrictConcaveOn ℝ s f := by
refine ⟨hf.1, fun x hx y hy hxy a b ha hb hab ↦ (hf.2 hx hy ha.le hb.le hab).trans_lt' <|
lt_add_of_pos_right _ ?_⟩
rw [← sub_ne_zero, ← norm_pos_iff] at hxy
have := hφ _ hxy.ne'
positivity
lemma UniformConvexOn.add (hf : UniformConvexOn s φ f) (hg : UniformConvexOn s ψ g) :
UniformConvexOn s (φ + ψ) (f + g) := by
refine ⟨hf.1, fun x hx y hy a b ha hb hab ↦ ?_⟩
simpa [mul_add, add_add_add_comm, sub_add_sub_comm]
using add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab)
lemma UniformConcaveOn.add (hf : UniformConcaveOn s φ f) (hg : UniformConcaveOn s ψ g) :
UniformConcaveOn s (φ + ψ) (f + g) := by
refine ⟨hf.1, fun x hx y hy a b ha hb hab ↦ ?_⟩
simpa [mul_add, add_add_add_comm] using add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab)
lemma UniformConvexOn.neg (hf : UniformConvexOn s φ f) : UniformConcaveOn s φ (-f) := by
refine ⟨hf.1, fun x hx y hy a b ha hb hab ↦ le_of_neg_le_neg ?_⟩
simpa [add_comm, -neg_le_neg_iff, le_sub_iff_add_le'] using hf.2 hx hy ha hb hab
lemma UniformConcaveOn.neg (hf : UniformConcaveOn s φ f) : UniformConvexOn s φ (-f) := by
refine ⟨hf.1, fun x hx y hy a b ha hb hab ↦ le_of_neg_le_neg ?_⟩
simpa [add_comm, -neg_le_neg_iff, ← le_sub_iff_add_le', sub_eq_add_neg, neg_add]
using hf.2 hx hy ha hb hab
lemma UniformConvexOn.sub (hf : UniformConvexOn s φ f) (hg : UniformConcaveOn s ψ g) :
UniformConvexOn s (φ + ψ) (f - g) := by simpa using hf.add hg.neg
lemma UniformConcaveOn.sub (hf : UniformConcaveOn s φ f) (hg : UniformConvexOn s ψ g) :
UniformConcaveOn s (φ + ψ) (f - g) := by simpa using hf.add hg.neg
/-- A function `f` from a real normed space is `m`-strongly convex if it is uniformly convex with
modulus `φ(r) = m / 2 * r ^ 2`.
In an inner product space, this is equivalent to `x ↦ f x - m / 2 * ‖x‖ ^ 2` being convex. -/
def StrongConvexOn (s : Set E) (m : ℝ) : (E → ℝ) → Prop :=
UniformConvexOn s fun r ↦ m / (2 : ℝ) * r ^ 2
/-- A function `f` from a real normed space is `m`-strongly concave if is strongly concave with
modulus `φ(r) = m / 2 * r ^ 2`.
In an inner product space, this is equivalent to `x ↦ f x + m / 2 * ‖x‖ ^ 2` being concave. -/
def StrongConcaveOn (s : Set E) (m : ℝ) : (E → ℝ) → Prop :=
UniformConcaveOn s fun r ↦ m / (2 : ℝ) * r ^ 2
variable {s : Set E} {f : E → ℝ} {m n : ℝ}
nonrec lemma StrongConvexOn.mono (hmn : m ≤ n) (hf : StrongConvexOn s n f) : StrongConvexOn s m f :=
hf.mono fun r ↦ by gcongr
nonrec lemma StrongConcaveOn.mono (hmn : m ≤ n) (hf : StrongConcaveOn s n f) :
StrongConcaveOn s m f := hf.mono fun r ↦ by gcongr
@[simp] lemma strongConvexOn_zero : StrongConvexOn s 0 f ↔ ConvexOn ℝ s f := by
simp [StrongConvexOn, ← Pi.zero_def]
@[simp] lemma strongConcaveOn_zero : StrongConcaveOn s 0 f ↔ ConcaveOn ℝ s f := by
simp [StrongConcaveOn, ← Pi.zero_def]
|
nonrec lemma StrongConvexOn.strictConvexOn (hf : StrongConvexOn s m f) (hm : 0 < m) :
| Mathlib/Analysis/Convex/Strong.lean | 139 | 140 |
/-
Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn
-/
import Mathlib.Data.Finset.Basic
import Mathlib.ModelTheory.Syntax
import Mathlib.Data.List.ProdSigma
/-!
# Basics on First-Order Semantics
This file defines the interpretations of first-order terms, formulas, sentences, and theories
in a style inspired by the [Flypitch project](https://flypitch.github.io/).
## Main Definitions
- `FirstOrder.Language.Term.realize` is defined so that `t.realize v` is the term `t` evaluated at
variables `v`.
- `FirstOrder.Language.BoundedFormula.Realize` is defined so that `φ.Realize v xs` is the bounded
formula `φ` evaluated at tuples of variables `v` and `xs`.
- `FirstOrder.Language.Formula.Realize` is defined so that `φ.Realize v` is the formula `φ`
evaluated at variables `v`.
- `FirstOrder.Language.Sentence.Realize` is defined so that `φ.Realize M` is the sentence `φ`
evaluated in the structure `M`. Also denoted `M ⊨ φ`.
- `FirstOrder.Language.Theory.Model` is defined so that `T.Model M` is true if and only if every
sentence of `T` is realized in `M`. Also denoted `T ⊨ φ`.
## Main Results
- Several results in this file show that syntactic constructions such as `relabel`, `castLE`,
`liftAt`, `subst`, and the actions of language maps commute with realization of terms, formulas,
sentences, and theories.
## Implementation Notes
- Formulas use a modified version of de Bruijn variables. Specifically, a `L.BoundedFormula α n`
is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some
indexed by `Fin n`, which can. For any `φ : L.BoundedFormula α (n + 1)`, we define the formula
`∀' φ : L.BoundedFormula α n` by universally quantifying over the variable indexed by
`n : Fin (n + 1)`.
## References
For the Flypitch project:
- [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*]
[flypitch_cpp]
- [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of
the continuum hypothesis*][flypitch_itp]
-/
universe u v w u' v'
namespace FirstOrder
namespace Language
variable {L : Language.{u, v}} {L' : Language}
variable {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P]
variable {α : Type u'} {β : Type v'} {γ : Type*}
open FirstOrder Cardinal
open Structure Cardinal Fin
namespace Term
/-- A term `t` with variables indexed by `α` can be evaluated by giving a value to each variable. -/
def realize (v : α → M) : ∀ _t : L.Term α, M
| var k => v k
| func f ts => funMap f fun i => (ts i).realize v
@[simp]
theorem realize_var (v : α → M) (k) : realize v (var k : L.Term α) = v k := rfl
@[simp]
theorem realize_func (v : α → M) {n} (f : L.Functions n) (ts) :
realize v (func f ts : L.Term α) = funMap f fun i => (ts i).realize v := rfl
@[simp]
theorem realize_relabel {t : L.Term α} {g : α → β} {v : β → M} :
(t.relabel g).realize v = t.realize (v ∘ g) := by
induction t with
| var => rfl
| func f ts ih => simp [ih]
@[simp]
theorem realize_liftAt {n n' m : ℕ} {t : L.Term (α ⊕ (Fin n))} {v : α ⊕ (Fin (n + n')) → M} :
(t.liftAt n' m).realize v =
t.realize (v ∘ Sum.map id fun i : Fin _ =>
if ↑i < m then Fin.castAdd n' i else Fin.addNat i n') :=
realize_relabel
@[simp]
theorem realize_constants {c : L.Constants} {v : α → M} : c.term.realize v = c :=
funMap_eq_coe_constants
@[simp]
theorem realize_functions_apply₁ {f : L.Functions 1} {t : L.Term α} {v : α → M} :
(f.apply₁ t).realize v = funMap f ![t.realize v] := by
rw [Functions.apply₁, Term.realize]
refine congr rfl (funext fun i => ?_)
simp only [Matrix.cons_val_fin_one]
@[simp]
theorem realize_functions_apply₂ {f : L.Functions 2} {t₁ t₂ : L.Term α} {v : α → M} :
(f.apply₂ t₁ t₂).realize v = funMap f ![t₁.realize v, t₂.realize v] := by
rw [Functions.apply₂, Term.realize]
refine congr rfl (funext (Fin.cases ?_ ?_))
· simp only [Matrix.cons_val_zero]
· simp only [Matrix.cons_val_succ, Matrix.cons_val_fin_one, forall_const]
theorem realize_con {A : Set M} {a : A} {v : α → M} : (L.con a).term.realize v = a :=
rfl
@[simp]
theorem realize_subst {t : L.Term α} {tf : α → L.Term β} {v : β → M} :
(t.subst tf).realize v = t.realize fun a => (tf a).realize v := by
induction t with
| var => rfl
| func _ _ ih => simp [ih]
theorem realize_restrictVar [DecidableEq α] {t : L.Term α} {f : t.varFinset → β}
{v : β → M} (v' : α → M) (hv' : ∀ a, v (f a) = v' a) :
(t.restrictVar f).realize v = t.realize v' := by
induction t with
| var => simp [restrictVar, hv']
| func _ _ ih =>
exact congr rfl (funext fun i => ih i ((by simp [Function.comp_apply, hv'])))
/-- A special case of `realize_restrictVar`, included because we can add the `simp` attribute
to it -/
@[simp]
theorem realize_restrictVar' [DecidableEq α] {t : L.Term α} {s : Set α} (h : ↑t.varFinset ⊆ s)
{v : α → M} : (t.restrictVar (Set.inclusion h)).realize (v ∘ (↑)) = t.realize v :=
realize_restrictVar _ (by simp)
theorem realize_restrictVarLeft [DecidableEq α] {γ : Type*} {t : L.Term (α ⊕ γ)}
{f : t.varFinsetLeft → β}
{xs : β ⊕ γ → M} (xs' : α → M) (hxs' : ∀ a, xs (Sum.inl (f a)) = xs' a) :
(t.restrictVarLeft f).realize xs = t.realize (Sum.elim xs' (xs ∘ Sum.inr)) := by
induction t with
| var a => cases a <;> simp [restrictVarLeft, hxs']
| func _ _ ih =>
exact congr rfl (funext fun i => ih i (by simp [hxs']))
/-- A special case of `realize_restrictVarLeft`, included because we can add the `simp` attribute
to it -/
@[simp]
theorem realize_restrictVarLeft' [DecidableEq α] {γ : Type*} {t : L.Term (α ⊕ γ)} {s : Set α}
(h : ↑t.varFinsetLeft ⊆ s) {v : α → M} {xs : γ → M} :
(t.restrictVarLeft (Set.inclusion h)).realize (Sum.elim (v ∘ (↑)) xs) =
t.realize (Sum.elim v xs) :=
realize_restrictVarLeft _ (by simp)
@[simp]
theorem realize_constantsToVars [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M]
{t : L[[α]].Term β} {v : β → M} :
t.constantsToVars.realize (Sum.elim (fun a => ↑(L.con a)) v) = t.realize v := by
induction t with
| var => simp
| @func n f ts ih =>
cases n
· cases f
· simp only [realize, ih, constantsOn, constantsOnFunc, constantsToVars]
-- Porting note: below lemma does not work with simp for some reason
rw [withConstants_funMap_sumInl]
· simp only [realize, constantsToVars, Sum.elim_inl, funMap_eq_coe_constants]
rfl
· obtain - | f := f
· simp only [realize, ih, constantsOn, constantsOnFunc, constantsToVars]
-- Porting note: below lemma does not work with simp for some reason
rw [withConstants_funMap_sumInl]
· exact isEmptyElim f
@[simp]
theorem realize_varsToConstants [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M]
{t : L.Term (α ⊕ β)} {v : β → M} :
t.varsToConstants.realize v = t.realize (Sum.elim (fun a => ↑(L.con a)) v) := by
induction t with
| var ab => rcases ab with a | b <;> simp [Language.con]
| func f ts ih =>
simp only [realize, constantsOn, constantsOnFunc, ih, varsToConstants]
-- Porting note: below lemma does not work with simp for some reason
rw [withConstants_funMap_sumInl]
theorem realize_constantsVarsEquivLeft [L[[α]].Structure M]
[(lhomWithConstants L α).IsExpansionOn M] {n} {t : L[[α]].Term (β ⊕ (Fin n))} {v : β → M}
{xs : Fin n → M} :
(constantsVarsEquivLeft t).realize (Sum.elim (Sum.elim (fun a => ↑(L.con a)) v) xs) =
t.realize (Sum.elim v xs) := by
simp only [constantsVarsEquivLeft, realize_relabel, Equiv.coe_trans, Function.comp_apply,
constantsVarsEquiv_apply, relabelEquiv_symm_apply]
refine _root_.trans ?_ realize_constantsToVars
rcongr x
rcases x with (a | (b | i)) <;> simp
end Term
namespace LHom
@[simp]
theorem realize_onTerm [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] (t : L.Term α)
(v : α → M) : (φ.onTerm t).realize v = t.realize v := by
induction t with
| var => rfl
| func f ts ih => simp only [Term.realize, LHom.onTerm, LHom.map_onFunction, ih]
end LHom
@[simp]
theorem HomClass.realize_term {F : Type*} [FunLike F M N] [HomClass L F M N]
(g : F) {t : L.Term α} {v : α → M} :
t.realize (g ∘ v) = g (t.realize v) := by
induction t
· rfl
· rw [Term.realize, Term.realize, HomClass.map_fun]
refine congr rfl ?_
ext x
simp [*]
variable {n : ℕ}
namespace BoundedFormula
open Term
/-- A bounded formula can be evaluated as true or false by giving values to each free variable. -/
def Realize : ∀ {l} (_f : L.BoundedFormula α l) (_v : α → M) (_xs : Fin l → M), Prop
| _, falsum, _v, _xs => False
| _, equal t₁ t₂, v, xs => t₁.realize (Sum.elim v xs) = t₂.realize (Sum.elim v xs)
| _, rel R ts, v, xs => RelMap R fun i => (ts i).realize (Sum.elim v xs)
| _, imp f₁ f₂, v, xs => Realize f₁ v xs → Realize f₂ v xs
| _, all f, v, xs => ∀ x : M, Realize f v (snoc xs x)
variable {l : ℕ} {φ ψ : L.BoundedFormula α l} {θ : L.BoundedFormula α l.succ}
variable {v : α → M} {xs : Fin l → M}
@[simp]
theorem realize_bot : (⊥ : L.BoundedFormula α l).Realize v xs ↔ False :=
Iff.rfl
@[simp]
theorem realize_not : φ.not.Realize v xs ↔ ¬φ.Realize v xs :=
Iff.rfl
@[simp]
theorem realize_bdEqual (t₁ t₂ : L.Term (α ⊕ (Fin l))) :
(t₁.bdEqual t₂).Realize v xs ↔ t₁.realize (Sum.elim v xs) = t₂.realize (Sum.elim v xs) :=
Iff.rfl
@[simp]
theorem realize_top : (⊤ : L.BoundedFormula α l).Realize v xs ↔ True := by simp [Top.top]
@[simp]
theorem realize_inf : (φ ⊓ ψ).Realize v xs ↔ φ.Realize v xs ∧ ψ.Realize v xs := by
simp [Inf.inf, Realize]
@[simp]
theorem realize_foldr_inf (l : List (L.BoundedFormula α n)) (v : α → M) (xs : Fin n → M) :
(l.foldr (· ⊓ ·) ⊤).Realize v xs ↔ ∀ φ ∈ l, BoundedFormula.Realize φ v xs := by
induction' l with φ l ih
· simp
· simp [ih]
@[simp]
theorem realize_imp : (φ.imp ψ).Realize v xs ↔ φ.Realize v xs → ψ.Realize v xs := by
simp only [Realize]
@[simp]
theorem realize_rel {k : ℕ} {R : L.Relations k} {ts : Fin k → L.Term _} :
(R.boundedFormula ts).Realize v xs ↔ RelMap R fun i => (ts i).realize (Sum.elim v xs) :=
Iff.rfl
@[simp]
theorem realize_rel₁ {R : L.Relations 1} {t : L.Term _} :
(R.boundedFormula₁ t).Realize v xs ↔ RelMap R ![t.realize (Sum.elim v xs)] := by
rw [Relations.boundedFormula₁, realize_rel, iff_eq_eq]
refine congr rfl (funext fun _ => ?_)
simp only [Matrix.cons_val_fin_one]
@[simp]
theorem realize_rel₂ {R : L.Relations 2} {t₁ t₂ : L.Term _} :
(R.boundedFormula₂ t₁ t₂).Realize v xs ↔
RelMap R ![t₁.realize (Sum.elim v xs), t₂.realize (Sum.elim v xs)] := by
rw [Relations.boundedFormula₂, realize_rel, iff_eq_eq]
refine congr rfl (funext (Fin.cases ?_ ?_))
· simp only [Matrix.cons_val_zero]
· simp only [Matrix.cons_val_succ, Matrix.cons_val_fin_one, forall_const]
@[simp]
theorem realize_sup : (φ ⊔ ψ).Realize v xs ↔ φ.Realize v xs ∨ ψ.Realize v xs := by
simp only [realize, max, realize_not, eq_iff_iff]
tauto
@[simp]
theorem realize_foldr_sup (l : List (L.BoundedFormula α n)) (v : α → M) (xs : Fin n → M) :
(l.foldr (· ⊔ ·) ⊥).Realize v xs ↔ ∃ φ ∈ l, BoundedFormula.Realize φ v xs := by
induction' l with φ l ih
· simp
· simp_rw [List.foldr_cons, realize_sup, ih, List.mem_cons, or_and_right, exists_or,
exists_eq_left]
@[simp]
theorem realize_all : (all θ).Realize v xs ↔ ∀ a : M, θ.Realize v (Fin.snoc xs a) :=
Iff.rfl
@[simp]
theorem realize_ex : θ.ex.Realize v xs ↔ ∃ a : M, θ.Realize v (Fin.snoc xs a) := by
rw [BoundedFormula.ex, realize_not, realize_all, not_forall]
simp_rw [realize_not, Classical.not_not]
@[simp]
theorem realize_iff : (φ.iff ψ).Realize v xs ↔ (φ.Realize v xs ↔ ψ.Realize v xs) := by
simp only [BoundedFormula.iff, realize_inf, realize_imp, and_imp, ← iff_def]
theorem realize_castLE_of_eq {m n : ℕ} (h : m = n) {h' : m ≤ n} {φ : L.BoundedFormula α m}
{v : α → M} {xs : Fin n → M} : (φ.castLE h').Realize v xs ↔ φ.Realize v (xs ∘ Fin.cast h) := by
subst h
simp only [castLE_rfl, cast_refl, OrderIso.coe_refl, Function.comp_id]
theorem realize_mapTermRel_id [L'.Structure M]
{ft : ∀ n, L.Term (α ⊕ (Fin n)) → L'.Term (β ⊕ (Fin n))}
{fr : ∀ n, L.Relations n → L'.Relations n} {n} {φ : L.BoundedFormula α n} {v : α → M}
{v' : β → M} {xs : Fin n → M}
(h1 :
∀ (n) (t : L.Term (α ⊕ (Fin n))) (xs : Fin n → M),
(ft n t).realize (Sum.elim v' xs) = t.realize (Sum.elim v xs))
(h2 : ∀ (n) (R : L.Relations n) (x : Fin n → M), RelMap (fr n R) x = RelMap R x) :
(φ.mapTermRel ft fr fun _ => id).Realize v' xs ↔ φ.Realize v xs := by
induction φ with
| falsum => rfl
| equal => simp [mapTermRel, Realize, h1]
| rel => simp [mapTermRel, Realize, h1, h2]
| imp _ _ ih1 ih2 => simp [mapTermRel, Realize, ih1, ih2]
| all _ ih => simp only [mapTermRel, Realize, ih, id]
theorem realize_mapTermRel_add_castLe [L'.Structure M] {k : ℕ}
{ft : ∀ n, L.Term (α ⊕ (Fin n)) → L'.Term (β ⊕ (Fin (k + n)))}
{fr : ∀ n, L.Relations n → L'.Relations n} {n} {φ : L.BoundedFormula α n}
(v : ∀ {n}, (Fin (k + n) → M) → α → M) {v' : β → M} (xs : Fin (k + n) → M)
(h1 :
∀ (n) (t : L.Term (α ⊕ (Fin n))) (xs' : Fin (k + n) → M),
(ft n t).realize (Sum.elim v' xs') = t.realize (Sum.elim (v xs') (xs' ∘ Fin.natAdd _)))
(h2 : ∀ (n) (R : L.Relations n) (x : Fin n → M), RelMap (fr n R) x = RelMap R x)
(hv : ∀ (n) (xs : Fin (k + n) → M) (x : M), @v (n + 1) (snoc xs x : Fin _ → M) = v xs) :
(φ.mapTermRel ft fr fun _ => castLE (add_assoc _ _ _).symm.le).Realize v' xs ↔
φ.Realize (v xs) (xs ∘ Fin.natAdd _) := by
induction φ with
| falsum => rfl
| equal => simp [mapTermRel, Realize, h1]
| rel => simp [mapTermRel, Realize, h1, h2]
| imp _ _ ih1 ih2 => simp [mapTermRel, Realize, ih1, ih2]
| all _ ih => simp [mapTermRel, Realize, ih, hv]
@[simp]
theorem realize_relabel {m n : ℕ} {φ : L.BoundedFormula α n} {g : α → β ⊕ (Fin m)} {v : β → M}
{xs : Fin (m + n) → M} :
(φ.relabel g).Realize v xs ↔
φ.Realize (Sum.elim v (xs ∘ Fin.castAdd n) ∘ g) (xs ∘ Fin.natAdd m) := by
apply realize_mapTermRel_add_castLe <;> simp
theorem realize_liftAt {n n' m : ℕ} {φ : L.BoundedFormula α n} {v : α → M} {xs : Fin (n + n') → M}
(hmn : m + n' ≤ n + 1) :
(φ.liftAt n' m).Realize v xs ↔
φ.Realize v (xs ∘ fun i => if ↑i < m then Fin.castAdd n' i else Fin.addNat i n') := by
rw [liftAt]
induction φ with
| falsum => simp [mapTermRel, Realize]
| equal => simp [mapTermRel, Realize, realize_rel, realize_liftAt, Sum.elim_comp_map]
| rel => simp [mapTermRel, Realize, realize_rel, realize_liftAt, Sum.elim_comp_map]
| imp _ _ ih1 ih2 => simp only [mapTermRel, Realize, ih1 hmn, ih2 hmn]
| @all k _ ih3 =>
have h : k + 1 + n' = k + n' + 1 := by rw [add_assoc, add_comm 1 n', ← add_assoc]
simp only [mapTermRel, Realize, realize_castLE_of_eq h, ih3 (hmn.trans k.succ.le_succ)]
refine forall_congr' fun x => iff_eq_eq.mpr (congr rfl (funext (Fin.lastCases ?_ fun i => ?_)))
· simp only [Function.comp_apply, val_last, snoc_last]
refine (congr rfl (Fin.ext ?_)).trans (snoc_last _ _)
split_ifs <;> dsimp; omega
· simp only [Function.comp_apply, Fin.snoc_castSucc]
refine (congr rfl (Fin.ext ?_)).trans (snoc_castSucc _ _ _)
simp only [coe_castSucc, coe_cast]
split_ifs <;> simp
theorem realize_liftAt_one {n m : ℕ} {φ : L.BoundedFormula α n} {v : α → M} {xs : Fin (n + 1) → M}
(hmn : m ≤ n) :
(φ.liftAt 1 m).Realize v xs ↔
φ.Realize v (xs ∘ fun i => if ↑i < m then castSucc i else i.succ) := by
simp [realize_liftAt (add_le_add_right hmn 1), castSucc]
@[simp]
theorem realize_liftAt_one_self {n : ℕ} {φ : L.BoundedFormula α n} {v : α → M}
{xs : Fin (n + 1) → M} : (φ.liftAt 1 n).Realize v xs ↔ φ.Realize v (xs ∘ castSucc) := by
rw [realize_liftAt_one (refl n), iff_eq_eq]
refine congr rfl (congr rfl (funext fun i => ?_))
rw [if_pos i.is_lt]
@[simp]
theorem realize_subst {φ : L.BoundedFormula α n} {tf : α → L.Term β} {v : β → M} {xs : Fin n → M} :
(φ.subst tf).Realize v xs ↔ φ.Realize (fun a => (tf a).realize v) xs :=
realize_mapTermRel_id
(fun n t x => by
rw [Term.realize_subst]
rcongr a
cases a
· simp only [Sum.elim_inl, Function.comp_apply, Term.realize_relabel, Sum.elim_comp_inl]
· rfl)
(by simp)
theorem realize_restrictFreeVar [DecidableEq α] {n : ℕ} {φ : L.BoundedFormula α n}
{f : φ.freeVarFinset → β} {v : β → M} {xs : Fin n → M}
(v' : α → M) (hv' : ∀ a, v (f a) = v' a) :
(φ.restrictFreeVar f).Realize v xs ↔ φ.Realize v' xs := by
induction φ with
| falsum => rfl
| equal =>
simp only [Realize, restrictFreeVar, freeVarFinset.eq_2]
rw [realize_restrictVarLeft v' (by simp [hv']), realize_restrictVarLeft v' (by simp [hv'])]
simp [Function.comp_apply]
| rel =>
simp only [Realize, freeVarFinset.eq_3, Finset.biUnion_val, restrictFreeVar]
congr!
rw [realize_restrictVarLeft v' (by simp [hv'])]
simp [Function.comp_apply]
| imp _ _ ih1 ih2 =>
simp only [Realize, restrictFreeVar, freeVarFinset.eq_4]
rw [ih1, ih2] <;> simp [hv']
| all _ ih3 =>
simp only [restrictFreeVar, Realize]
refine forall_congr' (fun _ => ?_)
rw [ih3]; simp [hv']
/-- A special case of `realize_restrictFreeVar`, included because we can add the `simp` attribute
to it -/
@[simp]
theorem realize_restrictFreeVar' [DecidableEq α] {n : ℕ} {φ : L.BoundedFormula α n} {s : Set α}
(h : ↑φ.freeVarFinset ⊆ s) {v : α → M} {xs : Fin n → M} :
(φ.restrictFreeVar (Set.inclusion h)).Realize (v ∘ (↑)) xs ↔ φ.Realize v xs :=
realize_restrictFreeVar _ (by simp)
theorem realize_constantsVarsEquiv [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M]
{n} {φ : L[[α]].BoundedFormula β n} {v : β → M} {xs : Fin n → M} :
(constantsVarsEquiv φ).Realize (Sum.elim (fun a => ↑(L.con a)) v) xs ↔ φ.Realize v xs := by
refine realize_mapTermRel_id (fun n t xs => realize_constantsVarsEquivLeft) fun n R xs => ?_
-- This used to be `rw`, but we need `erw` after https://github.com/leanprover/lean4/pull/2644
erw [← (lhomWithConstants L α).map_onRelation
(Equiv.sumEmpty (L.Relations n) ((constantsOn α).Relations n) R) xs]
rcongr
obtain - | R := R
· simp
· exact isEmptyElim R
@[simp]
theorem realize_relabelEquiv {g : α ≃ β} {k} {φ : L.BoundedFormula α k} {v : β → M}
{xs : Fin k → M} : (relabelEquiv g φ).Realize v xs ↔ φ.Realize (v ∘ g) xs := by
simp only [relabelEquiv, mapTermRelEquiv_apply, Equiv.coe_refl]
refine realize_mapTermRel_id (fun n t xs => ?_) fun _ _ _ => rfl
simp only [relabelEquiv_apply, Term.realize_relabel]
refine congr (congr rfl ?_) rfl
ext (i | i) <;> rfl
variable [Nonempty M]
theorem realize_all_liftAt_one_self {n : ℕ} {φ : L.BoundedFormula α n} {v : α → M}
{xs : Fin n → M} : (φ.liftAt 1 n).all.Realize v xs ↔ φ.Realize v xs := by
inhabit M
simp only [realize_all, realize_liftAt_one_self]
refine ⟨fun h => ?_, fun h a => ?_⟩
· refine (congr rfl (funext fun i => ?_)).mp (h default)
simp
· refine (congr rfl (funext fun i => ?_)).mp h
simp
end BoundedFormula
namespace LHom
open BoundedFormula
@[simp]
theorem realize_onBoundedFormula [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] {n : ℕ}
(ψ : L.BoundedFormula α n) {v : α → M} {xs : Fin n → M} :
(φ.onBoundedFormula ψ).Realize v xs ↔ ψ.Realize v xs := by
induction ψ with
| falsum => rfl
| equal => simp only [onBoundedFormula, realize_bdEqual, realize_onTerm]; rfl
| rel =>
simp only [onBoundedFormula, realize_rel, LHom.map_onRelation,
Function.comp_apply, realize_onTerm]
rfl
| imp _ _ ih1 ih2 => simp only [onBoundedFormula, ih1, ih2, realize_imp]
| all _ ih3 => simp only [onBoundedFormula, ih3, realize_all]
end LHom
namespace Formula
/-- A formula can be evaluated as true or false by giving values to each free variable. -/
nonrec def Realize (φ : L.Formula α) (v : α → M) : Prop :=
φ.Realize v default
variable {φ ψ : L.Formula α} {v : α → M}
@[simp]
theorem realize_not : φ.not.Realize v ↔ ¬φ.Realize v :=
Iff.rfl
@[simp]
theorem realize_bot : (⊥ : L.Formula α).Realize v ↔ False :=
Iff.rfl
@[simp]
theorem realize_top : (⊤ : L.Formula α).Realize v ↔ True :=
BoundedFormula.realize_top
@[simp]
theorem realize_inf : (φ ⊓ ψ).Realize v ↔ φ.Realize v ∧ ψ.Realize v :=
BoundedFormula.realize_inf
@[simp]
theorem realize_imp : (φ.imp ψ).Realize v ↔ φ.Realize v → ψ.Realize v :=
BoundedFormula.realize_imp
@[simp]
theorem realize_rel {k : ℕ} {R : L.Relations k} {ts : Fin k → L.Term α} :
(R.formula ts).Realize v ↔ RelMap R fun i => (ts i).realize v :=
BoundedFormula.realize_rel.trans (by simp)
@[simp]
theorem realize_rel₁ {R : L.Relations 1} {t : L.Term _} :
(R.formula₁ t).Realize v ↔ RelMap R ![t.realize v] := by
rw [Relations.formula₁, realize_rel, iff_eq_eq]
refine congr rfl (funext fun _ => ?_)
simp only [Matrix.cons_val_fin_one]
@[simp]
theorem realize_rel₂ {R : L.Relations 2} {t₁ t₂ : L.Term _} :
(R.formula₂ t₁ t₂).Realize v ↔ RelMap R ![t₁.realize v, t₂.realize v] := by
rw [Relations.formula₂, realize_rel, iff_eq_eq]
refine congr rfl (funext (Fin.cases ?_ ?_))
· simp only [Matrix.cons_val_zero]
· simp only [Matrix.cons_val_succ, Matrix.cons_val_fin_one, forall_const]
@[simp]
theorem realize_sup : (φ ⊔ ψ).Realize v ↔ φ.Realize v ∨ ψ.Realize v :=
BoundedFormula.realize_sup
@[simp]
theorem realize_iff : (φ.iff ψ).Realize v ↔ (φ.Realize v ↔ ψ.Realize v) :=
BoundedFormula.realize_iff
@[simp]
theorem realize_relabel {φ : L.Formula α} {g : α → β} {v : β → M} :
(φ.relabel g).Realize v ↔ φ.Realize (v ∘ g) := by
rw [Realize, Realize, relabel, BoundedFormula.realize_relabel, iff_eq_eq, Fin.castAdd_zero]
exact congr rfl (funext finZeroElim)
theorem realize_relabel_sumInr (φ : L.Formula (Fin n)) {v : Empty → M} {x : Fin n → M} :
(BoundedFormula.relabel Sum.inr φ).Realize v x ↔ φ.Realize x := by
rw [BoundedFormula.realize_relabel, Formula.Realize, Sum.elim_comp_inr, Fin.castAdd_zero,
cast_refl, Function.comp_id,
Subsingleton.elim (x ∘ (natAdd n : Fin 0 → Fin n)) default]
@[deprecated (since := "2025-02-21")] alias realize_relabel_sum_inr := realize_relabel_sumInr
@[simp]
theorem realize_equal {t₁ t₂ : L.Term α} {x : α → M} :
(t₁.equal t₂).Realize x ↔ t₁.realize x = t₂.realize x := by simp [Term.equal, Realize]
@[simp]
theorem realize_graph {f : L.Functions n} {x : Fin n → M} {y : M} :
(Formula.graph f).Realize (Fin.cons y x : _ → M) ↔ funMap f x = y := by
simp only [Formula.graph, Term.realize, realize_equal, Fin.cons_zero, Fin.cons_succ]
rw [eq_comm]
theorem boundedFormula_realize_eq_realize (φ : L.Formula α) (x : α → M) (y : Fin 0 → M) :
BoundedFormula.Realize φ x y ↔ φ.Realize x := by
rw [Formula.Realize, iff_iff_eq]
congr
ext i; exact Fin.elim0 i
end Formula
@[simp]
theorem LHom.realize_onFormula [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] (ψ : L.Formula α)
{v : α → M} : (φ.onFormula ψ).Realize v ↔ ψ.Realize v :=
φ.realize_onBoundedFormula ψ
@[simp]
theorem LHom.setOf_realize_onFormula [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M]
(ψ : L.Formula α) : (setOf (φ.onFormula ψ).Realize : Set (α → M)) = setOf ψ.Realize := by
ext
simp
variable (M)
/-- A sentence can be evaluated as true or false in a structure. -/
nonrec def Sentence.Realize (φ : L.Sentence) : Prop :=
φ.Realize (default : _ → M)
-- input using \|= or \vDash, but not using \models
@[inherit_doc Sentence.Realize]
infixl:51 " ⊨ " => Sentence.Realize
@[simp]
theorem Sentence.realize_not {φ : L.Sentence} : M ⊨ φ.not ↔ ¬M ⊨ φ :=
Iff.rfl
namespace Formula
@[simp]
theorem realize_equivSentence_symm_con [L[[α]].Structure M]
[(L.lhomWithConstants α).IsExpansionOn M] (φ : L[[α]].Sentence) :
((equivSentence.symm φ).Realize fun a => (L.con a : M)) ↔ φ.Realize M := by
simp only [equivSentence, _root_.Equiv.symm_symm, Equiv.coe_trans, Realize,
BoundedFormula.realize_relabelEquiv, Function.comp]
refine _root_.trans ?_ BoundedFormula.realize_constantsVarsEquiv
rw [iff_iff_eq]
congr with (_ | a)
· simp
· cases a
@[simp]
theorem realize_equivSentence [L[[α]].Structure M] [(L.lhomWithConstants α).IsExpansionOn M]
(φ : L.Formula α) : (equivSentence φ).Realize M ↔ φ.Realize fun a => (L.con a : M) := by
rw [← realize_equivSentence_symm_con M (equivSentence φ), _root_.Equiv.symm_apply_apply]
theorem realize_equivSentence_symm (φ : L[[α]].Sentence) (v : α → M) :
(equivSentence.symm φ).Realize v ↔
@Sentence.Realize _ M (@Language.withConstantsStructure L M _ α (constantsOn.structure v))
φ :=
letI := constantsOn.structure v
realize_equivSentence_symm_con M φ
end Formula
@[simp]
theorem LHom.realize_onSentence [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M]
(ψ : L.Sentence) : M ⊨ φ.onSentence ψ ↔ M ⊨ ψ :=
φ.realize_onFormula ψ
variable (L)
/-- The complete theory of a structure `M` is the set of all sentences `M` satisfies. -/
def completeTheory : L.Theory :=
{ φ | M ⊨ φ }
variable (N)
/-- Two structures are elementarily equivalent when they satisfy the same sentences. -/
def ElementarilyEquivalent : Prop :=
L.completeTheory M = L.completeTheory N
@[inherit_doc FirstOrder.Language.ElementarilyEquivalent]
scoped[FirstOrder]
notation:25 A " ≅[" L "] " B:50 => FirstOrder.Language.ElementarilyEquivalent L A B
variable {L} {M} {N}
@[simp]
theorem mem_completeTheory {φ : Sentence L} : φ ∈ L.completeTheory M ↔ M ⊨ φ :=
Iff.rfl
theorem elementarilyEquivalent_iff : M ≅[L] N ↔ ∀ φ : L.Sentence, M ⊨ φ ↔ N ⊨ φ := by
simp only [ElementarilyEquivalent, Set.ext_iff, completeTheory, Set.mem_setOf_eq]
variable (M)
/-- A model of a theory is a structure in which every sentence is realized as true. -/
class Theory.Model (T : L.Theory) : Prop where
realize_of_mem : ∀ φ ∈ T, M ⊨ φ
-- input using \|= or \vDash, but not using \models
@[inherit_doc Theory.Model]
infixl:51 " ⊨ " => Theory.Model
variable {M} (T : L.Theory)
@[simp default - 10]
theorem Theory.model_iff : M ⊨ T ↔ ∀ φ ∈ T, M ⊨ φ :=
⟨fun h => h.realize_of_mem, fun h => ⟨h⟩⟩
theorem Theory.realize_sentence_of_mem [M ⊨ T] {φ : L.Sentence} (h : φ ∈ T) : M ⊨ φ :=
Theory.Model.realize_of_mem φ h
@[simp]
theorem LHom.onTheory_model [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] (T : L.Theory) :
M ⊨ φ.onTheory T ↔ M ⊨ T := by simp [Theory.model_iff, LHom.onTheory]
variable {T}
instance model_empty : M ⊨ (∅ : L.Theory) :=
⟨fun φ hφ => (Set.not_mem_empty φ hφ).elim⟩
namespace Theory
theorem Model.mono {T' : L.Theory} (_h : M ⊨ T') (hs : T ⊆ T') : M ⊨ T :=
⟨fun _φ hφ => T'.realize_sentence_of_mem (hs hφ)⟩
theorem Model.union {T' : L.Theory} (h : M ⊨ T) (h' : M ⊨ T') : M ⊨ T ∪ T' := by
simp only [model_iff, Set.mem_union] at *
exact fun φ hφ => hφ.elim (h _) (h' _)
@[simp]
theorem model_union_iff {T' : L.Theory} : M ⊨ T ∪ T' ↔ M ⊨ T ∧ M ⊨ T' :=
⟨fun h => ⟨h.mono Set.subset_union_left, h.mono Set.subset_union_right⟩, fun h =>
h.1.union h.2⟩
@[simp]
theorem model_singleton_iff {φ : L.Sentence} : M ⊨ ({φ} : L.Theory) ↔ M ⊨ φ := by simp
theorem model_insert_iff {φ : L.Sentence} : M ⊨ insert φ T ↔ M ⊨ φ ∧ M ⊨ T := by
rw [Set.insert_eq, model_union_iff, model_singleton_iff]
theorem model_iff_subset_completeTheory : M ⊨ T ↔ T ⊆ L.completeTheory M :=
T.model_iff
theorem completeTheory.subset [MT : M ⊨ T] : T ⊆ L.completeTheory M :=
model_iff_subset_completeTheory.1 MT
end Theory
instance model_completeTheory : M ⊨ L.completeTheory M :=
Theory.model_iff_subset_completeTheory.2 (subset_refl _)
variable (M N)
theorem realize_iff_of_model_completeTheory [N ⊨ L.completeTheory M] (φ : L.Sentence) :
N ⊨ φ ↔ M ⊨ φ := by
refine ⟨fun h => ?_, (L.completeTheory M).realize_sentence_of_mem⟩
contrapose! h
rw [← Sentence.realize_not] at *
exact (L.completeTheory M).realize_sentence_of_mem (mem_completeTheory.2 h)
variable {M N}
namespace BoundedFormula
@[simp]
theorem realize_alls {φ : L.BoundedFormula α n} {v : α → M} :
φ.alls.Realize v ↔ ∀ xs : Fin n → M, φ.Realize v xs := by
induction' n with n ih
· exact Unique.forall_iff.symm
· simp only [alls, ih, Realize]
exact ⟨fun h xs => Fin.snoc_init_self xs ▸ h _ _, fun h xs x => h (Fin.snoc xs x)⟩
@[simp]
theorem realize_exs {φ : L.BoundedFormula α n} {v : α → M} :
φ.exs.Realize v ↔ ∃ xs : Fin n → M, φ.Realize v xs := by
induction' n with n ih
· exact Unique.exists_iff.symm
· simp only [BoundedFormula.exs, ih, realize_ex]
constructor
· rintro ⟨xs, x, h⟩
exact ⟨_, h⟩
· rintro ⟨xs, h⟩
rw [← Fin.snoc_init_self xs] at h
exact ⟨_, _, h⟩
@[simp]
theorem _root_.FirstOrder.Language.Formula.realize_iAlls
[Finite β] {φ : L.Formula (α ⊕ β)} {v : α → M} : (φ.iAlls β).Realize v ↔
∀ (i : β → M), φ.Realize (fun a => Sum.elim v i a) := by
let e := Classical.choice (Classical.choose_spec (Finite.exists_equiv_fin β))
rw [Formula.iAlls]
simp only [Nat.add_zero, realize_alls, realize_relabel, Function.comp_def,
castAdd_zero, finCongr_refl, OrderIso.refl_apply, Sum.elim_map, id_eq]
refine Equiv.forall_congr ?_ ?_
· exact ⟨fun v => v ∘ e, fun v => v ∘ e.symm,
fun _ => by simp [Function.comp_def],
fun _ => by simp [Function.comp_def]⟩
· intro x
rw [Formula.Realize, iff_iff_eq]
congr
funext i
exact i.elim0
@[simp]
theorem realize_iAlls [Finite β] {φ : L.Formula (α ⊕ β)} {v : α → M} {v' : Fin 0 → M} :
BoundedFormula.Realize (φ.iAlls β) v v' ↔
∀ (i : β → M), φ.Realize (fun a => Sum.elim v i a) := by
rw [← Formula.realize_iAlls, iff_iff_eq]; congr; simp [eq_iff_true_of_subsingleton]
@[simp]
theorem _root_.FirstOrder.Language.Formula.realize_iExs
[Finite γ] {φ : L.Formula (α ⊕ γ)} {v : α → M} : (φ.iExs γ).Realize v ↔
∃ (i : γ → M), φ.Realize (Sum.elim v i) := by
let e := Classical.choice (Classical.choose_spec (Finite.exists_equiv_fin γ))
rw [Formula.iExs]
simp only [Nat.add_zero, realize_exs, realize_relabel, Function.comp_def,
castAdd_zero, finCongr_refl, OrderIso.refl_apply, Sum.elim_map, id_eq]
refine Equiv.exists_congr ?_ ?_
· exact ⟨fun v => v ∘ e, fun v => v ∘ e.symm,
fun _ => by simp [Function.comp_def],
fun _ => by simp [Function.comp_def]⟩
· intro x
rw [Formula.Realize, iff_iff_eq]
congr
funext i
exact i.elim0
@[simp]
theorem realize_iExs [Finite γ] {φ : L.Formula (α ⊕ γ)} {v : α → M} {v' : Fin 0 → M} :
BoundedFormula.Realize (φ.iExs γ) v v' ↔
∃ (i : γ → M), φ.Realize (Sum.elim v i) := by
rw [← Formula.realize_iExs, iff_iff_eq]; congr; simp [eq_iff_true_of_subsingleton]
@[simp]
theorem realize_toFormula (φ : L.BoundedFormula α n) (v : α ⊕ (Fin n) → M) :
φ.toFormula.Realize v ↔ φ.Realize (v ∘ Sum.inl) (v ∘ Sum.inr) := by
induction φ with
| falsum => rfl
| equal => simp [BoundedFormula.Realize]
| rel => simp [BoundedFormula.Realize]
| imp _ _ ih1 ih2 =>
rw [toFormula, Formula.Realize, realize_imp, ← Formula.Realize, ih1, ← Formula.Realize, ih2,
realize_imp]
| all _ ih3 =>
rw [toFormula, Formula.Realize, realize_all, realize_all]
refine forall_congr' fun a => ?_
have h := ih3 (Sum.elim (v ∘ Sum.inl) (snoc (v ∘ Sum.inr) a))
simp only [Sum.elim_comp_inl, Sum.elim_comp_inr] at h
rw [← h, realize_relabel, Formula.Realize, iff_iff_eq]
simp only [Function.comp_def]
congr with x
· rcases x with _ | x
· simp
· refine Fin.lastCases ?_ ?_ x
· rw [Sum.elim_inr, Sum.elim_inr,
finSumFinEquiv_symm_last, Sum.map_inr, Sum.elim_inr]
simp [Fin.snoc]
· simp only [castSucc, Function.comp_apply, Sum.elim_inr,
finSumFinEquiv_symm_apply_castAdd, Sum.map_inl, Sum.elim_inl]
rw [← castSucc]
simp
· exact Fin.elim0 x
@[simp]
theorem realize_iSup [Finite β] {f : β → L.BoundedFormula α n}
{v : α → M} {v' : Fin n → M} :
(iSup f).Realize v v' ↔ ∃ b, (f b).Realize v v' := by
simp only [iSup, realize_foldr_sup, List.mem_map, Finset.mem_toList, Finset.mem_univ, true_and,
exists_exists_eq_and]
@[simp]
theorem realize_iInf [Finite β] {f : β → L.BoundedFormula α n}
{v : α → M} {v' : Fin n → M} :
(iInf f).Realize v v' ↔ ∀ b, (f b).Realize v v' := by
simp only [iInf, realize_foldr_inf, List.mem_map, Finset.mem_toList, Finset.mem_univ, true_and,
forall_exists_index, forall_apply_eq_imp_iff]
@[simp]
theorem _root_.FirstOrder.Language.Formula.realize_iExsUnique [Finite γ]
{φ : L.Formula (α ⊕ γ)} {v : α → M} : (φ.iExsUnique γ).Realize v ↔
∃! (i : γ → M), φ.Realize (Sum.elim v i) := by
rw [Formula.iExsUnique, ExistsUnique]
simp only [Formula.realize_iExs, Formula.realize_inf, Formula.realize_iAlls, Formula.realize_imp,
Formula.realize_relabel]
simp only [Formula.Realize, Function.comp_def, Term.equal, Term.relabel, realize_iInf,
realize_bdEqual, Term.realize_var, Sum.elim_inl, Sum.elim_inr, funext_iff]
refine exists_congr (fun i => and_congr_right' (forall_congr' (fun y => ?_)))
rw [iff_iff_eq]; congr with x
cases x <;> simp
@[simp]
theorem realize_iExsUnique [Finite γ] {φ : L.Formula (α ⊕ γ)} {v : α → M} {v' : Fin 0 → M} :
BoundedFormula.Realize (φ.iExsUnique γ) v v' ↔
∃! (i : γ → M), φ.Realize (Sum.elim v i) := by
rw [← Formula.realize_iExsUnique, iff_iff_eq]; congr; simp [eq_iff_true_of_subsingleton]
end BoundedFormula
namespace StrongHomClass
variable {F : Type*} [EquivLike F M N] [StrongHomClass L F M N] (g : F)
@[simp]
theorem realize_boundedFormula (φ : L.BoundedFormula α n) {v : α → M}
{xs : Fin n → M} : φ.Realize (g ∘ v) (g ∘ xs) ↔ φ.Realize v xs := by
induction φ with
| falsum => rfl
| equal =>
simp only [BoundedFormula.Realize, ← Sum.comp_elim, HomClass.realize_term,
EmbeddingLike.apply_eq_iff_eq g]
| rel =>
simp only [BoundedFormula.Realize, ← Sum.comp_elim, HomClass.realize_term]
exact StrongHomClass.map_rel g _ _
| imp _ _ ih1 ih2 => rw [BoundedFormula.Realize, ih1, ih2, BoundedFormula.Realize]
| all _ ih3 =>
rw [BoundedFormula.Realize, BoundedFormula.Realize]
constructor
· intro h a
have h' := h (g a)
rw [← Fin.comp_snoc, ih3] at h'
exact h'
· intro h a
have h' := h (EquivLike.inv g a)
rw [← ih3, Fin.comp_snoc, EquivLike.apply_inv_apply g] at h'
exact h'
@[simp]
theorem realize_formula (φ : L.Formula α) {v : α → M} :
φ.Realize (g ∘ v) ↔ φ.Realize v := by
rw [Formula.Realize, Formula.Realize, ← realize_boundedFormula g φ, iff_eq_eq,
Unique.eq_default (g ∘ default)]
include g
theorem realize_sentence (φ : L.Sentence) : M ⊨ φ ↔ N ⊨ φ := by
rw [Sentence.Realize, Sentence.Realize, ← realize_formula g,
Unique.eq_default (g ∘ default)]
theorem theory_model [M ⊨ T] : N ⊨ T :=
⟨fun φ hφ => (realize_sentence g φ).1 (Theory.realize_sentence_of_mem T hφ)⟩
theorem elementarilyEquivalent : M ≅[L] N :=
elementarilyEquivalent_iff.2 (realize_sentence g)
end StrongHomClass
namespace Relations
open BoundedFormula
variable {r : L.Relations 2}
@[simp]
theorem realize_reflexive : M ⊨ r.reflexive ↔ Reflexive fun x y : M => RelMap r ![x, y] :=
forall_congr' fun _ => realize_rel₂
@[simp]
theorem realize_irreflexive : M ⊨ r.irreflexive ↔ Irreflexive fun x y : M => RelMap r ![x, y] :=
forall_congr' fun _ => not_congr realize_rel₂
@[simp]
theorem realize_symmetric : M ⊨ r.symmetric ↔ Symmetric fun x y : M => RelMap r ![x, y] :=
forall_congr' fun _ => forall_congr' fun _ => imp_congr realize_rel₂ realize_rel₂
@[simp]
theorem realize_antisymmetric :
M ⊨ r.antisymmetric ↔ AntiSymmetric fun x y : M => RelMap r ![x, y] :=
forall_congr' fun _ =>
forall_congr' fun _ => imp_congr realize_rel₂ (imp_congr realize_rel₂ Iff.rfl)
@[simp]
theorem realize_transitive : M ⊨ r.transitive ↔ Transitive fun x y : M => RelMap r ![x, y] :=
forall_congr' fun _ =>
forall_congr' fun _ =>
forall_congr' fun _ => imp_congr realize_rel₂ (imp_congr realize_rel₂ realize_rel₂)
@[simp]
theorem realize_total : M ⊨ r.total ↔ Total fun x y : M => RelMap r ![x, y] :=
forall_congr' fun _ =>
forall_congr' fun _ => realize_sup.trans (or_congr realize_rel₂ realize_rel₂)
end Relations
section Cardinality
variable (L)
@[simp]
theorem Sentence.realize_cardGe (n) : M ⊨ Sentence.cardGe L n ↔ ↑n ≤ #M := by
rw [← lift_mk_fin, ← lift_le.{0}, lift_lift, lift_mk_le, Sentence.cardGe, Sentence.Realize,
BoundedFormula.realize_exs]
simp_rw [BoundedFormula.realize_foldr_inf]
simp only [Function.comp_apply, List.mem_map, Prod.exists, Ne, List.mem_product,
List.mem_finRange, forall_exists_index, and_imp, List.mem_filter, true_and]
refine ⟨?_, fun xs => ⟨xs.some, ?_⟩⟩
· rintro ⟨xs, h⟩
refine ⟨⟨xs, fun i j ij => ?_⟩⟩
contrapose! ij
have hij := h _ i j (by simpa using ij) rfl
simp only [BoundedFormula.realize_not, Term.realize, BoundedFormula.realize_bdEqual,
Sum.elim_inr] at hij
exact hij
· rintro _ i j ij rfl
simpa using ij
@[simp]
theorem model_infiniteTheory_iff : M ⊨ L.infiniteTheory ↔ Infinite M := by
simp [infiniteTheory, infinite_iff, aleph0_le]
instance model_infiniteTheory [h : Infinite M] : M ⊨ L.infiniteTheory :=
L.model_infiniteTheory_iff.2 h
@[simp]
theorem model_nonemptyTheory_iff : M ⊨ L.nonemptyTheory ↔ Nonempty M := by
simp only [nonemptyTheory, Theory.model_iff, Set.mem_singleton_iff, forall_eq,
Sentence.realize_cardGe, Nat.cast_one, one_le_iff_ne_zero, mk_ne_zero_iff]
instance model_nonempty [h : Nonempty M] : M ⊨ L.nonemptyTheory :=
L.model_nonemptyTheory_iff.2 h
theorem model_distinctConstantsTheory {M : Type w} [L[[α]].Structure M] (s : Set α) :
M ⊨ L.distinctConstantsTheory s ↔ Set.InjOn (fun i : α => (L.con i : M)) s := by
simp only [distinctConstantsTheory, Theory.model_iff, Set.mem_image, Set.mem_inter,
Set.mem_prod, Set.mem_compl, Prod.exists, forall_exists_index, and_imp]
refine ⟨fun h a as b bs ab => ?_, ?_⟩
| · contrapose! ab
have h' := h _ a b ⟨⟨as, bs⟩, ab⟩ rfl
simp only [Sentence.Realize, Formula.realize_not, Formula.realize_equal,
Term.realize_constants] at h'
exact h'
| Mathlib/ModelTheory/Semantics.lean | 1,000 | 1,004 |
/-
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 Mathlib.Analysis.SpecialFunctions.Complex.Circle
import Mathlib.Geometry.Euclidean.Angle.Oriented.Basic
/-!
# Rotations by oriented angles.
This file defines rotations by oriented angles in real inner product spaces.
## Main definitions
* `Orientation.rotation` is the rotation by an oriented angle with respect to an orientation.
-/
noncomputable section
open Module Complex
open scoped Real RealInnerProductSpace ComplexConjugate
namespace Orientation
attribute [local instance] Complex.finrank_real_complex_fact
variable {V V' : Type*}
variable [NormedAddCommGroup V] [NormedAddCommGroup V']
variable [InnerProductSpace ℝ V] [InnerProductSpace ℝ V']
variable [Fact (finrank ℝ V = 2)] [Fact (finrank ℝ V' = 2)] (o : Orientation ℝ V (Fin 2))
local notation "J" => o.rightAngleRotation
/-- Auxiliary construction to build a rotation by the oriented angle `θ`. -/
def rotationAux (θ : Real.Angle) : V →ₗᵢ[ℝ] V :=
LinearMap.isometryOfInner
(Real.Angle.cos θ • LinearMap.id +
Real.Angle.sin θ • (LinearIsometryEquiv.toLinearEquiv J).toLinearMap)
(by
intro x y
simp only [RCLike.conj_to_real, id, LinearMap.smul_apply, LinearMap.add_apply,
LinearMap.id_coe, LinearEquiv.coe_coe, LinearIsometryEquiv.coe_toLinearEquiv,
Orientation.areaForm_rightAngleRotation_left, Orientation.inner_rightAngleRotation_left,
Orientation.inner_rightAngleRotation_right, inner_add_left, inner_smul_left,
inner_add_right, inner_smul_right]
linear_combination inner (𝕜 := ℝ) x y * θ.cos_sq_add_sin_sq)
@[simp]
theorem rotationAux_apply (θ : Real.Angle) (x : V) :
o.rotationAux θ x = Real.Angle.cos θ • x + Real.Angle.sin θ • J x :=
rfl
/-- A rotation by the oriented angle `θ`. -/
def rotation (θ : Real.Angle) : V ≃ₗᵢ[ℝ] V :=
LinearIsometryEquiv.ofLinearIsometry (o.rotationAux θ)
(Real.Angle.cos θ • LinearMap.id -
Real.Angle.sin θ • (LinearIsometryEquiv.toLinearEquiv J).toLinearMap)
(by
ext x
convert congr_arg (fun t : ℝ => t • x) θ.cos_sq_add_sin_sq using 1
· simp only [o.rightAngleRotation_rightAngleRotation, o.rotationAux_apply,
Function.comp_apply, id, LinearEquiv.coe_coe, LinearIsometry.coe_toLinearMap,
LinearIsometryEquiv.coe_toLinearEquiv, map_smul, map_sub, LinearMap.coe_comp,
LinearMap.id_coe, LinearMap.smul_apply, LinearMap.sub_apply]
module
· simp)
(by
ext x
convert congr_arg (fun t : ℝ => t • x) θ.cos_sq_add_sin_sq using 1
· simp only [o.rightAngleRotation_rightAngleRotation, o.rotationAux_apply,
Function.comp_apply, id, LinearEquiv.coe_coe, LinearIsometry.coe_toLinearMap,
LinearIsometryEquiv.coe_toLinearEquiv, map_add, map_smul, LinearMap.coe_comp,
LinearMap.id_coe, LinearMap.smul_apply, LinearMap.sub_apply]
module
· simp)
theorem rotation_apply (θ : Real.Angle) (x : V) :
o.rotation θ x = Real.Angle.cos θ • x + Real.Angle.sin θ • J x :=
rfl
theorem rotation_symm_apply (θ : Real.Angle) (x : V) :
(o.rotation θ).symm x = Real.Angle.cos θ • x - Real.Angle.sin θ • J x :=
rfl
theorem rotation_eq_matrix_toLin (θ : Real.Angle) {x : V} (hx : x ≠ 0) :
(o.rotation θ).toLinearMap =
Matrix.toLin (o.basisRightAngleRotation x hx) (o.basisRightAngleRotation x hx)
!![θ.cos, -θ.sin; θ.sin, θ.cos] := by
apply (o.basisRightAngleRotation x hx).ext
intro i
fin_cases i
· rw [Matrix.toLin_self]
simp [rotation_apply, Fin.sum_univ_succ]
· rw [Matrix.toLin_self]
simp [rotation_apply, Fin.sum_univ_succ, add_comm]
/-- The determinant of `rotation` (as a linear map) is equal to `1`. -/
@[simp]
theorem det_rotation (θ : Real.Angle) : LinearMap.det (o.rotation θ).toLinearMap = 1 := by
haveI : Nontrivial V := nontrivial_of_finrank_eq_succ (@Fact.out (finrank ℝ V = 2) _)
obtain ⟨x, hx⟩ : ∃ x, x ≠ (0 : V) := exists_ne (0 : V)
rw [o.rotation_eq_matrix_toLin θ hx]
simpa [sq] using θ.cos_sq_add_sin_sq
/-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/
@[simp]
theorem linearEquiv_det_rotation (θ : Real.Angle) :
LinearEquiv.det (o.rotation θ).toLinearEquiv = 1 :=
Units.ext <| by
| -- Porting note: Lean can't see through `LinearEquiv.coe_det` and needed the rewrite
-- in mathlib3 this was just `units.ext <| o.det_rotation θ`
simpa only [LinearEquiv.coe_det, Units.val_one] using o.det_rotation θ
/-- The inverse of `rotation` is rotation by the negation of the angle. -/
@[simp]
| Mathlib/Geometry/Euclidean/Angle/Oriented/Rotation.lean | 114 | 119 |
/-
Copyright (c) 2020 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import Mathlib.Topology.Path
/-!
# Path connectedness
Continuing from `Mathlib.Topology.Path`, this file defines path components and path-connected
spaces.
## Main definitions
In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space.
* `Joined (x y : X)` means there is a path between `x` and `y`.
* `Joined.somePath (h : Joined x y)` selects some path between two points `x` and `y`.
* `pathComponent (x : X)` is the set of points joined to `x`.
* `PathConnectedSpace X` is a predicate class asserting that `X` is non-empty and every two
points of `X` are joined.
Then there are corresponding relative notions for `F : Set X`.
* `JoinedIn F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`.
* `JoinedIn.somePath (h : JoinedIn F x y)` selects a path from `x` to `y` inside `F`.
* `pathComponentIn F (x : X)` is the set of points joined to `x` in `F`.
* `IsPathConnected F` asserts that `F` is non-empty and every two
points of `F` are joined in `F`.
## Main theorems
* `Joined` is an equivalence relation, while `JoinedIn F` is at least symmetric and transitive.
One can link the absolute and relative version in two directions, using `(univ : Set X)` or the
subtype `↥F`.
* `pathConnectedSpace_iff_univ : PathConnectedSpace X ↔ IsPathConnected (univ : Set X)`
* `isPathConnected_iff_pathConnectedSpace : IsPathConnected F ↔ PathConnectedSpace ↥F`
Furthermore, it is shown that continuous images and quotients of path-connected sets/spaces are
path-connected, and that every path-connected set/space is also connected.
-/
noncomputable section
open Topology Filter unitInterval Set Function
variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {x y z : X} {ι : Type*}
/-! ### Being joined by a path -/
/-- The relation "being joined by a path". This is an equivalence relation. -/
def Joined (x y : X) : Prop :=
Nonempty (Path x y)
@[refl]
theorem Joined.refl (x : X) : Joined x x :=
⟨Path.refl x⟩
/-- When two points are joined, choose some path from `x` to `y`. -/
def Joined.somePath (h : Joined x y) : Path x y :=
Nonempty.some h
@[symm]
theorem Joined.symm {x y : X} (h : Joined x y) : Joined y x :=
⟨h.somePath.symm⟩
@[trans]
theorem Joined.trans {x y z : X} (hxy : Joined x y) (hyz : Joined y z) : Joined x z :=
⟨hxy.somePath.trans hyz.somePath⟩
variable (X)
/-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/
def pathSetoid : Setoid X where
r := Joined
iseqv := Equivalence.mk Joined.refl Joined.symm Joined.trans
/-- The quotient type of points of a topological space modulo being joined by a continuous path. -/
def ZerothHomotopy :=
Quotient (pathSetoid X)
instance ZerothHomotopy.inhabited : Inhabited (ZerothHomotopy ℝ) :=
⟨@Quotient.mk' ℝ (pathSetoid ℝ) 0⟩
variable {X}
/-! ### Being joined by a path inside a set -/
/-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not
reflexive for points that do not belong to `F`. -/
def JoinedIn (F : Set X) (x y : X) : Prop :=
∃ γ : Path x y, ∀ t, γ t ∈ F
variable {F : Set X}
theorem JoinedIn.mem (h : JoinedIn F x y) : x ∈ F ∧ y ∈ F := by
rcases h with ⟨γ, γ_in⟩
have : γ 0 ∈ F ∧ γ 1 ∈ F := by constructor <;> apply γ_in
simpa using this
theorem JoinedIn.source_mem (h : JoinedIn F x y) : x ∈ F :=
h.mem.1
theorem JoinedIn.target_mem (h : JoinedIn F x y) : y ∈ F :=
h.mem.2
/-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/
def JoinedIn.somePath (h : JoinedIn F x y) : Path x y :=
Classical.choose h
theorem JoinedIn.somePath_mem (h : JoinedIn F x y) (t : I) : h.somePath t ∈ F :=
Classical.choose_spec h t
/-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/
theorem JoinedIn.joined_subtype (h : JoinedIn F x y) :
Joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) :=
⟨{ toFun := fun t => ⟨h.somePath t, h.somePath_mem t⟩
continuous_toFun := by fun_prop
source' := by simp
target' := by simp }⟩
theorem JoinedIn.ofLine {f : ℝ → X} (hf : ContinuousOn f I) (h₀ : f 0 = x) (h₁ : f 1 = y)
(hF : f '' I ⊆ F) : JoinedIn F x y :=
⟨Path.ofLine hf h₀ h₁, fun t => hF <| Path.ofLine_mem hf h₀ h₁ t⟩
theorem JoinedIn.joined (h : JoinedIn F x y) : Joined x y :=
⟨h.somePath⟩
theorem joinedIn_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) :
JoinedIn F x y ↔ Joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) :=
⟨fun h => h.joined_subtype, fun h => ⟨h.somePath.map continuous_subtype_val, by simp⟩⟩
@[simp]
theorem joinedIn_univ : JoinedIn univ x y ↔ Joined x y := by
simp [JoinedIn, Joined, exists_true_iff_nonempty]
theorem JoinedIn.mono {U V : Set X} (h : JoinedIn U x y) (hUV : U ⊆ V) : JoinedIn V x y :=
⟨h.somePath, fun t => hUV (h.somePath_mem t)⟩
theorem JoinedIn.refl (h : x ∈ F) : JoinedIn F x x :=
⟨Path.refl x, fun _t => h⟩
@[symm]
theorem JoinedIn.symm (h : JoinedIn F x y) : JoinedIn F y x := by
obtain ⟨hx, hy⟩ := h.mem
simp_all only [joinedIn_iff_joined]
exact h.symm
theorem JoinedIn.trans (hxy : JoinedIn F x y) (hyz : JoinedIn F y z) : JoinedIn F x z := by
obtain ⟨hx, hy⟩ := hxy.mem
obtain ⟨hx, hy⟩ := hyz.mem
simp_all only [joinedIn_iff_joined]
exact hxy.trans hyz
theorem Specializes.joinedIn (h : x ⤳ y) (hx : x ∈ F) (hy : y ∈ F) : JoinedIn F x y := by
refine ⟨⟨⟨Set.piecewise {1} (const I y) (const I x), ?_⟩, by simp, by simp⟩, fun t ↦ ?_⟩
· exact isClosed_singleton.continuous_piecewise_of_specializes continuous_const continuous_const
fun _ ↦ h
· simp only [Path.coe_mk_mk, piecewise]
split_ifs <;> assumption
theorem Inseparable.joinedIn (h : Inseparable x y) (hx : x ∈ F) (hy : y ∈ F) : JoinedIn F x y :=
h.specializes.joinedIn hx hy
theorem JoinedIn.map_continuousOn (h : JoinedIn F x y) {f : X → Y} (hf : ContinuousOn f F) :
JoinedIn (f '' F) (f x) (f y) :=
let ⟨γ, hγ⟩ := h
⟨γ.map' <| hf.mono (range_subset_iff.mpr hγ), fun t ↦ mem_image_of_mem _ (hγ t)⟩
theorem JoinedIn.map (h : JoinedIn F x y) {f : X → Y} (hf : Continuous f) :
JoinedIn (f '' F) (f x) (f y) :=
h.map_continuousOn hf.continuousOn
theorem Topology.IsInducing.joinedIn_image {f : X → Y} (hf : IsInducing f) (hx : x ∈ F)
(hy : y ∈ F) : JoinedIn (f '' F) (f x) (f y) ↔ JoinedIn F x y := by
refine ⟨?_, (.map · hf.continuous)⟩
rintro ⟨γ, hγ⟩
choose γ' hγ'F hγ' using hγ
have h₀ : x ⤳ γ' 0 := by rw [← hf.specializes_iff, hγ', γ.source]
have h₁ : γ' 1 ⤳ y := by rw [← hf.specializes_iff, hγ', γ.target]
have h : JoinedIn F (γ' 0) (γ' 1) := by
refine ⟨⟨⟨γ', ?_⟩, rfl, rfl⟩, hγ'F⟩
simpa only [hf.continuous_iff, comp_def, hγ'] using map_continuous γ
exact (h₀.joinedIn hx (hγ'F _)).trans <| h.trans <| h₁.joinedIn (hγ'F _) hy
@[deprecated (since := "2024-10-28")] alias Inducing.joinedIn_image := IsInducing.joinedIn_image
/-! ### Path component -/
/-- The path component of `x` is the set of points that can be joined to `x`. -/
def pathComponent (x : X) :=
{ y | Joined x y }
theorem mem_pathComponent_iff : x ∈ pathComponent y ↔ Joined y x := .rfl
@[simp]
theorem mem_pathComponent_self (x : X) : x ∈ pathComponent x :=
Joined.refl x
@[simp]
theorem pathComponent.nonempty (x : X) : (pathComponent x).Nonempty :=
⟨x, mem_pathComponent_self x⟩
theorem mem_pathComponent_of_mem (h : x ∈ pathComponent y) : y ∈ pathComponent x :=
Joined.symm h
theorem pathComponent_symm : x ∈ pathComponent y ↔ y ∈ pathComponent x :=
⟨fun h => mem_pathComponent_of_mem h, fun h => mem_pathComponent_of_mem h⟩
theorem pathComponent_congr (h : x ∈ pathComponent y) : pathComponent x = pathComponent y := by
ext z
constructor
· intro h'
rw [pathComponent_symm]
exact (h.trans h').symm
· intro h'
rw [pathComponent_symm] at h' ⊢
exact h'.trans h
theorem pathComponent_subset_component (x : X) : pathComponent x ⊆ connectedComponent x :=
fun y h =>
(isConnected_range h.somePath.continuous).subset_connectedComponent ⟨0, by simp⟩ ⟨1, by simp⟩
/-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/
def pathComponentIn (x : X) (F : Set X) :=
{ y | JoinedIn F x y }
@[simp]
theorem pathComponentIn_univ (x : X) : pathComponentIn x univ = pathComponent x := by
simp [pathComponentIn, pathComponent, JoinedIn, Joined, exists_true_iff_nonempty]
theorem Joined.mem_pathComponent (hyz : Joined y z) (hxy : y ∈ pathComponent x) :
z ∈ pathComponent x :=
hxy.trans hyz
theorem mem_pathComponentIn_self (h : x ∈ F) : x ∈ pathComponentIn x F :=
JoinedIn.refl h
theorem pathComponentIn_subset : pathComponentIn x F ⊆ F :=
fun _ hy ↦ hy.target_mem
theorem pathComponentIn_nonempty_iff : (pathComponentIn x F).Nonempty ↔ x ∈ F :=
⟨fun ⟨_, ⟨γ, hγ⟩⟩ ↦ γ.source ▸ hγ 0, fun hx ↦ ⟨x, mem_pathComponentIn_self hx⟩⟩
theorem pathComponentIn_congr (h : x ∈ pathComponentIn y F) :
pathComponentIn x F = pathComponentIn y F := by
ext; exact ⟨h.trans, h.symm.trans⟩
@[gcongr]
theorem pathComponentIn_mono {G : Set X} (h : F ⊆ G) :
pathComponentIn x F ⊆ pathComponentIn x G :=
fun _ ⟨γ, hγ⟩ ↦ ⟨γ, fun t ↦ h (hγ t)⟩
/-! ### Path connected sets -/
/-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/
def IsPathConnected (F : Set X) : Prop :=
∃ x ∈ F, ∀ {y}, y ∈ F → JoinedIn F x y
theorem isPathConnected_iff_eq : IsPathConnected F ↔ ∃ x ∈ F, pathComponentIn x F = F := by
constructor <;> rintro ⟨x, x_in, h⟩ <;> use x, x_in
· ext y
exact ⟨fun hy => hy.mem.2, h⟩
· intro y y_in
rwa [← h] at y_in
theorem IsPathConnected.joinedIn (h : IsPathConnected F) :
∀ᵉ (x ∈ F) (y ∈ F), JoinedIn F x y := fun _x x_in _y y_in =>
let ⟨_b, _b_in, hb⟩ := h
(hb x_in).symm.trans (hb y_in)
theorem isPathConnected_iff :
IsPathConnected F ↔ F.Nonempty ∧ ∀ᵉ (x ∈ F) (y ∈ F), JoinedIn F x y :=
⟨fun h =>
⟨let ⟨b, b_in, _hb⟩ := h; ⟨b, b_in⟩, h.joinedIn⟩,
fun ⟨⟨b, b_in⟩, h⟩ => ⟨b, b_in, fun x_in => h _ b_in _ x_in⟩⟩
/-- If `f` is continuous on `F` and `F` is path-connected, so is `f(F)`. -/
theorem IsPathConnected.image' (hF : IsPathConnected F)
{f : X → Y} (hf : ContinuousOn f F) : IsPathConnected (f '' F) := by
rcases hF with ⟨x, x_in, hx⟩
use f x, mem_image_of_mem f x_in
rintro _ ⟨y, y_in, rfl⟩
refine ⟨(hx y_in).somePath.map' ?_, fun t ↦ ⟨_, (hx y_in).somePath_mem t, rfl⟩⟩
exact hf.mono (range_subset_iff.2 (hx y_in).somePath_mem)
/-- If `f` is continuous and `F` is path-connected, so is `f(F)`. -/
theorem IsPathConnected.image (hF : IsPathConnected F) {f : X → Y} (hf : Continuous f) :
IsPathConnected (f '' F) :=
hF.image' hf.continuousOn
/-- If `f : X → Y` is an inducing map, `f(F)` is path-connected iff `F` is. -/
nonrec theorem Topology.IsInducing.isPathConnected_iff {f : X → Y} (hf : IsInducing f) :
IsPathConnected F ↔ IsPathConnected (f '' F) := by
simp only [IsPathConnected, forall_mem_image, exists_mem_image]
refine exists_congr fun x ↦ and_congr_right fun hx ↦ forall₂_congr fun y hy ↦ ?_
rw [hf.joinedIn_image hx hy]
@[deprecated (since := "2024-10-28")]
alias Inducing.isPathConnected_iff := IsInducing.isPathConnected_iff
/-- If `h : X → Y` is a homeomorphism, `h(s)` is path-connected iff `s` is. -/
@[simp]
theorem Homeomorph.isPathConnected_image {s : Set X} (h : X ≃ₜ Y) :
IsPathConnected (h '' s) ↔ IsPathConnected s :=
h.isInducing.isPathConnected_iff.symm
/-- If `h : X → Y` is a homeomorphism, `h⁻¹(s)` is path-connected iff `s` is. -/
@[simp]
theorem Homeomorph.isPathConnected_preimage {s : Set Y} (h : X ≃ₜ Y) :
IsPathConnected (h ⁻¹' s) ↔ IsPathConnected s := by
rw [← Homeomorph.image_symm]; exact h.symm.isPathConnected_image
theorem IsPathConnected.mem_pathComponent (h : IsPathConnected F) (x_in : x ∈ F) (y_in : y ∈ F) :
y ∈ pathComponent x :=
(h.joinedIn x x_in y y_in).joined
theorem IsPathConnected.subset_pathComponent (h : IsPathConnected F) (x_in : x ∈ F) :
F ⊆ pathComponent x := fun _y y_in => h.mem_pathComponent x_in y_in
theorem IsPathConnected.subset_pathComponentIn {s : Set X} (hs : IsPathConnected s)
(hxs : x ∈ s) (hsF : s ⊆ F) : s ⊆ pathComponentIn x F :=
fun y hys ↦ (hs.joinedIn x hxs y hys).mono hsF
theorem isPathConnected_singleton (x : X) : IsPathConnected ({x} : Set X) := by
refine ⟨x, rfl, ?_⟩
rintro y rfl
exact JoinedIn.refl rfl
theorem isPathConnected_pathComponentIn (h : x ∈ F) : IsPathConnected (pathComponentIn x F) :=
⟨x, mem_pathComponentIn_self h, fun ⟨γ, hγ⟩ ↦ by
refine ⟨γ, fun t ↦
⟨(γ.truncateOfLE t.2.1).cast (γ.extend_zero.symm) (γ.extend_extends' t).symm, fun t' ↦ ?_⟩⟩
dsimp [Path.truncateOfLE, Path.truncate]
exact γ.extend_extends' ⟨min (max t'.1 0) t.1, by simp [t.2.1, t.2.2]⟩ ▸ hγ _⟩
theorem isPathConnected_pathComponent : IsPathConnected (pathComponent x) := by
rw [← pathComponentIn_univ]
exact isPathConnected_pathComponentIn (mem_univ x)
theorem IsPathConnected.union {U V : Set X} (hU : IsPathConnected U) (hV : IsPathConnected V)
(hUV : (U ∩ V).Nonempty) : IsPathConnected (U ∪ V) := by
rcases hUV with ⟨x, xU, xV⟩
use x, Or.inl xU
rintro y (yU | yV)
· exact (hU.joinedIn x xU y yU).mono subset_union_left
· exact (hV.joinedIn x xV y yV).mono subset_union_right
/-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller
ambient type `U` (when `U` contains `W`). -/
theorem IsPathConnected.preimage_coe {U W : Set X} (hW : IsPathConnected W) (hWU : W ⊆ U) :
IsPathConnected (((↑) : U → X) ⁻¹' W) := by
rwa [IsInducing.subtypeVal.isPathConnected_iff, Subtype.image_preimage_val, inter_eq_right.2 hWU]
theorem IsPathConnected.exists_path_through_family {n : ℕ}
{s : Set X} (h : IsPathConnected s) (p : Fin (n + 1) → X) (hp : ∀ i, p i ∈ s) :
∃ γ : Path (p 0) (p n), range γ ⊆ s ∧ ∀ i, p i ∈ range γ := by
let p' : ℕ → X := fun k => if h : k < n + 1 then p ⟨k, h⟩ else p ⟨0, n.zero_lt_succ⟩
obtain ⟨γ, hγ⟩ : ∃ γ : Path (p' 0) (p' n), (∀ i ≤ n, p' i ∈ range γ) ∧ range γ ⊆ s := by
have hp' : ∀ i ≤ n, p' i ∈ s := by
intro i hi
simp [p', Nat.lt_succ_of_le hi, hp]
clear_value p'
clear hp p
induction n with
| zero =>
use Path.refl (p' 0)
constructor
· rintro i hi
rw [Nat.le_zero.mp hi]
exact ⟨0, rfl⟩
· rw [range_subset_iff]
rintro _x
exact hp' 0 le_rfl
| succ n hn =>
rcases hn fun i hi => hp' i <| Nat.le_succ_of_le hi with ⟨γ₀, hγ₀⟩
rcases h.joinedIn (p' n) (hp' n n.le_succ) (p' <| n + 1) (hp' (n + 1) <| le_rfl) with
⟨γ₁, hγ₁⟩
let γ : Path (p' 0) (p' <| n + 1) := γ₀.trans γ₁
use γ
have range_eq : range γ = range γ₀ ∪ range γ₁ := γ₀.trans_range γ₁
constructor
· rintro i hi
by_cases hi' : i ≤ n
· rw [range_eq]
left
exact hγ₀.1 i hi'
· rw [not_le, ← Nat.succ_le_iff] at hi'
have : i = n.succ := le_antisymm hi hi'
rw [this]
use 1
exact γ.target
· rw [range_eq]
apply union_subset hγ₀.2
rw [range_subset_iff]
exact hγ₁
have hpp' : ∀ k < n + 1, p k = p' k := by
intro k hk
simp only [p', hk, dif_pos]
congr
ext
rw [Fin.val_cast_of_lt hk]
use γ.cast (hpp' 0 n.zero_lt_succ) (hpp' n n.lt_succ_self)
simp only [γ.cast_coe]
refine And.intro hγ.2 ?_
rintro ⟨i, hi⟩
suffices p ⟨i, hi⟩ = p' i by convert hγ.1 i (Nat.le_of_lt_succ hi)
rw [← hpp' i hi]
suffices i = i % n.succ by congr
rw [Nat.mod_eq_of_lt hi]
theorem IsPathConnected.exists_path_through_family' {n : ℕ}
{s : Set X} (h : IsPathConnected s) (p : Fin (n + 1) → X) (hp : ∀ i, p i ∈ s) :
∃ (γ : Path (p 0) (p n)) (t : Fin (n + 1) → I), (∀ t, γ t ∈ s) ∧ ∀ i, γ (t i) = p i := by
rcases h.exists_path_through_family p hp with ⟨γ, hγ⟩
rcases hγ with ⟨h₁, h₂⟩
simp only [range, mem_setOf_eq] at h₂
rw [range_subset_iff] at h₁
choose! t ht using h₂
exact ⟨γ, t, h₁, ht⟩
/-! ### Path connected spaces -/
/-- A topological space is path-connected if it is non-empty and every two points can be
joined by a continuous path. -/
@[mk_iff]
class PathConnectedSpace (X : Type*) [TopologicalSpace X] : Prop where
/-- A path-connected space must be nonempty. -/
nonempty : Nonempty X
/-- Any two points in a path-connected space must be joined by a continuous path. -/
joined : ∀ x y : X, Joined x y
theorem pathConnectedSpace_iff_zerothHomotopy :
PathConnectedSpace X ↔ Nonempty (ZerothHomotopy X) ∧ Subsingleton (ZerothHomotopy X) := by
letI := pathSetoid X
constructor
· intro h
refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨?_⟩⟩
rintro ⟨x⟩ ⟨y⟩
exact Quotient.sound (PathConnectedSpace.joined x y)
· unfold ZerothHomotopy
rintro ⟨h, h'⟩
exact ⟨(nonempty_quotient_iff _).mp h, fun x y => Quotient.exact <| Subsingleton.elim ⟦x⟧ ⟦y⟧⟩
namespace PathConnectedSpace
variable [PathConnectedSpace X]
/-- Use path-connectedness to build a path between two points. -/
def somePath (x y : X) : Path x y :=
Nonempty.some (joined x y)
end PathConnectedSpace
theorem pathConnectedSpace_iff_univ : PathConnectedSpace X ↔ IsPathConnected (univ : Set X) := by
simp [pathConnectedSpace_iff, isPathConnected_iff, nonempty_iff_univ_nonempty]
theorem isPathConnected_iff_pathConnectedSpace : IsPathConnected F ↔ PathConnectedSpace F := by
rw [pathConnectedSpace_iff_univ, IsInducing.subtypeVal.isPathConnected_iff, image_univ,
Subtype.range_val_subtype, setOf_mem_eq]
theorem isPathConnected_univ [PathConnectedSpace X] : IsPathConnected (univ : Set X) :=
pathConnectedSpace_iff_univ.mp inferInstance
theorem isPathConnected_range [PathConnectedSpace X] {f : X → Y} (hf : Continuous f) :
IsPathConnected (range f) := by
rw [← image_univ]
exact isPathConnected_univ.image hf
theorem Function.Surjective.pathConnectedSpace [PathConnectedSpace X]
{f : X → Y} (hf : Surjective f) (hf' : Continuous f) : PathConnectedSpace Y := by
rw [pathConnectedSpace_iff_univ, ← hf.range_eq]
exact isPathConnected_range hf'
instance Quotient.instPathConnectedSpace {s : Setoid X} [PathConnectedSpace X] :
PathConnectedSpace (Quotient s) :=
Quotient.mk'_surjective.pathConnectedSpace continuous_coinduced_rng
/-- This is a special case of `NormedSpace.instPathConnectedSpace` (and
`IsTopologicalAddGroup.pathConnectedSpace`). It exists only to simplify dependencies. -/
instance Real.instPathConnectedSpace : PathConnectedSpace ℝ where
joined x y := ⟨⟨⟨fun (t : I) ↦ (1 - t) * x + t * y, by fun_prop⟩, by simp, by simp⟩⟩
nonempty := inferInstance
theorem pathConnectedSpace_iff_eq : PathConnectedSpace X ↔ ∃ x : X, pathComponent x = univ := by
simp [pathConnectedSpace_iff_univ, isPathConnected_iff_eq]
-- see Note [lower instance priority]
instance (priority := 100) PathConnectedSpace.connectedSpace [PathConnectedSpace X] :
ConnectedSpace X := by
rw [connectedSpace_iff_connectedComponent]
rcases isPathConnected_iff_eq.mp (pathConnectedSpace_iff_univ.mp ‹_›) with ⟨x, _x_in, hx⟩
use x
rw [← univ_subset_iff]
exact (by simpa using hx : pathComponent x = univ) ▸ pathComponent_subset_component x
theorem IsPathConnected.isConnected (hF : IsPathConnected F) : IsConnected F := by
rw [isConnected_iff_connectedSpace]
rw [isPathConnected_iff_pathConnectedSpace] at hF
exact @PathConnectedSpace.connectedSpace _ _ hF
namespace PathConnectedSpace
variable [PathConnectedSpace X]
theorem exists_path_through_family {n : ℕ} (p : Fin (n + 1) → X) :
∃ γ : Path (p 0) (p n), ∀ i, p i ∈ range γ := by
have : IsPathConnected (univ : Set X) := pathConnectedSpace_iff_univ.mp (by infer_instance)
rcases this.exists_path_through_family p fun _i => True.intro with ⟨γ, -, h⟩
exact ⟨γ, h⟩
theorem exists_path_through_family' {n : ℕ} (p : Fin (n + 1) → X) :
∃ (γ : Path (p 0) (p n)) (t : Fin (n + 1) → I), ∀ i, γ (t i) = p i := by
have : IsPathConnected (univ : Set X) := pathConnectedSpace_iff_univ.mp (by infer_instance)
rcases this.exists_path_through_family' p fun _i => True.intro with ⟨γ, t, -, h⟩
exact ⟨γ, t, h⟩
end PathConnectedSpace
| Mathlib/Topology/Connected/PathConnected.lean | 1,300 | 1,319 | |
/-
Copyright (c) 2021 Justus Springer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Justus Springer
-/
import Mathlib.CategoryTheory.Sites.Spaces
import Mathlib.Topology.Sheaves.Sheaf
import Mathlib.CategoryTheory.Sites.DenseSubsite.Basic
/-!
# Coverings and sieves; from sheaves on sites and sheaves on spaces
In this file, we connect coverings in a topological space to sieves in the associated Grothendieck
topology, in preparation of connecting the sheaf condition on sites to the various sheaf conditions
on spaces.
We also specialize results about sheaves on sites to sheaves on spaces; we show that the inclusion
functor from a topological basis to `TopologicalSpace.Opens` is cover dense, that open maps
induce cover preserving functors, and that open embeddings induce continuous functors.
-/
noncomputable section
open CategoryTheory TopologicalSpace Topology
universe w v u
namespace TopCat.Presheaf
variable {X : TopCat.{w}}
/-- Given a presieve `R` on `U`, we obtain a covering family of open sets in `X`, by taking as index
type the type of dependent pairs `(V, f)`, where `f : V ⟶ U` is in `R`.
-/
def coveringOfPresieve (U : Opens X) (R : Presieve U) : (ΣV, { f : V ⟶ U // R f }) → Opens X :=
fun f => f.1
@[simp]
theorem coveringOfPresieve_apply (U : Opens X) (R : Presieve U) (f : Σ V, { f : V ⟶ U // R f }) :
coveringOfPresieve U R f = f.1 := rfl
namespace coveringOfPresieve
variable (U : Opens X) (R : Presieve U)
/-- If `R` is a presieve in the grothendieck topology on `Opens X`, the covering family associated
to `R` really is _covering_, i.e. the union of all open sets equals `U`.
-/
theorem iSup_eq_of_mem_grothendieck (hR : Sieve.generate R ∈ Opens.grothendieckTopology X U) :
iSup (coveringOfPresieve U R) = U := by
apply le_antisymm
· refine iSup_le ?_
intro f
exact f.2.1.le
intro x hxU
rw [Opens.coe_iSup, Set.mem_iUnion]
obtain ⟨V, iVU, ⟨W, iVW, iWU, hiWU, -⟩, hxV⟩ := hR x hxU
exact ⟨⟨W, ⟨iWU, hiWU⟩⟩, iVW.le hxV⟩
end coveringOfPresieve
/-- Given a family of opens `U : ι → Opens X` and any open `Y : Opens X`, we obtain a presieve
on `Y` by declaring that a morphism `f : V ⟶ Y` is a member of the presieve if and only if
there exists an index `i : ι` such that `V = U i`.
-/
def presieveOfCoveringAux {ι : Type v} (U : ι → Opens X) (Y : Opens X) : Presieve Y :=
fun V _ => ∃ i, V = U i
/-- Take `Y` to be `iSup U` and obtain a presieve over `iSup U`. -/
def presieveOfCovering {ι : Type v} (U : ι → Opens X) : Presieve (iSup U) :=
presieveOfCoveringAux U (iSup U)
/-- Given a presieve `R` on `Y`, if we take its associated family of opens via
`coveringOfPresieve` (which may not cover `Y` if `R` is not covering), and take
the presieve on `Y` associated to the family of opens via `presieveOfCoveringAux`,
then we get back the original presieve `R`. -/
@[simp]
theorem covering_presieve_eq_self {Y : Opens X} (R : Presieve Y) :
presieveOfCoveringAux (coveringOfPresieve Y R) Y = R := by
funext Z
ext f
exact ⟨fun ⟨⟨_, f', h⟩, rfl⟩ => by rwa [Subsingleton.elim f f'], fun h => ⟨⟨Z, f, h⟩, rfl⟩⟩
namespace presieveOfCovering
variable {ι : Type v} (U : ι → Opens X)
|
/-- The sieve generated by `presieveOfCovering U` is a member of the grothendieck topology.
-/
theorem mem_grothendieckTopology :
Sieve.generate (presieveOfCovering U) ∈ Opens.grothendieckTopology X (iSup U) := by
| Mathlib/Topology/Sheaves/SheafCondition/Sites.lean | 90 | 94 |
/-
Copyright (c) 2022 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import Mathlib.Geometry.Euclidean.Angle.Oriented.Affine
import Mathlib.Geometry.Euclidean.Angle.Unoriented.RightAngle
/-!
# Oriented angles in right-angled triangles.
This file proves basic geometrical results about distances and oriented angles in (possibly
degenerate) right-angled triangles in real inner product spaces and Euclidean affine spaces.
-/
noncomputable section
open scoped EuclideanGeometry
open scoped Real
open scoped RealInnerProductSpace
namespace Orientation
open Module
variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V]
variable [hd2 : Fact (finrank ℝ V = 2)] (o : Orientation ℝ V (Fin 2))
/-- An angle in a right-angled triangle expressed using `arccos`. -/
theorem oangle_add_right_eq_arccos_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle x (x + y) = Real.arccos (‖x‖ / ‖x + y‖) := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_add_eq_arccos_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
/-- An angle in a right-angled triangle expressed using `arccos`. -/
theorem oangle_add_left_eq_arccos_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x + y) y = Real.arccos (‖y‖ / ‖x + y‖) := by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h ⊢
rw [add_comm]
exact (-o).oangle_add_right_eq_arccos_of_oangle_eq_pi_div_two h
/-- An angle in a right-angled triangle expressed using `arcsin`. -/
theorem oangle_add_right_eq_arcsin_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle x (x + y) = Real.arcsin (‖y‖ / ‖x + y‖) := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_add_eq_arcsin_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.left_ne_zero_of_oangle_eq_pi_div_two h))]
/-- An angle in a right-angled triangle expressed using `arcsin`. -/
theorem oangle_add_left_eq_arcsin_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x + y) y = Real.arcsin (‖x‖ / ‖x + y‖) := by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h ⊢
rw [add_comm]
exact (-o).oangle_add_right_eq_arcsin_of_oangle_eq_pi_div_two h
/-- An angle in a right-angled triangle expressed using `arctan`. -/
theorem oangle_add_right_eq_arctan_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle x (x + y) = Real.arctan (‖y‖ / ‖x‖) := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs,
InnerProductGeometry.angle_add_eq_arctan_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h) (o.left_ne_zero_of_oangle_eq_pi_div_two h)]
/-- An angle in a right-angled triangle expressed using `arctan`. -/
theorem oangle_add_left_eq_arctan_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
o.oangle (x + y) y = Real.arctan (‖x‖ / ‖y‖) := by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h ⊢
rw [add_comm]
exact (-o).oangle_add_right_eq_arctan_of_oangle_eq_pi_div_two h
/-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/
theorem cos_oangle_add_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.cos (o.oangle x (x + y)) = ‖x‖ / ‖x + y‖ := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
InnerProductGeometry.cos_angle_add_of_inner_eq_zero (o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
/-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/
theorem cos_oangle_add_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.cos (o.oangle (x + y) y) = ‖y‖ / ‖x + y‖ := by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h ⊢
rw [add_comm]
exact (-o).cos_oangle_add_right_of_oangle_eq_pi_div_two h
/-- The sine of an angle in a right-angled triangle as a ratio of sides. -/
theorem sin_oangle_add_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.sin (o.oangle x (x + y)) = ‖y‖ / ‖x + y‖ := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
InnerProductGeometry.sin_angle_add_of_inner_eq_zero (o.inner_eq_zero_of_oangle_eq_pi_div_two h)
(Or.inl (o.left_ne_zero_of_oangle_eq_pi_div_two h))]
/-- The sine of an angle in a right-angled triangle as a ratio of sides. -/
theorem sin_oangle_add_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.sin (o.oangle (x + y) y) = ‖x‖ / ‖x + y‖ := by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h ⊢
rw [add_comm]
exact (-o).sin_oangle_add_right_of_oangle_eq_pi_div_two h
/-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/
theorem tan_oangle_add_right_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.tan (o.oangle x (x + y)) = ‖y‖ / ‖x‖ := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
InnerProductGeometry.tan_angle_add_of_inner_eq_zero (o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
/-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/
theorem tan_oangle_add_left_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = ↑(π / 2)) :
Real.Angle.tan (o.oangle (x + y) y) = ‖x‖ / ‖y‖ := by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h ⊢
rw [add_comm]
exact (-o).tan_oangle_add_right_of_oangle_eq_pi_div_two h
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side. -/
theorem cos_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.cos (o.oangle x (x + y)) * ‖x + y‖ = ‖x‖ := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.cos_coe,
InnerProductGeometry.cos_angle_add_mul_norm_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side. -/
theorem cos_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.cos (o.oangle (x + y) y) * ‖x + y‖ = ‖y‖ := by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h ⊢
rw [add_comm]
exact (-o).cos_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two h
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side. -/
theorem sin_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.sin (o.oangle x (x + y)) * ‖x + y‖ = ‖y‖ := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.sin_coe,
InnerProductGeometry.sin_angle_add_mul_norm_of_inner_eq_zero
(o.inner_eq_zero_of_oangle_eq_pi_div_two h)]
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side. -/
theorem sin_oangle_add_left_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.sin (o.oangle (x + y) y) * ‖x + y‖ = ‖x‖ := by
rw [← neg_inj, oangle_rev, ← oangle_neg_orientation_eq_neg, neg_inj] at h ⊢
rw [add_comm]
exact (-o).sin_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two h
| /-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side. -/
theorem tan_oangle_add_right_mul_norm_of_oangle_eq_pi_div_two {x y : V}
(h : o.oangle x y = ↑(π / 2)) : Real.Angle.tan (o.oangle x (x + y)) * ‖x‖ = ‖y‖ := by
have hs : (o.oangle x (x + y)).sign = 1 := by
rw [oangle_sign_add_right, h, Real.Angle.sign_coe_pi_div_two]
rw [o.oangle_eq_angle_of_sign_eq_one hs, Real.Angle.tan_coe,
| Mathlib/Geometry/Euclidean/Angle/Oriented/RightAngle.lean | 164 | 170 |
/-
Copyright (c) 2020 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison, Johan Commelin, Andrew Yang, Joël Riou
-/
import Mathlib.Algebra.Group.Basic
import Mathlib.CategoryTheory.Limits.Preserves.Shapes.Zero
import Mathlib.CategoryTheory.Monoidal.End
import Mathlib.CategoryTheory.Monoidal.Discrete
/-!
# Shift
A `Shift` on a category `C` indexed by a monoid `A` is nothing more than a monoidal functor
from `A` to `C ⥤ C`. A typical example to keep in mind might be the category of
complexes `⋯ → C_{n-1} → C_n → C_{n+1} → ⋯`. It has a shift indexed by `ℤ`, where we assign to
each `n : ℤ` the functor `C ⥤ C` that re-indexes the terms, so the degree `i` term of `Shift n C`
would be the degree `i+n`-th term of `C`.
## Main definitions
* `HasShift`: A typeclass asserting the existence of a shift functor.
* `shiftEquiv`: When the indexing monoid is a group, then the functor indexed by `n` and `-n` forms
a self-equivalence of `C`.
* `shiftComm`: When the indexing monoid is commutative, then shifts commute as well.
## Implementation Notes
`[HasShift C A]` is implemented using monoidal functors from `Discrete A` to `C ⥤ C`.
However, the API of monoidal functors is used only internally: one should use the API of
shifts functors which includes `shiftFunctor C a : C ⥤ C` for `a : A`,
`shiftFunctorZero C A : shiftFunctor C (0 : A) ≅ 𝟭 C` and
`shiftFunctorAdd C i j : shiftFunctor C (i + j) ≅ shiftFunctor C i ⋙ shiftFunctor C j`
(and its variant `shiftFunctorAdd'`). These isomorphisms satisfy some coherence properties
which are stated in lemmas like `shiftFunctorAdd'_assoc`, `shiftFunctorAdd'_zero_add` and
`shiftFunctorAdd'_add_zero`.
-/
namespace CategoryTheory
noncomputable section
universe v u
variable (C : Type u) (A : Type*) [Category.{v} C]
attribute [local instance] endofunctorMonoidalCategory
variable {A C}
section Defs
variable (A C) [AddMonoid A]
/-- A category has a shift indexed by an additive monoid `A`
if there is a monoidal functor from `A` to `C ⥤ C`. -/
class HasShift (C : Type u) (A : Type*) [Category.{v} C] [AddMonoid A] where
/-- a shift is a monoidal functor from `A` to `C ⥤ C` -/
shift : Discrete A ⥤ C ⥤ C
/-- `shift` is monoidal -/
shiftMonoidal : shift.Monoidal := by infer_instance
/-- A helper structure to construct the shift functor `(Discrete A) ⥤ (C ⥤ C)`. -/
structure ShiftMkCore where
/-- the family of shift functors -/
F : A → C ⥤ C
/-- the shift by 0 identifies to the identity functor -/
zero : F 0 ≅ 𝟭 C
/-- the composition of shift functors identifies to the shift by the sum -/
add : ∀ n m : A, F (n + m) ≅ F n ⋙ F m
/-- compatibility with the associativity -/
assoc_hom_app : ∀ (m₁ m₂ m₃ : A) (X : C),
(add (m₁ + m₂) m₃).hom.app X ≫ (F m₃).map ((add m₁ m₂).hom.app X) =
eqToHom (by rw [add_assoc]) ≫ (add m₁ (m₂ + m₃)).hom.app X ≫
(add m₂ m₃).hom.app ((F m₁).obj X) := by aesop_cat
/-- compatibility with the left addition with 0 -/
zero_add_hom_app : ∀ (n : A) (X : C), (add 0 n).hom.app X =
eqToHom (by dsimp; rw [zero_add]) ≫ (F n).map (zero.inv.app X) := by aesop_cat
/-- compatibility with the right addition with 0 -/
add_zero_hom_app : ∀ (n : A) (X : C), (add n 0).hom.app X =
eqToHom (by dsimp; rw [add_zero]) ≫ zero.inv.app ((F n).obj X) := by aesop_cat
namespace ShiftMkCore
variable {C A}
attribute [reassoc] assoc_hom_app
@[reassoc]
lemma assoc_inv_app (h : ShiftMkCore C A) (m₁ m₂ m₃ : A) (X : C) :
(h.F m₃).map ((h.add m₁ m₂).inv.app X) ≫ (h.add (m₁ + m₂) m₃).inv.app X =
(h.add m₂ m₃).inv.app ((h.F m₁).obj X) ≫ (h.add m₁ (m₂ + m₃)).inv.app X ≫
eqToHom (by rw [add_assoc]) := by
rw [← cancel_mono ((h.add (m₁ + m₂) m₃).hom.app X ≫ (h.F m₃).map ((h.add m₁ m₂).hom.app X)),
Category.assoc, Category.assoc, Category.assoc, Iso.inv_hom_id_app_assoc, ← Functor.map_comp,
Iso.inv_hom_id_app, Functor.map_id, h.assoc_hom_app, eqToHom_trans_assoc, eqToHom_refl,
Category.id_comp, Iso.inv_hom_id_app_assoc, Iso.inv_hom_id_app]
rfl
lemma zero_add_inv_app (h : ShiftMkCore C A) (n : A) (X : C) :
(h.add 0 n).inv.app X = (h.F n).map (h.zero.hom.app X) ≫
eqToHom (by dsimp; rw [zero_add]) := by
rw [← cancel_epi ((h.add 0 n).hom.app X), Iso.hom_inv_id_app, h.zero_add_hom_app,
Category.assoc, ← Functor.map_comp_assoc, Iso.inv_hom_id_app, Functor.map_id,
Category.id_comp, eqToHom_trans, eqToHom_refl]
lemma add_zero_inv_app (h : ShiftMkCore C A) (n : A) (X : C) :
(h.add n 0).inv.app X = h.zero.hom.app ((h.F n).obj X) ≫
eqToHom (by dsimp; rw [add_zero]) := by
rw [← cancel_epi ((h.add n 0).hom.app X), Iso.hom_inv_id_app, h.add_zero_hom_app,
Category.assoc, Iso.inv_hom_id_app_assoc, eqToHom_trans, eqToHom_refl]
end ShiftMkCore
section
attribute [local simp] eqToHom_map
instance (h : ShiftMkCore C A) : (Discrete.functor h.F).Monoidal :=
Functor.CoreMonoidal.toMonoidal
{ εIso := h.zero.symm
μIso := fun m n ↦ (h.add m.as n.as).symm
μIso_hom_natural_left := by
rintro ⟨X⟩ ⟨Y⟩ ⟨⟨⟨rfl⟩⟩⟩ ⟨X'⟩
ext
dsimp
simp
μIso_hom_natural_right := by
rintro ⟨X⟩ ⟨Y⟩ ⟨X'⟩ ⟨⟨⟨rfl⟩⟩⟩
ext
dsimp
simp
associativity := by
rintro ⟨m₁⟩ ⟨m₂⟩ ⟨m₃⟩
ext X
simp [endofunctorMonoidalCategory, h.assoc_inv_app_assoc]
left_unitality := by
rintro ⟨n⟩
ext X
simp [endofunctorMonoidalCategory, h.zero_add_inv_app, ← Functor.map_comp]
right_unitality := by
rintro ⟨n⟩
ext X
simp [endofunctorMonoidalCategory, h.add_zero_inv_app] }
/-- Constructs a `HasShift C A` instance from `ShiftMkCore`. -/
def hasShiftMk (h : ShiftMkCore C A) : HasShift C A where
shift := Discrete.functor h.F
end
section
variable [HasShift C A]
/-- The monoidal functor from `A` to `C ⥤ C` given a `HasShift` instance. -/
def shiftMonoidalFunctor : Discrete A ⥤ C ⥤ C :=
HasShift.shift
instance : (shiftMonoidalFunctor C A).Monoidal := HasShift.shiftMonoidal
variable {A}
open Functor.Monoidal
/-- The shift autoequivalence, moving objects and morphisms 'up'. -/
def shiftFunctor (i : A) : C ⥤ C :=
(shiftMonoidalFunctor C A).obj ⟨i⟩
/-- Shifting by `i + j` is the same as shifting by `i` and then shifting by `j`. -/
def shiftFunctorAdd (i j : A) : shiftFunctor C (i + j) ≅ shiftFunctor C i ⋙ shiftFunctor C j :=
(μIso (shiftMonoidalFunctor C A) ⟨i⟩ ⟨j⟩).symm
/-- When `k = i + j`, shifting by `k` is the same as shifting by `i` and then shifting by `j`. -/
def shiftFunctorAdd' (i j k : A) (h : i + j = k) :
shiftFunctor C k ≅ shiftFunctor C i ⋙ shiftFunctor C j :=
eqToIso (by rw [h]) ≪≫ shiftFunctorAdd C i j
lemma shiftFunctorAdd'_eq_shiftFunctorAdd (i j : A) :
shiftFunctorAdd' C i j (i+j) rfl = shiftFunctorAdd C i j := by
ext1
apply Category.id_comp
variable (A) in
/-- Shifting by zero is the identity functor. -/
def shiftFunctorZero : shiftFunctor C (0 : A) ≅ 𝟭 C :=
(εIso (shiftMonoidalFunctor C A)).symm
/-- Shifting by `a` such that `a = 0` identifies to the identity functor. -/
def shiftFunctorZero' (a : A) (ha : a = 0) : shiftFunctor C a ≅ 𝟭 C :=
eqToIso (by rw [ha]) ≪≫ shiftFunctorZero C A
end
variable {C A}
lemma ShiftMkCore.shiftFunctor_eq (h : ShiftMkCore C A) (a : A) :
letI := hasShiftMk C A h
shiftFunctor C a = h.F a := rfl
lemma ShiftMkCore.shiftFunctorZero_eq (h : ShiftMkCore C A) :
letI := hasShiftMk C A h
shiftFunctorZero C A = h.zero := rfl
lemma ShiftMkCore.shiftFunctorAdd_eq (h : ShiftMkCore C A) (a b : A) :
letI := hasShiftMk C A h
shiftFunctorAdd C a b = h.add a b := rfl
set_option quotPrecheck false in
/-- shifting an object `X` by `n` is obtained by the notation `X⟦n⟧` -/
notation -- Any better notational suggestions?
X "⟦" n "⟧" => (shiftFunctor _ n).obj X
set_option quotPrecheck false in
/-- shifting a morphism `f` by `n` is obtained by the notation `f⟦n⟧'` -/
notation f "⟦" n "⟧'" => (shiftFunctor _ n).map f
variable (C)
variable [HasShift C A]
lemma shiftFunctorAdd'_zero_add (a : A) :
shiftFunctorAdd' C 0 a a (zero_add a) = (Functor.leftUnitor _).symm ≪≫
isoWhiskerRight (shiftFunctorZero C A).symm (shiftFunctor C a) := by
ext X
dsimp [shiftFunctorAdd', shiftFunctorZero, shiftFunctor]
simp only [eqToHom_app, obj_ε_app, Discrete.addMonoidal_leftUnitor, eqToIso.inv,
eqToHom_map, Category.id_comp]
rfl
lemma shiftFunctorAdd'_add_zero (a : A) :
shiftFunctorAdd' C a 0 a (add_zero a) = (Functor.rightUnitor _).symm ≪≫
isoWhiskerLeft (shiftFunctor C a) (shiftFunctorZero C A).symm := by
ext
dsimp [shiftFunctorAdd', shiftFunctorZero, shiftFunctor]
simp only [eqToHom_app, ε_app_obj, Discrete.addMonoidal_rightUnitor, eqToIso.inv,
eqToHom_map, Category.id_comp]
rfl
lemma shiftFunctorAdd'_assoc (a₁ a₂ a₃ a₁₂ a₂₃ a₁₂₃ : A)
(h₁₂ : a₁ + a₂ = a₁₂) (h₂₃ : a₂ + a₃ = a₂₃) (h₁₂₃ : a₁ + a₂ + a₃ = a₁₂₃) :
shiftFunctorAdd' C a₁₂ a₃ a₁₂₃ (by rw [← h₁₂, h₁₂₃]) ≪≫
isoWhiskerRight (shiftFunctorAdd' C a₁ a₂ a₁₂ h₁₂) _ ≪≫ Functor.associator _ _ _ =
shiftFunctorAdd' C a₁ a₂₃ a₁₂₃ (by rw [← h₂₃, ← add_assoc, h₁₂₃]) ≪≫
isoWhiskerLeft _ (shiftFunctorAdd' C a₂ a₃ a₂₃ h₂₃) := by
subst h₁₂ h₂₃ h₁₂₃
ext X
dsimp
simp only [shiftFunctorAdd'_eq_shiftFunctorAdd, Category.comp_id]
dsimp [shiftFunctorAdd']
simp only [eqToHom_app]
dsimp [shiftFunctorAdd, shiftFunctor]
simp only [obj_μ_inv_app, Discrete.addMonoidal_associator, eqToIso.hom, eqToHom_map,
eqToHom_app]
erw [δ_μ_app_assoc, Category.assoc]
rfl
lemma shiftFunctorAdd_assoc (a₁ a₂ a₃ : A) :
shiftFunctorAdd C (a₁ + a₂) a₃ ≪≫
isoWhiskerRight (shiftFunctorAdd C a₁ a₂) _ ≪≫ Functor.associator _ _ _ =
shiftFunctorAdd' C a₁ (a₂ + a₃) _ (add_assoc a₁ a₂ a₃).symm ≪≫
isoWhiskerLeft _ (shiftFunctorAdd C a₂ a₃) := by
ext X
simpa [shiftFunctorAdd'_eq_shiftFunctorAdd]
using NatTrans.congr_app (congr_arg Iso.hom
(shiftFunctorAdd'_assoc C a₁ a₂ a₃ _ _ _ rfl rfl rfl)) X
variable {C}
lemma shiftFunctorAdd'_zero_add_hom_app (a : A) (X : C) :
(shiftFunctorAdd' C 0 a a (zero_add a)).hom.app X =
((shiftFunctorZero C A).inv.app X)⟦a⟧' := by
simpa using NatTrans.congr_app (congr_arg Iso.hom (shiftFunctorAdd'_zero_add C a)) X
lemma shiftFunctorAdd_zero_add_hom_app (a : A) (X : C) :
(shiftFunctorAdd C 0 a).hom.app X =
eqToHom (by dsimp; rw [zero_add]) ≫ ((shiftFunctorZero C A).inv.app X)⟦a⟧' := by
simp [← shiftFunctorAdd'_zero_add_hom_app, shiftFunctorAdd']
lemma shiftFunctorAdd'_zero_add_inv_app (a : A) (X : C) :
(shiftFunctorAdd' C 0 a a (zero_add a)).inv.app X =
((shiftFunctorZero C A).hom.app X)⟦a⟧' := by
simpa using NatTrans.congr_app (congr_arg Iso.inv (shiftFunctorAdd'_zero_add C a)) X
lemma shiftFunctorAdd_zero_add_inv_app (a : A) (X : C) : (shiftFunctorAdd C 0 a).inv.app X =
((shiftFunctorZero C A).hom.app X)⟦a⟧' ≫ eqToHom (by dsimp; rw [zero_add]) := by
simp [← shiftFunctorAdd'_zero_add_inv_app, shiftFunctorAdd']
lemma shiftFunctorAdd'_add_zero_hom_app (a : A) (X : C) :
(shiftFunctorAdd' C a 0 a (add_zero a)).hom.app X =
(shiftFunctorZero C A).inv.app (X⟦a⟧) := by
simpa using NatTrans.congr_app (congr_arg Iso.hom (shiftFunctorAdd'_add_zero C a)) X
lemma shiftFunctorAdd_add_zero_hom_app (a : A) (X : C) : (shiftFunctorAdd C a 0).hom.app X =
eqToHom (by dsimp; rw [add_zero]) ≫ (shiftFunctorZero C A).inv.app (X⟦a⟧) := by
simp [← shiftFunctorAdd'_add_zero_hom_app, shiftFunctorAdd']
lemma shiftFunctorAdd'_add_zero_inv_app (a : A) (X : C) :
(shiftFunctorAdd' C a 0 a (add_zero a)).inv.app X =
(shiftFunctorZero C A).hom.app (X⟦a⟧) := by
simpa using NatTrans.congr_app (congr_arg Iso.inv (shiftFunctorAdd'_add_zero C a)) X
lemma shiftFunctorAdd_add_zero_inv_app (a : A) (X : C) : (shiftFunctorAdd C a 0).inv.app X =
(shiftFunctorZero C A).hom.app (X⟦a⟧) ≫ eqToHom (by dsimp; rw [add_zero]) := by
simp [← shiftFunctorAdd'_add_zero_inv_app, shiftFunctorAdd']
@[reassoc]
lemma shiftFunctorAdd'_assoc_hom_app (a₁ a₂ a₃ a₁₂ a₂₃ a₁₂₃ : A)
(h₁₂ : a₁ + a₂ = a₁₂) (h₂₃ : a₂ + a₃ = a₂₃) (h₁₂₃ : a₁ + a₂ + a₃ = a₁₂₃) (X : C) :
(shiftFunctorAdd' C a₁₂ a₃ a₁₂₃ (by rw [← h₁₂, h₁₂₃])).hom.app X ≫
((shiftFunctorAdd' C a₁ a₂ a₁₂ h₁₂).hom.app X)⟦a₃⟧' =
(shiftFunctorAdd' C a₁ a₂₃ a₁₂₃ (by rw [← h₂₃, ← add_assoc, h₁₂₃])).hom.app X ≫
(shiftFunctorAdd' C a₂ a₃ a₂₃ h₂₃).hom.app (X⟦a₁⟧) := by
simpa using NatTrans.congr_app (congr_arg Iso.hom
(shiftFunctorAdd'_assoc C _ _ _ _ _ _ h₁₂ h₂₃ h₁₂₃)) X
@[reassoc]
lemma shiftFunctorAdd'_assoc_inv_app (a₁ a₂ a₃ a₁₂ a₂₃ a₁₂₃ : A)
(h₁₂ : a₁ + a₂ = a₁₂) (h₂₃ : a₂ + a₃ = a₂₃) (h₁₂₃ : a₁ + a₂ + a₃ = a₁₂₃) (X : C) :
((shiftFunctorAdd' C a₁ a₂ a₁₂ h₁₂).inv.app X)⟦a₃⟧' ≫
(shiftFunctorAdd' C a₁₂ a₃ a₁₂₃ (by rw [← h₁₂, h₁₂₃])).inv.app X =
(shiftFunctorAdd' C a₂ a₃ a₂₃ h₂₃).inv.app (X⟦a₁⟧) ≫
(shiftFunctorAdd' C a₁ a₂₃ a₁₂₃ (by rw [← h₂₃, ← add_assoc, h₁₂₃])).inv.app X := by
simpa using NatTrans.congr_app (congr_arg Iso.inv
(shiftFunctorAdd'_assoc C _ _ _ _ _ _ h₁₂ h₂₃ h₁₂₃)) X
@[reassoc]
lemma shiftFunctorAdd_assoc_hom_app (a₁ a₂ a₃ : A) (X : C) :
(shiftFunctorAdd C (a₁ + a₂) a₃).hom.app X ≫
((shiftFunctorAdd C a₁ a₂).hom.app X)⟦a₃⟧' =
(shiftFunctorAdd' C a₁ (a₂ + a₃) (a₁ + a₂ + a₃) (add_assoc _ _ _).symm).hom.app X ≫
(shiftFunctorAdd C a₂ a₃).hom.app (X⟦a₁⟧) := by
simpa using NatTrans.congr_app (congr_arg Iso.hom (shiftFunctorAdd_assoc C a₁ a₂ a₃)) X
@[reassoc]
lemma shiftFunctorAdd_assoc_inv_app (a₁ a₂ a₃ : A) (X : C) :
((shiftFunctorAdd C a₁ a₂).inv.app X)⟦a₃⟧' ≫
(shiftFunctorAdd C (a₁ + a₂) a₃).inv.app X =
(shiftFunctorAdd C a₂ a₃).inv.app (X⟦a₁⟧) ≫
(shiftFunctorAdd' C a₁ (a₂ + a₃) (a₁ + a₂ + a₃) (add_assoc _ _ _).symm).inv.app X := by
simpa using NatTrans.congr_app (congr_arg Iso.inv (shiftFunctorAdd_assoc C a₁ a₂ a₃)) X
end Defs
section AddMonoid
variable [AddMonoid A] [HasShift C A] (X Y : C) (f : X ⟶ Y)
--@[simp]
--theorem HasShift.shift_obj_obj (n : A) (X : C) : (HasShift.shift.obj ⟨n⟩).obj X = X⟦n⟧ :=
-- rfl
/-- Shifting by `i + j` is the same as shifting by `i` and then shifting by `j`. -/
abbrev shiftAdd (i j : A) : X⟦i + j⟧ ≅ X⟦i⟧⟦j⟧ :=
(shiftFunctorAdd C i j).app _
theorem shift_shift' (i j : A) :
f⟦i⟧'⟦j⟧' = (shiftAdd X i j).inv ≫ f⟦i + j⟧' ≫ (shiftAdd Y i j).hom := by
symm
rw [← Functor.comp_map, Iso.app_inv]
apply NatIso.naturality_1
variable (A)
/-- Shifting by zero is the identity functor. -/
abbrev shiftZero : X⟦(0 : A)⟧ ≅ X :=
(shiftFunctorZero C A).app _
theorem shiftZero' : f⟦(0 : A)⟧' = (shiftZero A X).hom ≫ f ≫ (shiftZero A Y).inv := by
symm
rw [Iso.app_inv, Iso.app_hom]
apply NatIso.naturality_2
variable (C) {A}
/-- When `i + j = 0`, shifting by `i` and by `j` gives the identity functor -/
def shiftFunctorCompIsoId (i j : A) (h : i + j = 0) :
shiftFunctor C i ⋙ shiftFunctor C j ≅ 𝟭 C :=
(shiftFunctorAdd' C i j 0 h).symm ≪≫ shiftFunctorZero C A
end AddMonoid
section AddGroup
variable (C)
variable [AddGroup A] [HasShift C A]
/-- Shifting by `i` and shifting by `j` forms an equivalence when `i + j = 0`. -/
@[simps]
def shiftEquiv' (i j : A) (h : i + j = 0) : C ≌ C where
functor := shiftFunctor C i
inverse := shiftFunctor C j
unitIso := (shiftFunctorCompIsoId C i j h).symm
counitIso := shiftFunctorCompIsoId C j i
(by rw [← add_left_inj j, add_assoc, h, zero_add, add_zero])
functor_unitIso_comp X := by
convert (equivOfTensorIsoUnit (shiftMonoidalFunctor C A) ⟨i⟩ ⟨j⟩ (Discrete.eqToIso h)
(Discrete.eqToIso (by dsimp; rw [← add_left_inj j, add_assoc, h, zero_add, add_zero]))
(Subsingleton.elim _ _)).functor_unitIso_comp X
all_goals
ext X
dsimp [shiftFunctorCompIsoId, unitOfTensorIsoUnit,
shiftFunctorAdd']
simp only [Category.assoc, eqToHom_map]
rfl
/-- Shifting by `n` and shifting by `-n` forms an equivalence. -/
abbrev shiftEquiv (n : A) : C ≌ C := shiftEquiv' C n (-n) (add_neg_cancel n)
variable (X Y : C) (f : X ⟶ Y)
/-- Shifting by `i` is an equivalence. -/
instance (i : A) : (shiftFunctor C i).IsEquivalence := by
change (shiftEquiv C i).functor.IsEquivalence
infer_instance
variable {C}
/-- Shifting by `i` and then shifting by `-i` is the identity. -/
abbrev shiftShiftNeg (i : A) : X⟦i⟧⟦-i⟧ ≅ X :=
(shiftEquiv C i).unitIso.symm.app X
/-- Shifting by `-i` and then shifting by `i` is the identity. -/
abbrev shiftNegShift (i : A) : X⟦-i⟧⟦i⟧ ≅ X :=
(shiftEquiv C i).counitIso.app X
variable {X Y}
theorem shift_shift_neg' (i : A) :
f⟦i⟧'⟦-i⟧' = (shiftFunctorCompIsoId C i (-i) (add_neg_cancel i)).hom.app X ≫
f ≫ (shiftFunctorCompIsoId C i (-i) (add_neg_cancel i)).inv.app Y :=
(NatIso.naturality_2 (shiftFunctorCompIsoId C i (-i) (add_neg_cancel i)) f).symm
theorem shift_neg_shift' (i : A) :
f⟦-i⟧'⟦i⟧' = (shiftFunctorCompIsoId C (-i) i (neg_add_cancel i)).hom.app X ≫ f ≫
(shiftFunctorCompIsoId C (-i) i (neg_add_cancel i)).inv.app Y :=
(NatIso.naturality_2 (shiftFunctorCompIsoId C (-i) i (neg_add_cancel i)) f).symm
theorem shift_equiv_triangle (n : A) (X : C) :
(shiftShiftNeg X n).inv⟦n⟧' ≫ (shiftNegShift (X⟦n⟧) n).hom = 𝟙 (X⟦n⟧) :=
(shiftEquiv C n).functor_unitIso_comp X
section
theorem shift_shiftFunctorCompIsoId_hom_app (n m : A) (h : n + m = 0) (X : C) :
((shiftFunctorCompIsoId C n m h).hom.app X)⟦n⟧' =
(shiftFunctorCompIsoId C m n
(by rw [← neg_eq_of_add_eq_zero_left h, add_neg_cancel])).hom.app (X⟦n⟧) := by
dsimp [shiftFunctorCompIsoId]
simpa only [Functor.map_comp, ← shiftFunctorAdd'_zero_add_inv_app n X,
← shiftFunctorAdd'_add_zero_inv_app n X]
using shiftFunctorAdd'_assoc_inv_app n m n 0 0 n h
(by rw [← neg_eq_of_add_eq_zero_left h, add_neg_cancel]) (by rw [h, zero_add]) X
theorem shift_shiftFunctorCompIsoId_inv_app (n m : A) (h : n + m = 0) (X : C) :
((shiftFunctorCompIsoId C n m h).inv.app X)⟦n⟧' =
((shiftFunctorCompIsoId C m n
(by rw [← neg_eq_of_add_eq_zero_left h, add_neg_cancel])).inv.app (X⟦n⟧)) := by
rw [← cancel_mono (((shiftFunctorCompIsoId C n m h).hom.app X)⟦n⟧'),
← Functor.map_comp, Iso.inv_hom_id_app, Functor.map_id,
shift_shiftFunctorCompIsoId_hom_app, Iso.inv_hom_id_app]
rfl
theorem shift_shiftFunctorCompIsoId_add_neg_cancel_hom_app (n : A) (X : C) :
((shiftFunctorCompIsoId C n (-n) (add_neg_cancel n)).hom.app X)⟦n⟧' =
(shiftFunctorCompIsoId C (-n) n (neg_add_cancel n)).hom.app (X⟦n⟧) := by
apply shift_shiftFunctorCompIsoId_hom_app
theorem shift_shiftFunctorCompIsoId_add_neg_cancel_inv_app (n : A) (X : C) :
((shiftFunctorCompIsoId C n (-n) (add_neg_cancel n)).inv.app X)⟦n⟧' =
(shiftFunctorCompIsoId C (-n) n (neg_add_cancel n)).inv.app (X⟦n⟧) := by
apply shift_shiftFunctorCompIsoId_inv_app
theorem shift_shiftFunctorCompIsoId_neg_add_cancel_hom_app (n : A) (X : C) :
((shiftFunctorCompIsoId C (-n) n (neg_add_cancel n)).hom.app X)⟦-n⟧' =
(shiftFunctorCompIsoId C n (-n) (add_neg_cancel n)).hom.app (X⟦-n⟧) := by
apply shift_shiftFunctorCompIsoId_hom_app
theorem shift_shiftFunctorCompIsoId_neg_add_cancel_inv_app (n : A) (X : C) :
((shiftFunctorCompIsoId C (-n) n (neg_add_cancel n)).inv.app X)⟦-n⟧' =
(shiftFunctorCompIsoId C n (-n) (add_neg_cancel n)).inv.app (X⟦-n⟧) := by
apply shift_shiftFunctorCompIsoId_inv_app
end
section
variable (A)
lemma shiftFunctorCompIsoId_zero_zero_hom_app (X : C) :
(shiftFunctorCompIsoId C 0 0 (add_zero 0)).hom.app X =
((shiftFunctorZero C A).hom.app X)⟦0⟧' ≫ (shiftFunctorZero C A).hom.app X := by
simp [shiftFunctorCompIsoId, shiftFunctorAdd'_zero_add_inv_app]
lemma shiftFunctorCompIsoId_zero_zero_inv_app (X : C) :
(shiftFunctorCompIsoId C 0 0 (add_zero 0)).inv.app X =
(shiftFunctorZero C A).inv.app X ≫ ((shiftFunctorZero C A).inv.app X)⟦0⟧' := by
simp [shiftFunctorCompIsoId, shiftFunctorAdd'_zero_add_hom_app]
end
section
variable (m n p m' n' p' : A) (hm : m' + m = 0) (hn : n' + n = 0) (hp : p' + p = 0)
(h : m + n = p)
lemma shiftFunctorCompIsoId_add'_inv_app :
(shiftFunctorCompIsoId C p' p hp).inv.app X =
(shiftFunctorCompIsoId C n' n hn).inv.app X ≫
(shiftFunctorCompIsoId C m' m hm).inv.app (X⟦n'⟧)⟦n⟧' ≫
(shiftFunctorAdd' C m n p h).inv.app (X⟦n'⟧⟦m'⟧) ≫
((shiftFunctorAdd' C n' m' p'
(by rw [← add_left_inj p, hp, ← h, add_assoc,
← add_assoc m', hm, zero_add, hn])).inv.app X)⟦p⟧' := by
dsimp [shiftFunctorCompIsoId]
simp only [Functor.map_comp, Category.assoc]
congr 1
rw [← NatTrans.naturality]
dsimp
rw [← cancel_mono ((shiftFunctorAdd' C p' p 0 hp).inv.app X), Iso.hom_inv_id_app,
Category.assoc, Category.assoc, Category.assoc, Category.assoc,
← shiftFunctorAdd'_assoc_inv_app p' m n n' p 0
(by rw [← add_left_inj n, hn, add_assoc, h, hp]) h (by rw [add_assoc, h, hp]),
← Functor.map_comp_assoc, ← Functor.map_comp_assoc, ← Functor.map_comp_assoc,
Category.assoc, Category.assoc,
shiftFunctorAdd'_assoc_inv_app n' m' m p' 0 n' _ _
(by rw [add_assoc, hm, add_zero]), Iso.hom_inv_id_app_assoc,
← shiftFunctorAdd'_add_zero_hom_app, Iso.hom_inv_id_app,
Functor.map_id, Category.id_comp, Iso.hom_inv_id_app]
lemma shiftFunctorCompIsoId_add'_hom_app :
(shiftFunctorCompIsoId C p' p hp).hom.app X =
((shiftFunctorAdd' C n' m' p'
(by rw [← add_left_inj p, hp, ← h, add_assoc,
← add_assoc m', hm, zero_add, hn])).hom.app X)⟦p⟧' ≫
(shiftFunctorAdd' C m n p h).hom.app (X⟦n'⟧⟦m'⟧) ≫
(shiftFunctorCompIsoId C m' m hm).hom.app (X⟦n'⟧)⟦n⟧' ≫
(shiftFunctorCompIsoId C n' n hn).hom.app X := by
rw [← cancel_mono ((shiftFunctorCompIsoId C p' p hp).inv.app X), Iso.hom_inv_id_app,
shiftFunctorCompIsoId_add'_inv_app m n p m' n' p' hm hn hp h,
Category.assoc, Category.assoc, Category.assoc, Iso.hom_inv_id_app_assoc,
← Functor.map_comp_assoc, Iso.hom_inv_id_app]
dsimp
rw [Functor.map_id, Category.id_comp, Iso.hom_inv_id_app_assoc,
← Functor.map_comp, Iso.hom_inv_id_app, Functor.map_id]
end
open CategoryTheory.Limits
variable [HasZeroMorphisms C]
theorem shift_zero_eq_zero (X Y : C) (n : A) : (0 : X ⟶ Y)⟦n⟧' = (0 : X⟦n⟧ ⟶ Y⟦n⟧) :=
CategoryTheory.Functor.map_zero _ _ _
end AddGroup
section AddCommMonoid
variable [AddCommMonoid A] [HasShift C A]
variable (C)
/-- When shifts are indexed by an additive commutative monoid, then shifts commute. -/
def shiftFunctorComm (i j : A) :
shiftFunctor C i ⋙ shiftFunctor C j ≅
shiftFunctor C j ⋙ shiftFunctor C i :=
(shiftFunctorAdd C i j).symm ≪≫ shiftFunctorAdd' C j i (i + j) (add_comm j i)
lemma shiftFunctorComm_eq (i j k : A) (h : i + j = k) :
shiftFunctorComm C i j = (shiftFunctorAdd' C i j k h).symm ≪≫
shiftFunctorAdd' C j i k (by rw [add_comm j i, h]) := by
subst h
rw [shiftFunctorAdd'_eq_shiftFunctorAdd]
rfl
@[simp]
lemma shiftFunctorComm_eq_refl (i : A) :
shiftFunctorComm C i i = Iso.refl _ := by
rw [shiftFunctorComm_eq C i i (i + i) rfl, Iso.symm_self_id]
lemma shiftFunctorComm_symm (i j : A) :
(shiftFunctorComm C i j).symm = shiftFunctorComm C j i := by
ext1
dsimp
rw [shiftFunctorComm_eq C i j (i+j) rfl, shiftFunctorComm_eq C j i (i+j) (add_comm j i)]
rfl
variable {C}
variable (X Y : C) (f : X ⟶ Y)
/-- When shifts are indexed by an additive commutative monoid, then shifts commute. -/
abbrev shiftComm (i j : A) : X⟦i⟧⟦j⟧ ≅ X⟦j⟧⟦i⟧ :=
| (shiftFunctorComm C i j).app X
@[simp]
| Mathlib/CategoryTheory/Shift/Basic.lean | 592 | 594 |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import Mathlib.Analysis.SpecialFunctions.Exp
import Mathlib.Data.Nat.Factorization.Defs
import Mathlib.Analysis.NormedSpace.Real
import Mathlib.Data.Rat.Cast.CharZero
/-!
# Real logarithm
In this file we define `Real.log` to be the logarithm of a real number. As usual, we extend it from
its domain `(0, +∞)` to a globally defined function. We choose to do it so that `log 0 = 0` and
`log (-x) = log x`.
We prove some basic properties of this function and show that it is continuous.
## Tags
logarithm, continuity
-/
open Set Filter Function
open Topology
noncomputable section
namespace Real
variable {x y : ℝ}
/-- The real logarithm function, equal to the inverse of the exponential for `x > 0`,
to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to
`(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and
the derivative of `log` is `1/x` away from `0`. -/
@[pp_nodot]
noncomputable def log (x : ℝ) : ℝ :=
if hx : x = 0 then 0 else expOrderIso.symm ⟨|x|, abs_pos.2 hx⟩
theorem log_of_ne_zero (hx : x ≠ 0) : log x = expOrderIso.symm ⟨|x|, abs_pos.2 hx⟩ :=
dif_neg hx
theorem log_of_pos (hx : 0 < x) : log x = expOrderIso.symm ⟨x, hx⟩ := by
rw [log_of_ne_zero hx.ne']
congr
exact abs_of_pos hx
theorem exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = |x| := by
rw [log_of_ne_zero hx, ← coe_expOrderIso_apply, OrderIso.apply_symm_apply, Subtype.coe_mk]
theorem exp_log (hx : 0 < x) : exp (log x) = x := by
rw [exp_log_eq_abs hx.ne']
exact abs_of_pos hx
theorem exp_log_of_neg (hx : x < 0) : exp (log x) = -x := by
rw [exp_log_eq_abs (ne_of_lt hx)]
exact abs_of_neg hx
theorem le_exp_log (x : ℝ) : x ≤ exp (log x) := by
by_cases h_zero : x = 0
· rw [h_zero, log, dif_pos rfl, exp_zero]
exact zero_le_one
· rw [exp_log_eq_abs h_zero]
exact le_abs_self _
@[simp]
theorem log_exp (x : ℝ) : log (exp x) = x :=
exp_injective <| exp_log (exp_pos x)
theorem exp_one_mul_le_exp {x : ℝ} : exp 1 * x ≤ exp x := by
by_cases hx0 : x ≤ 0
· apply le_trans (mul_nonpos_of_nonneg_of_nonpos (exp_pos 1).le hx0) (exp_nonneg x)
· have h := add_one_le_exp (log x)
rwa [← exp_le_exp, exp_add, exp_log (lt_of_not_le hx0), mul_comm] at h
theorem two_mul_le_exp {x : ℝ} : 2 * x ≤ exp x := by
by_cases hx0 : x < 0
· exact le_trans (mul_nonpos_of_nonneg_of_nonpos (by simp only [Nat.ofNat_nonneg]) hx0.le)
(exp_nonneg x)
· apply le_trans (mul_le_mul_of_nonneg_right _ (le_of_not_lt hx0)) exp_one_mul_le_exp
have := Real.add_one_le_exp 1
rwa [one_add_one_eq_two] at this
theorem surjOn_log : SurjOn log (Ioi 0) univ := fun x _ => ⟨exp x, exp_pos x, log_exp x⟩
theorem log_surjective : Surjective log := fun x => ⟨exp x, log_exp x⟩
@[simp]
theorem range_log : range log = univ :=
log_surjective.range_eq
@[simp]
theorem log_zero : log 0 = 0 :=
dif_pos rfl
@[simp]
theorem log_one : log 1 = 0 :=
exp_injective <| by rw [exp_log zero_lt_one, exp_zero]
/-- This holds true for all `x : ℝ` because of the junk values `0 / 0 = 0` and `log 0 = 0`. -/
@[simp] lemma log_div_self (x : ℝ) : log (x / x) = 0 := by
obtain rfl | hx := eq_or_ne x 0 <;> simp [*]
@[simp]
theorem log_abs (x : ℝ) : log |x| = log x := by
by_cases h : x = 0
· simp [h]
· rw [← exp_eq_exp, exp_log_eq_abs h, exp_log_eq_abs (abs_pos.2 h).ne', abs_abs]
@[simp]
theorem log_neg_eq_log (x : ℝ) : log (-x) = log x := by rw [← log_abs x, ← log_abs (-x), abs_neg]
theorem sinh_log {x : ℝ} (hx : 0 < x) : sinh (log x) = (x - x⁻¹) / 2 := by
rw [sinh_eq, exp_neg, exp_log hx]
theorem cosh_log {x : ℝ} (hx : 0 < x) : cosh (log x) = (x + x⁻¹) / 2 := by
rw [cosh_eq, exp_neg, exp_log hx]
theorem surjOn_log' : SurjOn log (Iio 0) univ := fun x _ =>
⟨-exp x, neg_lt_zero.2 <| exp_pos x, by rw [log_neg_eq_log, log_exp]⟩
theorem log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y :=
exp_injective <| by
rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul]
theorem log_div (hx : x ≠ 0) (hy : y ≠ 0) : log (x / y) = log x - log y :=
exp_injective <| by
rw [exp_log_eq_abs (div_ne_zero hx hy), exp_sub, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_div]
@[simp]
theorem log_inv (x : ℝ) : log x⁻¹ = -log x := by
by_cases hx : x = 0; · simp [hx]
rw [← exp_eq_exp, exp_log_eq_abs (inv_ne_zero hx), exp_neg, exp_log_eq_abs hx, abs_inv]
theorem log_le_log_iff (h : 0 < x) (h₁ : 0 < y) : log x ≤ log y ↔ x ≤ y := by
rw [← exp_le_exp, exp_log h, exp_log h₁]
@[gcongr, bound]
lemma log_le_log (hx : 0 < x) (hxy : x ≤ y) : log x ≤ log y :=
(log_le_log_iff hx (hx.trans_le hxy)).2 hxy
@[gcongr, bound]
theorem log_lt_log (hx : 0 < x) (h : x < y) : log x < log y := by
rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)]
theorem log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by
rw [← exp_lt_exp, exp_log hx, exp_log hy]
theorem log_le_iff_le_exp (hx : 0 < x) : log x ≤ y ↔ x ≤ exp y := by rw [← exp_le_exp, exp_log hx]
theorem log_lt_iff_lt_exp (hx : 0 < x) : log x < y ↔ x < exp y := by rw [← exp_lt_exp, exp_log hx]
theorem le_log_iff_exp_le (hy : 0 < y) : x ≤ log y ↔ exp x ≤ y := by rw [← exp_le_exp, exp_log hy]
theorem lt_log_iff_exp_lt (hy : 0 < y) : x < log y ↔ exp x < y := by rw [← exp_lt_exp, exp_log hy]
theorem log_pos_iff (hx : 0 ≤ x) : 0 < log x ↔ 1 < x := by
rcases hx.eq_or_lt with (rfl | hx)
· simp [le_refl, zero_le_one]
rw [← log_one]
exact log_lt_log_iff zero_lt_one hx
@[bound]
theorem log_pos (hx : 1 < x) : 0 < log x :=
(log_pos_iff (lt_trans zero_lt_one hx).le).2 hx
theorem log_pos_of_lt_neg_one (hx : x < -1) : 0 < log x := by
rw [← neg_neg x, log_neg_eq_log]
have : 1 < -x := by linarith
exact log_pos this
theorem log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by
rw [← log_one]
exact log_lt_log_iff h zero_lt_one
@[bound]
theorem log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 :=
(log_neg_iff h0).2 h1
theorem log_neg_of_lt_zero (h0 : x < 0) (h1 : -1 < x) : log x < 0 := by
rw [← neg_neg x, log_neg_eq_log]
have h0' : 0 < -x := by linarith
have h1' : -x < 1 := by linarith
exact log_neg h0' h1'
theorem log_nonneg_iff (hx : 0 < x) : 0 ≤ log x ↔ 1 ≤ x := by rw [← not_lt, log_neg_iff hx, not_lt]
@[bound]
theorem log_nonneg (hx : 1 ≤ x) : 0 ≤ log x :=
(log_nonneg_iff (zero_lt_one.trans_le hx)).2 hx
theorem log_nonpos_iff (hx : 0 ≤ x) : log x ≤ 0 ↔ x ≤ 1 := by
rcases hx.eq_or_lt with (rfl | hx)
· simp [le_refl, zero_le_one]
rw [← not_lt, log_pos_iff hx.le, not_lt]
@[deprecated (since := "2025-01-16")]
alias log_nonpos_iff' := log_nonpos_iff
@[bound]
theorem log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 :=
(log_nonpos_iff hx).2 h'x
theorem log_natCast_nonneg (n : ℕ) : 0 ≤ log n := by
if hn : n = 0 then
simp [hn]
else
have : (1 : ℝ) ≤ n := mod_cast Nat.one_le_of_lt <| Nat.pos_of_ne_zero hn
exact log_nonneg this
theorem log_neg_natCast_nonneg (n : ℕ) : 0 ≤ log (-n) := by
rw [← log_neg_eq_log, neg_neg]
exact log_natCast_nonneg _
theorem log_intCast_nonneg (n : ℤ) : 0 ≤ log n := by
cases lt_trichotomy 0 n with
| inl hn =>
have : (1 : ℝ) ≤ n := mod_cast hn
exact log_nonneg this
| inr hn =>
cases hn with
| inl hn => simp [hn.symm]
| inr hn =>
have : (1 : ℝ) ≤ -n := by rw [← neg_zero, ← lt_neg] at hn; exact mod_cast hn
rw [← log_neg_eq_log]
exact log_nonneg this
theorem strictMonoOn_log : StrictMonoOn log (Set.Ioi 0) := fun _ hx _ _ hxy => log_lt_log hx hxy
theorem strictAntiOn_log : StrictAntiOn log (Set.Iio 0) := by
rintro x (hx : x < 0) y (hy : y < 0) hxy
rw [← log_abs y, ← log_abs x]
refine log_lt_log (abs_pos.2 hy.ne) ?_
rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff]
theorem log_injOn_pos : Set.InjOn log (Set.Ioi 0) :=
strictMonoOn_log.injOn
theorem log_lt_sub_one_of_pos (hx1 : 0 < x) (hx2 : x ≠ 1) : log x < x - 1 := by
have h : log x ≠ 0 := by
rwa [← log_one, log_injOn_pos.ne_iff hx1]
exact mem_Ioi.mpr zero_lt_one
linarith [add_one_lt_exp h, exp_log hx1]
theorem eq_one_of_pos_of_log_eq_zero {x : ℝ} (h₁ : 0 < x) (h₂ : log x = 0) : x = 1 :=
log_injOn_pos (Set.mem_Ioi.2 h₁) (Set.mem_Ioi.2 zero_lt_one) (h₂.trans Real.log_one.symm)
theorem log_ne_zero_of_pos_of_ne_one {x : ℝ} (hx_pos : 0 < x) (hx : x ≠ 1) : log x ≠ 0 :=
mt (eq_one_of_pos_of_log_eq_zero hx_pos) hx
@[simp]
theorem log_eq_zero {x : ℝ} : log x = 0 ↔ x = 0 ∨ x = 1 ∨ x = -1 := by
constructor
· intro h
rcases lt_trichotomy x 0 with (x_lt_zero | rfl | x_gt_zero)
· refine Or.inr (Or.inr (neg_eq_iff_eq_neg.mp ?_))
rw [← log_neg_eq_log x] at h
exact eq_one_of_pos_of_log_eq_zero (neg_pos.mpr x_lt_zero) h
· exact Or.inl rfl
· exact Or.inr (Or.inl (eq_one_of_pos_of_log_eq_zero x_gt_zero h))
· rintro (rfl | rfl | rfl) <;> simp only [log_one, log_zero, log_neg_eq_log]
theorem log_ne_zero {x : ℝ} : log x ≠ 0 ↔ x ≠ 0 ∧ x ≠ 1 ∧ x ≠ -1 := by
simpa only [not_or] using log_eq_zero.not
@[simp]
theorem log_pow (x : ℝ) (n : ℕ) : log (x ^ n) = n * log x := by
induction n with
| zero => simp
| succ n ih =>
rcases eq_or_ne x 0 with (rfl | hx)
· simp
· rw [pow_succ, log_mul (pow_ne_zero _ hx) hx, ih, Nat.cast_succ, add_mul, one_mul]
@[simp]
theorem log_zpow (x : ℝ) (n : ℤ) : log (x ^ n) = n * log x := by
cases n
· rw [Int.ofNat_eq_coe, zpow_natCast, log_pow, Int.cast_natCast]
· rw [zpow_negSucc, log_inv, log_pow, Int.cast_negSucc, Nat.cast_add_one, neg_mul_eq_neg_mul]
theorem log_sqrt {x : ℝ} (hx : 0 ≤ x) : log (√x) = log x / 2 := by
rw [eq_div_iff, mul_comm, ← Nat.cast_two, ← log_pow, sq_sqrt hx]
exact two_ne_zero
theorem log_le_sub_one_of_pos {x : ℝ} (hx : 0 < x) : log x ≤ x - 1 := by
rw [le_sub_iff_add_le]
convert add_one_le_exp (log x)
rw [exp_log hx]
lemma one_sub_inv_le_log_of_pos (hx : 0 < x) : 1 - x⁻¹ ≤ log x := by
simpa [add_comm] using log_le_sub_one_of_pos (inv_pos.2 hx)
/-- See `Real.log_le_sub_one_of_pos` for the stronger version when `x ≠ 0`. -/
lemma log_le_self (hx : 0 ≤ x) : log x ≤ x := by
obtain rfl | hx := hx.eq_or_lt
· simp
· exact (log_le_sub_one_of_pos hx).trans (by linarith)
/-- See `Real.one_sub_inv_le_log_of_pos` for the stronger version when `x ≠ 0`. -/
lemma neg_inv_le_log (hx : 0 ≤ x) : -x⁻¹ ≤ log x := by
rw [neg_le, ← log_inv]; exact log_le_self <| inv_nonneg.2 hx
/-- Bound for `|log x * x|` in the interval `(0, 1]`. -/
theorem abs_log_mul_self_lt (x : ℝ) (h1 : 0 < x) (h2 : x ≤ 1) : |log x * x| < 1 := by
have : 0 < 1 / x := by simpa only [one_div, inv_pos] using h1
replace := log_le_sub_one_of_pos this
replace : log (1 / x) < 1 / x := by linarith
rw [log_div one_ne_zero h1.ne', log_one, zero_sub, lt_div_iff₀ h1] at this
have aux : 0 ≤ -log x * x := by
refine mul_nonneg ?_ h1.le
rw [← log_inv]
apply log_nonneg
rw [← le_inv_comm₀ h1 zero_lt_one, inv_one]
exact h2
rw [← abs_of_nonneg aux, neg_mul, abs_neg] at this
exact this
/-- The real logarithm function tends to `+∞` at `+∞`. -/
theorem tendsto_log_atTop : Tendsto log atTop atTop :=
tendsto_comp_exp_atTop.1 <| by simpa only [log_exp] using tendsto_id
lemma tendsto_log_nhdsGT_zero : Tendsto log (𝓝[>] 0) atBot := by
simpa [← tendsto_comp_exp_atBot] using tendsto_id
@[deprecated (since := "2025-03-18")]
alias tendsto_log_nhdsWithin_zero_right := tendsto_log_nhdsGT_zero
theorem tendsto_log_nhdsNE_zero : Tendsto log (𝓝[≠] 0) atBot := by
simpa [comp_def] using tendsto_log_nhdsGT_zero.comp tendsto_abs_nhdsNE_zero
@[deprecated (since := "2025-03-18")]
alias tendsto_log_nhdsWithin_zero := tendsto_log_nhdsNE_zero
lemma tendsto_log_nhdsLT_zero : Tendsto log (𝓝[<] 0) atBot :=
tendsto_log_nhdsNE_zero.mono_left <| nhdsWithin_mono _ fun _ h ↦ ne_of_lt h
@[deprecated (since := "2025-03-18")]
alias tendsto_log_nhdsWithin_zero_left := tendsto_log_nhdsLT_zero
theorem continuousOn_log : ContinuousOn log {0}ᶜ := by
simp +unfoldPartialApp only [continuousOn_iff_continuous_restrict,
restrict]
conv in log _ => rw [log_of_ne_zero (show (x : ℝ) ≠ 0 from x.2)]
exact expOrderIso.symm.continuous.comp (continuous_subtype_val.norm.subtype_mk _)
/-- The real logarithm is continuous as a function from nonzero reals. -/
@[fun_prop]
theorem continuous_log : Continuous fun x : { x : ℝ // x ≠ 0 } => log x :=
continuousOn_iff_continuous_restrict.1 <| continuousOn_log.mono fun _ => id
/-- The real logarithm is continuous as a function from positive reals. -/
@[fun_prop]
theorem continuous_log' : Continuous fun x : { x : ℝ // 0 < x } => log x :=
continuousOn_iff_continuous_restrict.1 <| continuousOn_log.mono fun _ hx => ne_of_gt hx
theorem continuousAt_log (hx : x ≠ 0) : ContinuousAt log x :=
(continuousOn_log x hx).continuousAt <| isOpen_compl_singleton.mem_nhds hx
@[simp]
theorem continuousAt_log_iff : ContinuousAt log x ↔ x ≠ 0 := by
refine ⟨?_, continuousAt_log⟩
rintro h rfl
exact not_tendsto_nhds_of_tendsto_atBot tendsto_log_nhdsNE_zero _ <|
h.tendsto.mono_left nhdsWithin_le_nhds
theorem log_prod {α : Type*} (s : Finset α) (f : α → ℝ) (hf : ∀ x ∈ s, f x ≠ 0) :
log (∏ i ∈ s, f i) = ∑ i ∈ s, log (f i) := by
induction' s using Finset.cons_induction_on with a s ha ih
· simp
· rw [Finset.forall_mem_cons] at hf
simp [ih hf.2, log_mul hf.1 (Finset.prod_ne_zero_iff.2 hf.2)]
protected theorem _root_.Finsupp.log_prod {α β : Type*} [Zero β] (f : α →₀ β) (g : α → β → ℝ)
(hg : ∀ a, g a (f a) = 0 → f a = 0) : log (f.prod g) = f.sum fun a b ↦ log (g a b) :=
log_prod _ _ fun _x hx h₀ ↦ Finsupp.mem_support_iff.1 hx <| hg _ h₀
theorem log_nat_eq_sum_factorization (n : ℕ) :
log n = n.factorization.sum fun p t => t * log p := by
rcases eq_or_ne n 0 with (rfl | hn)
· simp -- relies on junk values of `log` and `Nat.factorization`
· simp only [← log_pow, ← Nat.cast_pow]
rw [← Finsupp.log_prod, ← Nat.cast_finsuppProd, Nat.factorization_prod_pow_eq_self hn]
intro p hp
rw [pow_eq_zero (Nat.cast_eq_zero.1 hp), Nat.factorization_zero_right]
theorem tendsto_pow_log_div_mul_add_atTop (a b : ℝ) (n : ℕ) (ha : a ≠ 0) :
Tendsto (fun x => log x ^ n / (a * x + b)) atTop (𝓝 0) :=
((tendsto_div_pow_mul_exp_add_atTop a b n ha.symm).comp tendsto_log_atTop).congr' <| by
filter_upwards [eventually_gt_atTop (0 : ℝ)] with x hx using by simp [exp_log hx]
theorem isLittleO_pow_log_id_atTop {n : ℕ} : (fun x => log x ^ n) =o[atTop] id := by
rw [Asymptotics.isLittleO_iff_tendsto']
· simpa using tendsto_pow_log_div_mul_add_atTop 1 0 n one_ne_zero
filter_upwards [eventually_ne_atTop (0 : ℝ)] with x h₁ h₂ using (h₁ h₂).elim
theorem isLittleO_log_id_atTop : log =o[atTop] id :=
isLittleO_pow_log_id_atTop.congr_left fun _ => pow_one _
theorem isLittleO_const_log_atTop {c : ℝ} : (fun _ => c) =o[atTop] log := by
refine Asymptotics.isLittleO_of_tendsto' ?_
<| Tendsto.div_atTop (a := c) (by simp) tendsto_log_atTop
filter_upwards [eventually_gt_atTop 1] with x hx
aesop (add safe forward log_pos)
/-- `Real.exp` as a `PartialHomeomorph` with `source = univ` and `target = {z | 0 < z}`. -/
@[simps] noncomputable def expPartialHomeomorph : PartialHomeomorph ℝ ℝ where
toFun := Real.exp
invFun := Real.log
source := univ
target := Ioi (0 : ℝ)
map_source' x _ := exp_pos x
map_target' _ _ := mem_univ _
left_inv' _ _ := by simp
right_inv' _ hx := exp_log hx
open_source := isOpen_univ
open_target := isOpen_Ioi
continuousOn_toFun := continuousOn_exp
continuousOn_invFun x hx := (continuousAt_log (ne_of_gt hx)).continuousWithinAt
end Real
section Continuity
open Real
variable {α : Type*}
theorem Filter.Tendsto.log {f : α → ℝ} {l : Filter α} {x : ℝ} (h : Tendsto f l (𝓝 x)) (hx : x ≠ 0) :
Tendsto (fun x => log (f x)) l (𝓝 (log x)) :=
(continuousAt_log hx).tendsto.comp h
variable [TopologicalSpace α] {f : α → ℝ} {s : Set α} {a : α}
@[fun_prop]
theorem Continuous.log (hf : Continuous f) (h₀ : ∀ x, f x ≠ 0) : Continuous fun x => log (f x) :=
continuousOn_log.comp_continuous hf h₀
@[fun_prop]
nonrec theorem ContinuousAt.log (hf : ContinuousAt f a) (h₀ : f a ≠ 0) :
ContinuousAt (fun x => log (f x)) a :=
hf.log h₀
nonrec theorem ContinuousWithinAt.log (hf : ContinuousWithinAt f s a) (h₀ : f a ≠ 0) :
ContinuousWithinAt (fun x => log (f x)) s a :=
hf.log h₀
@[fun_prop]
theorem ContinuousOn.log (hf : ContinuousOn f s) (h₀ : ∀ x ∈ s, f x ≠ 0) :
ContinuousOn (fun x => log (f x)) s := fun x hx => (hf x hx).log (h₀ x hx)
end Continuity
section TendstoCompAddSub
open Filter
namespace Real
theorem tendsto_log_comp_add_sub_log (y : ℝ) :
Tendsto (fun x : ℝ => log (x + y) - log x) atTop (𝓝 0) := by
have : Tendsto (fun x ↦ 1 + y / x) atTop (𝓝 (1 + 0)) :=
tendsto_const_nhds.add (tendsto_const_nhds.div_atTop tendsto_id)
rw [← comap_exp_nhds_exp, exp_zero, tendsto_comap_iff, ← add_zero (1 : ℝ)]
refine this.congr' ?_
filter_upwards [eventually_gt_atTop (0 : ℝ), eventually_gt_atTop (-y)] with x hx₀ hxy
rw [comp_apply, exp_sub, exp_log, exp_log, one_add_div] <;> linarith
theorem tendsto_log_nat_add_one_sub_log : Tendsto (fun k : ℕ => log (k + 1) - log k) atTop (𝓝 0) :=
(tendsto_log_comp_add_sub_log 1).comp tendsto_natCast_atTop_atTop
end Real
end TendstoCompAddSub
namespace Mathlib.Meta.Positivity
open Lean.Meta Qq
variable {e : ℝ} {d : ℕ}
lemma log_nonneg_of_isNat {n : ℕ} (h : NormNum.IsNat e n) : 0 ≤ Real.log (e : ℝ) := by
rw [NormNum.IsNat.to_eq h rfl]
exact Real.log_natCast_nonneg _
lemma log_pos_of_isNat {n : ℕ} (h : NormNum.IsNat e n) (w : Nat.blt 1 n = true) :
0 < Real.log (e : ℝ) := by
rw [NormNum.IsNat.to_eq h rfl]
apply Real.log_pos
simpa using w
lemma log_nonneg_of_isNegNat {n : ℕ} (h : NormNum.IsInt e (.negOfNat n)) :
0 ≤ Real.log (e : ℝ) := by
rw [NormNum.IsInt.neg_to_eq h rfl]
exact Real.log_neg_natCast_nonneg _
lemma log_pos_of_isNegNat {n : ℕ} (h : NormNum.IsInt e (.negOfNat n)) (w : Nat.blt 1 n = true) :
0 < Real.log (e : ℝ) := by
| rw [NormNum.IsInt.neg_to_eq h rfl]
rw [Real.log_neg_eq_log]
apply Real.log_pos
simpa using w
| Mathlib/Analysis/SpecialFunctions/Log/Basic.lean | 500 | 504 |
/-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import Mathlib.Analysis.InnerProductSpace.Continuous
import Mathlib.Analysis.Normed.Module.Dual
import Mathlib.MeasureTheory.Function.AEEqOfLIntegral
import Mathlib.MeasureTheory.Function.StronglyMeasurable.Lp
import Mathlib.MeasureTheory.Integral.Bochner.ContinuousLinearMap
import Mathlib.Order.Filter.Ring
/-! # From equality of integrals to equality of functions
This file provides various statements of the general form "if two functions have the same integral
on all sets, then they are equal almost everywhere".
The different lemmas use various hypotheses on the class of functions, on the target space or on the
possible finiteness of the measure.
This file is about Bochner integrals. See the file `AEEqOfLIntegral` for Lebesgue integrals.
## Main statements
All results listed below apply to two functions `f, g`, together with two main hypotheses,
* `f` and `g` are integrable on all measurable sets with finite measure,
* for all measurable sets `s` with finite measure, `∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ`.
The conclusion is then `f =ᵐ[μ] g`. The main lemmas are:
* `ae_eq_of_forall_setIntegral_eq_of_sigmaFinite`: case of a sigma-finite measure.
* `AEFinStronglyMeasurable.ae_eq_of_forall_setIntegral_eq`: for functions which are
`AEFinStronglyMeasurable`.
* `Lp.ae_eq_of_forall_setIntegral_eq`: for elements of `Lp`, for `0 < p < ∞`.
* `Integrable.ae_eq_of_forall_setIntegral_eq`: for integrable functions.
For each of these results, we also provide a lemma about the equality of one function and 0. For
example, `Lp.ae_eq_zero_of_forall_setIntegral_eq_zero`.
Generally useful lemmas which are not related to integrals:
* `ae_eq_zero_of_forall_inner`: if for all constants `c`, `fun x => inner c (f x) =ᵐ[μ] 0` then
`f =ᵐ[μ] 0`.
* `ae_eq_zero_of_forall_dual`: if for all constants `c` in the dual space,
`fun x => c (f x) =ᵐ[μ] 0` then `f =ᵐ[μ] 0`.
-/
open MeasureTheory TopologicalSpace NormedSpace Filter
open scoped ENNReal NNReal MeasureTheory Topology
namespace MeasureTheory
section AeEqOfForall
variable {α E 𝕜 : Type*} {m : MeasurableSpace α} {μ : Measure α} [RCLike 𝕜]
theorem ae_eq_zero_of_forall_inner [NormedAddCommGroup E] [InnerProductSpace 𝕜 E]
[SecondCountableTopology E] {f : α → E} (hf : ∀ c : E, (fun x => (inner c (f x) : 𝕜)) =ᵐ[μ] 0) :
f =ᵐ[μ] 0 := by
let s := denseSeq E
have hs : DenseRange s := denseRange_denseSeq E
have hf' : ∀ᵐ x ∂μ, ∀ n : ℕ, inner (s n) (f x) = (0 : 𝕜) := ae_all_iff.mpr fun n => hf (s n)
refine hf'.mono fun x hx => ?_
rw [Pi.zero_apply, ← @inner_self_eq_zero 𝕜]
have h_closed : IsClosed {c : E | inner c (f x) = (0 : 𝕜)} :=
isClosed_eq (continuous_id.inner continuous_const) continuous_const
exact @isClosed_property ℕ E _ s (fun c => inner c (f x) = (0 : 𝕜)) hs h_closed hx _
local notation "⟪" x ", " y "⟫" => y x
variable (𝕜)
theorem ae_eq_zero_of_forall_dual_of_isSeparable [NormedAddCommGroup E] [NormedSpace 𝕜 E]
{t : Set E} (ht : TopologicalSpace.IsSeparable t) {f : α → E}
(hf : ∀ c : Dual 𝕜 E, (fun x => ⟪f x, c⟫) =ᵐ[μ] 0) (h't : ∀ᵐ x ∂μ, f x ∈ t) : f =ᵐ[μ] 0 := by
rcases ht with ⟨d, d_count, hd⟩
haveI : Encodable d := d_count.toEncodable
have : ∀ x : d, ∃ g : E →L[𝕜] 𝕜, ‖g‖ ≤ 1 ∧ g x = ‖(x : E)‖ :=
fun x => exists_dual_vector'' 𝕜 (x : E)
choose s hs using this
have A : ∀ a : E, a ∈ t → (∀ x, ⟪a, s x⟫ = (0 : 𝕜)) → a = 0 := by
intro a hat ha
contrapose! ha
have a_pos : 0 < ‖a‖ := by simp only [ha, norm_pos_iff, Ne, not_false_iff]
have a_mem : a ∈ closure d := hd hat
obtain ⟨x, hx⟩ : ∃ x : d, dist a x < ‖a‖ / 2 := by
rcases Metric.mem_closure_iff.1 a_mem (‖a‖ / 2) (half_pos a_pos) with ⟨x, h'x, hx⟩
exact ⟨⟨x, h'x⟩, hx⟩
use x
have I : ‖a‖ / 2 < ‖(x : E)‖ := by
have : ‖a‖ ≤ ‖(x : E)‖ + ‖a - x‖ := norm_le_insert' _ _
have : ‖a - x‖ < ‖a‖ / 2 := by rwa [dist_eq_norm] at hx
linarith
intro h
apply lt_irrefl ‖s x x‖
calc
‖s x x‖ = ‖s x (x - a)‖ := by simp only [h, sub_zero, ContinuousLinearMap.map_sub]
_ ≤ 1 * ‖(x : E) - a‖ := ContinuousLinearMap.le_of_opNorm_le _ (hs x).1 _
_ < ‖a‖ / 2 := by rw [one_mul]; rwa [dist_eq_norm'] at hx
_ < ‖(x : E)‖ := I
_ = ‖s x x‖ := by rw [(hs x).2, RCLike.norm_coe_norm]
have hfs : ∀ y : d, ∀ᵐ x ∂μ, ⟪f x, s y⟫ = (0 : 𝕜) := fun y => hf (s y)
have hf' : ∀ᵐ x ∂μ, ∀ y : d, ⟪f x, s y⟫ = (0 : 𝕜) := by rwa [ae_all_iff]
filter_upwards [hf', h't] with x hx h'x
exact A (f x) h'x hx
theorem ae_eq_zero_of_forall_dual [NormedAddCommGroup E] [NormedSpace 𝕜 E]
[SecondCountableTopology E] {f : α → E} (hf : ∀ c : Dual 𝕜 E, (fun x => ⟪f x, c⟫) =ᵐ[μ] 0) :
f =ᵐ[μ] 0 :=
ae_eq_zero_of_forall_dual_of_isSeparable 𝕜 (.of_separableSpace Set.univ) hf
(Eventually.of_forall fun _ => Set.mem_univ _)
variable {𝕜}
end AeEqOfForall
variable {α E : Type*} {m m0 : MeasurableSpace α} {μ : Measure α}
[NormedAddCommGroup E] [NormedSpace ℝ E] [CompleteSpace E] {p : ℝ≥0∞}
section AeEqOfForallSetIntegralEq
section Real
variable {f : α → ℝ}
theorem ae_nonneg_of_forall_setIntegral_nonneg (hf : Integrable f μ)
(hf_zero : ∀ s, MeasurableSet s → μ s < ∞ → 0 ≤ ∫ x in s, f x ∂μ) : 0 ≤ᵐ[μ] f := by
simp_rw [EventuallyLE, Pi.zero_apply]
rw [ae_const_le_iff_forall_lt_measure_zero]
intro b hb_neg
let s := {x | f x ≤ b}
have hs : NullMeasurableSet s μ := nullMeasurableSet_le hf.1.aemeasurable aemeasurable_const
have mus : μ s < ∞ := Integrable.measure_le_lt_top hf hb_neg
have h_int_gt : (∫ x in s, f x ∂μ) ≤ b * μ.real s := by
have h_const_le : (∫ x in s, f x ∂μ) ≤ ∫ _ in s, b ∂μ := by
refine setIntegral_mono_ae_restrict hf.integrableOn (integrableOn_const.mpr (Or.inr mus)) ?_
rw [EventuallyLE, ae_restrict_iff₀ (hs.mono μ.restrict_le_self)]
exact Eventually.of_forall fun x hxs => hxs
rwa [setIntegral_const, smul_eq_mul, mul_comm] at h_const_le
contrapose! h_int_gt with H
calc
b * μ.real s < 0 := mul_neg_of_neg_of_pos hb_neg <| ENNReal.toReal_pos H mus.ne
_ ≤ ∫ x in s, f x ∂μ := by
rw [← μ.restrict_toMeasurable mus.ne]
exact hf_zero _ (measurableSet_toMeasurable ..) (by rwa [measure_toMeasurable])
theorem ae_le_of_forall_setIntegral_le {f g : α → ℝ} (hf : Integrable f μ) (hg : Integrable g μ)
(hf_le : ∀ s, MeasurableSet s → μ s < ∞ → (∫ x in s, f x ∂μ) ≤ ∫ x in s, g x ∂μ) :
f ≤ᵐ[μ] g := by
rw [← eventually_sub_nonneg]
refine ae_nonneg_of_forall_setIntegral_nonneg (hg.sub hf) fun s hs => ?_
rw [integral_sub' hg.integrableOn hf.integrableOn, sub_nonneg]
exact hf_le s hs
theorem ae_nonneg_restrict_of_forall_setIntegral_nonneg_inter {f : α → ℝ} {t : Set α}
(hf : IntegrableOn f t μ)
(hf_zero : ∀ s, MeasurableSet s → μ (s ∩ t) < ∞ → 0 ≤ ∫ x in s ∩ t, f x ∂μ) :
0 ≤ᵐ[μ.restrict t] f := by
refine ae_nonneg_of_forall_setIntegral_nonneg hf fun s hs h's => ?_
simp_rw [Measure.restrict_restrict hs]
apply hf_zero s hs
rwa [Measure.restrict_apply hs] at h's
theorem ae_nonneg_of_forall_setIntegral_nonneg_of_sigmaFinite [SigmaFinite μ] {f : α → ℝ}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s, MeasurableSet s → μ s < ∞ → 0 ≤ ∫ x in s, f x ∂μ) : 0 ≤ᵐ[μ] f := by
apply ae_of_forall_measure_lt_top_ae_restrict
intro t t_meas t_lt_top
apply ae_nonneg_restrict_of_forall_setIntegral_nonneg_inter (hf_int_finite t t_meas t_lt_top)
intro s s_meas _
exact
hf_zero _ (s_meas.inter t_meas)
(lt_of_le_of_lt (measure_mono (Set.inter_subset_right)) t_lt_top)
theorem AEFinStronglyMeasurable.ae_nonneg_of_forall_setIntegral_nonneg {f : α → ℝ}
(hf : AEFinStronglyMeasurable f μ)
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s, MeasurableSet s → μ s < ∞ → 0 ≤ ∫ x in s, f x ∂μ) : 0 ≤ᵐ[μ] f := by
let t := hf.sigmaFiniteSet
suffices 0 ≤ᵐ[μ.restrict t] f from
ae_of_ae_restrict_of_ae_restrict_compl _ this hf.ae_eq_zero_compl.symm.le
haveI : SigmaFinite (μ.restrict t) := hf.sigmaFinite_restrict
refine
ae_nonneg_of_forall_setIntegral_nonneg_of_sigmaFinite (fun s hs hμts => ?_) fun s hs hμts => ?_
· rw [IntegrableOn, Measure.restrict_restrict hs]
rw [Measure.restrict_apply hs] at hμts
exact hf_int_finite (s ∩ t) (hs.inter hf.measurableSet) hμts
· rw [Measure.restrict_restrict hs]
rw [Measure.restrict_apply hs] at hμts
exact hf_zero (s ∩ t) (hs.inter hf.measurableSet) hμts
theorem ae_nonneg_restrict_of_forall_setIntegral_nonneg {f : α → ℝ}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s, MeasurableSet s → μ s < ∞ → 0 ≤ ∫ x in s, f x ∂μ) {t : Set α}
(ht : MeasurableSet t) (hμt : μ t ≠ ∞) : 0 ≤ᵐ[μ.restrict t] f := by
refine
ae_nonneg_restrict_of_forall_setIntegral_nonneg_inter
(hf_int_finite t ht (lt_top_iff_ne_top.mpr hμt)) fun s hs _ => ?_
refine hf_zero (s ∩ t) (hs.inter ht) ?_
exact (measure_mono Set.inter_subset_right).trans_lt (lt_top_iff_ne_top.mpr hμt)
theorem ae_eq_zero_restrict_of_forall_setIntegral_eq_zero_real {f : α → ℝ}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) {t : Set α}
(ht : MeasurableSet t) (hμt : μ t ≠ ∞) : f =ᵐ[μ.restrict t] 0 := by
suffices h_and : f ≤ᵐ[μ.restrict t] 0 ∧ 0 ≤ᵐ[μ.restrict t] f from
h_and.1.mp (h_and.2.mono fun x hx1 hx2 => le_antisymm hx2 hx1)
refine
⟨?_,
ae_nonneg_restrict_of_forall_setIntegral_nonneg hf_int_finite
(fun s hs hμs => (hf_zero s hs hμs).symm.le) ht hμt⟩
suffices h_neg : 0 ≤ᵐ[μ.restrict t] -f by
refine h_neg.mono fun x hx => ?_
rw [Pi.neg_apply] at hx
simpa using hx
refine
ae_nonneg_restrict_of_forall_setIntegral_nonneg (fun s hs hμs => (hf_int_finite s hs hμs).neg)
(fun s hs hμs => ?_) ht hμt
simp_rw [Pi.neg_apply]
rw [integral_neg, neg_nonneg]
exact (hf_zero s hs hμs).le
end Real
theorem ae_eq_zero_restrict_of_forall_setIntegral_eq_zero {f : α → E}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) {t : Set α}
(ht : MeasurableSet t) (hμt : μ t ≠ ∞) : f =ᵐ[μ.restrict t] 0 := by
rcases (hf_int_finite t ht hμt.lt_top).aestronglyMeasurable.isSeparable_ae_range with
⟨u, u_sep, hu⟩
refine ae_eq_zero_of_forall_dual_of_isSeparable ℝ u_sep (fun c => ?_) hu
refine ae_eq_zero_restrict_of_forall_setIntegral_eq_zero_real ?_ ?_ ht hμt
· intro s hs hμs
exact ContinuousLinearMap.integrable_comp c (hf_int_finite s hs hμs)
· intro s hs hμs
rw [ContinuousLinearMap.integral_comp_comm c (hf_int_finite s hs hμs), hf_zero s hs hμs]
exact ContinuousLinearMap.map_zero _
theorem ae_eq_restrict_of_forall_setIntegral_eq {f g : α → E}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hg_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn g s μ)
(hfg_zero : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ)
{t : Set α} (ht : MeasurableSet t) (hμt : μ t ≠ ∞) : f =ᵐ[μ.restrict t] g := by
rw [← sub_ae_eq_zero]
have hfg' : ∀ s : Set α, MeasurableSet s → μ s < ∞ → (∫ x in s, (f - g) x ∂μ) = 0 := by
intro s hs hμs
rw [integral_sub' (hf_int_finite s hs hμs) (hg_int_finite s hs hμs)]
exact sub_eq_zero.mpr (hfg_zero s hs hμs)
have hfg_int : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn (f - g) s μ := fun s hs hμs =>
(hf_int_finite s hs hμs).sub (hg_int_finite s hs hμs)
exact ae_eq_zero_restrict_of_forall_setIntegral_eq_zero hfg_int hfg' ht hμt
theorem ae_eq_zero_of_forall_setIntegral_eq_of_sigmaFinite [SigmaFinite μ] {f : α → E}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) : f =ᵐ[μ] 0 := by
let S := spanningSets μ
rw [← @Measure.restrict_univ _ _ μ, ← iUnion_spanningSets μ, EventuallyEq, ae_iff,
Measure.restrict_apply' (MeasurableSet.iUnion (measurableSet_spanningSets μ))]
rw [Set.inter_iUnion, measure_iUnion_null_iff]
intro n
have h_meas_n : MeasurableSet (S n) := measurableSet_spanningSets μ n
have hμn : μ (S n) < ∞ := measure_spanningSets_lt_top μ n
rw [← Measure.restrict_apply' h_meas_n]
exact ae_eq_zero_restrict_of_forall_setIntegral_eq_zero hf_int_finite hf_zero h_meas_n hμn.ne
theorem ae_eq_of_forall_setIntegral_eq_of_sigmaFinite [SigmaFinite μ] {f g : α → E}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hg_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn g s μ)
(hfg_eq : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) :
f =ᵐ[μ] g := by
rw [← sub_ae_eq_zero]
have hfg : ∀ s : Set α, MeasurableSet s → μ s < ∞ → (∫ x in s, (f - g) x ∂μ) = 0 := by
intro s hs hμs
rw [integral_sub' (hf_int_finite s hs hμs) (hg_int_finite s hs hμs),
sub_eq_zero.mpr (hfg_eq s hs hμs)]
have hfg_int : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn (f - g) s μ := fun s hs hμs =>
(hf_int_finite s hs hμs).sub (hg_int_finite s hs hμs)
exact ae_eq_zero_of_forall_setIntegral_eq_of_sigmaFinite hfg_int hfg
theorem AEFinStronglyMeasurable.ae_eq_zero_of_forall_setIntegral_eq_zero {f : α → E}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = 0)
(hf : AEFinStronglyMeasurable f μ) : f =ᵐ[μ] 0 := by
let t := hf.sigmaFiniteSet
suffices f =ᵐ[μ.restrict t] 0 from
ae_of_ae_restrict_of_ae_restrict_compl _ this hf.ae_eq_zero_compl
haveI : SigmaFinite (μ.restrict t) := hf.sigmaFinite_restrict
refine ae_eq_zero_of_forall_setIntegral_eq_of_sigmaFinite ?_ ?_
· intro s hs hμs
rw [IntegrableOn, Measure.restrict_restrict hs]
rw [Measure.restrict_apply hs] at hμs
exact hf_int_finite _ (hs.inter hf.measurableSet) hμs
· intro s hs hμs
rw [Measure.restrict_restrict hs]
rw [Measure.restrict_apply hs] at hμs
exact hf_zero _ (hs.inter hf.measurableSet) hμs
theorem AEFinStronglyMeasurable.ae_eq_of_forall_setIntegral_eq {f g : α → E}
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hg_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn g s μ)
(hfg_eq : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ)
(hf : AEFinStronglyMeasurable f μ) (hg : AEFinStronglyMeasurable g μ) : f =ᵐ[μ] g := by
rw [← sub_ae_eq_zero]
have hfg : ∀ s : Set α, MeasurableSet s → μ s < ∞ → (∫ x in s, (f - g) x ∂μ) = 0 := by
intro s hs hμs
rw [integral_sub' (hf_int_finite s hs hμs) (hg_int_finite s hs hμs),
sub_eq_zero.mpr (hfg_eq s hs hμs)]
have hfg_int : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn (f - g) s μ := fun s hs hμs =>
(hf_int_finite s hs hμs).sub (hg_int_finite s hs hμs)
exact (hf.sub hg).ae_eq_zero_of_forall_setIntegral_eq_zero hfg_int hfg
theorem Lp.ae_eq_zero_of_forall_setIntegral_eq_zero (f : Lp E p μ) (hp_ne_zero : p ≠ 0)
(hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) : f =ᵐ[μ] 0 :=
AEFinStronglyMeasurable.ae_eq_zero_of_forall_setIntegral_eq_zero hf_int_finite hf_zero
(Lp.finStronglyMeasurable _ hp_ne_zero hp_ne_top).aefinStronglyMeasurable
theorem Lp.ae_eq_of_forall_setIntegral_eq (f g : Lp E p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞)
(hf_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn f s μ)
(hg_int_finite : ∀ s, MeasurableSet s → μ s < ∞ → IntegrableOn g s μ)
(hfg : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) :
f =ᵐ[μ] g :=
AEFinStronglyMeasurable.ae_eq_of_forall_setIntegral_eq hf_int_finite hg_int_finite hfg
(Lp.finStronglyMeasurable _ hp_ne_zero hp_ne_top).aefinStronglyMeasurable
(Lp.finStronglyMeasurable _ hp_ne_zero hp_ne_top).aefinStronglyMeasurable
theorem ae_eq_zero_of_forall_setIntegral_eq_of_finStronglyMeasurable_trim (hm : m ≤ m0) {f : α → E}
(hf_int_finite : ∀ s, MeasurableSet[m] s → μ s < ∞ → IntegrableOn f s μ)
(hf_zero : ∀ s : Set α, MeasurableSet[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = 0)
(hf : FinStronglyMeasurable f (μ.trim hm)) : f =ᵐ[μ] 0 := by
obtain ⟨t, ht_meas, htf_zero, htμ⟩ := hf.exists_set_sigmaFinite
haveI : SigmaFinite ((μ.restrict t).trim hm) := by rwa [restrict_trim hm μ ht_meas] at htμ
have htf_zero : f =ᵐ[μ.restrict tᶜ] 0 := by
rw [EventuallyEq, ae_restrict_iff' (MeasurableSet.compl (hm _ ht_meas))]
exact Eventually.of_forall htf_zero
have hf_meas_m : StronglyMeasurable[m] f := hf.stronglyMeasurable
suffices f =ᵐ[μ.restrict t] 0 from
ae_of_ae_restrict_of_ae_restrict_compl _ this htf_zero
refine measure_eq_zero_of_trim_eq_zero hm ?_
refine ae_eq_zero_of_forall_setIntegral_eq_of_sigmaFinite ?_ ?_
· intro s hs hμs
unfold IntegrableOn
rw [restrict_trim hm (μ.restrict t) hs, Measure.restrict_restrict (hm s hs)]
rw [← restrict_trim hm μ ht_meas, Measure.restrict_apply hs,
trim_measurableSet_eq hm (hs.inter ht_meas)] at hμs
refine Integrable.trim hm ?_ hf_meas_m
exact hf_int_finite _ (hs.inter ht_meas) hμs
· intro s hs hμs
rw [restrict_trim hm (μ.restrict t) hs, Measure.restrict_restrict (hm s hs)]
rw [← restrict_trim hm μ ht_meas, Measure.restrict_apply hs,
trim_measurableSet_eq hm (hs.inter ht_meas)] at hμs
rw [← integral_trim hm hf_meas_m]
exact hf_zero _ (hs.inter ht_meas) hμs
theorem Integrable.ae_eq_zero_of_forall_setIntegral_eq_zero {f : α → E} (hf : Integrable f μ)
(hf_zero : ∀ s, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) : f =ᵐ[μ] 0 := by
have hf_Lp : MemLp f 1 μ := memLp_one_iff_integrable.mpr hf
let f_Lp := hf_Lp.toLp f
have hf_f_Lp : f =ᵐ[μ] f_Lp := (MemLp.coeFn_toLp hf_Lp).symm
refine hf_f_Lp.trans ?_
refine Lp.ae_eq_zero_of_forall_setIntegral_eq_zero f_Lp one_ne_zero ENNReal.coe_ne_top ?_ ?_
· exact fun s _ _ => Integrable.integrableOn (L1.integrable_coeFn _)
· intro s hs hμs
rw [integral_congr_ae (ae_restrict_of_ae hf_f_Lp.symm)]
exact hf_zero s hs hμs
theorem Integrable.ae_eq_of_forall_setIntegral_eq (f g : α → E) (hf : Integrable f μ)
(hg : Integrable g μ)
(hfg : ∀ s : Set α, MeasurableSet s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) :
f =ᵐ[μ] g := by
rw [← sub_ae_eq_zero]
have hfg' : ∀ s : Set α, MeasurableSet s → μ s < ∞ → (∫ x in s, (f - g) x ∂μ) = 0 := by
intro s hs hμs
rw [integral_sub' hf.integrableOn hg.integrableOn]
exact sub_eq_zero.mpr (hfg s hs hμs)
exact Integrable.ae_eq_zero_of_forall_setIntegral_eq_zero (hf.sub hg) hfg'
variable {β : Type*} [TopologicalSpace β] [MeasurableSpace β] [BorelSpace β]
/-- If an integrable function has zero integral on all closed sets, then it is zero
almost everywhere. -/
lemma ae_eq_zero_of_forall_setIntegral_isClosed_eq_zero {μ : Measure β} {f : β → E}
(hf : Integrable f μ) (h'f : ∀ (s : Set β), IsClosed s → ∫ x in s, f x ∂μ = 0) :
f =ᵐ[μ] 0 := by
suffices ∀ s, MeasurableSet s → ∫ x in s, f x ∂μ = 0 from
hf.ae_eq_zero_of_forall_setIntegral_eq_zero (fun s hs _ ↦ this s hs)
have A : ∀ (t : Set β), MeasurableSet t → ∫ (x : β) in t, f x ∂μ = 0
→ ∫ (x : β) in tᶜ, f x ∂μ = 0 := by
intro t t_meas ht
have I : ∫ x, f x ∂μ = 0 := by rw [← setIntegral_univ]; exact h'f _ isClosed_univ
simpa [ht, I] using integral_add_compl t_meas hf
intro s hs
induction s, hs using MeasurableSet.induction_on_open with
| isOpen U hU => exact compl_compl U ▸ A _ hU.measurableSet.compl (h'f _ hU.isClosed_compl)
| compl s hs ihs => exact A s hs ihs
| iUnion g g_disj g_meas hg => simp [integral_iUnion g_meas g_disj hf.integrableOn, hg]
/-- If an integrable function has zero integral on all compact sets in a sigma-compact space, then
it is zero almost everywhere. -/
lemma ae_eq_zero_of_forall_setIntegral_isCompact_eq_zero
[SigmaCompactSpace β] [R1Space β] {μ : Measure β} {f : β → E} (hf : Integrable f μ)
(h'f : ∀ (s : Set β), IsCompact s → ∫ x in s, f x ∂μ = 0) :
f =ᵐ[μ] 0 := by
apply ae_eq_zero_of_forall_setIntegral_isClosed_eq_zero hf (fun s hs ↦ ?_)
let t : ℕ → Set β := fun n ↦ closure (compactCovering β n) ∩ s
suffices H : Tendsto (fun n ↦ ∫ x in t n, f x ∂μ) atTop (𝓝 (∫ x in s, f x ∂μ)) by
have A : ∀ n, ∫ x in t n, f x ∂μ = 0 :=
fun n ↦ h'f _ ((isCompact_compactCovering β n).closure.inter_right hs)
simp_rw [A, tendsto_const_nhds_iff] at H
exact H.symm
have B : s = ⋃ n, t n := by
rw [← Set.iUnion_inter, iUnion_closure_compactCovering, Set.univ_inter]
rw [B]
apply tendsto_setIntegral_of_monotone
· intros n
exact (isClosed_closure.inter hs).measurableSet
· intros m n hmn
simp only [t, Set.le_iff_subset]
gcongr
· exact hf.integrableOn
/-- If a locally integrable function has zero integral on all compact sets in a sigma-compact space,
then it is zero almost everywhere. -/
lemma ae_eq_zero_of_forall_setIntegral_isCompact_eq_zero'
[SigmaCompactSpace β] [R1Space β] {μ : Measure β} {f : β → E} (hf : LocallyIntegrable f μ)
(h'f : ∀ (s : Set β), IsCompact s → ∫ x in s, f x ∂μ = 0) :
f =ᵐ[μ] 0 := by
rw [← μ.restrict_univ, ← iUnion_closure_compactCovering]
apply (ae_restrict_iUnion_iff _ _).2 (fun n ↦ ?_)
apply ae_eq_zero_of_forall_setIntegral_isCompact_eq_zero
· exact hf.integrableOn_isCompact (isCompact_compactCovering β n).closure
· intro s hs
rw [Measure.restrict_restrict' measurableSet_closure]
exact h'f _ (hs.inter_right isClosed_closure)
end AeEqOfForallSetIntegralEq
end MeasureTheory
| Mathlib/MeasureTheory/Function/AEEqOfIntegral.lean | 746 | 753 | |
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Ordmap.Invariants
/-!
# Verification of `Ordnode`
This file uses the invariants defined in `Mathlib.Data.Ordmap.Invariants` to construct `Ordset α`,
a wrapper around `Ordnode α` which includes the correctness invariant of the type. It exposes
parallel operations like `insert` as functions on `Ordset` that do the same thing but bundle the
correctness proofs.
The advantage is that it is possible to, for example, prove that the result of `find` on `insert`
will actually find the element, while `Ordnode` cannot guarantee this if the input tree did not
satisfy the type invariants.
## Main definitions
* `Ordnode.Valid`: The validity predicate for an `Ordnode` subtree.
* `Ordset α`: A well formed set of values of type `α`.
## Implementation notes
Because the `Ordnode` file was ported from Haskell, the correctness invariants of some
of the functions have not been spelled out, and some theorems like
`Ordnode.Valid'.balanceL_aux` show very intricate assumptions on the sizes,
which may need to be revised if it turns out some operations violate these assumptions,
because there is a decent amount of slop in the actual data structure invariants, so the
theorem will go through with multiple choices of assumption.
-/
variable {α : Type*}
namespace Ordnode
section Valid
variable [Preorder α]
/-- The validity predicate for an `Ordnode` subtree. This asserts that the `size` fields are
correct, the tree is balanced, and the elements of the tree are organized according to the
ordering. This version of `Valid` also puts all elements in the tree in the interval `(lo, hi)`. -/
structure Valid' (lo : WithBot α) (t : Ordnode α) (hi : WithTop α) : Prop where
ord : t.Bounded lo hi
sz : t.Sized
bal : t.Balanced
/-- The validity predicate for an `Ordnode` subtree. This asserts that the `size` fields are
correct, the tree is balanced, and the elements of the tree are organized according to the
ordering. -/
def Valid (t : Ordnode α) : Prop :=
Valid' ⊥ t ⊤
theorem Valid'.mono_left {x y : α} (xy : x ≤ y) {t : Ordnode α} {o} (h : Valid' y t o) :
Valid' x t o :=
⟨h.1.mono_left xy, h.2, h.3⟩
theorem Valid'.mono_right {x y : α} (xy : x ≤ y) {t : Ordnode α} {o} (h : Valid' o t x) :
Valid' o t y :=
⟨h.1.mono_right xy, h.2, h.3⟩
theorem Valid'.trans_left {t₁ t₂ : Ordnode α} {x : α} {o₁ o₂} (h : Bounded t₁ o₁ x)
(H : Valid' x t₂ o₂) : Valid' o₁ t₂ o₂ :=
⟨h.trans_left H.1, H.2, H.3⟩
theorem Valid'.trans_right {t₁ t₂ : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t₁ x)
(h : Bounded t₂ x o₂) : Valid' o₁ t₁ o₂ :=
⟨H.1.trans_right h, H.2, H.3⟩
theorem Valid'.of_lt {t : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t o₂) (h₁ : Bounded nil o₁ x)
(h₂ : All (· < x) t) : Valid' o₁ t x :=
⟨H.1.of_lt h₁ h₂, H.2, H.3⟩
theorem Valid'.of_gt {t : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t o₂) (h₁ : Bounded nil x o₂)
(h₂ : All (· > x) t) : Valid' x t o₂ :=
⟨H.1.of_gt h₁ h₂, H.2, H.3⟩
theorem Valid'.valid {t o₁ o₂} (h : @Valid' α _ o₁ t o₂) : Valid t :=
⟨h.1.weak, h.2, h.3⟩
theorem valid'_nil {o₁ o₂} (h : Bounded nil o₁ o₂) : Valid' o₁ (@nil α) o₂ :=
⟨h, ⟨⟩, ⟨⟩⟩
theorem valid_nil : Valid (@nil α) :=
valid'_nil ⟨⟩
theorem Valid'.node {s l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H : BalancedSz (size l) (size r)) (hs : s = size l + size r + 1) :
Valid' o₁ (@node α s l x r) o₂ :=
⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩
theorem Valid'.dual : ∀ {t : Ordnode α} {o₁ o₂}, Valid' o₁ t o₂ → @Valid' αᵒᵈ _ o₂ (dual t) o₁
| .nil, _, _, h => valid'_nil h.1.dual
| .node _ l _ r, _, _, ⟨⟨ol, Or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ =>
let ⟨ol', sl', bl'⟩ := Valid'.dual ⟨ol, sl, bl⟩
let ⟨or', sr', br'⟩ := Valid'.dual ⟨Or, sr, br⟩
⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩,
⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩
theorem Valid'.dual_iff {t : Ordnode α} {o₁ o₂} : Valid' o₁ t o₂ ↔ @Valid' αᵒᵈ _ o₂ (.dual t) o₁ :=
⟨Valid'.dual, fun h => by
have := Valid'.dual h; rwa [dual_dual, OrderDual.Preorder.dual_dual] at this⟩
theorem Valid.dual {t : Ordnode α} : Valid t → @Valid αᵒᵈ _ (.dual t) :=
Valid'.dual
theorem Valid.dual_iff {t : Ordnode α} : Valid t ↔ @Valid αᵒᵈ _ (.dual t) :=
Valid'.dual_iff
theorem Valid'.left {s l x r o₁ o₂} (H : Valid' o₁ (@Ordnode.node α s l x r) o₂) : Valid' o₁ l x :=
⟨H.1.1, H.2.2.1, H.3.2.1⟩
theorem Valid'.right {s l x r o₁ o₂} (H : Valid' o₁ (@Ordnode.node α s l x r) o₂) : Valid' x r o₂ :=
⟨H.1.2, H.2.2.2, H.3.2.2⟩
nonrec theorem Valid.left {s l x r} (H : Valid (@node α s l x r)) : Valid l :=
H.left.valid
nonrec theorem Valid.right {s l x r} (H : Valid (@node α s l x r)) : Valid r :=
H.right.valid
theorem Valid.size_eq {s l x r} (H : Valid (@node α s l x r)) :
size (@node α s l x r) = size l + size r + 1 :=
H.2.1
theorem Valid'.node' {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H : BalancedSz (size l) (size r)) : Valid' o₁ (@node' α l x r) o₂ :=
hl.node hr H rfl
theorem valid'_singleton {x : α} {o₁ o₂} (h₁ : Bounded nil o₁ x) (h₂ : Bounded nil x o₂) :
Valid' o₁ (singleton x : Ordnode α) o₂ :=
(valid'_nil h₁).node (valid'_nil h₂) (Or.inl zero_le_one) rfl
theorem valid_singleton {x : α} : Valid (singleton x : Ordnode α) :=
valid'_singleton ⟨⟩ ⟨⟩
theorem Valid'.node3L {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y)
(hr : Valid' y r o₂) (H1 : BalancedSz (size l) (size m))
(H2 : BalancedSz (size l + size m + 1) (size r)) : Valid' o₁ (@node3L α l x m y r) o₂ :=
(hl.node' hm H1).node' hr H2
theorem Valid'.node3R {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y)
(hr : Valid' y r o₂) (H1 : BalancedSz (size l) (size m + size r + 1))
(H2 : BalancedSz (size m) (size r)) : Valid' o₁ (@node3R α l x m y r) o₂ :=
hl.node' (hm.node' hr H2) H1
theorem Valid'.node4L_lemma₁ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9)
(mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : b < 3 * a + 1 := by omega
theorem Valid'.node4L_lemma₂ {b c d : ℕ} (mr₂ : b + c + 1 ≤ 3 * d) : c ≤ 3 * d := by omega
theorem Valid'.node4L_lemma₃ {b c d : ℕ} (mr₁ : 2 * d ≤ b + c + 1) (mm₁ : b ≤ 3 * c) :
d ≤ 3 * c := by omega
theorem Valid'.node4L_lemma₄ {a b c d : ℕ} (lr₁ : 3 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ 3 * d)
(mm₁ : b ≤ 3 * c) : a + b + 1 ≤ 3 * (c + d + 1) := by omega
theorem Valid'.node4L_lemma₅ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9)
(mr₁ : 2 * d ≤ b + c + 1) (mm₂ : c ≤ 3 * b) : c + d + 1 ≤ 3 * (a + b + 1) := by omega
theorem Valid'.node4L {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y)
(hr : Valid' (↑y) r o₂) (Hm : 0 < size m)
(H : size l = 0 ∧ size m = 1 ∧ size r ≤ 1 ∨
0 < size l ∧
ratio * size r ≤ size m ∧
delta * size l ≤ size m + size r ∧
3 * (size m + size r) ≤ 16 * size l + 9 ∧ size m ≤ delta * size r) :
Valid' o₁ (@node4L α l x m y r) o₂ := by
obtain - | ⟨s, ml, z, mr⟩ := m; · cases Hm
suffices
BalancedSz (size l) (size ml) ∧
BalancedSz (size mr) (size r) ∧ BalancedSz (size l + size ml + 1) (size mr + size r + 1) from
Valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2
rcases H with (⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lr₂, mr₂⟩)
· rw [hm.2.size_eq, Nat.succ_inj, add_eq_zero] at m1
rw [l0, m1.1, m1.2]; revert r0; rcases size r with (_ | _ | _) <;>
[decide; decide; (intro r0; unfold BalancedSz delta; omega)]
· rcases Nat.eq_zero_or_pos (size r) with r0 | r0
· rw [r0] at mr₂; cases not_le_of_lt Hm mr₂
rw [hm.2.size_eq] at lr₁ lr₂ mr₁ mr₂
by_cases mm : size ml + size mr ≤ 1
· have r1 :=
le_antisymm
((mul_le_mul_left (by decide)).1 (le_trans mr₁ (Nat.succ_le_succ mm) : _ ≤ ratio * 1)) r0
rw [r1, add_assoc] at lr₁
have l1 :=
le_antisymm
((mul_le_mul_left (by decide)).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≤ delta * 1))
l0
rw [l1, r1]
revert mm; cases size ml <;> cases size mr <;> intro mm
· decide
· rw [zero_add] at mm; rcases mm with (_ | ⟨⟨⟩⟩)
decide
· rcases mm with (_ | ⟨⟨⟩⟩); decide
· rw [Nat.succ_add] at mm; rcases mm with (_ | ⟨⟨⟩⟩)
rcases hm.3.1.resolve_left mm with ⟨mm₁, mm₂⟩
rcases Nat.eq_zero_or_pos (size ml) with ml0 | ml0
· rw [ml0, mul_zero, Nat.le_zero] at mm₂
rw [ml0, mm₂] at mm; cases mm (by decide)
have : 2 * size l ≤ size ml + size mr + 1 := by
have := Nat.mul_le_mul_left ratio lr₁
rw [mul_left_comm, mul_add] at this
have := le_trans this (add_le_add_left mr₁ _)
rw [← Nat.succ_mul] at this
exact (mul_le_mul_left (by decide)).1 this
refine ⟨Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩⟩
· refine (mul_le_mul_left (by decide)).1 (le_trans this ?_)
rw [two_mul, Nat.succ_le_iff]
refine add_lt_add_of_lt_of_le ?_ mm₂
simpa using (mul_lt_mul_right ml0).2 (by decide : 1 < 3)
· exact Nat.le_of_lt_succ (Valid'.node4L_lemma₁ lr₂ mr₂ mm₁)
· exact Valid'.node4L_lemma₂ mr₂
· exact Valid'.node4L_lemma₃ mr₁ mm₁
· exact Valid'.node4L_lemma₄ lr₁ mr₂ mm₁
· exact Valid'.node4L_lemma₅ lr₂ mr₁ mm₂
theorem Valid'.rotateL_lemma₁ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (hb₂ : c ≤ 3 * b) : a ≤ 3 * b := by
omega
theorem Valid'.rotateL_lemma₂ {a b c : ℕ} (H3 : 2 * (b + c) ≤ 9 * a + 3) (h : b < 2 * c) :
b < 3 * a + 1 := by omega
theorem Valid'.rotateL_lemma₃ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (h : b < 2 * c) : a + b < 3 * c := by
omega
theorem Valid'.rotateL_lemma₄ {a b : ℕ} (H3 : 2 * b ≤ 9 * a + 3) : 3 * b ≤ 16 * a + 9 := by
omega
theorem Valid'.rotateL {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H1 : ¬size l + size r ≤ 1) (H2 : delta * size l < size r)
(H3 : 2 * size r ≤ 9 * size l + 5 ∨ size r ≤ 3) : Valid' o₁ (@rotateL α l x r) o₂ := by
obtain - | ⟨rs, rl, rx, rr⟩ := r; · cases H2
rw [hr.2.size_eq, Nat.lt_succ_iff] at H2
rw [hr.2.size_eq] at H3
replace H3 : 2 * (size rl + size rr) ≤ 9 * size l + 3 ∨ size rl + size rr ≤ 2 :=
H3.imp (@Nat.le_of_add_le_add_right _ 2 _) Nat.le_of_succ_le_succ
have H3_0 : size l = 0 → size rl + size rr ≤ 2 := by
intro l0; rw [l0] at H3
exact
(or_iff_right_of_imp fun h => (mul_le_mul_left (by decide)).1 (le_trans h (by decide))).1 H3
have H3p : size l > 0 → 2 * (size rl + size rr) ≤ 9 * size l + 3 := fun l0 : 1 ≤ size l =>
(or_iff_left_of_imp <| by omega).1 H3
have ablem : ∀ {a b : ℕ}, 1 ≤ a → a + b ≤ 2 → b ≤ 1 := by omega
have hlp : size l > 0 → ¬size rl + size rr ≤ 1 := fun l0 hb =>
absurd (le_trans (le_trans (Nat.mul_le_mul_left _ l0) H2) hb) (by decide)
rw [Ordnode.rotateL_node]; split_ifs with h
· have rr0 : size rr > 0 :=
(mul_lt_mul_left (by decide)).1 (lt_of_le_of_lt (Nat.zero_le _) h : ratio * 0 < _)
suffices BalancedSz (size l) (size rl) ∧ BalancedSz (size l + size rl + 1) (size rr) by
exact hl.node3L hr.left hr.right this.1 this.2
rcases Nat.eq_zero_or_pos (size l) with l0 | l0
· rw [l0]; replace H3 := H3_0 l0
have := hr.3.1
rcases Nat.eq_zero_or_pos (size rl) with rl0 | rl0
· rw [rl0] at this ⊢
rw [le_antisymm (balancedSz_zero.1 this.symm) rr0]
decide
have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0
rw [add_comm] at H3
rw [rr1, show size rl = 1 from le_antisymm (ablem rr0 H3) rl0]
decide
replace H3 := H3p l0
rcases hr.3.1.resolve_left (hlp l0) with ⟨_, hb₂⟩
refine ⟨Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩⟩
· exact Valid'.rotateL_lemma₁ H2 hb₂
· exact Nat.le_of_lt_succ (Valid'.rotateL_lemma₂ H3 h)
· exact Valid'.rotateL_lemma₃ H2 h
· exact
le_trans hb₂
(Nat.mul_le_mul_left _ <| le_trans (Nat.le_add_left _ _) (Nat.le_add_right _ _))
· rcases Nat.eq_zero_or_pos (size rl) with rl0 | rl0
· rw [rl0, not_lt, Nat.le_zero, Nat.mul_eq_zero] at h
replace h := h.resolve_left (by decide)
rw [rl0, h, Nat.le_zero, Nat.mul_eq_zero] at H2
rw [hr.2.size_eq, rl0, h, H2.resolve_left (by decide)] at H1
cases H1 (by decide)
refine hl.node4L hr.left hr.right rl0 ?_
rcases Nat.eq_zero_or_pos (size l) with l0 | l0
· replace H3 := H3_0 l0
rcases Nat.eq_zero_or_pos (size rr) with rr0 | rr0
· have := hr.3.1
rw [rr0] at this
exact Or.inl ⟨l0, le_antisymm (balancedSz_zero.1 this) rl0, rr0.symm ▸ zero_le_one⟩
exact Or.inl ⟨l0, le_antisymm (ablem rr0 <| by rwa [add_comm]) rl0, ablem rl0 H3⟩
exact
Or.inr ⟨l0, not_lt.1 h, H2, Valid'.rotateL_lemma₄ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩
theorem Valid'.rotateR {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H1 : ¬size l + size r ≤ 1) (H2 : delta * size r < size l)
(H3 : 2 * size l ≤ 9 * size r + 5 ∨ size l ≤ 3) : Valid' o₁ (@rotateR α l x r) o₂ := by
refine Valid'.dual_iff.2 ?_
rw [dual_rotateR]
refine hr.dual.rotateL hl.dual ?_ ?_ ?_
· rwa [size_dual, size_dual, add_comm]
· rwa [size_dual, size_dual]
· rwa [size_dual, size_dual]
theorem Valid'.balance'_aux {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H₁ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3)
(H₂ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : Valid' o₁ (@balance' α l x r) o₂ := by
rw [balance']; split_ifs with h h_1 h_2
· exact hl.node' hr (Or.inl h)
· exact hl.rotateL hr h h_1 H₁
· exact hl.rotateR hr h h_2 H₂
· exact hl.node' hr (Or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩)
theorem Valid'.balance'_lemma {α l l' r r'} (H1 : BalancedSz l' r')
(H2 : Nat.dist (@size α l) l' ≤ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≤ 1 ∧ size l = l') :
2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3 := by
suffices @size α r ≤ 3 * (size l + 1) by omega
rcases H2 with (⟨hl, rfl⟩ | ⟨hr, rfl⟩) <;> rcases H1 with (h | ⟨_, h₂⟩)
· exact le_trans (Nat.le_add_left _ _) (le_trans h (Nat.le_add_left _ _))
· exact
le_trans h₂
(Nat.mul_le_mul_left _ <| le_trans (Nat.dist_tri_right _ _) (Nat.add_le_add_left hl _))
| · exact
le_trans (Nat.dist_tri_left' _ _)
(le_trans (add_le_add hr (le_trans (Nat.le_add_left _ _) h)) (by omega))
| Mathlib/Data/Ordmap/Ordset.lean | 321 | 323 |
/-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import Mathlib.Topology.Constructions
/-!
# Neighborhoods and continuity relative to a subset
This file develops API on the relative versions
* `nhdsWithin` of `nhds`
* `ContinuousOn` of `Continuous`
* `ContinuousWithinAt` of `ContinuousAt`
related to continuity, which are defined in previous definition files.
Their basic properties studied in this file include the relationships between
these restricted notions and the corresponding notions for the subtype
equipped with the subspace topology.
## Notation
* `𝓝 x`: the filter of neighborhoods of a point `x`;
* `𝓟 s`: the principal filter of a set `s`;
* `𝓝[s] x`: the filter `nhdsWithin x s` of neighborhoods of a point `x` within a set `s`.
-/
open Set Filter Function Topology Filter
variable {α β γ δ : Type*}
variable [TopologicalSpace α]
/-!
## Properties of the neighborhood-within filter
-/
@[simp]
theorem nhds_bind_nhdsWithin {a : α} {s : Set α} : ((𝓝 a).bind fun x => 𝓝[s] x) = 𝓝[s] a :=
bind_inf_principal.trans <| congr_arg₂ _ nhds_bind_nhds rfl
@[simp]
theorem eventually_nhds_nhdsWithin {a : α} {s : Set α} {p : α → Prop} :
(∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x :=
Filter.ext_iff.1 nhds_bind_nhdsWithin { x | p x }
theorem eventually_nhdsWithin_iff {a : α} {s : Set α} {p : α → Prop} :
(∀ᶠ x in 𝓝[s] a, p x) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → p x :=
eventually_inf_principal
theorem frequently_nhdsWithin_iff {z : α} {s : Set α} {p : α → Prop} :
(∃ᶠ x in 𝓝[s] z, p x) ↔ ∃ᶠ x in 𝓝 z, p x ∧ x ∈ s :=
frequently_inf_principal.trans <| by simp only [and_comm]
theorem mem_closure_ne_iff_frequently_within {z : α} {s : Set α} :
z ∈ closure (s \ {z}) ↔ ∃ᶠ x in 𝓝[≠] z, x ∈ s := by
simp [mem_closure_iff_frequently, frequently_nhdsWithin_iff]
@[simp]
theorem eventually_eventually_nhdsWithin {a : α} {s : Set α} {p : α → Prop} :
(∀ᶠ y in 𝓝[s] a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := by
refine ⟨fun h => ?_, fun h => (eventually_nhds_nhdsWithin.2 h).filter_mono inf_le_left⟩
simp only [eventually_nhdsWithin_iff] at h ⊢
exact h.mono fun x hx hxs => (hx hxs).self_of_nhds hxs
@[simp]
theorem eventually_mem_nhdsWithin_iff {x : α} {s t : Set α} :
(∀ᶠ x' in 𝓝[s] x, t ∈ 𝓝[s] x') ↔ t ∈ 𝓝[s] x :=
eventually_eventually_nhdsWithin
theorem nhdsWithin_eq (a : α) (s : Set α) :
𝓝[s] a = ⨅ t ∈ { t : Set α | a ∈ t ∧ IsOpen t }, 𝓟 (t ∩ s) :=
((nhds_basis_opens a).inf_principal s).eq_biInf
@[simp] lemma nhdsWithin_univ (a : α) : 𝓝[Set.univ] a = 𝓝 a := by
rw [nhdsWithin, principal_univ, inf_top_eq]
theorem nhdsWithin_hasBasis {ι : Sort*} {p : ι → Prop} {s : ι → Set α} {a : α}
(h : (𝓝 a).HasBasis p s) (t : Set α) : (𝓝[t] a).HasBasis p fun i => s i ∩ t :=
h.inf_principal t
theorem nhdsWithin_basis_open (a : α) (t : Set α) :
(𝓝[t] a).HasBasis (fun u => a ∈ u ∧ IsOpen u) fun u => u ∩ t :=
nhdsWithin_hasBasis (nhds_basis_opens a) t
theorem mem_nhdsWithin {t : Set α} {a : α} {s : Set α} :
t ∈ 𝓝[s] a ↔ ∃ u, IsOpen u ∧ a ∈ u ∧ u ∩ s ⊆ t := by
simpa only [and_assoc, and_left_comm] using (nhdsWithin_basis_open a s).mem_iff
theorem mem_nhdsWithin_iff_exists_mem_nhds_inter {t : Set α} {a : α} {s : Set α} :
t ∈ 𝓝[s] a ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t :=
(nhdsWithin_hasBasis (𝓝 a).basis_sets s).mem_iff
theorem diff_mem_nhdsWithin_compl {x : α} {s : Set α} (hs : s ∈ 𝓝 x) (t : Set α) :
s \ t ∈ 𝓝[tᶜ] x :=
diff_mem_inf_principal_compl hs t
theorem diff_mem_nhdsWithin_diff {x : α} {s t : Set α} (hs : s ∈ 𝓝[t] x) (t' : Set α) :
s \ t' ∈ 𝓝[t \ t'] x := by
rw [nhdsWithin, diff_eq, diff_eq, ← inf_principal, ← inf_assoc]
exact inter_mem_inf hs (mem_principal_self _)
theorem nhds_of_nhdsWithin_of_nhds {s t : Set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ 𝓝[s] a) :
t ∈ 𝓝 a := by
rcases mem_nhdsWithin_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩
exact (𝓝 a).sets_of_superset ((𝓝 a).inter_sets Hw h1) hw
theorem mem_nhdsWithin_iff_eventually {s t : Set α} {x : α} :
t ∈ 𝓝[s] x ↔ ∀ᶠ y in 𝓝 x, y ∈ s → y ∈ t :=
eventually_inf_principal
theorem mem_nhdsWithin_iff_eventuallyEq {s t : Set α} {x : α} :
t ∈ 𝓝[s] x ↔ s =ᶠ[𝓝 x] (s ∩ t : Set α) := by
simp_rw [mem_nhdsWithin_iff_eventually, eventuallyEq_set, mem_inter_iff, iff_self_and]
theorem nhdsWithin_eq_iff_eventuallyEq {s t : Set α} {x : α} : 𝓝[s] x = 𝓝[t] x ↔ s =ᶠ[𝓝 x] t :=
set_eventuallyEq_iff_inf_principal.symm
theorem nhdsWithin_le_iff {s t : Set α} {x : α} : 𝓝[s] x ≤ 𝓝[t] x ↔ t ∈ 𝓝[s] x :=
set_eventuallyLE_iff_inf_principal_le.symm.trans set_eventuallyLE_iff_mem_inf_principal
theorem preimage_nhdsWithin_coinduced' {π : α → β} {s : Set β} {t : Set α} {a : α} (h : a ∈ t)
(hs : s ∈ @nhds β (.coinduced (fun x : t => π x) inferInstance) (π a)) :
π ⁻¹' s ∈ 𝓝[t] a := by
lift a to t using h
replace hs : (fun x : t => π x) ⁻¹' s ∈ 𝓝 a := preimage_nhds_coinduced hs
rwa [← map_nhds_subtype_val, mem_map]
theorem mem_nhdsWithin_of_mem_nhds {s t : Set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ 𝓝[t] a :=
mem_inf_of_left h
theorem self_mem_nhdsWithin {a : α} {s : Set α} : s ∈ 𝓝[s] a :=
mem_inf_of_right (mem_principal_self s)
theorem eventually_mem_nhdsWithin {a : α} {s : Set α} : ∀ᶠ x in 𝓝[s] a, x ∈ s :=
self_mem_nhdsWithin
theorem inter_mem_nhdsWithin (s : Set α) {t : Set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ 𝓝[s] a :=
inter_mem self_mem_nhdsWithin (mem_inf_of_left h)
theorem pure_le_nhdsWithin {a : α} {s : Set α} (ha : a ∈ s) : pure a ≤ 𝓝[s] a :=
le_inf (pure_le_nhds a) (le_principal_iff.2 ha)
theorem mem_of_mem_nhdsWithin {a : α} {s t : Set α} (ha : a ∈ s) (ht : t ∈ 𝓝[s] a) : a ∈ t :=
pure_le_nhdsWithin ha ht
theorem Filter.Eventually.self_of_nhdsWithin {p : α → Prop} {s : Set α} {x : α}
(h : ∀ᶠ y in 𝓝[s] x, p y) (hx : x ∈ s) : p x :=
mem_of_mem_nhdsWithin hx h
theorem tendsto_const_nhdsWithin {l : Filter β} {s : Set α} {a : α} (ha : a ∈ s) :
Tendsto (fun _ : β => a) l (𝓝[s] a) :=
tendsto_const_pure.mono_right <| pure_le_nhdsWithin ha
theorem nhdsWithin_restrict'' {a : α} (s : Set α) {t : Set α} (h : t ∈ 𝓝[s] a) :
𝓝[s] a = 𝓝[s ∩ t] a :=
le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem self_mem_nhdsWithin h)))
(inf_le_inf_left _ (principal_mono.mpr Set.inter_subset_left))
theorem nhdsWithin_restrict' {a : α} (s : Set α) {t : Set α} (h : t ∈ 𝓝 a) : 𝓝[s] a = 𝓝[s ∩ t] a :=
nhdsWithin_restrict'' s <| mem_inf_of_left h
theorem nhdsWithin_restrict {a : α} (s : Set α) {t : Set α} (h₀ : a ∈ t) (h₁ : IsOpen t) :
𝓝[s] a = 𝓝[s ∩ t] a :=
nhdsWithin_restrict' s (IsOpen.mem_nhds h₁ h₀)
theorem nhdsWithin_le_of_mem {a : α} {s t : Set α} (h : s ∈ 𝓝[t] a) : 𝓝[t] a ≤ 𝓝[s] a :=
nhdsWithin_le_iff.mpr h
theorem nhdsWithin_le_nhds {a : α} {s : Set α} : 𝓝[s] a ≤ 𝓝 a := by
rw [← nhdsWithin_univ]
apply nhdsWithin_le_of_mem
exact univ_mem
theorem nhdsWithin_eq_nhdsWithin' {a : α} {s t u : Set α} (hs : s ∈ 𝓝 a) (h₂ : t ∩ s = u ∩ s) :
𝓝[t] a = 𝓝[u] a := by rw [nhdsWithin_restrict' t hs, nhdsWithin_restrict' u hs, h₂]
theorem nhdsWithin_eq_nhdsWithin {a : α} {s t u : Set α} (h₀ : a ∈ s) (h₁ : IsOpen s)
(h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by
rw [nhdsWithin_restrict t h₀ h₁, nhdsWithin_restrict u h₀ h₁, h₂]
@[simp] theorem nhdsWithin_eq_nhds {a : α} {s : Set α} : 𝓝[s] a = 𝓝 a ↔ s ∈ 𝓝 a :=
inf_eq_left.trans le_principal_iff
theorem IsOpen.nhdsWithin_eq {a : α} {s : Set α} (h : IsOpen s) (ha : a ∈ s) : 𝓝[s] a = 𝓝 a :=
nhdsWithin_eq_nhds.2 <| h.mem_nhds ha
theorem preimage_nhds_within_coinduced {π : α → β} {s : Set β} {t : Set α} {a : α} (h : a ∈ t)
(ht : IsOpen t)
(hs : s ∈ @nhds β (.coinduced (fun x : t => π x) inferInstance) (π a)) :
π ⁻¹' s ∈ 𝓝 a := by
rw [← ht.nhdsWithin_eq h]
exact preimage_nhdsWithin_coinduced' h hs
@[simp]
theorem nhdsWithin_empty (a : α) : 𝓝[∅] a = ⊥ := by rw [nhdsWithin, principal_empty, inf_bot_eq]
theorem nhdsWithin_union (a : α) (s t : Set α) : 𝓝[s ∪ t] a = 𝓝[s] a ⊔ 𝓝[t] a := by
delta nhdsWithin
rw [← inf_sup_left, sup_principal]
theorem nhds_eq_nhdsWithin_sup_nhdsWithin (b : α) {I₁ I₂ : Set α} (hI : Set.univ = I₁ ∪ I₂) :
nhds b = nhdsWithin b I₁ ⊔ nhdsWithin b I₂ := by
rw [← nhdsWithin_univ b, hI, nhdsWithin_union]
/-- If `L` and `R` are neighborhoods of `b` within sets whose union is `Set.univ`, then
`L ∪ R` is a neighborhood of `b`. -/
theorem union_mem_nhds_of_mem_nhdsWithin {b : α}
{I₁ I₂ : Set α} (h : Set.univ = I₁ ∪ I₂)
{L : Set α} (hL : L ∈ nhdsWithin b I₁)
{R : Set α} (hR : R ∈ nhdsWithin b I₂) : L ∪ R ∈ nhds b := by
rw [← nhdsWithin_univ b, h, nhdsWithin_union]
exact ⟨mem_of_superset hL (by simp), mem_of_superset hR (by simp)⟩
/-- Writing a punctured neighborhood filter as a sup of left and right filters. -/
lemma punctured_nhds_eq_nhdsWithin_sup_nhdsWithin [LinearOrder α] {x : α} :
𝓝[≠] x = 𝓝[<] x ⊔ 𝓝[>] x := by
rw [← Iio_union_Ioi, nhdsWithin_union]
/-- Obtain a "predictably-sided" neighborhood of `b` from two one-sided neighborhoods. -/
theorem nhds_of_Ici_Iic [LinearOrder α] {b : α}
{L : Set α} (hL : L ∈ 𝓝[≤] b)
{R : Set α} (hR : R ∈ 𝓝[≥] b) : L ∩ Iic b ∪ R ∩ Ici b ∈ 𝓝 b :=
union_mem_nhds_of_mem_nhdsWithin Iic_union_Ici.symm
(inter_mem hL self_mem_nhdsWithin) (inter_mem hR self_mem_nhdsWithin)
theorem nhdsWithin_biUnion {ι} {I : Set ι} (hI : I.Finite) (s : ι → Set α) (a : α) :
𝓝[⋃ i ∈ I, s i] a = ⨆ i ∈ I, 𝓝[s i] a := by
induction I, hI using Set.Finite.induction_on with
| empty => simp
| insert _ _ hT => simp only [hT, nhdsWithin_union, iSup_insert, biUnion_insert]
theorem nhdsWithin_sUnion {S : Set (Set α)} (hS : S.Finite) (a : α) :
𝓝[⋃₀ S] a = ⨆ s ∈ S, 𝓝[s] a := by
rw [sUnion_eq_biUnion, nhdsWithin_biUnion hS]
theorem nhdsWithin_iUnion {ι} [Finite ι] (s : ι → Set α) (a : α) :
𝓝[⋃ i, s i] a = ⨆ i, 𝓝[s i] a := by
rw [← sUnion_range, nhdsWithin_sUnion (finite_range s), iSup_range]
theorem nhdsWithin_inter (a : α) (s t : Set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓝[t] a := by
delta nhdsWithin
rw [inf_left_comm, inf_assoc, inf_principal, ← inf_assoc, inf_idem]
theorem nhdsWithin_inter' (a : α) (s t : Set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓟 t := by
delta nhdsWithin
rw [← inf_principal, inf_assoc]
theorem nhdsWithin_inter_of_mem {a : α} {s t : Set α} (h : s ∈ 𝓝[t] a) : 𝓝[s ∩ t] a = 𝓝[t] a := by
rw [nhdsWithin_inter, inf_eq_right]
exact nhdsWithin_le_of_mem h
theorem nhdsWithin_inter_of_mem' {a : α} {s t : Set α} (h : t ∈ 𝓝[s] a) : 𝓝[s ∩ t] a = 𝓝[s] a := by
rw [inter_comm, nhdsWithin_inter_of_mem h]
@[simp]
theorem nhdsWithin_singleton (a : α) : 𝓝[{a}] a = pure a := by
rw [nhdsWithin, principal_singleton, inf_eq_right.2 (pure_le_nhds a)]
@[simp]
theorem nhdsWithin_insert (a : α) (s : Set α) : 𝓝[insert a s] a = pure a ⊔ 𝓝[s] a := by
rw [← singleton_union, nhdsWithin_union, nhdsWithin_singleton]
theorem mem_nhdsWithin_insert {a : α} {s t : Set α} : t ∈ 𝓝[insert a s] a ↔ a ∈ t ∧ t ∈ 𝓝[s] a := by
simp
theorem insert_mem_nhdsWithin_insert {a : α} {s t : Set α} (h : t ∈ 𝓝[s] a) :
insert a t ∈ 𝓝[insert a s] a := by simp [mem_of_superset h]
theorem insert_mem_nhds_iff {a : α} {s : Set α} : insert a s ∈ 𝓝 a ↔ s ∈ 𝓝[≠] a := by
simp only [nhdsWithin, mem_inf_principal, mem_compl_iff, mem_singleton_iff, or_iff_not_imp_left,
insert_def]
@[simp]
theorem nhdsNE_sup_pure (a : α) : 𝓝[≠] a ⊔ pure a = 𝓝 a := by
rw [← nhdsWithin_singleton, ← nhdsWithin_union, compl_union_self, nhdsWithin_univ]
@[deprecated (since := "2025-03-02")]
alias nhdsWithin_compl_singleton_sup_pure := nhdsNE_sup_pure
@[simp]
theorem pure_sup_nhdsNE (a : α) : pure a ⊔ 𝓝[≠] a = 𝓝 a := by rw [← sup_comm, nhdsNE_sup_pure]
theorem nhdsWithin_prod [TopologicalSpace β]
{s u : Set α} {t v : Set β} {a : α} {b : β} (hu : u ∈ 𝓝[s] a) (hv : v ∈ 𝓝[t] b) :
u ×ˢ v ∈ 𝓝[s ×ˢ t] (a, b) := by
rw [nhdsWithin_prod_eq]
exact prod_mem_prod hu hv
lemma Filter.EventuallyEq.mem_interior {x : α} {s t : Set α} (hst : s =ᶠ[𝓝 x] t)
(h : x ∈ interior s) : x ∈ interior t := by
rw [← nhdsWithin_eq_iff_eventuallyEq] at hst
simpa [mem_interior_iff_mem_nhds, ← nhdsWithin_eq_nhds, hst] using h
lemma Filter.EventuallyEq.mem_interior_iff {x : α} {s t : Set α} (hst : s =ᶠ[𝓝 x] t) :
x ∈ interior s ↔ x ∈ interior t :=
⟨fun h ↦ hst.mem_interior h, fun h ↦ hst.symm.mem_interior h⟩
@[deprecated (since := "2024-11-11")]
alias EventuallyEq.mem_interior_iff := Filter.EventuallyEq.mem_interior_iff
section Pi
variable {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)]
theorem nhdsWithin_pi_eq' {I : Set ι} (hI : I.Finite) (s : ∀ i, Set (π i)) (x : ∀ i, π i) :
𝓝[pi I s] x = ⨅ i, comap (fun x => x i) (𝓝 (x i) ⊓ ⨅ (_ : i ∈ I), 𝓟 (s i)) := by
simp only [nhdsWithin, nhds_pi, Filter.pi, comap_inf, comap_iInf, pi_def, comap_principal, ←
iInf_principal_finite hI, ← iInf_inf_eq]
theorem nhdsWithin_pi_eq {I : Set ι} (hI : I.Finite) (s : ∀ i, Set (π i)) (x : ∀ i, π i) :
𝓝[pi I s] x =
(⨅ i ∈ I, comap (fun x => x i) (𝓝[s i] x i)) ⊓
⨅ (i) (_ : i ∉ I), comap (fun x => x i) (𝓝 (x i)) := by
simp only [nhdsWithin, nhds_pi, Filter.pi, pi_def, ← iInf_principal_finite hI, comap_inf,
comap_principal, eval]
rw [iInf_split _ fun i => i ∈ I, inf_right_comm]
simp only [iInf_inf_eq]
theorem nhdsWithin_pi_univ_eq [Finite ι] (s : ∀ i, Set (π i)) (x : ∀ i, π i) :
𝓝[pi univ s] x = ⨅ i, comap (fun x => x i) (𝓝[s i] x i) := by
simpa [nhdsWithin] using nhdsWithin_pi_eq finite_univ s x
theorem nhdsWithin_pi_eq_bot {I : Set ι} {s : ∀ i, Set (π i)} {x : ∀ i, π i} :
𝓝[pi I s] x = ⊥ ↔ ∃ i ∈ I, 𝓝[s i] x i = ⊥ := by
simp only [nhdsWithin, nhds_pi, pi_inf_principal_pi_eq_bot]
theorem nhdsWithin_pi_neBot {I : Set ι} {s : ∀ i, Set (π i)} {x : ∀ i, π i} :
(𝓝[pi I s] x).NeBot ↔ ∀ i ∈ I, (𝓝[s i] x i).NeBot := by
simp [neBot_iff, nhdsWithin_pi_eq_bot]
instance instNeBotNhdsWithinUnivPi {s : ∀ i, Set (π i)} {x : ∀ i, π i}
[∀ i, (𝓝[s i] x i).NeBot] : (𝓝[pi univ s] x).NeBot := by
simpa [nhdsWithin_pi_neBot]
instance Pi.instNeBotNhdsWithinIio [Nonempty ι] [∀ i, Preorder (π i)] {x : ∀ i, π i}
[∀ i, (𝓝[<] x i).NeBot] : (𝓝[<] x).NeBot :=
have : (𝓝[pi univ fun i ↦ Iio (x i)] x).NeBot := inferInstance
this.mono <| nhdsWithin_mono _ fun _y hy ↦ lt_of_strongLT fun i ↦ hy i trivial
instance Pi.instNeBotNhdsWithinIoi [Nonempty ι] [∀ i, Preorder (π i)] {x : ∀ i, π i}
[∀ i, (𝓝[>] x i).NeBot] : (𝓝[>] x).NeBot :=
Pi.instNeBotNhdsWithinIio (π := fun i ↦ (π i)ᵒᵈ) (x := fun i ↦ OrderDual.toDual (x i))
end Pi
theorem Filter.Tendsto.piecewise_nhdsWithin {f g : α → β} {t : Set α} [∀ x, Decidable (x ∈ t)]
{a : α} {s : Set α} {l : Filter β} (h₀ : Tendsto f (𝓝[s ∩ t] a) l)
(h₁ : Tendsto g (𝓝[s ∩ tᶜ] a) l) : Tendsto (piecewise t f g) (𝓝[s] a) l := by
apply Tendsto.piecewise <;> rwa [← nhdsWithin_inter']
theorem Filter.Tendsto.if_nhdsWithin {f g : α → β} {p : α → Prop} [DecidablePred p] {a : α}
{s : Set α} {l : Filter β} (h₀ : Tendsto f (𝓝[s ∩ { x | p x }] a) l)
(h₁ : Tendsto g (𝓝[s ∩ { x | ¬p x }] a) l) :
Tendsto (fun x => if p x then f x else g x) (𝓝[s] a) l :=
h₀.piecewise_nhdsWithin h₁
theorem map_nhdsWithin (f : α → β) (a : α) (s : Set α) :
map f (𝓝[s] a) = ⨅ t ∈ { t : Set α | a ∈ t ∧ IsOpen t }, 𝓟 (f '' (t ∩ s)) :=
((nhdsWithin_basis_open a s).map f).eq_biInf
theorem tendsto_nhdsWithin_mono_left {f : α → β} {a : α} {s t : Set α} {l : Filter β} (hst : s ⊆ t)
(h : Tendsto f (𝓝[t] a) l) : Tendsto f (𝓝[s] a) l :=
h.mono_left <| nhdsWithin_mono a hst
theorem tendsto_nhdsWithin_mono_right {f : β → α} {l : Filter β} {a : α} {s t : Set α} (hst : s ⊆ t)
(h : Tendsto f l (𝓝[s] a)) : Tendsto f l (𝓝[t] a) :=
h.mono_right (nhdsWithin_mono a hst)
theorem tendsto_nhdsWithin_of_tendsto_nhds {f : α → β} {a : α} {s : Set α} {l : Filter β}
(h : Tendsto f (𝓝 a) l) : Tendsto f (𝓝[s] a) l :=
h.mono_left inf_le_left
theorem eventually_mem_of_tendsto_nhdsWithin {f : β → α} {a : α} {s : Set α} {l : Filter β}
(h : Tendsto f l (𝓝[s] a)) : ∀ᶠ i in l, f i ∈ s := by
simp_rw [nhdsWithin_eq, tendsto_iInf, mem_setOf_eq, tendsto_principal, mem_inter_iff,
eventually_and] at h
exact (h univ ⟨mem_univ a, isOpen_univ⟩).2
theorem tendsto_nhds_of_tendsto_nhdsWithin {f : β → α} {a : α} {s : Set α} {l : Filter β}
(h : Tendsto f l (𝓝[s] a)) : Tendsto f l (𝓝 a) :=
h.mono_right nhdsWithin_le_nhds
theorem nhdsWithin_neBot_of_mem {s : Set α} {x : α} (hx : x ∈ s) : NeBot (𝓝[s] x) :=
mem_closure_iff_nhdsWithin_neBot.1 <| subset_closure hx
theorem IsClosed.mem_of_nhdsWithin_neBot {s : Set α} (hs : IsClosed s) {x : α}
(hx : NeBot <| 𝓝[s] x) : x ∈ s :=
hs.closure_eq ▸ mem_closure_iff_nhdsWithin_neBot.2 hx
theorem DenseRange.nhdsWithin_neBot {ι : Type*} {f : ι → α} (h : DenseRange f) (x : α) :
NeBot (𝓝[range f] x) :=
mem_closure_iff_clusterPt.1 (h x)
theorem mem_closure_pi {ι : Type*} {α : ι → Type*} [∀ i, TopologicalSpace (α i)] {I : Set ι}
{s : ∀ i, Set (α i)} {x : ∀ i, α i} : x ∈ closure (pi I s) ↔ ∀ i ∈ I, x i ∈ closure (s i) := by
simp only [mem_closure_iff_nhdsWithin_neBot, nhdsWithin_pi_neBot]
theorem closure_pi_set {ι : Type*} {α : ι → Type*} [∀ i, TopologicalSpace (α i)] (I : Set ι)
(s : ∀ i, Set (α i)) : closure (pi I s) = pi I fun i => closure (s i) :=
Set.ext fun _ => mem_closure_pi
theorem dense_pi {ι : Type*} {α : ι → Type*} [∀ i, TopologicalSpace (α i)] {s : ∀ i, Set (α i)}
(I : Set ι) (hs : ∀ i ∈ I, Dense (s i)) : Dense (pi I s) := by
simp only [dense_iff_closure_eq, closure_pi_set, pi_congr rfl fun i hi => (hs i hi).closure_eq,
pi_univ]
theorem DenseRange.piMap {ι : Type*} {X Y : ι → Type*} [∀ i, TopologicalSpace (Y i)]
{f : (i : ι) → (X i) → (Y i)} (hf : ∀ i, DenseRange (f i)):
DenseRange (Pi.map f) := by
rw [DenseRange, Set.range_piMap]
exact dense_pi Set.univ (fun i _ => hf i)
theorem eventuallyEq_nhdsWithin_iff {f g : α → β} {s : Set α} {a : α} :
f =ᶠ[𝓝[s] a] g ↔ ∀ᶠ x in 𝓝 a, x ∈ s → f x = g x :=
mem_inf_principal
/-- Two functions agree on a neighborhood of `x` if they agree at `x` and in a punctured
neighborhood. -/
theorem eventuallyEq_nhds_of_eventuallyEq_nhdsNE {f g : α → β} {a : α} (h₁ : f =ᶠ[𝓝[≠] a] g)
(h₂ : f a = g a) :
f =ᶠ[𝓝 a] g := by
filter_upwards [eventually_nhdsWithin_iff.1 h₁]
intro x hx
by_cases h₂x : x = a
· simp [h₂x, h₂]
· tauto
theorem eventuallyEq_nhdsWithin_of_eqOn {f g : α → β} {s : Set α} {a : α} (h : EqOn f g s) :
f =ᶠ[𝓝[s] a] g :=
mem_inf_of_right h
theorem Set.EqOn.eventuallyEq_nhdsWithin {f g : α → β} {s : Set α} {a : α} (h : EqOn f g s) :
f =ᶠ[𝓝[s] a] g :=
eventuallyEq_nhdsWithin_of_eqOn h
theorem tendsto_nhdsWithin_congr {f g : α → β} {s : Set α} {a : α} {l : Filter β}
(hfg : ∀ x ∈ s, f x = g x) (hf : Tendsto f (𝓝[s] a) l) : Tendsto g (𝓝[s] a) l :=
(tendsto_congr' <| eventuallyEq_nhdsWithin_of_eqOn hfg).1 hf
theorem eventually_nhdsWithin_of_forall {s : Set α} {a : α} {p : α → Prop} (h : ∀ x ∈ s, p x) :
∀ᶠ x in 𝓝[s] a, p x :=
mem_inf_of_right h
theorem tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within {a : α} {l : Filter β} {s : Set α}
(f : β → α) (h1 : Tendsto f l (𝓝 a)) (h2 : ∀ᶠ x in l, f x ∈ s) : Tendsto f l (𝓝[s] a) :=
tendsto_inf.2 ⟨h1, tendsto_principal.2 h2⟩
theorem tendsto_nhdsWithin_iff {a : α} {l : Filter β} {s : Set α} {f : β → α} :
Tendsto f l (𝓝[s] a) ↔ Tendsto f l (𝓝 a) ∧ ∀ᶠ n in l, f n ∈ s :=
⟨fun h => ⟨tendsto_nhds_of_tendsto_nhdsWithin h, eventually_mem_of_tendsto_nhdsWithin h⟩, fun h =>
tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within _ h.1 h.2⟩
@[simp]
theorem tendsto_nhdsWithin_range {a : α} {l : Filter β} {f : β → α} :
Tendsto f l (𝓝[range f] a) ↔ Tendsto f l (𝓝 a) :=
⟨fun h => h.mono_right inf_le_left, fun h =>
tendsto_inf.2 ⟨h, tendsto_principal.2 <| Eventually.of_forall mem_range_self⟩⟩
theorem Filter.EventuallyEq.eq_of_nhdsWithin {s : Set α} {f g : α → β} {a : α} (h : f =ᶠ[𝓝[s] a] g)
(hmem : a ∈ s) : f a = g a :=
h.self_of_nhdsWithin hmem
theorem eventually_nhdsWithin_of_eventually_nhds {s : Set α}
{a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) : ∀ᶠ x in 𝓝[s] a, p x :=
mem_nhdsWithin_of_mem_nhds h
lemma Set.MapsTo.preimage_mem_nhdsWithin {f : α → β} {s : Set α} {t : Set β} {x : α}
(hst : MapsTo f s t) : f ⁻¹' t ∈ 𝓝[s] x :=
Filter.mem_of_superset self_mem_nhdsWithin hst
/-!
### `nhdsWithin` and subtypes
-/
theorem mem_nhdsWithin_subtype {s : Set α} {a : { x // x ∈ s }} {t u : Set { x // x ∈ s }} :
t ∈ 𝓝[u] a ↔ t ∈ comap ((↑) : s → α) (𝓝[(↑) '' u] a) := by
rw [nhdsWithin, nhds_subtype, principal_subtype, ← comap_inf, ← nhdsWithin]
theorem nhdsWithin_subtype (s : Set α) (a : { x // x ∈ s }) (t : Set { x // x ∈ s }) :
𝓝[t] a = comap ((↑) : s → α) (𝓝[(↑) '' t] a) :=
Filter.ext fun _ => mem_nhdsWithin_subtype
theorem nhdsWithin_eq_map_subtype_coe {s : Set α} {a : α} (h : a ∈ s) :
𝓝[s] a = map ((↑) : s → α) (𝓝 ⟨a, h⟩) :=
(map_nhds_subtype_val ⟨a, h⟩).symm
theorem mem_nhds_subtype_iff_nhdsWithin {s : Set α} {a : s} {t : Set s} :
t ∈ 𝓝 a ↔ (↑) '' t ∈ 𝓝[s] (a : α) := by
rw [← map_nhds_subtype_val, image_mem_map_iff Subtype.val_injective]
theorem preimage_coe_mem_nhds_subtype {s t : Set α} {a : s} : (↑) ⁻¹' t ∈ 𝓝 a ↔ t ∈ 𝓝[s] ↑a := by
rw [← map_nhds_subtype_val, mem_map]
theorem eventually_nhds_subtype_iff (s : Set α) (a : s) (P : α → Prop) :
(∀ᶠ x : s in 𝓝 a, P x) ↔ ∀ᶠ x in 𝓝[s] a, P x :=
preimage_coe_mem_nhds_subtype
theorem frequently_nhds_subtype_iff (s : Set α) (a : s) (P : α → Prop) :
(∃ᶠ x : s in 𝓝 a, P x) ↔ ∃ᶠ x in 𝓝[s] a, P x :=
eventually_nhds_subtype_iff s a (¬ P ·) |>.not
| theorem tendsto_nhdsWithin_iff_subtype {s : Set α} {a : α} (h : a ∈ s) (f : α → β) (l : Filter β) :
Tendsto f (𝓝[s] a) l ↔ Tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l := by
| Mathlib/Topology/ContinuousOn.lean | 506 | 507 |
/-
Copyright (c) 2023 David Loeffler. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Loeffler
-/
import Mathlib.Analysis.SpecialFunctions.JapaneseBracket
import Mathlib.Analysis.SpecialFunctions.Integrals
import Mathlib.MeasureTheory.Group.Integral
import Mathlib.MeasureTheory.Integral.IntegralEqImproper
import Mathlib.MeasureTheory.Measure.Lebesgue.Integral
/-!
# Evaluation of specific improper integrals
This file contains some integrability results, and evaluations of integrals, over `ℝ` or over
half-infinite intervals in `ℝ`.
These lemmas are stated in terms of either `Iic` or `Ioi` (neglecting `Iio` and `Ici`) to match
mathlib's conventions for integrals over finite intervals (see `intervalIntegral`).
## See also
- `Mathlib.Analysis.SpecialFunctions.Integrals` -- integrals over finite intervals
- `Mathlib.Analysis.SpecialFunctions.Gaussian` -- integral of `exp (-x ^ 2)`
- `Mathlib.Analysis.SpecialFunctions.JapaneseBracket`-- integrability of `(1+‖x‖)^(-r)`.
-/
open Real Set Filter MeasureTheory intervalIntegral
open scoped Topology
theorem integrableOn_exp_Iic (c : ℝ) : IntegrableOn exp (Iic c) := by
refine
integrableOn_Iic_of_intervalIntegral_norm_bounded (exp c) c
(fun y => intervalIntegrable_exp.1) tendsto_id
(eventually_of_mem (Iic_mem_atBot 0) fun y _ => ?_)
simp_rw [norm_of_nonneg (exp_pos _).le, integral_exp, sub_le_self_iff]
exact (exp_pos _).le
| theorem integrableOn_exp_neg_Ioi (c : ℝ) : IntegrableOn (fun (x : ℝ) => exp (-x)) (Ioi c) :=
integrableOn_Ici_iff_integrableOn_Ioi.mp (integrableOn_exp_Iic (-c)).comp_neg_Ici
theorem integral_exp_Iic (c : ℝ) : ∫ x : ℝ in Iic c, exp x = exp c := by
refine
tendsto_nhds_unique
| Mathlib/Analysis/SpecialFunctions/ImproperIntegrals.lean | 41 | 46 |
/-
Copyright (c) 2022 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov, Heather Macbeth
-/
import Mathlib.MeasureTheory.Function.L1Space.AEEqFun
import Mathlib.MeasureTheory.Function.LpSpace.Complete
import Mathlib.MeasureTheory.Function.LpSpace.Indicator
/-!
# Density of simple functions
Show that each `Lᵖ` Borel measurable function can be approximated in `Lᵖ` norm
by a sequence of simple functions.
## Main definitions
* `MeasureTheory.Lp.simpleFunc`, the type of `Lp` simple functions
* `coeToLp`, the embedding of `Lp.simpleFunc E p μ` into `Lp E p μ`
## Main results
* `tendsto_approxOn_Lp_eLpNorm` (Lᵖ convergence): If `E` is a `NormedAddCommGroup` and `f` is
measurable and `MemLp` (for `p < ∞`), then the simple functions
`SimpleFunc.approxOn f hf s 0 h₀ n` may be considered as elements of `Lp E p μ`, and they tend
in Lᵖ to `f`.
* `Lp.simpleFunc.isDenseEmbedding`: the embedding `coeToLp` of the `Lp` simple functions into
`Lp` is dense.
* `Lp.simpleFunc.induction`, `Lp.induction`, `MemLp.induction`, `Integrable.induction`: to prove
a predicate for all elements of one of these classes of functions, it suffices to check that it
behaves correctly on simple functions.
## TODO
For `E` finite-dimensional, simple functions `α →ₛ E` are dense in L^∞ -- prove this.
## Notations
* `α →ₛ β` (local notation): the type of simple functions `α → β`.
* `α →₁ₛ[μ] E`: the type of `L1` simple functions `α → β`.
-/
noncomputable section
open Set Function Filter TopologicalSpace ENNReal EMetric Finset
open scoped Topology ENNReal MeasureTheory
variable {α β ι E F 𝕜 : Type*}
namespace MeasureTheory
local infixr:25 " →ₛ " => SimpleFunc
namespace SimpleFunc
/-! ### Lp approximation by simple functions -/
section Lp
variable [MeasurableSpace β] [MeasurableSpace E] [NormedAddCommGroup E] [NormedAddCommGroup F]
{q : ℝ} {p : ℝ≥0∞}
theorem nnnorm_approxOn_le [OpensMeasurableSpace E] {f : β → E} (hf : Measurable f) {s : Set E}
{y₀ : E} (h₀ : y₀ ∈ s) [SeparableSpace s] (x : β) (n : ℕ) :
‖approxOn f hf s y₀ h₀ n x - f x‖₊ ≤ ‖f x - y₀‖₊ := by
have := edist_approxOn_le hf h₀ x n
rw [edist_comm y₀] at this
simp only [edist_nndist, nndist_eq_nnnorm] at this
exact mod_cast this
theorem norm_approxOn_y₀_le [OpensMeasurableSpace E] {f : β → E} (hf : Measurable f) {s : Set E}
{y₀ : E} (h₀ : y₀ ∈ s) [SeparableSpace s] (x : β) (n : ℕ) :
‖approxOn f hf s y₀ h₀ n x - y₀‖ ≤ ‖f x - y₀‖ + ‖f x - y₀‖ := by
simpa [enorm, edist_eq_enorm_sub, ← ENNReal.coe_add, norm_sub_rev]
using edist_approxOn_y0_le hf h₀ x n
theorem norm_approxOn_zero_le [OpensMeasurableSpace E] {f : β → E} (hf : Measurable f) {s : Set E}
(h₀ : (0 : E) ∈ s) [SeparableSpace s] (x : β) (n : ℕ) :
‖approxOn f hf s 0 h₀ n x‖ ≤ ‖f x‖ + ‖f x‖ := by
simpa [enorm, edist_eq_enorm_sub, ← ENNReal.coe_add, norm_sub_rev]
using edist_approxOn_y0_le hf h₀ x n
theorem tendsto_approxOn_Lp_eLpNorm [OpensMeasurableSpace E] {f : β → E} (hf : Measurable f)
{s : Set E} {y₀ : E} (h₀ : y₀ ∈ s) [SeparableSpace s] (hp_ne_top : p ≠ ∞) {μ : Measure β}
(hμ : ∀ᵐ x ∂μ, f x ∈ closure s) (hi : eLpNorm (fun x => f x - y₀) p μ < ∞) :
Tendsto (fun n => eLpNorm (⇑(approxOn f hf s y₀ h₀ n) - f) p μ) atTop (𝓝 0) := by
by_cases hp_zero : p = 0
· simpa only [hp_zero, eLpNorm_exponent_zero] using tendsto_const_nhds
have hp : 0 < p.toReal := toReal_pos hp_zero hp_ne_top
suffices Tendsto (fun n => ∫⁻ x, ‖approxOn f hf s y₀ h₀ n x - f x‖ₑ ^ p.toReal ∂μ) atTop (𝓝 0) by
simp only [eLpNorm_eq_lintegral_rpow_enorm hp_zero hp_ne_top]
convert continuous_rpow_const.continuousAt.tendsto.comp this
simp [zero_rpow_of_pos (_root_.inv_pos.mpr hp)]
-- We simply check the conditions of the Dominated Convergence Theorem:
-- (1) The function "`p`-th power of distance between `f` and the approximation" is measurable
have hF_meas n : Measurable fun x => ‖approxOn f hf s y₀ h₀ n x - f x‖ₑ ^ p.toReal := by
simpa only [← edist_eq_enorm_sub] using
(approxOn f hf s y₀ h₀ n).measurable_bind (fun y x => edist y (f x) ^ p.toReal) fun y =>
(measurable_edist_right.comp hf).pow_const p.toReal
-- (2) The functions "`p`-th power of distance between `f` and the approximation" are uniformly
-- bounded, at any given point, by `fun x => ‖f x - y₀‖ ^ p.toReal`
have h_bound n :
(fun x ↦ ‖approxOn f hf s y₀ h₀ n x - f x‖ₑ ^ p.toReal) ≤ᵐ[μ] (‖f · - y₀‖ₑ ^ p.toReal) :=
.of_forall fun x => rpow_le_rpow (coe_mono (nnnorm_approxOn_le hf h₀ x n)) toReal_nonneg
-- (3) The bounding function `fun x => ‖f x - y₀‖ ^ p.toReal` has finite integral
have h_fin : (∫⁻ a : β, ‖f a - y₀‖ₑ ^ p.toReal ∂μ) ≠ ⊤ :=
(lintegral_rpow_enorm_lt_top_of_eLpNorm_lt_top hp_zero hp_ne_top hi).ne
-- (4) The functions "`p`-th power of distance between `f` and the approximation" tend pointwise
-- to zero
have h_lim :
∀ᵐ a : β ∂μ, Tendsto (‖approxOn f hf s y₀ h₀ · a - f a‖ₑ ^ p.toReal) atTop (𝓝 0) := by
filter_upwards [hμ] with a ha
have : Tendsto (fun n => (approxOn f hf s y₀ h₀ n) a - f a) atTop (𝓝 (f a - f a)) :=
(tendsto_approxOn hf h₀ ha).sub tendsto_const_nhds
convert continuous_rpow_const.continuousAt.tendsto.comp (tendsto_coe.mpr this.nnnorm)
simp [zero_rpow_of_pos hp]
-- Then we apply the Dominated Convergence Theorem
simpa using tendsto_lintegral_of_dominated_convergence _ hF_meas h_bound h_fin h_lim
theorem memLp_approxOn [BorelSpace E] {f : β → E} {μ : Measure β} (fmeas : Measurable f)
(hf : MemLp f p μ) {s : Set E} {y₀ : E} (h₀ : y₀ ∈ s) [SeparableSpace s]
(hi₀ : MemLp (fun _ => y₀) p μ) (n : ℕ) : MemLp (approxOn f fmeas s y₀ h₀ n) p μ := by
refine ⟨(approxOn f fmeas s y₀ h₀ n).aestronglyMeasurable, ?_⟩
suffices eLpNorm (fun x => approxOn f fmeas s y₀ h₀ n x - y₀) p μ < ⊤ by
have : MemLp (fun x => approxOn f fmeas s y₀ h₀ n x - y₀) p μ :=
⟨(approxOn f fmeas s y₀ h₀ n - const β y₀).aestronglyMeasurable, this⟩
convert eLpNorm_add_lt_top this hi₀
ext x
simp
have hf' : MemLp (fun x => ‖f x - y₀‖) p μ := by
have h_meas : Measurable fun x => ‖f x - y₀‖ := by
simp only [← dist_eq_norm]
exact (continuous_id.dist continuous_const).measurable.comp fmeas
refine ⟨h_meas.aemeasurable.aestronglyMeasurable, ?_⟩
| rw [eLpNorm_norm]
convert eLpNorm_add_lt_top hf hi₀.neg with x
simp [sub_eq_add_neg]
have : ∀ᵐ x ∂μ, ‖approxOn f fmeas s y₀ h₀ n x - y₀‖ ≤ ‖‖f x - y₀‖ + ‖f x - y₀‖‖ := by
filter_upwards with x
convert norm_approxOn_y₀_le fmeas h₀ x n using 1
rw [Real.norm_eq_abs, abs_of_nonneg]
positivity
calc
eLpNorm (fun x => approxOn f fmeas s y₀ h₀ n x - y₀) p μ ≤
eLpNorm (fun x => ‖f x - y₀‖ + ‖f x - y₀‖) p μ :=
eLpNorm_mono_ae this
_ < ⊤ := eLpNorm_add_lt_top hf' hf'
theorem tendsto_approxOn_range_Lp_eLpNorm [BorelSpace E] {f : β → E} (hp_ne_top : p ≠ ∞)
{μ : Measure β} (fmeas : Measurable f) [SeparableSpace (range f ∪ {0} : Set E)]
(hf : eLpNorm f p μ < ∞) :
Tendsto (fun n => eLpNorm (⇑(approxOn f fmeas (range f ∪ {0}) 0 (by simp) n) - f) p μ)
atTop (𝓝 0) := by
refine tendsto_approxOn_Lp_eLpNorm fmeas _ hp_ne_top ?_ ?_
· filter_upwards with x using subset_closure (by simp)
· simpa using hf
theorem memLp_approxOn_range [BorelSpace E] {f : β → E} {μ : Measure β} (fmeas : Measurable f)
[SeparableSpace (range f ∪ {0} : Set E)] (hf : MemLp f p μ) (n : ℕ) :
MemLp (approxOn f fmeas (range f ∪ {0}) 0 (by simp) n) p μ :=
memLp_approxOn fmeas hf (y₀ := 0) (by simp) MemLp.zero n
| Mathlib/MeasureTheory/Function/SimpleFuncDenseLp.lean | 138 | 165 |
/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import Mathlib.Geometry.Euclidean.Projection
import Mathlib.Geometry.Euclidean.Sphere.Basic
import Mathlib.LinearAlgebra.AffineSpace.FiniteDimensional
import Mathlib.Tactic.DeriveFintype
/-!
# Circumcenter and circumradius
This file proves some lemmas on points equidistant from a set of
points, and defines the circumradius and circumcenter of a simplex.
There are also some definitions for use in calculations where it is
convenient to work with affine combinations of vertices together with
the circumcenter.
## Main definitions
* `circumcenter` and `circumradius` are the circumcenter and
circumradius of a simplex.
## References
* https://en.wikipedia.org/wiki/Circumscribed_circle
-/
noncomputable section
open RealInnerProductSpace
namespace EuclideanGeometry
variable {V : Type*} {P : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P]
[NormedAddTorsor V P]
open AffineSubspace
/-- The induction step for the existence and uniqueness of the
circumcenter. Given a nonempty set of points in a nonempty affine
subspace whose direction is complete, such that there is a unique
(circumcenter, circumradius) pair for those points in that subspace,
and a point `p` not in that subspace, there is a unique (circumcenter,
circumradius) pair for the set with `p` added, in the span of the
subspace with `p` added. -/
theorem existsUnique_dist_eq_of_insert {s : AffineSubspace ℝ P}
[s.direction.HasOrthogonalProjection] {ps : Set P} (hnps : ps.Nonempty) {p : P} (hps : ps ⊆ s)
(hp : p ∉ s) (hu : ∃! cs : Sphere P, cs.center ∈ s ∧ ps ⊆ (cs : Set P)) :
∃! cs₂ : Sphere P,
cs₂.center ∈ affineSpan ℝ (insert p (s : Set P)) ∧ insert p ps ⊆ (cs₂ : Set P) := by
haveI : Nonempty s := Set.Nonempty.to_subtype (hnps.mono hps)
rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩
simp only at hcc hcr hcccru
let x := dist cc (orthogonalProjection s p)
let y := dist p (orthogonalProjection s p)
have hy0 : y ≠ 0 := dist_orthogonalProjection_ne_zero_of_not_mem hp
let ycc₂ := (x * x + y * y - cr * cr) / (2 * y)
let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonalProjection s p : V) +ᵥ cc
let cr₂ := √(cr * cr + ycc₂ * ycc₂)
use ⟨cc₂, cr₂⟩
simp -zeta -proj only
have hpo : p = (1 : ℝ) • (p -ᵥ orthogonalProjection s p : V) +ᵥ (orthogonalProjection s p : P) :=
by simp
constructor
· constructor
· refine vadd_mem_of_mem_direction ?_ (mem_affineSpan ℝ (Set.mem_insert_of_mem _ hcc))
rw [direction_affineSpan]
exact
Submodule.smul_mem _ _
(vsub_mem_vectorSpan ℝ (Set.mem_insert _ _)
(Set.mem_insert_of_mem _ (orthogonalProjection_mem _)))
· intro p₁ hp₁
rw [Sphere.mem_coe, mem_sphere, ← mul_self_inj_of_nonneg dist_nonneg (Real.sqrt_nonneg _),
Real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))]
rcases hp₁ with hp₁ | hp₁
· rw [hp₁]
rw [hpo,
dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonalProjection_mem p) hcc _ _
(vsub_orthogonalProjection_mem_direction_orthogonal s p),
← dist_eq_norm_vsub V p, dist_comm _ cc]
-- TODO(https://github.com/leanprover-community/mathlib4/issues/15486): used to be `field_simp`, but was really slow
-- replaced by `simp only ...` to speed up. Reinstate `field_simp` once it is faster.
simp (disch := field_simp_discharge) only [div_div, sub_div', one_mul, mul_div_assoc',
div_mul_eq_mul_div, add_div', eq_div_iff, div_eq_iff, ycc₂]
ring
· rw [dist_sq_eq_dist_orthogonalProjection_sq_add_dist_orthogonalProjection_sq _ (hps hp₁),
orthogonalProjection_vadd_smul_vsub_orthogonalProjection _ _ hcc, Subtype.coe_mk,
dist_of_mem_subset_mk_sphere hp₁ hcr, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←
dist_eq_norm_vsub V, Real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg,
div_mul_cancel₀ _ hy0, abs_mul_abs_self]
· rintro ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩
simp only at hcc₃ hcr₃
obtain ⟨t₃, cc₃', hcc₃', hcc₃''⟩ :
∃ r : ℝ, ∃ p0 ∈ s, cc₃ = r • (p -ᵥ ↑((orthogonalProjection s) p)) +ᵥ p0 := by
rwa [mem_affineSpan_insert_iff (orthogonalProjection_mem p)] at hcc₃
have hcr₃' : ∃ r, ∀ p₁ ∈ ps, dist p₁ cc₃ = r :=
⟨cr₃, fun p₁ hp₁ => dist_of_mem_subset_mk_sphere (Set.mem_insert_of_mem _ hp₁) hcr₃⟩
rw [exists_dist_eq_iff_exists_dist_orthogonalProjection_eq hps cc₃, hcc₃'',
orthogonalProjection_vadd_smul_vsub_orthogonalProjection _ _ hcc₃'] at hcr₃'
obtain ⟨cr₃', hcr₃'⟩ := hcr₃'
have hu := hcccru ⟨cc₃', cr₃'⟩
simp only at hu
replace hu := hu ⟨hcc₃', hcr₃'⟩
-- Porting note: was
-- cases' hu with hucc hucr
-- substs hucc hucr
cases hu
have hcr₃val : cr₃ = √(cr * cr + t₃ * y * (t₃ * y)) := by
obtain ⟨p0, hp0⟩ := hnps
have h' : ↑(⟨cc, hcc₃'⟩ : s) = cc := rfl
rw [← dist_of_mem_subset_mk_sphere (Set.mem_insert_of_mem _ hp0) hcr₃, hcc₃'', ←
mul_self_inj_of_nonneg dist_nonneg (Real.sqrt_nonneg _),
Real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)),
dist_sq_eq_dist_orthogonalProjection_sq_add_dist_orthogonalProjection_sq _ (hps hp0),
orthogonalProjection_vadd_smul_vsub_orthogonalProjection _ _ hcc₃', h',
dist_of_mem_subset_mk_sphere hp0 hcr, dist_eq_norm_vsub V _ cc, vadd_vsub, norm_smul, ←
dist_eq_norm_vsub V p, Real.norm_eq_abs, ← mul_assoc, mul_comm _ |t₃|, ← mul_assoc,
abs_mul_abs_self]
ring
replace hcr₃ := dist_of_mem_subset_mk_sphere (Set.mem_insert _ _) hcr₃
rw [hpo, hcc₃'', hcr₃val, ← mul_self_inj_of_nonneg dist_nonneg (Real.sqrt_nonneg _),
dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonalProjection_mem p) hcc₃' _ _
(vsub_orthogonalProjection_mem_direction_orthogonal s p),
dist_comm, ← dist_eq_norm_vsub V p,
Real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃
change x * x + _ * (y * y) = _ at hcr₃
rw [show
x * x + (1 - t₃) * (1 - t₃) * (y * y) = x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y)
by ring,
add_left_inj] at hcr₃
have ht₃ : t₃ = ycc₂ / y := by field_simp [ycc₂, ← hcr₃, hy0]
subst ht₃
change cc₃ = cc₂ at hcc₃''
congr
rw [hcr₃val]
congr 2
field_simp [hy0]
/-- Given a finite nonempty affinely independent family of points,
there is a unique (circumcenter, circumradius) pair for those points
in the affine subspace they span. -/
theorem _root_.AffineIndependent.existsUnique_dist_eq {ι : Type*} [hne : Nonempty ι] [Finite ι]
{p : ι → P} (ha : AffineIndependent ℝ p) :
∃! cs : Sphere P, cs.center ∈ affineSpan ℝ (Set.range p) ∧ Set.range p ⊆ (cs : Set P) := by
cases nonempty_fintype ι
induction' hn : Fintype.card ι with m hm generalizing ι
· exfalso
have h := Fintype.card_pos_iff.2 hne
rw [hn] at h
exact lt_irrefl 0 h
· rcases m with - | m
· rw [Fintype.card_eq_one_iff] at hn
obtain ⟨i, hi⟩ := hn
haveI : Unique ι := ⟨⟨i⟩, hi⟩
use ⟨p i, 0⟩
simp only [Set.range_unique, AffineSubspace.mem_affineSpan_singleton]
constructor
· simp_rw [hi default, Set.singleton_subset_iff]
exact ⟨⟨⟩, by simp only [Metric.sphere_zero, Set.mem_singleton_iff]⟩
· rintro ⟨cc, cr⟩
simp only
rintro ⟨rfl, hdist⟩
simp? [Set.singleton_subset_iff] at hdist says
simp only [Set.singleton_subset_iff, Metric.mem_sphere, dist_self] at hdist
rw [hi default, hdist]
· have i := hne.some
let ι2 := { x // x ≠ i }
classical
have hc : Fintype.card ι2 = m + 1 := by
rw [Fintype.card_of_subtype {x | x ≠ i}]
· rw [Finset.filter_not]
-- Porting note: removed `simp_rw [eq_comm]` and used `filter_eq'` instead of `filter_eq`
rw [Finset.filter_eq' _ i, if_pos (Finset.mem_univ _),
Finset.card_sdiff (Finset.subset_univ _), Finset.card_singleton, Finset.card_univ, hn]
simp
· simp
haveI : Nonempty ι2 := Fintype.card_pos_iff.1 (hc.symm ▸ Nat.zero_lt_succ _)
have ha2 : AffineIndependent ℝ fun i2 : ι2 => p i2 := ha.subtype _
replace hm := hm ha2 _ hc
have hr : Set.range p = insert (p i) (Set.range fun i2 : ι2 => p i2) := by
change _ = insert _ (Set.range fun i2 : { x | x ≠ i } => p i2)
rw [← Set.image_eq_range, ← Set.image_univ, ← Set.image_insert_eq]
congr with j
simp [Classical.em]
rw [hr, ← affineSpan_insert_affineSpan]
refine existsUnique_dist_eq_of_insert (Set.range_nonempty _) (subset_affineSpan ℝ _) ?_ hm
convert ha.not_mem_affineSpan_diff i Set.univ
change (Set.range fun i2 : { x | x ≠ i } => p i2) = _
rw [← Set.image_eq_range]
congr with j
simp
end EuclideanGeometry
namespace Affine
namespace Simplex
open Finset AffineSubspace EuclideanGeometry
variable {V : Type*} {P : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P]
[NormedAddTorsor V P]
/-- The circumsphere of a simplex. -/
def circumsphere {n : ℕ} (s : Simplex ℝ P n) : Sphere P :=
s.independent.existsUnique_dist_eq.choose
/-- The property satisfied by the circumsphere. -/
theorem circumsphere_unique_dist_eq {n : ℕ} (s : Simplex ℝ P n) :
(s.circumsphere.center ∈ affineSpan ℝ (Set.range s.points) ∧
Set.range s.points ⊆ s.circumsphere) ∧
∀ cs : Sphere P,
cs.center ∈ affineSpan ℝ (Set.range s.points) ∧ Set.range s.points ⊆ cs →
cs = s.circumsphere :=
s.independent.existsUnique_dist_eq.choose_spec
/-- The circumcenter of a simplex. -/
def circumcenter {n : ℕ} (s : Simplex ℝ P n) : P :=
s.circumsphere.center
/-- The circumradius of a simplex. -/
def circumradius {n : ℕ} (s : Simplex ℝ P n) : ℝ :=
s.circumsphere.radius
/-- The center of the circumsphere is the circumcenter. -/
@[simp]
theorem circumsphere_center {n : ℕ} (s : Simplex ℝ P n) : s.circumsphere.center = s.circumcenter :=
rfl
/-- The radius of the circumsphere is the circumradius. -/
@[simp]
theorem circumsphere_radius {n : ℕ} (s : Simplex ℝ P n) : s.circumsphere.radius = s.circumradius :=
rfl
/-- The circumcenter lies in the affine span. -/
theorem circumcenter_mem_affineSpan {n : ℕ} (s : Simplex ℝ P n) :
s.circumcenter ∈ affineSpan ℝ (Set.range s.points) :=
s.circumsphere_unique_dist_eq.1.1
/-- All points have distance from the circumcenter equal to the
circumradius. -/
@[simp]
theorem dist_circumcenter_eq_circumradius {n : ℕ} (s : Simplex ℝ P n) (i : Fin (n + 1)) :
dist (s.points i) s.circumcenter = s.circumradius :=
dist_of_mem_subset_sphere (Set.mem_range_self _) s.circumsphere_unique_dist_eq.1.2
/-- All points lie in the circumsphere. -/
theorem mem_circumsphere {n : ℕ} (s : Simplex ℝ P n) (i : Fin (n + 1)) :
s.points i ∈ s.circumsphere :=
s.dist_circumcenter_eq_circumradius i
/-- All points have distance to the circumcenter equal to the
circumradius. -/
@[simp]
theorem dist_circumcenter_eq_circumradius' {n : ℕ} (s : Simplex ℝ P n) :
∀ i, dist s.circumcenter (s.points i) = s.circumradius := by
intro i
rw [dist_comm]
exact dist_circumcenter_eq_circumradius _ _
/-- Given a point in the affine span from which all the points are
equidistant, that point is the circumcenter. -/
theorem eq_circumcenter_of_dist_eq {n : ℕ} (s : Simplex ℝ P n) {p : P}
(hp : p ∈ affineSpan ℝ (Set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) :
p = s.circumcenter := by
have h := s.circumsphere_unique_dist_eq.2 ⟨p, r⟩
simp only [hp, hr, forall_const, eq_self_iff_true, subset_sphere, Sphere.ext_iff,
Set.forall_mem_range, mem_sphere, true_and] at h
-- Porting note: added the next three lines (`simp` less powerful)
rw [subset_sphere (s := ⟨p, r⟩)] at h
simp only [hp, hr, forall_const, eq_self_iff_true, subset_sphere, Sphere.ext_iff,
Set.forall_mem_range, mem_sphere, true_and] at h
exact h.1
/-- Given a point in the affine span from which all the points are
equidistant, that distance is the circumradius. -/
theorem eq_circumradius_of_dist_eq {n : ℕ} (s : Simplex ℝ P n) {p : P}
(hp : p ∈ affineSpan ℝ (Set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) :
r = s.circumradius := by
have h := s.circumsphere_unique_dist_eq.2 ⟨p, r⟩
simp only [hp, hr, forall_const, eq_self_iff_true, subset_sphere, Sphere.ext_iff,
Set.forall_mem_range, mem_sphere] at h
-- Porting note: added the next three lines (`simp` less powerful)
rw [subset_sphere (s := ⟨p, r⟩)] at h
simp only [hp, hr, forall_const, eq_self_iff_true, subset_sphere, Sphere.ext_iff,
Set.forall_mem_range, mem_sphere, true_and] at h
exact h.2
/-- The circumradius is non-negative. -/
theorem circumradius_nonneg {n : ℕ} (s : Simplex ℝ P n) : 0 ≤ s.circumradius :=
s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg
/-- The circumradius of a simplex with at least two points is
positive. -/
theorem circumradius_pos {n : ℕ} (s : Simplex ℝ P (n + 1)) : 0 < s.circumradius := by
refine lt_of_le_of_ne s.circumradius_nonneg ?_
intro h
have hr := s.dist_circumcenter_eq_circumradius
simp_rw [← h, dist_eq_zero] at hr
have h01 := s.independent.injective.ne (by simp : (0 : Fin (n + 2)) ≠ 1)
simp [hr] at h01
/-- The circumcenter of a 0-simplex equals its unique point. -/
theorem circumcenter_eq_point (s : Simplex ℝ P 0) (i : Fin 1) : s.circumcenter = s.points i := by
have h := s.circumcenter_mem_affineSpan
have : Unique (Fin 1) := ⟨⟨0, by decide⟩, fun a => by simp only [Fin.eq_zero]⟩
simp only [Set.range_unique, AffineSubspace.mem_affineSpan_singleton] at h
rw [h]
congr
simp only [eq_iff_true_of_subsingleton]
/-- The circumcenter of a 1-simplex equals its centroid. -/
theorem circumcenter_eq_centroid (s : Simplex ℝ P 1) :
s.circumcenter = Finset.univ.centroid ℝ s.points := by
have hr :
Set.Pairwise Set.univ fun i j : Fin 2 =>
dist (s.points i) (Finset.univ.centroid ℝ s.points) =
dist (s.points j) (Finset.univ.centroid ℝ s.points) := by
intro i hi j hj hij
rw [Finset.centroid_pair_fin, dist_eq_norm_vsub V (s.points i),
dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, ←
one_smul ℝ (s.points i -ᵥ s.points 0), ← one_smul ℝ (s.points j -ᵥ s.points 0)]
fin_cases i <;> fin_cases j <;> simp [-one_smul, ← sub_smul] <;> norm_num
rw [Set.pairwise_eq_iff_exists_eq] at hr
obtain ⟨r, hr⟩ := hr
exact
(s.eq_circumcenter_of_dist_eq
(centroid_mem_affineSpan_of_card_eq_add_one ℝ _ (Finset.card_fin 2)) fun i =>
hr i (Set.mem_univ _)).symm
/-- Reindexing a simplex along an `Equiv` of index types does not change the circumsphere. -/
@[simp]
theorem circumsphere_reindex {m n : ℕ} (s : Simplex ℝ P m) (e : Fin (m + 1) ≃ Fin (n + 1)) :
(s.reindex e).circumsphere = s.circumsphere := by
refine s.circumsphere_unique_dist_eq.2 _ ⟨?_, ?_⟩ <;> rw [← s.reindex_range_points e]
· exact (s.reindex e).circumsphere_unique_dist_eq.1.1
· exact (s.reindex e).circumsphere_unique_dist_eq.1.2
/-- Reindexing a simplex along an `Equiv` of index types does not change the circumcenter. -/
@[simp]
theorem circumcenter_reindex {m n : ℕ} (s : Simplex ℝ P m) (e : Fin (m + 1) ≃ Fin (n + 1)) :
(s.reindex e).circumcenter = s.circumcenter := by simp_rw [circumcenter, circumsphere_reindex]
/-- Reindexing a simplex along an `Equiv` of index types does not change the circumradius. -/
@[simp]
theorem circumradius_reindex {m n : ℕ} (s : Simplex ℝ P m) (e : Fin (m + 1) ≃ Fin (n + 1)) :
(s.reindex e).circumradius = s.circumradius := by simp_rw [circumradius, circumsphere_reindex]
attribute [local instance] AffineSubspace.toAddTorsor
theorem dist_circumcenter_sq_eq_sq_sub_circumradius {n : ℕ} {r : ℝ} (s : Simplex ℝ P n) {p₁ : P}
(h₁ : ∀ i : Fin (n + 1), dist (s.points i) p₁ = r)
(h₁' : ↑(s.orthogonalProjectionSpan p₁) = s.circumcenter)
(h : s.points 0 ∈ affineSpan ℝ (Set.range s.points)) :
dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius := by
rw [dist_comm, ← h₁ 0,
s.dist_sq_eq_dist_orthogonalProjection_sq_add_dist_orthogonalProjection_sq p₁ h]
simp only [h₁', dist_comm p₁, add_sub_cancel_left, Simplex.dist_circumcenter_eq_circumradius]
/-- If there exists a distance that a point has from all vertices of a
simplex, the orthogonal projection of that point onto the subspace
spanned by that simplex is its circumcenter. -/
theorem orthogonalProjection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : Simplex ℝ P n) {p : P}
(hr : ∃ r, ∀ i, dist (s.points i) p = r) :
↑(s.orthogonalProjectionSpan p) = s.circumcenter := by
change ∃ r : ℝ, ∀ i, (fun x => dist x p = r) (s.points i) at hr
have hr : ∃ (r : ℝ), ∀ (a : P),
a ∈ Set.range (fun (i : Fin (n + 1)) => s.points i) → dist a p = r := by
obtain ⟨r, hr⟩ := hr
use r
refine Set.forall_mem_range.mpr ?_
exact hr
rw [exists_dist_eq_iff_exists_dist_orthogonalProjection_eq (subset_affineSpan ℝ _) p] at hr
obtain ⟨r, hr⟩ := hr
exact
s.eq_circumcenter_of_dist_eq (orthogonalProjection_mem p) fun i => hr _ (Set.mem_range_self i)
/-- If a point has the same distance from all vertices of a simplex,
the orthogonal projection of that point onto the subspace spanned by
that simplex is its circumcenter. -/
theorem orthogonalProjection_eq_circumcenter_of_dist_eq {n : ℕ} (s : Simplex ℝ P n) {p : P} {r : ℝ}
(hr : ∀ i, dist (s.points i) p = r) : ↑(s.orthogonalProjectionSpan p) = s.circumcenter :=
s.orthogonalProjection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩
/-- The orthogonal projection of the circumcenter onto a face is the
circumcenter of that face. -/
theorem orthogonalProjection_circumcenter {n : ℕ} (s : Simplex ℝ P n) {fs : Finset (Fin (n + 1))}
{m : ℕ} (h : #fs = m + 1) :
| ↑((s.face h).orthogonalProjectionSpan s.circumcenter) = (s.face h).circumcenter :=
haveI hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r := by
use s.circumradius
simp [face_points]
orthogonalProjection_eq_circumcenter_of_exists_dist_eq _ hr
| Mathlib/Geometry/Euclidean/Circumcenter.lean | 392 | 396 |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import Mathlib.Analysis.SpecialFunctions.Exp
import Mathlib.Data.Nat.Factorization.Defs
import Mathlib.Analysis.NormedSpace.Real
import Mathlib.Data.Rat.Cast.CharZero
/-!
# Real logarithm
In this file we define `Real.log` to be the logarithm of a real number. As usual, we extend it from
its domain `(0, +∞)` to a globally defined function. We choose to do it so that `log 0 = 0` and
`log (-x) = log x`.
We prove some basic properties of this function and show that it is continuous.
## Tags
logarithm, continuity
-/
open Set Filter Function
open Topology
noncomputable section
namespace Real
variable {x y : ℝ}
/-- The real logarithm function, equal to the inverse of the exponential for `x > 0`,
to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to
`(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and
the derivative of `log` is `1/x` away from `0`. -/
@[pp_nodot]
noncomputable def log (x : ℝ) : ℝ :=
if hx : x = 0 then 0 else expOrderIso.symm ⟨|x|, abs_pos.2 hx⟩
theorem log_of_ne_zero (hx : x ≠ 0) : log x = expOrderIso.symm ⟨|x|, abs_pos.2 hx⟩ :=
dif_neg hx
theorem log_of_pos (hx : 0 < x) : log x = expOrderIso.symm ⟨x, hx⟩ := by
rw [log_of_ne_zero hx.ne']
congr
exact abs_of_pos hx
theorem exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = |x| := by
rw [log_of_ne_zero hx, ← coe_expOrderIso_apply, OrderIso.apply_symm_apply, Subtype.coe_mk]
theorem exp_log (hx : 0 < x) : exp (log x) = x := by
rw [exp_log_eq_abs hx.ne']
exact abs_of_pos hx
theorem exp_log_of_neg (hx : x < 0) : exp (log x) = -x := by
rw [exp_log_eq_abs (ne_of_lt hx)]
exact abs_of_neg hx
theorem le_exp_log (x : ℝ) : x ≤ exp (log x) := by
by_cases h_zero : x = 0
· rw [h_zero, log, dif_pos rfl, exp_zero]
exact zero_le_one
· rw [exp_log_eq_abs h_zero]
exact le_abs_self _
@[simp]
theorem log_exp (x : ℝ) : log (exp x) = x :=
exp_injective <| exp_log (exp_pos x)
theorem exp_one_mul_le_exp {x : ℝ} : exp 1 * x ≤ exp x := by
by_cases hx0 : x ≤ 0
· apply le_trans (mul_nonpos_of_nonneg_of_nonpos (exp_pos 1).le hx0) (exp_nonneg x)
· have h := add_one_le_exp (log x)
rwa [← exp_le_exp, exp_add, exp_log (lt_of_not_le hx0), mul_comm] at h
theorem two_mul_le_exp {x : ℝ} : 2 * x ≤ exp x := by
by_cases hx0 : x < 0
· exact le_trans (mul_nonpos_of_nonneg_of_nonpos (by simp only [Nat.ofNat_nonneg]) hx0.le)
(exp_nonneg x)
· apply le_trans (mul_le_mul_of_nonneg_right _ (le_of_not_lt hx0)) exp_one_mul_le_exp
have := Real.add_one_le_exp 1
rwa [one_add_one_eq_two] at this
theorem surjOn_log : SurjOn log (Ioi 0) univ := fun x _ => ⟨exp x, exp_pos x, log_exp x⟩
theorem log_surjective : Surjective log := fun x => ⟨exp x, log_exp x⟩
@[simp]
theorem range_log : range log = univ :=
log_surjective.range_eq
@[simp]
theorem log_zero : log 0 = 0 :=
dif_pos rfl
@[simp]
theorem log_one : log 1 = 0 :=
exp_injective <| by rw [exp_log zero_lt_one, exp_zero]
/-- This holds true for all `x : ℝ` because of the junk values `0 / 0 = 0` and `log 0 = 0`. -/
@[simp] lemma log_div_self (x : ℝ) : log (x / x) = 0 := by
obtain rfl | hx := eq_or_ne x 0 <;> simp [*]
@[simp]
theorem log_abs (x : ℝ) : log |x| = log x := by
by_cases h : x = 0
· simp [h]
· rw [← exp_eq_exp, exp_log_eq_abs h, exp_log_eq_abs (abs_pos.2 h).ne', abs_abs]
@[simp]
theorem log_neg_eq_log (x : ℝ) : log (-x) = log x := by rw [← log_abs x, ← log_abs (-x), abs_neg]
theorem sinh_log {x : ℝ} (hx : 0 < x) : sinh (log x) = (x - x⁻¹) / 2 := by
rw [sinh_eq, exp_neg, exp_log hx]
theorem cosh_log {x : ℝ} (hx : 0 < x) : cosh (log x) = (x + x⁻¹) / 2 := by
rw [cosh_eq, exp_neg, exp_log hx]
theorem surjOn_log' : SurjOn log (Iio 0) univ := fun x _ =>
⟨-exp x, neg_lt_zero.2 <| exp_pos x, by rw [log_neg_eq_log, log_exp]⟩
theorem log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y :=
exp_injective <| by
rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul]
theorem log_div (hx : x ≠ 0) (hy : y ≠ 0) : log (x / y) = log x - log y :=
exp_injective <| by
rw [exp_log_eq_abs (div_ne_zero hx hy), exp_sub, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_div]
@[simp]
theorem log_inv (x : ℝ) : log x⁻¹ = -log x := by
by_cases hx : x = 0; · simp [hx]
rw [← exp_eq_exp, exp_log_eq_abs (inv_ne_zero hx), exp_neg, exp_log_eq_abs hx, abs_inv]
theorem log_le_log_iff (h : 0 < x) (h₁ : 0 < y) : log x ≤ log y ↔ x ≤ y := by
rw [← exp_le_exp, exp_log h, exp_log h₁]
@[gcongr, bound]
lemma log_le_log (hx : 0 < x) (hxy : x ≤ y) : log x ≤ log y :=
(log_le_log_iff hx (hx.trans_le hxy)).2 hxy
@[gcongr, bound]
theorem log_lt_log (hx : 0 < x) (h : x < y) : log x < log y := by
rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)]
theorem log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by
rw [← exp_lt_exp, exp_log hx, exp_log hy]
theorem log_le_iff_le_exp (hx : 0 < x) : log x ≤ y ↔ x ≤ exp y := by rw [← exp_le_exp, exp_log hx]
theorem log_lt_iff_lt_exp (hx : 0 < x) : log x < y ↔ x < exp y := by rw [← exp_lt_exp, exp_log hx]
theorem le_log_iff_exp_le (hy : 0 < y) : x ≤ log y ↔ exp x ≤ y := by rw [← exp_le_exp, exp_log hy]
theorem lt_log_iff_exp_lt (hy : 0 < y) : x < log y ↔ exp x < y := by rw [← exp_lt_exp, exp_log hy]
theorem log_pos_iff (hx : 0 ≤ x) : 0 < log x ↔ 1 < x := by
rcases hx.eq_or_lt with (rfl | hx)
· simp [le_refl, zero_le_one]
rw [← log_one]
exact log_lt_log_iff zero_lt_one hx
@[bound]
theorem log_pos (hx : 1 < x) : 0 < log x :=
(log_pos_iff (lt_trans zero_lt_one hx).le).2 hx
theorem log_pos_of_lt_neg_one (hx : x < -1) : 0 < log x := by
rw [← neg_neg x, log_neg_eq_log]
have : 1 < -x := by linarith
exact log_pos this
theorem log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by
rw [← log_one]
exact log_lt_log_iff h zero_lt_one
@[bound]
theorem log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 :=
(log_neg_iff h0).2 h1
theorem log_neg_of_lt_zero (h0 : x < 0) (h1 : -1 < x) : log x < 0 := by
rw [← neg_neg x, log_neg_eq_log]
have h0' : 0 < -x := by linarith
have h1' : -x < 1 := by linarith
exact log_neg h0' h1'
theorem log_nonneg_iff (hx : 0 < x) : 0 ≤ log x ↔ 1 ≤ x := by rw [← not_lt, log_neg_iff hx, not_lt]
@[bound]
theorem log_nonneg (hx : 1 ≤ x) : 0 ≤ log x :=
(log_nonneg_iff (zero_lt_one.trans_le hx)).2 hx
theorem log_nonpos_iff (hx : 0 ≤ x) : log x ≤ 0 ↔ x ≤ 1 := by
rcases hx.eq_or_lt with (rfl | hx)
· simp [le_refl, zero_le_one]
rw [← not_lt, log_pos_iff hx.le, not_lt]
@[deprecated (since := "2025-01-16")]
alias log_nonpos_iff' := log_nonpos_iff
@[bound]
theorem log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 :=
(log_nonpos_iff hx).2 h'x
theorem log_natCast_nonneg (n : ℕ) : 0 ≤ log n := by
if hn : n = 0 then
simp [hn]
else
have : (1 : ℝ) ≤ n := mod_cast Nat.one_le_of_lt <| Nat.pos_of_ne_zero hn
exact log_nonneg this
theorem log_neg_natCast_nonneg (n : ℕ) : 0 ≤ log (-n) := by
rw [← log_neg_eq_log, neg_neg]
exact log_natCast_nonneg _
theorem log_intCast_nonneg (n : ℤ) : 0 ≤ log n := by
cases lt_trichotomy 0 n with
| inl hn =>
have : (1 : ℝ) ≤ n := mod_cast hn
exact log_nonneg this
| inr hn =>
cases hn with
| inl hn => simp [hn.symm]
| inr hn =>
have : (1 : ℝ) ≤ -n := by rw [← neg_zero, ← lt_neg] at hn; exact mod_cast hn
rw [← log_neg_eq_log]
exact log_nonneg this
|
theorem strictMonoOn_log : StrictMonoOn log (Set.Ioi 0) := fun _ hx _ _ hxy => log_lt_log hx hxy
| Mathlib/Analysis/SpecialFunctions/Log/Basic.lean | 230 | 232 |
/-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Nat.Choose.Basic
import Mathlib.Data.List.FinRange
import Mathlib.Data.List.Perm.Basic
import Mathlib.Data.List.Lex
import Mathlib.Data.List.Induction
/-! # sublists
`List.Sublists` gives a list of all (not necessarily contiguous) sublists of a list.
This file contains basic results on this function.
-/
universe u v w
variable {α : Type u} {β : Type v} {γ : Type w}
open Nat
namespace List
/-! ### sublists -/
@[simp]
theorem sublists'_nil : sublists' (@nil α) = [[]] :=
rfl
@[simp]
theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] :=
rfl
/-- Auxiliary helper definition for `sublists'` -/
def sublists'Aux (a : α) (r₁ r₂ : List (List α)) : List (List α) :=
r₁.foldl (init := r₂) fun r l => r ++ [a :: l]
theorem sublists'Aux_eq_array_foldl (a : α) : ∀ (r₁ r₂ : List (List α)),
sublists'Aux a r₁ r₂ = ((r₁.toArray).foldl (init := r₂.toArray)
(fun r l => r.push (a :: l))).toList := by
intro r₁ r₂
rw [sublists'Aux, Array.foldl_toList]
have := List.foldl_hom Array.toList (g₁ := fun r l => r.push (a :: l))
(g₂ := fun r l => r ++ [a :: l]) (l := r₁) (init := r₂.toArray) (by simp)
simpa using this
theorem sublists'_eq_sublists'Aux (l : List α) :
sublists' l = l.foldr (fun a r => sublists'Aux a r r) [[]] := by
simp only [sublists', sublists'Aux_eq_array_foldl]
rw [← List.foldr_hom Array.toList]
· intros _ _; congr
theorem sublists'Aux_eq_map (a : α) (r₁ : List (List α)) : ∀ (r₂ : List (List α)),
sublists'Aux a r₁ r₂ = r₂ ++ map (cons a) r₁ :=
List.reverseRecOn r₁ (fun _ => by simp [sublists'Aux]) fun r₁ l ih r₂ => by
rw [map_append, map_singleton, ← append_assoc, ← ih, sublists'Aux, foldl_append, foldl]
simp [sublists'Aux]
@[simp 900]
theorem sublists'_cons (a : α) (l : List α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by
simp [sublists'_eq_sublists'Aux, foldr_cons, sublists'Aux_eq_map]
@[simp]
theorem mem_sublists' {s t : List α} : s ∈ sublists' t ↔ s <+ t := by
induction' t with a t IH generalizing s
· simp only [sublists'_nil, mem_singleton]
exact ⟨fun h => by rw [h], eq_nil_of_sublist_nil⟩
simp only [sublists'_cons, mem_append, IH, mem_map]
constructor <;> intro h
· rcases h with (h | ⟨s, h, rfl⟩)
· exact sublist_cons_of_sublist _ h
· exact h.cons_cons _
· obtain - | ⟨-, h⟩ | ⟨-, h⟩ := h
· exact Or.inl h
· exact Or.inr ⟨_, h, rfl⟩
@[simp]
theorem length_sublists' : ∀ l : List α, length (sublists' l) = 2 ^ length l
| [] => rfl
| a :: l => by
simp +arith only [sublists'_cons, length_append, length_sublists' l,
length_map, length, Nat.pow_succ']
@[simp]
theorem sublists_nil : sublists (@nil α) = [[]] :=
rfl
@[simp]
theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] :=
rfl
/-- Auxiliary helper function for `sublists` -/
def sublistsAux (a : α) (r : List (List α)) : List (List α) :=
r.foldl (init := []) fun r l => r ++ [l, a :: l]
theorem sublistsAux_eq_array_foldl :
sublistsAux = fun (a : α) (r : List (List α)) =>
(r.toArray.foldl (init := #[])
fun r l => (r.push l).push (a :: l)).toList := by
funext a r
simp only [sublistsAux, Array.foldl_toList, Array.mkEmpty]
have := foldl_hom Array.toList (g₁ := fun r l => (r.push l).push (a :: l))
(g₂ := fun r l => r ++ [l, a :: l]) (l := r) (init := #[]) (by simp)
simpa using this
theorem sublistsAux_eq_flatMap :
sublistsAux = fun (a : α) (r : List (List α)) => r.flatMap fun l => [l, a :: l] :=
funext fun a => funext fun r =>
List.reverseRecOn r
(by simp [sublistsAux])
(fun r l ih => by
rw [flatMap_append, ← ih, flatMap_singleton, sublistsAux, foldl_append]
simp [sublistsAux])
@[csimp] theorem sublists_eq_sublistsFast : @sublists = @sublistsFast := by
ext α l : 2
trans l.foldr sublistsAux [[]]
· rw [sublistsAux_eq_flatMap, sublists]
· simp only [sublistsFast, sublistsAux_eq_array_foldl, Array.foldr_toList]
rw [← foldr_hom Array.toList]
· intros _ _; congr
theorem sublists_append (l₁ l₂ : List α) :
sublists (l₁ ++ l₂) = (sublists l₂) >>= (fun x => (sublists l₁).map (· ++ x)) := by
simp only [sublists, foldr_append]
induction l₁ with
| nil => simp
| cons a l₁ ih =>
rw [foldr_cons, ih]
simp [List.flatMap, flatten_flatten, Function.comp_def]
theorem sublists_cons (a : α) (l : List α) :
sublists (a :: l) = sublists l >>= (fun x => [x, a :: x]) :=
show sublists ([a] ++ l) = _ by
rw [sublists_append]
simp only [sublists_singleton, map_cons, bind_eq_flatMap, nil_append, cons_append, map_nil]
@[simp]
theorem sublists_concat (l : List α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (fun x => x ++ [a]) (sublists l) := by
rw [sublists_append, sublists_singleton, bind_eq_flatMap, flatMap_cons, flatMap_cons, flatMap_nil,
map_id'' append_nil, append_nil]
theorem sublists_reverse (l : List α) : sublists (reverse l) = map reverse (sublists' l) := by
induction' l with hd tl ih <;> [rfl;
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_flatMap, map_map, flatMap_cons, append_nil, flatMap_nil,
Function.comp_def]]
theorem sublists_eq_sublists' (l : List α) : sublists l = map reverse (sublists' (reverse l)) := by
rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : List α) : sublists' (reverse l) = map reverse (sublists l) := by
simp only [sublists_eq_sublists', map_map, map_id'' reverse_reverse, Function.comp_def]
theorem sublists'_eq_sublists (l : List α) : sublists' l = map reverse (sublists (reverse l)) := by
rw [← sublists'_reverse, reverse_reverse]
@[simp]
theorem mem_sublists {s t : List α} : s ∈ sublists t ↔ s <+ t := by
rw [← reverse_sublist, ← mem_sublists', sublists'_reverse,
mem_map_of_injective reverse_injective]
@[simp]
theorem length_sublists (l : List α) : length (sublists l) = 2 ^ length l := by
simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_pure_sublist_sublists (l : List α) : map pure l <+ sublists l := by
induction' l using reverseRecOn with l a ih <;> simp only [map, map_append, sublists_concat]
· simp only [sublists_nil, sublist_cons_self]
exact ((append_sublist_append_left _).2 <|
singleton_sublist.2 <| mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by rfl⟩).trans
((append_sublist_append_right _).2 ih)
/-! ### sublistsLen -/
/-- Auxiliary function to construct the list of all sublists of a given length. Given an
integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of
`f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/
def sublistsLenAux : ℕ → List α → (List α → β) → List β → List β
| 0, _, f, r => f [] :: r
| _ + 1, [], _, r => r
| n + 1, a :: l, f, r => sublistsLenAux (n + 1) l f (sublistsLenAux n l (f ∘ List.cons a) r)
/-- The list of all sublists of a list `l` that are of length `n`. For instance, for
`l = [0, 1, 2, 3]` and `n = 2`, one gets
`[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/
def sublistsLen (n : ℕ) (l : List α) : List (List α) :=
sublistsLenAux n l id []
theorem sublistsLenAux_append :
∀ (n : ℕ) (l : List α) (f : List α → β) (g : β → γ) (r : List β) (s : List γ),
sublistsLenAux n l (g ∘ f) (r.map g ++ s) = (sublistsLenAux n l f r).map g ++ s
| 0, l, f, g, r, s => by unfold sublistsLenAux; simp
| _ + 1, [], _, _, _, _ => rfl
| n + 1, a :: l, f, g, r, s => by
unfold sublistsLenAux
simp only [show (g ∘ f) ∘ List.cons a = g ∘ f ∘ List.cons a by rfl, sublistsLenAux_append,
sublistsLenAux_append]
theorem sublistsLenAux_eq (l : List α) (n) (f : List α → β) (r) :
sublistsLenAux n l f r = (sublistsLen n l).map f ++ r := by
rw [sublistsLen, ← sublistsLenAux_append]; rfl
theorem sublistsLenAux_zero (l : List α) (f : List α → β) (r) :
sublistsLenAux 0 l f r = f [] :: r := by cases l <;> rfl
@[simp]
theorem sublistsLen_zero (l : List α) : sublistsLen 0 l = [[]] :=
sublistsLenAux_zero _ _ _
@[simp]
theorem sublistsLen_succ_nil (n) : sublistsLen (n + 1) (@nil α) = [] :=
rfl
@[simp]
theorem sublistsLen_succ_cons (n) (a : α) (l) :
sublistsLen (n + 1) (a :: l) = sublistsLen (n + 1) l ++ (sublistsLen n l).map (cons a) := by
rw [sublistsLen, sublistsLenAux, sublistsLenAux_eq, sublistsLenAux_eq, map_id,
append_nil]; rfl
theorem sublistsLen_one (l : List α) : sublistsLen 1 l = l.reverse.map ([·]) :=
l.rec (by rw [sublistsLen_succ_nil, reverse_nil, map_nil]) fun a s ih ↦ by
rw [sublistsLen_succ_cons, ih, reverse_cons, map_append, sublistsLen_zero]; rfl
@[simp]
theorem length_sublistsLen :
∀ (n) (l : List α), length (sublistsLen n l) = Nat.choose (length l) n
| 0, l => by simp
| _ + 1, [] => by simp
| n + 1, a :: l => by
rw [sublistsLen_succ_cons, length_append, length_sublistsLen (n+1) l,
length_map, length_sublistsLen n l, length_cons, Nat.choose_succ_succ, Nat.add_comm]
theorem sublistsLen_sublist_sublists' :
∀ (n) (l : List α), sublistsLen n l <+ sublists' l
| 0, l => by simp
| _ + 1, [] => nil_sublist _
| n + 1, a :: l => by
rw [sublistsLen_succ_cons, sublists'_cons]
exact (sublistsLen_sublist_sublists' _ _).append ((sublistsLen_sublist_sublists' _ _).map _)
theorem sublistsLen_sublist_of_sublist (n) {l₁ l₂ : List α} (h : l₁ <+ l₂) :
sublistsLen n l₁ <+ sublistsLen n l₂ := by
induction' n with n IHn generalizing l₁ l₂; · simp
induction h with
| slnil => rfl
| cons a _ IH =>
refine IH.trans ?_
rw [sublistsLen_succ_cons]
apply sublist_append_left
| cons₂ a s IH => simpa only [sublistsLen_succ_cons] using IH.append ((IHn s).map _)
theorem length_of_sublistsLen :
∀ {n} {l l' : List α}, l' ∈ sublistsLen n l → length l' = n
| 0, l, l', h => by simp_all
| n + 1, a :: l, l', h => by
rw [sublistsLen_succ_cons, mem_append, mem_map] at h
rcases h with (h | ⟨l', h, rfl⟩)
· exact length_of_sublistsLen h
· exact congr_arg (· + 1) (length_of_sublistsLen h)
theorem mem_sublistsLen_self {l l' : List α} (h : l' <+ l) :
l' ∈ sublistsLen (length l') l := by
induction h with
| slnil => simp
| @cons l₁ l₂ a s IH =>
rcases l₁ with - | ⟨b, l₁⟩
· simp
· rw [length, sublistsLen_succ_cons]
exact mem_append_left _ IH
| cons₂ a s IH =>
rw [length, sublistsLen_succ_cons]
exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩)
@[simp]
theorem mem_sublistsLen {n} {l l' : List α} :
l' ∈ sublistsLen n l ↔ l' <+ l ∧ length l' = n :=
⟨fun h =>
⟨mem_sublists'.1 ((sublistsLen_sublist_sublists' _ _).subset h), length_of_sublistsLen h⟩,
fun ⟨h₁, h₂⟩ => h₂ ▸ mem_sublistsLen_self h₁⟩
theorem sublistsLen_of_length_lt {n} {l : List α} (h : l.length < n) : sublistsLen n l = [] :=
eq_nil_iff_forall_not_mem.mpr fun _ =>
mem_sublistsLen.not.mpr fun ⟨hs, hl⟩ => (h.trans_eq hl.symm).not_le (Sublist.length_le hs)
@[simp]
theorem sublistsLen_length : ∀ l : List α, sublistsLen l.length l = [l]
| [] => rfl
| a :: l => by
simp only [length, sublistsLen_succ_cons, sublistsLen_length, map,
sublistsLen_of_length_lt (lt_succ_self _), nil_append]
open Function
theorem Pairwise.sublists' {R} :
∀ {l : List α}, Pairwise R l → Pairwise (Lex (swap R)) (sublists' l)
| _, Pairwise.nil => pairwise_singleton _ _
| _, @Pairwise.cons _ _ a l H₁ H₂ => by
| simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp,
and_imp]
refine ⟨H₂.sublists', H₂.sublists'.imp fun l₁ => Lex.cons l₁, ?_⟩
rintro l₁ sl₁ x l₂ _ rfl
rcases l₁ with - | ⟨b, l₁⟩; · constructor
exact Lex.rel (H₁ _ <| sl₁.subset mem_cons_self)
theorem pairwise_sublists {R} {l : List α} (H : Pairwise R l) :
| Mathlib/Data/List/Sublists.lean | 304 | 311 |
/-
Copyright (c) 2024 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import Mathlib.Algebra.MvPolynomial.Monad
import Mathlib.LinearAlgebra.Charpoly.ToMatrix
import Mathlib.LinearAlgebra.FreeModule.StrongRankCondition
import Mathlib.LinearAlgebra.Matrix.Charpoly.Univ
import Mathlib.RingTheory.TensorProduct.Finite
import Mathlib.RingTheory.TensorProduct.Free
/-!
# Characteristic polynomials of linear families of endomorphisms
The coefficients of the characteristic polynomials of a linear family of endomorphisms
are homogeneous polynomials in the parameters.
This result is used in Lie theory
to establish the existence of regular elements and Cartan subalgebras,
and ultimately a well-defined notion of rank for Lie algebras.
In this file we prove this result about characteristic polynomials.
Let `L` and `M` be modules over a nontrivial commutative ring `R`,
and let `φ : L →ₗ[R] Module.End R M` be a linear map.
Let `b` be a basis of `L`, indexed by `ι`.
Then we define a multivariate polynomial with variables indexed by `ι`
that evaluates on elements `x` of `L` to the characteristic polynomial of `φ x`.
## Main declarations
* `Matrix.toMvPolynomial M i`: the family of multivariate polynomials that evaluates on `c : n → R`
to the dot product of the `i`-th row of `M` with `c`.
`Matrix.toMvPolynomial M i` is the sum of the monomials `C (M i j) * X j`.
* `LinearMap.toMvPolynomial b₁ b₂ f`: a version of `Matrix.toMvPolynomial` for linear maps `f`
with respect to bases `b₁` and `b₂` of the domain and codomain.
* `LinearMap.polyCharpoly`: the multivariate polynomial that evaluates on elements `x` of `L`
to the characteristic polynomial of `φ x`.
* `LinearMap.polyCharpoly_map_eq_charpoly`: the evaluation of `polyCharpoly` on elements `x` of `L`
is the characteristic polynomial of `φ x`.
* `LinearMap.polyCharpoly_coeff_isHomogeneous`: the coefficients of `polyCharpoly`
are homogeneous polynomials in the parameters.
* `LinearMap.nilRank`: the smallest index at which `polyCharpoly` has a non-zero coefficient,
which is independent of the choice of basis for `L`.
* `LinearMap.IsNilRegular`: an element `x` of `L` is *nil-regular* with respect to `φ`
if the `n`-th coefficient of the characteristic polynomial of `φ x` is non-zero,
where `n` denotes the nil-rank of `φ`.
## Implementation details
We show that `LinearMap.polyCharpoly` does not depend on the choice of basis of the target module.
This is done via `LinearMap.polyCharpoly_eq_polyCharpolyAux`
and `LinearMap.polyCharpolyAux_basisIndep`.
The latter is proven by considering
the base change of the `R`-linear map `φ : L →ₗ[R] End R M`
to the multivariate polynomial ring `MvPolynomial ι R`,
and showing that `polyCharpolyAux φ` is equal to the characteristic polynomial of this base change.
The proof concludes because characteristic polynomials are independent of the chosen basis.
## References
* [barnes1967]: "On Cartan subalgebras of Lie algebras" by D.W. Barnes.
-/
open scoped Matrix
namespace Matrix
variable {m n o R S : Type*}
variable [Fintype n] [Fintype o] [CommSemiring R] [CommSemiring S]
open MvPolynomial
/-- Let `M` be an `(m × n)`-matrix over `R`.
Then `Matrix.toMvPolynomial M` is the family (indexed by `i : m`)
of multivariate polynomials in `n` variables over `R` that evaluates on `c : n → R`
to the dot product of the `i`-th row of `M` with `c`:
`Matrix.toMvPolynomial M i` is the sum of the monomials `C (M i j) * X j`. -/
noncomputable
def toMvPolynomial (M : Matrix m n R) (i : m) : MvPolynomial n R :=
∑ j, monomial (.single j 1) (M i j)
lemma toMvPolynomial_eval_eq_apply (M : Matrix m n R) (i : m) (c : n → R) :
eval c (M.toMvPolynomial i) = (M *ᵥ c) i := by
simp only [toMvPolynomial, map_sum, eval_monomial, pow_zero, Finsupp.prod_single_index, pow_one,
mulVec, dotProduct]
lemma toMvPolynomial_map (f : R →+* S) (M : Matrix m n R) (i : m) :
(M.map f).toMvPolynomial i = MvPolynomial.map f (M.toMvPolynomial i) := by
simp only [toMvPolynomial, map_apply, map_sum, map_monomial]
lemma toMvPolynomial_isHomogeneous (M : Matrix m n R) (i : m) :
(M.toMvPolynomial i).IsHomogeneous 1 := by
apply MvPolynomial.IsHomogeneous.sum
rintro j -
apply MvPolynomial.isHomogeneous_monomial _ _
simp [Finsupp.degree, Finsupp.support_single_ne_zero _ one_ne_zero, Finset.sum_singleton,
Finsupp.single_eq_same]
lemma toMvPolynomial_totalDegree_le (M : Matrix m n R) (i : m) :
(M.toMvPolynomial i).totalDegree ≤ 1 := by
apply (toMvPolynomial_isHomogeneous _ _).totalDegree_le
@[simp]
lemma toMvPolynomial_constantCoeff (M : Matrix m n R) (i : m) :
constantCoeff (M.toMvPolynomial i) = 0 := by
simp only [toMvPolynomial, ← C_mul_X_eq_monomial, map_sum, map_mul, constantCoeff_X,
mul_zero, Finset.sum_const_zero]
@[simp]
lemma toMvPolynomial_zero : (0 : Matrix m n R).toMvPolynomial = 0 := by
ext; simp only [toMvPolynomial, zero_apply, map_zero, Finset.sum_const_zero, Pi.zero_apply]
@[simp]
lemma toMvPolynomial_one [DecidableEq n] : (1 : Matrix n n R).toMvPolynomial = X := by
ext i : 1
rw [toMvPolynomial, Finset.sum_eq_single i]
· simp only [one_apply_eq, ← C_mul_X_eq_monomial, C_1, one_mul]
· rintro j - hj
simp only [one_apply_ne hj.symm, map_zero]
· intro h
exact (h (Finset.mem_univ _)).elim
lemma toMvPolynomial_add (M N : Matrix m n R) :
(M + N).toMvPolynomial = M.toMvPolynomial + N.toMvPolynomial := by
ext i : 1
simp only [toMvPolynomial, add_apply, map_add, Finset.sum_add_distrib, Pi.add_apply]
lemma toMvPolynomial_mul (M : Matrix m n R) (N : Matrix n o R) (i : m) :
(M * N).toMvPolynomial i = bind₁ N.toMvPolynomial (M.toMvPolynomial i) := by
simp only [toMvPolynomial, mul_apply, map_sum, Finset.sum_comm (γ := o), bind₁, aeval,
AlgHom.coe_mk, coe_eval₂Hom, eval₂_monomial, algebraMap_apply, Algebra.id.map_eq_id,
RingHom.id_apply, C_apply, pow_zero, Finsupp.prod_single_index, pow_one, Finset.mul_sum,
monomial_mul, zero_add]
end Matrix
namespace LinearMap
open MvPolynomial
section
variable {R M₁ M₂ ι₁ ι₂ : Type*}
variable [CommRing R] [AddCommGroup M₁] [AddCommGroup M₂]
variable [Module R M₁] [Module R M₂]
variable [Fintype ι₁] [Finite ι₂]
variable [DecidableEq ι₁]
variable (b₁ : Basis ι₁ R M₁) (b₂ : Basis ι₂ R M₂)
/-- Let `f : M₁ →ₗ[R] M₂` be an `R`-linear map
between modules `M₁` and `M₂` with bases `b₁` and `b₂` respectively.
Then `LinearMap.toMvPolynomial b₁ b₂ f` is the family of multivariate polynomials over `R`
that evaluates on an element `x` of `M₁` (represented on the basis `b₁`)
to the element `f x` of `M₂` (represented on the basis `b₂`). -/
noncomputable
def toMvPolynomial (f : M₁ →ₗ[R] M₂) (i : ι₂) :
MvPolynomial ι₁ R :=
(toMatrix b₁ b₂ f).toMvPolynomial i
lemma toMvPolynomial_eval_eq_apply (f : M₁ →ₗ[R] M₂) (i : ι₂) (c : ι₁ →₀ R) :
eval c (f.toMvPolynomial b₁ b₂ i) = b₂.repr (f (b₁.repr.symm c)) i := by
rw [toMvPolynomial, Matrix.toMvPolynomial_eval_eq_apply,
← LinearMap.toMatrix_mulVec_repr b₁ b₂, LinearEquiv.apply_symm_apply]
open Algebra.TensorProduct in
lemma toMvPolynomial_baseChange (f : M₁ →ₗ[R] M₂) (i : ι₂) (A : Type*) [CommRing A] [Algebra R A] :
(f.baseChange A).toMvPolynomial (basis A b₁) (basis A b₂) i =
MvPolynomial.map (algebraMap R A) (f.toMvPolynomial b₁ b₂ i) := by
simp only [toMvPolynomial, toMatrix_baseChange, Matrix.toMvPolynomial_map]
lemma toMvPolynomial_isHomogeneous (f : M₁ →ₗ[R] M₂) (i : ι₂) :
(f.toMvPolynomial b₁ b₂ i).IsHomogeneous 1 :=
Matrix.toMvPolynomial_isHomogeneous _ _
lemma toMvPolynomial_totalDegree_le (f : M₁ →ₗ[R] M₂) (i : ι₂) :
(f.toMvPolynomial b₁ b₂ i).totalDegree ≤ 1 :=
Matrix.toMvPolynomial_totalDegree_le _ _
@[simp]
lemma toMvPolynomial_constantCoeff (f : M₁ →ₗ[R] M₂) (i : ι₂) :
constantCoeff (f.toMvPolynomial b₁ b₂ i) = 0 :=
Matrix.toMvPolynomial_constantCoeff _ _
@[simp]
lemma toMvPolynomial_zero : (0 : M₁ →ₗ[R] M₂).toMvPolynomial b₁ b₂ = 0 := by
unfold toMvPolynomial; simp only [map_zero, Matrix.toMvPolynomial_zero]
|
@[simp]
lemma toMvPolynomial_id : (id : M₁ →ₗ[R] M₁).toMvPolynomial b₁ b₁ = X := by
| Mathlib/Algebra/Module/LinearMap/Polynomial.lean | 188 | 190 |
/-
Copyright (c) 2019 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison, Floris van Doorn
-/
import Mathlib.CategoryTheory.Limits.Filtered
import Mathlib.CategoryTheory.Limits.Shapes.FiniteProducts
import Mathlib.CategoryTheory.Limits.Shapes.Kernels
import Mathlib.CategoryTheory.Discrete.Basic
/-!
# Limits in `C` give colimits in `Cᵒᵖ`.
We also give special cases for (co)products,
(co)equalizers, and pullbacks / pushouts.
-/
universe v₁ v₂ u₁ u₂
noncomputable section
open CategoryTheory
open CategoryTheory.Functor
open Opposite
namespace CategoryTheory.Limits
variable {C : Type u₁} [Category.{v₁} C]
variable {J : Type u₂} [Category.{v₂} J]
/-- Turn a colimit for `F : J ⥤ Cᵒᵖ` into a limit for `F.leftOp : Jᵒᵖ ⥤ C`. -/
@[simps]
def isLimitConeLeftOpOfCocone (F : J ⥤ Cᵒᵖ) {c : Cocone F} (hc : IsColimit c) :
IsLimit (coneLeftOpOfCocone c) where
lift s := (hc.desc (coconeOfConeLeftOp s)).unop
fac s j :=
Quiver.Hom.op_inj <| by
simp only [coneLeftOpOfCocone_π_app, op_comp, Quiver.Hom.op_unop, IsColimit.fac,
coconeOfConeLeftOp_ι_app, op_unop]
uniq s m w := by
refine Quiver.Hom.op_inj (hc.hom_ext fun j => Quiver.Hom.unop_inj ?_)
simpa only [Quiver.Hom.op_unop, IsColimit.fac, coconeOfConeLeftOp_ι_app] using w (op j)
/-- Turn a limit of `F : J ⥤ Cᵒᵖ` into a colimit of `F.leftOp : Jᵒᵖ ⥤ C`. -/
@[simps]
def isColimitCoconeLeftOpOfCone (F : J ⥤ Cᵒᵖ) {c : Cone F} (hc : IsLimit c) :
IsColimit (coconeLeftOpOfCone c) where
desc s := (hc.lift (coneOfCoconeLeftOp s)).unop
fac s j :=
Quiver.Hom.op_inj <| by
simp only [coconeLeftOpOfCone_ι_app, op_comp, Quiver.Hom.op_unop, IsLimit.fac,
coneOfCoconeLeftOp_π_app, op_unop]
uniq s m w := by
refine Quiver.Hom.op_inj (hc.hom_ext fun j => Quiver.Hom.unop_inj ?_)
simpa only [Quiver.Hom.op_unop, IsLimit.fac, coneOfCoconeLeftOp_π_app] using w (op j)
/-- Turn a colimit for `F : Jᵒᵖ ⥤ C` into a limit for `F.rightOp : J ⥤ Cᵒᵖ`. -/
@[simps]
def isLimitConeRightOpOfCocone (F : Jᵒᵖ ⥤ C) {c : Cocone F} (hc : IsColimit c) :
IsLimit (coneRightOpOfCocone c) where
lift s := (hc.desc (coconeOfConeRightOp s)).op
fac s j := Quiver.Hom.unop_inj (by simp)
uniq s m w := by
refine Quiver.Hom.unop_inj (hc.hom_ext fun j => Quiver.Hom.op_inj ?_)
simpa only [Quiver.Hom.unop_op, IsColimit.fac] using w (unop j)
/-- Turn a limit for `F : Jᵒᵖ ⥤ C` into a colimit for `F.rightOp : J ⥤ Cᵒᵖ`. -/
@[simps]
def isColimitCoconeRightOpOfCone (F : Jᵒᵖ ⥤ C) {c : Cone F} (hc : IsLimit c) :
IsColimit (coconeRightOpOfCone c) where
desc s := (hc.lift (coneOfCoconeRightOp s)).op
fac s j := Quiver.Hom.unop_inj (by simp)
uniq s m w := by
refine Quiver.Hom.unop_inj (hc.hom_ext fun j => Quiver.Hom.op_inj ?_)
simpa only [Quiver.Hom.unop_op, IsLimit.fac] using w (unop j)
/-- Turn a colimit for `F : Jᵒᵖ ⥤ Cᵒᵖ` into a limit for `F.unop : J ⥤ C`. -/
@[simps]
def isLimitConeUnopOfCocone (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : Cocone F} (hc : IsColimit c) :
IsLimit (coneUnopOfCocone c) where
lift s := (hc.desc (coconeOfConeUnop s)).unop
fac s j := Quiver.Hom.op_inj (by simp)
uniq s m w := by
refine Quiver.Hom.op_inj (hc.hom_ext fun j => Quiver.Hom.unop_inj ?_)
simpa only [Quiver.Hom.op_unop, IsColimit.fac] using w (unop j)
/-- Turn a limit of `F : Jᵒᵖ ⥤ Cᵒᵖ` into a colimit of `F.unop : J ⥤ C`. -/
@[simps]
def isColimitCoconeUnopOfCone (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : Cone F} (hc : IsLimit c) :
IsColimit (coconeUnopOfCone c) where
desc s := (hc.lift (coneOfCoconeUnop s)).unop
fac s j := Quiver.Hom.op_inj (by simp)
uniq s m w := by
refine Quiver.Hom.op_inj (hc.hom_ext fun j => Quiver.Hom.unop_inj ?_)
simpa only [Quiver.Hom.op_unop, IsLimit.fac] using w (unop j)
/-- Turn a colimit for `F.leftOp : Jᵒᵖ ⥤ C` into a limit for `F : J ⥤ Cᵒᵖ`. -/
@[simps]
def isLimitConeOfCoconeLeftOp (F : J ⥤ Cᵒᵖ) {c : Cocone F.leftOp} (hc : IsColimit c) :
IsLimit (coneOfCoconeLeftOp c) where
lift s := (hc.desc (coconeLeftOpOfCone s)).op
fac s j :=
Quiver.Hom.unop_inj <| by
simp only [coneOfCoconeLeftOp_π_app, unop_comp, Quiver.Hom.unop_op, IsColimit.fac,
coconeLeftOpOfCone_ι_app, unop_op]
uniq s m w := by
refine Quiver.Hom.unop_inj (hc.hom_ext fun j => Quiver.Hom.op_inj ?_)
simpa only [Quiver.Hom.unop_op, IsColimit.fac, coneOfCoconeLeftOp_π_app] using w (unop j)
/-- Turn a limit of `F.leftOp : Jᵒᵖ ⥤ C` into a colimit of `F : J ⥤ Cᵒᵖ`. -/
@[simps]
def isColimitCoconeOfConeLeftOp (F : J ⥤ Cᵒᵖ) {c : Cone F.leftOp} (hc : IsLimit c) :
IsColimit (coconeOfConeLeftOp c) where
desc s := (hc.lift (coneLeftOpOfCocone s)).op
fac s j :=
Quiver.Hom.unop_inj <| by
simp only [coconeOfConeLeftOp_ι_app, unop_comp, Quiver.Hom.unop_op, IsLimit.fac,
coneLeftOpOfCocone_π_app, unop_op]
uniq s m w := by
refine Quiver.Hom.unop_inj (hc.hom_ext fun j => Quiver.Hom.op_inj ?_)
simpa only [Quiver.Hom.unop_op, IsLimit.fac, coconeOfConeLeftOp_ι_app] using w (unop j)
/-- Turn a colimit for `F.rightOp : J ⥤ Cᵒᵖ` into a limit for `F : Jᵒᵖ ⥤ C`. -/
@[simps]
def isLimitConeOfCoconeRightOp (F : Jᵒᵖ ⥤ C) {c : Cocone F.rightOp} (hc : IsColimit c) :
IsLimit (coneOfCoconeRightOp c) where
lift s := (hc.desc (coconeRightOpOfCone s)).unop
fac s j := Quiver.Hom.op_inj (by simp)
uniq s m w := by
refine Quiver.Hom.op_inj (hc.hom_ext fun j => Quiver.Hom.unop_inj ?_)
simpa only [Quiver.Hom.op_unop, IsColimit.fac] using w (op j)
/-- Turn a limit for `F.rightOp : J ⥤ Cᵒᵖ` into a colimit for `F : Jᵒᵖ ⥤ C`. -/
@[simps]
def isColimitCoconeOfConeRightOp (F : Jᵒᵖ ⥤ C) {c : Cone F.rightOp} (hc : IsLimit c) :
IsColimit (coconeOfConeRightOp c) where
desc s := (hc.lift (coneRightOpOfCocone s)).unop
fac s j := Quiver.Hom.op_inj (by simp)
uniq s m w := by
refine Quiver.Hom.op_inj (hc.hom_ext fun j => Quiver.Hom.unop_inj ?_)
simpa only [Quiver.Hom.op_unop, IsLimit.fac] using w (op j)
/-- Turn a colimit for `F.unop : J ⥤ C` into a limit for `F : Jᵒᵖ ⥤ Cᵒᵖ`. -/
@[simps]
def isLimitConeOfCoconeUnop (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : Cocone F.unop} (hc : IsColimit c) :
IsLimit (coneOfCoconeUnop c) where
lift s := (hc.desc (coconeUnopOfCone s)).op
fac s j := Quiver.Hom.unop_inj (by simp)
uniq s m w := by
refine Quiver.Hom.unop_inj (hc.hom_ext fun j => Quiver.Hom.op_inj ?_)
simpa only [Quiver.Hom.unop_op, IsColimit.fac] using w (op j)
/-- Turn a limit for `F.unop : J ⥤ C` into a colimit for `F : Jᵒᵖ ⥤ Cᵒᵖ`. -/
@[simps]
def isColimitCoconeOfConeUnop (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : Cone F.unop} (hc : IsLimit c) :
IsColimit (coconeOfConeUnop c) where
desc s := (hc.lift (coneUnopOfCocone s)).op
fac s j := Quiver.Hom.unop_inj (by simp)
uniq s m w := by
refine Quiver.Hom.unop_inj (hc.hom_ext fun j => Quiver.Hom.op_inj ?_)
simpa only [Quiver.Hom.unop_op, IsLimit.fac] using w (op j)
/-- Turn a limit for `F.leftOp : Jᵒᵖ ⥤ C` into a colimit for `F : J ⥤ Cᵒᵖ`. -/
@[simps!]
def isColimitOfConeLeftOpOfCocone (F : J ⥤ Cᵒᵖ) {c : Cocone F}
(hc : IsLimit (coneLeftOpOfCocone c)) : IsColimit c :=
isColimitCoconeOfConeLeftOp F hc
/-- Turn a colimit for `F.leftOp : Jᵒᵖ ⥤ C` into a limit for `F : J ⥤ Cᵒᵖ`. -/
@[simps!]
def isLimitOfCoconeLeftOpOfCone (F : J ⥤ Cᵒᵖ) {c : Cone F}
(hc : IsColimit (coconeLeftOpOfCone c)) : IsLimit c :=
isLimitConeOfCoconeLeftOp F hc
/-- Turn a limit for `F.rightOp : J ⥤ Cᵒᵖ` into a colimit for `F : Jᵒᵖ ⥤ C`. -/
@[simps!]
def isColimitOfConeRightOpOfCocone (F : Jᵒᵖ ⥤ C) {c : Cocone F}
(hc : IsLimit (coneRightOpOfCocone c)) : IsColimit c :=
isColimitCoconeOfConeRightOp F hc
/-- Turn a colimit for `F.rightOp : J ⥤ Cᵒᵖ` into a limit for `F : Jᵒᵖ ⥤ C`. -/
@[simps!]
def isLimitOfCoconeRightOpOfCone (F : Jᵒᵖ ⥤ C) {c : Cone F}
(hc : IsColimit (coconeRightOpOfCone c)) : IsLimit c :=
isLimitConeOfCoconeRightOp F hc
/-- Turn a limit for `F.unop : J ⥤ C` into a colimit for `F : Jᵒᵖ ⥤ Cᵒᵖ`. -/
@[simps!]
def isColimitOfConeUnopOfCocone (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : Cocone F}
(hc : IsLimit (coneUnopOfCocone c)) : IsColimit c :=
isColimitCoconeOfConeUnop F hc
/-- Turn a colimit for `F.unop : J ⥤ C` into a limit for `F : Jᵒᵖ ⥤ Cᵒᵖ`. -/
@[simps!]
def isLimitOfCoconeUnopOfCone (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : Cone F}
(hc : IsColimit (coconeUnopOfCone c)) : IsLimit c :=
isLimitConeOfCoconeUnop F hc
/-- Turn a limit for `F : J ⥤ Cᵒᵖ` into a colimit for `F.leftOp : Jᵒᵖ ⥤ C`. -/
@[simps!]
def isColimitOfConeOfCoconeLeftOp (F : J ⥤ Cᵒᵖ) {c : Cocone F.leftOp}
(hc : IsLimit (coneOfCoconeLeftOp c)) : IsColimit c :=
isColimitCoconeLeftOpOfCone F hc
/-- Turn a colimit for `F : J ⥤ Cᵒᵖ` into a limit for `F.leftOp : Jᵒᵖ ⥤ C`. -/
@[simps!]
def isLimitOfCoconeOfConeLeftOp (F : J ⥤ Cᵒᵖ) {c : Cone F.leftOp}
(hc : IsColimit (coconeOfConeLeftOp c)) : IsLimit c :=
isLimitConeLeftOpOfCocone F hc
/-- Turn a limit for `F : Jᵒᵖ ⥤ C` into a colimit for `F.rightOp : J ⥤ Cᵒᵖ.` -/
@[simps!]
def isColimitOfConeOfCoconeRightOp (F : Jᵒᵖ ⥤ C) {c : Cocone F.rightOp}
(hc : IsLimit (coneOfCoconeRightOp c)) : IsColimit c :=
isColimitCoconeRightOpOfCone F hc
/-- Turn a colimit for `F : Jᵒᵖ ⥤ C` into a limit for `F.rightOp : J ⥤ Cᵒᵖ`. -/
@[simps!]
def isLimitOfCoconeOfConeRightOp (F : Jᵒᵖ ⥤ C) {c : Cone F.rightOp}
(hc : IsColimit (coconeOfConeRightOp c)) : IsLimit c :=
isLimitConeRightOpOfCocone F hc
/-- Turn a limit for `F : Jᵒᵖ ⥤ Cᵒᵖ` into a colimit for `F.unop : J ⥤ C`. -/
@[simps!]
def isColimitOfConeOfCoconeUnop (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : Cocone F.unop}
(hc : IsLimit (coneOfCoconeUnop c)) : IsColimit c :=
isColimitCoconeUnopOfCone F hc
/-- Turn a colimit for `F : Jᵒᵖ ⥤ Cᵒᵖ` into a limit for `F.unop : J ⥤ C`. -/
@[simps!]
def isLimitOfCoconeOfConeUnop (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : Cone F.unop}
(hc : IsColimit (coconeOfConeUnop c)) : IsLimit c :=
isLimitConeUnopOfCocone F hc
@[deprecated (since := "2024-11-01")] alias isColimitConeOfCoconeUnop := isColimitCoconeOfConeUnop
/-- If `F.leftOp : Jᵒᵖ ⥤ C` has a colimit, we can construct a limit for `F : J ⥤ Cᵒᵖ`.
-/
theorem hasLimit_of_hasColimit_leftOp (F : J ⥤ Cᵒᵖ) [HasColimit F.leftOp] : HasLimit F :=
HasLimit.mk
{ cone := coneOfCoconeLeftOp (colimit.cocone F.leftOp)
isLimit := isLimitConeOfCoconeLeftOp _ (colimit.isColimit _) }
theorem hasLimit_of_hasColimit_op (F : J ⥤ C) [HasColimit F.op] : HasLimit F :=
HasLimit.mk
{ cone := (colimit.cocone F.op).unop
isLimit := (colimit.isColimit _).unop }
theorem hasLimit_of_hasColimit_rightOp (F : Jᵒᵖ ⥤ C) [HasColimit F.rightOp] : HasLimit F :=
HasLimit.mk
{ cone := coneOfCoconeRightOp (colimit.cocone F.rightOp)
isLimit := isLimitConeOfCoconeRightOp _ (colimit.isColimit _) }
theorem hasLimit_of_hasColimit_unop (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasColimit F.unop] : HasLimit F :=
HasLimit.mk
{ cone := coneOfCoconeUnop (colimit.cocone F.unop)
isLimit := isLimitConeOfCoconeUnop _ (colimit.isColimit _) }
instance hasLimit_op_of_hasColimit (F : J ⥤ C) [HasColimit F] : HasLimit F.op :=
HasLimit.mk
{ cone := (colimit.cocone F).op
isLimit := (colimit.isColimit _).op }
instance hasLimit_leftOp_of_hasColimit (F : J ⥤ Cᵒᵖ) [HasColimit F] : HasLimit F.leftOp :=
HasLimit.mk
{ cone := coneLeftOpOfCocone (colimit.cocone F)
isLimit := isLimitConeLeftOpOfCocone _ (colimit.isColimit _) }
instance hasLimit_rightOp_of_hasColimit (F : Jᵒᵖ ⥤ C) [HasColimit F] : HasLimit F.rightOp :=
HasLimit.mk
{ cone := coneRightOpOfCocone (colimit.cocone F)
isLimit := isLimitConeRightOpOfCocone _ (colimit.isColimit _) }
instance hasLimit_unop_of_hasColimit (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasColimit F] : HasLimit F.unop :=
HasLimit.mk
{ cone := coneUnopOfCocone (colimit.cocone F)
isLimit := isLimitConeUnopOfCocone _ (colimit.isColimit _) }
/-- The limit of `F.op` is the opposite of `colimit F`. -/
def limitOpIsoOpColimit (F : J ⥤ C) [HasColimit F] :
limit F.op ≅ op (colimit F) :=
limit.isoLimitCone ⟨_, (colimit.isColimit _).op⟩
@[reassoc (attr := simp)]
lemma limitOpIsoOpColimit_inv_comp_π (F : J ⥤ C) [HasColimit F] (j : Jᵒᵖ) :
(limitOpIsoOpColimit F).inv ≫ limit.π F.op j = (colimit.ι F j.unop).op := by
simp [limitOpIsoOpColimit]
@[reassoc (attr := simp)]
lemma limitOpIsoOpColimit_hom_comp_ι (F : J ⥤ C) [HasColimit F] (j : J) :
(limitOpIsoOpColimit F).hom ≫ (colimit.ι F j).op = limit.π F.op (op j) := by
simp [← Iso.eq_inv_comp]
/-- The limit of `F.leftOp` is the unopposite of `colimit F`. -/
def limitLeftOpIsoUnopColimit (F : J ⥤ Cᵒᵖ) [HasColimit F] :
limit F.leftOp ≅ unop (colimit F) :=
limit.isoLimitCone ⟨_, isLimitConeLeftOpOfCocone _ (colimit.isColimit _)⟩
@[reassoc (attr := simp)]
lemma limitLeftOpIsoUnopColimit_inv_comp_π (F : J ⥤ Cᵒᵖ) [HasColimit F] (j : Jᵒᵖ) :
(limitLeftOpIsoUnopColimit F).inv ≫ limit.π F.leftOp j = (colimit.ι F j.unop).unop := by
simp [limitLeftOpIsoUnopColimit]
@[reassoc (attr := simp)]
lemma limitLeftOpIsoUnopColimit_hom_comp_ι (F : J ⥤ Cᵒᵖ) [HasColimit F] (j : J) :
(limitLeftOpIsoUnopColimit F).hom ≫ (colimit.ι F j).unop = limit.π F.leftOp (op j) := by
simp [← Iso.eq_inv_comp]
/-- The limit of `F.rightOp` is the opposite of `colimit F`. -/
def limitRightOpIsoOpColimit (F : Jᵒᵖ ⥤ C) [HasColimit F] :
limit F.rightOp ≅ op (colimit F) :=
limit.isoLimitCone ⟨_, isLimitConeRightOpOfCocone _ (colimit.isColimit _)⟩
@[reassoc (attr := simp)]
lemma limitRightOpIsoOpColimit_inv_comp_π (F : Jᵒᵖ ⥤ C) [HasColimit F] (j : J) :
(limitRightOpIsoOpColimit F).inv ≫ limit.π F.rightOp j = (colimit.ι F (op j)).op := by
simp [limitRightOpIsoOpColimit]
@[reassoc (attr := simp)]
lemma limitRightOpIsoOpColimit_hom_comp_ι (F : Jᵒᵖ ⥤ C) [HasColimit F] (j : Jᵒᵖ) :
(limitRightOpIsoOpColimit F).hom ≫ (colimit.ι F j).op = limit.π F.rightOp j.unop := by
simp [← Iso.eq_inv_comp]
/-- The limit of `F.unop` is the unopposite of `colimit F`. -/
def limitUnopIsoUnopColimit (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasColimit F] :
limit F.unop ≅ unop (colimit F) :=
limit.isoLimitCone ⟨_, isLimitConeUnopOfCocone _ (colimit.isColimit _)⟩
@[reassoc (attr := simp)]
lemma limitUnopIsoUnopColimit_inv_comp_π (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasColimit F] (j : J) :
(limitUnopIsoUnopColimit F).inv ≫ limit.π F.unop j = (colimit.ι F (op j)).unop := by
simp [limitUnopIsoUnopColimit]
@[reassoc (attr := simp)]
lemma limitUnopIsoUnopColimit_hom_comp_ι (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasColimit F] (j : Jᵒᵖ) :
(limitUnopIsoUnopColimit F).hom ≫ (colimit.ι F j).unop = limit.π F.unop j.unop := by
simp [← Iso.eq_inv_comp]
/-- If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
theorem hasLimitsOfShape_op_of_hasColimitsOfShape [HasColimitsOfShape Jᵒᵖ C] :
HasLimitsOfShape J Cᵒᵖ :=
{ has_limit := fun F => hasLimit_of_hasColimit_leftOp F }
theorem hasLimitsOfShape_of_hasColimitsOfShape_op [HasColimitsOfShape Jᵒᵖ Cᵒᵖ] :
HasLimitsOfShape J C :=
{ has_limit := fun F => hasLimit_of_hasColimit_op F }
attribute [local instance] hasLimitsOfShape_op_of_hasColimitsOfShape
/-- If `C` has colimits, we can construct limits for `Cᵒᵖ`.
-/
instance hasLimits_op_of_hasColimits [HasColimitsOfSize.{v₂, u₂} C] :
HasLimitsOfSize.{v₂, u₂} Cᵒᵖ :=
⟨fun _ => inferInstance⟩
theorem hasLimits_of_hasColimits_op [HasColimitsOfSize.{v₂, u₂} Cᵒᵖ] :
HasLimitsOfSize.{v₂, u₂} C :=
{ has_limits_of_shape := fun _ _ => hasLimitsOfShape_of_hasColimitsOfShape_op }
instance has_cofiltered_limits_op_of_has_filtered_colimits [HasFilteredColimitsOfSize.{v₂, u₂} C] :
HasCofilteredLimitsOfSize.{v₂, u₂} Cᵒᵖ where
HasLimitsOfShape _ _ _ := hasLimitsOfShape_op_of_hasColimitsOfShape
theorem has_cofiltered_limits_of_has_filtered_colimits_op [HasFilteredColimitsOfSize.{v₂, u₂} Cᵒᵖ] :
HasCofilteredLimitsOfSize.{v₂, u₂} C :=
{ HasLimitsOfShape := fun _ _ _ => hasLimitsOfShape_of_hasColimitsOfShape_op }
/-- If `F.leftOp : Jᵒᵖ ⥤ C` has a limit, we can construct a colimit for `F : J ⥤ Cᵒᵖ`. -/
theorem hasColimit_of_hasLimit_leftOp (F : J ⥤ Cᵒᵖ) [HasLimit F.leftOp] : HasColimit F :=
HasColimit.mk
{ cocone := coconeOfConeLeftOp (limit.cone F.leftOp)
isColimit := isColimitCoconeOfConeLeftOp _ (limit.isLimit _) }
theorem hasColimit_of_hasLimit_op (F : J ⥤ C) [HasLimit F.op] : HasColimit F :=
HasColimit.mk
{ cocone := (limit.cone F.op).unop
isColimit := (limit.isLimit _).unop }
theorem hasColimit_of_hasLimit_rightOp (F : Jᵒᵖ ⥤ C) [HasLimit F.rightOp] : HasColimit F :=
HasColimit.mk
{ cocone := coconeOfConeRightOp (limit.cone F.rightOp)
isColimit := isColimitCoconeOfConeRightOp _ (limit.isLimit _) }
theorem hasColimit_of_hasLimit_unop (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasLimit F.unop] : HasColimit F :=
HasColimit.mk
{ cocone := coconeOfConeUnop (limit.cone F.unop)
isColimit := isColimitCoconeOfConeUnop _ (limit.isLimit _) }
instance hasColimit_op_of_hasLimit (F : J ⥤ C) [HasLimit F] : HasColimit F.op :=
HasColimit.mk
{ cocone := (limit.cone F).op
isColimit := (limit.isLimit _).op }
instance hasColimit_leftOp_of_hasLimit (F : J ⥤ Cᵒᵖ) [HasLimit F] : HasColimit F.leftOp :=
HasColimit.mk
{ cocone := coconeLeftOpOfCone (limit.cone F)
isColimit := isColimitCoconeLeftOpOfCone _ (limit.isLimit _) }
instance hasColimit_rightOp_of_hasLimit (F : Jᵒᵖ ⥤ C) [HasLimit F] : HasColimit F.rightOp :=
HasColimit.mk
{ cocone := coconeRightOpOfCone (limit.cone F)
isColimit := isColimitCoconeRightOpOfCone _ (limit.isLimit _) }
instance hasColimit_unop_of_hasLimit (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasLimit F] : HasColimit F.unop :=
HasColimit.mk
{ cocone := coconeUnopOfCone (limit.cone F)
isColimit := isColimitCoconeUnopOfCone _ (limit.isLimit _) }
/-- The colimit of `F.op` is the opposite of `limit F`. -/
def colimitOpIsoOpLimit (F : J ⥤ C) [HasLimit F] :
colimit F.op ≅ op (limit F) :=
colimit.isoColimitCocone ⟨_, (limit.isLimit _).op⟩
@[reassoc (attr := simp)]
lemma ι_comp_colimitOpIsoOpLimit_hom (F : J ⥤ C) [HasLimit F] (j : Jᵒᵖ) :
colimit.ι F.op j ≫ (colimitOpIsoOpLimit F).hom = (limit.π F j.unop).op := by
simp [colimitOpIsoOpLimit]
@[reassoc (attr := simp)]
lemma π_comp_colimitOpIsoOpLimit_inv (F : J ⥤ C) [HasLimit F] (j : J) :
(limit.π F j).op ≫ (colimitOpIsoOpLimit F).inv = colimit.ι F.op (op j) := by
simp [Iso.comp_inv_eq]
/-- The colimit of `F.leftOp` is the unopposite of `limit F`. -/
def colimitLeftOpIsoUnopLimit (F : J ⥤ Cᵒᵖ) [HasLimit F] :
colimit F.leftOp ≅ unop (limit F) :=
colimit.isoColimitCocone ⟨_, isColimitCoconeLeftOpOfCone _ (limit.isLimit _)⟩
@[reassoc (attr := simp)]
lemma ι_comp_colimitLeftOpIsoUnopLimit_hom (F : J ⥤ Cᵒᵖ) [HasLimit F] (j : Jᵒᵖ) :
colimit.ι F.leftOp j ≫ (colimitLeftOpIsoUnopLimit F).hom = (limit.π F j.unop).unop := by
simp [colimitLeftOpIsoUnopLimit]
@[reassoc (attr := simp)]
lemma π_comp_colimitLeftOpIsoUnopLimit_inv (F : J ⥤ Cᵒᵖ) [HasLimit F] (j : J) :
(limit.π F j).unop ≫ (colimitLeftOpIsoUnopLimit F).inv = colimit.ι F.leftOp (op j) := by
simp [Iso.comp_inv_eq]
/-- The colimit of `F.rightOp` is the opposite of `limit F`. -/
def colimitRightOpIsoUnopLimit (F : Jᵒᵖ ⥤ C) [HasLimit F] :
colimit F.rightOp ≅ op (limit F) :=
colimit.isoColimitCocone ⟨_, isColimitCoconeRightOpOfCone _ (limit.isLimit _)⟩
@[reassoc (attr := simp)]
lemma ι_comp_colimitRightOpIsoUnopLimit_hom (F : Jᵒᵖ ⥤ C) [HasLimit F] (j : J) :
colimit.ι F.rightOp j ≫ (colimitRightOpIsoUnopLimit F).hom = (limit.π F (op j)).op := by
simp [colimitRightOpIsoUnopLimit]
@[reassoc (attr := simp)]
lemma π_comp_colimitRightOpIsoUnopLimit_inv (F : Jᵒᵖ ⥤ C) [HasLimit F] (j : Jᵒᵖ) :
(limit.π F j).op ≫ (colimitRightOpIsoUnopLimit F).inv = colimit.ι F.rightOp j.unop := by
simp [Iso.comp_inv_eq]
/-- The colimit of `F.unop` is the unopposite of `limit F`. -/
def colimitUnopIsoOpLimit (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasLimit F] :
colimit F.unop ≅ unop (limit F) :=
colimit.isoColimitCocone ⟨_, isColimitCoconeUnopOfCone _ (limit.isLimit _)⟩
@[reassoc (attr := simp)]
lemma ι_comp_colimitUnopIsoOpLimit_hom (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasLimit F] (j : J) :
colimit.ι F.unop j ≫ (colimitUnopIsoOpLimit F).hom = (limit.π F (op j)).unop := by
simp [colimitUnopIsoOpLimit]
@[reassoc (attr := simp)]
lemma π_comp_colimitUnopIsoOpLimit_inv (F : Jᵒᵖ ⥤ Cᵒᵖ) [HasLimit F] (j : Jᵒᵖ) :
(limit.π F j).unop ≫ (colimitUnopIsoOpLimit F).inv = colimit.ι F.unop j.unop := by
simp [Iso.comp_inv_eq]
/-- If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
instance hasColimitsOfShape_op_of_hasLimitsOfShape [HasLimitsOfShape Jᵒᵖ C] :
HasColimitsOfShape J Cᵒᵖ where has_colimit F := hasColimit_of_hasLimit_leftOp F
theorem hasColimitsOfShape_of_hasLimitsOfShape_op [HasLimitsOfShape Jᵒᵖ Cᵒᵖ] :
HasColimitsOfShape J C :=
{ has_colimit := fun F => hasColimit_of_hasLimit_op F }
/-- If `C` has limits, we can construct colimits for `Cᵒᵖ`.
-/
instance hasColimits_op_of_hasLimits [HasLimitsOfSize.{v₂, u₂} C] :
HasColimitsOfSize.{v₂, u₂} Cᵒᵖ :=
⟨fun _ => inferInstance⟩
theorem hasColimits_of_hasLimits_op [HasLimitsOfSize.{v₂, u₂} Cᵒᵖ] :
HasColimitsOfSize.{v₂, u₂} C :=
{ has_colimits_of_shape := fun _ _ => hasColimitsOfShape_of_hasLimitsOfShape_op }
instance has_filtered_colimits_op_of_has_cofiltered_limits [HasCofilteredLimitsOfSize.{v₂, u₂} C] :
HasFilteredColimitsOfSize.{v₂, u₂} Cᵒᵖ where HasColimitsOfShape _ _ _ := inferInstance
theorem has_filtered_colimits_of_has_cofiltered_limits_op [HasCofilteredLimitsOfSize.{v₂, u₂} Cᵒᵖ] :
HasFilteredColimitsOfSize.{v₂, u₂} C :=
{ HasColimitsOfShape := fun _ _ _ => hasColimitsOfShape_of_hasLimitsOfShape_op }
variable (X : Type v₂)
/-- If `C` has products indexed by `X`, then `Cᵒᵖ` has coproducts indexed by `X`.
-/
instance hasCoproductsOfShape_opposite [HasProductsOfShape X C] : HasCoproductsOfShape X Cᵒᵖ := by
haveI : HasLimitsOfShape (Discrete X)ᵒᵖ C :=
hasLimitsOfShape_of_equivalence (Discrete.opposite X).symm
infer_instance
theorem hasCoproductsOfShape_of_opposite [HasProductsOfShape X Cᵒᵖ] : HasCoproductsOfShape X C :=
haveI : HasLimitsOfShape (Discrete X)ᵒᵖ Cᵒᵖ :=
hasLimitsOfShape_of_equivalence (Discrete.opposite X).symm
hasColimitsOfShape_of_hasLimitsOfShape_op
/-- If `C` has coproducts indexed by `X`, then `Cᵒᵖ` has products indexed by `X`.
-/
instance hasProductsOfShape_opposite [HasCoproductsOfShape X C] : HasProductsOfShape X Cᵒᵖ := by
haveI : HasColimitsOfShape (Discrete X)ᵒᵖ C :=
hasColimitsOfShape_of_equivalence (Discrete.opposite X).symm
infer_instance
theorem hasProductsOfShape_of_opposite [HasCoproductsOfShape X Cᵒᵖ] : HasProductsOfShape X C :=
haveI : HasColimitsOfShape (Discrete X)ᵒᵖ Cᵒᵖ :=
hasColimitsOfShape_of_equivalence (Discrete.opposite X).symm
hasLimitsOfShape_of_hasColimitsOfShape_op
instance hasProducts_opposite [HasCoproducts.{v₂} C] : HasProducts.{v₂} Cᵒᵖ := fun _ =>
inferInstance
theorem hasProducts_of_opposite [HasCoproducts.{v₂} Cᵒᵖ] : HasProducts.{v₂} C := fun X =>
hasProductsOfShape_of_opposite X
instance hasCoproducts_opposite [HasProducts.{v₂} C] : HasCoproducts.{v₂} Cᵒᵖ := fun _ =>
inferInstance
theorem hasCoproducts_of_opposite [HasProducts.{v₂} Cᵒᵖ] : HasCoproducts.{v₂} C := fun X =>
hasCoproductsOfShape_of_opposite X
instance hasFiniteCoproducts_opposite [HasFiniteProducts C] : HasFiniteCoproducts Cᵒᵖ where
out _ := Limits.hasCoproductsOfShape_opposite _
theorem hasFiniteCoproducts_of_opposite [HasFiniteProducts Cᵒᵖ] : HasFiniteCoproducts C :=
{ out := fun _ => hasCoproductsOfShape_of_opposite _ }
instance hasFiniteProducts_opposite [HasFiniteCoproducts C] : HasFiniteProducts Cᵒᵖ where
out _ := inferInstance
theorem hasFiniteProducts_of_opposite [HasFiniteCoproducts Cᵒᵖ] : HasFiniteProducts C :=
{ out := fun _ => hasProductsOfShape_of_opposite _ }
section OppositeCoproducts
variable {α : Type*} {Z : α → C}
section
variable [HasCoproduct Z]
instance : HasLimit (Discrete.functor Z).op := hasLimit_op_of_hasColimit (Discrete.functor Z)
instance : HasLimit ((Discrete.opposite α).inverse ⋙ (Discrete.functor Z).op) :=
hasLimitEquivalenceComp (Discrete.opposite α).symm
instance : HasProduct (op <| Z ·) := hasLimit_of_iso
((Discrete.natIsoFunctor ≪≫ Discrete.natIso (fun _ ↦ by rfl)) :
(Discrete.opposite α).inverse ⋙ (Discrete.functor Z).op ≅
Discrete.functor (op <| Z ·))
/-- A `Cofan` gives a `Fan` in the opposite category. -/
@[simp]
def Cofan.op (c : Cofan Z) : Fan (op <| Z ·) := Fan.mk _ (fun a ↦ (c.inj a).op)
/-- If a `Cofan` is colimit, then its opposite is limit. -/
-- noncomputability is just for performance (compilation takes a while)
noncomputable def Cofan.IsColimit.op {c : Cofan Z} (hc : IsColimit c) : IsLimit c.op := by
let e : Discrete.functor (Opposite.op <| Z ·) ≅ (Discrete.opposite α).inverse ⋙
(Discrete.functor Z).op := Discrete.natIso (fun _ ↦ Iso.refl _)
refine IsLimit.ofIsoLimit ((IsLimit.postcomposeInvEquiv e _).2
(IsLimit.whiskerEquivalence hc.op (Discrete.opposite α).symm))
(Cones.ext (Iso.refl _) (fun ⟨a⟩ ↦ ?_))
simp [e, Cofan.inj]
/--
The canonical isomorphism from the opposite of an abstract coproduct to the corresponding product
in the opposite category.
-/
def opCoproductIsoProduct' {c : Cofan Z} {f : Fan (op <| Z ·)}
(hc : IsColimit c) (hf : IsLimit f) : op c.pt ≅ f.pt :=
IsLimit.conePointUniqueUpToIso (Cofan.IsColimit.op hc) hf
variable (Z) in
/--
The canonical isomorphism from the opposite of the coproduct to the product in the opposite
category.
-/
def opCoproductIsoProduct :
op (∐ Z) ≅ ∏ᶜ (op <| Z ·) :=
opCoproductIsoProduct' (coproductIsCoproduct Z) (productIsProduct (op <| Z ·))
end
theorem opCoproductIsoProduct'_inv_comp_inj {c : Cofan Z} {f : Fan (op <| Z ·)}
(hc : IsColimit c) (hf : IsLimit f) (b : α) :
(opCoproductIsoProduct' hc hf).inv ≫ (c.inj b).op = f.proj b :=
IsLimit.conePointUniqueUpToIso_inv_comp (Cofan.IsColimit.op hc) hf ⟨b⟩
theorem opCoproductIsoProduct'_comp_self {c c' : Cofan Z} {f : Fan (op <| Z ·)}
(hc : IsColimit c) (hc' : IsColimit c') (hf : IsLimit f) :
(opCoproductIsoProduct' hc hf).hom ≫ (opCoproductIsoProduct' hc' hf).inv =
(hc.coconePointUniqueUpToIso hc').op.inv := by
apply Quiver.Hom.unop_inj
apply hc'.hom_ext
intro ⟨j⟩
change c'.inj _ ≫ _ = _
simp only [unop_op, unop_comp, Discrete.functor_obj, const_obj_obj, Iso.op_inv,
Quiver.Hom.unop_op, IsColimit.comp_coconePointUniqueUpToIso_inv]
apply Quiver.Hom.op_inj
simp only [op_comp, op_unop, Quiver.Hom.op_unop, Category.assoc,
opCoproductIsoProduct'_inv_comp_inj]
rw [← opCoproductIsoProduct'_inv_comp_inj hc hf]
simp only [Iso.hom_inv_id_assoc]
rfl
variable (Z) in
theorem opCoproductIsoProduct_inv_comp_ι [HasCoproduct Z] (b : α) :
(opCoproductIsoProduct Z).inv ≫ (Sigma.ι Z b).op = Pi.π (op <| Z ·) b :=
opCoproductIsoProduct'_inv_comp_inj _ _ b
theorem desc_op_comp_opCoproductIsoProduct'_hom {c : Cofan Z} {f : Fan (op <| Z ·)}
(hc : IsColimit c) (hf : IsLimit f) (c' : Cofan Z) :
(hc.desc c').op ≫ (opCoproductIsoProduct' hc hf).hom = hf.lift c'.op := by
refine (Iso.eq_comp_inv _).mp (Quiver.Hom.unop_inj (hc.hom_ext (fun ⟨j⟩ ↦ Quiver.Hom.op_inj ?_)))
simp only [unop_op, Discrete.functor_obj, const_obj_obj, Quiver.Hom.unop_op, IsColimit.fac,
Cofan.op, unop_comp, op_comp, op_unop, Quiver.Hom.op_unop, Category.assoc]
erw [opCoproductIsoProduct'_inv_comp_inj, IsLimit.fac]
rfl
theorem desc_op_comp_opCoproductIsoProduct_hom [HasCoproduct Z] {X : C} (π : (a : α) → Z a ⟶ X) :
(Sigma.desc π).op ≫ (opCoproductIsoProduct Z).hom = Pi.lift (fun a ↦ (π a).op) := by
convert desc_op_comp_opCoproductIsoProduct'_hom (coproductIsCoproduct Z)
(productIsProduct (op <| Z ·)) (Cofan.mk _ π)
· ext; simp [Sigma.desc, coproductIsCoproduct]
· ext; simp [Pi.lift, productIsProduct]
end OppositeCoproducts
section OppositeProducts
variable {α : Type*} {Z : α → C}
section
variable [HasProduct Z]
instance : HasColimit (Discrete.functor Z).op := hasColimit_op_of_hasLimit (Discrete.functor Z)
instance : HasColimit ((Discrete.opposite α).inverse ⋙ (Discrete.functor Z).op) :=
hasColimit_equivalence_comp (Discrete.opposite α).symm
instance : HasCoproduct (op <| Z ·) := hasColimit_of_iso
((Discrete.natIsoFunctor ≪≫ Discrete.natIso (fun _ ↦ by rfl)) :
(Discrete.opposite α).inverse ⋙ (Discrete.functor Z).op ≅
Discrete.functor (op <| Z ·)).symm
/-- A `Fan` gives a `Cofan` in the opposite category. -/
@[simp]
def Fan.op (f : Fan Z) : Cofan (op <| Z ·) := Cofan.mk _ (fun a ↦ (f.proj a).op)
/-- If a `Fan` is limit, then its opposite is colimit. -/
-- noncomputability is just for performance (compilation takes a while)
noncomputable def Fan.IsLimit.op {f : Fan Z} (hf : IsLimit f) : IsColimit f.op := by
let e : Discrete.functor (Opposite.op <| Z ·) ≅ (Discrete.opposite α).inverse ⋙
(Discrete.functor Z).op := Discrete.natIso (fun _ ↦ Iso.refl _)
refine IsColimit.ofIsoColimit ((IsColimit.precomposeHomEquiv e _).2
(IsColimit.whiskerEquivalence hf.op (Discrete.opposite α).symm))
(Cocones.ext (Iso.refl _) (fun ⟨a⟩ ↦ ?_))
dsimp
erw [Category.id_comp, Category.comp_id]
rfl
/--
The canonical isomorphism from the opposite of an abstract product to the corresponding coproduct
in the opposite category.
-/
def opProductIsoCoproduct' {f : Fan Z} {c : Cofan (op <| Z ·)}
(hf : IsLimit f) (hc : IsColimit c) : op f.pt ≅ c.pt :=
IsColimit.coconePointUniqueUpToIso (Fan.IsLimit.op hf) hc
variable (Z) in
/--
The canonical isomorphism from the opposite of the product to the coproduct in the opposite
category.
-/
def opProductIsoCoproduct :
op (∏ᶜ Z) ≅ ∐ (op <| Z ·) :=
opProductIsoCoproduct' (productIsProduct Z) (coproductIsCoproduct (op <| Z ·))
end
theorem proj_comp_opProductIsoCoproduct'_hom {f : Fan Z} {c : Cofan (op <| Z ·)}
(hf : IsLimit f) (hc : IsColimit c) (b : α) :
(f.proj b).op ≫ (opProductIsoCoproduct' hf hc).hom = c.inj b :=
IsColimit.comp_coconePointUniqueUpToIso_hom (Fan.IsLimit.op hf) hc ⟨b⟩
theorem opProductIsoCoproduct'_comp_self {f f' : Fan Z} {c : Cofan (op <| Z ·)}
(hf : IsLimit f) (hf' : IsLimit f') (hc : IsColimit c) :
(opProductIsoCoproduct' hf hc).hom ≫ (opProductIsoCoproduct' hf' hc).inv =
(hf.conePointUniqueUpToIso hf').op.inv := by
apply Quiver.Hom.unop_inj
apply hf.hom_ext
intro ⟨j⟩
change _ ≫ f.proj _ = _
simp only [unop_op, unop_comp, Category.assoc, Discrete.functor_obj, Iso.op_inv,
Quiver.Hom.unop_op, IsLimit.conePointUniqueUpToIso_inv_comp]
apply Quiver.Hom.op_inj
simp only [op_comp, op_unop, Quiver.Hom.op_unop, proj_comp_opProductIsoCoproduct'_hom]
rw [← proj_comp_opProductIsoCoproduct'_hom hf' hc]
simp only [Category.assoc, Iso.hom_inv_id, Category.comp_id]
rfl
variable (Z) in
theorem π_comp_opProductIsoCoproduct_hom [HasProduct Z] (b : α) :
(Pi.π Z b).op ≫ (opProductIsoCoproduct Z).hom = Sigma.ι (op <| Z ·) b :=
proj_comp_opProductIsoCoproduct'_hom _ _ b
theorem opProductIsoCoproduct'_inv_comp_lift {f : Fan Z} {c : Cofan (op <| Z ·)}
(hf : IsLimit f) (hc : IsColimit c) (f' : Fan Z) :
(opProductIsoCoproduct' hf hc).inv ≫ (hf.lift f').op = hc.desc f'.op := by
refine (Iso.inv_comp_eq _).mpr (Quiver.Hom.unop_inj (hf.hom_ext (fun ⟨j⟩ ↦ Quiver.Hom.op_inj ?_)))
simp only [Discrete.functor_obj, unop_op, Quiver.Hom.unop_op, IsLimit.fac, Fan.op, unop_comp,
Category.assoc, op_comp, op_unop, Quiver.Hom.op_unop]
erw [← Category.assoc, proj_comp_opProductIsoCoproduct'_hom, IsColimit.fac]
rfl
theorem opProductIsoCoproduct_inv_comp_lift [HasProduct Z] {X : C} (π : (a : α) → X ⟶ Z a) :
(opProductIsoCoproduct Z).inv ≫ (Pi.lift π).op = Sigma.desc (fun a ↦ (π a).op) := by
convert opProductIsoCoproduct'_inv_comp_lift (productIsProduct Z)
(coproductIsCoproduct (op <| Z ·)) (Fan.mk _ π)
· ext; simp [Pi.lift, productIsProduct]
· ext; simp [Sigma.desc, coproductIsCoproduct]
end OppositeProducts
section BinaryProducts
variable {A B : C} [HasBinaryProduct A B]
instance : HasBinaryCoproduct (op A) (op B) := by
have : HasProduct fun x ↦ (WalkingPair.casesOn x A B : C) := ‹_›
show HasCoproduct _
convert inferInstanceAs (HasCoproduct fun x ↦ op (WalkingPair.casesOn x A B : C)) with x
cases x <;> rfl
variable (A B) in
/--
The canonical isomorphism from the opposite of the binary product to the coproduct in the opposite
category.
-/
def opProdIsoCoprod : op (A ⨯ B) ≅ (op A ⨿ op B) where
hom := (prod.lift coprod.inl.unop coprod.inr.unop).op
inv := coprod.desc prod.fst.op prod.snd.op
hom_inv_id := by
apply Quiver.Hom.unop_inj
ext <;>
· simp only [limit.lift_π]
apply Quiver.Hom.op_inj
simp
inv_hom_id := by
ext <;>
· simp only [colimit.ι_desc_assoc]
apply Quiver.Hom.unop_inj
simp
@[reassoc (attr := simp)]
lemma fst_opProdIsoCoprod_hom : prod.fst.op ≫ (opProdIsoCoprod A B).hom = coprod.inl := by
rw [opProdIsoCoprod, ← op_comp, prod.lift_fst, Quiver.Hom.op_unop]
@[reassoc (attr := simp)]
lemma snd_opProdIsoCoprod_hom : prod.snd.op ≫ (opProdIsoCoprod A B).hom = coprod.inr := by
rw [opProdIsoCoprod, ← op_comp, prod.lift_snd, Quiver.Hom.op_unop]
@[reassoc (attr := simp)]
lemma inl_opProdIsoCoprod_inv : coprod.inl ≫ (opProdIsoCoprod A B).inv = prod.fst.op := by
rw [Iso.comp_inv_eq, fst_opProdIsoCoprod_hom]
@[reassoc (attr := simp)]
lemma inr_opProdIsoCoprod_inv : coprod.inr ≫ (opProdIsoCoprod A B).inv = prod.snd.op := by
rw [Iso.comp_inv_eq, snd_opProdIsoCoprod_hom]
@[reassoc (attr := simp)]
lemma opProdIsoCoprod_hom_fst : (opProdIsoCoprod A B).hom.unop ≫ prod.fst = coprod.inl.unop := by
simp [opProdIsoCoprod]
@[reassoc (attr := simp)]
lemma opProdIsoCoprod_hom_snd : (opProdIsoCoprod A B).hom.unop ≫ prod.snd = coprod.inr.unop := by
simp [opProdIsoCoprod]
@[reassoc (attr := simp)]
lemma opProdIsoCoprod_inv_inl : (opProdIsoCoprod A B).inv.unop ≫ coprod.inl.unop = prod.fst := by
rw [← unop_comp, inl_opProdIsoCoprod_inv, Quiver.Hom.unop_op]
|
@[reassoc (attr := simp)]
lemma opProdIsoCoprod_inv_inr : (opProdIsoCoprod A B).inv.unop ≫ coprod.inr.unop = prod.snd := by
rw [← unop_comp, inr_opProdIsoCoprod_inv, Quiver.Hom.unop_op]
end BinaryProducts
| Mathlib/CategoryTheory/Limits/Opposites.lean | 799 | 804 |
/-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import Mathlib.Data.Fintype.List
import Mathlib.Data.Fintype.OfMap
/-!
# Cycles of a list
Lists have an equivalence relation of whether they are rotational permutations of one another.
This relation is defined as `IsRotated`.
Based on this, we define the quotient of lists by the rotation relation, called `Cycle`.
We also define a representation of concrete cycles, available when viewing them in a goal state or
via `#eval`, when over representable types. For example, the cycle `(2 1 4 3)` will be shown
as `c[2, 1, 4, 3]`. Two equal cycles may be printed differently if their internal representation
is different.
-/
assert_not_exists MonoidWithZero
namespace List
variable {α : Type*} [DecidableEq α]
/-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/
def nextOr : ∀ (_ : List α) (_ _ : α), α
| [], _, default => default
| [_], _, default => default
-- Handles the not-found and the wraparound case
| y :: z :: xs, x, default => if x = y then z else nextOr (z :: xs) x default
@[simp]
theorem nextOr_nil (x d : α) : nextOr [] x d = d :=
rfl
@[simp]
theorem nextOr_singleton (x y d : α) : nextOr [y] x d = d :=
rfl
@[simp]
theorem nextOr_self_cons_cons (xs : List α) (x y d : α) : nextOr (x :: y :: xs) x d = y :=
if_pos rfl
theorem nextOr_cons_of_ne (xs : List α) (y x d : α) (h : x ≠ y) :
nextOr (y :: xs) x d = nextOr xs x d := by
rcases xs with - | ⟨z, zs⟩
· rfl
· exact if_neg h
/-- `nextOr` does not depend on the default value, if the next value appears. -/
theorem nextOr_eq_nextOr_of_mem_of_ne (xs : List α) (x d d' : α) (x_mem : x ∈ xs)
(x_ne : x ≠ xs.getLast (ne_nil_of_mem x_mem)) : nextOr xs x d = nextOr xs x d' := by
induction' xs with y ys IH
· cases x_mem
rcases ys with - | ⟨z, zs⟩
· simp at x_mem x_ne
contradiction
by_cases h : x = y
· rw [h, nextOr_self_cons_cons, nextOr_self_cons_cons]
· rw [nextOr, nextOr, IH]
· simpa [h] using x_mem
· simpa using x_ne
theorem mem_of_nextOr_ne {xs : List α} {x d : α} (h : nextOr xs x d ≠ d) : x ∈ xs := by
induction' xs with y ys IH
· simp at h
rcases ys with - | ⟨z, zs⟩
· simp at h
· by_cases hx : x = y
· simp [hx]
· rw [nextOr_cons_of_ne _ _ _ _ hx] at h
simpa [hx] using IH h
theorem nextOr_concat {xs : List α} {x : α} (d : α) (h : x ∉ xs) : nextOr (xs ++ [x]) x d = d := by
induction' xs with z zs IH
· simp
· obtain ⟨hz, hzs⟩ := not_or.mp (mt mem_cons.2 h)
rw [cons_append, nextOr_cons_of_ne _ _ _ _ hz, IH hzs]
theorem nextOr_mem {xs : List α} {x d : α} (hd : d ∈ xs) : nextOr xs x d ∈ xs := by
revert hd
suffices ∀ xs' : List α, (∀ x ∈ xs, x ∈ xs') → d ∈ xs' → nextOr xs x d ∈ xs' by
exact this xs fun _ => id
intro xs' hxs' hd
induction' xs with y ys ih
· exact hd
rcases ys with - | ⟨z, zs⟩
· exact hd
rw [nextOr]
split_ifs with h
· exact hxs' _ (mem_cons_of_mem _ mem_cons_self)
· exact ih fun _ h => hxs' _ (mem_cons_of_mem _ h)
/-- Given an element `x : α` of `l : List α` such that `x ∈ l`, get the next
element of `l`. This works from head to tail, (including a check for last element)
so it will match on first hit, ignoring later duplicates.
For example:
* `next [1, 2, 3] 2 _ = 3`
* `next [1, 2, 3] 3 _ = 1`
* `next [1, 2, 3, 2, 4] 2 _ = 3`
* `next [1, 2, 3, 2] 2 _ = 3`
* `next [1, 1, 2, 3, 2] 1 _ = 1`
-/
def next (l : List α) (x : α) (h : x ∈ l) : α :=
nextOr l x (l.get ⟨0, length_pos_of_mem h⟩)
/-- Given an element `x : α` of `l : List α` such that `x ∈ l`, get the previous
element of `l`. This works from head to tail, (including a check for last element)
so it will match on first hit, ignoring later duplicates.
* `prev [1, 2, 3] 2 _ = 1`
* `prev [1, 2, 3] 1 _ = 3`
* `prev [1, 2, 3, 2, 4] 2 _ = 1`
* `prev [1, 2, 3, 4, 2] 2 _ = 1`
* `prev [1, 1, 2] 1 _ = 2`
-/
def prev : ∀ l : List α, ∀ x ∈ l, α
| [], _, h => by simp at h
| [y], _, _ => y
| y :: z :: xs, x, h =>
if hx : x = y then getLast (z :: xs) (cons_ne_nil _ _)
else if x = z then y else prev (z :: xs) x (by simpa [hx] using h)
variable (l : List α) (x : α)
@[simp]
theorem next_singleton (x y : α) (h : x ∈ [y]) : next [y] x h = y :=
rfl
@[simp]
theorem prev_singleton (x y : α) (h : x ∈ [y]) : prev [y] x h = y :=
rfl
theorem next_cons_cons_eq' (y z : α) (h : x ∈ y :: z :: l) (hx : x = y) :
next (y :: z :: l) x h = z := by rw [next, nextOr, if_pos hx]
@[simp]
theorem next_cons_cons_eq (z : α) (h : x ∈ x :: z :: l) : next (x :: z :: l) x h = z :=
next_cons_cons_eq' l x x z h rfl
theorem next_ne_head_ne_getLast (h : x ∈ l) (y : α) (h : x ∈ y :: l) (hy : x ≠ y)
(hx : x ≠ getLast (y :: l) (cons_ne_nil _ _)) :
next (y :: l) x h = next l x (by simpa [hy] using h) := by
rw [next, next, nextOr_cons_of_ne _ _ _ _ hy, nextOr_eq_nextOr_of_mem_of_ne]
· rwa [getLast_cons] at hx
exact ne_nil_of_mem (by assumption)
· rwa [getLast_cons] at hx
theorem next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l)
(h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) :
next (y :: l ++ [x]) x h = y := by
rw [next, nextOr_concat]
· rfl
· simp [hy, hx]
theorem next_getLast_cons (h : x ∈ l) (y : α) (h : x ∈ y :: l) (hy : x ≠ y)
(hx : x = getLast (y :: l) (cons_ne_nil _ _)) (hl : Nodup l) : next (y :: l) x h = y := by
rw [next, get, ← dropLast_append_getLast (cons_ne_nil y l), hx, nextOr_concat]
subst hx
intro H
obtain ⟨_ | k, hk, hk'⟩ := getElem_of_mem H
· rw [← Option.some_inj] at hk'
rw [← getElem?_eq_getElem, dropLast_eq_take, getElem?_take_of_lt, getElem?_cons_zero,
Option.some_inj] at hk'
· exact hy (Eq.symm hk')
rw [length_cons]
exact length_pos_of_mem (by assumption)
suffices k + 1 = l.length by simp [this] at hk
rcases l with - | ⟨hd, tl⟩
· simp at hk
· rw [nodup_iff_injective_get] at hl
rw [length, Nat.succ_inj]
refine Fin.val_eq_of_eq <| @hl ⟨k, Nat.lt_of_succ_lt <| by simpa using hk⟩
⟨tl.length, by simp⟩ ?_
rw [← Option.some_inj] at hk'
rw [← getElem?_eq_getElem, dropLast_eq_take, getElem?_take_of_lt, getElem?_cons_succ,
getElem?_eq_getElem, Option.some_inj] at hk'
· rw [get_eq_getElem, hk']
simp only [getLast_eq_getElem, length_cons, Nat.succ_eq_add_one, Nat.succ_sub_succ_eq_sub,
Nat.sub_zero, get_eq_getElem, getElem_cons_succ]
simpa using hk
theorem prev_getLast_cons' (y : α) (hxy : x ∈ y :: l) (hx : x = y) :
prev (y :: l) x hxy = getLast (y :: l) (cons_ne_nil _ _) := by cases l <;> simp [prev, hx]
@[simp]
theorem prev_getLast_cons (h : x ∈ x :: l) :
prev (x :: l) x h = getLast (x :: l) (cons_ne_nil _ _) :=
prev_getLast_cons' l x x h rfl
theorem prev_cons_cons_eq' (y z : α) (h : x ∈ y :: z :: l) (hx : x = y) :
prev (y :: z :: l) x h = getLast (z :: l) (cons_ne_nil _ _) := by rw [prev, dif_pos hx]
theorem prev_cons_cons_eq (z : α) (h : x ∈ x :: z :: l) :
prev (x :: z :: l) x h = getLast (z :: l) (cons_ne_nil _ _) :=
prev_cons_cons_eq' l x x z h rfl
theorem prev_cons_cons_of_ne' (y z : α) (h : x ∈ y :: z :: l) (hy : x ≠ y) (hz : x = z) :
prev (y :: z :: l) x h = y := by
cases l
· simp [prev, hy, hz]
· rw [prev, dif_neg hy, if_pos hz]
theorem prev_cons_cons_of_ne (y : α) (h : x ∈ y :: x :: l) (hy : x ≠ y) :
prev (y :: x :: l) x h = y :=
prev_cons_cons_of_ne' _ _ _ _ _ hy rfl
theorem prev_ne_cons_cons (y z : α) (h : x ∈ y :: z :: l) (hy : x ≠ y) (hz : x ≠ z) :
prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) := by
cases l
· simp [hy, hz] at h
· rw [prev, dif_neg hy, if_neg hz]
theorem next_mem (h : x ∈ l) : l.next x h ∈ l :=
nextOr_mem (get_mem _ _)
theorem prev_mem (h : x ∈ l) : l.prev x h ∈ l := by
rcases l with - | ⟨hd, tl⟩
· simp at h
induction' tl with hd' tl hl generalizing hd
· simp
· by_cases hx : x = hd
· simp only [hx, prev_cons_cons_eq]
exact mem_cons_of_mem _ (getLast_mem _)
· rw [prev, dif_neg hx]
split_ifs with hm
· exact mem_cons_self
· exact mem_cons_of_mem _ (hl _ _)
theorem next_getElem (l : List α) (h : Nodup l) (i : Nat) (hi : i < l.length) :
next l l[i] (get_mem _ _) =
(l[(i + 1) % l.length]'(Nat.mod_lt _ (i.zero_le.trans_lt hi))) :=
match l, h, i, hi with
| [], _, i, hi => by simp at hi
| [_], _, _, _ => by simp
| x::y::l, _h, 0, h0 => by
have h₁ : (x :: y :: l)[0] = x := by simp
rw [next_cons_cons_eq' _ _ _ _ _ h₁]
simp
| x::y::l, hn, i+1, hi => by
have hx' : (x :: y :: l)[i+1] ≠ x := by
intro H
suffices (i + 1 : ℕ) = 0 by simpa
rw [nodup_iff_injective_get] at hn
refine Fin.val_eq_of_eq (@hn ⟨i + 1, hi⟩ ⟨0, by simp⟩ ?_)
simpa using H
have hi' : i ≤ l.length := Nat.le_of_lt_succ (Nat.succ_lt_succ_iff.1 hi)
rcases hi'.eq_or_lt with (hi' | hi')
· subst hi'
rw [next_getLast_cons]
· simp [hi', get]
· rw [getElem_cons_succ]; exact get_mem _ _
· exact hx'
· simp [getLast_eq_getElem]
· exact hn.of_cons
· rw [next_ne_head_ne_getLast _ _ _ _ _ hx']
· simp only [getElem_cons_succ]
rw [next_getElem (y::l), ← getElem_cons_succ (a := x)]
· congr
dsimp
rw [Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 hi'),
Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 (Nat.succ_lt_succ_iff.2 hi'))]
· simp [Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 hi'), hi']
· exact hn.of_cons
· rw [getLast_eq_getElem]
intro h
have := nodup_iff_injective_get.1 hn h
simp at this; simp [this] at hi'
· rw [getElem_cons_succ]; exact get_mem _ _
@[deprecated (since := "2025-02-015")] alias next_get := next_getElem
-- Unused variable linter incorrectly reports that `h` is unused here.
set_option linter.unusedVariables false in
theorem prev_getElem (l : List α) (h : Nodup l) (i : Nat) (hi : i < l.length) :
prev l l[i] (get_mem _ _) =
(l[(i + (l.length - 1)) % l.length]'(Nat.mod_lt _ (by omega))) :=
match l with
| [] => by simp at hi
| x::l => by
induction l generalizing i x with
| nil => simp
| cons y l hl =>
rcases i with (_ | _ | i)
· simp [getLast_eq_getElem]
· simp only [mem_cons, nodup_cons] at h
push_neg at h
simp only [zero_add, getElem_cons_succ, getElem_cons_zero,
List.prev_cons_cons_of_ne _ _ _ _ h.left.left.symm, length, add_comm,
Nat.add_sub_cancel_left, Nat.mod_self]
· rw [prev_ne_cons_cons]
· convert hl i.succ y h.of_cons (Nat.le_of_succ_le_succ hi) using 1
have : ∀ k hk, (y :: l)[k] = (x :: y :: l)[k + 1]'(Nat.succ_lt_succ hk) := by
simp
rw [this]
congr
simp only [Nat.add_succ_sub_one, add_zero, length]
simp only [length, Nat.succ_lt_succ_iff] at hi
set k := l.length
rw [Nat.succ_add, ← Nat.add_succ, Nat.add_mod_right, Nat.succ_add, ← Nat.add_succ _ k,
Nat.add_mod_right, Nat.mod_eq_of_lt, Nat.mod_eq_of_lt]
· exact Nat.lt_succ_of_lt hi
· exact Nat.succ_lt_succ (Nat.lt_succ_of_lt hi)
· intro H
suffices i.succ.succ = 0 by simpa
suffices Fin.mk _ hi = ⟨0, by omega⟩ by rwa [Fin.mk.inj_iff] at this
rw [nodup_iff_injective_get] at h
apply h; rw [← H]; simp
· intro H
suffices i.succ.succ = 1 by simpa
suffices Fin.mk _ hi = ⟨1, by omega⟩ by rwa [Fin.mk.inj_iff] at this
rw [nodup_iff_injective_get] at h
apply h; rw [← H]; simp
@[deprecated (since := "2025-02-15")] alias prev_get := prev_getElem
theorem pmap_next_eq_rotate_one (h : Nodup l) : (l.pmap l.next fun _ h => h) = l.rotate 1 := by
apply List.ext_getElem
· simp
· intros
rw [getElem_pmap, getElem_rotate, next_getElem _ h]
theorem pmap_prev_eq_rotate_length_sub_one (h : Nodup l) :
(l.pmap l.prev fun _ h => h) = l.rotate (l.length - 1) := by
apply List.ext_getElem
· simp
· intro n hn hn'
rw [getElem_rotate, getElem_pmap, prev_getElem _ h]
theorem prev_next (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :
prev l (next l x hx) (next_mem _ _ _) = x := by
obtain ⟨n, hn, rfl⟩ := getElem_of_mem hx
simp only [next_getElem, prev_getElem, h, Nat.mod_add_mod]
rcases l with - | ⟨hd, tl⟩
· simp at hn
· have : (n + 1 + length tl) % (length tl + 1) = n := by
rw [length_cons] at hn
rw [add_assoc, add_comm 1, Nat.add_mod_right, Nat.mod_eq_of_lt hn]
simp only [length_cons, Nat.succ_sub_succ_eq_sub, Nat.sub_zero, Nat.succ_eq_add_one, this]
theorem next_prev (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :
next l (prev l x hx) (prev_mem _ _ _) = x := by
obtain ⟨n, hn, rfl⟩ := getElem_of_mem hx
simp only [next_getElem, prev_getElem, h, Nat.mod_add_mod]
rcases l with - | ⟨hd, tl⟩
· simp at hn
· have : (n + length tl + 1) % (length tl + 1) = n := by
rw [length_cons] at hn
rw [add_assoc, Nat.add_mod_right, Nat.mod_eq_of_lt hn]
simp [this]
theorem prev_reverse_eq_next (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :
prev l.reverse x (mem_reverse.mpr hx) = next l x hx := by
obtain ⟨k, hk, rfl⟩ := getElem_of_mem hx
have lpos : 0 < l.length := k.zero_le.trans_lt hk
have key : l.length - 1 - k < l.length := by omega
rw [← getElem_pmap l.next (fun _ h => h) (by simpa using hk)]
simp_rw [getElem_eq_getElem_reverse (l := l), pmap_next_eq_rotate_one _ h]
rw [← getElem_pmap l.reverse.prev fun _ h => h]
· simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse,
length_reverse, Nat.mod_eq_of_lt (Nat.sub_lt lpos Nat.succ_pos'),
Nat.sub_sub_self (Nat.succ_le_of_lt lpos)]
rw [getElem_eq_getElem_reverse]
· simp [Nat.sub_sub_self (Nat.le_sub_one_of_lt hk)]
· simpa
theorem next_reverse_eq_prev (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :
next l.reverse x (mem_reverse.mpr hx) = prev l x hx := by
convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm
exact (reverse_reverse l).symm
theorem isRotated_next_eq {l l' : List α} (h : l ~r l') (hn : Nodup l) {x : α} (hx : x ∈ l) :
l.next x hx = l'.next x (h.mem_iff.mp hx) := by
obtain ⟨k, hk, rfl⟩ := getElem_of_mem hx
obtain ⟨n, rfl⟩ := id h
rw [next_getElem _ hn]
simp_rw [getElem_eq_getElem_rotate _ n k]
rw [next_getElem _ (h.nodup_iff.mp hn), getElem_eq_getElem_rotate _ n]
simp [add_assoc]
theorem isRotated_prev_eq {l l' : List α} (h : l ~r l') (hn : Nodup l) {x : α} (hx : x ∈ l) :
l.prev x hx = l'.prev x (h.mem_iff.mp hx) := by
rw [← next_reverse_eq_prev _ hn, ← next_reverse_eq_prev _ (h.nodup_iff.mp hn)]
exact isRotated_next_eq h.reverse (nodup_reverse.mpr hn) _
end List
open List
/-- `Cycle α` is the quotient of `List α` by cyclic permutation.
Duplicates are allowed.
-/
def Cycle (α : Type*) : Type _ :=
Quotient (IsRotated.setoid α)
namespace Cycle
variable {α : Type*}
/-- The coercion from `List α` to `Cycle α` -/
@[coe] def ofList : List α → Cycle α :=
Quot.mk _
instance : Coe (List α) (Cycle α) :=
⟨ofList⟩
@[simp]
theorem coe_eq_coe {l₁ l₂ : List α} : (l₁ : Cycle α) = (l₂ : Cycle α) ↔ l₁ ~r l₂ :=
@Quotient.eq _ (IsRotated.setoid _) _ _
@[simp]
theorem mk_eq_coe (l : List α) : Quot.mk _ l = (l : Cycle α) :=
rfl
@[simp]
theorem mk''_eq_coe (l : List α) : Quotient.mk'' l = (l : Cycle α) :=
rfl
theorem coe_cons_eq_coe_append (l : List α) (a : α) :
(↑(a :: l) : Cycle α) = (↑(l ++ [a]) : Cycle α) :=
Quot.sound ⟨1, by rw [rotate_cons_succ, rotate_zero]⟩
/-- The unique empty cycle. -/
def nil : Cycle α :=
([] : List α)
@[simp]
theorem coe_nil : ↑([] : List α) = @nil α :=
rfl
@[simp]
theorem coe_eq_nil (l : List α) : (l : Cycle α) = nil ↔ l = [] :=
coe_eq_coe.trans isRotated_nil_iff
/-- For consistency with `EmptyCollection (List α)`. -/
instance : EmptyCollection (Cycle α) :=
⟨nil⟩
@[simp]
theorem empty_eq : ∅ = @nil α :=
rfl
instance : Inhabited (Cycle α) :=
⟨nil⟩
/-- An induction principle for `Cycle`. Use as `induction s`. -/
@[elab_as_elim, induction_eliminator]
theorem induction_on {C : Cycle α → Prop} (s : Cycle α) (H0 : C nil)
(HI : ∀ (a) (l : List α), C ↑l → C ↑(a :: l)) : C s :=
Quotient.inductionOn' s fun l => by
refine List.recOn l ?_ ?_ <;> simp only [mk''_eq_coe, coe_nil]
assumption'
/-- For `x : α`, `s : Cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`. -/
def Mem (s : Cycle α) (a : α) : Prop :=
Quot.liftOn s (fun l => a ∈ l) fun _ _ e => propext <| e.mem_iff
instance : Membership α (Cycle α) :=
⟨Mem⟩
@[simp]
theorem mem_coe_iff {a : α} {l : List α} : a ∈ (↑l : Cycle α) ↔ a ∈ l :=
Iff.rfl
@[simp]
theorem not_mem_nil (a : α) : a ∉ nil :=
List.not_mem_nil
instance [DecidableEq α] : DecidableEq (Cycle α) := fun s₁ s₂ =>
Quotient.recOnSubsingleton₂' s₁ s₂ fun _ _ => decidable_of_iff' _ Quotient.eq''
instance [DecidableEq α] (x : α) (s : Cycle α) : Decidable (x ∈ s) :=
Quotient.recOnSubsingleton' s fun l => show Decidable (x ∈ l) from inferInstance
/-- Reverse a `s : Cycle α` by reversing the underlying `List`. -/
nonrec def reverse (s : Cycle α) : Cycle α :=
Quot.map reverse (fun _ _ => IsRotated.reverse) s
@[simp]
theorem reverse_coe (l : List α) : (l : Cycle α).reverse = l.reverse :=
rfl
@[simp]
theorem mem_reverse_iff {a : α} {s : Cycle α} : a ∈ s.reverse ↔ a ∈ s :=
Quot.inductionOn s fun _ => mem_reverse
@[simp]
theorem reverse_reverse (s : Cycle α) : s.reverse.reverse = s :=
Quot.inductionOn s fun _ => by simp
@[simp]
theorem reverse_nil : nil.reverse = @nil α :=
rfl
/-- The length of the `s : Cycle α`, which is the number of elements, counting duplicates. -/
def length (s : Cycle α) : ℕ :=
Quot.liftOn s List.length fun _ _ e => e.perm.length_eq
@[simp]
theorem length_coe (l : List α) : length (l : Cycle α) = l.length :=
rfl
@[simp]
theorem length_nil : length (@nil α) = 0 :=
rfl
@[simp]
theorem length_reverse (s : Cycle α) : s.reverse.length = s.length :=
Quot.inductionOn s fun _ => List.length_reverse
/-- A `s : Cycle α` that is at most one element. -/
def Subsingleton (s : Cycle α) : Prop :=
s.length ≤ 1
theorem subsingleton_nil : Subsingleton (@nil α) := Nat.zero_le _
theorem length_subsingleton_iff {s : Cycle α} : Subsingleton s ↔ length s ≤ 1 :=
Iff.rfl
@[simp]
theorem subsingleton_reverse_iff {s : Cycle α} : s.reverse.Subsingleton ↔ s.Subsingleton := by
simp [length_subsingleton_iff]
theorem Subsingleton.congr {s : Cycle α} (h : Subsingleton s) :
∀ ⦃x⦄ (_hx : x ∈ s) ⦃y⦄ (_hy : y ∈ s), x = y := by
induction' s using Quot.inductionOn with l
simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, Nat.lt_add_one_iff,
length_eq_zero_iff, length_eq_one_iff, Nat.not_lt_zero, false_or] at h
rcases h with (rfl | ⟨z, rfl⟩) <;> simp
/-- A `s : Cycle α` that is made up of at least two unique elements. -/
def Nontrivial (s : Cycle α) : Prop :=
∃ x y : α, x ≠ y ∧ x ∈ s ∧ y ∈ s
@[simp]
theorem nontrivial_coe_nodup_iff {l : List α} (hl : l.Nodup) :
Nontrivial (l : Cycle α) ↔ 2 ≤ l.length := by
rw [Nontrivial]
rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩)
· simp
· simp
· simp only [mem_cons, exists_prop, mem_coe_iff, List.length, Ne, Nat.succ_le_succ_iff,
Nat.zero_le, iff_true]
refine ⟨hd, hd', ?_, by simp⟩
simp only [not_or, mem_cons, nodup_cons] at hl
exact hl.left.left
@[simp]
theorem nontrivial_reverse_iff {s : Cycle α} : s.reverse.Nontrivial ↔ s.Nontrivial := by
simp [Nontrivial]
| theorem length_nontrivial {s : Cycle α} (h : Nontrivial s) : 2 ≤ length s := by
obtain ⟨x, y, hxy, hx, hy⟩ := h
| Mathlib/Data/List/Cycle.lean | 558 | 559 |
/-
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, Sébastien Gouëzel, Yury Kudryashov
-/
import Mathlib.Dynamics.Ergodic.MeasurePreserving
import Mathlib.LinearAlgebra.Determinant
import Mathlib.LinearAlgebra.Matrix.Diagonal
import Mathlib.LinearAlgebra.Matrix.Transvection
import Mathlib.MeasureTheory.Group.LIntegral
import Mathlib.MeasureTheory.Integral.Marginal
import Mathlib.MeasureTheory.Measure.Stieltjes
import Mathlib.MeasureTheory.Measure.Haar.OfBasis
/-!
# Lebesgue measure on the real line and on `ℝⁿ`
We show that the Lebesgue measure on the real line (constructed as a particular case of additive
Haar measure on inner product spaces) coincides with the Stieltjes measure associated
to the function `x ↦ x`. We deduce properties of this measure on `ℝ`, and then of the product
Lebesgue measure on `ℝⁿ`. In particular, we prove that they are translation invariant.
We show that, on `ℝⁿ`, a linear map acts on Lebesgue measure by rescaling it through the absolute
value of its determinant, in `Real.map_linearMap_volume_pi_eq_smul_volume_pi`.
More properties of the Lebesgue measure are deduced from this in
`Mathlib/MeasureTheory/Measure/Lebesgue/EqHaar.lean`, where they are proved more generally for any
additive Haar measure on a finite-dimensional real vector space.
-/
assert_not_exists MeasureTheory.integral
noncomputable section
open Set Filter MeasureTheory MeasureTheory.Measure TopologicalSpace
open ENNReal (ofReal)
open scoped ENNReal NNReal Topology
/-!
### Definition of the Lebesgue measure and lengths of intervals
-/
namespace Real
variable {ι : Type*} [Fintype ι]
/-- The volume on the real line (as a particular case of the volume on a finite-dimensional
inner product space) coincides with the Stieltjes measure coming from the identity function. -/
theorem volume_eq_stieltjes_id : (volume : Measure ℝ) = StieltjesFunction.id.measure := by
haveI : IsAddLeftInvariant StieltjesFunction.id.measure :=
⟨fun a =>
Eq.symm <|
Real.measure_ext_Ioo_rat fun p q => by
simp only [Measure.map_apply (measurable_const_add a) measurableSet_Ioo,
sub_sub_sub_cancel_right, StieltjesFunction.measure_Ioo, StieltjesFunction.id_leftLim,
StieltjesFunction.id_apply, id, preimage_const_add_Ioo]⟩
have A : StieltjesFunction.id.measure (stdOrthonormalBasis ℝ ℝ).toBasis.parallelepiped = 1 := by
change StieltjesFunction.id.measure (parallelepiped (stdOrthonormalBasis ℝ ℝ)) = 1
rcases parallelepiped_orthonormalBasis_one_dim (stdOrthonormalBasis ℝ ℝ) with (H | H) <;>
simp only [H, StieltjesFunction.measure_Icc, StieltjesFunction.id_apply, id, tsub_zero,
StieltjesFunction.id_leftLim, sub_neg_eq_add, zero_add, ENNReal.ofReal_one]
conv_rhs =>
rw [addHaarMeasure_unique StieltjesFunction.id.measure
(stdOrthonormalBasis ℝ ℝ).toBasis.parallelepiped, A]
simp only [volume, Basis.addHaar, one_smul]
theorem volume_val (s) : volume s = StieltjesFunction.id.measure s := by
simp [volume_eq_stieltjes_id]
@[simp]
theorem volume_Ico {a b : ℝ} : volume (Ico a b) = ofReal (b - a) := by simp [volume_val]
@[simp]
theorem volume_real_Ico {a b : ℝ} : volume.real (Ico a b) = max (b - a) 0 := by
simp [measureReal_def, ENNReal.toReal_ofReal']
theorem volume_real_Ico_of_le {a b : ℝ} (hab : a ≤ b) : volume.real (Ico a b) = b - a := by
simp [hab]
@[simp]
theorem volume_Icc {a b : ℝ} : volume (Icc a b) = ofReal (b - a) := by simp [volume_val]
@[simp]
theorem volume_real_Icc {a b : ℝ} : volume.real (Icc a b) = max (b - a) 0 := by
simp [measureReal_def, ENNReal.toReal_ofReal']
theorem volume_real_Icc_of_le {a b : ℝ} (hab : a ≤ b) : volume.real (Icc a b) = b - a := by
simp [hab]
@[simp]
theorem volume_Ioo {a b : ℝ} : volume (Ioo a b) = ofReal (b - a) := by simp [volume_val]
@[simp]
theorem volume_real_Ioo {a b : ℝ} : volume.real (Ioo a b) = max (b - a) 0 := by
simp [measureReal_def, ENNReal.toReal_ofReal']
theorem volume_real_Ioo_of_le {a b : ℝ} (hab : a ≤ b) : volume.real (Ioo a b) = b - a := by
simp [hab]
@[simp]
theorem volume_Ioc {a b : ℝ} : volume (Ioc a b) = ofReal (b - a) := by simp [volume_val]
@[simp]
theorem volume_real_Ioc {a b : ℝ} : volume.real (Ioc a b) = max (b - a) 0 := by
simp [measureReal_def, ENNReal.toReal_ofReal']
theorem volume_real_Ioc_of_le {a b : ℝ} (hab : a ≤ b) : volume.real (Ioc a b) = b - a := by
simp [hab]
theorem volume_singleton {a : ℝ} : volume ({a} : Set ℝ) = 0 := by simp [volume_val]
theorem volume_univ : volume (univ : Set ℝ) = ∞ :=
ENNReal.eq_top_of_forall_nnreal_le fun r =>
calc
(r : ℝ≥0∞) = volume (Icc (0 : ℝ) r) := by simp
_ ≤ volume univ := measure_mono (subset_univ _)
@[simp]
theorem volume_ball (a r : ℝ) : volume (Metric.ball a r) = ofReal (2 * r) := by
rw [ball_eq_Ioo, volume_Ioo, ← sub_add, add_sub_cancel_left, two_mul]
@[simp]
theorem volume_real_ball {a r : ℝ} (hr : 0 ≤ r) : volume.real (Metric.ball a r) = 2 * r := by
simp [measureReal_def, hr]
@[simp]
theorem volume_closedBall (a r : ℝ) : volume (Metric.closedBall a r) = ofReal (2 * r) := by
rw [closedBall_eq_Icc, volume_Icc, ← sub_add, add_sub_cancel_left, two_mul]
@[simp]
theorem volume_real_closedBall {a r : ℝ} (hr : 0 ≤ r) :
volume.real (Metric.closedBall a r) = 2 * r := by
simp [measureReal_def, hr]
@[simp]
theorem volume_emetric_ball (a : ℝ) (r : ℝ≥0∞) : volume (EMetric.ball a r) = 2 * r := by
rcases eq_or_ne r ∞ with (rfl | hr)
· rw [Metric.emetric_ball_top, volume_univ, two_mul, _root_.top_add]
· lift r to ℝ≥0 using hr
rw [Metric.emetric_ball_nnreal, volume_ball, two_mul, ← NNReal.coe_add,
ENNReal.ofReal_coe_nnreal, ENNReal.coe_add, two_mul]
@[simp]
theorem volume_emetric_closedBall (a : ℝ) (r : ℝ≥0∞) : volume (EMetric.closedBall a r) = 2 * r := by
rcases eq_or_ne r ∞ with (rfl | hr)
· rw [EMetric.closedBall_top, volume_univ, two_mul, _root_.top_add]
· lift r to ℝ≥0 using hr
rw [Metric.emetric_closedBall_nnreal, volume_closedBall, two_mul, ← NNReal.coe_add,
ENNReal.ofReal_coe_nnreal, ENNReal.coe_add, two_mul]
instance noAtoms_volume : NoAtoms (volume : Measure ℝ) :=
⟨fun _ => volume_singleton⟩
@[simp]
theorem volume_interval {a b : ℝ} : volume (uIcc a b) = ofReal |b - a| := by
rw [← Icc_min_max, volume_Icc, max_sub_min_eq_abs]
@[simp]
theorem volume_real_interval {a b : ℝ} : volume.real (uIcc a b) = |b - a| := by
simp [measureReal_def]
@[simp]
theorem volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ :=
top_unique <|
le_of_tendsto' ENNReal.tendsto_nat_nhds_top fun n =>
calc
(n : ℝ≥0∞) = volume (Ioo a (a + n)) := by simp
_ ≤ volume (Ioi a) := measure_mono Ioo_subset_Ioi_self
@[simp]
theorem volume_Ici {a : ℝ} : volume (Ici a) = ∞ := by rw [← measure_congr Ioi_ae_eq_Ici]; simp
@[simp]
theorem volume_Iio {a : ℝ} : volume (Iio a) = ∞ :=
top_unique <|
le_of_tendsto' ENNReal.tendsto_nat_nhds_top fun n =>
calc
(n : ℝ≥0∞) = volume (Ioo (a - n) a) := by simp
_ ≤ volume (Iio a) := measure_mono Ioo_subset_Iio_self
@[simp]
theorem volume_Iic {a : ℝ} : volume (Iic a) = ∞ := by rw [← measure_congr Iio_ae_eq_Iic]; simp
instance locallyFinite_volume : IsLocallyFiniteMeasure (volume : Measure ℝ) :=
⟨fun x =>
⟨Ioo (x - 1) (x + 1),
IsOpen.mem_nhds isOpen_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩, by
simp only [Real.volume_Ioo, ENNReal.ofReal_lt_top]⟩⟩
instance isFiniteMeasure_restrict_Icc (x y : ℝ) : IsFiniteMeasure (volume.restrict (Icc x y)) :=
⟨by simp⟩
instance isFiniteMeasure_restrict_Ico (x y : ℝ) : IsFiniteMeasure (volume.restrict (Ico x y)) :=
⟨by simp⟩
instance isFiniteMeasure_restrict_Ioc (x y : ℝ) : IsFiniteMeasure (volume.restrict (Ioc x y)) :=
⟨by simp⟩
instance isFiniteMeasure_restrict_Ioo (x y : ℝ) : IsFiniteMeasure (volume.restrict (Ioo x y)) :=
⟨by simp⟩
theorem volume_le_diam (s : Set ℝ) : volume s ≤ EMetric.diam s := by
by_cases hs : Bornology.IsBounded s
· rw [Real.ediam_eq hs, ← volume_Icc]
exact volume.mono hs.subset_Icc_sInf_sSup
· rw [Metric.ediam_of_unbounded hs]; exact le_top
theorem _root_.Filter.Eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ}
(h : ∀ᶠ x in 𝓝 a, p x) : (0 : ℝ≥0∞) < volume { x | p x } := by
rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩
refine lt_of_lt_of_le ?_ (measure_mono hs)
simpa [-mem_Ioo] using hx.1.trans hx.2
/-!
### Volume of a box in `ℝⁿ`
-/
theorem volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ENNReal.ofReal (b i - a i) := by
rw [← pi_univ_Icc, volume_pi_pi]
simp only [Real.volume_Icc]
@[simp]
theorem volume_Icc_pi_toReal {a b : ι → ℝ} (h : a ≤ b) :
(volume (Icc a b)).toReal = ∏ i, (b i - a i) := by
simp only [volume_Icc_pi, ENNReal.toReal_prod, ENNReal.toReal_ofReal (sub_nonneg.2 (h _))]
theorem volume_pi_Ioo {a b : ι → ℝ} :
volume (pi univ fun i => Ioo (a i) (b i)) = ∏ i, ENNReal.ofReal (b i - a i) :=
(measure_congr Measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi
@[simp]
theorem volume_pi_Ioo_toReal {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ fun i => Ioo (a i) (b i))).toReal = ∏ i, (b i - a i) := by
simp only [volume_pi_Ioo, ENNReal.toReal_prod, ENNReal.toReal_ofReal (sub_nonneg.2 (h _))]
theorem volume_pi_Ioc {a b : ι → ℝ} :
volume (pi univ fun i => Ioc (a i) (b i)) = ∏ i, ENNReal.ofReal (b i - a i) :=
(measure_congr Measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi
@[simp]
theorem volume_pi_Ioc_toReal {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ fun i => Ioc (a i) (b i))).toReal = ∏ i, (b i - a i) := by
simp only [volume_pi_Ioc, ENNReal.toReal_prod, ENNReal.toReal_ofReal (sub_nonneg.2 (h _))]
theorem volume_pi_Ico {a b : ι → ℝ} :
volume (pi univ fun i => Ico (a i) (b i)) = ∏ i, ENNReal.ofReal (b i - a i) :=
(measure_congr Measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi
@[simp]
theorem volume_pi_Ico_toReal {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ fun i => Ico (a i) (b i))).toReal = ∏ i, (b i - a i) := by
simp only [volume_pi_Ico, ENNReal.toReal_prod, ENNReal.toReal_ofReal (sub_nonneg.2 (h _))]
@[simp]
nonrec theorem volume_pi_ball (a : ι → ℝ) {r : ℝ} (hr : 0 < r) :
volume (Metric.ball a r) = ENNReal.ofReal ((2 * r) ^ Fintype.card ι) := by
simp only [MeasureTheory.volume_pi_ball a hr, volume_ball, Finset.prod_const]
exact (ENNReal.ofReal_pow (mul_nonneg zero_le_two hr.le) _).symm
@[simp]
nonrec theorem volume_pi_closedBall (a : ι → ℝ) {r : ℝ} (hr : 0 ≤ r) :
volume (Metric.closedBall a r) = ENNReal.ofReal ((2 * r) ^ Fintype.card ι) := by
simp only [MeasureTheory.volume_pi_closedBall a hr, volume_closedBall, Finset.prod_const]
exact (ENNReal.ofReal_pow (mul_nonneg zero_le_two hr) _).symm
theorem volume_pi_le_prod_diam (s : Set (ι → ℝ)) :
volume s ≤ ∏ i : ι, EMetric.diam (Function.eval i '' s) :=
calc
volume s ≤ volume (pi univ fun i => closure (Function.eval i '' s)) :=
volume.mono <|
Subset.trans (subset_pi_eval_image univ s) <| pi_mono fun _ _ => subset_closure
_ = ∏ i, volume (closure <| Function.eval i '' s) := volume_pi_pi _
_ ≤ ∏ i : ι, EMetric.diam (Function.eval i '' s) :=
Finset.prod_le_prod' fun _ _ => (volume_le_diam _).trans_eq (EMetric.diam_closure _)
theorem volume_pi_le_diam_pow (s : Set (ι → ℝ)) : volume s ≤ EMetric.diam s ^ Fintype.card ι :=
calc
volume s ≤ ∏ i : ι, EMetric.diam (Function.eval i '' s) := volume_pi_le_prod_diam s
_ ≤ ∏ _i : ι, (1 : ℝ≥0) * EMetric.diam s :=
(Finset.prod_le_prod' fun i _ => (LipschitzWith.eval i).ediam_image_le s)
_ = EMetric.diam s ^ Fintype.card ι := by
simp only [ENNReal.coe_one, one_mul, Finset.prod_const, Fintype.card]
/-!
### Images of the Lebesgue measure under multiplication in ℝ
-/
theorem smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) :
ENNReal.ofReal |a| • Measure.map (a * ·) volume = volume := by
refine (Real.measure_ext_Ioo_rat fun p q => ?_).symm
rcases lt_or_gt_of_ne h with h | h
· simp only [Real.volume_Ioo, Measure.smul_apply, ← ENNReal.ofReal_mul (le_of_lt <| neg_pos.2 h),
Measure.map_apply (measurable_const_mul a) measurableSet_Ioo, neg_sub_neg, neg_mul,
preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub, smul_eq_mul,
mul_div_cancel₀ _ (ne_of_lt h)]
· simp only [Real.volume_Ioo, Measure.smul_apply, ← ENNReal.ofReal_mul (le_of_lt h),
Measure.map_apply (measurable_const_mul a) measurableSet_Ioo, preimage_const_mul_Ioo _ _ h,
abs_of_pos h, mul_sub, mul_div_cancel₀ _ (ne_of_gt h), smul_eq_mul]
theorem map_volume_mul_left {a : ℝ} (h : a ≠ 0) :
Measure.map (a * ·) volume = ENNReal.ofReal |a⁻¹| • volume := by
conv_rhs =>
rw [← Real.smul_map_volume_mul_left h, smul_smul, ← ENNReal.ofReal_mul (abs_nonneg _), ←
abs_mul, inv_mul_cancel₀ h, abs_one, ENNReal.ofReal_one, one_smul]
@[simp]
theorem volume_preimage_mul_left {a : ℝ} (h : a ≠ 0) (s : Set ℝ) :
volume ((a * ·) ⁻¹' s) = ENNReal.ofReal (abs a⁻¹) * volume s :=
calc
volume ((a * ·) ⁻¹' s) = Measure.map (a * ·) volume s :=
((Homeomorph.mulLeft₀ a h).toMeasurableEquiv.map_apply s).symm
_ = ENNReal.ofReal (abs a⁻¹) * volume s := by rw [map_volume_mul_left h]; rfl
theorem smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) :
ENNReal.ofReal |a| • Measure.map (· * a) volume = volume := by
simpa only [mul_comm] using Real.smul_map_volume_mul_left h
| theorem map_volume_mul_right {a : ℝ} (h : a ≠ 0) :
Measure.map (· * a) volume = ENNReal.ofReal |a⁻¹| • volume := by
simpa only [mul_comm] using Real.map_volume_mul_left h
| Mathlib/MeasureTheory/Measure/Lebesgue/Basic.lean | 324 | 326 |
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn, Violeta Hernández Palacios
-/
import Mathlib.Algebra.GroupWithZero.Divisibility
import Mathlib.Data.Nat.SuccPred
import Mathlib.Order.SuccPred.InitialSeg
import Mathlib.SetTheory.Ordinal.Basic
/-!
# Ordinal arithmetic
Ordinals have an addition (corresponding to disjoint union) that turns them into an additive
monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns
them into a monoid. One can also define correspondingly a subtraction, a division, a successor
function, a power function and a logarithm function.
We also define limit ordinals and prove the basic induction principle on ordinals separating
successor ordinals and limit ordinals, in `limitRecOn`.
## Main definitions and results
* `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`.
* `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`.
* `o₁ * o₂` is the lexicographic order on `o₂ × o₁`.
* `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the
divisibility predicate, and a modulo operation.
* `Order.succ o = o + 1` is the successor of `o`.
* `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`.
We discuss the properties of casts of natural numbers of and of `ω` with respect to these
operations.
Some properties of the operations are also used to discuss general tools on ordinals:
* `IsLimit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor.
* `limitRecOn` is the main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals.
* `IsNormal`: a function `f : Ordinal → Ordinal` satisfies `IsNormal` if it is strictly increasing
and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`.
Various other basic arithmetic results are given in `Principal.lean` instead.
-/
assert_not_exists Field Module
noncomputable section
open Function Cardinal Set Equiv Order
open scoped Ordinal
universe u v w
namespace Ordinal
variable {α β γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
/-! ### Further properties of addition on ordinals -/
@[simp]
theorem lift_add (a b : Ordinal.{v}) : lift.{u} (a + b) = lift.{u} a + lift.{u} b :=
Quotient.inductionOn₂ a b fun ⟨_α, _r, _⟩ ⟨_β, _s, _⟩ =>
Quotient.sound
⟨(RelIso.preimage Equiv.ulift _).trans
(RelIso.sumLexCongr (RelIso.preimage Equiv.ulift _) (RelIso.preimage Equiv.ulift _)).symm⟩
@[simp]
theorem lift_succ (a : Ordinal.{v}) : lift.{u} (succ a) = succ (lift.{u} a) := by
rw [← add_one_eq_succ, lift_add, lift_one]
rfl
instance instAddLeftReflectLE :
AddLeftReflectLE Ordinal.{u} where
elim c a b := by
refine inductionOn₃ a b c fun α r _ β s _ γ t _ ⟨f⟩ ↦ ?_
have H₁ a : f (Sum.inl a) = Sum.inl a := by
simpa using ((InitialSeg.leAdd t r).trans f).eq (InitialSeg.leAdd t s) a
have H₂ a : ∃ b, f (Sum.inr a) = Sum.inr b := by
generalize hx : f (Sum.inr a) = x
obtain x | x := x
· rw [← H₁, f.inj] at hx
contradiction
· exact ⟨x, rfl⟩
choose g hg using H₂
refine (RelEmbedding.ofMonotone g fun _ _ h ↦ ?_).ordinal_type_le
rwa [← @Sum.lex_inr_inr _ t _ s, ← hg, ← hg, f.map_rel_iff, Sum.lex_inr_inr]
instance : IsLeftCancelAdd Ordinal where
add_left_cancel a b c h := by simpa only [le_antisymm_iff, add_le_add_iff_left] using h
@[deprecated add_left_cancel_iff (since := "2024-12-11")]
protected theorem add_left_cancel (a) {b c : Ordinal} : a + b = a + c ↔ b = c :=
add_left_cancel_iff
private theorem add_lt_add_iff_left' (a) {b c : Ordinal} : a + b < a + c ↔ b < c := by
rw [← not_le, ← not_le, add_le_add_iff_left]
instance instAddLeftStrictMono : AddLeftStrictMono Ordinal.{u} :=
⟨fun a _b _c ↦ (add_lt_add_iff_left' a).2⟩
instance instAddLeftReflectLT : AddLeftReflectLT Ordinal.{u} :=
⟨fun a _b _c ↦ (add_lt_add_iff_left' a).1⟩
instance instAddRightReflectLT : AddRightReflectLT Ordinal.{u} :=
⟨fun _a _b _c ↦ lt_imp_lt_of_le_imp_le fun h => add_le_add_right h _⟩
theorem add_le_add_iff_right {a b : Ordinal} : ∀ n : ℕ, a + n ≤ b + n ↔ a ≤ b
| 0 => by simp
| n + 1 => by
simp only [natCast_succ, add_succ, add_succ, succ_le_succ_iff, add_le_add_iff_right]
theorem add_right_cancel {a b : Ordinal} (n : ℕ) : a + n = b + n ↔ a = b := by
simp only [le_antisymm_iff, add_le_add_iff_right]
theorem add_eq_zero_iff {a b : Ordinal} : a + b = 0 ↔ a = 0 ∧ b = 0 :=
inductionOn₂ a b fun α r _ β s _ => by
simp_rw [← type_sum_lex, type_eq_zero_iff_isEmpty]
exact isEmpty_sum
theorem left_eq_zero_of_add_eq_zero {a b : Ordinal} (h : a + b = 0) : a = 0 :=
(add_eq_zero_iff.1 h).1
theorem right_eq_zero_of_add_eq_zero {a b : Ordinal} (h : a + b = 0) : b = 0 :=
(add_eq_zero_iff.1 h).2
/-! ### The predecessor of an ordinal -/
open Classical in
/-- The ordinal predecessor of `o` is `o'` if `o = succ o'`,
and `o` otherwise. -/
def pred (o : Ordinal) : Ordinal :=
if h : ∃ a, o = succ a then Classical.choose h else o
@[simp]
theorem pred_succ (o) : pred (succ o) = o := by
have h : ∃ a, succ o = succ a := ⟨_, rfl⟩
simpa only [pred, dif_pos h] using (succ_injective <| Classical.choose_spec h).symm
theorem pred_le_self (o) : pred o ≤ o := by
classical
exact if h : ∃ a, o = succ a then by
let ⟨a, e⟩ := h
rw [e, pred_succ]; exact le_succ a
else by rw [pred, dif_neg h]
theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬∃ a, o = succ a :=
⟨fun e ⟨a, e'⟩ => by rw [e', pred_succ] at e; exact (lt_succ a).ne e, fun h => dif_neg h⟩
theorem pred_eq_iff_not_succ' {o} : pred o = o ↔ ∀ a, o ≠ succ a := by
simpa using pred_eq_iff_not_succ
theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a :=
Iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le])
(iff_not_comm.1 pred_eq_iff_not_succ).symm
@[simp]
theorem pred_zero : pred 0 = 0 :=
pred_eq_iff_not_succ'.2 fun a => (succ_ne_zero a).symm
theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a :=
⟨fun e => ⟨_, e.symm⟩, fun ⟨a, e⟩ => by simp only [e, pred_succ]⟩
theorem succ_lt_of_not_succ {o b : Ordinal} (h : ¬∃ a, o = succ a) : succ b < o ↔ b < o :=
⟨(lt_succ b).trans, fun l => lt_of_le_of_ne (succ_le_of_lt l) fun e => h ⟨_, e.symm⟩⟩
theorem lt_pred {a b} : a < pred b ↔ succ a < b := by
classical
exact if h : ∃ a, b = succ a then by
let ⟨c, e⟩ := h
rw [e, pred_succ, succ_lt_succ_iff]
else by simp only [pred, dif_neg h, succ_lt_of_not_succ h]
theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b :=
le_iff_le_iff_lt_iff_lt.2 lt_pred
@[simp]
theorem lift_is_succ {o : Ordinal.{v}} : (∃ a, lift.{u} o = succ a) ↔ ∃ a, o = succ a :=
⟨fun ⟨a, h⟩ =>
let ⟨b, e⟩ := mem_range_lift_of_le <| show a ≤ lift.{u} o from le_of_lt <| h.symm ▸ lt_succ a
⟨b, (lift_inj.{u,v}).1 <| by rw [h, ← e, lift_succ]⟩,
fun ⟨a, h⟩ => ⟨lift.{u} a, by simp only [h, lift_succ]⟩⟩
@[simp]
theorem lift_pred (o : Ordinal.{v}) : lift.{u} (pred o) = pred (lift.{u} o) := by
classical
exact if h : ∃ a, o = succ a then by obtain ⟨a, e⟩ := h; simp only [e, pred_succ, lift_succ]
else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)]
/-! ### Limit ordinals -/
/-- A limit ordinal is an ordinal which is not zero and not a successor.
TODO: deprecate this in favor of `Order.IsSuccLimit`. -/
def IsLimit (o : Ordinal) : Prop :=
IsSuccLimit o
theorem isLimit_iff {o} : IsLimit o ↔ o ≠ 0 ∧ IsSuccPrelimit o := by
simp [IsLimit, IsSuccLimit]
theorem IsLimit.isSuccPrelimit {o} (h : IsLimit o) : IsSuccPrelimit o :=
IsSuccLimit.isSuccPrelimit h
theorem IsLimit.succ_lt {o a : Ordinal} (h : IsLimit o) : a < o → succ a < o :=
IsSuccLimit.succ_lt h
theorem isSuccPrelimit_zero : IsSuccPrelimit (0 : Ordinal) := isSuccPrelimit_bot
theorem not_zero_isLimit : ¬IsLimit 0 :=
not_isSuccLimit_bot
theorem not_succ_isLimit (o) : ¬IsLimit (succ o) :=
not_isSuccLimit_succ o
theorem not_succ_of_isLimit {o} (h : IsLimit o) : ¬∃ a, o = succ a
| ⟨a, e⟩ => not_succ_isLimit a (e ▸ h)
theorem succ_lt_of_isLimit {o a : Ordinal} (h : IsLimit o) : succ a < o ↔ a < o :=
IsSuccLimit.succ_lt_iff h
theorem le_succ_of_isLimit {o} (h : IsLimit o) {a} : o ≤ succ a ↔ o ≤ a :=
le_iff_le_iff_lt_iff_lt.2 <| succ_lt_of_isLimit h
theorem limit_le {o} (h : IsLimit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a :=
⟨fun h _x l => l.le.trans h, fun H =>
(le_succ_of_isLimit h).1 <| le_of_not_lt fun hn => not_lt_of_le (H _ hn) (lt_succ a)⟩
theorem lt_limit {o} (h : IsLimit o) {a} : a < o ↔ ∃ x < o, a < x := by
-- Porting note: `bex_def` is required.
simpa only [not_forall₂, not_le, bex_def] using not_congr (@limit_le _ h a)
@[simp]
theorem lift_isLimit (o : Ordinal.{v}) : IsLimit (lift.{u,v} o) ↔ IsLimit o :=
liftInitialSeg.isSuccLimit_apply_iff
theorem IsLimit.pos {o : Ordinal} (h : IsLimit o) : 0 < o :=
IsSuccLimit.bot_lt h
theorem IsLimit.ne_zero {o : Ordinal} (h : IsLimit o) : o ≠ 0 :=
h.pos.ne'
theorem IsLimit.one_lt {o : Ordinal} (h : IsLimit o) : 1 < o := by
simpa only [succ_zero] using h.succ_lt h.pos
theorem IsLimit.nat_lt {o : Ordinal} (h : IsLimit o) : ∀ n : ℕ, (n : Ordinal) < o
| 0 => h.pos
| n + 1 => h.succ_lt (IsLimit.nat_lt h n)
theorem zero_or_succ_or_limit (o : Ordinal) : o = 0 ∨ (∃ a, o = succ a) ∨ IsLimit o := by
simpa [eq_comm] using isMin_or_mem_range_succ_or_isSuccLimit o
theorem isLimit_of_not_succ_of_ne_zero {o : Ordinal} (h : ¬∃ a, o = succ a) (h' : o ≠ 0) :
IsLimit o := ((zero_or_succ_or_limit o).resolve_left h').resolve_left h
-- TODO: this is an iff with `IsSuccPrelimit`
theorem IsLimit.sSup_Iio {o : Ordinal} (h : IsLimit o) : sSup (Iio o) = o := by
apply (csSup_le' (fun a ha ↦ le_of_lt ha)).antisymm
apply le_of_forall_lt
intro a ha
exact (lt_succ a).trans_le (le_csSup bddAbove_Iio (h.succ_lt ha))
theorem IsLimit.iSup_Iio {o : Ordinal} (h : IsLimit o) : ⨆ a : Iio o, a.1 = o := by
rw [← sSup_eq_iSup', h.sSup_Iio]
/-- Main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/
@[elab_as_elim]
def limitRecOn {motive : Ordinal → Sort*} (o : Ordinal)
(zero : motive 0) (succ : ∀ o, motive o → motive (succ o))
(isLimit : ∀ o, IsLimit o → (∀ o' < o, motive o') → motive o) : motive o := by
refine SuccOrder.limitRecOn o (fun a ha ↦ ?_) (fun a _ ↦ succ a) isLimit
convert zero
simpa using ha
@[simp]
theorem limitRecOn_zero {motive} (H₁ H₂ H₃) : @limitRecOn motive 0 H₁ H₂ H₃ = H₁ :=
SuccOrder.limitRecOn_isMin _ _ _ isMin_bot
@[simp]
theorem limitRecOn_succ {motive} (o H₁ H₂ H₃) :
@limitRecOn motive (succ o) H₁ H₂ H₃ = H₂ o (@limitRecOn motive o H₁ H₂ H₃) :=
SuccOrder.limitRecOn_succ ..
@[simp]
theorem limitRecOn_limit {motive} (o H₁ H₂ H₃ h) :
@limitRecOn motive o H₁ H₂ H₃ = H₃ o h fun x _h => @limitRecOn motive x H₁ H₂ H₃ :=
SuccOrder.limitRecOn_of_isSuccLimit ..
/-- Bounded recursion on ordinals. Similar to `limitRecOn`, with the assumption `o < l`
added to all cases. The final term's domain is the ordinals below `l`. -/
@[elab_as_elim]
def boundedLimitRecOn {l : Ordinal} (lLim : l.IsLimit) {motive : Iio l → Sort*} (o : Iio l)
(zero : motive ⟨0, lLim.pos⟩)
(succ : (o : Iio l) → motive o → motive ⟨succ o, lLim.succ_lt o.2⟩)
(isLimit : (o : Iio l) → IsLimit o → (Π o' < o, motive o') → motive o) : motive o :=
limitRecOn (motive := fun p ↦ (h : p < l) → motive ⟨p, h⟩) o.1 (fun _ ↦ zero)
(fun o ih h ↦ succ ⟨o, _⟩ <| ih <| (lt_succ o).trans h)
(fun _o ho ih _ ↦ isLimit _ ho fun _o' h ↦ ih _ h _) o.2
@[simp]
theorem boundedLimitRec_zero {l} (lLim : l.IsLimit) {motive} (H₁ H₂ H₃) :
@boundedLimitRecOn l lLim motive ⟨0, lLim.pos⟩ H₁ H₂ H₃ = H₁ := by
rw [boundedLimitRecOn, limitRecOn_zero]
@[simp]
theorem boundedLimitRec_succ {l} (lLim : l.IsLimit) {motive} (o H₁ H₂ H₃) :
@boundedLimitRecOn l lLim motive ⟨succ o.1, lLim.succ_lt o.2⟩ H₁ H₂ H₃ = H₂ o
(@boundedLimitRecOn l lLim motive o H₁ H₂ H₃) := by
rw [boundedLimitRecOn, limitRecOn_succ]
rfl
theorem boundedLimitRec_limit {l} (lLim : l.IsLimit) {motive} (o H₁ H₂ H₃ oLim) :
@boundedLimitRecOn l lLim motive o H₁ H₂ H₃ = H₃ o oLim (fun x _ ↦
@boundedLimitRecOn l lLim motive x H₁ H₂ H₃) := by
rw [boundedLimitRecOn, limitRecOn_limit]
rfl
instance orderTopToTypeSucc (o : Ordinal) : OrderTop (succ o).toType :=
@OrderTop.mk _ _ (Top.mk _) le_enum_succ
theorem enum_succ_eq_top {o : Ordinal} :
enum (α := (succ o).toType) (· < ·) ⟨o, type_toType _ ▸ lt_succ o⟩ = ⊤ :=
rfl
theorem has_succ_of_type_succ_lt {α} {r : α → α → Prop} [wo : IsWellOrder α r]
(h : ∀ a < type r, succ a < type r) (x : α) : ∃ y, r x y := by
use enum r ⟨succ (typein r x), h _ (typein_lt_type r x)⟩
convert enum_lt_enum.mpr _
· rw [enum_typein]
· rw [Subtype.mk_lt_mk, lt_succ_iff]
theorem toType_noMax_of_succ_lt {o : Ordinal} (ho : ∀ a < o, succ a < o) : NoMaxOrder o.toType :=
⟨has_succ_of_type_succ_lt (type_toType _ ▸ ho)⟩
theorem bounded_singleton {r : α → α → Prop} [IsWellOrder α r] (hr : (type r).IsLimit) (x) :
Bounded r {x} := by
refine ⟨enum r ⟨succ (typein r x), hr.succ_lt (typein_lt_type r x)⟩, ?_⟩
intro b hb
rw [mem_singleton_iff.1 hb]
nth_rw 1 [← enum_typein r x]
rw [@enum_lt_enum _ r, Subtype.mk_lt_mk]
apply lt_succ
@[simp]
theorem typein_ordinal (o : Ordinal.{u}) :
@typein Ordinal (· < ·) _ o = Ordinal.lift.{u + 1} o := by
refine Quotient.inductionOn o ?_
rintro ⟨α, r, wo⟩; apply Quotient.sound
constructor; refine ((RelIso.preimage Equiv.ulift r).trans (enum r).symm).symm
theorem mk_Iio_ordinal (o : Ordinal.{u}) :
#(Iio o) = Cardinal.lift.{u + 1} o.card := by
rw [lift_card, ← typein_ordinal]
rfl
/-! ### Normal ordinal functions -/
/-- A normal ordinal function is a strictly increasing function which is
order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`. -/
def IsNormal (f : Ordinal → Ordinal) : Prop :=
(∀ o, f o < f (succ o)) ∧ ∀ o, IsLimit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a
theorem IsNormal.limit_le {f} (H : IsNormal f) :
∀ {o}, IsLimit o → ∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a :=
@H.2
theorem IsNormal.limit_lt {f} (H : IsNormal f) {o} (h : IsLimit o) {a} :
a < f o ↔ ∃ b < o, a < f b :=
not_iff_not.1 <| by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a
theorem IsNormal.strictMono {f} (H : IsNormal f) : StrictMono f := fun a b =>
limitRecOn b (Not.elim (not_lt_of_le <| Ordinal.zero_le _))
(fun _b IH h =>
(lt_or_eq_of_le (le_of_lt_succ h)).elim (fun h => (IH h).trans (H.1 _)) fun e => e ▸ H.1 _)
fun _b l _IH h => lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 le_rfl _ (l.succ_lt h))
theorem IsNormal.monotone {f} (H : IsNormal f) : Monotone f :=
H.strictMono.monotone
theorem isNormal_iff_strictMono_limit (f : Ordinal → Ordinal) :
IsNormal f ↔ StrictMono f ∧ ∀ o, IsLimit o → ∀ a, (∀ b < o, f b ≤ a) → f o ≤ a :=
⟨fun hf => ⟨hf.strictMono, fun a ha c => (hf.2 a ha c).2⟩, fun ⟨hs, hl⟩ =>
⟨fun a => hs (lt_succ a), fun a ha c =>
⟨fun hac _b hba => ((hs hba).trans_le hac).le, hl a ha c⟩⟩⟩
theorem IsNormal.lt_iff {f} (H : IsNormal f) {a b} : f a < f b ↔ a < b :=
StrictMono.lt_iff_lt <| H.strictMono
theorem IsNormal.le_iff {f} (H : IsNormal f) {a b} : f a ≤ f b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_iff
theorem IsNormal.inj {f} (H : IsNormal f) {a b} : f a = f b ↔ a = b := by
simp only [le_antisymm_iff, H.le_iff]
theorem IsNormal.id_le {f} (H : IsNormal f) : id ≤ f :=
H.strictMono.id_le
theorem IsNormal.le_apply {f} (H : IsNormal f) {a} : a ≤ f a :=
H.strictMono.le_apply
theorem IsNormal.le_iff_eq {f} (H : IsNormal f) {a} : f a ≤ a ↔ f a = a :=
H.le_apply.le_iff_eq
theorem IsNormal.le_set {f o} (H : IsNormal f) (p : Set Ordinal) (p0 : p.Nonempty) (b)
(H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, a ≤ o) : f b ≤ o ↔ ∀ a ∈ p, f a ≤ o :=
⟨fun h _ pa => (H.le_iff.2 ((H₂ _).1 le_rfl _ pa)).trans h, fun h => by
induction b using limitRecOn with
| zero =>
obtain ⟨x, px⟩ := p0
have := Ordinal.le_zero.1 ((H₂ _).1 (Ordinal.zero_le _) _ px)
rw [this] at px
exact h _ px
| succ S _ =>
rcases not_forall₂.1 (mt (H₂ S).2 <| (lt_succ S).not_le) with ⟨a, h₁, h₂⟩
exact (H.le_iff.2 <| succ_le_of_lt <| not_le.1 h₂).trans (h _ h₁)
| isLimit S L _ =>
refine (H.2 _ L _).2 fun a h' => ?_
rcases not_forall₂.1 (mt (H₂ a).2 h'.not_le) with ⟨b, h₁, h₂⟩
exact (H.le_iff.2 <| (not_le.1 h₂).le).trans (h _ h₁)⟩
theorem IsNormal.le_set' {f o} (H : IsNormal f) (p : Set α) (p0 : p.Nonempty) (g : α → Ordinal) (b)
(H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, g a ≤ o) : f b ≤ o ↔ ∀ a ∈ p, f (g a) ≤ o := by
simpa [H₂] using H.le_set (g '' p) (p0.image g) b
theorem IsNormal.refl : IsNormal id :=
⟨lt_succ, fun _o l _a => Ordinal.limit_le l⟩
theorem IsNormal.trans {f g} (H₁ : IsNormal f) (H₂ : IsNormal g) : IsNormal (f ∘ g) :=
⟨fun _x => H₁.lt_iff.2 (H₂.1 _), fun o l _a =>
H₁.le_set' (· < o) ⟨0, l.pos⟩ g _ fun _c => H₂.2 _ l _⟩
theorem IsNormal.isLimit {f} (H : IsNormal f) {o} (ho : IsLimit o) : IsLimit (f o) := by
rw [isLimit_iff, isSuccPrelimit_iff_succ_lt]
use (H.lt_iff.2 ho.pos).ne_bot
intro a ha
obtain ⟨b, hb, hab⟩ := (H.limit_lt ho).1 ha
rw [← succ_le_iff] at hab
apply hab.trans_lt
rwa [H.lt_iff]
theorem add_le_of_limit {a b c : Ordinal} (h : IsLimit b) :
a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c :=
⟨fun h _ l => (add_le_add_left l.le _).trans h, fun H =>
le_of_not_lt <| by
-- Porting note: `induction` tactics are required because of the parser bug.
induction a using inductionOn with
| H α r =>
induction b using inductionOn with
| H β s =>
intro l
suffices ∀ x : β, Sum.Lex r s (Sum.inr x) (enum _ ⟨_, l⟩) by
-- Porting note: `revert` & `intro` is required because `cases'` doesn't replace
-- `enum _ _ l` in `this`.
revert this; rcases enum _ ⟨_, l⟩ with x | x <;> intro this
· cases this (enum s ⟨0, h.pos⟩)
· exact irrefl _ (this _)
intro x
rw [← typein_lt_typein (Sum.Lex r s), typein_enum]
have := H _ (h.succ_lt (typein_lt_type s x))
rw [add_succ, succ_le_iff] at this
refine
(RelEmbedding.ofMonotone (fun a => ?_) fun a b => ?_).ordinal_type_le.trans_lt this
· rcases a with ⟨a | b, h⟩
· exact Sum.inl a
· exact Sum.inr ⟨b, by cases h; assumption⟩
· rcases a with ⟨a | a, h₁⟩ <;> rcases b with ⟨b | b, h₂⟩ <;> cases h₁ <;> cases h₂ <;>
rintro ⟨⟩ <;> constructor <;> assumption⟩
theorem isNormal_add_right (a : Ordinal) : IsNormal (a + ·) :=
⟨fun b => (add_lt_add_iff_left a).2 (lt_succ b), fun _b l _c => add_le_of_limit l⟩
theorem isLimit_add (a) {b} : IsLimit b → IsLimit (a + b) :=
(isNormal_add_right a).isLimit
alias IsLimit.add := isLimit_add
/-! ### Subtraction on ordinals -/
/-- The set in the definition of subtraction is nonempty. -/
private theorem sub_nonempty {a b : Ordinal} : { o | a ≤ b + o }.Nonempty :=
⟨a, le_add_left _ _⟩
/-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/
instance sub : Sub Ordinal :=
⟨fun a b => sInf { o | a ≤ b + o }⟩
theorem le_add_sub (a b : Ordinal) : a ≤ b + (a - b) :=
csInf_mem sub_nonempty
theorem sub_le {a b c : Ordinal} : a - b ≤ c ↔ a ≤ b + c :=
⟨fun h => (le_add_sub a b).trans (add_le_add_left h _), fun h => csInf_le' h⟩
theorem lt_sub {a b c : Ordinal} : a < b - c ↔ c + a < b :=
lt_iff_lt_of_le_iff_le sub_le
theorem add_sub_cancel (a b : Ordinal) : a + b - a = b :=
le_antisymm (sub_le.2 <| le_rfl) ((add_le_add_iff_left a).1 <| le_add_sub _ _)
theorem sub_eq_of_add_eq {a b c : Ordinal} (h : a + b = c) : c - a = b :=
h ▸ add_sub_cancel _ _
theorem sub_le_self (a b : Ordinal) : a - b ≤ a :=
sub_le.2 <| le_add_left _ _
protected theorem add_sub_cancel_of_le {a b : Ordinal} (h : b ≤ a) : b + (a - b) = a :=
(le_add_sub a b).antisymm'
(by
rcases zero_or_succ_or_limit (a - b) with (e | ⟨c, e⟩ | l)
· simp only [e, add_zero, h]
· rw [e, add_succ, succ_le_iff, ← lt_sub, e]
exact lt_succ c
· exact (add_le_of_limit l).2 fun c l => (lt_sub.1 l).le)
theorem le_sub_of_le {a b c : Ordinal} (h : b ≤ a) : c ≤ a - b ↔ b + c ≤ a := by
rw [← add_le_add_iff_left b, Ordinal.add_sub_cancel_of_le h]
theorem sub_lt_of_le {a b c : Ordinal} (h : b ≤ a) : a - b < c ↔ a < b + c :=
lt_iff_lt_of_le_iff_le (le_sub_of_le h)
instance existsAddOfLE : ExistsAddOfLE Ordinal :=
⟨fun h => ⟨_, (Ordinal.add_sub_cancel_of_le h).symm⟩⟩
@[simp]
theorem sub_zero (a : Ordinal) : a - 0 = a := by simpa only [zero_add] using add_sub_cancel 0 a
@[simp]
theorem zero_sub (a : Ordinal) : 0 - a = 0 := by rw [← Ordinal.le_zero]; apply sub_le_self
@[simp]
theorem sub_self (a : Ordinal) : a - a = 0 := by simpa only [add_zero] using add_sub_cancel a 0
protected theorem sub_eq_zero_iff_le {a b : Ordinal} : a - b = 0 ↔ a ≤ b :=
⟨fun h => by simpa only [h, add_zero] using le_add_sub a b, fun h => by
rwa [← Ordinal.le_zero, sub_le, add_zero]⟩
protected theorem sub_ne_zero_iff_lt {a b : Ordinal} : a - b ≠ 0 ↔ b < a := by
simpa using Ordinal.sub_eq_zero_iff_le.not
theorem sub_sub (a b c : Ordinal) : a - b - c = a - (b + c) :=
eq_of_forall_ge_iff fun d => by rw [sub_le, sub_le, sub_le, add_assoc]
@[simp]
theorem add_sub_add_cancel (a b c : Ordinal) : a + b - (a + c) = b - c := by
rw [← sub_sub, add_sub_cancel]
theorem le_sub_of_add_le {a b c : Ordinal} (h : b + c ≤ a) : c ≤ a - b := by
rw [← add_le_add_iff_left b]
exact h.trans (le_add_sub a b)
theorem sub_lt_of_lt_add {a b c : Ordinal} (h : a < b + c) (hc : 0 < c) : a - b < c := by
obtain hab | hba := lt_or_le a b
· rwa [Ordinal.sub_eq_zero_iff_le.2 hab.le]
· rwa [sub_lt_of_le hba]
theorem lt_add_iff {a b c : Ordinal} (hc : c ≠ 0) : a < b + c ↔ ∃ d < c, a ≤ b + d := by
use fun h ↦ ⟨_, sub_lt_of_lt_add h hc.bot_lt, le_add_sub a b⟩
rintro ⟨d, hd, ha⟩
exact ha.trans_lt (add_lt_add_left hd b)
theorem add_le_iff {a b c : Ordinal} (hb : b ≠ 0) : a + b ≤ c ↔ ∀ d < b, a + d < c := by
simpa using (lt_add_iff hb).not
@[deprecated add_le_iff (since := "2024-12-08")]
theorem add_le_of_forall_add_lt {a b c : Ordinal} (hb : 0 < b) (h : ∀ d < b, a + d < c) :
a + b ≤ c :=
(add_le_iff hb.ne').2 h
theorem isLimit_sub {a b} (ha : IsLimit a) (h : b < a) : IsLimit (a - b) := by
rw [isLimit_iff, Ordinal.sub_ne_zero_iff_lt, isSuccPrelimit_iff_succ_lt]
refine ⟨h, fun c hc ↦ ?_⟩
rw [lt_sub] at hc ⊢
rw [add_succ]
exact ha.succ_lt hc
/-! ### Multiplication of ordinals -/
/-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on
`o₂ × o₁`. -/
instance monoid : Monoid Ordinal.{u} where
mul a b :=
Quotient.liftOn₂ a b
(fun ⟨α, r, _⟩ ⟨β, s, _⟩ => ⟦⟨β × α, Prod.Lex s r, inferInstance⟩⟧ :
WellOrder → WellOrder → Ordinal)
fun ⟨_, _, _⟩ _ _ _ ⟨f⟩ ⟨g⟩ => Quot.sound ⟨RelIso.prodLexCongr g f⟩
one := 1
mul_assoc a b c :=
Quotient.inductionOn₃ a b c fun ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ =>
Eq.symm <|
Quotient.sound
⟨⟨prodAssoc _ _ _, @fun a b => by
rcases a with ⟨⟨a₁, a₂⟩, a₃⟩
rcases b with ⟨⟨b₁, b₂⟩, b₃⟩
simp [Prod.lex_def, and_or_left, or_assoc, and_assoc]⟩⟩
mul_one a :=
inductionOn a fun α r _ =>
Quotient.sound
⟨⟨punitProd _, @fun a b => by
rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩
simp only [Prod.lex_def, EmptyRelation, false_or]
simp only [eq_self_iff_true, true_and]
rfl⟩⟩
one_mul a :=
inductionOn a fun α r _ =>
Quotient.sound
⟨⟨prodPUnit _, @fun a b => by
rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩
simp only [Prod.lex_def, EmptyRelation, and_false, or_false]
rfl⟩⟩
@[simp]
theorem type_prod_lex {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [IsWellOrder α r]
[IsWellOrder β s] : type (Prod.Lex s r) = type r * type s :=
rfl
private theorem mul_eq_zero' {a b : Ordinal} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
inductionOn a fun α _ _ =>
inductionOn b fun β _ _ => by
simp_rw [← type_prod_lex, type_eq_zero_iff_isEmpty]
rw [or_comm]
exact isEmpty_prod
instance monoidWithZero : MonoidWithZero Ordinal :=
{ Ordinal.monoid with
zero := 0
mul_zero := fun _a => mul_eq_zero'.2 <| Or.inr rfl
zero_mul := fun _a => mul_eq_zero'.2 <| Or.inl rfl }
instance noZeroDivisors : NoZeroDivisors Ordinal :=
⟨fun {_ _} => mul_eq_zero'.1⟩
@[simp]
theorem lift_mul (a b : Ordinal.{v}) : lift.{u} (a * b) = lift.{u} a * lift.{u} b :=
Quotient.inductionOn₂ a b fun ⟨_α, _r, _⟩ ⟨_β, _s, _⟩ =>
Quotient.sound
⟨(RelIso.preimage Equiv.ulift _).trans
(RelIso.prodLexCongr (RelIso.preimage Equiv.ulift _)
(RelIso.preimage Equiv.ulift _)).symm⟩
@[simp]
theorem card_mul (a b) : card (a * b) = card a * card b :=
Quotient.inductionOn₂ a b fun ⟨α, _r, _⟩ ⟨β, _s, _⟩ => mul_comm #β #α
instance leftDistribClass : LeftDistribClass Ordinal.{u} :=
⟨fun a b c =>
Quotient.inductionOn₃ a b c fun ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ =>
Quotient.sound
⟨⟨sumProdDistrib _ _ _, by
rintro ⟨a₁ | a₁, a₂⟩ ⟨b₁ | b₁, b₂⟩ <;>
simp only [Prod.lex_def, Sum.lex_inl_inl, Sum.Lex.sep, Sum.lex_inr_inl, Sum.lex_inr_inr,
sumProdDistrib_apply_left, sumProdDistrib_apply_right, reduceCtorEq] <;>
-- Porting note: `Sum.inr.inj_iff` is required.
simp only [Sum.inl.inj_iff, Sum.inr.inj_iff, true_or, false_and, false_or]⟩⟩⟩
theorem mul_succ (a b : Ordinal) : a * succ b = a * b + a :=
mul_add_one a b
instance mulLeftMono : MulLeftMono Ordinal.{u} :=
⟨fun c a b =>
Quotient.inductionOn₃ a b c fun ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ => by
refine
(RelEmbedding.ofMonotone (fun a : α × γ => (f a.1, a.2)) fun a b h => ?_).ordinal_type_le
obtain ⟨-, -, h'⟩ | ⟨-, h'⟩ := h
· exact Prod.Lex.left _ _ (f.toRelEmbedding.map_rel_iff.2 h')
· exact Prod.Lex.right _ h'⟩
instance mulRightMono : MulRightMono Ordinal.{u} :=
⟨fun c a b =>
Quotient.inductionOn₃ a b c fun ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ => by
refine
(RelEmbedding.ofMonotone (fun a : γ × α => (a.1, f a.2)) fun a b h => ?_).ordinal_type_le
obtain ⟨-, -, h'⟩ | ⟨-, h'⟩ := h
· exact Prod.Lex.left _ _ h'
· exact Prod.Lex.right _ (f.toRelEmbedding.map_rel_iff.2 h')⟩
theorem le_mul_left (a : Ordinal) {b : Ordinal} (hb : 0 < b) : a ≤ a * b := by
convert mul_le_mul_left' (one_le_iff_pos.2 hb) a
rw [mul_one a]
theorem le_mul_right (a : Ordinal) {b : Ordinal} (hb : 0 < b) : a ≤ b * a := by
convert mul_le_mul_right' (one_le_iff_pos.2 hb) a
rw [one_mul a]
private theorem mul_le_of_limit_aux {α β r s} [IsWellOrder α r] [IsWellOrder β s] {c}
(h : IsLimit (type s)) (H : ∀ b' < type s, type r * b' ≤ c) (l : c < type r * type s) :
False := by
suffices ∀ a b, Prod.Lex s r (b, a) (enum _ ⟨_, l⟩) by
obtain ⟨b, a⟩ := enum _ ⟨_, l⟩
exact irrefl _ (this _ _)
intro a b
rw [← typein_lt_typein (Prod.Lex s r), typein_enum]
have := H _ (h.succ_lt (typein_lt_type s b))
rw [mul_succ] at this
have := ((add_lt_add_iff_left _).2 (typein_lt_type _ a)).trans_le this
refine (RelEmbedding.ofMonotone (fun a => ?_) fun a b => ?_).ordinal_type_le.trans_lt this
· rcases a with ⟨⟨b', a'⟩, h⟩
by_cases e : b = b'
· refine Sum.inr ⟨a', ?_⟩
subst e
obtain ⟨-, -, h⟩ | ⟨-, h⟩ := h
· exact (irrefl _ h).elim
· exact h
· refine Sum.inl (⟨b', ?_⟩, a')
obtain ⟨-, -, h⟩ | ⟨e, h⟩ := h
· exact h
· exact (e rfl).elim
· rcases a with ⟨⟨b₁, a₁⟩, h₁⟩
rcases b with ⟨⟨b₂, a₂⟩, h₂⟩
intro h
by_cases e₁ : b = b₁ <;> by_cases e₂ : b = b₂
· substs b₁ b₂
simpa only [subrel_val, Prod.lex_def, @irrefl _ s _ b, true_and, false_or,
eq_self_iff_true, dif_pos, Sum.lex_inr_inr] using h
· subst b₁
simp only [subrel_val, Prod.lex_def, e₂, Prod.lex_def, dif_pos, subrel_val, eq_self_iff_true,
or_false, dif_neg, not_false_iff, Sum.lex_inr_inl, false_and] at h ⊢
obtain ⟨-, -, h₂_h⟩ | e₂ := h₂ <;> [exact asymm h h₂_h; exact e₂ rfl]
· simp [e₂, dif_neg e₁, show b₂ ≠ b₁ from e₂ ▸ e₁]
· simpa only [dif_neg e₁, dif_neg e₂, Prod.lex_def, subrel_val, Subtype.mk_eq_mk,
Sum.lex_inl_inl] using h
theorem mul_le_of_limit {a b c : Ordinal} (h : IsLimit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c :=
⟨fun h _ l => (mul_le_mul_left' l.le _).trans h, fun H =>
-- Porting note: `induction` tactics are required because of the parser bug.
le_of_not_lt <| by
induction a using inductionOn with
| H α r =>
induction b using inductionOn with
| H β s =>
exact mul_le_of_limit_aux h H⟩
theorem isNormal_mul_right {a : Ordinal} (h : 0 < a) : IsNormal (a * ·) :=
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/12129): additional beta reduction needed
⟨fun b => by
beta_reduce
rw [mul_succ]
simpa only [add_zero] using (add_lt_add_iff_left (a * b)).2 h,
fun _ l _ => mul_le_of_limit l⟩
theorem lt_mul_of_limit {a b c : Ordinal} (h : IsLimit c) : a < b * c ↔ ∃ c' < c, a < b * c' := by
-- Porting note: `bex_def` is required.
simpa only [not_forall₂, not_le, bex_def] using not_congr (@mul_le_of_limit b c a h)
theorem mul_lt_mul_iff_left {a b c : Ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c :=
(isNormal_mul_right a0).lt_iff
theorem mul_le_mul_iff_left {a b c : Ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c :=
(isNormal_mul_right a0).le_iff
theorem mul_lt_mul_of_pos_left {a b c : Ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b :=
(mul_lt_mul_iff_left c0).2 h
theorem mul_pos {a b : Ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b := by
simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁
theorem mul_ne_zero {a b : Ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := by
simpa only [Ordinal.pos_iff_ne_zero] using mul_pos
theorem le_of_mul_le_mul_left {a b c : Ordinal} (h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b :=
le_imp_le_of_lt_imp_lt (fun h' => mul_lt_mul_of_pos_left h' h0) h
theorem mul_right_inj {a b c : Ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c :=
(isNormal_mul_right a0).inj
theorem isLimit_mul {a b : Ordinal} (a0 : 0 < a) : IsLimit b → IsLimit (a * b) :=
(isNormal_mul_right a0).isLimit
theorem isLimit_mul_left {a b : Ordinal} (l : IsLimit a) (b0 : 0 < b) : IsLimit (a * b) := by
rcases zero_or_succ_or_limit b with (rfl | ⟨b, rfl⟩ | lb)
· exact b0.false.elim
· rw [mul_succ]
exact isLimit_add _ l
· exact isLimit_mul l.pos lb
theorem smul_eq_mul : ∀ (n : ℕ) (a : Ordinal), n • a = a * n
| 0, a => by rw [zero_nsmul, Nat.cast_zero, mul_zero]
| n + 1, a => by rw [succ_nsmul, Nat.cast_add, mul_add, Nat.cast_one, mul_one, smul_eq_mul n]
private theorem add_mul_limit_aux {a b c : Ordinal} (ba : b + a = a) (l : IsLimit c)
(IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c :=
le_antisymm
((mul_le_of_limit l).2 fun c' h => by
apply (mul_le_mul_left' (le_succ c') _).trans
rw [IH _ h]
apply (add_le_add_left _ _).trans
· rw [← mul_succ]
exact mul_le_mul_left' (succ_le_of_lt <| l.succ_lt h) _
· rw [← ba]
exact le_add_right _ _)
(mul_le_mul_right' (le_add_right _ _) _)
theorem add_mul_succ {a b : Ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := by
induction c using limitRecOn with
| zero => simp only [succ_zero, mul_one]
| succ c IH =>
rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ]
| isLimit c l IH =>
rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc]
theorem add_mul_limit {a b c : Ordinal} (ba : b + a = a) (l : IsLimit c) : (a + b) * c = a * c :=
add_mul_limit_aux ba l fun c' _ => add_mul_succ c' ba
/-! ### Division on ordinals -/
/-- The set in the definition of division is nonempty. -/
private theorem div_nonempty {a b : Ordinal} (h : b ≠ 0) : { o | a < b * succ o }.Nonempty :=
⟨a, (succ_le_iff (a := a) (b := b * succ a)).1 <| by
simpa only [succ_zero, one_mul] using
mul_le_mul_right' (succ_le_of_lt (Ordinal.pos_iff_ne_zero.2 h)) (succ a)⟩
/-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/
instance div : Div Ordinal :=
⟨fun a b => if b = 0 then 0 else sInf { o | a < b * succ o }⟩
@[simp]
theorem div_zero (a : Ordinal) : a / 0 = 0 :=
dif_pos rfl
private theorem div_def (a) {b : Ordinal} (h : b ≠ 0) : a / b = sInf { o | a < b * succ o } :=
dif_neg h
theorem lt_mul_succ_div (a) {b : Ordinal} (h : b ≠ 0) : a < b * succ (a / b) := by
rw [div_def a h]; exact csInf_mem (div_nonempty h)
theorem lt_mul_div_add (a) {b : Ordinal} (h : b ≠ 0) : a < b * (a / b) + b := by
simpa only [mul_succ] using lt_mul_succ_div a h
theorem div_le {a b c : Ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c :=
⟨fun h => (lt_mul_succ_div a b0).trans_le (mul_le_mul_left' (succ_le_succ_iff.2 h) _), fun h => by
rw [div_def a b0]; exact csInf_le' h⟩
theorem lt_div {a b c : Ordinal} (h : c ≠ 0) : a < b / c ↔ c * succ a ≤ b := by
rw [← not_le, div_le h, not_lt]
theorem div_pos {b c : Ordinal} (h : c ≠ 0) : 0 < b / c ↔ c ≤ b := by simp [lt_div h]
theorem le_div {a b c : Ordinal} (c0 : c ≠ 0) : a ≤ b / c ↔ c * a ≤ b := by
induction a using limitRecOn with
| zero => simp only [mul_zero, Ordinal.zero_le]
| succ _ _ => rw [succ_le_iff, lt_div c0]
| isLimit _ h₁ h₂ =>
revert h₁ h₂
simp +contextual only [mul_le_of_limit, limit_le, forall_true_iff]
theorem div_lt {a b c : Ordinal} (b0 : b ≠ 0) : a / b < c ↔ a < b * c :=
lt_iff_lt_of_le_iff_le <| le_div b0
theorem div_le_of_le_mul {a b c : Ordinal} (h : a ≤ b * c) : a / b ≤ c :=
if b0 : b = 0 then by simp only [b0, div_zero, Ordinal.zero_le]
else
(div_le b0).2 <| h.trans_lt <| mul_lt_mul_of_pos_left (lt_succ c) (Ordinal.pos_iff_ne_zero.2 b0)
theorem mul_lt_of_lt_div {a b c : Ordinal} : a < b / c → c * a < b :=
lt_imp_lt_of_le_imp_le div_le_of_le_mul
@[simp]
theorem zero_div (a : Ordinal) : 0 / a = 0 :=
Ordinal.le_zero.1 <| div_le_of_le_mul <| Ordinal.zero_le _
theorem mul_div_le (a b : Ordinal) : b * (a / b) ≤ a :=
if b0 : b = 0 then by simp only [b0, zero_mul, Ordinal.zero_le] else (le_div b0).1 le_rfl
theorem div_le_left {a b : Ordinal} (h : a ≤ b) (c : Ordinal) : a / c ≤ b / c := by
obtain rfl | hc := eq_or_ne c 0
· rw [div_zero, div_zero]
· rw [le_div hc]
exact (mul_div_le a c).trans h
theorem mul_add_div (a) {b : Ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b := by
apply le_antisymm
· apply (div_le b0).2
rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left]
apply lt_mul_div_add _ b0
· rw [le_div b0, mul_add, add_le_add_iff_left]
apply mul_div_le
theorem div_eq_zero_of_lt {a b : Ordinal} (h : a < b) : a / b = 0 := by
rw [← Ordinal.le_zero, div_le <| Ordinal.pos_iff_ne_zero.1 <| (Ordinal.zero_le _).trans_lt h]
simpa only [succ_zero, mul_one] using h
@[simp]
theorem mul_div_cancel (a) {b : Ordinal} (b0 : b ≠ 0) : b * a / b = a := by
simpa only [add_zero, zero_div] using mul_add_div a b0 0
theorem mul_add_div_mul {a c : Ordinal} (hc : c < a) (b d : Ordinal) :
(a * b + c) / (a * d) = b / d := by
have ha : a ≠ 0 := ((Ordinal.zero_le c).trans_lt hc).ne'
obtain rfl | hd := eq_or_ne d 0
· rw [mul_zero, div_zero, div_zero]
· have H := mul_ne_zero ha hd
apply le_antisymm
· rw [← lt_succ_iff, div_lt H, mul_assoc]
· apply (add_lt_add_left hc _).trans_le
rw [← mul_succ]
apply mul_le_mul_left'
rw [succ_le_iff]
exact lt_mul_succ_div b hd
· rw [le_div H, mul_assoc]
exact (mul_le_mul_left' (mul_div_le b d) a).trans (le_add_right _ c)
theorem mul_div_mul_cancel {a : Ordinal} (ha : a ≠ 0) (b c) : a * b / (a * c) = b / c := by
convert mul_add_div_mul (Ordinal.pos_iff_ne_zero.2 ha) b c using 1
rw [add_zero]
@[simp]
theorem div_one (a : Ordinal) : a / 1 = a := by
simpa only [one_mul] using mul_div_cancel a Ordinal.one_ne_zero
@[simp]
theorem div_self {a : Ordinal} (h : a ≠ 0) : a / a = 1 := by
simpa only [mul_one] using mul_div_cancel 1 h
theorem mul_sub (a b c : Ordinal) : a * (b - c) = a * b - a * c :=
if a0 : a = 0 then by simp only [a0, zero_mul, sub_self]
else
eq_of_forall_ge_iff fun d => by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0]
theorem isLimit_add_iff {a b} : IsLimit (a + b) ↔ IsLimit b ∨ b = 0 ∧ IsLimit a := by
constructor <;> intro h
· by_cases h' : b = 0
· rw [h', add_zero] at h
right
exact ⟨h', h⟩
left
rw [← add_sub_cancel a b]
apply isLimit_sub h
suffices a + 0 < a + b by simpa only [add_zero] using this
rwa [add_lt_add_iff_left, Ordinal.pos_iff_ne_zero]
rcases h with (h | ⟨rfl, h⟩)
· exact isLimit_add a h
· simpa only [add_zero]
theorem dvd_add_iff : ∀ {a b c : Ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c)
| a, _, c, ⟨b, rfl⟩ =>
⟨fun ⟨d, e⟩ => ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, fun ⟨d, e⟩ => by
rw [e, ← mul_add]
apply dvd_mul_right⟩
theorem div_mul_cancel : ∀ {a b : Ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b
| a, _, a0, ⟨b, rfl⟩ => by rw [mul_div_cancel _ a0]
theorem le_of_dvd : ∀ {a b : Ordinal}, b ≠ 0 → a ∣ b → a ≤ b
-- Porting note: `⟨b, rfl⟩ => by` → `⟨b, e⟩ => by subst e`
| a, _, b0, ⟨b, e⟩ => by
subst e
-- Porting note: `Ne` is required.
simpa only [mul_one] using
mul_le_mul_left'
(one_le_iff_ne_zero.2 fun h : b = 0 => by
simp only [h, mul_zero, Ne, not_true_eq_false] at b0) a
theorem dvd_antisymm {a b : Ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b :=
if a0 : a = 0 then by subst a; exact (eq_zero_of_zero_dvd h₁).symm
else
if b0 : b = 0 then by subst b; exact eq_zero_of_zero_dvd h₂
else (le_of_dvd b0 h₁).antisymm (le_of_dvd a0 h₂)
instance isAntisymm : IsAntisymm Ordinal (· ∣ ·) :=
⟨@dvd_antisymm⟩
/-- `a % b` is the unique ordinal `o'` satisfying
`a = b * o + o'` with `o' < b`. -/
instance mod : Mod Ordinal :=
⟨fun a b => a - b * (a / b)⟩
theorem mod_def (a b : Ordinal) : a % b = a - b * (a / b) :=
rfl
theorem mod_le (a b : Ordinal) : a % b ≤ a :=
sub_le_self a _
@[simp]
theorem mod_zero (a : Ordinal) : a % 0 = a := by simp only [mod_def, div_zero, zero_mul, sub_zero]
theorem mod_eq_of_lt {a b : Ordinal} (h : a < b) : a % b = a := by
simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero]
@[simp]
theorem zero_mod (b : Ordinal) : 0 % b = 0 := by simp only [mod_def, zero_div, mul_zero, sub_self]
theorem div_add_mod (a b : Ordinal) : b * (a / b) + a % b = a :=
Ordinal.add_sub_cancel_of_le <| mul_div_le _ _
theorem mod_lt (a) {b : Ordinal} (h : b ≠ 0) : a % b < b :=
(add_lt_add_iff_left (b * (a / b))).1 <| by rw [div_add_mod]; exact lt_mul_div_add a h
@[simp]
theorem mod_self (a : Ordinal) : a % a = 0 :=
if a0 : a = 0 then by simp only [a0, zero_mod]
else by simp only [mod_def, div_self a0, mul_one, sub_self]
@[simp]
theorem mod_one (a : Ordinal) : a % 1 = 0 := by simp only [mod_def, div_one, one_mul, sub_self]
theorem dvd_of_mod_eq_zero {a b : Ordinal} (H : a % b = 0) : b ∣ a :=
⟨a / b, by simpa [H] using (div_add_mod a b).symm⟩
theorem mod_eq_zero_of_dvd {a b : Ordinal} (H : b ∣ a) : a % b = 0 := by
rcases H with ⟨c, rfl⟩
rcases eq_or_ne b 0 with (rfl | hb)
· simp
· simp [mod_def, hb]
theorem dvd_iff_mod_eq_zero {a b : Ordinal} : b ∣ a ↔ a % b = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
@[simp]
theorem mul_add_mod_self (x y z : Ordinal) : (x * y + z) % x = z % x := by
rcases eq_or_ne x 0 with rfl | hx
· simp
· rwa [mod_def, mul_add_div, mul_add, ← sub_sub, add_sub_cancel, mod_def]
@[simp]
theorem mul_mod (x y : Ordinal) : x * y % x = 0 := by
simpa using mul_add_mod_self x y 0
theorem mul_add_mod_mul {w x : Ordinal} (hw : w < x) (y z : Ordinal) :
(x * y + w) % (x * z) = x * (y % z) + w := by
rw [mod_def, mul_add_div_mul hw]
apply sub_eq_of_add_eq
rw [← add_assoc, mul_assoc, ← mul_add, div_add_mod]
theorem mul_mod_mul (x y z : Ordinal) : (x * y) % (x * z) = x * (y % z) := by
obtain rfl | hx := Ordinal.eq_zero_or_pos x
· simp
· convert mul_add_mod_mul hx y z using 1 <;>
rw [add_zero]
theorem mod_mod_of_dvd (a : Ordinal) {b c : Ordinal} (h : c ∣ b) : a % b % c = a % c := by
nth_rw 2 [← div_add_mod a b]
rcases h with ⟨d, rfl⟩
rw [mul_assoc, mul_add_mod_self]
@[simp]
theorem mod_mod (a b : Ordinal) : a % b % b = a % b :=
mod_mod_of_dvd a dvd_rfl
/-! ### Casting naturals into ordinals, compatibility with operations -/
instance instCharZero : CharZero Ordinal := by
refine ⟨fun a b h ↦ ?_⟩
rwa [← Cardinal.ord_nat, ← Cardinal.ord_nat, Cardinal.ord_inj, Nat.cast_inj] at h
@[simp]
theorem one_add_natCast (m : ℕ) : 1 + (m : Ordinal) = succ m := by
rw [← Nat.cast_one, ← Nat.cast_add, add_comm]
rfl
@[simp]
theorem one_add_ofNat (m : ℕ) [m.AtLeastTwo] :
1 + (ofNat(m) : Ordinal) = Order.succ (OfNat.ofNat m : Ordinal) :=
one_add_natCast m
@[simp, norm_cast]
theorem natCast_mul (m : ℕ) : ∀ n : ℕ, ((m * n : ℕ) : Ordinal) = m * n
| 0 => by simp
| n + 1 => by rw [Nat.mul_succ, Nat.cast_add, natCast_mul m n, Nat.cast_succ, mul_add_one]
@[simp, norm_cast]
theorem natCast_sub (m n : ℕ) : ((m - n : ℕ) : Ordinal) = m - n := by
rcases le_total m n with h | h
· rw [tsub_eq_zero_iff_le.2 h, Ordinal.sub_eq_zero_iff_le.2 (Nat.cast_le.2 h), Nat.cast_zero]
· rw [← add_left_cancel_iff (a := ↑n), ← Nat.cast_add, add_tsub_cancel_of_le h,
Ordinal.add_sub_cancel_of_le (Nat.cast_le.2 h)]
@[simp, norm_cast]
theorem natCast_div (m n : ℕ) : ((m / n : ℕ) : Ordinal) = m / n := by
rcases eq_or_ne n 0 with (rfl | hn)
· simp
· have hn' : (n : Ordinal) ≠ 0 := Nat.cast_ne_zero.2 hn
apply le_antisymm
· rw [le_div hn', ← natCast_mul, Nat.cast_le, mul_comm]
apply Nat.div_mul_le_self
· rw [div_le hn', ← add_one_eq_succ, ← Nat.cast_succ, ← natCast_mul, Nat.cast_lt, mul_comm,
← Nat.div_lt_iff_lt_mul (Nat.pos_of_ne_zero hn)]
apply Nat.lt_succ_self
@[simp, norm_cast]
theorem natCast_mod (m n : ℕ) : ((m % n : ℕ) : Ordinal) = m % n := by
rw [← add_left_cancel_iff, div_add_mod, ← natCast_div, ← natCast_mul, ← Nat.cast_add,
Nat.div_add_mod]
@[simp]
theorem lift_natCast : ∀ n : ℕ, lift.{u, v} n = n
| 0 => by simp
| n + 1 => by simp [lift_natCast n]
@[simp]
theorem lift_ofNat (n : ℕ) [n.AtLeastTwo] :
lift.{u, v} ofNat(n) = OfNat.ofNat n :=
lift_natCast n
theorem lt_omega0 {o : Ordinal} : o < ω ↔ ∃ n : ℕ, o = n := by
simp_rw [← Cardinal.ord_aleph0, Cardinal.lt_ord, lt_aleph0, card_eq_nat]
theorem nat_lt_omega0 (n : ℕ) : ↑n < ω :=
lt_omega0.2 ⟨_, rfl⟩
theorem eq_nat_or_omega0_le (o : Ordinal) : (∃ n : ℕ, o = n) ∨ ω ≤ o := by
obtain ho | ho := lt_or_le o ω
· exact Or.inl <| lt_omega0.1 ho
· exact Or.inr ho
theorem omega0_pos : 0 < ω :=
nat_lt_omega0 0
theorem omega0_ne_zero : ω ≠ 0 :=
omega0_pos.ne'
theorem one_lt_omega0 : 1 < ω := by simpa only [Nat.cast_one] using nat_lt_omega0 1
theorem isLimit_omega0 : IsLimit ω := by
rw [isLimit_iff, isSuccPrelimit_iff_succ_lt]
refine ⟨omega0_ne_zero, fun o h => ?_⟩
obtain ⟨n, rfl⟩ := lt_omega0.1 h
exact nat_lt_omega0 (n + 1)
theorem omega0_le {o : Ordinal} : ω ≤ o ↔ ∀ n : ℕ, ↑n ≤ o :=
⟨fun h n => (nat_lt_omega0 _).le.trans h, fun H =>
le_of_forall_lt fun a h => by
let ⟨n, e⟩ := lt_omega0.1 h
rw [e, ← succ_le_iff]; exact H (n + 1)⟩
theorem nat_lt_limit {o} (h : IsLimit o) : ∀ n : ℕ, ↑n < o
| 0 => h.pos
| n + 1 => h.succ_lt (nat_lt_limit h n)
theorem omega0_le_of_isLimit {o} (h : IsLimit o) : ω ≤ o :=
omega0_le.2 fun n => le_of_lt <| nat_lt_limit h n
theorem natCast_add_omega0 (n : ℕ) : n + ω = ω := by
refine le_antisymm (le_of_forall_lt fun a ha ↦ ?_) (le_add_left _ _)
obtain ⟨b, hb', hb⟩ := (lt_add_iff omega0_ne_zero).1 ha
obtain ⟨m, rfl⟩ := lt_omega0.1 hb'
apply hb.trans_lt
exact_mod_cast nat_lt_omega0 (n + m)
theorem one_add_omega0 : 1 + ω = ω :=
mod_cast natCast_add_omega0 1
theorem add_omega0 {a : Ordinal} (h : a < ω) : a + ω = ω := by
obtain ⟨n, rfl⟩ := lt_omega0.1 h
exact natCast_add_omega0 n
@[simp]
theorem natCast_add_of_omega0_le {o} (h : ω ≤ o) (n : ℕ) : n + o = o := by
rw [← Ordinal.add_sub_cancel_of_le h, ← add_assoc, natCast_add_omega0]
@[simp]
theorem one_add_of_omega0_le {o} (h : ω ≤ o) : 1 + o = o :=
mod_cast natCast_add_of_omega0_le h 1
open Ordinal
theorem isLimit_iff_omega0_dvd {a : Ordinal} : IsLimit a ↔ a ≠ 0 ∧ ω ∣ a := by
refine ⟨fun l => ⟨l.ne_zero, ⟨a / ω, le_antisymm ?_ (mul_div_le _ _)⟩⟩, fun h => ?_⟩
· refine (limit_le l).2 fun x hx => le_of_lt ?_
rw [← div_lt omega0_ne_zero, ← succ_le_iff, le_div omega0_ne_zero, mul_succ,
add_le_of_limit isLimit_omega0]
intro b hb
rcases lt_omega0.1 hb with ⟨n, rfl⟩
exact
(add_le_add_right (mul_div_le _ _) _).trans
(lt_sub.1 <| nat_lt_limit (isLimit_sub l hx) _).le
· rcases h with ⟨a0, b, rfl⟩
refine isLimit_mul_left isLimit_omega0 (Ordinal.pos_iff_ne_zero.2 <| mt ?_ a0)
intro e
simp only [e, mul_zero]
@[simp]
theorem natCast_mod_omega0 (n : ℕ) : n % ω = n :=
mod_eq_of_lt (nat_lt_omega0 n)
end Ordinal
namespace Cardinal
open Ordinal
@[simp]
theorem add_one_of_aleph0_le {c} (h : ℵ₀ ≤ c) : c + 1 = c := by
rw [add_comm, ← card_ord c, ← card_one, ← card_add, one_add_of_omega0_le]
rwa [← ord_aleph0, ord_le_ord]
theorem isLimit_ord {c} (co : ℵ₀ ≤ c) : (ord c).IsLimit := by
rw [isLimit_iff, isSuccPrelimit_iff_succ_lt]
refine ⟨fun h => aleph0_ne_zero ?_, fun a => lt_imp_lt_of_le_imp_le fun h => ?_⟩
· rw [← Ordinal.le_zero, ord_le] at h
simpa only [card_zero, nonpos_iff_eq_zero] using co.trans h
· rw [ord_le] at h ⊢
rwa [← @add_one_of_aleph0_le (card a), ← card_succ]
rw [← ord_le, ← le_succ_of_isLimit, ord_le]
· exact co.trans h
· rw [ord_aleph0]
exact Ordinal.isLimit_omega0
theorem noMaxOrder {c} (h : ℵ₀ ≤ c) : NoMaxOrder c.ord.toType :=
toType_noMax_of_succ_lt fun _ ↦ (isLimit_ord h).succ_lt
end Cardinal
| Mathlib/SetTheory/Ordinal/Arithmetic.lean | 2,048 | 2,053 | |
/-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.Algebra.DualNumber
import Mathlib.Algebra.QuaternionBasis
import Mathlib.Data.Complex.Module
import Mathlib.LinearAlgebra.CliffordAlgebra.Conjugation
import Mathlib.LinearAlgebra.CliffordAlgebra.Star
import Mathlib.LinearAlgebra.QuadraticForm.Prod
/-!
# Other constructions isomorphic to Clifford Algebras
This file contains isomorphisms showing that other types are equivalent to some `CliffordAlgebra`.
## Rings
* `CliffordAlgebraRing.equiv`: any ring is equivalent to a `CliffordAlgebra` over a
zero-dimensional vector space.
## Complex numbers
* `CliffordAlgebraComplex.equiv`: the `Complex` numbers are equivalent as an `ℝ`-algebra to a
`CliffordAlgebra` over a one-dimensional vector space with a quadratic form that satisfies
`Q (ι Q 1) = -1`.
* `CliffordAlgebraComplex.toComplex`: the forward direction of this equiv
* `CliffordAlgebraComplex.ofComplex`: the reverse direction of this equiv
We show additionally that this equivalence sends `Complex.conj` to `CliffordAlgebra.involute` and
vice-versa:
* `CliffordAlgebraComplex.toComplex_involute`
* `CliffordAlgebraComplex.ofComplex_conj`
Note that in this algebra `CliffordAlgebra.reverse` is the identity and so the clifford conjugate
is the same as `CliffordAlgebra.involute`.
## Quaternion algebras
* `CliffordAlgebraQuaternion.equiv`: a `QuaternionAlgebra` over `R` is equivalent as an
`R`-algebra to a clifford algebra over `R × R`, sending `i` to `(0, 1)` and `j` to `(1, 0)`.
* `CliffordAlgebraQuaternion.toQuaternion`: the forward direction of this equiv
* `CliffordAlgebraQuaternion.ofQuaternion`: the reverse direction of this equiv
We show additionally that this equivalence sends `QuaternionAlgebra.conj` to the clifford conjugate
and vice-versa:
* `CliffordAlgebraQuaternion.toQuaternion_star`
* `CliffordAlgebraQuaternion.ofQuaternion_star`
## Dual numbers
* `CliffordAlgebraDualNumber.equiv`: `R[ε]` is equivalent as an `R`-algebra to a clifford
algebra over `R` where `Q = 0`.
-/
open CliffordAlgebra
/-! ### The clifford algebra isomorphic to a ring -/
namespace CliffordAlgebraRing
open scoped ComplexConjugate
variable {R : Type*} [CommRing R]
@[simp]
theorem ι_eq_zero : ι (0 : QuadraticForm R Unit) = 0 :=
Subsingleton.elim _ _
/-- Since the vector space is empty the ring is commutative. -/
instance : CommRing (CliffordAlgebra (0 : QuadraticForm R Unit)) :=
{ CliffordAlgebra.instRing _ with
mul_comm := fun x y => by
induction x using CliffordAlgebra.induction with
| algebraMap r => apply Algebra.commutes
| ι x => simp
| add x₁ x₂ hx₁ hx₂ => rw [mul_add, add_mul, hx₁, hx₂]
| mul x₁ x₂ hx₁ hx₂ => rw [mul_assoc, hx₂, ← mul_assoc, hx₁, ← mul_assoc] }
theorem reverse_apply (x : CliffordAlgebra (0 : QuadraticForm R Unit)) :
x.reverse = x := by
induction x using CliffordAlgebra.induction with
| algebraMap r => exact reverse.commutes _
| ι x => rw [ι_eq_zero, LinearMap.zero_apply, reverse.map_zero]
| mul x₁ x₂ hx₁ hx₂ => rw [reverse.map_mul, mul_comm, hx₁, hx₂]
| add x₁ x₂ hx₁ hx₂ => rw [reverse.map_add, hx₁, hx₂]
@[simp]
theorem reverse_eq_id :
(reverse : CliffordAlgebra (0 : QuadraticForm R Unit) →ₗ[R] _) = LinearMap.id :=
LinearMap.ext reverse_apply
@[simp]
theorem involute_eq_id :
(involute : CliffordAlgebra (0 : QuadraticForm R Unit) →ₐ[R] _) = AlgHom.id R _ := by ext; simp
/-- The clifford algebra over a 0-dimensional vector space is isomorphic to its scalars. -/
protected def equiv : CliffordAlgebra (0 : QuadraticForm R Unit) ≃ₐ[R] R :=
AlgEquiv.ofAlgHom
(CliffordAlgebra.lift (0 : QuadraticForm R Unit) <|
⟨0, fun _ : Unit => (zero_mul (0 : R)).trans (algebraMap R _).map_zero.symm⟩)
(Algebra.ofId R _) (by ext)
(by ext : 1; rw [ι_eq_zero, LinearMap.comp_zero, LinearMap.comp_zero])
end CliffordAlgebraRing
/-! ### The clifford algebra isomorphic to the complex numbers -/
namespace CliffordAlgebraComplex
open scoped ComplexConjugate
/-- The quadratic form sending elements to the negation of their square. -/
def Q : QuadraticForm ℝ ℝ :=
-QuadraticMap.sq
@[simp]
theorem Q_apply (r : ℝ) : Q r = -(r * r) :=
rfl
/-- Intermediate result for `CliffordAlgebraComplex.equiv`: clifford algebras over
`CliffordAlgebraComplex.Q` above can be converted to `ℂ`. -/
def toComplex : CliffordAlgebra Q →ₐ[ℝ] ℂ :=
CliffordAlgebra.lift Q
⟨LinearMap.toSpanSingleton _ _ Complex.I, fun r => by
dsimp [LinearMap.toSpanSingleton, LinearMap.id]
rw [mul_mul_mul_comm]
simp⟩
@[simp]
theorem toComplex_ι (r : ℝ) : toComplex (ι Q r) = r • Complex.I :=
CliffordAlgebra.lift_ι_apply _ _ r
/-- `CliffordAlgebra.involute` is analogous to `Complex.conj`. -/
@[simp]
theorem toComplex_involute (c : CliffordAlgebra Q) :
toComplex (involute c) = conj (toComplex c) := by
have : toComplex (involute (ι Q 1)) = conj (toComplex (ι Q 1)) := by
simp only [involute_ι, toComplex_ι, map_neg, one_smul, Complex.conj_I]
suffices toComplex.comp involute = Complex.conjAe.toAlgHom.comp toComplex by
exact AlgHom.congr_fun this c
ext : 2
exact this
/-- Intermediate result for `CliffordAlgebraComplex.equiv`: `ℂ` can be converted to
`CliffordAlgebraComplex.Q` above can be converted to. -/
def ofComplex : ℂ →ₐ[ℝ] CliffordAlgebra Q :=
Complex.lift
⟨CliffordAlgebra.ι Q 1, by
rw [CliffordAlgebra.ι_sq_scalar, Q_apply, one_mul, RingHom.map_neg, RingHom.map_one]⟩
@[simp]
theorem ofComplex_I : ofComplex Complex.I = ι Q 1 :=
Complex.liftAux_apply_I _ (by simp)
@[simp]
theorem toComplex_comp_ofComplex : toComplex.comp ofComplex = AlgHom.id ℝ ℂ := by
ext1
dsimp only [AlgHom.comp_apply, Subtype.coe_mk, AlgHom.id_apply]
rw [ofComplex_I, toComplex_ι, one_smul]
@[simp]
theorem toComplex_ofComplex (c : ℂ) : toComplex (ofComplex c) = c :=
AlgHom.congr_fun toComplex_comp_ofComplex c
@[simp]
theorem ofComplex_comp_toComplex : ofComplex.comp toComplex = AlgHom.id ℝ (CliffordAlgebra Q) := by
ext
dsimp only [LinearMap.comp_apply, Subtype.coe_mk, AlgHom.id_apply, AlgHom.toLinearMap_apply,
AlgHom.comp_apply]
rw [toComplex_ι, one_smul, ofComplex_I]
@[simp]
theorem ofComplex_toComplex (c : CliffordAlgebra Q) : ofComplex (toComplex c) = c :=
AlgHom.congr_fun ofComplex_comp_toComplex c
/-- The clifford algebras over `CliffordAlgebraComplex.Q` is isomorphic as an `ℝ`-algebra to `ℂ`. -/
@[simps!]
protected def equiv : CliffordAlgebra Q ≃ₐ[ℝ] ℂ :=
AlgEquiv.ofAlgHom toComplex ofComplex toComplex_comp_ofComplex ofComplex_comp_toComplex
/-- The clifford algebra is commutative since it is isomorphic to the complex numbers.
TODO: prove this is true for all `CliffordAlgebra`s over a 1-dimensional vector space. -/
instance : CommRing (CliffordAlgebra Q) :=
{ CliffordAlgebra.instRing _ with
| mul_comm := fun x y =>
CliffordAlgebraComplex.equiv.injective <| by
rw [map_mul, mul_comm, map_mul] }
/-- `reverse` is a no-op over `CliffordAlgebraComplex.Q`. -/
| Mathlib/LinearAlgebra/CliffordAlgebra/Equivs.lean | 194 | 198 |
/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Sébastien Gouëzel, Heather Macbeth
-/
import Mathlib.Analysis.InnerProductSpace.Projection
import Mathlib.Analysis.Normed.Lp.PiLp
import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas
import Mathlib.LinearAlgebra.UnitaryGroup
import Mathlib.Util.Superscript
/-!
# `L²` inner product space structure on finite products of inner product spaces
The `L²` norm on a finite product of inner product spaces is compatible with an inner product
$$
\langle x, y\rangle = \sum \langle x_i, y_i \rangle.
$$
This is recorded in this file as an inner product space instance on `PiLp 2`.
This file develops the notion of a finite dimensional Hilbert space over `𝕜 = ℂ, ℝ`, referred to as
`E`. We define an `OrthonormalBasis 𝕜 ι E` as a linear isometric equivalence
between `E` and `EuclideanSpace 𝕜 ι`. Then `stdOrthonormalBasis` shows that such an equivalence
always exists if `E` is finite dimensional. We provide language for converting between a basis
that is orthonormal and an orthonormal basis (e.g. `Basis.toOrthonormalBasis`). We show that
orthonormal bases for each summand in a direct sum of spaces can be combined into an orthonormal
basis for the whole sum in `DirectSum.IsInternal.subordinateOrthonormalBasis`. In
the last section, various properties of matrices are explored.
## Main definitions
- `EuclideanSpace 𝕜 n`: defined to be `PiLp 2 (n → 𝕜)` for any `Fintype n`, i.e., the space
from functions to `n` to `𝕜` with the `L²` norm. We register several instances on it (notably
that it is a finite-dimensional inner product space), and provide a `!ₚ[]` notation (for numeric
subscripts like `₂`) for the case when the indexing type is `Fin n`.
- `OrthonormalBasis 𝕜 ι`: defined to be an isometry to Euclidean space from a given
finite-dimensional inner product space, `E ≃ₗᵢ[𝕜] EuclideanSpace 𝕜 ι`.
- `Basis.toOrthonormalBasis`: constructs an `OrthonormalBasis` for a finite-dimensional
Euclidean space from a `Basis` which is `Orthonormal`.
- `Orthonormal.exists_orthonormalBasis_extension`: provides an existential result of an
`OrthonormalBasis` extending a given orthonormal set
- `exists_orthonormalBasis`: provides an orthonormal basis on a finite dimensional vector space
- `stdOrthonormalBasis`: provides an arbitrarily-chosen `OrthonormalBasis` of a given finite
dimensional inner product space
For consequences in infinite dimension (Hilbert bases, etc.), see the file
`Analysis.InnerProductSpace.L2Space`.
-/
open Real Set Filter RCLike Submodule Function Uniformity Topology NNReal ENNReal
ComplexConjugate DirectSum
noncomputable section
variable {ι ι' 𝕜 : Type*} [RCLike 𝕜]
variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace 𝕜 E]
variable {F : Type*} [NormedAddCommGroup F] [InnerProductSpace ℝ F]
variable {F' : Type*} [NormedAddCommGroup F'] [InnerProductSpace ℝ F']
local notation "⟪" x ", " y "⟫" => @inner 𝕜 _ _ x y
/-
If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space,
then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm,
we use instead `PiLp 2 f` for the product space, which is endowed with the `L^2` norm.
-/
instance PiLp.innerProductSpace {ι : Type*} [Fintype ι] (f : ι → Type*)
[∀ i, NormedAddCommGroup (f i)] [∀ i, InnerProductSpace 𝕜 (f i)] :
InnerProductSpace 𝕜 (PiLp 2 f) where
inner x y := ∑ i, inner (x i) (y i)
norm_sq_eq_re_inner x := by
simp only [PiLp.norm_sq_eq_of_L2, map_sum, ← norm_sq_eq_re_inner, one_div]
conj_inner_symm := by
intro x y
unfold inner
rw [map_sum]
apply Finset.sum_congr rfl
rintro z -
apply inner_conj_symm
add_left x y z :=
show (∑ i, inner (x i + y i) (z i)) = (∑ i, inner (x i) (z i)) + ∑ i, inner (y i) (z i) by
simp only [inner_add_left, Finset.sum_add_distrib]
smul_left x y r :=
show (∑ i : ι, inner (r • x i) (y i)) = conj r * ∑ i, inner (x i) (y i) by
simp only [Finset.mul_sum, inner_smul_left]
@[simp]
theorem PiLp.inner_apply {ι : Type*} [Fintype ι] {f : ι → Type*} [∀ i, NormedAddCommGroup (f i)]
[∀ i, InnerProductSpace 𝕜 (f i)] (x y : PiLp 2 f) : ⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ :=
rfl
/-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional
space use `EuclideanSpace 𝕜 (Fin n)`.
For the case when `n = Fin _`, there is `!₂[x, y, ...]` notation for building elements of this type,
analogous to `![x, y, ...]` notation. -/
abbrev EuclideanSpace (𝕜 : Type*) (n : Type*) : Type _ :=
PiLp 2 fun _ : n => 𝕜
section Notation
open Lean Meta Elab Term Macro TSyntax PrettyPrinter.Delaborator SubExpr
open Mathlib.Tactic (subscriptTerm)
/-- Notation for vectors in Lp space. `!₂[x, y, ...]` is a shorthand for
`(WithLp.equiv 2 _ _).symm ![x, y, ...]`, of type `EuclideanSpace _ (Fin _)`.
This also works for other subscripts. -/
syntax (name := PiLp.vecNotation) "!" noWs subscriptTerm noWs "[" term,* "]" : term
macro_rules | `(!$p:subscript[$e:term,*]) => do
-- override the `Fin n.succ` to a literal
let n := e.getElems.size
`((WithLp.equiv $p <| ∀ _ : Fin $(quote n), _).symm ![$e,*])
/-- Unexpander for the `!₂[x, y, ...]` notation. -/
@[app_delab DFunLike.coe]
def EuclideanSpace.delabVecNotation : Delab :=
whenNotPPOption getPPExplicit <| whenPPOption getPPNotation <| withOverApp 6 do
-- check that the `(WithLp.equiv _ _).symm` is present
let p : Term ← withAppFn <| withAppArg do
let_expr Equiv.symm _ _ e := ← getExpr | failure
let_expr WithLp.equiv _ _ := e | failure
withNaryArg 2 <| withNaryArg 0 <| delab
-- to be conservative, only allow subscripts which are numerals
guard <| p matches `($_:num)
let `(![$elems,*]) := ← withAppArg delab | failure
`(!$p[$elems,*])
end Notation
theorem EuclideanSpace.nnnorm_eq {𝕜 : Type*} [RCLike 𝕜] {n : Type*} [Fintype n]
(x : EuclideanSpace 𝕜 n) : ‖x‖₊ = NNReal.sqrt (∑ i, ‖x i‖₊ ^ 2) :=
PiLp.nnnorm_eq_of_L2 x
theorem EuclideanSpace.norm_eq {𝕜 : Type*} [RCLike 𝕜] {n : Type*} [Fintype n]
(x : EuclideanSpace 𝕜 n) : ‖x‖ = √(∑ i, ‖x i‖ ^ 2) := by
simpa only [Real.coe_sqrt, NNReal.coe_sum] using congr_arg ((↑) : ℝ≥0 → ℝ) x.nnnorm_eq
theorem EuclideanSpace.dist_eq {𝕜 : Type*} [RCLike 𝕜] {n : Type*} [Fintype n]
(x y : EuclideanSpace 𝕜 n) : dist x y = √(∑ i, dist (x i) (y i) ^ 2) :=
PiLp.dist_eq_of_L2 x y
theorem EuclideanSpace.nndist_eq {𝕜 : Type*} [RCLike 𝕜] {n : Type*} [Fintype n]
(x y : EuclideanSpace 𝕜 n) : nndist x y = NNReal.sqrt (∑ i, nndist (x i) (y i) ^ 2) :=
PiLp.nndist_eq_of_L2 x y
theorem EuclideanSpace.edist_eq {𝕜 : Type*} [RCLike 𝕜] {n : Type*} [Fintype n]
(x y : EuclideanSpace 𝕜 n) : edist x y = (∑ i, edist (x i) (y i) ^ 2) ^ (1 / 2 : ℝ) :=
PiLp.edist_eq_of_L2 x y
theorem EuclideanSpace.ball_zero_eq {n : Type*} [Fintype n] (r : ℝ) (hr : 0 ≤ r) :
Metric.ball (0 : EuclideanSpace ℝ n) r = {x | ∑ i, x i ^ 2 < r ^ 2} := by
ext x
have : (0 : ℝ) ≤ ∑ i, x i ^ 2 := Finset.sum_nonneg fun _ _ => sq_nonneg _
simp_rw [mem_setOf, mem_ball_zero_iff, norm_eq, norm_eq_abs, sq_abs, sqrt_lt this hr]
theorem EuclideanSpace.closedBall_zero_eq {n : Type*} [Fintype n] (r : ℝ) (hr : 0 ≤ r) :
Metric.closedBall (0 : EuclideanSpace ℝ n) r = {x | ∑ i, x i ^ 2 ≤ r ^ 2} := by
ext
simp_rw [mem_setOf, mem_closedBall_zero_iff, norm_eq, norm_eq_abs, sq_abs, sqrt_le_left hr]
theorem EuclideanSpace.sphere_zero_eq {n : Type*} [Fintype n] (r : ℝ) (hr : 0 ≤ r) :
Metric.sphere (0 : EuclideanSpace ℝ n) r = {x | ∑ i, x i ^ 2 = r ^ 2} := by
ext x
have : (0 : ℝ) ≤ ∑ i, x i ^ 2 := Finset.sum_nonneg fun _ _ => sq_nonneg _
simp_rw [mem_setOf, mem_sphere_zero_iff_norm, norm_eq, norm_eq_abs, sq_abs,
Real.sqrt_eq_iff_eq_sq this hr]
section
variable [Fintype ι]
@[simp]
theorem finrank_euclideanSpace :
Module.finrank 𝕜 (EuclideanSpace 𝕜 ι) = Fintype.card ι := by
simp [EuclideanSpace, PiLp, WithLp]
theorem finrank_euclideanSpace_fin {n : ℕ} :
Module.finrank 𝕜 (EuclideanSpace 𝕜 (Fin n)) = n := by simp
theorem EuclideanSpace.inner_eq_star_dotProduct (x y : EuclideanSpace 𝕜 ι) :
⟪x, y⟫ = dotProduct (WithLp.equiv _ _ y) (star <| WithLp.equiv _ _ x) :=
rfl
theorem EuclideanSpace.inner_piLp_equiv_symm (x y : ι → 𝕜) :
⟪(WithLp.equiv 2 _).symm x, (WithLp.equiv 2 _).symm y⟫ = dotProduct y (star x) :=
rfl
/-- A finite, mutually orthogonal family of subspaces of `E`, which span `E`, induce an isometry
from `E` to `PiLp 2` of the subspaces equipped with the `L2` inner product. -/
def DirectSum.IsInternal.isometryL2OfOrthogonalFamily [DecidableEq ι] {V : ι → Submodule 𝕜 E}
(hV : DirectSum.IsInternal V)
(hV' : OrthogonalFamily 𝕜 (fun i => V i) fun i => (V i).subtypeₗᵢ) :
E ≃ₗᵢ[𝕜] PiLp 2 fun i => V i := by
let e₁ := DirectSum.linearEquivFunOnFintype 𝕜 ι fun i => V i
let e₂ := LinearEquiv.ofBijective (DirectSum.coeLinearMap V) hV
refine LinearEquiv.isometryOfInner (e₂.symm.trans e₁) ?_
suffices ∀ (v w : PiLp 2 fun i => V i), ⟪v, w⟫ = ⟪e₂ (e₁.symm v), e₂ (e₁.symm w)⟫ by
intro v₀ w₀
convert this (e₁ (e₂.symm v₀)) (e₁ (e₂.symm w₀)) <;>
simp only [LinearEquiv.symm_apply_apply, LinearEquiv.apply_symm_apply]
intro v w
trans ⟪∑ i, (V i).subtypeₗᵢ (v i), ∑ i, (V i).subtypeₗᵢ (w i)⟫
· simp only [sum_inner, hV'.inner_right_fintype, PiLp.inner_apply]
· congr <;> simp
@[simp]
theorem DirectSum.IsInternal.isometryL2OfOrthogonalFamily_symm_apply [DecidableEq ι]
{V : ι → Submodule 𝕜 E} (hV : DirectSum.IsInternal V)
(hV' : OrthogonalFamily 𝕜 (fun i => V i) fun i => (V i).subtypeₗᵢ) (w : PiLp 2 fun i => V i) :
(hV.isometryL2OfOrthogonalFamily hV').symm w = ∑ i, (w i : E) := by
classical
let e₁ := DirectSum.linearEquivFunOnFintype 𝕜 ι fun i => V i
let e₂ := LinearEquiv.ofBijective (DirectSum.coeLinearMap V) hV
suffices ∀ v : ⨁ i, V i, e₂ v = ∑ i, e₁ v i by exact this (e₁.symm w)
intro v
simp [e₁, e₂, DirectSum.coeLinearMap, DirectSum.toModule, DFinsupp.lsum,
DFinsupp.sumAddHom_apply]
end
variable (ι 𝕜)
/-- A shorthand for `PiLp.continuousLinearEquiv`. -/
abbrev EuclideanSpace.equiv : EuclideanSpace 𝕜 ι ≃L[𝕜] ι → 𝕜 :=
PiLp.continuousLinearEquiv 2 𝕜 _
variable {ι 𝕜}
/-- The projection on the `i`-th coordinate of `EuclideanSpace 𝕜 ι`, as a linear map. -/
abbrev EuclideanSpace.projₗ (i : ι) : EuclideanSpace 𝕜 ι →ₗ[𝕜] 𝕜 := PiLp.projₗ _ _ i
/-- The projection on the `i`-th coordinate of `EuclideanSpace 𝕜 ι`, as a continuous linear map. -/
abbrev EuclideanSpace.proj (i : ι) : EuclideanSpace 𝕜 ι →L[𝕜] 𝕜 := PiLp.proj _ _ i
section DecEq
variable [DecidableEq ι]
-- TODO : This should be generalized to `PiLp`.
/-- The vector given in euclidean space by being `a : 𝕜` at coordinate `i : ι` and `0 : 𝕜` at
all other coordinates. -/
def EuclideanSpace.single (i : ι) (a : 𝕜) : EuclideanSpace 𝕜 ι :=
(WithLp.equiv _ _).symm (Pi.single i a)
@[simp]
theorem WithLp.equiv_single (i : ι) (a : 𝕜) :
WithLp.equiv _ _ (EuclideanSpace.single i a) = Pi.single i a :=
rfl
@[simp]
theorem WithLp.equiv_symm_single (i : ι) (a : 𝕜) :
(WithLp.equiv _ _).symm (Pi.single i a) = EuclideanSpace.single i a :=
rfl
@[simp]
theorem EuclideanSpace.single_apply (i : ι) (a : 𝕜) (j : ι) :
(EuclideanSpace.single i a) j = ite (j = i) a 0 := by
rw [EuclideanSpace.single, WithLp.equiv_symm_pi_apply, ← Pi.single_apply i a j]
variable [Fintype ι]
theorem EuclideanSpace.inner_single_left (i : ι) (a : 𝕜) (v : EuclideanSpace 𝕜 ι) :
⟪EuclideanSpace.single i (a : 𝕜), v⟫ = conj a * v i := by simp [apply_ite conj, mul_comm]
theorem EuclideanSpace.inner_single_right (i : ι) (a : 𝕜) (v : EuclideanSpace 𝕜 ι) :
⟪v, EuclideanSpace.single i (a : 𝕜)⟫ = a * conj (v i) := by simp [apply_ite conj]
@[simp]
theorem EuclideanSpace.norm_single (i : ι) (a : 𝕜) :
‖EuclideanSpace.single i (a : 𝕜)‖ = ‖a‖ :=
PiLp.norm_equiv_symm_single 2 (fun _ => 𝕜) i a
@[simp]
theorem EuclideanSpace.nnnorm_single (i : ι) (a : 𝕜) :
‖EuclideanSpace.single i (a : 𝕜)‖₊ = ‖a‖₊ :=
PiLp.nnnorm_equiv_symm_single 2 (fun _ => 𝕜) i a
@[simp]
theorem EuclideanSpace.dist_single_same (i : ι) (a b : 𝕜) :
dist (EuclideanSpace.single i (a : 𝕜)) (EuclideanSpace.single i (b : 𝕜)) = dist a b :=
PiLp.dist_equiv_symm_single_same 2 (fun _ => 𝕜) i a b
@[simp]
theorem EuclideanSpace.nndist_single_same (i : ι) (a b : 𝕜) :
nndist (EuclideanSpace.single i (a : 𝕜)) (EuclideanSpace.single i (b : 𝕜)) = nndist a b :=
PiLp.nndist_equiv_symm_single_same 2 (fun _ => 𝕜) i a b
@[simp]
theorem EuclideanSpace.edist_single_same (i : ι) (a b : 𝕜) :
edist (EuclideanSpace.single i (a : 𝕜)) (EuclideanSpace.single i (b : 𝕜)) = edist a b :=
PiLp.edist_equiv_symm_single_same 2 (fun _ => 𝕜) i a b
/-- `EuclideanSpace.single` forms an orthonormal family. -/
theorem EuclideanSpace.orthonormal_single :
Orthonormal 𝕜 fun i : ι => EuclideanSpace.single i (1 : 𝕜) := by
simp_rw [orthonormal_iff_ite, EuclideanSpace.inner_single_left, map_one, one_mul,
EuclideanSpace.single_apply]
intros
trivial
theorem EuclideanSpace.piLpCongrLeft_single
{ι' : Type*} [Fintype ι'] [DecidableEq ι'] (e : ι' ≃ ι) (i' : ι') (v : 𝕜) :
LinearIsometryEquiv.piLpCongrLeft 2 𝕜 𝕜 e (EuclideanSpace.single i' v) =
EuclideanSpace.single (e i') v :=
LinearIsometryEquiv.piLpCongrLeft_single e i' _
end DecEq
variable (ι 𝕜 E)
variable [Fintype ι]
/-- An orthonormal basis on E is an identification of `E` with its dimensional-matching
`EuclideanSpace 𝕜 ι`. -/
structure OrthonormalBasis where ofRepr ::
/-- Linear isometry between `E` and `EuclideanSpace 𝕜 ι` representing the orthonormal basis. -/
repr : E ≃ₗᵢ[𝕜] EuclideanSpace 𝕜 ι
variable {ι 𝕜 E}
namespace OrthonormalBasis
theorem repr_injective :
Injective (repr : OrthonormalBasis ι 𝕜 E → E ≃ₗᵢ[𝕜] EuclideanSpace 𝕜 ι) := fun f g h => by
cases f
cases g
congr
/-- `b i` is the `i`th basis vector. -/
instance instFunLike : FunLike (OrthonormalBasis ι 𝕜 E) ι E where
coe b i := by classical exact b.repr.symm (EuclideanSpace.single i (1 : 𝕜))
coe_injective' b b' h := repr_injective <| LinearIsometryEquiv.toLinearEquiv_injective <|
LinearEquiv.symm_bijective.injective <| LinearEquiv.toLinearMap_injective <| by
classical
rw [← LinearMap.cancel_right (WithLp.linearEquiv 2 𝕜 (_ → 𝕜)).symm.surjective]
simp only [LinearIsometryEquiv.toLinearEquiv_symm]
refine LinearMap.pi_ext fun i k => ?_
have : k = k • (1 : 𝕜) := by rw [smul_eq_mul, mul_one]
rw [this, Pi.single_smul]
replace h := congr_fun h i
simp only [LinearEquiv.comp_coe, map_smul, LinearEquiv.coe_coe,
LinearEquiv.trans_apply, WithLp.linearEquiv_symm_apply, WithLp.equiv_symm_single,
LinearIsometryEquiv.coe_toLinearEquiv] at h ⊢
rw [h]
@[simp]
theorem coe_ofRepr [DecidableEq ι] (e : E ≃ₗᵢ[𝕜] EuclideanSpace 𝕜 ι) :
⇑(OrthonormalBasis.ofRepr e) = fun i => e.symm (EuclideanSpace.single i (1 : 𝕜)) := by
dsimp only [DFunLike.coe]
funext
congr!
@[simp]
protected theorem repr_symm_single [DecidableEq ι] (b : OrthonormalBasis ι 𝕜 E) (i : ι) :
b.repr.symm (EuclideanSpace.single i (1 : 𝕜)) = b i := by
dsimp only [DFunLike.coe]
congr!
@[simp]
protected theorem repr_self [DecidableEq ι] (b : OrthonormalBasis ι 𝕜 E) (i : ι) :
b.repr (b i) = EuclideanSpace.single i (1 : 𝕜) := by
rw [← b.repr_symm_single i, LinearIsometryEquiv.apply_symm_apply]
protected theorem repr_apply_apply (b : OrthonormalBasis ι 𝕜 E) (v : E) (i : ι) :
b.repr v i = ⟪b i, v⟫ := by
classical
rw [← b.repr.inner_map_map (b i) v, b.repr_self i, EuclideanSpace.inner_single_left]
simp only [one_mul, eq_self_iff_true, map_one]
@[simp]
protected theorem orthonormal (b : OrthonormalBasis ι 𝕜 E) : Orthonormal 𝕜 b := by
classical
rw [orthonormal_iff_ite]
intro i j
rw [← b.repr.inner_map_map (b i) (b j), b.repr_self i, b.repr_self j,
EuclideanSpace.inner_single_left, EuclideanSpace.single_apply, map_one, one_mul]
@[simp]
lemma norm_eq_one (b : OrthonormalBasis ι 𝕜 E) (i : ι) :
‖b i‖ = 1 := b.orthonormal.norm_eq_one i
@[simp]
lemma nnnorm_eq_one (b : OrthonormalBasis ι 𝕜 E) (i : ι) :
‖b i‖₊ = 1 := b.orthonormal.nnnorm_eq_one i
@[simp]
lemma enorm_eq_one (b : OrthonormalBasis ι 𝕜 E) (i : ι) :
‖b i‖ₑ = 1 := b.orthonormal.enorm_eq_one i
@[simp]
lemma inner_eq_zero (b : OrthonormalBasis ι 𝕜 E) {i j : ι} (hij : i ≠ j) :
⟪b i, b j⟫ = 0 := b.orthonormal.inner_eq_zero hij
/-- The `Basis ι 𝕜 E` underlying the `OrthonormalBasis` -/
protected def toBasis (b : OrthonormalBasis ι 𝕜 E) : Basis ι 𝕜 E :=
Basis.ofEquivFun b.repr.toLinearEquiv
@[simp]
protected theorem coe_toBasis (b : OrthonormalBasis ι 𝕜 E) : (⇑b.toBasis : ι → E) = ⇑b := rfl
@[simp]
protected theorem coe_toBasis_repr (b : OrthonormalBasis ι 𝕜 E) :
b.toBasis.equivFun = b.repr.toLinearEquiv :=
Basis.equivFun_ofEquivFun _
@[simp]
protected theorem coe_toBasis_repr_apply (b : OrthonormalBasis ι 𝕜 E) (x : E) (i : ι) :
b.toBasis.repr x i = b.repr x i := by
rw [← Basis.equivFun_apply, OrthonormalBasis.coe_toBasis_repr]
-- This used to be `rw`, but we need `erw` after https://github.com/leanprover/lean4/pull/2644
erw [LinearIsometryEquiv.coe_toLinearEquiv]
protected theorem sum_repr (b : OrthonormalBasis ι 𝕜 E) (x : E) : ∑ i, b.repr x i • b i = x := by
simp_rw [← b.coe_toBasis_repr_apply, ← b.coe_toBasis]
exact b.toBasis.sum_repr x
open scoped InnerProductSpace in
protected theorem sum_repr' (b : OrthonormalBasis ι 𝕜 E) (x : E) : ∑ i, ⟪b i, x⟫_𝕜 • b i = x := by
nth_rw 2 [← (b.sum_repr x)]
simp_rw [b.repr_apply_apply x]
protected theorem sum_repr_symm (b : OrthonormalBasis ι 𝕜 E) (v : EuclideanSpace 𝕜 ι) :
∑ i, v i • b i = b.repr.symm v := by simpa using (b.toBasis.equivFun_symm_apply v).symm
protected theorem sum_inner_mul_inner (b : OrthonormalBasis ι 𝕜 E) (x y : E) :
∑ i, ⟪x, b i⟫ * ⟪b i, y⟫ = ⟪x, y⟫ := by
have := congr_arg (innerSL 𝕜 x) (b.sum_repr y)
rw [map_sum] at this
convert this
rw [map_smul, b.repr_apply_apply, mul_comm]
simp
lemma sum_sq_norm_inner (b : OrthonormalBasis ι 𝕜 E) (x : E) :
∑ i, ‖⟪b i, x⟫‖ ^ 2 = ‖x‖ ^ 2 := by
rw [@norm_eq_sqrt_re_inner 𝕜, ← OrthonormalBasis.sum_inner_mul_inner b x x, map_sum]
simp_rw [inner_mul_symm_re_eq_norm, norm_mul, ← inner_conj_symm x, starRingEnd_apply,
norm_star, ← pow_two]
rw [Real.sq_sqrt]
exact Fintype.sum_nonneg fun _ ↦ by positivity
lemma norm_le_card_mul_iSup_norm_inner (b : OrthonormalBasis ι 𝕜 E) (x : E) :
‖x‖ ≤ √(Fintype.card ι) * ⨆ i, ‖⟪b i, x⟫‖ := by
calc ‖x‖
_ = √(∑ i, ‖⟪b i, x⟫‖ ^ 2) := by rw [sum_sq_norm_inner, Real.sqrt_sq (by positivity)]
_ ≤ √(∑ _ : ι, (⨆ j, ‖⟪b j, x⟫‖) ^ 2) := by
gcongr with i
exact le_ciSup (f := fun j ↦ ‖⟪b j, x⟫‖) (by simp) i
_ = √(Fintype.card ι) * ⨆ i, ‖⟪b i, x⟫‖ := by
simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, Nat.cast_nonneg, Real.sqrt_mul]
congr
rw [Real.sqrt_sq]
cases isEmpty_or_nonempty ι
· simp
· exact le_ciSup_of_le (by simp) (Nonempty.some inferInstance) (by positivity)
protected theorem orthogonalProjection_eq_sum {U : Submodule 𝕜 E} [CompleteSpace U]
(b : OrthonormalBasis ι 𝕜 U) (x : E) :
U.orthogonalProjection x = ∑ i, ⟪(b i : E), x⟫ • b i := by
simpa only [b.repr_apply_apply, inner_orthogonalProjection_eq_of_mem_left] using
(b.sum_repr (U.orthogonalProjection x)).symm
/-- Mapping an orthonormal basis along a `LinearIsometryEquiv`. -/
protected def map {G : Type*} [NormedAddCommGroup G] [InnerProductSpace 𝕜 G]
(b : OrthonormalBasis ι 𝕜 E) (L : E ≃ₗᵢ[𝕜] G) : OrthonormalBasis ι 𝕜 G where
repr := L.symm.trans b.repr
@[simp]
protected theorem map_apply {G : Type*} [NormedAddCommGroup G] [InnerProductSpace 𝕜 G]
(b : OrthonormalBasis ι 𝕜 E) (L : E ≃ₗᵢ[𝕜] G) (i : ι) : b.map L i = L (b i) :=
rfl
@[simp]
protected theorem toBasis_map {G : Type*} [NormedAddCommGroup G] [InnerProductSpace 𝕜 G]
(b : OrthonormalBasis ι 𝕜 E) (L : E ≃ₗᵢ[𝕜] G) :
(b.map L).toBasis = b.toBasis.map L.toLinearEquiv :=
rfl
/-- A basis that is orthonormal is an orthonormal basis. -/
def _root_.Basis.toOrthonormalBasis (v : Basis ι 𝕜 E) (hv : Orthonormal 𝕜 v) :
OrthonormalBasis ι 𝕜 E :=
OrthonormalBasis.ofRepr <|
LinearEquiv.isometryOfInner v.equivFun
(by
intro x y
let p : EuclideanSpace 𝕜 ι := v.equivFun x
let q : EuclideanSpace 𝕜 ι := v.equivFun y
have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫ := by
simp [inner_sum, inner_smul_right, hv.inner_left_fintype]
convert key
· rw [← v.equivFun.symm_apply_apply x, v.equivFun_symm_apply]
· rw [← v.equivFun.symm_apply_apply y, v.equivFun_symm_apply])
@[simp]
theorem _root_.Basis.coe_toOrthonormalBasis_repr (v : Basis ι 𝕜 E) (hv : Orthonormal 𝕜 v) :
((v.toOrthonormalBasis hv).repr : E → EuclideanSpace 𝕜 ι) = v.equivFun :=
rfl
@[simp]
theorem _root_.Basis.coe_toOrthonormalBasis_repr_symm (v : Basis ι 𝕜 E) (hv : Orthonormal 𝕜 v) :
((v.toOrthonormalBasis hv).repr.symm : EuclideanSpace 𝕜 ι → E) = v.equivFun.symm :=
rfl
@[simp]
theorem _root_.Basis.toBasis_toOrthonormalBasis (v : Basis ι 𝕜 E) (hv : Orthonormal 𝕜 v) :
(v.toOrthonormalBasis hv).toBasis = v := by
simp [Basis.toOrthonormalBasis, OrthonormalBasis.toBasis]
@[simp]
theorem _root_.Basis.coe_toOrthonormalBasis (v : Basis ι 𝕜 E) (hv : Orthonormal 𝕜 v) :
(v.toOrthonormalBasis hv : ι → E) = (v : ι → E) :=
calc
(v.toOrthonormalBasis hv : ι → E) = ((v.toOrthonormalBasis hv).toBasis : ι → E) := by
classical rw [OrthonormalBasis.coe_toBasis]
_ = (v : ι → E) := by simp
/-- `Pi.orthonormalBasis (B : ∀ i, OrthonormalBasis (ι i) 𝕜 (E i))` is the
`Σ i, ι i`-indexed orthonormal basis on `Π i, E i` given by `B i` on each component. -/
protected def _root_.Pi.orthonormalBasis {η : Type*} [Fintype η] {ι : η → Type*}
[∀ i, Fintype (ι i)] {𝕜 : Type*} [RCLike 𝕜] {E : η → Type*} [∀ i, NormedAddCommGroup (E i)]
[∀ i, InnerProductSpace 𝕜 (E i)] (B : ∀ i, OrthonormalBasis (ι i) 𝕜 (E i)) :
OrthonormalBasis ((i : η) × ι i) 𝕜 (PiLp 2 E) where
repr := .trans
(.piLpCongrRight 2 fun i => (B i).repr)
(.symm <| .piLpCurry 𝕜 2 fun _ _ => 𝕜)
theorem _root_.Pi.orthonormalBasis.toBasis {η : Type*} [Fintype η] {ι : η → Type*}
[∀ i, Fintype (ι i)] {𝕜 : Type*} [RCLike 𝕜] {E : η → Type*} [∀ i, NormedAddCommGroup (E i)]
[∀ i, InnerProductSpace 𝕜 (E i)] (B : ∀ i, OrthonormalBasis (ι i) 𝕜 (E i)) :
(Pi.orthonormalBasis B).toBasis =
((Pi.basis fun i : η ↦ (B i).toBasis).map (WithLp.linearEquiv 2 _ _).symm) := by ext; rfl
@[simp]
theorem _root_.Pi.orthonormalBasis_apply {η : Type*} [Fintype η] [DecidableEq η] {ι : η → Type*}
[∀ i, Fintype (ι i)] {𝕜 : Type*} [RCLike 𝕜] {E : η → Type*} [∀ i, NormedAddCommGroup (E i)]
[∀ i, InnerProductSpace 𝕜 (E i)] (B : ∀ i, OrthonormalBasis (ι i) 𝕜 (E i))
(j : (i : η) × (ι i)) :
Pi.orthonormalBasis B j = (WithLp.equiv _ _).symm (Pi.single _ (B j.fst j.snd)) := by
classical
ext k
obtain ⟨i, j⟩ := j
simp only [Pi.orthonormalBasis, coe_ofRepr, LinearIsometryEquiv.symm_trans,
LinearIsometryEquiv.symm_symm, LinearIsometryEquiv.piLpCongrRight_symm,
LinearIsometryEquiv.trans_apply, LinearIsometryEquiv.piLpCongrRight_apply,
LinearIsometryEquiv.piLpCurry_apply, WithLp.equiv_single, WithLp.equiv_symm_pi_apply,
Sigma.curry_single (γ := fun _ _ => 𝕜)]
obtain rfl | hi := Decidable.eq_or_ne i k
· simp only [Pi.single_eq_same, WithLp.equiv_symm_single, OrthonormalBasis.repr_symm_single]
· simp only [Pi.single_eq_of_ne' hi, WithLp.equiv_symm_zero, map_zero]
@[simp]
theorem _root_.Pi.orthonormalBasis_repr {η : Type*} [Fintype η] {ι : η → Type*}
[∀ i, Fintype (ι i)] {𝕜 : Type*} [RCLike 𝕜] {E : η → Type*} [∀ i, NormedAddCommGroup (E i)]
[∀ i, InnerProductSpace 𝕜 (E i)] (B : ∀ i, OrthonormalBasis (ι i) 𝕜 (E i)) (x : (i : η) → E i)
(j : (i : η) × (ι i)) :
(Pi.orthonormalBasis B).repr x j = (B j.fst).repr (x j.fst) j.snd := rfl
variable {v : ι → E}
/-- A finite orthonormal set that spans is an orthonormal basis -/
protected def mk (hon : Orthonormal 𝕜 v) (hsp : ⊤ ≤ Submodule.span 𝕜 (Set.range v)) :
OrthonormalBasis ι 𝕜 E :=
(Basis.mk (Orthonormal.linearIndependent hon) hsp).toOrthonormalBasis (by rwa [Basis.coe_mk])
@[simp]
protected theorem coe_mk (hon : Orthonormal 𝕜 v) (hsp : ⊤ ≤ Submodule.span 𝕜 (Set.range v)) :
⇑(OrthonormalBasis.mk hon hsp) = v := by
classical rw [OrthonormalBasis.mk, _root_.Basis.coe_toOrthonormalBasis, Basis.coe_mk]
/-- Any finite subset of an orthonormal family is an `OrthonormalBasis` for its span. -/
protected def span [DecidableEq E] {v' : ι' → E} (h : Orthonormal 𝕜 v') (s : Finset ι') :
OrthonormalBasis s 𝕜 (span 𝕜 (s.image v' : Set E)) :=
let e₀' : Basis s 𝕜 _ :=
Basis.span (h.linearIndependent.comp ((↑) : s → ι') Subtype.val_injective)
let e₀ : OrthonormalBasis s 𝕜 _ :=
OrthonormalBasis.mk
(by
convert orthonormal_span (h.comp ((↑) : s → ι') Subtype.val_injective)
simp [e₀', Basis.span_apply])
e₀'.span_eq.ge
let φ : span 𝕜 (s.image v' : Set E) ≃ₗᵢ[𝕜] span 𝕜 (range (v' ∘ ((↑) : s → ι'))) :=
LinearIsometryEquiv.ofEq _ _
(by
rw [Finset.coe_image, image_eq_range]
rfl)
e₀.map φ.symm
@[simp]
protected theorem span_apply [DecidableEq E] {v' : ι' → E} (h : Orthonormal 𝕜 v') (s : Finset ι')
(i : s) : (OrthonormalBasis.span h s i : E) = v' i := by
simp only [OrthonormalBasis.span, Basis.span_apply, LinearIsometryEquiv.ofEq_symm,
OrthonormalBasis.map_apply, OrthonormalBasis.coe_mk, LinearIsometryEquiv.coe_ofEq_apply,
comp_apply]
open Submodule
/-- A finite orthonormal family of vectors whose span has trivial orthogonal complement is an
orthonormal basis. -/
protected def mkOfOrthogonalEqBot (hon : Orthonormal 𝕜 v) (hsp : (span 𝕜 (Set.range v))ᗮ = ⊥) :
OrthonormalBasis ι 𝕜 E :=
OrthonormalBasis.mk hon
(by
refine Eq.ge ?_
haveI : FiniteDimensional 𝕜 (span 𝕜 (range v)) :=
FiniteDimensional.span_of_finite 𝕜 (finite_range v)
haveI : CompleteSpace (span 𝕜 (range v)) := FiniteDimensional.complete 𝕜 _
rwa [orthogonal_eq_bot_iff] at hsp)
@[simp]
protected theorem coe_of_orthogonal_eq_bot_mk (hon : Orthonormal 𝕜 v)
(hsp : (span 𝕜 (Set.range v))ᗮ = ⊥) : ⇑(OrthonormalBasis.mkOfOrthogonalEqBot hon hsp) = v :=
OrthonormalBasis.coe_mk hon _
variable [Fintype ι']
/-- `b.reindex (e : ι ≃ ι')` is an `OrthonormalBasis` indexed by `ι'` -/
def reindex (b : OrthonormalBasis ι 𝕜 E) (e : ι ≃ ι') : OrthonormalBasis ι' 𝕜 E :=
OrthonormalBasis.ofRepr (b.repr.trans (LinearIsometryEquiv.piLpCongrLeft 2 𝕜 𝕜 e))
protected theorem reindex_apply (b : OrthonormalBasis ι 𝕜 E) (e : ι ≃ ι') (i' : ι') :
(b.reindex e) i' = b (e.symm i') := by
classical
dsimp [reindex]
rw [coe_ofRepr]
dsimp
rw [← b.repr_symm_single, LinearIsometryEquiv.piLpCongrLeft_symm,
EuclideanSpace.piLpCongrLeft_single]
@[simp]
theorem reindex_toBasis (b : OrthonormalBasis ι 𝕜 E) (e : ι ≃ ι') :
(b.reindex e).toBasis = b.toBasis.reindex e := Basis.eq_ofRepr_eq_repr fun _ ↦ congr_fun rfl
@[simp]
protected theorem coe_reindex (b : OrthonormalBasis ι 𝕜 E) (e : ι ≃ ι') :
⇑(b.reindex e) = b ∘ e.symm :=
funext (b.reindex_apply e)
@[simp]
protected theorem repr_reindex (b : OrthonormalBasis ι 𝕜 E) (e : ι ≃ ι') (x : E) (i' : ι') :
(b.reindex e).repr x i' = b.repr x (e.symm i') := by
classical
rw [OrthonormalBasis.repr_apply_apply, b.repr_apply_apply, OrthonormalBasis.coe_reindex,
comp_apply]
end OrthonormalBasis
namespace EuclideanSpace
variable (𝕜 ι)
/-- The basis `Pi.basisFun`, bundled as an orthornormal basis of `EuclideanSpace 𝕜 ι`. -/
noncomputable def basisFun : OrthonormalBasis ι 𝕜 (EuclideanSpace 𝕜 ι) :=
⟨LinearIsometryEquiv.refl _ _⟩
@[simp]
theorem basisFun_apply [DecidableEq ι] (i : ι) : basisFun ι 𝕜 i = EuclideanSpace.single i 1 :=
PiLp.basisFun_apply _ _ _ _
@[simp]
theorem basisFun_repr (x : EuclideanSpace 𝕜 ι) (i : ι) : (basisFun ι 𝕜).repr x i = x i := rfl
theorem basisFun_toBasis : (basisFun ι 𝕜).toBasis = PiLp.basisFun _ 𝕜 ι := rfl
end EuclideanSpace
instance OrthonormalBasis.instInhabited : Inhabited (OrthonormalBasis ι 𝕜 (EuclideanSpace 𝕜 ι)) :=
⟨EuclideanSpace.basisFun ι 𝕜⟩
section Complex
/-- `![1, I]` is an orthonormal basis for `ℂ` considered as a real inner product space. -/
def Complex.orthonormalBasisOneI : OrthonormalBasis (Fin 2) ℝ ℂ :=
Complex.basisOneI.toOrthonormalBasis
(by
rw [orthonormal_iff_ite]
intro i; fin_cases i <;> intro j <;> fin_cases j <;> simp [real_inner_eq_re_inner])
@[simp]
theorem Complex.orthonormalBasisOneI_repr_apply (z : ℂ) :
Complex.orthonormalBasisOneI.repr z = ![z.re, z.im] :=
rfl
@[simp]
theorem Complex.orthonormalBasisOneI_repr_symm_apply (x : EuclideanSpace ℝ (Fin 2)) :
Complex.orthonormalBasisOneI.repr.symm x = x 0 + x 1 * I :=
rfl
@[simp]
theorem Complex.toBasis_orthonormalBasisOneI :
Complex.orthonormalBasisOneI.toBasis = Complex.basisOneI :=
Basis.toBasis_toOrthonormalBasis _ _
@[simp]
theorem Complex.coe_orthonormalBasisOneI :
(Complex.orthonormalBasisOneI : Fin 2 → ℂ) = ![1, I] := by
simp [Complex.orthonormalBasisOneI]
/-- The isometry between `ℂ` and a two-dimensional real inner product space given by a basis. -/
def Complex.isometryOfOrthonormal (v : OrthonormalBasis (Fin 2) ℝ F) : ℂ ≃ₗᵢ[ℝ] F :=
Complex.orthonormalBasisOneI.repr.trans v.repr.symm
@[simp]
theorem Complex.map_isometryOfOrthonormal (v : OrthonormalBasis (Fin 2) ℝ F) (f : F ≃ₗᵢ[ℝ] F') :
Complex.isometryOfOrthonormal (v.map f) = (Complex.isometryOfOrthonormal v).trans f := by
simp only [isometryOfOrthonormal, OrthonormalBasis.map, LinearIsometryEquiv.symm_trans,
LinearIsometryEquiv.symm_symm]
-- Porting note: `LinearIsometryEquiv.trans_assoc` doesn't trigger in the `simp` above
rw [LinearIsometryEquiv.trans_assoc]
theorem Complex.isometryOfOrthonormal_symm_apply (v : OrthonormalBasis (Fin 2) ℝ F) (f : F) :
(Complex.isometryOfOrthonormal v).symm f =
(v.toBasis.coord 0 f : ℂ) + (v.toBasis.coord 1 f : ℂ) * I := by
simp [Complex.isometryOfOrthonormal]
theorem Complex.isometryOfOrthonormal_apply (v : OrthonormalBasis (Fin 2) ℝ F) (z : ℂ) :
Complex.isometryOfOrthonormal v z = z.re • v 0 + z.im • v 1 := by
simp [Complex.isometryOfOrthonormal, ← v.sum_repr_symm]
end Complex
open Module
/-! ### Matrix representation of an orthonormal basis with respect to another -/
section ToMatrix
variable [DecidableEq ι]
section
open scoped Matrix
/-- A version of `OrthonormalBasis.toMatrix_orthonormalBasis_mem_unitary` that works for bases with
different index types. -/
| @[simp]
theorem OrthonormalBasis.toMatrix_orthonormalBasis_conjTranspose_mul_self [Fintype ι']
(a : OrthonormalBasis ι' 𝕜 E) (b : OrthonormalBasis ι 𝕜 E) :
(a.toBasis.toMatrix b)ᴴ * a.toBasis.toMatrix b = 1 := by
| Mathlib/Analysis/InnerProductSpace/PiL2.lean | 740 | 743 |
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn, Violeta Hernández Palacios
-/
import Mathlib.Algebra.GroupWithZero.Divisibility
import Mathlib.Data.Nat.SuccPred
import Mathlib.Order.SuccPred.InitialSeg
import Mathlib.SetTheory.Ordinal.Basic
/-!
# Ordinal arithmetic
Ordinals have an addition (corresponding to disjoint union) that turns them into an additive
monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns
them into a monoid. One can also define correspondingly a subtraction, a division, a successor
function, a power function and a logarithm function.
We also define limit ordinals and prove the basic induction principle on ordinals separating
successor ordinals and limit ordinals, in `limitRecOn`.
## Main definitions and results
* `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`.
* `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`.
* `o₁ * o₂` is the lexicographic order on `o₂ × o₁`.
* `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the
divisibility predicate, and a modulo operation.
* `Order.succ o = o + 1` is the successor of `o`.
* `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`.
We discuss the properties of casts of natural numbers of and of `ω` with respect to these
operations.
Some properties of the operations are also used to discuss general tools on ordinals:
* `IsLimit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor.
* `limitRecOn` is the main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals.
* `IsNormal`: a function `f : Ordinal → Ordinal` satisfies `IsNormal` if it is strictly increasing
and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`.
Various other basic arithmetic results are given in `Principal.lean` instead.
-/
assert_not_exists Field Module
noncomputable section
open Function Cardinal Set Equiv Order
open scoped Ordinal
universe u v w
namespace Ordinal
variable {α β γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
/-! ### Further properties of addition on ordinals -/
@[simp]
theorem lift_add (a b : Ordinal.{v}) : lift.{u} (a + b) = lift.{u} a + lift.{u} b :=
Quotient.inductionOn₂ a b fun ⟨_α, _r, _⟩ ⟨_β, _s, _⟩ =>
Quotient.sound
⟨(RelIso.preimage Equiv.ulift _).trans
(RelIso.sumLexCongr (RelIso.preimage Equiv.ulift _) (RelIso.preimage Equiv.ulift _)).symm⟩
@[simp]
theorem lift_succ (a : Ordinal.{v}) : lift.{u} (succ a) = succ (lift.{u} a) := by
rw [← add_one_eq_succ, lift_add, lift_one]
rfl
instance instAddLeftReflectLE :
AddLeftReflectLE Ordinal.{u} where
elim c a b := by
refine inductionOn₃ a b c fun α r _ β s _ γ t _ ⟨f⟩ ↦ ?_
have H₁ a : f (Sum.inl a) = Sum.inl a := by
simpa using ((InitialSeg.leAdd t r).trans f).eq (InitialSeg.leAdd t s) a
have H₂ a : ∃ b, f (Sum.inr a) = Sum.inr b := by
generalize hx : f (Sum.inr a) = x
obtain x | x := x
· rw [← H₁, f.inj] at hx
contradiction
· exact ⟨x, rfl⟩
choose g hg using H₂
refine (RelEmbedding.ofMonotone g fun _ _ h ↦ ?_).ordinal_type_le
rwa [← @Sum.lex_inr_inr _ t _ s, ← hg, ← hg, f.map_rel_iff, Sum.lex_inr_inr]
instance : IsLeftCancelAdd Ordinal where
add_left_cancel a b c h := by simpa only [le_antisymm_iff, add_le_add_iff_left] using h
@[deprecated add_left_cancel_iff (since := "2024-12-11")]
protected theorem add_left_cancel (a) {b c : Ordinal} : a + b = a + c ↔ b = c :=
add_left_cancel_iff
private theorem add_lt_add_iff_left' (a) {b c : Ordinal} : a + b < a + c ↔ b < c := by
rw [← not_le, ← not_le, add_le_add_iff_left]
instance instAddLeftStrictMono : AddLeftStrictMono Ordinal.{u} :=
⟨fun a _b _c ↦ (add_lt_add_iff_left' a).2⟩
instance instAddLeftReflectLT : AddLeftReflectLT Ordinal.{u} :=
⟨fun a _b _c ↦ (add_lt_add_iff_left' a).1⟩
instance instAddRightReflectLT : AddRightReflectLT Ordinal.{u} :=
⟨fun _a _b _c ↦ lt_imp_lt_of_le_imp_le fun h => add_le_add_right h _⟩
theorem add_le_add_iff_right {a b : Ordinal} : ∀ n : ℕ, a + n ≤ b + n ↔ a ≤ b
| 0 => by simp
| n + 1 => by
simp only [natCast_succ, add_succ, add_succ, succ_le_succ_iff, add_le_add_iff_right]
theorem add_right_cancel {a b : Ordinal} (n : ℕ) : a + n = b + n ↔ a = b := by
simp only [le_antisymm_iff, add_le_add_iff_right]
theorem add_eq_zero_iff {a b : Ordinal} : a + b = 0 ↔ a = 0 ∧ b = 0 :=
inductionOn₂ a b fun α r _ β s _ => by
simp_rw [← type_sum_lex, type_eq_zero_iff_isEmpty]
exact isEmpty_sum
theorem left_eq_zero_of_add_eq_zero {a b : Ordinal} (h : a + b = 0) : a = 0 :=
(add_eq_zero_iff.1 h).1
theorem right_eq_zero_of_add_eq_zero {a b : Ordinal} (h : a + b = 0) : b = 0 :=
(add_eq_zero_iff.1 h).2
/-! ### The predecessor of an ordinal -/
open Classical in
/-- The ordinal predecessor of `o` is `o'` if `o = succ o'`,
and `o` otherwise. -/
def pred (o : Ordinal) : Ordinal :=
if h : ∃ a, o = succ a then Classical.choose h else o
@[simp]
theorem pred_succ (o) : pred (succ o) = o := by
have h : ∃ a, succ o = succ a := ⟨_, rfl⟩
simpa only [pred, dif_pos h] using (succ_injective <| Classical.choose_spec h).symm
theorem pred_le_self (o) : pred o ≤ o := by
classical
exact if h : ∃ a, o = succ a then by
let ⟨a, e⟩ := h
rw [e, pred_succ]; exact le_succ a
else by rw [pred, dif_neg h]
theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬∃ a, o = succ a :=
⟨fun e ⟨a, e'⟩ => by rw [e', pred_succ] at e; exact (lt_succ a).ne e, fun h => dif_neg h⟩
theorem pred_eq_iff_not_succ' {o} : pred o = o ↔ ∀ a, o ≠ succ a := by
simpa using pred_eq_iff_not_succ
theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a :=
Iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le])
(iff_not_comm.1 pred_eq_iff_not_succ).symm
@[simp]
theorem pred_zero : pred 0 = 0 :=
pred_eq_iff_not_succ'.2 fun a => (succ_ne_zero a).symm
theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a :=
⟨fun e => ⟨_, e.symm⟩, fun ⟨a, e⟩ => by simp only [e, pred_succ]⟩
theorem succ_lt_of_not_succ {o b : Ordinal} (h : ¬∃ a, o = succ a) : succ b < o ↔ b < o :=
⟨(lt_succ b).trans, fun l => lt_of_le_of_ne (succ_le_of_lt l) fun e => h ⟨_, e.symm⟩⟩
theorem lt_pred {a b} : a < pred b ↔ succ a < b := by
classical
exact if h : ∃ a, b = succ a then by
let ⟨c, e⟩ := h
rw [e, pred_succ, succ_lt_succ_iff]
else by simp only [pred, dif_neg h, succ_lt_of_not_succ h]
theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b :=
le_iff_le_iff_lt_iff_lt.2 lt_pred
@[simp]
theorem lift_is_succ {o : Ordinal.{v}} : (∃ a, lift.{u} o = succ a) ↔ ∃ a, o = succ a :=
⟨fun ⟨a, h⟩ =>
let ⟨b, e⟩ := mem_range_lift_of_le <| show a ≤ lift.{u} o from le_of_lt <| h.symm ▸ lt_succ a
⟨b, (lift_inj.{u,v}).1 <| by rw [h, ← e, lift_succ]⟩,
fun ⟨a, h⟩ => ⟨lift.{u} a, by simp only [h, lift_succ]⟩⟩
@[simp]
theorem lift_pred (o : Ordinal.{v}) : lift.{u} (pred o) = pred (lift.{u} o) := by
classical
exact if h : ∃ a, o = succ a then by obtain ⟨a, e⟩ := h; simp only [e, pred_succ, lift_succ]
else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)]
/-! ### Limit ordinals -/
/-- A limit ordinal is an ordinal which is not zero and not a successor.
TODO: deprecate this in favor of `Order.IsSuccLimit`. -/
def IsLimit (o : Ordinal) : Prop :=
IsSuccLimit o
theorem isLimit_iff {o} : IsLimit o ↔ o ≠ 0 ∧ IsSuccPrelimit o := by
simp [IsLimit, IsSuccLimit]
theorem IsLimit.isSuccPrelimit {o} (h : IsLimit o) : IsSuccPrelimit o :=
IsSuccLimit.isSuccPrelimit h
theorem IsLimit.succ_lt {o a : Ordinal} (h : IsLimit o) : a < o → succ a < o :=
IsSuccLimit.succ_lt h
theorem isSuccPrelimit_zero : IsSuccPrelimit (0 : Ordinal) := isSuccPrelimit_bot
theorem not_zero_isLimit : ¬IsLimit 0 :=
not_isSuccLimit_bot
theorem not_succ_isLimit (o) : ¬IsLimit (succ o) :=
not_isSuccLimit_succ o
theorem not_succ_of_isLimit {o} (h : IsLimit o) : ¬∃ a, o = succ a
| ⟨a, e⟩ => not_succ_isLimit a (e ▸ h)
theorem succ_lt_of_isLimit {o a : Ordinal} (h : IsLimit o) : succ a < o ↔ a < o :=
IsSuccLimit.succ_lt_iff h
theorem le_succ_of_isLimit {o} (h : IsLimit o) {a} : o ≤ succ a ↔ o ≤ a :=
le_iff_le_iff_lt_iff_lt.2 <| succ_lt_of_isLimit h
theorem limit_le {o} (h : IsLimit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a :=
⟨fun h _x l => l.le.trans h, fun H =>
(le_succ_of_isLimit h).1 <| le_of_not_lt fun hn => not_lt_of_le (H _ hn) (lt_succ a)⟩
theorem lt_limit {o} (h : IsLimit o) {a} : a < o ↔ ∃ x < o, a < x := by
-- Porting note: `bex_def` is required.
simpa only [not_forall₂, not_le, bex_def] using not_congr (@limit_le _ h a)
@[simp]
theorem lift_isLimit (o : Ordinal.{v}) : IsLimit (lift.{u,v} o) ↔ IsLimit o :=
liftInitialSeg.isSuccLimit_apply_iff
theorem IsLimit.pos {o : Ordinal} (h : IsLimit o) : 0 < o :=
IsSuccLimit.bot_lt h
theorem IsLimit.ne_zero {o : Ordinal} (h : IsLimit o) : o ≠ 0 :=
h.pos.ne'
theorem IsLimit.one_lt {o : Ordinal} (h : IsLimit o) : 1 < o := by
simpa only [succ_zero] using h.succ_lt h.pos
theorem IsLimit.nat_lt {o : Ordinal} (h : IsLimit o) : ∀ n : ℕ, (n : Ordinal) < o
| 0 => h.pos
| n + 1 => h.succ_lt (IsLimit.nat_lt h n)
theorem zero_or_succ_or_limit (o : Ordinal) : o = 0 ∨ (∃ a, o = succ a) ∨ IsLimit o := by
simpa [eq_comm] using isMin_or_mem_range_succ_or_isSuccLimit o
theorem isLimit_of_not_succ_of_ne_zero {o : Ordinal} (h : ¬∃ a, o = succ a) (h' : o ≠ 0) :
IsLimit o := ((zero_or_succ_or_limit o).resolve_left h').resolve_left h
-- TODO: this is an iff with `IsSuccPrelimit`
theorem IsLimit.sSup_Iio {o : Ordinal} (h : IsLimit o) : sSup (Iio o) = o := by
apply (csSup_le' (fun a ha ↦ le_of_lt ha)).antisymm
apply le_of_forall_lt
intro a ha
exact (lt_succ a).trans_le (le_csSup bddAbove_Iio (h.succ_lt ha))
theorem IsLimit.iSup_Iio {o : Ordinal} (h : IsLimit o) : ⨆ a : Iio o, a.1 = o := by
rw [← sSup_eq_iSup', h.sSup_Iio]
/-- Main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/
@[elab_as_elim]
def limitRecOn {motive : Ordinal → Sort*} (o : Ordinal)
(zero : motive 0) (succ : ∀ o, motive o → motive (succ o))
(isLimit : ∀ o, IsLimit o → (∀ o' < o, motive o') → motive o) : motive o := by
refine SuccOrder.limitRecOn o (fun a ha ↦ ?_) (fun a _ ↦ succ a) isLimit
convert zero
simpa using ha
@[simp]
theorem limitRecOn_zero {motive} (H₁ H₂ H₃) : @limitRecOn motive 0 H₁ H₂ H₃ = H₁ :=
SuccOrder.limitRecOn_isMin _ _ _ isMin_bot
@[simp]
theorem limitRecOn_succ {motive} (o H₁ H₂ H₃) :
@limitRecOn motive (succ o) H₁ H₂ H₃ = H₂ o (@limitRecOn motive o H₁ H₂ H₃) :=
SuccOrder.limitRecOn_succ ..
@[simp]
theorem limitRecOn_limit {motive} (o H₁ H₂ H₃ h) :
@limitRecOn motive o H₁ H₂ H₃ = H₃ o h fun x _h => @limitRecOn motive x H₁ H₂ H₃ :=
SuccOrder.limitRecOn_of_isSuccLimit ..
/-- Bounded recursion on ordinals. Similar to `limitRecOn`, with the assumption `o < l`
added to all cases. The final term's domain is the ordinals below `l`. -/
@[elab_as_elim]
def boundedLimitRecOn {l : Ordinal} (lLim : l.IsLimit) {motive : Iio l → Sort*} (o : Iio l)
(zero : motive ⟨0, lLim.pos⟩)
(succ : (o : Iio l) → motive o → motive ⟨succ o, lLim.succ_lt o.2⟩)
(isLimit : (o : Iio l) → IsLimit o → (Π o' < o, motive o') → motive o) : motive o :=
limitRecOn (motive := fun p ↦ (h : p < l) → motive ⟨p, h⟩) o.1 (fun _ ↦ zero)
(fun o ih h ↦ succ ⟨o, _⟩ <| ih <| (lt_succ o).trans h)
(fun _o ho ih _ ↦ isLimit _ ho fun _o' h ↦ ih _ h _) o.2
@[simp]
theorem boundedLimitRec_zero {l} (lLim : l.IsLimit) {motive} (H₁ H₂ H₃) :
@boundedLimitRecOn l lLim motive ⟨0, lLim.pos⟩ H₁ H₂ H₃ = H₁ := by
rw [boundedLimitRecOn, limitRecOn_zero]
@[simp]
theorem boundedLimitRec_succ {l} (lLim : l.IsLimit) {motive} (o H₁ H₂ H₃) :
@boundedLimitRecOn l lLim motive ⟨succ o.1, lLim.succ_lt o.2⟩ H₁ H₂ H₃ = H₂ o
(@boundedLimitRecOn l lLim motive o H₁ H₂ H₃) := by
rw [boundedLimitRecOn, limitRecOn_succ]
rfl
theorem boundedLimitRec_limit {l} (lLim : l.IsLimit) {motive} (o H₁ H₂ H₃ oLim) :
@boundedLimitRecOn l lLim motive o H₁ H₂ H₃ = H₃ o oLim (fun x _ ↦
@boundedLimitRecOn l lLim motive x H₁ H₂ H₃) := by
rw [boundedLimitRecOn, limitRecOn_limit]
rfl
instance orderTopToTypeSucc (o : Ordinal) : OrderTop (succ o).toType :=
@OrderTop.mk _ _ (Top.mk _) le_enum_succ
theorem enum_succ_eq_top {o : Ordinal} :
enum (α := (succ o).toType) (· < ·) ⟨o, type_toType _ ▸ lt_succ o⟩ = ⊤ :=
rfl
theorem has_succ_of_type_succ_lt {α} {r : α → α → Prop} [wo : IsWellOrder α r]
(h : ∀ a < type r, succ a < type r) (x : α) : ∃ y, r x y := by
use enum r ⟨succ (typein r x), h _ (typein_lt_type r x)⟩
convert enum_lt_enum.mpr _
· rw [enum_typein]
· rw [Subtype.mk_lt_mk, lt_succ_iff]
theorem toType_noMax_of_succ_lt {o : Ordinal} (ho : ∀ a < o, succ a < o) : NoMaxOrder o.toType :=
⟨has_succ_of_type_succ_lt (type_toType _ ▸ ho)⟩
theorem bounded_singleton {r : α → α → Prop} [IsWellOrder α r] (hr : (type r).IsLimit) (x) :
Bounded r {x} := by
refine ⟨enum r ⟨succ (typein r x), hr.succ_lt (typein_lt_type r x)⟩, ?_⟩
intro b hb
rw [mem_singleton_iff.1 hb]
nth_rw 1 [← enum_typein r x]
rw [@enum_lt_enum _ r, Subtype.mk_lt_mk]
apply lt_succ
@[simp]
theorem typein_ordinal (o : Ordinal.{u}) :
@typein Ordinal (· < ·) _ o = Ordinal.lift.{u + 1} o := by
refine Quotient.inductionOn o ?_
rintro ⟨α, r, wo⟩; apply Quotient.sound
constructor; refine ((RelIso.preimage Equiv.ulift r).trans (enum r).symm).symm
theorem mk_Iio_ordinal (o : Ordinal.{u}) :
#(Iio o) = Cardinal.lift.{u + 1} o.card := by
rw [lift_card, ← typein_ordinal]
rfl
/-! ### Normal ordinal functions -/
/-- A normal ordinal function is a strictly increasing function which is
order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`. -/
def IsNormal (f : Ordinal → Ordinal) : Prop :=
(∀ o, f o < f (succ o)) ∧ ∀ o, IsLimit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a
theorem IsNormal.limit_le {f} (H : IsNormal f) :
∀ {o}, IsLimit o → ∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a :=
@H.2
theorem IsNormal.limit_lt {f} (H : IsNormal f) {o} (h : IsLimit o) {a} :
a < f o ↔ ∃ b < o, a < f b :=
not_iff_not.1 <| by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a
theorem IsNormal.strictMono {f} (H : IsNormal f) : StrictMono f := fun a b =>
limitRecOn b (Not.elim (not_lt_of_le <| Ordinal.zero_le _))
(fun _b IH h =>
(lt_or_eq_of_le (le_of_lt_succ h)).elim (fun h => (IH h).trans (H.1 _)) fun e => e ▸ H.1 _)
fun _b l _IH h => lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 le_rfl _ (l.succ_lt h))
theorem IsNormal.monotone {f} (H : IsNormal f) : Monotone f :=
H.strictMono.monotone
theorem isNormal_iff_strictMono_limit (f : Ordinal → Ordinal) :
IsNormal f ↔ StrictMono f ∧ ∀ o, IsLimit o → ∀ a, (∀ b < o, f b ≤ a) → f o ≤ a :=
⟨fun hf => ⟨hf.strictMono, fun a ha c => (hf.2 a ha c).2⟩, fun ⟨hs, hl⟩ =>
⟨fun a => hs (lt_succ a), fun a ha c =>
⟨fun hac _b hba => ((hs hba).trans_le hac).le, hl a ha c⟩⟩⟩
theorem IsNormal.lt_iff {f} (H : IsNormal f) {a b} : f a < f b ↔ a < b :=
StrictMono.lt_iff_lt <| H.strictMono
theorem IsNormal.le_iff {f} (H : IsNormal f) {a b} : f a ≤ f b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_iff
theorem IsNormal.inj {f} (H : IsNormal f) {a b} : f a = f b ↔ a = b := by
simp only [le_antisymm_iff, H.le_iff]
theorem IsNormal.id_le {f} (H : IsNormal f) : id ≤ f :=
H.strictMono.id_le
theorem IsNormal.le_apply {f} (H : IsNormal f) {a} : a ≤ f a :=
H.strictMono.le_apply
theorem IsNormal.le_iff_eq {f} (H : IsNormal f) {a} : f a ≤ a ↔ f a = a :=
H.le_apply.le_iff_eq
theorem IsNormal.le_set {f o} (H : IsNormal f) (p : Set Ordinal) (p0 : p.Nonempty) (b)
(H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, a ≤ o) : f b ≤ o ↔ ∀ a ∈ p, f a ≤ o :=
⟨fun h _ pa => (H.le_iff.2 ((H₂ _).1 le_rfl _ pa)).trans h, fun h => by
induction b using limitRecOn with
| zero =>
obtain ⟨x, px⟩ := p0
have := Ordinal.le_zero.1 ((H₂ _).1 (Ordinal.zero_le _) _ px)
rw [this] at px
exact h _ px
| succ S _ =>
rcases not_forall₂.1 (mt (H₂ S).2 <| (lt_succ S).not_le) with ⟨a, h₁, h₂⟩
exact (H.le_iff.2 <| succ_le_of_lt <| not_le.1 h₂).trans (h _ h₁)
| isLimit S L _ =>
refine (H.2 _ L _).2 fun a h' => ?_
rcases not_forall₂.1 (mt (H₂ a).2 h'.not_le) with ⟨b, h₁, h₂⟩
exact (H.le_iff.2 <| (not_le.1 h₂).le).trans (h _ h₁)⟩
theorem IsNormal.le_set' {f o} (H : IsNormal f) (p : Set α) (p0 : p.Nonempty) (g : α → Ordinal) (b)
(H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, g a ≤ o) : f b ≤ o ↔ ∀ a ∈ p, f (g a) ≤ o := by
simpa [H₂] using H.le_set (g '' p) (p0.image g) b
theorem IsNormal.refl : IsNormal id :=
⟨lt_succ, fun _o l _a => Ordinal.limit_le l⟩
theorem IsNormal.trans {f g} (H₁ : IsNormal f) (H₂ : IsNormal g) : IsNormal (f ∘ g) :=
⟨fun _x => H₁.lt_iff.2 (H₂.1 _), fun o l _a =>
H₁.le_set' (· < o) ⟨0, l.pos⟩ g _ fun _c => H₂.2 _ l _⟩
theorem IsNormal.isLimit {f} (H : IsNormal f) {o} (ho : IsLimit o) : IsLimit (f o) := by
rw [isLimit_iff, isSuccPrelimit_iff_succ_lt]
use (H.lt_iff.2 ho.pos).ne_bot
intro a ha
obtain ⟨b, hb, hab⟩ := (H.limit_lt ho).1 ha
rw [← succ_le_iff] at hab
apply hab.trans_lt
rwa [H.lt_iff]
theorem add_le_of_limit {a b c : Ordinal} (h : IsLimit b) :
a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c :=
⟨fun h _ l => (add_le_add_left l.le _).trans h, fun H =>
le_of_not_lt <| by
-- Porting note: `induction` tactics are required because of the parser bug.
induction a using inductionOn with
| H α r =>
induction b using inductionOn with
| H β s =>
intro l
suffices ∀ x : β, Sum.Lex r s (Sum.inr x) (enum _ ⟨_, l⟩) by
-- Porting note: `revert` & `intro` is required because `cases'` doesn't replace
-- `enum _ _ l` in `this`.
revert this; rcases enum _ ⟨_, l⟩ with x | x <;> intro this
· cases this (enum s ⟨0, h.pos⟩)
· exact irrefl _ (this _)
intro x
rw [← typein_lt_typein (Sum.Lex r s), typein_enum]
have := H _ (h.succ_lt (typein_lt_type s x))
rw [add_succ, succ_le_iff] at this
refine
(RelEmbedding.ofMonotone (fun a => ?_) fun a b => ?_).ordinal_type_le.trans_lt this
· rcases a with ⟨a | b, h⟩
· exact Sum.inl a
· exact Sum.inr ⟨b, by cases h; assumption⟩
· rcases a with ⟨a | a, h₁⟩ <;> rcases b with ⟨b | b, h₂⟩ <;> cases h₁ <;> cases h₂ <;>
rintro ⟨⟩ <;> constructor <;> assumption⟩
theorem isNormal_add_right (a : Ordinal) : IsNormal (a + ·) :=
⟨fun b => (add_lt_add_iff_left a).2 (lt_succ b), fun _b l _c => add_le_of_limit l⟩
theorem isLimit_add (a) {b} : IsLimit b → IsLimit (a + b) :=
(isNormal_add_right a).isLimit
alias IsLimit.add := isLimit_add
/-! ### Subtraction on ordinals -/
/-- The set in the definition of subtraction is nonempty. -/
private theorem sub_nonempty {a b : Ordinal} : { o | a ≤ b + o }.Nonempty :=
⟨a, le_add_left _ _⟩
/-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/
instance sub : Sub Ordinal :=
⟨fun a b => sInf { o | a ≤ b + o }⟩
theorem le_add_sub (a b : Ordinal) : a ≤ b + (a - b) :=
csInf_mem sub_nonempty
theorem sub_le {a b c : Ordinal} : a - b ≤ c ↔ a ≤ b + c :=
⟨fun h => (le_add_sub a b).trans (add_le_add_left h _), fun h => csInf_le' h⟩
theorem lt_sub {a b c : Ordinal} : a < b - c ↔ c + a < b :=
lt_iff_lt_of_le_iff_le sub_le
theorem add_sub_cancel (a b : Ordinal) : a + b - a = b :=
le_antisymm (sub_le.2 <| le_rfl) ((add_le_add_iff_left a).1 <| le_add_sub _ _)
theorem sub_eq_of_add_eq {a b c : Ordinal} (h : a + b = c) : c - a = b :=
h ▸ add_sub_cancel _ _
theorem sub_le_self (a b : Ordinal) : a - b ≤ a :=
sub_le.2 <| le_add_left _ _
protected theorem add_sub_cancel_of_le {a b : Ordinal} (h : b ≤ a) : b + (a - b) = a :=
(le_add_sub a b).antisymm'
(by
rcases zero_or_succ_or_limit (a - b) with (e | ⟨c, e⟩ | l)
· simp only [e, add_zero, h]
· rw [e, add_succ, succ_le_iff, ← lt_sub, e]
exact lt_succ c
· exact (add_le_of_limit l).2 fun c l => (lt_sub.1 l).le)
theorem le_sub_of_le {a b c : Ordinal} (h : b ≤ a) : c ≤ a - b ↔ b + c ≤ a := by
rw [← add_le_add_iff_left b, Ordinal.add_sub_cancel_of_le h]
theorem sub_lt_of_le {a b c : Ordinal} (h : b ≤ a) : a - b < c ↔ a < b + c :=
lt_iff_lt_of_le_iff_le (le_sub_of_le h)
instance existsAddOfLE : ExistsAddOfLE Ordinal :=
⟨fun h => ⟨_, (Ordinal.add_sub_cancel_of_le h).symm⟩⟩
@[simp]
theorem sub_zero (a : Ordinal) : a - 0 = a := by simpa only [zero_add] using add_sub_cancel 0 a
@[simp]
theorem zero_sub (a : Ordinal) : 0 - a = 0 := by rw [← Ordinal.le_zero]; apply sub_le_self
@[simp]
theorem sub_self (a : Ordinal) : a - a = 0 := by simpa only [add_zero] using add_sub_cancel a 0
protected theorem sub_eq_zero_iff_le {a b : Ordinal} : a - b = 0 ↔ a ≤ b :=
⟨fun h => by simpa only [h, add_zero] using le_add_sub a b, fun h => by
rwa [← Ordinal.le_zero, sub_le, add_zero]⟩
protected theorem sub_ne_zero_iff_lt {a b : Ordinal} : a - b ≠ 0 ↔ b < a := by
simpa using Ordinal.sub_eq_zero_iff_le.not
theorem sub_sub (a b c : Ordinal) : a - b - c = a - (b + c) :=
eq_of_forall_ge_iff fun d => by rw [sub_le, sub_le, sub_le, add_assoc]
@[simp]
theorem add_sub_add_cancel (a b c : Ordinal) : a + b - (a + c) = b - c := by
rw [← sub_sub, add_sub_cancel]
theorem le_sub_of_add_le {a b c : Ordinal} (h : b + c ≤ a) : c ≤ a - b := by
rw [← add_le_add_iff_left b]
exact h.trans (le_add_sub a b)
theorem sub_lt_of_lt_add {a b c : Ordinal} (h : a < b + c) (hc : 0 < c) : a - b < c := by
obtain hab | hba := lt_or_le a b
· rwa [Ordinal.sub_eq_zero_iff_le.2 hab.le]
· rwa [sub_lt_of_le hba]
theorem lt_add_iff {a b c : Ordinal} (hc : c ≠ 0) : a < b + c ↔ ∃ d < c, a ≤ b + d := by
use fun h ↦ ⟨_, sub_lt_of_lt_add h hc.bot_lt, le_add_sub a b⟩
rintro ⟨d, hd, ha⟩
exact ha.trans_lt (add_lt_add_left hd b)
theorem add_le_iff {a b c : Ordinal} (hb : b ≠ 0) : a + b ≤ c ↔ ∀ d < b, a + d < c := by
simpa using (lt_add_iff hb).not
@[deprecated add_le_iff (since := "2024-12-08")]
theorem add_le_of_forall_add_lt {a b c : Ordinal} (hb : 0 < b) (h : ∀ d < b, a + d < c) :
a + b ≤ c :=
(add_le_iff hb.ne').2 h
theorem isLimit_sub {a b} (ha : IsLimit a) (h : b < a) : IsLimit (a - b) := by
rw [isLimit_iff, Ordinal.sub_ne_zero_iff_lt, isSuccPrelimit_iff_succ_lt]
refine ⟨h, fun c hc ↦ ?_⟩
rw [lt_sub] at hc ⊢
rw [add_succ]
exact ha.succ_lt hc
/-! ### Multiplication of ordinals -/
/-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on
`o₂ × o₁`. -/
instance monoid : Monoid Ordinal.{u} where
mul a b :=
Quotient.liftOn₂ a b
(fun ⟨α, r, _⟩ ⟨β, s, _⟩ => ⟦⟨β × α, Prod.Lex s r, inferInstance⟩⟧ :
WellOrder → WellOrder → Ordinal)
fun ⟨_, _, _⟩ _ _ _ ⟨f⟩ ⟨g⟩ => Quot.sound ⟨RelIso.prodLexCongr g f⟩
one := 1
mul_assoc a b c :=
Quotient.inductionOn₃ a b c fun ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ =>
Eq.symm <|
Quotient.sound
⟨⟨prodAssoc _ _ _, @fun a b => by
rcases a with ⟨⟨a₁, a₂⟩, a₃⟩
rcases b with ⟨⟨b₁, b₂⟩, b₃⟩
simp [Prod.lex_def, and_or_left, or_assoc, and_assoc]⟩⟩
mul_one a :=
inductionOn a fun α r _ =>
Quotient.sound
⟨⟨punitProd _, @fun a b => by
rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩
simp only [Prod.lex_def, EmptyRelation, false_or]
simp only [eq_self_iff_true, true_and]
rfl⟩⟩
one_mul a :=
inductionOn a fun α r _ =>
Quotient.sound
⟨⟨prodPUnit _, @fun a b => by
rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩
simp only [Prod.lex_def, EmptyRelation, and_false, or_false]
rfl⟩⟩
@[simp]
theorem type_prod_lex {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [IsWellOrder α r]
[IsWellOrder β s] : type (Prod.Lex s r) = type r * type s :=
rfl
private theorem mul_eq_zero' {a b : Ordinal} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
inductionOn a fun α _ _ =>
inductionOn b fun β _ _ => by
simp_rw [← type_prod_lex, type_eq_zero_iff_isEmpty]
rw [or_comm]
exact isEmpty_prod
instance monoidWithZero : MonoidWithZero Ordinal :=
{ Ordinal.monoid with
zero := 0
mul_zero := fun _a => mul_eq_zero'.2 <| Or.inr rfl
zero_mul := fun _a => mul_eq_zero'.2 <| Or.inl rfl }
instance noZeroDivisors : NoZeroDivisors Ordinal :=
⟨fun {_ _} => mul_eq_zero'.1⟩
@[simp]
theorem lift_mul (a b : Ordinal.{v}) : lift.{u} (a * b) = lift.{u} a * lift.{u} b :=
Quotient.inductionOn₂ a b fun ⟨_α, _r, _⟩ ⟨_β, _s, _⟩ =>
Quotient.sound
⟨(RelIso.preimage Equiv.ulift _).trans
(RelIso.prodLexCongr (RelIso.preimage Equiv.ulift _)
(RelIso.preimage Equiv.ulift _)).symm⟩
@[simp]
theorem card_mul (a b) : card (a * b) = card a * card b :=
Quotient.inductionOn₂ a b fun ⟨α, _r, _⟩ ⟨β, _s, _⟩ => mul_comm #β #α
instance leftDistribClass : LeftDistribClass Ordinal.{u} :=
⟨fun a b c =>
Quotient.inductionOn₃ a b c fun ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ =>
Quotient.sound
⟨⟨sumProdDistrib _ _ _, by
rintro ⟨a₁ | a₁, a₂⟩ ⟨b₁ | b₁, b₂⟩ <;>
simp only [Prod.lex_def, Sum.lex_inl_inl, Sum.Lex.sep, Sum.lex_inr_inl, Sum.lex_inr_inr,
sumProdDistrib_apply_left, sumProdDistrib_apply_right, reduceCtorEq] <;>
-- Porting note: `Sum.inr.inj_iff` is required.
simp only [Sum.inl.inj_iff, Sum.inr.inj_iff, true_or, false_and, false_or]⟩⟩⟩
theorem mul_succ (a b : Ordinal) : a * succ b = a * b + a :=
mul_add_one a b
instance mulLeftMono : MulLeftMono Ordinal.{u} :=
⟨fun c a b =>
Quotient.inductionOn₃ a b c fun ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ => by
refine
(RelEmbedding.ofMonotone (fun a : α × γ => (f a.1, a.2)) fun a b h => ?_).ordinal_type_le
obtain ⟨-, -, h'⟩ | ⟨-, h'⟩ := h
· exact Prod.Lex.left _ _ (f.toRelEmbedding.map_rel_iff.2 h')
· exact Prod.Lex.right _ h'⟩
instance mulRightMono : MulRightMono Ordinal.{u} :=
⟨fun c a b =>
Quotient.inductionOn₃ a b c fun ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ => by
refine
(RelEmbedding.ofMonotone (fun a : γ × α => (a.1, f a.2)) fun a b h => ?_).ordinal_type_le
obtain ⟨-, -, h'⟩ | ⟨-, h'⟩ := h
· exact Prod.Lex.left _ _ h'
· exact Prod.Lex.right _ (f.toRelEmbedding.map_rel_iff.2 h')⟩
theorem le_mul_left (a : Ordinal) {b : Ordinal} (hb : 0 < b) : a ≤ a * b := by
convert mul_le_mul_left' (one_le_iff_pos.2 hb) a
rw [mul_one a]
theorem le_mul_right (a : Ordinal) {b : Ordinal} (hb : 0 < b) : a ≤ b * a := by
convert mul_le_mul_right' (one_le_iff_pos.2 hb) a
rw [one_mul a]
private theorem mul_le_of_limit_aux {α β r s} [IsWellOrder α r] [IsWellOrder β s] {c}
(h : IsLimit (type s)) (H : ∀ b' < type s, type r * b' ≤ c) (l : c < type r * type s) :
False := by
suffices ∀ a b, Prod.Lex s r (b, a) (enum _ ⟨_, l⟩) by
obtain ⟨b, a⟩ := enum _ ⟨_, l⟩
exact irrefl _ (this _ _)
intro a b
rw [← typein_lt_typein (Prod.Lex s r), typein_enum]
have := H _ (h.succ_lt (typein_lt_type s b))
rw [mul_succ] at this
have := ((add_lt_add_iff_left _).2 (typein_lt_type _ a)).trans_le this
refine (RelEmbedding.ofMonotone (fun a => ?_) fun a b => ?_).ordinal_type_le.trans_lt this
· rcases a with ⟨⟨b', a'⟩, h⟩
by_cases e : b = b'
· refine Sum.inr ⟨a', ?_⟩
subst e
obtain ⟨-, -, h⟩ | ⟨-, h⟩ := h
· exact (irrefl _ h).elim
· exact h
· refine Sum.inl (⟨b', ?_⟩, a')
obtain ⟨-, -, h⟩ | ⟨e, h⟩ := h
· exact h
· exact (e rfl).elim
· rcases a with ⟨⟨b₁, a₁⟩, h₁⟩
rcases b with ⟨⟨b₂, a₂⟩, h₂⟩
intro h
by_cases e₁ : b = b₁ <;> by_cases e₂ : b = b₂
· substs b₁ b₂
simpa only [subrel_val, Prod.lex_def, @irrefl _ s _ b, true_and, false_or,
eq_self_iff_true, dif_pos, Sum.lex_inr_inr] using h
· subst b₁
simp only [subrel_val, Prod.lex_def, e₂, Prod.lex_def, dif_pos, subrel_val, eq_self_iff_true,
or_false, dif_neg, not_false_iff, Sum.lex_inr_inl, false_and] at h ⊢
obtain ⟨-, -, h₂_h⟩ | e₂ := h₂ <;> [exact asymm h h₂_h; exact e₂ rfl]
· simp [e₂, dif_neg e₁, show b₂ ≠ b₁ from e₂ ▸ e₁]
· simpa only [dif_neg e₁, dif_neg e₂, Prod.lex_def, subrel_val, Subtype.mk_eq_mk,
Sum.lex_inl_inl] using h
theorem mul_le_of_limit {a b c : Ordinal} (h : IsLimit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c :=
⟨fun h _ l => (mul_le_mul_left' l.le _).trans h, fun H =>
-- Porting note: `induction` tactics are required because of the parser bug.
le_of_not_lt <| by
induction a using inductionOn with
| H α r =>
induction b using inductionOn with
| H β s =>
exact mul_le_of_limit_aux h H⟩
theorem isNormal_mul_right {a : Ordinal} (h : 0 < a) : IsNormal (a * ·) :=
-- Porting note (https://github.com/leanprover-community/mathlib4/issues/12129): additional beta reduction needed
⟨fun b => by
beta_reduce
rw [mul_succ]
simpa only [add_zero] using (add_lt_add_iff_left (a * b)).2 h,
fun _ l _ => mul_le_of_limit l⟩
theorem lt_mul_of_limit {a b c : Ordinal} (h : IsLimit c) : a < b * c ↔ ∃ c' < c, a < b * c' := by
-- Porting note: `bex_def` is required.
simpa only [not_forall₂, not_le, bex_def] using not_congr (@mul_le_of_limit b c a h)
theorem mul_lt_mul_iff_left {a b c : Ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c :=
(isNormal_mul_right a0).lt_iff
theorem mul_le_mul_iff_left {a b c : Ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c :=
(isNormal_mul_right a0).le_iff
theorem mul_lt_mul_of_pos_left {a b c : Ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b :=
(mul_lt_mul_iff_left c0).2 h
theorem mul_pos {a b : Ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b := by
simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁
theorem mul_ne_zero {a b : Ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := by
simpa only [Ordinal.pos_iff_ne_zero] using mul_pos
theorem le_of_mul_le_mul_left {a b c : Ordinal} (h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b :=
le_imp_le_of_lt_imp_lt (fun h' => mul_lt_mul_of_pos_left h' h0) h
theorem mul_right_inj {a b c : Ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c :=
(isNormal_mul_right a0).inj
theorem isLimit_mul {a b : Ordinal} (a0 : 0 < a) : IsLimit b → IsLimit (a * b) :=
(isNormal_mul_right a0).isLimit
theorem isLimit_mul_left {a b : Ordinal} (l : IsLimit a) (b0 : 0 < b) : IsLimit (a * b) := by
rcases zero_or_succ_or_limit b with (rfl | ⟨b, rfl⟩ | lb)
· exact b0.false.elim
· rw [mul_succ]
exact isLimit_add _ l
· exact isLimit_mul l.pos lb
theorem smul_eq_mul : ∀ (n : ℕ) (a : Ordinal), n • a = a * n
| 0, a => by rw [zero_nsmul, Nat.cast_zero, mul_zero]
| n + 1, a => by rw [succ_nsmul, Nat.cast_add, mul_add, Nat.cast_one, mul_one, smul_eq_mul n]
private theorem add_mul_limit_aux {a b c : Ordinal} (ba : b + a = a) (l : IsLimit c)
(IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c :=
le_antisymm
((mul_le_of_limit l).2 fun c' h => by
apply (mul_le_mul_left' (le_succ c') _).trans
rw [IH _ h]
apply (add_le_add_left _ _).trans
· rw [← mul_succ]
exact mul_le_mul_left' (succ_le_of_lt <| l.succ_lt h) _
· rw [← ba]
exact le_add_right _ _)
(mul_le_mul_right' (le_add_right _ _) _)
theorem add_mul_succ {a b : Ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := by
induction c using limitRecOn with
| zero => simp only [succ_zero, mul_one]
| succ c IH =>
rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ]
| isLimit c l IH =>
rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc]
theorem add_mul_limit {a b c : Ordinal} (ba : b + a = a) (l : IsLimit c) : (a + b) * c = a * c :=
add_mul_limit_aux ba l fun c' _ => add_mul_succ c' ba
/-! ### Division on ordinals -/
/-- The set in the definition of division is nonempty. -/
private theorem div_nonempty {a b : Ordinal} (h : b ≠ 0) : { o | a < b * succ o }.Nonempty :=
⟨a, (succ_le_iff (a := a) (b := b * succ a)).1 <| by
simpa only [succ_zero, one_mul] using
mul_le_mul_right' (succ_le_of_lt (Ordinal.pos_iff_ne_zero.2 h)) (succ a)⟩
/-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/
instance div : Div Ordinal :=
⟨fun a b => if b = 0 then 0 else sInf { o | a < b * succ o }⟩
@[simp]
theorem div_zero (a : Ordinal) : a / 0 = 0 :=
dif_pos rfl
private theorem div_def (a) {b : Ordinal} (h : b ≠ 0) : a / b = sInf { o | a < b * succ o } :=
dif_neg h
theorem lt_mul_succ_div (a) {b : Ordinal} (h : b ≠ 0) : a < b * succ (a / b) := by
rw [div_def a h]; exact csInf_mem (div_nonempty h)
theorem lt_mul_div_add (a) {b : Ordinal} (h : b ≠ 0) : a < b * (a / b) + b := by
simpa only [mul_succ] using lt_mul_succ_div a h
theorem div_le {a b c : Ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c :=
⟨fun h => (lt_mul_succ_div a b0).trans_le (mul_le_mul_left' (succ_le_succ_iff.2 h) _), fun h => by
rw [div_def a b0]; exact csInf_le' h⟩
theorem lt_div {a b c : Ordinal} (h : c ≠ 0) : a < b / c ↔ c * succ a ≤ b := by
rw [← not_le, div_le h, not_lt]
theorem div_pos {b c : Ordinal} (h : c ≠ 0) : 0 < b / c ↔ c ≤ b := by simp [lt_div h]
theorem le_div {a b c : Ordinal} (c0 : c ≠ 0) : a ≤ b / c ↔ c * a ≤ b := by
induction a using limitRecOn with
| zero => simp only [mul_zero, Ordinal.zero_le]
| succ _ _ => rw [succ_le_iff, lt_div c0]
| isLimit _ h₁ h₂ =>
revert h₁ h₂
simp +contextual only [mul_le_of_limit, limit_le, forall_true_iff]
theorem div_lt {a b c : Ordinal} (b0 : b ≠ 0) : a / b < c ↔ a < b * c :=
lt_iff_lt_of_le_iff_le <| le_div b0
theorem div_le_of_le_mul {a b c : Ordinal} (h : a ≤ b * c) : a / b ≤ c :=
if b0 : b = 0 then by simp only [b0, div_zero, Ordinal.zero_le]
else
(div_le b0).2 <| h.trans_lt <| mul_lt_mul_of_pos_left (lt_succ c) (Ordinal.pos_iff_ne_zero.2 b0)
theorem mul_lt_of_lt_div {a b c : Ordinal} : a < b / c → c * a < b :=
lt_imp_lt_of_le_imp_le div_le_of_le_mul
@[simp]
theorem zero_div (a : Ordinal) : 0 / a = 0 :=
Ordinal.le_zero.1 <| div_le_of_le_mul <| Ordinal.zero_le _
theorem mul_div_le (a b : Ordinal) : b * (a / b) ≤ a :=
if b0 : b = 0 then by simp only [b0, zero_mul, Ordinal.zero_le] else (le_div b0).1 le_rfl
theorem div_le_left {a b : Ordinal} (h : a ≤ b) (c : Ordinal) : a / c ≤ b / c := by
obtain rfl | hc := eq_or_ne c 0
· rw [div_zero, div_zero]
· rw [le_div hc]
exact (mul_div_le a c).trans h
theorem mul_add_div (a) {b : Ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b := by
apply le_antisymm
· apply (div_le b0).2
rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left]
apply lt_mul_div_add _ b0
· rw [le_div b0, mul_add, add_le_add_iff_left]
apply mul_div_le
theorem div_eq_zero_of_lt {a b : Ordinal} (h : a < b) : a / b = 0 := by
rw [← Ordinal.le_zero, div_le <| Ordinal.pos_iff_ne_zero.1 <| (Ordinal.zero_le _).trans_lt h]
simpa only [succ_zero, mul_one] using h
@[simp]
theorem mul_div_cancel (a) {b : Ordinal} (b0 : b ≠ 0) : b * a / b = a := by
simpa only [add_zero, zero_div] using mul_add_div a b0 0
theorem mul_add_div_mul {a c : Ordinal} (hc : c < a) (b d : Ordinal) :
(a * b + c) / (a * d) = b / d := by
have ha : a ≠ 0 := ((Ordinal.zero_le c).trans_lt hc).ne'
obtain rfl | hd := eq_or_ne d 0
· rw [mul_zero, div_zero, div_zero]
· have H := mul_ne_zero ha hd
apply le_antisymm
· rw [← lt_succ_iff, div_lt H, mul_assoc]
· apply (add_lt_add_left hc _).trans_le
rw [← mul_succ]
apply mul_le_mul_left'
rw [succ_le_iff]
exact lt_mul_succ_div b hd
· rw [le_div H, mul_assoc]
exact (mul_le_mul_left' (mul_div_le b d) a).trans (le_add_right _ c)
theorem mul_div_mul_cancel {a : Ordinal} (ha : a ≠ 0) (b c) : a * b / (a * c) = b / c := by
convert mul_add_div_mul (Ordinal.pos_iff_ne_zero.2 ha) b c using 1
rw [add_zero]
@[simp]
theorem div_one (a : Ordinal) : a / 1 = a := by
simpa only [one_mul] using mul_div_cancel a Ordinal.one_ne_zero
@[simp]
theorem div_self {a : Ordinal} (h : a ≠ 0) : a / a = 1 := by
simpa only [mul_one] using mul_div_cancel 1 h
theorem mul_sub (a b c : Ordinal) : a * (b - c) = a * b - a * c :=
if a0 : a = 0 then by simp only [a0, zero_mul, sub_self]
else
eq_of_forall_ge_iff fun d => by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0]
theorem isLimit_add_iff {a b} : IsLimit (a + b) ↔ IsLimit b ∨ b = 0 ∧ IsLimit a := by
constructor <;> intro h
· by_cases h' : b = 0
· rw [h', add_zero] at h
right
exact ⟨h', h⟩
left
rw [← add_sub_cancel a b]
apply isLimit_sub h
suffices a + 0 < a + b by simpa only [add_zero] using this
rwa [add_lt_add_iff_left, Ordinal.pos_iff_ne_zero]
rcases h with (h | ⟨rfl, h⟩)
· exact isLimit_add a h
· simpa only [add_zero]
theorem dvd_add_iff : ∀ {a b c : Ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c)
| a, _, c, ⟨b, rfl⟩ =>
⟨fun ⟨d, e⟩ => ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, fun ⟨d, e⟩ => by
rw [e, ← mul_add]
apply dvd_mul_right⟩
theorem div_mul_cancel : ∀ {a b : Ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b
| a, _, a0, ⟨b, rfl⟩ => by rw [mul_div_cancel _ a0]
theorem le_of_dvd : ∀ {a b : Ordinal}, b ≠ 0 → a ∣ b → a ≤ b
-- Porting note: `⟨b, rfl⟩ => by` → `⟨b, e⟩ => by subst e`
| a, _, b0, ⟨b, e⟩ => by
subst e
-- Porting note: `Ne` is required.
simpa only [mul_one] using
mul_le_mul_left'
(one_le_iff_ne_zero.2 fun h : b = 0 => by
simp only [h, mul_zero, Ne, not_true_eq_false] at b0) a
| theorem dvd_antisymm {a b : Ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b :=
if a0 : a = 0 then by subst a; exact (eq_zero_of_zero_dvd h₁).symm
| Mathlib/SetTheory/Ordinal/Arithmetic.lean | 959 | 960 |
/-
Copyright (c) 2021 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison
-/
import Mathlib.Data.Complex.Norm
/-!
# The partial order on the complex numbers
This order is defined by `z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im`.
This is a natural order on `ℂ` because, as is well-known, there does not exist an order on `ℂ`
making it into a `LinearOrderedField`. However, the order described above is the canonical order
stemming from the structure of `ℂ` as a ⋆-ring (i.e., it becomes a `StarOrderedRing`). Moreover,
with this order `ℂ` is a `StrictOrderedCommRing` and the coercion `(↑) : ℝ → ℂ` is an order
embedding.
This file only provides `Complex.partialOrder` and lemmas about it. Further structural classes are
provided by `Mathlib/Data/RCLike/Basic.lean` as
* `RCLike.toStrictOrderedCommRing`
* `RCLike.toStarOrderedRing`
* `RCLike.toOrderedSMul`
These are all only available with `open scoped ComplexOrder`.
-/
namespace Complex
/-- We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative.
Complex numbers with different imaginary parts are incomparable.
-/
protected def partialOrder : PartialOrder ℂ where
le z w := z.re ≤ w.re ∧ z.im = w.im
lt z w := z.re < w.re ∧ z.im = w.im
lt_iff_le_not_le z w := by
rw [lt_iff_le_not_le]
tauto
le_refl _ := ⟨le_rfl, rfl⟩
le_trans _ _ _ h₁ h₂ := ⟨h₁.1.trans h₂.1, h₁.2.trans h₂.2⟩
le_antisymm _ _ h₁ h₂ := ext (h₁.1.antisymm h₂.1) h₁.2
namespace _root_.ComplexOrder
scoped[ComplexOrder] attribute [instance] Complex.partialOrder
end _root_.ComplexOrder
open ComplexOrder
theorem le_def {z w : ℂ} : z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im :=
Iff.rfl
theorem lt_def {z w : ℂ} : z < w ↔ z.re < w.re ∧ z.im = w.im :=
Iff.rfl
theorem nonneg_iff {z : ℂ} : 0 ≤ z ↔ 0 ≤ z.re ∧ 0 = z.im :=
le_def
theorem pos_iff {z : ℂ} : 0 < z ↔ 0 < z.re ∧ 0 = z.im :=
lt_def
theorem nonpos_iff {z : ℂ} : z ≤ 0 ↔ z.re ≤ 0 ∧ z.im = 0 :=
le_def
theorem neg_iff {z : ℂ} : z < 0 ↔ z.re < 0 ∧ z.im = 0 :=
lt_def
@[simp, norm_cast]
theorem real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y := by simp [le_def, ofReal]
@[simp, norm_cast]
theorem real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y := by simp [lt_def, ofReal]
@[simp, norm_cast]
theorem zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x :=
real_le_real
@[simp, norm_cast]
theorem zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x :=
real_lt_real
theorem not_le_iff {z w : ℂ} : ¬z ≤ w ↔ w.re < z.re ∨ z.im ≠ w.im := by
rw [le_def, not_and_or, not_le]
theorem not_lt_iff {z w : ℂ} : ¬z < w ↔ w.re ≤ z.re ∨ z.im ≠ w.im := by
rw [lt_def, not_and_or, not_lt]
theorem not_le_zero_iff {z : ℂ} : ¬z ≤ 0 ↔ 0 < z.re ∨ z.im ≠ 0 :=
not_le_iff
theorem not_lt_zero_iff {z : ℂ} : ¬z < 0 ↔ 0 ≤ z.re ∨ z.im ≠ 0 :=
not_lt_iff
theorem eq_re_of_ofReal_le {r : ℝ} {z : ℂ} (hz : (r : ℂ) ≤ z) : z = z.re := by
rw [eq_comm, ← conj_eq_iff_re, conj_eq_iff_im, ← (Complex.le_def.1 hz).2, Complex.ofReal_im]
@[simp]
lemma re_eq_norm {z : ℂ} : z.re = ‖z‖ ↔ 0 ≤ z :=
have : 0 ≤ ‖z‖ := norm_nonneg z
⟨fun h ↦ ⟨h.symm ▸ this, (abs_re_eq_norm.1 <| h.symm ▸ abs_of_nonneg this).symm⟩,
fun ⟨h₁, h₂⟩ ↦ by rw [← abs_re_eq_norm.2 h₂.symm, abs_of_nonneg h₁]⟩
@[simp]
lemma neg_re_eq_norm {z : ℂ} : -z.re = ‖z‖ ↔ z ≤ 0 := by
rw [← neg_re, ← norm_neg z, re_eq_norm]
exact neg_nonneg.and <| eq_comm.trans neg_eq_zero
@[simp]
lemma re_eq_neg_norm {z : ℂ} : z.re = -‖z‖ ↔ z ≤ 0 := by rw [← neg_eq_iff_eq_neg, neg_re_eq_norm]
@[deprecated (since := "2025-02-16")] alias re_eq_abs := re_eq_norm
@[deprecated (since := "2025-02-16")] alias neg_re_eq_abs := neg_re_eq_norm
@[deprecated (since := "2025-02-16")] alias re_eq_neg_abs := re_eq_neg_norm
lemma monotone_ofReal : Monotone ofReal := by
intro x y hxy
simp only [ofRealHom_eq_coe, real_le_real, hxy]
| end Complex
namespace Mathlib.Meta.Positivity
| Mathlib/Data/Complex/Order.lean | 121 | 123 |
/-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Yaël Dillies
-/
import Mathlib.Data.List.Iterate
import Mathlib.GroupTheory.Perm.Cycle.Basic
import Mathlib.GroupTheory.NoncommPiCoprod
import Mathlib.Tactic.Group
/-!
# Cycle factors of a permutation
Let `β` be a `Fintype` and `f : Equiv.Perm β`.
* `Equiv.Perm.cycleOf`: `f.cycleOf x` is the cycle of `f` that `x` belongs to.
* `Equiv.Perm.cycleFactors`: `f.cycleFactors` is a list of disjoint cyclic permutations
that multiply to `f`.
-/
open Equiv Function Finset
variable {ι α β : Type*}
namespace Equiv.Perm
/-!
### `cycleOf`
-/
section CycleOf
variable {f g : Perm α} {x y : α}
/-- `f.cycleOf x` is the cycle of the permutation `f` to which `x` belongs. -/
def cycleOf (f : Perm α) [DecidableRel f.SameCycle] (x : α) : Perm α :=
ofSubtype (subtypePerm f fun _ => sameCycle_apply_right.symm : Perm { y // SameCycle f x y })
theorem cycleOf_apply (f : Perm α) [DecidableRel f.SameCycle] (x y : α) :
cycleOf f x y = if SameCycle f x y then f y else y := by
dsimp only [cycleOf]
split_ifs with h
· apply ofSubtype_apply_of_mem
exact h
· apply ofSubtype_apply_of_not_mem
exact h
theorem cycleOf_inv (f : Perm α) [DecidableRel f.SameCycle] (x : α) :
(cycleOf f x)⁻¹ = cycleOf f⁻¹ x :=
Equiv.ext fun y => by
rw [inv_eq_iff_eq, cycleOf_apply, cycleOf_apply]
split_ifs <;> simp_all [sameCycle_inv, sameCycle_inv_apply_right]
@[simp]
theorem cycleOf_pow_apply_self (f : Perm α) [DecidableRel f.SameCycle] (x : α) :
∀ n : ℕ, (cycleOf f x ^ n) x = (f ^ n) x := by
intro n
induction n with
| zero => rfl
| succ n hn =>
rw [pow_succ', mul_apply, cycleOf_apply, hn, if_pos, pow_succ', mul_apply]
exact ⟨n, rfl⟩
@[simp]
theorem cycleOf_zpow_apply_self (f : Perm α) [DecidableRel f.SameCycle] (x : α) :
∀ n : ℤ, (cycleOf f x ^ n) x = (f ^ n) x := by
intro z
cases z with
| ofNat z => exact cycleOf_pow_apply_self f x z
| negSucc z =>
rw [zpow_negSucc, ← inv_pow, cycleOf_inv, zpow_negSucc, ← inv_pow, cycleOf_pow_apply_self]
theorem SameCycle.cycleOf_apply [DecidableRel f.SameCycle] :
SameCycle f x y → cycleOf f x y = f y :=
ofSubtype_apply_of_mem _
theorem cycleOf_apply_of_not_sameCycle [DecidableRel f.SameCycle] :
¬SameCycle f x y → cycleOf f x y = y :=
ofSubtype_apply_of_not_mem _
theorem SameCycle.cycleOf_eq [DecidableRel f.SameCycle] (h : SameCycle f x y) :
cycleOf f x = cycleOf f y := by
ext z
rw [Equiv.Perm.cycleOf_apply]
split_ifs with hz
· exact (h.symm.trans hz).cycleOf_apply.symm
· exact (cycleOf_apply_of_not_sameCycle (mt h.trans hz)).symm
@[simp]
theorem cycleOf_apply_apply_zpow_self (f : Perm α) [DecidableRel f.SameCycle] (x : α) (k : ℤ) :
cycleOf f x ((f ^ k) x) = (f ^ (k + 1) : Perm α) x := by
rw [SameCycle.cycleOf_apply]
· rw [add_comm, zpow_add, zpow_one, mul_apply]
· exact ⟨k, rfl⟩
@[simp]
theorem cycleOf_apply_apply_pow_self (f : Perm α) [DecidableRel f.SameCycle] (x : α) (k : ℕ) :
cycleOf f x ((f ^ k) x) = (f ^ (k + 1) : Perm α) x := by
convert cycleOf_apply_apply_zpow_self f x k using 1
@[simp]
theorem cycleOf_apply_apply_self (f : Perm α) [DecidableRel f.SameCycle] (x : α) :
cycleOf f x (f x) = f (f x) := by
convert cycleOf_apply_apply_pow_self f x 1 using 1
@[simp]
theorem cycleOf_apply_self (f : Perm α) [DecidableRel f.SameCycle] (x : α) : cycleOf f x x = f x :=
SameCycle.rfl.cycleOf_apply
theorem IsCycle.cycleOf_eq [DecidableRel f.SameCycle]
(hf : IsCycle f) (hx : f x ≠ x) : cycleOf f x = f :=
Equiv.ext fun y =>
if h : SameCycle f x y then by rw [h.cycleOf_apply]
else by
rw [cycleOf_apply_of_not_sameCycle h,
Classical.not_not.1 (mt ((isCycle_iff_sameCycle hx).1 hf).2 h)]
@[simp]
theorem cycleOf_eq_one_iff (f : Perm α) [DecidableRel f.SameCycle] : cycleOf f x = 1 ↔ f x = x := by
simp_rw [Perm.ext_iff, cycleOf_apply, one_apply]
refine ⟨fun h => (if_pos (SameCycle.refl f x)).symm.trans (h x), fun h y => ?_⟩
by_cases hy : f y = y
· rw [hy, ite_self]
· exact if_neg (mt SameCycle.apply_eq_self_iff (by tauto))
@[simp]
theorem cycleOf_self_apply (f : Perm α) [DecidableRel f.SameCycle] (x : α) :
cycleOf f (f x) = cycleOf f x :=
(sameCycle_apply_right.2 SameCycle.rfl).symm.cycleOf_eq
@[simp]
theorem cycleOf_self_apply_pow (f : Perm α) [DecidableRel f.SameCycle] (n : ℕ) (x : α) :
cycleOf f ((f ^ n) x) = cycleOf f x :=
SameCycle.rfl.pow_left.cycleOf_eq
@[simp]
theorem cycleOf_self_apply_zpow (f : Perm α) [DecidableRel f.SameCycle] (n : ℤ) (x : α) :
cycleOf f ((f ^ n) x) = cycleOf f x :=
SameCycle.rfl.zpow_left.cycleOf_eq
protected theorem IsCycle.cycleOf [DecidableRel f.SameCycle] [DecidableEq α]
(hf : IsCycle f) : cycleOf f x = if f x = x then 1 else f := by
by_cases hx : f x = x
· rwa [if_pos hx, cycleOf_eq_one_iff]
· rwa [if_neg hx, hf.cycleOf_eq]
theorem cycleOf_one [DecidableRel (1 : Perm α).SameCycle] (x : α) :
cycleOf 1 x = 1 := (cycleOf_eq_one_iff 1).mpr rfl
theorem isCycle_cycleOf (f : Perm α) [DecidableRel f.SameCycle] (hx : f x ≠ x) :
IsCycle (cycleOf f x) :=
have : cycleOf f x x ≠ x := by rwa [SameCycle.rfl.cycleOf_apply]
(isCycle_iff_sameCycle this).2 @fun y =>
⟨fun h => mt h.apply_eq_self_iff.2 this, fun h =>
if hxy : SameCycle f x y then
let ⟨i, hi⟩ := hxy
⟨i, by rw [cycleOf_zpow_apply_self, hi]⟩
else by
rw [cycleOf_apply_of_not_sameCycle hxy] at h
exact (h rfl).elim⟩
theorem pow_mod_orderOf_cycleOf_apply (f : Perm α) [DecidableRel f.SameCycle] (n : ℕ) (x : α) :
(f ^ (n % orderOf (cycleOf f x))) x = (f ^ n) x := by
rw [← cycleOf_pow_apply_self f, ← cycleOf_pow_apply_self f, pow_mod_orderOf]
theorem cycleOf_mul_of_apply_right_eq_self [DecidableRel f.SameCycle]
[DecidableRel (f * g).SameCycle]
(h : Commute f g) (x : α) (hx : g x = x) : (f * g).cycleOf x = f.cycleOf x := by
ext y
by_cases hxy : (f * g).SameCycle x y
· obtain ⟨z, rfl⟩ := hxy
rw [cycleOf_apply_apply_zpow_self]
simp [h.mul_zpow, zpow_apply_eq_self_of_apply_eq_self hx]
· rw [cycleOf_apply_of_not_sameCycle hxy, cycleOf_apply_of_not_sameCycle]
contrapose! hxy
obtain ⟨z, rfl⟩ := hxy
refine ⟨z, ?_⟩
simp [h.mul_zpow, zpow_apply_eq_self_of_apply_eq_self hx]
theorem Disjoint.cycleOf_mul_distrib [DecidableRel f.SameCycle] [DecidableRel g.SameCycle]
[DecidableRel (f * g).SameCycle] [DecidableRel (g * f).SameCycle] (h : f.Disjoint g) (x : α) :
(f * g).cycleOf x = f.cycleOf x * g.cycleOf x := by
rcases (disjoint_iff_eq_or_eq.mp h) x with hfx | hgx
· simp [h.commute.eq, cycleOf_mul_of_apply_right_eq_self h.symm.commute, hfx]
· simp [cycleOf_mul_of_apply_right_eq_self h.commute, hgx]
private theorem mem_support_cycleOf_iff_aux [DecidableRel f.SameCycle] [DecidableEq α] [Fintype α] :
y ∈ support (f.cycleOf x) ↔ SameCycle f x y ∧ x ∈ support f := by
by_cases hx : f x = x
· rw [(cycleOf_eq_one_iff _).mpr hx]
simp [hx]
· rw [mem_support, cycleOf_apply]
split_ifs with hy
· simp only [hx, hy, Ne, not_false_iff, and_self_iff, mem_support]
rcases hy with ⟨k, rfl⟩
rw [← not_mem_support]
simpa using hx
· simpa [hx] using hy
private theorem mem_support_cycleOf_iff'_aux (hx : f x ≠ x)
[DecidableRel f.SameCycle] [DecidableEq α] [Fintype α] :
y ∈ support (f.cycleOf x) ↔ SameCycle f x y := by
rw [mem_support_cycleOf_iff_aux, and_iff_left (mem_support.2 hx)]
/-- `x` is in the support of `f` iff `Equiv.Perm.cycle_of f x` is a cycle. -/
theorem isCycle_cycleOf_iff (f : Perm α) [DecidableRel f.SameCycle] :
IsCycle (cycleOf f x) ↔ f x ≠ x := by
refine ⟨fun hx => ?_, f.isCycle_cycleOf⟩
rw [Ne, ← cycleOf_eq_one_iff f]
exact hx.ne_one
private theorem isCycleOn_support_cycleOf_aux [DecidableEq α] [Fintype α] (f : Perm α)
[DecidableRel f.SameCycle] (x : α) : f.IsCycleOn (f.cycleOf x).support :=
⟨f.bijOn <| by
refine fun _ ↦
⟨fun h ↦ mem_support_cycleOf_iff_aux.2 ?_, fun h ↦ mem_support_cycleOf_iff_aux.2 ?_⟩
· exact ⟨sameCycle_apply_right.1 (mem_support_cycleOf_iff_aux.1 h).1,
(mem_support_cycleOf_iff_aux.1 h).2⟩
· exact ⟨sameCycle_apply_right.2 (mem_support_cycleOf_iff_aux.1 h).1,
(mem_support_cycleOf_iff_aux.1 h).2⟩
, fun a ha b hb =>
by
rw [mem_coe, mem_support_cycleOf_iff_aux] at ha hb
exact ha.1.symm.trans hb.1⟩
private theorem SameCycle.exists_pow_eq_of_mem_support_aux {f} [DecidableEq α] [Fintype α]
[DecidableRel f.SameCycle] (h : SameCycle f x y) (hx : x ∈ f.support) :
∃ i < #(f.cycleOf x).support, (f ^ i) x = y := by
rw [mem_support] at hx
exact Equiv.Perm.IsCycleOn.exists_pow_eq (b := y) (f.isCycleOn_support_cycleOf_aux x)
(by rw [mem_support_cycleOf_iff'_aux hx]) (by rwa [mem_support_cycleOf_iff'_aux hx])
instance instDecidableRelSameCycle [DecidableEq α] [Fintype α] (f : Perm α) :
DecidableRel (SameCycle f) := fun x y =>
decidable_of_iff (y ∈ List.iterate f x (Fintype.card α)) <| by
simp only [List.mem_iterate, iterate_eq_pow, eq_comm (a := y)]
constructor
· rintro ⟨n, _, hn⟩
exact ⟨n, hn⟩
· intro hxy
by_cases hx : x ∈ f.support
case pos =>
-- we can't invoke the aux lemmas above without obtaining the decidable instance we are
-- already building; but now we've left the data, so we can do this non-constructively
-- without sacrificing computability.
let _inst (f : Perm α) : DecidableRel (SameCycle f) := Classical.decRel _
rcases hxy.exists_pow_eq_of_mem_support_aux hx with ⟨i, hixy, hi⟩
refine ⟨i, lt_of_lt_of_le hixy (card_le_univ _), hi⟩
case neg =>
haveI : Nonempty α := ⟨x⟩
rw [not_mem_support] at hx
exact ⟨0, Fintype.card_pos, hxy.eq_of_left hx⟩
@[simp]
theorem two_le_card_support_cycleOf_iff [DecidableEq α] [Fintype α] :
2 ≤ #(cycleOf f x).support ↔ f x ≠ x := by
refine ⟨fun h => ?_, fun h => by simpa using (isCycle_cycleOf _ h).two_le_card_support⟩
contrapose! h
rw [← cycleOf_eq_one_iff] at h
simp [h]
@[simp] lemma support_cycleOf_nonempty [DecidableEq α] [Fintype α] :
(cycleOf f x).support.Nonempty ↔ f x ≠ x := by
rw [← two_le_card_support_cycleOf_iff, ← card_pos, ← Nat.succ_le_iff]
exact ⟨fun h => Or.resolve_left h.eq_or_lt (card_support_ne_one _).symm, zero_lt_two.trans_le⟩
theorem mem_support_cycleOf_iff [DecidableEq α] [Fintype α] :
y ∈ support (f.cycleOf x) ↔ SameCycle f x y ∧ x ∈ support f :=
mem_support_cycleOf_iff_aux
theorem mem_support_cycleOf_iff' (hx : f x ≠ x) [DecidableEq α] [Fintype α] :
y ∈ support (f.cycleOf x) ↔ SameCycle f x y :=
mem_support_cycleOf_iff'_aux hx
theorem sameCycle_iff_cycleOf_eq_of_mem_support [DecidableEq α] [Fintype α]
{g : Perm α} {x y : α} (hx : x ∈ g.support) (hy : y ∈ g.support) :
g.SameCycle x y ↔ g.cycleOf x = g.cycleOf y := by
refine ⟨SameCycle.cycleOf_eq, fun h ↦ ?_⟩
rw [← mem_support_cycleOf_iff' (mem_support.mp hx), h,
mem_support_cycleOf_iff' (mem_support.mp hy)]
theorem support_cycleOf_eq_nil_iff [DecidableEq α] [Fintype α] :
(f.cycleOf x).support = ∅ ↔ x ∉ f.support := by simp
theorem isCycleOn_support_cycleOf [DecidableEq α] [Fintype α] (f : Perm α) (x : α) :
f.IsCycleOn (f.cycleOf x).support :=
isCycleOn_support_cycleOf_aux f x
theorem SameCycle.exists_pow_eq_of_mem_support {f} [DecidableEq α] [Fintype α] (h : SameCycle f x y)
(hx : x ∈ f.support) : ∃ i < #(f.cycleOf x).support, (f ^ i) x = y :=
h.exists_pow_eq_of_mem_support_aux hx
theorem support_cycleOf_le [DecidableEq α] [Fintype α] (f : Perm α) (x : α) :
support (f.cycleOf x) ≤ support f := by
intro y hy
rw [mem_support, cycleOf_apply] at hy
split_ifs at hy
· exact mem_support.mpr hy
· exact absurd rfl hy
theorem SameCycle.mem_support_iff {f} [DecidableEq α] [Fintype α] (h : SameCycle f x y) :
x ∈ support f ↔ y ∈ support f :=
⟨fun hx => support_cycleOf_le f x (mem_support_cycleOf_iff.mpr ⟨h, hx⟩), fun hy =>
support_cycleOf_le f y (mem_support_cycleOf_iff.mpr ⟨h.symm, hy⟩)⟩
theorem pow_mod_card_support_cycleOf_self_apply [DecidableEq α] [Fintype α]
(f : Perm α) (n : ℕ) (x : α) : (f ^ (n % #(f.cycleOf x).support)) x = (f ^ n) x := by
by_cases hx : f x = x
· rw [pow_apply_eq_self_of_apply_eq_self hx, pow_apply_eq_self_of_apply_eq_self hx]
· rw [← cycleOf_pow_apply_self, ← cycleOf_pow_apply_self f, ← (isCycle_cycleOf f hx).orderOf,
pow_mod_orderOf]
theorem SameCycle.exists_pow_eq [DecidableEq α] [Fintype α] (f : Perm α) (h : SameCycle f x y) :
∃ i : ℕ, 0 < i ∧ i ≤ #(f.cycleOf x).support + 1 ∧ (f ^ i) x = y := by
by_cases hx : x ∈ f.support
· obtain ⟨k, hk, hk'⟩ := h.exists_pow_eq_of_mem_support hx
rcases k with - | k
· refine ⟨#(f.cycleOf x).support, ?_, self_le_add_right _ _, ?_⟩
· refine zero_lt_one.trans (one_lt_card_support_of_ne_one ?_)
simpa using hx
· simp only [pow_zero, coe_one, id_eq] at hk'
subst hk'
rw [← (isCycle_cycleOf _ <| mem_support.1 hx).orderOf, ← cycleOf_pow_apply_self,
pow_orderOf_eq_one, one_apply]
· exact ⟨k + 1, by simp, Nat.le_succ_of_le hk.le, hk'⟩
· refine ⟨1, zero_lt_one, by simp, ?_⟩
obtain ⟨k, rfl⟩ := h
rw [not_mem_support] at hx
rw [pow_apply_eq_self_of_apply_eq_self hx, zpow_apply_eq_self_of_apply_eq_self hx]
theorem zpow_eq_zpow_on_iff [DecidableEq α] [Fintype α]
(g : Perm α) {m n : ℤ} {x : α} (hx : g x ≠ x) :
(g ^ m) x = (g ^ n) x ↔ m % #(g.cycleOf x).support = n % #(g.cycleOf x).support := by
rw [Int.emod_eq_emod_iff_emod_sub_eq_zero]
conv_lhs => rw [← Int.sub_add_cancel m n, Int.add_comm, zpow_add]
simp only [coe_mul, Function.comp_apply, EmbeddingLike.apply_eq_iff_eq]
rw [← Int.dvd_iff_emod_eq_zero]
rw [← cycleOf_zpow_apply_self g x, cycle_zpow_mem_support_iff]
· rw [← Int.dvd_iff_emod_eq_zero]
· exact isCycle_cycleOf g hx
· simp only [mem_support, cycleOf_apply_self]; exact hx
end CycleOf
/-!
### `cycleFactors`
-/
section cycleFactors
open scoped List in
/-- Given a list `l : List α` and a permutation `f : Perm α` whose nonfixed points are all in `l`,
recursively factors `f` into cycles. -/
def cycleFactorsAux [DecidableEq α] [Fintype α]
(l : List α) (f : Perm α) (h : ∀ {x}, f x ≠ x → x ∈ l) :
{ pl : List (Perm α) // pl.prod = f ∧ (∀ g ∈ pl, IsCycle g) ∧ pl.Pairwise Disjoint } :=
go l f h (fun _ => rfl)
where
/-- The auxiliary of `cycleFactorsAux`. This functions separates cycles from `f` instead of `g`
to prevent the process of a cycle gets complex. -/
go (l : List α) (g : Perm α) (hg : ∀ {x}, g x ≠ x → x ∈ l)
(hfg : ∀ {x}, g x ≠ x → cycleOf f x = cycleOf g x) :
{ pl : List (Perm α) // pl.prod = g ∧ (∀ g' ∈ pl, IsCycle g') ∧ pl.Pairwise Disjoint } :=
match l with
| [] => ⟨[], by
{ simp only [imp_false, List.Pairwise.nil, List.not_mem_nil, forall_const, and_true,
forall_prop_of_false, Classical.not_not, not_false_iff, List.prod_nil] at *
ext
simp [*]}⟩
| x :: l =>
if hx : g x = x then go l g (by
intro y hy; exact List.mem_of_ne_of_mem (fun h => hy (by rwa [h])) (hg hy)) hfg
else
let ⟨m, hm₁, hm₂, hm₃⟩ :=
go l ((cycleOf f x)⁻¹ * g) (by
rw [hfg hx]
intro y hy
exact List.mem_of_ne_of_mem
(fun h : y = x => by
rw [h, mul_apply, Ne, inv_eq_iff_eq, cycleOf_apply_self] at hy
exact hy rfl)
(hg fun h : g y = y => by
rw [mul_apply, h, Ne, inv_eq_iff_eq, cycleOf_apply] at hy
split_ifs at hy <;> tauto))
(by
rw [hfg hx]
intro y hy
simp [inv_eq_iff_eq, cycleOf_apply, eq_comm (a := g y)] at hy
rw [hfg (Ne.symm hy.right), ← mul_inv_eq_one (a := g.cycleOf y), cycleOf_inv]
simp_rw [mul_inv_rev]
rw [inv_inv, cycleOf_mul_of_apply_right_eq_self, ← cycleOf_inv, mul_inv_eq_one]
· rw [Commute.inv_left_iff, commute_iff_eq]
ext z; by_cases hz : SameCycle g x z
· simp [cycleOf_apply, hz]
· simp [cycleOf_apply_of_not_sameCycle, hz]
· exact cycleOf_apply_of_not_sameCycle hy.left)
⟨cycleOf f x :: m, by
rw [hfg hx] at hm₁ ⊢
constructor
· rw [List.prod_cons, hm₁]
simp
· exact
⟨fun g' hg' =>
((List.mem_cons).1 hg').elim (fun hg' => hg'.symm ▸ isCycle_cycleOf _ hx) (hm₂ g'),
List.pairwise_cons.2
⟨fun g' hg' y =>
or_iff_not_imp_left.2 fun hgy =>
have hxy : SameCycle g x y :=
Classical.not_not.1 (mt cycleOf_apply_of_not_sameCycle hgy)
have hg'm : (g' :: m.erase g') ~ m :=
List.cons_perm_iff_perm_erase.2 ⟨hg', List.Perm.refl _⟩
have : ∀ h ∈ m.erase g', Disjoint g' h :=
(List.pairwise_cons.1 ((hg'm.pairwise_iff Disjoint.symm).2 hm₃)).1
by_cases id fun hg'y : g' y ≠ y =>
(disjoint_prod_right _ this y).resolve_right <| by
have hsc : SameCycle g⁻¹ x (g y) := by
rwa [sameCycle_inv, sameCycle_apply_right]
rw [disjoint_prod_perm hm₃ hg'm.symm, List.prod_cons,
← eq_inv_mul_iff_mul_eq] at hm₁
rwa [hm₁, mul_apply, mul_apply, cycleOf_inv, hsc.cycleOf_apply,
inv_apply_self, inv_eq_iff_eq, eq_comm],
hm₃⟩⟩⟩
theorem mem_list_cycles_iff {α : Type*} [Finite α] {l : List (Perm α)}
(h1 : ∀ σ : Perm α, σ ∈ l → σ.IsCycle) (h2 : l.Pairwise Disjoint) {σ : Perm α} :
σ ∈ l ↔ σ.IsCycle ∧ ∀ a, σ a ≠ a → σ a = l.prod a := by
suffices σ.IsCycle → (σ ∈ l ↔ ∀ a, σ a ≠ a → σ a = l.prod a) by
exact ⟨fun hσ => ⟨h1 σ hσ, (this (h1 σ hσ)).mp hσ⟩, fun hσ => (this hσ.1).mpr hσ.2⟩
intro h3
classical
cases nonempty_fintype α
constructor
· intro h a ha
exact eq_on_support_mem_disjoint h h2 _ (mem_support.mpr ha)
· intro h
have hσl : σ.support ⊆ l.prod.support := by
intro x hx
rw [mem_support] at hx
rwa [mem_support, ← h _ hx]
obtain ⟨a, ha, -⟩ := id h3
rw [← mem_support] at ha
obtain ⟨τ, hτ, hτa⟩ := exists_mem_support_of_mem_support_prod (hσl ha)
have hτl : ∀ x ∈ τ.support, τ x = l.prod x := eq_on_support_mem_disjoint hτ h2
have key : ∀ x ∈ σ.support ∩ τ.support, σ x = τ x := by
intro x hx
rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hτl x (mem_of_mem_inter_right hx)]
convert hτ
refine h3.eq_on_support_inter_nonempty_congr (h1 _ hτ) key ?_ ha
exact key a (mem_inter_of_mem ha hτa)
open scoped List in
theorem list_cycles_perm_list_cycles {α : Type*} [Finite α] {l₁ l₂ : List (Perm α)}
(h₀ : l₁.prod = l₂.prod) (h₁l₁ : ∀ σ : Perm α, σ ∈ l₁ → σ.IsCycle)
(h₁l₂ : ∀ σ : Perm α, σ ∈ l₂ → σ.IsCycle) (h₂l₁ : l₁.Pairwise Disjoint)
(h₂l₂ : l₂.Pairwise Disjoint) : l₁ ~ l₂ := by
classical
refine
(List.perm_ext_iff_of_nodup (nodup_of_pairwise_disjoint_cycles h₁l₁ h₂l₁)
(nodup_of_pairwise_disjoint_cycles h₁l₂ h₂l₂)).mpr
fun σ => ?_
by_cases hσ : σ.IsCycle
· obtain _ := not_forall.mp (mt ext hσ.ne_one)
rw [mem_list_cycles_iff h₁l₁ h₂l₁, mem_list_cycles_iff h₁l₂ h₂l₂, h₀]
· exact iff_of_false (mt (h₁l₁ σ) hσ) (mt (h₁l₂ σ) hσ)
/-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/
def cycleFactors [Fintype α] [LinearOrder α] (f : Perm α) :
{ l : List (Perm α) // l.prod = f ∧ (∀ g ∈ l, IsCycle g) ∧ l.Pairwise Disjoint } :=
cycleFactorsAux (sort (α := α) (· ≤ ·) univ) f (fun {_ _} ↦ (mem_sort _).2 (mem_univ _))
/-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`,
without a linear order. -/
def truncCycleFactors [DecidableEq α] [Fintype α] (f : Perm α) :
Trunc { l : List (Perm α) // l.prod = f ∧ (∀ g ∈ l, IsCycle g) ∧ l.Pairwise Disjoint } :=
Quotient.recOnSubsingleton (@univ α _).1 (fun l h => Trunc.mk (cycleFactorsAux l f (h _)))
(show ∀ x, f x ≠ x → x ∈ (@univ α _).1 from fun _ _ => mem_univ _)
section CycleFactorsFinset
variable [DecidableEq α] [Fintype α] (f : Perm α)
/-- Factors a permutation `f` into a `Finset` of disjoint cyclic permutations that multiply to `f`.
-/
def cycleFactorsFinset : Finset (Perm α) :=
(truncCycleFactors f).lift
(fun l : { l : List (Perm α) // l.prod = f ∧ (∀ g ∈ l, IsCycle g) ∧ l.Pairwise Disjoint } =>
l.val.toFinset)
fun ⟨_, hl⟩ ⟨_, hl'⟩ =>
List.toFinset_eq_of_perm _ _
(list_cycles_perm_list_cycles (hl'.left.symm ▸ hl.left) hl.right.left hl'.right.left
hl.right.right hl'.right.right)
open scoped List in
theorem cycleFactorsFinset_eq_list_toFinset {σ : Perm α} {l : List (Perm α)} (hn : l.Nodup) :
σ.cycleFactorsFinset = l.toFinset ↔
(∀ f : Perm α, f ∈ l → f.IsCycle) ∧ l.Pairwise Disjoint ∧ l.prod = σ := by
obtain ⟨⟨l', hp', hc', hd'⟩, hl⟩ := Trunc.exists_rep σ.truncCycleFactors
have ht : cycleFactorsFinset σ = l'.toFinset := by
rw [cycleFactorsFinset, ← hl, Trunc.lift_mk]
rw [ht]
constructor
· intro h
have hn' : l'.Nodup := nodup_of_pairwise_disjoint_cycles hc' hd'
have hperm : l ~ l' := List.perm_of_nodup_nodup_toFinset_eq hn hn' h.symm
refine ⟨?_, ?_, ?_⟩
· exact fun _ h => hc' _ (hperm.subset h)
· have := List.Perm.pairwise_iff (@Disjoint.symmetric _) hperm
rwa [this]
· rw [← hp', hperm.symm.prod_eq']
refine hd'.imp ?_
exact Disjoint.commute
· rintro ⟨hc, hd, hp⟩
refine List.toFinset_eq_of_perm _ _ ?_
refine list_cycles_perm_list_cycles ?_ hc' hc hd' hd
rw [hp, hp']
theorem cycleFactorsFinset_eq_finset {σ : Perm α} {s : Finset (Perm α)} :
σ.cycleFactorsFinset = s ↔
(∀ f : Perm α, f ∈ s → f.IsCycle) ∧
∃ h : (s : Set (Perm α)).Pairwise Disjoint,
s.noncommProd id (h.mono' fun _ _ => Disjoint.commute) = σ := by
obtain ⟨l, hl, rfl⟩ := s.exists_list_nodup_eq
simp [cycleFactorsFinset_eq_list_toFinset, hl]
theorem cycleFactorsFinset_pairwise_disjoint :
(cycleFactorsFinset f : Set (Perm α)).Pairwise Disjoint :=
(cycleFactorsFinset_eq_finset.mp rfl).2.choose
/-- Two cycles of a permutation commute. -/
theorem cycleFactorsFinset_mem_commute : (cycleFactorsFinset f : Set (Perm α)).Pairwise Commute :=
(cycleFactorsFinset_pairwise_disjoint _).mono' fun _ _ => Disjoint.commute
/-- Two cycles of a permutation commute. -/
theorem cycleFactorsFinset_mem_commute' {g1 g2 : Perm α}
(h1 : g1 ∈ f.cycleFactorsFinset) (h2 : g2 ∈ f.cycleFactorsFinset) :
Commute g1 g2 := by
rcases eq_or_ne g1 g2 with rfl | h
· apply Commute.refl
· exact Equiv.Perm.cycleFactorsFinset_mem_commute f h1 h2 h
/-- The product of cycle factors is equal to the original `f : perm α`. -/
theorem cycleFactorsFinset_noncommProd
(comm : (cycleFactorsFinset f : Set (Perm α)).Pairwise Commute :=
cycleFactorsFinset_mem_commute f) :
f.cycleFactorsFinset.noncommProd id comm = f :=
(cycleFactorsFinset_eq_finset.mp rfl).2.choose_spec
theorem mem_cycleFactorsFinset_iff {f p : Perm α} :
p ∈ cycleFactorsFinset f ↔ p.IsCycle ∧ ∀ a ∈ p.support, p a = f a := by
obtain ⟨l, hl, hl'⟩ := f.cycleFactorsFinset.exists_list_nodup_eq
rw [← hl']
rw [eq_comm, cycleFactorsFinset_eq_list_toFinset hl] at hl'
simpa [List.mem_toFinset, Ne, ← hl'.right.right] using
mem_list_cycles_iff hl'.left hl'.right.left
theorem cycleOf_mem_cycleFactorsFinset_iff {f : Perm α} {x : α} :
cycleOf f x ∈ cycleFactorsFinset f ↔ x ∈ f.support := by
rw [mem_cycleFactorsFinset_iff]
constructor
· rintro ⟨hc, _⟩
contrapose! hc
rw [not_mem_support, ← cycleOf_eq_one_iff] at hc
simp [hc]
· intro hx
refine ⟨isCycle_cycleOf _ (mem_support.mp hx), ?_⟩
intro y hy
rw [mem_support] at hy
rw [cycleOf_apply]
split_ifs with H
· rfl
· rw [cycleOf_apply_of_not_sameCycle H] at hy
contradiction
lemma cycleOf_ne_one_iff_mem_cycleFactorsFinset {g : Equiv.Perm α} {x : α} :
g.cycleOf x ≠ 1 ↔ g.cycleOf x ∈ g.cycleFactorsFinset := by
rw [cycleOf_mem_cycleFactorsFinset_iff, mem_support, ne_eq, cycleOf_eq_one_iff]
theorem mem_cycleFactorsFinset_support_le {p f : Perm α} (h : p ∈ cycleFactorsFinset f) :
p.support ≤ f.support := by
rw [mem_cycleFactorsFinset_iff] at h
intro x hx
rwa [mem_support, ← h.right x hx, ← mem_support]
lemma support_zpowers_of_mem_cycleFactorsFinset_le {g : Perm α}
{c : g.cycleFactorsFinset} (v : Subgroup.zpowers (c : Perm α)) :
(v : Perm α).support ≤ g.support := by
obtain ⟨m, hm⟩ := v.prop
simp only [← hm]
exact le_trans (support_zpow_le _ _) (mem_cycleFactorsFinset_support_le c.prop)
|
theorem pairwise_disjoint_of_mem_zpowers :
Pairwise fun (i j : f.cycleFactorsFinset) ↦
∀ (x y : Perm α), x ∈ Subgroup.zpowers ↑i → y ∈ Subgroup.zpowers ↑j → Disjoint x y :=
fun c d hcd ↦ fun x y hx hy ↦ by
obtain ⟨m, hm⟩ := hx; obtain ⟨n, hn⟩ := hy
simp only [← hm, ← hn]
apply Disjoint.zpow_disjoint_zpow
exact f.cycleFactorsFinset_pairwise_disjoint c.prop d.prop (Subtype.coe_ne_coe.mpr hcd)
lemma pairwise_commute_of_mem_zpowers :
Pairwise fun (i j : f.cycleFactorsFinset) ↦
| Mathlib/GroupTheory/Perm/Cycle/Factors.lean | 592 | 603 |
/-
Copyright (c) 2023 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Yury Kudryashov
-/
import Mathlib.Analysis.Calculus.Deriv.Mul
import Mathlib.Analysis.Calculus.Deriv.Comp
/-!
# Derivatives of `x ↦ x⁻¹` and `f x / g x`
In this file we prove `(x⁻¹)' = -1 / x ^ 2`, `((f x)⁻¹)' = -f' x / (f x) ^ 2`, and
`(f x / g x)' = (f' x * g x - f x * g' x) / (g x) ^ 2` for different notions of derivative.
For a more detailed overview of one-dimensional derivatives in mathlib, see the module docstring of
`Analysis/Calculus/Deriv/Basic`.
## Keywords
derivative
-/
universe u
open scoped Topology
open Filter Asymptotics Set
open ContinuousLinearMap (smulRight)
variable {𝕜 : Type u} [NontriviallyNormedField 𝕜] {x : 𝕜} {s : Set 𝕜}
section Inverse
/-! ### Derivative of `x ↦ x⁻¹` -/
theorem hasStrictDerivAt_inv (hx : x ≠ 0) : HasStrictDerivAt Inv.inv (-(x ^ 2)⁻¹) x := by
suffices
(fun p : 𝕜 × 𝕜 => (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) =o[𝓝 (x, x)] fun p =>
(p.1 - p.2) * 1 by
refine .of_isLittleO <| this.congr' ?_ (Eventually.of_forall fun _ => mul_one _)
refine Eventually.mono ((isOpen_ne.prod isOpen_ne).mem_nhds ⟨hx, hx⟩) ?_
rintro ⟨y, z⟩ ⟨hy, hz⟩
simp only [mem_setOf_eq] at hy hz
-- hy : y ≠ 0, hz : z ≠ 0
field_simp [hx, hy, hz]
ring
refine (isBigO_refl (fun p : 𝕜 × 𝕜 => p.1 - p.2) _).mul_isLittleO ((isLittleO_one_iff 𝕜).2 ?_)
rw [← sub_self (x * x)⁻¹]
exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv₀ <| mul_ne_zero hx hx)
theorem hasDerivAt_inv (x_ne_zero : x ≠ 0) : HasDerivAt (fun y => y⁻¹) (-(x ^ 2)⁻¹) x :=
(hasStrictDerivAt_inv x_ne_zero).hasDerivAt
theorem hasDerivWithinAt_inv (x_ne_zero : x ≠ 0) (s : Set 𝕜) :
HasDerivWithinAt (fun x => x⁻¹) (-(x ^ 2)⁻¹) s x :=
(hasDerivAt_inv x_ne_zero).hasDerivWithinAt
theorem differentiableAt_inv_iff : DifferentiableAt 𝕜 (fun x => x⁻¹) x ↔ x ≠ 0 :=
⟨fun H => NormedField.continuousAt_inv.1 H.continuousAt, fun H =>
(hasDerivAt_inv H).differentiableAt⟩
theorem deriv_inv : deriv (fun x => x⁻¹) x = -(x ^ 2)⁻¹ := by
rcases eq_or_ne x 0 with (rfl | hne)
· simp [deriv_zero_of_not_differentiableAt (mt differentiableAt_inv_iff.1 (not_not.2 rfl))]
· exact (hasDerivAt_inv hne).deriv
@[simp]
theorem deriv_inv' : (deriv fun x : 𝕜 => x⁻¹) = fun x => -(x ^ 2)⁻¹ :=
funext fun _ => deriv_inv
theorem derivWithin_inv (x_ne_zero : x ≠ 0) (hxs : UniqueDiffWithinAt 𝕜 s x) :
derivWithin (fun x => x⁻¹) s x = -(x ^ 2)⁻¹ := by
rw [DifferentiableAt.derivWithin (differentiableAt_inv x_ne_zero) hxs]
exact deriv_inv
theorem hasFDerivAt_inv (x_ne_zero : x ≠ 0) :
HasFDerivAt (fun x => x⁻¹) (smulRight (1 : 𝕜 →L[𝕜] 𝕜) (-(x ^ 2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x :=
hasDerivAt_inv x_ne_zero
theorem hasStrictFDerivAt_inv (x_ne_zero : x ≠ 0) :
HasStrictFDerivAt (fun x => x⁻¹) (smulRight (1 : 𝕜 →L[𝕜] 𝕜) (-(x ^ 2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x :=
hasStrictDerivAt_inv x_ne_zero
theorem hasFDerivWithinAt_inv (x_ne_zero : x ≠ 0) :
HasFDerivWithinAt (fun x => x⁻¹) (smulRight (1 : 𝕜 →L[𝕜] 𝕜) (-(x ^ 2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x :=
(hasFDerivAt_inv x_ne_zero).hasFDerivWithinAt
theorem fderiv_inv : fderiv 𝕜 (fun x => x⁻¹) x = smulRight (1 : 𝕜 →L[𝕜] 𝕜) (-(x ^ 2)⁻¹) := by
rw [← deriv_fderiv, deriv_inv]
theorem fderivWithin_inv (x_ne_zero : x ≠ 0) (hxs : UniqueDiffWithinAt 𝕜 s x) :
fderivWithin 𝕜 (fun x => x⁻¹) s x = smulRight (1 : 𝕜 →L[𝕜] 𝕜) (-(x ^ 2)⁻¹) := by
rw [DifferentiableAt.fderivWithin (differentiableAt_inv x_ne_zero) hxs]
exact fderiv_inv
variable {c : 𝕜 → 𝕜} {c' : 𝕜}
|
theorem HasDerivWithinAt.inv (hc : HasDerivWithinAt c c' s x) (hx : c x ≠ 0) :
HasDerivWithinAt (fun y => (c y)⁻¹) (-c' / c x ^ 2) s x := by
convert (hasDerivAt_inv hx).comp_hasDerivWithinAt x hc using 1
| Mathlib/Analysis/Calculus/Deriv/Inv.lean | 98 | 101 |
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import Mathlib.MeasureTheory.Measure.Comap
import Mathlib.MeasureTheory.Measure.QuasiMeasurePreserving
/-!
# Restricting a measure to a subset or a subtype
Given a measure `μ` on a type `α` and a subset `s` of `α`, we define a measure `μ.restrict s` as
the restriction of `μ` to `s` (still as a measure on `α`).
We investigate how this notion interacts with usual operations on measures (sum, pushforward,
pullback), and on sets (inclusion, union, Union).
We also study the relationship between the restriction of a measure to a subtype (given by the
pullback under `Subtype.val`) and the restriction to a set as above.
-/
open scoped ENNReal NNReal Topology
open Set MeasureTheory Measure Filter MeasurableSpace ENNReal Function
variable {R α β δ γ ι : Type*}
namespace MeasureTheory
variable {m0 : MeasurableSpace α} [MeasurableSpace β] [MeasurableSpace γ]
variable {μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : Measure α} {s s' t : Set α}
namespace Measure
/-! ### Restricting a measure -/
/-- Restrict a measure `μ` to a set `s` as an `ℝ≥0∞`-linear map. -/
noncomputable def restrictₗ {m0 : MeasurableSpace α} (s : Set α) : Measure α →ₗ[ℝ≥0∞] Measure α :=
liftLinear (OuterMeasure.restrict s) fun μ s' hs' t => by
suffices μ (s ∩ t) = μ (s ∩ t ∩ s') + μ ((s ∩ t) \ s') by
simpa [← Set.inter_assoc, Set.inter_comm _ s, ← inter_diff_assoc]
exact le_toOuterMeasure_caratheodory _ _ hs' _
/-- Restrict a measure `μ` to a set `s`. -/
noncomputable def restrict {_m0 : MeasurableSpace α} (μ : Measure α) (s : Set α) : Measure α :=
restrictₗ s μ
@[simp]
theorem restrictₗ_apply {_m0 : MeasurableSpace α} (s : Set α) (μ : Measure α) :
restrictₗ s μ = μ.restrict s :=
rfl
/-- This lemma shows that `restrict` and `toOuterMeasure` commute. Note that the LHS has a
restrict on measures and the RHS has a restrict on outer measures. -/
theorem restrict_toOuterMeasure_eq_toOuterMeasure_restrict (h : MeasurableSet s) :
(μ.restrict s).toOuterMeasure = OuterMeasure.restrict s μ.toOuterMeasure := by
simp_rw [restrict, restrictₗ, liftLinear, LinearMap.coe_mk, AddHom.coe_mk,
toMeasure_toOuterMeasure, OuterMeasure.restrict_trim h, μ.trimmed]
theorem restrict_apply₀ (ht : NullMeasurableSet t (μ.restrict s)) : μ.restrict s t = μ (t ∩ s) := by
rw [← restrictₗ_apply, restrictₗ, liftLinear_apply₀ _ ht, OuterMeasure.restrict_apply,
coe_toOuterMeasure]
/-- If `t` is a measurable set, then the measure of `t` with respect to the restriction of
the measure to `s` equals the outer measure of `t ∩ s`. An alternate version requiring that `s`
be measurable instead of `t` exists as `Measure.restrict_apply'`. -/
@[simp]
theorem restrict_apply (ht : MeasurableSet t) : μ.restrict s t = μ (t ∩ s) :=
restrict_apply₀ ht.nullMeasurableSet
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
theorem restrict_mono' {_m0 : MeasurableSpace α} ⦃s s' : Set α⦄ ⦃μ ν : Measure α⦄ (hs : s ≤ᵐ[μ] s')
(hμν : μ ≤ ν) : μ.restrict s ≤ ν.restrict s' :=
Measure.le_iff.2 fun t ht => calc
μ.restrict s t = μ (t ∩ s) := restrict_apply ht
_ ≤ μ (t ∩ s') := (measure_mono_ae <| hs.mono fun _x hx ⟨hxt, hxs⟩ => ⟨hxt, hx hxs⟩)
_ ≤ ν (t ∩ s') := le_iff'.1 hμν (t ∩ s')
_ = ν.restrict s' t := (restrict_apply ht).symm
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
@[mono, gcongr]
theorem restrict_mono {_m0 : MeasurableSpace α} ⦃s s' : Set α⦄ (hs : s ⊆ s') ⦃μ ν : Measure α⦄
(hμν : μ ≤ ν) : μ.restrict s ≤ ν.restrict s' :=
restrict_mono' (ae_of_all _ hs) hμν
@[gcongr]
theorem restrict_mono_measure {_ : MeasurableSpace α} {μ ν : Measure α} (h : μ ≤ ν) (s : Set α) :
μ.restrict s ≤ ν.restrict s :=
restrict_mono subset_rfl h
@[gcongr]
theorem restrict_mono_set {_ : MeasurableSpace α} (μ : Measure α) {s t : Set α} (h : s ⊆ t) :
μ.restrict s ≤ μ.restrict t :=
restrict_mono h le_rfl
theorem restrict_mono_ae (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t :=
restrict_mono' h (le_refl μ)
theorem restrict_congr_set (h : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t :=
le_antisymm (restrict_mono_ae h.le) (restrict_mono_ae h.symm.le)
/-- If `s` is a measurable set, then the outer measure of `t` with respect to the restriction of
the measure to `s` equals the outer measure of `t ∩ s`. This is an alternate version of
`Measure.restrict_apply`, requiring that `s` is measurable instead of `t`. -/
@[simp]
theorem restrict_apply' (hs : MeasurableSet s) : μ.restrict s t = μ (t ∩ s) := by
rw [← toOuterMeasure_apply,
Measure.restrict_toOuterMeasure_eq_toOuterMeasure_restrict hs,
OuterMeasure.restrict_apply s t _, toOuterMeasure_apply]
theorem restrict_apply₀' (hs : NullMeasurableSet s μ) : μ.restrict s t = μ (t ∩ s) := by
rw [← restrict_congr_set hs.toMeasurable_ae_eq,
restrict_apply' (measurableSet_toMeasurable _ _),
measure_congr ((ae_eq_refl t).inter hs.toMeasurable_ae_eq)]
theorem restrict_le_self : μ.restrict s ≤ μ :=
Measure.le_iff.2 fun t ht => calc
μ.restrict s t = μ (t ∩ s) := restrict_apply ht
_ ≤ μ t := measure_mono inter_subset_left
variable (μ)
theorem restrict_eq_self (h : s ⊆ t) : μ.restrict t s = μ s :=
(le_iff'.1 restrict_le_self s).antisymm <|
calc
μ s ≤ μ (toMeasurable (μ.restrict t) s ∩ t) :=
measure_mono (subset_inter (subset_toMeasurable _ _) h)
_ = μ.restrict t s := by
rw [← restrict_apply (measurableSet_toMeasurable _ _), measure_toMeasurable]
@[simp]
theorem restrict_apply_self (s : Set α) : (μ.restrict s) s = μ s :=
restrict_eq_self μ Subset.rfl
variable {μ}
theorem restrict_apply_univ (s : Set α) : μ.restrict s univ = μ s := by
rw [restrict_apply MeasurableSet.univ, Set.univ_inter]
theorem le_restrict_apply (s t : Set α) : μ (t ∩ s) ≤ μ.restrict s t :=
calc
μ (t ∩ s) = μ.restrict s (t ∩ s) := (restrict_eq_self μ inter_subset_right).symm
_ ≤ μ.restrict s t := measure_mono inter_subset_left
theorem restrict_apply_le (s t : Set α) : μ.restrict s t ≤ μ t :=
Measure.le_iff'.1 restrict_le_self _
theorem restrict_apply_superset (h : s ⊆ t) : μ.restrict s t = μ s :=
((measure_mono (subset_univ _)).trans_eq <| restrict_apply_univ _).antisymm
((restrict_apply_self μ s).symm.trans_le <| measure_mono h)
@[simp]
theorem restrict_add {_m0 : MeasurableSpace α} (μ ν : Measure α) (s : Set α) :
(μ + ν).restrict s = μ.restrict s + ν.restrict s :=
(restrictₗ s).map_add μ ν
@[simp]
theorem restrict_zero {_m0 : MeasurableSpace α} (s : Set α) : (0 : Measure α).restrict s = 0 :=
(restrictₗ s).map_zero
@[simp]
theorem restrict_smul {_m0 : MeasurableSpace α} {R : Type*} [SMul R ℝ≥0∞]
[IsScalarTower R ℝ≥0∞ ℝ≥0∞] (c : R) (μ : Measure α) (s : Set α) :
(c • μ).restrict s = c • μ.restrict s := by
simpa only [smul_one_smul] using (restrictₗ s).map_smul (c • 1) μ
theorem restrict_restrict₀ (hs : NullMeasurableSet s (μ.restrict t)) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
ext fun u hu => by
simp only [Set.inter_assoc, restrict_apply hu,
restrict_apply₀ (hu.nullMeasurableSet.inter hs)]
@[simp]
theorem restrict_restrict (hs : MeasurableSet s) : (μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
restrict_restrict₀ hs.nullMeasurableSet
theorem restrict_restrict_of_subset (h : s ⊆ t) : (μ.restrict t).restrict s = μ.restrict s := by
ext1 u hu
rw [restrict_apply hu, restrict_apply hu, restrict_eq_self]
exact inter_subset_right.trans h
theorem restrict_restrict₀' (ht : NullMeasurableSet t μ) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
ext fun u hu => by simp only [restrict_apply hu, restrict_apply₀' ht, inter_assoc]
theorem restrict_restrict' (ht : MeasurableSet t) :
(μ.restrict t).restrict s = μ.restrict (s ∩ t) :=
restrict_restrict₀' ht.nullMeasurableSet
theorem restrict_comm (hs : MeasurableSet s) :
(μ.restrict t).restrict s = (μ.restrict s).restrict t := by
rw [restrict_restrict hs, restrict_restrict' hs, inter_comm]
theorem restrict_apply_eq_zero (ht : MeasurableSet t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := by
rw [restrict_apply ht]
theorem measure_inter_eq_zero_of_restrict (h : μ.restrict s t = 0) : μ (t ∩ s) = 0 :=
nonpos_iff_eq_zero.1 (h ▸ le_restrict_apply _ _)
theorem restrict_apply_eq_zero' (hs : MeasurableSet s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := by
rw [restrict_apply' hs]
@[simp]
theorem restrict_eq_zero : μ.restrict s = 0 ↔ μ s = 0 := by
rw [← measure_univ_eq_zero, restrict_apply_univ]
/-- If `μ s ≠ 0`, then `μ.restrict s ≠ 0`, in terms of `NeZero` instances. -/
instance restrict.neZero [NeZero (μ s)] : NeZero (μ.restrict s) :=
⟨mt restrict_eq_zero.mp <| NeZero.ne _⟩
theorem restrict_zero_set {s : Set α} (h : μ s = 0) : μ.restrict s = 0 :=
restrict_eq_zero.2 h
@[simp]
theorem restrict_empty : μ.restrict ∅ = 0 :=
restrict_zero_set measure_empty
@[simp]
theorem restrict_univ : μ.restrict univ = μ :=
ext fun s hs => by simp [hs]
theorem restrict_inter_add_diff₀ (s : Set α) (ht : NullMeasurableSet t μ) :
μ.restrict (s ∩ t) + μ.restrict (s \ t) = μ.restrict s := by
ext1 u hu
simp only [add_apply, restrict_apply hu, ← inter_assoc, diff_eq]
exact measure_inter_add_diff₀ (u ∩ s) ht
theorem restrict_inter_add_diff (s : Set α) (ht : MeasurableSet t) :
μ.restrict (s ∩ t) + μ.restrict (s \ t) = μ.restrict s :=
restrict_inter_add_diff₀ s ht.nullMeasurableSet
theorem restrict_union_add_inter₀ (s : Set α) (ht : NullMeasurableSet t μ) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t := by
rw [← restrict_inter_add_diff₀ (s ∪ t) ht, union_inter_cancel_right, union_diff_right, ←
restrict_inter_add_diff₀ s ht, add_comm, ← add_assoc, add_right_comm]
theorem restrict_union_add_inter (s : Set α) (ht : MeasurableSet t) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t :=
restrict_union_add_inter₀ s ht.nullMeasurableSet
theorem restrict_union_add_inter' (hs : MeasurableSet s) (t : Set α) :
μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t := by
simpa only [union_comm, inter_comm, add_comm] using restrict_union_add_inter t hs
theorem restrict_union₀ (h : AEDisjoint μ s t) (ht : NullMeasurableSet t μ) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t := by
simp [← restrict_union_add_inter₀ s ht, restrict_zero_set h]
theorem restrict_union (h : Disjoint s t) (ht : MeasurableSet t) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t :=
restrict_union₀ h.aedisjoint ht.nullMeasurableSet
theorem restrict_union' (h : Disjoint s t) (hs : MeasurableSet s) :
μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t := by
rw [union_comm, restrict_union h.symm hs, add_comm]
@[simp]
theorem restrict_add_restrict_compl (hs : MeasurableSet s) :
μ.restrict s + μ.restrict sᶜ = μ := by
rw [← restrict_union (@disjoint_compl_right (Set α) _ _) hs.compl, union_compl_self,
restrict_univ]
@[simp]
theorem restrict_compl_add_restrict (hs : MeasurableSet s) : μ.restrict sᶜ + μ.restrict s = μ := by
rw [add_comm, restrict_add_restrict_compl hs]
theorem restrict_union_le (s s' : Set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' :=
le_iff.2 fun t ht ↦ by
simpa [ht, inter_union_distrib_left] using measure_union_le (t ∩ s) (t ∩ s')
theorem restrict_iUnion_apply_ae [Countable ι] {s : ι → Set α} (hd : Pairwise (AEDisjoint μ on s))
(hm : ∀ i, NullMeasurableSet (s i) μ) {t : Set α} (ht : MeasurableSet t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t := by
simp only [restrict_apply, ht, inter_iUnion]
exact
measure_iUnion₀ (hd.mono fun i j h => h.mono inter_subset_right inter_subset_right)
fun i => ht.nullMeasurableSet.inter (hm i)
theorem restrict_iUnion_apply [Countable ι] {s : ι → Set α} (hd : Pairwise (Disjoint on s))
(hm : ∀ i, MeasurableSet (s i)) {t : Set α} (ht : MeasurableSet t) :
μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t :=
restrict_iUnion_apply_ae hd.aedisjoint (fun i => (hm i).nullMeasurableSet) ht
theorem restrict_iUnion_apply_eq_iSup [Countable ι] {s : ι → Set α} (hd : Directed (· ⊆ ·) s)
{t : Set α} (ht : MeasurableSet t) : μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t := by
simp only [restrict_apply ht, inter_iUnion]
rw [Directed.measure_iUnion]
exacts [hd.mono_comp _ fun s₁ s₂ => inter_subset_inter_right _]
/-- The restriction of the pushforward measure is the pushforward of the restriction. For a version
assuming only `AEMeasurable`, see `restrict_map_of_aemeasurable`. -/
theorem restrict_map {f : α → β} (hf : Measurable f) {s : Set β} (hs : MeasurableSet s) :
(μ.map f).restrict s = (μ.restrict <| f ⁻¹' s).map f :=
ext fun t ht => by simp [*, hf ht]
theorem restrict_toMeasurable (h : μ s ≠ ∞) : μ.restrict (toMeasurable μ s) = μ.restrict s :=
ext fun t ht => by
rw [restrict_apply ht, restrict_apply ht, inter_comm, measure_toMeasurable_inter ht h,
inter_comm]
theorem restrict_eq_self_of_ae_mem {_m0 : MeasurableSpace α} ⦃s : Set α⦄ ⦃μ : Measure α⦄
(hs : ∀ᵐ x ∂μ, x ∈ s) : μ.restrict s = μ :=
calc
μ.restrict s = μ.restrict univ := restrict_congr_set (eventuallyEq_univ.mpr hs)
_ = μ := restrict_univ
theorem restrict_congr_meas (hs : MeasurableSet s) :
μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, MeasurableSet t → μ t = ν t :=
⟨fun H t hts ht => by
rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht], fun H =>
ext fun t ht => by
rw [restrict_apply ht, restrict_apply ht, H _ inter_subset_right (ht.inter hs)]⟩
theorem restrict_congr_mono (hs : s ⊆ t) (h : μ.restrict t = ν.restrict t) :
μ.restrict s = ν.restrict s := by
rw [← restrict_restrict_of_subset hs, h, restrict_restrict_of_subset hs]
/-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all
measurable subsets of `s ∪ t`. -/
theorem restrict_union_congr :
μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔
μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t := by
refine ⟨fun h ↦ ⟨restrict_congr_mono subset_union_left h,
restrict_congr_mono subset_union_right h⟩, ?_⟩
rintro ⟨hs, ht⟩
ext1 u hu
simp only [restrict_apply hu, inter_union_distrib_left]
rcases exists_measurable_superset₂ μ ν (u ∩ s) with ⟨US, hsub, hm, hμ, hν⟩
calc
μ (u ∩ s ∪ u ∩ t) = μ (US ∪ u ∩ t) :=
measure_union_congr_of_subset hsub hμ.le Subset.rfl le_rfl
_ = μ US + μ ((u ∩ t) \ US) := (measure_add_diff hm.nullMeasurableSet _).symm
_ = restrict μ s u + restrict μ t (u \ US) := by
simp only [restrict_apply, hu, hu.diff hm, hμ, ← inter_comm t, inter_diff_assoc]
_ = restrict ν s u + restrict ν t (u \ US) := by rw [hs, ht]
_ = ν US + ν ((u ∩ t) \ US) := by
simp only [restrict_apply, hu, hu.diff hm, hν, ← inter_comm t, inter_diff_assoc]
_ = ν (US ∪ u ∩ t) := measure_add_diff hm.nullMeasurableSet _
_ = ν (u ∩ s ∪ u ∩ t) := .symm <| measure_union_congr_of_subset hsub hν.le Subset.rfl le_rfl
theorem restrict_finset_biUnion_congr {s : Finset ι} {t : ι → Set α} :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := by
classical
induction' s using Finset.induction_on with i s _ hs; · simp
simp only [forall_eq_or_imp, iUnion_iUnion_eq_or_left, Finset.mem_insert]
rw [restrict_union_congr, ← hs]
theorem restrict_iUnion_congr [Countable ι] {s : ι → Set α} :
μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := by
refine ⟨fun h i => restrict_congr_mono (subset_iUnion _ _) h, fun h => ?_⟩
ext1 t ht
have D : Directed (· ⊆ ·) fun t : Finset ι => ⋃ i ∈ t, s i :=
Monotone.directed_le fun t₁ t₂ ht => biUnion_subset_biUnion_left ht
rw [iUnion_eq_iUnion_finset]
simp only [restrict_iUnion_apply_eq_iSup D ht, restrict_finset_biUnion_congr.2 fun i _ => h i]
theorem restrict_biUnion_congr {s : Set ι} {t : ι → Set α} (hc : s.Countable) :
μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔
∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := by
haveI := hc.toEncodable
simp only [biUnion_eq_iUnion, SetCoe.forall', restrict_iUnion_congr]
theorem restrict_sUnion_congr {S : Set (Set α)} (hc : S.Countable) :
μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := by
rw [sUnion_eq_biUnion, restrict_biUnion_congr hc]
/-- This lemma shows that `Inf` and `restrict` commute for measures. -/
theorem restrict_sInf_eq_sInf_restrict {m0 : MeasurableSpace α} {m : Set (Measure α)}
(hm : m.Nonempty) (ht : MeasurableSet t) :
(sInf m).restrict t = sInf ((fun μ : Measure α => μ.restrict t) '' m) := by
ext1 s hs
simp_rw [sInf_apply hs, restrict_apply hs, sInf_apply (MeasurableSet.inter hs ht),
Set.image_image, restrict_toOuterMeasure_eq_toOuterMeasure_restrict ht, ←
Set.image_image _ toOuterMeasure, ← OuterMeasure.restrict_sInf_eq_sInf_restrict _ (hm.image _),
OuterMeasure.restrict_apply]
theorem exists_mem_of_measure_ne_zero_of_ae (hs : μ s ≠ 0) {p : α → Prop}
(hp : ∀ᵐ x ∂μ.restrict s, p x) : ∃ x, x ∈ s ∧ p x := by
rw [← μ.restrict_apply_self, ← frequently_ae_mem_iff] at hs
exact (hs.and_eventually hp).exists
/-- If a quasi measure preserving map `f` maps a set `s` to a set `t`,
then it is quasi measure preserving with respect to the restrictions of the measures. -/
theorem QuasiMeasurePreserving.restrict {ν : Measure β} {f : α → β}
(hf : QuasiMeasurePreserving f μ ν) {t : Set β} (hmaps : MapsTo f s t) :
QuasiMeasurePreserving f (μ.restrict s) (ν.restrict t) where
measurable := hf.measurable
absolutelyContinuous := by
refine AbsolutelyContinuous.mk fun u hum ↦ ?_
suffices ν (u ∩ t) = 0 → μ (f ⁻¹' u ∩ s) = 0 by simpa [hum, hf.measurable, hf.measurable hum]
refine fun hu ↦ measure_mono_null ?_ (hf.preimage_null hu)
rw [preimage_inter]
gcongr
assumption
/-! ### Extensionality results -/
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `Union`). -/
theorem ext_iff_of_iUnion_eq_univ [Countable ι] {s : ι → Set α} (hs : ⋃ i, s i = univ) :
μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := by
rw [← restrict_iUnion_congr, hs, restrict_univ, restrict_univ]
alias ⟨_, ext_of_iUnion_eq_univ⟩ := ext_iff_of_iUnion_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `biUnion`). -/
theorem ext_iff_of_biUnion_eq_univ {S : Set ι} {s : ι → Set α} (hc : S.Countable)
(hs : ⋃ i ∈ S, s i = univ) : μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) := by
rw [← restrict_biUnion_congr hc, hs, restrict_univ, restrict_univ]
alias ⟨_, ext_of_biUnion_eq_univ⟩ := ext_iff_of_biUnion_eq_univ
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `sUnion`). -/
theorem ext_iff_of_sUnion_eq_univ {S : Set (Set α)} (hc : S.Countable) (hs : ⋃₀ S = univ) :
μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s :=
ext_iff_of_biUnion_eq_univ hc <| by rwa [← sUnion_eq_biUnion]
alias ⟨_, ext_of_sUnion_eq_univ⟩ := ext_iff_of_sUnion_eq_univ
theorem ext_of_generateFrom_of_cover {S T : Set (Set α)} (h_gen : ‹_› = generateFrom S)
(hc : T.Countable) (h_inter : IsPiSystem S) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t ≠ ∞)
(ST_eq : ∀ t ∈ T, ∀ s ∈ S, μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) : μ = ν := by
refine ext_of_sUnion_eq_univ hc hU fun t ht => ?_
ext1 u hu
simp only [restrict_apply hu]
induction u, hu using induction_on_inter h_gen h_inter with
| empty => simp only [Set.empty_inter, measure_empty]
| basic u hu => exact ST_eq _ ht _ hu
| compl u hu ihu =>
have := T_eq t ht
rw [Set.inter_comm] at ihu ⊢
rwa [← measure_inter_add_diff t hu, ← measure_inter_add_diff t hu, ← ihu,
ENNReal.add_right_inj] at this
exact ne_top_of_le_ne_top (htop t ht) (measure_mono Set.inter_subset_left)
| iUnion f hfd hfm ihf =>
simp only [← restrict_apply (hfm _), ← restrict_apply (MeasurableSet.iUnion hfm)] at ihf ⊢
simp only [measure_iUnion hfd hfm, ihf]
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on an increasing spanning sequence of sets in the π-system.
This lemma is formulated using `sUnion`. -/
theorem ext_of_generateFrom_of_cover_subset {S T : Set (Set α)} (h_gen : ‹_› = generateFrom S)
(h_inter : IsPiSystem S) (h_sub : T ⊆ S) (hc : T.Countable) (hU : ⋃₀ T = univ)
(htop : ∀ s ∈ T, μ s ≠ ∞) (h_eq : ∀ s ∈ S, μ s = ν s) : μ = ν := by
refine ext_of_generateFrom_of_cover h_gen hc h_inter hU htop ?_ fun t ht => h_eq t (h_sub ht)
intro t ht s hs; rcases (s ∩ t).eq_empty_or_nonempty with H | H
· simp only [H, measure_empty]
· exact h_eq _ (h_inter _ hs _ (h_sub ht) H)
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on an increasing spanning sequence of sets in the π-system.
This lemma is formulated using `iUnion`.
`FiniteSpanningSetsIn.ext` is a reformulation of this lemma. -/
theorem ext_of_generateFrom_of_iUnion (C : Set (Set α)) (B : ℕ → Set α) (hA : ‹_› = generateFrom C)
(hC : IsPiSystem C) (h1B : ⋃ i, B i = univ) (h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) ≠ ∞)
(h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν := by
refine ext_of_generateFrom_of_cover_subset hA hC ?_ (countable_range B) h1B ?_ h_eq
· rintro _ ⟨i, rfl⟩
apply h2B
· rintro _ ⟨i, rfl⟩
apply hμB
@[simp]
theorem restrict_sum (μ : ι → Measure α) {s : Set α} (hs : MeasurableSet s) :
(sum μ).restrict s = sum fun i => (μ i).restrict s :=
ext fun t ht => by simp only [sum_apply, restrict_apply, ht, ht.inter hs]
@[simp]
theorem restrict_sum_of_countable [Countable ι] (μ : ι → Measure α) (s : Set α) :
(sum μ).restrict s = sum fun i => (μ i).restrict s := by
ext t ht
simp_rw [sum_apply _ ht, restrict_apply ht, sum_apply_of_countable]
lemma AbsolutelyContinuous.restrict (h : μ ≪ ν) (s : Set α) : μ.restrict s ≪ ν.restrict s := by
refine Measure.AbsolutelyContinuous.mk (fun t ht htν ↦ ?_)
rw [restrict_apply ht] at htν ⊢
exact h htν
theorem restrict_iUnion_ae [Countable ι] {s : ι → Set α} (hd : Pairwise (AEDisjoint μ on s))
(hm : ∀ i, NullMeasurableSet (s i) μ) : μ.restrict (⋃ i, s i) = sum fun i => μ.restrict (s i) :=
ext fun t ht => by simp only [sum_apply _ ht, restrict_iUnion_apply_ae hd hm ht]
theorem restrict_iUnion [Countable ι] {s : ι → Set α} (hd : Pairwise (Disjoint on s))
(hm : ∀ i, MeasurableSet (s i)) : μ.restrict (⋃ i, s i) = sum fun i => μ.restrict (s i) :=
restrict_iUnion_ae hd.aedisjoint fun i => (hm i).nullMeasurableSet
theorem restrict_iUnion_le [Countable ι] {s : ι → Set α} :
μ.restrict (⋃ i, s i) ≤ sum fun i => μ.restrict (s i) :=
le_iff.2 fun t ht ↦ by simpa [ht, inter_iUnion] using measure_iUnion_le (t ∩ s ·)
end Measure
@[simp]
theorem ae_restrict_iUnion_eq [Countable ι] (s : ι → Set α) :
ae (μ.restrict (⋃ i, s i)) = ⨆ i, ae (μ.restrict (s i)) :=
le_antisymm ((ae_sum_eq fun i => μ.restrict (s i)) ▸ ae_mono restrict_iUnion_le) <|
iSup_le fun i => ae_mono <| restrict_mono (subset_iUnion s i) le_rfl
@[simp]
theorem ae_restrict_union_eq (s t : Set α) :
ae (μ.restrict (s ∪ t)) = ae (μ.restrict s) ⊔ ae (μ.restrict t) := by
simp [union_eq_iUnion, iSup_bool_eq]
theorem ae_restrict_biUnion_eq (s : ι → Set α) {t : Set ι} (ht : t.Countable) :
ae (μ.restrict (⋃ i ∈ t, s i)) = ⨆ i ∈ t, ae (μ.restrict (s i)) := by
haveI := ht.to_subtype
rw [biUnion_eq_iUnion, ae_restrict_iUnion_eq, ← iSup_subtype'']
theorem ae_restrict_biUnion_finset_eq (s : ι → Set α) (t : Finset ι) :
ae (μ.restrict (⋃ i ∈ t, s i)) = ⨆ i ∈ t, ae (μ.restrict (s i)) :=
ae_restrict_biUnion_eq s t.countable_toSet
theorem ae_restrict_iUnion_iff [Countable ι] (s : ι → Set α) (p : α → Prop) :
(∀ᵐ x ∂μ.restrict (⋃ i, s i), p x) ↔ ∀ i, ∀ᵐ x ∂μ.restrict (s i), p x := by simp
theorem ae_restrict_union_iff (s t : Set α) (p : α → Prop) :
(∀ᵐ x ∂μ.restrict (s ∪ t), p x) ↔ (∀ᵐ x ∂μ.restrict s, p x) ∧ ∀ᵐ x ∂μ.restrict t, p x := by simp
theorem ae_restrict_biUnion_iff (s : ι → Set α) {t : Set ι} (ht : t.Countable) (p : α → Prop) :
(∀ᵐ x ∂μ.restrict (⋃ i ∈ t, s i), p x) ↔ ∀ i ∈ t, ∀ᵐ x ∂μ.restrict (s i), p x := by
simp_rw [Filter.Eventually, ae_restrict_biUnion_eq s ht, mem_iSup]
@[simp]
theorem ae_restrict_biUnion_finset_iff (s : ι → Set α) (t : Finset ι) (p : α → Prop) :
(∀ᵐ x ∂μ.restrict (⋃ i ∈ t, s i), p x) ↔ ∀ i ∈ t, ∀ᵐ x ∂μ.restrict (s i), p x := by
simp_rw [Filter.Eventually, ae_restrict_biUnion_finset_eq s, mem_iSup]
theorem ae_eq_restrict_iUnion_iff [Countable ι] (s : ι → Set α) (f g : α → δ) :
f =ᵐ[μ.restrict (⋃ i, s i)] g ↔ ∀ i, f =ᵐ[μ.restrict (s i)] g := by
simp_rw [EventuallyEq, ae_restrict_iUnion_eq, eventually_iSup]
theorem ae_eq_restrict_biUnion_iff (s : ι → Set α) {t : Set ι} (ht : t.Countable) (f g : α → δ) :
f =ᵐ[μ.restrict (⋃ i ∈ t, s i)] g ↔ ∀ i ∈ t, f =ᵐ[μ.restrict (s i)] g := by
simp_rw [ae_restrict_biUnion_eq s ht, EventuallyEq, eventually_iSup]
theorem ae_eq_restrict_biUnion_finset_iff (s : ι → Set α) (t : Finset ι) (f g : α → δ) :
f =ᵐ[μ.restrict (⋃ i ∈ t, s i)] g ↔ ∀ i ∈ t, f =ᵐ[μ.restrict (s i)] g :=
ae_eq_restrict_biUnion_iff s t.countable_toSet f g
open scoped Interval in
theorem ae_restrict_uIoc_eq [LinearOrder α] (a b : α) :
ae (μ.restrict (Ι a b)) = ae (μ.restrict (Ioc a b)) ⊔ ae (μ.restrict (Ioc b a)) := by
simp only [uIoc_eq_union, ae_restrict_union_eq]
open scoped Interval in
/-- See also `MeasureTheory.ae_uIoc_iff`. -/
theorem ae_restrict_uIoc_iff [LinearOrder α] {a b : α} {P : α → Prop} :
(∀ᵐ x ∂μ.restrict (Ι a b), P x) ↔
(∀ᵐ x ∂μ.restrict (Ioc a b), P x) ∧ ∀ᵐ x ∂μ.restrict (Ioc b a), P x := by
rw [ae_restrict_uIoc_eq, eventually_sup]
theorem ae_restrict_iff₀ {p : α → Prop} (hp : NullMeasurableSet { x | p x } (μ.restrict s)) :
(∀ᵐ x ∂μ.restrict s, p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := by
simp only [ae_iff, ← compl_setOf, Measure.restrict_apply₀ hp.compl]
rw [iff_iff_eq]; congr with x; simp [and_comm]
theorem ae_restrict_iff {p : α → Prop} (hp : MeasurableSet { x | p x }) :
(∀ᵐ x ∂μ.restrict s, p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
ae_restrict_iff₀ hp.nullMeasurableSet
theorem ae_imp_of_ae_restrict {s : Set α} {p : α → Prop} (h : ∀ᵐ x ∂μ.restrict s, p x) :
∀ᵐ x ∂μ, x ∈ s → p x := by
simp only [ae_iff] at h ⊢
simpa [setOf_and, inter_comm] using measure_inter_eq_zero_of_restrict h
theorem ae_restrict_iff'₀ {p : α → Prop} (hs : NullMeasurableSet s μ) :
(∀ᵐ x ∂μ.restrict s, p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := by
simp only [ae_iff, ← compl_setOf, restrict_apply₀' hs]
rw [iff_iff_eq]; congr with x; simp [and_comm]
theorem ae_restrict_iff' {p : α → Prop} (hs : MeasurableSet s) :
(∀ᵐ x ∂μ.restrict s, p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x :=
ae_restrict_iff'₀ hs.nullMeasurableSet
theorem _root_.Filter.EventuallyEq.restrict {f g : α → δ} {s : Set α} (hfg : f =ᵐ[μ] g) :
f =ᵐ[μ.restrict s] g := by
-- note that we cannot use `ae_restrict_iff` since we do not require measurability
refine hfg.filter_mono ?_
rw [Measure.ae_le_iff_absolutelyContinuous]
exact Measure.absolutelyContinuous_of_le Measure.restrict_le_self
theorem ae_restrict_mem₀ (hs : NullMeasurableSet s μ) : ∀ᵐ x ∂μ.restrict s, x ∈ s :=
(ae_restrict_iff'₀ hs).2 (Filter.Eventually.of_forall fun _ => id)
theorem ae_restrict_mem (hs : MeasurableSet s) : ∀ᵐ x ∂μ.restrict s, x ∈ s :=
ae_restrict_mem₀ hs.nullMeasurableSet
theorem ae_restrict_of_forall_mem {μ : Measure α} {s : Set α}
(hs : MeasurableSet s) {p : α → Prop} (h : ∀ x ∈ s, p x) : ∀ᵐ (x : α) ∂μ.restrict s, p x :=
(ae_restrict_mem hs).mono h
theorem ae_restrict_of_ae {s : Set α} {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) : ∀ᵐ x ∂μ.restrict s, p x :=
h.filter_mono (ae_mono Measure.restrict_le_self)
theorem ae_restrict_of_ae_restrict_of_subset {s t : Set α} {p : α → Prop} (hst : s ⊆ t)
(h : ∀ᵐ x ∂μ.restrict t, p x) : ∀ᵐ x ∂μ.restrict s, p x :=
h.filter_mono (ae_mono <| Measure.restrict_mono hst (le_refl μ))
theorem ae_of_ae_restrict_of_ae_restrict_compl (t : Set α) {p : α → Prop}
(ht : ∀ᵐ x ∂μ.restrict t, p x) (htc : ∀ᵐ x ∂μ.restrict tᶜ, p x) : ∀ᵐ x ∂μ, p x :=
nonpos_iff_eq_zero.1 <|
calc
μ { x | ¬p x } ≤ μ ({ x | ¬p x } ∩ t) + μ ({ x | ¬p x } ∩ tᶜ) :=
measure_le_inter_add_diff _ _ _
_ ≤ μ.restrict t { x | ¬p x } + μ.restrict tᶜ { x | ¬p x } :=
add_le_add (le_restrict_apply _ _) (le_restrict_apply _ _)
_ = 0 := by rw [ae_iff.1 ht, ae_iff.1 htc, zero_add]
theorem mem_map_restrict_ae_iff {β} {s : Set α} {t : Set β} {f : α → β} (hs : MeasurableSet s) :
t ∈ Filter.map f (ae (μ.restrict s)) ↔ μ ((f ⁻¹' t)ᶜ ∩ s) = 0 := by
rw [mem_map, mem_ae_iff, Measure.restrict_apply' hs]
theorem ae_add_measure_iff {p : α → Prop} {ν} :
(∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x :=
add_eq_zero
theorem ae_eq_comp' {ν : Measure β} {f : α → β} {g g' : β → δ} (hf : AEMeasurable f μ)
(h : g =ᵐ[ν] g') (h2 : μ.map f ≪ ν) : g ∘ f =ᵐ[μ] g' ∘ f :=
(tendsto_ae_map hf).mono_right h2.ae_le h
theorem Measure.QuasiMeasurePreserving.ae_eq_comp {ν : Measure β} {f : α → β} {g g' : β → δ}
(hf : QuasiMeasurePreserving f μ ν) (h : g =ᵐ[ν] g') : g ∘ f =ᵐ[μ] g' ∘ f :=
ae_eq_comp' hf.aemeasurable h hf.absolutelyContinuous
theorem ae_eq_comp {f : α → β} {g g' : β → δ} (hf : AEMeasurable f μ) (h : g =ᵐ[μ.map f] g') :
g ∘ f =ᵐ[μ] g' ∘ f :=
ae_eq_comp' hf h AbsolutelyContinuous.rfl
@[to_additive]
theorem div_ae_eq_one {β} [Group β] (f g : α → β) : f / g =ᵐ[μ] 1 ↔ f =ᵐ[μ] g := by
refine ⟨fun h ↦ h.mono fun x hx ↦ ?_, fun h ↦ h.mono fun x hx ↦ ?_⟩
· rwa [Pi.div_apply, Pi.one_apply, div_eq_one] at hx
· rwa [Pi.div_apply, Pi.one_apply, div_eq_one]
@[to_additive sub_nonneg_ae]
lemma one_le_div_ae {β : Type*} [Group β] [LE β] [MulRightMono β] (f g : α → β) :
1 ≤ᵐ[μ] g / f ↔ f ≤ᵐ[μ] g := by
refine ⟨fun h ↦ h.mono fun a ha ↦ ?_, fun h ↦ h.mono fun a ha ↦ ?_⟩
· rwa [Pi.one_apply, Pi.div_apply, one_le_div'] at ha
· rwa [Pi.one_apply, Pi.div_apply, one_le_div']
theorem le_ae_restrict : ae μ ⊓ 𝓟 s ≤ ae (μ.restrict s) := fun _s hs =>
eventually_inf_principal.2 (ae_imp_of_ae_restrict hs)
@[simp]
theorem ae_restrict_eq (hs : MeasurableSet s) : ae (μ.restrict s) = ae μ ⊓ 𝓟 s := by
ext t
simp only [mem_inf_principal, mem_ae_iff, restrict_apply_eq_zero' hs, compl_setOf,
Classical.not_imp, fun a => and_comm (a := a ∈ s) (b := ¬a ∈ t)]
rfl
lemma ae_restrict_le : ae (μ.restrict s) ≤ ae μ :=
ae_mono restrict_le_self
theorem ae_restrict_eq_bot {s} : ae (μ.restrict s) = ⊥ ↔ μ s = 0 :=
ae_eq_bot.trans restrict_eq_zero
theorem ae_restrict_neBot {s} : (ae <| μ.restrict s).NeBot ↔ μ s ≠ 0 :=
neBot_iff.trans ae_restrict_eq_bot.not
theorem self_mem_ae_restrict {s} (hs : MeasurableSet s) : s ∈ ae (μ.restrict s) := by
simp only [ae_restrict_eq hs, exists_prop, mem_principal, mem_inf_iff]
exact ⟨_, univ_mem, s, Subset.rfl, (univ_inter s).symm⟩
/-- If two measurable sets are ae_eq then any proposition that is almost everywhere true on one
is almost everywhere true on the other -/
theorem ae_restrict_of_ae_eq_of_ae_restrict {s t} (hst : s =ᵐ[μ] t) {p : α → Prop} :
(∀ᵐ x ∂μ.restrict s, p x) → ∀ᵐ x ∂μ.restrict t, p x := by simp [Measure.restrict_congr_set hst]
/-- If two measurable sets are ae_eq then any proposition that is almost everywhere true on one
is almost everywhere true on the other -/
theorem ae_restrict_congr_set {s t} (hst : s =ᵐ[μ] t) {p : α → Prop} :
(∀ᵐ x ∂μ.restrict s, p x) ↔ ∀ᵐ x ∂μ.restrict t, p x :=
⟨ae_restrict_of_ae_eq_of_ae_restrict hst, ae_restrict_of_ae_eq_of_ae_restrict hst.symm⟩
lemma NullMeasurable.measure_preimage_eq_measure_restrict_preimage_of_ae_compl_eq_const
{β : Type*} [MeasurableSpace β] {b : β} {f : α → β} {s : Set α}
(f_mble : NullMeasurable f (μ.restrict s)) (hs : f =ᵐ[Measure.restrict μ sᶜ] (fun _ ↦ b))
{t : Set β} (t_mble : MeasurableSet t) (ht : b ∉ t) :
μ (f ⁻¹' t) = μ.restrict s (f ⁻¹' t) := by
rw [Measure.restrict_apply₀ (f_mble t_mble)]
rw [EventuallyEq, ae_iff, Measure.restrict_apply₀] at hs
· apply le_antisymm _ (measure_mono inter_subset_left)
apply (measure_mono (Eq.symm (inter_union_compl (f ⁻¹' t) s)).le).trans
apply (measure_union_le _ _).trans
have obs : μ ((f ⁻¹' t) ∩ sᶜ) = 0 := by
apply le_antisymm _ (zero_le _)
rw [← hs]
apply measure_mono (inter_subset_inter_left _ _)
intro x hx hfx
simp only [mem_preimage, mem_setOf_eq] at hx hfx
exact ht (hfx ▸ hx)
simp only [obs, add_zero, le_refl]
· exact NullMeasurableSet.of_null hs
namespace Measure
section Subtype
/-! ### Subtype of a measure space -/
section ComapAnyMeasure
theorem MeasurableSet.nullMeasurableSet_subtype_coe {t : Set s} (hs : NullMeasurableSet s μ)
(ht : MeasurableSet t) : NullMeasurableSet ((↑) '' t) μ := by
rw [Subtype.instMeasurableSpace, comap_eq_generateFrom] at ht
induction t, ht using generateFrom_induction with
| hC t' ht' =>
obtain ⟨s', hs', rfl⟩ := ht'
rw [Subtype.image_preimage_coe]
exact hs.inter (hs'.nullMeasurableSet)
| empty => simp only [image_empty, nullMeasurableSet_empty]
| compl t' _ ht' =>
simp only [← range_diff_image Subtype.coe_injective, Subtype.range_coe_subtype, setOf_mem_eq]
exact hs.diff ht'
| iUnion f _ hf =>
dsimp only []
rw [image_iUnion]
exact .iUnion hf
theorem NullMeasurableSet.subtype_coe {t : Set s} (hs : NullMeasurableSet s μ)
(ht : NullMeasurableSet t (μ.comap Subtype.val)) : NullMeasurableSet (((↑) : s → α) '' t) μ :=
NullMeasurableSet.image _ μ Subtype.coe_injective
(fun _ => MeasurableSet.nullMeasurableSet_subtype_coe hs) ht
theorem measure_subtype_coe_le_comap (hs : NullMeasurableSet s μ) (t : Set s) :
μ (((↑) : s → α) '' t) ≤ μ.comap Subtype.val t :=
le_comap_apply _ _ Subtype.coe_injective (fun _ =>
MeasurableSet.nullMeasurableSet_subtype_coe hs) _
theorem measure_subtype_coe_eq_zero_of_comap_eq_zero (hs : NullMeasurableSet s μ) {t : Set s}
(ht : μ.comap Subtype.val t = 0) : μ (((↑) : s → α) '' t) = 0 :=
eq_bot_iff.mpr <| (measure_subtype_coe_le_comap hs t).trans ht.le
end ComapAnyMeasure
section MeasureSpace
variable {u : Set δ} [MeasureSpace δ] {p : δ → Prop}
/-- In a measure space, one can restrict the measure to a subtype to get a new measure space.
Not registered as an instance, as there are other natural choices such as the normalized restriction
for a probability measure, or the subspace measure when restricting to a vector subspace. Enable
locally if needed with `attribute [local instance] Measure.Subtype.measureSpace`. -/
noncomputable def Subtype.measureSpace : MeasureSpace (Subtype p) where
volume := Measure.comap Subtype.val volume
attribute [local instance] Subtype.measureSpace
theorem Subtype.volume_def : (volume : Measure u) = volume.comap Subtype.val :=
rfl
theorem Subtype.volume_univ (hu : NullMeasurableSet u) : volume (univ : Set u) = volume u := by
rw [Subtype.volume_def, comap_apply₀ _ _ _ _ MeasurableSet.univ.nullMeasurableSet]
· congr
simp only [image_univ, Subtype.range_coe_subtype, setOf_mem_eq]
· exact Subtype.coe_injective
· exact fun t => MeasurableSet.nullMeasurableSet_subtype_coe hu
theorem volume_subtype_coe_le_volume (hu : NullMeasurableSet u) (t : Set u) :
volume (((↑) : u → δ) '' t) ≤ volume t :=
measure_subtype_coe_le_comap hu t
theorem volume_subtype_coe_eq_zero_of_volume_eq_zero (hu : NullMeasurableSet u) {t : Set u}
(ht : volume t = 0) : volume (((↑) : u → δ) '' t) = 0 :=
measure_subtype_coe_eq_zero_of_comap_eq_zero hu ht
end MeasureSpace
end Subtype
end Measure
end MeasureTheory
open MeasureTheory Measure
namespace MeasurableEmbedding
variable {m0 : MeasurableSpace α} {m1 : MeasurableSpace β} {f : α → β}
section
variable (hf : MeasurableEmbedding f)
include hf
theorem map_comap (μ : Measure β) : (comap f μ).map f = μ.restrict (range f) := by
ext1 t ht
rw [hf.map_apply, comap_apply f hf.injective hf.measurableSet_image' _ (hf.measurable ht),
image_preimage_eq_inter_range, Measure.restrict_apply ht]
theorem comap_apply (μ : Measure β) (s : Set α) : comap f μ s = μ (f '' s) :=
calc
comap f μ s = comap f μ (f ⁻¹' (f '' s)) := by rw [hf.injective.preimage_image]
_ = (comap f μ).map f (f '' s) := (hf.map_apply _ _).symm
_ = μ (f '' s) := by
rw [hf.map_comap, restrict_apply' hf.measurableSet_range,
inter_eq_self_of_subset_left (image_subset_range _ _)]
theorem comap_map (μ : Measure α) : (map f μ).comap f = μ := by
ext t _
rw [hf.comap_apply, hf.map_apply, preimage_image_eq _ hf.injective]
theorem ae_map_iff {p : β → Prop} {μ : Measure α} : (∀ᵐ x ∂μ.map f, p x) ↔ ∀ᵐ x ∂μ, p (f x) := by
simp only [ae_iff, hf.map_apply, preimage_setOf_eq]
theorem restrict_map (μ : Measure α) (s : Set β) :
(μ.map f).restrict s = (μ.restrict <| f ⁻¹' s).map f :=
Measure.ext fun t ht => by simp [hf.map_apply, ht, hf.measurable ht]
protected theorem comap_preimage (μ : Measure β) (s : Set β) :
μ.comap f (f ⁻¹' s) = μ (s ∩ range f) := by
rw [← hf.map_apply, hf.map_comap, restrict_apply' hf.measurableSet_range]
lemma comap_restrict (μ : Measure β) (s : Set β) :
(μ.restrict s).comap f = (μ.comap f).restrict (f ⁻¹' s) := by
ext t ht
rw [Measure.restrict_apply ht, comap_apply hf, comap_apply hf,
Measure.restrict_apply (hf.measurableSet_image.2 ht), image_inter_preimage]
lemma restrict_comap (μ : Measure β) (s : Set α) :
(μ.comap f).restrict s = (μ.restrict (f '' s)).comap f := by
rw [comap_restrict hf, preimage_image_eq _ hf.injective]
end
theorem _root_.MeasurableEquiv.restrict_map (e : α ≃ᵐ β) (μ : Measure α) (s : Set β) :
(μ.map e).restrict s = (μ.restrict <| e ⁻¹' s).map e :=
e.measurableEmbedding.restrict_map _ _
end MeasurableEmbedding
section Subtype
theorem comap_subtype_coe_apply {_m0 : MeasurableSpace α} {s : Set α} (hs : MeasurableSet s)
(μ : Measure α) (t : Set s) : comap (↑) μ t = μ ((↑) '' t) :=
(MeasurableEmbedding.subtype_coe hs).comap_apply _ _
theorem map_comap_subtype_coe {m0 : MeasurableSpace α} {s : Set α} (hs : MeasurableSet s)
(μ : Measure α) : (comap (↑) μ).map ((↑) : s → α) = μ.restrict s := by
rw [(MeasurableEmbedding.subtype_coe hs).map_comap, Subtype.range_coe]
theorem ae_restrict_iff_subtype {m0 : MeasurableSpace α} {μ : Measure α} {s : Set α}
(hs : MeasurableSet s) {p : α → Prop} :
(∀ᵐ x ∂μ.restrict s, p x) ↔ ∀ᵐ (x : s) ∂comap ((↑) : s → α) μ, p x := by
rw [← map_comap_subtype_coe hs, (MeasurableEmbedding.subtype_coe hs).ae_map_iff]
variable [MeasureSpace α] {s t : Set α}
/-!
### Volume on `s : Set α`
Note the instance is provided earlier as `Subtype.measureSpace`.
-/
attribute [local instance] Subtype.measureSpace
theorem volume_set_coe_def (s : Set α) : (volume : Measure s) = comap ((↑) : s → α) volume :=
rfl
theorem MeasurableSet.map_coe_volume {s : Set α} (hs : MeasurableSet s) :
volume.map ((↑) : s → α) = restrict volume s := by
rw [volume_set_coe_def, (MeasurableEmbedding.subtype_coe hs).map_comap volume, Subtype.range_coe]
theorem volume_image_subtype_coe {s : Set α} (hs : MeasurableSet s) (t : Set s) :
volume ((↑) '' t : Set α) = volume t :=
(comap_subtype_coe_apply hs volume t).symm
@[simp]
theorem volume_preimage_coe (hs : NullMeasurableSet s) (ht : MeasurableSet t) :
volume (((↑) : s → α) ⁻¹' t) = volume (t ∩ s) := by
rw [volume_set_coe_def,
comap_apply₀ _ _ Subtype.coe_injective
(fun h => MeasurableSet.nullMeasurableSet_subtype_coe hs)
(measurable_subtype_coe ht).nullMeasurableSet,
image_preimage_eq_inter_range, Subtype.range_coe]
end Subtype
section Piecewise
variable [MeasurableSpace α] {μ : Measure α} {s t : Set α} {f g : α → β}
theorem piecewise_ae_eq_restrict [DecidablePred (· ∈ s)] (hs : MeasurableSet s) :
piecewise s f g =ᵐ[μ.restrict s] f := by
rw [ae_restrict_eq hs]
exact (piecewise_eqOn s f g).eventuallyEq.filter_mono inf_le_right
theorem piecewise_ae_eq_restrict_compl [DecidablePred (· ∈ s)] (hs : MeasurableSet s) :
piecewise s f g =ᵐ[μ.restrict sᶜ] g := by
rw [ae_restrict_eq hs.compl]
exact (piecewise_eqOn_compl s f g).eventuallyEq.filter_mono inf_le_right
|
theorem piecewise_ae_eq_of_ae_eq_set [DecidablePred (· ∈ s)] [DecidablePred (· ∈ t)]
(hst : s =ᵐ[μ] t) : s.piecewise f g =ᵐ[μ] t.piecewise f g :=
hst.mem_iff.mono fun x hx => by simp [piecewise, hx]
| Mathlib/MeasureTheory/Measure/Restrict.lean | 893 | 896 |
/-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import Mathlib.CategoryTheory.Adjunction.FullyFaithful
import Mathlib.CategoryTheory.Adjunction.Limits
import Mathlib.CategoryTheory.Limits.Shapes.Pullback.CommSq
import Mathlib.CategoryTheory.Limits.Shapes.StrictInitial
import Mathlib.CategoryTheory.Limits.FunctorCategory.Basic
import Mathlib.CategoryTheory.Limits.Constructions.FiniteProductsOfBinaryProducts
/-!
# Universal colimits and van Kampen colimits
## Main definitions
- `CategoryTheory.IsUniversalColimit`: A (colimit) cocone over a diagram `F : J ⥤ C` is universal
if it is stable under pullbacks.
- `CategoryTheory.IsVanKampenColimit`: A (colimit) cocone over a diagram `F : J ⥤ C` is van
Kampen if for every cocone `c'` over the pullback of the diagram `F' : J ⥤ C'`,
`c'` is colimiting iff `c'` is the pullback of `c`.
## References
- https://ncatlab.org/nlab/show/van+Kampen+colimit
- [Stephen Lack and Paweł Sobociński, Adhesive Categories][adhesive2004]
-/
open CategoryTheory.Limits
namespace CategoryTheory
universe v' u' v u
variable {J : Type v'} [Category.{u'} J] {C : Type u} [Category.{v} C]
variable {K : Type*} [Category K] {D : Type*} [Category D]
section NatTrans
/-- A natural transformation is equifibered if every commutative square of the following form is
a pullback.
```
F(X) → F(Y)
↓ ↓
G(X) → G(Y)
```
-/
def NatTrans.Equifibered {F G : J ⥤ C} (α : F ⟶ G) : Prop :=
∀ ⦃i j : J⦄ (f : i ⟶ j), IsPullback (F.map f) (α.app i) (α.app j) (G.map f)
theorem NatTrans.equifibered_of_isIso {F G : J ⥤ C} (α : F ⟶ G) [IsIso α] : Equifibered α :=
fun _ _ f => IsPullback.of_vert_isIso ⟨NatTrans.naturality _ f⟩
theorem NatTrans.Equifibered.comp {F G H : J ⥤ C} {α : F ⟶ G} {β : G ⟶ H} (hα : Equifibered α)
(hβ : Equifibered β) : Equifibered (α ≫ β) :=
fun _ _ f => (hα f).paste_vert (hβ f)
theorem NatTrans.Equifibered.whiskerRight {F G : J ⥤ C} {α : F ⟶ G} (hα : Equifibered α)
(H : C ⥤ D) [∀ (i j : J) (f : j ⟶ i), PreservesLimit (cospan (α.app i) (G.map f)) H] :
Equifibered (whiskerRight α H) :=
fun _ _ f => (hα f).map H
theorem NatTrans.Equifibered.whiskerLeft {K : Type*} [Category K] {F G : J ⥤ C} {α : F ⟶ G}
(hα : Equifibered α) (H : K ⥤ J) : Equifibered (whiskerLeft H α) :=
fun _ _ f => hα (H.map f)
theorem mapPair_equifibered {F F' : Discrete WalkingPair ⥤ C} (α : F ⟶ F') :
NatTrans.Equifibered α := by
rintro ⟨⟨⟩⟩ ⟨j⟩ ⟨⟨rfl : _ = j⟩⟩
all_goals
dsimp; simp only [Discrete.functor_map_id]
exact IsPullback.of_horiz_isIso ⟨by simp only [Category.comp_id, Category.id_comp]⟩
theorem NatTrans.equifibered_of_discrete {ι : Type*} {F G : Discrete ι ⥤ C}
(α : F ⟶ G) : NatTrans.Equifibered α := by
rintro ⟨i⟩ ⟨j⟩ ⟨⟨rfl : i = j⟩⟩
simp only [Discrete.functor_map_id]
exact IsPullback.of_horiz_isIso ⟨by rw [Category.id_comp, Category.comp_id]⟩
end NatTrans
/-- A (colimit) cocone over a diagram `F : J ⥤ C` is universal if it is stable under pullbacks. -/
def IsUniversalColimit {F : J ⥤ C} (c : Cocone F) : Prop :=
∀ ⦃F' : J ⥤ C⦄ (c' : Cocone F') (α : F' ⟶ F) (f : c'.pt ⟶ c.pt)
(_ : α ≫ c.ι = c'.ι ≫ (Functor.const J).map f) (_ : NatTrans.Equifibered α),
(∀ j : J, IsPullback (c'.ι.app j) (α.app j) f (c.ι.app j)) → Nonempty (IsColimit c')
/-- A (colimit) cocone over a diagram `F : J ⥤ C` is van Kampen if for every cocone `c'` over the
pullback of the diagram `F' : J ⥤ C'`, `c'` is colimiting iff `c'` is the pullback of `c`.
TODO: Show that this is iff the functor `C ⥤ Catᵒᵖ` sending `x` to `C/x` preserves it.
TODO: Show that this is iff the inclusion functor `C ⥤ Span(C)` preserves it.
-/
def IsVanKampenColimit {F : J ⥤ C} (c : Cocone F) : Prop :=
∀ ⦃F' : J ⥤ C⦄ (c' : Cocone F') (α : F' ⟶ F) (f : c'.pt ⟶ c.pt)
(_ : α ≫ c.ι = c'.ι ≫ (Functor.const J).map f) (_ : NatTrans.Equifibered α),
Nonempty (IsColimit c') ↔ ∀ j : J, IsPullback (c'.ι.app j) (α.app j) f (c.ι.app j)
theorem IsVanKampenColimit.isUniversal {F : J ⥤ C} {c : Cocone F} (H : IsVanKampenColimit c) :
IsUniversalColimit c :=
fun _ c' α f h hα => (H c' α f h hα).mpr
/-- A universal colimit is a colimit. -/
noncomputable def IsUniversalColimit.isColimit {F : J ⥤ C} {c : Cocone F}
(h : IsUniversalColimit c) : IsColimit c := by
refine ((h c (𝟙 F) (𝟙 c.pt :) (by rw [Functor.map_id, Category.comp_id, Category.id_comp])
(NatTrans.equifibered_of_isIso _)) fun j => ?_).some
haveI : IsIso (𝟙 c.pt) := inferInstance
exact IsPullback.of_vert_isIso ⟨by simp⟩
/-- A van Kampen colimit is a colimit. -/
noncomputable def IsVanKampenColimit.isColimit {F : J ⥤ C} {c : Cocone F}
(h : IsVanKampenColimit c) : IsColimit c :=
h.isUniversal.isColimit
theorem IsInitial.isVanKampenColimit [HasStrictInitialObjects C] {X : C} (h : IsInitial X) :
IsVanKampenColimit (asEmptyCocone X) := by
intro F' c' α f hf hα
have : F' = Functor.empty C := by apply Functor.hext <;> rintro ⟨⟨⟩⟩
subst this
haveI := h.isIso_to f
refine ⟨by rintro _ ⟨⟨⟩⟩,
fun _ => ⟨IsColimit.ofIsoColimit h (Cocones.ext (asIso f).symm <| by rintro ⟨⟨⟩⟩)⟩⟩
section Functor
theorem IsUniversalColimit.of_iso {F : J ⥤ C} {c c' : Cocone F} (hc : IsUniversalColimit c)
(e : c ≅ c') : IsUniversalColimit c' := by
intro F' c'' α f h hα H
have : c'.ι ≫ (Functor.const J).map e.inv.hom = c.ι := by
ext j
exact e.inv.2 j
apply hc c'' α (f ≫ e.inv.1) (by rw [Functor.map_comp, ← reassoc_of% h, this]) hα
intro j
rw [← Category.comp_id (α.app j)]
have : IsIso e.inv.hom := Functor.map_isIso (Cocones.forget _) e.inv
exact (H j).paste_vert (IsPullback.of_vert_isIso ⟨by simp⟩)
theorem IsVanKampenColimit.of_iso {F : J ⥤ C} {c c' : Cocone F} (H : IsVanKampenColimit c)
(e : c ≅ c') : IsVanKampenColimit c' := by
intro F' c'' α f h hα
have : c'.ι ≫ (Functor.const J).map e.inv.hom = c.ι := by
ext j
exact e.inv.2 j
rw [H c'' α (f ≫ e.inv.1) (by rw [Functor.map_comp, ← reassoc_of% h, this]) hα]
apply forall_congr'
intro j
conv_lhs => rw [← Category.comp_id (α.app j)]
haveI : IsIso e.inv.hom := Functor.map_isIso (Cocones.forget _) e.inv
exact (IsPullback.of_vert_isIso ⟨by simp⟩).paste_vert_iff (NatTrans.congr_app h j).symm
theorem IsVanKampenColimit.precompose_isIso {F G : J ⥤ C} (α : F ⟶ G) [IsIso α]
{c : Cocone G} (hc : IsVanKampenColimit c) :
IsVanKampenColimit ((Cocones.precompose α).obj c) := by
intros F' c' α' f e hα
refine (hc c' (α' ≫ α) f ((Category.assoc _ _ _).trans e)
(hα.comp (NatTrans.equifibered_of_isIso _))).trans ?_
apply forall_congr'
intro j
simp only [Functor.const_obj_obj, NatTrans.comp_app,
Cocones.precompose_obj_pt, Cocones.precompose_obj_ι]
have : IsPullback (α.app j ≫ c.ι.app j) (α.app j) (𝟙 _) (c.ι.app j) :=
IsPullback.of_vert_isIso ⟨Category.comp_id _⟩
rw [← IsPullback.paste_vert_iff this _, Category.comp_id]
exact (congr_app e j).symm
theorem IsUniversalColimit.precompose_isIso {F G : J ⥤ C} (α : F ⟶ G) [IsIso α]
{c : Cocone G} (hc : IsUniversalColimit c) :
IsUniversalColimit ((Cocones.precompose α).obj c) := by
intros F' c' α' f e hα H
apply (hc c' (α' ≫ α) f ((Category.assoc _ _ _).trans e)
(hα.comp (NatTrans.equifibered_of_isIso _)))
intro j
simp only [Functor.const_obj_obj, NatTrans.comp_app,
Cocones.precompose_obj_pt, Cocones.precompose_obj_ι]
rw [← Category.comp_id f]
exact (H j).paste_vert (IsPullback.of_vert_isIso ⟨Category.comp_id _⟩)
theorem IsVanKampenColimit.precompose_isIso_iff {F G : J ⥤ C} (α : F ⟶ G) [IsIso α]
{c : Cocone G} : IsVanKampenColimit ((Cocones.precompose α).obj c) ↔ IsVanKampenColimit c :=
⟨fun hc ↦ IsVanKampenColimit.of_iso (IsVanKampenColimit.precompose_isIso (inv α) hc)
(Cocones.ext (Iso.refl _) (by simp)),
IsVanKampenColimit.precompose_isIso α⟩
theorem IsUniversalColimit.of_mapCocone (G : C ⥤ D) {F : J ⥤ C} {c : Cocone F}
[PreservesLimitsOfShape WalkingCospan G] [ReflectsColimitsOfShape J G]
(hc : IsUniversalColimit (G.mapCocone c)) : IsUniversalColimit c :=
fun F' c' α f h hα H ↦
⟨isColimitOfReflects _ (hc (G.mapCocone c') (whiskerRight α G) (G.map f)
(by ext j; simpa using G.congr_map (NatTrans.congr_app h j))
(hα.whiskerRight G) (fun j ↦ (H j).map G)).some⟩
theorem IsVanKampenColimit.of_mapCocone (G : C ⥤ D) {F : J ⥤ C} {c : Cocone F}
[∀ (i j : J) (X : C) (f : X ⟶ F.obj j) (g : i ⟶ j), PreservesLimit (cospan f (F.map g)) G]
[∀ (i : J) (X : C) (f : X ⟶ c.pt), PreservesLimit (cospan f (c.ι.app i)) G]
[ReflectsLimitsOfShape WalkingCospan G]
[PreservesColimitsOfShape J G]
[ReflectsColimitsOfShape J G]
(H : IsVanKampenColimit (G.mapCocone c)) : IsVanKampenColimit c := by
intro F' c' α f h hα
refine (Iff.trans ?_ (H (G.mapCocone c') (whiskerRight α G) (G.map f)
(by ext j; simpa using G.congr_map (NatTrans.congr_app h j))
(hα.whiskerRight G))).trans (forall_congr' fun j => ?_)
· exact ⟨fun h => ⟨isColimitOfPreserves G h.some⟩, fun h => ⟨isColimitOfReflects G h.some⟩⟩
· exact IsPullback.map_iff G (NatTrans.congr_app h.symm j)
theorem IsVanKampenColimit.mapCocone_iff (G : C ⥤ D) {F : J ⥤ C} {c : Cocone F}
[G.IsEquivalence] : IsVanKampenColimit (G.mapCocone c) ↔ IsVanKampenColimit c :=
⟨IsVanKampenColimit.of_mapCocone G, fun hc ↦ by
let e : F ⋙ G ⋙ Functor.inv G ≅ F := NatIso.hcomp (Iso.refl F) G.asEquivalence.unitIso.symm
apply IsVanKampenColimit.of_mapCocone G.inv
apply (IsVanKampenColimit.precompose_isIso_iff e.inv).mp
exact hc.of_iso (Cocones.ext (G.asEquivalence.unitIso.app c.pt) (fun j => (by simp [e])))⟩
theorem IsUniversalColimit.whiskerEquivalence {K : Type*} [Category K] (e : J ≌ K)
{F : K ⥤ C} {c : Cocone F} (hc : IsUniversalColimit c) :
IsUniversalColimit (c.whisker e.functor) := by
intro F' c' α f e' hα H
convert hc (c'.whisker e.inverse) (whiskerLeft e.inverse α ≫ (e.invFunIdAssoc F).hom) f ?_
((hα.whiskerLeft _).comp (NatTrans.equifibered_of_isIso _)) ?_ using 1
· exact (IsColimit.whiskerEquivalenceEquiv e.symm).nonempty_congr
· convert congr_arg (whiskerLeft e.inverse) e'
ext
simp
· intro k
rw [← Category.comp_id f]
refine (H (e.inverse.obj k)).paste_vert ?_
have : IsIso (𝟙 (Cocone.whisker e.functor c).pt) := inferInstance
exact IsPullback.of_vert_isIso ⟨by simp⟩
theorem IsUniversalColimit.whiskerEquivalence_iff {K : Type*} [Category K] (e : J ≌ K)
{F : K ⥤ C} {c : Cocone F} :
IsUniversalColimit (c.whisker e.functor) ↔ IsUniversalColimit c :=
⟨fun hc ↦ ((hc.whiskerEquivalence e.symm).precompose_isIso (e.invFunIdAssoc F).inv).of_iso
(Cocones.ext (Iso.refl _) (by simp)), IsUniversalColimit.whiskerEquivalence e⟩
theorem IsVanKampenColimit.whiskerEquivalence {K : Type*} [Category K] (e : J ≌ K)
{F : K ⥤ C} {c : Cocone F} (hc : IsVanKampenColimit c) :
IsVanKampenColimit (c.whisker e.functor) := by
intro F' c' α f e' hα
convert hc (c'.whisker e.inverse) (whiskerLeft e.inverse α ≫ (e.invFunIdAssoc F).hom) f ?_
((hα.whiskerLeft _).comp (NatTrans.equifibered_of_isIso _)) using 1
· exact (IsColimit.whiskerEquivalenceEquiv e.symm).nonempty_congr
· simp only [Functor.const_obj_obj, Functor.comp_obj, Cocone.whisker_pt, Cocone.whisker_ι,
whiskerLeft_app, NatTrans.comp_app, Equivalence.invFunIdAssoc_hom_app, Functor.id_obj]
constructor
· intro H k
rw [← Category.comp_id f]
refine (H (e.inverse.obj k)).paste_vert ?_
have : IsIso (𝟙 (Cocone.whisker e.functor c).pt) := inferInstance
exact IsPullback.of_vert_isIso ⟨by simp⟩
· intro H j
have : α.app j
= F'.map (e.unit.app _) ≫ α.app _ ≫ F.map (e.counit.app (e.functor.obj j)) := by
simp [← Functor.map_comp]
rw [← Category.id_comp f, this]
refine IsPullback.paste_vert ?_ (H (e.functor.obj j))
exact IsPullback.of_vert_isIso ⟨by simp⟩
· ext k
simpa using congr_app e' (e.inverse.obj k)
theorem IsVanKampenColimit.whiskerEquivalence_iff {K : Type*} [Category K] (e : J ≌ K)
{F : K ⥤ C} {c : Cocone F} :
IsVanKampenColimit (c.whisker e.functor) ↔ IsVanKampenColimit c :=
⟨fun hc ↦ ((hc.whiskerEquivalence e.symm).precompose_isIso (e.invFunIdAssoc F).inv).of_iso
(Cocones.ext (Iso.refl _) (by simp)), IsVanKampenColimit.whiskerEquivalence e⟩
theorem isVanKampenColimit_of_evaluation [HasPullbacks D] [HasColimitsOfShape J D] (F : J ⥤ C ⥤ D)
(c : Cocone F) (hc : ∀ x : C, IsVanKampenColimit (((evaluation C D).obj x).mapCocone c)) :
IsVanKampenColimit c := by
intro F' c' α f e hα
have := fun x => hc x (((evaluation C D).obj x).mapCocone c') (whiskerRight α _)
(((evaluation C D).obj x).map f)
(by
ext y
dsimp
exact NatTrans.congr_app (NatTrans.congr_app e y) x)
(hα.whiskerRight _)
constructor
· rintro ⟨hc'⟩ j
refine ⟨⟨(NatTrans.congr_app e j).symm⟩, ⟨evaluationJointlyReflectsLimits _ ?_⟩⟩
refine fun x => (isLimitMapConePullbackConeEquiv _ _).symm ?_
exact ((this x).mp ⟨isColimitOfPreserves _ hc'⟩ _).isLimit
· exact fun H => ⟨evaluationJointlyReflectsColimits _ fun x =>
((this x).mpr fun j => (H j).map ((evaluation C D).obj x)).some⟩
end Functor
section reflective
theorem IsUniversalColimit.map_reflective
{Gl : C ⥤ D} {Gr : D ⥤ C} (adj : Gl ⊣ Gr) [Gr.Full] [Gr.Faithful]
{F : J ⥤ D} {c : Cocone (F ⋙ Gr)}
(H : IsUniversalColimit c)
[∀ X (f : X ⟶ Gl.obj c.pt), HasPullback (Gr.map f) (adj.unit.app c.pt)]
[∀ X (f : X ⟶ Gl.obj c.pt), PreservesLimit (cospan (Gr.map f) (adj.unit.app c.pt)) Gl] :
IsUniversalColimit (Gl.mapCocone c) := by
have := adj.rightAdjoint_preservesLimits
have : PreservesColimitsOfSize.{u', v'} Gl := adj.leftAdjoint_preservesColimits
intros F' c' α f h hα hc'
have : HasPullback (Gl.map (Gr.map f)) (Gl.map (adj.unit.app c.pt)) :=
⟨⟨_, isLimitPullbackConeMapOfIsLimit _ pullback.condition
(IsPullback.of_hasPullback _ _).isLimit⟩⟩
let α' := α ≫ (Functor.associator _ _ _).hom ≫ whiskerLeft F adj.counit ≫ F.rightUnitor.hom
have hα' : NatTrans.Equifibered α' := hα.comp (NatTrans.equifibered_of_isIso _)
have hadj : ∀ X, Gl.map (adj.unit.app X) = inv (adj.counit.app _) := by
intro X
apply IsIso.eq_inv_of_inv_hom_id
exact adj.left_triangle_components _
haveI : ∀ X, IsIso (Gl.map (adj.unit.app X)) := by
simp_rw [hadj]
infer_instance
have hα'' : ∀ j, Gl.map (Gr.map <| α'.app j) = adj.counit.app _ ≫ α.app j := by
intro j
rw [← cancel_mono (adj.counit.app <| F.obj j)]
dsimp [α']
simp only [Category.comp_id, Adjunction.counit_naturality_assoc, Category.id_comp,
Adjunction.counit_naturality, Category.assoc, Functor.map_comp]
have hc'' : ∀ j, α.app j ≫ Gl.map (c.ι.app j) = c'.ι.app j ≫ f := NatTrans.congr_app h
let β := isoWhiskerLeft F' (asIso adj.counit) ≪≫ F'.rightUnitor
let c'' : Cocone (F' ⋙ Gr) := by
refine
{ pt := pullback (Gr.map f) (adj.unit.app _)
ι := { app := fun j ↦ pullback.lift (Gr.map <| c'.ι.app j) (Gr.map (α'.app j) ≫ c.ι.app j) ?_
naturality := ?_ } }
· rw [← Gr.map_comp, ← hc'']
erw [← adj.unit_naturality]
rw [Gl.map_comp, hα'']
dsimp
simp only [Category.assoc, Functor.map_comp, adj.right_triangle_components_assoc]
· intros i j g
dsimp [α']
ext
all_goals simp only [Category.comp_id, Category.id_comp, Category.assoc,
← Functor.map_comp, pullback.lift_fst, pullback.lift_snd, ← Functor.map_comp_assoc]
· congr 1
exact c'.w _
· rw [α.naturality_assoc]
dsimp
rw [adj.counit_naturality, ← Category.assoc, Gr.map_comp_assoc]
congr 1
exact c.w _
let cf : (Cocones.precompose β.hom).obj c' ⟶ Gl.mapCocone c'' := by
refine { hom := pullback.lift ?_ f ?_ ≫ (PreservesPullback.iso _ _ _).inv, w := ?_ }
· exact inv <| adj.counit.app c'.pt
· simp [← cancel_mono (adj.counit.app <| Gl.obj c.pt)]
· intro j
rw [← Category.assoc, Iso.comp_inv_eq]
ext
all_goals simp only [c'', PreservesPullback.iso_hom_fst, PreservesPullback.iso_hom_snd,
pullback.lift_fst, pullback.lift_snd, Category.assoc,
Functor.mapCocone_ι_app, ← Gl.map_comp]
· rw [IsIso.comp_inv_eq, adj.counit_naturality]
dsimp [β]
rw [Category.comp_id]
· rw [Gl.map_comp, hα'', Category.assoc, hc'']
dsimp [β]
rw [Category.comp_id, Category.assoc]
have :
cf.hom ≫ (PreservesPullback.iso _ _ _).hom ≫ pullback.fst _ _ ≫ adj.counit.app _ = 𝟙 _ := by
simp only [cf, IsIso.inv_hom_id, Iso.inv_hom_id_assoc, Category.assoc,
pullback.lift_fst_assoc]
have : IsIso cf := by
apply @Cocones.cocone_iso_of_hom_iso (i := ?_)
rw [← IsIso.eq_comp_inv] at this
rw [this]
infer_instance
have ⟨Hc''⟩ := H c'' (whiskerRight α' Gr) (pullback.snd _ _) ?_ (hα'.whiskerRight Gr) ?_
· exact ⟨IsColimit.precomposeHomEquiv β c' <|
(isColimitOfPreserves Gl Hc'').ofIsoColimit (asIso cf).symm⟩
· ext j
dsimp [c'']
simp only [Category.comp_id, Category.id_comp, Category.assoc,
Functor.map_comp, pullback.lift_snd]
· intro j
apply IsPullback.of_right _ _ (IsPullback.of_hasPullback _ _)
· dsimp [α', c'']
simp only [Category.comp_id, Category.id_comp, Category.assoc, Functor.map_comp,
pullback.lift_fst]
rw [← Category.comp_id (Gr.map f)]
refine ((hc' j).map Gr).paste_vert (IsPullback.of_vert_isIso ⟨?_⟩)
rw [← adj.unit_naturality, Category.comp_id, ← Category.assoc,
← Category.id_comp (Gr.map ((Gl.mapCocone c).ι.app j))]
congr 1
rw [← cancel_mono (Gr.map (adj.counit.app (F.obj j)))]
dsimp
simp only [Category.comp_id, Adjunction.right_triangle_components, Category.id_comp,
Category.assoc]
· dsimp [c'']
simp only [Category.comp_id, Category.id_comp, Category.assoc, Functor.map_comp,
pullback.lift_snd]
theorem IsVanKampenColimit.map_reflective [HasColimitsOfShape J C]
{Gl : C ⥤ D} {Gr : D ⥤ C} (adj : Gl ⊣ Gr) [Gr.Full] [Gr.Faithful]
{F : J ⥤ D} {c : Cocone (F ⋙ Gr)} (H : IsVanKampenColimit c)
[∀ X (f : X ⟶ Gl.obj c.pt), HasPullback (Gr.map f) (adj.unit.app c.pt)]
[∀ X (f : X ⟶ Gl.obj c.pt), PreservesLimit (cospan (Gr.map f) (adj.unit.app c.pt)) Gl]
[∀ X i (f : X ⟶ c.pt), PreservesLimit (cospan f (c.ι.app i)) Gl] :
IsVanKampenColimit (Gl.mapCocone c) := by
have := adj.rightAdjoint_preservesLimits
have : PreservesColimitsOfSize.{u', v'} Gl := adj.leftAdjoint_preservesColimits
intro F' c' α f h hα
refine ⟨?_, H.isUniversal.map_reflective adj c' α f h hα⟩
intro ⟨hc'⟩ j
let α' := α ≫ (Functor.associator _ _ _).hom ≫ whiskerLeft F adj.counit ≫ F.rightUnitor.hom
have hα' : NatTrans.Equifibered α' := hα.comp (NatTrans.equifibered_of_isIso _)
have hα'' : ∀ j, Gl.map (Gr.map <| α'.app j) = adj.counit.app _ ≫ α.app j := by
intro j
rw [← cancel_mono (adj.counit.app <| F.obj j)]
dsimp [α']
simp only [Category.comp_id, Adjunction.counit_naturality_assoc, Category.id_comp,
Adjunction.counit_naturality, Category.assoc, Functor.map_comp]
let β := isoWhiskerLeft F' (asIso adj.counit) ≪≫ F'.rightUnitor
let hl := (IsColimit.precomposeHomEquiv β c').symm hc'
let hr := isColimitOfPreserves Gl (colimit.isColimit <| F' ⋙ Gr)
have : α.app j = β.inv.app _ ≫ Gl.map (Gr.map <| α'.app j) := by
rw [hα'']
simp [β]
rw [this]
have : f = (hl.coconePointUniqueUpToIso hr).hom ≫
Gl.map (colimit.desc _ ⟨_, whiskerRight α' Gr ≫ c.2⟩) := by
symm
convert @IsColimit.coconePointUniqueUpToIso_hom_desc _ _ _ _ ((F' ⋙ Gr) ⋙ Gl)
(Gl.mapCocone ⟨_, (whiskerRight α' Gr ≫ c.2 :)⟩) _ _ hl hr using 2
· apply hr.hom_ext
intro j
rw [hr.fac, Functor.mapCocone_ι_app, ← Gl.map_comp, colimit.cocone_ι, colimit.ι_desc]
rfl
· clear_value α'
apply hl.hom_ext
intro j
rw [hl.fac]
dsimp [β]
simp only [Category.comp_id, hα'', Category.assoc, Gl.map_comp]
congr 1
exact (NatTrans.congr_app h j).symm
rw [this]
have := ((H (colimit.cocone <| F' ⋙ Gr) (whiskerRight α' Gr)
(colimit.desc _ ⟨_, whiskerRight α' Gr ≫ c.2⟩) ?_ (hα'.whiskerRight Gr)).mp
⟨(getColimitCocone <| F' ⋙ Gr).2⟩ j).map Gl
· convert IsPullback.paste_vert _ this
refine IsPullback.of_vert_isIso ⟨?_⟩
rw [← IsIso.inv_comp_eq, ← Category.assoc, NatIso.inv_inv_app]
exact IsColimit.comp_coconePointUniqueUpToIso_hom hl hr _
· clear_value α'
ext j
simp
end reflective
section Initial
theorem hasStrictInitial_of_isUniversal [HasInitial C]
(H : IsUniversalColimit (BinaryCofan.mk (𝟙 (⊥_ C)) (𝟙 (⊥_ C)))) : HasStrictInitialObjects C :=
hasStrictInitialObjects_of_initial_is_strict
(by
intro A f
suffices IsColimit (BinaryCofan.mk (𝟙 A) (𝟙 A)) by
obtain ⟨l, h₁, h₂⟩ := Limits.BinaryCofan.IsColimit.desc' this (f ≫ initial.to A) (𝟙 A)
rcases(Category.id_comp _).symm.trans h₂ with rfl
exact ⟨⟨_, ((Category.id_comp _).symm.trans h₁).symm, initialIsInitial.hom_ext _ _⟩⟩
refine (H (BinaryCofan.mk (𝟙 _) (𝟙 _)) (mapPair f f) f (by ext ⟨⟨⟩⟩ <;> dsimp <;> simp)
(mapPair_equifibered _) ?_).some
rintro ⟨⟨⟩⟩ <;> dsimp <;>
exact IsPullback.of_horiz_isIso ⟨(Category.id_comp _).trans (Category.comp_id _).symm⟩)
theorem isVanKampenColimit_of_isEmpty [HasStrictInitialObjects C] [IsEmpty J] {F : J ⥤ C}
(c : Cocone F) (hc : IsColimit c) : IsVanKampenColimit c := by
have : IsInitial c.pt := by
have := (IsColimit.precomposeInvEquiv (Functor.uniqueFromEmpty _) _).symm
(hc.whiskerEquivalence (equivalenceOfIsEmpty (Discrete PEmpty.{1}) J))
exact IsColimit.ofIsoColimit this (Cocones.ext (Iso.refl c.pt) (fun {X} ↦ isEmptyElim X))
replace this := IsInitial.isVanKampenColimit this
apply (IsVanKampenColimit.whiskerEquivalence_iff
(equivalenceOfIsEmpty (Discrete PEmpty.{1}) J)).mp
exact (this.precompose_isIso (Functor.uniqueFromEmpty
((equivalenceOfIsEmpty (Discrete PEmpty.{1}) J).functor ⋙ F)).hom).of_iso
(Cocones.ext (Iso.refl _) (by simp))
end Initial
section BinaryCoproduct
variable {X Y : C}
theorem BinaryCofan.isVanKampen_iff (c : BinaryCofan X Y) :
IsVanKampenColimit c ↔
∀ {X' Y' : C} (c' : BinaryCofan X' Y') (αX : X' ⟶ X) (αY : Y' ⟶ Y) (f : c'.pt ⟶ c.pt)
(_ : αX ≫ c.inl = c'.inl ≫ f) (_ : αY ≫ c.inr = c'.inr ≫ f),
Nonempty (IsColimit c') ↔ IsPullback c'.inl αX f c.inl ∧ IsPullback c'.inr αY f c.inr := by
constructor
· introv H hαX hαY
rw [H c' (mapPair αX αY) f (by ext ⟨⟨⟩⟩ <;> dsimp <;> assumption) (mapPair_equifibered _)]
constructor
· intro H
exact ⟨H _, H _⟩
· rintro H ⟨⟨⟩⟩
exacts [H.1, H.2]
· introv H F' hα h
let X' := F'.obj ⟨WalkingPair.left⟩
let Y' := F'.obj ⟨WalkingPair.right⟩
have : F' = pair X' Y' := by
| apply Functor.hext
· rintro ⟨⟨⟩⟩ <;> rfl
· rintro ⟨⟨⟩⟩ ⟨j⟩ ⟨⟨rfl : _ = j⟩⟩ <;> simp [X', Y']
clear_value X' Y'
subst this
change BinaryCofan X' Y' at c'
rw [H c' _ _ _ (NatTrans.congr_app hα ⟨WalkingPair.left⟩)
(NatTrans.congr_app hα ⟨WalkingPair.right⟩)]
constructor
· rintro H ⟨⟨⟩⟩
exacts [H.1, H.2]
· intro H
exact ⟨H _, H _⟩
theorem BinaryCofan.isVanKampen_mk {X Y : C} (c : BinaryCofan X Y)
(cofans : ∀ X Y : C, BinaryCofan X Y) (colimits : ∀ X Y, IsColimit (cofans X Y))
(cones : ∀ {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z), PullbackCone f g)
(limits : ∀ {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z), IsLimit (cones f g))
(h₁ : ∀ {X' Y' : C} (αX : X' ⟶ X) (αY : Y' ⟶ Y) (f : (cofans X' Y').pt ⟶ c.pt)
(_ : αX ≫ c.inl = (cofans X' Y').inl ≫ f) (_ : αY ≫ c.inr = (cofans X' Y').inr ≫ f),
IsPullback (cofans X' Y').inl αX f c.inl ∧ IsPullback (cofans X' Y').inr αY f c.inr)
(h₂ : ∀ {Z : C} (f : Z ⟶ c.pt),
IsColimit (BinaryCofan.mk (cones f c.inl).fst (cones f c.inr).fst)) :
IsVanKampenColimit c := by
rw [BinaryCofan.isVanKampen_iff]
introv hX hY
constructor
· rintro ⟨h⟩
let e := h.coconePointUniqueUpToIso (colimits _ _)
obtain ⟨hl, hr⟩ := h₁ αX αY (e.inv ≫ f) (by simp [e, hX]) (by simp [e, hY])
| Mathlib/CategoryTheory/Limits/VanKampen.lean | 505 | 534 |
/-
Copyright (c) 2023 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.Algebra.Homology.ShortComplex.PreservesHomology
import Mathlib.Algebra.Homology.ShortComplex.Abelian
import Mathlib.Algebra.Homology.ShortComplex.QuasiIso
import Mathlib.CategoryTheory.Abelian.Opposite
import Mathlib.CategoryTheory.Preadditive.AdditiveFunctor
import Mathlib.CategoryTheory.Preadditive.Injective.Basic
/-!
# Exact short complexes
When `S : ShortComplex C`, this file defines a structure
`S.Exact` which expresses the exactness of `S`, i.e. there
exists a homology data `h : S.HomologyData` such that
`h.left.H` is zero. When `[S.HasHomology]`, it is equivalent
to the assertion `IsZero S.homology`.
Almost by construction, this notion of exactness is self dual,
see `Exact.op` and `Exact.unop`.
-/
namespace CategoryTheory
open Category Limits ZeroObject Preadditive
variable {C D : Type*} [Category C] [Category D]
namespace ShortComplex
section
variable
[HasZeroMorphisms C] [HasZeroMorphisms D] (S : ShortComplex C) {S₁ S₂ : ShortComplex C}
/-- The assertion that the short complex `S : ShortComplex C` is exact. -/
structure Exact : Prop where
/-- the condition that there exists an homology data whose `left.H` field is zero -/
condition : ∃ (h : S.HomologyData), IsZero h.left.H
variable {S}
lemma Exact.hasHomology (h : S.Exact) : S.HasHomology :=
HasHomology.mk' h.condition.choose
lemma Exact.hasZeroObject (h : S.Exact) : HasZeroObject C :=
⟨h.condition.choose.left.H, h.condition.choose_spec⟩
variable (S)
lemma exact_iff_isZero_homology [S.HasHomology] :
S.Exact ↔ IsZero S.homology := by
constructor
· rintro ⟨⟨h', z⟩⟩
exact IsZero.of_iso z h'.left.homologyIso
· intro h
exact ⟨⟨_, h⟩⟩
variable {S}
lemma LeftHomologyData.exact_iff [S.HasHomology]
(h : S.LeftHomologyData) :
S.Exact ↔ IsZero h.H := by
rw [S.exact_iff_isZero_homology]
exact Iso.isZero_iff h.homologyIso
lemma RightHomologyData.exact_iff [S.HasHomology]
(h : S.RightHomologyData) :
S.Exact ↔ IsZero h.H := by
rw [S.exact_iff_isZero_homology]
exact Iso.isZero_iff h.homologyIso
variable (S)
lemma exact_iff_isZero_leftHomology [S.HasHomology] :
S.Exact ↔ IsZero S.leftHomology :=
LeftHomologyData.exact_iff _
lemma exact_iff_isZero_rightHomology [S.HasHomology] :
S.Exact ↔ IsZero S.rightHomology :=
RightHomologyData.exact_iff _
variable {S}
lemma HomologyData.exact_iff (h : S.HomologyData) :
S.Exact ↔ IsZero h.left.H := by
haveI := HasHomology.mk' h
exact LeftHomologyData.exact_iff h.left
lemma HomologyData.exact_iff' (h : S.HomologyData) :
S.Exact ↔ IsZero h.right.H := by
haveI := HasHomology.mk' h
exact RightHomologyData.exact_iff h.right
variable (S)
lemma exact_iff_homology_iso_zero [S.HasHomology] [HasZeroObject C] :
S.Exact ↔ Nonempty (S.homology ≅ 0) := by
rw [exact_iff_isZero_homology]
constructor
· intro h
exact ⟨h.isoZero⟩
· rintro ⟨e⟩
exact IsZero.of_iso (isZero_zero C) e
lemma exact_of_iso (e : S₁ ≅ S₂) (h : S₁.Exact) : S₂.Exact := by
obtain ⟨⟨h, z⟩⟩ := h
exact ⟨⟨HomologyData.ofIso e h, z⟩⟩
lemma exact_iff_of_iso (e : S₁ ≅ S₂) : S₁.Exact ↔ S₂.Exact :=
⟨exact_of_iso e, exact_of_iso e.symm⟩
lemma exact_and_mono_f_iff_of_iso (e : S₁ ≅ S₂) :
S₁.Exact ∧ Mono S₁.f ↔ S₂.Exact ∧ Mono S₂.f := by
have : Mono S₁.f ↔ Mono S₂.f :=
(MorphismProperty.monomorphisms C).arrow_mk_iso_iff
(Arrow.isoMk (ShortComplex.π₁.mapIso e) (ShortComplex.π₂.mapIso e) e.hom.comm₁₂)
rw [exact_iff_of_iso e, this]
lemma exact_and_epi_g_iff_of_iso (e : S₁ ≅ S₂) :
S₁.Exact ∧ Epi S₁.g ↔ S₂.Exact ∧ Epi S₂.g := by
have : Epi S₁.g ↔ Epi S₂.g :=
(MorphismProperty.epimorphisms C).arrow_mk_iso_iff
(Arrow.isoMk (ShortComplex.π₂.mapIso e) (ShortComplex.π₃.mapIso e) e.hom.comm₂₃)
rw [exact_iff_of_iso e, this]
lemma exact_of_isZero_X₂ (h : IsZero S.X₂) : S.Exact := by
rw [(HomologyData.ofZeros S (IsZero.eq_of_tgt h _ _) (IsZero.eq_of_src h _ _)).exact_iff]
exact h
lemma exact_iff_of_epi_of_isIso_of_mono (φ : S₁ ⟶ S₂) [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] :
S₁.Exact ↔ S₂.Exact := by
constructor
· rintro ⟨h₁, z₁⟩
exact ⟨HomologyData.ofEpiOfIsIsoOfMono φ h₁, z₁⟩
· rintro ⟨h₂, z₂⟩
exact ⟨HomologyData.ofEpiOfIsIsoOfMono' φ h₂, z₂⟩
variable {S}
lemma HomologyData.exact_iff_i_p_zero (h : S.HomologyData) :
S.Exact ↔ h.left.i ≫ h.right.p = 0 := by
haveI := HasHomology.mk' h
rw [h.left.exact_iff, ← h.comm]
constructor
· intro z
rw [IsZero.eq_of_src z h.iso.hom 0, zero_comp, comp_zero]
· intro eq
simp only [IsZero.iff_id_eq_zero, ← cancel_mono h.iso.hom, id_comp, ← cancel_mono h.right.ι,
← cancel_epi h.left.π, eq, zero_comp, comp_zero]
variable (S)
lemma exact_iff_i_p_zero [S.HasHomology] (h₁ : S.LeftHomologyData)
(h₂ : S.RightHomologyData) :
S.Exact ↔ h₁.i ≫ h₂.p = 0 :=
(HomologyData.ofIsIsoLeftRightHomologyComparison' h₁ h₂).exact_iff_i_p_zero
lemma exact_iff_iCycles_pOpcycles_zero [S.HasHomology] :
S.Exact ↔ S.iCycles ≫ S.pOpcycles = 0 :=
S.exact_iff_i_p_zero _ _
lemma exact_iff_kernel_ι_comp_cokernel_π_zero [S.HasHomology]
[HasKernel S.g] [HasCokernel S.f] :
S.Exact ↔ kernel.ι S.g ≫ cokernel.π S.f = 0 := by
haveI := HasLeftHomology.hasCokernel S
haveI := HasRightHomology.hasKernel S
exact S.exact_iff_i_p_zero (LeftHomologyData.ofHasKernelOfHasCokernel S)
(RightHomologyData.ofHasCokernelOfHasKernel S)
variable {S}
lemma Exact.op (h : S.Exact) : S.op.Exact := by
obtain ⟨h, z⟩ := h
exact ⟨⟨h.op, (IsZero.of_iso z h.iso.symm).op⟩⟩
lemma Exact.unop {S : ShortComplex Cᵒᵖ} (h : S.Exact) : S.unop.Exact := by
obtain ⟨h, z⟩ := h
exact ⟨⟨h.unop, (IsZero.of_iso z h.iso.symm).unop⟩⟩
variable (S)
@[simp]
lemma exact_op_iff : S.op.Exact ↔ S.Exact :=
⟨Exact.unop, Exact.op⟩
@[simp]
lemma exact_unop_iff (S : ShortComplex Cᵒᵖ) : S.unop.Exact ↔ S.Exact :=
S.unop.exact_op_iff.symm
variable {S}
lemma LeftHomologyData.exact_map_iff (h : S.LeftHomologyData) (F : C ⥤ D)
[F.PreservesZeroMorphisms] [h.IsPreservedBy F] [(S.map F).HasHomology] :
(S.map F).Exact ↔ IsZero (F.obj h.H) :=
(h.map F).exact_iff
lemma RightHomologyData.exact_map_iff (h : S.RightHomologyData) (F : C ⥤ D)
[F.PreservesZeroMorphisms] [h.IsPreservedBy F] [(S.map F).HasHomology] :
(S.map F).Exact ↔ IsZero (F.obj h.H) :=
(h.map F).exact_iff
lemma Exact.map_of_preservesLeftHomologyOf (h : S.Exact) (F : C ⥤ D)
[F.PreservesZeroMorphisms] [F.PreservesLeftHomologyOf S]
[(S.map F).HasHomology] : (S.map F).Exact := by
have := h.hasHomology
rw [S.leftHomologyData.exact_iff, IsZero.iff_id_eq_zero] at h
rw [S.leftHomologyData.exact_map_iff F, IsZero.iff_id_eq_zero,
← F.map_id, h, F.map_zero]
lemma Exact.map_of_preservesRightHomologyOf (h : S.Exact) (F : C ⥤ D)
[F.PreservesZeroMorphisms] [F.PreservesRightHomologyOf S]
[(S.map F).HasHomology] : (S.map F).Exact := by
have : S.HasHomology := h.hasHomology
rw [S.rightHomologyData.exact_iff, IsZero.iff_id_eq_zero] at h
rw [S.rightHomologyData.exact_map_iff F, IsZero.iff_id_eq_zero,
← F.map_id, h, F.map_zero]
lemma Exact.map (h : S.Exact) (F : C ⥤ D)
[F.PreservesZeroMorphisms] [F.PreservesLeftHomologyOf S]
[F.PreservesRightHomologyOf S] : (S.map F).Exact := by
have := h.hasHomology
exact h.map_of_preservesLeftHomologyOf F
variable (S)
lemma exact_map_iff_of_faithful [S.HasHomology]
(F : C ⥤ D) [F.PreservesZeroMorphisms] [F.PreservesLeftHomologyOf S]
[F.PreservesRightHomologyOf S] [F.Faithful] :
(S.map F).Exact ↔ S.Exact := by
constructor
· intro h
rw [S.leftHomologyData.exact_iff, IsZero.iff_id_eq_zero]
rw [(S.leftHomologyData.map F).exact_iff, IsZero.iff_id_eq_zero,
LeftHomologyData.map_H] at h
apply F.map_injective
rw [F.map_id, F.map_zero, h]
· intro h
exact h.map F
variable {S}
@[reassoc]
lemma Exact.comp_eq_zero (h : S.Exact) {X Y : C} {a : X ⟶ S.X₂} (ha : a ≫ S.g = 0)
{b : S.X₂ ⟶ Y} (hb : S.f ≫ b = 0) : a ≫ b = 0 := by
have := h.hasHomology
have eq := h
rw [exact_iff_iCycles_pOpcycles_zero] at eq
rw [← S.liftCycles_i a ha, ← S.p_descOpcycles b hb, assoc, reassoc_of% eq,
zero_comp, comp_zero]
lemma Exact.isZero_of_both_zeros (ex : S.Exact) (hf : S.f = 0) (hg : S.g = 0) :
IsZero S.X₂ :=
(ShortComplex.HomologyData.ofZeros S hf hg).exact_iff.1 ex
end
section Preadditive
variable [Preadditive C] [Preadditive D] (S : ShortComplex C)
lemma exact_iff_mono [HasZeroObject C] (hf : S.f = 0) :
S.Exact ↔ Mono S.g := by
constructor
· intro h
have := h.hasHomology
simp only [exact_iff_isZero_homology] at h
have := S.isIso_pOpcycles hf
have := mono_of_isZero_kernel' _ S.homologyIsKernel h
rw [← S.p_fromOpcycles]
apply mono_comp
· intro
rw [(HomologyData.ofIsLimitKernelFork S hf _
(KernelFork.IsLimit.ofMonoOfIsZero (KernelFork.ofι (0 : 0 ⟶ S.X₂) zero_comp)
inferInstance (isZero_zero C))).exact_iff]
exact isZero_zero C
lemma exact_iff_epi [HasZeroObject C] (hg : S.g = 0) :
S.Exact ↔ Epi S.f := by
constructor
· intro h
have := h.hasHomology
simp only [exact_iff_isZero_homology] at h
haveI := S.isIso_iCycles hg
haveI : Epi S.toCycles := epi_of_isZero_cokernel' _ S.homologyIsCokernel h
rw [← S.toCycles_i]
apply epi_comp
· intro
rw [(HomologyData.ofIsColimitCokernelCofork S hg _
(CokernelCofork.IsColimit.ofEpiOfIsZero (CokernelCofork.ofπ (0 : S.X₂ ⟶ 0) comp_zero)
inferInstance (isZero_zero C))).exact_iff]
exact isZero_zero C
variable {S}
lemma Exact.epi_f' (hS : S.Exact) (h : LeftHomologyData S) : Epi h.f' :=
epi_of_isZero_cokernel' _ h.hπ (by
haveI := hS.hasHomology
dsimp
simpa only [← h.exact_iff] using hS)
lemma Exact.mono_g' (hS : S.Exact) (h : RightHomologyData S) : Mono h.g' :=
mono_of_isZero_kernel' _ h.hι (by
haveI := hS.hasHomology
dsimp
simpa only [← h.exact_iff] using hS)
lemma Exact.epi_toCycles (hS : S.Exact) [S.HasLeftHomology] : Epi S.toCycles :=
hS.epi_f' _
lemma Exact.mono_fromOpcycles (hS : S.Exact) [S.HasRightHomology] : Mono S.fromOpcycles :=
hS.mono_g' _
lemma LeftHomologyData.exact_iff_epi_f' [S.HasHomology] (h : LeftHomologyData S) :
S.Exact ↔ Epi h.f' := by
constructor
· intro hS
exact hS.epi_f' h
· intro
simp only [h.exact_iff, IsZero.iff_id_eq_zero, ← cancel_epi h.π, ← cancel_epi h.f',
comp_id, h.f'_π, comp_zero]
lemma RightHomologyData.exact_iff_mono_g' [S.HasHomology] (h : RightHomologyData S) :
S.Exact ↔ Mono h.g' := by
constructor
· intro hS
exact hS.mono_g' h
· intro
simp only [h.exact_iff, IsZero.iff_id_eq_zero, ← cancel_mono h.ι, ← cancel_mono h.g',
id_comp, h.ι_g', zero_comp]
/-- Given an exact short complex `S` and a limit kernel fork `kf` for `S.g`, this is the
left homology data for `S` with `K := kf.pt` and `H := 0`. -/
@[simps]
noncomputable def Exact.leftHomologyDataOfIsLimitKernelFork
(hS : S.Exact) [HasZeroObject C] (kf : KernelFork S.g) (hkf : IsLimit kf) :
S.LeftHomologyData where
K := kf.pt
H := 0
i := kf.ι
π := 0
wi := kf.condition
hi := IsLimit.ofIsoLimit hkf (Fork.ext (Iso.refl _) (by simp))
wπ := comp_zero
hπ := CokernelCofork.IsColimit.ofEpiOfIsZero _ (by
have := hS.hasHomology
refine ((MorphismProperty.epimorphisms C).arrow_mk_iso_iff ?_).1
hS.epi_toCycles
refine Arrow.isoMk (Iso.refl _)
(IsLimit.conePointUniqueUpToIso S.cyclesIsKernel hkf) ?_
apply Fork.IsLimit.hom_ext hkf
simp [IsLimit.conePointUniqueUpToIso]) (isZero_zero C)
/-- Given an exact short complex `S` and a colimit cokernel cofork `cc` for `S.f`, this is the
right homology data for `S` with `Q := cc.pt` and `H := 0`. -/
@[simps]
noncomputable def Exact.rightHomologyDataOfIsColimitCokernelCofork
(hS : S.Exact) [HasZeroObject C] (cc : CokernelCofork S.f) (hcc : IsColimit cc) :
S.RightHomologyData where
Q := cc.pt
H := 0
p := cc.π
ι := 0
wp := cc.condition
hp := IsColimit.ofIsoColimit hcc (Cofork.ext (Iso.refl _) (by simp))
wι := zero_comp
hι := KernelFork.IsLimit.ofMonoOfIsZero _ (by
have := hS.hasHomology
refine ((MorphismProperty.monomorphisms C).arrow_mk_iso_iff ?_).2
hS.mono_fromOpcycles
refine Arrow.isoMk (IsColimit.coconePointUniqueUpToIso hcc S.opcyclesIsCokernel)
(Iso.refl _) ?_
apply Cofork.IsColimit.hom_ext hcc
simp [IsColimit.coconePointUniqueUpToIso]) (isZero_zero C)
variable (S)
lemma exact_iff_epi_toCycles [S.HasHomology] : S.Exact ↔ Epi S.toCycles :=
S.leftHomologyData.exact_iff_epi_f'
lemma exact_iff_mono_fromOpcycles [S.HasHomology] : S.Exact ↔ Mono S.fromOpcycles :=
S.rightHomologyData.exact_iff_mono_g'
lemma exact_iff_epi_kernel_lift [S.HasHomology] [HasKernel S.g] :
S.Exact ↔ Epi (kernel.lift S.g S.f S.zero) := by
rw [exact_iff_epi_toCycles]
apply (MorphismProperty.epimorphisms C).arrow_mk_iso_iff
exact Arrow.isoMk (Iso.refl _) S.cyclesIsoKernel (by aesop_cat)
lemma exact_iff_mono_cokernel_desc [S.HasHomology] [HasCokernel S.f] :
S.Exact ↔ Mono (cokernel.desc S.f S.g S.zero) := by
rw [exact_iff_mono_fromOpcycles]
refine (MorphismProperty.monomorphisms C).arrow_mk_iso_iff (Iso.symm ?_)
exact Arrow.isoMk S.opcyclesIsoCokernel.symm (Iso.refl _) (by aesop_cat)
lemma QuasiIso.exact_iff {S₁ S₂ : ShortComplex C} (φ : S₁ ⟶ S₂)
[S₁.HasHomology] [S₂.HasHomology] [QuasiIso φ] : S₁.Exact ↔ S₂.Exact := by
simp only [exact_iff_isZero_homology]
exact Iso.isZero_iff (asIso (homologyMap φ))
lemma exact_of_f_is_kernel (hS : IsLimit (KernelFork.ofι S.f S.zero))
[S.HasHomology] : S.Exact := by
rw [exact_iff_epi_toCycles]
have : IsSplitEpi S.toCycles :=
⟨⟨{ section_ := hS.lift (KernelFork.ofι S.iCycles S.iCycles_g)
id := by
rw [← cancel_mono S.iCycles, assoc, toCycles_i, id_comp]
exact Fork.IsLimit.lift_ι hS }⟩⟩
infer_instance
lemma exact_of_g_is_cokernel (hS : IsColimit (CokernelCofork.ofπ S.g S.zero))
[S.HasHomology] : S.Exact := by
rw [exact_iff_mono_fromOpcycles]
have : IsSplitMono S.fromOpcycles :=
⟨⟨{ retraction := hS.desc (CokernelCofork.ofπ S.pOpcycles S.f_pOpcycles)
id := by
rw [← cancel_epi S.pOpcycles, p_fromOpcycles_assoc, comp_id]
exact Cofork.IsColimit.π_desc hS }⟩⟩
infer_instance
variable {S}
lemma Exact.mono_g (hS : S.Exact) (hf : S.f = 0) : Mono S.g := by
have := hS.hasHomology
have := hS.epi_toCycles
have : S.iCycles = 0 := by rw [← cancel_epi S.toCycles, comp_zero, toCycles_i, hf]
apply Preadditive.mono_of_cancel_zero
intro A x₂ hx₂
rw [← S.liftCycles_i x₂ hx₂, this, comp_zero]
lemma Exact.epi_f (hS : S.Exact) (hg : S.g = 0) : Epi S.f := by
have := hS.hasHomology
have := hS.mono_fromOpcycles
have : S.pOpcycles = 0 := by rw [← cancel_mono S.fromOpcycles, zero_comp, p_fromOpcycles, hg]
apply Preadditive.epi_of_cancel_zero
intro A x₂ hx₂
rw [← S.p_descOpcycles x₂ hx₂, this, zero_comp]
lemma Exact.mono_g_iff (hS : S.Exact) : Mono S.g ↔ S.f = 0 := by
constructor
| · intro
rw [← cancel_mono S.g, zero, zero_comp]
· exact hS.mono_g
lemma Exact.epi_f_iff (hS : S.Exact) : Epi S.f ↔ S.g = 0 := by
constructor
· intro
| Mathlib/Algebra/Homology/ShortComplex/Exact.lean | 445 | 451 |
/-
Copyright (c) 2024 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import Mathlib.Order.CompleteLatticeIntervals
import Mathlib.Order.CompactlyGenerated.Basic
/-!
# Results about compactness properties for intervals in complete lattices
-/
variable {ι α : Type*} [CompleteLattice α]
namespace Set.Iic
| theorem isCompactElement {a : α} {b : Iic a} (h : CompleteLattice.IsCompactElement (b : α)) :
CompleteLattice.IsCompactElement b := by
simp only [CompleteLattice.isCompactElement_iff, Finset.sup_eq_iSup] at h ⊢
intro ι s hb
replace hb : (b : α) ≤ iSup ((↑) ∘ s) := le_trans hb <| (coe_iSup s) ▸ le_refl _
obtain ⟨t, ht⟩ := h ι ((↑) ∘ s) hb
exact ⟨t, (by simpa using ht : (b : α) ≤ _)⟩
| Mathlib/Order/CompactlyGenerated/Intervals.lean | 18 | 24 |
/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import Mathlib.Analysis.SpecialFunctions.Trigonometric.Arctan
import Mathlib.Geometry.Euclidean.Angle.Unoriented.Affine
/-!
# Right-angled triangles
This file proves basic geometrical results about distances and angles in (possibly degenerate)
right-angled triangles in real inner product spaces and Euclidean affine spaces.
## Implementation notes
Results in this file are generally given in a form with only those non-degeneracy conditions
needed for the particular result, rather than requiring affine independence of the points of a
triangle unnecessarily.
## References
* https://en.wikipedia.org/wiki/Pythagorean_theorem
-/
noncomputable section
open scoped EuclideanGeometry
open scoped Real
open scoped RealInnerProductSpace
namespace InnerProductGeometry
variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V]
/-- Pythagorean theorem, if-and-only-if vector angle form. -/
theorem norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) :
‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ angle x y = π / 2 := by
rw [norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero]
exact inner_eq_zero_iff_angle_eq_pi_div_two x y
/-- Pythagorean theorem, vector angle form. -/
theorem norm_add_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = π / 2) :
‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ :=
(norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h
/-- Pythagorean theorem, subtracting vectors, if-and-only-if vector angle form. -/
theorem norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) :
‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ angle x y = π / 2 := by
rw [norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero]
exact inner_eq_zero_iff_angle_eq_pi_div_two x y
/-- Pythagorean theorem, subtracting vectors, vector angle form. -/
theorem norm_sub_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = π / 2) :
‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ :=
(norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h
/-- An angle in a right-angled triangle expressed using `arccos`. -/
theorem angle_add_eq_arccos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
angle x (x + y) = Real.arccos (‖x‖ / ‖x + y‖) := by
rw [angle, inner_add_right, h, add_zero, real_inner_self_eq_norm_mul_norm]
by_cases hx : ‖x‖ = 0; · simp [hx]
rw [div_mul_eq_div_div, mul_self_div_self]
/-- An angle in a right-angled triangle expressed using `arcsin`. -/
theorem angle_add_eq_arcsin_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) :
angle x (x + y) = Real.arcsin (‖y‖ / ‖x + y‖) := by
have hxy : ‖x + y‖ ^ 2 ≠ 0 := by
rw [pow_two, norm_add_sq_eq_norm_sq_add_norm_sq_real h, ne_comm]
refine ne_of_lt ?_
rcases h0 with (h0 | h0)
· exact
Left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _)
· exact
Left.add_pos_of_nonneg_of_pos (mul_self_nonneg _) (mul_self_pos.2 (norm_ne_zero_iff.2 h0))
rw [angle_add_eq_arccos_of_inner_eq_zero h,
Real.arccos_eq_arcsin (div_nonneg (norm_nonneg _) (norm_nonneg _)), div_pow, one_sub_div hxy]
nth_rw 1 [pow_two]
rw [norm_add_sq_eq_norm_sq_add_norm_sq_real h, pow_two, add_sub_cancel_left, ← pow_two, ← div_pow,
Real.sqrt_sq (div_nonneg (norm_nonneg _) (norm_nonneg _))]
/-- An angle in a right-angled triangle expressed using `arctan`. -/
theorem angle_add_eq_arctan_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) :
angle x (x + y) = Real.arctan (‖y‖ / ‖x‖) := by
rw [angle_add_eq_arcsin_of_inner_eq_zero h (Or.inl h0), Real.arctan_eq_arcsin, ←
div_mul_eq_div_div, norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h]
nth_rw 3 [← Real.sqrt_sq (norm_nonneg x)]
rw_mod_cast [← Real.sqrt_mul (sq_nonneg _), div_pow, pow_two, pow_two, mul_add, mul_one, mul_div,
mul_comm (‖x‖ * ‖x‖), ← mul_div, div_self (mul_self_pos.2 (norm_ne_zero_iff.2 h0)).ne', mul_one]
/-- An angle in a non-degenerate right-angled triangle is positive. -/
theorem angle_add_pos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) :
0 < angle x (x + y) := by
rw [angle_add_eq_arccos_of_inner_eq_zero h, Real.arccos_pos,
norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h]
by_cases hx : x = 0; · simp [hx]
rw [div_lt_one (Real.sqrt_pos.2 (Left.add_pos_of_pos_of_nonneg (mul_self_pos.2
(norm_ne_zero_iff.2 hx)) (mul_self_nonneg _))), Real.lt_sqrt (norm_nonneg _), pow_two]
simpa [hx] using h0
/-- An angle in a right-angled triangle is at most `π / 2`. -/
theorem angle_add_le_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
angle x (x + y) ≤ π / 2 := by
rw [angle_add_eq_arccos_of_inner_eq_zero h, Real.arccos_le_pi_div_two]
exact div_nonneg (norm_nonneg _) (norm_nonneg _)
/-- An angle in a non-degenerate right-angled triangle is less than `π / 2`. -/
theorem angle_add_lt_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) :
angle x (x + y) < π / 2 := by
rw [angle_add_eq_arccos_of_inner_eq_zero h, Real.arccos_lt_pi_div_two,
norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h]
exact div_pos (norm_pos_iff.2 h0) (Real.sqrt_pos.2 (Left.add_pos_of_pos_of_nonneg
(mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _)))
/-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/
theorem cos_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
Real.cos (angle x (x + y)) = ‖x‖ / ‖x + y‖ := by
rw [angle_add_eq_arccos_of_inner_eq_zero h,
Real.cos_arccos (le_trans (by norm_num) (div_nonneg (norm_nonneg _) (norm_nonneg _)))
(div_le_one_of_le₀ _ (norm_nonneg _))]
rw [mul_self_le_mul_self_iff (norm_nonneg _) (norm_nonneg _),
norm_add_sq_eq_norm_sq_add_norm_sq_real h]
exact le_add_of_nonneg_right (mul_self_nonneg _)
/-- The sine of an angle in a right-angled triangle as a ratio of sides. -/
theorem sin_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) :
Real.sin (angle x (x + y)) = ‖y‖ / ‖x + y‖ := by
rw [angle_add_eq_arcsin_of_inner_eq_zero h h0,
Real.sin_arcsin (le_trans (by norm_num) (div_nonneg (norm_nonneg _) (norm_nonneg _)))
(div_le_one_of_le₀ _ (norm_nonneg _))]
rw [mul_self_le_mul_self_iff (norm_nonneg _) (norm_nonneg _),
norm_add_sq_eq_norm_sq_add_norm_sq_real h]
exact le_add_of_nonneg_left (mul_self_nonneg _)
/-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/
theorem tan_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
Real.tan (angle x (x + y)) = ‖y‖ / ‖x‖ := by
by_cases h0 : x = 0; · simp [h0]
rw [angle_add_eq_arctan_of_inner_eq_zero h h0, Real.tan_arctan]
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side. -/
theorem cos_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
Real.cos (angle x (x + y)) * ‖x + y‖ = ‖x‖ := by
rw [cos_angle_add_of_inner_eq_zero h]
by_cases hxy : ‖x + y‖ = 0
· have h' := norm_add_sq_eq_norm_sq_add_norm_sq_real h
rw [hxy, zero_mul, eq_comm,
add_eq_zero_iff_of_nonneg (mul_self_nonneg ‖x‖) (mul_self_nonneg ‖y‖), mul_self_eq_zero] at h'
simp [h'.1]
· exact div_mul_cancel₀ _ hxy
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side. -/
theorem sin_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
Real.sin (angle x (x + y)) * ‖x + y‖ = ‖y‖ := by
by_cases h0 : x = 0 ∧ y = 0; · simp [h0]
rw [not_and_or] at h0
rw [sin_angle_add_of_inner_eq_zero h h0, div_mul_cancel₀]
rw [← mul_self_ne_zero, norm_add_sq_eq_norm_sq_add_norm_sq_real h]
refine (ne_of_lt ?_).symm
rcases h0 with (h0 | h0)
· exact Left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _)
· exact Left.add_pos_of_nonneg_of_pos (mul_self_nonneg _) (mul_self_pos.2 (norm_ne_zero_iff.2 h0))
/-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side. -/
theorem tan_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) :
Real.tan (angle x (x + y)) * ‖x‖ = ‖y‖ := by
rw [tan_angle_add_of_inner_eq_zero h]
rcases h0 with (h0 | h0) <;> simp [h0]
/-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the
hypotenuse. -/
theorem norm_div_cos_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) :
‖x‖ / Real.cos (angle x (x + y)) = ‖x + y‖ := by
rw [cos_angle_add_of_inner_eq_zero h]
rcases h0 with (h0 | h0)
· rw [div_div_eq_mul_div, mul_comm, div_eq_mul_inv, mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)]
· simp [h0]
/-- A side of a right-angled triangle divided by the sine of the opposite angle equals the
hypotenuse. -/
theorem norm_div_sin_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) :
‖y‖ / Real.sin (angle x (x + y)) = ‖x + y‖ := by
rcases h0 with (h0 | h0); · simp [h0]
rw [sin_angle_add_of_inner_eq_zero h (Or.inr h0), div_div_eq_mul_div, mul_comm, div_eq_mul_inv,
mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)]
/-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the
adjacent side. -/
theorem norm_div_tan_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) :
‖y‖ / Real.tan (angle x (x + y)) = ‖x‖ := by
rw [tan_angle_add_of_inner_eq_zero h]
rcases h0 with (h0 | h0)
· simp [h0]
· rw [div_div_eq_mul_div, mul_comm, div_eq_mul_inv, mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)]
/-- An angle in a right-angled triangle expressed using `arccos`, version subtracting vectors. -/
theorem angle_sub_eq_arccos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
angle x (x - y) = Real.arccos (‖x‖ / ‖x - y‖) := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [sub_eq_add_neg, angle_add_eq_arccos_of_inner_eq_zero h]
/-- An angle in a right-angled triangle expressed using `arcsin`, version subtracting vectors. -/
theorem angle_sub_eq_arcsin_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) :
angle x (x - y) = Real.arcsin (‖y‖ / ‖x - y‖) := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [or_comm, ← neg_ne_zero, or_comm] at h0
rw [sub_eq_add_neg, angle_add_eq_arcsin_of_inner_eq_zero h h0, norm_neg]
/-- An angle in a right-angled triangle expressed using `arctan`, version subtracting vectors. -/
theorem angle_sub_eq_arctan_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) :
angle x (x - y) = Real.arctan (‖y‖ / ‖x‖) := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [sub_eq_add_neg, angle_add_eq_arctan_of_inner_eq_zero h h0, norm_neg]
/-- An angle in a non-degenerate right-angled triangle is positive, version subtracting
vectors. -/
theorem angle_sub_pos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) :
0 < angle x (x - y) := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [← neg_ne_zero] at h0
rw [sub_eq_add_neg]
exact angle_add_pos_of_inner_eq_zero h h0
/-- An angle in a right-angled triangle is at most `π / 2`, version subtracting vectors. -/
theorem angle_sub_le_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
angle x (x - y) ≤ π / 2 := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [sub_eq_add_neg]
exact angle_add_le_pi_div_two_of_inner_eq_zero h
/-- An angle in a non-degenerate right-angled triangle is less than `π / 2`, version subtracting
vectors. -/
theorem angle_sub_lt_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) :
angle x (x - y) < π / 2 := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [sub_eq_add_neg]
exact angle_add_lt_pi_div_two_of_inner_eq_zero h h0
/-- The cosine of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem cos_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
Real.cos (angle x (x - y)) = ‖x‖ / ‖x - y‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [sub_eq_add_neg, cos_angle_add_of_inner_eq_zero h]
/-- The sine of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem sin_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) :
Real.sin (angle x (x - y)) = ‖y‖ / ‖x - y‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [or_comm, ← neg_ne_zero, or_comm] at h0
rw [sub_eq_add_neg, sin_angle_add_of_inner_eq_zero h h0, norm_neg]
/-- The tangent of an angle in a right-angled triangle as a ratio of sides, version subtracting
vectors. -/
theorem tan_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
Real.tan (angle x (x - y)) = ‖y‖ / ‖x‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [sub_eq_add_neg, tan_angle_add_of_inner_eq_zero h, norm_neg]
/-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
adjacent side, version subtracting vectors. -/
theorem cos_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
Real.cos (angle x (x - y)) * ‖x - y‖ = ‖x‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [sub_eq_add_neg, cos_angle_add_mul_norm_of_inner_eq_zero h]
/-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the
opposite side, version subtracting vectors. -/
theorem sin_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) :
Real.sin (angle x (x - y)) * ‖x - y‖ = ‖y‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [sub_eq_add_neg, sin_angle_add_mul_norm_of_inner_eq_zero h, norm_neg]
/-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals
the opposite side, version subtracting vectors. -/
theorem tan_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) :
Real.tan (angle x (x - y)) * ‖x‖ = ‖y‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [← neg_eq_zero] at h0
rw [sub_eq_add_neg, tan_angle_add_mul_norm_of_inner_eq_zero h h0, norm_neg]
/-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the
hypotenuse, version subtracting vectors. -/
theorem norm_div_cos_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) :
‖x‖ / Real.cos (angle x (x - y)) = ‖x - y‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [← neg_eq_zero] at h0
rw [sub_eq_add_neg, norm_div_cos_angle_add_of_inner_eq_zero h h0]
/-- A side of a right-angled triangle divided by the sine of the opposite angle equals the
hypotenuse, version subtracting vectors. -/
theorem norm_div_sin_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) :
‖y‖ / Real.sin (angle x (x - y)) = ‖x - y‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [← neg_ne_zero] at h0
rw [sub_eq_add_neg, ← norm_neg, norm_div_sin_angle_add_of_inner_eq_zero h h0]
/-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the
adjacent side, version subtracting vectors. -/
theorem norm_div_tan_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) :
‖y‖ / Real.tan (angle x (x - y)) = ‖x‖ := by
rw [← neg_eq_zero, ← inner_neg_right] at h
rw [← neg_ne_zero] at h0
rw [sub_eq_add_neg, ← norm_neg, norm_div_tan_angle_add_of_inner_eq_zero h h0]
end InnerProductGeometry
namespace EuclideanGeometry
open InnerProductGeometry
variable {V : Type*} {P : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P]
[NormedAddTorsor V P]
/-- **Pythagorean theorem**, if-and-only-if angle-at-point form. -/
theorem dist_sq_eq_dist_sq_add_dist_sq_iff_angle_eq_pi_div_two (p₁ p₂ p₃ : P) :
dist p₁ p₃ * dist p₁ p₃ = dist p₁ p₂ * dist p₁ p₂ + dist p₃ p₂ * dist p₃ p₂ ↔
∠ p₁ p₂ p₃ = π / 2 := by
erw [dist_comm p₃ p₂, dist_eq_norm_vsub V p₁ p₃, dist_eq_norm_vsub V p₁ p₂,
dist_eq_norm_vsub V p₂ p₃, ← norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two,
vsub_sub_vsub_cancel_right p₁, ← neg_vsub_eq_vsub_rev p₂ p₃, norm_neg]
/-- An angle in a right-angled triangle expressed using `arccos`. -/
theorem angle_eq_arccos_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) :
∠ p₂ p₃ p₁ = Real.arccos (dist p₃ p₂ / dist p₁ p₃) := by
rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ←
inner_neg_left, neg_vsub_eq_vsub_rev] at h
rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃,
add_comm, angle_add_eq_arccos_of_inner_eq_zero h]
/-- An angle in a right-angled triangle expressed using `arcsin`. -/
theorem angle_eq_arcsin_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2)
(h0 : p₁ ≠ p₂ ∨ p₃ ≠ p₂) : ∠ p₂ p₃ p₁ = Real.arcsin (dist p₁ p₂ / dist p₁ p₃) := by
rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ←
inner_neg_left, neg_vsub_eq_vsub_rev] at h
rw [← @vsub_ne_zero V, @ne_comm _ p₃, ← @vsub_ne_zero V _ _ _ p₂, or_comm] at h0
rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃,
add_comm, angle_add_eq_arcsin_of_inner_eq_zero h h0]
/-- An angle in a right-angled triangle expressed using `arctan`. -/
theorem angle_eq_arctan_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2)
(h0 : p₃ ≠ p₂) : ∠ p₂ p₃ p₁ = Real.arctan (dist p₁ p₂ / dist p₃ p₂) := by
rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ←
inner_neg_left, neg_vsub_eq_vsub_rev] at h
rw [ne_comm, ← @vsub_ne_zero V] at h0
rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ← vsub_add_vsub_cancel p₁ p₂ p₃,
add_comm, angle_add_eq_arctan_of_inner_eq_zero h h0]
/-- An angle in a non-degenerate right-angled triangle is positive. -/
theorem angle_pos_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2)
(h0 : p₁ ≠ p₂ ∨ p₃ = p₂) : 0 < ∠ p₂ p₃ p₁ := by
rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ←
inner_neg_left, neg_vsub_eq_vsub_rev] at h
rw [← @vsub_ne_zero V, eq_comm, ← @vsub_eq_zero_iff_eq V, or_comm] at h0
rw [angle, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm]
exact angle_add_pos_of_inner_eq_zero h h0
/-- An angle in a right-angled triangle is at most `π / 2`. -/
theorem angle_le_pi_div_two_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) :
∠ p₂ p₃ p₁ ≤ π / 2 := by
rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ←
inner_neg_left, neg_vsub_eq_vsub_rev] at h
rw [angle, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm]
exact angle_add_le_pi_div_two_of_inner_eq_zero h
/-- An angle in a non-degenerate right-angled triangle is less than `π / 2`. -/
theorem angle_lt_pi_div_two_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2)
(h0 : p₃ ≠ p₂) : ∠ p₂ p₃ p₁ < π / 2 := by
rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ←
inner_neg_left, neg_vsub_eq_vsub_rev] at h
rw [ne_comm, ← @vsub_ne_zero V] at h0
rw [angle, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm]
exact angle_add_lt_pi_div_two_of_inner_eq_zero h h0
/-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/
theorem cos_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) :
Real.cos (∠ p₂ p₃ p₁) = dist p₃ p₂ / dist p₁ p₃ := by
rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ←
inner_neg_left, neg_vsub_eq_vsub_rev] at h
| rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃,
add_comm, cos_angle_add_of_inner_eq_zero h]
/-- The sine of an angle in a right-angled triangle as a ratio of sides. -/
theorem sin_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2)
(h0 : p₁ ≠ p₂ ∨ p₃ ≠ p₂) : Real.sin (∠ p₂ p₃ p₁) = dist p₁ p₂ / dist p₁ p₃ := by
rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ←
| Mathlib/Geometry/Euclidean/Angle/Unoriented/RightAngle.lean | 388 | 394 |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel,
Rémy Degenne, David Loeffler
-/
import Mathlib.Analysis.SpecialFunctions.Pow.Real
/-!
# Power function on `ℝ≥0` and `ℝ≥0∞`
We construct the power functions `x ^ y` where
* `x` is a nonnegative real number and `y` is a real number;
* `x` is a number from `[0, +∞]` (a.k.a. `ℝ≥0∞`) and `y` is a real number.
We also prove basic properties of these functions.
-/
noncomputable section
open Real NNReal ENNReal ComplexConjugate Finset Function Set
namespace NNReal
variable {x : ℝ≥0} {w y z : ℝ}
/-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ` as the
restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`,
one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/
noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 :=
⟨(x : ℝ) ^ y, Real.rpow_nonneg x.2 y⟩
noncomputable instance : Pow ℝ≥0 ℝ :=
⟨rpow⟩
@[simp]
theorem rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y :=
rfl
@[simp, norm_cast]
theorem coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y :=
rfl
@[simp]
theorem rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 :=
NNReal.eq <| Real.rpow_zero _
@[simp]
theorem rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by
rw [← NNReal.coe_inj, coe_rpow, ← NNReal.coe_eq_zero]
exact Real.rpow_eq_zero_iff_of_nonneg x.2
lemma rpow_eq_zero (hy : y ≠ 0) : x ^ y = 0 ↔ x = 0 := by simp [hy]
@[simp]
theorem zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 :=
NNReal.eq <| Real.zero_rpow h
@[simp]
theorem rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x :=
NNReal.eq <| Real.rpow_one _
lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ (-y) = (x ^ y)⁻¹ :=
NNReal.eq <| Real.rpow_neg x.2 _
@[simp, norm_cast]
lemma rpow_natCast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
NNReal.eq <| by simpa only [coe_rpow, coe_pow] using Real.rpow_natCast x n
@[simp, norm_cast]
lemma rpow_intCast (x : ℝ≥0) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by
cases n <;> simp only [Int.ofNat_eq_coe, Int.cast_natCast, rpow_natCast, zpow_natCast,
Int.cast_negSucc, rpow_neg, zpow_negSucc]
@[simp]
theorem one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 :=
NNReal.eq <| Real.one_rpow _
theorem rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z :=
NNReal.eq <| Real.rpow_add ((NNReal.coe_pos.trans pos_iff_ne_zero).mpr hx) _ _
theorem rpow_add' (h : y + z ≠ 0) (x : ℝ≥0) : x ^ (y + z) = x ^ y * x ^ z :=
NNReal.eq <| Real.rpow_add' x.2 h
lemma rpow_add_intCast (hx : x ≠ 0) (y : ℝ) (n : ℤ) : x ^ (y + n) = x ^ y * x ^ n := by
ext; exact Real.rpow_add_intCast (mod_cast hx) _ _
lemma rpow_add_natCast (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y + n) = x ^ y * x ^ n := by
ext; exact Real.rpow_add_natCast (mod_cast hx) _ _
lemma rpow_sub_intCast (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y - n) = x ^ y / x ^ n := by
ext; exact Real.rpow_sub_intCast (mod_cast hx) _ _
lemma rpow_sub_natCast (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y - n) = x ^ y / x ^ n := by
ext; exact Real.rpow_sub_natCast (mod_cast hx) _ _
lemma rpow_add_intCast' {n : ℤ} (h : y + n ≠ 0) (x : ℝ≥0) : x ^ (y + n) = x ^ y * x ^ n := by
ext; exact Real.rpow_add_intCast' (mod_cast x.2) h
lemma rpow_add_natCast' {n : ℕ} (h : y + n ≠ 0) (x : ℝ≥0) : x ^ (y + n) = x ^ y * x ^ n := by
ext; exact Real.rpow_add_natCast' (mod_cast x.2) h
lemma rpow_sub_intCast' {n : ℤ} (h : y - n ≠ 0) (x : ℝ≥0) : x ^ (y - n) = x ^ y / x ^ n := by
ext; exact Real.rpow_sub_intCast' (mod_cast x.2) h
lemma rpow_sub_natCast' {n : ℕ} (h : y - n ≠ 0) (x : ℝ≥0) : x ^ (y - n) = x ^ y / x ^ n := by
ext; exact Real.rpow_sub_natCast' (mod_cast x.2) h
lemma rpow_add_one (hx : x ≠ 0) (y : ℝ) : x ^ (y + 1) = x ^ y * x := by
simpa using rpow_add_natCast hx y 1
lemma rpow_sub_one (hx : x ≠ 0) (y : ℝ) : x ^ (y - 1) = x ^ y / x := by
simpa using rpow_sub_natCast hx y 1
lemma rpow_add_one' (h : y + 1 ≠ 0) (x : ℝ≥0) : x ^ (y + 1) = x ^ y * x := by
rw [rpow_add' h, rpow_one]
lemma rpow_one_add' (h : 1 + y ≠ 0) (x : ℝ≥0) : x ^ (1 + y) = x * x ^ y := by
rw [rpow_add' h, rpow_one]
theorem rpow_add_of_nonneg (x : ℝ≥0) {y z : ℝ} (hy : 0 ≤ y) (hz : 0 ≤ z) :
x ^ (y + z) = x ^ y * x ^ z := by
ext; exact Real.rpow_add_of_nonneg x.2 hy hz
/-- Variant of `NNReal.rpow_add'` that avoids having to prove `y + z = w` twice. -/
lemma rpow_of_add_eq (x : ℝ≥0) (hw : w ≠ 0) (h : y + z = w) : x ^ w = x ^ y * x ^ z := by
rw [← h, rpow_add']; rwa [h]
theorem rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
NNReal.eq <| Real.rpow_mul x.2 y z
lemma rpow_natCast_mul (x : ℝ≥0) (n : ℕ) (z : ℝ) : x ^ (n * z) = (x ^ n) ^ z := by
rw [rpow_mul, rpow_natCast]
lemma rpow_mul_natCast (x : ℝ≥0) (y : ℝ) (n : ℕ) : x ^ (y * n) = (x ^ y) ^ n := by
rw [rpow_mul, rpow_natCast]
lemma rpow_intCast_mul (x : ℝ≥0) (n : ℤ) (z : ℝ) : x ^ (n * z) = (x ^ n) ^ z := by
rw [rpow_mul, rpow_intCast]
lemma rpow_mul_intCast (x : ℝ≥0) (y : ℝ) (n : ℤ) : x ^ (y * n) = (x ^ y) ^ n := by
rw [rpow_mul, rpow_intCast]
theorem rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x⁻¹ := by simp [rpow_neg]
theorem rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z :=
NNReal.eq <| Real.rpow_sub ((NNReal.coe_pos.trans pos_iff_ne_zero).mpr hx) y z
theorem rpow_sub' (h : y - z ≠ 0) (x : ℝ≥0) : x ^ (y - z) = x ^ y / x ^ z :=
NNReal.eq <| Real.rpow_sub' x.2 h
lemma rpow_sub_one' (h : y - 1 ≠ 0) (x : ℝ≥0) : x ^ (y - 1) = x ^ y / x := by
rw [rpow_sub' h, rpow_one]
lemma rpow_one_sub' (h : 1 - y ≠ 0) (x : ℝ≥0) : x ^ (1 - y) = x / x ^ y := by
rw [rpow_sub' h, rpow_one]
theorem rpow_inv_rpow_self {y : ℝ} (hy : y ≠ 0) (x : ℝ≥0) : (x ^ y) ^ (1 / y) = x := by
field_simp [← rpow_mul]
theorem rpow_self_rpow_inv {y : ℝ} (hy : y ≠ 0) (x : ℝ≥0) : (x ^ (1 / y)) ^ y = x := by
field_simp [← rpow_mul]
theorem inv_rpow (x : ℝ≥0) (y : ℝ) : x⁻¹ ^ y = (x ^ y)⁻¹ :=
NNReal.eq <| Real.inv_rpow x.2 y
theorem div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z :=
NNReal.eq <| Real.div_rpow x.2 y.2 z
theorem sqrt_eq_rpow (x : ℝ≥0) : sqrt x = x ^ (1 / (2 : ℝ)) := by
refine NNReal.eq ?_
push_cast
exact Real.sqrt_eq_rpow x.1
@[simp]
lemma rpow_ofNat (x : ℝ≥0) (n : ℕ) [n.AtLeastTwo] :
x ^ (ofNat(n) : ℝ) = x ^ (OfNat.ofNat n : ℕ) :=
rpow_natCast x n
theorem rpow_two (x : ℝ≥0) : x ^ (2 : ℝ) = x ^ 2 := rpow_ofNat x 2
theorem mul_rpow {x y : ℝ≥0} {z : ℝ} : (x * y) ^ z = x ^ z * y ^ z :=
NNReal.eq <| Real.mul_rpow x.2 y.2
/-- `rpow` as a `MonoidHom` -/
@[simps]
def rpowMonoidHom (r : ℝ) : ℝ≥0 →* ℝ≥0 where
toFun := (· ^ r)
map_one' := one_rpow _
map_mul' _x _y := mul_rpow
/-- `rpow` variant of `List.prod_map_pow` for `ℝ≥0` -/
theorem list_prod_map_rpow (l : List ℝ≥0) (r : ℝ) :
(l.map (· ^ r)).prod = l.prod ^ r :=
l.prod_hom (rpowMonoidHom r)
theorem list_prod_map_rpow' {ι} (l : List ι) (f : ι → ℝ≥0) (r : ℝ) :
(l.map (f · ^ r)).prod = (l.map f).prod ^ r := by
rw [← list_prod_map_rpow, List.map_map]; rfl
/-- `rpow` version of `Multiset.prod_map_pow` for `ℝ≥0`. -/
lemma multiset_prod_map_rpow {ι} (s : Multiset ι) (f : ι → ℝ≥0) (r : ℝ) :
(s.map (f · ^ r)).prod = (s.map f).prod ^ r :=
s.prod_hom' (rpowMonoidHom r) _
/-- `rpow` version of `Finset.prod_pow` for `ℝ≥0`. -/
lemma finset_prod_rpow {ι} (s : Finset ι) (f : ι → ℝ≥0) (r : ℝ) :
(∏ i ∈ s, f i ^ r) = (∏ i ∈ s, f i) ^ r :=
multiset_prod_map_rpow _ _ _
-- note: these don't really belong here, but they're much easier to prove in terms of the above
section Real
/-- `rpow` version of `List.prod_map_pow` for `Real`. -/
theorem _root_.Real.list_prod_map_rpow (l : List ℝ) (hl : ∀ x ∈ l, (0 : ℝ) ≤ x) (r : ℝ) :
(l.map (· ^ r)).prod = l.prod ^ r := by
lift l to List ℝ≥0 using hl
have := congr_arg ((↑) : ℝ≥0 → ℝ) (NNReal.list_prod_map_rpow l r)
push_cast at this
rw [List.map_map] at this ⊢
exact mod_cast this
theorem _root_.Real.list_prod_map_rpow' {ι} (l : List ι) (f : ι → ℝ)
(hl : ∀ i ∈ l, (0 : ℝ) ≤ f i) (r : ℝ) :
(l.map (f · ^ r)).prod = (l.map f).prod ^ r := by
rw [← Real.list_prod_map_rpow (l.map f) _ r, List.map_map]
· rfl
simpa using hl
/-- `rpow` version of `Multiset.prod_map_pow`. -/
theorem _root_.Real.multiset_prod_map_rpow {ι} (s : Multiset ι) (f : ι → ℝ)
(hs : ∀ i ∈ s, (0 : ℝ) ≤ f i) (r : ℝ) :
(s.map (f · ^ r)).prod = (s.map f).prod ^ r := by
induction' s using Quotient.inductionOn with l
simpa using Real.list_prod_map_rpow' l f hs r
/-- `rpow` version of `Finset.prod_pow`. -/
theorem _root_.Real.finset_prod_rpow
{ι} (s : Finset ι) (f : ι → ℝ) (hs : ∀ i ∈ s, 0 ≤ f i) (r : ℝ) :
(∏ i ∈ s, f i ^ r) = (∏ i ∈ s, f i) ^ r :=
Real.multiset_prod_map_rpow s.val f hs r
end Real
@[gcongr] theorem rpow_le_rpow {x y : ℝ≥0} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x ^ z ≤ y ^ z :=
Real.rpow_le_rpow x.2 h₁ h₂
@[gcongr] theorem rpow_lt_rpow {x y : ℝ≥0} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x ^ z < y ^ z :=
Real.rpow_lt_rpow x.2 h₁ h₂
theorem rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y :=
Real.rpow_lt_rpow_iff x.2 y.2 hz
theorem rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y :=
Real.rpow_le_rpow_iff x.2 y.2 hz
theorem le_rpow_inv_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ≤ y ^ z⁻¹ ↔ x ^ z ≤ y := by
rw [← rpow_le_rpow_iff hz, ← one_div, rpow_self_rpow_inv hz.ne']
theorem rpow_inv_le_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z⁻¹ ≤ y ↔ x ≤ y ^ z := by
rw [← rpow_le_rpow_iff hz, ← one_div, rpow_self_rpow_inv hz.ne']
theorem lt_rpow_inv_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x < y ^ z⁻¹ ↔ x ^z < y := by
simp only [← not_le, rpow_inv_le_iff hz]
theorem rpow_inv_lt_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z⁻¹ < y ↔ x < y ^ z := by
simp only [← not_le, le_rpow_inv_iff hz]
section
variable {y : ℝ≥0}
lemma rpow_lt_rpow_of_neg (hx : 0 < x) (hxy : x < y) (hz : z < 0) : y ^ z < x ^ z :=
Real.rpow_lt_rpow_of_neg hx hxy hz
lemma rpow_le_rpow_of_nonpos (hx : 0 < x) (hxy : x ≤ y) (hz : z ≤ 0) : y ^ z ≤ x ^ z :=
Real.rpow_le_rpow_of_nonpos hx hxy hz
lemma rpow_lt_rpow_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ^ z < y ^ z ↔ y < x :=
Real.rpow_lt_rpow_iff_of_neg hx hy hz
lemma rpow_le_rpow_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ^ z ≤ y ^ z ↔ y ≤ x :=
Real.rpow_le_rpow_iff_of_neg hx hy hz
lemma le_rpow_inv_iff_of_pos (hy : 0 ≤ y) (hz : 0 < z) (x : ℝ≥0) : x ≤ y ^ z⁻¹ ↔ x ^ z ≤ y :=
Real.le_rpow_inv_iff_of_pos x.2 hy hz
lemma rpow_inv_le_iff_of_pos (hy : 0 ≤ y) (hz : 0 < z) (x : ℝ≥0) : x ^ z⁻¹ ≤ y ↔ x ≤ y ^ z :=
Real.rpow_inv_le_iff_of_pos x.2 hy hz
lemma lt_rpow_inv_iff_of_pos (hy : 0 ≤ y) (hz : 0 < z) (x : ℝ≥0) : x < y ^ z⁻¹ ↔ x ^ z < y :=
Real.lt_rpow_inv_iff_of_pos x.2 hy hz
lemma rpow_inv_lt_iff_of_pos (hy : 0 ≤ y) (hz : 0 < z) (x : ℝ≥0) : x ^ z⁻¹ < y ↔ x < y ^ z :=
Real.rpow_inv_lt_iff_of_pos x.2 hy hz
lemma le_rpow_inv_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ≤ y ^ z⁻¹ ↔ y ≤ x ^ z :=
Real.le_rpow_inv_iff_of_neg hx hy hz
lemma lt_rpow_inv_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x < y ^ z⁻¹ ↔ y < x ^ z :=
Real.lt_rpow_inv_iff_of_neg hx hy hz
lemma rpow_inv_lt_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ^ z⁻¹ < y ↔ y ^ z < x :=
Real.rpow_inv_lt_iff_of_neg hx hy hz
lemma rpow_inv_le_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ^ z⁻¹ ≤ y ↔ y ^ z ≤ x :=
Real.rpow_inv_le_iff_of_neg hx hy hz
end
@[gcongr] theorem rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) :
x ^ y < x ^ z :=
Real.rpow_lt_rpow_of_exponent_lt hx hyz
@[gcongr] theorem rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) :
x ^ y ≤ x ^ z :=
Real.rpow_le_rpow_of_exponent_le hx hyz
theorem rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x ^ y < x ^ z :=
Real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz
theorem rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) :
x ^ y ≤ x ^ z :=
Real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz
theorem rpow_pos {p : ℝ} {x : ℝ≥0} (hx_pos : 0 < x) : 0 < x ^ p := by
have rpow_pos_of_nonneg : ∀ {p : ℝ}, 0 < p → 0 < x ^ p := by
intro p hp_pos
rw [← zero_rpow hp_pos.ne']
exact rpow_lt_rpow hx_pos hp_pos
rcases lt_trichotomy (0 : ℝ) p with (hp_pos | rfl | hp_neg)
· exact rpow_pos_of_nonneg hp_pos
· simp only [zero_lt_one, rpow_zero]
· rw [← neg_neg p, rpow_neg, inv_pos]
exact rpow_pos_of_nonneg (neg_pos.mpr hp_neg)
theorem rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx1 : x < 1) (hz : 0 < z) : x ^ z < 1 :=
Real.rpow_lt_one (coe_nonneg x) hx1 hz
theorem rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x ^ z ≤ 1 :=
Real.rpow_le_one x.2 hx2 hz
theorem rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x ^ z < 1 :=
Real.rpow_lt_one_of_one_lt_of_neg hx hz
theorem rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x ^ z ≤ 1 :=
Real.rpow_le_one_of_one_le_of_nonpos hx hz
theorem one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x ^ z :=
Real.one_lt_rpow hx hz
theorem one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x ^ z :=
Real.one_le_rpow h h₁
theorem one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1)
(hz : z < 0) : 1 < x ^ z :=
Real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz
theorem one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1)
(hz : z ≤ 0) : 1 ≤ x ^ z :=
Real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz
theorem rpow_le_self_of_le_one {x : ℝ≥0} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := by
rcases eq_bot_or_bot_lt x with (rfl | (h : 0 < x))
· have : z ≠ 0 := by linarith
simp [this]
nth_rw 2 [← NNReal.rpow_one x]
exact NNReal.rpow_le_rpow_of_exponent_ge h hx h_one_le
theorem rpow_left_injective {x : ℝ} (hx : x ≠ 0) : Function.Injective fun y : ℝ≥0 => y ^ x :=
fun y z hyz => by simpa only [rpow_inv_rpow_self hx] using congr_arg (fun y => y ^ (1 / x)) hyz
theorem rpow_eq_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : z ≠ 0) : x ^ z = y ^ z ↔ x = y :=
(rpow_left_injective hz).eq_iff
theorem rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : Function.Surjective fun y : ℝ≥0 => y ^ x :=
fun y => ⟨y ^ x⁻¹, by simp_rw [← rpow_mul, inv_mul_cancel₀ hx, rpow_one]⟩
theorem rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : Function.Bijective fun y : ℝ≥0 => y ^ x :=
⟨rpow_left_injective hx, rpow_left_surjective hx⟩
theorem eq_rpow_inv_iff {x y : ℝ≥0} {z : ℝ} (hz : z ≠ 0) : x = y ^ z⁻¹ ↔ x ^ z = y := by
rw [← rpow_eq_rpow_iff hz, ← one_div, rpow_self_rpow_inv hz]
theorem rpow_inv_eq_iff {x y : ℝ≥0} {z : ℝ} (hz : z ≠ 0) : x ^ z⁻¹ = y ↔ x = y ^ z := by
rw [← rpow_eq_rpow_iff hz, ← one_div, rpow_self_rpow_inv hz]
@[simp] lemma rpow_rpow_inv {y : ℝ} (hy : y ≠ 0) (x : ℝ≥0) : (x ^ y) ^ y⁻¹ = x := by
rw [← rpow_mul, mul_inv_cancel₀ hy, rpow_one]
@[simp] lemma rpow_inv_rpow {y : ℝ} (hy : y ≠ 0) (x : ℝ≥0) : (x ^ y⁻¹) ^ y = x := by
rw [← rpow_mul, inv_mul_cancel₀ hy, rpow_one]
theorem pow_rpow_inv_natCast (x : ℝ≥0) {n : ℕ} (hn : n ≠ 0) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by
rw [← NNReal.coe_inj, coe_rpow, NNReal.coe_pow]
exact Real.pow_rpow_inv_natCast x.2 hn
theorem rpow_inv_natCast_pow (x : ℝ≥0) {n : ℕ} (hn : n ≠ 0) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by
rw [← NNReal.coe_inj, NNReal.coe_pow, coe_rpow]
exact Real.rpow_inv_natCast_pow x.2 hn
theorem _root_.Real.toNNReal_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) :
Real.toNNReal (x ^ y) = Real.toNNReal x ^ y := by
nth_rw 1 [← Real.coe_toNNReal x hx]
rw [← NNReal.coe_rpow, Real.toNNReal_coe]
theorem strictMono_rpow_of_pos {z : ℝ} (h : 0 < z) : StrictMono fun x : ℝ≥0 => x ^ z :=
fun x y hxy => by simp only [NNReal.rpow_lt_rpow hxy h, coe_lt_coe]
theorem monotone_rpow_of_nonneg {z : ℝ} (h : 0 ≤ z) : Monotone fun x : ℝ≥0 => x ^ z :=
h.eq_or_lt.elim (fun h0 => h0 ▸ by simp only [rpow_zero, monotone_const]) fun h0 =>
(strictMono_rpow_of_pos h0).monotone
/-- Bundles `fun x : ℝ≥0 => x ^ y` into an order isomorphism when `y : ℝ` is positive,
where the inverse is `fun x : ℝ≥0 => x ^ (1 / y)`. -/
@[simps! apply]
def orderIsoRpow (y : ℝ) (hy : 0 < y) : ℝ≥0 ≃o ℝ≥0 :=
(strictMono_rpow_of_pos hy).orderIsoOfRightInverse (fun x => x ^ y) (fun x => x ^ (1 / y))
fun x => by
dsimp
rw [← rpow_mul, one_div_mul_cancel hy.ne.symm, rpow_one]
theorem orderIsoRpow_symm_eq (y : ℝ) (hy : 0 < y) :
(orderIsoRpow y hy).symm = orderIsoRpow (1 / y) (one_div_pos.2 hy) := by
simp only [orderIsoRpow, one_div_one_div]; rfl
theorem _root_.Real.nnnorm_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : ‖x ^ y‖₊ = ‖x‖₊ ^ y := by
ext; exact Real.norm_rpow_of_nonneg hx
end NNReal
namespace ENNReal
/-- The real power function `x^y` on extended nonnegative reals, defined for `x : ℝ≥0∞` and
`y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values
for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and
`⊤ ^ x = 1 / 0 ^ x`). -/
noncomputable def rpow : ℝ≥0∞ → ℝ → ℝ≥0∞
| some x, y => if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0)
| none, y => if 0 < y then ⊤ else if y = 0 then 1 else 0
noncomputable instance : Pow ℝ≥0∞ ℝ :=
⟨rpow⟩
@[simp]
theorem rpow_eq_pow (x : ℝ≥0∞) (y : ℝ) : rpow x y = x ^ y :=
rfl
@[simp]
theorem rpow_zero {x : ℝ≥0∞} : x ^ (0 : ℝ) = 1 := by
cases x <;>
· dsimp only [(· ^ ·), Pow.pow, rpow]
simp [lt_irrefl]
theorem top_rpow_def (y : ℝ) : (⊤ : ℝ≥0∞) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 :=
rfl
@[simp]
theorem top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ℝ≥0∞) ^ y = ⊤ := by simp [top_rpow_def, h]
@[simp]
theorem top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ℝ≥0∞) ^ y = 0 := by
simp [top_rpow_def, asymm h, ne_of_lt h]
@[simp]
theorem zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ℝ≥0∞) ^ y = 0 := by
rw [← ENNReal.coe_zero, ← ENNReal.some_eq_coe]
dsimp only [(· ^ ·), rpow, Pow.pow]
simp [h, asymm h, ne_of_gt h]
@[simp]
theorem zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ℝ≥0∞) ^ y = ⊤ := by
| rw [← ENNReal.coe_zero, ← ENNReal.some_eq_coe]
dsimp only [(· ^ ·), rpow, Pow.pow]
simp [h, ne_of_gt h]
theorem zero_rpow_def (y : ℝ) : (0 : ℝ≥0∞) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := by
rcases lt_trichotomy (0 : ℝ) y with (H | rfl | H)
| Mathlib/Analysis/SpecialFunctions/Pow/NNReal.lean | 473 | 478 |
/-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import Mathlib.Algebra.Algebra.Subalgebra.Tower
import Mathlib.Data.Finite.Sum
import Mathlib.Data.Matrix.Block
import Mathlib.Data.Matrix.Notation
import Mathlib.LinearAlgebra.Basis.Basic
import Mathlib.LinearAlgebra.Basis.Fin
import Mathlib.LinearAlgebra.Basis.Prod
import Mathlib.LinearAlgebra.Basis.SMul
import Mathlib.LinearAlgebra.Matrix.StdBasis
import Mathlib.RingTheory.AlgebraTower
import Mathlib.RingTheory.Ideal.Span
/-!
# Linear maps and matrices
This file defines the maps to send matrices to a linear map,
and to send linear maps between modules with a finite bases
to matrices. This defines a linear equivalence between linear maps
between finite-dimensional vector spaces and matrices indexed by
the respective bases.
## Main definitions
In the list below, and in all this file, `R` is a commutative ring (semiring
is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite
types used for indexing.
* `LinearMap.toMatrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`,
the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `Matrix κ ι R`
* `Matrix.toLin`: the inverse of `LinearMap.toMatrix`
* `LinearMap.toMatrix'`: the `R`-linear equivalence from `(m → R) →ₗ[R] (n → R)`
to `Matrix m n R` (with the standard basis on `m → R` and `n → R`)
* `Matrix.toLin'`: the inverse of `LinearMap.toMatrix'`
* `algEquivMatrix`: given a basis indexed by `n`, the `R`-algebra equivalence between
`R`-endomorphisms of `M` and `Matrix n n R`
## Issues
This file was originally written without attention to non-commutative rings,
and so mostly only works in the commutative setting. This should be fixed.
In particular, `Matrix.mulVec` gives us a linear equivalence
`Matrix m n R ≃ₗ[R] (n → R) →ₗ[Rᵐᵒᵖ] (m → R)`
while `Matrix.vecMul` gives us a linear equivalence
`Matrix m n R ≃ₗ[Rᵐᵒᵖ] (m → R) →ₗ[R] (n → R)`.
At present, the first equivalence is developed in detail but only for commutative rings
(and we omit the distinction between `Rᵐᵒᵖ` and `R`),
while the second equivalence is developed only in brief, but for not-necessarily-commutative rings.
Naming is slightly inconsistent between the two developments.
In the original (commutative) development `linear` is abbreviated to `lin`,
although this is not consistent with the rest of mathlib.
In the new (non-commutative) development `linear` is not abbreviated, and declarations use `_right`
to indicate they use the right action of matrices on vectors (via `Matrix.vecMul`).
When the two developments are made uniform, the names should be made uniform, too,
by choosing between `linear` and `lin` consistently,
and (presumably) adding `_left` where necessary.
## Tags
linear_map, matrix, linear_equiv, diagonal, det, trace
-/
noncomputable section
open LinearMap Matrix Set Submodule
section ToMatrixRight
variable {R : Type*} [Semiring R]
variable {l m n : Type*}
/-- `Matrix.vecMul M` is a linear map. -/
def Matrix.vecMulLinear [Fintype m] (M : Matrix m n R) : (m → R) →ₗ[R] n → R where
toFun x := x ᵥ* M
map_add' _ _ := funext fun _ ↦ add_dotProduct _ _ _
map_smul' _ _ := funext fun _ ↦ smul_dotProduct _ _ _
@[simp] theorem Matrix.vecMulLinear_apply [Fintype m] (M : Matrix m n R) (x : m → R) :
M.vecMulLinear x = x ᵥ* M := rfl
theorem Matrix.coe_vecMulLinear [Fintype m] (M : Matrix m n R) :
(M.vecMulLinear : _ → _) = M.vecMul := rfl
variable [Fintype m]
theorem range_vecMulLinear (M : Matrix m n R) :
LinearMap.range M.vecMulLinear = span R (range M.row) := by
letI := Classical.decEq m
simp_rw [range_eq_map, ← iSup_range_single, Submodule.map_iSup, range_eq_map, ←
Ideal.span_singleton_one, Ideal.span, Submodule.map_span, image_image, image_singleton,
Matrix.vecMulLinear_apply, iSup_span, range_eq_iUnion, iUnion_singleton_eq_range,
LinearMap.single, LinearMap.coe_mk, AddHom.coe_mk, row_def]
unfold vecMul
simp_rw [single_dotProduct, one_mul]
theorem Matrix.vecMul_injective_iff {R : Type*} [Ring R] {M : Matrix m n R} :
Function.Injective M.vecMul ↔ LinearIndependent R M.row := by
rw [← coe_vecMulLinear]
simp only [← LinearMap.ker_eq_bot, Fintype.linearIndependent_iff, Submodule.eq_bot_iff,
LinearMap.mem_ker, vecMulLinear_apply, row_def]
refine ⟨fun h c h0 ↦ congr_fun <| h c ?_, fun h c h0 ↦ funext <| h c ?_⟩
· rw [← h0]
ext i
simp [vecMul, dotProduct]
· rw [← h0]
ext j
simp [vecMul, dotProduct]
lemma Matrix.linearIndependent_rows_of_isUnit {R : Type*} [Ring R] {A : Matrix m m R}
[DecidableEq m] (ha : IsUnit A) : LinearIndependent R A.row := by
rw [← Matrix.vecMul_injective_iff]
exact Matrix.vecMul_injective_of_isUnit ha
section
variable [DecidableEq m]
/-- Linear maps `(m → R) →ₗ[R] (n → R)` are linearly equivalent over `Rᵐᵒᵖ` to `Matrix m n R`,
by having matrices act by right multiplication.
-/
def LinearMap.toMatrixRight' : ((m → R) →ₗ[R] n → R) ≃ₗ[Rᵐᵒᵖ] Matrix m n R where
toFun f i j := f (single R (fun _ ↦ R) i 1) j
invFun := Matrix.vecMulLinear
right_inv M := by
ext i j
simp
left_inv f := by
apply (Pi.basisFun R m).ext
intro j; ext i
simp
map_add' f g := by
ext i j
simp only [Pi.add_apply, LinearMap.add_apply, Matrix.add_apply]
map_smul' c f := by
ext i j
simp only [Pi.smul_apply, LinearMap.smul_apply, RingHom.id_apply, Matrix.smul_apply]
/-- A `Matrix m n R` is linearly equivalent over `Rᵐᵒᵖ` to a linear map `(m → R) →ₗ[R] (n → R)`,
by having matrices act by right multiplication. -/
abbrev Matrix.toLinearMapRight' [DecidableEq m] : Matrix m n R ≃ₗ[Rᵐᵒᵖ] (m → R) →ₗ[R] n → R :=
LinearEquiv.symm LinearMap.toMatrixRight'
@[simp]
theorem Matrix.toLinearMapRight'_apply (M : Matrix m n R) (v : m → R) :
(Matrix.toLinearMapRight') M v = v ᵥ* M := rfl
@[simp]
theorem Matrix.toLinearMapRight'_mul [Fintype l] [DecidableEq l] (M : Matrix l m R)
(N : Matrix m n R) :
Matrix.toLinearMapRight' (M * N) =
(Matrix.toLinearMapRight' N).comp (Matrix.toLinearMapRight' M) :=
LinearMap.ext fun _x ↦ (vecMul_vecMul _ M N).symm
theorem Matrix.toLinearMapRight'_mul_apply [Fintype l] [DecidableEq l] (M : Matrix l m R)
(N : Matrix m n R) (x) :
Matrix.toLinearMapRight' (M * N) x =
Matrix.toLinearMapRight' N (Matrix.toLinearMapRight' M x) :=
(vecMul_vecMul _ M N).symm
@[simp]
theorem Matrix.toLinearMapRight'_one :
Matrix.toLinearMapRight' (1 : Matrix m m R) = LinearMap.id := by
ext
simp [Module.End.one_apply]
/-- If `M` and `M'` are each other's inverse matrices, they provide an equivalence between `n → A`
and `m → A` corresponding to `M.vecMul` and `M'.vecMul`. -/
@[simps]
def Matrix.toLinearEquivRight'OfInv [Fintype n] [DecidableEq n] {M : Matrix m n R}
{M' : Matrix n m R} (hMM' : M * M' = 1) (hM'M : M' * M = 1) : (n → R) ≃ₗ[R] m → R :=
{ LinearMap.toMatrixRight'.symm M' with
toFun := Matrix.toLinearMapRight' M'
invFun := Matrix.toLinearMapRight' M
left_inv := fun x ↦ by
rw [← Matrix.toLinearMapRight'_mul_apply, hM'M, Matrix.toLinearMapRight'_one, id_apply]
right_inv := fun x ↦ by
rw [← Matrix.toLinearMapRight'_mul_apply, hMM', Matrix.toLinearMapRight'_one, id_apply] }
end
end ToMatrixRight
/-!
From this point on, we only work with commutative rings,
and fail to distinguish between `Rᵐᵒᵖ` and `R`.
This should eventually be remedied.
-/
section mulVec
variable {R : Type*} [CommSemiring R]
variable {k l m n : Type*}
/-- `Matrix.mulVec M` is a linear map. -/
def Matrix.mulVecLin [Fintype n] (M : Matrix m n R) : (n → R) →ₗ[R] m → R where
toFun := M.mulVec
map_add' _ _ := funext fun _ ↦ dotProduct_add _ _ _
map_smul' _ _ := funext fun _ ↦ dotProduct_smul _ _ _
theorem Matrix.coe_mulVecLin [Fintype n] (M : Matrix m n R) :
(M.mulVecLin : _ → _) = M.mulVec := rfl
@[simp]
theorem Matrix.mulVecLin_apply [Fintype n] (M : Matrix m n R) (v : n → R) :
M.mulVecLin v = M *ᵥ v :=
rfl
@[simp]
theorem Matrix.mulVecLin_zero [Fintype n] : Matrix.mulVecLin (0 : Matrix m n R) = 0 :=
LinearMap.ext zero_mulVec
@[simp]
theorem Matrix.mulVecLin_add [Fintype n] (M N : Matrix m n R) :
(M + N).mulVecLin = M.mulVecLin + N.mulVecLin :=
LinearMap.ext fun _ ↦ add_mulVec _ _ _
@[simp] theorem Matrix.mulVecLin_transpose [Fintype m] (M : Matrix m n R) :
Mᵀ.mulVecLin = M.vecMulLinear := by
ext; simp [mulVec_transpose]
@[simp] theorem Matrix.vecMulLinear_transpose [Fintype n] (M : Matrix m n R) :
Mᵀ.vecMulLinear = M.mulVecLin := by
ext; simp [vecMul_transpose]
theorem Matrix.mulVecLin_submatrix [Fintype n] [Fintype l] (f₁ : m → k) (e₂ : n ≃ l)
(M : Matrix k l R) :
(M.submatrix f₁ e₂).mulVecLin = funLeft R R f₁ ∘ₗ M.mulVecLin ∘ₗ funLeft _ _ e₂.symm :=
LinearMap.ext fun _ ↦ submatrix_mulVec_equiv _ _ _ _
/-- A variant of `Matrix.mulVecLin_submatrix` that keeps around `LinearEquiv`s. -/
theorem Matrix.mulVecLin_reindex [Fintype n] [Fintype l] (e₁ : k ≃ m) (e₂ : l ≃ n)
(M : Matrix k l R) :
(reindex e₁ e₂ M).mulVecLin =
↑(LinearEquiv.funCongrLeft R R e₁.symm) ∘ₗ
M.mulVecLin ∘ₗ ↑(LinearEquiv.funCongrLeft R R e₂) :=
Matrix.mulVecLin_submatrix _ _ _
variable [Fintype n]
@[simp]
theorem Matrix.mulVecLin_one [DecidableEq n] :
Matrix.mulVecLin (1 : Matrix n n R) = LinearMap.id := by
ext; simp [Matrix.one_apply, Pi.single_apply, eq_comm]
@[simp]
theorem Matrix.mulVecLin_mul [Fintype m] (M : Matrix l m R) (N : Matrix m n R) :
Matrix.mulVecLin (M * N) = (Matrix.mulVecLin M).comp (Matrix.mulVecLin N) :=
LinearMap.ext fun _ ↦ (mulVec_mulVec _ _ _).symm
theorem Matrix.ker_mulVecLin_eq_bot_iff {M : Matrix m n R} :
(LinearMap.ker M.mulVecLin) = ⊥ ↔ ∀ v, M *ᵥ v = 0 → v = 0 := by
simp only [Submodule.eq_bot_iff, LinearMap.mem_ker, Matrix.mulVecLin_apply]
theorem Matrix.range_mulVecLin (M : Matrix m n R) :
LinearMap.range M.mulVecLin = span R (range M.col) := by
rw [← vecMulLinear_transpose, range_vecMulLinear, row_transpose]
theorem Matrix.mulVec_injective_iff {R : Type*} [CommRing R] {M : Matrix m n R} :
Function.Injective M.mulVec ↔ LinearIndependent R M.col := by
change Function.Injective (fun x ↦ _) ↔ _
simp_rw [← M.vecMul_transpose, vecMul_injective_iff, row_transpose]
lemma Matrix.linearIndependent_cols_of_isUnit {R : Type*} [CommRing R] [Fintype m]
{A : Matrix m m R} [DecidableEq m] (ha : IsUnit A) :
LinearIndependent R A.col := by
rw [← Matrix.mulVec_injective_iff]
exact Matrix.mulVec_injective_of_isUnit ha
end mulVec
section ToMatrix'
variable {R : Type*} [CommSemiring R]
variable {k l m n : Type*} [DecidableEq n] [Fintype n]
/-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `Matrix m n R`. -/
def LinearMap.toMatrix' : ((n → R) →ₗ[R] m → R) ≃ₗ[R] Matrix m n R where
toFun f := of fun i j ↦ f (Pi.single j 1) i
invFun := Matrix.mulVecLin
right_inv M := by
ext i j
simp only [Matrix.mulVec_single_one, Matrix.mulVecLin_apply, of_apply, transpose_apply]
left_inv f := by
apply (Pi.basisFun R n).ext
intro j; ext i
simp only [Pi.basisFun_apply, Matrix.mulVec_single_one,
Matrix.mulVecLin_apply, of_apply, transpose_apply]
map_add' f g := by
ext i j
simp only [Pi.add_apply, LinearMap.add_apply, of_apply, Matrix.add_apply]
map_smul' c f := by
ext i j
simp only [Pi.smul_apply, LinearMap.smul_apply, RingHom.id_apply, of_apply, Matrix.smul_apply]
/-- A `Matrix m n R` is linearly equivalent to a linear map `(n → R) →ₗ[R] (m → R)`.
Note that the forward-direction does not require `DecidableEq` and is `Matrix.vecMulLin`. -/
def Matrix.toLin' : Matrix m n R ≃ₗ[R] (n → R) →ₗ[R] m → R :=
LinearMap.toMatrix'.symm
theorem Matrix.toLin'_apply' (M : Matrix m n R) : Matrix.toLin' M = M.mulVecLin :=
rfl
@[simp]
theorem LinearMap.toMatrix'_symm :
(LinearMap.toMatrix'.symm : Matrix m n R ≃ₗ[R] _) = Matrix.toLin' :=
rfl
@[simp]
theorem Matrix.toLin'_symm :
(Matrix.toLin'.symm : ((n → R) →ₗ[R] m → R) ≃ₗ[R] _) = LinearMap.toMatrix' :=
rfl
@[simp]
theorem LinearMap.toMatrix'_toLin' (M : Matrix m n R) : LinearMap.toMatrix' (Matrix.toLin' M) = M :=
LinearMap.toMatrix'.apply_symm_apply M
@[simp]
theorem Matrix.toLin'_toMatrix' (f : (n → R) →ₗ[R] m → R) :
Matrix.toLin' (LinearMap.toMatrix' f) = f :=
Matrix.toLin'.apply_symm_apply f
@[simp]
theorem LinearMap.toMatrix'_apply (f : (n → R) →ₗ[R] m → R) (i j) :
LinearMap.toMatrix' f i j = f (fun j' ↦ if j' = j then 1 else 0) i := by
simp only [LinearMap.toMatrix', LinearEquiv.coe_mk, of_apply]
congr! with i
split_ifs with h
· rw [h, Pi.single_eq_same]
apply Pi.single_eq_of_ne h
@[simp]
theorem Matrix.toLin'_apply (M : Matrix m n R) (v : n → R) : Matrix.toLin' M v = M *ᵥ v :=
rfl
@[simp]
theorem Matrix.toLin'_one : Matrix.toLin' (1 : Matrix n n R) = LinearMap.id :=
Matrix.mulVecLin_one
@[simp]
theorem LinearMap.toMatrix'_id : LinearMap.toMatrix' (LinearMap.id : (n → R) →ₗ[R] n → R) = 1 := by
ext
rw [Matrix.one_apply, LinearMap.toMatrix'_apply, id_apply]
@[simp]
theorem LinearMap.toMatrix'_one : LinearMap.toMatrix' (1 : (n → R) →ₗ[R] n → R) = 1 :=
LinearMap.toMatrix'_id
@[simp]
theorem Matrix.toLin'_mul [Fintype m] [DecidableEq m] (M : Matrix l m R) (N : Matrix m n R) :
Matrix.toLin' (M * N) = (Matrix.toLin' M).comp (Matrix.toLin' N) :=
Matrix.mulVecLin_mul _ _
@[simp]
theorem Matrix.toLin'_submatrix [Fintype l] [DecidableEq l] (f₁ : m → k) (e₂ : n ≃ l)
(M : Matrix k l R) :
Matrix.toLin' (M.submatrix f₁ e₂) =
funLeft R R f₁ ∘ₗ (Matrix.toLin' M) ∘ₗ funLeft _ _ e₂.symm :=
Matrix.mulVecLin_submatrix _ _ _
/-- A variant of `Matrix.toLin'_submatrix` that keeps around `LinearEquiv`s. -/
theorem Matrix.toLin'_reindex [Fintype l] [DecidableEq l] (e₁ : k ≃ m) (e₂ : l ≃ n)
(M : Matrix k l R) :
Matrix.toLin' (reindex e₁ e₂ M) =
↑(LinearEquiv.funCongrLeft R R e₁.symm) ∘ₗ (Matrix.toLin' M) ∘ₗ
↑(LinearEquiv.funCongrLeft R R e₂) :=
Matrix.mulVecLin_reindex _ _ _
/-- Shortcut lemma for `Matrix.toLin'_mul` and `LinearMap.comp_apply` -/
theorem Matrix.toLin'_mul_apply [Fintype m] [DecidableEq m] (M : Matrix l m R) (N : Matrix m n R)
(x) : Matrix.toLin' (M * N) x = Matrix.toLin' M (Matrix.toLin' N x) := by
rw [Matrix.toLin'_mul, LinearMap.comp_apply]
theorem LinearMap.toMatrix'_comp [Fintype l] [DecidableEq l] (f : (n → R) →ₗ[R] m → R)
(g : (l → R) →ₗ[R] n → R) :
LinearMap.toMatrix' (f.comp g) = LinearMap.toMatrix' f * LinearMap.toMatrix' g := by
suffices f.comp g = Matrix.toLin' (LinearMap.toMatrix' f * LinearMap.toMatrix' g) by
rw [this, LinearMap.toMatrix'_toLin']
rw [Matrix.toLin'_mul, Matrix.toLin'_toMatrix', Matrix.toLin'_toMatrix']
theorem LinearMap.toMatrix'_mul [Fintype m] [DecidableEq m] (f g : (m → R) →ₗ[R] m → R) :
LinearMap.toMatrix' (f * g) = LinearMap.toMatrix' f * LinearMap.toMatrix' g :=
LinearMap.toMatrix'_comp f g
@[simp]
theorem LinearMap.toMatrix'_algebraMap (x : R) :
LinearMap.toMatrix' (algebraMap R (Module.End R (n → R)) x) = scalar n x := by
simp [Module.algebraMap_end_eq_smul_id, smul_eq_diagonal_mul]
theorem Matrix.ker_toLin'_eq_bot_iff {M : Matrix n n R} :
LinearMap.ker (Matrix.toLin' M) = ⊥ ↔ ∀ v, M *ᵥ v = 0 → v = 0 :=
Matrix.ker_mulVecLin_eq_bot_iff
theorem Matrix.range_toLin' (M : Matrix m n R) :
LinearMap.range (Matrix.toLin' M) = span R (range M.col) :=
Matrix.range_mulVecLin _
/-- If `M` and `M'` are each other's inverse matrices, they provide an equivalence between `m → A`
and `n → A` corresponding to `M.mulVec` and `M'.mulVec`. -/
@[simps]
def Matrix.toLin'OfInv [Fintype m] [DecidableEq m] {M : Matrix m n R} {M' : Matrix n m R}
(hMM' : M * M' = 1) (hM'M : M' * M = 1) : (m → R) ≃ₗ[R] n → R :=
{ Matrix.toLin' M' with
toFun := Matrix.toLin' M'
invFun := Matrix.toLin' M
left_inv := fun x ↦ by rw [← Matrix.toLin'_mul_apply, hMM', Matrix.toLin'_one, id_apply]
right_inv := fun x ↦ by
rw [← Matrix.toLin'_mul_apply, hM'M, Matrix.toLin'_one, id_apply] }
/-- Linear maps `(n → R) →ₗ[R] (n → R)` are algebra equivalent to `Matrix n n R`. -/
def LinearMap.toMatrixAlgEquiv' : ((n → R) →ₗ[R] n → R) ≃ₐ[R] Matrix n n R :=
AlgEquiv.ofLinearEquiv LinearMap.toMatrix' LinearMap.toMatrix'_one LinearMap.toMatrix'_mul
/-- A `Matrix n n R` is algebra equivalent to a linear map `(n → R) →ₗ[R] (n → R)`. -/
def Matrix.toLinAlgEquiv' : Matrix n n R ≃ₐ[R] (n → R) →ₗ[R] n → R :=
LinearMap.toMatrixAlgEquiv'.symm
@[simp]
theorem LinearMap.toMatrixAlgEquiv'_symm :
(LinearMap.toMatrixAlgEquiv'.symm : Matrix n n R ≃ₐ[R] _) = Matrix.toLinAlgEquiv' :=
rfl
@[simp]
theorem Matrix.toLinAlgEquiv'_symm :
(Matrix.toLinAlgEquiv'.symm : ((n → R) →ₗ[R] n → R) ≃ₐ[R] _) = LinearMap.toMatrixAlgEquiv' :=
rfl
@[simp]
theorem LinearMap.toMatrixAlgEquiv'_toLinAlgEquiv' (M : Matrix n n R) :
LinearMap.toMatrixAlgEquiv' (Matrix.toLinAlgEquiv' M) = M :=
LinearMap.toMatrixAlgEquiv'.apply_symm_apply M
@[simp]
theorem Matrix.toLinAlgEquiv'_toMatrixAlgEquiv' (f : (n → R) →ₗ[R] n → R) :
Matrix.toLinAlgEquiv' (LinearMap.toMatrixAlgEquiv' f) = f :=
Matrix.toLinAlgEquiv'.apply_symm_apply f
@[simp]
theorem LinearMap.toMatrixAlgEquiv'_apply (f : (n → R) →ₗ[R] n → R) (i j) :
LinearMap.toMatrixAlgEquiv' f i j = f (fun j' ↦ if j' = j then 1 else 0) i := by
simp [LinearMap.toMatrixAlgEquiv']
@[simp]
theorem Matrix.toLinAlgEquiv'_apply (M : Matrix n n R) (v : n → R) :
Matrix.toLinAlgEquiv' M v = M *ᵥ v :=
rfl
theorem Matrix.toLinAlgEquiv'_one : Matrix.toLinAlgEquiv' (1 : Matrix n n R) = LinearMap.id :=
Matrix.toLin'_one
@[simp]
theorem LinearMap.toMatrixAlgEquiv'_id :
LinearMap.toMatrixAlgEquiv' (LinearMap.id : (n → R) →ₗ[R] n → R) = 1 :=
LinearMap.toMatrix'_id
theorem LinearMap.toMatrixAlgEquiv'_comp (f g : (n → R) →ₗ[R] n → R) :
LinearMap.toMatrixAlgEquiv' (f.comp g) =
LinearMap.toMatrixAlgEquiv' f * LinearMap.toMatrixAlgEquiv' g :=
LinearMap.toMatrix'_comp _ _
theorem LinearMap.toMatrixAlgEquiv'_mul (f g : (n → R) →ₗ[R] n → R) :
LinearMap.toMatrixAlgEquiv' (f * g) =
LinearMap.toMatrixAlgEquiv' f * LinearMap.toMatrixAlgEquiv' g :=
LinearMap.toMatrixAlgEquiv'_comp f g
end ToMatrix'
section ToMatrix
section Finite
variable {R : Type*} [CommSemiring R]
variable {l m n : Type*} [Fintype n] [Finite m] [DecidableEq n]
variable {M₁ M₂ : Type*} [AddCommMonoid M₁] [AddCommMonoid M₂] [Module R M₁] [Module R M₂]
variable (v₁ : Basis n R M₁) (v₂ : Basis m R M₂)
/-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear
equivalence between linear maps `M₁ →ₗ M₂` and matrices over `R` indexed by the bases. -/
def LinearMap.toMatrix : (M₁ →ₗ[R] M₂) ≃ₗ[R] Matrix m n R :=
LinearEquiv.trans (LinearEquiv.arrowCongr v₁.equivFun v₂.equivFun) LinearMap.toMatrix'
/-- `LinearMap.toMatrix'` is a particular case of `LinearMap.toMatrix`, for the standard basis
`Pi.basisFun R n`. -/
theorem LinearMap.toMatrix_eq_toMatrix' :
LinearMap.toMatrix (Pi.basisFun R n) (Pi.basisFun R n) = LinearMap.toMatrix' :=
rfl
/-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear
equivalence between matrices over `R` indexed by the bases and linear maps `M₁ →ₗ M₂`. -/
def Matrix.toLin : Matrix m n R ≃ₗ[R] M₁ →ₗ[R] M₂ :=
(LinearMap.toMatrix v₁ v₂).symm
/-- `Matrix.toLin'` is a particular case of `Matrix.toLin`, for the standard basis
`Pi.basisFun R n`. -/
theorem Matrix.toLin_eq_toLin' : Matrix.toLin (Pi.basisFun R n) (Pi.basisFun R m) = Matrix.toLin' :=
rfl
@[simp]
theorem LinearMap.toMatrix_symm : (LinearMap.toMatrix v₁ v₂).symm = Matrix.toLin v₁ v₂ :=
rfl
@[simp]
theorem Matrix.toLin_symm : (Matrix.toLin v₁ v₂).symm = LinearMap.toMatrix v₁ v₂ :=
rfl
@[simp]
theorem Matrix.toLin_toMatrix (f : M₁ →ₗ[R] M₂) :
Matrix.toLin v₁ v₂ (LinearMap.toMatrix v₁ v₂ f) = f := by
rw [← Matrix.toLin_symm, LinearEquiv.apply_symm_apply]
@[simp]
theorem LinearMap.toMatrix_toLin (M : Matrix m n R) :
LinearMap.toMatrix v₁ v₂ (Matrix.toLin v₁ v₂ M) = M := by
rw [← Matrix.toLin_symm, LinearEquiv.symm_apply_apply]
theorem LinearMap.toMatrix_apply (f : M₁ →ₗ[R] M₂) (i : m) (j : n) :
LinearMap.toMatrix v₁ v₂ f i j = v₂.repr (f (v₁ j)) i := by
rw [LinearMap.toMatrix, LinearEquiv.trans_apply, LinearMap.toMatrix'_apply,
LinearEquiv.arrowCongr_apply, Basis.equivFun_symm_apply, Finset.sum_eq_single j, if_pos rfl,
one_smul, Basis.equivFun_apply]
· intro j' _ hj'
rw [if_neg hj', zero_smul]
· intro hj
have := Finset.mem_univ j
contradiction
theorem LinearMap.toMatrix_transpose_apply (f : M₁ →ₗ[R] M₂) (j : n) :
(LinearMap.toMatrix v₁ v₂ f)ᵀ j = v₂.repr (f (v₁ j)) :=
funext fun i ↦ f.toMatrix_apply _ _ i j
theorem LinearMap.toMatrix_apply' (f : M₁ →ₗ[R] M₂) (i : m) (j : n) :
LinearMap.toMatrix v₁ v₂ f i j = v₂.repr (f (v₁ j)) i :=
LinearMap.toMatrix_apply v₁ v₂ f i j
theorem LinearMap.toMatrix_transpose_apply' (f : M₁ →ₗ[R] M₂) (j : n) :
(LinearMap.toMatrix v₁ v₂ f)ᵀ j = v₂.repr (f (v₁ j)) :=
LinearMap.toMatrix_transpose_apply v₁ v₂ f j
/-- This will be a special case of `LinearMap.toMatrix_id_eq_basis_toMatrix`. -/
theorem LinearMap.toMatrix_id : LinearMap.toMatrix v₁ v₁ id = 1 := by
ext i j
simp [LinearMap.toMatrix_apply, Matrix.one_apply, Finsupp.single_apply, eq_comm]
@[simp]
theorem LinearMap.toMatrix_one : LinearMap.toMatrix v₁ v₁ 1 = 1 :=
LinearMap.toMatrix_id v₁
@[simp]
lemma LinearMap.toMatrix_singleton {ι : Type*} [Unique ι] (f : R →ₗ[R] R) (i j : ι) :
f.toMatrix (.singleton ι R) (.singleton ι R) i j = f 1 := by
simp [toMatrix, Subsingleton.elim j default]
@[simp]
theorem Matrix.toLin_one : Matrix.toLin v₁ v₁ 1 = LinearMap.id := by
rw [← LinearMap.toMatrix_id v₁, Matrix.toLin_toMatrix]
theorem LinearMap.toMatrix_reindexRange [DecidableEq M₁] (f : M₁ →ₗ[R] M₂) (k : m) (i : n) :
LinearMap.toMatrix v₁.reindexRange v₂.reindexRange f ⟨v₂ k, Set.mem_range_self k⟩
⟨v₁ i, Set.mem_range_self i⟩ =
LinearMap.toMatrix v₁ v₂ f k i := by
simp_rw [LinearMap.toMatrix_apply, Basis.reindexRange_self, Basis.reindexRange_repr]
@[simp]
theorem LinearMap.toMatrix_algebraMap (x : R) :
LinearMap.toMatrix v₁ v₁ (algebraMap R (Module.End R M₁) x) = scalar n x := by
simp [Module.algebraMap_end_eq_smul_id, LinearMap.toMatrix_id, smul_eq_diagonal_mul]
theorem LinearMap.toMatrix_mulVec_repr (f : M₁ →ₗ[R] M₂) (x : M₁) :
LinearMap.toMatrix v₁ v₂ f *ᵥ v₁.repr x = v₂.repr (f x) := by
ext i
rw [← Matrix.toLin'_apply, LinearMap.toMatrix, LinearEquiv.trans_apply, Matrix.toLin'_toMatrix',
LinearEquiv.arrowCongr_apply, v₂.equivFun_apply]
congr
exact v₁.equivFun.symm_apply_apply x
@[simp]
theorem LinearMap.toMatrix_basis_equiv [Fintype l] [DecidableEq l] (b : Basis l R M₁)
(b' : Basis l R M₂) :
LinearMap.toMatrix b' b (b'.equiv b (Equiv.refl l) : M₂ →ₗ[R] M₁) = 1 := by
ext i j
simp [LinearMap.toMatrix_apply, Matrix.one_apply, Finsupp.single_apply, eq_comm]
theorem LinearMap.toMatrix_smulBasis_left {G} [Group G] [DistribMulAction G M₁]
[SMulCommClass G R M₁] (g : G) (f : M₁ →ₗ[R] M₂) :
LinearMap.toMatrix (g • v₁) v₂ f =
LinearMap.toMatrix v₁ v₂ (f ∘ₗ DistribMulAction.toLinearMap _ _ g) := by
ext
rw [LinearMap.toMatrix_apply, LinearMap.toMatrix_apply]
dsimp
theorem LinearMap.toMatrix_smulBasis_right {G} [Group G] [DistribMulAction G M₂]
[SMulCommClass G R M₂] (g : G) (f : M₁ →ₗ[R] M₂) :
LinearMap.toMatrix v₁ (g • v₂) f =
LinearMap.toMatrix v₁ v₂ (DistribMulAction.toLinearMap _ _ g⁻¹ ∘ₗ f) := by
ext
rw [LinearMap.toMatrix_apply, LinearMap.toMatrix_apply]
dsimp
end Finite
variable {R : Type*} [CommSemiring R]
variable {l m n : Type*} [Fintype n] [Fintype m] [DecidableEq n]
variable {M₁ M₂ : Type*} [AddCommMonoid M₁] [AddCommMonoid M₂] [Module R M₁] [Module R M₂]
variable (v₁ : Basis n R M₁) (v₂ : Basis m R M₂)
theorem Matrix.toLin_apply (M : Matrix m n R) (v : M₁) :
Matrix.toLin v₁ v₂ M v = ∑ j, (M *ᵥ v₁.repr v) j • v₂ j :=
show v₂.equivFun.symm (Matrix.toLin' M (v₁.repr v)) = _ by
rw [Matrix.toLin'_apply, v₂.equivFun_symm_apply]
@[simp]
theorem Matrix.toLin_self (M : Matrix m n R) (i : n) :
Matrix.toLin v₁ v₂ M (v₁ i) = ∑ j, M j i • v₂ j := by
rw [Matrix.toLin_apply, Finset.sum_congr rfl fun j _hj ↦ ?_]
rw [Basis.repr_self, Matrix.mulVec, dotProduct, Finset.sum_eq_single i, Finsupp.single_eq_same,
mul_one]
· intro i' _ i'_ne
rw [Finsupp.single_eq_of_ne i'_ne.symm, mul_zero]
· intros
have := Finset.mem_univ i
contradiction
variable {M₃ : Type*} [AddCommMonoid M₃] [Module R M₃] (v₃ : Basis l R M₃)
theorem LinearMap.toMatrix_comp [Finite l] [DecidableEq m] (f : M₂ →ₗ[R] M₃) (g : M₁ →ₗ[R] M₂) :
LinearMap.toMatrix v₁ v₃ (f.comp g) =
| LinearMap.toMatrix v₂ v₃ f * LinearMap.toMatrix v₁ v₂ g := by
simp_rw [LinearMap.toMatrix, LinearEquiv.trans_apply, LinearEquiv.arrowCongr_comp _ v₂.equivFun,
| Mathlib/LinearAlgebra/Matrix/ToLin.lean | 632 | 633 |
/-
Copyright (c) 2024 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.CategoryTheory.Limits.Shapes.Products
import Mathlib.CategoryTheory.Limits.Shapes.Pullback.CommSq
import Mathlib.CategoryTheory.Limits.Shapes.Pullback.HasPullback
import Mathlib.AlgebraicTopology.RelativeCellComplex.AttachCells
/-!
# Construction for the small object argument
Given a family of morphisms `f i : A i ⟶ B i` in a category `C`,
we define a functor
`SmallObject.functor f : Arrow S ⥤ Arrow S` which sends
an object given by arrow `πX : X ⟶ S` to the pushout `functorObj f πX`:
```
∐ functorObjSrcFamily f πX ⟶ X
| |
| |
v v
∐ functorObjTgtFamily f πX ⟶ functorObj f πX
```
where the morphism on the left is a coproduct (of copies of maps `f i`)
indexed by a type `FunctorObjIndex f πX` which parametrizes the
diagrams of the form
```
A i ⟶ X
| |
| |
v v
B i ⟶ S
```
The morphism `ιFunctorObj f πX : X ⟶ functorObj f πX` is part of
a natural transformation `SmallObject.ε f : 𝟭 (Arrow C) ⟶ functor f S`.
The main idea in this construction is that for any commutative square
as above, there may not exist a lifting `B i ⟶ X`, but the construction
provides a tautological morphism `B i ⟶ functorObj f πX`
(see `SmallObject.ιFunctorObj_extension`).
## References
- https://ncatlab.org/nlab/show/small+object+argument
-/
universe t w v u
namespace CategoryTheory
open Category Limits HomotopicalAlgebra
namespace SmallObject
variable {C : Type u} [Category.{v} C] {I : Type w} {A B : I → C} (f : ∀ i, A i ⟶ B i)
section
variable {S X : C} (πX : X ⟶ S)
/-- Given a family of morphisms `f i : A i ⟶ B i` and a morphism `πX : X ⟶ S`,
this type parametrizes the commutative squares with a morphism `f i` on the left
and `πX` in the right. -/
structure FunctorObjIndex where
/-- an element in the index type -/
i : I
/-- the top morphism in the square -/
t : A i ⟶ X
/-- the bottom morphism in the square -/
b : B i ⟶ S
w : t ≫ πX = f i ≫ b
attribute [reassoc (attr := simp)] FunctorObjIndex.w
variable [HasColimitsOfShape (Discrete (FunctorObjIndex f πX)) C]
/-- The family of objects `A x.i` parametrized by `x : FunctorObjIndex f πX`. -/
abbrev functorObjSrcFamily (x : FunctorObjIndex f πX) : C := A x.i
/-- The family of objects `B x.i` parametrized by `x : FunctorObjIndex f πX`. -/
abbrev functorObjTgtFamily (x : FunctorObjIndex f πX) : C := B x.i
/-- The family of the morphisms `f x.i : A x.i ⟶ B x.i`
parametrized by `x : FunctorObjIndex f πX`. -/
abbrev functorObjLeftFamily (x : FunctorObjIndex f πX) :
functorObjSrcFamily f πX x ⟶ functorObjTgtFamily f πX x := f x.i
/-- The top morphism in the pushout square in the definition of `pushoutObj f πX`. -/
noncomputable abbrev functorObjTop : ∐ functorObjSrcFamily f πX ⟶ X :=
Limits.Sigma.desc (fun x => x.t)
/-- The left morphism in the pushout square in the definition of `pushoutObj f πX`. -/
noncomputable abbrev functorObjLeft :
∐ functorObjSrcFamily f πX ⟶ ∐ functorObjTgtFamily f πX :=
Limits.Sigma.map (functorObjLeftFamily f πX)
variable [HasPushout (functorObjTop f πX) (functorObjLeft f πX)]
/-- The functor `SmallObject.functor f : Arrow C ⥤ Arrow C` that is part of
the small object argument for a family of morphisms `f`, on an object given
as a morphism `πX : X ⟶ S`. -/
noncomputable abbrev functorObj : C :=
pushout (functorObjTop f πX) (functorObjLeft f πX)
/-- The canonical morphism `X ⟶ functorObj f πX`. -/
noncomputable abbrev ιFunctorObj : X ⟶ functorObj f πX := pushout.inl _ _
/-- The canonical morphism `∐ (functorObjTgtFamily f πX) ⟶ functorObj f πX`. -/
noncomputable abbrev ρFunctorObj : ∐ functorObjTgtFamily f πX ⟶ functorObj f πX := pushout.inr _ _
@[reassoc]
lemma functorObj_comm :
functorObjTop f πX ≫ ιFunctorObj f πX = functorObjLeft f πX ≫ ρFunctorObj f πX :=
pushout.condition
lemma functorObj_isPushout :
IsPushout (functorObjTop f πX) (functorObjLeft f πX) (ιFunctorObj f πX) (ρFunctorObj f πX) :=
IsPushout.of_hasPushout _ _
@[reassoc]
lemma FunctorObjIndex.comm (x : FunctorObjIndex f πX) :
f x.i ≫ Sigma.ι (functorObjTgtFamily f πX) x ≫ ρFunctorObj f πX = x.t ≫ ιFunctorObj f πX := by
simpa using (Sigma.ι (functorObjSrcFamily f πX) x ≫= functorObj_comm f πX).symm
/-- The canonical projection on the base object. -/
noncomputable abbrev π'FunctorObj : ∐ functorObjTgtFamily f πX ⟶ S := Sigma.desc (fun x => x.b)
/-- The canonical projection on the base object. -/
noncomputable def πFunctorObj : functorObj f πX ⟶ S :=
pushout.desc πX (π'FunctorObj f πX) (by ext; simp [π'FunctorObj])
@[reassoc (attr := simp)]
lemma ρFunctorObj_π : ρFunctorObj f πX ≫ πFunctorObj f πX = π'FunctorObj f πX := by
simp [πFunctorObj]
@[reassoc (attr := simp)]
lemma ιFunctorObj_πFunctorObj : ιFunctorObj f πX ≫ πFunctorObj f πX = πX := by
| simp [ιFunctorObj, πFunctorObj]
/-- The morphism `ιFunctorObj f πX : X ⟶ functorObj f πX` is obtained by
| Mathlib/CategoryTheory/SmallObject/Construction.lean | 140 | 142 |
/-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon
-/
import Mathlib.Data.Fin.Fin2
import Mathlib.Logic.Function.Basic
import Mathlib.Tactic.Common
/-!
# Tuples of types, and their categorical structure.
## Features
* `TypeVec n` - n-tuples of types
* `α ⟹ β` - n-tuples of maps
* `f ⊚ g` - composition
Also, support functions for operating with n-tuples of types, such as:
* `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple
* `drop α` - drops the last element of an (n+1)-tuple
* `last α` - returns the last element of an (n+1)-tuple
* `appendFun f g` - appends a function g to an n-tuple of functions
* `dropFun f` - drops the last function from an n+1-tuple
* `lastFun f` - returns the last function of a tuple.
Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal
to it, we need support functions and lemmas to mediate between constructions.
-/
universe u v w
/-- n-tuples of types, as a category -/
@[pp_with_univ]
def TypeVec (n : ℕ) :=
Fin2 n → Type*
instance {n} : Inhabited (TypeVec.{u} n) :=
⟨fun _ => PUnit⟩
namespace TypeVec
variable {n : ℕ}
/-- arrow in the category of `TypeVec` -/
def Arrow (α β : TypeVec n) :=
∀ i : Fin2 n, α i → β i
@[inherit_doc] scoped[MvFunctor] infixl:40 " ⟹ " => TypeVec.Arrow
open MvFunctor
/-- Extensionality for arrows -/
@[ext]
theorem Arrow.ext {α β : TypeVec n} (f g : α ⟹ β) :
(∀ i, f i = g i) → f = g := by
intro h; funext i; apply h
instance Arrow.inhabited (α β : TypeVec n) [∀ i, Inhabited (β i)] : Inhabited (α ⟹ β) :=
⟨fun _ _ => default⟩
/-- identity of arrow composition -/
def id {α : TypeVec n} : α ⟹ α := fun _ x => x
/-- arrow composition in the category of `TypeVec` -/
def comp {α β γ : TypeVec n} (g : β ⟹ γ) (f : α ⟹ β) : α ⟹ γ := fun i x => g i (f i x)
@[inherit_doc] scoped[MvFunctor] infixr:80 " ⊚ " => TypeVec.comp -- type as \oo
@[simp]
theorem id_comp {α β : TypeVec n} (f : α ⟹ β) : id ⊚ f = f :=
rfl
@[simp]
theorem comp_id {α β : TypeVec n} (f : α ⟹ β) : f ⊚ id = f :=
rfl
theorem comp_assoc {α β γ δ : TypeVec n} (h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) :
(h ⊚ g) ⊚ f = h ⊚ g ⊚ f :=
rfl
/-- Support for extending a `TypeVec` by one element. -/
def append1 (α : TypeVec n) (β : Type*) : TypeVec (n + 1)
| Fin2.fs i => α i
| Fin2.fz => β
@[inherit_doc] infixl:67 " ::: " => append1
/-- retain only a `n-length` prefix of the argument -/
def drop (α : TypeVec.{u} (n + 1)) : TypeVec n := fun i => α i.fs
/-- take the last value of a `(n+1)-length` vector -/
def last (α : TypeVec.{u} (n + 1)) : Type _ :=
α Fin2.fz
instance last.inhabited (α : TypeVec (n + 1)) [Inhabited (α Fin2.fz)] : Inhabited (last α) :=
⟨show α Fin2.fz from default⟩
theorem drop_append1 {α : TypeVec n} {β : Type*} {i : Fin2 n} : drop (append1 α β) i = α i :=
rfl
theorem drop_append1' {α : TypeVec n} {β : Type*} : drop (append1 α β) = α :=
funext fun _ => drop_append1
theorem last_append1 {α : TypeVec n} {β : Type*} : last (append1 α β) = β :=
rfl
@[simp]
theorem append1_drop_last (α : TypeVec (n + 1)) : append1 (drop α) (last α) = α :=
funext fun i => by cases i <;> rfl
/-- cases on `(n+1)-length` vectors -/
@[elab_as_elim]
def append1Cases {C : TypeVec (n + 1) → Sort u} (H : ∀ α β, C (append1 α β)) (γ) : C γ := by
rw [← @append1_drop_last _ γ]; apply H
@[simp]
theorem append1_cases_append1 {C : TypeVec (n + 1) → Sort u} (H : ∀ α β, C (append1 α β)) (α β) :
@append1Cases _ C H (append1 α β) = H α β :=
rfl
/-- append an arrow and a function for arbitrary source and target type vectors -/
def splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') : α ⟹ α'
| Fin2.fs i => f i
| Fin2.fz => g
/-- append an arrow and a function as well as their respective source and target types / typevecs -/
def appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
append1 α β ⟹ append1 α' β' :=
splitFun f g
@[inherit_doc] infixl:0 " ::: " => appendFun
/-- split off the prefix of an arrow -/
def dropFun {α β : TypeVec (n + 1)} (f : α ⟹ β) : drop α ⟹ drop β := fun i => f i.fs
/-- split off the last function of an arrow -/
def lastFun {α β : TypeVec (n + 1)} (f : α ⟹ β) : last α → last β :=
f Fin2.fz
/-- arrow in the category of `0-length` vectors -/
def nilFun {α : TypeVec 0} {β : TypeVec 0} : α ⟹ β := fun i => by apply Fin2.elim0 i
theorem eq_of_drop_last_eq {α β : TypeVec (n + 1)} {f g : α ⟹ β} (h₀ : dropFun f = dropFun g)
(h₁ : lastFun f = lastFun g) : f = g := by
refine funext (fun x => ?_)
cases x
· apply h₁
· apply congr_fun h₀
@[simp]
theorem dropFun_splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') :
dropFun (splitFun f g) = f :=
rfl
/-- turn an equality into an arrow -/
def Arrow.mp {α β : TypeVec n} (h : α = β) : α ⟹ β
| _ => Eq.mp (congr_fun h _)
/-- turn an equality into an arrow, with reverse direction -/
def Arrow.mpr {α β : TypeVec n} (h : α = β) : β ⟹ α
| _ => Eq.mpr (congr_fun h _)
/-- decompose a vector into its prefix appended with its last element -/
def toAppend1DropLast {α : TypeVec (n + 1)} : α ⟹ (drop α ::: last α) :=
Arrow.mpr (append1_drop_last _)
/-- stitch two bits of a vector back together -/
def fromAppend1DropLast {α : TypeVec (n + 1)} : (drop α ::: last α) ⟹ α :=
Arrow.mp (append1_drop_last _)
@[simp]
theorem lastFun_splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') :
lastFun (splitFun f g) = g :=
rfl
@[simp]
theorem dropFun_appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
dropFun (f ::: g) = f :=
rfl
@[simp]
theorem lastFun_appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
lastFun (f ::: g) = g :=
rfl
theorem split_dropFun_lastFun {α α' : TypeVec (n + 1)} (f : α ⟹ α') :
splitFun (dropFun f) (lastFun f) = f :=
eq_of_drop_last_eq rfl rfl
theorem splitFun_inj {α α' : TypeVec (n + 1)} {f f' : drop α ⟹ drop α'} {g g' : last α → last α'}
(H : splitFun f g = splitFun f' g') : f = f' ∧ g = g' := by
rw [← dropFun_splitFun f g, H, ← lastFun_splitFun f g, H]; simp
theorem appendFun_inj {α α' : TypeVec n} {β β' : Type*} {f f' : α ⟹ α'} {g g' : β → β'} :
(f ::: g : (α ::: β) ⟹ _) = (f' ::: g' : (α ::: β) ⟹ _)
→ f = f' ∧ g = g' :=
splitFun_inj
theorem splitFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : drop α₀ ⟹ drop α₁)
(f₁ : drop α₁ ⟹ drop α₂) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) :
splitFun (f₁ ⊚ f₀) (g₁ ∘ g₀) = splitFun f₁ g₁ ⊚ splitFun f₀ g₀ :=
eq_of_drop_last_eq rfl rfl
theorem appendFun_comp_splitFun {α γ : TypeVec n} {β δ : Type*} {ε : TypeVec (n + 1)}
(f₀ : drop ε ⟹ α) (f₁ : α ⟹ γ) (g₀ : last ε → β) (g₁ : β → δ) :
appendFun f₁ g₁ ⊚ splitFun f₀ g₀ = splitFun (α' := γ.append1 δ) (f₁ ⊚ f₀) (g₁ ∘ g₀) :=
(splitFun_comp _ _ _ _).symm
theorem appendFun_comp {α₀ α₁ α₂ : TypeVec n}
{β₀ β₁ β₂ : Type*}
(f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂)
(g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
(f₁ ⊚ f₀ ::: g₁ ∘ g₀) = (f₁ ::: g₁) ⊚ (f₀ ::: g₀) :=
eq_of_drop_last_eq rfl rfl
theorem appendFun_comp' {α₀ α₁ α₂ : TypeVec n} {β₀ β₁ β₂ : Type*}
(f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
(f₁ ::: g₁) ⊚ (f₀ ::: g₀) = (f₁ ⊚ f₀ ::: g₁ ∘ g₀) :=
eq_of_drop_last_eq rfl rfl
theorem nilFun_comp {α₀ : TypeVec 0} (f₀ : α₀ ⟹ Fin2.elim0) : nilFun ⊚ f₀ = f₀ :=
funext Fin2.elim0
theorem appendFun_comp_id {α : TypeVec n} {β₀ β₁ β₂ : Type u} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
(@id _ α ::: g₁ ∘ g₀) = (id ::: g₁) ⊚ (id ::: g₀) :=
eq_of_drop_last_eq rfl rfl
@[simp]
theorem dropFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) :
dropFun (f₁ ⊚ f₀) = dropFun f₁ ⊚ dropFun f₀ :=
rfl
@[simp]
theorem lastFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) :
lastFun (f₁ ⊚ f₀) = lastFun f₁ ∘ lastFun f₀ :=
rfl
theorem appendFun_aux {α α' : TypeVec n} {β β' : Type*} (f : (α ::: β) ⟹ (α' ::: β')) :
(dropFun f ::: lastFun f) = f :=
eq_of_drop_last_eq rfl rfl
theorem appendFun_id_id {α : TypeVec n} {β : Type*} :
(@TypeVec.id n α ::: @_root_.id β) = TypeVec.id :=
eq_of_drop_last_eq rfl rfl
instance subsingleton0 : Subsingleton (TypeVec 0) :=
⟨fun _ _ => funext Fin2.elim0⟩
-- See `Mathlib.Tactic.Attr.Register` for `register_simp_attr typevec`
/-- cases distinction for 0-length type vector -/
protected def casesNil {β : TypeVec 0 → Sort*} (f : β Fin2.elim0) : ∀ v, β v :=
fun v => cast (by congr; funext i; cases i) f
/-- cases distinction for (n+1)-length type vector -/
protected def casesCons (n : ℕ) {β : TypeVec (n + 1) → Sort*}
(f : ∀ (t) (v : TypeVec n), β (v ::: t)) :
∀ v, β v :=
fun v : TypeVec (n + 1) => cast (by simp) (f v.last v.drop)
protected theorem casesNil_append1 {β : TypeVec 0 → Sort*} (f : β Fin2.elim0) :
TypeVec.casesNil f Fin2.elim0 = f :=
rfl
protected theorem casesCons_append1 (n : ℕ) {β : TypeVec (n + 1) → Sort*}
(f : ∀ (t) (v : TypeVec n), β (v ::: t)) (v : TypeVec n) (α) :
TypeVec.casesCons n f (v ::: α) = f α v :=
rfl
/-- cases distinction for an arrow in the category of 0-length type vectors -/
def typevecCasesNil₃ {β : ∀ v v' : TypeVec 0, v ⟹ v' → Sort*}
(f : β Fin2.elim0 Fin2.elim0 nilFun) :
∀ v v' fs, β v v' fs := fun v v' fs => by
refine cast ?_ f
have eq₁ : v = Fin2.elim0 := by funext i; contradiction
have eq₂ : v' = Fin2.elim0 := by funext i; contradiction
have eq₃ : fs = nilFun := by funext i; contradiction
cases eq₁; cases eq₂; cases eq₃; rfl
/-- cases distinction for an arrow in the category of (n+1)-length type vectors -/
def typevecCasesCons₃ (n : ℕ) {β : ∀ v v' : TypeVec (n + 1), v ⟹ v' → Sort*}
(F : ∀ (t t') (f : t → t') (v v' : TypeVec n) (fs : v ⟹ v'),
β (v ::: t) (v' ::: t') (fs ::: f)) :
∀ v v' fs, β v v' fs := by
intro v v'
rw [← append1_drop_last v, ← append1_drop_last v']
intro fs
rw [← split_dropFun_lastFun fs]
apply F
/-- specialized cases distinction for an arrow in the category of 0-length type vectors -/
def typevecCasesNil₂ {β : Fin2.elim0 ⟹ Fin2.elim0 → Sort*} (f : β nilFun) : ∀ f, β f := by
intro g
suffices g = nilFun by rwa [this]
ext ⟨⟩
/-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/
def typevecCasesCons₂ (n : ℕ) (t t' : Type*) (v v' : TypeVec n)
{β : (v ::: t) ⟹ (v' ::: t') → Sort*}
(F : ∀ (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) : ∀ fs, β fs := by
intro fs
rw [← split_dropFun_lastFun fs]
apply F
theorem typevecCasesNil₂_appendFun {β : Fin2.elim0 ⟹ Fin2.elim0 → Sort*} (f : β nilFun) :
typevecCasesNil₂ f nilFun = f :=
rfl
theorem typevecCasesCons₂_appendFun (n : ℕ) (t t' : Type*) (v v' : TypeVec n)
{β : (v ::: t) ⟹ (v' ::: t') → Sort*}
(F : ∀ (f : t → t') (fs : v ⟹ v'), β (fs ::: f))
(f fs) :
typevecCasesCons₂ n t t' v v' F (fs ::: f) = F f fs :=
rfl
-- for lifting predicates and relations
/-- `PredLast α p x` predicates `p` of the last element of `x : α.append1 β`. -/
def PredLast (α : TypeVec n) {β : Type*} (p : β → Prop) : ∀ ⦃i⦄, (α.append1 β) i → Prop
| Fin2.fs _ => fun _ => True
| Fin2.fz => p
/-- `RelLast α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and
all the other elements are equal. -/
def RelLast (α : TypeVec n) {β γ : Type u} (r : β → γ → Prop) :
∀ ⦃i⦄, (α.append1 β) i → (α.append1 γ) i → Prop
| Fin2.fs _ => Eq
| Fin2.fz => r
section Liftp'
open Nat
/-- `repeat n t` is a `n-length` type vector that contains `n` occurrences of `t` -/
def «repeat» : ∀ (n : ℕ), Sort _ → TypeVec n
| 0, _ => Fin2.elim0
| Nat.succ i, t => append1 («repeat» i t) t
/-- `prod α β` is the pointwise product of the components of `α` and `β` -/
def prod : ∀ {n}, TypeVec.{u} n → TypeVec.{u} n → TypeVec n
| 0, _, _ => Fin2.elim0
| n + 1, α, β => (@prod n (drop α) (drop β)) ::: (last α × last β)
@[inherit_doc] scoped[MvFunctor] infixl:45 " ⊗ " => TypeVec.prod
/-- `const x α` is an arrow that ignores its source and constructs a `TypeVec` that
contains nothing but `x` -/
protected def const {β} (x : β) : ∀ {n} (α : TypeVec n), α ⟹ «repeat» _ β
| succ _, α, Fin2.fs _ => TypeVec.const x (drop α) _
| succ _, _, Fin2.fz => fun _ => x
open Function (uncurry)
/-- vector of equality on a product of vectors -/
def repeatEq : ∀ {n} (α : TypeVec n), (α ⊗ α) ⟹ «repeat» _ Prop
| 0, _ => nilFun
| succ _, α => repeatEq (drop α) ::: uncurry Eq
theorem const_append1 {β γ} (x : γ) {n} (α : TypeVec n) :
TypeVec.const x (α ::: β) = appendFun (TypeVec.const x α) fun _ => x := by
ext i : 1; cases i <;> rfl
theorem eq_nilFun {α β : TypeVec 0} (f : α ⟹ β) : f = nilFun := by
ext x; cases x
theorem id_eq_nilFun {α : TypeVec 0} : @id _ α = nilFun := by
ext x; cases x
theorem const_nil {β} (x : β) (α : TypeVec 0) : TypeVec.const x α = nilFun := by
ext i : 1; cases i
@[typevec]
theorem repeat_eq_append1 {β} {n} (α : TypeVec n) :
repeatEq (α ::: β) = splitFun (α := (α ⊗ α) ::: _)
(α' := («repeat» n Prop) ::: _) (repeatEq α) (uncurry Eq) := by
induction n <;> rfl
@[typevec]
theorem repeat_eq_nil (α : TypeVec 0) : repeatEq α = nilFun := by ext i; cases i
/-- predicate on a type vector to constrain only the last object -/
def PredLast' (α : TypeVec n) {β : Type*} (p : β → Prop) :
(α ::: β) ⟹ «repeat» (n + 1) Prop :=
splitFun (TypeVec.const True α) p
/-- predicate on the product of two type vectors to constrain only their last object -/
def RelLast' (α : TypeVec n) {β : Type*} (p : β → β → Prop) :
(α ::: β) ⊗ (α ::: β) ⟹ «repeat» (n + 1) Prop :=
splitFun (repeatEq α) (uncurry p)
/-- given `F : TypeVec.{u} (n+1) → Type u`, `curry F : Type u → TypeVec.{u} → Type u`,
i.e. its first argument can be fed in separately from the rest of the vector of arguments -/
def Curry (F : TypeVec.{u} (n + 1) → Type*) (α : Type u) (β : TypeVec.{u} n) : Type _ :=
F (β ::: α)
instance Curry.inhabited (F : TypeVec.{u} (n + 1) → Type*) (α : Type u) (β : TypeVec.{u} n)
[I : Inhabited (F <| (β ::: α))] : Inhabited (Curry F α β) :=
I
/-- arrow to remove one element of a `repeat` vector -/
def dropRepeat (α : Type*) : ∀ {n}, drop («repeat» (succ n) α) ⟹ «repeat» n α
| succ _, Fin2.fs i => dropRepeat α i
| succ _, Fin2.fz => fun (a : α) => a
/-- projection for a repeat vector -/
def ofRepeat {α : Sort _} : ∀ {n i}, «repeat» n α i → α
| _, Fin2.fz => fun (a : α) => a
| _, Fin2.fs i => @ofRepeat _ _ i
theorem const_iff_true {α : TypeVec n} {i x p} : ofRepeat (TypeVec.const p α i x) ↔ p := by
induction i with
| fz => rfl
| fs _ ih =>
rw [TypeVec.const]
exact ih
section
variable {α β : TypeVec.{u} n}
variable (p : α ⟹ «repeat» n Prop)
/-- left projection of a `prod` vector -/
def prod.fst : ∀ {n} {α β : TypeVec.{u} n}, α ⊗ β ⟹ α
| succ _, α, β, Fin2.fs i => @prod.fst _ (drop α) (drop β) i
| succ _, _, _, Fin2.fz => Prod.fst
/-- right projection of a `prod` vector -/
def prod.snd : ∀ {n} {α β : TypeVec.{u} n}, α ⊗ β ⟹ β
| succ _, α, β, Fin2.fs i => @prod.snd _ (drop α) (drop β) i
| succ _, _, _, Fin2.fz => Prod.snd
/-- introduce a product where both components are the same -/
def prod.diag : ∀ {n} {α : TypeVec.{u} n}, α ⟹ α ⊗ α
| succ _, α, Fin2.fs _, x => @prod.diag _ (drop α) _ x
| succ _, _, Fin2.fz, x => (x, x)
/-- constructor for `prod` -/
def prod.mk : ∀ {n} {α β : TypeVec.{u} n} (i : Fin2 n), α i → β i → (α ⊗ β) i
| succ _, α, β, Fin2.fs i => mk (α := fun i => α i.fs) (β := fun i => β i.fs) i
| succ _, _, _, Fin2.fz => Prod.mk
end
@[simp]
theorem prod_fst_mk {α β : TypeVec n} (i : Fin2 n) (a : α i) (b : β i) :
TypeVec.prod.fst i (prod.mk i a b) = a := by
induction i with
| fz => simp_all only [prod.fst, prod.mk]
| fs _ i_ih => apply i_ih
@[simp]
theorem prod_snd_mk {α β : TypeVec n} (i : Fin2 n) (a : α i) (b : β i) :
TypeVec.prod.snd i (prod.mk i a b) = b := by
induction i with
| fz => simp_all [prod.snd, prod.mk]
| fs _ i_ih => apply i_ih
/-- `prod` is functorial -/
protected def prod.map : ∀ {n} {α α' β β' : TypeVec.{u} n}, α ⟹ β → α' ⟹ β' → α ⊗ α' ⟹ β ⊗ β'
| succ _, α, α', β, β', x, y, Fin2.fs _, a =>
@prod.map _ (drop α) (drop α') (drop β) (drop β') (dropFun x) (dropFun y) _ a
| succ _, _, _, _, _, x, y, Fin2.fz, a => (x _ a.1, y _ a.2)
@[inherit_doc] scoped[MvFunctor] infixl:45 " ⊗' " => TypeVec.prod.map
theorem fst_prod_mk {α α' β β' : TypeVec n} (f : α ⟹ β) (g : α' ⟹ β') :
TypeVec.prod.fst ⊚ (f ⊗' g) = f ⊚ TypeVec.prod.fst := by
funext i; induction i with
| fz => rfl
| fs _ i_ih => apply i_ih
theorem snd_prod_mk {α α' β β' : TypeVec n} (f : α ⟹ β) (g : α' ⟹ β') :
TypeVec.prod.snd ⊚ (f ⊗' g) = g ⊚ TypeVec.prod.snd := by
funext i; induction i with
| fz => rfl
| fs _ i_ih => apply i_ih
theorem fst_diag {α : TypeVec n} : TypeVec.prod.fst ⊚ (prod.diag : α ⟹ _) = id := by
funext i; induction i with
| fz => rfl
| fs _ i_ih => apply i_ih
theorem snd_diag {α : TypeVec n} : TypeVec.prod.snd ⊚ (prod.diag : α ⟹ _) = id := by
funext i; induction i with
| fz => rfl
| fs _ i_ih => apply i_ih
theorem repeatEq_iff_eq {α : TypeVec n} {i x y} :
ofRepeat (repeatEq α i (prod.mk _ x y)) ↔ x = y := by
induction i with
| fz => rfl
| fs _ i_ih =>
rw [repeatEq]
exact i_ih
/-- given a predicate vector `p` over vector `α`, `Subtype_ p` is the type of vectors
that contain an `α` that satisfies `p` -/
def Subtype_ : ∀ {n} {α : TypeVec.{u} n}, (α ⟹ «repeat» n Prop) → TypeVec n
| _, _, p, Fin2.fz => Subtype fun x => p Fin2.fz x
| _, _, p, Fin2.fs i => Subtype_ (dropFun p) i
/-- projection on `Subtype_` -/
def subtypeVal : ∀ {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop), Subtype_ p ⟹ α
| succ n, _, _, Fin2.fs i => @subtypeVal n _ _ i
| succ _, _, _, Fin2.fz => Subtype.val
/-- arrow that rearranges the type of `Subtype_` to turn a subtype of vector into
a vector of subtypes -/
def toSubtype :
∀ {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop),
(fun i : Fin2 n => { x // ofRepeat <| p i x }) ⟹ Subtype_ p
| succ _, _, p, Fin2.fs i, x => toSubtype (dropFun p) i x
| succ _, _, _, Fin2.fz, x => x
/-- arrow that rearranges the type of `Subtype_` to turn a vector of subtypes
into a subtype of vector -/
def ofSubtype {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop) :
Subtype_ p ⟹ fun i : Fin2 n => { x // ofRepeat <| p i x }
| Fin2.fs i, x => ofSubtype _ i x
| Fin2.fz, x => x
/-- similar to `toSubtype` adapted to relations (i.e. predicate on product) -/
def toSubtype' {n} {α : TypeVec.{u} n} (p : α ⊗ α ⟹ «repeat» n Prop) :
(fun i : Fin2 n => { x : α i × α i // ofRepeat <| p i (prod.mk _ x.1 x.2) }) ⟹ Subtype_ p
| Fin2.fs i, x => toSubtype' (dropFun p) i x
| Fin2.fz, x => ⟨x.val, cast (by congr) x.property⟩
/-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/
def ofSubtype' {n} {α : TypeVec.{u} n} (p : α ⊗ α ⟹ «repeat» n Prop) :
Subtype_ p ⟹ fun i : Fin2 n => { x : α i × α i // ofRepeat <| p i (prod.mk _ x.1 x.2) }
| Fin2.fs i, x => ofSubtype' _ i x
| Fin2.fz, x => ⟨x.val, cast (by congr) x.property⟩
/-- similar to `diag` but the target vector is a `Subtype_`
guaranteeing the equality of the components -/
def diagSub {n} {α : TypeVec.{u} n} : α ⟹ Subtype_ (repeatEq α)
| Fin2.fs _, x => @diagSub _ (drop α) _ x
| Fin2.fz, x => ⟨(x, x), rfl⟩
theorem subtypeVal_nil {α : TypeVec.{u} 0} (ps : α ⟹ «repeat» 0 Prop) :
TypeVec.subtypeVal ps = nilFun :=
funext <| by rintro ⟨⟩
theorem diag_sub_val {n} {α : TypeVec.{u} n} : subtypeVal (repeatEq α) ⊚ diagSub = prod.diag := by
ext i x
induction i with
| fz => simp only [comp, subtypeVal, repeatEq.eq_2, diagSub, prod.diag]
| fs _ i_ih => apply @i_ih (drop α)
theorem prod_id : ∀ {n} {α β : TypeVec.{u} n}, (id ⊗' id) = (id : α ⊗ β ⟹ _) := by
intros
ext i a
induction i with
| fz => cases a; rfl
| fs _ i_ih => apply i_ih
theorem append_prod_appendFun {n} {α α' β β' : TypeVec.{u} n} {φ φ' ψ ψ' : Type u}
{f₀ : α ⟹ α'} {g₀ : β ⟹ β'} {f₁ : φ → φ'} {g₁ : ψ → ψ'} :
((f₀ ⊗' g₀) ::: (_root_.Prod.map f₁ g₁)) = ((f₀ ::: f₁) ⊗' (g₀ ::: g₁)) := by
ext i a
cases i
· cases a
rfl
· rfl
end Liftp'
@[simp]
theorem dropFun_diag {α} : dropFun (@prod.diag (n + 1) α) = prod.diag := by
ext i : 2
induction i <;> simp [dropFun, *] <;> rfl
@[simp]
theorem dropFun_subtypeVal {α} (p : α ⟹ «repeat» (n + 1) Prop) :
dropFun (subtypeVal p) = subtypeVal _ :=
rfl
@[simp]
theorem lastFun_subtypeVal {α} (p : α ⟹ «repeat» (n + 1) Prop) :
lastFun (subtypeVal p) = Subtype.val :=
rfl
@[simp]
theorem dropFun_toSubtype {α} (p : α ⟹ «repeat» (n + 1) Prop) :
dropFun (toSubtype p) = toSubtype _ := by
ext i
induction i <;> simp [dropFun, *] <;> rfl
@[simp]
theorem lastFun_toSubtype {α} (p : α ⟹ «repeat» (n + 1) Prop) :
lastFun (toSubtype p) = _root_.id := by
ext i : 2
induction i; simp [dropFun, *]; rfl
@[simp]
theorem dropFun_of_subtype {α} (p : α ⟹ «repeat» (n + 1) Prop) :
dropFun (ofSubtype p) = ofSubtype _ := by
ext i : 2
induction i <;> simp [dropFun, *] <;> rfl
@[simp]
theorem lastFun_of_subtype {α} (p : α ⟹ «repeat» (n + 1) Prop) :
lastFun (ofSubtype p) = _root_.id := rfl
@[simp]
theorem dropFun_RelLast' {α : TypeVec n} {β} (R : β → β → Prop) :
dropFun (RelLast' α R) = repeatEq α :=
rfl
attribute [simp] drop_append1'
open MvFunctor
@[simp]
theorem dropFun_prod {α α' β β' : TypeVec (n + 1)} (f : α ⟹ β) (f' : α' ⟹ β') :
dropFun (f ⊗' f') = (dropFun f ⊗' dropFun f') := by
ext i : 2
induction i <;> simp [dropFun, *] <;> rfl
@[simp]
theorem lastFun_prod {α α' β β' : TypeVec (n + 1)} (f : α ⟹ β) (f' : α' ⟹ β') :
lastFun (f ⊗' f') = Prod.map (lastFun f) (lastFun f') := by
ext i : 1
induction i; simp [lastFun, *]; rfl
@[simp]
theorem dropFun_from_append1_drop_last {α : TypeVec (n + 1)} :
dropFun (@fromAppend1DropLast _ α) = id :=
rfl
@[simp]
theorem lastFun_from_append1_drop_last {α : TypeVec (n + 1)} :
lastFun (@fromAppend1DropLast _ α) = _root_.id :=
rfl
@[simp]
theorem dropFun_id {α : TypeVec (n + 1)} : dropFun (@TypeVec.id _ α) = id :=
rfl
@[simp]
theorem prod_map_id {α β : TypeVec n} : (@TypeVec.id _ α ⊗' @TypeVec.id _ β) = id := by
ext i x : 2
induction i <;> simp only [TypeVec.prod.map, *, dropFun_id]
cases x
· rfl
· rfl
@[simp]
theorem subtypeVal_diagSub {α : TypeVec n} : subtypeVal (repeatEq α) ⊚ diagSub = prod.diag := by
ext i x
induction i with
| fz => simp [comp, diagSub, subtypeVal, prod.diag]
| fs _ i_ih =>
simp only [comp, subtypeVal, diagSub, prod.diag] at *
apply i_ih
@[simp]
theorem toSubtype_of_subtype {α : TypeVec n} (p : α ⟹ «repeat» n Prop) :
toSubtype p ⊚ ofSubtype p = id := by
ext i x
induction i <;> simp only [id, toSubtype, comp, ofSubtype] at *
simp [*]
@[simp]
theorem subtypeVal_toSubtype {α : TypeVec n} (p : α ⟹ «repeat» n Prop) :
subtypeVal p ⊚ toSubtype p = fun _ => Subtype.val := by
ext i x
induction i <;> simp only [toSubtype, comp, subtypeVal] at *
simp [*]
@[simp]
theorem toSubtype_of_subtype_assoc
{α β : TypeVec n} (p : α ⟹ «repeat» n Prop) (f : β ⟹ Subtype_ p) :
@toSubtype n _ p ⊚ ofSubtype _ ⊚ f = f := by
rw [← comp_assoc, toSubtype_of_subtype]; simp
@[simp]
theorem toSubtype'_of_subtype' {α : TypeVec n} (r : α ⊗ α ⟹ «repeat» n Prop) :
toSubtype' r ⊚ ofSubtype' r = id := by
ext i x
induction i
<;> dsimp only [id, toSubtype', comp, ofSubtype'] at *
<;> simp [Subtype.eta, *]
theorem subtypeVal_toSubtype' {α : TypeVec n} (r : α ⊗ α ⟹ «repeat» n Prop) :
subtypeVal r ⊚ toSubtype' r = fun i x => prod.mk i x.1.fst x.1.snd := by
ext i x
induction i <;> simp only [id, toSubtype', comp, subtypeVal, prod.mk] at *
simp [*]
end TypeVec
| Mathlib/Data/TypeVec.lean | 804 | 809 | |
/-
Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Violeta Hernández Palacios
-/
import Mathlib.SetTheory.Ordinal.FixedPoint
/-!
# Principal ordinals
We define principal or indecomposable ordinals, and we prove the standard properties about them.
## Main definitions and results
* `Principal`: A principal or indecomposable ordinal under some binary operation. We include 0 and
any other typically excluded edge cases for simplicity.
* `not_bddAbove_principal`: Principal ordinals (under any operation) are unbounded.
* `principal_add_iff_zero_or_omega0_opow`: The main characterization theorem for additive principal
ordinals.
* `principal_mul_iff_le_two_or_omega0_opow_opow`: The main characterization theorem for
multiplicative principal ordinals.
## TODO
* Prove that exponential principal ordinals are 0, 1, 2, ω, or epsilon numbers, i.e. fixed points
of `fun x ↦ ω ^ x`.
-/
universe u
open Order
namespace Ordinal
variable {a b c o : Ordinal.{u}}
section Arbitrary
variable {op : Ordinal → Ordinal → Ordinal}
/-! ### Principal ordinals -/
/-- An ordinal `o` is said to be principal or indecomposable under an operation when the set of
ordinals less than it is closed under that operation. In standard mathematical usage, this term is
almost exclusively used for additive and multiplicative principal ordinals.
For simplicity, we break usual convention and regard `0` as principal. -/
def Principal (op : Ordinal → Ordinal → Ordinal) (o : Ordinal) : Prop :=
∀ ⦃a b⦄, a < o → b < o → op a b < o
theorem principal_swap_iff : Principal (Function.swap op) o ↔ Principal op o := by
constructor <;> exact fun h a b ha hb => h hb ha
theorem not_principal_iff : ¬ Principal op o ↔ ∃ a < o, ∃ b < o, o ≤ op a b := by
simp [Principal]
theorem principal_iff_of_monotone
(h₁ : ∀ a, Monotone (op a)) (h₂ : ∀ a, Monotone (Function.swap op a)) :
Principal op o ↔ ∀ a < o, op a a < o := by
use fun h a ha => h ha ha
intro H a b ha hb
obtain hab | hba := le_or_lt a b
· exact (h₂ b hab).trans_lt <| H b hb
· exact (h₁ a hba.le).trans_lt <| H a ha
theorem not_principal_iff_of_monotone
(h₁ : ∀ a, Monotone (op a)) (h₂ : ∀ a, Monotone (Function.swap op a)) :
¬ Principal op o ↔ ∃ a < o, o ≤ op a a := by
simp [principal_iff_of_monotone h₁ h₂]
theorem principal_zero : Principal op 0 := fun a _ h =>
(Ordinal.not_lt_zero a h).elim
@[simp]
theorem principal_one_iff : Principal op 1 ↔ op 0 0 = 0 := by
refine ⟨fun h => ?_, fun h a b ha hb => ?_⟩
· rw [← lt_one_iff_zero]
exact h zero_lt_one zero_lt_one
· rwa [lt_one_iff_zero, ha, hb] at *
theorem Principal.iterate_lt (hao : a < o) (ho : Principal op o) (n : ℕ) : (op a)^[n] a < o := by
induction' n with n hn
· rwa [Function.iterate_zero]
· rw [Function.iterate_succ']
exact ho hao hn
theorem op_eq_self_of_principal (hao : a < o) (H : IsNormal (op a))
(ho : Principal op o) (ho' : IsLimit o) : op a o = o := by
apply H.le_apply.antisymm'
rw [← IsNormal.bsup_eq.{u, u} H ho', bsup_le_iff]
exact fun b hbo => (ho hao hbo).le
theorem nfp_le_of_principal (hao : a < o) (ho : Principal op o) : nfp (op a) a ≤ o :=
nfp_le fun n => (ho.iterate_lt hao n).le
end Arbitrary
/-! ### Principal ordinals are unbounded -/
/-- We give an explicit construction for a principal ordinal larger or equal than `o`. -/
private theorem principal_nfp_iSup (op : Ordinal → Ordinal → Ordinal) (o : Ordinal) :
Principal op (nfp (fun x ↦ ⨆ y : Set.Iio x ×ˢ Set.Iio x, succ (op y.1.1 y.1.2)) o) := by
intro a b ha hb
rw [lt_nfp_iff] at *
obtain ⟨m, ha⟩ := ha
obtain ⟨n, hb⟩ := hb
obtain h | h := le_total
((fun x ↦ ⨆ y : Set.Iio x ×ˢ Set.Iio x, succ (op y.1.1 y.1.2))^[m] o)
((fun x ↦ ⨆ y : Set.Iio x ×ˢ Set.Iio x, succ (op y.1.1 y.1.2))^[n] o)
· use n + 1
rw [Function.iterate_succ']
apply (lt_succ _).trans_le
exact Ordinal.le_iSup (fun y : Set.Iio _ ×ˢ Set.Iio _ ↦ succ (op y.1.1 y.1.2))
⟨_, Set.mk_mem_prod (ha.trans_le h) hb⟩
· use m + 1
rw [Function.iterate_succ']
apply (lt_succ _).trans_le
exact Ordinal.le_iSup (fun y : Set.Iio _ ×ˢ Set.Iio _ ↦ succ (op y.1.1 y.1.2))
⟨_, Set.mk_mem_prod ha (hb.trans_le h)⟩
/-- Principal ordinals under any operation are unbounded. -/
theorem not_bddAbove_principal (op : Ordinal → Ordinal → Ordinal) :
¬ BddAbove { o | Principal op o } := by
rintro ⟨a, ha⟩
exact ((le_nfp _ _).trans (ha (principal_nfp_iSup op (succ a)))).not_lt (lt_succ a)
/-! #### Additive principal ordinals -/
theorem principal_add_one : Principal (· + ·) 1 :=
principal_one_iff.2 <| zero_add 0
theorem principal_add_of_le_one (ho : o ≤ 1) : Principal (· + ·) o := by
rcases le_one_iff.1 ho with (rfl | rfl)
· exact principal_zero
· exact principal_add_one
theorem isLimit_of_principal_add (ho₁ : 1 < o) (ho : Principal (· + ·) o) : o.IsLimit := by
rw [isLimit_iff, isSuccPrelimit_iff_succ_lt]
exact ⟨ho₁.ne_bot, fun _ ha ↦ ho ha ho₁⟩
theorem principal_add_iff_add_left_eq_self : Principal (· + ·) o ↔ ∀ a < o, a + o = o := by
refine ⟨fun ho a hao => ?_, fun h a b hao hbo => ?_⟩
· rcases lt_or_le 1 o with ho₁ | ho₁
· exact op_eq_self_of_principal hao (isNormal_add_right a) ho (isLimit_of_principal_add ho₁ ho)
· rcases le_one_iff.1 ho₁ with (rfl | rfl)
· exact (Ordinal.not_lt_zero a hao).elim
· rw [lt_one_iff_zero] at hao
rw [hao, zero_add]
· rw [← h a hao]
exact (isNormal_add_right a).strictMono hbo
theorem exists_lt_add_of_not_principal_add (ha : ¬ Principal (· + ·) a) :
∃ b < a, ∃ c < a, b + c = a := by
rw [not_principal_iff] at ha
rcases ha with ⟨b, hb, c, hc, H⟩
refine
⟨b, hb, _, lt_of_le_of_ne (sub_le_self a b) fun hab => ?_, Ordinal.add_sub_cancel_of_le hb.le⟩
rw [← sub_le, hab] at H
exact H.not_lt hc
theorem principal_add_iff_add_lt_ne_self : Principal (· + ·) a ↔ ∀ b < a, ∀ c < a, b + c ≠ a :=
⟨fun ha _ hb _ hc => (ha hb hc).ne, fun H => by
by_contra! ha
rcases exists_lt_add_of_not_principal_add ha with ⟨b, hb, c, hc, rfl⟩
exact (H b hb c hc).irrefl⟩
theorem principal_add_omega0 : Principal (· + ·) ω :=
principal_add_iff_add_left_eq_self.2 fun _ => add_omega0
theorem add_omega0_opow (h : a < ω ^ b) : a + ω ^ b = ω ^ b := by
refine le_antisymm ?_ (le_add_left _ a)
induction' b using limitRecOn with b _ b l IH
· rw [opow_zero, ← succ_zero, lt_succ_iff, Ordinal.le_zero] at h
rw [h, zero_add]
· rw [opow_succ] at h
rcases (lt_mul_of_limit isLimit_omega0).1 h with ⟨x, xo, ax⟩
apply (add_le_add_right ax.le _).trans
rw [opow_succ, ← mul_add, add_omega0 xo]
· rcases (lt_opow_of_limit omega0_ne_zero l).1 h with ⟨x, xb, ax⟩
apply (((isNormal_add_right a).trans <| isNormal_opow one_lt_omega0).limit_le l).2
intro y yb
calc a + ω ^ y ≤ a + ω ^ max x y :=
add_le_add_left (opow_le_opow_right omega0_pos (le_max_right x y)) _
_ ≤ ω ^ max x y :=
IH _ (max_lt xb yb) <| ax.trans_le <| opow_le_opow_right omega0_pos <| le_max_left x y
_ ≤ ω ^ b :=
opow_le_opow_right omega0_pos <| (max_lt xb yb).le
theorem principal_add_omega0_opow (o : Ordinal) : Principal (· + ·) (ω ^ o) :=
principal_add_iff_add_left_eq_self.2 fun _ => add_omega0_opow
/-- The main characterization theorem for additive principal ordinals. -/
theorem principal_add_iff_zero_or_omega0_opow :
Principal (· + ·) o ↔ o = 0 ∨ o ∈ Set.range (ω ^ · : Ordinal → Ordinal) := by
rcases eq_or_ne o 0 with (rfl | ho)
· simp only [principal_zero, Or.inl]
· rw [principal_add_iff_add_left_eq_self]
simp only [ho, false_or]
refine
⟨fun H => ⟨_, ((lt_or_eq_of_le (opow_log_le_self _ ho)).resolve_left fun h => ?_)⟩,
fun ⟨b, e⟩ => e.symm ▸ fun a => add_omega0_opow⟩
have := H _ h
have := lt_opow_succ_log_self one_lt_omega0 o
rw [opow_succ, lt_mul_of_limit isLimit_omega0] at this
rcases this with ⟨a, ao, h'⟩
rcases lt_omega0.1 ao with ⟨n, rfl⟩
clear ao
revert h'
apply not_lt_of_le
suffices e : ω ^ log ω o * n + o = o by
simpa only [e] using le_add_right (ω ^ log ω o * ↑n) o
induction' n with n IH
· simp [Nat.cast_zero, mul_zero, zero_add]
· simp only [Nat.cast_succ, mul_add_one, add_assoc, this, IH]
theorem principal_add_opow_of_principal_add {a} (ha : Principal (· + ·) a) (b : Ordinal) :
Principal (· + ·) (a ^ b) := by
rcases principal_add_iff_zero_or_omega0_opow.1 ha with (rfl | ⟨c, rfl⟩)
· rcases eq_or_ne b 0 with (rfl | hb)
· rw [opow_zero]
exact principal_add_one
· rwa [zero_opow hb]
· rw [← opow_mul]
exact principal_add_omega0_opow _
theorem add_absorp (h₁ : a < ω ^ b) (h₂ : ω ^ b ≤ c) : a + c = c := by
rw [← Ordinal.add_sub_cancel_of_le h₂, ← add_assoc, add_omega0_opow h₁]
theorem principal_add_mul_of_principal_add (a : Ordinal.{u}) {b : Ordinal.{u}} (hb₁ : b ≠ 1)
(hb : Principal (· + ·) b) : Principal (· + ·) (a * b) := by
rcases eq_zero_or_pos a with (rfl | _)
· rw [zero_mul]
exact principal_zero
· rcases eq_zero_or_pos b with (rfl | hb₁')
· rw [mul_zero]
exact principal_zero
· rw [← succ_le_iff, succ_zero] at hb₁'
intro c d hc hd
rw [lt_mul_of_limit (isLimit_of_principal_add (lt_of_le_of_ne hb₁' hb₁.symm) hb)] at *
rcases hc with ⟨x, hx, hx'⟩
rcases hd with ⟨y, hy, hy'⟩
use x + y, hb hx hy
rw [mul_add]
exact Left.add_lt_add hx' hy'
/-! #### Multiplicative principal ordinals -/
theorem principal_mul_one : Principal (· * ·) 1 := by
rw [principal_one_iff]
exact zero_mul _
theorem principal_mul_two : Principal (· * ·) 2 := by
intro a b ha hb
rw [← succ_one, lt_succ_iff] at *
convert mul_le_mul' ha hb
exact (mul_one 1).symm
theorem principal_mul_of_le_two (ho : o ≤ 2) : Principal (· * ·) o := by
rcases lt_or_eq_of_le ho with (ho | rfl)
· rw [← succ_one, lt_succ_iff] at ho
rcases lt_or_eq_of_le ho with (ho | rfl)
· rw [lt_one_iff_zero.1 ho]
exact principal_zero
· exact principal_mul_one
· exact principal_mul_two
theorem principal_add_of_principal_mul (ho : Principal (· * ·) o) (ho₂ : o ≠ 2) :
Principal (· + ·) o := by
rcases lt_or_gt_of_ne ho₂ with ho₁ | ho₂
· replace ho₁ : o < succ 1 := by rwa [succ_one]
rw [lt_succ_iff] at ho₁
exact principal_add_of_le_one ho₁
· refine fun a b hao hbo => lt_of_le_of_lt ?_ (ho (max_lt hao hbo) ho₂)
dsimp only
rw [← one_add_one_eq_two, mul_add, mul_one]
exact add_le_add (le_max_left a b) (le_max_right a b)
theorem isLimit_of_principal_mul (ho₂ : 2 < o) (ho : Principal (· * ·) o) : o.IsLimit :=
isLimit_of_principal_add ((lt_succ 1).trans (succ_one ▸ ho₂))
(principal_add_of_principal_mul ho (ne_of_gt ho₂))
theorem principal_mul_iff_mul_left_eq : Principal (· * ·) o ↔ ∀ a, 0 < a → a < o → a * o = o := by
refine ⟨fun h a ha₀ hao => ?_, fun h a b hao hbo => ?_⟩
· rcases le_or_gt o 2 with ho | ho
· convert one_mul o
apply le_antisymm
· rw [← lt_succ_iff, succ_one]
exact hao.trans_le ho
· rwa [← succ_le_iff, succ_zero] at ha₀
· exact op_eq_self_of_principal hao (isNormal_mul_right ha₀) h (isLimit_of_principal_mul ho h)
· rcases eq_or_ne a 0 with (rfl | ha)
· dsimp only; rwa [zero_mul]
rw [← Ordinal.pos_iff_ne_zero] at ha
rw [← h a ha hao]
exact (isNormal_mul_right ha).strictMono hbo
theorem principal_mul_omega0 : Principal (· * ·) ω := fun a b ha hb =>
match a, b, lt_omega0.1 ha, lt_omega0.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ => by
dsimp only; rw [← natCast_mul]
apply nat_lt_omega0
theorem mul_omega0 (a0 : 0 < a) (ha : a < ω) : a * ω = ω :=
principal_mul_iff_mul_left_eq.1 principal_mul_omega0 a a0 ha
theorem natCast_mul_omega0 {n : ℕ} (hn : 0 < n) : n * ω = ω :=
mul_omega0 (mod_cast hn) (nat_lt_omega0 n)
theorem mul_lt_omega0_opow (c0 : 0 < c) (ha : a < ω ^ c) (hb : b < ω) : a * b < ω ^ c := by
rcases zero_or_succ_or_limit c with (rfl | ⟨c, rfl⟩ | l)
· exact (lt_irrefl _).elim c0
· rw [opow_succ] at ha
obtain ⟨n, hn, an⟩ :=
((isNormal_mul_right <| opow_pos _ omega0_pos).limit_lt isLimit_omega0).1 ha
apply (mul_le_mul_right' (le_of_lt an) _).trans_lt
rw [opow_succ, mul_assoc, mul_lt_mul_iff_left (opow_pos _ omega0_pos)]
exact principal_mul_omega0 hn hb
· rcases ((isNormal_opow one_lt_omega0).limit_lt l).1 ha with ⟨x, hx, ax⟩
refine (mul_le_mul' (le_of_lt ax) (le_of_lt hb)).trans_lt ?_
rw [← opow_succ, opow_lt_opow_iff_right one_lt_omega0]
exact l.succ_lt hx
theorem mul_omega0_opow_opow (a0 : 0 < a) (h : a < ω ^ ω ^ b) : a * ω ^ ω ^ b = ω ^ ω ^ b := by
obtain rfl | b0 := eq_or_ne b 0
· rw [opow_zero, opow_one] at h ⊢
exact mul_omega0 a0 h
· apply le_antisymm
· obtain ⟨x, xb, ax⟩ :=
(lt_opow_of_limit omega0_ne_zero (isLimit_opow_left isLimit_omega0 b0)).1 h
apply (mul_le_mul_right' (le_of_lt ax) _).trans
rw [← opow_add, add_omega0_opow xb]
· conv_lhs => rw [← one_mul (ω ^ _)]
exact mul_le_mul_right' (one_le_iff_pos.2 a0) _
theorem principal_mul_omega0_opow_opow (o : Ordinal) : Principal (· * ·) (ω ^ ω ^ o) :=
principal_mul_iff_mul_left_eq.2 fun _ => mul_omega0_opow_opow
theorem principal_add_of_principal_mul_opow (hb : 1 < b) (ho : Principal (· * ·) (b ^ o)) :
Principal (· + ·) o := by
intro x y hx hy
have := ho ((opow_lt_opow_iff_right hb).2 hx) ((opow_lt_opow_iff_right hb).2 hy)
dsimp only at *
rwa [← opow_add, opow_lt_opow_iff_right hb] at this
/-- The main characterization theorem for multiplicative principal ordinals. -/
theorem principal_mul_iff_le_two_or_omega0_opow_opow :
Principal (· * ·) o ↔ o ≤ 2 ∨ o ∈ Set.range (ω ^ ω ^ · : Ordinal → Ordinal) := by
refine ⟨fun ho => ?_, ?_⟩
· rcases le_or_lt o 2 with ho₂ | ho₂
· exact Or.inl ho₂
· rcases principal_add_iff_zero_or_omega0_opow.1 (principal_add_of_principal_mul ho ho₂.ne')
with (rfl | ⟨a, rfl⟩)
· exact (Ordinal.not_lt_zero 2 ho₂).elim
· rcases principal_add_iff_zero_or_omega0_opow.1
(principal_add_of_principal_mul_opow one_lt_omega0 ho) with (rfl | ⟨b, rfl⟩)
· simp
· exact Or.inr ⟨b, rfl⟩
· rintro (ho₂ | ⟨a, rfl⟩)
· exact principal_mul_of_le_two ho₂
· exact principal_mul_omega0_opow_opow a
theorem mul_omega0_dvd (a0 : 0 < a) (ha : a < ω) : ∀ {b}, ω ∣ b → a * b = b
| _, ⟨b, rfl⟩ => by rw [← mul_assoc, mul_omega0 a0 ha]
theorem mul_eq_opow_log_succ (ha : a ≠ 0) (hb : Principal (· * ·) b) (hb₂ : 2 < b) :
a * b = b ^ succ (log b a) := by
apply le_antisymm
· have hbl := isLimit_of_principal_mul hb₂ hb
rw [← (isNormal_mul_right (Ordinal.pos_iff_ne_zero.2 ha)).bsup_eq hbl, bsup_le_iff]
intro c hcb
have hb₁ : 1 < b := one_lt_two.trans hb₂
have hbo₀ : b ^ log b a ≠ 0 := Ordinal.pos_iff_ne_zero.1 (opow_pos _ (zero_lt_one.trans hb₁))
apply (mul_le_mul_right' (le_of_lt (lt_mul_succ_div a hbo₀)) c).trans
rw [mul_assoc, opow_succ]
refine mul_le_mul_left' (hb (hbl.succ_lt ?_) hcb).le _
rw [div_lt hbo₀, ← opow_succ]
exact lt_opow_succ_log_self hb₁ _
· rw [opow_succ]
exact mul_le_mul_right' (opow_log_le_self b ha) b
/-! #### Exponential principal ordinals -/
theorem principal_opow_omega0 : Principal (· ^ ·) ω := fun a b ha hb =>
match a, b, lt_omega0.1 ha, lt_omega0.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ => by
simp_rw [← natCast_opow]
apply nat_lt_omega0
theorem opow_omega0 (a1 : 1 < a) (h : a < ω) : a ^ ω = ω :=
((opow_le_of_limit (one_le_iff_ne_zero.1 <| le_of_lt a1) isLimit_omega0).2 fun _ hb =>
(principal_opow_omega0 h hb).le).antisymm
(right_le_opow _ a1)
theorem natCast_opow_omega0 {n : ℕ} (hn : 1 < n) : n ^ ω = ω :=
opow_omega0 (mod_cast hn) (nat_lt_omega0 n)
end Ordinal
| Mathlib/SetTheory/Ordinal/Principal.lean | 420 | 424 | |
/-
Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov, Hunter Monroe
-/
import Mathlib.Combinatorics.SimpleGraph.Init
import Mathlib.Data.Finite.Prod
import Mathlib.Data.Rel
import Mathlib.Data.Set.Finite.Basic
import Mathlib.Data.Sym.Sym2
/-!
# Simple graphs
This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation.
## Main definitions
* `SimpleGraph` is a structure for symmetric, irreflexive relations.
* `SimpleGraph.neighborSet` is the `Set` of vertices adjacent to a given vertex.
* `SimpleGraph.commonNeighbors` is the intersection of the neighbor sets of two given vertices.
* `SimpleGraph.incidenceSet` is the `Set` of edges containing a given vertex.
* `CompleteAtomicBooleanAlgebra` instance: Under the subgraph relation, `SimpleGraph` forms a
`CompleteAtomicBooleanAlgebra`. In other words, this is the complete lattice of spanning subgraphs
of the complete graph.
## TODO
* This is the simplest notion of an unoriented graph.
This should eventually fit into a more complete combinatorics hierarchy which includes
multigraphs and directed graphs.
We begin with simple graphs in order to start learning what the combinatorics hierarchy should
look like.
-/
attribute [aesop norm unfold (rule_sets := [SimpleGraph])] Symmetric
attribute [aesop norm unfold (rule_sets := [SimpleGraph])] Irreflexive
/--
A variant of the `aesop` tactic for use in the graph library. Changes relative
to standard `aesop`:
- We use the `SimpleGraph` rule set in addition to the default rule sets.
- We instruct Aesop's `intro` rule to unfold with `default` transparency.
- We instruct Aesop to fail if it can't fully solve the goal. This allows us to
use `aesop_graph` for auto-params.
-/
macro (name := aesop_graph) "aesop_graph" c:Aesop.tactic_clause* : tactic =>
`(tactic|
aesop $c*
(config := { introsTransparency? := some .default, terminal := true })
(rule_sets := [$(Lean.mkIdent `SimpleGraph):ident]))
/--
Use `aesop_graph?` to pass along a `Try this` suggestion when using `aesop_graph`
-/
macro (name := aesop_graph?) "aesop_graph?" c:Aesop.tactic_clause* : tactic =>
`(tactic|
aesop? $c*
(config := { introsTransparency? := some .default, terminal := true })
(rule_sets := [$(Lean.mkIdent `SimpleGraph):ident]))
/--
A variant of `aesop_graph` which does not fail if it is unable to solve the goal.
Use this only for exploration! Nonterminal Aesop is even worse than nonterminal `simp`.
-/
macro (name := aesop_graph_nonterminal) "aesop_graph_nonterminal" c:Aesop.tactic_clause* : tactic =>
`(tactic|
aesop $c*
(config := { introsTransparency? := some .default, warnOnNonterminal := false })
(rule_sets := [$(Lean.mkIdent `SimpleGraph):ident]))
open Finset Function
universe u v w
/-- A simple graph is an irreflexive symmetric relation `Adj` on a vertex type `V`.
The relation describes which pairs of vertices are adjacent.
There is exactly one edge for every pair of adjacent vertices;
see `SimpleGraph.edgeSet` for the corresponding edge set.
-/
@[ext, aesop safe constructors (rule_sets := [SimpleGraph])]
structure SimpleGraph (V : Type u) where
/-- The adjacency relation of a simple graph. -/
Adj : V → V → Prop
symm : Symmetric Adj := by aesop_graph
loopless : Irreflexive Adj := by aesop_graph
initialize_simps_projections SimpleGraph (Adj → adj)
/-- Constructor for simple graphs using a symmetric irreflexive boolean function. -/
@[simps]
def SimpleGraph.mk' {V : Type u} :
{adj : V → V → Bool // (∀ x y, adj x y = adj y x) ∧ (∀ x, ¬ adj x x)} ↪ SimpleGraph V where
toFun x := ⟨fun v w ↦ x.1 v w, fun v w ↦ by simp [x.2.1], fun v ↦ by simp [x.2.2]⟩
inj' := by
rintro ⟨adj, _⟩ ⟨adj', _⟩
simp only [mk.injEq, Subtype.mk.injEq]
intro h
funext v w
simpa [Bool.coe_iff_coe] using congr_fun₂ h v w
/-- We can enumerate simple graphs by enumerating all functions `V → V → Bool`
and filtering on whether they are symmetric and irreflexive. -/
instance {V : Type u} [Fintype V] [DecidableEq V] : Fintype (SimpleGraph V) where
elems := Finset.univ.map SimpleGraph.mk'
complete := by
classical
rintro ⟨Adj, hs, hi⟩
simp only [mem_map, mem_univ, true_and, Subtype.exists, Bool.not_eq_true]
refine ⟨fun v w ↦ Adj v w, ⟨?_, ?_⟩, ?_⟩
· simp [hs.iff]
· intro v; simp [hi v]
· ext
simp
/-- There are finitely many simple graphs on a given finite type. -/
instance SimpleGraph.instFinite {V : Type u} [Finite V] : Finite (SimpleGraph V) :=
.of_injective SimpleGraph.Adj fun _ _ ↦ SimpleGraph.ext
/-- Construct the simple graph induced by the given relation. It
symmetrizes the relation and makes it irreflexive. -/
def SimpleGraph.fromRel {V : Type u} (r : V → V → Prop) : SimpleGraph V where
Adj a b := a ≠ b ∧ (r a b ∨ r b a)
symm := fun _ _ ⟨hn, hr⟩ => ⟨hn.symm, hr.symm⟩
loopless := fun _ ⟨hn, _⟩ => hn rfl
@[simp]
theorem SimpleGraph.fromRel_adj {V : Type u} (r : V → V → Prop) (v w : V) :
(SimpleGraph.fromRel r).Adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) :=
Iff.rfl
attribute [aesop safe (rule_sets := [SimpleGraph])] Ne.symm
attribute [aesop safe (rule_sets := [SimpleGraph])] Ne.irrefl
/-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices
adjacent. In `Mathlib`, this is usually referred to as `⊤`. -/
def completeGraph (V : Type u) : SimpleGraph V where Adj := Ne
/-- The graph with no edges on a given vertex type `V`. `Mathlib` prefers the notation `⊥`. -/
def emptyGraph (V : Type u) : SimpleGraph V where Adj _ _ := False
/-- Two vertices are adjacent in the complete bipartite graph on two vertex types
if and only if they are not from the same side.
Any bipartite graph may be regarded as a subgraph of one of these. -/
@[simps]
def completeBipartiteGraph (V W : Type*) : SimpleGraph (V ⊕ W) where
Adj v w := v.isLeft ∧ w.isRight ∨ v.isRight ∧ w.isLeft
symm v w := by cases v <;> cases w <;> simp
loopless v := by cases v <;> simp
namespace SimpleGraph
variable {ι : Sort*} {V : Type u} (G : SimpleGraph V) {a b c u v w : V} {e : Sym2 V}
@[simp]
protected theorem irrefl {v : V} : ¬G.Adj v v :=
G.loopless v
theorem adj_comm (u v : V) : G.Adj u v ↔ G.Adj v u :=
⟨fun x => G.symm x, fun x => G.symm x⟩
@[symm]
theorem adj_symm (h : G.Adj u v) : G.Adj v u :=
G.symm h
theorem Adj.symm {G : SimpleGraph V} {u v : V} (h : G.Adj u v) : G.Adj v u :=
G.symm h
theorem ne_of_adj (h : G.Adj a b) : a ≠ b := by
rintro rfl
exact G.irrefl h
protected theorem Adj.ne {G : SimpleGraph V} {a b : V} (h : G.Adj a b) : a ≠ b :=
G.ne_of_adj h
protected theorem Adj.ne' {G : SimpleGraph V} {a b : V} (h : G.Adj a b) : b ≠ a :=
h.ne.symm
theorem ne_of_adj_of_not_adj {v w x : V} (h : G.Adj v x) (hn : ¬G.Adj w x) : v ≠ w := fun h' =>
hn (h' ▸ h)
theorem adj_injective : Injective (Adj : SimpleGraph V → V → V → Prop) :=
fun _ _ => SimpleGraph.ext
@[simp]
theorem adj_inj {G H : SimpleGraph V} : G.Adj = H.Adj ↔ G = H :=
adj_injective.eq_iff
theorem adj_congr_of_sym2 {u v w x : V} (h : s(u, v) = s(w, x)) : G.Adj u v ↔ G.Adj w x := by
simp only [Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Prod.swap_prod_mk] at h
rcases h with hl | hr
· rw [hl.1, hl.2]
· rw [hr.1, hr.2, adj_comm]
section Order
/-- The relation that one `SimpleGraph` is a subgraph of another.
Note that this should be spelled `≤`. -/
def IsSubgraph (x y : SimpleGraph V) : Prop :=
∀ ⦃v w : V⦄, x.Adj v w → y.Adj v w
instance : LE (SimpleGraph V) :=
⟨IsSubgraph⟩
@[simp]
theorem isSubgraph_eq_le : (IsSubgraph : SimpleGraph V → SimpleGraph V → Prop) = (· ≤ ·) :=
rfl
/-- The supremum of two graphs `x ⊔ y` has edges where either `x` or `y` have edges. -/
instance : Max (SimpleGraph V) where
max x y :=
{ Adj := x.Adj ⊔ y.Adj
symm := fun v w h => by rwa [Pi.sup_apply, Pi.sup_apply, x.adj_comm, y.adj_comm] }
@[simp]
theorem sup_adj (x y : SimpleGraph V) (v w : V) : (x ⊔ y).Adj v w ↔ x.Adj v w ∨ y.Adj v w :=
Iff.rfl
/-- The infimum of two graphs `x ⊓ y` has edges where both `x` and `y` have edges. -/
instance : Min (SimpleGraph V) where
min x y :=
{ Adj := x.Adj ⊓ y.Adj
symm := fun v w h => by rwa [Pi.inf_apply, Pi.inf_apply, x.adj_comm, y.adj_comm] }
@[simp]
theorem inf_adj (x y : SimpleGraph V) (v w : V) : (x ⊓ y).Adj v w ↔ x.Adj v w ∧ y.Adj v w :=
Iff.rfl
/-- We define `Gᶜ` to be the `SimpleGraph V` such that no two adjacent vertices in `G`
are adjacent in the complement, and every nonadjacent pair of vertices is adjacent
(still ensuring that vertices are not adjacent to themselves). -/
instance hasCompl : HasCompl (SimpleGraph V) where
compl G :=
{ Adj := fun v w => v ≠ w ∧ ¬G.Adj v w
symm := fun v w ⟨hne, _⟩ => ⟨hne.symm, by rwa [adj_comm]⟩
loopless := fun _ ⟨hne, _⟩ => (hne rfl).elim }
@[simp]
theorem compl_adj (G : SimpleGraph V) (v w : V) : Gᶜ.Adj v w ↔ v ≠ w ∧ ¬G.Adj v w :=
Iff.rfl
/-- The difference of two graphs `x \ y` has the edges of `x` with the edges of `y` removed. -/
instance sdiff : SDiff (SimpleGraph V) where
sdiff x y :=
{ Adj := x.Adj \ y.Adj
symm := fun v w h => by change x.Adj w v ∧ ¬y.Adj w v; rwa [x.adj_comm, y.adj_comm] }
@[simp]
theorem sdiff_adj (x y : SimpleGraph V) (v w : V) : (x \ y).Adj v w ↔ x.Adj v w ∧ ¬y.Adj v w :=
Iff.rfl
instance supSet : SupSet (SimpleGraph V) where
sSup s :=
{ Adj := fun a b => ∃ G ∈ s, Adj G a b
symm := fun _ _ => Exists.imp fun _ => And.imp_right Adj.symm
loopless := by
rintro a ⟨G, _, ha⟩
exact ha.ne rfl }
instance infSet : InfSet (SimpleGraph V) where
sInf s :=
{ Adj := fun a b => (∀ ⦃G⦄, G ∈ s → Adj G a b) ∧ a ≠ b
symm := fun _ _ => And.imp (forall₂_imp fun _ _ => Adj.symm) Ne.symm
loopless := fun _ h => h.2 rfl }
@[simp]
theorem sSup_adj {s : Set (SimpleGraph V)} {a b : V} : (sSup s).Adj a b ↔ ∃ G ∈ s, Adj G a b :=
Iff.rfl
@[simp]
theorem sInf_adj {s : Set (SimpleGraph V)} : (sInf s).Adj a b ↔ (∀ G ∈ s, Adj G a b) ∧ a ≠ b :=
Iff.rfl
@[simp]
theorem iSup_adj {f : ι → SimpleGraph V} : (⨆ i, f i).Adj a b ↔ ∃ i, (f i).Adj a b := by simp [iSup]
@[simp]
theorem iInf_adj {f : ι → SimpleGraph V} : (⨅ i, f i).Adj a b ↔ (∀ i, (f i).Adj a b) ∧ a ≠ b := by
simp [iInf]
theorem sInf_adj_of_nonempty {s : Set (SimpleGraph V)} (hs : s.Nonempty) :
(sInf s).Adj a b ↔ ∀ G ∈ s, Adj G a b :=
sInf_adj.trans <|
and_iff_left_of_imp <| by
obtain ⟨G, hG⟩ := hs
exact fun h => (h _ hG).ne
theorem iInf_adj_of_nonempty [Nonempty ι] {f : ι → SimpleGraph V} :
(⨅ i, f i).Adj a b ↔ ∀ i, (f i).Adj a b := by
rw [iInf, sInf_adj_of_nonempty (Set.range_nonempty _), Set.forall_mem_range]
/-- For graphs `G`, `H`, `G ≤ H` iff `∀ a b, G.Adj a b → H.Adj a b`. -/
instance distribLattice : DistribLattice (SimpleGraph V) :=
{ show DistribLattice (SimpleGraph V) from
adj_injective.distribLattice _ (fun _ _ => rfl) fun _ _ => rfl with
le := fun G H => ∀ ⦃a b⦄, G.Adj a b → H.Adj a b }
instance completeAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra (SimpleGraph V) :=
{ SimpleGraph.distribLattice with
le := (· ≤ ·)
sup := (· ⊔ ·)
inf := (· ⊓ ·)
compl := HasCompl.compl
sdiff := (· \ ·)
top := completeGraph V
bot := emptyGraph V
le_top := fun x _ _ h => x.ne_of_adj h
bot_le := fun _ _ _ h => h.elim
sdiff_eq := fun x y => by
ext v w
refine ⟨fun h => ⟨h.1, ⟨?_, h.2⟩⟩, fun h => ⟨h.1, h.2.2⟩⟩
rintro rfl
exact x.irrefl h.1
inf_compl_le_bot := fun _ _ _ h => False.elim <| h.2.2 h.1
top_le_sup_compl := fun G v w hvw => by
by_cases h : G.Adj v w
· exact Or.inl h
· exact Or.inr ⟨hvw, h⟩
sSup := sSup
le_sSup := fun _ G hG _ _ hab => ⟨G, hG, hab⟩
sSup_le := fun s G hG a b => by
rintro ⟨H, hH, hab⟩
exact hG _ hH hab
sInf := sInf
sInf_le := fun _ _ hG _ _ hab => hab.1 hG
le_sInf := fun _ _ hG _ _ hab => ⟨fun _ hH => hG _ hH hab, hab.ne⟩
iInf_iSup_eq := fun f => by ext; simp [Classical.skolem] }
@[simp]
theorem top_adj (v w : V) : (⊤ : SimpleGraph V).Adj v w ↔ v ≠ w :=
Iff.rfl
@[simp]
theorem bot_adj (v w : V) : (⊥ : SimpleGraph V).Adj v w ↔ False :=
Iff.rfl
@[simp]
theorem completeGraph_eq_top (V : Type u) : completeGraph V = ⊤ :=
rfl
@[simp]
theorem emptyGraph_eq_bot (V : Type u) : emptyGraph V = ⊥ :=
rfl
@[simps]
instance (V : Type u) : Inhabited (SimpleGraph V) :=
⟨⊥⟩
instance [Subsingleton V] : Unique (SimpleGraph V) where
default := ⊥
uniq G := by ext a b; have := Subsingleton.elim a b; simp [this]
instance [Nontrivial V] : Nontrivial (SimpleGraph V) :=
⟨⟨⊥, ⊤, fun h ↦ not_subsingleton V ⟨by simpa only [← adj_inj, funext_iff, bot_adj,
top_adj, ne_eq, eq_iff_iff, false_iff, not_not] using h⟩⟩⟩
section Decidable
variable (V) (H : SimpleGraph V) [DecidableRel G.Adj] [DecidableRel H.Adj]
instance Bot.adjDecidable : DecidableRel (⊥ : SimpleGraph V).Adj :=
inferInstanceAs <| DecidableRel fun _ _ => False
instance Sup.adjDecidable : DecidableRel (G ⊔ H).Adj :=
inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∨ H.Adj v w
instance Inf.adjDecidable : DecidableRel (G ⊓ H).Adj :=
inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∧ H.Adj v w
instance Sdiff.adjDecidable : DecidableRel (G \ H).Adj :=
inferInstanceAs <| DecidableRel fun v w => G.Adj v w ∧ ¬H.Adj v w
variable [DecidableEq V]
instance Top.adjDecidable : DecidableRel (⊤ : SimpleGraph V).Adj :=
inferInstanceAs <| DecidableRel fun v w => v ≠ w
instance Compl.adjDecidable : DecidableRel (Gᶜ.Adj) :=
inferInstanceAs <| DecidableRel fun v w => v ≠ w ∧ ¬G.Adj v w
end Decidable
end Order
/-- `G.support` is the set of vertices that form edges in `G`. -/
def support : Set V :=
Rel.dom G.Adj
theorem mem_support {v : V} : v ∈ G.support ↔ ∃ w, G.Adj v w :=
Iff.rfl
theorem support_mono {G G' : SimpleGraph V} (h : G ≤ G') : G.support ⊆ G'.support :=
Rel.dom_mono h
/-- `G.neighborSet v` is the set of vertices adjacent to `v` in `G`. -/
def neighborSet (v : V) : Set V := {w | G.Adj v w}
instance neighborSet.memDecidable (v : V) [DecidableRel G.Adj] :
DecidablePred (· ∈ G.neighborSet v) :=
inferInstanceAs <| DecidablePred (Adj G v)
lemma neighborSet_subset_support (v : V) : G.neighborSet v ⊆ G.support :=
fun _ hadj ↦ ⟨v, hadj.symm⟩
section EdgeSet
variable {G₁ G₂ : SimpleGraph V}
/-- The edges of G consist of the unordered pairs of vertices related by
`G.Adj`. This is the order embedding; for the edge set of a particular graph, see
`SimpleGraph.edgeSet`.
The way `edgeSet` is defined is such that `mem_edgeSet` is proved by `Iff.rfl`.
(That is, `s(v, w) ∈ G.edgeSet` is definitionally equal to `G.Adj v w`.)
-/
-- Porting note: We need a separate definition so that dot notation works.
def edgeSetEmbedding (V : Type*) : SimpleGraph V ↪o Set (Sym2 V) :=
OrderEmbedding.ofMapLEIff (fun G => Sym2.fromRel G.symm) fun _ _ =>
⟨fun h a b => @h s(a, b), fun h e => Sym2.ind @h e⟩
/-- `G.edgeSet` is the edge set for `G`.
This is an abbreviation for `edgeSetEmbedding G` that permits dot notation. -/
abbrev edgeSet (G : SimpleGraph V) : Set (Sym2 V) := edgeSetEmbedding V G
@[simp]
theorem mem_edgeSet : s(v, w) ∈ G.edgeSet ↔ G.Adj v w :=
Iff.rfl
theorem not_isDiag_of_mem_edgeSet : e ∈ edgeSet G → ¬e.IsDiag :=
Sym2.ind (fun _ _ => Adj.ne) e
theorem edgeSet_inj : G₁.edgeSet = G₂.edgeSet ↔ G₁ = G₂ := (edgeSetEmbedding V).eq_iff_eq
@[simp]
theorem edgeSet_subset_edgeSet : edgeSet G₁ ⊆ edgeSet G₂ ↔ G₁ ≤ G₂ :=
(edgeSetEmbedding V).le_iff_le
@[simp]
theorem edgeSet_ssubset_edgeSet : edgeSet G₁ ⊂ edgeSet G₂ ↔ G₁ < G₂ :=
(edgeSetEmbedding V).lt_iff_lt
theorem edgeSet_injective : Injective (edgeSet : SimpleGraph V → Set (Sym2 V)) :=
(edgeSetEmbedding V).injective
alias ⟨_, edgeSet_mono⟩ := edgeSet_subset_edgeSet
alias ⟨_, edgeSet_strict_mono⟩ := edgeSet_ssubset_edgeSet
attribute [mono] edgeSet_mono edgeSet_strict_mono
variable (G₁ G₂)
@[simp]
theorem edgeSet_bot : (⊥ : SimpleGraph V).edgeSet = ∅ :=
Sym2.fromRel_bot
@[simp]
theorem edgeSet_top : (⊤ : SimpleGraph V).edgeSet = {e | ¬e.IsDiag} :=
Sym2.fromRel_ne
@[simp]
theorem edgeSet_subset_setOf_not_isDiag : G.edgeSet ⊆ {e | ¬e.IsDiag} :=
fun _ h => (Sym2.fromRel_irreflexive (sym := G.symm)).mp G.loopless h
@[simp]
theorem edgeSet_sup : (G₁ ⊔ G₂).edgeSet = G₁.edgeSet ∪ G₂.edgeSet := by
ext ⟨x, y⟩
rfl
@[simp]
theorem edgeSet_inf : (G₁ ⊓ G₂).edgeSet = G₁.edgeSet ∩ G₂.edgeSet := by
ext ⟨x, y⟩
rfl
@[simp]
theorem edgeSet_sdiff : (G₁ \ G₂).edgeSet = G₁.edgeSet \ G₂.edgeSet := by
ext ⟨x, y⟩
rfl
variable {G G₁ G₂}
@[simp] lemma disjoint_edgeSet : Disjoint G₁.edgeSet G₂.edgeSet ↔ Disjoint G₁ G₂ := by
rw [Set.disjoint_iff, disjoint_iff_inf_le, ← edgeSet_inf, ← edgeSet_bot, ← Set.le_iff_subset,
OrderEmbedding.le_iff_le]
@[simp] lemma edgeSet_eq_empty : G.edgeSet = ∅ ↔ G = ⊥ := by rw [← edgeSet_bot, edgeSet_inj]
@[simp] lemma edgeSet_nonempty : G.edgeSet.Nonempty ↔ G ≠ ⊥ := by
rw [Set.nonempty_iff_ne_empty, edgeSet_eq_empty.ne]
/-- This lemma, combined with `edgeSet_sdiff` and `edgeSet_from_edgeSet`,
allows proving `(G \ from_edgeSet s).edge_set = G.edgeSet \ s` by `simp`. -/
@[simp]
theorem edgeSet_sdiff_sdiff_isDiag (G : SimpleGraph V) (s : Set (Sym2 V)) :
G.edgeSet \ (s \ { e | e.IsDiag }) = G.edgeSet \ s := by
ext e
simp only [Set.mem_diff, Set.mem_setOf_eq, not_and, not_not, and_congr_right_iff]
intro h
simp only [G.not_isDiag_of_mem_edgeSet h, imp_false]
/-- Two vertices are adjacent iff there is an edge between them. The
condition `v ≠ w` ensures they are different endpoints of the edge,
which is necessary since when `v = w` the existential
`∃ (e ∈ G.edgeSet), v ∈ e ∧ w ∈ e` is satisfied by every edge
incident to `v`. -/
theorem adj_iff_exists_edge {v w : V} : G.Adj v w ↔ v ≠ w ∧ ∃ e ∈ G.edgeSet, v ∈ e ∧ w ∈ e := by
refine ⟨fun _ => ⟨G.ne_of_adj ‹_›, s(v, w), by simpa⟩, ?_⟩
rintro ⟨hne, e, he, hv⟩
rw [Sym2.mem_and_mem_iff hne] at hv
subst e
rwa [mem_edgeSet] at he
theorem adj_iff_exists_edge_coe : G.Adj a b ↔ ∃ e : G.edgeSet, e.val = s(a, b) := by
simp only [mem_edgeSet, exists_prop, SetCoe.exists, exists_eq_right, Subtype.coe_mk]
variable (G G₁ G₂)
theorem edge_other_ne {e : Sym2 V} (he : e ∈ G.edgeSet) {v : V} (h : v ∈ e) :
Sym2.Mem.other h ≠ v := by
rw [← Sym2.other_spec h, Sym2.eq_swap] at he
exact G.ne_of_adj he
instance decidableMemEdgeSet [DecidableRel G.Adj] : DecidablePred (· ∈ G.edgeSet) :=
Sym2.fromRel.decidablePred G.symm
instance fintypeEdgeSet [Fintype (Sym2 V)] [DecidableRel G.Adj] : Fintype G.edgeSet :=
Subtype.fintype _
instance fintypeEdgeSetBot : Fintype (⊥ : SimpleGraph V).edgeSet := by
rw [edgeSet_bot]
infer_instance
instance fintypeEdgeSetSup [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] :
Fintype (G₁ ⊔ G₂).edgeSet := by
rw [edgeSet_sup]
infer_instance
instance fintypeEdgeSetInf [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] :
Fintype (G₁ ⊓ G₂).edgeSet := by
rw [edgeSet_inf]
exact Set.fintypeInter _ _
instance fintypeEdgeSetSdiff [DecidableEq V] [Fintype G₁.edgeSet] [Fintype G₂.edgeSet] :
Fintype (G₁ \ G₂).edgeSet := by
rw [edgeSet_sdiff]
exact Set.fintypeDiff _ _
end EdgeSet
section FromEdgeSet
variable (s : Set (Sym2 V))
/-- `fromEdgeSet` constructs a `SimpleGraph` from a set of edges, without loops. -/
def fromEdgeSet : SimpleGraph V where
Adj := Sym2.ToRel s ⊓ Ne
symm _ _ h := ⟨Sym2.toRel_symmetric s h.1, h.2.symm⟩
@[simp]
theorem fromEdgeSet_adj : (fromEdgeSet s).Adj v w ↔ s(v, w) ∈ s ∧ v ≠ w :=
Iff.rfl
-- Note: we need to make sure `fromEdgeSet_adj` and this lemma are confluent.
-- In particular, both yield `s(u, v) ∈ (fromEdgeSet s).edgeSet` ==> `s(v, w) ∈ s ∧ v ≠ w`.
@[simp]
theorem edgeSet_fromEdgeSet : (fromEdgeSet s).edgeSet = s \ { e | e.IsDiag } := by
ext e
exact Sym2.ind (by simp) e
@[simp]
theorem fromEdgeSet_edgeSet : fromEdgeSet G.edgeSet = G := by
ext v w
exact ⟨fun h => h.1, fun h => ⟨h, G.ne_of_adj h⟩⟩
@[simp]
theorem fromEdgeSet_empty : fromEdgeSet (∅ : Set (Sym2 V)) = ⊥ := by
ext v w
simp only [fromEdgeSet_adj, Set.mem_empty_iff_false, false_and, bot_adj]
@[simp]
theorem fromEdgeSet_univ : fromEdgeSet (Set.univ : Set (Sym2 V)) = ⊤ := by
ext v w
simp only [fromEdgeSet_adj, Set.mem_univ, true_and, top_adj]
@[simp]
theorem fromEdgeSet_inter (s t : Set (Sym2 V)) :
fromEdgeSet (s ∩ t) = fromEdgeSet s ⊓ fromEdgeSet t := by
ext v w
simp only [fromEdgeSet_adj, Set.mem_inter_iff, Ne, inf_adj]
tauto
@[simp]
theorem fromEdgeSet_union (s t : Set (Sym2 V)) :
fromEdgeSet (s ∪ t) = fromEdgeSet s ⊔ fromEdgeSet t := by
ext v w
simp [Set.mem_union, or_and_right]
@[simp]
theorem fromEdgeSet_sdiff (s t : Set (Sym2 V)) :
fromEdgeSet (s \ t) = fromEdgeSet s \ fromEdgeSet t := by
ext v w
constructor <;> simp +contextual
@[gcongr, mono]
theorem fromEdgeSet_mono {s t : Set (Sym2 V)} (h : s ⊆ t) : fromEdgeSet s ≤ fromEdgeSet t := by
rintro v w
simp +contextual only [fromEdgeSet_adj, Ne, not_false_iff,
and_true, and_imp]
exact fun vws _ => h vws
@[simp] lemma disjoint_fromEdgeSet : Disjoint G (fromEdgeSet s) ↔ Disjoint G.edgeSet s := by
conv_rhs => rw [← Set.diff_union_inter s {e : Sym2 V | e.IsDiag}]
rw [← disjoint_edgeSet, edgeSet_fromEdgeSet, Set.disjoint_union_right, and_iff_left]
exact Set.disjoint_left.2 fun e he he' ↦ not_isDiag_of_mem_edgeSet _ he he'.2
@[simp] lemma fromEdgeSet_disjoint : Disjoint (fromEdgeSet s) G ↔ Disjoint s G.edgeSet := by
rw [disjoint_comm, disjoint_fromEdgeSet, disjoint_comm]
instance [DecidableEq V] [Fintype s] : Fintype (fromEdgeSet s).edgeSet := by
rw [edgeSet_fromEdgeSet s]
infer_instance
end FromEdgeSet
/-! ### Incidence set -/
/-- Set of edges incident to a given vertex, aka incidence set. -/
def incidenceSet (v : V) : Set (Sym2 V) :=
{ e ∈ G.edgeSet | v ∈ e }
theorem incidenceSet_subset (v : V) : G.incidenceSet v ⊆ G.edgeSet := fun _ h => h.1
theorem mk'_mem_incidenceSet_iff : s(b, c) ∈ G.incidenceSet a ↔ G.Adj b c ∧ (a = b ∨ a = c) :=
and_congr_right' Sym2.mem_iff
theorem mk'_mem_incidenceSet_left_iff : s(a, b) ∈ G.incidenceSet a ↔ G.Adj a b :=
and_iff_left <| Sym2.mem_mk_left _ _
theorem mk'_mem_incidenceSet_right_iff : s(a, b) ∈ G.incidenceSet b ↔ G.Adj a b :=
and_iff_left <| Sym2.mem_mk_right _ _
theorem edge_mem_incidenceSet_iff {e : G.edgeSet} : ↑e ∈ G.incidenceSet a ↔ a ∈ (e : Sym2 V) :=
and_iff_right e.2
theorem incidenceSet_inter_incidenceSet_subset (h : a ≠ b) :
G.incidenceSet a ∩ G.incidenceSet b ⊆ {s(a, b)} := fun _e he =>
(Sym2.mem_and_mem_iff h).1 ⟨he.1.2, he.2.2⟩
theorem incidenceSet_inter_incidenceSet_of_adj (h : G.Adj a b) :
G.incidenceSet a ∩ G.incidenceSet b = {s(a, b)} := by
refine (G.incidenceSet_inter_incidenceSet_subset <| h.ne).antisymm ?_
rintro _ (rfl : _ = s(a, b))
exact ⟨G.mk'_mem_incidenceSet_left_iff.2 h, G.mk'_mem_incidenceSet_right_iff.2 h⟩
theorem adj_of_mem_incidenceSet (h : a ≠ b) (ha : e ∈ G.incidenceSet a)
(hb : e ∈ G.incidenceSet b) : G.Adj a b := by
rwa [← mk'_mem_incidenceSet_left_iff, ←
Set.mem_singleton_iff.1 <| G.incidenceSet_inter_incidenceSet_subset h ⟨ha, hb⟩]
theorem incidenceSet_inter_incidenceSet_of_not_adj (h : ¬G.Adj a b) (hn : a ≠ b) :
G.incidenceSet a ∩ G.incidenceSet b = ∅ := by
simp_rw [Set.eq_empty_iff_forall_not_mem, Set.mem_inter_iff, not_and]
intro u ha hb
exact h (G.adj_of_mem_incidenceSet hn ha hb)
instance decidableMemIncidenceSet [DecidableEq V] [DecidableRel G.Adj] (v : V) :
DecidablePred (· ∈ G.incidenceSet v) :=
inferInstanceAs <| DecidablePred fun e => e ∈ G.edgeSet ∧ v ∈ e
@[simp]
theorem mem_neighborSet (v w : V) : w ∈ G.neighborSet v ↔ G.Adj v w :=
Iff.rfl
lemma not_mem_neighborSet_self : a ∉ G.neighborSet a := by simp
@[simp]
theorem mem_incidenceSet (v w : V) : s(v, w) ∈ G.incidenceSet v ↔ G.Adj v w := by
simp [incidenceSet]
theorem mem_incidence_iff_neighbor {v w : V} :
s(v, w) ∈ G.incidenceSet v ↔ w ∈ G.neighborSet v := by
simp only [mem_incidenceSet, mem_neighborSet]
theorem adj_incidenceSet_inter {v : V} {e : Sym2 V} (he : e ∈ G.edgeSet) (h : v ∈ e) :
G.incidenceSet v ∩ G.incidenceSet (Sym2.Mem.other h) = {e} := by
ext e'
simp only [incidenceSet, Set.mem_sep_iff, Set.mem_inter_iff, Set.mem_singleton_iff]
refine ⟨fun h' => ?_, ?_⟩
· rw [← Sym2.other_spec h]
exact (Sym2.mem_and_mem_iff (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩
· rintro rfl
exact ⟨⟨he, h⟩, he, Sym2.other_mem _⟩
theorem compl_neighborSet_disjoint (G : SimpleGraph V) (v : V) :
Disjoint (G.neighborSet v) (Gᶜ.neighborSet v) := by
rw [Set.disjoint_iff]
rintro w ⟨h, h'⟩
rw [mem_neighborSet, compl_adj] at h'
exact h'.2 h
theorem neighborSet_union_compl_neighborSet_eq (G : SimpleGraph V) (v : V) :
G.neighborSet v ∪ Gᶜ.neighborSet v = {v}ᶜ := by
ext w
have h := @ne_of_adj _ G
simp_rw [Set.mem_union, mem_neighborSet, compl_adj, Set.mem_compl_iff, Set.mem_singleton_iff]
tauto
theorem card_neighborSet_union_compl_neighborSet [Fintype V] (G : SimpleGraph V) (v : V)
[Fintype (G.neighborSet v ∪ Gᶜ.neighborSet v : Set V)] :
#(G.neighborSet v ∪ Gᶜ.neighborSet v).toFinset = Fintype.card V - 1 := by
classical simp_rw [neighborSet_union_compl_neighborSet_eq, Set.toFinset_compl,
Finset.card_compl, Set.toFinset_card, Set.card_singleton]
theorem neighborSet_compl (G : SimpleGraph V) (v : V) :
Gᶜ.neighborSet v = (G.neighborSet v)ᶜ \ {v} := by
ext w
simp [and_comm, eq_comm]
/-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the
intersection of the neighbor sets of `v` and `w`. -/
def commonNeighbors (v w : V) : Set V :=
G.neighborSet v ∩ G.neighborSet w
theorem commonNeighbors_eq (v w : V) : G.commonNeighbors v w = G.neighborSet v ∩ G.neighborSet w :=
rfl
theorem mem_commonNeighbors {u v w : V} : u ∈ G.commonNeighbors v w ↔ G.Adj v u ∧ G.Adj w u :=
Iff.rfl
theorem commonNeighbors_symm (v w : V) : G.commonNeighbors v w = G.commonNeighbors w v :=
Set.inter_comm _ _
theorem not_mem_commonNeighbors_left (v w : V) : v ∉ G.commonNeighbors v w := fun h =>
ne_of_adj G h.1 rfl
theorem not_mem_commonNeighbors_right (v w : V) : w ∉ G.commonNeighbors v w := fun h =>
ne_of_adj G h.2 rfl
theorem commonNeighbors_subset_neighborSet_left (v w : V) :
G.commonNeighbors v w ⊆ G.neighborSet v :=
Set.inter_subset_left
theorem commonNeighbors_subset_neighborSet_right (v w : V) :
G.commonNeighbors v w ⊆ G.neighborSet w :=
Set.inter_subset_right
instance decidableMemCommonNeighbors [DecidableRel G.Adj] (v w : V) :
DecidablePred (· ∈ G.commonNeighbors v w) :=
inferInstanceAs <| DecidablePred fun u => u ∈ G.neighborSet v ∧ u ∈ G.neighborSet w
theorem commonNeighbors_top_eq {v w : V} :
(⊤ : SimpleGraph V).commonNeighbors v w = Set.univ \ {v, w} := by
ext u
simp [commonNeighbors, eq_comm, not_or]
section Incidence
variable [DecidableEq V]
/-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/
def otherVertexOfIncident {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) : V :=
Sym2.Mem.other' h.2
theorem edge_other_incident_set {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) :
e ∈ G.incidenceSet (G.otherVertexOfIncident h) := by
use h.1
simp [otherVertexOfIncident, Sym2.other_mem']
theorem incidence_other_prop {v : V} {e : Sym2 V} (h : e ∈ G.incidenceSet v) :
G.otherVertexOfIncident h ∈ G.neighborSet v := by
obtain ⟨he, hv⟩ := h
rwa [← Sym2.other_spec' hv, mem_edgeSet] at he
-- Porting note: as a simp lemma this does not apply even to itself
theorem incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighborSet v) :
G.otherVertexOfIncident (G.mem_incidence_iff_neighbor.mpr h) = w :=
Sym2.congr_right.mp (Sym2.other_spec' (G.mem_incidence_iff_neighbor.mpr h).right)
/-- There is an equivalence between the set of edges incident to a given
vertex and the set of vertices adjacent to the vertex. -/
@[simps]
def incidenceSetEquivNeighborSet (v : V) : G.incidenceSet v ≃ G.neighborSet v where
toFun e := ⟨G.otherVertexOfIncident e.2, G.incidence_other_prop e.2⟩
invFun w := ⟨s(v, w.1), G.mem_incidence_iff_neighbor.mpr w.2⟩
left_inv x := by simp [otherVertexOfIncident]
right_inv := fun ⟨w, hw⟩ => by
simp only [mem_neighborSet, Subtype.mk.injEq]
exact incidence_other_neighbor_edge _ hw
end Incidence
end SimpleGraph
| Mathlib/Combinatorics/SimpleGraph/Basic.lean | 938 | 938 | |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Sean Leather
-/
import Batteries.Data.List.Perm
import Mathlib.Data.List.Pairwise
import Mathlib.Data.List.Nodup
import Mathlib.Data.List.Lookmap
import Mathlib.Data.Sigma.Basic
/-!
# Utilities for lists of sigmas
This file includes several ways of interacting with `List (Sigma β)`, treated as a key-value store.
If `α : Type*` and `β : α → Type*`, then we regard `s : Sigma β` as having key `s.1 : α` and value
`s.2 : β s.1`. Hence, `List (Sigma β)` behaves like a key-value store.
## Main Definitions
- `List.keys` extracts the list of keys.
- `List.NodupKeys` determines if the store has duplicate keys.
- `List.lookup`/`lookup_all` accesses the value(s) of a particular key.
- `List.kreplace` replaces the first value with a given key by a given value.
- `List.kerase` removes a value.
- `List.kinsert` inserts a value.
- `List.kunion` computes the union of two stores.
- `List.kextract` returns a value with a given key and the rest of the values.
-/
universe u u' v v'
namespace List
variable {α : Type u} {α' : Type u'} {β : α → Type v} {β' : α' → Type v'} {l l₁ l₂ : List (Sigma β)}
/-! ### `keys` -/
/-- List of keys from a list of key-value pairs -/
def keys : List (Sigma β) → List α :=
map Sigma.fst
@[simp]
theorem keys_nil : @keys α β [] = [] :=
rfl
@[simp]
theorem keys_cons {s} {l : List (Sigma β)} : (s :: l).keys = s.1 :: l.keys :=
rfl
theorem mem_keys_of_mem {s : Sigma β} {l : List (Sigma β)} : s ∈ l → s.1 ∈ l.keys :=
mem_map_of_mem
theorem exists_of_mem_keys {a} {l : List (Sigma β)} (h : a ∈ l.keys) :
∃ b : β a, Sigma.mk a b ∈ l :=
let ⟨⟨_, b'⟩, m, e⟩ := exists_of_mem_map h
Eq.recOn e (Exists.intro b' m)
theorem mem_keys {a} {l : List (Sigma β)} : a ∈ l.keys ↔ ∃ b : β a, Sigma.mk a b ∈ l :=
⟨exists_of_mem_keys, fun ⟨_, h⟩ => mem_keys_of_mem h⟩
theorem not_mem_keys {a} {l : List (Sigma β)} : a ∉ l.keys ↔ ∀ b : β a, Sigma.mk a b ∉ l :=
(not_congr mem_keys).trans not_exists
theorem ne_key {a} {l : List (Sigma β)} : a ∉ l.keys ↔ ∀ s : Sigma β, s ∈ l → a ≠ s.1 :=
Iff.intro (fun h₁ s h₂ e => absurd (mem_keys_of_mem h₂) (by rwa [e] at h₁)) fun f h₁ =>
let ⟨_, h₂⟩ := exists_of_mem_keys h₁
f _ h₂ rfl
@[deprecated (since := "2025-04-27")]
alias not_eq_key := ne_key
/-! ### `NodupKeys` -/
/-- Determines whether the store uses a key several times. -/
def NodupKeys (l : List (Sigma β)) : Prop :=
l.keys.Nodup
theorem nodupKeys_iff_pairwise {l} : NodupKeys l ↔ Pairwise (fun s s' : Sigma β => s.1 ≠ s'.1) l :=
pairwise_map
theorem NodupKeys.pairwise_ne {l} (h : NodupKeys l) :
Pairwise (fun s s' : Sigma β => s.1 ≠ s'.1) l :=
nodupKeys_iff_pairwise.1 h
@[simp]
theorem nodupKeys_nil : @NodupKeys α β [] :=
Pairwise.nil
@[simp]
theorem nodupKeys_cons {s : Sigma β} {l : List (Sigma β)} :
NodupKeys (s :: l) ↔ s.1 ∉ l.keys ∧ NodupKeys l := by simp [keys, NodupKeys]
theorem not_mem_keys_of_nodupKeys_cons {s : Sigma β} {l : List (Sigma β)} (h : NodupKeys (s :: l)) :
s.1 ∉ l.keys :=
(nodupKeys_cons.1 h).1
theorem nodupKeys_of_nodupKeys_cons {s : Sigma β} {l : List (Sigma β)} (h : NodupKeys (s :: l)) :
NodupKeys l :=
(nodupKeys_cons.1 h).2
theorem NodupKeys.eq_of_fst_eq {l : List (Sigma β)} (nd : NodupKeys l) {s s' : Sigma β} (h : s ∈ l)
(h' : s' ∈ l) : s.1 = s'.1 → s = s' :=
@Pairwise.forall_of_forall _ (fun s s' : Sigma β => s.1 = s'.1 → s = s') _
(fun _ _ H h => (H h.symm).symm) (fun _ _ _ => rfl)
((nodupKeys_iff_pairwise.1 nd).imp fun h h' => (h h').elim) _ h _ h'
theorem NodupKeys.eq_of_mk_mem {a : α} {b b' : β a} {l : List (Sigma β)} (nd : NodupKeys l)
(h : Sigma.mk a b ∈ l) (h' : Sigma.mk a b' ∈ l) : b = b' := by
cases nd.eq_of_fst_eq h h' rfl; rfl
theorem nodupKeys_singleton (s : Sigma β) : NodupKeys [s] :=
nodup_singleton _
theorem NodupKeys.sublist {l₁ l₂ : List (Sigma β)} (h : l₁ <+ l₂) : NodupKeys l₂ → NodupKeys l₁ :=
Nodup.sublist <| h.map _
protected theorem NodupKeys.nodup {l : List (Sigma β)} : NodupKeys l → Nodup l :=
Nodup.of_map _
theorem perm_nodupKeys {l₁ l₂ : List (Sigma β)} (h : l₁ ~ l₂) : NodupKeys l₁ ↔ NodupKeys l₂ :=
(h.map _).nodup_iff
theorem nodupKeys_flatten {L : List (List (Sigma β))} :
NodupKeys (flatten L) ↔ (∀ l ∈ L, NodupKeys l) ∧ Pairwise Disjoint (L.map keys) := by
rw [nodupKeys_iff_pairwise, pairwise_flatten, pairwise_map]
refine and_congr (forall₂_congr fun l _ => by simp [nodupKeys_iff_pairwise]) ?_
apply iff_of_eq; congr! with (l₁ l₂)
simp [keys, disjoint_iff_ne, Sigma.forall]
theorem nodup_zipIdx_map_snd (l : List α) : (l.zipIdx.map Prod.snd).Nodup := by
simp [List.nodup_range']
@[deprecated (since := "2025-01-28")] alias nodup_enum_map_fst := nodup_zipIdx_map_snd
theorem mem_ext {l₀ l₁ : List (Sigma β)} (nd₀ : l₀.Nodup) (nd₁ : l₁.Nodup)
(h : ∀ x, x ∈ l₀ ↔ x ∈ l₁) : l₀ ~ l₁ :=
(perm_ext_iff_of_nodup nd₀ nd₁).2 h
variable [DecidableEq α] [DecidableEq α']
/-! ### `dlookup` -/
/-- `dlookup a l` is the first value in `l` corresponding to the key `a`,
or `none` if no such element exists. -/
def dlookup (a : α) : List (Sigma β) → Option (β a)
| [] => none
| ⟨a', b⟩ :: l => if h : a' = a then some (Eq.recOn h b) else dlookup a l
@[simp]
theorem dlookup_nil (a : α) : dlookup a [] = @none (β a) :=
rfl
@[simp]
theorem dlookup_cons_eq (l) (a : α) (b : β a) : dlookup a (⟨a, b⟩ :: l) = some b :=
dif_pos rfl
@[simp]
theorem dlookup_cons_ne (l) {a} : ∀ s : Sigma β, a ≠ s.1 → dlookup a (s :: l) = dlookup a l
| ⟨_, _⟩, h => dif_neg h.symm
theorem dlookup_isSome {a : α} : ∀ {l : List (Sigma β)}, (dlookup a l).isSome ↔ a ∈ l.keys
| [] => by simp
| ⟨a', b⟩ :: l => by
by_cases h : a = a'
· subst a'
simp
· simp [h, dlookup_isSome]
theorem dlookup_eq_none {a : α} {l : List (Sigma β)} : dlookup a l = none ↔ a ∉ l.keys := by
simp [← dlookup_isSome, Option.isNone_iff_eq_none]
theorem of_mem_dlookup {a : α} {b : β a} :
∀ {l : List (Sigma β)}, b ∈ dlookup a l → Sigma.mk a b ∈ l
| ⟨a', b'⟩ :: l, H => by
by_cases h : a = a'
· subst a'
simp? at H says simp only [dlookup_cons_eq, Option.mem_def, Option.some.injEq] at H
simp [H]
· simp only [ne_eq, h, not_false_iff, dlookup_cons_ne] at H
simp [of_mem_dlookup H]
theorem mem_dlookup {a} {b : β a} {l : List (Sigma β)} (nd : l.NodupKeys) (h : Sigma.mk a b ∈ l) :
b ∈ dlookup a l := by
obtain ⟨b', h'⟩ := Option.isSome_iff_exists.mp (dlookup_isSome.mpr (mem_keys_of_mem h))
cases nd.eq_of_mk_mem h (of_mem_dlookup h')
exact h'
theorem map_dlookup_eq_find (a : α) :
∀ l : List (Sigma β), (dlookup a l).map (Sigma.mk a) = find? (fun s => a = s.1) l
| [] => rfl
| ⟨a', b'⟩ :: l => by
by_cases h : a = a'
· subst a'
simp
· simpa [h] using map_dlookup_eq_find a l
theorem mem_dlookup_iff {a : α} {b : β a} {l : List (Sigma β)} (nd : l.NodupKeys) :
b ∈ dlookup a l ↔ Sigma.mk a b ∈ l :=
⟨of_mem_dlookup, mem_dlookup nd⟩
theorem perm_dlookup (a : α) {l₁ l₂ : List (Sigma β)} (nd₁ : l₁.NodupKeys) (nd₂ : l₂.NodupKeys)
(p : l₁ ~ l₂) : dlookup a l₁ = dlookup a l₂ := by
ext b; simp only [mem_dlookup_iff nd₁, mem_dlookup_iff nd₂]; exact p.mem_iff
theorem lookup_ext {l₀ l₁ : List (Sigma β)} (nd₀ : l₀.NodupKeys) (nd₁ : l₁.NodupKeys)
(h : ∀ x y, y ∈ l₀.dlookup x ↔ y ∈ l₁.dlookup x) : l₀ ~ l₁ :=
mem_ext nd₀.nodup nd₁.nodup fun ⟨a, b⟩ => by
rw [← mem_dlookup_iff, ← mem_dlookup_iff, h] <;> assumption
theorem dlookup_map (l : List (Sigma β))
{f : α → α'} (hf : Function.Injective f) (g : ∀ a, β a → β' (f a)) (a : α) :
(l.map fun x => ⟨f x.1, g _ x.2⟩).dlookup (f a) = (l.dlookup a).map (g a) := by
induction' l with b l IH
· rw [map_nil, dlookup_nil, dlookup_nil, Option.map_none']
· rw [map_cons]
obtain rfl | h := eq_or_ne a b.1
· rw [dlookup_cons_eq, dlookup_cons_eq, Option.map_some']
· rw [dlookup_cons_ne _ _ h, dlookup_cons_ne _ _ (fun he => h <| hf he), IH]
theorem dlookup_map₁ {β : Type v} (l : List (Σ _ : α, β))
{f : α → α'} (hf : Function.Injective f) (a : α) :
(l.map fun x => ⟨f x.1, x.2⟩ : List (Σ _ : α', β)).dlookup (f a) = l.dlookup a := by
rw [dlookup_map (β' := fun _ => β) l hf (fun _ x => x) a, Option.map_id']
theorem dlookup_map₂ {γ δ : α → Type*} {l : List (Σ a, γ a)} {f : ∀ a, γ a → δ a} (a : α) :
(l.map fun x => ⟨x.1, f _ x.2⟩ : List (Σ a, δ a)).dlookup a = (l.dlookup a).map (f a) :=
dlookup_map l Function.injective_id _ _
/-! ### `lookupAll` -/
/-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/
def lookupAll (a : α) : List (Sigma β) → List (β a)
| [] => []
| ⟨a', b⟩ :: l => if h : a' = a then Eq.recOn h b :: lookupAll a l else lookupAll a l
@[simp]
theorem lookupAll_nil (a : α) : lookupAll a [] = @nil (β a) :=
rfl
@[simp]
theorem lookupAll_cons_eq (l) (a : α) (b : β a) : lookupAll a (⟨a, b⟩ :: l) = b :: lookupAll a l :=
dif_pos rfl
@[simp]
theorem lookupAll_cons_ne (l) {a} : ∀ s : Sigma β, a ≠ s.1 → lookupAll a (s :: l) = lookupAll a l
| ⟨_, _⟩, h => dif_neg h.symm
theorem lookupAll_eq_nil {a : α} :
∀ {l : List (Sigma β)}, lookupAll a l = [] ↔ ∀ b : β a, Sigma.mk a b ∉ l
| [] => by simp
| ⟨a', b⟩ :: l => by
by_cases h : a = a'
· subst a'
simp only [lookupAll_cons_eq, mem_cons, Sigma.mk.inj_iff, heq_eq_eq, true_and, not_or,
false_iff, not_forall, not_and, not_not, reduceCtorEq]
use b
simp
· simp [h, lookupAll_eq_nil]
theorem head?_lookupAll (a : α) : ∀ l : List (Sigma β), head? (lookupAll a l) = dlookup a l
| [] => by simp
| ⟨a', b⟩ :: l => by
by_cases h : a = a'
· subst h; simp
· rw [lookupAll_cons_ne, dlookup_cons_ne, head?_lookupAll a l] <;> assumption
theorem mem_lookupAll {a : α} {b : β a} :
∀ {l : List (Sigma β)}, b ∈ lookupAll a l ↔ Sigma.mk a b ∈ l
| [] => by simp
| ⟨a', b'⟩ :: l => by
by_cases h : a = a'
· subst h
simp [*, mem_lookupAll]
· simp [*, mem_lookupAll]
theorem lookupAll_sublist (a : α) : ∀ l : List (Sigma β), (lookupAll a l).map (Sigma.mk a) <+ l
| [] => by simp
| ⟨a', b'⟩ :: l => by
by_cases h : a = a'
· subst h
simp only [ne_eq, not_true, lookupAll_cons_eq, List.map]
exact (lookupAll_sublist a l).cons₂ _
· simp only [ne_eq, h, not_false_iff, lookupAll_cons_ne]
exact (lookupAll_sublist a l).cons _
theorem lookupAll_length_le_one (a : α) {l : List (Sigma β)} (h : l.NodupKeys) :
length (lookupAll a l) ≤ 1 := by
have := Nodup.sublist ((lookupAll_sublist a l).map _) h
rw [map_map] at this
rwa [← nodup_replicate, ← map_const]
theorem lookupAll_eq_dlookup (a : α) {l : List (Sigma β)} (h : l.NodupKeys) :
lookupAll a l = (dlookup a l).toList := by
rw [← head?_lookupAll]
have h1 := lookupAll_length_le_one a h; revert h1
rcases lookupAll a l with (_ | ⟨b, _ | ⟨c, l⟩⟩) <;> intro h1 <;> try rfl
exact absurd h1 (by simp)
theorem lookupAll_nodup (a : α) {l : List (Sigma β)} (h : l.NodupKeys) : (lookupAll a l).Nodup := by
(rw [lookupAll_eq_dlookup a h]; apply Option.toList_nodup)
theorem perm_lookupAll (a : α) {l₁ l₂ : List (Sigma β)} (nd₁ : l₁.NodupKeys) (nd₂ : l₂.NodupKeys)
(p : l₁ ~ l₂) : lookupAll a l₁ = lookupAll a l₂ := by
simp [lookupAll_eq_dlookup, nd₁, nd₂, perm_dlookup a nd₁ nd₂ p]
theorem dlookup_append (l₁ l₂ : List (Sigma β)) (a : α) :
(l₁ ++ l₂).dlookup a = (l₁.dlookup a).or (l₂.dlookup a) := by
induction l₁ with
| nil => rfl
| cons x l₁ IH =>
rw [cons_append]
obtain rfl | hb := Decidable.eq_or_ne a x.1
· rw [dlookup_cons_eq, dlookup_cons_eq, Option.or]
· rw [dlookup_cons_ne _ _ hb, dlookup_cons_ne _ _ hb, IH]
/-! ### `kreplace` -/
/-- Replaces the first value with key `a` by `b`. -/
def kreplace (a : α) (b : β a) : List (Sigma β) → List (Sigma β) :=
lookmap fun s => if a = s.1 then some ⟨a, b⟩ else none
theorem kreplace_of_forall_not (a : α) (b : β a) {l : List (Sigma β)}
(H : ∀ b : β a, Sigma.mk a b ∉ l) : kreplace a b l = l :=
lookmap_of_forall_not _ <| by
rintro ⟨a', b'⟩ h; dsimp; split_ifs
· subst a'
exact H _ h
· rfl
theorem kreplace_self {a : α} {b : β a} {l : List (Sigma β)} (nd : NodupKeys l)
(h : Sigma.mk a b ∈ l) : kreplace a b l = l := by
refine (lookmap_congr ?_).trans (lookmap_id' (Option.guard fun (s : Sigma β) => a = s.1) ?_ _)
· rintro ⟨a', b'⟩ h'
dsimp [Option.guard]
split_ifs
· subst a'
simp [nd.eq_of_mk_mem h h']
· rfl
· rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
dsimp [Option.guard]
split_ifs
· simp
· rintro ⟨⟩
theorem keys_kreplace (a : α) (b : β a) : ∀ l : List (Sigma β), (kreplace a b l).keys = l.keys :=
lookmap_map_eq _ _ <| by
rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩
dsimp
split_ifs with h <;> simp +contextual [h]
theorem kreplace_nodupKeys (a : α) (b : β a) {l : List (Sigma β)} :
(kreplace a b l).NodupKeys ↔ l.NodupKeys := by simp [NodupKeys, keys_kreplace]
theorem Perm.kreplace {a : α} {b : β a} {l₁ l₂ : List (Sigma β)} (nd : l₁.NodupKeys) :
l₁ ~ l₂ → kreplace a b l₁ ~ kreplace a b l₂ :=
perm_lookmap _ <| by
refine nd.pairwise_ne.imp ?_
intro x y h z h₁ w h₂
split_ifs at h₁ h₂ with h_2 h_1 <;> cases h₁ <;> cases h₂
exact (h (h_2.symm.trans h_1)).elim
/-! ### `kerase` -/
/-- Remove the first pair with the key `a`. -/
def kerase (a : α) : List (Sigma β) → List (Sigma β) :=
eraseP fun s => a = s.1
@[simp]
theorem kerase_nil {a} : @kerase _ β _ a [] = [] :=
rfl
@[simp]
theorem kerase_cons_eq {a} {s : Sigma β} {l : List (Sigma β)} (h : a = s.1) :
kerase a (s :: l) = l := by simp [kerase, h]
@[simp]
theorem kerase_cons_ne {a} {s : Sigma β} {l : List (Sigma β)} (h : a ≠ s.1) :
kerase a (s :: l) = s :: kerase a l := by simp [kerase, h]
@[simp]
theorem kerase_of_not_mem_keys {a} {l : List (Sigma β)} (h : a ∉ l.keys) : kerase a l = l := by
induction l with
| nil => rfl
| cons _ _ ih => simp [not_or] at h; simp [h.1, ih h.2]
theorem kerase_sublist (a : α) (l : List (Sigma β)) : kerase a l <+ l :=
eraseP_sublist
theorem kerase_keys_subset (a) (l : List (Sigma β)) : (kerase a l).keys ⊆ l.keys :=
((kerase_sublist a l).map _).subset
theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : List (Sigma β)} :
a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys :=
@kerase_keys_subset _ _ _ _ _ _
theorem exists_of_kerase {a : α} {l : List (Sigma β)} (h : a ∈ l.keys) :
∃ (b : β a) (l₁ l₂ : List (Sigma β)),
a ∉ l₁.keys ∧ l = l₁ ++ ⟨a, b⟩ :: l₂ ∧ kerase a l = l₁ ++ l₂ := by
induction l with
| nil => cases h
| cons hd tl ih =>
by_cases e : a = hd.1
· subst e
exact ⟨hd.2, [], tl, by simp, by cases hd; rfl, by simp⟩
· simp only [keys_cons, mem_cons] at h
rcases h with h | h
· exact absurd h e
rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩
exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁, by (rw [h₂]; rfl), by
simp [e, h₃]⟩
@[simp]
theorem mem_keys_kerase_of_ne {a₁ a₂} {l : List (Sigma β)} (h : a₁ ≠ a₂) :
a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys :=
(Iff.intro mem_keys_of_mem_keys_kerase) fun p =>
if q : a₂ ∈ l.keys then
match l, kerase a₂ l, exists_of_kerase q, p with
| _, _, ⟨_, _, _, _, rfl, rfl⟩, p => by simpa [keys, h] using p
else by simp [q, p]
theorem keys_kerase {a} {l : List (Sigma β)} : (kerase a l).keys = l.keys.erase a := by
rw [keys, kerase, erase_eq_eraseP, eraseP_map, Function.comp_def]
congr
theorem kerase_kerase {a a'} {l : List (Sigma β)} :
(kerase a' l).kerase a = (kerase a l).kerase a' := by
by_cases h : a = a'
· subst a'; rfl
induction' l with x xs
· rfl
· by_cases a' = x.1
· subst a'
simp [kerase_cons_ne h, kerase_cons_eq rfl]
by_cases h' : a = x.1
· subst a
simp [kerase_cons_eq rfl, kerase_cons_ne (Ne.symm h)]
· simp [kerase_cons_ne, *]
theorem NodupKeys.kerase (a : α) : NodupKeys l → (kerase a l).NodupKeys :=
NodupKeys.sublist <| kerase_sublist _ _
theorem Perm.kerase {a : α} {l₁ l₂ : List (Sigma β)} (nd : l₁.NodupKeys) :
l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ := by
apply Perm.eraseP
apply (nodupKeys_iff_pairwise.1 nd).imp
intros; simp_all
@[simp]
theorem not_mem_keys_kerase (a) {l : List (Sigma β)} (nd : l.NodupKeys) :
a ∉ (kerase a l).keys := by
induction l with
| nil => simp
| cons hd tl ih =>
simp? at nd says simp only [nodupKeys_cons] at nd
by_cases h : a = hd.1
· subst h
simp [nd.1]
· simp [h, ih nd.2]
@[simp]
theorem dlookup_kerase (a) {l : List (Sigma β)} (nd : l.NodupKeys) :
dlookup a (kerase a l) = none :=
dlookup_eq_none.mpr (not_mem_keys_kerase a nd)
@[simp]
theorem dlookup_kerase_ne {a a'} {l : List (Sigma β)} (h : a ≠ a') :
dlookup a (kerase a' l) = dlookup a l := by
induction l with
| nil => rfl
| cons hd tl ih =>
obtain ⟨ah, bh⟩ := hd
by_cases h₁ : a = ah <;> by_cases h₂ : a' = ah
· substs h₁ h₂
cases Ne.irrefl h
· subst h₁
simp [h₂]
· subst h₂
simp [h]
· simp [h₁, h₂, ih]
theorem kerase_append_left {a} :
∀ {l₁ l₂ : List (Sigma β)}, a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂
| [], _, h => by cases h
| s :: l₁, l₂, h₁ => by
if h₂ : a = s.1 then simp [h₂]
else simp at h₁; rcases h₁ with h₁ | h₁ <;>
[exact absurd h₁ h₂; simp [h₂, kerase_append_left h₁]]
theorem kerase_append_right {a} :
∀ {l₁ l₂ : List (Sigma β)}, a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂
| [], _, _ => rfl
| _ :: l₁, l₂, h => by
simp only [keys_cons, mem_cons, not_or] at h
simp [h.1, kerase_append_right h.2]
theorem kerase_comm (a₁ a₂) (l : List (Sigma β)) :
kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) :=
if h : a₁ = a₂ then by simp [h]
else
if ha₁ : a₁ ∈ l.keys then
if ha₂ : a₂ ∈ l.keys then
match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with
| _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, _ =>
if h' : a₂ ∈ l₁.keys then by
simp [kerase_append_left h',
kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)]
else by
simp [kerase_append_right h', kerase_append_right a₁_nin_l₁,
@kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (Ne.symm h)]
else by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂]
else by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁]
theorem sizeOf_kerase [SizeOf (Sigma β)] (x : α)
(xs : List (Sigma β)) : SizeOf.sizeOf (List.kerase x xs) ≤ SizeOf.sizeOf xs := by
simp only [SizeOf.sizeOf, _sizeOf_1]
induction' xs with y ys
· simp
· by_cases x = y.1 <;> simp [*]
/-! ### `kinsert` -/
/-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/
def kinsert (a : α) (b : β a) (l : List (Sigma β)) : List (Sigma β) :=
⟨a, b⟩ :: kerase a l
@[simp]
theorem kinsert_def {a} {b : β a} {l : List (Sigma β)} : kinsert a b l = ⟨a, b⟩ :: kerase a l :=
rfl
theorem mem_keys_kinsert {a a'} {b' : β a'} {l : List (Sigma β)} :
a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys := by by_cases h : a = a' <;> simp [h]
theorem kinsert_nodupKeys (a) (b : β a) {l : List (Sigma β)} (nd : l.NodupKeys) :
(kinsert a b l).NodupKeys :=
nodupKeys_cons.mpr ⟨not_mem_keys_kerase a nd, nd.kerase a⟩
theorem Perm.kinsert {a} {b : β a} {l₁ l₂ : List (Sigma β)} (nd₁ : l₁.NodupKeys) (p : l₁ ~ l₂) :
kinsert a b l₁ ~ kinsert a b l₂ :=
(p.kerase nd₁).cons _
theorem dlookup_kinsert {a} {b : β a} (l : List (Sigma β)) :
dlookup a (kinsert a b l) = some b := by
simp only [kinsert, dlookup_cons_eq]
theorem dlookup_kinsert_ne {a a'} {b' : β a'} {l : List (Sigma β)} (h : a ≠ a') :
dlookup a (kinsert a' b' l) = dlookup a l := by simp [h]
/-! ### `kextract` -/
/-- Finds the first entry with a given key `a` and returns its value (as an `Option` because there
might be no entry with key `a`) alongside with the rest of the entries. -/
def kextract (a : α) : List (Sigma β) → Option (β a) × List (Sigma β)
| [] => (none, [])
| s :: l =>
if h : s.1 = a then (some (Eq.recOn h s.2), l)
else
let (b', l') := kextract a l
(b', s :: l')
@[simp]
theorem kextract_eq_dlookup_kerase (a : α) :
∀ l : List (Sigma β), kextract a l = (dlookup a l, kerase a l)
| [] => rfl
| ⟨a', b⟩ :: l => by
simp only [kextract]; dsimp; split_ifs with h
· subst a'
simp [kerase]
· simp [kextract, Ne.symm h, kextract_eq_dlookup_kerase a l, kerase]
/-! ### `dedupKeys` -/
/-- Remove entries with duplicate keys from `l : List (Sigma β)`. -/
def dedupKeys : List (Sigma β) → List (Sigma β) :=
List.foldr (fun x => kinsert x.1 x.2) []
theorem dedupKeys_cons {x : Sigma β} (l : List (Sigma β)) :
dedupKeys (x :: l) = kinsert x.1 x.2 (dedupKeys l) :=
rfl
theorem nodupKeys_dedupKeys (l : List (Sigma β)) : NodupKeys (dedupKeys l) := by
dsimp [dedupKeys]
generalize hl : nil = l'
have : NodupKeys l' := by
rw [← hl]
apply nodup_nil
clear hl
induction' l with x xs l_ih
· apply this
· cases x
simp only [foldr_cons, kinsert_def, nodupKeys_cons, ne_eq, not_true]
constructor
· simp only [keys_kerase]
apply l_ih.not_mem_erase
· exact l_ih.kerase _
theorem dlookup_dedupKeys (a : α) (l : List (Sigma β)) : dlookup a (dedupKeys l) = dlookup a l := by
induction' l with l_hd _ l_ih
· rfl
obtain ⟨a', b⟩ := l_hd
by_cases h : a = a'
· subst a'
rw [dedupKeys_cons, dlookup_kinsert, dlookup_cons_eq]
· rw [dedupKeys_cons, dlookup_kinsert_ne h, l_ih, dlookup_cons_ne]
exact h
theorem sizeOf_dedupKeys [SizeOf (Sigma β)]
(xs : List (Sigma β)) : SizeOf.sizeOf (dedupKeys xs) ≤ SizeOf.sizeOf xs := by
simp only [SizeOf.sizeOf, _sizeOf_1]
induction' xs with x xs
· simp [dedupKeys]
· simp only [dedupKeys_cons, kinsert_def, Nat.add_le_add_iff_left, Sigma.eta]
trans
· apply sizeOf_kerase
· assumption
/-! ### `kunion` -/
/-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the
first matching pair in l₂ is erased. -/
def kunion : List (Sigma β) → List (Sigma β) → List (Sigma β)
| [], l₂ => l₂
| s :: l₁, l₂ => s :: kunion l₁ (kerase s.1 l₂)
@[simp]
theorem nil_kunion {l : List (Sigma β)} : kunion [] l = l :=
rfl
@[simp]
theorem kunion_nil : ∀ {l : List (Sigma β)}, kunion l [] = l
| [] => rfl
| _ :: l => by rw [kunion, kerase_nil, kunion_nil]
@[simp]
theorem kunion_cons {s} {l₁ l₂ : List (Sigma β)} :
kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) :=
rfl
@[simp]
theorem mem_keys_kunion {a} {l₁ l₂ : List (Sigma β)} :
a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys := by
induction l₁ generalizing l₂ with
| nil => simp
| cons s l₁ ih => by_cases h : a = s.1 <;> [simp [h]; simp [h, ih]]
@[simp]
theorem kunion_kerase {a} :
∀ {l₁ l₂ : List (Sigma β)}, kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂)
| [], _ => rfl
| s :: _, l => by by_cases h : a = s.1 <;> simp [h, kerase_comm a s.1 l, kunion_kerase]
theorem NodupKeys.kunion (nd₁ : l₁.NodupKeys) (nd₂ : l₂.NodupKeys) : (kunion l₁ l₂).NodupKeys := by
induction l₁ generalizing l₂ with
| nil => simp only [nil_kunion, nd₂]
| cons s l₁ ih =>
simp? at nd₁ says simp only [nodupKeys_cons] at nd₁
simp [not_or, nd₁.1, nd₂, ih nd₁.2 (nd₂.kerase s.1)]
theorem Perm.kunion_right {l₁ l₂ : List (Sigma β)} (p : l₁ ~ l₂) (l) :
| kunion l₁ l ~ kunion l₂ l := by
induction p generalizing l with
| nil => rfl
| cons hd _ ih =>
simp [ih (List.kerase _ _), Perm.cons]
| swap s₁ s₂ l => simp [kerase_comm, Perm.swap]
| trans _ _ ih₁₂ ih₂₃ => exact Perm.trans (ih₁₂ l) (ih₂₃ l)
theorem Perm.kunion_left :
| Mathlib/Data/List/Sigma.lean | 671 | 679 |
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kevin Kappelmann
-/
import Mathlib.Algebra.Order.Floor.Defs
import Mathlib.Algebra.Order.Floor.Ring
import Mathlib.Algebra.Order.Floor.Semiring
deprecated_module (since := "2025-04-13")
| Mathlib/Algebra/Order/Floor.lean | 243 | 245 | |
/-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import Mathlib.Algebra.CharP.Two
import Mathlib.Data.Nat.Cast.Field
import Mathlib.Data.Nat.Factorization.Basic
import Mathlib.Data.Nat.Factorization.Induction
import Mathlib.Data.Nat.Periodic
/-!
# Euler's totient function
This file defines [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function)
`Nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`.
We prove the divisor sum formula, namely that `n` equals `φ` summed over the divisors of `n`. See
`sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and
`totient_prime_pow`.
-/
assert_not_exists Algebra LinearMap
open Finset
namespace Nat
/-- Euler's totient function. This counts the number of naturals strictly less than `n` which are
coprime with `n`. -/
def totient (n : ℕ) : ℕ := #{a ∈ range n | n.Coprime a}
@[inherit_doc]
scoped notation "φ" => Nat.totient
@[simp]
theorem totient_zero : φ 0 = 0 :=
rfl
@[simp]
theorem totient_one : φ 1 = 1 := rfl
theorem totient_eq_card_coprime (n : ℕ) : φ n = #{a ∈ range n | n.Coprime a} := rfl
/-- A characterisation of `Nat.totient` that avoids `Finset`. -/
theorem totient_eq_card_lt_and_coprime (n : ℕ) : φ n = Nat.card { m | m < n ∧ n.Coprime m } := by
let e : { m | m < n ∧ n.Coprime m } ≃ {x ∈ range n | n.Coprime x} :=
{ toFun := fun m => ⟨m, by simpa only [Finset.mem_filter, Finset.mem_range] using m.property⟩
invFun := fun m => ⟨m, by simpa only [Finset.mem_filter, Finset.mem_range] using m.property⟩
left_inv := fun m => by simp only [Subtype.coe_mk, Subtype.coe_eta]
right_inv := fun m => by simp only [Subtype.coe_mk, Subtype.coe_eta] }
rw [totient_eq_card_coprime, card_congr e, card_eq_fintype_card, Fintype.card_coe]
theorem totient_le (n : ℕ) : φ n ≤ n :=
((range n).card_filter_le _).trans_eq (card_range n)
theorem totient_lt (n : ℕ) (hn : 1 < n) : φ n < n :=
(card_lt_card (filter_ssubset.2 ⟨0, by simp [hn.ne', pos_of_gt hn]⟩)).trans_eq (card_range n)
@[simp]
theorem totient_eq_zero : ∀ {n : ℕ}, φ n = 0 ↔ n = 0
| 0 => by decide
| n + 1 =>
suffices ∃ x < n + 1, (n + 1).gcd x = 1 by simpa [totient, filter_eq_empty_iff]
⟨1 % (n + 1), mod_lt _ n.succ_pos, by rw [gcd_comm, ← gcd_rec, gcd_one_right]⟩
@[simp] theorem totient_pos {n : ℕ} : 0 < φ n ↔ 0 < n := by simp [pos_iff_ne_zero]
instance neZero_totient {n : ℕ} [NeZero n] : NeZero n.totient :=
⟨(totient_pos.mpr <| NeZero.pos n).ne'⟩
theorem filter_coprime_Ico_eq_totient (a n : ℕ) :
#{x ∈ Ico n (n + a) | a.Coprime x} = totient a := by
rw [totient, filter_Ico_card_eq_of_periodic, count_eq_card_filter_range]
exact periodic_coprime a
theorem Ico_filter_coprime_le {a : ℕ} (k n : ℕ) (a_pos : 0 < a) :
#{x ∈ Ico k (k + n) | a.Coprime x} ≤ totient a * (n / a + 1) := by
conv_lhs => rw [← Nat.mod_add_div n a]
induction' n / a with i ih
· rw [← filter_coprime_Ico_eq_totient a k]
simp only [add_zero, mul_one, mul_zero, le_of_lt (mod_lt n a_pos), zero_add]
gcongr
exact le_of_lt (mod_lt n a_pos)
simp only [mul_succ]
simp_rw [← add_assoc] at ih ⊢
calc
#{x ∈ Ico k (k + n % a + a * i + a) | a.Coprime x}
≤ #{x ∈ Ico k (k + n % a + a * i) ∪
Ico (k + n % a + a * i) (k + n % a + a * i + a) | a.Coprime x} := by
gcongr
apply Ico_subset_Ico_union_Ico
_ ≤ #{x ∈ Ico k (k + n % a + a * i) | a.Coprime x} + a.totient := by
rw [filter_union, ← filter_coprime_Ico_eq_totient a (k + n % a + a * i)]
apply card_union_le
_ ≤ a.totient * i + a.totient + a.totient := add_le_add_right ih (totient a)
open ZMod
/-- Note this takes an explicit `Fintype ((ZMod n)ˣ)` argument to avoid trouble with instance
diamonds. -/
@[simp]
theorem _root_.ZMod.card_units_eq_totient (n : ℕ) [NeZero n] [Fintype (ZMod n)ˣ] :
Fintype.card (ZMod n)ˣ = φ n :=
calc
Fintype.card (ZMod n)ˣ = Fintype.card { x : ZMod n // x.val.Coprime n } :=
Fintype.card_congr ZMod.unitsEquivCoprime
_ = φ n := by
obtain ⟨m, rfl⟩ : ∃ m, n = m + 1 := exists_eq_succ_of_ne_zero NeZero.out
simp only [totient, Finset.card_eq_sum_ones, Fintype.card_subtype, Finset.sum_filter, ←
Fin.sum_univ_eq_sum_range, @Nat.coprime_comm (m + 1)]
rfl
theorem totient_even {n : ℕ} (hn : 2 < n) : Even n.totient := by
haveI : Fact (1 < n) := ⟨one_lt_two.trans hn⟩
haveI : NeZero n := NeZero.of_gt hn
suffices 2 = orderOf (-1 : (ZMod n)ˣ) by
rw [← ZMod.card_units_eq_totient, even_iff_two_dvd, this]
exact orderOf_dvd_card
rw [← orderOf_units, Units.coe_neg_one, orderOf_neg_one, ringChar.eq (ZMod n) n, if_neg hn.ne']
theorem totient_mul {m n : ℕ} (h : m.Coprime n) : φ (m * n) = φ m * φ n :=
if hmn0 : m * n = 0 then by
rcases Nat.mul_eq_zero.1 hmn0 with h | h <;>
simp only [totient_zero, mul_zero, zero_mul, h]
else by
haveI : NeZero (m * n) := ⟨hmn0⟩
haveI : NeZero m := ⟨left_ne_zero_of_mul hmn0⟩
haveI : NeZero n := ⟨right_ne_zero_of_mul hmn0⟩
simp only [← ZMod.card_units_eq_totient]
rw [Fintype.card_congr (Units.mapEquiv (ZMod.chineseRemainder h).toMulEquiv).toEquiv,
Fintype.card_congr (@MulEquiv.prodUnits (ZMod m) (ZMod n) _ _).toEquiv, Fintype.card_prod]
/-- For `d ∣ n`, the totient of `n/d` equals the number of values `k < n` such that `gcd n k = d` -/
theorem totient_div_of_dvd {n d : ℕ} (hnd : d ∣ n) :
φ (n / d) = #{k ∈ range n | n.gcd k = d} := by
rcases d.eq_zero_or_pos with (rfl | hd0); · simp [eq_zero_of_zero_dvd hnd]
rcases hnd with ⟨x, rfl⟩
rw [Nat.mul_div_cancel_left x hd0]
apply Finset.card_bij fun k _ => d * k
· simp only [mem_filter, mem_range, and_imp, Coprime]
refine fun a ha1 ha2 => ⟨(mul_lt_mul_left hd0).2 ha1, ?_⟩
rw [gcd_mul_left, ha2, mul_one]
· simp [hd0.ne']
· simp only [mem_filter, mem_range, exists_prop, and_imp]
refine fun b hb1 hb2 => ?_
have : d ∣ b := by
rw [← hb2]
| apply gcd_dvd_right
rcases this with ⟨q, rfl⟩
refine ⟨q, ⟨⟨(mul_lt_mul_left hd0).1 hb1, ?_⟩, rfl⟩⟩
rwa [gcd_mul_left, mul_right_eq_self_iff hd0] at hb2
theorem sum_totient (n : ℕ) : n.divisors.sum φ = n := by
rcases n.eq_zero_or_pos with (rfl | hn)
· simp
rw [← sum_div_divisors n φ]
have : n = ∑ d ∈ n.divisors, #{k ∈ range n | n.gcd k = d} := by
nth_rw 1 [← card_range n]
refine card_eq_sum_card_fiberwise fun x _ => mem_divisors.2 ⟨?_, hn.ne'⟩
apply gcd_dvd_left
nth_rw 3 [this]
exact sum_congr rfl fun x hx => totient_div_of_dvd (dvd_of_mem_divisors hx)
theorem sum_totient' (n : ℕ) : ∑ m ∈ range n.succ with m ∣ n, φ m = n := by
convert sum_totient _ using 1
| Mathlib/Data/Nat/Totient.lean | 148 | 165 |
/-
Copyright (c) 2022 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Stoll
-/
import Mathlib.Data.Int.Range
import Mathlib.Data.ZMod.Basic
import Mathlib.NumberTheory.MulChar.Basic
/-!
# Quadratic characters on ℤ/nℤ
This file defines some quadratic characters on the rings ℤ/4ℤ and ℤ/8ℤ.
We set them up to be of type `MulChar (ZMod n) ℤ`, where `n` is `4` or `8`.
## Tags
quadratic character, zmod
-/
/-!
### Quadratic characters mod 4 and 8
We define the primitive quadratic characters `χ₄`on `ZMod 4`
and `χ₈`, `χ₈'` on `ZMod 8`.
-/
namespace ZMod
section QuadCharModP
/-- Define the nontrivial quadratic character on `ZMod 4`, `χ₄`.
It corresponds to the extension `ℚ(√-1)/ℚ`. -/
@[simps]
def χ₄ : MulChar (ZMod 4) ℤ where
toFun a :=
match a with
| 0 | 2 => 0
| 1 => 1
| 3 => -1
map_one' := rfl
map_mul' := by decide
map_nonunit' := by decide
/-- `χ₄` takes values in `{0, 1, -1}` -/
theorem isQuadratic_χ₄ : χ₄.IsQuadratic := by
unfold MulChar.IsQuadratic
decide
/-- The value of `χ₄ n`, for `n : ℕ`, depends only on `n % 4`. -/
theorem χ₄_nat_mod_four (n : ℕ) : χ₄ n = χ₄ (n % 4 : ℕ) := by
rw [← ZMod.natCast_mod n 4]
/-- The value of `χ₄ n`, for `n : ℤ`, depends only on `n % 4`. -/
theorem χ₄_int_mod_four (n : ℤ) : χ₄ n = χ₄ (n % 4 : ℤ) := by
rw [← ZMod.intCast_mod n 4, Nat.cast_ofNat]
/-- An explicit description of `χ₄` on integers / naturals -/
theorem χ₄_int_eq_if_mod_four (n : ℤ) :
χ₄ n = if n % 2 = 0 then 0 else if n % 4 = 1 then 1 else -1 := by
have help : ∀ m : ℤ, 0 ≤ m → m < 4 → χ₄ m = if m % 2 = 0 then 0 else if m = 1 then 1 else -1 := by
decide
rw [← Int.emod_emod_of_dvd n (by omega : (2 : ℤ) ∣ 4), ← ZMod.intCast_mod n 4]
exact help (n % 4) (Int.emod_nonneg n (by omega)) (Int.emod_lt_abs n (by omega))
theorem χ₄_nat_eq_if_mod_four (n : ℕ) :
χ₄ n = if n % 2 = 0 then 0 else if n % 4 = 1 then 1 else -1 :=
mod_cast χ₄_int_eq_if_mod_four n
/-- Alternative description of `χ₄ n` for odd `n : ℕ` in terms of powers of `-1` -/
theorem χ₄_eq_neg_one_pow {n : ℕ} (hn : n % 2 = 1) : χ₄ n = (-1) ^ (n / 2) := by
rw [χ₄_nat_eq_if_mod_four]
simp only [hn, Nat.one_ne_zero, if_false]
nth_rewrite 3 [← Nat.div_add_mod n 4]
nth_rewrite 3 [show 4 = 2 * 2 by omega]
rw [mul_assoc, add_comm, Nat.add_mul_div_left _ _ zero_lt_two, pow_add, pow_mul,
neg_one_sq, one_pow, mul_one]
have help : ∀ m : ℕ, m < 4 → m % 2 = 1 → ite (m = 1) (1 : ℤ) (-1) = (-1) ^ (m / 2) := by decide
exact help _ (Nat.mod_lt n (by omega)) <| (Nat.mod_mod_of_dvd n (by omega : 2 ∣ 4)).trans hn
/-- If `n % 4 = 1`, then `χ₄ n = 1`. -/
theorem χ₄_nat_one_mod_four {n : ℕ} (hn : n % 4 = 1) : χ₄ n = 1 := by
rw [χ₄_nat_mod_four, hn]
rfl
/-- If `n % 4 = 3`, then `χ₄ n = -1`. -/
theorem χ₄_nat_three_mod_four {n : ℕ} (hn : n % 4 = 3) : χ₄ n = -1 := by
rw [χ₄_nat_mod_four, hn]
rfl
/-- If `n % 4 = 1`, then `χ₄ n = 1`. -/
theorem χ₄_int_one_mod_four {n : ℤ} (hn : n % 4 = 1) : χ₄ n = 1 := by
rw [χ₄_int_mod_four, hn]
rfl
/-- If `n % 4 = 3`, then `χ₄ n = -1`. -/
theorem χ₄_int_three_mod_four {n : ℤ} (hn : n % 4 = 3) : χ₄ n = -1 := by
rw [χ₄_int_mod_four, hn]
rfl
/-- If `n % 4 = 1`, then `(-1)^(n/2) = 1`. -/
theorem neg_one_pow_div_two_of_one_mod_four {n : ℕ} (hn : n % 4 = 1) : (-1 : ℤ) ^ (n / 2) = 1 :=
| χ₄_eq_neg_one_pow (Nat.odd_of_mod_four_eq_one hn) ▸ χ₄_nat_one_mod_four hn
/-- If `n % 4 = 3`, then `(-1)^(n/2) = -1`. -/
| Mathlib/NumberTheory/LegendreSymbol/ZModChar.lean | 106 | 108 |
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import Mathlib.Data.Countable.Defs
import Mathlib.Data.Nat.Factors
import Mathlib.Data.Nat.Prime.Infinite
import Mathlib.Data.Set.Finite.Lattice
/-!
# Prime numbers
This file contains some results about prime numbers which depend on finiteness of sets.
-/
open Finset
namespace Nat
variable {a b k m n p : ℕ}
/-- A version of `Nat.exists_infinite_primes` using the `Set.Infinite` predicate. -/
theorem infinite_setOf_prime : { p | Prime p }.Infinite :=
Set.infinite_of_not_bddAbove not_bddAbove_setOf_prime
instance Primes.infinite : Infinite Primes := infinite_setOf_prime.to_subtype
instance Primes.countable : Countable Primes := ⟨⟨coeNat.coe, coe_nat_injective⟩⟩
/-- The prime factors of a natural number as a finset. -/
def primeFactors (n : ℕ) : Finset ℕ := n.primeFactorsList.toFinset
@[simp] lemma toFinset_factors (n : ℕ) : n.primeFactorsList.toFinset = n.primeFactors := rfl
@[simp] lemma mem_primeFactors : p ∈ n.primeFactors ↔ p.Prime ∧ p ∣ n ∧ n ≠ 0 := by
simp_rw [← toFinset_factors, List.mem_toFinset, mem_primeFactorsList']
lemma mem_primeFactors_of_ne_zero (hn : n ≠ 0) : p ∈ n.primeFactors ↔ p.Prime ∧ p ∣ n := by
simp [hn]
lemma primeFactors_mono (hmn : m ∣ n) (hn : n ≠ 0) : primeFactors m ⊆ primeFactors n := by
simp only [subset_iff, mem_primeFactors, and_imp]
exact fun p hp hpm _ ↦ ⟨hp, hpm.trans hmn, hn⟩
lemma mem_primeFactors_iff_mem_primeFactorsList : p ∈ n.primeFactors ↔ p ∈ n.primeFactorsList := by
simp only [primeFactors, List.mem_toFinset]
lemma prime_of_mem_primeFactors (hp : p ∈ n.primeFactors) : p.Prime := (mem_primeFactors.1 hp).1
lemma dvd_of_mem_primeFactors (hp : p ∈ n.primeFactors) : p ∣ n := (mem_primeFactors.1 hp).2.1
lemma pos_of_mem_primeFactors (hp : p ∈ n.primeFactors) : 0 < p :=
(prime_of_mem_primeFactors hp).pos
lemma le_of_mem_primeFactors (h : p ∈ n.primeFactors) : p ≤ n :=
le_of_dvd (mem_primeFactors.1 h).2.2.bot_lt <| dvd_of_mem_primeFactors h
@[simp] lemma primeFactors_zero : primeFactors 0 = ∅ := by
ext
simp
@[simp] lemma primeFactors_one : primeFactors 1 = ∅ := by
ext
simpa using Prime.ne_one
@[simp] lemma primeFactors_eq_empty : n.primeFactors = ∅ ↔ n = 0 ∨ n = 1 := by
constructor
· contrapose!
rintro hn
obtain ⟨p, hp, hpn⟩ := exists_prime_and_dvd hn.2
exact Nonempty.ne_empty <| ⟨_, mem_primeFactors.2 ⟨hp, hpn, hn.1⟩⟩
· rintro (rfl | rfl) <;> simp
@[simp]
lemma nonempty_primeFactors {n : ℕ} : n.primeFactors.Nonempty ↔ 1 < n := by
rw [← not_iff_not, Finset.not_nonempty_iff_eq_empty, primeFactors_eq_empty, not_lt,
Nat.le_one_iff_eq_zero_or_eq_one]
@[simp] protected lemma Prime.primeFactors (hp : p.Prime) : p.primeFactors = {p} := by
simp [Nat.primeFactors, primeFactorsList_prime hp]
|
lemma primeFactors_mul (ha : a ≠ 0) (hb : b ≠ 0) :
| Mathlib/Data/Nat/PrimeFin.lean | 80 | 81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.