filename
stringlengths 5
42
| content
stringlengths 15
319k
|
|---|---|
Basic.lean
|
/-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import Mathlib.RingTheory.FiniteStability
import Mathlib.RingTheory.Ideal.Quotient.Nilpotent
import Mathlib.RingTheory.Kaehler.Basic
import Mathlib.RingTheory.Localization.Away.AdjoinRoot
/-!
# Unramified morphisms
An `R`-algebra `A` is formally unramified if `Ω[A⁄R]` is trivial.
This is equivalent to the standard definition "for every `R`-algebra,
every square-zero ideal `I : Ideal B` and `f : A →ₐ[R] B ⧸ I`, there exists
at most one lift `A →ₐ[R] B`".
It is unramified if it is formally unramified and of finite type.
Note that there are multiple definitions in the literature. The definition we give is equivalent to
the one in the Stacks Project https://stacks.math.columbia.edu/tag/00US. Note that in EGA unramified
is defined as formally unramified and of finite presentation.
We show that the property extends onto nilpotent ideals, and that it is stable
under `R`-algebra homomorphisms and compositions.
We show that unramified is stable under algebra isomorphisms, composition and
localization at an element.
-/
-- Porting note: added to make the syntax work below.
open scoped TensorProduct
universe u v w
namespace Algebra
section
variable (R : Type v) (A : Type u) [CommRing R] [CommRing A] [Algebra R A]
/--
An `R`-algebra `A` is formally unramified if `Ω[A⁄R]` is trivial.
This is equivalent to "for every `R`-algebra, every square-zero ideal
`I : Ideal B` and `f : A →ₐ[R] B ⧸ I`, there exists at most one lift `A →ₐ[R] B`".
See `Algebra.FormallyUnramified.iff_comp_injective`. -/
@[mk_iff, stacks 00UM]
class FormallyUnramified : Prop where
subsingleton_kaehlerDifferential : Subsingleton Ω[A⁄R]
attribute [instance] FormallyUnramified.subsingleton_kaehlerDifferential
end
namespace FormallyUnramified
section
variable {R : Type v} [CommRing R]
variable {A : Type u} [CommRing A] [Algebra R A]
variable {B : Type w} [CommRing B] [Algebra R B] (I : Ideal B)
theorem comp_injective [FormallyUnramified R A] (hI : I ^ 2 = ⊥) :
Function.Injective ((Ideal.Quotient.mkₐ R I).comp : (A →ₐ[R] B) → A →ₐ[R] B ⧸ I) := by
intro f₁ f₂ e
letI := f₁.toRingHom.toAlgebra
haveI := IsScalarTower.of_algebraMap_eq' f₁.comp_algebraMap.symm
have :=
((KaehlerDifferential.linearMapEquivDerivation R A).toEquiv.trans
(derivationToSquareZeroEquivLift I hI)).surjective.subsingleton
exact Subtype.ext_iff.mp (@Subsingleton.elim _ this ⟨f₁, rfl⟩ ⟨f₂, e.symm⟩)
theorem iff_comp_injective :
FormallyUnramified R A ↔
∀ ⦃B : Type u⦄ [CommRing B],
∀ [Algebra R B] (I : Ideal B) (_ : I ^ 2 = ⊥),
Function.Injective ((Ideal.Quotient.mkₐ R I).comp : (A →ₐ[R] B) → A →ₐ[R] B ⧸ I) := by
constructor
· intros; exact comp_injective _ ‹_›
· intro H
constructor
rw [← not_nontrivial_iff_subsingleton]
intro h
obtain ⟨f₁, f₂, e⟩ := (KaehlerDifferential.endEquiv R A).injective.nontrivial
apply e
ext1
refine H
(RingHom.ker (TensorProduct.lmul' R (S := A)).kerSquareLift.toRingHom) ?_ ?_
· rw [AlgHom.ker_kerSquareLift]
exact Ideal.cotangentIdeal_square _
· ext x
apply RingHom.kerLift_injective (TensorProduct.lmul' R (S := A)).kerSquareLift.toRingHom
simpa using DFunLike.congr_fun (f₁.2.trans f₂.2.symm) x
theorem lift_unique
[FormallyUnramified R A] (I : Ideal B) (hI : IsNilpotent I) (g₁ g₂ : A →ₐ[R] B)
(h : (Ideal.Quotient.mkₐ R I).comp g₁ = (Ideal.Quotient.mkₐ R I).comp g₂) : g₁ = g₂ := by
revert g₁ g₂
change Function.Injective (Ideal.Quotient.mkₐ R I).comp
revert ‹Algebra R B›
apply Ideal.IsNilpotent.induction_on (S := B) I hI
· intro B _ I hI _; exact FormallyUnramified.comp_injective I hI
· intro B _ I J hIJ h₁ h₂ _ g₁ g₂ e
apply h₁
apply h₂
ext x
replace e := AlgHom.congr_fun e x
dsimp only [AlgHom.comp_apply, Ideal.Quotient.mkₐ_eq_mk] at e ⊢
rwa [Ideal.Quotient.eq, ← map_sub, Ideal.mem_quotient_iff_mem hIJ, ← Ideal.Quotient.eq]
theorem ext [FormallyUnramified R A] (hI : IsNilpotent I) {g₁ g₂ : A →ₐ[R] B}
(H : ∀ x, Ideal.Quotient.mk I (g₁ x) = Ideal.Quotient.mk I (g₂ x)) : g₁ = g₂ :=
FormallyUnramified.lift_unique I hI g₁ g₂ (AlgHom.ext H)
theorem lift_unique_of_ringHom [FormallyUnramified R A] {C : Type*} [Ring C]
(f : B →+* C) (hf : IsNilpotent <| RingHom.ker f) (g₁ g₂ : A →ₐ[R] B)
(h : f.comp ↑g₁ = f.comp (g₂ : A →+* B)) : g₁ = g₂ :=
FormallyUnramified.lift_unique _ hf _ _
(by
ext x
have := RingHom.congr_fun h x
simpa only [Ideal.Quotient.eq, Function.comp_apply, AlgHom.coe_comp, Ideal.Quotient.mkₐ_eq_mk,
RingHom.mem_ker, map_sub, sub_eq_zero])
theorem ext' [FormallyUnramified R A] {C : Type*} [Ring C] (f : B →+* C)
(hf : IsNilpotent <| RingHom.ker f) (g₁ g₂ : A →ₐ[R] B) (h : ∀ x, f (g₁ x) = f (g₂ x)) :
g₁ = g₂ :=
FormallyUnramified.lift_unique_of_ringHom f hf g₁ g₂ (RingHom.ext h)
theorem lift_unique' [FormallyUnramified R A] {C : Type*} [Ring C]
[Algebra R C] (f : B →ₐ[R] C) (hf : IsNilpotent <| RingHom.ker (f : B →+* C))
(g₁ g₂ : A →ₐ[R] B) (h : f.comp g₁ = f.comp g₂) : g₁ = g₂ :=
FormallyUnramified.ext' _ hf g₁ g₂ (AlgHom.congr_fun h)
theorem ext_of_iInf [FormallyUnramified R A] (hI : ⨅ i, I ^ i = ⊥) {g₁ g₂ : A →ₐ[R] B}
(H : ∀ x, Ideal.Quotient.mk I (g₁ x) = Ideal.Quotient.mk I (g₂ x)) : g₁ = g₂ := by
have (i : ℕ) :
(Ideal.Quotient.mkₐ R (I ^ i)).comp g₁ = (Ideal.Quotient.mkₐ R (I ^ i)).comp g₂ := by
by_cases hi : i = 0
· ext x
have : Subsingleton (B ⧸ I ^ i) := by
rw [hi, pow_zero, Ideal.one_eq_top]
infer_instance
exact Subsingleton.elim _ _
apply ext (I.map (algebraMap _ _)) ⟨i, by simp [← Ideal.map_pow]⟩
intro x
dsimp
rw [Ideal.Quotient.eq, ← map_sub, ← Ideal.mem_comap, Ideal.comap_map_of_surjective',
sup_eq_left.mpr, ← Ideal.Quotient.eq]
· exact H _
· simpa using Ideal.pow_le_self hi
· exact Ideal.Quotient.mk_surjective
ext x
rw [← sub_eq_zero, ← Ideal.mem_bot, ← hI, Ideal.mem_iInf]
intro i
rw [← Ideal.Quotient.eq_zero_iff_mem, map_sub, sub_eq_zero]
exact DFunLike.congr_fun (this i) x
end
instance {R : Type*} [CommRing R] : FormallyUnramified R R := by
rw [iff_comp_injective]
intros B _ _ _ _ f₁ f₂ _
exact Subsingleton.elim _ _
section OfEquiv
variable {R : Type*} [CommRing R]
variable {A B : Type*} [CommRing A] [Algebra R A] [CommRing B] [Algebra R B]
theorem of_equiv [FormallyUnramified R A] (e : A ≃ₐ[R] B) :
FormallyUnramified R B := by
rw [iff_comp_injective]
intro C _ _ I hI f₁ f₂ e'
rw [← f₁.comp_id, ← f₂.comp_id, ← e.comp_symm, ← AlgHom.comp_assoc, ← AlgHom.comp_assoc]
congr 1
refine FormallyUnramified.comp_injective I hI ?_
rw [← AlgHom.comp_assoc, e', AlgHom.comp_assoc]
end OfEquiv
section Comp
variable (R : Type*) [CommRing R]
variable (A : Type*) [CommRing A] [Algebra R A]
variable (B : Type*) [CommRing B] [Algebra R B] [Algebra A B] [IsScalarTower R A B]
theorem comp [FormallyUnramified R A] [FormallyUnramified A B] :
FormallyUnramified R B := by
rw [iff_comp_injective]
intro C _ _ I hI f₁ f₂ e
have e' :=
FormallyUnramified.lift_unique I ⟨2, hI⟩ (f₁.comp <| IsScalarTower.toAlgHom R A B)
(f₂.comp <| IsScalarTower.toAlgHom R A B) (by rw [← AlgHom.comp_assoc, e, AlgHom.comp_assoc])
letI := (f₁.restrictDomain A).toAlgebra
let F₁ : B →ₐ[A] C := { f₁ with commutes' := fun r => rfl }
let F₂ : B →ₐ[A] C := { f₂ with commutes' := AlgHom.congr_fun e'.symm }
ext1 x
change F₁ x = F₂ x
congr
exact FormallyUnramified.ext I ⟨2, hI⟩ (AlgHom.congr_fun e)
theorem of_comp [FormallyUnramified R B] : FormallyUnramified A B := by
rw [iff_comp_injective]
intro Q _ _ I e f₁ f₂ e'
letI := ((algebraMap A Q).comp (algebraMap R A)).toAlgebra
letI : IsScalarTower R A Q := IsScalarTower.of_algebraMap_eq' rfl
refine AlgHom.restrictScalars_injective R ?_
refine FormallyUnramified.ext I ⟨2, e⟩ ?_
intro x
exact AlgHom.congr_fun e' x
end Comp
section of_surjective
variable {R : Type*} [CommRing R]
variable {A B : Type*} [CommRing A] [Algebra R A] [CommRing B] [Algebra R B]
/-- This holds in general for epimorphisms. -/
theorem of_surjective [FormallyUnramified R A] (f : A →ₐ[R] B) (H : Function.Surjective f) :
FormallyUnramified R B := by
rw [iff_comp_injective]
intro Q _ _ I hI f₁ f₂ e
ext x
obtain ⟨x, rfl⟩ := H x
rw [← AlgHom.comp_apply, ← AlgHom.comp_apply]
congr 1
apply FormallyUnramified.comp_injective I hI
ext x; exact DFunLike.congr_fun e (f x)
instance quotient {A} [CommRing A] [Algebra R A] [FormallyUnramified R A] (I : Ideal A) :
FormallyUnramified R (A ⧸ I) :=
FormallyUnramified.of_surjective (IsScalarTower.toAlgHom R A (A ⧸ I)) Ideal.Quotient.mk_surjective
theorem iff_of_equiv (e : A ≃ₐ[R] B) : FormallyUnramified R A ↔ FormallyUnramified R B :=
⟨fun _ ↦ of_equiv e, fun _ ↦ of_equiv e.symm⟩
end of_surjective
section BaseChange
open scoped TensorProduct
variable {R : Type*} [CommRing R]
variable {A : Type*} [CommRing A] [Algebra R A]
variable (B : Type*) [CommRing B] [Algebra R B]
instance base_change [FormallyUnramified R A] :
FormallyUnramified B (B ⊗[R] A) := by
rw [iff_comp_injective]
intro C _ _ I hI f₁ f₂ e
letI := ((algebraMap B C).comp (algebraMap R B)).toAlgebra
haveI : IsScalarTower R B C := IsScalarTower.of_algebraMap_eq' rfl
ext : 1
· subsingleton
· exact FormallyUnramified.ext I ⟨2, hI⟩ fun x => AlgHom.congr_fun e (1 ⊗ₜ x)
end BaseChange
section Localization
variable {R S Rₘ Sₘ : Type*} [CommRing R] [CommRing S] [CommRing Rₘ] [CommRing Sₘ]
variable (M : Submonoid R)
variable [Algebra R S] [Algebra R Sₘ] [Algebra S Sₘ] [Algebra R Rₘ] [Algebra Rₘ Sₘ]
variable [IsScalarTower R Rₘ Sₘ] [IsScalarTower R S Sₘ]
variable [IsLocalization (M.map (algebraMap R S)) Sₘ]
include M
/-- This holds in general for epimorphisms. -/
theorem of_isLocalization [IsLocalization M Rₘ] : FormallyUnramified R Rₘ := by
rw [iff_comp_injective]
intro Q _ _ I _ f₁ f₂ _
apply AlgHom.coe_ringHom_injective
refine IsLocalization.ringHom_ext M ?_
ext
simp
instance [FormallyUnramified R S] (M : Submonoid S) : FormallyUnramified R (Localization M) :=
have := of_isLocalization (Rₘ := Localization M) M
.comp _ S _
/-- This actually does not need the localization instance, and is stated here again for
consistency. See `Algebra.FormallyUnramified.of_comp` instead.
The intended use is for copying proofs between `Formally{Unramified, Smooth, Etale}`
without the need to change anything (including removing redundant arguments). -/
-- @[nolint unusedArguments] -- Porting note: removed
theorem localization_base [FormallyUnramified R Sₘ] : FormallyUnramified Rₘ Sₘ :=
-- Porting note: added
let _ := M
FormallyUnramified.of_comp R Rₘ Sₘ
theorem localization_map [FormallyUnramified R S] :
FormallyUnramified Rₘ Sₘ := by
haveI : FormallyUnramified S Sₘ :=
FormallyUnramified.of_isLocalization (M.map (algebraMap R S))
haveI : FormallyUnramified R Sₘ := FormallyUnramified.comp R S Sₘ
exact FormallyUnramified.localization_base M
end Localization
end FormallyUnramified
section
variable (R : Type*) [CommRing R]
variable (A : Type*) [CommRing A] [Algebra R A]
/-- An `R`-algebra `A` is unramified if it is formally unramified and of finite type. -/
@[stacks 00UT "Note that the Stacks project has a different definition of unramified, and tag
<https://stacks.math.columbia.edu/tag/00UU> shows that their definition is the same as this one."]
class Unramified : Prop where
formallyUnramified : FormallyUnramified R A := by infer_instance
finiteType : FiniteType R A := by infer_instance
end
namespace Unramified
attribute [instance] formallyUnramified finiteType
variable {R : Type*} [CommRing R]
variable {A B : Type*} [CommRing A] [Algebra R A] [CommRing B] [Algebra R B]
/-- Being unramified is transported via algebra isomorphisms. -/
theorem of_equiv [Unramified R A] (e : A ≃ₐ[R] B) : Unramified R B where
formallyUnramified := FormallyUnramified.of_equiv e
finiteType := FiniteType.equiv Unramified.finiteType e
/-- Localization at an element is unramified. -/
theorem of_isLocalization_Away (r : R) [IsLocalization.Away r A] : Unramified R A where
formallyUnramified := Algebra.FormallyUnramified.of_isLocalization (Submonoid.powers r)
finiteType :=
haveI : FinitePresentation R A := IsLocalization.Away.finitePresentation r
inferInstance
section Comp
variable (R A B)
/-- Unramified is stable under composition. -/
theorem comp [Algebra A B] [IsScalarTower R A B] [Unramified R A] [Unramified A B] :
Unramified R B where
formallyUnramified := FormallyUnramified.comp R A B
finiteType := FiniteType.trans (S := A) Unramified.finiteType
Unramified.finiteType
/-- Unramified is stable under base change. -/
instance baseChange [Unramified R A] : Unramified B (B ⊗[R] A) where
end Comp
end Unramified
end Algebra
|
Symbols.lean
|
/-
Copyright (c) 2024 Hannah Fechtner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Hannah Fechtner
-/
import Mathlib.Algebra.FreeMonoid.Basic
import Mathlib.Data.Finset.Lattice.Lemmas
/-!
# The finite set of symbols in a FreeMonoid element
This is separated from the main FreeMonoid file, as it imports the finiteness hierarchy
-/
variable {α : Type*} [DecidableEq α]
namespace FreeMonoid
/-- the set of unique symbols in a free monoid element -/
@[to_additive /-- The set of unique symbols in an additive free monoid element -/]
def symbols (a : FreeMonoid α) : Finset α := List.toFinset a
@[to_additive (attr := simp)]
theorem symbols_one : symbols (1 : FreeMonoid α) = ∅ := rfl
@[to_additive (attr := simp)]
theorem symbols_of {m : α} : symbols (of m) = {m} := rfl
@[to_additive (attr := simp)]
theorem symbols_mul {a b : FreeMonoid α} : symbols (a * b) = symbols a ∪ symbols b := by
simp only [symbols]
apply List.toFinset_append
@[to_additive (attr := simp)]
theorem mem_symbols {m : α} {a : FreeMonoid α} : m ∈ symbols a ↔ m ∈ a :=
List.mem_toFinset
end FreeMonoid
|
Normed.lean
|
/-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker, Sébastien Gouëzel, Yury Kudryashov, Dylan MacKenzie, Patrick Massot
-/
import Mathlib.Algebra.BigOperators.Module
import Mathlib.Algebra.Order.Field.Power
import Mathlib.Algebra.Polynomial.Monic
import Mathlib.Analysis.Asymptotics.Lemmas
import Mathlib.Analysis.Normed.Ring.InfiniteSum
import Mathlib.Analysis.Normed.Module.Basic
import Mathlib.Analysis.Normed.Order.Lattice
import Mathlib.Analysis.SpecificLimits.Basic
import Mathlib.Data.List.TFAE
import Mathlib.Data.Nat.Choose.Bounds
import Mathlib.Order.Filter.AtTopBot.ModEq
import Mathlib.RingTheory.Polynomial.Pochhammer
import Mathlib.Tactic.NoncommRing
/-!
# A collection of specific limit computations
This file contains important specific limit computations in (semi-)normed groups/rings/spaces, as
well as such computations in `ℝ` when the natural proof passes through a fact about normed spaces.
-/
noncomputable section
open Set Function Filter Finset Metric Asymptotics Topology Nat NNReal ENNReal
variable {α : Type*}
theorem tendsto_natCast_atTop_cobounded
[NormedRing α] [NormSMulClass ℤ α] [Nontrivial α] :
Tendsto Nat.cast atTop (Bornology.cobounded α) := by
rw [← tendsto_norm_atTop_iff_cobounded]
simpa [norm_natCast_eq_mul_norm_one] using tendsto_natCast_atTop_atTop
|>.atTop_mul_const (norm_pos_iff.mpr one_ne_zero)
theorem tendsto_intCast_atBot_sup_atTop_cobounded
[NormedRing α] [NormSMulClass ℤ α] [Nontrivial α] :
Tendsto Int.cast (atBot ⊔ atTop) (Bornology.cobounded α) := by
rw [← tendsto_norm_atTop_iff_cobounded]
simpa [norm_intCast_eq_abs_mul_norm_one] using tendsto_intCast_atTop_atTop
|>.comp (tendsto_abs_atBot_atTop.sup tendsto_abs_atTop_atTop)
|>.atTop_mul_const (norm_pos_iff.mpr one_ne_zero)
theorem tendsto_intCast_atBot_cobounded
[NormedRing α] [NormSMulClass ℤ α] [Nontrivial α] :
Tendsto Int.cast atBot (Bornology.cobounded α) :=
tendsto_intCast_atBot_sup_atTop_cobounded.mono_left le_sup_left
theorem tendsto_intCast_atTop_cobounded
[NormedRing α] [NormSMulClass ℤ α] [Nontrivial α] :
Tendsto Int.cast atTop (Bornology.cobounded α) :=
tendsto_intCast_atBot_sup_atTop_cobounded.mono_left le_sup_right
/-! ### Powers -/
theorem isLittleO_pow_pow_of_lt_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ < r₂) :
(fun n : ℕ ↦ r₁ ^ n) =o[atTop] fun n ↦ r₂ ^ n :=
have H : 0 < r₂ := h₁.trans_lt h₂
(isLittleO_of_tendsto fun _ hn ↦ False.elim <| H.ne' <| pow_eq_zero hn) <|
(tendsto_pow_atTop_nhds_zero_of_lt_one
(div_nonneg h₁ (h₁.trans h₂.le)) ((div_lt_one H).2 h₂)).congr fun _ ↦ div_pow _ _ _
theorem isBigO_pow_pow_of_le_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ ≤ r₂) :
(fun n : ℕ ↦ r₁ ^ n) =O[atTop] fun n ↦ r₂ ^ n :=
h₂.eq_or_lt.elim (fun h ↦ h ▸ isBigO_refl _ _) fun h ↦ (isLittleO_pow_pow_of_lt_left h₁ h).isBigO
theorem isLittleO_pow_pow_of_abs_lt_left {r₁ r₂ : ℝ} (h : |r₁| < |r₂|) :
(fun n : ℕ ↦ r₁ ^ n) =o[atTop] fun n ↦ r₂ ^ n := by
refine (IsLittleO.of_norm_left ?_).of_norm_right
exact (isLittleO_pow_pow_of_lt_left (abs_nonneg r₁) h).congr (pow_abs r₁) (pow_abs r₂)
open List in
/-- Various statements equivalent to the fact that `f n` grows exponentially slower than `R ^ n`.
* 0: $f n = o(a ^ n)$ for some $-R < a < R$;
* 1: $f n = o(a ^ n)$ for some $0 < a < R$;
* 2: $f n = O(a ^ n)$ for some $-R < a < R$;
* 3: $f n = O(a ^ n)$ for some $0 < a < R$;
* 4: there exist `a < R` and `C` such that one of `C` and `R` is positive and $|f n| ≤ Ca^n$
for all `n`;
* 5: there exists `0 < a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`;
* 6: there exists `a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`;
* 7: there exists `0 < a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`.
NB: For backwards compatibility, if you add more items to the list, please append them at the end of
the list. -/
theorem TFAE_exists_lt_isLittleO_pow (f : ℕ → ℝ) (R : ℝ) :
TFAE
[∃ a ∈ Ioo (-R) R, f =o[atTop] (a ^ ·), ∃ a ∈ Ioo 0 R, f =o[atTop] (a ^ ·),
∃ a ∈ Ioo (-R) R, f =O[atTop] (a ^ ·), ∃ a ∈ Ioo 0 R, f =O[atTop] (a ^ ·),
∃ a < R, ∃ C : ℝ, (0 < C ∨ 0 < R) ∧ ∀ n, |f n| ≤ C * a ^ n,
∃ a ∈ Ioo 0 R, ∃ C > 0, ∀ n, |f n| ≤ C * a ^ n, ∃ a < R, ∀ᶠ n in atTop, |f n| ≤ a ^ n,
∃ a ∈ Ioo 0 R, ∀ᶠ n in atTop, |f n| ≤ a ^ n] := by
have A : Ico 0 R ⊆ Ioo (-R) R :=
fun x hx ↦ ⟨(neg_lt_zero.2 (hx.1.trans_lt hx.2)).trans_le hx.1, hx.2⟩
have B : Ioo 0 R ⊆ Ioo (-R) R := Subset.trans Ioo_subset_Ico_self A
-- First we prove that 1-4 are equivalent using 2 → 3 → 4, 1 → 3, and 2 → 1
tfae_have 1 → 3 := fun ⟨a, ha, H⟩ ↦ ⟨a, ha, H.isBigO⟩
tfae_have 2 → 1 := fun ⟨a, ha, H⟩ ↦ ⟨a, B ha, H⟩
tfae_have 3 → 2
| ⟨a, ha, H⟩ => by
rcases exists_between (abs_lt.2 ha) with ⟨b, hab, hbR⟩
exact ⟨b, ⟨(abs_nonneg a).trans_lt hab, hbR⟩,
H.trans_isLittleO (isLittleO_pow_pow_of_abs_lt_left (hab.trans_le (le_abs_self b)))⟩
tfae_have 2 → 4 := fun ⟨a, ha, H⟩ ↦ ⟨a, ha, H.isBigO⟩
tfae_have 4 → 3 := fun ⟨a, ha, H⟩ ↦ ⟨a, B ha, H⟩
-- Add 5 and 6 using 4 → 6 → 5 → 3
tfae_have 4 → 6
| ⟨a, ha, H⟩ => by
rcases bound_of_isBigO_nat_atTop H with ⟨C, hC₀, hC⟩
refine ⟨a, ha, C, hC₀, fun n ↦ ?_⟩
simpa only [Real.norm_eq_abs, abs_pow, abs_of_nonneg ha.1.le] using hC (pow_ne_zero n ha.1.ne')
tfae_have 6 → 5 := fun ⟨a, ha, C, H₀, H⟩ ↦ ⟨a, ha.2, C, Or.inl H₀, H⟩
tfae_have 5 → 3
| ⟨a, ha, C, h₀, H⟩ => by
rcases sign_cases_of_C_mul_pow_nonneg fun n ↦ (abs_nonneg _).trans (H n) with (rfl | ⟨hC₀, ha₀⟩)
· obtain rfl : f = 0 := by
ext n
simpa using H n
simp only [lt_irrefl, false_or] at h₀
exact ⟨0, ⟨neg_lt_zero.2 h₀, h₀⟩, isBigO_zero _ _⟩
exact ⟨a, A ⟨ha₀, ha⟩,
isBigO_of_le' _ fun n ↦ (H n).trans <| mul_le_mul_of_nonneg_left (le_abs_self _) hC₀.le⟩
-- Add 7 and 8 using 2 → 8 → 7 → 3
tfae_have 2 → 8
| ⟨a, ha, H⟩ => by
refine ⟨a, ha, (H.def zero_lt_one).mono fun n hn ↦ ?_⟩
rwa [Real.norm_eq_abs, Real.norm_eq_abs, one_mul, abs_pow, abs_of_pos ha.1] at hn
tfae_have 8 → 7 := fun ⟨a, ha, H⟩ ↦ ⟨a, ha.2, H⟩
tfae_have 7 → 3
| ⟨a, ha, H⟩ => by
refine ⟨a, A ⟨?_, ha⟩, .of_norm_eventuallyLE H⟩
exact nonneg_of_eventually_pow_nonneg (H.mono fun n ↦ (abs_nonneg _).trans)
tfae_finish
/-- For any natural `k` and a real `r > 1` we have `n ^ k = o(r ^ n)` as `n → ∞`. -/
theorem isLittleO_pow_const_const_pow_of_one_lt {R : Type*} [NormedRing R] (k : ℕ) {r : ℝ}
(hr : 1 < r) : (fun n ↦ (n : R) ^ k : ℕ → R) =o[atTop] fun n ↦ r ^ n := by
have : Tendsto (fun x : ℝ ↦ x ^ k) (𝓝[>] 1) (𝓝 1) :=
((continuous_id.pow k).tendsto' (1 : ℝ) 1 (one_pow _)).mono_left inf_le_left
obtain ⟨r' : ℝ, hr' : r' ^ k < r, h1 : 1 < r'⟩ :=
((this.eventually (gt_mem_nhds hr)).and self_mem_nhdsWithin).exists
have h0 : 0 ≤ r' := zero_le_one.trans h1.le
suffices (fun n ↦ (n : R) ^ k : ℕ → R) =O[atTop] fun n : ℕ ↦ (r' ^ k) ^ n from
this.trans_isLittleO (isLittleO_pow_pow_of_lt_left (pow_nonneg h0 _) hr')
conv in (r' ^ _) ^ _ => rw [← pow_mul, mul_comm, pow_mul]
suffices ∀ n : ℕ, ‖(n : R)‖ ≤ (r' - 1)⁻¹ * ‖(1 : R)‖ * ‖r' ^ n‖ from
(isBigO_of_le' _ this).pow _
intro n
rw [mul_right_comm]
refine n.norm_cast_le.trans (mul_le_mul_of_nonneg_right ?_ (norm_nonneg _))
simpa [_root_.div_eq_inv_mul, Real.norm_eq_abs, abs_of_nonneg h0] using n.cast_le_pow_div_sub h1
/-- For a real `r > 1` we have `n = o(r ^ n)` as `n → ∞`. -/
theorem isLittleO_coe_const_pow_of_one_lt {R : Type*} [NormedRing R] {r : ℝ} (hr : 1 < r) :
((↑) : ℕ → R) =o[atTop] fun n ↦ r ^ n := by
simpa only [pow_one] using @isLittleO_pow_const_const_pow_of_one_lt R _ 1 _ hr
/-- If `‖r₁‖ < r₂`, then for any natural `k` we have `n ^ k r₁ ^ n = o (r₂ ^ n)` as `n → ∞`. -/
theorem isLittleO_pow_const_mul_const_pow_const_pow_of_norm_lt {R : Type*} [NormedRing R] (k : ℕ)
{r₁ : R} {r₂ : ℝ} (h : ‖r₁‖ < r₂) :
(fun n ↦ (n : R) ^ k * r₁ ^ n : ℕ → R) =o[atTop] fun n ↦ r₂ ^ n := by
by_cases h0 : r₁ = 0
· refine (isLittleO_zero _ _).congr' (mem_atTop_sets.2 <| ⟨1, fun n hn ↦ ?_⟩) EventuallyEq.rfl
simp [zero_pow (one_le_iff_ne_zero.1 hn), h0]
rw [← Ne, ← norm_pos_iff] at h0
have A : (fun n ↦ (n : R) ^ k : ℕ → R) =o[atTop] fun n ↦ (r₂ / ‖r₁‖) ^ n :=
isLittleO_pow_const_const_pow_of_one_lt k ((one_lt_div h0).2 h)
suffices (fun n ↦ r₁ ^ n) =O[atTop] fun n ↦ ‖r₁‖ ^ n by
simpa [div_mul_cancel₀ _ (pow_pos h0 _).ne', div_pow] using A.mul_isBigO this
exact .of_norm_eventuallyLE <| eventually_norm_pow_le r₁
theorem tendsto_pow_const_div_const_pow_of_one_lt (k : ℕ) {r : ℝ} (hr : 1 < r) :
Tendsto (fun n ↦ (n : ℝ) ^ k / r ^ n : ℕ → ℝ) atTop (𝓝 0) :=
(isLittleO_pow_const_const_pow_of_one_lt k hr).tendsto_div_nhds_zero
/-- If `|r| < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`. -/
theorem tendsto_pow_const_mul_const_pow_of_abs_lt_one (k : ℕ) {r : ℝ} (hr : |r| < 1) :
Tendsto (fun n ↦ (n : ℝ) ^ k * r ^ n : ℕ → ℝ) atTop (𝓝 0) := by
by_cases h0 : r = 0
· exact tendsto_const_nhds.congr'
(mem_atTop_sets.2 ⟨1, fun n hn ↦ by simp [zero_lt_one.trans_le hn |>.ne', h0]⟩)
have hr' : 1 < |r|⁻¹ := (one_lt_inv₀ (abs_pos.2 h0)).2 hr
rw [tendsto_zero_iff_norm_tendsto_zero]
simpa [div_eq_mul_inv] using tendsto_pow_const_div_const_pow_of_one_lt k hr'
/-- For `k ≠ 0` and a constant `r` the function `r / n ^ k` tends to zero. -/
lemma tendsto_const_div_pow (r : ℝ) (k : ℕ) (hk : k ≠ 0) :
Tendsto (fun n : ℕ => r / n ^ k) atTop (𝓝 0) := by
simpa using Filter.Tendsto.const_div_atTop (tendsto_natCast_atTop_atTop (R := ℝ).comp
(tendsto_pow_atTop hk) ) r
/-- If `0 ≤ r < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`.
This is a specialized version of `tendsto_pow_const_mul_const_pow_of_abs_lt_one`, singled out
for ease of application. -/
theorem tendsto_pow_const_mul_const_pow_of_lt_one (k : ℕ) {r : ℝ} (hr : 0 ≤ r) (h'r : r < 1) :
Tendsto (fun n ↦ (n : ℝ) ^ k * r ^ n : ℕ → ℝ) atTop (𝓝 0) :=
tendsto_pow_const_mul_const_pow_of_abs_lt_one k (abs_lt.2 ⟨neg_one_lt_zero.trans_le hr, h'r⟩)
/-- If `|r| < 1`, then `n * r ^ n` tends to zero. -/
theorem tendsto_self_mul_const_pow_of_abs_lt_one {r : ℝ} (hr : |r| < 1) :
Tendsto (fun n ↦ n * r ^ n : ℕ → ℝ) atTop (𝓝 0) := by
simpa only [pow_one] using tendsto_pow_const_mul_const_pow_of_abs_lt_one 1 hr
/-- If `0 ≤ r < 1`, then `n * r ^ n` tends to zero. This is a specialized version of
`tendsto_self_mul_const_pow_of_abs_lt_one`, singled out for ease of application. -/
theorem tendsto_self_mul_const_pow_of_lt_one {r : ℝ} (hr : 0 ≤ r) (h'r : r < 1) :
Tendsto (fun n ↦ n * r ^ n : ℕ → ℝ) atTop (𝓝 0) := by
simpa only [pow_one] using tendsto_pow_const_mul_const_pow_of_lt_one 1 hr h'r
/-- In a normed ring, the powers of an element x with `‖x‖ < 1` tend to zero. -/
theorem tendsto_pow_atTop_nhds_zero_of_norm_lt_one {R : Type*} [SeminormedRing R] {x : R}
(h : ‖x‖ < 1) :
Tendsto (fun n : ℕ ↦ x ^ n) atTop (𝓝 0) := by
apply squeeze_zero_norm' (eventually_norm_pow_le x)
exact tendsto_pow_atTop_nhds_zero_of_lt_one (norm_nonneg _) h
theorem tendsto_pow_atTop_nhds_zero_of_abs_lt_one {r : ℝ} (h : |r| < 1) :
Tendsto (fun n : ℕ ↦ r ^ n) atTop (𝓝 0) :=
tendsto_pow_atTop_nhds_zero_of_norm_lt_one h
lemma tendsto_pow_atTop_nhds_zero_iff_norm_lt_one {R : Type*} [SeminormedRing R] [NormMulClass R]
{x : R} : Tendsto (fun n : ℕ ↦ x ^ n) atTop (𝓝 0) ↔ ‖x‖ < 1 := by
-- this proof is slightly fiddly since `‖x ^ n‖ = ‖x‖ ^ n` might not hold for `n = 0`
refine ⟨?_, tendsto_pow_atTop_nhds_zero_of_norm_lt_one⟩
rw [← abs_of_nonneg (norm_nonneg _), ← tendsto_pow_atTop_nhds_zero_iff,
tendsto_zero_iff_norm_tendsto_zero]
apply Tendsto.congr'
filter_upwards [eventually_ge_atTop 1] with n hn
induction n, hn using Nat.le_induction with
| base => simp
| succ n hn IH => simp [pow_succ, IH]
/-! ### Geometric series -/
/-- A normed ring has summable geometric series if, for all `ξ` of norm `< 1`, the geometric series
`∑ ξ ^ n` converges. This holds both in complete normed rings and in normed fields, providing a
convenient abstraction of these two classes to avoid repeating the same proofs. -/
class HasSummableGeomSeries (K : Type*) [NormedRing K] : Prop where
summable_geometric_of_norm_lt_one : ∀ (ξ : K), ‖ξ‖ < 1 → Summable (fun n ↦ ξ ^ n)
lemma summable_geometric_of_norm_lt_one {K : Type*} [NormedRing K] [HasSummableGeomSeries K]
{x : K} (h : ‖x‖ < 1) : Summable (fun n ↦ x ^ n) :=
HasSummableGeomSeries.summable_geometric_of_norm_lt_one x h
instance {R : Type*} [NormedRing R] [CompleteSpace R] : HasSummableGeomSeries R := by
constructor
intro x hx
have h1 : Summable fun n : ℕ ↦ ‖x‖ ^ n := summable_geometric_of_lt_one (norm_nonneg _) hx
exact h1.of_norm_bounded_eventually_nat (eventually_norm_pow_le x)
section HasSummableGeometricSeries
variable {R : Type*} [NormedRing R]
open NormedSpace
/-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the
normed ring satisfies the axiom `‖1‖ = 1`. -/
theorem tsum_geometric_le_of_norm_lt_one (x : R) (h : ‖x‖ < 1) :
‖∑' n : ℕ, x ^ n‖ ≤ ‖(1 : R)‖ - 1 + (1 - ‖x‖)⁻¹ := by
by_cases hx : Summable (fun n ↦ x ^ n)
· rw [hx.tsum_eq_zero_add]
simp only [_root_.pow_zero]
refine le_trans (norm_add_le _ _) ?_
have : ‖∑' b : ℕ, (fun n ↦ x ^ (n + 1)) b‖ ≤ (1 - ‖x‖)⁻¹ - 1 := by
refine tsum_of_norm_bounded ?_ fun b ↦ norm_pow_le' _ (Nat.succ_pos b)
convert (hasSum_nat_add_iff' 1).mpr (hasSum_geometric_of_lt_one (norm_nonneg x) h)
simp
linarith
· simp [tsum_eq_zero_of_not_summable hx]
nontriviality R
have : 1 ≤ ‖(1 : R)‖ := one_le_norm_one R
have : 0 ≤ (1 - ‖x‖) ⁻¹ := inv_nonneg.2 (by linarith)
linarith
variable [HasSummableGeomSeries R]
theorem geom_series_mul_neg (x : R) (h : ‖x‖ < 1) : (∑' i : ℕ, x ^ i) * (1 - x) = 1 := by
have := (summable_geometric_of_norm_lt_one h).hasSum.mul_right (1 - x)
refine tendsto_nhds_unique this.tendsto_sum_nat ?_
have : Tendsto (fun n : ℕ ↦ 1 - x ^ n) atTop (𝓝 1) := by
simpa using tendsto_const_nhds.sub (tendsto_pow_atTop_nhds_zero_of_norm_lt_one h)
convert← this
rw [← geom_sum_mul_neg, Finset.sum_mul]
theorem mul_neg_geom_series (x : R) (h : ‖x‖ < 1) : (1 - x) * ∑' i : ℕ, x ^ i = 1 := by
have := (summable_geometric_of_norm_lt_one h).hasSum.mul_left (1 - x)
refine tendsto_nhds_unique this.tendsto_sum_nat ?_
have : Tendsto (fun n : ℕ ↦ 1 - x ^ n) atTop (𝓝 1) := by
simpa using tendsto_const_nhds.sub (tendsto_pow_atTop_nhds_zero_of_norm_lt_one h)
convert← this
rw [← mul_neg_geom_sum, Finset.mul_sum]
theorem geom_series_succ (x : R) (h : ‖x‖ < 1) : ∑' i : ℕ, x ^ (i + 1) = ∑' i : ℕ, x ^ i - 1 := by
rw [eq_sub_iff_add_eq, (summable_geometric_of_norm_lt_one h).tsum_eq_zero_add,
pow_zero, add_comm]
theorem geom_series_mul_shift (x : R) (h : ‖x‖ < 1) :
x * ∑' i : ℕ, x ^ i = ∑' i : ℕ, x ^ (i + 1) := by
simp_rw [← (summable_geometric_of_norm_lt_one h).tsum_mul_left, ← _root_.pow_succ']
theorem geom_series_mul_one_add (x : R) (h : ‖x‖ < 1) :
(1 + x) * ∑' i : ℕ, x ^ i = 2 * ∑' i : ℕ, x ^ i - 1 := by
rw [add_mul, one_mul, geom_series_mul_shift x h, geom_series_succ x h, two_mul, add_sub_assoc]
/-- In a normed ring with summable geometric series, a perturbation of `1` by an element `t`
of distance less than `1` from `1` is a unit. Here we construct its `Units` structure. -/
@[simps val]
def Units.oneSub (t : R) (h : ‖t‖ < 1) : Rˣ where
val := 1 - t
inv := ∑' n : ℕ, t ^ n
val_inv := mul_neg_geom_series t h
inv_val := geom_series_mul_neg t h
theorem geom_series_eq_inverse (x : R) (h : ‖x‖ < 1) :
∑' i, x ^ i = Ring.inverse (1 - x) := by
change (Units.oneSub x h) ⁻¹ = Ring.inverse (1 - x)
rw [← Ring.inverse_unit]
rfl
theorem hasSum_geom_series_inverse (x : R) (h : ‖x‖ < 1) :
HasSum (fun i ↦ x ^ i) (Ring.inverse (1 - x)) := by
convert (summable_geometric_of_norm_lt_one h).hasSum
exact (geom_series_eq_inverse x h).symm
lemma isUnit_one_sub_of_norm_lt_one {x : R} (h : ‖x‖ < 1) : IsUnit (1 - x) :=
⟨Units.oneSub x h, rfl⟩
end HasSummableGeometricSeries
section Geometric
variable {K : Type*} [NormedDivisionRing K] {ξ : K}
theorem hasSum_geometric_of_norm_lt_one (h : ‖ξ‖ < 1) : HasSum (fun n : ℕ ↦ ξ ^ n) (1 - ξ)⁻¹ := by
have xi_ne_one : ξ ≠ 1 := by
contrapose! h
simp [h]
have A : Tendsto (fun n ↦ (ξ ^ n - 1) * (ξ - 1)⁻¹) atTop (𝓝 ((0 - 1) * (ξ - 1)⁻¹)) :=
((tendsto_pow_atTop_nhds_zero_of_norm_lt_one h).sub tendsto_const_nhds).mul tendsto_const_nhds
rw [hasSum_iff_tendsto_nat_of_summable_norm]
· simpa [geom_sum_eq, xi_ne_one, neg_inv, div_eq_mul_inv] using A
· simp [norm_pow, summable_geometric_of_lt_one (norm_nonneg _) h]
instance : HasSummableGeomSeries K :=
⟨fun _ h ↦ (hasSum_geometric_of_norm_lt_one h).summable⟩
theorem tsum_geometric_of_norm_lt_one (h : ‖ξ‖ < 1) : ∑' n : ℕ, ξ ^ n = (1 - ξ)⁻¹ :=
(hasSum_geometric_of_norm_lt_one h).tsum_eq
theorem hasSum_geometric_of_abs_lt_one {r : ℝ} (h : |r| < 1) :
HasSum (fun n : ℕ ↦ r ^ n) (1 - r)⁻¹ :=
hasSum_geometric_of_norm_lt_one h
theorem summable_geometric_of_abs_lt_one {r : ℝ} (h : |r| < 1) : Summable fun n : ℕ ↦ r ^ n :=
summable_geometric_of_norm_lt_one h
theorem tsum_geometric_of_abs_lt_one {r : ℝ} (h : |r| < 1) : ∑' n : ℕ, r ^ n = (1 - r)⁻¹ :=
tsum_geometric_of_norm_lt_one h
/-- A geometric series in a normed field is summable iff the norm of the common ratio is less than
one. -/
@[simp]
theorem summable_geometric_iff_norm_lt_one : (Summable fun n : ℕ ↦ ξ ^ n) ↔ ‖ξ‖ < 1 := by
refine ⟨fun h ↦ ?_, summable_geometric_of_norm_lt_one⟩
obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ :=
(h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists
simp only [norm_pow, dist_zero_right] at hk
rw [← one_pow k] at hk
exact lt_of_pow_lt_pow_left₀ _ zero_le_one hk
end Geometric
section MulGeometric
variable {R : Type*} [NormedRing R] {𝕜 : Type*} [NormedDivisionRing 𝕜]
theorem summable_norm_mul_geometric_of_norm_lt_one {k : ℕ} {r : R}
(hr : ‖r‖ < 1) {u : ℕ → ℕ} (hu : (fun n ↦ (u n : ℝ)) =O[atTop] (fun n ↦ (↑(n ^ k) : ℝ))) :
Summable fun n : ℕ ↦ ‖(u n * r ^ n : R)‖ := by
rcases exists_between hr with ⟨r', hrr', h⟩
rw [← norm_norm] at hrr'
apply summable_of_isBigO_nat (summable_geometric_of_lt_one ((norm_nonneg _).trans hrr'.le) h)
calc
fun n ↦ ‖↑(u n) * r ^ n‖
_ =O[atTop] fun n ↦ u n * ‖r‖ ^ n := by
apply (IsBigOWith.of_bound (c := ‖(1 : R)‖) ?_).isBigO
filter_upwards [eventually_norm_pow_le r] with n hn
simp only [norm_mul, Real.norm_eq_abs, abs_cast, norm_pow, abs_norm]
apply (norm_mul_le _ _).trans
have : ‖(u n : R)‖ * ‖r ^ n‖ ≤ (u n * ‖(1 : R)‖) * ‖r‖ ^ n := by
gcongr; exact norm_cast_le (u n)
exact this.trans (le_of_eq (by ring))
_ =O[atTop] fun n ↦ ↑(n ^ k) * ‖r‖ ^ n := hu.mul (isBigO_refl _ _)
_ =O[atTop] fun n ↦ r' ^ n := by
simp only [cast_pow]
exact (isLittleO_pow_const_mul_const_pow_const_pow_of_norm_lt k hrr').isBigO
theorem summable_norm_pow_mul_geometric_of_norm_lt_one (k : ℕ) {r : R}
(hr : ‖r‖ < 1) : Summable fun n : ℕ ↦ ‖((n : R) ^ k * r ^ n : R)‖ := by
simp only [← cast_pow]
exact summable_norm_mul_geometric_of_norm_lt_one (k := k) (u := fun n ↦ n ^ k) hr
(isBigO_refl _ _)
theorem summable_norm_geometric_of_norm_lt_one {r : R}
(hr : ‖r‖ < 1) : Summable fun n : ℕ ↦ ‖(r ^ n : R)‖ := by
simpa using summable_norm_pow_mul_geometric_of_norm_lt_one 0 hr
variable [HasSummableGeomSeries R]
lemma hasSum_choose_mul_geometric_of_norm_lt_one'
(k : ℕ) {r : R} (hr : ‖r‖ < 1) :
HasSum (fun n ↦ (n + k).choose k * r ^ n) (Ring.inverse (1 - r) ^ (k + 1)) := by
induction k with
| zero => simpa using hasSum_geom_series_inverse r hr
| succ k ih =>
have I1 : Summable (fun (n : ℕ) ↦ ‖(n + k).choose k * r ^ n‖) := by
apply summable_norm_mul_geometric_of_norm_lt_one (k := k) hr
apply isBigO_iff.2 ⟨2 ^ k, ?_⟩
filter_upwards [Ioi_mem_atTop k] with n (hn : k < n)
simp only [Real.norm_eq_abs, abs_cast, cast_pow, norm_pow]
norm_cast
calc (n + k).choose k
_ ≤ (2 * n).choose k := choose_le_choose k (by omega)
_ ≤ (2 * n) ^ k := Nat.choose_le_pow _ _
_ = 2 ^ k * n ^ k := Nat.mul_pow 2 n k
convert hasSum_sum_range_mul_of_summable_norm' I1 ih.summable
(summable_norm_geometric_of_norm_lt_one hr) (summable_geometric_of_norm_lt_one hr) with n
· have : ∑ i ∈ Finset.range (n + 1), ↑((i + k).choose k) * r ^ i * r ^ (n - i) =
∑ i ∈ Finset.range (n + 1), ↑((i + k).choose k) * r ^ n := by
apply Finset.sum_congr rfl (fun i hi ↦ ?_)
simp only [Finset.mem_range] at hi
rw [mul_assoc, ← pow_add, show i + (n - i) = n by omega]
simp [this, ← sum_mul, ← Nat.cast_sum, sum_range_add_choose n k, add_assoc]
· rw [ih.tsum_eq, (hasSum_geom_series_inverse r hr).tsum_eq, pow_succ]
lemma summable_choose_mul_geometric_of_norm_lt_one (k : ℕ) {r : R} (hr : ‖r‖ < 1) :
Summable (fun n ↦ (n + k).choose k * r ^ n) :=
(hasSum_choose_mul_geometric_of_norm_lt_one' k hr).summable
lemma tsum_choose_mul_geometric_of_norm_lt_one' (k : ℕ) {r : R} (hr : ‖r‖ < 1) :
∑' n, (n + k).choose k * r ^ n = (Ring.inverse (1 - r)) ^ (k + 1) :=
(hasSum_choose_mul_geometric_of_norm_lt_one' k hr).tsum_eq
lemma hasSum_choose_mul_geometric_of_norm_lt_one
(k : ℕ) {r : 𝕜} (hr : ‖r‖ < 1) :
HasSum (fun n ↦ (n + k).choose k * r ^ n) (1 / (1 - r) ^ (k + 1)) := by
convert hasSum_choose_mul_geometric_of_norm_lt_one' k hr
simp
lemma tsum_choose_mul_geometric_of_norm_lt_one (k : ℕ) {r : 𝕜} (hr : ‖r‖ < 1) :
∑' n, (n + k).choose k * r ^ n = 1/ (1 - r) ^ (k + 1) :=
(hasSum_choose_mul_geometric_of_norm_lt_one k hr).tsum_eq
lemma summable_descFactorial_mul_geometric_of_norm_lt_one (k : ℕ) {r : R} (hr : ‖r‖ < 1) :
Summable (fun n ↦ (n + k).descFactorial k * r ^ n) := by
convert (summable_choose_mul_geometric_of_norm_lt_one k hr).mul_left (k.factorial : R)
using 2 with n
simp [← mul_assoc, descFactorial_eq_factorial_mul_choose (n + k) k]
open Polynomial in
theorem summable_pow_mul_geometric_of_norm_lt_one (k : ℕ) {r : R} (hr : ‖r‖ < 1) :
Summable (fun n ↦ (n : R) ^ k * r ^ n : ℕ → R) := by
refine Nat.strong_induction_on k fun k hk => ?_
obtain ⟨a, ha⟩ : ∃ (a : ℕ → ℕ), ∀ n, (n + k).descFactorial k
= n ^ k + ∑ i ∈ range k, a i * n ^ i := by
let P : Polynomial ℕ := (ascPochhammer ℕ k).comp (Polynomial.X + C 1)
refine ⟨fun i ↦ P.coeff i, fun n ↦ ?_⟩
have mP : Monic P := Monic.comp_X_add_C (monic_ascPochhammer ℕ k) _
have dP : P.natDegree = k := by
simp only [P, natDegree_comp, ascPochhammer_natDegree, mul_one, natDegree_X_add_C]
have A : (n + k).descFactorial k = P.eval n := by
have : n + 1 + k - 1 = n + k := by omega
simp [P, ascPochhammer_nat_eq_descFactorial, this]
conv_lhs => rw [A, mP.as_sum, dP]
simp [eval_finset_sum]
have : Summable (fun n ↦ (n + k).descFactorial k * r ^ n
- ∑ i ∈ range k, a i * n ^ (i : ℕ) * r ^ n) := by
apply (summable_descFactorial_mul_geometric_of_norm_lt_one k hr).sub
apply summable_sum (fun i hi ↦ ?_)
simp_rw [mul_assoc]
simp only [Finset.mem_range] at hi
exact (hk _ hi).mul_left _
convert this using 1
ext n
simp [ha n, add_mul, sum_mul]
/-- If `‖r‖ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`, `HasSum` version in a general ring
with summable geometric series. For a version in a field, using division instead of `Ring.inverse`,
see `hasSum_coe_mul_geometric_of_norm_lt_one`. -/
theorem hasSum_coe_mul_geometric_of_norm_lt_one'
{x : R} (h : ‖x‖ < 1) :
HasSum (fun n ↦ n * x ^ n : ℕ → R) (x * (Ring.inverse (1 - x)) ^ 2) := by
have A : HasSum (fun (n : ℕ) ↦ (n + 1) * x ^ n) (Ring.inverse (1 - x) ^ 2) := by
convert hasSum_choose_mul_geometric_of_norm_lt_one' 1 h with n
simp
have B : HasSum (fun (n : ℕ) ↦ x ^ n) (Ring.inverse (1 - x)) := hasSum_geom_series_inverse x h
convert A.sub B using 1
· ext n
simp [add_mul]
· symm
calc Ring.inverse (1 - x) ^ 2 - Ring.inverse (1 - x)
_ = Ring.inverse (1 - x) ^ 2 - ((1 - x) * Ring.inverse (1 - x)) * Ring.inverse (1 - x) := by
simp [Ring.mul_inverse_cancel (1 - x) (isUnit_one_sub_of_norm_lt_one h)]
_ = x * Ring.inverse (1 - x) ^ 2 := by noncomm_ring
/-- If `‖r‖ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`, version in a general ring with
summable geometric series. For a version in a field, using division instead of `Ring.inverse`,
see `tsum_coe_mul_geometric_of_norm_lt_one`. -/
theorem tsum_coe_mul_geometric_of_norm_lt_one'
{r : 𝕜} (hr : ‖r‖ < 1) : (∑' n : ℕ, n * r ^ n : 𝕜) = r * Ring.inverse (1 - r) ^ 2 :=
(hasSum_coe_mul_geometric_of_norm_lt_one' hr).tsum_eq
/-- If `‖r‖ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`, `HasSum` version. -/
theorem hasSum_coe_mul_geometric_of_norm_lt_one {r : 𝕜} (hr : ‖r‖ < 1) :
HasSum (fun n ↦ n * r ^ n : ℕ → 𝕜) (r / (1 - r) ^ 2) := by
convert hasSum_coe_mul_geometric_of_norm_lt_one' hr using 1
simp [div_eq_mul_inv]
/-- If `‖r‖ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`. -/
theorem tsum_coe_mul_geometric_of_norm_lt_one {r : 𝕜} (hr : ‖r‖ < 1) :
(∑' n : ℕ, n * r ^ n : 𝕜) = r / (1 - r) ^ 2 :=
(hasSum_coe_mul_geometric_of_norm_lt_one hr).tsum_eq
end MulGeometric
section SummableLeGeometric
variable [SeminormedAddCommGroup α] {r C : ℝ} {f : ℕ → α}
nonrec theorem SeminormedAddCommGroup.cauchySeq_of_le_geometric {C : ℝ} {r : ℝ} (hr : r < 1)
{u : ℕ → α} (h : ∀ n, ‖u n - u (n + 1)‖ ≤ C * r ^ n) : CauchySeq u :=
cauchySeq_of_le_geometric r C hr (by simpa [dist_eq_norm] using h)
theorem dist_partial_sum_le_of_le_geometric (hf : ∀ n, ‖f n‖ ≤ C * r ^ n) (n : ℕ) :
dist (∑ i ∈ range n, f i) (∑ i ∈ range (n + 1), f i) ≤ C * r ^ n := by
rw [sum_range_succ, dist_eq_norm, ← norm_neg, neg_sub, add_sub_cancel_left]
exact hf n
/-- If `‖f n‖ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a
Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/
theorem cauchySeq_finset_of_geometric_bound (hr : r < 1) (hf : ∀ n, ‖f n‖ ≤ C * r ^ n) :
CauchySeq fun s : Finset ℕ ↦ ∑ x ∈ s, f x :=
cauchySeq_finset_of_norm_bounded
(aux_hasSum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf
/-- If `‖f n‖ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within
distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or
`0 ≤ C`. -/
theorem norm_sub_le_of_geometric_bound_of_hasSum (hr : r < 1) (hf : ∀ n, ‖f n‖ ≤ C * r ^ n) {a : α}
(ha : HasSum f a) (n : ℕ) : ‖(∑ x ∈ Finset.range n, f x) - a‖ ≤ C * r ^ n / (1 - r) := by
rw [← dist_eq_norm]
apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf)
exact ha.tendsto_sum_nat
@[simp]
theorem dist_partial_sum (u : ℕ → α) (n : ℕ) :
dist (∑ k ∈ range (n + 1), u k) (∑ k ∈ range n, u k) = ‖u n‖ := by
simp [dist_eq_norm, sum_range_succ]
@[simp]
theorem dist_partial_sum' (u : ℕ → α) (n : ℕ) :
dist (∑ k ∈ range n, u k) (∑ k ∈ range (n + 1), u k) = ‖u n‖ := by
simp [dist_eq_norm', sum_range_succ]
theorem cauchy_series_of_le_geometric {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1)
(h : ∀ n, ‖u n‖ ≤ C * r ^ n) : CauchySeq fun n ↦ ∑ k ∈ range n, u k :=
cauchySeq_of_le_geometric r C hr (by simp [h])
theorem NormedAddCommGroup.cauchy_series_of_le_geometric' {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1)
(h : ∀ n, ‖u n‖ ≤ C * r ^ n) : CauchySeq fun n ↦ ∑ k ∈ range (n + 1), u k :=
(cauchy_series_of_le_geometric hr h).comp_tendsto <| tendsto_add_atTop_nat 1
theorem NormedAddCommGroup.cauchy_series_of_le_geometric'' {C : ℝ} {u : ℕ → α} {N : ℕ} {r : ℝ}
(hr₀ : 0 < r) (hr₁ : r < 1) (h : ∀ n ≥ N, ‖u n‖ ≤ C * r ^ n) :
CauchySeq fun n ↦ ∑ k ∈ range (n + 1), u k := by
set v : ℕ → α := fun n ↦ if n < N then 0 else u n
have hC : 0 ≤ C :=
(mul_nonneg_iff_of_pos_right <| pow_pos hr₀ N).mp ((norm_nonneg _).trans <| h N <| le_refl N)
have : ∀ n ≥ N, u n = v n := by
intro n hn
simp [v, if_neg (not_lt.mpr hn)]
apply cauchySeq_sum_of_eventually_eq this
(NormedAddCommGroup.cauchy_series_of_le_geometric' hr₁ _)
· exact C
intro n
simp only [v]
split_ifs with H
· rw [norm_zero]
exact mul_nonneg hC (pow_nonneg hr₀.le _)
· push_neg at H
exact h _ H
/-- The term norms of any convergent series are bounded by a constant. -/
lemma exists_norm_le_of_cauchySeq (h : CauchySeq fun n ↦ ∑ k ∈ range n, f k) :
∃ C, ∀ n, ‖f n‖ ≤ C := by
obtain ⟨b, ⟨_, key, _⟩⟩ := cauchySeq_iff_le_tendsto_0.mp h
refine ⟨b 0, fun n ↦ ?_⟩
simpa only [dist_partial_sum'] using key n (n + 1) 0 (_root_.zero_le _) (_root_.zero_le _)
end SummableLeGeometric
/-! ### Summability tests based on comparison with geometric series -/
theorem summable_of_ratio_norm_eventually_le {α : Type*} [SeminormedAddCommGroup α]
[CompleteSpace α] {f : ℕ → α} {r : ℝ} (hr₁ : r < 1)
(h : ∀ᶠ n in atTop, ‖f (n + 1)‖ ≤ r * ‖f n‖) : Summable f := by
by_cases hr₀ : 0 ≤ r
· rw [eventually_atTop] at h
rcases h with ⟨N, hN⟩
rw [← @summable_nat_add_iff α _ _ _ _ N]
refine .of_norm_bounded (g := fun n ↦ ‖f N‖ * r ^ n)
(Summable.mul_left _ <| summable_geometric_of_lt_one hr₀ hr₁) fun n ↦ ?_
simp only
conv_rhs => rw [mul_comm, ← zero_add N]
refine le_geom (u := fun n ↦ ‖f (n + N)‖) hr₀ n fun i _ ↦ ?_
convert hN (i + N) (N.le_add_left i) using 3
ac_rfl
· push_neg at hr₀
refine .of_norm_bounded_eventually_nat summable_zero ?_
filter_upwards [h] with _ hn
by_contra! h
exact not_lt.mpr (norm_nonneg _) (lt_of_le_of_lt hn <| mul_neg_of_neg_of_pos hr₀ h)
theorem summable_of_ratio_test_tendsto_lt_one {α : Type*} [NormedAddCommGroup α] [CompleteSpace α]
{f : ℕ → α} {l : ℝ} (hl₁ : l < 1) (hf : ∀ᶠ n in atTop, f n ≠ 0)
(h : Tendsto (fun n ↦ ‖f (n + 1)‖ / ‖f n‖) atTop (𝓝 l)) : Summable f := by
rcases exists_between hl₁ with ⟨r, hr₀, hr₁⟩
refine summable_of_ratio_norm_eventually_le hr₁ ?_
filter_upwards [h.eventually_le_const hr₀, hf] with _ _ h₁
rwa [← div_le_iff₀ (norm_pos_iff.mpr h₁)]
theorem not_summable_of_ratio_norm_eventually_ge {α : Type*} [SeminormedAddCommGroup α] {f : ℕ → α}
{r : ℝ} (hr : 1 < r) (hf : ∃ᶠ n in atTop, ‖f n‖ ≠ 0)
(h : ∀ᶠ n in atTop, r * ‖f n‖ ≤ ‖f (n + 1)‖) : ¬Summable f := by
rw [eventually_atTop] at h
rcases h with ⟨N₀, hN₀⟩
rw [frequently_atTop] at hf
rcases hf N₀ with ⟨N, hNN₀ : N₀ ≤ N, hN⟩
rw [← @summable_nat_add_iff α _ _ _ _ N]
refine mt Summable.tendsto_atTop_zero
fun h' ↦ not_tendsto_atTop_of_tendsto_nhds (tendsto_norm_zero.comp h') ?_
convert tendsto_atTop_of_geom_le _ hr _
· refine lt_of_le_of_ne (norm_nonneg _) ?_
intro h''
specialize hN₀ N hNN₀
simp only [comp_apply, zero_add] at h''
exact hN h''.symm
· grind
theorem not_summable_of_ratio_test_tendsto_gt_one {α : Type*} [SeminormedAddCommGroup α]
{f : ℕ → α} {l : ℝ} (hl : 1 < l) (h : Tendsto (fun n ↦ ‖f (n + 1)‖ / ‖f n‖) atTop (𝓝 l)) :
¬Summable f := by
have key : ∀ᶠ n in atTop, ‖f n‖ ≠ 0 := by
filter_upwards [h.eventually_const_le hl] with _ hn hc
rw [hc, _root_.div_zero] at hn
linarith
rcases exists_between hl with ⟨r, hr₀, hr₁⟩
refine not_summable_of_ratio_norm_eventually_ge hr₀ key.frequently ?_
filter_upwards [h.eventually_const_le hr₁, key] with _ _ h₁
rwa [← le_div_iff₀ (lt_of_le_of_ne (norm_nonneg _) h₁.symm)]
section NormedDivisionRing
variable [NormedDivisionRing α] [CompleteSpace α] {f : ℕ → α}
/-- If a power series converges at `w`, it converges absolutely at all `z` of smaller norm. -/
theorem summable_powerSeries_of_norm_lt {w z : α}
(h : CauchySeq fun n ↦ ∑ i ∈ range n, f i * w ^ i) (hz : ‖z‖ < ‖w‖) :
Summable fun n ↦ f n * z ^ n := by
have hw : 0 < ‖w‖ := (norm_nonneg z).trans_lt hz
obtain ⟨C, hC⟩ := exists_norm_le_of_cauchySeq h
rw [summable_iff_cauchySeq_finset]
refine cauchySeq_finset_of_geometric_bound (r := ‖z‖ / ‖w‖) (C := C) ((div_lt_one hw).mpr hz)
(fun n ↦ ?_)
rw [norm_mul, norm_pow, div_pow, ← mul_comm_div]
conv at hC => enter [n]; rw [norm_mul, norm_pow, ← _root_.le_div_iff₀ (by positivity)]
exact mul_le_mul_of_nonneg_right (hC n) (pow_nonneg (norm_nonneg z) n)
/-- If a power series converges at 1, it converges absolutely at all `z` of smaller norm. -/
theorem summable_powerSeries_of_norm_lt_one {z : α}
(h : CauchySeq fun n ↦ ∑ i ∈ range n, f i) (hz : ‖z‖ < 1) :
Summable fun n ↦ f n * z ^ n :=
summable_powerSeries_of_norm_lt (w := 1) (by simp [h]) (by simp [hz])
end NormedDivisionRing
section
/-! ### Dirichlet and alternating series tests -/
variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E]
variable {b : ℝ} {f : ℕ → ℝ} {z : ℕ → E}
/-- **Dirichlet's test** for monotone sequences. -/
theorem Monotone.cauchySeq_series_mul_of_tendsto_zero_of_bounded (hfa : Monotone f)
(hf0 : Tendsto f atTop (𝓝 0)) (hgb : ∀ n, ‖∑ i ∈ range n, z i‖ ≤ b) :
CauchySeq fun n ↦ ∑ i ∈ range n, f i • z i := by
rw [← cauchySeq_shift 1]
simp_rw [Finset.sum_range_by_parts _ _ (Nat.succ _), sub_eq_add_neg, Nat.succ_sub_succ_eq_sub,
tsub_zero]
apply (NormedField.tendsto_zero_smul_of_tendsto_zero_of_bounded hf0
⟨b, eventually_map.mpr <| Eventually.of_forall fun n ↦ hgb <| n + 1⟩).cauchySeq.add
refine CauchySeq.neg ?_
refine cauchySeq_range_of_norm_bounded ?_
(fun n ↦ ?_ : ∀ n, ‖(f (n + 1) + -f n) • (Finset.range (n + 1)).sum z‖ ≤ b * |f (n + 1) - f n|)
· simp_rw [abs_of_nonneg (sub_nonneg_of_le (hfa (Nat.le_succ _))), ← mul_sum]
apply Real.uniformContinuous_const_mul.comp_cauchySeq
simp_rw [sum_range_sub, sub_eq_add_neg]
exact (Tendsto.cauchySeq hf0).add_const
· rw [norm_smul, mul_comm]
exact mul_le_mul_of_nonneg_right (hgb _) (abs_nonneg _)
/-- **Dirichlet's test** for antitone sequences. -/
theorem Antitone.cauchySeq_series_mul_of_tendsto_zero_of_bounded (hfa : Antitone f)
(hf0 : Tendsto f atTop (𝓝 0)) (hzb : ∀ n, ‖∑ i ∈ range n, z i‖ ≤ b) :
CauchySeq fun n ↦ ∑ i ∈ range n, f i • z i := by
have hfa' : Monotone fun n ↦ -f n := fun _ _ hab ↦ neg_le_neg <| hfa hab
have hf0' : Tendsto (fun n ↦ -f n) atTop (𝓝 0) := by
convert hf0.neg
norm_num
convert (hfa'.cauchySeq_series_mul_of_tendsto_zero_of_bounded hf0' hzb).neg
simp
theorem norm_sum_neg_one_pow_le (n : ℕ) : ‖∑ i ∈ range n, (-1 : ℝ) ^ i‖ ≤ 1 := by
rw [neg_one_geom_sum]
split_ifs <;> norm_num
/-- The **alternating series test** for monotone sequences.
See also `Monotone.tendsto_alternating_series_of_tendsto_zero`. -/
theorem Monotone.cauchySeq_alternating_series_of_tendsto_zero (hfa : Monotone f)
(hf0 : Tendsto f atTop (𝓝 0)) : CauchySeq fun n ↦ ∑ i ∈ range n, (-1) ^ i * f i := by
simp_rw [mul_comm]
exact hfa.cauchySeq_series_mul_of_tendsto_zero_of_bounded hf0 norm_sum_neg_one_pow_le
/-- The **alternating series test** for monotone sequences. -/
theorem Monotone.tendsto_alternating_series_of_tendsto_zero (hfa : Monotone f)
(hf0 : Tendsto f atTop (𝓝 0)) :
∃ l, Tendsto (fun n ↦ ∑ i ∈ range n, (-1) ^ i * f i) atTop (𝓝 l) :=
cauchySeq_tendsto_of_complete <| hfa.cauchySeq_alternating_series_of_tendsto_zero hf0
/-- The **alternating series test** for antitone sequences.
See also `Antitone.tendsto_alternating_series_of_tendsto_zero`. -/
theorem Antitone.cauchySeq_alternating_series_of_tendsto_zero (hfa : Antitone f)
(hf0 : Tendsto f atTop (𝓝 0)) : CauchySeq fun n ↦ ∑ i ∈ range n, (-1) ^ i * f i := by
simp_rw [mul_comm]
exact hfa.cauchySeq_series_mul_of_tendsto_zero_of_bounded hf0 norm_sum_neg_one_pow_le
/-- The **alternating series test** for antitone sequences. -/
theorem Antitone.tendsto_alternating_series_of_tendsto_zero (hfa : Antitone f)
(hf0 : Tendsto f atTop (𝓝 0)) :
∃ l, Tendsto (fun n ↦ ∑ i ∈ range n, (-1) ^ i * f i) atTop (𝓝 l) :=
cauchySeq_tendsto_of_complete <| hfa.cauchySeq_alternating_series_of_tendsto_zero hf0
end
/-! ### Partial sum bounds on alternating convergent series -/
section
variable {E : Type*} [Ring E] [PartialOrder E] [IsOrderedRing E]
[TopologicalSpace E] [OrderClosedTopology E]
{l : E} {f : ℕ → E}
/-- Partial sums of an alternating monotone series with an even number of terms provide
upper bounds on the limit. -/
theorem Monotone.tendsto_le_alternating_series
(hfl : Tendsto (fun n ↦ ∑ i ∈ range n, (-1) ^ i * f i) atTop (𝓝 l))
(hfm : Monotone f) (k : ℕ) : l ≤ ∑ i ∈ range (2 * k), (-1) ^ i * f i := by
have ha : Antitone (fun n ↦ ∑ i ∈ range (2 * n), (-1) ^ i * f i) := by
refine antitone_nat_of_succ_le (fun n ↦ ?_)
rw [show 2 * (n + 1) = 2 * n + 1 + 1 by ring, sum_range_succ, sum_range_succ]
simp_rw [_root_.pow_succ', show (-1 : E) ^ (2 * n) = 1 by simp, neg_one_mul, one_mul,
← sub_eq_add_neg, sub_le_iff_le_add]
gcongr
exact hfm (by omega)
exact ha.le_of_tendsto (hfl.comp (tendsto_atTop_mono (fun n ↦ by dsimp; omega) tendsto_id)) _
/-- Partial sums of an alternating monotone series with an odd number of terms provide
lower bounds on the limit. -/
theorem Monotone.alternating_series_le_tendsto
(hfl : Tendsto (fun n ↦ ∑ i ∈ range n, (-1) ^ i * f i) atTop (𝓝 l))
(hfm : Monotone f) (k : ℕ) : ∑ i ∈ range (2 * k + 1), (-1) ^ i * f i ≤ l := by
have hm : Monotone (fun n ↦ ∑ i ∈ range (2 * n + 1), (-1) ^ i * f i) := by
refine monotone_nat_of_le_succ (fun n ↦ ?_)
rw [show 2 * (n + 1) = 2 * n + 1 + 1 by ring,
sum_range_succ _ (2 * n + 1 + 1), sum_range_succ _ (2 * n + 1)]
simp_rw [_root_.pow_succ', show (-1 : E) ^ (2 * n) = 1 by simp, neg_one_mul, neg_neg, one_mul,
← sub_eq_add_neg, sub_add_eq_add_sub, le_sub_iff_add_le]
gcongr
exact hfm (by omega)
exact hm.ge_of_tendsto (hfl.comp (tendsto_atTop_mono (fun n ↦ by dsimp; omega) tendsto_id)) _
/-- Partial sums of an alternating antitone series with an even number of terms provide
lower bounds on the limit. -/
theorem Antitone.alternating_series_le_tendsto
(hfl : Tendsto (fun n ↦ ∑ i ∈ range n, (-1) ^ i * f i) atTop (𝓝 l))
(hfa : Antitone f) (k : ℕ) : ∑ i ∈ range (2 * k), (-1) ^ i * f i ≤ l := by
have hm : Monotone (fun n ↦ ∑ i ∈ range (2 * n), (-1) ^ i * f i) := by
refine monotone_nat_of_le_succ (fun n ↦ ?_)
rw [show 2 * (n + 1) = 2 * n + 1 + 1 by ring, sum_range_succ, sum_range_succ]
simp_rw [_root_.pow_succ', show (-1 : E) ^ (2 * n) = 1 by simp, neg_one_mul, one_mul,
← sub_eq_add_neg, le_sub_iff_add_le]
gcongr
exact hfa (by omega)
exact hm.ge_of_tendsto (hfl.comp (tendsto_atTop_mono (fun n ↦ by dsimp; omega) tendsto_id)) _
/-- Partial sums of an alternating antitone series with an odd number of terms provide
upper bounds on the limit. -/
theorem Antitone.tendsto_le_alternating_series
(hfl : Tendsto (fun n ↦ ∑ i ∈ range n, (-1) ^ i * f i) atTop (𝓝 l))
(hfa : Antitone f) (k : ℕ) : l ≤ ∑ i ∈ range (2 * k + 1), (-1) ^ i * f i := by
have ha : Antitone (fun n ↦ ∑ i ∈ range (2 * n + 1), (-1) ^ i * f i) := by
refine antitone_nat_of_succ_le (fun n ↦ ?_)
rw [show 2 * (n + 1) = 2 * n + 1 + 1 by ring, sum_range_succ, sum_range_succ]
simp_rw [_root_.pow_succ', show (-1 : E) ^ (2 * n) = 1 by simp, neg_one_mul, neg_neg, one_mul,
← sub_eq_add_neg, sub_add_eq_add_sub, sub_le_iff_le_add]
gcongr
exact hfa (by omega)
exact ha.le_of_tendsto (hfl.comp (tendsto_atTop_mono (fun n ↦ by dsimp; omega) tendsto_id)) _
end
/-!
### Factorial
-/
/-- The series `∑' n, x ^ n / n!` is summable of any `x : ℝ`. See also `expSeries_div_summable`
for a version that also works in `ℂ`, and `NormedSpace.expSeries_summable'` for a version
that works in any normed algebra over `ℝ` or `ℂ`. -/
theorem Real.summable_pow_div_factorial (x : ℝ) : Summable (fun n ↦ x ^ n / n ! : ℕ → ℝ) := by
-- We start with trivial estimates
have A : (0 : ℝ) < ⌊‖x‖⌋₊ + 1 := zero_lt_one.trans_le (by simp)
have B : ‖x‖ / (⌊‖x‖⌋₊ + 1) < 1 := (div_lt_one A).2 (Nat.lt_floor_add_one _)
-- Then we apply the ratio test. The estimate works for `n ≥ ⌊‖x‖⌋₊`.
suffices ∀ n ≥ ⌊‖x‖⌋₊, ‖x ^ (n + 1) / (n + 1)!‖ ≤ ‖x‖ / (⌊‖x‖⌋₊ + 1) * ‖x ^ n / ↑n !‖ from
summable_of_ratio_norm_eventually_le B (eventually_atTop.2 ⟨⌊‖x‖⌋₊, this⟩)
-- Finally, we prove the upper estimate
intro n hn
calc
‖x ^ (n + 1) / (n + 1)!‖ = ‖x‖ / (n + 1) * ‖x ^ n / (n !)‖ := by
rw [_root_.pow_succ', Nat.factorial_succ, Nat.cast_mul, ← _root_.div_mul_div_comm, norm_mul,
norm_div, Real.norm_natCast, Nat.cast_succ]
_ ≤ ‖x‖ / (⌊‖x‖⌋₊ + 1) * ‖x ^ n / (n !)‖ := by gcongr
section
/-! Limits when `f x * g x` is bounded or convergent and `f` tends to the `cobounded` filter. -/
open Bornology
variable {R K : Type*}
lemma tendsto_zero_of_isBoundedUnder_smul_of_tendsto_cobounded [NormedAddGroup K]
[NormedAddGroup R] [SMulWithZero K R] [NoZeroSMulDivisors K R] [NormSMulClass K R]
{f : α → K} {g : α → R} {l : Filter α}
(hmul : IsBoundedUnder (· ≤ ·) l fun x ↦ ‖f x • g x‖)
(hf : Tendsto f l (cobounded K)) :
Tendsto g l (𝓝 0) := by
obtain ⟨c, hc⟩ := hmul.eventually_le
refine Metric.nhds_basis_closedBall.tendsto_right_iff.mpr fun ε hε0 ↦ ?_
filter_upwards [hc, hasBasis_cobounded_norm.tendsto_right_iff.mp hf (c / ε) trivial,
hf.eventually_ne_cobounded 0] with x hfgc hεf hf0
rcases eq_or_lt_of_le ((norm_nonneg _).trans hfgc) with rfl | hc0
· simpa [(smul_eq_zero_iff_right hf0).mp (norm_le_zero_iff.mp hfgc)] using hε0.le
calc
_ = ‖g x‖ := by simp
_ ≤ c / ‖f x‖ := by rwa [norm_smul, ← le_div_iff₀' (by positivity)] at hfgc
_ ≤ c / (c / ε) := by gcongr
_ = ε := div_div_cancel₀ hc0.ne'
section
variable [NormedRing K] [NormedAddCommGroup R]
variable [Module K R] [NoZeroSMulDivisors K R] [NormSMulClass K R]
lemma tendsto_smul_congr_of_tendsto_left_cobounded_of_isBoundedUnder
{f₁ f₂ : α → K} {g : α → R} {t : R} {l : Filter α}
(hmul : Tendsto (fun x ↦ f₁ x • g x) l (𝓝 t))
(hf₁ : Tendsto f₁ l (cobounded K))
(hbdd : IsBoundedUnder (· ≤ ·) l fun x ↦ ‖f₁ x - f₂ x‖) :
Tendsto (fun x ↦ f₂ x • g x) l (𝓝 t) := by
apply hmul.congr_dist
dsimp
simp_rw [dist_eq_norm, ← sub_smul, norm_smul]
apply isBoundedUnder_le_mul_tendsto_zero
· change IsBoundedUnder _ _ fun _ ↦ _
simpa using hbdd
· rw [← tendsto_zero_iff_norm_tendsto_zero]
exact tendsto_zero_of_isBoundedUnder_smul_of_tendsto_cobounded hmul.norm.isBoundedUnder_le hf₁
-- The use case in mind for this is when `K = ℝ`, and `R = ℝ` or `ℂ`
lemma tendsto_smul_comp_nat_floor_of_tendsto_nsmul [NormSMulClass ℤ K] [LinearOrder K]
[IsStrictOrderedRing K] [FloorSemiring K] [HasSolidNorm K] {g : ℕ → R} {t : R}
(hg : Tendsto (fun n : ℕ ↦ n • g n) atTop (𝓝 t)) :
Tendsto (fun x : K ↦ x • g ⌊x⌋₊) atTop (𝓝 t) := by
replace hg : Tendsto (fun n : ℕ ↦ (n : K) • g n) atTop (𝓝 t) := mod_cast hg
apply tendsto_smul_congr_of_tendsto_left_cobounded_of_isBoundedUnder
(hg.comp tendsto_nat_floor_atTop)
· exact tendsto_natCast_atTop_cobounded.comp tendsto_nat_floor_atTop
· apply isBoundedUnder_of_eventually_le (a := ‖(1 : K)‖)
apply Eventually.mono _ (fun x h ↦ norm_le_norm_of_abs_le_abs h)
simpa using ⟨0, fun _ h ↦ mod_cast Nat.abs_floor_sub_le h⟩
end
lemma tendsto_smul_comp_nat_floor_of_tendsto_mul [NormedRing K] [NormedRing R]
[Module K R] [NoZeroSMulDivisors K R] [NormSMulClass K R] [NormSMulClass ℤ K] [LinearOrder K]
[IsStrictOrderedRing K] [FloorSemiring K] [HasSolidNorm K] {g : ℕ → R} {t : R}
(hg : Tendsto (fun n : ℕ ↦ (n : R) * g n) atTop (𝓝 t)) :
Tendsto (fun x : K ↦ x • g ⌊x⌋₊) atTop (𝓝 t) :=
tendsto_smul_comp_nat_floor_of_tendsto_nsmul (by simpa only [nsmul_eq_mul] using hg)
end
|
BigOperators.lean
|
/-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import Mathlib.Algebra.BigOperators.Group.Finset.Preimage
import Mathlib.Order.Filter.AtTopBot.Basic
/-!
# Two lemmas about limit of `Π b ∈ s, f b` along
In this file we prove two auxiliary lemmas
about `Filter.atTop : Filter (Finset _)` and `∏ b ∈ s, f b`.
These lemmas are useful to build the theory of absolutely convergent series.
-/
open Filter Finset
variable {α β M : Type*} [CommMonoid M]
/-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient
condition for comparison of the filter `atTop.map (fun s ↦ ∏ b ∈ s, f b)` with
`atTop.map (fun s ↦ ∏ b ∈ s, g b)`. This is useful to compare the set of limit points of
`Π b in s, f b` as `s → atTop` with the similar set for `g`. -/
@[to_additive /-- Let `f` and `g` be two maps to the same commutative additive monoid. This lemma
gives a sufficient condition for comparison of the filter `atTop.map (fun s ↦ ∑ b ∈ s, f b)` with
`atTop.map (fun s ↦ ∑ b ∈ s, g b)`. This is useful to compare the set of limit points of
`∑ b ∈ s, f b` as `s → atTop` with the similar set for `g`. -/]
theorem Filter.map_atTop_finset_prod_le_of_prod_eq {f : α → M} {g : β → M}
(h_eq : ∀ u : Finset β,
∃ v : Finset α, ∀ v', v ⊆ v' → ∃ u', u ⊆ u' ∧ ∏ x ∈ u', g x = ∏ b ∈ v', f b) :
(atTop.map fun s : Finset α => ∏ b ∈ s, f b) ≤
atTop.map fun s : Finset β => ∏ x ∈ s, g x := by
classical
refine ((atTop_basis.map _).le_basis_iff (atTop_basis.map _)).2 fun b _ => ?_
let ⟨v, hv⟩ := h_eq b
refine ⟨v, trivial, ?_⟩
simpa [Finset.image_subset_iff] using hv
/-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g`
to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters
`atTop.map (fun s ↦ ∏ i ∈ s, f (g i))` and `atTop.map (fun s ↦ ∏ i ∈ s, f i)` coincide.
The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under
the same assumptions. -/
@[to_additive]
theorem Function.Injective.map_atTop_finset_prod_eq {g : α → β}
(hg : Function.Injective g) {f : β → M} (hf : ∀ x, x ∉ Set.range g → f x = 1) :
map (fun s => ∏ i ∈ s, f (g i)) atTop = map (fun s => ∏ i ∈ s, f i) atTop := by
haveI := Classical.decEq β
apply le_antisymm <;> refine map_atTop_finset_prod_le_of_prod_eq fun s => ?_
· refine ⟨s.preimage g hg.injOn, fun t ht => ?_⟩
refine ⟨t.image g ∪ s, Finset.subset_union_right, ?_⟩
rw [← Finset.prod_image hg.injOn]
refine (prod_subset subset_union_left ?_).symm
simp only [Finset.mem_union, Finset.mem_image]
refine fun y hy hyt => hf y (mt ?_ hyt)
rintro ⟨x, rfl⟩
exact ⟨x, ht (Finset.mem_preimage.2 <| hy.resolve_left hyt), rfl⟩
· refine ⟨s.image g, fun t ht => ?_⟩
simp only [← prod_preimage _ _ hg.injOn _ fun x _ => hf x]
exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩
/-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g`
to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the
filters `atTop.map (fun s ↦ ∑ i ∈ s, f (g i))` and `atTop.map (fun s ↦ ∑ i ∈ s, f i)` coincide.
This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under
the same assumptions. -/
add_decl_doc Function.Injective.map_atTop_finset_sum_eq
|
fingraph.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat.
From mathcomp Require Import seq path fintype.
(******************************************************************************)
(* This file develops the theory of finite graphs represented by an "edge" *)
(* relation over a finType T; this mainly amounts to the theory of the *)
(* transitive closure of such relations. *)
(* For g : T -> seq T, e : rel T and f : T -> T we define: *)
(* grel g == the adjacency relation y \in g x of the graph g. *)
(* rgraph e == the graph (x |-> enum (e x)) of the relation e. *)
(* dfs g n v x == the list of points traversed by a depth-first search of *)
(* the g, at depth n, starting from x, and avoiding v. *)
(* dfs_path g v x y <-> there is a path from x to y in g \ v. *)
(* connect e == the reflexive transitive closure of e (computed by dfs). *)
(* connect_sym e <-> connect e is symmetric, hence an equivalence relation. *)
(* root e x == a representative of connect e x, which is the component *)
(* of x in the transitive closure of e. *)
(* roots e == the codomain predicate of root e. *)
(* n_comp e a == the number of e-connected components of a, when a is *)
(* e-closed and connect e is symmetric. *)
(* equivalence classes of connect e if connect_sym e holds. *)
(* closed e a == the collective predicate a is e-invariant. *)
(* closure e a == the e-closure of a (the image of a under connect e). *)
(* rel_adjunction h e e' a <-> in the e-closed domain a, h is the left part *)
(* of an adjunction from e to another relation e'. *)
(* fconnect f == connect (frel f), i.e., "connected under f iteration". *)
(* froot f x == root (frel f) x, the root of the orbit of x under f. *)
(* froots f == roots (frel f) == orbit representatives for f. *)
(* orbit f x == lists the f-orbit of x. *)
(* findex f x y == index of y in the f-orbit of x. *)
(* order f x == size (cardinal) of the f-orbit of x. *)
(* order_set f n == elements of f-order n. *)
(* finv f == the inverse of f, if f is injective. *)
(* := finv f x := iter (order x).-1 f x. *)
(* fcard f a == number of orbits of f in a, provided a is f-invariant *)
(* f is one-to-one. *)
(* fclosed f a == the collective predicate a is f-invariant. *)
(* fclosure f a == the closure of a under f iteration. *)
(* fun_adjunction == rel_adjunction (frel f). *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Definition grel (T : eqType) (g : T -> seq T) := [rel x y | y \in g x].
(* Decidable connectivity in finite types. *)
Section Connect.
Variable T : finType.
Section Dfs.
Variable g : T -> seq T.
Implicit Type v w a : seq T.
Fixpoint dfs n v x :=
if x \in v then v else
if n is n'.+1 then foldl (dfs n') (x :: v) (g x) else v.
Lemma subset_dfs n v a : v \subset foldl (dfs n) v a.
Proof.
elim: n a v => [|n IHn]; first by elim=> //= *; rewrite if_same.
elim=> //= x a IHa v; apply: subset_trans {IHa}(IHa _); case: ifP => // _.
by apply: subset_trans (IHn _ _); apply/subsetP=> y; apply: predU1r.
Qed.
Inductive dfs_path v x y : Prop :=
DfsPath p of path (grel g) x p & y = last x p & [disjoint x :: p & v].
Lemma dfs_pathP n x y v :
#|T| <= #|v| + n -> y \notin v -> reflect (dfs_path v x y) (y \in dfs n v x).
Proof.
have dfs_id w z: z \notin w -> dfs_path w z z.
by exists [::]; rewrite ?disjoint_has //= orbF.
elim: n => [|n IHn] /= in x y v * => le_v'_n not_vy.
rewrite addn0 (geq_leqif (subset_leqif_card (subset_predT _))) in le_v'_n.
by rewrite predT_subset in not_vy.
have [v_x | not_vx] := ifPn.
by rewrite (negPf not_vy); right=> [] [p _ _]; rewrite disjoint_has /= v_x.
set v1 := x :: v; set a := g x; have sub_dfs := subsetP (subset_dfs n _ _).
have [-> | neq_yx] := eqVneq y x.
by rewrite sub_dfs ?mem_head //; left; apply: dfs_id.
apply: (@equivP (exists2 x1, x1 \in a & dfs_path v1 x1 y)); last first.
split=> {IHn} [[x1 a_x1 [p g_p p_y]] | [p /shortenP[]]].
rewrite disjoint_has has_sym /= has_sym /= => /norP[_ not_pv].
by exists (x1 :: p); rewrite /= ?a_x1 // disjoint_has negb_or not_vx.
case=> [_ _ _ eq_yx | x1 p1 /=]; first by case/eqP: neq_yx.
case/andP=> a_x1 g_p1 /andP[not_p1x _] /subsetP p_p1 p1y not_pv.
exists x1 => //; exists p1 => //.
rewrite disjoint_sym disjoint_cons not_p1x disjoint_sym.
by move: not_pv; rewrite disjoint_cons => /andP[_ /disjointWl->].
have{neq_yx not_vy}: y \notin v1 by apply/norP.
have{le_v'_n not_vx}: #|T| <= #|v1| + n by rewrite cardU1 not_vx addSnnS.
elim: {x v}a v1 => [|x a IHa] v /= le_v'_n not_vy.
by rewrite (negPf not_vy); right=> [] [].
set v2 := dfs n v x; have v2v: v \subset v2 := subset_dfs n v [:: x].
have [v2y | not_v2y] := boolP (y \in v2).
by rewrite sub_dfs //; left; exists x; [apply: mem_head | apply: IHn].
apply: {IHa}(equivP (IHa _ _ not_v2y)).
by rewrite (leq_trans le_v'_n) // leq_add2r subset_leq_card.
split=> [] [x1 a_x1 [p g_p p_y not_pv]].
exists x1; [exact: predU1r | exists p => //].
by rewrite disjoint_sym (disjointWl v2v) // disjoint_sym.
suffices not_p1v2: [disjoint x1 :: p & v2].
case/predU1P: a_x1 => [def_x1 | ]; last by exists x1; last exists p.
case/pred0Pn: not_p1v2; exists x; rewrite /= def_x1 mem_head /=.
suffices not_vx: x \notin v by apply/IHn; last apply: dfs_id.
by move: not_pv; rewrite disjoint_cons def_x1 => /andP[].
apply: contraR not_v2y => /pred0Pn[x2 /andP[/= p_x2 v2x2]].
case/splitPl: p_x2 p_y g_p not_pv => p0 p2 p0x2.
rewrite last_cat cat_path -cat_cons lastI cat_rcons {}p0x2 => p2y /andP[_ g_p2].
rewrite disjoint_cat disjoint_cons => /and3P[{p0}_ not_vx2 not_p2v].
have{not_vx2 v2x2} [p1 g_p1 p1_x2 not_p1v] := IHn _ _ v le_v'_n not_vx2 v2x2.
apply/IHn=> //; exists (p1 ++ p2); rewrite ?cat_path ?last_cat -?p1_x2 ?g_p1 //.
by rewrite -cat_cons disjoint_cat not_p1v.
Qed.
Lemma dfsP x y :
reflect (exists2 p, path (grel g) x p & y = last x p) (y \in dfs #|T| [::] x).
Proof.
apply: (iffP (dfs_pathP _ _ _)); rewrite ?card0 // => [] [p]; exists p => //.
by rewrite disjoint_sym disjoint0.
Qed.
End Dfs.
Variable e : rel T.
Definition rgraph x := enum (e x).
Lemma rgraphK : grel rgraph =2 e.
Proof. by move=> x y; rewrite /= mem_enum. Qed.
Definition connect : rel T := [rel x y | y \in dfs rgraph #|T| [::] x].
Canonical connect_app_pred x := ApplicativePred (connect x).
Lemma connectP x y :
reflect (exists2 p, path e x p & y = last x p) (connect x y).
Proof.
apply: (equivP (dfsP _ x y)).
by split=> [] [p e_p ->]; exists p => //; rewrite (eq_path rgraphK) in e_p *.
Qed.
Lemma connect_trans : transitive connect.
Proof.
move=> x y z /connectP[p e_p ->] /connectP[q e_q ->]; apply/connectP.
by exists (p ++ q); rewrite ?cat_path ?e_p ?last_cat.
Qed.
Lemma connect0 x : connect x x.
Proof. by apply/connectP; exists [::]. Qed.
Lemma eq_connect0 x y : x = y -> connect x y.
Proof. by move->; apply: connect0. Qed.
Lemma connect1 x y : e x y -> connect x y.
Proof. by move=> e_xy; apply/connectP; exists [:: y]; rewrite /= ?e_xy. Qed.
Lemma path_connect x p : path e x p -> subpred [in x :: p] (connect x).
Proof.
move=> e_p y p_y; case/splitPl: p / p_y e_p => p q <-.
by rewrite cat_path => /andP[e_p _]; apply/connectP; exists p.
Qed.
Lemma connect_cycle p : cycle e p -> {in p &, forall x y, connect x y}.
Proof.
move=> e_p x y /rot_to[i q rip]; rewrite -(mem_rot i) rip => yqx.
have /= : cycle e (x :: q) by rewrite -rip rot_cycle.
case/splitPl: yqx => r s lxr; rewrite rcons_cat cat_path => /andP[xr _].
by apply/connectP; exists r.
Qed.
Definition root x := odflt x (pick (connect x)).
Definition roots : pred T := fun x => root x == x.
Canonical roots_pred := ApplicativePred roots.
Definition n_comp_mem (m_a : mem_pred T) := #|predI roots m_a|.
Lemma connect_root x : connect x (root x).
Proof. by rewrite /root; case: pickP; rewrite ?connect0. Qed.
Definition connect_sym := symmetric connect.
Hypothesis sym_e : connect_sym.
Lemma same_connect : left_transitive connect.
Proof. exact: sym_left_transitive connect_trans. Qed.
Lemma same_connect_r : right_transitive connect.
Proof. exact: sym_right_transitive connect_trans. Qed.
Lemma same_connect1 x y : e x y -> connect x =1 connect y.
Proof. by move/connect1; apply: same_connect. Qed.
Lemma same_connect1r x y : e x y -> connect^~ x =1 connect^~ y.
Proof. by move/connect1; apply: same_connect_r. Qed.
Lemma rootP x y : reflect (root x = root y) (connect x y).
Proof.
apply: (iffP idP) => e_xy.
by rewrite /root -(eq_pick (same_connect e_xy)); case: pickP e_xy => // ->.
by apply: (connect_trans (connect_root x)); rewrite e_xy sym_e connect_root.
Qed.
Lemma root_root x : root (root x) = root x.
Proof. exact/esym/rootP/connect_root. Qed.
Lemma roots_root x : roots (root x).
Proof. exact/eqP/root_root. Qed.
Lemma root_connect x y : (root x == root y) = connect x y.
Proof. exact: sameP eqP (rootP x y). Qed.
Definition closed_mem m_a := forall x y, e x y -> in_mem x m_a = in_mem y m_a.
Definition closure_mem m_a : pred T :=
fun x => ~~ disjoint (mem (connect x)) m_a.
End Connect.
Arguments rgraphK [T].
#[global] Hint Resolve connect0 : core.
Notation n_comp e a := (n_comp_mem e (mem a)).
Notation closed e a := (closed_mem e (mem a)).
Notation closure e a := (closure_mem e (mem a)).
Prenex Implicits connect root roots.
Arguments dfsP {T g x y}.
Arguments connectP {T e x y}.
Arguments rootP [T e] _ {x y}.
Notation fconnect f := (connect (coerced_frel f)).
Notation froot f := (root (coerced_frel f)).
Notation froots f := (roots (coerced_frel f)).
Notation fcard_mem f := (n_comp_mem (coerced_frel f)).
Notation fcard f a := (fcard_mem f (mem a)).
Notation fclosed f a := (closed (coerced_frel f) a).
Notation fclosure f a := (closure (coerced_frel f) a).
Section EqConnect.
Variable T : finType.
Implicit Types (e : rel T) (a : {pred T}).
Lemma connect_sub e e' :
subrel e (connect e') -> subrel (connect e) (connect e').
Proof.
move=> e'e x _ /connectP[p e_p ->]; elim: p x e_p => //= y p IHp x /andP[exy].
by move/IHp; apply: connect_trans; apply: e'e.
Qed.
Lemma relU_sym e e' :
connect_sym e -> connect_sym e' -> connect_sym (relU e e').
Proof.
move=> sym_e sym_e'; apply: symmetric_from_pre => x _ /connectP[p e_p ->].
elim: p x e_p => //= y p IHp x /andP[e_xy /IHp{IHp}/connect_trans]; apply.
case/orP: e_xy => /connect1; rewrite (sym_e, sym_e');
by apply: connect_sub y x => x y e_xy; rewrite connect1 //= e_xy ?orbT.
Qed.
Lemma eq_connect e e' : e =2 e' -> connect e =2 connect e'.
Proof.
move=> eq_e x y; apply/connectP/connectP=> [] [p e_p ->];
by exists p; rewrite // (eq_path eq_e) in e_p *.
Qed.
Arguments eq_connect [e e'].
Lemma eq_n_comp e e' : connect e =2 connect e' -> n_comp_mem e =1 n_comp_mem e'.
Proof.
move=> eq_e [a]; apply: eq_card => x /=.
by rewrite !inE /= /roots /root /= (eq_pick (eq_e x)).
Qed.
Lemma eq_n_comp_r {e} a a' : a =i a' -> n_comp e a = n_comp e a'.
Proof. by move=> eq_a; apply: eq_card => x; rewrite inE /= eq_a. Qed.
Lemma n_compC a e : n_comp e T = n_comp e a + n_comp e [predC a].
Proof.
rewrite /n_comp_mem (eq_card (fun _ => andbT _)) -(cardID a); congr (_ + _).
by apply: eq_card => x; rewrite !inE andbC.
Qed.
Lemma eq_root e e' : e =2 e' -> root e =1 root e'.
Proof. by move=> eq_e x; rewrite /root (eq_pick (eq_connect eq_e x)). Qed.
Lemma eq_roots e e' : e =2 e' -> roots e =1 roots e'.
Proof. by move=> eq_e x; rewrite /roots (eq_root eq_e). Qed.
Lemma connect_rev e : connect [rel x y | e y x] =2 [rel x y | connect e y x].
Proof.
suff crev e': subrel (connect [rel x y | e' y x]) [rel x y | connect e' y x].
by move=> x y; apply/idP/idP; apply: crev.
move=> x y /connectP[p e_p p_y]; apply/connectP.
exists (rev (belast x p)); first by rewrite p_y rev_path.
by rewrite -(last_cons x) -rev_rcons p_y -lastI rev_cons last_rcons.
Qed.
Lemma sym_connect_sym e : symmetric e -> connect_sym e.
Proof. by move=> sym_e x y; rewrite (eq_connect sym_e) connect_rev. Qed.
End EqConnect.
Arguments eq_connect [T e e'].
Arguments connect_rev [T].
Section Closure.
Variables (T : finType) (e : rel T).
Hypothesis sym_e : connect_sym e.
Implicit Type a : {pred T}.
Lemma same_connect_rev : connect e =2 connect [rel x y | e y x].
Proof. by move=> x y; rewrite sym_e connect_rev. Qed.
Lemma intro_closed a : (forall x y, e x y -> x \in a -> y \in a) -> closed e a.
Proof.
move=> cl_a x y e_xy; apply/idP/idP=> [|a_y]; first exact: cl_a.
have{x e_xy} /connectP[p e_p ->]: connect e y x by rewrite sym_e connect1.
by elim: p y a_y e_p => //= y p IHp x a_x /andP[/cl_a/(_ a_x)]; apply: IHp.
Qed.
Lemma closed_connect a :
closed e a -> forall x y, connect e x y -> (x \in a) = (y \in a).
Proof.
move=> cl_a x _ /connectP[p e_p ->].
by elim: p x e_p => //= y p IHp x /andP[/cl_a->]; apply: IHp.
Qed.
Lemma connect_closed x : closed e (connect e x).
Proof. by move=> y z /connect1/same_connect_r; apply. Qed.
Lemma predC_closed a : closed e a -> closed e [predC a].
Proof. by move=> cl_a x y /cl_a /[!inE] ->. Qed.
Lemma closure_closed a : closed e (closure e a).
Proof.
apply: intro_closed => x y /connect1 e_xy; congr (~~ _).
by apply: eq_disjoint; apply: same_connect.
Qed.
Lemma mem_closure a : {subset a <= closure e a}.
Proof. by move=> x a_x; apply/existsP; exists x; rewrite !inE connect0. Qed.
Lemma subset_closure a : a \subset closure e a.
Proof. by apply/subsetP; apply: mem_closure. Qed.
Lemma n_comp_closure2 x y :
n_comp e (closure e (pred2 x y)) = (~~ connect e x y).+1.
Proof.
rewrite -(root_connect sym_e) -card2; apply: eq_card => z.
apply/idP/idP=> [/andP[/eqP {2}<- /pred0Pn[t /andP[/= ezt exyt]]] |].
by case/pred2P: exyt => <-; rewrite (rootP sym_e ezt) !inE eqxx ?orbT.
by case/pred2P=> ->; rewrite !inE roots_root //; apply/existsP;
[exists x | exists y]; rewrite !inE eqxx ?orbT sym_e connect_root.
Qed.
Lemma n_comp_connect x : n_comp e (connect e x) = 1.
Proof.
rewrite -(card1 (root e x)); apply: eq_card => y.
apply/andP/eqP => [[/eqP r_y /rootP-> //] | ->] /=.
by rewrite inE connect_root roots_root.
Qed.
End Closure.
Arguments same_connect_rev [T e].
Section Orbit.
Variables (T : finType) (f : T -> T).
Definition order x := #|fconnect f x|.
Definition orbit x := traject f x (order x).
Definition findex x y := index y (orbit x).
Definition finv x := iter (order x).-1 f x.
Lemma fconnect_iter n x : fconnect f x (iter n f x).
Proof.
apply/connectP.
by exists (traject f (f x) n); [apply: fpath_traject | rewrite last_traject].
Qed.
Lemma fconnect1 x : fconnect f x (f x).
Proof. exact: (fconnect_iter 1). Qed.
Lemma fconnect_finv x : fconnect f x (finv x).
Proof. exact: fconnect_iter. Qed.
Lemma orderSpred x : (order x).-1.+1 = order x.
Proof. by rewrite /order (cardD1 x) [_ x _]connect0. Qed.
Lemma size_orbit x : size (orbit x) = order x.
Proof. exact: size_traject. Qed.
Lemma looping_order x : looping f x (order x).
Proof.
apply: contraFT (ltnn (order x)); rewrite -looping_uniq => /card_uniqP.
rewrite size_traject => <-; apply: subset_leq_card.
by apply/subsetP=> _ /trajectP[i _ ->]; apply: fconnect_iter.
Qed.
Lemma fconnect_orbit x y : fconnect f x y = (y \in orbit x).
Proof.
apply/idP/idP=> [/connectP[_ /fpathP[m ->] ->] | /trajectP[i _ ->]].
by rewrite last_traject; apply/loopingP/looping_order.
exact: fconnect_iter.
Qed.
Lemma in_orbit x : x \in orbit x. Proof. by rewrite -fconnect_orbit. Qed.
Hint Resolve in_orbit : core.
Lemma order_gt0 x : order x > 0. Proof. by rewrite -orderSpred. Qed.
Hint Resolve order_gt0 : core.
Lemma orbit_uniq x : uniq (orbit x).
Proof.
rewrite /orbit -orderSpred looping_uniq; set n := (order x).-1.
apply: contraFN (ltnn n) => /trajectP[i lt_i_n eq_fnx_fix].
rewrite orderSpred -(size_traject f x n).
apply: (leq_trans (subset_leq_card _) (card_size _)); apply/subsetP=> z.
rewrite inE fconnect_orbit => /trajectP[j le_jn ->{z}].
rewrite -orderSpred -/n ltnS leq_eqVlt in le_jn.
by apply/trajectP; case/predU1P: le_jn => [->|]; [exists i | exists j].
Qed.
Lemma findex_max x y : fconnect f x y -> findex x y < order x.
Proof. by rewrite [_ y]fconnect_orbit -index_mem size_orbit. Qed.
Lemma findex_iter x i : i < order x -> findex x (iter i f x) = i.
Proof.
move=> lt_ix; rewrite -(nth_traject f lt_ix) /findex index_uniq ?orbit_uniq //.
by rewrite size_orbit.
Qed.
Lemma iter_findex x y : fconnect f x y -> iter (findex x y) f x = y.
Proof.
rewrite [_ y]fconnect_orbit => fxy; pose i := index y (orbit x).
have lt_ix: i < order x by rewrite -size_orbit index_mem.
by rewrite -(nth_traject f lt_ix) nth_index.
Qed.
Lemma findex0 x : findex x x = 0.
Proof. by rewrite /findex /orbit -orderSpred /= eqxx. Qed.
Lemma findex_eq0 x y : (findex x y == 0) = (x == y).
Proof. by rewrite /findex /orbit -orderSpred /=; case: (x == y). Qed.
Lemma fconnect_invariant (T' : eqType) (k : T -> T') :
invariant f k =1 xpredT -> forall x y, fconnect f x y -> k x = k y.
Proof.
move=> eq_k_f x y /iter_findex <-; elim: {y}(findex x y) => //= n ->.
by rewrite (eqP (eq_k_f _)).
Qed.
Lemma mem_orbit x : {homo f : y / y \in orbit x}.
Proof.
by move=> y; rewrite -!fconnect_orbit => /connect_trans->//; apply: fconnect1.
Qed.
Lemma image_orbit x : {subset image f (orbit x) <= orbit x}.
Proof.
by move=> _ /mapP[y yin ->]; apply: mem_orbit; rewrite ?mem_enum in yin.
Qed.
Section orbit_in.
Variable S : {pred T}.
Hypothesis f_in : {homo f : x / x \in S}.
Hypothesis injf : {in S &, injective f}.
Lemma finv_in : {homo finv : x / x \in S}.
Proof. by move=> x xS; rewrite iter_in. Qed.
Lemma f_finv_in : {in S, cancel finv f}.
Proof.
move=> x xS; move: (looping_order x) (orbit_uniq x).
rewrite /looping /orbit -orderSpred looping_uniq /= /looping; set n := _.-1.
case/predU1P=> // /trajectP[i lt_i_n]; rewrite -iterSr.
by move=> /injf ->; rewrite ?(iter_in _ f_in) //; case/trajectP; exists i.
Qed.
Lemma finv_f_in : {in S, cancel f finv}.
Proof. by move=> x xS; apply/injf; rewrite ?iter_in ?f_finv_in ?f_in. Qed.
Lemma finv_inj_in : {in S &, injective finv}.
Proof. by move=> x y xS yS q; rewrite -(f_finv_in xS) q f_finv_in. Qed.
Lemma fconnect_sym_in : {in S &, forall x y, fconnect f x y = fconnect f y x}.
Proof.
suff Sf : {in S &, forall x y, fconnect f x y -> fconnect f y x}.
by move=> *; apply/idP/idP=> /Sf->.
move=> x _ xS _ /connectP [p f_p ->]; elim: p => //= y p IHp in x xS f_p *.
case/andP: f_p => /eqP <- /(IHp _ (f_in xS)) /connect_trans -> //.
by apply: (connect_trans (fconnect_finv _)); rewrite finv_f_in.
Qed.
Lemma iter_order_in : {in S, forall x, iter (order x) f x = x}.
Proof. by move=> x xS; rewrite -orderSpred iterS; apply: f_finv_in. Qed.
Lemma iter_finv_in n :
{in S, forall x, n <= order x -> iter n finv x = iter (order x - n) f x}.
Proof.
move=> x xS; rewrite -[x in LHS]iter_order_in => // /subnKC {1}<-.
move: (_ - n) => m; rewrite iterD; elim: n => // n {2}<-.
by rewrite iterSr /= finv_f_in // -iterD iter_in.
Qed.
Lemma cycle_orbit_in : {in S, forall x, (fcycle f) (orbit x)}.
Proof.
move=> x xS; rewrite /orbit -orderSpred (cycle_path x) /= last_traject.
by rewrite -/(finv x) fpath_traject f_finv_in ?eqxx.
Qed.
Lemma fpath_finv_in p x :
(x \in S) && (fpath finv x p) =
(last x p \in S) && (fpath f (last x p) (rev (belast x p))).
Proof.
elim: p x => //= y p IHp x; rewrite rev_cons rcons_path.
transitivity [&& y \in S, f y == x & fpath finv y p].
apply/and3P/and3P => -[xS /eqP<- fxp]; split;
by rewrite ?f_finv_in ?finv_f_in ?finv_in ?f_in.
rewrite andbCA {}IHp !andbA [RHS]andbC -andbA; congr [&& _, _ & _].
by case: p => //= z p; rewrite rev_cons last_rcons.
Qed.
Lemma fpath_finv_f_in p : {in S, forall x,
fpath finv x p -> fpath f (last x p) (rev (belast x p))}.
Proof. by move=> x xS /(conj xS)/andP; rewrite fpath_finv_in => /andP[]. Qed.
Lemma fpath_f_finv_in p x : last x p \in S ->
fpath f (last x p) (rev (belast x p)) -> fpath finv x p.
Proof. by move=> lS /(conj lS)/andP; rewrite -fpath_finv_in => /andP[]. Qed.
End orbit_in.
Lemma injectivePcycle x :
reflect {in orbit x &, injective f} (fcycle f (orbit x)).
Proof.
apply: (iffP idP) => [/inj_cycle//|/cycle_orbit_in].
by apply; [apply: mem_orbit|apply: in_orbit].
Qed.
Section orbit_inj.
Hypothesis injf : injective f.
Lemma f_finv : cancel finv f. Proof. exact: (in1T (f_finv_in _ (in2W _))). Qed.
Lemma finv_f : cancel f finv. Proof. exact: (in1T (finv_f_in _ (in2W _))). Qed.
Lemma finv_bij : bijective finv.
Proof. by exists f; [apply: f_finv|apply: finv_f]. Qed.
Lemma finv_inj : injective finv. Proof. exact: (can_inj f_finv). Qed.
Lemma fconnect_sym x y : fconnect f x y = fconnect f y x.
Proof. exact: (in2T (fconnect_sym_in _ (in2W _))). Qed.
Let symf := fconnect_sym.
Lemma iter_order x : iter (order x) f x = x.
Proof. exact: (in1T (iter_order_in _ (in2W _))). Qed.
Lemma iter_finv n x : n <= order x -> iter n finv x = iter (order x - n) f x.
Proof. exact: (in1T (@iter_finv_in _ _ (in2W _) _)). Qed.
Lemma cycle_orbit x : fcycle f (orbit x).
Proof. exact: (in1T (cycle_orbit_in _ (in2W _))). Qed.
Lemma fpath_finv x p : fpath finv x p = fpath f (last x p) (rev (belast x p)).
Proof. exact: (@fpath_finv_in T _ (in2W _)). Qed.
Lemma same_fconnect_finv : fconnect finv =2 fconnect f.
Proof.
move=> x y; rewrite (same_connect_rev symf); apply: {x y}eq_connect => x y /=.
by rewrite (canF_eq finv_f) eq_sym.
Qed.
Lemma fcard_finv : fcard_mem finv =1 fcard_mem f.
Proof. exact: eq_n_comp same_fconnect_finv. Qed.
Definition order_set n : pred T := [pred x | order x == n].
Lemma fcard_order_set n (a : {pred T}) :
a \subset order_set n -> fclosed f a -> fcard f a * n = #|a|.
Proof.
move=> a_n cl_a; rewrite /n_comp_mem; set b := [predI froots f & a].
suff <-: #|preim (froot f) b| = #|b| * n.
apply: eq_card => x; rewrite !inE (roots_root fconnect_sym).
exact/esym/(closed_connect cl_a)/connect_root.
have{cl_a a_n} (x): b x -> froot f x = x /\ order x = n.
by case/andP=> /eqP-> /(subsetP a_n)/eqnP->.
elim: {a b}#|b| {1 3 4}b (eqxx #|b|) => [|m IHm] b def_m f_b.
by rewrite eq_card0 // => x; apply: (pred0P def_m).
have [x b_x | b0] := pickP b; last by rewrite (eq_card0 b0) in def_m.
have [r_x ox_n] := f_b x b_x; rewrite (cardD1 x) [x \in b]b_x eqSS in def_m.
rewrite mulSn -{1}ox_n -(IHm _ def_m) => [|_ /andP[_ /f_b //]].
rewrite -(cardID (fconnect f x)); congr (_ + _); apply: eq_card => y.
by apply: andb_idl => /= fxy; rewrite !inE -(rootP symf fxy) r_x.
by congr (~~ _ && _); rewrite /= /in_mem /= symf -(root_connect symf) r_x.
Qed.
Lemma fclosed1 (a : {pred T}) :
fclosed f a -> forall x, (x \in a) = (f x \in a).
Proof. by move=> cl_a x; apply: cl_a (eqxx _). Qed.
Lemma same_fconnect1 x : fconnect f x =1 fconnect f (f x).
Proof. by apply: same_connect1 => /=. Qed.
Lemma same_fconnect1_r x y : fconnect f x y = fconnect f x (f y).
Proof. by apply: same_connect1r x => /=. Qed.
Lemma fcard_gt0P (a : {pred T}) :
fclosed f a -> reflect (exists x, x \in a) (0 < fcard f a).
Proof.
move=> clfA; apply: (iffP card_gt0P) => [[x /andP[]]|[x xA]]; first by exists x.
exists (froot f x); rewrite inE roots_root /=; last exact: fconnect_sym.
by rewrite -(closed_connect clfA (connect_root _ x)).
Qed.
Lemma fcard_gt1P (A : {pred T}) :
fclosed f A ->
reflect (exists2 x, x \in A & exists2 y, y \in A & ~~ fconnect f x y)
(1 < fcard f A).
Proof.
move=> clAf; apply: (iffP card_gt1P) => [|[x xA [y yA not_xfy]]].
move=> [x [y [/andP [/= rfx xA] /andP[/= rfy yA] xDy]]].
by exists x; try exists y; rewrite // -root_connect // (eqP rfx) (eqP rfy).
exists (froot f x), (froot f y); rewrite !inE !roots_root ?root_connect //=.
by split => //; rewrite -(closed_connect clAf (connect_root _ _)).
Qed.
End orbit_inj.
Hint Resolve orbit_uniq : core.
Section fcycle_p.
Variables (p : seq T) (f_p : fcycle f p).
Section mem_cycle.
Variable (Up : uniq p) (x : T) (p_x : x \in p).
(* fconnect_cycle does not dependent on Up *)
Lemma fconnect_cycle y : fconnect f x y = (y \in p).
Proof.
have [i q def_p] := rot_to p_x; rewrite -(mem_rot i p) def_p.
have{i def_p} /andP[/eqP q_x f_q]: (f (last x q) == x) && fpath f x q.
by have:= f_p; rewrite -(rot_cycle i) def_p (cycle_path x).
apply/idP/idP=> [/connectP[_ /fpathP[j ->] ->] | ]; last exact: path_connect.
case/fpathP: f_q q_x => n ->; rewrite !last_traject -iterS => def_x.
by apply: (@loopingP _ f x n.+1); rewrite /looping def_x /= mem_head.
Qed.
(* order_le_cycle does not dependent on Up *)
Lemma order_le_cycle : order x <= size p.
Proof.
apply: leq_trans (card_size _); apply/subset_leq_card/subsetP=> y.
by rewrite !(fconnect_cycle, inE) ?eqxx.
Qed.
Lemma order_cycle : order x = size p.
Proof. by rewrite -(card_uniqP Up); apply: (eq_card fconnect_cycle). Qed.
Lemma orbitE : orbit x = rot (index x p) p.
Proof.
set i := index _ _; rewrite /orbit order_cycle -(size_rot i) rot_index// -/i.
set q := _ ++ _; suffices /fpathP[j ->]: fpath f x q by rewrite /= size_traject.
by move: f_p; rewrite -(rot_cycle i) rot_index// (cycle_path x); case/andP.
Qed.
Lemma orbit_rot_cycle : {i : nat | orbit x = rot i p}.
Proof. by rewrite orbitE; exists (index x p). Qed.
End mem_cycle.
Let f_inj := inj_cycle f_p.
Let homo_f := mem_fcycle f_p.
Lemma finv_cycle : {homo finv : x / x \in p}. Proof. exact: finv_in. Qed.
Lemma f_finv_cycle : {in p, cancel finv f}. Proof. exact: f_finv_in. Qed.
Lemma finv_f_cycle : {in p, cancel f finv}. Proof. exact: finv_f_in. Qed.
Lemma finv_inj_cycle : {in p &, injective finv}. Proof. exact: finv_inj_in. Qed.
Lemma iter_finv_cycle n :
{in p, forall x, n <= order x -> iter n finv x = iter (order x - n) f x}.
Proof. exact: iter_finv_in. Qed.
Lemma cycle_orbit_cycle : {in p, forall x, fcycle f (orbit x)}.
Proof. exact: cycle_orbit_in. Qed.
Lemma fpath_finv_cycle q x : (x \in p) && (fpath finv x q) =
(last x q \in p) && fpath f (last x q) (rev (belast x q)).
Proof. exact: fpath_finv_in. Qed.
Lemma fpath_finv_f_cycle q : {in p, forall x,
fpath finv x q -> fpath f (last x q) (rev (belast x q))}.
Proof. exact: fpath_finv_f_in. Qed.
Lemma fpath_f_finv_cycle q x : last x q \in p ->
fpath f (last x q) (rev (belast x q)) -> fpath finv x q.
Proof. exact: fpath_f_finv_in. Qed.
Lemma prevE x : x \in p -> prev p x = finv x.
Proof.
move=> x_p; have /eqP/(congr1 finv) := prev_cycle f_p x_p.
by rewrite finv_f_cycle// mem_prev.
Qed.
End fcycle_p.
Section fcycle_cons.
Variables (x : T) (p : seq T) (f_p : fcycle f (x :: p)).
Lemma fcycle_rconsE : rcons (x :: p) x = traject f x (size p).+2.
Proof. by rewrite rcons_cons; have /fpathE-> := f_p; rewrite size_rcons. Qed.
Lemma fcycle_consE : x :: p = traject f x (size p).+1.
Proof. by have := fcycle_rconsE; rewrite trajectSr => /rcons_inj[/= <-]. Qed.
Lemma fcycle_consEflatten : exists k, x :: p = flatten (nseq k.+1 (orbit x)).
Proof.
move: f_p; rewrite fcycle_consE; elim/ltn_ind: (size p) => n IHn t_cycle.
have := order_le_cycle t_cycle (mem_head _ _); rewrite size_traject.
case: ltngtP => [||<-] //; last by exists 0; rewrite /= cats0.
rewrite ltnS => n_ge _; have := t_cycle.
rewrite -(subnKC n_ge) -addnS trajectD.
rewrite (iter_order_in (mem_fcycle f_p) (inj_cycle f_p)) ?mem_head//.
set m := (_ - _) => cycle_cat.
have [||k->] := IHn m; last by exists k.+1.
by rewrite ltn_subrL (leq_trans _ n_ge) ?order_gt0.
move: cycle_cat; rewrite -orderSpred/= rcons_cat rcons_cons -cat_rcons.
by rewrite cat_path last_rcons => /andP[].
Qed.
Lemma undup_cycle_cons : undup (x :: p) = orbit x.
Proof.
by have [n {1}->] := fcycle_consEflatten; rewrite undup_flatten_nseq ?undup_id.
Qed.
End fcycle_cons.
Section fcycle_undup.
Variable (p : seq T) (f_p : fcycle f p).
Lemma fcycleEflatten : exists k, p = flatten (nseq k (undup p)).
Proof.
case: p f_p => [//|x q] f_q; first by exists 0.
have [k {1}->] := @fcycle_consEflatten x q f_q.
by exists k.+1; rewrite undup_cycle_cons.
Qed.
Lemma fcycle_undup : fcycle f (undup p).
Proof.
case: p f_p => [//|x q] f_q; rewrite undup_cycle_cons//.
by rewrite (cycle_orbit_in (mem_fcycle f_q) (inj_cycle f_q)) ?mem_head.
Qed.
Let p_undup_uniq := undup_uniq p.
Let f_inj := inj_cycle f_p.
Let homo_f := mem_fcycle f_p.
Lemma in_orbit_cycle : {in p &, forall x, orbit x =i p}.
Proof.
by move=> x y xp yp; rewrite (orbitE fcycle_undup)// ?mem_rot ?mem_undup.
Qed.
Lemma eq_order_cycle : {in p &, forall x y, order y = order x}.
Proof. by move=> x y xp yp; rewrite !(order_cycle fcycle_undup) ?mem_undup. Qed.
Lemma iter_order_cycle : {in p &, forall x y, iter (order x) f y = y}.
Proof.
by move=> x y xp yp; rewrite (eq_order_cycle yp) ?(iter_order_in homo_f f_inj).
Qed.
End fcycle_undup.
Section fconnect.
Lemma fconnect_eqVf x y : fconnect f x y = (x == y) || fconnect f (f x) y.
Proof.
apply/idP/idP => [/iter_findex <-|/predU1P [<-|] //]; last first.
exact/connect_trans/fconnect1.
by case: findex => [|i]; rewrite ?eqxx// iterSr fconnect_iter orbT.
Qed.
(*****************************************************************************)
(* Lemma orbitPcycle is of type "The Following Are Equivalent", which means *)
(* all four statements are equivalent to each other. In order to use it, one *)
(* has to apply it to the natural numbers corresponding to the line, e.g. *)
(* `orbitPcycle 0 2 : fcycle f (orbit x) <-> exists k, iter k.+1 f x = x`. *)
(* examples of this are in order_id_cycle and fconnnect_f. *)
(* One may also use lemma all_iffLR to get a one sided implication, as in *)
(* orderPcycle. *)
(*****************************************************************************)
Lemma orbitPcycle {x} : [<->
(* 0 *) fcycle f (orbit x);
(* 1 *) order (f x) = order x;
(* 2 *) x \in fconnect f (f x);
(* 3 *) exists k, iter k.+1 f x = x;
(* 4 *) iter (order x) f x = x;
(* 5 *) {in orbit x &, injective f}].
Proof.
tfae=> [xorbit_cycle|||[k fkx]|fx y z|/injectivePcycle//].
- by apply: eq_order_cycle xorbit_cycle _ _ _ _; rewrite ?mem_orbit.
- move=> /subset_cardP/(_ _)->; rewrite ?inE//; apply/subsetP=> y.
by apply: connect_trans; apply: fconnect1.
- by exists (findex (f x) x); rewrite // iterSr iter_findex.
- apply: (@iter_order_cycle (traject f x k.+1)); rewrite /= ?mem_head//.
by apply/fpathP; exists k.+1; rewrite trajectSr -iterSr fkx.
- rewrite -!fconnect_orbit => /iter_findex <- /iter_findex <-.
move/(congr1 (iter (order x).-1 f)).
by rewrite -!iterSr !orderSpred -!iterD ![order _ + _]addnC !iterD fx.
Qed.
Lemma order_id_cycle x : fcycle f (orbit x) -> order (f x) = order x.
Proof. by move/(orbitPcycle 0 1). Qed.
Inductive order_spec_cycle x : bool -> Type :=
| OrderStepCycle of fcycle f (orbit x) & order x = order (f x) :
order_spec_cycle x true
| OrderStepNoCycle of ~~ fcycle f (orbit x) & order x = (order (f x)).+1 :
order_spec_cycle x false.
Lemma orderPcycle x : order_spec_cycle x (fcycle f (orbit x)).
Proof.
have [xcycle|Ncycle] := boolP (fcycle f (orbit x)); constructor => //.
by rewrite order_id_cycle.
rewrite /order (eq_card (_ : _ =1 [predU1 x & fconnect f (f x)])).
by rewrite cardU1 inE (contraNN (all_iffLR orbitPcycle 2 0)).
by move=> y; rewrite !inE fconnect_eqVf eq_sym.
Qed.
Lemma fconnect_f x : fconnect f (f x) x = fcycle f (orbit x).
Proof. by apply/idP/idP => /(orbitPcycle 0 2). Qed.
Lemma fconnect_findex x y :
fconnect f x y -> y != x -> findex x y = (findex (f x) y).+1.
Proof.
rewrite /findex fconnect_orbit /orbit -orderSpred /= inE => /orP [-> //|].
rewrite eq_sym; move=> yin /negPf->; have [_ eq_o|_ ->//] := orderPcycle x.
by rewrite -(orderSpred (f x)) trajectSr -cats1 index_cat -eq_o yin.
Qed.
End fconnect.
End Orbit.
#[global] Hint Resolve in_orbit mem_orbit order_gt0 orbit_uniq : core.
Prenex Implicits order orbit findex finv order_set.
Arguments orbitPcycle {T f x}.
Arguments same_fconnect_finv [T f].
Section FconnectId.
Variable T : finType.
Lemma fconnect_id (x : T) : fconnect id x =1 xpred1 x.
Proof. by move=> y; rewrite (@fconnect_cycle _ _ [:: x]) //= ?inE ?eqxx. Qed.
Lemma order_id (x : T) : order id x = 1.
Proof. by rewrite /order (eq_card (fconnect_id x)) card1. Qed.
Lemma orbit_id (x : T) : orbit id x = [:: x].
Proof. by rewrite /orbit order_id. Qed.
Lemma froots_id (x : T) : froots id x.
Proof. by rewrite /roots -fconnect_id connect_root. Qed.
Lemma froot_id (x : T) : froot id x = x.
Proof. by apply/eqP; apply: froots_id. Qed.
Lemma fcard_id (a : {pred T}) : fcard id a = #|a|.
Proof. by apply: eq_card => x; rewrite inE froots_id. Qed.
End FconnectId.
Section FconnectEq.
Variables (T : finType) (f f' : T -> T).
Lemma finv_eq_can : cancel f f' -> finv f =1 f'.
Proof.
move=> fK; have inj_f := can_inj fK.
by apply: bij_can_eq fK; [apply: injF_bij | apply: finv_f].
Qed.
Hypothesis eq_f : f =1 f'.
Let eq_rf := eq_frel eq_f.
Lemma eq_fconnect : fconnect f =2 fconnect f'.
Proof. exact: eq_connect eq_rf. Qed.
Lemma eq_fcard : fcard_mem f =1 fcard_mem f'.
Proof. exact: eq_n_comp eq_fconnect. Qed.
Lemma eq_finv : finv f =1 finv f'.
Proof.
by move=> x; rewrite /finv /order (eq_card (@eq_fconnect x)) (eq_iter eq_f).
Qed.
Lemma eq_froot : froot f =1 froot f'.
Proof. exact: eq_root eq_rf. Qed.
Lemma eq_froots : froots f =1 froots f'.
Proof. exact: eq_roots eq_rf. Qed.
End FconnectEq.
Arguments eq_fconnect [T f f'].
Section FinvEq.
Variables (T : finType) (f : T -> T).
Hypothesis injf : injective f.
Lemma finv_inv : finv (finv f) =1 f.
Proof. exact: (finv_eq_can (f_finv injf)). Qed.
Lemma order_finv : order (finv f) =1 order f.
Proof. by move=> x; apply: eq_card (@same_fconnect_finv _ _ injf x). Qed.
Lemma order_set_finv n : order_set (finv f) n =i order_set f n.
Proof. by move=> x; rewrite !inE order_finv. Qed.
End FinvEq.
Section RelAdjunction.
Variables (T T' : finType) (h : T' -> T) (e : rel T) (e' : rel T').
Hypotheses (sym_e : connect_sym e) (sym_e' : connect_sym e').
Record rel_adjunction_mem m_a := RelAdjunction {
rel_unit x : in_mem x m_a -> {x' : T' | connect e x (h x')};
rel_functor x' y' :
in_mem (h x') m_a -> connect e' x' y' = connect e (h x') (h y')
}.
Variable a : {pred T}.
Hypothesis cl_a : closed e a.
Local Notation rel_adjunction := (rel_adjunction_mem (mem a)).
Lemma intro_adjunction (h' : forall x, x \in a -> T') :
(forall x a_x,
[/\ connect e x (h (h' x a_x))
& forall y a_y, e x y -> connect e' (h' x a_x) (h' y a_y)]) ->
(forall x' a_x,
[/\ connect e' x' (h' (h x') a_x)
& forall y', e' x' y' -> connect e (h x') (h y')]) ->
rel_adjunction.
Proof.
move=> Aee' Ae'e; split=> [y a_y | x' z' a_x].
by exists (h' y a_y); case/Aee': (a_y).
apply/idP/idP=> [/connectP[p e'p ->{z'}] | /connectP[p e_p p_z']].
elim: p x' a_x e'p => //= y' p IHp x' a_x.
case: (Ae'e x' a_x) => _ Ae'x /andP[/Ae'x e_xy /IHp e_yz] {Ae'x}.
by apply: connect_trans (e_yz _); rewrite // -(closed_connect cl_a e_xy).
case: (Ae'e x' a_x) => /connect_trans-> //.
elim: p {x'}(h x') p_z' a_x e_p => /= [|y p IHp] x p_z' a_x.
by rewrite -p_z' in a_x *; case: (Ae'e _ a_x); rewrite sym_e'.
case/andP=> e_xy /(IHp _ p_z') e'yz; have a_y: y \in a by rewrite -(cl_a e_xy).
by apply: connect_trans (e'yz a_y); case: (Aee' _ a_x) => _ ->.
Qed.
Lemma strict_adjunction :
injective h -> a \subset codom h -> rel_base h e e' [predC a] ->
rel_adjunction.
Proof.
move=> /= injh h_a a_ee'; pose h' x Hx := iinv (subsetP h_a x Hx).
apply: (@intro_adjunction h') => [x a_x | x' a_x].
rewrite f_iinv connect0; split=> // y a_y e_xy.
by rewrite connect1 // -a_ee' !f_iinv ?negbK.
rewrite [h' _ _]iinv_f //; split=> // y' e'xy.
by rewrite connect1 // a_ee' ?negbK.
Qed.
Let ccl_a := closed_connect cl_a.
Lemma adjunction_closed : rel_adjunction -> closed e' [preim h of a].
Proof.
case=> _ Ae'e; apply: intro_closed => // x' y' /connect1 e'xy a_x.
by rewrite Ae'e // in e'xy; rewrite !inE -(ccl_a e'xy).
Qed.
Lemma adjunction_n_comp :
rel_adjunction -> n_comp e a = n_comp e' [preim h of a].
Proof.
case=> Aee' Ae'e.
have inj_h: {in predI (roots e') [preim h of a] &, injective (root e \o h)}.
move=> x' y' /andP[/eqP r_x' /= a_x'] /andP[/eqP r_y' _] /(rootP sym_e).
by rewrite -Ae'e // => /(rootP sym_e'); rewrite r_x' r_y'.
rewrite /n_comp_mem -(card_in_image inj_h); apply: eq_card => x.
apply/andP/imageP=> [[/eqP rx a_x] | [x' /andP[/eqP r_x' a_x'] ->]]; last first.
by rewrite /= -(ccl_a (connect_root _ _)) roots_root.
have [y' e_xy]:= Aee' x a_x; pose x' := root e' y'.
have ay': h y' \in a by rewrite -(ccl_a e_xy).
have e_yx: connect e (h y') (h x') by rewrite -Ae'e ?connect_root.
exists x'; first by rewrite inE /= -(ccl_a e_yx) ?roots_root.
by rewrite /= -(rootP sym_e e_yx) -(rootP sym_e e_xy).
Qed.
End RelAdjunction.
Notation rel_adjunction h e e' a := (rel_adjunction_mem h e e' (mem a)).
Notation "@ 'rel_adjunction' T T' h e e' a" :=
(@rel_adjunction_mem T T' h e e' (mem a))
(at level 10, T, T', h, e, e', a at level 8, only parsing) : type_scope.
Notation fun_adjunction h f f' a := (rel_adjunction h (frel f) (frel f') a).
Notation "@ 'fun_adjunction' T T' h f f' a" :=
(@rel_adjunction T T' h (frel f) (frel f') a)
(at level 10, T, T', h, f, f', a at level 8, only parsing) : type_scope.
Arguments intro_adjunction [T T' h e e'] _ [a].
Arguments adjunction_n_comp [T T'] h [e e'] _ _ [a].
Unset Implicit Arguments.
|
Even.lean
|
/-
Copyright (c) 2022 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import Mathlib.Algebra.Group.Equiv.Basic
import Mathlib.Algebra.Group.Equiv.Opposite
import Mathlib.Algebra.Group.TypeTags.Basic
import Mathlib.Data.Set.Operations
/-!
# Squares and even elements
This file defines square and even elements in a monoid.
## Main declarations
* `IsSquare a` means that there is some `r` such that `a = r * r`
* `Even a` means that there is some `r` such that `a = r + r`
## Note
* Many lemmas about `Even` / `IsSquare`, including important `simp` lemmas,
are in `Mathlib/Algebra/Ring/Parity.lean`.
## TODO
* Try to generalize `IsSquare/Even` lemmas further. For example, there are still a few lemmas in
`Algebra.Ring.Parity` whose `Semiring` assumptions I (DT) am not convinced are necessary.
* The "old" definition of `Even a` asked for the existence of an element `c` such that `a = 2 * c`.
For this reason, several fixes introduce an extra `two_mul` or `← two_mul`.
It might be the case that by making a careful choice of `simp` lemma, this can be avoided.
## See also
`Mathlib/Algebra/Ring/Parity.lean` for the definition of odd elements as well as facts about
`Even` / `IsSquare` in rings.
-/
assert_not_exists MonoidWithZero DenselyOrdered
open MulOpposite
variable {F α β : Type*}
section Mul
variable [Mul α]
/-- An element `a` of a type `α` with multiplication satisfies `IsSquare a` if `a = r * r`,
for some root `r : α`. -/
@[to_additive /-- An element `a` of a type `α` with addition satisfies `Even a` if `a = r + r`,
for some `r : α`. -/]
def IsSquare (a : α) : Prop := ∃ r, a = r * r
@[to_additive]
lemma isSquare_iff_exists_mul_self (a : α) : IsSquare a ↔ ∃ r, a = r * r := .rfl
alias ⟨IsSquare.exists_mul_self, _⟩ := isSquare_iff_exists_mul_self
attribute [to_additive (attr := aesop unsafe 5% forward)] IsSquare.exists_mul_self
@[to_additive (attr := simp, aesop safe)]
lemma IsSquare.mul_self (r : α) : IsSquare (r * r) := ⟨r, rfl⟩
@[to_additive]
lemma isSquare_op_iff {a : α} : IsSquare (op a) ↔ IsSquare a :=
⟨fun ⟨r, hr⟩ ↦ ⟨unop r, congr_arg unop hr⟩, fun ⟨r, hr⟩ ↦ ⟨op r, congr_arg op hr⟩⟩
@[to_additive]
lemma isSquare_unop_iff {a : αᵐᵒᵖ} : IsSquare (unop a) ↔ IsSquare a := isSquare_op_iff.symm
@[to_additive]
instance [DecidablePred (IsSquare : α → Prop)] : DecidablePred (IsSquare : αᵐᵒᵖ → Prop) :=
fun _ ↦ decidable_of_iff _ isSquare_unop_iff
@[simp]
lemma even_ofMul_iff {a : α} : Even (Additive.ofMul a) ↔ IsSquare a := Iff.rfl
@[simp]
lemma isSquare_toMul_iff {a : Additive α} : IsSquare (a.toMul) ↔ Even a := Iff.rfl
instance Additive.instDecidablePredEven [DecidablePred (IsSquare : α → Prop)] :
DecidablePred (Even : Additive α → Prop) :=
fun _ ↦ decidable_of_iff _ isSquare_toMul_iff
end Mul
section Add
variable [Add α]
@[simp] lemma isSquare_ofAdd_iff {a : α} : IsSquare (Multiplicative.ofAdd a) ↔ Even a := Iff.rfl
@[simp]
lemma even_toAdd_iff {a : Multiplicative α} : Even a.toAdd ↔ IsSquare a := Iff.rfl
instance Multiplicative.instDecidablePredIsSquare [DecidablePred (Even : α → Prop)] :
DecidablePred (IsSquare : Multiplicative α → Prop) :=
fun _ ↦ decidable_of_iff _ even_toAdd_iff
end Add
@[to_additive (attr := simp, grind)]
lemma IsSquare.one [MulOneClass α] : IsSquare (1 : α) := ⟨1, (mul_one _).symm⟩
section MonoidHom
variable [MulOneClass α] [MulOneClass β] [FunLike F α β] [MonoidHomClass F α β]
@[to_additive (attr := aesop unsafe 90%)]
lemma IsSquare.map {a : α} (f : F) : IsSquare a → IsSquare (f a) :=
fun ⟨r, _⟩ => ⟨f r, by simp [*]⟩
@[to_additive]
lemma isSquare_subset_image_isSquare {f : F} (hf : Function.Surjective f) :
{b | IsSquare b} ⊆ f '' {a | IsSquare a} := fun b ⟨s, _⟩ => by
rcases hf s with ⟨r, rfl⟩
exact ⟨r * r, by simp [*]⟩
end MonoidHom
section Monoid
variable [Monoid α] {n : ℕ} {a : α}
@[to_additive even_iff_exists_two_nsmul]
lemma isSquare_iff_exists_sq (a : α) : IsSquare a ↔ ∃ r, a = r ^ 2 := by simp [IsSquare, pow_two]
@[to_additive Even.exists_two_nsmul
/-- Alias of the forwards direction of `even_iff_exists_two_nsmul`. -/]
alias ⟨IsSquare.exists_sq, _⟩ := isSquare_iff_exists_sq
-- provable by simp in `Algebra.Ring.Parity`
@[to_additive (attr := aesop safe) Even.two_nsmul]
lemma IsSquare.sq (r : α) : IsSquare (r ^ 2) := ⟨r, pow_two _⟩
@[to_additive (attr := aesop unsafe 80%) Even.nsmul_right]
lemma IsSquare.pow (n : ℕ) (ha : IsSquare a) : IsSquare (a ^ n) := by
aesop (add simp Commute.mul_pow)
@[to_additive (attr := aesop unsafe 90%) Even.nsmul_left]
lemma Even.isSquare_pow (hn : Even n) : ∀ a : α, IsSquare (a ^ n) := by aesop (add simp pow_add)
end Monoid
@[to_additive (attr := aesop unsafe 90%)]
lemma IsSquare.mul [CommSemigroup α] {a b : α} : IsSquare a → IsSquare b → IsSquare (a * b) :=
fun ⟨r, _⟩ ⟨s, _⟩ => ⟨r * s, by simp_all [mul_mul_mul_comm]⟩
section DivisionMonoid
variable [DivisionMonoid α] {a : α}
@[to_additive (attr := simp)] lemma isSquare_inv : IsSquare a⁻¹ ↔ IsSquare a := by
constructor <;> intro h <;> simpa using (isSquare_op_iff.mpr h).map (MulEquiv.inv' α).symm
@[to_additive] alias ⟨_, IsSquare.inv⟩ := isSquare_inv
@[to_additive (attr := aesop unsafe 80%) Even.zsmul_right]
lemma IsSquare.zpow (n : ℤ) : IsSquare a → IsSquare (a ^ n) := by
aesop (add simp Commute.mul_zpow)
end DivisionMonoid
@[to_additive (attr := aesop unsafe 90%)]
lemma IsSquare.div [DivisionCommMonoid α] {a b : α} (ha : IsSquare a) (hb : IsSquare b) :
IsSquare (a / b) := by aesop (add simp div_eq_mul_inv)
@[to_additive (attr := simp, aesop unsafe 90%) Even.zsmul_left]
lemma Even.isSquare_zpow [Group α] {n : ℤ} : Even n → ∀ a : α, IsSquare (a ^ n) := by
aesop (add simp zpow_add)
example {G : Type*} [CommGroup G] {a b c d e : G} (ha : IsSquare a) {n : ℕ} {k : ℤ} (hk : Even k) :
IsSquare <| a * (b * b) / (c ^ 2) * (d ^ k) * (e ^ (n + n)) := by aesop
example {G : Type*} [AddCommGroup G] {a b c d e : G} (ha : Even a) {n : ℕ} {k : ℤ} (hk : Even k) :
Even <| a + (b + b) - 2 • c + k • d + (n + n) • e := by aesop
|
Finiteness.lean
|
/-
Copyright (c) 2024 Jz Pan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jz Pan
-/
import Mathlib.LinearAlgebra.DFinsupp
import Mathlib.RingTheory.Finiteness.Basic
import Mathlib.LinearAlgebra.TensorProduct.Basic
/-!
# Some finiteness results of tensor product
This file contains some finiteness results of tensor product.
- `TensorProduct.exists_multiset`, `TensorProduct.exists_finsupp_left`,
`TensorProduct.exists_finsupp_right`, `TensorProduct.exists_finset`:
any element of `M ⊗[R] N` can be written as a finite sum of pure tensors.
See also `TensorProduct.span_tmul_eq_top`.
- `TensorProduct.exists_finite_submodule_left_of_finite`,
`TensorProduct.exists_finite_submodule_right_of_finite`,
`TensorProduct.exists_finite_submodule_of_finite`:
any finite subset of `M ⊗[R] N` is contained in `M' ⊗[R] N`,
resp. `M ⊗[R] N'`, resp. `M' ⊗[R] N'`,
for some finitely generated submodules `M'` and `N'` of `M` and `N`, respectively.
- `TensorProduct.exists_finite_submodule_left_of_finite'`,
`TensorProduct.exists_finite_submodule_right_of_finite'`,
`TensorProduct.exists_finite_submodule_of_finite'`:
variation of the above results where `M` and `N` are already submodules.
## Tags
tensor product, finitely generated
-/
open scoped TensorProduct
open Submodule
variable {R M N : Type*}
variable [CommSemiring R] [AddCommMonoid M] [AddCommMonoid N] [Module R M] [Module R N]
variable {M₁ M₂ : Submodule R M} {N₁ N₂ : Submodule R N}
namespace TensorProduct
/-- For any element `x` of `M ⊗[R] N`, there exists a (finite) multiset `{ (m_i, n_i) }`
of `M × N`, such that `x` is equal to the sum of `m_i ⊗ₜ[R] n_i`. -/
theorem exists_multiset (x : M ⊗[R] N) :
∃ S : Multiset (M × N), x = (S.map fun i ↦ i.1 ⊗ₜ[R] i.2).sum := by
induction x with
| zero => exact ⟨0, by simp⟩
| tmul x y => exact ⟨{(x, y)}, by simp⟩
| add x y hx hy =>
obtain ⟨Sx, hx⟩ := hx
obtain ⟨Sy, hy⟩ := hy
exact ⟨Sx + Sy, by rw [Multiset.map_add, Multiset.sum_add, hx, hy]⟩
/-- For any element `x` of `M ⊗[R] N`, there exists a finite subset `{ (m_i, n_i) }`
of `M × N` such that each `m_i` is distinct (we represent it as an element of `M →₀ N`),
such that `x` is equal to the sum of `m_i ⊗ₜ[R] n_i`. -/
theorem exists_finsupp_left (x : M ⊗[R] N) :
∃ S : M →₀ N, x = S.sum fun m n ↦ m ⊗ₜ[R] n := by
induction x with
| zero => exact ⟨0, by simp⟩
| tmul x y => exact ⟨Finsupp.single x y, by simp⟩
| add x y hx hy =>
obtain ⟨Sx, hx⟩ := hx
obtain ⟨Sy, hy⟩ := hy
use Sx + Sy
rw [hx, hy]
exact (Finsupp.sum_add_index' (by simp) TensorProduct.tmul_add).symm
/-- For any element `x` of `M ⊗[R] N`, there exists a finite subset `{ (m_i, n_i) }`
of `M × N` such that each `n_i` is distinct (we represent it as an element of `N →₀ M`),
such that `x` is equal to the sum of `m_i ⊗ₜ[R] n_i`. -/
theorem exists_finsupp_right (x : M ⊗[R] N) :
∃ S : N →₀ M, x = S.sum fun n m ↦ m ⊗ₜ[R] n := by
obtain ⟨S, h⟩ := exists_finsupp_left (TensorProduct.comm R M N x)
refine ⟨S, (TensorProduct.comm R M N).injective ?_⟩
simp_rw [h, Finsupp.sum, map_sum, comm_tmul]
/-- For any element `x` of `M ⊗[R] N`, there exists a finite subset `{ (m_i, n_i) }`
of `M × N`, such that `x` is equal to the sum of `m_i ⊗ₜ[R] n_i`. -/
theorem exists_finset (x : M ⊗[R] N) :
∃ S : Finset (M × N), x = S.sum fun i ↦ i.1 ⊗ₜ[R] i.2 := by
obtain ⟨S, h⟩ := exists_finsupp_left x
use S.graph
rw [h, Finsupp.sum]
apply Finset.sum_nbij' (fun m ↦ ⟨m, S m⟩) Prod.fst <;> simp
/-- For a finite subset `s` of `M ⊗[R] N`, there are finitely generated
submodules `M'` and `N'` of `M` and `N`, respectively, such that `s` is contained in the image
of `M' ⊗[R] N'` in `M ⊗[R] N`. -/
theorem exists_finite_submodule_of_finite (s : Set (M ⊗[R] N)) (hs : s.Finite) :
∃ (M' : Submodule R M) (N' : Submodule R N), Module.Finite R M' ∧ Module.Finite R N' ∧
s ⊆ LinearMap.range (mapIncl M' N') := by
simp_rw [Module.Finite.iff_fg]
induction s, hs using Set.Finite.induction_on with
| empty => exact ⟨_, _, fg_bot, fg_bot, Set.empty_subset _⟩
| @insert a s _ _ ih =>
obtain ⟨M', N', hM', hN', h⟩ := ih
refine TensorProduct.induction_on a ?_ (fun x y ↦ ?_) fun x y hx hy ↦ ?_
· exact ⟨M', N', hM', hN', Set.insert_subset (zero_mem _) h⟩
· refine ⟨_, _, hM'.sup (fg_span_singleton x),
hN'.sup (fg_span_singleton y), Set.insert_subset ?_ fun z hz ↦ ?_⟩
· exact ⟨⟨x, mem_sup_right (mem_span_singleton_self x)⟩ ⊗ₜ
⟨y, mem_sup_right (mem_span_singleton_self y)⟩, rfl⟩
· exact range_mapIncl_mono le_sup_left le_sup_left (h hz)
· obtain ⟨M₁', N₁', hM₁', hN₁', h₁⟩ := hx
obtain ⟨M₂', N₂', hM₂', hN₂', h₂⟩ := hy
refine ⟨_, _, hM₁'.sup hM₂', hN₁'.sup hN₂', Set.insert_subset (add_mem ?_ ?_) fun z hz ↦ ?_⟩
· exact range_mapIncl_mono le_sup_left le_sup_left (h₁ (Set.mem_insert x s))
· exact range_mapIncl_mono le_sup_right le_sup_right (h₂ (Set.mem_insert y s))
· exact range_mapIncl_mono le_sup_left le_sup_left (h₁ (Set.subset_insert x s hz))
/-- For a finite subset `s` of `M ⊗[R] N`, there exists a finitely generated
submodule `M'` of `M`, such that `s` is contained in the image
of `M' ⊗[R] N` in `M ⊗[R] N`. -/
theorem exists_finite_submodule_left_of_finite (s : Set (M ⊗[R] N)) (hs : s.Finite) :
∃ M' : Submodule R M, Module.Finite R M' ∧ s ⊆ LinearMap.range (M'.subtype.rTensor N) := by
obtain ⟨M', _, hfin, _, h⟩ := exists_finite_submodule_of_finite s hs
refine ⟨M', hfin, ?_⟩
rw [mapIncl, ← LinearMap.rTensor_comp_lTensor] at h
exact h.trans (LinearMap.range_comp_le_range _ _)
/-- For a finite subset `s` of `M ⊗[R] N`, there exists a finitely generated
submodule `N'` of `N`, such that `s` is contained in the image
of `M ⊗[R] N'` in `M ⊗[R] N`. -/
theorem exists_finite_submodule_right_of_finite (s : Set (M ⊗[R] N)) (hs : s.Finite) :
∃ N' : Submodule R N, Module.Finite R N' ∧ s ⊆ LinearMap.range (N'.subtype.lTensor M) := by
obtain ⟨_, N', _, hfin, h⟩ := exists_finite_submodule_of_finite s hs
refine ⟨N', hfin, ?_⟩
rw [mapIncl, ← LinearMap.lTensor_comp_rTensor] at h
exact h.trans (LinearMap.range_comp_le_range _ _)
/-- Variation of `TensorProduct.exists_finite_submodule_of_finite` where `M` and `N` are
already submodules. -/
theorem exists_finite_submodule_of_finite' (s : Set (M₁ ⊗[R] N₁)) (hs : s.Finite) :
∃ (M' : Submodule R M) (N' : Submodule R N) (hM : M' ≤ M₁) (hN : N' ≤ N₁),
Module.Finite R M' ∧ Module.Finite R N' ∧
s ⊆ LinearMap.range (TensorProduct.map (inclusion hM) (inclusion hN)) := by
obtain ⟨M', N', _, _, h⟩ := exists_finite_submodule_of_finite s hs
have hM := map_subtype_le M₁ M'
have hN := map_subtype_le N₁ N'
refine ⟨_, _, hM, hN, .map _ _, .map _ _, ?_⟩
rw [mapIncl,
show M'.subtype = inclusion hM ∘ₗ M₁.subtype.submoduleMap M' by ext; simp,
show N'.subtype = inclusion hN ∘ₗ N₁.subtype.submoduleMap N' by ext; simp,
map_comp] at h
exact h.trans (LinearMap.range_comp_le_range _ _)
/-- Variation of `TensorProduct.exists_finite_submodule_left_of_finite` where `M` and `N` are
already submodules. -/
theorem exists_finite_submodule_left_of_finite' (s : Set (M₁ ⊗[R] N₁)) (hs : s.Finite) :
∃ (M' : Submodule R M) (hM : M' ≤ M₁), Module.Finite R M' ∧
s ⊆ LinearMap.range ((inclusion hM).rTensor N₁) := by
obtain ⟨M', _, hM, _, hfin, _, h⟩ := exists_finite_submodule_of_finite' s hs
refine ⟨M', hM, hfin, ?_⟩
rw [← LinearMap.rTensor_comp_lTensor] at h
exact h.trans (LinearMap.range_comp_le_range _ _)
/-- Variation of `TensorProduct.exists_finite_submodule_right_of_finite` where `M` and `N` are
already submodules. -/
theorem exists_finite_submodule_right_of_finite' (s : Set (M₁ ⊗[R] N₁)) (hs : s.Finite) :
∃ (N' : Submodule R N) (hN : N' ≤ N₁), Module.Finite R N' ∧
s ⊆ LinearMap.range ((inclusion hN).lTensor M₁) := by
obtain ⟨_, N', _, hN, _, hfin, h⟩ := exists_finite_submodule_of_finite' s hs
refine ⟨N', hN, hfin, ?_⟩
rw [← LinearMap.lTensor_comp_rTensor] at h
exact h.trans (LinearMap.range_comp_le_range _ _)
end TensorProduct
|
QuadraticDiscriminant.lean
|
/-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import Mathlib.Order.Filter.AtTopBot.Field
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.LinearCombination
import Mathlib.Tactic.Linarith.Frontend
/-!
# Quadratic discriminants and roots of a quadratic
This file defines the discriminant of a quadratic and gives the solution to a quadratic equation.
## Main definition
- `discrim a b c`: the discriminant of a quadratic `a * (x * x) + b * x + c` is `b * b - 4 * a * c`.
## Main statements
- `quadratic_eq_zero_iff`: roots of a quadratic can be written as
`(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is a square root of the discriminant.
- `quadratic_ne_zero_of_discrim_ne_sq`: if the discriminant has no square root,
then the corresponding quadratic has no root.
- `discrim_le_zero`: if a quadratic is always non-negative, then its discriminant is non-positive.
- `discrim_le_zero_of_nonpos`, `discrim_lt_zero`, `discrim_lt_zero_of_neg`: versions of this
statement with other inequalities.
## Tags
polynomial, quadratic, discriminant, root
-/
assert_not_exists Finite Finset
open Filter
section Ring
variable {R : Type*}
/-- Discriminant of a quadratic -/
def discrim [Ring R] (a b c : R) : R :=
b ^ 2 - 4 * a * c
@[simp] lemma discrim_neg [Ring R] (a b c : R) : discrim (-a) (-b) (-c) = discrim a b c := by
simp [discrim]
variable [CommRing R] {a b c : R}
lemma discrim_eq_sq_of_quadratic_eq_zero {x : R} (h : a * (x * x) + b * x + c = 0) :
discrim a b c = (2 * a * x + b) ^ 2 := by
rw [discrim]
linear_combination -4 * a * h
/-- A quadratic has roots if and only if its discriminant equals some square.
-/
theorem quadratic_eq_zero_iff_discrim_eq_sq [NeZero (2 : R)] [NoZeroDivisors R]
(ha : a ≠ 0) (x : R) :
a * (x * x) + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b) ^ 2 := by
refine ⟨discrim_eq_sq_of_quadratic_eq_zero, fun h ↦ ?_⟩
rw [discrim] at h
have ha : 2 * 2 * a ≠ 0 := mul_ne_zero (mul_ne_zero (NeZero.ne _) (NeZero.ne _)) ha
apply mul_left_cancel₀ ha
linear_combination -h
/-- A quadratic has no root if its discriminant has no square root. -/
theorem quadratic_ne_zero_of_discrim_ne_sq (h : ∀ s : R, discrim a b c ≠ s^2) (x : R) :
a * (x * x) + b * x + c ≠ 0 :=
mt discrim_eq_sq_of_quadratic_eq_zero (h _)
end Ring
section Field
variable {K : Type*} [Field K] [NeZero (2 : K)] {a b c : K}
/-- Roots of a quadratic equation. -/
theorem quadratic_eq_zero_iff (ha : a ≠ 0) {s : K} (h : discrim a b c = s * s) (x : K) :
a * (x * x) + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := by
rw [quadratic_eq_zero_iff_discrim_eq_sq ha, h, sq, mul_self_eq_mul_self_iff]
field_simp
grind
/-- A quadratic has roots if its discriminant has square roots -/
theorem exists_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) :
∃ x, a * (x * x) + b * x + c = 0 := by
rcases h with ⟨s, hs⟩
use (-b + s) / (2 * a)
rw [quadratic_eq_zero_iff ha hs]
simp
/-- Root of a quadratic when its discriminant equals zero -/
theorem quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) (x : K) :
a * (x * x) + b * x + c = 0 ↔ x = -b / (2 * a) := by
have : discrim a b c = 0 * 0 := by rw [h, mul_zero]
rw [quadratic_eq_zero_iff ha this, add_zero, sub_zero, or_self_iff]
theorem discrim_eq_zero_of_existsUnique (ha : a ≠ 0) (h : ∃! x, a * (x * x) + b * x + c = 0) :
discrim a b c = 0 := by
simp_rw [quadratic_eq_zero_iff_discrim_eq_sq ha] at h
generalize discrim a b c = d at h
obtain ⟨x, rfl, hx⟩ := h
specialize hx (-(x + b / a))
grind
theorem discrim_eq_zero_iff (ha : a ≠ 0) :
discrim a b c = 0 ↔ (∃! x, a * (x * x) + b * x + c = 0) := by
refine ⟨fun hd => ?_, discrim_eq_zero_of_existsUnique ha⟩
simp_rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha hd, existsUnique_eq]
end Field
section LinearOrderedField
variable {K : Type*} [Field K] [LinearOrder K] [IsStrictOrderedRing K] {a b c : K}
/-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/
theorem discrim_le_zero (h : ∀ x : K, 0 ≤ a * (x * x) + b * x + c) : discrim a b c ≤ 0 := by
rw [discrim, sq]
obtain ha | rfl | ha : a < 0 ∨ a = 0 ∨ 0 < a := lt_trichotomy a 0
-- if a < 0
· have : Tendsto (fun x => (a * x + b) * x + c) atTop atBot :=
tendsto_atBot_add_const_right _ c <|
(tendsto_atBot_add_const_right _ b (tendsto_id.const_mul_atTop_of_neg ha)).atBot_mul_atTop₀
tendsto_id
rcases (this.eventually (eventually_lt_atBot 0)).exists with ⟨x, hx⟩
exact False.elim ((h x).not_gt <| by rwa [← mul_assoc, ← add_mul])
-- if a = 0
· rcases eq_or_ne b 0 with (rfl | hb)
· simp
· have := h ((-c - 1) / b)
rw [mul_div_cancel₀ _ hb] at this
linarith
-- if a > 0
· have ha' : 0 ≤ 4 * a := mul_nonneg zero_le_four ha.le
convert neg_nonpos.2 (mul_nonneg ha' (h (-b / (2 * a)))) using 1
field_simp
ring
lemma discrim_le_zero_of_nonpos (h : ∀ x : K, a * (x * x) + b * x + c ≤ 0) : discrim a b c ≤ 0 :=
discrim_neg a b c ▸ discrim_le_zero <| by simpa only [neg_mul, ← neg_add, neg_nonneg]
/-- If a polynomial of degree 2 is always positive, then its discriminant is negative,
at least when the coefficient of the quadratic term is nonzero.
-/
theorem discrim_lt_zero (ha : a ≠ 0) (h : ∀ x : K, 0 < a * (x * x) + b * x + c) :
discrim a b c < 0 := by
have : ∀ x : K, 0 ≤ a * (x * x) + b * x + c := fun x => le_of_lt (h x)
refine lt_of_le_of_ne (discrim_le_zero this) fun h' ↦ ?_
have := h (-b / (2 * a))
have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0 := by
rw [mul_assoc, quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))]
linarith
lemma discrim_lt_zero_of_neg (ha : a ≠ 0) (h : ∀ x : K, a * (x * x) + b * x + c < 0) :
discrim a b c < 0 :=
discrim_neg a b c ▸ discrim_lt_zero (neg_ne_zero.2 ha) <| by
simpa only [neg_mul, ← neg_add, neg_pos]
end LinearOrderedField
|
Sheafify.lean
|
/-
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.Topology.Sheaves.LocalPredicate
import Mathlib.Topology.Sheaves.Stalks
/-!
# Sheafification of `Type` valued presheaves
We construct the sheafification of a `Type` valued presheaf,
as the subsheaf of dependent functions into the stalks
consisting of functions which are locally germs.
We show that the stalks of the sheafification are isomorphic to the original stalks,
via `stalkToFiber` which evaluates a germ of a dependent function at a point.
We construct a morphism `toSheafify` from a presheaf to (the underlying presheaf of)
its sheafification, given by sending a section to its collection of germs.
## Future work
Show that the map induced on stalks by `toSheafify` is the inverse of `stalkToFiber`.
Show sheafification is a functor from presheaves to sheaves,
and that it is the left adjoint of the forgetful functor,
following <https://stacks.math.columbia.edu/tag/007X>.
-/
assert_not_exists CommRingCat
universe v
noncomputable section
open TopCat Opposite TopologicalSpace CategoryTheory
variable {X : TopCat.{v}} (F : Presheaf (Type v) X)
namespace TopCat.Presheaf
namespace Sheafify
attribute [local instance] Types.instFunLike Types.instConcreteCategory in
/--
The prelocal predicate on functions into the stalks, asserting that the function is equal to a germ.
-/
def isGerm : PrelocalPredicate fun x => F.stalk x where
pred {U} f := ∃ g : F.obj (op U), ∀ x : U, f x = F.germ U x.1 x.2 g
res := fun i _ ⟨g, p⟩ => ⟨F.map i.op g, fun x ↦ (p (i x)).trans (F.germ_res_apply i x x.2 g).symm⟩
/-- The local predicate on functions into the stalks,
asserting that the function is locally equal to a germ.
-/
def isLocallyGerm : LocalPredicate fun x => F.stalk x :=
(isGerm F).sheafify
end Sheafify
/-- The sheafification of a `Type` valued presheaf, defined as the functions into the stalks which
are locally equal to germs.
-/
def sheafify : Sheaf (Type v) X :=
subsheafToTypes (Sheafify.isLocallyGerm F)
attribute [local instance] Types.instFunLike Types.instConcreteCategory in
/-- The morphism from a presheaf to its sheafification,
sending each section to its germs.
(This forms the unit of the adjunction.)
-/
def toSheafify : F ⟶ F.sheafify.1 where
app U f := ⟨fun x => F.germ _ x x.2 f, PrelocalPredicate.sheafifyOf ⟨f, fun x => rfl⟩⟩
naturality U U' f := by
ext x
apply Subtype.ext -- Porting note: Added `apply`
ext ⟨u, m⟩
exact germ_res_apply F f.unop u m x
/-- The natural morphism from the stalk of the sheafification to the original stalk.
In `sheafifyStalkIso` we show this is an isomorphism.
-/
def stalkToFiber (x : X) : F.sheafify.presheaf.stalk x ⟶ F.stalk x :=
TopCat.stalkToFiber (Sheafify.isLocallyGerm F) x
attribute [local instance] Types.instFunLike Types.instConcreteCategory in
theorem stalkToFiber_surjective (x : X) : Function.Surjective (F.stalkToFiber x) := by
apply TopCat.stalkToFiber_surjective
intro t
obtain ⟨U, m, s, rfl⟩ := F.germ_exist _ t
use ⟨U, m⟩
fconstructor
· exact fun y => F.germ _ _ y.2 s
· exact ⟨PrelocalPredicate.sheafifyOf ⟨s, fun _ => rfl⟩, rfl⟩
attribute [local instance] Types.instFunLike Types.instConcreteCategory in
theorem stalkToFiber_injective (x : X) : Function.Injective (F.stalkToFiber x) := by
apply TopCat.stalkToFiber_injective
intro U V fU hU fV hV e
rcases hU ⟨x, U.2⟩ with ⟨U', mU, iU, gU, wU⟩
rcases hV ⟨x, V.2⟩ with ⟨V', mV, iV, gV, wV⟩
have wUx := wU ⟨x, mU⟩
dsimp at wUx; rw [wUx] at e; clear wUx
have wVx := wV ⟨x, mV⟩
dsimp at wVx; rw [wVx] at e; clear wVx
rcases F.germ_eq x mU mV gU gV e with ⟨W, mW, iU', iV', (e' : F.map iU'.op gU = F.map iV'.op gV)⟩
use ⟨W ⊓ (U' ⊓ V'), ⟨mW, mU, mV⟩⟩
refine ⟨?_, ?_, ?_⟩
· change W ⊓ (U' ⊓ V') ⟶ U.obj
exact Opens.infLERight _ _ ≫ Opens.infLELeft _ _ ≫ iU
· change W ⊓ (U' ⊓ V') ⟶ V.obj
exact Opens.infLERight _ _ ≫ Opens.infLERight _ _ ≫ iV
· intro w
specialize wU ⟨w.1, w.2.2.1⟩
specialize wV ⟨w.1, w.2.2.2⟩
refine wU.trans <| .trans ?_ wV.symm
rw [← F.germ_res iU' w w.2.1, ← F.germ_res iV' w w.2.1,
CategoryTheory.types_comp_apply, CategoryTheory.types_comp_apply, e']
/-- The isomorphism between a stalk of the sheafification and the original stalk.
-/
def sheafifyStalkIso (x : X) : F.sheafify.presheaf.stalk x ≅ F.stalk x :=
(Equiv.ofBijective _ ⟨stalkToFiber_injective _ _, stalkToFiber_surjective _ _⟩).toIso
-- PROJECT functoriality, and that sheafification is the left adjoint of the forgetful functor.
end TopCat.Presheaf
|
Instances.lean
|
/-
Copyright (c) 2025 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Stoll, Patrick Massot, Anatole Dedecker
-/
import Mathlib.Analysis.Normed.Field.Basic
import Mathlib.Analysis.Normed.Ring.Lemmas
import Mathlib.Order.Filter.IsBounded
import Mathlib.Topology.Algebra.UniformField
/-!
# A normed field is a completable topological field
-/
open SeminormedAddGroup IsUniformAddGroup Filter
variable {F : Type*} [NormedField F]
instance NormedField.instCompletableTopField : CompletableTopField F where
t0 := (inferInstanceAs <| T0Space _).t0
nice f hc hn := by
obtain ⟨δ, δ_pos, hδ⟩ := (disjoint_nhds_zero ..).mp <| disjoint_iff.mpr hn
have f_bdd : f.IsBoundedUnder (· ≤ ·) (‖·⁻¹‖) :=
⟨δ⁻¹, hδ.mono fun y hy ↦ le_inv_of_le_inv₀ δ_pos (by simpa using hy)⟩
have h₀ : ∀ᶠ y in f, y ≠ 0 := hδ.mono fun y hy ↦ by simpa using δ_pos.trans_le hy
have : ∀ᶠ p in f ×ˢ f, p.1⁻¹ - p.2⁻¹ = p.1⁻¹ * (p.2 - p.1) * p.2⁻¹ :=
h₀.prod_mk h₀ |>.mono fun ⟨x, y⟩ ⟨hx, hy⟩ ↦ by simp [mul_sub, sub_mul, hx, hy]
rw [cauchy_iff_tendsto_swapped] at hc
rw [cauchy_map_iff_tendsto, tendsto_congr' this]
refine ⟨hc.1, .zero_mul_isBoundedUnder_le ?_ <| tendsto_snd.isBoundedUnder_comp f_bdd⟩
exact isBoundedUnder_le_mul_tendsto_zero (tendsto_fst.isBoundedUnder_comp f_bdd) hc.2
|
Attr.lean
|
/-
Copyright (c) 2024 Tomáš Skřivan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tomáš Skřivan
-/
import Mathlib.Tactic.FunProp.Decl
import Mathlib.Tactic.FunProp.Theorems
/-!
## `funProp` attribute
-/
namespace Mathlib
open Lean Meta
namespace Meta.FunProp
private def funPropHelpString : String :=
"`fun_prop` tactic to prove function properties like `Continuous`, `Differentiable`, `IsLinearMap`"
/-- Initialization of `funProp` attribute -/
initialize funPropAttr : Unit ←
registerBuiltinAttribute {
name := `fun_prop
descr := funPropHelpString
applicationTime := AttributeApplicationTime.afterCompilation
add := fun declName _stx attrKind =>
discard <| MetaM.run do
let info ← getConstInfo declName
forallTelescope info.type fun _ b => do
if b.isProp then
addFunPropDecl declName
else
addTheorem declName attrKind
erase := fun _declName =>
throwError "can't remove `funProp` attribute (not implemented yet)"
}
end Meta.FunProp
end Mathlib
|
binomial.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path.
From mathcomp Require Import div fintype tuple finfun bigop prime finset.
(******************************************************************************)
(* This files contains the definition of: *)
(* 'C(n, m) == the binomial coefficient n choose m. *)
(* n ^_ m == the falling (or lower) factorial of n with m terms, i.e., *)
(* the product n * (n - 1) * ... * (n - m + 1). *)
(* Note that n ^_ m = 0 if m > n, and 'C(n, m) = n ^_ m %/ m`!. *)
(* *)
(* In additions to the properties of these functions, we prove a few seminal *)
(* results such as bin2_sum, Wilson and expnDn; their proofs are good *)
(* examples of how to manipulate expressions with bigops. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
(** More properties of the factorial **)
Lemma fact_prod n : n`! = \prod_(1 <= i < n.+1) i.
Proof.
elim: n => [|n IHn] //; first by rewrite big_nil.
by apply/esym; rewrite factS IHn // !big_add1 big_nat_recr //= mulnC.
Qed.
Lemma fact_split n m : m <= n -> n`! = m`! * \prod_(m.+1 <= k < n.+1) k.
Proof. by move=> leq_mn; rewrite !fact_prod -big_cat_nat. Qed.
Lemma logn_fact p n : prime p -> logn p n`! = \sum_(1 <= k < n.+1) n %/ p ^ k.
Proof.
move=> p_prime; transitivity (\sum_(1 <= i < n.+1) logn p i).
rewrite big_add1; elim: n => /= [|n IHn]; first by rewrite logn1 big_geq.
by rewrite big_nat_recr // -IHn /= factS mulnC lognM ?fact_gt0.
transitivity (\sum_(1 <= i < n.+1) \sum_(1 <= k < n.+1) (p ^ k %| i)).
apply: eq_big_nat => i /andP[i_gt0 le_i_n]; rewrite logn_count_dvd //.
rewrite -!big_mkcond (big_nat_widen _ _ n.+1) 1?ltnW //; apply: eq_bigl => k.
by apply: andb_idr => /dvdn_leq/(leq_trans (ltn_expl _ (prime_gt1 _)))->.
by rewrite exchange_big_nat; apply: eq_bigr => i _; rewrite divn_count_dvd.
Qed.
Theorem Wilson p : p > 1 -> prime p = (p %| ((p.-1)`!).+1).
Proof.
have dFact n: 0 < n -> (n.-1)`! = \prod_(0 <= i < n | i != 0) i.
move=> n_gt0; rewrite -big_filter fact_prod; symmetry; apply: congr_big => //.
rewrite /index_iota subn1 -[n]prednK //=; apply/all_filterP.
by rewrite all_predC has_pred1 mem_iota.
move=> lt1p; have p_gt0 := ltnW lt1p.
apply/idP/idP=> [pr_p | dv_pF]; last first.
apply/primeP; split=> // d dv_dp; have: d <= p by apply: dvdn_leq.
rewrite orbC leq_eqVlt => /orP[-> // | ltdp].
have:= dvdn_trans dv_dp dv_pF; rewrite dFact // big_mkord.
rewrite (bigD1 (Ordinal ltdp)) /=; last by rewrite -lt0n (dvdn_gt0 p_gt0).
by rewrite orbC -addn1 dvdn_addr ?dvdn_mulr // dvdn1 => ->.
pose Fp1 := Ordinal lt1p; pose Fp0 := Ordinal p_gt0.
have ltp1p: p.-1 < p by [rewrite prednK]; pose Fpn1 := Ordinal ltp1p.
case eqF1n1: (Fp1 == Fpn1); first by rewrite -{1}[p]prednK -1?((1 =P p.-1) _).
have toFpP m: m %% p < p by rewrite ltn_mod.
pose toFp := Ordinal (toFpP _); pose mFp (i j : 'I_p) := toFp (i * j).
have Fp_mod (i : 'I_p) : i %% p = i by apply: modn_small.
have mFpA: associative mFp.
by move=> i j k; apply: val_inj; rewrite /= modnMml modnMmr mulnA.
have mFpC: commutative mFp by move=> i j; apply: val_inj; rewrite /= mulnC.
have mFp1: left_id Fp1 mFp by move=> i; apply: val_inj; rewrite /= mul1n.
have mFp1r: right_id Fp1 mFp by move=> i; apply: val_inj; rewrite /= muln1.
pose mFpcM := Monoid.isComLaw.Build 'I_p Fp1 mFp mFpA mFpC mFp1.
pose mFpCL : Monoid.com_law _ := HB.pack mFp mFpcM.
pose mFpM := Monoid.Law.sort mFpCL.
pose vFp (i : 'I_p) := toFp (egcdn i p).1.
have vFpV i: i != Fp0 -> mFp (vFp i) i = Fp1.
rewrite -val_eqE /= -lt0n => i_gt0; apply: val_inj => /=.
rewrite modnMml; case: egcdnP => //= _ km -> _; rewrite {km}modnMDl.
suffices: coprime i p by move/eqnP->; rewrite modn_small.
rewrite coprime_sym prime_coprime //; apply/negP=> /(dvdn_leq i_gt0).
by rewrite leqNgt ltn_ord.
have vFp0 i: i != Fp0 -> vFp i != Fp0.
by move/vFpV; apply/contra_eq_neq => ->; rewrite -val_eqE /= mul0n mod0n.
have vFpK: {in predC1 Fp0, involutive vFp}.
move=> i n0i; rewrite /= -[vFp _]mFp1r -(vFpV _ n0i) mFpA.
by rewrite vFpV (vFp0, mFp1).
have le_pmFp (i : 'I_p) m: i <= p + m.
by apply: leq_trans (ltnW _) (leq_addr _ _).
have eqFp (i j : 'I_p): (i == j) = (p %| p + i - j).
by rewrite -eqn_mod_dvd ?(modnDl, Fp_mod).
have vFpId i: (vFp i == i :> nat) = xpred2 Fp1 Fpn1 i.
have [->{i} | ni0] := eqVneq i Fp0.
by rewrite -!val_eqE /= egcd0n modn_small //= -(subnKC lt1p).
rewrite 2![i == _]eqFp -Euclid_dvdM // -[_ - p.-1]subSS prednK //.
have lt0i: 0 < i by rewrite lt0n.
rewrite -addnS addKn -addnBA // mulnDl -{2}(addn1 i) -subn_sqr.
rewrite addnBA ?leq_sqr // mulnS -addnA -mulnn -mulnDl.
rewrite -(subnK (le_pmFp (vFp i) i)) mulnDl addnCA.
rewrite -[1 ^ 2]/(Fp1 : nat) -addnBA // dvdn_addl.
by rewrite Euclid_dvdM // -eqFp eq_sym orbC /dvdn Fp_mod eqn0Ngt lt0i.
by rewrite -eqn_mod_dvd // Fp_mod modnDl -(vFpV _ ni0).
suffices [mod_fact]: toFp (p.-1)`! = Fpn1.
by rewrite /dvdn -addn1 -modnDml mod_fact addn1 prednK // modnn.
rewrite dFact //; rewrite ((big_morph toFp) Fp1 mFpM) //; first last.
- by apply: val_inj; rewrite /= modn_small.
- by move=> i j; apply: val_inj; rewrite /= modnMm.
rewrite big_mkord (eq_bigr id) => [|i _]; last by apply: val_inj => /=.
pose ltv i := vFp i < i; rewrite (bigID ltv) -/mFpM [mFpM _ _]mFpC.
rewrite (bigD1 Fp1) -/mFpM; last by rewrite [ltv _]ltn_neqAle vFpId.
rewrite [mFpM _ _]mFp1 (bigD1 Fpn1) -?mFpA -/mFpM; last first.
rewrite -lt0n -ltnS prednK // lt1p.
by rewrite [ltv _]ltn_neqAle vFpId eqxx orbT eq_sym eqF1n1.
rewrite (reindex_onto vFp vFp) -/mFpM => [|i]; last by do 3!case/andP; auto.
rewrite (eq_bigl (xpredD1 ltv Fp0)) => [|i]; last first.
rewrite andbC -!andbA -2!negb_or -vFpId orbC -leq_eqVlt -ltnNge.
have [->|ni0] := eqVneq i; last by rewrite vFpK // eqxx vFp0.
by case: eqP => // ->; rewrite !andbF.
rewrite -{2}[mFp]/mFpM -[mFpM _ _]big_split -/mFpM.
by rewrite big1 ?mFp1r //= => i /andP [/vFpV].
Qed.
(** The falling factorial *)
Fixpoint ffact_rec n m := if m is m'.+1 then n * ffact_rec n.-1 m' else 1.
Definition falling_factorial := ffact_rec.
Arguments falling_factorial : simpl never.
Notation "n ^_ m" := (falling_factorial n m)
(at level 30, right associativity) : nat_scope.
Lemma ffactE : falling_factorial = ffact_rec. Proof. by []. Qed.
Lemma ffactn0 n : n ^_ 0 = 1. Proof. by []. Qed.
Lemma ffact0n m : 0 ^_ m = (m == 0). Proof. by case: m. Qed.
Lemma ffactnS n m : n ^_ m.+1 = n * n.-1 ^_ m. Proof. by []. Qed.
Lemma ffactSS n m : n.+1 ^_ m.+1 = n.+1 * n ^_ m. Proof. by []. Qed.
Lemma ffactn1 n : n ^_ 1 = n. Proof. exact: muln1. Qed.
Lemma ffactnSr n m : n ^_ m.+1 = n ^_ m * (n - m).
Proof.
elim: n m => [|n IHn] [|m] //=; first by rewrite ffactn1 mul1n.
by rewrite !ffactSS IHn mulnA.
Qed.
Lemma ffact_prod n m : n ^_ m = \prod_(i < m) (n - i).
Proof.
elim: m n => [n | m IH [|n] //]; first by rewrite ffactn0 big_ord0.
by rewrite big_ord_recr /= sub0n muln0.
by rewrite ffactSS IH big_ord_recl subn0.
Qed.
Lemma ffact_gt0 n m : (0 < n ^_ m) = (m <= n).
Proof. by elim: n m => [|n IHn] [|m] //=; rewrite ffactSS muln_gt0 IHn. Qed.
Lemma ffact_small n m : n < m -> n ^_ m = 0.
Proof. by rewrite ltnNge -ffact_gt0; case: posnP. Qed.
Lemma ffactnn n : n ^_ n = n`!.
Proof. by elim: n => [|n IHn] //; rewrite ffactnS IHn. Qed.
Lemma ffact_fact n m : m <= n -> n ^_ m * (n - m)`! = n`!.
Proof.
by elim: n m => [|n IHn] [|m] //= le_m_n; rewrite ?mul1n // -mulnA IHn.
Qed.
Lemma ffact_factd n m : m <= n -> n ^_ m = n`! %/ (n - m)`!.
Proof. by move/ffact_fact <-; rewrite mulnK ?fact_gt0. Qed.
(** Binomial coefficients *)
Fixpoint binomial n m :=
match n, m with
| n'.+1, m'.+1 => binomial n' m + binomial n' m'
| _, 0 => 1
| 0, _.+1 => 0
end.
Arguments binomial : simpl never.
Notation "''C' ( n , m )" := (binomial n m) : nat_scope.
Lemma binE n m : binomial n m =
match n, m with
| n'.+1, m'.+1 => binomial n' m + binomial n' m'
| _, 0 => 1
| 0, _.+1 => 0
end.
Proof. by case: n. Qed.
Lemma bin0 n : 'C(n, 0) = 1. Proof. by case: n. Qed.
Lemma bin0n m : 'C(0, m) = (m == 0). Proof. by case: m. Qed.
Lemma binS n m : 'C(n.+1, m.+1) = 'C(n, m.+1) + 'C(n, m). Proof. by []. Qed.
Lemma bin1 n : 'C(n, 1) = n.
Proof. by elim: n => //= n IHn; rewrite binS bin0 IHn addn1. Qed.
Lemma bin_gt0 n m : (0 < 'C(n, m)) = (m <= n).
Proof.
by elim: n m => [|n IHn] [|m] //; rewrite addn_gt0 !IHn orbC ltn_neqAle andKb.
Qed.
Lemma leq_bin2l n1 n2 m : n1 <= n2 -> 'C(n1, m) <= 'C(n2, m).
Proof.
by elim: n1 n2 m => [|n1 IHn] [|n2] [|n] le_n12 //; rewrite leq_add ?IHn.
Qed.
Lemma bin_small n m : n < m -> 'C(n, m) = 0.
Proof. by rewrite ltnNge -bin_gt0; case: posnP. Qed.
Lemma binn n : 'C(n, n) = 1.
Proof. by elim: n => [|n IHn] //; rewrite binS bin_small. Qed.
(* Multiply to move diagonally down and right in the Pascal triangle. *)
Lemma mul_bin_diag n m : n * 'C(n.-1, m) = m.+1 * 'C(n, m.+1).
Proof.
rewrite [RHS]mulnC; elim: n m => [|[|n] IHn] [|m] //=; first by rewrite bin1.
by rewrite mulSn [in _ * _]binS mulnDr addnCA !IHn -mulnS -mulnDl -binS.
Qed.
Lemma bin_fact n m : m <= n -> 'C(n, m) * (m`! * (n - m)`!) = n`!.
Proof.
elim: n m => [|n IHn] [|m] // le_m_n; first by rewrite bin0 !mul1n.
by rewrite !factS -!mulnA mulnCA mulnA -mul_bin_diag -mulnA IHn.
Qed.
(* In fact the only exception for bin_factd is n = 0 and m = 1 *)
Lemma bin_factd n m : 0 < n -> 'C(n, m) = n`! %/ (m`! * (n - m)`!).
Proof.
have [/bin_fact<-|*] := leqP m n; first by rewrite mulnK ?muln_gt0 ?fact_gt0.
by rewrite divnMA bin_small ?divn_small ?fact_gt0 ?ltn_fact.
Qed.
Lemma bin_ffact n m : 'C(n, m) * m`! = n ^_ m.
Proof.
have [lt_n_m | le_m_n] := ltnP n m; first by rewrite bin_small ?ffact_small.
by rewrite ffact_factd // -(bin_fact le_m_n) mulnA mulnK ?fact_gt0.
Qed.
Lemma bin_ffactd n m : 'C(n, m) = n ^_ m %/ m`!.
Proof. by rewrite -bin_ffact mulnK ?fact_gt0. Qed.
Lemma bin_sub n m : m <= n -> 'C(n, n - m) = 'C(n, m).
Proof.
by move=> le_m_n; rewrite !bin_ffactd !ffact_factd ?leq_subr // divnAC subKn.
Qed.
(* Multiply to move down in the Pascal triangle. *)
Lemma mul_bin_down n m : n * 'C(n.-1, m) = (n - m) * 'C(n, m).
Proof.
case: n => //= n; have [lt_n_m | le_m_n] := ltnP n m.
by rewrite (eqnP lt_n_m) mulnC bin_small.
by rewrite -!['C(_, m)]bin_sub ?leqW ?subSn ?mul_bin_diag.
Qed.
(* Multiply to move left in the Pascal triangle. *)
Lemma mul_bin_left n m : m.+1 * 'C(n, m.+1) = (n - m) * 'C(n, m).
Proof. by rewrite -mul_bin_diag mul_bin_down. Qed.
Lemma binSn n : 'C(n.+1, n) = n.+1.
Proof. by rewrite -bin_sub ?leqnSn // subSnn bin1. Qed.
Lemma bin2 n : 'C(n, 2) = (n * n.-1)./2.
Proof. by rewrite -[n.-1]bin1 mul_bin_diag -divn2 mulKn. Qed.
Lemma bin2odd n : odd n -> 'C(n, 2) = n * n.-1./2.
Proof. by case: n => // n oddn; rewrite bin2 -!divn2 muln_divA ?dvdn2. Qed.
Lemma prime_dvd_bin k p : prime p -> 0 < k < p -> p %| 'C(p, k).
Proof.
move=> p_pr /andP[k_gt0 lt_k_p].
suffices /Gauss_dvdr<-: coprime p (p - k) by rewrite -mul_bin_down dvdn_mulr.
by rewrite prime_coprime // dvdn_subr 1?ltnW // gtnNdvd.
Qed.
Lemma bin2_sum n : \sum_(0 <= i < n) i = 'C(n, 2).
Proof.
elim: n => [|n IHn]; first by rewrite big_geq.
by rewrite big_nat_recr // IHn binS bin1.
Qed.
#[deprecated(since="mathcomp 2.3.0", note="Use bin2_sum instead.")]
Notation triangular_sum := bin2_sum (only parsing).
(* textbook proof of `bin2_sum`. Should be moved out of the main
library, to a dedicated "showcase" library.
Lemma textbook_triangular_sum n : \sum_(0 <= i < n) i = 'C(n, 2).
Proof.
rewrite bin2; apply: canRL half_double _.
rewrite -addnn {1}big_nat_rev -big_split big_mkord /= ?add0n.
rewrite (eq_bigr (fun _ => n.-1)); first by rewrite sum_nat_const card_ord.
by case: n => [|n] [i le_i_n] //=; rewrite subSS subnK.
Qed. *)
Theorem expnDn a b n :
(a + b) ^ n = \sum_(i < n.+1) 'C(n, i) * (a ^ (n - i) * b ^ i).
Proof.
elim: n => [|n IHn]; rewrite big_ord_recl muln1 ?big_ord0 //.
rewrite expnS {}IHn /= mulnDl !big_distrr /= big_ord_recl muln1 subn0.
rewrite !big_ord_recr /= !binn !subnn bin0 !subn0 !mul1n -!expnS -addnA.
congr (_ + _); rewrite addnA -big_split /=; congr (_ + _).
apply: eq_bigr => i _; rewrite mulnCA (mulnA a) -expnS subnSK //=.
by rewrite (mulnC b) -2!mulnA -expnSr -mulnDl.
Qed.
#[deprecated(since="mathcomp 2.3.0", note="Use expnDn instead.")]
Definition Pascal := expnDn.
Lemma Vandermonde k l i :
\sum_(j < i.+1) 'C(k, j) * 'C(l, i - j) = 'C(k + l , i).
Proof.
pose f k i := \sum_(j < i.+1) 'C(k, j) * 'C(l, i - j).
suffices{k i} fxx k i: f k.+1 i.+1 = f k i.+1 + f k i.
elim: k i => [i | k IHk [|i]]; last by rewrite -/(f _ _) fxx /f !IHk -binS.
by rewrite big_ord_recl big1_eq addn0 mul1n subn0.
by rewrite big_ord_recl big_ord0 addn0 !bin0 muln1.
rewrite {}/f big_ord_recl (big_ord_recl (i.+1)) !bin0 !mul1n.
rewrite -addnA -big_split /=; congr (_ + _).
by apply: eq_bigr => j _; rewrite -mulnDl.
Qed.
Lemma subn_exp m n k :
m ^ k - n ^ k = (m - n) * (\sum_(i < k) m ^ (k.-1 -i) * n ^ i).
Proof.
case: k => [|k]; first by rewrite big_ord0 muln0.
rewrite mulnBl !big_distrr big_ord_recl big_ord_recr /= subn0 muln1.
rewrite subnn mul1n -!expnS subnDA; congr (_ - _); apply: canRL (addnK _) _.
congr (_ + _); apply: eq_bigr => i _.
by rewrite (mulnCA n) -expnS mulnA -expnS subnSK /=.
Qed.
Lemma predn_exp m k : (m ^ k).-1 = m.-1 * (\sum_(i < k) m ^ i).
Proof.
rewrite -!subn1 -[in LHS](exp1n k) subn_exp; congr (_ * _).
symmetry; rewrite (reindex_inj rev_ord_inj); apply: eq_bigr => i _ /=.
by rewrite -subn1 -subnDA exp1n muln1.
Qed.
Lemma dvdn_pred_predX n e : (n.-1 %| (n ^ e).-1)%N.
Proof. by rewrite predn_exp dvdn_mulr. Qed.
Lemma modn_summ I r (P : pred I) F d :
\sum_(i <- r | P i) F i %% d = \sum_(i <- r | P i) F i %[mod d].
Proof.
by apply/eqP; elim/big_rec2: _ => // i m n _; rewrite modnDml eqn_modDl.
Qed.
Lemma prime_modn_expSn p n : prime p -> n.+1 ^ p = (n ^ p).+1 %[mod p].
Proof.
case: p => // p pP.
rewrite -[(_ ^ _).+1]addn0 (expnDn 1) big_ord_recr big_ord_recl /=.
rewrite subnn binn exp1n !mul1n addnAC -modnDmr; congr ((_ + _) %% _).
apply/eqP/dvdn_sum => -[i ?] _; exact/dvdn_mulr/prime_dvd_bin.
Qed.
Lemma fermat_little a p : prime p -> a ^ p = a %[mod p].
Proof.
move=> pP.
elim: a => [|a IH]; first by rewrite exp0n // prime_gt0.
by rewrite prime_modn_expSn // -addn1 -modnDml IH modnDml addn1.
Qed.
(* Combinatorial characterizations. *)
Section Combinations.
Implicit Types T D : finType.
Lemma card_uniq_tuples T n (A : pred T) :
#|[set t : n.-tuple T | all A t & uniq t]| = #|A| ^_ n.
Proof.
elim: n A => [|n IHn] A.
by rewrite (@eq_card1 _ [tuple]) // => t; rewrite [t]tuple0 inE.
rewrite -sum1dep_card (partition_big (@thead _ _) A) /= => [|t]; last first.
by case/tupleP: t => x t; do 2!case/andP.
rewrite ffactnS -sum_nat_const; apply: eq_bigr => x Ax.
rewrite (cardD1 x) [x \in A]Ax /= -(IHn [predD1 A & x]) -sum1dep_card.
rewrite (reindex (fun t : n.-tuple T => [tuple of x :: t])) /=; last first.
pose ttail (t : n.+1.-tuple T) := [tuple of behead t].
exists ttail => [t _ | t /andP[_ /eqP <-]]; first exact: val_inj.
by rewrite -tuple_eta.
apply: eq_bigl=> t; rewrite Ax theadE eqxx andbT /= andbA; congr (_ && _).
by rewrite all_predI all_predC has_pred1 andbC.
Qed.
Lemma card_inj_ffuns_on D T (R : pred T) :
#|[set f : {ffun D -> T} in ffun_on R | injectiveb f]| = #|R| ^_ #|D|.
Proof.
rewrite -card_uniq_tuples.
have bijFF: {on (_ : pred _), bijective (@Finfun D T)}.
by exists fgraph => x _; [apply: FinfunK | apply: fgraphK].
rewrite -(on_card_preimset (bijFF _)); apply: eq_card => /= t.
rewrite !inE -(big_andE predT) -big_image /= big_all.
by rewrite -[t in RHS]FinfunK -codom_ffun.
Qed.
Lemma card_inj_ffuns D T :
#|[set f : {ffun D -> T} | injectiveb f]| = #|T| ^_ #|D|.
Proof.
rewrite -card_inj_ffuns_on; apply: eq_card => f.
by rewrite 2!inE; case: ffun_onP.
Qed.
Lemma cards_draws T (B : {set T}) k :
#|[set A : {set T} | A \subset B & #|A| == k]| = 'C(#|B|, k).
Proof.
have [ltTk | lekT] := ltnP #|B| k.
rewrite bin_small // eq_card0 // => A.
rewrite inE eqn_leq [k <= _]leqNgt.
have [AsubB /=|//] := boolP (A \subset B).
by rewrite (leq_ltn_trans (subset_leq_card AsubB)) ?andbF.
apply/eqP; rewrite -(eqn_pmul2r (fact_gt0 k)) bin_ffact // eq_sym.
rewrite -sum_nat_cond_const -{1 3}(card_ord k).
rewrite -card_inj_ffuns_on -sum1dep_card.
pose imIk (f : {ffun 'I_k -> T}) := f @: 'I_k.
rewrite (partition_big imIk (fun A => (A \subset B) && (#|A| == k))) /=
=> [|f]; last first.
move=> /andP [/ffun_onP f_ffun /injectiveP inj_f].
rewrite card_imset ?card_ord // eqxx andbT.
by apply/subsetP => x /imsetP [i _ ->]; rewrite f_ffun.
apply/eqP; apply: eq_bigr => A /andP [AsubB /eqP cardAk].
have [f0 inj_f0 im_f0]: exists2 f, injective f & f @: 'I_k = A.
rewrite -cardAk; exists enum_val; first exact: enum_val_inj.
apply/setP=> a; apply/imsetP/idP=> [[i _ ->] | Aa]; first exact: enum_valP.
by exists (enum_rank_in Aa a); rewrite ?enum_rankK_in.
rewrite (reindex (fun p : {ffun _} => [ffun i => f0 (p i)])) /=; last first.
pose ff0' f i := odflt i [pick j | f i == f0 j].
exists (fun f => [ffun i => ff0' f i]) => [p _ | f].
apply/ffunP=> i; rewrite ffunE /ff0'; case: pickP => [j | /(_ (p i))].
by rewrite ffunE (inj_eq inj_f0) => /eqP.
by rewrite ffunE eqxx.
rewrite -im_f0 => /andP[/andP[/ffun_onP f_ffun /injectiveP injf] /eqP im_f].
apply/ffunP=> i; rewrite !ffunE /ff0'; case: pickP => [y /eqP //|].
have /imsetP[j _ eq_f0j_fi]: f i \in f0 @: 'I_k by rewrite -im_f imset_f.
by move/(_ j)/eqP.
rewrite -ffactnn -card_inj_ffuns -sum1dep_card; apply: eq_bigl => p.
rewrite -andbA.
apply/and3P/injectiveP=> [[_ /injectiveP inj_f0p _] i j eq_pij | inj_p].
by apply: inj_f0p; rewrite !ffunE eq_pij.
set f := finfun _.
have injf: injective f by move=> i j /[!ffunE] /inj_f0; apply: inj_p.
have imIkf : imIk f == A.
rewrite eqEcard card_imset // cardAk card_ord leqnn andbT -im_f0.
by apply/subsetP=> x /imsetP[i _ ->]; rewrite ffunE imset_f.
split; [|exact/injectiveP|exact: imIkf].
by apply/ffun_onP => x; apply: (subsetP AsubB); rewrite -(eqP imIkf) imset_f.
Qed.
Lemma card_draws T k : #|[set A : {set T} | #|A| == k]| = 'C(#|T|, k).
Proof.
by rewrite -cardsT -cards_draws; apply: eq_card => A; rewrite !inE subsetT.
Qed.
Lemma card_ltn_sorted_tuples m n :
#|[set t : m.-tuple 'I_n | sorted ltn (map val t)]| = 'C(n, m).
Proof.
have [-> | n_gt0] := posnP n; last pose i0 := Ordinal n_gt0.
case: m => [|m]; last by apply: eq_card0; case/tupleP=> [[]].
by apply: (@eq_card1 _ [tuple]) => t; rewrite [t]tuple0 inE.
rewrite -[n in RHS]card_ord -card_draws.
pose f_t (t : m.-tuple 'I_n) := [set i in t].
pose f_A (A : {set 'I_n}) := [tuple of mkseq (nth i0 (enum A)) m].
have val_fA (A : {set 'I_n}) : #|A| = m -> val (f_A A) = enum A.
by move=> Am; rewrite -[enum _](mkseq_nth i0) -cardE Am.
have inc_A (A : {set 'I_n}) : sorted ltn (map val (enum A)).
rewrite -[enum _](eq_filter (mem_enum _)).
rewrite -(eq_filter (mem_map val_inj _)) -filter_map.
by rewrite (sorted_filter ltn_trans) // unlock val_ord_enum iota_ltn_sorted.
rewrite -!sum1dep_card (reindex_onto f_t f_A) /= => [|A]; last first.
by move/eqP=> cardAm; apply/setP=> x; rewrite inE -(mem_enum A) -val_fA.
apply: eq_bigl => t.
apply/idP/idP => [inc_t|/andP [/eqP t_m /eqP <-]]; last by rewrite val_fA.
have ft_m: #|f_t t| = m.
rewrite cardsE (card_uniqP _) ?size_tuple // -(map_inj_uniq val_inj).
exact: (sorted_uniq ltn_trans ltnn).
rewrite ft_m eqxx -val_eqE val_fA // -(inj_eq (inj_map val_inj)) /=.
apply/eqP/(irr_sorted_eq ltn_trans ltnn) => // y.
by apply/mapP/mapP=> [] [x t_x ->]; exists x; rewrite // mem_enum inE in t_x *.
Qed.
Lemma card_sorted_tuples m n :
#|[set t : m.-tuple 'I_n.+1 | sorted leq (map val t)]| = 'C(m + n, m).
Proof.
set In1 := 'I_n.+1; pose x0 : In1 := ord0.
have add_mnP (i : 'I_m) (x : In1) : i + x < m + n.
by rewrite -ltnS -addSn -!addnS leq_add.
pose add_mn t i := Ordinal (add_mnP i (tnth t i)).
pose add_mn_nat (t : m.-tuple In1) i := i + nth x0 t i.
have add_mnC t: val \o add_mn t =1 add_mn_nat t \o val.
by move=> i; rewrite /= (tnth_nth x0).
pose f_add t := [tuple of map (add_mn t) (ord_tuple m)].
rewrite -card_ltn_sorted_tuples -!sum1dep_card (reindex f_add) /=.
apply: eq_bigl => t; rewrite -map_comp (eq_map (add_mnC t)) map_comp.
rewrite enumT unlock val_ord_enum -[in LHS](drop0 t).
have [m0 | m_gt0] := posnP m.
by rewrite {2}m0 /= drop_oversize // size_tuple m0.
have def_m := subnK m_gt0; rewrite -{2}def_m addn1 /= {1}/add_mn_nat.
move: 0 (m - 1) def_m => i k; rewrite -[in RHS](size_tuple t) => def_m.
rewrite (drop_nth x0) /=; last by rewrite -def_m leq_addl.
elim: k i (nth x0 t i) def_m => [|k IHk] i x /=.
by rewrite add0n => ->; rewrite drop_size.
rewrite addSnnS => def_m; rewrite -addSn leq_add2l -IHk //.
by rewrite (drop_nth x0) // -def_m leq_addl.
pose sub_mn (t : m.-tuple 'I_(m + n)) i : In1 := inord (tnth t i - i).
exists (fun t => [tuple of map (sub_mn t) (ord_tuple m)]) => [t _ | t].
apply: eq_from_tnth => i; apply: val_inj.
by rewrite /sub_mn !(tnth_ord_tuple, tnth_map) addKn inord_val.
rewrite inE /= => inc_t; apply: eq_from_tnth => i; apply: val_inj.
rewrite tnth_map tnth_ord_tuple /= tnth_map tnth_ord_tuple.
suffices [le_i_ti le_ti_ni]: i <= tnth t i /\ tnth t i <= i + n.
by rewrite /sub_mn inordK ?subnKC // ltnS leq_subLR.
pose y0 := tnth t i; rewrite (tnth_nth y0) -(nth_map _ (val i)) ?size_tuple //.
case def_e: (map _ _) => [|x e] /=; first by rewrite nth_nil ?leq_addr.
set nth_i := nth (i : nat); rewrite def_e in inc_t; split.
have: i < size (x :: e) by rewrite -def_e size_map size_tuple ltn_ord.
elim: (val i) => //= j IHj lt_j_e.
by apply: leq_trans (pathP (val i) inc_t _ lt_j_e); rewrite ltnS IHj 1?ltnW.
move: (_ - _) (subnK (valP i)) => k /=.
elim: k (val i) => /= [|k IHk] j; rewrite -ltnS -addSn ?add0n => def_m.
by rewrite def_m -def_e /nth_i (nth_map y0) ?ltn_ord // size_tuple -def_m.
rewrite (leq_trans _ (IHk _ _)) -1?addSnnS //; apply: (pathP _ inc_t).
rewrite -ltnS (leq_trans (leq_addl k _)) // -addSnnS def_m.
by rewrite -(size_tuple t) -(size_map val) def_e.
Qed.
Lemma card_partial_ord_partitions m n :
#|[set t : m.-tuple 'I_n.+1 | \sum_(i <- t) i <= n]| = 'C(m + n, m).
Proof.
symmetry; set In1 := 'I_n.+1; pose x0 : In1 := ord0.
pose add_mn (i j : In1) : In1 := inord (i + j).
pose f_add (t : m.-tuple In1) := [tuple of scanl add_mn x0 t].
rewrite -card_sorted_tuples -!sum1dep_card (reindex f_add) /=.
apply: eq_bigl => t; rewrite -[\sum_(i <- t) i]add0n.
transitivity (path leq x0 (map val (f_add t))) => /=; first by case: map.
rewrite -{1 2}[0]/(val x0); elim: {t}(val t) (x0) => /= [|x t IHt] s.
by rewrite big_nil addn0 -ltnS ltn_ord.
rewrite big_cons addnA IHt /= val_insubd ltnS.
have [_ | ltn_n_sx] := leqP (s + x) n; first by rewrite leq_addr.
rewrite -(leq_add2r x) leqNgt (leq_trans (valP x)) //=.
by rewrite leqNgt (leq_trans ltn_n_sx) ?leq_addr.
pose sub_mn (i j : In1) := Ordinal (leq_ltn_trans (leq_subr i j) (valP j)).
exists (fun t : m.-tuple In1 => [tuple of pairmap sub_mn x0 t]) => /= t inc_t.
apply: val_inj => /=; have{inc_t}: path leq x0 (map val (f_add t)).
by move: inc_t; rewrite inE /=; case: map.
rewrite [map _ _]/=; elim: {t}(val t) (x0) => //= x t IHt s.
case/andP=> le_s_sx /IHt->; congr (_ :: _); apply: val_inj => /=.
move: le_s_sx; rewrite val_insubd.
case le_sx_n: (_ < n.+1); first by rewrite addKn.
by case: (val s) le_sx_n; rewrite ?ltn_ord.
apply: val_inj => /=; have{inc_t}: path leq x0 (map val t).
by move: inc_t; rewrite inE /=; case: map.
elim: {t}(val t) (x0) => //= x t IHt s /andP[le_s_sx inc_t].
suffices ->: add_mn s (sub_mn s x) = x by rewrite IHt.
by apply: val_inj; rewrite /add_mn /= subnKC ?inord_val.
Qed.
Lemma card_ord_partitions m n :
#|[set t : m.+1.-tuple 'I_n.+1 | \sum_(i <- t) i == n]| = 'C(m + n, m).
Proof.
symmetry; set In1 := 'I_n.+1; pose x0 : In1 := ord0.
pose f_add (t : m.-tuple In1) := [tuple of sub_ord (\sum_(x <- t) x) :: t].
rewrite -card_partial_ord_partitions -!sum1dep_card (reindex f_add) /=.
by apply: eq_bigl => t; rewrite big_cons /= addnC (sameP maxn_idPr eqP) maxnE.
exists (fun t : m.+1.-tuple In1 => [tuple of behead t]) => [t _|].
exact: val_inj.
case/tupleP=> x t /[!(inE, big_cons)] /eqP def_n.
by apply: val_inj; congr (_ :: _); apply: val_inj; rewrite /= -{1}def_n addnK.
Qed.
End Combinations.
|
Variables.lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro
-/
import Mathlib.Data.Finsupp.Lex
import Mathlib.Algebra.MvPolynomial.Degrees
/-!
# Variables of polynomials
This file establishes many results about the variable sets of a multivariate polynomial.
The *variable set* of a polynomial $P \in R[X]$ is a `Finset` containing each $x \in X$
that appears in a monomial in $P$.
## Main declarations
* `MvPolynomial.vars p` : the finset of variables occurring in `p`.
For example if `p = x⁴y+yz` then `vars p = {x, y, z}`
## Notation
As in other polynomial files, we typically use the notation:
+ `σ τ : Type*` (indexing the variables)
+ `R : Type*` `[CommSemiring R]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `MvPolynomial σ R` which mathematicians might call `X^s`
+ `r : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : MvPolynomial σ R`
-/
noncomputable section
open Set Function Finsupp AddMonoidAlgebra
universe u v w
variable {R : Type u} {S : Type v}
namespace MvPolynomial
variable {σ τ : Type*} {r : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section CommSemiring
variable [CommSemiring R] {p q : MvPolynomial σ R}
section Vars
/-! ### `vars` -/
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : MvPolynomial σ R) : Finset σ :=
letI := Classical.decEq σ
p.degrees.toFinset
theorem vars_def [DecidableEq σ] (p : MvPolynomial σ R) : p.vars = p.degrees.toFinset := by
rw [vars]
convert rfl
@[simp]
theorem vars_0 : (0 : MvPolynomial σ R).vars = ∅ := by
classical rw [vars_def, degrees_zero, Multiset.toFinset_zero]
@[simp]
theorem vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support := by
classical rw [vars_def, degrees_monomial_eq _ _ h, Finsupp.toFinset_toMultiset]
@[simp]
theorem vars_C : (C r : MvPolynomial σ R).vars = ∅ := by
classical rw [vars_def, degrees_C, Multiset.toFinset_zero]
@[simp]
theorem vars_X [Nontrivial R] : (X n : MvPolynomial σ R).vars = {n} := by
rw [X, vars_monomial (one_ne_zero' R), Finsupp.support_single_ne_zero _ (one_ne_zero' ℕ)]
theorem mem_vars (i : σ) : i ∈ p.vars ↔ ∃ d ∈ p.support, i ∈ d.support := by
classical simp only [vars_def, Multiset.mem_toFinset, mem_degrees, mem_support_iff]
theorem mem_support_notMem_vars_zero {f : MvPolynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support)
{v : σ} (h : v ∉ vars f) : x v = 0 := by
contrapose! h
exact (mem_vars v).mpr ⟨x, H, Finsupp.mem_support_iff.mpr h⟩
@[deprecated (since := "2025-05-23")]
alias mem_support_not_mem_vars_zero := mem_support_notMem_vars_zero
theorem vars_add_subset [DecidableEq σ] (p q : MvPolynomial σ R) :
(p + q).vars ⊆ p.vars ∪ q.vars := by
intro x hx
simp only [vars_def, Finset.mem_union, Multiset.mem_toFinset] at hx ⊢
simpa using Multiset.mem_of_le degrees_add_le hx
theorem vars_add_of_disjoint [DecidableEq σ] (h : Disjoint p.vars q.vars) :
(p + q).vars = p.vars ∪ q.vars := by
refine (vars_add_subset p q).antisymm fun x hx => ?_
simp only [vars_def, Multiset.disjoint_toFinset] at h hx ⊢
rwa [degrees_add_of_disjoint h, Multiset.toFinset_union]
section Mul
theorem vars_mul [DecidableEq σ] (φ ψ : MvPolynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars := by
simp_rw [vars_def, ← Multiset.toFinset_add, Multiset.toFinset_subset]
exact Multiset.subset_of_le degrees_mul_le
@[simp]
theorem vars_one : (1 : MvPolynomial σ R).vars = ∅ :=
vars_C
theorem vars_pow (φ : MvPolynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars := by
classical
induction n with
| zero => simp
| succ n ih =>
rw [pow_succ']
apply Finset.Subset.trans (vars_mul _ _)
exact Finset.union_subset (Finset.Subset.refl _) ih
/-- The variables of the product of a family of polynomials
are a subset of the union of the sets of variables of each polynomial.
-/
theorem vars_prod {ι : Type*} [DecidableEq σ] {s : Finset ι} (f : ι → MvPolynomial σ R) :
(∏ i ∈ s, f i).vars ⊆ s.biUnion fun i => (f i).vars := by
classical
induction s using Finset.induction_on with
| empty => simp
| insert _ _ hs hsub =>
simp only [hs, Finset.biUnion_insert, Finset.prod_insert, not_false_iff]
apply Finset.Subset.trans (vars_mul _ _)
exact Finset.union_subset_union (Finset.Subset.refl _) hsub
section IsDomain
variable {A : Type*} [CommRing A] [NoZeroDivisors A]
theorem vars_C_mul (a : A) (ha : a ≠ 0) (φ : MvPolynomial σ A) :
(C a * φ : MvPolynomial σ A).vars = φ.vars := by
ext1 i
simp only [mem_vars, mem_support_iff]
apply exists_congr
intro d
apply and_congr _ Iff.rfl
rw [coeff_C_mul, mul_ne_zero_iff, eq_true ha, true_and]
end IsDomain
end Mul
section Sum
variable {ι : Type*} (t : Finset ι) (φ : ι → MvPolynomial σ R)
theorem vars_sum_subset [DecidableEq σ] :
(∑ i ∈ t, φ i).vars ⊆ Finset.biUnion t fun i => (φ i).vars := by
classical
induction t using Finset.induction_on with
| empty => simp
| insert _ _ has hsum =>
rw [Finset.biUnion_insert, Finset.sum_insert has]
refine Finset.Subset.trans
(vars_add_subset _ _) (Finset.union_subset_union (Finset.Subset.refl _) ?_)
assumption
theorem vars_sum_of_disjoint [DecidableEq σ] (h : Pairwise <| (Disjoint on fun i => (φ i).vars)) :
(∑ i ∈ t, φ i).vars = Finset.biUnion t fun i => (φ i).vars := by
classical
induction t using Finset.induction_on with
| empty => simp
| insert _ _ has hsum =>
rw [Finset.biUnion_insert, Finset.sum_insert has, vars_add_of_disjoint, hsum]
unfold Pairwise onFun at h
simp only [Finset.disjoint_iff_ne] at h ⊢
grind
end Sum
section Map
variable [CommSemiring S] (f : R →+* S)
variable (p)
theorem vars_map : (map f p).vars ⊆ p.vars := by
classical simp [vars_def, Multiset.subset_of_le degrees_map_le]
variable {f}
theorem vars_map_of_injective (hf : Injective f) : (map f p).vars = p.vars := by
simp [vars, degrees_map_of_injective _ hf]
theorem vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) :
(monomial (Finsupp.single i e) r).vars = {i} := by
rw [vars_monomial hr, Finsupp.support_single_ne_zero _ he]
theorem vars_eq_support_biUnion_support [DecidableEq σ] :
p.vars = p.support.biUnion Finsupp.support := by
ext i
rw [mem_vars, Finset.mem_biUnion]
end Map
end Vars
section EvalVars
/-! ### `vars` and `eval` -/
variable [CommSemiring S]
theorem eval₂Hom_eq_constantCoeff_of_vars (f : R →+* S) {g : σ → S} {p : MvPolynomial σ R}
(hp : ∀ i ∈ p.vars, g i = 0) : eval₂Hom f g p = f (constantCoeff p) := by
conv_lhs => rw [p.as_sum]
simp only [map_sum, eval₂Hom_monomial]
by_cases h0 : constantCoeff p = 0
on_goal 1 =>
rw [h0, f.map_zero, Finset.sum_eq_zero]
intro d hd
on_goal 2 =>
rw [Finset.sum_eq_single (0 : σ →₀ ℕ)]
· rw [Finsupp.prod_zero_index, mul_one]
rfl
on_goal 1 => intro d hd hd0
on_goal 3 =>
rw [constantCoeff_eq, coeff, ← Ne, ← Finsupp.mem_support_iff] at h0
intro
contradiction
repeat'
obtain ⟨i, hi⟩ : Finset.Nonempty (Finsupp.support d) := by
rw [constantCoeff_eq, coeff, ← Finsupp.notMem_support_iff] at h0
rw [Finset.nonempty_iff_ne_empty, Ne, Finsupp.support_eq_empty]
rintro rfl
contradiction
rw [Finsupp.prod, Finset.prod_eq_zero hi, mul_zero]
rw [hp, zero_pow (Finsupp.mem_support_iff.1 hi)]
rw [mem_vars]
exact ⟨d, hd, hi⟩
theorem aeval_eq_constantCoeff_of_vars [Algebra R S] {g : σ → S} {p : MvPolynomial σ R}
(hp : ∀ i ∈ p.vars, g i = 0) : aeval g p = algebraMap _ _ (constantCoeff p) :=
eval₂Hom_eq_constantCoeff_of_vars _ hp
theorem eval₂Hom_congr' {f₁ f₂ : R →+* S} {g₁ g₂ : σ → S} {p₁ p₂ : MvPolynomial σ R} :
f₁ = f₂ →
(∀ i, i ∈ p₁.vars → i ∈ p₂.vars → g₁ i = g₂ i) →
p₁ = p₂ → eval₂Hom f₁ g₁ p₁ = eval₂Hom f₂ g₂ p₂ := by
rintro rfl h rfl
rw [p₁.as_sum]
simp only [map_sum, eval₂Hom_monomial]
apply Finset.sum_congr rfl
intro d hd
congr 1
simp only [Finsupp.prod]
apply Finset.prod_congr rfl
intro i hi
have : i ∈ p₁.vars := by
rw [mem_vars]
exact ⟨d, hd, hi⟩
rw [h i this this]
/-- If `f₁` and `f₂` are ring homs out of the polynomial ring and `p₁` and `p₂` are polynomials,
then `f₁ p₁ = f₂ p₂` if `p₁ = p₂` and `f₁` and `f₂` are equal on `R` and on the variables
of `p₁`. -/
theorem hom_congr_vars {f₁ f₂ : MvPolynomial σ R →+* S} {p₁ p₂ : MvPolynomial σ R}
(hC : f₁.comp C = f₂.comp C) (hv : ∀ i, i ∈ p₁.vars → i ∈ p₂.vars → f₁ (X i) = f₂ (X i))
(hp : p₁ = p₂) : f₁ p₁ = f₂ p₂ :=
calc
f₁ p₁ = eval₂Hom (f₁.comp C) (f₁ ∘ X) p₁ := RingHom.congr_fun (by ext <;> simp) _
_ = eval₂Hom (f₂.comp C) (f₂ ∘ X) p₂ := eval₂Hom_congr' hC hv hp
_ = f₂ p₂ := RingHom.congr_fun (by ext <;> simp) _
theorem exists_rename_eq_of_vars_subset_range (p : MvPolynomial σ R) (f : τ → σ) (hfi : Injective f)
(hf : ↑p.vars ⊆ Set.range f) : ∃ q : MvPolynomial τ R, rename f q = p :=
⟨aeval (fun i : σ => Option.elim' 0 X <| partialInv f i) p,
by
change (rename f).toRingHom.comp _ p = RingHom.id _ p
refine hom_congr_vars ?_ ?_ ?_
· ext1
simp [algebraMap_eq]
· intro i hip _
rcases hf hip with ⟨i, rfl⟩
simp [partialInv_left hfi]
· rfl⟩
theorem vars_rename [DecidableEq τ] (f : σ → τ) (φ : MvPolynomial σ R) :
(rename f φ).vars ⊆ φ.vars.image f := by
classical
intro i hi
simp only [vars_def, Multiset.mem_toFinset, Finset.mem_image] at hi ⊢
simpa only [Multiset.mem_map] using degrees_rename _ _ hi
theorem mem_vars_rename (f : σ → τ) (φ : MvPolynomial σ R) {j : τ} (h : j ∈ (rename f φ).vars) :
∃ i : σ, i ∈ φ.vars ∧ f i = j := by
classical
simpa only [exists_prop, Finset.mem_image] using vars_rename f φ h
lemma aeval_ite_mem_eq_self (q : MvPolynomial σ R) {s : Set σ} (hs : q.vars.toSet ⊆ s)
[∀ i, Decidable (i ∈ s)] :
MvPolynomial.aeval (fun i ↦ if i ∈ s then .X i else 0) q = q := by
rw [MvPolynomial.as_sum q, MvPolynomial.aeval_sum]
refine Finset.sum_congr rfl fun u hu ↦ ?_
rw [MvPolynomial.aeval_monomial, MvPolynomial.monomial_eq]
congr 1
exact Finsupp.prod_congr (fun i hi ↦ by simp [hs ((MvPolynomial.mem_vars _).mpr ⟨u, hu, hi⟩)])
end EvalVars
section Lex
variable [LinearOrder σ]
lemma leadingCoeff_toLex : p.leadingCoeff toLex = p.coeff (ofLex <| p.supDegree toLex) := by
rw [leadingCoeff]
apply congr_arg p.coeff
apply toLex.injective
rw [Function.rightInverse_invFun toLex.surjective, toLex_ofLex]
lemma supDegree_toLex_C (r : R) : supDegree toLex (C (σ := σ) r) = 0 := by
classical
exact (supDegree_single _ r).trans (ite_eq_iff'.mpr ⟨fun _ => rfl, fun _ => rfl⟩)
lemma leadingCoeff_toLex_C (r : R) : leadingCoeff toLex (C (σ := σ) r) = r :=
leadingCoeff_single toLex.injective _ r
end Lex
end CommSemiring
end MvPolynomial
|
Sublocale.lean
|
/-
Copyright (c) 2025 Christian Krause. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chriara Cimino, Christian Krause
-/
import Mathlib.Order.Nucleus
import Mathlib.Order.SupClosed
/-!
# Sublocale
Locales are the dual concept to frames. Locale theory is a branch of point-free topology, where
intuitively locales are like topological spaces which may or may not have enough points.
Sublocales of a locale generalize the concept of subspaces in topology to the point-free setting.
## TODO
Create separate definitions for `sInf_mem` and `HImpClosed` (also useful for `CompleteSublattice`)
## References
* [J. Picada A. Pultr, *Frames and Locales*][picado2012]
* https://ncatlab.org/nlab/show/sublocale
* https://ncatlab.org/nlab/show/nucleus
-/
variable {X : Type*} [Order.Frame X]
open Set
/-- A sublocale of a locale `X` is a set `S` which is closed under all meets and such that
`x ⇨ s ∈ S` for all `x : X` and `s ∈ S`.
Note that locales are the same thing as frames, but with reverse morphisms, which is why we assume
`Frame X`. We only need to define locales categorically. See `Locale`. -/
structure Sublocale (X : Type*) [Order.Frame X] where
/-- The set corresponding to the sublocale. -/
carrier : Set X
/-- A sublocale is closed under all meets.
Do NOT use directly. Use `Sublocale.sInf_mem` instead. -/
sInf_mem' : ∀ s ⊆ carrier, sInf s ∈ carrier
/-- A sublocale is closed under heyting implication.
Do NOT use directly. Use `Sublocale.himp_mem` instead. -/
himp_mem' : ∀ a b, b ∈ carrier → a ⇨ b ∈ carrier
namespace Sublocale
variable {ι : Sort*} {S T : Sublocale X} {s : Set X} {f : ι → X} {a b : X}
instance instSetLike : SetLike (Sublocale X) X where
coe x := x.carrier
coe_injective' s1 s2 h := by cases s1; congr
@[simp] lemma mem_carrier : a ∈ S.carrier ↔ a ∈ S := .rfl
@[simp] lemma mem_mk (carrier : Set X) (sInf_mem' himp_mem') :
a ∈ mk carrier sInf_mem' himp_mem' ↔ a ∈ carrier := .rfl
@[simp] lemma mk_le_mk (carrier₁ carrier₂ : Set X) (sInf_mem'₁ sInf_mem'₂ himp_mem'₁ himp_mem'₂) :
mk carrier₁ sInf_mem'₁ himp_mem'₁ ≤ mk carrier₂ sInf_mem'₂ himp_mem'₂ ↔ carrier₁ ⊆ carrier₂ :=
.rfl
@[gcongr]
alias ⟨_, _root_.GCongr.Sublocale.mk_le_mk⟩ := mk_le_mk
initialize_simps_projections Sublocale (carrier → coe, as_prefix coe)
@[ext] lemma ext (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := SetLike.ext h
lemma sInf_mem (hs : s ⊆ S) : sInf s ∈ S := S.sInf_mem' _ hs
lemma iInf_mem (hf : ∀ i, f i ∈ S) : ⨅ i, f i ∈ S := S.sInf_mem <| by simpa [range_subset_iff]
lemma infClosed : InfClosed (S : Set X) := by
rintro a ha b hb; rw [← sInf_pair]; exact S.sInf_mem (pair_subset ha hb)
lemma inf_mem (ha : a ∈ S) (hb : b ∈ S) : a ⊓ b ∈ S := S.infClosed ha hb
lemma top_mem : ⊤ ∈ S := by simpa using S.sInf_mem <| empty_subset _
lemma himp_mem (hb : b ∈ S) : a ⇨ b ∈ S := S.himp_mem' _ _ hb
instance carrier.instSemilatticeInf : SemilatticeInf S := Subtype.semilatticeInf fun _ _ ↦ inf_mem
instance carrier.instOrderTop : OrderTop S := Subtype.orderTop top_mem
instance carrier.instHImp : HImp S where himp a b := ⟨a ⇨ b, S.himp_mem b.2⟩
instance carrier.instInfSet : InfSet S where
sInf x := ⟨sInf (Subtype.val '' x), S.sInf_mem' _
(by simp_rw [image_subset_iff, subset_def]; simp)⟩
@[simp, norm_cast] lemma coe_inf (a b : S) : (a ⊓ b).val = ↑a ⊓ ↑b := rfl
@[simp, norm_cast] lemma coe_sInf (s : Set S) : (sInf s).val = sInf (Subtype.val '' s) := rfl
@[simp, norm_cast] lemma coe_iInf (f : ι → S) : (⨅ i, f i).val = ⨅ i, (f i).val := by
simp [iInf, ← range_comp, Function.comp_def]
instance carrier.instCompleteLattice : CompleteLattice S where
__ := instSemilatticeInf
__ := instOrderTop
__ := completeLatticeOfInf S <| by simp [isGLB_iff_le_iff, lowerBounds, ← Subtype.coe_le_coe]
@[simp, norm_cast] lemma coe_himp (a b : S) : (a ⇨ b).val = a.val ⇨ b.val := rfl
instance carrier.instHeytingAlgebra : HeytingAlgebra S where
le_himp_iff a b c := by simp [← Subtype.coe_le_coe, ← @Sublocale.coe_inf, himp]
compl a := a ⇨ ⊥
himp_bot _ := rfl
instance carrier.instFrame : Order.Frame S where
__ := carrier.instHeytingAlgebra
__ := carrier.instCompleteLattice
/-- See `Sublocale.restrict` for the public-facing version. -/
private def restrictAux (S : Sublocale X) (a : X) : S := sInf {s : S | a ≤ s}
private lemma le_restrictAux : a ≤ S.restrictAux a := by simp +contextual [restrictAux]
/-- See `Sublocale.giRestrict` for the public-facing version. -/
private def giAux (S : Sublocale X) : GaloisInsertion S.restrictAux Subtype.val where
choice x hx := ⟨x, by
rw [le_antisymm le_restrictAux hx]
exact S.sInf_mem <| by simp +contextual [Set.subset_def]⟩
gc a b := by
constructor <;> intro h
· exact le_trans (by simp +contextual [restrictAux]) h
· exact sInf_le (by simp [h])
le_l_u x := by simp [restrictAux]
choice_eq a h := by simp [le_antisymm_iff, restrictAux, sInf_le]
/-- The restriction from a locale X into the sublocale S. -/
def restrict (S : Sublocale X) : FrameHom X S where
toFun x := sInf {s : S | x ≤ s}
map_inf' a b := by
change Sublocale.restrictAux S (a ⊓ b) = Sublocale.restrictAux S a ⊓ Sublocale.restrictAux S b
refine eq_of_forall_ge_iff (fun s ↦ Iff.symm ?_)
calc
_ ↔ S.restrictAux a ≤ S.restrictAux b ⇨ s := by simp
_ ↔ S.restrictAux b ≤ a ⇨ s := by rw [S.giAux.gc.le_iff_le, @le_himp_comm, coe_himp]
_ ↔ b ≤ a ⇨ s := by
set c : S := ⟨a ⇨ s, S.himp_mem s.coe_prop⟩
change Sublocale.restrictAux S b ≤ c.val ↔ b ≤ c
rw [S.giAux.u_le_u_iff, S.giAux.gc.le_iff_le]
_ ↔ S.restrictAux (a ⊓ b) ≤ s := by simp [inf_comm, S.giAux.gc.le_iff_le]
map_sSup' s := by
change Sublocale.restrictAux S (sSup s) = _
rw [S.giAux.gc.l_sSup, sSup_image]
rfl
map_top' := by
refine le_antisymm le_top ?_
change _ ≤ restrictAux S ⊤
rw [← Subtype.coe_le_coe, S.giAux.gc.u_top]
simp [restrictAux, sInf]
/-- The restriction corresponding to a sublocale forms a Galois insertion with the forgetful map
from the sublocale to the original locale. -/
def giRestrict (S : Sublocale X) : GaloisInsertion S.restrict Subtype.val := S.giAux
@[simp] lemma restrict_of_mem (ha : a ∈ S) : S.restrict a = ⟨a, ha⟩ := S.giRestrict.l_u_eq ⟨a, ha⟩
/-- The restriction from the locale X into a sublocale is a nucleus. -/
@[simps]
def toNucleus (S : Sublocale X) : Nucleus X where
toFun x := S.restrict x
map_inf' _ _ := by simp [S.giRestrict.gc.u_inf]
idempotent' _ := by rw [S.giRestrict.gc.l_u_l_eq_l]
le_apply' _ := S.giRestrict.gc.le_u_l _
@[simp] lemma range_toNucleus : range S.toNucleus = S := by
ext x
constructor
· simp +contextual [eq_comm]
· intro hx
exact ⟨x, by simp_all⟩
@[simp] lemma toNucleus_le_toNucleus : S.toNucleus ≤ T.toNucleus ↔ T ≤ S := by
simp [← Nucleus.range_subset_range]
end Sublocale
namespace Nucleus
/-- The range of a nucleus is a sublocale. -/
@[simps]
def toSublocale (n : Nucleus X) : Sublocale X where
carrier := range n
sInf_mem' a h := by
rw [mem_range]
refine le_antisymm (le_sInf_iff.mpr (fun b h1 ↦ ?_)) le_apply
simp_rw [subset_def, mem_range] at h
rw [← h b h1]
exact n.monotone (sInf_le h1)
himp_mem' a b h := by rw [mem_range, ← h, map_himp_apply] at *
@[simp]
lemma mem_toSublocale {n : Nucleus X} {x : X} : x ∈ n.toSublocale ↔ ∃ y, n y = x := .rfl
@[simp] lemma toSublocale_le_toSublocale {m n : Nucleus X} :
m.toSublocale ≤ n.toSublocale ↔ n ≤ m := by simp [← SetLike.coe_subset_coe]
@[gcongr]
alias ⟨_, _root_.GCongr.Nucleus.toSublocale_le_toSublocale⟩ := toSublocale_le_toSublocale
@[simp] lemma restrict_toSublocale (n : Nucleus X) (x : X) :
n.toSublocale.restrict x = ⟨n x, x, rfl⟩ := by
ext
simpa [Sublocale.restrict, sInf_image, le_antisymm_iff (a := iInf _)] using
⟨iInf₂_le_of_le ⟨n x, x, rfl⟩ n.le_apply le_rfl, fun y hxy ↦ by simpa using n.monotone hxy⟩
end Nucleus
/-- The nuclei on a frame corresponds exactly to the sublocales on this frame.
The sublocales are ordered dually to the nuclei. -/
def nucleusIsoSublocale : (Nucleus X)ᵒᵈ ≃o Sublocale X where
toFun n := n.ofDual.toSublocale
invFun s := .toDual s.toNucleus
left_inv := by simp [Function.LeftInverse, Nucleus.ext_iff]
right_inv S := by ext x; simpa using ⟨by simp +contextual [eq_comm], fun hx ↦ ⟨x, by simp [hx]⟩⟩
map_rel_iff' := by simp
lemma nucleusIsoSublocale.eq_toSublocale : Nucleus.toSublocale = @nucleusIsoSublocale X _ := rfl
lemma nucleusIsoSublocale.symm_eq_toNucleus :
Sublocale.toNucleus = (@nucleusIsoSublocale X _).symm := rfl
instance Sublocale.instCompleteLattice : CompleteLattice (Sublocale X) :=
nucleusIsoSublocale.toGaloisInsertion.liftCompleteLattice
instance Sublocale.instCoframeMinimalAxioms : Order.Coframe.MinimalAxioms (Sublocale X) where
iInf_sup_le_sup_sInf a s := by simp [← toNucleus_le_toNucleus,
nucleusIsoSublocale.symm_eq_toNucleus, nucleusIsoSublocale.symm.map_sup,
nucleusIsoSublocale.symm.map_sInf, sup_iInf_eq, nucleusIsoSublocale.symm.map_iInf]
instance Sublocale.instCoframe : Order.Coframe (Sublocale X) :=
.ofMinimalAxioms instCoframeMinimalAxioms
|
Dual.lean
|
/-
Copyright (c) 2020 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.Analysis.InnerProductSpace.Projection.Submodule
import Mathlib.Analysis.Normed.Group.NullSubmodule
import Mathlib.Topology.Algebra.Module.PerfectPairing
/-!
# The Fréchet-Riesz representation theorem
We consider an inner product space `E` over `𝕜`, which is either `ℝ` or `ℂ`. We define
`toDualMap`, a conjugate-linear isometric embedding of `E` into its dual, which maps an element `x`
of the space to `fun y => ⟪x, y⟫`.
Under the hypothesis of completeness (i.e., for Hilbert spaces), we upgrade this to `toDual`, a
conjugate-linear isometric *equivalence* of `E` onto its dual; that is, we establish the
surjectivity of `toDualMap`. This is the Fréchet-Riesz representation theorem: every element of the
dual of a Hilbert space `E` has the form `fun u => ⟪x, u⟫` for some `x : E`.
For a bounded sesquilinear form `B : E →L⋆[𝕜] E →L[𝕜] 𝕜`,
we define a map `InnerProductSpace.continuousLinearMapOfBilin B : E →L[𝕜] E`,
given by substituting `E →L[𝕜] 𝕜` with `E` using `toDual`.
## References
* [M. Einsiedler and T. Ward, *Functional Analysis, Spectral Theory, and Applications*]
[EinsiedlerWard2017]
## Tags
dual, Fréchet-Riesz
-/
noncomputable section
open ComplexConjugate Module
universe u v
namespace InnerProductSpace
open RCLike ContinuousLinearMap
variable (𝕜 E : Type*)
section Seminormed
variable [RCLike 𝕜] [SeminormedAddCommGroup E] [InnerProductSpace 𝕜 E]
local notation "⟪" x ", " y "⟫" => inner 𝕜 x y
local postfix:90 "†" => starRingEnd _
/-- An element `x` of an inner product space `E` induces an element of the strong dual space
`StrongDual 𝕜 E`, the map `fun y => ⟪x, y⟫`; moreover this operation is a conjugate-linear isometric
embedding of `E` into `StrongDual 𝕜 E`.
If `E` is complete, this operation is surjective, hence a conjugate-linear isometric equivalence;
see `toDual`.
-/
def toDualMap : E →ₗᵢ⋆[𝕜] StrongDual 𝕜 E :=
{ innerSL 𝕜 with norm_map' := innerSL_apply_norm _ }
variable {E}
@[simp]
theorem toDualMap_apply {x y : E} : toDualMap 𝕜 E x y = ⟪x, y⟫ :=
rfl
variable {𝕜} in
@[simp]
theorem _root_.innerSL_inj {E : Type*} [NormedAddCommGroup E] [InnerProductSpace 𝕜 E] {x y : E} :
innerSL 𝕜 x = innerSL 𝕜 y ↔ x = y :=
(toDualMap 𝕜 E).injective.eq_iff
section NullSubmodule
open LinearMap
/-- For each `x : E`, the kernel of `⟪x, ⬝⟫` includes the null space. -/
lemma nullSubmodule_le_ker_toDualMap_right (x : E) : nullSubmodule 𝕜 E ≤ ker (toDualMap 𝕜 E x) :=
fun _ hx ↦ inner_eq_zero_of_right x ((mem_nullSubmodule_iff).mp hx)
/-- The kernel of the map `x ↦ ⟪·, x⟫` includes the null space. -/
lemma nullSubmodule_le_ker_toDualMap_left : nullSubmodule 𝕜 E ≤ ker (toDualMap 𝕜 E) :=
fun _ hx ↦ ContinuousLinearMap.ext <| fun y ↦ inner_eq_zero_of_left y hx
end NullSubmodule
end Seminormed
section Normed
variable [RCLike 𝕜] [NormedAddCommGroup E] [InnerProductSpace 𝕜 E]
local notation "⟪" x ", " y "⟫" => inner 𝕜 x y
local postfix:90 "†" => starRingEnd _
theorem innerSL_norm [Nontrivial E] : ‖(innerSL 𝕜 : E →L⋆[𝕜] E →L[𝕜] 𝕜)‖ = 1 :=
show ‖(toDualMap 𝕜 E).toContinuousLinearMap‖ = 1 from LinearIsometry.norm_toContinuousLinearMap _
variable {E 𝕜}
theorem ext_inner_left_basis {ι : Type*} {x y : E} (b : Basis ι 𝕜 E)
(h : ∀ i : ι, ⟪b i, x⟫ = ⟪b i, y⟫) : x = y := by
apply (toDualMap 𝕜 E).map_eq_iff.mp
refine (Function.Injective.eq_iff ContinuousLinearMap.coe_injective).mp (b.ext ?_)
intro i
simp only [ContinuousLinearMap.coe_coe]
rw [toDualMap_apply, toDualMap_apply]
rw [← inner_conj_symm]
conv_rhs => rw [← inner_conj_symm]
exact congr_arg conj (h i)
theorem ext_inner_right_basis {ι : Type*} {x y : E} (b : Basis ι 𝕜 E)
(h : ∀ i : ι, ⟪x, b i⟫ = ⟪y, b i⟫) : x = y := by
refine ext_inner_left_basis b fun i => ?_
rw [← inner_conj_symm]
conv_rhs => rw [← inner_conj_symm]
exact congr_arg conj (h i)
variable (𝕜) (E)
variable [CompleteSpace E]
/-- **Fréchet-Riesz representation**: any `ℓ` in the dual of a Hilbert space `E` is of the form
`fun u => ⟪y, u⟫` for some `y : E`, i.e. `toDualMap` is surjective.
-/
def toDual : E ≃ₗᵢ⋆[𝕜] StrongDual 𝕜 E :=
LinearIsometryEquiv.ofSurjective (toDualMap 𝕜 E)
(by
intro ℓ
set Y := LinearMap.ker ℓ
by_cases htriv : Y = ⊤
· have hℓ : ℓ = 0 := by
have h' := LinearMap.ker_eq_top.mp htriv
rw [← coe_zero] at h'
apply coe_injective
exact h'
exact ⟨0, by simp [hℓ]⟩
· rw [← Submodule.orthogonal_eq_bot_iff] at htriv
change Yᗮ ≠ ⊥ at htriv
rw [Submodule.ne_bot_iff] at htriv
obtain ⟨z : E, hz : z ∈ Yᗮ, z_ne_0 : z ≠ 0⟩ := htriv
refine ⟨(starRingEnd (R := 𝕜) (ℓ z) / ⟪z, z⟫) • z, ?_⟩
apply ContinuousLinearMap.ext
intro x
have h₁ : ℓ z • x - ℓ x • z ∈ Y := by
rw [LinearMap.mem_ker, map_sub, ContinuousLinearMap.map_smul,
ContinuousLinearMap.map_smul, Algebra.id.smul_eq_mul, Algebra.id.smul_eq_mul, mul_comm]
exact sub_self (ℓ x * ℓ z)
have h₂ : ℓ z * ⟪z, x⟫ = ℓ x * ⟪z, z⟫ :=
haveI h₃ :=
calc
0 = ⟪z, ℓ z • x - ℓ x • z⟫ := by
rw [(Y.mem_orthogonal' z).mp hz]
exact h₁
_ = ⟪z, ℓ z • x⟫ - ⟪z, ℓ x • z⟫ := by rw [inner_sub_right]
_ = ℓ z * ⟪z, x⟫ - ℓ x * ⟪z, z⟫ := by simp [inner_smul_right]
sub_eq_zero.mp (Eq.symm h₃)
have h₄ :=
calc
⟪(ℓ z† / ⟪z, z⟫) • z, x⟫ = ℓ z / ⟪z, z⟫ * ⟪z, x⟫ := by simp [inner_smul_left]
_ = ℓ z * ⟪z, x⟫ / ⟪z, z⟫ := by rw [← div_mul_eq_mul_div]
_ = ℓ x * ⟪z, z⟫ / ⟪z, z⟫ := by rw [h₂]
_ = ℓ x := by field_simp [inner_self_ne_zero.2 z_ne_0]
exact h₄)
variable {𝕜} {E}
@[simp]
theorem toDual_apply {x y : E} : toDual 𝕜 E x y = ⟪x, y⟫ :=
rfl
@[simp]
theorem toDual_symm_apply {x : E} {y : StrongDual 𝕜 E} : ⟪(toDual 𝕜 E).symm y, x⟫ = y x := by
rw [← toDual_apply]
simp only [LinearIsometryEquiv.apply_symm_apply]
/-- Maps a bounded sesquilinear form to its continuous linear map,
given by interpreting the form as a map `B : E →L⋆[𝕜] NormedSpace.Dual 𝕜 E`
and dualizing the result using `toDual`.
-/
def continuousLinearMapOfBilin (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) : E →L[𝕜] E :=
(toDual 𝕜 E).symm.toContinuousLinearEquiv.toContinuousLinearMap.comp B
local postfix:1024 "♯" => continuousLinearMapOfBilin
variable (B : E →L⋆[𝕜] E →L[𝕜] 𝕜)
@[simp]
theorem continuousLinearMapOfBilin_apply (v w : E) : ⟪B♯ v, w⟫ = B v w := by
rw [continuousLinearMapOfBilin, coe_comp', ContinuousLinearEquiv.coe_coe,
LinearIsometryEquiv.coe_toContinuousLinearEquiv, Function.comp_apply, toDual_symm_apply]
theorem unique_continuousLinearMapOfBilin {v f : E} (is_lax_milgram : ∀ w, ⟪f, w⟫ = B v w) :
f = B♯ v := by
refine ext_inner_right 𝕜 ?_
intro w
rw [continuousLinearMapOfBilin_apply]
exact is_lax_milgram w
end Normed
instance [NormedAddCommGroup E] [CompleteSpace E] [InnerProductSpace ℝ E] :
(innerₗ E).IsContPerfPair where
continuous_uncurry := continuous_inner
bijective_left := (toDual ℝ E).bijective
bijective_right := by
convert (toDual ℝ E).bijective
ext y
simp
end InnerProductSpace
|
AkraBazzi.lean
|
/-
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.SumTransform
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
* `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.
-/
namespace AkraBazziRecurrence
variable {α : Type*} [Fintype α] {T : ℕ → ℝ} {g : ℝ → ℝ} {a b : α → ℝ} {r : α → ℕ → ℕ}
variable [Nonempty α] (R : AkraBazziRecurrence T g a b r)
local notation "ε" => smoothingFn
/-!
#### 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_fun_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_fun_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, 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, 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_fun_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
have h₂ : 0 ≤ ε (b i * n) - ε n := by
refine sub_nonneg_of_le <|
(strictAntiOn_smoothingFn.le_iff_ge ?n_gt_one ?bn_gt_one).mpr ?le
case n_gt_one =>
rwa [Set.mem_Ioi, Nat.one_lt_cast]
case bn_gt_one =>
calc 1 = b i * (b i)⁻¹ := by rw [mul_inv_cancel₀ (by positivity)]
_ ≤ b i * ⌈(b i)⁻¹⌉₊ := by gcongr; exact Nat.le_ceil _
_ < b i * n := by gcongr
case le => calc b i * n ≤ 1 * n := by have := R.b_lt_one i; gcongr
_ = n := by rw [one_mul]
positivity
filter_upwards [h_main] with n hn
have h₁ : q (b i * n) + (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)
= (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n) := by
have := R.b_pos i
simp only [q, mul_rpow (by positivity : (0 : ℝ) ≤ b i) (by positivity : (0 : ℝ) ≤ n)]
ring
change q (r i n) ≤ (b i) ^ (p a b) * n ^ (p a b) * (1 - ε n)
rw [← h₁, ← sub_le_iff_le_add']
exact hn
lemma rpow_p_mul_one_add_smoothingFn_ge :
∀ᶠ (n : ℕ) in atTop, ∀ i, (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n)
≤ (r i n) ^ (p a b) * (1 + ε (r i 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_add_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_fun_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 :=
IsBigO.mul (isBigO_refl _ _) isEquivalent_one_add_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_add_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_add_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 (b i * n) - q (r i n))
≤ᶠ[atTop] fun (n : ℕ) => (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n) := by
calc (fun (n : ℕ) => q (b i * n) - q (r i n))
≤ᶠ[atTop] fun (n : ℕ) => ‖q (r i n) - q (b i * n)‖ := by
filter_upwards with _; rw [norm_sub_rev]; 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
have h₂ : 0 ≤ ε (b i * n) - ε n := by
refine sub_nonneg_of_le <|
(strictAntiOn_smoothingFn.le_iff_ge ?n_gt_one ?bn_gt_one).mpr ?le
case n_gt_one =>
change 1 < (n : ℝ)
rw [Nat.one_lt_cast]
exact hn'
case bn_gt_one =>
calc 1 = b i * (b i)⁻¹ := by rw [mul_inv_cancel₀ (by positivity)]
_ ≤ b i * ⌈(b i)⁻¹⌉₊ := by gcongr; exact Nat.le_ceil _
_ < b i * n := by gcongr
case le => calc b i * n ≤ 1 * n := by have := R.b_lt_one i; gcongr
_ = n := by rw [one_mul]
positivity
filter_upwards [h_main] with n hn
have h₁ : q (b i * n) - (b i) ^ (p a b) * n ^ (p a b) * (ε (b i * n) - ε n)
= (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) := by
have := R.b_pos i
simp only [q, mul_rpow (by positivity : (0 : ℝ) ≤ b i) (by positivity : (0 : ℝ) ≤ n)]
ring
change (b i) ^ (p a b) * n ^ (p a b) * (1 + ε n) ≤ q (r i n)
rw [← h₁, sub_le_iff_le_add', ← sub_le_iff_le_add]
exact hn
/-!
#### Main proof
This final section proves the Akra-Bazzi theorem.
-/
lemma base_nonempty {n : ℕ} (hn : 0 < n) : (Finset.Ico (⌊b (min_bi b) / 2 * n⌋₊) n).Nonempty := by
let b' := b (min_bi b)
have hb_pos : 0 < b' := R.b_pos _
simp_rw [Finset.nonempty_Ico]
have := calc ⌊b' / 2 * n⌋₊ ≤ b' / 2 * n := by exact Nat.floor_le (by positivity)
_ < 1 / 2 * n := by gcongr; exact R.b_lt_one (min_bi b)
_ ≤ 1 * n := by gcongr; norm_num
_ = n := by simp
exact_mod_cast this
/-- The main proof of the upper bound part of the Akra-Bazzi theorem. The factor
`1 - ε n` does not change the asymptotic order, but is needed for the induction step to go
through. -/
lemma T_isBigO_smoothingFn_mul_asympBound :
T =O[atTop] (fun n => (1 - ε n) * asympBound g a b n) := by
let b' := b (min_bi b) / 2
have hb_pos : 0 < b' := R.bi_min_div_two_pos
rw [isBigO_atTop_iff_eventually_exists]
obtain ⟨c₁, hc₁, h_sumTransform_aux⟩ := R.eventually_atTop_sumTransform_ge
filter_upwards [
-- n₀_ge_Rn₀
eventually_ge_atTop R.n₀,
-- h_smoothing_pos
eventually_forall_ge_atTop.mpr eventually_one_sub_smoothingFn_pos,
-- h_smoothing_gt_half
eventually_forall_ge_atTop.mpr
<| eventually_one_sub_smoothingFn_gt_const (1 / 2) (by norm_num),
-- h_asympBound_pos
eventually_forall_ge_atTop.mpr R.eventually_asympBound_pos,
-- h_asympBound_r_pos
eventually_forall_ge_atTop.mpr R.eventually_asympBound_r_pos,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_asympBound_floor
R.eventually_asympBound_pos,
-- n₀_pos
eventually_gt_atTop 0,
-- h_smoothing_r_pos
eventually_forall_ge_atTop.mpr R.eventually_one_sub_smoothingFn_r_pos,
-- bound1
eventually_forall_ge_atTop.mpr R.rpow_p_mul_one_sub_smoothingFn_le,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_smoothingFn_floor
eventually_one_sub_smoothingFn_pos,
-- h_sumTransform
eventually_forall_ge_atTop.mpr h_sumTransform_aux,
-- h_bi_le_r
eventually_forall_ge_atTop.mpr R.eventually_bi_mul_le_r]
with n₀ n₀_ge_Rn₀ h_smoothing_pos h_smoothing_gt_half
h_asympBound_pos h_asympBound_r_pos h_asympBound_floor n₀_pos h_smoothing_r_pos
bound1 h_smoothingFn_floor h_sumTransform h_bi_le_r
-- Max of the ratio `T(n) / asympBound(n)` over the base case `n ∈ [b * n₀, n₀)`
have h_base_nonempty := R.base_nonempty n₀_pos
let base_max : ℝ :=
(Finset.Ico (⌊b' * n₀⌋₊) n₀).sup' h_base_nonempty
fun n => T n / ((1 - ε n) * asympBound g a b n)
-- The big-O constant we are aiming for: max of the base case ratio and what we need to
-- cancel out the `g(n)` term in the calculation below
set C := max (2 * c₁⁻¹) base_max with hC
refine ⟨C, fun n hn => ?_⟩
-- Base case: statement is true for `b' * n₀ ≤ n < n₀`
have h_base : ∀ n ∈ Finset.Ico (⌊b' * n₀⌋₊) n₀, T n ≤ C * ((1 - ε n) * asympBound g a b n) := by
intro n hn
rw [Finset.mem_Ico] at hn
have htmp1 : 0 < 1 - ε n := h_smoothingFn_floor n hn.1
have htmp2 : 0 < asympBound g a b n := h_asympBound_floor n hn.1
rw [← _root_.div_le_iff₀ (by positivity)]
rw [← Finset.mem_Ico] at hn
calc T n / ((1 - ε ↑n) * asympBound g a b n)
≤ (Finset.Ico (⌊b' * n₀⌋₊) n₀).sup' h_base_nonempty
(fun z => T z / ((1 - ε z) * asympBound g a b z)) :=
Finset.le_sup'_of_le _ (b := n) hn le_rfl
_ ≤ C := le_max_right _ _
have h_asympBound_pos' : 0 < asympBound g a b n := h_asympBound_pos n hn
have h_one_sub_smoothingFn_pos' : 0 < 1 - ε n := h_smoothing_pos n hn
rw [Real.norm_of_nonneg (R.T_nonneg n), Real.norm_of_nonneg (by positivity)]
-- We now prove all other cases by induction
induction n using Nat.strongRecOn with
| ind n h_ind =>
have b_mul_n₀_le_ri i : ⌊b' * ↑n₀⌋₊ ≤ r i n := by
exact_mod_cast calc ⌊b' * (n₀ : ℝ)⌋₊ ≤ b' * n₀ := Nat.floor_le <| by positivity
_ ≤ b' * n := by gcongr
_ ≤ r i n := h_bi_le_r n hn i
have g_pos : 0 ≤ g n := R.g_nonneg n (by positivity)
calc
T n = (∑ i, a i * T (r i n)) + g n := by exact R.h_rec n <| n₀_ge_Rn₀.trans hn
_ ≤ (∑ i, a i * (C * ((1 - ε (r i n)) * asympBound g a b (r i n)))) + g n := by
-- Apply the induction hypothesis, or use the base case depending on how large n is
gcongr (∑ i, a i * ?_) + g n with i _
· exact le_of_lt <| R.a_pos _
· if ri_lt_n₀ : r i n < n₀ then
exact h_base _ <| by
simp_all only [gt_iff_lt, Nat.ofNat_pos, div_pos_iff_of_pos_right,
eventually_atTop, sub_pos, one_div, mem_Ico, and_imp,
forall_true_left, mem_univ, and_self, b', C, base_max]
else
push_neg at ri_lt_n₀
exact h_ind (r i n) (R.r_lt_n _ _ (n₀_ge_Rn₀.trans hn)) ri_lt_n₀
(h_asympBound_r_pos _ hn _) (h_smoothing_r_pos n hn i)
_ = (∑ i, a i * (C * ((1 - ε (r i n)) * ((r i n) ^ (p a b)
* (1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1))))))) + g n := by
simp_rw [asympBound_def']
_ = (∑ i, C * a i * ((r i n) ^ (p a b) * (1 - ε (r i n))
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by
congr; ext; ring
_ ≤ (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 - ε n)
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by
gcongr (∑ i, C * a i * (?_
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n with i
· have := R.a_pos i
positivity
· refine add_nonneg zero_le_one <| Finset.sum_nonneg fun j _ => ?_
rw [div_nonneg_iff]
exact Or.inl ⟨R.g_nonneg j (by positivity), by positivity⟩
· exact bound1 n hn i
_ = (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 - ε n)
* ((1 + ((∑ u ∈ range n, g u / u ^ ((p a b) + 1))
- (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))) + g n := by
congr; ext i; congr
refine eq_sub_of_add_eq ?_
rw [add_comm]
exact add_eq_of_eq_sub <| Finset.sum_Ico_eq_sub _
<| le_of_lt <| R.r_lt_n i n <| n₀_ge_Rn₀.trans hn
_ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n) * ((n ^ (p a b)
* (1 + (∑ u ∈ range n, g u / u ^ ((p a b) + 1)))
- n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))
+ g n := by
congr; ext; ring
_ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n)
* ((asympBound g a b n - sumTransform (p a b) g (r i n) n)))) + g n := by
simp_rw [asympBound_def', sumTransform_def]
_ ≤ (∑ i, C * a i * ((b i) ^ (p a b) * (1 - ε n)
* ((asympBound g a b n - c₁ * g n)))) + g n := by
gcongr with i
· have := R.a_pos i
positivity
· have := R.b_pos i
positivity
· exact h_sumTransform n hn i
_ = (∑ i, C * (1 - ε n) * ((asympBound g a b n - c₁ * g n))
* (a i * (b i) ^ (p a b))) + g n := by
congr; ext; ring
_ = C * (1 - ε n) * (asympBound g a b n - c₁ * g n) + g n := by
rw [← Finset.mul_sum, R.sumCoeffsExp_p_eq_one, mul_one]
_ = C * (1 - ε n) * asympBound g a b n + (1 - C * c₁ * (1 - ε n)) * g n := by ring
_ ≤ C * (1 - ε n) * asympBound g a b n + 0 := by
gcongr
refine mul_nonpos_of_nonpos_of_nonneg ?_ g_pos
rw [sub_nonpos]
calc 1 ≤ 2 * (c₁⁻¹ * c₁) * (1/2) := by
rw [inv_mul_cancel₀ (by positivity : c₁ ≠ 0)]; norm_num
_ = (2 * c₁⁻¹) * c₁ * (1/2) := by ring
_ ≤ C * c₁ * (1 - ε n) := by gcongr
· rw [hC]; exact le_max_left _ _
· exact le_of_lt <| h_smoothing_gt_half n hn
_ = C * ((1 - ε n) * asympBound g a b n) := by ring
/-- The main proof of the lower bound part of the Akra-Bazzi theorem. The factor
`1 + ε n` does not change the asymptotic order, but is needed for the induction step to go
through. -/
lemma smoothingFn_mul_asympBound_isBigO_T :
(fun (n : ℕ) => (1 + ε n) * asympBound g a b n) =O[atTop] T := by
let b' := b (min_bi b) / 2
have hb_pos : 0 < b' := R.bi_min_div_two_pos
rw [isBigO_atTop_iff_eventually_exists_pos]
obtain ⟨c₁, hc₁, h_sumTransform_aux⟩ := R.eventually_atTop_sumTransform_le
filter_upwards [
-- n₀_ge_Rn₀
eventually_ge_atTop R.n₀,
-- h_b_floor
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_gt_atTop 0,
-- h_smoothing_pos
eventually_forall_ge_atTop.mpr eventually_one_add_smoothingFn_pos,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_smoothing_pos'
eventually_one_add_smoothingFn_pos,
-- h_asympBound_pos
eventually_forall_ge_atTop.mpr R.eventually_asympBound_pos,
-- h_asympBound_r_pos
eventually_forall_ge_atTop.mpr R.eventually_asympBound_r_pos,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_asympBound_floor
R.eventually_asympBound_pos,
-- n₀_pos
eventually_gt_atTop 0,
-- h_smoothing_r_pos
eventually_forall_ge_atTop.mpr R.eventually_one_add_smoothingFn_r_pos,
-- bound2
eventually_forall_ge_atTop.mpr R.rpow_p_mul_one_add_smoothingFn_ge,
(tendsto_nat_floor_mul_atTop b' hb_pos).eventually_forall_ge_atTop
-- h_smoothingFn_floor
eventually_one_add_smoothingFn_pos,
-- h_sumTransform
eventually_forall_ge_atTop.mpr h_sumTransform_aux,
-- h_bi_le_r
eventually_forall_ge_atTop.mpr R.eventually_bi_mul_le_r,
-- h_exp
eventually_forall_ge_atTop.mpr (eventually_ge_atTop ⌈exp 1⌉₊)]
with n₀ n₀_ge_Rn₀ h_b_floor h_smoothing_pos h_smoothing_pos' h_asympBound_pos h_asympBound_r_pos
h_asympBound_floor n₀_pos h_smoothing_r_pos bound2 h_smoothingFn_floor h_sumTransform
h_bi_le_r h_exp
have h_base_nonempty := R.base_nonempty n₀_pos
-- Min of the ratio T(n) / asympBound(n) over the base case n ∈ [b * n₀, n₀)
set base_min : ℝ :=
(Finset.Ico (⌊b' * n₀⌋₊) n₀).inf' h_base_nonempty
(fun n => T n / ((1 + ε n) * asympBound g a b n)) with base_min_def
-- The big-O constant we are aiming for: min of the base case ratio and what we need to cancel
-- out the g(n) term in the calculation below
let C := min (2 * c₁)⁻¹ base_min
have hC_pos : 0 < C := by
refine lt_min (by positivity) ?_
obtain ⟨m, hm_mem, hm⟩ :=
Finset.exists_mem_eq_inf' h_base_nonempty (fun n => T n / ((1 + ε n) * asympBound g a b n))
calc 0 < T m / ((1 + ε m) * asympBound g a b m) := by
have H₁ : 0 < T m := by exact R.T_pos _
have H₂ : 0 < 1 + ε m := by rw [Finset.mem_Ico] at hm_mem
exact h_smoothing_pos' m hm_mem.1
have H₃ : 0 < asympBound g a b m := by
refine R.asympBound_pos m ?_
calc 0 < ⌊b' * n₀⌋₊ := by exact h_b_floor
_ ≤ m := by rw [Finset.mem_Ico] at hm_mem; exact hm_mem.1
positivity
_ = base_min := by rw [base_min_def, hm]
refine ⟨C, hC_pos, fun n hn => ?_⟩
-- Base case: statement is true for `b' * n₀ ≤ n < n₀`
have h_base : ∀ n ∈ Finset.Ico (⌊b' * n₀⌋₊) n₀, C * ((1 + ε n) * asympBound g a b n) ≤ T n := by
intro n hn
rw [Finset.mem_Ico] at hn
have htmp1 : 0 < 1 + ε n := h_smoothingFn_floor n hn.1
have htmp2 : 0 < asympBound g a b n := h_asympBound_floor n hn.1
rw [← _root_.le_div_iff₀ (by positivity)]
rw [← Finset.mem_Ico] at hn
calc T n / ((1 + ε ↑n) * asympBound g a b n)
≥ (Finset.Ico (⌊b' * n₀⌋₊) n₀).inf' h_base_nonempty
fun z => T z / ((1 + ε z) * asympBound g a b z) :=
Finset.inf'_le_of_le _ (b := n) hn <| le_refl _
_ ≥ C := min_le_right _ _
have h_asympBound_pos' : 0 < asympBound g a b n := h_asympBound_pos n hn
have h_one_sub_smoothingFn_pos' : 0 < 1 + ε n := h_smoothing_pos n hn
rw [Real.norm_of_nonneg (R.T_nonneg n), Real.norm_of_nonneg (by positivity)]
-- We now prove all other cases by induction
induction n using Nat.strongRecOn with
| ind n h_ind =>
have b_mul_n₀_le_ri i : ⌊b' * ↑n₀⌋₊ ≤ r i n := by
exact_mod_cast calc ⌊b' * ↑n₀⌋₊ ≤ b' * n₀ := Nat.floor_le <| by positivity
_ ≤ b' * n := by gcongr
_ ≤ r i n := h_bi_le_r n hn i
have g_pos : 0 ≤ g n := R.g_nonneg n (by positivity)
calc
T n = (∑ i, a i * T (r i n)) + g n := by exact R.h_rec n <| n₀_ge_Rn₀.trans hn
_ ≥ (∑ i, a i * (C * ((1 + ε (r i n)) * asympBound g a b (r i n)))) + g n := by
-- Apply the induction hypothesis, or use the base case depending on how large `n` is
gcongr (∑ i, a i * ?_) + g n with i _
· exact le_of_lt <| R.a_pos _
· cases lt_or_ge (r i n) n₀ with
| inl ri_lt_n₀ => exact h_base _ <| Finset.mem_Ico.mpr ⟨b_mul_n₀_le_ri i, ri_lt_n₀⟩
| inr n₀_le_ri =>
exact h_ind (r i n) (R.r_lt_n _ _ (n₀_ge_Rn₀.trans hn)) n₀_le_ri
(h_asympBound_r_pos _ hn _) (h_smoothing_r_pos n hn i)
_ = (∑ i, a i * (C * ((1 + ε (r i n)) * ((r i n) ^ (p a b)
* (1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1))))))) + g n := by
simp_rw [asympBound_def']
_ = (∑ i, C * a i * ((r i n)^(p a b) * (1 + ε (r i n))
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by
congr; ext; ring
_ ≥ (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 + ε n)
* ((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n := by
gcongr (∑ i, C * a i * (?_ *
((1 + (∑ u ∈ range (r i n), g u / u ^ ((p a b) + 1)))))) + g n with i
· have := R.a_pos i
positivity
· refine add_nonneg zero_le_one <| Finset.sum_nonneg fun j _ => ?_
rw [div_nonneg_iff]
exact Or.inl ⟨R.g_nonneg j (by positivity), by positivity⟩
· exact bound2 n hn i
_ = (∑ i, C * a i * ((b i) ^ (p a b) * n ^ (p a b) * (1 + ε n)
* ((1 + ((∑ u ∈ range n, g u / u ^ ((p a b) + 1))
- (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))) + g n := by
congr; ext i; congr
refine eq_sub_of_add_eq ?_
rw [add_comm]
exact add_eq_of_eq_sub <| Finset.sum_Ico_eq_sub _
<| le_of_lt <| R.r_lt_n i n <| n₀_ge_Rn₀.trans hn
_ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n)
* ((n ^ (p a b) * (1 + (∑ u ∈ range n, g u / u ^ ((p a b) + 1)))
- n ^ (p a b) * (∑ u ∈ Finset.Ico (r i n) n, g u / u ^ ((p a b) + 1))))))
+ g n := by
congr; ext; ring
_ = (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n)
* ((asympBound g a b n - sumTransform (p a b) g (r i n) n)))) + g n := by
simp_rw [asympBound_def', sumTransform_def]
_ ≥ (∑ i, C * a i * ((b i) ^ (p a b) * (1 + ε n)
* ((asympBound g a b n - c₁ * g n)))) + g n := by
gcongr with i
· have := R.a_pos i
positivity
· have := R.b_pos i
positivity
· exact h_sumTransform n hn i
_ = (∑ i, C * (1 + ε n) * ((asympBound g a b n - c₁ * g n))
* (a i * (b i) ^ (p a b))) + g n := by congr; ext; ring
_ = C * (1 + ε n) * (asympBound g a b n - c₁ * g n) + g n := by
rw [← Finset.mul_sum, R.sumCoeffsExp_p_eq_one, mul_one]
_ = C * (1 + ε n) * asympBound g a b n + (1 - C * c₁ * (1 + ε n)) * g n := by ring
_ ≥ C * (1 + ε n) * asympBound g a b n + 0 := by
gcongr
refine mul_nonneg ?_ g_pos
rw [sub_nonneg]
calc C * c₁ * (1 + ε n) ≤ C * c₁ * 2 := by
gcongr
refine one_add_smoothingFn_le_two ?_
calc exp 1 ≤ ⌈exp 1⌉₊ := by exact Nat.le_ceil _
_ ≤ n := by exact_mod_cast h_exp n hn
_ = C * (2 * c₁) := by ring
_ ≤ (2 * c₁)⁻¹ * (2 * c₁) := by gcongr; exact min_le_left _ _
_ = c₁⁻¹ * c₁ := by ring
_ = 1 := inv_mul_cancel₀ (by positivity)
_ = C * ((1 + ε n) * asympBound g a b n) := by ring
/-- The **Akra-Bazzi theorem**: `T ∈ O(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/
theorem isBigO_asympBound : T =O[atTop] asympBound g a b := by
calc T =O[atTop] (fun n => (1 - ε n) * asympBound g a b n) := by
exact R.T_isBigO_smoothingFn_mul_asympBound
_ =O[atTop] (fun n => 1 * asympBound g a b n) := by
refine IsBigO.mul (isBigO_const_of_tendsto (y := 1) ?_ one_ne_zero)
(isBigO_refl _ _)
rw [← Function.comp_def (fun n => 1 - ε n) Nat.cast]
exact Tendsto.comp isEquivalent_one_sub_smoothingFn_one.tendsto_const
tendsto_natCast_atTop_atTop
_ = asympBound g a b := by simp
/-- The **Akra-Bazzi theorem**: `T ∈ Ω(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/
theorem isBigO_symm_asympBound : asympBound g a b =O[atTop] T := by
calc asympBound g a b = (fun n => 1 * asympBound g a b n) := by simp
_ ~[atTop] (fun n => (1 + ε n) * asympBound g a b n) := by
refine IsEquivalent.mul (IsEquivalent.symm ?_) IsEquivalent.refl
rw [Function.const_def, isEquivalent_const_iff_tendsto one_ne_zero,
← Function.comp_def (fun n => 1 + ε n) Nat.cast]
exact Tendsto.comp isEquivalent_one_add_smoothingFn_one.tendsto_const
tendsto_natCast_atTop_atTop
_ =O[atTop] T := R.smoothingFn_mul_asympBound_isBigO_T
/-- The **Akra-Bazzi theorem**: `T ∈ Θ(n^p (1 + ∑_u^n g(u) / u^{p+1}))` -/
theorem isTheta_asympBound : T =Θ[atTop] asympBound g a b :=
⟨R.isBigO_asympBound, R.isBigO_symm_asympBound⟩
end AkraBazziRecurrence
|
AlgebraicClosure.lean
|
/-
Copyright (c) 2024 Junyan Xu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Junyan Xu
-/
import Mathlib.FieldTheory.AlgebraicClosure
import Mathlib.RingTheory.Algebraic.Integral
import Mathlib.RingTheory.AlgebraicIndependent.Transcendental
/-!
# Algebraic independence persists to the algebraic closure
## Main results
* `AlgebraicIndependent.extendScalars`: if A/S/R is a tower of algebras with S/R algebraic,
then a family of elements in A that are algebraically independent over R remains algebraically
independent over S, provided that S has no zero divisors.
* `AlgebraicIndependent.algebraicClosure`: an algebraically independent family remains
algebraically independent over the algebraic closure.
-/
open Function Algebra
section
variable {ι R S A : Type*} {x : ι → A} (S)
variable [CommRing R] [CommRing S] [CommRing A]
variable [Algebra R S] [Algebra R A] [Algebra S A] [IsScalarTower R S A]
variable [NoZeroDivisors S] (hx : AlgebraicIndependent R x)
include hx
namespace AlgebraicIndependent
theorem extendScalars [alg : Algebra.IsAlgebraic R S] : AlgebraicIndependent S x := by
refine algebraicIndependent_of_finite_type'
(Algebra.IsAlgebraic.injective_tower_top S hx.algebraMap_injective) fun t fin ind i hi ↦ ?_
let Rt := adjoin R (x '' t)
let St := adjoin S (x '' t)
let _ : Algebra Rt St :=
(Rt.inclusion (T := St.restrictScalars R) <| adjoin_le <| by exact subset_adjoin).toAlgebra
have : IsScalarTower Rt St A := .of_algebraMap_eq fun ⟨y, _⟩ ↦ show y = y from rfl
have : NoZeroDivisors St := (Set.image_eq_range _ _ ▸ ind.aevalEquiv)
|>.symm.injective.noZeroDivisors _ (map_zero _) (map_mul _)
have : NoZeroDivisors Rt := (Subalgebra.inclusion_injective _).noZeroDivisors
(algebraMap Rt St) (map_zero _) (map_mul _)
have : Algebra.IsAlgebraic Rt St := ⟨fun ⟨y, hy⟩ ↦ by
rw [← isAlgebraic_algHom_iff (IsScalarTower.toAlgHom Rt St A) Subtype.val_injective]
change IsAlgebraic Rt y
have := Algebra.IsAlgebraic.nontrivial R S
have := hx.algebraMap_injective.nontrivial
exact adjoin_induction (fun _ h ↦ isAlgebraic_algebraMap (⟨_, subset_adjoin h⟩ : Rt))
(fun z ↦ ((alg.1 z).algHom (IsScalarTower.toAlgHom R S A)).extendScalars fun _ _ eq ↦ by
exact hx.algebraMap_injective congr($eq.1)) (fun _ _ _ _ ↦ .add) (fun _ _ _ _ ↦ .mul) hy⟩
change Transcendental St (x i)
exact (hx.transcendental_adjoin hi).extendScalars _
theorem extendScalars_of_isIntegral [Algebra.IsIntegral R S] : AlgebraicIndependent S x := by
nontriviality S
have := Module.nontrivial R S
exact hx.extendScalars S
@[deprecated (since := "2025-02-08")] alias extendScalars_of_isSimpleRing := extendScalars
@[deprecated (since := "2025-02-08")] protected alias subalgebra := extendScalars
@[deprecated (since := "2025-02-08")] alias subalgebra_of_isIntegral := extendScalars_of_isIntegral
theorem subalgebraAlgebraicClosure [IsDomain R] [NoZeroDivisors A] :
AlgebraicIndependent (Subalgebra.algebraicClosure R A) x :=
hx.extendScalars _
protected theorem integralClosure [NoZeroDivisors A] :
AlgebraicIndependent (integralClosure R A) x :=
hx.extendScalars_of_isIntegral _
omit hx in
protected theorem algebraicClosure {F E : Type*} [Field F] [Field E] [Algebra F E] {x : ι → E}
(hx : AlgebraicIndependent F x) : AlgebraicIndependent (algebraicClosure F E) x :=
hx.extendScalars _
end AlgebraicIndependent
namespace Algebra
variable (R) [FaithfulSMul R S]
omit hx
protected theorem IsIntegral.algebraicIndependent_iff [Algebra.IsIntegral R S] :
AlgebraicIndependent R x ↔ AlgebraicIndependent S x :=
⟨(·.extendScalars_of_isIntegral _),
(·.restrictScalars (FaithfulSMul.algebraMap_injective R S))⟩
protected theorem IsIntegral.isTranscendenceBasis_iff [Algebra.IsIntegral R S] :
IsTranscendenceBasis R x ↔ IsTranscendenceBasis S x := by
simp_rw [IsTranscendenceBasis, IsIntegral.algebraicIndependent_iff R S]
protected theorem IsAlgebraic.algebraicIndependent_iff [Algebra.IsAlgebraic R S] :
AlgebraicIndependent R x ↔ AlgebraicIndependent S x :=
⟨(·.extendScalars _), (·.restrictScalars (FaithfulSMul.algebraMap_injective R S))⟩
protected theorem IsAlgebraic.isTranscendenceBasis_iff [Algebra.IsAlgebraic R S] :
IsTranscendenceBasis R x ↔ IsTranscendenceBasis S x := by
simp_rw [IsTranscendenceBasis, IsAlgebraic.algebraicIndependent_iff R S]
end Algebra
end
namespace IntermediateField
variable {ι F E R S : Type*} {s : Set E}
variable [Field F] [Field E] [Algebra F E]
variable [CommRing R] [Algebra R F] [Algebra R E] [IsScalarTower R F E]
open scoped algebraAdjoinAdjoin
section Ring
variable [Ring S] [Algebra E S]
theorem isAlgebraic_adjoin_iff {x : S} :
IsAlgebraic (adjoin F s) x ↔ IsAlgebraic (Algebra.adjoin F s) x :=
(IsAlgebraic.isAlgebraic_iff ..).symm
theorem isAlgebraic_adjoin_iff_top :
Algebra.IsAlgebraic (adjoin F s) S ↔ Algebra.IsAlgebraic (Algebra.adjoin F s) S :=
(IsAlgebraic.isAlgebraic_iff_top ..).symm
theorem isAlgebraic_adjoin_iff_bot :
Algebra.IsAlgebraic R (adjoin F s) ↔ Algebra.IsAlgebraic R (Algebra.adjoin F s) :=
IsAlgebraic.isAlgebraic_iff_bot ..
theorem transcendental_adjoin_iff {x : S} :
Transcendental (adjoin F s) x ↔ Transcendental (Algebra.adjoin F s) x :=
(IsAlgebraic.transcendental_iff ..).symm
end Ring
variable [CommRing S] [Algebra E S]
theorem algebraicIndependent_adjoin_iff {x : ι → S} :
AlgebraicIndependent (adjoin F s) x ↔ AlgebraicIndependent (Algebra.adjoin F s) x :=
(Algebra.IsAlgebraic.algebraicIndependent_iff ..).symm
theorem isTranscendenceBasis_adjoin_iff {x : ι → S} :
IsTranscendenceBasis (adjoin F s) x ↔ IsTranscendenceBasis (Algebra.adjoin F s) x :=
(Algebra.IsAlgebraic.isTranscendenceBasis_iff ..).symm
end IntermediateField
|
Centralizer.lean
|
/-
Copyright (c) 2021 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import Mathlib.GroupTheory.Subsemigroup.Centralizer
import Mathlib.GroupTheory.Submonoid.Center
/-!
# Centralizers of magmas and monoids
## Main definitions
* `Submonoid.centralizer`: the centralizer of a subset of a monoid
* `AddSubmonoid.centralizer`: the centralizer of a subset of an additive monoid
We provide `Subgroup.centralizer`, `AddSubgroup.centralizer` in other files.
-/
-- Guard against import creep
assert_not_exists Finset
variable {M : Type*} {S T : Set M}
namespace Submonoid
section
variable [Monoid M] (S)
/-- The centralizer of a subset of a monoid `M`. -/
@[to_additive /-- The centralizer of a subset of an additive monoid. -/]
def centralizer : Submonoid M where
carrier := S.centralizer
one_mem' := S.one_mem_centralizer
mul_mem' := Set.mul_mem_centralizer
@[to_additive (attr := simp, norm_cast)]
theorem coe_centralizer : ↑(centralizer S) = S.centralizer :=
rfl
@[to_additive AddSubmonoid.centralizer_toAddSubsemigroup]
theorem centralizer_toSubsemigroup : (centralizer S).toSubsemigroup = Subsemigroup.centralizer S :=
rfl
variable {S}
@[to_additive]
theorem mem_centralizer_iff {z : M} : z ∈ centralizer S ↔ ∀ g ∈ S, g * z = z * g :=
Iff.rfl
@[to_additive]
theorem center_le_centralizer (s) : center M ≤ centralizer s :=
s.center_subset_centralizer
@[to_additive]
instance decidableMemCentralizer (a) [Decidable <| ∀ b ∈ S, b * a = a * b] :
Decidable (a ∈ centralizer S) :=
decidable_of_iff' _ mem_centralizer_iff
@[to_additive]
theorem centralizer_le (h : S ⊆ T) : centralizer T ≤ centralizer S :=
Set.centralizer_subset h
@[to_additive (attr := simp)]
theorem centralizer_eq_top_iff_subset {s : Set M} : centralizer s = ⊤ ↔ s ⊆ center M :=
SetLike.ext'_iff.trans Set.centralizer_eq_top_iff_subset
variable (M)
@[to_additive (attr := simp)]
theorem centralizer_univ : centralizer Set.univ = center M :=
SetLike.ext' (Set.centralizer_univ M)
@[to_additive]
lemma le_centralizer_centralizer {s : Submonoid M} : s ≤ centralizer (centralizer (s : Set M)) :=
Set.subset_centralizer_centralizer
@[to_additive (attr := simp)]
lemma centralizer_centralizer_centralizer {s : Set M} :
centralizer s.centralizer.centralizer = centralizer s := by
apply SetLike.coe_injective
simp only [coe_centralizer, Set.centralizer_centralizer_centralizer]
variable {M} in
@[to_additive]
lemma closure_le_centralizer_centralizer (s : Set M) :
closure s ≤ centralizer (centralizer s) :=
closure_le.mpr Set.subset_centralizer_centralizer
/-- If all the elements of a set `s` commute, then `closure s` is a commutative monoid. -/
@[to_additive
/-- If all the elements of a set `s` commute, then `closure s` forms an additive
commutative monoid. -/]
abbrev closureCommMonoidOfComm {s : Set M} (hcomm : ∀ a ∈ s, ∀ b ∈ s, a * b = b * a) :
CommMonoid (closure s) :=
{ (closure s).toMonoid with
mul_comm := fun ⟨_, h₁⟩ ⟨_, h₂⟩ ↦
have := closure_le_centralizer_centralizer s
Subtype.ext <| Set.centralizer_centralizer_comm_of_comm hcomm _ (this h₁) _ (this h₂) }
end
end Submonoid
|
FintypeCat.lean
|
/-
Copyright (c) 2020 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Adam Topaz
-/
import Mathlib.CategoryTheory.ConcreteCategory.Basic
import Mathlib.CategoryTheory.Endomorphism
import Mathlib.CategoryTheory.Skeletal
import Mathlib.Data.Finite.Prod
/-!
# The category of finite types.
We define the category of finite types, denoted `FintypeCat` as
(bundled) types with a `Fintype` instance.
We also define `FintypeCat.Skeleton`, the standard skeleton of `FintypeCat` whose objects
are `Fin n` for `n : ℕ`. We prove that the obvious inclusion functor
`FintypeCat.Skeleton ⥤ FintypeCat` is an equivalence of categories in
`FintypeCat.Skeleton.equivalence`.
We prove that `FintypeCat.Skeleton` is a skeleton of `FintypeCat` in `FintypeCat.isSkeleton`.
-/
open CategoryTheory
/-- The category of finite types. -/
structure FintypeCat where
/-- The underlying type. -/
carrier : Type*
[str : Fintype carrier]
attribute [instance] FintypeCat.str
namespace FintypeCat
instance instCoeSort : CoeSort FintypeCat Type* :=
⟨carrier⟩
/-- Construct a bundled `FintypeCat` from the underlying type and typeclass. -/
abbrev of (X : Type*) [Fintype X] : FintypeCat where
carrier := X
instance : Inhabited FintypeCat :=
⟨of PEmpty⟩
instance {X : FintypeCat} : Fintype X :=
X.2
instance : Category FintypeCat :=
InducedCategory.category carrier
/-- The fully faithful embedding of `FintypeCat` into the category of types. -/
@[simps!]
def incl : FintypeCat ⥤ Type* :=
inducedFunctor _
instance : incl.Full := InducedCategory.full _
instance : incl.Faithful := InducedCategory.faithful _
instance (X Y : FintypeCat) : FunLike (X ⟶ Y) X Y where
coe f := f
coe_injective' _ _ h := h
instance concreteCategoryFintype : ConcreteCategory FintypeCat (· ⟶ ·) where
hom f := f
ofHom f := f
/- Help typeclass inference infer fullness of forgetful functor. -/
instance : (forget FintypeCat).Full := inferInstanceAs <| FintypeCat.incl.Full
@[simp]
theorem id_apply (X : FintypeCat) (x : X) : (𝟙 X : X → X) x = x :=
rfl
@[simp]
theorem comp_apply {X Y Z : FintypeCat} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) :=
rfl
-- Isn't `@[simp]` because `simp` can prove it after importing `Mathlib.CategoryTheory.Elementwise`.
lemma hom_inv_id_apply {X Y : FintypeCat} (f : X ≅ Y) (x : X) : f.inv (f.hom x) = x :=
congr_fun f.hom_inv_id x
-- Isn't `@[simp]` because `simp` can prove it after importing `Mathlib.CategoryTheory.Elementwise`.
lemma inv_hom_id_apply {X Y : FintypeCat} (f : X ≅ Y) (y : Y) : f.hom (f.inv y) = y :=
congr_fun f.inv_hom_id y
@[ext]
lemma hom_ext {X Y : FintypeCat} (f g : X ⟶ Y) (h : ∀ x, f x = g x) : f = g := by
funext
apply h
-- See `equivEquivIso` in the root namespace for the analogue in `Type`.
/-- Equivalences between finite types are the same as isomorphisms in `FintypeCat`. -/
@[simps]
def equivEquivIso {A B : FintypeCat} : A ≃ B ≃ (A ≅ B) where
toFun e :=
{ hom := e
inv := e.symm }
invFun i :=
{ toFun := i.hom
invFun := i.inv
left_inv := congr_fun i.hom_inv_id
right_inv := congr_fun i.inv_hom_id }
left_inv := by cat_disch
right_inv := by cat_disch
instance (X Y : FintypeCat) : Finite (X ⟶ Y) :=
inferInstanceAs <| Finite (X → Y)
instance (X Y : FintypeCat) : Finite (X ≅ Y) :=
Finite.of_injective _ (fun _ _ h ↦ Iso.ext h)
instance (X : FintypeCat) : Finite (Aut X) :=
inferInstanceAs <| Finite (X ≅ X)
universe u
/--
The "standard" skeleton for `FintypeCat`. This is the full subcategory of `FintypeCat`
spanned by objects of the form `ULift (Fin n)` for `n : ℕ`. We parameterize the objects
of `Fintype.Skeleton` directly as `ULift ℕ`, as the type `ULift (Fin m) ≃ ULift (Fin n)`
is nonempty if and only if `n = m`. Specifying universes, `Skeleton : Type u` is a small
skeletal category equivalent to `Fintype.{u}`.
-/
def Skeleton : Type u :=
ULift ℕ
namespace Skeleton
/-- Given any natural number `n`, this creates the associated object of `Fintype.Skeleton`. -/
def mk : ℕ → Skeleton :=
ULift.up
instance : Inhabited Skeleton :=
⟨mk 0⟩
/-- Given any object of `Fintype.Skeleton`, this returns the associated natural number. -/
def len : Skeleton → ℕ :=
ULift.down
@[ext]
theorem ext (X Y : Skeleton) : X.len = Y.len → X = Y :=
ULift.ext _ _
instance : SmallCategory Skeleton.{u} where
Hom X Y := ULift.{u} (Fin X.len) → ULift.{u} (Fin Y.len)
id _ := id
comp f g := g ∘ f
theorem is_skeletal : Skeletal Skeleton.{u} := fun X Y ⟨h⟩ =>
ext _ _ <|
Fin.equiv_iff_eq.mp <|
Nonempty.intro <|
{ toFun := fun x => (h.hom ⟨x⟩).down
invFun := fun x => (h.inv ⟨x⟩).down
left_inv := by
intro a
change ULift.down _ = _
rw [ULift.up_down]
change ((h.hom ≫ h.inv) _).down = _
simp
rfl
right_inv := by
intro a
change ULift.down _ = _
rw [ULift.up_down]
change ((h.inv ≫ h.hom) _).down = _
simp
rfl }
/-- The canonical fully faithful embedding of `Fintype.Skeleton` into `FintypeCat`. -/
def incl : Skeleton.{u} ⥤ FintypeCat.{u} where
obj X := FintypeCat.of (ULift (Fin X.len))
map f := f
instance : incl.Full where map_surjective f := ⟨f, rfl⟩
instance : incl.Faithful where
instance : incl.EssSurj :=
Functor.EssSurj.mk fun X =>
let F := Fintype.equivFin X
⟨mk (Fintype.card X),
Nonempty.intro
{ hom := F.symm ∘ ULift.down
inv := ULift.up ∘ F }⟩
noncomputable instance : incl.IsEquivalence where
/-- The equivalence between `Fintype.Skeleton` and `Fintype`. -/
noncomputable def equivalence : Skeleton ≌ FintypeCat :=
incl.asEquivalence
@[simp]
theorem incl_mk_nat_card (n : ℕ) : Fintype.card (incl.obj (mk n)) = n := by
convert Finset.card_fin n
apply Fintype.ofEquiv_card
end Skeleton
/-- `Fintype.Skeleton` is a skeleton of `Fintype`. -/
lemma isSkeleton : IsSkeletonOf FintypeCat Skeleton Skeleton.incl where
skel := Skeleton.is_skeletal
eqv := by infer_instance
section Universes
universe v
/-- If `u` and `v` are two arbitrary universes, we may construct a functor
`uSwitch.{u, v} : FintypeCat.{u} ⥤ FintypeCat.{v}` by sending
`X : FintypeCat.{u}` to `ULift.{v} (Fin (Fintype.card X))`. -/
noncomputable def uSwitch : FintypeCat.{u} ⥤ FintypeCat.{v} where
obj X := FintypeCat.of <| ULift.{v} (Fin (Fintype.card X))
map {X Y} f x := ULift.up <| (Fintype.equivFin Y) (f ((Fintype.equivFin X).symm x.down))
map_comp {X Y Z} f g := by funext; simp
/-- Switching the universe of an object `X : FintypeCat.{u}` does not change `X` up to equivalence
of types. This is natural in the sense that it commutes with `uSwitch.map f` for
any `f : X ⟶ Y` in `FintypeCat.{u}`. -/
noncomputable def uSwitchEquiv (X : FintypeCat.{u}) :
uSwitch.{u, v}.obj X ≃ X :=
Equiv.ulift.trans (Fintype.equivFin X).symm
lemma uSwitchEquiv_naturality {X Y : FintypeCat.{u}} (f : X ⟶ Y)
(x : uSwitch.{u, v}.obj X) :
f (X.uSwitchEquiv x) = Y.uSwitchEquiv (uSwitch.map f x) := by
simp only [uSwitch, uSwitchEquiv, Equiv.trans_apply, Equiv.ulift_apply, Equiv.symm_apply_apply]
lemma uSwitchEquiv_symm_naturality {X Y : FintypeCat.{u}} (f : X ⟶ Y) (x : X) :
uSwitch.map f (X.uSwitchEquiv.symm x) = Y.uSwitchEquiv.symm (f x) := by
rw [← Equiv.apply_eq_iff_eq_symm_apply, ← uSwitchEquiv_naturality f,
Equiv.apply_symm_apply]
lemma uSwitch_map_uSwitch_map {X Y : FintypeCat.{u}} (f : X ⟶ Y) :
uSwitch.map (uSwitch.map f) =
(equivEquivIso ((uSwitch.obj X).uSwitchEquiv.trans X.uSwitchEquiv)).hom ≫
f ≫ (equivEquivIso ((uSwitch.obj Y).uSwitchEquiv.trans
Y.uSwitchEquiv)).inv := by
ext x
simp only [comp_apply, equivEquivIso_apply_hom, Equiv.trans_apply]
rw [uSwitchEquiv_naturality f, ← uSwitchEquiv_naturality]
rfl
/-- `uSwitch.{u, v}` is an equivalence of categories with quasi-inverse `uSwitch.{v, u}`. -/
noncomputable def uSwitchEquivalence : FintypeCat.{u} ≌ FintypeCat.{v} where
functor := uSwitch
inverse := uSwitch
unitIso := NatIso.ofComponents (fun X ↦ (equivEquivIso <|
(uSwitch.obj X).uSwitchEquiv.trans X.uSwitchEquiv).symm) <| by
simp [uSwitch_map_uSwitch_map]
counitIso := NatIso.ofComponents (fun X ↦ equivEquivIso <|
(uSwitch.obj X).uSwitchEquiv.trans X.uSwitchEquiv) <| by
simp [uSwitch_map_uSwitch_map]
functor_unitIso_comp X := by
ext x
simp [← uSwitchEquiv_naturality]
instance : uSwitch.IsEquivalence :=
uSwitchEquivalence.isEquivalence_functor
end Universes
end FintypeCat
namespace FunctorToFintypeCat
universe u v w
variable {C : Type u} [Category.{v} C] (F G : C ⥤ FintypeCat.{w}) {X Y : C}
lemma naturality (σ : F ⟶ G) (f : X ⟶ Y) (x : F.obj X) :
σ.app Y (F.map f x) = G.map f (σ.app X x) :=
congr_fun (σ.naturality f) x
end FunctorToFintypeCat
|
AddSub.lean
|
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.Count
import Mathlib.Data.List.Count
/-!
# Sum and difference of multisets
This file defines the following operations on multisets:
* `Add (Multiset α)` instance: `s + t` adds the multiplicities of the elements of `s` and `t`
* `Sub (Multiset α)` instance: `s - t` subtracts the multiplicities of the elements of `s` and `t`
* `Multiset.erase`: `s.erase x` reduces the multiplicity of `x` in `s` by one.
## Notation (defined later)
* `s + t`: The multiset for which the number of occurrences of each `a` is the sum of the
occurrences of `a` in `s` and `t`.
* `s - t`: The multiset for which the number of occurrences of each `a` is the difference of the
occurrences of `a` in `s` and `t`.
-/
-- No algebra should be required
assert_not_exists Monoid
universe v
open List Subtype Nat Function
variable {α : Type*} {β : Type v} {γ : Type*}
namespace Multiset
/-! ### Additive monoid -/
section add
variable {s t u : Multiset α}
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : Multiset α) : Multiset α :=
(Quotient.liftOn₂ s₁ s₂ fun l₁ l₂ => ((l₁ ++ l₂ : List α) : Multiset α)) fun _ _ _ _ p₁ p₂ =>
Quot.sound <| p₁.append p₂
instance : Add (Multiset α) :=
⟨Multiset.add⟩
@[simp]
theorem coe_add (s t : List α) : (s + t : Multiset α) = (s ++ t : List α) :=
rfl
@[simp]
theorem singleton_add (a : α) (s : Multiset α) : {a} + s = a ::ₘ s :=
rfl
protected lemma add_le_add_iff_left : s + t ≤ s + u ↔ t ≤ u :=
Quotient.inductionOn₃ s t u fun _ _ _ => subperm_append_left _
protected lemma add_le_add_iff_right : s + u ≤ t + u ↔ s ≤ t :=
Quotient.inductionOn₃ s t u fun _ _ _ => subperm_append_right _
protected alias ⟨le_of_add_le_add_left, add_le_add_left⟩ := Multiset.add_le_add_iff_left
protected alias ⟨le_of_add_le_add_right, add_le_add_right⟩ := Multiset.add_le_add_iff_right
protected lemma add_comm (s t : Multiset α) : s + t = t + s :=
Quotient.inductionOn₂ s t fun _ _ ↦ Quot.sound perm_append_comm
protected lemma add_assoc (s t u : Multiset α) : s + t + u = s + (t + u) :=
Quotient.inductionOn₃ s t u fun _ _ _ ↦ congr_arg _ <| append_assoc ..
@[simp high]
protected lemma zero_add (s : Multiset α) : 0 + s = s := Quotient.inductionOn s fun _ ↦ rfl
@[simp high]
protected lemma add_zero (s : Multiset α) : s + 0 = s :=
Quotient.inductionOn s fun l ↦ congr_arg _ <| append_nil l
lemma le_add_right (s t : Multiset α) : s ≤ s + t := by
simpa using Multiset.add_le_add_left (zero_le t)
lemma le_add_left (s t : Multiset α) : s ≤ t + s := by
simpa using Multiset.add_le_add_right (zero_le t)
lemma subset_add_left {s t : Multiset α} : s ⊆ s + t := subset_of_le <| le_add_right s t
lemma subset_add_right {s t : Multiset α} : s ⊆ t + s := subset_of_le <| le_add_left s t
theorem le_iff_exists_add {s t : Multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨fun h =>
leInductionOn h fun s =>
let ⟨l, p⟩ := s.exists_perm_append
⟨l, Quot.sound p⟩,
fun ⟨_u, e⟩ => e.symm ▸ le_add_right _ _⟩
@[simp]
theorem cons_add (a : α) (s t : Multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by
rw [← singleton_add, ← singleton_add, Multiset.add_assoc]
@[simp]
theorem add_cons (a : α) (s t : Multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by
rw [Multiset.add_comm, cons_add, Multiset.add_comm]
@[simp, grind =]
theorem mem_add {a : α} {s t : Multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => mem_append
variable (p : α → Prop) [DecidablePred p]
@[simp]
theorem countP_add (s t) : countP p (s + t) = countP p s + countP p t :=
Quotient.inductionOn₂ s t fun _ _ => countP_append
variable [DecidableEq α] in
@[simp]
theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countP_add _
protected lemma add_left_inj : s + u = t + u ↔ s = t := by classical simp [Multiset.ext]
protected lemma add_right_inj : s + t = s + u ↔ t = u := by classical simp [Multiset.ext]
@[simp]
theorem card_add (s t : Multiset α) : card (s + t) = card s + card t :=
Quotient.inductionOn₂ s t fun _ _ => length_append
end add
/-! ### Erasing one copy of an element -/
section Erase
variable [DecidableEq α] {s t : Multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/
def erase (s : Multiset α) (a : α) : Multiset α :=
Quot.liftOn s (fun l => (l.erase a : Multiset α)) fun _l₁ _l₂ p => Quot.sound (p.erase a)
@[simp]
theorem coe_erase (l : List α) (a : α) : erase (l : Multiset α) a = l.erase a :=
rfl
@[simp]
theorem erase_zero (a : α) : (0 : Multiset α).erase a = 0 :=
rfl
@[simp]
theorem erase_cons_head (a : α) (s : Multiset α) : (a ::ₘ s).erase a = s :=
Quot.inductionOn s fun l => congr_arg _ <| List.erase_cons_head a l
@[simp]
theorem erase_cons_tail {a b : α} (s : Multiset α) (h : b ≠ a) :
(b ::ₘ s).erase a = b ::ₘ s.erase a :=
Quot.inductionOn s fun _ => congr_arg _ <| List.erase_cons_tail (not_beq_of_ne h)
@[simp]
theorem erase_singleton (a : α) : ({a} : Multiset α).erase a = 0 :=
erase_cons_head a 0
@[simp]
theorem erase_of_notMem {a : α} {s : Multiset α} : a ∉ s → s.erase a = s :=
Quot.inductionOn s fun _l h => congr_arg _ <| List.erase_of_not_mem h
@[deprecated (since := "2025-05-23")] alias erase_of_not_mem := erase_of_notMem
@[simp]
theorem cons_erase {s : Multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s :=
Quot.inductionOn s fun _l h => Quot.sound (perm_cons_erase h).symm
theorem erase_cons_tail_of_mem (h : a ∈ s) :
(b ::ₘ s).erase a = b ::ₘ s.erase a := by
rcases eq_or_ne a b with rfl | hab
· simp [cons_erase h]
· exact s.erase_cons_tail hab.symm
theorem le_cons_erase (s : Multiset α) (a : α) : s ≤ a ::ₘ s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw [erase_of_notMem h]; apply le_cons_self
theorem add_singleton_eq_iff {s t : Multiset α} {a : α} : s + {a} = t ↔ a ∈ t ∧ s = t.erase a := by
rw [Multiset.add_comm, singleton_add]
constructor
· rintro rfl
exact ⟨s.mem_cons_self a, (s.erase_cons_head a).symm⟩
· rintro ⟨h, rfl⟩
exact cons_erase h
theorem erase_add_left_pos {a : α} {s : Multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
Quotient.inductionOn₂ s t fun _l₁ l₂ h => congr_arg _ <| erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) (h : a ∈ t) : (s + t).erase a = s + t.erase a := by
rw [Multiset.add_comm, erase_add_left_pos s h, Multiset.add_comm]
theorem erase_add_right_neg {a : α} {s : Multiset α} (t) :
a ∉ s → (s + t).erase a = s + t.erase a :=
Quotient.inductionOn₂ s t fun _l₁ l₂ h => congr_arg _ <| erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) (h : a ∉ t) : (s + t).erase a = s.erase a + t := by
rw [Multiset.add_comm, erase_add_right_neg s h, Multiset.add_comm]
theorem erase_le (a : α) (s : Multiset α) : s.erase a ≤ s :=
Quot.inductionOn s fun _ => erase_sublist.subperm
@[simp]
theorem erase_lt {a : α} {s : Multiset α} : s.erase a < s ↔ a ∈ s :=
⟨fun h => not_imp_comm.1 erase_of_notMem (ne_of_lt h), fun h => by
simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : Multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : Multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
Quot.inductionOn s fun _l => List.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : Multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : Multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
Quot.inductionOn s fun l => congr_arg _ <| l.erase_comm a b
instance : RightCommutative erase (α := α) := ⟨erase_comm⟩
@[gcongr]
theorem erase_le_erase {s t : Multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
leInductionOn h fun h => (h.erase _).subperm
theorem erase_le_iff_le_cons {s t : Multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t :=
⟨fun h => le_trans (le_cons_erase _ _) (cons_le_cons _ h), fun h =>
if m : a ∈ s then by rw [← cons_erase m] at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_notMem m).1 h)⟩
@[simp]
theorem card_erase_of_mem {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) = pred (card s) :=
Quot.inductionOn s fun _l => length_erase_of_mem
-- @[simp] -- removed because LHS is not in simp normal form
theorem card_erase_add_one {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) + 1 = card s :=
Quot.inductionOn s fun _l => length_erase_add_one
theorem card_erase_lt_of_mem {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) < card s :=
fun h => card_lt_card (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : Multiset α} : card (s.erase a) ≤ card s :=
card_le_card (erase_le a s)
theorem card_erase_eq_ite {a : α} {s : Multiset α} :
card (s.erase a) = if a ∈ s then pred (card s) else card s := by
by_cases h : a ∈ s
· rwa [card_erase_of_mem h, if_pos]
· rwa [erase_of_notMem h, if_neg]
@[simp]
theorem count_erase_self (a : α) (s : Multiset α) : count a (erase s a) = count a s - 1 :=
Quotient.inductionOn s fun l => by
convert List.count_erase_self (a := a) (l := l) <;> rw [← coe_count] <;> simp
@[simp]
theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : Multiset α) :
count a (erase s b) = count a s :=
Quotient.inductionOn s fun l => by
convert List.count_erase_of_ne ab (l := l) <;> rw [← coe_count] <;> simp
end Erase
/-! ### Subtraction -/
section sub
variable [DecidableEq α] {s t u : Multiset α} {a : α}
/-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`.
(note that it is truncated subtraction, so `count a (s - t) = 0` if `count a s ≤ count a t`). -/
protected def sub (s t : Multiset α) : Multiset α :=
(Quotient.liftOn₂ s t fun l₁ l₂ => (l₁.diff l₂ : Multiset α)) fun _v₁ _v₂ _w₁ _w₂ p₁ p₂ =>
Quot.sound <| p₁.diff p₂
instance : Sub (Multiset α) := ⟨.sub⟩
@[simp]
lemma coe_sub (s t : List α) : (s - t : Multiset α) = s.diff t :=
rfl
/-- This is a special case of `tsub_zero`, which should be used instead of this.
This is needed to prove `OrderedSub (Multiset α)`. -/
@[simp high]
protected lemma sub_zero (s : Multiset α) : s - 0 = s :=
Quot.inductionOn s fun _l => rfl
@[simp]
lemma sub_cons (a : α) (s t : Multiset α) : s - a ::ₘ t = s.erase a - t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => congr_arg _ <| diff_cons _ _ _
protected lemma zero_sub (t : Multiset α) : 0 - t = 0 :=
Multiset.induction_on t rfl fun a s ih => by simp [ih]
@[simp]
lemma countP_sub {s t : Multiset α} :
t ≤ s → ∀ (p : α → Prop) [DecidablePred p], countP p (s - t) = countP p s - countP p t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ hl _ _ ↦ List.countP_diff hl _
@[simp]
lemma count_sub (a : α) (s t : Multiset α) : count a (s - t) = count a s - count a t :=
Quotient.inductionOn₂ s t <| by simp [List.count_diff]
/-- This is a special case of `tsub_le_iff_right`, which should be used instead of this.
This is needed to prove `OrderedSub (Multiset α)`. -/
protected lemma sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by
induction t using Multiset.induction_on generalizing s with
| empty => simp [Multiset.sub_zero]
| cons a s IH => simp [IH, erase_le_iff_le_cons]
/-- This is a special case of `tsub_le_iff_left`, which should be used instead of this. -/
protected lemma sub_le_iff_le_add' : s - t ≤ u ↔ s ≤ t + u := by
rw [Multiset.sub_le_iff_le_add, Multiset.add_comm]
protected theorem sub_le_self (s t : Multiset α) : s - t ≤ s := by
rw [Multiset.sub_le_iff_le_add]
exact le_add_right _ _
protected lemma add_sub_assoc (hut : u ≤ t) : s + t - u = s + (t - u) := by
ext a; simp [Nat.add_sub_assoc <| count_le_of_le _ hut]
protected lemma add_sub_cancel (hts : t ≤ s) : s - t + t = s := by
ext a; simp [Nat.sub_add_cancel <| count_le_of_le _ hts]
protected lemma sub_add_cancel (hts : t ≤ s) : s - t + t = s := by
ext a; simp [Nat.sub_add_cancel <| count_le_of_le _ hts]
protected lemma sub_add_eq_sub_sub : s - (t + u) = s - t - u := by ext; simp [Nat.sub_add_eq]
protected lemma le_sub_add : s ≤ s - t + t := Multiset.sub_le_iff_le_add.1 le_rfl
protected lemma le_add_sub : s ≤ t + (s - t) := Multiset.sub_le_iff_le_add'.1 le_rfl
protected lemma sub_le_sub_right (hst : s ≤ t) : s - u ≤ t - u :=
Multiset.sub_le_iff_le_add'.mpr <| hst.trans Multiset.le_add_sub
protected lemma add_sub_cancel_right : s + t - t = s := by ext a; simp
protected lemma eq_sub_of_add_eq (hstu : s + t = u) : s = u - t := by
rw [← hstu, Multiset.add_sub_cancel_right]
lemma cons_sub_of_le (a : α) {s t : Multiset α} (h : t ≤ s) : a ::ₘ s - t = a ::ₘ (s - t) := by
rw [← singleton_add, ← singleton_add, Multiset.add_sub_assoc h]
@[simp]
lemma card_sub {s t : Multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
Nat.eq_sub_of_add_eq <| by rw [← card_add, Multiset.sub_add_cancel h]
@[simp] theorem sub_singleton (a : α) (s : Multiset α) : s - {a} = s.erase a := by
ext
simp only [count_sub, count_singleton]
split <;> simp_all
theorem mem_sub {a : α} {s t : Multiset α} :
a ∈ s - t ↔ t.count a < s.count a := by
rw [← count_pos, count_sub, Nat.sub_pos_iff_lt]
end sub
/-! ### Lift a relation to `Multiset`s -/
section Rel
variable {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
theorem Rel.add {s t u v} (hst : Rel r s t) (huv : Rel r u v) : Rel r (s + u) (t + v) := by
induction hst with
| zero => simpa using huv
| cons hab hst ih => simpa using ih.cons hab
theorem rel_add_left {as₀ as₁} :
∀ {bs}, Rel r (as₀ + as₁) bs ↔ ∃ bs₀ bs₁, Rel r as₀ bs₀ ∧ Rel r as₁ bs₁ ∧ bs = bs₀ + bs₁ :=
@(Multiset.induction_on as₀ (by simp) fun a s ih bs ↦ by
simp only [ih, cons_add, rel_cons_left]
constructor
· intro h
rcases h with ⟨b, bs', hab, h, rfl⟩
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩
exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩
· intro h
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩
rcases h with ⟨b, bs, hab, h₀, rfl⟩
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩)
theorem rel_add_right {as bs₀ bs₁} :
Rel r as (bs₀ + bs₁) ↔ ∃ as₀ as₁, Rel r as₀ bs₀ ∧ Rel r as₁ bs₁ ∧ as = as₀ + as₁ := by
rw [← rel_flip, rel_add_left]; simp [rel_flip]
end Rel
section Nodup
@[simp]
theorem nodup_singleton : ∀ a : α, Nodup ({a} : Multiset α) :=
List.nodup_singleton
theorem not_nodup_pair : ∀ a : α, ¬Nodup (a ::ₘ a ::ₘ 0) :=
List.not_nodup_pair
theorem Nodup.erase [DecidableEq α] (a : α) {l} : Nodup l → Nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
theorem mem_sub_of_nodup [DecidableEq α] {a : α} {s t : Multiset α} (d : Nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨fun h =>
⟨mem_of_le (Multiset.sub_le_self ..) h, fun h' => by
refine count_eq_zero.1 ?_ h
rw [count_sub a s t, Nat.sub_eq_zero_iff_le]
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
fun ⟨h₁, h₂⟩ => Or.resolve_right (mem_add.1 <| mem_of_le Multiset.le_sub_add h₁) h₂⟩
end Nodup
end Multiset
|
OfColimitCommutesFiniteLimit.lean
|
/-
Copyright (c) 2024 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import Mathlib.CategoryTheory.Limits.Types.Colimits
import Mathlib.CategoryTheory.Limits.Filtered
import Mathlib.CategoryTheory.Limits.Yoneda
/-!
# If colimits of shape `K` commute with finite limits, then `K` is filtered.
-/
universe v u
namespace CategoryTheory
variable {K : Type v} [SmallCategory K]
open Limits
/-- A converse to `colimitLimitIso`: if colimits of shape `K` commute with finite
limits, then `K` is filtered. -/
theorem isFiltered_of_nonempty_limit_colimit_to_colimit_limit
(h : ∀ {J : Type v} [SmallCategory J] [FinCategory J] (F : J ⥤ K ⥤ Type v),
Nonempty (limit (colimit F.flip) ⟶ colimit (limit F))) : IsFiltered K := by
refine IsFiltered.iff_nonempty_limit.2 (fun {J} _ _ F => ?_)
suffices Nonempty (limit (colimit (F.op ⋙ coyoneda).flip)) by
obtain ⟨X, y, -⟩ := Types.jointly_surjective' (this.map (h (F.op ⋙ coyoneda)).some).some
exact ⟨X, ⟨(limitObjIsoLimitCompEvaluation (F.op ⋙ coyoneda) _).hom y⟩⟩
let _ (j : Jᵒᵖ) : Unique ((colimit (F.op ⋙ coyoneda).flip).obj j) :=
((colimitObjIsoColimitCompEvaluation (F.op ⋙ coyoneda).flip _ ≪≫
Coyoneda.colimitCoyonedaIso _)).toEquiv.unique
exact ⟨Types.Limit.mk (colimit (F.op ⋙ coyoneda).flip) (fun j => default) (by subsingleton)⟩
end CategoryTheory
|
enat_to_nat.lean
|
import Mathlib.Tactic.ENatToNat
example (a b : ENat) (h : a = b) : a - b = b - a := by
enat_to_nat
omega
example (a b : ENat) (h : a ≤ b) : a - b < b + 1 := by
enat_to_nat
omega
example (a b : ENat) (h : a ≤ b) : a - 2 * b ≤ b + 1 := by
enat_to_nat
omega
example (a b c : ENat) (hab : a ≥ b) (hbc : b ≥ c) : a ≥ c := by
enat_to_nat
omega
example (a b : ENat) (h : a = b) : a - b = b - a := by
-- to test if the tactic works with inaccessible names
let a : ℤ := 42
let b : ℤ := 32
enat_to_nat
omega
|
MinMax.lean
|
/-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Logic.OpClass
import Mathlib.Order.Lattice
/-!
# `max` and `min`
This file proves basic properties about maxima and minima on a `LinearOrder`.
## Tags
min, max
-/
universe u v
variable {α : Type u} {β : Type v}
section
variable [LinearOrder α] [LinearOrder β] {f : α → β} {s : Set α} {a b c d : α}
-- translate from lattices to linear orders (sup → max, inf → min)
theorem le_min_iff : c ≤ min a b ↔ c ≤ a ∧ c ≤ b :=
le_inf_iff
theorem le_max_iff : a ≤ max b c ↔ a ≤ b ∨ a ≤ c :=
le_sup_iff
theorem min_le_iff : min a b ≤ c ↔ a ≤ c ∨ b ≤ c :=
inf_le_iff
theorem max_le_iff : max a b ≤ c ↔ a ≤ c ∧ b ≤ c :=
sup_le_iff
theorem lt_min_iff : a < min b c ↔ a < b ∧ a < c :=
lt_inf_iff
theorem lt_max_iff : a < max b c ↔ a < b ∨ a < c :=
lt_sup_iff
theorem min_lt_iff : min a b < c ↔ a < c ∨ b < c :=
inf_lt_iff
theorem max_lt_iff : max a b < c ↔ a < c ∧ b < c :=
sup_lt_iff
theorem max_le_max : a ≤ c → b ≤ d → max a b ≤ max c d :=
sup_le_sup
theorem max_le_max_left (c) (h : a ≤ b) : max c a ≤ max c b := sup_le_sup_left h c
theorem max_le_max_right (c) (h : a ≤ b) : max a c ≤ max b c := sup_le_sup_right h c
theorem min_le_min : a ≤ c → b ≤ d → min a b ≤ min c d :=
inf_le_inf
theorem min_le_min_left (c) (h : a ≤ b) : min c a ≤ min c b := inf_le_inf_left c h
theorem min_le_min_right (c) (h : a ≤ b) : min a c ≤ min b c := inf_le_inf_right c h
theorem le_max_of_le_left : a ≤ b → a ≤ max b c :=
le_sup_of_le_left
theorem le_max_of_le_right : a ≤ c → a ≤ max b c :=
le_sup_of_le_right
theorem lt_max_of_lt_left (h : a < b) : a < max b c :=
h.trans_le (le_max_left b c)
theorem lt_max_of_lt_right (h : a < c) : a < max b c :=
h.trans_le (le_max_right b c)
theorem min_le_of_left_le : a ≤ c → min a b ≤ c :=
inf_le_of_left_le
theorem min_le_of_right_le : b ≤ c → min a b ≤ c :=
inf_le_of_right_le
theorem min_lt_of_left_lt (h : a < c) : min a b < c :=
(min_le_left a b).trans_lt h
theorem min_lt_of_right_lt (h : b < c) : min a b < c :=
(min_le_right a b).trans_lt h
lemma max_min_distrib_left (a b c : α) : max a (min b c) = min (max a b) (max a c) :=
sup_inf_left _ _ _
lemma max_min_distrib_right (a b c : α) : max (min a b) c = min (max a c) (max b c) :=
sup_inf_right _ _ _
lemma min_max_distrib_left (a b c : α) : min a (max b c) = max (min a b) (min a c) :=
inf_sup_left _ _ _
lemma min_max_distrib_right (a b c : α) : min (max a b) c = max (min a c) (min b c) :=
inf_sup_right _ _ _
theorem min_le_max : min a b ≤ max a b :=
le_trans (min_le_left a b) (le_max_left a b)
theorem min_eq_left_iff : min a b = a ↔ a ≤ b :=
inf_eq_left
theorem min_eq_right_iff : min a b = b ↔ b ≤ a :=
inf_eq_right
theorem max_eq_left_iff : max a b = a ↔ b ≤ a :=
sup_eq_left
theorem max_eq_right_iff : max a b = b ↔ a ≤ b :=
sup_eq_right
/-- For elements `a` and `b` of a linear order, either `min a b = a` and `a ≤ b`,
or `min a b = b` and `b < a`.
Use cases on this lemma to automate linarith in inequalities -/
theorem min_cases (a b : α) : min a b = a ∧ a ≤ b ∨ min a b = b ∧ b < a := by
by_cases h : a ≤ b
· left
exact ⟨min_eq_left h, h⟩
· right
exact ⟨min_eq_right (le_of_lt (not_le.mp h)), not_le.mp h⟩
/-- For elements `a` and `b` of a linear order, either `max a b = a` and `b ≤ a`,
or `max a b = b` and `a < b`.
Use cases on this lemma to automate linarith in inequalities -/
theorem max_cases (a b : α) : max a b = a ∧ b ≤ a ∨ max a b = b ∧ a < b :=
@min_cases αᵒᵈ _ a b
theorem min_eq_iff : min a b = c ↔ a = c ∧ a ≤ b ∨ b = c ∧ b ≤ a := by
constructor
· intro h
refine Or.imp (fun h' => ?_) (fun h' => ?_) (le_total a b) <;> exact ⟨by simpa [h'] using h, h'⟩
· rintro (⟨rfl, h⟩ | ⟨rfl, h⟩) <;> simp [h]
theorem max_eq_iff : max a b = c ↔ a = c ∧ b ≤ a ∨ b = c ∧ a ≤ b :=
@min_eq_iff αᵒᵈ _ a b c
theorem min_lt_min_left_iff : min a c < min b c ↔ a < b ∧ a < c := by
simp_rw [lt_min_iff, min_lt_iff, or_iff_left (lt_irrefl _)]
exact and_congr_left fun h => or_iff_left_of_imp h.trans
theorem min_lt_min_right_iff : min a b < min a c ↔ b < c ∧ b < a := by
simp_rw [min_comm a, min_lt_min_left_iff]
theorem max_lt_max_left_iff : max a c < max b c ↔ a < b ∧ c < b :=
@min_lt_min_left_iff αᵒᵈ _ _ _ _
theorem max_lt_max_right_iff : max a b < max a c ↔ b < c ∧ a < c :=
@min_lt_min_right_iff αᵒᵈ _ _ _ _
/-- An instance asserting that `max a a = a` -/
instance max_idem : Std.IdempotentOp (α := α) max where
idempotent := by simp
-- short-circuit type class inference
/-- An instance asserting that `min a a = a` -/
instance min_idem : Std.IdempotentOp (α := α) min where
idempotent := by simp
-- short-circuit type class inference
theorem min_lt_max : min a b < max a b ↔ a ≠ b :=
inf_lt_sup
theorem max_lt_max (h₁ : a < c) (h₂ : b < d) : max a b < max c d :=
max_lt (lt_max_of_lt_left h₁) (lt_max_of_lt_right h₂)
theorem min_lt_min (h₁ : a < c) (h₂ : b < d) : min a b < min c d :=
@max_lt_max αᵒᵈ _ _ _ _ _ h₁ h₂
theorem min_right_comm (a b c : α) : min (min a b) c = min (min a c) b := by
rw [min_assoc, min_comm b, min_assoc]
theorem Max.left_comm (a b c : α) : max a (max b c) = max b (max a c) := by
rw [← max_assoc, max_comm a, max_assoc]
theorem Max.right_comm (a b c : α) : max (max a b) c = max (max a c) b := by
rw [max_assoc, max_comm b, max_assoc]
theorem MonotoneOn.map_max (hf : MonotoneOn f s) (ha : a ∈ s) (hb : b ∈ s) : f (max a b) =
max (f a) (f b) := by
rcases le_total a b with h | h <;>
simp only [max_eq_right, max_eq_left, hf ha hb, hf hb ha, h]
theorem MonotoneOn.map_min (hf : MonotoneOn f s) (ha : a ∈ s) (hb : b ∈ s) : f (min a b) =
min (f a) (f b) := hf.dual.map_max ha hb
theorem AntitoneOn.map_max (hf : AntitoneOn f s) (ha : a ∈ s) (hb : b ∈ s) : f (max a b) =
min (f a) (f b) := hf.dual_right.map_max ha hb
theorem AntitoneOn.map_min (hf : AntitoneOn f s) (ha : a ∈ s) (hb : b ∈ s) : f (min a b) =
max (f a) (f b) := hf.dual.map_max ha hb
theorem Monotone.map_max (hf : Monotone f) : f (max a b) = max (f a) (f b) := by
rcases le_total a b with h | h <;> simp [h, hf h]
theorem Monotone.map_min (hf : Monotone f) : f (min a b) = min (f a) (f b) :=
hf.dual.map_max
theorem Antitone.map_max (hf : Antitone f) : f (max a b) = min (f a) (f b) := by
rcases le_total a b with h | h <;> simp [h, hf h]
theorem Antitone.map_min (hf : Antitone f) : f (min a b) = max (f a) (f b) :=
hf.dual.map_max
theorem min_choice (a b : α) : min a b = a ∨ min a b = b := by cases le_total a b <;> simp [*]
theorem max_choice (a b : α) : max a b = a ∨ max a b = b :=
@min_choice αᵒᵈ _ a b
theorem le_of_max_le_left {a b c : α} (h : max a b ≤ c) : a ≤ c :=
le_trans (le_max_left _ _) h
theorem le_of_max_le_right {a b c : α} (h : max a b ≤ c) : b ≤ c :=
le_trans (le_max_right _ _) h
instance instCommutativeMax : Std.Commutative (α := α) max where comm := max_comm
instance instAssociativeMax : Std.Associative (α := α) max where assoc := max_assoc
instance instCommutativeMin : Std.Commutative (α := α) min where comm := min_comm
instance instAssociativeMin : Std.Associative (α := α) min where assoc := min_assoc
theorem max_left_commutative : LeftCommutative (max : α → α → α) := ⟨max_left_comm⟩
theorem min_left_commutative : LeftCommutative (min : α → α → α) := ⟨min_left_comm⟩
end
|
ExistsI.lean
|
/-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll
-/
import Mathlib.Tactic.ExistsI
example : ∃ x : Nat, x = x := by
existsi 42
rfl
example : ∃ x : Nat, ∃ y : Nat, x = y := by
existsi 42, 42
rfl
|
UniversalVerts.lean
|
/-
Copyright (c) 2024 Pim Otte. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Pim Otte
-/
import Mathlib.Combinatorics.SimpleGraph.Clique
import Mathlib.Combinatorics.SimpleGraph.Connectivity.Represents
import Mathlib.Combinatorics.SimpleGraph.Matching
/-!
# Universal Vertices
This file defines the set of universal vertices: those vertices that are connected
to all others. In addition, it describes results when considering connected components
of the graph where universal vertices are deleted. This particular graph plays a role
in the proof of Tutte's Theorem.
## Main definitions
* `G.universalVerts` is the set of vertices that are connected to all other vertices.
* `G.deleteUniversalVerts` is the subgraph of `G` with the universal vertices removed.
-/
assert_not_exists Field TwoSidedIdeal
namespace SimpleGraph
variable {V : Type*} {G : SimpleGraph V}
/--
The set of vertices that are connected to all other vertices.
-/
def universalVerts (G : SimpleGraph V) : Set V := {v : V | ∀ ⦃w⦄, v ≠ w → G.Adj w v}
lemma isClique_universalVerts (G : SimpleGraph V) : G.IsClique G.universalVerts :=
fun _ _ _ hy hxy ↦ hy hxy.symm
/--
The subgraph of `G` with the universal vertices removed.
-/
@[simps!]
def deleteUniversalVerts (G : SimpleGraph V) : Subgraph G :=
(⊤ : Subgraph G).deleteVerts G.universalVerts
lemma Subgraph.IsMatching.exists_of_universalVerts [Finite V] {s : Set V}
(h : Disjoint G.universalVerts s) (hc : s.ncard ≤ G.universalVerts.ncard) :
∃ t ⊆ G.universalVerts, ∃ (M : Subgraph G), M.verts = s ∪ t ∧ M.IsMatching := by
obtain ⟨t, ht⟩ := Set.exists_subset_card_eq hc
refine ⟨t, ht.1, ?_⟩
obtain ⟨f⟩ : Nonempty (s ≃ t) := by
rw [← Cardinal.eq, ← t.cast_ncard t.toFinite, ← s.cast_ncard s.toFinite, ht.2]
letI hd := Set.disjoint_of_subset_left ht.1 h
have hadj (v : s) : G.Adj v (f v) := ht.1 (f v).2 (hd.ne_of_mem (f v).2 v.2)
exact Subgraph.IsMatching.exists_of_disjoint_sets_of_equiv hd.symm f hadj
lemma disjoint_image_val_universalVerts (s : Set G.deleteUniversalVerts.verts) :
Disjoint (Subtype.val '' s) G.universalVerts := by
simpa [← Set.disjoint_compl_right_iff_subset, Set.compl_eq_univ_diff] using
Subtype.coe_image_subset _ s
/-- A component of the graph with universal vertices is even if we remove a set of representatives
of odd components and a subset of universal vertices.
This is because the number of vertices in the even components is not affected, and from odd
components exactly one vertex is removed. -/
lemma even_ncard_image_val_supp_sdiff_image_val_rep_union {t : Set V}
{s : Set G.deleteUniversalVerts.verts} (K : G.deleteUniversalVerts.coe.ConnectedComponent)
(h : t ⊆ G.universalVerts)
(hrep : ConnectedComponent.Represents s G.deleteUniversalVerts.coe.oddComponents) :
Even (Subtype.val '' K.supp \ (Subtype.val '' s ∪ t)).ncard := by
simp [-deleteUniversalVerts_verts, ← Set.diff_inter_diff, ← Set.image_diff Subtype.val_injective,
sdiff_eq_left.mpr <| Set.disjoint_of_subset_right h (disjoint_image_val_universalVerts _),
Set.inter_diff_distrib_right, ← Set.image_inter Subtype.val_injective,
Set.ncard_image_of_injective _ Subtype.val_injective, K.even_ncard_supp_sdiff_rep hrep]
end SimpleGraph
|
FromLRAT.lean
|
/-
Copyright (c) 2022 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Algebra.Group.Nat.Defs
import Mathlib.Tactic.ByContra
/-!
# `lrat_proof` command
Defines a macro for producing SAT proofs from CNF / LRAT files.
These files are commonly used in the SAT community for writing proofs.
Most SAT solvers support export to [DRAT](https://arxiv.org/abs/1610.06229) format,
but this format can be expensive to reconstruct because it requires recomputing all
unit propagation steps. The [LRAT](https://arxiv.org/abs/1612.02353) format solves this
issue by attaching a proof to the deduction of each new clause.
(The L in LRAT stands for Linear time verification.)
There are several verified checkers for the LRAT format, and the program implemented here
makes it possible to use the lean kernel as an LRAT checker as well and expose the results
as a standard propositional theorem.
The input to the `lrat_proof` command is the name of the theorem to define,
and the statement (written in CNF format) and the proof (in LRAT format).
For example:
```
lrat_proof foo
"p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0"
"5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
```
produces a theorem:
```
foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1
```
* You can see the theorem statement by hovering over the word `foo`.
* You can use the `example` keyword in place of `foo` to avoid generating a theorem.
* You can use the `include_str` macro in place of the two strings
to load CNF / LRAT files from disk.
-/
open Lean hiding Literal
open Std (HashMap)
namespace Sat
/-- A literal is a positive or negative occurrence of an atomic propositional variable.
Note that unlike DIMACS, 0 is a valid variable index. -/
inductive Literal
| pos : Nat → Literal
| neg : Nat → Literal
/-- Construct a literal. Positive numbers are translated to positive literals,
and negative numbers become negative literals. The input is assumed to be nonzero. -/
def Literal.ofInt (i : Int) : Literal :=
if i < 0 then Literal.neg (-i-1).toNat else Literal.pos (i-1).toNat
/-- Swap the polarity of a literal. -/
def Literal.negate : Literal → Literal
| pos i => neg i
| neg i => pos i
instance : ToExpr Literal where
toTypeExpr := mkConst ``Literal
toExpr
| Literal.pos i => mkApp (mkConst ``Literal.pos) (mkRawNatLit i)
| Literal.neg i => mkApp (mkConst ``Literal.neg) (mkRawNatLit i)
/-- A clause is a list of literals, thought of as a disjunction like `a ∨ b ∨ ¬c`. -/
def Clause := List Literal
/-- The empty clause -/
def Clause.nil : Clause := []
/-- Append a literal to a clause. -/
def Clause.cons : Literal → Clause → Clause := List.cons
/-- A formula is a list of clauses, thought of as a conjunction like `(a ∨ b) ∧ c ∧ (¬c ∨ ¬d)`. -/
abbrev Fmla := List Clause
/-- A single clause as a formula. -/
def Fmla.one (c : Clause) : Fmla := [c]
/-- A conjunction of formulas. -/
def Fmla.and (a b : Fmla) : Fmla := a ++ b
/-- Formula `f` subsumes `f'` if all the clauses in `f'` are in `f`.
We use this to prove that all clauses in the formula are subsumed by it. -/
structure Fmla.subsumes (f f' : Fmla) : Prop where
prop : ∀ x, x ∈ f' → x ∈ f
theorem Fmla.subsumes_self (f : Fmla) : f.subsumes f := ⟨fun _ h ↦ h⟩
theorem Fmla.subsumes_left (f f₁ f₂ : Fmla) (H : f.subsumes (f₁.and f₂)) : f.subsumes f₁ :=
⟨fun _ h ↦ H.1 _ <| List.mem_append.2 <| Or.inl h⟩
theorem Fmla.subsumes_right (f f₁ f₂ : Fmla) (H : f.subsumes (f₁.and f₂)) : f.subsumes f₂ :=
⟨fun _ h ↦ H.1 _ <| List.mem_append.2 <| Or.inr h⟩
/-- A valuation is an assignment of values to all the propositional variables. -/
def Valuation := Nat → Prop
/-- `v.neg lit` asserts that literal `lit` is falsified in the valuation. -/
def Valuation.neg (v : Valuation) : Literal → Prop
| Literal.pos i => ¬ v i
| Literal.neg i => v i
/-- `v.satisfies c` asserts that clause `c` satisfied by the valuation.
It is written in a negative way: A clause like `a ∨ ¬b ∨ c` is rewritten as
`¬a → b → ¬c → False`, so we are asserting that it is not the case that
all literals in the clause are falsified. -/
def Valuation.satisfies (v : Valuation) : Clause → Prop
| [] => False
| l::c => v.neg l → v.satisfies c
/-- `v.satisfies_fmla f` asserts that formula `f` is satisfied by the valuation.
A formula is satisfied if all clauses in it are satisfied. -/
structure Valuation.satisfies_fmla (v : Valuation) (f : Fmla) : Prop where
prop : ∀ c, c ∈ f → v.satisfies c
/-- `f.proof c` asserts that `c` is derivable from `f`. -/
def Fmla.proof (f : Fmla) (c : Clause) : Prop :=
∀ v : Valuation, v.satisfies_fmla f → v.satisfies c
/-- If `f` subsumes `c` (i.e. `c ∈ f`), then `f.proof c`. -/
theorem Fmla.proof_of_subsumes {f : Fmla} {c : Clause}
(H : Fmla.subsumes f (Fmla.one c)) : f.proof c :=
fun _ h ↦ h.1 _ <| H.1 _ <| List.Mem.head ..
/-- The core unit-propagation step.
We have a local context of assumptions `¬l'` (sometimes called an assignment)
and we wish to add `¬l` to the context, that is, we want to prove `l` is also falsified.
This is because there is a clause `a ∨ b ∨ ¬l` in the global context
such that all literals in the clause are falsified except for `¬l`;
so in the context `h₁` where we suppose that `¬l` is falsified,
the clause itself is falsified so we can prove `False`.
We continue the proof in `h₂`, with the assumption that `l` is falsified. -/
theorem Valuation.by_cases {v : Valuation} {l}
(h₁ : v.neg l.negate → False) (h₂ : v.neg l → False) : False :=
match l with
| Literal.pos _ => h₂ h₁
| Literal.neg _ => h₁ h₂
/-- `v.implies p [a, b, c] 0` definitionally unfolds to `(v 0 ↔ a) → (v 1 ↔ b) → (v 2 ↔ c) → p`.
This is used to introduce assumptions about the first `n` values of `v` during reification. -/
def Valuation.implies (v : Valuation) (p : Prop) : List Prop → Nat → Prop
| [], _ => p
| a::as, n => (v n ↔ a) → v.implies p as (n + 1)
/-- `Valuation.mk [a, b, c]` is a valuation which is `a` at 0, `b` at 1 and `c` at 2, and false
everywhere else. -/
def Valuation.mk : List Prop → Valuation
| [], _ => False
| a::_, 0 => a
| _::as, n + 1 => mk as n
/-- The fundamental relationship between `mk` and `implies`:
`(mk ps).implies p ps 0` is equivalent to `p`. -/
theorem Valuation.mk_implies {p} {as ps} (as₁) : as = List.reverseAux as₁ ps →
(Valuation.mk as).implies p ps as₁.length → p := by
induction ps generalizing as₁ with
| nil => exact fun _ ↦ id
| cons a as ih =>
refine fun e H ↦ @ih (a::as₁) e (H ?_)
subst e; clear ih H
suffices ∀ n n', n' = List.length as₁ + n →
∀ bs, mk (as₁.reverseAux bs) n' ↔ mk bs n from this 0 _ rfl (a::as)
induction as₁ with
| nil => simp
| cons b as₁ ih => simpa using fun n bs ↦ ih (n + 1) _ (Nat.succ_add ..) _
/-- Asserts that `¬⟦f⟧_v` implies `p`. -/
structure Fmla.reify (v : Valuation) (f : Fmla) (p : Prop) : Prop where
prop : ¬ v.satisfies_fmla f → p
variable {v : Valuation}
/-- If `f` is unsatisfiable, and every `v` which agrees with `ps` implies `¬⟦f⟧_v → p`, then `p`.
Equivalently, there exists a valuation `v` which agrees with `ps`,
and every such valuation yields `¬⟦f⟧_v` because `f` is unsatisfiable. -/
theorem Fmla.refute {p : Prop} {ps} (f : Fmla) (hf : f.proof [])
(hv : ∀ v, Valuation.implies v (Fmla.reify v f p) ps 0) : p :=
(Valuation.mk_implies [] rfl (hv _)).1 (hf _)
/-- Negation turns AND into OR, so `¬⟦f₁ ∧ f₂⟧_v ≡ ¬⟦f₁⟧_v ∨ ¬⟦f₂⟧_v`. -/
theorem Fmla.reify_or {f₁ : Fmla} {a : Prop} {f₂ : Fmla} {b : Prop}
(h₁ : Fmla.reify v f₁ a) (h₂ : Fmla.reify v f₂ b) : Fmla.reify v (f₁.and f₂) (a ∨ b) := by
refine ⟨fun H ↦ by_contra fun hn ↦ H ⟨fun c h ↦ by_contra fun hn' ↦ ?_⟩⟩
rcases List.mem_append.1 h with h | h
· exact hn <| Or.inl <| h₁.1 fun Hc ↦ hn' <| Hc.1 _ h
· exact hn <| Or.inr <| h₂.1 fun Hc ↦ hn' <| Hc.1 _ h
/-- Asserts that `¬⟦c⟧_v` implies `p`. -/
structure Clause.reify (v : Valuation) (c : Clause) (p : Prop) : Prop where
prop : ¬ v.satisfies c → p
/-- Reification of a single clause formula. -/
theorem Fmla.reify_one {c : Clause} {a : Prop} (h : Clause.reify v c a) :
Fmla.reify v (Fmla.one c) a :=
⟨fun H ↦ h.1 fun h ↦ H ⟨fun | _, List.Mem.head .. => h⟩⟩
/-- Asserts that `¬⟦l⟧_v` implies `p`. -/
structure Literal.reify (v : Valuation) (l : Literal) (p : Prop) : Prop where
prop : v.neg l → p
/-- Negation turns OR into AND, so `¬⟦l ∨ c⟧_v ≡ ¬⟦l⟧_v ∧ ¬⟦c⟧_v`. -/
theorem Clause.reify_and {l : Literal} {a : Prop} {c : Clause} {b : Prop}
(h₁ : Literal.reify v l a) (h₂ : Clause.reify v c b) :
Clause.reify v (Clause.cons l c) (a ∧ b) :=
⟨fun H ↦ ⟨h₁.1 (by_contra fun hn ↦ H hn.elim), h₂.1 fun h ↦ H fun _ ↦ h⟩⟩
/-- The reification of the empty clause is `True`: `¬⟦⊥⟧_v ≡ True`. -/
theorem Clause.reify_zero : Clause.reify v Clause.nil True := ⟨fun _ ↦ trivial⟩
/-- The reification of a singleton clause `¬⟦l⟧_v ≡ ¬⟦l⟧_v`. -/
theorem Clause.reify_one {l : Literal} {a : Prop}
(h₁ : Literal.reify v l a) : Clause.reify v (Clause.nil.cons l) a :=
⟨fun H ↦ ((Clause.reify_and h₁ Clause.reify_zero).1 H).1⟩
/-- The reification of a positive literal `¬⟦a⟧_v ≡ ¬a`. -/
theorem Literal.reify_pos {a : Prop} {n : ℕ} (h : v n ↔ a) : (Literal.pos n).reify v ¬a := ⟨mt h.2⟩
/-- The reification of a negative literal `¬⟦¬a⟧_v ≡ a`. -/
theorem Literal.reify_neg {a : Prop} {n : ℕ} (h : v n ↔ a) : (Literal.neg n).reify v a := ⟨h.1⟩
end Sat
namespace Mathlib.Tactic.Sat
/-- The representation of a global clause. -/
structure Clause where
/-- The list of literals as read from the input file -/
lits : Array Int
/-- The clause expression of type `Clause` -/
expr : Expr
/-- A proof of `⊢ ctx.proof c`.
Note that we do not use `have` statements to cache these proofs:
this is literally the proof expression itself. As a result, the proof terms
rely heavily on dag-like sharing of the expression, and printing these proof terms
directly is likely to crash lean for larger examples. -/
proof : Expr
/-- Construct the clause expression from the input list. For example `[1, -2]` is translated to
`Clause.cons (Literal.pos 1) (Clause.cons (Literal.neg 2) Clause.nil)`. -/
def buildClause (arr : Array Int) : Expr :=
let nil := mkConst ``Sat.Clause.nil
let cons := mkConst ``Sat.Clause.cons
arr.foldr (fun i e ↦ mkApp2 cons (toExpr <| Sat.Literal.ofInt i) e) nil
/-- Constructs the formula expression from the input CNF, as a balanced tree of `Fmla.and` nodes. -/
partial def buildConj (arr : Array (Array Int)) (start stop : Nat) : Expr :=
match stop - start with
| 0 => panic! "empty"
| 1 => mkApp (mkConst ``Sat.Fmla.one) (buildClause arr[start]!)
| len =>
let mid := start + len / 2
mkApp2 (mkConst ``Sat.Fmla.and) (buildConj arr start mid) (buildConj arr mid stop)
/-- Constructs the proofs of `⊢ ctx.proof c` for each clause `c` in `ctx`.
The proofs are stashed in a `HashMap` keyed on the clause ID. -/
partial def buildClauses (arr : Array (Array Int)) (ctx : Expr) (start stop : Nat)
(f p : Expr) (accum : Nat × HashMap Nat Clause) : Nat × HashMap Nat Clause :=
match stop - start with
| 0 => panic! "empty"
| 1 =>
let c := f.appArg!
let proof := mkApp3 (mkConst ``Sat.Fmla.proof_of_subsumes) ctx c p
let n := accum.1 + 1
(n, accum.2.insert n { lits := arr[start]!, expr := c, proof })
| len =>
let mid := start + len / 2
let f₁ := f.appFn!.appArg!
let f₂ := f.appArg!
let p₁ := mkApp4 (mkConst ``Sat.Fmla.subsumes_left) ctx f₁ f₂ p
let p₂ := mkApp4 (mkConst ``Sat.Fmla.subsumes_right) ctx f₁ f₂ p
let accum := buildClauses arr ctx start mid f₁ p₁ accum
buildClauses arr ctx mid stop f₂ p₂ accum
/-- A localized clause reference.
It is the same as `Clause` except that the proof is now a local variable. -/
structure LClause where
/-- The list of literals as read from the input file -/
lits : Array Int
/-- The clause expression of type `Clause` -/
expr : Expr
/-- The bound variable index of the hypothesis asserting `⊢ ctx.proof c`,
_counting from the outside and 1-based_. (We use this numbering because we will need to
reference the variable from multiple binder depths.) -/
depth : Nat
/-- Construct an individual proof step `⊢ ctx.proof c`.
* `db`: the current global context
* `ns`, `clause`: the new clause
* `pf`: the LRAT proof trace
* `ctx`: the main formula
The proof has three steps:
1. Introduce local assumptions `have h1 : ctx.proof c1 := p1` for each clause `c1`
referenced in the proof. We actually do all the introductions at once,
as in `(fun h1 h2 h3 ↦ ...) p1 p2 p3`, because we want `p_i` to not be under any binders
to avoid the cost of `instantiate` during typechecking and get the benefits of dag-like
sharing in the `pi` (which are themselves previous proof steps which may be large terms).
The hypotheses are in `gctx`, keyed on the clause ID.
2. Unfold `⊢ ctx.proof [a, b, c]` to
`∀ v, v.satisfies_fmla ctx → v.neg a → v.neg b → v.neg c → False` and `intro v hv ha hb hc`,
storing each `ha : v.neg a` in `lctx`, keyed on the literal `a`.
3. For each LRAT step `hc : ctx.proof [x, y]`, `hc v hv : v.neg x → v.neg y → False`.
We look for a literal that is not falsified in the clause. Since it is a unit propagation
step, there can be at most one such literal.
* If `x` is the non-falsified clause, let `x'` denote the negated literal of `x`.
Then `x'.negate` reduces to `x`, so `hnx : v.neg x'.negate |- hc v hv hnx hy : False`,
so we construct the term
`by_cases (fun hnx : v.neg x'.negate ↦ hc v hv hnx hy) (fun hx : v.neg x ↦ ...)`
and `hx` is added to the local context.
* If all clauses are falsified, then we are done: `hc v hv hx hy : False`.
-/
partial def buildProofStep (db : HashMap Nat Clause)
(ns pf : Array Int) (ctx clause : Expr) : Except String Expr := Id.run do
let mut lams := #[]
let mut args := #[]
let mut gctx : HashMap Nat LClause := {}
-- step 1
for i in pf do
let i := i.natAbs
let some cl := db[i]? | return Except.error "missing clause"
if !gctx.contains i then
lams := lams.push (mkApp2 (mkConst ``Sat.Fmla.proof) ctx cl.expr)
args := args.push cl.proof
gctx := gctx.insert i {
lits := cl.lits
expr := cl.expr
depth := args.size
}
let n := args.size
-- step 2
let mut f :=
(mkAppN · args) ∘
lams.foldr (mkLambda `c default) ∘
mkLambda `v default (mkConst ``Sat.Valuation) ∘
mkLambda `hv default (mkApp2 (mkConst ``Sat.Valuation.satisfies_fmla) (mkBVar 0) ctx)
let v depth := mkBVar (depth + 1)
let hv depth := mkBVar depth
lams := #[]
let mut clause := clause
let mut depth := 0
let mut lctx : HashMap Int Nat := {}
for i in ns do
let l := clause.appFn!.appArg!
clause := clause.appArg!
lams := lams.push (mkApp2 (mkConst ``Sat.Valuation.neg) (v depth) l)
depth := depth.succ
lctx := lctx.insert i depth
f := f ∘ lams.foldr (mkLambda `h default)
-- step 3
for (step : Int) in pf do
if step < 0 then return Except.error "unimplemented: RAT step"
let some cl := gctx[step.toNat]? | return Except.error "missing clause"
let mut unit := none
for i in cl.lits do
unless lctx.contains i do
if unit.isSome then return Except.error s!"not unit: {cl.lits}"
depth := depth.succ
unit := some i
let mut pr := mkApp2 (mkBVar (depth + n + 2 - cl.depth)) (v depth) (hv depth)
for i in cl.lits do
pr := mkApp pr <| mkBVar (match lctx[i]? with | some k => depth - k | _ => 0)
let some u := unit | return Except.ok <| f pr
let lit := toExpr <| Sat.Literal.ofInt u
let nlit := toExpr <| Sat.Literal.ofInt (-u)
let d1 := depth-1
let app := mkApp3 (mkConst ``Sat.Valuation.by_cases) (v d1) nlit <|
mkLambda `h default (mkApp2 (mkConst ``Sat.Valuation.neg) (v d1) lit) pr
let dom := mkApp2 (mkConst ``Sat.Valuation.neg) (v d1) nlit
f := fun e ↦ f <| mkApp app <| mkLambda `h default dom e
lctx := lctx.insert (-u) depth
return Except.error s!"no refutation: {ns}, {pf}, {lctx.toList}"
/-- An LRAT step is either an addition or a deletion step. -/
inductive LRATStep
| /-- An addition step, with the clause ID, the clause literal list, and the proof trace -/
add (id : Nat) (lits : Array Int) (proof : Array Int) : LRATStep
| /-- A (multiple) deletion step, which deletes all the listed clause IDs from the context -/
del (ids : Array Nat) : LRATStep
/-- Build the main proof of `⊢ ctx.proof []` using the LRAT proof trace.
* `arr`: The input CNF
* `ctx`: The abbreviated formula, a constant like `foo.ctx_1`
* `ctx'`: The definitional expansion of the formula, a tree of `Fmla.and` nodes
* `steps`: The input LRAT proof trace
-/
partial def buildProof (arr : Array (Array Int)) (ctx ctx' : Expr)
(steps : Array LRATStep) : MetaM Expr := do
let p := mkApp (mkConst ``Sat.Fmla.subsumes_self) ctx
let mut db := (buildClauses arr ctx 0 arr.size ctx' p default).2
for step in steps do
match step with
| LRATStep.del ds => db := ds.foldl (·.erase ·) db
| LRATStep.add i ns pf =>
let e := buildClause ns
match buildProofStep db ns pf ctx e with
| Except.ok proof =>
if ns.isEmpty then return proof
db := db.insert i { lits := ns, expr := e, proof }
| Except.error msg => throwError msg
throwError "failed to prove empty clause"
/-- Build the type and value of the reified theorem. This rewrites all the SAT definitions
into standard operators on `Prop`, for example if the formula is `[[1, 2], [-1, 2], [-2]]` then
this produces a proof of `⊢ ∀ a b : Prop, (a ∧ b) ∨ (¬a ∧ b) ∨ ¬b`. We use the input `nvars` to
decide how many quantifiers to use.
Most of the proof is under `2 * nvars + 1` quantifiers
`a1 .. an : Prop, v : Valuation, h1 : v 0 ↔ a1, ... hn : v (n-1) ↔ an ⊢ ...`, and we do the index
arithmetic by hand.
1. First, we call `reifyFormula ctx'` which returns `a` and `pr : reify v ctx' a`
2. Then we build `fun (v : Valuation) (h1 : v 0 ↔ a1) ... (hn : v (n-1) ↔ an) ↦ pr`
3. We have to lower expression `a` from step 1 out of the quantifiers by lowering all variable
indices by `nvars+1`. This is okay because `v` and `h1..hn` do not appear in `a`.
4. We construct the expression `ps`, which is `a1 .. an : Prop ⊢ [a1, ..., an] : List Prop`
5. `refute ctx (hf : ctx.proof []) (fun v h1 .. hn ↦ pr) : a` forces some definitional unfolding
since `fun h1 .. hn ↦ pr` should have type `implies v (reify v ctx a) [a1, ..., an] a`,
which involves unfolding `implies` n times as well as `ctx ↦ ctx'`.
6. Finally, we `intro a1 ... an` so that we have a proof of `∀ a1 ... an, a`.
-/
partial def buildReify (ctx ctx' proof : Expr) (nvars : Nat) : Expr × Expr := Id.run do
let (e, pr) := reifyFmla ctx'
let mut pr := pr
for i in [0:nvars] do
let j := nvars-i-1
let ty := mkApp2 (mkConst ``Iff) (mkApp (mkBVar j) (mkRawNatLit j)) (mkBVar nvars)
pr := mkLambda `h default ty pr
pr := mkLambda `v default (mkConst ``Sat.Valuation) pr
let mut e := e.lowerLooseBVars (nvars+1) (nvars+1)
let cons := mkApp (mkConst ``List.cons [levelZero]) (mkSort levelZero)
let nil := mkApp (mkConst ``List.nil [levelZero]) (mkSort levelZero)
let rec mkPS depth e
| 0 => e
| n + 1 => mkPS (depth+1) (mkApp2 cons (mkBVar depth) e) n
pr := mkApp5 (mkConst ``Sat.Fmla.refute) e (mkPS 0 nil nvars) ctx proof pr
for _ in [0:nvars] do
e := mkForall `a default (mkSort levelZero) e
pr := mkLambda `a default (mkSort levelZero) pr
pure (e, pr)
where
/-- The `v` variable under the `a1 ... an, v, h1 ... hn` context -/
v := mkBVar nvars
/-- Returns `a` and `pr : reify v f a` given a formula `f` -/
reifyFmla f :=
match f.getAppFn.constName! with
| ``Sat.Fmla.and =>
let f₁ := f.appFn!.appArg!
let f₂ := f.appArg!
let (e₁, h₁) := reifyFmla f₁
let (e₂, h₂) := reifyFmla f₂
(mkApp2 (mkConst ``Or) e₁ e₂, mkApp7 (mkConst ``Sat.Fmla.reify_or) v f₁ e₁ f₂ e₂ h₁ h₂)
| ``Sat.Fmla.one =>
let c := f.appArg!
let (e, h) := reifyClause c
(e, mkApp4 (mkConst ``Sat.Fmla.reify_one) v c e h)
| _ => panic! "not a valid formula"
/-- Returns `a` and `pr : reify v c a` given a clause `c` -/
reifyClause c :=
if c.appFn!.isConst then
(mkConst ``True, mkApp (mkConst ``Sat.Clause.reify_zero) v)
else reifyClause1 c
/-- Returns `a` and `pr : reify v c a` given a nonempty clause `c` -/
reifyClause1 c :=
let l := c.appFn!.appArg!
let c := c.appArg!
let (e₁, h₁) := reifyLiteral l
if c.isConst then
(e₁, mkApp4 (mkConst ``Sat.Clause.reify_one) v l e₁ h₁)
else
let (e₂, h₂) := reifyClause1 c
(mkApp2 (mkConst ``And) e₁ e₂, mkApp7 (mkConst ``Sat.Clause.reify_and) v l e₁ c e₂ h₁ h₂)
/-- Returns `a` and `pr : reify v l a` given a literal `c` -/
reifyLiteral l :=
let n := l.appArg!
let (e, h) := reifyVar n
match l.appFn!.constName! with
| ``Sat.Literal.pos =>
(mkApp (mkConst ``Not) e, mkApp4 (mkConst ``Sat.Literal.reify_pos) v e n h)
| ``Sat.Literal.neg =>
(e, mkApp4 (mkConst ``Sat.Literal.reify_neg) v e n h)
| _ => panic! "not a valid literal"
/-- Returns `a` and `pr : v n ↔ a` given a variable index `n`.
These are both lookups into the context
`(a0 .. a(n-1) : Prop) (v) (h1 : v 0 ↔ a0) ... (hn : v (n-1) ↔ a(n-1))`. -/
reifyVar v :=
let n := v.rawNatLit?.get!
(mkBVar (2 * nvars - n), mkBVar (nvars - n - 1))
open Lean
namespace Parser
open Lean Std.Internal.Parsec String
/-- Parse a natural number -/
def parseNat : String.Parser Nat := Json.Parser.natMaybeZero
/-- Parse an integer -/
def parseInt : String.Parser Int := do
if (← peek!) = '-' then skip; pure <| -(← parseNat) else parseNat
/-- Parse a list of integers terminated by 0 -/
partial def parseInts (arr : Array Int := #[]) : String.Parser (Array Int) := do
match ← parseInt <* ws with
| 0 => pure arr
| n => parseInts (arr.push n)
/-- Parse a list of natural numbers terminated by 0 -/
partial def parseNats (arr : Array Nat := #[]) : String.Parser (Array Nat) := do
match ← parseNat <* ws with
| 0 => pure arr
| n => parseNats (arr.push n)
/-- Parse a DIMACS format `.cnf` file.
This is not very robust; we assume the file has had comments stripped. -/
def parseDimacs : String.Parser (Nat × Array (Array Int)) := do
pstring "p cnf" *> ws
let nvars ← parseNat <* ws
let nclauses ← parseNat <* ws
let mut clauses := Array.mkEmpty nclauses
for _ in [:nclauses] do
clauses := clauses.push (← parseInts)
pure (nvars, clauses)
/-- Parse an LRAT file into a list of steps. -/
def parseLRAT : String.Parser (Array LRATStep) := many do
let step ← parseNat <* ws
if (← peek!) = 'd' then skip <* ws; pure <| LRATStep.del (← parseNats)
else ws; pure <| LRATStep.add step (← parseInts) (← parseInts)
end Parser
open Std.Internal
/-- Core of `fromLRAT`. Constructs the context and main proof definitions,
but not the reification theorem. Returns:
* `nvars`: the number of variables specified in the CNF file
* `ctx`: The abbreviated formula, a constant like `foo.ctx_1`
* `ctx'`: The definitional expansion of the formula, a tree of `Fmla.and` nodes
* `proof`: A proof of `ctx.proof []`
-/
def fromLRATAux (cnf lrat : String) (name : Name) : MetaM (Nat × Expr × Expr × Expr) := do
let Parsec.ParseResult.success _ (nvars, arr) := Parser.parseDimacs cnf.mkIterator
| throwError "parse CNF failed"
if arr.isEmpty then throwError "empty CNF"
let ctx' := buildConj arr 0 arr.size
let ctxName ← mkAuxDeclName (name ++ `ctx)
addDecl <| Declaration.defnDecl {
name := ctxName
levelParams := []
type := mkConst ``Sat.Fmla
value := ctx'
hints := ReducibilityHints.regular 0
safety := DefinitionSafety.safe
}
let ctx := mkConst ctxName
let Parsec.ParseResult.success _ steps := Parser.parseLRAT lrat.mkIterator
| throwError "parse LRAT failed"
let proof ← buildProof arr ctx ctx' steps
let declName ← mkAuxDeclName (name ++ `proof)
addDecl <| Declaration.thmDecl {
name := declName
levelParams := []
type := mkApp2 (mkConst ``Sat.Fmla.proof) ctx (buildClause #[])
value := proof
}
return (nvars, ctx, ctx', mkConst declName)
/-- Main entry point. Given strings `cnf` and `lrat` with unparsed file data, and a name `name`,
adds `theorem name : type := proof` where `type` is a propositional theorem like
`∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1`.
Also creates auxiliaries named `name.ctx_1` (for the CNF formula)
and `name.proof_1` (for the LRAT proof), with `name` itself containing the reification proof. -/
def fromLRAT (cnf lrat : String) (name : Name) : MetaM Unit := do
let (nvars, ctx, ctx', proof) ← fromLRATAux cnf lrat name
let (type, value) := buildReify ctx ctx' proof nvars
addDecl <| Declaration.thmDecl { name, levelParams := [], type, value }
open Elab Term
/--
A macro for producing SAT proofs from CNF / LRAT files.
These files are commonly used in the SAT community for writing proofs.
The input to the `lrat_proof` command is the name of the theorem to define,
and the statement (written in CNF format) and the proof (in LRAT format).
For example:
```
lrat_proof foo
"p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0"
"5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
```
produces a theorem:
```
foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1
```
* You can see the theorem statement by hovering over the word `foo`.
* You can use the `example` keyword in place of `foo` to avoid generating a theorem.
* You can use the `include_str` macro in place of the two strings
to load CNF / LRAT files from disk.
-/
elab "lrat_proof " n:(ident <|> "example")
ppSpace cnf:term:max ppSpace lrat:term:max : command => do
let name := (← getCurrNamespace) ++ if n.1.isIdent then n.1.getId else `_example
Command.liftTermElabM do
let cnf ← unsafe evalTerm String (mkConst ``String) cnf
let lrat ← unsafe evalTerm String (mkConst ``String) lrat
let go := do
fromLRAT cnf lrat name
withSaveInfoContext do
Term.addTermInfo' n (mkConst name) (isBinder := true)
if n.1.isIdent then go else withoutModifyingEnv go
lrat_proof example
-- The CNF file
"p cnf 2 4
1 2 0
-1 2 0
1 -2 0
-1 -2 0"
-- The LRAT file
"5 -2 0 4 3 0
5 d 3 4 0
6 1 0 5 1 0
6 d 1 0
7 0 5 2 6 0"
-- lrat_proof full2
-- (include_str "full2.cnf")
-- (include_str "full2.lrat")
/--
A macro for producing SAT proofs from CNF / LRAT files.
These files are commonly used in the SAT community for writing proofs.
The input to the `from_lrat` term syntax is two string expressions with
the statement (written in CNF format) and the proof (in LRAT format).
For example:
```
def foo := from_lrat
"p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0"
"5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
```
produces a theorem:
```
foo : ∀ (a a_1 : Prop), (¬a ∧ ¬a_1 ∨ a ∧ ¬a_1) ∨ ¬a ∧ a_1 ∨ a ∧ a_1
```
* You can use this term after `have :=` or in `def foo :=` to produce the term
without constraining the type.
* You can use it when a specific type is expected, but it currently does not
pay any attention to the shape of the goal and always produces the same theorem,
so you can only use this to do alpha renaming.
* You can use the `include_str` macro in place of the two strings
to load CNF / LRAT files from disk.
-/
elab "from_lrat " cnf:term:max ppSpace lrat:term:max : term => do
let cnf ← unsafe evalTerm String (mkConst ``String) cnf
let lrat ← unsafe evalTerm String (mkConst ``String) lrat
let name ← mkAuxName `lrat
fromLRAT cnf lrat name
return mkConst name
example : ∀ (a b : Prop), (¬a ∧ ¬b ∨ a ∧ ¬b) ∨ ¬a ∧ b ∨ a ∧ b := from_lrat
"p cnf 2 4 1 2 0 -1 2 0 1 -2 0 -1 -2 0"
"5 -2 0 4 3 0 5 d 3 4 0 6 1 0 5 1 0 6 d 1 0 7 0 5 2 6 0"
end Sat
end Mathlib.Tactic
|
Defs.lean
|
/-
Copyright (c) 2021 Chris Birkbeck. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Birkbeck
-/
import Mathlib.LinearAlgebra.Matrix.NonsingularInverse
import Mathlib.LinearAlgebra.Matrix.SpecialLinearGroup
import Mathlib.LinearAlgebra.GeneralLinearGroup
import Mathlib.Algebra.Ring.Subring.Units
/-!
# The General Linear group $GL(n, R)$
This file defines the elements of the General Linear group `Matrix.GeneralLinearGroup n R`,
consisting of all invertible `n` by `n` `R`-matrices.
## Main definitions
* `Matrix.GeneralLinearGroup` is the type of matrices over R which are units in the matrix ring.
* `Matrix.GLPos` gives the subgroup of matrices with
positive determinant (over a linear ordered ring).
## Tags
matrix group, group, matrix inverse
-/
namespace Matrix
universe u v
open Matrix
open LinearMap
-- disable this instance so we do not accidentally use it in lemmas.
attribute [-instance] SpecialLinearGroup.instCoeFun
/-- `GL n R` is the group of `n` by `n` `R`-matrices with unit determinant.
Defined as a subtype of matrices -/
abbrev GeneralLinearGroup (n : Type u) (R : Type v) [DecidableEq n] [Fintype n] [CommRing R] :
Type _ :=
(Matrix n n R)ˣ
@[inherit_doc] notation "GL" => GeneralLinearGroup
namespace GeneralLinearGroup
variable {n : Type u} [DecidableEq n] [Fintype n] {R : Type v} [CommRing R]
section CoeFnInstance
instance instCoeFun : CoeFun (GL n R) fun _ => n → n → R where
coe A := (A : Matrix n n R)
end CoeFnInstance
/-- The determinant of a unit matrix is itself a unit. -/
@[simps]
def det : GL n R →* Rˣ where
toFun A :=
{ val := (↑A : Matrix n n R).det
inv := (↑A⁻¹ : Matrix n n R).det
val_inv := by rw [← det_mul, A.mul_inv, det_one]
inv_val := by rw [← det_mul, A.inv_mul, det_one] }
map_one' := Units.ext det_one
map_mul' _ _ := Units.ext <| det_mul _ _
lemma det_ne_zero [Nontrivial R] (g : GL n R) : g.val.det ≠ 0 :=
g.det.ne_zero
/-- The groups `GL n R` (notation for `Matrix.GeneralLinearGroup n R`) and
`LinearMap.GeneralLinearGroup R (n → R)` are multiplicatively equivalent -/
def toLin : GL n R ≃* LinearMap.GeneralLinearGroup R (n → R) :=
Units.mapEquiv toLinAlgEquiv'.toMulEquiv
/-- Given a matrix with invertible determinant, we get an element of `GL n R`. -/
@[simps! val]
def mk' (A : Matrix n n R) (_ : Invertible (Matrix.det A)) : GL n R :=
unitOfDetInvertible A
/-- Given a matrix with unit determinant, we get an element of `GL n R`. -/
@[simps! val]
noncomputable def mk'' (A : Matrix n n R) (h : IsUnit (Matrix.det A)) : GL n R :=
nonsingInvUnit A h
/-- Given a matrix with non-zero determinant over a field, we get an element of `GL n K`. -/
@[simps! val]
def mkOfDetNeZero {K : Type*} [Field K] (A : Matrix n n K) (h : Matrix.det A ≠ 0) : GL n K :=
mk' A (invertibleOfNonzero h)
theorem ext_iff (A B : GL n R) : A = B ↔ ∀ i j, (A : Matrix n n R) i j = (B : Matrix n n R) i j :=
Units.ext_iff.trans Matrix.ext_iff.symm
/-- Not marked `@[ext]` as the `ext` tactic already solves this. -/
theorem ext ⦃A B : GL n R⦄ (h : ∀ i j, (A : Matrix n n R) i j = (B : Matrix n n R) i j) : A = B :=
Units.ext <| Matrix.ext h
section CoeLemmas
variable (A B : GL n R)
@[simp]
theorem coe_mul : ↑(A * B) = (↑A : Matrix n n R) * (↑B : Matrix n n R) :=
rfl
@[simp]
theorem coe_one : ↑(1 : GL n R) = (1 : Matrix n n R) :=
rfl
theorem coe_inv : ↑A⁻¹ = (↑A : Matrix n n R)⁻¹ :=
letI := A.invertible
invOf_eq_nonsing_inv (↑A : Matrix n n R)
@[simp]
theorem coe_toLin : (toLin A : (n → R) →ₗ[R] n → R) = Matrix.mulVecLin A :=
rfl
@[simp]
theorem toLin_apply (v : n → R) : (toLin A : _ → n → R) v = Matrix.mulVecLin A v :=
rfl
end CoeLemmas
variable {S T : Type*} [CommRing S] [CommRing T]
/-- A ring homomorphism ``f : R →+* S`` induces a homomorphism ``GLₙ(f) : GLₙ(R) →* GLₙ(S)``. -/
@[simps! apply_val]
def map (f : R →+* S) : GL n R →* GL n S := Units.map <| (RingHom.mapMatrix f).toMonoidHom
@[simp]
theorem map_id : map (RingHom.id R) = MonoidHom.id (GL n R) :=
rfl
@[simp]
protected lemma map_apply (f : R →+* S) (i j : n) (g : GL n R) : map f g i j = f (g i j) := by
rfl
@[simp]
theorem map_comp (f : T →+* R) (g : R →+* S) :
map (g.comp f) = (map g).comp (map (n := n) f) :=
rfl
@[simp]
theorem map_comp_apply (f : T →+* R) (g : R →+* S) (x : GL n T) :
(map g).comp (map f) x = map g (map f x) :=
rfl
variable (f : R →+* S)
@[simp]
protected lemma map_one : map f (1 : GL n R) = 1 := by
ext
simp only [map_one, Units.val_one]
protected lemma map_mul (g h : GL n R) : map f (g * h) = map f g * map f h := by
ext
simp only [map_mul, Units.val_mul]
protected lemma map_inv (g : GL n R) : map f g⁻¹ = (map f g)⁻¹ := by
ext
simp only [map_inv, coe_units_inv]
protected lemma map_det (g : GL n R) : Matrix.GeneralLinearGroup.det (map f g) =
Units.map f (Matrix.GeneralLinearGroup.det g) := by
ext
simp only [map,
Matrix.GeneralLinearGroup.val_det_apply, Units.coe_map, MonoidHom.coe_coe]
exact Eq.symm (RingHom.map_det f g.1)
lemma map_mul_map_inv (g : GL n R) : map f g * map f g⁻¹ = 1 := by
simp only [map_inv, mul_inv_cancel]
lemma map_inv_mul_map (g : GL n R) : map f g⁻¹ * map f g = 1 := by
simp only [map_inv, inv_mul_cancel]
@[simp]
lemma coe_map_mul_map_inv (g : GL n R) : g.val.map f * g.val⁻¹.map f = 1 := by
rw [← Matrix.map_mul]
simp only [isUnits_det_units, mul_nonsing_inv, map_zero, map_one, Matrix.map_one]
@[simp]
lemma coe_map_inv_mul_map (g : GL n R) : g.val⁻¹.map f * g.val.map f = 1 := by
rw [← Matrix.map_mul]
simp only [isUnits_det_units, nonsing_inv_mul, map_zero, map_one, Matrix.map_one]
end GeneralLinearGroup
namespace SpecialLinearGroup
variable {n : Type u} [DecidableEq n] [Fintype n] {R : Type v} [CommRing R]
{S : Type*} [CommRing S] [Algebra R S]
/-- `toGL` is the map from the special linear group to the general linear group. -/
def toGL : Matrix.SpecialLinearGroup n R →* Matrix.GeneralLinearGroup n R where
toFun A := ⟨↑A, ↑A⁻¹, congr_arg (·.1) (mul_inv_cancel A), congr_arg (·.1) (inv_mul_cancel A)⟩
map_one' := Units.ext rfl
map_mul' _ _ := Units.ext rfl
instance hasCoeToGeneralLinearGroup : Coe (SpecialLinearGroup n R) (GL n R) :=
⟨toGL⟩
lemma toGL_injective :
Function.Injective (toGL : SpecialLinearGroup n R → GL n R) := fun g g' ↦ by
simpa [toGL] using fun h _ ↦ Subtype.ext h
@[simp]
lemma toGL_inj (g g' : SpecialLinearGroup n R) :
(g : GeneralLinearGroup n R) = g' ↔ g = g' :=
toGL_injective.eq_iff
@[simp]
theorem coeToGL_det (g : SpecialLinearGroup n R) :
Matrix.GeneralLinearGroup.det (g : GL n R) = 1 :=
Units.ext g.prop
@[simp]
lemma coe_GL_coe_matrix (g : SpecialLinearGroup n R) : ((toGL g) : Matrix n n R) = g := rfl
variable (S) in
/-- `mapGL` is the map from the special linear group over `R` to the general linear group over
`S`, where `S` is an `R`-algebra. -/
def mapGL : Matrix.SpecialLinearGroup n R →* Matrix.GeneralLinearGroup n S :=
toGL.comp (map (algebraMap R S))
@[simp]
lemma mapGL_inj [FaithfulSMul R S] (g g' : SpecialLinearGroup n R) :
mapGL S g = mapGL S g' ↔ g = g' := by
refine ⟨fun h ↦ ?_, by tauto⟩
apply SpecialLinearGroup.ext
simpa [mapGL, toGL_inj, ext_iff, (FaithfulSMul.algebraMap_injective R S).eq_iff] using h
lemma mapGL_injective [FaithfulSMul R S] :
Function.Injective (mapGL (R := R) (n := n) S) :=
fun a b ↦ by simp
@[simp]
lemma mapGL_coe_matrix (g : SpecialLinearGroup n R) :
((mapGL S g) : Matrix n n S) = g.map (algebraMap R S) :=
rfl
end SpecialLinearGroup
section
variable {n : Type u} {R : Type v} [DecidableEq n] [Fintype n]
[CommRing R] [LinearOrder R] [IsStrictOrderedRing R]
section
variable (n R)
/-- This is the subgroup of `nxn` matrices with entries over a
linear ordered ring and positive determinant. -/
def GLPos : Subgroup (GL n R) :=
(Units.posSubgroup R).comap GeneralLinearGroup.det
@[inherit_doc] scoped[MatrixGroups] notation "GL(" n ", " R ")" "⁺" => GLPos (Fin n) R
end
@[simp]
theorem mem_glpos (A : GL n R) : A ∈ GLPos n R ↔ 0 < (Matrix.GeneralLinearGroup.det A : R) :=
Iff.rfl
theorem GLPos.det_ne_zero (A : GLPos n R) : ((A : GL n R) : Matrix n n R).det ≠ 0 :=
ne_of_gt A.prop
end
section Neg
variable {n : Type u} {R : Type v} [DecidableEq n] [Fintype n]
[CommRing R] [LinearOrder R] [IsStrictOrderedRing R]
[Fact (Even (Fintype.card n))]
/-- Formal operation of negation on general linear group on even cardinality `n` given by negating
each element. -/
instance : Neg (GLPos n R) :=
⟨fun g =>
⟨-g, by
rw [mem_glpos, GeneralLinearGroup.val_det_apply, Units.val_neg, det_neg,
(Fact.out (p := Even <| Fintype.card n)).neg_one_pow, one_mul]
exact g.prop⟩⟩
@[simp]
theorem GLPos.coe_neg_GL (g : GLPos n R) : ↑(-g) = -(g : GL n R) :=
rfl
@[simp]
theorem GLPos.coe_neg (g : GLPos n R) : (↑(-g) : GL n R) = -((g : GL n R) : Matrix n n R) :=
rfl
@[simp]
theorem GLPos.coe_neg_apply (g : GLPos n R) (i j : n) :
((↑(-g) : GL n R) : Matrix n n R) i j = -((g : GL n R) : Matrix n n R) i j :=
rfl
instance : HasDistribNeg (GLPos n R) :=
Subtype.coe_injective.hasDistribNeg _ GLPos.coe_neg_GL (GLPos n R).coe_mul
end Neg
namespace SpecialLinearGroup
variable {n : Type u} [DecidableEq n] [Fintype n]
{R : Type v} [CommRing R] [LinearOrder R] [IsStrictOrderedRing R]
/-- `Matrix.SpecialLinearGroup n R` embeds into `GL_pos n R` -/
def toGLPos : SpecialLinearGroup n R →* GLPos n R where
toFun A := ⟨(A : GL n R), show 0 < (↑A : Matrix n n R).det from A.prop.symm ▸ zero_lt_one⟩
map_one' := Subtype.ext <| Units.ext <| rfl
map_mul' _ _ := Subtype.ext <| Units.ext <| rfl
instance : Coe (SpecialLinearGroup n R) (GLPos n R) :=
⟨toGLPos⟩
theorem toGLPos_injective : Function.Injective (toGLPos : SpecialLinearGroup n R → GLPos n R) :=
-- Porting note: had to rewrite this to hint the correct types to Lean
-- (It can't find the coercion GLPos n R → Matrix n n R)
Function.Injective.of_comp
(f := fun (A : GLPos n R) ↦ ((A : GL n R) : Matrix n n R))
Subtype.coe_injective
/-- Coercing a `Matrix.SpecialLinearGroup` via `GL_pos` and `GL` is the same as coercing straight to
a matrix. -/
@[simp]
theorem coe_GLPos_coe_GL_coe_matrix (g : SpecialLinearGroup n R) :
(↑(↑(↑g : GLPos n R) : GL n R) : Matrix n n R) = ↑g :=
rfl
@[simp]
theorem coe_to_GLPos_to_GL_det (g : SpecialLinearGroup n R) :
Matrix.GeneralLinearGroup.det ((g : GLPos n R) : GL n R) = 1 :=
Units.ext g.prop
variable [Fact (Even (Fintype.card n))]
@[norm_cast]
theorem coe_GLPos_neg (g : SpecialLinearGroup n R) : ↑(-g) = -(↑g : GLPos n R) :=
Subtype.ext <| Units.ext rfl
end SpecialLinearGroup
end Matrix
|
Basic.lean
|
/-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Yury Kudryashov, Joseph Myers, Heather Macbeth, Kim Morrison, Yaël Dillies
-/
import Mathlib.Algebra.GroupWithZero.Action.Units
import Mathlib.Algebra.Module.End
import Mathlib.Algebra.NoZeroSMulDivisors.Defs
/-!
# `NoZeroSMulDivisors`
This file defines the `NoZeroSMulDivisors` class, and includes some tests
for the vanishing of elements (especially in modules over division rings).
-/
assert_not_exists Multiset Set.indicator Pi.single_smul₀ Field
section NoZeroSMulDivisors
variable {R M : Type*}
section Module
section Nat
theorem Nat.noZeroSMulDivisors
(R) (M) [Semiring R] [CharZero R] [AddCommMonoid M] [Module R M] [NoZeroSMulDivisors R M] :
NoZeroSMulDivisors ℕ M where
eq_zero_or_eq_zero_of_smul_eq_zero {c x} := by rw [← Nat.cast_smul_eq_nsmul R, smul_eq_zero]; simp
theorem two_nsmul_eq_zero
(R) (M) [Semiring R] [CharZero R] [AddCommMonoid M] [Module R M] [NoZeroSMulDivisors R M]
{v : M} : 2 • v = 0 ↔ v = 0 := by
haveI := Nat.noZeroSMulDivisors R M
simp [smul_eq_zero]
end Nat
variable [Semiring R]
variable (R M)
/-- If `M` is an `R`-module with one and `M` has characteristic zero, then `R` has characteristic
zero as well. Usually `M` is an `R`-algebra. -/
theorem CharZero.of_module (M) [AddCommMonoidWithOne M] [CharZero M] [Module R M] : CharZero R := by
refine ⟨fun m n h => @Nat.cast_injective M _ _ _ _ ?_⟩
rw [← nsmul_one, ← nsmul_one, ← Nat.cast_smul_eq_nsmul R, ← Nat.cast_smul_eq_nsmul R, h]
end Module
section AddCommGroup
-- `R` can still be a semiring here
variable [Semiring R] [AddCommGroup M] [Module R M]
section SMulInjective
variable (M) in
theorem smul_right_injective [NoZeroSMulDivisors R M] {c : R} (hc : c ≠ 0) :
Function.Injective (c • · : M → M) :=
(injective_iff_map_eq_zero (smulAddHom R M c)).2 fun _ ha => (smul_eq_zero.mp ha).resolve_left hc
theorem smul_right_inj [NoZeroSMulDivisors R M] {c : R} (hc : c ≠ 0) {x y : M} :
c • x = c • y ↔ x = y :=
(smul_right_injective M hc).eq_iff
end SMulInjective
section Nat
theorem self_eq_neg
(R) (M) [Semiring R] [CharZero R] [AddCommGroup M] [Module R M] [NoZeroSMulDivisors R M]
{v : M} : v = -v ↔ v = 0 := by
rw [← two_nsmul_eq_zero R M, two_smul, add_eq_zero_iff_eq_neg]
theorem neg_eq_self
(R) (M) [Semiring R] [CharZero R] [AddCommGroup M] [Module R M] [NoZeroSMulDivisors R M]
{v : M} : -v = v ↔ v = 0 := by
rw [eq_comm, self_eq_neg R M]
theorem self_ne_neg
(R) (M) [Semiring R] [CharZero R] [AddCommGroup M] [Module R M] [NoZeroSMulDivisors R M]
{v : M} : v ≠ -v ↔ v ≠ 0 :=
(self_eq_neg R M).not
theorem neg_ne_self
(R) (M) [Semiring R] [CharZero R] [AddCommGroup M] [Module R M] [NoZeroSMulDivisors R M]
{v : M} : -v ≠ v ↔ v ≠ 0 :=
(neg_eq_self R M).not
end Nat
end AddCommGroup
section Module
variable [Ring R] [AddCommGroup M] [Module R M]
section SMulInjective
variable (R)
variable [NoZeroSMulDivisors R M]
theorem smul_left_injective {x : M} (hx : x ≠ 0) : Function.Injective fun c : R => c • x :=
fun c d h =>
sub_eq_zero.mp
((smul_eq_zero.mp
(calc
(c - d) • x = c • x - d • x := sub_smul c d x
_ = 0 := sub_eq_zero.mpr h
)).resolve_right
hx)
end SMulInjective
instance [NoZeroSMulDivisors ℤ M] : NoZeroSMulDivisors ℕ M :=
⟨fun {c x} hcx ↦ by rwa [← Nat.cast_smul_eq_nsmul ℤ, smul_eq_zero, Nat.cast_eq_zero] at hcx⟩
variable (R M)
theorem NoZeroSMulDivisors.int_of_charZero
(R) (M) [Ring R] [AddCommGroup M] [Module R M] [NoZeroSMulDivisors R M] [CharZero R] :
NoZeroSMulDivisors ℤ M :=
⟨fun {z x} h ↦ by simpa [← smul_one_smul R z x] using h⟩
/-- Only a ring of characteristic zero can have a non-trivial module without additive or
scalar torsion. -/
theorem CharZero.of_noZeroSMulDivisors [Nontrivial M] [NoZeroSMulDivisors ℤ M] : CharZero R := by
refine ⟨fun {n m h} ↦ ?_⟩
obtain ⟨x, hx⟩ := exists_ne (0 : M)
replace h : (n : ℤ) • x = (m : ℤ) • x := by simp [← Nat.cast_smul_eq_nsmul R, h]
simpa using smul_left_injective ℤ hx h
instance [AddCommGroup M] [NoZeroSMulDivisors ℤ M] : NoZeroSMulDivisors ℕ M :=
⟨fun {c x} hcx ↦ by rwa [← Nat.cast_smul_eq_nsmul ℤ c x, smul_eq_zero, Nat.cast_eq_zero] at hcx⟩
end Module
section GroupWithZero
variable [GroupWithZero R] [AddMonoid M] [DistribMulAction R M]
-- see note [lower instance priority]
/-- This instance applies to `DivisionSemiring`s, in particular `NNReal` and `NNRat`. -/
instance (priority := 100) GroupWithZero.toNoZeroSMulDivisors : NoZeroSMulDivisors R M :=
⟨fun {a _} h ↦ or_iff_not_imp_left.2 fun ha ↦ (smul_eq_zero_iff_eq <| Units.mk0 a ha).1 h⟩
end GroupWithZero
end NoZeroSMulDivisors
|
center.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div.
From mathcomp Require Import fintype bigop finset fingroup morphism perm.
From mathcomp Require Import automorphism quotient action gproduct gfunctor.
From mathcomp Require Import cyclic.
(******************************************************************************)
(* Definition of the center of a group and of external central products: *)
(* 'Z(G) == the center of the group G, i.e., 'C_G(G). *)
(* cprod_by isoZ == the finGroupType for the central product of H and K *)
(* with centers identified by the isomorphism gz on 'Z(H); *)
(* here isoZ : isom 'Z(H) 'Z(K) gz. Note that the actual *)
(* central product is [set: cprod_by isoZ]. *)
(* cpairg1 isoZ == the isomorphism from H to cprod_by isoZ, isoZ as above. *)
(* cpair1g isoZ == the isomorphism from K to cprod_by isoZ, isoZ as above. *)
(* xcprod H K == the finGroupType for the external central product of H *)
(* and K with identified centers, provided the dynamically *)
(* tested condition 'Z(H) \isog 'Z(K) holds. *)
(* ncprod H n == the finGroupType for the central product of n copies of *)
(* H with their centers identified; [set: ncprod H 0] is *)
(* isomorphic to 'Z(H). *)
(* xcprodm cf eqf == the morphism induced on cprod_by isoZ, where as above *)
(* isoZ : isom 'Z(H) 'Z(K) gz, by fH : {morphism H >-> rT} *)
(* and fK : {morphism K >-> rT}, given both *)
(* cf : fH @* H \subset 'C(fK @* K) and *)
(* eqf : {in 'Z(H), fH =1 fK \o gz}. *)
(* Following Aschbacher, we only provide external central products with *)
(* identified centers, as these are well defined provided the local center *)
(* isomorphism group of one of the subgroups is full. Nevertheless the *)
(* entire construction could be carried out under the weaker assumption that *)
(* gz is an isomorphism between subgroups of 'Z(H) and 'Z(K), and even the *)
(* uniqueness theorem holds under the weaker assumption that gz map 'Z(H) to *)
(* a characteristic subgroup of 'Z(K) not isomorphic to any other subgroup of *)
(* 'Z(K), a condition that holds for example when K is cyclic, as in the *)
(* structure theorem for p-groups of symplectic type. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import GroupScope.
Section Defs.
Variable gT : finGroupType.
Definition center (A : {set gT}) := 'C_A(A).
Canonical center_group (G : {group gT}) : {group gT} :=
Eval hnf in [group of center G].
End Defs.
Arguments center {gT} A%_g.
Notation "''Z' ( A )" := (center A) : group_scope.
Notation "''Z' ( H )" := (center_group H) : Group_scope.
Lemma morphim_center : GFunctor.pcontinuous (@center).
Proof. by move=> gT rT G D f; apply: morphim_subcent. Qed.
Canonical center_igFun := [igFun by fun _ _ => subsetIl _ _ & morphim_center].
Canonical center_gFun := [gFun by morphim_center].
Canonical center_pgFun := [pgFun by morphim_center].
Section Center.
Variables gT : finGroupType.
Implicit Type rT : finGroupType.
Implicit Types (x y : gT) (A B : {set gT}) (G H K D : {group gT}).
Lemma subcentP A B x : reflect (x \in A /\ centralises x B) (x \in 'C_A(B)).
Proof.
rewrite inE. case: (x \in A); last by right; case.
by apply: (iffP centP) => [|[]].
Qed.
Lemma subcent_sub A B : 'C_A(B) \subset 'N_A(B).
Proof. by rewrite setIS ?cent_sub. Qed.
Lemma subcent_norm G B : 'N_G(B) \subset 'N('C_G(B)).
Proof. by rewrite normsI ?subIset ?normG // orbC cent_norm. Qed.
Lemma subcent_normal G B : 'C_G(B) <| 'N_G(B).
Proof. by rewrite /normal subcent_sub subcent_norm. Qed.
Lemma subcent_char G H K : H \char G -> K \char G -> 'C_H(K) \char G.
Proof.
case/charP=> sHG chHG /charP[sKG chKG]; apply/charP.
split=> [|f injf Gf]; first by rewrite subIset ?sHG.
by rewrite injm_subcent ?chHG ?chKG.
Qed.
Lemma centerP A x : reflect (x \in A /\ centralises x A) (x \in 'Z(A)).
Proof. exact: subcentP. Qed.
Lemma center_sub A : 'Z(A) \subset A.
Proof. exact: subsetIl. Qed.
Lemma center1 : 'Z(1) = 1 :> {set gT}.
Proof. exact: gF1. Qed.
Lemma centerC A : {in A, centralised 'Z(A)}.
Proof. by apply/centsP; rewrite centsC subsetIr. Qed.
Lemma center_normal G : 'Z(G) <| G.
Proof. exact: gFnormal. Qed.
Lemma sub_center_normal H G : H \subset 'Z(G) -> H <| G.
Proof. by rewrite subsetI centsC /normal => /andP[-> /cents_norm]. Qed.
Lemma center_abelian G : abelian 'Z(G).
Proof. by rewrite /abelian subIset // centsC subIset // subxx orbT. Qed.
Lemma center_char G : 'Z(G) \char G.
Proof. exact: gFchar. Qed.
Lemma center_idP A : reflect ('Z(A) = A) (abelian A).
Proof. exact: setIidPl. Qed.
Lemma center_class_formula G :
#|G| = #|'Z(G)| + \sum_(xG in [set x ^: G | x in G :\: 'C(G)]) #|xG|.
Proof.
by rewrite acts_sum_card_orbit ?cardsID // astabsJ normsD ?norms_cent ?normG.
Qed.
Lemma subcent1P A x y : reflect (y \in A /\ commute x y) (y \in 'C_A[x]).
Proof.
rewrite inE; case: (y \in A); last by right; case.
by apply: (iffP cent1P) => [|[]].
Qed.
Lemma subcent1_id x G : x \in G -> x \in 'C_G[x].
Proof. by move=> Gx; rewrite inE Gx; apply/cent1P. Qed.
Lemma subcent1_sub x G : 'C_G[x] \subset G.
Proof. exact: subsetIl. Qed.
Lemma subcent1C x y G : x \in G -> y \in 'C_G[x] -> x \in 'C_G[y].
Proof. by move=> Gx /subcent1P[_ cxy]; apply/subcent1P. Qed.
Lemma subcent1_cycle_sub x G : x \in G -> <[x]> \subset 'C_G[x].
Proof. by move=> Gx; rewrite cycle_subG ?subcent1_id. Qed.
Lemma subcent1_cycle_norm x G : 'C_G[x] \subset 'N(<[x]>).
Proof. by rewrite cents_norm // cent_gen cent_set1 subsetIr. Qed.
Lemma subcent1_cycle_normal x G : x \in G -> <[x]> <| 'C_G[x].
Proof.
by move=> Gx; rewrite /normal subcent1_cycle_norm subcent1_cycle_sub.
Qed.
(* Gorenstein. 1.3.4 *)
Lemma cyclic_center_factor_abelian G : cyclic (G / 'Z(G)) -> abelian G.
Proof.
case/cyclicP=> a Ga; case: (cosetP a) => /= z Nz def_a.
have G_Zz: G :=: 'Z(G) * <[z]>.
rewrite -quotientK ?cycle_subG ?quotient_cycle //=.
by rewrite -def_a -Ga quotientGK // center_normal.
rewrite G_Zz abelianM cycle_abelian center_abelian centsC /= G_Zz.
by rewrite subIset ?centS ?orbT ?mulG_subr.
Qed.
Lemma cyclic_factor_abelian H G :
H \subset 'Z(G) -> cyclic (G / H) -> abelian G.
Proof.
move=> sHZ cycGH; apply: cyclic_center_factor_abelian.
have /andP[_ nHG]: H <| G := sub_center_normal sHZ.
have [f <-]:= homgP (homg_quotientS nHG (gFnorm _ G) sHZ).
exact: morphim_cyclic cycGH.
Qed.
Section Injm.
Variables (rT : finGroupType) (D : {group gT}) (f : {morphism D >-> rT}).
Hypothesis injf : 'injm f.
Lemma injm_center G : G \subset D -> f @* 'Z(G) = 'Z(f @* G).
Proof. exact: injm_subcent. Qed.
End Injm.
End Center.
Arguments center_idP {gT A}.
Lemma isog_center (aT rT : finGroupType) (G : {group aT}) (H : {group rT}) :
G \isog H -> 'Z(G) \isog 'Z(H).
Proof. exact: gFisog. Qed.
Section Product.
Variable gT : finGroupType.
Implicit Types (A B C : {set gT}) (G H K : {group gT}).
Lemma center_prod H K : K \subset 'C(H) -> 'Z(H) * 'Z(K) = 'Z(H * K).
Proof.
move=> cHK; apply/setP=> z; rewrite {3}/center centM !inE.
have cKH: H \subset 'C(K) by rewrite centsC.
apply/imset2P/and3P=> [[x y /setIP[Hx cHx] /setIP[Ky cKy] ->{z}]| []].
by rewrite imset2_f ?groupM // ?(subsetP cHK) ?(subsetP cKH).
case/imset2P=> x y Hx Ky ->{z}.
rewrite groupMr => [cHx|]; last exact: subsetP Ky.
rewrite groupMl => [cKy|]; last exact: subsetP Hx.
by exists x y; rewrite ?inE ?Hx ?Ky.
Qed.
Lemma center_cprod A B G : A \* B = G -> 'Z(A) \* 'Z(B) = 'Z(G).
Proof.
case/cprodP => [[H K -> ->] <- cHK].
rewrite cprodE ?center_prod //= subIset ?(subset_trans cHK) //.
by rewrite centS ?center_sub.
Qed.
Lemma center_bigcprod I r P (F : I -> {set gT}) G :
\big[cprod/1]_(i <- r | P i) F i = G ->
\big[cprod/1]_(i <- r | P i) 'Z(F i) = 'Z(G).
Proof.
elim/big_ind2: _ G => [_ <-|A B C D IHA IHB G dG|_ _ G ->]; rewrite ?center1 //.
case/cprodP: dG IHA IHB (dG) => [[H K -> ->] _ _] IHH IHK dG.
by rewrite (IHH H) // (IHK K) // (center_cprod dG).
Qed.
Lemma cprod_center_id G : G \* 'Z(G) = G.
Proof. by rewrite cprodE ?subsetIr // mulGSid ?center_sub. Qed.
Lemma center_dprod A B G : A \x B = G -> 'Z(A) \x 'Z(B) = 'Z(G).
Proof.
case/dprodP=> [[H1 H2 -> ->] defG cH12 trH12].
move: defG; rewrite -cprodE // => /center_cprod/cprodP[_ /= <- cZ12].
by apply: dprodE; rewrite //= setIAC setIA -setIA trH12 (setIidPl _) ?sub1G.
Qed.
Lemma center_bigdprod I r P (F: I -> {set gT}) G :
\big[dprod/1]_(i <- r | P i) F i = G ->
\big[dprod/1]_(i <- r | P i) 'Z(F i) = 'Z(G).
Proof.
elim/big_ind2: _ G => [_ <-|A B C D IHA IHB G dG|_ _ G ->]; rewrite ?center1 //.
case/dprodP: dG IHA IHB (dG) => [[H K -> ->] _ _ _] IHH IHK dG.
by rewrite (IHH H) // (IHK K) // (center_dprod dG).
Qed.
Lemma Aut_cprod_full G H K :
H \* K = G -> 'Z(H) = 'Z(K) ->
Aut_in (Aut H) 'Z(H) \isog Aut 'Z(H) ->
Aut_in (Aut K) 'Z(K) \isog Aut 'Z(K) ->
Aut_in (Aut G) 'Z(G) \isog Aut 'Z(G).
Proof.
move=> defG eqZHK; have [_ defHK cHK] := cprodP defG.
have defZ: 'Z(G) = 'Z(H) by rewrite -defHK -center_prod // eqZHK mulGid.
have ziHK: H :&: K = 'Z(K).
by apply/eqP; rewrite eqEsubset subsetI -{1 2}eqZHK !center_sub setIS.
have AutZP := Aut_sub_fullP (@center_sub gT _).
move/AutZP=> AutZHfull /AutZP AutZKfull; apply/AutZP=> g injg gZ.
have [gH [def_gH ker_gH _ im_gH]] := domP g defZ.
have [gK [def_gK ker_gK _ im_gK]] := domP g (etrans defZ eqZHK).
have [injgH injgK]: 'injm gH /\ 'injm gK by rewrite ker_gH ker_gK.
have [gHH gKK]: gH @* 'Z(H) = 'Z(H) /\ gK @* 'Z(K) = 'Z(K).
by rewrite im_gH im_gK -eqZHK -defZ.
have [|fH [injfH im_fH fHZ]] := AutZHfull gH injgH.
by rewrite im_gH /= -defZ.
have [|fK [injfK im_fK fKZ]] := AutZKfull gK injgK.
by rewrite im_gK /= -eqZHK -defZ.
have cfHK: fK @* K \subset 'C(fH @* H) by rewrite im_fH im_fK.
have eq_fHK: {in H :&: K, fH =1 fK}.
by move=> z; rewrite ziHK => Zz; rewrite fHZ ?fKZ /= ?eqZHK // def_gH def_gK.
exists (cprodm_morphism defG cfHK eq_fHK).
rewrite injm_cprodm injfH injfK im_cprodm im_fH im_fK defHK.
rewrite -morphimIdom ziHK -eqZHK injm_center // im_fH eqxx.
split=> //= z; rewrite {1}defZ => Zz; have [Hz _] := setIP Zz.
by rewrite cprodmEl // fHZ // def_gH.
Qed.
End Product.
Section CprodBy.
Variables gTH gTK : finGroupType.
Variables (H : {group gTH}) (K : {group gTK}) (gz : {morphism 'Z(H) >-> gTK}).
Definition ker_cprod_by of isom 'Z(H) 'Z(K) gz :=
[set xy | let: (x, y) := xy in (x \in 'Z(H)) && (y == (gz x)^-1)].
Hypothesis isoZ : isom 'Z(H) 'Z(K) gz.
Let kerHK := ker_cprod_by isoZ.
Let injgz : 'injm gz. Proof. by case/isomP: isoZ. Qed.
Let gzZ : gz @* 'Z(H) = 'Z(K). Proof. by case/isomP: isoZ. Qed.
Let gzZchar : gz @* 'Z(H) \char 'Z(K). Proof. by rewrite gzZ. Qed.
Let sgzZZ : gz @* 'Z(H) \subset 'Z(K) := char_sub gzZchar.
Let sZH := center_sub H.
Let sZK := center_sub K.
Let sgzZG : gz @* 'Z(H) \subset K := subset_trans sgzZZ sZK.
Lemma ker_cprod_by_is_group : group_set kerHK.
Proof.
apply/group_setP; rewrite inE /= group1 morph1 invg1 /=.
split=> // [[x1 y1] [x2 y2]].
rewrite inE /= => /andP[Zx1 /eqP->]; have [_ cGx1] := setIP Zx1.
rewrite inE /= => /andP[Zx2 /eqP->]; have [Gx2 _] := setIP Zx2.
by rewrite inE /= groupM //= -invMg (centP cGx1) // morphM.
Qed.
Canonical ker_cprod_by_group := Group ker_cprod_by_is_group.
Lemma ker_cprod_by_central : kerHK \subset 'Z(setX H K).
Proof.
rewrite -(center_dprod (setX_dprod H K)) -morphim_pairg1 -morphim_pair1g.
rewrite -!injm_center ?subsetT ?injm_pair1g ?injm_pairg1 //=.
rewrite morphim_pairg1 morphim_pair1g setX_dprod.
apply/subsetP=> [[x y]] /[1!inE] /andP[Zx /eqP->].
by rewrite inE /= Zx groupV (subsetP sgzZZ) ?mem_morphim.
Qed.
Fact cprod_by_key : unit. Proof. by []. Qed.
Definition cprod_by_def : finGroupType := subg_of (setX H K / kerHK).
Definition cprod_by := locked_with cprod_by_key cprod_by_def.
Local Notation C := [set: FinGroup.sort cprod_by].
(*FIXME : Check if we need arg_sort instead of sort*)
Definition in_cprod : gTH * gTK -> cprod_by :=
let: tt as k := cprod_by_key return _ -> locked_with k cprod_by_def in
subg _ \o coset kerHK.
Lemma in_cprodM : {in setX H K &, {morph in_cprod : u v / u * v}}.
Proof.
rewrite /in_cprod /cprod_by; case: cprod_by_key => /= u v Gu Gv.
have nkerHKG := normal_norm (sub_center_normal ker_cprod_by_central).
by rewrite -!morphM ?mem_quotient // (subsetP nkerHKG).
Qed.
Canonical in_cprod_morphism := Morphism in_cprodM.
Lemma ker_in_cprod : 'ker in_cprod = kerHK.
Proof.
transitivity ('ker (subg [group of setX H K / kerHK] \o coset kerHK)).
rewrite /ker /morphpre /= /in_cprod /cprod_by; case: cprod_by_key => /=.
by rewrite ['N(_) :&: _]quotientGK ?sub_center_normal ?ker_cprod_by_central.
by rewrite ker_comp ker_subg -kerE ker_coset.
Qed.
Lemma cpairg1_dom : H \subset 'dom (in_cprod \o @pairg1 gTH gTK).
Proof. by rewrite -sub_morphim_pre ?subsetT // morphim_pairg1 setXS ?sub1G. Qed.
Lemma cpair1g_dom : K \subset 'dom (in_cprod \o @pair1g gTH gTK).
Proof. by rewrite -sub_morphim_pre ?subsetT // morphim_pair1g setXS ?sub1G. Qed.
Definition cpairg1 := tag (restrmP _ cpairg1_dom).
Definition cpair1g := tag (restrmP _ cpair1g_dom).
Local Notation CH := (mfun cpairg1 @* gval H).
Local Notation CK := (mfun cpair1g @* gval K).
Lemma injm_cpairg1 : 'injm cpairg1.
Proof.
rewrite /cpairg1; case: restrmP => _ [_ -> _ _].
rewrite ker_comp ker_in_cprod; apply/subsetP=> x; rewrite !inE /=.
by case/and3P=> _ Zx; rewrite eq_sym (inv_eq invgK) invg1 morph_injm_eq1.
Qed.
Let injH := injm_cpairg1.
Lemma injm_cpair1g : 'injm cpair1g.
Proof.
rewrite /cpair1g; case: restrmP => _ [_ -> _ _].
rewrite ker_comp ker_in_cprod; apply/subsetP=> y; rewrite !inE /= morph1 invg1.
by case/and3P.
Qed.
Let injK := injm_cpair1g.
Lemma im_cpair_cent : CK \subset 'C(CH).
Proof.
rewrite /cpairg1 /cpair1g; do 2!case: restrmP => _ [_ _ _ -> //].
rewrite !morphim_comp morphim_cents // morphim_pair1g morphim_pairg1.
by case/dprodP: (setX_dprod H K).
Qed.
Hint Resolve im_cpair_cent : core.
Lemma im_cpair : CH * CK = C.
Proof.
rewrite /cpairg1 /cpair1g; do 2!case: restrmP => _ [_ _ _ -> //].
rewrite !morphim_comp -morphimMl morphim_pairg1 ?setXS ?sub1G //.
rewrite morphim_pair1g setX_prod morphimEdom /= /in_cprod /cprod_by.
by case: cprod_by_key; rewrite /= imset_comp imset_coset -morphimEdom im_subg.
Qed.
Lemma im_cpair_cprod : CH \* CK = C. Proof. by rewrite cprodE ?im_cpair. Qed.
Lemma eq_cpairZ : {in 'Z(H), cpairg1 =1 cpair1g \o gz}.
Proof.
rewrite /cpairg1 /cpair1g => z1 Zz1; set z2 := gz z1.
have Zz2: z2 \in 'Z(K) by rewrite (subsetP sgzZZ) ?mem_morphim.
have [[Gz1 _] [/= Gz2 _]]:= (setIP Zz1, setIP Zz2).
do 2![case: restrmP => f /= [df _ _ _]; rewrite {f}df].
apply/rcoset_kerP; rewrite ?inE ?group1 ?andbT //.
by rewrite ker_in_cprod mem_rcoset inE /= invg1 mulg1 mul1g Zz1 /=.
Qed.
Lemma setI_im_cpair : CH :&: CK = 'Z(CH).
Proof.
apply/eqP; rewrite eqEsubset setIS //=.
rewrite subsetI center_sub -injm_center //.
rewrite (eq_in_morphim _ eq_cpairZ); first by rewrite morphim_comp morphimS.
by rewrite !(setIidPr _) // -sub_morphim_pre.
Qed.
Lemma cpair1g_center : cpair1g @* 'Z(K) = 'Z(C).
Proof.
case/cprodP: (center_cprod im_cpair_cprod) => _ <- _.
by rewrite injm_center // -setI_im_cpair mulSGid //= setIC setIS 1?centsC.
Qed.
(* Uses gzZ. *)
Lemma cpair_center_id : 'Z(CH) = 'Z(CK).
Proof.
rewrite -!injm_center // -gzZ -morphim_comp; apply: eq_in_morphim eq_cpairZ.
by rewrite !(setIidPr _) // -sub_morphim_pre.
Qed.
(* Uses gzZ. *)
Lemma cpairg1_center : cpairg1 @* 'Z(H) = 'Z(C).
Proof. by rewrite -cpair1g_center !injm_center // cpair_center_id. Qed.
Section ExtCprodm.
Variable rT : finGroupType.
Variables (fH : {morphism H >-> rT}) (fK : {morphism K >-> rT}).
Hypothesis cfHK : fK @* K \subset 'C(fH @* H).
Hypothesis eq_fHK : {in 'Z(H), fH =1 fK \o gz}.
Let gH := ifactm fH injm_cpairg1.
Let gK := ifactm fK injm_cpair1g.
Lemma xcprodm_cent : gK @* CK \subset 'C(gH @* CH).
Proof. by rewrite !im_ifactm. Qed.
Lemma xcprodmI : {in CH :&: CK, gH =1 gK}.
Proof.
rewrite setI_im_cpair -injm_center // => fHx; case/morphimP=> x Gx Zx ->{fHx}.
by rewrite {2}eq_cpairZ //= ?ifactmE ?eq_fHK //= (subsetP sgzZG) ?mem_morphim.
Qed.
Definition xcprodm := cprodm im_cpair_cprod xcprodm_cent xcprodmI.
Canonical xcprod_morphism := [morphism of xcprodm].
Lemma xcprodmEl : {in H, forall x, xcprodm (cpairg1 x) = fH x}.
Proof. by move=> x Hx; rewrite /xcprodm cprodmEl ?mem_morphim ?ifactmE. Qed.
Lemma xcprodmEr : {in K, forall y, xcprodm (cpair1g y) = fK y}.
Proof. by move=> y Ky; rewrite /xcprodm cprodmEr ?mem_morphim ?ifactmE. Qed.
Lemma xcprodmE :
{in H & K, forall x y, xcprodm (cpairg1 x * cpair1g y) = fH x * fK y}.
Proof.
by move=> x y Hx Ky; rewrite /xcprodm cprodmE ?mem_morphim ?ifactmE.
Qed.
Lemma im_xcprodm : xcprodm @* C = fH @* H * fK @* K.
Proof. by rewrite -im_cpair morphim_cprodm // !im_ifactm. Qed.
Lemma im_xcprodml A : xcprodm @* (cpairg1 @* A) = fH @* A.
Proof.
rewrite -!(morphimIdom _ A) morphim_cprodml ?morphimS ?subsetIl //.
by rewrite morphim_ifactm ?subsetIl.
Qed.
Lemma im_xcprodmr A : xcprodm @* (cpair1g @* A) = fK @* A.
Proof.
rewrite -!(morphimIdom _ A) morphim_cprodmr ?morphimS ?subsetIl //.
by rewrite morphim_ifactm ?subsetIl.
Qed.
Lemma injm_xcprodm : 'injm xcprodm = 'injm fH && 'injm fK.
Proof.
rewrite injm_cprodm !ker_ifactm !subG1 !morphim_injm_eq1 ?subsetIl // -!subG1.
apply: andb_id2l => /= injfH; apply: andb_idr => _.
rewrite !im_ifactm // -(morphimIdom gH) setI_im_cpair -injm_center //.
rewrite morphim_ifactm // eqEsubset subsetI morphimS //=.
rewrite {1}injm_center // setIS //=.
rewrite (eq_in_morphim _ eq_fHK); first by rewrite morphim_comp morphimS.
by rewrite !(setIidPr _) // -sub_morphim_pre.
Qed.
End ExtCprodm.
(* Uses gzZchar. *)
Lemma Aut_cprod_by_full :
Aut_in (Aut H) 'Z(H) \isog Aut 'Z(H) ->
Aut_in (Aut K) 'Z(K) \isog Aut 'Z(K) ->
Aut_in (Aut C) 'Z(C) \isog Aut 'Z(C).
Proof.
move=> AutZinH AutZinK.
have Cfull:= Aut_cprod_full im_cpair_cprod cpair_center_id.
by rewrite Cfull // -injm_center // injm_Aut_full ?center_sub.
Qed.
Section Isomorphism.
Let gzZ_lone (Y : {group gTK}) :
Y \subset 'Z(K) -> gz @* 'Z(H) \isog Y -> gz @* 'Z(H) = Y.
Proof.
move=> sYZ isoY; apply/eqP.
by rewrite eq_sym eqEcard (card_isog isoY) gzZ sYZ /=.
Qed.
Variables (rT : finGroupType) (GH GK G : {group rT}).
Hypotheses (defG : GH \* GK = G) (ziGHK : GH :&: GK = 'Z(GH)).
Hypothesis AutZHfull : Aut_in (Aut H) 'Z(H) \isog Aut 'Z(H).
Hypotheses (isoGH : GH \isog H) (isoGK : GK \isog K).
(* Uses gzZ_lone *)
Lemma cprod_by_uniq :
exists f : {morphism G >-> cprod_by},
[/\ isom G C f, f @* GH = CH & f @* GK = CK].
Proof.
have [_ defGHK cGKH] := cprodP defG.
have AutZinH := Aut_sub_fullP sZH AutZHfull.
have [fH injfH defGH]:= isogP (isog_symr isoGH).
have [fK injfK defGK]:= isogP (isog_symr isoGK).
have sfHZfK: fH @* 'Z(H) \subset fK @* K.
by rewrite injm_center //= defGH defGK -ziGHK subsetIr.
have gzZ_id: gz @* 'Z(H) = invm injfK @* (fH @* 'Z(H)).
apply: gzZ_lone => /=.
rewrite injm_center // defGH -ziGHK sub_morphim_pre /= ?defGK ?subsetIr //.
by rewrite setIC morphpre_invm injm_center // defGK setIS 1?centsC.
rewrite -morphim_comp.
apply: isog_trans (sub_isog _ _); first by rewrite isog_sym sub_isog.
by rewrite -sub_morphim_pre.
by rewrite !injm_comp ?injm_invm.
have: 'dom (invm injfH \o fK \o gz) = 'Z(H).
rewrite /dom /= -(morphpreIdom gz); apply/setIidPl.
by rewrite -2?sub_morphim_pre // gzZ_id morphim_invmE morphpreK ?morphimS.
case/domP=> gzH [def_gzH ker_gzH _ im_gzH].
have{ker_gzH} injgzH: 'injm gzH by rewrite ker_gzH !injm_comp ?injm_invm.
have{AutZinH} [|gH [injgH gH_H def_gH]] := AutZinH _ injgzH.
by rewrite im_gzH !morphim_comp /= gzZ_id !morphim_invmE morphpreK ?injmK.
have: 'dom (fH \o gH) = H by rewrite /dom /= -{3}gH_H injmK.
case/domP=> gfH [def_gfH ker_gfH _ im_gfH].
have{im_gfH} gfH_H: gfH @* H = GH by rewrite im_gfH morphim_comp gH_H.
have cgfHfK: fK @* K \subset 'C(gfH @* H) by rewrite gfH_H defGK.
have eq_gfHK: {in 'Z(H), gfH =1 fK \o gz}.
move=> z Zz; rewrite def_gfH /= def_gH //= def_gzH /= invmK //.
have {Zz}: gz z \in gz @* 'Z(H) by rewrite mem_morphim.
rewrite gzZ_id morphim_invmE; case/morphpreP=> _.
exact: (subsetP (morphimS _ _)).
pose f := xcprodm cgfHfK eq_gfHK.
have injf: 'injm f by rewrite injm_xcprodm ker_gfH injm_comp.
have fCH: f @* CH = GH by rewrite im_xcprodml gfH_H.
have fCK: f @* CK = GK by rewrite im_xcprodmr defGK.
have fC: f @* C = G by rewrite im_xcprodm gfH_H defGK defGHK.
have [f' [_ ker_f' _ im_f']] := domP (invm_morphism injf) fC.
exists f'; rewrite -fCH -fCK !{1}im_f' !{1}morphim_invm ?subsetT //.
by split=> //; apply/isomP; rewrite ker_f' injm_invm im_f' -fC im_invm.
Qed.
Lemma isog_cprod_by : G \isog C.
Proof. by have [f [isoG _ _]] := cprod_by_uniq; apply: isom_isog isoG. Qed.
End Isomorphism.
End CprodBy.
Section ExtCprod.
Import finfun.
Variables gTH gTK : finGroupType.
Variables (H : {group gTH}) (K : {group gTK}).
Let gt_ b := if b then gTK else gTH.
Local Notation isob := ('Z(H) \isog 'Z(K)) (only parsing).
Let G_ b := if b as b' return {group gt_ b'} then K else H.
Lemma xcprod_subproof :
{gz : {morphism 'Z(H) >-> gt_ isob} | isom 'Z(H) 'Z(G_ isob) gz}.
Proof.
case: (pickP [pred f : {ffun _} | misom 'Z(H) 'Z(K) f]) => [f isoZ | no_f].
rewrite (misom_isog isoZ); case/andP: isoZ => fM isoZ.
by exists [morphism of morphm fM].
move/pred0P: no_f => not_isoZ; rewrite [isob](congr1 negb not_isoZ).
by exists (idm_morphism _); apply/isomP; rewrite injm_idm im_idm.
Qed.
Definition xcprod := cprod_by (svalP xcprod_subproof).
Inductive xcprod_spec : finGroupType -> Prop :=
XcprodSpec gz isoZ : xcprod_spec (@cprod_by gTH gTK H K gz isoZ).
Lemma xcprodP : 'Z(H) \isog 'Z(K) -> xcprod_spec xcprod.
Proof. by rewrite /xcprod => isoZ; move: xcprod_subproof; rewrite isoZ. Qed.
Lemma isog_xcprod (rT : finGroupType) (GH GK G : {group rT}) :
Aut_in (Aut H) 'Z(H) \isog Aut 'Z(H) ->
GH \isog H -> GK \isog K -> GH \* GK = G -> 'Z(GH) = 'Z(GK) ->
G \isog [set: xcprod].
Proof.
move=> AutZinH isoGH isoGK defG eqZGHK; have [_ _ cGHK] := cprodP defG.
have [|gz isoZ] := xcprodP.
have [[fH injfH <-] [fK injfK <-]] := (isogP isoGH, isogP isoGK).
rewrite -!injm_center -?(isog_transl _ (sub_isog _ _)) ?center_sub //=.
by rewrite eqZGHK sub_isog ?center_sub.
rewrite (isog_cprod_by _ defG) //.
by apply/eqP; rewrite eqEsubset setIS // subsetI {2}eqZGHK !center_sub.
Qed.
End ExtCprod.
Section IterCprod.
Variables (gT : finGroupType) (G : {group gT}).
Fixpoint ncprod_def n : finGroupType :=
if n is n'.+1 then xcprod G [set: ncprod_def n']
else subg_of 'Z(G).
Fact ncprod_key : unit. Proof. by []. Qed.
Definition ncprod := locked_with ncprod_key ncprod_def.
Local Notation G_ n := [set: gsort (ncprod n)].
Lemma ncprod0 : G_ 0 \isog 'Z(G).
Proof. by rewrite [ncprod]unlock isog_sym isog_subg. Qed.
Lemma center_ncprod0 : 'Z(G_ 0) = G_ 0.
Proof. by apply: center_idP; rewrite (isog_abelian ncprod0) center_abelian. Qed.
Lemma center_ncprod n : 'Z(G_ n) \isog 'Z(G).
Proof.
elim: n => [|n]; first by rewrite center_ncprod0 ncprod0.
rewrite [ncprod]unlock=> /isog_symr/xcprodP[gz isoZ] /=.
by rewrite -cpairg1_center isog_sym sub_isog ?center_sub ?injm_cpairg1.
Qed.
Lemma ncprodS n : xcprod_spec G [set: ncprod n] (ncprod n.+1).
Proof.
by have:= xcprodP (isog_symr (center_ncprod n)); rewrite [ncprod]unlock.
Qed.
Lemma ncprod1 : G_ 1 \isog G.
Proof.
case: ncprodS => gz isoZ; rewrite isog_sym /= -im_cpair.
rewrite mulGSid /=; first by rewrite sub_isog ?injm_cpairg1.
rewrite -{3}center_ncprod0 injm_center ?injm_cpair1g //.
by rewrite -cpair_center_id center_sub.
Qed.
Lemma Aut_ncprod_full n :
Aut_in (Aut G) 'Z(G) \isog Aut 'Z(G) ->
Aut_in (Aut (G_ n)) 'Z(G_ n) \isog Aut 'Z(G_ n).
Proof.
move=> AutZinG; elim: n => [|n IHn].
by rewrite center_ncprod0; apply/Aut_sub_fullP=> // g injg gG0; exists g.
by case: ncprodS => gz isoZ; apply: Aut_cprod_by_full.
Qed.
End IterCprod.
|
Finite.lean
|
/-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import Mathlib.Analysis.SpecialFunctions.Pow.Real
import Mathlib.LinearAlgebra.FreeModule.PID
import Mathlib.LinearAlgebra.Matrix.AbsoluteValue
import Mathlib.NumberTheory.ClassNumber.AdmissibleAbsoluteValue
import Mathlib.RingTheory.ClassGroup
import Mathlib.RingTheory.DedekindDomain.IntegralClosure
import Mathlib.RingTheory.Norm.Basic
/-!
# Class numbers of global fields
In this file, we use the notion of "admissible absolute value" to prove
finiteness of the class group for number fields and function fields.
## Main definitions
- `ClassGroup.fintypeOfAdmissibleOfAlgebraic`: if `R` has an admissible absolute value,
its integral closure has a finite class group
-/
open Module Ring
open scoped nonZeroDivisors
namespace ClassGroup
section EuclideanDomain
variable {R S : Type*} (K L : Type*) [EuclideanDomain R] [CommRing S] [IsDomain S]
variable [Field K] [Field L]
variable [Algebra R K] [IsFractionRing R K]
variable [Algebra K L] [FiniteDimensional K L] [Algebra.IsSeparable K L]
variable [algRL : Algebra R L] [IsScalarTower R K L]
variable [Algebra R S] [Algebra S L]
variable [ist : IsScalarTower R S L]
variable (abv : AbsoluteValue R ℤ)
variable {ι : Type*} [DecidableEq ι] [Fintype ι] (bS : Basis ι R S)
/-- If `b` is an `R`-basis of `S` of cardinality `n`, then `normBound abv b` is an integer
such that for every `R`-integral element `a : S` with coordinates `≤ y`,
we have algebra.norm a ≤ norm_bound abv b * y ^ n`. (See also `norm_le` and `norm_lt`). -/
noncomputable def normBound : ℤ :=
let n := Fintype.card ι
let i : ι := Nonempty.some bS.index_nonempty
let m : ℤ :=
Finset.max'
(Finset.univ.image fun ijk : ι × ι × ι =>
abv (Algebra.leftMulMatrix bS (bS ijk.1) ijk.2.1 ijk.2.2))
⟨_, Finset.mem_image.mpr ⟨⟨i, i, i⟩, Finset.mem_univ _, rfl⟩⟩
Nat.factorial n • (n • m) ^ n
theorem normBound_pos : 0 < normBound abv bS := by
obtain ⟨i, j, k, hijk⟩ : ∃ i j k, Algebra.leftMulMatrix bS (bS i) j k ≠ 0 := by
by_contra! h
obtain ⟨i⟩ := bS.index_nonempty
apply bS.ne_zero i
apply
(injective_iff_map_eq_zero (Algebra.leftMulMatrix bS)).mp (Algebra.leftMulMatrix_injective bS)
ext j k
simp [h]
simp only [normBound, Algebra.smul_def, eq_natCast]
apply mul_pos (Int.natCast_pos.mpr (Nat.factorial_pos _))
refine pow_pos (mul_pos (Int.natCast_pos.mpr (Fintype.card_pos_iff.mpr ⟨i⟩)) ?_) _
refine lt_of_lt_of_le (abv.pos hijk) (Finset.le_max' _ _ ?_)
exact Finset.mem_image.mpr ⟨⟨i, j, k⟩, Finset.mem_univ _, rfl⟩
/-- If the `R`-integral element `a : S` has coordinates `≤ y` with respect to some basis `b`,
its norm is less than `normBound abv b * y ^ dim S`. -/
theorem norm_le (a : S) {y : ℤ} (hy : ∀ k, abv (bS.repr a k) ≤ y) :
abv (Algebra.norm R a) ≤ normBound abv bS * y ^ Fintype.card ι := by
conv_lhs => rw [← bS.sum_repr a]
rw [Algebra.norm_apply, ← LinearMap.det_toMatrix bS]
simp only [map_sum, map_smul, map_sum, map_smul,
normBound, smul_mul_assoc, ← mul_pow]
convert Matrix.det_sum_smul_le Finset.univ _ hy using 3
· rw [Finset.card_univ, smul_mul_assoc, mul_comm]
· intro i j k
apply Finset.le_max'
exact Finset.mem_image.mpr ⟨⟨i, j, k⟩, Finset.mem_univ _, rfl⟩
/-- If the `R`-integral element `a : S` has coordinates `< y` with respect to some basis `b`,
its norm is strictly less than `normBound abv b * y ^ dim S`. -/
theorem norm_lt {T : Type*} [Ring T] [LinearOrder T] [IsStrictOrderedRing T] (a : S) {y : T}
(hy : ∀ k, (abv (bS.repr a k) : T) < y) :
(abv (Algebra.norm R a) : T) < normBound abv bS * y ^ Fintype.card ι := by
obtain ⟨i⟩ := bS.index_nonempty
have him : (Finset.univ.image fun k => abv (bS.repr a k)).Nonempty :=
⟨_, Finset.mem_image.mpr ⟨i, Finset.mem_univ _, rfl⟩⟩
set y' : ℤ := Finset.max' _ him with y'_def
have hy' : ∀ k, abv (bS.repr a k) ≤ y' := by
intro k
exact @Finset.le_max' ℤ _ _ _ (Finset.mem_image.mpr ⟨k, Finset.mem_univ _, rfl⟩)
have : (y' : T) < y := by
rw [y'_def, ←
Finset.max'_image (show Monotone (_ : ℤ → T) from fun x y h => Int.cast_le.mpr h)]
apply (Finset.max'_lt_iff _ (him.image _)).mpr
simp only [Finset.mem_image]
rintro _ ⟨x, ⟨k, -, rfl⟩, rfl⟩
exact hy k
have y'_nonneg : 0 ≤ y' := le_trans (abv.nonneg _) (hy' i)
apply (Int.cast_le.mpr (norm_le abv bS a hy')).trans_lt
simp only [Int.cast_mul, Int.cast_pow]
apply mul_lt_mul' le_rfl
· exact pow_lt_pow_left₀ this (Int.cast_nonneg.mpr y'_nonneg) (@Fintype.card_ne_zero _ _ ⟨i⟩)
· exact pow_nonneg (Int.cast_nonneg.mpr y'_nonneg) _
· exact Int.cast_pos.mpr (normBound_pos abv bS)
/-- A nonzero ideal has an element of minimal norm. -/
theorem exists_min (I : (Ideal S)⁰) :
∃ b ∈ (I : Ideal S),
b ≠ 0 ∧ ∀ c ∈ (I : Ideal S), abv (Algebra.norm R c) < abv (Algebra.norm R b) → c =
(0 : S) := by
obtain ⟨_, ⟨b, b_mem, b_ne_zero, rfl⟩, min⟩ := @Int.exists_least_of_bdd
(fun a => ∃ b ∈ (I : Ideal S), b ≠ (0 : S) ∧ abv (Algebra.norm R b) = a)
(by
use 0
rintro _ ⟨b, _, _, rfl⟩
apply abv.nonneg)
(by
obtain ⟨b, b_mem, b_ne_zero⟩ := (I : Ideal S).ne_bot_iff.mp (nonZeroDivisors.coe_ne_zero I)
exact ⟨_, ⟨b, b_mem, b_ne_zero, rfl⟩⟩)
refine ⟨b, b_mem, b_ne_zero, ?_⟩
intro c hc lt
contrapose! lt with c_ne_zero
exact min _ ⟨c, hc, c_ne_zero, rfl⟩
section IsAdmissible
variable {abv}
variable (adm : abv.IsAdmissible)
/-- If we have a large enough set of elements in `R^ι`, then there will be a pair
whose remainders are close together. We'll show that all sets of cardinality
at least `cardM bS adm` elements satisfy this condition.
The value of `cardM` is not at all optimal: for specific choices of `R`,
the minimum cardinality can be exponentially smaller.
-/
noncomputable def cardM : ℕ :=
adm.card (normBound abv bS ^ (-1 / Fintype.card ι : ℝ)) ^ Fintype.card ι
variable [Infinite R]
/-- In the following results, we need a large set of distinct elements of `R`. -/
noncomputable def distinctElems : Fin (cardM bS adm).succ ↪ R :=
Fin.valEmbedding.trans (Infinite.natEmbedding R)
variable [DecidableEq R]
/-- `finsetApprox` is a finite set such that each fractional ideal in the integral closure
contains an element close to `finsetApprox`. -/
noncomputable def finsetApprox : Finset R :=
(Finset.univ.image fun xy : _ × _ => distinctElems bS adm xy.1 - distinctElems bS adm xy.2).erase
0
theorem finsetApprox.zero_notMem : (0 : R) ∉ finsetApprox bS adm :=
Finset.notMem_erase _ _
@[deprecated (since := "2025-05-23")] alias finsetApprox.zero_not_mem := finsetApprox.zero_notMem
@[simp]
theorem mem_finsetApprox {x : R} :
x ∈ finsetApprox bS adm ↔ ∃ i j, i ≠ j ∧ distinctElems bS adm i - distinctElems bS adm j =
x := by
simp only [finsetApprox, Finset.mem_erase, Finset.mem_image]
constructor
· rintro ⟨hx, ⟨i, j⟩, _, rfl⟩
refine ⟨i, j, ?_, rfl⟩
rintro rfl
simp at hx
· rintro ⟨i, j, hij, rfl⟩
refine ⟨?_, ⟨i, j⟩, Finset.mem_univ _, rfl⟩
rw [Ne, sub_eq_zero]
exact fun h => hij ((distinctElems bS adm).injective h)
section Real
open Real
attribute [-instance] Real.decidableEq
/-- We can approximate `a / b : L` with `q / r`, where `r` has finitely many options for `L`. -/
theorem exists_mem_finsetApprox (a : S) {b} (hb : b ≠ (0 : R)) :
∃ q : S,
∃ r ∈ finsetApprox bS adm, abv (Algebra.norm R (r • a - b • q)) <
abv (Algebra.norm R (algebraMap R S b)) := by
have dim_pos := Fintype.card_pos_iff.mpr bS.index_nonempty
set ε : ℝ := normBound abv bS ^ (-1 / Fintype.card ι : ℝ) with ε_eq
have hε : 0 < ε := Real.rpow_pos_of_pos (Int.cast_pos.mpr (normBound_pos abv bS)) _
have ε_le : (normBound abv bS : ℝ) * (abv b • ε) ^ (Fintype.card ι : ℝ)
≤ abv b ^ (Fintype.card ι : ℝ) := by
have := normBound_pos abv bS
have := abv.nonneg b
rw [ε_eq, Algebra.smul_def, eq_intCast, mul_rpow, ← rpow_mul, div_mul_cancel₀, rpow_neg_one,
mul_left_comm, mul_inv_cancel₀, mul_one, rpow_natCast] <;>
try norm_cast; omega
· exact Iff.mpr Int.cast_nonneg this
· linarith
set μ : Fin (cardM bS adm).succ ↪ R := distinctElems bS adm
let s : ι →₀ R := bS.repr a
have s_eq : ∀ i, s i = bS.repr a i := fun i => rfl
let qs : Fin (cardM bS adm).succ → ι → R := fun j i => μ j * s i / b
let rs : Fin (cardM bS adm).succ → ι → R := fun j i => μ j * s i % b
have r_eq : ∀ j i, rs j i = μ j * s i % b := fun i j => rfl
have μ_eq : ∀ i j, μ j * s i = b * qs j i + rs j i := by
intro i j
rw [r_eq, EuclideanDomain.div_add_mod]
have μ_mul_a_eq : ∀ j, μ j • a = b • ∑ i, qs j i • bS i + ∑ i, rs j i • bS i := by
intro j
rw [← bS.sum_repr a]
simp only [μ, qs, rs, Finset.smul_sum, ← Finset.sum_add_distrib]
refine Finset.sum_congr rfl fun i _ => ?_
rw [← s_eq, ← mul_smul, μ_eq, add_smul, mul_smul, ← μ_eq]
obtain ⟨j, k, j_ne_k, hjk⟩ := adm.exists_approx hε hb fun j i => μ j * s i
have hjk' : ∀ i, (abv (rs k i - rs j i) : ℝ) < abv b • ε := by simpa only [r_eq] using hjk
let q := ∑ i, (qs k i - qs j i) • bS i
set r := μ k - μ j with r_eq
refine ⟨q, r, (mem_finsetApprox bS adm).mpr ?_, ?_⟩
· exact ⟨k, j, j_ne_k.symm, rfl⟩
have : r • a - b • q = ∑ x : ι, (rs k x • bS x - rs j x • bS x) := by
simp only [q, r_eq, sub_smul, μ_mul_a_eq, Finset.smul_sum, ← Finset.sum_add_distrib,
← Finset.sum_sub_distrib, smul_sub]
refine Finset.sum_congr rfl fun x _ => ?_
ring
rw [this, Algebra.norm_algebraMap_of_basis bS, abv.map_pow]
refine Int.cast_lt.mp ((norm_lt abv bS _ fun i => lt_of_le_of_lt ?_ (hjk' i)).trans_le ?_)
· apply le_of_eq
congr
simp_rw [map_sum, map_sub, map_smul, Finset.sum_apply',
Finsupp.sub_apply, Finsupp.smul_apply, Finset.sum_sub_distrib, Basis.repr_self_apply,
smul_eq_mul, mul_boole, Finset.sum_ite_eq', Finset.mem_univ, if_true]
· exact mod_cast ε_le
/-- We can approximate `a / b : L` with `q / r`, where `r` has finitely many options for `L`. -/
theorem exists_mem_finset_approx' [Algebra.IsAlgebraic R S] (a : S) {b : S} (hb : b ≠ 0) :
∃ q : S,
∃ r ∈ finsetApprox bS adm, abv (Algebra.norm R (r • a - q * b)) < abv (Algebra.norm R b) := by
obtain ⟨a', b', hb', h⟩ := Algebra.IsAlgebraic.exists_smul_eq_mul R a hb
obtain ⟨q, r, hr, hqr⟩ := exists_mem_finsetApprox bS adm a' hb'
refine ⟨q, r, hr, ?_⟩
refine
lt_of_mul_lt_mul_left ?_ (show 0 ≤ abv (Algebra.norm R (algebraMap R S b')) from abv.nonneg _)
refine
lt_of_le_of_lt (le_of_eq ?_)
(mul_lt_mul hqr le_rfl (abv.pos ((Algebra.norm_ne_zero_iff_of_basis bS).mpr hb))
(abv.nonneg _))
rw [← abv.map_mul, ← MonoidHom.map_mul, ← abv.map_mul, ← MonoidHom.map_mul, ← Algebra.smul_def,
smul_sub b', sub_mul, smul_comm, h, mul_comm b a', Algebra.smul_mul_assoc r a' b,
Algebra.smul_mul_assoc b' q b]
end Real
theorem prod_finsetApprox_ne_zero : algebraMap R S (∏ m ∈ finsetApprox bS adm, m) ≠ 0 := by
refine mt ((injective_iff_map_eq_zero _).mp bS.algebraMap_injective _) ?_
simp only [Finset.prod_eq_zero_iff, not_exists]
rintro x ⟨hx, rfl⟩
exact finsetApprox.zero_notMem bS adm hx
theorem ne_bot_of_prod_finsetApprox_mem (J : Ideal S)
(h : algebraMap _ _ (∏ m ∈ finsetApprox bS adm, m) ∈ J) : J ≠ ⊥ :=
(Submodule.ne_bot_iff _).mpr ⟨_, h, prod_finsetApprox_ne_zero _ _⟩
/-- Each class in the class group contains an ideal `J`
such that `M := Π m ∈ finsetApprox` is in `J`. -/
theorem exists_mk0_eq_mk0 [IsDedekindDomain S] [Algebra.IsAlgebraic R S] (I : (Ideal S)⁰) :
∃ J : (Ideal S)⁰,
ClassGroup.mk0 I = ClassGroup.mk0 J ∧
algebraMap _ _ (∏ m ∈ finsetApprox bS adm, m) ∈ (J : Ideal S) := by
set M := ∏ m ∈ finsetApprox bS adm, m
have hM : algebraMap R S M ≠ 0 := prod_finsetApprox_ne_zero bS adm
obtain ⟨b, b_mem, b_ne_zero, b_min⟩ := exists_min abv I
suffices Ideal.span {b} ∣ Ideal.span {algebraMap _ _ M} * I.1 by
obtain ⟨J, hJ⟩ := this
refine ⟨⟨J, ?_⟩, ?_, ?_⟩
· rw [mem_nonZeroDivisors_iff_ne_zero]
rintro rfl
rw [Ideal.zero_eq_bot, Ideal.mul_bot] at hJ
exact hM (Ideal.span_singleton_eq_bot.mp (I.2.2 _ hJ))
· rw [ClassGroup.mk0_eq_mk0_iff]
exact ⟨algebraMap _ _ M, b, hM, b_ne_zero, hJ⟩
rw [← SetLike.mem_coe, ← Set.singleton_subset_iff, ← Ideal.span_le, ← Ideal.dvd_iff_le]
apply (mul_dvd_mul_iff_left _).mp _
swap; · exact mt Ideal.span_singleton_eq_bot.mp b_ne_zero
rw [Subtype.coe_mk, Ideal.dvd_iff_le, ← hJ, mul_comm]
apply Ideal.mul_mono le_rfl
rw [Ideal.span_le, Set.singleton_subset_iff]
exact b_mem
rw [Ideal.dvd_iff_le, Ideal.mul_le]
intro r' hr' a ha
rw [Ideal.mem_span_singleton] at hr' ⊢
obtain ⟨q, r, r_mem, lt⟩ := exists_mem_finset_approx' bS adm a b_ne_zero
apply @dvd_of_mul_left_dvd _ _ q
simp only [Algebra.smul_def] at lt
rw [←
sub_eq_zero.mp (b_min _ (I.1.sub_mem (I.1.mul_mem_left _ ha) (I.1.mul_mem_left _ b_mem)) lt)]
refine mul_dvd_mul_right (dvd_trans (map_dvd _ ?_) hr') _
exact Multiset.dvd_prod (Multiset.mem_map.mpr ⟨_, r_mem, rfl⟩)
/-- `ClassGroup.mkMMem` is a specialization of `ClassGroup.mk0` to (the finite set of)
ideals that contain `M := ∏ m ∈ finsetApprox L f abs, m`.
By showing this function is surjective, we prove that the class group is finite. -/
noncomputable def mkMMem [IsDedekindDomain S]
(J : { J : Ideal S // algebraMap _ _ (∏ m ∈ finsetApprox bS adm, m) ∈ J }) : ClassGroup S :=
ClassGroup.mk0
⟨J.1, mem_nonZeroDivisors_iff_ne_zero.mpr (ne_bot_of_prod_finsetApprox_mem bS adm J.1 J.2)⟩
theorem mkMMem_surjective [IsDedekindDomain S] [Algebra.IsAlgebraic R S] :
Function.Surjective (ClassGroup.mkMMem bS adm) := by
intro I'
obtain ⟨⟨I, hI⟩, rfl⟩ := ClassGroup.mk0_surjective I'
obtain ⟨J, mk0_eq_mk0, J_dvd⟩ := exists_mk0_eq_mk0 bS adm ⟨I, hI⟩
exact ⟨⟨J, J_dvd⟩, mk0_eq_mk0.symm⟩
open Classical in
/-- The **class number theorem**: the class group of an integral closure `S` of `R` in an
algebraic extension `L` is finite if there is an admissible absolute value.
See also `ClassGroup.fintypeOfAdmissibleOfFinite` where `L` is a finite
extension of `K = Frac(R)`, supplying most of the required assumptions automatically.
-/
noncomputable def fintypeOfAdmissibleOfAlgebraic [IsDedekindDomain S]
[Algebra.IsAlgebraic R S] : Fintype (ClassGroup S) :=
@Fintype.ofSurjective _ _ _
(@Fintype.ofEquiv _
{ J // J ∣ Ideal.span ({algebraMap R S (∏ m ∈ finsetApprox bS adm, m)} : Set S) }
(UniqueFactorizationMonoid.fintypeSubtypeDvd _
(by
rw [Ne, Ideal.zero_eq_bot, Ideal.span_singleton_eq_bot]
exact prod_finsetApprox_ne_zero bS adm))
((Equiv.refl _).subtypeEquiv fun I =>
Ideal.dvd_iff_le.trans (by
rw [Equiv.refl_apply, Ideal.span_le, Set.singleton_subset_iff]; rfl)))
(ClassGroup.mkMMem bS adm) (ClassGroup.mkMMem_surjective bS adm)
/-- The main theorem: the class group of an integral closure `S` of `R` in a
finite extension `L` of `K = Frac(R)` is finite if there is an admissible
absolute value.
See also `ClassGroup.fintypeOfAdmissibleOfAlgebraic` where `L` is an
algebraic extension of `R`, that includes some extra assumptions.
-/
noncomputable def fintypeOfAdmissibleOfFinite [IsIntegralClosure S R L] :
Fintype (ClassGroup S) := by
letI := Classical.decEq L
letI := IsIntegralClosure.isFractionRing_of_finite_extension R K L S
letI := IsIntegralClosure.isDedekindDomain R K L S
choose s b hb_int using FiniteDimensional.exists_is_basis_integral R K L
have : LinearIndependent R ((Algebra.traceForm K L).dualBasis
(traceForm_nondegenerate K L) b) := by
apply (Basis.linearIndependent _).restrict_scalars
simp only [Algebra.smul_def, mul_one]
apply IsFractionRing.injective
obtain ⟨n, b⟩ :=
Submodule.basisOfPidOfLESpan this (IsIntegralClosure.range_le_span_dualBasis S b hb_int)
let f : (S ⧸ LinearMap.ker (LinearMap.restrictScalars R (Algebra.linearMap S L))) ≃ₗ[R] S := by
rw [LinearMap.ker_eq_bot.mpr]
· exact Submodule.quotEquivOfEqBot _ rfl
· exact IsIntegralClosure.algebraMap_injective _ R _
let bS := b.map ((LinearMap.quotKerEquivRange _).symm ≪≫ₗ f)
have : Algebra.IsIntegral R S := IsIntegralClosure.isIntegral_algebra R L
exact fintypeOfAdmissibleOfAlgebraic bS adm
end IsAdmissible
end EuclideanDomain
end ClassGroup
|
qfpoly.v
|
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice.
From mathcomp Require Import fintype tuple div bigop binomial finset finfun.
From mathcomp Require Import ssralg countalg finalg poly polydiv qpoly perm.
From mathcomp Require Import fingroup falgebra fieldext finfield galois.
From mathcomp Require Import finalg zmodp matrix vector.
(******************************************************************************)
(* This file extends the algebras R[X]/<p> defined in qpoly with the field *)
(* when p is irreducible *)
(* It defines the new field on top of {qpoly p}. As irreducible is in general *)
(* decidable in general, this is done by giving a proof explicitly. *)
(* monic_irreducible_poly p == proof that p is monic and irreducible *)
(* {poly %/ p with mi} == defined as {poly %/ p} where mi is proof of *)
(* monic_irreducible_poly p *)
(* It also defines the discrete logarithm with a primitive polynomial on a *)
(* finite field *)
(* primitive_poly p == p is a primitive polynomial *)
(* qlogp q == is the discrete log of q where q is an element of *)
(* the quotient field with respect to a primitive *)
(* polynomial p *)
(* plogp p q == is the discrete log of q with respect to p in {poly F} *)
(* this makes only sense if p is a primitive polynomial of *)
(* size > 2 *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import GRing.Theory.
Import Pdiv.CommonRing.
Import Pdiv.RingMonic.
Import Pdiv.Field.
Import FinRing.Theory.
Local Open Scope ring_scope.
Reserved Notation "{ 'poly' '%/' p 'with' mi }"
(p at level 2, mi at level 10, format "{ 'poly' '%/' p 'with' mi }").
Section DomainDef.
Variable R : idomainType.
Variable h : {poly R}.
Definition monic_irreducible_poly (p : {poly R}) :=
((irreducible_poly p) * (p \is monic))%type.
Hypothesis hI : monic_irreducible_poly h.
Definition qfpoly : monic_irreducible_poly h -> predArgType :=
fun=> {poly %/ h}.
End DomainDef.
Notation "{ 'poly' '%/' p 'with' hi }" := (@qfpoly _ p hi).
Section iDomain.
Variable R : idomainType.
Variable h : {poly R}.
Hypothesis hI : monic_irreducible_poly h.
HB.instance Definition _ := GRing.NzRing.on {poly %/ h with hI}.
End iDomain.
Section finIDomain.
Variable R : finIdomainType.
Variable h : {poly R}.
Hypothesis hI : monic_irreducible_poly h.
HB.instance Definition _ := Finite.on {poly %/ h with hI}.
End finIDomain.
Section Field.
Variable R : fieldType.
Variable h : {poly R}.
Local Notation hQ := (mk_monic h).
Hypothesis hI : monic_irreducible_poly h.
HB.instance Definition _ := GRing.ComUnitRing.on {poly %/ h with hI}.
Lemma mk_monicE : mk_monic h = h.
Proof. by rewrite /mk_monic !hI. Qed.
Lemma coprimep_unit (p : {poly %/ h}) : p != 0%R -> coprimep hQ p.
Proof.
move=> pNZ.
rewrite irreducible_poly_coprime //; last first.
by case: hI; rewrite mk_monicE.
apply: contra pNZ => H; case: eqP => // /eqP /dvdp_leq /(_ H).
by rewrite leqNgt size_mk_monic.
Qed.
Lemma qpoly_mulVp (p : {poly %/ h}) : p != 0%R -> (qpoly_inv p * p = 1)%R.
Proof. by move=> pNZ; apply/qpoly_mulVz/coprimep_unit. Qed.
Lemma qpoly_inv0 : qpoly_inv 0%R = 0%R :> {poly %/ h}.
Proof.
rewrite /qpoly_inv /= coprimep0 -size_poly_eq1.
rewrite [in X in X == _]mk_monicE.
by have [[]] := hI; case: size => [|[]].
Qed.
HB.instance Definition _ := GRing.ComUnitRing_isField.Build {poly %/ h with hI}
coprimep_unit.
HB.instance Definition _ := GRing.UnitAlgebra.on {poly %/ h with hI}.
HB.instance Definition _ := Vector.on {poly %/ h with hI}.
End Field.
Section FinField.
Variable R : finFieldType.
Variable h : {poly R}.
Local Notation hQ := (mk_monic h).
HB.instance Definition _ := Finite.on {poly %/ h}.
Hypothesis hI : monic_irreducible_poly h.
HB.instance Definition _ := Finite.on {poly %/ h with hI}.
Lemma card_qfpoly : #|{poly %/ h with hI}| = #|R| ^ (size h).-1.
Proof. by rewrite card_monic_qpoly ?hI. Qed.
Lemma card_qfpoly_gt1 : 1 < #|{poly %/ h with hI}|.
Proof. by have := card_finNzRing_gt1 {poly %/ h with hI}. Qed.
End FinField.
Section inPoly.
Variable R : comNzRingType.
Variable h : {poly R}.
Lemma in_qpoly_comp_horner (p q : {poly R}) :
in_qpoly h (p \Po q) =
(map_poly (qpolyC h) p).[in_qpoly h q].
Proof.
have hQM := monic_mk_monic h.
rewrite comp_polyE /map_poly poly_def horner_sum /=.
apply: val_inj.
rewrite /= rmodp_sum // poly_of_qpoly_sum.
apply: eq_bigr => i _.
rewrite !hornerE /in_qpoly /=.
rewrite mul_polyC // !rmodpZ //=.
by rewrite poly_of_qpolyX /= rmodp_id // rmodpX // rmodp_id.
Qed.
Lemma map_poly_div_inj : injective (map_poly (qpolyC h)).
Proof.
apply: map_inj_poly => [x y /val_eqP /eqP /polyC_inj //|].
by rewrite qpolyC0.
Qed.
End inPoly.
Section finPoly.
(* Unfortunately we need some duplications so inference
propagates qfpoly :-( )*)
Definition qfpoly_const (R : idomainType) (h : {poly R})
(hMI : monic_irreducible_poly h) : R -> {poly %/ h with hMI} :=
qpolyC h.
Lemma map_fpoly_div_inj (R : idomainType) (h : {poly R})
(hMI : monic_irreducible_poly h) :
injective (map_poly (qfpoly_const hMI)).
Proof. by apply: (@map_poly_div_inj R h). Qed.
End finPoly.
Section Splitting.
Variable F : finFieldType.
Variable h : {poly F}.
Hypothesis hI : monic_irreducible_poly h.
Definition qfpoly_splitting_field_type :=
FinSplittingFieldType F {poly %/ h with hI}.
End Splitting.
Section PrimitivePoly.
Variable F : finFieldType.
Variable h : {poly F}.
Hypothesis sh_gt2 : 2 < size h.
Let sh_gt1 : 1 < size h.
Proof. by apply: leq_ltn_trans sh_gt2. Qed.
Definition primitive_poly (p: {poly F}) :=
let v := #|{poly %/ p}|.-1 in
[&& p \is monic,
irreducibleb p,
p %| 'X^v - 1 &
[forall n : 'I_v, (p %| 'X^n - 1) ==> (n == 0%N :> nat)]].
Lemma primitive_polyP (p : {poly F}) :
reflect
(let v := #|{poly %/ p}|.-1 in
[/\ monic_irreducible_poly p,
p %| 'X^v - 1 &
forall n, 0 < n < v -> ~~ (p %| 'X^n - 1)])
(primitive_poly p).
Proof.
apply: (iffP and4P) => [[H1 H2 H3 /forallP H4] v|[[H1 H2] H3 H4]]; split => //.
- by split => //; apply/irreducibleP.
- move=> n /andP[n_gt0 nLv]; apply/negP => /(implyP (H4 (Ordinal nLv))) /=.
by rewrite eqn0Ngt n_gt0.
- by apply/irreducibleP.
apply/forallP=> [] [[|n] Hn] /=; apply/implyP => pDX //.
by case/negP: (H4 n.+1 Hn).
Qed.
Hypothesis Hh : primitive_poly h.
Lemma primitive_mi : monic_irreducible_poly h.
Proof. by case/primitive_polyP: Hh. Qed.
Lemma primitive_poly_in_qpoly_eq0 p : (in_qpoly h p == 0) = (h %| p).
Proof.
have hM : h \is monic by case/and4P:Hh.
have hMi : monic_irreducible_poly h by apply: primitive_mi.
apply/eqP/idP => [/val_eqP /= | hDp].
by rewrite -Pdiv.IdomainMonic.modpE mk_monicE.
by apply/val_eqP; rewrite /= -Pdiv.IdomainMonic.modpE mk_monicE.
Qed.
Local Notation qT := {poly %/ h with primitive_mi}.
Lemma card_primitive_qpoly : #|{poly %/ h}|= #|F| ^ (size h).-1.
Proof. by rewrite card_monic_qpoly ?primitive_mi. Qed.
Lemma qX_neq0 : 'qX != 0 :> qT.
Proof.
apply/eqP => /val_eqP/=.
by rewrite [rmodp _ _]qpolyXE ?polyX_eq0 //; case: primitive_mi.
Qed.
Lemma qX_in_unit : ('qX : qT) \in GRing.unit.
Proof. by rewrite unitfE /= qX_neq0. Qed.
Definition gX : {unit qT} := FinRing.unit _ qX_in_unit.
Lemma dvdp_order n : (h %| 'X^n - 1) = (gX ^+ n == 1)%g.
Proof.
have [hM hI] := primitive_mi.
have eqr_add2r (r : nzRingType) (a b c : r) : (a + c == b + c) = (a == b).
by apply/eqP/eqP => [H|->//]; rewrite -(addrK c a) H addrK.
rewrite -val_eqE /= val_unitX /= -val_eqE /=.
rewrite (poly_of_qpolyX) qpolyXE // mk_monicE //.
rewrite -[in RHS](subrK 1 'X^n) rmodpD //.
rewrite [rmodp 1 h]rmodp_small ?size_poly1 //.
rewrite -[1%:P]add0r polyC1 /= eqr_add2r.
by rewrite dvdpE /=; apply/rmodp_eq0P/eqP.
Qed.
Lemma gX_order : #[gX]%g = (#|qT|).-1.
Proof.
have /primitive_polyP[Hp1 Hp2 Hp3] := Hh.
set n := _.-1 in Hp2 Hp3 *.
have n_gt0 : 0 < n by rewrite ltn_predRL card_qfpoly_gt1.
have [hM hI] := primitive_mi.
have gX_neq1 : gX != 1%g.
apply/eqP/val_eqP/eqP/val_eqP=> /=.
rewrite [X in X != _]qpolyXE /= //.
by apply/eqP=> Hx1; have := @size_polyX F; rewrite Hx1 size_poly1.
have Hx : (gX ^+ n)%g = 1%g by apply/eqP; rewrite -dvdp_order.
have Hf i : 0 < i < n -> (gX ^+ i != 1)%g by rewrite -dvdp_order => /Hp3.
have o_gt0 : 0 < #[gX]%g by rewrite order_gt0.
have : n <= #[gX]%g.
rewrite leqNgt; apply/negP=> oLx.
have /Hf/eqP[] : 0 < #[gX]%g < n by rewrite o_gt0.
by rewrite expg_order.
case: ltngtP => nLo _ //.
have: uniq (path.traject (mulg gX) 1%g #[gX]%g).
by apply/card_uniqP; rewrite path.size_traject -(eq_card (cycle_traject gX)).
case: #[gX]%g o_gt0 nLo => //= n1 _ nLn1 /andP[/negP[]].
apply/path.trajectP; exists n.-1; first by rewrite prednK.
rewrite -iterSr prednK // -[LHS]Hx.
by elim: (n) => //= n2 <-; rewrite expgS.
Qed.
Lemma gX_all : <[gX]>%g = [set: {unit qT}]%G.
Proof.
apply/eqP; rewrite eqEcard; apply/andP; split.
by apply/subsetP=> i; rewrite inE.
rewrite leq_eqVlt; apply/orP; left; apply/eqP.
rewrite -orderE gX_order card_qfpoly -[in RHS](mk_monicE primitive_mi).
rewrite -card_qpoly -(cardC1 (0 : {poly %/ h with primitive_mi})).
rewrite cardsT card_sub.
by apply: eq_card => x; rewrite [LHS]unitfE.
Qed.
Let pred_card_qT_gt0 : 0 < #|qT|.-1.
Proof. by rewrite ltn_predRL card_qfpoly_gt1. Qed.
Definition qlogp (p : qT) : nat :=
odflt (Ordinal pred_card_qT_gt0) (pick [pred i in 'I_ _ | ('qX ^+ i == p)]).
Lemma qlogp_lt p : qlogp p < #|qT|.-1.
Proof. by rewrite /qlogp; case: pickP. Qed.
Lemma qlogp_qX (p : qT) : p != 0 -> 'qX ^+ (qlogp p) = p.
Proof.
move=> p_neq0.
have Up : p \in GRing.unit by rewrite unitfE.
pose gp : {unit qT}:= FinRing.unit _ Up.
have /cyclePmin[i iLc iX] : gp \in <[gX]>%g by rewrite gX_all inE.
rewrite gX_order in iLc.
rewrite /qlogp; case: pickP => [j /eqP//|/(_ (Ordinal iLc))] /eqP[].
by have /val_eqP/eqP/= := iX; rewrite FinRing.val_unitX.
Qed.
Lemma qX_order_card : 'qX ^+ (#|qT|).-1 = 1 :> qT.
Proof.
have /primitive_polyP [_ Hd _] := Hh.
rewrite dvdp_order in Hd.
have -> : 1 = val (1%g : {unit qT}) by [].
by rewrite -(eqP Hd) val_unitX.
Qed.
Lemma qX_order_dvd (i : nat) : 'qX ^+ i = 1 :> qT -> (#|qT|.-1 %| i)%N.
Proof.
rewrite -gX_order cyclic.order_dvdn => Hd.
by apply/eqP/val_inj; rewrite /= -Hd val_unitX.
Qed.
Lemma qlogp0 : qlogp 0 = 0%N.
Proof.
rewrite /qlogp; case: pickP => //= x.
by rewrite (expf_eq0 ('qX : qT)) (negPf qX_neq0) andbF.
Qed.
Lemma qlogp1 : qlogp 1 = 0%N.
Proof.
case: (qlogp 1 =P 0%N) => // /eqP log1_neq0.
have := qlogp_lt 1; rewrite ltnNge => /negP[].
apply: dvdn_leq; first by rewrite lt0n.
by rewrite qX_order_dvd // qlogp_qX ?oner_eq0.
Qed.
Lemma qlogp_eq0 (q : qT) : (qlogp q == 0%N) = (q == 0) || (q == 1).
Proof.
case: (q =P 0) => [->|/eqP q_neq0]/=; first by rewrite qlogp0.
case: (q =P 1) => [->|/eqP q_neq1]/=; first by rewrite qlogp1.
rewrite /qlogp; case: pickP => [x|/(_ (Ordinal (qlogp_lt q)))] /=.
by case: ((x : nat) =P 0%N) => // ->; rewrite expr0 eq_sym (negPf q_neq1).
by rewrite qlogp_qX // eqxx.
Qed.
Lemma qX_exp_neq0 i : 'qX ^+ i != 0 :> qT.
Proof. by rewrite expf_eq0 negb_and qX_neq0 orbT. Qed.
Lemma qX_exp_inj i j :
i < #|qT|.-1 -> j < #|qT|.-1 -> 'qX ^+ i = 'qX ^+ j :> qT -> i = j.
Proof.
wlog iLj : i j / (i <= j)%N => [Hw|] iL jL Hqx.
case: (ltngtP i j)=> // /ltnW iLj; first by apply: Hw.
by apply/sym_equal/Hw.
suff ji_eq0 : (j - i = 0)%N by rewrite -(subnK iLj) ji_eq0.
case: ((j - i)%N =P 0%N) => // /eqP ji_neq0.
have : j - i < #|qT|.-1 by apply: leq_ltn_trans (leq_subr _ _) jL.
rewrite ltnNge => /negP[].
apply: dvdn_leq; first by rewrite lt0n.
have HqXi : 'qX ^+ i != 0 :> qT by rewrite expf_eq0 (negPf qX_neq0) andbF.
by apply/qX_order_dvd/(mulIf HqXi); rewrite mul1r -exprD subnK.
Qed.
Lemma powX_eq_mod i j : i = j %[mod #|qT|.-1] -> 'qX ^+ i = 'qX ^+ j :> qT.
Proof.
set n := _.-1 => iEj.
rewrite [i](divn_eq i n) [j](divn_eq j n) !exprD ![(_ * n)%N]mulnC.
by rewrite !exprM !qX_order_card !expr1n !mul1r iEj.
Qed.
Lemma qX_expK i : i < #|qT|.-1 -> qlogp ('qX ^+ i) = i.
Proof.
move=> iLF; apply: qX_exp_inj => //; first by apply: qlogp_lt.
by rewrite qlogp_qX // expf_eq0 (negPf qX_neq0) andbF.
Qed.
Lemma qlogpD (q1 q2 : qT) :
q1 != 0 -> q2 != 0 ->qlogp (q1 * q2) = ((qlogp q1 + qlogp q2) %% #|qT|.-1)%N.
Proof.
move=> q1_neq0 q2_neq0.
apply: qX_exp_inj; [apply: qlogp_lt => // | rewrite ltn_mod // |].
rewrite -[RHS]mul1r -(expr1n _ ((qlogp q1 + qlogp q2) %/ #|qT|.-1)).
rewrite -qX_order_card -exprM mulnC -exprD -divn_eq exprD !qlogp_qX //.
by rewrite mulf_eq0 negb_or q1_neq0.
Qed.
End PrimitivePoly.
Section Plogp.
Variable F : finFieldType.
Definition plogp (p q : {poly F}) :=
if boolP (primitive_poly p) is AltTrue Hh then
qlogp ((in_qpoly p q) : {poly %/ p with primitive_mi Hh})
else 0%N.
Lemma plogp_lt (p q : {poly F}) : 2 < size p -> plogp p q < #|{poly %/ p}|.-1.
Proof.
move=> /ltnW size_gt1.
rewrite /plogp.
case (boolP (primitive_poly p)) => // Hh; first by apply: qlogp_lt.
by rewrite ltn_predRL (card_finNzRing_gt1 {poly %/ p}).
Qed.
Lemma plogp_X (p q : {poly F}) :
2 < size p -> primitive_poly p -> ~~ (p %| q) -> p %| q - 'X ^+ plogp p q.
Proof.
move=> sp_gt2 Hh pNDq.
rewrite /plogp.
case (boolP (primitive_poly p)) => // Hh'; last by case/negP: Hh'.
have pM : p \is monic by case/and4P: Hh'.
have pMi : monic_irreducible_poly p by apply: primitive_mi.
set q' : {poly %/ p with primitive_mi Hh'} := in_qpoly p q.
apply/modp_eq0P; rewrite modpD modpN; apply/eqP; rewrite subr_eq0; apply/eqP.
rewrite !Pdiv.IdomainMonic.modpE //=.
suff /val_eqP/eqP/= : 'qX ^+ qlogp q' = q'.
rewrite /= [X in rmodp _ X]mk_monicE // => <-.
by rewrite poly_of_qpolyX /= mk_monicE // [rmodp 'X p]rmodp_small ?size_polyX.
apply: qlogp_qX => //.
apply/eqP=> /val_eqP/eqP.
rewrite /= mk_monicE // => /rmodp_eq0P; rewrite -dvdpE => pDq.
by case/negP: pNDq.
Qed.
Lemma plogp0 (p : {poly F}) : 2 < size p -> plogp p 0 = 0%N.
Proof.
move=> sp_gt2; rewrite /plogp; case (boolP (primitive_poly p)) => // i.
by rewrite in_qpoly0 qlogp0.
Qed.
Lemma plogp1 (p : {poly F}) : 2 < size p -> plogp p 1 = 0%N.
Proof.
move=> sp_gt2; rewrite /plogp; case (boolP (primitive_poly p)) => // i.
suff->: in_qpoly p 1 = 1 by apply: qlogp1.
apply/val_eqP/eqP; apply: in_qpoly_small.
rewrite mk_monicE ?size_poly1 ?(leq_trans _ sp_gt2) //.
by apply: primitive_mi.
Qed.
Lemma plogp_div_eq0 (p q : {poly F}) :
2 < size p -> (p %| q) -> plogp p q = 0%N.
Proof.
move=> sp_gt2; rewrite /plogp; case (boolP (primitive_poly p)) => // i pDq.
suff-> : in_qpoly p q = 0 by apply: qlogp0.
by apply/eqP; rewrite primitive_poly_in_qpoly_eq0.
Qed.
Lemma plogpD (p q1 q2 : {poly F}) :
2 < size p -> primitive_poly p -> ~~ (p %| q1) -> ~~ (p %| q2) ->
plogp p (q1 * q2) = ((plogp p q1 + plogp p q2) %% #|{poly %/ p}|.-1)%N.
Proof.
move=> sp_gt2 Pp pNDq1 pNDq2.
rewrite /plogp; case (boolP (primitive_poly p)) => [|/negP//] i /=.
have pmi := primitive_mi i.
by rewrite rmorphM qlogpD //= primitive_poly_in_qpoly_eq0.
Qed.
End Plogp.
|
CharZero.lean
|
/-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Algebra.GroupWithZero.Units.Basic
import Mathlib.Algebra.Notation.Support
import Mathlib.Algebra.Ring.Units
import Mathlib.Data.Nat.Cast.Basic
import Mathlib.Logic.Embedding.Basic
/-!
# Characteristic zero rings
-/
assert_not_exists Field
open Function Set
variable {α R S : Type*} {n : ℕ}
section AddMonoidWithOne
variable [AddMonoidWithOne R] [CharZero R]
/-- `Nat.cast` as an embedding into monoids of characteristic `0`. -/
@[simps]
def Nat.castEmbedding : ℕ ↪ R := ⟨Nat.cast, cast_injective⟩
instance CharZero.NeZero.two : NeZero (2 : R) where
out := by rw [← Nat.cast_two, Nat.cast_ne_zero]; decide
namespace Function
lemma support_natCast (hn : n ≠ 0) : support (n : α → R) = univ :=
support_const <| Nat.cast_ne_zero.2 hn
lemma mulSupport_natCast (hn : n ≠ 1) : mulSupport (n : α → R) = univ :=
mulSupport_const <| Nat.cast_ne_one.2 hn
end Function
end AddMonoidWithOne
section NonAssocSemiring
variable [NonAssocSemiring R] [NonAssocSemiring S]
namespace RingHom
lemma charZero (ϕ : R →+* S) [CharZero S] : CharZero R where
cast_injective a b h := CharZero.cast_injective (R := S) <| by
rw [← map_natCast ϕ, ← map_natCast ϕ, h]
lemma charZero_iff {ϕ : R →+* S} (hϕ : Injective ϕ) : CharZero R ↔ CharZero S :=
⟨fun hR =>
⟨by intro a b h; rwa [← @Nat.cast_inj R, ← hϕ.eq_iff, map_natCast ϕ, map_natCast ϕ]⟩,
fun _ => ϕ.charZero⟩
lemma injective_nat (f : ℕ →+* R) [CharZero R] : Injective f :=
Subsingleton.elim (Nat.castRingHom _) f ▸ Nat.cast_injective
end RingHom
variable [NoZeroDivisors R] [CharZero R] {a : R}
@[simp]
theorem add_self_eq_zero {a : R} : a + a = 0 ↔ a = 0 := by
simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero, false_or]
end NonAssocSemiring
section Semiring
variable [Semiring R] [CharZero R]
@[simp] lemma Nat.cast_pow_eq_one {a : ℕ} (hn : n ≠ 0) : (a : R) ^ n = 1 ↔ a = 1 := by
simp [← cast_pow, cast_eq_one, hn]
end Semiring
section NonAssocRing
variable [NonAssocRing R] [NoZeroDivisors R] [CharZero R]
@[scoped simp] theorem CharZero.neg_eq_self_iff {a : R} : -a = a ↔ a = 0 :=
neg_eq_iff_add_eq_zero.trans add_self_eq_zero
@[scoped simp] theorem CharZero.eq_neg_self_iff {a : R} : a = -a ↔ a = 0 :=
eq_neg_iff_add_eq_zero.trans add_self_eq_zero
theorem nat_mul_inj {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) : n = 0 ∨ a = b := by
rw [← sub_eq_zero, ← mul_sub, mul_eq_zero, sub_eq_zero] at h
exact mod_cast h
theorem nat_mul_inj' {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) (w : n ≠ 0) : a = b := by
simpa [w] using nat_mul_inj h
end NonAssocRing
section Ring
variable [Ring R] [CharZero R]
@[simp]
theorem units_ne_neg_self (u : Rˣ) : u ≠ -u := by
simp_rw [ne_eq, Units.ext_iff, Units.val_neg, eq_neg_iff_add_eq_zero, ← two_mul,
Units.mul_left_eq_zero, two_ne_zero, not_false_iff]
@[simp]
theorem neg_units_ne_self (u : Rˣ) : -u ≠ u := (units_ne_neg_self u).symm
end Ring
|
Invariant.lean
|
/-
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.Algebra.Module.Equiv.Basic
import Mathlib.Algebra.Module.Submodule.Map
import Mathlib.LinearAlgebra.Span.Defs
import Mathlib.Order.Sublattice
/-!
# The lattice of invariant submodules
In this file we defined the type `Module.End.invtSubmodule`, associated to a linear endomorphism of
a module. Its utility stems primarily from those occasions on which we wish to take advantage of the
lattice structure of invariant submodules.
See also `Mathlib/Algebra/Polynomial/Module/AEval.lean`.
-/
open Submodule (span)
namespace Module.End
variable {R M : Type*} [Semiring R] [AddCommMonoid M] [Module R M] (f : End R M)
/-- Given an endomorphism, `f` of some module, this is the sublattice of all `f`-invariant
submodules. -/
def invtSubmodule : Sublattice (Submodule R M) where
carrier := {p : Submodule R M | p ≤ p.comap f}
supClosed' p hp q hq := sup_le_iff.mpr
⟨le_trans hp <| Submodule.comap_mono le_sup_left,
le_trans hq <| Submodule.comap_mono le_sup_right⟩
infClosed' p hp q hq := by
simp only [Set.mem_setOf_eq, Submodule.comap_inf, le_inf_iff]
exact ⟨inf_le_of_left_le hp, inf_le_of_right_le hq⟩
lemma mem_invtSubmodule {p : Submodule R M} :
p ∈ f.invtSubmodule ↔ p ≤ p.comap f :=
Iff.rfl
/-- `p` is `f` invariant if and only if `p.map f ≤ p`. -/
theorem mem_invtSubmodule_iff_map_le {p : Submodule R M} :
p ∈ f.invtSubmodule ↔ p.map f ≤ p := Submodule.map_le_iff_le_comap.symm
/-- `p` is `f` invariant if and only if `Set.MapsTo f p p`. -/
theorem mem_invtSubmodule_iff_mapsTo {p : Submodule R M} :
p ∈ f.invtSubmodule ↔ Set.MapsTo f p p := Iff.rfl
alias ⟨_, _root_.Set.Mapsto.mem_invtSubmodule⟩ := mem_invtSubmodule_iff_mapsTo
theorem mem_invtSubmodule_iff_forall_mem_of_mem {p : Submodule R M} :
p ∈ f.invtSubmodule ↔ ∀ x ∈ p, f x ∈ p :=
Iff.rfl
/-- `p` is `f.symm` invariant if and only if `p ≤ p.map f`. -/
lemma mem_invtSubmodule_symm_iff_le_map {f : M ≃ₗ[R] M} {p : Submodule R M} :
p ∈ invtSubmodule f.symm ↔ p ≤ p.map f :=
(mem_invtSubmodule_iff_map_le _).trans (f.toEquiv.symm.subset_symm_image _ _).symm
namespace invtSubmodule
variable {f}
lemma inf_mem {p q : Submodule R M} (hp : p ∈ f.invtSubmodule) (hq : q ∈ f.invtSubmodule) :
p ⊓ q ∈ f.invtSubmodule :=
Sublattice.inf_mem hp hq
lemma sup_mem {p q : Submodule R M} (hp : p ∈ f.invtSubmodule) (hq : q ∈ f.invtSubmodule) :
p ⊔ q ∈ f.invtSubmodule :=
Sublattice.sup_mem hp hq
variable (f)
@[simp]
protected lemma top_mem : ⊤ ∈ f.invtSubmodule := by simp [invtSubmodule]
@[simp]
protected lemma bot_mem : ⊥ ∈ f.invtSubmodule := by simp [invtSubmodule]
instance : BoundedOrder (f.invtSubmodule) where
top := ⟨⊤, invtSubmodule.top_mem f⟩
bot := ⟨⊥, invtSubmodule.bot_mem f⟩
le_top := fun ⟨p, hp⟩ ↦ by simp
bot_le := fun ⟨p, hp⟩ ↦ by simp
@[simp]
protected lemma zero :
(0 : End R M).invtSubmodule = ⊤ :=
eq_top_iff.mpr fun x ↦ by simp [invtSubmodule]
@[simp]
protected lemma id :
invtSubmodule (LinearMap.id : End R M) = ⊤ :=
eq_top_iff.mpr fun x ↦ by simp [invtSubmodule]
@[simp]
protected lemma one :
invtSubmodule (1 : End R M) = ⊤ :=
invtSubmodule.id
protected lemma mk_eq_bot_iff {p : Submodule R M} (hp : p ∈ f.invtSubmodule) :
(⟨p, hp⟩ : f.invtSubmodule) = ⊥ ↔ p = ⊥ :=
Subtype.mk_eq_bot_iff (by simp [invtSubmodule]) _
protected lemma mk_eq_top_iff {p : Submodule R M} (hp : p ∈ f.invtSubmodule) :
(⟨p, hp⟩ : f.invtSubmodule) = ⊤ ↔ p = ⊤ :=
Subtype.mk_eq_top_iff (by simp [invtSubmodule]) _
@[simp]
protected lemma disjoint_mk_iff {p q : Submodule R M}
(hp : p ∈ f.invtSubmodule) (hq : q ∈ f.invtSubmodule) :
Disjoint (α := f.invtSubmodule) ⟨p, hp⟩ ⟨q, hq⟩ ↔ Disjoint p q := by
rw [disjoint_iff, disjoint_iff, Sublattice.mk_inf_mk,
Subtype.mk_eq_bot_iff (⊥ : f.invtSubmodule).property]
protected lemma disjoint_iff {p q : f.invtSubmodule} :
Disjoint p q ↔ Disjoint (p : Submodule R M) (q : Submodule R M) := by
obtain ⟨p, hp⟩ := p
obtain ⟨q, hq⟩ := q
simp
@[simp]
protected lemma codisjoint_mk_iff {p q : Submodule R M}
(hp : p ∈ f.invtSubmodule) (hq : q ∈ f.invtSubmodule) :
Codisjoint (α := f.invtSubmodule) ⟨p, hp⟩ ⟨q, hq⟩ ↔ Codisjoint p q := by
rw [codisjoint_iff, codisjoint_iff, Sublattice.mk_sup_mk,
Subtype.mk_eq_top_iff (⊤ : f.invtSubmodule).property]
protected lemma codisjoint_iff {p q : f.invtSubmodule} :
Codisjoint p q ↔ Codisjoint (p : Submodule R M) (q : Submodule R M) := by
obtain ⟨p, hp⟩ := p
obtain ⟨q, hq⟩ := q
simp
@[simp]
protected lemma isCompl_mk_iff {p q : Submodule R M}
(hp : p ∈ f.invtSubmodule) (hq : q ∈ f.invtSubmodule) :
IsCompl (α := f.invtSubmodule) ⟨p, hp⟩ ⟨q, hq⟩ ↔ IsCompl p q := by
simp [isCompl_iff]
protected lemma isCompl_iff {p q : f.invtSubmodule} :
IsCompl p q ↔ IsCompl (p : Submodule R M) (q : Submodule R M) := by
obtain ⟨p, hp⟩ := p
obtain ⟨q, hq⟩ := q
simp
lemma map_subtype_mem_of_mem_invtSubmodule {p : Submodule R M} (hp : p ∈ f.invtSubmodule)
{q : Submodule R p} (hq : q ∈ invtSubmodule (LinearMap.restrict f hp)) :
Submodule.map p.subtype q ∈ f.invtSubmodule := by
rintro - ⟨⟨x, hx⟩, hx', rfl⟩
specialize hq hx'
rw [Submodule.mem_comap, LinearMap.restrict_apply] at hq
simpa [hq] using hp hx
protected lemma comp {p : Submodule R M} {g : End R M}
(hf : p ∈ f.invtSubmodule) (hg : p ∈ g.invtSubmodule) :
p ∈ invtSubmodule (f ∘ₗ g) :=
fun _ hx ↦ hf (hg hx)
@[simp] lemma _root_.LinearEquiv.map_mem_invtSubmodule_conj_iff {R M N : Type*} [CommSemiring R]
[AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] {f : End R M}
{e : M ≃ₗ[R] N} {p : Submodule R M} :
p.map e ∈ (e.conj f).invtSubmodule ↔ p ∈ f.invtSubmodule := by
change p.map e.toLinearMap ∈ _ ↔ _
have : e.symm.toLinearMap ∘ₗ ((e ∘ₗ f) ∘ₗ e.symm.toLinearMap) ∘ₗ e = f := by ext; simp
rw [LinearEquiv.conj_apply, mem_invtSubmodule, mem_invtSubmodule, Submodule.map_le_iff_le_comap,
Submodule.map_equiv_eq_comap_symm, ← Submodule.comap_comp, ← Submodule.comap_comp, this]
lemma _root_.LinearEquiv.map_mem_invtSubmodule_iff {R M N : Type*} [CommSemiring R]
[AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] {f : End R N}
{e : M ≃ₗ[R] N} {p : Submodule R M} :
p.map e ∈ f.invtSubmodule ↔ p ∈ (e.symm.conj f).invtSubmodule := by
simp [← e.map_mem_invtSubmodule_conj_iff]
end invtSubmodule
variable (R) in
lemma span_orbit_mem_invtSubmodule {G : Type*}
[Monoid G] [DistribMulAction G M] [SMulCommClass G R M] (x : M) (g : G) :
span R (MulAction.orbit G x) ∈ invtSubmodule (DistribMulAction.toLinearMap R M g) := by
rw [mem_invtSubmodule, Submodule.span_le, Submodule.comap_coe]
intro y hy
simp only [Set.mem_preimage, DistribMulAction.toLinearMap_apply, SetLike.mem_coe]
exact Submodule.subset_span <| MulAction.mem_orbit_of_mem_orbit g hy
end Module.End
|
TransImports.lean
|
import Mathlib.Util.TransImports
/--
info: 'MathlibTest.TransImports' has at most 1000 transitive imports
2 starting with "Mathlib.Tactic.Linter.H":
[Mathlib.Tactic.Linter.HashCommandLinter, Mathlib.Tactic.Linter.Header]
-/
#guard_msgs in
#trans_imports "Mathlib.Tactic.Linter.H" at_most 1000
|
Nondegenerate.lean
|
/-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import Mathlib.Data.Matrix.Basic
import Mathlib.LinearAlgebra.Matrix.Determinant.Basic
import Mathlib.LinearAlgebra.Matrix.Adjugate
/-!
# Matrices associated with non-degenerate bilinear forms
## Main definitions
* `Matrix.Nondegenerate A`: the proposition that when interpreted as a bilinear form, the matrix `A`
is nondegenerate.
-/
namespace Matrix
variable {m R A : Type*} [CommRing R]
/-- A matrix `M` is nondegenerate if for all `v ≠ 0`, there is a `w ≠ 0` with `w * M * v ≠ 0`. -/
def Nondegenerate [Finite m] (M : Matrix m m R) :=
letI : Fintype m := Fintype.ofFinite m
∀ v, (∀ w, v ⬝ᵥ M *ᵥ w = 0) → v = 0
variable [Fintype m]
lemma nondegenerate_def {M : Matrix m m R} :
M.Nondegenerate ↔ ∀ v, (∀ w, v ⬝ᵥ M *ᵥ w = 0) → v = 0 := by
refine forall_congr' fun v ↦ ⟨fun hM hv ↦ hM ?_, fun hM hv ↦ hM ?_⟩ <;> convert hv
/-- If `M` is nondegenerate and `w * M * v = 0` for all `w`, then `v = 0`. -/
theorem Nondegenerate.eq_zero_of_ortho {M : Matrix m m R} (hM : Nondegenerate M) {v : m → R}
(hv : ∀ w, v ⬝ᵥ M *ᵥ w = 0) : v = 0 :=
nondegenerate_def.mp hM v hv
/-- If `M` is nondegenerate and `v ≠ 0`, then there is some `w` such that `w * M * v ≠ 0`. -/
theorem Nondegenerate.exists_not_ortho_of_ne_zero {M : Matrix m m R} (hM : Nondegenerate M)
{v : m → R} (hv : v ≠ 0) : ∃ w, v ⬝ᵥ M *ᵥ w ≠ 0 :=
not_forall.mp (mt hM.eq_zero_of_ortho hv)
variable [CommRing A] [IsDomain A]
/-- If `M` has a nonzero determinant, then `M` as a bilinear form on `n → A` is nondegenerate.
See also `BilinForm.nondegenerateOfDetNeZero'` and `BilinForm.nondegenerateOfDetNeZero`.
-/
theorem nondegenerate_of_det_ne_zero [DecidableEq m] {M : Matrix m m A} (hM : M.det ≠ 0) :
Nondegenerate M := by
refine nondegenerate_def.mpr fun v hv ↦ ?_
ext i
specialize hv (M.cramer (Pi.single i 1))
refine (mul_eq_zero.mp ?_).resolve_right hM
convert hv
simp only [mulVec_cramer M (Pi.single i 1), dotProduct, Pi.smul_apply, smul_eq_mul]
rw [Finset.sum_eq_single i, Pi.single_eq_same, mul_one]
· intro j _ hj
simp [hj]
· intros
have := Finset.mem_univ i
contradiction
theorem eq_zero_of_vecMul_eq_zero [DecidableEq m] {M : Matrix m m A} (hM : M.det ≠ 0) {v : m → A}
(hv : v ᵥ* M = 0) : v = 0 :=
(nondegenerate_of_det_ne_zero hM).eq_zero_of_ortho fun w => by
rw [dotProduct_mulVec, hv, zero_dotProduct]
theorem eq_zero_of_mulVec_eq_zero [DecidableEq m] {M : Matrix m m A} (hM : M.det ≠ 0) {v : m → A}
(hv : M *ᵥ v = 0) : v = 0 :=
eq_zero_of_vecMul_eq_zero (by rwa [det_transpose]) ((vecMul_transpose M v).trans hv)
end Matrix
|
Int.lean
|
/-
Copyright (c) 2025 Xavier Roblot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Xavier Roblot
-/
import Mathlib.Algebra.Field.ZMod
import Mathlib.RingTheory.Ideal.Norm.AbsNorm
/-!
# Ideal of `ℤ`
We prove results about ideals of `ℤ` or ideals of extensions of `ℤ`.
In particular, for `I` an ideal of a ring `R` extending `ℤ`, we prove several results about
`absNorm (under ℤ I)` which is the smallest positive integer contained in `I`.
## Main definitions and results
* `Int.ideal_span_isMaximal_of_prime`: the ideal generated by a prime number is maximal.
* `Int.absNorm_under_eq_sInf`: the predicate that the `absNorm (under ℤ I)` is the smallest
positive integer in `I`.
* `Int.absNorm_under_dvd_absNorm`: `absNorm (under ℤ I)` divides the norm of `I`.
-/
instance Int.ideal_span_isMaximal_of_prime (p : ℕ) [Fact (Nat.Prime p)] :
(Ideal.span {(p : ℤ)}).IsMaximal :=
Ideal.Quotient.maximal_of_isField _ <|
(Int.quotientSpanNatEquivZMod p).toMulEquiv.isField (Field.toIsField _)
namespace Int
open Ideal
variable {R : Type*} [Ring R] {I : Ideal R}
theorem cast_mem_ideal_iff {d : ℤ} :
(d : R) ∈ I ↔ (absNorm (under ℤ I) : ℤ) ∣ d := by
rw [← mem_span_singleton, ideal_span_absNorm_eq_self, under_def, mem_comap, eq_intCast]
variable (I)
theorem absNorm_under_mem :
(absNorm (under ℤ I) : R) ∈ I := by
rw [← cast_natCast, cast_mem_ideal_iff]
theorem absNorm_under_eq_sInf :
absNorm (under ℤ I) = sInf {d : ℕ | 0 < d ∧ (d : R) ∈ I} := by
by_cases h : absNorm (under ℤ I) = 0
· have : {d : ℕ | 0 < d ∧ ↑d ∈ I} = ∅ := by
refine Set.eq_empty_of_forall_notMem ?_
intro x ⟨hx₁, hx₂⟩
rw [← cast_natCast, cast_mem_ideal_iff, h, natCast_dvd_natCast, Nat.zero_dvd] at hx₂
rw [Nat.pos_iff_ne_zero] at hx₁
exact hx₁ hx₂
rw [h, this, Nat.sInf_empty]
· have h₁ : absNorm (under ℤ I) ∈ {d : ℕ | 0 < d ∧ ↑d ∈ I} :=
⟨Nat.pos_of_ne_zero h, absNorm_under_mem I⟩
refine le_antisymm ?_ (Nat.sInf_le h₁)
by_contra! h₀
have h₂ := (Nat.sInf_mem (Set.nonempty_of_mem h₁)).2
rw [← cast_natCast, cast_mem_ideal_iff, natCast_dvd_natCast] at h₂
exact lt_iff_not_ge.mp h₀ <| Nat.le_of_dvd (Nat.sInf_mem (Set.nonempty_of_mem h₁)).1 h₂
theorem absNorm_under_dvd_absNorm {S : Type*} [CommRing S] [IsDedekindDomain S] [Module.Free ℤ S]
(I : Ideal S) :
absNorm (under ℤ I) ∣ absNorm I := by
by_cases h : Finite (S ⧸ I)
· have : Fintype (S ⧸ I) := Fintype.ofFinite (S ⧸ I)
have h_main {d : ℕ} : (d : S) ∈ I ↔ ∀ (x : S ⧸ I), d • x = 0 := by
simp_rw [nsmul_eq_mul, ← map_natCast (Ideal.Quotient.mk I), ← Quotient.eq_zero_iff_mem]
exact ⟨fun h _ ↦ by simp [h], fun h ↦ by simpa using h 1⟩
rw [Ideal.absNorm_apply I, Submodule.cardQuot_apply, Nat.card_eq_fintype_card]
simp_rw [absNorm_under_eq_sInf, h_main, ← AddMonoid.exponent_eq_sInf]
exact AddGroup.exponent_dvd_card (G := S ⧸ I)
· rw [show absNorm I = 0 by
exact AddSubgroup.index_eq_zero_iff_infinite.mpr <| not_finite_iff_infinite.mp h]
exact Nat.dvd_zero _
end Int
|
Infinite.lean
|
/-
Copyright (c) 2020 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
-/
import Mathlib.Data.Set.Finite.Basic
import Mathlib.Order.Interval.Set.Basic
/-!
# Infinitude of intervals
Bounded intervals in dense orders are infinite, as are unbounded intervals
in orders that are unbounded on the appropriate side. We also prove that an unbounded
preorder is an infinite type.
-/
variable {α : Type*} [Preorder α]
/-- A nonempty preorder with no maximal element is infinite. -/
instance NoMaxOrder.infinite [Nonempty α] [NoMaxOrder α] : Infinite α :=
let ⟨f, hf⟩ := Nat.exists_strictMono α
Infinite.of_injective f hf.injective
/-- A nonempty preorder with no minimal element is infinite. -/
instance NoMinOrder.infinite [Nonempty α] [NoMinOrder α] : Infinite α :=
@NoMaxOrder.infinite αᵒᵈ _ _ _
namespace Set
section DenselyOrdered
variable [DenselyOrdered α] {a b : α} (h : a < b)
include h
theorem Ioo.infinite : Infinite (Ioo a b) :=
@NoMaxOrder.infinite _ _ (nonempty_Ioo_subtype h) _
theorem Ioo_infinite : (Ioo a b).Infinite :=
infinite_coe_iff.1 <| Ioo.infinite h
theorem Ico_infinite : (Ico a b).Infinite :=
(Ioo_infinite h).mono Ioo_subset_Ico_self
theorem Ico.infinite : Infinite (Ico a b) :=
infinite_coe_iff.2 <| Ico_infinite h
theorem Ioc_infinite : (Ioc a b).Infinite :=
(Ioo_infinite h).mono Ioo_subset_Ioc_self
theorem Ioc.infinite : Infinite (Ioc a b) :=
infinite_coe_iff.2 <| Ioc_infinite h
theorem Icc_infinite : (Icc a b).Infinite :=
(Ioo_infinite h).mono Ioo_subset_Icc_self
theorem Icc.infinite : Infinite (Icc a b) :=
infinite_coe_iff.2 <| Icc_infinite h
end DenselyOrdered
instance [NoMinOrder α] {a : α} : Infinite (Iio a) :=
NoMinOrder.infinite
theorem Iio_infinite [NoMinOrder α] (a : α) : (Iio a).Infinite :=
infinite_coe_iff.1 inferInstance
instance [NoMinOrder α] {a : α} : Infinite (Iic a) :=
NoMinOrder.infinite
theorem Iic_infinite [NoMinOrder α] (a : α) : (Iic a).Infinite :=
infinite_coe_iff.1 inferInstance
instance [NoMaxOrder α] {a : α} : Infinite (Ioi a) :=
NoMaxOrder.infinite
theorem Ioi_infinite [NoMaxOrder α] (a : α) : (Ioi a).Infinite :=
infinite_coe_iff.1 inferInstance
instance [NoMaxOrder α] {a : α} : Infinite (Ici a) :=
NoMaxOrder.infinite
theorem Ici_infinite [NoMaxOrder α] (a : α) : (Ici a).Infinite :=
infinite_coe_iff.1 inferInstance
end Set
|
Final.lean
|
/-
Copyright (c) 2024 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jakob von Raumer
-/
import Mathlib.CategoryTheory.Functor.KanExtension.Adjunction
import Mathlib.CategoryTheory.Limits.IsConnected
import Mathlib.CategoryTheory.Limits.Sifted
import Mathlib.CategoryTheory.Filtered.Final
import Mathlib.CategoryTheory.Filtered.Flat
import Mathlib.CategoryTheory.Grothendieck
import Mathlib.CategoryTheory.Comma.StructuredArrow.CommaMap
/-!
# Finality of Projections in Comma Categories
We show that `fst L R` is final if `R` is and that `snd L R` is initial if `L` is.
As a corollary, we show that `Comma L R` with `L : A ⥤ T` and `R : B ⥤ T` is connected if `R` is
final and `A` is connected.
We then use this in a proof that derives finality of `map` between two comma categories
on a quasi-commutative diagram of functors, some of which need to be final.
Finally we prove filteredness of a `Comma L R` and finality of `snd L R`, given that `R` is final
and `A` and `B` are filtered.
## References
* [M. Kashiwara, P. Schapira, *Categories and Sheaves*][Kashiwara2006], Lemma 3.4.3 -- 3.4.5
-/
universe v₁ v₂ v₃ v₄ v₅ v₆ u₁ u₂ u₃ u₄ u₅ u₆
namespace CategoryTheory
namespace Comma
open Limits Functor CostructuredArrow
section Small
variable {A : Type v₁} [Category.{v₁} A]
variable {B : Type v₁} [Category.{v₁} B]
variable {T : Type v₁} [Category.{v₁} T]
variable (L : A ⥤ T) (R : B ⥤ T)
private lemma final_fst_small [R.Final] : (fst L R).Final := by
rw [Functor.final_iff_isIso_colimit_pre]
intro G
let i : colimit G ≅ colimit (fst L R ⋙ G) :=
colimitIsoColimitGrothendieck L G ≪≫
(Final.colimitIso (Grothendieck.pre (functor L) R) (grothendieckProj L ⋙ G)).symm ≪≫
HasColimit.isoOfNatIso (Iso.refl _) ≪≫
Final.colimitIso (grothendieckPrecompFunctorEquivalence L R).functor (fst L R ⋙ G)
convert i.isIso_inv
apply colimit.hom_ext
intro ⟨a, b, f⟩
simp only [colimit.ι_pre, comp_obj, fst_obj, grothendieckPrecompFunctorEquivalence_functor,
Iso.trans_inv, Iso.symm_inv, Category.assoc, i]
change _ = colimit.ι (fst L R ⋙ G)
((grothendieckPrecompFunctorToComma L R).obj ⟨b, CostructuredArrow.mk f⟩) ≫ _
simp
end Small
section NonSmall
variable {A : Type u₁} [Category.{v₁} A]
variable {B : Type u₂} [Category.{v₂} B]
variable {T : Type u₃} [Category.{v₃} T]
variable (L : A ⥤ T) (R : B ⥤ T)
instance final_fst [R.Final] : (fst L R).Final := by
let sA : A ≌ AsSmall.{max u₁ u₂ u₃ v₁ v₂ v₃} A := AsSmall.equiv
let sB : B ≌ AsSmall.{max u₁ u₂ u₃ v₁ v₂ v₃} B := AsSmall.equiv
let sT : T ≌ AsSmall.{max u₁ u₂ u₃ v₁ v₂ v₃} T := AsSmall.equiv
let L' := sA.inverse ⋙ L ⋙ sT.functor
let R' := sB.inverse ⋙ R ⋙ sT.functor
let fC : Comma L R ⥤ Comma L' R' :=
map (F₁ := sA.functor) (F := sT.functor) (F₂ := sB.functor)
(isoWhiskerRight sA.unitIso (L ⋙ sT.functor)).hom
(isoWhiskerRight sB.unitIso (R ⋙ sT.functor)).hom
have : Final (fst L' R') := final_fst_small _ _
apply final_of_natIso (F := (fC ⋙ fst L' R' ⋙ sA.inverse))
exact (Functor.associator _ _ _).symm.trans (Iso.compInverseIso (mapFst _ _))
instance initial_snd [L.Initial] : (snd L R).Initial := by
have : ((opFunctor L R).leftOp ⋙ fst R.op L.op).Final :=
final_equivalence_comp (opEquiv L R).functor.leftOp (fst R.op L.op)
have : (snd L R).op.Final := final_of_natIso (opFunctorCompFst _ _)
apply initial_of_final_op
/-- `Comma L R` with `L : A ⥤ T` and `R : B ⥤ T` is connected if `R` is final and `A` is
connected. -/
instance isConnected_comma_of_final [IsConnected A] [R.Final] : IsConnected (Comma L R) := by
rwa [isConnected_iff_of_final (fst L R)]
/-- `Comma L R` with `L : A ⥤ T` and `R : B ⥤ T` is connected if `L` is initial and `B` is
connected. -/
instance isConnected_comma_of_initial [IsConnected B] [L.Initial] : IsConnected (Comma L R) := by
rwa [isConnected_iff_of_initial (snd L R)]
end NonSmall
/-- Let the following diagram commute up to isomorphism:
```
L R
A ---→ T ←--- B
| | |
| F | H | G
↓ ↓ ↓
A' ---→ T' ←--- B'
L' R'
```
Let `F`, `G`, `R` and `R'` be final and `B` be filtered. Then, the induced functor between the comma
categories of the first and second row of the diagram is final. -/
lemma map_final {A : Type u₁} [Category.{v₁} A] {B : Type u₂} [Category.{v₂} B] {T : Type u₃}
[Category.{v₃} T] {L : A ⥤ T} {R : B ⥤ T} {A' : Type u₄} [Category.{v₄} A'] {B' : Type u₅}
[Category.{v₅} B'] {T' : Type u₆} [Category.{v₆} T'] {L' : A' ⥤ T'} {R' : B' ⥤ T'} {F : A ⥤ A'}
{G : B ⥤ B'} {H : T ⥤ T'} (iL : F ⋙ L' ≅ L ⋙ H) (iR : G ⋙ R' ≅ R ⋙ H) [IsFiltered B]
[R.Final] [R'.Final] [F.Final] [G.Final] :
(Comma.map iL.hom iR.inv).Final := ⟨fun ⟨i₂, j₂, u₂⟩ => by
haveI := final_of_natIso iR
rw [isConnected_iff_of_equivalence (StructuredArrow.commaMapEquivalence iL.hom iR.inv _)]
have : StructuredArrow.map₂ u₂ iR.hom ≅ StructuredArrow.post j₂ G R' ⋙
StructuredArrow.map₂ (G := 𝟭 _) (F := 𝟭 _) (R' := R ⋙ H) u₂ iR.hom ⋙
StructuredArrow.pre _ R H :=
eqToIso (by
congr
· simp
· ext; simp) ≪≫
(StructuredArrow.map₂CompMap₂Iso _ _ _ _).symm ≪≫
isoWhiskerLeft _ ((StructuredArrow.map₂CompMap₂Iso _ _ _ _).symm ≪≫
isoWhiskerLeft _ (StructuredArrow.preIsoMap₂ _ _ _).symm) ≪≫
isoWhiskerRight (StructuredArrow.postIsoMap₂ j₂ G R').symm _
haveI := final_of_natIso this.symm
rw [IsIso.Iso.inv_inv]
infer_instance⟩
section Filtered
variable {A : Type u₁} [Category.{v₁} A]
variable {B : Type u₂} [Category.{v₂} B]
variable {T : Type u₃} [Category.{v₃} T]
variable (L : A ⥤ T) (R : B ⥤ T)
attribute [local instance] map_final in
/-- Let `A` and `B` be filtered categories, `R : B ⥤ T` be final and `L : A ⥤ T`. Then, the
comma category `Comma L R` is filtered. -/
instance isFiltered_of_final [IsFiltered A] [IsFiltered B] [R.Final] : IsFiltered (Comma L R) := by
haveI (a : A) : IsFiltered (Comma (fromPUnit (L.obj a)) R) :=
R.final_iff_isFiltered_structuredArrow.mp inferInstance (L.obj a)
have (a : A) : (fromPUnit (Over.mk (𝟙 a))).Final := final_const_of_isTerminal Over.mkIdTerminal
let η (a : A) : fromPUnit (Over.mk (𝟙 a)) ⋙ Over.forget a ⋙ L ≅ fromPUnit (L.obj a) :=
NatIso.ofComponents (fun _ => Iso.refl _)
have (a : A) := IsFiltered.of_final (map (L := fromPUnit (L.obj a)) (F := 𝟭 T) (η a).hom
((Iso.refl (𝟭 B ⋙ R)).inv))
have : RepresentablyCoflat (fst L R) :=
⟨fun a => IsFiltered.of_equivalence (CostructuredArrow.ofCommaFstEquivalence L R a).symm⟩
apply isFiltered_of_representablyCoflat (fst L R)
attribute [local instance] isFiltered_of_final in
/-- Let `A` and `B` be cofiltered categories, `L : A ⥤ T` be initial and `R : B ⥤ T`. Then, the
comma category `Comma L R` is cofiltered. -/
lemma isCofiltered_of_initial [IsCofiltered A] [IsCofiltered B] [L.Initial] :
IsCofiltered (Comma L R) :=
IsCofiltered.of_equivalence (Comma.opEquiv _ _).symm
attribute [local instance] final_of_isFiltered_of_pUnit in
/-- Let `A` and `B` be filtered categories, `R : B ⥤ T` be final and `R : A ⥤ T`. Then, the
projection `snd L R : Comma L R ⥤ B` is final. -/
instance final_snd [IsFiltered A] [IsFiltered B] [R.Final] : (snd L R).Final := by
let iL : star.{1} A ⋙ 𝟭 _ ≅ L ⋙ star _ := Iso.refl _
let iR : 𝟭 B ⋙ star.{1} B ≅ R ⋙ star _ := Iso.refl _
have := map_final iL iR
let s := (equivProd (𝟭 _) (star B)).trans <| prod.leftUnitorEquivalence B
let iS : map iL.hom iR.inv ⋙ s.functor ≅ snd L R :=
NatIso.ofComponents (fun _ => Iso.refl _) (fun f => by simp [iL, iR, s])
apply final_of_natIso iS
/-- Let `A` and `B` be cofiltered categories, `L : A ⥤ T` be initial and `R : B ⥤ T`. Then, the
projection `fst L R : Comma L R ⥤ A` is initial. -/
instance initial_fst [IsCofiltered A] [IsCofiltered B] [L.Initial] : (fst L R).Initial := by
have : ((opFunctor L R).leftOp ⋙ snd R.op L.op).Final :=
final_equivalence_comp (opEquiv L R).functor.leftOp _
have : (fst L R).op.Final := final_of_natIso <| opFunctorCompSnd _ _
apply initial_of_final_op
end Filtered
end Comma
end CategoryTheory
|
Basic.lean
|
/-
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.HomotopyCategory.HomologicalFunctor
import Mathlib.Algebra.Homology.HomotopyCategory.ShiftSequence
import Mathlib.Algebra.Homology.HomotopyCategory.SingleFunctors
import Mathlib.Algebra.Homology.HomotopyCategory.Triangulated
import Mathlib.Algebra.Homology.Localization
/-! # The derived category of an abelian category
In this file, we construct the derived category `DerivedCategory C` of an
abelian category `C`. It is equipped with a triangulated structure.
The derived category is defined here as the localization of cochain complexes
indexed by `ℤ` with respect to quasi-isomorphisms: it is a type synonym of
`HomologicalComplexUpToQuasiIso C (ComplexShape.up ℤ)`. Then, we have a
localization functor `DerivedCategory.Q : CochainComplex C ℤ ⥤ DerivedCategory C`.
It was already shown in the file `Algebra.Homology.Localization` that the induced
functor `DerivedCategory.Qh : HomotopyCategory C (ComplexShape.up ℤ) ⥤ DerivedCategory C`
is a localization functor with respect to the class of morphisms
`HomotopyCategory.quasiIso C (ComplexShape.up ℤ)`. In the lemma
`HomotopyCategory.quasiIso_eq_subcategoryAcyclic_W` we obtain that this class of morphisms
consists of morphisms whose cone belongs to the triangulated subcategory
`HomotopyCategory.subcategoryAcyclic C` of acyclic complexes. Then, the triangulated
structure on `DerivedCategory C` is deduced from the triangulated structure
on the homotopy category (see file `Algebra.Homology.HomotopyCategory.Triangulated`)
using the localization theorem for triangulated categories which was obtained
in the file `CategoryTheory.Localization.Triangulated`.
## Implementation notes
If `C : Type u` and `Category.{v} C`, the constructed localized category of cochain
complexes with respect to quasi-isomorphisms has morphisms in `Type (max u v)`.
However, in certain circumstances, it shall be possible to prove that they are `v`-small
(when `C` is a Grothendieck abelian category (e.g. the category of modules over a ring),
it should be so by a theorem of Hovey.).
Then, when working with derived categories in mathlib, the user should add the variable
`[HasDerivedCategory.{w} C]` which is the assumption that there is a chosen derived
category with morphisms in `Type w`. When derived categories are used in order to
prove statements which do not involve derived categories, the `HasDerivedCategory.{max u v}`
instance should be obtained at the beginning of the proof, using the term
`HasDerivedCategory.standard C`.
## TODO (@joelriou)
- construct the distinguished triangle associated to a short exact sequence
of cochain complexes (done), and compare the associated connecting homomorphism
with the one defined in `Algebra.Homology.HomologySequence`.
## References
* [Jean-Louis Verdier, *Des catégories dérivées des catégories abéliennes*][verdier1996]
* [Mark Hovey, *Model category structures on chain complexes of sheaves*][hovey-2001]
-/
assert_not_exists TwoSidedIdeal
universe w v u
open CategoryTheory Limits Pretriangulated
variable (C : Type u) [Category.{v} C] [Abelian C]
namespace HomotopyCategory
/-- The triangulated subcategory of `HomotopyCategory C (ComplexShape.up ℤ)` consisting
of acyclic complexes. -/
def subcategoryAcyclic : ObjectProperty (HomotopyCategory C (ComplexShape.up ℤ)) :=
(homologyFunctor C (ComplexShape.up ℤ) 0).homologicalKernel
instance : (subcategoryAcyclic C).IsTriangulated := by
dsimp [subcategoryAcyclic]
infer_instance
instance : (subcategoryAcyclic C).IsClosedUnderIsomorphisms := by
dsimp [subcategoryAcyclic]
infer_instance
variable {C}
lemma mem_subcategoryAcyclic_iff (X : HomotopyCategory C (ComplexShape.up ℤ)) :
subcategoryAcyclic C X ↔ ∀ (n : ℤ), IsZero ((homologyFunctor _ _ n).obj X) :=
Functor.mem_homologicalKernel_iff _ X
lemma quotient_obj_mem_subcategoryAcyclic_iff_exactAt (K : CochainComplex C ℤ) :
subcategoryAcyclic C ((quotient _ _).obj K) ↔ ∀ (n : ℤ), K.ExactAt n := by
rw [mem_subcategoryAcyclic_iff]
refine forall_congr' (fun n => ?_)
simp only [HomologicalComplex.exactAt_iff_isZero_homology]
exact ((homologyFunctorFactors C (ComplexShape.up ℤ) n).app K).isZero_iff
variable (C)
lemma quasiIso_eq_subcategoryAcyclic_W :
quasiIso C (ComplexShape.up ℤ) = (subcategoryAcyclic C).trW := by
ext K L f
exact ((homologyFunctor C (ComplexShape.up ℤ) 0).mem_homologicalKernel_trW_iff f).symm
end HomotopyCategory
/-- The assumption that a localized category for
`(HomologicalComplex.quasiIso C (ComplexShape.up ℤ))` has been chosen, and that the morphisms
in this chosen category are in `Type w`. -/
abbrev HasDerivedCategory := MorphismProperty.HasLocalization.{w}
(HomologicalComplex.quasiIso C (ComplexShape.up ℤ))
/-- The derived category obtained using the constructed localized category of cochain complexes
with respect to quasi-isomorphisms. This should be used only while proving statements
which do not involve the derived category. -/
def HasDerivedCategory.standard : HasDerivedCategory.{max u v} C :=
MorphismProperty.HasLocalization.standard _
variable [HasDerivedCategory.{w} C]
/-- The derived category of an abelian category. -/
def DerivedCategory : Type (max u v) := HomologicalComplexUpToQuasiIso C (ComplexShape.up ℤ)
namespace DerivedCategory
instance : Category.{w} (DerivedCategory C) := by
dsimp [DerivedCategory]
infer_instance
variable {C}
/-- The localization functor `CochainComplex C ℤ ⥤ DerivedCategory C`. -/
def Q : CochainComplex C ℤ ⥤ DerivedCategory C := HomologicalComplexUpToQuasiIso.Q
instance : (Q (C := C)).IsLocalization
(HomologicalComplex.quasiIso C (ComplexShape.up ℤ)) := by
dsimp only [Q, DerivedCategory]
infer_instance
instance {K L : CochainComplex C ℤ} (f : K ⟶ L) [QuasiIso f] :
IsIso (Q.map f) :=
Localization.inverts Q (HomologicalComplex.quasiIso C (ComplexShape.up ℤ)) _
(inferInstanceAs (QuasiIso f))
/-- The localization functor `HomotopyCategory C (ComplexShape.up ℤ) ⥤ DerivedCategory C`. -/
def Qh : HomotopyCategory C (ComplexShape.up ℤ) ⥤ DerivedCategory C :=
HomologicalComplexUpToQuasiIso.Qh
variable (C)
/-- The natural isomorphism `HomotopyCategory.quotient C (ComplexShape.up ℤ) ⋙ Qh ≅ Q`. -/
def quotientCompQhIso : HomotopyCategory.quotient C (ComplexShape.up ℤ) ⋙ Qh ≅ Q :=
HomologicalComplexUpToQuasiIso.quotientCompQhIso C (ComplexShape.up ℤ)
instance : Qh.IsLocalization (HomotopyCategory.quasiIso C (ComplexShape.up ℤ)) := by
dsimp [Qh, DerivedCategory]
infer_instance
instance : Qh.IsLocalization (HomotopyCategory.subcategoryAcyclic C).trW := by
rw [← HomotopyCategory.quasiIso_eq_subcategoryAcyclic_W]
infer_instance
noncomputable instance : Preadditive (DerivedCategory C) :=
Localization.preadditive Qh (HomotopyCategory.subcategoryAcyclic C).trW
instance : (Qh (C := C)).Additive :=
Localization.functor_additive Qh (HomotopyCategory.subcategoryAcyclic C).trW
instance : (Q (C := C)).Additive :=
Functor.additive_of_iso (quotientCompQhIso C)
noncomputable instance : HasZeroObject (DerivedCategory C) :=
Q.hasZeroObject_of_additive
noncomputable instance : HasShift (DerivedCategory C) ℤ :=
HasShift.localized Qh (HomotopyCategory.subcategoryAcyclic C).trW ℤ
noncomputable instance : (Qh (C := C)).CommShift ℤ :=
Functor.CommShift.localized Qh (HomotopyCategory.subcategoryAcyclic C).trW ℤ
noncomputable instance : (Q (C := C)).CommShift ℤ :=
Functor.CommShift.ofIso (quotientCompQhIso C) ℤ
instance : NatTrans.CommShift (quotientCompQhIso C).hom ℤ :=
Functor.CommShift.ofIso_compatibility (quotientCompQhIso C) ℤ
instance (n : ℤ) : (shiftFunctor (DerivedCategory C) n).Additive := by
rw [Localization.functor_additive_iff
Qh (HomotopyCategory.subcategoryAcyclic C).trW]
exact Functor.additive_of_iso (Qh.commShiftIso n)
noncomputable instance : Pretriangulated (DerivedCategory C) :=
Triangulated.Localization.pretriangulated
Qh (HomotopyCategory.subcategoryAcyclic C).trW
instance : (Qh (C := C)).IsTriangulated :=
Triangulated.Localization.isTriangulated_functor
Qh (HomotopyCategory.subcategoryAcyclic C).trW
noncomputable instance : IsTriangulated (DerivedCategory C) :=
Triangulated.Localization.isTriangulated
Qh (HomotopyCategory.subcategoryAcyclic C).trW
instance : (Qh (C := C)).mapArrow.EssSurj :=
Localization.essSurj_mapArrow _ (HomotopyCategory.subcategoryAcyclic C).trW
instance {D : Type*} [Category D] : ((Functor.whiskeringLeft _ _ D).obj (Qh (C := C))).Full :=
inferInstanceAs
(Localization.whiskeringLeftFunctor' _ (HomotopyCategory.quasiIso _ _) D).Full
instance {D : Type*} [Category D] : ((Functor.whiskeringLeft _ _ D).obj (Qh (C := C))).Faithful :=
inferInstanceAs
(Localization.whiskeringLeftFunctor' _ (HomotopyCategory.quasiIso _ _) D).Faithful
variable {C} in
lemma mem_distTriang_iff (T : Triangle (DerivedCategory C)) :
(T ∈ distTriang (DerivedCategory C)) ↔ ∃ (X Y : CochainComplex C ℤ) (f : X ⟶ Y),
Nonempty (T ≅ Q.mapTriangle.obj (CochainComplex.mappingCone.triangle f)) := by
constructor
· rintro ⟨T', e, ⟨X, Y, f, ⟨e'⟩⟩⟩
refine ⟨_, _, f, ⟨?_⟩⟩
exact e ≪≫ Qh.mapTriangle.mapIso e' ≪≫
(Functor.mapTriangleCompIso (HomotopyCategory.quotient C _) Qh).symm.app _ ≪≫
(Functor.mapTriangleIso (quotientCompQhIso C)).app _
· rintro ⟨X, Y, f, ⟨e⟩⟩
refine isomorphic_distinguished _ (Qh.map_distinguished _ ?_) _
(e ≪≫ (Functor.mapTriangleIso (quotientCompQhIso C)).symm.app _ ≪≫
(Functor.mapTriangleCompIso (HomotopyCategory.quotient C _) Qh).app _)
exact ⟨_, _, f, ⟨Iso.refl _⟩⟩
/-- The single functors `C ⥤ DerivedCategory C` for all `n : ℤ` along with
their compatibilities with shifts. -/
noncomputable def singleFunctors : SingleFunctors C (DerivedCategory C) ℤ :=
(HomotopyCategory.singleFunctors C).postcomp Qh
/-- The shift functor `C ⥤ DerivedCategory C` which sends `X : C` to the
single cochain complex with `X` sitting in degree `n : ℤ`. -/
noncomputable abbrev singleFunctor (n : ℤ) := (singleFunctors C).functor n
instance (n : ℤ) : (singleFunctor C n).Additive := by
dsimp [singleFunctor, singleFunctors]
infer_instance
/-- The isomorphism
`DerivedCategory.singleFunctors C ≅ (HomotopyCategory.singleFunctors C).postcomp Qh` given
by the definition of `DerivedCategory.singleFunctors`. -/
noncomputable def singleFunctorsPostcompQhIso :
singleFunctors C ≅ (HomotopyCategory.singleFunctors C).postcomp Qh :=
Iso.refl _
/-- The isomorphism
`DerivedCategory.singleFunctors C ≅ (CochainComplex.singleFunctors C).postcomp Q`. -/
noncomputable def singleFunctorsPostcompQIso :
singleFunctors C ≅ (CochainComplex.singleFunctors C).postcomp Q :=
(SingleFunctors.postcompFunctor C ℤ (Qh : _ ⥤ DerivedCategory C)).mapIso
(HomotopyCategory.singleFunctorsPostcompQuotientIso C) ≪≫
(CochainComplex.singleFunctors C).postcompPostcompIso (HomotopyCategory.quotient _ _) Qh ≪≫
SingleFunctors.postcompIsoOfIso
(CochainComplex.singleFunctors C) (quotientCompQhIso C)
lemma singleFunctorsPostcompQIso_hom_hom (n : ℤ) :
(singleFunctorsPostcompQIso C).hom.hom n = 𝟙 _ := by
ext X
dsimp [singleFunctorsPostcompQIso, HomotopyCategory.singleFunctorsPostcompQuotientIso,
quotientCompQhIso, HomologicalComplexUpToQuasiIso.quotientCompQhIso]
rw [CategoryTheory.Functor.map_id, SingleFunctors.id_hom, NatTrans.id_app]
erw [Category.id_comp, Category.id_comp]
rfl
lemma singleFunctorsPostcompQIso_inv_hom (n : ℤ) :
(singleFunctorsPostcompQIso C).inv.hom n = 𝟙 _ := by
ext X
dsimp [singleFunctorsPostcompQIso, HomotopyCategory.singleFunctorsPostcompQuotientIso,
quotientCompQhIso, HomologicalComplexUpToQuasiIso.quotientCompQhIso]
erw [CategoryTheory.Functor.map_id]
rw [SingleFunctors.id_hom, NatTrans.id_app]
erw [Category.id_comp, Category.id_comp]
rfl
lemma isIso_Q_map_iff_quasiIso {K L : CochainComplex C ℤ} (φ : K ⟶ L) :
IsIso (Q.map φ) ↔ QuasiIso φ := by
apply HomologicalComplexUpToQuasiIso.isIso_Q_map_iff_mem_quasiIso
end DerivedCategory
|
lint-style.lean
|
/-
Copyright (c) 2024 Michael Rothgang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Rothgang
-/
import Lake.CLI.Main
import Lean.Elab.ParseImportsFast
import Batteries.Data.String.Basic
import Mathlib.Tactic.Linter.TextBased
import Cli.Basic
/-!
# Text-based style linters
This file defines the `lint-style` executable which runs all text-based style linters.
The linters themselves are defined in `Mathlib/Tactic/Linter/TextBased.lean`.
In addition, this checks that
- `Mathlib.Init` is (transitively) imported in all of mathlib, and
- every file in `scripts` is documented in its top-level README.
-/
open Cli Lean.Linter Mathlib.Linter.TextBased System.FilePath
/-- Additional imports generated by `mk_all`. -/
def explicitImports : Array Lean.Name := #[`Batteries, `Std]
/-- Remove the additional imports generated by `mk_all` so that only mathlib modules remain. -/
def eraseExplicitImports (names : Array Lean.Name) : Array Lean.Name :=
explicitImports.foldl Array.erase names
/-- Get the root package of the Lake workspace we are running in. -/
def getWorkspaceRoot : IO Lake.Package := do
let (elanInstall?, leanInstall?, lakeInstall?) ← Lake.findInstall?
let config ← Lake.MonadError.runEIO <| Lake.mkLoadConfig { elanInstall?, leanInstall?, lakeInstall? }
let some workspace ← Lake.loadWorkspace config |>.toBaseIO
| throw <| IO.userError "failed to load Lake workspace"
return workspace.root
/-- Convert the options that Lake knows into the option that Lean knows. -/
def toLeanOptions (opts : Array Lake.LeanOption) : Lean.Options :=
opts.foldl (init := Lean.Options.empty) fun opts o =>
-- Strip off the `weak.` prefix, like Lean does when parsing command line arguments.
if o.name.getRoot == `weak
then
opts.insert (o.name.replacePrefix `weak Lean.Name.anonymous) o.value.toDataValue
else
opts.insert o.name o.value.toDataValue
/-- Determine the `Lean.Options` from the Lakefile of the current project.
We have to do this since style linters do not run in the `CoreM`/`CommandElabM` monads,
and so they do not get access to the options in scope.
Please do not confuse this with the Lean options at the moment that `lint-style` was compiled.
-/
def getLakefileLeanOptions : IO Lean.Options := do
let root ← getWorkspaceRoot
-- Some projects declare options in the root package.
let rootOpts := root.leanOptions
-- Other projects, like Mathlib, declare options in the targets.
-- Here we use the default targets, since that probably contains the modules we'll be linting.
let defaultOpts := root.defaultTargets.flatMap fun target ↦
if let some lib := root.findLeanLib? target then
lib.config.leanOptions
else if let some exe := root.findLeanExe? target then
exe.config.leanOptions
else
#[]
return Lean.LeanOptions.toOptions (rootOpts.appendArray defaultOpts)
/-- Check that `Mathlib.Init` is transitively imported in all of Mathlib -/
register_option linter.checkInitImports : Bool := { defValue := false }
/-- Check that `Mathlib.Init` is transitively imported in all of Mathlib.
Moreover, every file imported in `Mathlib.Init` should in turn import the `Header` linter
(except for the header linter itself, of course).
Return the number of modules which violated one of these rules.
-/
def missingInitImports (opts : LinterOptions) : IO Nat := do
unless getLinterValue linter.checkInitImports opts do return 0
-- Find any file in the Mathlib directory which does not contain any Mathlib import.
-- We simply parse `Mathlib.lean`, as CI ensures this file is up to date.
let allModuleNames := eraseExplicitImports (← findImports "Mathlib.lean")
let mut modulesWithoutMathlibImports := #[]
let mut importsHeaderLinter := #[]
for module in allModuleNames do
let path := System.mkFilePath (module.components.map fun n ↦ n.toString)|>.addExtension "lean"
let imports ← findImports path
let hasNoMathlibImport := imports.all fun name ↦ name.getRoot != `Mathlib
if hasNoMathlibImport then
modulesWithoutMathlibImports := modulesWithoutMathlibImports.push module
if imports.contains `Mathlib.Tactic.Linter.Header then
importsHeaderLinter := importsHeaderLinter.push module
-- Every file importing the `header` linter should be imported in `Mathlib/Init.lean` itself.
-- (Downstream files should import `Mathlib.Init` and not the header linter.)
-- The only exception are auto-generated import-only files.
let initImports ← findImports ("Mathlib" / "Init.lean")
let mismatch := importsHeaderLinter.filter (fun mod ↦
![`Mathlib, `Mathlib.Tactic, `Mathlib.Init].contains mod && !initImports.contains mod)
-- This file is transitively imported by `Mathlib.Init`.
|>.erase `Mathlib.Tactic.DeclarationNames
if mismatch.size > 0 then
IO.eprintln s!"error: the following {mismatch.size} module(s) import the `header` linter \
directly, but should import Mathlib.Init instead: {mismatch}\n\
The `header` linter is included in Mathlib.Init, and every file in Mathlib \
should import Mathlib.Init.\nPlease adjust the imports accordingly."
return mismatch.size
-- Now, it only remains to check that every module (except for the Header linter itself)
-- imports some file in Mathlib.
let missing := modulesWithoutMathlibImports.erase `Mathlib.Tactic.Linter.Header
-- This file is imported by `Mathlib/Tactic/Linter/Header.lean`.
|>.erase `Mathlib.Tactic.Linter.DirectoryDependency
if missing.size > 0 then
IO.eprintln s!"error: the following {missing.size} module(s) do not import Mathlib.Init: \
{missing}"
return missing.size
return 0
/-- Verify that every file in the `scripts` directory is documented in `scripts/README.md` -/
register_option linter.allScriptsDocumented : Bool := { defValue := false }
/-- Verifies that every file in the `scripts` directory is documented in `scripts/README.md`.
Return the number of undocumented scripts. -/
def undocumentedScripts (opts : LinterOptions) : IO Nat := do
unless getLinterValue linter.allScriptsDocumented opts do return 0
-- Retrieve all scripts (except for the `bench` directory).
let allScripts ← (walkDir "scripts" fun p ↦ pure (p.components.getD 1 "" != "bench"))
let allScripts := allScripts.erase ("scripts" / "bench")|>.erase ("scripts" / "README.md")
-- Check if the README text contains each file enclosed in backticks.
let readme : String ← IO.FS.readFile ("scripts" / "README.md")
-- These are data files for linter exceptions: don't complain about these *for now*.
let dataFiles := #["noshake.json", "nolints-style.txt"]
-- For now, there are no scripts in sub-directories that should be documented.
let fileNames := allScripts.map (·.fileName.get!)
let undocumented := fileNames.filter fun script ↦
!readme.containsSubstr s!"`{script}`" && !dataFiles.contains script
if undocumented.size > 0 then
IO.println s!"error: found {undocumented.size} undocumented script(s): \
please describe the script(s) in 'scripts/README.md'\n \
{String.intercalate "," undocumented.toList}"
return undocumented.size
/-- Implementation of the `lint-style` command line program. -/
def lintStyleCli (args : Cli.Parsed) : IO UInt32 := do
-- Use the environment declared in Mathlib.Tactic.Linter.TextBased to determine the linter sets.
Lean.initSearchPath (← Lean.findSysroot)
let sets ← unsafe Lean.withImportModules #[{module := `Mathlib.Tactic.Linter.TextBased}] {}
fun env => pure <| linterSetsExt.getState env
let opts : LinterOptions := {
toOptions := ← getLakefileLeanOptions,
linterSets := sets,
}
let style : ErrorFormat := match args.hasFlag "github" with
| true => ErrorFormat.github
| false => ErrorFormat.humanReadable
let fix := args.hasFlag "fix"
-- If no modules are specified, use the defaults from the Lakefile.
let originModules ← match args.variableArgsAs! String with
| #[] =>
-- If none are specified, lint the default Lake modules.
let (elanInstall?, leanInstall?, lakeInstall?) ← Lake.findInstall?
let config ← Lake.MonadError.runEIO <| Lake.mkLoadConfig { elanInstall?, leanInstall?, lakeInstall? }
let some workspace ← Lake.loadWorkspace config |>.toBaseIO
| throw <| IO.userError "failed to load Lake workspace"
pure <| workspace.root.defaultTargets.flatMap fun target =>
if let some lib := workspace.root.findLeanLib? target then
lib.roots
else if let some exe := workspace.root.findLeanExe? target then
#[exe.config.root]
else
#[]
| mods => do
let mut result := #[]
for mod in mods do
let modParse := Lean.ParseImports.moduleIdent mod {}
match modParse.error? with
| none => result := result.append <| modParse.imports.map Lean.Import.module
| some err => throw <| IO.userError s!"could not parse module name {mod}: {err}"
pure result
-- Get all the imports, but only those in the same package.
let pkgs := originModules.map (·.components.head!)
Lean.initSearchPath (← Lean.findSysroot)
let searchPath ← Lean.getSrcSearchPath
let allModuleNames ← originModules.flatMapM fun mod => do
let imports ← match ← searchPath.findWithExt "lean" mod with
| some file => findImports file
| none => throw <| IO.userError s!"could not find module with name {mod}"
pure <| imports.filter (·.components.head! ∈ pkgs)
-- Read the `nolints` file, with manual exceptions for the linter.
-- NB. We pass these lints to `lintModules` explicitly to prevent cache invalidation bugs:
-- if the text-based linter read the file itself, replaying a cached build of that
-- file could re-use an outdated version of the nolints file.
-- (For syntax linters, such a bug actually occurred in mathlib.)
-- This script is re-run each time, hence is immune to such issues.
let filename : System.FilePath := ("scripts" / "nolints-style.txt")
let nolints ← try
IO.FS.lines filename
catch _ =>
IO.eprintln s!"warning: nolints file could not be read; treating as empty: {filename}"
pure #[]
let numberErrors := (← lintModules opts nolints allModuleNames style fix)
+ (← missingInitImports opts).toUInt32 + (← undocumentedScripts opts).toUInt32
+ (← modulesNotUpperCamelCase opts allModuleNames).toUInt32
+ (← modulesForbiddenWindows opts allModuleNames).toUInt32
-- If run with the `--fix` argument, return a zero exit code.
-- Otherwise, make sure to return an exit code of at most 125,
-- so this return value can be used further in shell scripts.
if args.hasFlag "fix" then
return 0
else return min numberErrors 125
/-- Setting up command line options and help text for `lake exe lint-style`. -/
-- so far, no help options or so: perhaps that is fine?
def lintStyle : Cmd := `[Cli|
«lint-style» VIA lintStyleCli; ["0.0.1"]
"Run text-based style linters on every Lean file in specified modules.
Print errors about any unexpected style errors to standard output."
FLAGS:
github; "Print errors in a format suitable for github problem matchers\n\
otherwise, produce human-readable output"
fix; "Automatically fix the style error, if possible"
ARGS:
...modules : String; "Which modules, and their imports, will be linted.\n\
If no modules are specified, the linter runs on the default Lake module(s)."
]
/-- The entry point to the `lake exe lint-style` command. -/
def main (args : List String) : IO UInt32 := do lintStyle.validate args
|
OrderedMonoid.lean
|
/-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Abhimanyu Pallavi Sudhir
-/
import Mathlib.Algebra.Module.Pi
import Mathlib.Algebra.Order.Monoid.Canonical.Defs
import Mathlib.Order.Filter.Germ.Basic
/-!
# Ordered monoid instances on the space of germs of a function at a filter
For each of the following structures we prove that if `β` has this structure, then so does
`Germ l β`:
* `OrderedCancelCommMonoid` and `OrderedCancelAddCommMonoid`.
## Tags
filter, germ
-/
namespace Filter.Germ
variable {α : Type*} {β : Type*} {l : Filter α}
@[to_additive]
instance instIsOrderedMonoid [CommMonoid β] [PartialOrder β] [IsOrderedMonoid β] :
IsOrderedMonoid (Germ l β) where
mul_le_mul_left f g := inductionOn₂ f g fun _ _ H h ↦ inductionOn h fun _ ↦ H.mono
fun _ H ↦ mul_le_mul_left' H _
@[to_additive]
instance instIsOrderedCancelMonoid [CommMonoid β] [PartialOrder β] [IsOrderedCancelMonoid β] :
IsOrderedCancelMonoid (Germ l β) where
le_of_mul_le_mul_left f g h := inductionOn₃ f g h fun _ _ _ H ↦ H.mono
fun _ ↦ le_of_mul_le_mul_left'
@[to_additive]
instance instCanonicallyOrderedMul [Mul β] [LE β] [CanonicallyOrderedMul β] :
CanonicallyOrderedMul (Germ l β) where
le_self_mul x y := inductionOn₂ x y fun _ _ ↦ Eventually.of_forall fun _ ↦ le_self_mul
end Filter.Germ
|
UniqueDifferential.lean
|
/-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Floris van Doorn
-/
import Mathlib.Geometry.Manifold.MFDeriv.Atlas
import Mathlib.Geometry.Manifold.VectorBundle.Basic
/-!
# Unique derivative sets in manifolds
In this file, we prove various properties of unique derivative sets in manifolds.
* `image_denseRange`: suppose `f` is differentiable on `s` and its derivative at every point of `s`
has dense range. If `s` has the unique differential property, then so does `f '' s`.
* `uniqueMDiffOn_preimage`: the unique differential property is preserved by local diffeomorphisms
* `uniqueDiffOn_target_inter`: the unique differential property is preserved by
pullbacks of extended charts
* `tangentBundle_proj_preimage`: if `s` has the unique differential property,
its preimage under the tangent bundle projection also has
-/
noncomputable section
open scoped Manifold
open Set
/-! ### Unique derivative sets in manifolds -/
section UniqueMDiff
variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {E : Type*} [NormedAddCommGroup E]
[NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] {I : ModelWithCorners 𝕜 E H} {M : Type*}
[TopologicalSpace M] [ChartedSpace H M] {E' : Type*}
[NormedAddCommGroup E'] [NormedSpace 𝕜 E'] {H' : Type*} [TopologicalSpace H']
{I' : ModelWithCorners 𝕜 E' H'} {M' : Type*} [TopologicalSpace M'] [ChartedSpace H' M']
{M'' : Type*} [TopologicalSpace M''] [ChartedSpace H' M'']
{s : Set M} {x : M}
section
/-- If `s` has the unique differential property at `x`, `f` is differentiable within `s` at x` and
its derivative has dense range, then `f '' s` has the unique differential property at `f x`. -/
theorem UniqueMDiffWithinAt.image_denseRange (hs : UniqueMDiffWithinAt I s x)
{f : M → M'} {f' : E →L[𝕜] E'} (hf : HasMFDerivWithinAt I I' f s x f')
(hd : DenseRange f') : UniqueMDiffWithinAt I' (f '' s) (f x) := by
/- Rewrite in coordinates, apply `HasFDerivWithinAt.uniqueDiffWithinAt`. -/
have := hs.inter' <| hf.1 (extChartAt_source_mem_nhds (I := I') (f x))
refine (((hf.2.mono ?sub1).uniqueDiffWithinAt this hd).mono ?sub2).congr_pt ?pt
case pt => simp only [mfld_simps]
case sub1 => mfld_set_tac
case sub2 =>
rintro _ ⟨y, ⟨⟨hys, hfy⟩, -⟩, rfl⟩
exact ⟨⟨_, hys, ((extChartAt I' (f x)).left_inv hfy).symm⟩, mem_range_self _⟩
/-- If `s` has the unique differential property, `f` is differentiable on `s` and its derivative
at every point of `s` has dense range, then `f '' s` has the unique differential property.
This version uses the `HasMFDerivWithinAt` predicate. -/
theorem UniqueMDiffOn.image_denseRange' (hs : UniqueMDiffOn I s) {f : M → M'}
{f' : M → E →L[𝕜] E'} (hf : ∀ x ∈ s, HasMFDerivWithinAt I I' f s x (f' x))
(hd : ∀ x ∈ s, DenseRange (f' x)) :
UniqueMDiffOn I' (f '' s) :=
forall_mem_image.2 fun x hx ↦ (hs x hx).image_denseRange (hf x hx) (hd x hx)
/-- If `s` has the unique differential property, `f` is differentiable on `s` and its derivative
at every point of `s` has dense range, then `f '' s` has the unique differential property. -/
theorem UniqueMDiffOn.image_denseRange (hs : UniqueMDiffOn I s) {f : M → M'}
(hf : MDifferentiableOn I I' f s) (hd : ∀ x ∈ s, DenseRange (mfderivWithin I I' f s x)) :
UniqueMDiffOn I' (f '' s) :=
hs.image_denseRange' (fun x hx ↦ (hf x hx).hasMFDerivWithinAt) hd
protected theorem UniqueMDiffWithinAt.preimage_partialHomeomorph (hs : UniqueMDiffWithinAt I s x)
{e : PartialHomeomorph M M'} (he : e.MDifferentiable I I') (hx : x ∈ e.source) :
UniqueMDiffWithinAt I' (e.target ∩ e.symm ⁻¹' s) (e x) := by
rw [← e.image_source_inter_eq', inter_comm]
exact (hs.inter (e.open_source.mem_nhds hx)).image_denseRange
(he.mdifferentiableAt hx).hasMFDerivAt.hasMFDerivWithinAt
(he.mfderiv_surjective hx).denseRange
/-- If a set has the unique differential property, then its image under a local
diffeomorphism also has the unique differential property. -/
theorem UniqueMDiffOn.uniqueMDiffOn_preimage (hs : UniqueMDiffOn I s) {e : PartialHomeomorph M M'}
(he : e.MDifferentiable I I') : UniqueMDiffOn I' (e.target ∩ e.symm ⁻¹' s) := fun _x hx ↦
e.right_inv hx.1 ▸ (hs _ hx.2).preimage_partialHomeomorph he (e.map_target hx.1)
variable [IsManifold I 1 M] in
/-- If a set in a manifold has the unique derivative property, then its pullback by any extended
chart, in the vector space, also has the unique derivative property. -/
theorem UniqueMDiffOn.uniqueMDiffOn_target_inter (hs : UniqueMDiffOn I s) (x : M) :
UniqueMDiffOn 𝓘(𝕜, E) ((extChartAt I x).target ∩ (extChartAt I x).symm ⁻¹' s) := by
-- this is just a reformulation of `UniqueMDiffOn.uniqueMDiffOn_preimage`, using as `e`
-- the local chart at `x`.
rw [← PartialEquiv.image_source_inter_eq', inter_comm, extChartAt_source]
exact (hs.inter (chartAt H x).open_source).image_denseRange'
(fun y hy ↦ hasMFDerivWithinAt_extChartAt hy.2)
fun y hy ↦ ((mdifferentiable_chart _).mfderiv_surjective hy.2).denseRange
variable [IsManifold I 1 M] in
/-- If a set in a manifold has the unique derivative property, then its pullback by any extended
chart, in the vector space, also has the unique derivative property. -/
theorem UniqueMDiffOn.uniqueDiffOn_target_inter (hs : UniqueMDiffOn I s) (x : M) :
UniqueDiffOn 𝕜 ((extChartAt I x).target ∩ (extChartAt I x).symm ⁻¹' s) :=
(hs.uniqueMDiffOn_target_inter x).uniqueDiffOn
variable [IsManifold I 1 M] in
theorem UniqueMDiffOn.uniqueDiffWithinAt_range_inter (hs : UniqueMDiffOn I s) (x : M) (y : E)
(hy : y ∈ (extChartAt I x).target ∩ (extChartAt I x).symm ⁻¹' s) :
UniqueDiffWithinAt 𝕜 (range I ∩ (extChartAt I x).symm ⁻¹' s) y := by
apply (hs.uniqueDiffOn_target_inter x y hy).mono
apply inter_subset_inter_left _ (extChartAt_target_subset_range x)
variable [IsManifold I 1 M] in
/-- When considering functions between manifolds, this statement shows up often. It entails
the unique differential of the pullback in extended charts of the set where the function can
be read in the charts. -/
theorem UniqueMDiffOn.uniqueDiffOn_inter_preimage (hs : UniqueMDiffOn I s) (x : M) (y : M'')
{f : M → M''} (hf : ContinuousOn f s) :
UniqueDiffOn 𝕜
((extChartAt I x).target ∩ (extChartAt I x).symm ⁻¹' (s ∩ f ⁻¹' (extChartAt I' y).source)) :=
haveI : UniqueMDiffOn I (s ∩ f ⁻¹' (extChartAt I' y).source) := by
intro z hz
apply (hs z hz.1).inter'
apply (hf z hz.1).preimage_mem_nhdsWithin
exact (isOpen_extChartAt_source y).mem_nhds hz.2
this.uniqueDiffOn_target_inter _
end
open Bundle
variable {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] {Z : M → Type*}
[TopologicalSpace (TotalSpace F Z)] [∀ b, TopologicalSpace (Z b)] [FiberBundle F Z]
private lemma UniqueMDiffWithinAt.bundle_preimage_aux {p : TotalSpace F Z}
(hs : UniqueMDiffWithinAt I s p.proj) (h's : s ⊆ (trivializationAt F Z p.proj).baseSet) :
UniqueMDiffWithinAt (I.prod 𝓘(𝕜, F)) (π F Z ⁻¹' s) p := by
suffices ((extChartAt I p.proj).symm ⁻¹' s ∩ range I) ×ˢ univ ⊆
(extChartAt (I.prod 𝓘(𝕜, F)) p).symm ⁻¹' (TotalSpace.proj ⁻¹' s) ∩ range (I.prod 𝓘(𝕜, F)) by
let w := (extChartAt (I.prod 𝓘(𝕜, F)) p p).2
have A : extChartAt (I.prod 𝓘(𝕜, F)) p p = (extChartAt I p.1 p.1, w) := by
ext
· simp [FiberBundle.chartedSpace_chartAt]
· rfl
simp only [UniqueMDiffWithinAt, A] at hs ⊢
exact (hs.prod (uniqueDiffWithinAt_univ (x := w))).mono this
rcases p with ⟨x, v⟩
dsimp
rintro ⟨z, w⟩ ⟨hz, -⟩
simp only [mem_inter_iff, mem_preimage, Function.comp_apply,
mem_range] at hz
simp only [FiberBundle.chartedSpace_chartAt, PartialHomeomorph.coe_trans_symm, mem_inter_iff,
mem_preimage, Function.comp_apply, mem_range]
constructor
· rw [PartialEquiv.prod_symm, PartialEquiv.refl_symm, PartialEquiv.prod_coe,
ModelWithCorners.toPartialEquiv_coe_symm, PartialEquiv.refl_coe,
PartialHomeomorph.prod_symm, PartialHomeomorph.refl_symm, PartialHomeomorph.prod_apply,
PartialHomeomorph.refl_apply]
convert hz.1
apply Trivialization.proj_symm_apply'
exact h's hz.1
· rcases hz.2 with ⟨u, rfl⟩
exact ⟨(u, w), rfl⟩
/-- In a fiber bundle, the preimage under the projection of a set with unique differentials
in the base has unique differentials in the bundle. -/
theorem UniqueMDiffWithinAt.bundle_preimage {p : TotalSpace F Z}
(hs : UniqueMDiffWithinAt I s p.proj) :
UniqueMDiffWithinAt (I.prod 𝓘(𝕜, F)) (π F Z ⁻¹' s) p := by
suffices UniqueMDiffWithinAt (I.prod 𝓘(𝕜, F))
(π F Z ⁻¹' (s ∩ (trivializationAt F Z p.proj).baseSet)) p from this.mono (by simp)
apply UniqueMDiffWithinAt.bundle_preimage_aux (hs.inter _) inter_subset_right
exact IsOpen.mem_nhds (trivializationAt F Z p.proj).open_baseSet
(FiberBundle.mem_baseSet_trivializationAt' p.proj)
variable (Z)
/-- In a fiber bundle, the preimage under the projection of a set with unique differentials
in the base has unique differentials in the bundle. Version with a point `⟨b, x⟩`. -/
theorem UniqueMDiffWithinAt.bundle_preimage' {b : M} (hs : UniqueMDiffWithinAt I s b)
(x : Z b) : UniqueMDiffWithinAt (I.prod 𝓘(𝕜, F)) (π F Z ⁻¹' s) ⟨b, x⟩ :=
hs.bundle_preimage (p := ⟨b, x⟩)
/-- In a fiber bundle, the preimage under the projection of a set with unique differentials
in the base has unique differentials in the bundle. -/
theorem UniqueMDiffOn.bundle_preimage (hs : UniqueMDiffOn I s) :
UniqueMDiffOn (I.prod 𝓘(𝕜, F)) (π F Z ⁻¹' s) := fun _p hp ↦
(hs _ hp).bundle_preimage
-- TODO: move me to `Mathlib/Geometry/Manifold/VectorBundle/MDifferentiable.lean`
variable [∀ b, AddCommMonoid (Z b)] [∀ b, Module 𝕜 (Z b)] [VectorBundle 𝕜 F Z]
theorem Trivialization.mdifferentiable [ContMDiffVectorBundle 1 F Z I]
(e : Trivialization F (π F Z)) [MemTrivializationAtlas e] :
e.MDifferentiable (I.prod 𝓘(𝕜, F)) (I.prod 𝓘(𝕜, F)) :=
⟨e.contMDiffOn.mdifferentiableOn le_rfl, e.contMDiffOn_symm.mdifferentiableOn le_rfl⟩
end UniqueMDiff
|
Quotient.lean
|
/-
Copyright (c) 2022 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.Algebra.Field.Basic
import Mathlib.Algebra.Order.Group.Unbundled.Int
import Mathlib.Algebra.Module.NatInt
import Mathlib.GroupTheory.QuotientGroup.Defs
import Mathlib.Algebra.Group.Subgroup.ZPowers.Basic
/-!
# Lemmas about quotients in characteristic zero
-/
variable {R : Type*} [DivisionRing R] [CharZero R] {p : R}
namespace AddSubgroup
/-- `z • r` is a multiple of `p` iff `r` is `k * (p / z)` above a multiple of `p`, where
`0 ≤ k < |z|`. -/
theorem zsmul_mem_zmultiples_iff_exists_sub_div {r : R} {z : ℤ} (hz : z ≠ 0) :
z • r ∈ AddSubgroup.zmultiples p ↔
∃ k : Fin z.natAbs, r - (k : ℕ) • (p / z : R) ∈ AddSubgroup.zmultiples p := by
rw [AddSubgroup.mem_zmultiples_iff]
simp_rw [AddSubgroup.mem_zmultiples_iff, div_eq_mul_inv, ← smul_mul_assoc, eq_sub_iff_add_eq]
have hz' : (z : R) ≠ 0 := Int.cast_ne_zero.mpr hz
conv_rhs => simp +singlePass only [← (mul_right_injective₀ hz').eq_iff]
simp_rw [← zsmul_eq_mul, smul_add, ← mul_smul_comm, zsmul_eq_mul (z : R)⁻¹, mul_inv_cancel₀ hz',
mul_one, ← natCast_zsmul, smul_smul, ← add_smul]
constructor
· rintro ⟨k, h⟩
simp_rw [← h]
refine ⟨⟨(k % z).toNat, ?_⟩, k / z, ?_⟩
· rw [← Int.ofNat_lt, Int.toNat_of_nonneg (Int.emod_nonneg _ hz)]
exact (Int.emod_lt_abs _ hz).trans_eq (Int.abs_eq_natAbs _)
rw [Fin.val_mk, Int.toNat_of_nonneg (Int.emod_nonneg _ hz)]
nth_rewrite 3 [← Int.ediv_add_emod k z]
rfl
· rintro ⟨k, n, h⟩
exact ⟨_, h⟩
theorem nsmul_mem_zmultiples_iff_exists_sub_div {r : R} {n : ℕ} (hn : n ≠ 0) :
n • r ∈ AddSubgroup.zmultiples p ↔
∃ k : Fin n, r - (k : ℕ) • (p / n : R) ∈ AddSubgroup.zmultiples p := by
rw [← natCast_zsmul r, zsmul_mem_zmultiples_iff_exists_sub_div (Int.natCast_ne_zero.mpr hn),
Int.cast_natCast]
rfl
end AddSubgroup
namespace QuotientAddGroup
theorem zmultiples_zsmul_eq_zsmul_iff {ψ θ : R ⧸ AddSubgroup.zmultiples p} {z : ℤ} (hz : z ≠ 0) :
z • ψ = z • θ ↔ ∃ k : Fin z.natAbs, ψ = θ + ((k : ℕ) • (p / z) : R) := by
induction ψ using Quotient.inductionOn
induction θ using Quotient.inductionOn
-- Porting note: Introduced Zp notation to shorten lines
let Zp := AddSubgroup.zmultiples p
have : (Quotient.mk _ : R → R ⧸ Zp) = ((↑) : R → R ⧸ Zp) := rfl
simp only [Zp, this]
simp_rw [← QuotientAddGroup.mk_zsmul, ← QuotientAddGroup.mk_add,
QuotientAddGroup.eq_iff_sub_mem, ← smul_sub, ← sub_sub]
exact AddSubgroup.zsmul_mem_zmultiples_iff_exists_sub_div hz
theorem zmultiples_nsmul_eq_nsmul_iff {ψ θ : R ⧸ AddSubgroup.zmultiples p} {n : ℕ} (hz : n ≠ 0) :
n • ψ = n • θ ↔ ∃ k : Fin n, ψ = θ + (k : ℕ) • (p / n : R) := by
rw [← natCast_zsmul ψ, ← natCast_zsmul θ,
zmultiples_zsmul_eq_zsmul_iff (Int.natCast_ne_zero.mpr hz), Int.cast_natCast]
rfl
end QuotientAddGroup
|
PUnit.lean
|
/-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import Mathlib.Algebra.Module.Defs
import Mathlib.Algebra.Ring.Action.Basic
import Mathlib.Algebra.Ring.PUnit
/-!
# Instances on PUnit
This file collects facts about module structures on the one-element type
-/
namespace PUnit
variable {R S : Type*}
@[to_additive]
instance smul : SMul R PUnit :=
⟨fun _ _ => unit⟩
@[to_additive (attr := simp)]
theorem smul_eq {R : Type*} (y : PUnit) (r : R) : r • y = unit :=
rfl
@[to_additive]
instance : IsCentralScalar R PUnit :=
⟨fun _ _ => rfl⟩
@[to_additive]
instance : SMulCommClass R S PUnit :=
⟨fun _ _ _ => rfl⟩
@[to_additive]
instance instIsScalarTowerOfSMul [SMul R S] : IsScalarTower R S PUnit :=
⟨fun _ _ _ => rfl⟩
instance smulWithZero [Zero R] : SMulWithZero R PUnit where
__ := PUnit.smul
smul_zero := by subsingleton
zero_smul := by subsingleton
instance mulAction [Monoid R] : MulAction R PUnit where
__ := PUnit.smul
one_smul := by subsingleton
mul_smul := by subsingleton
instance distribMulAction [Monoid R] : DistribMulAction R PUnit where
__ := PUnit.mulAction
smul_zero := by subsingleton
smul_add := by subsingleton
instance mulDistribMulAction [Monoid R] : MulDistribMulAction R PUnit where
__ := PUnit.mulAction
smul_mul := by subsingleton
smul_one := by subsingleton
instance mulSemiringAction [Semiring R] : MulSemiringAction R PUnit :=
{ PUnit.distribMulAction, PUnit.mulDistribMulAction with }
instance mulActionWithZero [MonoidWithZero R] : MulActionWithZero R PUnit :=
{ PUnit.mulAction, PUnit.smulWithZero with }
instance module [Semiring R] : Module R PUnit where
__ := PUnit.distribMulAction
add_smul := by subsingleton
zero_smul := by subsingleton
@[to_additive]
instance : SMul PUnit R where smul _ x := x
/-- The one-element type acts trivially on every element. -/
@[to_additive (attr := simp)]
lemma smul_eq' (r : PUnit) (a : R) : r • a = a := rfl
@[to_additive] instance [SMul R S] : SMulCommClass PUnit R S := ⟨by simp⟩
instance [SMul R S] : IsScalarTower PUnit R S := ⟨by simp⟩
instance : MulAction PUnit R where
__ := inferInstanceAs (SMul PUnit R)
one_smul _ := rfl
mul_smul _ _ _ := rfl
instance [Zero R] : SMulZeroClass PUnit R where
__ := inferInstanceAs (SMul PUnit R)
smul_zero _ := rfl
instance [AddMonoid R] : DistribMulAction PUnit R where
__ := inferInstanceAs (MulAction PUnit R)
__ := inferInstanceAs (SMulZeroClass PUnit R)
smul_add _ _ _ := rfl
end PUnit
|
Pullback.lean
|
/-
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.Category.ModuleCat.Presheaf.Generator
import Mathlib.Algebra.Category.ModuleCat.Presheaf.Pushforward
import Mathlib.CategoryTheory.Adjunction.PartialAdjoint
/-!
# Pullback of presheaves of modules
Let `F : C ⥤ D` be a functor, `R : Dᵒᵖ ⥤ RingCat` and `S : Cᵒᵖ ⥤ RingCat` be presheaves
of rings, and `φ : S ⟶ F.op ⋙ R` be a morphism of presheaves of rings,
we introduce the pullback functor `pullback : PresheafOfModules S ⥤ PresheafOfModules R`
as the left adjoint of `pushforward : PresheafOfModules R ⥤ PresheafOfModules S`.
The existence of this left adjoint functor is obtained under suitable universe assumptions.
-/
universe v v₁ v₂ u₁ u₂ u
open CategoryTheory Limits Opposite
namespace PresheafOfModules
section
variable {C : Type u₁} [Category.{v₁} C] {D : Type u₂} [Category.{v₂} D]
{F : C ⥤ D} {R : Dᵒᵖ ⥤ RingCat.{u}} {S : Cᵒᵖ ⥤ RingCat.{u}} (φ : S ⟶ F.op ⋙ R)
[(pushforward.{v} φ).IsRightAdjoint]
/-- The pullback functor `PresheafOfModules S ⥤ PresheafOfModules R` induced by
a morphism of presheaves of rings `S ⟶ F.op ⋙ R`, defined as the left adjoint
functor to the pushforward, when it exists. -/
noncomputable def pullback : PresheafOfModules.{v} S ⥤ PresheafOfModules.{v} R :=
(pushforward.{v} φ).leftAdjoint
/-- Given a morphism of presheaves of rings `S ⟶ F.op ⋙ R`, this is the adjunction
between associated pullback and pushforward functors on the categories
of presheaves of modules. -/
noncomputable def pullbackPushforwardAdjunction : pullback.{v} φ ⊣ pushforward.{v} φ :=
Adjunction.ofIsRightAdjoint (pushforward φ)
/-- Given a morphism of presheaves of rings `φ : S ⟶ F.op ⋙ R`, this is the property
that the (partial) left adjoint functor of `pushforward φ` is defined
on a certain object `M : PresheafOfModules S`. -/
abbrev pullbackObjIsDefined : ObjectProperty (PresheafOfModules.{v} S) :=
(pushforward φ).leftAdjointObjIsDefined
@[deprecated (since := "2025-03-06")]
alias PullbackObjIsDefined := pullbackObjIsDefined
end
section
variable {C D : Type u} [SmallCategory C] [SmallCategory D]
{F : C ⥤ D} {R : Dᵒᵖ ⥤ RingCat.{u}} {S : Cᵒᵖ ⥤ RingCat.{u}} (φ : S ⟶ F.op ⋙ R)
/-- Given a morphism of presheaves of rings `φ : S ⟶ F.op ⋙ R`, where `F : C ⥤ D`,
`S : Cᵒᵖ ⥤ RingCat`, `R : Dᵒᵖ ⥤ RingCat` and `X : C`, the (partial) left adjoint
functor of `pushforward φ` is defined on the object `(free S).obj (yoneda.obj X)`:
this object shall be mapped to `(free R).obj (yoneda.obj (F.obj X))`. -/
noncomputable def pushforwardCompCoyonedaFreeYonedaCorepresentableBy (X : C) :
(pushforward φ ⋙ coyoneda.obj (op ((free S).obj (yoneda.obj X)))).CorepresentableBy
((free R).obj (yoneda.obj (F.obj X))) where
homEquiv {M} := (freeYonedaEquiv).trans
(freeYonedaEquiv (M := (pushforward φ).obj M)).symm
homEquiv_comp {M N} g f := freeYonedaEquiv.injective (by
dsimp
erw [Equiv.apply_symm_apply, freeYonedaEquiv_comp]
conv_rhs => erw [freeYonedaEquiv_comp]
erw [Equiv.apply_symm_apply]
rfl)
lemma pullbackObjIsDefined_free_yoneda (X : C) :
pullbackObjIsDefined φ ((free S).obj (yoneda.obj X)) :=
(pushforwardCompCoyonedaFreeYonedaCorepresentableBy φ X).isCorepresentable
lemma pullbackObjIsDefined_eq_top :
pullbackObjIsDefined.{u} φ = ⊤ := by
ext M
simp only [Pi.top_apply, Prop.top_eq_true, iff_true]
apply Functor.leftAdjointObjIsDefined_of_isColimit
M.isColimitFreeYonedaCoproductsCokernelCofork
rintro (_ | _)
all_goals
apply Functor.leftAdjointObjIsDefined_colimit _
(fun _ ↦ pullbackObjIsDefined_free_yoneda _ _)
instance : (pushforward.{u} φ).IsRightAdjoint :=
Functor.isRightAdjoint_of_leftAdjointObjIsDefined_eq_top
(pullbackObjIsDefined_eq_top φ)
end
end PresheafOfModules
|
StrongRankCondition.lean
|
/-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import Mathlib.RingTheory.FiniteType
import Mathlib.LinearAlgebra.InvariantBasisNumber
/-!
# Strong rank condition for commutative rings
We prove that any nontrivial commutative ring satisfies `StrongRankCondition`, meaning that
if there is an injective linear map `(Fin n → R) →ₗ[R] Fin m → R`, then `n ≤ m`. This implies that
any commutative ring satisfies `InvariantBasisNumber`: the rank of a finitely generated free
module is well defined.
## Main result
* `commRing_strongRankCondition R` : `R` has the `StrongRankCondition`.
The `commRing_strongRankCondition` comes from `CommRing.orzechProperty`, proved in
`Mathlib/RingTheory/FiniteType.lean`, which states that any commutative ring satisfies
the `OrzechProperty`, that is, for any finitely generated
`R`-module `M`, any surjective homomorphism `f : N → M` from a submodule `N` of `M` to `M`
is injective.
## References
* [Orzech, Morris. *Onto endomorphisms are isomorphisms*][orzech1971]
* [Djoković, D. Ž. *Epimorphisms of modules which must be isomorphisms*][djokovic1973]
* [Ribenboim, Paulo. *Épimorphismes de modules qui sont nécessairement
des isomorphismes*][ribenboim1971]
-/
variable (R : Type*) [CommRing R] [Nontrivial R]
/-- Any nontrivial commutative ring satisfies the `StrongRankCondition`. -/
instance (priority := 100) commRing_strongRankCondition : StrongRankCondition R :=
inferInstance
|
Principal.lean
|
/-
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_gt 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
| zero => rwa [Function.iterate_zero]
| succ n hn =>
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' : IsSuccLimit 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_gt (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 isSuccLimit_of_principal_add (ho₁ : 1 < o) (ho : Principal (· + ·) o) : IsSuccLimit o := by
rw [isSuccLimit_iff, isSuccPrelimit_iff_succ_lt]
exact ⟨ho₁.ne_bot, fun _ ha ↦ ho ha ho₁⟩
@[deprecated (since := "2025-07-08")]
alias isLimit_of_principal_add := isSuccLimit_of_principal_add
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_ge 1 o with ho₁ | ho₁
· exact op_eq_self_of_principal hao (isNormal_add_right a) ho
(isSuccLimit_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_gt 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
| zero =>
rw [opow_zero, ← succ_zero, lt_succ_iff, Ordinal.le_zero] at h
rw [h, zero_add]
| succ =>
rw [opow_succ] at h
rcases (lt_mul_iff_of_isSuccLimit isSuccLimit_omega0).1 h with ⟨x, xo, ax⟩
apply (add_le_add_right ax.le _).trans
rw [opow_succ, ← mul_add, add_omega0 xo]
| limit b l IH =>
rcases (lt_opow_of_isSuccLimit 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_iff_of_isSuccLimit isSuccLimit_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_ge
suffices e : ω ^ log ω o * n + o = o by
simpa only [e] using le_add_right (ω ^ log ω o * ↑n) o
induction n with
| zero => simp [Nat.cast_zero, mul_zero, zero_add]
| succ n IH => 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_iff_of_isSuccLimit
(isSuccLimit_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 isSuccLimit_of_principal_mul (ho₂ : 2 < o) (ho : Principal (· * ·) o) : IsSuccLimit o :=
isSuccLimit_of_principal_add ((lt_succ 1).trans (succ_one ▸ ho₂))
(principal_add_of_principal_mul ho (ne_of_gt ho₂))
@[deprecated (since := "2025-07-08")]
alias isLimit_of_principal_mul := isSuccLimit_of_principal_mul
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
(isSuccLimit_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_isSuccLimit 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 isSuccLimit_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_isSuccLimit omega0_ne_zero (isSuccLimit_opow_left isSuccLimit_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_gt 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 := isSuccLimit_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_isSuccLimit (one_le_iff_ne_zero.1 <| le_of_lt a1) isSuccLimit_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
|
quotient.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div.
From mathcomp Require Import choice fintype prime finset fingroup morphism.
From mathcomp Require Import automorphism.
(******************************************************************************)
(* This file contains the definitions of: *)
(* coset_of H == the (sub)type of bilateral cosets of H (see below). *)
(* coset H == the canonical projection into coset_of H. *)
(* A / H == the quotient of A by H, that is, the morphic image *)
(* of A by coset H. We do not require H <| A, so in a *)
(* textbook A / H would be written 'N_A(H) * H / H. *)
(* quotm f (nHG : H <| G) == the quotient morphism induced by f, *)
(* mapping G / H onto f @* G / f @* H. *)
(* qisom f (eqHG : H = G) == the identity isomorphism between *)
(* [set: coset_of G] and [set: coset_of H]. *)
(* We also prove the three isomorphism theorems, and counting lemmas for *)
(* morphisms. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import GroupScope.
Section Cosets.
Variables (gT : finGroupType) (Q A : {set gT}).
(******************************************************************************)
(* Cosets are right cosets of elements in the normaliser. *)
(* We let cosets coerce to GroupSet.sort, so they inherit the group subset *)
(* base group structure. Later we will define a proper group structure on *)
(* cosets, which will then hide the inherited structure once coset_of unifies *)
(* with FinGroup.sort; the coercion to GroupSet.sort will no longer be used. *)
(* Note that for Hx Hy : coset_of H, Hx * Hy : {set gT} can mean either *)
(* set_of_coset (mulg Hx Hy) OR mulg (set_of_coset Hx) (set_of_coset Hy). *)
(* However, since the two terms are actually convertible, we can live with *)
(* this ambiguity. *)
(* We take great care that neither the type coset_of H, nor its Canonical *)
(* finGroupType structure, nor the coset H morphism depend on the actual *)
(* group structure of H. Otherwise, rewriting would be extremely awkward *)
(* because all our equalities are stated at the set level. *)
(* The trick we use is to interpret coset_of A, when A is any set, as the *)
(* type of cosets of the group <<A>> generated by A, in the group A <*> N(A) *)
(* generated by A and its normaliser. This coincides with the type of *)
(* bilateral cosets of A when A is a group. We restrict the domain of coset A *)
(* to 'N(A), so that we get almost all the same conversion equalities as if *)
(* we had forced A to be a group in the first place; the only exception, that *)
(* 1 : coset_of A : {set gT} = <<A>> rather than A, can be handled by genGid. *)
(******************************************************************************)
Notation H := <<A>>.
Definition coset_range := [pred B in rcosets H 'N(A)].
Record coset_of : Type :=
Coset { set_of_coset :> GroupSet.sort gT; _ : coset_range set_of_coset }.
HB.instance Definition _ := [isSub for set_of_coset].
#[hnf] HB.instance Definition _ := [Finite of coset_of by <:].
(* We build a new (canonical) structure of groupType for cosets. *)
(* When A is a group, this is the largest possible quotient 'N(A) / A. *)
Lemma coset_one_proof : coset_range H.
Proof. by apply/rcosetsP; exists (1 : gT); rewrite (group1, mulg1). Qed.
Definition coset_one := Coset coset_one_proof.
Let nNH := subsetP (norm_gen A).
Lemma coset_range_mul (B C : coset_of) : coset_range (B * C).
Proof.
case: B C => _ /= /rcosetsP[x Nx ->] [_ /= /rcosetsP[y Ny ->]].
by apply/rcosetsP; exists (x * y); rewrite !(groupM, rcoset_mul, nNH).
Qed.
Definition coset_mul B C := Coset (coset_range_mul B C).
Lemma coset_range_inv (B : coset_of) : coset_range B^-1.
Proof.
case: B => _ /= /rcosetsP[x Nx ->]; rewrite norm_rlcoset ?nNH // invg_lcoset.
by apply/rcosetsP; exists x^-1; rewrite ?groupV.
Qed.
Definition coset_inv B := Coset (coset_range_inv B).
Lemma coset_mulP : associative coset_mul.
Proof. by move=> B C D; apply: val_inj; rewrite /= mulgA. Qed.
Lemma coset_oneP : left_id coset_one coset_mul.
Proof.
case=> B coB; apply: val_inj => /=; case/rcosetsP: coB => x Hx ->{B}.
by rewrite mulgA mulGid.
Qed.
Lemma coset_invP : left_inverse coset_one coset_inv coset_mul.
Proof.
case=> B coB; apply: val_inj => /=; case/rcosetsP: coB => x Hx ->{B}.
rewrite invg_rcoset -mulgA (mulgA H) mulGid.
by rewrite norm_rlcoset ?nNH // -lcosetM mulVg mul1g.
Qed.
HB.instance Definition _ :=
isMulGroup.Build coset_of coset_mulP coset_oneP coset_invP.
(* Projection of the initial group type over the cosets groupType. *)
Definition coset x : coset_of := insubd (1 : coset_of) (H :* x).
(* This is a primitive lemma -- we'll need to restate it for *)
(* the case where A is a group. *)
Lemma val_coset_prim x : x \in 'N(A) -> coset x :=: H :* x.
Proof.
by move=> Nx; rewrite val_insubd /= mem_rcosets -{1}(mul1g x) mem_mulg.
Qed.
Lemma coset_morphM : {in 'N(A) &, {morph coset : x y / x * y}}.
Proof.
move=> x y Nx Ny; apply: val_inj.
by rewrite /= !val_coset_prim ?groupM //= rcoset_mul ?nNH.
Qed.
Canonical coset_morphism := Morphism coset_morphM.
Lemma ker_coset_prim : 'ker coset = 'N_H(A).
Proof.
apply/setP=> z; rewrite !in_setI andbC 2!inE -val_eqE /=.
case Nz: (z \in 'N(A)); rewrite ?andbF ?val_coset_prim // !andbT.
by apply/eqP/idP=> [<-| Az]; rewrite (rcoset_refl, rcoset_id).
Qed.
Implicit Type xbar : coset_of.
Lemma coset_mem y xbar : y \in xbar -> coset y = xbar.
Proof.
case: xbar => /= Hx NHx Hxy; apply: val_inj=> /=.
case/rcosetsP: NHx (NHx) Hxy => x Nx -> NHx Hxy.
by rewrite val_insubd /= (rcoset_eqP Hxy) NHx.
Qed.
(* coset is an inverse to repr *)
Lemma mem_repr_coset xbar : repr xbar \in xbar.
Proof. by case: xbar => /= _ /rcosetsP[x _ ->]; apply: mem_repr_rcoset. Qed.
Lemma repr_coset1 : repr (1 : coset_of) = 1.
Proof. exact: repr_group. Qed.
Lemma coset_reprK : cancel (fun xbar => repr xbar) coset.
Proof. by move=> xbar; apply: coset_mem (mem_repr_coset xbar). Qed.
(* cosetP is slightly stronger than using repr because we only *)
(* guarantee repr xbar \in 'N(A) when A is a group. *)
Lemma cosetP xbar : {x | x \in 'N(A) & xbar = coset x}.
Proof.
pose x := repr 'N_xbar(A).
have [xbar_x Nx]: x \in xbar /\ x \in 'N(A).
apply/setIP; rewrite {}/x; case: xbar => /= _ /rcosetsP[y Ny ->].
by apply: (mem_repr y); rewrite inE rcoset_refl.
by exists x; last rewrite (coset_mem xbar_x).
Qed.
Lemma coset_id x : x \in A -> coset x = 1.
Proof. by move=> Ax; apply: coset_mem; apply: mem_gen. Qed.
Lemma im_coset : coset @* 'N(A) = setT.
Proof.
by apply/setP=> xbar; case: (cosetP xbar) => x Nx ->; rewrite inE mem_morphim.
Qed.
Lemma sub_im_coset (C : {set coset_of}) : C \subset coset @* 'N(A).
Proof. by rewrite im_coset subsetT. Qed.
Lemma cosetpre_proper C D :
(coset @*^-1 C \proper coset @*^-1 D) = (C \proper D).
Proof. by rewrite morphpre_proper ?sub_im_coset. Qed.
Definition quotient : {set coset_of} := coset @* Q.
Lemma quotientE : quotient = coset @* Q. Proof. by []. Qed.
End Cosets.
Arguments coset_of {gT} H%_g : rename.
Arguments coset {gT} H%_g x%_g : rename.
Arguments quotient {gT} A%_g H%_g : rename.
Arguments coset_reprK {gT H%_g} xbar%_g : rename.
Bind Scope group_scope with coset_of.
Notation "A / H" := (quotient A H) : group_scope.
Section CosetOfGroupTheory.
Variables (gT : finGroupType) (H : {group gT}).
Implicit Types (A B : {set gT}) (G K : {group gT}) (xbar yb : coset_of H).
Implicit Types (C D : {set coset_of H}) (L M : {group coset_of H}).
Canonical quotient_group G A : {group coset_of A} :=
Eval hnf in [group of G / A].
Infix "/" := quotient_group : Group_scope.
Lemma val_coset x : x \in 'N(H) -> coset H x :=: H :* x.
Proof. by move=> Nx; rewrite val_coset_prim // genGid. Qed.
Lemma coset_default x : (x \in 'N(H)) = false -> coset H x = 1.
Proof.
move=> Nx; apply: val_inj.
by rewrite val_insubd /= mem_rcosets /= genGid mulSGid ?normG ?Nx.
Qed.
Lemma coset_norm xbar : xbar \subset 'N(H).
Proof.
case: xbar => /= _ /rcosetsP[x Nx ->].
by rewrite genGid mul_subG ?sub1set ?normG.
Qed.
Lemma ker_coset : 'ker (coset H) = H.
Proof. by rewrite ker_coset_prim genGid (setIidPl _) ?normG. Qed.
Lemma coset_idr x : x \in 'N(H) -> coset H x = 1 -> x \in H.
Proof. by move=> Nx Hx1; rewrite -ker_coset mem_morphpre //= Hx1 set11. Qed.
Lemma repr_coset_norm xbar : repr xbar \in 'N(H).
Proof. exact: subsetP (coset_norm _) _ (mem_repr_coset _). Qed.
Lemma imset_coset G : coset H @: G = G / H.
Proof.
apply/eqP; rewrite eqEsubset andbC imsetS ?subsetIr //=.
apply/subsetP=> _ /imsetP[x Gx ->].
by case Nx: (x \in 'N(H)); rewrite ?(coset_default Nx) ?mem_morphim ?group1.
Qed.
Lemma val_quotient A : val @: (A / H) = rcosets H 'N_A(H).
Proof.
apply/setP=> B; apply/imsetP/rcosetsP=> [[xbar Axbar]|[x /setIP[Ax Nx]]] ->{B}.
case/morphimP: Axbar => x Nx Ax ->{xbar}.
by exists x; [rewrite inE Ax | rewrite /= val_coset].
by exists (coset H x); [apply/morphimP; exists x | rewrite /= val_coset].
Qed.
Lemma card_quotient_subnorm A : #|A / H| = #|'N_A(H) : H|.
Proof. by rewrite -(card_imset _ val_inj) val_quotient. Qed.
Lemma leq_quotient A : #|A / H| <= #|A|.
Proof. exact: leq_morphim. Qed.
Lemma ltn_quotient A : H :!=: 1 -> H \subset A -> #|A / H| < #|A|.
Proof.
by move=> ntH sHA; rewrite ltn_morphim // ker_coset (setIidPr sHA) proper1G.
Qed.
Lemma card_quotient A : A \subset 'N(H) -> #|A / H| = #|A : H|.
Proof. by move=> nHA; rewrite card_quotient_subnorm (setIidPl nHA). Qed.
Lemma divg_normal G : H <| G -> #|G| %/ #|H| = #|G / H|.
Proof. by case/andP=> sHG nHG; rewrite divgS ?card_quotient. Qed.
(* Specializing all the morphisms lemmas that have different assumptions *)
(* (e.g., because 'ker (coset H) = H), or conclusions (e.g., because we use *)
(* A / H rather than coset H @* A). We may want to reevaluate later, and *)
(* eliminate variants that aren't used . *)
(* Variant of morph1; no specialization for other morph lemmas. *)
Lemma coset1 : coset H 1 :=: H.
Proof. by rewrite morph1 /= genGid. Qed.
(* Variant of kerE. *)
Lemma cosetpre1 : coset H @*^-1 1 = H.
Proof. by rewrite -kerE ker_coset. Qed.
(* Variant of morphimEdom; mophimE[sub] covered by imset_coset. *)
(* morph[im|pre]Iim are also covered by im_quotient. *)
Lemma im_quotient : 'N(H) / H = setT.
Proof. exact: im_coset. Qed.
Lemma quotientT : setT / H = setT.
Proof. by rewrite -im_quotient; apply: morphimT. Qed.
(* Variant of morphimIdom. *)
Lemma quotientInorm A : 'N_A(H) / H = A / H.
Proof. by rewrite /quotient setIC morphimIdom. Qed.
Lemma quotient_setIpre A D : (A :&: coset H @*^-1 D) / H = A / H :&: D.
Proof. exact: morphim_setIpre. Qed.
Lemma mem_quotient x G : x \in G -> coset H x \in G / H.
Proof. by move=> Gx; rewrite -imset_coset imset_f. Qed.
Lemma quotientS A B : A \subset B -> A / H \subset B / H.
Proof. exact: morphimS. Qed.
Lemma quotient0 : set0 / H = set0.
Proof. exact: morphim0. Qed.
Lemma quotient_set1 x : x \in 'N(H) -> [set x] / H = [set coset H x].
Proof. exact: morphim_set1. Qed.
Lemma quotient1 : 1 / H = 1.
Proof. exact: morphim1. Qed.
Lemma quotientV A : A^-1 / H = (A / H)^-1.
Proof. exact: morphimV. Qed.
Lemma quotientMl A B : A \subset 'N(H) -> A * B / H = (A / H) * (B / H).
Proof. exact: morphimMl. Qed.
Lemma quotientMr A B : B \subset 'N(H) -> A * B / H = (A / H) * (B / H).
Proof. exact: morphimMr. Qed.
Lemma cosetpreM C D : coset H @*^-1 (C * D) = coset H @*^-1 C * coset H @*^-1 D.
Proof. by rewrite morphpreMl ?sub_im_coset. Qed.
Lemma quotientJ A x : x \in 'N(H) -> A :^ x / H = (A / H) :^ coset H x.
Proof. exact: morphimJ. Qed.
Lemma quotientU A B : (A :|: B) / H = A / H :|: B / H.
Proof. exact: morphimU. Qed.
Lemma quotientI A B : (A :&: B) / H \subset A / H :&: B / H.
Proof. exact: morphimI. Qed.
Lemma quotientY A B :
A \subset 'N(H) -> B \subset 'N(H) -> (A <*> B) / H = (A / H) <*> (B / H).
Proof. exact: morphimY. Qed.
Lemma quotient_homg A : A \subset 'N(H) -> homg (A / H) A.
Proof. exact: morphim_homg. Qed.
Lemma coset_kerl x y : x \in H -> coset H (x * y) = coset H y.
Proof.
move=> Hx; case Ny: (y \in 'N(H)); first by rewrite mkerl ?ker_coset.
by rewrite !coset_default ?groupMl // (subsetP (normG H)).
Qed.
Lemma coset_kerr x y : y \in H -> coset H (x * y) = coset H x.
Proof.
move=> Hy; case Nx: (x \in 'N(H)); first by rewrite mkerr ?ker_coset.
by rewrite !coset_default ?groupMr // (subsetP (normG H)).
Qed.
Lemma rcoset_kercosetP x y :
x \in 'N(H) -> y \in 'N(H) -> reflect (coset H x = coset H y) (x \in H :* y).
Proof. by rewrite -{6}ker_coset; apply: rcoset_kerP. Qed.
Lemma kercoset_rcoset x y :
x \in 'N(H) -> y \in 'N(H) ->
coset H x = coset H y -> exists2 z, z \in H & x = z * y.
Proof. by move=> Nx Ny eqfxy; rewrite -ker_coset; apply: ker_rcoset. Qed.
Lemma quotientGI G A : H \subset G -> (G :&: A) / H = G / H :&: A / H.
Proof. by rewrite -{1}ker_coset; apply: morphimGI. Qed.
Lemma quotientIG A G : H \subset G -> (A :&: G) / H = A / H :&: G / H.
Proof. by rewrite -{1}ker_coset; apply: morphimIG. Qed.
Lemma quotientD A B : A / H :\: B / H \subset (A :\: B) / H.
Proof. exact: morphimD. Qed.
Lemma quotientD1 A : (A / H)^# \subset A^# / H.
Proof. exact: morphimD1. Qed.
Lemma quotientDG A G : H \subset G -> (A :\: G) / H = A / H :\: G / H.
Proof. by rewrite -{1}ker_coset; apply: morphimDG. Qed.
Lemma quotientK A : A \subset 'N(H) -> coset H @*^-1 (A / H) = H * A.
Proof. by rewrite -{8}ker_coset; apply: morphimK. Qed.
Lemma quotientYK G : G \subset 'N(H) -> coset H @*^-1 (G / H) = H <*> G.
Proof. by move=> nHG; rewrite quotientK ?norm_joinEr. Qed.
Lemma quotientGK G : H <| G -> coset H @*^-1 (G / H) = G.
Proof. by case/andP; rewrite -{1}ker_coset; apply: morphimGK. Qed.
Lemma quotient_class x A :
x \in 'N(H) -> A \subset 'N(H) -> x ^: A / H = coset H x ^: (A / H).
Proof. exact: morphim_class. Qed.
Lemma classes_quotient A :
A \subset 'N(H) -> classes (A / H) = [set xA / H | xA in classes A].
Proof. exact: classes_morphim. Qed.
Lemma cosetpre_set1 x :
x \in 'N(H) -> coset H @*^-1 [set coset H x] = H :* x.
Proof. by rewrite -{9}ker_coset; apply: morphpre_set1. Qed.
Lemma cosetpre_set1_coset xbar : coset H @*^-1 [set xbar] = xbar.
Proof. by case: (cosetP xbar) => x Nx ->; rewrite cosetpre_set1 ?val_coset. Qed.
Lemma cosetpreK C : coset H @*^-1 C / H = C.
Proof. by rewrite /quotient morphpreK ?sub_im_coset. Qed.
(* Variant of morhphim_ker *)
Lemma trivg_quotient : H / H = 1.
Proof. by rewrite -[X in X / _]ker_coset /quotient morphim_ker. Qed.
Lemma quotientS1 G : G \subset H -> G / H = 1.
Proof. by move=> sGH; apply/trivgP; rewrite -trivg_quotient quotientS. Qed.
Lemma sub_cosetpre M : H \subset coset H @*^-1 M.
Proof. by rewrite -{1}ker_coset; apply: ker_sub_pre. Qed.
Lemma quotient_proper G K :
H <| G -> H <| K -> (G / H \proper K / H) = (G \proper K).
Proof. by move=> nHG nHK; rewrite -cosetpre_proper ?quotientGK. Qed.
Lemma normal_cosetpre M : H <| coset H @*^-1 M.
Proof. by rewrite -{1}ker_coset; apply: ker_normal_pre. Qed.
Lemma cosetpreSK C D :
(coset H @*^-1 C \subset coset H @*^-1 D) = (C \subset D).
Proof. by rewrite morphpreSK ?sub_im_coset. Qed.
Lemma sub_quotient_pre A C :
A \subset 'N(H) -> (A / H \subset C) = (A \subset coset H @*^-1 C).
Proof. exact: sub_morphim_pre. Qed.
Lemma sub_cosetpre_quo C G :
H <| G -> (coset H @*^-1 C \subset G) = (C \subset G / H).
Proof. by move=> nHG; rewrite -cosetpreSK quotientGK. Qed.
(* Variant of ker_trivg_morphim. *)
Lemma quotient_sub1 A : A \subset 'N(H) -> (A / H \subset [1]) = (A \subset H).
Proof.
by move=> nHA /=; rewrite -[gval H in RHS]ker_coset ker_trivg_morphim nHA.
Qed.
Lemma quotientSK A B :
A \subset 'N(H) -> (A / H \subset B / H) = (A \subset H * B).
Proof. by move=> nHA; rewrite morphimSK ?ker_coset. Qed.
Lemma quotientSGK A G :
A \subset 'N(H) -> H \subset G -> (A / H \subset G / H) = (A \subset G).
Proof. by rewrite -{2}ker_coset; apply: morphimSGK. Qed.
Lemma quotient_injG :
{in [pred G : {group gT} | H <| G] &, injective (fun G => G / H)}.
Proof. by rewrite /normal -{1}ker_coset; apply: morphim_injG. Qed.
Lemma quotient_inj G1 G2 :
H <| G1 -> H <| G2 -> G1 / H = G2 / H -> G1 :=: G2.
Proof. by rewrite /normal -[in mem H]ker_coset; apply: morphim_inj. Qed.
Lemma quotient_neq1 A : H <| A -> (A / H != 1) = (H \proper A).
Proof.
case/andP=> sHA nHA; rewrite /proper sHA -trivg_quotient eqEsubset andbC.
by rewrite quotientS //= quotientSGK.
Qed.
Lemma quotient_gen A : A \subset 'N(H) -> <<A>> / H = <<A / H>>.
Proof. exact: morphim_gen. Qed.
Lemma cosetpre_gen C :
1 \in C -> coset H @*^-1 <<C>> = <<coset H @*^-1 C>>.
Proof. by move=> C1; rewrite morphpre_gen ?sub_im_coset. Qed.
Lemma quotientR A B :
A \subset 'N(H) -> B \subset 'N(H) -> [~: A, B] / H = [~: A / H, B / H].
Proof. exact: morphimR. Qed.
Lemma quotient_norm A : 'N(A) / H \subset 'N(A / H).
Proof. exact: morphim_norm. Qed.
Lemma quotient_norms A B : A \subset 'N(B) -> A / H \subset 'N(B / H).
Proof. exact: morphim_norms. Qed.
Lemma quotient_subnorm A B : 'N_A(B) / H \subset 'N_(A / H)(B / H).
Proof. exact: morphim_subnorm. Qed.
Lemma quotient_normal A B : A <| B -> A / H <| B / H.
Proof. exact: morphim_normal. Qed.
Lemma quotient_cent1 x : 'C[x] / H \subset 'C[coset H x].
Proof.
case Nx: (x \in 'N(H)); first exact: morphim_cent1.
by rewrite coset_default // cent11T subsetT.
Qed.
Lemma quotient_cent1s A x : A \subset 'C[x] -> A / H \subset 'C[coset H x].
Proof.
by move=> sAC; apply: subset_trans (quotientS sAC) (quotient_cent1 x).
Qed.
Lemma quotient_subcent1 A x : 'C_A[x] / H \subset 'C_(A / H)[coset H x].
Proof. exact: subset_trans (quotientI _ _) (setIS _ (quotient_cent1 x)). Qed.
Lemma quotient_cent A : 'C(A) / H \subset 'C(A / H).
Proof. exact: morphim_cent. Qed.
Lemma quotient_cents A B : A \subset 'C(B) -> A / H \subset 'C(B / H).
Proof. exact: morphim_cents. Qed.
Lemma quotient_abelian A : abelian A -> abelian (A / H).
Proof. exact: morphim_abelian. Qed.
Lemma quotient_subcent A B : 'C_A(B) / H \subset 'C_(A / H)(B / H).
Proof. exact: morphim_subcent. Qed.
Lemma norm_quotient_pre A C :
A \subset 'N(H) -> A / H \subset 'N(C) -> A \subset 'N(coset H @*^-1 C).
Proof.
by move/sub_quotient_pre=> -> /subset_trans-> //; apply: morphpre_norm.
Qed.
Lemma cosetpre_normal C D : (coset H @*^-1 C <| coset H @*^-1 D) = (C <| D).
Proof. by rewrite morphpre_normal ?sub_im_coset. Qed.
Lemma quotient_normG G : H <| G -> 'N(G) / H = 'N(G / H).
Proof.
case/andP=> sHG nHG.
by rewrite [_ / _]morphim_normG ?ker_coset // im_coset setTI.
Qed.
Lemma quotient_subnormG A G : H <| G -> 'N_A(G) / H = 'N_(A / H)(G / H).
Proof. by case/andP=> sHG nHG; rewrite -morphim_subnormG ?ker_coset. Qed.
Lemma cosetpre_cent1 x : 'C_('N(H))[x] \subset coset H @*^-1 'C[coset H x].
Proof.
case Nx: (x \in 'N(H)); first by rewrite morphpre_cent1.
by rewrite coset_default // cent11T morphpreT subsetIl.
Qed.
Lemma cosetpre_cent1s C x :
coset H @*^-1 C \subset 'C[x] -> C \subset 'C[coset H x].
Proof.
move=> sC; rewrite -cosetpreSK; apply: subset_trans (cosetpre_cent1 x).
by rewrite subsetI subsetIl.
Qed.
Lemma cosetpre_subcent1 C x :
'C_(coset H @*^-1 C)[x] \subset coset H @*^-1 'C_C[coset H x].
Proof.
by rewrite -morphpreIdom -setIA setICA morphpreI setIS // cosetpre_cent1.
Qed.
Lemma cosetpre_cent A : 'C_('N(H))(A) \subset coset H @*^-1 'C(A / H).
Proof. exact: morphpre_cent. Qed.
Lemma cosetpre_cents A C : coset H @*^-1 C \subset 'C(A) -> C \subset 'C(A / H).
Proof. by apply: morphpre_cents; rewrite ?sub_im_coset. Qed.
Lemma cosetpre_subcent C A :
'C_(coset H @*^-1 C)(A) \subset coset H @*^-1 'C_C(A / H).
Proof. exact: morphpre_subcent. Qed.
Lemma restrm_quotientE G A (nHG : G \subset 'N(H)) :
A \subset G -> restrm nHG (coset H) @* A = A / H.
Proof. exact: restrmEsub. Qed.
Section InverseImage.
Variables (G : {group gT}) (Kbar : {group coset_of H}).
Hypothesis nHG : H <| G.
Variant inv_quotient_spec (P : pred {group gT}) : Prop :=
InvQuotientSpec K of Kbar :=: K / H & H \subset K & P K.
Lemma inv_quotientS :
Kbar \subset G / H -> inv_quotient_spec (fun K => K \subset G).
Proof.
case/andP: nHG => sHG nHG' sKbarG.
have sKdH: Kbar \subset 'N(H) / H by rewrite (subset_trans sKbarG) ?morphimS.
exists (coset H @*^-1 Kbar)%G; first by rewrite cosetpreK.
by rewrite -{1}ker_coset morphpreS ?sub1G.
by rewrite sub_cosetpre_quo.
Qed.
Lemma inv_quotientN : Kbar <| G / H -> inv_quotient_spec (fun K => K <| G).
Proof.
move=> nKbar; case/inv_quotientS: (normal_sub nKbar) => K defKbar sHK sKG.
exists K => //; rewrite defKbar -cosetpre_normal !quotientGK // in nKbar.
exact: normalS nHG.
Qed.
End InverseImage.
Lemma quotientMidr A : A * H / H = A / H.
Proof.
by rewrite [_ /_]morphimMr ?normG //= -!quotientE trivg_quotient mulg1.
Qed.
Lemma quotientMidl A : H * A / H = A / H.
Proof.
by rewrite [_ /_]morphimMl ?normG //= -!quotientE trivg_quotient mul1g.
Qed.
Lemma quotientYidr G : G \subset 'N(H) -> G <*> H / H = G / H.
Proof.
move=> nHG; rewrite -genM_join quotient_gen ?mul_subG ?normG //.
by rewrite quotientMidr genGid.
Qed.
Lemma quotientYidl G : G \subset 'N(H) -> H <*> G / H = G / H.
Proof. by move=> nHG; rewrite joingC quotientYidr. Qed.
Section Injective.
Variables (G : {group gT}).
Hypotheses (nHG : G \subset 'N(H)) (tiHG : H :&: G = 1).
Lemma quotient_isom : isom G (G / H) (restrm nHG (coset H)).
Proof. by apply/isomP; rewrite ker_restrm setIC ker_coset tiHG im_restrm. Qed.
Lemma quotient_isog : isog G (G / H).
Proof. exact: isom_isog quotient_isom. Qed.
End Injective.
End CosetOfGroupTheory.
Notation "A / H" := (quotient_group A H) : Group_scope.
Section Quotient1.
Variables (gT : finGroupType) (A : {set gT}).
Lemma coset1_injm : 'injm (@coset gT 1).
Proof. by rewrite ker_coset /=. Qed.
Lemma quotient1_isom : isom A (A / 1) (coset 1).
Proof. by apply: sub_isom coset1_injm; rewrite ?norms1. Qed.
Lemma quotient1_isog : isog A (A / 1).
Proof. by apply: isom_isog quotient1_isom; apply: norms1. Qed.
End Quotient1.
Section QuotientMorphism.
Variable (gT rT : finGroupType) (G H : {group gT}) (f : {morphism G >-> rT}).
Implicit Types A : {set gT}.
Implicit Types B : {set (coset_of H)}.
Hypotheses (nsHG : H <| G).
Let sHG : H \subset G := normal_sub nsHG.
Let nHG : G \subset 'N(H) := normal_norm nsHG.
Let nfHfG : f @* G \subset 'N(f @* H) := morphim_norms f nHG.
Notation fH := (coset (f @* H) \o f).
Lemma quotm_dom_proof : G \subset 'dom fH.
Proof. by rewrite -sub_morphim_pre. Qed.
Notation fH_G := (restrm quotm_dom_proof fH).
Lemma quotm_ker_proof : 'ker (coset H) \subset 'ker fH_G.
Proof.
by rewrite ker_restrm ker_comp !ker_coset morphpreIdom morphimK ?mulG_subr.
Qed.
Definition quotm := factm quotm_ker_proof nHG.
Canonical quotm_morphism := [morphism G / H of quotm].
Lemma quotmE x : x \in G -> quotm (coset H x) = coset (f @* H) (f x).
Proof. exact: factmE. Qed.
Lemma morphim_quotm A : quotm @* (A / H) = f @* A / f @* H.
Proof. by rewrite morphim_factm [LHS]morphim_restrm morphim_comp morphimIdom. Qed.
Lemma morphpre_quotm Abar : quotm @*^-1 (Abar / f @* H) = f @*^-1 Abar / H.
Proof.
rewrite morphpre_factm morphpre_restrm morphpre_comp /=.
rewrite morphpreIdom -[Abar / _]quotientInorm quotientK ?subsetIr //=.
rewrite morphpreMl ?morphimS // morphimK // [_ * H]normC ?subIset ?nHG //.
rewrite -quotientE -mulgA quotientMidl /= setIC -morphpreIim setIA.
by rewrite (setIidPl nfHfG) morphpreIim -morphpreMl ?sub1G ?mul1g.
Qed.
Lemma ker_quotm : 'ker quotm = 'ker f / H.
Proof. by rewrite -morphpre_quotm /quotient morphim1. Qed.
Lemma injm_quotm : 'injm f -> 'injm quotm.
Proof. by move/trivgP=> /= kf1; rewrite ker_quotm kf1 quotientE morphim1. Qed.
End QuotientMorphism.
Section EqIso.
Variables (gT : finGroupType) (G H : {group gT}).
Hypothesis (eqGH : G :=: H).
Lemma im_qisom_proof : 'N(H) \subset 'N(G). Proof. by rewrite eqGH. Qed.
Lemma qisom_ker_proof : 'ker (coset G) \subset 'ker (coset H).
Proof. by rewrite eqGH. Qed.
Lemma qisom_restr_proof : setT \subset 'N(H) / G.
Proof. by rewrite eqGH im_quotient. Qed.
Definition qisom :=
restrm qisom_restr_proof (factm qisom_ker_proof im_qisom_proof).
Canonical qisom_morphism := Eval hnf in [morphism of qisom].
Lemma qisomE x : qisom (coset G x) = coset H x.
Proof.
case Nx: (x \in 'N(H)); first exact: factmE.
by rewrite !coset_default ?eqGH ?morph1.
Qed.
Lemma val_qisom Gx : val (qisom Gx) = val Gx.
Proof.
by case: (cosetP Gx) => x Nx ->{Gx}; rewrite qisomE /= !val_coset -?eqGH.
Qed.
Lemma morphim_qisom A : qisom @* (A / G) = A / H.
Proof. by rewrite morphim_restrm setTI morphim_factm. Qed.
Lemma morphpre_qisom A : qisom @*^-1 (A / H) = A / G.
Proof.
rewrite morphpre_restrm setTI morphpre_factm eqGH.
by rewrite morphpreK // im_coset subsetT.
Qed.
Lemma injm_qisom : 'injm qisom.
Proof. by rewrite -quotient1 -morphpre_qisom morphpreS ?sub1G. Qed.
Lemma im_qisom : qisom @* setT = setT.
Proof. by rewrite -{2}im_quotient morphim_qisom eqGH im_quotient. Qed.
Lemma qisom_isom : isom setT setT qisom.
Proof. by apply/isomP; rewrite injm_qisom im_qisom. Qed.
Lemma qisom_isog : [set: coset_of G] \isog [set: coset_of H].
Proof. exact: isom_isog qisom_isom. Qed.
Lemma qisom_inj : injective qisom.
Proof. by move=> x y; apply: (injmP injm_qisom); rewrite inE. Qed.
Lemma morphim_qisom_inj : injective (fun Gx => qisom @* Gx).
Proof.
by move=> Gx Gy; apply: injm_morphim_inj; rewrite (injm_qisom, subsetT).
Qed.
End EqIso.
Arguments qisom_inj {gT G H} eqGH [x1 x2].
Arguments morphim_qisom_inj {gT G H} eqGH [x1 x2].
Section FirstIsomorphism.
Variables aT rT : finGroupType.
Lemma first_isom (G : {group aT}) (f : {morphism G >-> rT}) :
{g : {morphism G / 'ker f >-> rT} | 'injm g &
forall A : {set aT}, g @* (A / 'ker f) = f @* A}.
Proof.
have nkG := ker_norm f.
have skk: 'ker (coset ('ker f)) \subset 'ker f by rewrite ker_coset.
exists (factm_morphism skk nkG) => /=; last exact: morphim_factm.
by rewrite ker_factm -quotientE trivg_quotient.
Qed.
Variables (G H : {group aT}) (f : {morphism G >-> rT}).
Hypothesis sHG : H \subset G.
Lemma first_isog : (G / 'ker f) \isog (f @* G).
Proof.
by case: (first_isom f) => g injg im_g; apply/isogP; exists g; rewrite ?im_g.
Qed.
Lemma first_isom_loc : {g : {morphism H / 'ker_H f >-> rT} |
'injm g & forall A : {set aT}, A \subset H -> g @* (A / 'ker_H f) = f @* A}.
Proof.
case: (first_isom (restrm_morphism sHG f)).
rewrite ker_restrm => g injg im_g; exists g => // A sAH.
by rewrite im_g morphim_restrm (setIidPr sAH).
Qed.
Lemma first_isog_loc : (H / 'ker_H f) \isog (f @* H).
Proof.
by case: first_isom_loc => g injg im_g; apply/isogP; exists g; rewrite ?im_g.
Qed.
End FirstIsomorphism.
Section SecondIsomorphism.
Variables (gT : finGroupType) (H K : {group gT}).
Hypothesis nKH : H \subset 'N(K).
Lemma second_isom : {f : {morphism H / (K :&: H) >-> coset_of K} |
'injm f & forall A : {set gT}, A \subset H -> f @* (A / (K :&: H)) = A / K}.
Proof.
have ->: K :&: H = 'ker_H (coset K) by rewrite ker_coset setIC.
exact: first_isom_loc.
Qed.
Lemma second_isog : H / (K :&: H) \isog H / K.
Proof. by rewrite setIC -{1 3}(ker_coset K); apply: first_isog_loc. Qed.
Lemma weak_second_isog : H / (K :&: H) \isog H * K / K.
Proof. by rewrite quotientMidr; apply: second_isog. Qed.
End SecondIsomorphism.
Section ThirdIsomorphism.
Variables (gT : finGroupType) (G H K : {group gT}).
Lemma homg_quotientS (A : {set gT}) :
A \subset 'N(H) -> A \subset 'N(K) -> H \subset K -> A / K \homg A / H.
Proof.
rewrite -!(gen_subG A) /=; set L := <<A>> => nHL nKL sKH.
have sub_ker: 'ker (restrm nHL (coset H)) \subset 'ker (restrm nKL (coset K)).
by rewrite !ker_restrm !ker_coset setIS.
have sAL: A \subset L := subset_gen A; rewrite -(setIidPr sAL).
rewrite -[_ / H](morphim_restrm nHL) -[_ / K](morphim_restrm nKL) /=.
by rewrite -(morphim_factm sub_ker (subxx L)) morphim_homg ?morphimS.
Qed.
Hypothesis sHK : H \subset K.
Hypothesis snHG : H <| G.
Hypothesis snKG : K <| G.
Theorem third_isom : {f : {morphism (G / H) / (K / H) >-> coset_of K} | 'injm f
& forall A : {set gT}, A \subset G -> f @* (A / H / (K / H)) = A / K}.
Proof.
have [[sKG nKG] [sHG nHG]] := (andP snKG, andP snHG).
have sHker: 'ker (coset H) \subset 'ker (restrm nKG (coset K)).
by rewrite ker_restrm !ker_coset subsetI sHG.
have:= first_isom_loc (factm_morphism sHker nHG) (subxx _) => /=.
rewrite ker_factm_loc ker_restrm ker_coset !(setIidPr sKG) /= -!quotientE.
case=> f injf im_f; exists f => // A sAG; rewrite im_f ?morphimS //.
by rewrite morphim_factm morphim_restrm (setIidPr sAG).
Qed.
Theorem third_isog : (G / H / (K / H)) \isog (G / K).
Proof.
by case: third_isom => f inj_f im_f; apply/isogP; exists f; rewrite ?im_f.
Qed.
End ThirdIsomorphism.
Lemma char_from_quotient (gT : finGroupType) (G H K : {group gT}) :
H <| K -> H \char G -> K / H \char G / H -> K \char G.
Proof.
case/andP=> sHK nHK chHG.
have nsHG := char_normal chHG; have [sHG nHG] := andP nsHG.
case/charP; rewrite quotientSGK // => sKG /= chKG.
apply/charP; split=> // f injf Gf; apply/morphim_fixP => //.
rewrite -(quotientSGK _ sHK); last by rewrite -morphimIim Gf subIset ?nHG.
have{chHG} Hf: f @* H = H by case/charP: chHG => _; apply.
set q := quotm_morphism f nsHG; have{injf}: 'injm q by apply: injm_quotm.
have: q @* _ = _ := morphim_quotm _ _ _; move: q; rewrite Hf => q im_q injq.
by rewrite -im_q chKG // im_q Gf.
Qed.
(* Counting lemmas for morphisms. *)
Section CardMorphism.
Variables (aT rT : finGroupType) (D : {group aT}) (f : {morphism D >-> rT}).
Implicit Types G H : {group aT}.
Implicit Types L M : {group rT}.
Lemma card_morphim G : #|f @* G| = #|D :&: G : 'ker f|.
Proof.
rewrite -morphimIdom -indexgI -card_quotient; last first.
by rewrite normsI ?normG ?subIset ?ker_norm.
by apply: esym (card_isog _); rewrite first_isog_loc ?subsetIl.
Qed.
Lemma dvdn_morphim G : #|f @* G| %| #|G|.
Proof.
rewrite card_morphim (dvdn_trans (dvdn_indexg _ _)) //.
by rewrite cardSg ?subsetIr.
Qed.
Lemma logn_morphim p G : logn p #|f @* G| <= logn p #|G|.
Proof. by rewrite dvdn_leq_log ?dvdn_morphim. Qed.
Lemma coprime_morphl G p : coprime #|G| p -> coprime #|f @* G| p.
Proof. exact: coprime_dvdl (dvdn_morphim G). Qed.
Lemma coprime_morphr G p : coprime p #|G| -> coprime p #|f @* G|.
Proof. exact: coprime_dvdr (dvdn_morphim G). Qed.
Lemma coprime_morph G H : coprime #|G| #|H| -> coprime #|f @* G| #|f @* H|.
Proof. by move=> coGH; rewrite coprime_morphl // coprime_morphr. Qed.
Lemma index_morphim_ker G H :
H \subset G -> G \subset D ->
(#|f @* G : f @* H| * #|'ker_G f : H|)%N = #|G : H|.
Proof.
move=> sHG sGD; apply/eqP.
rewrite -(eqn_pmul2l (cardG_gt0 (f @* H))) mulnA Lagrange ?morphimS //.
rewrite !card_morphim (setIidPr sGD) (setIidPr (subset_trans sHG sGD)).
rewrite -(eqn_pmul2l (cardG_gt0 ('ker_H f))) /=.
by rewrite -{1}(setIidPr sHG) setIAC mulnCA mulnC mulnA !LagrangeI Lagrange.
Qed.
Lemma index_morphim G H : G :&: H \subset D -> #|f @* G : f @* H| %| #|G : H|.
Proof.
move=> dGH; rewrite -(indexgI G) -(setIidPr dGH) setIA.
apply: dvdn_trans (indexSg (subsetIl _ H) (subsetIr D G)).
rewrite -index_morphim_ker ?subsetIl ?subsetIr ?dvdn_mulr //= morphimIdom.
by rewrite indexgS ?morphimS ?subsetIr.
Qed.
Lemma index_injm G H : 'injm f -> G \subset D -> #|f @* G : f @* H| = #|G : H|.
Proof.
move=> injf dG; rewrite -{2}(setIidPr dG) -(indexgI _ H) /=.
rewrite -index_morphim_ker ?subsetIl ?subsetIr //= setIAC morphimIdom setIC.
rewrite injmI ?subsetIr // indexgI /= morphimIdom setIC ker_injm //.
by rewrite -(indexgI (1 :&: _)) /= -setIA !(setIidPl (sub1G _)) indexgg muln1.
Qed.
Lemma card_morphpre L : L \subset f @* D -> #|f @*^-1 L| = (#|'ker f| * #|L|)%N.
Proof.
move/morphpreK=> {2} <-; rewrite card_morphim morphpreIdom.
by rewrite Lagrange // morphpreS ?sub1G.
Qed.
Lemma index_morphpre L M :
L \subset f @* D -> #|f @*^-1 L : f @*^-1 M| = #|L : M|.
Proof.
move=> dL; rewrite -!divgI -morphpreI /= card_morphpre //.
have: L :&: M \subset f @* D by rewrite subIset ?dL.
by move/card_morphpre->; rewrite divnMl ?cardG_gt0.
Qed.
End CardMorphism.
Lemma card_homg (aT rT : finGroupType) (G : {group aT}) (R : {group rT}) :
G \homg R -> #|G| %| #|R|.
Proof. by case/homgP=> f <-; rewrite card_morphim setIid dvdn_indexg. Qed.
Section CardCosetpre.
Variables (gT : finGroupType) (G H K : {group gT}) (L M : {group coset_of H}).
Lemma dvdn_quotient : #|G / H| %| #|G|.
Proof. exact: dvdn_morphim. Qed.
Lemma index_quotient_ker :
K \subset G -> G \subset 'N(H) ->
(#|G / H : K / H| * #|G :&: H : K|)%N = #|G : K|.
Proof. by rewrite -{5}(ker_coset H); apply: index_morphim_ker. Qed.
Lemma index_quotient : G :&: K \subset 'N(H) -> #|G / H : K / H| %| #|G : K|.
Proof. exact: index_morphim. Qed.
Lemma index_quotient_eq :
G :&: H \subset K -> K \subset G -> G \subset 'N(H) ->
#|G / H : K / H| = #|G : K|.
Proof.
move=> sGH_K sKG sGN; rewrite -index_quotient_ker {sKG sGN}//.
by rewrite -(indexgI _ K) (setIidPl sGH_K) indexgg muln1.
Qed.
Lemma card_cosetpre : #|coset H @*^-1 L| = (#|H| * #|L|)%N.
Proof. by rewrite card_morphpre ?ker_coset ?sub_im_coset. Qed.
Lemma index_cosetpre : #|coset H @*^-1 L : coset H @*^-1 M| = #|L : M|.
Proof. by rewrite index_morphpre ?sub_im_coset. Qed.
End CardCosetpre.
|
mxpoly.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat choice seq.
From mathcomp Require Import div fintype tuple finfun bigop fingroup perm.
From mathcomp Require Import ssralg zmodp matrix mxalgebra poly polydiv.
(******************************************************************************)
(* This file provides basic support for formal computation with matrices, *)
(* mainly results combining matrices and univariate polynomials, such as the *)
(* Cayley-Hamilton theorem; it also contains an extension of the first order *)
(* representation of algebra introduced in ssralg (GRing.term/formula). *)
(* rVpoly v == the little-endian decoding of the row vector v as a *)
(* polynomial p = \sum_i (v 0 i)%:P * 'X^i. *)
(* poly_rV p == the partial inverse to rVpoly, for polynomials of degree *)
(* less than d to 'rV_d (d is inferred from the context). *)
(* Sylvester_mx p q == the Sylvester matrix of p and q. *)
(* resultant p q == the resultant of p and q, i.e., \det (Sylvester_mx p q). *)
(* horner_mx A == the morphism from {poly R} to 'M_n (n of the form n'.+1) *)
(* mapping a (scalar) polynomial p to the value of its *)
(* scalar matrix interpretation at A (this is an instance of *)
(* the generic horner_morph construct defined in poly). *)
(* powers_mx A d == the d x (n ^ 2) matrix whose rows are the mxvec encodings *)
(* of the first d powers of A (n of the form n'.+1). Thus, *)
(* vec_mx (v *m powers_mx A d) = horner_mx A (rVpoly v). *)
(* char_poly A == the characteristic polynomial of A. *)
(* char_poly_mx A == a matrix whose determinant is char_poly A. *)
(* companionmx p == a matrix whose char_poly is p *)
(* mxminpoly A == the minimal polynomial of A, i.e., the smallest monic *)
(* polynomial that annihilates A (A must be nontrivial). *)
(* degree_mxminpoly A == the (positive) degree of mxminpoly A. *)
(* mx_inv_horner A == the inverse of horner_mx A for polynomials of degree *)
(* smaller than degree_mxminpoly A. *)
(* kermxpoly g p == the kernel of p(g) *)
(* geigenspace g a == the generalized eigenspace of g for eigenvalue a *)
(* := kermxpoly g ('X ^ n - a%:P) where g : 'M_n *)
(* eigenpoly g p <=> p is an eigen polynomial for g, i.e. kermxpoly g p != 0 *)
(* integralOver RtoK u <-> u is in the integral closure of the image of R *)
(* under RtoK : R -> K, i.e. u is a root of the image of a *)
(* monic polynomial in R. *)
(* algebraicOver FtoE u <-> u : E is algebraic over E; it is a root of the *)
(* image of a nonzero polynomial under FtoE; as F must be a *)
(* fieldType, this is equivalent to integralOver FtoE u. *)
(* integralRange RtoK <-> the integral closure of the image of R contains *)
(* all of K (:= forall u, integralOver RtoK u). *)
(* This toolkit for building formal matrix expressions is packaged in the *)
(* MatrixFormula submodule, and comprises the following: *)
(* eval_mx e == GRing.eval lifted to matrices (:= map_mx (GRing.eval e)). *)
(* mx_term A == GRing.Const lifted to matrices. *)
(* mulmx_term A B == the formal product of two matrices of terms. *)
(* mxrank_form m A == a GRing.formula asserting that the interpretation of *)
(* the term matrix A has rank m. *)
(* submx_form A B == a GRing.formula asserting that the row space of the *)
(* interpretation of the term matrix A is included in the *)
(* row space of the interpretation of B. *)
(* seq_of_rV v == the seq corresponding to a row vector. *)
(* row_env e == the flattening of a tensored environment e : seq 'rV_d. *)
(* row_var F d k == the term vector of width d such that for e : seq 'rV[F]_d *)
(* we have eval e 'X_k = eval_mx (row_env e) (row_var d k). *)
(* conjmx V f := V *m f *m pinvmx V *)
(* == the conjugation of f by V, i.e. "the" matrix of f *)
(* in the basis of row vectors of V. *)
(* Although this makes sense only when f stabilizes V, *)
(* the definition can be stated more generally. *)
(* restrictmx V := conjmx (row_base V) *)
(* A ~_P {in S'} == where P is a base change matrix, A is a matrix, and S *)
(* is a boolean predicate representing a set of matrices, *)
(* this states that conjmx P A is in S, *)
(* which means A is similar to a matrix in S. *)
(* From the latter, we derive several related notions: *)
(* A ~_P B := A ~_P {in pred1 B} *)
(* A is similar to B, with base change matrix P *)
(* A ~_{in S} B := exists P, P \in S /\ A ~_P B *)
(* == A is similar to B, with a base change matrix in S *)
(* A ~_{in S} {in S'} := exists P, P \in S /\ A ~_P {in S'} *)
(* == A is similar to a matrix in the class S', *)
(* with a base change matrix in S *)
(* all_simmx_in S As S' == all the matrices in the sequence As are *)
(* similar to some matrix in the predicate S', *)
(* with a base change matrix in S. *)
(* *)
(* We also specialize the class S' to diagonalizability: *)
(* diagonalizable_for P A := A ~_P {in is_diag_mx}. *)
(* diagonalizable_in S A := A ~_{in S} {in is_diag_mx}. *)
(* diagonalizable A := diagonalizable_in unitmx A. *)
(* codiagonalizable_in S As := all_simmx_in S As is_diag_mx. *)
(* codiagonalizable As := codiagonalizable_in unitmx As. *)
(* *)
(* The main results in diagnonalization theory are: *)
(* - diagonalizablePeigen: *)
(* a matrix is diagonalizable iff there is a sequence *)
(* of scalars r, such that the sum of the associated *)
(* eigenspaces is full. *)
(* - diagonalizableP: *)
(* a matrix is diagonalizable iff its minimal polynomial *)
(* divides a split polynomial with simple roots. *)
(* - codiagonalizableP: *)
(* a sequence of matrices are diagonalizable in the same basis *)
(* iff they are all diagonalizable and commute pairwize. *)
(* *)
(* Naming conventions: *)
(* - p, q are polynomials *)
(* - A, B, C are matrices *)
(* - f, g are matrices that are viewed as linear maps *)
(* - V, W are matrices that are viewed as subspaces *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import GRing.Theory.
Import Monoid.Theory.
Local Open Scope ring_scope.
Import Pdiv.Idomain.
(* Row vector <-> bounded degree polynomial bijection *)
Section RowPoly.
Variables (R : nzRingType) (d : nat).
Implicit Types u v : 'rV[R]_d.
Implicit Types p q : {poly R}.
Definition rVpoly v := \poly_(k < d) (if insub k is Some i then v 0 i else 0).
Definition poly_rV p := \row_(i < d) p`_i.
Lemma coef_rVpoly v k : (rVpoly v)`_k = if insub k is Some i then v 0 i else 0.
Proof. by rewrite coef_poly; case: insubP => [i ->|]; rewrite ?if_same. Qed.
Lemma coef_rVpoly_ord v (i : 'I_d) : (rVpoly v)`_i = v 0 i.
Proof. by rewrite coef_rVpoly valK. Qed.
Lemma rVpoly_delta i : rVpoly (delta_mx 0 i) = 'X^i.
Proof.
apply/polyP=> j; rewrite coef_rVpoly coefXn.
case: insubP => [k _ <- | j_ge_d]; first by rewrite mxE.
by case: eqP j_ge_d => // ->; rewrite ltn_ord.
Qed.
Lemma rVpolyK : cancel rVpoly poly_rV.
Proof. by move=> u; apply/rowP=> i; rewrite mxE coef_rVpoly_ord. Qed.
Lemma poly_rV_K p : size p <= d -> rVpoly (poly_rV p) = p.
Proof.
move=> le_p_d; apply/polyP=> k; rewrite coef_rVpoly.
case: insubP => [i _ <- | ]; first by rewrite mxE.
by rewrite -ltnNge => le_d_l; rewrite nth_default ?(leq_trans le_p_d).
Qed.
Lemma poly_rV_is_linear : linear poly_rV.
Proof. by move=> a p q; apply/rowP=> i; rewrite !mxE coefD coefZ. Qed.
HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} 'rV_d _ poly_rV
(GRing.semilinear_linear poly_rV_is_linear).
Lemma rVpoly_is_linear : linear rVpoly.
Proof.
move=> a u v; apply/polyP=> k; rewrite coefD coefZ !coef_rVpoly.
by case: insubP => [i _ _ | _]; rewrite ?mxE // mulr0 addr0.
Qed.
HB.instance Definition _ := GRing.isSemilinear.Build R 'rV_d {poly R} _ rVpoly
(GRing.semilinear_linear rVpoly_is_linear).
End RowPoly.
Prenex Implicits rVpoly rVpolyK.
Arguments poly_rV {R d}.
Arguments poly_rV_K {R d} [p] le_p_d.
Section Resultant.
Variables (R : nzRingType) (p q : {poly R}).
Let dS := ((size q).-1 + (size p).-1)%N.
Local Notation band r := (lin1_mx (poly_rV \o r \o* rVpoly)).
Definition Sylvester_mx : 'M[R]_dS := col_mx (band p) (band q).
Lemma Sylvester_mxE (i j : 'I_dS) :
let S_ r k := r`_(j - k) *+ (k <= j) in
Sylvester_mx i j = match split i with inl k => S_ p k | inr k => S_ q k end.
Proof.
move=> S_ /[1!mxE]; case: {i}(split i) => i /[!mxE]/=;
by rewrite rVpoly_delta coefXnM ltnNge if_neg -mulrb.
Qed.
Definition resultant := \det Sylvester_mx.
End Resultant.
Prenex Implicits Sylvester_mx resultant.
Lemma resultant_in_ideal (R : comNzRingType) (p q : {poly R}) :
size p > 1 -> size q > 1 ->
{uv : {poly R} * {poly R} | size uv.1 < size q /\ size uv.2 < size p
& (resultant p q)%:P = uv.1 * p + uv.2 * q}.
Proof.
move=> p_nc q_nc; pose dp := (size p).-1; pose dq := (size q).-1.
pose S := Sylvester_mx p q; pose dS := (dq + dp)%N.
have dS_gt0: dS > 0 by rewrite /dS /dq -(subnKC q_nc).
pose j0 := Ordinal dS_gt0.
pose Ss0 := col_mx (p *: \col_(i < dq) 'X^i) (q *: \col_(i < dp) 'X^i).
pose Ss := \matrix_(i, j) (if j == j0 then Ss0 i 0 else (S i j)%:P).
pose u ds s := \sum_(i < ds) cofactor Ss (s i) j0 * 'X^i.
exists (u _ (lshift dp), u _ ((rshift dq) _)).
suffices sz_u ds s: ds > 1 -> size (u ds.-1 s) < ds by rewrite !sz_u.
move/ltn_predK=> {2}<-; apply: leq_trans (size_sum _ _ _) _.
apply/bigmax_leqP=> i _.
have ->: cofactor Ss (s i) j0 = (cofactor S (s i) j0)%:P.
rewrite rmorphM /= rmorph_sign -det_map_mx; congr (_ * \det _).
by apply/matrixP=> i' j'; rewrite !mxE.
apply: leq_trans (size_polyMleq _ _) (leq_trans _ (valP i)).
by rewrite size_polyC size_polyXn addnS /= -add1n leq_add2r leq_b1.
transitivity (\det Ss); last first.
rewrite (expand_det_col Ss j0) big_split_ord !big_distrl /=.
by congr (_ + _); apply: eq_bigr => i _;
rewrite mxE eqxx (col_mxEu, col_mxEd) !mxE mulrC mulrA mulrAC.
pose S_ j1 := map_mx polyC (\matrix_(i, j) S i (if j == j0 then j1 else j)).
pose Ss0_ i dj := \poly_(j < dj) S i (insubd j0 j).
pose Ss_ dj := \matrix_(i, j) (if j == j0 then Ss0_ i dj else (S i j)%:P).
have{Ss u} ->: Ss = Ss_ dS.
apply/matrixP=> i j; rewrite mxE [in RHS]mxE; case: (j == j0) => {j}//.
apply/polyP=> k; rewrite coef_poly Sylvester_mxE mxE.
have [k_ge_dS | k_lt_dS] := leqP dS k.
case: (split i) => {}i; rewrite !mxE coefMXn;
case: ifP => // /negbT; rewrite -ltnNge ltnS => hi.
apply: (leq_sizeP _ _ (leqnn (size p))); rewrite -(ltn_predK p_nc).
by rewrite ltn_subRL (leq_trans _ k_ge_dS) // ltn_add2r.
- apply: (leq_sizeP _ _ (leqnn (size q))); rewrite -(ltn_predK q_nc).
by rewrite ltn_subRL (leq_trans _ k_ge_dS) // addnC ltn_add2l.
by rewrite insubdK //; case: (split i) => {}i;
rewrite !mxE coefMXn; case: leqP.
case: (ubnPgeq dS) (dS_gt0); elim=> // dj IHj ltjS _; pose j1 := Ordinal ltjS.
pose rj0T (A : 'M[{poly R}]_dS) := row j0 A^T.
have: rj0T (Ss_ dj.+1) = 'X^dj *: rj0T (S_ j1) + 1 *: rj0T (Ss_ dj).
apply/rowP=> i; apply/polyP=> k; rewrite scale1r !(Sylvester_mxE, mxE) eqxx.
rewrite coefD coefXnM coefC !coef_poly ltnS subn_eq0 ltn_neqAle andbC.
have [k_le_dj | k_gt_dj] /= := leqP k dj; last by rewrite addr0.
rewrite Sylvester_mxE insubdK; last exact: leq_ltn_trans (ltjS).
by have [->|] := eqP; rewrite (addr0, add0r).
rewrite -det_tr => /determinant_multilinear->;
try by apply/matrixP=> i j; rewrite !mxE lift_eqF.
have [dj0 | dj_gt0] := posnP dj; rewrite ?dj0 !mul1r.
rewrite !det_tr det_map_mx addrC (expand_det_col _ j0) big1 => [|i _].
rewrite add0r; congr (\det _)%:P.
apply/matrixP=> i j; rewrite [in RHS]mxE; case: eqP => // ->.
by congr (S i _); apply: val_inj.
by rewrite mxE /= [Ss0_ _ _]poly_def big_ord0 mul0r.
have /determinant_alternate->: j1 != j0 by rewrite -val_eqE -lt0n.
by rewrite mulr0 add0r det_tr IHj // ltnW.
by move=> i; rewrite !mxE if_same.
Qed.
Lemma resultant_eq0 (R : idomainType) (p q : {poly R}) :
(resultant p q == 0) = (size (gcdp p q) > 1).
Proof.
have dvdpp := dvdpp; set r := gcdp p q.
pose dp := (size p).-1; pose dq := (size q).-1.
have /andP[r_p r_q]: (r %| p) && (r %| q) by rewrite -dvdp_gcd.
apply/det0P/idP=> [[uv nz_uv] | r_nonC].
have [p0 _ | p_nz] := eqVneq p 0.
have: dq + dp > 0.
rewrite lt0n; apply: contraNneq nz_uv => dqp0.
by rewrite dqp0 in uv *; rewrite [uv]thinmx0.
by rewrite /dp /dq /r p0 size_poly0 addn0 gcd0p -subn1 subn_gt0.
do [rewrite -[uv]hsubmxK -{1}row_mx0 mul_row_col !mul_rV_lin1 /=] in nz_uv *.
set u := rVpoly _; set v := rVpoly _; pose m := gcdp (v * p) (v * q).
have lt_vp: size v < size p by rewrite (polySpred p_nz) ltnS size_poly.
move/(congr1 rVpoly)/eqP; rewrite -linearD linear0 poly_rV_K; last first.
rewrite (leq_trans (size_polyD _ _)) // geq_max.
rewrite !(leq_trans (size_polyMleq _ _)) // -subn1 leq_subLR.
by rewrite addnC addnA leq_add ?leqSpred ?size_poly.
by rewrite addnCA leq_add ?leqSpred ?size_poly.
rewrite addrC addr_eq0 => /eqP vq_up.
have nz_v: v != 0.
apply: contraNneq nz_uv => v0; apply/eqP.
congr row_mx; apply: (can_inj rVpolyK); rewrite linear0 // -/u.
by apply: contra_eq vq_up; rewrite v0 mul0r -addr_eq0 add0r => /mulf_neq0->.
have r_nz: r != 0 := dvdpN0 r_p p_nz.
have /dvdpP [[c w] /= nz_c wv]: v %| m by rewrite dvdp_gcd !dvdp_mulr.
have m_wd d: m %| v * d -> w %| d.
case/dvdpP=> [[k f]] /= nz_k /(congr1 ( *:%R c)).
rewrite mulrC scalerA scalerAl scalerAr wv mulrA => /(mulIf nz_v)def_fw.
by apply/dvdpP; exists (c * k, f); rewrite //= mulf_neq0.
have w_r: w %| r by rewrite dvdp_gcd !m_wd ?dvdp_gcdl ?dvdp_gcdr.
have w_nz: w != 0 := dvdpN0 w_r r_nz.
have p_m: p %| m by rewrite dvdp_gcd vq_up -mulNr !dvdp_mull.
rewrite (leq_trans _ (dvdp_leq r_nz w_r)) // -(ltn_add2l (size v)).
rewrite addnC -ltn_subRL subn1 -size_mul // mulrC -wv size_scale //.
rewrite (leq_trans lt_vp) // dvdp_leq // -size_poly_eq0.
by rewrite -(size_scale _ nz_c) size_poly_eq0 wv mulf_neq0.
have [[c p'] /= nz_c p'r] := dvdpP _ _ r_p.
have [[k q'] /= nz_k q'r] := dvdpP _ _ r_q.
have def_r := subnKC r_nonC; have r_nz: r != 0 by rewrite -size_poly_eq0 -def_r.
have le_p'_dp: size p' <= dp.
have [-> | nz_p'] := eqVneq p' 0; first by rewrite size_poly0.
by rewrite /dp -(size_scale p nz_c) p'r size_mul // addnC -def_r leq_addl.
have le_q'_dq: size q' <= dq.
have [-> | nz_q'] := eqVneq q' 0; first by rewrite size_poly0.
by rewrite /dq -(size_scale q nz_k) q'r size_mul // addnC -def_r leq_addl.
exists (row_mx (- c *: poly_rV q') (k *: poly_rV p')); last first.
rewrite mul_row_col scaleNr mulNmx !mul_rV_lin1 /= 2!linearZ /= !poly_rV_K //.
by rewrite !scalerCA p'r q'r mulrCA addNr.
apply: contraNneq r_nz; rewrite -row_mx0 => /eq_row_mx[/eqP].
rewrite scaleNr oppr_eq0 gcdp_eq0 -!size_poly_eq0 => /eqP q0 p0.
rewrite -(size_scale p nz_c) -(size_scale (c *: p) nz_k) p'r.
rewrite -(size_scale q nz_k) -(size_scale (k *: q) nz_c) q'r !scalerAl.
rewrite -(poly_rV_K le_p'_dp) -(poly_rV_K le_q'_dq).
by rewrite -2![_ *: rVpoly _]linearZ p0 q0 !linear0 mul0r size_poly0.
Qed.
Section HornerMx.
Variables (R : comNzRingType) (n' : nat).
Local Notation n := n'.+1.
Implicit Types (A B : 'M[R]_n) (p q : {poly R}).
Section OneMatrix.
Variable A : 'M[R]_n.
Definition horner_mx := horner_morph (comm_mx_scalar^~ A).
HB.instance Definition _ := GRing.RMorphism.on horner_mx.
Lemma horner_mx_C a : horner_mx a%:P = a%:M.
Proof. exact: horner_morphC. Qed.
Lemma horner_mx_X : horner_mx 'X = A. Proof. exact: horner_morphX. Qed.
Lemma horner_mxZ : scalable horner_mx.
Proof.
move=> a p /=; rewrite -mul_polyC rmorphM /=.
by rewrite horner_mx_C [_ * _]mul_scalar_mx.
Qed.
HB.instance Definition _ := GRing.isScalable.Build R _ _ *:%R horner_mx
horner_mxZ.
Definition powers_mx d := \matrix_(i < d) mxvec (A ^+ i).
Lemma horner_rVpoly m (u : 'rV_m) :
horner_mx (rVpoly u) = vec_mx (u *m powers_mx m).
Proof.
rewrite mulmx_sum_row [rVpoly u]poly_def 2!linear_sum; apply: eq_bigr => i _.
by rewrite valK /= 2!linearZ rmorphXn/= horner_mx_X rowK mxvecK.
Qed.
End OneMatrix.
Lemma horner_mx_diag (d : 'rV[R]_n) (p : {poly R}) :
horner_mx (diag_mx d) p = diag_mx (map_mx (horner p) d).
Proof.
apply/matrixP => i j; rewrite !mxE.
elim/poly_ind: p => [|p c ihp]; first by rewrite rmorph0 horner0 mxE mul0rn.
rewrite !hornerE mulrnDl rmorphD rmorphM /= horner_mx_X horner_mx_C !mxE.
rewrite (bigD1 j)//= ihp mxE eqxx mulr1n -mulrnAl big1 ?addr0.
by have [->|_] := eqVneq; rewrite /= !(mulr1n, addr0, mul0r).
by move=> k /negPf nkF; rewrite mxE nkF mulr0.
Qed.
Lemma comm_mx_horner A B p : comm_mx A B -> comm_mx A (horner_mx B p).
Proof.
move=> fg; apply: commr_horner => // i.
by rewrite coef_map; apply/comm_scalar_mx.
Qed.
Lemma comm_horner_mx A B p : comm_mx A B -> comm_mx (horner_mx A p) B.
Proof. by move=> ?; apply/comm_mx_sym/comm_mx_horner/comm_mx_sym. Qed.
Lemma comm_horner_mx2 A p q : GRing.comm (horner_mx A p) (horner_mx A q).
Proof. exact/comm_mx_horner/comm_horner_mx. Qed.
End HornerMx.
Lemma horner_mx_stable (K : fieldType) m n p
(V : 'M[K]_(n.+1, m.+1)) (f : 'M_m.+1) :
stablemx V f -> stablemx V (horner_mx f p).
Proof.
move=> V_fstab; elim/poly_ind: p => [|p c]; first by rewrite rmorph0 stablemx0.
move=> fp_stable; rewrite rmorphD rmorphM/= horner_mx_X horner_mx_C.
by rewrite stablemxD ?stablemxM ?fp_stable ?stablemxC.
Qed.
Prenex Implicits horner_mx powers_mx.
Section CharPoly.
Variables (R : nzRingType) (n : nat) (A : 'M[R]_n).
Implicit Types p q : {poly R}.
Definition char_poly_mx := 'X%:M - map_mx (@polyC R) A.
Definition char_poly := \det char_poly_mx.
Let diagA := [seq A i i | i <- index_enum _ & true].
Let size_diagA : size diagA = n.
Proof. by rewrite -[n]card_ord size_map; have [e _ _ []] := big_enumP. Qed.
Let split_diagA :
exists2 q, \prod_(x <- diagA) ('X - x%:P) + q = char_poly & size q <= n.-1.
Proof.
rewrite [char_poly](bigD1 1%g) //=; set q := \sum_(s | _) _; exists q.
congr (_ + _); rewrite odd_perm1 mul1r big_map big_filter /=.
by apply: eq_bigr => i _; rewrite !mxE perm1 eqxx.
apply: leq_trans {q}(size_sum _ _ _) _; apply/bigmax_leqP=> s nt_s.
have{nt_s} [i nfix_i]: exists i, s i != i.
apply/existsP; rewrite -negb_forall; apply: contra nt_s => s_1.
by apply/eqP/permP=> i; apply/eqP; rewrite perm1 (forallP s_1).
apply: leq_trans (_ : #|[pred j | s j == j]|.+1 <= n.-1).
rewrite -sum1_card (@big_mkcond nat) /= size_Msign.
apply: (big_ind2 (fun p m => size p <= m.+1)) => [| p mp q mq IHp IHq | j _].
- by rewrite size_poly1.
- apply: leq_trans (size_polyMleq _ _) _.
by rewrite -subn1 -addnS leq_subLR addnA leq_add.
rewrite !mxE eq_sym !inE; case: (s j == j); first by rewrite polyseqXsubC.
by rewrite sub0r size_polyN size_polyC leq_b1.
rewrite -[n in n.-1]card_ord -(cardC (pred2 (s i) i)) card2 nfix_i !ltnS.
apply/subset_leq_card/subsetP=> j /(_ =P j) fix_j.
rewrite !inE -{1}fix_j (inj_eq perm_inj) orbb.
by apply: contraNneq nfix_i => <-; rewrite fix_j.
Qed.
Lemma size_char_poly : size char_poly = n.+1.
Proof.
have [q <- lt_q_n] := split_diagA; have le_q_n := leq_trans lt_q_n (leq_pred n).
by rewrite size_polyDl size_prod_XsubC size_diagA.
Qed.
Lemma char_poly_monic : char_poly \is monic.
Proof.
rewrite monicE -(monicP (monic_prod_XsubC diagA xpredT id)).
rewrite !lead_coefE size_char_poly.
have [q <- lt_q_n] := split_diagA; have le_q_n := leq_trans lt_q_n (leq_pred n).
by rewrite size_prod_XsubC size_diagA coefD (nth_default 0 le_q_n) addr0.
Qed.
Lemma char_poly_trace : n > 0 -> char_poly`_n.-1 = - \tr A.
Proof.
move=> n_gt0; have [q <- lt_q_n] := split_diagA; set p := \prod_(x <- _) _.
rewrite coefD {q lt_q_n}(nth_default 0 lt_q_n) addr0.
have{n_gt0} ->: p`_n.-1 = ('X * p)`_n by rewrite coefXM eqn0Ngt n_gt0.
have ->: \tr A = \sum_(x <- diagA) x by rewrite big_map big_filter.
rewrite -size_diagA {}/p; elim: diagA => [|x d IHd].
by rewrite !big_nil mulr1 coefX oppr0.
rewrite !big_cons coefXM mulrBl coefB IHd opprD addrC; congr (- _ + _).
rewrite mul_polyC coefZ [size _]/= -(size_prod_XsubC _ id) -lead_coefE.
by rewrite (monicP _) ?monic_prod_XsubC ?mulr1.
Qed.
Lemma char_poly_det : char_poly`_0 = (- 1) ^+ n * \det A.
Proof.
rewrite big_distrr coef_sum [0%N]lock /=; apply: eq_bigr => s _.
rewrite -{1}rmorphN -rmorphXn mul_polyC coefZ /=.
rewrite mulrA -exprD addnC exprD -mulrA -lock; congr (_ * _).
transitivity (\prod_(i < n) - A i (s i)); last by rewrite prodrN card_ord.
elim: (index_enum _) => [|i e IHe]; rewrite !(big_nil, big_cons) ?coef1 //.
by rewrite coefM big_ord1 IHe !mxE coefB coefC coefMn coefX mul0rn sub0r.
Qed.
End CharPoly.
Prenex Implicits char_poly_mx char_poly.
Lemma mx_poly_ring_isom (R : nzRingType) n' (n := n'.+1) :
exists phi : {rmorphism 'M[{poly R}]_n -> {poly 'M[R]_n}},
[/\ bijective phi,
forall p, phi p%:M = map_poly scalar_mx p,
forall A, phi (map_mx polyC A) = A%:P
& forall A i j k, (phi A)`_k i j = (A i j)`_k].
Proof.
set M_RX := 'M[{poly R}]_n; set MR_X := ({poly 'M[R]_n}).
pose Msize (A : M_RX) := \max_i \max_j size (A i j).
pose phi (A : M_RX) := \poly_(k < Msize A) \matrix_(i, j) (A i j)`_k.
have coef_phi A i j k: (phi A)`_k i j = (A i j)`_k.
rewrite coef_poly; case: (ltnP k _) => le_m_k; rewrite mxE // nth_default //.
by apply: leq_trans (leq_trans (leq_bigmax i) le_m_k); apply: (leq_bigmax j).
have phi_is_zmod_morphism : zmod_morphism phi.
move=> A B; apply/polyP => k; apply/matrixP => i j.
by rewrite !(coef_phi, mxE, coefD, coefN).
have phi_is_monoid_morphism : monoid_morphism phi.
split=> [|A B]; apply/polyP => k; apply/matrixP => i j.
by rewrite coef_phi mxE coefMn !coefC; case: (k == _); rewrite ?mxE ?mul0rn.
rewrite !coef_phi !mxE !coefM summxE coef_sum.
pose F k1 k2 := (A i k1)`_k2 * (B k1 j)`_(k - k2).
transitivity (\sum_k1 \sum_(k2 < k.+1) F k1 k2); rewrite {}/F.
by apply: eq_bigr=> k1 _; rewrite coefM.
rewrite exchange_big /=; apply: eq_bigr => k2 _.
by rewrite mxE; apply: eq_bigr => k1 _; rewrite !coef_phi.
have bij_phi: bijective phi.
exists (fun P : MR_X => \matrix_(i, j) \poly_(k < size P) P`_k i j) => [A|P].
apply/matrixP=> i j; rewrite mxE; apply/polyP=> k.
rewrite coef_poly -coef_phi.
by case: leqP => // P_le_k; rewrite nth_default ?mxE.
apply/polyP=> k; apply/matrixP=> i j; rewrite coef_phi mxE coef_poly.
by case: leqP => // P_le_k; rewrite nth_default ?mxE.
pose phiaM := GRing.isZmodMorphism.Build _ _ phi phi_is_zmod_morphism.
pose phimM := GRing.isMonoidMorphism.Build _ _ phi phi_is_monoid_morphism.
pose phiRM : {rmorphism _ -> _} := HB.pack phi phiaM phimM.
exists phiRM; split=> // [p | A]; apply/polyP=> k; apply/matrixP=> i j.
by rewrite coef_phi coef_map !mxE coefMn.
by rewrite coef_phi !mxE !coefC; case k; last rewrite /= mxE.
Qed.
Theorem Cayley_Hamilton (R : comNzRingType) n' (A : 'M[R]_n'.+1) :
horner_mx A (char_poly A) = 0.
Proof.
have [phi [_ phiZ phiC _]] := mx_poly_ring_isom R n'.
apply/rootP/factor_theorem; rewrite -phiZ -mul_adj_mx rmorphM /=.
by move: (phi _) => q; exists q; rewrite rmorphB phiC phiZ map_polyX.
Qed.
Lemma eigenvalue_root_char (F : fieldType) n (A : 'M[F]_n) a :
eigenvalue A a = root (char_poly A) a.
Proof.
transitivity (\det (a%:M - A) == 0).
apply/eigenvalueP/det0P=> [[v Av_av v_nz] | [v v_nz Av_av]]; exists v => //.
by rewrite mulmxBr Av_av mul_mx_scalar subrr.
by apply/eqP; rewrite -mul_mx_scalar eq_sym -subr_eq0 -mulmxBr Av_av.
congr (_ == 0); rewrite horner_sum; apply: eq_bigr => s _.
rewrite hornerM horner_exp !hornerE; congr (_ * _).
rewrite (big_morph _ (fun p q => hornerM p q a) (hornerC 1 a)).
by apply: eq_bigr => i _; rewrite !mxE !(hornerE, hornerMn).
Qed.
Lemma char_poly_trig {R : comNzRingType} n (A : 'M[R]_n) : is_trig_mx A ->
char_poly A = \prod_(i < n) ('X - (A i i)%:P).
Proof.
move=> /is_trig_mxP Atrig; rewrite /char_poly det_trig.
by apply: eq_bigr => i; rewrite !mxE eqxx.
by apply/is_trig_mxP => i j lt_ij; rewrite !mxE -val_eqE ltn_eqF ?Atrig ?subrr.
Qed.
Definition companionmx {R : nzRingType} (p : seq R) (d := (size p).-1) :=
\matrix_(i < d, j < d)
if (i == d.-1 :> nat) then - p`_j else (i.+1 == j :> nat)%:R.
Lemma companionmxK {R : comNzRingType} (p : {poly R}) :
p \is monic -> char_poly (companionmx p) = p.
Proof.
pose D n : 'M[{poly R}]_n := \matrix_(i, j)
('X *+ (i == j.+1 :> nat) - ((i == j)%:R)%:P).
have detD n : \det (D n) = (-1) ^+ n.
elim: n => [|n IHn]; first by rewrite det_mx00.
rewrite (expand_det_row _ ord0) big_ord_recl !mxE /= sub0r.
rewrite big1 ?addr0; last by move=> i _; rewrite !mxE /= subrr mul0r.
rewrite /cofactor mul1r [X in \det X](_ : _ = D _) ?IHn ?exprS//.
by apply/matrixP=> i j; rewrite !mxE /= /bump !add1n eqSS.
elim/poly_ind: p => [|p c IHp].
by rewrite monicE lead_coef0 eq_sym oner_eq0.
have [->|p_neq0] := eqVneq p 0.
rewrite mul0r add0r monicE lead_coefC => /eqP->.
by rewrite /companionmx /char_poly size_poly1 det_mx00.
rewrite monicE lead_coefDl ?lead_coefMX => [p_monic|]; last first.
rewrite size_polyC size_mulX ?polyX_eq0// ltnS.
by rewrite (leq_trans (leq_b1 _)) ?size_poly_gt0.
rewrite -[in RHS]IHp // /companionmx size_MXaddC (negPf p_neq0) /=.
rewrite /char_poly polySpred //.
have [->|spV1_gt0] := posnP (size p).-1.
rewrite [X in \det X]mx11_scalar det_scalar1 !mxE ?eqxx det_mx00.
by rewrite mul1r -horner_coef0 hornerMXaddC mulr0 add0r rmorphN opprK.
rewrite (expand_det_col _ ord0) /= -[(size p).-1]prednK //.
rewrite big_ord_recr big_ord_recl/= big1 ?add0r //=; last first.
move=> i _; rewrite !mxE -val_eqE /= /bump leq0n add1n eqSS.
by rewrite ltn_eqF ?subrr ?mul0r.
rewrite !mxE ?subnn -horner_coef0 /= hornerMXaddC.
rewrite !(eqxx, mulr0, add0r, addr0, subr0, rmorphN, opprK)/=.
rewrite mulrC /cofactor; congr (_ * 'X + _).
rewrite /cofactor -signr_odd oddD addbb mul1r; congr (\det _).
apply/matrixP => i j; rewrite !mxE -val_eqE coefD coefMX coefC.
by rewrite /= /bump /= !add1n !eqSS addr0.
rewrite /cofactor [X in \det X](_ : _ = D _).
by rewrite detD /= addn0 -signr_odd -signr_addb addbb mulr1.
apply/matrixP=> i j; rewrite !mxE -!val_eqE /= /bump /=.
by rewrite leqNgt ltn_ord add0n add1n [_ == _.-2.+1]ltn_eqF.
Qed.
Lemma mulmx_delta_companion (R : nzRingType) (p : seq R)
(i: 'I_(size p).-1) (i_small : i.+1 < (size p).-1):
delta_mx 0 i *m companionmx p = delta_mx 0 (Ordinal i_small) :> 'rV__.
Proof.
apply/rowP => j; rewrite !mxE (bigD1 i) //= ?(=^~val_eqE, mxE) /= eqxx mul1r.
rewrite ltn_eqF ?big1 ?addr0 1?eq_sym //; last first.
by rewrite -ltnS prednK // (leq_trans _ i_small).
by move=> k /negPf ki_eqF; rewrite !mxE eqxx ki_eqF mul0r.
Qed.
Lemma row'_col'_char_poly_mx {R : nzRingType} m i (M : 'M[R]_m) :
row' i (col' i (char_poly_mx M)) = char_poly_mx (row' i (col' i M)).
Proof. by apply/matrixP => k l; rewrite !mxE (inj_eq lift_inj). Qed.
Lemma char_block_diag_mx {R : nzRingType} m n (A : 'M[R]_m) (B : 'M[R]_n) :
char_poly_mx (block_mx A 0 0 B) =
block_mx (char_poly_mx A) 0 0 (char_poly_mx B).
Proof.
rewrite /char_poly_mx map_block_mx/= !map_mx0.
by rewrite scalar_mx_block opp_block_mx add_block_mx !subr0.
Qed.
Section MinPoly.
Variables (F : fieldType) (n' : nat).
Local Notation n := n'.+1.
Variable A : 'M[F]_n.
Implicit Types p q : {poly F}.
Fact degree_mxminpoly_proof : exists d, \rank (powers_mx A d.+1) <= d.
Proof. by exists (n ^ 2)%N; rewrite rank_leq_col. Qed.
Definition degree_mxminpoly := ex_minn degree_mxminpoly_proof.
Local Notation d := degree_mxminpoly.
Local Notation Ad := (powers_mx A d).
Lemma mxminpoly_nonconstant : d > 0.
Proof.
rewrite /d; case: ex_minnP => -[] //; rewrite leqn0 mxrank_eq0; move/eqP.
by move/row_matrixP/(_ 0)/eqP; rewrite rowK row0 mxvec_eq0 -mxrank_eq0 mxrank1.
Qed.
Lemma minpoly_mx1 : (1%:M \in Ad)%MS.
Proof.
by apply: (eq_row_sub (Ordinal mxminpoly_nonconstant)); rewrite rowK.
Qed.
Lemma minpoly_mx_free : row_free Ad.
Proof.
have:= mxminpoly_nonconstant; rewrite /d; case: ex_minnP => -[] // d' _ /(_ d').
by move/implyP; rewrite ltnn implybF -ltnS ltn_neqAle rank_leq_row andbT negbK.
Qed.
Lemma horner_mx_mem p : (horner_mx A p \in Ad)%MS.
Proof.
elim/poly_ind: p => [|p a IHp]; first by rewrite rmorph0 // linear0 sub0mx.
rewrite rmorphD rmorphM /= horner_mx_C horner_mx_X.
rewrite addrC -scalemx1 linearP /= -(mul_vec_lin (mulmxr A)).
case/submxP: IHp => u ->{p}.
have: (powers_mx A (1 + d) <= Ad)%MS.
rewrite -(geq_leqif (mxrank_leqif_sup _)).
by rewrite (eqnP minpoly_mx_free) /d; case: ex_minnP.
rewrite addnC; apply/row_subP=> i.
by apply: eq_row_sub (lshift 1 i) _; rewrite !rowK.
apply: submx_trans; rewrite addmx_sub ?scalemx_sub //.
by apply: (eq_row_sub 0); rewrite rowK.
rewrite -mulmxA mulmx_sub {u}//; apply/row_subP=> i.
rewrite row_mul rowK mul_vec_lin /= mulmxE -exprSr.
by apply: (eq_row_sub (rshift 1 i)); rewrite rowK.
Qed.
Definition mx_inv_horner B := rVpoly (mxvec B *m pinvmx Ad).
Lemma mx_inv_horner0 : mx_inv_horner 0 = 0.
Proof. by rewrite /mx_inv_horner !(linear0, mul0mx). Qed.
Lemma mx_inv_hornerK B : (B \in Ad)%MS -> horner_mx A (mx_inv_horner B) = B.
Proof. by move=> sBAd; rewrite horner_rVpoly mulmxKpV ?mxvecK. Qed.
Lemma minpoly_mxM B C : (B \in Ad -> C \in Ad -> B * C \in Ad)%MS.
Proof.
move=> AdB AdC; rewrite -(mx_inv_hornerK AdB) -(mx_inv_hornerK AdC).
by rewrite -rmorphM ?horner_mx_mem.
Qed.
Lemma minpoly_mx_ring : mxring Ad.
Proof.
apply/andP; split; first exact/mulsmx_subP/minpoly_mxM.
apply/mxring_idP; exists 1%:M; split=> *; rewrite ?mulmx1 ?mul1mx //.
by rewrite -mxrank_eq0 mxrank1.
exact: minpoly_mx1.
Qed.
Definition mxminpoly := 'X^d - mx_inv_horner (A ^+ d).
Local Notation p_A := mxminpoly.
Lemma size_mxminpoly : size p_A = d.+1.
Proof. by rewrite size_polyDl ?size_polyXn // size_polyN ltnS size_poly. Qed.
Lemma mxminpoly_monic : p_A \is monic.
Proof.
rewrite monicE /lead_coef size_mxminpoly coefB coefXn eqxx /=.
by rewrite nth_default ?size_poly // subr0.
Qed.
Lemma size_mod_mxminpoly p : size (p %% p_A) <= d.
Proof.
by rewrite -ltnS -size_mxminpoly ltn_modp // -size_poly_eq0 size_mxminpoly.
Qed.
Lemma mx_root_minpoly : horner_mx A p_A = 0.
Proof.
rewrite rmorphB -{3}(horner_mx_X A) -rmorphXn /=.
by rewrite mx_inv_hornerK ?subrr ?horner_mx_mem.
Qed.
Lemma horner_rVpolyK (u : 'rV_d) :
mx_inv_horner (horner_mx A (rVpoly u)) = rVpoly u.
Proof.
congr rVpoly; rewrite horner_rVpoly vec_mxK.
by apply: (row_free_inj minpoly_mx_free); rewrite mulmxKpV ?submxMl.
Qed.
Lemma horner_mxK p : mx_inv_horner (horner_mx A p) = p %% p_A.
Proof.
rewrite {1}(Pdiv.IdomainMonic.divp_eq mxminpoly_monic p) rmorphD rmorphM /=.
rewrite mx_root_minpoly mulr0 add0r.
by rewrite -(poly_rV_K (size_mod_mxminpoly _)) horner_rVpolyK.
Qed.
Lemma mxminpoly_min p : horner_mx A p = 0 -> p_A %| p.
Proof. by move=> pA0; rewrite /dvdp -horner_mxK pA0 mx_inv_horner0. Qed.
Lemma mxminpoly_minP p : reflect (horner_mx A p = 0) (p_A %| p).
Proof.
apply: (iffP idP); last exact: mxminpoly_min.
by move=> /Pdiv.Field.dvdpP[q ->]; rewrite rmorphM/= mx_root_minpoly mulr0.
Qed.
Lemma dvd_mxminpoly p : (p_A %| p) = (horner_mx A p == 0).
Proof. exact/mxminpoly_minP/eqP. Qed.
Lemma horner_rVpoly_inj : injective (horner_mx A \o rVpoly : 'rV_d -> 'M_n).
Proof.
apply: can_inj (poly_rV \o mx_inv_horner) _ => u /=.
by rewrite horner_rVpolyK rVpolyK.
Qed.
Lemma mxminpoly_linear_is_scalar : (d <= 1) = is_scalar_mx A.
Proof.
have scalP := has_non_scalar_mxP minpoly_mx1.
rewrite leqNgt -(eqnP minpoly_mx_free); apply/scalP/idP=> [|[[B]]].
case scalA: (is_scalar_mx A); [by right | left].
by exists A; rewrite ?scalA // -{1}(horner_mx_X A) horner_mx_mem.
move/mx_inv_hornerK=> <- nsB; case/is_scalar_mxP=> a defA; case/negP: nsB.
move: {B}(_ B); apply: poly_ind => [|p c].
by rewrite rmorph0 ?mx0_is_scalar.
rewrite rmorphD ?rmorphM /= horner_mx_X defA; case/is_scalar_mxP=> b ->.
by rewrite -rmorphM horner_mx_C -rmorphD /= scalar_mx_is_scalar.
Qed.
Lemma mxminpoly_dvd_char : p_A %| char_poly A.
Proof. exact/mxminpoly_min/Cayley_Hamilton. Qed.
Lemma eigenvalue_root_min a : eigenvalue A a = root p_A a.
Proof.
apply/idP/idP=> Aa; last first.
rewrite eigenvalue_root_char !root_factor_theorem in Aa *.
exact: dvdp_trans Aa mxminpoly_dvd_char.
have{Aa} [v Av_av v_nz] := eigenvalueP Aa.
apply: contraR v_nz => pa_nz; rewrite -{pa_nz}(eqmx_eq0 (eqmx_scale _ pa_nz)).
apply/eqP; rewrite -(mulmx0 _ v) -mx_root_minpoly.
elim/poly_ind: p_A => [|p c IHp].
by rewrite rmorph0 horner0 scale0r mulmx0.
rewrite !hornerE rmorphD rmorphM /= horner_mx_X horner_mx_C scalerDl.
by rewrite -scalerA mulmxDr mul_mx_scalar mulmxA -IHp -scalemxAl Av_av.
Qed.
Lemma root_mxminpoly a : root p_A a = root (char_poly A) a.
Proof. by rewrite -eigenvalue_root_min eigenvalue_root_char. Qed.
End MinPoly.
Lemma mxminpoly_diag {F : fieldType} {n} (d : 'rV[F]_n.+1)
(u := undup [seq d 0 i | i <- enum 'I_n.+1]) :
mxminpoly (diag_mx d) = \prod_(r <- u) ('X - r%:P).
Proof.
apply/eqP; rewrite -eqp_monic ?mxminpoly_monic ?monic_prod_XsubC// /eqp.
rewrite mxminpoly_min/=; last first.
rewrite horner_mx_diag; apply/matrixP => i j; rewrite !mxE horner_prod.
case: (altP (i =P j)) => [->|neq_ij//]; rewrite mulr1n.
rewrite (bigD1_seq (d 0 j)) ?undup_uniq ?mem_undup ?map_f// /=.
by rewrite hornerD hornerN hornerX hornerC subrr mul0r.
apply: uniq_roots_dvdp; last by rewrite uniq_rootsE undup_uniq.
apply/allP => x; rewrite mem_undup root_mxminpoly char_poly_trig//.
rewrite -(big_map _ predT (fun x => _ - x%:P)) root_prod_XsubC.
by move=> /mapP[i _ ->]; apply/mapP; exists i; rewrite ?(mxE, eqxx).
Qed.
Prenex Implicits degree_mxminpoly mxminpoly mx_inv_horner.
Arguments mx_inv_hornerK {F n' A} [B] AnB.
Arguments horner_rVpoly_inj {F n' A} [u1 u2] eq_u12A : rename.
(* Parametricity. *)
Section MapRingMatrix.
Variables (aR rR : nzRingType) (f : {rmorphism aR -> rR}).
Local Notation "A ^f" := (map_mx (GRing.RMorphism.sort f) A) : ring_scope.
Local Notation fp := (map_poly (GRing.RMorphism.sort f)).
Variables (d n : nat) (A : 'M[aR]_n).
Lemma map_rVpoly (u : 'rV_d) : fp (rVpoly u) = rVpoly u^f.
Proof.
apply/polyP=> k; rewrite coef_map !coef_rVpoly.
by case: (insub k) => [i|]; rewrite /= ?rmorph0 // mxE.
Qed.
Lemma map_poly_rV p : (poly_rV p)^f = poly_rV (fp p) :> 'rV_d.
Proof. by apply/rowP=> j; rewrite !mxE coef_map. Qed.
Lemma map_char_poly_mx : map_mx fp (char_poly_mx A) = char_poly_mx A^f.
Proof.
rewrite raddfB /= map_scalar_mx /= map_polyX; congr (_ - _).
by apply/matrixP=> i j; rewrite !mxE map_polyC.
Qed.
Lemma map_char_poly : fp (char_poly A) = char_poly A^f.
Proof. by rewrite -det_map_mx map_char_poly_mx. Qed.
End MapRingMatrix.
Section MapResultant.
Lemma map_resultant (aR rR : nzRingType) (f : {rmorphism {poly aR} -> rR}) p q :
f (lead_coef p) != 0 -> f (lead_coef q) != 0 ->
f (resultant p q)= resultant (map_poly f p) (map_poly f q).
Proof.
move=> nz_fp nz_fq; rewrite /resultant /Sylvester_mx !size_map_poly_id0 //.
rewrite -det_map_mx /= map_col_mx; congr (\det (col_mx _ _));
by apply: map_lin1_mx => v; rewrite map_poly_rV rmorphM /= map_rVpoly.
Qed.
End MapResultant.
Section MapComRing.
Variables (aR rR : comNzRingType) (f : {rmorphism aR -> rR}).
Local Notation "A ^f" := (map_mx f A) : ring_scope.
Local Notation fp := (map_poly f).
Variables (n' : nat) (A : 'M[aR]_n'.+1).
Lemma map_powers_mx e : (powers_mx A e)^f = powers_mx A^f e.
Proof. by apply/row_matrixP=> i; rewrite -map_row !rowK map_mxvec rmorphXn. Qed.
Lemma map_horner_mx p : (horner_mx A p)^f = horner_mx A^f (fp p).
Proof.
rewrite -[p](poly_rV_K (leqnn _)) map_rVpoly.
by rewrite !horner_rVpoly map_vec_mx map_mxM map_powers_mx.
Qed.
End MapComRing.
Section MapField.
Variables (aF rF : fieldType) (f : {rmorphism aF -> rF}).
Local Notation "A ^f" := (map_mx f A) : ring_scope.
Local Notation fp := (map_poly f).
Variables (n' : nat) (A : 'M[aF]_n'.+1) (p : {poly aF}).
Lemma map_mx_companion (e := congr1 predn (size_map_poly _ _)) :
(companionmx p)^f = castmx (e, e) (companionmx (fp p)).
Proof.
apply/matrixP => i j; rewrite !(castmxE, mxE) /= (fun_if f).
by rewrite rmorphN coef_map size_map_poly rmorph_nat.
Qed.
Lemma companion_map_poly (e := esym (congr1 predn (size_map_poly _ _))) :
companionmx (fp p) = castmx (e, e) (companionmx p)^f.
Proof. by rewrite map_mx_companion castmx_comp castmx_id. Qed.
Lemma degree_mxminpoly_map : degree_mxminpoly A^f = degree_mxminpoly A.
Proof. by apply: eq_ex_minn => e; rewrite -map_powers_mx mxrank_map. Qed.
Lemma mxminpoly_map : mxminpoly A^f = fp (mxminpoly A).
Proof.
rewrite rmorphB; congr (_ - _).
by rewrite /= map_polyXn degree_mxminpoly_map.
rewrite degree_mxminpoly_map -rmorphXn /=.
apply/polyP=> i; rewrite coef_map //= !coef_rVpoly degree_mxminpoly_map.
case/insub: i => [i|]; last by rewrite rmorph0.
by rewrite -map_powers_mx -map_pinvmx // -map_mxvec -map_mxM // mxE.
Qed.
Lemma map_mx_inv_horner u : fp (mx_inv_horner A u) = mx_inv_horner A^f u^f.
Proof.
rewrite map_rVpoly map_mxM map_mxvec map_pinvmx map_powers_mx.
by rewrite /mx_inv_horner degree_mxminpoly_map.
Qed.
End MapField.
Section KernelLemmas.
Variable K : fieldType.
(* convertible to kermx (horner_mx g p) when n = n.+1 *)
Definition kermxpoly n (g : 'M_n) (p : {poly K}) : 'M_n :=
kermx ((if n is n.+1 then horner_mx^~ p : 'M_n.+1 -> 'M_n.+1 else \0) g).
Lemma kermxpolyC n (g : 'M_n) c : c != 0 -> kermxpoly g c%:P = 0.
Proof.
move=> c_neq0; case: n => [|n] in g *; first by rewrite thinmx0.
apply/eqP; rewrite /kermxpoly horner_mx_C kermx_eq0 row_free_unit.
by rewrite -scalemx1 scaler_unit ?unitmx1// unitfE.
Qed.
Lemma kermxpoly1 n (g : 'M_n) : kermxpoly g 1 = 0.
Proof. by rewrite kermxpolyC ?oner_eq0. Qed.
Lemma kermxpolyX n (g : 'M_n) : kermxpoly g 'X = kermx g.
Proof.
case: n => [|n] in g *; first by rewrite !thinmx0.
by rewrite /kermxpoly horner_mx_X.
Qed.
Lemma kermxpoly_min n (g : 'M[K]_n.+1) p :
mxminpoly g %| p -> (kermxpoly g p :=: 1)%MS.
Proof. by rewrite /kermxpoly => /mxminpoly_minP ->; apply: kermx0. Qed.
Lemma comm_mx_stable_kermxpoly n (f g : 'M_n) (p : {poly K}) : comm_mx f g ->
stablemx (kermxpoly f p) g.
Proof.
case: n => [|n] in f g *; first by rewrite !thinmx0.
move=> fg; rewrite /kermxpoly; apply: comm_mx_stable_ker.
by apply/comm_mx_sym/comm_mx_horner/comm_mx_sym.
Qed.
Lemma mxdirect_kermxpoly n (g : 'M_n) (p q : {poly K}) :
coprimep p q -> (kermxpoly g p :&: kermxpoly g q = 0)%MS.
Proof.
case: n => [|n] in g *; first by rewrite thinmx0 ?cap0mx ?submx_refl.
move=> /Bezout_eq1_coprimepP [[/= u v]]; rewrite mulrC [v * _]mulrC => cpq.
apply/eqP/rowV0P => x.
rewrite sub_capmx => /andP[/sub_kermxP xgp0 /sub_kermxP xgq0].
move: cpq => /(congr1 (mulmx x \o horner_mx g))/=.
rewrite !(rmorphM, rmorphD, rmorph1, mulmx1, mulmxDr, mulmxA).
by rewrite xgp0 xgq0 !mul0mx add0r.
Qed.
Lemma kermxpolyM n (g : 'M_n) (p q : {poly K}) : coprimep p q ->
(kermxpoly g (p * q) :=: kermxpoly g p + kermxpoly g q)%MS.
Proof.
case: n => [|n] in g *; first by rewrite !thinmx0.
move=> /Bezout_eq1_coprimepP [[/= u v]]; rewrite mulrC [v * _]mulrC => cpq.
apply/eqmxP/andP; split; last first.
apply/sub_kermxP/eqmx0P; rewrite !addsmxMr [in X in (_ + X)%MS]mulrC.
by rewrite !rmorphM/= !mulmxA !mulmx_ker !mul0mx !addsmx0 submx_refl.
move: cpq => /(congr1 (horner_mx g))/=; rewrite rmorph1 rmorphD/=.
rewrite -[X in (X <= _)%MS]mulr1 => <-; rewrite mulrDr [p * u]mulrC addrC.
rewrite addmx_sub_adds//; apply/sub_kermxP; rewrite mulmxE -mulrA -rmorphM.
by rewrite mulrAC [q * p]mulrC rmorphM/= mulrA -!mulmxE mulmx_ker mul0mx.
rewrite -[_ * _ * q]mulrA [u * _]mulrC.
by rewrite rmorphM mulrA -!mulmxE mulmx_ker mul0mx.
Qed.
Lemma kermxpoly_prod n (g : 'M_n)
(I : finType) (P : {pred I}) (p_ : I -> {poly K}) :
{in P &, forall i j, j != i -> coprimep (p_ i) (p_ j)} ->
(kermxpoly g (\prod_(i | P i) p_ i) :=: \sum_(i | P i) kermxpoly g (p_ i))%MS.
Proof.
move=> p_coprime; elim: index_enum (index_enum_uniq I).
by rewrite !big_nil ?kermxpoly1 ?submx_refl//.
move=> j js ihjs /= /andP[jNjs js_uniq]; apply/eqmxP.
rewrite !big_cons; case: ifP => [Pj|PNj]; rewrite ?ihjs ?submx_refl//.
suff cjjs: coprimep (p_ j) (\prod_(i <- js | P i) p_ i).
by rewrite !kermxpolyM// !(adds_eqmx (eqmx_refl _) (ihjs _)) ?submx_refl.
rewrite (@big_morph _ _ _ true andb) ?big_all_cond ?coprimep1//; last first.
by move=> p q; rewrite coprimepMr.
apply/allP => i i_js; apply/implyP => Pi; apply: p_coprime => //.
by apply: contraNneq jNjs => <-.
Qed.
Lemma mxdirect_sum_kermx n (g : 'M_n)
(I : finType) (P : {pred I}) (p_ : I -> {poly K}) :
{in P &, forall i j, j != i -> coprimep (p_ i) (p_ j)} ->
mxdirect (\sum_(i | P i) kermxpoly g (p_ i))%MS.
Proof.
move=> p_coprime; apply/mxdirect_sumsP => i Pi; apply/eqmx0P.
have cpNi : {in [pred j | P j && (j != i)] &,
forall j k : I, k != j -> coprimep (p_ j) (p_ k)}.
by move=> j k /andP[Pj _] /andP[Pk _]; apply: p_coprime.
rewrite -!(cap_eqmx (eqmx_refl _) (kermxpoly_prod g _))//.
rewrite mxdirect_kermxpoly ?submx_refl//.
rewrite (@big_morph _ _ _ true andb) ?big_all_cond ?coprimep1//; last first.
by move=> p q; rewrite coprimepMr.
by apply/allP => j _; apply/implyP => /andP[Pj neq_ji]; apply: p_coprime.
Qed.
Lemma eigenspace_poly n a (f : 'M_n) :
eigenspace f a = kermxpoly f ('X - a%:P).
Proof.
case: n => [|m] in a f *; first by rewrite !thinmx0.
by congr (kermx _); rewrite rmorphB /= ?horner_mx_X ?horner_mx_C.
Qed.
Definition geigenspace n (g : 'M_n) a := kermxpoly g (('X - a%:P) ^+ n).
Lemma geigenspaceE n' (g : 'M_n'.+1) a :
geigenspace g a = kermx ((g - a%:M) ^+ n'.+1).
Proof.
by rewrite /geigenspace /kermxpoly rmorphXn/= rmorphB/= horner_mx_X horner_mx_C.
Qed.
Lemma eigenspace_sub_geigen n (g : 'M_n) a :
(eigenspace g a <= geigenspace g a)%MS.
Proof.
case: n => [|n] in g *; rewrite ?thinmx0 ?sub0mx// geigenspaceE.
by apply/sub_kermxP; rewrite exprS mulmxA mulmx_ker mul0mx.
Qed.
Lemma mxdirect_sum_geigenspace
(I : finType) (n : nat) (g : 'M_n) (P : {pred I}) (a_ : I -> K) :
{in P &, injective a_} -> mxdirect (\sum_(i | P i) geigenspace g (a_ i)).
Proof.
move=> /inj_in_eq eq_a; apply: mxdirect_sum_kermx => i j Pi Pj Nji.
by rewrite coprimep_expr ?coprimep_expl// coprimep_XsubC root_XsubC eq_a.
Qed.
Definition eigenpoly n (g : 'M_n) : pred {poly K} :=
(fun p => kermxpoly g p != 0).
Lemma eigenpolyP n (g : 'M_n) (p : {poly K}) :
reflect (exists2 v : 'rV_n, (v <= kermxpoly g p)%MS & v != 0) (eigenpoly g p).
Proof. exact: rowV0Pn. Qed.
Lemma eigenvalue_poly n a (f : 'M_n) : eigenvalue f a = eigenpoly f ('X - a%:P).
Proof. by rewrite /eigenpoly /eigenvalue eigenspace_poly. Qed.
Lemma comm_mx_stable_geigenspace n (f g : 'M_n) a : comm_mx f g ->
stablemx (geigenspace f a) g.
Proof. exact: comm_mx_stable_kermxpoly. Qed.
End KernelLemmas.
Section MapKermxPoly.
Variables (aF rF : fieldType) (f : {rmorphism aF -> rF}).
Lemma map_kermxpoly (n : nat) (g : 'M_n) (p : {poly aF}) :
map_mx f (kermxpoly g p) = kermxpoly (map_mx f g) (map_poly f p).
Proof.
by case: n => [|n] in g *; rewrite ?thinmx0// map_kermx map_horner_mx.
Qed.
Lemma map_geigenspace (n : nat) (g : 'M_n) (a : aF) :
map_mx f (geigenspace g a) = geigenspace (map_mx f g) (f a).
Proof. by rewrite map_kermxpoly rmorphXn/= rmorphB /= map_polyX map_polyC. Qed.
Lemma eigenpoly_map n (g : 'M_n) (p : {poly aF}) :
eigenpoly (map_mx f g) (map_poly f p) = eigenpoly g p.
Proof. by rewrite /eigenpoly -map_kermxpoly map_mx_eq0. Qed.
End MapKermxPoly.
Section IntegralOverRing.
Definition integralOver (R K : nzRingType) (RtoK : R -> K) (z : K) :=
exists2 p, p \is monic & root (map_poly RtoK p) z.
Definition integralRange R K RtoK := forall z, @integralOver R K RtoK z.
Variables (B R K : nzRingType) (BtoR : B -> R) (RtoK : {rmorphism R -> K}).
Lemma integral_rmorph x :
integralOver BtoR x -> integralOver (RtoK \o BtoR) (RtoK x).
Proof. by case=> p; exists p; rewrite // map_poly_comp rmorph_root. Qed.
Lemma integral_id x : integralOver RtoK (RtoK x).
Proof. by exists ('X - x%:P); rewrite ?monicXsubC ?rmorph_root ?root_XsubC. Qed.
Lemma integral_nat n : integralOver RtoK n%:R.
Proof. by rewrite -(rmorph_nat RtoK); apply: integral_id. Qed.
Lemma integral0 : integralOver RtoK 0. Proof. exact: (integral_nat 0). Qed.
Lemma integral1 : integralOver RtoK 1. Proof. exact: (integral_nat 1). Qed.
Lemma integral_poly (p : {poly K}) :
(forall i, integralOver RtoK p`_i) <-> {in p : seq K, integralRange RtoK}.
Proof.
split=> intRp => [_ /(nthP 0)[i _ <-] // | i]; rewrite -[p]coefK coef_poly.
by case: ifP => [ltip | _]; [apply/intRp/mem_nth | apply: integral0].
Qed.
End IntegralOverRing.
Section IntegralOverComRing.
Variables (R K : comNzRingType) (RtoK : {rmorphism R -> K}).
Lemma integral_horner_root w (p q : {poly K}) :
p \is monic -> root p w ->
{in p : seq K, integralRange RtoK} -> {in q : seq K, integralRange RtoK} ->
integralOver RtoK q.[w].
Proof.
move=> mon_p pw0 intRp intRq.
pose memR y := exists x, y = RtoK x.
have memRid x: memR (RtoK x) by exists x.
have memR_nat n: memR n%:R by rewrite -(rmorph_nat RtoK) /=.
have [memR0 memR1]: memR 0 * memR 1 := (memR_nat 0, memR_nat 1).
have memRN1: memR (- 1) by exists (- 1); rewrite rmorphN1.
pose rVin (E : K -> Prop) n (a : 'rV[K]_n) := forall i, E (a 0 i).
pose pXin (E : K -> Prop) (r : {poly K}) := forall i, E r`_i.
pose memM E n (X : 'rV_n) y := exists a, rVin E n a /\ y = (a *m X^T) 0 0.
pose finM E S := exists n, exists X, forall y, memM E n X y <-> S y.
have tensorM E n1 n2 X Y: finM E (memM (memM E n2 Y) n1 X).
exists (n1 * n2)%N, (mxvec (X^T *m Y)) => y.
split=> [[a [Ea Dy]] | [a1 [/fin_all_exists[a /all_and2[Ea Da1]] ->]]].
exists (Y *m (vec_mx a)^T); split=> [i|].
exists (row i (vec_mx a)); split=> [j|]; first by rewrite !mxE; apply: Ea.
by rewrite -row_mul -{1}[Y]trmxK -trmx_mul !mxE.
by rewrite -[Y]trmxK -!trmx_mul mulmxA -mxvec_dotmul trmx_mul trmxK vec_mxK.
exists (mxvec (\matrix_i a i)); split.
by case/mxvec_indexP=> i j; rewrite mxvecE mxE; apply: Ea.
rewrite -[mxvec _]trmxK -trmx_mul mxvec_dotmul -mulmxA trmx_mul !mxE.
apply: eq_bigr => i _; rewrite Da1 !mxE; congr (_ * _).
by apply: eq_bigr => j _; rewrite !mxE.
suffices [m [X [[u [_ Du]] idealM]]]: exists m,
exists X, let M := memM memR m X in M 1 /\ forall y, M y -> M (q.[w] * y).
- do [set M := memM _ m X; move: q.[w] => z] in idealM *.
have MX i: M (X 0 i).
by exists (delta_mx 0 i); split=> [j|]; rewrite -?rowE !mxE.
have /fin_all_exists[a /all_and2[Fa Da1]] i := idealM _ (MX i).
have /fin_all_exists[r Dr] i := fin_all_exists (Fa i).
pose A := \matrix_(i, j) r j i; pose B := z%:M - map_mx RtoK A.
have XB0: X *m B = 0.
apply/eqP; rewrite mulmxBr mul_mx_scalar subr_eq0; apply/eqP/rowP=> i.
by rewrite !mxE Da1 mxE; apply: eq_bigr=> j _; rewrite !mxE mulrC Dr.
exists (char_poly A); first exact: char_poly_monic.
have: (\det B *: (u *m X^T)) 0 0 == 0.
rewrite scalemxAr -linearZ -mul_mx_scalar -mul_mx_adj mulmxA XB0 /=.
by rewrite mul0mx trmx0 mulmx0 mxE.
rewrite mxE -Du mulr1 rootE -horner_evalE -2!det_map_mx; congr (\det _ == 0).
rewrite raddfB/= map_scalar_mx; apply/matrixP=> i j.
by rewrite !mxE raddfB raddfMn/= map_polyX map_polyC /horner_eval !hornerE.
pose gen1 x E y := exists2 r, pXin E r & y = r.[x]; pose gen := foldr gen1 memR.
have gen1S (E : K -> Prop) x y: E 0 -> E y -> gen1 x E y.
by exists y%:P => [i|]; rewrite ?hornerC ?coefC //; case: ifP.
have genR S y: memR y -> gen S y.
by elim: S => //= x S IH in y * => /IH; apply/gen1S/IH.
have gen0 := genR _ 0 memR0; have gen_1 := genR _ 1 memR1.
have{gen1S} genS S y: y \in S -> gen S y.
elim: S => //= x S IH /predU1P[-> | /IH//]; last exact: gen1S.
by exists 'X => [i|]; rewrite ?hornerX // coefX; apply: genR.
pose propD (R : K -> Prop) := forall x y, R x -> R y -> R (x + y).
have memRD: propD memR.
by move=> _ _ [a ->] [b ->]; exists (a + b); rewrite rmorphD.
have genD S: propD (gen S).
elim: S => //= x S IH _ _ [r1 Sr1 ->] [r2 Sr2 ->]; rewrite -hornerD.
by exists (r1 + r2) => // i; rewrite coefD; apply: IH.
have gen_sum S := big_ind _ (gen0 S) (genD S).
pose propM (R : K -> Prop) := forall x y, R x -> R y -> R (x * y).
have memRM: propM memR.
by move=> _ _ [a ->] [b ->]; exists (a * b); rewrite rmorphM.
have genM S: propM (gen S).
elim: S => //= x S IH _ _ [r1 Sr1 ->] [r2 Sr2 ->]; rewrite -hornerM.
by exists (r1 * r2) => // i; rewrite coefM; apply: gen_sum => j _; apply: IH.
have gen_horner S r y: pXin (gen S) r -> gen S y -> gen S r.[y].
move=> Sq Sy; rewrite horner_coef; apply: gen_sum => [[i _] /= _].
by elim: {2}i => [|n IHn]; rewrite ?mulr1 // exprSr mulrA; apply: genM.
pose S := w :: q ++ p; suffices [m [X defX]]: finM memR (gen S).
exists m, X => M; split=> [|y /defX Xy]; first exact/defX.
apply/defX/genM => //; apply: gen_horner => // [i|]; last exact/genS/mem_head.
rewrite -[q]coefK coef_poly; case: ifP => // lt_i_q.
by apply: genS; rewrite inE mem_cat mem_nth ?orbT.
pose intR R y := exists r, [/\ r \is monic, root r y & pXin R r].
pose fix genI s := if s is y :: s1 then intR (gen s1) y /\ genI s1 else True.
have{mon_p pw0 intRp intRq}: genI S.
split; set S1 := _ ++ _; first exists p.
split=> // i; rewrite -[p]coefK coef_poly; case: ifP => // lt_i_p.
by apply: genS; rewrite mem_cat orbC mem_nth.
set S2 := S1; have: all [in S1] S2 by apply/allP.
elim: S2 => //= y S2 IH /andP[S1y S12]; split; last exact: IH.
have{q S S1 IH S1y S12 intRp intRq} [q mon_q qx0]: integralOver RtoK y.
by move: S1y; rewrite mem_cat => /orP[]; [apply: intRq | apply: intRp].
exists (map_poly RtoK q); split=> // [|i]; first exact: monic_map.
by rewrite coef_map /=; apply: genR.
elim: {w p q}S => /= [_|x S IH [[p [mon_p px0 Sp]] /IH{IH}[m2 [X2 defS]]]].
exists 1, 1 => y; split=> [[a [Fa ->]] | Fy].
by rewrite tr_scalar_mx mulmx1; apply: Fa.
by exists y%:M; split=> [i|]; rewrite 1?ord1 ?tr_scalar_mx ?mulmx1 mxE.
pose m1 := (size p).-1; pose X1 := \row_(i < m1) x ^+ i.
have [m [X defM]] := tensorM memR m1 m2 X1 X2; set M := memM _ _ _ in defM.
exists m, X => y; rewrite -/M; split=> [/defM[a [M2a]] | [q Sq]] -> {y}.
exists (rVpoly a) => [i|].
by rewrite coef_rVpoly; case/insub: i => // i; apply/defS/M2a.
rewrite mxE (horner_coef_wide _ (size_poly _ _)) -/(rVpoly a).
by apply: eq_bigr => i _; rewrite coef_rVpoly_ord !mxE.
have M_0: M 0 by exists 0; split=> [i|]; rewrite ?mul0mx mxE.
have M_D: propD M.
move=> _ _ [a [Fa ->]] [b [Fb ->]]; exists (a + b).
by rewrite mulmxDl !mxE; split=> // i /[1!mxE]; apply: memRD.
have{M_0 M_D} Msum := big_ind _ M_0 M_D.
rewrite horner_coef; apply: (Msum) => i _; case: i q`_i {Sq}(Sq i) => /=.
elim: {q}(size q) => // n IHn i i_le_n y Sy.
have [i_lt_m1 | m1_le_i] := ltnP i m1.
apply/defM; exists (y *: delta_mx 0 (Ordinal i_lt_m1)); split=> [j|].
by apply/defS; rewrite !mxE /= mulr_natr; case: eqP.
by rewrite -scalemxAl -rowE !mxE.
rewrite -(subnK m1_le_i) exprD -[x ^+ m1]subr0 -(rootP px0) horner_coef.
rewrite polySpred ?monic_neq0 // -/m1 big_ord_recr /= -lead_coefE.
rewrite opprD addrC (monicP mon_p) mul1r subrK !mulrN -mulNr !mulr_sumr.
apply: Msum => j _; rewrite [X in M X]mulrA mulrACA -exprD; apply: IHn.
by rewrite -addnS addnC addnBA // leq_subLR leq_add.
by rewrite -mulN1r; do 2!apply: (genM) => //; apply: genR.
Qed.
Lemma integral_root_monic u p :
p \is monic -> root p u -> {in p : seq K, integralRange RtoK} ->
integralOver RtoK u.
Proof.
move=> mon_p pu0 intRp; rewrite -[u]hornerX.
apply: integral_horner_root mon_p pu0 intRp _.
by apply/integral_poly => i; rewrite coefX; apply: integral_nat.
Qed.
Let integral0_RtoK := integral0 RtoK.
Let integral1_RtoK := integral1 RtoK.
Let monicXsubC_K := @monicXsubC K.
Hint Resolve integral0_RtoK integral1_RtoK monicXsubC_K : core.
Let XsubC0 (u : K) : root ('X - u%:P) u. Proof. by rewrite root_XsubC. Qed.
Let intR_XsubC u :
integralOver RtoK (- u) -> {in 'X - u%:P : seq K, integralRange RtoK}.
Proof. by move=> intRu v; rewrite polyseqXsubC !inE => /pred2P[]->. Qed.
Lemma integral_opp u : integralOver RtoK u -> integralOver RtoK (- u).
Proof. by rewrite -{1}[u]opprK => /intR_XsubC/integral_root_monic; apply. Qed.
Lemma integral_horner (p : {poly K}) u :
{in p : seq K, integralRange RtoK} -> integralOver RtoK u ->
integralOver RtoK p.[u].
Proof. by move=> ? /integral_opp/intR_XsubC/integral_horner_root; apply. Qed.
Lemma integral_sub u v :
integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u - v).
Proof.
move=> intRu /integral_opp/intR_XsubC/integral_horner/(_ intRu).
by rewrite !hornerE.
Qed.
Lemma integral_add u v :
integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u + v).
Proof. by rewrite -{2}[v]opprK => intRu /integral_opp; apply: integral_sub. Qed.
Lemma integral_mul u v :
integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u * v).
Proof.
rewrite -{2}[v]hornerX -hornerZ => intRu; apply: integral_horner.
by apply/integral_poly=> i; rewrite coefZ coefX mulr_natr mulrb; case: ifP.
Qed.
End IntegralOverComRing.
Section IntegralOverField.
Variables (F E : fieldType) (FtoE : {rmorphism F -> E}).
Definition algebraicOver (fFtoE : F -> E) u :=
exists2 p, p != 0 & root (map_poly fFtoE p) u.
Notation mk_mon p := ((lead_coef p)^-1 *: p).
Lemma integral_algebraic u : algebraicOver FtoE u <-> integralOver FtoE u.
Proof.
split=> [] [p p_nz pu0]; last by exists p; rewrite ?monic_neq0.
exists (mk_mon p); first by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0.
by rewrite linearZ rootE hornerZ (rootP pu0) mulr0.
Qed.
Lemma algebraic_id a : algebraicOver FtoE (FtoE a).
Proof. exact/integral_algebraic/integral_id. Qed.
Lemma algebraic0 : algebraicOver FtoE 0.
Proof. exact/integral_algebraic/integral0. Qed.
Lemma algebraic1 : algebraicOver FtoE 1.
Proof. exact/integral_algebraic/integral1. Qed.
Lemma algebraic_opp x : algebraicOver FtoE x -> algebraicOver FtoE (- x).
Proof. by move/integral_algebraic/integral_opp/integral_algebraic. Qed.
Lemma algebraic_add x y :
algebraicOver FtoE x -> algebraicOver FtoE y -> algebraicOver FtoE (x + y).
Proof.
move/integral_algebraic=> intFx /integral_algebraic intFy.
exact/integral_algebraic/integral_add.
Qed.
Lemma algebraic_sub x y :
algebraicOver FtoE x -> algebraicOver FtoE y -> algebraicOver FtoE (x - y).
Proof. by move=> algFx /algebraic_opp; apply: algebraic_add. Qed.
Lemma algebraic_mul x y :
algebraicOver FtoE x -> algebraicOver FtoE y -> algebraicOver FtoE (x * y).
Proof.
move/integral_algebraic=> intFx /integral_algebraic intFy.
exact/integral_algebraic/integral_mul.
Qed.
Lemma algebraic_inv u : algebraicOver FtoE u -> algebraicOver FtoE u^-1.
Proof.
have [-> | /expf_neq0 nz_u_n] := eqVneq u 0; first by rewrite invr0.
case=> p nz_p pu0; exists (Poly (rev p)).
apply/eqP=> /polyP/(_ 0); rewrite coef_Poly coef0 nth_rev ?size_poly_gt0 //.
by apply/eqP; rewrite subn1 lead_coef_eq0.
apply/eqP/(mulfI (nz_u_n (size p).-1)); rewrite mulr0 -(rootP pu0).
rewrite (@horner_coef_wide _ (size p)); last first.
by rewrite size_map_poly -(size_rev p) size_Poly.
rewrite horner_coef mulr_sumr size_map_poly.
rewrite [rhs in _ = rhs](reindex_inj rev_ord_inj) /=.
apply: eq_bigr => i _; rewrite !coef_map coef_Poly nth_rev // mulrCA.
by congr (_ * _); rewrite -{1}(subnKC (valP i)) addSn addnC exprD exprVn ?mulfK.
Qed.
Lemma algebraic_div x y :
algebraicOver FtoE x -> algebraicOver FtoE y -> algebraicOver FtoE (x / y).
Proof. by move=> algFx /algebraic_inv; apply: algebraic_mul. Qed.
Lemma integral_inv x : integralOver FtoE x -> integralOver FtoE x^-1.
Proof. by move/integral_algebraic/algebraic_inv/integral_algebraic. Qed.
Lemma integral_div x y :
integralOver FtoE x -> integralOver FtoE y -> integralOver FtoE (x / y).
Proof. by move=> algFx /integral_inv; apply: integral_mul. Qed.
Lemma integral_root p u :
p != 0 -> root p u -> {in p : seq E, integralRange FtoE} ->
integralOver FtoE u.
Proof.
move=> nz_p pu0 algFp.
have mon_p1: mk_mon p \is monic.
by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0.
have p1u0: root (mk_mon p) u by rewrite rootE hornerZ (rootP pu0) mulr0.
apply: integral_root_monic mon_p1 p1u0 _ => _ /(nthP 0)[i ltip <-].
rewrite coefZ mulrC; rewrite size_scale ?invr_eq0 ?lead_coef_eq0 // in ltip.
by apply: integral_div; apply/algFp/mem_nth; rewrite -?polySpred.
Qed.
End IntegralOverField.
(* Lifting term, formula, envs and eval to matrices. Wlog, and for the sake *)
(* of simplicity, we only lift (tensor) envs to row vectors; we can always *)
(* use mxvec/vec_mx to store and retrieve matrices. *)
(* We don't provide definitions for addition, subtraction, scaling, etc, *)
(* because they have simple matrix expressions. *)
Module MatrixFormula.
Section MatrixFormula.
Variable F : fieldType.
Local Notation False := GRing.False.
Local Notation True := GRing.True.
Local Notation And := GRing.And (only parsing).
Local Notation Add := GRing.Add (only parsing).
Local Notation Bool b := (GRing.Bool b%bool).
Local Notation term := (GRing.term F).
Local Notation form := (GRing.formula F).
Local Notation eval := GRing.eval.
Local Notation holds := GRing.holds.
Local Notation qf_form := GRing.qf_form.
Local Notation qf_eval := GRing.qf_eval.
Definition eval_mx (e : seq F) := @map_mx term F (eval e).
Definition mx_term := @map_mx F term GRing.Const.
Lemma eval_mx_term e m n (A : 'M_(m, n)) : eval_mx e (mx_term A) = A.
Proof. by apply/matrixP=> i j; rewrite !mxE. Qed.
Definition mulmx_term m n p (A : 'M[term]_(m, n)) (B : 'M_(n, p)) :=
\matrix_(i, k) (\big[Add/0]_j (A i j * B j k))%T.
Lemma eval_mulmx e m n p (A : 'M[term]_(m, n)) (B : 'M_(n, p)) :
eval_mx e (mulmx_term A B) = eval_mx e A *m eval_mx e B.
Proof.
apply/matrixP=> i k; rewrite !mxE /= ((big_morph (eval e)) 0 +%R) //=.
by apply: eq_bigr => j _; rewrite /= !mxE.
Qed.
Local Notation morphAnd f := ((big_morph f) true andb).
Let Schur m n (A : 'M[term]_(1 + m, 1 + n)) (a := A 0 0) :=
\matrix_(i, j) (drsubmx A i j - a^-1 * dlsubmx A i 0%R * ursubmx A 0%R j)%T.
Fixpoint mxrank_form (r m n : nat) : 'M_(m, n) -> form :=
match m, n return 'M_(m, n) -> form with
| m'.+1, n'.+1 => fun A : 'M_(1 + m', 1 + n') =>
let nzA k := A k.1 k.2 != 0 in
let xSchur k := Schur (xrow k.1 0%R (xcol k.2 0%R A)) in
let recf k := Bool (r > 0) /\ mxrank_form r.-1 (xSchur k) in
GRing.Pick nzA recf (Bool (r == 0%N))
| _, _ => fun _ => Bool (r == 0%N)
end%T.
Lemma mxrank_form_qf r m n (A : 'M_(m, n)) : qf_form (mxrank_form r A).
Proof.
by elim: m r n A => [|m IHm] r [|n] A //=; rewrite GRing.Pick_form_qf /=.
Qed.
Lemma eval_mxrank e r m n (A : 'M_(m, n)) :
qf_eval e (mxrank_form r A) = (\rank (eval_mx e A) == r).
Proof.
elim: m r n A => [|m IHm] r [|n] A /=; try by case r; rewrite unlock.
rewrite GRing.eval_Pick !unlock /=; set pf := fun _ => _.
rewrite -(@eq_pick _ pf) => [|k]; rewrite {}/pf ?mxE // eq_sym.
case: pick => [[i j]|] //=; set B := _ - _; have:= mxrankE B.
case: (Gaussian_elimination_ B) r => [[_ _] _] [|r] //= <-; rewrite {}IHm eqSS.
by congr (\rank _ == r); apply/matrixP=> k l; rewrite !(mxE, big_ord1) !tpermR.
Qed.
Lemma eval_vec_mx e m n (u : 'rV_(m * n)) :
eval_mx e (vec_mx u) = vec_mx (eval_mx e u).
Proof. by apply/matrixP=> i j; rewrite !mxE. Qed.
Lemma eval_mxvec e m n (A : 'M_(m, n)) :
eval_mx e (mxvec A) = mxvec (eval_mx e A).
Proof. by rewrite -{2}[A]mxvecK eval_vec_mx vec_mxK. Qed.
Section Subsetmx.
Variables (m1 m2 n : nat) (A : 'M[term]_(m1, n)) (B : 'M[term]_(m2, n)).
Definition submx_form :=
\big[And/True]_(r < n.+1) (mxrank_form r (col_mx A B) ==> mxrank_form r B)%T.
Lemma eval_col_mx e :
eval_mx e (col_mx A B) = col_mx (eval_mx e A) (eval_mx e B).
Proof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.
Lemma submx_form_qf : qf_form submx_form.
Proof.
by rewrite (morphAnd (@qf_form _)) ?big1 //= => r _; rewrite !mxrank_form_qf.
Qed.
Lemma eval_submx e : qf_eval e submx_form = (eval_mx e A <= eval_mx e B)%MS.
Proof.
rewrite (morphAnd (qf_eval e)) //= big_andE /=.
apply/forallP/idP=> /= [|sAB d]; last first.
rewrite !eval_mxrank eval_col_mx -addsmxE; apply/implyP=> /eqP <-.
by rewrite mxrank_leqif_sup ?addsmxSr // addsmx_sub sAB /=.
move/(_ (inord (\rank (eval_mx e (col_mx A B))))).
rewrite inordK ?ltnS ?rank_leq_col // !eval_mxrank eqxx /= eval_col_mx.
by rewrite -addsmxE mxrank_leqif_sup ?addsmxSr // addsmx_sub; case/andP.
Qed.
End Subsetmx.
Section Env.
Variable d : nat.
Definition seq_of_rV (v : 'rV_d) : seq F := fgraph [ffun i => v 0 i].
Lemma size_seq_of_rV v : size (seq_of_rV v) = d.
Proof. by rewrite tuple.size_tuple card_ord. Qed.
Lemma nth_seq_of_rV x0 v (i : 'I_d) : nth x0 (seq_of_rV v) i = v 0 i.
Proof. by rewrite nth_fgraph_ord ffunE. Qed.
Definition row_var k : 'rV[term]_d := \row_i ('X_(k * d + i))%T.
Definition row_env (e : seq 'rV_d) := flatten (map seq_of_rV e).
Lemma nth_row_env e k (i : 'I_d) : (row_env e)`_(k * d + i) = e`_k 0 i.
Proof.
elim: e k => [|v e IHe] k; first by rewrite !nth_nil mxE.
rewrite /row_env /= nth_cat size_seq_of_rV.
case: k => [|k]; first by rewrite (valP i) nth_seq_of_rV.
by rewrite mulSn -addnA -if_neg -leqNgt leq_addr addKn IHe.
Qed.
Lemma eval_row_var e k : eval_mx (row_env e) (row_var k) = e`_k :> 'rV_d.
Proof. by apply/rowP=> i; rewrite !mxE /= nth_row_env. Qed.
Definition Exists_row_form k (f : form) :=
foldr GRing.Exists f (codom (fun i : 'I_d => k * d + i)%N).
Lemma Exists_rowP e k f :
d > 0 ->
((exists v : 'rV[F]_d, holds (row_env (set_nth 0 e k v)) f)
<-> holds (row_env e) (Exists_row_form k f)).
Proof.
move=> d_gt0; pose i_ j := Ordinal (ltn_pmod j d_gt0).
have d_eq j: (j = j %/ d * d + i_ j)%N := divn_eq j d.
split=> [[v f_v] | ]; last case/GRing.foldExistsP=> e' ee' f_e'.
apply/GRing.foldExistsP; exists (row_env (set_nth 0 e k v)) => {f f_v}// j.
rewrite [j]d_eq !nth_row_env nth_set_nth /=; case: eqP => // ->.
by case/imageP; exists (i_ j).
exists (\row_i e'`_(k * d + i)); apply: eq_holds f_e' => j /=.
move/(_ j): ee'; rewrite [j]d_eq !nth_row_env nth_set_nth /=.
case: eqP => [-> | ne_j_k -> //]; first by rewrite mxE.
apply/mapP=> [[r lt_r_d]]; rewrite -d_eq => def_j; case: ne_j_k.
by rewrite def_j divnMDl // divn_small ?addn0.
Qed.
End Env.
End MatrixFormula.
End MatrixFormula.
Section ConjMx.
Context {F : fieldType}.
Definition conjmx (m n : nat)
(V : 'M_(m, n)) (f : 'M[F]_n) : 'M_m := V *m f *m pinvmx V.
Notation restrictmx V := (conjmx (row_base V)).
Lemma stablemx_comp (m n p : nat) (V : 'M[F]_(m, n)) (W : 'M_(n, p)) (f : 'M_p) :
stablemx W f -> stablemx V (conjmx W f) -> stablemx (V *m W) f.
Proof. by move=> Wf /(submxMr W); rewrite -mulmxA mulmxKpV// mulmxA. Qed.
Lemma stablemx_restrict m n (A : 'M[F]_n) (V : 'M_n) (W : 'M_(m, \rank V)):
stablemx V A -> stablemx W (restrictmx V A) = stablemx (W *m row_base V) A.
Proof.
move=> A_stabV; rewrite mulmxA -[in RHS]mulmxA.
rewrite -(submxMfree _ W (row_base_free V)) mulmxKpV //.
by rewrite mulmx_sub ?stablemx_row_base.
Qed.
Lemma conjmxM (m n : nat) (V : 'M[F]_(m, n)) :
{in [pred f | stablemx V f] &, {morph conjmx V : f g / f *m g}}.
Proof.
move=> f g; rewrite !inE => Vf Vg /=.
by rewrite /conjmx 2!mulmxA mulmxA mulmxKpV ?stablemx_row_base.
Qed.
Lemma conjMmx (m n p : nat) (V : 'M[F]_(m, n)) (W : 'M_(n, p)) (f : 'M_p) :
row_free (V *m W) -> stablemx W f -> stablemx V (conjmx W f) ->
conjmx (V *m W) f = conjmx V (conjmx W f).
Proof.
move=> rfVW Wf VWf; apply: (row_free_inj rfVW); rewrite mulmxKpV ?stablemx_comp//.
by rewrite mulmxA mulmxKpV// -[RHS]mulmxA mulmxKpV ?mulmxA.
Qed.
Lemma conjuMmx (m n : nat) (V : 'M[F]_m) (W : 'M_(m, n)) (f : 'M_n) :
V \in unitmx -> row_free W -> stablemx W f ->
conjmx (V *m W) f = conjmx V (conjmx W f).
Proof.
move=> Vu rfW Wf; rewrite conjMmx ?stablemx_unit//.
by rewrite /row_free mxrankMfree// -/(row_free V) row_free_unit.
Qed.
Lemma conjMumx (m n : nat) (V : 'M[F]_(m, n)) (W f : 'M_n) :
W \in unitmx -> row_free V -> stablemx V (conjmx W f) ->
conjmx (V *m W) f = conjmx V (conjmx W f).
Proof.
move=> Wu rfW Wf; rewrite conjMmx ?stablemx_unit//.
by rewrite /row_free mxrankMfree ?row_free_unit.
Qed.
Lemma conjuMumx (n : nat) (V W f : 'M[F]_n) :
V \in unitmx -> W \in unitmx ->
conjmx (V *m W) f = conjmx V (conjmx W f).
Proof. by move=> Vu Wu; rewrite conjuMmx ?stablemx_unit ?row_free_unit. Qed.
Lemma conjmx_scalar (m n : nat) (V : 'M[F]_(m, n)) (a : F) :
row_free V -> conjmx V a%:M = a%:M.
Proof. by move=> rfV; rewrite /conjmx scalar_mxC mulmxKp. Qed.
Lemma conj0mx (m n : nat) f : conjmx (0 : 'M[F]_(m, n)) f = 0.
Proof. by rewrite /conjmx !mul0mx. Qed.
Lemma conjmx0 (m n : nat) (V : 'M[F]_(m, n)) : conjmx V 0 = 0.
Proof. by rewrite /conjmx mulmx0 mul0mx. Qed.
Lemma conjumx (n : nat) (V : 'M_n) (f : 'M[F]_n) : V \in unitmx ->
conjmx V f = V *m f *m invmx V.
Proof. by move=> uV; rewrite /conjmx pinvmxE. Qed.
Lemma conj1mx (n : nat) (f : 'M[F]_n) : conjmx 1%:M f = f.
Proof. by rewrite conjumx ?unitmx1// invmx1 mulmx1 mul1mx. Qed.
Lemma conjVmx (n : nat) (V : 'M_n) (f : 'M[F]_n) : V \in unitmx ->
conjmx (invmx V) f = invmx V *m f *m V.
Proof. by move=> Vunit; rewrite conjumx ?invmxK ?unitmx_inv. Qed.
Lemma conjmxK (n : nat) (V f : 'M[F]_n) :
V \in unitmx -> conjmx (invmx V) (conjmx V f) = f.
Proof. by move=> Vu; rewrite -conjuMumx ?unitmx_inv// mulVmx ?conj1mx. Qed.
Lemma conjmxVK (n : nat) (V f : 'M[F]_n) :
V \in unitmx -> conjmx V (conjmx (invmx V) f) = f.
Proof. by move=> Vu; rewrite -conjuMumx ?unitmx_inv// mulmxV ?conj1mx. Qed.
Lemma horner_mx_conj m n p (V : 'M[F]_(n.+1, m.+1)) (f : 'M_m.+1) :
row_free V -> stablemx V f ->
horner_mx (conjmx V f) p = conjmx V (horner_mx f p).
Proof.
move=> V_free V_stab; rewrite/conjmx; elim/poly_ind: p => [|p c].
by rewrite !rmorph0 mulmx0 mul0mx.
rewrite !(rmorphD, rmorphM)/= !(horner_mx_X, horner_mx_C) => ->.
rewrite [_ * _]mulmxA [_ *m (V *m _)]mulmxA mulmxKpV ?horner_mx_stable//.
apply: (row_free_inj V_free); rewrite [_ *m V]mulmxDl.
pose stablemxE := (stablemxD, stablemxM, stablemxC, horner_mx_stable).
by rewrite !mulmxKpV -?[V *m _ *m _]mulmxA ?stablemxE// mulmxDr -scalar_mxC.
Qed.
Lemma horner_mx_uconj n p (V : 'M[F]_(n.+1)) (f : 'M_n.+1) :
V \is a GRing.unit ->
horner_mx (V *m f *m invmx V) p = V *m horner_mx f p *m invmx V.
Proof.
move=> V_unit; rewrite -!conjumx//.
by rewrite horner_mx_conj ?row_free_unit ?stablemx_unit.
Qed.
Lemma horner_mx_uconjC n p (V : 'M[F]_(n.+1)) (f : 'M_n.+1) :
V \is a GRing.unit ->
horner_mx (invmx V *m f *m V) p = invmx V *m horner_mx f p *m V.
Proof.
move=> V_unit; rewrite -[X in _ *m X](invmxK V).
by rewrite horner_mx_uconj ?invmxK ?unitmx_inv.
Qed.
Lemma mxminpoly_conj m n (V : 'M[F]_(m.+1, n.+1)) (f : 'M_n.+1) :
row_free V -> stablemx V f -> mxminpoly (conjmx V f) %| mxminpoly f.
Proof.
by move=> *; rewrite mxminpoly_min// horner_mx_conj// mx_root_minpoly conjmx0.
Qed.
Lemma mxminpoly_uconj n (V : 'M[F]_(n.+1)) (f : 'M_n.+1) :
V \in unitmx -> mxminpoly (conjmx V f) = mxminpoly f.
Proof.
have simp := (row_free_unit, stablemx_unit, unitmx_inv, unitmx1).
move=> Vu; apply/eqP; rewrite -eqp_monic ?mxminpoly_monic// /eqp.
apply/andP; split; first by rewrite mxminpoly_conj ?simp.
by rewrite -[f in X in X %| _](conjmxK _ Vu) mxminpoly_conj ?simp.
Qed.
Section fixed_stablemx_space.
Variables (m n : nat).
Implicit Types (V : 'M[F]_(m, n)) (A : 'M[F]_n).
Implicit Types (a : F) (p : {poly F}).
Section Sub.
Variable (k : nat).
Implicit Types (W : 'M[F]_(k, m)).
Lemma sub_kermxpoly_conjmx V f p W : stablemx V f -> row_free V ->
(W <= kermxpoly (conjmx V f) p)%MS = (W *m V <= kermxpoly f p)%MS.
Proof.
case: n m => [|n'] [|m'] in V f W * => fV rfV; rewrite ?thinmx0//.
by rewrite /row_free mxrank.unlock in rfV.
by rewrite mul0mx !sub0mx.
apply/sub_kermxP/sub_kermxP; rewrite horner_mx_conj//; last first.
by move=> /(congr1 (mulmxr (pinvmx V)))/=; rewrite mul0mx !mulmxA.
move=> /(congr1 (mulmxr V))/=; rewrite ![W *m _]mulmxA ?mul0mx mulmxKpV//.
by rewrite -mulmxA mulmx_sub// horner_mx_stable//.
Qed.
Lemma sub_eigenspace_conjmx V f a W : stablemx V f -> row_free V ->
(W <= eigenspace (conjmx V f) a)%MS = (W *m V <= eigenspace f a)%MS.
Proof. by move=> fV rfV; rewrite !eigenspace_poly sub_kermxpoly_conjmx. Qed.
End Sub.
Lemma eigenpoly_conjmx V f : stablemx V f -> row_free V ->
{subset eigenpoly (conjmx V f) <= eigenpoly f}.
Proof.
move=> fV rfV a /eigenpolyP [x]; rewrite sub_kermxpoly_conjmx//.
move=> xV_le_fa x_neq0; apply/eigenpolyP.
by exists (x *m V); rewrite ?mulmx_free_eq0.
Qed.
Lemma eigenvalue_conjmx V f : stablemx V f -> row_free V ->
{subset eigenvalue (conjmx V f) <= eigenvalue f}.
Proof.
by move=> fV rfV a; rewrite ![_ \in _]eigenvalue_poly; apply: eigenpoly_conjmx.
Qed.
Lemma conjmx_eigenvalue a V f : (V <= eigenspace f a)%MS -> row_free V ->
conjmx V f = a%:M.
Proof.
by move=> /eigenspaceP Vfa rfV; rewrite /conjmx Vfa -mul_scalar_mx mulmxKp.
Qed.
End fixed_stablemx_space.
End ConjMx.
Notation restrictmx V := (conjmx (row_base V)).
Definition simmx_to_for {F : fieldType} {m n}
(P : 'M_(m, n)) A (S : {pred 'M[F]_m}) := S (conjmx P A).
Notation "A ~_ P '{' 'in' S '}'" := (simmx_to_for P A S)
(at level 70, P at level 0, format "A ~_ P '{' 'in' S '}'") :
ring_scope.
Notation simmx_for P A B := (A ~_P {in PredOfSimpl.coerce (pred1 B)}).
Notation "A ~_ P B" := (simmx_for P A B) (format "A ~_ P B").
Notation simmx_in S A B := (exists2 P, P \in S & A ~_P B).
Notation "A '~_{in' S '}' B" := (simmx_in S A B)
(at level 70, format "A '~_{in' S '}' B").
Notation simmx_in_to S A S' := (exists2 P, P \in S & A ~_P {in S'}).
Notation "A '~_{in' S '}' '{' 'in' S' '}'" := (simmx_in_to S A S')
(format "A '~_{in' S '}' '{' 'in' S' '}'").
Notation all_simmx_in S As S' :=
(exists2 P, P \in S & all [pred A | A ~_P {in S'}] As).
Notation diagonalizable_for P A := (A ~_P {in is_diag_mx}).
Notation diagonalizable_in S A := (A ~_{in S} {in is_diag_mx}).
Notation diagonalizable A := (diagonalizable_in unitmx A).
Notation codiagonalizable_in S As := (all_simmx_in S As is_diag_mx).
Notation codiagonalizable As := (codiagonalizable_in unitmx As).
Section Simmxity.
Context {F : fieldType}.
Lemma simmxPp m n {P : 'M[F]_(m, n)} {A B} :
stablemx P A -> A ~_P B -> P *m A = B *m P.
Proof. by move=> stablemxPA /eqP <-; rewrite mulmxKpV. Qed.
Lemma simmxW m n {P : 'M[F]_(m, n)} {A B} : row_free P ->
P *m A = B *m P -> A ~_P B.
Proof. by rewrite /(_ ~__ _)/= /conjmx => fP ->; rewrite mulmxKp. Qed.
Section Simmx.
Context {n : nat}.
Implicit Types (A B P : 'M[F]_n) (As : seq 'M[F]_n) (d : 'rV[F]_n).
Lemma simmxP {P A B} : P \in unitmx ->
reflect (P *m A = B *m P) (A ~_P B).
Proof.
move=> p_unit; apply: (iffP idP); first exact/simmxPp/stablemx_unit.
by apply: simmxW; rewrite row_free_unit.
Qed.
Lemma simmxRL {P A B} : P \in unitmx ->
reflect (B = P *m A *m invmx P) (A ~_P B).
Proof. by move=> ?; apply: (iffP eqP); rewrite conjumx. Qed.
Lemma simmxLR {P A B} : P \in unitmx ->
reflect (A = conjmx (invmx P) B) (A ~_P B).
Proof.
by move=> Pu; rewrite conjVmx//; apply: (iffP (simmxRL Pu)) => ->;
rewrite !mulmxA ?(mulmxK, mulmxKV, mulVmx, mulmxV, mul1mx, mulmx1).
Qed.
End Simmx.
Lemma simmx_minpoly {n} {P A B : 'M[F]_n.+1} : P \in unitmx ->
A ~_P B -> mxminpoly A = mxminpoly B.
Proof. by move=> Pu /eqP<-; rewrite mxminpoly_uconj. Qed.
Lemma diagonalizable_for_row_base m n (P : 'M[F]_(m, n)) (A : 'M_n) :
diagonalizable_for (row_base P) A = is_diag_mx (restrictmx P A).
Proof. by []. Qed.
Lemma diagonalizable_forPp m n (P : 'M[F]_(m, n)) A :
reflect (forall i j : 'I__, i != j :> nat -> conjmx P A i j = 0)
(diagonalizable_for P A).
Proof. exact: @is_diag_mxP. Qed.
Lemma diagonalizable_forP n (P : 'M[F]_n) A : P \in unitmx ->
reflect (forall i j : 'I__, i != j :> nat -> (P *m A *m invmx P) i j = 0)
(diagonalizable_for P A).
Proof. by move=> Pu; rewrite -conjumx//; exact: is_diag_mxP. Qed.
Lemma diagonalizable_forPex {m} {n} {P : 'M[F]_(m, n)} {A} :
reflect (exists D, A ~_P (diag_mx D)) (diagonalizable_for P A).
Proof. by apply: (iffP (diag_mxP _)) => -[D]/eqP; exists D. Qed.
Lemma diagonalizable_forLR n {P : 'M[F]_n} {A} : P \in unitmx ->
reflect (exists D, A = conjmx (invmx P) (diag_mx D)) (diagonalizable_for P A).
Proof.
by move=> Punit; apply: (iffP diagonalizable_forPex) => -[D /(simmxLR Punit)]; exists D.
Qed.
Lemma diagonalizable_for_mxminpoly {n} {P A : 'M[F]_n.+1}
(rs := undup [seq conjmx P A i i | i <- enum 'I_n.+1]) :
P \in unitmx -> diagonalizable_for P A ->
mxminpoly A = \prod_(r <- rs) ('X - r%:P).
Proof.
rewrite /rs => pu /(diagonalizable_forLR pu)[d {A rs}->].
rewrite mxminpoly_uconj ?unitmx_inv// mxminpoly_diag.
by rewrite [in X in _ = X](@eq_map _ _ _ (d 0))// => i; rewrite conjmxVK// mxE eqxx.
Qed.
End Simmxity.
Lemma diagonalizable_for_sum (F : fieldType) (m n : nat) (p_ : 'I_n -> nat)
(V_ : forall i, 'M[F]_(p_ i, m)) (A : 'M[F]_m) :
mxdirect (\sum_i <<V_ i>>) ->
(forall i, stablemx (V_ i) A) ->
(forall i, row_free (V_ i)) ->
diagonalizable_for (\mxcol_i V_ i) A = [forall i, diagonalizable_for (V_ i) A].
Proof.
move=> Vd VA rAV; have aVA : stablemx (\mxcol_i V_ i) A.
rewrite (eqmx_stable _ (eqmx_col _)) stablemx_sums//.
by move=> i; rewrite (eqmx_stable _ (genmxE _)).
apply/diagonalizable_forPex/'forall_diagonalizable_forPex => /=
[[D /(simmxPp aVA) +] i|/(_ _)/sigW DoA].
rewrite mxcol_mul -[D]submxrowK diag_mxrow mul_mxdiag_mxcol.
move=> /eq_mxcolP/(_ i); set D0 := (submxrow _ _) => VMeq.
by exists D0; apply/simmxW.
exists (\mxrow_i tag (DoA i)); apply/simmxW.
rewrite -row_leq_rank eqmx_col (mxdirectP Vd)/=.
by under [leqRHS]eq_bigr do rewrite genmxE (eqP (rAV _)).
rewrite mxcol_mul diag_mxrow mul_mxdiag_mxcol; apply: eq_mxcol => i.
by case: DoA => /= k /(simmxPp); rewrite VA => /(_ isT) ->.
Qed.
Section Diag.
Variable (F : fieldType).
Lemma codiagonalizable1 n (A : 'M[F]_n) :
codiagonalizable [:: A] <-> diagonalizable A.
Proof. by split=> -[P Punit PA]; exists P; move: PA; rewrite //= andbT. Qed.
Definition codiagonalizablePfull n (As : seq 'M[F]_n) :
codiagonalizable As
<-> exists m, exists2 P : 'M_(m, n), row_full P &
all [pred A | diagonalizable_for P A] As.
Proof.
split => [[P Punit SPA]|[m [P Pfull SPA]]].
by exists n => //; exists P; rewrite ?row_full_unit.
have Qfull := fullrowsub_unit Pfull.
exists (rowsub (fullrankfun Pfull) P) => //; apply/allP => A AAs/=.
have /allP /(_ _ AAs)/= /diagonalizable_forPex[d /simmxPp] := SPA.
rewrite submx_full// => /(_ isT) PA_eq.
apply/diagonalizable_forPex; exists (colsub (fullrankfun Pfull) d).
apply/simmxP => //; apply/row_matrixP => i.
rewrite !row_mul row_diag_mx -scalemxAl -rowE !row_rowsub !mxE.
have /(congr1 (row (fullrankfun Pfull i))) := PA_eq.
by rewrite !row_mul row_diag_mx -scalemxAl -rowE => ->.
Qed.
Lemma codiagonalizable_on m n (V_ : 'I_n -> 'M[F]_m) (As : seq 'M[F]_m) :
(\sum_i V_ i :=: 1%:M)%MS -> mxdirect (\sum_i V_ i) ->
(forall i, all (fun A => stablemx (V_ i) A) As) ->
(forall i, codiagonalizable (map (restrictmx (V_ i)) As)) ->
codiagonalizable As.
Proof.
move=> V1 Vdirect /(_ _)/allP AV /(_ _) /sig2W/= Pof.
pose P_ i := tag (Pof i).
have P_unit i : P_ i \in unitmx by rewrite /P_; case: {+}Pof.
have P_diag i A : A \in As -> diagonalizable_for (P_ i *m row_base (V_ i)) A.
move=> AAs; rewrite /P_; case: {+}Pof => /= P Punit.
rewrite all_map => /allP/(_ A AAs); rewrite /= !/(diagonalizable_for _ _).
by rewrite conjuMmx ?row_base_free ?stablemx_row_base ?AV.
pose P := \mxcol_i (P_ i *m row_base (V_ i)).
have P_full i : row_full (P_ i) by rewrite row_full_unit.
have PrV i : (P_ i *m row_base (V_ i) :=: V_ i)%MS.
exact/(eqmx_trans _ (eq_row_base _))/eqmxMfull.
apply/codiagonalizablePfull; eexists _; last exists P; rewrite /=.
- rewrite -sub1mx eqmx_col.
by under eq_bigr do rewrite (eq_genmx (PrV _)); rewrite -genmx_sums genmxE V1.
apply/allP => A AAs /=; rewrite diagonalizable_for_sum.
- by apply/forallP => i; apply: P_diag.
- rewrite mxdirectE/=.
under eq_bigr do rewrite (eq_genmx (PrV _)); rewrite -genmx_sums genmxE V1.
by under eq_bigr do rewrite genmxE PrV; rewrite -(mxdirectP Vdirect)//= V1.
- by move=> i; rewrite (eqmx_stable _ (PrV _)) ?AV.
- by move=> i; rewrite /row_free eqmxMfull ?eq_row_base ?row_full_unit.
Qed.
Lemma diagonalizable_diag {n} (d : 'rV[F]_n) : diagonalizable (diag_mx d).
Proof.
exists 1%:M; rewrite ?unitmx1// /(diagonalizable_for _ _).
by rewrite conj1mx diag_mx_is_diag.
Qed.
Hint Resolve diagonalizable_diag : core.
Lemma diagonalizable_scalar {n} (a : F) : diagonalizable (a%:M : 'M_n).
Proof. by rewrite -diag_const_mx. Qed.
Hint Resolve diagonalizable_scalar : core.
Lemma diagonalizable0 {n} : diagonalizable (0 : 'M[F]_n).
Proof.
by rewrite (_ : 0 = 0%:M)//; apply/matrixP => i j; rewrite !mxE// mul0rn.
Qed.
Hint Resolve diagonalizable0 : core.
Lemma diagonalizablePeigen {n} {A : 'M[F]_n} :
diagonalizable A <->
exists2 rs, uniq rs & (\sum_(r <- rs) eigenspace A r :=: 1%:M)%MS.
Proof.
split=> [df|[rs urs rsP]].
suff [rs rsP] : exists rs, (\sum_(r <- rs) eigenspace A r :=: 1%:M)%MS.
exists (undup rs); rewrite ?undup_uniq//; apply: eqmx_trans rsP.
elim: rs => //= r rs IHrs; rewrite big_cons.
case: ifPn => in_rs; rewrite ?big_cons; last exact: adds_eqmx.
apply/(eqmx_trans IHrs)/eqmx_sym/addsmx_idPr.
have rrs : (index r rs < size rs)%N by rewrite index_mem.
rewrite (big_nth 0) big_mkord (sumsmx_sup (Ordinal rrs)) ?nth_index//.
move: df => [P Punit /(diagonalizable_forLR Punit)[d ->]].
exists [seq d 0 i | i <- enum 'I_n]; rewrite big_image/=.
apply: (@eqmx_trans _ _ _ _ _ _ P); apply/eqmxP;
rewrite ?sub1mx ?submx1 ?row_full_unit//.
rewrite submx_full ?row_full_unit//=.
apply/row_subP => i; rewrite rowE (sumsmx_sup i)//.
apply/eigenspaceP; rewrite conjVmx// !mulmxA mulmxK//.
by rewrite -rowE row_diag_mx scalemxAl.
have mxdirect_eigenspaces : mxdirect (\sum_(i < size rs) eigenspace A rs`_i).
apply: mxdirect_sum_eigenspace => i j _ _ rsij; apply/val_inj.
by apply: uniqP rsij; rewrite ?inE.
rewrite (big_nth 0) big_mkord in rsP; apply/codiagonalizable1.
apply/(codiagonalizable_on _ mxdirect_eigenspaces) => // i/=.
case: n => [|n] in A {mxdirect_eigenspaces} rsP *.
by rewrite thinmx0 sub0mx.
by rewrite comm_mx_stable_eigenspace.
apply/codiagonalizable1.
rewrite (@conjmx_eigenvalue _ _ _ rs`_i); first exact: diagonalizable_scalar.
by rewrite eq_row_base.
by rewrite row_base_free.
Qed.
Lemma diagonalizableP n' (n := n'.+1) (A : 'M[F]_n) :
diagonalizable A <->
exists2 rs, uniq rs & mxminpoly A %| \prod_(x <- rs) ('X - x%:P).
Proof.
split=> [[P Punit /diagonalizable_forPex[d /(simmxLR Punit)->]]|].
rewrite mxminpoly_uconj ?unitmx_inv// mxminpoly_diag.
by eexists; [|by []]; rewrite undup_uniq.
move=> + /ltac:(apply/diagonalizablePeigen) => -[rs rsu rsP]; exists rs => //.
rewrite (big_nth 0) [X in (X :=: _)%MS](big_nth 0) !big_mkord in rsP *.
rewrite (eq_bigr _ (fun _ _ => eigenspace_poly _ _)).
apply: (eqmx_trans (eqmx_sym (kermxpoly_prod _ _)) (kermxpoly_min _)) => //.
by move=> i j _ _; rewrite coprimep_XsubC root_XsubC nth_uniq.
Qed.
Lemma diagonalizable_conj_diag m n (V : 'M[F]_(m, n)) (d : 'rV[F]_n) :
stablemx V (diag_mx d) -> row_free V -> diagonalizable (conjmx V (diag_mx d)).
Proof.
case: m n => [|m] [|n] in V d * => Vd rdV; rewrite ?thinmx0.
- by [].
- by [].
- by exfalso; move: rdV; rewrite /row_free mxrank.unlock eqxx orbT.
apply/diagonalizableP; pose u := undup [seq d 0 i | i <- enum 'I_n.+1].
exists u; first by rewrite undup_uniq.
by rewrite (dvdp_trans (mxminpoly_conj (f:=diag_mx d) _ _))// mxminpoly_diag.
Qed.
Lemma codiagonalizableP n (As : seq 'M[F]_n) :
{in As &, forall A B, comm_mx A B} /\ {in As, forall A, diagonalizable A}
<-> codiagonalizable As.
Proof.
split => [cdAs|[P Punit /allP/= AsD]]/=; last first.
split; last by exists P; rewrite // AsD.
move=> A B AAs BAs; move=> /(_ _ _)/diagonalizable_forPex/sigW in AsD.
have [[dA /simmxLR->//] [dB /simmxLR->//]] := (AsD _ AAs, AsD _ BAs).
by rewrite /comm_mx -!conjmxM 1?diag_mxC// inE stablemx_unit ?unitmx_inv.
move: cdAs => -[]; move/(rwP (all_comm_mxP _)) => cdAs cdAs'.
have [k] := ubnP (size As); elim: k => [|k IHk]//= in n As cdAs cdAs' *.
case: As cdAs cdAs' => [|A As]//=; first by exists 1%:M; rewrite ?unitmx1.
rewrite ltnS all_comm_mx_cons => /andP[/allP/(_ _ _)/eqP AAsC AsC dAAs] Ask.
have /diagonalizablePeigen [rs urs rs1] := dAAs _ (mem_head _ _).
rewrite (big_nth 0) big_mkord in rs1.
have eAB (i : 'I_(size rs)) B : B \in A :: As -> stablemx (eigenspace A rs`_i) B.
case: n => [|n'] in B A As AAsC AsC {dAAs rs1 Ask} * => B_AAs.
by rewrite thinmx0 sub0mx.
rewrite comm_mx_stable_eigenspace//.
by move: B_AAs; rewrite !inE => /predU1P [->//|/AAsC].
apply/(@codiagonalizable_on _ _ _ (_ :: _) rs1) => [|i|i /=].
- apply: mxdirect_sum_eigenspace => i j _ _ rsij; apply/val_inj.
by apply: uniqP rsij; rewrite ?inE.
- by apply/allP => B B_AAs; rewrite eAB.
rewrite (@conjmx_eigenvalue _ _ _ rs`_i) ?eq_row_base ?row_base_free//.
set Bs := map _ _; suff [P Punit /= PBs] : codiagonalizable Bs.
exists P; rewrite /= ?PBs ?andbT// /(diagonalizable_for _ _).
by rewrite conjmx_scalar ?mx_scalar_is_diag// row_free_unit.
apply: IHk; rewrite ?size_map/= ?ltnS//.
apply/all_comm_mxP => _ _ /mapP[/= B BAs ->] /mapP[/= h hAs ->].
rewrite -!conjmxM ?inE ?stablemx_row_base ?eAB ?inE ?BAs ?hAs ?orbT//.
by rewrite (all_comm_mxP _ AsC).
move=> _ /mapP[/= B BAs ->].
have: stablemx (row_base (eigenspace A rs`_i)) B.
by rewrite stablemx_row_base eAB// inE BAs orbT.
have := dAAs B; rewrite inE BAs orbT => /(_ isT) [P Punit].
move=> /diagonalizable_forPex[D /(simmxLR Punit)->] sePD.
have rAeP : row_free (row_base (eigenspace A rs`_i) *m invmx P).
by rewrite /row_free mxrankMfree ?row_free_unit ?unitmx_inv// eq_row_base.
rewrite -conjMumx ?unitmx_inv ?row_base_free => [|//|//|//].
apply/diagonalizable_conj_diag => //.
by rewrite stablemx_comp// stablemx_unit ?unitmx_inv.
Qed.
End Diag.
|
classfun.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path.
From mathcomp Require Import div choice fintype tuple finfun bigop prime order.
From mathcomp Require Import ssralg poly finset fingroup morphism perm.
From mathcomp Require Import automorphism quotient finalg action gproduct zmodp.
From mathcomp Require Import commutator cyclic center pgroup sylow matrix.
From mathcomp Require Import vector falgebra ssrnum algC algnum archimedean.
(******************************************************************************)
(* This file contains the basic theory of class functions: *)
(* 'CF(G) == the type of class functions on G : {group gT}, i.e., *)
(* which map gT to the type algC of complex algebraics, *)
(* have support in G, and are constant on each conjugacy *)
(* class of G. 'CF(G) implements the falgType interface of *)
(* finite-dimensional F-algebras. *)
(* The identity 1 : 'CF(G) is the indicator function of G, *)
(* and (later) the principal character. *)
(* --> The %CF scope (cfun_scope) is bound to the 'CF(_) types. *)
(* 'CF(G)%VS == the (total) vector space of 'CF(G). *)
(* 'CF(G, A) == the subspace of functions in 'CF(G) with support in A. *)
(* phi x == the image of x : gT under phi : 'CF(G). *)
(* #[phi]%CF == the multiplicative order of phi : 'CF(G). *)
(* cfker phi == the kernel of phi : 'CF(G); note that cfker phi <| G. *)
(* cfaithful phi <=> phi : 'CF(G) is faithful (has a trivial kernel). *)
(* '1_A == the indicator function of A as a function of 'CF(G). *)
(* (Provided A <| G; G is determined by the context.) *)
(* phi^*%CF == the function conjugate to phi : 'CF(G). *)
(* cfAut u phi == the function conjugate to phi by an algC-automorphism u *)
(* phi^u The notation "_ ^u" is only reserved; it is up to *)
(* clients to set Notation "phi ^u" := (cfAut u phi). *)
(* '[phi, psi] == the convolution of phi, psi : 'CF(G) over G, normalised *)
(* '[phi, psi]_G by #|G| so that '[1, 1]_G = 1 (G is usually inferred). *)
(* cfdotr psi phi == '[phi, psi] (self-expanding). *)
(* '[phi], '[phi]_G == the squared norm '[phi, phi] of phi : 'CF(G). *)
(* orthogonal R S <=> each phi in R : seq 'CF(G) is orthogonal to each psi in *)
(* S, i.e., '[phi, psi] = 0. As 'CF(G) coerces to seq, one *)
(* can write orthogonal phi S and orthogonal phi psi. *)
(* pairwise_orthogonal S <=> the class functions in S are pairwise orthogonal *)
(* AND non-zero. *)
(* orthonormal S <=> S is pairwise orthogonal and all class functions in S *)
(* have norm 1. *)
(* isometry tau <-> tau : 'CF(D) -> 'CF(R) is an isometry, mapping *)
(* '[_, _]_D to '[_, _]_R. *)
(* {in CD, isometry tau, to CR} <-> in the domain CD, tau is an isometry *)
(* whose range is contained in CR. *)
(* cfReal phi <=> phi is real, i.e., phi^* == phi. *)
(* cfAut_closed u S <-> S : seq 'CF(G) is closed under conjugation by u. *)
(* cfConjC_closed S <-> S : seq 'CF(G) is closed under complex conjugation. *)
(* conjC_subset S1 S2 <-> S1 : seq 'CF(G) represents a subset of S2 closed *)
(* under complex conjugation. *)
(* := [/\ uniq S1, {subset S1 <= S2} & cfConjC_closed S1]. *)
(* 'Res[H] phi == the restriction of phi : 'CF(G) to a function of 'CF(H) *)
(* 'Res[H, G] phi 'Res[H] phi x = phi x if x \in H (when H \subset G), *)
(* 'Res phi 'Res[H] phi x = 0 if x \notin H. The syntax variants *)
(* allow H and G to be inferred; the default is to specify *)
(* H explicitly, and infer G from the type of phi. *)
(* 'Ind[G] phi == the class function of 'CF(G) induced by phi : 'CF(H), *)
(* 'Ind[G, H] phi when H \subset G. As with 'Res phi, both G and H can *)
(* 'Ind phi be inferred, though usually G isn't. *)
(* cfMorph phi == the class function in 'CF(G) that maps x to phi (f x), *)
(* where phi : 'CF(f @* G), provided G \subset 'dom f. *)
(* cfIsom isoGR phi == the class function in 'CF(R) that maps f x to phi x, *)
(* given isoGR : isom G R f, f : {morphism G >-> rT} and *)
(* phi : 'CF(G). *)
(* (phi %% H)%CF == special case of cfMorph phi, when phi : 'CF(G / H). *)
(* (phi / H)%CF == the class function in 'CF(G / H) that coincides with *)
(* phi : 'CF(G) on cosets of H \subset cfker phi. *)
(* For a group G that is a semidirect product (defG : K ><| H = G), we have *)
(* cfSdprod KxH phi == for phi : 'CF(H), the class function of 'CF(G) that *)
(* maps k * h to psi h when k \in K and h \in H. *)
(* For a group G that is a direct product (with KxH : K \x H = G), we have *)
(* cfDprodl KxH phi == for phi : 'CF(K), the class function of 'CF(G) that *)
(* maps k * h to phi k when k \in K and h \in H. *)
(* cfDprodr KxH psi == for psi : 'CF(H), the class function of 'CF(G) that *)
(* maps k * h to psi h when k \in K and h \in H. *)
(* cfDprod KxH phi psi == for phi : 'CF(K), psi : 'CF(H), the class function *)
(* of 'CF(G) that maps k * h to phi k * psi h (this is *)
(* the product of the two functions above). *)
(* Finally, given defG : \big[dprod/1]_(i | P i) A i = G, with G and A i *)
(* groups and i ranges over a finType, we have *)
(* cfBigdprodi defG phi == for phi : 'CF(A i) s.t. P i, the class function *)
(* of 'CF(G) that maps x to phi x_i, where x_i is the *)
(* (A i)-component of x : G. *)
(* cfBigdprod defG phi == for phi : forall i, 'CF(A i), the class function *)
(* of 'CF(G) that maps x to \prod_(i | P i) phi i x_i, *)
(* where x_i is the (A i)-component of x : G. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Declare Scope cfun_scope.
Import Order.TTheory GroupScope GRing.Theory Num.Theory.
Local Open Scope ring_scope.
Delimit Scope cfun_scope with CF.
Reserved Notation "''CF' ( G , A )" (format "''CF' ( G , A )").
Reserved Notation "''CF' ( G )" (format "''CF' ( G )").
Reserved Notation "''1_' G" (at level 8, G at level 2, format "''1_' G").
Reserved Notation "''Res[' H , G ]". (* only parsing *)
Reserved Notation "''Res[' H ]" (format "''Res[' H ]").
Reserved Notation "''Res'". (* only parsing *)
Reserved Notation "''Ind[' G , H ]". (* only parsing *)
Reserved Notation "''Ind[' G ]". (* only "''Ind[' G ]" *)
Reserved Notation "''Ind'". (* only parsing *)
Reserved Notation "'[ phi , psi ]_ G"
(at level 0, G at level 2). (* only parsing *)
Reserved Notation "'[ phi ]_ G"
(at level 0, G at level 2). (* only parsing *)
Reserved Notation "phi ^u" (format "phi ^u").
Section AlgC.
(* Arithmetic properties of group orders in the characteristic 0 field algC. *)
Variable (gT : finGroupType).
Implicit Types (G : {group gT}) (B : {set gT}).
Lemma neq0CG G : (#|G|)%:R != 0 :> algC. Proof. exact: natrG_neq0. Qed.
Lemma neq0CiG G B : (#|G : B|)%:R != 0 :> algC.
Proof. exact: natr_indexg_neq0. Qed.
Lemma gt0CG G : 0 < #|G|%:R :> algC. Proof. exact: natrG_gt0. Qed.
Lemma gt0CiG G B : 0 < #|G : B|%:R :> algC. Proof. exact: natr_indexg_gt0. Qed.
Lemma algC'G_pchar G : [pchar algC]^'.-group G.
Proof. by apply/pgroupP=> p _; rewrite inE /= pchar_num. Qed.
End AlgC.
#[deprecated(since="mathcomp 2.4.0", note="Use algC'G_pchar instead.")]
Notation algC'G := (algC'G_pchar) (only parsing).
Section Defs.
Variable gT : finGroupType.
Definition is_class_fun (B : {set gT}) (f : {ffun gT -> algC}) :=
[forall x, forall y in B, f (x ^ y) == f x] && (support f \subset B).
Lemma intro_class_fun (G : {group gT}) f :
{in G &, forall x y, f (x ^ y) = f x} ->
(forall x, x \notin G -> f x = 0) ->
is_class_fun G (finfun f).
Proof.
move=> fJ Gf; apply/andP; split; last first.
by apply/supportP=> x notAf; rewrite ffunE Gf.
apply/'forall_eqfun_inP=> x y Gy; rewrite !ffunE.
by have [/fJ-> // | notGx] := boolP (x \in G); rewrite !Gf ?groupJr.
Qed.
Variable B : {set gT}.
Local Notation G := <<B>>.
Record classfun : predArgType :=
Classfun {cfun_val; _ : is_class_fun G cfun_val}.
Implicit Types phi psi xi : classfun.
(* The default expansion lemma cfunE requires key = 0. *)
Fact classfun_key : unit. Proof. by []. Qed.
Definition Cfun := locked_with classfun_key (fun flag : nat => Classfun).
HB.instance Definition _ := [isSub for cfun_val].
HB.instance Definition _ := [Choice of classfun by <:].
Definition cfun_eqType : eqType := classfun.
Definition fun_of_cfun phi := cfun_val phi : gT -> algC.
Coercion fun_of_cfun : classfun >-> Funclass.
Lemma cfunElock k f fP : @Cfun k (finfun f) fP =1 f.
Proof. by rewrite locked_withE; apply: ffunE. Qed.
Lemma cfunE f fP : @Cfun 0 (finfun f) fP =1 f.
Proof. exact: cfunElock. Qed.
Lemma cfunP phi psi : phi =1 psi <-> phi = psi.
Proof. by split=> [/ffunP/val_inj | ->]. Qed.
Lemma cfun0gen phi x : x \notin G -> phi x = 0.
Proof. by case: phi => f fP; case: (andP fP) => _ /supportP; apply. Qed.
Lemma cfun_in_genP phi psi : {in G, phi =1 psi} -> phi = psi.
Proof.
move=> eq_phi; apply/cfunP=> x.
by have [/eq_phi-> // | notAx] := boolP (x \in G); rewrite !cfun0gen.
Qed.
Lemma cfunJgen phi x y : y \in G -> phi (x ^ y) = phi x.
Proof.
case: phi => f fP Gy; apply/eqP.
by case: (andP fP) => /'forall_forall_inP->.
Qed.
Fact cfun_zero_subproof : is_class_fun G (0 : {ffun _}).
Proof. exact: intro_class_fun. Qed.
Definition cfun_zero := Cfun 0 cfun_zero_subproof.
Fact cfun_comp_subproof f phi :
f 0 = 0 -> is_class_fun G [ffun x => f (phi x)].
Proof.
by move=> f0; apply: intro_class_fun => [x y _ /cfunJgen | x /cfun0gen] ->.
Qed.
Definition cfun_comp f f0 phi := Cfun 0 (@cfun_comp_subproof f phi f0).
Definition cfun_opp := cfun_comp (oppr0 _).
Fact cfun_add_subproof phi psi : is_class_fun G [ffun x => phi x + psi x].
Proof.
apply: intro_class_fun => [x y Gx Gy | x notGx]; rewrite ?cfunJgen //.
by rewrite !cfun0gen ?add0r.
Qed.
Definition cfun_add phi psi := Cfun 0 (cfun_add_subproof phi psi).
Fact cfun_indicator_subproof (A : {set gT}) :
is_class_fun G [ffun x => ((x \in G) && (x ^: G \subset A))%:R].
Proof.
apply: intro_class_fun => [x y Gx Gy | x /negbTE/= -> //].
by rewrite groupJr ?classGidl.
Qed.
Definition cfun_indicator A := Cfun 1 (cfun_indicator_subproof A).
Local Notation "''1_' A" := (cfun_indicator A) : ring_scope.
Lemma cfun1Egen x : '1_G x = (x \in G)%:R.
Proof. by rewrite cfunElock andb_idr // => /class_subG->. Qed.
Fact cfun_mul_subproof phi psi : is_class_fun G [ffun x => phi x * psi x].
Proof.
apply: intro_class_fun => [x y Gx Gy | x notGx]; rewrite ?cfunJgen //.
by rewrite cfun0gen ?mul0r.
Qed.
Definition cfun_mul phi psi := Cfun 0 (cfun_mul_subproof phi psi).
Definition cfun_unit := [pred phi : classfun | [forall x in G, phi x != 0]].
Definition cfun_inv phi :=
if phi \in cfun_unit then cfun_comp (invr0 _) phi else phi.
Definition cfun_scale a := cfun_comp (mulr0 a).
Fact cfun_addA : associative cfun_add.
Proof. by move=> phi psi xi; apply/cfunP=> x; rewrite !cfunE addrA. Qed.
Fact cfun_addC : commutative cfun_add.
Proof. by move=> phi psi; apply/cfunP=> x; rewrite !cfunE addrC. Qed.
Fact cfun_add0 : left_id cfun_zero cfun_add.
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE add0r. Qed.
Fact cfun_addN : left_inverse cfun_zero cfun_opp cfun_add.
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE addNr. Qed.
HB.instance Definition _ := GRing.isZmodule.Build classfun
cfun_addA cfun_addC cfun_add0 cfun_addN.
Lemma muln_cfunE phi n x : (phi *+ n) x = phi x *+ n.
Proof. by elim: n => [|n IHn]; rewrite ?mulrS !cfunE ?IHn. Qed.
Lemma sum_cfunE I r (P : pred I) (phi : I -> classfun) x :
(\sum_(i <- r | P i) phi i) x = \sum_(i <- r | P i) (phi i) x.
Proof. by elim/big_rec2: _ => [|i _ psi _ <-]; rewrite cfunE. Qed.
Fact cfun_mulA : associative cfun_mul.
Proof. by move=> phi psi xi; apply/cfunP=> x; rewrite !cfunE mulrA. Qed.
Fact cfun_mulC : commutative cfun_mul.
Proof. by move=> phi psi; apply/cfunP=> x; rewrite !cfunE mulrC. Qed.
Fact cfun_mul1 : left_id '1_G cfun_mul.
Proof.
by move=> phi; apply: cfun_in_genP => x Gx; rewrite !cfunE cfun1Egen Gx mul1r.
Qed.
Fact cfun_mulD : left_distributive cfun_mul cfun_add.
Proof. by move=> phi psi xi; apply/cfunP=> x; rewrite !cfunE mulrDl. Qed.
Fact cfun_nz1 : '1_G != 0.
Proof.
by apply/eqP=> /cfunP/(_ 1%g)/eqP; rewrite cfun1Egen cfunE group1 oner_eq0.
Qed.
HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build classfun
cfun_mulA cfun_mulC cfun_mul1 cfun_mulD cfun_nz1.
Definition cfun_nzRingType : nzRingType := classfun.
#[deprecated(since="mathcomp 2.4.0",
note="Use cfun_nzRingType instead.")]
Notation cfun_ringType := (cfun_nzRingType) (only parsing).
Lemma expS_cfunE phi n x : (phi ^+ n.+1) x = phi x ^+ n.+1.
Proof. by elim: n => //= n IHn; rewrite !cfunE IHn. Qed.
Fact cfun_mulV : {in cfun_unit, left_inverse 1 cfun_inv *%R}.
Proof.
move=> phi Uphi; rewrite /cfun_inv Uphi; apply/cfun_in_genP=> x Gx.
by rewrite !cfunE cfun1Egen Gx mulVf ?(forall_inP Uphi).
Qed.
Fact cfun_unitP phi psi : psi * phi = 1 -> phi \in cfun_unit.
Proof.
move/cfunP=> phiK; apply/forall_inP=> x Gx; rewrite -unitfE; apply/unitrP.
by exists (psi x); have:= phiK x; rewrite !cfunE cfun1Egen Gx mulrC.
Qed.
Fact cfun_inv0id : {in [predC cfun_unit], cfun_inv =1 id}.
Proof. by rewrite /cfun_inv => phi /negbTE/= ->. Qed.
HB.instance Definition _ :=
GRing.ComNzRing_hasMulInverse.Build classfun cfun_mulV cfun_unitP cfun_inv0id.
Fact cfun_scaleA a b phi :
cfun_scale a (cfun_scale b phi) = cfun_scale (a * b) phi.
Proof. by apply/cfunP=> x; rewrite !cfunE mulrA. Qed.
Fact cfun_scale1 : left_id 1 cfun_scale.
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE mul1r. Qed.
Fact cfun_scaleDr : right_distributive cfun_scale +%R.
Proof. by move=> a phi psi; apply/cfunP=> x; rewrite !cfunE mulrDr. Qed.
Fact cfun_scaleDl phi : {morph cfun_scale^~ phi : a b / a + b}.
Proof. by move=> a b; apply/cfunP=> x; rewrite !cfunE mulrDl. Qed.
HB.instance Definition _ := GRing.Zmodule_isLmodule.Build algC classfun
cfun_scaleA cfun_scale1 cfun_scaleDr cfun_scaleDl.
Fact cfun_scaleAl a phi psi : a *: (phi * psi) = (a *: phi) * psi.
Proof. by apply/cfunP=> x; rewrite !cfunE mulrA. Qed.
Fact cfun_scaleAr a phi psi : a *: (phi * psi) = phi * (a *: psi).
Proof. by rewrite !(mulrC phi) cfun_scaleAl. Qed.
HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build algC classfun
cfun_scaleAl.
HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build algC classfun
cfun_scaleAr.
Section Automorphism.
Variable u : {rmorphism algC -> algC}.
Definition cfAut := cfun_comp (rmorph0 u).
Lemma cfAut_cfun1i A : cfAut '1_A = '1_A.
Proof. by apply/cfunP=> x; rewrite !cfunElock rmorph_nat. Qed.
Lemma cfAutZ a phi : cfAut (a *: phi) = u a *: cfAut phi.
Proof. by apply/cfunP=> x; rewrite !cfunE rmorphM. Qed.
Lemma cfAut_is_zmod_morphism : zmod_morphism cfAut.
Proof.
by move=> phi psi; apply/cfunP=> x; rewrite ?cfAut_cfun1i // !cfunE /= rmorphB.
Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfAut_is_zmod_morphism` instead")]
Definition cfAut_is_additive := cfAut_is_zmod_morphism.
Lemma cfAut_is_monoid_morphism : monoid_morphism cfAut.
Proof.
by split=> [|phi psi]; apply/cfunP=> x; rewrite ?cfAut_cfun1i // !cfunE rmorphM.
Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfAut_is_monoid_morphism` instead")]
Definition cfAut_is_multiplicative :=
(fun g => (g.2,g.1)) cfAut_is_monoid_morphism.
HB.instance Definition _ := GRing.isZmodMorphism.Build classfun classfun cfAut
cfAut_is_zmod_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build classfun classfun cfAut
cfAut_is_monoid_morphism.
Lemma cfAut_cfun1 : cfAut 1 = 1. Proof. exact: rmorph1. Qed.
Lemma cfAut_scalable : scalable_for (u \; *:%R) cfAut.
Proof. by move=> a phi; apply/cfunP=> x; rewrite !cfunE rmorphM. Qed.
HB.instance Definition _ :=
GRing.isScalable.Build algC classfun classfun (u \; *:%R) cfAut
cfAut_scalable.
Definition cfAut_closed (S : seq classfun) :=
{in S, forall phi, cfAut phi \in S}.
End Automorphism.
(* FIX ME this has changed *)
Notation conjC := Num.conj_op.
Definition cfReal phi := cfAut conjC phi == phi.
Definition cfConjC_subset (S1 S2 : seq classfun) :=
[/\ uniq S1, {subset S1 <= S2} & cfAut_closed conjC S1].
Fact cfun_vect_iso : Vector.axiom #|classes G| classfun.
Proof.
exists (fun phi => \row_i phi (repr (enum_val i))) => [a phi psi|].
by apply/rowP=> i; rewrite !(mxE, cfunE).
set n := #|_|; pose eK x : 'I_n := enum_rank_in (classes1 _) (x ^: G).
have rV2vP v : is_class_fun G [ffun x => v (eK x) *+ (x \in G)].
apply: intro_class_fun => [x y Gx Gy | x /negbTE/=-> //].
by rewrite groupJr // /eK classGidl.
exists (fun v : 'rV_n => Cfun 0 (rV2vP (v 0))) => [phi | v].
apply/cfun_in_genP=> x Gx; rewrite cfunE Gx mxE enum_rankK_in ?mem_classes //.
by have [y Gy ->] := repr_class <<B>> x; rewrite cfunJgen.
apply/rowP=> i; rewrite mxE cfunE; have /imsetP[x Gx def_i] := enum_valP i.
rewrite def_i; have [y Gy ->] := repr_class <<B>> x.
by rewrite groupJ // /eK classGidl // -def_i enum_valK_in.
Qed.
HB.instance Definition _ := Lmodule_hasFinDim.Build algC classfun cfun_vect_iso.
Definition cfun_vectType : vectType _ := classfun.
Definition cfun_base A : #|classes B ::&: A|.-tuple classfun :=
[tuple of [seq '1_xB | xB in classes B ::&: A]].
Definition classfun_on A := <<cfun_base A>>%VS.
Definition cfdot phi psi := #|B|%:R^-1 * \sum_(x in B) phi x * (psi x)^*.
Definition cfdotr psi phi := cfdot phi psi.
Definition cfnorm phi := cfdot phi phi.
Coercion seq_of_cfun phi := [:: phi].
Definition cforder phi := \big[lcmn/1]_(x in <<B>>) #[phi x]%C.
End Defs.
Bind Scope cfun_scope with classfun.
Arguments classfun {gT} B%_g.
Arguments classfun_on {gT} B%_g A%_g.
Arguments cfun_indicator {gT} B%_g.
Arguments cfAut {gT B%_g} u phi%_CF.
Arguments cfReal {gT B%_g} phi%_CF.
Arguments cfdot {gT B%_g} phi%_CF psi%_CF.
Arguments cfdotr {gT B%_g} psi%_CF phi%_CF /.
Arguments cfnorm {gT B%_g} phi%_CF /.
Notation "''CF' ( G )" := (classfun G) : type_scope.
Notation "''CF' ( G )" := (@fullv _ (cfun_vectType G)) : vspace_scope.
Notation "''1_' A" := (cfun_indicator _ A) : ring_scope.
Notation "''CF' ( G , A )" := (classfun_on G A) : ring_scope.
Notation "1" := (@GRing.one (cfun_nzRingType _)) (only parsing) : cfun_scope.
(* FIX ME this has changed *)
Notation conjC := Num.conj_op.
Notation "phi ^*" := (cfAut conjC phi) : cfun_scope.
Notation cfConjC_closed := (cfAut_closed conjC).
Prenex Implicits cfReal.
(* Workaround for overeager projection reduction. *)
Notation eqcfP := (@eqP (cfun_eqType _) _ _) (only parsing).
Notation "#[ phi ]" := (cforder phi) : cfun_scope.
Notation "''[' u , v ]_ G":= (@cfdot _ G u v) (only parsing) : ring_scope.
Notation "''[' u , v ]" := (cfdot u v) : ring_scope.
Notation "''[' u ]_ G" := '[u, u]_G (only parsing) : ring_scope.
Notation "''[' u ]" := '[u, u] : ring_scope.
Section Predicates.
Variables (gT rT : finGroupType) (D : {set gT}) (R : {set rT}).
Implicit Types (phi psi : 'CF(D)) (S : seq 'CF(D)) (tau : 'CF(D) -> 'CF(R)).
Definition cfker phi := [set x in D | [forall y, phi (x * y)%g == phi y]].
Definition cfaithful phi := cfker phi \subset [1].
Definition ortho_rec S1 S2 :=
all [pred phi | all [pred psi | '[phi, psi] == 0] S2] S1.
Definition orthogonal := ortho_rec.
Arguments orthogonal : simpl never.
Fixpoint pair_ortho_rec S :=
if S is psi :: S' then ortho_rec psi S' && pair_ortho_rec S' else true.
(* We exclude 0 from pairwise orthogonal sets. *)
Definition pairwise_orthogonal S := (0 \notin S) && pair_ortho_rec S.
Definition orthonormal S := all [pred psi | '[psi] == 1] S && pair_ortho_rec S.
Definition isometry tau := forall phi psi, '[tau phi, tau psi] = '[phi, psi].
Definition isometry_from_to mCFD tau mCFR :=
prop_in2 mCFD (inPhantom (isometry tau))
/\ prop_in1 mCFD (inPhantom (forall phi, in_mem (tau phi) mCFR)).
End Predicates.
Arguments orthogonal : simpl never.
Arguments cfker {gT D%_g} phi%_CF.
Arguments cfaithful {gT D%_g} phi%_CF.
Arguments orthogonal {gT D%_g} S1%_CF S2%_CF.
Arguments pairwise_orthogonal {gT D%_g} S%_CF.
Arguments orthonormal {gT D%_g} S%_CF.
Arguments isometry {gT rT D%_g R%_g} tau%_CF.
Notation "{ 'in' CFD , 'isometry' tau , 'to' CFR }" :=
(isometry_from_to (mem CFD) tau (mem CFR))
(format "{ 'in' CFD , 'isometry' tau , 'to' CFR }")
: type_scope.
Section ClassFun.
Variables (gT : finGroupType) (G : {group gT}).
Implicit Types (A B : {set gT}) (H K : {group gT}) (phi psi xi : 'CF(G)).
Local Notation "''1_' A" := (cfun_indicator G A).
Lemma cfun0 phi x : x \notin G -> phi x = 0.
Proof. by rewrite -{1}(genGid G) => /(cfun0gen phi). Qed.
Lemma support_cfun phi : support phi \subset G.
Proof. by apply/subsetP=> g; apply: contraR => /cfun0->. Qed.
Lemma cfunJ phi x y : y \in G -> phi (x ^ y) = phi x.
Proof. by rewrite -{1}(genGid G) => /(cfunJgen phi)->. Qed.
Lemma cfun_repr phi x : phi (repr (x ^: G)) = phi x.
Proof. by have [y Gy ->] := repr_class G x; apply: cfunJ. Qed.
Lemma cfun_inP phi psi : {in G, phi =1 psi} -> phi = psi.
Proof. by rewrite -{1}genGid => /cfun_in_genP. Qed.
Lemma cfuniE A x : A <| G -> '1_A x = (x \in A)%:R.
Proof.
case/andP=> sAG nAG; rewrite cfunElock genGid.
by rewrite class_sub_norm // andb_idl // => /(subsetP sAG).
Qed.
Lemma support_cfuni A : A <| G -> support '1_A =i A.
Proof. by move=> nsAG x; rewrite !inE cfuniE // pnatr_eq0 -lt0n lt0b. Qed.
Lemma eq_mul_cfuni A phi : A <| G -> {in A, phi * '1_A =1 phi}.
Proof. by move=> nsAG x Ax; rewrite cfunE cfuniE // Ax mulr1. Qed.
Lemma eq_cfuni A : A <| G -> {in A, '1_A =1 (1 : 'CF(G))}.
Proof. by rewrite -['1_A]mul1r; apply: eq_mul_cfuni. Qed.
Lemma cfuniG : '1_G = 1.
Proof. by rewrite -[G in '1_G]genGid. Qed.
Lemma cfun1E g : (1 : 'CF(G)) g = (g \in G)%:R.
Proof. by rewrite -cfuniG cfuniE. Qed.
Lemma cfun11 : (1 : 'CF(G)) 1%g = 1.
Proof. by rewrite cfun1E group1. Qed.
Lemma prod_cfunE I r (P : pred I) (phi : I -> 'CF(G)) x :
x \in G -> (\prod_(i <- r | P i) phi i) x = \prod_(i <- r | P i) (phi i) x.
Proof.
by move=> Gx; elim/big_rec2: _ => [|i _ psi _ <-]; rewrite ?cfunE ?cfun1E ?Gx.
Qed.
Lemma exp_cfunE phi n x : x \in G -> (phi ^+ n) x = phi x ^+ n.
Proof. by rewrite -[n]card_ord -!prodr_const; apply: prod_cfunE. Qed.
Lemma mul_cfuni A B : '1_A * '1_B = '1_(A :&: B) :> 'CF(G).
Proof.
apply/cfunP=> g; rewrite !cfunElock -natrM mulnb subsetI.
by rewrite andbCA !andbA andbb.
Qed.
Lemma cfun_classE x y : '1_(x ^: G) y = ((x \in G) && (y \in x ^: G))%:R.
Proof.
rewrite cfunElock genGid class_sub_norm ?class_norm //; congr (_ : bool)%:R.
by apply: andb_id2r => /imsetP[z Gz ->]; rewrite groupJr.
Qed.
Lemma cfun_on_sum A :
'CF(G, A) = (\sum_(xG in classes G | xG \subset A) <['1_xG]>)%VS.
Proof.
by rewrite ['CF(G, A)]span_def big_image; apply: eq_bigl => xG; rewrite !inE.
Qed.
Lemma cfun_onP A phi :
reflect (forall x, x \notin A -> phi x = 0) (phi \in 'CF(G, A)).
Proof.
apply: (iffP idP) => [/coord_span-> x notAx | Aphi].
set b := cfun_base G A; rewrite sum_cfunE big1 // => i _; rewrite cfunE.
have /mapP[xG]: b`_i \in b by rewrite -tnth_nth mem_tnth.
rewrite mem_enum => /setIdP[/imsetP[y Gy ->] Ay] ->.
by rewrite cfun_classE Gy (contraNF (subsetP Ay x)) ?mulr0.
suffices <-: \sum_(xG in classes G) phi (repr xG) *: '1_xG = phi.
apply: memv_suml => _ /imsetP[x Gx ->]; rewrite rpredZeq cfun_repr.
have [s_xG_A | /subsetPn[_ /imsetP[y Gy ->]]] := boolP (x ^: G \subset A).
by rewrite cfun_on_sum [_ \in _](sumv_sup (x ^: G)) ?mem_classes ?orbT.
by move/Aphi; rewrite cfunJ // => ->; rewrite eqxx.
apply/cfun_inP=> x Gx; rewrite sum_cfunE (bigD1 (x ^: G)) ?mem_classes //=.
rewrite cfunE cfun_repr cfun_classE Gx class_refl mulr1.
rewrite big1 ?addr0 // => _ /andP[/imsetP[y Gy ->]]; apply: contraNeq.
rewrite cfunE cfun_repr cfun_classE Gy mulf_eq0 => /norP[_].
by rewrite pnatr_eq0 -lt0n lt0b => /class_eqP->.
Qed.
Arguments cfun_onP {A phi}.
Lemma cfun_on0 A phi x : phi \in 'CF(G, A) -> x \notin A -> phi x = 0.
Proof. by move/cfun_onP; apply. Qed.
Lemma sum_by_classes (R : nzRingType) (F : gT -> R) :
{in G &, forall g h, F (g ^ h) = F g} ->
\sum_(g in G) F g = \sum_(xG in classes G) #|xG|%:R * F (repr xG).
Proof.
move=> FJ; rewrite {1}(partition_big _ _ ((@mem_classes gT)^~ G)) /=.
apply: eq_bigr => _ /imsetP[x Gx ->]; have [y Gy ->] := repr_class G x.
rewrite mulr_natl -sumr_const FJ {y Gy}//; apply/esym/eq_big=> y /=.
apply/idP/andP=> [xGy | [Gy /eqP<-]]; last exact: class_refl.
by rewrite (class_eqP xGy) (subsetP (class_subG Gx (subxx _))).
by case/imsetP=> z Gz ->; rewrite FJ.
Qed.
Lemma cfun_base_free A : free (cfun_base G A).
Proof.
have b_i (i : 'I_#|classes G ::&: A|) : (cfun_base G A)`_i = '1_(enum_val i).
by rewrite /enum_val -!tnth_nth tnth_map.
apply/freeP => s S0 i; move/cfunP/(_ (repr (enum_val i))): S0.
rewrite sum_cfunE (bigD1 i) //= big1 ?addr0 => [|j].
rewrite b_i !cfunE; have /setIdP[/imsetP[x Gx ->] _] := enum_valP i.
by rewrite cfun_repr cfun_classE Gx class_refl mulr1.
apply: contraNeq; rewrite b_i !cfunE mulf_eq0 => /norP[_].
rewrite -(inj_eq enum_val_inj).
have /setIdP[/imsetP[x _ ->] _] := enum_valP i; rewrite cfun_repr.
have /setIdP[/imsetP[y Gy ->] _] := enum_valP j; rewrite cfun_classE Gy.
by rewrite pnatr_eq0 -lt0n lt0b => /class_eqP->.
Qed.
Lemma dim_cfun : \dim 'CF(G) = #|classes G|.
Proof. by rewrite dimvf /dim /= genGid. Qed.
Lemma dim_cfun_on A : \dim 'CF(G, A) = #|classes G ::&: A|.
Proof. by rewrite (eqnP (cfun_base_free A)) size_tuple. Qed.
Lemma dim_cfun_on_abelian A : abelian G -> A \subset G -> \dim 'CF(G, A) = #|A|.
Proof.
move/abelian_classP=> cGG sAG; rewrite -(card_imset _ set1_inj) dim_cfun_on.
apply/eq_card=> xG; rewrite !inE.
apply/andP/imsetP=> [[/imsetP[x Gx ->] Ax] | [x Ax ->]] {xG}.
by rewrite cGG ?sub1set // in Ax *; exists x.
by rewrite -{1}(cGG x) ?mem_classes ?(subsetP sAG) ?sub1set.
Qed.
Lemma cfuni_on A : '1_A \in 'CF(G, A).
Proof.
apply/cfun_onP=> x notAx; rewrite cfunElock genGid.
by case: andP => // [[_ s_xG_A]]; rewrite (subsetP s_xG_A) ?class_refl in notAx.
Qed.
Lemma mul_cfuni_on A phi : phi * '1_A \in 'CF(G, A).
Proof.
by apply/cfun_onP=> x /(cfun_onP (cfuni_on A)) Ax0; rewrite cfunE Ax0 mulr0.
Qed.
Lemma cfun_onE phi A : (phi \in 'CF(G, A)) = (support phi \subset A).
Proof. exact: (sameP cfun_onP supportP). Qed.
Lemma cfun_onT phi : phi \in 'CF(G, [set: gT]).
Proof. by rewrite cfun_onE. Qed.
Lemma cfun_onD1 phi A :
(phi \in 'CF(G, A^#)) = (phi \in 'CF(G, A)) && (phi 1%g == 0).
Proof.
by rewrite !cfun_onE -!(eq_subset (in_set (support _))) subsetD1 !inE negbK.
Qed.
Lemma cfun_onG phi : phi \in 'CF(G, G).
Proof. by rewrite cfun_onE support_cfun. Qed.
Lemma cfunD1E phi : (phi \in 'CF(G, G^#)) = (phi 1%g == 0).
Proof. by rewrite cfun_onD1 cfun_onG. Qed.
Lemma cfunGid : 'CF(G, G) = 'CF(G)%VS.
Proof. by apply/vspaceP=> phi; rewrite cfun_onG memvf. Qed.
Lemma cfun_onS A B phi : B \subset A -> phi \in 'CF(G, B) -> phi \in 'CF(G, A).
Proof. by rewrite !cfun_onE => sBA /subset_trans->. Qed.
Lemma cfun_complement A :
A <| G -> ('CF(G, A) + 'CF(G, G :\: A)%SET = 'CF(G))%VS.
Proof.
case/andP=> sAG nAG; rewrite -cfunGid [rhs in _ = rhs]cfun_on_sum.
rewrite (bigID (fun B => B \subset A)) /=.
congr (_ + _)%VS; rewrite cfun_on_sum; apply: eq_bigl => /= xG.
rewrite andbAC; apply/esym/andb_idr=> /andP[/imsetP[x Gx ->] _].
by rewrite class_subG.
rewrite -andbA; apply: andb_id2l => /imsetP[x Gx ->].
by rewrite !class_sub_norm ?normsD ?normG // inE andbC.
Qed.
Lemma cfConjCE phi x : ( phi^* )%CF x = (phi x)^*.
Proof. by rewrite cfunE. Qed.
Lemma cfConjCK : involutive (fun phi => phi^* )%CF.
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE /= conjCK. Qed.
Lemma cfConjC_cfun1 : ( 1^* )%CF = 1 :> 'CF(G).
Proof. exact: rmorph1. Qed.
(* Class function kernel and faithful class functions *)
Fact cfker_is_group phi : group_set (cfker phi).
Proof.
apply/group_setP; split=> [|x y]; rewrite !inE ?group1.
by apply/forallP=> y; rewrite mul1g.
case/andP=> Gx /forallP-Kx /andP[Gy /forallP-Ky]; rewrite groupM //.
by apply/forallP=> z; rewrite -mulgA (eqP (Kx _)) Ky.
Qed.
Canonical cfker_group phi := Group (cfker_is_group phi).
Lemma cfker_sub phi : cfker phi \subset G.
Proof. by rewrite /cfker setIdE subsetIl. Qed.
Lemma cfker_norm phi : G \subset 'N(cfker phi).
Proof.
apply/subsetP=> z Gz; have phiJz := cfunJ phi _ (groupVr Gz).
rewrite inE; apply/subsetP=> _ /imsetP[x /setIdP[Gx /forallP-Kx] ->].
rewrite inE groupJ //; apply/forallP=> y.
by rewrite -(phiJz y) -phiJz conjMg conjgK Kx.
Qed.
Lemma cfker_normal phi : cfker phi <| G.
Proof. by rewrite /normal cfker_sub cfker_norm. Qed.
Lemma cfkerMl phi x y : x \in cfker phi -> phi (x * y)%g = phi y.
Proof. by case/setIdP=> _ /eqfunP->. Qed.
Lemma cfkerMr phi x y : x \in cfker phi -> phi (y * x)%g = phi y.
Proof.
by move=> Kx; rewrite conjgC cfkerMl ?cfunJ ?(subsetP (cfker_sub phi)).
Qed.
Lemma cfker1 phi x : x \in cfker phi -> phi x = phi 1%g.
Proof. by move=> Kx; rewrite -[x]mulg1 cfkerMl. Qed.
Lemma cfker_cfun0 : @cfker _ G 0 = G.
Proof.
apply/setP=> x; rewrite !inE andb_idr // => Gx; apply/forallP=> y.
by rewrite !cfunE.
Qed.
Lemma cfker_add phi psi : cfker phi :&: cfker psi \subset cfker (phi + psi).
Proof.
apply/subsetP=> x /setIP[Kphi_x Kpsi_x]; have [Gx _] := setIdP Kphi_x.
by rewrite inE Gx; apply/forallP=> y; rewrite !cfunE !cfkerMl.
Qed.
Lemma cfker_sum I r (P : pred I) (Phi : I -> 'CF(G)) :
G :&: \bigcap_(i <- r | P i) cfker (Phi i)
\subset cfker (\sum_(i <- r | P i) Phi i).
Proof.
elim/big_rec2: _ => [|i K psi Pi sK_psi]; first by rewrite setIT cfker_cfun0.
by rewrite setICA; apply: subset_trans (setIS _ sK_psi) (cfker_add _ _).
Qed.
Lemma cfker_scale a phi : cfker phi \subset cfker (a *: phi).
Proof.
apply/subsetP=> x Kphi_x; have [Gx _] := setIdP Kphi_x.
by rewrite inE Gx; apply/forallP=> y; rewrite !cfunE cfkerMl.
Qed.
Lemma cfker_scale_nz a phi : a != 0 -> cfker (a *: phi) = cfker phi.
Proof.
move=> nz_a; apply/eqP.
by rewrite eqEsubset -{2}(scalerK nz_a phi) !cfker_scale.
Qed.
Lemma cfker_opp phi : cfker (- phi) = cfker phi.
Proof. by rewrite -scaleN1r cfker_scale_nz // oppr_eq0 oner_eq0. Qed.
Lemma cfker_cfun1 : @cfker _ G 1 = G.
Proof.
apply/setP=> x; rewrite !inE andb_idr // => Gx; apply/forallP=> y.
by rewrite !cfun1E groupMl.
Qed.
Lemma cfker_mul phi psi : cfker phi :&: cfker psi \subset cfker (phi * psi).
Proof.
apply/subsetP=> x /setIP[Kphi_x Kpsi_x]; have [Gx _] := setIdP Kphi_x.
by rewrite inE Gx; apply/forallP=> y; rewrite !cfunE !cfkerMl.
Qed.
Lemma cfker_prod I r (P : pred I) (Phi : I -> 'CF(G)) :
G :&: \bigcap_(i <- r | P i) cfker (Phi i)
\subset cfker (\prod_(i <- r | P i) Phi i).
Proof.
elim/big_rec2: _ => [|i K psi Pi sK_psi]; first by rewrite setIT cfker_cfun1.
by rewrite setICA; apply: subset_trans (setIS _ sK_psi) (cfker_mul _ _).
Qed.
Lemma cfaithfulE phi : cfaithful phi = (cfker phi \subset [1]).
Proof. by []. Qed.
End ClassFun.
Arguments classfun_on {gT} B%_g A%_g.
Notation "''CF' ( G , A )" := (classfun_on G A) : ring_scope.
Arguments cfun_onP {gT G A phi}.
Arguments cfConjCK {gT G} phi : rename.
#[global] Hint Resolve cfun_onT : core.
Section DotProduct.
Variable (gT : finGroupType) (G : {group gT}).
Implicit Types (M : {group gT}) (phi psi xi : 'CF(G)) (R S : seq 'CF(G)).
Lemma cfdotE phi psi :
'[phi, psi] = #|G|%:R^-1 * \sum_(x in G) phi x * (psi x)^*.
Proof. by []. Qed.
Lemma cfdotElr A B phi psi :
phi \in 'CF(G, A) -> psi \in 'CF(G, B) ->
'[phi, psi] = #|G|%:R^-1 * \sum_(x in A :&: B) phi x * (psi x)^*.
Proof.
move=> Aphi Bpsi; rewrite (big_setID G)/= cfdotE (big_setID (A :&: B))/= setIC.
congr (_ * (_ + _)); rewrite !big1 // => x /setDP[_].
by move/cfun0->; rewrite mul0r.
rewrite inE; case/nandP=> notABx; first by rewrite (cfun_on0 Aphi) ?mul0r.
by rewrite (cfun_on0 Bpsi) // rmorph0 mulr0.
Qed.
Lemma cfdotEl A phi psi :
phi \in 'CF(G, A) ->
'[phi, psi] = #|G|%:R^-1 * \sum_(x in A) phi x * (psi x)^*.
Proof. by move=> Aphi; rewrite (cfdotElr Aphi (cfun_onT psi)) setIT. Qed.
Lemma cfdotEr A phi psi :
psi \in 'CF(G, A) ->
'[phi, psi] = #|G|%:R^-1 * \sum_(x in A) phi x * (psi x)^*.
Proof. by move=> Apsi; rewrite (cfdotElr (cfun_onT phi) Apsi) setTI. Qed.
Lemma cfdot_complement A phi psi :
phi \in 'CF(G, A) -> psi \in 'CF(G, G :\: A) -> '[phi, psi] = 0.
Proof.
move=> Aphi A'psi; rewrite (cfdotElr Aphi A'psi).
by rewrite setDE setICA setICr setI0 big_set0 mulr0.
Qed.
Lemma cfnormE A phi :
phi \in 'CF(G, A) -> '[phi] = #|G|%:R^-1 * (\sum_(x in A) `|phi x| ^+ 2).
Proof. by move/cfdotEl->; rewrite (eq_bigr _ (fun _ _ => normCK _)). Qed.
Lemma eq_cfdotl A phi1 phi2 psi :
psi \in 'CF(G, A) -> {in A, phi1 =1 phi2} -> '[phi1, psi] = '[phi2, psi].
Proof.
move/cfdotEr=> eq_dot eq_phi; rewrite !eq_dot; congr (_ * _).
by apply: eq_bigr => x Ax; rewrite eq_phi.
Qed.
Lemma cfdot_cfuni A B :
A <| G -> B <| G -> '['1_A, '1_B]_G = #|A :&: B|%:R / #|G|%:R.
Proof.
move=> nsAG nsBG; rewrite (cfdotElr (cfuni_on G A) (cfuni_on G B)) mulrC.
congr (_ / _); rewrite -sumr_const; apply: eq_bigr => x /setIP[Ax Bx].
by rewrite !cfuniE // Ax Bx mul1r rmorph1.
Qed.
Lemma cfnorm1 : '[1]_G = 1.
Proof. by rewrite cfdot_cfuni ?genGid // setIid divff ?neq0CG. Qed.
Lemma cfdotrE psi phi : cfdotr psi phi = '[phi, psi]. Proof. by []. Qed.
Lemma cfdotr_is_linear xi : linear (cfdotr xi : 'CF(G) -> algC^o).
Proof.
move=> a phi psi; rewrite scalerAr -mulrDr; congr (_ * _).
rewrite linear_sum -big_split; apply: eq_bigr => x _ /=.
by rewrite !cfunE mulrDl -mulrA.
Qed.
HB.instance Definition _ xi := GRing.isSemilinear.Build algC _ _ _ (cfdotr xi)
(GRing.semilinear_linear (cfdotr_is_linear xi)).
Lemma cfdot0l xi : '[0, xi] = 0.
Proof. by rewrite -cfdotrE linear0. Qed.
Lemma cfdotNl xi phi : '[- phi, xi] = - '[phi, xi].
Proof. by rewrite -!cfdotrE linearN. Qed.
Lemma cfdotDl xi phi psi : '[phi + psi, xi] = '[phi, xi] + '[psi, xi].
Proof. by rewrite -!cfdotrE linearD. Qed.
Lemma cfdotBl xi phi psi : '[phi - psi, xi] = '[phi, xi] - '[psi, xi].
Proof. by rewrite -!cfdotrE linearB. Qed.
Lemma cfdotMnl xi phi n : '[phi *+ n, xi] = '[phi, xi] *+ n.
Proof. by rewrite -!cfdotrE linearMn. Qed.
Lemma cfdot_suml xi I r (P : pred I) (phi : I -> 'CF(G)) :
'[\sum_(i <- r | P i) phi i, xi] = \sum_(i <- r | P i) '[phi i, xi].
Proof. by rewrite -!cfdotrE linear_sum. Qed.
Lemma cfdotZl xi a phi : '[a *: phi, xi] = a * '[phi, xi].
Proof. by rewrite -!cfdotrE linearZ. Qed.
Lemma cfdotC phi psi : '[phi, psi] = ('[psi, phi])^*.
Proof.
rewrite /cfdot rmorphM /= fmorphV rmorph_nat rmorph_sum; congr (_ * _).
by apply: eq_bigr=> x _; rewrite rmorphM /= conjCK mulrC.
Qed.
Lemma eq_cfdotr A phi psi1 psi2 :
phi \in 'CF(G, A) -> {in A, psi1 =1 psi2} -> '[phi, psi1] = '[phi, psi2].
Proof. by move=> Aphi /eq_cfdotl eq_dot; rewrite cfdotC eq_dot // -cfdotC. Qed.
Lemma cfdotBr xi phi psi : '[xi, phi - psi] = '[xi, phi] - '[xi, psi].
Proof. by rewrite !(cfdotC xi) -rmorphB cfdotBl. Qed.
HB.instance Definition _ xi :=
GRing.isZmodMorphism.Build _ _ (cfdot xi) (cfdotBr xi).
Lemma cfdot0r xi : '[xi, 0] = 0. Proof. exact: raddf0. Qed.
Lemma cfdotNr xi phi : '[xi, - phi] = - '[xi, phi].
Proof. exact: raddfN. Qed.
Lemma cfdotDr xi phi psi : '[xi, phi + psi] = '[xi, phi] + '[xi, psi].
Proof. exact: raddfD. Qed.
Lemma cfdotMnr xi phi n : '[xi, phi *+ n] = '[xi, phi] *+ n.
Proof. exact: raddfMn. Qed.
Lemma cfdot_sumr xi I r (P : pred I) (phi : I -> 'CF(G)) :
'[xi, \sum_(i <- r | P i) phi i] = \sum_(i <- r | P i) '[xi, phi i].
Proof. exact: raddf_sum. Qed.
Lemma cfdotZr a xi phi : '[xi, a *: phi] = a^* * '[xi, phi].
Proof. by rewrite !(cfdotC xi) cfdotZl rmorphM. Qed.
Lemma cfdot_cfAut (u : {rmorphism algC -> algC}) phi psi :
{in image psi G, {morph u : x / x^*}} ->
'[cfAut u phi, cfAut u psi] = u '[phi, psi].
Proof.
move=> uC; rewrite rmorphM /= fmorphV rmorph_nat rmorph_sum; congr (_ * _).
by apply: eq_bigr => x Gx; rewrite !cfunE rmorphM /= uC ?map_f ?mem_enum.
Qed.
Lemma cfdot_conjC phi psi : '[phi^*, psi^*] = '[phi, psi]^*.
Proof. by rewrite cfdot_cfAut. Qed.
Lemma cfdot_conjCl phi psi : '[phi^*, psi] = '[phi, psi^*]^*.
Proof. by rewrite -cfdot_conjC cfConjCK. Qed.
Lemma cfdot_conjCr phi psi : '[phi, psi^*] = '[phi^*, psi]^*.
Proof. by rewrite -cfdot_conjC cfConjCK. Qed.
Lemma cfnorm_ge0 phi : 0 <= '[phi].
Proof.
by rewrite mulr_ge0 ?invr_ge0 ?ler0n ?sumr_ge0 // => x _; apply: mul_conjC_ge0.
Qed.
Lemma cfnorm_eq0 phi : ('[phi] == 0) = (phi == 0).
Proof.
apply/idP/eqP=> [|->]; last by rewrite cfdot0r.
rewrite mulf_eq0 invr_eq0 (negbTE (neq0CG G)) /= => /eqP/psumr_eq0P phi0.
apply/cfun_inP=> x Gx; apply/eqP; rewrite cfunE -mul_conjC_eq0.
by rewrite phi0 // => y _; apply: mul_conjC_ge0.
Qed.
Lemma cfnorm_gt0 phi : ('[phi] > 0) = (phi != 0).
Proof. by rewrite lt_def cfnorm_ge0 cfnorm_eq0 andbT. Qed.
Lemma sqrt_cfnorm_ge0 phi : 0 <= sqrtC '[phi].
Proof. by rewrite sqrtC_ge0 cfnorm_ge0. Qed.
Lemma sqrt_cfnorm_eq0 phi : (sqrtC '[phi] == 0) = (phi == 0).
Proof. by rewrite sqrtC_eq0 cfnorm_eq0. Qed.
Lemma sqrt_cfnorm_gt0 phi : (sqrtC '[phi] > 0) = (phi != 0).
Proof. by rewrite sqrtC_gt0 cfnorm_gt0. Qed.
Lemma cfnormZ a phi : '[a *: phi]= `|a| ^+ 2 * '[phi]_G.
Proof. by rewrite cfdotZl cfdotZr mulrA normCK. Qed.
Lemma cfnormN phi : '[- phi] = '[phi].
Proof. by rewrite cfdotNl raddfN opprK. Qed.
Lemma cfnorm_sign n phi : '[(-1) ^+ n *: phi] = '[phi].
Proof. by rewrite -signr_odd scaler_sign; case: (odd n); rewrite ?cfnormN. Qed.
Lemma cfnormD phi psi :
let d := '[phi, psi] in '[phi + psi] = '[phi] + '[psi] + ( d + d^* ).
Proof. by rewrite /= addrAC -cfdotC cfdotDl !cfdotDr !addrA. Qed.
Lemma cfnormB phi psi :
let d := '[phi, psi] in '[phi - psi] = '[phi] + '[psi] - ( d + d^* ).
Proof. by rewrite /= cfnormD cfnormN cfdotNr rmorphN -opprD. Qed.
Lemma cfnormDd phi psi : '[phi, psi] = 0 -> '[phi + psi] = '[phi] + '[psi].
Proof. by move=> ophipsi; rewrite cfnormD ophipsi rmorph0 !addr0. Qed.
Lemma cfnormBd phi psi : '[phi, psi] = 0 -> '[phi - psi] = '[phi] + '[psi].
Proof.
by move=> ophipsi; rewrite cfnormDd ?cfnormN // cfdotNr ophipsi oppr0.
Qed.
Lemma cfnorm_conjC phi : '[phi^*] = '[phi].
Proof. by rewrite cfdot_conjC geC0_conj // cfnorm_ge0. Qed.
Lemma cfCauchySchwarz phi psi :
`|'[phi, psi]| ^+ 2 <= '[phi] * '[psi] ?= iff ~~ free (phi :: psi).
Proof.
rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC.
have [-> | nz_psi] /= := eqVneq psi 0.
by apply/leifP; rewrite !cfdot0r normCK mul0r mulr0.
without loss ophi: phi / '[phi, psi] = 0.
move=> IHo; pose a := '[phi, psi] / '[psi]; pose phi1 := phi - a *: psi.
have ophi: '[phi1, psi] = 0.
by rewrite cfdotBl cfdotZl divfK ?cfnorm_eq0 ?subrr.
rewrite (canRL (subrK _) (erefl phi1)) rpredDr ?rpredZ ?memv_line //.
rewrite cfdotDl ophi add0r cfdotZl normrM (ger0_norm (cfnorm_ge0 _)).
rewrite exprMn mulrA -cfnormZ cfnormDd; last by rewrite cfdotZr ophi mulr0.
by have:= IHo _ ophi; rewrite mulrDl -leifBLR subrr ophi normCK mul0r.
rewrite ophi normCK mul0r; split; first by rewrite mulr_ge0 ?cfnorm_ge0.
rewrite eq_sym mulf_eq0 orbC cfnorm_eq0 (negPf nz_psi) /=.
apply/idP/idP=> [|/vlineP[a {2}->]]; last by rewrite cfdotZr ophi mulr0.
by rewrite cfnorm_eq0 => /eqP->; apply: rpred0.
Qed.
Lemma cfCauchySchwarz_sqrt phi psi :
`|'[phi, psi]| <= sqrtC '[phi] * sqrtC '[psi] ?= iff ~~ free (phi :: psi).
Proof.
rewrite -(sqrCK (normr_ge0 _)) -sqrtCM ?qualifE/= ?cfnorm_ge0 //.
rewrite (mono_in_leif (@ler_sqrtC _)) 1?rpredM ?qualifE/= ?cfnorm_ge0 //;
[ exact: cfCauchySchwarz | exact: O.. ].
Qed.
Lemma cf_triangle_leif phi psi :
sqrtC '[phi + psi] <= sqrtC '[phi] + sqrtC '[psi]
?= iff ~~ free (phi :: psi) && (0 <= coord [tuple psi] 0 phi).
Proof.
rewrite -(mono_in_leif ler_sqr) ?rpredD ?qualifE/= ?sqrtC_ge0 ?cfnorm_ge0 //;
[| exact: O.. ].
rewrite andbC sqrrD !sqrtCK addrAC cfnormD (mono_leif (lerD2l _)).
rewrite -mulr_natr -[_ + _](divfK (negbT (eqC_nat 2 0))) -/('Re _).
rewrite (mono_leif (ler_pM2r _)) ?ltr0n //.
have:= leif_trans (leif_Re_Creal '[phi, psi]) (cfCauchySchwarz_sqrt phi psi).
congr (_ <= _ ?= iff _); first by rewrite ReE.
apply: andb_id2r; rewrite free_cons span_seq1 seq1_free -negb_or negbK orbC /=.
have [-> | nz_psi] := eqVneq psi 0; first by rewrite cfdot0r coord0.
case/vlineP=> [x ->]; rewrite cfdotZl linearZ pmulr_lge0 ?cfnorm_gt0 //=.
by rewrite (coord_free 0) ?seq1_free // eqxx mulr1.
Qed.
Lemma orthogonal_cons phi R S :
orthogonal (phi :: R) S = orthogonal phi S && orthogonal R S.
Proof. by rewrite /orthogonal /= andbT. Qed.
Lemma orthoP phi psi : reflect ('[phi, psi] = 0) (orthogonal phi psi).
Proof. by rewrite /orthogonal /= !andbT; apply: eqP. Qed.
Lemma orthogonalP S R :
reflect {in S & R, forall phi psi, '[phi, psi] = 0} (orthogonal S R).
Proof.
apply: (iffP allP) => oSR phi => [psi /oSR/allP opS /opS/eqP // | /oSR opS].
by apply/allP=> psi /= /opS->.
Qed.
Lemma orthoPl phi S :
reflect {in S, forall psi, '[phi, psi] = 0} (orthogonal phi S).
Proof.
by rewrite [orthogonal _ S]andbT /=; apply: (iffP allP) => ophiS ? /ophiS/eqP.
Qed.
Arguments orthoPl {phi S}.
Lemma orthogonal_sym : symmetric (@orthogonal _ G).
Proof.
apply: symmetric_from_pre => R S /orthogonalP oRS.
by apply/orthogonalP=> phi psi Rpsi Sphi; rewrite cfdotC oRS ?rmorph0.
Qed.
Lemma orthoPr S psi :
reflect {in S, forall phi, '[phi, psi] = 0} (orthogonal S psi).
Proof.
rewrite orthogonal_sym.
by apply: (iffP orthoPl) => oSpsi phi Sphi; rewrite cfdotC oSpsi ?conjC0.
Qed.
Lemma eq_orthogonal R1 R2 S1 S2 :
R1 =i R2 -> S1 =i S2 -> orthogonal R1 S1 = orthogonal R2 S2.
Proof.
move=> eqR eqS; rewrite [orthogonal _ _](eq_all_r eqR).
by apply: eq_all => psi /=; apply: eq_all_r.
Qed.
Lemma orthogonal_catl R1 R2 S :
orthogonal (R1 ++ R2) S = orthogonal R1 S && orthogonal R2 S.
Proof. exact: all_cat. Qed.
Lemma orthogonal_catr R S1 S2 :
orthogonal R (S1 ++ S2) = orthogonal R S1 && orthogonal R S2.
Proof. by rewrite !(orthogonal_sym R) orthogonal_catl. Qed.
Lemma span_orthogonal S1 S2 phi1 phi2 :
orthogonal S1 S2 -> phi1 \in <<S1>>%VS -> phi2 \in <<S2>>%VS ->
'[phi1, phi2] = 0.
Proof.
move/orthogonalP=> oS12; do 2!move/(@coord_span _ _ _ (in_tuple _))->.
rewrite cfdot_suml big1 // => i _; rewrite cfdot_sumr big1 // => j _.
by rewrite cfdotZl cfdotZr oS12 ?mem_nth ?mulr0.
Qed.
Lemma orthogonal_split S beta :
{X : 'CF(G) & X \in <<S>>%VS &
{Y | [/\ beta = X + Y, '[X, Y] = 0 & orthogonal Y S]}}.
Proof.
suffices [X S_X [Y -> oYS]]:
{X : _ & X \in <<S>>%VS & {Y | beta = X + Y & orthogonal Y S}}.
- exists X => //; exists Y.
by rewrite cfdotC (span_orthogonal oYS) ?memv_span1 ?conjC0.
elim: S beta => [|phi S IHS] beta.
by exists 0; last exists beta; rewrite ?mem0v ?add0r.
have [[U S_U [V -> oVS]] [X S_X [Y -> oYS]]] := (IHS phi, IHS beta).
pose Z := '[Y, V] / '[V] *: V; exists (X + Z).
rewrite /Z -{4}(addKr U V) scalerDr scalerN addrA addrC span_cons.
by rewrite memv_add ?memvB ?memvZ ?memv_line.
exists (Y - Z); first by rewrite addrCA !addrA addrK addrC.
apply/orthoPl=> psi /[!inE] /predU1P[-> | Spsi]; last first.
by rewrite cfdotBl cfdotZl (orthoPl oVS _ Spsi) mulr0 subr0 (orthoPl oYS).
rewrite cfdotBl !cfdotDr (span_orthogonal oYS) // ?memv_span ?mem_head //.
rewrite !cfdotZl (span_orthogonal oVS _ S_U) ?mulr0 ?memv_span ?mem_head //.
have [-> | nzV] := eqVneq V 0; first by rewrite cfdot0r !mul0r subrr.
by rewrite divfK ?cfnorm_eq0 ?subrr.
Qed.
Lemma map_orthogonal M (nu : 'CF(G) -> 'CF(M)) S R (A : {pred 'CF(G)}) :
{in A &, isometry nu} -> {subset S <= A} -> {subset R <= A} ->
orthogonal (map nu S) (map nu R) = orthogonal S R.
Proof.
move=> Inu sSA sRA; rewrite [orthogonal _ _]all_map.
apply: eq_in_all => phi Sphi; rewrite /= all_map.
by apply: eq_in_all => psi Rpsi; rewrite /= Inu ?(sSA phi) ?(sRA psi).
Qed.
Lemma orthogonal_oppr S R : orthogonal S (map -%R R) = orthogonal S R.
Proof.
wlog suffices IH: S R / orthogonal S R -> orthogonal S (map -%R R).
by apply/idP/idP=> /IH; rewrite ?mapK //; apply: opprK.
move/orthogonalP=> oSR; apply/orthogonalP=> xi1 _ Sxi1 /mapP[xi2 Rxi2 ->].
by rewrite cfdotNr oSR ?oppr0.
Qed.
Lemma orthogonal_oppl S R : orthogonal (map -%R S) R = orthogonal S R.
Proof. by rewrite -!(orthogonal_sym R) orthogonal_oppr. Qed.
Lemma pairwise_orthogonalP S :
reflect (uniq (0 :: S)
/\ {in S &, forall phi psi, phi != psi -> '[phi, psi] = 0})
(pairwise_orthogonal S).
Proof.
rewrite /pairwise_orthogonal /=; case notS0: (~~ _); last by right; case.
elim: S notS0 => [|phi S IH] /=; first by left.
rewrite inE eq_sym andbT => /norP[nz_phi /IH{}IH].
have [opS | not_opS] := allP; last first.
right=> [[/andP[notSp _] opS]]; case: not_opS => psi Spsi /=.
by rewrite opS ?mem_head 1?mem_behead // (memPnC notSp).
rewrite (contra (opS _)) /= ?cfnorm_eq0 //.
apply: (iffP IH) => [] [uniqS oSS]; last first.
by split=> //; apply: sub_in2 oSS => psi Spsi; apply: mem_behead.
split=> // psi xi /[!inE] /predU1P[-> // | Spsi].
by case/predU1P=> [-> | /opS] /eqP.
case/predU1P=> [-> _ | Sxi /oSS-> //].
by apply/eqP; rewrite cfdotC conjC_eq0 [_ == 0]opS.
Qed.
Lemma pairwise_orthogonal_cat R S :
pairwise_orthogonal (R ++ S) =
[&& pairwise_orthogonal R, pairwise_orthogonal S & orthogonal R S].
Proof.
rewrite /pairwise_orthogonal mem_cat negb_or -!andbA; do !bool_congr.
elim: R => [|phi R /= ->]; rewrite ?andbT // orthogonal_cons all_cat -!andbA /=.
by do !bool_congr.
Qed.
Lemma eq_pairwise_orthogonal R S :
perm_eq R S -> pairwise_orthogonal R = pairwise_orthogonal S.
Proof.
apply: catCA_perm_subst R S => R S S'.
rewrite !pairwise_orthogonal_cat !orthogonal_catr (orthogonal_sym R S) -!andbA.
by do !bool_congr.
Qed.
Lemma sub_pairwise_orthogonal S1 S2 :
{subset S1 <= S2} -> uniq S1 ->
pairwise_orthogonal S2 -> pairwise_orthogonal S1.
Proof.
move=> sS12 uniqS1 /pairwise_orthogonalP[/andP[notS2_0 _] oS2].
apply/pairwise_orthogonalP; rewrite /= (contra (sS12 0)) //.
by split=> //; apply: sub_in2 oS2.
Qed.
Lemma orthogonal_free S : pairwise_orthogonal S -> free S.
Proof.
case/pairwise_orthogonalP=> [/=/andP[notS0 uniqS] oSS].
rewrite -(in_tupleE S); apply/freeP => a aS0 i.
have S_i: S`_i \in S by apply: mem_nth.
have /eqP: '[S`_i, 0]_G = 0 := cfdot0r _.
rewrite -{2}aS0 raddf_sum /= (bigD1 i) //= big1 => [|j neq_ji]; last 1 first.
by rewrite cfdotZr oSS ?mulr0 ?mem_nth // eq_sym nth_uniq.
rewrite addr0 cfdotZr mulf_eq0 conjC_eq0 cfnorm_eq0.
by case/pred2P=> // Si0; rewrite -Si0 S_i in notS0.
Qed.
Lemma filter_pairwise_orthogonal S p :
pairwise_orthogonal S -> pairwise_orthogonal (filter p S).
Proof.
move=> orthoS; apply: sub_pairwise_orthogonal (orthoS).
exact: mem_subseq (filter_subseq p S).
exact/filter_uniq/free_uniq/orthogonal_free.
Qed.
Lemma orthonormal_not0 S : orthonormal S -> 0 \notin S.
Proof.
by case/andP=> /allP S1 _; rewrite (contra (S1 _)) //= cfdot0r eq_sym oner_eq0.
Qed.
Lemma orthonormalE S :
orthonormal S = all [pred phi | '[phi] == 1] S && pairwise_orthogonal S.
Proof. by rewrite -(andb_idl (@orthonormal_not0 S)) andbCA. Qed.
Lemma orthonormal_orthogonal S : orthonormal S -> pairwise_orthogonal S.
Proof. by rewrite orthonormalE => /andP[_]. Qed.
Lemma orthonormal_cat R S :
orthonormal (R ++ S) = [&& orthonormal R, orthonormal S & orthogonal R S].
Proof.
rewrite !orthonormalE pairwise_orthogonal_cat all_cat -!andbA.
by do !bool_congr.
Qed.
Lemma eq_orthonormal R S : perm_eq R S -> orthonormal R = orthonormal S.
Proof.
move=> eqRS; rewrite !orthonormalE (eq_all_r (perm_mem eqRS)).
by rewrite (eq_pairwise_orthogonal eqRS).
Qed.
Lemma orthonormal_free S : orthonormal S -> free S.
Proof. by move/orthonormal_orthogonal/orthogonal_free. Qed.
Lemma orthonormalP S :
reflect (uniq S /\ {in S &, forall phi psi, '[phi, psi]_G = (phi == psi)%:R})
(orthonormal S).
Proof.
rewrite orthonormalE; have [/= normS | not_normS] := allP; last first.
by right=> [[_ o1S]]; case: not_normS => phi Sphi; rewrite /= o1S ?eqxx.
apply: (iffP (pairwise_orthogonalP S)) => [] [uniqS oSS].
split=> // [|phi psi]; first by case/andP: uniqS.
by have [-> _ /normS/eqP | /oSS] := eqVneq.
split=> // [|phi psi Sphi Spsi /negbTE]; last by rewrite oSS // => ->.
by rewrite /= (contra (normS _)) // cfdot0r eq_sym oner_eq0.
Qed.
Lemma sub_orthonormal S1 S2 :
{subset S1 <= S2} -> uniq S1 -> orthonormal S2 -> orthonormal S1.
Proof.
move=> sS12 uniqS1 /orthonormalP[_ oS1].
by apply/orthonormalP; split; last apply: sub_in2 sS12 _ _.
Qed.
Lemma orthonormal2P phi psi :
reflect [/\ '[phi, psi] = 0, '[phi] = 1 & '[psi] = 1]
(orthonormal [:: phi; psi]).
Proof.
rewrite /orthonormal /= !andbT andbC.
by apply: (iffP and3P) => [] []; do 3!move/eqP->.
Qed.
Lemma conjC_pair_orthogonal S chi :
cfConjC_closed S -> ~~ has cfReal S -> pairwise_orthogonal S -> chi \in S ->
pairwise_orthogonal (chi :: chi^*%CF).
Proof.
move=> ccS /hasPn nrS oSS Schi; apply: sub_pairwise_orthogonal oSS.
by apply/allP; rewrite /= Schi ccS.
by rewrite /= inE eq_sym nrS.
Qed.
Lemma cfdot_real_conjC phi psi : cfReal phi -> '[phi, psi^*]_G = '[phi, psi]^*.
Proof. by rewrite -cfdot_conjC => /eqcfP->. Qed.
Lemma extend_cfConjC_subset S X phi :
cfConjC_closed S -> ~~ has cfReal S -> phi \in S -> phi \notin X ->
cfConjC_subset X S -> cfConjC_subset [:: phi, phi^* & X]%CF S.
Proof.
move=> ccS nrS Sphi X'phi [uniqX /allP-sXS ccX].
split; last 1 [by apply/allP; rewrite /= Sphi ccS | apply/allP]; rewrite /= inE.
by rewrite negb_or X'phi eq_sym (hasPn nrS) // (contra (ccX _)) ?cfConjCK.
by rewrite cfConjCK !mem_head orbT; apply/allP=> xi Xxi; rewrite !inE ccX ?orbT.
Qed.
(* Note: other isometry lemmas, and the dot product lemmas for orthogonal *)
(* and orthonormal sequences are in vcharacter, because we need the 'Z[S] *)
(* notation for the isometry domains. Alternatively, this could be moved to *)
(* cfun. *)
End DotProduct.
Arguments orthoP {gT G phi psi}.
Arguments orthoPl {gT G phi S}.
Arguments orthoPr {gT G S psi}.
Arguments orthogonalP {gT G S R}.
Arguments pairwise_orthogonalP {gT G S}.
Arguments orthonormalP {gT G S}.
Section CfunOrder.
Variables (gT : finGroupType) (G : {group gT}) (phi : 'CF(G)).
Lemma dvdn_cforderP n :
reflect {in G, forall x, phi x ^+ n = 1} (#[phi]%CF %| n)%N.
Proof.
apply: (iffP (dvdn_biglcmP _ _ _)); rewrite genGid => phiG1 x Gx.
by apply/eqP; rewrite -dvdn_orderC phiG1.
by rewrite dvdn_orderC phiG1.
Qed.
Lemma dvdn_cforder n : (#[phi]%CF %| n) = (phi ^+ n == 1).
Proof.
apply/dvdn_cforderP/eqP=> phi_n_1 => [|x Gx].
by apply/cfun_inP=> x Gx; rewrite exp_cfunE // cfun1E Gx phi_n_1.
by rewrite -exp_cfunE // phi_n_1 // cfun1E Gx.
Qed.
Lemma exp_cforder : phi ^+ #[phi]%CF = 1.
Proof. by apply/eqP; rewrite -dvdn_cforder. Qed.
End CfunOrder.
Arguments dvdn_cforderP {gT G phi n}.
Section MorphOrder.
Variables (aT rT : finGroupType) (G : {group aT}) (R : {group rT}).
Variable f : {rmorphism 'CF(G) -> 'CF(R)}.
Lemma cforder_rmorph phi : #[f phi]%CF %| #[phi]%CF.
Proof. by rewrite dvdn_cforder -rmorphXn exp_cforder rmorph1. Qed.
Lemma cforder_inj_rmorph phi : injective f -> #[f phi]%CF = #[phi]%CF.
Proof.
move=> inj_f; apply/eqP; rewrite eqn_dvd cforder_rmorph dvdn_cforder /=.
by rewrite -(rmorph_eq1 _ inj_f) rmorphXn exp_cforder.
Qed.
End MorphOrder.
Section BuildIsometries.
Variable (gT : finGroupType) (L G : {group gT}).
Implicit Types (phi psi xi : 'CF(L)) (R S : seq 'CF(L)).
Implicit Types (U : {pred 'CF(L)}) (W : {pred 'CF(G)}).
Lemma sub_iso_to U1 U2 W1 W2 tau :
{subset U2 <= U1} -> {subset W1 <= W2} ->
{in U1, isometry tau, to W1} -> {in U2, isometry tau, to W2}.
Proof.
by move=> sU sW [Itau Wtau]; split=> [|u /sU/Wtau/sW //]; apply: sub_in2 Itau.
Qed.
Lemma isometry_of_free S f :
free S -> {in S &, isometry f} ->
{tau : {linear 'CF(L) -> 'CF(G)} |
{in S, tau =1 f} & {in <<S>>%VS &, isometry tau}}.
Proof.
move=> freeS If; have defS := free_span freeS.
have [tau /(_ freeS (size_map f S))Dtau] := linear_of_free S (map f S).
have{} Dtau: {in S, tau =1 f}.
by move=> _ /(nthP 0)[i ltiS <-]; rewrite -!(nth_map 0 0) ?Dtau.
exists tau => // _ _ /defS[a -> _] /defS[b -> _].
rewrite !{1}linear_sum !{1}cfdot_suml; apply/eq_big_seq=> xi1 Sxi1.
rewrite !{1}cfdot_sumr; apply/eq_big_seq=> xi2 Sxi2.
by rewrite !linearZ /= !Dtau // !cfdotZl !cfdotZr If.
Qed.
Lemma isometry_of_cfnorm S tauS :
pairwise_orthogonal S -> pairwise_orthogonal tauS ->
map cfnorm tauS = map cfnorm S ->
{tau : {linear 'CF(L) -> 'CF(G)} | map tau S = tauS
& {in <<S>>%VS &, isometry tau}}.
Proof.
move=> oS oT eq_nST; have freeS := orthogonal_free oS.
have eq_sz: size tauS = size S by have:= congr1 size eq_nST; rewrite !size_map.
have [tau defT] := linear_of_free S tauS; rewrite -[S]/(tval (in_tuple S)).
exists tau => [|u v /coord_span-> /coord_span->]; rewrite ?raddf_sum ?defT //=.
apply: eq_bigr => i _ /=; rewrite linearZ !cfdotZr !cfdot_suml; congr (_ * _).
apply: eq_bigr => j _ /=; rewrite linearZ !cfdotZl; congr (_ * _).
rewrite -!(nth_map 0 0 tau) ?{}defT //; have [-> | neq_ji] := eqVneq j i.
by rewrite -!['[_]](nth_map 0 0 cfnorm) ?eq_sz // eq_nST.
have{oS} [/=/andP[_ uS] oS] := pairwise_orthogonalP oS.
have{oT} [/=/andP[_ uT] oT] := pairwise_orthogonalP oT.
by rewrite oS ?oT ?mem_nth ?nth_uniq ?eq_sz.
Qed.
Lemma isometry_raddf_inj U (tau : {additive 'CF(L) -> 'CF(G)}) :
{in U &, isometry tau} -> {in U &, forall u v, u - v \in U} ->
{in U &, injective tau}.
Proof.
move=> Itau linU phi psi Uphi Upsi /eqP; rewrite -subr_eq0 -raddfB.
by rewrite -cfnorm_eq0 Itau ?linU // cfnorm_eq0 subr_eq0 => /eqP.
Qed.
Lemma opp_isometry : @isometry _ _ G G -%R.
Proof. by move=> x y; rewrite cfdotNl cfdotNr opprK. Qed.
End BuildIsometries.
Section Restrict.
Variables (gT : finGroupType) (A B : {set gT}).
Local Notation H := <<A>>.
Local Notation G := <<B>>.
Fact cfRes_subproof (phi : 'CF(B)) :
is_class_fun H [ffun x => phi (if H \subset G then x else 1%g) *+ (x \in H)].
Proof.
apply: intro_class_fun => /= [x y Hx Hy | x /negbTE/=-> //].
by rewrite Hx (groupJ Hx) //; case: subsetP => // sHG; rewrite cfunJgen ?sHG.
Qed.
Definition cfRes phi := Cfun 1 (cfRes_subproof phi).
Lemma cfResE phi : A \subset B -> {in A, cfRes phi =1 phi}.
Proof. by move=> sAB x Ax; rewrite cfunElock mem_gen ?genS. Qed.
Lemma cfRes1 phi : cfRes phi 1%g = phi 1%g.
Proof. by rewrite cfunElock if_same group1. Qed.
Lemma cfRes_is_linear : linear cfRes.
Proof.
by move=> a phi psi; apply/cfunP=> x; rewrite !cfunElock mulrnAr mulrnDl.
Qed.
HB.instance Definition _ := GRing.isSemilinear.Build algC _ _ _ cfRes
(GRing.semilinear_linear cfRes_is_linear).
Lemma cfRes_cfun1 : cfRes 1 = 1.
Proof.
apply: cfun_in_genP => x Hx; rewrite cfunElock Hx !cfun1Egen Hx.
by case: subsetP => [-> // | _]; rewrite group1.
Qed.
Lemma cfRes_is_monoid_morphism : monoid_morphism cfRes.
Proof.
split=> [|phi psi]; [exact: cfRes_cfun1 | apply/cfunP=> x].
by rewrite !cfunElock mulrnAr mulrnAl -mulrnA mulnb andbb.
Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfRes_is_monoid_morphism` instead")]
Definition cfRes_is_multiplicative :=
(fun g => (g.2,g.1)) cfRes_is_monoid_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build _ _ cfRes
cfRes_is_monoid_morphism.
End Restrict.
Arguments cfRes {gT} A%_g {B%_g} phi%_CF.
Notation "''Res[' H , G ]" := (@cfRes _ H G) (only parsing) : ring_scope.
Notation "''Res[' H ]" := 'Res[H, _] : ring_scope.
Notation "''Res'" := 'Res[_] (only parsing) : ring_scope.
Section MoreRestrict.
Variables (gT : finGroupType) (G H : {group gT}).
Implicit Types (A : {set gT}) (phi : 'CF(G)).
Lemma cfResEout phi : ~~ (H \subset G) -> 'Res[H] phi = (phi 1%g)%:A.
Proof.
move/negPf=> not_sHG; apply/cfunP=> x.
by rewrite cfunE cfun1E mulr_natr cfunElock !genGid not_sHG.
Qed.
Lemma cfResRes A phi :
A \subset H -> H \subset G -> 'Res[A] ('Res[H] phi) = 'Res[A] phi.
Proof.
move=> sAH sHG; apply/cfunP=> x; rewrite !cfunElock !genGid !gen_subG sAH sHG.
by rewrite (subset_trans sAH) // -mulrnA mulnb -in_setI (setIidPr _) ?gen_subG.
Qed.
Lemma cfRes_id A psi : 'Res[A] psi = psi.
Proof. by apply/cfun_in_genP=> x Ax; rewrite cfunElock Ax subxx. Qed.
Lemma sub_cfker_Res A phi :
A \subset H -> A \subset cfker phi -> A \subset cfker ('Res[H, G] phi).
Proof.
move=> sAH kerA; apply/subsetP=> x Ax; have Hx := subsetP sAH x Ax.
rewrite inE Hx; apply/forallP=> y; rewrite !cfunElock !genGid groupMl //.
by rewrite !(fun_if phi) cfkerMl // (subsetP kerA).
Qed.
Lemma eq_cfker_Res phi : H \subset cfker phi -> cfker ('Res[H, G] phi) = H.
Proof. by move=> kH; apply/eqP; rewrite eqEsubset cfker_sub sub_cfker_Res. Qed.
Lemma cfRes_sub_ker phi : H \subset cfker phi -> 'Res[H, G] phi = (phi 1%g)%:A.
Proof.
move=> kerHphi; have sHG := subset_trans kerHphi (cfker_sub phi).
apply/cfun_inP=> x Hx; have ker_x := subsetP kerHphi x Hx.
by rewrite cfResE // cfunE cfun1E Hx mulr1 cfker1.
Qed.
Lemma cforder_Res phi : #['Res[H] phi]%CF %| #[phi]%CF.
Proof. exact: cforder_rmorph. Qed.
End MoreRestrict.
Section Morphim.
Variables (aT rT : finGroupType) (D : {group aT}) (f : {morphism D >-> rT}).
Section Main.
Variable G : {group aT}.
Implicit Type phi : 'CF(f @* G).
Fact cfMorph_subproof phi :
is_class_fun <<G>>
[ffun x => phi (if G \subset D then f x else 1%g) *+ (x \in G)].
Proof.
rewrite genGid; apply: intro_class_fun => [x y Gx Gy | x /negPf-> //].
rewrite Gx groupJ //; case subsetP => // sGD.
by rewrite morphJ ?cfunJ ?mem_morphim ?sGD.
Qed.
Definition cfMorph phi := Cfun 1 (cfMorph_subproof phi).
Lemma cfMorphE phi x : G \subset D -> x \in G -> cfMorph phi x = phi (f x).
Proof. by rewrite cfunElock => -> ->. Qed.
Lemma cfMorph1 phi : cfMorph phi 1%g = phi 1%g.
Proof. by rewrite cfunElock morph1 if_same group1. Qed.
Lemma cfMorphEout phi : ~~ (G \subset D) -> cfMorph phi = (phi 1%g)%:A.
Proof.
move/negPf=> not_sGD; apply/cfunP=> x; rewrite cfunE cfun1E mulr_natr.
by rewrite cfunElock not_sGD.
Qed.
Lemma cfMorph_cfun1 : cfMorph 1 = 1.
Proof.
apply/cfun_inP=> x Gx; rewrite cfunElock !cfun1E Gx.
by case: subsetP => [sGD | _]; rewrite ?group1 // mem_morphim ?sGD.
Qed.
Fact cfMorph_is_linear : linear cfMorph.
Proof.
by move=> a phi psi; apply/cfunP=> x; rewrite !cfunElock mulrnAr -mulrnDl.
Qed.
HB.instance Definition _ := GRing.isSemilinear.Build algC _ _ _ cfMorph
(GRing.semilinear_linear cfMorph_is_linear).
Fact cfMorph_is_monoid_morphism : monoid_morphism cfMorph.
Proof.
split=> [|phi psi]; [exact: cfMorph_cfun1 | apply/cfunP=> x].
by rewrite !cfunElock mulrnAr mulrnAl -mulrnA mulnb andbb.
Qed.
HB.instance Definition _ := GRing.isMonoidMorphism.Build _ _ cfMorph
cfMorph_is_monoid_morphism.
Hypothesis sGD : G \subset D.
Lemma cfMorph_inj : injective cfMorph.
Proof.
move=> phi1 phi2 eq_phi; apply/cfun_inP=> _ /morphimP[x Dx Gx ->].
by rewrite -!cfMorphE // eq_phi.
Qed.
Lemma cfMorph_eq1 phi : (cfMorph phi == 1) = (phi == 1).
Proof. exact/rmorph_eq1/cfMorph_inj. Qed.
Lemma cfker_morph phi : cfker (cfMorph phi) = G :&: f @*^-1 (cfker phi).
Proof.
apply/setP=> x /[!inE]; apply: andb_id2l => Gx.
have Dx := subsetP sGD x Gx; rewrite Dx mem_morphim //=.
apply/forallP/forallP=> Kx y.
have [{y} /morphimP[y Dy Gy ->] | fG'y] := boolP (y \in f @* G).
by rewrite -morphM // -!(cfMorphE phi) ?groupM.
by rewrite !cfun0 ?groupMl // mem_morphim.
have [Gy | G'y] := boolP (y \in G); last by rewrite !cfun0 ?groupMl.
by rewrite !cfMorphE ?groupM ?morphM // (subsetP sGD).
Qed.
Lemma cfker_morph_im phi : f @* cfker (cfMorph phi) = cfker phi.
Proof. by rewrite cfker_morph // morphim_setIpre (setIidPr (cfker_sub _)). Qed.
Lemma sub_cfker_morph phi (A : {set aT}) :
(A \subset cfker (cfMorph phi)) = (A \subset G) && (f @* A \subset cfker phi).
Proof.
rewrite cfker_morph // subsetI; apply: andb_id2l => sAG.
by rewrite sub_morphim_pre // (subset_trans sAG).
Qed.
Lemma sub_morphim_cfker phi (A : {set aT}) :
A \subset G -> (f @* A \subset cfker phi) = (A \subset cfker (cfMorph phi)).
Proof. by move=> sAG; rewrite sub_cfker_morph ?sAG. Qed.
Lemma cforder_morph phi : #[cfMorph phi]%CF = #[phi]%CF.
Proof. exact/cforder_inj_rmorph/cfMorph_inj. Qed.
End Main.
Lemma cfResMorph (G H : {group aT}) (phi : 'CF(f @* G)) :
H \subset G -> G \subset D -> 'Res (cfMorph phi) = cfMorph ('Res[f @* H] phi).
Proof.
move=> sHG sGD; have sHD := subset_trans sHG sGD.
apply/cfun_inP=> x Hx; have [Gx Dx] := (subsetP sHG x Hx, subsetP sHD x Hx).
by rewrite !(cfMorphE, cfResE) ?morphimS ?mem_morphim //.
Qed.
End Morphim.
Prenex Implicits cfMorph.
Section Isomorphism.
Variables (aT rT : finGroupType) (G : {group aT}) (f : {morphism G >-> rT}).
Variable R : {group rT}.
Hypothesis isoGR : isom G R f.
Let defR := isom_im isoGR.
Local Notation G1 := (isom_inv isoGR @* R).
Let defG : G1 = G := isom_im (isom_sym isoGR).
Fact cfIsom_key : unit. Proof. by []. Qed.
Definition cfIsom :=
locked_with cfIsom_key (cfMorph \o 'Res[G1] : 'CF(G) -> 'CF(R)).
Canonical cfIsom_unlockable := [unlockable of cfIsom].
Lemma cfIsomE phi (x : aT : finType) : x \in G -> cfIsom phi (f x) = phi x.
Proof.
move=> Gx; rewrite unlock cfMorphE //= /restrm ?defG ?cfRes_id ?invmE //.
by rewrite -defR mem_morphim.
Qed.
Lemma cfIsom1 phi : cfIsom phi 1%g = phi 1%g.
Proof. by rewrite -(morph1 f) cfIsomE. Qed.
Lemma cfIsom_is_zmod_morphism : zmod_morphism cfIsom.
Proof. rewrite unlock; exact: raddfB. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfIsom_is_zmod_morphism` instead")]
Definition cfIsom_is_additive := cfIsom_is_zmod_morphism.
Lemma cfIsom_is_monoid_morphism : monoid_morphism cfIsom.
Proof. rewrite unlock; exact: (rmorph1 _, rmorphM _). Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfIsom_is_monoid_morphism` instead")]
Definition cfIsom_is_multiplicative :=
(fun g => (g.2,g.1)) cfIsom_is_monoid_morphism.
Lemma cfIsom_is_scalable : scalable cfIsom.
Proof. rewrite unlock; exact: linearZ_LR. Qed.
HB.instance Definition _ := GRing.isZmodMorphism.Build _ _ cfIsom cfIsom_is_zmod_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build _ _ cfIsom
cfIsom_is_monoid_morphism.
HB.instance Definition _ := GRing.isScalable.Build _ _ _ _ cfIsom
cfIsom_is_scalable.
Lemma cfIsom_cfun1 : cfIsom 1 = 1. Proof. exact: rmorph1. Qed.
Lemma cfker_isom phi : cfker (cfIsom phi) = f @* cfker phi.
Proof.
rewrite unlock cfker_morph // defG cfRes_id morphpre_restrm morphpre_invm.
by rewrite -defR !morphimIim.
Qed.
End Isomorphism.
Prenex Implicits cfIsom.
Section InvMorphism.
Variables (aT rT : finGroupType) (G : {group aT}) (f : {morphism G >-> rT}).
Variable R : {group rT}.
Hypothesis isoGR : isom G R f.
Lemma cfIsomK : cancel (cfIsom isoGR) (cfIsom (isom_sym isoGR)).
Proof.
move=> phi; apply/cfun_inP=> x Gx; rewrite -{1}(invmE (isom_inj isoGR) Gx).
by rewrite !cfIsomE // -(isom_im isoGR) mem_morphim.
Qed.
Lemma cfIsomKV : cancel (cfIsom (isom_sym isoGR)) (cfIsom isoGR).
Proof.
move=> phi; apply/cfun_inP=> y Ry; pose injGR := isom_inj isoGR.
rewrite -{1}[y](invmK injGR) ?(isom_im isoGR) //.
suffices /morphpreP[fGy Gf'y]: y \in invm injGR @*^-1 G by rewrite !cfIsomE.
by rewrite morphpre_invm (isom_im isoGR).
Qed.
Lemma cfIsom_inj : injective (cfIsom isoGR). Proof. exact: can_inj cfIsomK. Qed.
Lemma cfIsom_eq1 phi : (cfIsom isoGR phi == 1) = (phi == 1).
Proof. exact/rmorph_eq1/cfIsom_inj. Qed.
Lemma cforder_isom phi : #[cfIsom isoGR phi]%CF = #[phi]%CF.
Proof. exact: cforder_inj_rmorph cfIsom_inj. Qed.
End InvMorphism.
Arguments cfIsom_inj {aT rT G f R} isoGR [phi1 phi2] : rename.
Section Coset.
Variables (gT : finGroupType) (G : {group gT}) (B : {set gT}).
Implicit Type rT : finGroupType.
Local Notation H := <<B>>%g.
Definition cfMod : 'CF(G / B) -> 'CF(G) := cfMorph.
Definition ffun_Quo (phi : 'CF(G)) :=
[ffun Hx : coset_of B =>
phi (if B \subset cfker phi then repr Hx else 1%g) *+ (Hx \in G / B)%g].
Fact cfQuo_subproof phi : is_class_fun <<G / B>> (ffun_Quo phi).
Proof.
rewrite genGid; apply: intro_class_fun => [|Hx /negPf-> //].
move=> _ _ /morphimP[x Nx Gx ->] /morphimP[z Nz Gz ->].
rewrite -morphJ ?mem_morphim ?val_coset_prim ?groupJ //= -gen_subG.
case: subsetP => // KphiH; do 2!case: repr_rcosetP => _ /KphiH/cfkerMl->.
by rewrite cfunJ.
Qed.
Definition cfQuo phi := Cfun 1 (cfQuo_subproof phi).
Local Notation "phi / 'B'" := (cfQuo phi)
(at level 40, left associativity) : cfun_scope.
Local Notation "phi %% 'B'" := (cfMod phi) (at level 40) : cfun_scope.
(* We specialize the cfMorph lemmas to cfMod by strengthening the domain *)
(* condition G \subset 'N(H) to H <| G; the cfMorph lemmas can be used if the *)
(* stronger results are needed. *)
Lemma cfModE phi x : B <| G -> x \in G -> (phi %% B)%CF x = phi (coset B x).
Proof. by move/normal_norm=> nBG; apply: cfMorphE. Qed.
Lemma cfMod1 phi : (phi %% B)%CF 1%g = phi 1%g. Proof. exact: cfMorph1. Qed.
HB.instance Definition _ := GRing.LRMorphism.on cfMod.
Lemma cfMod_cfun1 : (1 %% B)%CF = 1. Proof. exact: rmorph1. Qed.
Lemma cfker_mod phi : B <| G -> B \subset cfker (phi %% B).
Proof.
case/andP=> sBG nBG; rewrite cfker_morph // subsetI sBG.
apply: subset_trans _ (ker_sub_pre _ _); rewrite ker_coset_prim subsetI.
by rewrite (subset_trans sBG nBG) sub_gen.
Qed.
(* Note that cfQuo is nondegenerate even when G does not normalize B. *)
Lemma cfQuoEnorm (phi : 'CF(G)) x :
B \subset cfker phi -> x \in 'N_G(B) -> (phi / B)%CF (coset B x) = phi x.
Proof.
rewrite cfunElock -gen_subG => sHK /setIP[Gx nHx]; rewrite sHK /=.
rewrite mem_morphim // val_coset_prim //.
by case: repr_rcosetP => _ /(subsetP sHK)/cfkerMl->.
Qed.
Lemma cfQuoE (phi : 'CF(G)) x :
B <| G -> B \subset cfker phi -> x \in G -> (phi / B)%CF (coset B x) = phi x.
Proof. by case/andP=> _ nBG sBK Gx; rewrite cfQuoEnorm // (setIidPl _). Qed.
Lemma cfQuo1 (phi : 'CF(G)) : (phi / B)%CF 1%g = phi 1%g.
Proof. by rewrite cfunElock repr_coset1 group1 if_same. Qed.
Lemma cfQuoEout (phi : 'CF(G)) :
~~ (B \subset cfker phi) -> (phi / B)%CF = (phi 1%g)%:A.
Proof.
move/negPf=> not_kerB; apply/cfunP=> x; rewrite cfunE cfun1E mulr_natr.
by rewrite cfunElock not_kerB.
Qed.
(* cfQuo is only linear on the class functions that have H in their kernel. *)
Lemma cfQuo_cfun1 : (1 / B)%CF = 1.
Proof.
apply/cfun_inP=> Hx G_Hx; rewrite cfunElock !cfun1E G_Hx cfker_cfun1 -gen_subG.
have [x nHx Gx ->] := morphimP G_Hx.
case: subsetP=> [sHG | _]; last by rewrite group1.
by rewrite val_coset_prim //; case: repr_rcosetP => y /sHG/groupM->.
Qed.
(* Cancellation properties *)
Lemma cfModK : B <| G -> cancel cfMod cfQuo.
Proof.
move=> nsBG phi; apply/cfun_inP=> _ /morphimP[x Nx Gx ->] //.
by rewrite cfQuoE ?cfker_mod ?cfModE.
Qed.
Lemma cfQuoK :
B <| G -> forall phi, B \subset cfker phi -> (phi / B %% B)%CF = phi.
Proof.
by move=> nsHG phi sHK; apply/cfun_inP=> x Gx; rewrite cfModE ?cfQuoE.
Qed.
Lemma cfMod_eq1 psi : B <| G -> (psi %% B == 1)%CF = (psi == 1).
Proof. by move/cfModK/can_eq <-; rewrite rmorph1. Qed.
Lemma cfQuo_eq1 phi :
B <| G -> B \subset cfker phi -> (phi / B == 1)%CF = (phi == 1).
Proof. by move=> nsBG kerH; rewrite -cfMod_eq1 // cfQuoK. Qed.
End Coset.
Arguments cfQuo {gT G%_G} B%_g phi%_CF.
Arguments cfMod {gT G%_G B%_g} phi%_CF.
Notation "phi / H" := (cfQuo H phi) : cfun_scope.
Notation "phi %% H" := (@cfMod _ _ H phi) : cfun_scope.
Section MoreCoset.
Variables (gT : finGroupType) (G : {group gT}).
Implicit Types (H K : {group gT}) (phi : 'CF(G)).
Lemma cfResMod H K (psi : 'CF(G / K)) :
H \subset G -> K <| G -> ('Res (psi %% K) = 'Res[H / K] psi %% K)%CF.
Proof. by move=> sHG /andP[_]; apply: cfResMorph. Qed.
Lemma quotient_cfker_mod (A : {set gT}) K (psi : 'CF(G / K)) :
K <| G -> (cfker (psi %% K) / K)%g = cfker psi.
Proof. by case/andP=> _ /cfker_morph_im <-. Qed.
Lemma sub_cfker_mod (A : {set gT}) K (psi : 'CF(G / K)) :
K <| G -> A \subset 'N(K) ->
(A \subset cfker (psi %% K)) = (A / K \subset cfker psi)%g.
Proof.
by move=> nsKG nKA; rewrite -(quotientSGK nKA) ?quotient_cfker_mod// cfker_mod.
Qed.
Lemma cfker_quo H phi :
H <| G -> H \subset cfker (phi) -> cfker (phi / H) = (cfker phi / H)%g.
Proof.
move=> nsHG /cfQuoK {2}<- //; have [sHG nHG] := andP nsHG.
by rewrite cfker_morph 1?quotientGI // cosetpreK (setIidPr _) ?cfker_sub.
Qed.
Lemma cfQuoEker phi x :
x \in G -> (phi / cfker phi)%CF (coset (cfker phi) x) = phi x.
Proof. by move/cfQuoE->; rewrite ?cfker_normal. Qed.
Lemma cfaithful_quo phi : cfaithful (phi / cfker phi).
Proof. by rewrite cfaithfulE cfker_quo ?cfker_normal ?trivg_quotient. Qed.
(* Note that there is no requirement that K be normal in H or G. *)
Lemma cfResQuo H K phi :
K \subset cfker phi -> K \subset H -> H \subset G ->
('Res[H / K] (phi / K) = 'Res[H] phi / K)%CF.
Proof.
move=> kerK sKH sHG; apply/cfun_inP=> xb Hxb; rewrite cfResE ?quotientS //.
have{xb Hxb} [x nKx Hx ->] := morphimP Hxb.
by rewrite !cfQuoEnorm ?cfResE// 1?inE ?Hx ?(subsetP sHG)// sub_cfker_Res.
Qed.
Lemma cfQuoInorm K phi :
K \subset cfker phi -> (phi / K)%CF = 'Res ('Res['N_G(K)] phi / K)%CF.
Proof.
move=> kerK; rewrite -cfResQuo ?subsetIl ?quotientInorm ?cfRes_id //.
by rewrite subsetI normG (subset_trans kerK) ?cfker_sub.
Qed.
Lemma cforder_mod H (psi : 'CF(G / H)) : H <| G -> #[psi %% H]%CF = #[psi]%CF.
Proof. by move/cfModK/can_inj/cforder_inj_rmorph->. Qed.
Lemma cforder_quo H phi :
H <| G -> H \subset cfker phi -> #[phi / H]%CF = #[phi]%CF.
Proof. by move=> nsHG kerHphi; rewrite -cforder_mod ?cfQuoK. Qed.
End MoreCoset.
Section Product.
Variable (gT : finGroupType) (G : {group gT}).
Lemma cfunM_onI A B phi psi :
phi \in 'CF(G, A) -> psi \in 'CF(G, B) -> phi * psi \in 'CF(G, A :&: B).
Proof.
rewrite !cfun_onE => Aphi Bpsi; apply/subsetP=> x; rewrite !inE cfunE mulf_eq0.
by case/norP=> /(subsetP Aphi)-> /(subsetP Bpsi).
Qed.
Lemma cfunM_on A phi psi :
phi \in 'CF(G, A) -> psi \in 'CF(G, A) -> phi * psi \in 'CF(G, A).
Proof. by move=> Aphi Bpsi; rewrite -[A]setIid cfunM_onI. Qed.
End Product.
Section SDproduct.
Variables (gT : finGroupType) (G K H : {group gT}).
Hypothesis defG : K ><| H = G.
Fact cfSdprodKey : unit. Proof. by []. Qed.
Definition cfSdprod :=
locked_with cfSdprodKey
(cfMorph \o cfIsom (tagged (sdprod_isom defG)) : 'CF(H) -> 'CF(G)).
Canonical cfSdprod_unlockable := [unlockable of cfSdprod].
Lemma cfSdprod_is_zmod_morphism : zmod_morphism cfSdprod.
Proof. rewrite unlock; exact: raddfB. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfSdprod_is_zmod_morphism` instead")]
Definition cfSdprod_is_additive := cfSdprod_is_zmod_morphism.
Lemma cfSdprod_is_monoid_morphism : monoid_morphism cfSdprod.
Proof. rewrite unlock; exact: (rmorph1 _, rmorphM _). Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `cfSdprod_is_monoid_morphism` instead")]
Definition cfSdprod_is_multiplicative :=
(fun g => (g.2,g.1)) cfSdprod_is_monoid_morphism.
Lemma cfSdprod_is_scalable : scalable cfSdprod.
Proof. rewrite unlock; exact: linearZ_LR. Qed.
HB.instance Definition _ := GRing.isZmodMorphism.Build _ _ cfSdprod cfSdprod_is_zmod_morphism.
HB.instance Definition _ := GRing.isMonoidMorphism.Build _ _ cfSdprod
cfSdprod_is_monoid_morphism.
HB.instance Definition _ := GRing.isScalable.Build _ _ _ _ cfSdprod
cfSdprod_is_scalable.
Lemma cfSdprod1 phi : cfSdprod phi 1%g = phi 1%g.
Proof. by rewrite unlock /= cfMorph1 cfIsom1. Qed.
Let nsKG : K <| G. Proof. by have [] := sdprod_context defG. Qed.
Let sHG : H \subset G. Proof. by have [] := sdprod_context defG. Qed.
Let sKG : K \subset G. Proof. by have [] := andP nsKG. Qed.
Lemma cfker_sdprod phi : K \subset cfker (cfSdprod phi).
Proof. by rewrite unlock_with cfker_mod. Qed.
Lemma cfSdprodEr phi : {in H, cfSdprod phi =1 phi}.
Proof. by move=> y Hy; rewrite unlock cfModE ?cfIsomE ?(subsetP sHG). Qed.
Lemma cfSdprodE phi : {in K & H, forall x y, cfSdprod phi (x * y)%g = phi y}.
Proof.
by move=> x y Kx Hy; rewrite /= cfkerMl ?(subsetP (cfker_sdprod _)) ?cfSdprodEr.
Qed.
Lemma cfSdprodK : cancel cfSdprod 'Res[H].
Proof. by move=> phi; apply/cfun_inP=> x Hx; rewrite cfResE ?cfSdprodEr. Qed.
Lemma cfSdprod_inj : injective cfSdprod. Proof. exact: can_inj cfSdprodK. Qed.
Lemma cfSdprod_eq1 phi : (cfSdprod phi == 1) = (phi == 1).
Proof. exact: rmorph_eq1 cfSdprod_inj. Qed.
Lemma cfRes_sdprodK phi : K \subset cfker phi -> cfSdprod ('Res[H] phi) = phi.
Proof.
move=> kerK; apply/cfun_inP=> _ /(mem_sdprod defG)[x [y [Kx Hy -> _]]].
by rewrite cfSdprodE // cfResE // cfkerMl ?(subsetP kerK).
Qed.
Lemma sdprod_cfker phi : K ><| cfker phi = cfker (cfSdprod phi).
Proof.
have [skerH [_ _ nKH tiKH]] := (cfker_sub phi, sdprodP defG).
rewrite unlock cfker_morph ?normal_norm // cfker_isom restrmEsub //=.
rewrite -(sdprod_modl defG) ?sub_cosetpre //=; congr (_ ><| _).
by rewrite quotientK ?(subset_trans skerH) // -group_modr //= setIC tiKH mul1g.
Qed.
Lemma cforder_sdprod phi : #[cfSdprod phi]%CF = #[phi]%CF.
Proof. exact: cforder_inj_rmorph cfSdprod_inj. Qed.
End SDproduct.
Section DProduct.
Variables (gT : finGroupType) (G K H : {group gT}).
Hypothesis KxH : K \x H = G.
Lemma reindex_dprod R idx (op : Monoid.com_law idx) (F : gT -> R) :
\big[op/idx]_(g in G) F g =
\big[op/idx]_(k in K) \big[op/idx]_(h in H) F (k * h)%g.
Proof.
have /mulgmP/misomP[fM /isomP[injf im_f]] := KxH.
rewrite pair_big_dep -im_f morphimEdom big_imset; last exact/injmP.
by apply: eq_big => [][x y]; rewrite ?inE.
Qed.
Definition cfDprodr := cfSdprod (dprodWsd KxH).
Definition cfDprodl := cfSdprod (dprodWsdC KxH).
Definition cfDprod phi psi := cfDprodl phi * cfDprodr psi.
HB.instance Definition _ := GRing.LRMorphism.on cfDprodl.
HB.instance Definition _ := GRing.LRMorphism.on cfDprodr.
Lemma cfDprodl1 phi : cfDprodl phi 1%g = phi 1%g. Proof. exact: cfSdprod1. Qed.
Lemma cfDprodr1 psi : cfDprodr psi 1%g = psi 1%g. Proof. exact: cfSdprod1. Qed.
Lemma cfDprod1 phi psi : cfDprod phi psi 1%g = phi 1%g * psi 1%g.
Proof. by rewrite cfunE /= !cfSdprod1. Qed.
Lemma cfDprodl_eq1 phi : (cfDprodl phi == 1) = (phi == 1).
Proof. exact: cfSdprod_eq1. Qed.
Lemma cfDprodr_eq1 psi : (cfDprodr psi == 1) = (psi == 1).
Proof. exact: cfSdprod_eq1. Qed.
Lemma cfDprod_cfun1r phi : cfDprod phi 1 = cfDprodl phi.
Proof. by rewrite /cfDprod rmorph1 mulr1. Qed.
Lemma cfDprod_cfun1l psi : cfDprod 1 psi = cfDprodr psi.
Proof. by rewrite /cfDprod rmorph1 mul1r. Qed.
Lemma cfDprod_cfun1 : cfDprod 1 1 = 1.
Proof. by rewrite cfDprod_cfun1l rmorph1. Qed.
Lemma cfDprod_split phi psi : cfDprod phi psi = cfDprod phi 1 * cfDprod 1 psi.
Proof. by rewrite cfDprod_cfun1l cfDprod_cfun1r. Qed.
Let nsKG : K <| G. Proof. by have [] := dprod_normal2 KxH. Qed.
Let nsHG : H <| G. Proof. by have [] := dprod_normal2 KxH. Qed.
Let cKH : H \subset 'C(K). Proof. by have [] := dprodP KxH. Qed.
Let sKG := normal_sub nsKG.
Let sHG := normal_sub nsHG.
Lemma cfDprodlK : cancel cfDprodl 'Res[K]. Proof. exact: cfSdprodK. Qed.
Lemma cfDprodrK : cancel cfDprodr 'Res[H]. Proof. exact: cfSdprodK. Qed.
Lemma cfker_dprodl phi : cfker phi \x H = cfker (cfDprodl phi).
Proof.
by rewrite dprodC -sdprod_cfker dprodEsd // centsC (centsS (cfker_sub _)).
Qed.
Lemma cfker_dprodr psi : K \x cfker psi = cfker (cfDprodr psi).
Proof. by rewrite -sdprod_cfker dprodEsd // (subset_trans (cfker_sub _)). Qed.
Lemma cfDprodEl phi : {in K & H, forall k h, cfDprodl phi (k * h)%g = phi k}.
Proof. by move=> k h Kk Hh /=; rewrite -(centsP cKH) // cfSdprodE. Qed.
Lemma cfDprodEr psi : {in K & H, forall k h, cfDprodr psi (k * h)%g = psi h}.
Proof. exact: cfSdprodE. Qed.
Lemma cfDprodE phi psi :
{in K & H, forall h k, cfDprod phi psi (h * k)%g = phi h * psi k}.
Proof. by move=> k h Kk Hh /=; rewrite cfunE cfDprodEl ?cfDprodEr. Qed.
Lemma cfDprod_Resl phi psi : 'Res[K] (cfDprod phi psi) = psi 1%g *: phi.
Proof.
by apply/cfun_inP=> x Kx; rewrite cfunE cfResE // -{1}[x]mulg1 mulrC cfDprodE.
Qed.
Lemma cfDprod_Resr phi psi : 'Res[H] (cfDprod phi psi) = phi 1%g *: psi.
Proof.
by apply/cfun_inP=> y Hy; rewrite cfunE cfResE // -{1}[y]mul1g cfDprodE.
Qed.
Lemma cfDprodKl (psi : 'CF(H)) : psi 1%g = 1 -> cancel (cfDprod^~ psi) 'Res.
Proof. by move=> psi1 phi; rewrite cfDprod_Resl psi1 scale1r. Qed.
Lemma cfDprodKr (phi : 'CF(K)) : phi 1%g = 1 -> cancel (cfDprod phi) 'Res.
Proof. by move=> phi1 psi; rewrite cfDprod_Resr phi1 scale1r. Qed.
(* Note that equality holds here iff either cfker phi = K and cfker psi = H, *)
(* or else phi != 0, psi != 0 and coprime #|K : cfker phi| #|H : cfker phi|. *)
Lemma cfker_dprod phi psi :
cfker phi <*> cfker psi \subset cfker (cfDprod phi psi).
Proof.
rewrite -genM_join gen_subG; apply/subsetP=> _ /mulsgP[x y kKx kHy ->] /=.
have [[Kx _] [Hy _]] := (setIdP kKx, setIdP kHy).
have Gxy: (x * y)%g \in G by rewrite -(dprodW KxH) mem_mulg.
rewrite inE Gxy; apply/forallP=> g.
have [Gg | G'g] := boolP (g \in G); last by rewrite !cfun0 1?groupMl.
have{g Gg} [k [h [Kk Hh -> _]]] := mem_dprod KxH Gg.
rewrite mulgA -(mulgA x) (centsP cKH y) // mulgA -mulgA !cfDprodE ?groupM //.
by rewrite !cfkerMl.
Qed.
Lemma cfdot_dprod phi1 phi2 psi1 psi2 :
'[cfDprod phi1 psi1, cfDprod phi2 psi2] = '[phi1, phi2] * '[psi1, psi2].
Proof.
rewrite !cfdotE mulrCA -mulrA mulrCA mulrA -invfM -natrM (dprod_card KxH).
congr (_ * _); rewrite big_distrl reindex_dprod /=; apply: eq_bigr => k Kk.
rewrite big_distrr; apply: eq_bigr => h Hh /=.
by rewrite mulrCA -mulrA -rmorphM mulrCA mulrA !cfDprodE.
Qed.
Lemma cfDprodl_iso : isometry cfDprodl.
Proof.
by move=> phi1 phi2; rewrite -!cfDprod_cfun1r cfdot_dprod cfnorm1 mulr1.
Qed.
Lemma cfDprodr_iso : isometry cfDprodr.
Proof.
by move=> psi1 psi2; rewrite -!cfDprod_cfun1l cfdot_dprod cfnorm1 mul1r.
Qed.
Lemma cforder_dprodl phi : #[cfDprodl phi]%CF = #[phi]%CF.
Proof. exact: cforder_sdprod. Qed.
Lemma cforder_dprodr psi : #[cfDprodr psi]%CF = #[psi]%CF.
Proof. exact: cforder_sdprod. Qed.
End DProduct.
Lemma cfDprodC (gT : finGroupType) (G K H : {group gT})
(KxH : K \x H = G) (HxK : H \x K = G) chi psi :
cfDprod KxH chi psi = cfDprod HxK psi chi.
Proof.
rewrite /cfDprod mulrC.
by congr (_ * _); congr (cfSdprod _ _); apply: eq_irrelevance.
Qed.
Section Bigdproduct.
Variables (gT : finGroupType) (I : finType) (P : pred I).
Variables (A : I -> {group gT}) (G : {group gT}).
Hypothesis defG : \big[dprod/1%g]_(i | P i) A i = G.
Let sAG i : P i -> A i \subset G.
Proof. by move=> Pi; rewrite -(bigdprodWY defG) (bigD1 i) ?joing_subl. Qed.
Fact cfBigdprodi_subproof i :
gval (if P i then A i else 1%G) \x <<\bigcup_(j | P j && (j != i)) A j>> = G.
Proof.
have:= defG; rewrite fun_if big_mkcond (bigD1 i) // -big_mkcondl /= => defGi.
by have [[_ Gi' _ defGi']] := dprodP defGi; rewrite (bigdprodWY defGi') -defGi'.
Qed.
Definition cfBigdprodi i := cfDprodl (cfBigdprodi_subproof i) \o 'Res[_, A i].
HB.instance Definition _ i := GRing.LRMorphism.on (@cfBigdprodi i).
Lemma cfBigdprodi1 i (phi : 'CF(A i)) : cfBigdprodi phi 1%g = phi 1%g.
Proof. by rewrite cfDprodl1 cfRes1. Qed.
Lemma cfBigdprodi_eq1 i (phi : 'CF(A i)) :
P i -> (cfBigdprodi phi == 1) = (phi == 1).
Proof. by move=> Pi; rewrite cfSdprod_eq1 Pi cfRes_id. Qed.
Lemma cfBigdprodiK i : P i -> cancel (@cfBigdprodi i) 'Res[A i].
Proof.
move=> Pi phi; have:= cfDprodlK (cfBigdprodi_subproof i) ('Res phi).
by rewrite -[cfDprodl _ _]/(cfBigdprodi phi) Pi cfRes_id.
Qed.
Lemma cfBigdprodi_inj i : P i -> injective (@cfBigdprodi i).
Proof. by move/cfBigdprodiK; apply: can_inj. Qed.
Lemma cfBigdprodEi i (phi : 'CF(A i)) x :
P i -> (forall j, P j -> x j \in A j) ->
cfBigdprodi phi (\prod_(j | P j) x j)%g = phi (x i).
Proof.
have [r big_r [Ur mem_r] _] := big_enumP P => Pi AxP.
have:= bigdprodWcp defG; rewrite -!big_r => defGr.
have{AxP} [r_i Axr]: i \in r /\ {in r, forall j, x j \in A j}.
by split=> [|j]; rewrite mem_r // => /AxP.
rewrite (perm_bigcprod defGr Axr (perm_to_rem r_i)) big_cons.
rewrite cfDprodEl ?Pi ?cfRes_id ?Axr // big_seq group_prod // => j.
rewrite mem_rem_uniq // => /andP[i'j /= r_j].
by apply/mem_gen/bigcupP; exists j; [rewrite -mem_r r_j | apply: Axr].
Qed.
Lemma cfBigdprodi_iso i : P i -> isometry (@cfBigdprodi i).
Proof. by move=> Pi phi psi; rewrite cfDprodl_iso Pi !cfRes_id. Qed.
Definition cfBigdprod (phi : forall i, 'CF(A i)) :=
\prod_(i | P i) cfBigdprodi (phi i).
Lemma cfBigdprodE phi x :
(forall i, P i -> x i \in A i) ->
cfBigdprod phi (\prod_(i | P i) x i)%g = \prod_(i | P i) phi i (x i).
Proof.
move=> Ax; rewrite prod_cfunE; last by rewrite -(bigdprodW defG) mem_prodg.
by apply: eq_bigr => i Pi; rewrite cfBigdprodEi.
Qed.
Lemma cfBigdprod1 phi : cfBigdprod phi 1%g = \prod_(i | P i) phi i 1%g.
Proof. by rewrite prod_cfunE //; apply/eq_bigr=> i _; apply: cfBigdprodi1. Qed.
Lemma cfBigdprodK phi (Phi := cfBigdprod phi) i (a := phi i 1%g / Phi 1%g) :
Phi 1%g != 0 -> P i -> a != 0 /\ a *: 'Res[A i] Phi = phi i.
Proof.
move=> nzPhi Pi; split.
rewrite mulf_neq0 ?invr_eq0 // (contraNneq _ nzPhi) // => phi_i0.
by rewrite cfBigdprod1 (bigD1 i) //= phi_i0 mul0r.
apply/cfun_inP=> x Aix; rewrite cfunE cfResE ?sAG // mulrAC.
have {1}->: x = (\prod_(j | P j) (if j == i then x else 1))%g.
rewrite -big_mkcondr (big_pred1 i) ?eqxx // => j /=.
by apply: andb_idl => /eqP->.
rewrite cfBigdprodE => [|j _]; last by case: eqP => // ->.
apply: canLR (mulfK nzPhi) _; rewrite cfBigdprod1 !(bigD1 i Pi) /= eqxx.
by rewrite mulrCA !mulrA; congr (_ * _); apply: eq_bigr => j /andP[_ /negPf->].
Qed.
Lemma cfdot_bigdprod phi psi :
'[cfBigdprod phi, cfBigdprod psi] = \prod_(i | P i) '[phi i, psi i].
Proof.
apply: canLR (mulKf (neq0CG G)) _; rewrite -(bigdprod_card defG).
rewrite (big_morph _ (@natrM _) (erefl _)) -big_split /=.
rewrite (eq_bigr _ (fun i _ => mulVKf (neq0CG _) _)) (big_distr_big_dep 1%g) /=.
set F := pfamily _ _ _; pose h (f : {ffun I -> gT}) := (\prod_(i | P i) f i)%g.
pose is_hK x f := forall f1, (f1 \in F) && (h f1 == x) = (f == f1).
have /fin_all_exists[h1 Dh1] x: exists f, x \in G -> is_hK x f.
case Gx: (x \in G); last by exists [ffun _ => x].
have [f [Af fK Uf]] := mem_bigdprod defG Gx.
exists [ffun i => if P i then f i else 1%g] => _ f1.
apply/andP/eqP=> [[/pfamilyP[Pf1 Af1] /eqP Dx] | <-].
by apply/ffunP=> i; rewrite ffunE; case: ifPn => [/Uf-> | /(supportP Pf1)].
split; last by rewrite fK; apply/eqP/eq_bigr=> i Pi; rewrite ffunE Pi.
by apply/familyP=> i; rewrite ffunE !unfold_in; case: ifP => //= /Af.
rewrite (reindex_onto h h1) /= => [|x /Dh1/(_ (h1 x))]; last first.
by rewrite eqxx => /andP[_ /eqP].
apply/eq_big => [f | f /andP[/Dh1<- /andP[/pfamilyP[_ Af] _]]]; last first.
by rewrite !cfBigdprodE // rmorph_prod -big_split /=.
apply/idP/idP=> [/andP[/Dh1<-] | Ff]; first by rewrite eqxx andbT.
have /pfamilyP[_ Af] := Ff; suffices Ghf: h f \in G by rewrite -Dh1 ?Ghf ?Ff /=.
by apply/group_prod=> i Pi; rewrite (subsetP (sAG Pi)) ?Af.
Qed.
End Bigdproduct.
Section MorphIsometry.
Variable gT : finGroupType.
Implicit Types (D G H K : {group gT}) (aT rT : finGroupType).
Lemma cfMorph_iso aT rT (G D : {group aT}) (f : {morphism D >-> rT}) :
G \subset D -> isometry (cfMorph : 'CF(f @* G) -> 'CF(G)).
Proof.
move=> sGD phi psi; rewrite !cfdotE card_morphim (setIidPr sGD).
rewrite -(LagrangeI G ('ker f)) /= mulnC natrM invfM -mulrA.
congr (_ * _); apply: (canLR (mulKf (neq0CG _))).
rewrite mulr_sumr (partition_big_imset f) /= -morphimEsub //.
apply: eq_bigr => _ /morphimP[x Dx Gx ->].
rewrite -(card_rcoset _ x) mulr_natl -sumr_const.
apply/eq_big => [y | y /andP[Gy /eqP <-]]; last by rewrite !cfMorphE.
rewrite mem_rcoset inE groupMr ?groupV // -mem_rcoset.
by apply: andb_id2l => /(subsetP sGD) Dy; apply: sameP eqP (rcoset_kerP f _ _).
Qed.
Lemma cfIsom_iso rT G (R : {group rT}) (f : {morphism G >-> rT}) :
forall isoG : isom G R f, isometry (cfIsom isoG).
Proof.
move=> isoG phi psi; rewrite unlock cfMorph_iso //; set G1 := _ @* R.
by rewrite -(isom_im (isom_sym isoG)) -/G1 in phi psi *; rewrite !cfRes_id.
Qed.
Lemma cfMod_iso H G : H <| G -> isometry (@cfMod _ G H).
Proof. by case/andP=> _; apply: cfMorph_iso. Qed.
Lemma cfQuo_iso H G :
H <| G -> {in [pred phi | H \subset cfker phi] &, isometry (@cfQuo _ G H)}.
Proof.
by move=> nsHG phi psi sHkphi sHkpsi; rewrite -(cfMod_iso nsHG) !cfQuoK.
Qed.
Lemma cfnorm_quo H G phi :
H <| G -> H \subset cfker phi -> '[phi / H] = '[phi]_G.
Proof. by move=> nsHG sHker; apply: cfQuo_iso. Qed.
Lemma cfSdprod_iso K H G (defG : K ><| H = G) : isometry (cfSdprod defG).
Proof.
move=> phi psi; have [/andP[_ nKG] _ _ _ _] := sdprod_context defG.
by rewrite [cfSdprod _]locked_withE cfMorph_iso ?cfIsom_iso.
Qed.
End MorphIsometry.
Section Induced.
Variable gT : finGroupType.
Section Def.
Variables B A : {set gT}.
Local Notation G := <<B>>.
Local Notation H := <<A>>.
(* The default value for the ~~ (H \subset G) case matches the one for cfRes *)
(* so that Frobenius reciprocity holds even in this degenerate case. *)
Definition ffun_cfInd (phi : 'CF(A)) :=
[ffun x => if H \subset G then #|A|%:R^-1 * (\sum_(y in G) phi (x ^ y))
else #|G|%:R * '[phi, 1] *+ (x == 1%g)].
Fact cfInd_subproof phi : is_class_fun G (ffun_cfInd phi).
Proof.
apply: intro_class_fun => [x y Gx Gy | x H'x]; last first.
case: subsetP => [sHG | _]; last by rewrite (negPf (group1_contra H'x)).
rewrite big1 ?mulr0 // => y Gy; rewrite cfun0gen ?(contra _ H'x) //= => /sHG.
by rewrite memJ_norm ?(subsetP (normG _)).
rewrite conjg_eq1 (reindex_inj (mulgI y^-1)%g); congr (if _ then _ * _ else _).
by apply: eq_big => [z | z Gz]; rewrite ?groupMl ?groupV // -conjgM mulKVg.
Qed.
Definition cfInd phi := Cfun 1 (cfInd_subproof phi).
Lemma cfInd_is_linear : linear cfInd.
Proof.
move=> c phi psi; apply/cfunP=> x; rewrite !cfunElock; case: ifP => _.
rewrite mulrCA -mulrDr [c * _]mulr_sumr -big_split /=.
by congr (_ * _); apply: eq_bigr => y _; rewrite !cfunE.
rewrite mulrnAr -mulrnDl !(mulrCA c) -!mulrDr [c * _]mulr_sumr -big_split /=.
by congr (_ * (_ * _) *+ _); apply: eq_bigr => y; rewrite !cfunE mulrA mulrDl.
Qed.
HB.instance Definition _ := GRing.isSemilinear.Build algC _ _ _ cfInd
(GRing.semilinear_linear cfInd_is_linear).
End Def.
Local Notation "''Ind[' B , A ]" := (@cfInd B A) : ring_scope.
Local Notation "''Ind[' B ]" := 'Ind[B, _] : ring_scope.
Lemma cfIndE (G H : {group gT}) phi x :
H \subset G -> 'Ind[G, H] phi x = #|H|%:R^-1 * (\sum_(y in G) phi (x ^ y)).
Proof. by rewrite cfunElock !genGid => ->. Qed.
Variables G K H : {group gT}.
Implicit Types (phi : 'CF(H)) (psi : 'CF(G)).
Lemma cfIndEout phi :
~~ (H \subset G) -> 'Ind[G] phi = (#|G|%:R * '[phi, 1]) *: '1_1%G.
Proof.
move/negPf=> not_sHG; apply/cfunP=> x; rewrite cfunE cfuniE ?normal1 // inE.
by rewrite mulr_natr cfunElock !genGid not_sHG.
Qed.
Lemma cfIndEsdprod (phi : 'CF(K)) x :
K ><| H = G -> 'Ind[G] phi x = \sum_(w in H) phi (x ^ w)%g.
Proof.
move=> defG; have [/andP[sKG _] _ mulKH nKH _] := sdprod_context defG.
rewrite cfIndE //; apply: canLR (mulKf (neq0CG _)) _; rewrite -mulKH mulr_sumr.
rewrite (set_partition_big _ (rcosets_partition_mul H K)) ?big_imset /=.
apply: eq_bigr => y Hy; rewrite rcosetE norm_rlcoset ?(subsetP nKH) //.
rewrite -lcosetE mulr_natl big_imset /=; last exact: in2W (mulgI _).
by rewrite -sumr_const; apply: eq_bigr => z Kz; rewrite conjgM cfunJ.
have [{}nKH /isomP[injf _]] := sdprod_isom defG.
apply: can_in_inj (fun Ky => invm injf (coset K (repr Ky))) _ => y Hy.
by rewrite rcosetE -val_coset ?(subsetP nKH) // coset_reprK invmE.
Qed.
Lemma cfInd_on A phi :
H \subset G -> phi \in 'CF(H, A) -> 'Ind[G] phi \in 'CF(G, class_support A G).
Proof.
move=> sHG Af; apply/cfun_onP=> g AG'g; rewrite cfIndE ?big1 ?mulr0 // => h Gh.
apply: (cfun_on0 Af); apply: contra AG'g => Agh.
by rewrite -[g](conjgK h) memJ_class_support // groupV.
Qed.
Lemma cfInd_id phi : 'Ind[H] phi = phi.
Proof.
apply/cfun_inP=> x Hx; rewrite cfIndE // (eq_bigr _ (cfunJ phi x)) sumr_const.
by rewrite -[phi x *+ _]mulr_natl mulKf ?neq0CG.
Qed.
Lemma cfInd_normal phi : H <| G -> 'Ind[G] phi \in 'CF(G, H).
Proof.
case/andP=> sHG nHG; apply: (cfun_onS (class_support_sub_norm (subxx _) nHG)).
by rewrite cfInd_on ?cfun_onG.
Qed.
Lemma cfInd1 phi : H \subset G -> 'Ind[G] phi 1%g = #|G : H|%:R * phi 1%g.
Proof.
move=> sHG; rewrite cfIndE // natf_indexg // -mulrA mulrCA; congr (_ * _).
by rewrite mulr_natl -sumr_const; apply: eq_bigr => x; rewrite conj1g.
Qed.
Lemma cfInd_cfun1 : H <| G -> 'Ind[G, H] 1 = #|G : H|%:R *: '1_H.
Proof.
move=> nsHG; have [sHG nHG] := andP nsHG; rewrite natf_indexg // mulrC.
apply/cfunP=> x; rewrite cfIndE ?cfunE ?cfuniE // -mulrA; congr (_ * _).
rewrite mulr_natl -sumr_const; apply: eq_bigr => y Gy.
by rewrite cfun1E -{1}(normsP nHG y Gy) memJ_conjg.
Qed.
Lemma cfnorm_Ind_cfun1 : H <| G -> '['Ind[G, H] 1] = #|G : H|%:R.
Proof.
move=> nsHG; rewrite cfInd_cfun1 // cfnormZ normr_nat cfdot_cfuni // setIid.
by rewrite expr2 {2}natf_indexg ?normal_sub // !mulrA divfK ?mulfK ?neq0CG.
Qed.
Lemma cfIndInd phi :
K \subset G -> H \subset K -> 'Ind[G] ('Ind[K] phi) = 'Ind[G] phi.
Proof.
move=> sKG sHK; apply/cfun_inP=> x Gx; rewrite !cfIndE ?(subset_trans sHK) //.
apply: canLR (mulKf (neq0CG K)) _; rewrite mulr_sumr mulr_natl.
transitivity (\sum_(y in G) \sum_(z in K) #|H|%:R^-1 * phi ((x ^ y) ^ z)).
by apply: eq_bigr => y Gy; rewrite cfIndE // -mulr_sumr.
symmetry; rewrite exchange_big /= -sumr_const; apply: eq_bigr => z Kz.
rewrite (reindex_inj (mulIg z)).
by apply: eq_big => [y | y _]; rewrite ?conjgM // groupMr // (subsetP sKG).
Qed.
(* This is Isaacs, Lemma (5.2). *)
Lemma Frobenius_reciprocity phi psi : '[phi, 'Res[H] psi] = '['Ind[G] phi, psi].
Proof.
have [sHG | not_sHG] := boolP (H \subset G); last first.
rewrite cfResEout // cfIndEout // cfdotZr cfdotZl mulrAC; congr (_ * _).
rewrite (cfdotEl _ (cfuni_on _ _)) mulVKf ?neq0CG // big_set1.
by rewrite cfuniE ?normal1 ?set11 ?mul1r.
transitivity (#|H|%:R^-1 * \sum_(x in G) phi x * (psi x)^* ).
rewrite (big_setID H) /= (setIidPr sHG) addrC big1 ?add0r; last first.
by move=> x /setDP[_ /cfun0->]; rewrite mul0r.
by congr (_ * _); apply: eq_bigr => x Hx; rewrite cfResE.
set h' := _^-1; apply: canRL (mulKf (neq0CG G)) _.
transitivity (h' * \sum_(y in G) \sum_(x in G) phi (x ^ y) * (psi (x ^ y))^* ).
rewrite mulrCA mulr_natl -sumr_const; congr (_ * _); apply: eq_bigr => y Gy.
by rewrite (reindex_acts 'J _ Gy) ?astabsJ ?normG.
rewrite exchange_big mulr_sumr; apply: eq_bigr => x _; rewrite cfIndE //=.
by rewrite -mulrA mulr_suml; congr (_ * _); apply: eq_bigr => y /(cfunJ psi)->.
Qed.
Definition cfdot_Res_r := Frobenius_reciprocity.
Lemma cfdot_Res_l psi phi : '['Res[H] psi, phi] = '[psi, 'Ind[G] phi].
Proof. by rewrite cfdotC cfdot_Res_r -cfdotC. Qed.
Lemma cfIndM phi psi: H \subset G ->
'Ind[G] (phi * ('Res[H] psi)) = 'Ind[G] phi * psi.
Proof.
move=> HsG; apply/cfun_inP=> x Gx; rewrite !cfIndE // !cfunE !cfIndE // -mulrA.
congr (_ * _); rewrite mulr_suml; apply: eq_bigr=> i iG; rewrite !cfunE.
case: (boolP (x ^ i \in H)) => xJi; last by rewrite cfun0gen ?mul0r ?genGid.
by rewrite !cfResE //; congr (_ * _); rewrite cfunJgen ?genGid.
Qed.
End Induced.
Arguments cfInd {gT} B%_g {A%_g} phi%_CF.
Notation "''Ind[' G , H ]" := (@cfInd _ G H) (only parsing) : ring_scope.
Notation "''Ind[' G ]" := 'Ind[G, _] : ring_scope.
Notation "''Ind'" := 'Ind[_] (only parsing) : ring_scope.
Section MorphInduced.
Variables (aT rT : finGroupType) (D G H : {group aT}) (R S : {group rT}).
Lemma cfIndMorph (f : {morphism D >-> rT}) (phi : 'CF(f @* H)) :
'ker f \subset H -> H \subset G -> G \subset D ->
'Ind[G] (cfMorph phi) = cfMorph ('Ind[f @* G] phi).
Proof.
move=> sKH sHG sGD; have [sHD inD] := (subset_trans sHG sGD, subsetP sGD).
apply/cfun_inP=> /= x Gx; have [Dx sKG] := (inD x Gx, subset_trans sKH sHG).
rewrite cfMorphE ?cfIndE ?morphimS // (partition_big_imset f) -morphimEsub //=.
rewrite card_morphim (setIidPr sHD) natf_indexg // invfM invrK -mulrA.
congr (_ * _); rewrite mulr_sumr; apply: eq_bigr => _ /morphimP[y Dy Gy ->].
rewrite -(card_rcoset _ y) mulr_natl -sumr_const.
apply: eq_big => [z | z /andP[Gz /eqP <-]].
have [Gz | G'z] := boolP (z \in G).
by rewrite (sameP eqP (rcoset_kerP _ _ _)) ?inD.
by case: rcosetP G'z => // [[t Kt ->]]; rewrite groupM // (subsetP sKG).
have [Dz Dxz] := (inD z Gz, inD (x ^ z) (groupJ Gx Gz)); rewrite -morphJ //.
have [Hxz | notHxz] := boolP (x ^ z \in H); first by rewrite cfMorphE.
by rewrite !cfun0 // -sub1set -morphim_set1 // morphimSGK ?sub1set.
Qed.
Variables (g : {morphism G >-> rT}) (h : {morphism H >-> rT}).
Hypotheses (isoG : isom G R g) (isoH : isom H S h) (eq_hg : {in H, h =1 g}).
Hypothesis sHG : H \subset G.
Lemma cfResIsom phi : 'Res[S] (cfIsom isoG phi) = cfIsom isoH ('Res[H] phi).
Proof.
have [[injg defR] [injh defS]] := (isomP isoG, isomP isoH).
rewrite !morphimEdom in defS defR; apply/cfun_inP=> s.
rewrite -{1}defS => /imsetP[x Hx ->] {s}; have Gx := subsetP sHG x Hx.
rewrite {1}eq_hg ?(cfResE, cfIsomE) // -defS -?eq_hg ?imset_f // -defR.
by rewrite (eq_in_imset eq_hg) imsetS.
Qed.
Lemma cfIndIsom phi : 'Ind[R] (cfIsom isoH phi) = cfIsom isoG ('Ind[G] phi).
Proof.
have [[injg defR] [_ defS]] := (isomP isoG, isomP isoH).
rewrite morphimEdom (eq_in_imset eq_hg) -morphimEsub // in defS.
apply/cfun_inP=> s; rewrite -{1}defR => /morphimP[x _ Gx ->]{s}.
rewrite cfIsomE ?cfIndE // -defR -{1}defS ?morphimS ?card_injm // morphimEdom.
congr (_ * _); rewrite big_imset //=; last exact/injmP.
apply: eq_bigr => y Gy; rewrite -morphJ //.
have [Hxy | H'xy] := boolP (x ^ y \in H); first by rewrite -eq_hg ?cfIsomE.
by rewrite !cfun0 -?defS // -sub1set -morphim_set1 ?injmSK ?sub1set // groupJ.
Qed.
End MorphInduced.
Section FieldAutomorphism.
Variables (u : {rmorphism algC -> algC}) (gT rT : finGroupType).
Variables (G K H : {group gT}) (f : {morphism G >-> rT}) (R : {group rT}).
Implicit Types (phi : 'CF(G)) (S : seq 'CF(G)).
Local Notation "phi ^u" := (cfAut u phi).
Lemma cfAutZ_nat n phi : (n%:R *: phi)^u = n%:R *: phi^u.
Proof. exact: raddfZnat. Qed.
Lemma cfAutZ_Cnat z phi : z \in Num.nat -> (z *: phi)^u = z *: phi^u.
Proof. exact: raddfZ_nat. Qed.
Lemma cfAutZ_Cint z phi : z \in Num.int -> (z *: phi)^u = z *: phi^u.
Proof. exact: raddfZ_int. Qed.
Lemma cfAutK : cancel (@cfAut gT G u) (cfAut (algC_invaut u)).
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE /= algC_autK. Qed.
Lemma cfAutVK : cancel (cfAut (algC_invaut u)) (@cfAut gT G u).
Proof. by move=> phi; apply/cfunP=> x; rewrite !cfunE /= algC_invautK. Qed.
Lemma cfAut_inj : injective (@cfAut gT G u).
Proof. exact: can_inj cfAutK. Qed.
Lemma cfAut_eq1 phi : (cfAut u phi == 1) = (phi == 1).
Proof. by rewrite rmorph_eq1 //; apply: cfAut_inj. Qed.
Lemma support_cfAut phi : support phi^u =i support phi.
Proof. by move=> x; rewrite !inE cfunE fmorph_eq0. Qed.
Lemma map_cfAut_free S : cfAut_closed u S -> free S -> free (map (cfAut u) S).
Proof.
set Su := map _ S => sSuS freeS; have uniqS := free_uniq freeS.
have uniqSu: uniq Su by rewrite (map_inj_uniq cfAut_inj).
have{} sSuS: {subset Su <= S} by move=> _ /mapP[phi Sphi ->]; apply: sSuS.
have [|_ eqSuS] := uniq_min_size uniqSu sSuS; first by rewrite size_map.
by rewrite (perm_free (uniq_perm uniqSu uniqS eqSuS)).
Qed.
Lemma cfAut_on A phi : (phi^u \in 'CF(G, A)) = (phi \in 'CF(G, A)).
Proof. by rewrite !cfun_onE (eq_subset (support_cfAut phi)). Qed.
Lemma cfker_aut phi : cfker phi^u = cfker phi.
Proof.
apply/setP=> x /[!inE]; apply: andb_id2l => Gx.
by apply/forallP/forallP=> Kx y;
have:= Kx y; rewrite !cfunE (inj_eq (fmorph_inj u)).
Qed.
Lemma cfAut_cfuni A : ('1_A)^u = '1_A :> 'CF(G).
Proof. by apply/cfunP=> x; rewrite !cfunElock rmorph_nat. Qed.
Lemma cforder_aut phi : #[phi^u]%CF = #[phi]%CF.
Proof. exact: cforder_inj_rmorph cfAut_inj. Qed.
Lemma cfAutRes phi : ('Res[H] phi)^u = 'Res phi^u.
Proof. by apply/cfunP=> x; rewrite !cfunElock rmorphMn. Qed.
Lemma cfAutMorph (psi : 'CF(f @* H)) : (cfMorph psi)^u = cfMorph psi^u.
Proof. by apply/cfun_inP=> x Hx; rewrite !cfunElock Hx. Qed.
Lemma cfAutIsom (isoGR : isom G R f) phi :
(cfIsom isoGR phi)^u = cfIsom isoGR phi^u.
Proof.
apply/cfun_inP=> y; have [_ {1}<-] := isomP isoGR => /morphimP[x _ Gx ->{y}].
by rewrite !(cfunE, cfIsomE).
Qed.
Lemma cfAutQuo phi : (phi / H)^u = (phi^u / H)%CF.
Proof. by apply/cfunP=> Hx; rewrite !cfunElock cfker_aut rmorphMn. Qed.
Lemma cfAutMod (psi : 'CF(G / H)) : (psi %% H)^u = (psi^u %% H)%CF.
Proof. by apply/cfunP=> x; rewrite !cfunElock rmorphMn. Qed.
Lemma cfAutInd (psi : 'CF(H)) : ('Ind[G] psi)^u = 'Ind psi^u.
Proof.
have [sHG | not_sHG] := boolP (H \subset G).
apply/cfunP=> x; rewrite !(cfunE, cfIndE) // rmorphM /= fmorphV rmorph_nat.
by congr (_ * _); rewrite rmorph_sum; apply: eq_bigr => y; rewrite !cfunE.
rewrite !cfIndEout // linearZ /= cfAut_cfuni rmorphM rmorph_nat /=.
rewrite -cfdot_cfAut ?rmorph1 // => _ /imageP[x Hx ->].
by rewrite cfun1E Hx !rmorph1.
Qed.
Hypothesis KxH : K \x H = G.
Lemma cfAutDprodl (phi : 'CF(K)) : (cfDprodl KxH phi)^u = cfDprodl KxH phi^u.
Proof.
apply/cfun_inP=> _ /(mem_dprod KxH)[x [y [Kx Hy -> _]]].
by rewrite !(cfunE, cfDprodEl).
Qed.
Lemma cfAutDprodr (psi : 'CF(H)) : (cfDprodr KxH psi)^u = cfDprodr KxH psi^u.
Proof.
apply/cfun_inP=> _ /(mem_dprod KxH)[x [y [Kx Hy -> _]]].
by rewrite !(cfunE, cfDprodEr).
Qed.
Lemma cfAutDprod (phi : 'CF(K)) (psi : 'CF(H)) :
(cfDprod KxH phi psi)^u = cfDprod KxH phi^u psi^u.
Proof. by rewrite rmorphM /= cfAutDprodl cfAutDprodr. Qed.
End FieldAutomorphism.
Arguments cfAutK u {gT G}.
Arguments cfAutVK u {gT G}.
Arguments cfAut_inj u {gT G} [phi1 phi2] : rename.
Definition conj_cfRes := cfAutRes conjC.
Definition cfker_conjC := cfker_aut conjC.
Definition conj_cfQuo := cfAutQuo conjC.
Definition conj_cfMod := cfAutMod conjC.
Definition conj_cfInd := cfAutInd conjC.
Definition cfconjC_eq1 := cfAut_eq1 conjC.
|
HomologicalComplexAbelian.lean
|
/-
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.Additive
import Mathlib.Algebra.Homology.HomologicalComplexLimits
import Mathlib.Algebra.Homology.ShortComplex.ShortExact
/-! # THe category of homological complexes is abelian
If `C` is an abelian category, then `HomologicalComplex C c` is an abelian
category for any complex shape `c : ComplexShape ι`.
We also obtain that a short complex in `HomologicalComplex C c`
is exact (resp. short exact) iff degreewise it is so.
-/
open CategoryTheory Category Limits
namespace HomologicalComplex
variable {C ι : Type*} {c : ComplexShape ι} [Category C] [Abelian C]
noncomputable instance : IsNormalEpiCategory (HomologicalComplex C c) := ⟨fun p _ =>
⟨NormalEpi.mk _ (kernel.ι p) (kernel.condition _)
(isColimitOfEval _ _ (fun _ =>
Abelian.isColimitMapCoconeOfCokernelCoforkOfπ _ _))⟩⟩
noncomputable instance : IsNormalMonoCategory (HomologicalComplex C c) := ⟨fun p _ =>
⟨NormalMono.mk _ (cokernel.π p) (cokernel.condition _)
(isLimitOfEval _ _ (fun _ =>
Abelian.isLimitMapConeOfKernelForkOfι _ _))⟩⟩
noncomputable instance : Abelian (HomologicalComplex C c) where
variable (S : ShortComplex (HomologicalComplex C c))
lemma exact_of_degreewise_exact (hS : ∀ (i : ι), (S.map (eval C c i)).Exact) :
S.Exact := by
simp only [ShortComplex.exact_iff_isZero_homology] at hS ⊢
rw [IsZero.iff_id_eq_zero]
ext i
apply (IsZero.of_iso (hS i) (S.mapHomologyIso (eval C c i)).symm).eq_of_src
lemma shortExact_of_degreewise_shortExact
(hS : ∀ (i : ι), (S.map (eval C c i)).ShortExact) :
S.ShortExact where
mono_f := mono_of_mono_f _ (fun i => (hS i).mono_f)
epi_g := epi_of_epi_f _ (fun i => (hS i).epi_g)
exact := exact_of_degreewise_exact S (fun i => (hS i).exact)
lemma exact_iff_degreewise_exact :
S.Exact ↔ ∀ (i : ι), (S.map (eval C c i)).Exact := by
constructor
· intro hS i
exact hS.map (eval C c i)
· exact exact_of_degreewise_exact S
lemma shortExact_iff_degreewise_shortExact :
S.ShortExact ↔ ∀ (i : ι), (S.map (eval C c i)).ShortExact := by
constructor
· intro hS i
have := hS.mono_f
have := hS.epi_g
exact hS.map (eval C c i)
· exact shortExact_of_degreewise_shortExact S
end HomologicalComplex
|
KummerPolynomial.lean
|
/-
Copyright (c) 2023 Andrew Yang, Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import Mathlib.RingTheory.AdjoinRoot
import Mathlib.RingTheory.Norm.Defs
/-!
# Irreducibility of X ^ p - a
## Main result
- `X_pow_sub_C_irreducible_iff_of_prime`: For `p` prime, `X ^ p - C a` is irreducible iff `a` is not
a `p`-power. This is not true for composite `n`. For example, `x^4+4=(x^2-2x+2)(x^2+2x+2)` but
`-4` is not a 4th power.
-/
universe u
variable {K : Type u} [Field K]
open Polynomial AdjoinRoot
section Splits
lemma root_X_pow_sub_C_pow (n : ℕ) (a : K) :
(AdjoinRoot.root (X ^ n - C a)) ^ n = AdjoinRoot.of _ a := by
rw [← sub_eq_zero, ← AdjoinRoot.eval₂_root, eval₂_sub, eval₂_C, eval₂_pow, eval₂_X]
lemma root_X_pow_sub_C_ne_zero {n : ℕ} (hn : 1 < n) (a : K) :
(AdjoinRoot.root (X ^ n - C a)) ≠ 0 :=
mk_ne_zero_of_natDegree_lt (monic_X_pow_sub_C _ (Nat.ne_zero_of_lt hn))
X_ne_zero <| by rwa [natDegree_X_pow_sub_C, natDegree_X]
lemma root_X_pow_sub_C_ne_zero' {n : ℕ} {a : K} (hn : 0 < n) (ha : a ≠ 0) :
(AdjoinRoot.root (X ^ n - C a)) ≠ 0 := by
obtain (rfl | hn) := (Nat.succ_le_iff.mpr hn).eq_or_lt
· rw [pow_one]
intro e
refine mk_ne_zero_of_natDegree_lt (monic_X_sub_C a) (C_ne_zero.mpr ha) (by simp) ?_
trans AdjoinRoot.mk (X - C a) (X - (X - C a))
· rw [sub_sub_cancel]
· rw [map_sub, mk_self, sub_zero, mk_X, e]
· exact root_X_pow_sub_C_ne_zero hn a
end Splits
section Irreducible
lemma ne_zero_of_irreducible_X_pow_sub_C {n : ℕ} {a : K} (H : Irreducible (X ^ n - C a)) :
n ≠ 0 := by
rintro rfl
rw [pow_zero, ← C.map_one, ← map_sub] at H
exact not_irreducible_C _ H
lemma ne_zero_of_irreducible_X_pow_sub_C' {n : ℕ} (hn : n ≠ 1) {a : K}
(H : Irreducible (X ^ n - C a)) : a ≠ 0 := by
rintro rfl
rw [map_zero, sub_zero] at H
exact not_irreducible_pow hn H
lemma root_X_pow_sub_C_eq_zero_iff {n : ℕ} {a : K} (H : Irreducible (X ^ n - C a)) :
(AdjoinRoot.root (X ^ n - C a)) = 0 ↔ a = 0 := by
have hn := Nat.pos_iff_ne_zero.mpr (ne_zero_of_irreducible_X_pow_sub_C H)
refine ⟨not_imp_not.mp (root_X_pow_sub_C_ne_zero' hn), ?_⟩
rintro rfl
have := not_imp_not.mp (fun hn ↦ ne_zero_of_irreducible_X_pow_sub_C' hn H) rfl
rw [this, pow_one, map_zero, sub_zero, ← mk_X, mk_self]
lemma root_X_pow_sub_C_ne_zero_iff {n : ℕ} {a : K} (H : Irreducible (X ^ n - C a)) :
(AdjoinRoot.root (X ^ n - C a)) ≠ 0 ↔ a ≠ 0 :=
(root_X_pow_sub_C_eq_zero_iff H).not
theorem pow_ne_of_irreducible_X_pow_sub_C {n : ℕ} {a : K}
(H : Irreducible (X ^ n - C a)) {m : ℕ} (hm : m ∣ n) (hm' : m ≠ 1) (b : K) : b ^ m ≠ a := by
have hn : n ≠ 0 := fun e ↦ not_irreducible_C
(1 - a) (by simpa only [e, pow_zero, ← C.map_one, ← map_sub] using H)
obtain ⟨k, rfl⟩ := hm
rintro rfl
obtain ⟨q, hq⟩ := sub_dvd_pow_sub_pow (X ^ k) (C b) m
rw [mul_comm, pow_mul, map_pow, hq] at H
have : degree q = 0 := by
simpa [isUnit_iff_degree_eq_zero, degree_X_pow_sub_C,
Nat.pos_iff_ne_zero, (mul_ne_zero_iff.mp hn).2] using H.2 rfl
apply_fun degree at hq
simp only [this, ← pow_mul, mul_comm k m, degree_X_pow_sub_C, Nat.pos_iff_ne_zero.mpr hn,
Nat.pos_iff_ne_zero.mpr (mul_ne_zero_iff.mp hn).2, degree_mul, ← map_pow, add_zero,
Nat.cast_injective.eq_iff] at hq
exact hm' ((mul_eq_right₀ (mul_ne_zero_iff.mp hn).2).mp hq)
/-- Let `p` be a prime number. Let `K` be a field.
Let `t ∈ K` be an element which does not have a `p`th root in `K`.
Then the polynomial `x ^ p - t` is irreducible over `K`. -/
@[stacks 09HF "We proved the result without the condition that `K` is char p in 09HF."]
theorem X_pow_sub_C_irreducible_of_prime {p : ℕ} (hp : p.Prime) {a : K} (ha : ∀ b : K, b ^ p ≠ a) :
Irreducible (X ^ p - C a) := by
-- First of all, We may find an irreducible factor `g` of `X ^ p - C a`.
have : ¬ IsUnit (X ^ p - C a) := by
rw [Polynomial.isUnit_iff_degree_eq_zero, degree_X_pow_sub_C hp.pos, Nat.cast_eq_zero]
exact hp.ne_zero
have ⟨g, hg, hg'⟩ := WfDvdMonoid.exists_irreducible_factor this (X_pow_sub_C_ne_zero hp.pos a)
-- It suffices to show that `deg g = p`.
suffices natDegree g = p from (associated_of_dvd_of_natDegree_le hg'
(X_pow_sub_C_ne_zero hp.pos a) (this.trans natDegree_X_pow_sub_C.symm).ge).irreducible hg
-- Suppose `deg g ≠ p`.
by_contra h
have : Fact (Irreducible g) := ⟨hg⟩
-- Let `r` be a root of `g`, then `N_K(r) ^ p = N_K(r ^ p) = N_K(a) = a ^ (deg g)`.
have key : (Algebra.norm K (AdjoinRoot.root g)) ^ p = a ^ g.natDegree := by
have := eval₂_eq_zero_of_dvd_of_eval₂_eq_zero _ _ hg' (AdjoinRoot.eval₂_root g)
rw [eval₂_sub, eval₂_pow, eval₂_C, eval₂_X, sub_eq_zero] at this
rw [← map_pow, this, ← AdjoinRoot.algebraMap_eq, Algebra.norm_algebraMap,
(powerBasis hg.ne_zero).finrank, powerBasis_dim hg.ne_zero]
-- Since `a ^ (deg g)` is a `p`-power, and `p` is coprime to `deg g`, we conclude that `a` is
-- also a `p`-power, contradicting the hypothesis
have : p.Coprime (natDegree g) := hp.coprime_iff_not_dvd.mpr (fun e ↦ h (((natDegree_le_of_dvd hg'
(X_pow_sub_C_ne_zero hp.pos a)).trans_eq natDegree_X_pow_sub_C).antisymm (Nat.le_of_dvd
(natDegree_pos_iff_degree_pos.mpr <| Polynomial.degree_pos_of_irreducible hg) e)))
exact ha _ ((pow_mem_range_pow_of_coprime this.symm a).mp ⟨_, key⟩).choose_spec
theorem X_pow_sub_C_irreducible_iff_of_prime {p : ℕ} (hp : p.Prime) {a : K} :
Irreducible (X ^ p - C a) ↔ ∀ b, b ^ p ≠ a :=
⟨(pow_ne_of_irreducible_X_pow_sub_C · dvd_rfl hp.ne_one), X_pow_sub_C_irreducible_of_prime hp⟩
end Irreducible
|
Centroid.lean
|
/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import Mathlib.LinearAlgebra.AffineSpace.Combination
/-!
# Centroid of a Finite Set of Points in Affine Space
This file defines the centroid of a finite set of points in an affine space over a division
ring.
## Main definitions
* `centroidWeights`: A constant weight function assigning to each index in a `Finset` the same
weight, equal to the reciprocal of the number of elements.
* `centroid`: the centroid of a `Finset` of points, defined as the affine combination using
`centroidWeights`.
-/
assert_not_exists Affine.Simplex
noncomputable section
open Affine
namespace Finset
variable (k : Type*) {V : Type*} {P : Type*} [DivisionRing k] [AddCommGroup V] [Module k V]
variable [AffineSpace V P] {ι : Type*} (s : Finset ι) {ι₂ : Type*} (s₂ : Finset ι₂)
/-- The weights for the centroid of some points. -/
def centroidWeights : ι → k :=
Function.const ι (#s : k)⁻¹
/-- `centroidWeights` at any point. -/
@[simp]
theorem centroidWeights_apply (i : ι) : s.centroidWeights k i = (#s : k)⁻¹ :=
rfl
/-- `centroidWeights` equals a constant function. -/
theorem centroidWeights_eq_const : s.centroidWeights k = Function.const ι (#s : k)⁻¹ :=
rfl
variable {k} in
/-- The weights in the centroid sum to 1, if the number of points,
converted to `k`, is not zero. -/
theorem sum_centroidWeights_eq_one_of_cast_card_ne_zero (h : (#s : k) ≠ 0) :
∑ i ∈ s, s.centroidWeights k i = 1 := by simp [h]
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the number of points is not zero. -/
theorem sum_centroidWeights_eq_one_of_card_ne_zero [CharZero k] (h : #s ≠ 0) :
∑ i ∈ s, s.centroidWeights k i = 1 := by
simp_all
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the set is nonempty. -/
theorem sum_centroidWeights_eq_one_of_nonempty [CharZero k] (h : s.Nonempty) :
∑ i ∈ s, s.centroidWeights k i = 1 :=
s.sum_centroidWeights_eq_one_of_card_ne_zero k (ne_of_gt (card_pos.2 h))
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the number of points is `n + 1`. -/
theorem sum_centroidWeights_eq_one_of_card_eq_add_one [CharZero k] {n : ℕ} (h : #s = n + 1) :
∑ i ∈ s, s.centroidWeights k i = 1 :=
s.sum_centroidWeights_eq_one_of_card_ne_zero k (h.symm ▸ Nat.succ_ne_zero n)
/-- The centroid of some points. Although defined for any `s`, this
is intended to be used in the case where the number of points,
converted to `k`, is not zero. -/
def centroid (p : ι → P) : P :=
s.affineCombination k p (s.centroidWeights k)
/-- The definition of the centroid. -/
theorem centroid_def (p : ι → P) : s.centroid k p = s.affineCombination k p (s.centroidWeights k) :=
rfl
theorem centroid_univ (s : Finset P) : univ.centroid k ((↑) : s → P) = s.centroid k id := by
rw [centroid, centroid, ← s.attach_affineCombination_coe]
congr
ext
simp
/-- The centroid of a single point. -/
@[simp]
theorem centroid_singleton (p : ι → P) (i : ι) : ({i} : Finset ι).centroid k p = p i := by
simp [centroid_def, affineCombination_apply]
/-- The centroid of two points, expressed directly as adding a vector
to a point. -/
theorem centroid_pair [DecidableEq ι] [Invertible (2 : k)] (p : ι → P) (i₁ i₂ : ι) :
({i₁, i₂} : Finset ι).centroid k p = (2⁻¹ : k) • (p i₂ -ᵥ p i₁) +ᵥ p i₁ := by
by_cases h : i₁ = i₂
· simp [h]
· have hc : (#{i₁, i₂} : k) ≠ 0 := by
rw [card_insert_of_notMem (notMem_singleton.2 h), card_singleton]
norm_num
exact Invertible.ne_zero _
rw [centroid_def,
affineCombination_eq_weightedVSubOfPoint_vadd_of_sum_eq_one _ _ _
(sum_centroidWeights_eq_one_of_cast_card_ne_zero _ hc) (p i₁)]
simp [h, one_add_one_eq_two]
/-- The centroid of two points indexed by `Fin 2`, expressed directly
as adding a vector to the first point. -/
theorem centroid_pair_fin [Invertible (2 : k)] (p : Fin 2 → P) :
univ.centroid k p = (2⁻¹ : k) • (p 1 -ᵥ p 0) +ᵥ p 0 := by
rw [univ_fin2]
convert centroid_pair k p 0 1
/-- A centroid, over the image of an embedding, equals a centroid with
the same points and weights over the original `Finset`. -/
theorem centroid_map (e : ι₂ ↪ ι) (p : ι → P) :
(s₂.map e).centroid k p = s₂.centroid k (p ∘ e) := by
simp [centroid_def, affineCombination_map, centroidWeights]
/-- `centroidWeights` gives the weights for the centroid as a
constant function, which is suitable when summing over the points
whose centroid is being taken. This function gives the weights in a
form suitable for summing over a larger set of points, as an indicator
function that is zero outside the set whose centroid is being taken.
In the case of a `Fintype`, the sum may be over `univ`. -/
def centroidWeightsIndicator : ι → k :=
Set.indicator (↑s) (s.centroidWeights k)
/-- The definition of `centroidWeightsIndicator`. -/
theorem centroidWeightsIndicator_def :
s.centroidWeightsIndicator k = Set.indicator (↑s) (s.centroidWeights k) :=
rfl
/-- The sum of the weights for the centroid indexed by a `Fintype`. -/
theorem sum_centroidWeightsIndicator [Fintype ι] :
∑ i, s.centroidWeightsIndicator k i = ∑ i ∈ s, s.centroidWeights k i :=
sum_indicator_subset _ (subset_univ _)
/-- In the characteristic zero case, the weights in the centroid
indexed by a `Fintype` sum to 1 if the number of points is not
zero. -/
theorem sum_centroidWeightsIndicator_eq_one_of_card_ne_zero [CharZero k] [Fintype ι]
(h : #s ≠ 0) : ∑ i, s.centroidWeightsIndicator k i = 1 := by
rw [sum_centroidWeightsIndicator]
exact s.sum_centroidWeights_eq_one_of_card_ne_zero k h
/-- In the characteristic zero case, the weights in the centroid
indexed by a `Fintype` sum to 1 if the set is nonempty. -/
theorem sum_centroidWeightsIndicator_eq_one_of_nonempty [CharZero k] [Fintype ι] (h : s.Nonempty) :
∑ i, s.centroidWeightsIndicator k i = 1 := by
rw [sum_centroidWeightsIndicator]
exact s.sum_centroidWeights_eq_one_of_nonempty k h
/-- In the characteristic zero case, the weights in the centroid
indexed by a `Fintype` sum to 1 if the number of points is `n + 1`. -/
theorem sum_centroidWeightsIndicator_eq_one_of_card_eq_add_one [CharZero k] [Fintype ι] {n : ℕ}
(h : #s = n + 1) : ∑ i, s.centroidWeightsIndicator k i = 1 := by
rw [sum_centroidWeightsIndicator]
exact s.sum_centroidWeights_eq_one_of_card_eq_add_one k h
/-- The centroid as an affine combination over a `Fintype`. -/
theorem centroid_eq_affineCombination_fintype [Fintype ι] (p : ι → P) :
s.centroid k p = univ.affineCombination k p (s.centroidWeightsIndicator k) :=
affineCombination_indicator_subset _ _ (subset_univ _)
/-- An indexed family of points that is injective on the given
`Finset` has the same centroid as the image of that `Finset`. This is
stated in terms of a set equal to the image to provide control of
definitional equality for the index type used for the centroid of the
image. -/
theorem centroid_eq_centroid_image_of_inj_on {p : ι → P}
(hi : ∀ i ∈ s, ∀ j ∈ s, p i = p j → i = j) {ps : Set P} [Fintype ps]
(hps : ps = p '' ↑s) : s.centroid k p = (univ : Finset ps).centroid k fun x => (x : P) := by
let f : p '' ↑s → ι := fun x => x.property.choose
have hf : ∀ x, f x ∈ s ∧ p (f x) = x := fun x => x.property.choose_spec
let f' : ps → ι := fun x => f ⟨x, hps ▸ x.property⟩
have hf' : ∀ x, f' x ∈ s ∧ p (f' x) = x := fun x => hf ⟨x, hps ▸ x.property⟩
have hf'i : Function.Injective f' := by
intro x y h
rw [Subtype.ext_iff, ← (hf' x).2, ← (hf' y).2, h]
let f'e : ps ↪ ι := ⟨f', hf'i⟩
have hu : Finset.univ.map f'e = s := by
ext x
rw [mem_map]
constructor
· rintro ⟨i, _, rfl⟩
exact (hf' i).1
· intro hx
use ⟨p x, hps.symm ▸ Set.mem_image_of_mem _ hx⟩, mem_univ _
refine hi _ (hf' _).1 _ hx ?_
rw [(hf' _).2]
rw [← hu, centroid_map]
congr with x
change p (f' x) = ↑x
rw [(hf' x).2]
/-- Two indexed families of points that are injective on the given
`Finset`s and with the same points in the image of those `Finset`s
have the same centroid. -/
theorem centroid_eq_of_inj_on_of_image_eq {p : ι → P}
(hi : ∀ i ∈ s, ∀ j ∈ s, p i = p j → i = j) {p₂ : ι₂ → P}
(hi₂ : ∀ i ∈ s₂, ∀ j ∈ s₂, p₂ i = p₂ j → i = j) (he : p '' ↑s = p₂ '' ↑s₂) :
s.centroid k p = s₂.centroid k p₂ := by
classical rw [s.centroid_eq_centroid_image_of_inj_on k hi rfl,
s₂.centroid_eq_centroid_image_of_inj_on k hi₂ he]
end Finset
section DivisionRing
variable {k : Type*} {V : Type*} {P : Type*} [DivisionRing k] [AddCommGroup V] [Module k V]
variable [AffineSpace V P] {ι : Type*}
open Set Finset
/-- The centroid lies in the affine span if the number of points,
converted to `k`, is not zero. -/
theorem centroid_mem_affineSpan_of_cast_card_ne_zero {s : Finset ι} (p : ι → P)
(h : (#s : k) ≠ 0) : s.centroid k p ∈ affineSpan k (range p) :=
affineCombination_mem_affineSpan (s.sum_centroidWeights_eq_one_of_cast_card_ne_zero h) p
variable (k)
/-- In the characteristic zero case, the centroid lies in the affine
span if the number of points is not zero. -/
theorem centroid_mem_affineSpan_of_card_ne_zero [CharZero k] {s : Finset ι} (p : ι → P)
(h : #s ≠ 0) : s.centroid k p ∈ affineSpan k (range p) :=
affineCombination_mem_affineSpan (s.sum_centroidWeights_eq_one_of_card_ne_zero k h) p
/-- In the characteristic zero case, the centroid lies in the affine
span if the set is nonempty. -/
theorem centroid_mem_affineSpan_of_nonempty [CharZero k] {s : Finset ι} (p : ι → P)
(h : s.Nonempty) : s.centroid k p ∈ affineSpan k (range p) :=
affineCombination_mem_affineSpan (s.sum_centroidWeights_eq_one_of_nonempty k h) p
/-- In the characteristic zero case, the centroid lies in the affine
span if the number of points is `n + 1`. -/
theorem centroid_mem_affineSpan_of_card_eq_add_one [CharZero k] {s : Finset ι} (p : ι → P) {n : ℕ}
(h : #s = n + 1) : s.centroid k p ∈ affineSpan k (range p) :=
affineCombination_mem_affineSpan (s.sum_centroidWeights_eq_one_of_card_eq_add_one k h) p
end DivisionRing
|
Homology.lean
|
/-
Copyright (c) 2025 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Richard Hill, Andrew Yang
-/
import Mathlib.Algebra.Category.ModuleCat.Abelian
import Mathlib.Algebra.Category.ModuleCat.Topology.Basic
import Mathlib.Algebra.Homology.ShortComplex.Abelian
import Mathlib.Algebra.Homology.ShortComplex.PreservesHomology
/-!
# `TopModuleCat` is a `CategoryWithHomology`
`TopModuleCat R`, the category of topological `R`-modules, is not an abelian category.
But since the topology on subquotients is well-defined, we can still talk about homology in this
category. See the `CategoryWithHomology (TopModuleCat R)` instance in this file.
-/
universe v u
open CategoryTheory Limits
namespace TopModuleCat
variable {R : Type u} [Ring R] [TopologicalSpace R]
variable {M N : TopModuleCat.{v} R} (φ : M ⟶ N)
section kernel
/-- Kernel in `TopModuleCat R` is the kernel of the linear map with the subspace topology. -/
abbrev ker : TopModuleCat R := .of R (LinearMap.ker φ.hom)
/-- The inclusion map from the kernel in `TopModuleCat R`. -/
def kerι : ker φ ⟶ M := ofHom ⟨Submodule.subtype _, continuous_subtype_val⟩
instance : Mono (kerι φ) := ConcreteCategory.mono_of_injective (kerι φ) <| Subtype.val_injective
@[simp] lemma kerι_comp : kerι φ ≫ φ = 0 := by ext ⟨_, hm⟩; exact hm
@[simp] lemma kerι_apply (x) : kerι φ x = x.1 := rfl
/-- `TopModuleCat.ker` is indeed the kernel in `TopModuleCat R`. -/
def isLimitKer : IsLimit (KernelFork.ofι (kerι φ) (kerι_comp φ)) :=
isLimitAux (KernelFork.ofι (kerι φ) (kerι_comp φ))
(fun s ↦ ofHom <| (Fork.ι s).hom.codRestrict (LinearMap.ker φ.hom) fun m ↦ by
rw [LinearMap.mem_ker, ← ConcreteCategory.comp_apply (Fork.ι s) φ,
KernelFork.condition, hom_zero_apply])
(fun s ↦ rfl)
(fun s m h ↦ by dsimp at h ⊢; rw [← cancel_mono (kerι φ), h]; rfl)
end kernel
section cokernel
/-- Cokernel in `TopModuleCat R` is the cokernel of the linear map with the quotient topology. -/
abbrev coker : TopModuleCat R := .of R (N ⧸ LinearMap.range φ.hom)
/-- The projection map to the cokernel in `TopModuleCat R`. -/
def cokerπ : N ⟶ coker φ := ofHom <| ⟨Submodule.mkQ _, by tauto⟩
@[simp]
lemma hom_cokerπ (x) : (cokerπ φ).hom x = Submodule.mkQ _ x := rfl
lemma cokerπ_surjective : Function.Surjective (cokerπ φ).hom := Submodule.mkQ_surjective _
instance : Epi (cokerπ φ) := ConcreteCategory.epi_of_surjective (cokerπ φ) (cokerπ_surjective φ)
@[simp] lemma comp_cokerπ : φ ≫ cokerπ φ = 0 := by
ext m
change Submodule.mkQ _ (φ m) = 0
simp
/-- `TopModuleCat.coker` is indeed the cokernel in `TopModuleCat R`. -/
def isColimitCoker : IsColimit (CokernelCofork.ofπ (cokerπ φ) (comp_cokerπ φ)) :=
isColimitAux (.ofπ (cokerπ φ) (comp_cokerπ φ))
(fun s ↦ ofHom <|
{ toLinearMap := (LinearMap.range φ.hom).liftQ s.π.hom.toLinearMap
(LinearMap.range_le_ker_iff.mpr <| show (φ ≫ s.π).hom.toLinearMap = 0 by
rw [s.condition, hom_zero, ContinuousLinearMap.coe_zero])
cont := Continuous.quotient_lift s.π.hom.2 _ })
(fun s ↦ rfl)
(fun s m h ↦ by dsimp at h ⊢; rw [← cancel_epi (cokerπ φ), h]; rfl)
end cokernel
instance : CategoryWithHomology (TopModuleCat R) := by
constructor
intro S
let D₁ : S.LeftHomologyData := ⟨_, _, _, _, _, isLimitKer _, by simp, isColimitCoker _⟩
let D₂ : S.RightHomologyData := ⟨_, _, _, _, by simp, isColimitCoker _, _, isLimitKer _⟩
let F := ShortComplex.leftRightHomologyComparison' D₁ D₂
suffices IsIso F from ⟨⟨.ofIsIsoLeftRightHomologyComparison' D₁ D₂⟩⟩
have hF : Function.Bijective F := by
change Function.Bijective ((forget₂ _ (ModuleCat R)).map F)
rw [← ConcreteCategory.isIso_iff_bijective, ShortComplex.map_leftRightHomologyComparison']
infer_instance
have hF' : Topology.IsEmbedding F := by
refine .of_comp F.1.2 D₂.ι.1.2 ?_
-- `isEmbedding_of_isOpenQuotientMap_of_isInducing` is the key lemma that shows the two
-- definitions of homology give the same topology.
refine isEmbedding_of_isOpenQuotientMap_of_isInducing
D₁.i (F ≫ D₂.ι) D₁.π D₂.p ?_ .subtypeVal
(Submodule.isOpenQuotientMap_mkQ _).isQuotientMap
(Submodule.isOpenQuotientMap_mkQ _)
(Subtype.val_injective.comp hF.1) ?_
· rw [← ContinuousLinearMap.coe_comp', ← ContinuousLinearMap.coe_comp',
← hom_comp, ← hom_comp, ShortComplex.π_leftRightHomologyComparison'_ι]
· suffices ∀ x y, S.g y = 0 → D₂.p y = D₂.p x → S.g x = 0 by
simpa [Set.subset_def, D₁, kerι_apply S.g] using this
intro x y hy e
obtain ⟨z, hz⟩ := (Submodule.Quotient.eq _).mp e
obtain rfl := eq_sub_iff_add_eq.mp hz
simpa [show S.g (S.f z) = 0 from ConcreteCategory.congr_hom S.zero z] using hy
rw [← isIso_iff_of_reflects_iso _ (forget₂ (TopModuleCat R) TopCat),
TopCat.isIso_iff_isHomeomorph, isHomeomorph_iff_isEmbedding_surjective]
exact ⟨hF', hF.2⟩
end TopModuleCat
|
apply_with.lean
|
import Mathlib.Tactic.ApplyWith
set_option autoImplicit true
example (f : ∀ x : Nat, x = x → α) : α := by
apply (config := {}) f
apply rfl
apply 1
example (f : ∀ x : Nat, x = x → α) : α := by
apply (config := { newGoals := .nonDependentOnly }) f
apply @rfl _ 1
example (f : ∀ x : Nat, x = x → α) : α := by
apply (config := { newGoals := .all }) f
apply 1
apply rfl
|
AddAut.lean
|
/-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import Mathlib.Algebra.GroupWithZero.Action.Basic
import Mathlib.Algebra.GroupWithZero.Action.Units
import Mathlib.Algebra.Group.Units.Opposite
import Mathlib.Algebra.Module.Opposite
/-!
# Multiplication on the left/right as additive automorphisms
In this file we define `AddAut.mulLeft` and `AddAut.mulRight`.
See also `AddMonoidHom.mulLeft`, `AddMonoidHom.mulRight`, `AddMonoid.End.mulLeft`, and
`AddMonoid.End.mulRight` for multiplication by `R` as an endomorphism instead of multiplication by
`Rˣ` as an automorphism.
-/
namespace AddAut
variable {R : Type*} [Semiring R]
/-- Left multiplication by a unit of a semiring as an additive automorphism. -/
@[simps! +simpRhs]
def mulLeft : Rˣ →* AddAut R :=
DistribMulAction.toAddAut _ _
/-- Right multiplication by a unit of a semiring as an additive automorphism. -/
def mulRight (u : Rˣ) : AddAut R :=
DistribMulAction.toAddAut Rᵐᵒᵖˣ R (Units.opEquiv.symm <| MulOpposite.op u)
@[simp]
theorem mulRight_apply (u : Rˣ) (x : R) : mulRight u x = x * u :=
rfl
@[simp]
theorem mulRight_symm_apply (u : Rˣ) (x : R) : (mulRight u).symm x = x * u⁻¹ :=
rfl
end AddAut
|
Functorial.lean
|
/-
Copyright (c) 2019 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison
-/
import Mathlib.CategoryTheory.Functor.Basic
/-!
# Unbundled functors, as a typeclass decorating the object-level function.
-/
namespace CategoryTheory
-- declare the `v`'s first; see `CategoryTheory.Category` for an explanation
universe v v₁ v₂ v₃ u u₁ u₂ u₃
variable {C : Type u₁} [Category.{v₁} C] {D : Type u₂} [Category.{v₂} D]
-- Perhaps in the future we could redefine `Functor` in terms of this, but that isn't the
-- immediate plan.
/-- An unbundled functor. -/
class Functorial (F : C → D) : Type max v₁ v₂ u₁ u₂ where
/-- If `F : C → D` (just a function) has `[Functorial F]`,
we can write `map F f : F X ⟶ F Y` for the action of `F` on a morphism `f : X ⟶ Y`. -/
map (F) : ∀ {X Y : C}, (X ⟶ Y) → (F X ⟶ F Y)
/-- A functorial map preserves identities. -/
map_id : ∀ {X : C}, map (𝟙 X) = 𝟙 (F X) := by cat_disch
/-- A functorial map preserves composition of morphisms. -/
map_comp : ∀ {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z}, map (f ≫ g) = map f ≫ map g := by
cat_disch
attribute [simp, grind =] Functorial.map_id Functorial.map_comp
export Functorial (map)
namespace Functor
/-- Bundle a functorial function as a functor.
-/
def of (F : C → D) [I : Functorial.{v₁, v₂} F] : C ⥤ D :=
{ I with obj := F
map := Functorial.map F }
end Functor
instance (F : C ⥤ D) : Functorial.{v₁, v₂} F.obj :=
{ F with map := F.map }
@[simp, grind =]
theorem map_functorial_obj (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : map F.obj f = F.map f :=
rfl
instance functorial_id : Functorial.{v₁, v₁} (id : C → C) where map f := f
section
variable {E : Type u₃} [Category.{v₃} E]
-- This is no longer viable as an instance in Lean 3.7,
-- #lint reports an instance loop
-- Will this be a problem?
/-- `G ∘ F` is a functorial if both `F` and `G` are.
-/
def functorial_comp (F : C → D) [Functorial.{v₁, v₂} F] (G : D → E) [Functorial.{v₂, v₃} G] :
Functorial.{v₁, v₃} (G ∘ F) :=
{ Functor.of F ⋙ Functor.of G with map := fun f => map G (map F f) }
end
end CategoryTheory
|
FinsetBuilder.lean
|
import Mathlib.Data.Fintype.Defs
variable {α : Type*} [Fintype α] {p : α → Prop} {s : Finset α} {a : α}
[DecidablePred p] [DecidableEq α] [Singleton α (Finset α)] [HasCompl (Finset α)]
/-- info: {x | p x} : Finset α -/
#guard_msgs in
#check ({x | p x} : Finset α)
/-- info: {x ∈ s | p x} : Finset α -/
#guard_msgs in
#check ({x ∈ s | p x})
/-- info: {x ≠ a | p x} : Finset α -/
#guard_msgs in
#check ({x ≠ a | p x} : Finset α)
/-- info: {x ∉ s | p x} : Finset α -/
#guard_msgs in
#check ({x ∉ s | p x})
/-- info: {x : α | p x} : Finset α -/
#guard_msgs in
set_option pp.funBinderTypes true in
#check ({x | p x} : Finset α)
/-- info: {x ∈ s | p x} : Finset α -/
#guard_msgs in
set_option pp.funBinderTypes true in
#check ({x ∈ s | p x})
/-- info: {x ≠ a | p x} : Finset α -/
#guard_msgs in
set_option pp.funBinderTypes true in
#check ({x ≠ a | p x} : Finset α)
/-- info: {x ∉ s | p x} : Finset α -/
#guard_msgs in
set_option pp.funBinderTypes true in
#check ({x ∉ s | p x})
|
LibraryRewrite.lean
|
/-
Copyright (c) 2024 Jovan Gerbscheid. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jovan Gerbscheid, Anand Rao
-/
import Mathlib.Lean.Meta.RefinedDiscrTree
import Mathlib.Tactic.Widget.InteractiveUnfold
import ProofWidgets.Component.FilterDetails
/-!
# Point & click library rewriting
This file defines `rw??`, an interactive tactic that suggests rewrites for any expression selected
by the user.
`rw??` uses a (lazy) `RefinedDiscrTree` to lookup a list of candidate rewrite lemmas.
It excludes lemmas that are automatically generated.
Each lemma is then checked one by one to see whether it is applicable.
For each lemma that works, the corresponding rewrite tactic is constructed
and converted into a `String` that fits inside mathlib's 100 column limit,
so that it can be pasted into the editor when selected by the user.
The `RefinedDiscrTree` lookup groups the results by match pattern and gives a score to each pattern.
This is used to display the results in sections. The sections are ordered by this score.
Within each section, the lemmas are sorted by
- rewrites with fewer extra goals come first
- left-to-right rewrites come first
- shorter lemma names come first
- shorter replacement expressions come first (when taken as a string)
- alphabetically ordered by lemma name
The lemmas are optionally filtered to avoid duplicate rewrites, or trivial rewrites. This
is controlled by the filter button on the top right of the results.
When a rewrite lemma introduces new goals, these are shown after a `⊢`.
## TODO
Ways to improve `rw??`:
- Improve the logic around `nth_rw` and occurrences,
and about when to pass explicit arguments to the rewrite lemma.
For example, we could only pass explicit arguments if that avoids using `nth_rw`.
Performance may be a limiting factor for this.
Currently, the occurrence is computed by `viewKAbstractSubExpr`.
- Modify the interface to allow creating a whole `rw [.., ..]` chain, without having to go into
the editor in between. For this to work, we will need a more general syntax,
something like `rw [..]??`, which would be pasted into the editor.
- We could look for rewrites of partial applications of the selected expression.
For example, when clicking on `(f + g) x`, there should still be an `add_comm` suggestion.
Ways to extend `rw??`:
- Support generalized rewriting (`grw`)
- Integrate rewrite search with the `calc?` widget so that a `calc` block can be created using
just point & click.
-/
/-! ### Caching -/
namespace Mathlib.Tactic.LibraryRewrite
open Lean Meta RefinedDiscrTree
/-- The structure for rewrite lemmas stored in the `RefinedDiscrTree`. -/
structure RewriteLemma where
/-- The name of the lemma -/
name : Name
/-- `symm` is `true` when rewriting from right to left -/
symm : Bool
deriving BEq, Inhabited
instance : ToFormat RewriteLemma where
format lem := f! "{if lem.symm then "← " else ""}{lem.name}"
/-- Return `true` if `s` and `t` are equal up to changing the `MVarId`s. -/
def isMVarSwap (t s : Expr) : Bool :=
go t s {} |>.isSome
where
/-- The main loop of `isMVarSwap`. Returning `none` corresponds to a failure. -/
go (t s : Expr) (swaps : List (MVarId × MVarId)) : Option (List (MVarId × MVarId)) := do
let isTricky e := e.hasExprMVar || e.hasLevelParam
if isTricky t then
guard (isTricky s)
match t, s with
-- Note we don't bother keeping track of universe level metavariables.
| .const n₁ _ , .const n₂ _ => guard (n₁ == n₂); some swaps
| .sort _ , .sort _ => some swaps
| .forallE _ d₁ b₁ _, .forallE _ d₂ b₂ _ => go d₁ d₂ swaps >>= go b₁ b₂
| .lam _ d₁ b₁ _ , .lam _ d₂ b₂ _ => go d₁ d₂ swaps >>= go b₁ b₂
| .mdata d₁ e₁ , .mdata d₂ e₂ => guard (d₁ == d₂); go e₁ e₂ swaps
| .letE _ t₁ v₁ b₁ _, .letE _ t₂ v₂ b₂ _ => go t₁ t₂ swaps >>= go v₁ v₂ >>= go b₁ b₂
| .app f₁ a₁ , .app f₂ a₂ => go f₁ f₂ swaps >>= go a₁ a₂
| .proj n₁ i₁ e₁ , .proj n₂ i₂ e₂ => guard (n₁ == n₂ && i₁ == i₂); go e₁ e₂ swaps
| .fvar fvarId₁ , .fvar fvarId₂ => guard (fvarId₁ == fvarId₂); some swaps
| .lit v₁ , .lit v₂ => guard (v₁ == v₂); some swaps
| .bvar i₁ , .bvar i₂ => guard (i₁ == i₂); some swaps
| .mvar mvarId₁ , .mvar mvarId₂ =>
match swaps.find? (·.1 == mvarId₁) with
| none =>
guard (swaps.all (·.2 != mvarId₂))
let swaps := (mvarId₁, mvarId₂) :: swaps
if mvarId₁ == mvarId₂ then
some swaps
else
some <| (mvarId₂, mvarId₁) :: swaps
| some (_, mvarId) => guard (mvarId == mvarId₂); some swaps
| _ , _ => none
else
guard (t == s); some swaps
/-- Extract the left and right hand sides of an equality or iff statement. -/
@[inline] def eqOrIff? (e : Expr) : Option (Expr × Expr) :=
match e.eq? with
| some (_, lhs, rhs) => some (lhs, rhs)
| none => e.iff?
/-- Try adding the lemma to the `RefinedDiscrTree`. -/
def addRewriteEntry (name : Name) (cinfo : ConstantInfo) :
MetaM (List (RewriteLemma × List (Key × LazyEntry))) := do
-- we start with a fast-failing check to see if the lemma has the right shape
let .const head _ := cinfo.type.getForallBody.getAppFn | return []
unless head == ``Eq || head == ``Iff do return []
setMCtx {} -- recall that the metavariable context is not guaranteed to be empty at the start
let (_, _, eqn) ← forallMetaTelescope cinfo.type
let some (lhs, rhs) := eqOrIff? eqn | return []
let badMatch e :=
e.getAppFn.isMVar ||
-- this extra check excludes general equality lemmas that apply at any equality
-- these are almost never useful, and there are very many of them.
e.eq?.any fun (α, l, r) =>
α.getAppFn.isMVar && l.getAppFn.isMVar && r.getAppFn.isMVar && l != r
if badMatch lhs then
if badMatch rhs then
return []
else
return [({ name, symm := true }, ← initializeLazyEntryWithEta rhs)]
else
let result := ({ name, symm := false }, ← initializeLazyEntryWithEta lhs)
if badMatch rhs || isMVarSwap lhs rhs then
return [result]
else
return [result, ({ name, symm := true }, ← initializeLazyEntryWithEta rhs)]
/-- Try adding the local hypothesis to the `RefinedDiscrTree`. -/
def addLocalRewriteEntry (decl : LocalDecl) :
MetaM (List ((FVarId × Bool) × List (Key × LazyEntry))) :=
withReducible do
let (_, _, eqn) ← forallMetaTelescope decl.type
let some (lhs, rhs) := eqOrIff? eqn | return []
let result := ((decl.fvarId, false), ← initializeLazyEntryWithEta lhs)
return [result, ((decl.fvarId, true), ← initializeLazyEntryWithEta rhs)]
private abbrev ExtState := IO.Ref (Option (RefinedDiscrTree RewriteLemma))
private builtin_initialize ExtState.default : ExtState ←
IO.mkRef none
private instance : Inhabited ExtState where
default := ExtState.default
private initialize importedRewriteLemmasExt : EnvExtension ExtState ←
registerEnvExtension (IO.mkRef none)
/-! ### Computing the Rewrites -/
/-- Get all potential rewrite lemmas from the imported environment.
By setting the `librarySearch.excludedModules` option, all lemmas from certain modules
can be excluded. -/
def getImportCandidates (e : Expr) : MetaM (Array (Array RewriteLemma)) := do
let matchResult ← findImportMatches importedRewriteLemmasExt addRewriteEntry
/-
5000 constants seems to be approximately the right number of tasks
Too many means the tasks are too long.
Too few means less cache can be reused and more time is spent on combining different results.
With 5000 constants per task, we set the `HashMap` capacity to 256,
which is the largest capacity it gets to reach.
-/
(constantsPerTask := 5000) (capacityPerTask := 256) e
return matchResult.flatten
/-- Get all potential rewrite lemmas from the current file. Exclude lemmas from modules
in the `librarySearch.excludedModules` option. -/
def getModuleCandidates (e : Expr) : MetaM (Array (Array RewriteLemma)) := do
let moduleTreeRef ← createModuleTreeRef addRewriteEntry
let matchResult ← findModuleMatches moduleTreeRef e
return matchResult.flatten
/-- A rewrite lemma that has been applied to an expression. -/
structure Rewrite where
/-- `symm` is `true` when rewriting from right to left -/
symm : Bool
/-- The proof of the rewrite -/
proof : Expr
/-- The replacement expression obtained from the rewrite -/
replacement : Expr
/-- The size of the replacement when printed -/
stringLength : Nat
/-- The extra goals created by the rewrite -/
extraGoals : Array (MVarId × BinderInfo)
/-- Whether the rewrite introduces a new metavariable in the replacement expression. -/
makesNewMVars : Bool
/-- If `thm` can be used to rewrite `e`, return the rewrite. -/
def checkRewrite (thm e : Expr) (symm : Bool) : MetaM (Option Rewrite) := do
withTraceNodeBefore `rw?? (return m!
"rewriting {e} by {if symm then "← " else ""}{thm}") do
let (mvars, binderInfos, eqn) ← forallMetaTelescope (← inferType thm)
let some (lhs, rhs) := eqOrIff? eqn | return none
let (lhs, rhs) := if symm then (rhs, lhs) else (lhs, rhs)
let unifies ← withTraceNodeBefore `rw?? (return m! "unifying {e} =?= {lhs}")
(withReducible (isDefEq lhs e))
unless unifies do return none
-- just like in `kabstract`, we compare the `HeadIndex` and number of arguments
let lhs ← instantiateMVars lhs
if lhs.toHeadIndex != e.toHeadIndex || lhs.headNumArgs != e.headNumArgs then
return none
synthAppInstances `rw?? default mvars binderInfos false false
let mut extraGoals := #[]
for mvar in mvars, bi in binderInfos do
unless ← mvar.mvarId!.isAssigned do
extraGoals := extraGoals.push (mvar.mvarId!, bi)
let replacement ← instantiateMVars rhs
let stringLength := (← ppExpr replacement).pretty.length
let makesNewMVars := (replacement.findMVar? fun mvarId => mvars.any (·.mvarId! == mvarId)).isSome
let proof ← instantiateMVars (mkAppN thm mvars)
return some { symm, proof, replacement, stringLength, extraGoals, makesNewMVars }
initialize
registerTraceClass `rw??
/-- Try to rewrite `e` with each of the rewrite lemmas, and sort the resulting rewrites. -/
def checkAndSortRewriteLemmas (e : Expr) (rewrites : Array RewriteLemma) :
MetaM (Array (Rewrite × Name)) := do
let rewrites ← rewrites.filterMapM fun rw =>
tryCatchRuntimeEx do
let thm ← mkConstWithFreshMVarLevels rw.name
Option.map (·, rw.name) <$> checkRewrite thm e rw.symm
fun _ =>
return none
let lt (a b : (Rewrite × Name)) := Ordering.isLT <|
(compare a.1.extraGoals.size b.1.extraGoals.size).then <|
(compare a.1.symm b.1.symm).then <|
(compare a.2.toString.length b.2.toString.length).then <|
(compare a.1.stringLength b.1.stringLength).then <|
(Name.cmp a.2 b.2)
return rewrites.qsort lt
/-- Return all applicable library rewrites of `e`.
Note that the result may contain duplicate rewrites. These can be removed with `filterRewrites`. -/
def getImportRewrites (e : Expr) : MetaM (Array (Array (Rewrite × Name))) := do
(← getImportCandidates e).mapM (checkAndSortRewriteLemmas e)
/-- Same as `getImportRewrites`, but for lemmas from the current file. -/
def getModuleRewrites (e : Expr) : MetaM (Array (Array (Rewrite × Name))) := do
(← getModuleCandidates e).mapM (checkAndSortRewriteLemmas e)
/-! ### Rewriting by hypotheses -/
/-- Construct the `RefinedDiscrTree` of all local hypotheses. -/
def getHypotheses (except : Option FVarId) : MetaM (RefinedDiscrTree (FVarId × Bool)) := do
let mut tree : PreDiscrTree (FVarId × Bool) := {}
for decl in ← getLCtx do
if !decl.isImplementationDetail && except.all (· != decl.fvarId) then
for (val, entries) in ← addLocalRewriteEntry decl do
for (key, entry) in entries do
tree := tree.push key (entry, val)
return tree.toRefinedDiscrTree
/-- Return all applicable hypothesis rewrites of `e`. Similar to `getImportRewrites`. -/
def getHypothesisRewrites (e : Expr) (except : Option FVarId) :
MetaM (Array (Array (Rewrite × FVarId))) := do
let (candidates, _) ← (← getHypotheses except).getMatch e (unify := false) (matchRootStar := true)
let candidates := (← MonadExcept.ofExcept candidates).flatten
candidates.mapM <| Array.filterMapM fun (fvarId, symm) =>
tryCatchRuntimeEx do
Option.map (·, fvarId) <$> checkRewrite (.fvar fvarId) e symm
fun _ =>
return none
/-! ### Filtering out duplicate lemmas -/
/-- Get the `BinderInfo`s for the arguments of `mkAppN fn args`. -/
def getBinderInfos (fn : Expr) (args : Array Expr) : MetaM (Array BinderInfo) := do
let mut fnType ← inferType fn
let mut result := Array.mkEmpty args.size
let mut j := 0
for i in [:args.size] do
unless fnType.isForall do
fnType ← whnfD (fnType.instantiateRevRange j i args)
j := i
let .forallE _ _ b bi := fnType | throwError m! "expected function type {indentExpr fnType}"
fnType := b
result := result.push bi
return result
/-- Determine whether the explicit parts of two expressions are equal,
and the implicit parts are definitionally equal. -/
partial def isExplicitEq (t s : Expr) : MetaM Bool := do
if t == s then
return true
unless t.getAppNumArgs == s.getAppNumArgs && t.getAppFn == s.getAppFn do
return false
let tArgs := t.getAppArgs
let sArgs := s.getAppArgs
let bis ← getBinderInfos t.getAppFn tArgs
t.getAppNumArgs.allM fun i _ =>
if bis[i]!.isExplicit then
isExplicitEq tArgs[i]! sArgs[i]!
else
isDefEq tArgs[i]! sArgs[i]!
/-- Filter out duplicate rewrites, reflexive rewrites
or rewrites that have metavariables in the replacement expression. -/
@[specialize]
def filterRewrites {α} (e : Expr) (rewrites : Array α) (replacement : α → Expr)
(makesNewMVars : α → Bool) : MetaM (Array α) :=
withNewMCtxDepth do
let mut filtered := #[]
for rw in rewrites do
-- exclude rewrites that introduce new metavariables into the expression
if makesNewMVars rw then continue
-- exclude a reflexive rewrite
if ← isExplicitEq (replacement rw) e then
trace[rw??] "discarded reflexive rewrite {replacement rw}"
continue
-- exclude two identical looking rewrites
if ← filtered.anyM (isExplicitEq (replacement rw) <| replacement ·) then
trace[rw??] "discarded duplicate rewrite {replacement rw}"
continue
filtered := filtered.push rw
return filtered
/-! ### User interface -/
/-- Return the rewrite tactic that performs the rewrite. -/
def tacticSyntax (rw : Rewrite) (occ : Option Nat) (loc : Option Name) :
MetaM (TSyntax `tactic) := withoutModifyingMCtx do
-- we want the new metavariables to be printed as `?_` in the tactic syntax
for (mvarId, _) in rw.extraGoals do mvarId.setTag .anonymous
let proof ← withOptions (pp.mvars.anonymous.set · false) (PrettyPrinter.delab rw.proof)
mkRewrite occ rw.symm proof loc
open Widget ProofWidgets Jsx Server
/-- The structure with all data necessary for rendering a rewrite suggestion -/
structure RewriteInterface where
/-- `symm` is `true` when rewriting from right to left -/
symm : Bool
/-- The rewrite tactic string that performs the rewrite -/
tactic : String
/-- The replacement expression obtained from the rewrite -/
replacement : Expr
/-- The replacement expression obtained from the rewrite -/
replacementString : String
/-- The extra goals created by the rewrite -/
extraGoals : Array CodeWithInfos
/-- The lemma name with hover information -/
prettyLemma : CodeWithInfos
/-- The type of the lemma -/
lemmaType : Expr
/-- Whether the rewrite introduces new metavariables with the replacement. -/
makesNewMVars : Bool
/-- Construct the `RewriteInterface` from a `Rewrite`. -/
def Rewrite.toInterface (rw : Rewrite) (name : Name ⊕ FVarId) (occ : Option Nat)
(loc : Option Name) (range : Lsp.Range) : MetaM RewriteInterface := do
let tactic ← tacticSyntax rw occ loc
let tactic ← tacticPasteString tactic range
let replacementString := Format.pretty (← ppExpr rw.replacement)
let mut extraGoals := #[]
for (mvarId, bi) in rw.extraGoals do
if bi.isExplicit then
let extraGoal ← ppExprTagged (← instantiateMVars (← mvarId.getType))
extraGoals := extraGoals.push extraGoal
match name with
| .inl name =>
let prettyLemma := match ← ppExprTagged (← mkConstWithLevelParams name) with
| .tag tag _ => .tag tag (.text s!"{name}")
| code => code
let lemmaType := (← getConstInfo name).type
return { rw with tactic, replacementString, extraGoals, prettyLemma, lemmaType }
| .inr fvarId =>
let prettyLemma ← ppExprTagged (.fvar fvarId)
let lemmaType ← fvarId.getType
return { rw with tactic, replacementString, extraGoals, prettyLemma, lemmaType }
/-- The kind of rewrite -/
inductive Kind where
/-- A rewrite with a local hypothesis -/
| hypothesis
/-- A rewrite with a lemma from the current file -/
| fromFile
/-- A rewrite with a lemma from an imported file -/
| fromCache
/-- Return the Interfaces for rewriting `e`, both filtered and unfiltered. -/
def getRewriteInterfaces (e : Expr) (occ : Option Nat) (loc : Option Name) (except : Option FVarId)
(range : Lsp.Range) :
MetaM (Array (Array RewriteInterface × Kind) × Array (Array RewriteInterface × Kind)) := do
let mut filtr := #[]
let mut all := #[]
for rewrites in ← getHypothesisRewrites e except do
let rewrites ← rewrites.mapM fun (rw, fvarId) => rw.toInterface (.inr fvarId) occ loc range
all := all.push (rewrites, .hypothesis)
filtr := filtr.push (← filterRewrites e rewrites (·.replacement) (·.makesNewMVars), .hypothesis)
for rewrites in ← getModuleRewrites e do
let rewrites ← rewrites.mapM fun (rw, name) => rw.toInterface (.inl name) occ loc range
all := all.push (rewrites, .fromFile)
filtr := filtr.push (← filterRewrites e rewrites (·.replacement) (·.makesNewMVars), .fromFile)
for rewrites in ← getImportRewrites e do
let rewrites ← rewrites.mapM fun (rw, name) => rw.toInterface (.inl name) occ loc range
all := all.push (rewrites, .fromCache)
filtr := filtr.push (← filterRewrites e rewrites (·.replacement) (·.makesNewMVars), .fromCache)
return (filtr, all)
/-- Render the matching side of the rewrite lemma.
This is shown at the header of each section of rewrite results. -/
def pattern {α} (type : Expr) (symm : Bool) (k : Expr → MetaM α) : MetaM α := do
forallTelescope type fun _ e => do
let some (lhs, rhs) := eqOrIff? e | throwError "Expected equation, not {indentExpr e}"
k (if symm then rhs else lhs)
/-- Render the given rewrite results. -/
def renderRewrites (e : Expr) (results : Array (Array RewriteInterface × Kind)) (init : Option Html)
(range : Lsp.Range) (doc : FileWorker.EditableDocument) (showNames : Bool) :
MetaM Html := do
let htmls ← results.filterMapM (renderSection showNames)
let htmls := match init with
| some html => #[html] ++ htmls
| none => htmls
if htmls.isEmpty then
return <p> No rewrites found for <InteractiveCode fmt={← ppExprTagged e}/> </p>
else
return .element "div" #[("style", json% {"marginLeft" : "4px"})] htmls
where
/-- Render one section of rewrite results. -/
renderSection (showNames : Bool) (sec : Array RewriteInterface × Kind) : MetaM (Option Html) := do
let some head := sec.1[0]? | return none
let suffix := match sec.2 with
| .hypothesis => " (local hypotheses)"
| .fromFile => " (lemmas from current file)"
| .fromCache => ""
return <details «open»={true}>
<summary className="mv2 pointer">
Pattern
{← pattern head.lemmaType head.symm (return <InteractiveCode fmt={← ppExprTagged ·}/>)}
{.text suffix}
</summary>
{renderSectionCore showNames sec.1}
</details>
/-- Render the list of rewrite results in one section. -/
renderSectionCore (showNames : Bool) (sec : Array RewriteInterface) : Html :=
.element "ul" #[("style", json% { "padding-left" : "30px"})] <|
sec.map fun rw =>
<li> { .element "p" #[] <|
let button :=
<span className="font-code"> {
Html.ofComponent MakeEditLink
(.ofReplaceRange doc.meta range rw.tactic)
#[.text rw.replacementString] }
</span>
let extraGoals := rw.extraGoals.flatMap fun extraGoal =>
#[<br/>, <strong className="goal-vdash">⊢ </strong>, <InteractiveCode fmt={extraGoal}/>]
#[button] ++ extraGoals ++
if showNames then #[<br/>, <InteractiveCode fmt={rw.prettyLemma}/>] else #[] }
</li>
@[server_rpc_method_cancellable]
private def rpc (props : SelectInsertParams) : RequestM (RequestTask Html) :=
RequestM.asTask do
let doc ← RequestM.readDoc
let some loc := props.selectedLocations.back? |
return .text "rw??: Please shift-click an expression."
if loc.loc matches .hypValue .. then
return .text "rw??: cannot rewrite in the value of a let variable."
let some goal := props.goals[0]? | return .text "rw??: there is no goal to solve!"
if loc.mvarId != goal.mvarId then
return .text "rw??: the selected expression should be in the main goal."
goal.ctx.val.runMetaM {} do
let md ← goal.mvarId.getDecl
let lctx := md.lctx |>.sanitizeNames.run' {options := (← getOptions)}
Meta.withLCtx lctx md.localInstances do
let rootExpr ← loc.rootExpr
let some (subExpr, occ) ← withReducible <| viewKAbstractSubExpr rootExpr loc.pos |
return .text "rw??: expressions with bound variables are not yet supported"
unless ← kabstractIsTypeCorrect rootExpr subExpr loc.pos do
return .text <| "rw??: the selected expression cannot be rewritten, \
because the motive is not type correct. \
This usually occurs when trying to rewrite a term that appears as a dependent argument."
let location ← loc.fvarId?.mapM FVarId.getUserName
let unfoldsHtml ← InteractiveUnfold.renderUnfolds subExpr occ location props.replaceRange doc
let (filtered, all) ← getRewriteInterfaces subExpr occ location loc.fvarId? props.replaceRange
let filtered ← renderRewrites subExpr filtered unfoldsHtml props.replaceRange doc false
let all ← renderRewrites subExpr all unfoldsHtml props.replaceRange doc true
return <FilterDetails
summary={.text "Rewrite suggestions:"}
all={all}
filtered={filtered}
initiallyFiltered={true} />
/-- The component called by the `rw??` tactic -/
@[widget_module]
def LibraryRewriteComponent : Component SelectInsertParams :=
mk_rpc_widget% LibraryRewrite.rpc
/--
`rw??` is an interactive tactic that suggests rewrites for any expression selected by the user.
To use it, shift-click an expression in the goal or a hypothesis that you want to rewrite.
Clicking on one of the rewrite suggestions will paste the relevant rewrite tactic into the editor.
The rewrite suggestions are grouped and sorted by the pattern that the rewrite lemmas match with.
Rewrites that don't change the goal and rewrites that create the same goal as another rewrite
are filtered out, as well as rewrites that have new metavariables in the replacement expression.
To see all suggestions, click on the filter button (▼) in the top right.
-/
elab stx:"rw??" : tactic => do
let some range := (← getFileMap).rangeOfStx? stx | return
Widget.savePanelWidgetInfo (hash LibraryRewriteComponent.javascript)
(pure <| json% { replaceRange : $range }) stx
/-- Represent a `Rewrite` as `MessageData`. -/
def Rewrite.toMessageData (rw : Rewrite) (name : Name) : MetaM MessageData := do
let extraGoals ← rw.extraGoals.filterMapM fun (mvarId, bi) => do
if bi.isExplicit then
return some m! "⊢ {← mvarId.getType}"
return none
let list := [m! "{rw.replacement}"]
++ extraGoals.toList
++ [m! "{name}"]
return .group <| .nest 2 <| "· " ++ .joinSep list "\n"
/-- Represent a section of rewrites as `MessageData`. -/
def SectionToMessageData (sec : Array (Rewrite × Name) × Bool) : MetaM (Option MessageData) := do
let rewrites ← sec.1.toList.mapM fun (rw, name) => rw.toMessageData name
let rewrites : MessageData := .group (.joinSep rewrites "\n")
let some (rw, name) := sec.1[0]? | return none
let head ← pattern (← getConstInfo name).type rw.symm (addMessageContext m! "{·}")
return some <| "Pattern " ++ head ++ "\n" ++ rewrites
/-- `#rw?? e` gives all possible rewrites of `e`. It is a testing command for the `rw??` tactic -/
syntax (name := rw??Command) "#rw??" (&"all")? term : command
open Elab
/-- Elaborate a `#rw??` command. -/
@[command_elab rw??Command]
def elabrw??Command : Command.CommandElab := fun stx =>
withoutModifyingEnv <| Command.runTermElabM fun _ => do
let e ← Term.elabTerm stx[2] none
Term.synthesizeSyntheticMVarsNoPostponing
let e ← Term.levelMVarToParam (← instantiateMVars e)
let filter := stx[1].isNone
let mut rewrites := #[]
for rws in ← getModuleRewrites e do
let rws ← if filter then
filterRewrites e rws (·.1.replacement) (·.1.makesNewMVars)
else pure rws
rewrites := rewrites.push (rws, true)
for rws in ← getImportRewrites e do
let rws ← if filter then
filterRewrites e rws (·.1.replacement) (·.1.makesNewMVars)
else pure rws
rewrites := rewrites.push (rws, false)
let sections ← liftMetaM <| rewrites.filterMapM SectionToMessageData
if sections.isEmpty then
logInfo m! "No rewrites found for {e}"
else
logInfo (.joinSep sections.toList "\n\n")
end Mathlib.Tactic.LibraryRewrite
|
Basic.lean
|
/-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Yury Kudryashov
-/
import Mathlib.Algebra.AddTorsor.Defs
import Mathlib.Algebra.Group.Action.Basic
import Mathlib.Algebra.Group.End
import Mathlib.Algebra.Group.Pointwise.Set.Scalar
/-!
# Torsors of additive group actions
Further results for torsors, that are not in `Mathlib/Algebra/AddTorsor/Defs.lean` to avoid
increasing imports there.
-/
open scoped Pointwise
section General
variable {G : Type*} {P : Type*} [AddGroup G] [T : AddTorsor G P]
namespace Set
theorem singleton_vsub_self (p : P) : ({p} : Set P) -ᵥ {p} = {(0 : G)} := by
rw [Set.singleton_vsub_singleton, vsub_self]
end Set
/-- If the same point subtracted from two points produces equal
results, those points are equal. -/
theorem vsub_left_cancel {p₁ p₂ p : P} (h : p₁ -ᵥ p = p₂ -ᵥ p) : p₁ = p₂ := by
rwa [← sub_eq_zero, vsub_sub_vsub_cancel_right, vsub_eq_zero_iff_eq] at h
/-- The same point subtracted from two points produces equal results
if and only if those points are equal. -/
@[simp]
theorem vsub_left_cancel_iff {p₁ p₂ p : P} : p₁ -ᵥ p = p₂ -ᵥ p ↔ p₁ = p₂ :=
⟨vsub_left_cancel, fun h => h ▸ rfl⟩
/-- Subtracting the point `p` is an injective function. -/
theorem vsub_left_injective (p : P) : Function.Injective ((· -ᵥ p) : P → G) := fun _ _ =>
vsub_left_cancel
/-- If subtracting two points from the same point produces equal
results, those points are equal. -/
theorem vsub_right_cancel {p₁ p₂ p : P} (h : p -ᵥ p₁ = p -ᵥ p₂) : p₁ = p₂ := by
refine vadd_left_cancel (p -ᵥ p₂) ?_
rw [vsub_vadd, ← h, vsub_vadd]
/-- Subtracting two points from the same point produces equal results
if and only if those points are equal. -/
@[simp]
theorem vsub_right_cancel_iff {p₁ p₂ p : P} : p -ᵥ p₁ = p -ᵥ p₂ ↔ p₁ = p₂ :=
⟨vsub_right_cancel, fun h => h ▸ rfl⟩
/-- Subtracting a point from the point `p` is an injective
function. -/
theorem vsub_right_injective (p : P) : Function.Injective ((p -ᵥ ·) : P → G) := fun _ _ =>
vsub_right_cancel
end General
section comm
variable {G : Type*} {P : Type*} [AddCommGroup G] [AddTorsor G P]
/-- Cancellation subtracting the results of two subtractions. -/
@[simp]
theorem vsub_sub_vsub_cancel_left (p₁ p₂ p₃ : P) : p₃ -ᵥ p₂ - (p₃ -ᵥ p₁) = p₁ -ᵥ p₂ := by
rw [sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm, vsub_add_vsub_cancel]
@[simp]
theorem vadd_vsub_vadd_cancel_left (v : G) (p₁ p₂ : P) : (v +ᵥ p₁) -ᵥ (v +ᵥ p₂) = p₁ -ᵥ p₂ := by
rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub_cancel_left]
theorem vadd_vsub_vadd_comm (v₁ v₂ : G) (p₁ p₂ : P) :
(v₁ +ᵥ p₁) -ᵥ (v₂ +ᵥ p₂) = (v₁ - v₂) + (p₁ -ᵥ p₂) := by
rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub_assoc, ← add_comm_sub]
theorem sub_add_vsub_comm (v₁ v₂ : G) (p₁ p₂ : P) :
(v₁ - v₂) + (p₁ -ᵥ p₂) = (v₁ +ᵥ p₁) -ᵥ (v₂ +ᵥ p₂) :=
vadd_vsub_vadd_comm _ _ _ _ |>.symm
theorem vsub_vadd_comm (p₁ p₂ p₃ : P) : (p₁ -ᵥ p₂ : G) +ᵥ p₃ = (p₃ -ᵥ p₂) +ᵥ p₁ := by
rw [← @vsub_eq_zero_iff_eq G, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub]
simp
theorem vadd_eq_vadd_iff_sub_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} :
v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ v₂ - v₁ = p₁ -ᵥ p₂ := by
rw [vadd_eq_vadd_iff_neg_add_eq_vsub, neg_add_eq_sub]
theorem vsub_sub_vsub_comm (p₁ p₂ p₃ p₄ : P) : p₁ -ᵥ p₂ - (p₃ -ᵥ p₄) = p₁ -ᵥ p₃ - (p₂ -ᵥ p₄) := by
rw [← vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub]
namespace Set
@[simp] lemma vadd_set_vsub_vadd_set (v : G) (s t : Set P) : (v +ᵥ s) -ᵥ (v +ᵥ t) = s -ᵥ t := by
ext; simp [mem_vsub, mem_vadd_set]
end Set
end comm
namespace Prod
variable {G G' P P' : Type*} [AddGroup G] [AddGroup G'] [AddTorsor G P] [AddTorsor G' P']
instance instAddTorsor : AddTorsor (G × G') (P × P') where
vadd v p := (v.1 +ᵥ p.1, v.2 +ᵥ p.2)
zero_vadd _ := Prod.ext (zero_vadd _ _) (zero_vadd _ _)
add_vadd _ _ _ := Prod.ext (add_vadd _ _ _) (add_vadd _ _ _)
vsub p₁ p₂ := (p₁.1 -ᵥ p₂.1, p₁.2 -ᵥ p₂.2)
vsub_vadd' _ _ := Prod.ext (vsub_vadd _ _) (vsub_vadd _ _)
vadd_vsub' _ _ := Prod.ext (vadd_vsub _ _) (vadd_vsub _ _)
@[simp]
theorem fst_vadd (v : G × G') (p : P × P') : (v +ᵥ p).1 = v.1 +ᵥ p.1 :=
rfl
@[simp]
theorem snd_vadd (v : G × G') (p : P × P') : (v +ᵥ p).2 = v.2 +ᵥ p.2 :=
rfl
@[simp]
theorem mk_vadd_mk (v : G) (v' : G') (p : P) (p' : P') : (v, v') +ᵥ (p, p') = (v +ᵥ p, v' +ᵥ p') :=
rfl
@[simp]
theorem fst_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').1 = p₁.1 -ᵥ p₂.1 :=
rfl
@[simp]
theorem snd_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').2 = p₁.2 -ᵥ p₂.2 :=
rfl
@[simp]
theorem mk_vsub_mk (p₁ p₂ : P) (p₁' p₂' : P') :
((p₁, p₁') -ᵥ (p₂, p₂') : G × G') = (p₁ -ᵥ p₂, p₁' -ᵥ p₂') :=
rfl
end Prod
namespace Pi
universe u v w
variable {I : Type u} {fg : I → Type v} [∀ i, AddGroup (fg i)] {fp : I → Type w}
open AddAction AddTorsor
/-- A product of `AddTorsor`s is an `AddTorsor`. -/
instance instAddTorsor [∀ i, AddTorsor (fg i) (fp i)] : AddTorsor (∀ i, fg i) (∀ i, fp i) where
vadd g p i := g i +ᵥ p i
zero_vadd p := funext fun i => zero_vadd (fg i) (p i)
add_vadd g₁ g₂ p := funext fun i => add_vadd (g₁ i) (g₂ i) (p i)
vsub p₁ p₂ i := p₁ i -ᵥ p₂ i
vsub_vadd' p₁ p₂ := funext fun i => vsub_vadd (p₁ i) (p₂ i)
vadd_vsub' g p := funext fun i => vadd_vsub (g i) (p i)
end Pi
namespace Equiv
variable (G : Type*) (P : Type*) [AddGroup G] [AddTorsor G P]
@[simp]
theorem constVAdd_zero : constVAdd P (0 : G) = 1 :=
ext <| zero_vadd G
variable {G}
@[simp]
theorem constVAdd_add (v₁ v₂ : G) : constVAdd P (v₁ + v₂) = constVAdd P v₁ * constVAdd P v₂ :=
ext <| add_vadd v₁ v₂
/-- `Equiv.constVAdd` as a homomorphism from `Multiplicative G` to `Equiv.perm P` -/
def constVAddHom : Multiplicative G →* Equiv.Perm P where
toFun v := constVAdd P (v.toAdd)
map_one' := constVAdd_zero G P
map_mul' := constVAdd_add P
variable {P}
open Function
@[simp]
theorem left_vsub_pointReflection (x y : P) : x -ᵥ pointReflection x y = y -ᵥ x :=
neg_injective <| by simp
@[simp]
theorem right_vsub_pointReflection (x y : P) : y -ᵥ pointReflection x y = 2 • (y -ᵥ x) :=
neg_injective <| by simp [← neg_nsmul]
/-- `x` is the only fixed point of `pointReflection x`. This lemma requires
`x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/
theorem pointReflection_fixed_iff_of_injective_two_nsmul {x y : P} (h : Injective (2 • · : G → G)) :
pointReflection x y = y ↔ y = x := by
rw [pointReflection_apply, eq_comm, eq_vadd_iff_vsub_eq, ← neg_vsub_eq_vsub_rev,
neg_eq_iff_add_eq_zero, ← two_nsmul, ← nsmul_zero 2, h.eq_iff, vsub_eq_zero_iff_eq, eq_comm]
theorem injective_pointReflection_left_of_injective_two_nsmul {G P : Type*} [AddCommGroup G]
[AddTorsor G P] (h : Injective (2 • · : G → G)) (y : P) :
Injective fun x : P => pointReflection x y :=
fun x₁ x₂ (hy : pointReflection x₁ y = pointReflection x₂ y) => by
rwa [pointReflection_apply, pointReflection_apply, vadd_eq_vadd_iff_sub_eq_vsub,
vsub_sub_vsub_cancel_right, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero,
← two_nsmul, ← nsmul_zero 2, h.eq_iff, vsub_eq_zero_iff_eq] at hy
/-- In the special case of additive commutative groups (as opposed to just additive torsors),
`Equiv.pointReflection x` coincides with `Equiv.subLeft (2 • x)`. -/
lemma pointReflection_eq_subLeft {G : Type*} [AddCommGroup G] (x : G) :
pointReflection x = Equiv.subLeft (2 • x) := by
ext; simp [pointReflection, sub_add_eq_add_sub, two_nsmul]
end Equiv
|
Hom.lean
|
/-
Copyright (c) 2024 Amelia Livingston. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov, Amelia Livingston
-/
import Mathlib.RingTheory.Coalgebra.Basic
/-!
# Homomorphisms of `R`-coalgebras
This file defines bundled homomorphisms of `R`-coalgebras. We largely mimic
`Mathlib/Algebra/Algebra/Hom.lean`.
## Main definitions
* `CoalgHom R A B`: the type of `R`-coalgebra morphisms from `A` to `B`.
* `Coalgebra.counitCoalgHom R A : A →ₗc[R] R`: the counit of a coalgebra as a coalgebra
homomorphism.
## Notations
* `A →ₗc[R] B` : `R`-coalgebra homomorphism from `A` to `B`.
-/
open TensorProduct Coalgebra
universe u v w
/-- Given `R`-modules `A, B` with comultiplication maps `Δ_A, Δ_B` and counit maps
`ε_A, ε_B`, an `R`-coalgebra homomorphism `A →ₗc[R] B` is an `R`-linear map `f` such that
`ε_B ∘ f = ε_A` and `(f ⊗ f) ∘ Δ_A = Δ_B ∘ f`. -/
structure CoalgHom (R A B : Type*) [CommSemiring R]
[AddCommMonoid A] [Module R A] [AddCommMonoid B] [Module R B]
[CoalgebraStruct R A] [CoalgebraStruct R B] extends A →ₗ[R] B where
counit_comp : counit ∘ₗ toLinearMap = counit
map_comp_comul : TensorProduct.map toLinearMap toLinearMap ∘ₗ comul = comul ∘ₗ toLinearMap
@[inherit_doc CoalgHom]
infixr:25 " →ₗc " => CoalgHom _
@[inherit_doc]
notation:25 A " →ₗc[" R "] " B => CoalgHom R A B
/-- `CoalgHomClass F R A B` asserts `F` is a type of bundled coalgebra homomorphisms
from `A` to `B`. -/
class CoalgHomClass (F : Type*) (R A B : outParam Type*)
[CommSemiring R] [AddCommMonoid A] [Module R A] [AddCommMonoid B] [Module R B]
[CoalgebraStruct R A] [CoalgebraStruct R B] [FunLike F A B] : Prop
extends SemilinearMapClass F (RingHom.id R) A B where
counit_comp : ∀ f : F, counit ∘ₗ (f : A →ₗ[R] B) = counit
map_comp_comul : ∀ f : F, TensorProduct.map (f : A →ₗ[R] B)
(f : A →ₗ[R] B) ∘ₗ comul = comul ∘ₗ (f : A →ₗ[R] B)
attribute [simp] CoalgHomClass.counit_comp CoalgHomClass.map_comp_comul
namespace CoalgHomClass
variable {R A B F : Type*} [CommSemiring R]
[AddCommMonoid A] [Module R A] [AddCommMonoid B] [Module R B]
[CoalgebraStruct R A] [CoalgebraStruct R B] [FunLike F A B]
[CoalgHomClass F R A B]
/-- Turn an element of a type `F` satisfying `CoalgHomClass F R A B` into an actual
`CoalgHom`. This is declared as the default coercion from `F` to `A →ₗc[R] B`. -/
@[coe]
def toCoalgHom (f : F) : A →ₗc[R] B :=
{ (f : A →ₗ[R] B) with
toFun := f
counit_comp := CoalgHomClass.counit_comp f
map_comp_comul := CoalgHomClass.map_comp_comul f }
instance instCoeToCoalgHom : CoeHead F (A →ₗc[R] B) :=
⟨CoalgHomClass.toCoalgHom⟩
@[simp]
theorem counit_comp_apply (f : F) (x : A) : counit (f x) = counit (R := R) x :=
LinearMap.congr_fun (counit_comp f) _
@[simp]
theorem map_comp_comul_apply (f : F) (x : A) :
TensorProduct.map f f (comul x) = comul (R := R) (f x) :=
LinearMap.congr_fun (map_comp_comul f) _
end CoalgHomClass
namespace CoalgHom
variable {R A B C D : Type*}
section
variable [CommSemiring R] [AddCommMonoid A] [Module R A] [AddCommMonoid B] [Module R B]
[AddCommMonoid C] [Module R C] [AddCommMonoid D] [Module R D]
[CoalgebraStruct R A] [CoalgebraStruct R B] [CoalgebraStruct R C] [CoalgebraStruct R D]
instance funLike : FunLike (A →ₗc[R] B) A B where
coe f := f.toFun
coe_injective' f g h := by
rcases f with ⟨⟨⟨_, _⟩, _⟩, _, _⟩
rcases g with ⟨⟨⟨_, _⟩, _⟩, _, _⟩
congr
instance coalgHomClass : CoalgHomClass (A →ₗc[R] B) R A B where
map_add := fun f => f.map_add'
map_smulₛₗ := fun f => f.map_smul'
counit_comp := fun f => f.counit_comp
map_comp_comul := fun f => f.map_comp_comul
/-- See Note [custom simps projection] -/
def Simps.apply {R α β : Type*} [CommSemiring R]
[AddCommMonoid α] [Module R α] [AddCommMonoid β]
[Module R β] [CoalgebraStruct R α] [CoalgebraStruct R β]
(f : α →ₗc[R] β) : α → β := f
initialize_simps_projections CoalgHom (toFun → apply)
@[simp]
protected theorem coe_coe {F : Type*} [FunLike F A B] [CoalgHomClass F R A B] (f : F) :
⇑(f : A →ₗc[R] B) = f :=
rfl
@[simp]
theorem coe_mk {f : A →ₗ[R] B} (h h₁) : ((⟨f, h, h₁⟩ : A →ₗc[R] B) : A → B) = f :=
rfl
@[norm_cast]
theorem coe_mks {f : A → B} (h₁ h₂ h₃ h₄) : ⇑(⟨⟨⟨f, h₁⟩, h₂⟩, h₃, h₄⟩ : A →ₗc[R] B) = f :=
rfl
@[simp, norm_cast]
theorem coe_linearMap_mk {f : A →ₗ[R] B} (h h₁) : ((⟨f, h, h₁⟩ : A →ₗc[R] B) : A →ₗ[R] B) = f :=
rfl
@[simp]
theorem toLinearMap_eq_coe (f : A →ₗc[R] B) : f.toLinearMap = f :=
rfl
@[simp, norm_cast]
theorem coe_toLinearMap (f : A →ₗc[R] B) : ⇑(f : A →ₗ[R] B) = f :=
rfl
@[norm_cast]
theorem coe_toAddMonoidHom (f : A →ₗc[R] B) : ⇑(f : A →+ B) = f :=
rfl
theorem coe_fn_injective : @Function.Injective (A →ₗc[R] B) (A → B) (↑) :=
DFunLike.coe_injective
theorem coe_fn_inj {φ₁ φ₂ : A →ₗc[R] B} : (φ₁ : A → B) = φ₂ ↔ φ₁ = φ₂ :=
DFunLike.coe_fn_eq
theorem coe_linearMap_injective : Function.Injective ((↑) : (A →ₗc[R] B) → A →ₗ[R] B) :=
fun φ₁ φ₂ H => coe_fn_injective <|
show ((φ₁ : A →ₗ[R] B) : A → B) = ((φ₂ : A →ₗ[R] B) : A → B) from congr_arg _ H
theorem coe_addMonoidHom_injective : Function.Injective ((↑) : (A →ₗc[R] B) → A →+ B) :=
LinearMap.toAddMonoidHom_injective.comp coe_linearMap_injective
protected theorem congr_fun {φ₁ φ₂ : A →ₗc[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x :=
DFunLike.congr_fun H x
protected theorem congr_arg (φ : A →ₗc[R] B) {x y : A} (h : x = y) : φ x = φ y :=
DFunLike.congr_arg φ h
@[ext]
theorem ext {φ₁ φ₂ : A →ₗc[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
DFunLike.ext _ _ H
@[ext high]
theorem ext_of_ring {f g : R →ₗc[R] A} (h : f 1 = g 1) : f = g :=
coe_linearMap_injective (by ext; assumption)
@[simp]
theorem mk_coe {f : A →ₗc[R] B} (h₁ h₂ h₃ h₄) : (⟨⟨⟨f, h₁⟩, h₂⟩, h₃, h₄⟩ : A →ₗc[R] B) = f :=
ext fun _ => rfl
/-- Copy of a `CoalgHom` with a new `toFun` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (f : A →ₗc[R] B) (f' : A → B) (h : f' = ⇑f) : A →ₗc[R] B :=
{ toLinearMap := (f : A →ₗ[R] B).copy f' h
counit_comp := by ext; simp_all
map_comp_comul := by simp only [(f : A →ₗ[R] B).copy_eq f' h,
CoalgHomClass.map_comp_comul] }
@[simp]
theorem coe_copy (f : A →ₗc[R] B) (f' : A → B) (h : f' = ⇑f) : ⇑(f.copy f' h) = f' :=
rfl
theorem copy_eq (f : A →ₗc[R] B) (f' : A → B) (h : f' = ⇑f) : f.copy f' h = f :=
DFunLike.ext' h
variable (R A)
/-- Identity map as a `CoalgHom`. -/
@[simps!] protected def id : A →ₗc[R] A :=
{ LinearMap.id with
counit_comp := by ext; rfl
map_comp_comul := by simp only [map_id, LinearMap.id_comp, LinearMap.comp_id] }
variable {R A}
@[simp, norm_cast]
theorem coe_id : ⇑(CoalgHom.id R A) = id :=
rfl
@[simp]
theorem id_toLinearMap : (CoalgHom.id R A : A →ₗ[R] A) = LinearMap.id := rfl
/-- Composition of coalgebra homomorphisms. -/
@[simps!] def comp (φ₁ : B →ₗc[R] C) (φ₂ : A →ₗc[R] B) : A →ₗc[R] C :=
{ (φ₁ : B →ₗ[R] C) ∘ₗ (φ₂ : A →ₗ[R] B) with
counit_comp := by ext; simp
map_comp_comul := by ext; simp [map_comp] }
@[simp]
theorem coe_comp (φ₁ : B →ₗc[R] C) (φ₂ : A →ₗc[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl
@[simp]
theorem comp_toLinearMap (φ₁ : B →ₗc[R] C) (φ₂ : A →ₗc[R] B) :
φ₁.comp φ₂ = (φ₁ : B →ₗ[R] C) ∘ₗ (φ₂ : A →ₗ[R] B) := rfl
variable (φ : A →ₗc[R] B)
@[simp]
theorem comp_id : φ.comp (CoalgHom.id R A) = φ :=
ext fun _x => rfl
@[simp]
theorem id_comp : (CoalgHom.id R B).comp φ = φ :=
ext fun _x => rfl
theorem comp_assoc (φ₁ : C →ₗc[R] D) (φ₂ : B →ₗc[R] C) (φ₃ : A →ₗc[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext fun _x => rfl
theorem map_smul_of_tower {R'} [SMul R' A] [SMul R' B] [LinearMap.CompatibleSMul A B R' R] (r : R')
(x : A) : φ (r • x) = r • φ x :=
φ.toLinearMap.map_smul_of_tower r x
@[simps -isSimp toSemigroup_toMul_mul toOne_one]
instance End : Monoid (A →ₗc[R] A) where
mul := comp
mul_assoc _ _ _ := rfl
one := CoalgHom.id R A
one_mul _ := ext fun _ => rfl
mul_one _ := ext fun _ => rfl
@[simp]
theorem one_apply (x : A) : (1 : A →ₗc[R] A) x = x :=
rfl
@[simp]
theorem mul_apply (φ ψ : A →ₗc[R] A) (x : A) : (φ * ψ) x = φ (ψ x) :=
rfl
end
end CoalgHom
namespace Coalgebra
variable (R : Type u) (A : Type v) (B : Type w)
variable [CommSemiring R] [AddCommMonoid A] [AddCommMonoid B] [Module R A] [Module R B]
variable [Coalgebra R A] [Coalgebra R B]
/-- The counit of a coalgebra as a `CoalgHom`. -/
noncomputable def counitCoalgHom : A →ₗc[R] R :=
{ counit with
counit_comp := by ext; simp
map_comp_comul := by
ext
simp only [LinearMap.coe_comp, Function.comp_apply, CommSemiring.comul_apply,
← LinearMap.lTensor_comp_rTensor, rTensor_counit_comul, LinearMap.lTensor_tmul] }
@[simp]
theorem counitCoalgHom_apply (x : A) :
counitCoalgHom R A x = counit x := rfl
@[simp]
theorem counitCoalgHom_toLinearMap :
counitCoalgHom R A = counit (R := R) (A := A) := rfl
variable {R}
instance subsingleton_to_ring : Subsingleton (A →ₗc[R] R) :=
⟨fun f g => CoalgHom.ext fun x => by
have hf := CoalgHomClass.counit_comp_apply f x
have hg := CoalgHomClass.counit_comp_apply g x
simp_all only [CommSemiring.counit_apply]⟩
@[ext high]
theorem ext_to_ring (f g : A →ₗc[R] R) : f = g := Subsingleton.elim _ _
variable {A B}
/--
If `φ : A → B` is a coalgebra map and `a = ∑ xᵢ ⊗ yᵢ`, then `φ a = ∑ φ xᵢ ⊗ φ yᵢ`
-/
@[simps]
def Repr.induced {a : A} (repr : Repr R a)
{F : Type*} [FunLike F A B] [CoalgHomClass F R A B]
(φ : F) : Repr R (φ a) where
index := repr.index
left := φ ∘ repr.left
right := φ ∘ repr.right
eq := (congr($((CoalgHomClass.map_comp_comul φ).symm) a).trans <|
by rw [LinearMap.comp_apply, ← repr.eq, map_sum]; rfl).symm
end Coalgebra
|
Option.lean
|
/-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.Data.Fintype.Option
import Mathlib.GroupTheory.Perm.Sign
/-!
# Permutations of `Option α`
-/
open Equiv
@[simp]
theorem Equiv.optionCongr_one {α : Type*} : (1 : Perm α).optionCongr = 1 :=
Equiv.optionCongr_refl
@[simp]
theorem Equiv.optionCongr_swap {α : Type*} [DecidableEq α] (x y : α) :
optionCongr (swap x y) = swap (some x) (some y) := by
ext (_ | i)
· simp [swap_apply_of_ne_of_ne]
· by_cases hx : i = x
· simp only [hx, optionCongr_apply, Option.map_some, swap_apply_left,
Option.some.injEq]
by_cases hy : i = y <;> simp [hx, hy, swap_apply_of_ne_of_ne]
@[simp]
theorem Equiv.optionCongr_sign {α : Type*} [DecidableEq α] [Fintype α] (e : Perm α) :
Perm.sign e.optionCongr = Perm.sign e := by
induction e using Perm.swap_induction_on with
| one => simp [Perm.one_def]
| swap_mul f x y hne h =>
simp [h, hne, Perm.mul_def]
@[simp]
theorem map_equiv_removeNone {α : Type*} [DecidableEq α] (σ : Perm (Option α)) :
(removeNone σ).optionCongr = swap none (σ none) * σ := by
ext1 x
have : Option.map (⇑(removeNone σ)) x = (swap none (σ none)) (σ x) := by
obtain - | x := x
· simp
· cases h : σ (some _)
· simp [removeNone_none _ h]
· have hn : σ (some x) ≠ none := by simp [h]
have hσn : σ (some x) ≠ σ none := σ.injective.ne (by simp)
simp [removeNone_some _ ⟨_, h⟩, ← h, swap_apply_of_ne_of_ne hn hσn]
simpa using this
/-- Permutations of `Option α` are equivalent to fixing an
`Option α` and permuting the remaining with a `Perm α`.
The fixed `Option α` is swapped with `none`. -/
@[simps]
def Equiv.Perm.decomposeOption {α : Type*} [DecidableEq α] :
Perm (Option α) ≃ Option α × Perm α where
toFun σ := (σ none, removeNone σ)
invFun i := swap none i.1 * i.2.optionCongr
left_inv σ := by simp
right_inv := fun ⟨x, σ⟩ => by
have : removeNone (swap none x * σ.optionCongr) = σ :=
Equiv.optionCongr_injective (by simp [← mul_assoc])
simp [this]
theorem Equiv.Perm.decomposeOption_symm_of_none_apply {α : Type*} [DecidableEq α] (e : Perm α)
(i : Option α) : Equiv.Perm.decomposeOption.symm (none, e) i = i.map e := by simp
theorem Equiv.Perm.decomposeOption_symm_sign {α : Type*} [DecidableEq α] [Fintype α] (e : Perm α) :
Perm.sign (Equiv.Perm.decomposeOption.symm (none, e)) = Perm.sign e := by simp
/-- The set of all permutations of `Option α` can be constructed by augmenting the set of
permutations of `α` by each element of `Option α` in turn. -/
theorem Finset.univ_perm_option {α : Type*} [DecidableEq α] [Fintype α] :
@Finset.univ (Perm <| Option α) _ =
(Finset.univ : Finset <| Option α × Perm α).map Equiv.Perm.decomposeOption.symm.toEmbedding :=
(Finset.univ_map_equiv_to_embedding _).symm
|
Option.lean
|
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import Mathlib.Algebra.Group.Action.Faithful
/-!
# Option instances for additive and multiplicative actions
This file defines instances for additive and multiplicative actions on `Option` type. Scalar
multiplication is defined by `a • some b = some (a • b)` and `a • none = none`.
## See also
* `Mathlib/Algebra/Group/Action/Pi.lean`
* `Mathlib/Algebra/Group/Action/Sigma.lean`
* `Mathlib/Algebra/Group/Action/Sum.lean`
-/
assert_not_exists MonoidWithZero
variable {M N α : Type*}
namespace Option
section SMul
variable [SMul M α] [SMul N α] (a : M) (b : α) (x : Option α)
@[to_additive Option.VAdd]
instance : SMul M (Option α) :=
⟨fun a => Option.map <| (a • ·)⟩
@[to_additive]
theorem smul_def : a • x = x.map (a • ·) :=
rfl
@[to_additive (attr := simp)]
theorem smul_none : a • (none : Option α) = none :=
rfl
@[to_additive (attr := simp)]
theorem smul_some : a • some b = some (a • b) :=
rfl
@[to_additive]
instance instIsScalarTowerOfSMul [SMul M N] [IsScalarTower M N α] : IsScalarTower M N (Option α) :=
⟨fun a b x => by
cases x
exacts [rfl, congr_arg some (smul_assoc _ _ _)]⟩
@[to_additive]
instance [SMulCommClass M N α] : SMulCommClass M N (Option α) :=
⟨fun _ _ => Function.Commute.option_map <| smul_comm _ _⟩
@[to_additive]
instance [SMul Mᵐᵒᵖ α] [IsCentralScalar M α] : IsCentralScalar M (Option α) :=
⟨fun a x => by
cases x
exacts [rfl, congr_arg some (op_smul_eq_smul _ _)]⟩
@[to_additive]
instance [FaithfulSMul M α] : FaithfulSMul M (Option α) :=
⟨fun h => eq_of_smul_eq_smul fun b : α => by injection h (some b)⟩
end SMul
instance [Monoid M] [MulAction M α] :
MulAction M (Option α) where
smul := (· • ·)
one_smul b := by
cases b
exacts [rfl, congr_arg some (one_smul _ _)]
mul_smul a₁ a₂ b := by
cases b
exacts [rfl, congr_arg some (mul_smul _ _ _)]
end Option
|
Germ.lean
|
/-
Copyright (c) 2023 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import Mathlib.Algebra.BigOperators.Group.Finset.Defs
import Mathlib.Algebra.Module.LinearMap.Defs
import Mathlib.Algebra.Order.Hom.Ring
import Mathlib.Order.Filter.Germ.Basic
import Mathlib.Topology.LocallyConstant.Basic
/-! # Germs of functions between topological spaces
In this file, we prove basic properties of germs of functions between topological spaces,
with respect to the neighbourhood filter `𝓝 x`.
## Main definitions and results
* `Filter.Germ.value φ f`: value associated to the germ `φ` at a point `x`, w.r.t. the
neighbourhood filter at `x`. This is the common value of all representatives of `φ` at `x`.
* `Filter.Germ.valueOrderRingHom` and friends: the map `Germ (𝓝 x) E → E` is a
monoid homomorphism, 𝕜-linear map, ring homomorphism, monotone ring homomorphism
* `RestrictGermPredicate`: given a predicate on germs `P : Π x : X, germ (𝓝 x) Y → Prop` and
`A : set X`, build a new predicate on germs `restrictGermPredicate P A` such that
`(∀ x, RestrictGermPredicate P A x f) ↔ ∀ᶠ x near A, P x f`;
`forall_restrictRermPredicate_iff` is this equivalence.
* `Filter.Germ.sliceLeft, sliceRight`: map the germ of functions `X × Y → Z` at `p = (x,y) ∈ X × Y`
to the corresponding germ of functions `X → Z` at `x ∈ X` resp. `Y → Z` at `y ∈ Y`.
* `eq_of_germ_isConstant`: if each germ of `f : X → Y` is constant and `X` is pre-connected,
`f` is constant.
-/
open scoped Topology
open Filter Set
variable {X Y Z : Type*} [TopologicalSpace X] {f g : X → Y} {A : Set X} {x : X}
namespace Filter.Germ
/-- The value associated to a germ at a point. This is the common value
shared by all representatives at the given point. -/
def value {X α : Type*} [TopologicalSpace X] {x : X} (φ : Germ (𝓝 x) α) : α :=
Quotient.liftOn' φ (fun f ↦ f x) fun f g h ↦ by dsimp only; rw [Eventually.self_of_nhds h]
theorem value_smul {α β : Type*} [SMul α β] (φ : Germ (𝓝 x) α)
(ψ : Germ (𝓝 x) β) : (φ • ψ).value = φ.value • ψ.value :=
Germ.inductionOn φ fun _ ↦ Germ.inductionOn ψ fun _ ↦ rfl
/-- The map `Germ (𝓝 x) E → E` into a monoid `E` as a monoid homomorphism -/
@[to_additive /-- The map `Germ (𝓝 x) E → E` as an additive monoid homomorphism -/]
def valueMulHom {X E : Type*} [Monoid E] [TopologicalSpace X] {x : X} : Germ (𝓝 x) E →* E where
toFun := Filter.Germ.value
map_one' := rfl
map_mul' φ ψ := Germ.inductionOn φ fun _ ↦ Germ.inductionOn ψ fun _ ↦ rfl
/-- The map `Germ (𝓝 x) E → E` into a `𝕜`-module `E` as a `𝕜`-linear map -/
def valueₗ {X 𝕜 E : Type*} [Semiring 𝕜] [AddCommMonoid E] [Module 𝕜 E] [TopologicalSpace X]
{x : X} : Germ (𝓝 x) E →ₗ[𝕜] E where
__ := Filter.Germ.valueAddHom
map_smul' := fun _ φ ↦ Germ.inductionOn φ fun _ ↦ rfl
/-- The map `Germ (𝓝 x) E → E` as a ring homomorphism -/
def valueRingHom {X E : Type*} [Semiring E] [TopologicalSpace X] {x : X} : Germ (𝓝 x) E →+* E :=
{ Filter.Germ.valueMulHom, Filter.Germ.valueAddHom with }
/-- The map `Germ (𝓝 x) E → E` as a monotone ring homomorphism -/
def valueOrderRingHom {X E : Type*} [Semiring E] [PartialOrder E] [TopologicalSpace X] {x : X} :
Germ (𝓝 x) E →+*o E where
__ := Filter.Germ.valueRingHom
monotone' := fun φ ψ ↦
Germ.inductionOn φ fun _ ↦ Germ.inductionOn ψ fun _ h ↦ h.self_of_nhds
end Filter.Germ
section RestrictGermPredicate
/-- Given a predicate on germs `P : Π x : X, germ (𝓝 x) Y → Prop` and `A : set X`,
build a new predicate on germs `RestrictGermPredicate P A` such that
`(∀ x, RestrictGermPredicate P A x f) ↔ ∀ᶠ x near A, P x f`, see
`forall_restrictGermPredicate_iff` for this equivalence. -/
def RestrictGermPredicate (P : ∀ x : X, Germ (𝓝 x) Y → Prop)
(A : Set X) : ∀ x : X, Germ (𝓝 x) Y → Prop := fun x φ ↦
Germ.liftOn φ (fun f ↦ x ∈ A → ∀ᶠ y in 𝓝 x, P y f)
haveI : ∀ f f' : X → Y, f =ᶠ[𝓝 x] f' → (∀ᶠ y in 𝓝 x, P y f) → ∀ᶠ y in 𝓝 x, P y f' := by
intro f f' hff' hf
apply (hf.and <| Eventually.eventually_nhds hff').mono
rintro y ⟨hy, hy'⟩
rwa [Germ.coe_eq.mpr (EventuallyEq.symm hy')]
fun f f' hff' ↦ propext <| forall_congr' fun _ ↦ ⟨this f f' hff', this f' f hff'.symm⟩
theorem Filter.Eventually.germ_congr_set
{P : ∀ x : X, Germ (𝓝 x) Y → Prop} (hf : ∀ᶠ x in 𝓝ˢ A, P x f)
(h : ∀ᶠ z in 𝓝ˢ A, g z = f z) : ∀ᶠ x in 𝓝ˢ A, P x g := by
rw [eventually_nhdsSet_iff_forall] at *
intro x hx
apply ((hf x hx).and (h x hx).eventually_nhds).mono
intro y hy
convert hy.1 using 1
exact Germ.coe_eq.mpr hy.2
theorem restrictGermPredicate_congr {P : ∀ x : X, Germ (𝓝 x) Y → Prop}
(hf : RestrictGermPredicate P A x f) (h : ∀ᶠ z in 𝓝ˢ A, g z = f z) :
RestrictGermPredicate P A x g := by
intro hx
apply ((hf hx).and <| (eventually_nhdsSet_iff_forall.mp h x hx).eventually_nhds).mono
rintro y ⟨hy, h'y⟩
rwa [Germ.coe_eq.mpr h'y]
theorem forall_restrictGermPredicate_iff {P : ∀ x : X, Germ (𝓝 x) Y → Prop} :
(∀ x, RestrictGermPredicate P A x f) ↔ ∀ᶠ x in 𝓝ˢ A, P x f := by
rw [eventually_nhdsSet_iff_forall]
rfl
theorem forall_restrictGermPredicate_of_forall
{P : ∀ x : X, Germ (𝓝 x) Y → Prop} (h : ∀ x, P x f) :
∀ x, RestrictGermPredicate P A x f :=
forall_restrictGermPredicate_iff.mpr (Eventually.of_forall h)
end RestrictGermPredicate
namespace Filter.Germ
/-- Map the germ of functions `X × Y → Z` at `p = (x,y) ∈ X × Y` to the corresponding germ
of functions `X → Z` at `x ∈ X` -/
def sliceLeft [TopologicalSpace Y] {p : X × Y} (P : Germ (𝓝 p) Z) : Germ (𝓝 p.1) Z :=
P.compTendsto (Prod.mk · p.2) (Continuous.prodMk_left p.2).continuousAt
@[simp]
theorem sliceLeft_coe [TopologicalSpace Y] {y : Y} (f : X × Y → Z) :
(↑f : Germ (𝓝 (x, y)) Z).sliceLeft = fun x' ↦ f (x', y) :=
rfl
/-- Map the germ of functions `X × Y → Z` at `p = (x,y) ∈ X × Y` to the corresponding germ
of functions `Y → Z` at `y ∈ Y` -/
def sliceRight [TopologicalSpace Y] {p : X × Y} (P : Germ (𝓝 p) Z) : Germ (𝓝 p.2) Z :=
P.compTendsto (Prod.mk p.1) (Continuous.prodMk_right p.1).continuousAt
@[simp]
theorem sliceRight_coe [TopologicalSpace Y] {y : Y} (f : X × Y → Z) :
(↑f : Germ (𝓝 (x, y)) Z).sliceRight = fun y' ↦ f (x, y') :=
rfl
lemma isConstant_comp_subtype {s : Set X} {f : X → Y} {x : s}
(hf : (f : Germ (𝓝 (x : X)) Y).IsConstant) :
((f ∘ Subtype.val : s → Y) : Germ (𝓝 x) Y).IsConstant :=
isConstant_comp_tendsto hf continuousAt_subtype_val
end Filter.Germ
/-- If the germ of `f` w.r.t. each `𝓝 x` is constant, `f` is locally constant. -/
lemma IsLocallyConstant.of_germ_isConstant (h : ∀ x : X, (f : Germ (𝓝 x) Y).IsConstant) :
IsLocallyConstant f := by
intro s
rw [isOpen_iff_mem_nhds]
intro a ha
obtain ⟨b, hb⟩ := h a
apply mem_of_superset hb
intro x hx
have : f x = f a := (mem_of_mem_nhds hb) ▸ hx
rw [mem_preimage, this]
exact ha
theorem eq_of_germ_isConstant [i : PreconnectedSpace X]
(h : ∀ x : X, (f : Germ (𝓝 x) Y).IsConstant) (x x' : X) : f x = f x' :=
(IsLocallyConstant.of_germ_isConstant h).apply_eq_of_isPreconnected
(preconnectedSpace_iff_univ.mp i) (by trivial) (by trivial)
lemma eq_of_germ_isConstant_on {s : Set X} (h : ∀ x ∈ s, (f : Germ (𝓝 x) Y).IsConstant)
(hs : IsPreconnected s) {x' : X} (x_in : x ∈ s) (x'_in : x' ∈ s) : f x = f x' := by
let i : s → X := fun x ↦ x
change (f ∘ i) (⟨x, x_in⟩ : s) = (f ∘ i) (⟨x', x'_in⟩ : s)
have : PreconnectedSpace s := Subtype.preconnectedSpace hs
exact eq_of_germ_isConstant (fun y ↦ Germ.isConstant_comp_subtype (h y y.2)) _ _
@[to_additive (attr := simp)]
theorem Germ.coe_prod {α : Type*} (l : Filter α) (R : Type*) [CommMonoid R] {ι} (f : ι → α → R)
(s : Finset ι) : ((∏ i ∈ s, f i : α → R) : Germ l R) = ∏ i ∈ s, (f i : Germ l R) :=
map_prod (Germ.coeMulHom l : (α → R) →* Germ l R) f s
|
ToNat.lean
|
/-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import Mathlib.SetTheory.Cardinal.ENat
/-!
# Projection from cardinal numbers to natural numbers
In this file we define `Cardinal.toNat` to be the natural projection `Cardinal → ℕ`,
sending all infinite cardinals to zero.
We also prove basic lemmas about this definition.
-/
assert_not_exists Field
universe u v
open Function Set
namespace Cardinal
variable {α : Type u} {c d : Cardinal.{u}}
/-- This function sends finite cardinals to the corresponding natural, and infinite cardinals
to 0. -/
noncomputable def toNat : Cardinal →*₀ ℕ :=
ENat.toNatHom.comp toENat
@[simp] lemma toNat_toENat (a : Cardinal) : ENat.toNat (toENat a) = toNat a := rfl
@[simp]
theorem toNat_ofENat (n : ℕ∞) : toNat n = ENat.toNat n :=
congr_arg ENat.toNat <| toENat_ofENat n
@[simp, norm_cast] theorem toNat_natCast (n : ℕ) : toNat n = n := toNat_ofENat n
@[simp]
lemma toNat_eq_zero : toNat c = 0 ↔ c = 0 ∨ ℵ₀ ≤ c := by
rw [← toNat_toENat, ENat.toNat_eq_zero, toENat_eq_zero, toENat_eq_top]
lemma toNat_ne_zero : toNat c ≠ 0 ↔ c ≠ 0 ∧ c < ℵ₀ := by simp [not_or]
@[simp] lemma toNat_pos : 0 < toNat c ↔ c ≠ 0 ∧ c < ℵ₀ := pos_iff_ne_zero.trans toNat_ne_zero
theorem cast_toNat_of_lt_aleph0 {c : Cardinal} (h : c < ℵ₀) : ↑(toNat c) = c := by
lift c to ℕ using h
rw [toNat_natCast]
theorem toNat_apply_of_lt_aleph0 {c : Cardinal.{u}} (h : c < ℵ₀) :
toNat c = Classical.choose (lt_aleph0.1 h) :=
Nat.cast_injective (R := Cardinal.{u}) <| by
rw [cast_toNat_of_lt_aleph0 h, ← Classical.choose_spec (lt_aleph0.1 h)]
theorem toNat_apply_of_aleph0_le {c : Cardinal} (h : ℵ₀ ≤ c) : toNat c = 0 := by simp [h]
theorem cast_toNat_of_aleph0_le {c : Cardinal} (h : ℵ₀ ≤ c) : ↑(toNat c) = (0 : Cardinal) := by
rw [toNat_apply_of_aleph0_le h, Nat.cast_zero]
theorem cast_toNat_eq_iff_lt_aleph0 {c : Cardinal} : (toNat c) = c ↔ c < ℵ₀ := by
constructor
· intro h; by_contra h'; rw [not_lt] at h'
rw [toNat_apply_of_aleph0_le h'] at h; rw [← h] at h'
absurd h'; rw [not_le]; exact nat_lt_aleph0 0
· exact fun h ↦ (Cardinal.cast_toNat_of_lt_aleph0 h)
theorem toNat_strictMonoOn : StrictMonoOn toNat (Iio ℵ₀) := by
simp only [← range_natCast, StrictMonoOn, forall_mem_range, toNat_natCast, Nat.cast_lt]
exact fun _ _ ↦ id
theorem toNat_monotoneOn : MonotoneOn toNat (Iio ℵ₀) := toNat_strictMonoOn.monotoneOn
theorem toNat_injOn : InjOn toNat (Iio ℵ₀) := toNat_strictMonoOn.injOn
/-- Two finite cardinals are equal
iff they are equal their `Cardinal.toNat` projections are equal. -/
theorem toNat_inj_of_lt_aleph0 (hc : c < ℵ₀) (hd : d < ℵ₀) :
toNat c = toNat d ↔ c = d :=
toNat_injOn.eq_iff hc hd
theorem toNat_le_iff_le_of_lt_aleph0 (hc : c < ℵ₀) (hd : d < ℵ₀) :
toNat c ≤ toNat d ↔ c ≤ d :=
toNat_strictMonoOn.le_iff_le hc hd
theorem toNat_lt_iff_lt_of_lt_aleph0 (hc : c < ℵ₀) (hd : d < ℵ₀) :
toNat c < toNat d ↔ c < d :=
toNat_strictMonoOn.lt_iff_lt hc hd
@[gcongr]
theorem toNat_le_toNat (hcd : c ≤ d) (hd : d < ℵ₀) : toNat c ≤ toNat d :=
toNat_monotoneOn (hcd.trans_lt hd) hd hcd
theorem toNat_lt_toNat (hcd : c < d) (hd : d < ℵ₀) : toNat c < toNat d :=
toNat_strictMonoOn (hcd.trans hd) hd hcd
@[simp]
theorem toNat_ofNat (n : ℕ) [n.AtLeastTwo] :
Cardinal.toNat ofNat(n) = OfNat.ofNat n :=
toNat_natCast n
/-- `toNat` has a right-inverse: coercion. -/
theorem toNat_rightInverse : Function.RightInverse ((↑) : ℕ → Cardinal) toNat :=
toNat_natCast
theorem toNat_surjective : Surjective toNat :=
toNat_rightInverse.surjective
@[simp]
theorem mk_toNat_of_infinite [h : Infinite α] : toNat #α = 0 := by simp
@[simp]
theorem aleph0_toNat : toNat ℵ₀ = 0 :=
toNat_apply_of_aleph0_le le_rfl
theorem mk_toNat_eq_card [Fintype α] : toNat #α = Fintype.card α := by simp
@[simp]
theorem zero_toNat : toNat 0 = 0 := map_zero _
theorem one_toNat : toNat 1 = 1 := map_one _
theorem toNat_eq_iff {n : ℕ} (hn : n ≠ 0) : toNat c = n ↔ c = n := by
rw [← toNat_toENat, ENat.toNat_eq_iff hn, toENat_eq_nat]
/-- A version of `toNat_eq_iff` for literals -/
theorem toNat_eq_ofNat {n : ℕ} [Nat.AtLeastTwo n] :
toNat c = OfNat.ofNat n ↔ c = OfNat.ofNat n :=
toNat_eq_iff <| OfNat.ofNat_ne_zero n
@[simp]
theorem toNat_eq_one : toNat c = 1 ↔ c = 1 := by
rw [toNat_eq_iff one_ne_zero, Nat.cast_one]
theorem toNat_eq_one_iff_unique : toNat #α = 1 ↔ Subsingleton α ∧ Nonempty α :=
toNat_eq_one.trans eq_one_iff_unique
@[simp]
theorem toNat_lift (c : Cardinal.{v}) : toNat (lift.{u, v} c) = toNat c := by
simp only [← toNat_toENat, toENat_lift]
theorem toNat_congr {β : Type v} (e : α ≃ β) : toNat #α = toNat #β := by
-- Porting note: Inserted universe hint below
rw [← toNat_lift, (lift_mk_eq.{_,_,v}).mpr ⟨e⟩, toNat_lift]
theorem toNat_mul (x y : Cardinal) : toNat (x * y) = toNat x * toNat y := map_mul toNat x y
@[simp]
theorem toNat_add (hc : c < ℵ₀) (hd : d < ℵ₀) : toNat (c + d) = toNat c + toNat d := by
lift c to ℕ using hc
lift d to ℕ using hd
norm_cast
theorem toNat_lift_add_lift {a : Cardinal.{u}} {b : Cardinal.{v}} (ha : a < ℵ₀) (hb : b < ℵ₀) :
toNat (lift.{v} a + lift.{u} b) = toNat a + toNat b := by
simp [*]
end Cardinal
|
Transfer.lean
|
/-
Copyright (c) 2022 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison
-/
import Mathlib.CategoryTheory.Abelian.Basic
import Mathlib.CategoryTheory.Adjunction.Limits
import Mathlib.CategoryTheory.Limits.Preserves.Shapes.AbelianImages
import Mathlib.CategoryTheory.Preadditive.Transfer
/-!
# Transferring "abelian-ness" across a functor
If `C` is an additive category, `D` is an abelian category,
we have `F : C ⥤ D` `G : D ⥤ C` (both preserving zero morphisms),
`G` is left exact (that is, preserves finite limits),
and further we have `adj : G ⊣ F` and `i : F ⋙ G ≅ 𝟭 C`,
then `C` is also abelian.
A particular example is the transfer of `Abelian` instances from a category `C` to `ShrinkHoms C`;
see `ShrinkHoms.abelian`. In this case, we also transfer the `Preadditive` structure.
See <https://stacks.math.columbia.edu/tag/03A3>
## Notes
The hypotheses, following the statement from the Stacks project,
may appear surprising: we don't ask that the counit of the adjunction is an isomorphism,
but just that we have some potentially unrelated isomorphism `i : F ⋙ G ≅ 𝟭 C`.
However Lemma A1.1.1 from [Elephant] shows that in this situation the counit itself
must be an isomorphism, and thus that `C` is a reflective subcategory of `D`.
Someone may like to formalize that lemma, and restate this theorem in terms of `Reflective`.
(That lemma has a nice string diagrammatic proof that holds in any bicategory.)
-/
noncomputable section
namespace CategoryTheory
open Limits
universe v₁ v₂ u₁ u₂
namespace AbelianOfAdjunction
variable {C : Type u₁} [Category.{v₁} C] [Preadditive C]
variable {D : Type u₂} [Category.{v₂} D] [Abelian D]
variable (F : C ⥤ D)
variable (G : D ⥤ C) [Functor.PreservesZeroMorphisms G]
/-- No point making this an instance, as it requires `i`. -/
theorem hasKernels [PreservesFiniteLimits G] (i : F ⋙ G ≅ 𝟭 C) : HasKernels C :=
{ has_limit := fun f => by
have := NatIso.naturality_1 i f
simp? at this says
simp only [Functor.id_obj, Functor.comp_obj, Functor.comp_map, Functor.id_map] at this
rw [← this]
haveI : HasKernel (G.map (F.map f) ≫ i.hom.app _) := Limits.hasKernel_comp_mono _ _
apply Limits.hasKernel_iso_comp }
/-- No point making this an instance, as it requires `i` and `adj`. -/
theorem hasCokernels (i : F ⋙ G ≅ 𝟭 C) (adj : G ⊣ F) : HasCokernels C :=
{ has_colimit := fun f => by
have : PreservesColimits G := adj.leftAdjoint_preservesColimits
have := NatIso.naturality_1 i f
simp? at this says
simp only [Functor.id_obj, Functor.comp_obj, Functor.comp_map, Functor.id_map] at this
rw [← this]
haveI : HasCokernel (G.map (F.map f) ≫ i.hom.app _) := Limits.hasCokernel_comp_iso _ _
apply Limits.hasCokernel_epi_comp }
end AbelianOfAdjunction
open AbelianOfAdjunction
/-- If `C` is an additive category, `D` is an abelian category,
we have `F : C ⥤ D` `G : D ⥤ C` (with `G` preserving zero morphisms),
`G` is left exact (that is, preserves finite limits),
and further we have `adj : G ⊣ F` and `i : F ⋙ G ≅ 𝟭 C`,
then `C` is also abelian. -/
@[stacks 03A3]
def abelianOfAdjunction {C : Type u₁} [Category.{v₁} C] [Preadditive C] [HasFiniteProducts C]
{D : Type u₂} [Category.{v₂} D] [Abelian D] (F : C ⥤ D)
(G : D ⥤ C) [Functor.PreservesZeroMorphisms G] [PreservesFiniteLimits G] (i : F ⋙ G ≅ 𝟭 C)
(adj : G ⊣ F) : Abelian C := by
haveI := hasKernels F G i
haveI := hasCokernels F G i adj
have : ∀ {X Y : C} (f : X ⟶ Y), IsIso (Abelian.coimageImageComparison f) := by
intro X Y f
let arrowIso : Arrow.mk (G.map (F.map f)) ≅ Arrow.mk f :=
((Functor.mapArrowFunctor _ _).mapIso i).app (Arrow.mk f)
have : PreservesColimits G := adj.leftAdjoint_preservesColimits
let iso : Arrow.mk (G.map (Abelian.coimageImageComparison (F.map f))) ≅
Arrow.mk (Abelian.coimageImageComparison f) :=
Abelian.PreservesCoimageImageComparison.iso G (F.map f) ≪≫
Abelian.coimageImageComparisonFunctor.mapIso arrowIso
rw [Arrow.isIso_iff_isIso_of_isIso iso.inv]
infer_instance
apply Abelian.ofCoimageImageComparisonIsIso
/-- If `C` is an additive category equivalent to an abelian category `D`
via a functor that preserves zero morphisms,
then `C` is also abelian.
-/
def abelianOfEquivalence {C : Type u₁} [Category.{v₁} C] [Preadditive C] [HasFiniteProducts C]
{D : Type u₂} [Category.{v₂} D] [Abelian D] (F : C ⥤ D)
[F.IsEquivalence] : Abelian C :=
abelianOfAdjunction F F.inv F.asEquivalence.unitIso.symm F.asEquivalence.symm.toAdjunction
namespace ShrinkHoms
universe w
variable {C : Type*} [Category C] [LocallySmall.{w} C]
section Preadditive
variable [Preadditive C]
variable (C)
instance preadditive : Preadditive.{w} (ShrinkHoms C) :=
.ofFullyFaithful (equivalence C).fullyFaithfulInverse
instance : (inverse C).Additive :=
(equivalence C).symm.fullyFaithfulFunctor.additive_ofFullyFaithful
instance : (functor C).Additive :=
(equivalence C).symm.additive_inverse_of_FullyFaithful
instance hasLimitsOfShape (J : Type*) [Category J]
[HasLimitsOfShape J C] : HasLimitsOfShape.{_, _, w} J (ShrinkHoms C) :=
Adjunction.hasLimitsOfShape_of_equivalence (inverse C)
instance hasFiniteLimits [HasFiniteLimits C] :
HasFiniteLimits.{w} (ShrinkHoms C) := ⟨fun _ => inferInstance⟩
end Preadditive
variable (C) in
noncomputable instance abelian [Abelian C] :
Abelian.{w} (ShrinkHoms C) := abelianOfEquivalence (inverse C)
end ShrinkHoms
namespace AsSmall
universe w v u
variable {C : Type u} [Category.{v} C]
section Preadditive
variable [Preadditive C]
variable (C)
instance preadditive : Preadditive (AsSmall.{w} C) :=
.ofFullyFaithful equiv.fullyFaithfulInverse
instance : (down (C := C)).Additive :=
equiv.symm.fullyFaithfulFunctor.additive_ofFullyFaithful
instance : (up (C := C)).Additive :=
equiv.symm.additive_inverse_of_FullyFaithful
instance hasLimitsOfShape (J : Type*) [Category J]
[HasLimitsOfShape J C] : HasLimitsOfShape.{_, _, max u v w} J (AsSmall.{w} C) :=
Adjunction.hasLimitsOfShape_of_equivalence equiv.inverse
instance hasFiniteLimits [HasFiniteLimits C] :
HasFiniteLimits (AsSmall.{w} C) := ⟨fun _ => inferInstance⟩
end Preadditive
variable (C) in
noncomputable instance abelian [Abelian C] :
Abelian (AsSmall.{w} C) := abelianOfEquivalence equiv.inverse
end AsSmall
end CategoryTheory
|
Prod.lean
|
/-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import Mathlib.MeasureTheory.Measure.GiryMonad
import Mathlib.MeasureTheory.Measure.OpenPos
/-!
# The product measure
In this file we define and prove properties about the binary product measure. If `α` and `β` have
s-finite measures `μ` resp. `ν` then `α × β` can be equipped with a s-finite measure `μ.prod ν` that
satisfies `(μ.prod ν) s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`.
We also have `(μ.prod ν) (s ×ˢ t) = μ s * ν t`, i.e. the measure of a rectangle is the product of
the measures of the sides.
We also prove Tonelli's theorem.
## Main definition
* `MeasureTheory.Measure.prod`: The product of two measures.
## Main results
* `MeasureTheory.Measure.prod_apply` states `μ.prod ν s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`
for measurable `s`. `MeasureTheory.Measure.prod_apply_symm` is the reversed version.
* `MeasureTheory.Measure.prod_prod` states `μ.prod ν (s ×ˢ t) = μ s * ν t` for measurable sets
`s` and `t`.
* `MeasureTheory.lintegral_prod`: Tonelli's theorem. It states that for a measurable function
`α × β → ℝ≥0∞` we have `∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ`. The version
for functions `α → β → ℝ≥0∞` is reversed, and called `lintegral_lintegral`. Both versions have
a variant with `_symm` appended, where the order of integration is reversed.
The lemma `Measurable.lintegral_prod_right'` states that the inner integral of the right-hand side
is measurable.
## Implementation Notes
Many results are proven twice, once for functions in curried form (`α → β → γ`) and one for
functions in uncurried form (`α × β → γ`). The former often has an assumption
`Measurable (uncurry f)`, which could be inconvenient to discharge, but for the latter it is more
common that the function has to be given explicitly, since Lean cannot synthesize the function by
itself. We name the lemmas about the uncurried form with a prime.
Tonelli's theorem has a different naming scheme, since the version for the uncurried version is
reversed.
## Tags
product measure, Tonelli's theorem, Fubini-Tonelli theorem
-/
noncomputable section
open Topology ENNReal MeasureTheory Set Function Real ENNReal MeasurableSpace MeasureTheory.Measure
open TopologicalSpace hiding generateFrom
open Filter hiding prod_eq map
variable {α β γ : Type*}
variable [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ]
variable {μ μ' : Measure α} {ν ν' : Measure β} {τ : Measure γ}
/-- If `ν` is a finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is
a measurable function. `measurable_measure_prodMk_left` is strictly more general. -/
theorem measurable_measure_prodMk_left_finite [IsFiniteMeasure ν] {s : Set (α × β)}
(hs : MeasurableSet s) : Measurable fun x => ν (Prod.mk x ⁻¹' s) := by
induction s, hs using induction_on_inter generateFrom_prod.symm isPiSystem_prod with
| empty => simp
| basic s hs =>
obtain ⟨s, hs, t, -, rfl⟩ := hs
classical simpa only [mk_preimage_prod_right_eq_if, measure_if]
using measurable_const.indicator hs
| compl s hs ihs =>
simp_rw [preimage_compl, measure_compl (measurable_prodMk_left hs) (measure_ne_top ν _)]
exact ihs.const_sub _
| iUnion f hfd hfm ihf =>
have (a : α) : ν (Prod.mk a ⁻¹' ⋃ i, f i) = ∑' i, ν (Prod.mk a ⁻¹' f i) := by
rw [preimage_iUnion, measure_iUnion]
exacts [hfd.mono fun _ _ ↦ .preimage _, fun i ↦ measurable_prodMk_left (hfm i)]
simpa only [this] using Measurable.ennreal_tsum ihf
@[deprecated (since := "2025-03-05")]
alias measurable_measure_prod_mk_left_finite := measurable_measure_prodMk_left_finite
/-- If `ν` is an s-finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }`
is a measurable function.
Not true without the s-finite assumption: on `ℝ × ℝ` with the product sigma-algebra, let `s` be the
diagonal and let `ν` be an uncountable sum of Dirac measures (all Dirac measures for points in a
set `t`). Then `ν (Prod.mk x ⁻¹' s) = ν {x} = if x ∈ t then 1 else 0`. If `t` is chosen
non-measurable, this will not be measurable. -/
theorem measurable_measure_prodMk_left [SFinite ν] {s : Set (α × β)} (hs : MeasurableSet s) :
Measurable fun x => ν (Prod.mk x ⁻¹' s) := by
rw [← sum_sfiniteSeq ν]
simp_rw [Measure.sum_apply_of_countable]
exact Measurable.ennreal_tsum (fun i ↦ measurable_measure_prodMk_left_finite hs)
@[deprecated (since := "2025-03-05")]
alias measurable_measure_prod_mk_left := measurable_measure_prodMk_left
/-- If `μ` is an s-finite measure, and `s ⊆ α × β` is measurable, then `y ↦ μ { x | (x, y) ∈ s }` is
a measurable function. -/
theorem measurable_measure_prodMk_right {μ : Measure α} [SFinite μ] {s : Set (α × β)}
(hs : MeasurableSet s) : Measurable fun y => μ ((fun x => (x, y)) ⁻¹' s) :=
measurable_measure_prodMk_left (measurableSet_swap_iff.mpr hs)
@[deprecated (since := "2025-03-05")]
alias measurable_measure_prod_mk_right := measurable_measure_prodMk_right
theorem Measurable.map_prodMk_left [SFinite ν] :
Measurable fun x : α => map (Prod.mk x) ν := by
apply measurable_of_measurable_coe; intro s hs
simp_rw [map_apply measurable_prodMk_left hs]
exact measurable_measure_prodMk_left hs
@[deprecated (since := "2025-03-05")]
alias Measurable.map_prod_mk_left := Measurable.map_prodMk_left
theorem Measurable.map_prodMk_right {μ : Measure α} [SFinite μ] :
Measurable fun y : β => map (fun x : α => (x, y)) μ := by
apply measurable_of_measurable_coe; intro s hs
simp_rw [map_apply measurable_prodMk_right hs]
exact measurable_measure_prodMk_right hs
@[deprecated (since := "2025-03-05")]
alias Measurable.map_prod_mk_right := Measurable.map_prodMk_right
/-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of)
Tonelli's theorem is measurable. -/
@[fun_prop, measurability]
theorem Measurable.lintegral_prod_right' [SFinite ν] :
∀ {f : α × β → ℝ≥0∞}, Measurable f → Measurable fun x => ∫⁻ y, f (x, y) ∂ν := by
have m := @measurable_prodMk_left
refine Measurable.ennreal_induction (motive := fun f ↦ Measurable fun (x : α) ↦ ∫⁻ y, f (x, y) ∂ν)
?_ ?_ ?_
· intro c s hs
simp only [← indicator_comp_right]
suffices Measurable fun x => c * ν (Prod.mk x ⁻¹' s) by simpa [lintegral_indicator (m hs)]
exact (measurable_measure_prodMk_left hs).const_mul _
· rintro f g - hf - h2f h2g
simp only [Pi.add_apply]
conv => enter [1, x]; erw [lintegral_add_left (hf.comp m)]
exact h2f.add h2g
· intro f hf h2f h3f
have : ∀ x, Monotone fun n y => f n (x, y) := fun x i j hij y => h2f hij (x, y)
conv => enter [1, x]; erw [lintegral_iSup (fun n => (hf n).comp m) (this x)]
exact .iSup h3f
/-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of)
Tonelli's theorem is measurable.
This version has the argument `f` in curried form. -/
@[fun_prop, measurability]
theorem Measurable.lintegral_prod_right [SFinite ν] {f : α → β → ℝ≥0∞}
(hf : Measurable (uncurry f)) : Measurable fun x => ∫⁻ y, f x y ∂ν :=
hf.lintegral_prod_right'
/-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of)
the symmetric version of Tonelli's theorem is measurable. -/
@[fun_prop, measurability]
theorem Measurable.lintegral_prod_left' [SFinite μ] {f : α × β → ℝ≥0∞} (hf : Measurable f) :
Measurable fun y => ∫⁻ x, f (x, y) ∂μ :=
(measurable_swap_iff.mpr hf).lintegral_prod_right'
/-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of)
the symmetric version of Tonelli's theorem is measurable.
This version has the argument `f` in curried form. -/
@[fun_prop, measurability]
theorem Measurable.lintegral_prod_left [SFinite μ] {f : α → β → ℝ≥0∞}
(hf : Measurable (uncurry f)) : Measurable fun y => ∫⁻ x, f x y ∂μ :=
hf.lintegral_prod_left'
/-! ### The product measure -/
namespace MeasureTheory
namespace Measure
/-- The binary product of measures. They are defined for arbitrary measures, but we basically
prove all properties under the assumption that at least one of them is s-finite. -/
protected irreducible_def prod (μ : Measure α) (ν : Measure β) : Measure (α × β) :=
bind μ fun x : α => map (Prod.mk x) ν
instance prod.measureSpace {α β} [MeasureSpace α] [MeasureSpace β] : MeasureSpace (α × β) where
volume := volume.prod volume
theorem volume_eq_prod (α β) [MeasureSpace α] [MeasureSpace β] :
(volume : Measure (α × β)) = (volume : Measure α).prod (volume : Measure β) :=
rfl
/-- For an s-finite measure `ν`, see `prod_apply` below. -/
theorem prod_apply_le {s : Set (α × β)} (hs : MeasurableSet s) :
μ.prod ν s ≤ ∫⁻ x, ν (Prod.mk x ⁻¹' s) ∂μ := by
simp only [Measure.prod, ← map_apply measurable_prodMk_left hs]
exact bind_apply_le _ hs
/-- For any measures `μ` and `ν` and any sets `s` and `t`,
we have `μ.prod ν (s ×ˢ t) ≤ μ s * ν t`.
If `ν` is an s-finite measure (which is usually true),
then this inequality becomes an equality, see `prod_prod` below. -/
theorem prod_prod_le (s : Set α) (t : Set β) : μ.prod ν (s ×ˢ t) ≤ μ s * ν t := by
set S := toMeasurable μ s
set T := toMeasurable ν t
calc
μ.prod ν (s ×ˢ t) ≤ μ.prod ν (S ×ˢ T) := by gcongr <;> apply subset_toMeasurable
_ ≤ ∫⁻ x, ν (Prod.mk x ⁻¹' (S ×ˢ T)) ∂μ := prod_apply_le (by measurability)
_ = μ S * ν T := by
classical
simp_rw [S, mk_preimage_prod_right_eq_if, measure_if,
lintegral_indicator (measurableSet_toMeasurable _ _), lintegral_const,
restrict_apply_univ, mul_comm]
_ = μ s * ν t := by rw [measure_toMeasurable, measure_toMeasurable]
instance prod.instNoAtoms_fst [NoAtoms μ] :
NoAtoms (Measure.prod μ ν) where
measure_singleton
| (x, y) => nonpos_iff_eq_zero.mp <| calc
μ.prod ν {(x, y)} = μ.prod ν ({x} ×ˢ {y}) := by rw [singleton_prod_singleton]
_ ≤ μ {x} * ν {y} := prod_prod_le _ _
_ = 0 := by simp
instance prod.instNoAtoms_snd [NoAtoms ν] :
NoAtoms (Measure.prod μ ν) where
measure_singleton
| (x, y) => nonpos_iff_eq_zero.mp <| calc
μ.prod ν {(x, y)} = μ.prod ν ({x} ×ˢ {y}) := by rw [singleton_prod_singleton]
_ ≤ μ {x} * ν {y} := prod_prod_le _ _
_ = 0 := by simp
variable [SFinite ν]
theorem prod_apply {s : Set (α × β)} (hs : MeasurableSet s) :
μ.prod ν s = ∫⁻ x, ν (Prod.mk x ⁻¹' s) ∂μ := by
simp_rw [Measure.prod, bind_apply hs (Measurable.map_prodMk_left (ν := ν)).aemeasurable,
map_apply measurable_prodMk_left hs]
/-- The product measure of the product of two sets is the product of their measures. Note that we
do not need the sets to be measurable. -/
@[simp]
theorem prod_prod (s : Set α) (t : Set β) : μ.prod ν (s ×ˢ t) = μ s * ν t := by
apply (prod_prod_le s t).antisymm
-- Formalization is based on https://mathoverflow.net/a/254134/136589
set ST := toMeasurable (μ.prod ν) (s ×ˢ t)
have hSTm : MeasurableSet ST := measurableSet_toMeasurable _ _
have hST : s ×ˢ t ⊆ ST := subset_toMeasurable _ _
set f : α → ℝ≥0∞ := fun x => ν (Prod.mk x ⁻¹' ST)
have hfm : Measurable f := measurable_measure_prodMk_left hSTm
set s' : Set α := { x | ν t ≤ f x }
have hss' : s ⊆ s' := fun x hx => measure_mono fun y hy => hST <| mk_mem_prod hx hy
calc
μ s * ν t ≤ μ s' * ν t := by gcongr
_ = ∫⁻ _ in s', ν t ∂μ := by rw [setLIntegral_const, mul_comm]
_ ≤ ∫⁻ x in s', f x ∂μ := setLIntegral_mono hfm fun x => id
_ ≤ ∫⁻ x, f x ∂μ := lintegral_mono' restrict_le_self le_rfl
_ = μ.prod ν ST := (prod_apply hSTm).symm
_ = μ.prod ν (s ×ˢ t) := measure_toMeasurable _
@[simp]
theorem _root_.MeasureTheory.measureReal_prod_prod (s : Set α) (t : Set β) :
(μ.prod ν).real (s ×ˢ t) = μ.real s * ν.real t := by
simp only [measureReal_def, prod_prod, ENNReal.toReal_mul]
@[simp] lemma map_fst_prod : Measure.map Prod.fst (μ.prod ν) = (ν univ) • μ := by
ext s hs
simp [Measure.map_apply measurable_fst hs, ← prod_univ, mul_comm]
lemma _root_.MeasureTheory.measurePreserving_fst [IsProbabilityMeasure ν] :
MeasurePreserving Prod.fst (μ.prod ν) μ :=
⟨measurable_fst, by rw [map_fst_prod, measure_univ, one_smul]⟩
@[simp] lemma map_snd_prod : Measure.map Prod.snd (μ.prod ν) = (μ univ) • ν := by
ext s hs
simp [Measure.map_apply measurable_snd hs, ← univ_prod]
lemma _root_.MeasureTheory.measurePreserving_snd [IsProbabilityMeasure μ] :
MeasurePreserving Prod.snd (μ.prod ν) ν :=
⟨measurable_snd, by rw [map_snd_prod, measure_univ, one_smul]⟩
instance prod.instIsOpenPosMeasure {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y]
{m : MeasurableSpace X} {μ : Measure X} [IsOpenPosMeasure μ] {m' : MeasurableSpace Y}
{ν : Measure Y} [IsOpenPosMeasure ν] [SFinite ν] : IsOpenPosMeasure (μ.prod ν) := by
constructor
rintro U U_open ⟨⟨x, y⟩, hxy⟩
rcases isOpen_prod_iff.1 U_open x y hxy with ⟨u, v, u_open, v_open, xu, yv, huv⟩
refine ne_of_gt (lt_of_lt_of_le ?_ (measure_mono huv))
simp only [prod_prod, CanonicallyOrderedAdd.mul_pos]
constructor
· exact u_open.measure_pos μ ⟨x, xu⟩
· exact v_open.measure_pos ν ⟨y, yv⟩
instance {X Y : Type*}
[TopologicalSpace X] [MeasureSpace X] [IsOpenPosMeasure (volume : Measure X)]
[TopologicalSpace Y] [MeasureSpace Y] [IsOpenPosMeasure (volume : Measure Y)]
[SFinite (volume : Measure Y)] : IsOpenPosMeasure (volume : Measure (X × Y)) :=
prod.instIsOpenPosMeasure
instance prod.instIsFiniteMeasure {α β : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β}
(μ : Measure α) (ν : Measure β) [IsFiniteMeasure μ] [IsFiniteMeasure ν] :
IsFiniteMeasure (μ.prod ν) := by
constructor
rw [← univ_prod_univ, prod_prod]
finiteness
instance {α β : Type*} [MeasureSpace α] [MeasureSpace β] [IsFiniteMeasure (volume : Measure α)]
[IsFiniteMeasure (volume : Measure β)] : IsFiniteMeasure (volume : Measure (α × β)) :=
prod.instIsFiniteMeasure _ _
instance prod.instIsProbabilityMeasure {α β : Type*} {mα : MeasurableSpace α}
{mβ : MeasurableSpace β} (μ : Measure α) (ν : Measure β) [IsProbabilityMeasure μ]
[IsProbabilityMeasure ν] : IsProbabilityMeasure (μ.prod ν) :=
⟨by rw [← univ_prod_univ, prod_prod, measure_univ, measure_univ, mul_one]⟩
instance {α β : Type*} [MeasureSpace α] [MeasureSpace β]
[IsProbabilityMeasure (volume : Measure α)] [IsProbabilityMeasure (volume : Measure β)] :
IsProbabilityMeasure (volume : Measure (α × β)) :=
prod.instIsProbabilityMeasure _ _
instance prod.instIsFiniteMeasureOnCompacts {α β : Type*} [TopologicalSpace α] [TopologicalSpace β]
{mα : MeasurableSpace α} {mβ : MeasurableSpace β} (μ : Measure α) (ν : Measure β)
[IsFiniteMeasureOnCompacts μ] [IsFiniteMeasureOnCompacts ν] :
IsFiniteMeasureOnCompacts (μ.prod ν) where
lt_top_of_isCompact K hK := calc
μ.prod ν K ≤ μ.prod ν ((Prod.fst '' K) ×ˢ (Prod.snd '' K)) := measure_mono subset_prod
_ ≤ μ (Prod.fst '' K) * ν (Prod.snd '' K) := prod_prod_le _ _
_ < ∞ :=
mul_lt_top (hK.image continuous_fst).measure_lt_top (hK.image continuous_snd).measure_lt_top
instance {X Y : Type*}
[TopologicalSpace X] [MeasureSpace X] [IsFiniteMeasureOnCompacts (volume : Measure X)]
[TopologicalSpace Y] [MeasureSpace Y] [IsFiniteMeasureOnCompacts (volume : Measure Y)] :
IsFiniteMeasureOnCompacts (volume : Measure (X × Y)) :=
prod.instIsFiniteMeasureOnCompacts _ _
theorem ae_measure_lt_top {s : Set (α × β)} (hs : MeasurableSet s) (h2s : (μ.prod ν) s ≠ ∞) :
∀ᵐ x ∂μ, ν (Prod.mk x ⁻¹' s) < ∞ := by
rw [prod_apply hs] at h2s
exact ae_lt_top (measurable_measure_prodMk_left hs) h2s
omit [SFinite ν] in
/-- If `μ`-a.e. section `{y | (x, y) ∈ s}` of a measurable set have `ν` measure zero,
then `s` has `μ.prod ν` measure zero.
This implication requires `s` to be measurable but does not require `ν` to be s-finite.
See also `measure_prod_null` and `measure_ae_null_of_prod_null` below. -/
theorem measure_prod_null_of_ae_null {s : Set (α × β)} (hsm : MeasurableSet s)
(hs : (fun x => ν (Prod.mk x ⁻¹' s)) =ᵐ[μ] 0) : μ.prod ν s = 0 := by
rw [← nonpos_iff_eq_zero]
calc
μ.prod ν s ≤ ∫⁻ x, ν (Prod.mk x ⁻¹' s) ∂μ := prod_apply_le hsm
_ = 0 := by simp [lintegral_congr_ae hs]
/-- A measurable set `s` has `μ.prod ν` measure zero, where `ν` is an s-finite measure,
if and only if `μ`-a.e. section `{y | (x, y) ∈ s}` of `s` have `ν` measure zero.
See `measure_ae_null_of_prod_null` for the forward implication without the measurability assumption
and `measure_prod_null_of_ae_null` for the reverse implication without the s-finiteness assumption.
Note: the assumption `hs` cannot be dropped. For a counterexample, see
Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/
theorem measure_prod_null {s : Set (α × β)} (hs : MeasurableSet s) :
μ.prod ν s = 0 ↔ (fun x => ν (Prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by
rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prodMk_left hs)]
/-- Note: the converse is not true without assuming that `s` is measurable. For a counterexample,
see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/
theorem measure_ae_null_of_prod_null {s : Set (α × β)} (h : μ.prod ν s = 0) :
(fun x => ν (Prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by
obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h
rw [measure_prod_null mt] at ht
rw [eventuallyLE_antisymm_iff]
exact
⟨EventuallyLE.trans_eq (Eventually.of_forall fun x => measure_mono (preimage_mono hst))
ht,
Eventually.of_forall fun x => zero_le _⟩
omit [SFinite ν] in
theorem AbsolutelyContinuous.prod [SFinite ν'] (h1 : μ ≪ μ') (h2 : ν ≪ ν') :
μ.prod ν ≪ μ'.prod ν' := by
refine AbsolutelyContinuous.mk fun s hs h2s => ?_
apply measure_prod_null_of_ae_null hs
rw [measure_prod_null hs] at h2s
exact (h2s.filter_mono h1.ae_le).mono fun _ h => h2 h
/-- Note: the converse is not true. For a counterexample, see
Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. It is true if the set is
measurable, see `ae_prod_mem_iff_ae_ae_mem`. -/
theorem ae_ae_of_ae_prod {p : α × β → Prop} (h : ∀ᵐ z ∂μ.prod ν, p z) :
∀ᵐ x ∂μ, ∀ᵐ y ∂ν, p (x, y) :=
measure_ae_null_of_prod_null h
theorem ae_ae_eq_curry_of_prod {γ : Type*} {f g : α × β → γ} (h : f =ᵐ[μ.prod ν] g) :
∀ᵐ x ∂μ, curry f x =ᵐ[ν] curry g x :=
ae_ae_of_ae_prod h
theorem ae_ae_eq_of_ae_eq_uncurry {γ : Type*} {f g : α → β → γ}
(h : uncurry f =ᵐ[μ.prod ν] uncurry g) : ∀ᵐ x ∂μ, f x =ᵐ[ν] g x :=
ae_ae_eq_curry_of_prod h
theorem ae_prod_iff_ae_ae {p : α × β → Prop} (hp : MeasurableSet {x | p x}) :
(∀ᵐ z ∂μ.prod ν, p z) ↔ ∀ᵐ x ∂μ, ∀ᵐ y ∂ν, p (x, y) :=
measure_prod_null hp.compl
theorem ae_prod_mem_iff_ae_ae_mem {s : Set (α × β)} (hs : MeasurableSet s) :
(∀ᵐ z ∂μ.prod ν, z ∈ s) ↔ ∀ᵐ x ∂μ, ∀ᵐ y ∂ν, (x, y) ∈ s :=
measure_prod_null hs.compl
omit [SFinite ν] in
@[fun_prop]
theorem quasiMeasurePreserving_fst : QuasiMeasurePreserving Prod.fst (μ.prod ν) μ := by
refine ⟨measurable_fst, AbsolutelyContinuous.mk fun s hs h2s => ?_⟩
rw [map_apply measurable_fst hs, ← prod_univ, ← nonpos_iff_eq_zero]
refine (prod_prod_le _ _).trans_eq ?_
rw [h2s, zero_mul]
omit [SFinite ν] in
@[fun_prop]
theorem quasiMeasurePreserving_snd : QuasiMeasurePreserving Prod.snd (μ.prod ν) ν := by
refine ⟨measurable_snd, AbsolutelyContinuous.mk fun s hs h2s => ?_⟩
rw [map_apply measurable_snd hs, ← univ_prod, ← nonpos_iff_eq_zero]
refine (prod_prod_le _ _).trans_eq ?_
rw [h2s, mul_zero]
omit [SFinite ν] in
lemma set_prod_ae_eq {s s' : Set α} {t t' : Set β} (hs : s =ᵐ[μ] s') (ht : t =ᵐ[ν] t') :
(s ×ˢ t : Set (α × β)) =ᵐ[μ.prod ν] (s' ×ˢ t' : Set (α × β)) :=
(quasiMeasurePreserving_fst.preimage_ae_eq hs).inter
(quasiMeasurePreserving_snd.preimage_ae_eq ht)
lemma measure_prod_compl_eq_zero {s : Set α} {t : Set β}
(s_ae_univ : μ sᶜ = 0) (t_ae_univ : ν tᶜ = 0) :
μ.prod ν (s ×ˢ t)ᶜ = 0 := by
rw [Set.compl_prod_eq_union, measure_union_null_iff]
simp [s_ae_univ, t_ae_univ]
omit [SFinite ν] in
lemma _root_.MeasureTheory.NullMeasurableSet.prod {s : Set α} {t : Set β}
(s_mble : NullMeasurableSet s μ) (t_mble : NullMeasurableSet t ν) :
NullMeasurableSet (s ×ˢ t) (μ.prod ν) :=
let ⟨s₀, mble_s₀, s_aeeq_s₀⟩ := s_mble
let ⟨t₀, mble_t₀, t_aeeq_t₀⟩ := t_mble
⟨s₀ ×ˢ t₀, ⟨mble_s₀.prod mble_t₀, set_prod_ae_eq s_aeeq_s₀ t_aeeq_t₀⟩⟩
/-- If `s ×ˢ t` is a null measurable set and `μ s ≠ 0`, then `t` is a null measurable set. -/
lemma _root_.MeasureTheory.NullMeasurableSet.right_of_prod {s : Set α} {t : Set β}
(h : NullMeasurableSet (s ×ˢ t) (μ.prod ν)) (hs : μ s ≠ 0) : NullMeasurableSet t ν := by
rcases h with ⟨u, hum, hu⟩
obtain ⟨x, hxs, hx⟩ : ∃ x ∈ s, (Prod.mk x ⁻¹' (s ×ˢ t)) =ᵐ[ν] (Prod.mk x ⁻¹' u) :=
((frequently_ae_iff.2 hs).and_eventually (ae_ae_eq_curry_of_prod hu)).exists
refine ⟨Prod.mk x ⁻¹' u, measurable_prodMk_left hum, ?_⟩
rwa [mk_preimage_prod_right hxs] at hx
/-- If `Prod.snd ⁻¹' t` is a null measurable set and `μ ≠ 0`, then `t` is a null measurable set. -/
lemma _root_.MeasureTheory.NullMeasurableSet.of_preimage_snd [NeZero μ] {t : Set β}
(h : NullMeasurableSet (Prod.snd ⁻¹' t) (μ.prod ν)) : NullMeasurableSet t ν :=
.right_of_prod (by rwa [univ_prod]) (NeZero.ne (μ univ))
/-- `Prod.snd ⁻¹' t` is null measurable w.r.t. `μ.prod ν` iff `t` is null measurable w.r.t. `ν`
provided that `μ ≠ 0`. -/
lemma nullMeasurableSet_preimage_snd [NeZero μ] {t : Set β} :
NullMeasurableSet (Prod.snd ⁻¹' t) (μ.prod ν) ↔ NullMeasurableSet t ν :=
⟨.of_preimage_snd, (.preimage · quasiMeasurePreserving_snd)⟩
lemma nullMeasurable_comp_snd [NeZero μ] {f : β → γ} :
NullMeasurable (f ∘ Prod.snd) (μ.prod ν) ↔ NullMeasurable f ν :=
forall₂_congr fun s _ ↦ nullMeasurableSet_preimage_snd (t := f ⁻¹' s)
/-- `μ.prod ν` has finite spanning sets in rectangles of finite spanning sets. -/
noncomputable def FiniteSpanningSetsIn.prod {ν : Measure β} {C : Set (Set α)} {D : Set (Set β)}
(hμ : μ.FiniteSpanningSetsIn C) (hν : ν.FiniteSpanningSetsIn D) :
(μ.prod ν).FiniteSpanningSetsIn (image2 (· ×ˢ ·) C D) := by
haveI := hν.sigmaFinite
refine
⟨fun n => hμ.set n.unpair.1 ×ˢ hν.set n.unpair.2, fun n =>
mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), fun n => ?_, ?_⟩
· rw [prod_prod]
exact mul_lt_top (hμ.finite _) (hν.finite _)
· simp_rw [iUnion_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ]
lemma prod_sum_left {ι : Type*} (m : ι → Measure α) (μ : Measure β) [SFinite μ] :
(Measure.sum m).prod μ = Measure.sum (fun i ↦ (m i).prod μ) := by
ext s hs
simp only [prod_apply hs, lintegral_sum_measure, hs, sum_apply]
lemma prod_sum_right {ι' : Type*} [Countable ι'] (m : Measure α) (m' : ι' → Measure β)
[∀ n, SFinite (m' n)] :
m.prod (Measure.sum m') = Measure.sum (fun p ↦ m.prod (m' p)) := by
ext s hs
simp only [prod_apply hs, hs, sum_apply]
have M : ∀ x, MeasurableSet (Prod.mk x ⁻¹' s) := fun x => measurable_prodMk_left hs
simp_rw [Measure.sum_apply _ (M _)]
rw [lintegral_tsum (fun i ↦ (measurable_measure_prodMk_left hs).aemeasurable)]
lemma prod_sum {ι ι' : Type*} [Countable ι'] (m : ι → Measure α) (m' : ι' → Measure β)
[∀ n, SFinite (m' n)] :
(Measure.sum m).prod (Measure.sum m') =
Measure.sum (fun (p : ι × ι') ↦ (m p.1).prod (m' p.2)) := by
simp_rw [prod_sum_left, prod_sum_right, sum_sum]
instance prod.instSigmaFinite {α β : Type*} {_ : MeasurableSpace α} {μ : Measure α}
[SigmaFinite μ] {_ : MeasurableSpace β} {ν : Measure β} [SigmaFinite ν] :
SigmaFinite (μ.prod ν) :=
(μ.toFiniteSpanningSetsIn.prod ν.toFiniteSpanningSetsIn).sigmaFinite
instance prod.instSFinite {α β : Type*} {_ : MeasurableSpace α} {μ : Measure α}
[SFinite μ] {_ : MeasurableSpace β} {ν : Measure β} [SFinite ν] :
SFinite (μ.prod ν) := by
have : μ.prod ν =
Measure.sum (fun (p : ℕ × ℕ) ↦ (sfiniteSeq μ p.1).prod (sfiniteSeq ν p.2)) := by
conv_lhs => rw [← sum_sfiniteSeq μ, ← sum_sfiniteSeq ν]
apply prod_sum
rw [this]
infer_instance
instance {α β} [MeasureSpace α] [SigmaFinite (volume : Measure α)]
[MeasureSpace β] [SigmaFinite (volume : Measure β)] : SigmaFinite (volume : Measure (α × β)) :=
prod.instSigmaFinite
instance {α β} [MeasureSpace α] [SFinite (volume : Measure α)]
[MeasureSpace β] [SFinite (volume : Measure β)] : SFinite (volume : Measure (α × β)) :=
prod.instSFinite
/-- A measure on a product space equals the product measure if they are equal on rectangles
with as sides sets that generate the corresponding σ-algebras. -/
theorem prod_eq_generateFrom {μ : Measure α} {ν : Measure β} {C : Set (Set α)} {D : Set (Set β)}
(hC : generateFrom C = ‹_›) (hD : generateFrom D = ‹_›) (h2C : IsPiSystem C)
(h2D : IsPiSystem D) (h3C : μ.FiniteSpanningSetsIn C) (h3D : ν.FiniteSpanningSetsIn D)
{μν : Measure (α × β)} (h₁ : ∀ s ∈ C, ∀ t ∈ D, μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := by
refine
(h3C.prod h3D).ext
(generateFrom_eq_prod hC hD h3C.isCountablySpanning h3D.isCountablySpanning).symm
(h2C.prod h2D) ?_
rintro _ ⟨s, hs, t, ht, rfl⟩
haveI := h3D.sigmaFinite
rw [h₁ s hs t ht, prod_prod]
/- Note that the next theorem is not true for s-finite measures: let `μ = ν = ∞ • Leb` on `[0,1]`
(they are s-finite as countable sums of the finite Lebesgue measure), and let `μν = μ.prod ν + λ`
where `λ` is Lebesgue measure on the diagonal. Then both measures give infinite mass to rectangles
`s × t` whose sides have positive Lebesgue measure, and `0` measure when one of the sides has zero
Lebesgue measure. And yet they do not coincide, as the first one gives zero mass to the diagonal,
and the second one gives mass one.
-/
/-- A measure on a product space equals the product measure of sigma-finite measures if they are
equal on rectangles. -/
theorem prod_eq {μ : Measure α} [SigmaFinite μ] {ν : Measure β} [SigmaFinite ν]
{μν : Measure (α × β)}
(h : ∀ s t, MeasurableSet s → MeasurableSet t → μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν :=
prod_eq_generateFrom generateFrom_measurableSet generateFrom_measurableSet
isPiSystem_measurableSet isPiSystem_measurableSet μ.toFiniteSpanningSetsIn
ν.toFiniteSpanningSetsIn fun s hs t ht => h s t hs ht
variable [SFinite μ]
theorem prod_swap : map Prod.swap (μ.prod ν) = ν.prod μ := by
have : sum (fun (i : ℕ × ℕ) ↦ map Prod.swap ((sfiniteSeq μ i.1).prod (sfiniteSeq ν i.2)))
= sum (fun (i : ℕ × ℕ) ↦ map Prod.swap ((sfiniteSeq μ i.2).prod (sfiniteSeq ν i.1))) := by
ext s hs
rw [sum_apply _ hs, sum_apply _ hs]
exact ((Equiv.prodComm ℕ ℕ).tsum_eq _).symm
rw [← sum_sfiniteSeq μ, ← sum_sfiniteSeq ν, prod_sum, prod_sum,
map_sum measurable_swap.aemeasurable, this]
congr 1
ext1 i
refine (prod_eq ?_).symm
intro s t hs ht
simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod, mul_comm]
theorem measurePreserving_swap : MeasurePreserving Prod.swap (μ.prod ν) (ν.prod μ) :=
⟨measurable_swap, prod_swap⟩
theorem prod_apply_symm {s : Set (α × β)} (hs : MeasurableSet s) :
μ.prod ν s = ∫⁻ y, μ ((fun x => (x, y)) ⁻¹' s) ∂ν := by
rw [← prod_swap, map_apply measurable_swap hs, prod_apply (measurable_swap hs)]
rfl
theorem ae_ae_comm {p : α → β → Prop} (h : MeasurableSet {x : α × β | p x.1 x.2}) :
(∀ᵐ x ∂μ, ∀ᵐ y ∂ν, p x y) ↔ ∀ᵐ y ∂ν, ∀ᵐ x ∂μ, p x y := calc
_ ↔ ∀ᵐ x ∂μ.prod ν, p x.1 x.2 := .symm <| ae_prod_iff_ae_ae h
_ ↔ ∀ᵐ x ∂ν.prod μ, p x.2 x.1 := by rw [← prod_swap, ae_map_iff (by fun_prop) h]; simp
_ ↔ ∀ᵐ y ∂ν, ∀ᵐ x ∂μ, p x y := ae_prod_iff_ae_ae <| measurable_swap h
/-- If `s ×ˢ t` is a null measurable set and `ν t ≠ 0`, then `s` is a null measurable set. -/
lemma _root_.MeasureTheory.NullMeasurableSet.left_of_prod {s : Set α} {t : Set β}
(h : NullMeasurableSet (s ×ˢ t) (μ.prod ν)) (ht : ν t ≠ 0) : NullMeasurableSet s μ := by
refine .right_of_prod ?_ ht
rw [← preimage_swap_prod]
exact h.preimage measurePreserving_swap.quasiMeasurePreserving
/-- If `Prod.fst ⁻¹' s` is a null measurable set and `ν ≠ 0`, then `s` is a null measurable set. -/
lemma _root_.MeasureTheory.NullMeasurableSet.of_preimage_fst [NeZero ν] {s : Set α}
(h : NullMeasurableSet (Prod.fst ⁻¹' s) (μ.prod ν)) : NullMeasurableSet s μ :=
.left_of_prod (by rwa [prod_univ]) (NeZero.ne (ν univ))
/-- `Prod.fst ⁻¹' s` is null measurable w.r.t. `μ.prod ν` iff `s` is null measurable w.r.t. `μ`
provided that `ν ≠ 0`. -/
lemma nullMeasurableSet_preimage_fst [NeZero ν] {s : Set α} :
NullMeasurableSet (Prod.fst ⁻¹' s) (μ.prod ν) ↔ NullMeasurableSet s μ :=
⟨.of_preimage_fst, (.preimage · quasiMeasurePreserving_fst)⟩
lemma nullMeasurable_comp_fst [NeZero ν] {f : α → γ} :
NullMeasurable (f ∘ Prod.fst) (μ.prod ν) ↔ NullMeasurable f μ :=
forall₂_congr fun s _ ↦ nullMeasurableSet_preimage_fst (s := f ⁻¹' s)
/-- The product of two non-null sets is null measurable
if and only if both of them are null measurable. -/
lemma nullMeasurableSet_prod_of_ne_zero {s : Set α} {t : Set β} (hs : μ s ≠ 0) (ht : ν t ≠ 0) :
NullMeasurableSet (s ×ˢ t) (μ.prod ν) ↔ NullMeasurableSet s μ ∧ NullMeasurableSet t ν :=
⟨fun h ↦ ⟨h.left_of_prod ht, h.right_of_prod hs⟩, fun ⟨hs, ht⟩ ↦ hs.prod ht⟩
/-- The product of two sets is null measurable
if and only if both of them are null measurable or one of them has measure zero. -/
lemma nullMeasurableSet_prod {s : Set α} {t : Set β} :
NullMeasurableSet (s ×ˢ t) (μ.prod ν) ↔
NullMeasurableSet s μ ∧ NullMeasurableSet t ν ∨ μ s = 0 ∨ ν t = 0 := by
rcases eq_or_ne (μ s) 0 with hs | hs; · simp [NullMeasurableSet.of_null, *]
rcases eq_or_ne (ν t) 0 with ht | ht; · simp [NullMeasurableSet.of_null, *]
simp [*, nullMeasurableSet_prod_of_ne_zero]
theorem prodAssoc_prod [SFinite τ] :
map MeasurableEquiv.prodAssoc ((μ.prod ν).prod τ) = μ.prod (ν.prod τ) := by
have : sum (fun (p : ℕ × ℕ × ℕ) ↦
(sfiniteSeq μ p.1).prod ((sfiniteSeq ν p.2.1).prod (sfiniteSeq τ p.2.2)))
= sum (fun (p : (ℕ × ℕ) × ℕ) ↦
(sfiniteSeq μ p.1.1).prod ((sfiniteSeq ν p.1.2).prod (sfiniteSeq τ p.2))) := by
ext s hs
rw [sum_apply _ hs, sum_apply _ hs, ← (Equiv.prodAssoc _ _ _).tsum_eq]
simp only [Equiv.prodAssoc_apply]
rw [← sum_sfiniteSeq μ, ← sum_sfiniteSeq ν, ← sum_sfiniteSeq τ, prod_sum, prod_sum,
map_sum MeasurableEquiv.prodAssoc.measurable.aemeasurable, prod_sum, prod_sum, this]
congr
ext1 i
refine (prod_eq_generateFrom generateFrom_measurableSet generateFrom_prod
isPiSystem_measurableSet isPiSystem_prod ((sfiniteSeq μ i.1.1)).toFiniteSpanningSetsIn
((sfiniteSeq ν i.1.2).toFiniteSpanningSetsIn.prod (sfiniteSeq τ i.2).toFiniteSpanningSetsIn)
?_).symm
rintro s hs _ ⟨t, ht, u, hu, rfl⟩; rw [mem_setOf_eq] at hs ht hu
simp_rw [map_apply (MeasurableEquiv.measurable _) (hs.prod (ht.prod hu)),
MeasurableEquiv.prodAssoc, MeasurableEquiv.coe_mk, Equiv.prod_assoc_preimage, prod_prod,
mul_assoc]
/-! ### The product of specific measures -/
theorem prod_restrict (s : Set α) (t : Set β) :
(μ.restrict s).prod (ν.restrict t) = (μ.prod ν).restrict (s ×ˢ t) := by
rw [← sum_sfiniteSeq μ, ← sum_sfiniteSeq ν, restrict_sum_of_countable, restrict_sum_of_countable,
prod_sum, prod_sum, restrict_sum_of_countable]
congr 1
ext1 i
refine prod_eq fun s' t' hs' ht' => ?_
rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod, restrict_apply hs',
restrict_apply ht']
theorem restrict_prod_eq_prod_univ (s : Set α) :
(μ.restrict s).prod ν = (μ.prod ν).restrict (s ×ˢ univ) := by
have : ν = ν.restrict Set.univ := Measure.restrict_univ.symm
rw [this, Measure.prod_restrict, ← this]
theorem prod_dirac (y : β) : μ.prod (dirac y) = map (fun x => (x, y)) μ := by
classical
rw [← sum_sfiniteSeq μ, prod_sum_left, map_sum measurable_prodMk_right.aemeasurable]
congr
ext1 i
refine prod_eq fun s t hs ht => ?_
simp_rw [map_apply measurable_prodMk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if,
dirac_apply' _ ht, ← indicator_mul_right _ fun _ => sfiniteSeq μ i s, Pi.one_apply, mul_one]
theorem dirac_prod (x : α) : (dirac x).prod ν = map (Prod.mk x) ν := by
classical
rw [← sum_sfiniteSeq ν, prod_sum_right, map_sum measurable_prodMk_left.aemeasurable]
congr
ext1 i
refine prod_eq fun s t hs ht => ?_
simp_rw [map_apply measurable_prodMk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if,
dirac_apply' _ hs, ← indicator_mul_left _ _ fun _ => sfiniteSeq ν i t, Pi.one_apply, one_mul]
theorem dirac_prod_dirac {x : α} {y : β} : (dirac x).prod (dirac y) = dirac (x, y) := by
rw [prod_dirac, map_dirac measurable_prodMk_right]
theorem prod_add (ν' : Measure β) [SFinite ν'] : μ.prod (ν + ν') = μ.prod ν + μ.prod ν' := by
simp_rw [← sum_sfiniteSeq ν, ← sum_sfiniteSeq ν', sum_add_sum, ← sum_sfiniteSeq μ, prod_sum,
sum_add_sum]
congr
ext1 i
refine prod_eq fun s t _ _ => ?_
simp_rw [add_apply, prod_prod, left_distrib]
theorem add_prod (μ' : Measure α) [SFinite μ'] : (μ + μ').prod ν = μ.prod ν + μ'.prod ν := by
simp_rw [← sum_sfiniteSeq μ, ← sum_sfiniteSeq μ', sum_add_sum, ← sum_sfiniteSeq ν, prod_sum,
sum_add_sum]
congr
ext1 i
refine prod_eq fun s t _ _ => ?_
simp_rw [add_apply, prod_prod, right_distrib]
@[simp]
theorem zero_prod (ν : Measure β) : (0 : Measure α).prod ν = 0 := by
rw [Measure.prod]
exact bind_zero_left _
@[simp]
theorem prod_zero (μ : Measure α) : μ.prod (0 : Measure β) = 0 := by simp [Measure.prod]
theorem map_prod_map {δ} [MeasurableSpace δ] {f : α → β} {g : γ → δ} (μa : Measure α)
(μc : Measure γ) [SFinite μa] [SFinite μc] (hf : Measurable f) (hg : Measurable g) :
(map f μa).prod (map g μc) = map (Prod.map f g) (μa.prod μc) := by
simp_rw [← sum_sfiniteSeq μa, ← sum_sfiniteSeq μc, map_sum hf.aemeasurable,
map_sum hg.aemeasurable, prod_sum, map_sum (hf.prodMap hg).aemeasurable]
congr
ext1 i
refine prod_eq fun s t hs ht => ?_
rw [map_apply (hf.prodMap hg) (hs.prod ht), map_apply hf hs, map_apply hg ht]
exact prod_prod (f ⁻¹' s) (g ⁻¹' t)
-- `prod_smul_right` needs an instance to get `SFinite (c • ν)` from `SFinite ν`,
-- hence it is placed in the `WithDensity` file, where the instance is defined.
lemma prod_smul_left {μ : Measure α} (c : ℝ≥0∞) : (c • μ).prod ν = c • (μ.prod ν) := by
ext s hs
rw [Measure.prod_apply hs, Measure.smul_apply, Measure.prod_apply hs]
simp
end Measure
open Measure
namespace MeasurePreserving
variable {δ : Type*} [MeasurableSpace δ] {μa : Measure α} {μb : Measure β} {μc : Measure γ}
{μd : Measure δ}
/-- Let `f : α → β` be a measure preserving map.
For a.e. all `a`, let `g a : γ → δ` be a measure preserving map.
Also suppose that `g` is measurable as a function of two arguments.
Then the map `fun (a, c) ↦ (f a, g a c)` is a measure preserving map
for the product measures on `α × γ` and `β × δ`.
Some authors call a map of the form `fun (a, c) ↦ (f a, g a c)` a *skew product* over `f`,
thus the choice of a name.
-/
theorem skew_product [SFinite μa] [SFinite μc] {f : α → β} (hf : MeasurePreserving f μa μb)
{g : α → γ → δ} (hgm : Measurable (uncurry g)) (hg : ∀ᵐ a ∂μa, map (g a) μc = μd) :
MeasurePreserving (fun p : α × γ => (f p.1, g p.1 p.2)) (μa.prod μc) (μb.prod μd) := by
have : Measurable fun p : α × γ => (f p.1, g p.1 p.2) := (hf.1.comp measurable_fst).prodMk hgm
use this
/- if `μa = 0`, then the lemma is trivial, otherwise we can use `hg`
to deduce `SFinite μd`. -/
rcases eq_zero_or_neZero μa with rfl | _
· simp [← hf.map_eq]
have sf : SFinite μd := by
obtain ⟨a, ha⟩ : ∃ a, map (g a) μc = μd := hg.exists
rw [← ha]
infer_instance
-- Thus we can use the integral formula for the product measure, and compute things explicitly
ext s hs
rw [map_apply this hs, prod_apply (this hs), prod_apply hs,
← hf.lintegral_comp (measurable_measure_prodMk_left hs)]
apply lintegral_congr_ae
filter_upwards [hg] with a ha
rw [← ha, map_apply hgm.of_uncurry_left (measurable_prodMk_left hs), preimage_preimage,
preimage_preimage]
/-- If `f : α → β` sends the measure `μa` to `μb` and `g : γ → δ` sends the measure `μc` to `μd`,
then `Prod.map f g` sends `μa.prod μc` to `μb.prod μd`. -/
protected theorem prod [SFinite μa] [SFinite μc] {f : α → β} {g : γ → δ}
(hf : MeasurePreserving f μa μb) (hg : MeasurePreserving g μc μd) :
MeasurePreserving (Prod.map f g) (μa.prod μc) (μb.prod μd) :=
have : Measurable (uncurry fun _ : α => g) := hg.1.comp measurable_snd
hf.skew_product this <| ae_of_all _ fun _ => hg.map_eq
end MeasurePreserving
namespace QuasiMeasurePreserving
theorem prod_of_right {f : α × β → γ} {μ : Measure α} {ν : Measure β} {τ : Measure γ}
(hf : Measurable f) [SFinite ν]
(h2f : ∀ᵐ x ∂μ, QuasiMeasurePreserving (fun y => f (x, y)) ν τ) :
QuasiMeasurePreserving f (μ.prod ν) τ := by
refine ⟨hf, ?_⟩
refine AbsolutelyContinuous.mk fun s hs h2s => ?_
rw [map_apply hf hs, prod_apply (hf hs)]; simp_rw [preimage_preimage]
rw [lintegral_congr_ae (h2f.mono fun x hx => hx.preimage_null h2s), lintegral_zero]
theorem prod_of_left {α β γ} [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ]
{f : α × β → γ} {μ : Measure α} {ν : Measure β} {τ : Measure γ} (hf : Measurable f)
[SFinite μ] [SFinite ν]
(h2f : ∀ᵐ y ∂ν, QuasiMeasurePreserving (fun x => f (x, y)) μ τ) :
QuasiMeasurePreserving f (μ.prod ν) τ := by
rw [← prod_swap]
convert (QuasiMeasurePreserving.prod_of_right (hf.comp measurable_swap) h2f).comp
((measurable_swap.measurePreserving (ν.prod μ)).symm
MeasurableEquiv.prodComm).quasiMeasurePreserving
@[fun_prop]
protected theorem fst {f : α → β × γ} (hf : QuasiMeasurePreserving f μ (ν.prod τ)) :
QuasiMeasurePreserving (fun x ↦ (f x).1) μ ν :=
(quasiMeasurePreserving_fst (μ := ν) (ν := τ)).comp hf
@[fun_prop]
protected theorem snd {f : α → β × γ} (hf : QuasiMeasurePreserving f μ (ν.prod τ)) :
QuasiMeasurePreserving (fun x ↦ (f x).2) μ τ :=
(quasiMeasurePreserving_snd (μ := ν) (ν := τ)).comp hf
@[fun_prop]
protected theorem prodMap {ω : Type*} {mω : MeasurableSpace ω} {υ : Measure ω}
[SFinite μ] [SFinite τ] [SFinite υ] {f : α → β} {g : γ → ω}
(hf : QuasiMeasurePreserving f μ ν) (hg : QuasiMeasurePreserving g τ υ) :
QuasiMeasurePreserving (Prod.map f g) (μ.prod τ) (ν.prod υ) := by
refine ⟨by fun_prop, ?_⟩
rw [← map_prod_map _ _ (by fun_prop) (by fun_prop)]
exact hf.absolutelyContinuous.prod hg.absolutelyContinuous
end QuasiMeasurePreserving
end MeasureTheory
open MeasureTheory.Measure
section
theorem AEMeasurable.prod_swap [SFinite μ] [SFinite ν] {f : β × α → γ}
(hf : AEMeasurable f (ν.prod μ)) : AEMeasurable (fun z : α × β => f z.swap) (μ.prod ν) := by
rw [← Measure.prod_swap] at hf
exact hf.comp_measurable measurable_swap
theorem MeasureTheory.NullMeasurable.comp_fst {f : α → γ} (hf : NullMeasurable f μ) :
NullMeasurable (fun z : α × β => f z.1) (μ.prod ν) :=
hf.comp_quasiMeasurePreserving quasiMeasurePreserving_fst
theorem AEMeasurable.comp_fst {f : α → γ} (hf : AEMeasurable f μ) :
AEMeasurable (fun z : α × β => f z.1) (μ.prod ν) :=
hf.comp_quasiMeasurePreserving quasiMeasurePreserving_fst
theorem MeasureTheory.NullMeasurable.comp_snd {f : β → γ} (hf : NullMeasurable f ν) :
NullMeasurable (fun z : α × β => f z.2) (μ.prod ν) :=
hf.comp_quasiMeasurePreserving quasiMeasurePreserving_snd
theorem AEMeasurable.comp_snd {f : β → γ} (hf : AEMeasurable f ν) :
AEMeasurable (fun z : α × β => f z.2) (μ.prod ν) :=
hf.comp_quasiMeasurePreserving quasiMeasurePreserving_snd
@[fun_prop, measurability]
theorem AEMeasurable.lintegral_prod_right' [SFinite ν] {f : α × β → ℝ≥0∞}
(hf : AEMeasurable f (μ.prod ν)) : AEMeasurable (fun x ↦ ∫⁻ y, f (x, y) ∂ν) μ := by
obtain ⟨g, hg, hfg⟩ := hf
refine ⟨fun x ↦ ∫⁻ y, g (x, y) ∂ν, by fun_prop, ?_⟩
exact (ae_ae_of_ae_prod hfg).mono fun x hfg' ↦ lintegral_congr_ae hfg'
@[fun_prop, measurability]
theorem AEMeasurable.lintegral_prod_right [SFinite ν] {f : α → β → ℝ≥0∞}
(hf : AEMeasurable f.uncurry (μ.prod ν)) : AEMeasurable (fun x ↦ ∫⁻ y, f x y ∂ν) μ :=
hf.lintegral_prod_right'
@[fun_prop, measurability]
theorem AEMeasurable.lintegral_prod_left' [SFinite ν] [SFinite μ] {f : α × β → ℝ≥0∞}
(hf : AEMeasurable f (μ.prod ν)) : AEMeasurable (fun y ↦ ∫⁻ x, f (x, y) ∂μ) ν :=
hf.prod_swap.lintegral_prod_right'
@[fun_prop, measurability]
theorem AEMeasurable.lintegral_prod_left [SFinite ν] [SFinite μ] {f : α → β → ℝ≥0∞}
(hf : AEMeasurable f.uncurry (μ.prod ν)) : AEMeasurable (fun y ↦ ∫⁻ x, f x y ∂μ) ν :=
hf.lintegral_prod_left'
end
namespace MeasureTheory
/-! ### The Lebesgue integral on a product -/
variable [SFinite ν]
theorem lintegral_prod_swap [SFinite μ] (f : α × β → ℝ≥0∞) :
∫⁻ z, f z.swap ∂ν.prod μ = ∫⁻ z, f z ∂μ.prod ν :=
measurePreserving_swap.lintegral_comp_emb MeasurableEquiv.prodComm.measurableEmbedding f
/-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`,
the integral of `f` is equal to the iterated integral. -/
theorem lintegral_prod (f : α × β → ℝ≥0∞) (hf : AEMeasurable f (μ.prod ν)) :
∫⁻ z, f z ∂μ.prod ν = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := by
rw [Measure.prod] at *
rw [lintegral_bind Measurable.map_prodMk_left.aemeasurable hf]
apply lintegral_congr_ae
filter_upwards [Measurable.map_prodMk_left.aemeasurable.ae_of_bind hf] with a ha
exact lintegral_map' ha (by fun_prop)
/-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued measurable functions on `α × β`,
the integral of `f` is equal to the iterated integral. -/
@[deprecated lintegral_prod (since := "2025-04-06")]
theorem lintegral_prod_of_measurable (f : α × β → ℝ≥0∞) (hf : Measurable f) :
∫⁻ z, f z ∂μ.prod ν = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ :=
lintegral_prod f hf.aemeasurable
omit [SFinite ν] in
theorem lintegral_prod_le (f : α × β → ℝ≥0∞) :
∫⁻ z, f z ∂μ.prod ν ≤ ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := by
rw [Measure.prod]
exact (lintegral_bind_le _ _ _).trans <| lintegral_mono fun a ↦ lintegral_map_le _ _
/-- **Tonelli's Theorem for set integrals**: For `ℝ≥0∞`-valued almost everywhere measurable
functions on `s ×ˢ t`, the integral of `f` on `s ×ˢ t` is equal to the iterated integral on `s`
and `t` respectively. -/
theorem setLIntegral_prod [SFinite μ] {s : Set α} {t : Set β} (f : α × β → ℝ≥0∞)
(hf : AEMeasurable f ((μ.prod ν).restrict (s ×ˢ t))) :
∫⁻ z in s ×ˢ t, f z ∂μ.prod ν = ∫⁻ x in s, ∫⁻ y in t, f (x, y) ∂ν ∂μ := by
rw [← Measure.prod_restrict, lintegral_prod _ (by rwa [Measure.prod_restrict])]
/-- The symmetric version of Tonelli's Theorem: For `ℝ≥0∞`-valued almost everywhere measurable
functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/
theorem lintegral_prod_symm [SFinite μ] (f : α × β → ℝ≥0∞) (hf : AEMeasurable f (μ.prod ν)) :
∫⁻ z, f z ∂μ.prod ν = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := by
simp_rw [← lintegral_prod_swap f]
exact lintegral_prod _ hf.prod_swap
/-- The symmetric version of Tonelli's Theorem: For `ℝ≥0∞`-valued measurable
functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/
theorem lintegral_prod_symm' [SFinite μ] (f : α × β → ℝ≥0∞) (hf : Measurable f) :
∫⁻ z, f z ∂μ.prod ν = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν :=
lintegral_prod_symm f hf.aemeasurable
/-- The symmetric version of Tonelli's Theorem for set integrals: For `ℝ≥0∞`-valued almost
everywhere measurable functions on `s ×ˢ t`, the integral of `f` on `s ×ˢ t` is equal to the
iterated integral on `t` and `s` respectively. -/
theorem setLIntegral_prod_symm [SFinite μ] {s : Set α} {t : Set β} (f : α × β → ℝ≥0∞)
(hf : AEMeasurable f ((μ.prod ν).restrict (s ×ˢ t))) :
∫⁻ z in s ×ˢ t, f z ∂μ.prod ν = ∫⁻ y in t, ∫⁻ x in s, f (x, y) ∂μ ∂ν := by
rw [← Measure.prod_restrict, ← lintegral_prod_swap, Measure.prod_restrict,
setLIntegral_prod]
· rfl
· refine AEMeasurable.comp_measurable ?_ measurable_swap
convert hf
rw [← Measure.prod_restrict, Measure.prod_swap, Measure.prod_restrict]
/-- The reversed version of **Tonelli's Theorem**. In this version `f` is in curried form, which
makes it easier for the elaborator to figure out `f` automatically. -/
theorem lintegral_lintegral ⦃f : α → β → ℝ≥0∞⦄ (hf : AEMeasurable (uncurry f) (μ.prod ν)) :
∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.1 z.2 ∂μ.prod ν :=
(lintegral_prod _ hf).symm
/-- The reversed version of **Tonelli's Theorem** (symmetric version). In this version `f` is in
curried form, which makes it easier for the elaborator to figure out `f` automatically. -/
theorem lintegral_lintegral_symm [SFinite μ] ⦃f : α → β → ℝ≥0∞⦄
(hf : AEMeasurable (uncurry f) (μ.prod ν)) :
∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.2 z.1 ∂ν.prod μ :=
(lintegral_prod_symm _ hf.prod_swap).symm
/-- Change the order of Lebesgue integration. -/
theorem lintegral_lintegral_swap [SFinite μ] ⦃f : α → β → ℝ≥0∞⦄
(hf : AEMeasurable (uncurry f) (μ.prod ν)) :
∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ y, ∫⁻ x, f x y ∂μ ∂ν :=
(lintegral_lintegral hf).trans (lintegral_prod_symm _ hf)
theorem lintegral_prod_mul {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : AEMeasurable f μ)
(hg : AEMeasurable g ν) : ∫⁻ z, f z.1 * g z.2 ∂μ.prod ν = (∫⁻ x, f x ∂μ) * ∫⁻ y, g y ∂ν := by
rw [lintegral_prod _ (by fun_prop)]
simp [lintegral_lintegral_mul hf hg]
/-! ### Marginals of a measure defined on a product -/
namespace Measure
variable {ρ : Measure (α × β)}
/-- Marginal measure on `α` obtained from a measure `ρ` on `α × β`, defined by `ρ.map Prod.fst`. -/
noncomputable def fst (ρ : Measure (α × β)) : Measure α :=
ρ.map Prod.fst
theorem fst_apply {s : Set α} (hs : MeasurableSet s) : ρ.fst s = ρ (Prod.fst ⁻¹' s) := by
rw [fst, Measure.map_apply measurable_fst hs]
theorem fst_univ : ρ.fst univ = ρ univ := by rw [fst_apply MeasurableSet.univ, preimage_univ]
@[simp] theorem fst_zero : fst (0 : Measure (α × β)) = 0 := by simp [fst]
instance [SFinite ρ] : SFinite ρ.fst := by
rw [fst]
infer_instance
instance fst.instIsFiniteMeasure [IsFiniteMeasure ρ] : IsFiniteMeasure ρ.fst := by
rw [fst]
infer_instance
instance fst.instIsProbabilityMeasure [IsProbabilityMeasure ρ] : IsProbabilityMeasure ρ.fst where
measure_univ := by
rw [fst_univ]
exact measure_univ
instance fst.instIsZeroOrProbabilityMeasure [IsZeroOrProbabilityMeasure ρ] :
IsZeroOrProbabilityMeasure ρ.fst := by
rcases eq_zero_or_isProbabilityMeasure ρ with h | h
· simp only [h, fst_zero]
infer_instance
· infer_instance
@[simp]
lemma fst_prod [IsProbabilityMeasure ν] : (μ.prod ν).fst = μ := by
ext1 s hs
rw [fst_apply hs, ← prod_univ, prod_prod, measure_univ, mul_one]
theorem fst_map_prodMk₀ {X : α → β} {Y : α → γ} {μ : Measure α}
(hY : AEMeasurable Y μ) : (μ.map fun a => (X a, Y a)).fst = μ.map X := by
by_cases hX : AEMeasurable X μ
· ext1 s hs
rw [Measure.fst_apply hs, Measure.map_apply_of_aemeasurable (hX.prodMk hY) (measurable_fst hs),
Measure.map_apply_of_aemeasurable hX hs, ← prod_univ, mk_preimage_prod, preimage_univ,
inter_univ]
· have : ¬AEMeasurable (fun x ↦ (X x, Y x)) μ := by
contrapose! hX
exact measurable_fst.comp_aemeasurable hX
simp [map_of_not_aemeasurable, hX, this]
@[deprecated (since := "2025-03-05")]
alias fst_map_prod_mk₀ := fst_map_prodMk₀
theorem fst_map_prodMk {X : α → β} {Y : α → γ} {μ : Measure α}
(hY : Measurable Y) : (μ.map fun a => (X a, Y a)).fst = μ.map X :=
fst_map_prodMk₀ hY.aemeasurable
@[deprecated (since := "2025-03-05")]
alias fst_map_prod_mk := fst_map_prodMk
@[simp]
lemma fst_add {μ ν : Measure (α × β)} : (μ + ν).fst = μ.fst + ν.fst :=
Measure.map_add _ _ measurable_fst
lemma fst_sum {ι : Type*} (μ : ι → Measure (α × β)) : (sum μ).fst = sum (fun n ↦ (μ n).fst) :=
Measure.map_sum measurable_fst.aemeasurable
@[gcongr]
theorem fst_mono {μ : Measure (α × β)} (h : ρ ≤ μ) : ρ.fst ≤ μ.fst := map_mono h measurable_fst
/-- Marginal measure on `β` obtained from a measure on `ρ` `α × β`, defined by `ρ.map Prod.snd`. -/
noncomputable def snd (ρ : Measure (α × β)) : Measure β :=
ρ.map Prod.snd
theorem snd_apply {s : Set β} (hs : MeasurableSet s) : ρ.snd s = ρ (Prod.snd ⁻¹' s) := by
rw [snd, Measure.map_apply measurable_snd hs]
theorem snd_univ : ρ.snd univ = ρ univ := by rw [snd_apply MeasurableSet.univ, preimage_univ]
@[simp] theorem snd_zero : snd (0 : Measure (α × β)) = 0 := by simp [snd]
instance [SFinite ρ] : SFinite ρ.snd := by
rw [snd]
infer_instance
instance snd.instIsFiniteMeasure [IsFiniteMeasure ρ] : IsFiniteMeasure ρ.snd := by
rw [snd]
infer_instance
instance snd.instIsProbabilityMeasure [IsProbabilityMeasure ρ] : IsProbabilityMeasure ρ.snd where
measure_univ := by
rw [snd_univ]
exact measure_univ
instance snd.instIsZeroOrProbabilityMeasure [IsZeroOrProbabilityMeasure ρ] :
IsZeroOrProbabilityMeasure ρ.snd := by
rcases eq_zero_or_isProbabilityMeasure ρ with h | h
· simp only [h, snd_zero]
infer_instance
· infer_instance
@[simp]
lemma snd_prod [IsProbabilityMeasure μ] : (μ.prod ν).snd = ν := by
ext1 s hs
rw [snd_apply hs, ← univ_prod, prod_prod, measure_univ, one_mul]
theorem snd_map_prodMk₀ {X : α → β} {Y : α → γ} {μ : Measure α} (hX : AEMeasurable X μ) :
(μ.map fun a => (X a, Y a)).snd = μ.map Y := by
by_cases hY : AEMeasurable Y μ
· ext1 s hs
rw [Measure.snd_apply hs, Measure.map_apply_of_aemeasurable (hX.prodMk hY) (measurable_snd hs),
Measure.map_apply_of_aemeasurable hY hs, ← univ_prod, mk_preimage_prod, preimage_univ,
univ_inter]
· have : ¬AEMeasurable (fun x ↦ (X x, Y x)) μ := by
contrapose! hY
exact measurable_snd.comp_aemeasurable hY
simp [map_of_not_aemeasurable, hY, this]
@[deprecated (since := "2025-03-05")]
alias snd_map_prod_mk₀ := snd_map_prodMk₀
theorem snd_map_prodMk {X : α → β} {Y : α → γ} {μ : Measure α} (hX : Measurable X) :
(μ.map fun a => (X a, Y a)).snd = μ.map Y :=
snd_map_prodMk₀ hX.aemeasurable
@[deprecated (since := "2025-03-05")]
alias snd_map_prod_mk := snd_map_prodMk
@[simp]
lemma snd_add {μ ν : Measure (α × β)} : (μ + ν).snd = μ.snd + ν.snd :=
Measure.map_add _ _ measurable_snd
lemma snd_sum {ι : Type*} (μ : ι → Measure (α × β)) : (sum μ).snd = sum (fun n ↦ (μ n).snd) :=
map_sum measurable_snd.aemeasurable
@[gcongr]
theorem snd_mono {μ : Measure (α × β)} (h : ρ ≤ μ) : ρ.snd ≤ μ.snd := map_mono h measurable_snd
@[simp] lemma fst_map_swap : (ρ.map Prod.swap).fst = ρ.snd := by
rw [Measure.fst, Measure.map_map measurable_fst measurable_swap]
rfl
@[simp] lemma snd_map_swap : (ρ.map Prod.swap).snd = ρ.fst := by
rw [Measure.snd, Measure.map_map measurable_snd measurable_swap]
rfl
end Measure
section MeasurePreserving
-- Note that these results cannot be put in the previous `measurePreserving` section since
-- they use `lintegral_prod`.
/-- The measurable equiv induced by the equiv `(α × β) × γ ≃ α × (β × γ)` is measure preserving. -/
theorem _root_.MeasureTheory.measurePreserving_prodAssoc (μa : Measure α) (μb : Measure β)
(μc : Measure γ) [SFinite μb] [SFinite μc] :
MeasurePreserving (MeasurableEquiv.prodAssoc : (α × β) × γ ≃ᵐ α × β × γ)
((μa.prod μb).prod μc) (μa.prod (μb.prod μc)) where
measurable := MeasurableEquiv.prodAssoc.measurable
map_eq := by
ext s hs
have A (x : α) : MeasurableSet (Prod.mk x ⁻¹' s) := measurable_prodMk_left hs
have B : MeasurableSet (MeasurableEquiv.prodAssoc ⁻¹' s) :=
MeasurableEquiv.prodAssoc.measurable hs
simp_rw [map_apply MeasurableEquiv.prodAssoc.measurable hs, prod_apply hs, prod_apply (A _),
prod_apply B, lintegral_prod _ (measurable_measure_prodMk_left B).aemeasurable]
rfl
theorem _root_.MeasureTheory.volume_preserving_prodAssoc {α₁ β₁ γ₁ : Type*} [MeasureSpace α₁]
[MeasureSpace β₁] [MeasureSpace γ₁] [SFinite (volume : Measure β₁)]
[SFinite (volume : Measure γ₁)] :
MeasurePreserving (MeasurableEquiv.prodAssoc : (α₁ × β₁) × γ₁ ≃ᵐ α₁ × β₁ × γ₁) :=
MeasureTheory.measurePreserving_prodAssoc volume volume volume
end MeasurePreserving
end MeasureTheory
|
Pi.lean
|
/-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import Mathlib.Algebra.BigOperators.Group.Finset.Lemmas
import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise
import Mathlib.Algebra.BigOperators.GroupWithZero.Finset
import Mathlib.Algebra.Group.Action.Pi
import Mathlib.Algebra.Notation.Indicator
import Mathlib.Algebra.Ring.Pi
import Mathlib.Data.Finset.Lattice.Fold
import Mathlib.Data.Fintype.Basic
/-!
# Big operators for Pi Types
This file contains theorems relevant to big operators in binary and arbitrary product
of monoids and groups
-/
open scoped Finset
variable {ι κ M N R α : Type*}
namespace Pi
@[to_additive]
theorem list_prod_apply {α : Type*} {M : α → Type*} [∀ a, Monoid (M a)] (a : α)
(l : List (∀ a, M a)) : l.prod a = (l.map fun f : ∀ a, M a ↦ f a).prod :=
map_list_prod (evalMonoidHom M a) _
@[to_additive]
theorem multiset_prod_apply {α : Type*} {M : α → Type*} [∀ a, CommMonoid (M a)] (a : α)
(s : Multiset (∀ a, M a)) : s.prod a = (s.map fun f : ∀ a, M a ↦ f a).prod :=
(evalMonoidHom M a).map_multiset_prod _
end Pi
@[to_additive (attr := simp)]
theorem Finset.prod_apply {α : Type*} {M : α → Type*} [∀ a, CommMonoid (M a)] (a : α)
(s : Finset ι) (g : ι → ∀ a, M a) : (∏ c ∈ s, g c) a = ∏ c ∈ s, g c a :=
map_prod (Pi.evalMonoidHom M a) _ _
/-- An 'unapplied' analogue of `Finset.prod_apply`. -/
@[to_additive /-- An 'unapplied' analogue of `Finset.sum_apply`. -/]
theorem Finset.prod_fn {α : Type*} {M : α → Type*} {ι} [∀ a, CommMonoid (M a)] (s : Finset ι)
(g : ι → ∀ a, M a) : ∏ c ∈ s, g c = fun a ↦ ∏ c ∈ s, g c a :=
funext fun _ ↦ Finset.prod_apply _ _ _
@[to_additive]
theorem Fintype.prod_apply {α : Type*} {M : α → Type*} [Fintype ι] [∀ a, CommMonoid (M a)] (a : α)
(g : ι → ∀ a, M a) : (∏ c, g c) a = ∏ c, g c a :=
Finset.prod_apply a Finset.univ g
@[to_additive prod_mk_sum]
theorem prod_mk_prod [CommMonoid M] [CommMonoid N] (s : Finset ι) (f : ι → M) (g : ι → N) :
(∏ x ∈ s, f x, ∏ x ∈ s, g x) = ∏ x ∈ s, (f x, g x) :=
haveI := Classical.decEq ι
Finset.induction_on s rfl (by simp +contextual [Prod.ext_iff])
/-- decomposing `x : ι → R` as a sum along the canonical basis -/
theorem pi_eq_sum_univ {ι : Type*} [Fintype ι] [DecidableEq ι] {R : Type*} [NonAssocSemiring R]
(x : ι → R) : x = ∑ i, (x i) • fun j => if i = j then (1 : R) else 0 := by
ext
simp
section CommSemiring
variable [CommSemiring R]
lemma prod_indicator_apply (s : Finset ι) (f : ι → Set κ) (g : ι → κ → R) (j : κ) :
∏ i ∈ s, (f i).indicator (g i) j = (⋂ x ∈ s, f x).indicator (∏ i ∈ s, g i) j := by
rw [Set.indicator]
split_ifs with hj
· rw [Finset.prod_apply]
congr! 1 with i hi
simp only [Set.mem_iInter] at hj
exact Set.indicator_of_mem (hj _ hi) _
· obtain ⟨i, hi, hj⟩ := by simpa using hj
exact Finset.prod_eq_zero hi <| Set.indicator_of_notMem hj _
lemma prod_indicator (s : Finset ι) (f : ι → Set κ) (g : ι → κ → R) :
∏ i ∈ s, (f i).indicator (g i) = (⋂ x ∈ s, f x).indicator (∏ i ∈ s, g i) := by
ext a; simpa using prod_indicator_apply ..
lemma prod_indicator_const_apply (s : Finset ι) (f : ι → Set κ) (g : κ → R) (j : κ) :
∏ i ∈ s, (f i).indicator g j = (⋂ x ∈ s, f x).indicator (g ^ #s) j := by
simp [prod_indicator_apply]
lemma prod_indicator_const (s : Finset ι) (f : ι → Set κ) (g : κ → R) :
∏ i ∈ s, (f i).indicator g = (⋂ x ∈ s, f x).indicator (g ^ #s) := by simp [prod_indicator]
end CommSemiring
section MulSingle
variable {I : Type*} [DecidableEq I] {M : I → Type*}
variable [∀ i, CommMonoid (M i)]
@[to_additive]
theorem Finset.univ_prod_mulSingle [Fintype I] (f : ∀ i, M i) :
(∏ i, Pi.mulSingle i (f i)) = f := by
ext a
simp
@[to_additive]
theorem MonoidHom.functions_ext [Finite I] (N : Type*) [CommMonoid N] (g h : (∀ i, M i) →* N)
(H : ∀ i x, g (Pi.mulSingle i x) = h (Pi.mulSingle i x)) : g = h := by
cases nonempty_fintype I
ext k
rw [← Finset.univ_prod_mulSingle k, map_prod, map_prod]
simp only [H]
/-- This is used as the ext lemma instead of `MonoidHom.functions_ext` for reasons explained in
note [partially-applied ext lemmas]. -/
@[to_additive (attr := ext)
/-- This is used as the ext lemma instead of `AddMonoidHom.functions_ext` for reasons
explained in note [partially-applied ext lemmas]. -/]
theorem MonoidHom.functions_ext' [Finite I] (N : Type*) [CommMonoid N] (g h : (∀ i, M i) →* N)
(H : ∀ i, g.comp (MonoidHom.mulSingle M i) = h.comp (MonoidHom.mulSingle M i)) : g = h :=
g.functions_ext N h fun i => DFunLike.congr_fun (H i)
end MulSingle
section RingHom
open Pi
variable {I : Type*} [DecidableEq I] {R : I → Type*}
variable [∀ i, NonAssocSemiring (R i)]
@[ext]
theorem RingHom.functions_ext [Finite I] (S : Type*) [NonAssocSemiring S] (g h : (∀ i, R i) →+* S)
(H : ∀ (i : I) (x : R i), g (single i x) = h (single i x)) : g = h :=
RingHom.coe_addMonoidHom_injective <|
@AddMonoidHom.functions_ext I _ R _ _ S _ (g : (∀ i, R i) →+ S) h H
end RingHom
namespace Prod
variable [CommMonoid M] [CommMonoid N] {s : Finset ι} {f : ι → M × N}
@[to_additive]
theorem fst_prod : (∏ c ∈ s, f c).1 = ∏ c ∈ s, (f c).1 :=
map_prod (MonoidHom.fst ..) f s
@[to_additive]
theorem snd_prod : (∏ c ∈ s, f c).2 = ∏ c ∈ s, (f c).2 :=
map_prod (MonoidHom.snd ..) f s
end Prod
section MulEquiv
/-- The canonical isomorphism between the monoid of homomorphisms from a finite product of
commutative monoids to another commutative monoid and the product of the homomorphism monoids. -/
@[to_additive /-- The canonical isomorphism between the additive monoid of homomorphisms from
a finite product of additive commutative monoids to another additive commutative monoid and
the product of the homomorphism monoids. -/]
def Pi.monoidHomMulEquiv {ι : Type*} [Fintype ι] [DecidableEq ι] (M : ι → Type*)
[(i : ι) → CommMonoid (M i)] (M' : Type*) [CommMonoid M'] :
(((i : ι) → M i) →* M') ≃* ((i : ι) → (M i →* M')) where
toFun φ i := φ.comp <| MonoidHom.mulSingle M i
invFun φ := ∏ (i : ι), (φ i).comp (Pi.evalMonoidHom M i)
left_inv φ := by
ext
simp only [MonoidHom.finset_prod_apply, MonoidHom.coe_comp, Function.comp_apply,
evalMonoidHom_apply, MonoidHom.mulSingle_apply, ← map_prod]
refine congrArg _ <| funext fun _ ↦ ?_
rw [Fintype.prod_apply]
exact Fintype.prod_pi_mulSingle ..
right_inv φ := by
ext i m
simp only [MonoidHom.coe_comp, Function.comp_apply, MonoidHom.mulSingle_apply,
MonoidHom.finset_prod_apply, evalMonoidHom_apply, ]
let φ' i : M i → M' := ⇑(φ i)
conv =>
enter [1, 2, j]
rw [show φ j = φ' j from rfl, Pi.apply_mulSingle φ' (fun i ↦ map_one (φ i))]
rw [show φ' i = φ i from rfl]
exact Fintype.prod_pi_mulSingle' ..
map_mul' φ ψ := by
ext
simp only [MonoidHom.coe_comp, Function.comp_apply, MonoidHom.mulSingle_apply,
MonoidHom.mul_apply, mul_apply]
end MulEquiv
variable [Finite ι] [DecidableEq ι] {M : Type*}
-- manually additivized to fix variable names
-- See https://github.com/leanprover-community/mathlib4/issues/11462
lemma Pi.single_induction [AddCommMonoid M] (p : (ι → M) → Prop) (f : ι → M)
(zero : p 0) (add : ∀ f g, p f → p g → p (f + g))
(single : ∀ i m, p (Pi.single i m)) : p f := by
cases nonempty_fintype ι
rw [← Finset.univ_sum_single f]
exact Finset.sum_induction _ _ add zero (by simp [single])
@[to_additive existing (attr := elab_as_elim)]
lemma Pi.mulSingle_induction [CommMonoid M] (p : (ι → M) → Prop) (f : ι → M)
(one : p 1) (mul : ∀ f g, p f → p g → p (f * g))
(mulSingle : ∀ i m, p (Pi.mulSingle i m)) : p f := by
cases nonempty_fintype ι
rw [← Finset.univ_prod_mulSingle f]
exact Finset.prod_induction _ _ mul one (by simp [mulSingle])
section EqOn
@[to_additive]
theorem eqOn_finsetProd {ι α β : Type*} [CommMonoid α]
{s : Set β} {f f' : ι → β → α} (h : ∀ (i : ι), Set.EqOn (f i) (f' i) s) (v : Finset ι) :
Set.EqOn (∏ i ∈ v, f i) (∏ i ∈ v, f' i) s :=
fun t ht => by simp [funext fun i ↦ h i ht]
@[to_additive]
theorem eqOn_fun_finsetProd {ι α β : Type*} [CommMonoid α]
{s : Set β} {f f' : ι → β → α} (h : ∀ (i : ι), Set.EqOn (f i) (f' i) s) (v : Finset ι) :
Set.EqOn (fun b ↦ ∏ i ∈ v, f i b) (fun b ↦ ∏ i ∈ v, f' i b) s := by
convert eqOn_finsetProd h v <;> simp
end EqOn
|
Projections.lean
|
/-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import Mathlib.AlgebraicTopology.DoldKan.Faces
import Mathlib.CategoryTheory.Idempotents.Basic
/-!
# Construction of projections for the Dold-Kan correspondence
In this file, we construct endomorphisms `P q : K[X] ⟶ K[X]` for all
`q : ℕ`. We study how they behave with respect to face maps with the lemmas
`HigherFacesVanish.of_P`, `HigherFacesVanish.comp_P_eq_self` and
`comp_P_eq_self_iff`.
Then, we show that they are projections (see `P_f_idem`
and `P_idem`). They are natural transformations (see `natTransP`
and `P_f_naturality`) and are compatible with the application
of additive functors (see `map_P`).
By passing to the limit, these endomorphisms `P q` shall be used in `PInfty.lean`
in order to define `PInfty : K[X] ⟶ K[X]`.
(See `Equivalence.lean` for the general strategy of proof of the Dold-Kan equivalence.)
-/
open CategoryTheory CategoryTheory.Category CategoryTheory.Limits CategoryTheory.Preadditive
CategoryTheory.SimplicialObject Opposite CategoryTheory.Idempotents
open Simplicial DoldKan
noncomputable section
namespace AlgebraicTopology
namespace DoldKan
variable {C : Type*} [Category C] [Preadditive C] {X : SimplicialObject C}
/-- This is the inductive definition of the projections `P q : K[X] ⟶ K[X]`,
with `P 0 := 𝟙 _` and `P (q+1) := P q ≫ (𝟙 _ + Hσ q)`. -/
noncomputable def P : ℕ → (K[X] ⟶ K[X])
| 0 => 𝟙 _
| q + 1 => P q ≫ (𝟙 _ + Hσ q)
lemma P_zero : (P 0 : K[X] ⟶ K[X]) = 𝟙 _ := rfl
lemma P_succ (q : ℕ) : (P (q+1) : K[X] ⟶ K[X]) = P q ≫ (𝟙 _ + Hσ q) := rfl
/-- All the `P q` coincide with `𝟙 _` in degree 0. -/
@[simp]
theorem P_f_0_eq (q : ℕ) : ((P q).f 0 : X _⦋0⦌ ⟶ X _⦋0⦌) = 𝟙 _ := by
induction' q with q hq
· rfl
· simp only [P_succ, HomologicalComplex.add_f_apply, HomologicalComplex.comp_f,
HomologicalComplex.id_f, id_comp, hq, Hσ_eq_zero, add_zero]
/-- `Q q` is the complement projection associated to `P q` -/
def Q (q : ℕ) : K[X] ⟶ K[X] :=
𝟙 _ - P q
theorem P_add_Q (q : ℕ) : P q + Q q = 𝟙 K[X] := by
rw [Q]
abel
theorem P_add_Q_f (q n : ℕ) : (P q).f n + (Q q).f n = 𝟙 (X _⦋n⦌) :=
HomologicalComplex.congr_hom (P_add_Q q) n
@[simp]
theorem Q_zero : (Q 0 : K[X] ⟶ _) = 0 :=
sub_self _
theorem Q_succ (q : ℕ) : (Q (q + 1) : K[X] ⟶ _) = Q q - P q ≫ Hσ q := by
simp only [Q, P_succ, comp_add, comp_id]
abel
/-- All the `Q q` coincide with `0` in degree 0. -/
@[simp]
theorem Q_f_0_eq (q : ℕ) : ((Q q).f 0 : X _⦋0⦌ ⟶ X _⦋0⦌) = 0 := by
simp only [HomologicalComplex.sub_f_apply, HomologicalComplex.id_f, Q, P_f_0_eq, sub_self]
namespace HigherFacesVanish
/-- This lemma expresses the vanishing of
`(P q).f (n+1) ≫ X.δ k : X _⦋n+1⦌ ⟶ X _⦋n⦌` when `k≠0` and `k≥n-q+2` -/
theorem of_P : ∀ q n : ℕ, HigherFacesVanish q ((P q).f (n + 1) : X _⦋n + 1⦌ ⟶ X _⦋n + 1⦌)
| 0 => fun n j hj₁ => by omega
| q + 1 => fun n => by
simp only [P_succ]
exact (of_P q n).induction
@[reassoc]
theorem comp_P_eq_self {Y : C} {n q : ℕ} {φ : Y ⟶ X _⦋n + 1⦌} (v : HigherFacesVanish q φ) :
φ ≫ (P q).f (n + 1) = φ := by
induction' q with q hq
· simp only [P_zero]
apply comp_id
· simp only [P_succ, comp_add, HomologicalComplex.comp_f, HomologicalComplex.add_f_apply,
comp_id, ← assoc, hq v.of_succ, add_eq_left]
by_cases hqn : n < q
· exact v.of_succ.comp_Hσ_eq_zero hqn
· obtain ⟨a, ha⟩ := Nat.le.dest (not_lt.mp hqn)
have hnaq : n = a + q := by omega
simp only [v.of_succ.comp_Hσ_eq hnaq, neg_eq_zero, ← assoc]
have eq := v ⟨a, by omega⟩ (by
simp only [hnaq, add_assoc]
rfl)
simp only [Fin.succ_mk] at eq
simp only [eq, zero_comp]
end HigherFacesVanish
theorem comp_P_eq_self_iff {Y : C} {n q : ℕ} {φ : Y ⟶ X _⦋n + 1⦌} :
φ ≫ (P q).f (n + 1) = φ ↔ HigherFacesVanish q φ := by
constructor
· intro hφ
rw [← hφ]
apply HigherFacesVanish.of_comp
apply HigherFacesVanish.of_P
· exact HigherFacesVanish.comp_P_eq_self
@[reassoc (attr := simp)]
theorem P_f_idem (q n : ℕ) : ((P q).f n : X _⦋n⦌ ⟶ _) ≫ (P q).f n = (P q).f n := by
rcases n with (_ | n)
· rw [P_f_0_eq q, comp_id]
· exact (HigherFacesVanish.of_P q n).comp_P_eq_self
@[reassoc (attr := simp)]
theorem Q_f_idem (q n : ℕ) : ((Q q).f n : X _⦋n⦌ ⟶ _) ≫ (Q q).f n = (Q q).f n :=
idem_of_id_sub_idem _ (P_f_idem q n)
@[reassoc (attr := simp)]
theorem P_idem (q : ℕ) : (P q : K[X] ⟶ K[X]) ≫ P q = P q := by
ext n
exact P_f_idem q n
@[reassoc (attr := simp)]
theorem Q_idem (q : ℕ) : (Q q : K[X] ⟶ K[X]) ≫ Q q = Q q := by
ext n
exact Q_f_idem q n
/-- For each `q`, `P q` is a natural transformation. -/
@[simps]
def natTransP (q : ℕ) : alternatingFaceMapComplex C ⟶ alternatingFaceMapComplex C where
app _ := P q
naturality _ _ f := by
induction' q with q hq
· dsimp [alternatingFaceMapComplex]
simp only [P_zero, id_comp, comp_id]
· simp only [P_succ, add_comp, comp_add, assoc, comp_id, hq, reassoc_of% hq]
-- `erw` is needed to see through `natTransHσ q).app = Hσ q`
erw [(natTransHσ q).naturality f]
rfl
@[reassoc (attr := simp)]
theorem P_f_naturality (q n : ℕ) {X Y : SimplicialObject C} (f : X ⟶ Y) :
f.app (op ⦋n⦌) ≫ (P q).f n = (P q).f n ≫ f.app (op ⦋n⦌) :=
HomologicalComplex.congr_hom ((natTransP q).naturality f) n
@[reassoc (attr := simp)]
theorem Q_f_naturality (q n : ℕ) {X Y : SimplicialObject C} (f : X ⟶ Y) :
f.app (op ⦋n⦌) ≫ (Q q).f n = (Q q).f n ≫ f.app (op ⦋n⦌) := by
simp only [Q, HomologicalComplex.sub_f_apply, HomologicalComplex.id_f, comp_sub, P_f_naturality,
sub_comp, sub_left_inj]
dsimp
simp only [comp_id, id_comp]
/-- For each `q`, `Q q` is a natural transformation. -/
@[simps]
def natTransQ (q : ℕ) : alternatingFaceMapComplex C ⟶ alternatingFaceMapComplex C where
app _ := Q q
theorem map_P {D : Type*} [Category D] [Preadditive D] (G : C ⥤ D) [G.Additive]
(X : SimplicialObject C) (q n : ℕ) :
G.map ((P q : K[X] ⟶ _).f n) = (P q : K[((whiskering C D).obj G).obj X] ⟶ _).f n := by
induction' q with q hq
· simp only [P_zero]
apply G.map_id
· simp only [P_succ, comp_add, HomologicalComplex.comp_f, HomologicalComplex.add_f_apply,
comp_id, Functor.map_add, Functor.map_comp, hq, map_Hσ]
theorem map_Q {D : Type*} [Category D] [Preadditive D] (G : C ⥤ D) [G.Additive]
(X : SimplicialObject C) (q n : ℕ) :
G.map ((Q q : K[X] ⟶ _).f n) = (Q q : K[((whiskering C D).obj G).obj X] ⟶ _).f n := by
rw [← add_right_inj (G.map ((P q : K[X] ⟶ _).f n)), ← G.map_add, map_P G X q n, P_add_Q_f,
P_add_Q_f]
apply G.map_id
end DoldKan
end AlgebraicTopology
|
Basic.lean
|
/-
Copyright (c) 2024 Christian Merten. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Christian Merten
-/
import Mathlib.Algebra.Category.Ring.Colimits
import Mathlib.Algebra.Category.Ring.Constructions
import Mathlib.CategoryTheory.Comma.Over.Pullback
/-!
# Under `CommRingCat`
In this file we provide basic API for `Under R` when `R : CommRingCat`. `Under R` is
(equivalent to) the category of commutative `R`-algebras. For not necessarily commutative
algebras, use `AlgCat R` instead.
-/
noncomputable section
universe u
open TensorProduct CategoryTheory Limits
variable {R S : CommRingCat.{u}}
namespace CommRingCat
instance : CoeSort (Under R) (Type u) where
coe A := A.right
instance (A : Under R) : Algebra R A := RingHom.toAlgebra A.hom.hom
/-- Turn a morphism in `Under R` into an algebra homomorphism. -/
def toAlgHom {A B : Under R} (f : A ⟶ B) : A →ₐ[R] B where
__ := f.right.hom
commutes' a := by
have : (A.hom ≫ f.right) a = B.hom a := by simp
simpa only [Functor.const_obj_obj, Functor.id_obj, CommRingCat.comp_apply] using this
@[simp]
lemma toAlgHom_id (A : Under R) : toAlgHom (𝟙 A) = AlgHom.id R A := rfl
@[simp]
lemma toAlgHom_comp {A B C : Under R} (f : A ⟶ B) (g : B ⟶ C) :
toAlgHom (f ≫ g) = (toAlgHom g).comp (toAlgHom f) := rfl
@[simp]
lemma toAlgHom_apply {A B : Under R} (f : A ⟶ B) (a : A) :
toAlgHom f a = f.right a :=
rfl
variable (R) in
/-- Make an object of `Under R` from an `R`-algebra. -/
@[simps! hom, simps! -isSimp right]
def mkUnder (A : Type u) [CommRing A] [Algebra R A] : Under R :=
Under.mk (CommRingCat.ofHom <| algebraMap R A)
@[ext]
lemma mkUnder_ext {A : Type u} [CommRing A] [Algebra R A] {B : Under R}
{f g : mkUnder R A ⟶ B} (h : ∀ a : A, f.right a = g.right a) :
f = g := by
ext x
exact h x
end CommRingCat
namespace AlgHom
/-- Make a morphism in `Under R` from an algebra map. -/
def toUnder {A B : Type u} [CommRing A] [CommRing B] [Algebra R A] [Algebra R B]
(f : A →ₐ[R] B) : CommRingCat.mkUnder R A ⟶ CommRingCat.mkUnder R B :=
Under.homMk (CommRingCat.ofHom f.toRingHom) <| by
ext a
exact f.commutes' a
@[simp]
lemma toUnder_right {A B : Type u} [CommRing A] [CommRing B] [Algebra R A]
[Algebra R B] (f : A →ₐ[R] B) (a : A) :
f.toUnder.right a = f a :=
rfl
@[simp]
lemma toUnder_comp {A B C : Type u} [CommRing A] [CommRing B] [CommRing C]
[Algebra R A] [Algebra R B] [Algebra R C] (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).toUnder = f.toUnder ≫ g.toUnder :=
rfl
end AlgHom
namespace AlgEquiv
/-- Make an isomorphism in `Under R` from an algebra isomorphism. -/
def toUnder {A B : Type u} [CommRing A] [CommRing B] [Algebra R A] [Algebra R B]
(f : A ≃ₐ[R] B) :
CommRingCat.mkUnder R A ≅ CommRingCat.mkUnder R B where
hom := f.toAlgHom.toUnder
inv := f.symm.toAlgHom.toUnder
hom_inv_id := by
ext (a : (CommRingCat.mkUnder R A).right)
simp
inv_hom_id := by
ext a
simp
@[simp]
lemma toUnder_hom_right_apply {A B : Type u} [CommRing A] [CommRing B] [Algebra R A]
[Algebra R B] (f : A ≃ₐ[R] B) (a : A) :
f.toUnder.hom.right a = f a := rfl
@[simp]
lemma toUnder_inv_right_apply {A B : Type u} [CommRing A] [CommRing B] [Algebra R A]
[Algebra R B] (f : A ≃ₐ[R] B) (b : B) :
f.toUnder.inv.right b = f.symm b := rfl
@[simp]
lemma toUnder_trans {A B C : Type u} [CommRing A] [CommRing B] [CommRing C]
[Algebra R A] [Algebra R B] [Algebra R C] (f : A ≃ₐ[R] B) (g : B ≃ₐ[R] C) :
(f.trans g).toUnder = f.toUnder ≪≫ g.toUnder :=
rfl
end AlgEquiv
namespace CommRingCat
variable [Algebra R S]
variable (R S) in
/-- The base change functor `A ↦ S ⊗[R] A`. -/
@[simps! map_right]
def tensorProd : Under R ⥤ Under S where
obj A := mkUnder S (S ⊗[R] A)
map f := Algebra.TensorProduct.map (AlgHom.id S S) (toAlgHom f) |>.toUnder
map_comp {X Y Z} f g := by simp [Algebra.TensorProduct.map_id_comp]
variable (S) in
/-- The natural isomorphism `S ⊗[R] A ≅ pushout A.hom (algebraMap R S)` in `Under S`. -/
def tensorProdObjIsoPushoutObj (A : Under R) :
mkUnder S (S ⊗[R] A) ≅ (Under.pushout (ofHom <| algebraMap R S)).obj A :=
Under.isoMk (CommRingCat.isPushout_tensorProduct R S A).flip.isoPushout <| by
simp only [Functor.const_obj_obj, Under.pushout_obj, Functor.id_obj, Under.mk_right,
mkUnder_hom, AlgHom.toRingHom_eq_coe, IsPushout.inr_isoPushout_hom, Under.mk_hom]
rfl
@[reassoc (attr := simp)]
lemma pushout_inl_tensorProdObjIsoPushoutObj_inv_right (A : Under R) :
pushout.inl A.hom (ofHom <| algebraMap R S) ≫ (tensorProdObjIsoPushoutObj S A).inv.right =
(ofHom <| Algebra.TensorProduct.includeRight.toRingHom) := by
simp [tensorProdObjIsoPushoutObj]
@[reassoc (attr := simp)]
lemma pushout_inr_tensorProdObjIsoPushoutObj_inv_right (A : Under R) :
pushout.inr A.hom (ofHom <| algebraMap R S) ≫
(tensorProdObjIsoPushoutObj S A).inv.right =
(CommRingCat.ofHom <| Algebra.TensorProduct.includeLeftRingHom) := by
simp [tensorProdObjIsoPushoutObj]
variable (R S) in
/-- `A ↦ S ⊗[R] A` is naturally isomorphic to `A ↦ pushout A.hom (algebraMap R S)`. -/
def tensorProdIsoPushout : tensorProd R S ≅ Under.pushout (ofHom <| algebraMap R S) :=
NatIso.ofComponents (fun A ↦ tensorProdObjIsoPushoutObj S A) <| by
intro A B f
dsimp
rw [← cancel_epi (tensorProdObjIsoPushoutObj S A).inv]
ext : 1
apply pushout.hom_ext
· rw [← cancel_mono (tensorProdObjIsoPushoutObj S B).inv.right]
ext x
simp [mkUnder_right]
· rw [← cancel_mono (tensorProdObjIsoPushoutObj S B).inv.right]
ext (x : S)
simp [mkUnder_right]
@[simp]
lemma tensorProdIsoPushout_app (A : Under R) :
(tensorProdIsoPushout R S).app A = tensorProdObjIsoPushoutObj S A :=
rfl
end CommRingCat
|
generic_quotient.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat choice.
From mathcomp Require Import seq fintype.
(*****************************************************************************)
(* Quotient Types *)
(* *)
(* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *)
(* *)
(* Provided a base type T, this files defines an interface for quotients Q *)
(* of the type T with explicit functions for canonical surjection (\pi *)
(* : T -> Q) and for choosing a representative (repr : Q -> T). It then *)
(* provides a helper to quotient T by a decidable equivalence relation (e *)
(* : rel T) if T is a choiceType (or encodable as a choiceType modulo e). *)
(* *)
(* Reference: Cyril Cohen, Pragmatic Quotient Types in Coq, ITP 2013 *)
(* *)
(* *** Generic Quotienting *** *)
(* quotType T == the type of quotient types based on T *)
(* The HB class is called Quotient. *)
(* *)
(* The quotType interface supports these operations (in quotient_scope): *)
(* \pi_Q x == the class in Q of the element x of T *)
(* \pi x == the class of x where Q is inferred from the context *)
(* repr c == canonical representative in T of the class c *)
(* x = y %[mod Q] := \pi_Q x = \pi_Q y *)
(* <-> x and y are equal modulo Q *)
(* x <> y %[mod Q] := \pi_Q x <> \pi_Q y *)
(* x == y %[mod Q] := \pi_Q x == \pi_Q y *)
(* x != y %[mod Q] := \pi_Q x != \pi_Q y *)
(* *)
(* The quotient_scope is delimited by %qT, *)
(* The most useful lemmas are piE and reprK. *)
(* *)
(* List of factories: *)
(* isQuotient.Build T Q (reprK : cancel repr pi) == builds the quotient *)
(* whose canonical surjection function is (pi : T -> Q) and *)
(* whose representative selection function is repr *)
(* *** Morphisms *** *)
(* One may declare existing functions and predicates as liftings of some *)
(* morphisms for a quotient. *)
(* PiMorph1 pi_f == where pi_f : {morph \pi : x / f x >-> fq x} *)
(* declares fq : Q -> Q as the lifting of f : T -> T *)
(* PiMorph2 pi_g == idem with pi_g : {morph \pi : x y / g x y >-> gq x y} *)
(* PiMono1 pi_p == idem with pi_p : {mono \pi : x / p x >-> pq x} *)
(* PiMono2 pi_r == idem with pi_r : {morph \pi : x y / r x y >-> rq x y} *)
(* PiMorph11 pi_f == idem with pi_f : {morph \pi : x / f x >-> fq x} *)
(* where fq : Q -> Q' and f : T -> T'. *)
(* PiMorph eq == Most general declaration of compatibility, *)
(* /!\ use with caution /!\ *)
(* One can use the following helpers to build the liftings which may or *)
(* may not satisfy the above properties (but if they do not, it is *)
(* probably not a good idea to define them): *)
(* lift_op1 Q f := lifts f : T -> T *)
(* lift_op2 Q g := lifts g : T -> T -> T *)
(* lift_fun1 Q p := lifts p : T -> R *)
(* lift_fun2 Q r := lifts r : T -> T -> R *)
(* lift_op11 Q Q' f := lifts f : T -> T' *)
(* There is also the special case of constants and embedding functions *)
(* that one may define and declare as compatible with Q using: *)
(* lift_cst Q x := lifts x : T to Q *)
(* PiConst c := declare the result c of the previous construction as *)
(* compatible with Q *)
(* lift_embed Q e := lifts e : R -> T to R -> Q *)
(* PiEmbed f := declare the result f of the previous construction as *)
(* compatible with Q *)
(* *)
(* *** Quotients that have an eqType structure *** *)
(* Having a canonical (eqQuotType e) structure enables piE to replace terms *)
(* of the form (x == y) by terms of the form (e x' y') if x and y are *)
(* canonical surjections of some x' and y'. *)
(* eqQuotType e == the type of quotients types on T which mirror *)
(* the equivalence relation (e : rel T) *)
(* the HB class is called EqQuotient. *)
(* *)
(* The most useful property is that an eqQuotType is an eqType. *)
(* List of factories: *)
(* isEqQuotient.Build T e Q m *)
(* == builds an (eqQuotType e) structure on Q from the *)
(* morphism property m *)
(* where m : {mono \pi : x y / e x y >-> x == y} *)
(* *)
(* *** Equivalence and quotient by an equivalence *** *)
(* EquivRel r er es et == builds an equiv_rel structure based on the *)
(* reflexivity, symmetry and transitivity property *)
(* of a boolean relation. *)
(* {eq_quot e} == builds the quotType of T by equiv *)
(* where e : rel T is an equiv_rel *)
(* and T is a choiceType or a (choiceTypeMod e) *)
(* it is canonically an eqType, a choiceType, *)
(* a quotType and an eqQuotType *)
(* x = y %[mod_eq e] := x = y %[mod {eq_quot e}] *)
(* <-> x and y are equal modulo e *)
(* ... *)
(*****************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Declare Scope quotient_scope.
Reserved Notation "\pi_ Q" (at level 0, format "\pi_ Q").
Reserved Notation "\pi" (format "\pi").
Reserved Notation "{pi_ Q a }" (Q at next level, format "{pi_ Q a }").
Reserved Notation "{pi a }" (format "{pi a }").
#[warning="-postfix-notation-not-level-1"]
Reserved Notation "x == y %[mod_eq e ]"
(no associativity, format "'[hv ' x '/' == y '/' %[mod_eq e ] ']'").
#[warning="-postfix-notation-not-level-1"]
Reserved Notation "x = y %[mod_eq e ]"
(no associativity, format "'[hv ' x '/' = y '/' %[mod_eq e ] ']'").
#[warning="-postfix-notation-not-level-1"]
Reserved Notation "x != y %[mod_eq e ]"
(no associativity, format "'[hv ' x '/' != y '/' %[mod_eq e ] ']'").
#[warning="-postfix-notation-not-level-1"]
Reserved Notation "x <> y %[mod_eq e ]"
(no associativity, format "'[hv ' x '/' <> y '/' %[mod_eq e ] ']'").
Reserved Notation "{eq_quot e }" (format "{eq_quot e }").
Delimit Scope quotient_scope with qT.
Local Open Scope quotient_scope.
(*****************************************)
(* Definition of the quotient interface. *)
(*****************************************)
HB.mixin Record isQuotient T (qT : Type) := {
repr_of : qT -> T;
quot_pi_subdef : T -> qT;
repr_ofK_subproof : cancel repr_of quot_pi_subdef
}.
#[short(type="quotType")]
HB.structure Definition Quotient T := { qT of isQuotient T qT }.
Arguments repr_of [T qT] : rename.
Section QuotientDef.
Variable T : Type.
Variable qT : quotType T.
Definition pi_subdef := @quot_pi_subdef _ qT.
Local Notation "\pi" := pi_subdef.
Lemma repr_ofK : cancel (@repr_of _ _) \pi.
Proof. exact: repr_ofK_subproof. Qed.
End QuotientDef.
Arguments repr_ofK {T qT}.
(****************************)
(* Protecting some symbols. *)
(****************************)
HB.lock Definition pi := pi_subdef.
HB.lock Definition mpi := pi_subdef.
HB.lock Definition repr := repr_of.
(*******************)
(* Fancy Notations *)
(*******************)
Arguments pi.body [T]%_type qT%_type.
Notation "\pi_ Q" := (@pi _ Q) : quotient_scope.
Notation "\pi" := (@pi _ _) (only parsing) : quotient_scope.
Notation "x == y %[mod Q ]" := (\pi_Q x == \pi_Q y) : quotient_scope.
Notation "x = y %[mod Q ]" := (\pi_Q x = \pi_Q y) : quotient_scope.
Notation "x != y %[mod Q ]" := (\pi_Q x != \pi_Q y) : quotient_scope.
Notation "x <> y %[mod Q ]" := (\pi_Q x <> \pi_Q y) : quotient_scope.
Local Notation "\mpi" := (@mpi _ _).
Canonical mpi_unlock := Unlockable mpi.unlock.
Canonical pi_unlock := Unlockable pi.unlock.
Canonical repr_unlock := Unlockable repr.unlock.
Arguments repr {T qT} x.
(************************)
(* Exporting the theory *)
(************************)
Section QuotTypeTheory.
Variable T : Type.
Variable qT : quotType T.
Lemma reprK : cancel repr \pi_qT.
Proof. by move=> x; rewrite !unlock repr_ofK. Qed.
Variant pi_spec (x : T) : T -> Type :=
PiSpec y of x = y %[mod qT] : pi_spec x y.
Lemma piP (x : T) : pi_spec x (repr (\pi_qT x)).
Proof. by constructor; rewrite reprK. Qed.
Lemma mpiE : \mpi =1 \pi_qT.
Proof. by move=> x; rewrite !unlock. Qed.
Lemma quotW P : (forall y : T, P (\pi_qT y)) -> forall x : qT, P x.
Proof. by move=> Py x; rewrite -[x]reprK; apply: Py. Qed.
Lemma quotP P : (forall y : T, repr (\pi_qT y) = y -> P (\pi_qT y))
-> forall x : qT, P x.
Proof. by move=> Py x; rewrite -[x]reprK; apply: Py; rewrite reprK. Qed.
End QuotTypeTheory.
Arguments reprK {T qT} x.
(*******************)
(* About morphisms *)
(*******************)
(* This was pi_morph T (x : T) := PiMorph { pi_op : T; _ : x = pi_op }. *)
Structure equal_to T (x : T) := EqualTo {
equal_val : T;
_ : x = equal_val
}.
Lemma equal_toE (T : Type) (x : T) (m : equal_to x) : equal_val m = x.
Proof. by case: m. Qed.
Notation piE := (@equal_toE _ _).
Canonical equal_to_pi T (qT : quotType T) (x : T) :=
@EqualTo _ (\pi_qT x) (\pi x) (erefl _).
Arguments EqualTo {T x equal_val}.
Section Morphism.
Variables T U : Type.
Variable (qT : quotType T).
Variable (qU : quotType U).
Variable (f : T -> T) (g : T -> T -> T) (p : T -> U) (r : T -> T -> U).
Variable (fq : qT -> qT) (gq : qT -> qT -> qT) (pq : qT -> U) (rq : qT -> qT -> U).
Variable (h : T -> U) (hq : qT -> qU).
Hypothesis pi_f : {morph \pi : x / f x >-> fq x}.
Hypothesis pi_g : {morph \pi : x y / g x y >-> gq x y}.
Hypothesis pi_p : {mono \pi : x / p x >-> pq x}.
Hypothesis pi_r : {mono \pi : x y / r x y >-> rq x y}.
Hypothesis pi_h : forall (x : T), \pi_qU (h x) = hq (\pi_qT x).
Variables (a b : T) (x : equal_to (\pi_qT a)) (y : equal_to (\pi_qT b)).
(* Internal Lemmas : do not use directly *)
Lemma pi_morph1 : \pi (f a) = fq (equal_val x). Proof. by rewrite !piE. Qed.
Lemma pi_morph2 : \pi (g a b) = gq (equal_val x) (equal_val y). Proof. by rewrite !piE. Qed.
Lemma pi_mono1 : p a = pq (equal_val x). Proof. by rewrite !piE. Qed.
Lemma pi_mono2 : r a b = rq (equal_val x) (equal_val y). Proof. by rewrite !piE. Qed.
Lemma pi_morph11 : \pi (h a) = hq (equal_val x). Proof. by rewrite !piE. Qed.
End Morphism.
Arguments pi_morph1 {T qT f fq}.
Arguments pi_morph2 {T qT g gq}.
Arguments pi_mono1 {T U qT p pq}.
Arguments pi_mono2 {T U qT r rq}.
Arguments pi_morph11 {T U qT qU h hq}.
Notation "{pi_ Q a }" := (equal_to (\pi_Q a)) : quotient_scope.
Notation "{pi a }" := (equal_to (\pi a)) : quotient_scope.
(* Declaration of morphisms *)
Notation PiMorph pi_x := (EqualTo pi_x).
Notation PiMorph1 pi_f :=
(fun a (x : {pi a}) => EqualTo (pi_morph1 pi_f a x)).
Notation PiMorph2 pi_g :=
(fun a b (x : {pi a}) (y : {pi b}) => EqualTo (pi_morph2 pi_g a b x y)).
Notation PiMono1 pi_p :=
(fun a (x : {pi a}) => EqualTo (pi_mono1 pi_p a x)).
Notation PiMono2 pi_r :=
(fun a b (x : {pi a}) (y : {pi b}) => EqualTo (pi_mono2 pi_r a b x y)).
Notation PiMorph11 pi_f :=
(fun a (x : {pi a}) => EqualTo (pi_morph11 pi_f a x)).
(* lifting helpers *)
Notation lift_op1 Q f := (locked (fun x : Q => \pi_Q (f (repr x)) : Q)).
Notation lift_op2 Q g :=
(locked (fun x y : Q => \pi_Q (g (repr x) (repr y)) : Q)).
Notation lift_fun1 Q f := (locked (fun x : Q => f (repr x))).
Notation lift_fun2 Q g := (locked (fun x y : Q => g (repr x) (repr y))).
Notation lift_op11 Q Q' f := (locked (fun x : Q => \pi_Q' (f (repr x)) : Q')).
(* constant declaration *)
Notation lift_cst Q x := (locked (\pi_Q x : Q)).
Notation PiConst a := (@EqualTo _ _ a (lock _)).
(* embedding declaration, please don't redefine \pi *)
Notation lift_embed qT e := (locked (fun x => \pi_qT (e x) : qT)).
Lemma eq_lock T T' e : e =1 (@locked (T -> T') (fun x : T => e x)).
Proof. by rewrite -lock. Qed.
Prenex Implicits eq_lock.
Notation PiEmbed e :=
(fun x => @EqualTo _ _ (e x) (eq_lock (fun _ => \pi _) _)).
(********************)
(* About eqQuotType *)
(********************)
HB.mixin Record isEqQuotient T (eq_quot_op : rel T) (Q : Type) of
isQuotient T Q & hasDecEq Q := {
pi_eq_quot : {mono \pi_Q : x y / eq_quot_op x y >-> x == y}
}.
#[short(type="eqQuotType")]
HB.structure Definition EqQuotient T eq_quot_op :=
{Q of isEqQuotient T eq_quot_op Q & Quotient T Q & hasDecEq Q}.
Canonical pi_eq_quot_mono T eq_quot_op eqT :=
PiMono2 (@pi_eq_quot T eq_quot_op eqT).
(**************************************************************************)
(* Even if a quotType is a natural subType, we do not make this subType *)
(* canonical, to allow the user to define the subtyping he wants. However *)
(* one can: *)
(* - get the hasDecEq and the hasChoice by subtyping *)
(* - get the subType structure and maybe declare it Canonical. *)
(**************************************************************************)
Definition quot_type_of T (qT : quotType T) : Type := qT.
Arguments quot_type_of T%_type qT%_type : clear implicits.
Notation quot_type Q := (quot_type_of _ Q).
HB.instance Definition _ T (qT : quotType T) := Quotient.on (quot_type qT).
Module QuotSubType.
Section QuotSubType.
Variable (T : eqType) (qT : quotType T).
Definition Sub x (px : repr (\pi_qT x) == x) := \pi_qT x.
Lemma qreprK x Px : repr (@Sub x Px) = x.
Proof. by rewrite /Sub (eqP Px). Qed.
Lemma sortPx (x : qT) : repr (\pi_qT (repr x)) == repr x.
Proof. by rewrite !reprK eqxx. Qed.
Lemma sort_Sub (x : qT) : x = Sub (sortPx x).
Proof. by rewrite /Sub reprK. Qed.
Lemma reprP K (PK : forall x Px, K (@Sub x Px)) u : K u.
Proof. by rewrite (sort_Sub u); apply: PK. Qed.
#[export]
HB.instance Definition _ := isSub.Build _ _ (quot_type qT) reprP qreprK.
#[export]
HB.instance Definition _ := [Equality of quot_type qT by <:].
End QuotSubType.
Module Exports. HB.reexport. End Exports.
End QuotSubType.
Export QuotSubType.Exports.
HB.instance Definition _ (T : choiceType) (qT : quotType T) :=
[Choice of quot_type qT by <:].
HB.instance Definition _ (T : countType) (qT : quotType T) :=
[Countable of quot_type qT by <:].
HB.instance Definition _ (T : finType) (qT : quotType T) :=
[Finite of quot_type qT by <:].
Notation "[ 'Sub' Q 'of' T 'by' %/ ]" :=
(SubType.copy Q%type (quot_type_of T Q%type))
(format "[ 'Sub' Q 'of' T 'by' %/ ]") : form_scope.
Notation "[ 'Sub' Q 'by' %/ ]" :=
(SubType.copy Q%type (quot_type Q))
(format "[ 'Sub' Q 'by' %/ ]") : form_scope.
Notation "[ 'Equality' 'of' Q 'by' <:%/ ]" :=
(Equality.copy Q%type (quot_type Q))
(format "[ 'Equality' 'of' Q 'by' <:%/ ]") : form_scope.
Notation "[ 'Choice' 'of' Q 'by' <:%/ ]" := (Choice.copy Q%type (quot_type Q))
(format "[ 'Choice' 'of' Q 'by' <:%/ ]") : form_scope.
Notation "[ 'Countable' 'of' Q 'by' <:%/ ]" := (Countable.copy Q%type (quot_type Q))
(format "[ 'Countable' 'of' Q 'by' <:%/ ]") : form_scope.
Notation "[ 'Finite' 'of' Q 'by' <:%/ ]" := (Finite.copy Q%type (quot_type Q))
(format "[ 'Finite' 'of' Q 'by' <:%/ ]") : form_scope.
(****************************************************)
(* Definition of a (decidable) equivalence relation *)
(****************************************************)
Section EquivRel.
Variable T : Type.
Lemma left_trans (e : rel T) :
symmetric e -> transitive e -> left_transitive e.
Proof. by move=> s t ? * ?; apply/idP/idP; apply: t; rewrite // s. Qed.
Lemma right_trans (e : rel T) :
symmetric e -> transitive e -> right_transitive e.
Proof. by move=> s t ? * x; rewrite ![e x _]s; apply: left_trans. Qed.
Variant equiv_class_of (equiv : rel T) :=
EquivClass of reflexive equiv & symmetric equiv & transitive equiv.
Record equiv_rel := EquivRelPack {
equiv :> rel T;
_ : equiv_class_of equiv
}.
Variable e : equiv_rel.
Definition equiv_class :=
let: EquivRelPack _ ce as e' := e return equiv_class_of e' in ce.
Definition equiv_pack (r : rel T) ce of phant_id ce equiv_class :=
@EquivRelPack r ce.
Lemma equiv_refl x : e x x. Proof. by case: e => [] ? []. Qed.
Lemma equiv_sym : symmetric e. Proof. by case: e => [] ? []. Qed.
Lemma equiv_trans : transitive e. Proof. by case: e => [] ? []. Qed.
Lemma eq_op_trans (T' : eqType) : transitive (@eq_op T').
Proof. by move=> x y z /eqP -> /eqP ->. Qed.
Lemma equiv_ltrans: left_transitive e.
Proof. by apply: left_trans; [apply: equiv_sym|apply: equiv_trans]. Qed.
Lemma equiv_rtrans: right_transitive e.
Proof. by apply: right_trans; [apply: equiv_sym|apply: equiv_trans]. Qed.
End EquivRel.
#[global] Hint Resolve equiv_refl : core.
Notation EquivRel r er es et := (@EquivRelPack _ r (EquivClass er es et)).
Notation "[ 'equiv_rel' 'of' e ]" := (@equiv_pack _ _ e _ id)
(format "[ 'equiv_rel' 'of' e ]") : form_scope.
(**************************************************)
(* Encoding to another type modulo an equivalence *)
(**************************************************)
Section EncodingModuloRel.
Variables (D E : Type) (ED : E -> D) (DE : D -> E) (e : rel D).
Variant encModRel_class_of (r : rel D) :=
EncModRelClassPack of (forall x, r x x -> r (ED (DE x)) x) & (r =2 e).
Record encModRel := EncModRelPack {
enc_mod_rel :> rel D;
_ : encModRel_class_of enc_mod_rel
}.
Variable r : encModRel.
Definition encModRelClass :=
let: EncModRelPack _ c as r' := r return encModRel_class_of r' in c.
Definition encModRelP (x : D) : r x x -> r (ED (DE x)) x.
Proof. by case: r => [] ? [] /= he _ /he. Qed.
Definition encModRelE : r =2 e. Proof. by case: r => [] ? []. Qed.
Definition encoded_equiv : rel E := [rel x y | r (ED x) (ED y)].
End EncodingModuloRel.
Notation EncModRelClass m :=
(EncModRelClassPack (fun x _ => m x) (fun _ _ => erefl _)).
Notation EncModRel r m := (@EncModRelPack _ _ _ _ _ r (EncModRelClass m)).
Section EncodingModuloEquiv.
Variables (D E : Type) (ED : E -> D) (DE : D -> E) (e : equiv_rel D).
Variable (r : encModRel ED DE e).
Lemma enc_mod_rel_is_equiv : equiv_class_of (enc_mod_rel r).
Proof.
split => [x|x y|y x z]; rewrite !encModRelE //; first by rewrite equiv_sym.
by move=> exy /(equiv_trans exy).
Qed.
Definition enc_mod_rel_equiv_rel := EquivRelPack enc_mod_rel_is_equiv.
Definition encModEquivP (x : D) : r (ED (DE x)) x.
Proof. by rewrite encModRelP ?encModRelE. Qed.
Local Notation e' := (encoded_equiv r).
Lemma encoded_equivE : e' =2 [rel x y | e (ED x) (ED y)].
Proof. by move=> x y; rewrite /encoded_equiv /= encModRelE. Qed.
Local Notation e'E := encoded_equivE.
Lemma encoded_equiv_is_equiv : equiv_class_of e'.
Proof.
split => [x|x y|y x z]; rewrite !e'E //=; first by rewrite equiv_sym.
by move=> exy /(equiv_trans exy).
Qed.
Canonical encoded_equiv_equiv_rel := EquivRelPack encoded_equiv_is_equiv.
Lemma encoded_equivP x : e' (DE (ED x)) x.
Proof. by rewrite /encoded_equiv /= encModEquivP. Qed.
End EncodingModuloEquiv.
(**************************************)
(* Quotient by a equivalence relation *)
(**************************************)
Module EquivQuot.
Section EquivQuot.
Variables (D : Type) (C : choiceType) (CD : C -> D) (DC : D -> C).
Variables (eD : equiv_rel D) (encD : encModRel CD DC eD).
Notation eC := (encoded_equiv encD).
Definition canon x := choose (eC x) (x).
Record equivQuotient := EquivQuotient {
erepr : C;
_ : (frel canon) erepr erepr
}.
Definition type_of of (phantom (rel _) encD) := equivQuotient.
Lemma canon_id : forall x, (invariant canon canon) x.
Proof.
move=> x /=; rewrite /canon (@eq_choose _ _ (eC x)).
by rewrite (@choose_id _ (eC x) _ x) ?chooseP ?equiv_refl.
by move=> y; apply: equiv_ltrans; rewrite equiv_sym /= chooseP.
Qed.
Definition pi := locked (fun x => EquivQuotient (canon_id x)).
Lemma ereprK : cancel erepr pi.
Proof.
pose T : subType _ := HB.pack equivQuotient [isSub for erepr].
by unlock pi; case=> x hx; apply/(@val_inj _ _ T)/eqP.
Qed.
Local Notation encDE := (encModRelE encD).
Local Notation encDP := (encModEquivP encD).
Canonical encD_equiv_rel := EquivRelPack (enc_mod_rel_is_equiv encD).
Lemma pi_CD (x y : C) : reflect (pi x = pi y) (eC x y).
Proof.
apply: (iffP idP) => hxy.
apply: (can_inj ereprK); unlock pi canon => /=.
rewrite -(@eq_choose _ (eC x) (eC y)); last first.
by move=> z; rewrite /eC /=; apply: equiv_ltrans.
by apply: choose_id; rewrite ?equiv_refl //.
rewrite (equiv_trans (chooseP (equiv_refl _ _))) //=.
move: hxy => /(f_equal erepr) /=; unlock pi canon => /= ->.
by rewrite equiv_sym /= chooseP.
Qed.
Lemma pi_DC (x y : D) :
reflect (pi (DC x) = pi (DC y)) (eD x y).
Proof.
apply: (iffP idP)=> hxy.
apply/pi_CD; rewrite /eC /=.
by rewrite (equiv_ltrans (encDP _)) (equiv_rtrans (encDP _)) /= encDE.
rewrite -encDE -(equiv_ltrans (encDP _)) -(equiv_rtrans (encDP _)) /=.
exact/pi_CD.
Qed.
Lemma equivQTP : cancel (CD \o erepr) (pi \o DC).
Proof. by move=> x; rewrite /= (pi_CD _ (erepr x) _) ?ereprK /eC /= ?encDP. Qed.
Local Notation qT := (type_of (Phantom (rel D) encD)).
#[export]
HB.instance Definition _ := isQuotient.Build D qT equivQTP.
Lemma eqmodP x y : reflect (x = y %[mod qT]) (eD x y).
Proof. by apply: (iffP (pi_DC _ _)); rewrite !unlock. Qed.
#[export]
HB.instance Definition _ := Choice.copy qT (can_type ereprK).
Lemma eqmodE x y : x == y %[mod qT] = eD x y.
Proof. exact: sameP eqP (@eqmodP _ _). Qed.
#[export]
HB.instance Definition _ := isEqQuotient.Build _ eD qT eqmodE.
End EquivQuot.
Module Exports. HB.reexport. End Exports.
End EquivQuot.
Export EquivQuot.Exports.
Arguments EquivQuot.ereprK {D C CD DC eD encD}.
Notation "{eq_quot e }" :=
(@EquivQuot.type_of _ _ _ _ _ _ (Phantom (rel _) e)) : quotient_scope.
Notation "x == y %[mod_eq r ]" := (x == y %[mod {eq_quot r}]) : quotient_scope.
Notation "x = y %[mod_eq r ]" := (x = y %[mod {eq_quot r}]) : quotient_scope.
Notation "x != y %[mod_eq r ]" := (x != y %[mod {eq_quot r}]) : quotient_scope.
Notation "x <> y %[mod_eq r ]" := (x <> y %[mod {eq_quot r}]) : quotient_scope.
(***********************************************************)
(* If the type is directly a choiceType, no need to encode *)
(***********************************************************)
Section DefaultEncodingModuloRel.
Variables (D : choiceType) (r : rel D).
Definition defaultEncModRelClass :=
@EncModRelClassPack D D id id r r (fun _ rxx => rxx) (fun _ _ => erefl _).
Canonical defaultEncModRel := EncModRelPack defaultEncModRelClass.
End DefaultEncodingModuloRel.
(***************************************************)
(* Recovering a potential countable type structure *)
(***************************************************)
Section CountEncodingModuloRel.
Variables (D : Type) (C : countType) (CD : C -> D) (DC : D -> C).
Variables (eD : equiv_rel D) (encD : encModRel CD DC eD).
Notation eC := (encoded_equiv encD).
HB.instance Definition _ :=
Countable.copy {eq_quot encD} (can_type EquivQuot.ereprK).
End CountEncodingModuloRel.
Section EquivQuotTheory.
Variables (T : choiceType) (e : equiv_rel T) (Q : eqQuotType e).
Lemma eqmodE x y : x == y %[mod_eq e] = e x y.
Proof. by rewrite pi_eq_quot. Qed.
Lemma eqmodP x y : reflect (x = y %[mod_eq e]) (e x y).
Proof. by rewrite -eqmodE; apply/eqP. Qed.
End EquivQuotTheory.
Prenex Implicits eqmodE eqmodP.
Section EqQuotTheory.
Variables (T : Type) (e : rel T) (Q : eqQuotType e).
Lemma eqquotE x y : x == y %[mod Q] = e x y.
Proof. by rewrite pi_eq_quot. Qed.
Lemma eqquotP x y : reflect (x = y %[mod Q]) (e x y).
Proof. by rewrite -eqquotE; apply/eqP. Qed.
End EqQuotTheory.
Prenex Implicits eqquotE eqquotP.
|
Basic.lean
|
/-
Copyright (c) 2025 Mitchell Horner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mitchell Horner
-/
import Mathlib.Algebra.Order.Floor.Defs
import Mathlib.Algebra.Order.Floor.Semiring
import Mathlib.Combinatorics.SimpleGraph.Operations
import Mathlib.Combinatorics.SimpleGraph.Copy
/-!
# Extremal graph theory
This file introduces basic definitions for extremal graph theory, including extremal numbers.
## Main definitions
* `SimpleGraph.IsExtremal` is the predicate that `G` satisfies `p` and any `H` satisfying `p` has
at most as many edges as `G`.
* `SimpleGraph.extremalNumber` is the maximum number of edges in a `H`-free simple graph on `n`
vertices.
If `H` is contained in all simple graphs on `n` vertices, then this is `0`.
-/
open Finset Fintype
namespace SimpleGraph
section IsExtremal
variable {V : Type*} [Fintype V] {G : SimpleGraph V} [DecidableRel G.Adj]
/-- `G` is an extremal graph satisfying `p` if `G` has the maximum number of edges of any simple
graph satisfying `p`. -/
def IsExtremal (G : SimpleGraph V) [DecidableRel G.Adj] (p : SimpleGraph V → Prop) :=
p G ∧ ∀ ⦃G' : SimpleGraph V⦄ [DecidableRel G'.Adj], p G' → #G'.edgeFinset ≤ #G.edgeFinset
lemma IsExtremal.prop {p : SimpleGraph V → Prop} (h : G.IsExtremal p) : p G := h.1
open Classical in
/-- If one simple graph satisfies `p`, then there exists an extremal graph satisfying `p`. -/
theorem exists_isExtremal_iff_exists (p : SimpleGraph V → Prop) :
(∃ G : SimpleGraph V, ∃ _ : DecidableRel G.Adj, G.IsExtremal p) ↔ ∃ G, p G := by
refine ⟨fun ⟨_, _, h⟩ ↦ ⟨_, h.1⟩, fun ⟨G, hp⟩ ↦ ?_⟩
obtain ⟨G', hp', h⟩ := by
apply exists_max_image { G | p G } (#·.edgeFinset)
use G, by simpa using hp
use G', inferInstanceAs (DecidableRel G'.Adj)
exact ⟨by simpa using hp', fun _ _ hp ↦ by convert h _ (by simpa using hp)⟩
/-- If `H` has at least one edge, then there exists an extremal `H.Free` graph. -/
theorem exists_isExtremal_free {W : Type*} {H : SimpleGraph W} (h : H ≠ ⊥) :
∃ G : SimpleGraph V, ∃ _ : DecidableRel G.Adj, G.IsExtremal H.Free :=
(exists_isExtremal_iff_exists H.Free).mpr ⟨⊥, free_bot h⟩
end IsExtremal
section ExtremalNumber
open Classical in
/-- The extremal number of a natural number `n` and a simple graph `H` is the the maximum number of
edges in a `H`-free simple graph on `n` vertices.
If `H` is contained in all simple graphs on `n` vertices, then this is `0`. -/
noncomputable def extremalNumber (n : ℕ) {W : Type*} (H : SimpleGraph W) : ℕ :=
sup { G : SimpleGraph (Fin n) | H.Free G } (#·.edgeFinset)
variable {n : ℕ} {V W : Type*} {G : SimpleGraph V} {H : SimpleGraph W}
open Classical in
theorem extremalNumber_of_fintypeCard_eq [Fintype V] (hc : card V = n) :
extremalNumber n H = sup { G : SimpleGraph V | H.Free G } (#·.edgeFinset) := by
let e := Fintype.equivFinOfCardEq hc
rw [extremalNumber, le_antisymm_iff]
and_intros
on_goal 1 =>
replace e := e.symm
all_goals
rw [Finset.sup_le_iff]
intro G h
let G' := G.map e.toEmbedding
replace h' : G' ∈ univ.filter (H.Free ·) := by
rw [mem_filter, ← free_congr .refl (.map e G)]
simpa using h
rw [Iso.card_edgeFinset_eq (.map e G)]
convert @le_sup _ _ _ _ { G | H.Free G } (#·.edgeFinset) G' h'
variable [Fintype V] [DecidableRel G.Adj]
/-- If `G` is `H`-free, then `G` has at most `extremalNumber (card V) H` edges. -/
theorem card_edgeFinset_le_extremalNumber (h : H.Free G) :
#G.edgeFinset ≤ extremalNumber (card V) H := by
rw [extremalNumber_of_fintypeCard_eq rfl]
convert @le_sup _ _ _ _ { G | H.Free G } (#·.edgeFinset) G (by simpa using h)
/-- If `G` has more than `extremalNumber (card V) H` edges, then `G` contains a copy of `H`. -/
theorem IsContained.of_extremalNumber_lt_card_edgeFinset
(h : extremalNumber (card V) H < #G.edgeFinset) : H ⊑ G := by
contrapose! h
exact card_edgeFinset_le_extremalNumber h
/-- `extremalNumber (card V) H` is at most `x` if and only if every `H`-free simple graph `G` has
at most `x` edges. -/
theorem extremalNumber_le_iff (H : SimpleGraph W) (m : ℕ) :
extremalNumber (card V) H ≤ m ↔
∀ ⦃G : SimpleGraph V⦄ [DecidableRel G.Adj], H.Free G → #G.edgeFinset ≤ m := by
simp_rw [extremalNumber_of_fintypeCard_eq rfl, Finset.sup_le_iff, mem_filter_univ]
exact ⟨fun h _ _ h' ↦ by convert h _ h', fun h _ h' ↦ by convert h h'⟩
/-- `extremalNumber (card V) H` is greater than `x` if and only if there exists a `H`-free simple
graph `G` with more than `x` edges. -/
theorem lt_extremalNumber_iff (H : SimpleGraph W) (m : ℕ) :
m < extremalNumber (card V) H ↔
∃ G : SimpleGraph V, ∃ _ : DecidableRel G.Adj, H.Free G ∧ m < #G.edgeFinset := by
simp_rw [extremalNumber_of_fintypeCard_eq rfl, Finset.lt_sup_iff, mem_filter_univ]
exact ⟨fun ⟨_, h, h'⟩ ↦ ⟨_, _, h, h'⟩, fun ⟨_, _, h, h'⟩ ↦ ⟨_, h, by convert h'⟩⟩
variable {R : Type*} [Semiring R] [LinearOrder R] [FloorSemiring R]
@[inherit_doc extremalNumber_le_iff]
theorem extremalNumber_le_iff_of_nonneg (H : SimpleGraph W) {m : R} (h : 0 ≤ m) :
extremalNumber (card V) H ≤ m ↔
∀ ⦃G : SimpleGraph V⦄ [DecidableRel G.Adj], H.Free G → #G.edgeFinset ≤ m := by
simp_rw [← Nat.le_floor_iff h]
exact extremalNumber_le_iff H ⌊m⌋₊
@[inherit_doc lt_extremalNumber_iff]
theorem lt_extremalNumber_iff_of_nonneg (H : SimpleGraph W) {m : R} (h : 0 ≤ m) :
m < extremalNumber (card V) H ↔
∃ G : SimpleGraph V, ∃ _ : DecidableRel G.Adj, H.Free G ∧ m < #G.edgeFinset := by
simp_rw [← Nat.floor_lt h]
exact lt_extremalNumber_iff H ⌊m⌋₊
/-- If `H` contains a copy of `H'`, then `extremalNumber n H` is at most `extremalNumber n H`. -/
theorem IsContained.extremalNumber_le {W' : Type*} {H' : SimpleGraph W'} (h : H' ⊑ H) :
extremalNumber n H' ≤ extremalNumber n H := by
rw [← Fintype.card_fin n, extremalNumber_le_iff]
intro _ _ h'
contrapose! h'
rw [not_not]
exact h.trans (IsContained.of_extremalNumber_lt_card_edgeFinset h')
/-- If `H₁ ≃g H₂`, then `extremalNumber n H₁` equals `extremalNumber n H₂`. -/
@[congr]
theorem extremalNumber_congr {n₁ n₂ : ℕ} {W₁ W₂ : Type*} {H₁ : SimpleGraph W₁}
{H₂ : SimpleGraph W₂} (h : n₁ = n₂) (e : H₁ ≃g H₂) :
extremalNumber n₁ H₁ = extremalNumber n₂ H₂ := by
rw [h, le_antisymm_iff]
and_intros
on_goal 2 =>
replace e := e.symm
all_goals
rw [← Fintype.card_fin n₂, extremalNumber_le_iff]
intro G _ h
apply card_edgeFinset_le_extremalNumber
contrapose! h
rw [not_free] at h ⊢
exact h.trans' ⟨e.toCopy⟩
/-- If `H₁ ≃g H₂`, then `extremalNumber n H₁` equals `extremalNumber n H₂`. -/
theorem extremalNumber_congr_right {W₁ W₂ : Type*} {H₁ : SimpleGraph W₁} {H₂ : SimpleGraph W₂}
(e : H₁ ≃g H₂) : extremalNumber n H₁ = extremalNumber n H₂ := extremalNumber_congr rfl e
/-- `H`-free extremal graphs are `H`-free simple graphs having `extremalNumber (card V) H` many
edges. -/
theorem isExtremal_free_iff :
G.IsExtremal H.Free ↔ H.Free G ∧ #G.edgeFinset = extremalNumber (card V) H := by
rw [IsExtremal, and_congr_right_iff, ← extremalNumber_le_iff]
exact fun h ↦ ⟨eq_of_le_of_ge (card_edgeFinset_le_extremalNumber h), ge_of_eq⟩
lemma card_edgeFinset_of_isExtremal_free (h : G.IsExtremal H.Free) :
#G.edgeFinset = extremalNumber (card V) H := (isExtremal_free_iff.mp h).2
/-- If `G` is `H.Free`, then `G.deleteIncidenceSet v` is also `H.Free` and has at most
`extremalNumber (card V-1) H` many edges. -/
theorem card_edgeFinset_deleteIncidenceSet_le_extremalNumber
[DecidableEq V] (h : H.Free G) (v : V) :
#(G.deleteIncidenceSet v).edgeFinset ≤ extremalNumber (card V - 1) H := by
rw [← card_edgeFinset_induce_compl_singleton, ← @card_unique ({v} : Set V), ← card_compl_set]
apply card_edgeFinset_le_extremalNumber
contrapose! h
rw [not_free] at h ⊢
exact h.trans ⟨Copy.induce G {v}ᶜ⟩
end ExtremalNumber
end SimpleGraph
|
Jensen.lean
|
/-
Copyright (c) 2019 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Yury Kudryashov
-/
import Mathlib.Analysis.Convex.Combination
import Mathlib.Analysis.Convex.Function
import Mathlib.Tactic.FieldSimp
/-!
# Jensen's inequality and maximum principle for convex functions
In this file, we prove the finite Jensen inequality and the finite maximum principle for convex
functions. The integral versions are to be found in `Analysis.Convex.Integral`.
## Main declarations
Jensen's inequalities:
* `ConvexOn.map_centerMass_le`, `ConvexOn.map_sum_le`: Convex Jensen's inequality. The image of a
convex combination of points under a convex function is less than the convex combination of the
images.
* `ConcaveOn.le_map_centerMass`, `ConcaveOn.le_map_sum`: Concave Jensen's inequality.
* `StrictConvexOn.map_sum_lt`: Convex strict Jensen inequality.
* `StrictConcaveOn.lt_map_sum`: Concave strict Jensen inequality.
As corollaries, we get:
* `StrictConvexOn.map_sum_eq_iff`: Equality case of the convex Jensen inequality.
* `StrictConcaveOn.map_sum_eq_iff`: Equality case of the concave Jensen inequality.
* `ConvexOn.exists_ge_of_mem_convexHull`: Maximum principle for convex functions.
* `ConcaveOn.exists_le_of_mem_convexHull`: Minimum principle for concave functions.
-/
open Finset LinearMap Set Convex Pointwise
variable {𝕜 E F β ι : Type*}
/-! ### Jensen's inequality -/
section Jensen
variable [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜] [AddCommGroup E]
[AddCommGroup β] [PartialOrder β] [IsOrderedAddMonoid β] [Module 𝕜 E] [Module 𝕜 β]
[OrderedSMul 𝕜 β] {s : Set E} {f : E → β} {t : Finset ι} {w : ι → 𝕜} {p : ι → E} {v : 𝕜} {q : E}
/-- Convex **Jensen's inequality**, `Finset.centerMass` version. -/
theorem ConvexOn.map_centerMass_le (hf : ConvexOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i)
(h₁ : 0 < ∑ i ∈ t, w i) (hmem : ∀ i ∈ t, p i ∈ s) :
f (t.centerMass w p) ≤ t.centerMass w (f ∘ p) := by
have hmem' : ∀ i ∈ t, (p i, (f ∘ p) i) ∈ { p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2 } := fun i hi =>
⟨hmem i hi, le_rfl⟩
convert (hf.convex_epigraph.centerMass_mem h₀ h₁ hmem').2 <;>
simp only [centerMass, Function.comp, Prod.smul_fst, Prod.fst_sum, Prod.smul_snd, Prod.snd_sum]
/-- Concave **Jensen's inequality**, `Finset.centerMass` version. -/
theorem ConcaveOn.le_map_centerMass (hf : ConcaveOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i)
(h₁ : 0 < ∑ i ∈ t, w i) (hmem : ∀ i ∈ t, p i ∈ s) :
t.centerMass w (f ∘ p) ≤ f (t.centerMass w p) :=
ConvexOn.map_centerMass_le (β := βᵒᵈ) hf h₀ h₁ hmem
/-- Convex **Jensen's inequality**, `Finset.sum` version. -/
theorem ConvexOn.map_sum_le (hf : ConvexOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i ∈ t, w i = 1)
(hmem : ∀ i ∈ t, p i ∈ s) : f (∑ i ∈ t, w i • p i) ≤ ∑ i ∈ t, w i • f (p i) := by
simpa only [centerMass, h₁, inv_one, one_smul] using
hf.map_centerMass_le h₀ (h₁.symm ▸ zero_lt_one) hmem
/-- Concave **Jensen's inequality**, `Finset.sum` version. -/
theorem ConcaveOn.le_map_sum (hf : ConcaveOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i)
(h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) :
(∑ i ∈ t, w i • f (p i)) ≤ f (∑ i ∈ t, w i • p i) :=
ConvexOn.map_sum_le (β := βᵒᵈ) hf h₀ h₁ hmem
/-- Convex **Jensen's inequality** where an element plays a distinguished role. -/
lemma ConvexOn.map_add_sum_le (hf : ConvexOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i)
(h₁ : v + ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) (hv : 0 ≤ v) (hq : q ∈ s) :
f (v • q + ∑ i ∈ t, w i • p i) ≤ v • f q + ∑ i ∈ t, w i • f (p i) := by
let W j := Option.elim j v w
let P j := Option.elim j q p
have : f (∑ j ∈ insertNone t, W j • P j) ≤ ∑ j ∈ insertNone t, W j • f (P j) :=
hf.map_sum_le (forall_mem_insertNone.2 ⟨hv, h₀⟩) (by simpa using h₁)
(forall_mem_insertNone.2 ⟨hq, hmem⟩)
simpa using this
/-- Concave **Jensen's inequality** where an element plays a distinguished role. -/
lemma ConcaveOn.map_add_sum_le (hf : ConcaveOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i)
(h₁ : v + ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) (hv : 0 ≤ v) (hq : q ∈ s) :
v • f q + ∑ i ∈ t, w i • f (p i) ≤ f (v • q + ∑ i ∈ t, w i • p i) :=
hf.dual.map_add_sum_le h₀ h₁ hmem hv hq
/-! ### Strict Jensen inequality -/
/-- Convex **strict Jensen inequality**.
If the function is strictly convex, the weights are strictly positive and the indexed family of
points is non-constant, then Jensen's inequality is strict.
See also `StrictConvexOn.map_sum_eq_iff`. -/
lemma StrictConvexOn.map_sum_lt (hf : StrictConvexOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 < w i)
(h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) (hp : ∃ j ∈ t, ∃ k ∈ t, p j ≠ p k) :
f (∑ i ∈ t, w i • p i) < ∑ i ∈ t, w i • f (p i) := by
classical
obtain ⟨j, hj, k, hk, hjk⟩ := hp
-- We replace `t` by `t \ {j, k}`
have : k ∈ t.erase j := mem_erase.2 ⟨ne_of_apply_ne _ hjk.symm, hk⟩
let u := (t.erase j).erase k
have hj : j ∉ u := by simp [u]
have hk : k ∉ u := by simp [u]
have ht :
t = (u.cons k hk).cons j (mem_cons.not.2 <| not_or_intro (ne_of_apply_ne _ hjk) hj) := by
simp [u, insert_erase this, insert_erase ‹j ∈ t›, *]
clear_value u
subst ht
simp only [sum_cons]
have := h₀ j <| by simp
have := h₀ k <| by simp
let c := w j + w k
have hc : w j / c + w k / c = 1 := by field_simp [c]
calc f (w j • p j + (w k • p k + ∑ x ∈ u, w x • p x))
_ = f (c • ((w j / c) • p j + (w k / c) • p k) + ∑ x ∈ u, w x • p x) := by
congrm f ?_
match_scalars <;> field_simp
_ ≤ c • f ((w j / c) • p j + (w k / c) • p k) + ∑ x ∈ u, w x • f (p x) :=
-- apply the usual Jensen's inequality wrt the weighted average of the two distinguished
-- points and all the other points
hf.convexOn.map_add_sum_le (fun i hi ↦ (h₀ _ <| by simp [hi]).le)
(by simpa [-cons_eq_insert, ← add_assoc] using h₁)
(forall_of_forall_cons <| forall_of_forall_cons hmem) (by positivity) <| by
refine hf.1 (hmem _ <| by simp) (hmem _ <| by simp) ?_ ?_ hc <;> positivity
_ < c • ((w j / c) • f (p j) + (w k / c) • f (p k)) + ∑ x ∈ u, w x • f (p x) := by
-- then apply the definition of strict convexity for the two distinguished points
gcongr; refine hf.2 (hmem _ <| by simp) (hmem _ <| by simp) hjk ?_ ?_ hc <;> positivity
_ = (w j • f (p j) + w k • f (p k)) + ∑ x ∈ u, w x • f (p x) := by
match_scalars <;> field_simp
_ = w j • f (p j) + (w k • f (p k) + ∑ x ∈ u, w x • f (p x)) := by abel_nf
/-- Concave **strict Jensen inequality**.
If the function is strictly concave, the weights are strictly positive and the indexed family of
points is non-constant, then Jensen's inequality is strict.
See also `StrictConcaveOn.map_sum_eq_iff`. -/
lemma StrictConcaveOn.lt_map_sum (hf : StrictConcaveOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 < w i)
(h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) (hp : ∃ j ∈ t, ∃ k ∈ t, p j ≠ p k) :
∑ i ∈ t, w i • f (p i) < f (∑ i ∈ t, w i • p i) := hf.dual.map_sum_lt h₀ h₁ hmem hp
/-! ### Equality case of Jensen's inequality -/
/-- A form of the **equality case of Jensen's equality**.
For a strictly convex function `f` and positive weights `w`, if
`f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i)`, then the points `p` are all equal.
See also `StrictConvexOn.map_sum_eq_iff`. -/
lemma StrictConvexOn.eq_of_le_map_sum (hf : StrictConvexOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 < w i)
(h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s)
(h_eq : ∑ i ∈ t, w i • f (p i) ≤ f (∑ i ∈ t, w i • p i)) :
∀ ⦃j⦄, j ∈ t → ∀ ⦃k⦄, k ∈ t → p j = p k := by
by_contra!; exact h_eq.not_gt <| hf.map_sum_lt h₀ h₁ hmem this
/-- A form of the **equality case of Jensen's equality**.
For a strictly concave function `f` and positive weights `w`, if
`f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i)`, then the points `p` are all equal.
See also `StrictConcaveOn.map_sum_eq_iff`. -/
lemma StrictConcaveOn.eq_of_map_sum_eq (hf : StrictConcaveOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 < w i)
(h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s)
(h_eq : f (∑ i ∈ t, w i • p i) ≤ ∑ i ∈ t, w i • f (p i)) :
∀ ⦃j⦄, j ∈ t → ∀ ⦃k⦄, k ∈ t → p j = p k := by
by_contra!; exact h_eq.not_gt <| hf.lt_map_sum h₀ h₁ hmem this
/-- Canonical form of the **equality case of Jensen's equality**.
For a strictly convex function `f` and positive weights `w`, we have
`f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i)` if and only if the points `p` are all equal
(and in fact all equal to their center of mass wrt `w`). -/
lemma StrictConvexOn.map_sum_eq_iff {w : ι → 𝕜} {p : ι → E} (hf : StrictConvexOn 𝕜 s f)
(h₀ : ∀ i ∈ t, 0 < w i) (h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) :
f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i) ↔ ∀ j ∈ t, p j = ∑ i ∈ t, w i • p i := by
constructor
· obtain rfl | ⟨i₀, hi₀⟩ := t.eq_empty_or_nonempty
· simp
intro h_eq i hi
have H : ∀ j ∈ t, p j = p i₀ := by
intro j hj
apply hf.eq_of_le_map_sum h₀ h₁ hmem h_eq.ge hj hi₀
calc p i = p i₀ := by rw [H _ hi]
_ = (1 : 𝕜) • p i₀ := by simp
_ = (∑ j ∈ t, w j) • p i₀ := by rw [h₁]
_ = ∑ j ∈ t, (w j • p i₀) := by rw [sum_smul]
_ = ∑ j ∈ t, (w j • p j) := by congr! 2 with j hj; rw [← H _ hj]
· intro h
have H : ∀ j ∈ t, w j • f (p j) = w j • f (∑ i ∈ t, w i • p i) := by
intro j hj
simp [h j hj]
rw [sum_congr rfl H, ← sum_smul, h₁, one_smul]
/-- Canonical form of the **equality case of Jensen's equality**.
For a strictly concave function `f` and positive weights `w`, we have
`f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i)` if and only if the points `p` are all equal
(and in fact all equal to their center of mass wrt `w`). -/
lemma StrictConcaveOn.map_sum_eq_iff (hf : StrictConcaveOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 < w i)
(h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) :
f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i) ↔ ∀ j ∈ t, p j = ∑ i ∈ t, w i • p i := by
simpa using hf.neg.map_sum_eq_iff h₀ h₁ hmem
/-- Canonical form of the **equality case of Jensen's equality**.
For a strictly convex function `f` and nonnegative weights `w`, we have
`f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i)` if and only if the points `p` with nonzero
weight are all equal (and in fact all equal to their center of mass wrt `w`). -/
lemma StrictConvexOn.map_sum_eq_iff' (hf : StrictConvexOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i)
(h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) :
f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i) ↔
∀ j ∈ t, w j ≠ 0 → p j = ∑ i ∈ t, w i • p i := by
have hw (i) (_ : i ∈ t) : w i • p i ≠ 0 → w i ≠ 0 := by aesop
have hw' (i) (_ : i ∈ t) : w i • f (p i) ≠ 0 → w i ≠ 0 := by aesop
rw [← sum_filter_of_ne hw, ← sum_filter_of_ne hw', hf.map_sum_eq_iff]
· simp
· simp +contextual [(h₀ _ _).lt_iff_ne']
· rwa [sum_filter_ne_zero]
· simp +contextual [hmem _ _]
/-- Canonical form of the **equality case of Jensen's equality**.
For a strictly concave function `f` and nonnegative weights `w`, we have
`f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i)` if and only if the points `p` with nonzero
weight are all equal (and in fact all equal to their center of mass wrt `w`). -/
lemma StrictConcaveOn.map_sum_eq_iff' (hf : StrictConcaveOn 𝕜 s f) (h₀ : ∀ i ∈ t, 0 ≤ w i)
(h₁ : ∑ i ∈ t, w i = 1) (hmem : ∀ i ∈ t, p i ∈ s) :
f (∑ i ∈ t, w i • p i) = ∑ i ∈ t, w i • f (p i) ↔
∀ j ∈ t, w j ≠ 0 → p j = ∑ i ∈ t, w i • p i := hf.dual.map_sum_eq_iff' h₀ h₁ hmem
end Jensen
/-! ### Maximum principle -/
section MaximumPrinciple
variable [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜] [AddCommGroup E]
[AddCommGroup β] [LinearOrder β] [IsOrderedAddMonoid β] [Module 𝕜 E]
[Module 𝕜 β] [OrderedSMul 𝕜 β] {s : Set E} {f : E → β} {w : ι → 𝕜} {p : ι → E}
{x y z : E}
theorem ConvexOn.le_sup_of_mem_convexHull {t : Finset E} (hf : ConvexOn 𝕜 s f) (hts : ↑t ⊆ s)
(hx : x ∈ convexHull 𝕜 (t : Set E)) :
f x ≤ t.sup' (coe_nonempty.1 <| convexHull_nonempty_iff.1 ⟨x, hx⟩) f := by
obtain ⟨w, hw₀, hw₁, rfl⟩ := mem_convexHull.1 hx
exact (hf.map_centerMass_le hw₀ (by positivity) hts).trans
(centerMass_le_sup hw₀ <| by positivity)
theorem ConvexOn.inf_le_of_mem_convexHull {t : Finset E} (hf : ConcaveOn 𝕜 s f) (hts : ↑t ⊆ s)
(hx : x ∈ convexHull 𝕜 (t : Set E)) :
t.inf' (coe_nonempty.1 <| convexHull_nonempty_iff.1 ⟨x, hx⟩) f ≤ f x :=
hf.dual.le_sup_of_mem_convexHull hts hx
/-- If a function `f` is convex on `s`, then the value it takes at some center of mass of points of
`s` is less than the value it takes on one of those points. -/
lemma ConvexOn.exists_ge_of_centerMass {t : Finset ι} (h : ConvexOn 𝕜 s f)
(hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : 0 < ∑ i ∈ t, w i) (hp : ∀ i ∈ t, p i ∈ s) :
∃ i ∈ t, f (t.centerMass w p) ≤ f (p i) := by
set y := t.centerMass w p
-- TODO: can `rsuffices` be used to write the `exact` first, then the proof of this obtain?
obtain ⟨i, hi, hfi⟩ : ∃ i ∈ {i ∈ t | w i ≠ 0}, w i • f y ≤ w i • (f ∘ p) i := by
have hw' : (0 : 𝕜) < ∑ i ∈ t with w i ≠ 0, w i := by rwa [sum_filter_ne_zero]
refine exists_le_of_sum_le (nonempty_of_sum_ne_zero hw'.ne') ?_
rw [← sum_smul, ← smul_le_smul_iff_of_pos_left (inv_pos.2 hw'), inv_smul_smul₀ hw'.ne', ←
centerMass, centerMass_filter_ne_zero]
exact h.map_centerMass_le hw₀ hw₁ hp
rw [mem_filter] at hi
exact ⟨i, hi.1, (smul_le_smul_iff_of_pos_left <| (hw₀ i hi.1).lt_of_ne hi.2.symm).1 hfi⟩
/-- If a function `f` is concave on `s`, then the value it takes at some center of mass of points of
`s` is greater than the value it takes on one of those points. -/
lemma ConcaveOn.exists_le_of_centerMass {t : Finset ι} (h : ConcaveOn 𝕜 s f)
(hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : 0 < ∑ i ∈ t, w i) (hp : ∀ i ∈ t, p i ∈ s) :
∃ i ∈ t, f (p i) ≤ f (t.centerMass w p) := h.dual.exists_ge_of_centerMass hw₀ hw₁ hp
/-- **Maximum principle** for convex functions. If a function `f` is convex on the convex hull of
`s`, then the eventual maximum of `f` on `convexHull 𝕜 s` lies in `s`. -/
lemma ConvexOn.exists_ge_of_mem_convexHull {t : Set E} (hf : ConvexOn 𝕜 s f) (hts : t ⊆ s)
(hx : x ∈ convexHull 𝕜 t) : ∃ y ∈ t, f x ≤ f y := by
rw [_root_.convexHull_eq] at hx
obtain ⟨α, t, w, p, hw₀, hw₁, hp, rfl⟩ := hx
obtain ⟨i, hit, Hi⟩ := hf.exists_ge_of_centerMass hw₀ (hw₁.symm ▸ zero_lt_one)
fun i hi ↦ hts (hp i hi)
exact ⟨p i, hp i hit, Hi⟩
/-- **Minimum principle** for concave functions. If a function `f` is concave on the convex hull of
`s`, then the eventual minimum of `f` on `convexHull 𝕜 s` lies in `s`. -/
lemma ConcaveOn.exists_le_of_mem_convexHull {t : Set E} (hf : ConcaveOn 𝕜 s f) (hts : t ⊆ s)
(hx : x ∈ convexHull 𝕜 t) : ∃ y ∈ t, f y ≤ f x := hf.dual.exists_ge_of_mem_convexHull hts hx
/-- **Maximum principle** for convex functions on a segment. If a function `f` is convex on the
segment `[x, y]`, then the eventual maximum of `f` on `[x, y]` is at `x` or `y`. -/
lemma ConvexOn.le_max_of_mem_segment (hf : ConvexOn 𝕜 s f) (hx : x ∈ s) (hy : y ∈ s)
(hz : z ∈ [x -[𝕜] y]) : f z ≤ max (f x) (f y) := by
rw [← convexHull_pair] at hz; simpa using hf.exists_ge_of_mem_convexHull (pair_subset hx hy) hz
/-- **Minimum principle** for concave functions on a segment. If a function `f` is concave on the
segment `[x, y]`, then the eventual minimum of `f` on `[x, y]` is at `x` or `y`. -/
lemma ConcaveOn.min_le_of_mem_segment (hf : ConcaveOn 𝕜 s f) (hx : x ∈ s) (hy : y ∈ s)
(hz : z ∈ [x -[𝕜] y]) : min (f x) (f y) ≤ f z := hf.dual.le_max_of_mem_segment hx hy hz
/-- **Maximum principle** for convex functions on an interval. If a function `f` is convex on the
interval `[x, y]`, then the eventual maximum of `f` on `[x, y]` is at `x` or `y`. -/
lemma ConvexOn.le_max_of_mem_Icc {s : Set 𝕜} {f : 𝕜 → β} {x y z : 𝕜} (hf : ConvexOn 𝕜 s f)
(hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ Icc x y) : f z ≤ max (f x) (f y) := by
rw [← segment_eq_Icc (hz.1.trans hz.2)] at hz; exact hf.le_max_of_mem_segment hx hy hz
/-- **Minimum principle** for concave functions on an interval. If a function `f` is concave on the
interval `[x, y]`, then the eventual minimum of `f` on `[x, y]` is at `x` or `y`. -/
lemma ConcaveOn.min_le_of_mem_Icc {s : Set 𝕜} {f : 𝕜 → β} {x y z : 𝕜} (hf : ConcaveOn 𝕜 s f)
(hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ Icc x y) : min (f x) (f y) ≤ f z :=
hf.dual.le_max_of_mem_Icc hx hy hz
lemma ConvexOn.bddAbove_convexHull {s t : Set E} (hst : s ⊆ t) (hf : ConvexOn 𝕜 t f) :
BddAbove (f '' s) → BddAbove (f '' convexHull 𝕜 s) := by
rintro ⟨b, hb⟩
refine ⟨b, ?_⟩
rintro _ ⟨x, hx, rfl⟩
obtain ⟨y, hy, hxy⟩ := hf.exists_ge_of_mem_convexHull hst hx
exact hxy.trans <| hb <| mem_image_of_mem _ hy
lemma ConcaveOn.bddBelow_convexHull {s t : Set E} (hst : s ⊆ t) (hf : ConcaveOn 𝕜 t f) :
BddBelow (f '' s) → BddBelow (f '' convexHull 𝕜 s) := hf.dual.bddAbove_convexHull hst
end MaximumPrinciple
|
Shrink.lean
|
/-
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.Algebra.Group.Shrink
import Mathlib.Algebra.Module.TransferInstance
/-!
# Transfer module and algebra structures from `α` to `Shrink α`
-/
-- FIXME: `to_additive` is incompatible with `noncomputable section`.
-- See https://github.com/leanprover-community/mathlib4/issues/1074.
suppress_compilation
universe v
variable {R α : Type*} [Small.{v} α] [Semiring R] [AddCommMonoid α] [Module R α]
namespace Shrink
instance : Module R (Shrink.{v} α) := (equivShrink α).symm.module R
variable (R α) in
/-- Shrinking `α` to a smaller universe preserves module structure. -/
@[simps!]
def linearEquiv : Shrink.{v} α ≃ₗ[R] α := (equivShrink α).symm.linearEquiv _
end Shrink
/-- A small module is linearly equivalent to its small model. -/
@[deprecated Shrink.linearEquiv (since := "2025-07-11")]
def linearEquivShrink (α β) [Semiring α] [AddCommMonoid β] [Module α β] [Small β] :
β ≃ₗ[α] Shrink β :=
((equivShrink β).symm.linearEquiv α).symm
|
StoneCech.lean
|
import Mathlib.Topology.Compactification.StoneCech
deprecated_module (since := "2025-06-07")
|
fintype.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool ssrnotations eqtype.
From mathcomp Require Import ssrnat seq choice path div.
(******************************************************************************)
(* Finite types *)
(* *)
(* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *)
(* *)
(* This file defines an interface for finite types: *)
(* *)
(* finType == type with finitely many inhabitants *)
(* The HB class is called Finite. *)
(* subFinType P == join of finType and subType P *)
(* The HB class is called SubFinite. *)
(* *)
(* The Finite interface describes Types with finitely many elements, *)
(* supplying a duplicate-free sequence of all the elements. It is a subclass *)
(* of Countable and thus of Choice and Equality. *)
(* *)
(* Bounded integers are supported by the following type and operations: *)
(* *)
(* 'I_n, ordinal n == the finite subType of integers i < n, whose *)
(* enumeration is {0, ..., n.-1} *)
(* 'I_n coerces to nat, so all the integer arithmetic *)
(* functions can be used with 'I_n. *)
(* Ordinal lt_i_n == the element of 'I_n with (nat) value i, given *)
(* lt_i_n : i < n *)
(* nat_of_ord i == the nat value of i : 'I_n (this function is a *)
(* coercion so it is not usually displayed) *)
(* ord_enum n == the explicit increasing sequence of the i : 'I_n *)
(* cast_ord eq_n_m i == the element j : 'I_m with the same value as i : 'I_n *)
(* given eq_n_m : n = m (indeed, i : nat and j : nat *)
(* are convertible) *)
(* ordS n i == the successor of i : 'I_n along the cyclic structure *)
(* of 'I_n, reduces in nat to i.+1 %% n *)
(* ord_pred n i == the predecessor of i : 'I_n along the cyclic *)
(* structure of 'I_n, reduces in nat to (i + n).-1 %% n *)
(* widen_ord le_n_m i == a j : 'I_m with the same value as i : 'I_n, given *)
(* le_n_m : n <= m *)
(* rev_ord i == the complement to n.-1 of i : 'I_n, such that *)
(* i + rev_ord i = n.-1 *)
(* inord k == the i : 'I_n.+1 with value k (n is inferred from the *)
(* context) *)
(* sub_ord k == the i : 'I_n.+1 with value n - k (n is inferred from *)
(* the context) *)
(* ord0 == the i : 'I_n.+1 with value 0 (n is inferred from the *)
(* context) *)
(* ord_max == the i : 'I_n.+1 with value n (n is inferred from the *)
(* context) *)
(* bump h k == k.+1 if k >= h, else k (this is a nat function) *)
(* unbump h k == k.-1 if k > h, else k (this is a nat function) *)
(* lift i j == the j' : 'I_n with value bump i j, where i : 'I_n *)
(* and j : 'I_n.-1 *)
(* unlift i j == None if i = j, else Some j', where j' : 'I_n.-1 has *)
(* value unbump i j, given i, j : 'I_n *)
(* lshift n j == the i : 'I_(m + n) with value j : 'I_m *)
(* rshift m k == the i : 'I_(m + n) with value m + k, k : 'I_n *)
(* unsplit u == either lshift n j or rshift m k, depending on *)
(* whether if u : 'I_m + 'I_n is inl j or inr k *)
(* split i == the u : 'I_m + 'I_n such that i = unsplit u; the *)
(* type 'I_(m + n) of i determines the split *)
(* *)
(* Finally, every type T with a finType structure supports the following *)
(* operations: *)
(* *)
(* enum A == a duplicate-free list of all the x \in A, where A is a *)
(* collective predicate over T *)
(* #|A| == the cardinal of A, i.e., the number of x \in A *)
(* enum_val i == the i'th item of enum A, where i : 'I_(#|A|) *)
(* enum_rank x == the i : 'I_(#|T|) such that enum_val i = x *)
(* enum_rank_in Ax0 x == some i : 'I_(#|A|) such that enum_val i = x if *)
(* x \in A, given Ax0 : x0 \in A *)
(* A \subset B <=> all x \in A satisfy x \in B *)
(* A \proper B <=> all x \in A satisfy x \in B but not the converse *)
(* [disjoint A & B] <=> no x \in A satisfies x \in B *)
(* image f A == the sequence of f x for all x : T such that x \in A *)
(* (where A is an applicative predicate), of length #|A|. *)
(* The codomain of F can be any type, but image f A can *)
(* only be used as a collective predicate if it is an *)
(* eqType *)
(* codom f == a sequence spanning the codomain of f (:= image f T) *)
(* [seq F | x : T in A] := image (fun x : T => F) A *)
(* [seq F | x : T] := [seq F | x <- {: T}] *)
(* [seq F | x in A], [seq F | x] == variants without casts *)
(* iinv im_y == some x such that P x holds and f x = y, given *)
(* im_y : y \in image f P *)
(* invF inj_f y == the x such that f x = y, for inj_j : injective f with *)
(* f : T -> T *)
(* dinjectiveb A f <=> the restriction of f : T -> R to A is injective *)
(* (this is a boolean predicate, R must be an eqType) *)
(* injectiveb f <=> f : T -> R is injective (boolean predicate) *)
(* pred0b A <=> no x : T satisfies x \in A *)
(* [forall x, P] <=> P (in which x can appear) is true for all values of x *)
(* x must range over a finType *)
(* [exists x, P] <=> P is true for some value of x *)
(* [forall (x | C), P] := [forall x, C ==> P] *)
(* [forall x in A, P] := [forall (x | x \in A), P] *)
(* [exists (x | C), P] := [exists x, C && P] *)
(* [exists x in A, P] := [exists (x | x \in A), P] *)
(* and typed variants [forall x : T, P], [forall (x : T | C), P], *)
(* [exists x : T, P], [exists x : T in A, P], etc *)
(* -> The outer brackets can be omitted when nesting finitary quantifiers, *)
(* e.g., [forall i in I, forall j in J, exists a, f i j == a]. *)
(* 'forall_pP <-> view for [forall x, p _], for pP : reflect .. (p _) *)
(* 'exists_pP <-> view for [exists x, p _], for pP : reflect .. (p _) *)
(* 'forall_in_pP <-> view for [forall x in .., p _], for pP as above *)
(* 'exists_in_pP <-> view for [exists x in .., p _], for pP as above *)
(* [pick x | P] == Some x, for an x such that P holds, or None if there *)
(* is no such x *)
(* [pick x : T] == Some x with x : T, provided T is nonempty, else None *)
(* [pick x in A] == Some x, with x \in A, or None if A is empty *)
(* [pick x in A | P] == Some x, with x \in A such that P holds, else None *)
(* [pick x | P & Q] := [pick x | P & Q] *)
(* [pick x in A | P & Q] := [pick x | P & Q] *)
(* and (un)typed variants [pick x : T | P], [pick x : T in A], [pick x], etc *)
(* [arg min_(i < i0 | P) M] == a value i : T minimizing M : nat, subject *)
(* to the condition P (i may appear in P and M), and *)
(* provided P holds for i0 *)
(* [arg max_(i > i0 | P) M] == a value i maximizing M subject to P and *)
(* provided P holds for i0 *)
(* [arg min_(i < i0 in A) M] == an i \in A minimizing M if i0 \in A *)
(* [arg max_(i > i0 in A) M] == an i \in A maximizing M if i0 \in A *)
(* [arg min_(i < i0) M] == an i : T minimizing M, given i0 : T *)
(* [arg max_(i > i0) M] == an i : T maximizing M, given i0 : T *)
(* These are special instances of *)
(* [arg[ord]_(i < i0 | P) F] == a value i : I, minimizing F wrt ord : rel T *)
(* such that for all j : T, ord (F i) (F j) *)
(* subject to the condition P, and provided P i0 *)
(* where I : finType, T : eqType and F : I -> T *)
(* [arg[ord]_(i < i0 in A) F] == an i \in A minimizing F wrt ord, if i0 \in A *)
(* [arg[ord]_(i < i0) F] == an i : T minimizing F wrt ord, given i0 : T *)
(* *)
(* We define the following interfaces and structures: *)
(* Finite.axiom e <-> every x : T occurs exactly once in e : seq T. *)
(* [Finite of T by <:] == a finType structure for T, when T has a subType *)
(* structure over an existing finType. *)
(* We define or propagate the finType structure appropriately for all basic *)
(* types : unit, bool, void, option, prod, sum, sig and sigT. We also define *)
(* a generic type constructor for finite subtypes based on an explicit *)
(* enumeration: *)
(* seq_sub s == the subType of all x \in s, where s : seq T for some *)
(* eqType T; seq_sub s has a canonical finType instance *)
(* when T is a choiceType *)
(* adhoc_seq_sub_choiceType s, adhoc_seq_sub_finType s == *)
(* non-canonical instances for seq_sub s, s : seq T, *)
(* which can be used when T is not a choiceType *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Declare Scope fin_quant_scope.
Definition finite_axiom (T : eqType) e :=
forall x : T, count_mem x e = 1.
HB.mixin Record isFinite T of Equality T := {
enum_subdef : seq T;
enumP_subdef : finite_axiom enum_subdef
}.
(* Finiteness could be stated more simply by bounding the range of the pickle *)
(* function supplied by the Countable interface, but this would yield *)
(* a useless computational interpretation due to the wasteful Peano integer *)
(* encodings. *)
#[short(type="finType")]
HB.structure Definition Finite := {T of isFinite T & Countable T }.
(* As with Countable, the interface explicitly includes the somewhat redundant*)
(* Equality, Choice and Countable superclasses to ensure the forgetful *)
(* inheritance criterion is met. *)
Module Export FiniteNES.
Module Finite.
HB.lock Definition enum T := isFinite.enum_subdef (Finite.class T).
Notation axiom := finite_axiom.
Lemma uniq_enumP (T : eqType) e : uniq e -> e =i T -> axiom e.
Proof. by move=> Ue sT x; rewrite count_uniq_mem ?sT. Qed.
Section WithCountType.
Variable (T : countType) (n : nat).
Definition count_enum := pmap (@pickle_inv T) (iota 0 n).
Hypothesis ubT : forall x : T, pickle x < n.
Lemma count_enumP : axiom count_enum.
Proof.
apply: uniq_enumP (pmap_uniq (@pickle_invK T) (iota_uniq _ _)) _ => x.
by rewrite mem_pmap -pickleK_inv map_f // mem_iota ubT.
Qed.
End WithCountType.
End Finite.
Canonical finEnum_unlock := Unlockable Finite.enum.unlock.
End FiniteNES.
Section CanonicalFinType.
Variable (T : eqType) (s : seq T).
Definition fin_type of finite_axiom s : Type := T.
Variable (f : finite_axiom s).
Notation fT := (fin_type f).
Definition fin_pickle (x : fT) : nat := index x s.
Definition fin_unpickle (n : nat) : option fT :=
nth None (map some s) n.
Lemma fin_pickleK : pcancel fin_pickle fin_unpickle.
Proof.
move=> x; rewrite /fin_pickle/fin_unpickle.
rewrite -(index_map Some_inj) nth_index ?map_f//.
by apply/count_memPn=> /eqP; rewrite f.
Qed.
HB.instance Definition _ := Equality.on fT.
HB.instance Definition _ := isCountable.Build fT fin_pickleK.
HB.instance Definition _ := isFinite.Build fT f.
End CanonicalFinType.
(* Workaround for the silly syntactic uniformity restriction on coercions; *)
(* this avoids a cross-dependency between finset.v and prime.v for the *)
(* definition of the \pi(A) notation. *)
Definition fin_pred_sort (T : finType) (pT : predType T) := pred_sort pT.
Identity Coercion pred_sort_of_fin : fin_pred_sort >-> pred_sort.
Definition enum_mem T (mA : mem_pred _) := filter mA (Finite.enum T).
Notation enum A := (enum_mem (mem A)).
Definition pick (T : finType) (P : pred T) := ohead (enum P).
Notation "[ 'pick' x | P ]" := (pick (fun x => P%B))
(x name, format "[ 'pick' x | P ]") : form_scope.
Notation "[ 'pick' x : T | P ]" := (pick (fun x : T => P%B))
(x name, only parsing) : form_scope.
Definition pick_true T (x : T) := true.
Reserved Notation "[ 'pick' x : T ]" (x name, format "[ 'pick' x : T ]").
Notation "[ 'pick' x : T ]" := [pick x : T | pick_true x]
(only parsing) : form_scope.
Notation "[ 'pick' x : T ]" := [pick x : T | pick_true _]
(only printing) : form_scope.
Notation "[ 'pick' x ]" := [pick x : _] (x name, only parsing) : form_scope.
Notation "[ 'pick' x | P & Q ]" := [pick x | P && Q ]
(x name, format "[ '[hv ' 'pick' x | P '/ ' & Q ] ']'") : form_scope.
Notation "[ 'pick' x : T | P & Q ]" := [pick x : T | P && Q ]
(x name, only parsing) : form_scope.
Notation "[ 'pick' x 'in' A ]" := [pick x | x \in A]
(x name, format "[ 'pick' x 'in' A ]") : form_scope.
Notation "[ 'pick' x : T 'in' A ]" := [pick x : T | x \in A]
(x name, only parsing) : form_scope.
Notation "[ 'pick' x 'in' A | P ]" := [pick x | x \in A & P ]
(x name, format "[ '[hv ' 'pick' x 'in' A '/ ' | P ] ']'") : form_scope.
Notation "[ 'pick' x : T 'in' A | P ]" := [pick x : T | x \in A & P ]
(x name, only parsing) : form_scope.
Notation "[ 'pick' x 'in' A | P & Q ]" := [pick x in A | P && Q]
(x name, format
"[ '[hv ' 'pick' x 'in' A '/ ' | P '/ ' & Q ] ']'") : form_scope.
Notation "[ 'pick' x : T 'in' A | P & Q ]" := [pick x : T in A | P && Q]
(x name, only parsing) : form_scope.
(* We lock the definitions of card and subset to mitigate divergence of the *)
(* Coq term comparison algorithm. *)
HB.lock Definition card (T : finType) (mA : mem_pred T) := size (enum_mem mA).
Canonical card_unlock := Unlockable card.unlock.
(* A is at level 99 to allow the notation #|G : H| in groups. *)
Notation "#| A |" := (card (mem A))
(A at level 99, format "#| A |") : nat_scope.
Definition pred0b (T : finType) (P : pred T) := #|P| == 0.
Prenex Implicits pred0b.
Module FiniteQuant.
Variant quantified := Quantified of bool.
Delimit Scope fin_quant_scope with Q. (* Bogus, only used to declare scope. *)
Bind Scope fin_quant_scope with quantified.
Notation "F ^*" := (Quantified F).
Section Definitions.
Variable T : finType.
Implicit Types (B : quantified) (x y : T).
Definition quant0b Bp := pred0b [pred x : T | let: F^* := Bp x x in F].
(* The first redundant argument protects the notation from Coq's K-term *)
(* display kludge; the second protects it from simpl and /=. *)
Definition ex B x y := B.
(* Binding the predicate value rather than projecting it prevents spurious *)
(* unfolding of the boolean connectives by unification. *)
Definition all B x y := let: F^* := B in (~~ F)^*.
Definition all_in C B x y := let: F^* := B in (~~ (C ==> F))^*.
Definition ex_in C B x y := let: F^* := B in (C && F)^*.
End Definitions.
Notation "[ x | B ]" := (quant0b (fun x => B x)) (x name).
Notation "[ x : T | B ]" := (quant0b (fun x : T => B x)) (x name).
Module Exports.
Notation ", F" := F^* (at level 200, format ", '/ ' F") : fin_quant_scope.
Notation "[ 'forall' x B ]" := [x | all B]
(x at level 99, format "[ '[hv' 'forall' x B ] ']'") : bool_scope.
Notation "[ 'forall' x : T B ]" := [x : T | all B] (only parsing) : bool_scope.
Notation "[ 'forall' ( x | C ) B ]" := [x | all_in C B]
(x at level 99,
format "[ '[hv' '[' 'forall' ( x '/ ' | C ) ']' B ] ']'") : bool_scope.
Notation "[ 'forall' ( x : T | C ) B ]" := [x : T | all_in C B]
(x at level 99, only parsing) : bool_scope.
Notation "[ 'forall' x 'in' A B ]" := [x | all_in (x \in A) B]
(format "[ '[hv' '[' 'forall' x '/ ' 'in' A ']' B ] ']'") : bool_scope.
Notation "[ 'forall' x : T 'in' A B ]" := [x : T | all_in (x \in A) B]
(only parsing) : bool_scope.
Notation ", 'forall' x B" := [x | all B]^*
(at level 200, x at level 99,
format ", '/ ' 'forall' x B") : fin_quant_scope.
Notation ", 'forall' x : T B" := [x : T | all B]^*
(only parsing) : fin_quant_scope.
Notation ", 'forall' ( x | C ) B" := [x | all_in C B]^*
(x at level 99,
format ", '/ ' '[' 'forall' ( x '/ ' | C ) ']' B") : fin_quant_scope.
Notation ", 'forall' ( x : T | C ) B" := [x : T | all_in C B]^*
(only parsing) : fin_quant_scope.
Notation ", 'forall' x 'in' A B" := [x | all_in (x \in A) B]^*
(format ", '/ ' '[' 'forall' x '/ ' 'in' A ']' B") : bool_scope.
Notation ", 'forall' x : T 'in' A B" := [x : T | all_in (x \in A) B]^*
(only parsing) : bool_scope.
Notation "[ 'exists' x B ]" := (~~ [x | ex B])
(x at level 99,
format "[ '[hv' 'exists' x B ] ']'") : bool_scope.
Notation "[ 'exists' x : T B ]" := (~~ [x : T | ex B]) (only parsing) : bool_scope.
Notation "[ 'exists' ( x | C ) B ]" := (~~ [x | ex_in C B])
(x at level 99,
format "[ '[hv' '[' 'exists' ( x '/ ' | C ) ']' B ] ']'") : bool_scope.
Notation "[ 'exists' ( x : T | C ) B ]" := (~~ [x : T | ex_in C B])
(only parsing) : bool_scope.
Notation "[ 'exists' x 'in' A B ]" := (~~ [x | ex_in (x \in A) B])
(format "[ '[hv' '[' 'exists' x '/ ' 'in' A ']' B ] ']'") : bool_scope.
Notation "[ 'exists' x : T 'in' A B ]" := (~~ [x : T | ex_in (x \in A) B])
(only parsing) : bool_scope.
Notation ", 'exists' x B" := (~~ [x | ex B])^*
(x at level 99, format ", '/ ' 'exists' x B") : fin_quant_scope.
Notation ", 'exists' x : T B" := (~~ [x : T | ex B])^*
(only parsing) : fin_quant_scope.
Notation ", 'exists' ( x | C ) B" := (~~ [x | ex_in C B])^*
(x at level 99,
format ", '/ ' '[' 'exists' ( x '/ ' | C ) ']' B") : fin_quant_scope.
Notation ", 'exists' ( x : T | C ) B" := (~~ [x : T | ex_in C B])^*
(only parsing) : fin_quant_scope.
Notation ", 'exists' x 'in' A B" := (~~ [x | ex_in (x \in A) B])^*
(format ", '/ ' '[' 'exists' x '/ ' 'in' A ']' B") : bool_scope.
Notation ", 'exists' x : T 'in' A B" := (~~ [x : T | ex_in (x \in A) B])^*
(only parsing) : bool_scope.
End Exports.
End FiniteQuant.
Export FiniteQuant.Exports.
Definition disjoint T (A B : mem_pred _) := @pred0b T (predI A B).
Notation "[ 'disjoint' A & B ]" := (disjoint (mem A) (mem B))
(format "'[hv' [ 'disjoint' '/ ' A '/' & B ] ']'") : bool_scope.
HB.lock
Definition subset (T : finType) (A B : mem_pred T) : bool := pred0b (predD A B).
Canonical subset_unlock := Unlockable subset.unlock.
Notation "A \subset B" := (subset (mem A) (mem B))
(at level 70, no associativity) : bool_scope.
Definition proper T A B := @subset T A B && ~~ subset B A.
Notation "A \proper B" := (proper (mem A) (mem B))
(at level 70, no associativity) : bool_scope.
(* image, xinv, inv, and ordinal operations will be defined later. *)
Section OpsTheory.
Variable T : finType.
Implicit Types (A B C D : {pred T}) (P Q : pred T) (x y : T) (s : seq T).
Lemma enumP : Finite.axiom (Finite.enum T).
Proof. by rewrite unlock; apply: enumP_subdef. Qed.
Section EnumPick.
Variable P : pred T.
Lemma enumT : enum T = Finite.enum T.
Proof. exact: filter_predT. Qed.
Lemma mem_enum A : enum A =i A.
Proof. by move=> x; rewrite mem_filter andbC -has_pred1 has_count enumP. Qed.
Lemma enum_uniq A : uniq (enum A).
Proof.
by apply/filter_uniq/count_mem_uniq => x; rewrite enumP -enumT mem_enum.
Qed.
Lemma enum0 : enum pred0 = Nil T. Proof. exact: filter_pred0. Qed.
Lemma enum1 x : enum (pred1 x) = [:: x].
Proof.
rewrite [enum _](all_pred1P x _ _); first by rewrite size_filter enumP.
by apply/allP=> y; rewrite mem_enum.
Qed.
Variant pick_spec : option T -> Type :=
| Pick x of P x : pick_spec (Some x)
| Nopick of P =1 xpred0 : pick_spec None.
Lemma pickP : pick_spec (pick P).
Proof.
rewrite /pick; case: (enum _) (mem_enum P) => [|x s] Pxs /=.
by right; apply: fsym.
by left; rewrite -[P _]Pxs mem_head.
Qed.
End EnumPick.
Lemma eq_enum A B : A =i B -> enum A = enum B.
Proof. by move=> eqAB; apply: eq_filter. Qed.
Lemma eq_pick P Q : P =1 Q -> pick P = pick Q.
Proof. by move=> eqPQ; rewrite /pick (eq_enum eqPQ). Qed.
Lemma cardE A : #|A| = size (enum A).
Proof. by rewrite unlock. Qed.
Lemma eq_card A B : A =i B -> #|A| = #|B|.
Proof. by move=> eqAB; rewrite !cardE (eq_enum eqAB). Qed.
Lemma eq_card_trans A B n : #|A| = n -> B =i A -> #|B| = n.
Proof. by move <-; apply: eq_card. Qed.
Lemma card0 : #|@pred0 T| = 0. Proof. by rewrite cardE enum0. Qed.
Lemma cardT : #|T| = size (enum T). Proof. by rewrite cardE. Qed.
Lemma card1 x : #|pred1 x| = 1.
Proof. by rewrite cardE enum1. Qed.
Lemma eq_card0 A : A =i pred0 -> #|A| = 0.
Proof. exact: eq_card_trans card0. Qed.
Lemma eq_cardT A : A =i predT -> #|A| = size (enum T).
Proof. exact: eq_card_trans cardT. Qed.
Lemma eq_card1 x A : A =i pred1 x -> #|A| = 1.
Proof. exact: eq_card_trans (card1 x). Qed.
Lemma cardUI A B : #|[predU A & B]| + #|[predI A & B]| = #|A| + #|B|.
Proof. by rewrite !cardE !size_filter count_predUI. Qed.
Lemma cardID B A : #|[predI A & B]| + #|[predD A & B]| = #|A|.
Proof.
rewrite -cardUI addnC [#|predI _ _|]eq_card0 => [|x] /=.
by apply: eq_card => x; rewrite !inE andbC -andb_orl orbN.
by rewrite !inE -!andbA andbC andbA andbN.
Qed.
Lemma cardC A : #|A| + #|[predC A]| = #|T|.
Proof. by rewrite !cardE !size_filter count_predC. Qed.
Lemma cardU1 x A : #|[predU1 x & A]| = (x \notin A) + #|A|.
Proof.
case Ax: (x \in A).
by apply: eq_card => y /[1!inE]/=; case: eqP => // ->.
rewrite /= -(card1 x) -cardUI addnC.
rewrite [#|predI _ _|]eq_card0 => [|y /=]; first exact: eq_card.
by rewrite !inE; case: eqP => // ->.
Qed.
Lemma card2 x y : #|pred2 x y| = (x != y).+1.
Proof. by rewrite cardU1 card1 addn1. Qed.
Lemma cardC1 x : #|predC1 x| = #|T|.-1.
Proof. by rewrite -(cardC (pred1 x)) card1. Qed.
Lemma cardD1 x A : #|A| = (x \in A) + #|[predD1 A & x]|.
Proof.
case Ax: (x \in A); last first.
by apply: eq_card => y /[!inE]/=; case: eqP => // ->.
rewrite /= -(card1 x) -cardUI addnC /=.
rewrite [#|predI _ _|]eq_card0 => [|y]; last by rewrite !inE; case: eqP.
by apply: eq_card => y /[!inE]; case: eqP => // ->.
Qed.
Lemma max_card A : #|A| <= #|T|.
Proof. by rewrite -(cardC A) leq_addr. Qed.
Lemma card_size s : #|s| <= size s.
Proof.
elim: s => [|x s IHs] /=; first by rewrite card0.
by rewrite cardU1 /=; case: (~~ _) => //; apply: leqW.
Qed.
Lemma card_uniqP s : reflect (#|s| = size s) (uniq s).
Proof.
elim: s => [|x s IHs]; first by left; apply: card0.
rewrite cardU1 /= /addn; case: {+}(x \in s) => /=.
by right=> card_Ssz; have:= card_size s; rewrite card_Ssz ltnn.
by apply: (iffP IHs) => [<-| [<-]].
Qed.
Lemma card0_eq A : #|A| = 0 -> A =i pred0.
Proof. by move=> A0 x; apply/idP => Ax; rewrite (cardD1 x) Ax in A0. Qed.
Lemma fintype0 : T -> #|T| <> 0. Proof. by move=> x /card0_eq/(_ x). Qed.
Lemma pred0P P : reflect (P =1 pred0) (pred0b P).
Proof. by apply: (iffP eqP); [apply: card0_eq | apply: eq_card0]. Qed.
Lemma pred0Pn P : reflect (exists x, P x) (~~ pred0b P).
Proof.
case: (pickP P) => [x Px | P0].
by rewrite (introN (pred0P P)) => [|P0]; [left; exists x | rewrite P0 in Px].
by rewrite -lt0n eq_card0 //; right=> [[x]]; rewrite P0.
Qed.
Lemma card_gt0P A : reflect (exists i, i \in A) (#|A| > 0).
Proof. by rewrite lt0n; apply: pred0Pn. Qed.
Lemma card_le1P {A} : reflect {in A, forall x, A =i pred1 x} (#|A| <= 1).
Proof.
apply: (iffP idP) => [A1 x xA y|]; last first.
by have [/= x xA /(_ _ xA)/eq_card1->|/eq_card0->//] := pickP [in A].
move: A1; rewrite (cardD1 x) xA ltnS leqn0 => /eqP/card0_eq/(_ y).
by rewrite !inE; have [->|]:= eqP.
Qed.
Lemma mem_card1 A : #|A| = 1 -> {x | A =i pred1 x}.
Proof.
move=> A1; have /card_gt0P/sigW[x xA]: #|A| > 0 by rewrite A1.
by exists x; apply/card_le1P; rewrite ?A1.
Qed.
Lemma card1P A : reflect (exists x, A =i pred1 x) (#|A| == 1).
Proof.
by apply: (iffP idP) => [/eqP/mem_card1[x inA]|[x /eq_card1/eqP//]]; exists x.
Qed.
Lemma card_le1_eqP A :
reflect {in A &, forall x, all_equal_to x} (#|A| <= 1).
Proof.
apply: (iffP card_le1P) => [Ale1 x y xA yA /=|all_eq x xA y].
by apply/eqP; rewrite -[_ == _]/(y \in pred1 x) -Ale1.
by rewrite inE; case: (altP (y =P x)) => [->//|]; exact/contra_neqF/all_eq.
Qed.
Lemma fintype_le1P : reflect (forall x : T, all_equal_to x) (#|T| <= 1).
Proof. apply: (iffP (card_le1_eqP {:T})); [exact: in2T | exact: in2W]. Qed.
Lemma fintype1 : #|T| = 1 -> {x : T | all_equal_to x}.
Proof.
by move=> /mem_card1[x ex]; exists x => y; suff: y \in T by rewrite ex => /eqP.
Qed.
Lemma fintype1P : reflect (exists x, all_equal_to x) (#|T| == 1).
Proof.
apply: (iffP idP) => [/eqP/fintype1|] [x eqx]; first by exists x.
by apply/card1P; exists x => y; rewrite eqx !inE eqxx.
Qed.
Lemma subsetE A B : (A \subset B) = pred0b [predD A & B].
Proof. by rewrite unlock. Qed.
Lemma subsetP A B : reflect {subset A <= B} (A \subset B).
Proof.
rewrite unlock; apply: (iffP (pred0P _)) => [AB0 x | sAB x /=].
by apply/implyP; apply/idPn; rewrite negb_imply andbC [_ && _]AB0.
by rewrite andbC -negb_imply; apply/negbF/implyP; apply: sAB.
Qed.
Lemma subsetPn A B :
reflect (exists2 x, x \in A & x \notin B) (~~ (A \subset B)).
Proof.
rewrite unlock; apply: (iffP (pred0Pn _)) => [[x] | [x Ax nBx]].
by case/andP; exists x.
by exists x; rewrite /= nBx.
Qed.
Lemma subset_leq_card A B : A \subset B -> #|A| <= #|B|.
Proof.
move=> sAB.
rewrite -(cardID A B) [#|predI _ _|](@eq_card _ A) ?leq_addr //= => x.
by rewrite !inE andbC; case Ax: (x \in A) => //; apply: subsetP Ax.
Qed.
Lemma subxx_hint (mA : mem_pred T) : subset mA mA.
Proof.
by case: mA => A; have:= introT (subsetP A A); rewrite !unlock => ->.
Qed.
Hint Resolve subxx_hint : core.
(* The parametrization by predType makes it easier to apply subxx. *)
Lemma subxx (pT : predType T) (pA : pT) : pA \subset pA.
Proof. by []. Qed.
Lemma eq_subset A B : A =i B -> subset (mem A) =1 subset (mem B).
Proof.
move=> eqAB [C]; rewrite !unlock; congr (_ == 0).
by apply: eq_card => x; rewrite inE /= eqAB.
Qed.
Lemma eq_subset_r A B :
A =i B -> (@subset T)^~ (mem A) =1 (@subset T)^~ (mem B).
Proof.
move=> eqAB [C]; rewrite !unlock; congr (_ == 0).
by apply: eq_card => x; rewrite !inE /= eqAB.
Qed.
Lemma eq_subxx A B : A =i B -> A \subset B.
Proof. by move/eq_subset->. Qed.
Lemma subset_predT A : A \subset T.
Proof. exact/subsetP. Qed.
Lemma predT_subset A : T \subset A -> forall x, x \in A.
Proof. by move/subsetP=> allA x; apply: allA. Qed.
Lemma subset_pred1 A x : (pred1 x \subset A) = (x \in A).
Proof. by apply/subsetP/idP=> [-> // | Ax y /eqP-> //]; apply: eqxx. Qed.
Lemma subset_eqP A B : reflect (A =i B) ((A \subset B) && (B \subset A)).
Proof.
apply: (iffP andP) => [[sAB sBA] x| eqAB]; last by rewrite !eq_subxx.
by apply/idP/idP; apply: subsetP.
Qed.
Lemma subset_cardP A B : #|A| = #|B| -> reflect (A =i B) (A \subset B).
Proof.
move=> eqcAB; case: (subsetP A B) (subset_eqP A B) => //= sAB.
case: (subsetP B A) => [//|[]] x Bx; apply/idPn => Ax.
case/idP: (ltnn #|A|); rewrite {2}eqcAB (cardD1 x B) Bx /=.
apply: subset_leq_card; apply/subsetP=> y Ay; rewrite inE /= andbC.
by rewrite sAB //; apply/eqP => eqyx; rewrite -eqyx Ay in Ax.
Qed.
Lemma subset_leqif_card A B : A \subset B -> #|A| <= #|B| ?= iff (B \subset A).
Proof.
move=> sAB; split; [exact: subset_leq_card | apply/eqP/idP].
by move/subset_cardP=> sABP; rewrite (eq_subset_r (sABP sAB)).
by move=> sBA; apply: eq_card; apply/subset_eqP; rewrite sAB.
Qed.
Lemma subset_trans A B C : A \subset B -> B \subset C -> A \subset C.
Proof.
by move/subsetP=> sAB /subsetP=> sBC; apply/subsetP=> x /sAB; apply: sBC.
Qed.
Lemma subset_all s A : (s \subset A) = all [in A] s.
Proof. exact: (sameP (subsetP _ _) allP). Qed.
Lemma subset_cons s x : s \subset x :: s.
Proof. by apply/subsetP => y /[!inE] ->; rewrite orbT. Qed.
Lemma subset_cons2 s1 s2 x : s1 \subset s2 -> x :: s1 \subset x :: s2.
Proof.
by move=> ?; apply/subsetP => y /[!inE]; case: eqP => // _; apply: subsetP.
Qed.
Lemma subset_catl s s' : s \subset s ++ s'.
Proof. by apply/subsetP=> x xins; rewrite mem_cat xins. Qed.
Lemma subset_catr s s' : s \subset s' ++ s.
Proof. by apply/subsetP => x xins; rewrite mem_cat xins orbT. Qed.
Lemma subset_cat2 s1 s2 s3 : s1 \subset s2 -> s3 ++ s1 \subset s3 ++ s2.
Proof.
move=> /subsetP s12; apply/subsetP => x.
by rewrite !mem_cat => /orP[->|/s12->]; rewrite ?orbT.
Qed.
Lemma filter_subset p s : [seq a <- s | p a] \subset s.
Proof. by apply/subsetP=> x; rewrite mem_filter => /andP[]. Qed.
Lemma subset_filter p s1 s2 :
s1 \subset s2 -> [seq a <- s1 | p a] \subset [seq a <- s2 | p a].
Proof.
by move/subsetP=> s12; apply/subsetP=> x; rewrite !mem_filter=> /andP[-> /s12].
Qed.
Lemma properE A B : A \proper B = (A \subset B) && ~~ (B \subset A).
Proof. by []. Qed.
Lemma properP A B :
reflect (A \subset B /\ (exists2 x, x \in B & x \notin A)) (A \proper B).
Proof. by rewrite properE; apply: (iffP andP) => [] [-> /subsetPn]. Qed.
Lemma proper_sub A B : A \proper B -> A \subset B.
Proof. by case/andP. Qed.
Lemma proper_subn A B : A \proper B -> ~~ (B \subset A).
Proof. by case/andP. Qed.
Lemma proper_trans A B C : A \proper B -> B \proper C -> A \proper C.
Proof.
case/properP=> sAB [x Bx nAx] /properP[sBC [y Cy nBy]].
rewrite properE (subset_trans sAB) //=; apply/subsetPn; exists y => //.
by apply: contra nBy; apply: subsetP.
Qed.
Lemma proper_sub_trans A B C : A \proper B -> B \subset C -> A \proper C.
Proof.
case/properP=> sAB [x Bx nAx] sBC; rewrite properE (subset_trans sAB) //.
by apply/subsetPn; exists x; rewrite ?(subsetP _ _ sBC).
Qed.
Lemma sub_proper_trans A B C : A \subset B -> B \proper C -> A \proper C.
Proof.
move=> sAB /properP[sBC [x Cx nBx]]; rewrite properE (subset_trans sAB) //.
by apply/subsetPn; exists x => //; apply: contra nBx; apply: subsetP.
Qed.
Lemma proper_card A B : A \proper B -> #|A| < #|B|.
Proof.
by case/andP=> sAB nsBA; rewrite ltn_neqAle !(subset_leqif_card sAB) andbT.
Qed.
Lemma proper_irrefl A : ~~ (A \proper A).
Proof. by rewrite properE subxx. Qed.
Lemma properxx A : (A \proper A) = false.
Proof. by rewrite properE subxx. Qed.
Lemma eq_proper A B : A =i B -> proper (mem A) =1 proper (mem B).
Proof.
move=> eAB [C]; congr (_ && _); first exact: (eq_subset eAB).
by rewrite (eq_subset_r eAB).
Qed.
Lemma eq_proper_r A B :
A =i B -> (@proper T)^~ (mem A) =1 (@proper T)^~ (mem B).
Proof.
move=> eAB [C]; congr (_ && _); first exact: (eq_subset_r eAB).
by rewrite (eq_subset eAB).
Qed.
Lemma card_geqP {A n} :
reflect (exists s, [/\ uniq s, size s = n & {subset s <= A}]) (n <= #|A|).
Proof.
apply: (iffP idP) => [n_le_A|[s] [uniq_s size_s /subsetP subA]]; last first.
by rewrite -size_s -(card_uniqP _ uniq_s); exact: subset_leq_card.
exists (take n (enum A)); rewrite take_uniq ?enum_uniq // size_take.
split => //; last by move => x /mem_take; rewrite mem_enum.
case: (ltnP n (size (enum A))) => // size_A.
by apply/eqP; rewrite eqn_leq size_A -cardE n_le_A.
Qed.
Lemma card_gt1P A :
reflect (exists x y, [/\ x \in A, y \in A & x != y]) (1 < #|A|).
Proof.
apply: (iffP card_geqP) => [[s] []|[x] [y] [xA yA xDy]].
case: s => [|a [|b []]]//= /[!(inE, andbT)] aDb _ subD.
by exists a, b; rewrite aDb !subD ?inE ?eqxx ?orbT.
by exists [:: x; y]; rewrite /= !inE xDy; split=> // z /[!inE] /pred2P[]->.
Qed.
Lemma card_gt2P A :
reflect (exists x y z,
[/\ x \in A, y \in A & z \in A] /\ [/\ x != y, y != z & z != x])
(2 < #|A|).
Proof.
apply: (iffP card_geqP) => [[s] []|[x] [y] [z] [[xD yD zD] [xDy xDz yDz]]].
case: s => [|x [|y [|z []]]]//=; rewrite !inE !andbT negb_or -andbA.
case/and3P => xDy xDz yDz _ subA.
by exists x, y, z; rewrite xDy yDz eq_sym xDz !subA ?inE ?eqxx ?orbT.
exists [:: x; y; z]; rewrite /= !inE negb_or xDy xDz eq_sym yDz; split=> // u.
by rewrite !inE => /or3P [] /eqP->.
Qed.
Lemma disjoint_sym A B : [disjoint A & B] = [disjoint B & A].
Proof. by congr (_ == 0); apply: eq_card => x; apply: andbC. Qed.
Lemma eq_disjoint A B : A =i B -> disjoint (mem A) =1 disjoint (mem B).
Proof.
by move=> eqAB [C]; congr (_ == 0); apply: eq_card => x; rewrite !inE eqAB.
Qed.
Lemma eq_disjoint_r A B : A =i B ->
(@disjoint T)^~ (mem A) =1 (@disjoint T)^~ (mem B).
Proof.
by move=> eqAB [C]; congr (_ == 0); apply: eq_card => x; rewrite !inE eqAB.
Qed.
Lemma subset_disjoint A B : (A \subset B) = [disjoint A & [predC B]].
Proof. by rewrite disjoint_sym unlock. Qed.
Lemma disjoint_subset A B : [disjoint A & B] = (A \subset [predC B]).
Proof.
by rewrite subset_disjoint; apply: eq_disjoint_r => x; rewrite !inE /= negbK.
Qed.
Lemma disjointFr A B x : [disjoint A & B] -> x \in A -> x \in B = false.
Proof. by move/pred0P/(_ x) => /=; case: (x \in A). Qed.
Lemma disjointFl A B x : [disjoint A & B] -> x \in B -> x \in A = false.
Proof. rewrite disjoint_sym; exact: disjointFr. Qed.
Lemma disjointWl A B C :
A \subset B -> [disjoint B & C] -> [disjoint A & C].
Proof. by rewrite 2!disjoint_subset; apply: subset_trans. Qed.
Lemma disjointWr A B C : A \subset B -> [disjoint C & B] -> [disjoint C & A].
Proof. rewrite ![[disjoint C & _]]disjoint_sym. exact:disjointWl. Qed.
Lemma disjointW A B C D :
A \subset B -> C \subset D -> [disjoint B & D] -> [disjoint A & C].
Proof.
by move=> subAB subCD BD; apply/(disjointWl subAB)/(disjointWr subCD).
Qed.
Lemma disjoint0 A : [disjoint pred0 & A].
Proof. exact/pred0P. Qed.
Lemma eq_disjoint0 A B : A =i pred0 -> [disjoint A & B].
Proof. by move/eq_disjoint->; apply: disjoint0. Qed.
Lemma disjoint1 x A : [disjoint pred1 x & A] = (x \notin A).
Proof.
apply/negbRL/(sameP (pred0Pn _))=> /=.
apply: introP => [Ax | notAx [_ /andP[/eqP->]]]; last exact: negP.
by exists x; rewrite inE eqxx.
Qed.
Lemma eq_disjoint1 x A B :
A =i pred1 x -> [disjoint A & B] = (x \notin B).
Proof. by move/eq_disjoint->; apply: disjoint1. Qed.
Lemma disjointU A B C :
[disjoint predU A B & C] = [disjoint A & C] && [disjoint B & C].
Proof.
case: [disjoint A & C] / (pred0P (xpredI A C)) => [A0 | nA0] /=.
by congr (_ == 0); apply: eq_card => x; rewrite [x \in _]andb_orl A0.
apply/pred0P=> nABC; case: nA0 => x; apply/idPn=> /=; move/(_ x): nABC.
by rewrite [_ x]andb_orl; case/norP.
Qed.
Lemma disjointU1 x A B :
[disjoint predU1 x A & B] = (x \notin B) && [disjoint A & B].
Proof. by rewrite disjointU disjoint1. Qed.
Lemma disjoint_cons x s B :
[disjoint x :: s & B] = (x \notin B) && [disjoint s & B].
Proof. exact: disjointU1. Qed.
Lemma disjoint_has s A : [disjoint s & A] = ~~ has [in A] s.
Proof.
apply/negbRL; apply/pred0Pn/hasP => [[x /andP[]]|[x]]; exists x => //.
exact/andP.
Qed.
Lemma disjoint_cat s1 s2 A :
[disjoint s1 ++ s2 & A] = [disjoint s1 & A] && [disjoint s2 & A].
Proof. by rewrite !disjoint_has has_cat negb_or. Qed.
End OpsTheory.
Lemma map_subset {T T' : finType} (s1 s2 : seq T) (f : T -> T') :
s1 \subset s2 -> [seq f x | x <- s1 ] \subset [seq f x | x <- s2].
Proof.
move=> s1s2; apply/subsetP => _ /mapP[y] /[swap] -> ys1.
by apply/mapP; exists y => //; move/subsetP : s1s2; exact.
Qed.
#[global] Hint Resolve subxx_hint : core.
Arguments pred0P {T P}.
Arguments pred0Pn {T P}.
Arguments card_le1P {T A}.
Arguments card_le1_eqP {T A}.
Arguments card1P {T A}.
Arguments fintype_le1P {T}.
Arguments fintype1P {T}.
Arguments subsetP {T A B}.
Arguments subsetPn {T A B}.
Arguments subset_eqP {T A B}.
Arguments card_uniqP {T s}.
Arguments card_geqP {T A n}.
Arguments card_gt0P {T A}.
Arguments card_gt1P {T A}.
Arguments card_gt2P {T A}.
Arguments properP {T A B}.
(**********************************************************************)
(* *)
(* Boolean quantifiers for finType *)
(* *)
(**********************************************************************)
Section QuantifierCombinators.
Variables (T : finType) (P : pred T) (PP : T -> Prop).
Hypothesis viewP : forall x, reflect (PP x) (P x).
Lemma existsPP : reflect (exists x, PP x) [exists x, P x].
Proof. by apply: (iffP pred0Pn) => -[x /viewP]; exists x. Qed.
Lemma forallPP : reflect (forall x, PP x) [forall x, P x].
Proof. by apply: (iffP pred0P) => /= allP x; have /viewP//=-> := allP x. Qed.
End QuantifierCombinators.
Notation "'exists_ view" := (existsPP (fun _ => view))
(at level 4, right associativity, format "''exists_' view").
Notation "'forall_ view" := (forallPP (fun _ => view))
(at level 4, right associativity, format "''forall_' view").
Section Quantifiers.
Variables (T : finType) (rT : T -> eqType).
Implicit Types (D P : pred T) (f : forall x, rT x).
Lemma forallP P : reflect (forall x, P x) [forall x, P x].
Proof. exact: 'forall_idP. Qed.
Lemma eqfunP f1 f2 : reflect (forall x, f1 x = f2 x) [forall x, f1 x == f2 x].
Proof. exact: 'forall_eqP. Qed.
Lemma forall_inP D P : reflect (forall x, D x -> P x) [forall (x | D x), P x].
Proof. exact: 'forall_implyP. Qed.
Lemma forall_inPP D P PP : (forall x, reflect (PP x) (P x)) ->
reflect (forall x, D x -> PP x) [forall (x | D x), P x].
Proof. by move=> vP; apply: (iffP (forall_inP _ _)) => /(_ _ _) /vP. Qed.
Lemma eqfun_inP D f1 f2 :
reflect {in D, forall x, f1 x = f2 x} [forall (x | x \in D), f1 x == f2 x].
Proof. exact: (forall_inPP _ (fun=> eqP)). Qed.
Lemma existsP P : reflect (exists x, P x) [exists x, P x].
Proof. exact: 'exists_idP. Qed.
Lemma existsb P (x : T) : P x -> [exists x, P x].
Proof. by move=> Px; apply/existsP; exists x. Qed.
Lemma exists_eqP f1 f2 :
reflect (exists x, f1 x = f2 x) [exists x, f1 x == f2 x].
Proof. exact: 'exists_eqP. Qed.
Lemma exists_inP D P : reflect (exists2 x, D x & P x) [exists (x | D x), P x].
Proof. by apply: (iffP 'exists_andP) => [[x []] | [x]]; exists x. Qed.
Lemma exists_inb D P (x : T) : D x -> P x -> [exists (x | D x), P x].
Proof. by move=> Dx Px; apply/exists_inP; exists x. Qed.
Lemma exists_inPP D P PP : (forall x, reflect (PP x) (P x)) ->
reflect (exists2 x, D x & PP x) [exists (x | D x), P x].
Proof. by move=> vP; apply: (iffP (exists_inP _ _)) => -[x?/vP]; exists x. Qed.
Lemma exists_eq_inP D f1 f2 :
reflect (exists2 x, D x & f1 x = f2 x) [exists (x | D x), f1 x == f2 x].
Proof. exact: (exists_inPP _ (fun=> eqP)). Qed.
Lemma eq_existsb P1 P2 : P1 =1 P2 -> [exists x, P1 x] = [exists x, P2 x].
Proof. by move=> eqP12; congr (_ != 0); apply: eq_card. Qed.
Lemma eq_existsb_in D P1 P2 :
(forall x, D x -> P1 x = P2 x) ->
[exists (x | D x), P1 x] = [exists (x | D x), P2 x].
Proof. by move=> eqP12; apply: eq_existsb => x; apply: andb_id2l => /eqP12. Qed.
Lemma eq_forallb P1 P2 : P1 =1 P2 -> [forall x, P1 x] = [forall x, P2 x].
Proof. by move=> eqP12; apply/negb_inj/eq_existsb=> /= x; rewrite eqP12. Qed.
Lemma eq_forallb_in D P1 P2 :
(forall x, D x -> P1 x = P2 x) ->
[forall (x | D x), P1 x] = [forall (x | D x), P2 x].
Proof.
by move=> eqP12; apply: eq_forallb => i; case Di: (D i); rewrite // eqP12.
Qed.
Lemma existsbWl P Q : [exists x, P x && Q x] -> [exists x, P x].
Proof. move => /existsP ; case => x /andP [H _] ; apply/existsP ; by exists x. Qed.
Lemma existsbWr P Q : [exists x, P x && Q x] -> [exists x, Q x].
Proof. move => /existsP ; case => x /andP [_ H] ; apply/existsP ; by exists x. Qed.
Lemma negb_forall P : ~~ [forall x, P x] = [exists x, ~~ P x].
Proof. by []. Qed.
Lemma negb_forall_in D P :
~~ [forall (x | D x), P x] = [exists (x | D x), ~~ P x].
Proof. by apply: eq_existsb => x; rewrite negb_imply. Qed.
Lemma negb_exists P : ~~ [exists x, P x] = [forall x, ~~ P x].
Proof. by apply/negbLR/esym/eq_existsb=> x; apply: negbK. Qed.
Lemma negb_exists_in D P :
~~ [exists (x | D x), P x] = [forall (x | D x), ~~ P x].
Proof. by rewrite negb_exists; apply/eq_forallb => x; rewrite [~~ _]fun_if. Qed.
Lemma existsPn P :
reflect (forall x, ~~ P x) (~~ [exists x, P x]).
Proof. rewrite negb_exists. exact: forallP. Qed.
Lemma forallPn P :
reflect (exists x, ~~ P x) (~~ [forall x, P x]).
Proof. rewrite negb_forall. exact: existsP. Qed.
Lemma exists_inPn D P :
reflect (forall x, x \in D -> ~~ P x) (~~ [exists x in D, P x]).
Proof. rewrite negb_exists_in. exact: forall_inP. Qed.
Lemma forall_inPn D P :
reflect (exists2 x, x \in D & ~~ P x) (~~ [forall x in D, P x]).
Proof. rewrite negb_forall_in. exact: exists_inP. Qed.
End Quantifiers.
Arguments forallP {T P}.
Arguments eqfunP {T rT f1 f2}.
Arguments forall_inP {T D P}.
Arguments eqfun_inP {T rT D f1 f2}.
Arguments existsP {T P}.
Arguments existsb {T P}.
Arguments exists_eqP {T rT f1 f2}.
Arguments exists_inP {T D P}.
Arguments exists_inb {T D P}.
Arguments exists_eq_inP {T rT D f1 f2}.
Arguments existsPn {T P}.
Arguments exists_inPn {T D P}.
Arguments forallPn {T P}.
Arguments forall_inPn {T D P}.
Notation "'exists_in_ view" := (exists_inPP _ (fun _ => view))
(at level 4, right associativity, format "''exists_in_' view").
Notation "'forall_in_ view" := (forall_inPP _ (fun _ => view))
(at level 4, right associativity, format "''forall_in_' view").
(**********************************************************************)
(* *)
(* Boolean injectivity test for functions with a finType domain *)
(* *)
(**********************************************************************)
Section Injectiveb.
Variables (aT : finType) (rT : eqType).
Implicit Type (f : aT -> rT) (D : {pred aT}).
Definition dinjectiveb f D := uniq (map f (enum D)).
Definition injectiveb f := dinjectiveb f aT.
Lemma dinjectivePn f D :
reflect (exists2 x, x \in D & exists2 y, y \in [predD1 D & x] & f x = f y)
(~~ dinjectiveb f D).
Proof.
apply: (iffP idP) => [injf | [x Dx [y Dxy eqfxy]]]; last first.
move: Dx; rewrite -(mem_enum D) => /rot_to[i E defE].
rewrite /dinjectiveb -(rot_uniq i) -map_rot defE /=; apply/nandP; left.
rewrite inE /= -(mem_enum D) -(mem_rot i) defE inE in Dxy.
rewrite andb_orr andbC andbN in Dxy.
by rewrite eqfxy map_f //; case/andP: Dxy.
pose p := [pred x in D | [exists (y | y \in [predD1 D & x]), f x == f y]].
case: (pickP p) => [x /= /andP[Dx /exists_inP[y Dxy /eqP eqfxy]] | no_p].
by exists x; last exists y.
rewrite /dinjectiveb map_inj_in_uniq ?enum_uniq // in injf => x y Dx Dy eqfxy.
apply: contraNeq (negbT (no_p x)) => ne_xy /=; rewrite -mem_enum Dx.
by apply/existsP; exists y; rewrite /= !inE eq_sym ne_xy -mem_enum Dy eqfxy /=.
Qed.
Lemma dinjectiveP f D : reflect {in D &, injective f} (dinjectiveb f D).
Proof.
rewrite -[dinjectiveb f D]negbK.
case: dinjectivePn=> [noinjf | injf]; constructor.
case: noinjf => x Dx [y /andP[neqxy /= Dy] eqfxy] injf.
by case/eqP: neqxy; apply: injf.
move=> x y Dx Dy /= eqfxy; apply/eqP; apply/idPn=> nxy; case: injf.
by exists x => //; exists y => //=; rewrite inE /= eq_sym nxy.
Qed.
Lemma eq_dinjectiveb f1 f2 D1 D2 :
f1 =1 f2 -> D1 =i D2 -> dinjectiveb f1 D1 = dinjectiveb f2 D2.
Proof.
move=> ef eD; rewrite /dinjectiveb (eq_enum eD).
by under eq_map => x do rewrite ef.
Qed.
Lemma injectivePn f :
reflect (exists x, exists2 y, x != y & f x = f y) (~~ injectiveb f).
Proof.
apply: (iffP (dinjectivePn _ _)) => [[x _ [y nxy eqfxy]] | [x [y nxy eqfxy]]];
by exists x => //; exists y => //; rewrite inE /= andbT eq_sym in nxy *.
Qed.
Lemma injectiveP f : reflect (injective f) (injectiveb f).
Proof.
by apply: (iffP (dinjectiveP _ _)) => injf x y => [|_ _]; apply: injf.
Qed.
Lemma eq_injectiveb f1 f2 : f1 =1 f2 -> injectiveb f1 = injectiveb f2.
Proof. move=> ?; exact: eq_dinjectiveb. Qed.
End Injectiveb.
Definition image_mem T T' f mA : seq T' := map f (@enum_mem T mA).
Notation image f A := (image_mem f (mem A)).
Notation "[ 'seq' F | x 'in' A ]" := (image (fun x => F) A)
(x binder, format "'[hv' [ 'seq' F '/ ' | x 'in' A ] ']'") : seq_scope.
Notation "[ 'seq' F | x ]" :=
[seq F | x in pred_of_simpl (@pred_of_argType
(* kludge for getting the type of x *)
match _, (fun x => I) with
| T, f
=> match match f return T -> True with f' => f' end with
| _ => T
end
end)]
(x binder, only parsing) : seq_scope.
Notation "[ 'seq' F | x : T ]" :=
[seq F | x in pred_of_simpl (@pred_of_argType T)]
(x binder, only printing,
format "'[hv' [ 'seq' F '/ ' | x : T ] ']'") : seq_scope.
Notation "[ 'seq' F , x ]" := [seq F | x ]
(x binder, only parsing) : seq_scope.
Definition codom T T' f := @image_mem T T' f (mem T).
Section Image.
Variable T : finType.
Implicit Type A : {pred T}.
Section SizeImage.
Variables (T' : Type) (f : T -> T').
Lemma size_image A : size (image f A) = #|A|.
Proof. by rewrite size_map -cardE. Qed.
Lemma size_codom : size (codom f) = #|T|.
Proof. exact: size_image. Qed.
Lemma codomE : codom f = map f (enum T).
Proof. by []. Qed.
End SizeImage.
Variables (T' : eqType) (f : T -> T').
Lemma imageP A y : reflect (exists2 x, x \in A & y = f x) (y \in image f A).
Proof.
by apply: (iffP mapP) => [] [x Ax y_fx]; exists x; rewrite // mem_enum in Ax *.
Qed.
Lemma codomP y : reflect (exists x, y = f x) (y \in codom f).
Proof. by apply: (iffP (imageP _ y)) => [][x]; exists x. Qed.
Remark iinv_proof A y : y \in image f A -> {x | x \in A & f x = y}.
Proof.
move=> fy; pose b x := A x && (f x == y).
case: (pickP b) => [x /andP[Ax /eqP] | nfy]; first by exists x.
by case/negP: fy => /imageP[x Ax fx_y]; case/andP: (nfy x); rewrite fx_y.
Qed.
Definition iinv A y fAy := s2val (@iinv_proof A y fAy).
Lemma f_iinv A y fAy : f (@iinv A y fAy) = y.
Proof. exact: s2valP' (iinv_proof fAy). Qed.
Lemma mem_iinv A y fAy : @iinv A y fAy \in A.
Proof. exact: s2valP (iinv_proof fAy). Qed.
Lemma in_iinv_f A : {in A &, injective f} ->
forall x fAfx, x \in A -> @iinv A (f x) fAfx = x.
Proof.
by move=> injf x fAfx Ax; apply: injf => //; [apply: mem_iinv | apply: f_iinv].
Qed.
Lemma preim_iinv A B y fAy : preim f B (@iinv A y fAy) = B y.
Proof. by rewrite /= f_iinv. Qed.
Lemma image_f A x : x \in A -> f x \in image f A.
Proof. by move=> Ax; apply/imageP; exists x. Qed.
Lemma codom_f x : f x \in codom f.
Proof. exact: image_f. Qed.
Lemma image_codom A : {subset image f A <= codom f}.
Proof. by move=> _ /imageP[x _ ->]; apply: codom_f. Qed.
Lemma image_pred0 : image f pred0 =i pred0.
Proof. by move=> x; rewrite /image_mem /= enum0. Qed.
Section Injective.
Hypothesis injf : injective f.
Lemma mem_image A x : (f x \in image f A) = (x \in A).
Proof. by rewrite mem_map ?mem_enum. Qed.
Lemma pre_image A : [preim f of image f A] =i A.
Proof. by move=> x; rewrite inE /= mem_image. Qed.
Lemma image_iinv A y (fTy : y \in codom f) :
(y \in image f A) = (iinv fTy \in A).
Proof. by rewrite -mem_image ?f_iinv. Qed.
Lemma iinv_f x fTfx : @iinv T (f x) fTfx = x.
Proof. by apply: in_iinv_f; first apply: in2W. Qed.
Lemma image_pre (B : pred T') : image f [preim f of B] =i [predI B & codom f].
Proof. by move=> y; rewrite /image_mem -filter_map /= mem_filter -enumT. Qed.
Lemma bij_on_codom (x0 : T) : {on [pred y in codom f], bijective f}.
Proof.
pose g y := iinv (valP (insigd (codom_f x0) y)).
by exists g => [x fAfx | y fAy]; first apply: injf; rewrite f_iinv insubdK.
Qed.
Lemma bij_on_image A (x0 : T) : {on [pred y in image f A], bijective f}.
Proof. exact: subon_bij (@image_codom A) (bij_on_codom x0). Qed.
End Injective.
Fixpoint preim_seq s :=
if s is y :: s' then
(if pick (preim f (pred1 y)) is Some x then cons x else id) (preim_seq s')
else [::].
Lemma map_preim (s : seq T') : {subset s <= codom f} -> map f (preim_seq s) = s.
Proof.
elim: s => //= y s IHs; case: pickP => [x /eqP fx_y | nfTy] fTs.
by rewrite /= fx_y IHs // => z s_z; apply: fTs; apply: predU1r.
by case/imageP: (fTs y (mem_head y s)) => x _ fx_y; case/eqP: (nfTy x).
Qed.
End Image.
Prenex Implicits codom iinv.
Arguments imageP {T T' f A y}.
Arguments codomP {T T' f y}.
Lemma flatten_imageP (aT : finType) (rT : eqType)
(A : aT -> seq rT) (P : {pred aT}) (y : rT) :
reflect (exists2 x, x \in P & y \in A x) (y \in flatten [seq A x | x in P]).
Proof.
by apply: (iffP flatten_mapP) => [][x Px]; exists x; rewrite ?mem_enum in Px *.
Qed.
Arguments flatten_imageP {aT rT A P y}.
Section CardFunImage.
Variables (T T' : finType) (f : T -> T').
Implicit Type A : {pred T}.
Lemma leq_image_card A : #|image f A| <= #|A|.
Proof. by rewrite (cardE A) -(size_map f) card_size. Qed.
Lemma card_in_image A : {in A &, injective f} -> #|image f A| = #|A|.
Proof.
move=> injf; rewrite (cardE A) -(size_map f); apply/card_uniqP.
by rewrite map_inj_in_uniq ?enum_uniq // => x y; rewrite !mem_enum; apply: injf.
Qed.
Lemma image_injP A : reflect {in A &, injective f} (#|image f A| == #|A|).
Proof.
apply: (iffP eqP) => [eqfA |]; last exact: card_in_image.
by apply/dinjectiveP; apply/card_uniqP; rewrite size_map -cardE.
Qed.
Lemma leq_card_in A : {in A &, injective f} -> #|A| <= #|T'|.
Proof. by move=> /card_in_image <-; rewrite max_card. Qed.
Hypothesis injf : injective f.
Lemma card_image A : #|image f A| = #|A|.
Proof. by apply: card_in_image; apply: in2W. Qed.
Lemma card_codom : #|codom f| = #|T|.
Proof. exact: card_image. Qed.
Lemma card_preim (B : {pred T'}) : #|[preim f of B]| = #|[predI codom f & B]|.
Proof.
rewrite -card_image /=; apply: eq_card => y.
by rewrite [y \in _]image_pre !inE andbC.
Qed.
Lemma leq_card : #|T| <= #|T'|. Proof. exact: (leq_card_in (in2W _)). Qed.
Hypothesis card_range : #|T| >= #|T'|.
Let eq_card : #|T| = #|T'|. Proof. by apply/eqP; rewrite eqn_leq leq_card. Qed.
Lemma inj_card_onto y : y \in codom f.
Proof. by move: y; apply/subset_cardP; rewrite ?card_codom ?subset_predT. Qed.
Lemma inj_card_bij : bijective f.
Proof.
by exists (fun y => iinv (inj_card_onto y)) => y; rewrite ?iinv_f ?f_iinv.
Qed.
End CardFunImage.
Arguments image_injP {T T' f A}.
Arguments leq_card_in [T T'] f.
Arguments leq_card [T T'] f.
Lemma bij_eq_card (T T' : finType) (f : T -> T') : bijective f -> #|T| = #|T'|.
Proof. by move=> [g /can_inj/leq_card + /can_inj/leq_card]; case: ltngtP. Qed.
Section FinCancel.
Variables (T : finType) (f g : T -> T).
Section Inv.
Hypothesis injf : injective f.
Lemma injF_onto y : y \in codom f. Proof. exact: inj_card_onto. Qed.
Definition invF y := iinv (injF_onto y).
Lemma invF_f : cancel f invF. Proof. by move=> x; apply: iinv_f. Qed.
Lemma f_invF : cancel invF f. Proof. by move=> y; apply: f_iinv. Qed.
Lemma injF_bij : bijective f. Proof. exact: inj_card_bij. Qed.
End Inv.
Hypothesis fK : cancel f g.
Lemma canF_sym : cancel g f.
Proof. exact/(bij_can_sym (injF_bij (can_inj fK))). Qed.
Lemma canF_LR x y : x = g y -> f x = y.
Proof. exact: canLR canF_sym. Qed.
Lemma canF_RL x y : g x = y -> x = f y.
Proof. exact: canRL canF_sym. Qed.
Lemma canF_eq x y : (f x == y) = (x == g y).
Proof. exact: (can2_eq fK canF_sym). Qed.
Lemma canF_invF : g =1 invF (can_inj fK).
Proof. by move=> y; apply: (canLR fK); rewrite f_invF. Qed.
End FinCancel.
Section EqImage.
Variables (T : finType) (T' : Type).
Lemma eq_image (A B : {pred T}) (f g : T -> T') :
A =i B -> f =1 g -> image f A = image g B.
Proof.
by move=> eqAB eqfg; rewrite /image_mem (eq_enum eqAB) (eq_map eqfg).
Qed.
Lemma eq_codom (f g : T -> T') : f =1 g -> codom f = codom g.
Proof. exact: eq_image. Qed.
Lemma eq_invF f g injf injg : f =1 g -> @invF T f injf =1 @invF T g injg.
Proof.
by move=> eq_fg x; apply: (canLR (invF_f injf)); rewrite eq_fg f_invF.
Qed.
End EqImage.
(* Standard finTypes *)
Lemma unit_enumP : Finite.axiom [::tt]. Proof. by case. Qed.
HB.instance Definition _ := isFinite.Build unit unit_enumP.
Lemma card_unit : #|{: unit}| = 1. Proof. by rewrite cardT enumT unlock. Qed.
Lemma bool_enumP : Finite.axiom [:: true; false]. Proof. by case. Qed.
HB.instance Definition _ := isFinite.Build bool bool_enumP.
Lemma card_bool : #|{: bool}| = 2. Proof. by rewrite cardT enumT unlock. Qed.
Lemma void_enumP : Finite.axiom (Nil void). Proof. by case. Qed.
HB.instance Definition _ := isFinite.Build void void_enumP.
Lemma card_void : #|{: void}| = 0. Proof. by rewrite cardT enumT unlock. Qed.
Local Notation enumF T := (Finite.enum T).
Section OptionFinType.
Variable T : finType.
Definition option_enum := None :: map some (enumF T).
Lemma option_enumP : Finite.axiom option_enum.
Proof. by case=> [x|]; rewrite /= count_map (count_pred0, enumP). Qed.
HB.instance Definition _ := isFinite.Build (option T) option_enumP.
Lemma card_option : #|{: option T}| = #|T|.+1.
Proof. by rewrite !cardT !enumT [in LHS]unlock /= !size_map. Qed.
End OptionFinType.
Section TransferFinTypeFromCount.
Variables (eT : countType) (fT : finType) (f : eT -> fT).
Lemma pcan_enumP g : pcancel f g -> Finite.axiom (undup (pmap g (enumF fT))).
Proof.
move=> fK x; rewrite count_uniq_mem ?undup_uniq // mem_undup.
by rewrite mem_pmap -fK map_f // -enumT mem_enum.
Qed.
Definition PCanIsFinite g fK := @isFinite.Build _ _ (@pcan_enumP g fK).
Definition CanIsFinite g (fK : cancel f g) := PCanIsFinite (can_pcan fK).
End TransferFinTypeFromCount.
Section TransferFinType.
Variables (eT : Type) (fT : finType) (f : eT -> fT).
HB.instance Definition _ (g : fT -> option eT) (fK : pcancel f g) :=
isFinite.Build (pcan_type fK) (@pcan_enumP (pcan_type fK) fT f g fK).
HB.instance Definition _ (g : fT -> eT) (fK : cancel f g) :=
isFinite.Build (can_type fK) (@pcan_enumP (can_type fK) fT f _ (can_pcan fK)).
End TransferFinType.
#[short(type="subFinType")]
HB.structure Definition SubFinite (T : Type) (P : pred T) :=
{ sT of Finite sT & isSub T P sT }.
Section SubFinType.
Variables (T : choiceType) (P : pred T).
Import Finite.
Implicit Type sT : subFinType P.
Lemma codom_val sT x : (x \in codom (val : sT -> T)) = P x.
Proof.
by apply/codomP/idP=> [[u ->]|Px]; last exists (Sub x Px); rewrite ?valP ?SubK.
Qed.
End SubFinType.
HB.factory Record SubCountable_isFinite (T : finType) P (sT : Type)
of SubCountable T P sT := { }.
HB.builders Context (T : finType) (P : pred T) (sT : Type)
(a : SubCountable_isFinite T P sT).
Definition sub_enum : seq sT := pmap insub (enumF T).
Lemma mem_sub_enum u : u \in sub_enum.
Proof. by rewrite mem_pmap_sub -enumT mem_enum. Qed.
Lemma sub_enum_uniq : uniq sub_enum.
Proof. by rewrite pmap_sub_uniq // -enumT enum_uniq. Qed.
Lemma val_sub_enum : map val sub_enum = enum P.
Proof.
rewrite pmap_filter; last exact: insubK.
by apply: eq_filter => x; apply: isSome_insub.
Qed.
HB.instance Definition SubFinMixin := isFinite.Build sT
(Finite.uniq_enumP sub_enum_uniq mem_sub_enum).
HB.end.
(* This assumes that T has a subCountType structure over a type that *)
(* has a finType structure. *)
HB.instance Definition _ (T : finType) (P : pred T) (sT : subType P) :=
(SubCountable_isFinite.Build _ _ (sub_type sT)).
Notation "[ 'Finite' 'of' T 'by' <: ]" := (Finite.copy T%type (sub_type T%type))
(format "[ 'Finite' 'of' T 'by' <: ]") : form_scope.
Section SubCountable_isFiniteTheory.
Variables (T : finType) (P : pred T) (sfT : subFinType P).
Lemma card_sub : #|sfT| = #|[pred x | P x]|.
Proof. by rewrite -(eq_card (codom_val sfT)) (card_image val_inj). Qed.
Lemma eq_card_sub (A : {pred sfT}) : A =i predT -> #|A| = #|[pred x | P x]|.
Proof. exact: eq_card_trans card_sub. Qed.
End SubCountable_isFiniteTheory.
(* (* Regression for the subFinType stack *) *)
(* Record myb : Type := MyB {myv : bool; _ : ~~ myv}. *)
(* HB.instance Definition myb_sub : isSub bool (fun x => ~~ x) myb := *)
(* [isSub for myv]. *)
(* HB.instance Definition _ := [Finite of myb by <:]. *)
(* Check [subFinType of myb]. *)
(* Check [finType of myb]. *)
Section CardSig.
Variables (T : finType) (P : pred T).
HB.instance Definition _ := [Finite of {x | P x} by <:].
Lemma card_sig : #|{: {x | P x}}| = #|[pred x | P x]|.
Proof. exact: card_sub. Qed.
End CardSig.
(* Subtype for an explicit enumeration. *)
Section SeqSubType.
Variables (T : eqType) (s : seq T).
Record seq_sub : Type := SeqSub {ssval : T; ssvalP : in_mem ssval (@mem T _ s)}.
HB.instance Definition _ := [isSub for ssval].
HB.instance Definition _ := [Equality of seq_sub by <:].
Definition seq_sub_enum : seq seq_sub := undup (pmap insub s).
Lemma mem_seq_sub_enum x : x \in seq_sub_enum.
Proof. by rewrite mem_undup mem_pmap -valK map_f ?ssvalP. Qed.
Lemma val_seq_sub_enum : uniq s -> map val seq_sub_enum = s.
Proof.
move=> Us; rewrite /seq_sub_enum undup_id ?pmap_sub_uniq //.
rewrite (pmap_filter (insubK _)); apply/all_filterP.
by apply/allP => x; rewrite isSome_insub.
Qed.
Definition seq_sub_pickle x := index x seq_sub_enum.
Definition seq_sub_unpickle n := nth None (map some seq_sub_enum) n.
Lemma seq_sub_pickleK : pcancel seq_sub_pickle seq_sub_unpickle.
Proof.
rewrite /seq_sub_unpickle => x.
by rewrite (nth_map x) ?nth_index ?index_mem ?mem_seq_sub_enum.
Qed.
Definition seq_sub_isCountable := isCountable.Build seq_sub seq_sub_pickleK.
Fact seq_sub_axiom : Finite.axiom seq_sub_enum.
Proof. exact: Finite.uniq_enumP (undup_uniq _) mem_seq_sub_enum. Qed.
Definition seq_sub_isFinite := isFinite.Build seq_sub seq_sub_axiom.
(* Beware: these are not the canonical instances, as they are not consistent *)
(* with the generic sub_choiceType canonical instance. *)
Definition adhoc_seq_sub_choiceType : choiceType := pcan_type seq_sub_pickleK.
Definition adhoc_seq_sub_countType := HB.pack_for countType seq_sub
seq_sub_isCountable (Choice.class adhoc_seq_sub_choiceType).
Definition adhoc_seq_sub_finType := HB.pack_for finType seq_sub
seq_sub_isFinite seq_sub_isCountable (Choice.class adhoc_seq_sub_choiceType).
End SeqSubType.
Section SeqReplace.
Variables (T : eqType).
Implicit Types (s : seq T).
Lemma seq_sub_default s : size s > 0 -> seq_sub s.
Proof. by case: s => // x s _; exists x; rewrite mem_head. Qed.
Lemma seq_subE s (s_gt0 : size s > 0) :
s = map val (map (insubd (seq_sub_default s_gt0)) s : seq (seq_sub s)).
Proof. by rewrite -map_comp map_id_in// => x x_in_s /=; rewrite insubdK. Qed.
End SeqReplace.
Notation in_sub_seq s_gt0 := (insubd (seq_sub_default s_gt0)).
Section SeqFinType.
Variables (T : choiceType) (s : seq T).
Local Notation sT := (seq_sub s).
HB.instance Definition _ := [Choice of sT by <:].
HB.instance Definition _ : isCountable sT := seq_sub_isCountable s.
HB.instance Definition _ : isFinite sT := seq_sub_isFinite s.
Lemma card_seq_sub : uniq s -> #|{:sT}| = size s.
Proof.
by move=> Us; rewrite cardE enumT -(size_map val) unlock val_seq_sub_enum.
Qed.
End SeqFinType.
Section Extrema.
Variant extremum_spec {T : eqType} (ord : rel T) {I : finType}
(P : pred I) (F : I -> T) : I -> Type :=
ExtremumSpec (i : I) of P i & (forall j : I, P j -> ord (F i) (F j)) :
extremum_spec ord P F i.
Let arg_pred {T : eqType} ord {I : finType} (P : pred I) (F : I -> T) :=
[pred i | P i & [forall (j | P j), ord (F i) (F j)]].
Section Extremum.
Context {T : eqType} {I : finType} (ord : rel T).
Context (i0 : I) (P : pred I) (F : I -> T).
Definition extremum := odflt i0 (pick (arg_pred ord P F)).
Hypothesis ord_refl : reflexive ord.
Hypothesis ord_trans : transitive ord.
Hypothesis ord_total : total ord.
Hypothesis Pi0 : P i0.
Lemma extremumP : extremum_spec ord P F extremum.
Proof.
rewrite /extremum; case: pickP => [i /andP[Pi /'forall_implyP/= min_i] | no_i].
by split=> // j; apply/implyP.
have := sort_sorted ord_total [seq F i | i <- enum P].
set s := sort _ _ => ss; have s_gt0 : size s > 0
by rewrite size_sort size_map -cardE; apply/card_gt0P; exists i0.
pose t0 := nth (F i0) s 0; have: t0 \in s by rewrite mem_nth.
rewrite mem_sort => /mapP/sig2_eqW[it0]; rewrite mem_enum => it0P def_t0.
have /negP[/=] := no_i it0; rewrite [P _]it0P/=; apply/'forall_implyP=> j Pj.
have /(nthP (F i0))[k g_lt <-] : F j \in s by rewrite mem_sort map_f ?mem_enum.
by rewrite -def_t0 sorted_leq_nth.
Qed.
End Extremum.
Section ExtremumIn.
Context {T : eqType} {I : finType} (ord : rel T).
Context (i0 : I) (P : pred I) (F : I -> T).
Hypothesis ord_refl : {in P, reflexive (relpre F ord)}.
Hypothesis ord_trans : {in P & P & P, transitive (relpre F ord)}.
Hypothesis ord_total : {in P &, total (relpre F ord)}.
Hypothesis Pi0 : P i0.
Lemma extremum_inP : extremum_spec ord P F (extremum ord i0 P F).
Proof.
rewrite /extremum; case: pickP => [i /andP[Pi /'forall_implyP/= min_i] | no_i].
by split=> // j; apply/implyP.
pose TP := seq_sub [seq F i | i <- enum P].
have FPP (iP : {i | P i}) : F (proj1_sig iP) \in [seq F i | i <- enum P].
by rewrite map_f// mem_enum; apply: valP.
pose FP := SeqSub (FPP _).
have []//= := @extremumP _ _ (relpre val ord) (exist P i0 Pi0) xpredT FP.
- by move=> [/= _/mapP[i iP ->]]; apply: ord_refl; rewrite mem_enum in iP.
- move=> [/= _/mapP[j jP ->]] [/= _/mapP[i iP ->]] [/= _/mapP[k kP ->]].
by apply: ord_trans; rewrite !mem_enum in iP jP kP.
- move=> [/= _/mapP[i iP ->]] [/= _/mapP[j jP ->]].
by apply: ord_total; rewrite !mem_enum in iP jP.
- rewrite /FP => -[/= i Pi] _ /(_ (exist _ _ _))/= ordF.
have /negP/negP/= := no_i i; rewrite Pi/= negb_forall => /existsP/sigW[j].
by rewrite negb_imply => /andP[Pj]; rewrite ordF.
Qed.
End ExtremumIn.
Notation "[ 'arg[' ord ]_( i < i0 | P ) F ]" :=
(extremum ord i0 (fun i => P%B) (fun i => F))
(ord, i, i0 at level 10,
format "[ 'arg[' ord ]_( i < i0 | P ) F ]") : nat_scope.
Notation "[ 'arg[' ord ]_( i < i0 'in' A ) F ]" :=
[arg[ord]_(i < i0 | i \in A) F]
(format "[ 'arg[' ord ]_( i < i0 'in' A ) F ]") : nat_scope.
Notation "[ 'arg[' ord ]_( i < i0 ) F ]" := [arg[ord]_(i < i0 | true) F]
(format "[ 'arg[' ord ]_( i < i0 ) F ]") : nat_scope.
Section ArgMinMax.
Variables (I : finType) (i0 : I) (P : pred I) (F : I -> nat) (Pi0 : P i0).
Definition arg_min := extremum leq i0 P F.
Definition arg_max := extremum geq i0 P F.
Lemma arg_minnP : extremum_spec leq P F arg_min.
Proof. by apply: extremumP => //; [apply: leq_trans|apply: leq_total]. Qed.
Lemma arg_maxnP : extremum_spec geq P F arg_max.
Proof.
apply: extremumP => //; first exact: leqnn.
by move=> n m p mn np; apply: leq_trans mn.
by move=> ??; apply: leq_total.
Qed.
End ArgMinMax.
End Extrema.
Notation "[ 'arg' 'min_' ( i < i0 | P ) F ]" :=
(arg_min i0 (fun i => P%B) (fun i => F))
(i, i0 at level 10,
format "[ 'arg' 'min_' ( i < i0 | P ) F ]") : nat_scope.
Notation "[ 'arg' 'min_' ( i < i0 'in' A ) F ]" :=
[arg min_(i < i0 | i \in A) F]
(format "[ 'arg' 'min_' ( i < i0 'in' A ) F ]") : nat_scope.
Notation "[ 'arg' 'min_' ( i < i0 ) F ]" := [arg min_(i < i0 | true) F]
(format "[ 'arg' 'min_' ( i < i0 ) F ]") : nat_scope.
Notation "[ 'arg' 'max_' ( i > i0 | P ) F ]" :=
(arg_max i0 (fun i => P%B) (fun i => F))
(i, i0 at level 10,
format "[ 'arg' 'max_' ( i > i0 | P ) F ]") : nat_scope.
Notation "[ 'arg' 'max_' ( i > i0 'in' A ) F ]" :=
[arg max_(i > i0 | i \in A) F]
(format "[ 'arg' 'max_' ( i > i0 'in' A ) F ]") : nat_scope.
Notation "[ 'arg' 'max_' ( i > i0 ) F ]" := [arg max_(i > i0 | true) F]
(format "[ 'arg' 'max_' ( i > i0 ) F ]") : nat_scope.
(**********************************************************************)
(* *)
(* Ordinal finType : {0, ... , n-1} *)
(* *)
(**********************************************************************)
Section OrdinalSub.
Variable n : nat.
Inductive ordinal : predArgType := Ordinal m of m < n.
Coercion nat_of_ord i := let: Ordinal m _ := i in m.
HB.instance Definition _ := [isSub of ordinal for nat_of_ord].
HB.instance Definition _ := [Countable of ordinal by <:].
Lemma ltn_ord (i : ordinal) : i < n. Proof. exact: valP i. Qed.
Lemma ord_inj : injective nat_of_ord. Proof. exact: val_inj. Qed.
Definition ord_enum : seq ordinal := pmap insub (iota 0 n).
Lemma val_ord_enum : map val ord_enum = iota 0 n.
Proof.
rewrite pmap_filter; last exact: insubK.
by apply/all_filterP; apply/allP=> i; rewrite mem_iota isSome_insub.
Qed.
Lemma ord_enum_uniq : uniq ord_enum.
Proof. by rewrite pmap_sub_uniq ?iota_uniq. Qed.
Lemma mem_ord_enum i : i \in ord_enum.
Proof. by rewrite -(mem_map ord_inj) val_ord_enum mem_iota ltn_ord. Qed.
HB.instance Definition _ := isFinite.Build ordinal
(Finite.uniq_enumP ord_enum_uniq mem_ord_enum).
End OrdinalSub.
Notation "''I_' n" := (ordinal n)
(at level 0, n at level 2, format "''I_' n").
#[global] Hint Resolve ltn_ord : core.
Section OrdinalEnum.
Variable n : nat.
Lemma val_enum_ord : map val (enum 'I_n) = iota 0 n.
Proof. by rewrite enumT unlock val_ord_enum. Qed.
Lemma size_enum_ord : size (enum 'I_n) = n.
Proof. by rewrite -(size_map val) val_enum_ord size_iota. Qed.
Lemma card_ord : #|'I_n| = n.
Proof. by rewrite cardE size_enum_ord. Qed.
Lemma nth_enum_ord i0 m : m < n -> nth i0 (enum 'I_n) m = m :> nat.
Proof.
by move=> ?; rewrite -(nth_map _ 0) (size_enum_ord, val_enum_ord) // nth_iota.
Qed.
Lemma nth_ord_enum (i0 i : 'I_n) : nth i0 (enum 'I_n) i = i.
Proof. by apply: val_inj; apply: nth_enum_ord. Qed.
Lemma index_enum_ord (i : 'I_n) : index i (enum 'I_n) = i.
Proof.
by rewrite -[in LHS](nth_ord_enum i i) index_uniq ?(enum_uniq, size_enum_ord).
Qed.
Lemma mask_enum_ord m :
mask m (enum 'I_n) = [seq i <- enum 'I_n | nth false m (val i)].
Proof.
rewrite mask_filter ?enum_uniq//; apply: eq_filter => i.
by rewrite in_mask ?enum_uniq ?mem_enum// index_enum_ord.
Qed.
End OrdinalEnum.
Lemma enum_ord0 : enum 'I_0 = [::].
Proof. by apply/eqP; rewrite -size_eq0 size_enum_ord. Qed.
Lemma widen_ord_proof n m (i : 'I_n) : n <= m -> i < m.
Proof. exact: leq_trans. Qed.
Definition widen_ord n m le_n_m i := Ordinal (@widen_ord_proof n m i le_n_m).
Lemma cast_ord_proof n m (i : 'I_n) : n = m -> i < m.
Proof. by move <-. Qed.
Definition cast_ord n m eq_n_m i := Ordinal (@cast_ord_proof n m i eq_n_m).
Lemma cast_ord_id n eq_n i : cast_ord eq_n i = i :> 'I_n.
Proof. exact: val_inj. Qed.
Lemma cast_ord_comp n1 n2 n3 eq_n2 eq_n3 i :
@cast_ord n2 n3 eq_n3 (@cast_ord n1 n2 eq_n2 i) =
cast_ord (etrans eq_n2 eq_n3) i.
Proof. exact: val_inj. Qed.
Lemma cast_ordK n1 n2 eq_n :
cancel (@cast_ord n1 n2 eq_n) (cast_ord (esym eq_n)).
Proof. by move=> i; apply: val_inj. Qed.
Lemma cast_ordKV n1 n2 eq_n :
cancel (cast_ord (esym eq_n)) (@cast_ord n1 n2 eq_n).
Proof. by move=> i; apply: val_inj. Qed.
Lemma cast_ord_inj n1 n2 eq_n : injective (@cast_ord n1 n2 eq_n).
Proof. exact: can_inj (cast_ordK eq_n). Qed.
Fact ordS_subproof n (i : 'I_n) : i.+1 %% n < n.
Proof. by case: n i => [|n] [m m_lt]//=; rewrite ltn_pmod. Qed.
Definition ordS n (i : 'I_n) := Ordinal (ordS_subproof i).
Fact ord_pred_subproof n (i : 'I_n) : (i + n).-1 %% n < n.
Proof. by case: n i => [|n] [m m_lt]//=; rewrite ltn_pmod. Qed.
Definition ord_pred n (i : 'I_n) := Ordinal (ord_pred_subproof i).
Lemma ordSK n : cancel (@ordS n) (@ord_pred n).
Proof.
move=> [i ilt]; apply/val_inj => /=.
case: (ltngtP i.+1) (ilt) => // [Silt|<-]; last by rewrite modnn/= modn_small.
by rewrite [i.+1 %% n]modn_small// addSn/= modnDr modn_small.
Qed.
Lemma ord_predK n : cancel (@ord_pred n) (@ordS n).
Proof.
move=> [[|i] ilt]; apply/val_inj => /=.
by rewrite [n.-1 %% n]modn_small// prednK// modnn.
by rewrite modnDr [i %% n]modn_small ?modn_small// ltnW.
Qed.
Lemma ordS_bij n : bijective (@ordS n).
Proof. exact: (Bijective (@ordSK n) (@ord_predK n)). Qed.
Lemma ordS_inj n : injective (@ordS n).
Proof. exact: (bij_inj (ordS_bij n)). Qed.
Lemma ord_pred_bij n : bijective (@ord_pred n).
Proof. exact (Bijective (@ord_predK n) (@ordSK n)). Qed.
Lemma ord_pred_inj n : injective (@ord_pred n).
Proof. exact: (bij_inj (ord_pred_bij n)). Qed.
Lemma rev_ord_proof n (i : 'I_n) : n - i.+1 < n.
Proof. by case: n i => [|n] [i lt_i_n] //; rewrite ltnS subSS leq_subr. Qed.
Definition rev_ord n i := Ordinal (@rev_ord_proof n i).
Lemma rev_ordK {n} : involutive (@rev_ord n).
Proof.
by case: n => [|n] [i lti] //; apply: val_inj; rewrite /= !subSS subKn.
Qed.
Lemma rev_ord_inj {n} : injective (@rev_ord n).
Proof. exact: inv_inj rev_ordK. Qed.
Lemma inj_leq m n (f : 'I_m -> 'I_n) : injective f -> m <= n.
Proof. by move=> /leq_card; rewrite !card_ord. Qed.
Arguments inj_leq [m n] f _.
(* bijection between any finType T and the Ordinal finType of its cardinal *)
Lemma enum_rank_subproof (T : finType) x0 (A : {pred T}) : x0 \in A -> 0 < #|A|.
Proof. by move=> Ax0; rewrite (cardD1 x0) Ax0. Qed.
HB.lock
Definition enum_rank_in (T : finType) x0 (A : {pred T}) (Ax0 : x0 \in A) x :=
insubd (Ordinal (@enum_rank_subproof T x0 [eta A] Ax0)) (index x (enum A)).
Canonical unlockable_enum_rank_in := Unlockable enum_rank_in.unlock.
Section EnumRank.
Variable T : finType.
Implicit Type A : {pred T}.
Definition enum_rank x := @enum_rank_in T x T (erefl true) x.
Lemma enum_default A : 'I_(#|A|) -> T.
Proof. by rewrite cardE; case: (enum A) => [|//] []. Qed.
Definition enum_val A i := nth (@enum_default [eta A] i) (enum A) i.
Prenex Implicits enum_val.
Lemma enum_valP A i : @enum_val A i \in A.
Proof. by rewrite -mem_enum mem_nth -?cardE. Qed.
Lemma enum_val_nth A x i : @enum_val A i = nth x (enum A) i.
Proof. by apply: set_nth_default; rewrite cardE in i *; apply: ltn_ord. Qed.
Lemma nth_image T' y0 (f : T -> T') A (i : 'I_#|A|) :
nth y0 (image f A) i = f (enum_val i).
Proof. by rewrite -(nth_map _ y0) // -cardE. Qed.
Lemma nth_codom T' y0 (f : T -> T') (i : 'I_#|T|) :
nth y0 (codom f) i = f (enum_val i).
Proof. exact: nth_image. Qed.
Lemma nth_enum_rank_in x00 x0 A Ax0 :
{in A, cancel (@enum_rank_in T x0 A Ax0) (nth x00 (enum A))}.
Proof.
move=> x Ax; rewrite enum_rank_in.unlock insubdK ?nth_index ?mem_enum //.
by rewrite cardE [_ \in _]index_mem mem_enum.
Qed.
Lemma nth_enum_rank x0 : cancel enum_rank (nth x0 (enum T)).
Proof. by move=> x; apply: nth_enum_rank_in. Qed.
Lemma enum_rankK_in x0 A Ax0 :
{in A, cancel (@enum_rank_in T x0 A Ax0) enum_val}.
Proof. by move=> x; apply: nth_enum_rank_in. Qed.
Lemma enum_rankK : cancel enum_rank enum_val.
Proof. by move=> x; apply: enum_rankK_in. Qed.
Lemma enum_valK_in x0 A Ax0 : cancel enum_val (@enum_rank_in T x0 A Ax0).
Proof.
move=> x; apply: ord_inj; rewrite enum_rank_in.unlock insubdK; last first.
by rewrite cardE [_ \in _]index_mem mem_nth // -cardE.
by rewrite index_uniq ?enum_uniq // -cardE.
Qed.
Lemma enum_valK : cancel enum_val enum_rank.
Proof. by move=> x; apply: enum_valK_in. Qed.
Lemma enum_rank_inj : injective enum_rank.
Proof. exact: can_inj enum_rankK. Qed.
Lemma enum_val_inj A : injective (@enum_val A).
Proof. by move=> i; apply: can_inj (enum_valK_in (enum_valP i)) (i). Qed.
Lemma enum_val_bij_in x0 A : x0 \in A -> {on A, bijective (@enum_val A)}.
Proof.
move=> Ax0; exists (enum_rank_in Ax0) => [i _|]; last exact: enum_rankK_in.
exact: enum_valK_in.
Qed.
Lemma eq_enum_rank_in (x0 y0 : T) A (Ax0 : x0 \in A) (Ay0 : y0 \in A) :
{in A, enum_rank_in Ax0 =1 enum_rank_in Ay0}.
Proof. by move=> x xA; apply: enum_val_inj; rewrite !enum_rankK_in. Qed.
Lemma enum_rank_in_inj (x0 y0 : T) A (Ax0 : x0 \in A) (Ay0 : y0 \in A) :
{in A &, forall x y, enum_rank_in Ax0 x = enum_rank_in Ay0 y -> x = y}.
Proof. by move=> x y xA yA /(congr1 enum_val); rewrite !enum_rankK_in. Qed.
Lemma enum_rank_bij : bijective enum_rank.
Proof. by move: enum_rankK enum_valK; exists (@enum_val T). Qed.
Lemma enum_val_bij : bijective (@enum_val T).
Proof. by move: enum_rankK enum_valK; exists enum_rank. Qed.
(* Due to the limitations of the Coq unification patterns, P can only be *)
(* inferred from the premise of this lemma, not its conclusion. As a result *)
(* this lemma will only be usable in forward chaining style. *)
Lemma fin_all_exists U (P : forall x : T, U x -> Prop) :
(forall x, exists u, P x u) -> (exists u, forall x, P x (u x)).
Proof.
move=> ex_u; pose Q m x := enum_rank x < m -> {ux | P x ux}.
suffices: forall m, m <= #|T| -> exists w : forall x, Q m x, True.
case/(_ #|T|)=> // w _; pose u x := sval (w x (ltn_ord _)).
by exists u => x; rewrite {}/u; case: (w x _).
elim=> [|m IHm] ltmX; first by have w x: Q 0 x by []; exists w.
have{IHm} [w _] := IHm (ltnW ltmX); pose i := Ordinal ltmX.
have [u Pu] := ex_u (enum_val i); suffices w' x: Q m.+1 x by exists w'.
rewrite /Q ltnS leq_eqVlt (val_eqE _ i); case: eqP => [def_i _ | _ /w //].
by rewrite -def_i enum_rankK in u Pu; exists u.
Qed.
Lemma fin_all_exists2 U (P Q : forall x : T, U x -> Prop) :
(forall x, exists2 u, P x u & Q x u) ->
(exists2 u, forall x, P x (u x) & forall x, Q x (u x)).
Proof.
move=> ex_u; have (x): exists u, P x u /\ Q x u by have [u] := ex_u x; exists u.
by case/fin_all_exists=> u /all_and2[]; exists u.
Qed.
End EnumRank.
Arguments enum_val_inj {T A} [i1 i2] : rename.
Arguments enum_rank_inj {T} [x1 x2].
Prenex Implicits enum_val enum_rank enum_valK enum_rankK.
Lemma enum_rank_ord n i : enum_rank i = cast_ord (esym (card_ord n)) i.
Proof.
apply: val_inj; rewrite /enum_rank enum_rank_in.unlock.
by rewrite insubdK ?index_enum_ord // card_ord [_ \in _]ltn_ord.
Qed.
Lemma enum_val_ord n i : enum_val i = cast_ord (card_ord n) i.
Proof.
by apply: canLR (@enum_rankK _) _; apply: val_inj; rewrite enum_rank_ord.
Qed.
(* The integer bump / unbump operations. *)
Definition bump h i := (h <= i) + i.
Definition unbump h i := i - (h < i).
Lemma bumpK h : cancel (bump h) (unbump h).
Proof.
rewrite /bump /unbump => i.
have [le_hi | lt_ih] := leqP h i; first by rewrite ltnS le_hi subn1.
by rewrite ltnNge ltnW ?subn0.
Qed.
Lemma neq_bump h i : h != bump h i.
Proof.
rewrite /bump eqn_leq; have [le_hi | lt_ih] := leqP h i.
by rewrite ltnNge le_hi andbF.
by rewrite leqNgt lt_ih.
Qed.
Lemma unbumpKcond h i : bump h (unbump h i) = (i == h) + i.
Proof.
rewrite /bump /unbump leqNgt -subSKn.
case: (ltngtP i h) => /= [-> | ltih | ->] //; last by rewrite ltnn.
by rewrite subn1 /= leqNgt !(ltn_predK ltih, ltih, add1n).
Qed.
Lemma unbumpK {h} : {in predC1 h, cancel (unbump h) (bump h)}.
Proof. by move=> i /negbTE-neq_h_i; rewrite unbumpKcond neq_h_i. Qed.
Lemma bumpDl h i k : bump (k + h) (k + i) = k + bump h i.
Proof. by rewrite /bump leq_add2l addnCA. Qed.
Lemma bumpS h i : bump h.+1 i.+1 = (bump h i).+1.
Proof. exact: addnS. Qed.
Lemma unbumpDl h i k : unbump (k + h) (k + i) = k + unbump h i.
Proof.
apply: (can_inj (bumpK (k + h))).
by rewrite bumpDl !unbumpKcond eqn_add2l addnCA.
Qed.
Lemma unbumpS h i : unbump h.+1 i.+1 = (unbump h i).+1.
Proof. exact: unbumpDl 1. Qed.
Lemma leq_bump h i j : (i <= bump h j) = (unbump h i <= j).
Proof.
rewrite /bump leq_subLR.
case: (leqP i h) (leqP h j) => [le_i_h | lt_h_i] [le_h_j | lt_j_h] //.
by rewrite leqW (leq_trans le_i_h).
by rewrite !(leqNgt i) ltnW (leq_trans _ lt_h_i).
Qed.
Lemma leq_bump2 h i j : (bump h i <= bump h j) = (i <= j).
Proof. by rewrite leq_bump bumpK. Qed.
Lemma bumpC h1 h2 i :
bump h1 (bump h2 i) = bump (bump h1 h2) (bump (unbump h2 h1) i).
Proof.
rewrite {1 5}/bump -leq_bump addnCA; congr (_ + (_ + _)).
rewrite 2!leq_bump /unbump /bump; case: (leqP h1 h2) => [le_h12 | lt_h21].
by rewrite subn0 ltnS le_h12 subn1.
by rewrite subn1 (ltn_predK lt_h21) (leqNgt h1) lt_h21 subn0.
Qed.
(* The lift operations on ordinals; to avoid a messy dependent type, *)
(* unlift is a partial operation (returns an option). *)
Lemma lift_subproof n h (i : 'I_n.-1) : bump h i < n.
Proof. by case: n i => [[]|n] //= i; rewrite -addnS (leq_add (leq_b1 _)). Qed.
Definition lift n (h : 'I_n) (i : 'I_n.-1) := Ordinal (lift_subproof h i).
Lemma unlift_subproof n (h : 'I_n) (u : {j | j != h}) : unbump h (val u) < n.-1.
Proof.
case: n h u => [|n h] [] //= j ne_jh.
rewrite -(leq_bump2 h.+1) bumpS unbumpK // /bump.
case: (ltngtP n h) => [|_|eq_nh]; rewrite ?(leqNgt _ h) ?ltn_ord //.
by rewrite ltn_neqAle [j <= _](valP j) {2}eq_nh andbT.
Qed.
Definition unlift n (h i : 'I_n) :=
omap (fun u : {j | j != h} => Ordinal (unlift_subproof u)) (insub i).
Variant unlift_spec n h i : option 'I_n.-1 -> Type :=
| UnliftSome j of i = lift h j : unlift_spec h i (Some j)
| UnliftNone of i = h : unlift_spec h i None.
Lemma unliftP n (h i : 'I_n) : unlift_spec h i (unlift h i).
Proof.
rewrite /unlift; case: insubP => [u nhi | ] def_i /=; constructor.
by apply: val_inj; rewrite /= def_i unbumpK.
by rewrite negbK in def_i; apply/eqP.
Qed.
Lemma neq_lift n (h : 'I_n) i : h != lift h i.
Proof. exact: neq_bump. Qed.
Lemma eq_liftF n (h : 'I_n) i : (h == lift h i) = false.
Proof. exact/negbTE/neq_lift. Qed.
Lemma lift_eqF n (h : 'I_n) i : (lift h i == h) = false.
Proof. by rewrite eq_sym eq_liftF. Qed.
Lemma unlift_none n (h : 'I_n) : unlift h h = None.
Proof. by case: unliftP => // j Dh; case/eqP: (neq_lift h j). Qed.
Lemma unlift_some n (h i : 'I_n) :
h != i -> {j | i = lift h j & unlift h i = Some j}.
Proof.
rewrite eq_sym => /eqP neq_ih.
by case Dui: (unlift h i) / (unliftP h i) => [j Dh|//]; exists j.
Qed.
Lemma lift_inj n (h : 'I_n) : injective (lift h).
Proof. by move=> i1 i2 [/(can_inj (bumpK h))/val_inj]. Qed.
Arguments lift_inj {n h} [i1 i2] eq_i12h : rename.
Lemma liftK n (h : 'I_n) : pcancel (lift h) (unlift h).
Proof. by move=> i; case: (unlift_some (neq_lift h i)) => j /lift_inj->. Qed.
(* Shifting and splitting indices, for cutting and pasting arrays *)
Lemma lshift_subproof m n (i : 'I_m) : i < m + n.
Proof. by apply: leq_trans (valP i) _; apply: leq_addr. Qed.
Lemma rshift_subproof m n (i : 'I_n) : m + i < m + n.
Proof. by rewrite ltn_add2l. Qed.
Definition lshift m n (i : 'I_m) := Ordinal (lshift_subproof n i).
Definition rshift m n (i : 'I_n) := Ordinal (rshift_subproof m i).
Lemma lshift_inj m n : injective (@lshift m n).
Proof. by move=> ? ? /(f_equal val) /= /val_inj. Qed.
Lemma rshift_inj m n : injective (@rshift m n).
Proof. by move=> ? ? /(f_equal val) /addnI /val_inj. Qed.
Lemma eq_lshift m n i j : (@lshift m n i == @lshift m n j) = (i == j).
Proof. by rewrite (inj_eq (@lshift_inj _ _)). Qed.
Lemma eq_rshift m n i j : (@rshift m n i == @rshift m n j) = (i == j).
Proof. by rewrite (inj_eq (@rshift_inj _ _)). Qed.
Lemma eq_lrshift m n i j : (@lshift m n i == @rshift m n j) = false.
Proof.
apply/eqP=> /(congr1 val)/= def_i; have := ltn_ord i.
by rewrite def_i -ltn_subRL subnn.
Qed.
Lemma eq_rlshift m n i j : (@rshift m n i == @lshift m n j) = false.
Proof. by rewrite eq_sym eq_lrshift. Qed.
Definition eq_shift := (eq_lshift, eq_rshift, eq_lrshift, eq_rlshift).
Lemma split_subproof m n (i : 'I_(m + n)) : i >= m -> i - m < n.
Proof. by move/subSn <-; rewrite leq_subLR. Qed.
Definition split {m n} (i : 'I_(m + n)) : 'I_m + 'I_n :=
match ltnP (i) m with
| LtnNotGeq lt_i_m => inl _ (Ordinal lt_i_m)
| GeqNotLtn ge_i_m => inr _ (Ordinal (split_subproof ge_i_m))
end.
Variant split_spec m n (i : 'I_(m + n)) : 'I_m + 'I_n -> bool -> Type :=
| SplitLo (j : 'I_m) of i = j :> nat : split_spec i (inl _ j) true
| SplitHi (k : 'I_n) of i = m + k :> nat : split_spec i (inr _ k) false.
Lemma splitP m n (i : 'I_(m + n)) : split_spec i (split i) (i < m).
Proof.
(* We need to prevent the case on ltnP from rewriting the hidden constructor *)
(* argument types of the match branches exposed by unfolding split. If the *)
(* match representation is changed to omit these then this proof could reduce *)
(* to by rewrite /split; case: ltnP; [left | right. rewrite subnKC]. *)
set lt_i_m := i < m; rewrite /split.
by case: _ _ _ _ {-}_ lt_i_m / ltnP; [left | right; rewrite subnKC].
Qed.
Variant split_ord_spec m n (i : 'I_(m + n)) : 'I_m + 'I_n -> bool -> Type :=
| SplitOrdLo (j : 'I_m) of i = lshift _ j : split_ord_spec i (inl _ j) true
| SplitOrdHi (k : 'I_n) of i = rshift _ k : split_ord_spec i (inr _ k) false.
Lemma split_ordP m n (i : 'I_(m + n)) : split_ord_spec i (split i) (i < m).
Proof. by case: splitP; [left|right]; apply: val_inj. Qed.
Definition unsplit {m n} (jk : 'I_m + 'I_n) :=
match jk with inl j => lshift n j | inr k => rshift m k end.
Lemma ltn_unsplit m n (jk : 'I_m + 'I_n) : (unsplit jk < m) = jk.
Proof. by case: jk => [j|k]; rewrite /= ?ltn_ord // ltnNge leq_addr. Qed.
Lemma splitK {m n} : cancel (@split m n) unsplit.
Proof. by move=> i; case: split_ordP. Qed.
Lemma unsplitK {m n} : cancel (@unsplit m n) split.
Proof.
by move=> [j|k]; case: split_ordP => ? /eqP; rewrite eq_shift// => /eqP->.
Qed.
Section OrdinalPos.
Variable n' : nat.
Local Notation n := n'.+1.
Definition ord0 := Ordinal (ltn0Sn n').
Definition ord_max := Ordinal (ltnSn n').
Lemma leq_ord (i : 'I_n) : i <= n'. Proof. exact: valP i. Qed.
Lemma sub_ord_proof m : n' - m < n.
Proof. by rewrite ltnS leq_subr. Qed.
Definition sub_ord m := Ordinal (sub_ord_proof m).
Lemma sub_ordK (i : 'I_n) : n' - (n' - i) = i.
Proof. by rewrite subKn ?leq_ord. Qed.
Definition inord m : 'I_n := insubd ord0 m.
Lemma inordK m : m < n -> inord m = m :> nat.
Proof. by move=> lt_m; rewrite val_insubd lt_m. Qed.
Lemma inord_val (i : 'I_n) : inord i = i.
Proof. by rewrite /inord /insubd valK. Qed.
Lemma enum_ordSl : enum 'I_n = ord0 :: map (lift ord0) (enum 'I_n').
Proof.
apply: (inj_map val_inj); rewrite val_enum_ord /= -map_comp.
by rewrite (map_comp (addn 1)) val_enum_ord -iotaDl.
Qed.
Lemma enum_ordSr :
enum 'I_n = rcons (map (widen_ord (leqnSn _)) (enum 'I_n')) ord_max.
Proof.
apply: (inj_map val_inj); rewrite val_enum_ord.
rewrite -[in iota _ _]addn1 iotaD/= cats1 map_rcons; congr (rcons _ _).
by rewrite -map_comp/= (@eq_map _ _ _ val) ?val_enum_ord.
Qed.
Lemma lift_max (i : 'I_n') : lift ord_max i = i :> nat.
Proof. by rewrite /= /bump leqNgt ltn_ord. Qed.
Lemma lift0 (i : 'I_n') : lift ord0 i = i.+1 :> nat. Proof. by []. Qed.
End OrdinalPos.
Arguments ord0 {n'}.
Arguments ord_max {n'}.
Arguments inord {n'}.
Arguments sub_ord {n'}.
Arguments sub_ordK {n'}.
Arguments inord_val {n'}.
Lemma ord1 : all_equal_to (ord0 : 'I_1).
Proof. by case=> [[] // ?]; apply: val_inj. Qed.
(* Product of two fintypes which is a fintype *)
Section ProdFinType.
Variable T1 T2 : finType.
Definition prod_enum := [seq (x1, x2) | x1 <- enum T1, x2 <- enum T2].
Lemma predX_prod_enum (A1 : {pred T1}) (A2 : {pred T2}) :
count [predX A1 & A2] prod_enum = #|A1| * #|A2|.
Proof.
rewrite !cardE !size_filter -!enumT /prod_enum.
elim: (enum T1) => //= x1 s1 IHs; rewrite count_cat {}IHs count_map /preim /=.
by case: (x1 \in A1); rewrite ?count_pred0.
Qed.
Lemma prod_enumP : Finite.axiom prod_enum.
Proof.
by case=> x1 x2; rewrite (predX_prod_enum (pred1 x1) (pred1 x2)) !card1.
Qed.
HB.instance Definition _ := isFinite.Build (T1 * T2)%type prod_enumP.
Lemma cardX (A1 : {pred T1}) (A2 : {pred T2}) :
#|[predX A1 & A2]| = #|A1| * #|A2|.
Proof. by rewrite -predX_prod_enum unlock size_filter unlock. Qed.
Lemma card_prod : #|{: T1 * T2}| = #|T1| * #|T2|.
Proof. by rewrite -cardX; apply: eq_card; case. Qed.
Lemma eq_card_prod (A : {pred (T1 * T2)}) : A =i predT -> #|A| = #|T1| * #|T2|.
Proof. exact: eq_card_trans card_prod. Qed.
End ProdFinType.
Section TagFinType.
Variables (I : finType) (T_ : I -> finType).
Definition tag_enum :=
flatten [seq [seq Tagged T_ x | x <- enumF (T_ i)] | i <- enumF I].
Lemma tag_enumP : Finite.axiom tag_enum.
Proof.
case=> i x; rewrite -(enumP i) /tag_enum -enumT.
elim: (enum I) => //= j e IHe.
rewrite count_cat count_map {}IHe; congr (_ + _).
rewrite -size_filter -cardE /=; case: eqP => [-> | ne_j_i].
by apply: (@eq_card1 _ x) => y; rewrite -topredE /= tagged_asE ?eqxx.
by apply: eq_card0 => y.
Qed.
HB.instance Definition _ := isFinite.Build {i : I & T_ i} tag_enumP.
Lemma card_tagged :
#|{: {i : I & T_ i}}| = sumn (map (fun i => #|T_ i|) (enum I)).
Proof.
rewrite cardE !enumT [in LHS]unlock size_flatten /shape -map_comp.
by congr (sumn _); apply: eq_map => i; rewrite /= size_map -enumT -cardE.
Qed.
End TagFinType.
Section SumFinType.
Variables T1 T2 : finType.
Definition sum_enum :=
[seq inl _ x | x <- enumF T1] ++ [seq inr _ y | y <- enumF T2].
Lemma sum_enum_uniq : uniq sum_enum.
Proof.
rewrite cat_uniq -!enumT !(enum_uniq, map_inj_uniq); try by move=> ? ? [].
by rewrite andbT; apply/hasP=> [[_ /mapP[x _ ->] /mapP[]]].
Qed.
Lemma mem_sum_enum u : u \in sum_enum.
Proof. by case: u => x; rewrite mem_cat -!enumT map_f ?mem_enum ?orbT. Qed.
HB.instance Definition sum_isFinite := isFinite.Build (T1 + T2)%type
(Finite.uniq_enumP sum_enum_uniq mem_sum_enum).
Lemma card_sum : #|{: T1 + T2}| = #|T1| + #|T2|.
Proof. by rewrite !cardT !enumT [in LHS]unlock size_cat !size_map. Qed.
End SumFinType.
|
Univ.lean
|
/-
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.Equiv
import Mathlib.LinearAlgebra.Matrix.Charpoly.Coeff
import Mathlib.RingTheory.MvPolynomial.Homogeneous
/-!
# The universal characteristic polynomial
In this file we define the universal characteristic polynomial `Matrix.charpoly.univ`,
which is the charactistic polynomial of the matrix with entries `Xᵢⱼ`,
and hence has coefficients that are multivariate polynomials.
It is universal in the sense that one obtains the characteristic polynomial of a matrix `M`
by evaluating the coefficients of `univ` at the entries of `M`.
We use it to show that the coefficients of the characteristic polynomial
of a matrix are homogeneous polynomials in the matrix entries.
## Main results
* `Matrix.charpoly.univ`: the universal characteristic polynomial
* `Matrix.charpoly.univ_map_eval₂Hom`: evaluating `univ` on the entries of a matrix `M`
gives the characteristic polynomial of `M`.
* `Matrix.charpoly.univ_coeff_isHomogeneous`:
the `i`-th coefficient of `univ` is a homogeneous polynomial of degree `n - i`.
-/
namespace Matrix.charpoly
variable {R S : Type*} (n : Type*) [CommRing R] [CommRing S] [Fintype n] [DecidableEq n]
variable (f : R →+* S)
variable (R) in
/-- The universal characteristic polynomial for `n × n`-matrices,
is the charactistic polynomial of `Matrix.mvPolynomialX n n ℤ` with entries `Xᵢⱼ`.
Its `i`-th coefficient is a homogeneous polynomial of degree `n - i`,
see `Matrix.charpoly.univ_coeff_isHomogeneous`.
By evaluating the coefficients at the entries of a matrix `M`,
one obtains the characteristic polynomial of `M`,
see `Matrix.charpoly.univ_map_eval₂Hom`. -/
noncomputable
abbrev univ : Polynomial (MvPolynomial (n × n) R) :=
charpoly <| mvPolynomialX n n R
open MvPolynomial RingHomClass in
@[simp]
lemma univ_map_eval₂Hom (M : n × n → S) :
(univ R n).map (eval₂Hom f M) = charpoly (Matrix.of M.curry) := by
rw [univ, ← charpoly_map, coe_eval₂Hom, ← mvPolynomialX_map_eval₂ f (Matrix.of M.curry)]
simp only [of_apply, Function.curry_apply, Prod.mk.eta]
lemma univ_map_map :
(univ R n).map (MvPolynomial.map f) = univ S n := by
rw [MvPolynomial.map, univ_map_eval₂Hom]; rfl
@[simp]
lemma univ_coeff_eval₂Hom (M : n × n → S) (i : ℕ) :
MvPolynomial.eval₂Hom f M ((univ R n).coeff i) =
(charpoly (Matrix.of M.curry)).coeff i := by
rw [← univ_map_eval₂Hom n f M, Polynomial.coeff_map]
variable (R)
lemma univ_monic : (univ R n).Monic := charpoly_monic (mvPolynomialX n n R)
lemma univ_natDegree [Nontrivial R] : (univ R n).natDegree = Fintype.card n :=
charpoly_natDegree_eq_dim (mvPolynomialX n n R)
@[simp]
lemma univ_coeff_card : (univ R n).coeff (Fintype.card n) = 1 := by
suffices Polynomial.coeff (univ ℤ n) (Fintype.card n) = 1 by
rw [← univ_map_map n (Int.castRingHom R), Polynomial.coeff_map, this, map_one]
rw [← univ_natDegree ℤ n]
exact (univ_monic ℤ n).leadingCoeff
open MvPolynomial in
lemma optionEquivLeft_symm_univ_isHomogeneous :
((optionEquivLeft R (n × n)).symm (univ R n)).IsHomogeneous (Fintype.card n) := by
have aux : Fintype.card n = 0 + ∑ i : n, 1 := by
simp only [zero_add, Finset.sum_const, smul_eq_mul, mul_one, Fintype.card]
simp only [aux, univ, charpoly, charmatrix, scalar_apply, RingHom.mapMatrix_apply, det_apply',
sub_apply, map_apply, of_apply, map_sum, map_mul, map_intCast, map_prod, map_sub,
optionEquivLeft_symm_apply, Polynomial.aevalTower_C, rename_X, diagonal, mvPolynomialX]
apply IsHomogeneous.sum
rintro i -
apply IsHomogeneous.mul
· apply isHomogeneous_C
· apply IsHomogeneous.prod
rintro j -
by_cases h : i j = j
· simp only [h, ↓reduceIte, Polynomial.aevalTower_X, IsHomogeneous.sub, isHomogeneous_X]
· simp only [h, ↓reduceIte, map_zero, zero_sub, (isHomogeneous_X _ _).neg]
lemma univ_coeff_isHomogeneous (i j : ℕ) (h : i + j = Fintype.card n) :
((univ R n).coeff i).IsHomogeneous j :=
(optionEquivLeft_symm_univ_isHomogeneous R n).coeff_isHomogeneous_of_optionEquivLeft_symm _ _ h
end Matrix.charpoly
|
Finite.lean
|
/-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import Mathlib.RingTheory.LocalProperties.Basic
import Mathlib.RingTheory.Localization.Integer
import Mathlib.RingTheory.TensorProduct.Finite
/-!
# The meta properties of finite ring homomorphisms.
## Main results
Let `R` be a commutative ring, `S` is an `R`-algebra, `M` be a submonoid of `R`.
* `finite_localizationPreserves` : If `S` is a finite `R`-algebra, then `S' = M⁻¹S` is a
finite `R' = M⁻¹R`-algebra.
* `finite_ofLocalizationSpan` : `S` is a finite `R`-algebra if there exists
a set `{ r }` that spans `R` such that `Sᵣ` is a finite `Rᵣ`-algebra.
-/
namespace RingHom
open scoped TensorProduct
open TensorProduct Algebra.TensorProduct
theorem finite_stableUnderComposition : StableUnderComposition @Finite := by
introv R hf hg
exact hg.comp hf
theorem finite_respectsIso : RespectsIso @Finite := by
apply finite_stableUnderComposition.respectsIso
intros
exact Finite.of_surjective _ (RingEquiv.toEquiv _).surjective
lemma finite_containsIdentities : ContainsIdentities @Finite := Finite.id
theorem finite_isStableUnderBaseChange : IsStableUnderBaseChange @Finite := by
refine IsStableUnderBaseChange.mk finite_respectsIso ?_
classical
introv h
replace h : Module.Finite R T := by
rw [RingHom.Finite] at h; convert h; ext; simp_rw [Algebra.smul_def]; rfl
suffices Module.Finite S (S ⊗[R] T) by
rw [RingHom.Finite]; convert this; congr; ext; simp_rw [Algebra.smul_def]; rfl
exact inferInstance
end RingHom
open scoped Pointwise
universe u
variable {R S : Type*} [CommRing R] [CommRing S] (M : Submonoid R) (f : R →+* S)
variable (R' S' : Type*) [CommRing R'] [CommRing S']
variable [Algebra R R'] [Algebra S S']
lemma Module.Finite.of_isLocalization (R S) {Rₚ Sₚ : Type*} [CommSemiring R] [CommSemiring S]
[CommSemiring Rₚ] [CommSemiring Sₚ] [Algebra R S] [Algebra R Rₚ] [Algebra R Sₚ] [Algebra S Sₚ]
[Algebra Rₚ Sₚ] [IsScalarTower R S Sₚ] [IsScalarTower R Rₚ Sₚ] (M : Submonoid R)
[IsLocalization M Rₚ] [IsLocalization (Algebra.algebraMapSubmonoid S M) Sₚ]
[hRS : Module.Finite R S] :
Module.Finite Rₚ Sₚ := by
classical
have : algebraMap Rₚ Sₚ = IsLocalization.map (T := Algebra.algebraMapSubmonoid S M) Sₚ
(algebraMap R S) (Submonoid.le_comap_map M) := by
apply IsLocalization.ringHom_ext M
simp only [IsLocalization.map_comp, ← IsScalarTower.algebraMap_eq]
-- We claim that if `S` is generated by `T` as an `R`-module,
-- then `S'` is generated by `T` as an `R'`-module.
obtain ⟨T, hT⟩ := hRS
use T.image (algebraMap S Sₚ)
rw [eq_top_iff]
rintro x -
-- By the hypotheses, for each `x : S'`, we have `x = y / (f r)` for some `y : S` and `r : M`.
-- Since `S` is generated by `T`, the image of `y` should fall in the span of the image of `T`.
obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ :=
IsLocalization.mk'_surjective (Algebra.algebraMapSubmonoid S M) x
rw [IsLocalization.mk'_eq_mul_mk'_one, mul_comm, Finset.coe_image]
have hy : y ∈ Submodule.span R ↑T := by rw [hT]; trivial
replace hy : algebraMap S Sₚ y ∈ Submodule.map (IsScalarTower.toAlgHom R S Sₚ).toLinearMap
(Submodule.span R (T : Set S)) := Submodule.mem_map_of_mem
-- -- Note: https://github.com/leanprover-community/mathlib4/pull/8386 had to specify the value of `f` below
(f := (IsScalarTower.toAlgHom R S Sₚ).toLinearMap) hy
rw [Submodule.map_span (IsScalarTower.toAlgHom R S Sₚ).toLinearMap T] at hy
have H : Submodule.span R (algebraMap S Sₚ '' T) ≤
(Submodule.span Rₚ (algebraMap S Sₚ '' T)).restrictScalars R := by
rw [Submodule.span_le]; exact Submodule.subset_span
-- Now, since `y ∈ span T`, and `(f r)⁻¹ ∈ R'`, `x / (f r)` is in `span T` as well.
convert (Submodule.span Rₚ (algebraMap S Sₚ '' T)).smul_mem
(IsLocalization.mk' Rₚ (1 : R) ⟨r, hr⟩) (H hy) using 1
rw [Algebra.smul_def, this, IsLocalization.map_mk', map_one]
@[deprecated (since := "2025-05-01")] alias Module.Finite_of_isLocalization :=
Module.Finite.of_isLocalization
open Algebra nonZeroDivisors in
instance {A C : Type*} [CommRing A] [CommRing C] [Algebra A C] [Module.Finite A C] :
Module.Finite (FractionRing A) (Localization (algebraMapSubmonoid C A⁰)) :=
have : IsScalarTower A (FractionRing A) (Localization (algebraMapSubmonoid C A⁰)) :=
instIsScalarTowerLocalizationAlgebraMapSubmonoid A⁰ C
.of_isLocalization A C A⁰
/-- If `S` is a finite `R`-algebra, then `S' = M⁻¹S` is a finite `R' = M⁻¹R`-algebra. -/
theorem RingHom.finite_localizationPreserves : RingHom.LocalizationPreserves @RingHom.Finite := by
introv R hf
letI := f.toAlgebra
letI := ((algebraMap S S').comp f).toAlgebra
let f' : R' →+* S' := IsLocalization.map S' f (Submonoid.le_comap_map M)
letI := f'.toAlgebra
have : IsScalarTower R R' S' := IsScalarTower.of_algebraMap_eq'
(IsLocalization.map_comp M.le_comap_map).symm
have : IsScalarTower R S S' := IsScalarTower.of_algebraMap_eq' rfl
have : IsLocalization (Algebra.algebraMapSubmonoid S M) S' := by
rwa [Algebra.algebraMapSubmonoid, RingHom.algebraMap_toAlgebra]
have : Module.Finite R S := hf
exact .of_isLocalization R S M
theorem RingHom.localization_away_map_finite (R S R' S' : Type u) [CommRing R] [CommRing S]
[CommRing R'] [CommRing S'] [Algebra R R'] (f : R →+* S) [Algebra S S']
(r : R) [IsLocalization.Away r R']
[IsLocalization.Away (f r) S'] (hf : f.Finite) : (IsLocalization.Away.map R' S' f r).Finite :=
finite_localizationPreserves.away f r _ _ hf
open scoped Classical in
/-- Let `S` be an `R`-algebra, `M` a submonoid of `R`, and `S' = M⁻¹S`.
If the image of some `x : S` falls in the span of some finite `s ⊆ S'` over `R`,
then there exists some `m : M` such that `m • x` falls in the
span of `IsLocalization.finsetIntegerMultiple _ s` over `R`.
-/
theorem IsLocalization.smul_mem_finsetIntegerMultiple_span [Algebra R S] [Algebra R S']
[IsScalarTower R S S'] [IsLocalization (M.map (algebraMap R S)) S'] (x : S) (s : Finset S')
(hx : algebraMap S S' x ∈ Submodule.span R (s : Set S')) :
∃ m : M, m • x ∈
Submodule.span R
(IsLocalization.finsetIntegerMultiple (M.map (algebraMap R S)) s : Set S) := by
let g : S →ₐ[R] S' :=
AlgHom.mk' (algebraMap S S') fun c x => by simp [Algebra.algebraMap_eq_smul_one]
have g_apply : ∀ x, g x = algebraMap S S' x := fun _ => rfl
-- We first obtain the `y' ∈ M` such that `s' = y' • s` is falls in the image of `S` in `S'`.
let y := IsLocalization.commonDenomOfFinset (M.map (algebraMap R S)) s
have hx₁ : (y : S) • (s : Set S') = g '' _ :=
(IsLocalization.finsetIntegerMultiple_image _ s).symm
obtain ⟨y', hy', e : algebraMap R S y' = y⟩ := y.prop
have : algebraMap R S y' • (s : Set S') = y' • (s : Set S') := by
simp_rw [Algebra.algebraMap_eq_smul_one, smul_assoc, one_smul]
rw [← e, this] at hx₁
replace hx₁ := congr_arg (Submodule.span R) hx₁
rw [Submodule.span_smul] at hx₁
replace hx : _ ∈ y' • Submodule.span R (s : Set S') := Set.smul_mem_smul_set hx
rw [hx₁, ← g_apply, ← map_smul g, g_apply, ← Algebra.linearMap_apply, ← Submodule.map_span]
at hx
-- Since `x` falls in the span of `s` in `S'`, `y' • x : S` falls in the span of `s'` in `S'`.
-- That is, there exists some `x' : S` in the span of `s'` in `S` and `x' = y' • x` in `S'`.
-- Thus `a • (y' • x) = a • x' ∈ span s'` in `S` for some `a ∈ M`.
obtain ⟨x', hx', hx'' : algebraMap _ _ _ = _⟩ := hx
obtain ⟨⟨_, a, ha₁, rfl⟩, ha₂⟩ :=
(IsLocalization.eq_iff_exists (M.map (algebraMap R S)) S').mp hx''
use (⟨a, ha₁⟩ : M) * (⟨y', hy'⟩ : M)
convert (Submodule.span R
(IsLocalization.finsetIntegerMultiple (Submonoid.map (algebraMap R S) M) s : Set S)).smul_mem
a hx' using 1
convert ha₂.symm using 1
· rw [Subtype.coe_mk, Submonoid.smul_def, Submonoid.coe_mul, ← smul_smul]
exact Algebra.smul_def _ _
· exact Algebra.smul_def _ _
/-- If `M` is an `R' = S⁻¹R` module, and `x ∈ span R' s`,
then `t • x ∈ span R s` for some `t : S`. -/
theorem multiple_mem_span_of_mem_localization_span
{N : Type*} [AddCommMonoid N] [Module R N] [Module R' N]
[IsScalarTower R R' N] [IsLocalization M R'] (s : Set N) (x : N)
(hx : x ∈ Submodule.span R' s) : ∃ (t : M), t • x ∈ Submodule.span R s := by
classical
obtain ⟨s', hss', hs'⟩ := Submodule.mem_span_finite_of_mem_span hx
rsuffices ⟨t, ht⟩ : ∃ t : M, t • x ∈ Submodule.span R (s' : Set N)
· exact ⟨t, Submodule.span_mono hss' ht⟩
clear hx hss' s
induction s' using Finset.induction_on generalizing x with
| empty => use 1; simpa using hs'
| insert a s _ hs =>
simp only [Finset.coe_insert,
Submodule.mem_span_insert] at hs' ⊢
rcases hs' with ⟨y, z, hz, rfl⟩
rcases IsLocalization.surj M y with ⟨⟨y', s'⟩, e⟩
apply congrArg (fun x ↦ x • a) at e
simp only [algebraMap_smul] at e
rcases hs _ hz with ⟨t, ht⟩
refine ⟨t * s', t * y', _, (Submodule.span R (s : Set N)).smul_mem s' ht, ?_⟩
rw [smul_add, ← smul_smul, mul_comm, ← smul_smul, ← smul_smul, ← e, mul_comm, ← Algebra.smul_def]
simp [Submonoid.smul_def]
/-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ adjoin R' s`,
then `t • x ∈ adjoin R s` for some `t : M`. -/
theorem multiple_mem_adjoin_of_mem_localization_adjoin [Algebra R' S] [Algebra R S]
[IsScalarTower R R' S] [IsLocalization M R'] (s : Set S) (x : S)
(hx : x ∈ Algebra.adjoin R' s) : ∃ t : M, t • x ∈ Algebra.adjoin R s := by
change ∃ t : M, t • x ∈ Subalgebra.toSubmodule (Algebra.adjoin R s)
change x ∈ Subalgebra.toSubmodule (Algebra.adjoin R' s) at hx
simp_rw [Algebra.adjoin_eq_span] at hx ⊢
exact multiple_mem_span_of_mem_localization_span M R' _ _ hx
/-- `S` is a finite `R`-algebra if there exists a set `{ r }` that
spans `R` such that `Sᵣ` is a finite `Rᵣ`-algebra. -/
theorem RingHom.finite_ofLocalizationSpan : RingHom.OfLocalizationSpan @RingHom.Finite := by
classical
rw [RingHom.ofLocalizationSpan_iff_finite]
introv R hs H
-- We first setup the instances
letI := f.toAlgebra
letI := fun r : s => (Localization.awayMap f r).toAlgebra
have : ∀ r : s,
IsLocalization ((Submonoid.powers (r : R)).map (algebraMap R S)) (Localization.Away (f r)) :=
by intro r; rw [Submonoid.map_powers]; exact Localization.isLocalization
haveI : ∀ r : s, IsScalarTower R (Localization.Away (r : R)) (Localization.Away (f r)) :=
fun r => IsScalarTower.of_algebraMap_eq'
(IsLocalization.map_comp (Submonoid.powers (r : R)).le_comap_map).symm
-- By the hypothesis, we may find a finite generating set for each `Sᵣ`. This set can then be
-- lifted into `R` by multiplying a sufficiently large power of `r`. I claim that the union of
-- these generates `S`.
constructor
replace H := fun r => (H r).1
choose s₁ s₂ using H
let sf := fun x : s => IsLocalization.finsetIntegerMultiple (Submonoid.powers (f x)) (s₁ x)
use s.attach.biUnion sf
rw [Submodule.span_attach_biUnion, eq_top_iff]
-- It suffices to show that `r ^ n • x ∈ span T` for each `r : s`, since `{ r ^ n }` spans `R`.
-- This then follows from the fact that each `x : R` is a linear combination of the generating set
-- of `Sᵣ`. By multiplying a sufficiently large power of `r`, we can cancel out the `r`s in the
-- denominators of both the generating set and the coefficients.
rintro x -
apply Submodule.mem_of_span_eq_top_of_smul_pow_mem _ (s : Set R) hs _ _
intro r
obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ :=
multiple_mem_span_of_mem_localization_span (Submonoid.powers (r : R))
(Localization.Away (r : R)) (s₁ r : Set (Localization.Away (f r))) (algebraMap S _ x)
(by rw [s₂ r]; trivial)
dsimp only at hn₁
rw [Submonoid.smul_def, Algebra.smul_def, IsScalarTower.algebraMap_apply R S, ← map_mul] at hn₁
obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ :=
IsLocalization.smul_mem_finsetIntegerMultiple_span (Submonoid.powers (r : R))
(Localization.Away (f r)) _ (s₁ r) hn₁
rw [Submonoid.smul_def, ← Algebra.smul_def, smul_smul, ← pow_add] at hn₂
simp_rw [Submonoid.map_powers] at hn₂
use n₂ + n₁
exact le_iSup (fun x : s => Submodule.span R (sf x : Set S)) r hn₂
instance {R S : Type*} [CommRing R] {P : Ideal R} [CommRing S] [Algebra R S]
[Module.Finite R S] [P.IsPrime] :
Module.Finite (Localization.AtPrime P)
(Localization (Algebra.algebraMapSubmonoid S P.primeCompl)) :=
.of_isLocalization R S P.primeCompl
|
mxabelem.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path.
From mathcomp Require Import div choice fintype tuple finfun bigop prime.
From mathcomp Require Import ssralg poly finset fingroup morphism perm.
From mathcomp Require Import automorphism quotient gproduct action finalg.
From mathcomp Require Import zmodp commutator cyclic center pgroup gseries.
From mathcomp Require Import nilpotent sylow maximal abelian matrix.
From mathcomp Require Import mxalgebra mxrepresentation.
(******************************************************************************)
(* This file completes the theory developed in mxrepresentation.v with the *)
(* construction and properties of linear representations over finite fields, *)
(* and in particular the correspondence between internal action on a (normal) *)
(* elementary abelian p-subgroup and a linear representation on an Fp-module. *)
(* We provide the following next constructions for a finite field F: *)
(* 'Zm%act == the action of {unit F} on 'M[F]_(m, n). *)
(* rowg A == the additive group of 'rV[F]_n spanned by the row space *)
(* of the matrix A. *)
(* rowg_mx L == the partial inverse to rowg; for any 'Zm-stable group L *)
(* of 'rV[F]_n we have rowg (rowg_mx L) = L. *)
(* GLrepr F n == the natural, faithful representation of 'GL_n[F]. *)
(* reprGLm rG == the morphism G >-> 'GL_n[F] equivalent to the *)
(* representation r of G (with rG : mx_repr r G). *)
(* ('MR rG)%act == the action of G on 'rV[F]_n equivalent to the *)
(* representation r of G (with rG : mx_repr r G). *)
(* The second set of constructions defines the interpretation of a normal *)
(* non-trivial elementary abelian p-subgroup as an 'F_p module. We assume *)
(* abelE : p.-abelem E and ntE : E != 1, throughout, as these are needed to *)
(* build the isomorphism between E and a nontrivial 'rV['F_p]_n. *)
(* 'rV(E) == the type of row vectors of the 'F_p module equivalent *)
(* to E when E is a non-trivial p.-abelem group. *)
(* 'M(E) == the type of matrices corresponding to E. *)
(* 'dim E == the width of vectors/matrices in 'rV(E) / 'M(E). *)
(* abelem_rV abelE ntE == the one-to-one injection of E onto 'rV(E). *)
(* rVabelem abelE ntE == the one-to-one projection of 'rV(E) onto E. *)
(* abelem_repr abelE ntE nEG == the representation of G on 'rV(E) that is *)
(* equivalent to conjugation by G in E; here abelE, ntE are *)
(* as above, and G \subset 'N(E). *)
(* This file end with basic results on p-modular representations of p-groups, *)
(* and theorems giving the structure of the representation of extraspecial *)
(* groups; these results use somewhat more advanced group theory than the *)
(* rest of mxrepresentation, in particular, results of sylow.v and maximal.v. *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Declare Scope abelem_scope.
Import GroupScope GRing.Theory FinRing.Theory.
Local Open Scope ring_scope.
(* Special results for representations on a finite field. In this case, the *)
(* representation is equivalent to a morphism into the general linear group *)
(* 'GL_n[F]. It is furthermore equivalent to a group action on the finite *)
(* additive group of the corresponding row space 'rV_n. In addition, row *)
(* spaces of matrices in 'M[F]_n correspond to subgroups of that vector group *)
(* (this is only surjective when F is a prime field 'F_p), with moduleules *)
(* corresponding to subgroups stabilized by the external action. *)
Section FinNzRingRepr.
Variable (R : finComUnitRingType) (gT : finGroupType).
Variables (G : {group gT}) (n : nat) (rG : mx_representation R G n).
Definition mx_repr_act (u : 'rV_n) x := u *m rG (val (subg G x)).
Lemma mx_repr_actE u x : x \in G -> mx_repr_act u x = u *m rG x.
Proof. by move=> Gx; rewrite /mx_repr_act /= subgK. Qed.
Fact mx_repr_is_action : is_action G mx_repr_act.
Proof.
split=> [x | u x y Gx Gy]; first exact: can_inj (repr_mxK _ (subgP _)).
by rewrite !mx_repr_actE ?groupM // -mulmxA repr_mxM.
Qed.
Canonical Structure mx_repr_action := Action mx_repr_is_action.
Fact mx_repr_is_groupAction : is_groupAction [set: 'rV[R]_n] mx_repr_action.
Proof.
move=> x Gx /[!inE]; apply/andP; split; first by apply/subsetP=> u /[!inE].
by apply/morphicP=> /= u v _ _; rewrite !actpermE /= /mx_repr_act mulmxDl.
Qed.
Canonical Structure mx_repr_groupAction := GroupAction mx_repr_is_groupAction.
End FinNzRingRepr.
Notation "''MR' rG" := (mx_repr_action rG)
(at level 10, rG at level 8) : action_scope.
Notation "''MR' rG" := (mx_repr_groupAction rG) : groupAction_scope.
Section FinFieldRepr.
Variable F : finFieldType.
(* The external group action (by scaling) of the multiplicative unit group *)
(* of the finite field, and the correspondence between additive subgroups *)
(* of row vectors that are stable by this action, and the matrix row spaces. *)
Section ScaleAction.
Variables m n : nat.
Definition scale_act (A : 'M[F]_(m, n)) (a : {unit F}) := val a *: A.
Lemma scale_actE A a : scale_act A a = val a *: A. Proof. by []. Qed.
Fact scale_is_action : is_action setT scale_act.
Proof.
apply: is_total_action=> [A | A a b]; rewrite /scale_act ?scale1r //.
by rewrite ?scalerA mulrC.
Qed.
Canonical scale_action := Action scale_is_action.
Fact scale_is_groupAction : is_groupAction setT scale_action.
Proof.
move=> a _ /[1!inE]; apply/andP; split; first by apply/subsetP=> A /[!inE].
by apply/morphicP=> u A _ _ /=; rewrite !actpermE /= /scale_act scalerDr.
Qed.
Canonical scale_groupAction := GroupAction scale_is_groupAction.
Lemma astab1_scale_act A : A != 0 -> 'C[A | scale_action] = 1%g.
Proof.
rewrite -mxrank_eq0=> nzA; apply/trivgP/subsetP=> a; apply: contraLR.
rewrite !inE -val_eqE -subr_eq0 sub1set !inE => nz_a1.
by rewrite -subr_eq0 -scaleN1r -scalerDl -mxrank_eq0 eqmx_scale.
Qed.
End ScaleAction.
Local Notation "'Zm" := (scale_action _ _) : action_scope.
Section RowGroup.
Variable n : nat.
Local Notation rVn := 'rV[F]_n.
Definition rowg m (A : 'M[F]_(m, n)) : {set rVn} := [set u | u <= A]%MS.
Lemma mem_rowg m A v : (v \in @rowg m A) = (v <= A)%MS.
Proof. by rewrite inE. Qed.
Fact rowg_group_set m A : group_set (@rowg m A).
Proof.
by apply/group_setP; split=> [|u v]; rewrite !inE ?sub0mx //; apply: addmx_sub.
Qed.
Canonical rowg_group m A := Group (@rowg_group_set m A).
Lemma rowg_stable m (A : 'M_(m, n)) : [acts setT, on rowg A | 'Zm].
Proof. by apply/actsP=> a _ v; rewrite !inE eqmx_scale // -unitfE (valP a). Qed.
Lemma rowgS m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :
(rowg A \subset rowg B) = (A <= B)%MS.
Proof.
apply/subsetP/idP=> sAB => [|u /[!inE] suA]; last exact: submx_trans sAB.
by apply/row_subP=> i; have /[!(inE, row_sub)]-> := sAB (row i A).
Qed.
Lemma eq_rowg m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :
(A :=: B)%MS -> rowg A = rowg B.
Proof. by move=> eqAB; apply/eqP; rewrite eqEsubset !rowgS !eqAB andbb. Qed.
Lemma rowg0 m : rowg (0 : 'M_(m, n)) = 1%g.
Proof. by apply/trivgP/subsetP=> v; rewrite !inE eqmx0 submx0. Qed.
Lemma rowg1 : rowg 1%:M = setT.
Proof. by apply/setP=> x; rewrite !inE submx1. Qed.
Lemma trivg_rowg m (A : 'M_(m, n)) : (rowg A == 1%g) = (A == 0).
Proof. by rewrite -submx0 -rowgS rowg0 (sameP trivgP eqP). Qed.
Definition rowg_mx (L : {set rVn}) := <<\matrix_(i < #|L|) enum_val i>>%MS.
Lemma rowgK m (A : 'M_(m, n)) : (rowg_mx (rowg A) :=: A)%MS.
Proof.
apply/eqmxP; rewrite !genmxE; apply/andP; split.
by apply/row_subP=> i; rewrite rowK; have /[!inE] := enum_valP i.
apply/row_subP=> i; set v := row i A.
have Av: v \in rowg A by rewrite inE row_sub.
by rewrite (eq_row_sub (enum_rank_in Av v)) // rowK enum_rankK_in.
Qed.
Lemma rowg_mxS (L M : {set 'rV[F]_n}) :
L \subset M -> (rowg_mx L <= rowg_mx M)%MS.
Proof.
move/subsetP=> sLM; rewrite !genmxE; apply/row_subP=> i.
rewrite rowK; move: (enum_val i) (sLM _ (enum_valP i)) => v Mv.
by rewrite (eq_row_sub (enum_rank_in Mv v)) // rowK enum_rankK_in.
Qed.
Lemma sub_rowg_mx (L : {set rVn}) : L \subset rowg (rowg_mx L).
Proof.
apply/subsetP=> v Lv; rewrite inE genmxE.
by rewrite (eq_row_sub (enum_rank_in Lv v)) // rowK enum_rankK_in.
Qed.
Lemma stable_rowg_mxK (L : {group rVn}) :
[acts setT, on L | 'Zm] -> rowg (rowg_mx L) = L.
Proof.
move=> linL; apply/eqP; rewrite eqEsubset sub_rowg_mx andbT.
apply/subsetP=> v; rewrite inE genmxE => /submxP[u ->{v}].
rewrite mulmx_sum_row group_prod // => i _.
rewrite rowK; move: (enum_val i) (enum_valP i) => v Lv.
have [->|] := eqVneq (u 0 i) 0; first by rewrite scale0r group1.
by rewrite -unitfE => aP; rewrite ((actsP linL) (FinRing.Unit aP)) ?inE.
Qed.
Lemma rowg_mx1 : rowg_mx 1%g = 0.
Proof. by apply/eqP; rewrite -submx0 -(rowg0 0) rowgK sub0mx. Qed.
Lemma rowg_mx_eq0 (L : {group rVn}) : (rowg_mx L == 0) = (L :==: 1%g).
Proof.
rewrite -trivg_rowg; apply/idP/eqP=> [|->]; last by rewrite rowg_mx1 rowg0.
exact/contraTeq/subG1_contra/sub_rowg_mx.
Qed.
Lemma rowgI m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :
rowg (A :&: B)%MS = rowg A :&: rowg B.
Proof. by apply/setP=> u; rewrite !inE sub_capmx. Qed.
Lemma card_rowg m (A : 'M_(m, n)) : #|rowg A| = (#|F| ^ \rank A)%N.
Proof.
rewrite -[\rank A]mul1n -card_mx.
have injA: injective (mulmxr (row_base A)).
have /row_freeP[A' A'K] := row_base_free A.
by move=> ?; apply: can_inj (mulmxr A') _ => u; rewrite /= -mulmxA A'K mulmx1.
rewrite -(card_image (injA _)); apply: eq_card => v.
by rewrite inE -(eq_row_base A) (sameP submxP codomP).
Qed.
Lemma rowgD m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :
rowg (A + B)%MS = (rowg A * rowg B)%g.
Proof.
apply/eqP; rewrite eq_sym eqEcard mulG_subG /= !rowgS.
rewrite addsmxSl addsmxSr -(@leq_pmul2r #|rowg A :&: rowg B|) ?cardG_gt0 //=.
by rewrite -mul_cardG -rowgI !card_rowg -!expnD mxrank_sum_cap.
Qed.
Lemma cprod_rowg m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :
(rowg A \* rowg B)%g = rowg (A + B)%MS.
Proof. by rewrite rowgD cprodE // (sub_abelian_cent2 (zmod_abelian setT)). Qed.
Lemma dprod_rowg m1 m2 (A : 'M[F]_(m1, n)) (B : 'M[F]_(m2, n)) :
mxdirect (A + B) -> rowg A \x rowg B = rowg (A + B)%MS.
Proof.
rewrite (sameP mxdirect_addsP eqP) -trivg_rowg rowgI => /eqP tiAB.
by rewrite -cprod_rowg dprodEcp.
Qed.
Lemma bigcprod_rowg m I r (P : pred I) (A : I -> 'M[F]_n) (B : 'M[F]_(m, n)) :
(\sum_(i <- r | P i) A i :=: B)%MS ->
\big[cprod/1%g]_(i <- r | P i) rowg (A i) = rowg B.
Proof.
by move/eq_rowg <-; apply/esym/big_morph=> [? ?|]; rewrite (rowg0, cprod_rowg).
Qed.
Lemma bigdprod_rowg m (I : finType) (P : pred I) A (B : 'M[F]_(m, n)) :
let S := (\sum_(i | P i) A i)%MS in (S :=: B)%MS -> mxdirect S ->
\big[dprod/1%g]_(i | P i) rowg (A i) = rowg B.
Proof.
move=> S defS; rewrite mxdirectE defS /= => /eqP rankB.
apply: bigcprod_card_dprod (bigcprod_rowg defS) (eq_leq _).
by rewrite card_rowg rankB expn_sum; apply: eq_bigr => i; rewrite card_rowg.
Qed.
End RowGroup.
Variables (gT : finGroupType) (G : {group gT}) (n' : nat).
Local Notation n := n'.+1.
Variable (rG : mx_representation F G n).
Fact GL_mx_repr : mx_repr 'GL_n[F] GLval. Proof. by []. Qed.
Canonical GLrepr := MxRepresentation GL_mx_repr.
Lemma GLmx_faithful : mx_faithful GLrepr.
Proof. by apply/subsetP=> A; rewrite !inE mul1mx. Qed.
Definition reprGLm x : {'GL_n[F]} := insubd (1%g : {'GL_n[F]}) (rG x).
Lemma val_reprGLm x : x \in G -> val (reprGLm x) = rG x.
Proof. by move=> Gx; rewrite val_insubd (repr_mx_unitr rG). Qed.
Lemma comp_reprGLm : {in G, GLval \o reprGLm =1 rG}.
Proof. exact: val_reprGLm. Qed.
Lemma reprGLmM : {in G &, {morph reprGLm : x y / x * y}}%g.
Proof.
by move=> x y Gx Gy; apply: val_inj; rewrite /= !val_reprGLm ?groupM ?repr_mxM.
Qed.
Canonical reprGL_morphism := Morphism reprGLmM.
Lemma ker_reprGLm : 'ker reprGLm = rker rG.
Proof.
apply/setP=> x; rewrite !inE mul1mx; apply: andb_id2l => Gx.
by rewrite -val_eqE val_reprGLm.
Qed.
Lemma astab_rowg_repr m (A : 'M_(m, n)) : 'C(rowg A | 'MR rG) = rstab rG A.
Proof.
apply/setP=> x /[!inE]/=; apply: andb_id2l => Gx.
apply/subsetP/eqP=> cAx => [|u]; last first.
by rewrite !inE mx_repr_actE // => /submxP[u' ->]; rewrite -mulmxA cAx.
apply/row_matrixP=> i; apply/eqP; move/implyP: (cAx (row i A)).
by rewrite !inE row_sub mx_repr_actE //= row_mul.
Qed.
Lemma astabs_rowg_repr m (A : 'M_(m, n)) : 'N(rowg A | 'MR rG) = rstabs rG A.
Proof.
apply/setP=> x /[!inE]/=; apply: andb_id2l => Gx.
apply/subsetP/idP=> nAx => [|u]; last first.
by rewrite !inE mx_repr_actE // => Au; apply: (submx_trans (submxMr _ Au)).
apply/row_subP=> i; move/implyP: (nAx (row i A)).
by rewrite !inE row_sub mx_repr_actE //= row_mul.
Qed.
Lemma acts_rowg (A : 'M_n) : [acts G, on rowg A | 'MR rG] = mxmodule rG A.
Proof. by rewrite astabs_rowg_repr. Qed.
Lemma astab_setT_repr : 'C(setT | 'MR rG) = rker rG.
Proof. by rewrite -rowg1 astab_rowg_repr. Qed.
Lemma mx_repr_action_faithful :
[faithful G, on setT | 'MR rG] = mx_faithful rG.
Proof.
by rewrite /faithful astab_setT_repr (setIidPr _) // [rker _]setIdE subsetIl.
Qed.
Lemma afix_repr (H : {set gT}) :
H \subset G -> 'Fix_('MR rG)(H) = rowg (rfix_mx rG H).
Proof.
move/subsetP=> sHG; apply/setP=> /= u; rewrite !inE.
apply/subsetP/rfix_mxP=> cHu x Hx; have:= cHu x Hx;
by rewrite !inE /= => /eqP; rewrite mx_repr_actE ?sHG.
Qed.
Lemma gacent_repr (H : {set gT}) :
H \subset G -> 'C_(| 'MR rG)(H) = rowg (rfix_mx rG H).
Proof. by move=> sHG; rewrite gacentE // setTI afix_repr. Qed.
End FinFieldRepr.
Arguments rowg_mx {F n%_N} L%_g.
Notation "''Zm'" := (scale_action _ _ _) : action_scope.
Notation "''Zm'" := (scale_groupAction _ _ _) : groupAction_scope.
Section MatrixGroups.
Implicit Types m n p q : nat.
Lemma exponent_mx_group m n q :
m > 0 -> n > 0 -> q > 1 -> exponent [set: 'M['Z_q]_(m, n)] = q.
Proof.
move=> m_gt0 n_gt0 q_gt1; apply/eqP; rewrite eqn_dvd; apply/andP; split.
apply/exponentP=> x _; apply/matrixP=> i j; rewrite mulmxnE !mxE.
by rewrite -mulr_natr -Zp_nat_mod // modnn mulr0.
pose cmx1 := const_mx 1%R : 'M['Z_q]_(m, n).
apply: dvdn_trans (dvdn_exponent (in_setT cmx1)).
have/matrixP/(_ (Ordinal m_gt0))/(_ (Ordinal n_gt0))/eqP := expg_order cmx1.
by rewrite mulmxnE !mxE -order_dvdn order_Zp1 Zp_cast.
Qed.
Lemma rank_mx_group m n q : 'r([set: 'M['Z_q]_(m, n)]) = (m * n)%N.
Proof.
wlog q_gt1: q / q > 1 by case: q => [|[|q -> //]] /(_ 2)->.
set G := setT; have cGG: abelian G := zmod_abelian _.
have [mn0 | ] := posnP (m * n).
by rewrite [G](card1_trivg _) ?rank1 // cardsT card_mx mn0.
rewrite muln_gt0 => /andP[m_gt0 n_gt0].
have expG: exponent G = q := exponent_mx_group m_gt0 n_gt0 q_gt1.
apply/eqP; rewrite eqn_leq andbC -(leq_exp2l _ _ q_gt1) -{2}expG.
have ->: (q ^ (m * n))%N = #|G| by rewrite cardsT card_mx card_ord Zp_cast.
rewrite max_card_abelian //= -grank_abelian //= -/G.
pose B : {set 'M['Z_q]_(m, n)} := [set delta_mx ij.1 ij.2 | ij : 'I_m * 'I_n].
suffices ->: G = <<B>>.
have ->: (m * n)%N = #|{: 'I_m * 'I_n}| by rewrite card_prod !card_ord.
exact: leq_trans (grank_min _) (leq_imset_card _ _).
apply/setP=> v; rewrite inE (matrix_sum_delta v).
rewrite group_prod // => i _; rewrite group_prod // => j _.
rewrite -[v i j]natr_Zp scaler_nat groupX // mem_gen //.
by apply/imsetP; exists (i, j).
Qed.
Lemma mx_group_homocyclic m n q : homocyclic [set: 'M['Z_q]_(m, n)].
Proof.
wlog q_gt1: q / q > 1 by case: q => [|[|q -> //]] /(_ 2)->.
set G := setT; have cGG: abelian G := zmod_abelian _.
rewrite -max_card_abelian //= rank_mx_group cardsT card_mx card_ord -/G.
rewrite {1}Zp_cast //; have [-> // | ] := posnP (m * n).
by rewrite muln_gt0 => /andP[m_gt0 n_gt0]; rewrite exponent_mx_group.
Qed.
Lemma abelian_type_mx_group m n q :
q > 1 -> abelian_type [set: 'M['Z_q]_(m, n)] = nseq (m * n) q.
Proof.
rewrite (abelian_type_homocyclic (mx_group_homocyclic m n q)) rank_mx_group.
have [-> // | ] := posnP (m * n); rewrite muln_gt0 => /andP[m_gt0 n_gt0] q_gt1.
by rewrite exponent_mx_group.
Qed.
End MatrixGroups.
Delimit Scope abelem_scope with Mg.
Open Scope abelem_scope.
Definition abelem_dim' (gT : finGroupType) (E : {set gT}) :=
(logn (pdiv #|E|) #|E|).-1.
Arguments abelem_dim' {gT} E%_g.
Notation "''dim' E" := (abelem_dim' E).+1
(at level 10, E at level 8, format "''dim' E") : abelem_scope.
Notation "''rV' ( E )" := 'rV_('dim E) (format "''rV' ( E )") : abelem_scope.
Notation "''M' ( E )" := 'M_('dim E) (format "''M' ( E )") : abelem_scope.
Notation "''rV[' F ] ( E )" := 'rV[F]_('dim E) (only parsing) : abelem_scope.
Notation "''M[' F ] ( E )" := 'M[F]_('dim E) (only parsing) : abelem_scope.
Section AbelemRepr.
Section FpMatrix.
Variables p m n : nat.
Local Notation Mmn := 'M['F_p]_(m, n).
Lemma mx_Fp_abelem : prime p -> p.-abelem [set: Mmn].
Proof. exact: fin_Fp_lmod_abelem. Qed.
Lemma mx_Fp_stable (L : {group Mmn}) : [acts setT, on L | 'Zm].
Proof.
apply/subsetP=> a _ /[!inE]; apply/subsetP=> A L_A.
by rewrite inE /= /scale_act -[val _]natr_Zp scaler_nat groupX.
Qed.
End FpMatrix.
Section FpRow.
Variables p n : nat.
Local Notation rVn := 'rV['F_p]_n.
Lemma rowg_mxK (L : {group rVn}) : rowg (rowg_mx L) = L.
Proof. by apply: stable_rowg_mxK; apply: mx_Fp_stable. Qed.
Lemma rowg_mxSK (L : {set rVn}) (M : {group rVn}) :
(rowg_mx L <= rowg_mx M)%MS = (L \subset M).
Proof.
apply/idP/idP; last exact: rowg_mxS.
by rewrite -rowgS rowg_mxK; apply/subset_trans/sub_rowg_mx.
Qed.
Lemma mxrank_rowg (L : {group rVn}) :
prime p -> \rank (rowg_mx L) = logn p #|L|.
Proof.
by move=> p_pr; rewrite -{2}(rowg_mxK L) card_rowg card_Fp ?pfactorK.
Qed.
End FpRow.
Variables (p : nat) (gT : finGroupType) (E : {group gT}).
Hypotheses (abelE : p.-abelem E) (ntE : E :!=: 1%g).
Let pE : p.-group E := abelem_pgroup abelE.
Let p_pr : prime p. Proof. by have [] := pgroup_pdiv pE ntE. Qed.
Local Notation n' := (abelem_dim' (gval E)).
Local Notation n := n'.+1.
Local Notation rVn := 'rV['F_p](gval E).
Lemma dim_abelemE : n = logn p #|E|.
Proof.
rewrite /n'; have [_ _ [k ->]] := pgroup_pdiv pE ntE.
by rewrite /pdiv primesX ?primes_prime // pfactorK.
Qed.
Lemma card_abelem_rV : #|rVn| = #|E|.
Proof.
by rewrite dim_abelemE card_mx mul1n card_Fp // -p_part part_pnat_id.
Qed.
Lemma isog_abelem_rV : E \isog [set: rVn].
Proof.
by rewrite (isog_abelem_card _ abelE) cardsT card_abelem_rV mx_Fp_abelem /=.
Qed.
Local Notation ab_rV_P := (existsP isog_abelem_rV).
Definition abelem_rV : gT -> rVn := xchoose ab_rV_P.
Local Notation ErV := abelem_rV.
Lemma abelem_rV_M : {in E &, {morph ErV : x y / (x * y)%g >-> x + y}}.
Proof. by case/misomP: (xchooseP ab_rV_P) => fM _; move/morphicP: fM. Qed.
Canonical abelem_rV_morphism := Morphism abelem_rV_M.
Lemma abelem_rV_isom : isom E setT ErV.
Proof. by case/misomP: (xchooseP ab_rV_P). Qed.
Lemma abelem_rV_injm : 'injm ErV. Proof. by case/isomP: abelem_rV_isom. Qed.
Lemma abelem_rV_inj : {in E &, injective ErV}.
Proof. by apply/injmP; apply: abelem_rV_injm. Qed.
Lemma im_abelem_rV : ErV @* E = setT. Proof. by case/isomP: abelem_rV_isom. Qed.
Lemma mem_im_abelem_rV u : u \in ErV @* E.
Proof. by rewrite im_abelem_rV inE. Qed.
Lemma sub_im_abelem_rV mA : subset mA (mem (ErV @* E)).
Proof. by rewrite unlock; apply/pred0P=> v /=; rewrite mem_im_abelem_rV. Qed.
Hint Resolve mem_im_abelem_rV sub_im_abelem_rV : core.
Lemma abelem_rV_1 : ErV 1 = 0%R. Proof. by rewrite morph1. Qed.
Lemma abelem_rV_X x i : x \in E -> ErV (x ^+ i) = i%:R *: ErV x.
Proof. by move=> Ex; rewrite morphX // scaler_nat. Qed.
Lemma abelem_rV_V x : x \in E -> ErV x^-1 = - ErV x.
Proof. by move=> Ex; rewrite morphV. Qed.
Definition rVabelem : rVn -> gT := invm abelem_rV_injm.
Canonical rVabelem_morphism := [morphism of rVabelem].
Local Notation rV_E := rVabelem.
Lemma rVabelem0 : rV_E 0 = 1%g. Proof. exact: morph1. Qed.
Lemma rVabelemD : {morph rV_E : u v / u + v >-> (u * v)%g}.
Proof. by move=> u v /=; rewrite -morphM. Qed.
Lemma rVabelemN : {morph rV_E: u / - u >-> (u^-1)%g}.
Proof. by move=> u /=; rewrite -morphV. Qed.
Lemma rVabelemZ (m : 'F_p) : {morph rV_E : u / m *: u >-> (u ^+ m)%g}.
Proof. by move=> u; rewrite /= -morphX -?[(u ^+ m)%g]scaler_nat ?natr_Zp. Qed.
Lemma abelem_rV_K : {in E, cancel ErV rV_E}. Proof. exact: invmE. Qed.
Lemma rVabelemK : cancel rV_E ErV. Proof. by move=> u; rewrite invmK. Qed.
Lemma rVabelem_inj : injective rV_E. Proof. exact: can_inj rVabelemK. Qed.
Lemma rVabelem_injm : 'injm rV_E. Proof. exact: injm_invm abelem_rV_injm. Qed.
Lemma im_rVabelem : rV_E @* setT = E.
Proof. by rewrite -im_abelem_rV im_invm. Qed.
Lemma mem_rVabelem u : rV_E u \in E.
Proof. by rewrite -im_rVabelem mem_morphim. Qed.
Lemma sub_rVabelem L : rV_E @* L \subset E.
Proof. by rewrite -[_ @* L]morphimIim im_invm subsetIl. Qed.
Hint Resolve mem_rVabelem sub_rVabelem : core.
Lemma card_rVabelem L : #|rV_E @* L| = #|L|.
Proof. by rewrite card_injm ?rVabelem_injm. Qed.
Lemma abelem_rV_mK (H : {set gT}) : H \subset E -> rV_E @* (ErV @* H) = H.
Proof. exact: morphim_invm abelem_rV_injm H. Qed.
Lemma rVabelem_mK L : ErV @* (rV_E @* L) = L.
Proof. by rewrite morphim_invmE morphpreK. Qed.
Lemma rVabelem_minj : injective (morphim (MorPhantom rV_E)).
Proof. exact: can_inj rVabelem_mK. Qed.
Lemma rVabelemS L M : (rV_E @* L \subset rV_E @* M) = (L \subset M).
Proof. by rewrite injmSK ?rVabelem_injm. Qed.
Lemma abelem_rV_S (H K : {set gT}) :
H \subset E -> (ErV @* H \subset ErV @* K) = (H \subset K).
Proof. by move=> sHE; rewrite injmSK ?abelem_rV_injm. Qed.
Lemma sub_rVabelem_im L (H : {set gT}) :
(rV_E @* L \subset H) = (L \subset ErV @* H).
Proof. by rewrite sub_morphim_pre ?morphpre_invm. Qed.
Lemma sub_abelem_rV_im (H : {set gT}) (L : {set 'rV['F_p]_n}) :
H \subset E -> (ErV @* H \subset L) = (H \subset rV_E @* L).
Proof. by move=> sHE; rewrite sub_morphim_pre ?morphim_invmE. Qed.
Section OneGroup.
Variable G : {group gT}.
Definition abelem_mx_fun (g : subg_of G) v := ErV ((rV_E v) ^ val g).
Definition abelem_mx of G \subset 'N(E) :=
fun x => lin1_mx (abelem_mx_fun (subg G x)).
Hypothesis nEG : G \subset 'N(E).
Local Notation r := (abelem_mx nEG).
Fact abelem_mx_linear_proof g : linear (abelem_mx_fun g).
Proof.
rewrite /abelem_mx_fun; case: g => x /= /(subsetP nEG) Nx /= m u v.
rewrite rVabelemD rVabelemZ conjMg conjXg.
by rewrite abelem_rV_M ?abelem_rV_X ?groupX ?memJ_norm // natr_Zp.
Qed.
HB.instance Definition _ (g : [subg G]) :=
GRing.isSemilinear.Build 'F_p rVn rVn _ (abelem_mx_fun g)
(GRing.semilinear_linear (abelem_mx_linear_proof g)).
Let rVabelemJmx v x : x \in G -> rV_E (v *m r x) = (rV_E v) ^ x.
Proof.
move=> Gx; rewrite /= mul_rV_lin1 /= /abelem_mx_fun subgK //.
by rewrite abelem_rV_K // memJ_norm // (subsetP nEG).
Qed.
Fact abelem_mx_repr : mx_repr G r.
Proof.
split=> [|x y Gx Gy]; apply/row_matrixP=> i; apply: rVabelem_inj.
by rewrite rowE -row1 rVabelemJmx // conjg1.
by rewrite !rowE mulmxA !rVabelemJmx ?groupM // conjgM.
Qed.
Canonical abelem_repr := MxRepresentation abelem_mx_repr.
Let rG := abelem_repr.
Lemma rVabelemJ v x : x \in G -> rV_E (v *m rG x) = (rV_E v) ^ x.
Proof. exact: rVabelemJmx. Qed.
Lemma abelem_rV_J : {in E & G, forall x y, ErV (x ^ y) = ErV x *m rG y}.
Proof.
by move=> x y Ex Gy; rewrite -{1}(abelem_rV_K Ex) -rVabelemJ ?rVabelemK.
Qed.
Lemma abelem_rowgJ m (A : 'M_(m, n)) x :
x \in G -> rV_E @* rowg (A *m rG x) = (rV_E @* rowg A) :^ x.
Proof.
move=> Gx; apply: (canRL (conjsgKV _)); apply/setP=> y.
rewrite mem_conjgV !morphim_invmE !inE memJ_norm ?(subsetP nEG) //=.
apply: andb_id2l => Ey; rewrite abelem_rV_J //.
by rewrite submxMfree // row_free_unit (repr_mx_unit rG).
Qed.
Lemma rV_abelem_sJ (L : {group gT}) x :
x \in G -> L \subset E -> ErV @* (L :^ x) = rowg (rowg_mx (ErV @* L) *m rG x).
Proof.
move=> Gx sLE; apply: rVabelem_minj; rewrite abelem_rowgJ //.
by rewrite rowg_mxK !morphim_invm // -(normsP nEG x Gx) conjSg.
Qed.
Lemma rstab_abelem m (A : 'M_(m, n)) : rstab rG A = 'C_G(rV_E @* rowg A).
Proof.
apply/setP=> x /[!inE]/=; apply: andb_id2l => Gx; apply/eqP/centP => cAx.
move=> _ /morphimP[u _ + ->] => /[1!inE] /submxP[{}u ->].
by apply/esym/commgP/conjg_fixP; rewrite -rVabelemJ -?mulmxA ?cAx.
apply/row_matrixP=> i; apply: rVabelem_inj.
by rewrite row_mul rVabelemJ // /conjg -cAx ?mulKg ?mem_morphim // inE row_sub.
Qed.
Lemma rstabs_abelem m (A : 'M_(m, n)) : rstabs rG A = 'N_G(rV_E @* rowg A).
Proof.
apply/setP=> x /[!inE]/=; apply: andb_id2l => Gx.
by rewrite -rowgS -rVabelemS abelem_rowgJ.
Qed.
Lemma rstabs_abelemG (L : {group gT}) :
L \subset E -> rstabs rG (rowg_mx (ErV @* L)) = 'N_G(L).
Proof. by move=> sLE; rewrite rstabs_abelem rowg_mxK morphim_invm. Qed.
Lemma mxmodule_abelem m (U : 'M['F_p]_(m, n)) :
mxmodule rG U = (G \subset 'N(rV_E @* rowg U)).
Proof. by rewrite -subsetIidl -rstabs_abelem. Qed.
Lemma mxmodule_abelemG (L : {group gT}) :
L \subset E -> mxmodule rG (rowg_mx (ErV @* L)) = (G \subset 'N(L)).
Proof. by move=> sLE; rewrite -subsetIidl -rstabs_abelemG. Qed.
Lemma mxsimple_abelemP (U : 'M['F_p]_n) :
reflect (mxsimple rG U) (minnormal (rV_E @* rowg U) G).
Proof.
apply: (iffP mingroupP) => [[/andP[ntU modU] minU] | [modU ntU minU]].
split=> [||V modV sVU ntV]; first by rewrite mxmodule_abelem.
by apply: contraNneq ntU => ->; rewrite /= rowg0 morphim1.
rewrite -rowgS -rVabelemS [_ @* rowg V]minU //.
rewrite -subG1 sub_rVabelem_im morphim1 subG1 trivg_rowg ntV /=.
by rewrite -mxmodule_abelem.
by rewrite rVabelemS rowgS.
split=> [|D /andP[ntD nDG sDU]].
rewrite -subG1 sub_rVabelem_im morphim1 subG1 trivg_rowg ntU /=.
by rewrite -mxmodule_abelem.
apply/eqP; rewrite eqEsubset sDU sub_rVabelem_im /= -rowg_mxSK rowgK.
have sDE: D \subset E := subset_trans sDU (sub_rVabelem _).
rewrite minU ?mxmodule_abelemG //.
by rewrite -rowgS rowg_mxK sub_abelem_rV_im.
by rewrite rowg_mx_eq0 (morphim_injm_eq1 abelem_rV_injm).
Qed.
Lemma mxsimple_abelemGP (L : {group gT}) :
L \subset E -> reflect (mxsimple rG (rowg_mx (ErV @* L))) (minnormal L G).
Proof.
move/abelem_rV_mK=> {2}<-; rewrite -{2}[_ @* L]rowg_mxK.
exact: mxsimple_abelemP.
Qed.
Lemma abelem_mx_irrP : reflect (mx_irreducible rG) (minnormal E G).
Proof.
by rewrite -[E in minnormal E G]im_rVabelem -rowg1; apply: mxsimple_abelemP.
Qed.
Lemma rfix_abelem (H : {set gT}) :
H \subset G -> (rfix_mx rG H :=: rowg_mx (ErV @* 'C_E(H)%g))%MS.
Proof.
move/subsetP=> sHG; apply/eqmxP/andP; split.
rewrite -rowgS rowg_mxK -sub_rVabelem_im // subsetI sub_rVabelem /=.
apply/centsP=> y /morphimP[v _] /[1!inE] cGv ->{y} x Gx.
by apply/commgP/conjg_fixP; rewrite /= -rVabelemJ ?sHG ?(rfix_mxP H _).
rewrite genmxE; apply/rfix_mxP=> x Hx; apply/row_matrixP=> i.
rewrite row_mul rowK; case/morphimP: (enum_valP i) => z Ez /setIP[_ cHz] ->.
by rewrite -abelem_rV_J ?sHG // conjgE (centP cHz) ?mulKg.
Qed.
Lemma rker_abelem : rker rG = 'C_G(E).
Proof. by rewrite /rker rstab_abelem rowg1 im_rVabelem. Qed.
Lemma abelem_mx_faithful : 'C_G(E) = 1%g -> mx_faithful rG.
Proof. by rewrite /mx_faithful rker_abelem => ->. Qed.
End OneGroup.
Section SubGroup.
Variables G H : {group gT}.
Hypotheses (nEG : G \subset 'N(E)) (sHG : H \subset G).
Let nEH := subset_trans sHG nEG.
Local Notation rG := (abelem_repr nEG).
Local Notation rHG := (subg_repr rG sHG).
Local Notation rH := (abelem_repr nEH).
Lemma eq_abelem_subg_repr : {in H, rHG =1 rH}.
Proof.
move=> x Hx; apply/row_matrixP=> i; rewrite !rowE !mul_rV_lin1 /=.
by rewrite /abelem_mx_fun !subgK ?(subsetP sHG).
Qed.
Lemma rsim_abelem_subg : mx_rsim rHG rH.
Proof.
exists 1%:M => [//| |x Hx]; first by rewrite row_free_unit unitmx1.
by rewrite mul1mx mulmx1 eq_abelem_subg_repr.
Qed.
Lemma mxmodule_abelem_subg m (U : 'M_(m, n)) : mxmodule rHG U = mxmodule rH U.
Proof.
apply: eq_subset_r => x.
rewrite [LHS]inE inE; apply: andb_id2l => Hx.
by rewrite eq_abelem_subg_repr.
Qed.
Lemma mxsimple_abelem_subg U : mxsimple rHG U <-> mxsimple rH U.
Proof.
have eq_modH := mxmodule_abelem_subg; rewrite /mxsimple eq_modH.
by split=> [] [-> -> minU]; split=> [//|//|V]; have:= minU V; rewrite eq_modH.
Qed.
End SubGroup.
End AbelemRepr.
Arguments rVabelem_inj {p%_N gT E%_G} abelE ntE [v1%_R v2%_R] : rename.
Section ModularRepresentation.
Variables (F : fieldType) (p : nat) (gT : finGroupType).
Hypothesis pcharFp : p \in [pchar F].
Implicit Types G H : {group gT}.
(* This is Gorenstein, Lemma 2.6.3. *)
Lemma rfix_pgroup_pchar G H n (rG : mx_representation F G n) :
n > 0 -> p.-group H -> H \subset G -> rfix_mx rG H != 0.
Proof.
move=> n_gt0 pH sHG; rewrite -(rfix_subg rG sHG).
move: {2}_.+1 (ltnSn (n + #|H|)) {rG G sHG}(subg_repr _ _) => m.
elim: m gT H pH => // m IHm gT' G pG in n n_gt0 *; rewrite ltnS => le_nG_m rG.
apply/eqP=> Gregular; have irrG: mx_irreducible rG.
apply/mx_irrP; split=> // U modU; rewrite -mxrank_eq0 -lt0n => Unz.
rewrite /row_full eqn_leq rank_leq_col leqNgt; apply/negP=> ltUn.
have: rfix_mx (submod_repr modU) G != 0.
by apply: IHm => //; apply: leq_trans le_nG_m; rewrite ltn_add2r.
by rewrite -mxrank_eq0 (rfix_submod modU) // Gregular capmx0 linear0 mxrank0.
have{m le_nG_m IHm} faithfulG: mx_faithful rG.
apply/trivgP/eqP/idPn; set C := _ rG => ntC.
suffices: rfix_mx (kquo_repr rG) (G / _)%g != 0.
by rewrite -mxrank_eq0 rfix_quo // Gregular mxrank0.
apply: (IHm _ _ (morphim_pgroup _ _)) => //.
by apply: leq_trans le_nG_m; rewrite ltn_add2l ltn_quotient // rstab_sub.
have{Gregular} ntG: G :!=: 1%g.
apply: contraL n_gt0; move/eqP=> G1; rewrite -leqNgt -(mxrank1 F n).
rewrite -(mxrank0 F n n) -Gregular mxrankS //; apply/rfix_mxP=> x.
by rewrite {1}G1 mul1mx => /set1P->; rewrite repr_mx1.
have p_pr: prime p by case/andP: pcharFp.
have{ntG pG} [z]: {z | z \in 'Z(G) & #[z] = p}; last case/setIP=> Gz cGz ozp.
apply: Cauchy => //; apply: contraR ntG; rewrite -p'natE // => p'Z.
have pZ: p.-group 'Z(G) by rewrite (pgroupS (center_sub G)).
by rewrite (trivg_center_pgroup pG (card1_trivg (pnat_1 pZ p'Z))).
have{cGz} cGz1: centgmx rG (rG z - 1%:M).
apply/centgmxP=> x Gx; rewrite mulmxBl mulmxBr mulmx1 mul1mx.
by rewrite -!repr_mxM // (centP cGz).
have{irrG faithfulG cGz1} Urz1: rG z - 1%:M \in unitmx.
apply: (mx_Schur irrG) cGz1 _; rewrite subr_eq0.
move/implyP: (subsetP faithfulG z).
by rewrite !inE Gz mul1mx -order_eq1 ozp -implybNN neq_ltn orbC prime_gt1.
do [case: n n_gt0 => // n' _; set n := n'.+1] in rG Urz1 *.
have pcharMp: p \in [pchar 'M[F]_n].
exact: (rmorph_pchar (@scalar_mx F n)).
have{Urz1}: pFrobenius_aut pcharMp (rG z - 1) \in GRing.unit by rewrite unitrX.
rewrite (pFrobenius_autB_comm _ (commr1 _)) pFrobenius_aut1.
by rewrite -[_ (rG z)](repr_mxX rG) // -ozp expg_order repr_mx1 subrr unitr0.
Qed.
Variables (G : {group gT}) (n : nat) (rG : mx_representation F G n).
Lemma pcore_sub_rstab_mxsimple_pchar M :
mxsimple rG M -> 'O_p(G) \subset rstab rG M.
Proof.
case=> modM nzM simM; have sGpG := pcore_sub p G.
rewrite rfix_mx_rstabC //; set U := rfix_mx _ _.
have:= simM (M :&: U)%MS; rewrite sub_capmx submx_refl.
apply; rewrite ?capmxSl //.
by rewrite capmx_module // normal_rfix_mx_module ?pcore_normal.
rewrite -(in_submodK (capmxSl _ _)) val_submod_eq0 -submx0.
rewrite -(rfix_submod modM) // submx0 rfix_pgroup_pchar ?pcore_pgroup //.
by rewrite lt0n mxrank_eq0.
Qed.
Lemma pcore_sub_rker_mx_irr_pchar :
mx_irreducible rG -> 'O_p(G) \subset rker rG.
Proof. exact: pcore_sub_rstab_mxsimple_pchar. Qed.
(* This is Gorenstein, Lemma 3.1.3. *)
Lemma pcore_faithful_mx_irr_pchar :
mx_irreducible rG -> mx_faithful rG -> 'O_p(G) = 1%g.
Proof.
move=> irrG ffulG; apply/trivgP; apply: subset_trans ffulG.
exact: pcore_sub_rstab_mxsimple_pchar.
Qed.
End ModularRepresentation.
#[deprecated(since="mathcomp 2.4.0", note="Use rfix_pgroup_pchar instead.")]
Notation rfix_pgroup_char := (rfix_pgroup_pchar) (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pcore_sub_rstab_mxsimple_pchar instead.")]
Notation pcore_sub_rstab_mxsimple := (pcore_sub_rstab_mxsimple_pchar) (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pcore_sub_rker_mx_irr_pchar instead.")]
Notation pcore_sub_rker_mx_irr := (pcore_sub_rker_mx_irr_pchar) (only parsing).
#[deprecated(since="mathcomp 2.4.0", note="Use pcore_faithful_mx_irr_pchar instead.")]
Notation pcore_faithful_mx_irr := (pcore_faithful_mx_irr_pchar) (only parsing).
Section Extraspecial.
Variables (F : fieldType) (gT : finGroupType) (S : {group gT}) (p n : nat).
Hypotheses (pS : p.-group S) (esS : extraspecial S).
Hypothesis oSpn : #|S| = (p ^ n.*2.+1)%N.
Hypotheses (splitF : group_splitting_field F S) (F'S : [pchar F]^'.-group S).
Let p_pr := extraspecial_prime pS esS.
Let p_gt0 := prime_gt0 p_pr.
Let p_gt1 := prime_gt1 p_pr.
Let oZp := card_center_extraspecial pS esS.
Let modIp' (i : 'I_p.-1) : (i.+1 %% p = i.+1)%N.
Proof. by case: i => i; rewrite /= -ltnS prednK //; apply: modn_small. Qed.
(* This is Aschbacher (34.9), parts (1)-(4). *)
Theorem extraspecial_repr_structure_pchar (sS : irrType F S) :
[/\ #|linear_irr sS| = (p ^ n.*2)%N,
exists iphi : 'I_p.-1 -> sS, let phi i := irr_repr (iphi i) in
[/\ injective iphi,
codom iphi =i ~: linear_irr sS,
forall i, mx_faithful (phi i),
forall z, z \in 'Z(S)^# ->
exists2 w, primitive_root_of_unity p w
& forall i, phi i z = (w ^+ i.+1)%:M
& forall i, irr_degree (iphi i) = (p ^ n)%N]
& #|sS| = (p ^ n.*2 + p.-1)%N].
Proof.
have [[defPhiS defS'] prZ] := esS; set linS := linear_irr sS.
have nb_lin: #|linS| = (p ^ n.*2)%N.
rewrite card_linear_irr // -divgS ?der_sub //=.
by rewrite oSpn defS' oZp expnS mulKn.
have nb_irr: #|sS| = (p ^ n.*2 + p.-1)%N.
pose Zcl := classes S ::&: 'Z(S).
have cardZcl: #|Zcl| = p.
transitivity #|[set [set z] | z in 'Z(S)]|; last first.
by rewrite card_imset //; apply: set1_inj.
apply: eq_card => zS; apply/setIdP/imsetP=> [[] | [z]].
case/imsetP=> z Sz ->{zS} szSZ.
have Zz: z \in 'Z(S) by rewrite (subsetP szSZ) ?class_refl.
exists z => //; rewrite inE Sz in Zz.
apply/eqP; rewrite eq_sym eqEcard sub1set class_refl cards1.
by rewrite -index_cent1 (setIidPl _) ?indexgg // sub_cent1.
case/setIP=> Sz cSz ->{zS}; rewrite sub1set inE Sz; split=> //.
apply/imsetP; exists z; rewrite //.
apply/eqP; rewrite eqEcard sub1set class_refl cards1.
by rewrite -index_cent1 (setIidPl _) ?indexgg // sub_cent1.
move/eqP: (class_formula S); rewrite (bigID [in Zcl]) /=.
rewrite (eq_bigr (fun _ => 1)) => [|zS]; last first.
case/andP=> _ /setIdP[/imsetP[z Sz ->{zS}] /subsetIP[_ cSzS]].
rewrite (setIidPl _) ?indexgg // sub_cent1 (subsetP cSzS) //.
exact: mem_repr (class_refl S z).
rewrite sum1dep_card setIdE (setIidPr _) 1?cardsE ?cardZcl; last first.
by apply/subsetP=> zS /[!inE] /andP[].
have pn_gt0: p ^ n.*2 > 0 by rewrite expn_gt0 p_gt0.
rewrite card_irr_pchar // oSpn expnS -(prednK pn_gt0) mulnS eqn_add2l.
rewrite (eq_bigr (fun _ => p)) => [|xS]; last first.
case/andP=> SxS; rewrite inE SxS; case/imsetP: SxS => x Sx ->{xS} notZxS.
have [y Sy ->] := repr_class S x; apply: p_maximal_index => //.
apply: cent1_extraspecial_maximal => //; first exact: groupJ.
apply: contra notZxS => Zxy; rewrite -{1}(lcoset_id Sy) class_lcoset.
rewrite ((_ ^: _ =P [set x ^ y])%g _) ?sub1set // eq_sym eqEcard.
rewrite sub1set class_refl cards1 -index_cent1 (setIidPl _) ?indexgg //.
by rewrite sub_cent1; apply: subsetP Zxy; apply: subsetIr.
rewrite sum_nat_cond_const mulnC eqn_pmul2l //; move/eqP <-.
rewrite addSnnS prednK // -cardZcl -[card _](cardsID Zcl) /= addnC.
by congr (_ + _)%N; apply: eq_card => t; rewrite !inE andbC // andbAC andbb.
have fful_nlin i: i \in ~: linS -> mx_faithful (irr_repr i).
rewrite !inE => nlin_phi.
apply/trivgP; apply: (TI_center_nil (pgroup_nil pS) (rker_normal _)).
rewrite setIC; apply: (prime_TIg prZ); rewrite /= -defS' der1_sub_rker //.
exact: socle_irr.
have [i0 nlin_i0]: exists i0, i0 \in ~: linS.
by apply/card_gt0P; rewrite cardsCs setCK nb_irr nb_lin addKn -subn1 subn_gt0.
have [z defZ]: exists z, 'Z(S) = <[z]> by apply/cyclicP; rewrite prime_cyclic.
have Zz: z \in 'Z(S) by [rewrite defZ cycle_id]; have [Sz cSz] := setIP Zz.
have ozp: #[z] = p by rewrite -oZp defZ.
have ntz: z != 1%g by rewrite -order_gt1 ozp.
pose phi := irr_repr i0; have irr_phi: mx_irreducible phi := socle_irr i0.
pose w := irr_mode i0 z.
have phi_z: phi z = w%:M by rewrite /phi irr_center_scalar.
have phi_ze e: phi (z ^+ e)%g = (w ^+ e)%:M.
by rewrite /phi irr_center_scalar ?groupX ?irr_modeX.
have wp1: w ^+ p = 1 by rewrite -irr_modeX // -ozp expg_order irr_mode1.
have injw: {in 'Z(S) &, injective (irr_mode i0)}.
move=> x y Zx Zy /= eq_xy; have [[Sx _] [Sy _]] := (setIP Zx, setIP Zy).
apply: mx_faithful_inj (fful_nlin _ nlin_i0) _ _ Sx Sy _.
by rewrite !{1}irr_center_scalar ?eq_xy; first by split.
have prim_w e: 0 < e < p -> p.-primitive_root (w ^+ e).
case/andP=> e_gt0 lt_e_p; apply/andP; split=> //.
apply/eqfunP=> -[d ltdp] /=; rewrite unity_rootE -exprM.
rewrite -(irr_mode1 i0) -irr_modeX // (inj_in_eq injw) ?groupX ?group1 //.
rewrite -order_dvdn ozp Euclid_dvdM // gtnNdvd //=.
move: ltdp; rewrite leq_eqVlt.
by case: eqP => [-> _ | _ ltd1p]; rewrite (dvdnn, gtnNdvd).
have /cyclicP[a defAutZ]: cyclic (Aut 'Z(S)) by rewrite Aut_prime_cyclic ?ozp.
have phi_unitP (i : 'I_p.-1): (i.+1%:R : 'Z_#[z]) \in GRing.unit.
by rewrite unitZpE ?order_gt1 // ozp prime_coprime // -lt0n !modIp'.
pose ephi i := invm (injm_Zpm a) (Zp_unitm (FinRing.Unit (phi_unitP i))).
pose j : 'Z_#[z] := val (invm (injm_Zp_unitm z) a).
have co_j_p: coprime j p.
rewrite coprime_sym /j; case: (invm _ a) => /=.
by rewrite ozp /GRing.unit /= Zp_cast.
have [alpha Aut_alpha alphaZ] := center_aut_extraspecial pS esS co_j_p.
have alpha_i_z i: ((alpha ^+ ephi i) z = z ^+ i.+1)%g.
transitivity ((a ^+ ephi i) z)%g.
elim: (ephi i : nat) => // e IHe; rewrite !expgS !permM alphaZ //.
have Aut_a: a \in Aut 'Z(S) by rewrite defAutZ cycle_id.
rewrite -{2}[a](invmK (injm_Zp_unitm z)); last by rewrite im_Zp_unitm -defZ.
rewrite /= autE ?cycle_id // -/j /= /cyclem.
rewrite -(autmE (groupX _ Aut_a)) -(autmE (groupX _ Aut_alpha)).
by rewrite !morphX //= !autmE IHe.
rewrite [(a ^+ _)%g](invmK (injm_Zpm a)) /=; last first.
by rewrite im_Zpm -defAutZ defZ Aut_aut.
by rewrite autE ?cycle_id //= val_Zp_nat ozp ?modIp'.
have rphiP i: S :==: autm (groupX (ephi i) Aut_alpha) @* S by rewrite im_autm.
pose rphi i := morphim_repr (eqg_repr phi (rphiP i)) (subxx S).
have rphi_irr i: mx_irreducible (rphi i) by apply/morphim_mx_irr/eqg_mx_irr.
have rphi_fful i: mx_faithful (rphi i).
rewrite /mx_faithful rker_morphim rker_eqg.
by rewrite (trivgP (fful_nlin _ nlin_i0)) morphpreIdom; apply: injm_autm.
have rphi_z i: rphi i z = (w ^+ i.+1)%:M.
by rewrite /rphi [phi]lock /= /morphim_mx autmE alpha_i_z -lock phi_ze.
pose iphi i := irr_comp sS (rphi i); pose phi_ i := irr_repr (iphi i).
have{} phi_ze i e: phi_ i (z ^+ e)%g = (w ^+ (e * i.+1)%N)%:M.
rewrite /phi_ !{1}irr_center_scalar ?groupX ?irr_modeX //.
suffices ->: irr_mode (iphi i) z = w ^+ i.+1 by rewrite mulnC exprM.
have:= mx_rsim_sym (rsim_irr_comp_pchar sS F'S (rphi_irr i)).
case/mx_rsim_def=> B [B' _ homB]; rewrite /irr_mode homB // rphi_z.
rewrite -{1}scalemx1 -scalemxAr -scalemxAl -{1}(repr_mx1 (rphi i)).
by rewrite -homB // repr_mx1 scalemx1 mxE.
have inj_iphi: injective iphi.
move=> i1 i2 eqi12; apply/eqP.
move/eqP: (congr1 (fun i => irr_mode i (z ^+ 1)) eqi12).
rewrite /irr_mode !{1}[irr_repr _ _]phi_ze !{1}mxE !mul1n.
by rewrite (eq_prim_root_expr (prim_w 1 p_gt1)) !modIp'.
have deg_phi i: irr_degree (iphi i) = irr_degree i0.
by case: (rsim_irr_comp_pchar sS F'S (rphi_irr i)).
have im_iphi: codom iphi =i ~: linS.
apply/subset_cardP; last apply/subsetP=> _ /codomP[i ->].
by rewrite card_image // card_ord cardsCs setCK nb_irr nb_lin addKn.
by rewrite !inE /= (deg_phi i) in nlin_i0 *.
split=> //; exists iphi; rewrite -/phi_.
split=> // [i | ze | i].
- have sim_i := rsim_irr_comp_pchar sS F'S (rphi_irr i).
by rewrite -(mx_rsim_faithful sim_i) rphi_fful.
- rewrite {1}defZ 2!inE andbC; case/andP.
case/cyclePmin=> e; rewrite ozp => lt_e_p ->{ze}.
case: (posnP e) => [-> | e_gt0 _]; first by rewrite eqxx.
exists (w ^+ e) => [|i]; first by rewrite prim_w ?e_gt0.
by rewrite phi_ze exprM.
rewrite deg_phi {i}; set d := irr_degree i0.
apply/eqP; move/eqP: (sum_irr_degree_pchar sS F'S splitF).
rewrite (bigID [in linS]) /= -/irr_degree.
rewrite (eq_bigr (fun=> 1)) => [|i]; last by rewrite !inE; move/eqP->.
rewrite sum1_card nb_lin.
rewrite (eq_bigl [in codom iphi]) // => [|i]; last first.
by rewrite -in_setC -im_iphi.
rewrite (eq_bigr (fun=> d ^ 2))%N => [|_ /codomP[i ->]]; last first.
by rewrite deg_phi.
rewrite sum_nat_const card_image // card_ord oSpn (expnS p) -{3}[p]prednK //.
rewrite mulSn eqn_add2l eqn_pmul2l; last by rewrite -ltnS prednK.
by rewrite -muln2 expnM eqn_sqr.
Qed.
(* This is the corolloray of the above that is actually used in the proof of *)
(* B & G, Theorem 2.5. It encapsulates the dependency on a socle of the *)
(* regular representation. *)
Variables (m : nat) (rS : mx_representation F S m) (U : 'M[F]_m).
Hypotheses (simU : mxsimple rS U) (ffulU : rstab rS U == 1%g).
Let sZS := center_sub S.
Let rZ := subg_repr rS sZS.
Lemma faithful_repr_extraspecial_pchar :
\rank U = (p ^ n)%N /\
(forall V, mxsimple rS V -> mx_iso rZ U V -> mx_iso rS U V).
Proof.
suffices IH V: mxsimple rS V -> mx_iso rZ U V ->
[&& \rank U == (p ^ n)%N & mxsimple_iso rS U V].
- split=> [|/= V simV isoUV].
by case/andP: (IH U simU (mx_iso_refl _ _)) => /eqP.
by case/andP: (IH V simV isoUV) => _ /(mxsimple_isoP simU).
move=> simV isoUV; wlog sS: / irrType F S by apply: socle_exists.
have [[_ defS'] prZ] := esS.
have{prZ} ntZ: 'Z(S) :!=: 1%g by case: eqP prZ => // ->; rewrite cards1.
have [_ [iphi]] := extraspecial_repr_structure_pchar sS.
set phi := fun i => _ => [] [inj_phi im_phi _ phiZ dim_phi] _.
have [modU nzU _]:= simU; pose rU := submod_repr modU.
have nlinU: \rank U != 1.
apply/eqP=> /(rker_linear rU); apply/negP; rewrite /rker rstab_submod.
by rewrite (eqmx_rstab _ (val_submod1 _)) (eqP ffulU) defS' subG1.
have irrU: mx_irreducible rU by apply/submod_mx_irr.
have rsimU := rsim_irr_comp_pchar sS F'S irrU.
set iU := irr_comp sS rU in rsimU; have [_ degU _ _]:= rsimU.
have phiUP: iU \in codom iphi by rewrite im_phi !inE -degU.
rewrite degU -(f_iinv phiUP) dim_phi eqxx /=; apply/(mxsimple_isoP simU).
have [modV _ _]:= simV; pose rV := submod_repr modV.
have irrV: mx_irreducible rV by apply/submod_mx_irr.
have rsimV := rsim_irr_comp_pchar sS F'S irrV.
set iV := irr_comp sS rV in rsimV; have [_ degV _ _]:= rsimV.
have phiVP: iV \in codom iphi by rewrite im_phi !inE -degV -(mxrank_iso isoUV).
pose jU := iinv phiUP; pose jV := iinv phiVP.
have [z Zz ntz]:= trivgPn _ ntZ.
have [|w prim_w phi_z] := phiZ z; first by rewrite 2!inE ntz.
suffices eqjUV: jU == jV.
apply/(mx_rsim_iso modU modV); apply: mx_rsim_trans rsimU _.
by rewrite -(f_iinv phiUP) -/jU (eqP eqjUV) f_iinv; apply: mx_rsim_sym.
have rsimUV: mx_rsim (subg_repr (phi jU) sZS) (subg_repr (phi jV) sZS).
have [bU _ bUfree bUhom] := mx_rsim_sym rsimU.
have [bV _ bVfree bVhom] := rsimV.
have modUZ := mxmodule_subg sZS modU; have modVZ := mxmodule_subg sZS modV.
case/(mx_rsim_iso modUZ modVZ): isoUV => [bZ degZ bZfree bZhom].
rewrite /phi !f_iinv; exists (bU *m bZ *m bV)=> [||x Zx].
- by rewrite -degU degZ degV.
- by rewrite /row_free !mxrankMfree.
have Sx := subsetP sZS x Zx.
rewrite 2!mulmxA bUhom // -(mulmxA _ _ bZ) bZhom //.
by rewrite -!(mulmxA bU) -!(mulmxA bZ) bVhom.
have{rsimUV} [B [B' _ homB]] := mx_rsim_def rsimUV.
have:= eqxx (irr_mode (iphi jU) z); rewrite /irr_mode; set i0 := Ordinal _.
rewrite {2}[_ z]homB // ![_ z]phi_z mxE mulr1n -scalemx1 -scalemxAr -scalemxAl.
rewrite -(repr_mx1 (subg_repr (phi jV) sZS)) -{B B'}homB // repr_mx1 scalemx1.
by rewrite mxE (eq_prim_root_expr prim_w) !modIp'.
Qed.
End Extraspecial.
#[deprecated(since="mathcomp 2.4.0",
note="Use extraspecial_repr_structure_pchar instead.")]
Notation extraspecial_repr_structure := (extraspecial_repr_structure_pchar)
(only parsing).
#[deprecated(since="mathcomp 2.4.0",
note="Use faithful_repr_extraspecial_pchar instead.")]
Notation faithful_repr_extraspecial := (faithful_repr_extraspecial_pchar)
(only parsing).
|
Basic.lean
|
/-
Copyright (c) 2023 Ziyu Wang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ziyu Wang, Chenyi Li, Sébastien Gouëzel, Penghao Yu, Zhipeng Cao
-/
import Mathlib.Analysis.InnerProductSpace.Dual
import Mathlib.Analysis.Calculus.FDeriv.Basic
import Mathlib.Analysis.Calculus.Deriv.Basic
/-!
# Gradient
## Main Definitions
Let `f` be a function from a Hilbert Space `F` to `𝕜` (`𝕜` is `ℝ` or `ℂ`) , `x` be a point in `F`
and `f'` be a vector in F. Then
`HasGradientWithinAt f f' s x`
says that `f` has a gradient `f'` at `x`, where the domain of interest
is restricted to `s`. We also have
`HasGradientAt f f' x := HasGradientWithinAt f f' x univ`
## Main results
This file contains the following parts of gradient.
* the definition of gradient.
* the theorems translating between `HasGradientAtFilter` and `HasFDerivAtFilter`,
`HasGradientWithinAt` and `HasFDerivWithinAt`, `HasGradientAt` and `HasFDerivAt`,
`Gradient` and `fderiv`.
* theorems the Uniqueness of Gradient.
* the theorems translating between `HasGradientAtFilter` and `HasDerivAtFilter`,
`HasGradientAt` and `HasDerivAt`, `Gradient` and `deriv` when `F = 𝕜`.
* the theorems about the congruence of the gradient.
* the theorems about the gradient of constant function.
* the theorems about the continuity of a function admitting a gradient.
-/
open Topology InnerProductSpace Function Set
noncomputable section
variable {𝕜 F : Type*} [RCLike 𝕜]
variable [NormedAddCommGroup F] [InnerProductSpace 𝕜 F] [CompleteSpace F]
variable {f : F → 𝕜} {f' x : F}
/-- A function `f` has the gradient `f'` as derivative along the filter `L` if
`f x' = f x + ⟨f', x' - x⟩ + o (x' - x)` when `x'` converges along the filter `L`. -/
def HasGradientAtFilter (f : F → 𝕜) (f' x : F) (L : Filter F) :=
HasFDerivAtFilter f (toDual 𝕜 F f') x L
/-- `f` has the gradient `f'` at the point `x` within the subset `s` if
`f x' = f x + ⟨f', x' - x⟩ + o (x' - x)` where `x'` converges to `x` inside `s`. -/
def HasGradientWithinAt (f : F → 𝕜) (f' : F) (s : Set F) (x : F) :=
HasGradientAtFilter f f' x (𝓝[s] x)
/-- `f` has the gradient `f'` at the point `x` if
`f x' = f x + ⟨f', x' - x⟩ + o (x' - x)` where `x'` converges to `x`. -/
def HasGradientAt (f : F → 𝕜) (f' x : F) :=
HasGradientAtFilter f f' x (𝓝 x)
/-- Gradient of `f` at the point `x` within the set `s`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', HasGradientWithinAt f f' s x`), then
`f x' = f x + ⟨f', x' - x⟩ + o (x' - x)` where `x'` converges to `x` inside `s`. -/
def gradientWithin (f : F → 𝕜) (s : Set F) (x : F) : F :=
(toDual 𝕜 F).symm (fderivWithin 𝕜 f s x)
/-- Gradient of `f` at the point `x`, if it exists. Zero otherwise.
Denoted as `∇` within the Gradient namespace.
If the derivative exists (i.e., `∃ f', HasGradientAt f f' x`), then
`f x' = f x + ⟨f', x' - x⟩ + o (x' - x)` where `x'` converges to `x`. -/
def gradient (f : F → 𝕜) (x : F) : F :=
(toDual 𝕜 F).symm (fderiv 𝕜 f x)
@[inherit_doc]
scoped[Gradient] notation "∇" => gradient
local notation "⟪" x ", " y "⟫" => inner 𝕜 x y
open scoped Gradient
variable {s : Set F} {L : Filter F}
theorem hasGradientWithinAt_iff_hasFDerivWithinAt {s : Set F} :
HasGradientWithinAt f f' s x ↔ HasFDerivWithinAt f (toDual 𝕜 F f') s x :=
Iff.rfl
theorem hasFDerivWithinAt_iff_hasGradientWithinAt {frechet : F →L[𝕜] 𝕜} {s : Set F} :
HasFDerivWithinAt f frechet s x ↔ HasGradientWithinAt f ((toDual 𝕜 F).symm frechet) s x := by
rw [hasGradientWithinAt_iff_hasFDerivWithinAt, (toDual 𝕜 F).apply_symm_apply frechet]
theorem hasGradientAt_iff_hasFDerivAt :
HasGradientAt f f' x ↔ HasFDerivAt f (toDual 𝕜 F f') x :=
Iff.rfl
theorem hasFDerivAt_iff_hasGradientAt {frechet : F →L[𝕜] 𝕜} :
HasFDerivAt f frechet x ↔ HasGradientAt f ((toDual 𝕜 F).symm frechet) x := by
rw [hasGradientAt_iff_hasFDerivAt, (toDual 𝕜 F).apply_symm_apply frechet]
alias ⟨HasGradientWithinAt.hasFDerivWithinAt, _⟩ := hasGradientWithinAt_iff_hasFDerivWithinAt
alias ⟨HasFDerivWithinAt.hasGradientWithinAt, _⟩ := hasFDerivWithinAt_iff_hasGradientWithinAt
alias ⟨HasGradientAt.hasFDerivAt, _⟩ := hasGradientAt_iff_hasFDerivAt
alias ⟨HasFDerivAt.hasGradientAt, _⟩ := hasFDerivAt_iff_hasGradientAt
theorem gradient_eq_zero_of_not_differentiableAt (h : ¬DifferentiableAt 𝕜 f x) : ∇ f x = 0 := by
rw [gradient, fderiv_zero_of_not_differentiableAt h, map_zero]
theorem HasGradientAt.unique {gradf gradg : F}
(hf : HasGradientAt f gradf x) (hg : HasGradientAt f gradg x) :
gradf = gradg :=
(toDual 𝕜 F).injective (hf.hasFDerivAt.unique hg.hasFDerivAt)
theorem DifferentiableAt.hasGradientAt (h : DifferentiableAt 𝕜 f x) :
HasGradientAt f (∇ f x) x := by
rw [hasGradientAt_iff_hasFDerivAt, gradient, (toDual 𝕜 F).apply_symm_apply (fderiv 𝕜 f x)]
exact h.hasFDerivAt
theorem HasGradientAt.differentiableAt (h : HasGradientAt f f' x) :
DifferentiableAt 𝕜 f x :=
h.hasFDerivAt.differentiableAt
theorem DifferentiableWithinAt.hasGradientWithinAt (h : DifferentiableWithinAt 𝕜 f s x) :
HasGradientWithinAt f (gradientWithin f s x) s x := by
rw [hasGradientWithinAt_iff_hasFDerivWithinAt, gradientWithin,
(toDual 𝕜 F).apply_symm_apply (fderivWithin 𝕜 f s x)]
exact h.hasFDerivWithinAt
theorem HasGradientWithinAt.differentiableWithinAt (h : HasGradientWithinAt f f' s x) :
DifferentiableWithinAt 𝕜 f s x :=
h.hasFDerivWithinAt.differentiableWithinAt
@[simp]
theorem hasGradientWithinAt_univ : HasGradientWithinAt f f' univ x ↔ HasGradientAt f f' x := by
rw [hasGradientWithinAt_iff_hasFDerivWithinAt, hasGradientAt_iff_hasFDerivAt]
exact hasFDerivWithinAt_univ
theorem DifferentiableOn.hasGradientAt (h : DifferentiableOn 𝕜 f s) (hs : s ∈ 𝓝 x) :
HasGradientAt f (∇ f x) x :=
(h.hasFDerivAt hs).hasGradientAt
theorem HasGradientAt.gradient (h : HasGradientAt f f' x) : ∇ f x = f' :=
h.differentiableAt.hasGradientAt.unique h
theorem gradient_eq {f' : F → F} (h : ∀ x, HasGradientAt f (f' x) x) : ∇ f = f' :=
funext fun x => (h x).gradient
section OneDimension
variable {g : 𝕜 → 𝕜} {g' u : 𝕜} {L' : Filter 𝕜}
theorem HasGradientAtFilter.hasDerivAtFilter (h : HasGradientAtFilter g g' u L') :
HasDerivAtFilter g (starRingEnd 𝕜 g') u L' := by
have : ContinuousLinearMap.smulRight (1 : 𝕜 →L[𝕜] 𝕜) (starRingEnd 𝕜 g') = (toDual 𝕜 𝕜) g' := by
ext; simp
rwa [HasDerivAtFilter, this]
theorem HasDerivAtFilter.hasGradientAtFilter (h : HasDerivAtFilter g g' u L') :
HasGradientAtFilter g (starRingEnd 𝕜 g') u L' := by
have : ContinuousLinearMap.smulRight (1 : 𝕜 →L[𝕜] 𝕜) g' = (toDual 𝕜 𝕜) (starRingEnd 𝕜 g') := by
ext; simp
rwa [HasGradientAtFilter, ← this]
theorem HasGradientAt.hasDerivAt (h : HasGradientAt g g' u) :
HasDerivAt g (starRingEnd 𝕜 g') u := by
rw [hasGradientAt_iff_hasFDerivAt, hasFDerivAt_iff_hasDerivAt] at h
simpa using h
theorem HasDerivAt.hasGradientAt (h : HasDerivAt g g' u) :
HasGradientAt g (starRingEnd 𝕜 g') u := by
rw [hasGradientAt_iff_hasFDerivAt, hasFDerivAt_iff_hasDerivAt]
simpa
theorem gradient_eq_deriv : ∇ g u = starRingEnd 𝕜 (deriv g u) := by
by_cases h : DifferentiableAt 𝕜 g u
· rw [h.hasGradientAt.hasDerivAt.deriv, RCLike.conj_conj]
· rw [gradient_eq_zero_of_not_differentiableAt h, deriv_zero_of_not_differentiableAt h, map_zero]
end OneDimension
section OneDimensionReal
variable {g : ℝ → ℝ} {g' u : ℝ} {L' : Filter ℝ}
theorem HasGradientAtFilter.hasDerivAtFilter' (h : HasGradientAtFilter g g' u L') :
HasDerivAtFilter g g' u L' := h.hasDerivAtFilter
theorem HasDerivAtFilter.hasGradientAtFilter' (h : HasDerivAtFilter g g' u L') :
HasGradientAtFilter g g' u L' := h.hasGradientAtFilter
theorem HasGradientAt.hasDerivAt' (h : HasGradientAt g g' u) :
HasDerivAt g g' u := h.hasDerivAt
theorem HasDerivAt.hasGradientAt' (h : HasDerivAt g g' u) :
HasGradientAt g g' u := h.hasGradientAt
theorem gradient_eq_deriv' : ∇ g u = deriv g u := gradient_eq_deriv
end OneDimensionReal
open Filter
section GradientProperties
theorem hasGradientAtFilter_iff_isLittleO :
HasGradientAtFilter f f' x L ↔
(fun x' : F => f x' - f x - ⟪f', x' - x⟫) =o[L] fun x' => x' - x :=
hasFDerivAtFilter_iff_isLittleO ..
theorem hasGradientWithinAt_iff_isLittleO :
HasGradientWithinAt f f' s x ↔
(fun x' : F => f x' - f x - ⟪f', x' - x⟫) =o[𝓝[s] x] fun x' => x' - x :=
hasGradientAtFilter_iff_isLittleO
theorem hasGradientWithinAt_iff_tendsto :
HasGradientWithinAt f f' s x ↔
Tendsto (fun x' => ‖x' - x‖⁻¹ * ‖f x' - f x - ⟪f', x' - x⟫‖) (𝓝[s] x) (𝓝 0) :=
hasFDerivAtFilter_iff_tendsto
theorem hasGradientAt_iff_isLittleO : HasGradientAt f f' x ↔
(fun x' : F => f x' - f x - ⟪f', x' - x⟫) =o[𝓝 x] fun x' => x' - x :=
hasGradientAtFilter_iff_isLittleO
theorem hasGradientAt_iff_tendsto :
HasGradientAt f f' x ↔
Tendsto (fun x' => ‖x' - x‖⁻¹ * ‖f x' - f x - ⟪f', x' - x⟫‖) (𝓝 x) (𝓝 0) :=
hasFDerivAtFilter_iff_tendsto
theorem HasGradientAtFilter.isBigO_sub (h : HasGradientAtFilter f f' x L) :
(fun x' => f x' - f x) =O[L] fun x' => x' - x :=
HasFDerivAtFilter.isBigO_sub h
theorem hasGradientWithinAt_congr_set' {s t : Set F} (y : F) (h : s =ᶠ[𝓝[{y}ᶜ] x] t) :
HasGradientWithinAt f f' s x ↔ HasGradientWithinAt f f' t x :=
hasFDerivWithinAt_congr_set' y h
theorem hasGradientWithinAt_congr_set {s t : Set F} (h : s =ᶠ[𝓝 x] t) :
HasGradientWithinAt f f' s x ↔ HasGradientWithinAt f f' t x :=
hasFDerivWithinAt_congr_set h
theorem hasGradientAt_iff_isLittleO_nhds_zero : HasGradientAt f f' x ↔
(fun h => f (x + h) - f x - ⟪f', h⟫) =o[𝓝 0] fun h => h :=
hasFDerivAt_iff_isLittleO_nhds_zero
end GradientProperties
section congr
/-! ### Congruence properties of the Gradient -/
variable {f₀ f₁ : F → 𝕜} {f₀' f₁' : F} {t : Set F}
theorem Filter.EventuallyEq.hasGradientAtFilter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x)
(h₁ : f₀' = f₁') : HasGradientAtFilter f₀ f₀' x L ↔ HasGradientAtFilter f₁ f₁' x L :=
h₀.hasFDerivAtFilter_iff hx (by simp [h₁])
theorem HasGradientAtFilter.congr_of_eventuallyEq (h : HasGradientAtFilter f f' x L)
(hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : HasGradientAtFilter f₁ f' x L := by
rwa [hL.hasGradientAtFilter_iff hx rfl]
theorem HasGradientWithinAt.congr_mono (h : HasGradientWithinAt f f' s x) (ht : ∀ x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : HasGradientWithinAt f₁ f' t x :=
HasFDerivWithinAt.congr_mono h ht hx h₁
theorem HasGradientWithinAt.congr (h : HasGradientWithinAt f f' s x) (hs : ∀ x ∈ s, f₁ x = f x)
(hx : f₁ x = f x) : HasGradientWithinAt f₁ f' s x :=
h.congr_mono hs hx (by tauto)
theorem HasGradientWithinAt.congr_of_mem (h : HasGradientWithinAt f f' s x)
(hs : ∀ x ∈ s, f₁ x = f x) (hx : x ∈ s) : HasGradientWithinAt f₁ f' s x :=
h.congr hs (hs _ hx)
theorem HasGradientWithinAt.congr_of_eventuallyEq (h : HasGradientWithinAt f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : HasGradientWithinAt f₁ f' s x :=
HasGradientAtFilter.congr_of_eventuallyEq h h₁ hx
theorem HasGradientWithinAt.congr_of_eventuallyEq_of_mem (h : HasGradientWithinAt f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : HasGradientWithinAt f₁ f' s x :=
h.congr_of_eventuallyEq h₁ (h₁.eq_of_nhdsWithin hx)
theorem HasGradientAt.congr_of_eventuallyEq (h : HasGradientAt f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) :
HasGradientAt f₁ f' x :=
HasGradientAtFilter.congr_of_eventuallyEq h h₁ (mem_of_mem_nhds h₁ :)
theorem Filter.EventuallyEq.gradient_eq (hL : f₁ =ᶠ[𝓝 x] f) : ∇ f₁ x = ∇ f x := by
unfold gradient
rwa [Filter.EventuallyEq.fderiv_eq]
protected theorem Filter.EventuallyEq.gradient (h : f₁ =ᶠ[𝓝 x] f) : ∇ f₁ =ᶠ[𝓝 x] ∇ f :=
h.eventuallyEq_nhds.mono fun _ h => h.gradient_eq
end congr
/-! ### The Gradient of constant functions -/
section Const
variable (c : 𝕜) (s x L)
theorem hasGradientAtFilter_const : HasGradientAtFilter (fun _ => c) 0 x L := by
rw [HasGradientAtFilter, map_zero]; apply hasFDerivAtFilter_const c x L
theorem hasGradientWithinAt_const : HasGradientWithinAt (fun _ => c) 0 s x :=
hasGradientAtFilter_const _ _ _
theorem hasGradientAt_const : HasGradientAt (fun _ => c) 0 x :=
hasGradientAtFilter_const _ _ _
theorem gradient_fun_const : ∇ (fun _ => c) x = 0 := by simp [gradient]
theorem gradient_const : ∇ (const F c) x = 0 := gradient_fun_const x c
@[simp]
theorem gradient_fun_const' : (∇ fun _ : F => c) = fun _ => 0 :=
funext fun x => gradient_const x c
@[simp]
theorem gradient_const' : ∇ (const F c) = 0 := gradient_fun_const' c
end Const
section Continuous
/-! ### Continuity of a function admitting a gradient -/
nonrec theorem HasGradientAtFilter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : HasGradientAtFilter f f' x L) :
Tendsto f L (𝓝 (f x)) :=
h.tendsto_nhds hL
theorem HasGradientWithinAt.continuousWithinAt (h : HasGradientWithinAt f f' s x) :
ContinuousWithinAt f s x :=
HasGradientAtFilter.tendsto_nhds inf_le_left h
theorem HasGradientAt.continuousAt (h : HasGradientAt f f' x) : ContinuousAt f x :=
HasGradientAtFilter.tendsto_nhds le_rfl h
protected theorem HasGradientAt.continuousOn {f' : F → F} (h : ∀ x ∈ s, HasGradientAt f (f' x) x) :
ContinuousOn f s :=
fun x hx => (h x hx).continuousAt.continuousWithinAt
end Continuous
|
IrrationalPowerOfIrrational.lean
|
/-
Copyright (c) 2024 Seewoo Lee. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Seewoo Lee
-/
import Mathlib.Data.Real.Irrational
import Mathlib.Analysis.SpecialFunctions.Pow.NNReal
/-
# Irrational power of irrational numbers are not necessarily irrational.
Prove that there exist irrational numbers `a`, `b` such that `a^b` is rational.
We use the following famous argument (based on the law of excluded middle and irrationality of √2).
Consider `c = √2^√2`. If `c` is rational, we are done.
If `c` is irrational, then `c^√2 = 2` is rational, so we are done.
-/
open Real
namespace Counterexample
/--
There exist irrational `a`, `b` with rational `a^b`.
Note that the positivity assumption on `a` is imposed because of the definition of `rpow` for
negative bases. See `Real.rpow_def_of_neg` for more details.
-/
theorem not_irrational_rpow :
¬ ∀ a b : ℝ, Irrational a → Irrational b → 0 < a → Irrational (a ^ b) := by
push_neg
by_cases hc : Irrational (√2 ^ √2)
· use (√2 ^ √2), √2, hc, irrational_sqrt_two, by positivity
rw [← rpow_mul, mul_self_sqrt, rpow_two, sq_sqrt] <;> norm_num
· use √2, √2, irrational_sqrt_two, irrational_sqrt_two, by positivity, hc
end Counterexample
|
Periodic.lean
|
/-
Copyright (c) 2021 Bolton Bailey. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bolton Bailey
-/
import Mathlib.Algebra.Ring.Periodic
import Mathlib.Data.Nat.Count
/-!
# Periodic Functions on ℕ
This file identifies a few functions on `ℕ` which are periodic, and also proves a lemma about
periodic predicates which helps determine their cardinality when filtering intervals over them.
-/
assert_not_exists TwoSidedIdeal
namespace Nat
open Function
theorem periodic_gcd (a : ℕ) : Periodic (gcd a) a := by
simp only [forall_const, gcd_add_self_right, Periodic]
theorem periodic_coprime (a : ℕ) : Periodic (Coprime a) a := by
simp only [coprime_add_self_right, forall_const, Periodic]
theorem periodic_mod (a : ℕ) : Periodic (fun n => n % a) a := by
simp only [forall_const, add_mod_right, Periodic]
theorem _root_.Function.Periodic.map_mod_nat {α : Type*} {f : ℕ → α} {a : ℕ} (hf : Periodic f a) :
∀ n, f (n % a) = f n := fun n => by
conv_rhs => rw [← Nat.mod_add_div n a, mul_comm, ← Nat.nsmul_eq_mul, hf.nsmul]
section Multiset
open Multiset
/-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality
equal to the number naturals below `a` for which `p a` is true. -/
theorem filter_multiset_Ico_card_eq_of_periodic (n a : ℕ) (p : ℕ → Prop) [DecidablePred p]
(pp : Periodic p a) : card (filter p (Ico n (n + a))) = a.count p := by
rw [count_eq_card_filter_range, Finset.card, Finset.filter_val, Finset.range_val, ←
multiset_Ico_map_mod n, ← map_count_True_eq_filter_card, ← map_count_True_eq_filter_card,
map_map]
congr; funext n
exact (Function.Periodic.map_mod_nat pp n).symm
end Multiset
section Finset
open Finset
/-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality
equal to the number naturals below `a` for which `p a` is true. -/
theorem filter_Ico_card_eq_of_periodic (n a : ℕ) (p : ℕ → Prop) [DecidablePred p]
(pp : Periodic p a) : ((Ico n (n + a)).filter p).card = a.count p :=
filter_multiset_Ico_card_eq_of_periodic n a p pp
end Finset
end Nat
|
Assoc.lean
|
/-
Copyright (c) 2018 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import Mathlib.CategoryTheory.Limits.Shapes.Pullback.Pasting
/-!
# Associativity of pullbacks
This file shows that pullbacks (and pushouts) are associative up to natural isomorphism.
-/
noncomputable section
open CategoryTheory
universe w v₁ v₂ v u u₂
namespace CategoryTheory.Limits
variable {C : Type u} [Category.{v} C]
section PullbackAssoc
/-
The objects and morphisms are as follows:
```
Z₂ - g₄ -> X₃
| |
g₃ f₄
∨ ∨
Z₁ - g₂ -> X₂ - f₃ -> Y₂
| |
g₁ f₂
∨ ∨
X₁ - f₁ -> Y₁
```
where the two squares are pullbacks.
We can then construct the pullback squares
```
W - l₂ -> Z₂ - g₄ -> X₃
| |
l₁ f₄
∨ ∨
Z₁ - g₂ -> X₂ - f₃ -> Y₂
```
and
```
W' - l₂' -> Z₂
| |
l₁' g₃
∨ ∨
Z₁ X₂
| |
g₁ f₂
∨ ∨
X₁ - f₁ -> Y₁
```
We will show that both `W` and `W'` are pullbacks over `g₁, g₂`, and thus we may construct a
canonical isomorphism between them. -/
variable {X₁ X₂ X₃ Y₁ Y₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₁) (f₃ : X₂ ⟶ Y₂)
variable (f₄ : X₃ ⟶ Y₂) [HasPullback f₁ f₂] [HasPullback f₃ f₄]
local notation "Z₁" => pullback f₁ f₂
local notation "Z₂" => pullback f₃ f₄
local notation "g₁" => (pullback.fst _ _ : Z₁ ⟶ X₁)
local notation "g₂" => (pullback.snd _ _ : Z₁ ⟶ X₂)
local notation "g₃" => (pullback.fst _ _ : Z₂ ⟶ X₂)
local notation "g₄" => (pullback.snd _ _ : Z₂ ⟶ X₃)
local notation "W" => pullback (g₂ ≫ f₃) f₄
local notation "W'" => pullback f₁ (g₃ ≫ f₂)
local notation "l₁" => (pullback.fst _ _ : W ⟶ Z₁)
local notation "l₂" =>
(pullback.lift (pullback.fst _ _ ≫ g₂) (pullback.snd _ _)
(Eq.trans (Category.assoc _ _ _) pullback.condition) :
W ⟶ Z₂)
local notation "l₁'" =>
(pullback.lift (pullback.fst _ _) (pullback.snd _ _ ≫ g₃)
(pullback.condition.trans (Eq.symm (Category.assoc _ _ _))) :
W' ⟶ Z₁)
local notation "l₂'" => (pullback.snd f₁ (g₃ ≫ f₂))
/-- `(X₁ ×[Y₁] X₂) ×[Y₂] X₃` is the pullback `(X₁ ×[Y₁] X₂) ×[X₂] (X₂ ×[Y₂] X₃)`. -/
def pullbackPullbackLeftIsPullback [HasPullback (g₂ ≫ f₃) f₄] : IsLimit (PullbackCone.mk l₁ l₂
(show l₁ ≫ g₂ = l₂ ≫ g₃ from (pullback.lift_fst _ _ _).symm)) := by
apply leftSquareIsPullback _ rfl (pullbackIsPullback f₃ f₄)
simpa [PullbackCone.pasteHoriz] using PullbackCone.mkSelfIsLimit (pullbackIsPullback _ f₄)
/-- `(X₁ ×[Y₁] X₂) ×[Y₂] X₃` is the pullback `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)`. -/
def pullbackAssocIsPullback [HasPullback (g₂ ≫ f₃) f₄] :
IsLimit
(PullbackCone.mk (l₁ ≫ g₁) l₂
(show (l₁ ≫ g₁) ≫ f₁ = l₂ ≫ g₃ ≫ f₂ by
rw [pullback.lift_fst_assoc, Category.assoc, Category.assoc, pullback.condition])) := by
simpa using pasteVertIsPullback rfl (pullbackIsPullback _ _)
(pullbackPullbackLeftIsPullback f₁ f₂ f₃ f₄)
theorem hasPullback_assoc [HasPullback (g₂ ≫ f₃) f₄] : HasPullback f₁ (g₃ ≫ f₂) :=
⟨⟨⟨_, pullbackAssocIsPullback f₁ f₂ f₃ f₄⟩⟩⟩
/-- `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)` is the pullback `(X₁ ×[Y₁] X₂) ×[X₂] (X₂ ×[Y₂] X₃)`. -/
def pullbackPullbackRightIsPullback [HasPullback f₁ (g₃ ≫ f₂)] :
IsLimit (PullbackCone.mk l₁' l₂' (show l₁' ≫ g₂ = l₂' ≫ g₃ from pullback.lift_snd _ _ _)) := by
apply topSquareIsPullback _ rfl (pullbackIsPullback f₁ f₂)
simpa [PullbackCone.pasteVert] using PullbackCone.mkSelfIsLimit (pullbackIsPullback _ _)
/-- `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)` is the pullback `(X₁ ×[Y₁] X₂) ×[Y₂] X₃`. -/
def pullbackAssocSymmIsPullback [HasPullback f₁ (g₃ ≫ f₂)] :
IsLimit
(PullbackCone.mk l₁' (l₂' ≫ g₄)
(show l₁' ≫ g₂ ≫ f₃ = (l₂' ≫ g₄) ≫ f₄ by
rw [pullback.lift_snd_assoc, Category.assoc, Category.assoc, pullback.condition])) := by
simpa [PullbackCone.pasteHoriz] using pasteHorizIsPullback rfl
(pullbackIsPullback f₃ f₄) (pullbackPullbackRightIsPullback _ _ _ _)
theorem hasPullback_assoc_symm [HasPullback f₁ (g₃ ≫ f₂)] : HasPullback (g₂ ≫ f₃) f₄ :=
⟨⟨⟨_, pullbackAssocSymmIsPullback f₁ f₂ f₃ f₄⟩⟩⟩
/-- The canonical isomorphism `(X₁ ×[Y₁] X₂) ×[Y₂] X₃ ≅ X₁ ×[Y₁] (X₂ ×[Y₂] X₃)`. -/
noncomputable def pullbackAssoc [HasPullback ((pullback.snd _ _ : Z₁ ⟶ X₂) ≫ f₃) f₄]
[HasPullback f₁ ((pullback.fst _ _ : Z₂ ⟶ X₂) ≫ f₂)] :
pullback (pullback.snd _ _ ≫ f₃ : pullback f₁ f₂ ⟶ _) f₄ ≅
pullback f₁ (pullback.fst _ _ ≫ f₂ : pullback f₃ f₄ ⟶ _) :=
(pullbackPullbackLeftIsPullback f₁ f₂ f₃ f₄).conePointUniqueUpToIso
(pullbackPullbackRightIsPullback f₁ f₂ f₃ f₄)
@[reassoc (attr := simp)]
theorem pullbackAssoc_inv_fst_fst [HasPullback ((pullback.snd _ _ : Z₁ ⟶ X₂) ≫ f₃) f₄]
[HasPullback f₁ ((pullback.fst _ _ : Z₂ ⟶ X₂) ≫ f₂)] :
(pullbackAssoc f₁ f₂ f₃ f₄).inv ≫ pullback.fst _ _ ≫ pullback.fst _ _ = pullback.fst _ _ := by
trans l₁' ≫ pullback.fst _ _
· rw [← Category.assoc]
congr 1
exact IsLimit.conePointUniqueUpToIso_inv_comp _ _ WalkingCospan.left
· exact pullback.lift_fst _ _ _
@[reassoc (attr := simp)]
theorem pullbackAssoc_hom_fst [HasPullback ((pullback.snd _ _ : Z₁ ⟶ X₂) ≫ f₃) f₄]
[HasPullback f₁ ((pullback.fst _ _ : Z₂ ⟶ X₂) ≫ f₂)] :
(pullbackAssoc f₁ f₂ f₃ f₄).hom ≫ pullback.fst _ _ = pullback.fst _ _ ≫ pullback.fst _ _ := by
rw [← Iso.eq_inv_comp, pullbackAssoc_inv_fst_fst]
@[reassoc (attr := simp)]
theorem pullbackAssoc_hom_snd_fst [HasPullback ((pullback.snd _ _ : Z₁ ⟶ X₂) ≫ f₃) f₄]
[HasPullback f₁ ((pullback.fst _ _ : Z₂ ⟶ X₂) ≫ f₂)] : (pullbackAssoc f₁ f₂ f₃ f₄).hom ≫
pullback.snd _ _ ≫ pullback.fst _ _ = pullback.fst _ _ ≫ pullback.snd _ _ := by
trans l₂ ≫ pullback.fst _ _
· rw [← Category.assoc]
congr 1
exact IsLimit.conePointUniqueUpToIso_hom_comp _ _ WalkingCospan.right
· exact pullback.lift_fst _ _ _
@[reassoc (attr := simp)]
theorem pullbackAssoc_hom_snd_snd [HasPullback ((pullback.snd _ _ : Z₁ ⟶ X₂) ≫ f₃) f₄]
[HasPullback f₁ ((pullback.fst _ _ : Z₂ ⟶ X₂) ≫ f₂)] :
(pullbackAssoc f₁ f₂ f₃ f₄).hom ≫ pullback.snd _ _ ≫ pullback.snd _ _ = pullback.snd _ _ := by
trans l₂ ≫ pullback.snd _ _
· rw [← Category.assoc]
congr 1
exact IsLimit.conePointUniqueUpToIso_hom_comp _ _ WalkingCospan.right
· exact pullback.lift_snd _ _ _
@[reassoc (attr := simp)]
theorem pullbackAssoc_inv_fst_snd [HasPullback ((pullback.snd _ _ : Z₁ ⟶ X₂) ≫ f₃) f₄]
[HasPullback f₁ ((pullback.fst _ _ : Z₂ ⟶ X₂) ≫ f₂)] :
(pullbackAssoc f₁ f₂ f₃ f₄).inv ≫ pullback.fst _ _ ≫ pullback.snd _ _ =
pullback.snd _ _ ≫ pullback.fst _ _ := by rw [Iso.inv_comp_eq, pullbackAssoc_hom_snd_fst]
@[reassoc (attr := simp)]
theorem pullbackAssoc_inv_snd [HasPullback ((pullback.snd _ _ : Z₁ ⟶ X₂) ≫ f₃) f₄]
[HasPullback f₁ ((pullback.fst _ _ : Z₂ ⟶ X₂) ≫ f₂)] :
(pullbackAssoc f₁ f₂ f₃ f₄).inv ≫ pullback.snd _ _ = pullback.snd _ _ ≫ pullback.snd _ _ := by
rw [Iso.inv_comp_eq, pullbackAssoc_hom_snd_snd]
end PullbackAssoc
section PushoutAssoc
/-
The objects and morphisms are as follows:
```
Z₂ - g₄ -> X₃
| |
g₃ f₄
∨ ∨
Z₁ - g₂ -> X₂ - f₃ -> Y₂
| |
g₁ f₂
∨ ∨
X₁ - f₁ -> Y₁
```
where the two squares are pushouts.
We can then construct the pushout squares
```
Z₁ - g₂ -> X₂ - f₃ -> Y₂
| |
g₁ l₂
∨ ∨
X₁ - f₁ -> Y₁ - l₁ -> W
and
Z₂ - g₄ -> X₃
| |
g₃ f₄
∨ ∨
X₂ Y₂
| |
f₂ l₂'
∨ ∨
Y₁ - l₁' -> W'
```
We will show that both `W` and `W'` are pushouts over `f₂, f₃`, and thus we may construct a
canonical isomorphism between them. -/
variable {X₁ X₂ X₃ Z₁ Z₂ : C} (g₁ : Z₁ ⟶ X₁) (g₂ : Z₁ ⟶ X₂) (g₃ : Z₂ ⟶ X₂)
variable (g₄ : Z₂ ⟶ X₃) [HasPushout g₁ g₂] [HasPushout g₃ g₄]
local notation "Y₁" => pushout g₁ g₂
local notation "Y₂" => pushout g₃ g₄
local notation "f₁" => (pushout.inl _ _ : X₁ ⟶ Y₁)
local notation "f₂" => (pushout.inr _ _ : X₂ ⟶ Y₁)
local notation "f₃" => (pushout.inl _ _ : X₂ ⟶ Y₂)
local notation "f₄" => (pushout.inr _ _ : X₃ ⟶ Y₂)
local notation "W" => pushout g₁ (g₂ ≫ f₃)
local notation "W'" => pushout (g₃ ≫ f₂) g₄
local notation "l₁" =>
(pushout.desc (pushout.inl _ _) (f₃ ≫ pushout.inr _ _)
(pushout.condition.trans (Category.assoc _ _ _)) : Y₁ ⟶ W)
local notation "l₂" => (pushout.inr _ _ : Y₂ ⟶ W)
local notation "l₁'" => (pushout.inl _ _ : Y₁ ⟶ W')
local notation "l₂'" =>
(pushout.desc (f₂ ≫ pushout.inl _ _) (pushout.inr _ _)
(Eq.trans (Eq.symm (Category.assoc _ _ _)) pushout.condition) :
Y₂ ⟶ W')
/-- `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃` is the pushout `(X₁ ⨿[Z₁] X₂) ×[X₂] (X₂ ⨿[Z₂] X₃)`. -/
def pushoutPushoutLeftIsPushout [HasPushout (g₃ ≫ f₂) g₄] :
IsColimit
(PushoutCocone.mk l₁' l₂' (show f₂ ≫ l₁' = f₃ ≫ l₂' from (pushout.inl_desc _ _ _).symm)) := by
apply botSquareIsPushout _ rfl (pushoutIsPushout _ g₄)
simpa [PushoutCocone.pasteVert] using
PushoutCocone.mkSelfIsColimit (pushoutIsPushout (g₃ ≫ f₂) g₄)
/-- `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃` is the pushout `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)`. -/
def pushoutAssocIsPushout [HasPushout (g₃ ≫ f₂) g₄] :
IsColimit
(PushoutCocone.mk (f₁ ≫ l₁') l₂'
(show g₁ ≫ f₁ ≫ l₁' = (g₂ ≫ f₃) ≫ l₂' by
rw [Category.assoc, pushout.inl_desc, pushout.condition_assoc])) := by
simpa using pasteHorizIsPushout rfl (pushoutIsPushout g₁ g₂)
(pushoutPushoutLeftIsPushout g₁ g₂ g₃ g₄)
theorem hasPushout_assoc [HasPushout (g₃ ≫ f₂) g₄] : HasPushout g₁ (g₂ ≫ f₃) :=
⟨⟨⟨_, pushoutAssocIsPushout g₁ g₂ g₃ g₄⟩⟩⟩
/-- `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)` is the pushout `(X₁ ⨿[Z₁] X₂) ×[X₂] (X₂ ⨿[Z₂] X₃)`. -/
def pushoutPushoutRightIsPushout [HasPushout g₁ (g₂ ≫ f₃)] :
IsColimit (PushoutCocone.mk l₁ l₂ (show f₂ ≫ l₁ = f₃ ≫ l₂ from pushout.inr_desc _ _ _)) := by
apply rightSquareIsPushout _ rfl (pushoutIsPushout _ _)
simpa [PushoutCocone.pasteHoriz] using PushoutCocone.mkSelfIsColimit (pushoutIsPushout _ _)
/-- `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)` is the pushout `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃`. -/
def pushoutAssocSymmIsPushout [HasPushout g₁ (g₂ ≫ f₃)] :
IsColimit
(PushoutCocone.mk l₁ (f₄ ≫ l₂)
(show (g₃ ≫ f₂) ≫ l₁ = g₄ ≫ f₄ ≫ l₂ by
rw [Category.assoc, pushout.inr_desc, pushout.condition_assoc])) := by
simpa using pasteVertIsPushout rfl (pushoutIsPushout _ _) (pushoutPushoutRightIsPushout _ _ _ _)
theorem hasPushout_assoc_symm [HasPushout g₁ (g₂ ≫ f₃)] : HasPushout (g₃ ≫ f₂) g₄ :=
⟨⟨⟨_, pushoutAssocSymmIsPushout g₁ g₂ g₃ g₄⟩⟩⟩
-- Porting note: these are not propagating so moved into statements
-- variable [HasPushout (g₃ ≫ f₂) g₄] [HasPushout g₁ (g₂ ≫ f₃)]
/-- The canonical isomorphism `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃ ≅ X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)`. -/
noncomputable def pushoutAssoc [HasPushout (g₃ ≫ (pushout.inr _ _ : X₂ ⟶ Y₁)) g₄]
[HasPushout g₁ (g₂ ≫ (pushout.inl _ _ : X₂ ⟶ Y₂))] :
pushout (g₃ ≫ pushout.inr _ _ : _ ⟶ pushout g₁ g₂) g₄ ≅
pushout g₁ (g₂ ≫ pushout.inl _ _ : _ ⟶ pushout g₃ g₄) :=
(pushoutPushoutLeftIsPushout g₁ g₂ g₃ g₄).coconePointUniqueUpToIso
(pushoutPushoutRightIsPushout g₁ g₂ g₃ g₄)
@[reassoc (attr := simp)]
theorem inl_inl_pushoutAssoc_hom [HasPushout (g₃ ≫ (pushout.inr _ _ : X₂ ⟶ Y₁)) g₄]
[HasPushout g₁ (g₂ ≫ (pushout.inl _ _ : X₂ ⟶ Y₂))] :
pushout.inl _ _ ≫ pushout.inl _ _ ≫ (pushoutAssoc g₁ g₂ g₃ g₄).hom = pushout.inl _ _ := by
trans f₁ ≫ l₁
· congr 1
exact
(pushoutPushoutLeftIsPushout g₁ g₂ g₃ g₄).comp_coconePointUniqueUpToIso_hom _
WalkingCospan.left
· exact pushout.inl_desc _ _ _
@[reassoc (attr := simp)]
theorem inr_inl_pushoutAssoc_hom [HasPushout (g₃ ≫ (pushout.inr _ _ : X₂ ⟶ Y₁)) g₄]
[HasPushout g₁ (g₂ ≫ (pushout.inl _ _ : X₂ ⟶ Y₂))] :
pushout.inr _ _ ≫ pushout.inl _ _ ≫ (pushoutAssoc g₁ g₂ g₃ g₄).hom =
pushout.inl _ _ ≫ pushout.inr _ _ := by
trans f₂ ≫ l₁
· congr 1
exact
(pushoutPushoutLeftIsPushout g₁ g₂ g₃ g₄).comp_coconePointUniqueUpToIso_hom _
WalkingCospan.left
· exact pushout.inr_desc _ _ _
@[reassoc (attr := simp)]
theorem inr_inr_pushoutAssoc_inv [HasPushout (g₃ ≫ (pushout.inr _ _ : X₂ ⟶ Y₁)) g₄]
[HasPushout g₁ (g₂ ≫ (pushout.inl _ _ : X₂ ⟶ Y₂))] :
pushout.inr _ _ ≫ pushout.inr _ _ ≫ (pushoutAssoc g₁ g₂ g₃ g₄).inv = pushout.inr _ _ := by
trans f₄ ≫ l₂'
· congr 1
exact
(pushoutPushoutLeftIsPushout g₁ g₂ g₃ g₄).comp_coconePointUniqueUpToIso_inv
(pushoutPushoutRightIsPushout g₁ g₂ g₃ g₄) WalkingCospan.right
· exact pushout.inr_desc _ _ _
@[reassoc (attr := simp)]
theorem inl_pushoutAssoc_inv [HasPushout (g₃ ≫ (pushout.inr _ _ : X₂ ⟶ Y₁)) g₄]
[HasPushout g₁ (g₂ ≫ (pushout.inl _ _ : X₂ ⟶ Y₂))] :
pushout.inl _ _ ≫ (pushoutAssoc g₁ g₂ g₃ g₄).inv = pushout.inl _ _ ≫ pushout.inl _ _ := by
rw [Iso.comp_inv_eq, Category.assoc, inl_inl_pushoutAssoc_hom]
@[reassoc (attr := simp)]
theorem inl_inr_pushoutAssoc_inv [HasPushout (g₃ ≫ (pushout.inr _ _ : X₂ ⟶ Y₁)) g₄]
[HasPushout g₁ (g₂ ≫ (pushout.inl _ _ : X₂ ⟶ Y₂))] :
pushout.inl _ _ ≫ pushout.inr _ _ ≫ (pushoutAssoc g₁ g₂ g₃ g₄).inv =
pushout.inr _ _ ≫ pushout.inl _ _ := by
rw [← Category.assoc, Iso.comp_inv_eq, Category.assoc, inr_inl_pushoutAssoc_hom]
@[reassoc (attr := simp)]
theorem inr_pushoutAssoc_hom [HasPushout (g₃ ≫ (pushout.inr _ _ : X₂ ⟶ Y₁)) g₄]
[HasPushout g₁ (g₂ ≫ (pushout.inl _ _ : X₂ ⟶ Y₂))] :
pushout.inr _ _ ≫ (pushoutAssoc g₁ g₂ g₃ g₄).hom = pushout.inr _ _ ≫ pushout.inr _ _ := by
rw [← Iso.eq_comp_inv, Category.assoc, inr_inr_pushoutAssoc_inv]
end PushoutAssoc
end CategoryTheory.Limits
|
Equivalence.lean
|
/-
Copyright (c) 2021 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import Mathlib.ModelTheory.Satisfiability
/-!
# Equivalence of Formulas
## Main Definitions
- `FirstOrder.Language.Theory.Imp`: `φ ⟹[T] ψ` indicates that `φ` implies `ψ` in models of `T`.
- `FirstOrder.Language.Theory.Iff`: `φ ⇔[T] ψ` indicates that `φ` and `ψ` are equivalent formulas or
sentences in models of `T`.
## TODO
- Define the quotient of `L.Formula α` modulo `⇔[T]` and its Boolean Algebra structure.
-/
universe u v w w'
open Cardinal CategoryTheory
open FirstOrder
namespace FirstOrder
namespace Language
variable {L : Language.{u, v}} {T : L.Theory} {α : Type w} {n : ℕ}
variable {M : Type*} [Nonempty M] [L.Structure M] [M ⊨ T]
namespace Theory
/-- `φ ⟹[T] ψ` indicates that `φ` implies `ψ` in models of `T`. -/
protected def Imp (T : L.Theory) (φ ψ : L.BoundedFormula α n) : Prop :=
T ⊨ᵇ φ.imp ψ
@[inherit_doc FirstOrder.Language.Theory.Imp]
scoped[FirstOrder] notation:51 φ:50 " ⟹[" T "] " ψ:51 => Language.Theory.Imp T φ ψ
namespace Imp
@[refl]
protected theorem refl (φ : L.BoundedFormula α n) : φ ⟹[T] φ := fun _ _ _ => id
instance : IsRefl (L.BoundedFormula α n) T.Imp := ⟨Imp.refl⟩
@[trans]
protected theorem trans {φ ψ θ : L.BoundedFormula α n} (h1 : φ ⟹[T] ψ) (h2 : ψ ⟹[T] θ) :
φ ⟹[T] θ := fun M v xs => (h2 M v xs) ∘ (h1 M v xs)
instance : IsTrans (L.BoundedFormula α n) T.Imp := ⟨fun _ _ _ => Imp.trans⟩
end Imp
section Imp
lemma bot_imp (φ : L.BoundedFormula α n) : ⊥ ⟹[T] φ := fun M v xs => by
simp only [BoundedFormula.realize_imp, BoundedFormula.realize_bot, false_implies]
lemma imp_top (φ : L.BoundedFormula α n) : φ ⟹[T] ⊤ := fun M v xs => by
simp only [BoundedFormula.realize_imp, BoundedFormula.realize_top, implies_true]
lemma imp_sup_left (φ ψ : L.BoundedFormula α n) : φ ⟹[T] φ ⊔ ψ := fun M v xs => by
simp only [BoundedFormula.realize_imp, BoundedFormula.realize_sup]
exact Or.inl
lemma imp_sup_right (φ ψ : L.BoundedFormula α n) : ψ ⟹[T] φ ⊔ ψ := fun M v xs => by
simp only [BoundedFormula.realize_imp, BoundedFormula.realize_sup]
exact Or.inr
lemma sup_imp {φ ψ θ : L.BoundedFormula α n} (h₁ : φ ⟹[T] θ) (h₂ : ψ ⟹[T] θ) :
φ ⊔ ψ ⟹[T] θ := fun M v xs => by
simp only [BoundedFormula.realize_imp, BoundedFormula.realize_sup]
exact fun h => h.elim (h₁ M v xs) (h₂ M v xs)
lemma sup_imp_iff {φ ψ θ : L.BoundedFormula α n} :
(φ ⊔ ψ ⟹[T] θ) ↔ (φ ⟹[T] θ) ∧ (ψ ⟹[T] θ) :=
⟨fun h => ⟨(imp_sup_left _ _).trans h, (imp_sup_right _ _).trans h⟩,
fun ⟨h₁, h₂⟩ => sup_imp h₁ h₂⟩
lemma inf_imp_left (φ ψ : L.BoundedFormula α n) : φ ⊓ ψ ⟹[T] φ := fun M v xs => by
simp only [BoundedFormula.realize_imp, BoundedFormula.realize_inf]
exact And.left
lemma inf_imp_right (φ ψ : L.BoundedFormula α n) : φ ⊓ ψ ⟹[T] ψ := fun M v xs => by
simp only [BoundedFormula.realize_imp, BoundedFormula.realize_inf]
exact And.right
lemma imp_inf {φ ψ θ : L.BoundedFormula α n} (h₁ : φ ⟹[T] ψ) (h₂ : φ ⟹[T] θ) :
φ ⟹[T] ψ ⊓ θ := fun M v xs => by
simp only [BoundedFormula.realize_imp, BoundedFormula.realize_inf]
exact fun h => ⟨h₁ M v xs h, h₂ M v xs h⟩
lemma imp_inf_iff {φ ψ θ : L.BoundedFormula α n} :
(φ ⟹[T] ψ ⊓ θ) ↔ (φ ⟹[T] ψ) ∧ (φ ⟹[T] θ) :=
⟨fun h => ⟨h.trans (inf_imp_left _ _), h.trans (inf_imp_right _ _)⟩,
fun ⟨h₁, h₂⟩ => imp_inf h₁ h₂⟩
end Imp
/-- Two (bounded) formulas are semantically equivalent over a theory `T` when they have the same
interpretation in every model of `T`. (This is also known as logical equivalence, which also has a
proof-theoretic definition.) -/
protected def Iff (T : L.Theory) (φ ψ : L.BoundedFormula α n) : Prop :=
T ⊨ᵇ φ.iff ψ
@[inherit_doc FirstOrder.Language.Theory.Iff]
scoped[FirstOrder]
notation:51 φ:50 " ⇔[" T "] " ψ:51 => Language.Theory.Iff T φ ψ
theorem iff_iff_imp_and_imp {φ ψ : L.BoundedFormula α n} :
(φ ⇔[T] ψ) ↔ (φ ⟹[T] ψ) ∧ (ψ ⟹[T] φ) := by
simp only [Theory.Imp, ModelsBoundedFormula, BoundedFormula.realize_imp, ← forall_and,
Theory.Iff, BoundedFormula.realize_iff, iff_iff_implies_and_implies]
theorem imp_antisymm {φ ψ : L.BoundedFormula α n} (h₁ : φ ⟹[T] ψ) (h₂ : ψ ⟹[T] φ) :
φ ⇔[T] ψ :=
iff_iff_imp_and_imp.2 ⟨h₁, h₂⟩
namespace Iff
protected theorem mp {φ ψ : L.BoundedFormula α n} (h : φ ⇔[T] ψ) :
φ ⟹[T] ψ := (iff_iff_imp_and_imp.1 h).1
protected theorem mpr {φ ψ : L.BoundedFormula α n} (h : φ ⇔[T] ψ) :
ψ ⟹[T] φ := (iff_iff_imp_and_imp.1 h).2
@[refl]
protected theorem refl (φ : L.BoundedFormula α n) : φ ⇔[T] φ :=
fun M v xs => by rw [BoundedFormula.realize_iff]
instance : IsRefl (L.BoundedFormula α n) T.Iff :=
⟨Iff.refl⟩
@[symm]
protected theorem symm {φ ψ : L.BoundedFormula α n}
(h : φ ⇔[T] ψ) : ψ ⇔[T] φ := fun M v xs => by
rw [BoundedFormula.realize_iff, Iff.comm, ← BoundedFormula.realize_iff]
exact h M v xs
instance : IsSymm (L.BoundedFormula α n) T.Iff :=
⟨fun _ _ => Iff.symm⟩
@[trans]
protected theorem trans {φ ψ θ : L.BoundedFormula α n}
(h1 : φ ⇔[T] ψ) (h2 : ψ ⇔[T] θ) :
φ ⇔[T] θ := fun M v xs => by
have h1' := h1 M v xs
have h2' := h2 M v xs
rw [BoundedFormula.realize_iff] at *
exact ⟨h2'.1 ∘ h1'.1, h1'.2 ∘ h2'.2⟩
instance : IsTrans (L.BoundedFormula α n) T.Iff :=
⟨fun _ _ _ => Iff.trans⟩
theorem realize_bd_iff {φ ψ : L.BoundedFormula α n} (h : φ ⇔[T] ψ)
{v : α → M} {xs : Fin n → M} : φ.Realize v xs ↔ ψ.Realize v xs :=
BoundedFormula.realize_iff.1 (h.realize_boundedFormula M)
theorem realize_iff {φ ψ : L.Formula α} {M : Type*} [Nonempty M]
[L.Structure M] [M ⊨ T] (h : φ ⇔[T] ψ) {v : α → M} :
φ.Realize v ↔ ψ.Realize v :=
h.realize_bd_iff
theorem models_sentence_iff {φ ψ : L.Sentence} {M : Type*} [Nonempty M]
[L.Structure M] [M ⊨ T] (h : φ ⇔[T] ψ) :
M ⊨ φ ↔ M ⊨ ψ :=
h.realize_iff
protected theorem all {φ ψ : L.BoundedFormula α (n + 1)}
(h : φ ⇔[T] ψ) : φ.all ⇔[T] ψ.all := by
simp_rw [Theory.Iff, ModelsBoundedFormula, BoundedFormula.realize_iff,
BoundedFormula.realize_all]
exact fun M v xs => forall_congr' fun a => h.realize_bd_iff
protected theorem ex {φ ψ : L.BoundedFormula α (n + 1)} (h : φ ⇔[T] ψ) :
φ.ex ⇔[T] ψ.ex := by
simp_rw [Theory.Iff, ModelsBoundedFormula, BoundedFormula.realize_iff,
BoundedFormula.realize_ex]
exact fun M v xs => exists_congr fun a => h.realize_bd_iff
protected theorem not {φ ψ : L.BoundedFormula α n} (h : φ ⇔[T] ψ) :
φ.not ⇔[T] ψ.not := by
simp_rw [Theory.Iff, ModelsBoundedFormula, BoundedFormula.realize_iff,
BoundedFormula.realize_not]
exact fun M v xs => not_congr h.realize_bd_iff
protected theorem imp {φ ψ φ' ψ' : L.BoundedFormula α n} (h : φ ⇔[T] ψ) (h' : φ' ⇔[T] ψ') :
(φ.imp φ') ⇔[T] (ψ.imp ψ') := by
simp_rw [Theory.Iff, ModelsBoundedFormula, BoundedFormula.realize_iff,
BoundedFormula.realize_imp]
exact fun M v xs => imp_congr h.realize_bd_iff h'.realize_bd_iff
end Iff
/-- Semantic equivalence forms an equivalence relation on formulas. -/
def iffSetoid (T : L.Theory) : Setoid (L.BoundedFormula α n) where
r := T.Iff
iseqv := ⟨fun _ => refl _, fun {_ _} h => h.symm, fun {_ _ _} h1 h2 => h1.trans h2⟩
end Theory
namespace BoundedFormula
variable (φ ψ : L.BoundedFormula α n)
theorem iff_not_not : φ ⇔[T] φ.not.not := fun M v xs => by
simp
theorem imp_iff_not_sup : (φ.imp ψ) ⇔[T] (φ.not ⊔ ψ) :=
fun M v xs => by simp [imp_iff_not_or]
theorem sup_iff_not_inf_not : (φ ⊔ ψ) ⇔[T] (φ.not ⊓ ψ.not).not :=
fun M v xs => by simp [imp_iff_not_or]
theorem inf_iff_not_sup_not : (φ ⊓ ψ) ⇔[T] (φ.not ⊔ ψ.not).not :=
fun M v xs => by simp
theorem all_iff_not_ex_not (φ : L.BoundedFormula α (n + 1)) :
φ.all ⇔[T] φ.not.ex.not := fun M v xs => by simp
theorem ex_iff_not_all_not (φ : L.BoundedFormula α (n + 1)) :
φ.ex ⇔[T] φ.not.all.not := fun M v xs => by simp
theorem iff_all_liftAt : φ ⇔[T] (φ.liftAt 1 n).all :=
fun M v xs => by
rw [realize_iff, realize_all_liftAt_one_self]
lemma inf_not_iff_bot :
φ ⊓ ∼φ ⇔[T] ⊥ := fun M v xs => by
simp only [realize_iff, realize_inf, realize_not, and_not_self, realize_bot]
lemma sup_not_iff_top :
φ ⊔ ∼φ ⇔[T] ⊤ := fun M v xs => by
simp only [realize_iff, realize_sup, realize_not, realize_top, or_not]
end BoundedFormula
namespace Formula
variable (φ ψ : L.Formula α)
theorem iff_not_not : φ ⇔[T] φ.not.not :=
BoundedFormula.iff_not_not φ
theorem imp_iff_not_sup : (φ.imp ψ) ⇔[T] (φ.not ⊔ ψ) :=
BoundedFormula.imp_iff_not_sup φ ψ
theorem sup_iff_not_inf_not : (φ ⊔ ψ) ⇔[T] (φ.not ⊓ ψ.not).not :=
BoundedFormula.sup_iff_not_inf_not φ ψ
theorem inf_iff_not_sup_not : (φ ⊓ ψ) ⇔[T] (φ.not ⊔ ψ.not).not :=
BoundedFormula.inf_iff_not_sup_not φ ψ
end Formula
end Language
end FirstOrder
|
choice.v
|
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *)
(* Distributed under the terms of CeCILL-B. *)
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.
(******************************************************************************)
(* Types with a choice operator *)
(* *)
(* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *)
(* *)
(* This file contains the definitions of: *)
(* choiceType == interface for types with a choice operator *)
(* The HB class is Choice. *)
(* The exact contents is documented below just before *)
(* hasChoice. *)
(* subChoiceType == interface for types that are both subType and choiceType *)
(* The HB class is SubChoice. *)
(* countType == interface for countable types (implies choiceType) *)
(* The HB class is Countable. *)
(* subCountType == interface for types that are both subType and countType *)
(* The HB class is SubCountable. *)
(* *)
(* xchoose exP == a standard x such that P x, given exP : exists x : T, P x *)
(* when T is a choiceType *)
(* The choice depends only on the extent of P (in particular,*)
(* it is independent of exP). *)
(* choose P x0 == if P x0, a standard x such that P x *)
(* pickle x == a nat encoding the value x : T, where T is a countType *)
(* unpickle n == a partial inverse to pickle: unpickle (pickle x) = Some x *)
(* pickle_inv n == a sharp partial inverse to pickle pickle_inv n = Some x *)
(* if and only if pickle x = n *)
(* *)
(* PCanIsCountable ff' == builds an instance of the isCountable interface *)
(* given ff' : pcancel f f' where the codomain of f is *)
(* a countType *)
(* CanIsCountable ff' == builds an instance of the isCountable interface *)
(* given ff' : cancel f f' where the codomain of f is *)
(* a countType *)
(* *)
(* [Choice of T by <:], [Countable of T by <:] == Choice/Countable interface *)
(* for T when T has a subType p structure with p : pred cT *)
(* and cT has a Choice/Countable interface *)
(* The corresponding structure is Canonical. This notation *)
(* is in form_scope. *)
(* *)
(* List of Choice/Countable factories with a dedicated alias: *)
(* pcan_type fK == Choice/Countable for T, given f : T -> cT where cT *)
(* has a Choice/Countable structure, a left inverse *)
(* partial function g and fK : pcancel f g *)
(* can_type fK == Choice/Countable for T, given f : T -> cT, g and *)
(* fK : cancel f g *)
(* *)
(* GenTree.tree T == generic n-ary tree type with nat-labeled nodes and *)
(* T-labeled leaves, for example GenTree.Leaf (x : T), *)
(* GenTree.Node 5 [:: t; t'] *)
(* GenTree.tree is equipped with eqType, choiceType, *)
(* and countType instances, and so simple datatypes *)
(* can be similarly equipped by encoding into *)
(* GenTree.tree and using the interfaces above. *)
(* CodeSeq.code == bijection from seq nat to nat *)
(* CodeSeq.decode == bijection inverse to CodeSeq.code *)
(* *)
(* In addition to the lemmas relevant to these definitions, this file also *)
(* contains definitions of choiceType and countType instances for all basic *)
(* basic datatypes (e.g., nat, bool, subTypes, pairs, sums, etc.). *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
(* Technical definitions about coding and decoding of nat sequences, which *)
(* are used below to define various Canonical instances of the choice and *)
(* countable interfaces. *)
Module CodeSeq.
(* Goedel-style one-to-one encoding of seq nat into nat. *)
(* The code for [:: n1; ...; nk] has binary representation *)
(* 1 0 ... 0 1 ... 1 0 ... 0 1 0 ... 0 *)
(* <-----> <-----> <-----> *)
(* nk 0s n2 0s n1 0s *)
Definition code := foldr (fun n m => 2 ^ n * m.*2.+1) 0.
Fixpoint decode_rec (v q r : nat) {struct q} :=
match q, r with
| 0, _ => [:: v]
| q'.+1, 0 => v :: [rec 0, q', q']
| q'.+1, 1 => [rec v.+1, q', q']
| q'.+1, r'.+2 => [rec v, q', r']
end where "[ 'rec' v , q , r ]" := (decode_rec v q r).
Arguments decode_rec : simpl nomatch.
Definition decode n := if n is 0 then [::] else [rec 0, n.-1, n.-1].
Lemma decodeK : cancel decode code.
Proof.
have m2s: forall n, n.*2 - n = n by move=> n; rewrite -addnn addnK.
case=> //= n; rewrite -[n.+1]mul1n -(expn0 2) -[n in RHS]m2s.
elim: n {2 4}n {1 3}0 => [|q IHq] [|[|r]] v //=; rewrite {}IHq ?mul1n ?m2s //.
by rewrite expnSr -mulnA mul2n.
Qed.
Lemma codeK : cancel code decode.
Proof.
elim=> //= v s IHs; rewrite -[_ * _]prednK ?muln_gt0 ?expn_gt0 //=.
set two := 2; rewrite -[v in RHS]addn0; elim: v 0 => [|v IHv {IHs}] q.
rewrite mul1n add0n /= -{}[in RHS]IHs; case: (code s) => // u; pose n := u.+1.
by transitivity [rec q, n + u.+1, n.*2]; [rewrite addnn | elim: n => //=].
rewrite expnS -mulnA mul2n -{1}addnn -[_ * _]prednK ?muln_gt0 ?expn_gt0 //.
set u := _.-1 in IHv *; set n := u; rewrite [in u1 in _ + u1]/n.
by rewrite [in RHS]addSnnS -{}IHv; elim: n.
Qed.
Lemma ltn_code s : all (fun j => j < code s) s.
Proof.
elim: s => //= i s IHs; rewrite -[_.+1]muln1 leq_mul 1?ltn_expl //=.
apply: sub_all IHs => j /leqW lejs; rewrite -[j.+1]mul1n leq_mul ?expn_gt0 //.
by rewrite ltnS -[j]mul1n -mul2n leq_mul.
Qed.
Lemma gtn_decode n : all (ltn^~ n) (decode n).
Proof. by rewrite -{1}[n]decodeK ltn_code. Qed.
End CodeSeq.
Section OtherEncodings.
(* Miscellaneous encodings: option T -c-> seq T, T1 * T2 -c-> {i : T1 & T2} *)
(* T1 + T2 -c-> option T1 * option T2, unit -c-> bool; bool -c-> nat is *)
(* already covered in ssrnat by the nat_of_bool coercion, the odd predicate, *)
(* and their "cancellation" lemma oddb. We use these encodings to propagate *)
(* canonical structures through these type constructors so that ultimately *)
(* all Choice and Countable instanced derive from nat and the seq and sigT *)
(* constructors. *)
Variables T T1 T2 : Type.
Definition seq_of_opt := @oapp T _ (nseq 1) [::].
Lemma seq_of_optK : cancel seq_of_opt ohead. Proof. by case. Qed.
Definition tag_of_pair (p : T1 * T2) := @Tagged T1 p.1 (fun _ => T2) p.2.
Definition pair_of_tag (u : {i : T1 & T2}) := (tag u, tagged u).
Lemma tag_of_pairK : cancel tag_of_pair pair_of_tag. Proof. by case. Qed.
Lemma pair_of_tagK : cancel pair_of_tag tag_of_pair. Proof. by case. Qed.
Definition opair_of_sum (s : T1 + T2) :=
match s with inl x => (Some x, None) | inr y => (None, Some y) end.
Definition sum_of_opair p :=
oapp (some \o @inr T1 T2) (omap (@inl _ T2) p.1) p.2.
Lemma opair_of_sumK : pcancel opair_of_sum sum_of_opair. Proof. by case. Qed.
Lemma bool_of_unitK : cancel (fun _ => true) (fun _ => tt).
Proof. by case. Qed.
End OtherEncodings.
Prenex Implicits seq_of_opt tag_of_pair pair_of_tag opair_of_sum sum_of_opair.
Prenex Implicits seq_of_optK tag_of_pairK pair_of_tagK opair_of_sumK.
(* Generic variable-arity tree type, providing an encoding target for *)
(* miscellaneous user datatypes. The GenTree.tree type can be combined with *)
(* a sigT type to model multi-sorted concrete datatypes. *)
Module GenTree.
Section Def.
Variable T : Type.
Unset Elimination Schemes.
Inductive tree := Leaf of T | Node of nat & seq tree.
Definition tree_rect K IH_leaf IH_node :=
fix loop t : K t := match t with
| Leaf x => IH_leaf x
| Node n f0 =>
let fix iter_pair f : foldr (fun t => prod (K t)) unit f :=
if f is t :: f' then (loop t, iter_pair f') else tt in
IH_node n f0 (iter_pair f0)
end.
Definition tree_rec (K : tree -> Set) := @tree_rect K.
Definition tree_ind K IH_leaf IH_node :=
fix loop t : K t : Prop := match t with
| Leaf x => IH_leaf x
| Node n f0 =>
let fix iter_conj f : foldr (fun t => and (K t)) True f :=
if f is t :: f' then conj (loop t) (iter_conj f') else Logic.I
in IH_node n f0 (iter_conj f0)
end.
Fixpoint encode t : seq (nat + T) :=
match t with
| Leaf x => [:: inr _ x]
| Node n f => inl _ n.+1 :: rcons (flatten (map encode f)) (inl _ 0)
end.
Definition decode_step c fs :=
match c with
| inr x => (Leaf x :: fs.1, fs.2)
| inl 0 => ([::], fs.1 :: fs.2)
| inl n.+1 => (Node n fs.1 :: head [::] fs.2, behead fs.2)
end.
Definition decode c := ohead (foldr decode_step ([::], [::]) c).1.
Lemma codeK : pcancel encode decode.
Proof.
move=> t; rewrite /decode; set fs := (_, _).
suffices ->: foldr decode_step fs (encode t) = (t :: fs.1, fs.2) by [].
elim: t => //= n f IHt in (fs) *; elim: f IHt => //= t f IHf [].
by rewrite rcons_cat foldr_cat => -> /= /IHf[-> -> ->].
Qed.
End Def.
End GenTree.
Arguments GenTree.codeK : clear implicits.
HB.instance Definition _ (T : eqType) := Equality.copy (GenTree.tree T)
(pcan_type (GenTree.codeK T)).
(* Structures for Types with a choice function, and for Types with countably *)
(* many elements. The two concepts are closely linked: we indeed make *)
(* Countable a subclass of Choice, as countable choice is valid in CiC. This *)
(* apparent redundancy is needed to ensure the consistency of the Canonical *)
(* inference, as the canonical Choice for a given type may differ from the *)
(* countable choice for its canonical Countable structure, e.g., for options. *)
(* The Choice interface exposes two choice functions; for T : choiceType *)
(* and P : pred T, we provide: *)
(* xchoose : (exists x, P x) -> T *)
(* choose : pred T -> T -> T *)
(* While P (xchoose exP) will always hold, P (choose P x0) will be true if *)
(* and only if P x0 holds. Both xchoose and choose are extensional in P and *)
(* do not depend on the witness exP or x0 (provided P x0 holds). Note that *)
(* xchoose is slightly more powerful, but less convenient to use. *)
(* However, neither choose nor xchoose are composable: it would not be *)
(* be possible to extend the Choice structure to arbitrary pairs using only *)
(* these functions, for instance. Internally, the interfaces provides a *)
(* subtly stronger operation, Choice.InternalTheory.find, which performs a *)
(* limited search using an integer parameter only rather than a full value as *)
(* [x]choose does. This is not a restriction in a constructive theory, where *)
(* all types are concrete and hence countable. In the case of an axiomatic *)
(* theory, such as that of the Coq reals library, postulating a suitable *)
(* axiom of choice suppresses the need for guidance. Nevertheless this *)
(* operation is just what is needed to make the Choice interface compose. *)
(* The Countable interface provides three functions; for T : countType we *)
(* get pickle : T -> nat, and unpickle, pickle_inv : nat -> option T. *)
(* The functions provide an effective embedding of T in nat: unpickle is a *)
(* left inverse to pickle, which satisfies pcancel pickle unpickle, i.e., *)
(* unpickle \o pickle =1 some; pickle_inv is a more precise inverse for which *)
(* we also have ocancel pickle_inv pickle. Both unpickle and pickle need to *)
(* be partial functions to allow for possibly empty types such as {x | P x}. *)
(* The names of these functions underline the correspondence with the *)
(* notion of "Serializable" types in programming languages. *)
(* Finally, we need to provide a join class to let type inference unify *)
(* subType and countType class constraints, e.g., for a countable subType of *)
(* an uncountable choiceType (the issue does not arise earlier with eqType or *)
(* choiceType because in practice the base type of an Equality/Choice subType *)
(* is always an Equality/Choice Type). *)
HB.mixin Record hasChoice T := Mixin {
find_subdef : pred T -> nat -> option T;
choice_correct_subdef {P n x} : find_subdef P n = Some x -> P x;
choice_complete_subdef {P : pred T} :
(exists x, P x) -> exists n, find_subdef P n;
choice_extensional_subdef {P Q : pred T} :
P =1 Q -> find_subdef P =1 find_subdef Q
}.
#[short(type="choiceType")]
HB.structure Definition Choice := { T of hasChoice T & hasDecEq T}.
Module Export ChoiceNamespace.
Module Choice.
Module InternalTheory.
Notation find := find_subdef.
Notation correct := choice_correct_subdef.
Arguments correct {_ _ _ _}.
Notation complete := choice_complete_subdef.
Arguments complete {_ _}.
Notation extensional := choice_extensional_subdef.
Arguments extensional {_ _ _}.
Section InternalTheory.
Variable T : Choice.type.
Implicit Types P Q : pred T.
Fact xchoose_subproof P exP :
{x | find P (ex_minn (@choice_complete_subdef _ P exP)) = Some x}.
Proof.
case: (ex_minnP (complete exP)) => n.
by case: (find P n) => // x; exists x.
Qed.
End InternalTheory.
End InternalTheory.
End Choice.
End ChoiceNamespace.
Section ChoiceTheory.
Implicit Type T : choiceType.
Import Choice.InternalTheory CodeSeq.
Local Notation dc := decode.
Section OneType.
Variable T : choiceType.
Implicit Types P Q : pred T.
Definition xchoose P exP := sval (@xchoose_subproof T P exP).
Lemma xchooseP P exP : P (@xchoose P exP).
Proof. by rewrite /xchoose; case: (xchoose_subproof exP) => x /= /correct. Qed.
Lemma eq_xchoose P Q exP exQ : P =1 Q -> @xchoose P exP = @xchoose Q exQ.
Proof.
rewrite /xchoose => eqPQ.
case: (xchoose_subproof exP) => x; case: (xchoose_subproof exQ) => y /=.
case: ex_minnP => n; rewrite -(extensional eqPQ) => Pn minQn.
case: ex_minnP => m; rewrite !(extensional eqPQ) => Qm minPm.
by case: (eqVneq m n) => [-> -> [] //|]; rewrite eqn_leq minQn ?minPm.
Qed.
Lemma sigW P : (exists x, P x) -> {x | P x}.
Proof. by move=> exP; exists (xchoose exP); apply: xchooseP. Qed.
Lemma sig2W P Q : (exists2 x, P x & Q x) -> {x | P x & Q x}.
Proof.
move=> exPQ; have [|x /andP[]] := @sigW (predI P Q); last by exists x.
by have [x Px Qx] := exPQ; exists x; apply/andP.
Qed.
Lemma sig_eqW (vT : eqType) (lhs rhs : T -> vT) :
(exists x, lhs x = rhs x) -> {x | lhs x = rhs x}.
Proof.
move=> exP; suffices [x /eqP Ex]: {x | lhs x == rhs x} by exists x.
by apply: sigW; have [x /eqP Ex] := exP; exists x.
Qed.
Lemma sig2_eqW (vT : eqType) (P : pred T) (lhs rhs : T -> vT) :
(exists2 x, P x & lhs x = rhs x) -> {x | P x & lhs x = rhs x}.
Proof.
move=> exP; suffices [x Px /eqP Ex]: {x | P x & lhs x == rhs x} by exists x.
by apply: sig2W; have [x Px /eqP Ex] := exP; exists x.
Qed.
Definition choose P x0 :=
if insub x0 : {? x | P x} is Some (exist x Px) then
xchoose (ex_intro [eta P] x Px)
else x0.
Lemma chooseP P x0 : P x0 -> P (choose P x0).
Proof. by move=> Px0; rewrite /choose insubT xchooseP. Qed.
Lemma choose_id P x0 y0 : P x0 -> P y0 -> choose P x0 = choose P y0.
Proof. by move=> Px0 Py0; rewrite /choose !insubT /=; apply: eq_xchoose. Qed.
Lemma eq_choose P Q : P =1 Q -> choose P =1 choose Q.
Proof.
rewrite /choose => eqPQ x0.
do [case: insubP; rewrite eqPQ] => [[x Px] Qx0 _| ?]; last by rewrite insubN.
by rewrite insubT; apply: eq_xchoose.
Qed.
Section CanChoice.
Variables (sT : Type) (f : sT -> T).
Lemma PCanHasChoice f' : pcancel f f' -> hasChoice sT.
Proof.
move=> fK; pose liftP sP := [pred x | oapp sP false (f' x)].
pose sf sP := [fun n => obind f' (find (liftP sP) n)].
exists sf => [sP n x | sP [y sPy] | sP sQ eqPQ n] /=.
- by case Df: (find _ n) => //= [?] Dx; have:= correct Df; rewrite /= Dx.
- have [|n Pn] := @complete T (liftP sP); first by exists (f y); rewrite /= fK.
exists n; case Df: (find _ n) Pn => //= [x] _.
by have:= correct Df => /=; case: (f' x).
by congr (obind _ _); apply: extensional => x /=; case: (f' x) => /=.
Qed.
Definition CanHasChoice f' (fK : cancel f f') :=
PCanHasChoice (can_pcan fK).
HB.instance Definition _ f' (fK : pcancel f f') : hasChoice (pcan_type fK) :=
PCanHasChoice fK.
HB.instance Definition _ f' (fK : cancel f f') : hasChoice (can_type fK) :=
PCanHasChoice (can_pcan fK).
End CanChoice.
Section SubChoice.
Variables (P : pred T) (sT : subType P).
#[hnf] HB.instance Definition _ := Choice.copy (sub_type sT) (pcan_type valK).
End SubChoice.
Fact seq_hasChoice : hasChoice (seq T).
Proof.
pose r f := [fun xs => fun x : T => f (x :: xs) : option (seq T)].
pose fix f sP ns xs {struct ns} :=
if ns is n :: ns1 then let fr := r (f sP ns1) xs in obind fr (find fr n)
else if sP xs then Some xs else None.
exists (fun sP nn => f sP (dc nn) nil) => [sP n ys | sP [ys] | sP sQ eqPQ n].
- elim: {n}(dc n) nil => [|n ns IHs] xs /=; first by case: ifP => // sPxs [<-].
by case: (find _ n) => //= [x]; apply: IHs.
- rewrite -(cats0 ys); elim/last_ind: ys nil => [|ys y IHs] xs /=.
by move=> sPxs; exists 0; rewrite /= sPxs.
rewrite cat_rcons => /IHs[n1 sPn1] {IHs}.
have /complete[n]: exists z, f sP (dc n1) (z :: xs) by exists y.
case Df: (find _ n)=> // [x] _; exists (code (n :: dc n1)).
by rewrite codeK /= Df /= (correct Df).
elim: {n}(dc n) nil => [|n ns IHs] xs /=; first by rewrite eqPQ.
rewrite (@extensional _ _ (r (f sQ ns) xs)) => [|x]; last by rewrite IHs.
by case: find => /=.
Qed.
HB.instance Definition _ := seq_hasChoice.
End OneType.
Section TagChoice.
Variables (I : choiceType) (T_ : I -> choiceType).
Fact tagged_hasChoice : hasChoice {i : I & T_ i}.
Proof.
pose mkT i (x : T_ i) := Tagged T_ x.
pose ft tP n i := omap (mkT i) (find (tP \o mkT i) n).
pose fi tP ni nt := obind (ft tP nt) (find (ft tP nt) ni).
pose f tP n := if dc n is [:: ni; nt] then fi tP ni nt else None.
exists f => [tP n u | tP [[i x] tPxi] | sP sQ eqPQ n].
- rewrite /f /fi; case: (dc n) => [|ni [|nt []]] //=.
case: (find _ _) => //= [i]; rewrite /ft.
by case Df: (find _ _) => //= [x] [<-]; have:= correct Df.
- have /complete[nt tPnt]: exists y, (tP \o mkT i) y by exists x.
have{tPnt}: exists j, ft tP nt j by exists i; rewrite /ft; case: find tPnt.
case/complete=> ni tPn; exists (code [:: ni; nt]); rewrite /f codeK /fi.
by case Df: find tPn => //= [j] _; have:= correct Df.
rewrite /f /fi; case: (dc n) => [|ni [|nt []]] //=.
rewrite (@extensional _ _ (ft sQ nt)) => [|i].
by case: find => //= i; congr (omap _ _); apply: extensional => x /=.
by congr (omap _ _); apply: extensional => x /=.
Qed.
HB.instance Definition _ := tagged_hasChoice.
End TagChoice.
Fact nat_hasChoice : hasChoice nat.
Proof.
pose f := [fun (P : pred nat) n => if P n then Some n else None].
exists f => [P n m | P [n Pn] | P Q eqPQ n] /=; last by rewrite eqPQ.
by case: ifP => // Pn [<-].
by exists n; rewrite Pn.
Qed.
HB.instance Definition _ := nat_hasChoice.
HB.instance Definition _ := Choice.copy bool (can_type oddb).
HB.instance Definition _ := Choice.on bitseq.
HB.instance Definition _ := Choice.copy unit (can_type bool_of_unitK).
HB.instance Definition _ := Choice.copy void (pcan_type (of_voidK unit)).
HB.instance Definition _ T :=
Choice.copy (option T) (can_type (@seq_of_optK (Choice.sort T))).
HB.instance Definition _ (T1 T2 : choiceType) :=
Choice.copy (T1 * T2)%type (can_type (@tag_of_pairK T1 T2)).
HB.instance Definition _ (T1 T2 : choiceType) :=
Choice.copy (T1 + T2)%type (pcan_type (@opair_of_sumK T1 T2)).
HB.instance Definition _ T :=
Choice.copy (GenTree.tree T) (pcan_type (GenTree.codeK T)).
End ChoiceTheory.
#[short(type="subChoiceType")]
HB.structure Definition SubChoice T (P : pred T) :=
{ sT of Choice sT & isSub T P sT }.
Prenex Implicits xchoose choose.
Notation "[ 'Choice' 'of' T 'by' <: ]" := (Choice.copy T%type (sub_type T%type))
(format "[ 'Choice' 'of' T 'by' <: ]") : form_scope.
HB.instance Definition _ (T : choiceType) (P : pred T) :=
[Choice of {x | P x} by <:].
HB.mixin Record Choice_isCountable (T : Type) : Type := {
pickle : T -> nat;
unpickle : nat -> option T;
pickleK : pcancel pickle unpickle
}.
Arguments Choice_isCountable.axioms_ T%_type_scope.
#[short(type="countType")]
HB.structure Definition Countable := { T of Choice T & Choice_isCountable T }.
HB.factory Record isCountable (T : Type) : Type := {
pickle : T -> nat;
unpickle : nat -> option T;
pickleK : pcancel pickle unpickle
}.
HB.builders Context T of isCountable T.
HB.instance Definition _ := Equality.copy T (pcan_type pickleK).
HB.instance Definition _ := PCanHasChoice pickleK.
HB.instance Definition _ := Choice_isCountable.Build T pickleK.
HB.end.
Arguments isCountable.axioms_ T%_type_scope.
Section CountableTheory.
Variable T : countType.
Definition pickle_inv n :=
obind (fun x : T => if pickle x == n then Some x else None) (unpickle n).
Lemma pickle_invK : ocancel pickle_inv pickle.
Proof.
by rewrite /pickle_inv => n; case def_x: (unpickle n) => //= [x]; case: eqP.
Qed.
Lemma pickleK_inv : pcancel pickle pickle_inv.
Proof. by rewrite /pickle_inv => x; rewrite pickleK /= eqxx. Qed.
Lemma pcan_pickleK sT f f' :
@pcancel T sT f f' -> pcancel (pickle \o f) (pcomp f' unpickle).
Proof. by move=> fK x; rewrite /pcomp pickleK /= fK. Qed.
Definition PCanIsCountable sT (f : sT -> T) f' (fK : pcancel f f') :=
isCountable.Build sT (pcan_pickleK fK).
Definition CanIsCountable sT f f' (fK : cancel f f') :=
@PCanIsCountable sT _ _ (can_pcan fK).
HB.instance Definition _ sT (f : sT -> T) f' (fK : pcancel f f') :
isCountable (pcan_type fK) := PCanIsCountable fK.
HB.instance Definition _ sT (f : sT -> T) f' (fK : cancel f f') :
isCountable (can_type fK) := CanIsCountable fK.
#[hnf] HB.instance Definition _ (P : pred T) (sT : subType P) :=
Countable.copy (sub_type sT) (pcan_type valK).
Definition pickle_seq s := CodeSeq.code (map (@pickle T) s).
Definition unpickle_seq n := Some (pmap (@unpickle T) (CodeSeq.decode n)).
Lemma pickle_seqK : pcancel pickle_seq unpickle_seq.
Proof. by move=> s; rewrite /unpickle_seq CodeSeq.codeK (map_pK pickleK). Qed.
HB.instance Definition _ := isCountable.Build (seq T) pickle_seqK.
End CountableTheory.
Notation "[ 'Countable' 'of' T 'by' <: ]" :=
(Countable.copy T%type (sub_type T%type))
(format "[ 'Countable' 'of' T 'by' <: ]") : form_scope.
Arguments pickle_inv {T} n.
Arguments pickleK {T} x : rename.
Arguments pickleK_inv {T} x.
Arguments pickle_invK {T} n : rename.
#[short(type="subCountType")]
HB.structure Definition SubCountable T (P : pred T) :=
{ sT of Countable sT & isSub T P sT}.
Section TagCountType.
Variables (I : countType) (T_ : I -> countType).
Definition pickle_tagged (u : {i : I & T_ i}) :=
CodeSeq.code [:: pickle (tag u); pickle (tagged u)].
Definition unpickle_tagged s :=
if CodeSeq.decode s is [:: ni; nx] then
obind (fun i => omap (@Tagged I i T_) (unpickle nx)) (unpickle ni)
else None.
Lemma pickle_taggedK : pcancel pickle_tagged unpickle_tagged.
Proof.
by case=> i x; rewrite /unpickle_tagged CodeSeq.codeK /= pickleK /= pickleK.
Qed.
HB.instance Definition _ :=
Choice_isCountable.Build {i : I & T_ i} pickle_taggedK.
End TagCountType.
(* The remaining instances for standard datatypes. *)
Section CountableDataTypes.
Implicit Type T : countType.
Lemma nat_pickleK : pcancel id (@Some nat). Proof. by []. Qed.
HB.instance Definition _ := Choice_isCountable.Build nat nat_pickleK.
HB.instance Definition _ := Countable.copy bool (can_type oddb).
HB.instance Definition _ := Countable.on bitseq.
HB.instance Definition _ := Countable.copy unit (can_type bool_of_unitK).
HB.instance Definition _ := Countable.copy void
(pcan_type (of_voidK unit)).
HB.instance Definition _ T := Countable.copy (option T)
(can_type (@seq_of_optK T)).
HB.instance Definition _ T (P : pred T) := [Countable of {x | P x} by <:].
HB.instance Definition _ T1 T2 :=
Countable.copy (T1 * T2)%type (can_type (@tag_of_pairK T1 T2)).
HB.instance Definition _ (T1 T2 : countType) :=
Countable.copy (T1 + T2)%type (pcan_type (@opair_of_sumK T1 T2)).
HB.instance Definition _ T := Countable.copy (GenTree.tree T)
(pcan_type (GenTree.codeK T)).
End CountableDataTypes.
|
FiberPartition.lean
|
/-
Copyright (c) 2024 Dagur Asgeirsson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Dagur Asgeirsson
-/
import Mathlib.Data.Set.Insert
/-!
This file defines the type `f.Fiber` of fibers of a function `f : Y → Z`, and provides some API
to work with and construct terms of this type.
Note: this API is designed to be useful when defining the counit of the adjunction between
the functor which takes a set to the condensed set corresponding to locally constant maps to that
set, and the forgetful functor from the category of condensed sets to the category of sets
(see PR https://github.com/leanprover-community/mathlib4/pull/14027).
-/
assert_not_exists RelIso
variable {X Y Z : Type*}
namespace Function
/-- The indexing set of the partition. -/
def Fiber (f : Y → Z) : Type _ := Set.range (fun (x : Set.range f) ↦ f ⁻¹' {x.val})
namespace Fiber
/--
Any `a : Fiber f` is of the form `f ⁻¹' {x}` for some `x` in the image of `f`. We define `a.image`
as an arbitrary such `x`.
-/
noncomputable def image (f : Y → Z) (a : Fiber f) : Z := a.2.choose.1
lemma eq_fiber_image (f : Y → Z) (a : Fiber f) : a.1 = f ⁻¹' {a.image} := a.2.choose_spec.symm
/--
Given `y : Y`, `Fiber.mk f y` is the fiber of `f` that `y` belongs to, as an element of `Fiber f`.
-/
def mk (f : Y → Z) (y : Y) : Fiber f := ⟨f ⁻¹' {f y}, by simp⟩
/-- `y : Y` as a term of the type `Fiber.mk f y` -/
def mkSelf (f : Y → Z) (y : Y) : (mk f y).val := ⟨y, rfl⟩
lemma map_eq_image (f : Y → Z) (a : Fiber f) (x : a.1) : f x = a.image := by
have := a.2.choose_spec
rw [← Set.mem_singleton_iff, ← Set.mem_preimage]
convert x.prop
lemma mk_image (f : Y → Z) (y : Y) : (Fiber.mk f y).image = f y :=
(map_eq_image (x := mkSelf f y)).symm
lemma mem_iff_eq_image (f : Y → Z) (y : Y) (a : Fiber f) : y ∈ a.val ↔ f y = a.image :=
⟨fun h ↦ a.map_eq_image _ ⟨y, h⟩, fun h ↦ by rw [a.eq_fiber_image]; exact h⟩
/-- An arbitrary element of `a : Fiber f`. -/
noncomputable def preimage (f : Y → Z) (a : Fiber f) : Y := a.2.choose.2.choose
lemma map_preimage_eq_image (f : Y → Z) (a : Fiber f) : f a.preimage = a.image :=
a.2.choose.2.choose_spec
lemma fiber_nonempty (f : Y → Z) (a : Fiber f) : Set.Nonempty a.val := by
refine ⟨preimage f a, ?_⟩
rw [mem_iff_eq_image, ← map_preimage_eq_image]
lemma map_preimage_eq_image_map {W : Type*} (f : Y → Z) (g : Z → W) (a : Fiber (g ∘ f)) :
g (f a.preimage) = a.image := by rw [← map_preimage_eq_image, comp_apply]
lemma image_eq_image_mk (f : Y → Z) (g : X → Y) (a : Fiber (f ∘ g)) :
a.image = (Fiber.mk f (g (a.preimage _))).image := by
rw [← map_preimage_eq_image_map _ _ a, mk_image]
end Function.Fiber
|
LiminfLimsup.lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov, Yaël Dillies
-/
import Mathlib.Algebra.Order.Group.DenselyOrdered
import Mathlib.Data.Real.Archimedean
import Mathlib.Topology.Algebra.Group.Basic
import Mathlib.Topology.Order.LiminfLimsup
/-!
# Lemmas about liminf and limsup in an order topology.
## Main declarations
* `BoundedLENhdsClass`: Typeclass stating that neighborhoods are eventually bounded above.
* `BoundedGENhdsClass`: Typeclass stating that neighborhoods are eventually bounded below.
## Implementation notes
The same lemmas are true in `ℝ`, `ℝ × ℝ`, `ι → ℝ`, `EuclideanSpace ι ℝ`. To avoid code
duplication, we provide an ad hoc axiomatisation of the properties we need.
-/
open Filter TopologicalSpace
open scoped Topology
universe u v
variable {ι α β R S : Type*} {X : ι → Type*}
section LiminfLimsupAdd
variable [AddCommGroup α] [ConditionallyCompleteLinearOrder α] [DenselyOrdered α]
[AddLeftMono α]
{f : Filter ι} [f.NeBot] {u v : ι → α}
lemma le_limsup_add (h₁ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u := by isBoundedDefault)
(h₂ : IsCoboundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u := by isBoundedDefault)
(h₃ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f v := by isBoundedDefault)
(h₄ : IsBoundedUnder (fun x1 x2 ↦ x1 ≥ x2) f v := by isBoundedDefault) :
(limsup u f) + liminf v f ≤ limsup (u + v) f := by
have h := isCoboundedUnder_le_add h₄ h₂ -- These `have` tactic improve performance.
have h' := isBoundedUnder_le_add h₃ h₁
rw [add_comm] at h h'
refine add_le_of_forall_lt fun a a_u b b_v ↦ (le_limsup_iff h h').2 fun c c_ab ↦ ?_
refine ((frequently_lt_of_lt_limsup h₂ a_u).and_eventually
(eventually_lt_of_lt_liminf b_v h₄)).mono fun _ ab_x ↦ ?_
exact c_ab.trans (add_lt_add ab_x.1 ab_x.2)
lemma limsup_add_le (h₁ : IsBoundedUnder (fun x1 x2 ↦ x1 ≥ x2) f u := by isBoundedDefault)
(h₂ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u := by isBoundedDefault)
(h₃ : IsCoboundedUnder (fun x1 x2 ↦ x1 ≤ x2) f v := by isBoundedDefault)
(h₄ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f v := by isBoundedDefault) :
limsup (u + v) f ≤ (limsup u f) + limsup v f := by
have h := isCoboundedUnder_le_add h₁ h₃
have h' := isBoundedUnder_le_add h₂ h₄
refine le_add_of_forall_lt fun a a_u b b_v ↦ ?_
rw [limsup_le_iff h h']
intro c c_ab
filter_upwards [eventually_lt_of_limsup_lt a_u, eventually_lt_of_limsup_lt b_v] with x a_x b_x
exact (add_lt_add a_x b_x).trans c_ab
lemma le_liminf_add (h₁ : IsBoundedUnder (fun x1 x2 ↦ x1 ≥ x2) f u := by isBoundedDefault)
(h₂ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u := by isBoundedDefault)
(h₃ : IsBoundedUnder (fun x1 x2 ↦ x1 ≥ x2) f v := by isBoundedDefault)
(h₄ : IsCoboundedUnder (fun x1 x2 ↦ x1 ≥ x2) f v := by isBoundedDefault) :
(liminf u f) + liminf v f ≤ liminf (u + v) f := by
have h := isCoboundedUnder_ge_add h₂ h₄
have h' := isBoundedUnder_ge_add h₁ h₃
refine add_le_of_forall_lt fun a a_u b b_v ↦ ?_
rw [le_liminf_iff h h']
intro c c_ab
filter_upwards [eventually_lt_of_lt_liminf a_u, eventually_lt_of_lt_liminf b_v] with x a_x b_x
exact c_ab.trans (add_lt_add a_x b_x)
lemma liminf_add_le (h₁ : IsBoundedUnder (fun x1 x2 ↦ x1 ≥ x2) f u := by isBoundedDefault)
(h₂ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u := by isBoundedDefault)
(h₃ : IsBoundedUnder (fun x1 x2 ↦ x1 ≥ x2) f v := by isBoundedDefault)
(h₄ : IsCoboundedUnder (fun x1 x2 ↦ x1 ≥ x2) f v := by isBoundedDefault) :
liminf (u + v) f ≤ (limsup u f) + liminf v f := by
have h := isCoboundedUnder_ge_add h₂ h₄
have h' := isBoundedUnder_ge_add h₁ h₃
refine le_add_of_forall_lt fun a a_u b b_v ↦ (liminf_le_iff h h').2 fun _ c_ab ↦ ?_
refine ((frequently_lt_of_liminf_lt h₄ b_v).and_eventually
(eventually_lt_of_limsup_lt a_u h₂)).mono fun _ ab_x ↦ ?_
exact (add_lt_add ab_x.2 ab_x.1).trans c_ab
end LiminfLimsupAdd
section LiminfLimsupMul
open Filter Real
variable {f : Filter ι} {u v : ι → ℝ}
lemma le_limsup_mul (h₁ : ∃ᶠ x in f, 0 ≤ u x) (h₂ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u)
(h₃ : 0 ≤ᶠ[f] v) (h₄ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f v) :
(limsup u f) * liminf v f ≤ limsup (u * v) f := by
have h := IsCoboundedUnder.of_frequently_ge (a := 0)
<| (h₁.and_eventually h₃).mono fun x ⟨ux_0, vx_0⟩ ↦ mul_nonneg ux_0 vx_0
have h' := isBoundedUnder_le_mul_of_nonneg h₁ h₂ h₃ h₄
have u0 : 0 ≤ limsup u f := le_limsup_of_frequently_le h₁ h₂
have uv : 0 ≤ limsup (u * v) f :=
le_limsup_of_frequently_le ((h₁.and_eventually h₃).mono fun _ ⟨hu, hv⟩ ↦ mul_nonneg hu hv) h'
refine mul_le_of_forall_lt_of_nonneg u0 uv fun a a0 au b b0 bv ↦ ?_
refine (le_limsup_iff h h').2 fun c c_ab ↦ ?_
replace h₁ := IsCoboundedUnder.of_frequently_ge h₁ -- Pre-compute it to gain 4 s.
have h₅ := frequently_lt_of_lt_limsup h₁ au
have h₆ := eventually_lt_of_lt_liminf bv (isBoundedUnder_of_eventually_ge h₃)
apply (h₅.and_eventually (h₆.and h₃)).mono
exact fun x ⟨xa, ⟨xb, _⟩⟩ ↦ c_ab.trans_le <| mul_le_mul xa.le xb.le b0 (a0.trans xa.le)
lemma limsup_mul_le (h₁ : ∃ᶠ x in f, 0 ≤ u x) (h₂ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u)
(h₃ : 0 ≤ᶠ[f] v) (h₄ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f v) :
limsup (u * v) f ≤ (limsup u f) * limsup v f := by
have h := IsCoboundedUnder.of_frequently_ge (a := 0)
<| (h₁.and_eventually h₃).mono fun x ⟨ux_0, vx_0⟩ ↦ mul_nonneg ux_0 vx_0
have h' := isBoundedUnder_le_mul_of_nonneg h₁ h₂ h₃ h₄
refine le_mul_of_forall_lt₀ fun a a_u b b_v ↦ (limsup_le_iff h h').2 fun c c_ab ↦ ?_
filter_upwards [eventually_lt_of_limsup_lt a_u, eventually_lt_of_limsup_lt b_v, h₃]
with x x_a x_b v_0
apply lt_of_le_of_lt _ c_ab
rcases lt_or_ge (u x) 0 with u_0 | u_0
· apply (mul_nonpos_of_nonpos_of_nonneg u_0.le v_0).trans
exact mul_nonneg ((le_limsup_of_frequently_le h₁ h₂).trans a_u.le) (v_0.trans x_b.le)
· exact mul_le_mul x_a.le x_b.le v_0 (u_0.trans x_a.le)
lemma le_liminf_mul [f.NeBot] (h₁ : 0 ≤ᶠ[f] u) (h₂ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u)
(h₃ : 0 ≤ᶠ[f] v) (h₄ : IsCoboundedUnder (fun x1 x2 ↦ x1 ≥ x2) f v) :
(liminf u f) * liminf v f ≤ liminf (u * v) f := by
have h := isCoboundedUnder_ge_mul_of_nonneg h₁ h₂ h₃ h₄
have h' := isBoundedUnder_of_eventually_ge (a := 0)
<| (h₁.and h₃).mono fun x ⟨u0, v0⟩ ↦ mul_nonneg u0 v0
apply mul_le_of_forall_lt_of_nonneg (le_liminf_of_le h₂.isCoboundedUnder_ge h₁)
(le_liminf_of_le h ((h₁.and h₃).mono fun x ⟨u0, v0⟩ ↦ mul_nonneg u0 v0))
intro a a0 au b b0 bv
refine (le_liminf_iff h h').2 fun c c_ab ↦ ?_
filter_upwards [eventually_lt_of_lt_liminf au (isBoundedUnder_of_eventually_ge h₁),
eventually_lt_of_lt_liminf bv (isBoundedUnder_of_eventually_ge h₃)] with x xa xb
exact c_ab.trans_le (mul_le_mul xa.le xb.le b0 (a0.trans xa.le))
lemma liminf_mul_le [f.NeBot] (h₁ : 0 ≤ᶠ[f] u) (h₂ : IsBoundedUnder (fun x1 x2 ↦ x1 ≤ x2) f u)
(h₃ : 0 ≤ᶠ[f] v) (h₄ : IsCoboundedUnder (fun x1 x2 ↦ x1 ≥ x2) f v) :
liminf (u * v) f ≤ (limsup u f) * liminf v f := by
have h := isCoboundedUnder_ge_mul_of_nonneg h₁ h₂ h₃ h₄
have h' := isBoundedUnder_of_eventually_ge (a := 0)
<| (h₁.and h₃).mono fun x ⟨u_0, v_0⟩ ↦ mul_nonneg u_0 v_0
refine le_mul_of_forall_lt₀ fun a a_u b b_v ↦ (liminf_le_iff h h').2 fun c c_ab ↦ ?_
refine ((frequently_lt_of_liminf_lt h₄ b_v).and_eventually ((eventually_lt_of_limsup_lt a_u).and
(h₁.and h₃))).mono fun x ⟨x_v, x_u, u_0, v_0⟩ ↦ ?_
exact (mul_le_mul x_u.le x_v.le v_0 (u_0.trans x_u.le)).trans_lt c_ab
end LiminfLimsupMul
section LiminfLimsupAddSub
variable [ConditionallyCompleteLinearOrder R] [TopologicalSpace R] [OrderTopology R]
/-- `liminf (c + xᵢ) = c + liminf xᵢ`. -/
lemma limsup_const_add (F : Filter ι) [NeBot F] [Add R] [ContinuousAdd R]
[AddLeftMono R] (f : ι → R) (c : R)
(bdd_above : F.IsBoundedUnder (· ≤ ·) f) (cobdd : F.IsCoboundedUnder (· ≤ ·) f) :
Filter.limsup (fun i ↦ c + f i) F = c + Filter.limsup f F :=
(Monotone.map_limsSup_of_continuousAt (F := F.map f) (f := fun (x : R) ↦ c + x)
(fun _ _ h ↦ add_le_add_left h c) (continuous_add_left c).continuousAt bdd_above cobdd).symm
/-- `limsup (xᵢ + c) = (limsup xᵢ) + c`. -/
lemma limsup_add_const (F : Filter ι) [NeBot F] [Add R] [ContinuousAdd R]
[AddRightMono R] (f : ι → R) (c : R)
(bdd_above : F.IsBoundedUnder (· ≤ ·) f) (cobdd : F.IsCoboundedUnder (· ≤ ·) f) :
Filter.limsup (fun i ↦ f i + c) F = Filter.limsup f F + c :=
(Monotone.map_limsSup_of_continuousAt (F := F.map f) (f := fun (x : R) ↦ x + c)
(fun _ _ h ↦ add_le_add_right h c) (continuous_add_right c).continuousAt bdd_above cobdd).symm
/-- `liminf (c + xᵢ) = c + liminf xᵢ`. -/
lemma liminf_const_add (F : Filter ι) [NeBot F] [Add R] [ContinuousAdd R]
[AddLeftMono R] (f : ι → R) (c : R)
(cobdd : F.IsCoboundedUnder (· ≥ ·) f) (bdd_below : F.IsBoundedUnder (· ≥ ·) f) :
Filter.liminf (fun i ↦ c + f i) F = c + Filter.liminf f F :=
(Monotone.map_limsInf_of_continuousAt (F := F.map f) (f := fun (x : R) ↦ c + x)
(fun _ _ h ↦ add_le_add_left h c) (continuous_add_left c).continuousAt cobdd bdd_below).symm
/-- `liminf (xᵢ + c) = (liminf xᵢ) + c`. -/
lemma liminf_add_const (F : Filter ι) [NeBot F] [Add R] [ContinuousAdd R]
[AddRightMono R] (f : ι → R) (c : R)
(cobdd : F.IsCoboundedUnder (· ≥ ·) f) (bdd_below : F.IsBoundedUnder (· ≥ ·) f) :
Filter.liminf (fun i ↦ f i + c) F = Filter.liminf f F + c :=
(Monotone.map_limsInf_of_continuousAt (F := F.map f) (f := fun (x : R) ↦ x + c)
(fun _ _ h ↦ add_le_add_right h c) (continuous_add_right c).continuousAt cobdd bdd_below).symm
/-- `limsup (c - xᵢ) = c - liminf xᵢ`. -/
lemma limsup_const_sub (F : Filter ι) [AddCommSemigroup R] [Sub R] [ContinuousSub R] [OrderedSub R]
[AddLeftMono R] (f : ι → R) (c : R)
(cobdd : F.IsCoboundedUnder (· ≥ ·) f) (bdd_below : F.IsBoundedUnder (· ≥ ·) f) :
Filter.limsup (fun i ↦ c - f i) F = c - Filter.liminf f F := by
rcases F.eq_or_neBot with rfl | _
· simp only [liminf, limsInf, limsup, limsSup, map_bot, eventually_bot, Set.setOf_true]
simp only [IsCoboundedUnder, IsCobounded, map_bot, eventually_bot, true_implies] at cobdd
rcases cobdd with ⟨x, hx⟩
refine (csInf_le ?_ (Set.mem_univ _)).antisymm
(tsub_le_iff_tsub_le.1 (le_csSup ?_ (Set.mem_univ _)))
· refine ⟨x - x, mem_lowerBounds.2 fun y ↦ ?_⟩
simp only [Set.mem_univ, true_implies]
exact tsub_le_iff_tsub_le.1 (hx (x - y))
· refine ⟨x, mem_upperBounds.2 fun y ↦ ?_⟩
simp only [Set.mem_univ, hx y, implies_true]
· exact (Antitone.map_limsInf_of_continuousAt (F := F.map f) (f := fun (x : R) ↦ c - x)
(fun _ _ h ↦ tsub_le_tsub_left h c) (continuous_sub_left c).continuousAt cobdd bdd_below).symm
/-- `limsup (xᵢ - c) = (limsup xᵢ) - c`. -/
lemma limsup_sub_const (F : Filter ι) [AddCommSemigroup R] [Sub R] [ContinuousSub R] [OrderedSub R]
(f : ι → R) (c : R)
(bdd_above : F.IsBoundedUnder (· ≤ ·) f) (cobdd : F.IsCoboundedUnder (· ≤ ·) f) :
Filter.limsup (fun i ↦ f i - c) F = Filter.limsup f F - c := by
rcases F.eq_or_neBot with rfl | _
· have {a : R} : sInf Set.univ ≤ a := by
apply csInf_le _ (Set.mem_univ a)
simp only [IsCoboundedUnder, IsCobounded, map_bot, eventually_bot, true_implies] at cobdd
rcases cobdd with ⟨x, hx⟩
refine ⟨x, mem_lowerBounds.2 fun y ↦ ?_⟩
simp only [Set.mem_univ, hx y, implies_true]
simp only [limsup, limsSup, map_bot, eventually_bot, Set.setOf_true]
exact this.antisymm (tsub_le_iff_right.2 this)
· apply (Monotone.map_limsSup_of_continuousAt (F := F.map f) (f := fun (x : R) ↦ x - c) _ _).symm
· exact fun _ _ h ↦ tsub_le_tsub_right h c
· exact (continuous_sub_right c).continuousAt
/-- `liminf (c - xᵢ) = c - limsup xᵢ`. -/
lemma liminf_const_sub (F : Filter ι) [NeBot F] [AddCommSemigroup R] [Sub R] [ContinuousSub R]
[OrderedSub R] [AddLeftMono R] (f : ι → R) (c : R)
(bdd_above : F.IsBoundedUnder (· ≤ ·) f) (cobdd : F.IsCoboundedUnder (· ≤ ·) f) :
Filter.liminf (fun i ↦ c - f i) F = c - Filter.limsup f F :=
(Antitone.map_limsSup_of_continuousAt (F := F.map f) (f := fun (x : R) ↦ c - x)
(fun _ _ h ↦ tsub_le_tsub_left h c) (continuous_sub_left c).continuousAt bdd_above cobdd).symm
/-- `liminf (xᵢ - c) = (liminf xᵢ) - c`. -/
lemma liminf_sub_const (F : Filter ι) [NeBot F] [AddCommSemigroup R] [Sub R] [ContinuousSub R]
[OrderedSub R] (f : ι → R) (c : R)
(cobdd : F.IsCoboundedUnder (· ≥ ·) f) (bdd_below : F.IsBoundedUnder (· ≥ ·) f) :
Filter.liminf (fun i ↦ f i - c) F = Filter.liminf f F - c :=
(Monotone.map_limsInf_of_continuousAt (F := F.map f) (f := fun (x : R) ↦ x - c)
(fun _ _ h ↦ tsub_le_tsub_right h c) (continuous_sub_right c).continuousAt cobdd bdd_below).symm
end LiminfLimsupAddSub -- section
|
SFinite.lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import Mathlib.MeasureTheory.Measure.Typeclasses.Finite
/-!
# Classes for s-finite measures
We introduce the following typeclasses for measures:
* `SFinite μ`: the measure `μ` can be written as a countable sum of finite measures;
* `SigmaFinite μ`: there exists a countable collection of sets that cover `univ`
where `μ` is finite.
-/
namespace MeasureTheory
open Set Filter Function Measure MeasurableSpace NNReal ENNReal
variable {α β ι : Type*} {m0 : MeasurableSpace α} [MeasurableSpace β] {μ ν : Measure α}
{s t : Set α} {a : α}
section SFinite
/-- A measure is called s-finite if it is a countable sum of finite measures. -/
class SFinite (μ : Measure α) : Prop where
out' : ∃ m : ℕ → Measure α, (∀ n, IsFiniteMeasure (m n)) ∧ μ = Measure.sum m
/-- A sequence of finite measures such that `μ = sum (sfiniteSeq μ)` (see `sum_sfiniteSeq`). -/
noncomputable def sfiniteSeq (μ : Measure α) [h : SFinite μ] : ℕ → Measure α := h.1.choose
instance isFiniteMeasure_sfiniteSeq [h : SFinite μ] (n : ℕ) : IsFiniteMeasure (sfiniteSeq μ n) :=
h.1.choose_spec.1 n
lemma sum_sfiniteSeq (μ : Measure α) [h : SFinite μ] : sum (sfiniteSeq μ) = μ :=
h.1.choose_spec.2.symm
lemma sfiniteSeq_le (μ : Measure α) [SFinite μ] (n : ℕ) : sfiniteSeq μ n ≤ μ :=
(le_sum _ n).trans (sum_sfiniteSeq μ).le
instance : SFinite (0 : Measure α) := ⟨fun _ ↦ 0, inferInstance, by rw [Measure.sum_zero]⟩
@[simp]
lemma sfiniteSeq_zero (n : ℕ) : sfiniteSeq (0 : Measure α) n = 0 :=
bot_unique <| sfiniteSeq_le _ _
/-- A countable sum of finite measures is s-finite.
This lemma is superseded by the instance below. -/
lemma sfinite_sum_of_countable [Countable ι]
(m : ι → Measure α) [∀ n, IsFiniteMeasure (m n)] : SFinite (Measure.sum m) := by
classical
obtain ⟨f, hf⟩ : ∃ f : ι → ℕ, Function.Injective f := Countable.exists_injective_nat ι
refine ⟨_, fun n ↦ ?_, (sum_extend_zero hf m).symm⟩
rcases em (n ∈ range f) with ⟨i, rfl⟩ | hn
· rw [hf.extend_apply]
infer_instance
· rw [Function.extend_apply' _ _ _ hn, Pi.zero_apply]
infer_instance
instance [Countable ι] (m : ι → Measure α) [∀ n, SFinite (m n)] : SFinite (Measure.sum m) := by
change SFinite (Measure.sum (fun i ↦ m i))
simp_rw [← sum_sfiniteSeq (m _), Measure.sum_sum]
apply sfinite_sum_of_countable
instance [SFinite μ] [SFinite ν] : SFinite (μ + ν) := by
have : ∀ b : Bool, SFinite (cond b μ ν) := by simp [*]
simpa using inferInstanceAs (SFinite (.sum (cond · μ ν)))
instance [SFinite μ] (s : Set α) : SFinite (μ.restrict s) :=
⟨fun n ↦ (sfiniteSeq μ n).restrict s, fun n ↦ inferInstance,
by rw [← restrict_sum_of_countable, sum_sfiniteSeq]⟩
variable (μ) in
/-- For an s-finite measure `μ`, there exists a finite measure `ν`
such that each of `μ` and `ν` is absolutely continuous with respect to the other.
-/
theorem exists_isFiniteMeasure_absolutelyContinuous [SFinite μ] :
∃ ν : Measure α, IsFiniteMeasure ν ∧ μ ≪ ν ∧ ν ≪ μ := by
rcases ENNReal.exists_pos_tsum_mul_lt_of_countable top_ne_zero (sfiniteSeq μ · univ)
fun _ ↦ measure_ne_top _ _ with ⟨c, hc₀, hc⟩
have {s : Set α} : sum (fun n ↦ c n • sfiniteSeq μ n) s = 0 ↔ μ s = 0 := by
conv_rhs => rw [← sum_sfiniteSeq μ, sum_apply_of_countable]
simp [(hc₀ _).ne']
refine ⟨.sum fun n ↦ c n • sfiniteSeq μ n, ⟨?_⟩, fun _ ↦ this.1, fun _ ↦ this.2⟩
simpa [mul_comm] using hc
end SFinite
/-- A measure `μ` is called σ-finite if there is a countable collection of sets
`{ A i | i ∈ ℕ }` such that `μ (A i) < ∞` and `⋃ i, A i = s`. -/
class SigmaFinite {m0 : MeasurableSpace α} (μ : Measure α) : Prop where
out' : Nonempty (μ.FiniteSpanningSetsIn univ)
theorem sigmaFinite_iff : SigmaFinite μ ↔ Nonempty (μ.FiniteSpanningSetsIn univ) :=
⟨fun h => h.1, fun h => ⟨h⟩⟩
theorem SigmaFinite.out (h : SigmaFinite μ) : Nonempty (μ.FiniteSpanningSetsIn univ) :=
h.1
/-- If `μ` is σ-finite it has finite spanning sets in the collection of all measurable sets. -/
def Measure.toFiniteSpanningSetsIn (μ : Measure α) [h : SigmaFinite μ] :
μ.FiniteSpanningSetsIn { s | MeasurableSet s } where
set n := toMeasurable μ (h.out.some.set n)
set_mem _ := measurableSet_toMeasurable _ _
finite n := by
rw [measure_toMeasurable]
exact h.out.some.finite n
spanning := eq_univ_of_subset (iUnion_mono fun _ => subset_toMeasurable _ _) h.out.some.spanning
/-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite
measure using `Classical.choose`. This definition satisfies monotonicity in addition to all other
properties in `SigmaFinite`. -/
def spanningSets (μ : Measure α) [SigmaFinite μ] (i : ℕ) : Set α :=
Accumulate μ.toFiniteSpanningSetsIn.set i
theorem monotone_spanningSets (μ : Measure α) [SigmaFinite μ] : Monotone (spanningSets μ) :=
monotone_accumulate
@[gcongr]
lemma spanningSets_mono [SigmaFinite μ] {m n : ℕ} (hmn : m ≤ n) :
spanningSets μ m ⊆ spanningSets μ n := monotone_spanningSets _ hmn
theorem measurableSet_spanningSets (μ : Measure α) [SigmaFinite μ] (i : ℕ) :
MeasurableSet (spanningSets μ i) :=
MeasurableSet.iUnion fun j => MeasurableSet.iUnion fun _ => μ.toFiniteSpanningSetsIn.set_mem j
theorem measure_spanningSets_lt_top (μ : Measure α) [SigmaFinite μ] (i : ℕ) :
μ (spanningSets μ i) < ∞ :=
measure_biUnion_lt_top (finite_le_nat i) fun j _ => μ.toFiniteSpanningSetsIn.finite j
@[simp]
theorem iUnion_spanningSets (μ : Measure α) [SigmaFinite μ] : ⋃ i : ℕ, spanningSets μ i = univ := by
simp_rw [spanningSets, iUnion_accumulate, μ.toFiniteSpanningSetsIn.spanning]
theorem isCountablySpanning_spanningSets (μ : Measure α) [SigmaFinite μ] :
IsCountablySpanning (range (spanningSets μ)) :=
⟨spanningSets μ, mem_range_self, iUnion_spanningSets μ⟩
open scoped Classical in
/-- `spanningSetsIndex μ x` is the least `n : ℕ` such that `x ∈ spanningSets μ n`. -/
noncomputable def spanningSetsIndex (μ : Measure α) [SigmaFinite μ] (x : α) : ℕ :=
Nat.find <| iUnion_eq_univ_iff.1 (iUnion_spanningSets μ) x
open scoped Classical in
theorem measurableSet_spanningSetsIndex (μ : Measure α) [SigmaFinite μ] :
Measurable (spanningSetsIndex μ) :=
measurable_find _ <| measurableSet_spanningSets μ
open scoped Classical in
theorem preimage_spanningSetsIndex_singleton (μ : Measure α) [SigmaFinite μ] (n : ℕ) :
spanningSetsIndex μ ⁻¹' {n} = disjointed (spanningSets μ) n :=
preimage_find_eq_disjointed _ _ _
theorem spanningSetsIndex_eq_iff (μ : Measure α) [SigmaFinite μ] {x : α} {n : ℕ} :
spanningSetsIndex μ x = n ↔ x ∈ disjointed (spanningSets μ) n := by
convert Set.ext_iff.1 (preimage_spanningSetsIndex_singleton μ n) x
theorem mem_disjointed_spanningSetsIndex (μ : Measure α) [SigmaFinite μ] (x : α) :
x ∈ disjointed (spanningSets μ) (spanningSetsIndex μ x) :=
(spanningSetsIndex_eq_iff μ).1 rfl
theorem mem_spanningSetsIndex (μ : Measure α) [SigmaFinite μ] (x : α) :
x ∈ spanningSets μ (spanningSetsIndex μ x) :=
disjointed_subset _ _ (mem_disjointed_spanningSetsIndex μ x)
theorem mem_spanningSets_of_index_le (μ : Measure α) [SigmaFinite μ] (x : α) {n : ℕ}
(hn : spanningSetsIndex μ x ≤ n) : x ∈ spanningSets μ n :=
monotone_spanningSets μ hn (mem_spanningSetsIndex μ x)
theorem eventually_mem_spanningSets (μ : Measure α) [SigmaFinite μ] (x : α) :
∀ᶠ n in atTop, x ∈ spanningSets μ n :=
eventually_atTop.2 ⟨spanningSetsIndex μ x, fun _ => mem_spanningSets_of_index_le μ x⟩
lemma measure_singleton_lt_top [SigmaFinite μ] : μ {a} < ∞ :=
measure_lt_top_mono (singleton_subset_iff.2 <| mem_spanningSetsIndex ..)
(measure_spanningSets_lt_top _ _)
theorem sum_restrict_disjointed_spanningSets (μ ν : Measure α) [SigmaFinite ν] :
sum (fun n ↦ μ.restrict (disjointed (spanningSets ν) n)) = μ := by
rw [← restrict_iUnion (disjoint_disjointed _)
(MeasurableSet.disjointed (measurableSet_spanningSets _)),
iUnion_disjointed, iUnion_spanningSets, restrict_univ]
instance (priority := 100) [SigmaFinite μ] : SFinite μ := by
have : ∀ n, Fact (μ (disjointed (spanningSets μ) n) < ∞) :=
fun n ↦ ⟨(measure_mono (disjointed_subset _ _)).trans_lt (measure_spanningSets_lt_top μ n)⟩
exact ⟨⟨fun n ↦ μ.restrict (disjointed (spanningSets μ) n), fun n ↦ by infer_instance,
(sum_restrict_disjointed_spanningSets μ μ).symm⟩⟩
namespace Measure
/-- A set in a σ-finite space has zero measure if and only if its intersection with
all members of the countable family of finite measure spanning sets has zero measure. -/
theorem forall_measure_inter_spanningSets_eq_zero [MeasurableSpace α] {μ : Measure α}
[SigmaFinite μ] (s : Set α) : (∀ n, μ (s ∩ spanningSets μ n) = 0) ↔ μ s = 0 := by
nth_rw 2 [show s = ⋃ n, s ∩ spanningSets μ n by
rw [← inter_iUnion, iUnion_spanningSets, inter_univ] ]
rw [measure_iUnion_null_iff]
/-- A set in a σ-finite space has positive measure if and only if its intersection with
some member of the countable family of finite measure spanning sets has positive measure. -/
theorem exists_measure_inter_spanningSets_pos [MeasurableSpace α] {μ : Measure α} [SigmaFinite μ]
(s : Set α) : (∃ n, 0 < μ (s ∩ spanningSets μ n)) ↔ 0 < μ s := by
rw [← not_iff_not]
simp only [not_exists, not_lt, nonpos_iff_eq_zero]
exact forall_measure_inter_spanningSets_eq_zero s
/-- If the union of a.e.-disjoint null-measurable sets has finite measure, then there are only
finitely many members of the union whose measure exceeds any given positive number. -/
theorem finite_const_le_meas_of_disjoint_iUnion₀ {ι : Type*} [MeasurableSpace α] (μ : Measure α)
{ε : ℝ≥0∞} (ε_pos : 0 < ε) {As : ι → Set α} (As_mble : ∀ i : ι, NullMeasurableSet (As i) μ)
(As_disj : Pairwise (AEDisjoint μ on As)) (Union_As_finite : μ (⋃ i, As i) ≠ ∞) :
Set.Finite { i : ι | ε ≤ μ (As i) } :=
ENNReal.finite_const_le_of_tsum_ne_top
(ne_top_of_le_ne_top Union_As_finite (tsum_meas_le_meas_iUnion_of_disjoint₀ μ As_mble As_disj))
ε_pos.ne'
/-- If the union of disjoint measurable sets has finite measure, then there are only
finitely many members of the union whose measure exceeds any given positive number. -/
theorem finite_const_le_meas_of_disjoint_iUnion {ι : Type*} [MeasurableSpace α] (μ : Measure α)
{ε : ℝ≥0∞} (ε_pos : 0 < ε) {As : ι → Set α} (As_mble : ∀ i : ι, MeasurableSet (As i))
(As_disj : Pairwise (Disjoint on As)) (Union_As_finite : μ (⋃ i, As i) ≠ ∞) :
Set.Finite { i : ι | ε ≤ μ (As i) } :=
finite_const_le_meas_of_disjoint_iUnion₀ μ ε_pos (fun i ↦ (As_mble i).nullMeasurableSet)
(fun _ _ h ↦ Disjoint.aedisjoint (As_disj h)) Union_As_finite
/-- If all elements of an infinite set have measure uniformly separated from zero,
then the set has infinite measure. -/
theorem _root_.Set.Infinite.meas_eq_top [MeasurableSingletonClass α]
{s : Set α} (hs : s.Infinite) (h' : ∃ ε, ε ≠ 0 ∧ ∀ x ∈ s, ε ≤ μ {x}) : μ s = ∞ := top_unique <|
let ⟨ε, hne, hε⟩ := h'; have := hs.to_subtype
calc
∞ = ∑' _ : s, ε := (ENNReal.tsum_const_eq_top_of_ne_zero hne).symm
_ ≤ ∑' x : s, μ {x.1} := ENNReal.tsum_le_tsum fun x ↦ hε x x.2
_ ≤ μ (⋃ x : s, {x.1}) := tsum_meas_le_meas_iUnion_of_disjoint _
(fun _ ↦ MeasurableSet.singleton _) fun x y hne ↦ by simpa [Subtype.val_inj]
_ = μ s := by simp
/-- If the union of a.e.-disjoint null-measurable sets has finite measure, then there are only
countably many members of the union whose measure is positive. -/
theorem countable_meas_pos_of_disjoint_of_meas_iUnion_ne_top₀ {ι : Type*} {_ : MeasurableSpace α}
(μ : Measure α) {As : ι → Set α} (As_mble : ∀ i : ι, NullMeasurableSet (As i) μ)
(As_disj : Pairwise (AEDisjoint μ on As)) (Union_As_finite : μ (⋃ i, As i) ≠ ∞) :
Set.Countable { i : ι | 0 < μ (As i) } := by
set posmeas := { i : ι | 0 < μ (As i) } with posmeas_def
rcases exists_seq_strictAnti_tendsto' (zero_lt_one : (0 : ℝ≥0∞) < 1) with
⟨as, _, as_mem, as_lim⟩
set fairmeas := fun n : ℕ => { i : ι | as n ≤ μ (As i) }
have countable_union : posmeas = ⋃ n, fairmeas n := by
have fairmeas_eq : ∀ n, fairmeas n = (fun i => μ (As i)) ⁻¹' Ici (as n) := fun n => by
simp only [fairmeas]
rfl
simpa only [fairmeas_eq, posmeas_def, ← preimage_iUnion,
iUnion_Ici_eq_Ioi_of_lt_of_tendsto (fun n => (as_mem n).1) as_lim]
rw [countable_union]
refine countable_iUnion fun n => Finite.countable ?_
exact finite_const_le_meas_of_disjoint_iUnion₀ μ (as_mem n).1 As_mble As_disj Union_As_finite
/-- If the union of disjoint measurable sets has finite measure, then there are only
countably many members of the union whose measure is positive. -/
theorem countable_meas_pos_of_disjoint_of_meas_iUnion_ne_top {ι : Type*} {_ : MeasurableSpace α}
(μ : Measure α) {As : ι → Set α} (As_mble : ∀ i : ι, MeasurableSet (As i))
(As_disj : Pairwise (Disjoint on As)) (Union_As_finite : μ (⋃ i, As i) ≠ ∞) :
Set.Countable { i : ι | 0 < μ (As i) } :=
countable_meas_pos_of_disjoint_of_meas_iUnion_ne_top₀ μ (fun i ↦ (As_mble i).nullMeasurableSet)
((fun _ _ h ↦ Disjoint.aedisjoint (As_disj h))) Union_As_finite
/-- In an s-finite space, among disjoint null-measurable sets, only countably many can have positive
measure. -/
theorem countable_meas_pos_of_disjoint_iUnion₀ {ι : Type*} {_ : MeasurableSpace α} {μ : Measure α}
[SFinite μ] {As : ι → Set α} (As_mble : ∀ i : ι, NullMeasurableSet (As i) μ)
(As_disj : Pairwise (AEDisjoint μ on As)) :
Set.Countable { i : ι | 0 < μ (As i) } := by
rw [← sum_sfiniteSeq μ] at As_disj As_mble ⊢
have obs : { i : ι | 0 < sum (sfiniteSeq μ) (As i) }
⊆ ⋃ n, { i : ι | 0 < sfiniteSeq μ n (As i) } := by
intro i hi
by_contra con
simp only [mem_iUnion, mem_setOf_eq, not_exists, not_lt, nonpos_iff_eq_zero] at *
rw [sum_apply₀] at hi
· simp_rw [con] at hi
simp at hi
· exact As_mble i
apply Countable.mono obs
refine countable_iUnion fun n ↦ ?_
apply countable_meas_pos_of_disjoint_of_meas_iUnion_ne_top₀
· exact fun i ↦ (As_mble i).mono (le_sum _ _)
· exact fun i j hij ↦ AEDisjoint.of_le (As_disj hij) (le_sum _ _)
· exact measure_ne_top _ (⋃ i, As i)
/-- In an s-finite space, among disjoint measurable sets, only countably many can have positive
measure. -/
theorem countable_meas_pos_of_disjoint_iUnion {ι : Type*} {_ : MeasurableSpace α} {μ : Measure α}
[SFinite μ] {As : ι → Set α} (As_mble : ∀ i : ι, MeasurableSet (As i))
(As_disj : Pairwise (Disjoint on As)) : Set.Countable { i : ι | 0 < μ (As i) } :=
countable_meas_pos_of_disjoint_iUnion₀ (fun i ↦ (As_mble i).nullMeasurableSet)
((fun _ _ h ↦ Disjoint.aedisjoint (As_disj h)))
theorem countable_meas_level_set_pos₀ {α β : Type*} {_ : MeasurableSpace α} {μ : Measure α}
[SFinite μ] [MeasurableSpace β] [MeasurableSingletonClass β] {g : α → β}
(g_mble : NullMeasurable g μ) : Set.Countable { t : β | 0 < μ { a : α | g a = t } } := by
have level_sets_disjoint : Pairwise (Disjoint on fun t : β => { a : α | g a = t }) :=
fun s t hst => Disjoint.preimage g (disjoint_singleton.mpr hst)
exact Measure.countable_meas_pos_of_disjoint_iUnion₀
(fun b => g_mble (‹MeasurableSingletonClass β›.measurableSet_singleton b))
((fun _ _ h ↦ Disjoint.aedisjoint (level_sets_disjoint h)))
theorem countable_meas_level_set_pos {α β : Type*} {_ : MeasurableSpace α} {μ : Measure α}
[SFinite μ] [MeasurableSpace β] [MeasurableSingletonClass β] {g : α → β}
(g_mble : Measurable g) : Set.Countable { t : β | 0 < μ { a : α | g a = t } } :=
countable_meas_level_set_pos₀ g_mble.nullMeasurable
/-- If a measure `μ` is the sum of a countable family `mₙ`, and a set `t` has finite measure for
each `mₙ`, then its measurable superset `toMeasurable μ t` (which has the same measure as `t`)
satisfies, for any measurable set `s`, the equality `μ (toMeasurable μ t ∩ s) = μ (t ∩ s)`. -/
theorem measure_toMeasurable_inter_of_sum {s : Set α} (hs : MeasurableSet s) {t : Set α}
{m : ℕ → Measure α} (hv : ∀ n, m n t ≠ ∞) (hμ : μ = sum m) :
μ (toMeasurable μ t ∩ s) = μ (t ∩ s) := by
-- we show that there is a measurable superset of `t` satisfying the conclusion for any
-- measurable set `s`. It is built for each measure `mₙ` using `toMeasurable`
-- (which is well behaved for finite measure sets thanks to `measure_toMeasurable_inter`), and
-- then taking the intersection over `n`.
have A : ∃ t', t' ⊇ t ∧ MeasurableSet t' ∧ ∀ u, MeasurableSet u → μ (t' ∩ u) = μ (t ∩ u) := by
let w n := toMeasurable (m n) t
have T : t ⊆ ⋂ n, w n := subset_iInter (fun i ↦ subset_toMeasurable (m i) t)
have M : MeasurableSet (⋂ n, w n) :=
MeasurableSet.iInter (fun i ↦ measurableSet_toMeasurable (m i) t)
refine ⟨⋂ n, w n, T, M, fun u hu ↦ ?_⟩
refine le_antisymm ?_ (by gcongr)
rw [hμ, sum_apply _ (M.inter hu)]
apply le_trans _ (le_sum_apply _ _)
apply ENNReal.tsum_le_tsum (fun i ↦ ?_)
calc
m i ((⋂ n, w n) ∩ u) ≤ m i (w i ∩ u) := by gcongr; apply iInter_subset
_ = m i (t ∩ u) := measure_toMeasurable_inter hu (hv i)
-- thanks to the definition of `toMeasurable`, the previous property will also be shared
-- by `toMeasurable μ t`, which is enough to conclude the proof.
rw [toMeasurable]
split_ifs with ht
· apply measure_congr
exact ae_eq_set_inter ht.choose_spec.2.2 (ae_eq_refl _)
· exact A.choose_spec.2.2 s hs
/-- If a set `t` is covered by a countable family of finite measure sets, then its measurable
superset `toMeasurable μ t` (which has the same measure as `t`) satisfies,
for any measurable set `s`, the equality `μ (toMeasurable μ t ∩ s) = μ (t ∩ s)`. -/
theorem measure_toMeasurable_inter_of_cover {s : Set α} (hs : MeasurableSet s) {t : Set α}
{v : ℕ → Set α} (hv : t ⊆ ⋃ n, v n) (h'v : ∀ n, μ (t ∩ v n) ≠ ∞) :
μ (toMeasurable μ t ∩ s) = μ (t ∩ s) := by
-- we show that there is a measurable superset of `t` satisfying the conclusion for any
-- measurable set `s`. It is built on each member of a spanning family using `toMeasurable`
-- (which is well behaved for finite measure sets thanks to `measure_toMeasurable_inter`), and
-- the desired property passes to the union.
have A : ∃ t', t' ⊇ t ∧ MeasurableSet t' ∧ ∀ u, MeasurableSet u → μ (t' ∩ u) = μ (t ∩ u) := by
let w n := toMeasurable μ (t ∩ v n)
have hw : ∀ n, μ (w n) < ∞ := by
intro n
simp_rw [w, measure_toMeasurable]
exact (h'v n).lt_top
set t' := ⋃ n, toMeasurable μ (t ∩ disjointed w n) with ht'
have tt' : t ⊆ t' :=
calc
t ⊆ ⋃ n, t ∩ disjointed w n := by
rw [← inter_iUnion, iUnion_disjointed, inter_iUnion]
intro x hx
rcases mem_iUnion.1 (hv hx) with ⟨n, hn⟩
refine mem_iUnion.2 ⟨n, ?_⟩
have : x ∈ t ∩ v n := ⟨hx, hn⟩
exact ⟨hx, subset_toMeasurable μ _ this⟩
_ ⊆ ⋃ n, toMeasurable μ (t ∩ disjointed w n) :=
iUnion_mono fun n => subset_toMeasurable _ _
refine ⟨t', tt', MeasurableSet.iUnion fun n => measurableSet_toMeasurable μ _, fun u hu => ?_⟩
apply le_antisymm _ (by gcongr)
calc
μ (t' ∩ u) ≤ ∑' n, μ (toMeasurable μ (t ∩ disjointed w n) ∩ u) := by
rw [ht', iUnion_inter]
exact measure_iUnion_le _
_ = ∑' n, μ (t ∩ disjointed w n ∩ u) := by
congr 1
ext1 n
apply measure_toMeasurable_inter hu
apply ne_of_lt
calc
μ (t ∩ disjointed w n) ≤ μ (t ∩ w n) := by
gcongr
exact disjointed_le w n
_ ≤ μ (w n) := measure_mono inter_subset_right
_ < ∞ := hw n
_ = ∑' n, μ.restrict (t ∩ u) (disjointed w n) := by
congr 1
ext1 n
rw [restrict_apply, inter_comm t _, inter_assoc]
refine MeasurableSet.disjointed (fun n => ?_) n
exact measurableSet_toMeasurable _ _
_ = μ.restrict (t ∩ u) (⋃ n, disjointed w n) := by
rw [measure_iUnion]
· exact disjoint_disjointed _
· intro i
refine MeasurableSet.disjointed (fun n => ?_) i
exact measurableSet_toMeasurable _ _
_ ≤ μ.restrict (t ∩ u) univ := measure_mono (subset_univ _)
_ = μ (t ∩ u) := by rw [restrict_apply MeasurableSet.univ, univ_inter]
-- thanks to the definition of `toMeasurable`, the previous property will also be shared
-- by `toMeasurable μ t`, which is enough to conclude the proof.
rw [toMeasurable]
split_ifs with ht
· apply measure_congr
exact ae_eq_set_inter ht.choose_spec.2.2 (ae_eq_refl _)
· exact A.choose_spec.2.2 s hs
theorem restrict_toMeasurable_of_cover {s : Set α} {v : ℕ → Set α} (hv : s ⊆ ⋃ n, v n)
(h'v : ∀ n, μ (s ∩ v n) ≠ ∞) : μ.restrict (toMeasurable μ s) = μ.restrict s :=
ext fun t ht => by
simp only [restrict_apply ht, inter_comm t, measure_toMeasurable_inter_of_cover ht hv h'v]
/-- The measurable superset `toMeasurable μ t` of `t` (which has the same measure as `t`)
satisfies, for any measurable set `s`, the equality `μ (toMeasurable μ t ∩ s) = μ (t ∩ s)`.
This only holds when `μ` is s-finite -- for example for σ-finite measures. For a version without
this assumption (but requiring that `t` has finite measure), see `measure_toMeasurable_inter`. -/
theorem measure_toMeasurable_inter_of_sFinite [SFinite μ] {s : Set α} (hs : MeasurableSet s)
(t : Set α) : μ (toMeasurable μ t ∩ s) = μ (t ∩ s) :=
measure_toMeasurable_inter_of_sum hs (fun _ ↦ measure_ne_top _ t) (sum_sfiniteSeq μ).symm
@[simp]
theorem restrict_toMeasurable_of_sFinite [SFinite μ] (s : Set α) :
μ.restrict (toMeasurable μ s) = μ.restrict s :=
ext fun t ht => by
rw [restrict_apply ht, inter_comm t, measure_toMeasurable_inter_of_sFinite ht,
restrict_apply ht, inter_comm t]
/-- Auxiliary lemma for `iSup_restrict_spanningSets`. -/
theorem iSup_restrict_spanningSets_of_measurableSet [SigmaFinite μ] (hs : MeasurableSet s) :
⨆ i, μ.restrict (spanningSets μ i) s = μ s :=
calc
⨆ i, μ.restrict (spanningSets μ i) s = μ.restrict (⋃ i, spanningSets μ i) s :=
(restrict_iUnion_apply_eq_iSup (monotone_spanningSets μ).directed_le hs).symm
_ = μ s := by rw [iUnion_spanningSets, restrict_univ]
theorem iSup_restrict_spanningSets [SigmaFinite μ] (s : Set α) :
⨆ i, μ.restrict (spanningSets μ i) s = μ s := by
rw [← measure_toMeasurable s,
← iSup_restrict_spanningSets_of_measurableSet (measurableSet_toMeasurable _ _)]
simp_rw [restrict_apply' (measurableSet_spanningSets μ _), Set.inter_comm s,
← restrict_apply (measurableSet_spanningSets μ _), ← restrict_toMeasurable_of_sFinite s,
restrict_apply (measurableSet_spanningSets μ _), Set.inter_comm _ (toMeasurable μ s)]
/-- In a σ-finite space, any measurable set of measure `> r` contains a measurable subset of
finite measure `> r`. -/
theorem exists_subset_measure_lt_top [SigmaFinite μ] {r : ℝ≥0∞} (hs : MeasurableSet s)
(h's : r < μ s) : ∃ t, MeasurableSet t ∧ t ⊆ s ∧ r < μ t ∧ μ t < ∞ := by
rw [← iSup_restrict_spanningSets,
@lt_iSup_iff _ _ _ r fun i : ℕ => μ.restrict (spanningSets μ i) s] at h's
rcases h's with ⟨n, hn⟩
simp only [restrict_apply hs] at hn
refine
⟨s ∩ spanningSets μ n, hs.inter (measurableSet_spanningSets _ _), inter_subset_left, hn, ?_⟩
exact (measure_mono inter_subset_right).trans_lt (measure_spanningSets_lt_top _ _)
namespace FiniteSpanningSetsIn
variable {C D : Set (Set α)}
/-- If `μ` has finite spanning sets in `C` and `C ∩ {s | μ s < ∞} ⊆ D` then `μ` has finite spanning
sets in `D`. -/
protected def mono' (h : μ.FiniteSpanningSetsIn C) (hC : C ∩ { s | μ s < ∞ } ⊆ D) :
μ.FiniteSpanningSetsIn D :=
⟨h.set, fun i => hC ⟨h.set_mem i, h.finite i⟩, h.finite, h.spanning⟩
/-- If `μ` has finite spanning sets in `C` and `C ⊆ D` then `μ` has finite spanning sets in `D`. -/
protected def mono (h : μ.FiniteSpanningSetsIn C) (hC : C ⊆ D) : μ.FiniteSpanningSetsIn D :=
h.mono' fun _s hs => hC hs.1
/-- If `μ` has finite spanning sets in the collection of measurable sets `C`, then `μ` is σ-finite.
-/
protected theorem sigmaFinite (h : μ.FiniteSpanningSetsIn C) : SigmaFinite μ :=
⟨⟨h.mono <| subset_univ C⟩⟩
/-- An extensionality for measures. It is `ext_of_generateFrom_of_iUnion` formulated in terms of
`FiniteSpanningSetsIn`. -/
protected theorem ext {ν : Measure α} {C : Set (Set α)} (hA : ‹_› = generateFrom C)
(hC : IsPiSystem C) (h : μ.FiniteSpanningSetsIn C) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν :=
ext_of_generateFrom_of_iUnion C _ hA hC h.spanning h.set_mem (fun i => (h.finite i).ne) h_eq
protected theorem isCountablySpanning (h : μ.FiniteSpanningSetsIn C) : IsCountablySpanning C :=
⟨h.set, h.set_mem, h.spanning⟩
end FiniteSpanningSetsIn
theorem sigmaFinite_of_countable {S : Set (Set α)} (hc : S.Countable) (hμ : ∀ s ∈ S, μ s < ∞)
(hU : ⋃₀ S = univ) : SigmaFinite μ := by
obtain ⟨s, hμ, hs⟩ : ∃ s : ℕ → Set α, (∀ n, μ (s n) < ∞) ∧ ⋃ n, s n = univ :=
(@exists_seq_cover_iff_countable _ (fun x => μ x < ∞) ⟨∅, by simp⟩).2 ⟨S, hc, hμ, hU⟩
exact ⟨⟨⟨fun n => s n, fun _ => trivial, hμ, hs⟩⟩⟩
/-- Given measures `μ`, `ν` where `ν ≤ μ`, `FiniteSpanningSetsIn.ofLe` provides the induced
`FiniteSpanningSet` with respect to `ν` from a `FiniteSpanningSet` with respect to `μ`. -/
def FiniteSpanningSetsIn.ofLE (h : ν ≤ μ) {C : Set (Set α)} (S : μ.FiniteSpanningSetsIn C) :
ν.FiniteSpanningSetsIn C where
set := S.set
set_mem := S.set_mem
finite n := lt_of_le_of_lt (le_iff'.1 h _) (S.finite n)
spanning := S.spanning
theorem sigmaFinite_of_le (μ : Measure α) [hs : SigmaFinite μ] (h : ν ≤ μ) : SigmaFinite ν :=
⟨hs.out.map <| FiniteSpanningSetsIn.ofLE h⟩
@[simp] lemma add_right_inj (μ ν₁ ν₂ : Measure α) [SigmaFinite μ] :
μ + ν₁ = μ + ν₂ ↔ ν₁ = ν₂ := by
refine ⟨fun h ↦ ?_, fun h ↦ by rw [h]⟩
rw [ext_iff_of_iUnion_eq_univ (iUnion_spanningSets μ)]
intro i
ext s hs
rw [← ENNReal.add_right_inj (measure_mono s.inter_subset_right |>.trans_lt <|
measure_spanningSets_lt_top μ i).ne]
simp only [ext_iff', coe_add, Pi.add_apply] at h
simp [hs, h]
@[simp] lemma add_left_inj (μ ν₁ ν₂ : Measure α) [SigmaFinite μ] :
ν₁ + μ = ν₂ + μ ↔ ν₁ = ν₂ := by rw [add_comm _ μ, add_comm _ μ, μ.add_right_inj]
end Measure
/-- Every finite measure is σ-finite. -/
instance (priority := 100) IsFiniteMeasure.toSigmaFinite {_m0 : MeasurableSpace α} (μ : Measure α)
[IsFiniteMeasure μ] : SigmaFinite μ :=
⟨⟨⟨fun _ => univ, fun _ => trivial, fun _ => measure_lt_top μ _, iUnion_const _⟩⟩⟩
/-- A measure on a countable space is sigma-finite iff it gives finite mass to every singleton.
See `measure_singleton_lt_top` for the forward direction without the countability assumption. -/
lemma Measure.sigmaFinite_iff_measure_singleton_lt_top [Countable α] :
SigmaFinite μ ↔ ∀ a, μ {a} < ∞ where
mp _ a := measure_singleton_lt_top
mpr hμ := by
cases isEmpty_or_nonempty α
· rw [Subsingleton.elim μ 0]
infer_instance
· obtain ⟨f, hf⟩ := exists_surjective_nat α
exact ⟨⟨⟨fun n ↦ {f n}, by simp, by simpa [hf.forall] using hμ, by simp [hf.range_eq]⟩⟩⟩
theorem sigmaFinite_bot_iff (μ : @Measure α ⊥) : SigmaFinite μ ↔ IsFiniteMeasure μ := by
refine ⟨fun h => ⟨?_⟩, fun h => by infer_instance⟩
haveI : SigmaFinite μ := h
let s := spanningSets μ
have hs_univ : ⋃ i, s i = Set.univ := iUnion_spanningSets μ
have hs_meas : ∀ i, MeasurableSet[⊥] (s i) := measurableSet_spanningSets μ
simp_rw [MeasurableSpace.measurableSet_bot_iff] at hs_meas
by_cases h_univ_empty : (Set.univ : Set α) = ∅
· rw [h_univ_empty, measure_empty]
exact ENNReal.zero_ne_top.lt_top
obtain ⟨i, hsi⟩ : ∃ i, s i = Set.univ := by
by_contra! h_not_univ
have h_empty : ∀ i, s i = ∅ := by simpa [h_not_univ] using hs_meas
simp only [h_empty, iUnion_empty] at hs_univ
exact h_univ_empty hs_univ.symm
rw [← hsi]
exact measure_spanningSets_lt_top μ i
instance Restrict.sigmaFinite (μ : Measure α) [SigmaFinite μ] (s : Set α) :
SigmaFinite (μ.restrict s) := by
refine ⟨⟨⟨spanningSets μ, fun _ => trivial, fun i => ?_, iUnion_spanningSets μ⟩⟩⟩
rw [Measure.restrict_apply (measurableSet_spanningSets μ i)]
exact (measure_mono inter_subset_left).trans_lt (measure_spanningSets_lt_top μ i)
instance sum.sigmaFinite {ι} [Finite ι] (μ : ι → Measure α) [∀ i, SigmaFinite (μ i)] :
SigmaFinite (sum μ) := by
cases nonempty_fintype ι
have : ∀ n, MeasurableSet (⋂ i : ι, spanningSets (μ i) n) := fun n =>
MeasurableSet.iInter fun i => measurableSet_spanningSets (μ i) n
refine ⟨⟨⟨fun n => ⋂ i, spanningSets (μ i) n, fun _ => trivial, fun n => ?_, ?_⟩⟩⟩
· rw [sum_apply _ (this n), tsum_fintype, ENNReal.sum_lt_top]
rintro i -
exact (measure_mono <| iInter_subset _ i).trans_lt (measure_spanningSets_lt_top (μ i) n)
· rw [iUnion_iInter_of_monotone]
· simp_rw [iUnion_spanningSets, iInter_univ]
exact fun i => monotone_spanningSets (μ i)
instance Add.sigmaFinite (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] :
SigmaFinite (μ + ν) := by
rw [← sum_cond]
refine @sum.sigmaFinite _ _ _ _ _ (Bool.rec ?_ ?_) <;> simpa
instance SMul.sigmaFinite {μ : Measure α} [SigmaFinite μ] (c : ℝ≥0) :
MeasureTheory.SigmaFinite (c • μ) where
out' :=
⟨{ set := spanningSets μ
set_mem := fun _ ↦ trivial
finite := by
intro i
simp only [Measure.coe_smul, Pi.smul_apply, nnreal_smul_coe_apply]
exact ENNReal.mul_lt_top ENNReal.coe_lt_top (measure_spanningSets_lt_top μ i)
spanning := iUnion_spanningSets μ }⟩
instance [SigmaFinite (μ.restrict s)] [SigmaFinite (μ.restrict t)] :
SigmaFinite (μ.restrict (s ∪ t)) := sigmaFinite_of_le _ (restrict_union_le _ _)
instance [SigmaFinite (μ.restrict s)] : SigmaFinite (μ.restrict (s ∩ t)) :=
sigmaFinite_of_le (μ.restrict s) (restrict_mono_ae (ae_of_all _ Set.inter_subset_left))
instance [SigmaFinite (μ.restrict t)] : SigmaFinite (μ.restrict (s ∩ t)) :=
sigmaFinite_of_le (μ.restrict t) (restrict_mono_ae (ae_of_all _ Set.inter_subset_right))
theorem SigmaFinite.of_map (μ : Measure α) {f : α → β} (hf : AEMeasurable f μ)
(h : SigmaFinite (μ.map f)) : SigmaFinite μ :=
⟨⟨⟨fun n => f ⁻¹' spanningSets (μ.map f) n, fun _ => trivial, fun n => by
simp only [← map_apply_of_aemeasurable hf, measurableSet_spanningSets,
measure_spanningSets_lt_top],
by rw [← preimage_iUnion, iUnion_spanningSets, preimage_univ]⟩⟩⟩
lemma _root_.MeasurableEmbedding.sigmaFinite_map {f : α → β} (hf : MeasurableEmbedding f)
[SigmaFinite μ] :
SigmaFinite (μ.map f) := by
refine ⟨fun n ↦ f '' (spanningSets μ n) ∪ (Set.range f)ᶜ, by simp, fun n ↦ ?_, ?_⟩
· rw [hf.map_apply, Set.preimage_union]
simp only [Set.preimage_compl, Set.preimage_range, Set.compl_univ, Set.union_empty,
Set.preimage_image_eq _ hf.injective]
exact measure_spanningSets_lt_top μ n
· rw [← Set.iUnion_union, ← Set.image_iUnion, iUnion_spanningSets,
Set.image_univ, Set.union_compl_self]
theorem _root_.MeasurableEquiv.sigmaFinite_map (f : α ≃ᵐ β) [SigmaFinite μ] :
SigmaFinite (μ.map f) := f.measurableEmbedding.sigmaFinite_map
/-- Similar to `ae_of_forall_measure_lt_top_ae_restrict`, but where you additionally get the
hypothesis that another σ-finite measure has finite values on `s`. -/
theorem ae_of_forall_measure_lt_top_ae_restrict' {μ : Measure α} (ν : Measure α) [SigmaFinite μ]
[SigmaFinite ν] (P : α → Prop)
(h : ∀ s, MeasurableSet s → μ s < ∞ → ν s < ∞ → ∀ᵐ x ∂μ.restrict s, P x) : ∀ᵐ x ∂μ, P x := by
have : ∀ n, ∀ᵐ x ∂μ, x ∈ spanningSets (μ + ν) n → P x := by
intro n
have := h
(spanningSets (μ + ν) n) (measurableSet_spanningSets _ _)
((self_le_add_right _ _).trans_lt (measure_spanningSets_lt_top (μ + ν) _))
((self_le_add_left _ _).trans_lt (measure_spanningSets_lt_top (μ + ν) _))
exact (ae_restrict_iff' (measurableSet_spanningSets _ _)).mp this
filter_upwards [ae_all_iff.2 this] with _ hx using hx _ (mem_spanningSetsIndex _ _)
/-- To prove something for almost all `x` w.r.t. a σ-finite measure, it is sufficient to show that
this holds almost everywhere in sets where the measure has finite value. -/
theorem ae_of_forall_measure_lt_top_ae_restrict {μ : Measure α} [SigmaFinite μ] (P : α → Prop)
(h : ∀ s, MeasurableSet s → μ s < ∞ → ∀ᵐ x ∂μ.restrict s, P x) : ∀ᵐ x ∂μ, P x :=
ae_of_forall_measure_lt_top_ae_restrict' μ P fun s hs h2s _ => h s hs h2s
instance (priority := 100) SigmaFinite.of_isFiniteMeasureOnCompacts [TopologicalSpace α]
[SigmaCompactSpace α] (μ : Measure α) [IsFiniteMeasureOnCompacts μ] : SigmaFinite μ :=
⟨⟨{ set := compactCovering α
set_mem := fun _ => trivial
finite := fun n => (isCompact_compactCovering α n).measure_lt_top
spanning := iUnion_compactCovering α }⟩⟩
-- see Note [lower instance priority]
instance (priority := 100) sigmaFinite_of_locallyFinite [TopologicalSpace α]
[SecondCountableTopology α] [IsLocallyFiniteMeasure μ] : SigmaFinite μ := by
choose s hsx hsμ using μ.finiteAt_nhds
rcases TopologicalSpace.countable_cover_nhds hsx with ⟨t, htc, htU⟩
refine Measure.sigmaFinite_of_countable (htc.image s) (forall_mem_image.2 fun x _ => hsμ x) ?_
rwa [sUnion_image]
namespace Measure
section disjointed
/-- Given `S : μ.FiniteSpanningSetsIn {s | MeasurableSet s}`,
`FiniteSpanningSetsIn.disjointed` provides a `FiniteSpanningSetsIn {s | MeasurableSet s}`
such that its underlying sets are pairwise disjoint. -/
protected def FiniteSpanningSetsIn.disjointed {μ : Measure α}
(S : μ.FiniteSpanningSetsIn { s | MeasurableSet s }) :
μ.FiniteSpanningSetsIn { s | MeasurableSet s } :=
⟨disjointed S.set, MeasurableSet.disjointed S.set_mem, fun n =>
lt_of_le_of_lt (measure_mono (disjointed_subset S.set n)) (S.finite _),
S.spanning ▸ iUnion_disjointed⟩
theorem FiniteSpanningSetsIn.disjointed_set_eq {μ : Measure α}
(S : μ.FiniteSpanningSetsIn { s | MeasurableSet s }) : S.disjointed.set = disjointed S.set :=
rfl
theorem exists_eq_disjoint_finiteSpanningSetsIn (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] :
∃ (S : μ.FiniteSpanningSetsIn { s | MeasurableSet s })
(T : ν.FiniteSpanningSetsIn { s | MeasurableSet s }),
S.set = T.set ∧ Pairwise (Disjoint on S.set) :=
let S := (μ + ν).toFiniteSpanningSetsIn.disjointed
⟨S.ofLE (Measure.le_add_right le_rfl), S.ofLE (Measure.le_add_left le_rfl), rfl,
disjoint_disjointed _⟩
end disjointed
end Measure
end MeasureTheory
|
CategoryWithCofibrations.lean
|
/-
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.MorphismProperty.Basic
/-!
# Categories with classes of fibrations, cofibrations, weak equivalences
We introduce typeclasses `CategoryWithFibrations`, `CategoryWithCofibrations` and
`CategoryWithWeakEquivalences` to express that a category `C` is equipped with
classes of morphisms named "fibrations", "cofibrations" or "weak equivalences".
-/
universe v u
namespace HomotopicalAlgebra
open CategoryTheory
variable (C : Type u) [Category.{v} C]
/-- A category with fibrations is a category equipped with
a class of morphisms named "fibrations". -/
class CategoryWithFibrations where
/-- the class of fibrations -/
fibrations : MorphismProperty C
/-- A category with cofibrations is a category equipped with
a class of morphisms named "cofibrations". -/
class CategoryWithCofibrations where
/-- the class of cofibrations -/
cofibrations : MorphismProperty C
/-- A category with weak equivalences is a category equipped with
a class of morphisms named "weak equivalences". -/
class CategoryWithWeakEquivalences where
/-- the class of weak equivalences -/
weakEquivalences : MorphismProperty C
variable {X Y : C} (f : X ⟶ Y)
section Fib
variable [CategoryWithFibrations C]
/-- The class of fibrations in a category with fibrations. -/
def fibrations : MorphismProperty C := CategoryWithFibrations.fibrations
variable {C}
/-- A morphism `f` satisfies `[Fibration f]` if it belongs to `fibrations C`. -/
@[mk_iff]
class Fibration : Prop where
mem : fibrations C f
lemma mem_fibrations [Fibration f] : fibrations C f := Fibration.mem
end Fib
section Cof
variable [CategoryWithCofibrations C]
/-- The class of cofibrations in a category with cofibrations. -/
def cofibrations : MorphismProperty C := CategoryWithCofibrations.cofibrations
variable {C}
/-- A morphism `f` satisfies `[Cofibration f]` if it belongs to `cofibrations C`. -/
@[mk_iff]
class Cofibration : Prop where
mem : cofibrations C f
lemma mem_cofibrations [Cofibration f] : cofibrations C f := Cofibration.mem
end Cof
section W
variable [CategoryWithWeakEquivalences C]
/-- The class of weak equivalences in a category with weak equivalences. -/
def weakEquivalences : MorphismProperty C := CategoryWithWeakEquivalences.weakEquivalences
variable {C}
/-- A morphism `f` satisfies `[WeakEquivalence f]` if it belongs to `weakEquivalences C`. -/
@[mk_iff]
class WeakEquivalence : Prop where
mem : weakEquivalences C f
lemma mem_weakEquivalences [WeakEquivalence f] : weakEquivalences C f := WeakEquivalence.mem
end W
section TrivFib
variable [CategoryWithFibrations C] [CategoryWithWeakEquivalences C]
/-- A trivial fibration is a morphism that is both a fibration and a weak equivalence. -/
def trivialFibrations : MorphismProperty C := fibrations C ⊓ weakEquivalences C
lemma trivialFibrations_sub_fibrations : trivialFibrations C ≤ fibrations C :=
fun _ _ _ hf ↦ hf.1
lemma trivialFibrations_sub_weakEquivalences : trivialFibrations C ≤ weakEquivalences C :=
fun _ _ _ hf ↦ hf.2
variable {C}
lemma mem_trivialFibrations [Fibration f] [WeakEquivalence f] :
trivialFibrations C f :=
⟨mem_fibrations f, mem_weakEquivalences f⟩
lemma mem_trivialFibrations_iff :
trivialFibrations C f ↔ Fibration f ∧ WeakEquivalence f := by
rw [fibration_iff, weakEquivalence_iff]
rfl
end TrivFib
section TrivCof
variable [CategoryWithCofibrations C] [CategoryWithWeakEquivalences C]
/-- A trivial cofibration is a morphism that is both a cofibration and a weak equivalence. -/
def trivialCofibrations : MorphismProperty C := cofibrations C ⊓ weakEquivalences C
lemma trivialCofibrations_sub_cofibrations : trivialCofibrations C ≤ cofibrations C :=
fun _ _ _ hf ↦ hf.1
lemma trivialCofibrations_sub_weakEquivalences : trivialCofibrations C ≤ weakEquivalences C :=
fun _ _ _ hf ↦ hf.2
variable {C}
lemma mem_trivialCofibrations [Cofibration f] [WeakEquivalence f] :
trivialCofibrations C f :=
⟨mem_cofibrations f, mem_weakEquivalences f⟩
lemma mem_trivialCofibrations_iff :
trivialCofibrations C f ↔ Cofibration f ∧ WeakEquivalence f := by
rw [cofibration_iff, weakEquivalence_iff]
rfl
end TrivCof
end HomotopicalAlgebra
|
Defs.lean
|
/-
Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Kurniadi Angdinata
-/
import Mathlib.RingTheory.Ideal.Maximal
/-!
# Maximal spectrum of a commutative (semi)ring
The maximal spectrum of a commutative (semi)ring is the type of all maximal ideals.
It is naturally a subset of the prime spectrum endowed with the subspace topology.
## Main definitions
* `MaximalSpectrum R`: The maximal spectrum of a commutative (semi)ring `R`,
i.e., the set of all maximal ideals of `R`.
-/
/-- The maximal spectrum of a commutative (semi)ring `R` is the type of all
maximal ideals of `R`. -/
@[ext]
structure MaximalSpectrum (R : Type*) [CommSemiring R] where
asIdeal : Ideal R
isMaximal : asIdeal.IsMaximal
attribute [instance] MaximalSpectrum.isMaximal
|
qpoly.v
|
From HB Require Import structures.
From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice.
From mathcomp Require Import fintype tuple bigop binomial finset finfun ssralg.
From mathcomp Require Import countalg finalg poly polydiv perm fingroup matrix.
From mathcomp Require Import mxalgebra mxpoly vector countalg.
(******************************************************************************)
(* This file defines the algebras R[X]/<p> and their theory. *)
(* It mimics the zmod file for polynomials *)
(* First, it defines polynomials of bounded size (equivalent of 'I_n), *)
(* gives it a structure of choice, finite and countable ring, ..., and *)
(* lmodule, when possible. *)
(* Internally, the construction uses poly_rV and rVpoly, but they should not *)
(* be exposed. *)
(* We provide two bases: the 'X^i and the lagrange polynomials. *)
(* {poly_n R} == the type of polynomial of size at most n *)
(* irreducibleb p == boolean decision procedure for irreducibility *)
(* of a bounded size polynomial over a finite idomain *)
(* Considering {poly_n F} over a field F, it is a vectType and *)
(* 'nX^i == 'X^i as an element of {poly_n R} *)
(* polynX == [tuple 'X^0, ..., 'X^(n - 1)], basis of {poly_n R} *)
(* x.-lagrange == lagrange basis of {poly_n R} wrt x : nat -> F *)
(* x.-lagrange_ i == the ith lagrange polynomial wrt the sampling points x *)
(* Second, it defines polynomials quotiented by a poly (equivalent of 'Z_p), *)
(* as bounded polynomial. As we are aiming to build a ring structure we need *)
(* the polynomial to be monic and of size greater than one. If it is not the *)
(* case we quotient by 'X *)
(* mk_monic p == the actual polynomial on which we quotient *)
(* if p is monic and of size > 1 it is p otherwise 'X *)
(* {poly %/ p} == defined as {poly_(size (mk_poly p)).-1 R} on which *)
(* there is a ring structure *)
(* in_qpoly q == turn the polynomial q into an element of {poly %/ p} by *)
(* taking a modulo *)
(* 'qX == in_qpoly 'X *)
(* The last part that defines the field structure when the quotient is an *)
(* irreducible polynomial is defined in field/qfpoly *)
(******************************************************************************)
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.
Import GRing.Theory.
Import Pdiv.CommonRing.
Import Pdiv.RingMonic.
Import Pdiv.Field.
Import FinRing.Theory.
Local Open Scope ring_scope.
Reserved Notation "'{poly_' n R }" (n at level 2, format "'{poly_' n R }").
Reserved Notation "''nX^' i" (at level 1, format "''nX^' i").
Reserved Notation "x .-lagrange" (format "x .-lagrange").
Reserved Notation "x .-lagrange_" (format "x .-lagrange_").
Reserved Notation "'qX".
Reserved Notation "{ 'poly' '%/' p }"
(p at level 2, format "{ 'poly' '%/' p }").
Section poly_of_size_zmod.
Context {R : nzRingType}.
Implicit Types (n : nat).
Section poly_of_size.
Variable (n : nat).
Definition poly_of_size_pred := fun p : {poly R} => size p <= n.
Arguments poly_of_size_pred _ /.
Definition poly_of_size := [qualify a p | poly_of_size_pred p].
Lemma npoly_submod_closed : submod_closed poly_of_size.
Proof.
split=> [|x p q sp sq]; rewrite qualifE/= ?size_polyC ?eqxx//.
rewrite (leq_trans (size_polyD _ _)) // geq_max.
by rewrite (leq_trans (size_scale_leq _ _)).
Qed.
HB.instance Definition _ :=
GRing.isSubmodClosed.Build R {poly R} poly_of_size_pred npoly_submod_closed.
End poly_of_size.
Arguments poly_of_size_pred _ _ /.
Section npoly.
Variable (n : nat).
Record npoly : predArgType := NPoly {
polyn :> {poly R};
_ : polyn \is a poly_of_size n
}.
HB.instance Definition _ := [isSub for @polyn].
Lemma npoly_is_a_poly_of_size (p : npoly) : val p \is a poly_of_size n.
Proof. by case: p. Qed.
Hint Resolve npoly_is_a_poly_of_size : core.
Lemma size_npoly (p : npoly) : size p <= n.
Proof. exact: npoly_is_a_poly_of_size. Qed.
Hint Resolve size_npoly : core.
HB.instance Definition _ := [Choice of npoly by <:].
HB.instance Definition _ := [SubChoice_isSubLmodule of npoly by <:].
Definition npoly_rV : npoly -> 'rV[R]_n := poly_rV \o val.
Definition rVnpoly : 'rV[R]_n -> npoly :=
insubd (0 : npoly) \o rVpoly.
Arguments rVnpoly /.
Arguments npoly_rV /.
Lemma npoly_rV_K : cancel npoly_rV rVnpoly.
Proof.
move=> p /=; apply/val_inj.
by rewrite val_insubd [_ \is a _]size_poly ?poly_rV_K.
Qed.
Lemma rVnpolyK : cancel rVnpoly npoly_rV.
Proof. by move=> p /=; rewrite val_insubd [_ \is a _]size_poly rVpolyK. Qed.
Hint Resolve npoly_rV_K rVnpolyK : core.
Lemma npoly_vect_axiom : Vector.axiom n npoly.
Proof. by exists npoly_rV; [exact:linearPZ | exists rVnpoly]. Qed.
HB.instance Definition _ := Lmodule_hasFinDim.Build R npoly npoly_vect_axiom.
End npoly.
End poly_of_size_zmod.
Arguments npoly {R}%_type n%_N.
Notation "'{poly_' n R }" := (@npoly R n) : type_scope.
#[global]
Hint Resolve size_npoly npoly_is_a_poly_of_size : core.
Arguments poly_of_size_pred _ _ _ /.
Arguments npoly : clear implicits.
HB.instance Definition _ (R : countNzRingType) n :=
[Countable of {poly_n R} by <:].
HB.instance Definition _ (R : finNzRingType) n : isFinite {poly_n R} :=
CanIsFinite (@npoly_rV_K R n).
Section npoly_theory.
Context (R : nzRingType) {n : nat}.
Lemma polyn_is_linear : linear (@polyn _ _ : {poly_n R} -> _).
Proof. by []. Qed.
HB.instance Definition _ :=
GRing.isSemilinear.Build R {poly_n R} {poly R} _ (polyn (n:=n))
(GRing.semilinear_linear polyn_is_linear).
Canonical mk_npoly (E : nat -> R) : {poly_n R} :=
@NPoly R _ (\poly_(i < n) E i) (size_poly _ _).
Fact size_npoly0 : size (0 : {poly R}) <= n.
Proof. by rewrite size_poly0. Qed.
Definition npoly0 := NPoly (size_npoly0).
Fact npolyp_key : unit. Proof. exact: tt. Qed.
Definition npolyp : {poly R} -> {poly_n R} :=
locked_with npolyp_key (mk_npoly \o (nth 0)).
Definition npoly_of_seq := npolyp \o Poly.
Lemma npolyP (p q : {poly_n R}) : nth 0 p =1 nth 0 q <-> p = q.
Proof. by split => [/polyP/val_inj|->]. Qed.
Lemma coef_npolyp (p : {poly R}) i : (npolyp p)`_i = if i < n then p`_i else 0.
Proof. by rewrite /npolyp unlock /= coef_poly. Qed.
Lemma big_coef_npoly (p : {poly_n R}) i : n <= i -> p`_i = 0.
Proof.
by move=> i_big; rewrite nth_default // (leq_trans _ i_big) ?size_npoly.
Qed.
Lemma npolypK (p : {poly R}) : size p <= n -> npolyp p = p :> {poly R}.
Proof.
move=> spn; apply/polyP=> i; rewrite coef_npolyp.
by have [i_big|i_small] // := ltnP; rewrite nth_default ?(leq_trans spn).
Qed.
Lemma coefn_sum (I : Type) (r : seq I) (P : pred I)
(F : I -> {poly_n R}) (k : nat) :
(\sum_(i <- r | P i) F i)`_k = \sum_(i <- r | P i) (F i)`_k.
Proof. by rewrite !raddf_sum //= coef_sum. Qed.
End npoly_theory.
Arguments mk_npoly {R} n E.
Arguments npolyp {R} n p.
Section fin_npoly.
Variable R : finNzRingType.
Variable n : nat.
Implicit Types p q : {poly_n R}.
Definition npoly_enum : seq {poly_n R} :=
if n isn't n.+1 then [:: npoly0 _] else
pmap insub [seq \poly_(i < n.+1) c (inord i) | c : (R ^ n.+1)%type].
Lemma npoly_enum_uniq : uniq npoly_enum.
Proof.
rewrite /npoly_enum; case: n=> [|k] //.
rewrite pmap_sub_uniq // map_inj_uniq => [|f g eqfg]; rewrite ?enum_uniq //.
apply/ffunP => /= i; have /(congr1 (fun p : {poly _} => p`_i)) := eqfg.
by rewrite !coef_poly ltn_ord inord_val.
Qed.
Lemma mem_npoly_enum p : p \in npoly_enum.
Proof.
rewrite /npoly_enum; case: n => [|k] // in p *.
case: p => [p sp] /=.
by rewrite in_cons -val_eqE /= -size_poly_leq0 [size _ <= _]sp.
rewrite mem_pmap_sub; apply/mapP.
eexists [ffun i : 'I__ => p`_i]; first by rewrite mem_enum.
apply/polyP => i; rewrite coef_poly.
have [i_small|i_big] := ltnP; first by rewrite ffunE /= inordK.
by rewrite nth_default // 1?(leq_trans _ i_big) // size_npoly.
Qed.
Lemma card_npoly : #|{poly_n R}| = (#|R| ^ n)%N.
Proof.
rewrite -(card_imset _ (can_inj (@npoly_rV_K _ _))) eq_cardT.
by rewrite -cardT /= card_mx mul1n.
by move=> v; apply/imsetP; exists (rVnpoly v); rewrite ?rVnpolyK //.
Qed.
End fin_npoly.
Section Irreducible.
Variable R : finIdomainType.
Variable p : {poly R}.
Definition irreducibleb :=
((1 < size p) &&
[forall q : {poly_((size p).-1) R},
(Pdiv.Ring.rdvdp q p)%R ==> (size q <= 1)])%N.
Lemma irreducibleP : reflect (irreducible_poly p) irreducibleb.
Proof.
rewrite /irreducibleb /irreducible_poly.
apply: (iffP idP) => [/andP[sp /'forall_implyP /= Fp]|[sp Fpoly]].
have sp_gt0 : size p > 0 by case: size sp.
have p_neq0 : p != 0 by rewrite -size_poly_eq0; case: size sp.
split => // q sq_neq1 dvd_qp; rewrite -dvdp_size_eqp // eqn_leq dvdp_leq //=.
apply: contraNT sq_neq1; rewrite -ltnNge => sq_lt_sp.
have q_small: (size q <= (size p).-1)%N by rewrite -ltnS prednK.
rewrite Pdiv.Idomain.dvdpE in dvd_qp.
have /= := Fp (NPoly q_small) dvd_qp.
rewrite leq_eqVlt ltnS => /orP[//|]; rewrite size_poly_leq0 => /eqP q_eq0.
by rewrite -Pdiv.Idomain.dvdpE q_eq0 dvd0p (negPf p_neq0) in dvd_qp.
have sp_gt0 : size p > 0 by case: size sp.
rewrite sp /=; apply/'forall_implyP => /= q.
rewrite -Pdiv.Idomain.dvdpE=> dvd_qp.
have [/eqP->//|/Fpoly/(_ dvd_qp)/eqp_size sq_eq_sp] := boolP (size q == 1%N).
by have := size_npoly q; rewrite sq_eq_sp -ltnS prednK ?ltnn.
Qed.
End Irreducible.
Section Vspace.
Variable (K : fieldType) (n : nat).
Lemma dim_polyn : \dim (fullv : {vspace {poly_n K}}) = n.
Proof. by rewrite [LHS]mxrank_gen mxrank1. Qed.
Definition npolyX : n.-tuple {poly_n K} := [tuple npolyp n 'X^i | i < n].
Notation "''nX^' i" := (tnth npolyX i).
Lemma npolyXE (i : 'I_n) : 'nX^i = 'X^i :> {poly _}.
Proof. by rewrite tnth_map tnth_ord_tuple npolypK // size_polyXn. Qed.
Lemma nth_npolyX (i : 'I_n) : npolyX`_i = 'nX^i.
Proof. by rewrite -tnth_nth. Qed.
Lemma npolyX_free : free npolyX.
Proof.
apply/freeP=> u /= sum_uX_eq0 i; have /npolyP /(_ i) := sum_uX_eq0.
rewrite (@big_morph _ _ _ 0%R +%R) // coef_sum coef0.
rewrite (bigD1 i) ?big1 /= ?addr0 ?coefZ ?(nth_map 0%N) ?size_iota //.
by rewrite nth_npolyX npolyXE coefXn eqxx mulr1.
move=> j; rewrite -val_eqE /= => neq_ji.
by rewrite nth_npolyX npolyXE coefZ coefXn eq_sym (negPf neq_ji) mulr0.
Qed.
Lemma npolyX_full : basis_of fullv npolyX.
Proof.
by rewrite basisEfree npolyX_free subvf size_map size_enum_ord dim_polyn /=.
Qed.
Lemma npolyX_coords (p : {poly_n K}) i : coord npolyX i p = p`_i.
Proof.
rewrite [p in RHS](coord_basis npolyX_full) ?memvf // coefn_sum.
rewrite (bigD1 i) //= coefZ nth_npolyX npolyXE coefXn eqxx mulr1 big1 ?addr0//.
move=> j; rewrite -val_eqE => /= neq_ji.
by rewrite coefZ nth_npolyX npolyXE coefXn eq_sym (negPf neq_ji) mulr0.
Qed.
Lemma npolyX_gen (p : {poly K}) : (size p <= n)%N ->
p = \sum_(i < n) p`_i *: 'nX^i.
Proof.
move=> sp; rewrite -[p](@npolypK _ n) //.
rewrite [npolyp _ _ in LHS](coord_basis npolyX_full) ?memvf //.
rewrite (@big_morph _ _ _ 0%R +%R) // !raddf_sum.
by apply: eq_bigr=> i _; rewrite npolyX_coords //= nth_npolyX npolyXE.
Qed.
Section lagrange.
Variables (x : nat -> K).
Notation lagrange_def := (fun i :'I_n =>
let k := i in let p := \prod_(j < n | j != k) ('X - (x j)%:P)
in (p.[x k]^-1)%:P * p).
Fact lagrange_key : unit. Proof. exact: tt. Qed.
Definition lagrange := locked_with lagrange_key
[tuple npolyp n (lagrange_def i) | i < n].
Notation lagrange_ := (tnth lagrange).
Hypothesis n_gt0 : (0 < n)%N.
Hypothesis x_inj : injective x.
Let lagrange_def_sample (i j : 'I_n) : (lagrange_def i).[x j] = (i == j)%:R.
Proof.
clear n_gt0; rewrite hornerM hornerC; set p := (\prod_(_ < _ | _) _).
have [<-|neq_ij] /= := altP eqP.
rewrite mulVf // horner_prod; apply/prodf_neq0 => k neq_ki.
by rewrite hornerXsubC subr_eq0 inj_eq // eq_sym.
rewrite [X in _ * X]horner_prod (bigD1 j) 1?eq_sym //=.
by rewrite hornerXsubC subrr mul0r mulr0.
Qed.
Let size_lagrange_def i : size (lagrange_def i) = n.
Proof.
rewrite size_Cmul; last first.
suff : (lagrange_def i).[x i] != 0.
by rewrite hornerE mulf_eq0 => /norP [].
by rewrite lagrange_def_sample ?eqxx ?oner_eq0.
rewrite size_prod /=; last first.
by move=> j neq_ji; rewrite polyXsubC_eq0.
rewrite (eq_bigr (fun=> (2 * 1)%N)); last first.
by move=> j neq_ji; rewrite size_XsubC.
rewrite -big_distrr /= sum1_card cardC1 card_ord /=.
by case: (n) {i} n_gt0 => ?; rewrite mul2n -addnn -addSn addnK.
Qed.
Lemma lagrangeE i : lagrange_ i = lagrange_def i :> {poly _}.
Proof.
rewrite [lagrange]unlock tnth_map.
by rewrite [val _]npolypK tnth_ord_tuple // size_lagrange_def.
Qed.
Lemma nth_lagrange (i : 'I_n) : lagrange`_i = lagrange_ i.
Proof. by rewrite -tnth_nth. Qed.
Lemma size_lagrange_ i : size (lagrange_ i) = n.
Proof. by rewrite lagrangeE size_lagrange_def. Qed.
Lemma size_lagrange : size lagrange = n.
Proof. by rewrite size_tuple. Qed.
Lemma lagrange_sample (i j : 'I_n) : (lagrange_ i).[x j] = (i == j)%:R.
Proof. by rewrite lagrangeE lagrange_def_sample. Qed.
Lemma lagrange_free : free lagrange.
Proof.
apply/freeP=> lambda eq_l i.
have /(congr1 (fun p : {poly__ _} => p.[x i])) := eq_l.
rewrite (@big_morph _ _ _ 0%R +%R) // horner_sum horner0.
rewrite (bigD1 i) // big1 => [|j /= /negPf ji] /=;
by rewrite ?hornerE nth_lagrange lagrange_sample ?eqxx ?ji ?mulr1 ?mulr0.
Qed.
Lemma lagrange_full : basis_of fullv lagrange.
Proof.
by rewrite basisEfree lagrange_free subvf size_lagrange dim_polyn /=.
Qed.
Lemma lagrange_coords (p : {poly_n K}) i : coord lagrange i p = p.[x i].
Proof.
rewrite [p in RHS](coord_basis lagrange_full) ?memvf //.
rewrite (@big_morph _ _ _ 0%R +%R) // horner_sum.
rewrite (bigD1 i) // big1 => [|j /= /negPf ji] /=;
by rewrite ?hornerE nth_lagrange lagrange_sample ?eqxx ?ji ?mulr1 ?mulr0.
Qed.
Lemma lagrange_gen (p : {poly K}) : (size p <= n)%N ->
p = \sum_(i < n) p.[x i]%:P * lagrange_ i.
Proof.
move=> sp; rewrite -[p](@npolypK _ n) //.
rewrite [npolyp _ _ in LHS](coord_basis lagrange_full) ?memvf //.
rewrite (@big_morph _ _ _ 0%R +%R) //; apply: eq_bigr=> i _.
by rewrite lagrange_coords mul_polyC nth_lagrange.
Qed.
End lagrange.
End Vspace.
Notation "''nX^' i" := (tnth (npolyX _) i) : ring_scope.
Notation "x .-lagrange" := (lagrange x) : ring_scope.
Notation "x .-lagrange_" := (tnth x.-lagrange) : ring_scope.
Section Qpoly.
Variable R : nzRingType.
Variable h : {poly R}.
Definition mk_monic :=
if (1 < size h)%N && (h \is monic) then h else 'X.
Definition qpoly := {poly_(size mk_monic).-1 R}.
End Qpoly.
Notation "{ 'poly' '%/' p }" := (qpoly p) : type_scope.
Section QpolyProp.
Variable R : nzRingType.
Variable h : {poly R}.
Lemma monic_mk_monic : (mk_monic h) \is monic.
Proof.
rewrite /mk_monic; case: leqP=> [_|/=]; first by apply: monicX.
by case E : (h \is monic) => [->//|] => _; apply: monicX.
Qed.
Lemma size_mk_monic_gt1 : (1 < size (mk_monic h))%N.
Proof.
by rewrite !fun_if size_polyX; case: leqP => //=; rewrite if_same.
Qed.
Lemma size_mk_monic_gt0 : (0 < size (mk_monic h))%N.
Proof. by rewrite (leq_trans _ size_mk_monic_gt1). Qed.
Lemma mk_monic_neq0 : mk_monic h != 0.
Proof. by rewrite -size_poly_gt0 size_mk_monic_gt0. Qed.
Lemma size_mk_monic (p : {poly %/ h}) : size p < size (mk_monic h).
Proof.
have: (p : {poly R}) \is a poly_of_size (size (mk_monic h)).-1 by case: p.
by rewrite qualifE/= -ltnS prednK // size_mk_monic_gt0.
Qed.
(* standard inject *)
Lemma poly_of_size_mod p :
rmodp p (mk_monic h) \is a poly_of_size (size (mk_monic h)).-1.
Proof.
rewrite qualifE/= -ltnS prednK ?size_mk_monic_gt0 //.
by apply: ltn_rmodpN0; rewrite mk_monic_neq0.
Qed.
Definition in_qpoly p : {poly %/ h} := NPoly (poly_of_size_mod p).
Lemma in_qpoly_small (p : {poly R}) :
size p < size (mk_monic h) -> in_qpoly p = p :> {poly R}.
Proof. exact: rmodp_small. Qed.
Lemma in_qpoly0 : in_qpoly 0 = 0.
Proof. by apply/val_eqP; rewrite /= rmod0p. Qed.
Lemma in_qpolyD p q : in_qpoly (p + q) = in_qpoly p + in_qpoly q.
Proof. by apply/val_eqP=> /=; rewrite rmodpD ?monic_mk_monic. Qed.
Lemma in_qpolyZ a p : in_qpoly (a *: p) = a *: in_qpoly p.
Proof. apply/val_eqP=> /=; rewrite rmodpZ ?monic_mk_monic //. Qed.
Fact in_qpoly_is_linear : linear in_qpoly.
Proof. by move=> k p q; rewrite in_qpolyD in_qpolyZ. Qed.
HB.instance Definition _ :=
GRing.isSemilinear.Build R {poly R} {poly_(size (mk_monic h)).-1 R} _ in_qpoly
(GRing.semilinear_linear in_qpoly_is_linear).
Lemma qpolyC_proof k :
(k%:P : {poly R}) \is a poly_of_size (size (mk_monic h)).-1.
Proof.
rewrite qualifE/= -ltnS size_polyC prednK ?size_mk_monic_gt0 //.
by rewrite (leq_ltn_trans _ size_mk_monic_gt1) //; case: eqP.
Qed.
Definition qpolyC k : {poly %/ h} := NPoly (qpolyC_proof k).
Lemma qpolyCE k : qpolyC k = k%:P :> {poly R}.
Proof. by []. Qed.
Lemma qpolyC0 : qpolyC 0 = 0.
Proof. by apply/val_eqP/eqP. Qed.
Definition qpoly1 := qpolyC 1.
Definition qpoly_mul (q1 q2 : {poly %/ h}) : {poly %/ h} :=
in_qpoly ((q1 : {poly R}) * q2).
Lemma qpoly_mul1z : left_id qpoly1 qpoly_mul.
Proof.
by move=> x; apply: val_inj; rewrite /= mul1r rmodp_small // size_mk_monic.
Qed.
Lemma qpoly_mulz1 : right_id qpoly1 qpoly_mul.
Proof.
by move=> x; apply: val_inj; rewrite /= mulr1 rmodp_small // size_mk_monic.
Qed.
Lemma qpoly_nontrivial : qpoly1 != 0.
Proof. by apply/eqP/val_eqP; rewrite /= oner_eq0. Qed.
Definition qpolyX := in_qpoly 'X.
Notation "'qX" := qpolyX.
Lemma qpolyXE : 2 < size h -> h \is monic -> 'qX = 'X :> {poly R}.
Proof.
move=> sh_gt2 h_mo.
by rewrite in_qpoly_small // size_polyX /mk_monic ifT // (ltn_trans _ sh_gt2).
Qed.
End QpolyProp.
Notation "'qX" := (qpolyX _) : ring_scope.
Lemma mk_monic_X (R : nzRingType) : mk_monic 'X = 'X :> {poly R}.
Proof. by rewrite /mk_monic size_polyX monicX. Qed.
Lemma mk_monic_Xn (R : nzRingType) n : mk_monic 'X^n = 'X^(n.-1.+1) :> {poly R}.
Proof. by case: n => [|n]; rewrite /mk_monic size_polyXn monicXn /= ?expr1. Qed.
Lemma card_qpoly (R : finNzRingType) (h : {poly R}):
#|{poly %/ h}| = #|R| ^ (size (mk_monic h)).-1.
Proof. by rewrite card_npoly. Qed.
Lemma card_monic_qpoly (R : finNzRingType) (h : {poly R}):
1 < size h -> h \is monic -> #|{poly %/ h}| = #|R| ^ (size h).-1.
Proof. by move=> sh_gt1 hM; rewrite card_qpoly /mk_monic sh_gt1 hM. Qed.
Section QRing.
Variable A : comNzRingType.
Variable h : {poly A}.
(* Ring operations *)
Lemma qpoly_mulC : commutative (@qpoly_mul A h).
Proof. by move=> p q; apply: val_inj; rewrite /= mulrC. Qed.
Lemma qpoly_mulA : associative (@qpoly_mul A h).
Proof.
have rPM := monic_mk_monic h; move=> p q r; apply: val_inj.
by rewrite /= rmodp_mulml // rmodp_mulmr // mulrA.
Qed.
Lemma qpoly_mul_addr : right_distributive (@qpoly_mul A h) +%R.
Proof.
have rPM := monic_mk_monic h; move=> p q r; apply: val_inj.
by rewrite /= !(mulrDr, rmodp_mulmr, rmodpD).
Qed.
Lemma qpoly_mul_addl : left_distributive (@qpoly_mul A h) +%R.
Proof. by move=> p q r; rewrite -!(qpoly_mulC r) qpoly_mul_addr. Qed.
HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build {poly__ A} qpoly_mulA
qpoly_mulC (@qpoly_mul1z _ h) qpoly_mul_addl (@qpoly_nontrivial _ h).
HB.instance Definition _ := GRing.ComNzRing.on {poly %/ h}.
Lemma in_qpoly1 : in_qpoly h 1 = 1.
Proof.
apply/val_eqP/eqP/in_qpoly_small.
by rewrite size_polyC oner_eq0 /= size_mk_monic_gt1.
Qed.
Lemma in_qpolyM q1 q2 : in_qpoly h (q1 * q2) = in_qpoly h q1 * in_qpoly h q2.
Proof.
apply/val_eqP => /=.
by rewrite rmodp_mulml ?rmodp_mulmr // monic_mk_monic.
Qed.
Fact in_qpoly_monoid_morphism : monoid_morphism (in_qpoly h).
Proof. by split; [ apply: in_qpoly1 | apply: in_qpolyM]. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `in_qpoly_is_monoid_morphism` instead")]
Definition in_qpoly_is_multiplicative :=
(fun g => (g.2,g.1)) in_qpoly_monoid_morphism.
HB.instance Definition _ :=
GRing.isMonoidMorphism.Build {poly A} {poly %/ h} (in_qpoly h)
in_qpoly_monoid_morphism.
Lemma poly_of_qpoly_sum I (r : seq I) (P1 : pred I) (F : I -> {poly %/ h}) :
((\sum_(i <- r | P1 i) F i) =
\sum_(p <- r | P1 p) ((F p) : {poly A}) :> {poly A})%R.
Proof. by elim/big_rec2: _ => // i p q IH <-. Qed.
Lemma poly_of_qpolyD (p q : {poly %/ h}) :
p + q= (p : {poly A}) + q :> {poly A}.
Proof. by []. Qed.
Lemma qpolyC_natr p : (p%:R : {poly %/ h}) = p%:R :> {poly A}.
Proof. by elim: p => //= p IH; rewrite !mulrS poly_of_qpolyD IH. Qed.
Lemma pchar_qpoly : [pchar {poly %/ h}] =i [pchar A].
Proof.
move=> p; rewrite !inE; congr (_ && _).
apply/eqP/eqP=> [/(congr1 val) /=|pE]; last first.
by apply: val_inj => //=; rewrite qpolyC_natr /= -polyC_natr pE.
rewrite !qpolyC_natr -!polyC_natr => /(congr1 val) /=.
by rewrite polyseqC polyseq0; case: eqP.
Qed.
Lemma poly_of_qpolyM (p q : {poly %/ h}) :
p * q = rmodp ((p : {poly A}) * q) (mk_monic h) :> {poly A}.
Proof. by []. Qed.
Lemma poly_of_qpolyX (p : {poly %/ h}) n :
p ^+ n = rmodp ((p : {poly A}) ^+ n) (mk_monic h) :> {poly A}.
Proof.
have HhQ := monic_mk_monic h.
elim: n => //= [|n IH].
rewrite rmodp_small // size_polyC ?(leq_ltn_trans _ (size_mk_monic_gt1 _)) //.
by case: eqP.
by rewrite exprS /= IH // rmodp_mulmr // -exprS.
Qed.
Lemma qpolyCN (a : A) : qpolyC h (- a) = -(qpolyC h a).
Proof. apply: val_inj; rewrite /= raddfN //= raddfN. Qed.
Lemma qpolyCD : {morph (qpolyC h) : a b / a + b >-> a + b}%R.
Proof. by move=> a b; apply/val_eqP/eqP=> /=; rewrite -!raddfD. Qed.
Lemma qpolyCM : {morph (qpolyC h) : a b / a * b >-> a * b}%R.
Proof.
move=> a b; apply/val_eqP/eqP=> /=; rewrite -polyCM rmodp_small //=.
have := qpolyC_proof h (a * b).
by rewrite qualifE/= -ltnS prednK // size_mk_monic_gt0.
Qed.
Lemma qpolyC_is_zmod_morphism : zmod_morphism (qpolyC h).
Proof. by move=> x y; rewrite qpolyCD qpolyCN. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `qpolyC_is_zmod_morphism` instead")]
Definition qpolyC_is_additive := qpolyC_is_zmod_morphism.
Lemma qpolyC_is_monoid_morphism : monoid_morphism (qpolyC h).
Proof. by split=> // x y; rewrite qpolyCM. Qed.
#[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0",
note="use `qpolyC_is_monoid_morphism` instead")]
Definition qpolyC_is_multiplicative :=
(fun g => (g.2,g.1)) qpolyC_is_monoid_morphism.
HB.instance Definition _ := GRing.isZmodMorphism.Build A {poly %/ h} (qpolyC h)
qpolyC_is_zmod_morphism.
HB.instance Definition _ :=
GRing.isMonoidMorphism.Build A {poly %/ h} (qpolyC h)
qpolyC_is_monoid_morphism.
Definition qpoly_scale k (p : {poly %/ h}) : {poly %/ h} := (k *: p)%R.
Fact qpoly_scaleA a b p :
qpoly_scale a (qpoly_scale b p) = qpoly_scale (a * b) p.
Proof. by apply/val_eqP; rewrite /= scalerA. Qed.
Fact qpoly_scale1l : left_id 1%R qpoly_scale.
Proof. by move=> p; apply/val_eqP; rewrite /= scale1r. Qed.
Fact qpoly_scaleDr a : {morph qpoly_scale a : p q / (p + q)%R}.
Proof. by move=> p q; apply/val_eqP; rewrite /= scalerDr. Qed.
Fact qpoly_scaleDl p : {morph qpoly_scale^~ p : a b / a + b}%R.
Proof. by move=> a b; apply/val_eqP; rewrite /= scalerDl. Qed.
Fact qpoly_scaleAl a p q : qpoly_scale a (p * q) = (qpoly_scale a p * q).
Proof. by apply/val_eqP; rewrite /= -scalerAl rmodpZ // monic_mk_monic. Qed.
Fact qpoly_scaleAr a p q : qpoly_scale a (p * q) = p * (qpoly_scale a q).
Proof. by apply/val_eqP; rewrite /= -scalerAr rmodpZ // monic_mk_monic. Qed.
HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build A {poly__ A}
qpoly_scaleAl.
HB.instance Definition _ := GRing.Lalgebra.on {poly %/ h}.
HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build A {poly__ A}
qpoly_scaleAr.
HB.instance Definition _ := GRing.Algebra.on {poly %/ h}.
Lemma poly_of_qpolyZ (p : {poly %/ h}) a :
a *: p = a *: (p : {poly A}) :> {poly A}.
Proof. by []. Qed.
End QRing.
#[deprecated(since="mathcomp 2.4.0", note="Use pchar_qpoly instead.")]
Notation char_qpoly := (pchar_qpoly) (only parsing).
Section Field.
Variable R : fieldType.
Variable h : {poly R}.
Local Notation hQ := (mk_monic h).
Definition qpoly_inv (p : {poly %/ h}) :=
if coprimep hQ p then let v : {poly %/ h} := in_qpoly h (egcdp hQ p).2 in
((lead_coef (v * p)) ^-1 *: v) else p.
(* Ugly *)
Lemma qpoly_mulVz (p : {poly %/ h}) : coprimep hQ p -> (qpoly_inv p * p = 1)%R.
Proof.
have hQM := monic_mk_monic h.
move=> hCp; apply: val_inj; rewrite /qpoly_inv /in_qpoly hCp /=.
have p_neq0 : p != 0%R.
apply/eqP=> pZ; move: hCp; rewrite pZ.
rewrite coprimep0 -size_poly_eq1.
by case: size (size_mk_monic_gt1 h) => [|[]].
have F : (egcdp hQ p).1 * hQ + (egcdp hQ p).2 * p %= 1.
apply: eqp_trans _ (_ : gcdp hQ p %= _).
rewrite eqp_sym.
by case: (egcdpP (mk_monic_neq0 h) p_neq0).
by rewrite -size_poly_eq1.
rewrite rmodp_mulml // -scalerAl rmodpZ // rmodp_mulml //.
rewrite -[rmodp]/Pdiv.Ring.rmodp -!Pdiv.IdomainMonic.modpE //.
have := eqp_modpl hQ F.
rewrite modpD // modp_mull add0r // .
rewrite [(1 %% _)%R]modp_small => // [egcdE|]; last first.
by rewrite size_polyC oner_eq0 size_mk_monic_gt1.
rewrite {2}(eqpfP egcdE) lead_coefC divr1 alg_polyC scale_polyC mulVf //.
rewrite lead_coef_eq0.
apply/eqP => egcdZ.
by move: egcdE; rewrite -size_poly_eq1 egcdZ size_polyC eq_sym eqxx.
Qed.
Lemma qpoly_mulzV (p : {poly %/ h}) :
coprimep hQ p -> (p * (qpoly_inv p) = 1)%R.
Proof. by move=> hCp; rewrite /= mulrC qpoly_mulVz. Qed.
Lemma qpoly_intro_unit (p q : {poly %/ h}) : (q * p = 1)%R -> coprimep hQ p.
Proof.
have hQM := monic_mk_monic h.
case; rewrite -[rmodp]/Pdiv.Ring.rmodp -!Pdiv.IdomainMonic.modpE // => qp1.
have:= coprimep1 hQ.
rewrite -coprimep_modr -[1%R]qp1 !coprimep_modr coprimepMr; by case/andP.
Qed.
Lemma qpoly_inv_out (p : {poly %/ h}) : ~~ coprimep hQ p -> qpoly_inv p = p.
Proof. by rewrite /qpoly_inv => /negPf->. Qed.
HB.instance Definition _ := GRing.ComNzRing_hasMulInverse.Build {poly__ _}
qpoly_mulVz qpoly_intro_unit qpoly_inv_out.
HB.instance Definition _ := GRing.ComUnitAlgebra.on {poly %/ h}.
Lemma irreducible_poly_coprime (A : idomainType) (p q : {poly A}) :
irreducible_poly p -> coprimep p q = ~~(p %| q)%R.
Proof.
case => H1 H2; apply/coprimepP/negP.
move=> sPq H.
by have := sPq p (dvdpp _) H; rewrite -size_poly_eq1; case: size H1 => [|[]].
move=> pNDq d dDp dPq.
rewrite -size_poly_eq1; case: eqP => // /eqP /(H2 _) => /(_ dDp) dEp.
by case: pNDq; rewrite -(eqp_dvdl _ dEp).
Qed.
End Field.
|
Symmetric.lean
|
/-
Copyright (c) 2023 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.LinearAlgebra.QuadraticForm.QuadraticModuleCat.Monoidal
import Mathlib.Algebra.Category.ModuleCat.Monoidal.Symmetric
/-!
# The monoidal structure on `QuadraticModuleCat` is symmetric.
In this file we show:
* `QuadraticModuleCat.instSymmetricCategory : SymmetricCategory (QuadraticModuleCat.{u} R)`
## Implementation notes
This file essentially mirrors `Mathlib/Algebra/Category/AlgCat/Symmetric.lean`.
-/
open CategoryTheory
universe v u
variable {R : Type u} [CommRing R] [Invertible (2 : R)]
namespace QuadraticModuleCat
open QuadraticForm
instance : BraidedCategory (QuadraticModuleCat.{u} R) :=
.ofFaithful (forget₂ (QuadraticModuleCat R) (ModuleCat R))
fun X Y ↦ ofIso <| tensorComm X.form Y.form
/-- `forget₂ (QuadraticModuleCat R) (ModuleCat R)` is a braided functor. -/
instance : (forget₂ (QuadraticModuleCat R) (ModuleCat R)).Braided where
instance instSymmetricCategory : SymmetricCategory (QuadraticModuleCat.{u} R) :=
symmetricCategoryOfFaithful (forget₂ (QuadraticModuleCat R) (ModuleCat R))
end QuadraticModuleCat
|
Cocardinal.lean
|
/-
Copyright (c) 2024 Josha Dekker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Josha Dekker
-/
import Mathlib.Order.Filter.Cofinite
import Mathlib.Order.Filter.CountableInter
import Mathlib.Order.Filter.CardinalInter
import Mathlib.SetTheory.Cardinal.Arithmetic
import Mathlib.SetTheory.Cardinal.Cofinality
/-!
# The cocardinal filter
In this file we define `Filter.cocardinal hc`: the filter of sets with cardinality less than
a regular cardinal `c` that satisfies `Cardinal.aleph0 < c`.
Such filters are `CardinalInterFilter` with cardinality `c`.
-/
open Set Filter Cardinal
universe u
variable {α : Type u} {c : Cardinal.{u}} {hreg : c.IsRegular}
namespace Filter
variable (α) in
/-- The filter defined by all sets that have a complement with at most cardinality `c`. For a union
of `c` sets of `c` elements to have `c` elements, we need that `c` is a regular cardinal. -/
def cocardinal (hreg : c.IsRegular) : Filter α := by
apply ofCardinalUnion {s | Cardinal.mk s < c} (lt_of_lt_of_le (nat_lt_aleph0 2) hreg.aleph0_le)
· refine fun s hS hSc ↦ lt_of_le_of_lt (mk_sUnion_le _) <| mul_lt_of_lt hreg.aleph0_le hS ?_
exact iSup_lt_of_isRegular hreg hS fun i ↦ hSc i i.property
· exact fun _ hSc _ ht ↦ lt_of_le_of_lt (mk_le_mk_of_subset ht) hSc
@[simp]
theorem mem_cocardinal {s : Set α} :
s ∈ cocardinal α hreg ↔ Cardinal.mk (sᶜ : Set α) < c := Iff.rfl
@[simp] lemma cocardinal_aleph0_eq_cofinite :
cocardinal (α := α) isRegular_aleph0 = cofinite := by
aesop
instance instCardinalInterFilter_cocardinal : CardinalInterFilter (cocardinal (α := α) hreg) c where
cardinal_sInter_mem S hS hSs := by
rw [mem_cocardinal, Set.compl_sInter]
apply lt_of_le_of_lt (mk_sUnion_le _)
apply mul_lt_of_lt hreg.aleph0_le (lt_of_le_of_lt mk_image_le hS)
apply iSup_lt_of_isRegular hreg <| lt_of_le_of_lt mk_image_le hS
aesop
@[simp]
theorem eventually_cocardinal {p : α → Prop} :
(∀ᶠ x in cocardinal α hreg, p x) ↔ #{ x | ¬p x } < c := Iff.rfl
theorem hasBasis_cocardinal : HasBasis (cocardinal α hreg) {s : Set α | #s < c} compl :=
⟨fun s =>
⟨fun h => ⟨sᶜ, h, (compl_compl s).subset⟩, fun ⟨_t, htf, hts⟩ => by
have : #↑sᶜ < c := by
apply lt_of_le_of_lt _ htf
rw [compl_subset_comm] at hts
apply Cardinal.mk_le_mk_of_subset hts
simp_all only [mem_cocardinal] ⟩⟩
theorem frequently_cocardinal {p : α → Prop} :
(∃ᶠ x in cocardinal α hreg, p x) ↔ c ≤ # { x | p x } := by
simp only [Filter.Frequently, eventually_cocardinal, not_not,coe_setOf, not_lt]
lemma frequently_cocardinal_mem {s : Set α} :
(∃ᶠ x in cocardinal α hreg, x ∈ s) ↔ c ≤ #s := frequently_cocardinal
@[simp]
lemma cocardinal_inf_principal_neBot_iff {s : Set α} :
(cocardinal α hreg ⊓ 𝓟 s).NeBot ↔ c ≤ #s :=
frequently_mem_iff_neBot.symm.trans frequently_cocardinal
theorem compl_mem_cocardinal_of_card_lt {s : Set α} (hs : #s < c) :
sᶜ ∈ cocardinal α hreg :=
mem_cocardinal.2 <| (compl_compl s).symm ▸ hs
theorem _root_.Set.Finite.compl_mem_cocardinal {s : Set α} (hs : s.Finite) :
sᶜ ∈ cocardinal α hreg :=
compl_mem_cocardinal_of_card_lt <| lt_of_lt_of_le (Finite.lt_aleph0 hs) (hreg.aleph0_le)
theorem eventually_cocardinal_notMem_of_card_lt {s : Set α} (hs : #s < c) :
∀ᶠ x in cocardinal α hreg, x ∉ s :=
compl_mem_cocardinal_of_card_lt hs
@[deprecated (since := "2025-05-24")]
alias eventually_cocardinal_nmem_of_card_lt := eventually_cocardinal_notMem_of_card_lt
theorem _root_.Finset.eventually_cocardinal_notMem (s : Finset α) :
∀ᶠ x in cocardinal α hreg, x ∉ s :=
eventually_cocardinal_notMem_of_card_lt <| (finset_card_lt_aleph0 s).trans_le (hreg.aleph0_le)
@[deprecated (since := "2025-05-24")]
alias _root_.Finset.eventually_cocardinal_nmem := _root_.Finset.eventually_cocardinal_notMem
theorem eventually_cocardinal_ne (x : α) : ∀ᶠ a in cocardinal α hreg, a ≠ x := by
simpa [Set.finite_singleton x] using hreg.nat_lt 1
/-- The filter defined by all sets that have countable complements. -/
abbrev cocountable : Filter α := cocardinal α Cardinal.isRegular_aleph_one
theorem mem_cocountable {s : Set α} :
s ∈ cocountable ↔ (sᶜ : Set α).Countable := by
rw [Cardinal.countable_iff_lt_aleph_one, mem_cocardinal]
end Filter
|
UniformTime.lean
|
/-
Copyright (c) 2023 Winston Yin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Winston Yin
-/
import Mathlib.Geometry.Manifold.IntegralCurve.ExistUnique
/-!
# Uniform time lemma for the global existence of integral curves
## Main results
* `exists_isMIntegralCurve_of_isMIntegralCurveOn`: If there exists `ε > 0` such that the local
integral curve at each point `x : M` is defined at least on an open interval `Ioo (-ε) ε`, then
every point on `M` has a global integral curve passing through it.
## Reference
* [Lee, J. M. (2012). _Introduction to Smooth Manifolds_. Springer New York.][lee2012]
## Tags
integral curve, vector field, global existence
-/
open scoped Topology
open Function Set
variable
{E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E]
{H : Type*} [TopologicalSpace H] {I : ModelWithCorners ℝ E H}
{M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M]
[T2Space M] {γ γ' : ℝ → M} {v : (x : M) → TangentSpace I x} {s s' : Set ℝ} {t₀ : ℝ}
/-- This is the uniqueness theorem of integral curves applied to a real-indexed family of integral
curves with the same starting point. -/
lemma eqOn_of_isMIntegralCurveOn_Ioo [BoundarylessManifold I M]
(hv : ContMDiff I I.tangent 1 (fun x ↦ (⟨x, v x⟩ : TangentBundle I M))) {x : M}
(γ : ℝ → ℝ → M) (hγx : ∀ a, γ a 0 = x) (hγ : ∀ a > 0, IsMIntegralCurveOn (γ a) v (Ioo (-a) a))
{a a' : ℝ} (hpos : 0 < a') (hle : a' ≤ a) :
EqOn (γ a') (γ a) (Ioo (-a') a') := by
apply isMIntegralCurveOn_Ioo_eqOn_of_contMDiff_boundaryless _ hv
(hγ a' (by positivity)) ((hγ a (lt_of_lt_of_le hpos hle)).mono _)
(by rw [hγx a, hγx a'])
· rw [mem_Ioo]
exact ⟨neg_lt_zero.mpr hpos, by positivity⟩
· apply Ioo_subset_Ioo <;> linarith
@[deprecated (since := "2025-08-12")] alias eqOn_of_isIntegralCurveOn_Ioo :=
eqOn_of_isMIntegralCurveOn_Ioo
/-- For a family of integral curves `γ : ℝ → ℝ → M` with the same starting point `γ 0 = x` such that
each `γ a` is defined on `Ioo (-a) a`, the global curve `γ_ext := fun t ↦ γ (|t| + 1) t` agrees
with each `γ a` on `Ioo (-a) a`. This will help us show that `γ_ext` is a global integral curve. -/
lemma eqOn_abs_add_one_of_isMIntegralCurveOn_Ioo [BoundarylessManifold I M]
(hv : ContMDiff I I.tangent 1 (fun x ↦ (⟨x, v x⟩ : TangentBundle I M))) {x : M}
(γ : ℝ → ℝ → M) (hγx : ∀ a, γ a 0 = x) (hγ : ∀ a > 0, IsMIntegralCurveOn (γ a) v (Ioo (-a) a))
{a : ℝ} : EqOn (fun t ↦ γ (|t| + 1) t) (γ a) (Ioo (-a) a) := by
intros t ht
by_cases hlt : |t| + 1 < a
· exact eqOn_of_isMIntegralCurveOn_Ioo hv γ hγx hγ
(by positivity) hlt.le (abs_lt.mp <| lt_add_one _)
· exact eqOn_of_isMIntegralCurveOn_Ioo hv γ hγx hγ
(neg_lt_self_iff.mp <| lt_trans ht.1 ht.2) (not_lt.mp hlt) ht |>.symm
@[deprecated (since := "2025-08-12")] alias eqOn_abs_add_one_of_isIntegralCurveOn_Ioo :=
eqOn_abs_add_one_of_isMIntegralCurveOn_Ioo
/-- For a family of integral curves `γ : ℝ → ℝ → M` with the same starting point `γ 0 = x` such that
each `γ a` is defined on `Ioo (-a) a`, the function `γ_ext := fun t ↦ γ (|t| + 1) t` is a global
integral curve. -/
lemma isMIntegralCurve_abs_add_one_of_isMIntegralCurveOn_Ioo [BoundarylessManifold I M]
(hv : ContMDiff I I.tangent 1 (fun x ↦ (⟨x, v x⟩ : TangentBundle I M))) {x : M}
(γ : ℝ → ℝ → M) (hγx : ∀ a, γ a 0 = x) (hγ : ∀ a > 0, IsMIntegralCurveOn (γ a) v (Ioo (-a) a)) :
IsMIntegralCurve (fun t ↦ γ (|t| + 1) t) v := by
intro t
have ht : t ∈ Ioo (-(|t| + 1)) (|t| + 1) := by
rw [mem_Ioo, ← abs_lt]
exact lt_add_one _
apply HasMFDerivAt.congr_of_eventuallyEq (f := γ (|t| + 1))
· exact hγ (|t| + 1) (by positivity) _ ht |>.hasMFDerivAt (Ioo_mem_nhds ht.1 ht.2)
· rw [Filter.eventuallyEq_iff_exists_mem]
refine ⟨Ioo (-(|t| + 1)) (|t| + 1), ?_,
eqOn_abs_add_one_of_isMIntegralCurveOn_Ioo hv γ hγx hγ⟩
have : |t| < |t| + 1 := lt_add_of_pos_right |t| zero_lt_one
rw [abs_lt] at this
exact Ioo_mem_nhds this.1 this.2
@[deprecated (since := "2025-08-12")] alias
isIntegralCurve_abs_add_one_of_isIntegralCurveOn_Ioo :=
isMIntegralCurve_abs_add_one_of_isMIntegralCurveOn_Ioo
/-- The existence of a global integral curve is equivalent to the existence of a family of local
integral curves `γ : ℝ → ℝ → M` with the same starting point `γ 0 = x` such that each `γ a` is
defined on `Ioo (-a) a`. -/
lemma exists_isMIntegralCurve_iff_exists_isMIntegralCurveOn_Ioo [BoundarylessManifold I M]
(hv : ContMDiff I I.tangent 1 (fun x ↦ (⟨x, v x⟩ : TangentBundle I M))) (x : M) :
(∃ γ, γ 0 = x ∧ IsMIntegralCurve γ v) ↔
∀ a, ∃ γ, γ 0 = x ∧ IsMIntegralCurveOn γ v (Ioo (-a) a) := by
refine ⟨fun ⟨γ, h1, h2⟩ _ ↦ ⟨γ, h1, h2.isMIntegralCurveOn _⟩, fun h ↦ ?_⟩
choose γ hγx hγ using h
exact ⟨fun t ↦ γ (|t| + 1) t, hγx (|0| + 1),
isMIntegralCurve_abs_add_one_of_isMIntegralCurveOn_Ioo hv γ hγx (fun a _ ↦ hγ a)⟩
@[deprecated (since := "2025-08-12")] alias
exists_isIntegralCurve_iff_exists_isIntegralCurveOn_Ioo :=
exists_isMIntegralCurve_iff_exists_isMIntegralCurveOn_Ioo
/-- Let `γ` and `γ'` be integral curves defined on `Ioo a b` and `Ioo a' b'`, respectively. Then,
`piecewise (Ioo a b) γ γ'` is equal to `γ` and `γ'` in their respective domains.
`Set.piecewise_eqOn` shows the equality for `γ` by definition, while this lemma shows the equality
for `γ'` by the uniqueness of integral curves. -/
lemma eqOn_piecewise_of_isMIntegralCurveOn_Ioo [BoundarylessManifold I M]
(hv : ContMDiff I I.tangent 1 (fun x ↦ (⟨x, v x⟩ : TangentBundle I M)))
{a b a' b' : ℝ} (hγ : IsMIntegralCurveOn γ v (Ioo a b))
(hγ' : IsMIntegralCurveOn γ' v (Ioo a' b'))
(ht₀ : t₀ ∈ Ioo a b ∩ Ioo a' b') (h : γ t₀ = γ' t₀) :
EqOn (piecewise (Ioo a b) γ γ') γ' (Ioo a' b') := by
intros t ht
suffices H : EqOn γ γ' (Ioo (max a a') (min b b')) by
by_cases hmem : t ∈ Ioo a b
· rw [piecewise, if_pos hmem]
apply H
simp [ht.1, ht.2, hmem.1, hmem.2]
· rw [piecewise, if_neg hmem]
apply isMIntegralCurveOn_Ioo_eqOn_of_contMDiff_boundaryless _ hv
(hγ.mono (Ioo_subset_Ioo (le_max_left ..) (min_le_left ..)))
(hγ'.mono (Ioo_subset_Ioo (le_max_right ..) (min_le_right ..))) h
exact ⟨max_lt ht₀.1.1 ht₀.2.1, lt_min ht₀.1.2 ht₀.2.2⟩
@[deprecated (since := "2025-08-12")] alias eqOn_piecewise_of_isIntegralCurveOn_Ioo :=
eqOn_piecewise_of_isMIntegralCurveOn_Ioo
/-- The extension of an integral curve by another integral curve is an integral curve.
If two integral curves are defined on overlapping open intervals, and they agree at a point in
their common domain, then they can be patched together to form a longer integral curve.
This is stated for manifolds without boundary for simplicity. We actually only need to assume that
the images of `γ` and `γ'` lie in the interior of the manifold.
TODO: Generalise to manifolds with boundary. -/
lemma isMIntegralCurveOn_piecewise [BoundarylessManifold I M]
(hv : ContMDiff I I.tangent 1 (fun x ↦ (⟨x, v x⟩ : TangentBundle I M)))
{a b a' b' : ℝ} (hγ : IsMIntegralCurveOn γ v (Ioo a b))
(hγ' : IsMIntegralCurveOn γ' v (Ioo a' b')) {t₀ : ℝ}
(ht₀ : t₀ ∈ Ioo a b ∩ Ioo a' b') (h : γ t₀ = γ' t₀) :
IsMIntegralCurveOn (piecewise (Ioo a b) γ γ') v (Ioo a b ∪ Ioo a' b') := by
intros t ht
by_cases hmem : t ∈ Ioo a b
· rw [piecewise, if_pos hmem]
apply hγ t hmem |>.hasMFDerivAt (Ioo_mem_nhds hmem.1 hmem.2) |>.hasMFDerivWithinAt
(s := Ioo a b ∪ Ioo a' b') |>.congr_of_eventuallyEq _ (by rw [piecewise, if_pos hmem])
rw [Filter.eventuallyEq_iff_exists_mem]
refine ⟨Ioo a b, ?_, fun _ ht' ↦ by rw [piecewise, if_pos ht']⟩
rw [(isOpen_Ioo.union isOpen_Ioo).nhdsWithin_eq ht]
exact Ioo_mem_nhds hmem.1 hmem.2
· have ht' := ht
rw [mem_union, or_iff_not_imp_left] at ht
rw [piecewise, if_neg hmem]
apply hγ' t (ht hmem) |>.hasMFDerivAt (Ioo_mem_nhds (ht hmem).1 (ht hmem).2)
|>.hasMFDerivWithinAt (s := Ioo a b ∪ Ioo a' b')
|>.congr_of_eventuallyEq _ (by rw [piecewise, if_neg hmem])
rw [Filter.eventuallyEq_iff_exists_mem]
refine ⟨Ioo a' b', ?_,
eqOn_piecewise_of_isMIntegralCurveOn_Ioo hv hγ hγ' ht₀ h⟩
rw [(isOpen_Ioo.union isOpen_Ioo).nhdsWithin_eq ht']
exact Ioo_mem_nhds (ht hmem).1 (ht hmem).2
@[deprecated (since := "2025-08-12")] alias isIntegralCurveOn_piecewise :=
isMIntegralCurveOn_piecewise
/-- If there exists `ε > 0` such that the local integral curve at each point `x : M` is defined at
least on an open interval `Ioo (-ε) ε`, then every point on `M` has a global integral curve
passing through it.
See Lemma 9.15, [J.M. Lee (2012)][lee2012]. -/
lemma exists_isMIntegralCurve_of_isMIntegralCurveOn [BoundarylessManifold I M]
{v : (x : M) → TangentSpace I x}
(hv : ContMDiff I I.tangent 1 (fun x ↦ (⟨x, v x⟩ : TangentBundle I M)))
{ε : ℝ} (hε : 0 < ε) (h : ∀ x : M, ∃ γ : ℝ → M, γ 0 = x ∧ IsMIntegralCurveOn γ v (Ioo (-ε) ε))
(x : M) : ∃ γ : ℝ → M, γ 0 = x ∧ IsMIntegralCurve γ v := by
let s := { a | ∃ γ, γ 0 = x ∧ IsMIntegralCurveOn γ v (Ioo (-a) a) }
suffices hbdd : ¬BddAbove s by
rw [not_bddAbove_iff] at hbdd
rw [exists_isMIntegralCurve_iff_exists_isMIntegralCurveOn_Ioo hv]
intro a
obtain ⟨y, ⟨γ, hγ1, hγ2⟩, hlt⟩ := hbdd a
exact ⟨γ, hγ1, hγ2.mono <| Ioo_subset_Ioo (neg_le_neg hlt.le) hlt.le⟩
intro hbdd
set asup := sSup s with hasup
-- we will obtain two integral curves, one centred at some `t₀ > 0` with
-- `0 ≤ asup - ε < t₀ < asup`; let `t₀ = asup - ε / 2`
-- another centred at 0 with domain up to `a ∈ S` with `t₀ < a < asup`
obtain ⟨a, ha, hlt⟩ := Real.add_neg_lt_sSup (⟨ε, h x⟩ : Set.Nonempty s) (ε := - (ε / 2))
(by rw [neg_lt, neg_zero]; exact half_pos hε)
rw [mem_setOf] at ha
rw [← hasup, ← sub_eq_add_neg] at hlt
-- integral curve defined on `Ioo (-a) a`
obtain ⟨γ, h0, hγ⟩ := ha
-- integral curve starting at `-(asup - ε / 2)` with radius `ε`
obtain ⟨γ1_aux, h1_aux, hγ1⟩ := h (γ (-(asup - ε / 2)))
rw [isMIntegralCurveOn_comp_add (dt := asup - ε / 2)] at hγ1
set γ1 := γ1_aux ∘ (· + (asup - ε / 2)) with γ1_def
have heq1 : γ1 (-(asup - ε / 2)) = γ (-(asup - ε / 2)) := by simp [γ1_def, h1_aux]
-- integral curve starting at `asup - ε / 2` with radius `ε`
obtain ⟨γ2_aux, h2_aux, hγ2⟩ := h (γ (asup - ε / 2))
rw [isMIntegralCurveOn_comp_sub (dt := asup - ε / 2)] at hγ2
set γ2 := γ2_aux ∘ (· - (asup - ε / 2)) with γ2_def
have heq2 : γ2 (asup - ε / 2) = γ (asup - ε / 2) := by simp [γ2_def, h2_aux]
-- rewrite shifted Ioo as Ioo
simp_rw [Set.mem_Ioo, ← sub_lt_iff_lt_add, ← lt_sub_iff_add_lt, ← Set.mem_Ioo] at hγ1
simp_rw [Set.mem_Ioo, lt_sub_iff_add_lt, sub_lt_iff_lt_add, ← Set.mem_Ioo] at hγ2
-- to help `linarith`
have hεle : ε ≤ asup := le_csSup hbdd (h x)
-- extend `γ` on the left by `γ1` and on the right by `γ2`
set γ_ext : ℝ → M := piecewise (Ioo (-(asup + ε / 2)) a)
(piecewise (Ioo (-a) a) γ γ1) γ2 with γ_ext_def
have heq_ext : γ_ext 0 = x := by
rw [γ_ext_def, piecewise, if_pos ⟨by linarith, by linarith⟩, piecewise,
if_pos ⟨by linarith, by linarith⟩, h0]
-- `asup + ε / 2` is an element of `s` greater than `asup`, a contradiction
suffices hext : IsMIntegralCurveOn γ_ext v (Ioo (-(asup + ε / 2)) (asup + ε / 2)) from
(not_lt.mpr <| le_csSup hbdd ⟨γ_ext, heq_ext, hext⟩) <| lt_add_of_pos_right asup (half_pos hε)
apply (isMIntegralCurveOn_piecewise (t₀ := asup - ε / 2) hv _ hγ2
⟨⟨by linarith, hlt⟩, ⟨by linarith, by linarith⟩⟩
(by rw [piecewise, if_pos ⟨by linarith, hlt⟩, ← heq2])).mono
(Ioo_subset_Ioo_union_Ioo le_rfl (by linarith) (by linarith))
exact (isMIntegralCurveOn_piecewise (t₀ := -(asup - ε / 2)) hv hγ hγ1
⟨⟨neg_lt_neg hlt, by linarith⟩, ⟨by linarith, by linarith⟩⟩ heq1.symm).mono
(union_comm _ _ ▸ Ioo_subset_Ioo_union_Ioo (by linarith) (by linarith) le_rfl)
@[deprecated (since := "2025-08-12")] alias exists_isIntegralCurve_of_isIntegralCurveOn :=
exists_isMIntegralCurve_of_isMIntegralCurveOn
|
PresheafOfFunctions.lean
|
/-
Copyright (c) 2019 Kim Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Morrison
-/
import Mathlib.Topology.Sheaves.Presheaf
/-!
# Presheaves of functions
We construct some simple examples of presheaves of functions on a topological space.
* `presheafToTypes X T`, where `T : X → Type`,
is the presheaf of dependently-typed (not-necessarily continuous) functions
* `presheafToType X T`, where `T : Type`,
is the presheaf of (not-necessarily-continuous) functions to a fixed target type `T`
* `presheafToTop X T`, where `T : TopCat`,
is the presheaf of continuous functions into a topological space `T`
* `presheafToTopCommRing X R`, where `R : TopCommRingCat`
is the presheaf valued in `CommRing` of functions functions into a topological ring `R`
* as an example of the previous construction,
`presheafToTopCommRing X (TopCommRingCat.of ℂ)`
is the presheaf of rings of continuous complex-valued functions on `X`.
-/
open CategoryTheory TopologicalSpace Opposite
namespace TopCat
variable (X : TopCat)
/-- The presheaf of dependently typed functions on `X`, with fibres given by a type family `T`.
There is no requirement that the functions are continuous, here.
-/
def presheafToTypes (T : X → Type*) : X.Presheaf (Type _) where
obj U := ∀ x : U.unop, T x
map {_ V} i g := fun x : V.unop => g (i.unop x)
map_id U := by
ext g
rfl
map_comp {_ _ _} _ _ := rfl
@[simp]
theorem presheafToTypes_obj {T : X → Type*} {U : (Opens X)ᵒᵖ} :
(presheafToTypes X T).obj U = ∀ x : U.unop, T x :=
rfl
@[simp]
theorem presheafToTypes_map {T : X → Type*} {U V : (Opens X)ᵒᵖ} {i : U ⟶ V} {f} :
(presheafToTypes X T).map i f = fun x => f (i.unop x) :=
rfl
-- We don't just define this in terms of `presheafToTypes`,
-- as it's helpful later to see (at a syntactic level) that `(presheafToType X T).obj U`
-- is a non-dependent function.
-- We don't use `@[simps]` to generate the projection lemmas here,
-- as it turns out to be useful to have `presheafToType_map`
-- written as an equality of functions (rather than being applied to some argument).
/-- The presheaf of functions on `X` with values in a type `T`.
There is no requirement that the functions are continuous, here.
-/
def presheafToType (T : Type*) : X.Presheaf (Type _) where
obj U := U.unop → T
map {_ _} i g := g ∘ i.unop
map_id U := by
ext g
rfl
map_comp {_ _ _} _ _ := rfl
@[simp]
theorem presheafToType_obj {T : Type*} {U : (Opens X)ᵒᵖ} :
(presheafToType X T).obj U = (U.unop → T) :=
rfl
@[simp]
theorem presheafToType_map {T : Type*} {U V : (Opens X)ᵒᵖ} {i : U ⟶ V} {f} :
(presheafToType X T).map i f = f ∘ i.unop :=
rfl
/-- The presheaf of continuous functions on `X` with values in fixed target topological space
`T`. -/
def presheafToTop (T : TopCat) : X.Presheaf (Type _) :=
(Opens.toTopCat X).op ⋙ yoneda.obj T
@[simp]
theorem presheafToTop_obj (T : TopCat) (U : (Opens X)ᵒᵖ) :
(presheafToTop X T).obj U = ((Opens.toTopCat X).obj (unop U) ⟶ T) :=
rfl
end TopCat
|
ExtensiveSheaves.lean
|
/-
Copyright (c) 2023 Dagur Asgeirsson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Dagur Asgeirsson, Filippo A. E. Nuccio, Riccardo Brasca
-/
import Mathlib.CategoryTheory.Limits.Preserves.Finite
import Mathlib.CategoryTheory.Sites.Canonical
import Mathlib.CategoryTheory.Sites.Coherent.Basic
import Mathlib.CategoryTheory.Sites.Preserves
/-!
# Sheaves for the extensive topology
This file characterises sheaves for the extensive topology.
## Main result
* `isSheaf_iff_preservesFiniteProducts`: In a finitary extensive category, the sheaves for the
extensive topology are precisely those preserving finite products.
-/
universe w
namespace CategoryTheory
open Limits Presieve Opposite
variable {C : Type*} [Category C] {D : Type*} [Category D]
variable [FinitaryPreExtensive C]
/-- A presieve is *extensive* if it is finite and its arrows induce an isomorphism from the
coproduct to the target. -/
class Presieve.Extensive {X : C} (R : Presieve X) : Prop where
/-- `R` consists of a finite collection of arrows that together induce an isomorphism from the
coproduct of their sources. -/
arrows_nonempty_isColimit : ∃ (α : Type) (_ : Finite α) (Z : α → C) (π : (a : α) → (Z a ⟶ X)),
R = Presieve.ofArrows Z π ∧ Nonempty (IsColimit (Cofan.mk X π))
instance {X : C} (S : Presieve X) [S.Extensive] : S.hasPullbacks where
has_pullbacks := by
obtain ⟨_, _, _, _, rfl, ⟨hc⟩⟩ := Presieve.Extensive.arrows_nonempty_isColimit (R := S)
intro _ _ _ _ _ hg
cases hg
apply FinitaryPreExtensive.hasPullbacks_of_is_coproduct hc
/--
A finite product preserving presheaf is a sheaf for the extensive topology on a category which is
`FinitaryPreExtensive`.
-/
theorem isSheafFor_extensive_of_preservesFiniteProducts {X : C} (S : Presieve X) [S.Extensive]
(F : Cᵒᵖ ⥤ Type w) [PreservesFiniteProducts F] : S.IsSheafFor F := by
obtain ⟨α, _, Z, π, rfl, ⟨hc⟩⟩ := Extensive.arrows_nonempty_isColimit (R := S)
have : (ofArrows Z (Cofan.mk X π).inj).hasPullbacks :=
(inferInstance : (ofArrows Z π).hasPullbacks)
cases nonempty_fintype α
exact isSheafFor_of_preservesProduct F _ hc
instance {α : Type} [Finite α] (Z : α → C) : (ofArrows Z (fun i ↦ Sigma.ι Z i)).Extensive :=
⟨⟨α, inferInstance, Z, (fun i ↦ Sigma.ι Z i), rfl, ⟨coproductIsCoproduct _⟩⟩⟩
/-- Every Yoneda-presheaf is a sheaf for the extensive topology. -/
theorem extensiveTopology.isSheaf_yoneda_obj (W : C) : Presieve.IsSheaf (extensiveTopology C)
(yoneda.obj W) := by
rw [extensiveTopology, isSheaf_coverage]
intro X R ⟨Y, α, Z, π, hR, hi⟩
have : IsIso (Sigma.desc (Cofan.inj (Cofan.mk X π))) := hi
have : R.Extensive := ⟨Y, α, Z, π, hR, ⟨Cofan.isColimitOfIsIsoSigmaDesc (Cofan.mk X π)⟩⟩
exact isSheafFor_extensive_of_preservesFiniteProducts _ _
/-- The extensive topology on a finitary pre-extensive category is subcanonical. -/
instance extensiveTopology.subcanonical : (extensiveTopology C).Subcanonical :=
GrothendieckTopology.Subcanonical.of_isSheaf_yoneda_obj _ isSheaf_yoneda_obj
variable [FinitaryExtensive C]
/--
A presheaf of sets on a category which is `FinitaryExtensive` is a sheaf iff it preserves finite
products.
-/
theorem Presieve.isSheaf_iff_preservesFiniteProducts (F : Cᵒᵖ ⥤ Type w) :
Presieve.IsSheaf (extensiveTopology C) F ↔ PreservesFiniteProducts F := by
refine ⟨fun hF ↦ ⟨fun n ↦ ⟨fun {K} ↦ ?_⟩⟩, fun hF ↦ ?_⟩
· rw [extensiveTopology, isSheaf_coverage] at hF
let Z : Fin n → C := fun i ↦ unop (K.obj ⟨i⟩)
have : (ofArrows Z (Cofan.mk (∐ Z) (Sigma.ι Z)).inj).hasPullbacks :=
inferInstanceAs (ofArrows Z (Sigma.ι Z)).hasPullbacks
have : ∀ (i : Fin n), Mono (Cofan.inj (Cofan.mk (∐ Z) (Sigma.ι Z)) i) :=
inferInstanceAs <| ∀ (i : Fin n), Mono (Sigma.ι Z i)
let i : K ≅ Discrete.functor (fun i ↦ op (Z i)) := Discrete.natIsoFunctor
let _ : PreservesLimit (Discrete.functor (fun i ↦ op (Z i))) F :=
Presieve.preservesProduct_of_isSheafFor F ?_ initialIsInitial _ (coproductIsCoproduct Z)
(FinitaryExtensive.isPullback_initial_to_sigma_ι Z)
(hF (Presieve.ofArrows Z (fun i ↦ Sigma.ι Z i)) ?_)
· exact preservesLimit_of_iso_diagram F i.symm
· apply hF
refine ⟨Empty, inferInstance, Empty.elim, IsEmpty.elim inferInstance, rfl, ⟨default,?_, ?_⟩⟩
· ext b
cases b
· simp only [eq_iff_true_of_subsingleton]
· refine ⟨Fin n, inferInstance, Z, (fun i ↦ Sigma.ι Z i), rfl, ?_⟩
suffices Sigma.desc (fun i ↦ Sigma.ι Z i) = 𝟙 _ by rw [this]; infer_instance
ext
simp
· rw [extensiveTopology, Presieve.isSheaf_coverage]
intro X R ⟨Y, α, Z, π, hR, hi⟩
have : IsIso (Sigma.desc (Cofan.inj (Cofan.mk X π))) := hi
have : R.Extensive := ⟨Y, α, Z, π, hR, ⟨Cofan.isColimitOfIsIsoSigmaDesc (Cofan.mk X π)⟩⟩
exact isSheafFor_extensive_of_preservesFiniteProducts R F
/--
A presheaf on a category which is `FinitaryExtensive` is a sheaf iff it preserves finite products.
-/
theorem Presheaf.isSheaf_iff_preservesFiniteProducts (F : Cᵒᵖ ⥤ D) :
IsSheaf (extensiveTopology C) F ↔ PreservesFiniteProducts F := by
constructor
· intro h
rw [IsSheaf] at h
refine ⟨fun n ↦ ⟨fun {K} ↦ ⟨fun {c} hc ↦ ?_⟩⟩⟩
constructor
apply coyonedaJointlyReflectsLimits
intro ⟨E⟩
specialize h E
rw [Presieve.isSheaf_iff_preservesFiniteProducts] at h
exact isLimitOfPreserves (F.comp (coyoneda.obj ⟨E⟩)) hc
· intro _ E
rw [Presieve.isSheaf_iff_preservesFiniteProducts]
exact ⟨inferInstance⟩
instance (F : Sheaf (extensiveTopology C) D) : PreservesFiniteProducts F.val :=
(Presheaf.isSheaf_iff_preservesFiniteProducts F.val).mp F.cond
end CategoryTheory
|
Schreier.lean
|
/-
Copyright (c) 2022 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import Mathlib.Algebra.Group.Pointwise.Finset.Basic
import Mathlib.GroupTheory.Abelianization.Defs
import Mathlib.GroupTheory.Commutator.Finite
import Mathlib.GroupTheory.Transfer
/-!
# Schreier's Lemma
In this file we prove Schreier's lemma.
## Main results
- `closure_mul_image_eq` : **Schreier's Lemma**: If `R : Set G` is a right_transversal
of `H : Subgroup G` with `1 ∈ R`, and if `G` is generated by `S : Set G`,
then `H` is generated by the `Set` `(R * S).image (fun g ↦ g * (hR.toRightFun g)⁻¹)`.
- `fg_of_index_ne_zero` : **Schreier's Lemma**: A finite index subgroup of a finitely generated
group is finitely generated.
- `card_commutator_le_of_finite_commutatorSet`: A theorem of Schur: The size of the commutator
subgroup is bounded in terms of the number of commutators.
-/
open scoped Finset Pointwise
section CommGroup
open Subgroup
variable (G : Type*) [CommGroup G] [Group.FG G]
@[to_additive]
theorem card_dvd_exponent_pow_rank : Nat.card G ∣ Monoid.exponent G ^ Group.rank G := by
classical
obtain ⟨S, hS1, hS2⟩ := Group.rank_spec G
rw [← hS1, ← Fintype.card_coe, ← Finset.card_univ, ← Finset.prod_const]
let f : (∀ g : S, zpowers (g : G)) →* G := noncommPiCoprod fun s t _ x y _ _ => mul_comm x _
have hf : Function.Surjective f := by
rw [← MonoidHom.range_eq_top, eq_top_iff, ← hS2, closure_le]
exact fun g hg => ⟨Pi.mulSingle ⟨g, hg⟩ ⟨g, mem_zpowers g⟩, noncommPiCoprod_mulSingle _ _⟩
replace hf := card_dvd_of_surjective f hf
rw [Nat.card_pi] at hf
refine hf.trans (Finset.prod_dvd_prod_of_dvd _ _ fun g _ => ?_)
rw [Nat.card_zpowers]
exact Monoid.order_dvd_exponent (g : G)
@[to_additive]
theorem card_dvd_exponent_pow_rank' {n : ℕ} (hG : ∀ g : G, g ^ n = 1) :
Nat.card G ∣ n ^ Group.rank G :=
(card_dvd_exponent_pow_rank G).trans
(pow_dvd_pow_of_dvd (Monoid.exponent_dvd_of_forall_pow_eq_one hG) (Group.rank G))
end CommGroup
namespace Subgroup
variable {G : Type*} [Group G] {H : Subgroup G} {R S : Set G}
theorem closure_mul_image_mul_eq_top
(hR : IsComplement H R) (hR1 : (1 : G) ∈ R) (hS : closure S = ⊤) :
(closure ((R * S).image fun g => g * (hR.toRightFun g : G)⁻¹)) * R = ⊤ := by
let f : G → R := hR.toRightFun
let U : Set G := (R * S).image fun g => g * (f g : G)⁻¹
change (closure U : Set G) * R = ⊤
refine top_le_iff.mp fun g _ => ?_
refine closure_induction_right ?_ ?_ ?_ (eq_top_iff.mp hS (mem_top g))
· exact ⟨1, (closure U).one_mem, 1, hR1, one_mul 1⟩
· rintro - - s hs ⟨u, hu, r, hr, rfl⟩
rw [show u * r * s = u * (r * s * (f (r * s) : G)⁻¹) * f (r * s) by group]
refine Set.mul_mem_mul ((closure U).mul_mem hu ?_) (f (r * s)).coe_prop
exact subset_closure ⟨r * s, Set.mul_mem_mul hr hs, rfl⟩
· rintro - - s hs ⟨u, hu, r, hr, rfl⟩
rw [show u * r * s⁻¹ = u * (f (r * s⁻¹) * s * r⁻¹)⁻¹ * f (r * s⁻¹) by group]
refine Set.mul_mem_mul ((closure U).mul_mem hu ((closure U).inv_mem ?_)) (f (r * s⁻¹)).2
refine subset_closure ⟨f (r * s⁻¹) * s, Set.mul_mem_mul (f (r * s⁻¹)).2 hs, ?_⟩
rw [mul_right_inj, inv_inj, ← Subtype.coe_mk r hr, ← Subtype.ext_iff, Subtype.coe_mk]
apply (isComplement_iff_existsUnique_mul_inv_mem.mp hR (f (r * s⁻¹) * s)).unique
(hR.mul_inv_toRightFun_mem (f (r * s⁻¹) * s))
rw [mul_assoc, ← inv_inv s, ← mul_inv_rev, inv_inv]
exact hR.toRightFun_mul_inv_mem (r * s⁻¹)
/-- **Schreier's Lemma**: If `R : Set G` is a `rightTransversal` of `H : Subgroup G`
with `1 ∈ R`, and if `G` is generated by `S : Set G`, then `H` is generated by the `Set`
`(R * S).image (fun g ↦ g * (hR.toRightFun g)⁻¹)`. -/
theorem closure_mul_image_eq (hR : IsComplement H R) (hR1 : (1 : G) ∈ R)
(hS : closure S = ⊤) : closure ((R * S).image fun g => g * (hR.toRightFun g : G)⁻¹) = H := by
have hU : closure ((R * S).image fun g => g * (hR.toRightFun g : G)⁻¹) ≤ H := by
rw [closure_le]
rintro - ⟨g, -, rfl⟩
exact hR.mul_inv_toRightFun_mem g
refine le_antisymm hU fun h hh => ?_
obtain ⟨g, hg, r, hr, rfl⟩ :=
show h ∈ _ from eq_top_iff.mp (closure_mul_image_mul_eq_top hR hR1 hS) (mem_top h)
suffices (⟨r, hr⟩ : R) = (⟨1, hR1⟩ : R) by
simpa only [show r = 1 from Subtype.ext_iff.mp this, mul_one]
apply (isComplement_iff_existsUnique_mul_inv_mem.mp hR r).unique
· rw [Subtype.coe_mk, mul_inv_cancel]
exact H.one_mem
· rw [Subtype.coe_mk, inv_one, mul_one]
exact (H.mul_mem_cancel_left (hU hg)).mp hh
/-- **Schreier's Lemma**: If `R : Set G` is a `rightTransversal` of `H : Subgroup G`
with `1 ∈ R`, and if `G` is generated by `S : Set G`, then `H` is generated by the `Set`
`(R * S).image (fun g ↦ g * (hR.toRightFun g)⁻¹)`. -/
theorem closure_mul_image_eq_top (hR : IsComplement H R) (hR1 : (1 : G) ∈ R)
(hS : closure S = ⊤) : closure ((R * S).image fun g =>
⟨g * (hR.toRightFun g : G)⁻¹, hR.mul_inv_toRightFun_mem g⟩ : Set H) = ⊤ := by
rw [eq_top_iff, ← map_subtype_le_map_subtype, MonoidHom.map_closure, Set.image_image]
exact (map_subtype_le ⊤).trans (ge_of_eq (closure_mul_image_eq hR hR1 hS))
/-- **Schreier's Lemma**: If `R : Finset G` is a `rightTransversal` of `H : Subgroup G`
with `1 ∈ R`, and if `G` is generated by `S : Finset G`, then `H` is generated by the `Finset`
`(R * S).image (fun g ↦ g * (hR.toRightFun g)⁻¹)`. -/
theorem closure_mul_image_eq_top' [DecidableEq G] {R S : Finset G}
(hR : IsComplement (H : Set G) R) (hR1 : (1 : G) ∈ R)
(hS : closure (S : Set G) = ⊤) :
closure (((R * S).image fun g => ⟨_, hR.mul_inv_toRightFun_mem g⟩ : Finset H) : Set H) = ⊤ := by
rw [Finset.coe_image, Finset.coe_mul]
exact closure_mul_image_eq_top hR hR1 hS
variable (H)
theorem exists_finset_card_le_mul [FiniteIndex H] {S : Finset G} (hS : closure (S : Set G) = ⊤) :
∃ T : Finset H, #T ≤ H.index * #S ∧ closure (T : Set H) = ⊤ := by
letI := H.fintypeQuotientOfFiniteIndex
haveI : DecidableEq G := Classical.decEq G
obtain ⟨R₀, hR, hR1⟩ := H.exists_isComplement_right 1
haveI : Fintype R₀ := Fintype.ofEquiv _ hR.rightQuotientEquiv
let R : Finset G := Set.toFinset R₀
replace hR : IsComplement (H : Set G) R := by rwa [Set.coe_toFinset]
replace hR1 : (1 : G) ∈ R := by rwa [Set.mem_toFinset]
refine ⟨_, ?_, closure_mul_image_eq_top' hR hR1 hS⟩
calc
_ ≤ #(R * S) := Finset.card_image_le
_ ≤ #R * #S := Finset.card_mul_le
_ = H.index * S.card := congr_arg (· * S.card) ?_
calc
#R = Fintype.card R := (Fintype.card_coe R).symm
_ = _ := (Fintype.card_congr hR.rightQuotientEquiv).symm
_ = Fintype.card (G ⧸ H) := QuotientGroup.card_quotient_rightRel H
_ = H.index := by rw [index_eq_card, Nat.card_eq_fintype_card]
/-- **Schreier's Lemma**: A finite index subgroup of a finitely generated
group is finitely generated. -/
instance fg_of_index_ne_zero [hG : Group.FG G] [FiniteIndex H] : Group.FG H := by
obtain ⟨S, hS⟩ := hG.1
obtain ⟨T, -, hT⟩ := exists_finset_card_le_mul H hS
exact ⟨⟨T, hT⟩⟩
theorem rank_le_index_mul_rank [hG : Group.FG G] [FiniteIndex H] :
Group.rank H ≤ H.index * Group.rank G := by
haveI := H.fg_of_index_ne_zero
obtain ⟨S, hS₀, hS⟩ := Group.rank_spec G
obtain ⟨T, hT₀, hT⟩ := exists_finset_card_le_mul H hS
calc
Group.rank H ≤ #T := Group.rank_le hT
_ ≤ H.index * #S := hT₀
_ = H.index * Group.rank G := congr_arg (H.index * ·) hS₀
variable (G)
/-- If `G` has `n` commutators `[g₁, g₂]`, then `|G'| ∣ [G : Z(G)] ^ ([G : Z(G)] * n + 1)`,
where `G'` denotes the commutator of `G`. -/
theorem card_commutator_dvd_index_center_pow [Finite (commutatorSet G)] :
Nat.card (_root_.commutator G) ∣
(center G).index ^ ((center G).index * Nat.card (commutatorSet G) + 1) := by
-- First handle the case when `Z(G)` has infinite index and `[G : Z(G)]` is defined to be `0`
by_cases hG : (center G).index = 0
· simp_rw [hG, zero_mul, zero_add, pow_one, dvd_zero]
haveI : FiniteIndex (center G) := ⟨hG⟩
-- Rewrite as `|Z(G) ∩ G'| * [G' : Z(G) ∩ G'] ∣ [G : Z(G)] ^ ([G : Z(G)] * n) * [G : Z(G)]`
rw [← ((center G).subgroupOf (_root_.commutator G)).card_mul_index, pow_succ]
-- We have `h1 : [G' : Z(G) ∩ G'] ∣ [G : Z(G)]`
have h1 := relindex_dvd_index_of_normal (center G) (_root_.commutator G)
-- So we can reduce to proving `|Z(G) ∩ G'| ∣ [G : Z(G)] ^ ([G : Z(G)] * n)`
refine mul_dvd_mul ?_ h1
-- We know that `[G' : Z(G) ∩ G'] < ∞` by `h1` and `hG`
haveI : FiniteIndex ((center G).subgroupOf (_root_.commutator G)) :=
⟨ne_zero_of_dvd_ne_zero hG h1⟩
-- We have `h2 : rank (Z(G) ∩ G') ≤ [G' : Z(G) ∩ G'] * rank G'` by Schreier's lemma
have h2 := rank_le_index_mul_rank ((center G).subgroupOf (_root_.commutator G))
-- We have `h3 : [G' : Z(G) ∩ G'] * rank G' ≤ [G : Z(G)] * n` by `h1` and `rank G' ≤ n`
have h3 := Nat.mul_le_mul (Nat.le_of_dvd (Nat.pos_of_ne_zero hG) h1) (rank_commutator_le_card G)
-- So we can reduce to proving `|Z(G) ∩ G'| ∣ [G : Z(G)] ^ rank (Z(G) ∩ G')`
refine dvd_trans ?_ (pow_dvd_pow (center G).index (h2.trans h3))
-- `Z(G) ∩ G'` is abelian, so it enough to prove that `g ^ [G : Z(G)] = 1` for `g ∈ Z(G) ∩ G'`
apply card_dvd_exponent_pow_rank'
intro g
-- `Z(G)` is abelian, so `g ∈ Z(G) ∩ G' ≤ G' ≤ ker (transfer : G → Z(G))`
have := Abelianization.commutator_subset_ker (MonoidHom.transferCenterPow G) g.1.2
-- `transfer g` is defeq to `g ^ [G : Z(G)]`, so we are done
simpa only [MonoidHom.mem_ker, Subtype.ext_iff] using this
/-- A bound for the size of the commutator subgroup in terms of the number of commutators. -/
def cardCommutatorBound (n : ℕ) :=
(n ^ (2 * n)) ^ (n ^ (2 * n + 1) + 1)
/-- A theorem of Schur: The size of the commutator subgroup is bounded in terms of the number of
commutators. -/
theorem card_commutator_le_of_finite_commutatorSet [Finite (commutatorSet G)] :
Nat.card (_root_.commutator G) ≤ cardCommutatorBound (Nat.card (commutatorSet G)) := by
have h1 := index_center_le_pow (closureCommutatorRepresentatives G)
have h2 := card_commutator_dvd_index_center_pow (closureCommutatorRepresentatives G)
rw [card_commutatorSet_closureCommutatorRepresentatives] at h1 h2
rw [card_commutator_closureCommutatorRepresentatives] at h2
replace h1 :=
h1.trans
(Nat.pow_le_pow_right Finite.card_pos (rank_closureCommutatorRepresentatives_le G))
replace h2 := h2.trans (pow_dvd_pow _ (add_le_add_right (mul_le_mul_right' h1 _) 1))
rw [← pow_succ] at h2
refine (Nat.le_of_dvd ?_ h2).trans (Nat.pow_le_pow_left h1 _)
exact pow_pos (Nat.pos_of_ne_zero FiniteIndex.index_ne_zero) _
/-- A theorem of Schur: A group with finitely many commutators has finite commutator subgroup. -/
instance [Finite (commutatorSet G)] : Finite (_root_.commutator G) := by
have h2 := card_commutator_dvd_index_center_pow (closureCommutatorRepresentatives G)
refine Nat.finite_of_card_ne_zero fun h => ?_
rw [card_commutator_closureCommutatorRepresentatives, h, zero_dvd_iff] at h2
exact FiniteIndex.index_ne_zero (pow_eq_zero h2)
end Subgroup
|
FunProp.lean
|
/-
Copyright (c) 2024 Tomas Skrivan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tomas Skrivan
-/
import Mathlib.Tactic.FunProp.Attr
import Mathlib.Tactic.FunProp.Core
import Mathlib.Tactic.FunProp.Decl
import Mathlib.Tactic.FunProp.Elab
import Mathlib.Tactic.FunProp.FunctionData
import Mathlib.Tactic.FunProp.Mor
import Mathlib.Tactic.FunProp.Theorems
import Mathlib.Tactic.FunProp.ToBatteries
import Mathlib.Tactic.FunProp.Types
/-!
# Tactic `fun_prop` for proving function properties like `Continuous f`, `Differentiable ℝ f`, ...
**Basic use:**
Using the `fun_prop` tactic should be as simple as:
```lean
example : Continuous (fun x : ℝ => x * sin x) := by fun_prop
```
Mathlib sets up `fun_prop` for many different properties like `Continuous`, `Measurable`,
`Differentiable`, `ContDiff`, etc., so `fun_prop` should work for such goals. The basic idea behind
`fun_prop` is that it decomposes the function into a composition of elementary functions and then
checks if every single elementary function is, e.g., `Continuous`.
For `ContinuousAt/On/Within` variants, one has to specify a tactic to solve potential side goals
with `disch:=<tactic>`. For example:
```lean
example (y : ℝ) (hy : y ≠ 0) : ContinuousAt (fun x : ℝ => 1/x) y := by fun_prop (disch:=assumption)
```
**Basic debugging:**
The most common issue is that a function is missing the appropriate theorem. For example:
```lean
import Mathlib.Data.Complex.Trigonometric
example : Continuous (fun x : ℝ => x * Real.sin x) := by fun_prop
```
Fails with the error:
```lean
`fun_prop` was unable to prove `Continuous fun x => x * x.sin`
Issues:
No theorems found for `Real.sin` in order to prove `Continuous fun x => x.sin`
```
This can be easily fixed by importing `Mathlib/Analysis/SpecialFunctions/Trigonometric/Basic.lean`
where the theorem `Real.continuous_sin` is marked with the `fun_prop` attribute.
When the issue is not simply a few missing theorems, you can turn on the option:
```lean
set_option trace.Meta.Tactic.fun_prop true
```
This will display the trace of how `fun_prop` steps through the whole expression.
**Basic setup for a new function property:**
To set up `fun_prop` for a new function property, you have to:
1. Mark the function property with the `fun_prop` attribute when defining it:
```lean
@[fun_prop]
def Continuous (f : X → Y) := ...
```
or later on with:
```lean
attribute [fun_prop] Continuous
```
2. Mark basic lambda calculus theorems. The bare minimum is the identity, constant, and composition
theorems:
```lean
@[fun_prop]
theorem continuous_id : Continuous (fun x => x) := ...
@[fun_prop]
theorem continuous_const (y : Y) : Continuous (fun x => y) := ...
@[fun_prop]
theorem continuous_comp (f : Y → Z) (g : X → Y) (hf : Continuous f) (hg : Continuous g) :
Continuous (fun x => f (g x)) := ...
```
The constant theorem is not absolutely necessary as, for example, `IsLinearMap ℝ (fun x => y)` does
not hold, but we almost certainly want to mark it if it is available.
You should also provide theorems for `Prod.mk`, `Prod.fst`, and `Prod.snd`:
```lean
@[fun_prop]
theorem continuous_fst (f : X → Y × Z) (hf : Continuous f) : Continuous (fun x => (f x).fst) := ...
@[fun_prop]
theorem continuous_snd (f : X → Y × Z) (hf : Continuous f) : Continuous (fun x => (f x).snd) := ...
@[fun_prop]
theorem continuous_prod_mk (f : X → Y) (g : X → Z) (hf : Continuous f) (hg : Continuous g) :
Continuous (fun x => Prod.mk (f x) (g x)) := ...
```
3. Mark function theorems. They can be stated simply as:
```lean
@[fun_prop]
theorem continuous_neg : Continuous (fun x => - x) := ...
@[fun_prop]
theorem continuous_add : Continuous (fun x : X × X => x.1 + x.2) := ...
```
where functions of multiple arguments have to be appropriately uncurried. Alternatively, they can
be stated in compositional form as:
```lean
@[fun_prop]
theorem continuous_neg (f : X → Y) (hf : Continuous f) : Continuous (fun x => - f x) := ...
@[fun_prop]
theorem continuous_add (f g : X → Y) (hf : Continuous f) (hg : Continuous g) :
Continuous (fun x => f x + g x) := ...
```
It is enough to provide function theorems in either form. It is mainly a matter of convenience.
With such a basic setup, you should be able to prove the continuity of basic algebraic expressions.
When marking theorems, it is a good idea to check that a theorem has been registered correctly.
You can do this by turning on the `Meta.Tactic.fun_prop.attr` option. For example:
(note that the notation `f x + g x` is just syntactic sugar for `@HAdd.hAdd X Y Y _ (f x) (g x)`)
```lean
set_option trace.Meta.Tactic.fun_prop.attr true
@[fun_prop]
theorem continuous_add (f g : X → Y) (hf : Continuous f) (hg : Continuous g) :
Continuous (fun x => @HAdd.hAdd X Y Y _ (f x) (g x)) := ...
```
displays:
```lean
[Meta.Tactic.fun_prop.attr] function theorem: continuous_add
function property: Continuous
function name: HAdd.hAdd
main arguments: [4, 5]
applied arguments: 6
form: compositional form
```
This indicates that the theorem `continuous_add` states the continuity of `HAdd.hAdd` in the 4th and
5th arguments and the theorem is in compositional form.
### Advanced
### Type of Theorems
There are four types of theorems that are used a bit differently.
- Lambda Theorems:
These theorems are about basic lambda calculus terms like identity, constant, composition, etc.
They are used when a bigger expression is decomposed into a sequence of function compositions.
They are also used when, for example, we know that a function is continuous in the `x` and `y`
variables, but we want continuity only in `x`.
There are five of them, and they should be formulated in the following way:
- Identity Theorem
```lean
@[fun_prop]
theorem continuous_id : Continuous (fun (x : X) => x) := ..
```
- Constant Theorem
```lean
@[fun_prop]
theorem continuous_const (y : Y) : Continuous (fun (x : X) => y) := ..
```
- Composition Theorem
```lean
@[fun_prop]
theorem continuous_comp (f : Y → Z) (g : X → Y) (hf : Continuous f) (hg : Continuous g) :
Continuous (fun (x : X) => f (g x)) := ..
```
- Apply Theorem
It can be either non-dependent version
```lean
@[fun_prop]
theorem continuous_apply (a : α) : Continuous (fun f : (α → X) => f a) := ..
```
or dependent version
```lean
@[fun_prop]
theorem continuous_apply (a : α) : Continuous (fun f : ((a' : α) → E a') => f a) := ..
```
- Pi Theorem
```lean
@[fun_prop]
theorem continuous_pi (f : X → α → Y) (hf : ∀ a, Continuous (f x a)) :
Continuous (fun x a => f x a) := ..
```
Not all of these theorems have to be provided, but at least the identity and composition
theorems should be.
You should also add theorems for `Prod.mk`, `Prod.fst`, and `Prod.snd`. Technically speaking,
they fall under the *function theorems* category, but without them, `fun_prop` can't function
properly. We are mentioning them as they are used together with *lambda theorems* to break
complicated expressions into a composition of simpler functions.
```lean
@[fun_prop]
theorem continuous_fst (f : X → Y × Z) (hf : Continuous f) :
Continuous (fun x => (f x).fst) := ...
@[fun_prop]
theorem continuous_snd (f : X → Y × Z) (hf : Continuous f) :
Continuous (fun x => (f x).snd) := ...
@[fun_prop]
theorem continuous_prod_mk (f : X → Y) (g : X → Z) (hf : Continuous f) (hg : Continuous g) :
Continuous (fun x => (f x, g x)) := ...
```
- Function Theorems:
When `fun_prop` breaks complicated expression apart using *lambda theorems* it then uses
*function theorems* to prove that each piece is, for example, continuous.
The function theorem for `Neg.neg` and `Continuous` can be stated as:
```lean
@[fun_prop]
theorem continuous_neg : Continuous (fun x => - x) := ...
```
or as:
```lean
@[fun_prop]
theorem continuous_neg (f : X → Y) (hf : Continuous f) : Continuous (fun x => - f x) := ...
```
The first form is called *uncurried form* and the second form is called *compositional form*.
You can provide either form; it is mainly a matter of convenience. You can check if the form of
a theorem has been correctly detected by turning on the option:
```lean
set_option Meta.Tactic.fun_prop.attr true
```
If you really care that the resulting proof term is as short as possible, it is a good idea to
provide both versions.
One exception to this rule is the theorem for `Prod.mk`, which has to be stated in compositional
form. This because this theorem together with *lambda theorems* is used to break expression to
smaller pieces and `fun_prop` assumes it is written in compositional form.
The reason the first form is called *uncurried* is because if we have a function of multiple
arguments, we have to uncurry the function:
```lean
@[fun_prop]
theorem continuous_add : Continuous (fun (x : X × X) => x.1 + x.2) := ...
```
and the *compositional form* of this theorem is:
```lean
@[fun_prop]
theorem continuous_add (f g : X → Y) (hf : Continuous f) (hg : Continuous g) :
Continuous (fun x => f x + g x) := ...
```
When dealing with functions with multiple arguments, you need to state, e.g., continuity only
in the maximal set of arguments. Once we state that addition is jointly continuous in both
arguments, we do not need to add new theorems that addition is also continuous only in the first
or only in the second argument. This is automatically inferred using lambda theorems.
- Morphism Theorems:
The `fun_prop` tactic can also deal with bundled morphisms. For example, we can state that every
continuous linear function is indeed continuous:
```lean
@[fun_prop]
theorem continuous_clm_eval (f : X →L[𝕜] Y) : Continuous 𝕜 (fun x => f x) := ...
```
In this case, the head of the function body `f x` is `DFunLike.coe`. This function is
treated differently and its theorems are tracked separately.
`DFunLike.coe` has two arguments: the morphism `f` and the argument `x`. One difference is that
theorems talking about the argument `f` have to be stated in the compositional form:
```lean
@[fun_prop]
theorem continuous_clm_apply (f : X → Y →L[𝕜] Z) (hf : Continuous f) (y : Y) :
Continuous 𝕜 (fun x => f x y) := ...
```
Note that without notation and coercion, the function looks like
`fun x => DFunLike.coe (f x) y`.
In fact, not only `DFunLike.coe` but any function coercion is treated this way. Such function
coercion has to be registered with `Lean.Meta.registerCoercion` with coercion type `.coeFun`.
Here is an example of custom structure `MyFunLike` that that should be considered as bundled
morphism by `fun_prop`:
```lean
structure MyFunLike (α β : Type) where
toFun : α → β
instance {α β} : CoeFun (MyFunLike α β) (fun _ => α → β) := ⟨MyFunLike.toFun⟩
#eval Lean.Elab.Command.liftTermElabM do
Lean.Meta.registerCoercion ``MyFunLike.toFun
(.some { numArgs := 3, coercee := 2, type := .coeFun })
```
- Transition Theorems:
Transition theorems allow `fun_prop` to infer one function property from another.
For example, a theorem like:
```lean
@[fun_prop]
theorem differentiable_continuous (f : X → Y) (hf : Differentiable 𝕜 f) :
Continuous f := ...
```
There are two features of these theorems: they mix different function properties and the
conclusion is about a free variable `f`.
Transition theorems are the most dangerous theorems as they considerably increase the search
space since they do not simplify the function in question. For this reason, `fun_prop` only
applies transition theorems to functions that can't be written as a non-trivial composition of
two functions (`f = f ∘ id`, `f = id ∘ f` is considered to be a trivial composition).
For this reason, it is recommended to state *function theorems* for every property. For example,
if you have a theorem:
```lean
@[fun_prop]
theorem differentiable_neg : Differentiable ℝ (fun x => -x) := ...
```
you should also state the continuous theorem:
```lean
@[fun_prop]
theorem continuous_neg : Continuous ℝ (fun x => -x) := ...
```
even though `fun_prop` can already prove `continuous_neg` from `differentiable_continuous` and
`differentiable_neg`. Doing this will have a considerable impact on `fun_prop` speed.
By default, `fun_prop` will not apply more then one transitions theorems consecutivelly. For
example, it won't prove `AEMeasurable f` from `Continuous f` by using transition theorems
`Measurable.aemeasurable` and `Continuous.measurable`. You can enable this by running
`fun_prop (maxTransitionDepth :=2)`.
Ideally `fun_prop` theorems should be transitivelly closed i.e. if `Measurable.aemeasurable` and
`Continuous.measurable` are `fun_prop` theorems then `Continuous.aemeasurable` should be too.
Transition theorems do not have to be between two completely different properties. They can be
between the same property differing by a parameter. Consider this example:
```lean
example (f : X → Y) (hf : ContDiff ℝ ∞ f) : ContDiff ℝ 2 (fun x => f x + f x) := by
fun_prop (disch := aesop)
```
which is first reduced to `ContDiff ℝ 2 f` using lambda theorems and then the transition
theorem:
```lean
@[fun_prop]
theorem contdiff_le (f : ContDiff 𝕜 n f) (h : m ≤ n) : ContDiff 𝕜 m f := ...
```
is used together with `aesop` to discharge the `2 ≤ ∞` subgoal.
-/
|
Finite.lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad
-/
import Mathlib.Data.Set.Finite.Lattice
import Mathlib.Order.Filter.Basic
/-!
# Results filters related to finiteness.
-/
open Function Set Order
open scoped symmDiff
universe u v w x y
namespace Filter
variable {α : Type u} {f g : Filter α} {s t : Set α}
@[simp]
theorem biInter_mem {β : Type v} {s : β → Set α} {is : Set β} (hf : is.Finite) :
(⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := by
induction is, hf using Set.Finite.induction_on with
| empty => simp
| insert _ _ hs => simp [hs]
@[simp]
theorem biInter_finset_mem {β : Type v} {s : β → Set α} (is : Finset β) :
(⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f :=
biInter_mem is.finite_toSet
protected alias _root_.Finset.iInter_mem_sets := biInter_finset_mem
@[simp]
theorem sInter_mem {s : Set (Set α)} (hfin : s.Finite) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by
rw [sInter_eq_biInter, biInter_mem hfin]
@[simp]
theorem iInter_mem {β : Sort v} {s : β → Set α} [Finite β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f :=
(sInter_mem (finite_range _)).trans forall_mem_range
end Filter
namespace Filter
variable {α : Type u} {β : Type v} {γ : Type w} {δ : Type*} {ι : Sort x}
section Lattice
variable {f g : Filter α} {s t : Set α}
theorem mem_generate_iff {s : Set <| Set α} {U : Set α} :
U ∈ generate s ↔ ∃ t ⊆ s, Set.Finite t ∧ ⋂₀ t ⊆ U := by
constructor <;> intro h
· induction h with
| @basic V V_in =>
exact ⟨{V}, singleton_subset_iff.2 V_in, finite_singleton _, (sInter_singleton _).subset⟩
| univ => exact ⟨∅, empty_subset _, finite_empty, subset_univ _⟩
| superset _ hVW hV =>
rcases hV with ⟨t, hts, ht, htV⟩
exact ⟨t, hts, ht, htV.trans hVW⟩
| inter _ _ hV hW =>
rcases hV, hW with ⟨⟨t, hts, ht, htV⟩, u, hus, hu, huW⟩
exact
⟨t ∪ u, union_subset hts hus, ht.union hu,
(sInter_union _ _).subset.trans <| inter_subset_inter htV huW⟩
· rcases h with ⟨t, hts, tfin, h⟩
exact mem_of_superset ((sInter_mem tfin).2 fun V hV => GenerateSets.basic <| hts hV) h
theorem mem_iInf_of_iInter {ι} {s : ι → Filter α} {U : Set α} {I : Set ι} (I_fin : I.Finite)
{V : I → Set α} (hV : ∀ (i : I), V i ∈ s i) (hU : ⋂ i, V i ⊆ U) : U ∈ ⨅ i, s i := by
haveI := I_fin.fintype
refine mem_of_superset (iInter_mem.2 fun i => ?_) hU
exact mem_iInf_of_mem (i : ι) (hV _)
theorem mem_iInf {ι} {s : ι → Filter α} {U : Set α} :
(U ∈ ⨅ i, s i) ↔
∃ I : Set ι, I.Finite ∧ ∃ V : I → Set α, (∀ (i : I), V i ∈ s i) ∧ U = ⋂ i, V i := by
constructor
· rw [iInf_eq_generate, mem_generate_iff]
rintro ⟨t, tsub, tfin, tinter⟩
rcases eq_finite_iUnion_of_finite_subset_iUnion tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩
rw [sInter_iUnion] at tinter
set V := fun i => U ∪ ⋂₀ σ i with hV
have V_in : ∀ (i : I), V i ∈ s i := by
rintro i
have : ⋂₀ σ i ∈ s i := by
rw [sInter_mem (σfin _)]
apply σsub
exact mem_of_superset this subset_union_right
refine ⟨I, Ifin, V, V_in, ?_⟩
rwa [hV, ← union_iInter, union_eq_self_of_subset_right]
· rintro ⟨I, Ifin, V, V_in, rfl⟩
exact mem_iInf_of_iInter Ifin V_in Subset.rfl
theorem mem_iInf' {ι} {s : ι → Filter α} {U : Set α} :
(U ∈ ⨅ i, s i) ↔
∃ I : Set ι, I.Finite ∧ ∃ V : ι → Set α, (∀ i, V i ∈ s i) ∧
(∀ i ∉ I, V i = univ) ∧ (U = ⋂ i ∈ I, V i) ∧ U = ⋂ i, V i := by
classical
simp only [mem_iInf, biInter_eq_iInter]
refine ⟨?_, fun ⟨I, If, V, hVs, _, hVU, _⟩ => ⟨I, If, fun i => V i, fun i => hVs i, hVU⟩⟩
rintro ⟨I, If, V, hV, rfl⟩
refine ⟨I, If, fun i => if hi : i ∈ I then V ⟨i, hi⟩ else univ, fun i => ?_, fun i hi => ?_, ?_⟩
· dsimp only
split_ifs
exacts [hV ⟨i,_⟩, univ_mem]
· exact dif_neg hi
· simp only [iInter_dite, biInter_eq_iInter, dif_pos (Subtype.coe_prop _), Subtype.coe_eta,
iInter_univ, inter_univ, true_and]
theorem exists_iInter_of_mem_iInf {ι : Sort*} {α : Type*} {f : ι → Filter α} {s}
(hs : s ∈ ⨅ i, f i) : ∃ t : ι → Set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := by
rw [← iInf_range' (g := (·))] at hs
let ⟨_, _, V, hVs, _, _, hVU'⟩ := mem_iInf'.1 hs
use V ∘ rangeFactorization f, fun i ↦ hVs (rangeFactorization f i)
rw [hVU', ← surjective_onto_range.iInter_comp, comp_def]
theorem mem_iInf_of_finite {ι : Sort*} [Finite ι] {α : Type*} {f : ι → Filter α} (s) :
(s ∈ ⨅ i, f i) ↔ ∃ t : ι → Set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := by
refine ⟨exists_iInter_of_mem_iInf, ?_⟩
rintro ⟨t, ht, rfl⟩
exact iInter_mem.2 fun i => mem_iInf_of_mem i (ht i)
theorem mem_biInf_principal {ι : Type*} {p : ι → Prop} {s : ι → Set α} {t : Set α} :
t ∈ ⨅ (i : ι) (_ : p i), 𝓟 (s i) ↔
∃ I : Set ι, I.Finite ∧ (∀ i ∈ I, p i) ∧ ⋂ i ∈ I, s i ⊆ t := by
constructor
· simp only [mem_iInf (ι := ι), mem_iInf_of_finite, mem_principal]
rintro ⟨I, hIf, V, hV₁, hV₂, rfl⟩
choose! t ht₁ ht₂ using hV₁
refine ⟨I ∩ {i | p i}, hIf.inter_of_left _, fun i ↦ And.right, ?_⟩
simp only [mem_inter_iff, iInter_and, biInter_eq_iInter, ht₂, mem_setOf_eq]
gcongr with i hpi
exact ht₁ i hpi
· rintro ⟨I, hIf, hpI, hst⟩
rw [biInter_eq_iInter] at hst
refine mem_iInf_of_iInter hIf (fun i ↦ ?_) hst
simp [hpI i i.2]
/-! ### Lattice equations -/
theorem _root_.Pairwise.exists_mem_filter_of_disjoint {ι : Type*} [Finite ι] {l : ι → Filter α}
(hd : Pairwise (Disjoint on l)) :
∃ s : ι → Set α, (∀ i, s i ∈ l i) ∧ Pairwise (Disjoint on s) := by
have : Pairwise fun i j => ∃ (s : {s // s ∈ l i}) (t : {t // t ∈ l j}), Disjoint s.1 t.1 := by
simpa only [Pairwise, Function.onFun, Filter.disjoint_iff, exists_prop, Subtype.exists] using hd
choose! s t hst using this
refine ⟨fun i => ⋂ j, @s i j ∩ @t j i, fun i => ?_, fun i j hij => ?_⟩
exacts [iInter_mem.2 fun j => inter_mem (@s i j).2 (@t j i).2,
(hst hij).mono ((iInter_subset _ j).trans inter_subset_left)
((iInter_subset _ i).trans inter_subset_right)]
theorem _root_.Set.PairwiseDisjoint.exists_mem_filter {ι : Type*} {l : ι → Filter α} {t : Set ι}
(hd : t.PairwiseDisjoint l) (ht : t.Finite) :
∃ s : ι → Set α, (∀ i, s i ∈ l i) ∧ t.PairwiseDisjoint s := by
haveI := ht.to_subtype
rcases (hd.subtype _ _).exists_mem_filter_of_disjoint with ⟨s, hsl, hsd⟩
lift s to (i : t) → {s // s ∈ l i} using hsl
rcases @Subtype.exists_pi_extension ι (fun i => { s // s ∈ l i }) _ _ s with ⟨s, rfl⟩
exact ⟨fun i => s i, fun i => (s i).2, hsd.set_of_subtype _ _⟩
theorem iInf_sets_eq_finite {ι : Type*} (f : ι → Filter α) :
(⨅ i, f i).sets = ⋃ t : Finset ι, (⨅ i ∈ t, f i).sets := by
rw [iInf_eq_iInf_finset, iInf_sets_eq]
exact directed_of_isDirected_le fun _ _ => biInf_mono
theorem iInf_sets_eq_finite' (f : ι → Filter α) :
(⨅ i, f i).sets = ⋃ t : Finset (PLift ι), (⨅ i ∈ t, f (PLift.down i)).sets := by
rw [← iInf_sets_eq_finite, ← Equiv.plift.surjective.iInf_comp, Equiv.plift_apply]
theorem mem_iInf_finite {ι : Type*} {f : ι → Filter α} (s) :
s ∈ iInf f ↔ ∃ t : Finset ι, s ∈ ⨅ i ∈ t, f i :=
(Set.ext_iff.1 (iInf_sets_eq_finite f) s).trans mem_iUnion
theorem mem_iInf_finite' {f : ι → Filter α} (s) :
s ∈ iInf f ↔ ∃ t : Finset (PLift ι), s ∈ ⨅ i ∈ t, f (PLift.down i) :=
(Set.ext_iff.1 (iInf_sets_eq_finite' f) s).trans mem_iUnion
/-- The dual version does not hold! `Filter α` is not a `CompleteDistribLattice`. -/
-- See note [reducible non-instances]
abbrev coframeMinimalAxioms : Coframe.MinimalAxioms (Filter α) :=
{ Filter.instCompleteLatticeFilter with
iInf_sup_le_sup_sInf := fun f s t ⟨h₁, h₂⟩ => by
classical
rw [iInf_subtype']
rw [sInf_eq_iInf', ← Filter.mem_sets, iInf_sets_eq_finite, mem_iUnion] at h₂
obtain ⟨u, hu⟩ := h₂
rw [← Finset.inf_eq_iInf] at hu
suffices ⨅ i : s, f ⊔ ↑i ≤ f ⊔ u.inf fun i => ↑i from this ⟨h₁, hu⟩
refine Finset.induction_on u (le_sup_of_le_right le_top) ?_
rintro ⟨i⟩ u _ ih
rw [Finset.inf_insert, sup_inf_left]
exact le_inf (iInf_le _ _) ih }
instance instCoframe : Coframe (Filter α) := .ofMinimalAxioms coframeMinimalAxioms
theorem mem_iInf_finset {s : Finset α} {f : α → Filter β} {t : Set β} :
(t ∈ ⨅ a ∈ s, f a) ↔ ∃ p : α → Set β, (∀ a ∈ s, p a ∈ f a) ∧ t = ⋂ a ∈ s, p a := by
classical
simp only [← Finset.set_biInter_coe, biInter_eq_iInter, iInf_subtype']
refine ⟨fun h => ?_, ?_⟩
· rcases (mem_iInf_of_finite _).1 h with ⟨p, hp, rfl⟩
refine ⟨fun a => if h : a ∈ s then p ⟨a, h⟩ else univ,
fun a ha => by simpa [ha] using hp ⟨a, ha⟩, ?_⟩
refine iInter_congr_of_surjective id surjective_id ?_
rintro ⟨a, ha⟩
simp [ha]
· rintro ⟨p, hpf, rfl⟩
exact iInter_mem.2 fun a => mem_iInf_of_mem a (hpf a a.2)
@[elab_as_elim]
theorem iInf_sets_induct {f : ι → Filter α} {s : Set α} (hs : s ∈ iInf f) {p : Set α → Prop}
(uni : p univ) (ins : ∀ {i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) : p s := by
classical
rw [mem_iInf_finite'] at hs
simp only [← Finset.inf_eq_iInf] at hs
rcases hs with ⟨is, his⟩
induction is using Finset.induction_on generalizing s with
| empty => rwa [mem_top.1 his]
| insert _ _ _ ih =>
rw [Finset.inf_insert, mem_inf_iff] at his
rcases his with ⟨s₁, hs₁, s₂, hs₂, rfl⟩
exact ins hs₁ (ih hs₂)
/-! #### `principal` equations -/
@[simp]
theorem iInf_principal_finset {ι : Type w} (s : Finset ι) (f : ι → Set α) :
⨅ i ∈ s, 𝓟 (f i) = 𝓟 (⋂ i ∈ s, f i) := by
classical
induction s using Finset.induction_on with
| empty => simp
| insert i s _ hs => rw [Finset.iInf_insert, Finset.set_biInter_insert, hs, inf_principal]
theorem iInf_principal {ι : Sort w} [Finite ι] (f : ι → Set α) : ⨅ i, 𝓟 (f i) = 𝓟 (⋂ i, f i) := by
cases nonempty_fintype (PLift ι)
rw [← iInf_plift_down, ← iInter_plift_down]
simpa using iInf_principal_finset Finset.univ (f <| PLift.down ·)
/-- A special case of `iInf_principal` that is safe to mark `simp`. -/
@[simp]
theorem iInf_principal' {ι : Type w} [Finite ι] (f : ι → Set α) : ⨅ i, 𝓟 (f i) = 𝓟 (⋂ i, f i) :=
iInf_principal _
theorem iInf_principal_finite {ι : Type w} {s : Set ι} (hs : s.Finite) (f : ι → Set α) :
⨅ i ∈ s, 𝓟 (f i) = 𝓟 (⋂ i ∈ s, f i) := by
lift s to Finset ι using hs
exact mod_cast iInf_principal_finset s f
end Lattice
/-! ### Eventually -/
@[simp]
theorem eventually_all {ι : Sort*} [Finite ι] {l} {p : ι → α → Prop} :
(∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by
simpa only [Filter.Eventually, setOf_forall] using iInter_mem
@[simp]
theorem eventually_all_finite {ι} {I : Set ι} (hI : I.Finite) {l} {p : ι → α → Prop} :
(∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := by
simpa only [Filter.Eventually, setOf_forall] using biInter_mem hI
alias _root_.Set.Finite.eventually_all := eventually_all_finite
-- attribute [protected] Set.Finite.eventually_all
@[simp] theorem eventually_all_finset {ι} (I : Finset ι) {l} {p : ι → α → Prop} :
(∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x :=
I.finite_toSet.eventually_all
alias _root_.Finset.eventually_all := eventually_all_finset
-- attribute [protected] Finset.eventually_all
/-!
### Relation “eventually equal”
-/
section EventuallyEq
variable {l : Filter α} {f g : α → β}
variable {l : Filter α}
protected lemma EventuallyLE.iUnion [Finite ι] {s t : ι → Set α}
(h : ∀ i, s i ≤ᶠ[l] t i) : (⋃ i, s i) ≤ᶠ[l] ⋃ i, t i :=
(eventually_all.2 h).mono fun _x hx hx' ↦
let ⟨i, hi⟩ := mem_iUnion.1 hx'; mem_iUnion.2 ⟨i, hx i hi⟩
protected lemma EventuallyEq.iUnion [Finite ι] {s t : ι → Set α}
(h : ∀ i, s i =ᶠ[l] t i) : (⋃ i, s i) =ᶠ[l] ⋃ i, t i :=
(EventuallyLE.iUnion fun i ↦ (h i).le).antisymm <| .iUnion fun i ↦ (h i).symm.le
protected lemma EventuallyLE.iInter [Finite ι] {s t : ι → Set α}
(h : ∀ i, s i ≤ᶠ[l] t i) : (⋂ i, s i) ≤ᶠ[l] ⋂ i, t i :=
(eventually_all.2 h).mono fun _x hx hx' ↦ mem_iInter.2 fun i ↦ hx i (mem_iInter.1 hx' i)
protected lemma EventuallyEq.iInter [Finite ι] {s t : ι → Set α}
(h : ∀ i, s i =ᶠ[l] t i) : (⋂ i, s i) =ᶠ[l] ⋂ i, t i :=
(EventuallyLE.iInter fun i ↦ (h i).le).antisymm <| .iInter fun i ↦ (h i).symm.le
lemma _root_.Set.Finite.eventuallyLE_iUnion {ι : Type*} {s : Set ι} (hs : s.Finite)
{f g : ι → Set α} (hle : ∀ i ∈ s, f i ≤ᶠ[l] g i) : (⋃ i ∈ s, f i) ≤ᶠ[l] (⋃ i ∈ s, g i) := by
have := hs.to_subtype
rw [biUnion_eq_iUnion, biUnion_eq_iUnion]
exact .iUnion fun i ↦ hle i.1 i.2
alias EventuallyLE.biUnion := Set.Finite.eventuallyLE_iUnion
lemma _root_.Set.Finite.eventuallyEq_iUnion {ι : Type*} {s : Set ι} (hs : s.Finite)
{f g : ι → Set α} (heq : ∀ i ∈ s, f i =ᶠ[l] g i) : (⋃ i ∈ s, f i) =ᶠ[l] (⋃ i ∈ s, g i) :=
(EventuallyLE.biUnion hs fun i hi ↦ (heq i hi).le).antisymm <|
.biUnion hs fun i hi ↦ (heq i hi).symm.le
alias EventuallyEq.biUnion := Set.Finite.eventuallyEq_iUnion
lemma _root_.Set.Finite.eventuallyLE_iInter {ι : Type*} {s : Set ι} (hs : s.Finite)
{f g : ι → Set α} (hle : ∀ i ∈ s, f i ≤ᶠ[l] g i) : (⋂ i ∈ s, f i) ≤ᶠ[l] (⋂ i ∈ s, g i) := by
have := hs.to_subtype
rw [biInter_eq_iInter, biInter_eq_iInter]
exact .iInter fun i ↦ hle i.1 i.2
alias EventuallyLE.biInter := Set.Finite.eventuallyLE_iInter
lemma _root_.Set.Finite.eventuallyEq_iInter {ι : Type*} {s : Set ι} (hs : s.Finite)
{f g : ι → Set α} (heq : ∀ i ∈ s, f i =ᶠ[l] g i) : (⋂ i ∈ s, f i) =ᶠ[l] (⋂ i ∈ s, g i) :=
(EventuallyLE.biInter hs fun i hi ↦ (heq i hi).le).antisymm <|
.biInter hs fun i hi ↦ (heq i hi).symm.le
alias EventuallyEq.biInter := Set.Finite.eventuallyEq_iInter
lemma _root_.Finset.eventuallyLE_iUnion {ι : Type*} (s : Finset ι) {f g : ι → Set α}
(hle : ∀ i ∈ s, f i ≤ᶠ[l] g i) : (⋃ i ∈ s, f i) ≤ᶠ[l] (⋃ i ∈ s, g i) :=
.biUnion s.finite_toSet hle
lemma _root_.Finset.eventuallyEq_iUnion {ι : Type*} (s : Finset ι) {f g : ι → Set α}
(heq : ∀ i ∈ s, f i =ᶠ[l] g i) : (⋃ i ∈ s, f i) =ᶠ[l] (⋃ i ∈ s, g i) :=
.biUnion s.finite_toSet heq
lemma _root_.Finset.eventuallyLE_iInter {ι : Type*} (s : Finset ι) {f g : ι → Set α}
(hle : ∀ i ∈ s, f i ≤ᶠ[l] g i) : (⋂ i ∈ s, f i) ≤ᶠ[l] (⋂ i ∈ s, g i) :=
.biInter s.finite_toSet hle
lemma _root_.Finset.eventuallyEq_iInter {ι : Type*} (s : Finset ι) {f g : ι → Set α}
(heq : ∀ i ∈ s, f i =ᶠ[l] g i) : (⋂ i ∈ s, f i) =ᶠ[l] (⋂ i ∈ s, g i) :=
.biInter s.finite_toSet heq
end EventuallyEq
end Filter
open Filter
|
ValExtension.lean
|
/-
Copyright (c) 2024 Jiedong Jiang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jiedong Jiang, Bichang Lei
-/
import Mathlib.RingTheory.Valuation.Extension
deprecated_module (since := "2025-05-06")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.