filename
stringlengths
5
42
content
stringlengths
15
319k
Defs.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Algebra.Module.Equiv.Defs import Mathlib.Algebra.Module.Pi import Mathlib.Data.Finsupp.SMul /-! # Properties of the module `α →₀ M` Given an `R`-module `M`, the `R`-module structure on `α →₀ M` is defined in `Data.Finsupp.Basic`. In this file we define `LinearMap` versions of various maps: * `Finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `Finsupp.single a` as a linear map; * `Finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `fun f ↦ f a` as a linear map; * `Finsupp.lsubtypeDomain (s : Set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a linear map; * `Finsupp.restrictDom`: `Finsupp.filter` as a linear map to `Finsupp.supported s`; * `Finsupp.lmapDomain`: a linear map version of `Finsupp.mapDomain`; ## Tags function with finite support, module, linear algebra -/ assert_not_exists Submodule noncomputable section open Set LinearMap namespace Finsupp variable {α : Type*} {M : Type*} {N : Type*} {P : Type*} {R R₂ R₃ : Type*} {S : Type*} variable [Semiring R] [Semiring R₂] [Semiring R₃] [Semiring S] variable [AddCommMonoid M] [Module R M] variable [AddCommMonoid N] [Module R₂ N] variable [AddCommMonoid P] [Module R₃ P] variable {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} variable {σ₂₃ : R₂ →+* R₃} {σ₃₂ : R₃ →+* R₂} variable {σ₁₃ : R →+* R₃} {σ₃₁ : R₃ →+* R} variable [RingHomCompTriple σ₁₂ σ₂₃ σ₁₃] [RingHomCompTriple σ₃₂ σ₂₁ σ₃₁] section LinearEquivFunOnFinite variable (R : Type*) {S : Type*} (M : Type*) (α : Type*) variable [Finite α] [AddCommMonoid M] [Semiring R] [Module R M] /-- Given `Finite α`, `linearEquivFunOnFinite R` is the natural `R`-linear equivalence between `α →₀ β` and `α → β`. -/ @[simps apply] noncomputable def linearEquivFunOnFinite : (α →₀ M) ≃ₗ[R] α → M := { equivFunOnFinite with toFun := (⇑) map_add' := fun _ _ => rfl map_smul' := fun _ _ => rfl } @[simp] theorem linearEquivFunOnFinite_single [DecidableEq α] (x : α) (m : M) : (linearEquivFunOnFinite R M α) (single x m) = Pi.single x m := equivFunOnFinite_single x m @[simp] theorem linearEquivFunOnFinite_symm_single [DecidableEq α] (x : α) (m : M) : (linearEquivFunOnFinite R M α).symm (Pi.single x m) = single x m := equivFunOnFinite_symm_single x m @[simp] theorem linearEquivFunOnFinite_symm_coe (f : α →₀ M) : (linearEquivFunOnFinite R M α).symm f = f := (linearEquivFunOnFinite R M α).symm_apply_apply f end LinearEquivFunOnFinite /-- Interpret `Finsupp.single a` as a linear map. -/ def lsingle (a : α) : M →ₗ[R] α →₀ M := { Finsupp.singleAddHom a with map_smul' := fun _ _ => (smul_single _ _ _).symm } /-- Two `R`-linear maps from `Finsupp X M` which agree on each `single x y` agree everywhere. -/ theorem lhom_ext ⦃φ ψ : (α →₀ M) →ₛₗ[σ₁₂] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) : φ = ψ := LinearMap.toAddMonoidHom_injective <| addHom_ext h /-- Two `R`-linear maps from `Finsupp X M` which agree on each `single x y` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ -- Porting note: The priority should be higher than `LinearMap.ext`. @[ext high] theorem lhom_ext' ⦃φ ψ : (α →₀ M) →ₛₗ[σ₁₂] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) : φ = ψ := lhom_ext fun a => LinearMap.congr_fun (h a) /-- Interpret `fun f : α →₀ M ↦ f a` as a linear map. -/ def lapply (a : α) : (α →₀ M) →ₗ[R] M := { Finsupp.applyAddHom a with map_smul' := fun _ _ => rfl } instance [Nonempty α] [FaithfulSMul R M] : FaithfulSMul R (α →₀ M) := .of_injective (Finsupp.lsingle <| Classical.arbitrary _) (Finsupp.single_injective _) section LSubtypeDomain variable (s : Set α) /-- Interpret `Finsupp.subtypeDomain s` as a linear map. -/ def lsubtypeDomain : (α →₀ M) →ₗ[R] s →₀ M where toFun := subtypeDomain fun x => x ∈ s map_add' _ _ := subtypeDomain_add map_smul' _ _ := ext fun _ => rfl theorem lsubtypeDomain_apply (f : α →₀ M) : (lsubtypeDomain s : (α →₀ M) →ₗ[R] s →₀ M) f = subtypeDomain (fun x => x ∈ s) f := rfl end LSubtypeDomain @[simp] theorem lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] α →₀ M) b = single a b := rfl @[simp] theorem lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] theorem lapply_comp_lsingle_same (a : α) : lapply a ∘ₗ lsingle a = (.id : M →ₗ[R] M) := by ext; simp @[simp] theorem lapply_comp_lsingle_of_ne (a a' : α) (h : a ≠ a') : lapply a ∘ₗ lsingle a' = (0 : M →ₗ[R] M) := by ext; simp [h.symm] section LMapDomain variable {α' : Type*} {α'' : Type*} (M R) /-- Interpret `Finsupp.mapDomain` as a linear map. -/ def lmapDomain (f : α → α') : (α →₀ M) →ₗ[R] α' →₀ M where toFun := mapDomain f map_add' _ _ := mapDomain_add map_smul' := mapDomain_smul @[simp] theorem lmapDomain_apply (f : α → α') (l : α →₀ M) : (lmapDomain M R f : (α →₀ M) →ₗ[R] α' →₀ M) l = mapDomain f l := rfl @[simp] theorem lmapDomain_id : (lmapDomain M R _root_.id : (α →₀ M) →ₗ[R] α →₀ M) = LinearMap.id := LinearMap.ext fun _ => mapDomain_id theorem lmapDomain_comp (f : α → α') (g : α' → α'') : lmapDomain M R (g ∘ f) = (lmapDomain M R g).comp (lmapDomain M R f) := LinearMap.ext fun _ => mapDomain_comp /-- `Finsupp.mapDomain` as a `LinearEquiv`. -/ def mapDomain.linearEquiv (f : α ≃ α') : (α →₀ M) ≃ₗ[R] (α' →₀ M) where __ := lmapDomain M R f.toFun invFun := mapDomain f.symm left_inv _ := by simp [← mapDomain_comp] right_inv _ := by simp [← mapDomain_comp] @[simp] theorem mapDomain.coe_linearEquiv (f : α ≃ α') : ⇑(linearEquiv M R f) = mapDomain f := rfl @[simp] theorem mapDomain.toLinearMap_linearEquiv (f : α ≃ α') : (linearEquiv M R f : _ →ₗ[R] _) = lmapDomain M R f := rfl @[simp] theorem mapDomain.linearEquiv_symm (f : α ≃ α') : (linearEquiv M R f).symm = linearEquiv M R f.symm := rfl end LMapDomain section LComapDomain variable {β : Type*} /-- Given `f : α → β` and a proof `hf` that `f` is injective, `lcomapDomain f hf` is the linear map sending `l : β →₀ M` to the finitely supported function from `α` to `M` given by composing `l` with `f`. This is the linear version of `Finsupp.comapDomain`. -/ @[simps] def lcomapDomain (f : α → β) (hf : Function.Injective f) : (β →₀ M) →ₗ[R] α →₀ M where toFun l := Finsupp.comapDomain f l hf.injOn map_add' x y := by ext; simp map_smul' c x := by ext; simp theorem leftInverse_lcomapDomain_mapDomain (f : α → β) (hf : Function.Injective f) : Function.LeftInverse (lcomapDomain (R := R) (M := M) f hf) (mapDomain f) := comapDomain_mapDomain f hf end LComapDomain /-- `Finsupp.mapRange` as a `LinearMap`. -/ @[simps apply] def mapRange.linearMap (f : M →ₛₗ[σ₁₂] N) : (α →₀ M) →ₛₗ[σ₁₂] α →₀ N := { mapRange.addMonoidHom f.toAddMonoidHom with toFun := (mapRange f f.map_zero : (α →₀ M) → α →₀ N) map_smul' := fun c v => mapRange_smul' c (σ₁₂ c) v (f.map_smulₛₗ c) } @[simp] theorem mapRange.linearMap_id : mapRange.linearMap LinearMap.id = (LinearMap.id : (α →₀ M) →ₗ[R] _) := LinearMap.ext mapRange_id theorem mapRange.linearMap_comp (f : N →ₛₗ[σ₂₃] P) (f₂ : M →ₛₗ[σ₁₂] N) : (mapRange.linearMap (f.comp f₂) : (α →₀ _) →ₛₗ[σ₁₃] _) = (mapRange.linearMap f).comp (mapRange.linearMap f₂) := LinearMap.ext <| mapRange_comp f f.map_zero f₂ f₂.map_zero (comp f f₂).map_zero @[simp] theorem mapRange.linearMap_toAddMonoidHom (f : M →ₛₗ[σ₁₂] N) : (mapRange.linearMap f).toAddMonoidHom = (mapRange.addMonoidHom f.toAddMonoidHom : (α →₀ M) →+ _) := AddMonoidHom.ext fun _ => rfl section Equiv variable [RingHomInvPair σ₁₂ σ₂₁] [RingHomInvPair σ₂₁ σ₁₂] variable [RingHomInvPair σ₂₃ σ₃₂] [RingHomInvPair σ₃₂ σ₂₃] variable [RingHomInvPair σ₁₃ σ₃₁] [RingHomInvPair σ₃₁ σ₁₃] /-- `Finsupp.mapRange` as a `LinearEquiv`. -/ @[simps apply] def mapRange.linearEquiv (e : M ≃ₛₗ[σ₁₂] N) : (α →₀ M) ≃ₛₗ[σ₁₂] α →₀ N := { mapRange.linearMap e.toLinearMap, mapRange.addEquiv e.toAddEquiv with toFun := mapRange e e.map_zero invFun := mapRange e.symm e.symm.map_zero } @[simp] theorem mapRange.linearEquiv_refl : mapRange.linearEquiv (LinearEquiv.refl R M) = LinearEquiv.refl R (α →₀ M) := LinearEquiv.ext mapRange_id theorem mapRange.linearEquiv_trans (f : M ≃ₛₗ[σ₁₂] N) (f₂ : N ≃ₛₗ[σ₂₃] P) : (mapRange.linearEquiv (f.trans f₂) : (α →₀ _) ≃ₛₗ[σ₁₃] _) = (mapRange.linearEquiv f).trans (mapRange.linearEquiv f₂) := LinearEquiv.ext <| mapRange_comp f₂ f₂.map_zero f f.map_zero (f.trans f₂).map_zero @[simp] theorem mapRange.linearEquiv_symm (f : M ≃ₛₗ[σ₁₂] N) : ((mapRange.linearEquiv f).symm : (α →₀ _) ≃ₛₗ[σ₂₁] _) = mapRange.linearEquiv f.symm := LinearEquiv.ext fun _x => rfl -- Porting note: This priority should be higher than `LinearEquiv.coe_toAddEquiv`. @[simp 1500] theorem mapRange.linearEquiv_toAddEquiv (f : M ≃ₛₗ[σ₁₂] N) : (mapRange.linearEquiv f).toAddEquiv = (mapRange.addEquiv f.toAddEquiv : (α →₀ M) ≃+ _) := AddEquiv.ext fun _ => rfl @[simp] theorem mapRange.linearEquiv_toLinearMap (f : M ≃ₛₗ[σ₁₂] N) : (mapRange.linearEquiv f).toLinearMap = (mapRange.linearMap f.toLinearMap : (α →₀ M) →ₛₗ[σ₁₂] _) := LinearMap.ext fun _ => rfl end Equiv section Prod variable {α β R M : Type*} [DecidableEq α] [Semiring R] [AddCommMonoid M] [Module R M] variable (R) in /-- The linear equivalence between `α × β →₀ M` and `α →₀ β →₀ M`. This is the `LinearEquiv` version of `Finsupp.finsuppProdEquiv`. -/ @[simps +simpRhs] noncomputable def finsuppProdLEquiv : (α × β →₀ M) ≃ₗ[R] α →₀ β →₀ M := { finsuppProdEquiv with map_add' f g := by ext; simp map_smul' c f := by ext; simp } theorem finsuppProdLEquiv_symm_apply_apply (f : α →₀ β →₀ M) (xy) : (finsuppProdLEquiv R).symm f xy = f xy.1 xy.2 := rfl end Prod end Finsupp variable {R : Type*} {M : Type*} {N : Type*} variable [Semiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] open Finsupp section variable (R) /-- If `Subsingleton R`, then `M ≃ₗ[R] ι →₀ R` for any type `ι`. -/ @[simps] def Module.subsingletonEquiv (R M ι : Type*) [Semiring R] [Subsingleton R] [AddCommMonoid M] [Module R M] : M ≃ₗ[R] ι →₀ R where toFun _ := 0 invFun _ := 0 left_inv m := have := Module.subsingleton R M Subsingleton.elim _ _ right_inv f := by simp only [eq_iff_true_of_subsingleton] map_add' _ _ := (add_zero 0).symm map_smul' r _ := (smul_zero r).symm end
LeftHomology.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.ShortComplex.Basic import Mathlib.CategoryTheory.Limits.Shapes.Kernels /-! # Left Homology of short complexes Given a short complex `S : ShortComplex C`, which consists of two composable maps `f : X₁ ⟶ X₂` and `g : X₂ ⟶ X₃` such that `f ≫ g = 0`, we shall define here the "left homology" `S.leftHomology` of `S`. For this, we introduce the notion of "left homology data". Such an `h : S.LeftHomologyData` consists of the data of morphisms `i : K ⟶ X₂` and `π : K ⟶ H` such that `i` identifies `K` with the kernel of `g : X₂ ⟶ X₃`, and that `π` identifies `H` with the cokernel of the induced map `f' : X₁ ⟶ K`. When such a `S.LeftHomologyData` exists, we shall say that `[S.HasLeftHomology]` and we define `S.leftHomology` to be the `H` field of a chosen left homology data. Similarly, we define `S.cycles` to be the `K` field. The dual notion is defined in `RightHomologyData.lean`. In `Homology.lean`, when `S` has two compatible left and right homology data (i.e. they give the same `H` up to a canonical isomorphism), we shall define `[S.HasHomology]` and `S.homology`. -/ namespace CategoryTheory open Category Limits namespace ShortComplex variable {C : Type*} [Category C] [HasZeroMorphisms C] (S : ShortComplex C) {S₁ S₂ S₃ : ShortComplex C} /-- A left homology data for a short complex `S` consists of morphisms `i : K ⟶ S.X₂` and `π : K ⟶ H` such that `i` identifies `K` to the kernel of `g : S.X₂ ⟶ S.X₃`, and that `π` identifies `H` to the cokernel of the induced map `f' : S.X₁ ⟶ K` -/ structure LeftHomologyData where /-- a choice of kernel of `S.g : S.X₂ ⟶ S.X₃` -/ K : C /-- a choice of cokernel of the induced morphism `S.f' : S.X₁ ⟶ K` -/ H : C /-- the inclusion of cycles in `S.X₂` -/ i : K ⟶ S.X₂ /-- the projection from cycles to the (left) homology -/ π : K ⟶ H /-- the kernel condition for `i` -/ wi : i ≫ S.g = 0 /-- `i : K ⟶ S.X₂` is a kernel of `g : S.X₂ ⟶ S.X₃` -/ hi : IsLimit (KernelFork.ofι i wi) /-- the cokernel condition for `π` -/ wπ : hi.lift (KernelFork.ofι _ S.zero) ≫ π = 0 /-- `π : K ⟶ H` is a cokernel of the induced morphism `S.f' : S.X₁ ⟶ K` -/ hπ : IsColimit (CokernelCofork.ofπ π wπ) initialize_simps_projections LeftHomologyData (-hi, -hπ) namespace LeftHomologyData /-- The chosen kernels and cokernels of the limits API give a `LeftHomologyData` -/ @[simps] noncomputable def ofHasKernelOfHasCokernel [HasKernel S.g] [HasCokernel (kernel.lift S.g S.f S.zero)] : S.LeftHomologyData where K := kernel S.g H := cokernel (kernel.lift S.g S.f S.zero) i := kernel.ι _ π := cokernel.π _ wi := kernel.condition _ hi := kernelIsKernel _ wπ := cokernel.condition _ hπ := cokernelIsCokernel _ attribute [reassoc (attr := simp)] wi wπ variable {S} variable (h : S.LeftHomologyData) {A : C} instance : Mono h.i := ⟨fun _ _ => Fork.IsLimit.hom_ext h.hi⟩ instance : Epi h.π := ⟨fun _ _ => Cofork.IsColimit.hom_ext h.hπ⟩ /-- Any morphism `k : A ⟶ S.X₂` that is a cycle (i.e. `k ≫ S.g = 0`) lifts to a morphism `A ⟶ K` -/ def liftK (k : A ⟶ S.X₂) (hk : k ≫ S.g = 0) : A ⟶ h.K := h.hi.lift (KernelFork.ofι k hk) @[reassoc (attr := simp)] lemma liftK_i (k : A ⟶ S.X₂) (hk : k ≫ S.g = 0) : h.liftK k hk ≫ h.i = k := h.hi.fac _ WalkingParallelPair.zero /-- The (left) homology class `A ⟶ H` attached to a cycle `k : A ⟶ S.X₂` -/ @[simp] def liftH (k : A ⟶ S.X₂) (hk : k ≫ S.g = 0) : A ⟶ h.H := h.liftK k hk ≫ h.π /-- Given `h : LeftHomologyData S`, this is morphism `S.X₁ ⟶ h.K` induced by `S.f : S.X₁ ⟶ S.X₂` and the fact that `h.K` is a kernel of `S.g : S.X₂ ⟶ S.X₃`. -/ def f' : S.X₁ ⟶ h.K := h.liftK S.f S.zero @[reassoc (attr := simp)] lemma f'_i : h.f' ≫ h.i = S.f := liftK_i _ _ _ @[reassoc (attr := simp)] lemma f'_π : h.f' ≫ h.π = 0 := h.wπ @[reassoc] lemma liftK_π_eq_zero_of_boundary (k : A ⟶ S.X₂) (x : A ⟶ S.X₁) (hx : k = x ≫ S.f) : h.liftK k (by rw [hx, assoc, S.zero, comp_zero]) ≫ h.π = 0 := by rw [show 0 = (x ≫ h.f') ≫ h.π by simp] congr 1 simp only [← cancel_mono h.i, hx, liftK_i, assoc, f'_i] /-- For `h : S.LeftHomologyData`, this is a restatement of `h.hπ`, saying that `π : h.K ⟶ h.H` is a cokernel of `h.f' : S.X₁ ⟶ h.K`. -/ def hπ' : IsColimit (CokernelCofork.ofπ h.π h.f'_π) := h.hπ /-- The morphism `H ⟶ A` induced by a morphism `k : K ⟶ A` such that `f' ≫ k = 0` -/ def descH (k : h.K ⟶ A) (hk : h.f' ≫ k = 0) : h.H ⟶ A := h.hπ.desc (CokernelCofork.ofπ k hk) @[reassoc (attr := simp)] lemma π_descH (k : h.K ⟶ A) (hk : h.f' ≫ k = 0) : h.π ≫ h.descH k hk = k := h.hπ.fac (CokernelCofork.ofπ k hk) WalkingParallelPair.one lemma isIso_i (hg : S.g = 0) : IsIso h.i := ⟨h.liftK (𝟙 S.X₂) (by rw [hg, id_comp]), by simp only [← cancel_mono h.i, id_comp, assoc, liftK_i, comp_id], liftK_i _ _ _⟩ lemma isIso_π (hf : S.f = 0) : IsIso h.π := by have ⟨φ, hφ⟩ := CokernelCofork.IsColimit.desc' h.hπ' (𝟙 _) (by rw [← cancel_mono h.i, comp_id, f'_i, zero_comp, hf]) dsimp at hφ exact ⟨φ, hφ, by rw [← cancel_epi h.π, reassoc_of% hφ, comp_id]⟩ variable (S) /-- When the second map `S.g` is zero, this is the left homology data on `S` given by any colimit cokernel cofork of `S.f` -/ @[simps] def ofIsColimitCokernelCofork (hg : S.g = 0) (c : CokernelCofork S.f) (hc : IsColimit c) : S.LeftHomologyData where K := S.X₂ H := c.pt i := 𝟙 _ π := c.π wi := by rw [id_comp, hg] hi := KernelFork.IsLimit.ofId _ hg wπ := CokernelCofork.condition _ hπ := IsColimit.ofIsoColimit hc (Cofork.ext (Iso.refl _)) @[simp] lemma ofIsColimitCokernelCofork_f' (hg : S.g = 0) (c : CokernelCofork S.f) (hc : IsColimit c) : (ofIsColimitCokernelCofork S hg c hc).f' = S.f := by rw [← cancel_mono (ofIsColimitCokernelCofork S hg c hc).i, f'_i, ofIsColimitCokernelCofork_i] dsimp rw [comp_id] /-- When the second map `S.g` is zero, this is the left homology data on `S` given by the chosen `cokernel S.f` -/ @[simps!] noncomputable def ofHasCokernel [HasCokernel S.f] (hg : S.g = 0) : S.LeftHomologyData := ofIsColimitCokernelCofork S hg _ (cokernelIsCokernel _) /-- When the first map `S.f` is zero, this is the left homology data on `S` given by any limit kernel fork of `S.g` -/ @[simps] def ofIsLimitKernelFork (hf : S.f = 0) (c : KernelFork S.g) (hc : IsLimit c) : S.LeftHomologyData where K := c.pt H := c.pt i := c.ι π := 𝟙 _ wi := KernelFork.condition _ hi := IsLimit.ofIsoLimit hc (Fork.ext (Iso.refl _)) wπ := Fork.IsLimit.hom_ext hc (by dsimp simp only [comp_id, zero_comp, Fork.IsLimit.lift_ι, Fork.ι_ofι, hf]) hπ := CokernelCofork.IsColimit.ofId _ (Fork.IsLimit.hom_ext hc (by dsimp simp only [comp_id, zero_comp, Fork.IsLimit.lift_ι, Fork.ι_ofι, hf])) @[simp] lemma ofIsLimitKernelFork_f' (hf : S.f = 0) (c : KernelFork S.g) (hc : IsLimit c) : (ofIsLimitKernelFork S hf c hc).f' = 0 := by rw [← cancel_mono (ofIsLimitKernelFork S hf c hc).i, f'_i, hf, zero_comp] /-- When the first map `S.f` is zero, this is the left homology data on `S` given by the chosen `kernel S.g` -/ @[simp] noncomputable def ofHasKernel [HasKernel S.g] (hf : S.f = 0) : S.LeftHomologyData := ofIsLimitKernelFork S hf _ (kernelIsKernel _) /-- When both `S.f` and `S.g` are zero, the middle object `S.X₂` gives a left homology data on S -/ @[simps] def ofZeros (hf : S.f = 0) (hg : S.g = 0) : S.LeftHomologyData where K := S.X₂ H := S.X₂ i := 𝟙 _ π := 𝟙 _ wi := by rw [id_comp, hg] hi := KernelFork.IsLimit.ofId _ hg wπ := by change S.f ≫ 𝟙 _ = 0 simp only [hf, zero_comp] hπ := CokernelCofork.IsColimit.ofId _ hf @[simp] lemma ofZeros_f' (hf : S.f = 0) (hg : S.g = 0) : (ofZeros S hf hg).f' = 0 := by rw [← cancel_mono ((ofZeros S hf hg).i), zero_comp, f'_i, hf] variable {S} in /-- Given a left homology data `h` of a short complex `S`, we can construct another left homology data by choosing another kernel and cokernel that are isomorphic to the ones in `h`. -/ @[simps] def copy {K' H' : C} (eK : K' ≅ h.K) (eH : H' ≅ h.H) : S.LeftHomologyData where K := K' H := H' i := eK.hom ≫ h.i π := eK.hom ≫ h.π ≫ eH.inv wi := by rw [assoc, h.wi, comp_zero] hi := IsKernel.isoKernel _ _ h.hi eK (by simp) wπ := by simp [IsKernel.isoKernel] hπ := IsColimit.equivOfNatIsoOfIso (parallelPair.ext (Iso.refl S.X₁) eK.symm (by simp [IsKernel.isoKernel]) (by simp)) _ _ (Cocones.ext (by exact eH.symm) (by rintro (_ | _) <;> simp [IsKernel.isoKernel])) h.hπ end LeftHomologyData /-- A short complex `S` has left homology when there exists a `S.LeftHomologyData` -/ class HasLeftHomology : Prop where condition : Nonempty S.LeftHomologyData /-- A chosen `S.LeftHomologyData` for a short complex `S` that has left homology -/ noncomputable def leftHomologyData [S.HasLeftHomology] : S.LeftHomologyData := HasLeftHomology.condition.some variable {S} namespace HasLeftHomology lemma mk' (h : S.LeftHomologyData) : HasLeftHomology S := ⟨Nonempty.intro h⟩ instance of_hasKernel_of_hasCokernel [HasKernel S.g] [HasCokernel (kernel.lift S.g S.f S.zero)] : S.HasLeftHomology := HasLeftHomology.mk' (LeftHomologyData.ofHasKernelOfHasCokernel S) instance of_hasCokernel {X Y : C} (f : X ⟶ Y) (Z : C) [HasCokernel f] : (ShortComplex.mk f (0 : Y ⟶ Z) comp_zero).HasLeftHomology := HasLeftHomology.mk' (LeftHomologyData.ofHasCokernel _ rfl) instance of_hasKernel {Y Z : C} (g : Y ⟶ Z) (X : C) [HasKernel g] : (ShortComplex.mk (0 : X ⟶ Y) g zero_comp).HasLeftHomology := HasLeftHomology.mk' (LeftHomologyData.ofHasKernel _ rfl) instance of_zeros (X Y Z : C) : (ShortComplex.mk (0 : X ⟶ Y) (0 : Y ⟶ Z) zero_comp).HasLeftHomology := HasLeftHomology.mk' (LeftHomologyData.ofZeros _ rfl rfl) end HasLeftHomology section variable (φ : S₁ ⟶ S₂) (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) /-- Given left homology data `h₁` and `h₂` for two short complexes `S₁` and `S₂`, a `LeftHomologyMapData` for a morphism `φ : S₁ ⟶ S₂` consists of a description of the induced morphisms on the `K` (cycles) and `H` (left homology) fields of `h₁` and `h₂`. -/ structure LeftHomologyMapData where /-- the induced map on cycles -/ φK : h₁.K ⟶ h₂.K /-- the induced map on left homology -/ φH : h₁.H ⟶ h₂.H /-- commutation with `i` -/ commi : φK ≫ h₂.i = h₁.i ≫ φ.τ₂ := by cat_disch /-- commutation with `f'` -/ commf' : h₁.f' ≫ φK = φ.τ₁ ≫ h₂.f' := by cat_disch /-- commutation with `π` -/ commπ : h₁.π ≫ φH = φK ≫ h₂.π := by cat_disch namespace LeftHomologyMapData attribute [reassoc (attr := simp)] commi commf' commπ /-- The left homology map data associated to the zero morphism between two short complexes. -/ @[simps] def zero (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) : LeftHomologyMapData 0 h₁ h₂ where φK := 0 φH := 0 /-- The left homology map data associated to the identity morphism of a short complex. -/ @[simps] def id (h : S.LeftHomologyData) : LeftHomologyMapData (𝟙 S) h h where φK := 𝟙 _ φH := 𝟙 _ /-- The composition of left homology map data. -/ @[simps] def comp {φ : S₁ ⟶ S₂} {φ' : S₂ ⟶ S₃} {h₁ : S₁.LeftHomologyData} {h₂ : S₂.LeftHomologyData} {h₃ : S₃.LeftHomologyData} (ψ : LeftHomologyMapData φ h₁ h₂) (ψ' : LeftHomologyMapData φ' h₂ h₃) : LeftHomologyMapData (φ ≫ φ') h₁ h₃ where φK := ψ.φK ≫ ψ'.φK φH := ψ.φH ≫ ψ'.φH instance : Subsingleton (LeftHomologyMapData φ h₁ h₂) := ⟨fun ψ₁ ψ₂ => by have hK : ψ₁.φK = ψ₂.φK := by rw [← cancel_mono h₂.i, commi, commi] have hH : ψ₁.φH = ψ₂.φH := by rw [← cancel_epi h₁.π, commπ, commπ, hK] cases ψ₁ cases ψ₂ congr⟩ instance : Inhabited (LeftHomologyMapData φ h₁ h₂) := ⟨by let φK : h₁.K ⟶ h₂.K := h₂.liftK (h₁.i ≫ φ.τ₂) (by rw [assoc, φ.comm₂₃, h₁.wi_assoc, zero_comp]) have commf' : h₁.f' ≫ φK = φ.τ₁ ≫ h₂.f' := by rw [← cancel_mono h₂.i, assoc, assoc, LeftHomologyData.liftK_i, LeftHomologyData.f'_i_assoc, LeftHomologyData.f'_i, φ.comm₁₂] let φH : h₁.H ⟶ h₂.H := h₁.descH (φK ≫ h₂.π) (by rw [reassoc_of% commf', h₂.f'_π, comp_zero]) exact ⟨φK, φH, by simp [φK], commf', by simp [φH]⟩⟩ instance : Unique (LeftHomologyMapData φ h₁ h₂) := Unique.mk' _ variable {φ h₁ h₂} lemma congr_φH {γ₁ γ₂ : LeftHomologyMapData φ h₁ h₂} (eq : γ₁ = γ₂) : γ₁.φH = γ₂.φH := by rw [eq] lemma congr_φK {γ₁ γ₂ : LeftHomologyMapData φ h₁ h₂} (eq : γ₁ = γ₂) : γ₁.φK = γ₂.φK := by rw [eq] /-- When `S₁.f`, `S₁.g`, `S₂.f` and `S₂.g` are all zero, the action on left homology of a morphism `φ : S₁ ⟶ S₂` is given by the action `φ.τ₂` on the middle objects. -/ @[simps] def ofZeros (φ : S₁ ⟶ S₂) (hf₁ : S₁.f = 0) (hg₁ : S₁.g = 0) (hf₂ : S₂.f = 0) (hg₂ : S₂.g = 0) : LeftHomologyMapData φ (LeftHomologyData.ofZeros S₁ hf₁ hg₁) (LeftHomologyData.ofZeros S₂ hf₂ hg₂) where φK := φ.τ₂ φH := φ.τ₂ /-- When `S₁.g` and `S₂.g` are zero and we have chosen colimit cokernel coforks `c₁` and `c₂` for `S₁.f` and `S₂.f` respectively, the action on left homology of a morphism `φ : S₁ ⟶ S₂` of short complexes is given by the unique morphism `f : c₁.pt ⟶ c₂.pt` such that `φ.τ₂ ≫ c₂.π = c₁.π ≫ f`. -/ @[simps] def ofIsColimitCokernelCofork (φ : S₁ ⟶ S₂) (hg₁ : S₁.g = 0) (c₁ : CokernelCofork S₁.f) (hc₁ : IsColimit c₁) (hg₂ : S₂.g = 0) (c₂ : CokernelCofork S₂.f) (hc₂ : IsColimit c₂) (f : c₁.pt ⟶ c₂.pt) (comm : φ.τ₂ ≫ c₂.π = c₁.π ≫ f) : LeftHomologyMapData φ (LeftHomologyData.ofIsColimitCokernelCofork S₁ hg₁ c₁ hc₁) (LeftHomologyData.ofIsColimitCokernelCofork S₂ hg₂ c₂ hc₂) where φK := φ.τ₂ φH := f commπ := comm.symm commf' := by simp only [LeftHomologyData.ofIsColimitCokernelCofork_f', φ.comm₁₂] /-- When `S₁.f` and `S₂.f` are zero and we have chosen limit kernel forks `c₁` and `c₂` for `S₁.g` and `S₂.g` respectively, the action on left homology of a morphism `φ : S₁ ⟶ S₂` of short complexes is given by the unique morphism `f : c₁.pt ⟶ c₂.pt` such that `c₁.ι ≫ φ.τ₂ = f ≫ c₂.ι`. -/ @[simps] def ofIsLimitKernelFork (φ : S₁ ⟶ S₂) (hf₁ : S₁.f = 0) (c₁ : KernelFork S₁.g) (hc₁ : IsLimit c₁) (hf₂ : S₂.f = 0) (c₂ : KernelFork S₂.g) (hc₂ : IsLimit c₂) (f : c₁.pt ⟶ c₂.pt) (comm : c₁.ι ≫ φ.τ₂ = f ≫ c₂.ι) : LeftHomologyMapData φ (LeftHomologyData.ofIsLimitKernelFork S₁ hf₁ c₁ hc₁) (LeftHomologyData.ofIsLimitKernelFork S₂ hf₂ c₂ hc₂) where φK := f φH := f commi := comm.symm variable (S) /-- When both maps `S.f` and `S.g` of a short complex `S` are zero, this is the left homology map data (for the identity of `S`) which relates the left homology data `ofZeros` and `ofIsColimitCokernelCofork`. -/ @[simps] def compatibilityOfZerosOfIsColimitCokernelCofork (hf : S.f = 0) (hg : S.g = 0) (c : CokernelCofork S.f) (hc : IsColimit c) : LeftHomologyMapData (𝟙 S) (LeftHomologyData.ofZeros S hf hg) (LeftHomologyData.ofIsColimitCokernelCofork S hg c hc) where φK := 𝟙 _ φH := c.π /-- When both maps `S.f` and `S.g` of a short complex `S` are zero, this is the left homology map data (for the identity of `S`) which relates the left homology data `LeftHomologyData.ofIsLimitKernelFork` and `ofZeros` . -/ @[simps] def compatibilityOfZerosOfIsLimitKernelFork (hf : S.f = 0) (hg : S.g = 0) (c : KernelFork S.g) (hc : IsLimit c) : LeftHomologyMapData (𝟙 S) (LeftHomologyData.ofIsLimitKernelFork S hf c hc) (LeftHomologyData.ofZeros S hf hg) where φK := c.ι φH := c.ι end LeftHomologyMapData end section variable (S) variable [S.HasLeftHomology] /-- The left homology of a short complex, given by the `H` field of a chosen left homology data. -/ noncomputable def leftHomology : C := S.leftHomologyData.H -- `S.leftHomology` is the simp normal form. @[simp] lemma leftHomologyData_H : S.leftHomologyData.H = S.leftHomology := rfl /-- The cycles of a short complex, given by the `K` field of a chosen left homology data. -/ noncomputable def cycles : C := S.leftHomologyData.K /-- The "homology class" map `S.cycles ⟶ S.leftHomology`. -/ noncomputable def leftHomologyπ : S.cycles ⟶ S.leftHomology := S.leftHomologyData.π /-- The inclusion `S.cycles ⟶ S.X₂`. -/ noncomputable def iCycles : S.cycles ⟶ S.X₂ := S.leftHomologyData.i /-- The "boundaries" map `S.X₁ ⟶ S.cycles`. (Note that in this homology API, we make no use of the "image" of this morphism, which under some categorical assumptions would be a subobject of `S.X₂` contained in `S.cycles`.) -/ noncomputable def toCycles : S.X₁ ⟶ S.cycles := S.leftHomologyData.f' @[reassoc (attr := simp)] lemma iCycles_g : S.iCycles ≫ S.g = 0 := S.leftHomologyData.wi @[reassoc (attr := simp)] lemma toCycles_i : S.toCycles ≫ S.iCycles = S.f := S.leftHomologyData.f'_i instance : Mono S.iCycles := by dsimp only [iCycles] infer_instance instance : Epi S.leftHomologyπ := by dsimp only [leftHomologyπ] infer_instance lemma leftHomology_ext_iff {A : C} (f₁ f₂ : S.leftHomology ⟶ A) : f₁ = f₂ ↔ S.leftHomologyπ ≫ f₁ = S.leftHomologyπ ≫ f₂ := by rw [cancel_epi] @[ext] lemma leftHomology_ext {A : C} (f₁ f₂ : S.leftHomology ⟶ A) (h : S.leftHomologyπ ≫ f₁ = S.leftHomologyπ ≫ f₂) : f₁ = f₂ := by simpa only [leftHomology_ext_iff] using h lemma cycles_ext_iff {A : C} (f₁ f₂ : A ⟶ S.cycles) : f₁ = f₂ ↔ f₁ ≫ S.iCycles = f₂ ≫ S.iCycles := by rw [cancel_mono] @[ext] lemma cycles_ext {A : C} (f₁ f₂ : A ⟶ S.cycles) (h : f₁ ≫ S.iCycles = f₂ ≫ S.iCycles) : f₁ = f₂ := by simpa only [cycles_ext_iff] using h lemma isIso_iCycles (hg : S.g = 0) : IsIso S.iCycles := LeftHomologyData.isIso_i _ hg /-- When `S.g = 0`, this is the canonical isomorphism `S.cycles ≅ S.X₂` induced by `S.iCycles`. -/ @[simps! hom] noncomputable def cyclesIsoX₂ (hg : S.g = 0) : S.cycles ≅ S.X₂ := by have := S.isIso_iCycles hg exact asIso S.iCycles @[reassoc (attr := simp)] lemma cyclesIsoX₂_hom_inv_id (hg : S.g = 0) : S.iCycles ≫ (S.cyclesIsoX₂ hg).inv = 𝟙 _ := (S.cyclesIsoX₂ hg).hom_inv_id @[reassoc (attr := simp)] lemma cyclesIsoX₂_inv_hom_id (hg : S.g = 0) : (S.cyclesIsoX₂ hg).inv ≫ S.iCycles = 𝟙 _ := (S.cyclesIsoX₂ hg).inv_hom_id lemma isIso_leftHomologyπ (hf : S.f = 0) : IsIso S.leftHomologyπ := LeftHomologyData.isIso_π _ hf /-- When `S.f = 0`, this is the canonical isomorphism `S.cycles ≅ S.leftHomology` induced by `S.leftHomologyπ`. -/ @[simps! hom] noncomputable def cyclesIsoLeftHomology (hf : S.f = 0) : S.cycles ≅ S.leftHomology := by have := S.isIso_leftHomologyπ hf exact asIso S.leftHomologyπ @[reassoc (attr := simp)] lemma cyclesIsoLeftHomology_hom_inv_id (hf : S.f = 0) : S.leftHomologyπ ≫ (S.cyclesIsoLeftHomology hf).inv = 𝟙 _ := (S.cyclesIsoLeftHomology hf).hom_inv_id @[reassoc (attr := simp)] lemma cyclesIsoLeftHomology_inv_hom_id (hf : S.f = 0) : (S.cyclesIsoLeftHomology hf).inv ≫ S.leftHomologyπ = 𝟙 _ := (S.cyclesIsoLeftHomology hf).inv_hom_id end section variable (φ : S₁ ⟶ S₂) (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) /-- The (unique) left homology map data associated to a morphism of short complexes that are both equipped with left homology data. -/ def leftHomologyMapData : LeftHomologyMapData φ h₁ h₂ := default /-- Given a morphism `φ : S₁ ⟶ S₂` of short complexes and left homology data `h₁` and `h₂` for `S₁` and `S₂` respectively, this is the induced left homology map `h₁.H ⟶ h₁.H`. -/ def leftHomologyMap' : h₁.H ⟶ h₂.H := (leftHomologyMapData φ _ _).φH /-- Given a morphism `φ : S₁ ⟶ S₂` of short complexes and left homology data `h₁` and `h₂` for `S₁` and `S₂` respectively, this is the induced morphism `h₁.K ⟶ h₁.K` on cycles. -/ def cyclesMap' : h₁.K ⟶ h₂.K := (leftHomologyMapData φ _ _).φK @[reassoc (attr := simp)] lemma cyclesMap'_i : cyclesMap' φ h₁ h₂ ≫ h₂.i = h₁.i ≫ φ.τ₂ := LeftHomologyMapData.commi _ @[reassoc (attr := simp)] lemma f'_cyclesMap' : h₁.f' ≫ cyclesMap' φ h₁ h₂ = φ.τ₁ ≫ h₂.f' := by simp only [← cancel_mono h₂.i, assoc, φ.comm₁₂, cyclesMap'_i, LeftHomologyData.f'_i_assoc, LeftHomologyData.f'_i] @[reassoc (attr := simp)] lemma leftHomologyπ_naturality' : h₁.π ≫ leftHomologyMap' φ h₁ h₂ = cyclesMap' φ h₁ h₂ ≫ h₂.π := LeftHomologyMapData.commπ _ end section variable [HasLeftHomology S₁] [HasLeftHomology S₂] (φ : S₁ ⟶ S₂) /-- The (left) homology map `S₁.leftHomology ⟶ S₂.leftHomology` induced by a morphism `S₁ ⟶ S₂` of short complexes. -/ noncomputable def leftHomologyMap : S₁.leftHomology ⟶ S₂.leftHomology := leftHomologyMap' φ _ _ /-- The morphism `S₁.cycles ⟶ S₂.cycles` induced by a morphism `S₁ ⟶ S₂` of short complexes. -/ noncomputable def cyclesMap : S₁.cycles ⟶ S₂.cycles := cyclesMap' φ _ _ @[reassoc (attr := simp)] lemma cyclesMap_i : cyclesMap φ ≫ S₂.iCycles = S₁.iCycles ≫ φ.τ₂ := cyclesMap'_i _ _ _ @[reassoc (attr := simp)] lemma toCycles_naturality : S₁.toCycles ≫ cyclesMap φ = φ.τ₁ ≫ S₂.toCycles := f'_cyclesMap' _ _ _ @[reassoc (attr := simp)] lemma leftHomologyπ_naturality : S₁.leftHomologyπ ≫ leftHomologyMap φ = cyclesMap φ ≫ S₂.leftHomologyπ := leftHomologyπ_naturality' _ _ _ end namespace LeftHomologyMapData variable {φ : S₁ ⟶ S₂} {h₁ : S₁.LeftHomologyData} {h₂ : S₂.LeftHomologyData} (γ : LeftHomologyMapData φ h₁ h₂) lemma leftHomologyMap'_eq : leftHomologyMap' φ h₁ h₂ = γ.φH := LeftHomologyMapData.congr_φH (Subsingleton.elim _ _) lemma cyclesMap'_eq : cyclesMap' φ h₁ h₂ = γ.φK := LeftHomologyMapData.congr_φK (Subsingleton.elim _ _) end LeftHomologyMapData @[simp] lemma leftHomologyMap'_id (h : S.LeftHomologyData) : leftHomologyMap' (𝟙 S) h h = 𝟙 _ := (LeftHomologyMapData.id h).leftHomologyMap'_eq @[simp] lemma cyclesMap'_id (h : S.LeftHomologyData) : cyclesMap' (𝟙 S) h h = 𝟙 _ := (LeftHomologyMapData.id h).cyclesMap'_eq variable (S) @[simp] lemma leftHomologyMap_id [HasLeftHomology S] : leftHomologyMap (𝟙 S) = 𝟙 _ := leftHomologyMap'_id _ @[simp] lemma cyclesMap_id [HasLeftHomology S] : cyclesMap (𝟙 S) = 𝟙 _ := cyclesMap'_id _ @[simp] lemma leftHomologyMap'_zero (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) : leftHomologyMap' 0 h₁ h₂ = 0 := (LeftHomologyMapData.zero h₁ h₂).leftHomologyMap'_eq @[simp] lemma cyclesMap'_zero (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) : cyclesMap' 0 h₁ h₂ = 0 := (LeftHomologyMapData.zero h₁ h₂).cyclesMap'_eq variable (S₁ S₂) @[simp] lemma leftHomologyMap_zero [HasLeftHomology S₁] [HasLeftHomology S₂] : leftHomologyMap (0 : S₁ ⟶ S₂) = 0 := leftHomologyMap'_zero _ _ @[simp] lemma cyclesMap_zero [HasLeftHomology S₁] [HasLeftHomology S₂] : cyclesMap (0 : S₁ ⟶ S₂) = 0 := cyclesMap'_zero _ _ variable {S₁ S₂} @[reassoc] lemma leftHomologyMap'_comp (φ₁ : S₁ ⟶ S₂) (φ₂ : S₂ ⟶ S₃) (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) (h₃ : S₃.LeftHomologyData) : leftHomologyMap' (φ₁ ≫ φ₂) h₁ h₃ = leftHomologyMap' φ₁ h₁ h₂ ≫ leftHomologyMap' φ₂ h₂ h₃ := by let γ₁ := leftHomologyMapData φ₁ h₁ h₂ let γ₂ := leftHomologyMapData φ₂ h₂ h₃ rw [γ₁.leftHomologyMap'_eq, γ₂.leftHomologyMap'_eq, (γ₁.comp γ₂).leftHomologyMap'_eq, LeftHomologyMapData.comp_φH] @[reassoc] lemma cyclesMap'_comp (φ₁ : S₁ ⟶ S₂) (φ₂ : S₂ ⟶ S₃) (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) (h₃ : S₃.LeftHomologyData) : cyclesMap' (φ₁ ≫ φ₂) h₁ h₃ = cyclesMap' φ₁ h₁ h₂ ≫ cyclesMap' φ₂ h₂ h₃ := by let γ₁ := leftHomologyMapData φ₁ h₁ h₂ let γ₂ := leftHomologyMapData φ₂ h₂ h₃ rw [γ₁.cyclesMap'_eq, γ₂.cyclesMap'_eq, (γ₁.comp γ₂).cyclesMap'_eq, LeftHomologyMapData.comp_φK] @[reassoc] lemma leftHomologyMap_comp [HasLeftHomology S₁] [HasLeftHomology S₂] [HasLeftHomology S₃] (φ₁ : S₁ ⟶ S₂) (φ₂ : S₂ ⟶ S₃) : leftHomologyMap (φ₁ ≫ φ₂) = leftHomologyMap φ₁ ≫ leftHomologyMap φ₂ := leftHomologyMap'_comp _ _ _ _ _ @[reassoc] lemma cyclesMap_comp [HasLeftHomology S₁] [HasLeftHomology S₂] [HasLeftHomology S₃] (φ₁ : S₁ ⟶ S₂) (φ₂ : S₂ ⟶ S₃) : cyclesMap (φ₁ ≫ φ₂) = cyclesMap φ₁ ≫ cyclesMap φ₂ := cyclesMap'_comp _ _ _ _ _ attribute [simp] leftHomologyMap_comp cyclesMap_comp /-- An isomorphism of short complexes `S₁ ≅ S₂` induces an isomorphism on the `H` fields of left homology data of `S₁` and `S₂`. -/ @[simps] def leftHomologyMapIso' (e : S₁ ≅ S₂) (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) : h₁.H ≅ h₂.H where hom := leftHomologyMap' e.hom h₁ h₂ inv := leftHomologyMap' e.inv h₂ h₁ hom_inv_id := by rw [← leftHomologyMap'_comp, e.hom_inv_id, leftHomologyMap'_id] inv_hom_id := by rw [← leftHomologyMap'_comp, e.inv_hom_id, leftHomologyMap'_id] instance isIso_leftHomologyMap'_of_isIso (φ : S₁ ⟶ S₂) [IsIso φ] (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) : IsIso (leftHomologyMap' φ h₁ h₂) := (inferInstance : IsIso (leftHomologyMapIso' (asIso φ) h₁ h₂).hom) /-- An isomorphism of short complexes `S₁ ≅ S₂` induces an isomorphism on the `K` fields of left homology data of `S₁` and `S₂`. -/ @[simps] def cyclesMapIso' (e : S₁ ≅ S₂) (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) : h₁.K ≅ h₂.K where hom := cyclesMap' e.hom h₁ h₂ inv := cyclesMap' e.inv h₂ h₁ hom_inv_id := by rw [← cyclesMap'_comp, e.hom_inv_id, cyclesMap'_id] inv_hom_id := by rw [← cyclesMap'_comp, e.inv_hom_id, cyclesMap'_id] instance isIso_cyclesMap'_of_isIso (φ : S₁ ⟶ S₂) [IsIso φ] (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) : IsIso (cyclesMap' φ h₁ h₂) := (inferInstance : IsIso (cyclesMapIso' (asIso φ) h₁ h₂).hom) /-- The isomorphism `S₁.leftHomology ≅ S₂.leftHomology` induced by an isomorphism of short complexes `S₁ ≅ S₂`. -/ @[simps] noncomputable def leftHomologyMapIso (e : S₁ ≅ S₂) [S₁.HasLeftHomology] [S₂.HasLeftHomology] : S₁.leftHomology ≅ S₂.leftHomology where hom := leftHomologyMap e.hom inv := leftHomologyMap e.inv hom_inv_id := by rw [← leftHomologyMap_comp, e.hom_inv_id, leftHomologyMap_id] inv_hom_id := by rw [← leftHomologyMap_comp, e.inv_hom_id, leftHomologyMap_id] instance isIso_leftHomologyMap_of_iso (φ : S₁ ⟶ S₂) [IsIso φ] [S₁.HasLeftHomology] [S₂.HasLeftHomology] : IsIso (leftHomologyMap φ) := (inferInstance : IsIso (leftHomologyMapIso (asIso φ)).hom) /-- The isomorphism `S₁.cycles ≅ S₂.cycles` induced by an isomorphism of short complexes `S₁ ≅ S₂`. -/ @[simps] noncomputable def cyclesMapIso (e : S₁ ≅ S₂) [S₁.HasLeftHomology] [S₂.HasLeftHomology] : S₁.cycles ≅ S₂.cycles where hom := cyclesMap e.hom inv := cyclesMap e.inv hom_inv_id := by rw [← cyclesMap_comp, e.hom_inv_id, cyclesMap_id] inv_hom_id := by rw [← cyclesMap_comp, e.inv_hom_id, cyclesMap_id] instance isIso_cyclesMap_of_iso (φ : S₁ ⟶ S₂) [IsIso φ] [S₁.HasLeftHomology] [S₂.HasLeftHomology] : IsIso (cyclesMap φ) := (inferInstance : IsIso (cyclesMapIso (asIso φ)).hom) variable {S} namespace LeftHomologyData variable (h : S.LeftHomologyData) [S.HasLeftHomology] /-- The isomorphism `S.leftHomology ≅ h.H` induced by a left homology data `h` for a short complex `S`. -/ noncomputable def leftHomologyIso : S.leftHomology ≅ h.H := leftHomologyMapIso' (Iso.refl _) _ _ /-- The isomorphism `S.cycles ≅ h.K` induced by a left homology data `h` for a short complex `S`. -/ noncomputable def cyclesIso : S.cycles ≅ h.K := cyclesMapIso' (Iso.refl _) _ _ @[reassoc (attr := simp)] lemma cyclesIso_hom_comp_i : h.cyclesIso.hom ≫ h.i = S.iCycles := by dsimp [iCycles, LeftHomologyData.cyclesIso] simp only [cyclesMap'_i, id_τ₂, comp_id] @[reassoc (attr := simp)] lemma cyclesIso_inv_comp_iCycles : h.cyclesIso.inv ≫ S.iCycles = h.i := by simp only [← h.cyclesIso_hom_comp_i, Iso.inv_hom_id_assoc] @[reassoc (attr := simp)] lemma leftHomologyπ_comp_leftHomologyIso_hom : S.leftHomologyπ ≫ h.leftHomologyIso.hom = h.cyclesIso.hom ≫ h.π := by dsimp only [leftHomologyπ, leftHomologyIso, cyclesIso, leftHomologyMapIso', cyclesMapIso', Iso.refl] rw [← leftHomologyπ_naturality'] @[reassoc (attr := simp)] lemma π_comp_leftHomologyIso_inv : h.π ≫ h.leftHomologyIso.inv = h.cyclesIso.inv ≫ S.leftHomologyπ := by simp only [← cancel_epi h.cyclesIso.hom, ← cancel_mono h.leftHomologyIso.hom, assoc, Iso.inv_hom_id, comp_id, Iso.hom_inv_id_assoc, LeftHomologyData.leftHomologyπ_comp_leftHomologyIso_hom] end LeftHomologyData namespace LeftHomologyMapData variable {φ : S₁ ⟶ S₂} {h₁ : S₁.LeftHomologyData} {h₂ : S₂.LeftHomologyData} (γ : LeftHomologyMapData φ h₁ h₂) lemma leftHomologyMap_eq [S₁.HasLeftHomology] [S₂.HasLeftHomology] : leftHomologyMap φ = h₁.leftHomologyIso.hom ≫ γ.φH ≫ h₂.leftHomologyIso.inv := by dsimp [LeftHomologyData.leftHomologyIso, leftHomologyMapIso'] rw [← γ.leftHomologyMap'_eq, ← leftHomologyMap'_comp, ← leftHomologyMap'_comp, id_comp, comp_id] rfl lemma cyclesMap_eq [S₁.HasLeftHomology] [S₂.HasLeftHomology] : cyclesMap φ = h₁.cyclesIso.hom ≫ γ.φK ≫ h₂.cyclesIso.inv := by dsimp [LeftHomologyData.cyclesIso, cyclesMapIso'] rw [← γ.cyclesMap'_eq, ← cyclesMap'_comp, ← cyclesMap'_comp, id_comp, comp_id] rfl lemma leftHomologyMap_comm [S₁.HasLeftHomology] [S₂.HasLeftHomology] : leftHomologyMap φ ≫ h₂.leftHomologyIso.hom = h₁.leftHomologyIso.hom ≫ γ.φH := by simp only [γ.leftHomologyMap_eq, assoc, Iso.inv_hom_id, comp_id] lemma cyclesMap_comm [S₁.HasLeftHomology] [S₂.HasLeftHomology] : cyclesMap φ ≫ h₂.cyclesIso.hom = h₁.cyclesIso.hom ≫ γ.φK := by simp only [γ.cyclesMap_eq, assoc, Iso.inv_hom_id, comp_id] end LeftHomologyMapData section variable (C) variable [HasKernels C] [HasCokernels C] /-- The left homology functor `ShortComplex C ⥤ C`, where the left homology of a short complex `S` is understood as a cokernel of the obvious map `S.toCycles : S.X₁ ⟶ S.cycles` where `S.cycles` is a kernel of `S.g : S.X₂ ⟶ S.X₃`. -/ @[simps] noncomputable def leftHomologyFunctor : ShortComplex C ⥤ C where obj S := S.leftHomology map := leftHomologyMap /-- The cycles functor `ShortComplex C ⥤ C` which sends a short complex `S` to `S.cycles` which is a kernel of `S.g : S.X₂ ⟶ S.X₃`. -/ @[simps] noncomputable def cyclesFunctor : ShortComplex C ⥤ C where obj S := S.cycles map := cyclesMap /-- The natural transformation `S.cycles ⟶ S.leftHomology` for all short complexes `S`. -/ @[simps] noncomputable def leftHomologyπNatTrans : cyclesFunctor C ⟶ leftHomologyFunctor C where app S := leftHomologyπ S naturality := fun _ _ φ => (leftHomologyπ_naturality φ).symm /-- The natural transformation `S.cycles ⟶ S.X₂` for all short complexes `S`. -/ @[simps] noncomputable def iCyclesNatTrans : cyclesFunctor C ⟶ ShortComplex.π₂ where app S := S.iCycles /-- The natural transformation `S.X₁ ⟶ S.cycles` for all short complexes `S`. -/ @[simps] noncomputable def toCyclesNatTrans : π₁ ⟶ cyclesFunctor C where app S := S.toCycles naturality := fun _ _ φ => (toCycles_naturality φ).symm end namespace LeftHomologyData /-- If `φ : S₁ ⟶ S₂` is a morphism of short complexes such that `φ.τ₁` is epi, `φ.τ₂` is an iso and `φ.τ₃` is mono, then a left homology data for `S₁` induces a left homology data for `S₂` with the same `K` and `H` fields. The inverse construction is `ofEpiOfIsIsoOfMono'`. -/ @[simps] noncomputable def ofEpiOfIsIsoOfMono (φ : S₁ ⟶ S₂) (h : LeftHomologyData S₁) [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : LeftHomologyData S₂ := by let i : h.K ⟶ S₂.X₂ := h.i ≫ φ.τ₂ have wi : i ≫ S₂.g = 0 := by simp only [i, assoc, φ.comm₂₃, h.wi_assoc, zero_comp] have hi : IsLimit (KernelFork.ofι i wi) := KernelFork.IsLimit.ofι _ _ (fun x hx => h.liftK (x ≫ inv φ.τ₂) (by rw [assoc, ← cancel_mono φ.τ₃, assoc, assoc, ← φ.comm₂₃, IsIso.inv_hom_id_assoc, hx, zero_comp])) (fun x hx => by simp [i]) (fun x hx b hb => by dsimp rw [← cancel_mono h.i, ← cancel_mono φ.τ₂, assoc, assoc, liftK_i_assoc, assoc, IsIso.inv_hom_id, comp_id, hb]) let f' := hi.lift (KernelFork.ofι S₂.f S₂.zero) have hf' : φ.τ₁ ≫ f' = h.f' := by have eq := @Fork.IsLimit.lift_ι _ _ _ _ _ _ _ ((KernelFork.ofι S₂.f S₂.zero)) hi simp only [Fork.ι_ofι] at eq rw [← cancel_mono h.i, ← cancel_mono φ.τ₂, assoc, assoc, eq, f'_i, φ.comm₁₂] have wπ : f' ≫ h.π = 0 := by rw [← cancel_epi φ.τ₁, comp_zero, reassoc_of% hf', h.f'_π] have hπ : IsColimit (CokernelCofork.ofπ h.π wπ) := CokernelCofork.IsColimit.ofπ _ _ (fun x hx => h.descH x (by rw [← hf', assoc, hx, comp_zero])) (fun x hx => by simp) (fun x hx b hb => by rw [← cancel_epi h.π, π_descH, hb]) exact ⟨h.K, h.H, i, h.π, wi, hi, wπ, hπ⟩ @[simp] lemma τ₁_ofEpiOfIsIsoOfMono_f' (φ : S₁ ⟶ S₂) (h : LeftHomologyData S₁) [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : φ.τ₁ ≫ (ofEpiOfIsIsoOfMono φ h).f' = h.f' := by rw [← cancel_mono (ofEpiOfIsIsoOfMono φ h).i, assoc, f'_i, ofEpiOfIsIsoOfMono_i, f'_i_assoc, φ.comm₁₂] /-- If `φ : S₁ ⟶ S₂` is a morphism of short complexes such that `φ.τ₁` is epi, `φ.τ₂` is an iso and `φ.τ₃` is mono, then a left homology data for `S₂` induces a left homology data for `S₁` with the same `K` and `H` fields. The inverse construction is `ofEpiOfIsIsoOfMono`. -/ @[simps] noncomputable def ofEpiOfIsIsoOfMono' (φ : S₁ ⟶ S₂) (h : LeftHomologyData S₂) [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : LeftHomologyData S₁ := by let i : h.K ⟶ S₁.X₂ := h.i ≫ inv φ.τ₂ have wi : i ≫ S₁.g = 0 := by rw [assoc, ← cancel_mono φ.τ₃, zero_comp, assoc, assoc, ← φ.comm₂₃, IsIso.inv_hom_id_assoc, h.wi] have hi : IsLimit (KernelFork.ofι i wi) := KernelFork.IsLimit.ofι _ _ (fun x hx => h.liftK (x ≫ φ.τ₂) (by rw [assoc, φ.comm₂₃, reassoc_of% hx, zero_comp])) (fun x hx => by simp [i]) (fun x hx b hb => by rw [← cancel_mono h.i, ← cancel_mono (inv φ.τ₂), assoc, assoc, hb, liftK_i_assoc, assoc, IsIso.hom_inv_id, comp_id]) let f' := hi.lift (KernelFork.ofι S₁.f S₁.zero) have hf' : f' ≫ i = S₁.f := Fork.IsLimit.lift_ι _ have hf'' : f' = φ.τ₁ ≫ h.f' := by rw [← cancel_mono h.i, ← cancel_mono (inv φ.τ₂), assoc, assoc, assoc, hf', f'_i_assoc, φ.comm₁₂_assoc, IsIso.hom_inv_id, comp_id] have wπ : f' ≫ h.π = 0 := by simp only [hf'', assoc, f'_π, comp_zero] have hπ : IsColimit (CokernelCofork.ofπ h.π wπ) := CokernelCofork.IsColimit.ofπ _ _ (fun x hx => h.descH x (by rw [← cancel_epi φ.τ₁, ← reassoc_of% hf'', hx, comp_zero])) (fun x hx => π_descH _ _ _) (fun x hx b hx => by rw [← cancel_epi h.π, π_descH, hx]) exact ⟨h.K, h.H, i, h.π, wi, hi, wπ, hπ⟩ @[simp] lemma ofEpiOfIsIsoOfMono'_f' (φ : S₁ ⟶ S₂) (h : LeftHomologyData S₂) [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : (ofEpiOfIsIsoOfMono' φ h).f' = φ.τ₁ ≫ h.f' := by rw [← cancel_mono (ofEpiOfIsIsoOfMono' φ h).i, f'_i, ofEpiOfIsIsoOfMono'_i, assoc, f'_i_assoc, φ.comm₁₂_assoc, IsIso.hom_inv_id, comp_id] /-- If `e : S₁ ≅ S₂` is an isomorphism of short complexes and `h₁ : LeftHomologyData S₁`, this is the left homology data for `S₂` deduced from the isomorphism. -/ noncomputable def ofIso (e : S₁ ≅ S₂) (h₁ : LeftHomologyData S₁) : LeftHomologyData S₂ := h₁.ofEpiOfIsIsoOfMono e.hom end LeftHomologyData lemma hasLeftHomology_of_epi_of_isIso_of_mono (φ : S₁ ⟶ S₂) [HasLeftHomology S₁] [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : HasLeftHomology S₂ := HasLeftHomology.mk' (LeftHomologyData.ofEpiOfIsIsoOfMono φ S₁.leftHomologyData) lemma hasLeftHomology_of_epi_of_isIso_of_mono' (φ : S₁ ⟶ S₂) [HasLeftHomology S₂] [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : HasLeftHomology S₁ := HasLeftHomology.mk' (LeftHomologyData.ofEpiOfIsIsoOfMono' φ S₂.leftHomologyData) lemma hasLeftHomology_of_iso {S₁ S₂ : ShortComplex C} (e : S₁ ≅ S₂) [HasLeftHomology S₁] : HasLeftHomology S₂ := hasLeftHomology_of_epi_of_isIso_of_mono e.hom namespace LeftHomologyMapData /-- This left homology map data expresses compatibilities of the left homology data constructed by `LeftHomologyData.ofEpiOfIsIsoOfMono` -/ @[simps] noncomputable def ofEpiOfIsIsoOfMono (φ : S₁ ⟶ S₂) (h : LeftHomologyData S₁) [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : LeftHomologyMapData φ h (LeftHomologyData.ofEpiOfIsIsoOfMono φ h) where φK := 𝟙 _ φH := 𝟙 _ /-- This left homology map data expresses compatibilities of the left homology data constructed by `LeftHomologyData.ofEpiOfIsIsoOfMono'` -/ @[simps] noncomputable def ofEpiOfIsIsoOfMono' (φ : S₁ ⟶ S₂) (h : LeftHomologyData S₂) [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : LeftHomologyMapData φ (LeftHomologyData.ofEpiOfIsIsoOfMono' φ h) h where φK := 𝟙 _ φH := 𝟙 _ end LeftHomologyMapData instance (φ : S₁ ⟶ S₂) (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : IsIso (leftHomologyMap' φ h₁ h₂) := by let h₂' := LeftHomologyData.ofEpiOfIsIsoOfMono φ h₁ have : IsIso (leftHomologyMap' φ h₁ h₂') := by rw [(LeftHomologyMapData.ofEpiOfIsIsoOfMono φ h₁).leftHomologyMap'_eq] dsimp infer_instance have eq := leftHomologyMap'_comp φ (𝟙 S₂) h₁ h₂' h₂ rw [comp_id] at eq rw [eq] infer_instance /-- If a morphism of short complexes `φ : S₁ ⟶ S₂` is such that `φ.τ₁` is epi, `φ.τ₂` is an iso, and `φ.τ₃` is mono, then the induced morphism on left homology is an isomorphism. -/ instance (φ : S₁ ⟶ S₂) [S₁.HasLeftHomology] [S₂.HasLeftHomology] [Epi φ.τ₁] [IsIso φ.τ₂] [Mono φ.τ₃] : IsIso (leftHomologyMap φ) := by dsimp only [leftHomologyMap] infer_instance section variable (S) (h : LeftHomologyData S) {A : C} (k : A ⟶ S.X₂) (hk : k ≫ S.g = 0) [HasLeftHomology S] /-- A morphism `k : A ⟶ S.X₂` such that `k ≫ S.g = 0` lifts to a morphism `A ⟶ S.cycles`. -/ noncomputable def liftCycles : A ⟶ S.cycles := S.leftHomologyData.liftK k hk @[reassoc (attr := simp)] lemma liftCycles_i : S.liftCycles k hk ≫ S.iCycles = k := LeftHomologyData.liftK_i _ k hk @[reassoc] lemma comp_liftCycles {A' : C} (α : A' ⟶ A) : α ≫ S.liftCycles k hk = S.liftCycles (α ≫ k) (by rw [assoc, hk, comp_zero]) := by cat_disch /-- Via `S.iCycles : S.cycles ⟶ S.X₂`, the object `S.cycles` identifies to the kernel of `S.g : S.X₂ ⟶ S.X₃`. -/ noncomputable def cyclesIsKernel : IsLimit (KernelFork.ofι S.iCycles S.iCycles_g) := S.leftHomologyData.hi /-- The canonical isomorphism `S.cycles ≅ kernel S.g`. -/ @[simps] noncomputable def cyclesIsoKernel [HasKernel S.g] : S.cycles ≅ kernel S.g where hom := kernel.lift S.g S.iCycles (by simp) inv := S.liftCycles (kernel.ι S.g) (by simp) /-- The morphism `A ⟶ S.leftHomology` obtained from a morphism `k : A ⟶ S.X₂` such that `k ≫ S.g = 0.` -/ @[simp] noncomputable def liftLeftHomology : A ⟶ S.leftHomology := S.liftCycles k hk ≫ S.leftHomologyπ @[reassoc] lemma liftCycles_leftHomologyπ_eq_zero_of_boundary (x : A ⟶ S.X₁) (hx : k = x ≫ S.f) : S.liftCycles k (by rw [hx, assoc, S.zero, comp_zero]) ≫ S.leftHomologyπ = 0 := LeftHomologyData.liftK_π_eq_zero_of_boundary _ k x hx @[reassoc (attr := simp)] lemma toCycles_comp_leftHomologyπ : S.toCycles ≫ S.leftHomologyπ = 0 := S.liftCycles_leftHomologyπ_eq_zero_of_boundary S.f (𝟙 _) (by rw [id_comp]) /-- Via `S.leftHomologyπ : S.cycles ⟶ S.leftHomology`, the object `S.leftHomology` identifies to the cokernel of `S.toCycles : S.X₁ ⟶ S.cycles`. -/ noncomputable def leftHomologyIsCokernel : IsColimit (CokernelCofork.ofπ S.leftHomologyπ S.toCycles_comp_leftHomologyπ) := S.leftHomologyData.hπ @[reassoc (attr := simp)] lemma liftCycles_comp_cyclesMap (φ : S ⟶ S₁) [S₁.HasLeftHomology] : S.liftCycles k hk ≫ cyclesMap φ = S₁.liftCycles (k ≫ φ.τ₂) (by rw [assoc, φ.comm₂₃, reassoc_of% hk, zero_comp]) := by cat_disch variable {S} @[reassoc (attr := simp)] lemma LeftHomologyData.liftCycles_comp_cyclesIso_hom : S.liftCycles k hk ≫ h.cyclesIso.hom = h.liftK k hk := by simp only [← cancel_mono h.i, assoc, LeftHomologyData.cyclesIso_hom_comp_i, liftCycles_i, LeftHomologyData.liftK_i] @[reassoc (attr := simp)] lemma LeftHomologyData.lift_K_comp_cyclesIso_inv : h.liftK k hk ≫ h.cyclesIso.inv = S.liftCycles k hk := by rw [← h.liftCycles_comp_cyclesIso_hom, assoc, Iso.hom_inv_id, comp_id] end namespace HasLeftHomology variable (S) lemma hasKernel [S.HasLeftHomology] : HasKernel S.g := ⟨⟨⟨_, S.leftHomologyData.hi⟩⟩⟩ lemma hasCokernel [S.HasLeftHomology] [HasKernel S.g] : HasCokernel (kernel.lift S.g S.f S.zero) := by let h := S.leftHomologyData haveI : HasColimit (parallelPair h.f' 0) := ⟨⟨⟨_, h.hπ'⟩⟩⟩ let e : parallelPair (kernel.lift S.g S.f S.zero) 0 ≅ parallelPair h.f' 0 := parallelPair.ext (Iso.refl _) (IsLimit.conePointUniqueUpToIso (kernelIsKernel S.g) h.hi) (by cat_disch) (by simp) exact hasColimit_of_iso e end HasLeftHomology /-- The left homology of a short complex `S` identifies to the cokernel of the canonical morphism `S.X₁ ⟶ kernel S.g`. -/ noncomputable def leftHomologyIsoCokernelLift [S.HasLeftHomology] [HasKernel S.g] [HasCokernel (kernel.lift S.g S.f S.zero)] : S.leftHomology ≅ cokernel (kernel.lift S.g S.f S.zero) := (LeftHomologyData.ofHasKernelOfHasCokernel S).leftHomologyIso /-! The following lemmas and instance gives a sufficient condition for a morphism of short complexes to induce an isomorphism on cycles. -/ lemma isIso_cyclesMap'_of_isIso_of_mono (φ : S₁ ⟶ S₂) (h₂ : IsIso φ.τ₂) (h₃ : Mono φ.τ₃) (h₁ : S₁.LeftHomologyData) (h₂ : S₂.LeftHomologyData) : IsIso (cyclesMap' φ h₁ h₂) := by refine ⟨h₁.liftK (h₂.i ≫ inv φ.τ₂) ?_, ?_, ?_⟩ · simp only [assoc, ← cancel_mono φ.τ₃, zero_comp, ← φ.comm₂₃, IsIso.inv_hom_id_assoc, h₂.wi] · simp only [← cancel_mono h₁.i, assoc, h₁.liftK_i, cyclesMap'_i_assoc, IsIso.hom_inv_id, comp_id, id_comp] · simp only [← cancel_mono h₂.i, assoc, cyclesMap'_i, h₁.liftK_i_assoc, IsIso.inv_hom_id, comp_id, id_comp] lemma isIso_cyclesMap_of_isIso_of_mono' (φ : S₁ ⟶ S₂) (h₂ : IsIso φ.τ₂) (h₃ : Mono φ.τ₃) [S₁.HasLeftHomology] [S₂.HasLeftHomology] : IsIso (cyclesMap φ) := isIso_cyclesMap'_of_isIso_of_mono φ h₂ h₃ _ _ instance isIso_cyclesMap_of_isIso_of_mono (φ : S₁ ⟶ S₂) [IsIso φ.τ₂] [Mono φ.τ₃] [S₁.HasLeftHomology] [S₂.HasLeftHomology] : IsIso (cyclesMap φ) := isIso_cyclesMap_of_isIso_of_mono' φ inferInstance inferInstance end ShortComplex end CategoryTheory
BitIndices.lean
/- Copyright (c) 2024 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson -/ import Mathlib.Algebra.BigOperators.Ring.List import Mathlib.Algebra.Order.BigOperators.Group.List import Mathlib.Algebra.Order.Group.Nat import Mathlib.Algebra.Order.Sub.Basic import Mathlib.Data.List.Sort import Mathlib.Data.Nat.Bitwise /-! # Bit Indices Given `n : ℕ`, we define `Nat.bitIndices n`, which is the `List` of indices of `1`s in the binary expansion of `n`. If `s : Finset ℕ` and `n = ∑ i ∈ s, 2^i`, then `Nat.bitIndices n` is the sorted list of elements of `s`. The lemma `twoPowSum_bitIndices` proves that summing `2 ^ i` over this list gives `n`. This is used in `Combinatorics.colex` to construct a bijection `equivBitIndices : ℕ ≃ Finset ℕ`. ## TODO Relate the material in this file to `Nat.digits` and `Nat.bits`. -/ open List namespace Nat variable {a n : ℕ} /-- The function which maps each natural number `∑ i ∈ s, 2^i` to the list of elements of `s` in increasing order. -/ def bitIndices (n : ℕ) : List ℕ := @binaryRec (fun _ ↦ List ℕ) [] (fun b _ s ↦ b.casesOn (s.map (· + 1)) (0 :: s.map (· + 1))) n @[simp] theorem bitIndices_zero : bitIndices 0 = [] := by simp [bitIndices] @[simp] theorem bitIndices_one : bitIndices 1 = [0] := by simp [bitIndices] theorem bitIndices_bit_true (n : ℕ) : bitIndices (bit true n) = 0 :: ((bitIndices n).map (· + 1)) := binaryRec_eq _ _ (.inl rfl) theorem bitIndices_bit_false (n : ℕ) : bitIndices (bit false n) = (bitIndices n).map (· + 1) := binaryRec_eq _ _ (.inl rfl) @[simp] theorem bitIndices_two_mul_add_one (n : ℕ) : bitIndices (2 * n + 1) = 0 :: (bitIndices n).map (· + 1) := by rw [← bitIndices_bit_true, bit_true] @[simp] theorem bitIndices_two_mul (n : ℕ) : bitIndices (2 * n) = (bitIndices n).map (· + 1) := by rw [← bitIndices_bit_false, bit_false] @[simp] theorem bitIndices_sorted {n : ℕ} : n.bitIndices.Sorted (· < ·) := by induction' n using binaryRec with b n hs · simp suffices List.Pairwise (fun a b ↦ a < b) n.bitIndices by cases b <;> simpa [List.Sorted, bit_false, bit_true, List.pairwise_map] exact List.Pairwise.imp (by simp) hs @[simp] theorem bitIndices_two_pow_mul (k n : ℕ) : bitIndices (2^k * n) = (bitIndices n).map (· + k) := by induction' k with k ih · simp rw [add_comm, pow_add, pow_one, mul_assoc, bitIndices_two_mul, ih, List.map_map, comp_add_right] simp [add_comm (a := 1)] @[simp] theorem bitIndices_two_pow (k : ℕ) : bitIndices (2^k) = [k] := by rw [← mul_one (a := 2^k), bitIndices_two_pow_mul]; simp @[simp] theorem twoPowSum_bitIndices (n : ℕ) : (n.bitIndices.map (fun i ↦ 2 ^ i)).sum = n := by induction' n using binaryRec with b n hs · simp have hrw : (fun i ↦ 2^i) ∘ (fun x ↦ x+1) = fun i ↦ 2 * 2 ^ i := by ext i; simp [pow_add, mul_comm] cases b · simpa [hrw, List.sum_map_mul_left] simp [hrw, List.sum_map_mul_left, hs, add_comm (a := 1)] /-- Together with `Nat.twoPowSum_bitIndices`, this implies a bijection between `ℕ` and `Finset ℕ`. See `Finset.equivBitIndices` for this bijection. -/ theorem bitIndices_twoPowsum {L : List ℕ} (hL : List.Sorted (· < ·) L) : (L.map (fun i ↦ 2^i)).sum.bitIndices = L := by cases L with | nil => simp | cons a L => obtain ⟨haL, hL⟩ := sorted_cons.1 hL simp_rw [Nat.lt_iff_add_one_le] at haL have h' : ∃ (L₀ : List ℕ), L₀.Sorted (· < ·) ∧ L = L₀.map (· + a + 1) := by refine ⟨L.map (· - (a+1)), ?_, ?_⟩ · rwa [Sorted, pairwise_map, Pairwise.and_mem, Pairwise.iff (S := fun x y ↦ x ∈ L ∧ y ∈ L ∧ x < y), ← Pairwise.and_mem] simp only [and_congr_right_iff] exact fun x y hx _ ↦ by rw [tsub_lt_tsub_iff_right (haL _ hx)] have h' : ∀ x ∈ L, ((fun x ↦ x + a + 1) ∘ (fun x ↦ x - (a + 1))) x = x := fun x hx ↦ by simp only [add_assoc, Function.comp_apply]; rw [tsub_add_cancel_of_le (haL _ hx)] simp [List.map_congr_left h'] obtain ⟨L₀, hL₀, rfl⟩ := h' have _ : L₀.length < (a :: (L₀.map (· + a + 1))).length := by simp have hrw : (2^·) ∘ (· + a + 1) = fun i ↦ 2^a * (2 * 2^i) := by ext x; simp only [Function.comp_apply, pow_add, pow_one]; ac_rfl simp only [List.map_cons, List.map_map, List.sum_map_mul_left, List.sum_cons, hrw] nth_rw 1 [← mul_one (a := 2^a)] rw [← mul_add, bitIndices_two_pow_mul, add_comm, bitIndices_two_mul_add_one, bitIndices_twoPowsum hL₀] simp [add_comm (a := 1), add_assoc] termination_by L.length theorem two_pow_le_of_mem_bitIndices (ha : a ∈ n.bitIndices) : 2^a ≤ n := by rw [← twoPowSum_bitIndices n] exact List.single_le_sum (by simp) _ <| mem_map_of_mem ha theorem notMem_bitIndices_self (n : ℕ) : n ∉ n.bitIndices := fun h ↦ (n.lt_two_pow_self).not_ge <| two_pow_le_of_mem_bitIndices h @[deprecated (since := "2025-05-23")] alias not_mem_bitIndices_self := notMem_bitIndices_self end Nat
Functors.lean
/- Copyright (c) 2021 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu, Andrew Yang -/ import Mathlib.Topology.Sheaves.SheafCondition.Sites import Mathlib.CategoryTheory.Sites.Pullback /-! # functors between categories of sheaves Show that the pushforward of a sheaf is a sheaf, and define the pushforward functor from the category of C-valued sheaves on X to that of sheaves on Y, given a continuous map between topological spaces X and Y. ## Main definitions - `TopCat.Sheaf.pushforward`: The pushforward functor between sheaf categories over topological spaces. - `TopCat.Sheaf.pullback`: The pullback functor between sheaf categories over topological spaces. - `TopCat.Sheaf.pullbackPushforwardAdjunction`: The adjunction between pullback and pushforward for sheaves on topological spaces. -/ noncomputable section universe w v u open CategoryTheory open CategoryTheory.Limits open TopologicalSpace open scoped AlgebraicGeometry variable {C : Type u} [Category.{v} C] variable {X Y : TopCat.{w}} (f : X ⟶ Y) variable ⦃ι : Type w⦄ {U : ι → Opens Y} namespace TopCat namespace Sheaf open Presheaf /-- The pushforward of a sheaf (by a continuous map) is a sheaf. -/ theorem pushforward_sheaf_of_sheaf {F : X.Presheaf C} (h : F.IsSheaf) : (f _* F).IsSheaf := (Opens.map f).op_comp_isSheaf _ _ ⟨_, h⟩ variable (C) /-- The pushforward functor. -/ def pushforward (f : X ⟶ Y) : X.Sheaf C ⥤ Y.Sheaf C := (Opens.map f).sheafPushforwardContinuous _ _ _ lemma pushforward_forget (f : X ⟶ Y) : pushforward C f ⋙ forget C Y = forget C X ⋙ Presheaf.pushforward C f := rfl /-- Pushforward of sheaves is isomorphic (actually definitionally equal) to pushforward of presheaves. -/ def pushforwardForgetIso (f : X ⟶ Y) : pushforward C f ⋙ forget C Y ≅ forget C X ⋙ Presheaf.pushforward C f := Iso.refl _ variable {C} @[simp] lemma pushforward_obj_val (f : X ⟶ Y) (F : X.Sheaf C) : ((pushforward C f).obj F).1 = f _* F.1 := rfl @[simp] lemma pushforward_map (f : X ⟶ Y) {F F' : X.Sheaf C} (α : F ⟶ F') : ((pushforward C f).map α).1 = (Presheaf.pushforward C f).map α.1 := rfl variable (A : Type*) [Category.{w} A] {FA : A → A → Type*} {CA : A → Type w} variable [∀ X Y, FunLike (FA X Y) (CA X) (CA Y)] [ConcreteCategory.{w} A FA] [HasColimits A] variable [HasLimits A] [PreservesLimits (CategoryTheory.forget A)] variable [PreservesFilteredColimits (CategoryTheory.forget A)] variable [(CategoryTheory.forget A).ReflectsIsomorphisms] /-- The pullback functor. -/ def pullback (f : X ⟶ Y) : Y.Sheaf A ⥤ X.Sheaf A := (Opens.map f).sheafPullback _ _ _ /-- The pullback of a sheaf is isomorphic (actually definitionally equal) to the sheafification of the pullback as a presheaf. -/ def pullbackIso (f : X ⟶ Y) : pullback A f ≅ forget A Y ⋙ Presheaf.pullback A f ⋙ presheafToSheaf _ _ := Functor.sheafPullbackConstruction.sheafPullbackIso _ _ _ _ /-- The adjunction between pullback and pushforward for sheaves on topological spaces. -/ def pullbackPushforwardAdjunction (f : X ⟶ Y) : pullback A f ⊣ pushforward A f := (Opens.map f).sheafAdjunctionContinuous _ _ _ instance : (pullback A f).IsLeftAdjoint := (pullbackPushforwardAdjunction A f).isLeftAdjoint instance : (pushforward A f).IsRightAdjoint := (pullbackPushforwardAdjunction A f).isRightAdjoint end Sheaf end TopCat
burnside_app.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 div. From mathcomp Require Import choice fintype tuple finfun bigop finset fingroup. From mathcomp Require Import action perm primitive_action ssrAC. (* Application of the Burside formula to count the number of distinct *) (* colorings of the vertices of a square and a cube. *) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Lemma burnside_formula : forall (gT : finGroupType) s (G : {group gT}), uniq s -> s =i G -> forall (sT : finType) (to : {action gT &-> sT}), (#|orbit to G @: setT| * size s)%N = \sum_(p <- s) #|'Fix_to[p]|. Proof. move=> gT s G Us sG sT to. rewrite big_uniq // -(card_uniqP Us) (eq_card sG) -Frobenius_Cauchy. by apply: eq_big => // p _; rewrite setTI. by apply/actsP=> ? _ ?; rewrite !inE. Qed. Arguments burnside_formula {gT}. Section colouring. Variable n : nat. Definition colors := 'I_n. HB.instance Definition _ := Finite.on colors. Section square_colouring. Definition square := 'I_4. HB.instance Definition _ := SubType.on square. HB.instance Definition _ := Finite.on square. Definition mksquare i : square := Sub (i %% _) (ltn_mod i 4). Definition c0 := mksquare 0. Definition c1 := mksquare 1. Definition c2 := mksquare 2. Definition c3 := mksquare 3. (*rotations*) Definition R1 (sc : square) : square := tnth [tuple c1; c2; c3; c0] sc. Definition R2 (sc : square) : square := tnth [tuple c2; c3; c0; c1] sc. Definition R3 (sc : square) : square := tnth [tuple c3; c0; c1; c2] sc. Ltac get_inv elt l := match l with | (_, (elt, ?x)) => x | (elt, ?x) => x | (?x, _) => get_inv elt x end. Definition rot_inv := ((R1, R3), (R2, R2), (R3, R1)). Ltac inj_tac := move: (erefl rot_inv); unfold rot_inv; match goal with |- ?X = _ -> injective ?Y => move=> _; let x := get_inv Y X in apply: (can_inj (g:=x)); move=> [val H1] end. Lemma R1_inj : injective R1. Proof. by inj_tac; repeat (destruct val => //=; first by apply/eqP). Qed. Lemma R2_inj : injective R2. Proof. by inj_tac; repeat (destruct val => //=; first by apply/eqP). Qed. Lemma R3_inj : injective R3. Proof. by inj_tac; repeat (destruct val => //=; first by apply/eqP). Qed. Definition r1 := (perm R1_inj). Definition r2 := (perm R2_inj). Definition r3 := (perm R3_inj). Definition id1 := (1 : {perm square}). Definition is_rot (r : {perm _}) := (r * r1 == r1 * r). Definition rot := [set r | is_rot r]. Lemma group_set_rot : group_set rot. Proof. apply/group_setP; split; first by rewrite /rot inE /is_rot mulg1 mul1g. move=> x1 y; rewrite /rot !inE /= /is_rot; move/eqP => hx1; move/eqP => hy. by rewrite -mulgA hy !mulgA hx1. Qed. Canonical rot_group := Group group_set_rot. Definition rotations := [set id1; r1; r2; r3]. Lemma rot_eq_c0 : forall r s : {perm square}, is_rot r -> is_rot s -> r c0 = s c0 -> r = s. Proof. rewrite /is_rot => r s; move/eqP => hr; move/eqP=> hs hrs; apply/permP => a. have ->: a = (r1 ^+ a) c0 by apply/eqP; case: a; do 4?case=> //=; rewrite ?permM !permE. by rewrite -!permM -!commuteX // !permM hrs. Qed. Lemma rot_r1 : forall r, is_rot r -> r = r1 ^+ (r c0). Proof. move=> r hr; apply: rot_eq_c0 => //; apply/eqP. by symmetry; apply: commuteX. by case: (r c0); do 4?case=> //=; rewrite ?permM !permE /=. Qed. Lemma rotations_is_rot : forall r, r \in rotations -> is_rot r. Proof. move=> r Dr; apply/eqP; apply/permP => a; rewrite !inE -!orbA !permM in Dr *. by case/or4P: Dr; move/eqP->; rewrite !permE //; case: a; do 4?case. Qed. Lemma rot_is_rot : rot = rotations. Proof. apply/setP=> r; apply/idP/idP => [|/rotations_is_rot] /[!inE]// h. have -> : r = r1 ^+ (r c0) by apply: rot_eq_c0; rewrite // -rot_r1. have e2: 2 = r2 c0 by rewrite permE /=. have e3: 3 = r3 c0 by rewrite permE /=. case (r c0); do 4?[case] => // ?; rewrite ?(expg1, eqxx, orbT) //. by rewrite [nat_of_ord _]/= e2 -rot_r1 ?(eqxx, orbT, rotations_is_rot, inE). by rewrite [nat_of_ord _]/= e3 -rot_r1 ?(eqxx, orbT, rotations_is_rot, inE). Qed. (*symmetries*) Definition Sh (sc : square) : square := tnth [tuple c1; c0; c3; c2] sc. Lemma Sh_inj : injective Sh. Proof. by apply: (can_inj (g:= Sh)); case; do 4?case=> //=; move=> H; apply/eqP. Qed. Definition sh := (perm Sh_inj). Lemma sh_inv : sh^-1 = sh. Proof. apply: (mulIg sh); rewrite mulVg; apply/permP. by case; do 4?case=> //=; move=> H; rewrite !permE /= !permE; apply/eqP. Qed. Definition Sv (sc : square) : square := tnth [tuple c3; c2; c1; c0] sc. Lemma Sv_inj : injective Sv. Proof. by apply: (can_inj (g:= Sv)); case; do 4?case=> //=; move=> H; apply/eqP. Qed. Definition sv := (perm Sv_inj). Lemma sv_inv : sv^-1 = sv. Proof. apply: (mulIg sv); rewrite mulVg; apply/permP. by case; do 4?case=> //=; move=> H; rewrite !permE /= !permE; apply/eqP. Qed. Definition Sd1 (sc : square) : square := tnth [tuple c0; c3; c2; c1] sc. Lemma Sd1_inj : injective Sd1. Proof. by apply: can_inj Sd1 _; case; do 4?case=> //=; move=> H; apply/eqP. Qed. Definition sd1 := (perm Sd1_inj). Lemma sd1_inv : sd1^-1 = sd1. Proof. apply: (mulIg sd1); rewrite mulVg; apply/permP. by case; do 4?case=> //=; move=> H; rewrite !permE /= !permE; apply/eqP. Qed. Definition Sd2 (sc : square) : square := tnth [tuple c2; c1; c0; c3] sc. Lemma Sd2_inj : injective Sd2. Proof. by apply: can_inj Sd2 _; case; do 4?case=> //=; move=> H; apply/eqP. Qed. Definition sd2 := (perm Sd2_inj). Lemma sd2_inv : sd2^-1 = sd2. Proof. apply: (mulIg sd2); rewrite mulVg; apply/permP. by case; do 4?case=> //=; move=> H; rewrite !permE /= !permE; apply/eqP. Qed. Lemma ord_enum4 : enum 'I_4 = [:: c0; c1; c2; c3]. Proof. by apply: (inj_map val_inj); rewrite val_enum_ord. Qed. Lemma diff_id_sh : 1 != sh. Proof. by apply/eqP; move/(congr1 (fun p : {perm square} => p c0)); rewrite !permE. Qed. Definition isometries2 := [set 1; sh]. Lemma card_iso2 : #|isometries2| = 2. Proof. by rewrite cards2 diff_id_sh. Qed. Lemma group_set_iso2 : group_set isometries2. Proof. apply/group_setP; split => [|x y]; rewrite !inE ?eqxx //. do 2![case/orP; move/eqP->]; rewrite ?(mul1g, mulg1) ?eqxx ?orbT//. by rewrite -/sh -{1}sh_inv mulVg eqxx. Qed. Canonical iso2_group := Group group_set_iso2. Definition isometries := [set p | [|| p == 1, p == r1, p == r2, p == r3, p == sh, p == sv, p == sd1 | p == sd2 ]]. Definition opp (sc : square) := tnth [tuple c2; c3; c0; c1] sc. Definition is_iso (p : {perm square}) := forall ci, p (opp ci) = opp (p ci). Lemma isometries_iso : forall p, p \in isometries -> is_iso p. Proof. move=> p; rewrite inE. by do ?case/orP; move/eqP=> -> a; rewrite !permE; case: a; do 4?case. Qed. Ltac non_inj p a1 a2 heq1 heq2 := let h1:= fresh "h1" in (absurd (p a1 = p a2); first (by red => - h1; move: (perm_inj h1)); by rewrite heq1 heq2; apply/eqP). Ltac is_isoPtac p f e0 e1 e2 e3 := suff ->: p = f by [rewrite inE eqxx ?orbT]; let e := fresh "e" in apply/permP; (do 5?[case] => // ?; [move: e0 | move: e1 | move: e2 | move: e3]) => e; apply: etrans (congr1 p _) (etrans e _); apply/eqP; rewrite // permE. Lemma is_isoP : forall p, reflect (is_iso p) (p \in isometries). Proof. move=> p; apply: (iffP idP) => [|iso_p]; first exact: isometries_iso. move e1: (p c1) (iso_p c1) => k1; move e0: (p c0) (iso_p c0) k1 e1 => k0. case: k0 e0; do 4?[case] => //= ? e0 e2; do 5?[case] => //= ? e1 e3; try by [non_inj p c0 c1 e0 e1 | non_inj p c0 c3 e0 e3]. by is_isoPtac p id1 e0 e1 e2 e3. by is_isoPtac p sd1 e0 e1 e2 e3. by is_isoPtac p sh e0 e1 e2 e3. by is_isoPtac p r1 e0 e1 e2 e3. by is_isoPtac p sd2 e0 e1 e2 e3. by is_isoPtac p r2 e0 e1 e2 e3. by is_isoPtac p r3 e0 e1 e2 e3. by is_isoPtac p sv e0 e1 e2 e3. Qed. Lemma group_set_iso : group_set isometries. Proof. apply/group_setP; split; first by rewrite inE eqxx /=. by move=> x y hx hy; apply/is_isoP => ci; rewrite !permM !isometries_iso. Qed. Canonical iso_group := Group group_set_iso. Lemma card_rot : #|rot| = 4. Proof. rewrite -[4]/(size [:: id1; r1; r2; r3]) -(card_uniqP _). by apply: eq_card => x; rewrite rot_is_rot !inE -!orbA. by apply: map_uniq (fun p : {perm square} => p c0) _ _; rewrite /= !permE. Qed. Lemma group_set_rotations : group_set rotations. Proof. by rewrite -rot_is_rot group_set_rot. Qed. Canonical rotations_group := Group group_set_rotations. Notation col_squares := {ffun square -> colors}. Definition act_f (sc : col_squares) (p : {perm square}) : col_squares := [ffun z => sc (p^-1 z)]. Lemma act_f_1 : forall k, act_f k 1 = k. Proof. by move=> k; apply/ffunP=> a; rewrite ffunE invg1 permE. Qed. Lemma act_f_morph : forall k x y, act_f k (x * y) = act_f (act_f k x) y. Proof. by move=> k x y; apply/ffunP=> a; rewrite !ffunE invMg permE. Qed. Definition to := TotalAction act_f_1 act_f_morph. Definition square_coloring_number2 := #|orbit to isometries2 @: setT|. Definition square_coloring_number4 := #|orbit to rotations @: setT|. Definition square_coloring_number8 := #|orbit to isometries @: setT|. Lemma Fid : 'Fix_to(1) = setT. Proof. by apply/setP=> x /=; rewrite in_setT; apply/afix1P; apply: act1. Qed. Lemma card_Fid : #|'Fix_to(1)| = (n ^ 4)%N. Proof. rewrite -[4]card_ord -[n]card_ord -card_ffun_on Fid cardsE. by symmetry; apply: eq_card => f; apply/ffun_onP. Qed. Definition coin0 (sc : col_squares) : colors := sc c0. Definition coin1 (sc : col_squares) : colors := sc c1. Definition coin2 (sc : col_squares) : colors := sc c2. Definition coin3 (sc : col_squares) : colors := sc c3. Lemma eqperm_map : forall p1 p2 : col_squares, (p1 == p2) = all (fun s => p1 s == p2 s) [:: c0; c1; c2; c3]. Proof. move=> p1 p2; apply/eqP/allP=> [-> // | Ep12]; apply/ffunP=> x. by apply/eqP; apply Ep12; case: x; do 4!case=> //. Qed. Lemma F_Sh : 'Fix_to[sh] = [set x | (coin0 x == coin1 x) && (coin2 x == coin3 x)]. Proof. apply/setP=> x; rewrite (sameP afix1P eqP) !inE eqperm_map /=. rewrite /act_f sh_inv !ffunE !permE /=. by rewrite eq_sym (eq_sym (x c3)) andbT andbA !andbb. Qed. Lemma F_Sv : 'Fix_to[sv] = [set x | (coin0 x == coin3 x) && (coin2 x == coin1 x)]. Proof. apply/setP=> x; rewrite (sameP afix1P eqP) !inE eqperm_map /=. rewrite /act_f sv_inv !ffunE !permE /=. by rewrite eq_sym andbT andbC (eq_sym (x c1)) andbA -andbA !andbb andbC. Qed. Ltac inv_tac := apply: esym (etrans _ (mul1g _)); apply: canRL (mulgK _) _; let a := fresh "a" in apply/permP => a; apply/eqP; rewrite permM !permE; case: a; do 4?case. Lemma r1_inv : r1^-1 = r3. Proof. by inv_tac. Qed. Lemma r2_inv : r2^-1 = r2. Proof. by inv_tac. Qed. Lemma r3_inv : r3^-1 = r1. Proof. by inv_tac. Qed. Lemma F_r2 : 'Fix_to[r2] = [set x | (coin0 x == coin2 x) && (coin1 x == coin3 x)]. Proof. apply/setP=> x; rewrite (sameP afix1P eqP) !inE eqperm_map /=. rewrite /act_f r2_inv !ffunE !permE /=. by rewrite eq_sym andbT andbCA andbC (eq_sym (x c3)) andbA -andbA !andbb andbC. Qed. Lemma F_r1 : 'Fix_to[r1] = [set x | (coin0 x == coin1 x)&&(coin1 x == coin2 x)&&(coin2 x == coin3 x)]. Proof. apply/setP=> x; rewrite (sameP afix1P eqP) !inE eqperm_map /=. rewrite /act_f r1_inv !ffunE !permE andbC. by do 3![case E: {+}(_ == _); rewrite // {E}(eqP E)]; rewrite eqxx. Qed. Lemma F_r3 : 'Fix_to[r3] = [set x | (coin0 x == coin1 x)&&(coin1 x == coin2 x)&&(coin2 x == coin3 x)]. Proof. apply/setP=> x; rewrite (sameP afix1P eqP) !inE eqperm_map /=. rewrite /act_f r3_inv !ffunE !permE /=. by do 3![case: eqVneq=> // <-]. Qed. Lemma card_n2 : forall x y z t : square, uniq [:: x; y; z; t] -> #|[set p : col_squares | (p x == p y) && (p z == p t)]| = (n ^ 2)%N. Proof. move=> x y z t Uxt; rewrite -[n]card_ord. pose f (p : col_squares) := (p x, p z); rewrite -(@card_in_image _ _ f). rewrite -mulnn -card_prod; apply: eq_card => [] [c d] /=; apply/imageP. rewrite (cat_uniq [::x; y]) in Uxt; case/and3P: Uxt => _. rewrite /= !orbF !andbT => /norP[] /[!inE] nxzt nyzt _. exists [ffun i => if pred2 x y i then c else d]. by rewrite inE !ffunE /= !eqxx orbT (negbTE nxzt) (negbTE nyzt) !eqxx. by rewrite {}/f !ffunE /= eqxx (negbTE nxzt). move=> p1 p2 /[!inE] /andP[p1y p1t] /andP[p2y p2t] [px pz]. have eqp12: all (fun i => p1 i == p2 i) [:: x; y; z; t]. by rewrite /= -(eqP p1y) -(eqP p1t) -(eqP p2y) -(eqP p2t) px pz !eqxx. apply/ffunP=> i; apply/eqP; apply: (allP eqp12). by rewrite (subset_cardP _ (subset_predT _)) // (card_uniqP Uxt) card_ord. Qed. Lemma card_n : #|[set x | (coin0 x == coin1 x)&&(coin1 x == coin2 x)&& (coin2 x == coin3 x)]| = n. Proof. rewrite -[n]card_ord /coin0 /coin1 /coin2 /coin3. pose f (p : col_squares) := p c3; rewrite -(@card_in_image _ _ f). apply: eq_card => c /=; apply/imageP. exists ([ffun => c] : col_squares); last by rewrite /f ffunE. by rewrite /= inE !ffunE !eqxx. move=> p1 p2; rewrite /= !inE /f -!andbA => eqp1 eqp2 eqp12. apply/eqP; rewrite eqperm_map /= andbT. case/and3P: eqp1; do 3!move/eqP->; case/and3P: eqp2; do 3!move/eqP->. by rewrite !andbb eqp12. Qed. Lemma burnside_app2 : (square_coloring_number2 * 2 = n ^ 4 + n ^ 2)%N. Proof. rewrite (burnside_formula [:: id1; sh]) => [||p]; last first. - by rewrite !inE. - by rewrite /= inE diff_id_sh. by rewrite 2!big_cons big_nil addn0 {1}card_Fid F_Sh card_n2. Qed. Lemma burnside_app_rot : (square_coloring_number4 * 4 = n ^ 4 + n ^ 2 + 2 * n)%N. Proof. rewrite (burnside_formula [:: id1; r1; r2; r3]) => [||p]; last first. - by rewrite !inE !orbA. - by apply: map_uniq (fun p : {perm square} => p c0) _ _; rewrite /= !permE. rewrite !big_cons big_nil /= addn0 {1}card_Fid F_r1 F_r2 F_r3. by rewrite card_n card_n2 //= [n + _]addnC !addnA addn0. Qed. Lemma F_Sd1 : 'Fix_to[sd1] = [set x | coin1 x == coin3 x]. Proof. apply/setP => x; rewrite (sameP afix1P eqP) !inE eqperm_map /=. rewrite /act_f sd1_inv !ffunE !permE /=. by rewrite !eqxx !andbT eq_sym /= andbb. Qed. Lemma card_n3 : forall x y : square, x != y -> #|[set k : col_squares | k x == k y]| = (n ^ 3)%N. Proof. move=> x y nxy; apply/eqP; case: (posnP n) => [n0|]. by rewrite n0; apply/existsP=> [] [p _]; case: (p c0) => i; rewrite n0. move/eqn_pmul2l <-; rewrite -expnS -card_Fid Fid cardsT. rewrite -{1}[n]card_ord -cardX. pose pk k := [ffun i => k (if i == y then x else i) : colors]. rewrite -(@card_image _ _ (fun k : col_squares => (k y, pk k))). apply/eqP; apply: eq_card => ck /=; rewrite inE /= [_ \in _]inE. apply/eqP/imageP; last first. by case=> k _ -> /=; rewrite !ffunE if_same eqxx. case: ck => c k /= kxy. exists [ffun i => if i == y then c else k i]; first by rewrite inE. rewrite !ffunE eqxx; congr (_, _); apply/ffunP=> i; rewrite !ffunE. case Eiy: (i == y); last by rewrite Eiy. by rewrite (negbTE nxy) (eqP Eiy). move=> k1 k2 [Eky Epk]; apply/ffunP=> i. have{Epk}: pk k1 i = pk k2 i by rewrite Epk. by rewrite !ffunE; case: eqP => // ->. Qed. Lemma F_Sd2 : 'Fix_to[sd2] = [set x | coin0 x == coin2 x]. Proof. apply/setP => x; rewrite (sameP afix1P eqP) !inE eqperm_map /=. by rewrite /act_f sd2_inv !ffunE !permE /= !eqxx !andbT eq_sym /= andbb. Qed. Lemma burnside_app_iso : (square_coloring_number8 * 8 = n ^ 4 + 2 * n ^ 3 + 3 * n ^ 2 + 2 * n)%N. Proof. pose iso_list := [:: id1; r1; r2; r3; sh; sv; sd1; sd2]. rewrite (burnside_formula iso_list) => [||p]; last first. - by rewrite /= !inE. - apply: map_uniq (fun p : {perm square} => (p c0, p c1)) _ _. by rewrite /= !permE. rewrite !big_cons big_nil {1}card_Fid F_r1 F_r2 F_r3 F_Sh F_Sv F_Sd1 F_Sd2. rewrite card_n !card_n3 // !card_n2 //= !addnA !addn0. by rewrite [LHS]addn.[ACl 1 * 7 * 8 * 3 * 5 * 6 * 2 * 4]. Qed. End square_colouring. Section cube_colouring. Definition cube := 'I_6. HB.instance Definition _ := SubType.on cube. HB.instance Definition _ := Finite.on cube. Definition mkFcube i : cube := Sub (i %% 6) (ltn_mod i 6). Definition F0 := mkFcube 0. Definition F1 := mkFcube 1. Definition F2 := mkFcube 2. Definition F3 := mkFcube 3. Definition F4 := mkFcube 4. Definition F5 := mkFcube 5. (* axial symetries*) Definition S05 := [:: F0; F4; F3; F2; F1; F5]. Definition S05f (sc : cube) : cube := tnth [tuple of S05] sc. Definition S14 := [:: F5; F1; F3; F2; F4; F0]. Definition S14f (sc : cube) : cube := tnth [tuple of S14] sc. Definition S23 := [:: F5; F4; F2; F3; F1; F0]. Definition S23f (sc : cube) : cube := tnth [tuple of S23] sc. (* rotations 90 *) Definition R05 := [:: F0; F2; F4; F1; F3; F5]. Definition R05f (sc : cube) : cube := tnth [tuple of R05] sc. Definition R50 := [:: F0; F3; F1; F4; F2; F5]. Definition R50f (sc : cube) : cube := tnth [tuple of R50] sc. Definition R14 := [:: F3; F1; F0; F5; F4; F2]. Definition R14f (sc : cube) : cube := tnth [tuple of R14] sc. Definition R41 := [:: F2; F1; F5; F0; F4; F3]. Definition R41f (sc : cube) : cube := tnth [tuple of R41] sc. Definition R23 := [:: F1; F5; F2; F3; F0; F4]. Definition R23f (sc : cube) : cube := tnth [tuple of R23] sc. Definition R32 := [:: F4; F0; F2; F3; F5; F1]. Definition R32f (sc : cube) : cube := tnth [tuple of R32] sc. (* rotations 120 *) Definition R024 := [:: F2; F5; F4; F1; F0; F3]. Definition R024f (sc : cube) : cube := tnth [tuple of R024] sc. Definition R042 := [:: F4; F3; F0; F5; F2; F1]. Definition R042f (sc : cube) : cube := tnth [tuple of R042] sc. Definition R012 := [:: F1; F2; F0; F5; F3; F4]. Definition R012f (sc : cube) : cube := tnth [tuple of R012] sc. Definition R021 := [:: F2; F0; F1; F4; F5; F3]. Definition R021f (sc : cube) : cube := tnth [tuple of R021] sc. Definition R031 := [:: F3; F0; F4; F1; F5; F2]. Definition R031f (sc : cube) : cube := tnth [tuple of R031] sc. Definition R013 := [:: F1; F3; F5; F0; F2; F4]. Definition R013f (sc : cube) : cube := tnth [tuple of R013] sc. Definition R043 := [:: F4; F2; F5; F0; F3; F1]. Definition R043f (sc : cube) : cube := tnth [tuple of R043] sc. Definition R034 := [:: F3; F5; F1; F4; F0; F2]. Definition R034f (sc : cube) : cube := tnth [tuple of R034] sc. (* last symmetries*) Definition S1 := [:: F5; F2; F1; F4; F3; F0]. Definition S1f (sc : cube) : cube := tnth [tuple of S1] sc. Definition S2 := [:: F5; F3; F4; F1; F2; F0]. Definition S2f (sc : cube) : cube := tnth [tuple of S2] sc. Definition S3 := [:: F1; F0; F3; F2; F5; F4]. Definition S3f (sc : cube) : cube := tnth [tuple of S3] sc. Definition S4 := [:: F4; F5; F3; F2; F0; F1]. Definition S4f (sc : cube) : cube := tnth [tuple of S4] sc. Definition S5 := [:: F2; F4; F0; F5; F1; F3]. Definition S5f (sc : cube) : cube := tnth [tuple of S5] sc. Definition S6 := [::F3; F4; F5; F0; F1; F2]. Definition S6f (sc : cube) : cube := tnth [tuple of S6] sc. Lemma S1_inv : involutive S1f. Proof. by move=> z; apply/eqP; case: z; do 6?case. Qed. Lemma S2_inv : involutive S2f. Proof. by move=> z; apply/eqP; case: z; do 6?case. Qed. Lemma S3_inv : involutive S3f. Proof. by move=> z; apply/eqP; case: z; do 6?case. Qed. Lemma S4_inv : involutive S4f. Proof. by move=> z; apply/eqP; case: z; do 6?case. Qed. Lemma S5_inv : involutive S5f. Proof. by move=> z; apply/eqP; case: z; do 6?case. Qed. Lemma S6_inv : involutive S6f. Proof. by move=> z; apply/eqP; case: z; do 6?case. Qed. Lemma S05_inj : injective S05f. Proof. by apply: can_inj S05f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma S14_inj : injective S14f. Proof. by apply: can_inj S14f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma S23_inv : involutive S23f. Proof. by move=> z; apply/eqP; case: z; do 6?case. Qed. Lemma R05_inj : injective R05f. Proof. by apply: can_inj R50f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R14_inj : injective R14f. Proof. by apply: can_inj R41f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R23_inj : injective R23f. Proof. by apply: can_inj R32f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R50_inj : injective R50f. Proof. by apply: can_inj R05f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R41_inj : injective R41f. Proof. by apply: can_inj R14f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R32_inj : injective R32f. Proof. by apply: can_inj R23f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R024_inj : injective R024f. Proof. by apply: can_inj R042f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R042_inj : injective R042f. Proof. by apply: can_inj R024f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R012_inj : injective R012f. Proof. by apply: can_inj R021f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R021_inj : injective R021f. Proof. by apply: can_inj R012f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R031_inj : injective R031f. Proof. by apply: can_inj R013f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R013_inj : injective R013f. Proof. by apply: can_inj R031f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R043_inj : injective R043f. Proof. by apply: can_inj R034f _ => z; apply/eqP; case: z; do 6?case. Qed. Lemma R034_inj : injective R034f. Proof. by apply: can_inj R043f _ => z; apply/eqP; case: z; do 6?case. Qed. Definition id3 := 1 : {perm cube}. Definition s05 := (perm S05_inj). Definition s14 : {perm cube}. Proof. apply: (@perm _ S14f); apply: can_inj S14f _ => z. by apply/eqP; case: z; do 6?case. Defined. Definition s23 := (perm (inv_inj S23_inv)). Definition r05 := (perm R05_inj). Definition r14 := (perm R14_inj). Definition r23 := (perm R23_inj). Definition r50 := (perm R50_inj). Definition r41 := (perm R41_inj). Definition r32 := (perm R32_inj). Definition r024 := (perm R024_inj). Definition r042 := (perm R042_inj). Definition r012 := (perm R012_inj). Definition r021 := (perm R021_inj). Definition r031 := (perm R031_inj). Definition r013 := (perm R013_inj). Definition r043 := (perm R043_inj). Definition r034 := (perm R034_inj). Definition s1 := (perm (inv_inj S1_inv)). Definition s2 := (perm (inv_inj S2_inv)). Definition s3 := (perm (inv_inj S3_inv)). Definition s4 := (perm (inv_inj S4_inv)). Definition s5 := (perm (inv_inj S5_inv)). Definition s6 := (perm (inv_inj S6_inv)). Definition dir_iso3 := [set p | [|| id3 == p, s05 == p, s14 == p, s23 == p, r05 == p, r14 == p, r23 == p, r50 == p, r41 == p, r32 == p, r024 == p, r042 == p, r012 == p, r021 == p, r031 == p, r013 == p, r043 == p, r034 == p, s1 == p, s2 == p, s3 == p, s4 == p, s5 == p | s6 == p]]. Definition dir_iso3l := [:: id3; s05; s14; s23; r05; r14; r23; r50; r41; r32; r024; r042; r012; r021; r031; r013; r043; r034; s1; s2; s3; s4; s5; s6]. Definition S0 := [:: F5; F4; F3; F2; F1; F0]. Definition S0f (sc : cube) : cube := tnth [tuple of S0] sc. Lemma S0_inv : involutive S0f. Proof. by move=> z; apply/eqP; case: z; do 6?case. Qed. Definition s0 := (perm (inv_inj S0_inv)). Definition is_iso3 (p : {perm cube}) := forall fi, p (s0 fi) = s0 (p fi). Lemma dir_iso_iso3 : forall p, p \in dir_iso3 -> is_iso3 p. Proof. move=> p; rewrite inE. by do ?case/orP; move/eqP=> <- a; rewrite !permE; case: a; do 6?case. Qed. Lemma iso3_ndir : forall p, p \in dir_iso3 -> is_iso3 (s0 * p). Proof. move=> p; rewrite inE. by do ?case/orP; move/eqP=> <- a; rewrite !(permM, permE); case: a; do 6?case. Qed. Definition sop (p : {perm cube}) : seq cube := fgraph (val p). Lemma sop_inj : injective sop. Proof. by move=> p1 p2 /val_inj/(can_inj fgraphK)/val_inj. Qed. Definition prod_tuple (t1 t2 : seq cube) := map (fun n : 'I_6 => nth F0 t2 n) t1. Lemma sop_spec x (n0 : 'I_6): nth F0 (sop x) n0 = x n0. Proof. by rewrite nth_fgraph_ord pvalE. Qed. Lemma prod_t_correct : forall (x y : {perm cube}) (i : cube), (x * y) i = nth F0 (prod_tuple (sop x) (sop y)) i. Proof. move=> x y i; rewrite permM -!sop_spec [RHS](nth_map F0) // size_tuple /=. by rewrite card_ord ltn_ord. Qed. Lemma sop_morph : {morph sop : x y / x * y >-> prod_tuple x y}. Proof. move=> x y; apply: (@eq_from_nth _ F0) => [|/= i]. by rewrite size_map !size_tuple. rewrite size_tuple card_ord => lti6. by rewrite -[i]/(val (Ordinal lti6)) sop_spec -prod_t_correct. Qed. Definition ecubes : seq cube := [:: F0; F1; F2; F3; F4; F5]. Lemma ecubes_def : ecubes = enum (@predT cube). Proof. by apply: (inj_map val_inj); rewrite val_enum_ord. Qed. Definition seq_iso_L := [:: [:: F0; F1; F2; F3; F4; F5]; S05; S14; S23; R05; R14; R23; R50; R41; R32; R024; R042; R012; R021; R031; R013; R043; R034; S1; S2; S3; S4; S5; S6]. Lemma seqs1 : forall f injf, sop (@perm _ f injf) = map f ecubes. Proof. move=> f ?; rewrite ecubes_def /sop /= -codom_ffun pvalE. by apply: eq_codom; apply: permE. Qed. Lemma Lcorrect : seq_iso_L == map sop [:: id3; s05; s14; s23; r05; r14; r23; r50; r41; r32; r024; r042; r012; r021; r031; r013; r043; r034; s1; s2; s3; s4; s5; s6]. Proof. by rewrite /= !seqs1. Qed. Lemma iso0_1 : dir_iso3 =i dir_iso3l. Proof. by move=> p; rewrite /= !inE /= -!(eq_sym p). Qed. Lemma L_iso : forall p, (p \in dir_iso3) = (sop p \in seq_iso_L). Proof. by move=> p; rewrite (eqP Lcorrect) mem_map ?iso0_1 //; apply: sop_inj. Qed. Lemma stable : forall x y, x \in dir_iso3 -> y \in dir_iso3 -> x * y \in dir_iso3. Proof. move=> x y; rewrite !L_iso sop_morph => Hx Hy. by move/sop: y Hy; apply/allP; move/sop: x Hx; apply/allP; vm_compute. Qed. Lemma iso_eq_F0_F1 : forall r s : {perm cube}, r \in dir_iso3 -> s \in dir_iso3 -> r F0 = s F0 -> r F1 = s F1 -> r = s. Proof. move=> r s; rewrite !L_iso => hr hs hrs0 hrs1; apply: sop_inj; apply/eqP. move/eqP: hrs0; apply/implyP; move/eqP: hrs1; apply/implyP; rewrite -!sop_spec. by move/sop: r hr; apply/allP; move/sop: s hs; apply/allP; vm_compute. Qed. Lemma ndir_s0p : forall p, p \in dir_iso3 -> s0 * p \notin dir_iso3. Proof. move=> p; rewrite !L_iso sop_morph seqs1. by move/sop: p; apply/allP; vm_compute. Qed. Definition indir_iso3l := map (mulg s0) dir_iso3l. Definition iso3l := dir_iso3l ++ indir_iso3l. Definition seq_iso3_L := map sop iso3l. Lemma eqperm : forall p1 p2 : {perm cube}, (p1 == p2) = all (fun s => p1 s == p2 s) ecubes. Proof. move=> p1 p2; apply/eqP/allP=> [-> // | Ep12]; apply/permP=> x. by apply/eqP; rewrite Ep12 // ecubes_def mem_enum. Qed. Lemma iso_eq_F0_F1_F2 : forall r s : {perm cube}, is_iso3 r -> is_iso3 s -> r F0 = s F0 -> r F1 = s F1 -> r F2 = s F2 -> r = s. Proof. move=> r s hr hs hrs0 hrs1 hrs2. have:= hrs0; have:= hrs1; have:= hrs2. have e23: F2 = s0 F3 by apply/eqP; rewrite permE /S0f (tnth_nth F0). have e14: F1 = s0 F4 by apply/eqP; rewrite permE /S0f (tnth_nth F0). have e05: F0 = s0 F5 by apply/eqP; rewrite permE /S0f (tnth_nth F0). rewrite e23 e14 e05; rewrite !hr !hs. move/perm_inj=> hrs3; move/perm_inj=> hrs4; move/perm_inj=> hrs5. by apply/eqP; rewrite eqperm /= hrs0 hrs1 hrs2 hrs3 hrs4 hrs5 !eqxx. Qed. Ltac iso_tac := let a := fresh "a" in apply/permP => a; apply/eqP; rewrite !permM !permE; case: a; do 6?case. Ltac inv_tac := apply: esym (etrans _ (mul1g _)); apply: canRL (mulgK _) _; iso_tac. Lemma dir_s0p : forall p, (s0 * p) \in dir_iso3 -> p \notin dir_iso3. Proof. move=> p Hs0p; move: (ndir_s0p Hs0p); rewrite mulgA. have e: (s0^-1=s0) by inv_tac. by rewrite -{1}e mulVg mul1g. Qed. Definition is_iso3b p := (p * s0 == s0 * p). Definition iso3 := [set p | is_iso3b p]. Lemma is_iso3P : forall p, reflect (is_iso3 p) (p \in iso3). Proof. move=> p; apply: (iffP idP); rewrite inE /iso3 /is_iso3b /is_iso3 => e. by move=> fi; rewrite -!permM (eqP e). by apply/eqP; apply/permP=> z; rewrite !permM (e z). Qed. Lemma group_set_iso3 : group_set iso3. Proof. apply/group_setP; split. by apply/is_iso3P => fi; rewrite -!permM mulg1 mul1g. move=> x1 y; rewrite /iso3 !inE /= /is_iso3. rewrite /is_iso3b. rewrite -mulgA. move/eqP => hx1; move/eqP => hy. rewrite hy !mulgA. by rewrite -hx1. Qed. Canonical iso_group3 := Group group_set_iso3. Lemma group_set_diso3 : group_set dir_iso3. Proof. apply/group_setP; split; first by rewrite inE eqxx /=. by apply: stable. Qed. Canonical diso_group3 := Group group_set_diso3. Lemma gen_diso3 : dir_iso3 = <<[set r05; r14]>>. Proof. apply/setP/subset_eqP/andP; split; first last. rewrite gen_subG; apply/subsetP. by move=> x /[!inE] /orP[] /eqP->; rewrite !eqxx !orbT. apply/subsetP => x /[!inE]. have -> : s05 = r05 * r05 by iso_tac. have -> : s14 = r14 * r14 by iso_tac. have -> : s23 = r14 * r14 * r05 * r05 by iso_tac. have -> : r23 = r05 * r14 * r05 * r14 * r14 by iso_tac. have -> : r50 = r05 * r05 * r05 by iso_tac. have -> : r41 = r14 * r14 * r14 by iso_tac. have -> : r32 = r14 * r14 * r14 * r05* r14 by iso_tac. have -> : r024 = r05 * r14 * r14 * r14 by iso_tac. have -> : r042 = r14 * r05 * r05 * r05 by iso_tac. have -> : r012 = r14 * r05 by iso_tac. have -> : r021 = r05 * r14 * r05 * r05 by iso_tac. have -> : r031 = r05 * r14 by iso_tac. have -> : r013 = r05 * r05 * r14 * r05 by iso_tac. have -> : r043 = r14 * r14 * r14 * r05 by iso_tac. have -> : r034 = r05 * r05 * r05 * r14 by iso_tac. have -> : s1 = r14 * r14 * r05 by iso_tac. have -> : s2 = r05 * r14 * r14 by iso_tac. have -> : s3 = r05 * r14 * r05 by iso_tac. have -> : s4 = r05 * r14 * r14 * r14 * r05 by iso_tac. have -> : s5 = r14 * r05 * r05 by iso_tac. have -> : s6 = r05 * r05 * r14 by iso_tac. by do ?case/predU1P=> [<-|]; first exact: group1; last (move/eqP<-); rewrite ?groupMl ?mem_gen // !inE eqxx ?orbT. Qed. Notation col_cubes := {ffun cube -> colors}. Definition act_g (sc : col_cubes) (p : {perm cube}) : col_cubes := [ffun z => sc (p^-1 z)]. Lemma act_g_1 : forall k, act_g k 1 = k. Proof. by move=> k; apply/ffunP=> a; rewrite ffunE invg1 permE. Qed. Lemma act_g_morph : forall k x y, act_g k (x * y) = act_g (act_g k x) y. Proof. by move=> k x y; apply/ffunP=> a; rewrite !ffunE invMg permE. Qed. Definition to_g := TotalAction act_g_1 act_g_morph. Definition cube_coloring_number24 := #|orbit to_g diso_group3 @: setT|. Lemma Fid3 : 'Fix_to_g[1] = setT. Proof. by apply/setP=> x /=; rewrite (sameP afix1P eqP) !inE act1 eqxx. Qed. Lemma card_Fid3 : #|'Fix_to_g[1]| = (n ^ 6)%N. Proof. rewrite -[6]card_ord -[n]card_ord -card_ffun_on Fid3 cardsT. by symmetry; apply: eq_card => ff; apply/ffun_onP. Qed. Definition col0 (sc : col_cubes) : colors := sc F0. Definition col1 (sc : col_cubes) : colors := sc F1. Definition col2 (sc : col_cubes) : colors := sc F2. Definition col3 (sc : col_cubes) : colors := sc F3. Definition col4 (sc : col_cubes) : colors := sc F4. Definition col5 (sc : col_cubes) : colors := sc F5. Lemma eqperm_map2 : forall p1 p2 : col_cubes, (p1 == p2) = all (fun s => p1 s == p2 s) [:: F0; F1; F2; F3; F4; F5]. Proof. move=> p1 p2; apply/eqP/allP=> [-> // | Ep12]; apply/ffunP=> x. by apply/eqP; apply Ep12; case: x; do 6?case. Qed. Notation infE := (sameP afix1P eqP). Lemma F_s05 : 'Fix_to_g[s05] = [set x | (col1 x == col4 x) && (col2 x == col3 x)]. Proof. have s05_inv: s05^-1=s05 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s05_inv !ffunE !permE /=. apply sym_equal; rewrite !eqxx /= andbT/col1/col2/col3/col4/col5/col0. by do 2![rewrite eq_sym; case: {+}(_ == _)=> //= ]. Qed. Lemma F_s14 : 'Fix_to_g[s14]= [set x | (col0 x == col5 x) && (col2 x == col3 x)]. Proof. have s14_inv: s14^-1=s14 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s14_inv !ffunE !permE /=. apply sym_equal; rewrite !eqxx /= andbT/col1/col2/col3/col4/col5/col0. by do 2![rewrite eq_sym; case: {+}(_ == _)=> //= ]. Qed. Lemma r05_inv : r05^-1 = r50. Proof. by inv_tac. Qed. Lemma r50_inv : r50^-1 = r05. Proof. by inv_tac. Qed. Lemma r14_inv : r14^-1 = r41. Proof. by inv_tac. Qed. Lemma r41_inv : r41^-1 = r14. Proof. by inv_tac. Qed. Lemma s23_inv : s23^-1 = s23. Proof. by inv_tac. Qed. Lemma F_s23 : 'Fix_to_g[s23] = [set x | (col0 x == col5 x) && (col1 x == col4 x)]. Proof. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s23_inv !ffunE !permE /=. apply sym_equal; rewrite !eqxx /= andbT/col1/col2/col3/col4/col5/col0. by do 2![rewrite eq_sym; case: {+}(_ == _)=> //=]. Qed. Lemma F_r05 : 'Fix_to_g[r05]= [set x | (col1 x == col2 x) && (col2 x == col3 x) && (col3 x == col4 x)]. Proof. apply sym_equal. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r05_inv !ffunE !permE /=. rewrite !eqxx /= !andbT /col1/col2/col3/col4/col5/col0. by do 3![case: eqVneq; rewrite ?andbF // => <-]. Qed. Lemma F_r50 : 'Fix_to_g[r50]= [set x | (col1 x == col2 x) && (col2 x == col3 x) && (col3 x == col4 x)]. Proof. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r50_inv !ffunE !permE /=. apply sym_equal; rewrite !eqxx /= !andbT /col1/col2/col3/col4. by do 3![case: eqVneq; rewrite ?andbF // => <-]. Qed. Lemma F_r23 : 'Fix_to_g[r23] = [set x | (col0 x == col1 x) && (col1 x == col4 x) && (col4 x == col5 x)]. Proof. have r23_inv: r23^-1 = r32 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r23_inv !ffunE !permE /=. apply sym_equal; rewrite !eqxx /= !andbT /col1/col0/col5/col4. by do 3![case: eqVneq; rewrite ?andbF // => <-]. Qed. Lemma F_r32 : 'Fix_to_g[r32] = [set x | (col0 x == col1 x) && (col1 x == col4 x) && (col4 x == col5 x)]. Proof. have r32_inv: r32^-1 = r23 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r32_inv !ffunE !permE /=. apply sym_equal; rewrite !eqxx /= !andbT /col1/col0/col5/col4. by do 3![case: eqVneq; rewrite ?andbF // => <-]. Qed. Lemma F_r14 : 'Fix_to_g[r14] = [set x | (col0 x == col2 x) && (col2 x == col3 x) && (col3 x == col5 x)]. Proof. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r14_inv !ffunE !permE /=. apply sym_equal; rewrite !eqxx /= !andbT /col2/col0/col5/col3. by do 3![case: eqVneq; rewrite ?andbF // => <-]. Qed. Lemma F_r41 : 'Fix_to_g[r41] = [set x | (col0 x == col2 x) && (col2 x == col3 x) && (col3 x == col5 x)]. Proof. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r41_inv !ffunE !permE /=. apply sym_equal; rewrite !eqxx /= !andbT /col2/col0/col5/col3. by do 3![case: eqVneq; rewrite ?andbF // => <-]. Qed. Lemma F_r024 : 'Fix_to_g[r024] = [set x | (col0 x == col4 x) && (col4 x == col2 x) && (col1 x == col3 x) && (col3 x == col5 x) ]. Proof. have r024_inv: r024^-1 = r042 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r024_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 4![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_r042 : 'Fix_to_g[r042] = [set x | (col0 x == col4 x) && (col4 x == col2 x) && (col1 x == col3 x) && (col3 x == col5 x)]. Proof. have r042_inv: r042^-1 = r024 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r042_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 4![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_r012 : 'Fix_to_g[r012] = [set x | (col0 x == col2 x) && (col2 x == col1 x) && (col3 x == col4 x) && (col4 x == col5 x)]. Proof. have r012_inv: r012^-1 = r021 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r012_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 4![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_r021 : 'Fix_to_g[r021] = [set x | (col0 x == col2 x) && (col2 x == col1 x) && (col3 x == col4 x) && (col4 x == col5 x)]. Proof. have r021_inv: r021^-1 = r012 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r021_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. do 4![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_r031 : 'Fix_to_g[r031] = [set x | (col0 x == col3 x) && (col3 x == col1 x) && (col2 x == col4 x) && (col4 x == col5 x)]. Proof. have r031_inv: r031^-1 = r013 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r031_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 4![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_r013 : 'Fix_to_g[r013] = [set x | (col0 x == col3 x) && (col3 x == col1 x) && (col2 x == col4 x) && (col4 x == col5 x)]. Proof. have r013_inv: r013^-1 = r031 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r013_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 4![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_r043 : 'Fix_to_g[r043] = [set x | (col0 x == col4 x) && (col4 x == col3 x) && (col1 x == col2 x) && (col2 x == col5 x)]. Proof. have r043_inv: r043^-1 = r034 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r043_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 4![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_r034 : 'Fix_to_g[r034] = [set x | (col0 x == col4 x) && (col4 x == col3 x) && (col1 x == col2 x) && (col2 x == col5 x)]. Proof. have r034_inv: r034^-1 = r043 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g r034_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 4![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_s1 : 'Fix_to_g[s1] = [set x | (col0 x == col5 x) && (col1 x == col2 x) && (col3 x == col4 x)]. Proof. have s1_inv: s1^-1 = s1 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s1_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 3![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_s2 : 'Fix_to_g[s2] = [set x | (col0 x == col5 x) && (col1 x == col3 x) && (col2 x == col4 x)]. Proof. have s2_inv: s2^-1 = s2 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s2_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 3![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_s3 : 'Fix_to_g[s3] = [set x | (col0 x == col1 x) && (col2 x == col3 x) && (col4 x == col5 x)]. Proof. have s3_inv: s3^-1 = s3 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s3_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 3![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_s4 : 'Fix_to_g[s4] = [set x | (col0 x == col4 x) && (col1 x == col5 x) && (col2 x == col3 x)]. Proof. have s4_inv: s4^-1 = s4 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s4_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 3![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_s5 : 'Fix_to_g[s5] = [set x | (col0 x == col2 x) && (col1 x == col4 x) && (col3 x == col5 x)]. Proof. have s5_inv: s5^-1 = s5 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s5_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 3![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma F_s6 : 'Fix_to_g[s6] = [set x | (col0 x == col3 x) && (col1 x == col4 x) && (col2 x == col5 x)]. Proof. have s6_inv: s6^-1 = s6 by inv_tac. apply/setP => x; rewrite infE !inE eqperm_map2 /= /act_g s6_inv !ffunE !permE /=. apply sym_equal; rewrite ?eqxx /= !andbT /col0/col1/col2/col3/col4/col5. by do 3![case: eqVneq=> E; rewrite ?andbF // ?{}E]. Qed. Lemma uniq4_uniq6 : forall x y z t : cube, uniq [:: x; y; z; t] -> exists u, exists v, uniq [:: x; y; z; t; u; v]. Proof. move=> x y z t Uxt; move: (cardC [in [:: x; y; z; t]]). rewrite card_ord (card_uniq_tuple Uxt) => hcard. have hcard2: #|[predC [:: x; y; z; t]]| = 2. by apply: (@addnI 4); rewrite /injective hcard. have: #|[predC [:: x; y; z; t]]| != 0 by rewrite hcard2. case/existsP=> u Hu; exists u. move: (cardC [in [:: x; y; z; t; u]]); rewrite card_ord => hcard5. have: #|[predC [:: x; y; z; t; u]]| !=0. rewrite -lt0n -(ltn_add2l #|[:: x; y; z; t; u]|) hcard5 addn0. by apply: (leq_ltn_trans (card_size [:: x; y; z; t; u])). case/existsP => v; rewrite (mem_cat _ [:: _; _; _; _]) => /norP[Hv Huv]. exists v; rewrite (cat_uniq [:: x; y; z; t]) Uxt andTb -rev_uniq /= orbF. by rewrite negb_or Hu Hv Huv. Qed. Lemma card_n4 : forall x y z t : cube, uniq [:: x; y; z; t] -> #|[set p : col_cubes | (p x == p y) && (p z == p t)]| = (n ^ 4)%N. Proof. move=> x y z t Uxt; rewrite -[n]card_ord. case: (uniq4_uniq6 Uxt) => u [v Uxv]. pose ff (p : col_cubes) := (p x, p z, p u, p v). rewrite -(@card_in_image _ _ ff); first last. move=> p1 p2 /[!inE] /andP[p1y p1t] /andP[p2y p2t] [px pz] pu pv. have eqp12 : all (fun i => p1 i == p2 i) [:: x; y; z; t; u; v]. by rewrite /= -(eqP p1y) -(eqP p1t) -(eqP p2y) -(eqP p2t) px pz pu pv !eqxx. apply/ffunP=> i; apply/eqP; apply: (allP eqp12). by rewrite (subset_cardP _ (subset_predT _)) // (card_uniqP Uxv) card_ord. have -> : forall n, (n ^ 4 = n * n * n * n)%N by move=> ?; rewrite -!mulnA. rewrite -!card_prod; apply: eq_card => [] [[[c d] e] g] /=; apply/imageP => /=. move: Uxv; rewrite (cat_uniq [:: x; y; z; t]) => /and3P[_]/=; rewrite orbF. move=> /norP[] /[!inE] + + /andP[/negPf nuv _]. rewrite orbA => /norP[/negPf nxyu /negPf nztu]. rewrite orbA => /norP[/negPf nxyv /negPf nztv]. move: Uxt; rewrite (cat_uniq [::x; y]) => /and3P[_]/= /[!(andbT, orbF)]. move=> /norP[] /[!inE] /negPf nxyz /negPf nxyt _. exists [ffun i => if pred2 x y i then c else if pred2 z t i then d else if u == i then e else g]. by rewrite !(inE, ffunE, eqxx,orbT)//= nxyz nxyt. by rewrite {}/ff !ffunE /= !eqxx /= nxyz nxyu nztu nxyv nztv nuv. Qed. Lemma card_n3_3 : forall x y z t: cube, uniq [:: x; y; z; t] -> #|[set p : col_cubes | (p x == p y) && (p y == p z)&& (p z == p t)]| = (n ^ 3)%N. Proof. move=> x y z t Uxt; rewrite -[n]card_ord. case: (uniq4_uniq6 Uxt) => u [v Uxv]. pose ff (p : col_cubes) := (p x, p u, p v); rewrite -(@card_in_image _ _ ff); first last. move=> p1 p2 /[!inE]; rewrite -!andbA. move=> /and3P[/eqP p1xy /eqP p1yz /eqP p1zt]. move=> /and3P[/eqP p2xy /eqP p2yz /eqP p2zt] [px pu] pv. have eqp12: all (fun i => p1 i == p2 i) [:: x; y; z; t; u; v]. by rewrite /= -p1zt -p2zt -p1yz -p2yz -p1xy -p2xy px pu pv !eqxx. apply/ffunP=> i; apply/eqP; apply: (allP eqp12). by rewrite (subset_cardP _ (subset_predT _)) // (card_uniqP Uxv) card_ord. have -> : forall n, (n ^ 3 = n * n * n)%N by move=> ?; rewrite -!mulnA. rewrite -!card_prod; apply: eq_card => [] [[c d] e] /=; apply/imageP. move: Uxv; rewrite (cat_uniq [::x; y; z; t]) => /and3P[_ hasxt]. rewrite /uniq !inE !andbT => /negPf nuv. exists [ffun i => if i \in [:: x; y; z; t] then c else if u == i then d else e]. by rewrite /= !(inE, ffunE, eqxx, orbT). rewrite {}/ff !(ffunE, inE, eqxx) /=; move: hasxt; rewrite nuv. by do 8![case E: ( _ == _ ); rewrite ?(eqP E)/= ?inE ?eqxx //= ?E {E}]. Qed. Lemma card_n2_3 : forall x y z t u v: cube, uniq [:: x; y; z; t; u; v] -> #|[set p : col_cubes | (p x == p y) && (p y == p z)&& (p t == p u ) && (p u== p v)]| = (n ^ 2)%N. Proof. move=> x y z t u v Uxv; rewrite -[n]card_ord . pose ff (p : col_cubes) := (p x, p t). rewrite -(@card_in_image _ _ ff); first last. move=> p1 p2 /[!inE]; rewrite -!andbA. move=> /and4P[/eqP p1xy /eqP p1yz /eqP p1tu /eqP p1uv]. move=> /and4P[/eqP p2xy/eqP p2yz /eqP p2tu /eqP p2uv] [px pu]. have eqp12: all (fun i => p1 i == p2 i) [:: x; y; z; t; u; v]. by rewrite /= -p1yz -p2yz -p1xy -p2xy -p1uv -p2uv -p1tu -p2tu px pu !eqxx. apply/ffunP=> i; apply/eqP; apply: (allP eqp12). by rewrite (subset_cardP _ (subset_predT _)) // (card_uniqP Uxv) card_ord. rewrite -mulnn -!card_prod; apply: eq_card => [] [c d]/=; apply/imageP. move: Uxv; rewrite (cat_uniq [::x; y; z]) => /= /and3P[Uxt + nuv]. move=> /[!orbF] /norP[] /[!inE] /negPf nxyzt /norP[/negPf nxyzu /negPf nxyzv]. exists [ffun i => if (i \in [:: x; y; z] ) then c else d]. by rewrite /= !(inE, ffunE, eqxx, orbT, nxyzt, nxyzu, nxyzv). by rewrite {}/ff !ffunE !inE /= !eqxx /= nxyzt. Qed. Lemma card_n3s : forall x y z t u v: cube, uniq [:: x; y; z; t; u; v] -> #|[set p : col_cubes | (p x == p y) && (p z == p t)&& (p u == p v )]| = (n ^ 3)%N. Proof. move=> x y z t u v Uxv; rewrite -[n]card_ord . pose ff (p : col_cubes) := (p x, p z, p u). rewrite -(@card_in_image _ _ ff); first last. move=> p1 p2 /[!inE]; rewrite -!andbA. move=> /and3P[/eqP p1xy /eqP p1zt /eqP p1uv]. move=> /and3P[/eqP p2xy /eqP p2zt /eqP p2uv] [px pz] pu. have eqp12: all (fun i => p1 i == p2 i) [:: x; y; z; t; u; v]. by rewrite /= -p1xy -p2xy -p1zt -p2zt -p1uv -p2uv px pz pu !eqxx. apply/ffunP=> i; apply/eqP; apply: (allP eqp12). by rewrite (subset_cardP _ (subset_predT _)) // (card_uniqP Uxv) card_ord. have -> : forall n, (n ^ 3 = n * n * n)%N by move=> ?; rewrite -!mulnA. rewrite -!card_prod; apply: eq_card => [] [[c d] e] /=; apply/imageP. move: Uxv; rewrite (cat_uniq [::x; y; z; t]) => /and3P[Uxt + nuv]. move=> /= /[!orbF] /norP[] /[!inE]. rewrite orbA => /norP[/negPf nxyu /negPf nztu]. rewrite orbA => /norP[/negPf nxyv /negPf nztv]. move: Uxt; rewrite (cat_uniq [::x; y]) => /and3P[_]. rewrite /= !orbF !andbT => /norP[] /[!inE] /negPf nxyz /negPf nxyt _. exists [ffun i => if i \in [:: x; y] then c else if i \in [:: z; t] then d else e]. by rewrite !(inE, ffunE, eqxx,orbT)//= nxyz nxyt nxyu nztu nxyv nztv !eqxx. by rewrite {}/ff !ffunE !inE /= !eqxx nxyz nxyu nztu. Qed. Lemma burnside_app_iso3 : (cube_coloring_number24 * 24 = n ^ 6 + 6 * n ^ 3 + 3 * n ^ 4 + 8 * (n ^ 2) + 6 * n ^ 3)%N. Proof. pose iso_list := [:: id3; s05; s14; s23; r05; r14; r23; r50; r41; r32; r024; r042; r012; r021; r031; r013; r043; r034; s1; s2; s3; s4; s5; s6]. rewrite (burnside_formula iso_list); last first. - by move=> p; rewrite !inE /= !(eq_sym _ p). - apply: map_uniq (fun p : {perm cube} => (p F0, p F1)) _ _. have bsr : (fun p : {perm cube} => (p F0, p F1)) =1 (fun p => (nth F0 p F0, nth F0 p F1)) \o sop. by move=> x; rewrite /= -2!sop_spec. by rewrite (eq_map bsr) map_comp -(eqP Lcorrect); vm_compute. rewrite !big_cons big_nil {1}card_Fid3 /= F_s05 F_s14 F_s23 F_r05 F_r14 F_r23 F_r50 F_r41 F_r32 F_r024 F_r042 F_r012 F_r021 F_r031 F_r013 F_r043 F_r034 F_s1 F_s2 F_s3 F_s4 F_s5 F_s6. rewrite !card_n4 // !card_n3_3 // !card_n2_3 // !card_n3s //. by rewrite [RHS]addn.[ACl 1 * 3 * 2 * 4 * 5] !addnA !addn0. Qed. End cube_colouring. End colouring. Corollary burnside_app_iso_3_3col: cube_coloring_number24 3 = 57. Proof. by apply/eqP; rewrite -(@eqn_pmul2r 24) // burnside_app_iso3. Qed. Corollary burnside_app_iso_2_4col: square_coloring_number8 4 = 55. Proof. by apply/eqP; rewrite -(@eqn_pmul2r 8) // burnside_app_iso. Qed.
PiTensorProduct.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, Eric Wieser -/ import Mathlib.LinearAlgebra.Multilinear.TensorProduct import Mathlib.Tactic.AdaptationNote import Mathlib.LinearAlgebra.Multilinear.Curry /-! # Tensor product of an indexed family of modules over commutative semirings We define the tensor product of an indexed family `s : ι → Type*` of modules over commutative semirings. We denote this space by `⨂[R] i, s i` and define it as `FreeAddMonoid (R × Π i, s i)` quotiented by the appropriate equivalence relation. The treatment follows very closely that of the binary tensor product in `LinearAlgebra/TensorProduct.lean`. ## Main definitions * `PiTensorProduct R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. * `tprod R f` with `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`. This is bundled as a multilinear map from `Π i, s i` to `⨂[R] i, s i`. * `liftAddHom` constructs an `AddMonoidHom` from `(⨂[R] i, s i)` to some space `F` from a function `φ : (R × Π i, s i) → F` with the appropriate properties. * `lift φ` with `φ : MultilinearMap R s E` is the corresponding linear map `(⨂[R] i, s i) →ₗ[R] E`. This is bundled as a linear equivalence. * `PiTensorProduct.reindex e` re-indexes the components of `⨂[R] i : ι, M` along `e : ι ≃ ι₂`. * `PiTensorProduct.tmulEquiv` equivalence between a `TensorProduct` of `PiTensorProduct`s and a single `PiTensorProduct`. ## Notations * `⨂[R] i, s i` is defined as localized notation in locale `TensorProduct`. * `⨂ₜ[R] i, f i` with `f : ∀ i, s i` is defined globally as the tensor product of all the `f i`'s. ## Implementation notes * We define it via `FreeAddMonoid (R × Π i, s i)` with the `R` representing a "hidden" tensor factor, rather than `FreeAddMonoid (Π i, s i)` to ensure that, if `ι` is an empty type, the space is isomorphic to the base ring `R`. * We have not restricted the index type `ι` to be a `Fintype`, as nothing we do here strictly requires it. However, problems may arise in the case where `ι` is infinite; use at your own caution. * Instead of requiring `DecidableEq ι` as an argument to `PiTensorProduct` itself, we include it as an argument in the constructors of the relation. A decidability instance still has to come from somewhere due to the use of `Function.update`, but this hides it from the downstream user. See the implementation notes for `MultilinearMap` for an extended discussion of this choice. ## TODO * Define tensor powers, symmetric subspace, etc. * API for the various ways `ι` can be split into subsets; connect this with the binary tensor product. * Include connection with holors. * Port more of the API from the binary tensor product over to this case. ## Tags multilinear, tensor, tensor product -/ open Function section Semiring variable {ι ι₂ ι₃ : Type*} variable {R : Type*} [CommSemiring R] variable {R₁ R₂ : Type*} variable {s : ι → Type*} [∀ i, AddCommMonoid (s i)] [∀ i, Module R (s i)] variable {M : Type*} [AddCommMonoid M] [Module R M] variable {E : Type*} [AddCommMonoid E] [Module R E] variable {F : Type*} [AddCommMonoid F] namespace PiTensorProduct variable (R) (s) /-- The relation on `FreeAddMonoid (R × Π i, s i)` that generates a congruence whose quotient is the tensor product. -/ inductive Eqv : FreeAddMonoid (R × Π i, s i) → FreeAddMonoid (R × Π i, s i) → Prop | of_zero : ∀ (r : R) (f : Π i, s i) (i : ι) (_ : f i = 0), Eqv (FreeAddMonoid.of (r, f)) 0 | of_zero_scalar : ∀ f : Π i, s i, Eqv (FreeAddMonoid.of (0, f)) 0 | of_add : ∀ (_ : DecidableEq ι) (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), Eqv (FreeAddMonoid.of (r, update f i m₁) + FreeAddMonoid.of (r, update f i m₂)) (FreeAddMonoid.of (r, update f i (m₁ + m₂))) | of_add_scalar : ∀ (r r' : R) (f : Π i, s i), Eqv (FreeAddMonoid.of (r, f) + FreeAddMonoid.of (r', f)) (FreeAddMonoid.of (r + r', f)) | of_smul : ∀ (_ : DecidableEq ι) (r : R) (f : Π i, s i) (i : ι) (r' : R), Eqv (FreeAddMonoid.of (r, update f i (r' • f i))) (FreeAddMonoid.of (r' * r, f)) | add_comm : ∀ x y, Eqv (x + y) (y + x) end PiTensorProduct variable (R) (s) /-- `PiTensorProduct R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. -/ def PiTensorProduct : Type _ := (addConGen (PiTensorProduct.Eqv R s)).Quotient variable {R} /-- This enables the notation `⨂[R] i : ι, s i` for the pi tensor product `PiTensorProduct`, given an indexed family of types `s : ι → Type*`. -/ scoped[TensorProduct] notation3:100"⨂["R"] "(...)", "r:(scoped f => PiTensorProduct R f) => r open TensorProduct namespace PiTensorProduct section Module instance : AddCommMonoid (⨂[R] i, s i) := { (addConGen (PiTensorProduct.Eqv R s)).addMonoid with add_comm := fun x y ↦ AddCon.induction_on₂ x y fun _ _ ↦ Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.add_comm _ _ } instance : Inhabited (⨂[R] i, s i) := ⟨0⟩ variable (R) {s} /-- `tprodCoeff R r f` with `r : R` and `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`, multiplied by the coefficient `r`. Note that this is meant as an auxiliary definition for this file alone, and that one should use `tprod` defined below for most purposes. -/ def tprodCoeff (r : R) (f : Π i, s i) : ⨂[R] i, s i := AddCon.mk' _ <| FreeAddMonoid.of (r, f) variable {R} theorem zero_tprodCoeff (f : Π i, s i) : tprodCoeff R 0 f = 0 := Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_zero_scalar _ theorem zero_tprodCoeff' (z : R) (f : Π i, s i) (i : ι) (hf : f i = 0) : tprodCoeff R z f = 0 := Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_zero _ _ i hf theorem add_tprodCoeff [DecidableEq ι] (z : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i) : tprodCoeff R z (update f i m₁) + tprodCoeff R z (update f i m₂) = tprodCoeff R z (update f i (m₁ + m₂)) := Quotient.sound' <| AddConGen.Rel.of _ _ (Eqv.of_add _ z f i m₁ m₂) theorem add_tprodCoeff' (z₁ z₂ : R) (f : Π i, s i) : tprodCoeff R z₁ f + tprodCoeff R z₂ f = tprodCoeff R (z₁ + z₂) f := Quotient.sound' <| AddConGen.Rel.of _ _ (Eqv.of_add_scalar z₁ z₂ f) theorem smul_tprodCoeff_aux [DecidableEq ι] (z : R) (f : Π i, s i) (i : ι) (r : R) : tprodCoeff R z (update f i (r • f i)) = tprodCoeff R (r * z) f := Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_smul _ _ _ _ _ theorem smul_tprodCoeff [DecidableEq ι] (z : R) (f : Π i, s i) (i : ι) (r : R₁) [SMul R₁ R] [IsScalarTower R₁ R R] [SMul R₁ (s i)] [IsScalarTower R₁ R (s i)] : tprodCoeff R z (update f i (r • f i)) = tprodCoeff R (r • z) f := by have h₁ : r • z = r • (1 : R) * z := by rw [smul_mul_assoc, one_mul] have h₂ : r • f i = (r • (1 : R)) • f i := (smul_one_smul _ _ _).symm rw [h₁, h₂] exact smul_tprodCoeff_aux z f i _ /-- Construct an `AddMonoidHom` from `(⨂[R] i, s i)` to some space `F` from a function `φ : (R × Π i, s i) → F` with the appropriate properties. -/ def liftAddHom (φ : (R × Π i, s i) → F) (C0 : ∀ (r : R) (f : Π i, s i) (i : ι) (_ : f i = 0), φ (r, f) = 0) (C0' : ∀ f : Π i, s i, φ (0, f) = 0) (C_add : ∀ [DecidableEq ι] (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), φ (r, update f i m₁) + φ (r, update f i m₂) = φ (r, update f i (m₁ + m₂))) (C_add_scalar : ∀ (r r' : R) (f : Π i, s i), φ (r, f) + φ (r', f) = φ (r + r', f)) (C_smul : ∀ [DecidableEq ι] (r : R) (f : Π i, s i) (i : ι) (r' : R), φ (r, update f i (r' • f i)) = φ (r' * r, f)) : (⨂[R] i, s i) →+ F := (addConGen (PiTensorProduct.Eqv R s)).lift (FreeAddMonoid.lift φ) <| AddCon.addConGen_le fun x y hxy ↦ match hxy with | Eqv.of_zero r' f i hf => (AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, C0 r' f i hf] | Eqv.of_zero_scalar f => (AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, C0'] | Eqv.of_add inst z f i m₁ m₂ => (AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, @C_add inst] | Eqv.of_add_scalar z₁ z₂ f => (AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, C_add_scalar] | Eqv.of_smul inst z f i r' => (AddCon.ker_rel _).2 <| by simp [FreeAddMonoid.lift_eval_of, @C_smul inst] | Eqv.add_comm x y => (AddCon.ker_rel _).2 <| by simp_rw [AddMonoidHom.map_add, add_comm] /-- Induct using `tprodCoeff` -/ @[elab_as_elim] protected theorem induction_on' {motive : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i) (tprodCoeff : ∀ (r : R) (f : Π i, s i), motive (tprodCoeff R r f)) (add : ∀ x y, motive x → motive y → motive (x + y)) : motive z := by have C0 : motive 0 := by have h₁ := tprodCoeff 0 0 rwa [zero_tprodCoeff] at h₁ refine AddCon.induction_on z fun x ↦ FreeAddMonoid.recOn x C0 ?_ simp_rw [AddCon.coe_add] refine fun f y ih ↦ add _ _ ?_ ih convert tprodCoeff f.1 f.2 section DistribMulAction variable [Monoid R₁] [DistribMulAction R₁ R] [SMulCommClass R₁ R R] variable [Monoid R₂] [DistribMulAction R₂ R] [SMulCommClass R₂ R R] -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance hasSMul' : SMul R₁ (⨂[R] i, s i) := ⟨fun r ↦ liftAddHom (fun f : R × Π i, s i ↦ tprodCoeff R (r • f.1) f.2) (fun r' f i hf ↦ by simp_rw [zero_tprodCoeff' _ f i hf]) (fun f ↦ by simp [zero_tprodCoeff]) (fun r' f i m₁ m₂ ↦ by simp [add_tprodCoeff]) (fun r' r'' f ↦ by simp [add_tprodCoeff']) fun z f i r' ↦ by simp [smul_tprodCoeff, mul_smul_comm]⟩ instance : SMul R (⨂[R] i, s i) := PiTensorProduct.hasSMul' theorem smul_tprodCoeff' (r : R₁) (z : R) (f : Π i, s i) : r • tprodCoeff R z f = tprodCoeff R (r • z) f := rfl protected theorem smul_add (r : R₁) (x y : ⨂[R] i, s i) : r • (x + y) = r • x + r • y := AddMonoidHom.map_add _ _ _ instance distribMulAction' : DistribMulAction R₁ (⨂[R] i, s i) where smul := (· • ·) smul_add _ _ _ := AddMonoidHom.map_add _ _ _ mul_smul r r' x := PiTensorProduct.induction_on' x (fun {r'' f} ↦ by simp [smul_tprodCoeff', smul_smul]) fun {x y} ihx ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihx, ihy] one_smul x := PiTensorProduct.induction_on' x (fun {r f} ↦ by rw [smul_tprodCoeff', one_smul]) fun {z y} ihz ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihz, ihy] smul_zero _ := AddMonoidHom.map_zero _ instance smulCommClass' [SMulCommClass R₁ R₂ R] : SMulCommClass R₁ R₂ (⨂[R] i, s i) := ⟨fun {r' r''} x ↦ PiTensorProduct.induction_on' x (fun {xr xf} ↦ by simp only [smul_tprodCoeff', smul_comm]) fun {z y} ihz ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihz, ihy]⟩ instance isScalarTower' [SMul R₁ R₂] [IsScalarTower R₁ R₂ R] : IsScalarTower R₁ R₂ (⨂[R] i, s i) := ⟨fun {r' r''} x ↦ PiTensorProduct.induction_on' x (fun {xr xf} ↦ by simp only [smul_tprodCoeff', smul_assoc]) fun {z y} ihz ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihz, ihy]⟩ end DistribMulAction -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance module' [Semiring R₁] [Module R₁ R] [SMulCommClass R₁ R R] : Module R₁ (⨂[R] i, s i) := { PiTensorProduct.distribMulAction' with add_smul := fun r r' x ↦ PiTensorProduct.induction_on' x (fun {r f} ↦ by simp_rw [smul_tprodCoeff', add_smul, add_tprodCoeff']) fun {x y} ihx ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihx, ihy, add_add_add_comm] zero_smul := fun x ↦ PiTensorProduct.induction_on' x (fun {r f} ↦ by simp_rw [smul_tprodCoeff', zero_smul, zero_tprodCoeff]) fun {x y} ihx ihy ↦ by simp_rw [PiTensorProduct.smul_add, ihx, ihy, add_zero] } -- shortcut instances instance : Module R (⨂[R] i, s i) := PiTensorProduct.module' instance : SMulCommClass R R (⨂[R] i, s i) := PiTensorProduct.smulCommClass' instance : IsScalarTower R R (⨂[R] i, s i) := PiTensorProduct.isScalarTower' variable (R) in /-- The canonical `MultilinearMap R s (⨂[R] i, s i)`. `tprod R fun i => f i` has notation `⨂ₜ[R] i, f i`. -/ def tprod : MultilinearMap R s (⨂[R] i, s i) where toFun := tprodCoeff R 1 map_update_add' {_ f} i x y := (add_tprodCoeff (1 : R) f i x y).symm map_update_smul' {_ f} i r x := by rw [smul_tprodCoeff', ← smul_tprodCoeff (1 : R) _ i, update_idem, update_self] @[inherit_doc tprod] notation3:100 "⨂ₜ["R"] "(...)", "r:(scoped f => tprod R f) => r theorem tprod_eq_tprodCoeff_one : ⇑(tprod R : MultilinearMap R s (⨂[R] i, s i)) = tprodCoeff R 1 := rfl @[simp] theorem tprodCoeff_eq_smul_tprod (z : R) (f : Π i, s i) : tprodCoeff R z f = z • tprod R f := by have : z = z • (1 : R) := by simp only [mul_one, Algebra.id.smul_eq_mul] conv_lhs => rw [this] rfl /-- The image of an element `p` of `FreeAddMonoid (R × Π i, s i)` in the `PiTensorProduct` is equal to the sum of `a • ⨂ₜ[R] i, m i` over all the entries `(a, m)` of `p`. -/ lemma _root_.FreeAddMonoid.toPiTensorProduct (p : FreeAddMonoid (R × Π i, s i)) : AddCon.toQuotient (c := addConGen (PiTensorProduct.Eqv R s)) p = List.sum (List.map (fun x ↦ x.1 • ⨂ₜ[R] i, x.2 i) p.toList) := by -- TODO: this is defeq abuse: `p` is not a `List`. match p with | [] => rw [FreeAddMonoid.toList_nil, List.map_nil, List.sum_nil]; rfl | x :: ps => rw [FreeAddMonoid.toList_cons, List.map_cons, List.sum_cons, ← List.singleton_append, ← toPiTensorProduct ps, ← tprodCoeff_eq_smul_tprod] rfl /-- The set of lifts of an element `x` of `⨂[R] i, s i` in `FreeAddMonoid (R × Π i, s i)`. -/ def lifts (x : ⨂[R] i, s i) : Set (FreeAddMonoid (R × Π i, s i)) := {p | AddCon.toQuotient (c := addConGen (PiTensorProduct.Eqv R s)) p = x} /-- An element `p` of `FreeAddMonoid (R × Π i, s i)` lifts an element `x` of `⨂[R] i, s i` if and only if `x` is equal to the sum of `a • ⨂ₜ[R] i, m i` over all the entries `(a, m)` of `p`. -/ lemma mem_lifts_iff (x : ⨂[R] i, s i) (p : FreeAddMonoid (R × Π i, s i)) : p ∈ lifts x ↔ List.sum (List.map (fun x ↦ x.1 • ⨂ₜ[R] i, x.2 i) p.toList) = x := by simp only [lifts, Set.mem_setOf_eq, FreeAddMonoid.toPiTensorProduct] /-- Every element of `⨂[R] i, s i` has a lift in `FreeAddMonoid (R × Π i, s i)`. -/ lemma nonempty_lifts (x : ⨂[R] i, s i) : Set.Nonempty (lifts x) := by existsi @Quotient.out _ (addConGen (PiTensorProduct.Eqv R s)).toSetoid x simp only [lifts, Set.mem_setOf_eq] rw [← AddCon.quot_mk_eq_coe] erw [Quot.out_eq] /-- The empty list lifts the element `0` of `⨂[R] i, s i`. -/ lemma lifts_zero : 0 ∈ lifts (0 : ⨂[R] i, s i) := by rw [mem_lifts_iff, FreeAddMonoid.toList_zero, List.map_nil, List.sum_nil] /-- If elements `p,q` of `FreeAddMonoid (R × Π i, s i)` lift elements `x,y` of `⨂[R] i, s i` respectively, then `p + q` lifts `x + y`. -/ lemma lifts_add {x y : ⨂[R] i, s i} {p q : FreeAddMonoid (R × Π i, s i)} (hp : p ∈ lifts x) (hq : q ∈ lifts y) : p + q ∈ lifts (x + y) := by simp only [lifts, Set.mem_setOf_eq, AddCon.coe_add] rw [hp, hq] /-- If an element `p` of `FreeAddMonoid (R × Π i, s i)` lifts an element `x` of `⨂[R] i, s i`, and if `a` is an element of `R`, then the list obtained by multiplying the first entry of each element of `p` by `a` lifts `a • x`. -/ lemma lifts_smul {x : ⨂[R] i, s i} {p : FreeAddMonoid (R × Π i, s i)} (h : p ∈ lifts x) (a : R) : p.map (fun (y : R × Π i, s i) ↦ (a * y.1, y.2)) ∈ lifts (a • x) := by rw [mem_lifts_iff] at h ⊢ rw [← h] simp [Function.comp_def, mul_smul, List.smul_sum] /-- Induct using scaled versions of `PiTensorProduct.tprod`. -/ @[elab_as_elim] protected theorem induction_on {motive : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i) (smul_tprod : ∀ (r : R) (f : Π i, s i), motive (r • tprod R f)) (add : ∀ x y, motive x → motive y → motive (x + y)) : motive z := by simp_rw [← tprodCoeff_eq_smul_tprod] at smul_tprod exact PiTensorProduct.induction_on' z smul_tprod add @[ext] theorem ext {φ₁ φ₂ : (⨂[R] i, s i) →ₗ[R] E} (H : φ₁.compMultilinearMap (tprod R) = φ₂.compMultilinearMap (tprod R)) : φ₁ = φ₂ := by refine LinearMap.ext ?_ refine fun z ↦ PiTensorProduct.induction_on' z ?_ fun {x y} hx hy ↦ by rw [φ₁.map_add, φ₂.map_add, hx, hy] · intro r f rw [tprodCoeff_eq_smul_tprod, φ₁.map_smul, φ₂.map_smul] apply congr_arg exact MultilinearMap.congr_fun H f /-- The pure tensors (i.e. the elements of the image of `PiTensorProduct.tprod`) span the tensor product. -/ theorem span_tprod_eq_top : Submodule.span R (Set.range (tprod R)) = (⊤ : Submodule R (⨂[R] i, s i)) := Submodule.eq_top_iff'.mpr fun t ↦ t.induction_on (fun _ _ ↦ Submodule.smul_mem _ _ (Submodule.subset_span (by simp only [Set.mem_range, exists_apply_eq_apply]))) (fun _ _ hx hy ↦ Submodule.add_mem _ hx hy) end Module section Multilinear open MultilinearMap variable {s} section lift /-- Auxiliary function to constructing a linear map `(⨂[R] i, s i) → E` given a `MultilinearMap R s E` with the property that its composition with the canonical `MultilinearMap R s (⨂[R] i, s i)` is the given multilinear map. -/ def liftAux (φ : MultilinearMap R s E) : (⨂[R] i, s i) →+ E := liftAddHom (fun p : R × Π i, s i ↦ p.1 • φ p.2) (fun z f i hf ↦ by simp_rw [map_coord_zero φ i hf, smul_zero]) (fun f ↦ by simp_rw [zero_smul]) (fun z f i m₁ m₂ ↦ by simp_rw [← smul_add, φ.map_update_add]) (fun z₁ z₂ f ↦ by rw [← add_smul]) fun z f i r ↦ by simp [φ.map_update_smul, smul_smul, mul_comm] theorem liftAux_tprod (φ : MultilinearMap R s E) (f : Π i, s i) : liftAux φ (tprod R f) = φ f := by simp only [liftAux, liftAddHom, tprod_eq_tprodCoeff_one, tprodCoeff, AddCon.coe_mk'] -- The end of this proof was very different before https://github.com/leanprover/lean4/pull/2644: -- rw [FreeAddMonoid.of, FreeAddMonoid.ofList, Equiv.refl_apply, AddCon.lift_coe] -- dsimp [FreeAddMonoid.lift, FreeAddMonoid.sumAux] -- show _ • _ = _ -- rw [one_smul] erw [AddCon.lift_coe] simp theorem liftAux_tprodCoeff (φ : MultilinearMap R s E) (z : R) (f : Π i, s i) : liftAux φ (tprodCoeff R z f) = z • φ f := rfl theorem liftAux.smul {φ : MultilinearMap R s E} (r : R) (x : ⨂[R] i, s i) : liftAux φ (r • x) = r • liftAux φ x := by refine PiTensorProduct.induction_on' x ?_ ?_ · intro z f rw [smul_tprodCoeff' r z f, liftAux_tprodCoeff, liftAux_tprodCoeff, smul_assoc] · intro z y ihz ihy rw [smul_add, (liftAux φ).map_add, ihz, ihy, (liftAux φ).map_add, smul_add] /-- Constructing a linear map `(⨂[R] i, s i) → E` given a `MultilinearMap R s E` with the property that its composition with the canonical `MultilinearMap R s E` is the given multilinear map `φ`. -/ def lift : MultilinearMap R s E ≃ₗ[R] (⨂[R] i, s i) →ₗ[R] E where toFun φ := { liftAux φ with map_smul' := liftAux.smul } invFun φ' := φ'.compMultilinearMap (tprod R) left_inv φ := by ext simp [liftAux_tprod, LinearMap.compMultilinearMap] right_inv φ := by ext simp [liftAux_tprod] map_add' φ₁ φ₂ := by ext simp [liftAux_tprod] map_smul' r φ₂ := by ext simp [liftAux_tprod] variable {φ : MultilinearMap R s E} @[simp] theorem lift.tprod (f : Π i, s i) : lift φ (tprod R f) = φ f := liftAux_tprod φ f theorem lift.unique' {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : φ'.compMultilinearMap (PiTensorProduct.tprod R) = φ) : φ' = lift φ := ext <| H.symm ▸ (lift.symm_apply_apply φ).symm theorem lift.unique {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : ∀ f, φ' (PiTensorProduct.tprod R f) = φ f) : φ' = lift φ := lift.unique' (MultilinearMap.ext H) @[simp] theorem lift_symm (φ' : (⨂[R] i, s i) →ₗ[R] E) : lift.symm φ' = φ'.compMultilinearMap (tprod R) := rfl @[simp] theorem lift_tprod : lift (tprod R : MultilinearMap R s _) = LinearMap.id := Eq.symm <| lift.unique' rfl end lift section map variable {t t' : ι → Type*} variable [∀ i, AddCommMonoid (t i)] [∀ i, Module R (t i)] variable [∀ i, AddCommMonoid (t' i)] [∀ i, Module R (t' i)] variable (g : Π i, t i →ₗ[R] t' i) (f : Π i, s i →ₗ[R] t i) /-- Let `sᵢ` and `tᵢ` be two families of `R`-modules. Let `f` be a family of `R`-linear maps between `sᵢ` and `tᵢ`, i.e. `f : Πᵢ sᵢ → tᵢ`, then there is an induced map `⨂ᵢ sᵢ → ⨂ᵢ tᵢ` by `⨂ aᵢ ↦ ⨂ fᵢ aᵢ`. This is `TensorProduct.map` for an arbitrary family of modules. -/ def map : (⨂[R] i, s i) →ₗ[R] ⨂[R] i, t i := lift <| (tprod R).compLinearMap f @[simp] lemma map_tprod (x : Π i, s i) : map f (tprod R x) = tprod R fun i ↦ f i (x i) := lift.tprod _ -- No lemmas about associativity, because we don't have associativity of `PiTensorProduct` yet. theorem map_range_eq_span_tprod : LinearMap.range (map f) = Submodule.span R {t | ∃ (m : Π i, s i), tprod R (fun i ↦ f i (m i)) = t} := by rw [← Submodule.map_top, ← span_tprod_eq_top, Submodule.map_span, ← Set.range_comp] apply congrArg; ext x simp only [Set.mem_range, comp_apply, map_tprod, Set.mem_setOf_eq] /-- Given submodules `p i ⊆ s i`, this is the natural map: `⨂[R] i, p i → ⨂[R] i, s i`. This is `TensorProduct.mapIncl` for an arbitrary family of modules. -/ @[simp] def mapIncl (p : Π i, Submodule R (s i)) : (⨂[R] i, p i) →ₗ[R] ⨂[R] i, s i := map fun (i : ι) ↦ (p i).subtype theorem map_comp : map (fun (i : ι) ↦ g i ∘ₗ f i) = map g ∘ₗ map f := by ext simp only [LinearMap.compMultilinearMap_apply, map_tprod, LinearMap.coe_comp, Function.comp_apply] theorem lift_comp_map (h : MultilinearMap R t E) : lift h ∘ₗ map f = lift (h.compLinearMap f) := by ext simp only [LinearMap.compMultilinearMap_apply, LinearMap.coe_comp, Function.comp_apply, map_tprod, lift.tprod, MultilinearMap.compLinearMap_apply] attribute [local ext high] ext @[simp] theorem map_id : map (fun i ↦ (LinearMap.id : s i →ₗ[R] s i)) = .id := by ext simp only [LinearMap.compMultilinearMap_apply, map_tprod, LinearMap.id_coe, id_eq] @[simp] protected theorem map_one : map (fun (i : ι) ↦ (1 : s i →ₗ[R] s i)) = 1 := map_id protected theorem map_mul (f₁ f₂ : Π i, s i →ₗ[R] s i) : map (fun i ↦ f₁ i * f₂ i) = map f₁ * map f₂ := map_comp f₁ f₂ /-- Upgrading `PiTensorProduct.map` to a `MonoidHom` when `s = t`. -/ @[simps] def mapMonoidHom : (Π i, s i →ₗ[R] s i) →* ((⨂[R] i, s i) →ₗ[R] ⨂[R] i, s i) where toFun := map map_one' := PiTensorProduct.map_one map_mul' := PiTensorProduct.map_mul @[simp] protected theorem map_pow (f : Π i, s i →ₗ[R] s i) (n : ℕ) : map (f ^ n) = map f ^ n := MonoidHom.map_pow mapMonoidHom _ _ open Function in private theorem map_add_smul_aux [DecidableEq ι] (i : ι) (x : Π i, s i) (u : s i →ₗ[R] t i) : (fun j ↦ update f i u j (x j)) = update (fun j ↦ (f j) (x j)) i (u (x i)) := by ext j exact apply_update (fun i F => F (x i)) f i u j open Function in protected theorem map_update_add [DecidableEq ι] (i : ι) (u v : s i →ₗ[R] t i) : map (update f i (u + v)) = map (update f i u) + map (update f i v) := by ext x simp only [LinearMap.compMultilinearMap_apply, map_tprod, map_add_smul_aux, LinearMap.add_apply, MultilinearMap.map_update_add] open Function in protected theorem map_update_smul [DecidableEq ι] (i : ι) (c : R) (u : s i →ₗ[R] t i) : map (update f i (c • u)) = c • map (update f i u) := by ext x simp only [LinearMap.compMultilinearMap_apply, map_tprod, map_add_smul_aux, LinearMap.smul_apply, MultilinearMap.map_update_smul] variable (R s t) /-- The tensor of a family of linear maps from `sᵢ` to `tᵢ`, as a multilinear map of the family. -/ @[simps] noncomputable def mapMultilinear : MultilinearMap R (fun (i : ι) ↦ s i →ₗ[R] t i) ((⨂[R] i, s i) →ₗ[R] ⨂[R] i, t i) where toFun := map map_update_smul' _ _ _ _ := PiTensorProduct.map_update_smul _ _ _ _ map_update_add' _ _ _ _ := PiTensorProduct.map_update_add _ _ _ _ variable {R s t} /-- Let `sᵢ` and `tᵢ` be families of `R`-modules. Then there is an `R`-linear map between `⨂ᵢ Hom(sᵢ, tᵢ)` and `Hom(⨂ᵢ sᵢ, ⨂ tᵢ)` defined by `⨂ᵢ fᵢ ↦ ⨂ᵢ aᵢ ↦ ⨂ᵢ fᵢ aᵢ`. This is `TensorProduct.homTensorHomMap` for an arbitrary family of modules. Note that `PiTensorProduct.piTensorHomMap (tprod R f)` is equal to `PiTensorProduct.map f`. -/ def piTensorHomMap : (⨂[R] i, s i →ₗ[R] t i) →ₗ[R] (⨂[R] i, s i) →ₗ[R] ⨂[R] i, t i := lift.toLinearMap ∘ₗ lift (MultilinearMap.piLinearMap <| tprod R) @[simp] lemma piTensorHomMap_tprod_tprod (f : Π i, s i →ₗ[R] t i) (x : Π i, s i) : piTensorHomMap (tprod R f) (tprod R x) = tprod R fun i ↦ f i (x i) := by simp [piTensorHomMap] lemma piTensorHomMap_tprod_eq_map (f : Π i, s i →ₗ[R] t i) : piTensorHomMap (tprod R f) = map f := by ext; simp /-- If `s i` and `t i` are linearly equivalent for every `i` in `ι`, then `⨂[R] i, s i` and `⨂[R] i, t i` are linearly equivalent. This is the n-ary version of `TensorProduct.congr` -/ noncomputable def congr (f : Π i, s i ≃ₗ[R] t i) : (⨂[R] i, s i) ≃ₗ[R] ⨂[R] i, t i := .ofLinear (map (fun i ↦ f i)) (map (fun i ↦ (f i).symm)) (by ext; simp) (by ext; simp) @[simp] theorem congr_tprod (f : Π i, s i ≃ₗ[R] t i) (m : Π i, s i) : congr f (tprod R m) = tprod R (fun (i : ι) ↦ (f i) (m i)) := by simp only [congr, LinearEquiv.ofLinear_apply, map_tprod, LinearEquiv.coe_coe] @[simp] theorem congr_symm_tprod (f : Π i, s i ≃ₗ[R] t i) (p : Π i, t i) : (congr f).symm (tprod R p) = tprod R (fun (i : ι) ↦ (f i).symm (p i)) := by simp only [congr, LinearEquiv.ofLinear_symm_apply, map_tprod, LinearEquiv.coe_coe] /-- Let `sᵢ`, `tᵢ` and `t'ᵢ` be families of `R`-modules, then `f : Πᵢ sᵢ → tᵢ → t'ᵢ` induces an element of `Hom(⨂ᵢ sᵢ, Hom(⨂ tᵢ, ⨂ᵢ t'ᵢ))` defined by `⨂ᵢ aᵢ ↦ ⨂ᵢ bᵢ ↦ ⨂ᵢ fᵢ aᵢ bᵢ`. This is `PiTensorProduct.map` for two arbitrary families of modules. This is `TensorProduct.map₂` for families of modules. -/ def map₂ (f : Π i, s i →ₗ[R] t i →ₗ[R] t' i) : (⨂[R] i, s i) →ₗ[R] (⨂[R] i, t i) →ₗ[R] ⨂[R] i, t' i := lift <| LinearMap.compMultilinearMap piTensorHomMap <| (tprod R).compLinearMap f lemma map₂_tprod_tprod (f : Π i, s i →ₗ[R] t i →ₗ[R] t' i) (x : Π i, s i) (y : Π i, t i) : map₂ f (tprod R x) (tprod R y) = tprod R fun i ↦ f i (x i) (y i) := by simp [map₂] /-- Let `sᵢ`, `tᵢ` and `t'ᵢ` be families of `R`-modules. Then there is a function from `⨂ᵢ Hom(sᵢ, Hom(tᵢ, t'ᵢ))` to `Hom(⨂ᵢ sᵢ, Hom(⨂ tᵢ, ⨂ᵢ t'ᵢ))` defined by `⨂ᵢ fᵢ ↦ ⨂ᵢ aᵢ ↦ ⨂ᵢ bᵢ ↦ ⨂ᵢ fᵢ aᵢ bᵢ`. -/ def piTensorHomMapFun₂ : (⨂[R] i, s i →ₗ[R] t i →ₗ[R] t' i) → (⨂[R] i, s i) →ₗ[R] (⨂[R] i, t i) →ₗ[R] (⨂[R] i, t' i) := fun φ => lift <| LinearMap.compMultilinearMap piTensorHomMap <| (lift <| MultilinearMap.piLinearMap <| tprod R) φ theorem piTensorHomMapFun₂_add (φ ψ : ⨂[R] i, s i →ₗ[R] t i →ₗ[R] t' i) : piTensorHomMapFun₂ (φ + ψ) = piTensorHomMapFun₂ φ + piTensorHomMapFun₂ ψ := by dsimp [piTensorHomMapFun₂]; ext; simp only [map_add, LinearMap.compMultilinearMap_apply, lift.tprod, add_apply, LinearMap.add_apply] theorem piTensorHomMapFun₂_smul (r : R) (φ : ⨂[R] i, s i →ₗ[R] t i →ₗ[R] t' i) : piTensorHomMapFun₂ (r • φ) = r • piTensorHomMapFun₂ φ := by dsimp [piTensorHomMapFun₂]; ext; simp only [map_smul, LinearMap.compMultilinearMap_apply, lift.tprod, smul_apply, LinearMap.smul_apply] /-- Let `sᵢ`, `tᵢ` and `t'ᵢ` be families of `R`-modules. Then there is an linear map from `⨂ᵢ Hom(sᵢ, Hom(tᵢ, t'ᵢ))` to `Hom(⨂ᵢ sᵢ, Hom(⨂ tᵢ, ⨂ᵢ t'ᵢ))` defined by `⨂ᵢ fᵢ ↦ ⨂ᵢ aᵢ ↦ ⨂ᵢ bᵢ ↦ ⨂ᵢ fᵢ aᵢ bᵢ`. This is `TensorProduct.homTensorHomMap` for two arbitrary families of modules. -/ def piTensorHomMap₂ : (⨂[R] i, s i →ₗ[R] t i →ₗ[R] t' i) →ₗ[R] (⨂[R] i, s i) →ₗ[R] (⨂[R] i, t i) →ₗ[R] (⨂[R] i, t' i) where toFun := piTensorHomMapFun₂ map_add' x y := piTensorHomMapFun₂_add x y map_smul' x y := piTensorHomMapFun₂_smul x y @[simp] lemma piTensorHomMap₂_tprod_tprod_tprod (f : ∀ i, s i →ₗ[R] t i →ₗ[R] t' i) (a : ∀ i, s i) (b : ∀ i, t i) : piTensorHomMap₂ (tprod R f) (tprod R a) (tprod R b) = tprod R (fun i ↦ f i (a i) (b i)) := by simp [piTensorHomMapFun₂, piTensorHomMap₂] end map section variable (R M) variable (s) in /-- Re-index the components of the tensor power by `e`. -/ def reindex (e : ι ≃ ι₂) : (⨂[R] i : ι, s i) ≃ₗ[R] ⨂[R] i : ι₂, s (e.symm i) := let f := domDomCongrLinearEquiv' R R s (⨂[R] (i : ι₂), s (e.symm i)) e let g := domDomCongrLinearEquiv' R R s (⨂[R] (i : ι), s i) e LinearEquiv.ofLinear (lift <| f.symm <| tprod R) (lift <| g <| tprod R) (by aesop) (by aesop) end @[simp] theorem reindex_tprod (e : ι ≃ ι₂) (f : Π i, s i) : reindex R s e (tprod R f) = tprod R fun i ↦ f (e.symm i) := by dsimp [reindex] exact liftAux_tprod _ f @[simp] theorem reindex_comp_tprod (e : ι ≃ ι₂) : (reindex R s e).compMultilinearMap (tprod R) = (domDomCongrLinearEquiv' R R s _ e).symm (tprod R) := MultilinearMap.ext <| reindex_tprod e theorem lift_comp_reindex (e : ι ≃ ι₂) (φ : MultilinearMap R (fun i ↦ s (e.symm i)) E) : lift φ ∘ₗ (reindex R s e) = lift ((domDomCongrLinearEquiv' R R s _ e).symm φ) := by ext; simp [reindex] @[simp] theorem lift_comp_reindex_symm (e : ι ≃ ι₂) (φ : MultilinearMap R s E) : lift φ ∘ₗ (reindex R s e).symm = lift (domDomCongrLinearEquiv' R R s _ e φ) := by ext; simp [reindex] theorem lift_reindex (e : ι ≃ ι₂) (φ : MultilinearMap R (fun i ↦ s (e.symm i)) E) (x : ⨂[R] i, s i) : lift φ (reindex R s e x) = lift ((domDomCongrLinearEquiv' R R s _ e).symm φ) x := LinearMap.congr_fun (lift_comp_reindex e φ) x @[simp] theorem lift_reindex_symm (e : ι ≃ ι₂) (φ : MultilinearMap R s E) (x : ⨂[R] i, s (e.symm i)) : lift φ (reindex R s e |>.symm x) = lift (domDomCongrLinearEquiv' R R s _ e φ) x := LinearMap.congr_fun (lift_comp_reindex_symm e φ) x @[simp] theorem reindex_trans (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) : (reindex R s e).trans (reindex R _ e') = reindex R s (e.trans e') := by apply LinearEquiv.toLinearMap_injective ext f simp only [LinearEquiv.trans_apply, LinearEquiv.coe_coe, reindex_tprod, LinearMap.coe_compMultilinearMap, Function.comp_apply, reindex_comp_tprod] congr theorem reindex_reindex (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) (x : ⨂[R] i, s i) : reindex R _ e' (reindex R s e x) = reindex R s (e.trans e') x := LinearEquiv.congr_fun (reindex_trans e e' : _ = reindex R s (e.trans e')) x /-- This lemma is impractical to state in the dependent case. -/ @[simp] theorem reindex_symm (e : ι ≃ ι₂) : (reindex R (fun _ ↦ M) e).symm = reindex R (fun _ ↦ M) e.symm := by ext x simp [reindex] @[simp] theorem reindex_refl : reindex R s (Equiv.refl ι) = LinearEquiv.refl R _ := by apply LinearEquiv.toLinearMap_injective ext simp only [Equiv.refl_symm, Equiv.refl_apply, reindex, domDomCongrLinearEquiv', LinearEquiv.coe_symm_mk, LinearMap.compMultilinearMap_apply, LinearEquiv.coe_coe, LinearEquiv.refl_toLinearMap, LinearMap.id_coe, id_eq] simp variable {t : ι → Type*} variable [∀ i, AddCommMonoid (t i)] [∀ i, Module R (t i)] /-- Re-indexing the components of the tensor product by an equivalence `e` is compatible with `PiTensorProduct.map`. -/ theorem map_comp_reindex_eq (f : Π i, s i →ₗ[R] t i) (e : ι ≃ ι₂) : map (fun i ↦ f (e.symm i)) ∘ₗ reindex R s e = reindex R t e ∘ₗ map f := by ext m simp only [LinearMap.compMultilinearMap_apply, LinearEquiv.coe_coe, LinearMap.comp_apply, reindex_tprod, map_tprod] theorem map_reindex (f : Π i, s i →ₗ[R] t i) (e : ι ≃ ι₂) (x : ⨂[R] i, s i) : map (fun i ↦ f (e.symm i)) (reindex R s e x) = reindex R t e (map f x) := DFunLike.congr_fun (map_comp_reindex_eq _ _) _ theorem map_comp_reindex_symm (f : Π i, s i →ₗ[R] t i) (e : ι ≃ ι₂) : map f ∘ₗ (reindex R s e).symm = (reindex R t e).symm ∘ₗ map (fun i => f (e.symm i)) := by ext m apply LinearEquiv.injective (reindex R t e) simp only [LinearMap.compMultilinearMap_apply, LinearMap.coe_comp, LinearEquiv.coe_coe, comp_apply, ← map_reindex, LinearEquiv.apply_symm_apply, map_tprod] theorem map_reindex_symm (f : Π i, s i →ₗ[R] t i) (e : ι ≃ ι₂) (x : ⨂[R] i, s (e.symm i)) : map f ((reindex R s e).symm x) = (reindex R t e).symm (map (fun i ↦ f (e.symm i)) x) := DFunLike.congr_fun (map_comp_reindex_symm _ _) _ variable (ι) attribute [local simp] eq_iff_true_of_subsingleton in /-- The tensor product over an empty index type `ι` is isomorphic to the base ring. -/ @[simps symm_apply] def isEmptyEquiv [IsEmpty ι] : (⨂[R] i : ι, s i) ≃ₗ[R] R where toFun := lift (constOfIsEmpty R _ 1) invFun r := r • tprod R (@isEmptyElim _ _ _) left_inv x := by refine x.induction_on ?_ ?_ · intro x y simp only [map_smulₛₗ, RingHom.id_apply, lift.tprod, constOfIsEmpty_apply, const_apply, smul_eq_mul, mul_one] congr aesop · simp only intro x y hx hy rw [map_add, add_smul, hx, hy] right_inv t := by simp map_add' := LinearMap.map_add _ map_smul' := fun r x => by exact LinearMap.map_smul _ r x @[simp] theorem isEmptyEquiv_apply_tprod [IsEmpty ι] (f : Π i, s i) : isEmptyEquiv ι (tprod R f) = 1 := lift.tprod _ variable {ι} /-- Tensor product of `M` over a singleton set is equivalent to `M` -/ @[simps symm_apply] def subsingletonEquiv [Subsingleton ι] (i₀ : ι) : (⨂[R] _ : ι, M) ≃ₗ[R] M where toFun := lift (MultilinearMap.ofSubsingleton R M M i₀ .id) invFun m := tprod R fun _ ↦ m left_inv x := by dsimp only have : ∀ (f : ι → M) (z : M), (fun _ : ι ↦ z) = update f i₀ z := fun f z ↦ by ext i rw [Subsingleton.elim i i₀, Function.update_self] refine x.induction_on ?_ ?_ · intro r f simp only [LinearMap.map_smul, LinearMap.id_apply, lift.tprod, ofSubsingleton_apply_apply, this f, MultilinearMap.map_update_smul, update_eq_self] · intro x y hx hy rw [LinearMap.map_add, this 0 (_ + _), MultilinearMap.map_update_add, ← this 0 (lift _ _), hx, ← this 0 (lift _ _), hy] right_inv t := by simp only [ofSubsingleton_apply_apply, LinearMap.id_apply, lift.tprod] map_add' := LinearMap.map_add _ map_smul' := fun r x => by exact LinearMap.map_smul _ r x @[simp] theorem subsingletonEquiv_apply_tprod [Subsingleton ι] (i : ι) (f : ι → M) : subsingletonEquiv i (tprod R f) = f i := lift.tprod _ variable (R M) section tmulEquivDep variable (N : ι ⊕ ι₂ → Type*) [∀ i, AddCommMonoid (N i)] [∀ i, Module R (N i)] /-- Equivalence between a `TensorProduct` of `PiTensorProduct`s and a single `PiTensorProduct` indexed by a `Sum` type. If `N` is a constant family of modules, use the non-dependant version `PiTensorProduct.tmulEquiv` instead. -/ def tmulEquivDep : (⨂[R] i₁, N (.inl i₁)) ⊗[R] (⨂[R] i₂, N (.inr i₂)) ≃ₗ[R] ⨂[R] i, N i := LinearEquiv.ofLinear (TensorProduct.lift { toFun a := PiTensorProduct.lift (PiTensorProduct.lift (MultilinearMap.currySumEquiv (tprod R)) a) map_add' := by simp map_smul' := by simp }) (PiTensorProduct.lift (MultilinearMap.domCoprodDep (tprod R) (tprod R))) (by ext dsimp simp only [lift.tprod, domCoprodDep_apply, lift.tmul, LinearMap.coe_mk, AddHom.coe_mk, currySum_apply] congr ext (_ | _) <;> simp) (TensorProduct.ext (by aesop)) @[simp] lemma tmulEquivDep_apply (a : (i₁ : ι) → N (.inl i₁)) (b : (i₂ : ι₂) → N (.inr i₂)) : tmulEquivDep R N ((⨂ₜ[R] i₁, a i₁) ⊗ₜ (⨂ₜ[R] i₂, b i₂)) = (⨂ₜ[R] i, Sum.rec a b i) := by simp [tmulEquivDep] @[simp] lemma tmulEquivDep_symm_apply (f : (i : ι ⊕ ι₂) → N i) : (tmulEquivDep R N).symm (⨂ₜ[R] i, f i) = ((⨂ₜ[R] i₁, f (.inl i₁)) ⊗ₜ (⨂ₜ[R] i₂, f (.inr i₂))) := by simp [tmulEquivDep] end tmulEquivDep section tmulEquiv /-- Equivalence between a `TensorProduct` of `PiTensorProduct`s and a single `PiTensorProduct` indexed by a `Sum` type. See `PiTensorProduct.tmulEquivDep` for the dependent version. -/ def tmulEquiv : (⨂[R] (_ : ι), M) ⊗[R] (⨂[R] (_ : ι₂), M) ≃ₗ[R] ⨂[R] (_ : ι ⊕ ι₂), M := tmulEquivDep R (fun _ ↦ M) @[simp] theorem tmulEquiv_apply (a : ι → M) (b : ι₂ → M) : tmulEquiv R M ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, Sum.elim a b i := by simp [tmulEquiv, Sum.elim] @[simp] theorem tmulEquiv_symm_apply (a : ι ⊕ ι₂ → M) : (tmulEquiv R M).symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (Sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (Sum.inr i)) := by simp [tmulEquiv] end tmulEquiv end Multilinear end PiTensorProduct end Semiring section Ring namespace PiTensorProduct open PiTensorProduct open TensorProduct variable {ι : Type*} {R : Type*} [CommRing R] variable {s : ι → Type*} [∀ i, AddCommGroup (s i)] [∀ i, Module R (s i)] /- Unlike for the binary tensor product, we require `R` to be a `CommRing` here, otherwise this is false in the case where `ι` is empty. -/ instance : AddCommGroup (⨂[R] i, s i) := Module.addCommMonoidToAddCommGroup R end PiTensorProduct end Ring
closed_field.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 choice ssrnat seq. From mathcomp Require Import fintype generic_quotient bigop ssralg poly. From mathcomp Require Import polydiv matrix mxpoly countalg ring_quotient. (******************************************************************************) (* A quantifier elimination for algebraically closed fields *) (* *) (* This files contains two main contributions: *) (* 1. Factory "Field_isAlgClosed" *) (* Build an algebraically closed field that enjoy quantifier elimination, *) (* as described in *) (* ``A formal quantifier elimination for algebraically closed fields'', *) (* proceedings of Calculemus 2010, by Cyril Cohen and Assia Mahboubi *) (* *) (* We construct an instance of quantifier elimination mixin, *) (* (see the ssralg library) from the theory of polynomials with coefficients *) (* in an algebraically closed field (see the polydiv library). *) (* The algebraic operations on formulae are implemented in CPS style. *) (* We provide one CPS counterpart for each operation involved in the proof *) (* of quantifier elimination. See the paper above for more details. *) (* *) (* 2. Theorems "countable_field_extension" and "countable_algebraic_closure" *) (* constructions for both simple extension and algebraic closure of *) (* countable fields, by Georges Gonthier. *) (* Note that the construction of the algebraic closure relies on the *) (* above mentioned quantifier elimination. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory. Local Open Scope ring_scope. Import Pdiv.Ring. Import PreClosedField. Module ClosedFieldQE. Section ClosedFieldQE. Variables (F : fieldType) (F_closed : GRing.closed_field_axiom F). Notation fF := (@GRing.formula F). Notation tF := (@GRing.term F). Notation qf f := (GRing.qf_form f && GRing.rformula f). Definition polyF := seq tF. Lemma qf_simpl (f : fF) : (qf f -> GRing.qf_form f) * (qf f -> GRing.rformula f). Proof. by split=> /andP[]. Qed. Notation cps T := ((T -> fF) -> fF). Definition ret T1 : T1 -> cps T1 := fun x k => k x. Arguments ret {T1} x k /. Definition bind T1 T2 (x : cps T1) (f : T1 -> cps T2) : cps T2 := fun k => x (fun x => f x k). Arguments bind {T1 T2} x f k /. Notation "''let' x <- y ; z" := (bind y (fun x => z)) (at level 99, x at level 0, z at level 200, format "'[hv' ''let' x <- y ; '/' z ']'"). Definition cpsif T (c : fF) (t : T) (e : T) : cps T := fun k => GRing.If c (k t) (k e). Arguments cpsif {T} c t e k /. Notation "''if' c1 'then' c2 'else' c3" := (cpsif c1%T c2%T c3%T) (at level 200, right associativity, format "'[hv ' ''if' c1 '/' '[' 'then' c2 ']' '/' '[' 'else' c3 ']' ']'"). Notation eval := GRing.eval. Notation rterm := GRing.rterm. Notation qf_eval := GRing.qf_eval. Fixpoint eval_poly (e : seq F) pf := if pf is c :: q then eval_poly e q * 'X + (eval e c)%:P else 0. Definition rpoly (p : polyF) := all (@rterm F) p. Definition sizeT : polyF -> cps nat := (fix loop p := if p isn't c :: q then ret 0 else 'let n <- loop q; if n is m.+1 then ret m.+2 else 'if (c == 0) then 0%N else 1%N). Definition qf_red_cps T (x : cps T) (y : _ -> T) := forall e k, qf_eval e (x k) = qf_eval e (k (y e)). Notation "x ->_ e y" := (qf_red_cps x (fun e => y)) (e name, at level 90, format "x ->_ e y"). Definition qf_cps T D (x : cps T) := forall k, (forall y, D y -> qf (k y)) -> qf (x k). Lemma qf_cps_ret T D (x : T) : D x -> qf_cps D (ret x). Proof. move=> ??; exact. Qed. Hint Resolve qf_cps_ret : core. Lemma qf_cps_bind T1 D1 T2 D2 (x : cps T1) (f : T1 -> cps T2) : qf_cps D1 x -> (forall x, D1 x -> qf_cps D2 (f x)) -> qf_cps D2 (bind x f). Proof. by move=> xP fP k kP /=; apply: xP => y ?; apply: fP. Qed. Lemma qf_cps_if T D (c : fF) (t : T) (e : T) : qf c -> D t -> D e -> qf_cps D ('if c then t else e). Proof. move=> qfc Dt De k kP /=; have [qft qfe] := (kP _ Dt, kP _ De). by do !rewrite qf_simpl //. Qed. Lemma sizeTP (pf : polyF) : sizeT pf ->_e size (eval_poly e pf). Proof. elim: pf=> [|c qf qfP /=]; first by rewrite /= size_poly0. move=> e k; rewrite size_MXaddC qfP -(size_poly_eq0 (eval_poly _ _)). by case: (size (eval_poly e qf))=> //=; case: eqP; rewrite // orbF. Qed. Lemma sizeT_qf (p : polyF) : rpoly p -> qf_cps xpredT (sizeT p). Proof. elim: p => /= [_|c p ihp /andP[rc rq]]; first exact: qf_cps_ret. apply: qf_cps_bind; first exact: ihp. move=> [|n] //= _; last exact: qf_cps_ret. by apply: qf_cps_if; rewrite //= rc. Qed. Definition isnull (p : polyF) : cps bool := 'let n <- sizeT p; ret (n == 0). Lemma isnullP (p : polyF) : isnull p ->_e (eval_poly e p == 0). Proof. by move=> e k; rewrite sizeTP size_poly_eq0. Qed. Lemma isnull_qf (p : polyF) : rpoly p -> qf_cps xpredT (isnull p). Proof. move=> rp; apply: qf_cps_bind; first exact: sizeT_qf. by move=> ? _; apply: qf_cps_ret. Qed. Definition lt_sizeT (p q : polyF) : cps bool := 'let n <- sizeT p; 'let m <- sizeT q; ret (n < m). Definition lift (p : {poly F}) := map GRing.Const p. Lemma eval_lift (e : seq F) (p : {poly F}) : eval_poly e (lift p) = p. Proof. elim/poly_ind: p => [|p c]; first by rewrite /lift polyseq0. rewrite -cons_poly_def /lift polyseq_cons /nilp. case pn0: (_ == _) => /=; last by move->; rewrite -cons_poly_def. move=> _; rewrite polyseqC. case c0: (_==_)=> /=. move: pn0; rewrite (eqP c0) size_poly_eq0; move/eqP->. by apply: val_inj=> /=; rewrite polyseq_cons // polyseq0. by rewrite mul0r add0r; apply: val_inj=> /=; rewrite polyseq_cons // /nilp pn0. Qed. Fixpoint lead_coefT p : cps tF := if p is c :: q then 'let l <- lead_coefT q; 'if (l == 0) then c else l else ret 0%T. Lemma lead_coefTP (k : tF -> fF) : (forall x e, qf_eval e (k x) = qf_eval e (k (eval e x)%:T%T)) -> forall (p : polyF) (e : seq F), qf_eval e (lead_coefT p k) = qf_eval e (k (lead_coef (eval_poly e p))%:T%T). Proof. move=> kP p e; elim: p => [|a p IHp]/= in k kP e *. by rewrite lead_coef0 kP. rewrite IHp; last by move=> *; rewrite //= -kP. rewrite GRing.eval_If /= lead_coef_eq0. case p'0: (_ == _); first by rewrite (eqP p'0) mul0r add0r lead_coefC -kP. rewrite lead_coefDl ?lead_coefMX // polyseqC size_mul ?p'0 //; last first. by rewrite -size_poly_eq0 size_polyX. rewrite size_polyX addnC /=; case: (_ == _)=> //=. by rewrite ltnS lt0n size_poly_eq0 p'0. Qed. Lemma lead_coefT_qf (p : polyF) : rpoly p -> qf_cps (@rterm _) (lead_coefT p). Proof. elim: p => [_|c q ihp //= /andP[rc rq]]; first by apply: qf_cps_ret. apply: qf_cps_bind => [|y ty]; first exact: ihp. by apply: qf_cps_if; rewrite //= ty. Qed. Fixpoint amulXnT (a : tF) (n : nat) : polyF := if n is n'.+1 then 0%T :: (amulXnT a n') else [:: a]. Lemma eval_amulXnT (a : tF) (n : nat) (e : seq F) : eval_poly e (amulXnT a n) = (eval e a)%:P * 'X^n. Proof. elim: n=> [|n] /=; first by rewrite expr0 mulr1 mul0r add0r. by move->; rewrite addr0 -mulrA -exprSr. Qed. Lemma ramulXnT: forall a n, rterm a -> rpoly (amulXnT a n). Proof. by move=> a n; elim: n a=> [a /= -> //|n ihn a ra]; apply: ihn. Qed. Fixpoint sumpT (p q : polyF) := match p, q with a :: p, b :: q => (a + b)%T :: sumpT p q | [::], q => q | p, [::] => p end. Arguments sumpT : simpl nomatch. Lemma eval_sumpT (p q : polyF) (e : seq F) : eval_poly e (sumpT p q) = (eval_poly e p) + (eval_poly e q). Proof. elim: p q => [|a p Hp] q /=; first by rewrite add0r. case: q => [|b q] /=; first by rewrite addr0. rewrite Hp mulrDl -!addrA; congr (_ + _); rewrite polyCD addrC -addrA. by congr (_ + _); rewrite addrC. Qed. Lemma rsumpT (p q : polyF) : rpoly p -> rpoly q -> rpoly (sumpT p q). Proof. elim: p q=> [|a p ihp] q rp rq //; move: rp; case/andP=> ra rp. case: q rq => [|b q]; rewrite /= ?ra ?rp //=. by case/andP=> -> rq //=; apply: ihp. Qed. Fixpoint mulpT (p q : polyF) := if p isn't a :: p then [::] else sumpT [seq (a * x)%T | x <- q] (0%T :: mulpT p q). Lemma eval_mulpT (p q : polyF) (e : seq F) : eval_poly e (mulpT p q) = (eval_poly e p) * (eval_poly e q). Proof. elim: p q=> [|a p Hp] q /=; first by rewrite mul0r. rewrite eval_sumpT /= Hp addr0 mulrDl addrC mulrAC; congr (_ + _). by elim: q=> [|b q Hq] /=; rewrite ?mulr0 // Hq polyCM mulrDr mulrA. Qed. Lemma rpoly_map_mul (t : tF) (p : polyF) (rt : rterm t) : rpoly [seq (t * x)%T | x <- p] = rpoly p. Proof. by rewrite /rpoly all_map; apply/eq_all => x; rewrite /= rt. Qed. Lemma rmulpT (p q : polyF) : rpoly p -> rpoly q -> rpoly (mulpT p q). Proof. elim: p q=> [|a p ihp] q rp rq //=; move: rp; case/andP=> ra rp /=. apply: rsumpT; last exact: ihp. by rewrite rpoly_map_mul. Qed. Definition opppT : polyF -> polyF := map (GRing.Mul (- 1%T)%T). Lemma eval_opppT (p : polyF) (e : seq F) : eval_poly e (opppT p) = - eval_poly e p. Proof. by elim: p; rewrite /= ?oppr0 // => ? ? ->; rewrite !mulNr opprD polyCN mul1r. Qed. Definition natmulpT n : polyF -> polyF := map (GRing.Mul n%:R%T). Lemma eval_natmulpT (p : polyF) (n : nat) (e : seq F) : eval_poly e (natmulpT n p) = (eval_poly e p) *+ n. Proof. elim: p; rewrite //= ?mul0rn // => c p ->. rewrite mulrnDl mulr_natl polyCMn; congr (_ + _). by rewrite -mulr_natl mulrAC -mulrA mulr_natl mulrC. Qed. Fixpoint redivp_rec_loopT (q : polyF) sq cq (c : nat) (qq r : polyF) (n : nat) {struct n} : cps (nat * polyF * polyF) := 'let sr <- sizeT r; if sr < sq then ret (c, qq, r) else 'let lr <- lead_coefT r; let m := amulXnT lr (sr - sq) in let qq1 := sumpT (mulpT qq [::cq]) m in let r1 := sumpT (mulpT r ([::cq])) (opppT (mulpT m q)) in if n is n1.+1 then redivp_rec_loopT q sq cq c.+1 qq1 r1 n1 else ret (c.+1, qq1, r1). Fixpoint redivp_rec_loop (q : {poly F}) sq cq (k : nat) (qq r : {poly F}) (n : nat) {struct n} := if size r < sq then (k, qq, r) else let m := (lead_coef r) *: 'X^(size r - sq) in let qq1 := qq * cq%:P + m in let r1 := r * cq%:P - m * q in if n is n1.+1 then redivp_rec_loop q sq cq k.+1 qq1 r1 n1 else (k.+1, qq1, r1). Lemma redivp_rec_loopTP (k : nat * polyF * polyF -> fF) : (forall c qq r e, qf_eval e (k (c,qq,r)) = qf_eval e (k (c, lift (eval_poly e qq), lift (eval_poly e r)))) -> forall q sq cq c qq r n e (d := redivp_rec_loop (eval_poly e q) sq (eval e cq) c (eval_poly e qq) (eval_poly e r) n), qf_eval e (redivp_rec_loopT q sq cq c qq r n k) = qf_eval e (k (d.1.1, lift d.1.2, lift d.2)). Proof. move=> Pk q sq cq c qq r n e /=. elim: n c qq r k Pk e => [|n Pn] c qq r k Pk e; rewrite sizeTP. case ltrq : (_ < _); first by rewrite /= ltrq /= -Pk. rewrite lead_coefTP => [|a p]; rewrite [in LHS]Pk; [|symmetry]. rewrite ?(eval_mulpT,eval_amulXnT,eval_sumpT,eval_opppT) //=. by rewrite ltrq //= !mul_polyC ?(mul0r,add0r,scale0r). by rewrite [in LHS]Pk ?(eval_mulpT,eval_amulXnT,eval_sumpT, eval_opppT). case ltrq : (_<_); first by rewrite /= ltrq Pk. rewrite lead_coefTP. rewrite Pn ?(eval_mulpT,eval_amulXnT,eval_sumpT,eval_opppT) //=. by rewrite ltrq //= !mul_polyC ?(mul0r,add0r,scale0r). rewrite -/redivp_rec_loopT => x e'. rewrite Pn; last by move=> *; rewrite Pk. symmetry; rewrite Pn; last by move=> *; rewrite Pk. rewrite Pk ?(eval_lift,eval_mulpT,eval_amulXnT,eval_sumpT,eval_opppT). by rewrite mul_polyC ?(mul0r,add0r). Qed. Lemma redivp_rec_loopT_qf (q : polyF) (sq : nat) (cq : tF) (c : nat) (qq r : polyF) (n : nat) : rpoly q -> rterm cq -> rpoly qq -> rpoly r -> qf_cps (fun x => [&& rpoly x.1.2 & rpoly x.2]) (redivp_rec_loopT q sq cq c qq r n). Proof. do ![move=>x/(pair x){x}] => rw; elim: n => [|n IHn]//= in q sq cq c qq r rw *; apply: qf_cps_bind; do ?[by apply: sizeT_qf; rewrite !rw] => sr _; case: ifPn => // _; do ?[by apply: qf_cps_ret; rewrite //= ?rw]; apply: qf_cps_bind; do ?[by apply: lead_coefT_qf; rewrite !rw] => lr /= rlr; [apply: qf_cps_ret|apply: IHn]; by do !rewrite ?(rsumpT,rmulpT,ramulXnT,rpoly_map_mul,rlr,rw) //=. Qed. Definition redivpT (p : polyF) (q : polyF) : cps (nat * polyF * polyF) := 'let b <- isnull q; if b then ret (0, [::0%T], p) else 'let sq <- sizeT q; 'let sp <- sizeT p; 'let lq <- lead_coefT q; redivp_rec_loopT q sq lq 0 [::0%T] p sp. Lemma redivp_rec_loopP (q : {poly F}) (c : nat) (qq r : {poly F}) (n : nat) : redivp_rec q c qq r n = redivp_rec_loop q (size q) (lead_coef q) c qq r n. Proof. by elim: n c qq r => [| n Pn] c qq r //=; rewrite Pn. Qed. Lemma redivpTP (k : nat * polyF * polyF -> fF) : (forall c qq r e, qf_eval e (k (c,qq,r)) = qf_eval e (k (c, lift (eval_poly e qq), lift (eval_poly e r)))) -> forall p q e (d := redivp (eval_poly e p) (eval_poly e q)), qf_eval e (redivpT p q k) = qf_eval e (k (d.1.1, lift d.1.2, lift d.2)). Proof. move=> Pk p q e /=; rewrite isnullP unlock /=. case q0 : (eval_poly e q == 0) => /=; first by rewrite Pk /= mul0r add0r polyC0. rewrite !sizeTP lead_coefTP /=; last by move=> *; rewrite !redivp_rec_loopTP. rewrite redivp_rec_loopTP /=; last by move=> *; rewrite Pk. by rewrite mul0r add0r polyC0 redivp_rec_loopP. Qed. Lemma redivpT_qf (p : polyF) (q : polyF) : rpoly p -> rpoly q -> qf_cps (fun x => [&& rpoly x.1.2 & rpoly x.2]) (redivpT p q). Proof. move=> rp rq; apply: qf_cps_bind => [|[] _]; first exact: isnull_qf. by apply: qf_cps_ret. apply: qf_cps_bind => [|sp _]; first exact: sizeT_qf. apply: qf_cps_bind => [|sq _]; first exact: sizeT_qf. apply: qf_cps_bind => [|lq rlq]; first exact: lead_coefT_qf. by apply: redivp_rec_loopT_qf => //=. Qed. Definition rmodpT (p : polyF) (q : polyF) : cps polyF := 'let d <- redivpT p q; ret d.2. Definition rdivpT (p : polyF) (q : polyF) : cps polyF := 'let d <- redivpT p q; ret d.1.2. Definition rscalpT (p : polyF) (q : polyF) : cps nat := 'let d <- redivpT p q; ret d.1.1. Definition rdvdpT (p : polyF) (q : polyF) : cps bool := 'let d <- rmodpT p q; isnull d. Fixpoint rgcdp_loop n (pp qq : {poly F}) {struct n} := let rr := rmodp pp qq in if rr == 0 then qq else if n is n1.+1 then rgcdp_loop n1 qq rr else rr. Fixpoint rgcdp_loopT n (pp : polyF) (qq : polyF) : cps polyF := 'let rr <- rmodpT pp qq; 'let nrr <- isnull rr; if nrr then ret qq else if n is n1.+1 then rgcdp_loopT n1 qq rr else ret rr. Lemma rgcdp_loopP (k : polyF -> fF) : (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) -> forall n p q e, qf_eval e (rgcdp_loopT n p q k) = qf_eval e (k (lift (rgcdp_loop n (eval_poly e p) (eval_poly e q)))). Proof. move=> Pk n p q e; elim: n => /= [| m IHm] in p q e *; rewrite redivpTP /==> *; rewrite ?isnullP ?eval_lift -/(rmodp _ _); by case: (_ == _); do ?by rewrite -?Pk ?IHm ?eval_lift. Qed. Lemma rgcdp_loopT_qf (n : nat) (p : polyF) (q : polyF) : rpoly p -> rpoly q -> qf_cps rpoly (rgcdp_loopT n p q). Proof. elim: n => [|n IHn] in p q * => rp rq /=; (apply: qf_cps_bind=> [|rr rrr]; [ apply: qf_cps_bind => [|[[a u] v]]; do ?exact: redivpT_qf; by move=> /andP[/= ??]; apply: (@qf_cps_ret _ rpoly)| apply: qf_cps_bind => [|[] _]; by [apply: isnull_qf|apply: qf_cps_ret|apply: IHn]]). Qed. Definition rgcdpT (p : polyF) (q : polyF) : cps polyF := let aux p1 q1 : cps polyF := 'let b <- isnull p1; if b then ret q1 else 'let n <- sizeT p1; rgcdp_loopT n p1 q1 in 'let b <- lt_sizeT p q; if b then aux q p else aux p q. Lemma rgcdpTP (k : polyF -> fF) : (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) -> forall p q e, qf_eval e (rgcdpT p q k) = qf_eval e (k (lift (rgcdp (eval_poly e p) (eval_poly e q)))). Proof. move=> Pk p q e; rewrite /rgcdpT /rgcdp !sizeTP /=. case: (_ < _); rewrite !isnullP /=; case: (_ == _); rewrite -?Pk ?sizeTP; by rewrite ?rgcdp_loopP. Qed. Lemma rgcdpT_qf (p : polyF) (q : polyF) : rpoly p -> rpoly q -> qf_cps rpoly (rgcdpT p q). Proof. move=> rp rq k kP; rewrite /rgcdpT /=; do ![rewrite sizeT_qf => // ? _]. case: (_ < _); rewrite ?isnull_qf // => -[]; rewrite ?kP // => _; by rewrite sizeT_qf => // ? _; rewrite rgcdp_loopT_qf. Qed. Fixpoint rgcdpTs (ps : seq polyF) : cps polyF := if ps is p :: pr then 'let pr <- rgcdpTs pr; rgcdpT p pr else ret [::0%T]. Lemma rgcdpTsP (k : polyF -> fF) : (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) -> forall ps e, qf_eval e (rgcdpTs ps k) = qf_eval e (k (lift (\big[@rgcdp _/0%:P]_(i <- ps)(eval_poly e i)))). Proof. move=> Pk ps e; elim: ps k Pk => [|p ps Pps] /= k Pk. by rewrite /= big_nil Pk /= mul0r add0r. by rewrite big_cons Pps => *; rewrite !rgcdpTP // !eval_lift -?Pk. Qed. Lemma rgcdpTs_qf (ps : seq polyF) : all rpoly ps -> qf_cps rpoly (rgcdpTs ps). Proof. elim: ps => [_|c p ihp /andP[rc rp]] //=; first exact: qf_cps_ret. by apply: qf_cps_bind => [|r rr]; [apply: ihp|apply: rgcdpT_qf]. Qed. Fixpoint rgdcop_recT n (q : polyF) (p : polyF) := if n is m.+1 then 'let g <- rgcdpT p q; 'let sg <- sizeT g; if sg == 1 then ret p else 'let r <- rdivpT p g; rgdcop_recT m q r else 'let b <- isnull q; ret [::b%:R%T]. Lemma rgdcop_recTP (k : polyF -> fF) : (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) -> forall p q n e, qf_eval e (rgdcop_recT n p q k) = qf_eval e (k (lift (rgdcop_rec (eval_poly e p) (eval_poly e q) n))). Proof. move=> Pk p q n e; elim: n => [|n Pn] /= in k Pk p q e *. rewrite isnullP /=. by case: (_ == _); rewrite Pk /= mul0r add0r ?(polyC0, polyC1). rewrite /rcoprimep rgcdpTP ?sizeTP ?eval_lift => * /=. case: (_ == _); by do ?[rewrite /= ?(=^~Pk, redivpTP, rgcdpTP, sizeTP, Pn, eval_lift) //==> *]. do ?[rewrite /= ?(=^~Pk, redivpTP, rgcdpTP, sizeTP, Pn, eval_lift) //==> *]. case: (_ == _); by do ?[rewrite /= ?(=^~Pk, redivpTP, rgcdpTP, sizeTP, Pn, eval_lift) //==> *]. Qed. Lemma rgdcop_recT_qf (n : nat) (p : polyF) (q : polyF) : rpoly p -> rpoly q -> qf_cps rpoly (rgdcop_recT n p q). Proof. elim: n => [|n ihn] in p q * => k kP rp rq /=. by rewrite isnull_qf => //*; rewrite rq. rewrite rgcdpT_qf=> //*; rewrite sizeT_qf=> //*. case: (_ == _); rewrite ?kP ?rq //= redivpT_qf=> //= ? /andP[??]. by rewrite ihn. Qed. Definition rgdcopT q p := 'let sp <- sizeT p; rgdcop_recT sp q p. Lemma rgdcopTP (k : polyF -> fF) : (forall p e, qf_eval e (k p) = qf_eval e (k (lift (eval_poly e p)))) -> forall p q e, qf_eval e (rgdcopT p q k) = qf_eval e (k (lift (rgdcop (eval_poly e p) (eval_poly e q)))). Proof. by move=> *; rewrite sizeTP rgdcop_recTP 1?Pk. Qed. Lemma rgdcopT_qf (p : polyF) (q : polyF) : rpoly p -> rpoly q -> qf_cps rpoly (rgdcopT p q). Proof. by move=> rp rq k kP; rewrite sizeT_qf => //*; rewrite rgdcop_recT_qf. Qed. Definition ex_elim_seq (ps : seq polyF) (q : polyF) : fF := ('let g <- rgcdpTs ps; 'let d <- rgdcopT q g; 'let n <- sizeT d; ret (n != 1)) GRing.Bool. Lemma ex_elim_seqP (ps : seq polyF) (q : polyF) (e : seq F) : let gp := (\big[@rgcdp _/0%:P]_(p <- ps)(eval_poly e p)) in qf_eval e (ex_elim_seq ps q) = (size (rgdcop (eval_poly e q) gp) != 1). Proof. by do ![rewrite (rgcdpTsP,rgdcopTP,sizeTP,eval_lift) //= | move=> * //=]. Qed. Lemma ex_elim_seq_qf (ps : seq polyF) (q : polyF) : all rpoly ps -> rpoly q -> qf (ex_elim_seq ps q). Proof. move=> rps rq; apply: rgcdpTs_qf=> // g rg; apply: rgdcopT_qf=> // d rd. exact : sizeT_qf. Qed. Fixpoint abstrX (i : nat) (t : tF) := match t with | 'X_n => if n == i then [::0; 1] else [::t] | - x => opppT (abstrX i x) | x + y => sumpT (abstrX i x) (abstrX i y) | x * y => mulpT (abstrX i x) (abstrX i y) | x *+ n => natmulpT n (abstrX i x) | x ^+ n => let ax := (abstrX i x) in iter n (mulpT ax) [::1] | _ => [::t] end%T. Lemma abstrXP (i : nat) (t : tF) (e : seq F) (x : F) : rterm t -> (eval_poly e (abstrX i t)).[x] = eval (set_nth 0 e i x) t. Proof. elim: t => [n | r | n | t tP s sP | t tP | t tP n | t tP s sP | t tP | t tP n] h. - move=> /=; case ni: (_ == _); rewrite //= ?(mul0r,add0r,addr0,polyC1,mul1r,hornerX,hornerC); by rewrite // nth_set_nth /= ni. - by rewrite /= mul0r add0r hornerC. - by rewrite /= mul0r add0r hornerC. - by case/andP: h => *; rewrite /= eval_sumpT hornerD tP ?sP. - by rewrite /= eval_opppT hornerN tP. - by rewrite /= eval_natmulpT hornerMn tP. - by case/andP: h => *; rewrite /= eval_mulpT hornerM tP ?sP. - by []. - elim: n h => [|n ihn] rt; first by rewrite /= expr0 mul0r add0r hornerC. by rewrite /= eval_mulpT exprSr hornerM ihn // mulrC tP. Qed. Lemma rabstrX (i : nat) (t : tF) : rterm t -> rpoly (abstrX i t). Proof. elim: t; do ?[ by move=> * //=; do ?case: (_ == _)]. - move=> t irt s irs /=; case/andP=> rt rs. by apply: rsumpT; rewrite ?irt ?irs //. - by move=> t irt /= rt; rewrite rpoly_map_mul ?irt //. - by move=> t irt /= n rt; rewrite rpoly_map_mul ?irt //. - move=> t irt s irs /=; case/andP=> rt rs. by apply: rmulpT; rewrite ?irt ?irs //. - move=> t irt /= n rt; move: (irt rt) => {}rt; elim: n => [|n ihn] //=. exact: rmulpT. Qed. Implicit Types tx ty : tF. Lemma abstrX_mulM (i : nat) : {morph abstrX i : x y / x * y >-> mulpT x y}%T. Proof. by []. Qed. Lemma abstrX1 (i : nat) : abstrX i 1%T = [::1%T]. Proof. done. Qed. Lemma eval_poly_mulM e : {morph eval_poly e : x y / mulpT x y >-> x * y}. Proof. by move=> x y; rewrite eval_mulpT. Qed. Lemma eval_poly1 e : eval_poly e [::1%T] = 1. Proof. by rewrite /= mul0r add0r. Qed. Notation abstrX_bigmul := (big_morph _ (abstrX_mulM _) (abstrX1 _)). Notation eval_bigmul := (big_morph _ (eval_poly_mulM _) (eval_poly1 _)). Notation bigmap_id := (big_map _ (fun _ => true) id). Lemma rseq_poly_map (x : nat) (ts : seq tF) : all (@rterm _) ts -> all rpoly (map (abstrX x) ts). Proof. by elim: ts => //= t ts iht; case/andP=> rt rts; rewrite rabstrX // iht. Qed. Definition ex_elim (x : nat) (pqs : seq tF * seq tF) := ex_elim_seq (map (abstrX x) pqs.1) (abstrX x (\big[GRing.Mul/1%T]_(q <- pqs.2) q)). Lemma ex_elim_qf (x : nat) (pqs : seq tF * seq tF) : GRing.dnf_rterm pqs -> qf (ex_elim x pqs). case: pqs => ps qs; case/andP=> /= rps rqs. apply: ex_elim_seq_qf; first exact: rseq_poly_map. apply: rabstrX=> /=. elim: qs rqs=> [|t ts iht] //=; first by rewrite big_nil. by case/andP=> rt rts; rewrite big_cons /= rt /= iht. Qed. Lemma holds_conj : forall e i x ps, all (@rterm _) ps -> (GRing.holds (set_nth 0 e i x) (foldr (fun t : tF => GRing.And (t == 0)) GRing.True%T ps) <-> all ((@root _)^~ x) (map (eval_poly e \o abstrX i) ps)). Proof. move=> e i x; elim=> [|p ps ihps] //=. case/andP=> rp rps; rewrite rootE abstrXP //. constructor; first by case=> -> hps; rewrite eqxx /=; apply/ihps. by case/andP; move/eqP=> -> psr; split=> //; apply/ihps. Qed. Lemma holds_conjn (e : seq F) (i : nat) (x : F) (ps : seq tF) : all (@rterm _) ps -> (GRing.holds (set_nth 0 e i x) (foldr (fun t : tF => GRing.And (t != 0)) GRing.True ps) <-> all (fun p => ~~root p x) (map (eval_poly e \o abstrX i) ps)). Proof. elim: ps => [|p ps ihps] //=. case/andP=> rp rps; rewrite rootE abstrXP //. constructor; first by case=> /eqP-> hps /=; apply/ihps. by case/andP=> pr psr; split; first apply/eqP=> //; apply/ihps. Qed. Lemma holds_ex_elim: GRing.valid_QE_proj ex_elim. Proof. move=> i [ps qs] /= e; case/andP=> /= rps rqs. rewrite ex_elim_seqP big_map. have -> : \big[@rgcdp _/0%:P]_(j <- ps) eval_poly e (abstrX i j) = \big[@rgcdp _/0%:P]_(j <- (map (eval_poly e) (map (abstrX i) (ps)))) j. by rewrite !big_map. rewrite -!map_comp. have aux I (l : seq I) (P : I -> {poly F}) : \big[(@gcdp F)/0]_(j <- l) P j %= \big[(@rgcdp F)/0]_(j <- l) P j. elim: l => [| u l ihl] /=; first by rewrite !big_nil eqpxx. rewrite !big_cons; move: ihl; move/(eqp_gcdr (P u)) => h. by apply: eqp_trans h _; rewrite eqp_sym; apply: eqp_rgcd_gcd. case g0: (\big[(@rgcdp F)/0%:P]_(j <- map (eval_poly e \o abstrX i) ps) j == 0). rewrite (eqP g0) rgdcop0. case m0 : (_ == 0)=> //=; rewrite ?(size_poly1,size_poly0) //=. rewrite abstrX_bigmul eval_bigmul -bigmap_id in m0. constructor=> [[x] // []] //. case=> _; move/holds_conjn=> hc; move/hc:rqs. by rewrite -root_bigmul //= (eqP m0) root0. constructor; move/negP:m0; move/negP=>m0. case: (closed_nonrootP F_closed _ m0) => x {m0}. rewrite abstrX_bigmul eval_bigmul -bigmap_id root_bigmul=> m0. exists x; do 2?constructor=> //; last by apply/holds_conjn. apply/holds_conj; rewrite //= -root_biggcd. by rewrite (eqp_root (aux _ _ _ )) (eqP g0) root0. apply: (iffP (closed_rootP F_closed _)) => -[x Px]; exists x; move: Px => //=. rewrite (eqp_root (@eqp_rgdco_gdco F _ _)) root_gdco ?g0 //. rewrite -(eqp_root (aux _ _ _ )) root_biggcd abstrX_bigmul eval_bigmul. rewrite -bigmap_id root_bigmul; case/andP=> psr qsr. do 2?constructor; first by apply/holds_conj. by apply/holds_conjn. rewrite (eqp_root(@eqp_rgdco_gdco F _ _)) root_gdco?g0// -(eqp_root(aux _ _ _)). rewrite root_biggcd abstrX_bigmul eval_bigmul -bigmap_id. rewrite root_bigmul=> [[] // [hps hqs]]; apply/andP. constructor; first by apply/holds_conj. by apply/holds_conjn. Qed. Lemma wf_ex_elim : GRing.wf_QE_proj ex_elim. Proof. by move=> i bc /= rbc; apply: ex_elim_qf. Qed. End ClosedFieldQE. End ClosedFieldQE. HB.factory Record Field_isAlgClosed F of GRing.Field F := { solve_monicpoly : GRing.closed_field_axiom F; }. HB.builders Context F of Field_isAlgClosed F. HB.instance Definition _ := GRing.Field_QE_isDecField.Build F (@ClosedFieldQE.wf_ex_elim F) (ClosedFieldQE.holds_ex_elim solve_monicpoly). HB.instance Definition _ := GRing.DecField_isAlgClosed.Build F solve_monicpoly. HB.end. Import CodeSeq. Lemma countable_field_extension (F : countFieldType) (p : {poly F}) : size p > 1 -> {E : countFieldType & {FtoE : {rmorphism F -> E} & {w : E | root (map_poly FtoE p) w & forall u : E, exists q, u = (map_poly FtoE q).[w]}}}. Proof. pose fix d i := if i is i1.+1 then let d1 := oapp (gcdp (d i1)) 0 (unpickle i1) in if size d1 > 1 then d1 else d i1 else p. move=> p_gt1; have sz_d i: size (d i) > 1 by elim: i => //= i IHi; case: ifP. have dv_d i j: i <= j -> d j %| d i. move/subnK <-; elim: {j}(j - i)%N => //= j IHj; case: ifP => //=. case: (unpickle _) => /= [q _|]; last by rewrite size_poly0. exact: dvdp_trans (dvdp_gcdl _ _) IHj. pose I : pred {poly F} := [pred q | d (pickle q).+1 %| q]. have I'co q i: q \notin I -> i > pickle q -> coprimep q (d i). rewrite inE => I'q /dv_d/coprimep_dvdl-> //; apply: contraR I'q. rewrite coprimep_sym /coprimep /= pickleK /= neq_ltn. case: ifP => [_ _| ->]; first exact: dvdp_gcdr. rewrite orbF ltnS leqn0 size_poly_eq0 gcdp_eq0 -size_poly_eq0. by rewrite -leqn0 leqNgt ltnW //. have memI q: reflect (exists i, d i %| q) (q \in I). apply: (iffP idP) => [|[i dv_di_q]]; first by exists (pickle q).+1. have [le_i_q | /I'co i_co_q] := leqP i (pickle q). rewrite inE /= pickleK /=; case: ifP => _; first exact: dvdp_gcdr. exact: dvdp_trans (dv_d _ _ le_i_q) dv_di_q. apply: contraR i_co_q _. by rewrite /coprimep (eqp_size (dvdp_gcd_idr dv_di_q)) neq_ltn sz_d orbT. have I_ideal : idealr_closed I. split=> [||a q1 q2 Iq1 Iq2]; first exact: dvdp0. by apply/memI=> [[i /idPn[]]]; rewrite dvdp1 neq_ltn sz_d orbT. apply/memI; exists (maxn (pickle q1).+1 (pickle q2).+1); apply: dvdp_add. by apply: dvdp_mull; apply: dvdp_trans Iq1; apply/dv_d/leq_maxl. by apply: dvdp_trans Iq2; apply/dv_d/leq_maxr. pose IaM := GRing.isZmodClosed.Build _ I (idealr_closedB I_ideal). pose IpM := isProperIdeal.Build _ I (idealr_closed_nontrivial I_ideal). pose Iid : idealr _ := HB.pack I IaM IpM. pose E : comNzRingType := {ideal_quot Iid}. pose PtoE : {rmorphism {poly F} -> E} := \pi_E%qT. have PtoEd i: PtoE (d i) = 0. by apply/eqP; rewrite piE Quotient.equivE subr0; apply/memI; exists i. pose Einv (z : E) (q := repr z) (dq := d (pickle q).+1) := let q_unitP := Bezout_eq1_coprimepP q dq in if q_unitP is ReflectT ex_uv then PtoE (sval (sig_eqW ex_uv)).1 else 0. have Einv0 : Einv 0 = 0. rewrite /Einv; case: Bezout_eq1_coprimepP => // ex_uv. case/negP: (oner_neq0 E); rewrite [X in X == _]piE. rewrite /= -[_ 1]/(PtoE 1); have [uv <-] := ex_uv. by rewrite rmorphD !rmorphM [X in _ + _ * X]PtoEd /= reprK !mulr0 addr0. have EmulV : forall x, x != 0 -> Einv x * x = 1. rewrite /Einv=> z nz_z; case: Bezout_eq1_coprimepP => [ex_uv |]; last first. move/Bezout_eq1_coprimepP; rewrite I'co //. by rewrite piE -{1}[z]reprK -Quotient.idealrBE subr0 in nz_z. apply/eqP; case: sig_eqW => {ex_uv} [uv uv1]; set i := _.+1 in uv1 *. rewrite piE /= -[z]reprK -(rmorphM PtoE) -Quotient.idealrBE. rewrite -[X in _ - X]uv1 opprD addNKr -mulNr. by apply/memI; exists i; apply: dvdp_mull. pose EfieldMixin := GRing.ComNzRing_isField.Build _ EmulV Einv0. pose Efield : fieldType := HB.pack E EfieldMixin. pose EIsCountable := isCountable.Build E (pcan_pickleK (can_pcan (reprK))). pose Ecount : countFieldType := HB.pack E Efield EIsCountable. pose FtoE : {rmorphism _ -> _} := PtoE \o polyC; pose w : E := PtoE 'X. have defPtoE q: (map_poly FtoE q).[w] = PtoE q. by rewrite (map_poly_comp PtoE polyC) horner_map [_.['X]]comp_polyXr. exists Ecount, FtoE, w => [|u]. by rewrite /root defPtoE (PtoEd 0). by exists (repr u); rewrite defPtoE /= reprK. Qed. Lemma countable_algebraic_closure (F : countFieldType) : {K : countClosedFieldType & {FtoK : {rmorphism F -> K} | integralRange FtoK}}. Proof. pose minXp (R : nzRingType) (p : {poly R}) := if size p > 1 then p else 'X. have minXp_gt1 R p: size (minXp R p) > 1. by rewrite /minXp; case: ifP => // _; rewrite size_polyX. have minXpE (R : nzRingType) (p : {poly R}) : size p > 1 -> minXp R p = p. by rewrite /minXp => ->. have ext1 p := countable_field_extension (minXp_gt1 _ p). pose ext1fT E p := tag (ext1 E p). pose ext1to E p : {rmorphism _ -> ext1fT E p} := tag (tagged (ext1 E p)). pose ext1w E p : ext1fT E p := s2val (tagged (tagged (ext1 E p))). have ext1root E p: root (map_poly (ext1to E p) (minXp E p)) (ext1w E p). by rewrite /ext1w; case: (tagged (tagged (ext1 E p))). have ext1gen E p u: {q | u = (map_poly (ext1to E p) q).[ext1w E p]}. by apply: sig_eqW; rewrite /ext1w; case: (tagged (tagged (ext1 E p))) u. pose pExtEnum (E : countFieldType) := nat -> {poly E}. pose Ext := {E : countFieldType & pExtEnum E}; pose MkExt : Ext := Tagged _ _. pose EtoInc (E : Ext) i := ext1to (tag E) (tagged E i). pose incEp E i j := let v := map_poly (EtoInc E i) (tagged E j) in if decode j is [:: i1; k] then if i1 == i then odflt v (unpickle k) else v else v. pose fix E_ i := if i is i1.+1 then MkExt _ (incEp (E_ i1) i1) else MkExt F \0. pose E i := tag (E_ i); pose Krep := {i : nat & E i}. pose fix toEadd i k : {rmorphism E i -> E (k + i)%N} := if k isn't k1.+1 then idfun else EtoInc _ (k1 + i)%N \o toEadd _ _. pose toE i j (le_ij : i <= j) := ecast j {rmorphism E i -> E j} (subnK le_ij) (toEadd i (j - i)%N). have toEeq i le_ii: toE i i le_ii =1 id. by rewrite /toE; move: (subnK _); rewrite subnn => ?; rewrite eq_axiomK. have toEleS i j leij leiSj z: toE i j.+1 leiSj z = EtoInc _ _ (toE i j leij z). rewrite /toE; move: (j - i)%N {leij leiSj}(subnK _) (subnK _) => k. by case: j /; rewrite (addnK i k.+1) => eq_kk; rewrite [eq_kk]eq_axiomK. have toEirr := congr1 ((toE _ _)^~ _) (bool_irrelevance _ _). have toEtrans j i k leij lejk leik z: toE i k leik z = toE j k lejk (toE i j leij z). - elim: k leik lejk => [|k IHk] leiSk lejSk. by case: j => // in leij lejSk *; rewrite toEeq. have:= lejSk; rewrite {1}leq_eqVlt ltnS => /predU1P[Dk | lejk]. by rewrite -Dk in leiSk lejSk *; rewrite toEeq. by have leik := leq_trans leij lejk; rewrite !toEleS -IHk. have [leMl leMr] := (leq_maxl, leq_maxr); pose le_max := (leq_max, leqnn, orbT). pose pairK (x y : Krep) (m := maxn _ _) := (toE _ m (leMl _ _) (tagged x), toE _ m (leMr _ _) (tagged y)). pose eqKrep x y := uncurry (@eq_op _) (pairK x y). have eqKrefl : reflexive eqKrep by move=> z; apply/eqP; apply: toEirr. have eqKsym : symmetric eqKrep. move=> z1 z2; rewrite {1}/eqKrep /= eq_sym; move: (leMl _ _) (leMr _ _). by rewrite maxnC => lez1m lez2m; congr (_ == _); apply: toEirr. have eqKtrans : transitive eqKrep. rewrite /eqKrep /= => z2 z1 z3 /eqP eq_z12 /eqP eq_z23. rewrite -(inj_eq (fmorph_inj (toE _ _ (leMr (tag z2) _)))). rewrite -!toEtrans ?le_max // maxnCA maxnA => lez3m lez1m. rewrite {lez1m}(toEtrans (maxn (tag z1) (tag z2))) // {}eq_z12. do [rewrite -toEtrans ?le_max // -maxnA => lez2m] in lez3m *. by rewrite (toEtrans (maxn (tag z2) (tag z3))) // eq_z23 -toEtrans. pose K := {eq_quot EquivRel _ eqKrefl eqKsym eqKtrans}%qT. pose cntK := isCountable.Build K (pcan_pickleK (can_pcan (reprK))). pose EtoKrep i (x : E i) : K := \pi%qT (Tagged E x). have [EtoK piEtoK]: {EtoK | forall i, EtoKrep i =1 EtoK i} by exists EtoKrep. pose FtoK := EtoK 0; rewrite {}/EtoKrep in piEtoK. have eqEtoK i j x y: toE i _ (leMl i j) x = toE j _ (leMr i j) y -> EtoK i x = EtoK j y. - by move/eqP=> eq_xy; rewrite -!piEtoK; apply/eqmodP. have toEtoK j i leij x : EtoK j (toE i j leij x) = EtoK i x. by apply: eqEtoK; rewrite -toEtrans. have EtoK_0 i: EtoK i 0 = FtoK 0 by apply: eqEtoK; rewrite !rmorph0. have EtoK_1 i: EtoK i 1 = FtoK 1 by apply: eqEtoK; rewrite !rmorph1. have EtoKeq0 i x: (EtoK i x == FtoK 0) = (x == 0). by rewrite /FtoK -!piEtoK eqmodE /= /eqKrep /= rmorph0 fmorph_eq0. have toErepr m i leim x lerm: toE _ m lerm (tagged (repr (EtoK i x))) = toE i m leim x. - have: (Tagged E x == repr (EtoK i x) %[mod K])%qT by rewrite reprK piEtoK. rewrite eqmodE /= /eqKrep; case: (repr _) => j y /= in lerm * => /eqP /=. have leijm: maxn i j <= m by rewrite geq_max leim. by move/(congr1 (toE _ _ leijm)); rewrite -!toEtrans. pose Kadd (x y : K) := EtoK _ (uncurry +%R (pairK (repr x) (repr y))). pose Kopp (x : K) := EtoK _ (- tagged (repr x)). pose Kmul (x y : K) := EtoK _ (uncurry *%R (pairK (repr x) (repr y))). pose Kinv (x : K) := EtoK _ (tagged (repr x))^-1. have EtoK_D i: {morph EtoK i : x y / x + y >-> Kadd x y}. move=> x y; apply: eqEtoK; set j := maxn (tag _) _; rewrite !rmorphD. rewrite -![X in _ = X + _]toEtrans ?le_max// => lexm. rewrite -![X in _ = _ + X]toEtrans ?le_max// => leym. by rewrite !toErepr. have EtoK_N i: {morph EtoK i : x / - x >-> Kopp x}. by move=> x; apply: eqEtoK; set j := tag _; rewrite !rmorphN toErepr. have EtoK_M i: {morph EtoK i : x y / x * y >-> Kmul x y}. move=> x y; apply: eqEtoK; set j := maxn (tag _) _; rewrite !rmorphM. rewrite -![X in _ = X * _]toEtrans ?le_max// => lexm. rewrite -![X in _ = _ * X]toEtrans ?le_max// => leym. by rewrite !toErepr. have EtoK_V i: {morph EtoK i : x / x^-1 >-> Kinv x}. by move=> x; apply: eqEtoK; set j := tag _; rewrite !fmorphV toErepr. case: {toErepr}I in (Kadd) (Kopp) (Kmul) (Kinv) EtoK_D EtoK_N EtoK_M EtoK_V. pose inEi i z := {x : E i | z = EtoK i x}; have KtoE z: {i : nat & inEi i z}. by elim/quotW: z => [[i x] /=]; exists i, x; rewrite piEtoK. have inEle i j z: i <= j -> inEi i z -> inEi j z. by move=> leij [x ->]; exists (toE i j leij x); rewrite toEtoK. have KtoE2 z1 z2: {i : nat & inEi i z1 & inEi i z2}. have [[i1 Ez1] [i2 Ez2]] := (KtoE z1, KtoE z2). by exists (maxn i1 i2); [apply: inEle Ez1 | apply: inEle Ez2]. have KtoE3 z1 z2 z3: {i : nat & inEi i z1 & inEi i z2 * inEi i z3}%type. have [[i1 Ez1] [i2 Ez2 Ez3]] := (KtoE z1, KtoE2 z2 z3). by exists (maxn i1 i2); [apply: inEle Ez1 | split; apply: inEle (leMr _ _) _]. have KaddC: commutative Kadd. by move=> u v; have [i [x ->] [y ->]] := KtoE2 u v; rewrite -!EtoK_D addrC. have KaddA: associative Kadd. move=> u v w; have [i [x ->] [[y ->] [z ->]]] := KtoE3 u v w. by rewrite -!EtoK_D addrA. have Kadd0: left_id (FtoK 0) Kadd. by move=> u; have [i [x ->]] := KtoE u; rewrite -(EtoK_0 i) -EtoK_D add0r. have KaddN: left_inverse (FtoK 0) Kopp Kadd. by move=> u; have [i [x ->]] := KtoE u; rewrite -EtoK_N -EtoK_D addNr EtoK_0. pose KzmodMixin := GRing.isZmodule.Build K KaddA KaddC Kadd0 KaddN. pose Kzmod : countZmodType := HB.pack K KzmodMixin. have KmulC: commutative Kmul. by move=> u v; have [i [x ->] [y ->]] := KtoE2 u v; rewrite -!EtoK_M mulrC. have KmulA: @associative Kzmod Kmul. move=> u v w; have [i [x ->] [[y ->] [z ->]]] := KtoE3 u v w. by rewrite -!EtoK_M mulrA. have Kmul1: left_id (FtoK 1) Kmul. by move=> u; have [i [x ->]] := KtoE u; rewrite -(EtoK_1 i) -EtoK_M mul1r. have KmulD: left_distributive Kmul Kadd. move=> u v w; have [i [x ->] [[y ->] [z ->]]] := KtoE3 u v w. by rewrite -!(EtoK_M, EtoK_D) mulrDl. have Kone_nz: FtoK 1 != FtoK 0 by rewrite EtoKeq0 oner_neq0. pose KringMixin := GRing.Zmodule_isComNzRing.Build _ KmulA KmulC Kmul1 KmulD Kone_nz. pose Kring : comNzRingType := HB.pack K Kzmod KringMixin cntK. have KmulV: forall x : Kring, x != 0 -> (Kinv x : Kring) * x = 1. move=> u; have [i [x ->]] := KtoE u; rewrite EtoKeq0 => nz_x. by rewrite -EtoK_V -[_ * _]EtoK_M mulVf ?EtoK_1. have Kinv0: Kinv (FtoK 0) = FtoK 0 by rewrite -EtoK_V invr0. pose KfieldMixin := GRing.ComNzRing_isField.Build _ KmulV Kinv0. pose Kfield : fieldType := HB.pack K Kring KfieldMixin. have EtoKAdd i : zmod_morphism (EtoK i : E i -> Kfield). by move=> x y; rewrite EtoK_D EtoK_N. have EtoKMul i : monoid_morphism (EtoK i : E i -> Kfield). by split=> [|x y]; rewrite ?EtoK_M ?EtoK_1. pose EtoKMa i := GRing.isZmodMorphism.Build _ _ _ (EtoKAdd i). pose EtoKMm i := GRing.isMonoidMorphism.Build _ _ _ (EtoKMul i). pose EtoKM i : {rmorphism _ -> _} := HB.pack (EtoK i : E i -> Kfield) (EtoKMa i) (EtoKMm i). have EtoK_E: EtoK _ = EtoKM _ by []. have toEtoKp := @eq_map_poly _ Kring _ _(toEtoK _ _ _). have Kclosed: GRing.closed_field_axiom Kfield. move=> n pK n_gt0; pose m0 := \max_(i < n) tag (KtoE (pK i)); pose m := m0.+1. have /fin_all_exists[pE DpE] (i : 'I_n): exists y, EtoK m y = pK i. pose u := KtoE (pK i); have leum0: tag u <= m0 by rewrite (bigmax_sup i). by have [y ->] := tagged u; exists (toE _ _ (leqW leum0) y); rewrite toEtoK. pose p := 'X^n - rVpoly (\row_i pE i); pose j := code [:: m0; pickle p]. pose pj := tagged (E_ j) j; pose w : E j.+1 := ext1w (E j) pj. have lemj: m <= j by rewrite (allP (ltn_code _)) ?mem_head. exists (EtoKM j.+1 w); apply/eqP; rewrite -subr_eq0; apply/eqP. transitivity (EtoKM j.+1 (map_poly (toE m j.+1 (leqW lemj)) p).[w]). rewrite -horner_map -map_poly_comp toEtoKp EtoK_E. move: (EtoKM j.+1 w) => {}w. rewrite rmorphB [_ 'X^n]map_polyXn !hornerE; congr (_ - _ : Kring). rewrite (@horner_coef_wide _ n) ?size_map_poly ?size_poly //. by apply: eq_bigr => i _; rewrite coef_map coef_rVpoly valK mxE /= DpE. suffices Dpj: map_poly (toE m j lemj) p = pj. apply/eqP; rewrite EtoKeq0 (eq_map_poly (toEleS _ _ _ _)) map_poly_comp Dpj. rewrite -rootE -[pj]minXpE ?ext1root // -Dpj size_map_poly. by rewrite size_polyDl ?size_polyXn ltnS ?size_polyN ?size_poly. rewrite {w}/pj; set j0 := (j in tagged (E_ _) j). elim: {+}j lemj => // k IHk lemSk; rewrite {}/j0 in IHk *. have:= lemSk; rewrite leq_eqVlt ltnS => /predU1P[Dm | lemk]. rewrite -{}Dm in lemSk *; rewrite {k IHk lemSk}(eq_map_poly (toEeq m _)). by rewrite map_poly_id //= /incEp codeK eqxx pickleK. rewrite (eq_map_poly (toEleS _ _ _ _)) map_poly_comp {}IHk //= /incEp codeK. by rewrite -if_neg neq_ltn lemk. suffices{Kclosed} algF_K: {FtoK : {rmorphism F -> Kfield} | integralRange FtoK}. pose Kcc := Field_isAlgClosed.Build Kfield Kclosed. by exists (HB.pack_for countClosedFieldType K Kfield Kcc). exists (EtoKM 0) => /= z; have [i [{}z ->]] := KtoE z. suffices{z} /(_ z)[p mon_p]: integralRange (toE 0 i isT). by rewrite -(fmorph_root (EtoKM i)) -map_poly_comp toEtoKp; exists p. rewrite /toE /E; clear - minXp_gt1 ext1root ext1gen. move: (i - 0)%N (subnK _) => n; case: i /. elim: n => [|n IHn] /= z; first exact: integral_id. have{z} [q ->] := ext1gen _ _ z; set pn := tagged (E_ _) _. apply: integral_horner. by apply/integral_poly=> i; rewrite coef_map; apply: integral_rmorph. apply: integral_root (ext1root _ _) _. by rewrite map_poly_eq0 -size_poly_gt0 ltnW. by apply/integral_poly=> i; rewrite coef_map; apply: integral_rmorph. Qed.
W.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import Mathlib.Data.PFunctor.Multivariate.Basic /-! # The W construction as a multivariate polynomial functor. W types are well-founded tree-like structures. They are defined as the least fixpoint of a polynomial functor. ## Main definitions * `W_mk` - constructor * `W_dest - destructor * `W_rec` - recursor: basis for defining functions by structural recursion on `P.W α` * `W_rec_eq` - defining equation for `W_rec` * `W_ind` - induction principle for `P.W α` ## Implementation notes Three views of M-types: * `wp`: polynomial functor * `W`: data type inductively defined by a triple: shape of the root, data in the root and children of the root * `W`: least fixed point of a polynomial functor Specifically, we define the polynomial functor `wp` as: * A := a tree-like structure without information in the nodes * B := given the tree-like structure `t`, `B t` is a valid path (specified inductively by `W_path`) from the root of `t` to any given node. As a result `wp α` is made of a dataless tree and a function from its valid paths to values of `α` ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u v namespace MvPFunctor open TypeVec open MvFunctor variable {n : ℕ} (P : MvPFunctor.{u} (n + 1)) /-- A path from the root of a tree to one of its node -/ inductive WPath : P.last.W → Fin2 n → Type u | root (a : P.A) (f : P.last.B a → P.last.W) (i : Fin2 n) (c : P.drop.B a i) : WPath ⟨a, f⟩ i | child (a : P.A) (f : P.last.B a → P.last.W) (i : Fin2 n) (j : P.last.B a) (c : WPath (f j) i) : WPath ⟨a, f⟩ i instance WPath.inhabited (x : P.last.W) {i} [I : Inhabited (P.drop.B x.head i)] : Inhabited (WPath P x i) := ⟨match x, I with | ⟨a, f⟩, I => WPath.root a f i (@default _ I)⟩ /-- Specialized destructor on `WPath` -/ def wPathCasesOn {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W} (g' : P.drop.B a ⟹ α) (g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) : P.WPath ⟨a, f⟩ ⟹ α := by intro i x match x with | WPath.root _ _ i c => exact g' i c | WPath.child _ _ i j c => exact g j i c /-- Specialized destructor on `WPath` -/ def wPathDestLeft {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W} (h : P.WPath ⟨a, f⟩ ⟹ α) : P.drop.B a ⟹ α := fun i c => h i (WPath.root a f i c) /-- Specialized destructor on `WPath` -/ def wPathDestRight {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W} (h : P.WPath ⟨a, f⟩ ⟹ α) : ∀ j : P.last.B a, P.WPath (f j) ⟹ α := fun j i c => h i (WPath.child a f i j c) theorem wPathDestLeft_wPathCasesOn {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W} (g' : P.drop.B a ⟹ α) (g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) : P.wPathDestLeft (P.wPathCasesOn g' g) = g' := rfl theorem wPathDestRight_wPathCasesOn {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W} (g' : P.drop.B a ⟹ α) (g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) : P.wPathDestRight (P.wPathCasesOn g' g) = g := rfl theorem wPathCasesOn_eta {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W} (h : P.WPath ⟨a, f⟩ ⟹ α) : P.wPathCasesOn (P.wPathDestLeft h) (P.wPathDestRight h) = h := by ext i x; cases x <;> rfl theorem comp_wPathCasesOn {α β : TypeVec n} (h : α ⟹ β) {a : P.A} {f : P.last.B a → P.last.W} (g' : P.drop.B a ⟹ α) (g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) : h ⊚ P.wPathCasesOn g' g = P.wPathCasesOn (h ⊚ g') fun i => h ⊚ g i := by ext i x; cases x <;> rfl /-- Polynomial functor for the W-type of `P`. `A` is a data-less well-founded tree whereas, for a given `a : A`, `B a` is a valid path in tree `a` so that `Wp.obj α` is made of a tree and a function from its valid paths to the values it contains -/ def wp : MvPFunctor n where A := P.last.W B := P.WPath /-- W-type of `P` -/ def W (α : TypeVec n) : Type _ := P.wp α instance mvfunctorW : MvFunctor P.W := by delta MvPFunctor.W; infer_instance /-! First, describe operations on `W` as a polynomial functor. -/ /-- Constructor for `wp` -/ def wpMk {α : TypeVec n} (a : P.A) (f : P.last.B a → P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ α) : P.W α := ⟨⟨a, f⟩, f'⟩ def wpRec {α : TypeVec n} {C : Type*} (g : ∀ (a : P.A) (f : P.last.B a → P.last.W), P.WPath ⟨a, f⟩ ⟹ α → (P.last.B a → C) → C) : ∀ (x : P.last.W) (_ : P.WPath x ⟹ α), C | ⟨a, f⟩, f' => g a f f' fun i => wpRec g (f i) (P.wPathDestRight f' i) theorem wpRec_eq {α : TypeVec n} {C : Type*} (g : ∀ (a : P.A) (f : P.last.B a → P.last.W), P.WPath ⟨a, f⟩ ⟹ α → (P.last.B a → C) → C) (a : P.A) (f : P.last.B a → P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ α) : P.wpRec g ⟨a, f⟩ f' = g a f f' fun i => P.wpRec g (f i) (P.wPathDestRight f' i) := rfl -- Note: we could replace Prop by Type* and obtain a dependent recursor theorem wp_ind {α : TypeVec n} {C : ∀ x : P.last.W, P.WPath x ⟹ α → Prop} (ih : ∀ (a : P.A) (f : P.last.B a → P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ α), (∀ i : P.last.B a, C (f i) (P.wPathDestRight f' i)) → C ⟨a, f⟩ f') : ∀ (x : P.last.W) (f' : P.WPath x ⟹ α), C x f' | ⟨a, f⟩, f' => ih a f f' fun _i => wp_ind ih _ _ /-! Now think of W as defined inductively by the data ⟨a, f', f⟩ where - `a : P.A` is the shape of the top node - `f' : P.drop.B a ⟹ α` is the contents of the top node - `f : P.last.B a → P.last.W` are the subtrees -/ /-- Constructor for `W` -/ def wMk {α : TypeVec n} (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α) : P.W α := let g : P.last.B a → P.last.W := fun i => (f i).fst let g' : P.WPath ⟨a, g⟩ ⟹ α := P.wPathCasesOn f' fun i => (f i).snd ⟨⟨a, g⟩, g'⟩ /-- Recursor for `W` -/ def wRec {α : TypeVec n} {C : Type*} (g : ∀ a : P.A, P.drop.B a ⟹ α → (P.last.B a → P.W α) → (P.last.B a → C) → C) : P.W α → C | ⟨a, f'⟩ => let g' (a : P.A) (f : P.last.B a → P.last.W) (h : P.WPath ⟨a, f⟩ ⟹ α) (h' : P.last.B a → C) : C := g a (P.wPathDestLeft h) (fun i => ⟨f i, P.wPathDestRight h i⟩) h' P.wpRec g' a f' /-- Defining equation for the recursor of `W` -/ theorem wRec_eq {α : TypeVec n} {C : Type*} (g : ∀ a : P.A, P.drop.B a ⟹ α → (P.last.B a → P.W α) → (P.last.B a → C) → C) (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α) : P.wRec g (P.wMk a f' f) = g a f' f fun i => P.wRec g (f i) := by rw [wMk, wRec]; rw [wpRec_eq] dsimp only [wPathDestLeft_wPathCasesOn, wPathDestRight_wPathCasesOn] congr /-- Induction principle for `W` -/ theorem w_ind {α : TypeVec n} {C : P.W α → Prop} (ih : ∀ (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α), (∀ i, C (f i)) → C (P.wMk a f' f)) : ∀ x, C x := by intro x; obtain ⟨a, f⟩ := x apply @wp_ind n P α fun a f => C ⟨a, f⟩ intro a f f' ih' dsimp [wMk] at ih let ih'' := ih a (P.wPathDestLeft f') fun i => ⟨f i, P.wPathDestRight f' i⟩ dsimp at ih''; rw [wPathCasesOn_eta] at ih'' apply ih'' apply ih' theorem w_cases {α : TypeVec n} {C : P.W α → Prop} (ih : ∀ (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α), C (P.wMk a f' f)) : ∀ x, C x := P.w_ind fun a f' f _ih' => ih a f' f /-- W-types are functorial -/ def wMap {α β : TypeVec n} (g : α ⟹ β) : P.W α → P.W β := fun x => g <$$> x theorem wMk_eq {α : TypeVec n} (a : P.A) (f : P.last.B a → P.last.W) (g' : P.drop.B a ⟹ α) (g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) : (P.wMk a g' fun i => ⟨f i, g i⟩) = ⟨⟨a, f⟩, P.wPathCasesOn g' g⟩ := rfl theorem w_map_wMk {α β : TypeVec n} (g : α ⟹ β) (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α) : g <$$> P.wMk a f' f = P.wMk a (g ⊚ f') fun i => g <$$> f i := by change _ = P.wMk a (g ⊚ f') (MvFunctor.map g ∘ f) have : MvFunctor.map g ∘ f = fun i => ⟨(f i).fst, g ⊚ (f i).snd⟩ := by ext i : 1 dsimp [Function.comp_def] cases f i rfl rw [this] have : f = fun i => ⟨(f i).fst, (f i).snd⟩ := by ext1 x cases f x rfl rw [this] dsimp rw [wMk_eq, wMk_eq] have h := MvPFunctor.map_eq P.wp g rw [h, comp_wPathCasesOn] -- TODO: this technical theorem is used in one place in constructing the initial algebra. -- Can it be avoided? /-- Constructor of a value of `P.obj (α ::: β)` from components. Useful to avoid complicated type annotation -/ abbrev objAppend1 {α : TypeVec n} {β : Type u} (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → β) : P (α ::: β) := ⟨a, splitFun f' f⟩ theorem map_objAppend1 {α γ : TypeVec n} (g : α ⟹ γ) (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α) : appendFun g (P.wMap g) <$$> P.objAppend1 a f' f = P.objAppend1 a (g ⊚ f') fun x => P.wMap g (f x) := by rw [objAppend1, objAppend1, map_eq, appendFun, ← splitFun_comp]; rfl /-! Yet another view of the W type: as a fixed point for a multivariate polynomial functor. These are needed to use the W-construction to construct a fixed point of a qpf, since the qpf axioms are expressed in terms of `map` on `P`. -/ /-- Constructor for the W-type of `P` -/ def wMk' {α : TypeVec n} : P (α ::: P.W α) → P.W α | ⟨a, f⟩ => P.wMk a (dropFun f) (lastFun f) /-- Destructor for the W-type of `P` -/ def wDest' {α : TypeVec.{u} n} : P.W α → P (α.append1 (P.W α)) := P.wRec fun a f' f _ => ⟨a, splitFun f' f⟩ theorem wDest'_wMk {α : TypeVec n} (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α) : P.wDest' (P.wMk a f' f) = ⟨a, splitFun f' f⟩ := by rw [wDest', wRec_eq] theorem wDest'_wMk' {α : TypeVec n} (x : P (α.append1 (P.W α))) : P.wDest' (P.wMk' x) = x := by obtain ⟨a, f⟩ := x; rw [wMk', wDest'_wMk, split_dropFun_lastFun] end MvPFunctor
Circulant.lean
/- Copyright (c) 2021 Lu-Ming Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lu-Ming Zhang -/ import Mathlib.Algebra.Group.Fin.Basic import Mathlib.LinearAlgebra.Matrix.Symmetric import Mathlib.Tactic.Abel /-! # Circulant matrices This file contains the definition and basic results about circulant matrices. Given a vector `v : n → α` indexed by a type that is endowed with subtraction, `Matrix.circulant v` is the matrix whose `(i, j)`th entry is `v (i - j)`. ## Main results - `Matrix.circulant`: the circulant matrix generated by a given vector `v : n → α`. - `Matrix.circulant_mul`: the product of two circulant matrices `circulant v` and `circulant w` is the circulant matrix generated by `circulant v *ᵥ w`. - `Matrix.circulant_mul_comm`: multiplication of circulant matrices commutes when the elements do. ## Implementation notes `Matrix.Fin.foo` is the `Fin n` version of `Matrix.foo`. Namely, the index type of the circulant matrices in discussion is `Fin n`. ## Tags circulant, matrix -/ variable {α β n R : Type*} namespace Matrix open Function open Matrix /-- Given the condition `[Sub n]` and a vector `v : n → α`, we define `circulant v` to be the circulant matrix generated by `v` of type `Matrix n n α`. The `(i,j)`th entry is defined to be `v (i - j)`. -/ def circulant [Sub n] (v : n → α) : Matrix n n α := of fun i j => v (i - j) -- TODO: set as an equation lemma for `circulant`, see https://github.com/leanprover-community/mathlib4/pull/3024 @[simp] theorem circulant_apply [Sub n] (v : n → α) (i j) : circulant v i j = v (i - j) := rfl theorem circulant_col_zero_eq [SubtractionMonoid n] (v : n → α) (i : n) : circulant v i 0 = v i := congr_arg v (sub_zero _) theorem circulant_injective [SubtractionMonoid n] : Injective (circulant : (n → α) → Matrix n n α) := by intro v w h ext k rw [← circulant_col_zero_eq v, ← circulant_col_zero_eq w, h] theorem Fin.circulant_injective : ∀ n, Injective fun v : Fin n → α => circulant v | 0 => by simp [Injective] | _ + 1 => Matrix.circulant_injective @[simp] theorem circulant_inj [SubtractionMonoid n] {v w : n → α} : circulant v = circulant w ↔ v = w := circulant_injective.eq_iff @[simp] theorem Fin.circulant_inj {n} {v w : Fin n → α} : circulant v = circulant w ↔ v = w := (Fin.circulant_injective n).eq_iff theorem transpose_circulant [SubtractionMonoid n] (v : n → α) : (circulant v)ᵀ = circulant fun i => v (-i) := by ext; simp theorem conjTranspose_circulant [Star α] [SubtractionMonoid n] (v : n → α) : (circulant v)ᴴ = circulant (star fun i => v (-i)) := by ext; simp theorem Fin.transpose_circulant : ∀ {n} (v : Fin n → α), (circulant v)ᵀ = circulant fun i => v (-i) | 0 => by simp [eq_iff_true_of_subsingleton] | _ + 1 => Matrix.transpose_circulant theorem Fin.conjTranspose_circulant [Star α] : ∀ {n} (v : Fin n → α), (circulant v)ᴴ = circulant (star fun i => v (-i)) | 0 => by simp [eq_iff_true_of_subsingleton] | _ + 1 => Matrix.conjTranspose_circulant theorem map_circulant [Sub n] (v : n → α) (f : α → β) : (circulant v).map f = circulant fun i => f (v i) := ext fun _ _ => rfl theorem circulant_neg [Neg α] [Sub n] (v : n → α) : circulant (-v) = -circulant v := ext fun _ _ => rfl @[simp] theorem circulant_zero (α n) [Zero α] [Sub n] : circulant 0 = (0 : Matrix n n α) := ext fun _ _ => rfl theorem circulant_add [Add α] [Sub n] (v w : n → α) : circulant (v + w) = circulant v + circulant w := ext fun _ _ => rfl theorem circulant_sub [Sub α] [Sub n] (v w : n → α) : circulant (v - w) = circulant v - circulant w := ext fun _ _ => rfl /-- The product of two circulant matrices `circulant v` and `circulant w` is the circulant matrix generated by `circulant v *ᵥ w`. -/ theorem circulant_mul [NonUnitalNonAssocSemiring α] [Fintype n] [AddGroup n] (v w : n → α) : circulant v * circulant w = circulant (circulant v *ᵥ w) := by ext i j simp only [mul_apply, mulVec, circulant_apply, dotProduct] refine Fintype.sum_equiv (Equiv.subRight j) _ _ ?_ intro x simp only [Equiv.subRight_apply, sub_sub_sub_cancel_right] theorem Fin.circulant_mul [NonUnitalNonAssocSemiring α] : ∀ {n} (v w : Fin n → α), circulant v * circulant w = circulant (circulant v *ᵥ w) | 0 => by simp [eq_iff_true_of_subsingleton] | _ + 1 => Matrix.circulant_mul /-- Multiplication of circulant matrices commutes when the elements do. -/ theorem circulant_mul_comm [CommMagma α] [AddCommMonoid α] [Fintype n] [AddCommGroup n] (v w : n → α) : circulant v * circulant w = circulant w * circulant v := by ext i j simp only [mul_apply, circulant_apply] refine Fintype.sum_equiv ((Equiv.subLeft i).trans (Equiv.addRight j)) _ _ ?_ intro x simp only [Equiv.trans_apply, Equiv.subLeft_apply, Equiv.coe_addRight, add_sub_cancel_right, mul_comm] congr 2 abel theorem Fin.circulant_mul_comm [CommMagma α] [AddCommMonoid α] : ∀ {n} (v w : Fin n → α), circulant v * circulant w = circulant w * circulant v | 0 => by simp | _ + 1 => Matrix.circulant_mul_comm /-- `k • circulant v` is another circulant matrix `circulant (k • v)`. -/ theorem circulant_smul [Sub n] [SMul R α] (k : R) (v : n → α) : circulant (k • v) = k • circulant v := rfl @[simp] theorem circulant_single_one (α n) [Zero α] [One α] [DecidableEq n] [AddGroup n] : circulant (Pi.single 0 1 : n → α) = (1 : Matrix n n α) := by ext i j simp [one_apply, Pi.single_apply, sub_eq_zero] @[simp] theorem circulant_single (n) [Semiring α] [DecidableEq n] [AddGroup n] [Fintype n] (a : α) : circulant (Pi.single 0 a : n → α) = scalar n a := by ext i j simp [Pi.single_apply, diagonal_apply, sub_eq_zero] /-- Note we use `↑i = 0` instead of `i = 0` as `Fin 0` has no `0`. This means that we cannot state this with `Pi.single` as we did with `Matrix.circulant_single`. -/ theorem Fin.circulant_ite (α) [Zero α] [One α] : ∀ n, circulant (fun i => ite (i.1 = 0) 1 0 : Fin n → α) = 1 | 0 => by simp [eq_iff_true_of_subsingleton] | n + 1 => by rw [← circulant_single_one] congr with j simp [Pi.single_apply] /-- A circulant of `v` is symmetric iff `v` equals its reverse. -/ theorem circulant_isSymm_iff [SubtractionMonoid n] {v : n → α} : (circulant v).IsSymm ↔ ∀ i, v (-i) = v i := by rw [IsSymm, transpose_circulant, circulant_inj, funext_iff] theorem Fin.circulant_isSymm_iff : ∀ {n} {v : Fin n → α}, (circulant v).IsSymm ↔ ∀ i, v (-i) = v i | 0 => by simp [IsSymm.ext_iff, IsEmpty.forall_iff] | _ + 1 => Matrix.circulant_isSymm_iff /-- If `circulant v` is symmetric, `∀ i j : I, v (- i) = v i`. -/ theorem circulant_isSymm_apply [SubtractionMonoid n] {v : n → α} (h : (circulant v).IsSymm) (i : n) : v (-i) = v i := circulant_isSymm_iff.1 h i theorem Fin.circulant_isSymm_apply {n} {v : Fin n → α} (h : (circulant v).IsSymm) (i : Fin n) : v (-i) = v i := Fin.circulant_isSymm_iff.1 h i end Matrix
SimpleFunc.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import Mathlib.Algebra.Order.Pi import Mathlib.Algebra.Algebra.Pi import Mathlib.MeasureTheory.Constructions.BorelSpace.Order /-! # Simple functions A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. In this file, we define simple functions and establish their basic properties; and we construct a sequence of simple functions approximating an arbitrary Borel measurable function `f : α → ℝ≥0∞`. The theorem `Measurable.ennreal_induction` shows that in order to prove something for an arbitrary measurable function into `ℝ≥0∞`, it is sufficient to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. -/ noncomputable section open Set hiding restrict restrict_apply open Filter ENNReal open Function (support) open Topology NNReal ENNReal MeasureTheory namespace MeasureTheory variable {α β γ δ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure SimpleFunc.{u, v} (α : Type u) [MeasurableSpace α] (β : Type v) where /-- The underlying function -/ toFun : α → β measurableSet_fiber' : ∀ x, MeasurableSet (toFun ⁻¹' {x}) finite_range' : (Set.range toFun).Finite local infixr:25 " →ₛ " => SimpleFunc namespace SimpleFunc section Measurable variable [MeasurableSpace α] instance instFunLike : FunLike (α →ₛ β) α β where coe := toFun coe_injective' | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl => rfl theorem coe_injective ⦃f g : α →ₛ β⦄ (H : (f : α → β) = g) : f = g := DFunLike.ext' H @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := DFunLike.ext _ _ H theorem finite_range (f : α →ₛ β) : (Set.range f).Finite := f.finite_range' theorem measurableSet_fiber (f : α →ₛ β) (x : β) : MeasurableSet (f ⁻¹' {x}) := f.measurableSet_fiber' x @[simp] theorem coe_mk (f : α → β) (h h') : ⇑(mk f h h') = f := rfl theorem apply_mk (f : α → β) (h h') (x : α) : SimpleFunc.mk f h h' x = f x := rfl /-- Simple function defined on a finite type. -/ def ofFinite [Finite α] [MeasurableSingletonClass α] (f : α → β) : α →ₛ β where toFun := f measurableSet_fiber' x := (toFinite (f ⁻¹' {x})).measurableSet finite_range' := Set.finite_range f /-- Simple function defined on the empty type. -/ def ofIsEmpty [IsEmpty α] : α →ₛ β := ofFinite isEmptyElim /-- Range of a simple function `α →ₛ β` as a `Finset β`. -/ protected def range (f : α →ₛ β) : Finset β := f.finite_range.toFinset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f := Finite.mem_toFinset _ theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] theorem coe_range (f : α →ₛ β) : (↑f.range : Set β) = Set.range f := f.finite_range.coe_toFinset theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : Measure α} (H : μ (f ⁻¹' {x}) ≠ 0) : x ∈ f.range := let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H mem_range.2 ⟨a, ha⟩ theorem forall_mem_range {f : α →ₛ β} {p : β → Prop} : (∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) := by simp only [mem_range, Set.forall_mem_range] theorem exists_range_iff {f : α →ₛ β} {p : β → Prop} : (∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) := by simpa only [mem_range, exists_prop] using Set.exists_range_iff theorem preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := preimage_singleton_eq_empty.trans <| not_congr mem_range.symm theorem exists_forall_le [Nonempty β] [Preorder β] [IsDirected β (· ≤ ·)] (f : α →ₛ β) : ∃ C, ∀ x, f x ≤ C := f.range.exists_le.imp fun _ => forall_mem_range.1 /-- Constant function as a `SimpleFunc`. -/ def const (α) {β} [MeasurableSpace α] (b : β) : α →ₛ β := ⟨fun _ => b, fun _ => MeasurableSet.const _, finite_range_const⟩ instance instInhabited [Inhabited β] : Inhabited (α →ₛ β) := ⟨const _ default⟩ theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl @[simp] theorem coe_const (b : β) : ⇑(const α b) = Function.const α b := rfl @[simp] theorem range_const (α) [MeasurableSpace α] [Nonempty α] (b : β) : (const α b).range = {b} := Finset.coe_injective <| by simp +unfoldPartialApp [Function.const] theorem range_const_subset (α) [MeasurableSpace α] (b : β) : (const α b).range ⊆ {b} := Finset.coe_subset.1 <| by simp theorem simpleFunc_bot {α} (f : @SimpleFunc α ⊥ β) [Nonempty β] : ∃ c, ∀ x, f x = c := by have hf_meas := @SimpleFunc.measurableSet_fiber α _ ⊥ f simp_rw [MeasurableSpace.measurableSet_bot_iff] at hf_meas exact (exists_eq_const_of_preimage_singleton hf_meas).imp fun c hc ↦ congr_fun hc theorem simpleFunc_bot' {α} [Nonempty β] (f : @SimpleFunc α ⊥ β) : ∃ c, f = @SimpleFunc.const α _ ⊥ c := letI : MeasurableSpace α := ⊥; (simpleFunc_bot f).imp fun _ ↦ ext theorem measurableSet_cut (r : α → β → Prop) (f : α →ₛ β) (h : ∀ b, MeasurableSet { a | r a b }) : MeasurableSet { a | r a (f a) } := by have : { a | r a (f a) } = ⋃ b ∈ range f, { a | r a b } ∩ f ⁻¹' {b} := by ext a suffices r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i by simpa exact ⟨fun h => ⟨a, ⟨h, rfl⟩⟩, fun ⟨a', ⟨h', e⟩⟩ => e.symm ▸ h'⟩ rw [this] exact MeasurableSet.biUnion f.finite_range.countable fun b _ => MeasurableSet.inter (h b) (f.measurableSet_fiber _) @[measurability] theorem measurableSet_preimage (f : α →ₛ β) (s) : MeasurableSet (f ⁻¹' s) := measurableSet_cut (fun _ b => b ∈ s) f fun b => MeasurableSet.const (b ∈ s) /-- A simple function is measurable -/ @[measurability, fun_prop] protected theorem measurable [MeasurableSpace β] (f : α →ₛ β) : Measurable f := fun s _ => measurableSet_preimage f s @[measurability] protected theorem aemeasurable [MeasurableSpace β] {μ : Measure α} (f : α →ₛ β) : AEMeasurable f μ := f.measurable.aemeasurable protected theorem sum_measure_preimage_singleton (f : α →ₛ β) {μ : Measure α} (s : Finset β) : (∑ y ∈ s, μ (f ⁻¹' {y})) = μ (f ⁻¹' ↑s) := sum_measure_preimage_singleton _ fun _ _ => f.measurableSet_fiber _ theorem sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : Measure α) : (∑ y ∈ f.range, μ (f ⁻¹' {y})) = μ univ := by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range] open scoped Classical in /-- If-then-else as a `SimpleFunc`. -/ def piecewise (s : Set α) (hs : MeasurableSet s) (f g : α →ₛ β) : α →ₛ β := ⟨s.piecewise f g, fun _ => letI : MeasurableSpace β := ⊤ f.measurable.piecewise hs g.measurable trivial, (f.finite_range.union g.finite_range).subset range_ite_subset⟩ open scoped Classical in @[simp] theorem coe_piecewise {s : Set α} (hs : MeasurableSet s) (f g : α →ₛ β) : ⇑(piecewise s hs f g) = s.piecewise f g := rfl open scoped Classical in theorem piecewise_apply {s : Set α} (hs : MeasurableSet s) (f g : α →ₛ β) (a) : piecewise s hs f g a = if a ∈ s then f a else g a := rfl open scoped Classical in @[simp] theorem piecewise_compl {s : Set α} (hs : MeasurableSet sᶜ) (f g : α →ₛ β) : piecewise sᶜ hs f g = piecewise s hs.of_compl g f := coe_injective <| by simp @[simp] theorem piecewise_univ (f g : α →ₛ β) : piecewise univ MeasurableSet.univ f g = f := coe_injective <| by simp @[simp] theorem piecewise_empty (f g : α →ₛ β) : piecewise ∅ MeasurableSet.empty f g = g := coe_injective <| by simp open scoped Classical in @[simp] theorem piecewise_same (f : α →ₛ β) {s : Set α} (hs : MeasurableSet s) : piecewise s hs f f = f := coe_injective <| Set.piecewise_same _ _ theorem support_indicator [Zero β] {s : Set α} (hs : MeasurableSet s) (f : α →ₛ β) : Function.support (f.piecewise s hs (SimpleFunc.const α 0)) = s ∩ Function.support f := Set.support_indicator open scoped Classical in theorem range_indicator {s : Set α} (hs : MeasurableSet s) (hs_nonempty : s.Nonempty) (hs_ne_univ : s ≠ univ) (x y : β) : (piecewise s hs (const α x) (const α y)).range = {x, y} := by simp only [← Finset.coe_inj, coe_range, coe_piecewise, range_piecewise, coe_const, Finset.coe_insert, Finset.coe_singleton, hs_nonempty.image_const, (nonempty_compl.2 hs_ne_univ).image_const, singleton_union, Function.const] theorem measurable_bind [MeasurableSpace γ] (f : α →ₛ β) (g : β → α → γ) (hg : ∀ b, Measurable (g b)) : Measurable fun a => g (f a) a := fun s hs => f.measurableSet_cut (fun a b => g b a ∈ s) fun b => hg b hs /-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨fun a => g (f a) a, fun c => f.measurableSet_cut (fun a b => g b a = c) fun b => (g b).measurableSet_preimage {c}, (f.finite_range.biUnion fun b _ => (g b).finite_range).subset <| by rintro _ ⟨a, rfl⟩; simp⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h : γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl @[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [DecidableEq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := Finset.coe_injective <| by simp only [coe_range, coe_map, Finset.coe_image, range_comp] @[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl open scoped Classical in theorem map_preimage (f : α →ₛ β) (g : β → γ) (s : Set γ) : f.map g ⁻¹' s = f ⁻¹' ↑{b ∈ f.range | g b ∈ s} := by simp only [coe_range, sep_mem_eq, coe_map, Finset.coe_filter, ← mem_preimage, inter_comm, preimage_inter_range, ← Finset.mem_coe] exact preimage_comp open scoped Classical in theorem map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : f.map g ⁻¹' {c} = f ⁻¹' ↑{b ∈ f.range | g b = c} := map_preimage _ _ _ /-- Composition of a `SimpleFun` and a measurable function is a `SimpleFunc`. -/ def comp [MeasurableSpace β] (f : β →ₛ γ) (g : α → β) (hgm : Measurable g) : α →ₛ γ where toFun := f ∘ g finite_range' := f.finite_range.subset <| Set.range_comp_subset_range _ _ measurableSet_fiber' z := hgm (f.measurableSet_fiber z) @[simp] theorem coe_comp [MeasurableSpace β] (f : β →ₛ γ) {g : α → β} (hgm : Measurable g) : ⇑(f.comp g hgm) = f ∘ g := rfl theorem range_comp_subset_range [MeasurableSpace β] (f : β →ₛ γ) {g : α → β} (hgm : Measurable g) : (f.comp g hgm).range ⊆ f.range := Finset.coe_subset.1 <| by simp only [coe_range, coe_comp, Set.range_comp_subset_range] /-- Extend a `SimpleFunc` along a measurable embedding: `f₁.extend g hg f₂` is the function `F : β →ₛ γ` such that `F ∘ g = f₁` and `F y = f₂ y` whenever `y ∉ range g`. -/ def extend [MeasurableSpace β] (f₁ : α →ₛ γ) (g : α → β) (hg : MeasurableEmbedding g) (f₂ : β →ₛ γ) : β →ₛ γ where toFun := Function.extend g f₁ f₂ finite_range' := (f₁.finite_range.union <| f₂.finite_range.subset (image_subset_range _ _)).subset (range_extend_subset _ _ _) measurableSet_fiber' := by letI : MeasurableSpace γ := ⊤; haveI : MeasurableSingletonClass γ := ⟨fun _ => trivial⟩ exact fun x => hg.measurable_extend f₁.measurable f₂.measurable (measurableSet_singleton _) @[simp] theorem extend_apply [MeasurableSpace β] (f₁ : α →ₛ γ) {g : α → β} (hg : MeasurableEmbedding g) (f₂ : β →ₛ γ) (x : α) : (f₁.extend g hg f₂) (g x) = f₁ x := hg.injective.extend_apply _ _ _ @[simp] theorem extend_apply' [MeasurableSpace β] (f₁ : α →ₛ γ) {g : α → β} (hg : MeasurableEmbedding g) (f₂ : β →ₛ γ) {y : β} (h : ¬∃ x, g x = y) : (f₁.extend g hg f₂) y = f₂ y := Function.extend_apply' _ _ _ h @[simp] theorem extend_comp_eq' [MeasurableSpace β] (f₁ : α →ₛ γ) {g : α → β} (hg : MeasurableEmbedding g) (f₂ : β →ₛ γ) : f₁.extend g hg f₂ ∘ g = f₁ := funext fun _ => extend_apply _ _ _ _ @[simp] theorem extend_comp_eq [MeasurableSpace β] (f₁ : α →ₛ γ) {g : α → β} (hg : MeasurableEmbedding g) (f₂ : β →ₛ γ) : (f₁.extend g hg f₂).comp g hg.measurable = f₁ := coe_injective <| extend_comp_eq' _ hg _ /-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/ def seq (f : α →ₛ β → γ) (g : α →ₛ β) : α →ₛ γ := f.bind fun f => g.map f @[simp] theorem seq_apply (f : α →ₛ β → γ) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β` into `fun a => (f a, g a)`. -/ def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ β × γ := (f.map Prod.mk).seq g @[simp] theorem pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl theorem pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : Set β) (t : Set γ) : pair f g ⁻¹' s ×ˢ t = f ⁻¹' s ∩ g ⁻¹' t := rfl -- A special form of `pair_preimage` theorem pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : pair f g ⁻¹' {(b, c)} = f ⁻¹' {b} ∩ g ⁻¹' {c} := by rw [← singleton_prod_singleton] exact pair_preimage _ _ _ _ @[simp] theorem map_fst_pair (f : α →ₛ β) (g : α →ₛ γ) : (f.pair g).map Prod.fst = f := rfl @[simp] theorem map_snd_pair (f : α →ₛ β) (g : α →ₛ γ) : (f.pair g).map Prod.snd = g := rfl @[simp] theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp @[to_additive] instance instOne [One β] : One (α →ₛ β) := ⟨const α 1⟩ @[to_additive] instance instMul [Mul β] : Mul (α →ₛ β) := ⟨fun f g => (f.map (· * ·)).seq g⟩ @[to_additive] instance instDiv [Div β] : Div (α →ₛ β) := ⟨fun f g => (f.map (· / ·)).seq g⟩ @[to_additive] instance instInv [Inv β] : Inv (α →ₛ β) := ⟨fun f => f.map Inv.inv⟩ instance instSup [Max β] : Max (α →ₛ β) := ⟨fun f g => (f.map (· ⊔ ·)).seq g⟩ instance instInf [Min β] : Min (α →ₛ β) := ⟨fun f g => (f.map (· ⊓ ·)).seq g⟩ instance instLE [LE β] : LE (α →ₛ β) := ⟨fun f g => ∀ a, f a ≤ g a⟩ @[to_additive (attr := simp)] theorem const_one [One β] : const α (1 : β) = 1 := rfl @[to_additive (attr := simp, norm_cast)] theorem coe_one [One β] : ⇑(1 : α →ₛ β) = 1 := rfl @[to_additive (attr := simp, norm_cast)] theorem coe_mul [Mul β] (f g : α →ₛ β) : ⇑(f * g) = ⇑f * ⇑g := rfl @[to_additive (attr := simp, norm_cast)] theorem coe_inv [Inv β] (f : α →ₛ β) : ⇑(f⁻¹) = (⇑f)⁻¹ := rfl @[to_additive (attr := simp, norm_cast)] theorem coe_div [Div β] (f g : α →ₛ β) : ⇑(f / g) = ⇑f / ⇑g := rfl @[simp, norm_cast] theorem coe_le [LE β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := Iff.rfl @[simp, norm_cast] theorem coe_sup [Max β] (f g : α →ₛ β) : ⇑(f ⊔ g) = ⇑f ⊔ ⇑g := rfl @[simp, norm_cast] theorem coe_inf [Min β] (f g : α →ₛ β) : ⇑(f ⊓ g) = ⇑f ⊓ ⇑g := rfl @[to_additive] theorem mul_apply [Mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl @[to_additive] theorem div_apply [Div β] (f g : α →ₛ β) (x : α) : (f / g) x = f x / g x := rfl @[to_additive] theorem inv_apply [Inv β] (f : α →ₛ β) (x : α) : f⁻¹ x = (f x)⁻¹ := rfl theorem sup_apply [Max β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl theorem inf_apply [Min β] (f g : α →ₛ β) (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl @[to_additive (attr := simp)] theorem range_one [Nonempty α] [One β] : (1 : α →ₛ β).range = {1} := Finset.ext fun x => by simp @[simp] theorem range_eq_empty_of_isEmpty {β} [hα : IsEmpty α] (f : α →ₛ β) : f.range = ∅ := by rw [← Finset.not_nonempty_iff_eq_empty] by_contra h obtain ⟨y, hy_mem⟩ := h rw [SimpleFunc.mem_range, Set.mem_range] at hy_mem obtain ⟨x, hxy⟩ := hy_mem rw [isEmpty_iff] at hα exact hα x theorem eq_zero_of_mem_range_zero [Zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 := @(forall_mem_range.2 fun _ => rfl) @[to_additive] theorem mul_eq_map₂ [Mul β] (f g : α →ₛ β) : f * g = (pair f g).map fun p : β × β => p.1 * p.2 := rfl theorem sup_eq_map₂ [Max β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map fun p : β × β => p.1 ⊔ p.2 := rfl @[to_additive] theorem const_mul_eq_map [Mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map fun a => b * a := rfl @[to_additive] theorem map_mul [Mul β] [Mul γ] {g : β → γ} (hg : ∀ x y, g (x * y) = g x * g y) (f₁ f₂ : α →ₛ β) : (f₁ * f₂).map g = f₁.map g * f₂.map g := ext fun _ => hg _ _ variable {K : Type*} @[to_additive] instance instSMul [SMul K β] : SMul K (α →ₛ β) := ⟨fun k f => f.map (k • ·)⟩ @[to_additive (attr := simp)] theorem coe_smul [SMul K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • ⇑f := rfl @[to_additive (attr := simp)] theorem smul_apply [SMul K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl instance hasNatSMul [AddMonoid β] : SMul ℕ (α →ₛ β) := inferInstance @[to_additive existing hasNatSMul] instance hasNatPow [Monoid β] : Pow (α →ₛ β) ℕ := ⟨fun f n => f.map (· ^ n)⟩ @[simp] theorem coe_pow [Monoid β] (f : α →ₛ β) (n : ℕ) : ⇑(f ^ n) = (⇑f) ^ n := rfl theorem pow_apply [Monoid β] (n : ℕ) (f : α →ₛ β) (a : α) : (f ^ n) a = f a ^ n := rfl instance hasIntPow [DivInvMonoid β] : Pow (α →ₛ β) ℤ := ⟨fun f n => f.map (· ^ n)⟩ @[simp] theorem coe_zpow [DivInvMonoid β] (f : α →ₛ β) (z : ℤ) : ⇑(f ^ z) = (⇑f) ^ z := rfl theorem zpow_apply [DivInvMonoid β] (z : ℤ) (f : α →ₛ β) (a : α) : (f ^ z) a = f a ^ z := rfl -- TODO: work out how to generate these instances with `to_additive`, which gets confused by the -- argument order swap between `coe_smul` and `coe_pow`. section Additive instance instAddMonoid [AddMonoid β] : AddMonoid (α →ₛ β) := fast_instance% Function.Injective.addMonoid (fun f => show α → β from f) coe_injective coe_zero coe_add fun _ _ => coe_smul _ _ instance instAddCommMonoid [AddCommMonoid β] : AddCommMonoid (α →ₛ β) := fast_instance% Function.Injective.addCommMonoid (fun f => show α → β from f) coe_injective coe_zero coe_add fun _ _ => coe_smul _ _ instance instAddGroup [AddGroup β] : AddGroup (α →ₛ β) := Function.Injective.addGroup (fun f => show α → β from f) coe_injective coe_zero coe_add coe_neg coe_sub (fun _ _ => coe_smul _ _) fun _ _ => coe_smul _ _ instance instAddCommGroup [AddCommGroup β] : AddCommGroup (α →ₛ β) := fast_instance% Function.Injective.addCommGroup (fun f => show α → β from f) coe_injective coe_zero coe_add coe_neg coe_sub (fun _ _ => coe_smul _ _) fun _ _ => coe_smul _ _ end Additive @[to_additive existing] instance instMonoid [Monoid β] : Monoid (α →ₛ β) := fast_instance% Function.Injective.monoid (fun f => show α → β from f) coe_injective coe_one coe_mul coe_pow @[to_additive existing] instance instCommMonoid [CommMonoid β] : CommMonoid (α →ₛ β) := fast_instance% Function.Injective.commMonoid (fun f => show α → β from f) coe_injective coe_one coe_mul coe_pow @[to_additive existing] instance instGroup [Group β] : Group (α →ₛ β) := fast_instance% Function.Injective.group (fun f => show α → β from f) coe_injective coe_one coe_mul coe_inv coe_div coe_pow coe_zpow @[to_additive existing] instance instCommGroup [CommGroup β] : CommGroup (α →ₛ β) := fast_instance% Function.Injective.commGroup (fun f => show α → β from f) coe_injective coe_one coe_mul coe_inv coe_div coe_pow coe_zpow instance [Monoid K] [MulAction K β] : MulAction K (α →ₛ β) := fast_instance% Function.Injective.mulAction (fun f => show α → β from f) coe_injective coe_smul instance instModule [Semiring K] [AddCommMonoid β] [Module K β] : Module K (α →ₛ β) := fast_instance% Function.Injective.module K ⟨⟨fun f => show α → β from f, coe_zero⟩, coe_add⟩ coe_injective coe_smul theorem smul_eq_map [SMul K β] (k : K) (f : α →ₛ β) : k • f = f.map (k • ·) := rfl lemma smul_const [SMul K β] (k : K) (b : β) : (k • const α b : α →ₛ β) = const α (k • b) := ext fun _ ↦ rfl instance [NonUnitalNonAssocSemiring β] : NonUnitalNonAssocSemiring (α →ₛ β) := fast_instance% Function.Injective.nonUnitalNonAssocSemiring (fun f => show α → β from f) coe_injective coe_zero coe_add coe_mul coe_smul instance [NonUnitalSemiring β] : NonUnitalSemiring (α →ₛ β) := fast_instance% Function.Injective.nonUnitalSemiring (fun f => show α → β from f) SimpleFunc.coe_injective coe_zero coe_add coe_mul coe_smul instance [NatCast β] : NatCast (α →ₛ β) where natCast n := const _ (NatCast.natCast n) @[simp, norm_cast] lemma coe_natCast [NatCast β] (n : ℕ) : ⇑(↑n : α →ₛ β) = fun _ ↦ ↑n := rfl instance [NonAssocSemiring β] : NonAssocSemiring (α →ₛ β) := fast_instance% Function.Injective.nonAssocSemiring (fun f => show α → β from f) coe_injective coe_zero coe_one coe_add coe_mul coe_smul coe_natCast instance [IntCast β] : IntCast (α →ₛ β) where intCast n := const _ (IntCast.intCast n) @[simp, norm_cast] lemma coe_intCast [IntCast β] (n : ℤ) : ⇑(↑n : α →ₛ β) = fun _ ↦ ↑n := rfl instance [NonAssocRing β] : NonAssocRing (α →ₛ β) := fast_instance% Function.Injective.nonAssocRing (fun f => show α → β from f) coe_injective coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_smul coe_smul coe_natCast coe_intCast instance [NonUnitalCommSemiring β] : NonUnitalCommSemiring (α →ₛ β) := fast_instance% Function.Injective.nonUnitalCommSemiring (fun f => show α → β from f) coe_injective coe_zero coe_add coe_mul coe_smul instance [CommSemiring β] : CommSemiring (α →ₛ β) := fast_instance% Function.Injective.commSemiring (fun f => show α → β from f) coe_injective coe_zero coe_one coe_add coe_mul coe_smul coe_pow coe_natCast instance [NonUnitalCommRing β] : NonUnitalCommRing (α →ₛ β) := fast_instance% Function.Injective.nonUnitalCommRing (fun f => show α → β from f) coe_injective coe_zero coe_add coe_mul coe_neg coe_sub coe_smul coe_smul instance [CommRing β] : CommRing (α →ₛ β) := fast_instance% Function.Injective.commRing (fun f => show α → β from f) coe_injective coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_smul coe_smul coe_pow coe_natCast coe_intCast instance [Semiring β] : Semiring (α →ₛ β) := fast_instance% Function.Injective.semiring (fun f => show α → β from f) coe_injective coe_zero coe_one coe_add coe_mul coe_smul coe_pow coe_natCast instance [NonUnitalRing β] : NonUnitalRing (α →ₛ β) := fast_instance% Function.Injective.nonUnitalRing (fun f => show α → β from f) coe_injective coe_zero coe_add coe_mul coe_neg coe_sub coe_smul coe_smul instance [Ring β] : Ring (α →ₛ β) := fast_instance% Function.Injective.ring (fun f => show α → β from f) coe_injective coe_zero coe_one coe_add coe_mul coe_neg coe_sub coe_smul coe_smul coe_pow coe_natCast coe_intCast instance [SMul K γ] [SMul γ β] [SMul K β] [IsScalarTower K γ β] : IsScalarTower K γ (α →ₛ β) where smul_assoc _ _ _ := ext fun _ ↦ smul_assoc .. instance [SMul γ β] [SMul K β] [SMulCommClass K γ β] : SMulCommClass K γ (α →ₛ β) where smul_comm _ _ _ := ext fun _ ↦ smul_comm .. instance [CommSemiring K] [Semiring β] [Algebra K β] : Algebra K (α →ₛ β) where algebraMap :={ toFun r := const α <| algebraMap K β r map_one' := ext fun _ ↦ algebraMap K β |>.map_one ▸ rfl map_mul' _ _ := ext fun _ ↦ algebraMap K β |>.map_mul .. map_zero' := ext fun _ ↦ algebraMap K β |>.map_zero ▸ rfl map_add' _ _ := ext fun _ ↦ algebraMap K β |>.map_add ..} commutes' _ _ := ext fun _ ↦ Algebra.commutes .. smul_def' _ _ := ext fun _ ↦ Algebra.smul_def .. @[simp] lemma const_algebraMap [CommSemiring K] [Semiring β] [Algebra K β] (k : K) : const α (algebraMap K β k) = algebraMap K (α →ₛ β) k := rfl @[simp] lemma coe_algebraMap [CommSemiring K] [Semiring β] [Algebra K β] (k : K) (x : α) : ⇑(algebraMap K (α →ₛ β)) k x = algebraMap K (α → β) k x := rfl section Star instance [Star β] : Star (α →ₛ β) where star f := f.map Star.star @[simp] lemma coe_star [Star β] {f : α →ₛ β} : ⇑(star f) = star ⇑f := rfl instance [InvolutiveStar β] : InvolutiveStar (α →ₛ β) where star_involutive _ := ext fun _ ↦ star_star _ instance [AddMonoid β] [StarAddMonoid β] : StarAddMonoid (α →ₛ β) where star_add _ _ := ext fun _ ↦ star_add .. instance [Mul β] [StarMul β] : StarMul (α →ₛ β) where star_mul _ _ := ext fun _ ↦ star_mul .. instance [NonUnitalNonAssocSemiring β] [StarRing β] : StarRing (α →ₛ β) where star_add _ _ := ext fun _ ↦ star_add .. end Star section Preorder variable [Preorder β] {s : Set α} {f f₁ f₂ g g₁ g₂ : α →ₛ β} {hs : MeasurableSet s} instance instPreorder : Preorder (α →ₛ β) := Preorder.lift (⇑) @[norm_cast] lemma coe_le_coe : ⇑f ≤ g ↔ f ≤ g := .rfl @[simp, norm_cast] lemma coe_lt_coe : ⇑f < g ↔ f < g := .rfl @[simp] lemma mk_le_mk {f g : α → β} {hf hg hf' hg'} : mk f hf hf' ≤ mk g hg hg' ↔ f ≤ g := Iff.rfl @[simp] lemma mk_lt_mk {f g : α → β} {hf hg hf' hg'} : mk f hf hf' < mk g hg hg' ↔ f < g := Iff.rfl @[gcongr] protected alias ⟨_, GCongr.mk_le_mk⟩ := mk_le_mk @[gcongr] protected alias ⟨_, GCongr.mk_lt_mk⟩ := mk_lt_mk @[gcongr] protected alias ⟨_, GCongr.coe_le_coe⟩ := coe_le_coe @[gcongr] protected alias ⟨_, GCongr.coe_lt_coe⟩ := coe_lt_coe open scoped Classical in @[gcongr] lemma piecewise_mono (hf : ∀ a ∈ s, f₁ a ≤ f₂ a) (hg : ∀ a ∉ s, g₁ a ≤ g₂ a) : piecewise s hs f₁ g₁ ≤ piecewise s hs f₂ g₂ := Set.piecewise_mono hf hg end Preorder instance instPartialOrder [PartialOrder β] : PartialOrder (α →ₛ β) := { SimpleFunc.instPreorder with le_antisymm := fun _f _g hfg hgf => ext fun a => le_antisymm (hfg a) (hgf a) } instance instOrderBot [LE β] [OrderBot β] : OrderBot (α →ₛ β) where bot := const α ⊥ bot_le _ _ := bot_le instance instOrderTop [LE β] [OrderTop β] : OrderTop (α →ₛ β) where top := const α ⊤ le_top _ _ := le_top @[to_additive] instance [CommMonoid β] [PartialOrder β] [IsOrderedMonoid β] : IsOrderedMonoid (α →ₛ β) where mul_le_mul_left _ _ h _ _ := mul_le_mul_left' (h _) _ instance instSemilatticeInf [SemilatticeInf β] : SemilatticeInf (α →ₛ β) := { SimpleFunc.instPartialOrder with inf := (· ⊓ ·) inf_le_left := fun _ _ _ => inf_le_left inf_le_right := fun _ _ _ => inf_le_right le_inf := fun _f _g _h hfh hgh a => le_inf (hfh a) (hgh a) } instance instSemilatticeSup [SemilatticeSup β] : SemilatticeSup (α →ₛ β) := { SimpleFunc.instPartialOrder with sup := (· ⊔ ·) le_sup_left := fun _ _ _ => le_sup_left le_sup_right := fun _ _ _ => le_sup_right sup_le := fun _f _g _h hfh hgh a => sup_le (hfh a) (hgh a) } instance instLattice [Lattice β] : Lattice (α →ₛ β) := { SimpleFunc.instSemilatticeSup, SimpleFunc.instSemilatticeInf with } instance instBoundedOrder [LE β] [BoundedOrder β] : BoundedOrder (α →ₛ β) := { SimpleFunc.instOrderBot, SimpleFunc.instOrderTop with } theorem finset_sup_apply [SemilatticeSup β] [OrderBot β] {f : γ → α →ₛ β} (s : Finset γ) (a : α) : s.sup f a = s.sup fun c => f c a := by classical refine Finset.induction_on s rfl ?_ intro a s _ ih rw [Finset.sup_insert, Finset.sup_insert, sup_apply, ih] section Restrict variable [Zero β] open scoped Classical in /-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/ def restrict (f : α →ₛ β) (s : Set α) : α →ₛ β := if hs : MeasurableSet s then piecewise s hs f 0 else 0 theorem restrict_of_not_measurable {f : α →ₛ β} {s : Set α} (hs : ¬MeasurableSet s) : restrict f s = 0 := dif_neg hs @[simp] theorem coe_restrict (f : α →ₛ β) {s : Set α} (hs : MeasurableSet s) : ⇑(restrict f s) = indicator s f := by classical rw [restrict, dif_pos hs, coe_piecewise, coe_zero, piecewise_eq_indicator] @[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f := by simp [restrict] @[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 := by simp [restrict] open scoped Classical in theorem map_restrict_of_zero [Zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : Set α) : (f.restrict s).map g = (f.map g).restrict s := ext fun x => if hs : MeasurableSet s then by simp [hs, Set.indicator_comp_of_zero hg] else by simp [restrict_of_not_measurable hs, hg] theorem map_coe_ennreal_restrict (f : α →ₛ ℝ≥0) (s : Set α) : (f.restrict s).map ((↑) : ℝ≥0 → ℝ≥0∞) = (f.map (↑)).restrict s := map_restrict_of_zero ENNReal.coe_zero _ _ theorem map_coe_nnreal_restrict (f : α →ₛ ℝ≥0) (s : Set α) : (f.restrict s).map ((↑) : ℝ≥0 → ℝ) = (f.map (↑)).restrict s := map_restrict_of_zero NNReal.coe_zero _ _ theorem restrict_apply (f : α →ₛ β) {s : Set α} (hs : MeasurableSet s) (a) : restrict f s a = indicator s f a := by simp only [f.coe_restrict hs] theorem restrict_preimage (f : α →ₛ β) {s : Set α} (hs : MeasurableSet s) {t : Set β} (ht : (0 : β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by simp [hs, indicator_preimage_of_notMem _ _ ht, inter_comm] theorem restrict_preimage_singleton (f : α →ₛ β) {s : Set α} (hs : MeasurableSet s) {r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} := f.restrict_preimage hs hr.symm theorem mem_restrict_range {r : β} {s : Set α} {f : α →ₛ β} (hs : MeasurableSet s) : r ∈ (restrict f s).range ↔ r = 0 ∧ s ≠ univ ∨ r ∈ f '' s := by rw [← Finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator] open scoped Classical in theorem mem_image_of_mem_range_restrict {r : β} {s : Set α} {f : α →ₛ β} (hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) : r ∈ f '' s := if hs : MeasurableSet s then by simpa [mem_restrict_range hs, h0, -mem_range] using hr else by rw [restrict_of_not_measurable hs] at hr exact (h0 <| eq_zero_of_mem_range_zero hr).elim open scoped Classical in @[gcongr, mono] theorem restrict_mono [Preorder β] (s : Set α) {f g : α →ₛ β} (H : f ≤ g) : f.restrict s ≤ g.restrict s := if hs : MeasurableSet s then fun x => by simp only [coe_restrict _ hs, indicator_le_indicator (H x)] else by simp only [restrict_of_not_measurable hs, le_refl] end Restrict section Approx section variable [SemilatticeSup β] [OrderBot β] [Zero β] /-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation by simple functions is defined so that in case `β = ℝ≥0∞` it sends each `a` to the supremum of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `iSup_approx_apply` for details. -/ def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (Finset.range n).sup fun k => restrict (const α (i k)) { a : α | i k ≤ f a } open scoped Classical in theorem approx_apply [TopologicalSpace β] [OrderClosedTopology β] [MeasurableSpace β] [OpensMeasurableSpace β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : Measurable f) : (approx i f n : α →ₛ β) a = (Finset.range n).sup fun k => if i k ≤ f a then i k else 0 := by dsimp only [approx] rw [finset_sup_apply] congr funext k rw [restrict_apply] · simp only [coe_const, mem_setOf_eq, indicator_apply, Function.const_apply] · exact hf measurableSet_Ici theorem monotone_approx (i : ℕ → β) (f : α → β) : Monotone (approx i f) := fun _ _ h => Finset.sup_mono <| Finset.range_subset.2 h theorem approx_comp [TopologicalSpace β] [OrderClosedTopology β] [MeasurableSpace β] [OpensMeasurableSpace β] [MeasurableSpace γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : Measurable f) (hg : Measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg), Function.comp_apply] end theorem iSup_approx_apply [TopologicalSpace β] [CompleteLattice β] [OrderClosedTopology β] [Zero β] [MeasurableSpace β] [OpensMeasurableSpace β] (i : ℕ → β) (f : α → β) (a : α) (hf : Measurable f) (h_zero : (0 : β) = ⊥) : ⨆ n, (approx i f n : α →ₛ β) a = ⨆ (k) (_ : i k ≤ f a), i k := by refine le_antisymm (iSup_le fun n => ?_) (iSup_le fun k => iSup_le fun hk => ?_) · rw [approx_apply a hf, h_zero] refine Finset.sup_le fun k _ => ?_ split_ifs with h · exact le_iSup_of_le k (le_iSup (fun _ : i k ≤ f a => i k) h) · exact bot_le · refine le_iSup_of_le (k + 1) ?_ rw [approx_apply a hf] have : k ∈ Finset.range (k + 1) := Finset.mem_range.2 (Nat.lt_succ_self _) refine le_trans (le_of_eq ?_) (Finset.le_sup this) rw [if_pos hk] end Approx section EApprox variable {f : α → ℝ≥0∞} /-- A sequence of `ℝ≥0∞`s such that its range is the set of non-negative rational numbers. -/ def ennrealRatEmbed (n : ℕ) : ℝ≥0∞ := ENNReal.ofReal ((Encodable.decode (α := ℚ) n).getD (0 : ℚ)) theorem ennrealRatEmbed_encode (q : ℚ) : ennrealRatEmbed (Encodable.encode q) = Real.toNNReal q := by rw [ennrealRatEmbed, Encodable.encodek]; rfl /-- Approximate a function `α → ℝ≥0∞` by a sequence of simple functions. -/ def eapprox : (α → ℝ≥0∞) → ℕ → α →ₛ ℝ≥0∞ := approx ennrealRatEmbed theorem eapprox_lt_top (f : α → ℝ≥0∞) (n : ℕ) (a : α) : eapprox f n a < ∞ := by simp only [eapprox, approx, finset_sup_apply, restrict] rw [Finset.sup_lt_iff (α := ℝ≥0∞) WithTop.top_pos] intro b _ split_ifs · simp only [coe_zero, coe_piecewise, piecewise_eq_indicator, coe_const] calc { a : α | ennrealRatEmbed b ≤ f a }.indicator (fun _ => ennrealRatEmbed b) a ≤ ennrealRatEmbed b := indicator_le_self _ _ a _ < ⊤ := ENNReal.coe_lt_top · exact WithTop.top_pos @[mono] theorem monotone_eapprox (f : α → ℝ≥0∞) : Monotone (eapprox f) := monotone_approx _ f @[gcongr] lemma eapprox_mono {m n : ℕ} (hmn : m ≤ n) : eapprox f m ≤ eapprox f n := monotone_eapprox _ hmn lemma iSup_eapprox_apply (hf : Measurable f) (a : α) : ⨆ n, (eapprox f n : α →ₛ ℝ≥0∞) a = f a := by rw [eapprox, iSup_approx_apply ennrealRatEmbed f a hf rfl] refine le_antisymm (iSup_le fun i => iSup_le fun hi => hi) (le_of_not_gt ?_) intro h rcases ENNReal.lt_iff_exists_rat_btwn.1 h with ⟨q, _, lt_q, q_lt⟩ have : (Real.toNNReal q : ℝ≥0∞) ≤ ⨆ (k : ℕ) (_ : ennrealRatEmbed k ≤ f a), ennrealRatEmbed k := by refine le_iSup_of_le (Encodable.encode q) ?_ rw [ennrealRatEmbed_encode q] exact le_iSup_of_le (le_of_lt q_lt) le_rfl exact lt_irrefl _ (lt_of_le_of_lt this lt_q) lemma iSup_coe_eapprox (hf : Measurable f) : ⨆ n, ⇑(eapprox f n) = f := by simpa [funext_iff] using iSup_eapprox_apply hf theorem eapprox_comp [MeasurableSpace γ] {f : γ → ℝ≥0∞} {g : α → γ} {n : ℕ} (hf : Measurable f) (hg : Measurable g) : (eapprox (f ∘ g) n : α → ℝ≥0∞) = (eapprox f n : γ →ₛ ℝ≥0∞) ∘ g := funext fun a => approx_comp a hf hg lemma tendsto_eapprox {f : α → ℝ≥0∞} (hf_meas : Measurable f) (a : α) : Tendsto (fun n ↦ eapprox f n a) atTop (𝓝 (f a)) := by nth_rw 2 [← iSup_coe_eapprox hf_meas] rw [iSup_apply] exact tendsto_atTop_iSup fun _ _ hnm ↦ monotone_eapprox f hnm a /-- Approximate a function `α → ℝ≥0∞` by a series of simple functions taking their values in `ℝ≥0`. -/ def eapproxDiff (f : α → ℝ≥0∞) : ℕ → α →ₛ ℝ≥0 | 0 => (eapprox f 0).map ENNReal.toNNReal | n + 1 => (eapprox f (n + 1) - eapprox f n).map ENNReal.toNNReal theorem sum_eapproxDiff (f : α → ℝ≥0∞) (n : ℕ) (a : α) : (∑ k ∈ Finset.range (n + 1), (eapproxDiff f k a : ℝ≥0∞)) = eapprox f n a := by induction n with | zero => simp [eapproxDiff, (eapprox_lt_top f 0 a).ne] | succ n IH => rw [Finset.sum_range_succ, IH, eapproxDiff, coe_map, Function.comp_apply, coe_sub, Pi.sub_apply, ENNReal.coe_toNNReal, add_tsub_cancel_of_le (monotone_eapprox f (Nat.le_succ _) _)] apply (lt_of_le_of_lt _ (eapprox_lt_top f (n + 1) a)).ne rw [tsub_le_iff_right] exact le_self_add theorem tsum_eapproxDiff (f : α → ℝ≥0∞) (hf : Measurable f) (a : α) : (∑' n, (eapproxDiff f n a : ℝ≥0∞)) = f a := by simp_rw [ENNReal.tsum_eq_iSup_nat' (tendsto_add_atTop_nat 1), sum_eapproxDiff, iSup_eapprox_apply hf a] end EApprox end Measurable section Measure variable {m : MeasurableSpace α} {μ ν : Measure α} /-- Integral of a simple function whose codomain is `ℝ≥0∞`. -/ def lintegral {_m : MeasurableSpace α} (f : α →ₛ ℝ≥0∞) (μ : Measure α) : ℝ≥0∞ := ∑ x ∈ f.range, x * μ (f ⁻¹' {x}) theorem lintegral_eq_of_subset (f : α →ₛ ℝ≥0∞) {s : Finset ℝ≥0∞} (hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) : f.lintegral μ = ∑ x ∈ s, x * μ (f ⁻¹' {x}) := by refine Finset.sum_bij_ne_zero (fun r _ _ => r) ?_ ?_ ?_ ?_ · simpa only [forall_mem_range, mul_ne_zero_iff, and_imp] · intros assumption · intro b _ hb refine ⟨b, ?_, hb, rfl⟩ rw [mem_range, ← preimage_singleton_nonempty] exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 · intros rfl theorem lintegral_eq_of_subset' (f : α →ₛ ℝ≥0∞) {s : Finset ℝ≥0∞} (hs : f.range \ {0} ⊆ s) : f.lintegral μ = ∑ x ∈ s, x * μ (f ⁻¹' {x}) := f.lintegral_eq_of_subset fun x hfx _ => hs <| Finset.mem_sdiff.2 ⟨f.mem_range_self x, mt Finset.mem_singleton.1 hfx⟩ /-- Calculate the integral of `(g ∘ f)`, where `g : β → ℝ≥0∞` and `f : α →ₛ β`. -/ theorem map_lintegral (g : β → ℝ≥0∞) (f : α →ₛ β) : (f.map g).lintegral μ = ∑ x ∈ f.range, g x * μ (f ⁻¹' {x}) := by simp only [lintegral, range_map] refine Finset.sum_image' _ fun b hb => ?_ rcases mem_range.1 hb with ⟨a, rfl⟩ rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, Finset.mul_sum] refine Finset.sum_congr ?_ ?_ · congr · grind theorem add_lintegral (f g : α →ₛ ℝ≥0∞) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ := calc (f + g).lintegral μ = ∑ x ∈ (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) := by rw [add_eq_map₂, map_lintegral]; exact Finset.sum_congr rfl fun a _ => add_mul _ _ _ _ = (∑ x ∈ (pair f g).range, x.1 * μ (pair f g ⁻¹' {x})) + ∑ x ∈ (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) := by rw [Finset.sum_add_distrib] _ = ((pair f g).map Prod.fst).lintegral μ + ((pair f g).map Prod.snd).lintegral μ := by rw [map_lintegral, map_lintegral] _ = lintegral f μ + lintegral g μ := rfl theorem const_mul_lintegral (f : α →ₛ ℝ≥0∞) (x : ℝ≥0∞) : (const α x * f).lintegral μ = x * f.lintegral μ := calc (f.map fun a => x * a).lintegral μ = ∑ r ∈ f.range, x * r * μ (f ⁻¹' {r}) := map_lintegral _ _ _ = x * ∑ r ∈ f.range, r * μ (f ⁻¹' {r}) := by simp_rw [Finset.mul_sum, mul_assoc] /-- Integral of a simple function `α →ₛ ℝ≥0∞` as a bilinear map. -/ def lintegralₗ {m : MeasurableSpace α} : (α →ₛ ℝ≥0∞) →ₗ[ℝ≥0∞] Measure α →ₗ[ℝ≥0∞] ℝ≥0∞ where toFun f := { toFun := lintegral f map_add' := by simp [lintegral, mul_add, Finset.sum_add_distrib] map_smul' := fun c μ => by simp [lintegral, mul_left_comm _ c, Finset.mul_sum, Measure.smul_apply c] } map_add' f g := LinearMap.ext fun _ => add_lintegral f g map_smul' c f := LinearMap.ext fun _ => const_mul_lintegral f c @[simp] theorem zero_lintegral : (0 : α →ₛ ℝ≥0∞).lintegral μ = 0 := LinearMap.ext_iff.1 lintegralₗ.map_zero μ theorem lintegral_add {ν} (f : α →ₛ ℝ≥0∞) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν := (lintegralₗ f).map_add μ ν theorem lintegral_smul {R : Type*} [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] (f : α →ₛ ℝ≥0∞) (c : R) : f.lintegral (c • μ) = c • f.lintegral μ := by simpa only [smul_one_smul] using (lintegralₗ f).map_smul (c • 1) μ @[simp] theorem lintegral_zero [MeasurableSpace α] (f : α →ₛ ℝ≥0∞) : f.lintegral 0 = 0 := (lintegralₗ f).map_zero theorem lintegral_finset_sum {ι} (f : α →ₛ ℝ≥0∞) (μ : ι → Measure α) (s : Finset ι) : f.lintegral (∑ i ∈ s, μ i) = ∑ i ∈ s, f.lintegral (μ i) := map_sum (lintegralₗ f) .. theorem lintegral_sum {m : MeasurableSpace α} {ι} (f : α →ₛ ℝ≥0∞) (μ : ι → Measure α) : f.lintegral (Measure.sum μ) = ∑' i, f.lintegral (μ i) := by simp only [lintegral, Measure.sum_apply, f.measurableSet_preimage, ← Finset.tsum_subtype, ← ENNReal.tsum_mul_left] apply ENNReal.tsum_comm open scoped Classical in theorem restrict_lintegral (f : α →ₛ ℝ≥0∞) {s : Set α} (hs : MeasurableSet s) : (restrict f s).lintegral μ = ∑ r ∈ f.range, r * μ (f ⁻¹' {r} ∩ s) := calc (restrict f s).lintegral μ = ∑ r ∈ f.range, r * μ (restrict f s ⁻¹' {r}) := lintegral_eq_of_subset _ fun x hx => if hxs : x ∈ s then fun _ => by simp only [f.restrict_apply hs, indicator_of_mem hxs, mem_range_self] else False.elim <| hx <| by simp [*] _ = ∑ r ∈ f.range, r * μ (f ⁻¹' {r} ∩ s) := Finset.sum_congr rfl <| forall_mem_range.2 fun b => if hb : f b = 0 then by simp only [hb, zero_mul] else by rw [restrict_preimage_singleton _ hs hb, inter_comm] theorem lintegral_restrict {m : MeasurableSpace α} (f : α →ₛ ℝ≥0∞) (s : Set α) (μ : Measure α) : f.lintegral (μ.restrict s) = ∑ y ∈ f.range, y * μ (f ⁻¹' {y} ∩ s) := by simp only [lintegral, Measure.restrict_apply, f.measurableSet_preimage] theorem restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ℝ≥0∞) {s : Set α} (hs : MeasurableSet s) : (restrict f s).lintegral μ = f.lintegral (μ.restrict s) := by rw [f.restrict_lintegral hs, lintegral_restrict] theorem lintegral_restrict_iUnion_of_directed {ι : Type*} [Countable ι] (f : α →ₛ ℝ≥0∞) {s : ι → Set α} (hd : Directed (· ⊆ ·) s) (μ : Measure α) : f.lintegral (μ.restrict (⋃ i, s i)) = ⨆ i, f.lintegral (μ.restrict (s i)) := by simp only [lintegral, Measure.restrict_iUnion_apply_eq_iSup hd (measurableSet_preimage ..), ENNReal.mul_iSup] refine finsetSum_iSup fun i j ↦ (hd i j).imp fun k ⟨hik, hjk⟩ ↦ fun a ↦ ?_ -- TODO https://github.com/leanprover-community/mathlib4/pull/14739 make `gcongr` close this goal constructor <;> · gcongr; refine Measure.restrict_mono ?_ le_rfl _; assumption theorem const_lintegral (c : ℝ≥0∞) : (const α c).lintegral μ = c * μ univ := by rw [lintegral] cases isEmpty_or_nonempty α · simp [μ.eq_zero_of_isEmpty] · simp only [range_const, coe_const, Finset.sum_singleton] unfold Function.const; rw [preimage_const_of_mem (mem_singleton c)] theorem const_lintegral_restrict (c : ℝ≥0∞) (s : Set α) : (const α c).lintegral (μ.restrict s) = c * μ s := by rw [const_lintegral, Measure.restrict_apply MeasurableSet.univ, univ_inter] theorem restrict_const_lintegral (c : ℝ≥0∞) {s : Set α} (hs : MeasurableSet s) : ((const α c).restrict s).lintegral μ = c * μ s := by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict] theorem lintegral_mono_fun {f g : α →ₛ ℝ≥0∞} (h : f ≤ g) : f.lintegral μ ≤ g.lintegral μ := by refine Monotone.of_left_le_map_sup (f := (lintegral · μ)) (fun f g ↦ ?_) h calc f.lintegral μ = ((pair f g).map Prod.fst).lintegral μ := by rw [map_fst_pair] _ ≤ ((pair f g).map fun p ↦ p.1 ⊔ p.2).lintegral μ := by simp only [map_lintegral] gcongr exact le_sup_left theorem le_sup_lintegral (f g : α →ₛ ℝ≥0∞) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ := Monotone.le_map_sup (fun _ _ ↦ lintegral_mono_fun) f g theorem lintegral_mono_measure {f : α →ₛ ℝ≥0∞} (h : μ ≤ ν) : f.lintegral μ ≤ f.lintegral ν := by simp only [lintegral] gcongr apply h /-- `SimpleFunc.lintegral` is monotone both in function and in measure. -/ @[mono, gcongr] theorem lintegral_mono {f g : α →ₛ ℝ≥0∞} (hfg : f ≤ g) (hμν : μ ≤ ν) : f.lintegral μ ≤ g.lintegral ν := (lintegral_mono_fun hfg).trans (lintegral_mono_measure hμν) /-- `SimpleFunc.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/ theorem lintegral_eq_of_measure_preimage [MeasurableSpace β] {f : α →ₛ ℝ≥0∞} {g : β →ₛ ℝ≥0∞} {ν : Measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) : f.lintegral μ = g.lintegral ν := by simp only [lintegral, ← H] apply lintegral_eq_of_subset simp only [H] intros exact mem_range_of_measure_ne_zero ‹_› /-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/ theorem lintegral_congr {f g : α →ₛ ℝ≥0∞} (h : f =ᵐ[μ] g) : f.lintegral μ = g.lintegral μ := lintegral_eq_of_measure_preimage fun y => measure_congr <| Eventually.set_eq <| h.mono fun x hx => by simp [hx] theorem lintegral_map' {β} [MeasurableSpace β] {μ' : Measure β} (f : α →ₛ ℝ≥0∞) (g : β →ₛ ℝ≥0∞) (m' : α → β) (eq : ∀ a, f a = g (m' a)) (h : ∀ s, MeasurableSet s → μ' s = μ (m' ⁻¹' s)) : f.lintegral μ = g.lintegral μ' := lintegral_eq_of_measure_preimage fun y => by simp only [preimage, eq] exact (h (g ⁻¹' {y}) (g.measurableSet_preimage _)).symm theorem lintegral_map {β} [MeasurableSpace β] (g : β →ₛ ℝ≥0∞) {f : α → β} (hf : Measurable f) : g.lintegral (Measure.map f μ) = (g.comp f hf).lintegral μ := Eq.symm <| lintegral_map' _ _ f (fun _ => rfl) fun _s hs => Measure.map_apply hf hs end Measure section FinMeasSupp open Finset Function open scoped Classical in theorem support_eq [MeasurableSpace α] [Zero β] (f : α →ₛ β) : support f = ⋃ y ∈ {y ∈ f.range | y ≠ 0}, f ⁻¹' {y} := Set.ext fun x => by simp only [mem_support, Set.mem_preimage, mem_filter, mem_range_self, true_and, exists_prop, mem_iUnion, mem_singleton_iff, exists_eq_right'] variable {m : MeasurableSpace α} [Zero β] [Zero γ] {μ : Measure α} {f : α →ₛ β} theorem measurableSet_support [MeasurableSpace α] (f : α →ₛ β) : MeasurableSet (support f) := by rw [f.support_eq] exact Finset.measurableSet_biUnion _ fun y _ => measurableSet_fiber _ _ lemma measure_support_lt_top (f : α →ₛ β) (hf : ∀ y, y ≠ 0 → μ (f ⁻¹' {y}) < ∞) : μ (support f) < ∞ := by classical rw [support_eq] refine (measure_biUnion_finset_le _ _).trans_lt (ENNReal.sum_lt_top.mpr fun y hy => ?_) rw [Finset.mem_filter] at hy exact hf y hy.2 /-- A `SimpleFunc` has finite measure support if it is equal to `0` outside of a set of finite measure. -/ protected def FinMeasSupp {_m : MeasurableSpace α} (f : α →ₛ β) (μ : Measure α) : Prop := f =ᶠ[μ.cofinite] 0 theorem finMeasSupp_iff_support : f.FinMeasSupp μ ↔ μ (support f) < ∞ := Iff.rfl theorem finMeasSupp_iff : f.FinMeasSupp μ ↔ ∀ y, y ≠ 0 → μ (f ⁻¹' {y}) < ∞ := by classical constructor · refine fun h y hy => lt_of_le_of_lt (measure_mono ?_) h exact fun x hx (H : f x = 0) => hy <| H ▸ Eq.symm hx · intro H rw [finMeasSupp_iff_support, support_eq] exact measure_biUnion_lt_top (finite_toSet _) fun y hy ↦ H y (mem_filter.1 hy).2 namespace FinMeasSupp theorem meas_preimage_singleton_ne_zero (h : f.FinMeasSupp μ) {y : β} (hy : y ≠ 0) : μ (f ⁻¹' {y}) < ∞ := finMeasSupp_iff.1 h y hy protected theorem map {g : β → γ} (hf : f.FinMeasSupp μ) (hg : g 0 = 0) : (f.map g).FinMeasSupp μ := flip lt_of_le_of_lt hf (measure_mono <| support_comp_subset hg f) theorem of_map {g : β → γ} (h : (f.map g).FinMeasSupp μ) (hg : ∀ b, g b = 0 → b = 0) : f.FinMeasSupp μ := flip lt_of_le_of_lt h <| measure_mono <| support_subset_comp @(hg) _ theorem map_iff {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) : (f.map g).FinMeasSupp μ ↔ f.FinMeasSupp μ := ⟨fun h => h.of_map fun _ => hg.1, fun h => h.map <| hg.2 rfl⟩ protected theorem pair {g : α →ₛ γ} (hf : f.FinMeasSupp μ) (hg : g.FinMeasSupp μ) : (pair f g).FinMeasSupp μ := calc μ (support <| pair f g) = μ (support f ∪ support g) := congr_arg μ <| support_prodMk f g _ ≤ μ (support f) + μ (support g) := measure_union_le _ _ _ < _ := add_lt_top.2 ⟨hf, hg⟩ protected theorem map₂ [Zero δ] (hf : f.FinMeasSupp μ) {g : α →ₛ γ} (hg : g.FinMeasSupp μ) {op : β → γ → δ} (H : op 0 0 = 0) : ((pair f g).map (Function.uncurry op)).FinMeasSupp μ := (hf.pair hg).map H protected theorem add {β} [AddZeroClass β] {f g : α →ₛ β} (hf : f.FinMeasSupp μ) (hg : g.FinMeasSupp μ) : (f + g).FinMeasSupp μ := by rw [add_eq_map₂] exact hf.map₂ hg (zero_add 0) protected theorem mul {β} [MulZeroClass β] {f g : α →ₛ β} (hf : f.FinMeasSupp μ) (hg : g.FinMeasSupp μ) : (f * g).FinMeasSupp μ := by rw [mul_eq_map₂] exact hf.map₂ hg (zero_mul 0) theorem lintegral_lt_top {f : α →ₛ ℝ≥0∞} (hm : f.FinMeasSupp μ) (hf : ∀ᵐ a ∂μ, f a ≠ ∞) : f.lintegral μ < ∞ := by refine sum_lt_top.2 fun a ha => ?_ rcases eq_or_ne a ∞ with (rfl | ha) · simp only [ae_iff, Ne, Classical.not_not] at hf simp [Set.preimage, hf] · by_cases ha0 : a = 0 · subst a simp · exact mul_lt_top ha.lt_top (finMeasSupp_iff.1 hm _ ha0) theorem of_lintegral_ne_top {f : α →ₛ ℝ≥0∞} (h : f.lintegral μ ≠ ∞) : f.FinMeasSupp μ := by refine finMeasSupp_iff.2 fun b hb => ?_ rw [f.lintegral_eq_of_subset' (Finset.subset_insert b _)] at h refine ENNReal.lt_top_of_mul_ne_top_right ?_ hb exact (lt_top_of_sum_ne_top h (Finset.mem_insert_self _ _)).ne theorem iff_lintegral_lt_top {f : α →ₛ ℝ≥0∞} (hf : ∀ᵐ a ∂μ, f a ≠ ∞) : f.FinMeasSupp μ ↔ f.lintegral μ < ∞ := ⟨fun h => h.lintegral_lt_top hf, fun h => of_lintegral_ne_top h.ne⟩ end FinMeasSupp lemma measure_support_lt_top_of_lintegral_ne_top {f : α →ₛ ℝ≥0∞} (hf : f.lintegral μ ≠ ∞) : μ (support f) < ∞ := by refine measure_support_lt_top f ?_ rw [← finMeasSupp_iff] exact FinMeasSupp.of_lintegral_ne_top hf end FinMeasSupp /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition (of functions with disjoint support). It is possible to make the hypotheses in `h_add` a bit stronger, and such conditions can be added once we need them (for example it is only necessary to consider the case where `g` is a multiple of a characteristic function, and that this multiple doesn't appear in the image of `f`). To use in an induction proof, the syntax is `induction f using SimpleFunc.induction with`. -/ @[elab_as_elim] protected theorem induction {α γ} [MeasurableSpace α] [AddZeroClass γ] {motive : SimpleFunc α γ → Prop} (const : ∀ (c) {s} (hs : MeasurableSet s), motive (SimpleFunc.piecewise s hs (SimpleFunc.const _ c) (SimpleFunc.const _ 0))) (add : ∀ ⦃f g : SimpleFunc α γ⦄, Disjoint (support f) (support g) → motive f → motive g → motive (f + g)) (f : SimpleFunc α γ) : motive f := by classical generalize h : f.range \ {0} = s rw [← Finset.coe_inj, Finset.coe_sdiff, Finset.coe_singleton, SimpleFunc.coe_range] at h induction s using Finset.induction generalizing f with | empty => rw [Finset.coe_empty, diff_eq_empty, range_subset_singleton] at h convert const 0 MeasurableSet.univ ext x simp [h] | insert x s hxs ih => have mx := f.measurableSet_preimage {x} let g := SimpleFunc.piecewise (f ⁻¹' {x}) mx 0 f have Pg : motive g := by apply ih simp only [g, SimpleFunc.coe_piecewise, range_piecewise] rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, h, Finset.coe_insert, insert_diff_self_of_notMem, diff_eq_empty.mpr, Set.empty_union] · rw [Set.image_subset_iff] convert Set.subset_univ _ exact preimage_const_of_mem (mem_singleton _) · rwa [Finset.mem_coe] convert add _ Pg (const x mx) · ext1 y by_cases hy : y ∈ f ⁻¹' {x} · simpa [g, hy] · simp [g, hy] rw [disjoint_iff_inf_le] rintro y by_cases hy : y ∈ f ⁻¹' {x} <;> simp [g, hy] /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for constant functions and that it is closed under piecewise combinations of functions. To use in an induction proof, the syntax is `induction f with`. -/ @[induction_eliminator] protected theorem induction' {α γ} [MeasurableSpace α] [Nonempty γ] {P : SimpleFunc α γ → Prop} (const : ∀ (c), P (SimpleFunc.const _ c)) (pcw : ∀ ⦃f g : SimpleFunc α γ⦄ {s} (hs : MeasurableSet s), P f → P g → P (f.piecewise s hs g)) (f : SimpleFunc α γ) : P f := by let c : γ := Classical.ofNonempty classical generalize h : f.range \ {c} = s rw [← Finset.coe_inj, Finset.coe_sdiff, Finset.coe_singleton, SimpleFunc.coe_range] at h induction s using Finset.induction generalizing f with | empty => rw [Finset.coe_empty, diff_eq_empty, range_subset_singleton] at h convert const c ext x simp [h] | insert x s hxs ih => have mx := f.measurableSet_preimage {x} let g := SimpleFunc.piecewise (f ⁻¹' {x}) mx (SimpleFunc.const α c) f have Pg : P g := by apply ih simp only [g, SimpleFunc.coe_piecewise, range_piecewise] rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, h, Finset.coe_insert, insert_diff_self_of_notMem, diff_eq_empty.mpr, Set.empty_union] · rw [Set.image_subset_iff] convert Set.subset_univ _ exact preimage_const_of_mem (mem_singleton _) · rwa [Finset.mem_coe] convert pcw mx.compl Pg (const x) · ext1 y by_cases hy : y ∈ f ⁻¹' {x} · simpa [g, hy] · simp [g, hy] /-- In a topological vector space, the addition of a measurable function and a simple function is measurable. -/ theorem _root_.Measurable.add_simpleFunc {E : Type*} {_ : MeasurableSpace α} [MeasurableSpace E] [AddCancelMonoid E] [MeasurableAdd E] {g : α → E} (hg : Measurable g) (f : SimpleFunc α E) : Measurable (g + (f : α → E)) := by classical induction f using SimpleFunc.induction with | @const c s hs => simp only [SimpleFunc.const_zero, SimpleFunc.coe_piecewise, SimpleFunc.coe_const, SimpleFunc.coe_zero] rw [← s.piecewise_same g, ← piecewise_add] exact Measurable.piecewise hs (hg.add_const _) (hg.add_const _) | @add f f' hff' hf hf' => have : (g + ↑(f + f')) = (Function.support f).piecewise (g + (f : α → E)) (g + f') := by ext x by_cases hx : x ∈ Function.support f · simpa only [SimpleFunc.coe_add, Pi.add_apply, Function.mem_support, ne_eq, not_not, Set.piecewise_eq_of_mem _ _ _ hx, _root_.add_right_inj, add_eq_left] using Set.disjoint_left.1 hff' hx · simpa only [SimpleFunc.coe_add, Pi.add_apply, Function.mem_support, ne_eq, not_not, Set.piecewise_eq_of_notMem _ _ _ hx, _root_.add_right_inj, add_eq_right] using hx rw [this] exact Measurable.piecewise f.measurableSet_support hf hf' /-- In a topological vector space, the addition of a simple function and a measurable function is measurable. -/ theorem _root_.Measurable.simpleFunc_add {E : Type*} {_ : MeasurableSpace α} [MeasurableSpace E] [AddCancelMonoid E] [MeasurableAdd E] {g : α → E} (hg : Measurable g) (f : SimpleFunc α E) : Measurable ((f : α → E) + g) := by classical induction f using SimpleFunc.induction with | @const c s hs => simp only [SimpleFunc.const_zero, SimpleFunc.coe_piecewise, SimpleFunc.coe_const, SimpleFunc.coe_zero] rw [← s.piecewise_same g, ← piecewise_add] exact Measurable.piecewise hs (hg.const_add _) (hg.const_add _) | @add f f' hff' hf hf' => have : (↑(f + f') + g) = (Function.support f).piecewise ((f : α → E) + g) (f' + g) := by ext x by_cases hx : x ∈ Function.support f · simpa only [coe_add, Pi.add_apply, Function.mem_support, ne_eq, not_not, Set.piecewise_eq_of_mem _ _ _ hx, _root_.add_left_inj, add_eq_left] using Set.disjoint_left.1 hff' hx · simpa only [SimpleFunc.coe_add, Pi.add_apply, Function.mem_support, ne_eq, not_not, Set.piecewise_eq_of_notMem _ _ _ hx, _root_.add_left_inj, add_eq_right] using hx rw [this] exact Measurable.piecewise f.measurableSet_support hf hf' end SimpleFunc end MeasureTheory open MeasureTheory MeasureTheory.SimpleFunc variable {α : Type*} {mα : MeasurableSpace α} {μ : Measure α} /-- To prove something for an arbitrary measurable function into `ℝ≥0∞`, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_add` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_elim] theorem Measurable.ennreal_induction {motive : (α → ℝ≥0∞) → Prop} (indicator : ∀ (c : ℝ≥0∞) ⦃s⦄, MeasurableSet s → motive (Set.indicator s fun _ => c)) (add : ∀ ⦃f g : α → ℝ≥0∞⦄, Disjoint (support f) (support g) → Measurable f → Measurable g → motive f → motive g → motive (f + g)) (iSup : ∀ ⦃f : ℕ → α → ℝ≥0∞⦄, (∀ n, Measurable (f n)) → Monotone f → (∀ n, motive (f n)) → motive fun x => ⨆ n, f n x) ⦃f : α → ℝ≥0∞⦄ (hf : Measurable f) : motive f := by convert iSup (fun n => (eapprox f n).measurable) (monotone_eapprox f) _ using 2 · rw [iSup_eapprox_apply hf] · exact fun n => SimpleFunc.induction (fun c s hs => indicator c hs) (fun f g hfg hf hg => add hfg f.measurable g.measurable hf hg) (eapprox f n) /-- To prove something for an arbitrary measurable function into `ℝ≥0∞`, it suffices to show that the property holds for (multiples of) characteristic functions with finite mass according to some sigma-finite measure and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_add` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_elim] lemma Measurable.ennreal_sigmaFinite_induction [SigmaFinite μ] {motive : (α → ℝ≥0∞) → Prop} (indicator : ∀ (c : ℝ≥0∞) ⦃s⦄, MeasurableSet s → μ s < ∞ → motive (Set.indicator s fun _ ↦ c)) (add : ∀ ⦃f g : α → ℝ≥0∞⦄, Disjoint (support f) (support g) → Measurable f → Measurable g → motive f → motive g → motive (f + g)) (iSup : ∀ ⦃f : ℕ → α → ℝ≥0∞⦄, (∀ n, Measurable (f n)) → Monotone f → (∀ n, motive (f n)) → motive fun x => ⨆ n, f n x) ⦃f : α → ℝ≥0∞⦄ (hf : Measurable f) : motive f := by refine Measurable.ennreal_induction (fun c s hs ↦ ?_) add iSup hf convert iSup (f := fun n ↦ (s ∩ spanningSets μ n).indicator fun _ ↦ c) (fun n ↦ measurable_const.indicator (hs.inter (measurableSet_spanningSets ..))) (fun m n hmn a ↦ Set.indicator_le_indicator_of_subset (by gcongr) (by simp) _) (fun n ↦ indicator _ (hs.inter (measurableSet_spanningSets ..)) (measure_inter_lt_top_of_right_ne_top (measure_spanningSets_lt_top ..).ne)) with a simp [← Set.indicator_iUnion_apply (M := ℝ≥0∞) rfl, ← Set.inter_iUnion]
Turan.lean
/- Copyright (c) 2024 Jeremy Tan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Tan -/ import Mathlib.Combinatorics.SimpleGraph.Clique import Mathlib.Order.Partition.Equipartition /-! # Turán's theorem In this file we prove Turán's theorem, the first important result of extremal graph theory, which states that the `r + 1`-cliquefree graph on `n` vertices with the most edges is the complete `r`-partite graph with part sizes as equal as possible (`turanGraph n r`). The forward direction of the proof performs "Zykov symmetrisation", which first shows constructively that non-adjacency is an equivalence relation in a maximal graph, so it must be complete multipartite with the parts being the equivalence classes. Then basic manipulations show that the graph is isomorphic to the Turán graph for the given parameters. For the reverse direction we first show that a Turán-maximal graph exists, then transfer the property through `turanGraph n r` using the isomorphism provided by the forward direction. ## Main declarations * `SimpleGraph.IsTuranMaximal`: `G.IsTuranMaximal r` means that `G` has the most number of edges for its number of vertices while still being `r + 1`-cliquefree. * `SimpleGraph.turanGraph n r`: The canonical `r + 1`-cliquefree Turán graph on `n` vertices. * `SimpleGraph.IsTuranMaximal.finpartition`: The result of Zykov symmetrisation, a finpartition of the vertices such that two vertices are in the same part iff they are non-adjacent. * `SimpleGraph.IsTuranMaximal.nonempty_iso_turanGraph`: The forward direction, an isomorphism between `G` satisfying `G.IsTuranMaximal r` and `turanGraph n r`. * `isTuranMaximal_of_iso`: the reverse direction, `G.IsTuranMaximal r` given the isomorphism. * `isTuranMaximal_iff_nonempty_iso_turanGraph`: Turán's theorem in full. ## References * https://en.wikipedia.org/wiki/Turán%27s_theorem -/ open Finset namespace SimpleGraph variable {V : Type*} [Fintype V] {G : SimpleGraph V} [DecidableRel G.Adj] {n r : ℕ} variable (G) in /-- An `r + 1`-cliquefree graph is `r`-Turán-maximal if any other `r + 1`-cliquefree graph on the same vertex set has the same or fewer number of edges. -/ def IsTuranMaximal (r : ℕ) : Prop := G.CliqueFree (r + 1) ∧ ∀ (H : SimpleGraph V) [DecidableRel H.Adj], H.CliqueFree (r + 1) → #H.edgeFinset ≤ #G.edgeFinset section Defs variable {H : SimpleGraph V} lemma IsTuranMaximal.le_iff_eq (hG : G.IsTuranMaximal r) (hH : H.CliqueFree (r + 1)) : G ≤ H ↔ G = H := by classical exact ⟨fun hGH ↦ edgeFinset_inj.1 <| eq_of_subset_of_card_le (edgeFinset_subset_edgeFinset.2 hGH) (hG.2 _ hH), le_of_eq⟩ /-- The canonical `r + 1`-cliquefree Turán graph on `n` vertices. -/ def turanGraph (n r : ℕ) : SimpleGraph (Fin n) where Adj v w := v % r ≠ w % r instance turanGraph.instDecidableRelAdj : DecidableRel (turanGraph n r).Adj := by dsimp only [turanGraph]; infer_instance @[simp] lemma turanGraph_zero : turanGraph n 0 = ⊤ := by ext a b; simp_rw [turanGraph, top_adj, Nat.mod_zero, not_iff_not, Fin.val_inj] @[simp] theorem turanGraph_eq_top : turanGraph n r = ⊤ ↔ r = 0 ∨ n ≤ r := by simp_rw [SimpleGraph.ext_iff, funext_iff, turanGraph, top_adj, eq_iff_iff, not_iff_not] refine ⟨fun h ↦ ?_, ?_⟩ · contrapose! h use ⟨0, (Nat.pos_of_ne_zero h.1).trans h.2⟩, ⟨r, h.2⟩ simp [h.1.symm] · rintro (rfl | h) a b · simp [Fin.val_inj] · rw [Nat.mod_eq_of_lt (a.2.trans_le h), Nat.mod_eq_of_lt (b.2.trans_le h), Fin.val_inj] theorem turanGraph_cliqueFree (hr : 0 < r) : (turanGraph n r).CliqueFree (r + 1) := by rw [cliqueFree_iff] by_contra h rw [not_isEmpty_iff] at h obtain ⟨f, ha⟩ := h simp only [turanGraph, top_adj] at ha obtain ⟨x, y, d, c⟩ := Fintype.exists_ne_map_eq_of_card_lt (fun x ↦ (⟨(f x).1 % r, Nat.mod_lt _ hr⟩ : Fin r)) (by simp) simp only [Fin.mk.injEq] at c exact absurd c ((@ha x y).mpr d) /-- An `r + 1`-cliquefree Turán-maximal graph is _not_ `r`-cliquefree if it can accommodate such a clique. -/ theorem not_cliqueFree_of_isTuranMaximal (hn : r ≤ Fintype.card V) (hG : G.IsTuranMaximal r) : ¬G.CliqueFree r := by rintro h obtain ⟨K, _, rfl⟩ := exists_subset_card_eq hn obtain ⟨a, -, b, -, hab, hGab⟩ : ∃ a ∈ K, ∃ b ∈ K, a ≠ b ∧ ¬ G.Adj a b := by simpa only [isNClique_iff, IsClique, Set.Pairwise, mem_coe, ne_eq, and_true, not_forall, exists_prop, exists_and_right] using h K exact hGab <| le_sup_right.trans_eq ((hG.le_iff_eq <| h.sup_edge _ _).1 le_sup_left).symm <| (edge_adj ..).2 ⟨Or.inl ⟨rfl, rfl⟩, hab⟩ lemma exists_isTuranMaximal (hr : 0 < r) : ∃ H : SimpleGraph V, ∃ _ : DecidableRel H.Adj, H.IsTuranMaximal r := by classical let c := {H : SimpleGraph V | H.CliqueFree (r + 1)} have cn : c.toFinset.Nonempty := ⟨⊥, by rw [Set.toFinset_setOf, mem_filter_univ] exact cliqueFree_bot (by omega)⟩ obtain ⟨S, Sm, Sl⟩ := exists_max_image c.toFinset (#·.edgeFinset) cn use S, inferInstance rw [Set.mem_toFinset] at Sm refine ⟨Sm, fun I _ cf ↦ ?_⟩ by_cases Im : I ∈ c.toFinset · convert Sl I Im · rw [Set.mem_toFinset] at Im contradiction end Defs namespace IsTuranMaximal variable {s t u : V} /-- In a Turán-maximal graph, non-adjacent vertices have the same degree. -/ lemma degree_eq_of_not_adj (h : G.IsTuranMaximal r) (hn : ¬G.Adj s t) : G.degree s = G.degree t := by rw [IsTuranMaximal] at h; contrapose! h; intro cf wlog hd : G.degree t < G.degree s generalizing G t s · replace hd : G.degree s < G.degree t := lt_of_le_of_ne (le_of_not_gt hd) h exact this (by rwa [adj_comm] at hn) hd.ne' cf hd classical use G.replaceVertex s t, inferInstance, cf.replaceVertex s t have := G.card_edgeFinset_replaceVertex_of_not_adj hn omega /-- In a Turán-maximal graph, non-adjacency is transitive. -/ lemma not_adj_trans (h : G.IsTuranMaximal r) (hts : ¬G.Adj t s) (hsu : ¬G.Adj s u) : ¬G.Adj t u := by have hst : ¬G.Adj s t := fun a ↦ hts a.symm have dst := h.degree_eq_of_not_adj hst have dsu := h.degree_eq_of_not_adj hsu rw [IsTuranMaximal] at h; contrapose! h; intro cf classical use (G.replaceVertex s t).replaceVertex s u, inferInstance, (cf.replaceVertex s t).replaceVertex s u have nst : s ≠ t := fun a ↦ hsu (a ▸ h) have ntu : t ≠ u := G.ne_of_adj h have := (G.adj_replaceVertex_iff_of_ne s nst ntu.symm).not.mpr hsu rw [card_edgeFinset_replaceVertex_of_not_adj _ this, card_edgeFinset_replaceVertex_of_not_adj _ hst, dst, Nat.add_sub_cancel] have l1 : (G.replaceVertex s t).degree s = G.degree s := by unfold degree; congr 1; ext v simp only [mem_neighborFinset] by_cases eq : v = t · simpa only [eq, not_adj_replaceVertex_same, false_iff] · rw [G.adj_replaceVertex_iff_of_ne s nst eq] have l2 : (G.replaceVertex s t).degree u = G.degree u - 1 := by rw [degree, degree, ← card_singleton t, ← card_sdiff (by simp [h.symm])] congr 1; ext v simp only [mem_neighborFinset, mem_sdiff, mem_singleton, replaceVertex] split_ifs <;> simp_all [adj_comm] have l3 : 0 < G.degree u := by rw [G.degree_pos_iff_exists_adj u]; use t, h.symm omega variable (h : G.IsTuranMaximal r) include h /-- In a Turán-maximal graph, non-adjacency is an equivalence relation. -/ theorem equivalence_not_adj : Equivalence (¬G.Adj · ·) where refl := by simp symm := by simp [adj_comm] trans := h.not_adj_trans /-- The non-adjacency setoid over the vertices of a Turán-maximal graph induced by `equivalence_not_adj`. -/ def setoid : Setoid V := ⟨_, h.equivalence_not_adj⟩ instance : DecidableRel h.setoid.r := inferInstanceAs <| DecidableRel (¬G.Adj · ·) /-- The finpartition derived from `h.setoid`. -/ def finpartition [DecidableEq V] : Finpartition (univ : Finset V) := Finpartition.ofSetoid h.setoid lemma not_adj_iff_part_eq [DecidableEq V] : ¬G.Adj s t ↔ h.finpartition.part s = h.finpartition.part t := by change h.setoid.r s t ↔ _ rw [← Finpartition.mem_part_ofSetoid_iff_rel] let fp := h.finpartition change t ∈ fp.part s ↔ fp.part s = fp.part t rw [fp.mem_part_iff_part_eq_part (mem_univ t) (mem_univ s), eq_comm] lemma degree_eq_card_sub_part_card [DecidableEq V] : G.degree s = Fintype.card V - #(h.finpartition.part s) := calc _ = #{t | G.Adj s t} := by simp [← card_neighborFinset_eq_degree, neighborFinset] _ = Fintype.card V - #{t | ¬G.Adj s t} := eq_tsub_of_add_eq (filter_card_add_filter_neg_card_eq_card _) _ = _ := by congr; ext; rw [mem_filter] convert Finpartition.mem_part_ofSetoid_iff_rel.symm simp [setoid] /-- The parts of a Turán-maximal graph form an equipartition. -/ theorem isEquipartition [DecidableEq V] : h.finpartition.IsEquipartition := by set fp := h.finpartition by_contra hn rw [Finpartition.not_isEquipartition] at hn obtain ⟨large, hl, small, hs, ineq⟩ := hn obtain ⟨w, hw⟩ := fp.nonempty_of_mem_parts hl obtain ⟨v, hv⟩ := fp.nonempty_of_mem_parts hs apply absurd h rw [IsTuranMaximal]; push_neg; intro cf use G.replaceVertex v w, inferInstance, cf.replaceVertex v w have large_eq := fp.part_eq_of_mem hl hw have small_eq := fp.part_eq_of_mem hs hv have ha : G.Adj v w := by by_contra hn; rw [h.not_adj_iff_part_eq, small_eq, large_eq] at hn rw [hn] at ineq; omega rw [G.card_edgeFinset_replaceVertex_of_adj ha, degree_eq_card_sub_part_card h, small_eq, degree_eq_card_sub_part_card h, large_eq] have : #large ≤ Fintype.card V := by simpa using card_le_card large.subset_univ omega lemma card_parts_le [DecidableEq V] : #h.finpartition.parts ≤ r := by by_contra! l obtain ⟨z, -, hz⟩ := h.finpartition.exists_subset_part_bijOn have ncf : ¬G.CliqueFree #z := by refine IsNClique.not_cliqueFree ⟨fun v hv w hw hn ↦ ?_, rfl⟩ contrapose! hn exact hz.injOn hv hw (by rwa [← h.not_adj_iff_part_eq]) rw [Finset.card_eq_of_equiv hz.equiv] at ncf exact absurd (h.1.mono (Nat.succ_le_of_lt l)) ncf /-- There are `min n r` parts in a graph on `n` vertices satisfying `G.IsTuranMaximal r`. `min` handles the `n < r` case, when `G` is complete but still `r + 1`-cliquefree for having insufficiently many vertices. -/ theorem card_parts [DecidableEq V] : #h.finpartition.parts = min (Fintype.card V) r := by set fp := h.finpartition apply le_antisymm (le_min fp.card_parts_le_card h.card_parts_le) by_contra! l rw [lt_min_iff] at l obtain ⟨x, -, y, -, hn, he⟩ := exists_ne_map_eq_of_card_lt_of_maps_to l.1 fun a _ ↦ fp.part_mem.2 (mem_univ a) apply absurd h rw [IsTuranMaximal]; push_neg; rintro - have cf : G.CliqueFree r := by simp_rw [← cliqueFinset_eq_empty_iff, cliqueFinset, filter_eq_empty_iff, mem_univ, forall_true_left, isNClique_iff, and_comm, not_and, isClique_iff, Set.Pairwise] #adaptation_note /-- 2025-07-19 added `-congrConsts` -/ intro z zc; push_neg; simp_rw -congrConsts [h.not_adj_iff_part_eq] exact exists_ne_map_eq_of_card_lt_of_maps_to (zc.symm ▸ l.2) fun a _ ↦ fp.part_mem.2 (mem_univ a) use G ⊔ edge x y, inferInstance, cf.sup_edge x y convert Nat.lt.base #G.edgeFinset convert G.card_edgeFinset_sup_edge _ hn rwa [h.not_adj_iff_part_eq] /-- **Turán's theorem**, forward direction. Any `r + 1`-cliquefree Turán-maximal graph on `n` vertices is isomorphic to `turanGraph n r`. -/ theorem nonempty_iso_turanGraph : Nonempty (G ≃g turanGraph (Fintype.card V) r) := by classical obtain ⟨zm, zp⟩ := h.isEquipartition.exists_partPreservingEquiv use (Equiv.subtypeUnivEquiv mem_univ).symm.trans zm intro a b simp_rw [turanGraph, Equiv.trans_apply, Equiv.subtypeUnivEquiv_symm_apply] have := zp ⟨a, mem_univ a⟩ ⟨b, mem_univ b⟩ rw [← h.not_adj_iff_part_eq] at this rw [← not_iff_not, not_ne_iff, this, card_parts] rcases le_or_gt r (Fintype.card V) with c | c · rw [min_eq_right c]; rfl · have lc : ∀ x, zm ⟨x, _⟩ < Fintype.card V := fun x ↦ (zm ⟨x, mem_univ x⟩).2 rw [min_eq_left c.le, Nat.mod_eq_of_lt (lc a), Nat.mod_eq_of_lt (lc b), ← Nat.mod_eq_of_lt ((lc a).trans c), ← Nat.mod_eq_of_lt ((lc b).trans c)]; rfl end IsTuranMaximal /-- **Turán's theorem**, reverse direction. Any graph isomorphic to `turanGraph n r` is itself Turán-maximal if `0 < r`. -/ theorem isTuranMaximal_of_iso (f : G ≃g turanGraph n r) (hr : 0 < r) : G.IsTuranMaximal r := by obtain ⟨J, _, j⟩ := exists_isTuranMaximal (V := V) hr obtain ⟨g⟩ := j.nonempty_iso_turanGraph rw [f.card_eq, Fintype.card_fin] at g use (turanGraph_cliqueFree (n := n) hr).comap f, fun H _ cf ↦ (f.symm.comp g).card_edgeFinset_eq ▸ j.2 H cf /-- Turán-maximality with `0 < r` transfers across graph isomorphisms. -/ theorem IsTuranMaximal.iso {W : Type*} [Fintype W] {H : SimpleGraph W} [DecidableRel H.Adj] (h : G.IsTuranMaximal r) (f : G ≃g H) (hr : 0 < r) : H.IsTuranMaximal r := isTuranMaximal_of_iso (h.nonempty_iso_turanGraph.some.comp f.symm) hr /-- For `0 < r`, `turanGraph n r` is Turán-maximal. -/ theorem isTuranMaximal_turanGraph (hr : 0 < r) : (turanGraph n r).IsTuranMaximal r := isTuranMaximal_of_iso Iso.refl hr /-- **Turán's theorem**. `turanGraph n r` is, up to isomorphism, the unique `r + 1`-cliquefree Turán-maximal graph on `n` vertices. -/ theorem isTuranMaximal_iff_nonempty_iso_turanGraph (hr : 0 < r) : G.IsTuranMaximal r ↔ Nonempty (G ≃g turanGraph (Fintype.card V) r) := ⟨fun h ↦ h.nonempty_iso_turanGraph, fun h ↦ isTuranMaximal_of_iso h.some hr⟩ end SimpleGraph
TMComputable.lean
/- Copyright (c) 2020 Pim Spelier, Daan van Gent. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pim Spelier, Daan van Gent -/ import Mathlib.Algebra.Polynomial.Eval.Defs import Mathlib.Computability.Encoding import Mathlib.Computability.TuringMachine /-! # Computable functions This file contains the definition of a Turing machine with some finiteness conditions (bundling the definition of TM2 in `TuringMachine.lean`), a definition of when a TM gives a certain output (in a certain time), and the definition of computability (in polynomial time or any time function) of a function between two types that have an encoding (as in `Encoding.lean`). ## Main theorems - `idComputableInPolyTime` : a TM + a proof it computes the identity on a type in polytime. - `idComputable` : a TM + a proof it computes the identity on a type. ## Implementation notes To count the execution time of a Turing machine, we have decided to count the number of times the `step` function is used. Each step executes a statement (of type `Stmt`); this is a function, and generally contains multiple "fundamental" steps (pushing, popping, and so on). However, as functions only contain a finite number of executions and each one is executed at most once, this execution time is up to multiplication by a constant the amount of fundamental steps. -/ open Computability namespace Turing /-- A bundled TM2 (an equivalent of the classical Turing machine, defined starting from the namespace `Turing.TM2` in `TuringMachine.lean`), with an input and output stack, a main function, an initial state and some finiteness guarantees. -/ structure FinTM2 where /-- index type of stacks -/ {K : Type} [kDecidableEq : DecidableEq K] /-- A TM2 machine has finitely many stacks. -/ [kFin : Fintype K] /-- input resp. output stack -/ (k₀ k₁ : K) /-- type of stack elements -/ (Γ : K → Type) /-- type of function labels -/ (Λ : Type) /-- a main function: the initial function that is executed, given by its label -/ (main : Λ) /-- A TM2 machine has finitely many function labels. -/ [ΛFin : Fintype Λ] /-- type of states of the machine -/ (σ : Type) /-- the initial state of the machine -/ (initialState : σ) /-- a TM2 machine has finitely many internal states. -/ [σFin : Fintype σ] /-- Each internal stack is finite. -/ [Γk₀Fin : Fintype (Γ k₀)] /-- the program itself, i.e. one function for every function label -/ (m : Λ → Turing.TM2.Stmt Γ Λ σ) attribute [nolint docBlame] FinTM2.kDecidableEq namespace FinTM2 section variable (tm : FinTM2) instance decidableEqK : DecidableEq tm.K := tm.kDecidableEq instance inhabitedσ : Inhabited tm.σ := ⟨tm.initialState⟩ /-- The type of statements (functions) corresponding to this TM. -/ def Stmt : Type := Turing.TM2.Stmt tm.Γ tm.Λ tm.σ instance inhabitedStmt : Inhabited (Stmt tm) := inferInstanceAs (Inhabited (Turing.TM2.Stmt tm.Γ tm.Λ tm.σ)) /-- The type of configurations (functions) corresponding to this TM. -/ def Cfg : Type := Turing.TM2.Cfg tm.Γ tm.Λ tm.σ instance inhabitedCfg : Inhabited (Cfg tm) := Turing.TM2.Cfg.inhabited _ _ _ /-- The step function corresponding to this TM. -/ @[simp] def step : tm.Cfg → Option tm.Cfg := Turing.TM2.step tm.m end end FinTM2 /-- The initial configuration corresponding to a list in the input alphabet. -/ def initList (tm : FinTM2) (s : List (tm.Γ tm.k₀)) : tm.Cfg where l := Option.some tm.main var := tm.initialState stk k := @dite (List (tm.Γ k)) (k = tm.k₀) (tm.kDecidableEq k tm.k₀) (fun h => by rw [h]; exact s) fun _ => [] /-- The final configuration corresponding to a list in the output alphabet. -/ def haltList (tm : FinTM2) (s : List (tm.Γ tm.k₁)) : tm.Cfg where l := Option.none var := tm.initialState stk k := @dite (List (tm.Γ k)) (k = tm.k₁) (tm.kDecidableEq k tm.k₁) (fun h => by rw [h]; exact s) fun _ => [] /-- A "proof" of the fact that `f` eventually reaches `b` when repeatedly evaluated on `a`, remembering the number of steps it takes. -/ structure EvalsTo {σ : Type*} (f : σ → Option σ) (a : σ) (b : Option σ) where /-- number of steps taken -/ steps : ℕ evals_in_steps : (flip bind f)^[steps] a = b -- note: this cannot currently be used in `calc`, as the last two arguments must be `a` and `b`. -- If this is desired, this argument order can be changed, but this spelling is I think the most -- natural, so there is a trade-off that needs to be made here. A notation can get around this. /-- A "proof" of the fact that `f` eventually reaches `b` in at most `m` steps when repeatedly evaluated on `a`, remembering the number of steps it takes. -/ structure EvalsToInTime {σ : Type*} (f : σ → Option σ) (a : σ) (b : Option σ) (m : ℕ) extends EvalsTo f a b where steps_le_m : steps ≤ m /-- Reflexivity of `EvalsTo` in 0 steps. -/ def EvalsTo.refl {σ : Type*} (f : σ → Option σ) (a : σ) : EvalsTo f a (some a) := ⟨0, rfl⟩ /-- Transitivity of `EvalsTo` in the sum of the numbers of steps. -/ @[trans] def EvalsTo.trans {σ : Type*} (f : σ → Option σ) (a : σ) (b : σ) (c : Option σ) (h₁ : EvalsTo f a b) (h₂ : EvalsTo f b c) : EvalsTo f a c := ⟨h₂.steps + h₁.steps, by rw [Function.iterate_add_apply, h₁.evals_in_steps, h₂.evals_in_steps]⟩ /-- Reflexivity of `EvalsToInTime` in 0 steps. -/ def EvalsToInTime.refl {σ : Type*} (f : σ → Option σ) (a : σ) : EvalsToInTime f a (some a) 0 := ⟨EvalsTo.refl f a, le_refl 0⟩ /-- Transitivity of `EvalsToInTime` in the sum of the numbers of steps. -/ @[trans] def EvalsToInTime.trans {σ : Type*} (f : σ → Option σ) (m₁ : ℕ) (m₂ : ℕ) (a : σ) (b : σ) (c : Option σ) (h₁ : EvalsToInTime f a b m₁) (h₂ : EvalsToInTime f b c m₂) : EvalsToInTime f a c (m₂ + m₁) := ⟨EvalsTo.trans f a b c h₁.toEvalsTo h₂.toEvalsTo, add_le_add h₂.steps_le_m h₁.steps_le_m⟩ /-- A proof of tm outputting l' when given l. -/ def TM2Outputs (tm : FinTM2) (l : List (tm.Γ tm.k₀)) (l' : Option (List (tm.Γ tm.k₁))) := EvalsTo tm.step (initList tm l) ((Option.map (haltList tm)) l') /-- A proof of tm outputting l' when given l in at most m steps. -/ def TM2OutputsInTime (tm : FinTM2) (l : List (tm.Γ tm.k₀)) (l' : Option (List (tm.Γ tm.k₁))) (m : ℕ) := EvalsToInTime tm.step (initList tm l) ((Option.map (haltList tm)) l') m /-- The forgetful map, forgetting the upper bound on the number of steps. -/ def TM2OutputsInTime.toTM2Outputs {tm : FinTM2} {l : List (tm.Γ tm.k₀)} {l' : Option (List (tm.Γ tm.k₁))} {m : ℕ} (h : TM2OutputsInTime tm l l' m) : TM2Outputs tm l l' := h.toEvalsTo /-- A (bundled TM2) Turing machine with input alphabet equivalent to `Γ₀` and output alphabet equivalent to `Γ₁`. -/ structure TM2ComputableAux (Γ₀ Γ₁ : Type) where /-- the underlying bundled TM2 -/ tm : FinTM2 /-- the input alphabet is equivalent to `Γ₀` -/ inputAlphabet : tm.Γ tm.k₀ ≃ Γ₀ /-- the output alphabet is equivalent to `Γ₁` -/ outputAlphabet : tm.Γ tm.k₁ ≃ Γ₁ /-- A Turing machine + a proof it outputs `f`. -/ structure TM2Computable {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β) (f : α → β) extends TM2ComputableAux ea.Γ eb.Γ where /-- a proof this machine outputs `f` -/ outputsFun : ∀ a, TM2Outputs tm (List.map inputAlphabet.invFun (ea.encode a)) (Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a)))) /-- A Turing machine + a time function + a proof it outputs `f` in at most `time(input.length)` steps. -/ structure TM2ComputableInTime {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β) (f : α → β) extends TM2ComputableAux ea.Γ eb.Γ where /-- a time function -/ time : ℕ → ℕ /-- proof this machine outputs `f` in at most `time(input.length)` steps -/ outputsFun : ∀ a, TM2OutputsInTime tm (List.map inputAlphabet.invFun (ea.encode a)) (Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a)))) (time (ea.encode a).length) /-- A Turing machine + a polynomial time function + a proof it outputs `f` in at most `time(input.length)` steps. -/ structure TM2ComputableInPolyTime {α β : Type} (ea : FinEncoding α) (eb : FinEncoding β) (f : α → β) extends TM2ComputableAux ea.Γ eb.Γ where /-- a polynomial time function -/ time : Polynomial ℕ /-- proof that this machine outputs `f` in at most `time(input.length)` steps -/ outputsFun : ∀ a, TM2OutputsInTime tm (List.map inputAlphabet.invFun (ea.encode a)) (Option.some ((List.map outputAlphabet.invFun) (eb.encode (f a)))) (time.eval (ea.encode a).length) /-- A forgetful map, forgetting the time bound on the number of steps. -/ def TM2ComputableInTime.toTM2Computable {α β : Type} {ea : FinEncoding α} {eb : FinEncoding β} {f : α → β} (h : TM2ComputableInTime ea eb f) : TM2Computable ea eb f := ⟨h.toTM2ComputableAux, fun a => TM2OutputsInTime.toTM2Outputs (h.outputsFun a)⟩ /-- A forgetful map, forgetting that the time function is polynomial. -/ def TM2ComputableInPolyTime.toTM2ComputableInTime {α β : Type} {ea : FinEncoding α} {eb : FinEncoding β} {f : α → β} (h : TM2ComputableInPolyTime ea eb f) : TM2ComputableInTime ea eb f := ⟨h.toTM2ComputableAux, fun n => h.time.eval n, h.outputsFun⟩ open Turing.TM2.Stmt /-- A Turing machine computing the identity on α. -/ def idComputer {α : Type} (ea : FinEncoding α) : FinTM2 where K := Unit k₀ := ⟨⟩ k₁ := ⟨⟩ Γ _ := ea.Γ Λ := Unit main := ⟨⟩ σ := Unit initialState := ⟨⟩ Γk₀Fin := ea.ΓFin m _ := halt instance inhabitedFinTM2 : Inhabited FinTM2 := ⟨idComputer Computability.inhabitedFinEncoding.default⟩ noncomputable section /-- A proof that the identity map on α is computable in polytime. -/ def idComputableInPolyTime {α : Type} (ea : FinEncoding α) : @TM2ComputableInPolyTime α α ea ea id where tm := idComputer ea inputAlphabet := Equiv.cast rfl outputAlphabet := Equiv.cast rfl time := 1 outputsFun _ := { steps := 1 evals_in_steps := rfl steps_le_m := by simp only [Polynomial.eval_one, le_refl] } instance inhabitedTM2ComputableInPolyTime : Inhabited (TM2ComputableInPolyTime (default : FinEncoding Bool) default id) := ⟨idComputableInPolyTime Computability.inhabitedFinEncoding.default⟩ instance inhabitedTM2OutputsInTime : Inhabited (TM2OutputsInTime (idComputer finEncodingBoolBool) (List.map (Equiv.cast rfl).invFun [false]) (some (List.map (Equiv.cast rfl).invFun [false])) (Polynomial.eval 1 1)) := ⟨(idComputableInPolyTime finEncodingBoolBool).outputsFun false⟩ instance inhabitedTM2Outputs : Inhabited (TM2Outputs (idComputer finEncodingBoolBool) (List.map (Equiv.cast rfl).invFun [false]) (some (List.map (Equiv.cast rfl).invFun [false]))) := ⟨TM2OutputsInTime.toTM2Outputs Turing.inhabitedTM2OutputsInTime.default⟩ instance inhabitedEvalsToInTime : Inhabited (EvalsToInTime (fun _ : Unit => some ⟨⟩) ⟨⟩ (some ⟨⟩) 0) := ⟨EvalsToInTime.refl _ _⟩ instance inhabitedTM2EvalsTo : Inhabited (EvalsTo (fun _ : Unit => some ⟨⟩) ⟨⟩ (some ⟨⟩)) := ⟨EvalsTo.refl _ _⟩ /-- A proof that the identity map on α is computable in time. -/ def idComputableInTime {α : Type} (ea : FinEncoding α) : @TM2ComputableInTime α α ea ea id := TM2ComputableInPolyTime.toTM2ComputableInTime <| idComputableInPolyTime ea instance inhabitedTM2ComputableInTime : Inhabited (TM2ComputableInTime finEncodingBoolBool finEncodingBoolBool id) := ⟨idComputableInTime Computability.inhabitedFinEncoding.default⟩ /-- A proof that the identity map on α is computable. -/ def idComputable {α : Type} (ea : FinEncoding α) : @TM2Computable α α ea ea id := TM2ComputableInTime.toTM2Computable <| idComputableInTime ea instance inhabitedTM2Computable : Inhabited (TM2Computable finEncodingBoolBool finEncodingBoolBool id) := ⟨idComputable Computability.inhabitedFinEncoding.default⟩ instance inhabitedTM2ComputableAux : Inhabited (TM2ComputableAux Bool Bool) := ⟨(default : TM2Computable finEncodingBoolBool finEncodingBoolBool id).toTM2ComputableAux⟩ /-- For any two polynomial time Multi-tape Turing Machines, there exists another polynomial time multi-tape Turing Machine that composes their operations. This machine can work by simply having one tape for each tape in both of the composed TMs. It first carries out the operations of the first TM on the tapes associated with the first TM, then copies the output tape of the first TM to the input tape of the second TM, then runs the second TM. -/ proof_wanted TM2ComputableInPolyTime.comp {α β γ : Type} {eα : FinEncoding α} {eβ : FinEncoding β} {eγ : FinEncoding γ} {f : α → β} {g : β → γ} (h1 : TM2ComputableInPolyTime eα eβ f) (h2 : TM2ComputableInPolyTime eβ eγ g) : Nonempty (TM2ComputableInPolyTime eα eγ (g ∘ f)) end end Turing
DistribMulAction.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.Submonoid.MulAction import Mathlib.Algebra.GroupWithZero.Action.Defs /-! # Distributive actions by submonoids -/ assert_not_exists RelIso Ring namespace Submonoid variable {M α : Type*} [Monoid M] variable {S : Type*} [SetLike S M] (s : S) [SubmonoidClass S M] instance (priority := low) [AddMonoid α] [DistribMulAction M α] : DistribMulAction s α where smul_zero r := smul_zero (r : M) smul_add r := smul_add (r : M) /-- The action by a submonoid is the action by the underlying monoid. -/ instance distribMulAction [AddMonoid α] [DistribMulAction M α] (S : Submonoid M) : DistribMulAction S α := inferInstance instance (priority := low) [Monoid α] [MulDistribMulAction M α] : MulDistribMulAction s α where smul_mul r := smul_mul' (r : M) smul_one r := smul_one (r : M) /-- The action by a submonoid is the action by the underlying monoid. -/ instance mulDistribMulAction [Monoid α] [MulDistribMulAction M α] (S : Submonoid M) : MulDistribMulAction S α := inferInstance end Submonoid
CochainComplex.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.Embedding.TruncLEHomology import Mathlib.Algebra.Homology.HomotopyCategory.SingleFunctors import Mathlib.Algebra.Homology.HomotopyCategory.ShiftSequence /-! # Truncations on cochain complexes indexed by the integers. In this file, we introduce abbreviations for the canonical truncations `CochainComplex.truncLE`, `CochainComplex.truncGE` of cochain complexes indexed by `ℤ`, as well as the conditions `CochainComplex.IsStrictlyLE`, `CochainComplex.IsStrictlyGE`, `CochainComplex.IsLE`, and `CochainComplex.IsGE`. -/ open CategoryTheory Category Limits ComplexShape ZeroObject namespace CochainComplex variable {C : Type*} [Category C] open HomologicalComplex section HasZeroMorphisms variable [HasZeroMorphisms C] (K L : CochainComplex C ℤ) (φ : K ⟶ L) (e : K ≅ L) section variable [HasZeroObject C] [∀ i, K.HasHomology i] [∀ i, L.HasHomology i] /-- If `K : CochainComplex C ℤ`, this is the canonical truncation `≤ n` of `K`. -/ noncomputable abbrev truncLE (n : ℤ) : CochainComplex C ℤ := HomologicalComplex.truncLE K (embeddingUpIntLE n) /-- If `K : CochainComplex C ℤ`, this is the canonical truncation `≥ n` of `K`. -/ noncomputable abbrev truncGE (n : ℤ) : CochainComplex C ℤ := HomologicalComplex.truncGE K (embeddingUpIntGE n) /-- The canonical map `K.truncLE n ⟶ K` for `K : CochainComplex C ℤ`. -/ noncomputable def ιTruncLE (n : ℤ) : K.truncLE n ⟶ K := HomologicalComplex.ιTruncLE K (embeddingUpIntLE n) /-- The canonical map `K ⟶ K.truncGE n` for `K : CochainComplex C ℤ`. -/ noncomputable def πTruncGE (n : ℤ) : K ⟶ K.truncGE n := HomologicalComplex.πTruncGE K (embeddingUpIntGE n) section variable {K L} /-- The morphism `K.truncLE n ⟶ L.truncLE n` induced by a morphism `K ⟶ L`. -/ noncomputable abbrev truncLEMap (n : ℤ) : K.truncLE n ⟶ L.truncLE n := HomologicalComplex.truncLEMap φ (embeddingUpIntLE n) /-- The morphism `K.truncGE n ⟶ L.truncGE n` induced by a morphism `K ⟶ L`. -/ noncomputable abbrev truncGEMap (n : ℤ) : K.truncGE n ⟶ L.truncGE n := HomologicalComplex.truncGEMap φ (embeddingUpIntGE n) @[reassoc (attr := simp)] lemma ιTruncLE_naturality (n : ℤ) : truncLEMap φ n ≫ L.ιTruncLE n = K.ιTruncLE n ≫ φ := by apply HomologicalComplex.ιTruncLE_naturality @[reassoc (attr := simp)] lemma πTruncGE_naturality (n : ℤ) : K.πTruncGE n ≫ truncGEMap φ n = φ ≫ L.πTruncGE n := by apply HomologicalComplex.πTruncGE_naturality end end /-- The condition that a cochain complex `K` is strictly `≥ n`. -/ abbrev IsStrictlyGE (n : ℤ) := K.IsStrictlySupported (embeddingUpIntGE n) /-- The condition that a cochain complex `K` is strictly `≤ n`. -/ abbrev IsStrictlyLE (n : ℤ) := K.IsStrictlySupported (embeddingUpIntLE n) /-- The condition that a cochain complex `K` is (cohomologically) `≥ n`. -/ abbrev IsGE (n : ℤ) := K.IsSupported (embeddingUpIntGE n) /-- The condition that a cochain complex `K` is (cohomologically) `≤ n`. -/ abbrev IsLE (n : ℤ) := K.IsSupported (embeddingUpIntLE n) lemma isZero_of_isStrictlyGE (n i : ℤ) (hi : i < n) [K.IsStrictlyGE n] : IsZero (K.X i) := isZero_X_of_isStrictlySupported K (embeddingUpIntGE n) i (by simpa only [notMem_range_embeddingUpIntGE_iff] using hi) lemma isZero_of_isStrictlyLE (n i : ℤ) (hi : n < i) [K.IsStrictlyLE n] : IsZero (K.X i) := isZero_X_of_isStrictlySupported K (embeddingUpIntLE n) i (by simpa only [notMem_range_embeddingUpIntLE_iff] using hi) lemma exactAt_of_isGE (n i : ℤ) (hi : i < n) [K.IsGE n] : K.ExactAt i := exactAt_of_isSupported K (embeddingUpIntGE n) i (by simpa only [notMem_range_embeddingUpIntGE_iff] using hi) lemma exactAt_of_isLE (n i : ℤ) (hi : n < i) [K.IsLE n] : K.ExactAt i := exactAt_of_isSupported K (embeddingUpIntLE n) i (by simpa only [notMem_range_embeddingUpIntLE_iff] using hi) lemma isZero_of_isGE (n i : ℤ) (hi : i < n) [K.IsGE n] [K.HasHomology i] : IsZero (K.homology i) := (K.exactAt_of_isGE n i hi).isZero_homology lemma isZero_of_isLE (n i : ℤ) (hi : n < i) [K.IsLE n] [K.HasHomology i] : IsZero (K.homology i) := (K.exactAt_of_isLE n i hi).isZero_homology lemma isStrictlyGE_iff (n : ℤ) : K.IsStrictlyGE n ↔ ∀ (i : ℤ) (_ : i < n), IsZero (K.X i) := by constructor · intro _ i hi exact K.isZero_of_isStrictlyGE n i hi · intro h refine IsStrictlySupported.mk (fun i hi ↦ ?_) rw [notMem_range_embeddingUpIntGE_iff] at hi exact h i hi lemma isStrictlyLE_iff (n : ℤ) : K.IsStrictlyLE n ↔ ∀ (i : ℤ) (_ : n < i), IsZero (K.X i) := by constructor · intro _ i hi exact K.isZero_of_isStrictlyLE n i hi · intro h refine IsStrictlySupported.mk (fun i hi ↦ ?_) rw [notMem_range_embeddingUpIntLE_iff] at hi exact h i hi lemma isGE_iff (n : ℤ) : K.IsGE n ↔ ∀ (i : ℤ) (_ : i < n), K.ExactAt i := by constructor · intro _ i hi exact K.exactAt_of_isGE n i hi · intro h refine IsSupported.mk (fun i hi ↦ ?_) rw [notMem_range_embeddingUpIntGE_iff] at hi exact h i hi lemma isLE_iff (n : ℤ) : K.IsLE n ↔ ∀ (i : ℤ) (_ : n < i), K.ExactAt i := by constructor · intro _ i hi exact K.exactAt_of_isLE n i hi · intro h refine IsSupported.mk (fun i hi ↦ ?_) rw [notMem_range_embeddingUpIntLE_iff] at hi exact h i hi lemma isStrictlyLE_of_le (p q : ℤ) (hpq : p ≤ q) [K.IsStrictlyLE p] : K.IsStrictlyLE q := by rw [isStrictlyLE_iff] intro i hi apply K.isZero_of_isStrictlyLE p omega lemma isStrictlyGE_of_ge (p q : ℤ) (hpq : p ≤ q) [K.IsStrictlyGE q] : K.IsStrictlyGE p := by rw [isStrictlyGE_iff] intro i hi apply K.isZero_of_isStrictlyGE q omega lemma isLE_of_le (p q : ℤ) (hpq : p ≤ q) [K.IsLE p] : K.IsLE q := by rw [isLE_iff] intro i hi apply K.exactAt_of_isLE p omega lemma isGE_of_ge (p q : ℤ) (hpq : p ≤ q) [K.IsGE q] : K.IsGE p := by rw [isGE_iff] intro i hi apply K.exactAt_of_isGE q omega section variable {K L} include e lemma isStrictlyLE_of_iso (n : ℤ) [K.IsStrictlyLE n] : L.IsStrictlyLE n := by apply isStrictlySupported_of_iso e lemma isStrictlyGE_of_iso (n : ℤ) [K.IsStrictlyGE n] : L.IsStrictlyGE n := by apply isStrictlySupported_of_iso e lemma isLE_of_iso (n : ℤ) [K.IsLE n] : L.IsLE n := by apply isSupported_of_iso e lemma isGE_of_iso (n : ℤ) [K.IsGE n] : L.IsGE n := by apply isSupported_of_iso e end section variable [HasZeroObject C] /-- A cochain complex that is both strictly `≤ n` and `≥ n` is isomorphic to a complex `(single _ _ n).obj M` for some object `M`. -/ lemma exists_iso_single (n : ℤ) [K.IsStrictlyGE n] [K.IsStrictlyLE n] : ∃ (M : C), Nonempty (K ≅ (single _ _ n).obj M) := ⟨K.X n, ⟨{ hom := mkHomToSingle (𝟙 _) (fun i (hi : i + 1 = n) ↦ (K.isZero_of_isStrictlyGE n i (by omega)).eq_of_src _ _) inv := mkHomFromSingle (𝟙 _) (fun i (hi : n + 1 = i) ↦ (K.isZero_of_isStrictlyLE n i (by omega)).eq_of_tgt _ _) hom_inv_id := by ext i obtain hi | rfl | hi := lt_trichotomy i n · apply (K.isZero_of_isStrictlyGE n i (by omega)).eq_of_src · simp · apply (K.isZero_of_isStrictlyLE n i (by omega)).eq_of_tgt inv_hom_id := by aesop }⟩⟩ instance (A : C) (n : ℤ) : IsStrictlyGE ((single C (ComplexShape.up ℤ) n).obj A) n := by rw [isStrictlyGE_iff] intro i hi exact isZero_single_obj_X _ _ _ _ (by omega) instance (A : C) (n : ℤ) : IsStrictlyLE ((single C (ComplexShape.up ℤ) n).obj A) n := by rw [isStrictlyLE_iff] intro i hi exact isZero_single_obj_X _ _ _ _ (by omega) variable [∀ i, K.HasHomology i] [∀ i, L.HasHomology i] (n : ℤ) instance [K.IsStrictlyGE n] : IsIso (K.πTruncGE n) := by dsimp [πTruncGE]; infer_instance instance [K.IsStrictlyLE n] : IsIso (K.ιTruncLE n) := by dsimp [ιTruncLE]; infer_instance lemma isIso_πTruncGE_iff : IsIso (K.πTruncGE n) ↔ K.IsStrictlyGE n := by apply HomologicalComplex.isIso_πTruncGE_iff lemma isIso_ιTruncLE_iff : IsIso (K.ιTruncLE n) ↔ K.IsStrictlyLE n := by apply HomologicalComplex.isIso_ιTruncLE_iff lemma quasiIso_πTruncGE_iff : QuasiIso (K.πTruncGE n) ↔ K.IsGE n := quasiIso_πTruncGE_iff_isSupported K (embeddingUpIntGE n) lemma quasiIso_ιTruncLE_iff : QuasiIso (K.ιTruncLE n) ↔ K.IsLE n := quasiIso_ιTruncLE_iff_isSupported K (embeddingUpIntLE n) instance [K.IsGE n] : QuasiIso (K.πTruncGE n) := by rw [quasiIso_πTruncGE_iff] infer_instance instance [K.IsLE n] : QuasiIso (K.ιTruncLE n) := by rw [quasiIso_ιTruncLE_iff] infer_instance variable {K L} lemma quasiIso_truncGEMap_iff : QuasiIso (truncGEMap φ n) ↔ ∀ (i : ℤ) (_ : n ≤ i), QuasiIsoAt φ i := by rw [HomologicalComplex.quasiIso_truncGEMap_iff] constructor · intro h i hi obtain ⟨k, rfl⟩ := Int.le.dest hi exact h k _ rfl · rintro h i i' rfl exact h _ (by dsimp; omega) lemma quasiIso_truncLEMap_iff : QuasiIso (truncLEMap φ n) ↔ ∀ (i : ℤ) (_ : i ≤ n), QuasiIsoAt φ i := by rw [HomologicalComplex.quasiIso_truncLEMap_iff] constructor · intro h i hi obtain ⟨k, rfl⟩ := Int.le.dest hi exact h k _ (by dsimp; omega) · rintro h i i' rfl exact h _ (by dsimp; omega) end end HasZeroMorphisms section Preadditive variable [Preadditive C] instance [HasZeroObject C] (A : C) (n : ℤ) : ((singleFunctor C n).obj A).IsStrictlyGE n := inferInstanceAs (IsStrictlyGE ((single C (ComplexShape.up ℤ) n).obj A) n) instance [HasZeroObject C] (A : C) (n : ℤ) : ((singleFunctor C n).obj A).IsStrictlyLE n := inferInstanceAs (IsStrictlyLE ((single C (ComplexShape.up ℤ) n).obj A) n) variable (K : CochainComplex C ℤ) lemma isStrictlyLE_shift (n : ℤ) [K.IsStrictlyLE n] (a n' : ℤ) (h : a + n' = n) : (K⟦a⟧).IsStrictlyLE n' := by rw [isStrictlyLE_iff] intro i hi exact IsZero.of_iso (K.isZero_of_isStrictlyLE n _ (by omega)) (K.shiftFunctorObjXIso a i _ rfl) lemma isStrictlyGE_shift (n : ℤ) [K.IsStrictlyGE n] (a n' : ℤ) (h : a + n' = n) : (K⟦a⟧).IsStrictlyGE n' := by rw [isStrictlyGE_iff] intro i hi exact IsZero.of_iso (K.isZero_of_isStrictlyGE n _ (by omega)) (K.shiftFunctorObjXIso a i _ rfl) section variable [CategoryWithHomology C] lemma isLE_shift (n : ℤ) [K.IsLE n] (a n' : ℤ) (h : a + n' = n) : (K⟦a⟧).IsLE n' := by rw [isLE_iff] intro i hi rw [exactAt_iff_isZero_homology] exact IsZero.of_iso (K.isZero_of_isLE n (a + i) (by omega)) (((homologyFunctor C _ (0 : ℤ)).shiftIso a i _ rfl).app K) lemma isGE_shift (n : ℤ) [K.IsGE n] (a n' : ℤ) (h : a + n' = n) : (K⟦a⟧).IsGE n' := by rw [isGE_iff] intro i hi rw [exactAt_iff_isZero_homology] exact IsZero.of_iso (K.isZero_of_isGE n (a + i) (by omega)) (((homologyFunctor C _ (0 : ℤ)).shiftIso a i _ rfl).app K) end end Preadditive end CochainComplex
BanachSteinhaus.lean
/- Copyright (c) 2021 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.NormedSpace.OperatorNorm.NormedSpace import Mathlib.Analysis.LocallyConvex.Barrelled import Mathlib.Topology.Baire.CompleteMetrizable /-! # The Banach-Steinhaus theorem: Uniform Boundedness Principle Herein we prove the Banach-Steinhaus theorem for normed spaces: any collection of bounded linear maps from a Banach space into a normed space which is pointwise bounded is uniformly bounded. Note that we prove the more general version about barrelled spaces in `Analysis.LocallyConvex.Barrelled`, and the usual version below is indeed deduced from the more general setup. -/ open Set variable {E F 𝕜 𝕜₂ : Type*} [SeminormedAddCommGroup E] [SeminormedAddCommGroup F] [NontriviallyNormedField 𝕜] [NontriviallyNormedField 𝕜₂] [NormedSpace 𝕜 E] [NormedSpace 𝕜₂ F] {σ₁₂ : 𝕜 →+* 𝕜₂} [RingHomIsometric σ₁₂] /-- This is the standard Banach-Steinhaus theorem, or Uniform Boundedness Principle. If a family of continuous linear maps from a Banach space into a normed space is pointwise bounded, then the norms of these linear maps are uniformly bounded. See also `WithSeminorms.banach_steinhaus` for the general statement in barrelled spaces. -/ theorem banach_steinhaus {ι : Type*} [CompleteSpace E] {g : ι → E →SL[σ₁₂] F} (h : ∀ x, ∃ C, ∀ i, ‖g i x‖ ≤ C) : ∃ C', ∀ i, ‖g i‖ ≤ C' := by rw [show (∃ C, ∀ i, ‖g i‖ ≤ C) ↔ _ from (NormedSpace.equicontinuous_TFAE g).out 5 2] refine (norm_withSeminorms 𝕜₂ F).banach_steinhaus (fun _ x ↦ ?_) simpa [bddAbove_def, forall_mem_range] using h x open ENNReal /-- This version of Banach-Steinhaus is stated in terms of suprema of `↑‖·‖₊ : ℝ≥0∞` for convenience. -/ theorem banach_steinhaus_iSup_nnnorm {ι : Type*} [CompleteSpace E] {g : ι → E →SL[σ₁₂] F} (h : ∀ x, (⨆ i, ↑‖g i x‖₊) < ∞) : (⨆ i, ↑‖g i‖₊) < ∞ := by rw [show ((⨆ i, ↑‖g i‖₊) < ∞) ↔ _ from (NormedSpace.equicontinuous_TFAE g).out 8 2] refine (norm_withSeminorms 𝕜₂ F).banach_steinhaus (fun _ x ↦ ?_) simpa [← NNReal.bddAbove_coe, ← Set.range_comp] using ENNReal.iSup_coe_lt_top.1 (h x) open Topology open Filter /-- Given a *sequence* of continuous linear maps which converges pointwise and for which the domain is complete, the Banach-Steinhaus theorem is used to guarantee that the limit map is a *continuous* linear map as well. -/ abbrev continuousLinearMapOfTendsto {α : Type*} [CompleteSpace E] [T2Space F] {l : Filter α} [l.IsCountablyGenerated] [l.NeBot] (g : α → E →SL[σ₁₂] F) {f : E → F} (h : Tendsto (fun n x ↦ g n x) l (𝓝 f)) : E →SL[σ₁₂] F := (norm_withSeminorms 𝕜₂ F).continuousLinearMapOfTendsto g h
Equiv.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.Algebra.BigOperators.Finsupp.Fin import Mathlib.Algebra.MvPolynomial.Degrees import Mathlib.Algebra.MvPolynomial.Rename import Mathlib.Algebra.Polynomial.AlgebraMap import Mathlib.Algebra.Polynomial.Degree.Lemmas import Mathlib.Data.Finsupp.Option import Mathlib.Logic.Equiv.Fin.Basic /-! # Equivalences between polynomial rings This file establishes a number of equivalences between polynomial rings, based on equivalences between the underlying types. ## 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` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : MvPolynomial σ R` ## Tags equivalence, isomorphism, morphism, ring hom, hom -/ noncomputable section open Polynomial Set Function Finsupp AddMonoidAlgebra universe u v w x variable {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} namespace MvPolynomial variable {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {s : σ →₀ ℕ} section Equiv variable (R) [CommSemiring R] /-- The ring isomorphism between multivariable polynomials in a single variable and polynomials over the ground ring. -/ @[simps] def pUnitAlgEquiv : MvPolynomial PUnit R ≃ₐ[R] R[X] where toFun := eval₂ Polynomial.C fun _ => Polynomial.X invFun := Polynomial.eval₂ MvPolynomial.C (X PUnit.unit) left_inv := by let f : R[X] →+* MvPolynomial PUnit R := Polynomial.eval₂RingHom MvPolynomial.C (X PUnit.unit) let g : MvPolynomial PUnit R →+* R[X] := eval₂Hom Polynomial.C fun _ => Polynomial.X change ∀ p, f.comp g p = p apply is_id · ext a dsimp [f, g] rw [eval₂_C, Polynomial.eval₂_C] · rintro ⟨⟩ dsimp [f, g] rw [eval₂_X, Polynomial.eval₂_X] right_inv p := Polynomial.induction_on p (fun a => by rw [Polynomial.eval₂_C, MvPolynomial.eval₂_C]) (fun p q hp hq => by rw [Polynomial.eval₂_add, MvPolynomial.eval₂_add, hp, hq]) fun p n _ => by rw [Polynomial.eval₂_mul, Polynomial.eval₂_pow, Polynomial.eval₂_X, Polynomial.eval₂_C, eval₂_mul, eval₂_C, eval₂_pow, eval₂_X] map_mul' _ _ := eval₂_mul _ _ map_add' _ _ := eval₂_add _ _ commutes' _ := eval₂_C _ _ _ theorem pUnitAlgEquiv_monomial {d : PUnit →₀ ℕ} {r : R} : MvPolynomial.pUnitAlgEquiv R (MvPolynomial.monomial d r) = Polynomial.monomial (d ()) r := by simp [Polynomial.C_mul_X_pow_eq_monomial] theorem pUnitAlgEquiv_symm_monomial {d : PUnit →₀ ℕ} {r : R} : (MvPolynomial.pUnitAlgEquiv R).symm (Polynomial.monomial (d ()) r) = MvPolynomial.monomial d r := by simp [MvPolynomial.monomial_eq] section Map variable {R} (σ) /-- If `e : A ≃+* B` is an isomorphism of rings, then so is `map e`. -/ @[simps apply] def mapEquiv [CommSemiring S₁] [CommSemiring S₂] (e : S₁ ≃+* S₂) : MvPolynomial σ S₁ ≃+* MvPolynomial σ S₂ := { map (e : S₁ →+* S₂) with toFun := map (e : S₁ →+* S₂) invFun := map (e.symm : S₂ →+* S₁) left_inv := map_leftInverse e.left_inv right_inv := map_rightInverse e.right_inv } @[simp] theorem mapEquiv_refl : mapEquiv σ (RingEquiv.refl R) = RingEquiv.refl _ := RingEquiv.ext map_id @[simp] theorem mapEquiv_symm [CommSemiring S₁] [CommSemiring S₂] (e : S₁ ≃+* S₂) : (mapEquiv σ e).symm = mapEquiv σ e.symm := rfl @[simp] theorem mapEquiv_trans [CommSemiring S₁] [CommSemiring S₂] [CommSemiring S₃] (e : S₁ ≃+* S₂) (f : S₂ ≃+* S₃) : (mapEquiv σ e).trans (mapEquiv σ f) = mapEquiv σ (e.trans f) := RingEquiv.ext fun p => by simp only [RingEquiv.coe_trans, comp_apply, mapEquiv_apply, RingEquiv.coe_ringHom_trans, map_map] variable {A₁ A₂ A₃ : Type*} [CommSemiring A₁] [CommSemiring A₂] [CommSemiring A₃] variable [Algebra R A₁] [Algebra R A₂] [Algebra R A₃] /-- If `e : A ≃ₐ[R] B` is an isomorphism of `R`-algebras, then so is `map e`. -/ @[simps apply] def mapAlgEquiv (e : A₁ ≃ₐ[R] A₂) : MvPolynomial σ A₁ ≃ₐ[R] MvPolynomial σ A₂ := { mapAlgHom (e : A₁ →ₐ[R] A₂), mapEquiv σ (e : A₁ ≃+* A₂) with toFun := map (e : A₁ →+* A₂) } @[simp] theorem mapAlgEquiv_refl : mapAlgEquiv σ (AlgEquiv.refl : A₁ ≃ₐ[R] A₁) = AlgEquiv.refl := AlgEquiv.ext map_id @[simp] theorem mapAlgEquiv_symm (e : A₁ ≃ₐ[R] A₂) : (mapAlgEquiv σ e).symm = mapAlgEquiv σ e.symm := rfl @[simp] theorem mapAlgEquiv_trans (e : A₁ ≃ₐ[R] A₂) (f : A₂ ≃ₐ[R] A₃) : (mapAlgEquiv σ e).trans (mapAlgEquiv σ f) = mapAlgEquiv σ (e.trans f) := by ext simp only [AlgEquiv.trans_apply, mapAlgEquiv_apply, map_map] rfl end Map section Eval variable {R S : Type*} [CommSemiring R] [CommSemiring S] theorem eval₂_pUnitAlgEquiv_symm {f : Polynomial R} {φ : R →+* S} {a : Unit → S} : ((MvPolynomial.pUnitAlgEquiv R).symm f : MvPolynomial Unit R).eval₂ φ a = f.eval₂ φ (a ()) := by simp only [MvPolynomial.pUnitAlgEquiv_symm_apply] induction f using Polynomial.induction_on' with | add f g hf hg => simp [hf, hg] | monomial n r => simp theorem eval₂_const_pUnitAlgEquiv_symm {f : Polynomial R} {φ : R →+* S} {a : S} : ((MvPolynomial.pUnitAlgEquiv R).symm f : MvPolynomial Unit R).eval₂ φ (fun _ ↦ a) = f.eval₂ φ a := by rw [eval₂_pUnitAlgEquiv_symm] theorem eval₂_pUnitAlgEquiv {f : MvPolynomial PUnit R} {φ : R →+* S} {a : PUnit → S} : ((MvPolynomial.pUnitAlgEquiv R) f : Polynomial R).eval₂ φ (a default) = f.eval₂ φ a := by simp only [MvPolynomial.pUnitAlgEquiv_apply] induction f using MvPolynomial.induction_on' with | monomial d r => simp | add f g hf hg => simp [hf, hg] theorem eval₂_const_pUnitAlgEquiv {f : MvPolynomial PUnit R} {φ : R →+* S} {a : S} : ((MvPolynomial.pUnitAlgEquiv R) f : Polynomial R).eval₂ φ a = f.eval₂ φ (fun _ ↦ a) := by rw [← eval₂_pUnitAlgEquiv] end Eval section variable (S₁ S₂ S₃) /-- The function from multivariable polynomials in a sum of two types, to multivariable polynomials in one of the types, with coefficients in multivariable polynomials in the other type. See `sumRingEquiv` for the ring isomorphism. -/ def sumToIter : MvPolynomial (S₁ ⊕ S₂) R →+* MvPolynomial S₁ (MvPolynomial S₂ R) := eval₂Hom (C.comp C) fun bc => Sum.recOn bc X (C ∘ X) @[simp] theorem sumToIter_C (a : R) : sumToIter R S₁ S₂ (C a) = C (C a) := eval₂_C _ _ a @[simp] theorem sumToIter_Xl (b : S₁) : sumToIter R S₁ S₂ (X (Sum.inl b)) = X b := eval₂_X _ _ (Sum.inl b) @[simp] theorem sumToIter_Xr (c : S₂) : sumToIter R S₁ S₂ (X (Sum.inr c)) = C (X c) := eval₂_X _ _ (Sum.inr c) /-- The function from multivariable polynomials in one type, with coefficients in multivariable polynomials in another type, to multivariable polynomials in the sum of the two types. See `sumRingEquiv` for the ring isomorphism. -/ def iterToSum : MvPolynomial S₁ (MvPolynomial S₂ R) →+* MvPolynomial (S₁ ⊕ S₂) R := eval₂Hom (eval₂Hom C (X ∘ Sum.inr)) (X ∘ Sum.inl) @[simp] theorem iterToSum_C_C (a : R) : iterToSum R S₁ S₂ (C (C a)) = C a := Eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _) @[simp] theorem iterToSum_X (b : S₁) : iterToSum R S₁ S₂ (X b) = X (Sum.inl b) := eval₂_X _ _ _ @[simp] theorem iterToSum_C_X (c : S₂) : iterToSum R S₁ S₂ (C (X c)) = X (Sum.inr c) := Eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _) section isEmptyRingEquiv variable [IsEmpty σ] variable (σ) in /-- The algebra isomorphism between multivariable polynomials in no variables and the ground ring. -/ @[simps! apply] def isEmptyAlgEquiv : MvPolynomial σ R ≃ₐ[R] R := .ofAlgHom (aeval isEmptyElim) (Algebra.ofId _ _) (by ext) (by ext i m; exact isEmptyElim i) variable {R S₁} in @[simp] lemma aeval_injective_iff_of_isEmpty [CommSemiring S₁] [Algebra R S₁] {f : σ → S₁} : Function.Injective (aeval f : MvPolynomial σ R →ₐ[R] S₁) ↔ Function.Injective (algebraMap R S₁) := by have : aeval f = (Algebra.ofId R S₁).comp (@isEmptyAlgEquiv R σ _ _).toAlgHom := by ext i exact IsEmpty.elim' ‹IsEmpty σ› i rw [this, ← Injective.of_comp_iff' _ (@isEmptyAlgEquiv R σ _ _).bijective] rfl variable (σ) in /-- The ring isomorphism between multivariable polynomials in no variables and the ground ring. -/ @[simps! apply] def isEmptyRingEquiv : MvPolynomial σ R ≃+* R := (isEmptyAlgEquiv R σ).toRingEquiv lemma isEmptyRingEquiv_symm_toRingHom : (isEmptyRingEquiv R σ).symm.toRingHom = C := rfl @[simp] lemma isEmptyRingEquiv_symm_apply (r : R) : (isEmptyRingEquiv R σ).symm r = C r := rfl lemma isEmptyRingEquiv_eq_coeff_zero {σ R : Type*} [CommSemiring R] [IsEmpty σ] {x} : isEmptyRingEquiv R σ x = x.coeff 0 := by obtain ⟨x, rfl⟩ := (isEmptyRingEquiv R σ).symm.surjective x; simp end isEmptyRingEquiv /-- A helper function for `sumRingEquiv`. -/ @[simps] def mvPolynomialEquivMvPolynomial [CommSemiring S₃] (f : MvPolynomial S₁ R →+* MvPolynomial S₂ S₃) (g : MvPolynomial S₂ S₃ →+* MvPolynomial S₁ R) (hfgC : (f.comp g).comp C = C) (hfgX : ∀ n, f (g (X n)) = X n) (hgfC : (g.comp f).comp C = C) (hgfX : ∀ n, g (f (X n)) = X n) : MvPolynomial S₁ R ≃+* MvPolynomial S₂ S₃ where toFun := f invFun := g left_inv := is_id (RingHom.comp _ _) hgfC hgfX right_inv := is_id (RingHom.comp _ _) hfgC hfgX map_mul' := f.map_mul map_add' := f.map_add /-- The ring isomorphism between multivariable polynomials in a sum of two types, and multivariable polynomials in one of the types, with coefficients in multivariable polynomials in the other type. -/ def sumRingEquiv : MvPolynomial (S₁ ⊕ S₂) R ≃+* MvPolynomial S₁ (MvPolynomial S₂ R) := by apply mvPolynomialEquivMvPolynomial R (S₁ ⊕ S₂) _ _ (sumToIter R S₁ S₂) (iterToSum R S₁ S₂) · refine RingHom.ext (hom_eq_hom _ _ ?hC ?hX) case hC => ext1; simp only [RingHom.comp_apply, iterToSum_C_C, sumToIter_C] case hX => intro; simp only [RingHom.comp_apply, iterToSum_C_X, sumToIter_Xr] · simp [iterToSum_X, sumToIter_Xl] · ext1; simp only [RingHom.comp_apply, sumToIter_C, iterToSum_C_C] · rintro ⟨⟩ <;> simp only [sumToIter_Xl, iterToSum_X, sumToIter_Xr, iterToSum_C_X] /-- The algebra isomorphism between multivariable polynomials in a sum of two types, and multivariable polynomials in one of the types, with coefficients in multivariable polynomials in the other type. -/ @[simps!] def sumAlgEquiv : MvPolynomial (S₁ ⊕ S₂) R ≃ₐ[R] MvPolynomial S₁ (MvPolynomial S₂ R) := { sumRingEquiv R S₁ S₂ with commutes' := by intro r have A : algebraMap R (MvPolynomial S₁ (MvPolynomial S₂ R)) r = (C (C r) :) := rfl have B : algebraMap R (MvPolynomial (S₁ ⊕ S₂) R) r = C r := rfl simp only [sumRingEquiv, mvPolynomialEquivMvPolynomial, Equiv.toFun_as_coe, Equiv.coe_fn_mk, B, sumToIter_C, A] } lemma sumAlgEquiv_comp_rename_inr : (sumAlgEquiv R S₁ S₂).toAlgHom.comp (rename Sum.inr) = IsScalarTower.toAlgHom R (MvPolynomial S₂ R) (MvPolynomial S₁ (MvPolynomial S₂ R)) := by ext i simp lemma sumAlgEquiv_comp_rename_inl : (sumAlgEquiv R S₁ S₂).toAlgHom.comp (rename Sum.inl) = MvPolynomial.mapAlgHom (Algebra.ofId _ _) := by ext i simp section commAlgEquiv variable {R S₁ S₂ : Type*} [CommSemiring R] variable (R S₁ S₂) in /-- The algebra isomorphism between multivariable polynomials in variables `S₁` of multivariable polynomials in variables `S₂` and multivariable polynomials in variables `S₂` of multivariable polynomials in variables `S₁`. -/ noncomputable def commAlgEquiv : MvPolynomial S₁ (MvPolynomial S₂ R) ≃ₐ[R] MvPolynomial S₂ (MvPolynomial S₁ R) := (sumAlgEquiv R S₁ S₂).symm.trans <| (renameEquiv _ (.sumComm S₁ S₂)).trans (sumAlgEquiv R S₂ S₁) @[simp] lemma commAlgEquiv_C (p) : commAlgEquiv R S₁ S₂ (.C p) = .map C p := by suffices (commAlgEquiv R S₁ S₂).toAlgHom.comp (IsScalarTower.toAlgHom R (MvPolynomial S₂ R) _) = mapAlgHom (Algebra.ofId _ _) by exact DFunLike.congr_fun this p ext x : 1 simp [commAlgEquiv] lemma commAlgEquiv_C_X (i) : commAlgEquiv R S₁ S₂ (.C (.X i)) = .X i := by simp @[simp] lemma commAlgEquiv_X (i) : commAlgEquiv R S₁ S₂ (.X i) = .C (.X i) := by simp [commAlgEquiv] end commAlgEquiv section -- this speeds up typeclass search in the lemma below attribute [local instance] IsScalarTower.right /-- The algebra isomorphism between multivariable polynomials in `Option S₁` and polynomials with coefficients in `MvPolynomial S₁ R`. -/ @[simps! -isSimp] def optionEquivLeft : MvPolynomial (Option S₁) R ≃ₐ[R] Polynomial (MvPolynomial S₁ R) := AlgEquiv.ofAlgHom (MvPolynomial.aeval fun o => o.elim Polynomial.X fun s => Polynomial.C (X s)) (Polynomial.aevalTower (MvPolynomial.rename some) (X none)) (by ext : 2 <;> simp) (by ext i : 2; cases i <;> simp) lemma optionEquivLeft_X_some (x : S₁) : optionEquivLeft R S₁ (X (some x)) = Polynomial.C (X x) := by simp [optionEquivLeft_apply, aeval_X] lemma optionEquivLeft_X_none : optionEquivLeft R S₁ (X none) = Polynomial.X := by simp [optionEquivLeft_apply, aeval_X] lemma optionEquivLeft_C (r : R) : optionEquivLeft R S₁ (C r) = Polynomial.C (C r) := by simp only [optionEquivLeft_apply, aeval_C, Polynomial.algebraMap_apply, algebraMap_eq] theorem optionEquivLeft_monomial (m : Option S₁ →₀ ℕ) (r : R) : optionEquivLeft R S₁ (monomial m r) = .monomial (m none) (monomial m.some r) := by rw [optionEquivLeft_apply, aeval_monomial, prod_option_index] · rw [MvPolynomial.monomial_eq, ← Polynomial.C_mul_X_pow_eq_monomial] simp only [Polynomial.algebraMap_apply, algebraMap_eq, Option.elim_none, Option.elim_some, map_mul, mul_assoc] apply congr_arg₂ _ rfl simp only [mul_comm, map_finsuppProd, map_pow] · intros; simp · intros; rw [pow_add] /-- The coefficient of `n.some` in the `n none`-th coefficient of `optionEquivLeft R S₁ f` equals the coefficient of `n` in `f` -/ theorem optionEquivLeft_coeff_coeff (n : Option S₁ →₀ ℕ) (f : MvPolynomial (Option S₁) R) : coeff n.some (Polynomial.coeff (optionEquivLeft R S₁ f) (n none)) = coeff n f := by induction' f using MvPolynomial.induction_on' with j r p q hp hq generalizing n swap · simp only [map_add, Polynomial.coeff_add, coeff_add, hp, hq] · rw [optionEquivLeft_monomial] classical simp only [Polynomial.coeff_monomial, MvPolynomial.coeff_monomial, apply_ite] simp only [coeff_zero] by_cases hj : j = n · simp [hj] · rw [if_neg hj] simp only [ite_eq_right_iff] intro hj_none hj_some apply False.elim (hj _) simp only [Finsupp.ext_iff, Option.forall, hj_none, true_and] simpa only [Finsupp.ext_iff] using hj_some theorem optionEquivLeft_elim_eval (s : S₁ → R) (y : R) (f : MvPolynomial (Option S₁) R) : eval (fun x ↦ Option.elim x y s) f = Polynomial.eval y (Polynomial.map (eval s) (optionEquivLeft R S₁ f)) := by -- turn this into a def `Polynomial.mapAlgHom` let φ : (MvPolynomial S₁ R)[X] →ₐ[R] R[X] := { Polynomial.mapRingHom (eval s) with commutes' := fun r => by convert Polynomial.map_C (eval s) exact (eval_C _).symm } change aeval (fun x ↦ Option.elim x y s) f = (Polynomial.aeval y).comp (φ.comp (optionEquivLeft _ _).toAlgHom) f congr 2 apply MvPolynomial.algHom_ext rw [Option.forall] simp only [aeval_X, Option.elim_none, AlgEquiv.toAlgHom_eq_coe, AlgHom.coe_comp, Polynomial.coe_aeval_eq_eval, AlgHom.coe_mk, coe_mapRingHom, AlgHom.coe_coe, comp_apply, optionEquivLeft_apply, Polynomial.map_X, Polynomial.eval_X, Option.elim_some, Polynomial.map_C, eval_X, Polynomial.eval_C, implies_true, and_self, φ] @[simp] lemma natDegree_optionEquivLeft (p : MvPolynomial (Option S₁) R) : (optionEquivLeft R S₁ p).natDegree = p.degreeOf .none := by apply le_antisymm · rw [Polynomial.natDegree_le_iff_coeff_eq_zero] intro N hN ext σ trans p.coeff (σ.embDomain .some + .single .none N) · simpa using optionEquivLeft_coeff_coeff R S₁ (σ.embDomain .some + .single .none N) p simp only [coeff_zero, ← notMem_support_iff] intro H simpa using (degreeOf_lt_iff ((zero_le _).trans_lt hN)).mp hN _ H · rw [degreeOf_le_iff] intro σ hσ refine Polynomial.le_natDegree_of_ne_zero fun H ↦ ?_ have := optionEquivLeft_coeff_coeff R S₁ σ p rw [H, coeff_zero, eq_comm, ← notMem_support_iff] at this exact this hσ lemma totalDegree_coeff_optionEquivLeft_add_le (p : MvPolynomial (Option S₁) R) (i : ℕ) (hi : i ≤ p.totalDegree) : ((optionEquivLeft R S₁ p).coeff i).totalDegree + i ≤ p.totalDegree := by classical by_cases hpi : (optionEquivLeft R S₁ p).coeff i = 0 · rw [hpi]; simpa rw [totalDegree, add_comm, Finset.add_sup (by simpa only [support_nonempty]), Finset.sup_le_iff] intro σ hσ refine le_trans ?_ (Finset.le_sup (b := σ.embDomain .some + .single .none i) ?_) · simp [Finsupp.sum_add_index, Finsupp.sum_embDomain, add_comm i] · simpa [mem_support_iff, ← optionEquivLeft_coeff_coeff R S₁] using hσ lemma totalDegree_coeff_optionEquivLeft_le (p : MvPolynomial (Option S₁) R) (i : ℕ) : ((optionEquivLeft R S₁ p).coeff i).totalDegree ≤ p.totalDegree := by classical by_cases hpi : (optionEquivLeft R S₁ p).coeff i = 0 · rw [hpi]; simp rw [totalDegree, Finset.sup_le_iff] intro σ hσ refine le_trans ?_ (Finset.le_sup (b := σ.embDomain .some + .single .none i) ?_) · simp [Finsupp.sum_add_index, Finsupp.sum_embDomain] · simpa [mem_support_iff, ← optionEquivLeft_coeff_coeff R S₁] using hσ end /-- The algebra isomorphism between multivariable polynomials in `Option S₁` and multivariable polynomials with coefficients in polynomials. -/ @[simps!] def optionEquivRight : MvPolynomial (Option S₁) R ≃ₐ[R] MvPolynomial S₁ R[X] := AlgEquiv.ofAlgHom (MvPolynomial.aeval fun o => o.elim (C Polynomial.X) X) (MvPolynomial.aevalTower (Polynomial.aeval (X none)) fun i => X (Option.some i)) (by ext : 2 <;> simp only [MvPolynomial.algebraMap_eq, Option.elim, AlgHom.coe_comp, AlgHom.id_comp, IsScalarTower.coe_toAlgHom', comp_apply, aevalTower_C, Polynomial.aeval_X, aeval_X, aevalTower_X, AlgHom.coe_id, id]) (by ext ⟨i⟩ : 2 <;> simp only [Option.elim, AlgHom.coe_comp, comp_apply, aeval_X, aevalTower_C, Polynomial.aeval_X, AlgHom.coe_id, id, aevalTower_X]) lemma optionEquivRight_X_some (x : S₁) : optionEquivRight R S₁ (X (some x)) = X x := by simp [optionEquivRight_apply, aeval_X] lemma optionEquivRight_X_none : optionEquivRight R S₁ (X none) = C Polynomial.X := by simp [optionEquivRight_apply, aeval_X] lemma optionEquivRight_C (r : R) : optionEquivRight R S₁ (C r) = C (Polynomial.C r) := by simp only [optionEquivRight_apply, aeval_C, algebraMap_apply, Polynomial.algebraMap_eq] variable (n : ℕ) /-- The algebra isomorphism between multivariable polynomials in `Fin (n + 1)` and polynomials over multivariable polynomials in `Fin n`. -/ def finSuccEquiv : MvPolynomial (Fin (n + 1)) R ≃ₐ[R] Polynomial (MvPolynomial (Fin n) R) := (renameEquiv R (_root_.finSuccEquiv n)).trans (optionEquivLeft R (Fin n)) theorem finSuccEquiv_eq : (finSuccEquiv R n : MvPolynomial (Fin (n + 1)) R →+* Polynomial (MvPolynomial (Fin n) R)) = eval₂Hom (Polynomial.C.comp (C : R →+* MvPolynomial (Fin n) R)) fun i : Fin (n + 1) => Fin.cases Polynomial.X (fun k => Polynomial.C (X k)) i := by ext i : 2 · simp only [finSuccEquiv, optionEquivLeft_apply, aeval_C, AlgEquiv.coe_trans, RingHom.coe_coe, coe_eval₂Hom, comp_apply, renameEquiv_apply, eval₂_C, RingHom.coe_comp, rename_C] rfl · refine Fin.cases ?_ ?_ i <;> simp [optionEquivLeft_apply, finSuccEquiv] theorem finSuccEquiv_apply (p : MvPolynomial (Fin (n + 1)) R) : finSuccEquiv R n p = eval₂Hom (Polynomial.C.comp (C : R →+* MvPolynomial (Fin n) R)) (fun i : Fin (n + 1) => Fin.cases Polynomial.X (fun k => Polynomial.C (X k)) i) p := by rw [← finSuccEquiv_eq, RingHom.coe_coe] theorem finSuccEquiv_comp_C_eq_C {R : Type u} [CommSemiring R] (n : ℕ) : (↑(MvPolynomial.finSuccEquiv R n).symm : Polynomial (MvPolynomial (Fin n) R) →+* _).comp (Polynomial.C.comp MvPolynomial.C) = (MvPolynomial.C : R →+* MvPolynomial (Fin n.succ) R) := by refine RingHom.ext fun x => ?_ rw [RingHom.comp_apply] refine (MvPolynomial.finSuccEquiv R n).injective (Trans.trans ((MvPolynomial.finSuccEquiv R n).apply_symm_apply _) ?_) simp only [MvPolynomial.finSuccEquiv_apply, MvPolynomial.eval₂Hom_C] variable {n} {R} theorem finSuccEquiv_X_zero : finSuccEquiv R n (X 0) = Polynomial.X := by simp [finSuccEquiv_apply] theorem finSuccEquiv_X_succ {j : Fin n} : finSuccEquiv R n (X j.succ) = Polynomial.C (X j) := by simp [finSuccEquiv_apply] /-- The coefficient of `m` in the `i`-th coefficient of `finSuccEquiv R n f` equals the coefficient of `Finsupp.cons i m` in `f`. -/ theorem finSuccEquiv_coeff_coeff (m : Fin n →₀ ℕ) (f : MvPolynomial (Fin (n + 1)) R) (i : ℕ) : coeff m (Polynomial.coeff (finSuccEquiv R n f) i) = coeff (m.cons i) f := by induction f using MvPolynomial.induction_on' generalizing i m with | add p q hp hq => simp only [map_add, Polynomial.coeff_add, coeff_add, hp, hq] | monomial j r => simp only [finSuccEquiv_apply, coe_eval₂Hom, eval₂_monomial, RingHom.coe_comp, Finsupp.prod_pow, Polynomial.coeff_C_mul, coeff_C_mul, coeff_monomial, Fin.prod_univ_succ, Fin.cases_zero, Fin.cases_succ, ← map_prod, ← RingHom.map_pow, Function.comp_apply] rw [← mul_boole, mul_comm (Polynomial.X ^ j 0), Polynomial.coeff_C_mul_X_pow]; congr 1 obtain rfl | hjmi := eq_or_ne j (m.cons i) · simpa only [cons_zero, cons_succ, if_pos rfl, monomial_eq, C_1, one_mul, Finsupp.prod_pow] using coeff_monomial m m (1 : R) · simp only [hjmi, if_false] obtain hij | rfl := ne_or_eq i (j 0) · simp only [hij, if_false, coeff_zero] simp only [if_true] have hmj : m ≠ j.tail := by rintro rfl rw [cons_tail] at hjmi contradiction simpa only [monomial_eq, C_1, one_mul, Finsupp.prod_pow, tail_apply, if_neg hmj.symm] using coeff_monomial m j.tail (1 : R) theorem eval_eq_eval_mv_eval' (s : Fin n → R) (y : R) (f : MvPolynomial (Fin (n + 1)) R) : eval (Fin.cons y s : Fin (n + 1) → R) f = Polynomial.eval y (Polynomial.map (eval s) (finSuccEquiv R n f)) := by -- turn this into a def `Polynomial.mapAlgHom` let φ : (MvPolynomial (Fin n) R)[X] →ₐ[R] R[X] := { Polynomial.mapRingHom (eval s) with commutes' := fun r => by convert Polynomial.map_C (eval s) exact (eval_C _).symm } change aeval (Fin.cons y s : Fin (n + 1) → R) f = (Polynomial.aeval y).comp (φ.comp (finSuccEquiv R n).toAlgHom) f congr 2 apply MvPolynomial.algHom_ext rw [Fin.forall_iff_succ] simp only [φ, aeval_X, Fin.cons_zero, AlgEquiv.toAlgHom_eq_coe, AlgHom.coe_comp, Polynomial.coe_aeval_eq_eval, Polynomial.map_C, AlgHom.coe_mk, Polynomial.coe_mapRingHom, comp_apply, finSuccEquiv_apply, eval₂Hom_X', Fin.cases_zero, Polynomial.map_X, Polynomial.eval_X, Fin.cons_succ, Fin.cases_succ, eval_X, Polynomial.eval_C, AlgHom.coe_coe, implies_true, and_self] theorem coeff_eval_eq_eval_coeff (s' : S₁ → R) (f : Polynomial (MvPolynomial S₁ R)) (i : ℕ) : Polynomial.coeff (Polynomial.map (eval s') f) i = eval s' (Polynomial.coeff f i) := by simp only [Polynomial.coeff_map] theorem support_coeff_finSuccEquiv {f : MvPolynomial (Fin (n + 1)) R} {i : ℕ} {m : Fin n →₀ ℕ} : m ∈ ((finSuccEquiv R n f).coeff i).support ↔ m.cons i ∈ f.support := by apply Iff.intro · intro h simpa [← finSuccEquiv_coeff_coeff] using h · intro h simpa [mem_support_iff, ← finSuccEquiv_coeff_coeff m f i] using h /-- The `totalDegree` of a multivariable polynomial `p` is at least `i` more than the `totalDegree` of the `i`th coefficient of `finSuccEquiv` applied to `p`, if this is nonzero. -/ lemma totalDegree_coeff_finSuccEquiv_add_le (f : MvPolynomial (Fin (n + 1)) R) (i : ℕ) (hi : (finSuccEquiv R n f).coeff i ≠ 0) : totalDegree ((finSuccEquiv R n f).coeff i) + i ≤ totalDegree f := by have hf'_sup : ((finSuccEquiv R n f).coeff i).support.Nonempty := by rw [Finset.nonempty_iff_ne_empty, ne_eq, support_eq_empty] exact hi -- Let σ be a monomial index of ((finSuccEquiv R n p).coeff i) of maximal total degree have ⟨σ, hσ1, hσ2⟩ := Finset.exists_mem_eq_sup (support _) hf'_sup (fun s => Finsupp.sum s fun _ e => e) -- Then cons i σ is a monomial index of p with total degree equal to the desired bound let σ' : Fin (n + 1) →₀ ℕ := cons i σ convert le_totalDegree (s := σ') _ · rw [totalDegree, hσ2, sum_cons, add_comm] · rw [← support_coeff_finSuccEquiv] exact hσ1 theorem support_finSuccEquiv (f : MvPolynomial (Fin (n + 1)) R) : (finSuccEquiv R n f).support = Finset.image (fun m : Fin (n + 1) →₀ ℕ => m 0) f.support := by ext i rw [Polynomial.mem_support_iff, Finset.mem_image, Finsupp.ne_iff] constructor · rintro ⟨m, hm⟩ refine ⟨cons i m, ?_, cons_zero _ _⟩ rw [← support_coeff_finSuccEquiv] simpa using hm · rintro ⟨m, h, rfl⟩ refine ⟨tail m, ?_⟩ rwa [← coeff, zero_apply, ← mem_support_iff, support_coeff_finSuccEquiv, cons_tail] theorem mem_support_finSuccEquiv {f : MvPolynomial (Fin (n + 1)) R} {x} : x ∈ (finSuccEquiv R n f).support ↔ x ∈ (fun m : Fin (n + 1) →₀ _ ↦ m 0) '' f.support := by simpa using congr(x ∈ $(support_finSuccEquiv f)) theorem image_support_finSuccEquiv {f : MvPolynomial (Fin (n + 1)) R} {i : ℕ} : ((finSuccEquiv R n f).coeff i).support.image (Finsupp.cons i) = {m ∈ f.support | m 0 = i} := by ext m rw [Finset.mem_filter, Finset.mem_image, mem_support_iff] conv_lhs => congr ext rw [mem_support_iff, finSuccEquiv_coeff_coeff, Ne] constructor · grind [cons_zero] · intro h use tail m rw [← h.2, cons_tail] simp [h.1] lemma mem_image_support_coeff_finSuccEquiv {f : MvPolynomial (Fin (n + 1)) R} {i : ℕ} {x} : x ∈ Finsupp.cons i '' ((finSuccEquiv R n f).coeff i).support ↔ x ∈ f.support ∧ x 0 = i := by simpa using congr(x ∈ $image_support_finSuccEquiv) lemma mem_support_coeff_finSuccEquiv {f : MvPolynomial (Fin (n + 1)) R} {i : ℕ} {x} : x ∈ ((finSuccEquiv R n f).coeff i).support ↔ x.cons i ∈ f.support := by rw [← (Finsupp.cons_right_injective i).mem_finset_image (a := x), image_support_finSuccEquiv] simp only [Finset.mem_filter, mem_support_iff, ne_eq, cons_zero, and_true] -- TODO: generalize `finSuccEquiv R n` to an arbitrary ZeroHom theorem support_finSuccEquiv_nonempty {f : MvPolynomial (Fin (n + 1)) R} (h : f ≠ 0) : (finSuccEquiv R n f).support.Nonempty := by rwa [Polynomial.support_nonempty, EmbeddingLike.map_ne_zero_iff] theorem degree_finSuccEquiv {f : MvPolynomial (Fin (n + 1)) R} (h : f ≠ 0) : (finSuccEquiv R n f).degree = degreeOf 0 f := by -- TODO: these should be lemmas have h₀ : ∀ {α β : Type _} (f : α → β), (fun x => x) ∘ f = f := fun f => rfl have h₁ : ∀ {α β : Type _} (f : α → β), f ∘ (fun x => x) = f := fun f => rfl have h' : ((finSuccEquiv R n f).support.sup fun x => x) = degreeOf 0 f := by rw [degreeOf_eq_sup, support_finSuccEquiv, Finset.sup_image, h₀] rw [Polynomial.degree, ← h', Nat.cast_withBot, Finset.coe_sup_of_nonempty (support_finSuccEquiv_nonempty h), Finset.max_eq_sup_coe, h₁] theorem natDegree_finSuccEquiv (f : MvPolynomial (Fin (n + 1)) R) : (finSuccEquiv R n f).natDegree = degreeOf 0 f := by by_cases c : f = 0 · rw [c, map_zero, Polynomial.natDegree_zero, degreeOf_zero] · rw [Polynomial.natDegree, degree_finSuccEquiv c, Nat.cast_withBot, WithBot.unbotD_coe] theorem degreeOf_coeff_finSuccEquiv (p : MvPolynomial (Fin (n + 1)) R) (j : Fin n) (i : ℕ) : degreeOf j (Polynomial.coeff (finSuccEquiv R n p) i) ≤ degreeOf j.succ p := by rw [degreeOf_eq_sup, degreeOf_eq_sup, Finset.sup_le_iff] intro m hm rw [← Finsupp.cons_succ j i m] exact Finset.le_sup (f := fun (g : Fin (Nat.succ n) →₀ ℕ) => g (Fin.succ j)) (support_coeff_finSuccEquiv.1 hm) /-- Consider a multivariate polynomial `φ` whose variables are indexed by `Option σ`, and suppose that `σ ≃ Fin n`. Then one may view `φ` as a polynomial over `MvPolynomial (Fin n) R`, by 1. renaming the variables via `Option σ ≃ Fin (n+1)`, and then singling out the `0`-th variable via `MvPolynomial.finSuccEquiv`; 2. first viewing it as polynomial over `MvPolynomial σ R` via `MvPolynomial.optionEquivLeft`, and then renaming the variables. This lemma shows that both constructions are the same. -/ lemma finSuccEquiv_rename_finSuccEquiv (e : σ ≃ Fin n) (φ : MvPolynomial (Option σ) R) : ((finSuccEquiv R n) ((rename ((Equiv.optionCongr e).trans (_root_.finSuccEquiv n).symm)) φ)) = Polynomial.map (rename e).toRingHom (optionEquivLeft R σ φ) := by suffices (finSuccEquiv R n).toRingEquiv.toRingHom.comp (rename ((Equiv.optionCongr e).trans (_root_.finSuccEquiv n).symm)).toRingHom = (Polynomial.mapRingHom (rename e).toRingHom).comp (optionEquivLeft R σ) by exact DFunLike.congr_fun this φ apply ringHom_ext · simp [Polynomial.algebraMap_apply, algebraMap_eq, finSuccEquiv_apply, optionEquivLeft_apply] · rintro (i|i) <;> simp [finSuccEquiv_apply, optionEquivLeft_apply] end @[simp] theorem rename_polynomial_aeval_X {σ τ : Type*} (f : σ → τ) (i : σ) (p : R[X]) : rename f (Polynomial.aeval (X i) p) = Polynomial.aeval (X (f i) : MvPolynomial τ R) p := by rw [← aeval_algHom_apply, rename_X] end Equiv end MvPolynomial section toMvPolynomial variable {R S σ τ : Type*} [CommSemiring R] [CommSemiring S] [Algebra R S] /-- The embedding of `R[X]` into `R[Xᵢ]` as an `R`-algebra homomorphism. -/ noncomputable def Polynomial.toMvPolynomial (i : σ) : R[X] →ₐ[R] MvPolynomial σ R := aeval (MvPolynomial.X i) @[simp] lemma Polynomial.toMvPolynomial_C (i : σ) (r : R) : (C r).toMvPolynomial i = MvPolynomial.C r := by simp [toMvPolynomial] @[simp] lemma Polynomial.toMvPolynomial_X (i : σ) : X.toMvPolynomial i = MvPolynomial.X (R := R) i := by simp [toMvPolynomial] lemma Polynomial.toMvPolynomial_eq_rename_comp (i : σ) : toMvPolynomial (R := R) i = (MvPolynomial.rename (fun _ : Unit ↦ i)).comp (MvPolynomial.pUnitAlgEquiv R).symm := by ext simp lemma Polynomial.toMvPolynomial_injective (i : σ) : Function.Injective (toMvPolynomial (R := R) i) := by simp only [toMvPolynomial_eq_rename_comp, AlgHom.coe_comp, AlgHom.coe_coe, EquivLike.injective_comp] exact MvPolynomial.rename_injective (fun x ↦ i) fun _ _ _ ↦ rfl @[simp] lemma MvPolynomial.eval_comp_toMvPolynomial (f : σ → R) (i : σ) : (eval f).comp (toMvPolynomial (R := R) i) = Polynomial.evalRingHom (f i) := by ext <;> simp @[simp] lemma MvPolynomial.eval_toMvPolynomial (f : σ → R) (i : σ) (p : R[X]) : eval f (p.toMvPolynomial i) = Polynomial.eval (f i) p := DFunLike.congr_fun (eval_comp_toMvPolynomial ..) p @[simp] lemma MvPolynomial.aeval_comp_toMvPolynomial (f : σ → S) (i : σ) : (aeval (R := R) f).comp (toMvPolynomial i) = Polynomial.aeval (f i) := by ext simp @[simp] lemma MvPolynomial.aeval_toMvPolynomial (f : σ → S) (i : σ) (p : R[X]) : aeval f (p.toMvPolynomial i) = Polynomial.aeval (f i) p := DFunLike.congr_fun (aeval_comp_toMvPolynomial ..) p @[simp] lemma MvPolynomial.rename_comp_toMvPolynomial (f : σ → τ) (a : σ) : (rename (R := R) f).comp (Polynomial.toMvPolynomial a) = Polynomial.toMvPolynomial (f a) := by ext simp @[simp] lemma MvPolynomial.rename_toMvPolynomial (f : σ → τ) (a : σ) (p : R[X]) : (rename (R := R) f) (p.toMvPolynomial a) = p.toMvPolynomial (f a) := DFunLike.congr_fun (rename_comp_toMvPolynomial ..) p end toMvPolynomial
GuardHypNums.lean
import Mathlib.Tactic.GuardHypNums set_option linter.unusedTactic false example (a b c : Nat) (_ : a = b) (_ : c = 3) : true := by guard_hyp_nums 6 trivial example : true := by guard_hyp_nums 1 trivial
Group.lean
/- Copyright (c) 2023 David Kurniadi Angdinata. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Kurniadi Angdinata -/ import Mathlib.AlgebraicGeometry.EllipticCurve.Affine.Basic import Mathlib.AlgebraicGeometry.EllipticCurve.Affine.Formula import Mathlib.AlgebraicGeometry.EllipticCurve.Affine.Point deprecated_module (since := "2025-05-07")
imset2_gproduct.v
From mathcomp Require Import all_boot all_fingroup. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Open Scope group_scope. Check @ker_sdprodm.
Join.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.Analysis.Convex.Hull /-! # Convex join This file defines the convex join of two sets. The convex join of `s` and `t` is the union of the segments with one end in `s` and the other in `t`. This is notably a useful gadget to deal with convex hulls of finite sets. -/ open Set variable {ι : Sort*} {𝕜 E : Type*} section OrderedSemiring variable (𝕜) [Semiring 𝕜] [PartialOrder 𝕜] [AddCommMonoid E] [Module 𝕜 E] {s t s₁ s₂ t₁ t₂ u : Set E} {x y : E} /-- The join of two sets is the union of the segments joining them. This can be interpreted as the topological join, but within the original space. -/ def convexJoin (s t : Set E) : Set E := ⋃ (x ∈ s) (y ∈ t), segment 𝕜 x y variable {𝕜} theorem mem_convexJoin : x ∈ convexJoin 𝕜 s t ↔ ∃ a ∈ s, ∃ b ∈ t, x ∈ segment 𝕜 a b := by simp [convexJoin] theorem convexJoin_comm (s t : Set E) : convexJoin 𝕜 s t = convexJoin 𝕜 t s := (iUnion₂_comm _).trans <| by simp_rw [convexJoin, segment_symm] theorem convexJoin_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : convexJoin 𝕜 s₁ t₁ ⊆ convexJoin 𝕜 s₂ t₂ := biUnion_mono hs fun _ _ => biUnion_subset_biUnion_left ht theorem convexJoin_mono_left (hs : s₁ ⊆ s₂) : convexJoin 𝕜 s₁ t ⊆ convexJoin 𝕜 s₂ t := convexJoin_mono hs Subset.rfl theorem convexJoin_mono_right (ht : t₁ ⊆ t₂) : convexJoin 𝕜 s t₁ ⊆ convexJoin 𝕜 s t₂ := convexJoin_mono Subset.rfl ht @[simp] theorem convexJoin_empty_left (t : Set E) : convexJoin 𝕜 ∅ t = ∅ := by simp [convexJoin] @[simp] theorem convexJoin_empty_right (s : Set E) : convexJoin 𝕜 s ∅ = ∅ := by simp [convexJoin] @[simp] theorem convexJoin_singleton_left (t : Set E) (x : E) : convexJoin 𝕜 {x} t = ⋃ y ∈ t, segment 𝕜 x y := by simp [convexJoin] @[simp] theorem convexJoin_singleton_right (s : Set E) (y : E) : convexJoin 𝕜 s {y} = ⋃ x ∈ s, segment 𝕜 x y := by simp [convexJoin] theorem convexJoin_singletons (x : E) : convexJoin 𝕜 {x} {y} = segment 𝕜 x y := by simp @[simp] theorem convexJoin_union_left (s₁ s₂ t : Set E) : convexJoin 𝕜 (s₁ ∪ s₂) t = convexJoin 𝕜 s₁ t ∪ convexJoin 𝕜 s₂ t := by simp_rw [convexJoin, mem_union, iUnion_or, iUnion_union_distrib] @[simp] theorem convexJoin_union_right (s t₁ t₂ : Set E) : convexJoin 𝕜 s (t₁ ∪ t₂) = convexJoin 𝕜 s t₁ ∪ convexJoin 𝕜 s t₂ := by simp_rw [convexJoin_comm s, convexJoin_union_left] @[simp] theorem convexJoin_iUnion_left (s : ι → Set E) (t : Set E) : convexJoin 𝕜 (⋃ i, s i) t = ⋃ i, convexJoin 𝕜 (s i) t := by simp_rw [convexJoin, mem_iUnion, iUnion_exists] exact iUnion_comm _ @[simp] theorem convexJoin_iUnion_right (s : Set E) (t : ι → Set E) : convexJoin 𝕜 s (⋃ i, t i) = ⋃ i, convexJoin 𝕜 s (t i) := by simp_rw [convexJoin_comm s, convexJoin_iUnion_left] theorem segment_subset_convexJoin (hx : x ∈ s) (hy : y ∈ t) : segment 𝕜 x y ⊆ convexJoin 𝕜 s t := subset_iUnion₂_of_subset x hx <| subset_iUnion₂ (s := fun y _ ↦ segment 𝕜 x y) y hy section variable [IsOrderedRing 𝕜] theorem subset_convexJoin_left (h : t.Nonempty) : s ⊆ convexJoin 𝕜 s t := fun _x hx => let ⟨_y, hy⟩ := h segment_subset_convexJoin hx hy <| left_mem_segment _ _ _ theorem subset_convexJoin_right (h : s.Nonempty) : t ⊆ convexJoin 𝕜 s t := convexJoin_comm (𝕜 := 𝕜) t s ▸ subset_convexJoin_left h end theorem convexJoin_subset (hs : s ⊆ u) (ht : t ⊆ u) (hu : Convex 𝕜 u) : convexJoin 𝕜 s t ⊆ u := iUnion₂_subset fun _x hx => iUnion₂_subset fun _y hy => hu.segment_subset (hs hx) (ht hy) theorem convexJoin_subset_convexHull (s t : Set E) : convexJoin 𝕜 s t ⊆ convexHull 𝕜 (s ∪ t) := convexJoin_subset (subset_union_left.trans <| subset_convexHull _ _) (subset_union_right.trans <| subset_convexHull _ _) <| convex_convexHull _ _ end OrderedSemiring section LinearOrderedField variable [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜] [AddCommGroup E] [Module 𝕜 E] {s t : Set E} {x : E} theorem convexJoin_assoc_aux (s t u : Set E) : convexJoin 𝕜 (convexJoin 𝕜 s t) u ⊆ convexJoin 𝕜 s (convexJoin 𝕜 t u) := by simp_rw [subset_def, mem_convexJoin] rintro _ ⟨z, ⟨x, hx, y, hy, a₁, b₁, ha₁, hb₁, hab₁, rfl⟩, z, hz, a₂, b₂, ha₂, hb₂, hab₂, rfl⟩ obtain rfl | hb₂ := hb₂.eq_or_lt · refine ⟨x, hx, y, ⟨y, hy, z, hz, left_mem_segment 𝕜 _ _⟩, a₁, b₁, ha₁, hb₁, hab₁, ?_⟩ linear_combination (norm := module) -hab₂ • (a₁ • x + b₁ • y) refine ⟨x, hx, (a₂ * b₁ / (a₂ * b₁ + b₂)) • y + (b₂ / (a₂ * b₁ + b₂)) • z, ⟨y, hy, z, hz, _, _, by positivity, by positivity, by field_simp, rfl⟩, a₂ * a₁, a₂ * b₁ + b₂, by positivity, by positivity, ?_, ?_⟩ · linear_combination a₂ * hab₁ + hab₂ · match_scalars <;> field_simp theorem convexJoin_assoc (s t u : Set E) : convexJoin 𝕜 (convexJoin 𝕜 s t) u = convexJoin 𝕜 s (convexJoin 𝕜 t u) := by refine (convexJoin_assoc_aux _ _ _).antisymm ?_ simp_rw [convexJoin_comm s, convexJoin_comm _ u] exact convexJoin_assoc_aux _ _ _ theorem convexJoin_left_comm (s t u : Set E) : convexJoin 𝕜 s (convexJoin 𝕜 t u) = convexJoin 𝕜 t (convexJoin 𝕜 s u) := by simp_rw [← convexJoin_assoc, convexJoin_comm] theorem convexJoin_right_comm (s t u : Set E) : convexJoin 𝕜 (convexJoin 𝕜 s t) u = convexJoin 𝕜 (convexJoin 𝕜 s u) t := by simp_rw [convexJoin_assoc, convexJoin_comm] theorem convexJoin_convexJoin_convexJoin_comm (s t u v : Set E) : convexJoin 𝕜 (convexJoin 𝕜 s t) (convexJoin 𝕜 u v) = convexJoin 𝕜 (convexJoin 𝕜 s u) (convexJoin 𝕜 t v) := by simp_rw [← convexJoin_assoc, convexJoin_right_comm] protected theorem Convex.convexJoin (hs : Convex 𝕜 s) (ht : Convex 𝕜 t) : Convex 𝕜 (convexJoin 𝕜 s t) := by simp only [Convex, StarConvex, convexJoin, mem_iUnion] rintro _ ⟨x₁, hx₁, y₁, hy₁, a₁, b₁, ha₁, hb₁, hab₁, rfl⟩ _ ⟨x₂, hx₂, y₂, hy₂, a₂, b₂, ha₂, hb₂, hab₂, rfl⟩ p q hp hq hpq rcases hs.exists_mem_add_smul_eq hx₁ hx₂ (mul_nonneg hp ha₁) (mul_nonneg hq ha₂) with ⟨x, hxs, hx⟩ rcases ht.exists_mem_add_smul_eq hy₁ hy₂ (mul_nonneg hp hb₁) (mul_nonneg hq hb₂) with ⟨y, hyt, hy⟩ refine ⟨_, hxs, _, hyt, p * a₁ + q * a₂, p * b₁ + q * b₂, ?_, ?_, ?_, ?_⟩ <;> try positivity · linear_combination p * hab₁ + q * hab₂ + hpq · rw [hx, hy] module protected theorem Convex.convexHull_union (hs : Convex 𝕜 s) (ht : Convex 𝕜 t) (hs₀ : s.Nonempty) (ht₀ : t.Nonempty) : convexHull 𝕜 (s ∪ t) = convexJoin 𝕜 s t := (convexHull_min (union_subset (subset_convexJoin_left ht₀) <| subset_convexJoin_right hs₀) <| hs.convexJoin ht).antisymm <| convexJoin_subset_convexHull _ _ theorem convexHull_union (hs : s.Nonempty) (ht : t.Nonempty) : convexHull 𝕜 (s ∪ t) = convexJoin 𝕜 (convexHull 𝕜 s) (convexHull 𝕜 t) := by rw [← convexHull_convexHull_union_left, ← convexHull_convexHull_union_right] exact (convex_convexHull 𝕜 s).convexHull_union (convex_convexHull 𝕜 t) hs.convexHull ht.convexHull theorem convexHull_insert (hs : s.Nonempty) : convexHull 𝕜 (insert x s) = convexJoin 𝕜 {x} (convexHull 𝕜 s) := by rw [insert_eq, convexHull_union (singleton_nonempty _) hs, convexHull_singleton] theorem convexJoin_segments (a b c d : E) : convexJoin 𝕜 (segment 𝕜 a b) (segment 𝕜 c d) = convexHull 𝕜 {a, b, c, d} := by simp_rw [← convexHull_pair, convexHull_insert (insert_nonempty _ _), convexHull_insert (singleton_nonempty _), convexJoin_assoc, convexHull_singleton] theorem convexJoin_segment_singleton (a b c : E) : convexJoin 𝕜 (segment 𝕜 a b) {c} = convexHull 𝕜 {a, b, c} := by rw [← pair_eq_singleton, ← convexJoin_segments, segment_same, pair_eq_singleton] theorem convexJoin_singleton_segment (a b c : E) : convexJoin 𝕜 {a} (segment 𝕜 b c) = convexHull 𝕜 {a, b, c} := by rw [← segment_same 𝕜, convexJoin_segments, insert_idem] end LinearOrderedField
ShiftedHomOpposite.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.Triangulated.Opposite.Basic import Mathlib.CategoryTheory.Shift.ShiftedHom /-! Shifted morphisms in the opposite category If `C` is a category equipped with a shift by `ℤ`, `X` and `Y` are objects of `C`, and `n : ℤ`, we define a bijection `ShiftedHom.opEquiv : ShiftedHom X Y n ≃ ShiftedHom (Opposite.op Y) (Opposite.op X) n`. We also introduce `ShiftedHom.opEquiv'` which produces a bijection `ShiftedHom X Y a' ≃ (Opposite.op (Y⟦a⟧) ⟶ (Opposite.op X)⟦n⟧)` when `n + a = a'`. The compatibilities that are obtained shall be used in order to study the homological functor `preadditiveYoneda.obj B : Cᵒᵖ ⥤ Type _` when `B` is an object in a pretriangulated category `C`. -/ namespace CategoryTheory open Category Pretriangulated.Opposite Pretriangulated variable {C : Type*} [Category C] [HasShift C ℤ] {X Y Z : C} namespace ShiftedHom /-- The bijection `ShiftedHom X Y n ≃ ShiftedHom (Opposite.op Y) (Opposite.op X) n` when `n : ℤ`, and `X` and `Y` are objects of a category equipped with a shift by `ℤ`. -/ noncomputable def opEquiv (n : ℤ) : ShiftedHom X Y n ≃ ShiftedHom (Opposite.op Y) (Opposite.op X) n := Quiver.Hom.opEquiv.trans ((opShiftFunctorEquivalence C n).symm.toAdjunction.homEquiv (Opposite.op Y) (Opposite.op X)) lemma opEquiv_symm_apply {n : ℤ} (f : ShiftedHom (Opposite.op Y) (Opposite.op X) n) : (opEquiv n).symm f = ((opShiftFunctorEquivalence C n).unitIso.inv.app (Opposite.op X)).unop ≫ f.unop⟦n⟧' := rfl lemma opEquiv_symm_apply_comp {X Y : C} {a : ℤ} (f : ShiftedHom (Opposite.op X) (Opposite.op Y) a) {b : ℤ} {Z : C} (z : ShiftedHom X Z b) {c : ℤ} (h : b + a = c) : ((ShiftedHom.opEquiv a).symm f).comp z h = (ShiftedHom.opEquiv a).symm (z.op ≫ f) ≫ (shiftFunctorAdd' C b a c h).inv.app Z := by rw [ShiftedHom.opEquiv_symm_apply, ShiftedHom.opEquiv_symm_apply, ShiftedHom.comp] dsimp simp only [assoc, Functor.map_comp] lemma opEquiv_symm_comp {a b : ℤ} (f : ShiftedHom (Opposite.op Z) (Opposite.op Y) a) (g : ShiftedHom (Opposite.op Y) (Opposite.op X) b) {c : ℤ} (h : b + a = c) : (opEquiv _).symm (f.comp g h) = ((opEquiv _).symm g).comp ((opEquiv _).symm f) (by omega) := by rw [opEquiv_symm_apply, opEquiv_symm_apply, opShiftFunctorEquivalence_unitIso_inv_app_eq _ _ _ _ (show a + b = c by omega), comp, comp] dsimp rw [assoc, assoc, assoc, assoc, ← Functor.map_comp, ← unop_comp_assoc, Iso.inv_hom_id_app] dsimp rw [assoc, id_comp, Functor.map_comp, ← NatTrans.naturality_assoc, ← NatTrans.naturality, opEquiv_symm_apply] dsimp rw [← Functor.map_comp_assoc, ← Functor.map_comp_assoc, ← Functor.map_comp_assoc] rw [← unop_comp_assoc] erw [← NatTrans.naturality] rfl /-- The bijection `ShiftedHom X Y a' ≃ (Opposite.op (Y⟦a⟧) ⟶ (Opposite.op X)⟦n⟧)` when integers `n`, `a` and `a'` satisfy `n + a = a'`, and `X` and `Y` are objects of a category equipped with a shift by `ℤ`. -/ noncomputable def opEquiv' (n a a' : ℤ) (h : n + a = a') : ShiftedHom X Y a' ≃ (Opposite.op (Y⟦a⟧) ⟶ (Opposite.op X)⟦n⟧) := ((shiftFunctorAdd' C a n a' (by omega)).symm.app Y).homToEquiv.symm.trans (opEquiv n) lemma opEquiv'_symm_apply {n a : ℤ} (f : Opposite.op (Y⟦a⟧) ⟶ (Opposite.op X)⟦n⟧) (a' : ℤ) (h : n + a = a') : (opEquiv' n a a' h).symm f = (opEquiv n).symm f ≫ (shiftFunctorAdd' C a n a' (by omega)).inv.app _ := rfl lemma opEquiv'_apply {a' : ℤ} (f : ShiftedHom X Y a') (n a : ℤ) (h : n + a = a') : opEquiv' n a a' h f = opEquiv n (f ≫ (shiftFunctorAdd' C a n a' (by omega)).hom.app Y) := by rfl lemma opEquiv'_symm_op_opShiftFunctorEquivalence_counitIso_inv_app_op_shift {n m : ℤ} (f : ShiftedHom X Y n) (g : ShiftedHom Y Z m) (q : ℤ) (hq : n + m = q) : (opEquiv' n m q hq).symm (g.op ≫ (opShiftFunctorEquivalence C n).counitIso.inv.app _ ≫ f.op⟦n⟧') = f.comp g (by omega) := by rw [opEquiv'_symm_apply, opEquiv_symm_apply] dsimp [comp] apply Quiver.Hom.op_inj simp only [assoc, Functor.map_comp, op_comp, Quiver.Hom.op_unop, opShiftFunctorEquivalence_unitIso_inv_naturality] erw [(opShiftFunctorEquivalence C n).inverse_counitInv_comp_assoc (Opposite.op Y)] lemma opEquiv'_symm_comp (f : Y ⟶ X) {n a : ℤ} (x : Opposite.op (Z⟦a⟧) ⟶ (Opposite.op X⟦n⟧)) (a' : ℤ) (h : n + a = a') : (opEquiv' n a a' h).symm (x ≫ f.op⟦n⟧') = f ≫ (opEquiv' n a a' h).symm x := Quiver.Hom.op_inj (by simp [opEquiv'_symm_apply, opEquiv_symm_apply]) lemma opEquiv'_zero_add_symm (a : ℤ) (f : Opposite.op (Y⟦a⟧) ⟶ (Opposite.op X)⟦(0 : ℤ)⟧) : (opEquiv' 0 a a (zero_add a)).symm f = ((shiftFunctorZero Cᵒᵖ ℤ).hom.app _).unop ≫ f.unop := by simp [opEquiv'_symm_apply, opEquiv_symm_apply, shiftFunctorAdd'_add_zero, opShiftFunctorEquivalence_zero_unitIso_inv_app] lemma opEquiv'_add_symm (n m a a' a'' : ℤ) (ha' : n + a = a') (ha'' : m + a' = a'') (x : (Opposite.op (Y⟦a⟧) ⟶ (Opposite.op X)⟦m + n⟧)) : (opEquiv' (m + n) a a'' (by omega)).symm x = (opEquiv' m a' a'' ha'').symm ((opEquiv' n a a' ha').symm (x ≫ (shiftFunctorAdd Cᵒᵖ m n).hom.app _)).op := by simp only [opEquiv'_symm_apply, opEquiv_symm_apply, opShiftFunctorEquivalence_unitIso_inv_app_eq _ _ _ _ (add_comm n m)] dsimp simp only [assoc, Functor.map_comp, ← shiftFunctorAdd'_eq_shiftFunctorAdd, ← NatTrans.naturality_assoc, shiftFunctorAdd'_assoc_inv_app a n m a' (m + n) a'' (by omega) (by omega) (by omega)] rfl section Preadditive variable [Preadditive C] [∀ (n : ℤ), (shiftFunctor C n).Additive] @[simp] lemma opEquiv_symm_add {n : ℤ} (x y : ShiftedHom (Opposite.op Y) (Opposite.op X) n) : (opEquiv n).symm (x + y) = (opEquiv n).symm x + (opEquiv n).symm y := by dsimp [opEquiv_symm_apply] rw [← Preadditive.comp_add, ← Functor.map_add] rfl @[simp] lemma opEquiv'_symm_add {n a : ℤ} (x y : (Opposite.op (Y⟦a⟧) ⟶ (Opposite.op X)⟦n⟧)) (a' : ℤ) (h : n + a = a') : (opEquiv' n a a' h).symm (x + y) = (opEquiv' n a a' h).symm x + (opEquiv' n a a' h).symm y := by dsimp [opEquiv'] erw [opEquiv_symm_add, Iso.homToEquiv_apply, Iso.homToEquiv_apply, Iso.homToEquiv_apply] rw [Preadditive.add_comp] rfl end Preadditive end ShiftedHom end CategoryTheory
MvPolynomial.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.Algebra.MvPolynomial.Eval import Mathlib.Algebra.MvPolynomial.CommRing import Mathlib.LinearAlgebra.Matrix.Determinant.Basic /-! # Matrices of multivariate polynomials In this file, we prove results about matrices over an mv_polynomial ring. In particular, we provide `Matrix.mvPolynomialX` which associates every entry of a matrix with a unique variable. ## Tags matrix determinant, multivariate polynomial -/ variable {m n R S : Type*} namespace Matrix variable (m n R) /-- The matrix with variable `X (i,j)` at location `(i,j)`. -/ noncomputable def mvPolynomialX [CommSemiring R] : Matrix m n (MvPolynomial (m × n) R) := of fun i j => MvPolynomial.X (i, j) -- TODO: set as an equation lemma for `mv_polynomial_X`, see https://github.com/leanprover-community/mathlib4/pull/3024 @[simp] theorem mvPolynomialX_apply [CommSemiring R] (i j) : mvPolynomialX m n R i j = MvPolynomial.X (i, j) := rfl variable {m n R} /-- Any matrix `A` can be expressed as the evaluation of `Matrix.mvPolynomialX`. This is of particular use when `MvPolynomial (m × n) R` is an integral domain but `S` is not, as if the `MvPolynomial.eval₂` can be pulled to the outside of a goal, it can be solved in under cancellative assumptions. -/ theorem mvPolynomialX_map_eval₂ [CommSemiring R] [CommSemiring S] (f : R →+* S) (A : Matrix m n S) : (mvPolynomialX m n R).map (MvPolynomial.eval₂ f fun p : m × n => A p.1 p.2) = A := ext fun i j => MvPolynomial.eval₂_X _ (fun p : m × n => A p.1 p.2) (i, j) /-- A variant of `Matrix.mvPolynomialX_map_eval₂` with a bundled `RingHom` on the LHS. -/ theorem mvPolynomialX_mapMatrix_eval [Fintype m] [DecidableEq m] [CommSemiring R] (A : Matrix m m R) : (MvPolynomial.eval fun p : m × m => A p.1 p.2).mapMatrix (mvPolynomialX m m R) = A := mvPolynomialX_map_eval₂ _ A variable (R) /-- A variant of `Matrix.mvPolynomialX_map_eval₂` with a bundled `AlgHom` on the LHS. -/ theorem mvPolynomialX_mapMatrix_aeval [Fintype m] [DecidableEq m] [CommSemiring R] [CommSemiring S] [Algebra R S] (A : Matrix m m S) : (MvPolynomial.aeval fun p : m × m => A p.1 p.2).mapMatrix (mvPolynomialX m m R) = A := mvPolynomialX_map_eval₂ _ A variable (m) /-- In a nontrivial ring, `Matrix.mvPolynomialX m m R` has non-zero determinant. -/ theorem det_mvPolynomialX_ne_zero [DecidableEq m] [Fintype m] [CommRing R] [Nontrivial R] : det (mvPolynomialX m m R) ≠ 0 := by intro h_det have := congr_arg Matrix.det (mvPolynomialX_mapMatrix_eval (1 : Matrix m m R)) rw [det_one, ← RingHom.map_det, h_det, RingHom.map_zero] at this exact zero_ne_one this end Matrix
Radon.lean
/- Copyright (c) 2023 Vasily Nesterov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Vasily Nesterov -/ import Mathlib.Analysis.Convex.Combination import Mathlib.Data.Set.Card import Mathlib.LinearAlgebra.AffineSpace.FiniteDimensional import Mathlib.Topology.Separation.Hausdorff /-! # Radon's theorem on convex sets Radon's theorem states that any affine dependent set can be partitioned into two sets whose convex hulls intersect nontrivially. As a corollary, we prove Helly's theorem, which is a basic result in discrete geometry on the intersection of convex sets. Let `X₁, ⋯, Xₙ` be a finite family of convex sets in `ℝᵈ` with `n ≥ d + 1`. The theorem states that if any `d + 1` sets from this family intersect nontrivially, then the whole family intersect nontrivially. For the infinite family of sets it is not true, as example of `Set.Ioo 0 (1 / n)` for `n : ℕ` shows. But the statement is true, if we assume compactness of sets (see `helly_theorem_compact`) ## Tags convex hull, affine independence, Radon, Helly -/ open Fintype Finset Set namespace Convex variable {ι 𝕜 E : Type*} [Field 𝕜] [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜] [AddCommGroup E] [Module 𝕜 E] /-- **Radon's theorem on convex sets**. Any family `f` of affine dependent vectors contains a set `I` with the property that convex hulls of `I` and `Iᶜ` intersect nontrivially. In particular, any `d + 2` points in a `d`-dimensional space can be partitioned this way, since they are affinely dependent (see `finrank_vectorSpan_le_iff_not_affineIndependent`). -/ theorem radon_partition {f : ι → E} (h : ¬ AffineIndependent 𝕜 f) : ∃ I, (convexHull 𝕜 (f '' I) ∩ convexHull 𝕜 (f '' Iᶜ)).Nonempty := by rw [affineIndependent_iff] at h push_neg at h obtain ⟨s, w, h_wsum, h_vsum, nonzero_w_index, h1, h2⟩ := h let I : Finset ι := {i ∈ s | 0 ≤ w i} let J : Finset ι := {i ∈ s | w i < 0} let p : E := centerMass I w f -- point of intersection have hJI : ∑ j ∈ J, w j + ∑ i ∈ I, w i = 0 := by simpa only [h_wsum, not_lt] using sum_filter_add_sum_filter_not s (fun i ↦ w i < 0) w have hI : 0 < ∑ i ∈ I, w i := by rcases exists_pos_of_sum_zero_of_exists_nonzero _ h_wsum ⟨nonzero_w_index, h1, h2⟩ with ⟨pos_w_index, h1', h2'⟩ exact sum_pos' (fun _i hi ↦ (mem_filter.1 hi).2) ⟨pos_w_index, by simp only [I, mem_filter, h1', h2'.le, and_self, h2']⟩ have hp : centerMass J w f = p := centerMass_of_sum_add_sum_eq_zero hJI <| by simpa only [← h_vsum, not_lt] using sum_filter_add_sum_filter_not s (fun i ↦ w i < 0) _ refine ⟨I, p, ?_, ?_⟩ · exact centerMass_mem_convexHull _ (fun _i hi ↦ (mem_filter.mp hi).2) hI (fun _i hi ↦ mem_image_of_mem _ hi) rw [← hp] refine centerMass_mem_convexHull_of_nonpos _ (fun _ hi ↦ (mem_filter.mp hi).2.le) ?_ (fun _i hi ↦ mem_image_of_mem _ fun hi' ↦ ?_) · linarith only [hI, hJI] · exact (mem_filter.mp hi').2.not_gt (mem_filter.mp hi).2 open Module omit [LinearOrder 𝕜] [IsStrictOrderedRing 𝕜] in /-- Corner case for `helly_theorem'`. -/ private lemma helly_theorem_corner {F : ι → Set E} {s : Finset ι} (h_card_small : #s ≤ finrank 𝕜 E + 1) (h_inter : ∀ I ⊆ s, #I ≤ finrank 𝕜 E + 1 → (⋂ i ∈ I, F i).Nonempty) : (⋂ i ∈ s, F i).Nonempty := h_inter s (by simp) h_card_small variable [FiniteDimensional 𝕜 E] /-- **Helly's theorem** for finite families of convex sets. If `F` is a finite family of convex sets in a vector space of finite dimension `d`, and any `k ≤ d + 1` sets of `F` intersect nontrivially, then all sets of `F` intersect nontrivially. -/ theorem helly_theorem' {F : ι → Set E} {s : Finset ι} (h_convex : ∀ i ∈ s, Convex 𝕜 (F i)) (h_inter : ∀ I ⊆ s, #I ≤ finrank 𝕜 E + 1 → (⋂ i ∈ I, F i).Nonempty) : (⋂ i ∈ s, F i).Nonempty := by classical obtain h_card | h_card := lt_or_ge #s (finrank 𝕜 E + 1) · exact helly_theorem_corner (le_of_lt h_card) h_inter generalize hn : #s = n rw [hn] at h_card induction' n, h_card using Nat.le_induction with k h_card hk generalizing ι · exact helly_theorem_corner (le_of_eq hn) h_inter /- Construct a family of vectors indexed by `ι` such that the vector corresponding to `i : ι` is an arbitrary element of the intersection of all `F j` except `F i`. -/ let a (i : s) : E := Set.Nonempty.some (s := ⋂ j ∈ s.erase i, F j) <| by apply hk (s := s.erase i) · exact fun i hi ↦ h_convex i (mem_of_mem_erase hi) · intro J hJ_ss hJ_card exact h_inter J (subset_trans hJ_ss (erase_subset i.val s)) hJ_card · simp only [coe_mem, card_erase_of_mem]; omega /- This family of vectors is not affine independent because the number of them exceeds the dimension of the space. -/ have h_ind : ¬AffineIndependent 𝕜 a := by rw [← finrank_vectorSpan_le_iff_not_affineIndependent 𝕜 a (n := (k - 1))] · exact (Submodule.finrank_le (vectorSpan 𝕜 (range a))).trans (Nat.le_pred_of_lt h_card) · simp only [card_coe]; omega /- Use `radon_partition` to conclude there is a subset `I` of `s` and a point `p : E` which lies in the convex hull of either `a '' I` or `a '' Iᶜ`. We claim that `p ∈ ⋂ i ∈ s, F i`. -/ obtain ⟨I, p, hp_I, hp_Ic⟩ := radon_partition h_ind use p apply mem_biInter intro i hi let i : s := ⟨i, hi⟩ /- It suffices to show that for any subcollection `J` of `s` containing `i`, the convex hull of `a '' (s \ J)` is contained in `F i`. -/ suffices ∀ J : Set s, (i ∈ J) → (convexHull 𝕜) (a '' Jᶜ) ⊆ F i by by_cases h : i ∈ I · exact this I h hp_Ic · apply this Iᶜ h; rwa [compl_compl] /- Given any subcollection `J` of `ι` containing `i`, because `F i` is convex, we need only show that `a j ∈ F i` for each `j ∈ s \ J`. -/ intro J hi rw [convexHull_subset_iff (h_convex i.1 i.2)] rintro v ⟨j, hj, hj_v⟩ rw [← hj_v] /- Since `j ∈ Jᶜ` and `i ∈ J`, we conclude that `i ≠ j`, and hence by the definition of `a`: `a j ∈ ⋂ F '' (Set.univ \ {j}) ⊆ F i`. -/ apply mem_of_subset_of_mem (s₁ := ⋂ k ∈ (s.erase j), F k) · apply biInter_subset_of_mem simp only [erase_val] suffices h : i.val ∈ s.erase j by assumption simp only [mem_erase] constructor · exact fun h' ↦ hj ((show i = j from SetCoe.ext h') ▸ hi) · assumption · apply Nonempty.some_mem /-- **Helly's theorem** for finite families of convex sets in its classical form. If `F` is a family of `n` convex sets in a vector space of finite dimension `d`, with `n ≥ d + 1`, and any `d + 1` sets of `F` intersect nontrivially, then all sets of `F` intersect nontrivially. -/ theorem helly_theorem {F : ι → Set E} {s : Finset ι} (h_card : finrank 𝕜 E + 1 ≤ #s) (h_convex : ∀ i ∈ s, Convex 𝕜 (F i)) (h_inter : ∀ I ⊆ s, #I = finrank 𝕜 E + 1 → (⋂ i ∈ I, F i).Nonempty) : (⋂ i ∈ s, F i).Nonempty := by apply helly_theorem' h_convex intro I hI_ss hI_card obtain ⟨J, hI_ss_J, hJ_ss, hJ_card⟩ := exists_subsuperset_card_eq hI_ss hI_card h_card apply Set.Nonempty.mono <| biInter_mono hI_ss_J (fun _ _ ↦ Set.Subset.rfl) exact h_inter J hJ_ss hJ_card /-- **Helly's theorem** for finite sets of convex sets. If `F` is a finite set of convex sets in a vector space of finite dimension `d`, and any `k ≤ d + 1` sets from `F` intersect nontrivially, then all sets from `F` intersect nontrivially. -/ theorem helly_theorem_set' {F : Finset (Set E)} (h_convex : ∀ X ∈ F, Convex 𝕜 X) (h_inter : ∀ G : Finset (Set E), G ⊆ F → #G ≤ finrank 𝕜 E + 1 → (⋂₀ G : Set E).Nonempty) : (⋂₀ (F : Set (Set E))).Nonempty := by classical -- for DecidableEq, required for the family version rw [show ⋂₀ F = ⋂ X ∈ F, (X : Set E) by ext; simp] apply helly_theorem' h_convex intro G hG_ss hG_card rw [show ⋂ X ∈ G, X = ⋂₀ G by ext; simp] exact h_inter G hG_ss hG_card /-- **Helly's theorem** for finite sets of convex sets in its classical form. If `F` is a finite set of convex sets in a vector space of finite dimension `d`, with `n ≥ d + 1`, and any `d + 1` sets from `F` intersect nontrivially, then all sets from `F` intersect nontrivially. -/ theorem helly_theorem_set {F : Finset (Set E)} (h_card : finrank 𝕜 E + 1 ≤ #F) (h_convex : ∀ X ∈ F, Convex 𝕜 X) (h_inter : ∀ G : Finset (Set E), G ⊆ F → #G = finrank 𝕜 E + 1 → (⋂₀ G : Set E).Nonempty) : (⋂₀ (F : Set (Set E))).Nonempty := by apply helly_theorem_set' h_convex intro I hI_ss hI_card obtain ⟨J, _, hJ_ss, hJ_card⟩ := exists_subsuperset_card_eq hI_ss hI_card h_card have : ⋂₀ (J : Set (Set E)) ⊆ ⋂₀ I := sInter_mono (by simpa [hI_ss]) apply Set.Nonempty.mono this exact h_inter J hJ_ss (by omega) /-- **Helly's theorem** for families of compact convex sets. If `F` is a family of compact convex sets in a vector space of finite dimension `d`, and any `k ≤ d + 1` sets of `F` intersect nontrivially, then all sets of `F` intersect nontrivially. -/ theorem helly_theorem_compact' [TopologicalSpace E] [T2Space E] {F : ι → Set E} (h_convex : ∀ i, Convex 𝕜 (F i)) (h_compact : ∀ i, IsCompact (F i)) (h_inter : ∀ I : Finset ι, #I ≤ finrank 𝕜 E + 1 → (⋂ i ∈ I, F i).Nonempty) : (⋂ i, F i).Nonempty := by classical /- If `ι` is empty the statement is trivial. -/ rcases isEmpty_or_nonempty ι with _ | h_nonempty · simp only [iInter_of_empty, Set.univ_nonempty] /- By the finite version of theorem, every finite subfamily has an intersection. -/ have h_fin (I : Finset ι) : (⋂ i ∈ I, F i).Nonempty := by apply helly_theorem' (s := I) (𝕜 := 𝕜) (by simp [h_convex]) exact fun J _ hJ_card ↦ h_inter J hJ_card /- The following is a clumsy proof that family of compact sets with the finite intersection property has a nonempty intersection. -/ have i0 : ι := Nonempty.some h_nonempty rw [show ⋂ i, F i = (F i0) ∩ ⋂ i, F i by simp [iInter_subset]] apply IsCompact.inter_iInter_nonempty · exact h_compact i0 · intro i exact (h_compact i).isClosed · intro I simpa using h_fin ({i0} ∪ I) /-- **Helly's theorem** for families of compact convex sets in its classical form. If `F` is a (possibly infinite) family of more than `d + 1` compact convex sets in a vector space of finite dimension `d`, and any `d + 1` sets of `F` intersect nontrivially, then all sets of `F` intersect nontrivially. -/ theorem helly_theorem_compact [TopologicalSpace E] [T2Space E] {F : ι → Set E} (h_card : finrank 𝕜 E + 1 ≤ ENat.card ι) (h_convex : ∀ i, Convex 𝕜 (F i)) (h_compact : ∀ i, IsCompact (F i)) (h_inter : ∀ I : Finset ι, #I = finrank 𝕜 E + 1 → (⋂ i ∈ I, F i).Nonempty) : (⋂ i, F i).Nonempty := by apply helly_theorem_compact' h_convex h_compact intro I hI_card have hJ : ∃ J : Finset ι, I ⊆ J ∧ #J = finrank 𝕜 E + 1 := by by_cases h : Infinite ι · exact Infinite.exists_superset_card_eq _ _ hI_card · have : Finite ι := Finite.of_not_infinite h have : Fintype ι := Fintype.ofFinite ι apply exists_superset_card_eq hI_card simp only [ENat.card_eq_coe_fintype_card] at h_card rwa [← Nat.cast_one, ← Nat.cast_add, Nat.cast_le] at h_card obtain ⟨J, hJ_ss, hJ_card⟩ := hJ apply Set.Nonempty.mono <| biInter_mono hJ_ss (by intro _ _; rfl) exact h_inter J hJ_card /-- **Helly's theorem** for sets of compact convex sets. If `F` is a set of compact convex sets in a vector space of finite dimension `d`, and any `k ≤ d + 1` sets from `F` intersect nontrivially, then all sets from `F` intersect nontrivially. -/ theorem helly_theorem_set_compact' [TopologicalSpace E] [T2Space E] {F : Set (Set E)} (h_convex : ∀ X ∈ F, Convex 𝕜 X) (h_compact : ∀ X ∈ F, IsCompact X) (h_inter : ∀ G : Finset (Set E), (G : Set (Set E)) ⊆ F → #G ≤ finrank 𝕜 E + 1 → (⋂₀ G : Set E).Nonempty) : (⋂₀ (F : Set (Set E))).Nonempty := by classical -- for DecidableEq, required for the family version rw [show ⋂₀ F = ⋂ X : F, (X : Set E) by ext; simp] refine helly_theorem_compact' (F := fun x : F ↦ x.val) (fun X ↦ h_convex X (by simp)) (fun X ↦ h_compact X (by simp)) ?_ intro G _ let G' : Finset (Set E) := image Subtype.val G rw [show ⋂ i ∈ G, ↑i = ⋂₀ (G' : Set (Set E)) by simp [G']] apply h_inter G' · simp [G'] · apply le_trans card_image_le assumption /-- **Helly's theorem** for sets of compact convex sets in its classical version. If `F` is a (possibly infinite) set of more than `d + 1` compact convex sets in a vector space of finite dimension `d`, and any `d + 1` sets from `F` intersect nontrivially, then all sets from `F` intersect nontrivially. -/ theorem helly_theorem_set_compact [TopologicalSpace E] [T2Space E] {F : Set (Set E)} (h_card : finrank 𝕜 E + 1 ≤ F.encard) (h_convex : ∀ X ∈ F, Convex 𝕜 X) (h_compact : ∀ X ∈ F, IsCompact X) (h_inter : ∀ G : Finset (Set E), (G : Set (Set E)) ⊆ F → #G = finrank 𝕜 E + 1 → (⋂₀ G : Set E).Nonempty) : (⋂₀ (F : Set (Set E))).Nonempty := by apply helly_theorem_set_compact' h_convex h_compact intro I hI_ss hI_card obtain ⟨J, _, hJ_ss, hJ_card⟩ := exists_superset_subset_encard_eq hI_ss (hkt := h_card) (by simpa only [encard_coe_eq_coe_finsetCard, ← ENat.coe_one, ← ENat.coe_add, Nat.cast_le]) apply Set.Nonempty.mono <| sInter_mono (by simpa [hI_ss]) have hJ_fin : Fintype J := Finite.fintype <| finite_of_encard_eq_coe hJ_card let J' := J.toFinset rw [← coe_toFinset J] apply h_inter J' · simpa [J'] · rwa [encard_eq_coe_toFinset_card J, ← ENat.coe_one, ← ENat.coe_add, Nat.cast_inj] at hJ_card end Convex
prime.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path. From mathcomp Require Import choice fintype div bigop. (******************************************************************************) (* This file contains the definitions of: *) (* prime p <=> p is a prime. *) (* primes m == the sorted list of prime divisors of m > 1, else [::]. *) (* pfactor p e == the value p ^ e of a prime factor (p, e). *) (* NumFactor f == print version of a prime factor, converting the prime *) (* component to a Num (which can print large values). *) (* prime_decomp m == the list of prime factors of m > 1, sorted by primes. *) (* logn p m == the e such that (p ^ e) \in prime_decomp n, else 0. *) (* trunc_log p m == the largest e such that p ^ e <= m, or 0 if p <= 1 or *) (* m is 0. *) (* up_log p m == the smallest e such that m <= p ^ e, or 0 if p <= 1 *) (* pdiv n == the smallest prime divisor of n > 1, else 1. *) (* max_pdiv n == the largest prime divisor of n > 1, else 1. *) (* divisors m == the sorted list of divisors of m > 0, else [::]. *) (* totient n == the Euler totient (#|{i < n | i and n coprime}|). *) (* nat_pred == the type of explicit collective nat predicates. *) (* := simpl_pred nat. *) (* -> We allow the coercion nat >-> nat_pred, interpreting p as pred1 p. *) (* -> We define a predType for nat_pred, enabling the notation p \in pi. *) (* -> We don't have nat_pred >-> pred, which would imply nat >-> Funclass. *) (* pi^' == the complement of pi : nat_pred, i.e., the nat_pred such *) (* that (p \in pi^') = (p \notin pi). *) (* \pi(n) == the set of prime divisors of n, i.e., the nat_pred such *) (* that (p \in \pi(n)) = (p \in primes n). *) (* \pi(A) == the set of primes of #|A|, with A a collective predicate *) (* over a finite Type. *) (* -> The notation \pi(A) is implemented with a collapsible Coercion. The *) (* type of A must coerce to finpred_sort (e.g., by coercing to {set T}) *) (* and not merely implement the predType interface (as seq T does). *) (* -> The expression #|A| will only appear in \pi(A) after simplification *) (* collapses the coercion, so it is advisable to do so early on. *) (* pi.-nat n <=> n > 0 and all prime divisors of n are in pi. *) (* n`_pi == the pi-part of n -- the largest pi.-nat divisor of n. *) (* := \prod_(0 <= p < n.+1 | p \in pi) p ^ logn p n. *) (* -> The nat >-> nat_pred coercion lets us write p.-nat n and n`_p. *) (* In addition to the lemmas relevant to these definitions, this file also *) (* contains the dvdn_sum lemma, so that bigop.v doesn't depend on div.v. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "pi ^'" (format "pi ^'"). Reserved Notation "pi .-nat" (format "pi .-nat"). (* The complexity of any arithmetic operation with the Peano representation *) (* is pretty dreadful, so using algorithms for "harder" problems such as *) (* factoring, that are geared for efficient arithmetic leads to dismal *) (* performance -- it takes a significant time, for instance, to compute the *) (* divisors of just a two-digit number. On the other hand, for Peano *) (* integers, prime factoring (and testing) is linear-time with a small *) (* constant factor -- indeed, the same as converting in and out of a binary *) (* representation. This is implemented by the code below, which is then *) (* used to give the "standard" definitions of prime, primes, and divisors, *) (* which can then be used casually in proofs with moderately-sized numeric *) (* values (indeed, the code here performs well for up to 6-digit numbers). *) Module Import PrimeDecompAux. (* We start with faster mod-2 and 2-valuation functions. *) Fixpoint edivn2 q r := if r is r'.+2 then edivn2 q.+1 r' else (q, r). Lemma edivn2P n : edivn_spec n 2 (edivn2 0 n). Proof. rewrite -[n]odd_double_half addnC -{1}[n./2]addn0 -{1}mul2n mulnC. elim: n./2 {1 4}0 => [|r IHr] q; first by case (odd n) => /=. by rewrite addSnnS; apply: IHr. Qed. Fixpoint elogn2 e q r {struct q} := match q, r with | 0, _ | _, 0 => (e, q) | q'.+1, 1 => elogn2 e.+1 q' q' | q'.+1, r'.+2 => elogn2 e q' r' end. Arguments elogn2 : simpl nomatch. Variant elogn2_spec n : nat * nat -> Type := Elogn2Spec e m of n = 2 ^ e * m.*2.+1 : elogn2_spec n (e, m). Lemma elogn2P n : elogn2_spec n.+1 (elogn2 0 n n). Proof. rewrite -[n.+1]mul1n -[1]/(2 ^ 0) -[n in _ * n.+1](addKn n n) addnn. elim: n {1 4 6}n {2 3}0 (leqnn n) => [|q IHq] [|[|r]] e //=; last first. by move/ltnW; apply: IHq. rewrite subn1 prednK // -mul2n mulnA -expnSr. by rewrite -[q in _ * q.+1](addKn q q) addnn => _; apply: IHq. Qed. Definition ifnz T n (x y : T) := if n is 0 then y else x. Variant ifnz_spec T n (x y : T) : T -> Type := | IfnzPos of n > 0 : ifnz_spec n x y x | IfnzZero of n = 0 : ifnz_spec n x y y. Lemma ifnzP T n (x y : T) : ifnz_spec n x y (ifnz n x y). Proof. by case: n => [|n]; [right | left]. Qed. (* The list of divisors and the Euler function are computed directly from *) (* the decomposition, using a merge_sort variant sort of the divisor list. *) Definition add_divisors f divs := let: (p, e) := f in let add1 divs' := merge leq (map (NatTrec.mul p) divs') divs in iter e add1 divs. Import NatTrec. Definition add_totient_factor f m := let: (p, e) := f in p.-1 * p ^ e.-1 * m. Definition cons_pfactor (p e : nat) pd := ifnz e ((p, e) :: pd) pd. Notation "p ^? e :: pd" := (cons_pfactor p e pd) (at level 30, e at level 30, pd at level 60) : nat_scope. End PrimeDecompAux. (* For pretty-printing. *) Definition NumFactor (f : nat * nat) := ([Num of f.1], f.2). Definition pfactor p e := p ^ e. Section prime_decomp. Import NatTrec. Local Fixpoint prime_decomp_rec m k a b c e := let p := k.*2.+1 in if a is a'.+1 then if b - (ifnz e 1 k - c) is b'.+1 then [rec m, k, a', b', ifnz c c.-1 (ifnz e p.-2 1), e] else if (b == 0) && (c == 0) then let b' := k + a' in [rec b'.*2.+3, k, a', b', k.-1, e.+1] else let bc' := ifnz e (ifnz b (k, 0) (edivn2 0 c)) (b, c) in p ^? e :: ifnz a' [rec m, k.+1, a'.-1, bc'.1 + a', bc'.2, 0] [:: (m, 1)] else if (b == 0) && (c == 0) then [:: (p, e.+2)] else p ^? e :: [:: (m, 1)] where "[ 'rec' m , k , a , b , c , e ]" := (prime_decomp_rec m k a b c e). Definition prime_decomp n := let: (e2, m2) := elogn2 0 n.-1 n.-1 in if m2 < 2 then 2 ^? e2 :: 3 ^? m2 :: [::] else let: (a, bc) := edivn m2.-2 3 in let: (b, c) := edivn (2 - bc) 2 in 2 ^? e2 :: [rec m2.*2.+1, 1, a, b, c, 0]. End prime_decomp. Definition primes n := unzip1 (prime_decomp n). Definition prime p := if prime_decomp p is [:: (_ , 1)] then true else false. Definition nat_pred := simpl_pred nat. Definition pi_arg := nat. Coercion pi_arg_of_nat (n : nat) : pi_arg := n. Coercion pi_arg_of_fin_pred T pT (A : @fin_pred_sort T pT) : pi_arg := #|A|. Arguments pi_arg_of_nat n /. Arguments pi_arg_of_fin_pred {T pT} A /. Definition pi_of (n : pi_arg) : nat_pred := [pred p in primes n]. Notation "\pi ( n )" := (pi_of n) (format "\pi ( n )") : nat_scope. Notation "\p 'i' ( A )" := \pi(#|A|) (format "\p 'i' ( A )") : nat_scope. Definition pdiv n := head 1 (primes n). Definition max_pdiv n := last 1 (primes n). Definition divisors n := foldr add_divisors [:: 1] (prime_decomp n). Definition totient n := foldr add_totient_factor (n > 0) (prime_decomp n). (* Correctness of the decomposition algorithm. *) Lemma prime_decomp_correct : let pd_val pd := \prod_(f <- pd) pfactor f.1 f.2 in let lb_dvd q m := ~~ has [pred d | d %| m] (index_iota 2 q) in let pf_ok f := lb_dvd f.1 f.1 && (0 < f.2) in let pd_ord q pd := path ltn q (unzip1 pd) in let pd_ok q n pd := [/\ n = pd_val pd, all pf_ok pd & pd_ord q pd] in forall n, n > 0 -> pd_ok 1 n (prime_decomp n). Proof. rewrite unlock => pd_val lb_dvd pf_ok pd_ord pd_ok. have leq_pd_ok m p q pd: q <= p -> pd_ok p m pd -> pd_ok q m pd. rewrite /pd_ok /pd_ord; case: pd => [|[r _] pd] //= leqp [<- ->]. by case/andP=> /(leq_trans _)->. have apd_ok m e q p pd: lb_dvd p p || (e == 0) -> q < p -> pd_ok p m pd -> pd_ok q (p ^ e * m) (p ^? e :: pd). - case: e => [|e]; rewrite orbC /= => pr_p ltqp. by rewrite mul1n; apply: leq_pd_ok; apply: ltnW. by rewrite /pd_ok /pd_ord /pf_ok /= pr_p ltqp => [[<- -> ->]]. case=> // n _; rewrite /prime_decomp. case: elogn2P => e2 m2 -> {n}; case: m2 => [|[|abc]]; try exact: apd_ok. rewrite [_.-2]/= !ltnS ltn0 natTrecE; case: edivnP => a bc ->{abc}. case: edivnP => b c def_bc /= ltc2 ltbc3; apply: (apd_ok) => //. move def_m: _.*2.+1 => m; set k := {2}1; rewrite -[2]/k.*2; set e := 0. pose p := k.*2.+1; rewrite -{1}[m]mul1n -[1]/(p ^ e)%N. have{def_m bc def_bc ltc2 ltbc3}: let kb := (ifnz e k 1).*2 in [&& k > 0, p < m, lb_dvd p m, c < kb & lb_dvd p p || (e == 0)] /\ m + (b * kb + c).*2 = p ^ 2 + (a * p).*2. - rewrite -def_m [in lb_dvd _ _]def_m; split=> //=; last first. by rewrite -def_bc addSn -doubleD 2!addSn -addnA subnKC // addnC. rewrite ltc2 /lb_dvd /index_iota /= dvdn2 -def_m. by rewrite [_.+2]lock /= odd_double. have [n] := ubnP a. elim: n => // n IHn in a (k) p m b c (e) * => /ltnSE-le_a_n []. set kb := _.*2; set d := _ + c => /and5P[lt0k ltpm leppm ltc pr_p def_m]. have def_k1: k.-1.+1 = k := ltn_predK lt0k. have def_kb1: kb.-1.+1 = kb by rewrite /kb -def_k1; case e. have eq_bc_0: (b == 0) && (c == 0) = (d == 0). by rewrite addn_eq0 muln_eq0 orbC -def_kb1. have lt1p: 1 < p by rewrite ltnS double_gt0. have co_p_2: coprime p 2 by rewrite /coprime gcdnC gcdnE modn2 /= odd_double. have if_d0: d = 0 -> [/\ m = (p + a.*2) * p, lb_dvd p p & lb_dvd p (p + a.*2)]. move=> d0; have{d0} def_m: m = (p + a.*2) * p. by rewrite d0 addn0 -!mul2n mulnA -mulnDl in def_m *. split=> //; apply/hasPn=> r /(hasPn leppm); apply: contra => /= dv_r. by rewrite def_m dvdn_mull. by rewrite def_m dvdn_mulr. case def_a: a => [|a'] /= in le_a_n *; rewrite !natTrecE -/p {}eq_bc_0. case: d if_d0 def_m => [[//| def_m {}pr_p pr_m'] _ | d _ def_m] /=. rewrite def_m def_a addn0 mulnA -2!expnSr. by split; rewrite /pd_ord /pf_ok /= ?muln1 ?pr_p ?leqnn. apply: apd_ok; rewrite // /pd_ok /= /pfactor expn1 muln1 /pd_ord /= ltpm. rewrite /pf_ok !andbT /=; split=> //; apply: contra leppm. case/hasP=> r /=; rewrite mem_index_iota => /andP[lt1r ltrm] dvrm; apply/hasP. have [ltrp | lepr] := ltnP r p. by exists r; rewrite // mem_index_iota lt1r. case/dvdnP: dvrm => q def_q; exists q; last by rewrite def_q /= dvdn_mulr. rewrite mem_index_iota -(ltn_pmul2r (ltnW lt1r)) -def_q mul1n ltrm. move: def_m; rewrite def_a addn0 -(@ltn_pmul2r p) // mulnn => <-. apply: (@leq_ltn_trans m); first by rewrite def_q leq_mul. by rewrite -addn1 leq_add2l. have def_k2: k.*2 = ifnz e 1 k * kb. by rewrite /kb; case: (e) => [|e']; rewrite (mul1n, muln2). case def_b': (b - _) => [|b']; last first. have ->: ifnz e k.*2.-1 1 = kb.-1 by rewrite /kb; case e. apply: IHn => {n le_a_n}//; rewrite -/p -/kb; split=> //. rewrite lt0k ltpm leppm pr_p andbT /=. by case: ifnzP; [move/ltn_predK->; apply: ltnW | rewrite def_kb1]. apply: (@addIn p.*2). rewrite -2!addnA -!doubleD -addnA -mulSnr -def_a -def_m /d. have ->: b * kb = b' * kb + (k.*2 - c * kb + kb). rewrite addnCA addnC -mulSnr -def_b' def_k2 -mulnBl -mulnDl subnK //. by rewrite ltnW // -subn_gt0 def_b'. rewrite -addnA; congr (_ + (_ + _).*2). case: (c) ltc; first by rewrite -addSnnS def_kb1 subn0 addn0 addnC. rewrite /kb; case e => [[] // _ | e' c' _] /=; last first. by rewrite subnDA subnn addnC addSnnS. by rewrite mul1n -doubleB -doubleD subn1 !addn1 def_k1. have ltdp: d < p. move/eqP: def_b'; rewrite subn_eq0 -(@leq_pmul2r kb); last first. by rewrite -def_kb1. rewrite mulnBl -def_k2 ltnS -(leq_add2r c); move/leq_trans; apply. have{} ltc: c < k.*2. by apply: (leq_trans ltc); rewrite leq_double /kb; case e. rewrite -{2}(subnK (ltnW ltc)) leq_add2r leq_sub2l //. by rewrite -def_kb1 mulnS leq_addr. case def_d: d if_d0 => [|d'] => [[//|{ltdp pr_p}def_m pr_p pr_m'] | _]. rewrite eqxx -doubleS -addnS -def_a doubleD -addSn -/p def_m. rewrite mulnCA mulnC -expnSr. apply: IHn => {n le_a_n}//; rewrite -/p -/kb; split. rewrite lt0k -addn1 leq_add2l {1}def_a pr_m' pr_p /= def_k1 -addnn. by rewrite leq_addr. rewrite -addnA -doubleD addnCA def_a addSnnS def_k1 -(addnC k) -mulnSr. by rewrite -[_.*2.+1]/p mulnDl doubleD addnA -mul2n mulnA mul2n -mulSn. have next_pm: lb_dvd p.+2 m. rewrite /lb_dvd /index_iota (addKn 2) -(subnK lt1p) iotaD has_cat. apply/norP; split; rewrite //= orbF subnKC // orbC. apply/norP; split; apply/dvdnP=> [[q def_q]]. case/hasP: leppm; exists 2; first by rewrite /p -(subnKC lt0k). by rewrite /= def_q dvdn_mull // dvdn2 /= odd_double. move/(congr1 (dvdn p)): def_m; rewrite -!mul2n mulnA -mulnDl. rewrite dvdn_mull // dvdn_addr; last by rewrite def_q dvdn_mull. case/dvdnP=> r; rewrite mul2n => def_r; move: ltdp (congr1 odd def_r). rewrite odd_double -ltn_double def_r -mul2n ltn_pmul2r //. by case: r def_r => [|[|[]]] //; rewrite def_d // mul1n /= odd_double. apply: apd_ok => //; case: a' def_a le_a_n => [|a'] def_a => [_ | lta] /=. rewrite /pd_ok /= /pfactor expn1 muln1 /pd_ord /= ltpm /pf_ok !andbT /=. split=> //; apply: contra next_pm. case/hasP=> q; rewrite mem_index_iota => /andP[lt1q ltqm] dvqm; apply/hasP. have [ltqp | lepq] := ltnP q p.+2. by exists q; rewrite // mem_index_iota lt1q. case/dvdnP: dvqm => r def_r; exists r; last by rewrite def_r /= dvdn_mulr. rewrite mem_index_iota -(ltn_pmul2r (ltnW lt1q)) -def_r mul1n ltqm /=. rewrite -(@ltn_pmul2l p.+2) //; apply: (@leq_ltn_trans m). by rewrite def_r mulnC leq_mul. rewrite -addn2 mulnn sqrnD mul2n muln2 -addnn addnACA. by rewrite def_a mul1n in def_m; rewrite -def_m addnS /= ltnS -addnA leq_addr. set bc := ifnz _ _ _; apply: leq_pd_ok (leqnSn _) _. rewrite -doubleS -{1}[m]mul1n -[1]/(k.+1.*2.+1 ^ 0)%N. apply: IHn; first exact: ltnW. rewrite doubleS -/p [ifnz 0 _ _]/=; do 2?split => //. rewrite orbT next_pm /= -(leq_add2r d.*2) def_m 2!addSnnS -doubleS leq_add. - move: ltc; rewrite /kb {}/bc andbT; case e => //= e' _; case: ifnzP => //. by case: edivn2P. - by rewrite -[ltnLHS]muln1 ltn_pmul2l. by rewrite leq_double def_a mulSn (leq_trans ltdp) ?leq_addr. rewrite mulnDl !muln2 -addnA addnCA doubleD addnCA. rewrite (_ : _ + bc.2 = d); last first. rewrite /d {}/bc /kb -muln2. case: (e) (b) def_b' => //= _ []; first by case: edivn2P. by case c; do 2?case; rewrite // mul1n /= muln2. rewrite def_m 3!doubleS addnC -(addn2 p) sqrnD mul2n muln2 -3!addnA. congr (_ + _); rewrite 4!addnS -!doubleD; congr _.*2.+2.+2. by rewrite def_a -add2n mulnDl -addnA -muln2 -mulnDr mul2n. Qed. Lemma primePn n : reflect (n < 2 \/ exists2 d, 1 < d < n & d %| n) (~~ prime n). Proof. rewrite /prime; case: n => [|[|p2]]; try by do 2!left. case: (@prime_decomp_correct p2.+2) => //; rewrite unlock. case: prime_decomp => [|[q [|[|e]]] pd] //=; last first; last by rewrite andbF. rewrite {1}/pfactor 2!expnS -!mulnA /=. case: (_ ^ _ * _) => [|u -> _ /andP[lt1q _]]; first by rewrite !muln0. left; right; exists q; last by rewrite dvdn_mulr. have lt0q := ltnW lt1q; rewrite lt1q -[ltnLHS]muln1 ltn_pmul2l //. by rewrite -[2]muln1 leq_mul. rewrite {1}/pfactor expn1; case: pd => [|[r e] pd] /=; last first. case: e => [|e] /=; first by rewrite !andbF. rewrite {1}/pfactor expnS -mulnA. case: (_ ^ _ * _) => [|u -> _ /and3P[lt1q ltqr _]]; first by rewrite !muln0. left; right; exists q; last by rewrite dvdn_mulr. by rewrite lt1q -[ltnLHS]mul1n ltn_mul // -[q.+1]muln1 leq_mul. rewrite muln1 !andbT => def_q pr_q lt1q; right=> [[]] // [d]. by rewrite def_q -mem_index_iota => in_d_2q dv_d_q; case/hasP: pr_q; exists d. Qed. Lemma primeNsig n : ~~ prime n -> 2 <= n -> { d : nat | 1 < d < n & d %| n }. Proof. by move=> /primePn; case: ltnP => // lt1n nP _; apply/sig2W; case: nP. Qed. Lemma primeP p : reflect (p > 1 /\ forall d, d %| p -> xpred2 1 p d) (prime p). Proof. rewrite -[prime p]negbK; have [npr_p | pr_p] := primePn p. right=> [[lt1p pr_p]]; case: npr_p => [|[d n1pd]]. by rewrite ltnNge lt1p. by move/pr_p=> /orP[] /eqP def_d; rewrite def_d ltnn ?andbF in n1pd. have [lep1 | lt1p] := leqP; first by case: pr_p; left. left; split=> // d dv_d_p; apply/norP=> [[nd1 ndp]]; case: pr_p; right. exists d; rewrite // andbC 2!ltn_neqAle ndp eq_sym nd1. by have lt0p := ltnW lt1p; rewrite dvdn_leq // (dvdn_gt0 lt0p). Qed. Lemma prime_nt_dvdP d p : prime p -> d != 1 -> reflect (d = p) (d %| p). Proof. case/primeP=> _ min_p d_neq1; apply: (iffP idP) => [/min_p|-> //]. by rewrite (negPf d_neq1) /= => /eqP. Qed. Arguments primeP {p}. Arguments primePn {n}. Lemma prime_gt1 p : prime p -> 1 < p. Proof. by case/primeP. Qed. Lemma prime_gt0 p : prime p -> 0 < p. Proof. by move/prime_gt1; apply: ltnW. Qed. #[global] Hint Resolve prime_gt1 prime_gt0 : core. Lemma prod_prime_decomp n : n > 0 -> n = \prod_(f <- prime_decomp n) f.1 ^ f.2. Proof. by case/prime_decomp_correct. Qed. Lemma even_prime p : prime p -> p = 2 \/ odd p. Proof. move=> pr_p; case odd_p: (odd p); [by right | left]. have: 2 %| p by rewrite dvdn2 odd_p. by case/primeP: pr_p => _ dv_p /dv_p/(2 =P p). Qed. Lemma prime_oddPn p : prime p -> reflect (p = 2) (~~ odd p). Proof. by move=> p_pr; apply: (iffP idP) => [|-> //]; case/even_prime: p_pr => ->. Qed. Lemma odd_prime_gt2 p : odd p -> prime p -> p > 2. Proof. by move=> odd_p /prime_gt1; apply: odd_gt2. Qed. Lemma mem_prime_decomp n p e : (p, e) \in prime_decomp n -> [/\ prime p, e > 0 & p ^ e %| n]. Proof. case: (posnP n) => [-> //| /prime_decomp_correct[def_n mem_pd ord_pd pd_pe]]. have /andP[pr_p ->] := allP mem_pd _ pd_pe; split=> //; last first. case/splitPr: pd_pe def_n => pd1 pd2 ->. by rewrite big_cat big_cons /= mulnCA dvdn_mulr. have lt1p: 1 < p. apply: (allP (order_path_min ltn_trans ord_pd)). by apply/mapP; exists (p, e). apply/primeP; split=> // d dv_d_p; apply/norP=> [[nd1 ndp]]. case/hasP: pr_p; exists d => //. rewrite mem_index_iota andbC 2!ltn_neqAle ndp eq_sym nd1. by have lt0p := ltnW lt1p; rewrite dvdn_leq // (dvdn_gt0 lt0p). Qed. Lemma prime_coprime p m : prime p -> coprime p m = ~~ (p %| m). Proof. case/primeP=> p_gt1 p_pr; apply/eqP/negP=> [d1 | ndv_pm]. case/dvdnP=> k def_m; rewrite -(addn0 m) def_m gcdnMDl gcdn0 in d1. by rewrite d1 in p_gt1. by apply: gcdn_def => // d /p_pr /orP[] /eqP->. Qed. Lemma dvdn_prime2 p q : prime p -> prime q -> (p %| q) = (p == q). Proof. move=> pr_p pr_q; apply: negb_inj. by rewrite eqn_dvd negb_and -!prime_coprime // coprime_sym orbb. Qed. Lemma Euclid_dvd1 p : prime p -> (p %| 1) = false. Proof. by rewrite dvdn1; case: eqP => // ->. Qed. Lemma Euclid_dvdM m n p : prime p -> (p %| m * n) = (p %| m) || (p %| n). Proof. move=> pr_p; case dv_pm: (p %| m); first exact: dvdn_mulr. by rewrite Gauss_dvdr // prime_coprime // dv_pm. Qed. Lemma Euclid_dvd_prod (I : Type) (r : seq I) (P : pred I) (f : I -> nat) p : prime p -> p %| \prod_(i <- r | P i) f i = \big[orb/false]_(i <- r | P i) (p %| f i). Proof. move=> pP; apply: big_morph=> [x y|]; [exact: Euclid_dvdM | exact: Euclid_dvd1]. Qed. Lemma Euclid_dvdX m n p : prime p -> (p %| m ^ n) = (p %| m) && (n > 0). Proof. case: n => [|n] pr_p; first by rewrite andbF Euclid_dvd1. by apply: (inv_inj negbK); rewrite !andbT -!prime_coprime // coprime_pexpr. Qed. Lemma mem_primes p n : (p \in primes n) = [&& prime p, n > 0 & p %| n]. Proof. rewrite andbCA; have [-> // | /= n_gt0] := posnP. apply/mapP/andP=> [[[q e]]|[pr_p]] /=. case/mem_prime_decomp=> pr_q e_gt0 /dvdnP [u ->] -> {p}. by rewrite -(prednK e_gt0) expnS mulnCA dvdn_mulr. rewrite [n in _ %| n]prod_prime_decomp // big_seq. apply big_ind => [| u v IHu IHv | [q e] /= mem_qe dv_p_qe]. - by rewrite Euclid_dvd1. - by rewrite Euclid_dvdM // => /orP[]. exists (q, e) => //=; case/mem_prime_decomp: mem_qe => pr_q _ _. by rewrite Euclid_dvdX // dvdn_prime2 // in dv_p_qe; case: eqP dv_p_qe. Qed. Lemma sorted_primes n : sorted ltn (primes n). Proof. by case: (posnP n) => [-> // | /prime_decomp_correct[_ _]]; apply: path_sorted. Qed. Lemma all_prime_primes n : all prime (primes n). Proof. by apply/allP => p; rewrite mem_primes => /and3P[]. Qed. Lemma eq_primes m n : (primes m =i primes n) <-> (primes m = primes n). Proof. split=> [eqpr| -> //]. by apply: (irr_sorted_eq ltn_trans ltnn); rewrite ?sorted_primes. Qed. Lemma primes_uniq n : uniq (primes n). Proof. exact: (sorted_uniq ltn_trans ltnn (sorted_primes n)). Qed. (* The smallest prime divisor *) Lemma pi_pdiv n : (pdiv n \in \pi(n)) = (n > 1). Proof. case: n => [|[|n]] //; rewrite /pdiv !inE /primes. have:= prod_prime_decomp (ltn0Sn n.+1); rewrite unlock. by case: prime_decomp => //= pf pd _; rewrite mem_head. Qed. Lemma pdiv_prime n : 1 < n -> prime (pdiv n). Proof. by rewrite -pi_pdiv mem_primes; case/and3P. Qed. Lemma pdiv_dvd n : pdiv n %| n. Proof. by case: n (pi_pdiv n) => [|[|n]] //; rewrite mem_primes=> /and3P[]. Qed. Lemma pi_max_pdiv n : (max_pdiv n \in \pi(n)) = (n > 1). Proof. rewrite !inE -pi_pdiv /max_pdiv /pdiv !inE. by case: (primes n) => //= p ps; rewrite mem_head mem_last. Qed. Lemma max_pdiv_prime n : n > 1 -> prime (max_pdiv n). Proof. by rewrite -pi_max_pdiv mem_primes => /andP[]. Qed. Lemma max_pdiv_dvd n : max_pdiv n %| n. Proof. by case: n (pi_max_pdiv n) => [|[|n]] //; rewrite mem_primes => /andP[]. Qed. Lemma pdiv_leq n : 0 < n -> pdiv n <= n. Proof. by move=> n_gt0; rewrite dvdn_leq // pdiv_dvd. Qed. Lemma max_pdiv_leq n : 0 < n -> max_pdiv n <= n. Proof. by move=> n_gt0; rewrite dvdn_leq // max_pdiv_dvd. Qed. Lemma pdiv_gt0 n : 0 < pdiv n. Proof. by case: n => [|[|n]] //; rewrite prime_gt0 ?pdiv_prime. Qed. Lemma max_pdiv_gt0 n : 0 < max_pdiv n. Proof. by case: n => [|[|n]] //; rewrite prime_gt0 ?max_pdiv_prime. Qed. #[global] Hint Resolve pdiv_gt0 max_pdiv_gt0 : core. Lemma pdiv_min_dvd m d : 1 < d -> d %| m -> pdiv m <= d. Proof. case: (posnP m) => [->|mpos] lt1d dv_d_m; first exact: ltnW. rewrite /pdiv; apply: leq_trans (pdiv_leq (ltnW lt1d)). have: pdiv d \in primes m. by rewrite mem_primes mpos pdiv_prime // (dvdn_trans (pdiv_dvd d)). case: (primes m) (sorted_primes m) => //= p pm ord_pm; rewrite inE. by case/predU1P => [-> | /(allP (order_path_min ltn_trans ord_pm)) /ltnW]. Qed. Lemma max_pdiv_max n p : p \in \pi(n) -> p <= max_pdiv n. Proof. rewrite /max_pdiv !inE => n_p. case/splitPr: n_p (sorted_primes n) => p1 p2; rewrite last_cat -cat_rcons /=. rewrite headI /= cat_path -(last_cons 0) -headI last_rcons; case/andP=> _. move/(order_path_min ltn_trans); case/lastP: p2 => //= p2 q. by rewrite all_rcons last_rcons ltn_neqAle -andbA => /and3P[]. Qed. Lemma ltn_pdiv2_prime n : 0 < n -> n < pdiv n ^ 2 -> prime n. Proof. case def_n: n => [|[|n']] // _; rewrite -def_n => lt_n_p2. suffices ->: n = pdiv n by rewrite pdiv_prime ?def_n. apply/eqP; rewrite eqn_leq leqNgt andbC pdiv_leq; last by rewrite def_n. apply/contraL: lt_n_p2 => lt_pm_m; case/dvdnP: (pdiv_dvd n) => q def_q. rewrite -leqNgt [leqRHS]def_q leq_pmul2r // pdiv_min_dvd //. by rewrite -[pdiv n]mul1n [ltnRHS]def_q ltn_pmul2r in lt_pm_m. by rewrite def_q dvdn_mulr. Qed. Lemma primePns n : reflect (n < 2 \/ exists p, [/\ prime p, p ^ 2 <= n & p %| n]) (~~ prime n). Proof. apply: (iffP idP) => [npr_p|]; last first. case=> [|[p [pr_p le_p2_n dv_p_n]]]; first by case: n => [|[]]. apply/negP=> pr_n; move: dv_p_n le_p2_n; rewrite dvdn_prime2 //; move/eqP->. by rewrite leqNgt -[ltnLHS]muln1 ltn_pmul2l ?prime_gt1 ?prime_gt0. have [lt1p|] := leqP; [right | by left]. exists (pdiv n); rewrite pdiv_dvd pdiv_prime //; split=> //. by case: leqP npr_p => // /ltn_pdiv2_prime -> //; exact: ltnW. Qed. Arguments primePns {n}. Lemma pdivP n : n > 1 -> {p | prime p & p %| n}. Proof. by move=> lt1n; exists (pdiv n); rewrite ?pdiv_dvd ?pdiv_prime. Qed. Lemma primes_eq0 n : (primes n == [::]) = (n < 2). Proof. case: n => [|[|n']]//=; have [//|p pp pn] := @pdivP (n'.+2). suff: p \in primes n'.+2 by case: primes. by rewrite mem_primes pp pn. Qed. Lemma primesM m n p : m > 0 -> n > 0 -> (p \in primes (m * n)) = (p \in primes m) || (p \in primes n). Proof. move=> m_gt0 n_gt0; rewrite !mem_primes muln_gt0 m_gt0 n_gt0. by case pr_p: (prime p); rewrite // Euclid_dvdM. Qed. Lemma primesX m n : n > 0 -> primes (m ^ n) = primes m. Proof. case: n => // n _; rewrite expnS; have [-> // | m_gt0] := posnP m. apply/eq_primes => /= p; elim: n => [|n IHn]; first by rewrite muln1. by rewrite primesM ?(expn_gt0, expnS, IHn, orbb, m_gt0). Qed. Lemma primes_prime p : prime p -> primes p = [:: p]. Proof. move=> pr_p; apply: (irr_sorted_eq ltn_trans ltnn) => // [|q]. exact: sorted_primes. rewrite mem_seq1 mem_primes prime_gt0 //=. by apply/andP/idP=> [[pr_q q_p] | /eqP-> //]; rewrite -dvdn_prime2. Qed. Lemma coprime_has_primes m n : 0 < m -> 0 < n -> coprime m n = ~~ has [in primes m] (primes n). Proof. move=> m_gt0 n_gt0; apply/eqP/hasPn=> [mn1 p | no_p_mn]. rewrite /= !mem_primes m_gt0 n_gt0 /= => /andP[pr_p p_n]. have:= prime_gt1 pr_p; rewrite pr_p ltnNge -mn1 /=; apply: contra => p_m. by rewrite dvdn_leq ?gcdn_gt0 ?m_gt0 // dvdn_gcd ?p_m. apply/eqP; rewrite eqn_leq gcdn_gt0 m_gt0 andbT leqNgt; apply/negP. move/pdiv_prime; set p := pdiv _ => pr_p. move/implyP: (no_p_mn p); rewrite /= !mem_primes m_gt0 n_gt0 pr_p /=. by rewrite !(dvdn_trans (pdiv_dvd _)) // (dvdn_gcdl, dvdn_gcdr). Qed. Lemma pdiv_id p : prime p -> pdiv p = p. Proof. by move=> p_pr; rewrite /pdiv primes_prime. Qed. Lemma pdiv_pfactor p k : prime p -> pdiv (p ^ k.+1) = p. Proof. by move=> p_pr; rewrite /pdiv primesX ?primes_prime. Qed. (* Primes are unbounded. *) Lemma prime_above m : {p | m < p & prime p}. Proof. have /pdivP[p pr_p p_dv_m1]: 1 < m`! + 1 by rewrite addn1 ltnS fact_gt0. exists p => //; rewrite ltnNge; apply: contraL p_dv_m1 => p_le_m. by rewrite dvdn_addr ?dvdn_fact ?prime_gt0 // gtnNdvd ?prime_gt1. Qed. (* "prime" logarithms and p-parts. *) Fixpoint logn_rec d m r := match r, edivn m d with | r'.+1, (_.+1 as m', 0) => (logn_rec d m' r').+1 | _, _ => 0 end. Definition logn p m := if prime p then logn_rec p m m else 0. Lemma lognE p m : logn p m = if [&& prime p, 0 < m & p %| m] then (logn p (m %/ p)).+1 else 0. Proof. rewrite /logn /dvdn; case p_pr: (prime p) => //. case def_m: m => // [m']; rewrite !andTb [LHS]/= -def_m /divn modn_def. case: edivnP def_m => [[|q] [|r] -> _] // def_m; congr _.+1; rewrite [_.1]/=. have{m def_m}: q < m'. by rewrite -ltnS -def_m addn0 mulnC -{1}[q.+1]mul1n ltn_pmul2r // prime_gt1. elim/ltn_ind: m' {q}q.+1 (ltn0Sn q) => -[_ []|r IHr m] //= m_gt0 le_mr. rewrite -[m in logn_rec _ _ m]prednK //=. case: edivnP => [[|q] [|_] def_q _] //; rewrite addn0 in def_q. have{def_q} lt_qm1: q < m.-1. by rewrite -[q.+1]muln1 -ltnS prednK // def_q ltn_pmul2l // prime_gt1. have{le_mr} le_m1r: m.-1 <= r by rewrite -ltnS prednK. by rewrite (IHr r) ?(IHr m.-1) // (leq_trans lt_qm1). Qed. Lemma logn_gt0 p n : (0 < logn p n) = (p \in primes n). Proof. by rewrite lognE -mem_primes; case: {+}(p \in _). Qed. Lemma ltn_log0 p n : n < p -> logn p n = 0. Proof. by case: n => [|n] ltnp; rewrite lognE ?andbF // gtnNdvd ?andbF. Qed. Lemma logn0 p : logn p 0 = 0. Proof. by rewrite /logn if_same. Qed. Lemma logn1 p : logn p 1 = 0. Proof. by rewrite lognE dvdn1 /= andbC; case: eqP => // ->. Qed. Lemma pfactor_gt0 p n : 0 < p ^ logn p n. Proof. by rewrite expn_gt0 lognE; case: (posnP p) => // ->. Qed. #[global] Hint Resolve pfactor_gt0 : core. Lemma pfactor_dvdn p n m : prime p -> m > 0 -> (p ^ n %| m) = (n <= logn p m). Proof. move=> p_pr; elim: n m => [|n IHn] m m_gt0; first exact: dvd1n. rewrite lognE p_pr m_gt0 /=; case dv_pm: (p %| m); last first. apply/dvdnP=> [] [/= q def_m]. by rewrite def_m expnS mulnCA dvdn_mulr in dv_pm. case/dvdnP: dv_pm m_gt0 => q ->{m}; rewrite muln_gt0 => /andP[p_gt0 q_gt0]. by rewrite expnSr dvdn_pmul2r // mulnK // IHn. Qed. Lemma pfactor_dvdnn p n : p ^ logn p n %| n. Proof. case: n => // n; case pr_p: (prime p); first by rewrite pfactor_dvdn. by rewrite lognE pr_p dvd1n. Qed. Lemma logn_prime p q : prime q -> logn p q = (p == q). Proof. move=> pr_q; have q_gt0 := prime_gt0 pr_q; rewrite lognE q_gt0 /=. case pr_p: (prime p); last by case: eqP pr_p pr_q => // -> ->. by rewrite dvdn_prime2 //; case: eqP => // ->; rewrite divnn q_gt0 logn1. Qed. Lemma pfactor_coprime p n : prime p -> n > 0 -> {m | coprime p m & n = m * p ^ logn p n}. Proof. move=> p_pr n_gt0; set k := logn p n. have dv_pk_n: p ^ k %| n by rewrite pfactor_dvdn. exists (n %/ p ^ k); last by rewrite divnK. rewrite prime_coprime // -(@dvdn_pmul2r (p ^ k)) ?expn_gt0 ?prime_gt0 //. by rewrite -expnS divnK // pfactor_dvdn // ltnn. Qed. Lemma pfactorK p n : prime p -> logn p (p ^ n) = n. Proof. move=> p_pr; have pn_gt0: p ^ n > 0 by rewrite expn_gt0 prime_gt0. apply/eqP; rewrite eqn_leq -pfactor_dvdn // dvdnn andbT. by rewrite -(leq_exp2l _ _ (prime_gt1 p_pr)) dvdn_leq // pfactor_dvdn. Qed. Lemma pfactorKpdiv p n : prime p -> logn (pdiv (p ^ n)) (p ^ n) = n. Proof. by case: n => // n p_pr; rewrite pdiv_pfactor ?pfactorK. Qed. Lemma dvdn_leq_log p m n : 0 < n -> m %| n -> logn p m <= logn p n. Proof. move=> n_gt0 dv_m_n; have m_gt0 := dvdn_gt0 n_gt0 dv_m_n. case p_pr: (prime p); last by do 2!rewrite lognE p_pr /=. by rewrite -pfactor_dvdn //; apply: dvdn_trans dv_m_n; rewrite pfactor_dvdn. Qed. Lemma ltn_logl p n : 0 < n -> logn p n < n. Proof. move=> n_gt0; have [p_gt1 | p_le1] := boolP (1 < p). by rewrite (leq_trans (ltn_expl _ p_gt1)) // dvdn_leq ?pfactor_dvdnn. by rewrite lognE (contraNF (@prime_gt1 _)). Qed. Lemma logn_Gauss p m n : coprime p m -> logn p (m * n) = logn p n. Proof. move=> co_pm; case p_pr: (prime p); last by rewrite /logn p_pr. have [-> | n_gt0] := posnP n; first by rewrite muln0. have [m0 | m_gt0] := posnP m; first by rewrite m0 prime_coprime ?dvdn0 in co_pm. have mn_gt0: m * n > 0 by rewrite muln_gt0 m_gt0. apply/eqP; rewrite eqn_leq andbC dvdn_leq_log ?dvdn_mull //. set k := logn p _; have: p ^ k %| m * n by rewrite pfactor_dvdn. by rewrite Gauss_dvdr ?coprimeXl // -pfactor_dvdn. Qed. Lemma logn_coprime p m : coprime p m -> logn p m = 0. Proof. by move=> coprime_pm; rewrite -[m]muln1 logn_Gauss// logn1. Qed. Lemma lognM p m n : 0 < m -> 0 < n -> logn p (m * n) = logn p m + logn p n. Proof. case p_pr: (prime p); last by rewrite /logn p_pr. have xlp := pfactor_coprime p_pr. case/xlp=> m' co_m' def_m /xlp[n' co_n' def_n] {xlp}. rewrite [in LHS]def_m [in LHS]def_n mulnCA -mulnA -expnD !logn_Gauss //. exact: pfactorK. Qed. Lemma lognX p m n : logn p (m ^ n) = n * logn p m. Proof. case p_pr: (prime p); last by rewrite /logn p_pr muln0. elim: n => [|n IHn]; first by rewrite logn1. have [->|m_gt0] := posnP m; first by rewrite exp0n // lognE andbF muln0. by rewrite expnS lognM ?IHn // expn_gt0 m_gt0. Qed. Lemma logn_div p m n : m %| n -> logn p (n %/ m) = logn p n - logn p m. Proof. rewrite dvdn_eq => /eqP def_n. case: (posnP n) => [-> |]; first by rewrite div0n logn0. by rewrite -{1 3}def_n muln_gt0 => /andP[q_gt0 m_gt0]; rewrite lognM ?addnK. Qed. Lemma dvdn_pfactor p d n : prime p -> reflect (exists2 m, m <= n & d = p ^ m) (d %| p ^ n). Proof. move=> p_pr; have pn_gt0: p ^ n > 0 by rewrite expn_gt0 prime_gt0. apply: (iffP idP) => [dv_d_pn|[m le_m_n ->]]; last first. by rewrite -(subnK le_m_n) expnD dvdn_mull. exists (logn p d); first by rewrite -(pfactorK n p_pr) dvdn_leq_log. have d_gt0: d > 0 by apply: dvdn_gt0 dv_d_pn. case: (pfactor_coprime p_pr d_gt0) => q co_p_q def_d. rewrite [LHS]def_d ((q =P 1) _) ?mul1n // -dvdn1. suff: q %| p ^ n * 1 by rewrite Gauss_dvdr // coprime_sym coprimeXl. by rewrite muln1 (dvdn_trans _ dv_d_pn) // def_d dvdn_mulr. Qed. Lemma prime_decompE n : prime_decomp n = [seq (p, logn p n) | p <- primes n]. Proof. case: n => // n; pose f0 := (0, 0); rewrite -map_comp. apply: (@eq_from_nth _ f0) => [|i lt_i_n]; first by rewrite size_map. rewrite (nth_map f0) //; case def_f: (nth _ _ i) => [p e] /=. congr (_, _); rewrite [n.+1]prod_prime_decomp //. have: (p, e) \in prime_decomp n.+1 by rewrite -def_f mem_nth. case/mem_prime_decomp=> pr_p _ _. rewrite (big_nth f0) big_mkord (bigD1 (Ordinal lt_i_n)) //=. rewrite def_f mulnC logn_Gauss ?pfactorK //. apply big_ind => [|m1 m2 com1 com2| [j ltj] /=]; first exact: coprimen1. by rewrite coprimeMr com1. rewrite -val_eqE /= => nji; case def_j: (nth _ _ j) => [q e1] /=. have: (q, e1) \in prime_decomp n.+1 by rewrite -def_j mem_nth. case/mem_prime_decomp=> pr_q e1_gt0 _; rewrite coprime_pexpr //. rewrite prime_coprime // dvdn_prime2 //; apply: contra nji => eq_pq. rewrite -(nth_uniq 0 _ _ (primes_uniq n.+1)) ?size_map //=. by rewrite !(nth_map f0) // def_f def_j /= eq_sym. Qed. (* Some combinatorial formulae. *) Lemma divn_count_dvd d n : n %/ d = \sum_(1 <= i < n.+1) (d %| i). Proof. have [-> | d_gt0] := posnP d; first by rewrite big_add1 divn0 big1. apply: (@addnI (d %| 0)); rewrite -(@big_ltn _ 0 _ 0 _ (dvdn d)) // big_mkord. rewrite (partition_big (fun i : 'I_n.+1 => inord (i %/ d)) 'I_(n %/ d).+1) //=. rewrite dvdn0 add1n -[_.+1 in LHS]card_ord -sum1_card. apply: eq_bigr => [[q ?] _]. rewrite (bigD1 (inord (q * d))) /eq_op /= !inordK ?ltnS -?leq_divRL ?mulnK //. rewrite dvdn_mull ?big1 // => [[i /= ?] /andP[/eqP <- /negPf]]. by rewrite eq_sym dvdn_eq inordK ?ltnS ?leq_div2r // => ->. Qed. Lemma logn_count_dvd p n : prime p -> logn p n = \sum_(1 <= k < n) (p ^ k %| n). Proof. rewrite big_add1 => p_prime; case: n => [|n]; first by rewrite logn0 big_geq. rewrite big_mkord -big_mkcond (eq_bigl _ _ (fun _ => pfactor_dvdn _ _ _)) //=. by rewrite big_ord_narrow ?sum1_card ?card_ord // -ltnS ltn_logl. Qed. (* Truncated real log. *) Definition trunc_log p n := let fix loop n k := if k is k'.+1 then if p <= n then (loop (n %/ p) k').+1 else 0 else 0 in if p <= 1 then 0 else loop n n. Lemma trunc_log0 p : trunc_log p 0 = 0. Proof. by case: p => [] // []. Qed. Lemma trunc_log1 p : trunc_log p 1 = 0. Proof. by case: p => [|[]]. Qed. Lemma trunc_log_bounds p n : 1 < p -> 0 < n -> let k := trunc_log p n in p ^ k <= n < p ^ k.+1. Proof. rewrite {+}/trunc_log => p_gt1; have p_gt0 := ltnW p_gt1. rewrite [p <= 1]leqNgt p_gt1 /=. set loop := (loop in loop n n); set m := n; rewrite [in n in loop m n]/m. have: m <= n by []; elim: n m => [|n IHn] [|m] //= /ltnSE-le_m_n _. have [le_p_n | // ] := leqP p _; rewrite 2!expnSr -leq_divRL -?ltn_divLR //. by apply: IHn; rewrite ?divn_gt0 // -ltnS (leq_trans (ltn_Pdiv _ _)). Qed. Lemma trunc_logP p n : 1 < p -> 0 < n -> p ^ trunc_log p n <= n. Proof. by move=> p_gt1 /(trunc_log_bounds p_gt1)/andP[]. Qed. Lemma trunc_log_ltn p n : 1 < p -> n < p ^ (trunc_log p n).+1. Proof. have [-> | n_gt0] := posnP n; first by rewrite trunc_log0 => /ltnW. by case/trunc_log_bounds/(_ n_gt0)/andP. Qed. Lemma trunc_log_max p k j : 1 < p -> p ^ j <= k -> j <= trunc_log p k. Proof. move=> p_gt1 le_pj_k; rewrite -ltnS -(@ltn_exp2l p) //. exact: leq_ltn_trans (trunc_log_ltn _ _). Qed. Lemma trunc_log_eq0 p n : (trunc_log p n == 0) = (p <= 1) || (n <= p.-1). Proof. case: p => [|[|p]]; case: n => // n; rewrite /= ltnS. have /= /andP[] := trunc_log_bounds (isT : 1 < p.+2) (isT : 0 < n.+1). case: trunc_log => [//|k] b1 b2. apply/idP/idP => [/eqP sk0 | nlep]; first by move: b2; rewrite sk0. symmetry; rewrite -[_ == _]/false /is_true -b1; apply/negbTE; rewrite -ltnNge. move: nlep; rewrite -ltnS => nlep; apply: (leq_ltn_trans nlep). by rewrite -[leqLHS]expn1; apply: leq_pexp2l. Qed. Lemma trunc_log_gt0 p n : (0 < trunc_log p n) = (1 < p) && (p.-1 < n). Proof. by rewrite ltnNge leqn0 trunc_log_eq0 negb_or -!ltnNge. Qed. Lemma trunc_log0n n : trunc_log 0 n = 0. Proof. by []. Qed. Lemma trunc_log1n n : trunc_log 1 n = 0. Proof. by []. Qed. Lemma leq_trunc_log p m n : m <= n -> trunc_log p m <= trunc_log p n. Proof. move=> mlen; case: p => [|[|p]]; rewrite ?trunc_log0n ?trunc_log1n //. case: m mlen => [|m] mlen; first by rewrite trunc_log0. apply/trunc_log_max => //; apply: leq_trans mlen; exact: trunc_logP. Qed. Lemma trunc_log_eq p n k : 1 < p -> p ^ n <= k < p ^ n.+1 -> trunc_log p k = n. Proof. move=> p_gt1 /andP[npLk kLpn]; apply/anti_leq. rewrite trunc_log_max// andbT -ltnS -(ltn_exp2l _ _ p_gt1). apply: leq_ltn_trans kLpn; apply: trunc_logP => //. by apply: leq_trans npLk; rewrite expn_gt0 ltnW. Qed. Lemma trunc_lognn p : 1 < p -> trunc_log p p = 1. Proof. by case: p => [|[|p]] // _; rewrite /trunc_log ltnSn divnn. Qed. Lemma trunc_expnK p n : 1 < p -> trunc_log p (p ^ n) = n. Proof. by move=> ?; apply: trunc_log_eq; rewrite // leqnn ltn_exp2l /=. Qed. Lemma trunc_logMp p n : 1 < p -> 0 < n -> trunc_log p (p * n) = (trunc_log p n).+1. Proof. case: p => [//|p] => p_gt0 n_gt0; apply: trunc_log_eq => //. rewrite expnS leq_pmul2l// trunc_logP//=. by rewrite expnS ltn_pmul2l// trunc_log_ltn. Qed. Lemma trunc_log2_double n : 0 < n -> trunc_log 2 n.*2 = (trunc_log 2 n).+1. Proof. by move=> n_gt0; rewrite -mul2n trunc_logMp. Qed. Lemma trunc_log2S n : 1 < n -> trunc_log 2 n = (trunc_log 2 n./2).+1. Proof. move=> n_gt1. rewrite -trunc_log2_double ?half_gt0//. rewrite -[n in LHS]odd_double_half. case: odd => //; rewrite add1n. apply: trunc_log_eq => //. rewrite leqW ?trunc_logP //= ?double_gt0 ?half_gt0//. rewrite trunc_log2_double ?half_gt0// expnS. by rewrite -doubleS mul2n leq_double trunc_log_ltn. Qed. (* Truncated up real logarithm *) Definition up_log p n := if (p <= 1) then 0 else let v := trunc_log p n in if n <= p ^ v then v else v.+1. Lemma up_log0 p : up_log p 0 = 0. Proof. by case: p => // [] []. Qed. Lemma up_log1 p : up_log p 1 = 0. Proof. by case: p => // [] []. Qed. Lemma up_log_eq0 p n : (up_log p n == 0) = (p <= 1) || (n <= 1). Proof. case: p => // [] [] // p. case: n => [|[|n]]; rewrite /up_log //=. have /= := trunc_log_bounds (isT : 1 < p.+2) (isT : 0 < n.+2). by case: (leqP _ n.+1); case: trunc_log. Qed. Lemma up_log_gt0 p n : (0 < up_log p n) = (1 < p) && (1 < n). Proof. by rewrite ltnNge leqn0 up_log_eq0 negb_or -!ltnNge. Qed. Lemma up_log_bounds p n : 1 < p -> 1 < n -> let k := up_log p n in p ^ k.-1 < n <= p ^ k. Proof. move=> p_gt1 n_gt1. have n_gt0 : 0 < n by apply: leq_trans n_gt1. rewrite /up_log (leqNgt p 1) p_gt1 /=. have /= /andP[tpLn nLtpS] := trunc_log_bounds p_gt1 n_gt0. have [nLnp|npLn] := leqP n (p ^ trunc_log p n); last by rewrite npLn ltnW. rewrite nLnp (leq_trans _ tpLn) // ltn_exp2l // prednK ?leqnn //. by case: trunc_log (leq_trans n_gt1 nLnp). Qed. Lemma up_logP p n : 1 < p -> n <= p ^ up_log p n. Proof. case: n => [|[|n]] // p_gt1; first by rewrite up_log1. by have /andP[] := up_log_bounds p_gt1 (isT: 1 < n.+2). Qed. Lemma up_log_gtn p n : 1 < p -> 1 < n -> p ^ (up_log p n).-1 < n. Proof. by case: n => [|[|n]] p_gt1 n_gt1 //; have /andP[] := up_log_bounds p_gt1 n_gt1. Qed. Lemma up_log_min p k j : 1 < p -> k <= p ^ j -> up_log p k <= j. Proof. case: k => [|[|k]] // p_gt1 kLj; rewrite ?(up_log0, up_log1) //. rewrite -[up_log _ _]prednK ?up_log_gt0 ?p_gt1 // -(@ltn_exp2l p) //. by apply: leq_trans (up_log_gtn p_gt1 (isT : 1 < k.+2)) _. Qed. Lemma leq_up_log p m n : m <= n -> up_log p m <= up_log p n. Proof. move=> mLn; case: p => [|[|p]] //. by apply/up_log_min => //; apply: leq_trans mLn (up_logP _ _). Qed. Lemma up_log_eq p n k : 1 < p -> p ^ n < k <= p ^ n.+1 -> up_log p k = n.+1. Proof. move=> p_gt1 /andP[npLk kLpn]; apply/eqP; rewrite eqn_leq. apply/andP; split; first by apply: up_log_min. rewrite -(ltn_exp2l _ _ p_gt1) //. by apply: leq_trans npLk (up_logP _ _). Qed. Lemma up_lognn p : 1 < p -> up_log p p = 1. Proof. by move=> p_gt1; apply: up_log_eq; rewrite p_gt1 /=. Qed. Lemma up_expnK p n : 1 < p -> up_log p (p ^ n) = n. Proof. case: n => [|n] p_gt1 /=; first by rewrite up_log1. by apply: up_log_eq; rewrite // leqnn andbT ltn_exp2l. Qed. Lemma up_logMp p n : 1 < p -> 0 < n -> up_log p (p * n) = (up_log p n).+1. Proof. case: p => [//|p] p_gt0. case: n => [//|[|n]] _; first by rewrite muln1 up_lognn// up_log1. apply: up_log_eq => //. rewrite expnS leq_pmul2l// up_logP// andbT. rewrite -[up_log _ _]prednK ?up_log_gt0 ?p_gt0 //. by rewrite expnS ltn_pmul2l// up_log_gtn. Qed. Lemma up_log2_double n : 0 < n -> up_log 2 n.*2 = (up_log 2 n).+1. Proof. by move=> n_gt0; rewrite -mul2n up_logMp. Qed. Lemma up_log2S n : 0 < n -> up_log 2 n.+1 = (up_log 2 (n./2.+1)).+1. Proof. case: n=> // [] [|n] // _. apply: up_log_eq => //; apply/andP; split. apply: leq_trans (_ : n./2.+1.*2 < n.+3); last first. by rewrite doubleS !ltnS -[leqRHS]odd_double_half leq_addl. have /= /andP[H1n _] := up_log_bounds (isT : 1 < 2) (isT : 1 < n./2.+2). by rewrite ltnS -leq_double -mul2n -expnS prednK ?up_log_gt0 // in H1n. rewrite -[_./2.+1]/(n./2.+2). have /= /andP[_ H2n] := up_log_bounds (isT : 1 < 2) (isT : 1 < n./2.+2). rewrite -leq_double -!mul2n -expnS in H2n. apply: leq_trans H2n. rewrite mul2n !doubleS !ltnS. by rewrite -[leqLHS]odd_double_half -add1n leq_add2r; case: odd. Qed. Lemma up_log_trunc_log p n : 1 < p -> 1 < n -> up_log p n = (trunc_log p n.-1).+1. Proof. move=> p_gt1 n_gt1; apply: up_log_eq => //. rewrite -[n]prednK ?ltnS -?pred_Sn ?[0 < n]ltnW//. by rewrite trunc_logP ?ltn_predRL// trunc_log_ltn. Qed. Lemma trunc_log_up_log p n : 1 < p -> 0 < n -> trunc_log p n = (up_log p n.+1).-1. Proof. by move=> ? ?; rewrite up_log_trunc_log. Qed. (* pi- parts *) (* Testing for membership in set of prime factors. *) Canonical nat_pred_pred := Eval hnf in [predType of nat_pred]. Coercion nat_pred_of_nat (p : nat) : nat_pred := pred1 p. Section NatPreds. Variables (n : nat) (pi : nat_pred). Definition negn : nat_pred := [predC pi]. Definition pnat : pred nat := fun m => (m > 0) && all [in pi] (primes m). Definition partn := \prod_(0 <= p < n.+1 | p \in pi) p ^ logn p n. End NatPreds. Notation "pi ^'" := (negn pi) : nat_scope. Notation "pi .-nat" := (pnat pi) : nat_scope. Notation "n `_ pi" := (partn n pi) : nat_scope. Section PnatTheory. Implicit Types (n p : nat) (pi rho : nat_pred). Lemma negnK pi : pi^'^' =i pi. Proof. by move=> p; apply: negbK. Qed. Lemma eq_negn pi1 pi2 : pi1 =i pi2 -> pi1^' =i pi2^'. Proof. by move=> eq_pi n; rewrite inE eq_pi. Qed. Lemma eq_piP m n : \pi(m) =i \pi(n) <-> \pi(m) = \pi(n). Proof. rewrite /pi_of; have eqs := irr_sorted_eq ltn_trans ltnn. by split=> [|-> //] /(eqs _ _ (sorted_primes m) (sorted_primes n)) ->. Qed. Lemma part_gt0 pi n : 0 < n`_pi. Proof. exact: prodn_gt0. Qed. Hint Resolve part_gt0 : core. Lemma sub_in_partn pi1 pi2 n : {in \pi(n), {subset pi1 <= pi2}} -> n`_pi1 %| n`_pi2. Proof. move=> pi12; rewrite ![n`__]big_mkcond /=. apply (big_ind2 (fun m1 m2 => m1 %| m2)) => // [*|p _]; first exact: dvdn_mul. rewrite lognE -mem_primes; case: ifP => pi1p; last exact: dvd1n. by case: ifP => pr_p; [rewrite pi12 | rewrite if_same]. Qed. Lemma eq_in_partn pi1 pi2 n : {in \pi(n), pi1 =i pi2} -> n`_pi1 = n`_pi2. Proof. by move=> pi12; apply/eqP; rewrite eqn_dvd ?sub_in_partn // => p /pi12->. Qed. Lemma eq_partn pi1 pi2 n : pi1 =i pi2 -> n`_pi1 = n`_pi2. Proof. by move=> pi12; apply: eq_in_partn => p _. Qed. Lemma partnNK pi n : n`_pi^'^' = n`_pi. Proof. by apply: eq_partn; apply: negnK. Qed. Lemma widen_partn m pi n : n <= m -> n`_pi = \prod_(0 <= p < m.+1 | p \in pi) p ^ logn p n. Proof. move=> le_n_m; rewrite big_mkcond /=. rewrite [n`_pi](big_nat_widen _ _ m.+1) // big_mkcond /=. apply: eq_bigr => p _; rewrite ltnS lognE. by case: and3P => [[_ n_gt0 p_dv_n]|]; rewrite ?if_same // andbC dvdn_leq. Qed. Lemma eq_partn_from_log m n (pi : nat_pred) : 0 < m -> 0 < n -> {in pi, logn^~ m =1 logn^~ n} -> m`_pi = n`_pi. Proof. move=> m0 n0 eq_log; rewrite !(@widen_partn (maxn m n)) ?leq_maxl ?leq_maxr//. by apply: eq_bigr => p /eq_log ->. Qed. Lemma partn0 pi : 0`_pi = 1. Proof. by apply: big1_seq => [] [|n]; rewrite andbC. Qed. Lemma partn1 pi : 1`_pi = 1. Proof. by apply: big1_seq => [] [|[|n]]; rewrite andbC. Qed. Lemma partnM pi m n : m > 0 -> n > 0 -> (m * n)`_pi = m`_pi * n`_pi. Proof. have le_pmul m' n': m' > 0 -> n' <= m' * n' by move/prednK <-; apply: leq_addr. move=> mpos npos; rewrite !(@widen_partn (n * m)) 3?(le_pmul, mulnC) //. rewrite !big_mkord -big_split; apply: eq_bigr => p _ /=. by rewrite lognM // expnD. Qed. Lemma partnX pi m n : (m ^ n)`_pi = m`_pi ^ n. Proof. elim: n => [|n IHn]; first exact: partn1. rewrite expnS; have [->|m_gt0] := posnP m; first by rewrite partn0 exp1n. by rewrite expnS partnM ?IHn // expn_gt0 m_gt0. Qed. Lemma partn_dvd pi m n : n > 0 -> m %| n -> m`_pi %| n`_pi. Proof. move=> n_gt0 dvmn; case/dvdnP: dvmn n_gt0 => q ->{n}. by rewrite muln_gt0 => /andP[q_gt0 m_gt0]; rewrite partnM ?dvdn_mull. Qed. Lemma p_part p n : n`_p = p ^ logn p n. Proof. case (posnP (logn p n)) => [log0 |]. by rewrite log0 [n`_p]big1_seq // => q /andP [/eqP ->]; rewrite log0. rewrite logn_gt0 mem_primes; case/and3P=> _ n_gt0 dv_p_n. have le_p_n: p < n.+1 by rewrite ltnS dvdn_leq. by rewrite [n`_p]big_mkord (big_pred1 (Ordinal le_p_n)). Qed. Lemma p_part_eq1 p n : (n`_p == 1) = (p \notin \pi(n)). Proof. rewrite mem_primes p_part lognE; case: and3P => // [[p_pr _ _]]. by rewrite -dvdn1 pfactor_dvdn // logn1. Qed. Lemma p_part_gt1 p n : (n`_p > 1) = (p \in \pi(n)). Proof. by rewrite ltn_neqAle part_gt0 andbT eq_sym p_part_eq1 negbK. Qed. Lemma primes_part pi n : primes n`_pi = filter [in pi] (primes n). Proof. have ltnT := ltn_trans; have [->|n_gt0] := posnP n; first by rewrite partn0. apply: (irr_sorted_eq ltnT ltnn); rewrite ?(sorted_primes, sorted_filter) //. move=> p; rewrite mem_filter /= !mem_primes n_gt0 part_gt0 /=. apply/andP/and3P=> [[p_pr] | [pi_p p_pr dv_p_n]]. rewrite /partn; apply big_ind => [|n1 n2 IHn1 IHn2|q pi_q]. - by rewrite dvdn1; case: eqP p_pr => // ->. - by rewrite Euclid_dvdM //; case/orP. rewrite -{1}(expn1 p) pfactor_dvdn // lognX muln_gt0. rewrite logn_gt0 mem_primes n_gt0 - andbA /=; case/and3P=> pr_q dv_q_n. by rewrite logn_prime //; case: eqP => // ->. have le_p_n: p < n.+1 by rewrite ltnS dvdn_leq. rewrite [n`_pi]big_mkord (bigD1 (Ordinal le_p_n)) //= dvdn_mulr //. by rewrite lognE p_pr n_gt0 dv_p_n expnS dvdn_mulr. Qed. Lemma filter_pi_of n m : n < m -> filter \pi(n) (index_iota 0 m) = primes n. Proof. move=> lt_n_m; have ltnT := ltn_trans; apply: (irr_sorted_eq ltnT ltnn). - by rewrite sorted_filter // iota_ltn_sorted. - exact: sorted_primes. move=> p; rewrite mem_filter mem_index_iota /= mem_primes; case: and3P => //. by case=> _ n_gt0 dv_p_n; apply: leq_ltn_trans lt_n_m; apply: dvdn_leq. Qed. Lemma partn_pi n : n > 0 -> n`_\pi(n) = n. Proof. move=> n_gt0; rewrite [RHS]prod_prime_decomp // prime_decompE big_map. by rewrite -[n`__]big_filter filter_pi_of. Qed. Lemma partnT n : n > 0 -> n`_predT = n. Proof. move=> n_gt0; rewrite -[RHS]partn_pi // [RHS]/partn big_mkcond /=. by apply: eq_bigr => p _; rewrite -logn_gt0; case: (logn p _). Qed. Lemma eqn_from_log m n : 0 < m -> 0 < n -> logn^~ m =1 logn^~ n -> m = n. Proof. by move=> ? ? /(@in1W _ predT)/eq_partn_from_log; rewrite !partnT// => ->. Qed. Lemma partnC pi n : n > 0 -> n`_pi * n`_pi^' = n. Proof. move=> n_gt0; rewrite -[RHS]partnT /partn //. do 2!rewrite mulnC big_mkcond /=; rewrite -big_split; apply: eq_bigr => p _ /=. by rewrite mulnC inE /=; case: (p \in pi); rewrite /= (muln1, mul1n). Qed. Lemma dvdn_part pi n : n`_pi %| n. Proof. by case: n => // n; rewrite -{2}[n.+1](@partnC pi) // dvdn_mulr. Qed. Lemma logn_part p m : logn p m`_p = logn p m. Proof. case p_pr: (prime p); first by rewrite p_part pfactorK. by rewrite lognE (lognE p m) p_pr. Qed. Lemma partn_lcm pi m n : m > 0 -> n > 0 -> (lcmn m n)`_pi = lcmn m`_pi n`_pi. Proof. move=> m_gt0 n_gt0; have p_gt0: lcmn m n > 0 by rewrite lcmn_gt0 m_gt0. apply/eqP; rewrite eqn_dvd dvdn_lcm !partn_dvd ?dvdn_lcml ?dvdn_lcmr //. rewrite -(dvdn_pmul2r (part_gt0 pi^' (lcmn m n))) partnC // dvdn_lcm !andbT. rewrite -[m in m %| _](partnC pi m_gt0) andbC -[n in n %| _](partnC pi n_gt0). by rewrite !dvdn_mul ?partn_dvd ?dvdn_lcml ?dvdn_lcmr. Qed. Lemma partn_gcd pi m n : m > 0 -> n > 0 -> (gcdn m n)`_pi = gcdn m`_pi n`_pi. Proof. move=> m_gt0 n_gt0; have p_gt0: gcdn m n > 0 by rewrite gcdn_gt0 m_gt0. apply/eqP; rewrite eqn_dvd dvdn_gcd !partn_dvd ?dvdn_gcdl ?dvdn_gcdr //=. rewrite -(dvdn_pmul2r (part_gt0 pi^' (gcdn m n))) partnC // dvdn_gcd. rewrite -[m in _ %| m](partnC pi m_gt0) andbC -[n in _%| n](partnC pi n_gt0). by rewrite !dvdn_mul ?partn_dvd ?dvdn_gcdl ?dvdn_gcdr. Qed. Lemma partn_biglcm (I : finType) (P : pred I) F pi : (forall i, P i -> F i > 0) -> (\big[lcmn/1%N]_(i | P i) F i)`_pi = \big[lcmn/1%N]_(i | P i) (F i)`_pi. Proof. move=> F_gt0; set m := \big[lcmn/1%N]_(i | P i) F i. have m_gt0: 0 < m by elim/big_ind: m => // p q p_gt0; rewrite lcmn_gt0 p_gt0. apply/eqP; rewrite eqn_dvd andbC; apply/andP; split. by apply/dvdn_biglcmP=> i Pi; rewrite partn_dvd // (@biglcmn_sup _ i). rewrite -(dvdn_pmul2r (part_gt0 pi^' m)) partnC //. apply/dvdn_biglcmP=> i Pi; rewrite -(partnC pi (F_gt0 i Pi)) dvdn_mul //. by rewrite (@biglcmn_sup _ i). by rewrite partn_dvd // (@biglcmn_sup _ i). Qed. Lemma partn_biggcd (I : finType) (P : pred I) F pi : #|SimplPred P| > 0 -> (forall i, P i -> F i > 0) -> (\big[gcdn/0]_(i | P i) F i)`_pi = \big[gcdn/0]_(i | P i) (F i)`_pi. Proof. move=> ntP F_gt0; set d := \big[gcdn/0]_(i | P i) F i. have d_gt0: 0 < d. case/card_gt0P: ntP => i /= Pi; have:= F_gt0 i Pi. rewrite !lt0n -!dvd0n; apply: contra => dv0d. by rewrite (dvdn_trans dv0d) // (@biggcdn_inf _ i). apply/eqP; rewrite eqn_dvd; apply/andP; split. by apply/dvdn_biggcdP=> i Pi; rewrite partn_dvd ?F_gt0 // (@biggcdn_inf _ i). rewrite -(dvdn_pmul2r (part_gt0 pi^' d)) partnC //. apply/dvdn_biggcdP=> i Pi; rewrite -(partnC pi (F_gt0 i Pi)) dvdn_mul //. by rewrite (@biggcdn_inf _ i). by rewrite partn_dvd ?F_gt0 // (@biggcdn_inf _ i). Qed. Lemma logn_gcd p m n : 0 < m -> 0 < n -> logn p (gcdn m n) = minn (logn p m) (logn p n). Proof. move=> m_gt0 n_gt0; case p_pr: (prime p); last by rewrite /logn p_pr. by apply: (@expnI p); rewrite ?prime_gt1// expn_min -!p_part partn_gcd. Qed. Lemma logn_lcm p m n : 0 < m -> 0 < n -> logn p (lcmn m n) = maxn (logn p m) (logn p n). Proof. move=> m_gt0 n_gt0; rewrite /lcmn logn_div ?dvdn_mull ?dvdn_gcdr//. by rewrite lognM// logn_gcd// -addn_min_max addnC addnK. Qed. Lemma sub_in_pnat pi rho n : {in \pi(n), {subset pi <= rho}} -> pi.-nat n -> rho.-nat n. Proof. rewrite /pnat => subpi /andP[-> pi_n]. by apply/allP=> p pr_p; apply: subpi => //; apply: (allP pi_n). Qed. Lemma eq_in_pnat pi rho n : {in \pi(n), pi =i rho} -> pi.-nat n = rho.-nat n. Proof. by move=> eqpi; apply/idP/idP; apply: sub_in_pnat => p /eqpi->. Qed. Lemma eq_pnat pi rho n : pi =i rho -> pi.-nat n = rho.-nat n. Proof. by move=> eqpi; apply: eq_in_pnat => p _. Qed. Lemma pnatNK pi n : pi^'^'.-nat n = pi.-nat n. Proof. exact: eq_pnat (negnK pi). Qed. Lemma pnatI pi rho n : [predI pi & rho].-nat n = pi.-nat n && rho.-nat n. Proof. by rewrite /pnat andbCA all_predI !andbA andbb. Qed. Lemma pnatM pi m n : pi.-nat (m * n) = pi.-nat m && pi.-nat n. Proof. rewrite /pnat muln_gt0 andbCA -andbA andbCA. case: posnP => // n_gt0; case: posnP => //= m_gt0. apply/allP/andP=> [pi_mn | [pi_m pi_n] p]. by split; apply/allP=> p m_p; apply: pi_mn; rewrite primesM // m_p ?orbT. by rewrite primesM // => /orP[]; [apply: (allP pi_m) | apply: (allP pi_n)]. Qed. Lemma pnatX pi m n : pi.-nat (m ^ n) = pi.-nat m || (n == 0). Proof. by case: n => [|n]; rewrite orbC // /pnat expn_gt0 orbC primesX. Qed. Lemma part_pnat pi n : pi.-nat n`_pi. Proof. rewrite /pnat primes_part part_gt0. by apply/allP=> p; rewrite mem_filter => /andP[]. Qed. Lemma pnatE pi p : prime p -> pi.-nat p = (p \in pi). Proof. by move=> pr_p; rewrite /pnat prime_gt0 ?primes_prime //= andbT. Qed. Lemma pnat_id p : prime p -> p.-nat p. Proof. by move=> pr_p; rewrite pnatE ?inE /=. Qed. Lemma coprime_pi' m n : m > 0 -> n > 0 -> coprime m n = \pi(m)^'.-nat n. Proof. by move=> m_gt0 n_gt0; rewrite /pnat n_gt0 all_predC coprime_has_primes. Qed. Lemma pnat_pi n : n > 0 -> \pi(n).-nat n. Proof. by rewrite /pnat => ->; apply/allP. Qed. Lemma pi_of_dvd m n : m %| n -> n > 0 -> {subset \pi(m) <= \pi(n)}. Proof. move=> m_dv_n n_gt0 p; rewrite !mem_primes n_gt0 => /and3P[-> _ p_dv_m]. exact: dvdn_trans p_dv_m m_dv_n. Qed. Lemma pi_ofM m n : m > 0 -> n > 0 -> \pi(m * n) =i [predU \pi(m) & \pi(n)]. Proof. by move=> m_gt0 n_gt0 p; apply: primesM. Qed. Lemma pi_of_part pi n : n > 0 -> \pi(n`_pi) =i [predI \pi(n) & pi]. Proof. by move=> n_gt0 p; rewrite /pi_of primes_part mem_filter andbC. Qed. Lemma pi_of_exp p n : n > 0 -> \pi(p ^ n) = \pi(p). Proof. by move=> n_gt0; rewrite /pi_of primesX. Qed. Lemma pi_of_prime p : prime p -> \pi(p) =i (p : nat_pred). Proof. by move=> pr_p q; rewrite /pi_of primes_prime // mem_seq1. Qed. Lemma p'natEpi p n : n > 0 -> p^'.-nat n = (p \notin \pi(n)). Proof. by case: n => // n _; rewrite /pnat all_predC has_pred1. Qed. Lemma p'natE p n : prime p -> p^'.-nat n = ~~ (p %| n). Proof. case: n => [|n] p_pr; first by case: p p_pr. by rewrite p'natEpi // mem_primes p_pr. Qed. Lemma pnatPpi pi n p : pi.-nat n -> p \in \pi(n) -> p \in pi. Proof. by case/andP=> _ /allP; apply. Qed. Lemma pnat_dvd m n pi : m %| n -> pi.-nat n -> pi.-nat m. Proof. by case/dvdnP=> q ->; rewrite pnatM; case/andP. Qed. Lemma pnat_div m n pi : m %| n -> pi.-nat n -> pi.-nat (n %/ m). Proof. case/dvdnP=> q ->; rewrite pnatM andbC => /andP[]. by case: m => // m _; rewrite mulnK. Qed. Lemma pnat_coprime pi m n : pi.-nat m -> pi^'.-nat n -> coprime m n. Proof. case/andP=> m_gt0 pi_m /andP[n_gt0 pi'_n]; rewrite coprime_has_primes //. by apply/hasPn=> p /(allP pi'_n); apply/contra/allP. Qed. Lemma p'nat_coprime pi m n : pi^'.-nat m -> pi.-nat n -> coprime m n. Proof. by move=> pi'm pi_n; rewrite (pnat_coprime pi'm) ?pnatNK. Qed. Lemma sub_pnat_coprime pi rho m n : {subset rho <= pi^'} -> pi.-nat m -> rho.-nat n -> coprime m n. Proof. by move=> pi'rho pi_m /(sub_in_pnat (in1W pi'rho)); apply: pnat_coprime. Qed. Lemma coprime_partC pi m n : coprime m`_pi n`_pi^'. Proof. by apply: (@pnat_coprime pi); apply: part_pnat. Qed. Lemma pnat_1 pi n : pi.-nat n -> pi^'.-nat n -> n = 1. Proof. by move=> pi_n pi'_n; rewrite -(eqnP (pnat_coprime pi_n pi'_n)) gcdnn. Qed. Lemma part_pnat_id pi n : pi.-nat n -> n`_pi = n. Proof. case/andP=> n_gt0 pi_n; rewrite -[RHS]partnT // /partn big_mkcond /=. apply: eq_bigr=> p _; have [->|] := posnP (logn p n); first by rewrite if_same. by rewrite logn_gt0 => /(allP pi_n)/= ->. Qed. Lemma part_p'nat pi n : pi^'.-nat n -> n`_pi = 1. Proof. case/andP=> n_gt0 pi'_n; apply: big1_seq => p /andP[pi_p _]. by have [-> //|] := posnP (logn p n); rewrite logn_gt0; case/(allP pi'_n)/negP. Qed. Lemma partn_eq1 pi n : n > 0 -> (n`_pi == 1) = pi^'.-nat n. Proof. move=> n_gt0; apply/eqP/idP=> [pi_n_1|]; last exact: part_p'nat. by rewrite -(partnC pi n_gt0) pi_n_1 mul1n part_pnat. Qed. Lemma pnatP pi n : n > 0 -> reflect (forall p, prime p -> p %| n -> p \in pi) (pi.-nat n). Proof. move=> n_gt0; rewrite /pnat n_gt0. apply: (iffP allP) => /= pi_n p => [pr_p p_n|]. by rewrite pi_n // mem_primes pr_p n_gt0. by rewrite mem_primes n_gt0 /=; case/andP; move: p. Qed. Lemma pi_pnat pi p n : p.-nat n -> p \in pi -> pi.-nat n. Proof. move=> p_n pi_p; have [n_gt0 _] := andP p_n. by apply/pnatP=> // q q_pr /(pnatP _ n_gt0 p_n _ q_pr)/eqnP->. Qed. Lemma p_natP p n : p.-nat n -> {k | n = p ^ k}. Proof. by move=> p_n; exists (logn p n); rewrite -p_part part_pnat_id. Qed. Lemma pi'_p'nat pi p n : pi^'.-nat n -> p \in pi -> p^'.-nat n. Proof. by move=> pi'n pi_p; apply: sub_in_pnat pi'n => q _; apply: contraNneq => ->. Qed. Lemma pi_p'nat p pi n : pi.-nat n -> p \in pi^' -> p^'.-nat n. Proof. by move=> pi_n; apply: pi'_p'nat; rewrite pnatNK. Qed. Lemma partn_part pi rho n : {subset pi <= rho} -> n`_rho`_pi = n`_pi. Proof. move=> pi_sub_rho; have [->|n_gt0] := posnP n; first by rewrite !partn0 partn1. rewrite -[in RHS](partnC rho n_gt0) partnM //. suffices: pi^'.-nat n`_rho^' by move/part_p'nat->; rewrite muln1. by apply: sub_in_pnat (part_pnat _ _) => q _; apply/contra/pi_sub_rho. Qed. Lemma partnI pi rho n : n`_[predI pi & rho] = n`_pi`_rho. Proof. rewrite -(@partnC [predI pi & rho] _`_rho) //. symmetry; rewrite 2?partn_part; try by move=> p /andP []. rewrite mulnC part_p'nat ?mul1n // pnatNK pnatI part_pnat andbT. exact: pnat_dvd (dvdn_part _ _) (part_pnat _ _). Qed. Lemma odd_2'nat n : odd n = 2^'.-nat n. Proof. by case: n => // n; rewrite p'natE // dvdn2 negbK. Qed. End PnatTheory. #[global] Hint Resolve part_gt0 : core. (************************************) (* Properties of the divisors list. *) (************************************) Lemma divisors_correct n : n > 0 -> [/\ uniq (divisors n), sorted leq (divisors n) & forall d, (d \in divisors n) = (d %| n)]. Proof. move/prod_prime_decomp=> def_n; rewrite {4}def_n {def_n}. have: all prime (primes n) by apply/allP=> p; rewrite mem_primes; case/andP. have:= primes_uniq n; rewrite /primes /divisors; move/prime_decomp: n. elim=> [|[p e] pd] /=; first by split=> // d; rewrite big_nil dvdn1 mem_seq1. rewrite big_cons /=; move: (foldr _ _ pd) => divs. move=> IHpd /andP[npd_p Upd] /andP[pr_p pr_pd]. have lt0p: 0 < p by apply: prime_gt0. have {IHpd Upd}[Udivs Odivs mem_divs] := IHpd Upd pr_pd. have ndivs_p m: p * m \notin divs. suffices: p \notin divs; rewrite !mem_divs. by apply: contra => /dvdnP[n ->]; rewrite mulnCA dvdn_mulr. have ndv_p_1: ~~(p %| 1) by rewrite dvdn1 neq_ltn orbC prime_gt1. rewrite big_seq; elim/big_ind: _ => [//|u v npu npv|[q f] /= pd_qf]. by rewrite Euclid_dvdM //; apply/norP. elim: (f) => // f'; rewrite expnS Euclid_dvdM // orbC negb_or => -> {f'}/=. have pd_q: q \in unzip1 pd by apply/mapP; exists (q, f). by apply: contra npd_p; rewrite dvdn_prime2 // ?(allP pr_pd) // => /eqP->. elim: e => [|e] /=; first by split=> // d; rewrite mul1n. have Tmulp_inj: injective (NatTrec.mul p). by move=> u v /eqP; rewrite !natTrecE eqn_pmul2l // => /eqP. move: (iter e _ _) => divs' [Udivs' Odivs' mem_divs']; split=> [||d]. - rewrite merge_uniq cat_uniq map_inj_uniq // Udivs Udivs' andbT /=. apply/hasP=> [[d dv_d /mapP[d' _ def_d]]]. by case/idPn: dv_d; rewrite def_d natTrecE. - rewrite (merge_sorted leq_total) //; case: (divs') Odivs' => //= d ds. rewrite (@map_path _ _ _ _ leq xpred0) ?has_pred0 // => u v _. by rewrite !natTrecE leq_pmul2l. rewrite mem_merge mem_cat; case dv_d_p: (p %| d). case/dvdnP: dv_d_p => d' ->{d}; rewrite mulnC (negbTE (ndivs_p d')) orbF. rewrite expnS -mulnA dvdn_pmul2l // -mem_divs'. by rewrite -(mem_map Tmulp_inj divs') natTrecE. case pdiv_d: (_ \in _). by case/mapP: pdiv_d dv_d_p => d' _ ->; rewrite natTrecE dvdn_mulr. rewrite mem_divs Gauss_dvdr // coprime_sym. by rewrite coprimeXl ?prime_coprime ?dv_d_p. Qed. Lemma sorted_divisors n : sorted leq (divisors n). Proof. by case: (posnP n) => [-> | /divisors_correct[]]. Qed. Lemma divisors_uniq n : uniq (divisors n). Proof. by case: (posnP n) => [-> | /divisors_correct[]]. Qed. Lemma sorted_divisors_ltn n : sorted ltn (divisors n). Proof. by rewrite ltn_sorted_uniq_leq divisors_uniq sorted_divisors. Qed. Lemma dvdn_divisors d m : 0 < m -> (d %| m) = (d \in divisors m). Proof. by case/divisors_correct. Qed. Lemma divisor1 n : 1 \in divisors n. Proof. by case: n => // n; rewrite -dvdn_divisors // dvd1n. Qed. Lemma divisors_id n : 0 < n -> n \in divisors n. Proof. by move/dvdn_divisors <-. Qed. (* Big sum / product lemmas*) Lemma dvdn_sum d I r (K : pred I) F : (forall i, K i -> d %| F i) -> d %| \sum_(i <- r | K i) F i. Proof. by move=> dF; elim/big_ind: _ => //; apply: dvdn_add. Qed. Lemma dvdn_partP n m : 0 < n -> reflect (forall p, p \in \pi(n) -> n`_p %| m) (n %| m). Proof. move=> n_gt0; apply: (iffP idP) => n_dvd_m => [p _|]. by apply: dvdn_trans n_dvd_m; apply: dvdn_part. have [-> // | m_gt0] := posnP m. rewrite -(partnT n_gt0) -(partnT m_gt0). rewrite !(@widen_partn (m + n)) ?leq_addl ?leq_addr // /in_mem /=. elim/big_ind2: _ => // [* | q _]; first exact: dvdn_mul. have [-> // | ] := posnP (logn q n); rewrite logn_gt0 => q_n. have pr_q: prime q by move: q_n; rewrite mem_primes; case/andP. by have:= n_dvd_m q q_n; rewrite p_part !pfactor_dvdn // pfactorK. Qed. Lemma modn_partP n a b : 0 < n -> reflect (forall p : nat, p \in \pi(n) -> a = b %[mod n`_p]) (a == b %[mod n]). Proof. move=> n_gt0; wlog le_b_a: a b / b <= a. move=> IH; case: (leqP b a) => [|/ltnW] /IH {IH}// IH. by rewrite eq_sym; apply: (iffP IH) => eqab p /eqab. rewrite eqn_mod_dvd //; apply: (iffP (dvdn_partP _ n_gt0)) => eqab p /eqab; by rewrite -eqn_mod_dvd // => /eqP. Qed. (* The Euler totient function *) Lemma totientE n : n > 0 -> totient n = \prod_(p <- primes n) (p.-1 * p ^ (logn p n).-1). Proof. move=> n_gt0; rewrite /totient n_gt0 prime_decompE unlock. by elim: (primes n) => //= [p pr ->]; rewrite !natTrecE. Qed. Lemma totient_gt0 n : (0 < totient n) = (0 < n). Proof. case: n => // n; rewrite totientE // big_seq_cond prodn_cond_gt0 // => p. by rewrite mem_primes muln_gt0 expn_gt0; case: p => [|[|]]. Qed. Lemma totient_pfactor p e : prime p -> e > 0 -> totient (p ^ e) = p.-1 * p ^ e.-1. Proof. move=> p_pr e_gt0; rewrite totientE ?expn_gt0 ?prime_gt0 //. by rewrite primesX // primes_prime // unlock /= muln1 pfactorK. Qed. Lemma totient_prime p : prime p -> totient p = p.-1. Proof. by move=> p_prime; rewrite -{1}[p]expn1 totient_pfactor // muln1. Qed. Lemma totient_coprime m n : coprime m n -> totient (m * n) = totient m * totient n. Proof. move=> co_mn; have [-> //| m_gt0] := posnP m. have [->|n_gt0] := posnP n; first by rewrite !muln0. rewrite !totientE ?muln_gt0 ?m_gt0 //. have /(perm_big _)->: perm_eq (primes (m * n)) (primes m ++ primes n). apply: uniq_perm => [||p]; first exact: primes_uniq. by rewrite cat_uniq !primes_uniq -coprime_has_primes // co_mn. by rewrite mem_cat primesM. rewrite big_cat /= !big_seq. congr (_ * _); apply: eq_bigr => p; rewrite mem_primes => /and3P[_ _ dvp]. rewrite (mulnC m) logn_Gauss //; move: co_mn. by rewrite -(divnK dvp) coprimeMl => /andP[]. rewrite logn_Gauss //; move: co_mn. by rewrite coprime_sym -(divnK dvp) coprimeMl => /andP[]. Qed. Lemma totient_count_coprime n : totient n = \sum_(0 <= d < n) coprime n d. Proof. elim/ltn_ind: n => // n IHn. case: (leqP n 1) => [|lt1n]; first by rewrite unlock; case: (n) => [|[]]. pose p := pdiv n; have p_pr: prime p by apply: pdiv_prime. have p1 := prime_gt1 p_pr; have p0 := ltnW p1. pose np := n`_p; pose np' := n`_p^'. have co_npp': coprime np np' by rewrite coprime_partC. have [n0 np0 np'0]: [/\ n > 0, np > 0 & np' > 0] by rewrite ltnW ?part_gt0. have def_n: n = np * np' by rewrite partnC. have lnp0: 0 < logn p n by rewrite lognE p_pr n0 pdiv_dvd. pose in_mod k (k0 : k > 0) d := Ordinal (ltn_pmod d k0). rewrite {1}def_n totient_coprime // {IHn}(IHn np') ?big_mkord; last first. by rewrite def_n ltn_Pmull // /np p_part -(expn0 p) ltn_exp2l. have ->: totient np = #|[pred d : 'I_np | coprime np d]|. rewrite [np in LHS]p_part totient_pfactor //=; set q := p ^ _. apply: (@addnI (1 * q)); rewrite -mulnDl [1 + _]prednK // mul1n. have def_np: np = p * q by rewrite -expnS prednK // -p_part. pose mulp := [fun d : 'I_q => in_mod _ np0 (p * d)]. rewrite -def_np -{1}[np]card_ord -(cardC [in codom mulp]). rewrite card_in_image => [|[d1 ltd1] [d2 ltd2] /= _ _ []]; last first. move/eqP; rewrite def_np -!muln_modr ?modn_small //. by rewrite eqn_pmul2l // => eq_op12; apply/eqP. rewrite card_ord; congr (q + _); apply: eq_card => d /=. rewrite !inE [np in coprime np _]p_part coprime_pexpl ?prime_coprime //. congr (~~ _); apply/codomP/idP=> [[d' -> /=] | /dvdnP[r def_d]]. by rewrite def_np -muln_modr // dvdn_mulr. do [rewrite mulnC; case: d => d ltd /=] in def_d *. have ltr: r < q by rewrite -(ltn_pmul2l p0) -def_np -def_d. by exists (Ordinal ltr); apply: val_inj; rewrite /= -def_d modn_small. pose h (d : 'I_n) := (in_mod _ np0 d, in_mod _ np'0 d). pose h' (d : 'I_np * 'I_np') := in_mod _ n0 (chinese np np' d.1 d.2). rewrite -!big_mkcond -sum_nat_const pair_big (reindex_onto h h') => [|[d d'] _]. apply: eq_bigl => [[d ltd] /=]; rewrite !inE -val_eqE /= andbC !coprime_modr. by rewrite def_n -chinese_mod // -coprimeMl -def_n modn_small ?eqxx. apply/eqP; rewrite /eq_op /= /eq_op /= !modn_dvdm ?dvdn_part //. by rewrite chinese_modl // chinese_modr // !modn_small ?eqxx ?ltn_ord. Qed. Lemma totient_gt1 n : (totient n > 1) = (n > 2). Proof. case: n => [|[|[|[|n']]]]//=; set n := n'.+4; rewrite [RHS]isT. wlog [q] : / exists k, k.+3 \in primes n; last first. rewrite mem_primes => /and3P[qp ngt0 qn]. have [[|k]// cqk ->] := pfactor_coprime qp ngt0. rewrite totient_coprime 1?coprime_sym ?coprimeXl//. rewrite totient_pfactor// -?pfactor_dvdn// mulnCA/= (@leq_trans q.+2)//. by rewrite leq_pmulr// muln_gt0 totient_gt0 expn_gt0. have := @prod_prime_decomp n isT; rewrite prime_decompE big_map/=. case: (primes n) (all_prime_primes n) (sorted_primes n) => [|[|[|p']]// [|[|[|[|q']]] r]]//=; first by rewrite big_nil. case: p' => [_ _|p' _ _ _]; last by apply; exists p'; rewrite ?mem_head. rewrite big_seq1; case: logn => [|[|k]]//= ->. by rewrite totient_pfactor//= mul1n (@leq_pexp2l 2 1)//. by move=> _ _ _; apply; exists q'=> //; rewrite !in_cons eqxx orbT. Qed.
ssrbool.v
From mathcomp Require Import ssreflect ssrfun. From Corelib Require Export ssrbool. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. (**********************) (* not yet backported *) (**********************) Lemma homo_mono1 [aT rT : Type] [f : aT -> rT] [g : rT -> aT] [aP : pred aT] [rP : pred rT] : cancel g f -> {homo f : x / aP x >-> rP x} -> {homo g : x / rP x >-> aP x} -> {mono g : x / rP x >-> aP x}. Proof. by move=> gK fP gP x; apply/idP/idP => [/fP|/gP//]; rewrite gK. Qed. Lemma if_and b1 b2 T (x y : T) : (if b1 && b2 then x else y) = (if b1 then if b2 then x else y else y). Proof. by case: b1 b2 => [] []. Qed. Lemma if_or b1 b2 T (x y : T) : (if b1 || b2 then x else y) = (if b1 then x else if b2 then x else y). Proof. by case: b1 b2 => [] []. Qed. Lemma if_implyb b1 b2 T (x y : T) : (if b1 ==> b2 then x else y) = (if b1 then if b2 then x else y else x). Proof. by case: b1 b2 => [] []. Qed. Lemma if_implybC b1 b2 T (x y : T) : (if b1 ==> b2 then x else y) = (if b2 then x else if b1 then y else x). Proof. by case: b1 b2 => [] []. Qed. Lemma if_add b1 b2 T (x y : T) : (if b1 (+) b2 then x else y) = (if b1 then if b2 then y else x else if b2 then x else y). Proof. by case: b1 b2 => [] []. Qed. Lemma relpre_trans {T' T : Type} {leT : rel T} {f : T' -> T} : transitive leT -> transitive (relpre f leT). Proof. by move=> + y x z; apply. Qed.
LinearGrowth.lean
/- Copyright (c) 2025 Damien Thomine. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damien Thomine -/ import Mathlib.Analysis.SpecificLimits.Basic /-! # Linear growth This file defines the linear growth of a sequence `u : ℕ → R`. This notion comes in two versions, using a `liminf` and a `limsup` respectively. Most properties are developed for `R = EReal`. ## Main definitions - `linearGrowthInf`, `linearGrowthSup`: respectively, `liminf` and `limsup` of `(u n) / n`. - `linearGrowthInfTopHom`, `linearGrowthSupBotHom`: the functions `linearGrowthInf`, `linearGrowthSup` as homomorphisms preserving finitary `Inf`/`Sup` respectively. ## TODO Generalize statements from `EReal` to `ENNReal` (or others). This may need additional typeclasses. Lemma about coercion from `ENNReal` to `EReal`. This needs additional lemmas about `ENNReal.toEReal`. -/ namespace LinearGrowth open EReal Filter Function open scoped Topology /-! ### Definition -/ section definition variable {R : Type*} [ConditionallyCompleteLattice R] [Div R] [NatCast R] /-- Lower linear growth of a sequence. -/ noncomputable def linearGrowthInf (u : ℕ → R) : R := liminf (fun n ↦ u n / n) atTop /-- Upper linear growth of a sequence. -/ noncomputable def linearGrowthSup (u : ℕ → R) : R := limsup (fun n ↦ u n / n) atTop end definition /-! ### Basic properties -/ section basic_properties variable {R : Type*} [ConditionallyCompleteLattice R] [Div R] [NatCast R] {u v : ℕ → R} lemma linearGrowthInf_congr (h : u =ᶠ[atTop] v) : linearGrowthInf u = linearGrowthInf v := liminf_congr (h.mono fun _ uv ↦ uv ▸ rfl) lemma linearGrowthSup_congr (h : u =ᶠ[atTop] v) : linearGrowthSup u = linearGrowthSup v := limsup_congr (h.mono fun _ uv ↦ uv ▸ rfl) lemma linearGrowthInf_le_linearGrowthSup (h : IsBoundedUnder (· ≤ ·) atTop fun n ↦ u n / n := by isBoundedDefault) (h' : IsBoundedUnder (· ≥ ·) atTop fun n ↦ u n / n := by isBoundedDefault) : linearGrowthInf u ≤ linearGrowthSup u := liminf_le_limsup h h' end basic_properties section basic_properties variable {u v : ℕ → EReal} {a b : EReal} lemma linearGrowthInf_eventually_monotone (h : u ≤ᶠ[atTop] v) : linearGrowthInf u ≤ linearGrowthInf v := liminf_le_liminf (h.mono fun n u_v ↦ EReal.monotone_div_right_of_nonneg n.cast_nonneg' u_v) lemma linearGrowthInf_monotone (h : u ≤ v) : linearGrowthInf u ≤ linearGrowthInf v := linearGrowthInf_eventually_monotone (Eventually.of_forall h) lemma linearGrowthSup_eventually_monotone (h : u ≤ᶠ[atTop] v) : linearGrowthSup u ≤ linearGrowthSup v := limsup_le_limsup (h.mono fun n u_v ↦ monotone_div_right_of_nonneg n.cast_nonneg' u_v) lemma linearGrowthSup_monotone (h : u ≤ v) : linearGrowthSup u ≤ linearGrowthSup v := linearGrowthSup_eventually_monotone (Eventually.of_forall h) lemma linearGrowthInf_le_linearGrowthSup_of_frequently_le (h : ∃ᶠ n in atTop, u n ≤ v n) : linearGrowthInf u ≤ linearGrowthSup v := (liminf_le_limsup_of_frequently_le) <| h.mono fun n u_v ↦ by gcongr lemma linearGrowthInf_le_iff : linearGrowthInf u ≤ a ↔ ∀ b > a, ∃ᶠ n : ℕ in atTop, u n ≤ b * n := by rw [linearGrowthInf, liminf_le_iff'] refine forall₂_congr fun b _ ↦ frequently_congr (eventually_atTop.2 ⟨1, fun n _ ↦ ?_⟩) rw [div_le_iff_le_mul (by norm_cast) (natCast_ne_top n), mul_comm _ b] lemma le_linearGrowthInf_iff : a ≤ linearGrowthInf u ↔ ∀ b < a, ∀ᶠ n : ℕ in atTop, b * n ≤ u n := by rw [linearGrowthInf, le_liminf_iff'] refine forall₂_congr fun b _ ↦ eventually_congr (eventually_atTop.2 ⟨1, fun n _ ↦ ?_⟩) nth_rw 1 [le_div_iff_mul_le (by norm_cast) (natCast_ne_top n)] lemma linearGrowthSup_le_iff : linearGrowthSup u ≤ a ↔ ∀ b > a, ∀ᶠ n : ℕ in atTop, u n ≤ b * n := by rw [linearGrowthSup, limsup_le_iff'] refine forall₂_congr fun b _ ↦ eventually_congr (eventually_atTop.2 ⟨1, fun n _ ↦ ?_⟩) rw [div_le_iff_le_mul (by norm_cast) (natCast_ne_top n), mul_comm _ b] lemma le_linearGrowthSup_iff : a ≤ linearGrowthSup u ↔ ∀ b < a, ∃ᶠ n : ℕ in atTop, b * n ≤ u n := by rw [linearGrowthSup, le_limsup_iff'] refine forall₂_congr fun b _ ↦ frequently_congr (eventually_atTop.2 ⟨1, fun n _ ↦ ?_⟩) nth_rw 1 [le_div_iff_mul_le (by norm_cast) (natCast_ne_top n)] /- Forward direction of `linearGrowthInf_le_iff`. -/ lemma frequently_le_mul (h : linearGrowthInf u < a) : ∃ᶠ n : ℕ in atTop, u n ≤ a * n := linearGrowthInf_le_iff.1 (le_refl (linearGrowthInf u)) a h /- Forward direction of `le_linearGrowthInf_iff`. -/ lemma eventually_mul_le (h : a < linearGrowthInf u) : ∀ᶠ n : ℕ in atTop, a * n ≤ u n := le_linearGrowthInf_iff.1 (le_refl (linearGrowthInf u)) a h /- Forward direction of `linearGrowthSup_le_iff`. -/ lemma eventually_le_mul (h : linearGrowthSup u < a) : ∀ᶠ n : ℕ in atTop, u n ≤ a * n := linearGrowthSup_le_iff.1 (le_refl (linearGrowthSup u)) a h /- Forward direction of `le_linearGrowthSup_iff`. -/ lemma frequently_mul_le (h : a < linearGrowthSup u) : ∃ᶠ n : ℕ in atTop, a * n ≤ u n := le_linearGrowthSup_iff.1 (le_refl (linearGrowthSup u)) a h lemma _root_.Frequently.linearGrowthInf_le (h : ∃ᶠ n : ℕ in atTop, u n ≤ a * n) : linearGrowthInf u ≤ a := linearGrowthInf_le_iff.2 fun c c_u ↦ h.mono fun n hn ↦ hn.trans <| by gcongr lemma _root_.Eventually.le_linearGrowthInf (h : ∀ᶠ n : ℕ in atTop, a * n ≤ u n) : a ≤ linearGrowthInf u := le_linearGrowthInf_iff.2 fun c c_u ↦ h.mono fun n hn ↦ hn.trans' <| by gcongr lemma _root_.Eventually.linearGrowthSup_le (h : ∀ᶠ n : ℕ in atTop, u n ≤ a * n) : linearGrowthSup u ≤ a:= linearGrowthSup_le_iff.2 fun c c_u ↦ h.mono fun n hn ↦ hn.trans <| by gcongr lemma _root_.Frequently.le_linearGrowthSup (h : ∃ᶠ n : ℕ in atTop, a * n ≤ u n) : a ≤ linearGrowthSup u := le_linearGrowthSup_iff.2 fun c c_u ↦ h.mono fun n hn ↦ hn.trans' <| by gcongr /-! ### Special cases -/ lemma linearGrowthSup_bot : linearGrowthSup (⊥ : ℕ → EReal) = (⊥ : EReal) := by nth_rw 2 [← limsup_const (f := atTop (α := ℕ)) ⊥] refine limsup_congr <| (eventually_gt_atTop 0).mono fun n n_pos ↦ ?_ exact bot_div_of_pos_ne_top (by positivity) (natCast_ne_top n) lemma linearGrowthInf_bot : linearGrowthInf (⊥ : ℕ → EReal) = (⊥ : EReal) := by apply le_bot_iff.1 rw [← linearGrowthSup_bot] exact linearGrowthInf_le_linearGrowthSup lemma linearGrowthInf_top : linearGrowthInf ⊤ = (⊤ : EReal) := by nth_rw 2 [← liminf_const (f := atTop (α := ℕ)) ⊤] refine liminf_congr (eventually_atTop.2 ?_) exact ⟨1, fun n n_pos ↦ top_div_of_pos_ne_top (Nat.cast_pos'.2 n_pos) (natCast_ne_top n)⟩ lemma linearGrowthSup_top : linearGrowthSup (⊤ : ℕ → EReal) = (⊤ : EReal) := by apply top_le_iff.1 rw [← linearGrowthInf_top] exact linearGrowthInf_le_linearGrowthSup lemma linearGrowthInf_const (h : b ≠ ⊥) (h' : b ≠ ⊤) : linearGrowthInf (fun _ ↦ b) = 0 := (tendsto_const_div_atTop_nhds_zero_nat h h').liminf_eq lemma linearGrowthSup_const (h : b ≠ ⊥) (h' : b ≠ ⊤) : linearGrowthSup (fun _ ↦ b) = 0 := (tendsto_const_div_atTop_nhds_zero_nat h h').limsup_eq lemma linearGrowthInf_zero : linearGrowthInf 0 = (0 : EReal) := linearGrowthInf_const zero_ne_bot zero_ne_top lemma linearGrowthSup_zero : linearGrowthSup 0 = (0 : EReal) := linearGrowthSup_const zero_ne_bot zero_ne_top lemma linearGrowthInf_const_mul_self : linearGrowthInf (fun n ↦ a * n) = a := le_antisymm (Frequently.linearGrowthInf_le (Frequently.of_forall fun _ ↦ le_refl _)) (Eventually.le_linearGrowthInf (Eventually.of_forall fun _ ↦ le_refl _)) lemma linearGrowthSup_const_mul_self : linearGrowthSup (fun n ↦ a * n) = a := le_antisymm (Eventually.linearGrowthSup_le (Eventually.of_forall fun _ ↦ le_refl _)) (Frequently.le_linearGrowthSup (Frequently.of_forall fun _ ↦ le_refl _)) lemma linearGrowthInf_natCast_nonneg (v : ℕ → ℕ) : 0 ≤ linearGrowthInf fun n ↦ (v n : EReal) := (le_liminf_of_le) (Eventually.of_forall fun n ↦ div_nonneg (v n).cast_nonneg' n.cast_nonneg') lemma tendsto_atTop_of_linearGrowthInf_pos (h : 0 < linearGrowthInf u) : Tendsto u atTop (𝓝 ⊤) := by obtain ⟨a, a_0, a_v⟩ := exists_between h apply tendsto_nhds_top_mono _ ((le_linearGrowthInf_iff (u := u)).1 (le_refl _) a a_v) refine tendsto_nhds_top_iff_real.2 fun M ↦ eventually_atTop.2 ?_ lift a to ℝ using ⟨ne_top_of_lt a_v, ne_bot_of_gt a_0⟩ rw [EReal.coe_pos] at a_0 obtain ⟨n, hn⟩ := exists_nat_ge (M / a) refine ⟨n + 1, fun k k_n ↦ ?_⟩ rw [← coe_coe_eq_natCast, ← coe_mul, EReal.coe_lt_coe_iff, mul_comm] exact (div_lt_iff₀ a_0).1 (hn.trans_lt (Nat.cast_lt.2 k_n)) /-! ### Addition and negation -/ lemma le_linearGrowthInf_add : linearGrowthInf u + linearGrowthInf v ≤ linearGrowthInf (u + v) := by refine le_liminf_add.trans_eq (liminf_congr (Eventually.of_forall fun n ↦ ?_)) rw [Pi.add_apply, Pi.add_apply, ← add_div_of_nonneg_right n.cast_nonneg'] /-- See `linearGrowthInf_add_le'` for a version with swapped argument `u` and `v`. -/ lemma linearGrowthInf_add_le (h : linearGrowthSup u ≠ ⊥ ∨ linearGrowthInf v ≠ ⊤) (h' : linearGrowthSup u ≠ ⊤ ∨ linearGrowthInf v ≠ ⊥) : linearGrowthInf (u + v) ≤ linearGrowthSup u + linearGrowthInf v := by refine (liminf_add_le h h').trans_eq' (liminf_congr (Eventually.of_forall fun n ↦ ?_)) rw [Pi.add_apply, Pi.add_apply, ← add_div_of_nonneg_right n.cast_nonneg'] /-- See `linearGrowthInf_add_le` for a version with swapped argument `u` and `v`. -/ lemma linearGrowthInf_add_le' (h : linearGrowthInf u ≠ ⊥ ∨ linearGrowthSup v ≠ ⊤) (h' : linearGrowthInf u ≠ ⊤ ∨ linearGrowthSup v ≠ ⊥) : linearGrowthInf (u + v) ≤ linearGrowthInf u + linearGrowthSup v := by rw [add_comm u v, add_comm (linearGrowthInf u) (linearGrowthSup v)] exact linearGrowthInf_add_le h'.symm h.symm /-- See `le_linearGrowthSup_add'` for a version with swapped argument `u` and `v`. -/ lemma le_linearGrowthSup_add : linearGrowthSup u + linearGrowthInf v ≤ linearGrowthSup (u + v) := by refine le_limsup_add.trans_eq (limsup_congr (Eventually.of_forall fun n ↦ ?_)) rw [Pi.add_apply, Pi.add_apply, add_div_of_nonneg_right n.cast_nonneg'] /-- See `le_linearGrowthSup_add` for a version with swapped argument `u` and `v`. -/ lemma le_linearGrowthSup_add' : linearGrowthInf u + linearGrowthSup v ≤ linearGrowthSup (u + v) := by rw [add_comm u v, add_comm (linearGrowthInf u) (linearGrowthSup v)] exact le_linearGrowthSup_add lemma linearGrowthSup_add_le (h : linearGrowthSup u ≠ ⊥ ∨ linearGrowthSup v ≠ ⊤) (h' : linearGrowthSup u ≠ ⊤ ∨ linearGrowthSup v ≠ ⊥) : linearGrowthSup (u + v) ≤ linearGrowthSup u + linearGrowthSup v := by refine (limsup_add_le h h').trans_eq' (limsup_congr (Eventually.of_forall fun n ↦ ?_)) rw [Pi.add_apply, Pi.add_apply, add_div_of_nonneg_right n.cast_nonneg'] lemma linearGrowthInf_neg : linearGrowthInf (- u) = - linearGrowthSup u := by rw [linearGrowthSup, ← liminf_neg] refine liminf_congr (Eventually.of_forall fun n ↦ ?_) rw [Pi.neg_apply, Pi.neg_apply, div_eq_mul_inv, div_eq_mul_inv, ← neg_mul] lemma linearGrowthSup_inv : linearGrowthSup (- u) = - linearGrowthInf u := by rw [linearGrowthInf, ← limsup_neg] refine limsup_congr (Eventually.of_forall fun n ↦ ?_) rw [Pi.neg_apply, Pi.neg_apply, div_eq_mul_inv, div_eq_mul_inv, ← neg_mul] /-! ### Affine bounds -/ lemma linearGrowthInf_le_of_eventually_le (hb : b ≠ ⊤) (h : ∀ᶠ n in atTop, u n ≤ v n + b) : linearGrowthInf u ≤ linearGrowthInf v := by apply (linearGrowthInf_eventually_monotone h).trans rcases eq_bot_or_bot_lt b with rfl | b_bot · simp only [add_bot, ← Pi.bot_def, linearGrowthInf_bot, bot_le] · apply (linearGrowthInf_add_le' _ _).trans_eq <;> rw [linearGrowthSup_const b_bot.ne' hb] · exact add_zero (linearGrowthInf v) · exact Or.inr EReal.zero_ne_top · exact Or.inr EReal.zero_ne_bot lemma linearGrowthSup_le_of_eventually_le (hb : b ≠ ⊤) (h : ∀ᶠ n in atTop, u n ≤ v n + b) : linearGrowthSup u ≤ linearGrowthSup v := by apply (linearGrowthSup_eventually_monotone h).trans rcases eq_bot_or_bot_lt b with rfl | b_bot · simp only [add_bot, ← Pi.bot_def, linearGrowthSup_bot, bot_le] · apply (linearGrowthSup_add_le _ _).trans_eq <;> rw [linearGrowthSup_const b_bot.ne' hb] · exact add_zero (linearGrowthSup v) · exact Or.inr EReal.zero_ne_top · exact Or.inr EReal.zero_ne_bot /-! ### Infimum and supremum -/ lemma linearGrowthInf_inf : linearGrowthInf (u ⊓ v) = min (linearGrowthInf u) (linearGrowthInf v) := by rw [linearGrowthInf, linearGrowthInf, linearGrowthInf, ← liminf_min] refine liminf_congr (Eventually.of_forall fun n ↦ ?_) exact (monotone_div_right_of_nonneg n.cast_nonneg').map_min /-- Lower linear growth as an `InfTopHom`. -/ noncomputable def linearGrowthInfTopHom : InfTopHom (ℕ → EReal) EReal where toFun := linearGrowthInf map_inf' _ _ := linearGrowthInf_inf map_top' := linearGrowthInf_top lemma linearGrowthInf_biInf {α : Type*} (u : α → ℕ → EReal) {s : Set α} (hs : s.Finite) : linearGrowthInf (⨅ x ∈ s, u x) = ⨅ x ∈ s, linearGrowthInf (u x) := by have := map_finset_inf linearGrowthInfTopHom hs.toFinset u simpa only [linearGrowthInfTopHom, InfTopHom.coe_mk, InfHom.coe_mk, Finset.inf_eq_iInf, hs.mem_toFinset, comp_apply] lemma linearGrowthInf_iInf {ι : Type*} [Finite ι] (u : ι → ℕ → EReal) : linearGrowthInf (⨅ i, u i) = ⨅ i, linearGrowthInf (u i) := by rw [← iInf_univ, linearGrowthInf_biInf u Set.finite_univ, iInf_univ] lemma linearGrowthSup_sup : linearGrowthSup (u ⊔ v) = max (linearGrowthSup u) (linearGrowthSup v) := by rw [linearGrowthSup, linearGrowthSup, linearGrowthSup, ← limsup_max] refine limsup_congr (Eventually.of_forall fun n ↦ ?_) exact (monotone_div_right_of_nonneg n.cast_nonneg').map_max /-- Upper linear growth as a `SupBotHom`. -/ noncomputable def linearGrowthSupBotHom : SupBotHom (ℕ → EReal) EReal where toFun := linearGrowthSup map_sup' _ _ := linearGrowthSup_sup map_bot' := linearGrowthSup_bot lemma linearGrowthSup_biSup {α : Type*} (u : α → ℕ → EReal) {s : Set α} (hs : s.Finite) : linearGrowthSup (⨆ x ∈ s, u x) = ⨆ x ∈ s, linearGrowthSup (u x) := by have := map_finset_sup linearGrowthSupBotHom hs.toFinset u simpa only [linearGrowthSupBotHom, SupBotHom.coe_mk, SupHom.coe_mk, Finset.sup_eq_iSup, hs.mem_toFinset, comp_apply] lemma linearGrowthSup_iSup {ι : Type*} [Finite ι] (u : ι → ℕ → EReal) : linearGrowthSup (⨆ i, u i) = ⨆ i, linearGrowthSup (u i) := by rw [← iSup_univ, linearGrowthSup_biSup u Set.finite_univ, iSup_univ] end basic_properties /-! ### Composition -/ section composition variable {u : ℕ → EReal} {v : ℕ → ℕ} lemma Real.eventually_atTop_exists_int_between {a b : ℝ} (h : a < b) : ∀ᶠ x : ℝ in atTop, ∃ n : ℤ, a * x ≤ n ∧ n ≤ b * x := by refine (eventually_ge_atTop (b-a)⁻¹).mono fun x ab_x ↦ ?_ rw [inv_le_iff_one_le_mul₀ (sub_pos_of_lt h), mul_comm, sub_mul, le_sub_iff_add_le'] at ab_x obtain ⟨n, n_bx, hn⟩ := (b * x).exists_floor refine ⟨n, ?_, n_bx⟩ specialize hn (n + 1) simp only [Int.cast_add, Int.cast_one, add_le_iff_nonpos_right, Int.reduceLE, imp_false, not_le] at hn exact le_of_add_le_add_right (ab_x.trans hn.le) lemma Real.eventually_atTop_exists_nat_between {a b : ℝ} (h : a < b) (hb : 0 ≤ b) : ∀ᶠ x : ℝ in atTop, ∃ n : ℕ, a * x ≤ n ∧ n ≤ b * x := by filter_upwards [eventually_ge_atTop 0, Real.eventually_atTop_exists_int_between h] with x x_0 ⟨m, m_a, m_b⟩ refine ⟨m.toNat, m_a.trans (Int.cast_le.2 m.self_le_toNat), ?_⟩ apply le_of_eq_of_le _ (max_le m_b (mul_nonneg hb x_0)) norm_cast exact Int.toNat_eq_max m lemma EReal.eventually_atTop_exists_nat_between {a b : EReal} (h : a < b) (hb : 0 ≤ b) : ∀ᶠ n : ℕ in atTop, ∃ m : ℕ, a * n ≤ m ∧ m ≤ b * n := match a with | ⊤ => (not_top_lt h).rec | ⊥ => by refine Eventually.of_forall fun n ↦ ⟨0, ?_, ?_⟩ <;> rw [Nat.cast_zero] · apply mul_nonpos_iff.2 -- Split apply and exact for a 0.5s. gain exact .inr ⟨bot_le, n.cast_nonneg'⟩ · exact mul_nonneg hb n.cast_nonneg' | (a : ℝ) => match b with | ⊤ => by refine (eventually_gt_atTop 0).mono fun n n_0 ↦ ?_ obtain ⟨m, hm⟩ := exists_nat_ge_mul h.ne n exact ⟨m, hm, le_of_le_of_eq le_top (top_mul_of_pos (Nat.cast_pos'.2 n_0)).symm⟩ | ⊥ => (not_lt_bot h).rec | (b : ℝ) => by obtain ⟨x, hx⟩ := eventually_atTop.1 <| Real.eventually_atTop_exists_nat_between (EReal.coe_lt_coe_iff.1 h) (EReal.coe_nonneg.1 hb) obtain ⟨n, x_n⟩ := exists_nat_ge x refine eventually_atTop.2 ⟨n, fun k n_k ↦ ?_⟩ simp only [← coe_coe_eq_natCast, ← EReal.coe_mul, EReal.coe_le_coe_iff] exact hx k (x_n.trans (Nat.cast_le.2 n_k)) lemma tendsto_atTop_of_linearGrowthInf_natCast_pos (h : (linearGrowthInf fun n ↦ v n : EReal) ≠ 0) : Tendsto v atTop atTop := by refine tendsto_atTop.2 fun M ↦ ?_ have := tendsto_atTop_of_linearGrowthInf_pos (h.lt_of_le' (linearGrowthInf_natCast_nonneg v)) refine (tendsto_nhds_top_iff_real.1 this M).mono fun n ↦ ?_ rw [coe_coe_eq_natCast, Nat.cast_lt] exact le_of_lt lemma le_linearGrowthInf_comp (hu : 0 ≤ᶠ[atTop] u) (hv : Tendsto v atTop atTop) : (linearGrowthInf fun n ↦ v n : EReal) * linearGrowthInf u ≤ linearGrowthInf (u ∘ v) := by have uv_0 : 0 ≤ linearGrowthInf (u ∘ v) := by rw [← linearGrowthInf_const zero_ne_bot zero_ne_top] exact linearGrowthInf_eventually_monotone (hv.eventually hu) apply EReal.mul_le_of_forall_lt_of_nonneg (linearGrowthInf_natCast_nonneg v) uv_0 refine fun a ⟨_, a_v⟩ b ⟨b_0, b_u⟩ ↦ Eventually.le_linearGrowthInf ?_ have b_uv := eventually_map.1 ((eventually_mul_le b_u).filter_mono hv) filter_upwards [b_uv, eventually_lt_of_lt_liminf a_v, eventually_gt_atTop 0] with n b_uvn a_vn n_0 replace a_vn := ((lt_div_iff (Nat.cast_pos'.2 n_0) (natCast_ne_top n)).1 a_vn).le rw [comp_apply, mul_comm a b, mul_assoc b a] exact b_uvn.trans' <| by gcongr lemma linearGrowthSup_comp_le (hu : ∃ᶠ n in atTop, 0 ≤ u n) (hv₀ : (linearGrowthSup fun n ↦ v n : EReal) ≠ 0) (hv₁ : (linearGrowthSup fun n ↦ v n : EReal) ≠ ⊤) (hv₂ : Tendsto v atTop atTop) : linearGrowthSup (u ∘ v) ≤ (linearGrowthSup fun n ↦ v n : EReal) * linearGrowthSup u := by have v_0 := hv₀.symm.lt_of_le <| (linearGrowthInf_natCast_nonneg v).trans (liminf_le_limsup) refine le_mul_of_forall_lt (.inl v_0) (.inl hv₁) ?_ refine fun a v_a b u_b ↦ Eventually.linearGrowthSup_le ?_ have b_0 : 0 ≤ b := by rw [← linearGrowthInf_const zero_ne_bot zero_ne_top] exact (linearGrowthInf_le_linearGrowthSup_of_frequently_le hu).trans u_b.le have uv_b : ∀ᶠ n in atTop, u (v n) ≤ b * v n := eventually_map.1 ((eventually_le_mul u_b).filter_mono hv₂) filter_upwards [uv_b, eventually_lt_of_limsup_lt v_a, eventually_gt_atTop 0] with n uvn_b vn_a n_0 replace vn_a := ((div_lt_iff (Nat.cast_pos'.2 n_0) (natCast_ne_top n)).1 vn_a).le rw [comp_apply, mul_comm a b, mul_assoc b a] exact uvn_b.trans <| by gcongr /-! ### Monotone sequences -/ lemma _root_.Monotone.linearGrowthInf_nonneg (h : Monotone u) (h' : u ≠ ⊥) : 0 ≤ linearGrowthInf u := by simp only [ne_eq, funext_iff, not_forall] at h' obtain ⟨m, hm⟩ := h' have m_n : ∀ᶠ n in atTop, u m ≤ u n := eventually_atTop.2 ⟨m, fun _ hb ↦ h hb⟩ rcases eq_or_ne (u m) ⊤ with hm' | hm' · rw [hm'] at m_n exact le_top.trans (linearGrowthInf_top.symm.trans_le (linearGrowthInf_eventually_monotone m_n)) · rw [← linearGrowthInf_const hm hm'] exact linearGrowthInf_eventually_monotone m_n lemma _root_.Monotone.linearGrowthSup_nonneg (h : Monotone u) (h' : u ≠ ⊥) : 0 ≤ linearGrowthSup u := (h.linearGrowthInf_nonneg h').trans (linearGrowthInf_le_linearGrowthSup) lemma linearGrowthInf_comp_nonneg (h : Monotone u) (h' : u ≠ ⊥) (hv : Tendsto v atTop atTop) : 0 ≤ linearGrowthInf (u ∘ v) := by simp only [ne_eq, funext_iff, not_forall] at h' obtain ⟨m, hum⟩ := h' have um_uvn : ∀ᶠ n in atTop, u m ≤ (u ∘ v) n := by apply (eventually_map (P := fun n : ℕ ↦ u m ≤ u n)).2 exact (eventually_atTop.2 ⟨m, fun n m_n ↦ h m_n⟩).filter_mono hv apply (linearGrowthInf_eventually_monotone um_uvn).trans' rcases eq_or_ne (u m) ⊤ with hum' | hum' · rw [hum', ← Pi.top_def, linearGrowthInf_top]; exact le_top · rw [linearGrowthInf_const hum hum'] lemma linearGrowthSup_comp_nonneg (h : Monotone u) (h' : u ≠ ⊥) (hv : Tendsto v atTop atTop) : 0 ≤ linearGrowthSup (u ∘ v) := (linearGrowthInf_comp_nonneg h h' hv).trans linearGrowthInf_le_linearGrowthSup lemma _root_.Monotone.linearGrowthInf_comp_le (h : Monotone u) (hv₀ : (linearGrowthSup fun n ↦ v n : EReal) ≠ 0) (hv₁ : (linearGrowthSup fun n ↦ v n : EReal) ≠ ⊤) : linearGrowthInf (u ∘ v) ≤ (linearGrowthSup fun n ↦ v n : EReal) * linearGrowthInf u := by -- First we apply `le_mul_of_forall_lt`. by_cases u_0 : u = ⊥ · rw [u_0, Pi.bot_comp, linearGrowthInf_bot]; exact bot_le have v_0 := hv₀.symm.lt_of_le <| (linearGrowthInf_natCast_nonneg v).trans (liminf_le_limsup) refine le_mul_of_forall_lt (.inl v_0) (.inl hv₁) fun a v_a b u_b ↦ ?_ have a_0 := v_0.trans v_a have b_0 := (h.linearGrowthInf_nonneg u_0).trans_lt u_b rcases eq_or_ne a ⊤ with rfl | a_top · rw [top_mul_of_pos b_0]; exact le_top apply Frequently.linearGrowthInf_le obtain ⟨a', v_a', a_a'⟩ := exists_between v_a -- We get an epsilon of room: if `m` is large enough, then `v n ≤ a' * n < a * n`. -- Using `u_b`, we can find arbitrarily large values `n` such that `u n ≤ b * n`. -- If such an `n` is large enough, then we can find an integer `k` such that -- `a⁻¹ * n ≤ k ≤ a'⁻¹ * n`, or, in other words, `a' * k ≤ n ≤ a * k`. -- Then `v k ≤ a' * k ≤ n`, so `u (v k) ≤ u n ≤ b * n ≤ b * a * k`. have a_0' := v_0.trans v_a' have a_a_inv' : a⁻¹ < a'⁻¹ := inv_strictAntiOn (Set.mem_Ioi.2 a_0') (Set.mem_Ioi.2 a_0) a_a' replace v_a' : ∀ᶠ n : ℕ in atTop, v n ≤ a' * n := by filter_upwards [eventually_lt_of_limsup_lt v_a', eventually_gt_atTop 0] with n vn_a' n_0 rw [mul_comm] exact (div_le_iff_le_mul (Nat.cast_pos'.2 n_0) (natCast_ne_top n)).1 vn_a'.le suffices h : (∀ᶠ n : ℕ in atTop, v n ≤ a' * n) → ∃ᶠ n : ℕ in atTop, (u ∘ v) n ≤ a * b * n from h v_a' rw [← frequently_imp_distrib] replace u_b := ((frequently_le_mul u_b).and_eventually (eventually_gt_atTop 0)).and_eventually <| EReal.eventually_atTop_exists_nat_between a_a_inv' (inv_nonneg_of_nonneg a_0'.le) refine frequently_atTop.2 fun M ↦ ?_ obtain ⟨M', aM_M'⟩ := exists_nat_ge_mul a_top M obtain ⟨n, n_M', ⟨un_bn, _⟩, k, an_k, k_an'⟩ := frequently_atTop.1 u_b M' refine ⟨k, ?_, fun vk_ak' ↦ ?_⟩ · rw [mul_comm a, ← le_div_iff_mul_le a_0 a_top, EReal.div_eq_inv_mul] at aM_M' apply Nat.cast_le.1 <| aM_M'.trans <| an_k.trans' _ gcongr · rw [comp_apply, mul_comm a b, mul_assoc b a] rw [← EReal.div_eq_inv_mul, le_div_iff_mul_le a_0' (ne_top_of_lt a_a'), mul_comm] at k_an' rw [← EReal.div_eq_inv_mul, div_le_iff_le_mul a_0 a_top] at an_k have vk_n := Nat.cast_le.1 (vk_ak'.trans k_an') exact (h vk_n).trans <| un_bn.trans <| by gcongr lemma _root_.Monotone.le_linearGrowthSup_comp (h : Monotone u) (hv : (linearGrowthInf fun n ↦ v n : EReal) ≠ 0) : (linearGrowthInf fun n ↦ v n : EReal) * linearGrowthSup u ≤ linearGrowthSup (u ∘ v) := by have v_0 := hv.symm.lt_of_le (linearGrowthInf_natCast_nonneg v) -- WLOG, `u` is non-bot, and we can apply `mul_le_of_forall_lt_of_nonneg`. by_cases u_0 : u = ⊥ · rw [u_0, linearGrowthSup_bot, mul_bot_of_pos v_0]; exact bot_le apply EReal.mul_le_of_forall_lt_of_nonneg v_0.le (linearGrowthSup_comp_nonneg h u_0 (tendsto_atTop_of_linearGrowthInf_natCast_pos hv)) intro a ⟨a_0, a_v⟩ b ⟨b_0, b_u⟩ apply Frequently.le_linearGrowthSup obtain ⟨a', a_a', a_v'⟩ := exists_between a_v -- We get an epsilon of room: if `m` is large enough, then `a * n < a' * n ≤ v n`. -- Using `b_u`, we can find arbitrarily large values `n` such that `b * n ≤ u n`. -- If such an `n` is large enough, then we can find an integer `k` such that -- `a'⁻¹ * n ≤ k ≤ a⁻¹ * n`, or, in other words, `a * k ≤ n ≤ a' * k`. -- Then `v k ≥ a' * k ≥ n`, so `u (v k) ≥ u n ≥ b * n ≥ b * a * k`. have a_top' := ne_top_of_lt a_v' have a_0' := a_0.trans a_a' have a_a_inv' : a'⁻¹ < a⁻¹ := inv_strictAntiOn (Set.mem_Ioi.2 a_0) (Set.mem_Ioi.2 a_0') a_a' replace a_v' : ∀ᶠ n : ℕ in atTop, a' * n ≤ v n := by filter_upwards [eventually_lt_of_lt_liminf a_v', eventually_gt_atTop 0] with n a_vn' n_0 exact (le_div_iff_mul_le (Nat.cast_pos'.2 n_0) (natCast_ne_top n)).1 a_vn'.le suffices h : (∀ᶠ n : ℕ in atTop, a' * n ≤ v n) → ∃ᶠ n : ℕ in atTop, a * b * n ≤ (u ∘ v) n from h a_v' rw [← frequently_imp_distrib] replace b_u := ((frequently_mul_le b_u).and_eventually (eventually_gt_atTop 0)).and_eventually <| EReal.eventually_atTop_exists_nat_between a_a_inv' (inv_nonneg_of_nonneg a_0.le) refine frequently_atTop.2 fun M ↦ ?_ obtain ⟨M', aM_M'⟩ := exists_nat_ge_mul a_top' M obtain ⟨n, n_M', ⟨bn_un, _⟩, k, an_k', k_an⟩ := frequently_atTop.1 b_u M' refine ⟨k, ?_, fun ak_vk' ↦ ?_⟩ · rw [mul_comm a', ← le_div_iff_mul_le a_0' a_top', EReal.div_eq_inv_mul] at aM_M' apply Nat.cast_le.1 <| aM_M'.trans <| an_k'.trans' _ gcongr · rw [comp_apply, mul_comm a b, mul_assoc b a] rw [← EReal.div_eq_inv_mul, div_le_iff_le_mul a_0' a_top'] at an_k' rw [← EReal.div_eq_inv_mul, le_div_iff_mul_le a_0 (ne_top_of_lt a_a'), mul_comm] at k_an have n_vk := Nat.cast_le.1 (an_k'.trans ak_vk') exact le_trans (by gcongr) <| bn_un.trans (h n_vk) lemma _root_.Monotone.linearGrowthInf_comp {a : EReal} (h : Monotone u) (hv : Tendsto (fun n ↦ (v n : EReal) / n) atTop (𝓝 a)) (ha : a ≠ 0) (ha' : a ≠ ⊤) : linearGrowthInf (u ∘ v) = a * linearGrowthInf u := by have hv₁ : 0 < liminf (fun n ↦ (v n : EReal) / n) atTop := by rw [← hv.liminf_eq] at ha exact ha.symm.lt_of_le (linearGrowthInf_natCast_nonneg v) have v_top := tendsto_atTop_of_linearGrowthInf_natCast_pos hv₁.ne.symm -- Either `u = 0`, or `u` is non-zero and bounded by `1`, or `u` is eventually larger than one. -- In the latter case, we apply `le_linearGrowthInf_comp` and `linearGrowthInf_comp_le`. by_cases u_0 : u = ⊥ · rw [u_0, Pi.bot_comp, linearGrowthInf_bot, ← hv.liminf_eq, mul_bot_of_pos hv₁] by_cases h1 : ∃ᶠ n : ℕ in atTop, u n ≤ 0 · replace h' (n : ℕ) : u n ≤ 0 := by obtain ⟨m, n_m, um_1⟩ := (frequently_atTop.1 h1) n exact (h n_m).trans um_1 have u_0' : linearGrowthInf u = 0 := by apply le_antisymm _ (h.linearGrowthInf_nonneg u_0) exact (linearGrowthInf_monotone h').trans_eq (linearGrowthInf_const zero_ne_bot zero_ne_top) rw [u_0', mul_zero] apply le_antisymm _ (linearGrowthInf_comp_nonneg h u_0 v_top) apply (linearGrowthInf_monotone fun n ↦ h' (v n)).trans_eq exact linearGrowthInf_const zero_ne_bot zero_ne_top · replace h' := (not_frequently.1 h1).mono fun _ hn ↦ le_of_not_ge hn apply le_antisymm · rw [← hv.limsup_eq] at ha ha' ⊢ exact h.linearGrowthInf_comp_le ha ha' · rw [← hv.liminf_eq] exact le_linearGrowthInf_comp h' v_top lemma _root_.Monotone.linearGrowthSup_comp {a : EReal} (h : Monotone u) (hv : Tendsto (fun n ↦ (v n : EReal) / n) atTop (𝓝 a)) (ha : a ≠ 0) (ha' : a ≠ ⊤) : linearGrowthSup (u ∘ v) = a * linearGrowthSup u := by have hv₁ : 0 < liminf (fun n ↦ (v n : EReal) / n) atTop := by rw [← hv.liminf_eq] at ha exact ha.symm.lt_of_le (linearGrowthInf_natCast_nonneg v) have v_top := tendsto_atTop_of_linearGrowthInf_natCast_pos hv₁.ne.symm -- Either `u = 0`, or `u` is non-zero and bounded by `1`, or `u` is eventually larger than one. -- In the latter case, we apply `le_linearGrowthSup_comp` and `linearGrowthSup_comp_le`. by_cases u_0 : u = ⊥ · rw [u_0, Pi.bot_comp, linearGrowthSup_bot, ← hv.liminf_eq, mul_bot_of_pos hv₁] by_cases u_1 : ∀ᶠ n : ℕ in atTop, u n ≤ 0 · have u_0' : linearGrowthSup u = 0 := by apply le_antisymm _ (h.linearGrowthSup_nonneg u_0) apply (linearGrowthSup_eventually_monotone u_1).trans_eq exact (linearGrowthSup_const zero_ne_bot zero_ne_top) rw [u_0', mul_zero] apply le_antisymm _ (linearGrowthSup_comp_nonneg h u_0 v_top) apply (linearGrowthSup_eventually_monotone (v_top.eventually u_1)).trans_eq exact linearGrowthSup_const zero_ne_bot zero_ne_top · replace h' := (not_eventually.1 u_1).mono fun x hx ↦ (lt_of_not_ge hx).le apply le_antisymm · rw [← hv.limsup_eq] at ha ha' ⊢ exact linearGrowthSup_comp_le h' ha ha' v_top · rw [← hv.liminf_eq] exact h.le_linearGrowthSup_comp hv₁.ne.symm lemma _root_.Monotone.linearGrowthInf_comp_mul {m : ℕ} (h : Monotone u) (hm : m ≠ 0) : linearGrowthInf (fun n ↦ u (m * n)) = m * linearGrowthInf u := by have : Tendsto (fun n : ℕ ↦ ((m * n : ℕ) : EReal) / n) atTop (𝓝 m) := by refine tendsto_nhds_of_eventually_eq ((eventually_gt_atTop 0).mono fun x hx ↦ ?_) rw [mul_comm, natCast_mul x m, ← mul_div] exact mul_div_cancel (natCast_ne_bot x) (natCast_ne_top x) (Nat.cast_ne_zero.2 hx.ne.symm) exact h.linearGrowthInf_comp this (Nat.cast_ne_zero.2 hm) (natCast_ne_top m) lemma _root_.Monotone.linearGrowthSup_comp_mul {m : ℕ} (h : Monotone u) (hm : m ≠ 0) : linearGrowthSup (fun n ↦ u (m * n)) = m * linearGrowthSup u := by have : Tendsto (fun n : ℕ ↦ ((m * n : ℕ) : EReal) / n) atTop (𝓝 m) := by refine tendsto_nhds_of_eventually_eq ((eventually_gt_atTop 0).mono fun x hx ↦ ?_) rw [mul_comm, natCast_mul x m, ← mul_div] exact mul_div_cancel (natCast_ne_bot x) (natCast_ne_top x) (Nat.cast_ne_zero.2 hx.ne.symm) exact h.linearGrowthSup_comp this (Nat.cast_ne_zero.2 hm) (natCast_ne_top m) end composition end LinearGrowth
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.
DirichletLSeries.lean
/- Copyright (c) 2023 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import Mathlib.NumberTheory.EulerProduct.ExpLog import Mathlib.NumberTheory.LSeries.Dirichlet /-! # The Euler Product for the Riemann Zeta Function and Dirichlet L-Series The first main result of this file is the Euler Product formula for the Riemann ζ function $$\prod_p \frac{1}{1 - p^{-s}} = \lim_{n \to \infty} \prod_{p < n} \frac{1}{1 - p^{-s}} = \zeta(s)$$ for $s$ with real part $> 1$ ($p$ runs through the primes). `riemannZeta_eulerProduct` is the second equality above. There are versions `riemannZeta_eulerProduct_hasProd` and `riemannZeta_eulerProduct_tprod` in terms of `HasProd` and `tprod`, respectively. The second result is `dirichletLSeries_eulerProduct` (with variants `dirichletLSeries_eulerProduct_hasProd` and `dirichletLSeries_eulerProduct_tprod`), which is the analogous statement for Dirichlet L-series. -/ open Complex variable {s : ℂ} /-- When `s ≠ 0`, the map `n ↦ n^(-s)` is completely multiplicative and vanishes at zero. -/ noncomputable def riemannZetaSummandHom (hs : s ≠ 0) : ℕ →*₀ ℂ where toFun n := (n : ℂ) ^ (-s) map_zero' := by simp [hs] map_one' := by simp map_mul' m n := by simpa only [Nat.cast_mul, ofReal_natCast] using mul_cpow_ofReal_nonneg m.cast_nonneg n.cast_nonneg _ /-- When `χ` is a Dirichlet character and `s ≠ 0`, the map `n ↦ χ n * n^(-s)` is completely multiplicative and vanishes at zero. -/ noncomputable def dirichletSummandHom {n : ℕ} (χ : DirichletCharacter ℂ n) (hs : s ≠ 0) : ℕ →*₀ ℂ where toFun n := χ n * (n : ℂ) ^ (-s) map_zero' := by simp [hs] map_one' := by simp map_mul' m n := by simp_rw [← ofReal_natCast] simpa only [Nat.cast_mul, IsUnit.mul_iff, not_and, map_mul, ofReal_mul, mul_cpow_ofReal_nonneg m.cast_nonneg n.cast_nonneg _] using mul_mul_mul_comm .. /-- When `s.re > 1`, the map `n ↦ n^(-s)` is norm-summable. -/ lemma summable_riemannZetaSummand (hs : 1 < s.re) : Summable (fun n ↦ ‖riemannZetaSummandHom (ne_zero_of_one_lt_re hs) n‖) := by simp only [riemannZetaSummandHom, MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk] convert Real.summable_nat_rpow_inv.mpr hs with n rw [← ofReal_natCast, norm_cpow_eq_rpow_re_of_nonneg (Nat.cast_nonneg n) <| re_neg_ne_zero_of_one_lt_re hs, neg_re, Real.rpow_neg <| Nat.cast_nonneg n] lemma tsum_riemannZetaSummand (hs : 1 < s.re) : ∑' (n : ℕ), riemannZetaSummandHom (ne_zero_of_one_lt_re hs) n = riemannZeta s := by have hsum := summable_riemannZetaSummand hs rw [zeta_eq_tsum_one_div_nat_add_one_cpow hs, hsum.of_norm.tsum_eq_zero_add, map_zero, zero_add] simp only [riemannZetaSummandHom, cpow_neg, MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk, Nat.cast_add, Nat.cast_one, one_div] /-- When `s.re > 1`, the map `n ↦ χ(n) * n^(-s)` is norm-summable. -/ lemma summable_dirichletSummand {N : ℕ} (χ : DirichletCharacter ℂ N) (hs : 1 < s.re) : Summable (fun n ↦ ‖dirichletSummandHom χ (ne_zero_of_one_lt_re hs) n‖) := by simp only [dirichletSummandHom, MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk, norm_mul] exact (summable_riemannZetaSummand hs).of_nonneg_of_le (fun _ ↦ by positivity) (fun n ↦ mul_le_of_le_one_left (norm_nonneg _) <| χ.norm_le_one n) open scoped LSeries.notation in lemma tsum_dirichletSummand {N : ℕ} (χ : DirichletCharacter ℂ N) (hs : 1 < s.re) : ∑' (n : ℕ), dirichletSummandHom χ (ne_zero_of_one_lt_re hs) n = L ↗χ s := by simp only [dirichletSummandHom, cpow_neg, MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk, LSeries, LSeries.term_of_ne_zero' (ne_zero_of_one_lt_re hs), div_eq_mul_inv] open Filter Nat Topology EulerProduct /-- The Euler product for the Riemann ζ function, valid for `s.re > 1`. This version is stated in terms of `HasProd`. -/ theorem riemannZeta_eulerProduct_hasProd (hs : 1 < s.re) : HasProd (fun p : Primes ↦ (1 - (p : ℂ) ^ (-s))⁻¹) (riemannZeta s) := by rw [← tsum_riemannZetaSummand hs] apply eulerProduct_completely_multiplicative_hasProd <| summable_riemannZetaSummand hs /-- The Euler product for the Riemann ζ function, valid for `s.re > 1`. This version is stated in terms of `tprod`. -/ theorem riemannZeta_eulerProduct_tprod (hs : 1 < s.re) : ∏' p : Primes, (1 - (p : ℂ) ^ (-s))⁻¹ = riemannZeta s := (riemannZeta_eulerProduct_hasProd hs).tprod_eq /-- The Euler product for the Riemann ζ function, valid for `s.re > 1`. This version is stated in the form of convergence of finite partial products. -/ theorem riemannZeta_eulerProduct (hs : 1 < s.re) : Tendsto (fun n : ℕ ↦ ∏ p ∈ primesBelow n, (1 - (p : ℂ) ^ (-s))⁻¹) atTop (𝓝 (riemannZeta s)) := by rw [← tsum_riemannZetaSummand hs] apply eulerProduct_completely_multiplicative <| summable_riemannZetaSummand hs open scoped LSeries.notation /-- The Euler product for Dirichlet L-series, valid for `s.re > 1`. This version is stated in terms of `HasProd`. -/ theorem DirichletCharacter.LSeries_eulerProduct_hasProd {N : ℕ} (χ : DirichletCharacter ℂ N) (hs : 1 < s.re) : HasProd (fun p : Primes ↦ (1 - χ p * (p : ℂ) ^ (-s))⁻¹) (L ↗χ s) := by rw [← tsum_dirichletSummand χ hs] convert eulerProduct_completely_multiplicative_hasProd <| summable_dirichletSummand χ hs /-- The Euler product for Dirichlet L-series, valid for `s.re > 1`. This version is stated in terms of `tprod`. -/ theorem DirichletCharacter.LSeries_eulerProduct_tprod {N : ℕ} (χ : DirichletCharacter ℂ N) (hs : 1 < s.re) : ∏' p : Primes, (1 - χ p * (p : ℂ) ^ (-s))⁻¹ = L ↗χ s := (DirichletCharacter.LSeries_eulerProduct_hasProd χ hs).tprod_eq /-- The Euler product for Dirichlet L-series, valid for `s.re > 1`. This version is stated in the form of convergence of finite partial products. -/ theorem DirichletCharacter.LSeries_eulerProduct {N : ℕ} (χ : DirichletCharacter ℂ N) (hs : 1 < s.re) : Tendsto (fun n : ℕ ↦ ∏ p ∈ primesBelow n, (1 - χ p * (p : ℂ) ^ (-s))⁻¹) atTop (𝓝 (L ↗χ s)) := by rw [← tsum_dirichletSummand χ hs] apply eulerProduct_completely_multiplicative <| summable_dirichletSummand χ hs open LSeries /-- A variant of the Euler product for Dirichlet L-series. -/ theorem DirichletCharacter.LSeries_eulerProduct_exp_log {N : ℕ} (χ : DirichletCharacter ℂ N) {s : ℂ} (hs : 1 < s.re) : exp (∑' p : Nat.Primes, -log (1 - χ p * p ^ (-s))) = L ↗χ s := by let f := dirichletSummandHom χ <| ne_zero_of_one_lt_re hs have h n : term ↗χ s n = f n := by rcases eq_or_ne n 0 with rfl | hn · simp only [term_zero, map_zero] · simp only [ne_eq, hn, not_false_eq_true, term_of_ne_zero, div_eq_mul_inv, dirichletSummandHom, cpow_neg, MonoidWithZeroHom.coe_mk, ZeroHom.coe_mk, f] simpa only [LSeries, h] using exp_tsum_primes_log_eq_tsum (f := f) <| summable_dirichletSummand χ hs open DirichletCharacter /-- A variant of the Euler product for the L-series of `ζ`. -/ theorem ArithmeticFunction.LSeries_zeta_eulerProduct_exp_log {s : ℂ} (hs : 1 < s.re) : exp (∑' p : Nat.Primes, -Complex.log (1 - p ^ (-s))) = L 1 s := by convert modOne_eq_one (R := ℂ) ▸ DirichletCharacter.LSeries_eulerProduct_exp_log (1 : DirichletCharacter ℂ 1) hs using 7 rw [MulChar.one_apply <| isUnit_of_subsingleton _, one_mul] /-- A variant of the Euler product for the Riemann zeta function. -/ theorem riemannZeta_eulerProduct_exp_log {s : ℂ} (hs : 1 < s.re) : exp (∑' p : Nat.Primes, -Complex.log (1 - p ^ (-s))) = riemannZeta s := LSeries_one_eq_riemannZeta hs ▸ ArithmeticFunction.LSeries_zeta_eulerProduct_exp_log hs /-! ### Changing the level of a Dirichlet `L`-series -/ /-- If `χ` is a Dirichlet character and its level `M` divides `N`, then we obtain the L-series of `χ` considered as a Dirichlet character of level `N` from the L-series of `χ` by multiplying with `∏ p ∈ N.primeFactors, (1 - χ p * p ^ (-s))`. -/ lemma DirichletCharacter.LSeries_changeLevel {M N : ℕ} [NeZero N] (hMN : M ∣ N) (χ : DirichletCharacter ℂ M) {s : ℂ} (hs : 1 < s.re) : LSeries ↗(changeLevel hMN χ) s = LSeries ↗χ s * ∏ p ∈ N.primeFactors, (1 - χ p * p ^ (-s)) := by rw [prod_eq_tprod_mulIndicator, ← DirichletCharacter.LSeries_eulerProduct_tprod _ hs, ← DirichletCharacter.LSeries_eulerProduct_tprod _ hs] -- convert to a form suitable for `tprod_subtype` have (f : Primes → ℂ) : ∏' (p : Primes), f p = ∏' (p : ↑{p : ℕ | p.Prime}), f p := rfl rw [this, tprod_subtype _ fun p : ℕ ↦ (1 - (changeLevel hMN χ) p * p ^ (-s))⁻¹, this, tprod_subtype _ fun p : ℕ ↦ (1 - χ p * p ^ (-s))⁻¹, ← Multipliable.tprod_mul] rotate_left -- deal with convergence goals first · exact multipliable_subtype_iff_mulIndicator.mp (DirichletCharacter.LSeries_eulerProduct_hasProd χ hs).multipliable · exact multipliable_subtype_iff_mulIndicator.mp Multipliable.of_finite · congr 1 with p simp only [Set.mulIndicator_apply, Set.mem_setOf_eq, Finset.mem_coe, Nat.mem_primeFactors, ne_eq, mul_ite, ite_mul, one_mul, mul_one] by_cases h : p.Prime; swap · simp only [h, false_and, if_false] simp only [h, true_and, if_true] by_cases hp' : p ∣ N; swap · simp only [hp', false_and, ↓reduceIte, inv_inj, sub_right_inj, mul_eq_mul_right_iff, cpow_eq_zero_iff, Nat.cast_eq_zero, h.ne_zero, ne_eq, neg_eq_zero, or_false] have hq : IsUnit (p : ZMod N) := (ZMod.isUnit_prime_iff_not_dvd h).mpr hp' simp only [hq.unit_spec ▸ DirichletCharacter.changeLevel_eq_cast_of_dvd χ hMN hq.unit, ZMod.cast_natCast hMN] · simp only [hp', NeZero.ne N, not_false_eq_true, and_self, ↓reduceIte] have : ¬IsUnit (p : ZMod N) := by rwa [ZMod.isUnit_prime_iff_not_dvd h, not_not] rw [MulChar.map_nonunit _ this, zero_mul, sub_zero, inv_one] refine (inv_mul_cancel₀ ?_).symm rw [sub_ne_zero, ne_comm] -- Remains to show `χ p * p ^ (-s) ≠ 1`. We show its norm is strictly `< 1`. apply_fun (‖·‖) simp only [norm_mul, norm_one] have ha : ‖χ p‖ ≤ 1 := χ.norm_le_one p have hb : ‖(p : ℂ) ^ (-s)‖ ≤ 1 / 2 := norm_prime_cpow_le_one_half ⟨p, h⟩ hs exact ((mul_le_mul ha hb (norm_nonneg _) zero_le_one).trans_lt (by norm_num)).ne
morphism.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 choice. From mathcomp Require Import fintype finfun bigop finset fingroup. (******************************************************************************) (* This file contains the definitions of: *) (* *) (* {morphism D >-> rT} == *) (* the structure type of functions that are group morphisms mapping a *) (* domain set D : {set aT} to a type rT; rT must have a finGroupType *) (* structure, and D is usually a group (most of the theory expects this). *) (* mfun == the coercion projecting {morphism D >-> rT} to aT -> rT *) (* *) (* Basic examples: *) (* idm D == the identity morphism with domain D, or more precisely *) (* the identity function, but with a canonical *) (* {morphism G -> gT} structure. *) (* trivm D == the trivial morphism with domain D. *) (* If f has a {morphism D >-> rT} structure *) (* 'dom f == D, the domain of f. *) (* f @* A == the image of A by f, where f is defined. *) (* := f @: (D :&: A) *) (* f @*^-1 R == the pre-image of R by f, where f is defined. *) (* := D :&: f @^-1: R *) (* 'ker f == the kernel of f. *) (* := f @*^-1 1 *) (* 'ker_G f == the kernel of f restricted to G. *) (* := G :&: 'ker f (this is a pure notation) *) (* 'injm f <=> f injective on D. *) (* <-> ker f \subset 1 (this is a pure notation) *) (* invm injf == the inverse morphism of f, with domain f @* D, when f *) (* is injective (injf : 'injm f). *) (* restrm f sDom == the restriction of f to a subset A of D, given *) (* (sDom : A \subset D); restrm f sDom is transparently *) (* identical to f; the restrmP and domP lemmas provide *) (* opaque restrictions. *) (* *) (* G \isog H <=> G and H are isomorphic as groups. *) (* H \homg G <=> H is a homomorphic image of G. *) (* isom G H f <=> f maps G isomorphically to H, provided D contains G. *) (* := f @: G^# == H^# *) (* *) (* If, moreover, g : {morphism G >-> gT} with G : {group aT}, *) (* factm sKer sDom == the (natural) factor morphism mapping f @* G to g @* G *) (* with sDom : G \subset D, sKer : 'ker f \subset 'ker g. *) (* ifactm injf g == the (natural) factor morphism mapping f @* G to g @* G *) (* when f is injective (injf : 'injm f); here g must *) (* denote an actual morphism structure, not its function *) (* projection. *) (* *) (* If g has a {morphism G >-> aT} structure for any G : {group gT}, then *) (* f \o g has a canonical {morphism g @*^-1 D >-> rT} structure. *) (* *) (* Finally, for an arbitrary function f : aT -> rT *) (* morphic D f <=> f preserves group multiplication in D, i.e., *) (* f (x * y) = (f x) * (f y) for all x, y in D. *) (* morphm fM == a function identical to f, but with a canonical *) (* {morphism D >-> rT} structure, given fM : morphic D f. *) (* misom D C f <=> f is a morphism that maps D isomorphically to C. *) (* := morphic D f && isom D C f *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Reserved Notation "x \isog y" (at level 70). Section MorphismStructure. Variables aT rT : finGroupType. Structure morphism (D : {set aT}) : Type := Morphism { mfun :> aT -> FinGroup.sort rT; _ : {in D &, {morph mfun : x y / x * y}} }. (* We give the 'lightest' possible specification to define morphisms: local *) (* congruence, in D, with the group law of aT. We then provide the properties *) (* for the 'textbook' notion of morphism, when the required structures are *) (* available (e.g. its domain is a group). *) Definition morphism_for D of phant rT := morphism D. Definition clone_morphism D f := let: Morphism _ fM := f return {type of @Morphism D for f} -> morphism_for D (Phant rT) in fun k => k fM. Variables (D A : {set aT}) (R : {set rT}) (x : aT) (y : rT) (f : aT -> rT). Variant morphim_spec : Prop := MorphimSpec z & z \in D & z \in A & y = f z. Lemma morphimP : reflect morphim_spec (y \in f @: (D :&: A)). Proof. apply: (iffP imsetP) => [] [z]; first by case/setIP; exists z. by exists z; first apply/setIP. Qed. Lemma morphpreP : reflect (x \in D /\ f x \in R) (x \in D :&: f @^-1: R). Proof. by rewrite !inE; apply: andP. Qed. End MorphismStructure. Notation "{ 'morphism' D >-> T }" := (morphism_for D (Phant T)) (format "{ 'morphism' D >-> T }") : type_scope. Notation "[ 'morphism' D 'of' f ]" := (@clone_morphism _ _ D _ (fun fM => @Morphism _ _ D f fM)) (format "[ 'morphism' D 'of' f ]") : form_scope. Notation "[ 'morphism' 'of' f ]" := (clone_morphism (@Morphism _ _ _ f)) (format "[ 'morphism' 'of' f ]") : form_scope. Arguments morphimP {aT rT D A y f}. Arguments morphpreP {aT rT D R x f}. (* Domain, image, preimage, kernel, using phantom types to infer the domain. *) Section MorphismOps1. Variables (aT rT : finGroupType) (D : {set aT}) (f : {morphism D >-> rT}). Lemma morphM : {in D &, {morph f : x y / x * y}}. Proof. by case f. Qed. Notation morPhantom := (phantom (aT -> rT)). Definition MorPhantom := Phantom (aT -> rT). Definition dom of morPhantom f := D. Definition morphim of morPhantom f := fun A => f @: (D :&: A). Definition morphpre of morPhantom f := fun R : {set rT} => D :&: f @^-1: R. Definition ker mph := morphpre mph 1. End MorphismOps1. Arguments morphim _ _ _%_g _ _ _%_g. Arguments morphpre _ _ _%_g _ _ _%_g. Notation "''dom' f" := (dom (MorPhantom f)) (at level 10, f at level 8, format "''dom' f") : group_scope. Notation "''ker' f" := (ker (MorPhantom f)) (at level 10, f at level 8, format "''ker' f") : group_scope. Notation "''ker_' H f" := (H :&: 'ker f) (at level 10, H at level 2, f at level 8, format "''ker_' H f") : group_scope. Notation "f @* A" := (morphim (MorPhantom f) A) (at level 24, format "f @* A") : group_scope. Notation "f @*^-1 R" := (morphpre (MorPhantom f) R) (at level 24, format "f @*^-1 R") : group_scope. Notation "''injm' f" := (pred_of_set ('ker f) \subset pred_of_set 1) (at level 10, f at level 8, format "''injm' f") : group_scope. Section MorphismTheory. Variables aT rT : finGroupType. Implicit Types A B : {set aT}. Implicit Types G H : {group aT}. Implicit Types R S : {set rT}. Implicit Types M : {group rT}. (* Most properties of morphims hold only when the domain is a group. *) Variables (D : {group aT}) (f : {morphism D >-> rT}). Lemma morph1 : f 1 = 1. Proof. by apply: (mulgI (f 1)); rewrite -morphM ?mulg1. Qed. Lemma morph_prod I r (P : pred I) F : (forall i, P i -> F i \in D) -> f (\prod_(i <- r | P i) F i) = \prod_( i <- r | P i) f (F i). Proof. move=> D_F; elim/(big_load (fun x => x \in D)): _. elim/big_rec2: _ => [|i _ x Pi [Dx <-]]; first by rewrite morph1. by rewrite groupM ?morphM // D_F. Qed. Lemma morphV : {in D, {morph f : x / x^-1}}. Proof. move=> x Dx; apply: (mulgI (f x)). by rewrite -morphM ?groupV // !mulgV morph1. Qed. Lemma morphJ : {in D &, {morph f : x y / x ^ y}}. Proof. by move=> * /=; rewrite !morphM ?morphV // ?groupM ?groupV. Qed. Lemma morphX n : {in D, {morph f : x / x ^+ n}}. Proof. by elim: n => [|n IHn] x Dx; rewrite ?morph1 // !expgS morphM ?(groupX, IHn). Qed. Lemma morphR : {in D &, {morph f : x y / [~ x, y]}}. Proof. by move=> * /=; rewrite morphM ?(groupV, groupJ) // morphJ ?morphV. Qed. (* Morphic image, preimage properties w.r.t. set-theoretic operations. *) Lemma morphimE A : f @* A = f @: (D :&: A). Proof. by []. Qed. Lemma morphpreE R : f @*^-1 R = D :&: f @^-1: R. Proof. by []. Qed. Lemma kerE : 'ker f = f @*^-1 1. Proof. by []. Qed. Lemma morphimEsub A : A \subset D -> f @* A = f @: A. Proof. by move=> sAD; rewrite /morphim (setIidPr sAD). Qed. Lemma morphimEdom : f @* D = f @: D. Proof. exact: morphimEsub. Qed. Lemma morphimIdom A : f @* (D :&: A) = f @* A. Proof. by rewrite /morphim setIA setIid. Qed. Lemma morphpreIdom R : D :&: f @*^-1 R = f @*^-1 R. Proof. by rewrite /morphim setIA setIid. Qed. Lemma morphpreIim R : f @*^-1 (f @* D :&: R) = f @*^-1 R. Proof. apply/setP=> x; rewrite morphimEdom !inE. by case Dx: (x \in D); rewrite // imset_f. Qed. Lemma morphimIim A : f @* D :&: f @* A = f @* A. Proof. by apply/setIidPr; rewrite imsetS // setIid subsetIl. Qed. Lemma mem_morphim A x : x \in D -> x \in A -> f x \in f @* A. Proof. by move=> Dx Ax; apply/morphimP; exists x. Qed. Lemma mem_morphpre R x : x \in D -> f x \in R -> x \in f @*^-1 R. Proof. by move=> Dx Rfx; apply/morphpreP. Qed. Lemma morphimS A B : A \subset B -> f @* A \subset f @* B. Proof. by move=> sAB; rewrite imsetS ?setIS. Qed. Lemma morphim_sub A : f @* A \subset f @* D. Proof. by rewrite imsetS // setIid subsetIl. Qed. Lemma leq_morphim A : #|f @* A| <= #|A|. Proof. by apply: (leq_trans (leq_imset_card _ _)); rewrite subset_leq_card ?subsetIr. Qed. Lemma morphpreS R S : R \subset S -> f @*^-1 R \subset f @*^-1 S. Proof. by move=> sRS; rewrite setIS ?preimsetS. Qed. Lemma morphpre_sub R : f @*^-1 R \subset D. Proof. exact: subsetIl. Qed. Lemma morphim_setIpre A R : f @* (A :&: f @*^-1 R) = f @* A :&: R. Proof. apply/setP=> fa; apply/morphimP/setIP=> [[a Da] | [/morphimP[a Da Aa ->] Rfa]]. by rewrite !inE Da /= => /andP[Aa Rfa] ->; rewrite mem_morphim. by exists a; rewrite // !inE Aa Da. Qed. Lemma morphim0 : f @* set0 = set0. Proof. by rewrite morphimE setI0 imset0. Qed. Lemma morphim_eq0 A : A \subset D -> (f @* A == set0) = (A == set0). Proof. by rewrite imset_eq0 => /setIidPr->. Qed. Lemma morphim_set1 x : x \in D -> f @* [set x] = [set f x]. Proof. by rewrite /morphim -sub1set => /setIidPr->; apply: imset_set1. Qed. Lemma morphim1 : f @* 1 = 1. Proof. by rewrite morphim_set1 ?morph1. Qed. Lemma morphimV A : f @* A^-1 = (f @* A)^-1. Proof. wlog suffices: A / f @* A^-1 \subset (f @* A)^-1. by move=> IH; apply/eqP; rewrite eqEsubset IH -invSg invgK -{1}(invgK A) IH. apply/subsetP=> _ /morphimP[x Dx Ax' ->]; rewrite !inE in Ax' *. by rewrite -morphV // imset_f // inE groupV Dx. Qed. Lemma morphpreV R : f @*^-1 R^-1 = (f @*^-1 R)^-1. Proof. apply/setP=> x; rewrite !inE groupV; case Dx: (x \in D) => //=. by rewrite morphV. Qed. Lemma morphimMl A B : A \subset D -> f @* (A * B) = f @* A * f @* B. Proof. move=> sAD; rewrite /morphim setIC -group_modl // (setIidPr sAD). apply/setP=> fxy; apply/idP/idP. case/imsetP=> _ /imset2P[x y Ax /setIP[Dy By] ->] ->{fxy}. by rewrite morphM // (subsetP sAD, imset2_f) // imset_f // inE By. case/imset2P=> _ _ /imsetP[x Ax ->] /morphimP[y Dy By ->] ->{fxy}. by rewrite -morphM // (subsetP sAD, imset_f) // mem_mulg // inE By. Qed. Lemma morphimMr A B : B \subset D -> f @* (A * B) = f @* A * f @* B. Proof. move=> sBD; apply: invg_inj. by rewrite invMg -!morphimV invMg morphimMl // -invGid invSg. Qed. Lemma morphpreMl R S : R \subset f @* D -> f @*^-1 (R * S) = f @*^-1 R * f @*^-1 S. Proof. move=> sRfD; apply/setP=> x; rewrite !inE. apply/andP/imset2P=> [[Dx] | [y z]]; last first. rewrite !inE => /andP[Dy Rfy] /andP[Dz Rfz] ->. by rewrite ?(groupM, morphM, imset2_f). case/imset2P=> fy fz Rfy Rfz def_fx. have /morphimP[y Dy _ def_fy]: fy \in f @* D := subsetP sRfD fy Rfy. exists y (y^-1 * x); last by rewrite mulKVg. by rewrite !inE Dy -def_fy. by rewrite !inE groupM ?(morphM, morphV, groupV) // def_fx -def_fy mulKg. Qed. Lemma morphimJ A x : x \in D -> f @* (A :^ x) = f @* A :^ f x. Proof. move=> Dx; rewrite !conjsgE morphimMl ?(morphimMr, sub1set, groupV) //. by rewrite !(morphim_set1, groupV, morphV). Qed. Lemma morphpreJ R x : x \in D -> f @*^-1 (R :^ f x) = f @*^-1 R :^ x. Proof. move=> Dx; apply/setP=> y; rewrite conjIg !inE conjGid // !mem_conjg inE. by case Dy: (y \in D); rewrite // morphJ ?(morphV, groupV). Qed. Lemma morphim_class x A : x \in D -> A \subset D -> f @* (x ^: A) = f x ^: f @* A. Proof. move=> Dx sAD; rewrite !morphimEsub ?class_subG // /class -!imset_comp. by apply: eq_in_imset => y Ay /=; rewrite morphJ // (subsetP sAD). Qed. Lemma classes_morphim A : A \subset D -> classes (f @* A) = [set f @* xA | xA in classes A]. Proof. move=> sAD; rewrite morphimEsub // /classes -!imset_comp. apply: eq_in_imset => x /(subsetP sAD) Dx /=. by rewrite morphim_class ?morphimEsub. Qed. Lemma morphimT : f @* setT = f @* D. Proof. by rewrite -morphimIdom setIT. Qed. Lemma morphimU A B : f @* (A :|: B) = f @* A :|: f @* B. Proof. by rewrite -imsetU -setIUr. Qed. Lemma morphimI A B : f @* (A :&: B) \subset f @* A :&: f @* B. Proof. by rewrite subsetI // ?morphimS ?(subsetIl, subsetIr). Qed. Lemma morphpre0 : f @*^-1 set0 = set0. Proof. by rewrite morphpreE preimset0 setI0. Qed. Lemma morphpreT : f @*^-1 setT = D. Proof. by rewrite morphpreE preimsetT setIT. Qed. Lemma morphpreU R S : f @*^-1 (R :|: S) = f @*^-1 R :|: f @*^-1 S. Proof. by rewrite -setIUr -preimsetU. Qed. Lemma morphpreI R S : f @*^-1 (R :&: S) = f @*^-1 R :&: f @*^-1 S. Proof. by rewrite -setIIr -preimsetI. Qed. Lemma morphpreD R S : f @*^-1 (R :\: S) = f @*^-1 R :\: f @*^-1 S. Proof. by apply/setP=> x /[!inE]; case: (x \in D). Qed. (* kernel, domain properties *) Lemma kerP x : x \in D -> reflect (f x = 1) (x \in 'ker f). Proof. by move=> Dx; rewrite 2!inE Dx; apply: set1P. Qed. Lemma dom_ker : {subset 'ker f <= D}. Proof. by move=> x /morphpreP[]. Qed. Lemma mker x : x \in 'ker f -> f x = 1. Proof. by move=> Kx; apply/kerP=> //; apply: dom_ker. Qed. Lemma mkerl x y : x \in 'ker f -> y \in D -> f (x * y) = f y. Proof. by move=> Kx Dy; rewrite morphM // ?(dom_ker, mker Kx, mul1g). Qed. Lemma mkerr x y : x \in D -> y \in 'ker f -> f (x * y) = f x. Proof. by move=> Dx Ky; rewrite morphM // ?(dom_ker, mker Ky, mulg1). Qed. Lemma rcoset_kerP x y : x \in D -> y \in D -> reflect (f x = f y) (x \in 'ker f :* y). Proof. move=> Dx Dy; rewrite mem_rcoset !inE groupM ?morphM ?groupV //=. by rewrite morphV // -eq_mulgV1; apply: eqP. Qed. Lemma ker_rcoset x y : x \in D -> y \in D -> f x = f y -> exists2 z, z \in 'ker f & x = z * y. Proof. by move=> Dx Dy eqfxy; apply/rcosetP; apply/rcoset_kerP. Qed. Lemma ker_norm : D \subset 'N('ker f). Proof. apply/subsetP=> x Dx /[1!inE]; apply/subsetP=> _ /imsetP[y Ky ->]. by rewrite !inE groupJ ?morphJ // ?dom_ker //= mker ?conj1g. Qed. Lemma ker_normal : 'ker f <| D. Proof. by rewrite /(_ <| D) subsetIl ker_norm. Qed. Lemma morphimGI G A : 'ker f \subset G -> f @* (G :&: A) = f @* G :&: f @* A. Proof. move=> sKG; apply/eqP; rewrite eqEsubset morphimI setIC. apply/subsetP=> _ /setIP[/morphimP[x Dx Ax ->] /morphimP[z Dz Gz]]. case/ker_rcoset=> {Dz}// y Ky def_x. have{z Gz y Ky def_x} Gx: x \in G by rewrite def_x groupMl // (subsetP sKG). by rewrite imset_f ?inE // Dx Gx Ax. Qed. Lemma morphimIG A G : 'ker f \subset G -> f @* (A :&: G) = f @* A :&: f @* G. Proof. by move=> sKG; rewrite setIC morphimGI // setIC. Qed. Lemma morphimD A B : f @* A :\: f @* B \subset f @* (A :\: B). Proof. rewrite subDset -morphimU morphimS //. by rewrite setDE setUIr setUCr setIT subsetUr. Qed. Lemma morphimDG A G : 'ker f \subset G -> f @* (A :\: G) = f @* A :\: f @* G. Proof. move=> sKG; apply/eqP; rewrite eqEsubset morphimD andbT !setDE subsetI. rewrite morphimS ?subsetIl // -[~: f @* G]setU0 -subDset setDE setCK. by rewrite -morphimIG //= setIAC -setIA setICr setI0 morphim0. Qed. Lemma morphimD1 A : (f @* A)^# \subset f @* A^#. Proof. by rewrite -!set1gE -morphim1 morphimD. Qed. (* group structure preservation *) Lemma morphpre_groupset M : group_set (f @*^-1 M). Proof. apply/group_setP; split=> [|x y]; rewrite !inE ?(morph1, group1) //. by case/andP=> Dx Mfx /andP[Dy Mfy]; rewrite morphM ?groupM. Qed. Lemma morphim_groupset G : group_set (f @* G). Proof. apply/group_setP; split=> [|_ _ /morphimP[x Dx Gx ->] /morphimP[y Dy Gy ->]]. by rewrite -morph1 imset_f ?group1. by rewrite -morphM ?imset_f ?inE ?groupM. Qed. Canonical morphpre_group fPh M := @group _ (morphpre fPh M) (morphpre_groupset M). Canonical morphim_group fPh G := @group _ (morphim fPh G) (morphim_groupset G). Canonical ker_group fPh : {group aT} := Eval hnf in [group of ker fPh]. Lemma morph_dom_groupset : group_set (f @: D). Proof. by rewrite -morphimEdom groupP. Qed. Canonical morph_dom_group := group morph_dom_groupset. Lemma morphpreMr R S : S \subset f @* D -> f @*^-1 (R * S) = f @*^-1 R * f @*^-1 S. Proof. move=> sSfD; apply: invg_inj. by rewrite invMg -!morphpreV invMg morphpreMl // -invSg invgK invGid. Qed. Lemma morphimK A : A \subset D -> f @*^-1 (f @* A) = 'ker f * A. Proof. move=> sAD; apply/setP=> x; rewrite !inE. apply/idP/idP=> [/andP[Dx /morphimP[y Dy Ay eqxy]] | /imset2P[z y Kz Ay ->{x}]]. rewrite -(mulgKV y x) mem_mulg // !inE !(groupM, morphM, groupV) //. by rewrite morphV //= eqxy mulgV. have [Dy Dz]: y \in D /\ z \in D by rewrite (subsetP sAD) // dom_ker. by rewrite groupM // morphM // mker // mul1g imset_f // inE Dy. Qed. Lemma morphimGK G : 'ker f \subset G -> G \subset D -> f @*^-1 (f @* G) = G. Proof. by move=> sKG sGD; rewrite morphimK // mulSGid. Qed. Lemma morphpre_set1 x : x \in D -> f @*^-1 [set f x] = 'ker f :* x. Proof. by move=> Dx; rewrite -morphim_set1 // morphimK ?sub1set. Qed. Lemma morphpreK R : R \subset f @* D -> f @* (f @*^-1 R) = R. Proof. move=> sRfD; apply/setP=> y; apply/morphimP/idP=> [[x _] | Ry]. by rewrite !inE; case/andP=> _ Rfx ->. have /morphimP[x Dx _ defy]: y \in f @* D := subsetP sRfD y Ry. by exists x; rewrite // !inE Dx -defy. Qed. Lemma morphim_ker : f @* 'ker f = 1. Proof. by rewrite morphpreK ?sub1G. Qed. Lemma ker_sub_pre M : 'ker f \subset f @*^-1 M. Proof. by rewrite morphpreS ?sub1G. Qed. Lemma ker_normal_pre M : 'ker f <| f @*^-1 M. Proof. by rewrite /normal ker_sub_pre subIset ?ker_norm. Qed. Lemma morphpreSK R S : R \subset f @* D -> (f @*^-1 R \subset f @*^-1 S) = (R \subset S). Proof. move=> sRfD; apply/idP/idP=> [sf'RS|]; last exact: morphpreS. suffices: R \subset f @* D :&: S by rewrite subsetI sRfD. rewrite -(morphpreK sRfD) -[_ :&: S]morphpreK (morphimS, subsetIl) //. by rewrite morphpreI morphimGK ?subsetIl // setIA setIid. Qed. Lemma sub_morphim_pre A R : A \subset D -> (f @* A \subset R) = (A \subset f @*^-1 R). Proof. move=> sAD; rewrite -morphpreSK (morphimS, morphimK) //. apply/idP/idP; first by apply: subset_trans; apply: mulG_subr. by move/(mulgS ('ker f)); rewrite -morphpreMl ?(sub1G, mul1g). Qed. Lemma morphpre_proper R S : R \subset f @* D -> S \subset f @* D -> (f @*^-1 R \proper f @*^-1 S) = (R \proper S). Proof. by move=> dQ dR; rewrite /proper !morphpreSK. Qed. Lemma sub_morphpre_im R G : 'ker f \subset G -> G \subset D -> R \subset f @* D -> (f @*^-1 R \subset G) = (R \subset f @* G). Proof. by symmetry; rewrite -morphpreSK ?morphimGK. Qed. Lemma ker_trivg_morphim A : (A \subset 'ker f) = (A \subset D) && (f @* A \subset [1]). Proof. case sAD: (A \subset D); first by rewrite sub_morphim_pre. by rewrite subsetI sAD. Qed. Lemma morphimSK A B : A \subset D -> (f @* A \subset f @* B) = (A \subset 'ker f * B). Proof. move=> sAD; transitivity (A \subset 'ker f * (D :&: B)). by rewrite -morphimK ?subsetIl // -sub_morphim_pre // /morphim setIA setIid. by rewrite setIC group_modl (subsetIl, subsetI) // andbC sAD. Qed. Lemma morphimSGK A G : A \subset D -> 'ker f \subset G -> (f @* A \subset f @* G) = (A \subset G). Proof. by move=> sGD skfK; rewrite morphimSK // mulSGid. Qed. Lemma ltn_morphim A : [1] \proper 'ker_A f -> #|f @* A| < #|A|. Proof. case/properP; rewrite sub1set => /setIP[A1 _] [x /setIP[Ax kx] x1]. rewrite (cardsD1 1 A) A1 ltnS -{1}(setD1K A1) morphimU morphim1. rewrite (setUidPr _) ?sub1set; last first. by rewrite -(mker kx) mem_morphim ?(dom_ker kx) // inE x1. by rewrite (leq_trans (leq_imset_card _ _)) ?subset_leq_card ?subsetIr. Qed. (* injectivity of image and preimage *) Lemma morphpre_inj : {in [pred R : {set rT} | R \subset f @* D] &, injective (fun R => f @*^-1 R)}. Proof. exact: can_in_inj morphpreK. Qed. Lemma morphim_injG : {in [pred G : {group aT} | 'ker f \subset G & G \subset D] &, injective (fun G => f @* G)}. Proof. move=> G H /andP[sKG sGD] /andP[sKH sHD] eqfGH. by apply: val_inj; rewrite /= -(morphimGK sKG sGD) eqfGH morphimGK. Qed. Lemma morphim_inj G H : ('ker f \subset G) && (G \subset D) -> ('ker f \subset H) && (H \subset D) -> f @* G = f @* H -> G :=: H. Proof. by move=> nsGf nsHf /morphim_injG->. Qed. (* commutation with generated groups and cycles *) Lemma morphim_gen A : A \subset D -> f @* <<A>> = <<f @* A>>. Proof. move=> sAD; apply/eqP. rewrite eqEsubset andbC gen_subG morphimS; last exact: subset_gen. by rewrite sub_morphim_pre gen_subG // -sub_morphim_pre // subset_gen. Qed. Lemma morphim_cycle x : x \in D -> f @* <[x]> = <[f x]>. Proof. by move=> Dx; rewrite morphim_gen (sub1set, morphim_set1). Qed. Lemma morphimY A B : A \subset D -> B \subset D -> f @* (A <*> B) = f @* A <*> f @* B. Proof. by move=> sAD sBD; rewrite morphim_gen ?morphimU // subUset sAD. Qed. Lemma morphpre_gen R : 1 \in R -> R \subset f @* D -> f @*^-1 <<R>> = <<f @*^-1 R>>. Proof. move=> R1 sRfD; apply/eqP. rewrite eqEsubset andbC gen_subG morphpreS; last exact: subset_gen. rewrite -{1}(morphpreK sRfD) -morphim_gen ?subsetIl // morphimGK //=. by rewrite sub_gen // setIS // preimsetS ?sub1set. by rewrite gen_subG subsetIl. Qed. (* commutator, normaliser, normal, center properties*) Lemma morphimR A B : A \subset D -> B \subset D -> f @* [~: A, B] = [~: f @* A, f @* B]. Proof. move/subsetP=> sAD /subsetP sBD. rewrite morphim_gen; last first; last congr <<_>>. by apply/subsetP=> _ /imset2P[x y Ax By ->]; rewrite groupR; auto. apply/setP=> fz; apply/morphimP/imset2P=> [[z _] | [fx fy]]. case/imset2P=> x y Ax By -> -> {z fz}. have Dx := sAD x Ax; have Dy := sBD y By. by exists (f x) (f y); rewrite ?(imset_f, morphR) // ?(inE, Dx, Dy). case/morphimP=> x Dx Ax ->{fx}; case/morphimP=> y Dy By ->{fy} -> {fz}. by exists [~ x, y]; rewrite ?(inE, morphR, groupR, imset2_f). Qed. Lemma morphim_norm A : f @* 'N(A) \subset 'N(f @* A). Proof. apply/subsetP=> fx; case/morphimP=> x Dx Nx -> {fx}. by rewrite inE -morphimJ ?(normP Nx). Qed. Lemma morphim_norms A B : A \subset 'N(B) -> f @* A \subset 'N(f @* B). Proof. by move=> nBA; apply: subset_trans (morphim_norm B); apply: morphimS. Qed. Lemma morphim_subnorm A B : f @* 'N_A(B) \subset 'N_(f @* A)(f @* B). Proof. exact: subset_trans (morphimI A _) (setIS _ (morphim_norm B)). Qed. Lemma morphim_normal A B : A <| B -> f @* A <| f @* B. Proof. by case/andP=> sAB nAB; rewrite /(_ <| _) morphimS // morphim_norms. Qed. Lemma morphim_cent1 x : x \in D -> f @* 'C[x] \subset 'C[f x]. Proof. by move=> Dx; rewrite -(morphim_set1 Dx) morphim_norm. Qed. Lemma morphim_cent1s A x : x \in D -> A \subset 'C[x] -> f @* A \subset 'C[f x]. Proof. by move=> Dx cAx; apply: subset_trans (morphim_cent1 Dx); apply: morphimS. Qed. Lemma morphim_subcent1 A x : x \in D -> f @* 'C_A[x] \subset 'C_(f @* A)[f x]. Proof. by move=> Dx; rewrite -(morphim_set1 Dx) morphim_subnorm. Qed. Lemma morphim_cent A : f @* 'C(A) \subset 'C(f @* A). Proof. apply/bigcapsP=> fx; case/morphimP=> x Dx Ax ->{fx}. by apply: subset_trans (morphim_cent1 Dx); apply: morphimS; apply: bigcap_inf. Qed. Lemma morphim_cents A B : A \subset 'C(B) -> f @* A \subset 'C(f @* B). Proof. by move=> cBA; apply: subset_trans (morphim_cent B); apply: morphimS. Qed. Lemma morphim_subcent A B : f @* 'C_A(B) \subset 'C_(f @* A)(f @* B). Proof. exact: subset_trans (morphimI A _) (setIS _ (morphim_cent B)). Qed. Lemma morphim_abelian A : abelian A -> abelian (f @* A). Proof. exact: morphim_cents. Qed. Lemma morphpre_norm R : f @*^-1 'N(R) \subset 'N(f @*^-1 R). Proof. by apply/subsetP=> x /[!inE] /andP[Dx Nfx]; rewrite -morphpreJ ?morphpreS. Qed. Lemma morphpre_norms R S : R \subset 'N(S) -> f @*^-1 R \subset 'N(f @*^-1 S). Proof. by move=> nSR; apply: subset_trans (morphpre_norm S); apply: morphpreS. Qed. Lemma morphpre_normal R S : R \subset f @* D -> S \subset f @* D -> (f @*^-1 R <| f @*^-1 S) = (R <| S). Proof. move=> sRfD sSfD; apply/idP/andP=> [|[sRS nSR]]. by move/morphim_normal; rewrite !morphpreK //; case/andP. by rewrite /(_ <| _) (subset_trans _ (morphpre_norm _)) morphpreS. Qed. Lemma morphpre_subnorm R S : f @*^-1 'N_R(S) \subset 'N_(f @*^-1 R)(f @*^-1 S). Proof. by rewrite morphpreI setIS ?morphpre_norm. Qed. Lemma morphim_normG G : 'ker f \subset G -> G \subset D -> f @* 'N(G) = 'N_(f @* D)(f @* G). Proof. move=> sKG sGD; apply/eqP; rewrite eqEsubset -{1}morphimIdom morphim_subnorm. rewrite -(morphpreK (subsetIl _ _)) morphimS //= morphpreI subIset // orbC. by rewrite -{2}(morphimGK sKG sGD) morphpre_norm. Qed. Lemma morphim_subnormG A G : 'ker f \subset G -> G \subset D -> f @* 'N_A(G) = 'N_(f @* A)(f @* G). Proof. move=> sKB sBD; rewrite morphimIG ?normsG // morphim_normG //. by rewrite setICA setIA morphimIim. Qed. Lemma morphpre_cent1 x : x \in D -> 'C_D[x] \subset f @*^-1 'C[f x]. Proof. move=> Dx; rewrite -sub_morphim_pre ?subsetIl //. by apply: subset_trans (morphim_cent1 Dx); rewrite morphimS ?subsetIr. Qed. Lemma morphpre_cent1s R x : x \in D -> R \subset f @* D -> f @*^-1 R \subset 'C[x] -> R \subset 'C[f x]. Proof. by move=> Dx sRfD; move/(morphim_cent1s Dx); rewrite morphpreK. Qed. Lemma morphpre_subcent1 R x : x \in D -> 'C_(f @*^-1 R)[x] \subset f @*^-1 'C_R[f x]. Proof. move=> Dx; rewrite -morphpreIdom -setIA setICA morphpreI setIS //. exact: morphpre_cent1. Qed. Lemma morphpre_cent A : 'C_D(A) \subset f @*^-1 'C(f @* A). Proof. rewrite -sub_morphim_pre ?subsetIl // morphimGI ?(subsetIl, subIset) // orbC. by rewrite (subset_trans (morphim_cent _)). Qed. Lemma morphpre_cents A R : R \subset f @* D -> f @*^-1 R \subset 'C(A) -> R \subset 'C(f @* A). Proof. by move=> sRfD; move/morphim_cents; rewrite morphpreK. Qed. Lemma morphpre_subcent R A : 'C_(f @*^-1 R)(A) \subset f @*^-1 'C_R(f @* A). Proof. by rewrite -morphpreIdom -setIA setICA morphpreI setIS //; apply: morphpre_cent. Qed. (* local injectivity properties *) Lemma injmP : reflect {in D &, injective f} ('injm f). Proof. apply: (iffP subsetP) => [injf x y Dx Dy | injf x /= Kx]. by case/ker_rcoset=> // z /injf/set1P->; rewrite mul1g. have Dx := dom_ker Kx; apply/set1P/injf => //. by apply/rcoset_kerP; rewrite // mulg1. Qed. Lemma card_im_injm : (#|f @* D| == #|D|) = 'injm f. Proof. by rewrite morphimEdom (sameP imset_injP injmP). Qed. Section Injective. Hypothesis injf : 'injm f. Lemma ker_injm : 'ker f = 1. Proof. exact/trivgP. Qed. Lemma injmK A : A \subset D -> f @*^-1 (f @* A) = A. Proof. by move=> sAD; rewrite morphimK // ker_injm // mul1g. Qed. Lemma injm_morphim_inj A B : A \subset D -> B \subset D -> f @* A = f @* B -> A = B. Proof. by move=> sAD sBD eqAB; rewrite -(injmK sAD) eqAB injmK. Qed. Lemma card_injm A : A \subset D -> #|f @* A| = #|A|. Proof. move=> sAD; rewrite morphimEsub // card_in_imset //. exact: (sub_in2 (subsetP sAD) (injmP injf)). Qed. Lemma order_injm x : x \in D -> #[f x] = #[x]. Proof. by move=> Dx; rewrite orderE -morphim_cycle // card_injm ?cycle_subG. Qed. Lemma injm1 x : x \in D -> f x = 1 -> x = 1. Proof. by move=> Dx; move/(kerP Dx); rewrite ker_injm; move/set1P. Qed. Lemma morph_injm_eq1 x : x \in D -> (f x == 1) = (x == 1). Proof. by move=> Dx; rewrite -morph1 (inj_in_eq (injmP injf)) ?group1. Qed. Lemma injmSK A B : A \subset D -> (f @* A \subset f @* B) = (A \subset B). Proof. by move=> sAD; rewrite morphimSK // ker_injm mul1g. Qed. Lemma sub_morphpre_injm R A : A \subset D -> R \subset f @* D -> (f @*^-1 R \subset A) = (R \subset f @* A). Proof. by move=> sAD sRfD; rewrite -morphpreSK ?injmK. Qed. Lemma injm_eq A B : A \subset D -> B \subset D -> (f @* A == f @* B) = (A == B). Proof. by move=> sAD sBD; rewrite !eqEsubset !injmSK. Qed. Lemma morphim_injm_eq1 A : A \subset D -> (f @* A == 1) = (A == 1). Proof. by move=> sAD; rewrite -morphim1 injm_eq ?sub1G. Qed. Lemma injmI A B : f @* (A :&: B) = f @* A :&: f @* B. Proof. rewrite -morphimIdom setIIr -4!(injmK (subsetIl D _), =^~ morphimIdom). by rewrite -morphpreI morphpreK // subIset ?morphim_sub. Qed. Lemma injmD1 A : f @* A^# = (f @* A)^#. Proof. by have:= morphimDG A injf; rewrite morphim1. Qed. Lemma nclasses_injm A : A \subset D -> #|classes (f @* A)| = #|classes A|. Proof. move=> sAD; rewrite classes_morphim // card_in_imset //. move=> _ _ /imsetP[x Ax ->] /imsetP[y Ay ->]. by apply: injm_morphim_inj; rewrite // class_subG ?(subsetP sAD). Qed. Lemma injm_norm A : A \subset D -> f @* 'N(A) = 'N_(f @* D)(f @* A). Proof. move=> sAD; apply/eqP; rewrite -morphimIdom eqEsubset morphim_subnorm. rewrite -sub_morphpre_injm ?subsetIl // morphpreI injmK // setIS //. by rewrite -{2}(injmK sAD) morphpre_norm. Qed. Lemma injm_norms A B : A \subset D -> B \subset D -> (f @* A \subset 'N(f @* B)) = (A \subset 'N(B)). Proof. by move=> sAD sBD; rewrite -injmSK // injm_norm // subsetI morphimS. Qed. Lemma injm_normal A B : A \subset D -> B \subset D -> (f @* A <| f @* B) = (A <| B). Proof. by move=> sAD sBD; rewrite /normal injmSK ?injm_norms. Qed. Lemma injm_subnorm A B : B \subset D -> f @* 'N_A(B) = 'N_(f @* A)(f @* B). Proof. by move=> sBD; rewrite injmI injm_norm // setICA setIA morphimIim. Qed. Lemma injm_cent1 x : x \in D -> f @* 'C[x] = 'C_(f @* D)[f x]. Proof. by move=> Dx; rewrite injm_norm ?morphim_set1 ?sub1set. Qed. Lemma injm_subcent1 A x : x \in D -> f @* 'C_A[x] = 'C_(f @* A)[f x]. Proof. by move=> Dx; rewrite injm_subnorm ?morphim_set1 ?sub1set. Qed. Lemma injm_cent A : A \subset D -> f @* 'C(A) = 'C_(f @* D)(f @* A). Proof. move=> sAD; apply/eqP; rewrite -morphimIdom eqEsubset morphim_subcent. apply/subsetP=> fx; case/setIP; case/morphimP=> x Dx _ ->{fx} cAfx. rewrite mem_morphim // inE Dx -sub1set centsC cent_set1 -injmSK //. by rewrite injm_cent1 // subsetI morphimS // -cent_set1 centsC sub1set. Qed. Lemma injm_cents A B : A \subset D -> B \subset D -> (f @* A \subset 'C(f @* B)) = (A \subset 'C(B)). Proof. by move=> sAD sBD; rewrite -injmSK // injm_cent // subsetI morphimS. Qed. Lemma injm_subcent A B : B \subset D -> f @* 'C_A(B) = 'C_(f @* A)(f @* B). Proof. by move=> sBD; rewrite injmI injm_cent // setICA setIA morphimIim. Qed. Lemma injm_abelian A : A \subset D -> abelian (f @* A) = abelian A. Proof. by move=> sAD; rewrite /abelian -subsetIidl -injm_subcent // injmSK ?subsetIidl. Qed. End Injective. Lemma eq_morphim (g : {morphism D >-> rT}): {in D, f =1 g} -> forall A, f @* A = g @* A. Proof. by move=> efg A; apply: eq_in_imset; apply: sub_in1 efg => x /setIP[]. Qed. Lemma eq_in_morphim B A (g : {morphism B >-> rT}) : D :&: A = B :&: A -> {in A, f =1 g} -> f @* A = g @* A. Proof. move=> eqDBA eqAfg; rewrite /morphim /= eqDBA. by apply: eq_in_imset => x /setIP[_]/eqAfg. Qed. End MorphismTheory. Notation "''ker' f" := (ker_group (MorPhantom f)) : Group_scope. Notation "''ker_' G f" := (G :&: 'ker f)%G : Group_scope. Notation "f @* G" := (morphim_group (MorPhantom f) G) : Group_scope. Notation "f @*^-1 M" := (morphpre_group (MorPhantom f) M) : Group_scope. Notation "f @: D" := (morph_dom_group f D) : Group_scope. Arguments injmP {aT rT D f}. Arguments morphpreK {aT rT D f} [R] sRf. Section IdentityMorphism. Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Type G : {group gT}. Definition idm of {set gT} := fun x : gT => x : FinGroup.sort gT. Lemma idm_morphM A : {in A & , {morph idm A : x y / x * y}}. Proof. by []. Qed. Canonical idm_morphism A := Morphism (@idm_morphM A). Lemma injm_idm G : 'injm (idm G). Proof. by apply/injmP=> x y _ _. Qed. Lemma ker_idm G : 'ker (idm G) = 1. Proof. by apply/trivgP; apply: injm_idm. Qed. Lemma morphim_idm A B : B \subset A -> idm A @* B = B. Proof. rewrite /morphim /= /idm => /setIidPr->. by apply/setP=> x; apply/imsetP/idP=> [[y By ->]|Bx]; last exists x. Qed. Lemma morphpre_idm A B : idm A @*^-1 B = A :&: B. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma im_idm A : idm A @* A = A. Proof. exact: morphim_idm. Qed. End IdentityMorphism. Arguments idm {_} _%_g _%_g. Section RestrictedMorphism. Variables aT rT : finGroupType. Variables A D : {set aT}. Implicit Type B : {set aT}. Implicit Type R : {set rT}. Definition restrm of A \subset D := @id (aT -> FinGroup.sort rT). Section Props. Hypothesis sAD : A \subset D. Variable f : {morphism D >-> rT}. Local Notation fA := (restrm sAD (mfun f)). Canonical restrm_morphism := @Morphism aT rT A fA (sub_in2 (subsetP sAD) (morphM f)). Lemma morphim_restrm B : fA @* B = f @* (A :&: B). Proof. by rewrite {2}/morphim setIA (setIidPr sAD). Qed. Lemma restrmEsub B : B \subset A -> fA @* B = f @* B. Proof. by rewrite morphim_restrm => /setIidPr->. Qed. Lemma im_restrm : fA @* A = f @* A. Proof. exact: restrmEsub. Qed. Lemma morphpre_restrm R : fA @*^-1 R = A :&: f @*^-1 R. Proof. by rewrite setIA (setIidPl sAD). Qed. Lemma ker_restrm : 'ker fA = 'ker_A f. Proof. exact: morphpre_restrm. Qed. Lemma injm_restrm : 'injm f -> 'injm fA. Proof. by apply: subset_trans; rewrite ker_restrm subsetIr. Qed. End Props. Lemma restrmP (f : {morphism D >-> rT}) : A \subset 'dom f -> {g : {morphism A >-> rT} | [/\ g = f :> (aT -> rT), 'ker g = 'ker_A f, forall R, g @*^-1 R = A :&: f @*^-1 R & forall B, B \subset A -> g @* B = f @* B]}. Proof. move=> sAD; exists (restrm_morphism sAD f). split=> // [|R|B sBA]; first 1 [exact: ker_restrm | exact: morphpre_restrm]. by rewrite morphim_restrm (setIidPr sBA). Qed. Lemma domP (f : {morphism D >-> rT}) : 'dom f = A -> {g : {morphism A >-> rT} | [/\ g = f :> (aT -> rT), 'ker g = 'ker f, forall R, g @*^-1 R = f @*^-1 R & forall B, g @* B = f @* B]}. Proof. by move <-; exists f. Qed. End RestrictedMorphism. Arguments restrm {_ _ _%_g _%_g} _ _%_g. Arguments restrmP {aT rT A D}. Arguments domP {aT rT A D}. Section TrivMorphism. Variables aT rT : finGroupType. Definition trivm of {set aT} & aT := 1 : FinGroup.sort rT. Lemma trivm_morphM (A : {set aT}) : {in A &, {morph trivm A : x y / x * y}}. Proof. by move=> x y /=; rewrite mulg1. Qed. Canonical triv_morph A := Morphism (@trivm_morphM A). Lemma morphim_trivm (G H : {group aT}) : trivm G @* H = 1. Proof. apply/setP=> /= y; rewrite inE; apply/idP/eqP=> [|->]; first by case/morphimP. by apply/morphimP; exists (1 : aT); rewrite /= ?group1. Qed. Lemma ker_trivm (G : {group aT}) : 'ker (trivm G) = G. Proof. by apply/setIidPl/subsetP=> x _; rewrite !inE /=. Qed. End TrivMorphism. Arguments trivm {aT rT} _%_g _%_g. (* The composition of two morphisms is a Canonical morphism instance. *) Section MorphismComposition. Variables gT hT rT : finGroupType. Variables (G : {group gT}) (H : {group hT}). Variable f : {morphism G >-> hT}. Variable g : {morphism H >-> rT}. Local Notation gof := (mfun g \o mfun f). Lemma comp_morphM : {in f @*^-1 H &, {morph gof: x y / x * y}}. Proof. by move=> x y; rewrite /= !inE => /andP[? ?] /andP[? ?]; rewrite !morphM. Qed. Canonical comp_morphism := Morphism comp_morphM. Lemma ker_comp : 'ker gof = f @*^-1 'ker g. Proof. by apply/setP=> x; rewrite !inE andbA. Qed. Lemma injm_comp : 'injm f -> 'injm g -> 'injm gof. Proof. by move=> injf; rewrite ker_comp; move/trivgP=> ->. Qed. Lemma morphim_comp (A : {set gT}) : gof @* A = g @* (f @* A). Proof. apply/setP=> z; apply/morphimP/morphimP=> [[x]|[y Hy fAy ->{z}]]. rewrite !inE => /andP[Gx Hfx]; exists (f x) => //. by apply/morphimP; exists x. by case/morphimP: fAy Hy => x Gx Ax ->{y} Hfx; exists x; rewrite ?inE ?Gx. Qed. Lemma morphpre_comp (C : {set rT}) : gof @*^-1 C = f @*^-1 (g @*^-1 C). Proof. by apply/setP=> z; rewrite !inE andbA. Qed. End MorphismComposition. (* The factor morphism *) Section FactorMorphism. Variables aT qT rT : finGroupType. Variables G H : {group aT}. Variable f : {morphism G >-> rT}. Variable q : {morphism H >-> qT}. Definition factm of 'ker q \subset 'ker f & G \subset H := fun x => f (repr (q @*^-1 [set x])). Hypothesis sKqKf : 'ker q \subset 'ker f. Hypothesis sGH : G \subset H. Notation ff := (factm sKqKf sGH). Lemma factmE x : x \in G -> ff (q x) = f x. Proof. rewrite /ff => Gx; have Hx := subsetP sGH x Gx. have /mem_repr: x \in q @*^-1 [set q x] by rewrite !inE Hx /=. case/morphpreP; move: (repr _) => y Hy /set1P. by case/ker_rcoset=> // z Kz ->; rewrite mkerl ?(subsetP sKqKf). Qed. Lemma factm_morphM : {in q @* G &, {morph ff : x y / x * y}}. Proof. move=> _ _ /morphimP[x Hx Gx ->] /morphimP[y Hy Gy ->]. by rewrite -morphM ?factmE ?groupM // morphM. Qed. Canonical factm_morphism := Morphism factm_morphM. Lemma morphim_factm (A : {set aT}) : ff @* (q @* A) = f @* A. Proof. rewrite -morphim_comp /= {1}/morphim /= morphimGK //; last first. by rewrite (subset_trans sKqKf) ?subsetIl. apply/setP=> y; apply/morphimP/morphimP; by case=> x Gx Ax ->{y}; exists x; rewrite //= factmE. Qed. Lemma morphpre_factm (C : {set rT}) : ff @*^-1 C = q @* (f @*^-1 C). Proof. apply/setP=> y /[!inE]/=; apply/andP/morphimP=> [[]|[x Hx]]; last first. by case/morphpreP=> Gx Cfx ->; rewrite factmE ?imset_f ?inE ?Hx. case/morphimP=> x Hx Gx ->; rewrite factmE //. by exists x; rewrite // !inE Gx. Qed. Lemma ker_factm : 'ker ff = q @* 'ker f. Proof. exact: morphpre_factm. Qed. Lemma injm_factm : 'injm f -> 'injm ff. Proof. by rewrite ker_factm => /trivgP->; rewrite morphim1. Qed. Lemma injm_factmP : reflect ('ker f = 'ker q) ('injm ff). Proof. rewrite ker_factm -morphimIdom sub_morphim_pre ?subsetIl //. rewrite setIA (setIidPr sGH) (sameP setIidPr eqP) (setIidPl _) // eq_sym. exact: eqP. Qed. Lemma ker_factm_loc (K : {group aT}) : 'ker_(q @* K) ff = q @* 'ker_K f. Proof. by rewrite ker_factm -morphimIG. Qed. End FactorMorphism. Prenex Implicits factm. Section InverseMorphism. Variables aT rT : finGroupType. Implicit Types A B : {set aT}. Implicit Types C D : {set rT}. Variables (G : {group aT}) (f : {morphism G >-> rT}). Hypothesis injf : 'injm f. Lemma invm_subker : 'ker f \subset 'ker (idm G). Proof. by rewrite ker_idm. Qed. Definition invm := factm invm_subker (subxx _). Canonical invm_morphism := Eval hnf in [morphism of invm]. Lemma invmE : {in G, cancel f invm}. Proof. exact: factmE. Qed. Lemma invmK : {in f @* G, cancel invm f}. Proof. by move=> fx; case/morphimP=> x _ Gx ->; rewrite invmE. Qed. Lemma morphpre_invm A : invm @*^-1 A = f @* A. Proof. by rewrite morphpre_factm morphpre_idm morphimIdom. Qed. Lemma morphim_invm A : A \subset G -> invm @* (f @* A) = A. Proof. by move=> sAG; rewrite morphim_factm morphim_idm. Qed. Lemma morphim_invmE C : invm @* C = f @*^-1 C. Proof. rewrite -morphpreIdom -(morphim_invm (subsetIl _ _)). by rewrite morphimIdom -morphpreIim morphpreK (subsetIl, morphimIdom). Qed. Lemma injm_proper A B : A \subset G -> B \subset G -> (f @* A \proper f @* B) = (A \proper B). Proof. move=> dA dB; rewrite -morphpre_invm -(morphpre_invm B). by rewrite morphpre_proper ?morphim_invm. Qed. Lemma injm_invm : 'injm invm. Proof. by move/can_in_inj/injmP: invmK. Qed. Lemma ker_invm : 'ker invm = 1. Proof. by move/trivgP: injm_invm. Qed. Lemma im_invm : invm @* (f @* G) = G. Proof. exact: morphim_invm. Qed. End InverseMorphism. Prenex Implicits invm. Section InjFactm. Variables (gT aT rT : finGroupType) (D G : {group gT}). Variables (g : {morphism G >-> rT}) (f : {morphism D >-> aT}) (injf : 'injm f). Definition ifactm := tag (domP [morphism of g \o invm injf] (morphpre_invm injf G)). Lemma ifactmE : {in D, forall x, ifactm (f x) = g x}. Proof. rewrite /ifactm => x Dx; case: domP => f' /= [def_f' _ _ _]. by rewrite {f'}def_f' //= invmE. Qed. Lemma morphim_ifactm (A : {set gT}) : A \subset D -> ifactm @* (f @* A) = g @* A. Proof. rewrite /ifactm => sAD; case: domP => _ /= [_ _ _ ->]. by rewrite morphim_comp morphim_invm. Qed. Lemma im_ifactm : G \subset D -> ifactm @* (f @* G) = g @* G. Proof. exact: morphim_ifactm. Qed. Lemma morphpre_ifactm C : ifactm @*^-1 C = f @* (g @*^-1 C). Proof. rewrite /ifactm; case: domP => _ /= [_ _ -> _]. by rewrite morphpre_comp morphpre_invm. Qed. Lemma ker_ifactm : 'ker ifactm = f @* 'ker g. Proof. exact: morphpre_ifactm. Qed. Lemma injm_ifactm : 'injm g -> 'injm ifactm. Proof. by rewrite ker_ifactm => /trivgP->; rewrite morphim1. Qed. End InjFactm. (* Reflected (boolean) form of morphism and isomorphism properties. *) Section ReflectProp. Variables aT rT : finGroupType. Section Defs. Variables (A : {set aT}) (B : {set rT}). (* morphic is the morphM property of morphisms seen through morphicP. *) Definition morphic (f : aT -> rT) := [forall u in [predX A & A], f (u.1 * u.2) == f u.1 * f u.2]. Definition isom f := f @: A^# == B^#. Definition misom f := morphic f && isom f. Definition isog := [exists f : {ffun aT -> rT}, misom f]. Section MorphicProps. Variable f : aT -> rT. Lemma morphicP : reflect {in A &, {morph f : x y / x * y}} (morphic f). Proof. apply: (iffP forallP) => [fM x y Ax Ay | fM [x y] /=]. by apply/eqP; have:= fM (x, y); rewrite inE /= Ax Ay. by apply/implyP=> /andP[Ax Ay]; rewrite fM. Qed. Definition morphm of morphic f := f : aT -> FinGroup.sort rT. Lemma morphmE fM : morphm fM = f. Proof. by []. Qed. Canonical morphm_morphism fM := @Morphism _ _ A (morphm fM) (morphicP fM). End MorphicProps. Lemma misomP f : reflect {fM : morphic f & isom (morphm fM)} (misom f). Proof. by apply: (iffP andP) => [] [fM fiso] //; exists fM. Qed. Lemma misom_isog f : misom f -> isog. Proof. case/andP=> fM iso_f; apply/existsP; exists (finfun f). apply/andP; split; last by rewrite /misom /isom !(eq_imset _ (ffunE f)). by apply/forallP=> u; rewrite !ffunE; apply: forallP fM u. Qed. Lemma isom_isog (D : {group aT}) (f : {morphism D >-> rT}) : A \subset D -> isom f -> isog. Proof. move=> sAD isof; apply: (@misom_isog f); rewrite /misom isof andbT. by apply/morphicP; apply: (sub_in2 (subsetP sAD) (morphM f)). Qed. Lemma isog_isom : isog -> {f : {morphism A >-> rT} | isom f}. Proof. by case/existsP/sigW=> f /misomP[fM isom_f]; exists (morphm_morphism fM). Qed. End Defs. Infix "\isog" := isog. Arguments isom_isog [A B D]. (* The real reflection properties only hold for true groups and morphisms. *) Section Main. Variables (G : {group aT}) (H : {group rT}). Lemma isomP (f : {morphism G >-> rT}) : reflect ('injm f /\ f @* G = H) (isom G H f). Proof. apply: (iffP eqP) => [eqfGH | [injf <-]]; last first. by rewrite -injmD1 // morphimEsub ?subsetDl. split. apply/subsetP=> x /morphpreP[Gx fx1]; have: f x \notin H^# by rewrite inE fx1. by apply: contraR => ntx; rewrite -eqfGH imset_f // inE ntx. rewrite morphimEdom -{2}(setD1K (group1 G)) imsetU eqfGH. by rewrite imset_set1 morph1 setD1K. Qed. Lemma isogP : reflect (exists2 f : {morphism G >-> rT}, 'injm f & f @* G = H) (G \isog H). Proof. apply: (iffP idP) => [/isog_isom[f /isomP[]] | [f injf fG]]; first by exists f. by apply: (isom_isog f) => //; apply/isomP. Qed. Variable f : {morphism G >-> rT}. Hypothesis isoGH : isom G H f. Lemma isom_inj : 'injm f. Proof. by have /isomP[] := isoGH. Qed. Lemma isom_im : f @* G = H. Proof. by have /isomP[] := isoGH. Qed. Lemma isom_card : #|G| = #|H|. Proof. by rewrite -isom_im card_injm ?isom_inj. Qed. Lemma isom_sub_im : H \subset f @* G. Proof. by rewrite isom_im. Qed. Definition isom_inv := restrm isom_sub_im (invm isom_inj). End Main. Variables (G : {group aT}) (f : {morphism G >-> rT}). Lemma morphim_isom (H : {group aT}) (K : {group rT}) : H \subset G -> isom H K f -> f @* H = K. Proof. by case/(restrmP f)=> g [gf _ _ <- //]; rewrite -gf; case/isomP. Qed. Lemma sub_isom (A : {set aT}) (C : {set rT}) : A \subset G -> f @* A = C -> 'injm f -> isom A C f. Proof. move=> sAG; case: (restrmP f sAG) => g [_ _ _ img] <-{C} injf. rewrite /isom -morphimEsub ?morphimDG ?morphim1 //. by rewrite subDset setUC subsetU ?sAG. Qed. Lemma sub_isog (A : {set aT}) : A \subset G -> 'injm f -> isog A (f @* A). Proof. by move=> sAG injf; apply: (isom_isog f sAG); apply: sub_isom. Qed. Lemma restr_isom_to (A : {set aT}) (C R : {group rT}) (sAG : A \subset G) : f @* A = C -> isom G R f -> isom A C (restrm sAG f). Proof. by move=> defC /isomP[inj_f _]; apply: sub_isom. Qed. Lemma restr_isom (A : {group aT}) (R : {group rT}) (sAG : A \subset G) : isom G R f -> isom A (f @* A) (restrm sAG f). Proof. exact: restr_isom_to. Qed. End ReflectProp. Arguments isom {_ _} _%_g _%_g _. Arguments morphic {_ _} _%_g _. Arguments misom _ _ _%_g _%_g _. Arguments isog {_ _} _%_g _%_g. Arguments morphicP {aT rT A f}. Arguments misomP {aT rT A B f}. Arguments isom_isog [aT rT A B D]. Arguments isomP {aT rT G H f}. Arguments isogP {aT rT G H}. Prenex Implicits morphm. Notation "x \isog y":= (isog x y). Section Isomorphisms. Variables gT hT kT : finGroupType. Variables (G : {group gT}) (H : {group hT}) (K : {group kT}). Lemma idm_isom : isom G G (idm G). Proof. exact: sub_isom (im_idm G) (injm_idm G). Qed. Lemma isog_refl : G \isog G. Proof. exact: isom_isog idm_isom. Qed. Lemma card_isog : G \isog H -> #|G| = #|H|. Proof. by case/isogP=> f injf <-; apply: isom_card (f) _; apply/isomP. Qed. Lemma isog_abelian : G \isog H -> abelian G = abelian H. Proof. by case/isogP=> f injf <-; rewrite injm_abelian. Qed. Lemma trivial_isog : G :=: 1 -> H :=: 1 -> G \isog H. Proof. move=> -> ->; apply/isogP. exists [morphism of @trivm gT hT 1]; rewrite /= ?morphim1 //. by rewrite ker_trivm; apply: subxx. Qed. Lemma isog_eq1 : G \isog H -> (G :==: 1) = (H :==: 1). Proof. by move=> isoGH; rewrite !trivg_card1 card_isog. Qed. Lemma isom_sym (f : {morphism G >-> hT}) (isoGH : isom G H f) : isom H G (isom_inv isoGH). Proof. rewrite sub_isom 1?injm_restrm ?injm_invm // im_restrm. by rewrite -(isom_im isoGH) im_invm. Qed. Lemma isog_symr : G \isog H -> H \isog G. Proof. by case/isog_isom=> f /isom_sym/isom_isog->. Qed. Lemma isog_trans : G \isog H -> H \isog K -> G \isog K. Proof. case/isogP=> f injf <-; case/isogP=> g injg <-. have defG: f @*^-1 (f @* G) = G by rewrite morphimGK ?subsetIl. rewrite -morphim_comp -{1 8}defG. by apply/isogP; exists [morphism of g \o f]; rewrite ?injm_comp. Qed. Lemma nclasses_isog : G \isog H -> #|classes G| = #|classes H|. Proof. by case/isogP=> f injf <-; rewrite nclasses_injm. Qed. End Isomorphisms. Section IsoBoolEquiv. Variables gT hT kT : finGroupType. Variables (G : {group gT}) (H : {group hT}) (K : {group kT}). Lemma isog_sym : (G \isog H) = (H \isog G). Proof. by apply/idP/idP; apply: isog_symr. Qed. Lemma isog_transl : G \isog H -> (G \isog K) = (H \isog K). Proof. by move=> iso; apply/idP/idP; apply: isog_trans; rewrite // -isog_sym. Qed. Lemma isog_transr : G \isog H -> (K \isog G) = (K \isog H). Proof. by move=> iso; apply/idP/idP; move/isog_trans; apply; rewrite // -isog_sym. Qed. End IsoBoolEquiv. Section Homg. Implicit Types rT gT aT : finGroupType. Definition homg rT aT (C : {set rT}) (D : {set aT}) := [exists (f : {ffun aT -> rT} | morphic D f), f @: D == C]. Lemma homgP rT aT (C : {set rT}) (D : {set aT}) : reflect (exists f : {morphism D >-> rT}, f @* D = C) (homg C D). Proof. apply: (iffP exists_eq_inP) => [[f fM <-] | [f <-]]. by exists (morphm_morphism fM); rewrite /morphim /= setIid. exists (finfun f); first by apply/morphicP=> x y Dx Dy; rewrite !ffunE morphM. by rewrite /morphim setIid; apply: eq_imset => x; rewrite ffunE. Qed. Lemma morphim_homg aT rT (A D : {set aT}) (f : {morphism D >-> rT}) : A \subset D -> homg (f @* A) A. Proof. move=> sAD; apply/homgP; exists (restrm_morphism sAD f). by rewrite morphim_restrm setIid. Qed. Lemma leq_homg rT aT (C : {set rT}) (G : {group aT}) : homg C G -> #|C| <= #|G|. Proof. by case/homgP=> f <-; apply: leq_morphim. Qed. Lemma homg_refl aT (A : {set aT}) : homg A A. Proof. by apply/homgP; exists (idm_morphism A); rewrite im_idm. Qed. Lemma homg_trans aT (B : {set aT}) rT (C : {set rT}) gT (G : {group gT}) : homg C B -> homg B G -> homg C G. Proof. move=> homCB homBG; case/homgP: homBG homCB => fG <- /homgP[fK <-]. by rewrite -morphim_comp morphim_homg // -sub_morphim_pre. Qed. Lemma isogEcard rT aT (G : {group rT}) (H : {group aT}) : (G \isog H) = (homg G H) && (#|H| <= #|G|). Proof. rewrite isog_sym; apply/isogP/andP=> [[f injf <-] | []]. by rewrite leq_eqVlt eq_sym card_im_injm injf morphim_homg. case/homgP=> f <-; rewrite leq_eqVlt eq_sym card_im_injm. by rewrite ltnNge leq_morphim orbF; exists f. Qed. Lemma isog_hom rT aT (G : {group rT}) (H : {group aT}) : G \isog H -> homg G H. Proof. by rewrite isogEcard; case/andP. Qed. Lemma isogEhom rT aT (G : {group rT}) (H : {group aT}) : (G \isog H) = homg G H && homg H G. Proof. apply/idP/andP=> [isoGH | [homGH homHG]]. by rewrite !isog_hom // isog_sym. by rewrite isogEcard homGH leq_homg. Qed. Lemma eq_homgl gT aT rT (G : {group gT}) (H : {group aT}) (K : {group rT}) : G \isog H -> homg G K = homg H K. Proof. by rewrite isogEhom => /andP[homGH homHG]; apply/idP/idP; apply: homg_trans. Qed. Lemma eq_homgr gT rT aT (G : {group gT}) (H : {group rT}) (K : {group aT}) : G \isog H -> homg K G = homg K H. Proof. rewrite isogEhom => /andP[homGH homHG]. by apply/idP/idP=> homK; apply: homg_trans homK _. Qed. End Homg. Arguments homg _ _ _%_g _%_g. Notation "G \homg H" := (homg G H) (at level 70, no associativity) : group_scope. Arguments homgP {rT aT C D}. (* Isomorphism between a group and its subtype. *) Section SubMorphism. Variables (gT : finGroupType) (G : {group gT}). Canonical sgval_morphism := Morphism (@sgvalM _ G). Canonical subg_morphism := Morphism (@subgM _ G). Lemma injm_sgval : 'injm sgval. Proof. exact/injmP/(in2W subg_inj). Qed. Lemma injm_subg : 'injm (subg G). Proof. exact/injmP/(can_in_inj subgK). Qed. Hint Resolve injm_sgval injm_subg : core. Lemma ker_sgval : 'ker sgval = 1. Proof. exact/trivgP. Qed. Lemma ker_subg : 'ker (subg G) = 1. Proof. exact/trivgP. Qed. Lemma im_subg : subg G @* G = [subg G]. Proof. apply/eqP; rewrite -subTset morphimEdom. by apply/subsetP=> u _; rewrite -(sgvalK u) imset_f ?subgP. Qed. Lemma sgval_sub A : sgval @* A \subset G. Proof. by apply/subsetP=> x; case/imsetP=> u _ ->; apply: subgP. Qed. Lemma sgvalmK A : subg G @* (sgval @* A) = A. Proof. apply/eqP; rewrite eqEcard !card_injm ?subsetT ?sgval_sub // leqnn andbT. rewrite -morphim_comp; apply/subsetP=> _ /morphimP[v _ Av ->] /=. by rewrite sgvalK. Qed. Lemma subgmK (A : {set gT}) : A \subset G -> sgval @* (subg G @* A) = A. Proof. move=> sAG; apply/eqP; rewrite eqEcard !card_injm ?subsetT //. rewrite leqnn andbT -morphim_comp morphimE /= morphpreT. by apply/subsetP=> _ /morphimP[v Gv Av ->] /=; rewrite subgK. Qed. Lemma im_sgval : sgval @* [subg G] = G. Proof. by rewrite -{2}im_subg subgmK. Qed. Lemma isom_subg : isom G [subg G] (subg G). Proof. by apply/isomP; rewrite im_subg. Qed. Lemma isom_sgval : isom [subg G] G sgval. Proof. by apply/isomP; rewrite im_sgval. Qed. Lemma isog_subg : isog G [subg G]. Proof. exact: isom_isog isom_subg. Qed. End SubMorphism. Arguments sgvalmK {gT G} A. Arguments subgmK {gT G} [A] sAG.
Factorial.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Data.Nat.Prime.Basic /-! # Prime natural numbers and the factorial operator -/ open Bool Subtype open Nat namespace Nat theorem Prime.dvd_factorial : ∀ {n p : ℕ} (_ : Prime p), p ∣ n ! ↔ p ≤ n | 0, _, hp => iff_of_false hp.not_dvd_one (not_le_of_gt hp.pos) | n + 1, p, hp => by rw [factorial_succ, hp.dvd_mul, Prime.dvd_factorial hp] exact ⟨fun h => h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, fun h => (_root_.lt_or_eq_of_le h).elim (Or.inr ∘ le_of_lt_succ) fun h => Or.inl <| by rw [h]⟩ theorem coprime_factorial_iff {m n : ℕ} (hm : m ≠ 1) : m.Coprime n ! ↔ n < m.minFac := by rw [← not_le, iff_not_comm, Nat.Prime.not_coprime_iff_dvd] constructor · intro h exact ⟨m.minFac, minFac_prime hm, minFac_dvd m, Nat.dvd_factorial (minFac_pos m) h⟩ · rintro ⟨p, hp, hdvd, hdvd'⟩ exact le_trans (minFac_le_of_dvd hp.two_le hdvd) (hp.dvd_factorial.mp hdvd') end Nat
Basic.lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import Mathlib.Algebra.MvPolynomial.Counit import Mathlib.Algebra.MvPolynomial.Invertible import Mathlib.RingTheory.WittVector.Defs /-! # Witt vectors This file verifies that the ring operations on `WittVector p R` satisfy the axioms of a commutative ring. ## Main definitions * `WittVector.map`: lifts a ring homomorphism `R →+* S` to a ring homomorphism `𝕎 R →+* 𝕎 S`. * `WittVector.ghostComponent n x`: evaluates the `n`th Witt polynomial on the first `n` coefficients of `x`, producing a value in `R`. This is a ring homomorphism. * `WittVector.ghostMap`: a ring homomorphism `𝕎 R →+* (ℕ → R)`, obtained by packaging all the ghost components together. If `p` is invertible in `R`, then the ghost map is an equivalence, which we use to define the ring operations on `𝕎 R`. * `WittVector.CommRing`: the ring structure induced by the ghost components. ## Notation We use notation `𝕎 R`, entered `\bbW`, for the Witt vectors over `R`. ## Implementation details As we prove that the ghost components respect the ring operations, we face a number of repetitive proofs. To avoid duplicating code we factor these proofs into a custom tactic, only slightly more powerful than a tactic macro. This tactic is not particularly useful outside of its applications in this file. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ noncomputable section open MvPolynomial Function variable {p : ℕ} {R S : Type*} [CommRing R] [CommRing S] variable {α : Type*} {β : Type*} local notation "𝕎" => WittVector p local notation "W_" => wittPolynomial p -- type as `\bbW` open scoped Witt namespace WittVector /-- `f : α → β` induces a map from `𝕎 α` to `𝕎 β` by applying `f` componentwise. If `f` is a ring homomorphism, then so is `f`, see `WittVector.map f`. -/ def mapFun (f : α → β) : 𝕎 α → 𝕎 β := fun x => mk _ (f ∘ x.coeff) namespace mapFun -- Porting note: switched the proof to tactic mode. I think that `ext` was the issue. theorem injective (f : α → β) (hf : Injective f) : Injective (mapFun f : 𝕎 α → 𝕎 β) := by intros _ _ h ext p exact hf (congr_arg (fun x => coeff x p) h :) theorem surjective (f : α → β) (hf : Surjective f) : Surjective (mapFun f : 𝕎 α → 𝕎 β) := fun x => ⟨mk _ fun n => Classical.choose <| hf <| x.coeff n, by ext n; simp only [mapFun, coeff_mk, comp_apply, Classical.choose_spec (hf (x.coeff n))]⟩ /-- Auxiliary tactic for showing that `mapFun` respects the ring operations. -/ -- porting note: a very crude port. macro "map_fun_tac" : tactic => `(tactic| ( ext n simp only [mapFun, mk, comp_apply, zero_coeff, map_zero, -- Porting note: the lemmas on the next line do not have the `simp` tag in mathlib4 add_coeff, sub_coeff, mul_coeff, neg_coeff, nsmul_coeff, zsmul_coeff, pow_coeff, peval, map_aeval, algebraMap_int_eq, coe_eval₂Hom] <;> try { cases n <;> simp <;> done } <;> -- Porting note: this line solves `one` apply eval₂Hom_congr (RingHom.ext_int _ _) _ rfl <;> ext ⟨i, k⟩ <;> fin_cases i <;> rfl)) variable [Fact p.Prime] -- Porting note: using `(x y : 𝕎 R)` instead of `(x y : WittVector p R)` produced sorries. variable (f : R →+* S) (x y : WittVector p R) -- and until `pow`. -- We do not tag these lemmas as `@[simp]` because they will be bundled in `map` later on. theorem zero : mapFun f (0 : 𝕎 R) = 0 := by map_fun_tac theorem one : mapFun f (1 : 𝕎 R) = 1 := by map_fun_tac theorem add : mapFun f (x + y) = mapFun f x + mapFun f y := by map_fun_tac theorem sub : mapFun f (x - y) = mapFun f x - mapFun f y := by map_fun_tac theorem mul : mapFun f (x * y) = mapFun f x * mapFun f y := by map_fun_tac theorem neg : mapFun f (-x) = -mapFun f x := by map_fun_tac theorem nsmul (n : ℕ) (x : WittVector p R) : mapFun f (n • x) = n • mapFun f x := by map_fun_tac theorem zsmul (z : ℤ) (x : WittVector p R) : mapFun f (z • x) = z • mapFun f x := by map_fun_tac theorem pow (n : ℕ) : mapFun f (x ^ n) = mapFun f x ^ n := by map_fun_tac theorem natCast (n : ℕ) : mapFun f (n : 𝕎 R) = n := show mapFun f n.unaryCast = (n : WittVector p S) by induction n <;> simp [*, Nat.unaryCast, add, one, zero] <;> rfl theorem intCast (n : ℤ) : mapFun f (n : 𝕎 R) = n := show mapFun f n.castDef = (n : WittVector p S) by cases n <;> simp [*, Int.castDef, neg, natCast] <;> rfl end mapFun end WittVector namespace WittVector /-- Evaluates the `n`th Witt polynomial on the first `n` coefficients of `x`, producing a value in `R`. This function will be bundled as the ring homomorphism `WittVector.ghostMap` once the ring structure is available, but we rely on it to set up the ring structure in the first place. -/ private def ghostFun : 𝕎 R → ℕ → R := fun x n => aeval x.coeff (W_ ℤ n) section Tactic open Lean Elab Tactic /-- An auxiliary tactic for proving that `ghostFun` respects the ring operations. -/ elab "ghost_fun_tac " φ:term ", " fn:term : tactic => do evalTactic (← `(tactic| ( ext n have := congr_fun (congr_arg (@peval R _ _) (wittStructureInt_prop p $φ n)) $fn simp only [wittZero, OfNat.ofNat, Zero.zero, wittOne, One.one, HAdd.hAdd, Add.add, HSub.hSub, Sub.sub, Neg.neg, HMul.hMul, Mul.mul, HPow.hPow, Pow.pow, wittNSMul, wittZSMul, HSMul.hSMul, SMul.smul] simpa +unfoldPartialApp [WittVector.ghostFun, aeval_rename, aeval_bind₁, comp, uncurry, peval, eval] using this ))) end Tactic section GhostFun -- The following lemmas are not `@[simp]` because they will be bundled in `ghostMap` later on. @[local simp] theorem matrix_vecEmpty_coeff {R} (i j) : @coeff p R (Matrix.vecEmpty i) j = (Matrix.vecEmpty i : ℕ → R) j := by rcases i with ⟨_ | _ | _ | _ | i_val, ⟨⟩⟩ variable [Fact p.Prime] variable (x y : WittVector p R) private theorem ghostFun_zero : ghostFun (0 : 𝕎 R) = 0 := by ghost_fun_tac 0, ![] private theorem ghostFun_one : ghostFun (1 : 𝕎 R) = 1 := by ghost_fun_tac 1, ![] private theorem ghostFun_add : ghostFun (x + y) = ghostFun x + ghostFun y := by ghost_fun_tac X 0 + X 1, ![x.coeff, y.coeff] private theorem ghostFun_natCast (i : ℕ) : ghostFun (i : 𝕎 R) = i := show ghostFun i.unaryCast = _ by induction i <;> simp [*, Nat.unaryCast, ghostFun_zero, ghostFun_one, ghostFun_add] private theorem ghostFun_sub : ghostFun (x - y) = ghostFun x - ghostFun y := by ghost_fun_tac X 0 - X 1, ![x.coeff, y.coeff] private theorem ghostFun_mul : ghostFun (x * y) = ghostFun x * ghostFun y := by ghost_fun_tac X 0 * X 1, ![x.coeff, y.coeff] private theorem ghostFun_neg : ghostFun (-x) = -ghostFun x := by ghost_fun_tac -X 0, ![x.coeff] private theorem ghostFun_intCast (i : ℤ) : ghostFun (i : 𝕎 R) = i := show ghostFun i.castDef = _ by cases i <;> simp [*, Int.castDef, ghostFun_natCast, ghostFun_neg] private lemma ghostFun_nsmul (m : ℕ) (x : WittVector p R) : ghostFun (m • x) = m • ghostFun x := by ghost_fun_tac m • (X 0), ![x.coeff] private lemma ghostFun_zsmul (m : ℤ) (x : WittVector p R) : ghostFun (m • x) = m • ghostFun x := by ghost_fun_tac m • (X 0), ![x.coeff] private theorem ghostFun_pow (m : ℕ) : ghostFun (x ^ m) = ghostFun x ^ m := by ghost_fun_tac X 0 ^ m, ![x.coeff] end GhostFun variable (p) (R) /-- The bijection between `𝕎 R` and `ℕ → R`, under the assumption that `p` is invertible in `R`. In `WittVector.ghostEquiv` we upgrade this to an isomorphism of rings. -/ private def ghostEquiv' [Invertible (p : R)] : 𝕎 R ≃ (ℕ → R) where toFun := ghostFun invFun x := mk p fun n => aeval x (xInTermsOfW p R n) left_inv := by intro x ext n have := bind₁_wittPolynomial_xInTermsOfW p R n apply_fun aeval x.coeff at this simpa +unfoldPartialApp only [aeval_bind₁, aeval_X, ghostFun, aeval_wittPolynomial] right_inv := by intro x ext n have := bind₁_xInTermsOfW_wittPolynomial p R n apply_fun aeval x at this simpa only [aeval_bind₁, aeval_X, ghostFun, aeval_wittPolynomial] variable [Fact p.Prime] @[local instance] private def comm_ring_aux₁ : CommRing (𝕎 (MvPolynomial R ℚ)) := (ghostEquiv' p (MvPolynomial R ℚ)).injective.commRing ghostFun ghostFun_zero ghostFun_one ghostFun_add ghostFun_mul ghostFun_neg ghostFun_sub ghostFun_nsmul ghostFun_zsmul ghostFun_pow ghostFun_natCast ghostFun_intCast @[local instance] private abbrev comm_ring_aux₂ : CommRing (𝕎 (MvPolynomial R ℤ)) := (mapFun.injective _ <| map_injective (Int.castRingHom ℚ) Int.cast_injective).commRing _ (mapFun.zero _) (mapFun.one _) (mapFun.add _) (mapFun.mul _) (mapFun.neg _) (mapFun.sub _) (mapFun.nsmul _) (mapFun.zsmul _) (mapFun.pow _) (mapFun.natCast _) (mapFun.intCast _) /-- The commutative ring structure on `𝕎 R`. -/ instance : CommRing (𝕎 R) := (mapFun.surjective _ <| counit_surjective _).commRing (mapFun <| MvPolynomial.counit _) (mapFun.zero _) (mapFun.one _) (mapFun.add _) (mapFun.mul _) (mapFun.neg _) (mapFun.sub _) (mapFun.nsmul _) (mapFun.zsmul _) (mapFun.pow _) (mapFun.natCast _) (mapFun.intCast _) variable {p R} /-- `WittVector.map f` is the ring homomorphism `𝕎 R →+* 𝕎 S` naturally induced by a ring homomorphism `f : R →+* S`. It acts coefficientwise. -/ noncomputable def map (f : R →+* S) : 𝕎 R →+* 𝕎 S where toFun := mapFun f map_zero' := mapFun.zero f map_one' := mapFun.one f map_add' := mapFun.add f map_mul' := mapFun.mul f theorem map_injective (f : R →+* S) (hf : Injective f) : Injective (map f : 𝕎 R → 𝕎 S) := mapFun.injective f hf theorem map_surjective (f : R →+* S) (hf : Surjective f) : Surjective (map f : 𝕎 R → 𝕎 S) := mapFun.surjective f hf @[simp] theorem map_coeff (f : R →+* S) (x : 𝕎 R) (n : ℕ) : (map f x).coeff n = f (x.coeff n) := rfl /-- `WittVector.ghostMap` is a ring homomorphism that maps each Witt vector to the sequence of its ghost components. -/ def ghostMap : 𝕎 R →+* ℕ → R where toFun := ghostFun map_zero' := ghostFun_zero map_one' := ghostFun_one map_add' := ghostFun_add map_mul' := ghostFun_mul /-- Evaluates the `n`th Witt polynomial on the first `n` coefficients of `x`, producing a value in `R`. -/ def ghostComponent (n : ℕ) : 𝕎 R →+* R := (Pi.evalRingHom _ n).comp ghostMap theorem ghostComponent_apply (n : ℕ) (x : 𝕎 R) : ghostComponent n x = aeval x.coeff (W_ ℤ n) := rfl @[simp] theorem ghostMap_apply (x : 𝕎 R) (n : ℕ) : ghostMap x n = ghostComponent n x := rfl section Invertible variable (p R) variable [Invertible (p : R)] /-- `WittVector.ghostMap` is a ring isomorphism when `p` is invertible in `R`. -/ def ghostEquiv : 𝕎 R ≃+* (ℕ → R) := { (ghostMap : 𝕎 R →+* ℕ → R), ghostEquiv' p R with } @[simp] theorem ghostEquiv_coe : (ghostEquiv p R : 𝕎 R →+* ℕ → R) = ghostMap := rfl theorem ghostMap.bijective_of_invertible : Function.Bijective (ghostMap : 𝕎 R → ℕ → R) := (ghostEquiv p R).bijective end Invertible /-- `WittVector.coeff x 0` as a `RingHom` -/ @[simps] noncomputable def constantCoeff : 𝕎 R →+* R where toFun x := x.coeff 0 map_zero' := by simp map_one' := by simp map_add' := add_coeff_zero map_mul' := mul_coeff_zero instance [Nontrivial R] : Nontrivial (𝕎 R) := constantCoeff.domain_nontrivial end WittVector
rat.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 choice. From mathcomp Require Import prime fintype finfun bigop order tuple ssralg. From mathcomp Require Import countalg div ssrnum ssrint archimedean poly zmodp. From mathcomp Require Import polydiv intdiv matrix mxalgebra vector. (******************************************************************************) (* This file defines a datatype for rational numbers and equips it with a *) (* structure of archimedean, real field, with int and nat declared as closed *) (* subrings. *) (* rat == the type of rational number, with single constructor Rat *) (* <number> == <number> as a rat with <number> a decimal constant. *) (* This notation is in rat_scope (delimited with %Q). *) (* n%:Q == explicit cast from int to rat, ie. the specialization to *) (* rationals of the generic ring morphism n%:~R *) (* numq r == numerator of (r : rat) *) (* denq r == denominator of (r : rat) *) (* ratr r == generic embedding of (r : rat) into an arbitrary unit ring.*) (* [rat x // y] == smart constructor for rationals, definitionally equal *) (* to x / y for concrete values, intended for printing only *) (* of normal forms. The parsable notation is for debugging. *) (* inIntSpan X v <-> v is an integral linear combination of elements of *) (* X : seq V, where V is a zmodType. We prove that this is a *) (* decidable property for Q-vector spaces. *) (******************************************************************************) Import Order.TTheory GRing.Theory Num.Theory. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "[ 'rat' x // y ]" (format "[ 'rat' x // y ]"). Reserved Notation "n %:Q" (left associativity, format "n %:Q"). Local Open Scope ring_scope. Local Notation sgr := Num.sg. Record rat : Set := Rat { valq : (int * int); _ : (0 < valq.2) && coprime `|valq.1| `|valq.2| }. Bind Scope ring_scope with rat. Delimit Scope rat_scope with Q. Definition ratz (n : int) := @Rat (n, 1) (coprimen1 _). (* Coercion ratz (n : int) := @Rat (n, 1) (coprimen1 _). *) Definition rat_isSub := Eval hnf in [isSub for valq]. HB.instance Definition _ := rat_isSub. #[hnf] HB.instance Definition _ := [Equality of rat by <:]. HB.instance Definition _ := [Countable of rat by <:]. Definition numq x := (valq x).1. Definition denq x := (valq x).2. Arguments numq : simpl never. Arguments denq : simpl never. Lemma denq_gt0 x : 0 < denq x. Proof. by rewrite /denq; case: x=> [[a b] /= /andP []]. Qed. #[global] Hint Resolve denq_gt0 : core. Definition denq_ge0 x := ltW (denq_gt0 x). Lemma denq_lt0 x : (denq x < 0) = false. Proof. by rewrite lt_gtF. Qed. Lemma denq_neq0 x : denq x != 0. Proof. by rewrite /denq gt_eqF ?denq_gt0. Qed. #[global] Hint Resolve denq_neq0 : core. Lemma denq_eq0 x : (denq x == 0) = false. Proof. exact: negPf (denq_neq0 _). Qed. Lemma coprime_num_den x : coprime `|numq x| `|denq x|. Proof. by rewrite /numq /denq; case: x=> [[a b] /= /andP []]. Qed. Fact RatK x P : @Rat (numq x, denq x) P = x. Proof. by move: x P => [[a b] P'] P; apply: val_inj. Qed. Definition fracq_subdef x := if x.2 != 0 then let g := gcdn `|x.1| `|x.2| in ((-1) ^ ((x.2 < 0) (+) (x.1 < 0)) * (`|x.1| %/ g)%:Z, (`|x.2| %/ g)%:Z) else (0, 1). Arguments fracq_subdef /. Definition fracq_opt_subdef (x : int * int) := if (0 < x.2) && coprime `|x.1| `|x.2| then x else fracq_subdef x. Lemma fracq_opt_subdefE x : fracq_opt_subdef x = fracq_subdef x. Proof. rewrite /fracq_opt_subdef; case: ifP => //; case: x => n d /= /andP[d_gt0 cnd]. rewrite /fracq_subdef gt_eqF//= lt_gtF//= (eqP cnd) !divn1 abszEsg gtz0_abs//. rewrite mulrA sgz_def mulrnAr -signr_addb addbb expr0. by have [->|] := eqVneq n 0; rewrite (mulr0, mul1r). Qed. Fact fracq_subproof x (y := fracq_opt_subdef x) : (0 < y.2) && (coprime `|y.1| `|y.2|). Proof. rewrite {}/y fracq_opt_subdefE /=; have [] //= := eqVneq x.2 0. case: x => [/= n d]; rewrite -absz_gt0 => dN0. have ggt0 : (0 < gcdn `|n| `|d|)%N by rewrite gcdn_gt0 dN0 orbT. rewrite ltz_nat divn_gt0// dvdn_leq ?dvdn_gcdr//=. rewrite abszM abszX abszN1 exp1n mul1n absz_nat. rewrite /coprime -(@eqn_pmul2r (gcdn `|n| `|d|))// mul1n. by rewrite muln_gcdl !divnK ?(dvdn_gcdl, dvdn_gcdr). Qed. Lemma fracq_opt_subdef_id x : fracq_opt_subdef (fracq_opt_subdef x) = fracq_subdef x. Proof. rewrite [fracq_opt_subdef (_ x)]/fracq_opt_subdef. by rewrite fracq_subproof fracq_opt_subdefE. Qed. (* We use a match expression in order to "lock" the definition of fracq. *) (* Indeed, the kernel will try to reduce a fracq only when applied to *) (* a term which has "enough" constructors: i.e. it reduces to a pair of *) (* a Posz or Negz on the first component, and a Posz of 0 or S, or a Negz *) (* on the second component. See issue #698. *) (* Additionally, we use fracq_opt_subdef to precompute the normal form *) (* before we use fracq_subproof in order to make sure the proof will be *) (* independent from the input of fracq. This ensure reflexivity of any *) (* computation involving rationals as long as all operators use fracq. *) (* As a consequence val (fracq x) = fracq_opt_subdef (fracq_opt_subdef x)) *) Definition fracq '((n', d')) : rat := match d', n' with | Posz 0 as d, _ as n => Rat (fracq_subproof (1, 0)) | _ as d, Posz _ as n | _ as d, _ as n => Rat (fracq_subproof (fracq_opt_subdef (n, d))) end. Arguments fracq : simpl never. (* Define a Number Notation for rat in rat_scope *) (* Since rat values obtained from fracq contain fracq_subdef, which is not *) (* an inductive constructor, we need to go through an intermediate *) (* inductive type. *) Variant Irat_prf := Ifracq_subproof : (int * int) -> Irat_prf. Variant Irat := IRat : (int * int) -> Irat_prf -> Irat. Definition parse (x : Number.number) : option Irat := let parse_pos i f := let nf := Decimal.nb_digits f in let d := (10 ^ nf)%nat in let n := (Nat.of_uint i * d + Nat.of_uint f)%nat in valq (fracq (Posz n, Posz d)) in let parse i f := match i with | Decimal.Pos i => parse_pos i f | Decimal.Neg i => let (n, d) := parse_pos i f in ((- n)%R, d) end in match x with | Number.Decimal (Decimal.Decimal i f) => let nd := parse i f in Some (IRat nd (Ifracq_subproof nd)) | Number.Decimal (Decimal.DecimalExp _ _ _) => None | Number.Hexadecimal _ => None end. Definition print (r : Irat) : option Number.number := let print_pos n d := if d == 1%nat then Some (Nat.to_uint n, Decimal.Nil) else let d2d5 := match prime_decomp d with | [:: (2, d2); (5, d5)] => Some (d2, d5) | [:: (2, d2)] => Some (d2, O) | [:: (5, d5)] => Some (O, d5) | _ => None end in match d2d5 with | Some (d2, d5) => let f := (2 ^ (d5 - d2) * 5 ^ (d2 - d5))%nat in let (i, f) := edivn (n * f) (d * f) in Some (Nat.to_uint i, Nat.to_uint f) | None => None end in let print_IRat nd := match nd with | (Posz n, Posz d) => match print_pos n d with | Some (i, f) => Some (Decimal.Pos i, f) | None => None end | (Negz n, Posz d) => match print_pos n.+1 d with | Some (i, f) => Some (Decimal.Neg i, f) | None => None end | (_, Negz _) => None end in match r with | IRat nd _ => match print_IRat nd with | Some (i, f) => Some (Number.Decimal (Decimal.Decimal i f)) | None => None end end. Number Notation rat parse print (via Irat mapping [Rat => IRat, fracq_subproof => Ifracq_subproof]) : rat_scope. (* Now, the following should parse as rat (and print unchanged) *) (* Check 12%Q. *) (* Check 3.14%Q. *) (* Check (-3.14)%Q. *) (* Check 0.5%Q. *) (* Check 0.2%Q. *) Lemma val_fracq x : val (fracq x) = fracq_subdef x. Proof. by case: x => [[n|n] [[|[|d]]|d]]//=; rewrite !fracq_opt_subdef_id. Qed. Lemma num_fracq x : numq (fracq x) = if x.2 != 0 then (-1) ^ ((x.2 < 0) (+) (x.1 < 0)) * (`|x.1| %/ gcdn `|x.1| `|x.2|)%:Z else 0. Proof. by rewrite /numq val_fracq/=; case: ifP. Qed. Lemma den_fracq x : denq (fracq x) = if x.2 != 0 then (`|x.2| %/ gcdn `|x.1| `|x.2|)%:Z else 1. Proof. by rewrite /denq val_fracq/=; case: ifP. Qed. Fact ratz_frac n : ratz n = fracq (n, 1). Proof. by apply: val_inj; rewrite val_fracq/= gcdn1 !divn1 abszE mulr_sign_norm. Qed. Fact valqK x : fracq (valq x) = x. Proof. move: x => [[n d] /= Pnd]; apply: val_inj; rewrite ?val_fracq/=. move: Pnd; rewrite /coprime /fracq /= => /andP[] hd -/eqP hnd. by rewrite lt_gtF ?gt_eqF //= hnd !divn1 mulz_sign_abs abszE gtr0_norm. Qed. Definition scalq '(n, d) := sgr d * (gcdn `|n| `|d|)%:Z. Lemma scalq_def x : scalq x = sgr x.2 * (gcdn `|x.1| `|x.2|)%:Z. Proof. by case: x. Qed. Fact scalq_eq0 x : (scalq x == 0) = (x.2 == 0). Proof. case: x => n d; rewrite scalq_def /= mulf_eq0 sgr_eq0 /= eqz_nat. rewrite -[gcdn _ _ == 0]negbK -lt0n gcdn_gt0 ?absz_gt0 [X in ~~ X]orbC. by case: sgrP. Qed. Lemma sgr_scalq x : sgr (scalq x) = sgr x.2. Proof. rewrite scalq_def sgrM sgr_id -[(gcdn _ _)%:Z]intz sgr_nat. by rewrite -lt0n gcdn_gt0 ?absz_gt0 orbC; case: sgrP; rewrite // mul0r. Qed. Lemma signr_scalq x : (scalq x < 0) = (x.2 < 0). Proof. by rewrite -!sgr_cp0 sgr_scalq. Qed. Lemma scalqE x : x.2 != 0 -> scalq x = (-1) ^+ (x.2 < 0)%R * (gcdn `|x.1| `|x.2|)%:Z. Proof. by rewrite scalq_def; case: sgrP. Qed. Fact valq_frac x : x.2 != 0 -> x = (scalq x * numq (fracq x), scalq x * denq (fracq x)). Proof. move=> x2_neq0; rewrite scalqE//; move: x2_neq0. case: x => [n d] /= d_neq0; rewrite num_fracq den_fracq/= ?d_neq0. rewrite mulr_signM -mulrA -!PoszM addKb. do 2!rewrite muln_divCA ?(dvdn_gcdl, dvdn_gcdr) // divnn. by rewrite gcdn_gt0 !absz_gt0 d_neq0 orbT !muln1 !mulz_sign_abs. Qed. Definition zeroq := 0%Q. Definition oneq := 1%Q. Fact frac0q x : fracq (0, x) = zeroq. Proof. apply: val_inj; rewrite //= val_fracq/= div0n !gcd0n !mulr0 !divnn. by have [//|x_neq0] := eqVneq; rewrite absz_gt0 x_neq0. Qed. Fact fracq0 x : fracq (x, 0) = zeroq. Proof. exact/eqP. Qed. Variant fracq_spec (x : int * int) : int * int -> rat -> Type := | FracqSpecN of x.2 = 0 : fracq_spec x (x.1, 0) zeroq | FracqSpecP k fx of k != 0 : fracq_spec x (k * numq fx, k * denq fx) fx. Fact fracqP x : fracq_spec x x (fracq x). Proof. case: x => n d /=; have [d_eq0 | d_neq0] := eqVneq d 0. by rewrite d_eq0 fracq0; constructor. by rewrite {2}[(_, _)]valq_frac //; constructor; rewrite scalq_eq0. Qed. Lemma rat_eqE x y : (x == y) = (numq x == numq y) && (denq x == denq y). Proof. rewrite -val_eqE [val x]surjective_pairing [val y]surjective_pairing /=. by rewrite xpair_eqE. Qed. Lemma sgr_denq x : sgr (denq x) = 1. Proof. by apply/eqP; rewrite sgr_cp0. Qed. Lemma normr_denq x : `|denq x| = denq x. Proof. by rewrite gtr0_norm. Qed. Lemma absz_denq x : `|denq x|%N = denq x :> int. Proof. by rewrite abszE normr_denq. Qed. Lemma rat_eq x y : (x == y) = (numq x * denq y == numq y * denq x). Proof. symmetry; rewrite rat_eqE andbC. have [->|] /= := eqVneq (denq _); first by rewrite (inj_eq (mulIf _)). apply: contraNF => /eqP hxy; rewrite -absz_denq -[eqbRHS]absz_denq. rewrite eqz_nat /= eqn_dvd. rewrite -(@Gauss_dvdr _ `|numq x|) 1?coprime_sym ?coprime_num_den // andbC. rewrite -(@Gauss_dvdr _ `|numq y|) 1?coprime_sym ?coprime_num_den //. by rewrite -!abszM hxy -{1}hxy !abszM !dvdn_mull ?dvdnn. Qed. Fact fracq_eq x y : x.2 != 0 -> y.2 != 0 -> (fracq x == fracq y) = (x.1 * y.2 == y.1 * x.2). Proof. case: fracqP=> //= u fx u_neq0 _; case: fracqP=> //= v fy v_neq0 _; symmetry. rewrite [eqbRHS]mulrC mulrACA [eqbRHS]mulrACA. by rewrite [denq _ * _]mulrC (inj_eq (mulfI _)) ?mulf_neq0 // rat_eq. Qed. Fact fracq_eq0 x : (fracq x == zeroq) = (x.1 == 0) || (x.2 == 0). Proof. move: x=> [n d] /=; have [->|d0] := eqVneq d 0. by rewrite fracq0 eqxx orbT. by rewrite -[zeroq]valqK orbF fracq_eq ?d0 //= mulr1 mul0r. Qed. Fact fracqMM x n d : x != 0 -> fracq (x * n, x * d) = fracq (n, d). Proof. move=> x_neq0; apply/eqP. have [->|d_neq0] := eqVneq d 0; first by rewrite mulr0 !fracq0. by rewrite fracq_eq ?mulf_neq0 //= mulrCA mulrA. Qed. (* We "lock" the definition of addq, oppq, mulq and invq, using a match on *) (* the constructor Rat for both arguments, so that it may only be reduced *) (* when applied to explicit rationals. Since fracq is also "locked" in a *) (* similar way, fracq will not reduce to a Rat x xP unless it is also applied *) (* to "enough" constructors. This preserves the reduction on gound elements *) (* while it suspends it when applied to at least one variable at the leaf of *) (* the arithmetic operation. *) (* Moreover we optimize addition when one or both arguments are integers, *) (* in which case we presimplify the output, this shortens the size of the hnf *) (* of terms of the form N%:Q when N is a concrete natural number. *) Definition addq_subdef (x y : int * int) := let: (x1, x2) := x in let: (y1, y2) := y in match x2, y2 with | Posz 1, Posz 1 => match x1, y1 with | Posz 0, _ => (y1, 1) | _, Posz 0 => (x1, 1) | Posz n, Posz 1 => (Posz n.+1, 1) | Posz 1, Posz n => (Posz n.+1, 1) | _, _ => (x1 + y1, 1) end | Posz 1, _ => (x1 * y2 + y1, y2) | _, Posz 1 => (x1 + y1 * x2, x2) | _, _ => (x1 * y2 + y1 * x2, x2 * y2) end. Definition addq '(Rat x xP) '(Rat y yP) := fracq (addq_subdef x y). Lemma addq_def x y : addq x y = fracq (addq_subdef (valq x) (valq y)). Proof. by case: x; case: y. Qed. Lemma addq_subdefE x y : addq_subdef x y = (x.1 * y.2 + y.1 * x.2, x.2 * y.2). Proof. case: x y => [x1 [[|[|x2]]|x2]] [y1 [[|[|y2]]|y2]]/=; rewrite ?Monoid.simpm//. by case: x1 y1 => [[|[|m]]|m] [[|[|n]]|n]; rewrite ?Monoid.simpm// -PoszD addn1. Qed. Definition oppq_subdef (x : int * int) := (- x.1, x.2). Definition oppq '(Rat x xP) := fracq (oppq_subdef x). Definition oppq_def x : oppq x = fracq (oppq_subdef (valq x)). Proof. by case: x. Qed. Fact addq_subdefC : commutative addq_subdef. Proof. by move=> x y; rewrite !addq_subdefE addrC [x.2 * _]mulrC. Qed. Fact addq_subdefA : associative addq_subdef. Proof. move=> x y z; rewrite !addq_subdefE. by rewrite !mulrA !mulrDl addrA ![_ * x.2]mulrC !mulrA. Qed. Fact addq_frac x y : x.2 != 0 -> y.2 != 0 -> (addq (fracq x) (fracq y)) = fracq (addq_subdef x y). Proof. case: fracqP => // u fx u_neq0 _; case: fracqP => // v fy v_neq0 _. rewrite addq_def !addq_subdefE /=. rewrite ![(_ * numq _) * _]mulrACA [(_ * denq _) * _]mulrACA. by rewrite [v * _]mulrC -mulrDr fracqMM ?mulf_neq0. Qed. Fact ratzD : {morph ratz : x y / x + y >-> addq x y}. Proof. by move=> x y; rewrite !ratz_frac addq_frac// addq_subdefE/= !mulr1. Qed. Fact oppq_frac x : oppq (fracq x) = fracq (oppq_subdef x). Proof. rewrite /oppq_subdef; case: fracqP => /= [|u fx u_neq0]. by rewrite fracq0. by rewrite oppq_def -mulrN fracqMM. Qed. Fact ratzN : {morph ratz : x / - x >-> oppq x}. Proof. by move=> x /=; rewrite !ratz_frac // /add /= !mulr1. Qed. Fact addqC : commutative addq. Proof. by move=> x y; rewrite !addq_def /= addq_subdefC. Qed. Fact addqA : associative addq. Proof. move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK. by rewrite ?addq_frac ?addq_subdefA// ?addq_subdefE ?mulf_neq0 ?denq_neq0. Qed. Fact add0q : left_id zeroq addq. Proof. move=> x; rewrite -[x]valqK -[zeroq]valqK addq_frac ?denq_neq0 // !addq_subdefE. by rewrite mul0r add0r mulr1 mul1r -surjective_pairing. Qed. Fact addNq : left_inverse (fracq (0, 1)) oppq addq. Proof. move=> x; rewrite -[x]valqK !(addq_frac, oppq_frac) ?denq_neq0 //. rewrite !addq_subdefE /oppq_subdef //= mulNr addNr; apply/eqP. by rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= !mul0r. Qed. HB.instance Definition _ := GRing.isZmodule.Build rat addqA addqC add0q addNq. Definition mulq_subdef (x y : int * int) := let: (x1, x2) := x in let: (y1, y2) := y in match x2, y2 with | Posz 1, Posz 1 => (x1 * y1, 1) | Posz 1, _ => (x1 * y1, y2) | _, Posz 1 => (x1 * y1, x2) | _, _ => (x1 * y1, x2 * y2) end. Definition mulq '(Rat x xP) '(Rat y yP) := fracq (mulq_subdef x y). Lemma mulq_def x y : mulq x y = fracq (mulq_subdef (valq x) (valq y)). Proof. by case: x; case: y. Qed. Lemma mulq_subdefE x y : mulq_subdef x y = (x.1 * y.1, x.2 * y.2). Proof. by case: x y => [x1 [[|[|x2]]|x2]] [y1 [[|[|y2]]|y2]]/=; rewrite ?Monoid.simpm. Qed. Fact mulq_subdefC : commutative mulq_subdef. Proof. by move=> x y; rewrite !mulq_subdefE mulrC [_ * x.2]mulrC. Qed. Fact mul_subdefA : associative mulq_subdef. Proof. by move=> x y z; rewrite !mulq_subdefE !mulrA. Qed. Definition invq_subdef (x : int * int) := (x.2, x.1). Definition invq '(Rat x xP) := fracq (invq_subdef x). Lemma invq_def x : invq x = fracq (invq_subdef (valq x)). Proof. by case: x. Qed. Fact mulq_frac x y : (mulq (fracq x) (fracq y)) = fracq (mulq_subdef x y). Proof. rewrite mulq_def !mulq_subdefE; case: (fracqP x) => /= [|u fx u_neq0]. by rewrite !mul0r !mul1r fracq0 frac0q. case: (fracqP y) => /= [|v fy v_neq0]. by rewrite !mulr0 !mulr1 fracq0 frac0q. by rewrite ![_ * (v * _)]mulrACA [RHS]fracqMM ?mulf_neq0. Qed. Fact ratzM : {morph ratz : x y / x * y >-> mulq x y}. Proof. by move=> x y /=; rewrite !ratz_frac //= !mulr1. Qed. Fact invq_frac x : x.1 != 0 -> x.2 != 0 -> invq (fracq x) = fracq (invq_subdef x). Proof. by rewrite invq_def; case: (fracqP x) => // k ? k0; rewrite fracqMM. Qed. Fact mulqC : commutative mulq. Proof. by move=> x y; rewrite !mulq_def mulq_subdefC. Qed. Fact mulqA : associative mulq. Proof. by move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK !mulq_frac mul_subdefA. Qed. Fact mul1q : left_id oneq mulq. Proof. move=> x; rewrite -[x]valqK -[oneq]valqK; rewrite mulq_frac !mulq_subdefE. by rewrite !mul1r -surjective_pairing. Qed. Fact mulq_addl : left_distributive mulq addq. Proof. move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK /=. rewrite !(mulq_frac, addq_frac, mulq_subdefE, addq_subdefE) ?mulf_neq0 ?denq_neq0 //=. apply/eqP; rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= !mulrDl; apply/eqP. by rewrite !mulrA ![_ * (valq z).1]mulrC !mulrA ![_ * (valq x).2]mulrC !mulrA. Qed. Fact nonzero1q : oneq != zeroq. Proof. by []. Qed. HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build rat mulqA mulqC mul1q mulq_addl nonzero1q. Fact mulVq x : x != 0 -> mulq (invq x) x = 1. Proof. rewrite -[x]valqK -[0]valqK fracq_eq ?denq_neq0 //= mulr1 mul0r=> nx0. rewrite !(mulq_frac, invq_frac, mulq_subdefE) ?denq_neq0 // -[1]valqK. by apply/eqP; rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= mulr1 mul1r mulrC. Qed. Fact invq0 : invq 0 = 0. Proof. exact/eqP. Qed. HB.instance Definition _ := GRing.ComNzRing_isField.Build rat mulVq invq0. Lemma numq_eq0 x : (numq x == 0) = (x == 0). Proof. rewrite -[x]valqK fracq_eq0; case: fracqP=> /= [|k {}x k0]. by rewrite eqxx orbT. by rewrite !mulf_eq0 (negPf k0) /= denq_eq0 orbF. Qed. Notation "n %:Q" := ((n : int)%:~R : rat) : ring_scope. #[global] Hint Resolve denq_neq0 denq_gt0 denq_ge0 : core. Definition subq (x y : rat) : rat := (addq x (oppq y)). Definition divq (x y : rat) : rat := (mulq x (invq y)). Infix "+" := addq : rat_scope. Notation "- x" := (oppq x) : rat_scope. Infix "*" := mulq : rat_scope. Notation "x ^-1" := (invq x) : rat_scope. Infix "-" := subq : rat_scope. Infix "/" := divq : rat_scope. (* ratz should not be used, %:Q should be used instead *) Lemma ratzE n : ratz n = n%:Q. Proof. elim: n=> [|n ihn|n ihn]; first by rewrite mulr0z ratz_frac. by rewrite intS mulrzDr ratzD ihn. by rewrite intS opprD mulrzDr ratzD ihn. Qed. Lemma numq_int n : numq n%:Q = n. Proof. by rewrite -ratzE. Qed. Lemma denq_int n : denq n%:Q = 1. Proof. by rewrite -ratzE. Qed. Lemma rat0 : 0%:Q = 0. Proof. by []. Qed. Lemma rat1 : 1%:Q = 1. Proof. by []. Qed. Lemma numqN x : numq (- x) = - numq x. Proof. rewrite [- _]oppq_def/= num_fracq. case: x => -[a b]; rewrite /numq/= => /andP[b_gt0]. rewrite /coprime => /eqP cab. by rewrite lt_gtF ?gt_eqF // {2}abszN cab divn1 mulz_sign_abs. Qed. Lemma denqN x : denq (- x) = denq x. Proof. rewrite [- _]oppq_def den_fracq. case: x => -[a b]; rewrite /denq/= => /andP[b_gt0]. by rewrite /coprime=> /eqP cab; rewrite gt_eqF // abszN cab divn1 gtz0_abs. Qed. (* Will be subsumed by pnatr_eq0 *) Fact intq_eq0 n : (n%:~R == 0 :> rat) = (n == 0)%N. Proof. by rewrite -ratzE /ratz rat_eqE/= /numq /denq/= eqxx andbT. Qed. (* fracq should never appear, its canonical form is _%:Q / _%:Q *) Lemma fracqE x : fracq x = x.1%:Q / x.2%:Q. Proof. move: x => [m n] /=; apply/val_inj; rewrite val_fracq/=. case: eqVneq => //= [->|n_neq0]; first by rewrite rat0 invr0 mulr0. rewrite -[m%:Q]valqK -[n%:Q]valqK. rewrite [_^-1]invq_frac ?denq_neq0 ?numq_eq0 ?intq_eq0//=. rewrite [X in valq X]mulq_frac val_fracq /invq_subdef !mulq_subdefE/=. by rewrite -!/(numq _) -!/(denq _) !numq_int !denq_int mul1r mulr1 n_neq0. Qed. Lemma divq_num_den x : (numq x)%:Q / (denq x)%:Q = x. Proof. by rewrite -{3}[x]valqK [valq _]surjective_pairing /= fracqE. Qed. Variant divq_spec (n d : int) : int -> int -> rat -> Type := | DivqSpecN of d = 0 : divq_spec n d n 0 0 | DivqSpecP k x of k != 0 : divq_spec n d (k * numq x) (k * denq x) x. (* replaces fracqP *) Lemma divqP n d : divq_spec n d n d (n%:Q / d%:Q). Proof. set x := (n, d); rewrite -[n]/x.1 -[d]/x.2 -fracqE. by case: fracqP => [_|k fx k_neq0] /=; constructor. Qed. Variant rat_spec (* (x : rat) *) : rat -> int -> int -> Type := Rat_spec (n : int) (d : nat) & coprime `|n| d.+1 : rat_spec (* x *) (n%:Q / d.+1%:Q) n d.+1. Lemma ratP x : rat_spec x (numq x) (denq x). Proof. rewrite -{1}[x](divq_num_den); case hd: denq => [p|n]. have: 0 < p%:Z by rewrite -hd denq_gt0. case: p hd=> //= n hd; constructor; rewrite -?hd ?divq_num_den //. by rewrite -[n.+1]/`|n.+1|%N -hd coprime_num_den. by move: (denq_gt0 x); rewrite hd. Qed. Lemma coprimeq_num n d : coprime `|n| `|d| -> numq (n%:~R / d%:~R) = sgr d * n. Proof. move=> cnd /=; have <- := fracqE (n, d). rewrite num_fracq/= (eqP (cnd : _ == 1)) divn1. have [|d_gt0|d_lt0] := sgrP d; by rewrite (mul0r, mul1r, mulN1r) //= ?[_ ^ _]signrN ?mulNr mulz_sign_abs. Qed. Lemma coprimeq_den n d : coprime `|n| `|d| -> denq (n%:~R / d%:~R) = (if d == 0 then 1 else `|d|). Proof. move=> cnd; have <- := fracqE (n, d). by rewrite den_fracq/= (eqP (cnd : _ == 1)) divn1; case: d {cnd}; case. Qed. Lemma denqVz (i : int) : i != 0 -> denq (i%:~R^-1) = `|i|. Proof. move=> h; rewrite -div1r -[1]/(1%:~R). by rewrite coprimeq_den /= ?coprime1n // (negPf h). Qed. Lemma numqE x : (numq x)%:~R = x * (denq x)%:~R. Proof. by rewrite -{2}[x]divq_num_den divfK // intq_eq0 denq_eq0. Qed. Lemma denqP x : {d | denq x = d.+1}. Proof. by rewrite /denq; case: x => [[_ [[|d]|]] //= _]; exists d. Qed. Definition normq '(Rat x _) : rat := `|x.1|%:~R / (x.2)%:~R. Definition le_rat '(Rat x _) '(Rat y _) := x.1 * y.2 <= y.1 * x.2. Definition lt_rat '(Rat x _) '(Rat y _) := x.1 * y.2 < y.1 * x.2. Lemma normqE x : normq x = `|numq x|%:~R / (denq x)%:~R. Proof. by case: x. Qed. Lemma le_ratE x y : le_rat x y = (numq x * denq y <= numq y * denq x). Proof. by case: x; case: y. Qed. Lemma lt_ratE x y : lt_rat x y = (numq x * denq y < numq y * denq x). Proof. by case: x; case: y. Qed. Lemma gt_rat0 x : lt_rat 0 x = (0 < numq x). Proof. by rewrite lt_ratE mul0r mulr1. Qed. Lemma lt_rat0 x : lt_rat x 0 = (numq x < 0). Proof. by rewrite lt_ratE mul0r mulr1. Qed. Lemma ge_rat0 x : le_rat 0 x = (0 <= numq x). Proof. by rewrite le_ratE mul0r mulr1. Qed. Lemma le_rat0 x : le_rat x 0 = (numq x <= 0). Proof. by rewrite le_ratE mul0r mulr1. Qed. Fact le_rat0D x y : le_rat 0 x -> le_rat 0 y -> le_rat 0 (x + y). Proof. rewrite !ge_rat0 => hnx hny. have hxy: (0 <= numq x * denq y + numq y * denq x). by rewrite addr_ge0 ?mulr_ge0. rewrite [_ + _]addq_def /numq /= -!/(denq _) ?mulf_eq0 ?denq_eq0. rewrite val_fracq/=; case: ifP => //=. by rewrite ?addq_subdefE !mulr_ge0// !le_gtF ?mulr_ge0 ?denq_ge0//=. Qed. Fact le_rat0M x y : le_rat 0 x -> le_rat 0 y -> le_rat 0 (x * y). Proof. rewrite !ge_rat0 => hnx hny. have hxy: (0 <= numq x * denq y + numq y * denq x). by rewrite addr_ge0 ?mulr_ge0. rewrite [_ * _]mulq_def /numq /= -!/(denq _) ?mulf_eq0 ?denq_eq0. rewrite val_fracq/=; case: ifP => //=. by rewrite ?mulq_subdefE !mulr_ge0// !le_gtF ?mulr_ge0 ?denq_ge0//=. Qed. Fact le_rat0_anti x : le_rat 0 x -> le_rat x 0 -> x = 0. Proof. by move=> hx hy; apply/eqP; rewrite -numq_eq0 eq_le -ge_rat0 -le_rat0 hx hy. Qed. Lemma sgr_numq_div (n d : int) : sgr (numq (n%:Q / d%:Q)) = sgr n * sgr d. Proof. set x := (n, d); rewrite -[n]/x.1 -[d]/x.2 -fracqE. case: fracqP => [|k fx k_neq0] /=; first by rewrite mulr0. by rewrite !sgrM mulrACA -expr2 sqr_sg k_neq0 sgr_denq mulr1 mul1r. Qed. Fact subq_ge0 x y : le_rat 0 (y - x) = le_rat x y. Proof. symmetry; rewrite ge_rat0 !le_ratE -subr_ge0. case: ratP => nx dx cndx; case: ratP => ny dy cndy. rewrite -!mulNr addf_div ?intq_eq0 // !mulNr -!rmorphM -rmorphB /=. symmetry; rewrite !leNgt -sgr_cp0 sgr_numq_div mulrC gtr0_sg //. by rewrite mul1r sgr_cp0. Qed. Fact le_rat_total : total le_rat. Proof. by move=> x y; rewrite !le_ratE; apply: le_total. Qed. Fact numq_sign_mul (b : bool) x : numq ((-1) ^+ b * x) = (-1) ^+ b * numq x. Proof. by case: b; rewrite ?(mul1r, mulN1r) // numqN. Qed. Fact numq_div_lt0 n d : n != 0 -> d != 0 -> (numq (n%:~R / d%:~R) < 0)%R = (n < 0)%R (+) (d < 0)%R. Proof. move=> n0 d0; rewrite -sgr_cp0 sgr_numq_div !sgr_def n0 d0. by rewrite !mulr1n -signr_addb; case: (_ (+) _). Qed. Lemma normr_num_div n d : `|numq (n%:~R / d%:~R)| = numq (`|n|%:~R / `|d|%:~R). Proof. rewrite (normrEsg n) (normrEsg d) !rmorphM /= invfM mulrACA !sgr_def. have [->|n_neq0] := eqVneq; first by rewrite mul0r mulr0. have [->|d_neq0] := eqVneq; first by rewrite invr0 !mulr0. rewrite !intr_sign invr_sign -signr_addb numq_sign_mul -numq_div_lt0 //. by apply: (canRL (signrMK _)); rewrite mulz_sign_abs. Qed. Fact norm_ratN x : normq (- x) = normq x. Proof. by rewrite !normqE numqN denqN normrN. Qed. Fact ge_rat0_norm x : le_rat 0 x -> normq x = x. Proof. rewrite ge_rat0; case: ratP=> [] // n d cnd n_ge0. by rewrite normqE /= normr_num_div ?ger0_norm // divq_num_den. Qed. Fact lt_rat_def x y : (lt_rat x y) = (y != x) && (le_rat x y). Proof. by rewrite lt_ratE le_ratE lt_def rat_eq. Qed. HB.instance Definition _ := Num.IntegralDomain_isLeReal.Build rat le_rat0D le_rat0M le_rat0_anti subq_ge0 (@le_rat_total 0) norm_ratN ge_rat0_norm lt_rat_def. Lemma numq_ge0 x : (0 <= numq x) = (0 <= x). Proof. by case: ratP => n d cnd; rewrite ?pmulr_lge0 ?invr_gt0 (ler0z, ltr0z). Qed. Lemma numq_le0 x : (numq x <= 0) = (x <= 0). Proof. by rewrite -oppr_ge0 -numqN numq_ge0 oppr_ge0. Qed. Lemma numq_gt0 x : (0 < numq x) = (0 < x). Proof. by rewrite !ltNge numq_le0. Qed. Lemma numq_lt0 x : (numq x < 0) = (x < 0). Proof. by rewrite !ltNge numq_ge0. Qed. Lemma sgr_numq x : sgz (numq x) = sgz x. Proof. apply/eqP; case: (sgzP x); rewrite sgz_cp0 ?(numq_gt0, numq_lt0) //. by move->. Qed. Lemma denq_mulr_sign (b : bool) x : denq ((-1) ^+ b * x) = denq x. Proof. by case: b; rewrite ?(mul1r, mulN1r) // denqN. Qed. Lemma denq_norm x : denq `|x| = denq x. Proof. by rewrite normrEsign denq_mulr_sign. Qed. Module ratArchimedean. Section ratArchimedean. Implicit Types x : rat. Definition floor x : int := (numq x %/ denq x)%Z. Definition ceil x : int := - (- numq x %/ denq x)%Z. Definition truncn x : nat := if 0 <= x then (`|numq x| %/ `|denq x|)%N else 0%N. Let is_int x := denq x == 1. Let is_nat x := (0 <= x) && (denq x == 1). Fact floorP x : if x \is Num.real then (floor x)%:~R <= x < (floor x + 1)%:~R else floor x == 0. Proof. rewrite num_real /floor; case: (ratP x) => n d _ {x}; rewrite ler_pdivlMr//. by rewrite ltr_pdivrMr// -!intrM ler_int ltr_int lez_floor ?ltz_ceil. Qed. Fact ceilP x : ceil x = - floor (- x). Proof. by rewrite /ceil /floor numqN denqN. Qed. Fact truncnP x : truncn x = if floor x is Posz n then n else 0. Proof. rewrite /truncn /floor; case: (ratP x) => n d _ {x} /=. by rewrite !ler_pdivlMr// mul0r; case: n => n; rewrite ler0z//= mul1n. Qed. Fact intrP x : reflect (exists n, x = n%:~R) (is_int x). Proof. apply: (iffP idP) => [/eqP d1 | [i ->]]; [|by rewrite /is_int denq_int]. by exists (numq x); case: (ratP x) d1 => n d _ ->; rewrite divr1. Qed. Fact natrP x : reflect (exists n, x = n%:R) (is_nat x). Proof. apply: (iffP idP) => [/andP[]/[swap]/intrP[i ->]|[n ->]]. by rewrite ler0z; case: i => [n _|//]; exists n. by rewrite /is_nat pmulrn ler0z denq_int. Qed. End ratArchimedean. End ratArchimedean. HB.instance Definition _ := Num.NumDomain_hasFloorCeilTruncn.Build rat ratArchimedean.floorP ratArchimedean.ceilP ratArchimedean.truncnP ratArchimedean.intrP ratArchimedean.natrP. Lemma floorErat (x : rat) : Num.floor x = (numq x %/ denq x)%Z. Proof. by []. Qed. Lemma ceilErat (x : rat) : Num.ceil x = - (- numq x %/ denq x)%Z. Proof. by []. Qed. Lemma Qint_def (x : rat) : (x \is a Num.int) = (denq x == 1). Proof. by []. Qed. Lemma numqK : {in Num.int, cancel (fun x => numq x) intr}. Proof. by move=> _ /intrP [x ->]; rewrite numq_int. Qed. Lemma natq_div m n : (n %| m)%N -> (m %/ n)%:R = m%:R / n%:R :> rat. Proof. exact/pchar0_natf_div/pchar_num. Qed. Section InRing. Variable R : unitRingType. Definition ratr x : R := (numq x)%:~R / (denq x)%:~R. Lemma ratr_int z : ratr z%:~R = z%:~R. Proof. by rewrite /ratr numq_int denq_int divr1. Qed. Lemma ratr_nat n : ratr n%:R = n%:R. Proof. exact: ratr_int n. Qed. Lemma rpred_rat (S : divringClosed R) a : ratr a \in S. Proof. by rewrite rpred_div ?rpred_int. Qed. End InRing. Section Fmorph. Implicit Type rR : unitRingType. Lemma fmorph_rat (aR : fieldType) rR (f : {rmorphism aR -> rR}) a : f (ratr _ a) = ratr _ a. Proof. by rewrite fmorph_div !rmorph_int. Qed. Lemma fmorph_eq_rat rR (f : {rmorphism rat -> rR}) : f =1 ratr _. Proof. by move=> a; rewrite -{1}[a]divq_num_den fmorph_div !rmorph_int. Qed. End Fmorph. Section Linear. Implicit Types (U V : lmodType rat) (A B : lalgType rat). Lemma rat_linear U V (f : U -> V) : zmod_morphism f -> scalable f. Proof. move=> fB a u. pose aM := GRing.isZmodMorphism.Build U V f fB. pose phi : {additive U -> V} := HB.pack f aM. rewrite -[f]/(phi : _ -> _) -{2}[a]divq_num_den mulrC -scalerA. apply: canRL (scalerK _) _; first by rewrite intr_eq0 denq_neq0. rewrite 2!scaler_int -3!raddfMz /=. by rewrite -scalerMzr scalerMzl -mulrzr -numqE scaler_int. Qed. End Linear. Section InPrealField. Variable F : numFieldType. Fact ratr_is_zmod_morphism : zmod_morphism (@ratr F). Proof. have injZtoQ: @injective rat int intr by apply: intr_inj. have nz_den x: (denq x)%:~R != 0 :> F by rewrite intr_eq0 denq_eq0. move=> x y. apply: (canLR (mulfK (nz_den _))); apply: (mulIf (nz_den x)). rewrite mulrAC mulrBl divfK ?nz_den // mulrAC -!rmorphM. apply: (mulIf (nz_den y)); rewrite mulrAC mulrBl divfK ?nz_den //. rewrite -!(rmorphM, rmorphB); congr _%:~R; apply: injZtoQ. rewrite !(rmorphM, rmorphB) /= [_ - _]lock /= -lock !numqE. by rewrite (mulrAC y) -!mulrBl -mulrA mulrAC !mulrA. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `ratr_is_additive` instead")] Definition ratr_is_additive := ratr_is_zmod_morphism. Fact ratr_is_monoid_morphism : monoid_morphism (@ratr F). Proof. have injZtoQ: @injective rat int intr by apply: intr_inj. have nz_den x: (denq x)%:~R != 0 :> F by rewrite intr_eq0 denq_eq0. split=> [|x y]; first by rewrite /ratr divr1. rewrite /ratr mulrC mulrAC; apply: canLR (mulKf (nz_den _)) _; rewrite !mulrA. do 2!apply: canRL (mulfK (nz_den _)) _; rewrite -!rmorphM; congr _%:~R. apply: injZtoQ; rewrite !rmorphM [x * y]lock /= !numqE -lock. by rewrite -!mulrA mulrA mulrCA -!mulrA (mulrCA y). Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `ratr_is_monoid_morphism` instead")] Definition ratr_is_multiplicative := (fun g => (g.2,g.1)) ratr_is_monoid_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build rat F (@ratr F) ratr_is_zmod_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build rat F (@ratr F) ratr_is_monoid_morphism. Lemma ler_rat : {mono (@ratr F) : x y / x <= y}. Proof. move=> x y /=; case: (ratP x) => nx dx cndx; case: (ratP y) => ny dy cndy. rewrite !fmorph_div /= !ratr_int !ler_pdivlMr ?ltr0z //. by rewrite ![_ / _ * _]mulrAC !ler_pdivrMr ?ltr0z // -!rmorphM /= !ler_int. Qed. Lemma ltr_rat : {mono (@ratr F) : x y / x < y}. Proof. exact: leW_mono ler_rat. Qed. Lemma ler0q x : (0 <= ratr F x) = (0 <= x). Proof. by rewrite (_ : 0 = ratr F 0) ?ler_rat ?rmorph0. Qed. Lemma lerq0 x : (ratr F x <= 0) = (x <= 0). Proof. by rewrite (_ : 0 = ratr F 0) ?ler_rat ?rmorph0. Qed. Lemma ltr0q x : (0 < ratr F x) = (0 < x). Proof. by rewrite (_ : 0 = ratr F 0) ?ltr_rat ?rmorph0. Qed. Lemma ltrq0 x : (ratr F x < 0) = (x < 0). Proof. by rewrite (_ : 0 = ratr F 0) ?ltr_rat ?rmorph0. Qed. Lemma ratr_sg x : ratr F (sgr x) = sgr (ratr F x). Proof. by rewrite !sgr_def fmorph_eq0 ltrq0 rmorphMn /= rmorph_sign. Qed. Lemma ratr_norm x : ratr F `|x| = `|ratr F x|. Proof. by rewrite {2}[x]numEsign rmorphMsign normrMsign [`|ratr F _|]ger0_norm ?ler0q. Qed. Lemma minr_rat : {morph ratr F : x y / Num.min x y}. Proof. by move=> x y; rewrite !minEle ler_rat; case: leP. Qed. Lemma maxr_rat : {morph ratr F : x y / Num.max x y}. Proof. by move=> x y; rewrite !maxEle ler_rat; case: leP. Qed. End InPrealField. Section InParchiField. Variable F : archiNumFieldType. Lemma floor_rat : {mono (@ratr F) : x / Num.floor x}. Proof. move=> x; apply: floor_def; apply/andP; split. - by rewrite -ratr_int ler_rat floor_le_tmp. - by rewrite -ratr_int ltr_rat floorD1_gt. Qed. Lemma ceil_rat : {mono (@ratr F) : x / Num.ceil x}. Proof. by move=> x; rewrite !ceilNfloor -rmorphN floor_rat. Qed. End InParchiField. Arguments ratr {R}. Lemma Qint_dvdz (m d : int) : (d %| m)%Z -> (m%:~R / d%:~R : rat) \is a Num.int. Proof. case/dvdzP=> z ->; rewrite rmorphM /=; have [->|dn0] := eqVneq d 0. by rewrite mulr0 mul0r. by rewrite mulfK ?intr_eq0. Qed. Lemma Qnat_dvd (m d : nat) : (d %| m)%N -> (m%:R / d%:R : rat) \is a Num.nat. Proof. by move=> h; rewrite natrEint divr_ge0 ?ler0n // !pmulrn Qint_dvdz. Qed. Section ZpolyScale. Local Notation pZtoQ := (map_poly (intr : int -> rat)). Lemma size_rat_int_poly p : size (pZtoQ p) = size p. Proof. by apply: size_map_inj_poly; first apply: intr_inj. Qed. Lemma rat_poly_scale (p : {poly rat}) : {q : {poly int} & {a | a != 0 & p = a%:~R^-1 *: pZtoQ q}}. Proof. pose a := \prod_(i < size p) denq p`_i. have nz_a: a != 0 by apply/prodf_neq0=> i _; apply: denq_neq0. exists (map_poly numq (a%:~R *: p)), a => //. apply: canRL (scalerK _) _; rewrite ?intr_eq0 //. apply/polyP=> i; rewrite !(coefZ, coef_map_id0) // numqK // Qint_def mulrC. have [ltip | /(nth_default 0)->] := ltnP i (size p); last by rewrite mul0r. by rewrite [a](bigD1 (Ordinal ltip)) // rmorphM mulrA -numqE -rmorphM denq_int. Qed. Lemma dvdp_rat_int p q : (pZtoQ p %| pZtoQ q) = (p %| q). Proof. apply/dvdpP/Pdiv.Idomain.dvdpP=> [[/= r1 Dq] | [[/= a r] nz_a Dq]]; last first. exists (a%:~R^-1 *: pZtoQ r). by rewrite -scalerAl -rmorphM -Dq /= linearZ/= scalerK ?intr_eq0. have [r [a nz_a Dr1]] := rat_poly_scale r1; exists (a, r) => //=. apply: (map_inj_poly _ _ : injective pZtoQ) => //; first exact: intr_inj. by rewrite linearZ /= Dq Dr1 -scalerAl -rmorphM scalerKV ?intr_eq0. Qed. Lemma dvdpP_rat_int p q : p %| pZtoQ q -> {p1 : {poly int} & {a | a != 0 & p = a *: pZtoQ p1} & {r | q = p1 * r}}. Proof. have{p} [p [a nz_a ->]] := rat_poly_scale p. rewrite dvdpZl ?invr_eq0 ?intr_eq0 // dvdp_rat_int => dv_p_q. exists (zprimitive p); last exact: dvdpP_int. have [-> | nz_p] := eqVneq p 0. by exists 1; rewrite ?oner_eq0 // zprimitive0 map_poly0 !scaler0. exists ((zcontents p)%:~R / a%:~R). by rewrite mulf_neq0 ?invr_eq0 ?intr_eq0 ?zcontents_eq0. by rewrite mulrC -scalerA -map_polyZ -zpolyEprim. Qed. Lemma irreducible_rat_int p : irreducible_poly (pZtoQ p) <-> irreducible_poly p. Proof. rewrite /irreducible_poly size_rat_int_poly; split=> -[] p1 p_irr; split=> //. move=> q q1; rewrite /eqp -!dvdp_rat_int => rq. by apply/p_irr => //; rewrite size_rat_int_poly. move=> q + /dvdpP_rat_int [] r [] c c0 qE [] s sE. rewrite qE size_scale// size_rat_int_poly => r1. apply/(eqp_trans (eqp_scale _ c0)). rewrite /eqp !dvdp_rat_int; apply/p_irr => //. by rewrite sE dvdp_mulIl. Qed. End ZpolyScale. (* Integral spans. *) Definition inIntSpan (V : zmodType) m (s : m.-tuple V) v := exists a : int ^ m, v = \sum_(i < m) s`_i *~ a i. Lemma solve_Qint_span (vT : vectType rat) m (s : m.-tuple vT) v : {b : int ^ m & {p : seq (int ^ m) & forall a : int ^ m, v = \sum_(i < m) s`_i *~ a i <-> exists c : seq int, a = b + \sum_(i < size p) p`_i *~ c`_i}} + (~ inIntSpan s v). Proof. have s_s (i : 'I_m): s`_i \in <<s>>%VS by rewrite memv_span ?memt_nth. have s_Zs a: \sum_(i < m) s`_i *~ a i \in <<s>>%VS. by apply/rpred_sum => i _; apply/rpredMz. case s_v: (v \in <<s>>%VS); last by right=> [[a Dv]]; rewrite Dv s_Zs in s_v. move SE : (\matrix_(i < m, j < _) coord (vbasis <<s>>) j s`_i) => S. move rE : (\rank S) => r; move kE : (m - r)%N => k. have Dm: (m = k + r)%N by rewrite -kE -rE subnK ?rank_leq_row. rewrite Dm in s s_s s_Zs s_v S SE rE kE *. move=> {Dm m}; pose m := (k + r)%N. have [K kerK]: {K : 'M_(k, m) | map_mx intr K == kermx S}%MS. move: (mxrank_ker S); rewrite rE kE => krk. pose B := row_base (kermx S); pose d := \prod_ij denq (B ij.1 ij.2). exists (castmx (krk, erefl m) (map_mx numq (intr d *: B))). rewrite map_castmx !eqmx_cast -map_mx_comp map_mx_id_in => [|i j]; last first. rewrite mxE mulrC [d](bigD1 (i, j)) //= rmorphM mulrA. by rewrite -numqE -rmorphM numq_int. suff nz_d: d%:Q != 0 by rewrite !eqmx_scale // !eq_row_base andbb. by rewrite intr_eq0; apply/prodf_neq0 => i _; apply: denq_neq0. have [L _ [G uG [D _ defK]]] := int_Smith_normal_form K. have {K L D defK kerK} [kerGu kerS_sub_Gu]: map_mx intr (usubmx G) *m S = 0 /\ (kermx S <= map_mx intr (usubmx G))%MS. pose Kl : 'M[rat]_k := map_mx intr (lsubmx (K *m invmx G)). have {}defK: map_mx intr K = Kl *m map_mx intr (usubmx G). rewrite /Kl -map_mxM; congr map_mx. rewrite -[LHS](mulmxKV uG) -{2}[G]vsubmxK -{1}[K *m _]hsubmxK. rewrite mul_row_col -[RHS]addr0; congr (_ + _). rewrite defK mulmxK //= -[RHS](mul0mx _ (dsubmx G)); congr (_ *m _). apply/matrixP => i j; rewrite !mxE big1 //= => j1 _. rewrite mxE /= eqn_leq andbC. by rewrite leqNgt (leq_trans (valP j1)) ?mulr0 ?leq_addr. split; last by rewrite -(eqmxP kerK); apply/submxP; exists Kl. suff /row_full_inj: row_full Kl. by apply; rewrite mulmx0 mulmxA (sub_kermxP _) // -(eqmxP kerK) defK. rewrite /row_full eqn_leq rank_leq_row /= -{1}kE -{2}rE -(mxrank_ker S). by rewrite -(eqmxP kerK) defK mxrankM_maxl. pose T := map_mx intr (dsubmx G) *m S. have defS: map_mx intr (rsubmx (invmx G)) *m T = S. rewrite mulmxA -map_mxM /=; move: (mulVmx uG). rewrite -{2}[G]vsubmxK -{1}[invmx G]hsubmxK mul_row_col. move/(canRL (addKr _)) ->; rewrite -mulNmx raddfD /= map_mx1 map_mxM /=. by rewrite mulmxDl -mulmxA kerGu mulmx0 add0r mul1mx. pose vv := \row_j coord (vbasis <<s>>) j v. have uS: row_full S. apply/row_fullP; exists (\matrix_(i, j) coord s j (vbasis <<s>>)`_i). apply/matrixP => j1 j2; rewrite !mxE. rewrite -(coord_free _ _ (basis_free (vbasisP _))). rewrite -!tnth_nth (coord_span (vbasis_mem (mem_tnth j1 _))) linear_sum. by apply: eq_bigr => /= i _; rewrite -SE !mxE (tnth_nth 0) !linearZ. have eqST: (S :=: T)%MS by apply/eqmxP; rewrite -{1}defS !submxMl. case Zv: (map_mx denq (vv *m pinvmx T) == const_mx 1); last first. right=> [[a Dv]]; case/eqP: Zv; apply/rowP. have ->: vv = map_mx intr (\row_i a i) *m S. apply/rowP => j; rewrite !mxE Dv linear_sum. by apply: eq_bigr => i _; rewrite -SE -scaler_int linearZ !mxE. rewrite -defS -2!mulmxA; have ->: T *m pinvmx T = 1%:M. have uT: row_free T by rewrite /row_free -eqST rE. by apply: (row_free_inj uT); rewrite mul1mx mulmxKpV. by move=> i; rewrite mulmx1 -map_mxM 2!mxE denq_int mxE. pose b := map_mx numq (vv *m pinvmx T) *m dsubmx G. left; exists [ffun j => b 0 j], [seq [ffun j => (usubmx G) i j] | i : 'I_k]. rewrite size_image card_ord => a; rewrite -[a](addNKr [ffun j => b 0 j]). move: (_ + a) => h; under eq_bigr => i _ do rewrite !ffunE mulrzDr. rewrite big_split /=. have <-: v = \sum_(i < m) s`_i *~ b 0 i. transitivity (\sum_j (map_mx intr b *m S) 0 j *: (vbasis <<s>>)`_j). rewrite {1}(coord_vbasis s_v); apply: eq_bigr => j _; congr (_ *: _). suff ->: map_mx intr b = vv *m pinvmx T *m map_mx intr (dsubmx G). by rewrite -(mulmxA _ _ S) mulmxKpV ?mxE // -eqST submx_full. rewrite map_mxM /=; congr (_ *m _); apply/rowP => i; rewrite 2!mxE numqE. by have /eqP/rowP/(_ i)/[!mxE] -> := Zv; rewrite mulr1. rewrite (coord_vbasis (s_Zs _)); apply: eq_bigr => j _; congr (_ *: _). rewrite linear_sum mxE; apply: eq_bigr => i _. by rewrite -SE -scaler_int linearZ [b]lock !mxE. split. rewrite -[LHS]addr0 => /addrI hP; pose c := \row_i h i *m lsubmx (invmx G). exists [seq c 0 i | i : 'I_k]; congr (_ + _). have/sub_kermxP: map_mx intr (\row_i h i) *m S = 0. transitivity (\row_j coord (vbasis <<s>>) j (\sum_(i < m) s`_i *~ h i)). apply/rowP => j; rewrite !mxE linear_sum; apply: eq_bigr => i _. by rewrite -SE !mxE -scaler_int linearZ. by apply/rowP => j; rewrite !mxE -hP linear0. case/submx_trans/(_ kerS_sub_Gu)/submxP => c' /[dup]. move/(congr1 (mulmx^~ (map_mx intr (lsubmx (invmx G))))). rewrite -mulmxA -!map_mxM [in RHS]mulmx_lsub mul_usub_mx -/c mulmxV //=. rewrite scalar_mx_block -/(ulsubmx _) block_mxKul map_scalar_mx mulmx1. move=> <- {c'}; rewrite -map_mxM /= => defh; apply/ffunP => j. move/rowP/(_ j): defh; rewrite sum_ffunE !mxE => /intr_inj ->. apply: eq_bigr => i _; rewrite ffunMzE mulrzz mulrC. rewrite (nth_map i) ?size_enum_ord // nth_ord_enum ffunE. by rewrite (nth_map i) ?size_enum_ord // nth_ord_enum. case=> c /addrI -> {h}; rewrite -[LHS]addr0; congr (_ + _). pose h := \row_(j < k) c`_j *m usubmx G. transitivity (\sum_j (map_mx intr h *m S) 0 j *: (vbasis <<s>>)`_j). by rewrite map_mxM -mulmxA kerGu mulmx0 big1 // => j _; rewrite mxE scale0r. rewrite (coord_vbasis (s_Zs _)); apply: eq_bigr => i _; congr (_ *: _). rewrite linear_sum -SE mxE; apply: eq_bigr => j _. rewrite -scaler_int linearZ !mxE sum_ffunE; congr (_%:~R * _). apply: {i} eq_bigr => i _; rewrite mxE ffunMzE mulrzz mulrC. by rewrite (nth_map i) ?size_enum_ord // ffunE nth_ord_enum. Qed. Lemma dec_Qint_span (vT : vectType rat) m (s : m.-tuple vT) v : decidable (inIntSpan s v). Proof. have [[b [p aP]]|] := solve_Qint_span s v; last by right. left; exists b; apply/(aP b); exists [::]; rewrite big1 ?addr0 // => i _. by rewrite nth_nil mulr0z. Qed. Lemma eisenstein_crit (p : nat) (q : {poly int}) : prime p -> (size q != 1)%N -> ~~ (p %| lead_coef q)%Z -> ~~ (p ^+ 2 %| q`_0)%Z -> (forall i, (i < (size q).-1)%N -> p %| q`_i)%Z -> irreducible_poly q. Proof. move=> p_prime qN1 Ndvd_pql Ndvd_pq0 dvd_pq. apply/irreducible_rat_int. have qN0 : q != 0 by rewrite -lead_coef_eq0; apply: contraNneq Ndvd_pql => ->. split. rewrite size_map_poly_id0 ?intr_eq0 ?lead_coef_eq0//. by rewrite ltn_neqAle eq_sym qN1 size_poly_gt0. move=> f' +/dvdpP_rat_int[f [d dN0 feq]]; rewrite {f'}feq size_scale// => fN1. move=> /= [g q_eq]; rewrite q_eq (eqp_trans (eqp_scale _ _))//. have fN0 : f != 0 by apply: contra_neq qN0; rewrite q_eq => ->; rewrite mul0r. have gN0 : g != 0 by apply: contra_neq qN0; rewrite q_eq => ->; rewrite mulr0. rewrite size_map_poly_id0 ?intr_eq0 ?lead_coef_eq0// in fN1. have [/eqP/size_poly1P[c cN0 ->]|gN1] := eqVneq (size g) 1%N. by rewrite mulrC mul_polyC map_polyZ/= eqp_sym eqp_scale// intr_eq0. have c_neq0 : (lead_coef q)%:~R != 0 :> 'F_p by rewrite -(dvdz_pcharf (pchar_Fp _)). have : map_poly (intr : int -> 'F_p) q = (lead_coef q)%:~R *: 'X^((size q).-1). apply/val_inj/(@eq_from_nth _ 0) => [|i]; rewrite size_map_poly_id0//. by rewrite size_scale// size_polyXn -polySpred. move=> i_small; rewrite coef_poly i_small coefZ coefXn lead_coefE. move: i_small; rewrite polySpred// ltnS/=. case: ltngtP => // [i_lt|->]; rewrite (mulr1, mulr0)//= => _. by apply/eqP; rewrite -(dvdz_pcharf (pchar_Fp _))// dvd_pq. rewrite [in LHS]q_eq rmorphM/=. set c := (X in X *: _); set n := (_.-1). set pf := map_poly _ f; set pg := map_poly _ g => pfMpg. have dvdXn (r : {poly _}) : size r != 1%N -> r %| c *: 'X^n -> r`_0 = 0. move=> rN1; rewrite (eqp_dvdr _ (eqp_scale _ _))//. rewrite -['X]subr0; move=> /dvdp_exp_XsubCP[k lekn]; rewrite subr0. move=> /eqpP[u /andP[u1N0 u2N0]]; have [->|k_gt0] := posnP k. move=> /(congr1 (size \o val))/eqP. by rewrite /= !size_scale// size_polyXn (negPf rN1). move=> /(congr1 (fun p : {poly _} => p`_0))/eqP. by rewrite !coefZ coefXn [0 == _]ltn_eqF// mulr0 mulf_eq0 (negPf u1N0)=> /eqP. suff : ((p : int) ^+ 2 %| q`_0)%Z by rewrite (negPf Ndvd_pq0). have := c_neq0; rewrite q_eq coefM big_ord1. rewrite lead_coefM rmorphM mulf_eq0 negb_or => /andP[lpfN0 qfN0]. have pfN1 : size pf != 1%N by rewrite size_map_poly_id0. have pgN1 : size pg != 1%N by rewrite size_map_poly_id0. have /(dvdXn _ pgN1) /eqP : pg %| c *: 'X^n by rewrite -pfMpg dvdp_mull. have /(dvdXn _ pfN1) /eqP : pf %| c *: 'X^n by rewrite -pfMpg dvdp_mulr. by rewrite !coef_map// -!(dvdz_pcharf (pchar_Fp _))//; apply: dvdz_mul. Qed. (* Connecting rationals to the ring and field tactics *) Ltac rat_to_ring := rewrite -?[0%Q]/(0 : rat)%R -?[1%Q]/(1 : rat)%R -?[(_ - _)%Q]/(_ - _ : rat)%R -?[(_ / _)%Q]/(_ / _ : rat)%R -?[(_ + _)%Q]/(_ + _ : rat)%R -?[(_ * _)%Q]/(_ * _ : rat)%R -?[(- _)%Q]/(- _ : rat)%R -?[(_ ^-1)%Q]/(_ ^-1 : rat)%R /=. Ltac ring_to_rat := rewrite -?[0%R]/0%Q -?[1%R]/1%Q -?[(_ - _)%R]/(_ - _)%Q -?[(_ / _)%R]/(_ / _)%Q -?[(_ + _)%R]/(_ + _)%Q -?[(_ * _)%R]/(_ * _)%Q -?[(- _)%R]/(- _)%Q -?[(_ ^-1)%R]/(_ ^-1)%Q /=. (* Pretty printing or normal element of rat. *) Notation "[ 'rat' x // y ]" := (@Rat (x, y) _) (only printing) : ring_scope. (* For debugging purposes we provide the parsable version *) Notation "[ 'rat' x // y ]" := (@Rat (x : int, y : int) (fracq_subproof (x : int, y : int))) : ring_scope. (* A specialization of vm_compute rewrite rule for pattern _%:Q *) Lemma rat_vm_compute n (x : rat) : vm_compute_eq n%:Q x -> n%:Q = x. Proof. exact. Qed.
InjSurj.lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.Group.InjSurj import Mathlib.Algebra.GroupWithZero.NeZero /-! # Lifting groups with zero along injective/surjective maps -/ assert_not_exists DenselyOrdered Ring open Function variable {M₀ G₀ M₀' G₀' : Type*} section MulZeroClass variable [MulZeroClass M₀] /-- Pull back a `MulZeroClass` instance along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.mulZeroClass [Mul M₀'] [Zero M₀'] (f : M₀' → M₀) (hf : Injective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) : MulZeroClass M₀' where mul := (· * ·) zero := 0 zero_mul a := hf <| by simp only [mul, zero, zero_mul] mul_zero a := hf <| by simp only [mul, zero, mul_zero] /-- Push forward a `MulZeroClass` instance along a surjective function. See note [reducible non-instances]. -/ protected abbrev Function.Surjective.mulZeroClass [Mul M₀'] [Zero M₀'] (f : M₀ → M₀') (hf : Surjective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) : MulZeroClass M₀' where mul := (· * ·) zero := 0 mul_zero := hf.forall.2 fun x => by simp only [← zero, ← mul, mul_zero] zero_mul := hf.forall.2 fun x => by simp only [← zero, ← mul, zero_mul] end MulZeroClass section NoZeroDivisors variable [Mul M₀] [Zero M₀] [Mul M₀'] [Zero M₀'] (f : M₀ → M₀') (hf : Injective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) include hf zero mul /-- Pull back a `NoZeroDivisors` instance along an injective function. -/ protected theorem Function.Injective.noZeroDivisors [NoZeroDivisors M₀'] : NoZeroDivisors M₀ where eq_zero_or_eq_zero_of_mul_eq_zero {a b} H := have : f a * f b = 0 := by rw [← mul, H, zero] (eq_zero_or_eq_zero_of_mul_eq_zero this).imp (fun H ↦ hf <| by rwa [zero]) fun H ↦ hf <| by rwa [zero] protected theorem Function.Injective.isLeftCancelMulZero [IsLeftCancelMulZero M₀'] : IsLeftCancelMulZero M₀ where mul_left_cancel_of_ne_zero Hne _ _ He := by have := congr_arg f He rw [mul, mul] at this exact hf (mul_left_cancel₀ (fun Hfa => Hne <| hf <| by rw [Hfa, zero]) this) protected theorem Function.Injective.isRightCancelMulZero [IsRightCancelMulZero M₀'] : IsRightCancelMulZero M₀ where mul_right_cancel_of_ne_zero Hne _ _ He := by have := congr_arg f He rw [mul, mul] at this exact hf (mul_right_cancel₀ (fun Hfa => Hne <| hf <| by rw [Hfa, zero]) this) protected theorem Function.Injective.isCancelMulZero [IsCancelMulZero M₀'] : IsCancelMulZero M₀ where __ := hf.isLeftCancelMulZero f zero mul __ := hf.isRightCancelMulZero f zero mul end NoZeroDivisors section MulZeroOneClass variable [MulZeroOneClass M₀] /-- Pull back a `MulZeroOneClass` instance along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.mulZeroOneClass [Mul M₀'] [Zero M₀'] [One M₀'] (f : M₀' → M₀) (hf : Injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ a b, f (a * b) = f a * f b) : MulZeroOneClass M₀' := { hf.mulZeroClass f zero mul, hf.mulOneClass f one mul with } /-- Push forward a `MulZeroOneClass` instance along a surjective function. See note [reducible non-instances]. -/ protected abbrev Function.Surjective.mulZeroOneClass [Mul M₀'] [Zero M₀'] [One M₀'] (f : M₀ → M₀') (hf : Surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ a b, f (a * b) = f a * f b) : MulZeroOneClass M₀' := { hf.mulZeroClass f zero mul, hf.mulOneClass f one mul with } end MulZeroOneClass section SemigroupWithZero /-- Pull back a `SemigroupWithZero` along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.semigroupWithZero [Zero M₀'] [Mul M₀'] [SemigroupWithZero M₀] (f : M₀' → M₀) (hf : Injective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) : SemigroupWithZero M₀' := { hf.mulZeroClass f zero mul, ‹Zero M₀'›, hf.semigroup f mul with } /-- Push forward a `SemigroupWithZero` along a surjective function. See note [reducible non-instances]. -/ protected abbrev Function.Surjective.semigroupWithZero [SemigroupWithZero M₀] [Zero M₀'] [Mul M₀'] (f : M₀ → M₀') (hf : Surjective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) : SemigroupWithZero M₀' := { hf.mulZeroClass f zero mul, ‹Zero M₀'›, hf.semigroup f mul with } end SemigroupWithZero section MonoidWithZero /-- Pull back a `MonoidWithZero` along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.monoidWithZero [Zero M₀'] [Mul M₀'] [One M₀'] [Pow M₀' ℕ] [MonoidWithZero M₀] (f : M₀' → M₀) (hf : Injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : MonoidWithZero M₀' := { hf.monoid f one mul npow, hf.mulZeroClass f zero mul with } /-- Push forward a `MonoidWithZero` along a surjective function. See note [reducible non-instances]. -/ protected abbrev Function.Surjective.monoidWithZero [Zero M₀'] [Mul M₀'] [One M₀'] [Pow M₀' ℕ] [MonoidWithZero M₀] (f : M₀ → M₀') (hf : Surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : MonoidWithZero M₀' := { hf.monoid f one mul npow, hf.mulZeroClass f zero mul with } /-- Pull back a `CommMonoidWithZero` along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.commMonoidWithZero [Zero M₀'] [Mul M₀'] [One M₀'] [Pow M₀' ℕ] [CommMonoidWithZero M₀] (f : M₀' → M₀) (hf : Injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : CommMonoidWithZero M₀' := { hf.commMonoid f one mul npow, hf.mulZeroClass f zero mul with } /-- Push forward a `CommMonoidWithZero` along a surjective function. See note [reducible non-instances]. -/ protected abbrev Function.Surjective.commMonoidWithZero [Zero M₀'] [Mul M₀'] [One M₀'] [Pow M₀' ℕ] [CommMonoidWithZero M₀] (f : M₀ → M₀') (hf : Surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : CommMonoidWithZero M₀' := { hf.commMonoid f one mul npow, hf.mulZeroClass f zero mul with } end MonoidWithZero section CancelMonoidWithZero variable [CancelMonoidWithZero M₀] /-- Pull back a `CancelMonoidWithZero` along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.cancelMonoidWithZero [Zero M₀'] [Mul M₀'] [One M₀'] [Pow M₀' ℕ] (f : M₀' → M₀) (hf : Injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : CancelMonoidWithZero M₀' := { hf.monoid f one mul npow, hf.mulZeroClass f zero mul with mul_left_cancel_of_ne_zero hx _ _ H := hf <| mul_left_cancel₀ ((hf.ne_iff' zero).2 hx) <| by dsimp only at H; rw [← mul, ← mul, H], mul_right_cancel_of_ne_zero hx _ _ H := hf <| mul_right_cancel₀ ((hf.ne_iff' zero).2 hx) <| by dsimp only at H; rw [← mul, ← mul, H] } end CancelMonoidWithZero section CancelCommMonoidWithZero variable [CancelCommMonoidWithZero M₀] /-- Pull back a `CancelCommMonoidWithZero` along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.cancelCommMonoidWithZero [Zero M₀'] [Mul M₀'] [One M₀'] [Pow M₀' ℕ] (f : M₀' → M₀) (hf : Injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) : CancelCommMonoidWithZero M₀' := { hf.commMonoidWithZero f zero one mul npow, hf.cancelMonoidWithZero f zero one mul npow with } end CancelCommMonoidWithZero section GroupWithZero variable [GroupWithZero G₀] /-- Pull back a `GroupWithZero` along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.groupWithZero [Zero G₀'] [Mul G₀'] [One G₀'] [Inv G₀'] [Div G₀'] [Pow G₀' ℕ] [Pow G₀' ℤ] (f : G₀' → G₀) (hf : Injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : GroupWithZero G₀' := { hf.monoidWithZero f zero one mul npow, hf.divInvMonoid f one mul inv div npow zpow, domain_nontrivial f zero one with inv_zero := hf <| by rw [inv, zero, inv_zero], mul_inv_cancel := fun x hx => hf <| by rw [one, mul, inv, mul_inv_cancel₀ ((hf.ne_iff' zero).2 hx)] } /-- Push forward a `GroupWithZero` along a surjective function. See note [reducible non-instances]. -/ protected abbrev Function.Surjective.groupWithZero [Zero G₀'] [Mul G₀'] [One G₀'] [Inv G₀'] [Div G₀'] [Pow G₀' ℕ] [Pow G₀' ℤ] (h01 : (0 : G₀') ≠ 1) (f : G₀ → G₀') (hf : Surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : GroupWithZero G₀' := { hf.monoidWithZero f zero one mul npow, hf.divInvMonoid f one mul inv div npow zpow with inv_zero := by rw [← zero, ← inv, inv_zero], mul_inv_cancel := hf.forall.2 fun x hx => by rw [← inv, ← mul, mul_inv_cancel₀ (mt (congr_arg f) fun h ↦ hx (h.trans zero)), one] exists_pair_ne := ⟨0, 1, h01⟩ } end GroupWithZero section CommGroupWithZero variable [CommGroupWithZero G₀] /-- Pull back a `CommGroupWithZero` along an injective function. See note [reducible non-instances]. -/ protected abbrev Function.Injective.commGroupWithZero [Zero G₀'] [Mul G₀'] [One G₀'] [Inv G₀'] [Div G₀'] [Pow G₀' ℕ] [Pow G₀' ℤ] (f : G₀' → G₀) (hf : Injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : CommGroupWithZero G₀' := { hf.groupWithZero f zero one mul inv div npow zpow, hf.commSemigroup f mul with } /-- Push forward a `CommGroupWithZero` along a surjective function. See note [reducible non-instances]. -/ protected def Function.Surjective.commGroupWithZero [Zero G₀'] [Mul G₀'] [One G₀'] [Inv G₀'] [Div G₀'] [Pow G₀' ℕ] [Pow G₀' ℤ] (h01 : (0 : G₀') ≠ 1) (f : G₀ → G₀') (hf : Surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ (x) (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ (x) (n : ℤ), f (x ^ n) = f x ^ n) : CommGroupWithZero G₀' := { hf.groupWithZero h01 f zero one mul inv div npow zpow, hf.commSemigroup f mul with } end CommGroupWithZero
HomologicalComplexBiprod.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.HomologicalComplexLimits import Mathlib.Algebra.Homology.Additive /-! Binary biproducts of homological complexes In this file, it is shown that if two homological complex `K` and `L` in a preadditive category are such that for all `i : ι`, the binary biproduct `K.X i ⊞ L.X i` exists, then `K ⊞ L` exists, and there is an isomorphism `biprodXIso K L i : (K ⊞ L).X i ≅ (K.X i) ⊞ (L.X i)`. -/ open CategoryTheory Limits namespace HomologicalComplex variable {C ι : Type*} [Category C] [Preadditive C] {c : ComplexShape ι} (K L : HomologicalComplex C c) [∀ i, HasBinaryBiproduct (K.X i) (L.X i)] instance (i : ι) : HasBinaryBiproduct ((eval C c i).obj K) ((eval C c i).obj L) := by dsimp [eval] infer_instance instance (i : ι) : HasLimit ((pair K L) ⋙ (eval C c i)) := by have e : _ ≅ pair (K.X i) (L.X i) := diagramIsoPair (pair K L ⋙ eval C c i) exact hasLimit_of_iso e.symm instance (i : ι) : HasColimit ((pair K L) ⋙ (eval C c i)) := by have e : _ ≅ pair (K.X i) (L.X i) := diagramIsoPair (pair K L ⋙ eval C c i) exact hasColimit_of_iso e instance : HasBinaryBiproduct K L := HasBinaryBiproduct.of_hasBinaryProduct _ _ instance (i : ι) : PreservesBinaryBiproduct K L (eval C c i) := preservesBinaryBiproduct_of_preservesBinaryProduct _ /-- The canonical isomorphism `(K ⊞ L).X i ≅ (K.X i) ⊞ (L.X i)`. -/ noncomputable def biprodXIso (i : ι) : (K ⊞ L).X i ≅ (K.X i) ⊞ (L.X i) := (eval C c i).mapBiprod K L @[reassoc (attr := simp)] lemma inl_biprodXIso_inv (i : ι) : biprod.inl ≫ (biprodXIso K L i).inv = (biprod.inl : K ⟶ K ⊞ L).f i := by simp [biprodXIso] @[reassoc (attr := simp)] lemma inr_biprodXIso_inv (i : ι) : biprod.inr ≫ (biprodXIso K L i).inv = (biprod.inr : L ⟶ K ⊞ L).f i := by simp [biprodXIso] @[reassoc (attr := simp)] lemma biprodXIso_hom_fst (i : ι) : (biprodXIso K L i).hom ≫ biprod.fst = (biprod.fst : K ⊞ L ⟶ K).f i := by simp [biprodXIso] @[reassoc (attr := simp)] lemma biprodXIso_hom_snd (i : ι) : (biprodXIso K L i).hom ≫ biprod.snd = (biprod.snd : K ⊞ L ⟶ L).f i := by simp [biprodXIso] @[reassoc (attr := simp)] lemma biprod_inl_fst_f (i : ι) : (biprod.inl : K ⟶ K ⊞ L).f i ≫ (biprod.fst : K ⊞ L ⟶ K).f i = 𝟙 _ := by rw [← comp_f, biprod.inl_fst, id_f] @[reassoc (attr := simp)] lemma biprod_inl_snd_f (i : ι) : (biprod.inl : K ⟶ K ⊞ L).f i ≫ (biprod.snd : K ⊞ L ⟶ L).f i = 0 := by rw [← comp_f, biprod.inl_snd, zero_f] @[reassoc (attr := simp)] lemma biprod_inr_fst_f (i : ι) : (biprod.inr : L ⟶ K ⊞ L).f i ≫ (biprod.fst : K ⊞ L ⟶ K).f i = 0 := by rw [← comp_f, biprod.inr_fst, zero_f] @[reassoc (attr := simp)] lemma biprod_inr_snd_f (i : ι) : (biprod.inr : L ⟶ K ⊞ L).f i ≫ (biprod.snd : K ⊞ L ⟶ L).f i = 𝟙 _ := by rw [← comp_f, biprod.inr_snd, id_f] variable {K L} variable {M : HomologicalComplex C c} @[reassoc (attr := simp)] lemma biprod_inl_desc_f (α : K ⟶ M) (β : L ⟶ M) (i : ι) : (biprod.inl : K ⟶ K ⊞ L).f i ≫ (biprod.desc α β).f i = α.f i := by rw [← comp_f, biprod.inl_desc] @[reassoc (attr := simp)] lemma biprod_inr_desc_f (α : K ⟶ M) (β : L ⟶ M) (i : ι) : (biprod.inr : L ⟶ K ⊞ L).f i ≫ (biprod.desc α β).f i = β.f i := by rw [← comp_f, biprod.inr_desc] @[reassoc (attr := simp)] lemma biprod_lift_fst_f (α : M ⟶ K) (β : M ⟶ L) (i : ι) : (biprod.lift α β).f i ≫ (biprod.fst : K ⊞ L ⟶ K).f i = α.f i := by rw [← comp_f, biprod.lift_fst] @[reassoc (attr := simp)] lemma biprod_lift_snd_f (α : M ⟶ K) (β : M ⟶ L) (i : ι) : (biprod.lift α β).f i ≫ (biprod.snd : K ⊞ L ⟶ L).f i = β.f i := by rw [← comp_f, biprod.lift_snd] end HomologicalComplex
Induced.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, Jeremy Avigad -/ import Mathlib.Data.Set.Lattice.Image import Mathlib.Topology.Basic /-! # Induced and coinduced topologies In this file we define the induced and coinduced topologies, as well as topology inducing maps, topological embeddings, and quotient maps. ## Main definitions * `TopologicalSpace.induced`: given `f : X → Y` and a topology on `Y`, the induced topology on `X` is the collection of sets that are preimages of some open set in `Y`. This is the coarsest topology that makes `f` continuous. * `TopologicalSpace.coinduced`: given `f : X → Y` and a topology on `X`, the coinduced topology on `Y` is defined such that `s : Set Y` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. * `IsInducing`: a map `f : X → Y` is called *inducing*, if the topology on the domain is equal to the induced topology. * `IsEmbedding`: a map `f : X → Y` is an *embedding*, if it is a topology inducing map and it is injective. * `IsOpenEmbedding`: a map `f : X → Y` is an *open embedding*, if it is an embedding and its range is open. An open embedding is an open map. * `IsClosedEmbedding`: a map `f : X → Y` is an *open embedding*, if it is an embedding and its range is open. An open embedding is an open map. * `IsQuotientMap`: a map `f : X → Y` is a *quotient map*, if it is surjective and the topology on the codomain is equal to the coinduced topology. -/ open Set open scoped Topology namespace TopologicalSpace variable {X Y : Type*} /-- Given `f : X → Y` and a topology on `Y`, the induced topology on `X` is the collection of sets that are preimages of some open set in `Y`. This is the coarsest topology that makes `f` continuous. -/ def induced (f : X → Y) (t : TopologicalSpace Y) : TopologicalSpace X where IsOpen s := ∃ t, IsOpen t ∧ f ⁻¹' t = s isOpen_univ := ⟨univ, isOpen_univ, preimage_univ⟩ isOpen_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩ exact ⟨s'₁ ∩ s'₂, hs₁.inter hs₂, preimage_inter⟩ isOpen_sUnion S h := by choose! g hgo hfg using h refine ⟨⋃₀ (g '' S), isOpen_sUnion <| forall_mem_image.2 hgo, ?_⟩ rw [preimage_sUnion, biUnion_image, sUnion_eq_biUnion] exact iUnion₂_congr hfg instance _root_.instTopologicalSpaceSubtype {p : X → Prop} [t : TopologicalSpace X] : TopologicalSpace (Subtype p) := induced (↑) t /-- Given `f : X → Y` and a topology on `X`, the coinduced topology on `Y` is defined such that `s : Set Y` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def coinduced (f : X → Y) (t : TopologicalSpace X) : TopologicalSpace Y where IsOpen s := IsOpen (f ⁻¹' s) isOpen_univ := t.isOpen_univ isOpen_inter _ _ h₁ h₂ := h₁.inter h₂ isOpen_sUnion s h := by simpa only [preimage_sUnion] using isOpen_biUnion h end TopologicalSpace namespace Topology variable {X Y : Type*} [tX : TopologicalSpace X] [tY : TopologicalSpace Y] /-- We say that restrictions of the topology on `X` to sets from a family `S` generates the original topology, if either of the following equivalent conditions hold: - a set which is relatively open in each `s ∈ S` is open; - a set which is relatively closed in each `s ∈ S` is closed; - for any topological space `Y`, a function `f : X → Y` is continuous provided that it is continuous on each `s ∈ S`. -/ structure IsCoherentWith (S : Set (Set X)) : Prop where isOpen_of_forall_induced (u : Set X) : (∀ s ∈ S, IsOpen ((↑) ⁻¹' u : Set s)) → IsOpen u @[deprecated (since := "2025-04-08")] alias RestrictGenTopology := Topology.IsCoherentWith /-- A function `f : X → Y` between topological spaces is inducing if the topology on `X` is induced by the topology on `Y` through `f`, meaning that a set `s : Set X` is open iff it is the preimage under `f` of some open set `t : Set Y`. -/ @[mk_iff] structure IsInducing (f : X → Y) : Prop where /-- The topology on the domain is equal to the induced topology. -/ eq_induced : tX = tY.induced f /-- A function between topological spaces is an embedding if it is injective, and for all `s : Set X`, `s` is open iff it is the preimage of an open set. -/ @[mk_iff] structure IsEmbedding (f : X → Y) : Prop extends IsInducing f where /-- A topological embedding is injective. -/ injective : Function.Injective f /-- An open embedding is an embedding with open range. -/ @[mk_iff] structure IsOpenEmbedding (f : X → Y) : Prop extends IsEmbedding f where /-- The range of an open embedding is an open set. -/ isOpen_range : IsOpen <| range f /-- A closed embedding is an embedding with closed image. -/ @[mk_iff] structure IsClosedEmbedding (f : X → Y) : Prop extends IsEmbedding f where /-- The range of a closed embedding is a closed set. -/ isClosed_range : IsClosed <| range f /-- A function between topological spaces is a quotient map if it is surjective, and for all `s : Set Y`, `s` is open iff its preimage is an open set. -/ @[mk_iff isQuotientMap_iff'] structure IsQuotientMap {X : Type*} {Y : Type*} [tX : TopologicalSpace X] [tY : TopologicalSpace Y] (f : X → Y) : Prop where surjective : Function.Surjective f eq_coinduced : tY = tX.coinduced f end Topology
nmodule.v
From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype choice ssrnat seq. From mathcomp Require Import bigop fintype finfun monoid. (******************************************************************************) (* Additive group-like structures *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines the following algebraic structures: *) (* *) (* baseAddMagmaType == type with an addition operator *) (* The HB class is called BaseAddMagma. *) (* ChoiceBaseAddMagma.type == join of baseAddMagmaType and choiceType *) (* The HB class is called ChoiceBaseAddMagma. *) (* addMagmaType == additive magma *) (* The HB class is called AddMagma. *) (* addSemigroupType == additive semigroup *) (* The HB class is called AddSemigroup. *) (* baseAddUMagmaType == pointed additive magma *) (* The HB class is called BaseAddUMagma. *) (* ChoiceBaseAddUMagma.type == join of baseAddUMagmaType and choiceType *) (* The HB class is called ChoiceBaseUMagma. *) (* addUmagmaType == additive unitary magma *) (* The HB class is called AddUMagma. *) (* nmodType == additive monoid *) (* The HB class is called Nmodule. *) (* baseZmodType == pointed additive magma with an opposite *) (* operator *) (* The HB class is called BaseZmodule. *) (* zmodType == abelian group *) (* The HB class is called Group. *) (* *) (* and their joins with subType: *) (* *) (* subBaseAddUMagmaType V P == join of baseAddUMagmaType and subType *) (* (P : pred V) such that val is additive *) (* The HB class is called SubBaseAddUMagma. *) (* subAddUMagmaType V P == join of addUMagmaType and subType (P : pred V)*) (* such that val is additive *) (* The HB class is called SubAddUMagma. *) (* subNmodType V P == join of nmodType and subType (P : pred V) *) (* such that val is additive *) (* The HB class is called SubNmodule. *) (* subZmodType V P == join of zmodType and subType (P : pred V) *) (* such that val is additive *) (* The HB class is called SubZmodule. *) (* *) (* Morphisms between the above structures (see below for details): *) (* *) (* {additive U -> V} == nmod (resp. zmod) morphism between nmodType *) (* (resp. zmodType) instances U and V. *) (* The HB class is called Additive. *) (* *) (* Closedness predicates for the algebraic structures: *) (* *) (* mulgClosed V == predicate closed under multiplication on G : magmaType *) (* The HB class is called MulClosed. *) (* umagmaClosed V == predicate closed under multiplication and containing 1 *) (* on G : baseUMagmaType *) (* The HB class is called UMagmaClosed. *) (* invgClosed V == predicate closed under inversion on G : baseGroupType *) (* The HB class is called InvClosed. *) (* groupClosed V == predicate closed under multiplication and inversion and *) (* containing 1 on G : baseGroupType *) (* The HB class is called InvClosed. *) (* *) (* Canonical properties of the algebraic structures: *) (* * addMagmaType (additive magmas): *) (* x + y == the addition of x and y *) (* addr_closed S <-> collective predicate S is closed under addition *) (* *) (* * baseAddUMagmaType (pointed additive magmas): *) (* 0 == the zero of a unitary additive magma *) (* x *+ n == n times x, with n in nat (non-negative), *) (* i.e. x + (x + .. (x + x)..) (n terms); x *+ 1 is *) (* thus convertible to x, and x *+ 2 to x + x *) (* \sum_<range> e == iterated sum for a baseAddUMagmaType (cf bigop.v)*) (* e`_i == nth 0 e i, when e : seq M and M has an *) (* addUMagmaType structure *) (* support f == 0.-support f, i.e., [pred x | f x != 0] *) (* addumagma_closed S <-> collective predicate S is closed under *) (* addition and contains 0 *) (* *) (* * nmodType (abelian monoids): *) (* nmod_closed S := addumagma_closed S *) (* *) (* * baseZmodType (pointed additive magmas with an opposite operator): *) (* - x == the opposite of x *) (* x - y == x + (- y) *) (* x *- n == - (x *+ n) *) (* oppr_closed S <-> collective predicate S is closed under opposite *) (* subr_closed S <-> collective predicate S is closed under *) (* subtraction *) (* zmod_closed S <-> collective predicate S is closed under *) (* subtraction and contains 1 *) (* *) (* In addition to this structure hierarchy, we also develop a separate, *) (* parallel hierarchy for morphisms linking these structures: *) (* *) (* * Additive (nmod or zmod morphisms): *) (* nmod_morphism f <-> f of type U -> V is an nmod morphism, i.e., f *) (* maps the Nmodule structure of U to that of V, 0 *) (* to 0 and + to + *) (* := (f 0 = 0) * {morph f : x y / x + y} *) (* zmod_morphisme f <-> f of type U -> V is a zmod morphism, i.e., f *) (* maps the Zmodule structure of U to that of V, 0 *) (* to 0, - to - and + to + (equivalently, binary - *) (* to -) *) (* := {morph f : u v / u - v} *) (* {additive U -> V} == the interface type for a Structure (keyed on *) (* a function f : U -> V) that encapsulates the *) (* nmod_morphism property; both U and V must have *) (* canonical baseAddUMagmaType instances *) (* When both U and V have zmodType instances, it is *) (* a zmod morphism. *) (* := Algebra.Additive.type U V *) (* *) (* Notations are defined in scope ring_scope (delimiter %R) *) (* This library also extends the conventional suffixes described in library *) (* ssrbool.v with the following: *) (* 0 -- unitary additive magma 0, as in addr0 : x + 0 = x *) (* D -- additive magma addition, as in mulrnDr : *) (* x *+ (m + n) = x *+ m + x *+ n *) (* B -- z-module subtraction, as in opprB : - (x - y) = y - x *) (* Mn -- ring by nat multiplication, as in raddfMn : f (x *+ n) = f x *+ n *) (* N -- z-module opposite, as in mulNr : (- x) * y = - (x * y) *) (* The operator suffixes D, B are also used for the corresponding operations *) (* on nat, as in mulrDr : x *+ (m + n) = x *+ m + x *+ n. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope ring_scope. Delimit Scope ring_scope with R. Local Open Scope ring_scope. Reserved Notation "+%R" (at level 0). Reserved Notation "-%R" (at level 0). Reserved Notation "n %:R" (at level 1, left associativity, format "n %:R"). Reserved Notation "\0" (at level 0). Reserved Notation "f \+ g" (at level 50, left associativity). Reserved Notation "f \- g" (at level 50, left associativity). Reserved Notation "\- f" (at level 35, f at level 35). Reserved Notation "'{' 'additive' U '->' V '}'" (at level 0, U at level 98, V at level 99, format "{ 'additive' U -> V }"). Module Import Algebra. HB.mixin Record hasAdd V := { add : V -> V -> V }. #[short(type="baseAddMagmaType")] HB.structure Definition BaseAddMagma := {V of hasAdd V}. Module BaseAddMagmaExports. Bind Scope ring_scope with BaseAddMagma.sort. End BaseAddMagmaExports. HB.export BaseAddMagmaExports. HB.structure Definition ChoiceBaseAddMagma := {V of BaseAddMagma V & Choice V}. Module ChoiceBaseAddMagmaExports. Bind Scope ring_scope with ChoiceBaseAddMagma.sort. End ChoiceBaseAddMagmaExports. HB.export ChoiceBaseAddMagmaExports. Local Notation "+%R" := (@add _) : function_scope. Local Notation "x + y" := (add x y) : ring_scope. Definition to_multiplicative := @id Type. #[export] HB.instance Definition _ (V : choiceType) := Choice.on (to_multiplicative V). #[export] HB.instance Definition _ (V : baseAddMagmaType) := hasMul.Build (to_multiplicative V) (@add V). (* FIXME: HB.saturate *) #[export] HB.instance Definition _ (V : ChoiceBaseAddMagma.type) := Magma.on (to_multiplicative V). Section BaseAddMagmaTheory. Variables V : baseAddMagmaType. Section ClosedPredicates. Variable S : {pred V}. Definition addr_closed := {in S &, forall u v, u + v \in S}. End ClosedPredicates. End BaseAddMagmaTheory. HB.mixin Record BaseAddMagma_isAddMagma V of BaseAddMagma V := { addrC : commutative (@add V) }. #[short(type="addMagmaType")] HB.structure Definition AddMagma := {V of BaseAddMagma_isAddMagma V & ChoiceBaseAddMagma V}. HB.factory Record isAddMagma V of Choice V := { add : V -> V -> V; addrC : commutative add }. HB.builders Context V of isAddMagma V. HB.instance Definition _ := hasAdd.Build V add. HB.instance Definition _ := BaseAddMagma_isAddMagma.Build V addrC. HB.end. Module AddMagmaExports. Bind Scope ring_scope with AddMagma.sort. End AddMagmaExports. HB.export AddMagmaExports. Section AddMagmaTheory. Variables V : addMagmaType. Lemma commuteT x y : @commute (to_multiplicative V) x y. Proof. exact/addrC. Qed. End AddMagmaTheory. HB.mixin Record AddMagma_isAddSemigroup V of AddMagma V := { addrA : associative (@add V) }. #[short(type="addSemigroupType")] HB.structure Definition AddSemigroup := {V of AddMagma_isAddSemigroup V & AddMagma V}. HB.factory Record isAddSemigroup V of Choice V := { add : V -> V -> V; addrC : commutative add; addrA : associative add }. HB.builders Context V of isAddSemigroup V. HB.instance Definition _ := isAddMagma.Build V addrC. HB.instance Definition _ := AddMagma_isAddSemigroup.Build V addrA. HB.end. Module AddSemigroupExports. Bind Scope ring_scope with AddSemigroup.sort. End AddSemigroupExports. HB.export AddSemigroupExports. #[export] HB.instance Definition _ (V : addSemigroupType) := Magma_isSemigroup.Build (to_multiplicative V) addrA. Section AddSemigroupTheory. Variables V : addSemigroupType. Lemma addrCA : @left_commutative V V +%R. Proof. by move=> x y z; rewrite !addrA [x + _]addrC. Qed. Lemma addrAC : @right_commutative V V +%R. Proof. by move=> x y z; rewrite -!addrA [y + _]addrC. Qed. Lemma addrACA : @interchange V +%R +%R. Proof. by move=> x y z t; rewrite -!addrA [y + (z + t)]addrCA. Qed. End AddSemigroupTheory. HB.mixin Record hasZero V := { zero : V }. #[short(type="baseAddUMagmaType")] HB.structure Definition BaseAddUMagma := {V of hasZero V & BaseAddMagma V}. Module BaseAddUMagmaExports. Bind Scope ring_scope with BaseAddUMagma.sort. End BaseAddUMagmaExports. HB.export BaseAddUMagmaExports. HB.structure Definition ChoiceBaseAddUMagma := {V of BaseAddUMagma V & Choice V}. Module ChoiceBaseAddUMagmaExports. Bind Scope ring_scope with ChoiceBaseAddUMagma.sort. End ChoiceBaseAddUMagmaExports. HB.export ChoiceBaseAddUMagmaExports. Local Notation "0" := (@zero _) : ring_scope. Definition natmul (V : baseAddUMagmaType) (x : V) n : V := iterop n +%R x 0. Arguments natmul : simpl never. Local Notation "x *+ n" := (natmul x n) : ring_scope. #[export] HB.instance Definition _ (V : baseAddUMagmaType) := hasOne.Build (to_multiplicative V) (@zero V). (* FIXME: HB.saturate *) #[export] HB.instance Definition _ (V : ChoiceBaseAddUMagma.type) := BaseUMagma.on (to_multiplicative V). Section BaseAddUMagmaTheory. Variable V : baseAddUMagmaType. Implicit Types x : V. Lemma mulr0n x : x *+ 0 = 0. Proof. by []. Qed. Lemma mulr1n x : x *+ 1 = x. Proof. by []. Qed. Lemma mulr2n x : x *+ 2 = x + x. Proof. by []. Qed. Lemma mulrb x (b : bool) : x *+ b = (if b then x else 0). Proof. exact: (@expgb (to_multiplicative V)). Qed. Lemma mulrSS x n : x *+ n.+2 = x + x *+ n.+1. Proof. by []. Qed. Section ClosedPredicates. Variable S : {pred V}. Definition addumagma_closed := 0 \in S /\ addr_closed S. End ClosedPredicates. End BaseAddUMagmaTheory. HB.mixin Record BaseAddUMagma_isAddUMagma V of BaseAddUMagma V := { add0r : left_id zero (@add V) }. HB.factory Record isAddUMagma V of Choice V := { add : V -> V -> V; zero : V; addrC : commutative add; add0r : left_id zero add }. HB.builders Context V of isAddUMagma V. HB.instance Definition _ := isAddMagma.Build V addrC. HB.instance Definition _ := hasZero.Build V zero. #[warning="-HB.no-new-instance"] HB.instance Definition _ := BaseAddUMagma_isAddUMagma.Build V add0r. HB.end. #[short(type="addUMagmaType")] HB.structure Definition AddUMagma := {V of isAddUMagma V & Choice V}. Lemma addr0 (V : addUMagmaType) : right_id (@zero V) add. Proof. by move=> x; rewrite addrC add0r. Qed. Local Notation "\sum_ ( i <- r | P ) F" := (\big[+%R/0]_(i <- r | P) F). Local Notation "\sum_ ( m <= i < n ) F" := (\big[+%R/0]_(m <= i < n) F). Local Notation "\sum_ ( i < n ) F" := (\big[+%R/0]_(i < n) F). Local Notation "\sum_ ( i 'in' A ) F" := (\big[+%R/0]_(i in A) F). Import Monoid.Theory. #[export] HB.instance Definition _ (V : addUMagmaType) := Magma_isUMagma.Build (to_multiplicative V) add0r (@addr0 V). HB.factory Record isNmodule V of Choice V := { zero : V; add : V -> V -> V; addrA : associative add; addrC : commutative add; add0r : left_id zero add }. HB.builders Context V of isNmodule V. HB.instance Definition _ := isAddUMagma.Build V addrC add0r. HB.instance Definition _ := AddMagma_isAddSemigroup.Build V addrA. HB.end. Module AddUMagmaExports. Bind Scope ring_scope with AddUMagma.sort. End AddUMagmaExports. HB.export AddUMagmaExports. #[short(type="nmodType")] HB.structure Definition Nmodule := {V of isNmodule V & Choice V}. Module NmoduleExports. Bind Scope ring_scope with Nmodule.sort. End NmoduleExports. HB.export NmoduleExports. #[export] HB.instance Definition _ (V : nmodType) := UMagma_isMonoid.Build (to_multiplicative V) addrA. #[export] HB.instance Definition _ (V : nmodType) := Monoid.isComLaw.Build V 0%R +%R addrA addrC add0r. Section NmoduleTheory. Variable V : nmodType. Implicit Types x y : V. Let G := to_multiplicative V. (* addrA, addrC and add0r in the structure *) (* addr0 proved above *) Lemma mulrS x n : x *+ n.+1 = x + (x *+ n). Proof. exact: (@expgS G). Qed. Lemma mulrSr x n : x *+ n.+1 = x *+ n + x. Proof. exact: (@expgSr G). Qed. Lemma mul0rn n : 0 *+ n = 0 :> V. Proof. exact: (@expg1n G). Qed. Lemma mulrnDl n : {morph (fun x => x *+ n) : x y / x + y}. Proof. by move=> x y; apply/(@expgMn G)/commuteT. Qed. Lemma mulrnDr x m n : x *+ (m + n) = x *+ m + x *+ n. Proof. exact: (@expgnDr G). Qed. Lemma mulrnA x m n : x *+ (m * n) = x *+ m *+ n. Proof. exact: (@expgnA G). Qed. Lemma mulrnAC x m n : x *+ m *+ n = x *+ n *+ m. Proof. exact: (@expgnAC G). Qed. Lemma iter_addr n x y : iter n (+%R x) y = x *+ n + y. Proof. exact: (@iter_mulg G). Qed. Lemma iter_addr_0 n x : iter n (+%R x) 0 = x *+ n. Proof. exact: (@iter_mulg_1 G). Qed. Lemma sumrMnl I r P (F : I -> V) n : \sum_(i <- r | P i) F i *+ n = (\sum_(i <- r | P i) F i) *+ n. Proof. by rewrite (big_morph _ (mulrnDl n) (mul0rn _)). Qed. Lemma sumrMnr x I r P (F : I -> nat) : \sum_(i <- r | P i) x *+ F i = x *+ (\sum_(i <- r | P i) F i). Proof. by rewrite (big_morph _ (mulrnDr x) (erefl _)). Qed. Lemma sumr_const (I : finType) (A : pred I) x : \sum_(i in A) x = x *+ #|A|. Proof. by rewrite big_const -iteropE. Qed. Lemma sumr_const_nat m n x : \sum_(n <= i < m) x = x *+ (m - n). Proof. by rewrite big_const_nat iter_addr_0. Qed. End NmoduleTheory. Notation nmod_closed := addumagma_closed. HB.mixin Record hasOpp V := { opp : V -> V }. #[short(type="baseZmodType")] HB.structure Definition BaseZmodule := {V of hasOpp V & BaseAddUMagma V}. Module BaseZmodExports. Bind Scope ring_scope with BaseZmodule.sort. End BaseZmodExports. HB.export BaseZmodExports. Local Notation "-%R" := (@opp _) : ring_scope. Local Notation "- x" := (opp x) : ring_scope. Local Notation "x - y" := (x + - y) : ring_scope. Local Notation "x *- n" := (- (x *+ n)) : ring_scope. Section ClosedPredicates. Variable (U : baseZmodType) (S : {pred U}). Definition oppr_closed := {in S, forall u, - u \in S}. Definition subr_closed := {in S &, forall u v, u - v \in S}. Definition zmod_closed := 0 \in S /\ subr_closed. End ClosedPredicates. HB.mixin Record BaseZmoduleNmodule_isZmodule V of BaseZmodule V := { addNr : left_inverse zero opp (@add V) }. #[short(type="zmodType")] HB.structure Definition Zmodule := {V of BaseZmoduleNmodule_isZmodule V & BaseZmodule V & Nmodule V}. HB.factory Record Nmodule_isZmodule V of Nmodule V := { opp : V -> V; addNr : left_inverse zero opp add }. HB.builders Context V of Nmodule_isZmodule V. HB.instance Definition _ := hasOpp.Build V opp. HB.instance Definition _ := BaseZmoduleNmodule_isZmodule.Build V addNr. HB.end. HB.factory Record isZmodule V of Choice V := { zero : V; opp : V -> V; add : V -> V -> V; addrA : associative add; addrC : commutative add; add0r : left_id zero add; addNr : left_inverse zero opp add }. HB.builders Context V of isZmodule V. HB.instance Definition _ := isNmodule.Build V addrA addrC add0r. HB.instance Definition _ := Nmodule_isZmodule.Build V addNr. HB.end. Module ZmoduleExports. Bind Scope ring_scope with Zmodule.sort. End ZmoduleExports. HB.export ZmoduleExports. Lemma addrN (V : zmodType) : @right_inverse V V V 0 -%R +%R. Proof. by move=> x; rewrite addrC addNr. Qed. #[export] HB.instance Definition _ (V : baseZmodType) := hasInv.Build (to_multiplicative V) (@opp V). #[export] HB.instance Definition _ (V : zmodType) := Monoid_isGroup.Build (to_multiplicative V) addNr (@addrN V). Section ZmoduleTheory. Variable V : zmodType. Implicit Types x y : V. Let G := to_multiplicative V. Definition subrr := addrN. Lemma addKr : @left_loop V V -%R +%R. Proof. exact: (@mulKg G). Qed. Lemma addNKr : @rev_left_loop V V -%R +%R. Proof. exact: (@mulVKg G). Qed. Lemma addrK : @right_loop V V -%R +%R. Proof. exact: (@mulgK G). Qed. Lemma addrNK : @rev_right_loop V V -%R +%R. Proof. exact: (@mulgVK G). Qed. Definition subrK := addrNK. Lemma subKr x : involutive (fun y => x - y). Proof. by move=> y; exact/(@divKg G)/commuteT. Qed. Lemma addrI : @right_injective V V V +%R. Proof. exact: (@mulgI G). Qed. Lemma addIr : @left_injective V V V +%R. Proof. exact: (@mulIg G). Qed. Lemma subrI : right_injective (fun x y => x - y). Proof. exact: (@divgI G). Qed. Lemma subIr : left_injective (fun x y => x - y). Proof. exact: (@divIg G). Qed. Lemma opprK : @involutive V -%R. Proof. exact: (@invgK G). Qed. Lemma oppr_inj : @injective V V -%R. Proof. exact: (@invg_inj G). Qed. Lemma oppr0 : -0 = 0 :> V. Proof. exact: (@invg1 G). Qed. Lemma oppr_eq0 x : (- x == 0) = (x == 0). Proof. exact: (@invg_eq1 G). Qed. Lemma subr0 x : x - 0 = x. Proof. exact: (@divg1 G). Qed. Lemma sub0r x : 0 - x = - x. Proof. exact: (@div1g G). Qed. Lemma opprB x y : - (x - y) = y - x. Proof. exact: (@invgF G). Qed. Lemma opprD : {morph -%R: x y / x + y : V}. Proof. by move=> x y; rewrite -[y in LHS]opprK opprB addrC. Qed. Lemma addrKA z x y : (x + z) - (z + y) = x - y. Proof. by rewrite opprD addrA addrK. Qed. Lemma subrKA z x y : (x - z) + (z + y) = x + y. Proof. exact: (@divgKA G). Qed. Lemma addr0_eq x y : x + y = 0 -> - x = y. Proof. exact: (@mulg1_eq G). Qed. Lemma subr0_eq x y : x - y = 0 -> x = y. Proof. exact: (@divg1_eq G). Qed. Lemma subr_eq x y z : (x - z == y) = (x == y + z). Proof. exact: (@divg_eq G). Qed. Lemma subr_eq0 x y : (x - y == 0) = (x == y). Proof. exact: (@divg_eq1 G). Qed. Lemma addr_eq0 x y : (x + y == 0) = (x == - y). Proof. exact: (@mulg_eq1 G). Qed. Lemma eqr_opp x y : (- x == - y) = (x == y). Proof. exact: (@eqg_inv G). Qed. Lemma eqr_oppLR x y : (- x == y) = (x == - y). Proof. exact: (@eqg_invLR G). Qed. Lemma mulNrn x n : (- x) *+ n = x *- n. Proof. exact: (@expVgn G). Qed. Lemma mulrnBl n : {morph (fun x => x *+ n) : x y / x - y}. Proof. by move=> x y; exact/(@expgnFl G)/commuteT. Qed. Lemma mulrnBr x m n : n <= m -> x *+ (m - n) = x *+ m - x *+ n. Proof. exact: (@expgnFr G). Qed. Lemma sumrN I r P (F : I -> V) : (\sum_(i <- r | P i) - F i = - (\sum_(i <- r | P i) F i)). Proof. by rewrite (big_morph _ opprD oppr0). Qed. Lemma sumrB I r (P : pred I) (F1 F2 : I -> V) : \sum_(i <- r | P i) (F1 i - F2 i) = \sum_(i <- r | P i) F1 i - \sum_(i <- r | P i) F2 i. Proof. by rewrite -sumrN -big_split /=. Qed. Lemma telescope_sumr n m (f : nat -> V) : n <= m -> \sum_(n <= k < m) (f k.+1 - f k) = f m - f n. Proof. move=> nm; rewrite (telescope_big (fun i j => f j - f i)). by case: ltngtP nm => // ->; rewrite subrr. by move=> k /andP[nk km]/=; rewrite addrC subrKA. Qed. Lemma telescope_sumr_eq n m (f u : nat -> V) : n <= m -> (forall k, (n <= k < m)%N -> u k = f k.+1 - f k) -> \sum_(n <= k < m) u k = f m - f n. Proof. by move=> ? uE; under eq_big_nat do rewrite uE //=; exact: telescope_sumr. Qed. Section ClosedPredicates. Variable (S : {pred V}). Lemma zmod_closedN : zmod_closed S -> oppr_closed S. Proof. exact: (@group_closedV G). Qed. Lemma zmod_closedD : zmod_closed S -> addr_closed S. Proof. exact: (@group_closedM G). Qed. Lemma zmod_closed0D : zmod_closed S -> nmod_closed S. Proof. by move=> z; split; [case: z|apply: zmod_closedD]. Qed. End ClosedPredicates. End ZmoduleTheory. Arguments addrI {V} y [x1 x2]. Arguments addIr {V} x [x1 x2]. Arguments opprK {V}. Arguments oppr_inj {V} [x1 x2]. Definition nmod_morphism (U V : baseAddUMagmaType) (f : U -> V) : Prop := (f 0 = 0) * {morph f : x y / x + y}. #[deprecated(since="mathcomp 2.5.0", note="use `nmod_morphism` instead")] Definition semi_additive := nmod_morphism. HB.mixin Record isNmodMorphism (U V : baseAddUMagmaType) (apply : U -> V) := { nmod_morphism_subproof : nmod_morphism apply; }. Module isSemiAdditive. #[deprecated(since="mathcomp 2.5.0", note="Use isNmodMorphism.Build instead.")] Notation Build U V apply := (isNmodMorphism.Build U V apply) (only parsing). End isSemiAdditive. #[mathcomp(axiom="nmod_morphism")] HB.structure Definition Additive (U V : baseAddUMagmaType) := {f of isNmodMorphism U V f}. Definition zmod_morphism (U V : zmodType) (f : U -> V) := {morph f : x y / x - y}. #[deprecated(since="mathcomp 2.5.0", note="use `zmod_morphism` instead")] Definition additive := zmod_morphism. HB.factory Record isZmodMorphism (U V : zmodType) (apply : U -> V) := { zmod_morphism_subproof : zmod_morphism apply; }. Module isAdditive. #[deprecated(since="mathcomp 2.5.0", note="Use isZmodMorphism.Build instead.")] Notation Build U V apply := (isZmodMorphism.Build U V apply) (only parsing). End isAdditive. HB.builders Context U V apply of isZmodMorphism U V apply. Local Lemma raddf0 : apply 0 = 0. Proof. by rewrite -[0]subr0 zmod_morphism_subproof subrr. Qed. Local Lemma raddfD : {morph apply : x y / x + y}. Proof. move=> x y; rewrite -[y in LHS]opprK -[- y]add0r. by rewrite !zmod_morphism_subproof raddf0 sub0r opprK. Qed. HB.instance Definition _ := isNmodMorphism.Build U V apply (conj raddf0 raddfD). HB.end. Module AdditiveExports. Notation "{ 'additive' U -> V }" := (Additive.type U%type V%type) : type_scope. End AdditiveExports. HB.export AdditiveExports. Section AdditiveTheory. Variables (U V : baseAddUMagmaType) (f : {additive U -> V}). Lemma raddf0 : f 0 = 0. Proof. exact: nmod_morphism_subproof.1. Qed. Lemma raddfD : {morph f : x y / x + y}. Proof. exact: nmod_morphism_subproof.2. Qed. End AdditiveTheory. Definition to_fmultiplicative U V := @id (to_multiplicative U -> to_multiplicative V). #[export] HB.instance Definition _ U V (f : {additive U -> V}) := isMultiplicative.Build (to_multiplicative U) (to_multiplicative V) (to_fmultiplicative f) (@raddfD _ _ f). #[export] HB.instance Definition _ (U V : baseAddUMagmaType) (f : {additive U -> V}) := Multiplicative_isUMagmaMorphism.Build (to_multiplicative U) (to_multiplicative V) (to_fmultiplicative f) (@raddf0 _ _ f). Section LiftedAddMagma. Variables (U : Type) (V : baseAddMagmaType). Definition add_fun (f g : U -> V) x := f x + g x. End LiftedAddMagma. Section LiftedNmod. Variables (U : Type) (V : baseAddUMagmaType). Definition null_fun of U : V := 0. End LiftedNmod. Section LiftedZmod. Variables (U : Type) (V : baseZmodType). Definition opp_fun (f : U -> V) x := - f x. Definition sub_fun (f g : U -> V) x := f x - g x. End LiftedZmod. Arguments null_fun {_} V _ /. Arguments add_fun {_ _} f g _ /. Arguments opp_fun {_ _} f _ /. Arguments sub_fun {_ _} f g _ /. Local Notation "\0" := (null_fun _) : function_scope. Local Notation "f \+ g" := (add_fun f g) : function_scope. Local Notation "\- f" := (opp_fun f) : function_scope. Local Notation "f \- g" := (sub_fun f g) : function_scope. Section Nmod. Variables (U V : addUMagmaType) (f : {additive U -> V}). Let g := to_fmultiplicative f. Lemma raddf_eq0 x : injective f -> (f x == 0) = (x == 0). Proof. exact: (@gmulf_eq1 _ _ g). Qed. Lemma raddfMn n : {morph f : x / x *+ n}. Proof. exact: (@gmulfXn _ _ g). Qed. Lemma raddf_sum I r (P : pred I) E : f (\sum_(i <- r | P i) E i) = \sum_(i <- r | P i) f (E i). Proof. exact: (@gmulf_prod _ _ g). Qed. Lemma can2_nmod_morphism f' : cancel f f' -> cancel f' f -> nmod_morphism f'. Proof. split; first exact/(@can2_gmulf1 _ _ g). exact/(@can2_gmulfM _ _ g). Qed. #[deprecated(since="mathcomp 2.5.0", note="use `can2_nmod_morphism` instead")] Definition can2_semi_additive := can2_nmod_morphism. End Nmod. Section Zmod. Variables (U V : zmodType) (f : {additive U -> V}). Let g := to_fmultiplicative f. Lemma raddfN : {morph f : x / - x}. Proof. exact: (@gmulfV _ _ g). Qed. Lemma raddfB : {morph f : x y / x - y}. Proof. exact: (@gmulfF _ _ g). Qed. Lemma raddf_inj : (forall x, f x = 0 -> x = 0) -> injective f. Proof. exact: (@gmulf_inj _ _ g). Qed. Lemma raddfMNn n : {morph f : x / x *- n}. Proof. exact: (@gmulfXVn _ _ g). Qed. Lemma can2_zmod_morphism f' : cancel f f' -> cancel f' f -> zmod_morphism f'. Proof. by move=> fK f'K x y /=; apply: (canLR fK); rewrite raddfB !f'K. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `can2_zmod_morphism` instead")] Definition can2_additive := can2_zmod_morphism. End Zmod. Section AdditiveTheory. Section AddCFun. Variables (U : baseAddUMagmaType) (V : nmodType). Implicit Types (f g : {additive U -> V}). Fact add_fun_nmod_morphism f g : nmod_morphism (add_fun f g). Proof. by split=> [|x y]; rewrite /= ?raddf0 ?addr0// !raddfD addrCA -!addrA addrCA. Qed. #[export] HB.instance Definition _ f g := isNmodMorphism.Build U V (add_fun f g) (add_fun_nmod_morphism f g). End AddCFun. Section AddFun. Variables (U V W : baseAddUMagmaType). Variables (f : {additive V -> W}) (g : {additive U -> V}). Fact idfun_is_nmod_morphism : nmod_morphism (@idfun U). Proof. by []. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U U idfun idfun_is_nmod_morphism. Fact comp_is_nmod_morphism : nmod_morphism (f \o g). Proof. by split=> [|x y]; rewrite /= ?raddf0// !raddfD. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U W (f \o g) comp_is_nmod_morphism. End AddFun. Section AddFun. Variables (U : baseAddUMagmaType) (V : addUMagmaType) (W : nmodType). Variables (f g : {additive U -> W}). Fact null_fun_is_nmod_morphism : nmod_morphism (\0 : U -> V). Proof. by split=> // x y /=; rewrite addr0. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U V (\0 : U -> V) null_fun_is_nmod_morphism. End AddFun. Section AddVFun. Variables (U : baseAddUMagmaType) (V : zmodType). Variables (f g : {additive U -> V}). Fact opp_is_zmod_morphism : zmod_morphism (-%R : V -> V). Proof. by move=> x y; rewrite /= opprD. Qed. #[export] HB.instance Definition _ := isZmodMorphism.Build V V -%R opp_is_zmod_morphism. Fact opp_fun_is_zmod_morphism : nmod_morphism (\- f). Proof. split=> [|x y]; first by rewrite -[LHS]/(- (f 0)) raddf0 oppr0. by rewrite -[LHS]/(- (f (x + y))) !raddfD/=. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U V (opp_fun f) opp_fun_is_zmod_morphism. Fact sub_fun_is_zmod_morphism : nmod_morphism (f \- g). Proof. split=> [|x y]/=; first by rewrite !raddf0 addr0. by rewrite !raddfD/= addrACA. Qed. #[export] HB.instance Definition _ := isNmodMorphism.Build U V (f \- g) sub_fun_is_zmod_morphism. End AddVFun. End AdditiveTheory. (* Mixins for stability properties *) HB.mixin Record isAddClosed (V : baseAddUMagmaType) (S : {pred V}) := { nmod_closed_subproof : addumagma_closed S }. HB.mixin Record isOppClosed (V : zmodType) (S : {pred V}) := { oppr_closed_subproof : oppr_closed S }. (* Structures for stability properties *) #[short(type="addrClosed")] HB.structure Definition AddClosed V := {S of isAddClosed V S}. #[short(type="opprClosed")] HB.structure Definition OppClosed V := {S of isOppClosed V S}. #[short(type="zmodClosed")] HB.structure Definition ZmodClosed V := {S of OppClosed V S & AddClosed V S}. (* Factories for stability properties *) HB.factory Record isZmodClosed (V : zmodType) (S : V -> bool) := { zmod_closed_subproof : zmod_closed S }. HB.builders Context V S of isZmodClosed V S. HB.instance Definition _ := isOppClosed.Build V S (zmod_closedN zmod_closed_subproof). HB.instance Definition _ := isAddClosed.Build V S (zmod_closed0D zmod_closed_subproof). HB.end. Definition to_pmultiplicative (T : Type) := @id {pred to_multiplicative T}. #[export] HB.instance Definition _ (U : baseAddUMagmaType) (S : addrClosed U) := isMulClosed.Build (to_multiplicative U) (to_pmultiplicative S) (snd nmod_closed_subproof). #[export] HB.instance Definition _ (U : baseAddUMagmaType) (S : addrClosed U) := isMul1Closed.Build (to_multiplicative U) (to_pmultiplicative S) (fst nmod_closed_subproof). #[export] HB.instance Definition _ (U : zmodType) (S : opprClosed U) := isInvClosed.Build (to_multiplicative U) (to_pmultiplicative S) oppr_closed_subproof. (* FIXME: HB.saturate *) #[export] HB.instance Definition _ (U : zmodType) (S : zmodClosed U) := InvClosed.on (to_pmultiplicative S). Section BaseAddUMagmaPred. Variables (V : baseAddUMagmaType). Section BaseAddUMagmaPred. Variables S : addrClosed V. Lemma rpred0 : 0 \in S. Proof. by case: (@nmod_closed_subproof V S). Qed. Lemma rpredD : {in S &, forall u v, u + v \in S}. Proof. by case: (@nmod_closed_subproof V S). Qed. Lemma rpred0D : addumagma_closed S. Proof. exact: nmod_closed_subproof. Qed. Lemma rpredMn n : {in S, forall u, u *+ n \in S}. Proof. exact: (@gpredXn _ (to_pmultiplicative S)). Qed. Lemma rpred_sum I r (P : pred I) F : (forall i, P i -> F i \in S) -> \sum_(i <- r | P i) F i \in S. Proof. by move=> IH; elim/big_ind: _; [apply: rpred0 | apply: rpredD |]. Qed. End BaseAddUMagmaPred. End BaseAddUMagmaPred. Section ZmodPred. Variables (V : zmodType). Section Opp. Variable S : opprClosed V. Lemma rpredNr : {in S, forall u, - u \in S}. Proof. exact: oppr_closed_subproof. Qed. Lemma rpredN : {mono -%R: u / u \in S}. Proof. exact: (gpredV (to_pmultiplicative S)). Qed. End Opp. Section Zmod. Variables S : zmodClosed V. Let T := to_pmultiplicative S. Lemma rpredB : {in S &, forall u v, u - v \in S}. Proof. exact: (@gpredF _ T). Qed. Lemma rpredBC u v : u - v \in S = (v - u \in S). Proof. exact: (@gpredFC _ T). Qed. Lemma rpredMNn n: {in S, forall u, u *- n \in S}. Proof. exact: (@gpredXNn _ T). Qed. Lemma rpredDr x y : x \in S -> (y + x \in S) = (y \in S). Proof. exact: (@gpredMr _ T). Qed. Lemma rpredDl x y : x \in S -> (x + y \in S) = (y \in S). Proof. exact: (@gpredMl _ T). Qed. Lemma rpredBr x y : x \in S -> (y - x \in S) = (y \in S). Proof. exact: (@gpredFr _ T). Qed. Lemma rpredBl x y : x \in S -> (x - y \in S) = (y \in S). Proof. exact: (@gpredFl _ T). Qed. Lemma zmodClosedP : zmod_closed S. Proof. split; [ exact: (@rpred0D V S).1 | exact: rpredB ]. Qed. End Zmod. End ZmodPred. HB.mixin Record isSubBaseAddUMagma (V : baseAddUMagmaType) (S : pred V) U of SubType V S U & BaseAddUMagma U := { valD0_subproof : nmod_morphism (val : U -> V) }. #[short(type="subBaseAddUMagma")] HB.structure Definition SubBaseAddUMagma (V : baseAddUMagmaType) S := { U of SubChoice V S U & BaseAddUMagma U & isSubBaseAddUMagma V S U }. #[short(type="subAddUMagma")] HB.structure Definition SubAddUMagma (V : addUMagmaType) S := { U of SubChoice V S U & AddUMagma U & isSubBaseAddUMagma V S U }. #[short(type="subNmodType")] HB.structure Definition SubNmodule (V : nmodType) S := { U of SubChoice V S U & Nmodule U & isSubBaseAddUMagma V S U}. Section subBaseAddUMagma. Context (V : baseAddUMagmaType) (S : pred V) (U : subBaseAddUMagma S). Notation val := (val : U -> V). #[export] HB.instance Definition _ := isNmodMorphism.Build U V val valD0_subproof. Lemma valD : {morph val : x y / x + y}. Proof. exact: raddfD. Qed. Lemma val0 : val 0 = 0. Proof. exact: raddf0. Qed. End subBaseAddUMagma. HB.factory Record SubChoice_isSubAddUMagma (V : addUMagmaType) S U of SubChoice V S U := { addumagma_closed_subproof : addumagma_closed S }. HB.builders Context V S U of SubChoice_isSubAddUMagma V S U. HB.instance Definition _ := isAddClosed.Build V S addumagma_closed_subproof. Let inU v Sv : U := Sub v Sv. Let addU (u1 u2 : U) := inU (rpredD (valP u1) (valP u2)). Let oneU := inU (fst addumagma_closed_subproof). Lemma addrC : commutative addU. Proof. by move=> x y; apply/val_inj; rewrite !SubK addrC. Qed. Lemma add0r : left_id oneU addU. Proof. by move=> x; apply/val_inj; rewrite !SubK add0r. Qed. HB.instance Definition _ := isAddUMagma.Build U addrC add0r. Lemma valD0 : nmod_morphism (val : U -> V). Proof. by split=> [|x y]; rewrite !SubK. Qed. HB.instance Definition _ := isSubBaseAddUMagma.Build V S U valD0. HB.end. HB.factory Record SubChoice_isSubNmodule (V : nmodType) S U of SubChoice V S U := { nmod_closed_subproof : nmod_closed S }. HB.builders Context V S U of SubChoice_isSubNmodule V S U. HB.instance Definition _ := SubChoice_isSubAddUMagma.Build V S U nmod_closed_subproof. Lemma addrA : associative (@add U). Proof. by move=> x y z; apply/val_inj; rewrite !SubK addrA. Qed. HB.instance Definition _ := AddMagma_isAddSemigroup.Build U addrA. HB.end. #[short(type="subZmodType")] HB.structure Definition SubZmodule (V : zmodType) S := { U of SubChoice V S U & Zmodule U & isSubBaseAddUMagma V S U}. Section zmod_morphism. Context (V : zmodType) (S : pred V) (U : SubZmodule.type S). Notation val := (val : U -> V). Lemma valB : {morph val : x y / x - y}. Proof. exact: raddfB. Qed. Lemma valN : {morph val : x / - x}. Proof. exact: raddfN. Qed. End zmod_morphism. HB.factory Record isSubZmodule (V : zmodType) S U of SubChoice V S U & Zmodule U := { valB_subproof : zmod_morphism (val : U -> V) }. HB.builders Context V S U of isSubZmodule V S U. Fact valD0 : nmod_morphism (val : U -> V). Proof. have val0: (val : U -> V) 0 = 0. by rewrite -[X in val X](subr0 0) valB_subproof subrr. split=> // x y; apply/(@subIr _ (val y)). by rewrite -valB_subproof -!addrA !subrr !addr0. Qed. HB.instance Definition _ := isSubBaseAddUMagma.Build V S U valD0. HB.end. HB.factory Record SubChoice_isSubZmodule (V : zmodType) S U of SubChoice V S U := { zmod_closed_subproof : zmod_closed S }. HB.builders Context V S U of SubChoice_isSubZmodule V S U. HB.instance Definition _ := isZmodClosed.Build V S zmod_closed_subproof. HB.instance Definition _ := SubChoice_isSubNmodule.Build V S U nmod_closed_subproof. Let inU v Sv : U := Sub v Sv. Let oppU (u : U) := inU (rpredNr (valP u)). HB.instance Definition _ := hasOpp.Build U oppU. Lemma addNr : left_inverse 0 oppU (@add U). Proof. by move=> x; apply/val_inj; rewrite !SubK addNr. Qed. HB.instance Definition _ := Nmodule_isZmodule.Build U addNr. HB.end. Module SubExports. Notation "[ 'SubChoice_isSubNmodule' 'of' U 'by' <: ]" := (SubChoice_isSubNmodule.Build _ _ U rpred0D) (at level 0, format "[ 'SubChoice_isSubNmodule' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isSubZmodule' 'of' U 'by' <: ]" := (SubChoice_isSubZmodule.Build _ _ U (zmodClosedP _)) (at level 0, format "[ 'SubChoice_isSubZmodule' 'of' U 'by' <: ]") : form_scope. End SubExports. HB.export SubExports. Module AllExports. HB.reexport. End AllExports. End Algebra. Export AllExports. Notation "0" := (@zero _) : ring_scope. Notation "-%R" := (@opp _) : ring_scope. Notation "- x" := (opp x) : ring_scope. Notation "+%R" := (@add _) : function_scope. Notation "x + y" := (add x y) : ring_scope. Notation "x - y" := (add x (- y)) : ring_scope. Arguments natmul : simpl never. Notation "x *+ n" := (natmul x n) : ring_scope. Notation "x *- n" := (opp (x *+ n)) : ring_scope. Notation "s `_ i" := (seq.nth 0%R s%R i) : ring_scope. Notation support := 0.-support. Notation "1" := (@one _) : ring_scope. Notation "- 1" := (opp 1) : ring_scope. Notation "n %:R" := (natmul 1 n) : ring_scope. Notation "\sum_ ( i <- r | P ) F" := (\big[+%R/0%R]_(i <- r | P%B) F%R) : ring_scope. Notation "\sum_ ( i <- r ) F" := (\big[+%R/0%R]_(i <- r) F%R) : ring_scope. Notation "\sum_ ( m <= i < n | P ) F" := (\big[+%R/0%R]_(m <= i < n | P%B) F%R) : ring_scope. Notation "\sum_ ( m <= i < n ) F" := (\big[+%R/0%R]_(m <= i < n) F%R) : ring_scope. Notation "\sum_ ( i | P ) F" := (\big[+%R/0%R]_(i | P%B) F%R) : ring_scope. Notation "\sum_ i F" := (\big[+%R/0%R]_i F%R) : ring_scope. Notation "\sum_ ( i : t | P ) F" := (\big[+%R/0%R]_(i : t | P%B) F%R) (only parsing) : ring_scope. Notation "\sum_ ( i : t ) F" := (\big[+%R/0%R]_(i : t) F%R) (only parsing) : ring_scope. Notation "\sum_ ( i < n | P ) F" := (\big[+%R/0%R]_(i < n | P%B) F%R) : ring_scope. Notation "\sum_ ( i < n ) F" := (\big[+%R/0%R]_(i < n) F%R) : ring_scope. Notation "\sum_ ( i 'in' A | P ) F" := (\big[+%R/0%R]_(i in A | P%B) F%R) : ring_scope. Notation "\sum_ ( i 'in' A ) F" := (\big[+%R/0%R]_(i in A) F%R) : ring_scope. Section FinFunBaseAddMagma. Variable (aT : finType) (rT : baseAddMagmaType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_add f g := [ffun a => f a + g a]. HB.instance Definition _ := hasAdd.Build {ffun aT -> rT} ffun_add. End FinFunBaseAddMagma. Section FinFunAddMagma. Variable (aT : finType) (rT : addMagmaType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_addrC : commutative (@ffun_add aT rT). Proof. by move=> f1 f2; apply/ffunP => a; rewrite !ffunE addrC. Qed. HB.instance Definition _ := BaseAddMagma_isAddMagma.Build {ffun aT -> rT} ffun_addrC. End FinFunAddMagma. Section FinFunAddSemigroup. Variable (aT : finType) (rT : addSemigroupType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_addrA : associative (@ffun_add aT rT). Proof. by move=> f g h; apply/ffunP => a; rewrite !ffunE addrA. Qed. HB.instance Definition _ := AddMagma_isAddSemigroup.Build {ffun aT -> rT} ffun_addrA. End FinFunAddSemigroup. Section FinFunBaseAddUMagma. Variable (aT : finType) (rT : baseAddUMagmaType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_zero := [ffun a : aT => (0 : rT)]. HB.instance Definition _ := hasZero.Build {ffun aT -> rT} ffun_zero. End FinFunBaseAddUMagma. Section FinFunAddUMagma. Variable (aT : finType) (rT : addUMagmaType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_add0r : left_id (@ffun_zero aT rT) (@ffun_add aT rT). Proof. by move=> f; apply/ffunP => a; rewrite !ffunE add0r. Qed. HB.instance Definition _ := BaseAddUMagma_isAddUMagma.Build {ffun aT -> rT} ffun_add0r. End FinFunAddUMagma. (* FIXME: HB.saturate *) HB.instance Definition _ (aT : finType) (rT : ChoiceBaseAddMagma.type) := BaseAddMagma.on {ffun aT -> rT}. HB.instance Definition _ (aT : finType) (rT : ChoiceBaseAddUMagma.type) := BaseAddMagma.on {ffun aT -> rT}. Section FinFunNmod. Variable (aT : finType) (rT : nmodType). Implicit Types f g : {ffun aT -> rT}. (* FIXME: HB.saturate *) HB.instance Definition _ := AddSemigroup.on {ffun aT -> rT}. Lemma ffunMnE f n x : (f *+ n) x = f x *+ n. Proof. elim: n => [|n IHn]; first by rewrite ffunE. by rewrite !mulrS ffunE IHn. Qed. Section Sum. Variables (I : Type) (r : seq I) (P : pred I) (F : I -> {ffun aT -> rT}). Lemma sum_ffunE x : (\sum_(i <- r | P i) F i) x = \sum_(i <- r | P i) F i x. Proof. by elim/big_rec2: _ => // [|i _ y _ <-]; rewrite !ffunE. Qed. Lemma sum_ffun : \sum_(i <- r | P i) F i = [ffun x => \sum_(i <- r | P i) F i x]. Proof. by apply/ffunP=> i; rewrite sum_ffunE ffunE. Qed. End Sum. End FinFunNmod. Section FinFunZmod. Variable (aT : finType) (rT : zmodType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_opp f := [ffun a => - f a]. HB.instance Definition _ := hasOpp.Build {ffun aT -> rT} ffun_opp. Fact ffun_addNr : left_inverse 0 ffun_opp +%R. Proof. by move=> f; apply/ffunP => a; rewrite !ffunE addNr. Qed. HB.instance Definition _ := Nmodule_isZmodule.Build {ffun aT -> rT} ffun_addNr. End FinFunZmod. Section PairBaseAddMagma. Variables U V : baseAddMagmaType. Definition add_pair (a b : U * V) := (a.1 + b.1, a.2 + b.2). HB.instance Definition _ := hasAdd.Build (U * V)%type add_pair. End PairBaseAddMagma. Section PairAddMagma. Variables U V : addMagmaType. Fact pair_addrC : commutative (@add_pair U V). Proof. by move=> a b; congr pair; exact: addrC. Qed. HB.instance Definition _ := BaseAddMagma_isAddMagma.Build (U * V)%type pair_addrC. End PairAddMagma. Section PairAddSemigroup. Variables U V : addSemigroupType. Fact pair_addrA : associative (@add_pair U V). Proof. by move=> [] al ar [] bl br [] cl cr; rewrite /add_pair !addrA. Qed. HB.instance Definition _ := AddMagma_isAddSemigroup.Build (U * V)%type pair_addrA. End PairAddSemigroup. Section PairBaseAddUMagma. Variables U V : baseAddUMagmaType. Definition pair_zero : U * V := (0, 0). HB.instance Definition _ := hasZero.Build (U * V)%type pair_zero. Fact fst_is_zmod_morphism : nmod_morphism (@fst U V). Proof. by []. Qed. Fact snd_is_zmod_morphism : nmod_morphism (@snd U V). Proof. by []. Qed. HB.instance Definition _ := isNmodMorphism.Build _ _ (@fst U V) fst_is_zmod_morphism. HB.instance Definition _ := isNmodMorphism.Build _ _ (@snd U V) snd_is_zmod_morphism. End PairBaseAddUMagma. Section PairAddUMagma. Variables U V : addUMagmaType. Fact pair_add0r : left_id (@pair_zero U V) (@add_pair U V). Proof. by move=> [] al ar; rewrite /add_pair !add0r. Qed. HB.instance Definition _ := BaseAddUMagma_isAddUMagma.Build (U * V)%type pair_add0r. End PairAddUMagma. (* FIXME: HB.saturate *) HB.instance Definition _ (U V : ChoiceBaseAddMagma.type) := BaseAddMagma.on (U * V)%type. HB.instance Definition _ (U V : ChoiceBaseAddUMagma.type) := BaseAddMagma.on (U * V)%type. HB.instance Definition _ (U V : nmodType) := AddSemigroup.on (U * V)%type. (* /FIXME *) Section PairZmodule. Variables U V : zmodType. Definition pair_opp (a : U * V) := (- a.1, - a.2). HB.instance Definition _ := hasOpp.Build (U * V)%type pair_opp. Fact pair_addNr : left_inverse 0 pair_opp +%R. Proof. by move=> [] al ar; rewrite /pair_opp; congr pair; apply/addNr. Qed. HB.instance Definition _ := Nmodule_isZmodule.Build (U * V)%type pair_addNr. End PairZmodule. (* zmodType structure on bool *) HB.instance Definition _ := isZmodule.Build bool addbA addbC addFb addbb. (* nmodType structure on nat *) HB.instance Definition _ := isNmodule.Build nat addnA addnC add0n. HB.instance Definition _ (V : nmodType) (x : V) := isNmodMorphism.Build nat V (natmul x) (mulr0n x, mulrnDr x). Lemma natr0E : 0 = 0%N. Proof. by []. Qed. Lemma natrDE n m : n + m = (n + m)%N. Proof. by []. Qed. Definition natrE := (natr0E, natrDE).
orderedzmod.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 choice. From mathcomp Require Import ssrAC div fintype path bigop order finset fingroup. From mathcomp Require Import ssralg poly. (******************************************************************************) (* Number structures *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines some classes to manipulate number structures, i.e, *) (* structures with an order and a norm. To use this file, insert *) (* "Import Num.Theory." before your scripts. You can also "Import Num.Def." *) (* to enjoy shorter notations (e.g., minr instead of Num.min, lerif instead *) (* of Num.leif, etc.). *) (* *) (* This file defines the following number structures: *) (* *) (* porderZmodType == join of Order.POrder and GRing.Zmodule *) (* The HB class is called POrderedZmodule. *) (* *) (* The ordering symbols and notations (<, <=, >, >=, _ <= _ ?= iff _, *) (* _ < _ ?<= if _, >=<, and ><) and lattice operations (meet and join) *) (* defined in order.v are redefined for the ring_display in the ring_scope *) (* (%R). 0-ary ordering symbols for the ring_display have the suffix "%R", *) (* e.g., <%R. All the other ordering notations are the same as order.v. *) (* *) (* Over these structures, we have the following operations: *) (* x \is a Num.pos <=> x is positive (:= x > 0) *) (* x \is a Num.neg <=> x is negative (:= x < 0) *) (* x \is a Num.nneg <=> x is positive or 0 (:= x >= 0) *) (* x \is a Num.npos <=> x is negative or 0 (:= x <= 0) *) (* x \is a Num.real <=> x is real (:= x >= 0 or x < 0) *) (* *) (* - list of prefixes : *) (* p : positive *) (* n : negative *) (* sp : strictly positive *) (* sn : strictly negative *) (* i : interior = in [0, 1] or ]0, 1[ *) (* e : exterior = in [1, +oo[ or ]1; +oo[ *) (* w : non strict (weak) monotony *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "n .-root" (format "n .-root"). Reserved Notation "'i". Reserved Notation "'Re z" (at level 10, z at level 8). Reserved Notation "'Im z" (at level 10, z at level 8). Local Open Scope order_scope. Local Open Scope group_scope. Local Open Scope ring_scope. Import Order.TTheory GRing.Theory. Fact ring_display : Order.disp_t. Proof. exact. Qed. Module Num. #[short(type="porderZmodType")] HB.structure Definition POrderedZmodule := { R of Order.isPOrder ring_display R & GRing.Zmodule R }. Module Export Def. Notation ler := (@Order.le ring_display _) (only parsing). Notation "@ 'ler' R" := (@Order.le ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation ltr := (@Order.lt ring_display _) (only parsing). Notation "@ 'ltr' R" := (@Order.lt ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation ger := (@Order.ge ring_display _) (only parsing). Notation "@ 'ger' R" := (@Order.ge ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation gtr := (@Order.gt ring_display _) (only parsing). Notation "@ 'gtr' R" := (@Order.gt ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation lerif := (@Order.leif ring_display _) (only parsing). Notation "@ 'lerif' R" := (@Order.leif ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation lterif := (@Order.lteif ring_display _) (only parsing). Notation "@ 'lteif' R" := (@Order.lteif ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation comparabler := (@Order.comparable ring_display _) (only parsing). Notation "@ 'comparabler' R" := (@Order.comparable ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation maxr := (@Order.max ring_display _). Notation "@ 'maxr' R" := (@Order.max ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation minr := (@Order.min ring_display _). Notation "@ 'minr' R" := (@Order.min ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Section Def. Context {R : porderZmodType}. Definition Rpos_pred := fun x : R => 0 < x. Definition Rpos : qualifier 0 R := [qualify x | Rpos_pred x]. Definition Rneg_pred := fun x : R => x < 0. Definition Rneg : qualifier 0 R := [qualify x : R | Rneg_pred x]. Definition Rnneg_pred := fun x : R => 0 <= x. Definition Rnneg : qualifier 0 R := [qualify x : R | Rnneg_pred x]. Definition Rnpos_pred := fun x : R => x <= 0. Definition Rnpos : qualifier 0 R := [qualify x : R | Rnpos_pred x]. Definition Rreal_pred := fun x : R => (0 <= x) || (x <= 0). Definition Rreal : qualifier 0 R := [qualify x : R | Rreal_pred x]. End Def. Arguments Rpos_pred _ _ /. Arguments Rneg_pred _ _ /. Arguments Rnneg_pred _ _ /. Arguments Rreal_pred _ _ /. End Def. (* Shorter qualified names, when Num.Def is not imported. *) Notation le := ler (only parsing). Notation lt := ltr (only parsing). Notation ge := ger (only parsing). Notation gt := gtr (only parsing). Notation leif := lerif (only parsing). Notation lteif := lterif (only parsing). Notation comparable := comparabler (only parsing). Notation max := maxr. Notation min := minr. Notation pos := Rpos. Notation neg := Rneg. Notation nneg := Rnneg. Notation npos := Rnpos. Notation real := Rreal. (* (Exported) symbolic syntax. *) Module Import Syntax. Notation "<=%R" := le : function_scope. Notation ">=%R" := ge : function_scope. Notation "<%R" := lt : function_scope. Notation ">%R" := gt : function_scope. Notation "<?=%R" := leif : function_scope. Notation "<?<=%R" := lteif : function_scope. Notation ">=<%R" := comparable : function_scope. Notation "><%R" := (fun x y => ~~ (comparable x y)) : function_scope. Notation "<= y" := (ge y) : ring_scope. Notation "<= y :> T" := (<= (y : T)) (only parsing) : ring_scope. Notation ">= y" := (le y) : ring_scope. Notation ">= y :> T" := (>= (y : T)) (only parsing) : ring_scope. Notation "< y" := (gt y) : ring_scope. Notation "< y :> T" := (< (y : T)) (only parsing) : ring_scope. Notation "> y" := (lt y) : ring_scope. Notation "> y :> T" := (> (y : T)) (only parsing) : ring_scope. Notation "x <= y" := (le x y) : ring_scope. Notation "x <= y :> T" := ((x : T) <= (y : T)) (only parsing) : ring_scope. Notation "x >= y" := (y <= x) (only parsing) : ring_scope. Notation "x >= y :> T" := ((x : T) >= (y : T)) (only parsing) : ring_scope. Notation "x < y" := (lt x y) : ring_scope. Notation "x < y :> T" := ((x : T) < (y : T)) (only parsing) : ring_scope. Notation "x > y" := (y < x) (only parsing) : ring_scope. Notation "x > y :> T" := ((x : T) > (y : T)) (only parsing) : ring_scope. Notation "x <= y <= z" := ((x <= y) && (y <= z)) : ring_scope. Notation "x < y <= z" := ((x < y) && (y <= z)) : ring_scope. Notation "x <= y < z" := ((x <= y) && (y < z)) : ring_scope. Notation "x < y < z" := ((x < y) && (y < z)) : ring_scope. Notation "x <= y ?= 'iff' C" := (lerif x y C) : ring_scope. Notation "x <= y ?= 'iff' C :> R" := ((x : R) <= (y : R) ?= iff C) (only parsing) : ring_scope. Notation "x < y ?<= 'if' C" := (lterif x y C) : ring_scope. Notation "x < y ?<= 'if' C :> R" := ((x : R) < (y : R) ?<= if C) (only parsing) : ring_scope. Notation ">=< y" := [pred x | comparable x y] : ring_scope. Notation ">=< y :> T" := (>=< (y : T)) (only parsing) : ring_scope. Notation "x >=< y" := (comparable x y) : ring_scope. Notation ">< y" := [pred x | ~~ comparable x y] : ring_scope. Notation ">< y :> T" := (>< (y : T)) (only parsing) : ring_scope. Notation "x >< y" := (~~ (comparable x y)) : ring_scope. Export Order.PreOCoercions. End Syntax. Module Export Theory. End Theory. Module Exports. HB.reexport. End Exports. End Num. Export Num.Syntax Num.Exports.
LeftInvariantDerivation.lean
/- Copyright (c) 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import Mathlib.RingTheory.Derivation.Lie import Mathlib.Geometry.Manifold.DerivationBundle /-! # Left invariant derivations In this file we define the concept of left invariant derivation for a Lie group. The concept is analogous to the more classical concept of left invariant vector fields, and it holds that the derivation associated to a vector field is left invariant iff the field is. Moreover we prove that `LeftInvariantDerivation I G` has the structure of a Lie algebra, hence implementing one of the possible definitions of the Lie algebra attached to a Lie group. Note that one can also define a Lie algebra on the space of left-invariant vector fields (see `instLieAlgebraGroupLieAlgebra`). For finite-dimensional `C^∞` real manifolds, the space of derivations can be canonically identified with the tangent space, and we recover the same Lie algebra structure (TODO: prove this). In other smoothness classes or on other fields, this identification is not always true, though, so the derivations point of view does not work in these settings. The left-invariant vector fields should therefore be favored to construct a theory of Lie groups in suitable generality. -/ noncomputable section open scoped LieGroup Manifold Derivation ContDiff variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {n : WithTop ℕ∞} {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {H : Type*} [TopologicalSpace H] (I : ModelWithCorners 𝕜 E H) (G : Type*) [TopologicalSpace G] [ChartedSpace H G] [Monoid G] [ContMDiffMul I ∞ G] (g h : G) -- Generate trivial has_sizeof instance. It prevents weird type class inference timeout problems -- Porting note (https://github.com/leanprover-community/mathlib4/issues/12096): removed @[nolint instance_priority], linter not ported yet -- @[local nolint instance_priority, local instance 10000] -- private def disable_has_sizeof {α} : SizeOf α := -- ⟨fun _ => 0⟩ /-- Left-invariant global derivations. A global derivation is left-invariant if it is equal to its pullback along left multiplication by an arbitrary element of `G`. -/ structure LeftInvariantDerivation extends Derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯ where left_invariant'' : ∀ g, 𝒅ₕ (smoothLeftMul_one I g) (Derivation.evalAt 1 toDerivation) = Derivation.evalAt g toDerivation variable {I G} namespace LeftInvariantDerivation instance : Coe (LeftInvariantDerivation I G) (Derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) := ⟨toDerivation⟩ attribute [coe] toDerivation theorem toDerivation_injective : Function.Injective (toDerivation : LeftInvariantDerivation I G → _) := fun X Y h => by cases X; cases Y; congr instance : FunLike (LeftInvariantDerivation I G) C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯ where coe f := f.toDerivation coe_injective' _ _ h := toDerivation_injective <| DFunLike.ext' h instance : LinearMapClass (LeftInvariantDerivation I G) 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯ where map_add f := map_add f.1 map_smulₛₗ f := map_smul f.1.1 variable {r : 𝕜} {X Y : LeftInvariantDerivation I G} {f f' : C^∞⟮I, G; 𝕜⟯} theorem toFun_eq_coe : X.toFun = ⇑X := rfl -- Porting note: now LHS is the same as RHS theorem coe_injective : @Function.Injective (LeftInvariantDerivation I G) (_ → C^∞⟮I, G; 𝕜⟯) DFunLike.coe := DFunLike.coe_injective @[ext] theorem ext (h : ∀ f, X f = Y f) : X = Y := DFunLike.ext _ _ h variable (X Y f) theorem coe_derivation : ⇑(X : Derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = (X : C^∞⟮I, G; 𝕜⟯ → C^∞⟮I, G; 𝕜⟯) := rfl /-- Premature version of the lemma. Prefer using `left_invariant` instead. -/ theorem left_invariant' : 𝒅ₕ (smoothLeftMul_one I g) (Derivation.evalAt (1 : G) ↑X) = Derivation.evalAt g ↑X := left_invariant'' X g protected theorem map_add : X (f + f') = X f + X f' := by simp protected theorem map_zero : X 0 = 0 := by simp protected theorem map_neg : X (-f) = -X f := by simp protected theorem map_sub : X (f - f') = X f - X f' := by simp protected theorem map_smul : X (r • f) = r • X f := by simp @[simp] theorem leibniz : X (f * f') = f • X f' + f' • X f := X.leibniz' _ _ instance : Zero (LeftInvariantDerivation I G) := ⟨⟨0, fun g => by simp only [map_zero]⟩⟩ instance : Inhabited (LeftInvariantDerivation I G) := ⟨0⟩ instance : Add (LeftInvariantDerivation I G) where add X Y := ⟨X + Y, fun g => by simp only [map_add, left_invariant']⟩ instance : Neg (LeftInvariantDerivation I G) where neg X := ⟨-X, fun g => by simp [left_invariant']⟩ instance : Sub (LeftInvariantDerivation I G) where sub X Y := ⟨X - Y, fun g => by simp [left_invariant']⟩ @[simp] theorem coe_add : ⇑(X + Y) = X + Y := rfl @[simp] theorem coe_zero : ⇑(0 : LeftInvariantDerivation I G) = 0 := rfl @[simp] theorem coe_neg : ⇑(-X) = -X := rfl @[simp] theorem coe_sub : ⇑(X - Y) = X - Y := rfl @[simp, norm_cast] theorem lift_add : (↑(X + Y) : Derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = X + Y := rfl @[simp, norm_cast] theorem lift_zero : (↑(0 : LeftInvariantDerivation I G) : Derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = 0 := rfl instance hasNatScalar : SMul ℕ (LeftInvariantDerivation I G) where smul r X := ⟨r • X.1, fun g => by simp_rw [LinearMap.map_smul_of_tower _ r, left_invariant']⟩ instance hasIntScalar : SMul ℤ (LeftInvariantDerivation I G) where smul r X := ⟨r • X.1, fun g => by simp_rw [LinearMap.map_smul_of_tower _ r, left_invariant']⟩ instance : AddCommGroup (LeftInvariantDerivation I G) := coe_injective.addCommGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ => rfl) fun _ _ => rfl instance : SMul 𝕜 (LeftInvariantDerivation I G) where smul r X := ⟨r • X.1, fun g => by simp_rw [LinearMap.map_smul, left_invariant']⟩ variable (r) @[simp] theorem coe_smul : ⇑(r • X) = r • ⇑X := rfl @[simp] theorem lift_smul (k : 𝕜) : (k • X).1 = k • X.1 := rfl variable (I G) /-- The coercion to function is a monoid homomorphism. -/ @[simps] def coeFnAddMonoidHom : LeftInvariantDerivation I G →+ C^∞⟮I, G; 𝕜⟯ → C^∞⟮I, G; 𝕜⟯ := ⟨⟨DFunLike.coe, coe_zero⟩, coe_add⟩ variable {I G} instance : Module 𝕜 (LeftInvariantDerivation I G) := coe_injective.module _ (coeFnAddMonoidHom I G) coe_smul /-- Evaluation at a point for left invariant derivation. Same thing as for generic global derivations (`Derivation.evalAt`). -/ def evalAt : LeftInvariantDerivation I G →ₗ[𝕜] PointDerivation I g where toFun X := Derivation.evalAt g X.1 map_add' _ _ := rfl map_smul' _ _ := rfl theorem evalAt_apply : evalAt g X f = (X f) g := rfl @[simp] theorem evalAt_coe : Derivation.evalAt g ↑X = evalAt g X := rfl theorem left_invariant : 𝒅ₕ (smoothLeftMul_one I g) (evalAt (1 : G) X) = evalAt g X := X.left_invariant'' g theorem evalAt_mul : evalAt (g * h) X = 𝒅ₕ (L_apply I g h) (evalAt h X) := by ext f rw [← left_invariant, hfdifferential_apply, hfdifferential_apply, L_mul, fdifferential_comp, fdifferential_apply] -- Porting note: more aggressive here erw [LinearMap.comp_apply] -- This used to be `rw`, but we need `erw` after https://github.com/leanprover/lean4/pull/2644 erw [fdifferential_apply, ← hfdifferential_apply, left_invariant] theorem comp_L : (X f).comp (𝑳 I g) = X (f.comp (𝑳 I g)) := by ext h rw [ContMDiffMap.comp_apply, L_apply, ← evalAt_apply, evalAt_mul, hfdifferential_apply, fdifferential_apply, evalAt_apply] instance : Bracket (LeftInvariantDerivation I G) (LeftInvariantDerivation I G) where bracket X Y := ⟨⁅(X : Derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯), Y⁆, fun g => by ext f have hX := Derivation.congr_fun (left_invariant' g X) (Y f) have hY := Derivation.congr_fun (left_invariant' g Y) (X f) rw [hfdifferential_apply, fdifferential_apply, Derivation.evalAt_apply] at hX hY ⊢ rw [comp_L] at hX hY rw [Derivation.commutator_apply, ContMDiffMap.coe_sub, Pi.sub_apply, coe_derivation] rw [coe_derivation] at hX hY ⊢ rw [hX, hY] rfl⟩ @[simp] theorem commutator_coe_derivation : ⇑⁅X, Y⁆ = (⁅(X : Derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯), Y⁆ : Derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) := rfl theorem commutator_apply : ⁅X, Y⁆ f = X (Y f) - Y (X f) := rfl instance : LieRing (LeftInvariantDerivation I G) where add_lie X Y Z := by ext1 simp only [commutator_apply, coe_add, Pi.add_apply, map_add] ring lie_add X Y Z := by ext1 simp only [commutator_apply, coe_add, Pi.add_apply, map_add] ring lie_self X := by ext1; simp only [commutator_apply, sub_self]; rfl leibniz_lie X Y Z := by ext1 simp only [commutator_apply, coe_add, map_sub, Pi.add_apply] ring instance : LieAlgebra 𝕜 (LeftInvariantDerivation I G) where lie_smul r Y Z := by ext1 simp only [commutator_apply, map_smul, smul_sub, coe_smul, Pi.smul_apply] end LeftInvariantDerivation
Finite.lean
/- Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller -/ import Mathlib.Data.Fintype.Basic import Mathlib.Data.Fintype.Powerset import Mathlib.Data.Set.Finite.Basic /-! # Hall's Marriage Theorem for finite index types This module proves the basic form of Hall's theorem. In contrast to the theorem described in `Combinatorics.Hall.Basic`, this version requires that the indexed family `t : ι → Finset α` have `ι` be finite. The `Combinatorics.Hall.Basic` module applies a compactness argument to this version to remove the `Finite` constraint on `ι`. The modules are split like this since the generalized statement depends on the topology and category theory libraries, but the finite case in this module has few dependencies. A description of this formalization is in [Gusakov2021]. ## Main statements * `Finset.all_card_le_biUnion_card_iff_existsInjective'` is Hall's theorem with a finite index set. This is elsewhere generalized to `Finset.all_card_le_biUnion_card_iff_existsInjective`. ## Tags Hall's Marriage Theorem, indexed families -/ open Finset universe u v namespace HallMarriageTheorem variable {ι : Type u} {α : Type v} [DecidableEq α] {t : ι → Finset α} section Fintype variable [Fintype ι] theorem hall_cond_of_erase {x : ι} (a : α) (ha : ∀ s : Finset ι, s.Nonempty → s ≠ univ → #s < #(s.biUnion t)) (s' : Finset { x' : ι | x' ≠ x }) : #s' ≤ #(s'.biUnion fun x' => (t x').erase a) := by haveI := Classical.decEq ι specialize ha (s'.image fun z => z.1) rw [image_nonempty, Finset.card_image_of_injective s' Subtype.coe_injective] at ha by_cases he : s'.Nonempty · have ha' : #s' < #(s'.biUnion fun x => t x) := by convert ha he fun h => by simpa [← h] using mem_univ x using 2 ext x simp only [mem_image, mem_biUnion, SetCoe.exists, exists_and_right, exists_eq_right] rw [← erase_biUnion] by_cases hb : a ∈ s'.biUnion fun x => t x · rw [card_erase_of_mem hb] exact Nat.le_sub_one_of_lt ha' · rw [erase_eq_of_notMem hb] exact Nat.le_of_lt ha' · rw [nonempty_iff_ne_empty, not_not] at he subst s' simp /-- First case of the inductive step: assuming that `∀ (s : Finset ι), s.Nonempty → s ≠ univ → #s < #(s.biUnion t)` and that the statement of **Hall's Marriage Theorem** is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`. -/ theorem hall_hard_inductive_step_A {n : ℕ} (hn : Fintype.card ι = n + 1) (ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) (ih : ∀ {ι' : Type u} [Fintype ι'] (t' : ι' → Finset α), Fintype.card ι' ≤ n → (∀ s' : Finset ι', #s' ≤ #(s'.biUnion t')) → ∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x) (ha : ∀ s : Finset ι, s.Nonempty → s ≠ univ → #s < #(s.biUnion t)) : ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by haveI : Nonempty ι := Fintype.card_pos_iff.mp (hn.symm ▸ Nat.succ_pos _) haveI := Classical.decEq ι -- Choose an arbitrary element `x : ι` and `y : t x`. let x := Classical.arbitrary ι have tx_ne : (t x).Nonempty := by rw [← Finset.card_pos] calc 0 < 1 := Nat.one_pos _ ≤ #(.biUnion {x} t) := ht {x} _ = (t x).card := by rw [Finset.singleton_biUnion] choose y hy using tx_ne -- Restrict to everything except `x` and `y`. let ι' := { x' : ι | x' ≠ x } let t' : ι' → Finset α := fun x' => (t x').erase y have card_ι' : Fintype.card ι' = n := calc Fintype.card ι' = Fintype.card ι - 1 := Set.card_ne_eq _ _ = n := by rw [hn, Nat.add_succ_sub_one, add_zero] rcases ih t' card_ι'.le (hall_cond_of_erase y ha) with ⟨f', hfinj, hfr⟩ -- Extend the resulting function. refine ⟨fun z => if h : z = x then y else f' ⟨z, h⟩, ?_, ?_⟩ · rintro z₁ z₂ have key : ∀ {x}, y ≠ f' x := by intro x h simpa [t', ← h] using hfr x by_cases h₁ : z₁ = x <;> by_cases h₂ : z₂ = x <;> simp [h₁, h₂, hfinj.eq_iff, key, key.symm] · intro z simp only split_ifs with hz · rwa [hz] · specialize hfr ⟨z, hz⟩ rw [mem_erase] at hfr exact hfr.2 theorem hall_cond_of_restrict {ι : Type u} {t : ι → Finset α} {s : Finset ι} (ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) (s' : Finset (s : Set ι)) : #s' ≤ #(s'.biUnion fun a' => t a') := by classical rw [← card_image_of_injective s' Subtype.coe_injective] convert ht (s'.image fun z => z.1) using 1 apply congr_arg ext y simp theorem hall_cond_of_compl {ι : Type u} {t : ι → Finset α} {s : Finset ι} (hus : #s = #(s.biUnion t)) (ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) (s' : Finset (sᶜ : Set ι)) : #s' ≤ #(s'.biUnion fun x' => t x' \ s.biUnion t) := by haveI := Classical.decEq ι have disj : Disjoint s (s'.image fun z => z.1) := by simp only [disjoint_left, not_exists, mem_image, SetCoe.exists, exists_and_right, exists_eq_right] intro x hx hc _ exact absurd hx hc have : #s' = #(s ∪ s'.image fun z => z.1) - #s := by simp [disj, card_image_of_injective _ Subtype.coe_injective, Nat.add_sub_cancel_left] rw [this, hus] refine (Nat.sub_le_sub_right (ht _) _).trans ?_ rw [← card_sdiff] · refine (card_le_card ?_).trans le_rfl intro t simp only [mem_biUnion, mem_sdiff, not_exists, mem_image, and_imp, mem_union, exists_imp] rintro x (hx | ⟨x', hx', rfl⟩) rat hs · exact False.elim <| (hs x) <| And.intro hx rat · use x', hx', rat, hs · apply biUnion_subset_biUnion_of_subset_left apply subset_union_left /-- Second case of the inductive step: assuming that `∃ (s : Finset ι), s ≠ univ → #s = #(s.biUnion t)` and that the statement of **Hall's Marriage Theorem** is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`. -/ theorem hall_hard_inductive_step_B {n : ℕ} (hn : Fintype.card ι = n + 1) (ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) (ih : ∀ {ι' : Type u} [Fintype ι'] (t' : ι' → Finset α), Fintype.card ι' ≤ n → (∀ s' : Finset ι', #s' ≤ #(s'.biUnion t')) → ∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x) (s : Finset ι) (hs : s.Nonempty) (hns : s ≠ univ) (hus : #s = #(s.biUnion t)) : ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by haveI := Classical.decEq ι -- Restrict to `s` rw [Nat.add_one] at hn have card_ι'_le : Fintype.card s ≤ n := by apply Nat.le_of_lt_succ calc Fintype.card s = #s := Fintype.card_coe _ _ < Fintype.card ι := (card_lt_iff_ne_univ _).mpr hns _ = n.succ := hn let t' : s → Finset α := fun x' => t x' rcases ih t' card_ι'_le (hall_cond_of_restrict ht) with ⟨f', hf', hsf'⟩ -- Restrict to `sᶜ` in the domain and `(s.biUnion t)ᶜ` in the codomain. set ι'' := (s : Set ι)ᶜ let t'' : ι'' → Finset α := fun a'' => t a'' \ s.biUnion t have card_ι''_le : Fintype.card ι'' ≤ n := by simp_rw [ι'', ← Nat.lt_succ_iff, ← hn, ← Finset.coe_compl, coe_sort_coe] rwa [Fintype.card_coe, card_compl_lt_iff_nonempty] rcases ih t'' card_ι''_le (hall_cond_of_compl hus ht) with ⟨f'', hf'', hsf''⟩ -- Put them together have f'_mem_biUnion : ∀ (x') (hx' : x' ∈ s), f' ⟨x', hx'⟩ ∈ s.biUnion t := by intro x' hx' rw [mem_biUnion] exact ⟨x', hx', hsf' _⟩ have f''_notMem_biUnion : ∀ (x'') (hx'' : x'' ∉ s), f'' ⟨x'', hx''⟩ ∉ s.biUnion t := by intro x'' hx'' have h := hsf'' ⟨x'', hx''⟩ rw [mem_sdiff] at h exact h.2 have im_disj : ∀ (x' x'' : ι) (hx' : x' ∈ s) (hx'' : x'' ∉ s), f' ⟨x', hx'⟩ ≠ f'' ⟨x'', hx''⟩ := by grind refine ⟨fun x => if h : x ∈ s then f' ⟨x, h⟩ else f'' ⟨x, h⟩, ?_, ?_⟩ · refine hf'.dite _ hf'' (@fun x x' => im_disj x x' _ _) · intro x simp only split_ifs with h · exact hsf' ⟨x, h⟩ · exact sdiff_subset (hsf'' ⟨x, h⟩) end Fintype variable [Finite ι] /-- Here we combine the two inductive steps into a full strong induction proof, completing the proof the harder direction of **Hall's Marriage Theorem**. -/ theorem hall_hard_inductive (ht : ∀ s : Finset ι, #s ≤ #(s.biUnion t)) : ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by cases nonempty_fintype ι generalize hn : Fintype.card ι = m induction m using Nat.strongRecOn generalizing ι with | ind n ih => _ rcases n with (_ | n) · rw [Fintype.card_eq_zero_iff] at hn exact ⟨isEmptyElim, isEmptyElim, isEmptyElim⟩ · have ih' : ∀ (ι' : Type u) [Fintype ι'] (t' : ι' → Finset α), Fintype.card ι' ≤ n → (∀ s' : Finset ι', #s' ≤ #(s'.biUnion t')) → ∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x := by intro ι' _ _ hι' ht' exact ih _ (Nat.lt_succ_of_le hι') ht' _ rfl by_cases h : ∀ s : Finset ι, s.Nonempty → s ≠ univ → #s < #(s.biUnion t) · refine hall_hard_inductive_step_A hn ht (@fun ι' => ih' ι') h · push_neg at h rcases h with ⟨s, sne, snu, sle⟩ exact hall_hard_inductive_step_B hn ht (@fun ι' => ih' ι') s sne snu (Nat.le_antisymm (ht _) sle) end HallMarriageTheorem /-- This is the version of **Hall's Marriage Theorem** in terms of indexed families of finite sets `t : ι → Finset α` with `ι` finite. It states that there is a set of distinct representatives if and only if every union of `k` of the sets has at least `k` elements. See `Finset.all_card_le_biUnion_card_iff_exists_injective` for a version where the `Finite ι` constraint is removed. -/ theorem Finset.all_card_le_biUnion_card_iff_existsInjective' {ι α : Type*} [Finite ι] [DecidableEq α] (t : ι → Finset α) : (∀ s : Finset ι, #s ≤ #(s.biUnion t)) ↔ ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by constructor · exact HallMarriageTheorem.hall_hard_inductive · rintro ⟨f, hf₁, hf₂⟩ s rw [← card_image_of_injective s hf₁] apply card_le_card intro rw [mem_image, mem_biUnion] rintro ⟨x, hx, rfl⟩ exact ⟨x, hx, hf₂ x⟩
Attr.lean
/- Copyright (c) 2023 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import Mathlib.Init import Lean.LabelAttribute /-! # The @[mono] attribute -/ namespace Mathlib.Tactic.Monotonicity syntax mono.side := &"left" <|> &"right" <|> &"both" namespace Attr /-- A lemma stating the monotonicity of some function, with respect to appropriate relations on its domain and range, and possibly with side conditions. -/ syntax (name := mono) "mono" (ppSpace mono.side)? : attr -- The following is inlined from `register_label_attr`. /- TODO: currently `left`/`right`/`both` is ignored, and e.g. `@[mono left]` means the same as `@[mono]`. No error is thrown by e.g. `@[mono left]`. -/ -- TODO: possibly extend `register_label_attr` to handle trailing syntax open Lean in @[inherit_doc mono] initialize ext : LabelExtension ← ( let descr := "A lemma stating the monotonicity of some function, with respect to appropriate relations on its domain and range, and possibly with side conditions." let mono := `mono registerLabelAttr mono descr mono) end Attr end Monotonicity end Mathlib.Tactic
PartialSups.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.Order.Lattice import Mathlib.Order.PartialSups /-! # Continuity of `partialSups` In this file we prove that `partialSups` of a sequence of continuous functions is continuous as well as versions for `Filter.Tendsto`, `ContinuousAt`, `ContinuousWithinAt`, and `ContinuousOn`. -/ open Filter open scoped Topology variable {L : Type*} [SemilatticeSup L] [TopologicalSpace L] [ContinuousSup L] namespace Filter.Tendsto variable {α : Type*} {l : Filter α} {f : ℕ → α → L} {g : ℕ → L} {n : ℕ} protected lemma partialSups (hf : ∀ k ≤ n, Tendsto (f k) l (𝓝 (g k))) : Tendsto (partialSups f n) l (𝓝 (partialSups g n)) := by simp only [partialSups_eq_sup'_range] refine finset_sup'_nhds _ ?_ simpa [Nat.lt_succ_iff] protected lemma partialSups_apply (hf : ∀ k ≤ n, Tendsto (f k) l (𝓝 (g k))) : Tendsto (fun a ↦ partialSups (f · a) n) l (𝓝 (partialSups g n)) := by simpa only [← Pi.partialSups_apply] using Tendsto.partialSups hf end Filter.Tendsto variable {X : Type*} [TopologicalSpace X] {f : ℕ → X → L} {n : ℕ} {s : Set X} {x : X} protected lemma ContinuousAt.partialSups_apply (hf : ∀ k ≤ n, ContinuousAt (f k) x) : ContinuousAt (fun a ↦ partialSups (f · a) n) x := Tendsto.partialSups_apply hf protected lemma ContinuousAt.partialSups (hf : ∀ k ≤ n, ContinuousAt (f k) x) : ContinuousAt (partialSups f n) x := by simpa only [← Pi.partialSups_apply] using ContinuousAt.partialSups_apply hf protected lemma ContinuousWithinAt.partialSups_apply (hf : ∀ k ≤ n, ContinuousWithinAt (f k) s x) : ContinuousWithinAt (fun a ↦ partialSups (f · a) n) s x := Tendsto.partialSups_apply hf protected lemma ContinuousWithinAt.partialSups (hf : ∀ k ≤ n, ContinuousWithinAt (f k) s x) : ContinuousWithinAt (partialSups f n) s x := by simpa only [← Pi.partialSups_apply] using ContinuousWithinAt.partialSups_apply hf protected lemma ContinuousOn.partialSups_apply (hf : ∀ k ≤ n, ContinuousOn (f k) s) : ContinuousOn (fun a ↦ partialSups (f · a) n) s := fun x hx ↦ ContinuousWithinAt.partialSups_apply fun k hk ↦ hf k hk x hx protected lemma ContinuousOn.partialSups (hf : ∀ k ≤ n, ContinuousOn (f k) s) : ContinuousOn (partialSups f n) s := fun x hx ↦ ContinuousWithinAt.partialSups fun k hk ↦ hf k hk x hx protected lemma Continuous.partialSups_apply (hf : ∀ k ≤ n, Continuous (f k)) : Continuous (fun a ↦ partialSups (f · a) n) := continuous_iff_continuousAt.2 fun _ ↦ ContinuousAt.partialSups_apply fun k hk ↦ (hf k hk).continuousAt protected lemma Continuous.partialSups (hf : ∀ k ≤ n, Continuous (f k)) : Continuous (partialSups f n) := continuous_iff_continuousAt.2 fun _ ↦ ContinuousAt.partialSups fun k hk ↦ (hf k hk).continuousAt
Egorov.lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import Mathlib.MeasureTheory.Function.StronglyMeasurable.Basic /-! # Egorov theorem This file contains the Egorov theorem which states that an almost everywhere convergent sequence on a finite measure space converges uniformly except on an arbitrarily small set. This theorem is useful for the Vitali convergence theorem as well as theorems regarding convergence in measure. ## Main results * `MeasureTheory.tendstoUniformlyOn_of_ae_tendsto`: Egorov's theorem which shows that a sequence of almost everywhere convergent functions converges uniformly except on an arbitrarily small set. -/ noncomputable section open MeasureTheory NNReal ENNReal Topology namespace MeasureTheory open Set Filter TopologicalSpace variable {α β ι : Type*} {m : MeasurableSpace α} [PseudoEMetricSpace β] {μ : Measure α} namespace Egorov /-- Given a sequence of functions `f` and a function `g`, `notConvergentSeq f g n j` is the set of elements such that `f k x` and `g x` are separated by at least `1 / (n + 1)` for some `k ≥ j`. This definition is useful for Egorov's theorem. -/ def notConvergentSeq [Preorder ι] (f : ι → α → β) (g : α → β) (n : ℕ) (j : ι) : Set α := ⋃ (k) (_ : j ≤ k), { x | (n : ℝ≥0∞)⁻¹ < edist (f k x) (g x) } variable {n : ℕ} {j : ι} {s : Set α} {ε : ℝ} {f : ι → α → β} {g : α → β} theorem mem_notConvergentSeq_iff [Preorder ι] {x : α} : x ∈ notConvergentSeq f g n j ↔ ∃ k ≥ j, (n : ℝ≥0∞)⁻¹ < edist (f k x) (g x) := by simp_rw [notConvergentSeq, Set.mem_iUnion, exists_prop, mem_setOf] theorem notConvergentSeq_antitone [Preorder ι] : Antitone (notConvergentSeq f g n) := fun _ _ hjk => Set.iUnion₂_mono' fun l hl => ⟨l, le_trans hjk hl, Set.Subset.rfl⟩ theorem measure_inter_notConvergentSeq_eq_zero [SemilatticeSup ι] [Nonempty ι] (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) (n : ℕ) : μ (s ∩ ⋂ j, notConvergentSeq f g n j) = 0 := by simp_rw [EMetric.tendsto_atTop, ae_iff] at hfg rw [← nonpos_iff_eq_zero, ← hfg] refine measure_mono fun x => ?_ simp only [Set.mem_inter_iff, Set.mem_iInter, mem_notConvergentSeq_iff] push_neg rintro ⟨hmem, hx⟩ refine ⟨hmem, (n : ℝ≥0∞)⁻¹, by simp, fun N => ?_⟩ obtain ⟨n, hn₁, hn₂⟩ := hx N exact ⟨n, hn₁, hn₂.le⟩ theorem notConvergentSeq_measurableSet [Preorder ι] [Countable ι] (hf : ∀ n, StronglyMeasurable[m] (f n)) (hg : StronglyMeasurable g) : MeasurableSet (notConvergentSeq f g n j) := MeasurableSet.iUnion fun k => MeasurableSet.iUnion fun _ => StronglyMeasurable.measurableSet_lt stronglyMeasurable_const <| (hf k).edist hg theorem measure_notConvergentSeq_tendsto_zero [SemilatticeSup ι] [Countable ι] (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) (n : ℕ) : Tendsto (fun j => μ (s ∩ notConvergentSeq f g n j)) atTop (𝓝 0) := by rcases isEmpty_or_nonempty ι with h | h · have : (fun j => μ (s ∩ notConvergentSeq f g n j)) = fun j => 0 := by simp only [eq_iff_true_of_subsingleton] rw [this] exact tendsto_const_nhds rw [← measure_inter_notConvergentSeq_eq_zero hfg n, Set.inter_iInter] refine tendsto_measure_iInter_atTop (fun n ↦ (hsm.inter <| notConvergentSeq_measurableSet hf hg).nullMeasurableSet) (fun k l hkl => Set.inter_subset_inter_right _ <| notConvergentSeq_antitone hkl) ⟨h.some, ne_top_of_le_ne_top hs (measure_mono Set.inter_subset_left)⟩ variable [SemilatticeSup ι] [Nonempty ι] [Countable ι] theorem exists_notConvergentSeq_lt (hε : 0 < ε) (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) (n : ℕ) : ∃ j : ι, μ (s ∩ notConvergentSeq f g n j) ≤ ENNReal.ofReal (ε * 2⁻¹ ^ n) := by have ⟨N, hN⟩ := (ENNReal.tendsto_atTop ENNReal.zero_ne_top).1 (measure_notConvergentSeq_tendsto_zero hf hg hsm hs hfg n) (.ofReal (ε * 2⁻¹ ^ n)) (by positivity) rw [zero_add] at hN exact ⟨N, (hN N le_rfl).2⟩ /-- Given some `ε > 0`, `notConvergentSeqLTIndex` provides the index such that `notConvergentSeq` (intersected with a set of finite measure) has measure less than `ε * 2⁻¹ ^ n`. This definition is useful for Egorov's theorem. -/ def notConvergentSeqLTIndex (hε : 0 < ε) (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) (n : ℕ) : ι := Classical.choose <| exists_notConvergentSeq_lt hε hf hg hsm hs hfg n theorem notConvergentSeqLTIndex_spec (hε : 0 < ε) (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) (n : ℕ) : μ (s ∩ notConvergentSeq f g n (notConvergentSeqLTIndex hε hf hg hsm hs hfg n)) ≤ ENNReal.ofReal (ε * 2⁻¹ ^ n) := Classical.choose_spec <| exists_notConvergentSeq_lt hε hf hg hsm hs hfg n /-- Given some `ε > 0`, `iUnionNotConvergentSeq` is the union of `notConvergentSeq` with specific indices such that `iUnionNotConvergentSeq` has measure less equal than `ε`. This definition is useful for Egorov's theorem. -/ def iUnionNotConvergentSeq (hε : 0 < ε) (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) : Set α := ⋃ n, s ∩ notConvergentSeq f g n (notConvergentSeqLTIndex (half_pos hε) hf hg hsm hs hfg n) theorem iUnionNotConvergentSeq_measurableSet (hε : 0 < ε) (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) : MeasurableSet <| iUnionNotConvergentSeq hε hf hg hsm hs hfg := MeasurableSet.iUnion fun _ => hsm.inter <| notConvergentSeq_measurableSet hf hg theorem measure_iUnionNotConvergentSeq (hε : 0 < ε) (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) : μ (iUnionNotConvergentSeq hε hf hg hsm hs hfg) ≤ ENNReal.ofReal ε := by refine le_trans (measure_iUnion_le _) (le_trans (ENNReal.tsum_le_tsum <| notConvergentSeqLTIndex_spec (half_pos hε) hf hg hsm hs hfg) ?_) simp_rw [ENNReal.ofReal_mul (half_pos hε).le] rw [ENNReal.tsum_mul_left, ← ENNReal.ofReal_tsum_of_nonneg, inv_eq_one_div, tsum_geometric_two, ← ENNReal.ofReal_mul (half_pos hε).le, div_mul_cancel₀ ε two_ne_zero] · intro n; positivity · rw [inv_eq_one_div] exact summable_geometric_two theorem iUnionNotConvergentSeq_subset (hε : 0 < ε) (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) : iUnionNotConvergentSeq hε hf hg hsm hs hfg ⊆ s := by rw [iUnionNotConvergentSeq, ← Set.inter_iUnion] exact Set.inter_subset_left theorem tendstoUniformlyOn_diff_iUnionNotConvergentSeq (hε : 0 < ε) (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) : TendstoUniformlyOn f g atTop (s \ Egorov.iUnionNotConvergentSeq hε hf hg hsm hs hfg) := by rw [EMetric.tendstoUniformlyOn_iff] intro δ hδ obtain ⟨N, hN⟩ := ENNReal.exists_inv_nat_lt hδ.ne' rw [eventually_atTop] refine ⟨Egorov.notConvergentSeqLTIndex (half_pos hε) hf hg hsm hs hfg N, fun n hn x hx => ?_⟩ simp only [Set.mem_diff, Egorov.iUnionNotConvergentSeq, not_exists, Set.mem_iUnion, Set.mem_inter_iff, not_and, exists_and_left] at hx obtain ⟨hxs, hx⟩ := hx specialize hx hxs N rw [Egorov.mem_notConvergentSeq_iff] at hx push_neg at hx rw [edist_comm] exact lt_of_le_of_lt (hx n hn) hN end Egorov variable [SemilatticeSup ι] [Nonempty ι] [Countable ι] {f : ι → α → β} {g : α → β} {s : Set α} /-- **Egorov's theorem**: If `f : ι → α → β` is a sequence of strongly measurable functions that converges to `g : α → β` almost everywhere on a measurable set `s` of finite measure, then for all `ε > 0`, there exists a subset `t ⊆ s` such that `μ t ≤ ε` and `f` converges to `g` uniformly on `s \ t`. We require the index type `ι` to be countable, and usually `ι = ℕ`. In other words, a sequence of almost everywhere convergent functions converges uniformly except on an arbitrarily small set. -/ theorem tendstoUniformlyOn_of_ae_tendsto (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hsm : MeasurableSet s) (hs : μ s ≠ ∞) (hfg : ∀ᵐ x ∂μ, x ∈ s → Tendsto (fun n => f n x) atTop (𝓝 (g x))) {ε : ℝ} (hε : 0 < ε) : ∃ t ⊆ s, MeasurableSet t ∧ μ t ≤ ENNReal.ofReal ε ∧ TendstoUniformlyOn f g atTop (s \ t) := ⟨Egorov.iUnionNotConvergentSeq hε hf hg hsm hs hfg, Egorov.iUnionNotConvergentSeq_subset hε hf hg hsm hs hfg, Egorov.iUnionNotConvergentSeq_measurableSet hε hf hg hsm hs hfg, Egorov.measure_iUnionNotConvergentSeq hε hf hg hsm hs hfg, Egorov.tendstoUniformlyOn_diff_iUnionNotConvergentSeq hε hf hg hsm hs hfg⟩ /-- Egorov's theorem for finite measure spaces. -/ theorem tendstoUniformlyOn_of_ae_tendsto' [IsFiniteMeasure μ] (hf : ∀ n, StronglyMeasurable (f n)) (hg : StronglyMeasurable g) (hfg : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x))) {ε : ℝ} (hε : 0 < ε) : ∃ t, MeasurableSet t ∧ μ t ≤ ENNReal.ofReal ε ∧ TendstoUniformlyOn f g atTop tᶜ := by have ⟨t, _, ht, htendsto⟩ := tendstoUniformlyOn_of_ae_tendsto hf hg MeasurableSet.univ (measure_ne_top μ Set.univ) (by filter_upwards [hfg] with _ htendsto _ using htendsto) hε refine ⟨_, ht, ?_⟩ rwa [Set.compl_eq_univ_diff] end MeasureTheory
Sifted.lean
/- Copyright (c) 2024 Robin Carlier. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robin Carlier -/ import Mathlib.CategoryTheory.Limits.Final /-! # Sifted categories A category `C` is sifted if `C` is nonempty and the diagonal functor `C ⥤ C × C` is final. Sifted categories can be characterized as those such that the colimit functor `(C ⥤ Type) ⥤ Type ` preserves finite products. ## Main results - `isSifted_of_hasBinaryCoproducts_and_nonempty`: A nonempty category with binary coproducts is sifted. ## References - [nLab, *Sifted category*](https://ncatlab.org/nlab/show/sifted+category) - [*Algebraic Theories*, Chapter 2.][Adamek_Rosicky_Vitale_2010] -/ universe w v v₁ v₂ u u₁ u₂ namespace CategoryTheory open Limits Functor section variable (C : Type u) [Category.{v} C] /-- A category `C` `IsSiftedOrEmpty` if the diagonal functor `C ⥤ C × C` is final. -/ abbrev IsSiftedOrEmpty : Prop := Final (diag C) /-- A category `C` `IsSifted` if 1. the diagonal functor `C ⥤ C × C` is final. 2. there exists some object. -/ class IsSifted : Prop extends IsSiftedOrEmpty C where [nonempty : Nonempty C] /- This instance is scoped since - it applies unconditionally (which can be a performance drain), - infers a *very* generic typeclass, - and does so from a *very* specialised class. -/ attribute [scoped instance] IsSifted.nonempty namespace IsSifted variable {C} /-- Being sifted is preserved by equivalences of categories -/ lemma isSifted_of_equiv [IsSifted C] {D : Type u₁} [Category.{v₁} D] (e : D ≌ C) : IsSifted D := letI : Final (diag D) := by letI : D × D ≌ C × C:= Equivalence.prod e e have sq : (e.inverse ⋙ diag D ⋙ this.functor ≅ diag C) := NatIso.ofComponents (fun c ↦ by dsimp [this] exact Iso.prod (e.counitIso.app c) (e.counitIso.app c)) apply_rules [final_iff_comp_equivalence _ this.functor|>.mpr, final_iff_final_comp e.inverse _ |>.mpr, final_of_natIso sq.symm] letI : _root_.Nonempty D := ⟨e.inverse.obj (_root_.Nonempty.some IsSifted.nonempty)⟩ ⟨⟩ /-- In particular a category is sifted iff and only if it is so when viewed as a small category -/ lemma isSifted_iff_asSmallIsSifted : IsSifted C ↔ IsSifted (AsSmall.{w} C) where mp _ := isSifted_of_equiv AsSmall.equiv.symm mpr _ := isSifted_of_equiv AsSmall.equiv /-- A sifted category is connected. -/ instance [IsSifted C] : IsConnected C := isConnected_of_zigzag (by intro c₁ c₂ have X : StructuredArrow (c₁, c₂) (diag C) := letI S : Final (diag C) := by infer_instance Nonempty.some (S.out (c₁, c₂)).is_nonempty use [X.right, c₂] constructor · constructor · exact Zag.of_hom X.hom.fst · simp exact Zag.of_inv X.hom.snd · rfl) /-- A category with binary coproducts is sifted or empty. -/ instance [HasBinaryCoproducts C] : IsSiftedOrEmpty C := by constructor rintro ⟨c₁, c₂⟩ haveI : _root_.Nonempty <| StructuredArrow (c₁,c₂) (diag C) := ⟨.mk ((coprod.inl : c₁ ⟶ c₁ ⨿ c₂), (coprod.inr : c₂ ⟶ c₁ ⨿ c₂))⟩ apply isConnected_of_zigzag rintro ⟨_, c, f⟩ ⟨_, c', g⟩ dsimp only [const_obj_obj, diag_obj, prod_Hom] at f g use [.mk ((coprod.inl : c₁ ⟶ c₁ ⨿ c₂), (coprod.inr : c₂ ⟶ c₁ ⨿ c₂)), .mk (g.fst, g.snd)] simp only [colimit.cocone_x, diag_obj, Prod.mk.eta, List.chain_cons, List.Chain.nil, and_true, ne_eq, reduceCtorEq, not_false_eq_true, List.getLast_cons, List.cons_ne_self, List.getLast_singleton] exact ⟨⟨Zag.of_inv <| StructuredArrow.homMk <| coprod.desc f.fst f.snd, Zag.of_hom <| StructuredArrow.homMk <| coprod.desc g.fst g.snd⟩, rfl⟩ /-- A nonempty category with binary coproducts is sifted. -/ instance isSifted_of_hasBinaryCoproducts_and_nonempty [_root_.Nonempty C] [HasBinaryCoproducts C] : IsSifted C where end IsSifted end section variable {C : Type u} [Category.{v} C] [IsSiftedOrEmpty C] {D : Type u₁} [Category.{v₁} D] {D' : Type u₂} [Category.{v₂} D'] (F : C ⥤ D) (G : C ⥤ D') instance [F.Final] [G.Final] : (F.prod' G).Final := show (diag C ⋙ F.prod G).Final from final_comp _ _ end end CategoryTheory
imset2_finset.v
From mathcomp Require Import all_boot. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Check @imset2_pair.
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.
BorelCantelli.lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import Mathlib.Algebra.Order.Archimedean.IndicatorCard import Mathlib.Probability.Martingale.Centering import Mathlib.Probability.Martingale.Convergence import Mathlib.Probability.Martingale.OptionalStopping /-! # Generalized Borel-Cantelli lemma This file proves Lévy's generalized Borel-Cantelli lemma which is a generalization of the Borel-Cantelli lemmas. With this generalization, one can easily deduce the Borel-Cantelli lemmas by choosing appropriate filtrations. This file also contains the one sided martingale bound which is required to prove the generalized Borel-Cantelli. **Note**: the usual Borel-Cantelli lemmas are not in this file. See `MeasureTheory.measure_limsup_atTop_eq_zero` for the first (which does not depend on the results here), and `ProbabilityTheory.measure_limsup_eq_one` for the second (which does). ## Main results - `MeasureTheory.Submartingale.bddAbove_iff_exists_tendsto`: the one sided martingale bound: given a submartingale `f` with uniformly bounded differences, the set for which `f` converges is almost everywhere equal to the set for which it is bounded. - `MeasureTheory.ae_mem_limsup_atTop_iff`: Lévy's generalized Borel-Cantelli: given a filtration `ℱ` and a sequence of sets `s` such that `s n ∈ ℱ n` for all `n`, `limsup atTop s` is almost everywhere equal to the set for which `∑ ℙ[s (n + 1)∣ℱ n] = ∞`. -/ open Filter open scoped NNReal ENNReal MeasureTheory ProbabilityTheory Topology namespace MeasureTheory variable {Ω : Type*} {m0 : MeasurableSpace Ω} {μ : Measure Ω} {ℱ : Filtration ℕ m0} {f : ℕ → Ω → ℝ} /-! ### One sided martingale bound -/ -- TODO: `leastGE` should be defined taking values in `WithTop ℕ` once the `stoppedProcess` -- refactor is complete /-- `leastGE f r n` is the stopping time corresponding to the first time `f ≥ r`. -/ noncomputable def leastGE (f : ℕ → Ω → ℝ) (r : ℝ) (n : ℕ) := hitting f (Set.Ici r) 0 n theorem Adapted.isStoppingTime_leastGE (r : ℝ) (n : ℕ) (hf : Adapted ℱ f) : IsStoppingTime ℱ (leastGE f r n) := hitting_isStoppingTime hf measurableSet_Ici theorem leastGE_le {i : ℕ} {r : ℝ} (ω : Ω) : leastGE f r i ω ≤ i := hitting_le ω -- The following four lemmas shows `leastGE` behaves like a stopped process. Ideally we should -- define `leastGE` as a stopping time and take its stopped process. However, we can't do that -- with our current definition since a stopping time takes only finite indices. An upcoming -- refactor should hopefully make it possible to have stopping times taking infinity as a value theorem leastGE_mono {n m : ℕ} (hnm : n ≤ m) (r : ℝ) (ω : Ω) : leastGE f r n ω ≤ leastGE f r m ω := hitting_mono hnm theorem leastGE_eq_min (π : Ω → ℕ) (r : ℝ) (ω : Ω) {n : ℕ} (hπn : ∀ ω, π ω ≤ n) : leastGE f r (π ω) ω = min (π ω) (leastGE f r n ω) := by classical refine le_antisymm (le_min (leastGE_le _) (leastGE_mono (hπn ω) r ω)) ?_ by_cases hle : π ω ≤ leastGE f r n ω · rw [min_eq_left hle, leastGE] by_cases h : ∃ j ∈ Set.Icc 0 (π ω), f j ω ∈ Set.Ici r · refine hle.trans (Eq.le ?_) rw [leastGE, ← hitting_eq_hitting_of_exists (hπn ω) h] · simp only [hitting, if_neg h, le_rfl] · rw [min_eq_right (not_le.1 hle).le, leastGE, leastGE, ← hitting_eq_hitting_of_exists (hπn ω) _] rw [not_le, leastGE, hitting_lt_iff _ (hπn ω)] at hle exact let ⟨j, hj₁, hj₂⟩ := hle ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ theorem stoppedValue_stoppedValue_leastGE (f : ℕ → Ω → ℝ) (π : Ω → ℕ) (r : ℝ) {n : ℕ} (hπn : ∀ ω, π ω ≤ n) : stoppedValue (fun i => stoppedValue f (leastGE f r i)) π = stoppedValue (stoppedProcess f (leastGE f r n)) π := by ext1 ω simp +unfoldPartialApp only [stoppedProcess, stoppedValue] rw [leastGE_eq_min _ _ _ hπn] theorem Submartingale.stoppedValue_leastGE [IsFiniteMeasure μ] (hf : Submartingale f ℱ μ) (r : ℝ) : Submartingale (fun i => stoppedValue f (leastGE f r i)) ℱ μ := by rw [submartingale_iff_expected_stoppedValue_mono] · intro σ π hσ hπ hσ_le_π hπ_bdd obtain ⟨n, hπ_le_n⟩ := hπ_bdd simp_rw [stoppedValue_stoppedValue_leastGE f σ r fun i => (hσ_le_π i).trans (hπ_le_n i)] simp_rw [stoppedValue_stoppedValue_leastGE f π r hπ_le_n] refine hf.expected_stoppedValue_mono ?_ ?_ ?_ fun ω => (min_le_left _ _).trans (hπ_le_n ω) · exact hσ.min (hf.adapted.isStoppingTime_leastGE _ _) · exact hπ.min (hf.adapted.isStoppingTime_leastGE _ _) · exact fun ω => min_le_min (hσ_le_π ω) le_rfl · exact fun i => stronglyMeasurable_stoppedValue_of_le hf.adapted.progMeasurable_of_discrete (hf.adapted.isStoppingTime_leastGE _ _) leastGE_le · exact fun i => integrable_stoppedValue _ (hf.adapted.isStoppingTime_leastGE _ _) hf.integrable leastGE_le variable {r : ℝ} {R : ℝ≥0} theorem norm_stoppedValue_leastGE_le (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : ∀ᵐ ω ∂μ, stoppedValue f (leastGE f r i) ω ≤ r + R := by filter_upwards [hbdd] with ω hbddω change f (leastGE f r i ω) ω ≤ r + R by_cases heq : leastGE f r i ω = 0 · rw [heq, hf0, Pi.zero_apply] exact add_nonneg hr R.coe_nonneg · obtain ⟨k, hk⟩ := Nat.exists_eq_succ_of_ne_zero heq rw [hk, add_comm, ← sub_le_iff_le_add] have := notMem_of_lt_hitting (hk.symm ▸ k.lt_succ_self : k < leastGE f r i ω) (zero_le _) simp only [Set.mem_Ici, not_le] at this exact (sub_lt_sub_left this _).le.trans ((le_abs_self _).trans (hbddω _)) theorem Submartingale.stoppedValue_leastGE_eLpNorm_le [IsFiniteMeasure μ] (hf : Submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : eLpNorm (stoppedValue f (leastGE f r i)) 1 μ ≤ 2 * μ Set.univ * ENNReal.ofReal (r + R) := by refine eLpNorm_one_le_of_le' ((hf.stoppedValue_leastGE r).integrable _) ?_ (norm_stoppedValue_leastGE_le hr hf0 hbdd i) rw [← setIntegral_univ] refine le_trans ?_ ((hf.stoppedValue_leastGE r).setIntegral_le (zero_le _) MeasurableSet.univ) simp_rw [stoppedValue, leastGE, hitting_of_le le_rfl, hf0, integral_zero', le_rfl] theorem Submartingale.stoppedValue_leastGE_eLpNorm_le' [IsFiniteMeasure μ] (hf : Submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : eLpNorm (stoppedValue f (leastGE f r i)) 1 μ ≤ ENNReal.toNNReal (2 * μ Set.univ * ENNReal.ofReal (r + R)) := by refine (hf.stoppedValue_leastGE_eLpNorm_le hr hf0 hbdd i).trans ?_ simp [ENNReal.coe_toNNReal (measure_ne_top μ _), ENNReal.coe_toNNReal] /-- This lemma is superseded by `Submartingale.bddAbove_iff_exists_tendsto`. -/ theorem Submartingale.exists_tendsto_of_abs_bddAbove_aux [IsFiniteMeasure μ] (hf : Submartingale f ℱ μ) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, BddAbove (Set.range fun n => f n ω) → ∃ c, Tendsto (fun n => f n ω) atTop (𝓝 c) := by have ht : ∀ᵐ ω ∂μ, ∀ i : ℕ, ∃ c, Tendsto (fun n => stoppedValue f (leastGE f i n) ω) atTop (𝓝 c) := by rw [ae_all_iff] exact fun i => Submartingale.exists_ae_tendsto_of_bdd (hf.stoppedValue_leastGE i) (hf.stoppedValue_leastGE_eLpNorm_le' i.cast_nonneg hf0 hbdd) filter_upwards [ht] with ω hω hωb rw [BddAbove] at hωb obtain ⟨i, hi⟩ := exists_nat_gt hωb.some have hib : ∀ n, f n ω < i := by intro n exact lt_of_le_of_lt ((mem_upperBounds.1 hωb.some_mem) _ ⟨n, rfl⟩) hi have heq : ∀ n, stoppedValue f (leastGE f i n) ω = f n ω := by intro n rw [leastGE]; unfold hitting; rw [stoppedValue] rw [if_neg] simp only [Set.mem_Icc, Set.mem_Ici] push_neg exact fun j _ => hib j simp only [← heq, hω i] theorem Submartingale.bddAbove_iff_exists_tendsto_aux [IsFiniteMeasure μ] (hf : Submartingale f ℱ μ) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, BddAbove (Set.range fun n => f n ω) ↔ ∃ c, Tendsto (fun n => f n ω) atTop (𝓝 c) := by filter_upwards [hf.exists_tendsto_of_abs_bddAbove_aux hf0 hbdd] with ω hω using ⟨hω, fun ⟨c, hc⟩ => hc.bddAbove_range⟩ /-- One sided martingale bound: If `f` is a submartingale which has uniformly bounded differences, then for almost every `ω`, `f n ω` is bounded above (in `n`) if and only if it converges. -/ theorem Submartingale.bddAbove_iff_exists_tendsto [IsFiniteMeasure μ] (hf : Submartingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, BddAbove (Set.range fun n => f n ω) ↔ ∃ c, Tendsto (fun n => f n ω) atTop (𝓝 c) := by set g : ℕ → Ω → ℝ := fun n ω => f n ω - f 0 ω have hg : Submartingale g ℱ μ := hf.sub_martingale (martingale_const_fun _ _ (hf.adapted 0) (hf.integrable 0)) have hg0 : g 0 = 0 := by ext ω simp only [g, sub_self, Pi.zero_apply] have hgbdd : ∀ᵐ ω ∂μ, ∀ i : ℕ, |g (i + 1) ω - g i ω| ≤ ↑R := by simpa only [g, sub_sub_sub_cancel_right] filter_upwards [hg.bddAbove_iff_exists_tendsto_aux hg0 hgbdd] with ω hω convert hω using 1 · refine ⟨fun h => ?_, fun h => ?_⟩ <;> obtain ⟨b, hb⟩ := h <;> refine ⟨b + |f 0 ω|, fun y hy => ?_⟩ <;> obtain ⟨n, rfl⟩ := hy · simp_rw [g, sub_eq_add_neg] exact add_le_add (hb ⟨n, rfl⟩) (neg_le_abs _) · exact sub_le_iff_le_add.1 (le_trans (sub_le_sub_left (le_abs_self _) _) (hb ⟨n, rfl⟩)) · refine ⟨fun h => ?_, fun h => ?_⟩ <;> obtain ⟨c, hc⟩ := h · exact ⟨c - f 0 ω, hc.sub_const _⟩ · refine ⟨c + f 0 ω, ?_⟩ have := hc.add_const (f 0 ω) simpa only [g, sub_add_cancel] /-! ### Lévy's generalization of the Borel-Cantelli lemma Lévy's generalization of the Borel-Cantelli lemma states that: given a natural number indexed filtration $(\mathcal{F}_n)$, and a sequence of sets $(s_n)$ such that for all $n$, $s_n \in \mathcal{F}_n$, $limsup_n s_n$ is almost everywhere equal to the set for which $\sum_n \mathbb{P}[s_n \mid \mathcal{F}_n] = \infty$. The proof strategy follows by constructing a martingale satisfying the one sided martingale bound. In particular, we define $$ f_n := \sum_{k < n} \mathbf{1}_{s_{n + 1}} - \mathbb{P}[s_{n + 1} \mid \mathcal{F}_n]. $$ Then, as a martingale is both a sub and a super-martingale, the set for which it is unbounded from above must agree with the set for which it is unbounded from below almost everywhere. Thus, it can only converge to $\pm \infty$ with probability 0. Thus, by considering $$ \limsup_n s_n = \{\sum_n \mathbf{1}_{s_n} = \infty\} $$ almost everywhere, the result follows. -/ theorem Martingale.bddAbove_range_iff_bddBelow_range [IsFiniteMeasure μ] (hf : Martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, BddAbove (Set.range fun n => f n ω) ↔ BddBelow (Set.range fun n => f n ω) := by have hbdd' : ∀ᵐ ω ∂μ, ∀ i, |(-f) (i + 1) ω - (-f) i ω| ≤ R := by filter_upwards [hbdd] with ω hω i erw [← abs_neg, neg_sub, sub_neg_eq_add, neg_add_eq_sub] exact hω i have hup := hf.submartingale.bddAbove_iff_exists_tendsto hbdd have hdown := hf.neg.submartingale.bddAbove_iff_exists_tendsto hbdd' filter_upwards [hup, hdown] with ω hω₁ hω₂ have : (∃ c, Tendsto (fun n => f n ω) atTop (𝓝 c)) ↔ ∃ c, Tendsto (fun n => (-f) n ω) atTop (𝓝 c) := by constructor <;> rintro ⟨c, hc⟩ · exact ⟨-c, hc.neg⟩ · refine ⟨-c, ?_⟩ convert hc.neg simp only [neg_neg, Pi.neg_apply] rw [hω₁, this, ← hω₂] constructor <;> rintro ⟨c, hc⟩ <;> refine ⟨-c, fun ω hω => ?_⟩ · rw [mem_upperBounds] at hc refine neg_le.2 (hc _ ?_) simpa only [Pi.neg_apply, Set.mem_range, neg_inj] · rw [mem_lowerBounds] at hc simp_rw [Set.mem_range, Pi.neg_apply, neg_eq_iff_eq_neg] at hω refine le_neg.1 (hc _ ?_) simpa only [Set.mem_range] theorem Martingale.ae_not_tendsto_atTop_atTop [IsFiniteMeasure μ] (hf : Martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, ¬Tendsto (fun n => f n ω) atTop atTop := by filter_upwards [hf.bddAbove_range_iff_bddBelow_range hbdd] with ω hω htop using not_bddAbove_of_tendsto_atTop htop (hω.2 <| bddBelow_range_of_tendsto_atTop_atTop htop) theorem Martingale.ae_not_tendsto_atTop_atBot [IsFiniteMeasure μ] (hf : Martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, ¬Tendsto (fun n => f n ω) atTop atBot := by filter_upwards [hf.bddAbove_range_iff_bddBelow_range hbdd] with ω hω htop using not_bddBelow_of_tendsto_atBot htop (hω.1 <| bddAbove_range_of_tendsto_atTop_atBot htop) namespace BorelCantelli /-- Auxiliary definition required to prove Lévy's generalization of the Borel-Cantelli lemmas for which we will take the martingale part. -/ noncomputable def process (s : ℕ → Set Ω) (n : ℕ) : Ω → ℝ := ∑ k ∈ Finset.range n, (s (k + 1)).indicator 1 variable {s : ℕ → Set Ω} theorem process_zero : process s 0 = 0 := by rw [process, Finset.range_zero, Finset.sum_empty] theorem adapted_process (hs : ∀ n, MeasurableSet[ℱ n] (s n)) : Adapted ℱ (process s) := fun _ => Finset.stronglyMeasurable_sum _ fun _ hk => stronglyMeasurable_one.indicator <| ℱ.mono (Finset.mem_range.1 hk) _ <| hs _ theorem martingalePart_process_ae_eq (ℱ : Filtration ℕ m0) (μ : Measure Ω) (s : ℕ → Set Ω) (n : ℕ) : martingalePart (process s) ℱ μ n = ∑ k ∈ Finset.range n, ((s (k + 1)).indicator 1 - μ[(s (k + 1)).indicator 1|ℱ k]) := by simp only [martingalePart_eq_sum, process_zero, zero_add] refine Finset.sum_congr rfl fun k _ => ?_ simp only [process, Finset.sum_range_succ_sub_sum] theorem predictablePart_process_ae_eq (ℱ : Filtration ℕ m0) (μ : Measure Ω) (s : ℕ → Set Ω) (n : ℕ) : predictablePart (process s) ℱ μ n = ∑ k ∈ Finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ)|ℱ k] := by have := martingalePart_process_ae_eq ℱ μ s n simp_rw [martingalePart, process, Finset.sum_sub_distrib] at this exact sub_right_injective this theorem process_difference_le (s : ℕ → Set Ω) (ω : Ω) (n : ℕ) : |process s (n + 1) ω - process s n ω| ≤ (1 : ℝ≥0) := by norm_cast rw [process, process, Finset.sum_apply, Finset.sum_apply, Finset.sum_range_succ_sub_sum, ← Real.norm_eq_abs, norm_indicator_eq_indicator_norm] refine Set.indicator_le' (fun _ _ => ?_) (fun _ _ => zero_le_one) _ rw [Pi.one_apply, norm_one] theorem integrable_process (μ : Measure Ω) [IsFiniteMeasure μ] (hs : ∀ n, MeasurableSet[ℱ n] (s n)) (n : ℕ) : Integrable (process s n) μ := integrable_finset_sum' _ fun _ _ => IntegrableOn.integrable_indicator (integrable_const 1) <| ℱ.le _ _ <| hs _ end BorelCantelli open BorelCantelli /-- An a.e. monotone adapted process `f` with uniformly bounded differences converges to `+∞` if and only if its predictable part also converges to `+∞`. -/ theorem tendsto_sum_indicator_atTop_iff [IsFiniteMeasure μ] (hfmono : ∀ᵐ ω ∂μ, ∀ n, f n ω ≤ f (n + 1) ω) (hf : Adapted ℱ f) (hint : ∀ n, Integrable (f n) μ) (hbdd : ∀ᵐ ω ∂μ, ∀ n, |f (n + 1) ω - f n ω| ≤ R) : ∀ᵐ ω ∂μ, Tendsto (fun n => f n ω) atTop atTop ↔ Tendsto (fun n => predictablePart f ℱ μ n ω) atTop atTop := by have h₁ := (martingale_martingalePart hf hint).ae_not_tendsto_atTop_atTop (martingalePart_bdd_difference ℱ hbdd) have h₂ := (martingale_martingalePart hf hint).ae_not_tendsto_atTop_atBot (martingalePart_bdd_difference ℱ hbdd) have h₃ : ∀ᵐ ω ∂μ, ∀ n, 0 ≤ (μ[f (n + 1) - f n|ℱ n]) ω := by refine ae_all_iff.2 fun n => condExp_nonneg ?_ filter_upwards [ae_all_iff.1 hfmono n] with ω hω using sub_nonneg.2 hω filter_upwards [h₁, h₂, h₃, hfmono] with ω hω₁ hω₂ hω₃ hω₄ constructor <;> intro ht · refine tendsto_atTop_atTop_of_monotone' ?_ ?_ · intro n m hnm simp only [predictablePart, Finset.sum_apply] exact Finset.sum_mono_set_of_nonneg hω₃ (Finset.range_mono hnm) rintro ⟨b, hbdd⟩ rw [← tendsto_neg_atBot_iff] at ht simp only [martingalePart, sub_eq_add_neg] at hω₁ exact hω₁ (tendsto_atTop_add_right_of_le _ (-b) (tendsto_neg_atBot_iff.1 ht) fun n => neg_le_neg (hbdd ⟨n, rfl⟩)) · refine tendsto_atTop_atTop_of_monotone' (monotone_nat_of_le_succ hω₄) ?_ rintro ⟨b, hbdd⟩ exact hω₂ ((tendsto_atBot_add_left_of_ge _ b fun n => hbdd ⟨n, rfl⟩) <| tendsto_neg_atBot_iff.2 ht) open BorelCantelli theorem tendsto_sum_indicator_atTop_iff' [IsFiniteMeasure μ] {s : ℕ → Set Ω} (hs : ∀ n, MeasurableSet[ℱ n] (s n)) : ∀ᵐ ω ∂μ, Tendsto (fun n => ∑ k ∈ Finset.range n, (s (k + 1)).indicator (1 : Ω → ℝ) ω) atTop atTop ↔ Tendsto (fun n => ∑ k ∈ Finset.range n, (μ[(s (k + 1)).indicator (1 : Ω → ℝ)|ℱ k]) ω) atTop atTop := by have := tendsto_sum_indicator_atTop_iff (Eventually.of_forall fun ω n => ?_) (adapted_process hs) (integrable_process μ hs) (Eventually.of_forall <| process_difference_le s) swap · rw [process, process, ← sub_nonneg, Finset.sum_apply, Finset.sum_apply, Finset.sum_range_succ_sub_sum] exact Set.indicator_nonneg (fun _ _ => zero_le_one) _ simp_rw [process, predictablePart_process_ae_eq] at this simpa using this /-- **Lévy's generalization of the Borel-Cantelli lemma**: given a sequence of sets `s` and a filtration `ℱ` such that for all `n`, `s n` is `ℱ n`-measurable, `limsup s atTop` is almost everywhere equal to the set for which `∑ k, ℙ(s (k + 1) | ℱ k) = ∞`. -/ theorem ae_mem_limsup_atTop_iff (μ : Measure Ω) [IsFiniteMeasure μ] {s : ℕ → Set Ω} (hs : ∀ n, MeasurableSet[ℱ n] (s n)) : ∀ᵐ ω ∂μ, ω ∈ limsup s atTop ↔ Tendsto (fun n => ∑ k ∈ Finset.range n, (μ[(s (k + 1)).indicator (1 : Ω → ℝ)|ℱ k]) ω) atTop atTop := by rw [← limsup_nat_add s 1, Set.limsup_eq_tendsto_sum_indicator_atTop (zero_lt_one (α := ℝ)) (fun n ↦ s (n + 1))] exact tendsto_sum_indicator_atTop_iff' hs end MeasureTheory
Extract.lean
/- Copyright (c) 2024 Jiecheng Zhao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jiecheng Zhao -/ import Mathlib.Init /-! # Lemmas about `Array.extract` Some useful lemmas about Array.extract -/ universe u variable {α : Type u} {i : Nat} namespace Array @[simp] theorem extract_eq_nil_of_start_eq_end {a : Array α} : a.extract i i = #[] := by refine extract_empty_of_stop_le_start ?h exact Nat.le_refl i /-- This is a stronger version of `Array.extract_append_left`, and should be upstreamed to replace that. -/ theorem extract_append_left' {a b : Array α} {i j : Nat} (h : j ≤ a.size) : (a ++ b).extract i j = a.extract i j := by simp [h] /-- This is a stronger version of `Array.extract_append_right`, and should be upstreamed to replace that. -/ theorem extract_append_right' {a b : Array α} {i j : Nat} (h : a.size ≤ i) : (a ++ b).extract i j = b.extract (i - a.size) (j - a.size) := by apply ext · rw [size_extract, size_extract, size_append] omega · intro k hi h2 rw [getElem_extract, getElem_extract, getElem_append_right (show size a ≤ i + k by omega)] congr omega theorem extract_eq_of_size_le_end {l p : Nat} {a : Array α} (h : a.size ≤ l) : a.extract p l = a.extract p a.size := by simp only [extract, Nat.min_eq_right h, Nat.sub_eq, Nat.min_self] end Array
GaussSum.lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import Mathlib.NumberTheory.LegendreSymbol.AddCharacter import Mathlib.NumberTheory.LegendreSymbol.ZModChar import Mathlib.Algebra.CharP.CharAndCard /-! # Gauss sums We define the Gauss sum associated to a multiplicative and an additive character of a finite field and prove some results about them. ## Main definition Let `R` be a finite commutative ring and let `R'` be another commutative ring. If `χ` is a multiplicative character `R → R'` (type `MulChar R R'`) and `ψ` is an additive character `R → R'` (type `AddChar R R'`, which abbreviates `(Multiplicative R) →* R'`), then the *Gauss sum* of `χ` and `ψ` is `∑ a, χ a * ψ a`. ## Main results Some important results are as follows. * `gaussSum_mul_gaussSum_eq_card`: The product of the Gauss sums of `χ` and `ψ` and that of `χ⁻¹` and `ψ⁻¹` is the cardinality of the source ring `R` (if `χ` is nontrivial, `ψ` is primitive and `R` is a field). * `gaussSum_sq`: The square of the Gauss sum is `χ(-1)` times the cardinality of `R` if in addition `χ` is a quadratic character. * `MulChar.IsQuadratic.gaussSum_frob`: For a quadratic character `χ`, raising the Gauss sum to the `p`th power (where `p` is the characteristic of the target ring `R'`) multiplies it by `χ p`. * `Char.card_pow_card`: When `F` and `F'` are finite fields and `χ : F → F'` is a nontrivial quadratic character, then `(χ (-1) * #F)^(#F'/2) = χ #F'`. * `FiniteField.two_pow_card`: For every finite field `F` of odd characteristic, we have `2^(#F/2) = χ₈ #F` in `F`. This machinery can be used to derive (a generalization of) the Law of Quadratic Reciprocity. ## Tags additive character, multiplicative character, Gauss sum -/ universe u v open AddChar MulChar section GaussSumDef -- `R` is the domain of the characters variable {R : Type u} [CommRing R] [Fintype R] -- `R'` is the target of the characters variable {R' : Type v} [CommRing R'] /-! ### Definition and first properties -/ /-- Definition of the Gauss sum associated to a multiplicative and an additive character. -/ def gaussSum (χ : MulChar R R') (ψ : AddChar R R') : R' := ∑ a, χ a * ψ a /-- Replacing `ψ` by `mulShift ψ a` and multiplying the Gauss sum by `χ a` does not change it. -/ theorem gaussSum_mulShift (χ : MulChar R R') (ψ : AddChar R R') (a : Rˣ) : χ a * gaussSum χ (mulShift ψ a) = gaussSum χ ψ := by simp only [gaussSum, mulShift_apply, Finset.mul_sum] simp_rw [← mul_assoc, ← map_mul] exact Fintype.sum_bijective _ a.mulLeft_bijective _ _ fun x ↦ rfl end GaussSumDef /-! ### The product of two Gauss sums -/ section GaussSumProd open Finset in /-- A formula for the product of two Gauss sums with the same additive character. -/ lemma gaussSum_mul {R : Type u} [CommRing R] [Fintype R] {R' : Type v} [CommRing R'] (χ φ : MulChar R R') (ψ : AddChar R R') : gaussSum χ ψ * gaussSum φ ψ = ∑ t : R, ∑ x : R, χ x * φ (t - x) * ψ t := by rw [gaussSum, gaussSum, sum_mul_sum] conv => enter [1, 2, x, 2, x_1]; rw [mul_mul_mul_comm] simp only [← ψ.map_add_eq_mul] have sum_eq x : ∑ y : R, χ x * φ y * ψ (x + y) = ∑ y : R, χ x * φ (y - x) * ψ y := by rw [sum_bij (fun a _ ↦ a + x)] · simp only [mem_univ, forall_const] · simp only [mem_univ, add_left_inj, imp_self, forall_const] · exact fun b _ ↦ ⟨b - x, mem_univ _, by rw [sub_add_cancel]⟩ · exact fun a _ ↦ by rw [add_sub_cancel_right, add_comm] rw [sum_congr rfl fun x _ ↦ sum_eq x, sum_comm] -- In the following, we need `R` to be a finite field. variable {R : Type u} [Field R] [Fintype R] {R' : Type v} [CommRing R'] lemma mul_gaussSum_inv_eq_gaussSum (χ : MulChar R R') (ψ : AddChar R R') : χ (-1) * gaussSum χ ψ⁻¹ = gaussSum χ ψ := by rw [ψ.inv_mulShift, ← Units.coe_neg_one] exact gaussSum_mulShift χ ψ (-1) variable [IsDomain R'] -- From now on, `R'` needs to be a domain. -- A helper lemma for `gaussSum_mul_gaussSum_eq_card` below -- Is this useful enough in other contexts to be public? private theorem gaussSum_mul_aux {χ : MulChar R R'} (hχ : χ ≠ 1) (ψ : AddChar R R') (b : R) : ∑ a, χ (a * b⁻¹) * ψ (a - b) = ∑ c, χ c * ψ (b * (c - 1)) := by rcases eq_or_ne b 0 with hb | hb · -- case `b = 0` simp only [hb, inv_zero, mul_zero, MulChar.map_zero, zero_mul, Finset.sum_const_zero, map_zero_eq_one, mul_one, χ.sum_eq_zero_of_ne_one hχ] · -- case `b ≠ 0` refine (Fintype.sum_bijective _ (mulLeft_bijective₀ b hb) _ _ fun x ↦ ?_).symm rw [mul_assoc, mul_comm x, ← mul_assoc, mul_inv_cancel₀ hb, one_mul, mul_sub, mul_one] /-- We have `gaussSum χ ψ * gaussSum χ⁻¹ ψ⁻¹ = Fintype.card R` when `χ` is nontrivial and `ψ` is primitive (and `R` is a field). -/ theorem gaussSum_mul_gaussSum_eq_card {χ : MulChar R R'} (hχ : χ ≠ 1) {ψ : AddChar R R'} (hψ : IsPrimitive ψ) : gaussSum χ ψ * gaussSum χ⁻¹ ψ⁻¹ = Fintype.card R := by simp only [gaussSum, AddChar.inv_apply, Finset.sum_mul, Finset.mul_sum, MulChar.inv_apply'] conv => enter [1, 2, x, 2, y] rw [mul_mul_mul_comm, ← map_mul, ← map_add_eq_mul, ← sub_eq_add_neg] -- conv in _ * _ * (_ * _) => rw [mul_mul_mul_comm, ← map_mul, ← map_add_eq_mul, ← sub_eq_add_neg] simp_rw [gaussSum_mul_aux hχ ψ] rw [Finset.sum_comm] classical -- to get `[DecidableEq R]` for `sum_mulShift` simp_rw [← Finset.mul_sum, sum_mulShift _ hψ, sub_eq_zero, apply_ite, Nat.cast_zero, mul_zero] rw [Finset.sum_ite_eq' Finset.univ (1 : R)] simp only [Finset.mem_univ, map_one, one_mul, if_true] /-- If `χ` is a multiplicative character of order `n` on a finite field `F`, then `g(χ) * g(χ^(n-1)) = χ(-1)*#F` -/ lemma gaussSum_mul_gaussSum_pow_orderOf_sub_one {χ : MulChar R R'} {ψ : AddChar R R'} (hχ : χ ≠ 1) (hψ : ψ.IsPrimitive) : gaussSum χ ψ * gaussSum (χ ^ (orderOf χ - 1)) ψ = χ (-1) * Fintype.card R := by have h : χ ^ (orderOf χ - 1) = χ⁻¹ := by refine (inv_eq_of_mul_eq_one_right ?_).symm rw [← pow_succ', Nat.sub_one_add_one_eq_of_pos χ.orderOf_pos, pow_orderOf_eq_one] rw [h, ← mul_gaussSum_inv_eq_gaussSum χ⁻¹, mul_left_comm, gaussSum_mul_gaussSum_eq_card hχ hψ, MulChar.inv_apply', inv_neg_one] /-- The Gauss sum of a nontrivial character on a finite field does not vanish. -/ lemma gaussSum_ne_zero_of_nontrivial (h : (Fintype.card R : R') ≠ 0) {χ : MulChar R R'} (hχ : χ ≠ 1) {ψ : AddChar R R'} (hψ : ψ.IsPrimitive) : gaussSum χ ψ ≠ 0 := fun H ↦ h.symm <| zero_mul (gaussSum χ⁻¹ _) ▸ H ▸ gaussSum_mul_gaussSum_eq_card hχ hψ /-- When `χ` is a nontrivial quadratic character, then the square of `gaussSum χ ψ` is `χ(-1)` times the cardinality of `R`. -/ theorem gaussSum_sq {χ : MulChar R R'} (hχ₁ : χ ≠ 1) (hχ₂ : IsQuadratic χ) {ψ : AddChar R R'} (hψ : IsPrimitive ψ) : gaussSum χ ψ ^ 2 = χ (-1) * Fintype.card R := by rw [pow_two, ← gaussSum_mul_gaussSum_eq_card hχ₁ hψ, hχ₂.inv, mul_rotate'] congr rw [mul_comm, ← gaussSum_mulShift _ _ (-1 : Rˣ), inv_mulShift] rfl end GaussSumProd /-! ### Gauss sums and Frobenius -/ section gaussSum_frob variable {R : Type u} [CommRing R] [Fintype R] {R' : Type v} [CommRing R'] -- We assume that the target ring `R'` has prime characteristic `p`. variable (p : ℕ) [fp : Fact p.Prime] [hch : CharP R' p] /-- When `R'` has prime characteristic `p`, then the `p`th power of the Gauss sum of `χ` and `ψ` is the Gauss sum of `χ^p` and `ψ^p`. -/ theorem gaussSum_frob (χ : MulChar R R') (ψ : AddChar R R') : gaussSum χ ψ ^ p = gaussSum (χ ^ p) (ψ ^ p) := by rw [← frobenius_def, gaussSum, gaussSum, map_sum] simp_rw [pow_apply' χ fp.1.ne_zero, map_mul, frobenius_def] rfl /-- For a quadratic character `χ` and when the characteristic `p` of the target ring is a unit in the source ring, the `p`th power of the Gauss sum of`χ` and `ψ` is `χ p` times the original Gauss sum. -/ theorem MulChar.IsQuadratic.gaussSum_frob (hp : IsUnit (p : R)) {χ : MulChar R R'} (hχ : IsQuadratic χ) (ψ : AddChar R R') : gaussSum χ ψ ^ p = χ p * gaussSum χ ψ := by rw [_root_.gaussSum_frob, pow_mulShift, hχ.pow_char p, ← gaussSum_mulShift χ ψ hp.unit, ← mul_assoc, hp.unit_spec, ← pow_two, ← pow_apply' _ two_ne_zero, hχ.sq_eq_one, ← hp.unit_spec, one_apply_coe, one_mul] /-- For a quadratic character `χ` and when the characteristic `p` of the target ring is a unit in the source ring and `n` is a natural number, the `p^n`th power of the Gauss sum of`χ` and `ψ` is `χ (p^n)` times the original Gauss sum. -/ theorem MulChar.IsQuadratic.gaussSum_frob_iter (n : ℕ) (hp : IsUnit (p : R)) {χ : MulChar R R'} (hχ : IsQuadratic χ) (ψ : AddChar R R') : gaussSum χ ψ ^ p ^ n = χ ((p : R) ^ n) * gaussSum χ ψ := by induction n with | zero => rw [pow_zero, pow_one, pow_zero, MulChar.map_one, one_mul] | succ n ih => rw [pow_succ, pow_mul, ih, mul_pow, hχ.gaussSum_frob _ hp, ← mul_assoc, pow_succ, map_mul, ← pow_apply' χ fp.1.ne_zero ((p : R) ^ n), hχ.pow_char p] end gaussSum_frob /-! ### Values of quadratic characters -/ section GaussSumValues variable {R : Type u} [CommRing R] [Fintype R] {R' : Type v} [CommRing R'] [IsDomain R'] /-- If the square of the Gauss sum of a quadratic character is `χ(-1) * #R`, then we get, for all `n : ℕ`, the relation `(χ(-1) * #R) ^ (p^n/2) = χ(p^n)`, where `p` is the (odd) characteristic of the target ring `R'`. This version can be used when `R` is not a field, e.g., `ℤ/8ℤ`. -/ theorem Char.card_pow_char_pow {χ : MulChar R R'} (hχ : IsQuadratic χ) (ψ : AddChar R R') (p n : ℕ) [fp : Fact p.Prime] [hch : CharP R' p] (hp : IsUnit (p : R)) (hp' : p ≠ 2) (hg : gaussSum χ ψ ^ 2 = χ (-1) * Fintype.card R) : (χ (-1) * Fintype.card R) ^ (p ^ n / 2) = χ ((p : R) ^ n) := by have : gaussSum χ ψ ≠ 0 := by intro hf rw [hf, zero_pow two_ne_zero, eq_comm, mul_eq_zero] at hg exact not_isUnit_prime_of_dvd_card p ((CharP.cast_eq_zero_iff R' p _).mp <| hg.resolve_left (isUnit_one.neg.map χ).ne_zero) hp rw [← hg] apply mul_right_cancel₀ this rw [← hχ.gaussSum_frob_iter p n hp ψ, ← pow_mul, ← pow_succ, Nat.two_mul_div_two_add_one_of_odd (fp.1.eq_two_or_odd'.resolve_left hp').pow] /-- When `F` and `F'` are finite fields and `χ : F → F'` is a nontrivial quadratic character, then `(χ(-1) * #F)^(#F'/2) = χ #F'`. -/ theorem Char.card_pow_card {F : Type*} [Field F] [Fintype F] {F' : Type*} [Field F'] [Fintype F'] {χ : MulChar F F'} (hχ₁ : χ ≠ 1) (hχ₂ : IsQuadratic χ) (hch₁ : ringChar F' ≠ ringChar F) (hch₂ : ringChar F' ≠ 2) : (χ (-1) * Fintype.card F) ^ (Fintype.card F' / 2) = χ (Fintype.card F') := by obtain ⟨n, hp, hc⟩ := FiniteField.card F (ringChar F) obtain ⟨n', hp', hc'⟩ := FiniteField.card F' (ringChar F') let ψ := FiniteField.primitiveChar F F' hch₁ let FF' := CyclotomicField ψ.n F' have hchar := Algebra.ringChar_eq F' FF' apply (algebraMap F' FF').injective rw [map_pow, map_mul, map_natCast, hc', hchar, Nat.cast_pow] simp only [← MulChar.ringHomComp_apply] have := Fact.mk hp' have := Fact.mk (hchar.subst hp') rw [Ne, ← Nat.prime_dvd_prime_iff_eq hp' hp, ← isUnit_iff_not_dvd_char, hchar] at hch₁ exact Char.card_pow_char_pow (hχ₂.comp _) ψ.char (ringChar FF') n' hch₁ (hchar ▸ hch₂) (gaussSum_sq ((ringHomComp_ne_one_iff (RingHom.injective _)).mpr hχ₁) (hχ₂.comp _) ψ.prim) end GaussSumValues section GaussSumTwo /-! ### The quadratic character of 2 This section proves the following result. For every finite field `F` of odd characteristic, we have `2^(#F/2) = χ₈#F` in `F`. This can be used to show that the quadratic character of `F` takes the value `χ₈#F` at `2`. The proof uses the Gauss sum of `χ₈` and a primitive additive character on `ℤ/8ℤ`; in this way, the result is reduced to `card_pow_char_pow`. -/ open ZMod /-- For every finite field `F` of odd characteristic, we have `2^(#F/2) = χ₈ #F` in `F`. -/ theorem FiniteField.two_pow_card {F : Type*} [Fintype F] [Field F] (hF : ringChar F ≠ 2) : (2 : F) ^ (Fintype.card F / 2) = χ₈ (Fintype.card F) := by have hp2 (n : ℕ) : (2 ^ n : F) ≠ 0 := pow_ne_zero n (Ring.two_ne_zero hF) obtain ⟨n, hp, hc⟩ := FiniteField.card F (ringChar F) -- we work in `FF`, the eighth cyclotomic field extension of `F` let FF := CyclotomicField 8 F have hchar := Algebra.ringChar_eq F FF have FFp := hchar.subst hp have := Fact.mk FFp have hFF := hchar ▸ hF -- `ringChar FF ≠ 2` have hu : IsUnit (ringChar FF : ZMod 8) := by rw [isUnit_iff_not_dvd_char, ringChar_zmod_n] rw [Ne, ← Nat.prime_dvd_prime_iff_eq FFp Nat.prime_two] at hFF change ¬_ ∣ 2 ^ 3 exact mt FFp.dvd_of_dvd_pow hFF -- there is a primitive additive character `ℤ/8ℤ → FF`, sending `a + 8ℤ ↦ τ^a` -- with a primitive eighth root of unity `τ` let ψ₈ := primitiveZModChar 8 F (by convert hp2 3 using 1; norm_cast) -- We cast from `AddChar (ZMod (8 : ℕ+)) FF` to `AddChar (ZMod 8) FF` -- This is needed to make `simp_rw [← h₁]` below work. let ψ₈char : AddChar (ZMod 8) FF := ψ₈.char let τ : FF := ψ₈char 1 have τ_spec : τ ^ 4 = -1 := by rw [show τ = ψ₈.char 1 from rfl] -- to make `rw [ψ₈.prim.zmod_char_eq_one_iff]` work refine (sq_eq_one_iff.1 ?_).resolve_left ?_ · rw [← pow_mul, ← map_nsmul_eq_pow ψ₈.char, ψ₈.prim.zmod_char_eq_one_iff] decide · rw [← map_nsmul_eq_pow ψ₈.char, ψ₈.prim.zmod_char_eq_one_iff] decide -- we consider `χ₈` as a multiplicative character `ℤ/8ℤ → FF` let χ := χ₈.ringHomComp (Int.castRingHom FF) have hχ : χ (-1) = 1 := Int.cast_one have hq : IsQuadratic χ := isQuadratic_χ₈.comp _ -- we now show that the Gauss sum of `χ` and `ψ₈` has the relevant property have h₁ : (fun (a : Fin 8) ↦ ↑(χ₈ a) * τ ^ (a : ℕ)) = fun a ↦ χ a * ↑(ψ₈char a) := by ext1; congr; apply pow_one have hg₁ : gaussSum χ ψ₈char = 2 * (τ - τ ^ 3) := by rw [gaussSum, ← h₁, Fin.sum_univ_eight, -- evaluate `χ₈` show χ₈ 0 = 0 from rfl, show χ₈ 1 = 1 from rfl, show χ₈ 2 = 0 from rfl, show χ₈ 3 = -1 from rfl, show χ₈ 4 = 0 from rfl, show χ₈ 5 = -1 from rfl, show χ₈ 6 = 0 from rfl, show χ₈ 7 = 1 from rfl, -- normalize exponents show ((3 : Fin 8) : ℕ) = 3 from rfl, show ((5 : Fin 8) : ℕ) = 5 from rfl, show ((7 : Fin 8) : ℕ) = 7 from rfl] simp only [Int.cast_zero, zero_mul, Int.cast_one, Fin.val_one, pow_one, one_mul, zero_add, Fin.val_two, add_zero, Int.reduceNeg, Int.cast_neg] linear_combination (τ ^ 3 - τ) * τ_spec have hg : gaussSum χ ψ₈char ^ 2 = χ (-1) * Fintype.card (ZMod 8) := by rw [hχ, one_mul, ZMod.card, Nat.cast_ofNat, hg₁] linear_combination (4 * τ ^ 2 - 8) * τ_spec -- this allows us to apply `card_pow_char_pow` to our situation have h := Char.card_pow_char_pow (R := ZMod 8) hq ψ₈char (ringChar FF) n hu hFF hg rw [ZMod.card, ← hchar, hχ, one_mul, ← hc, ← Nat.cast_pow (ringChar F), ← hc] at h -- finally, we change `2` to `8` on the left hand side convert_to (8 : F) ^ (Fintype.card F / 2) = _ · rw [(by norm_num : (8 : F) = 2 ^ 2 * 2), mul_pow, (FiniteField.isSquare_iff hF <| hp2 2).mp ⟨2, pow_two 2⟩, one_mul] apply (algebraMap F FF).injective simpa only [map_pow, map_ofNat, map_intCast, Nat.cast_ofNat] using h end GaussSumTwo
Nerve.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.SimplicialSet.Basic import Mathlib.CategoryTheory.ComposableArrows /-! # The nerve of a category This file provides the definition of the nerve of a category `C`, which is a simplicial set `nerve C` (see [goerss-jardine-2009], Example I.1.4). By definition, the type of `n`-simplices of `nerve C` is `ComposableArrows C n`, which is the category `Fin (n + 1) ⥤ C`. ## References * [Paul G. Goerss, John F. Jardine, *Simplicial Homotopy Theory*][goerss-jardine-2009] -/ open CategoryTheory.Category Simplicial universe v u namespace CategoryTheory /-- The nerve of a category -/ @[simps] def nerve (C : Type u) [Category.{v} C] : SSet.{max u v} where obj Δ := ComposableArrows C (Δ.unop.len) map f x := x.whiskerLeft (SimplexCategory.toCat.map f.unop) -- `aesop` can prove these but is slow, help it out: map_id _ := rfl map_comp _ _ := rfl instance {C : Type*} [Category C] {Δ : SimplexCategoryᵒᵖ} : Category ((nerve C).obj Δ) := (inferInstance : Category (ComposableArrows C (Δ.unop.len))) /-- Given a functor `C ⥤ D`, we obtain a morphism `nerve C ⟶ nerve D` of simplicial sets. -/ @[simps] def nerveMap {C D : Type u} [Category.{v} C] [Category.{v} D] (F : C ⥤ D) : nerve C ⟶ nerve D := { app := fun _ => (F.mapComposableArrows _).obj } /-- The nerve of a category, as a functor `Cat ⥤ SSet` -/ @[simps] def nerveFunctor : Cat.{v, u} ⥤ SSet where obj C := nerve C map F := nerveMap F /-- The 0-simplices of the nerve of a category are equivalent to the objects of the category. -/ def nerveEquiv (C : Type u) [Category.{v} C] : nerve C _⦋0⦌ ≃ C where toFun f := f.obj ⟨0, by omega⟩ invFun f := (Functor.const _).obj f left_inv f := ComposableArrows.ext₀ rfl namespace nerve variable {C : Type*} [Category C] {n : ℕ} lemma δ₀_eq {x : nerve C _⦋n + 1⦌} : (nerve C).δ (0 : Fin (n + 2)) x = x.δ₀ := rfl lemma σ₀_mk₀_eq (x : C) : (nerve C).σ (0 : Fin 1) (.mk₀ x) = .mk₁ (𝟙 x) := ComposableArrows.ext₁ rfl rfl (by simp; rfl) section variable {X₀ X₁ X₂ : C} (f : X₀ ⟶ X₁) (g : X₁ ⟶ X₂) theorem δ₂_mk₂_eq : (nerve C).δ 2 (ComposableArrows.mk₂ f g) = ComposableArrows.mk₁ f := ComposableArrows.ext₁ rfl rfl (by simp; rfl) theorem δ₀_mk₂_eq : (nerve C).δ 0 (ComposableArrows.mk₂ f g) = ComposableArrows.mk₁ g := ComposableArrows.ext₁ rfl rfl (by simp; rfl) theorem δ₁_mk₂_eq : (nerve C).δ 1 (ComposableArrows.mk₂ f g) = ComposableArrows.mk₁ (f ≫ g) := ComposableArrows.ext₁ rfl rfl (by simp; rfl) end end nerve end CategoryTheory
log.lean
import Mathlib.Data.Nat.Log /-! This used to fail (ran out of heartbeats) but with a new faster `Nat.logC` tagged `csimp`, it succeeds. -/ /-- info: 10000000 -/ #guard_msgs in #eval Nat.log 2 (2 ^ 10000000)
Synonym.lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Yaël Dillies -/ import Mathlib.Algebra.Order.Group.Synonym import Mathlib.Algebra.Ring.Defs /-! # Ring structure on the order type synonyms Transfer algebraic instances from `R` to `Rᵒᵈ` and `Lex R`. -/ variable {R : Type*} /-! ### Order dual -/ instance [h : Distrib R] : Distrib Rᵒᵈ := h instance [Mul R] [Add R] [h : LeftDistribClass R] : LeftDistribClass Rᵒᵈ := h instance [Mul R] [Add R] [h : RightDistribClass R] : RightDistribClass Rᵒᵈ := h instance [h : NonUnitalNonAssocSemiring R] : NonUnitalNonAssocSemiring Rᵒᵈ := h instance [h : NonUnitalSemiring R] : NonUnitalSemiring Rᵒᵈ := h instance [h : NonAssocSemiring R] : NonAssocSemiring Rᵒᵈ := h instance [h : Semiring R] : Semiring Rᵒᵈ := h instance [h : NonUnitalCommSemiring R] : NonUnitalCommSemiring Rᵒᵈ := h instance [h : CommSemiring R] : CommSemiring Rᵒᵈ := h instance [Mul R] [h : HasDistribNeg R] : HasDistribNeg Rᵒᵈ := h instance [h : NonUnitalNonAssocRing R] : NonUnitalNonAssocRing Rᵒᵈ := h instance [h : NonUnitalRing R] : NonUnitalRing Rᵒᵈ := h instance [h : NonAssocRing R] : NonAssocRing Rᵒᵈ := h instance [h : Ring R] : Ring Rᵒᵈ := h instance [h : NonUnitalCommRing R] : NonUnitalCommRing Rᵒᵈ := h instance [h : CommRing R] : CommRing Rᵒᵈ := h instance [Ring R] [h : IsDomain R] : IsDomain Rᵒᵈ := h /-! ### Lexicographical order -/ instance [h : Distrib R] : Distrib (Lex R) := h instance [Mul R] [Add R] [h : LeftDistribClass R] : LeftDistribClass (Lex R) := h instance [Mul R] [Add R] [h : RightDistribClass R] : RightDistribClass (Lex R) := h instance [h : NonUnitalNonAssocSemiring R] : NonUnitalNonAssocSemiring (Lex R) := h instance [h : NonUnitalSemiring R] : NonUnitalSemiring (Lex R) := h instance [h : NonAssocSemiring R] : NonAssocSemiring (Lex R) := h instance [h : Semiring R] : Semiring (Lex R) := h instance [h : NonUnitalCommSemiring R] : NonUnitalCommSemiring (Lex R) := h instance [h : CommSemiring R] : CommSemiring (Lex R) := h instance [Mul R] [h : HasDistribNeg R] : HasDistribNeg (Lex R) := h instance [h : NonUnitalNonAssocRing R] : NonUnitalNonAssocRing (Lex R) := h instance [h : NonUnitalRing R] : NonUnitalRing (Lex R) := h instance [h : NonAssocRing R] : NonAssocRing (Lex R) := h instance [h : Ring R] : Ring (Lex R) := h instance [h : NonUnitalCommRing R] : NonUnitalCommRing (Lex R) := h instance [h : CommRing R] : CommRing (Lex R) := h instance [Ring R] [h : IsDomain R] : IsDomain (Lex R) := h
InfSemilattice.lean
import Mathlib.CategoryTheory.Monoidal.Cartesian.InfSemilattice deprecated_module (since := "2025-05-15")
Lebesgue.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import Mathlib.MeasureTheory.Integral.Lebesgue.Basic import Mathlib.MeasureTheory.Integral.Lebesgue.Countable import Mathlib.MeasureTheory.Integral.Lebesgue.MeasurePreserving import Mathlib.MeasureTheory.Integral.Lebesgue.Norm deprecated_module (since := "2025-04-13")
NoncommCoprod.lean
/- Copyright (c) 2023 Antoine Chambert-Loir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Chambert-Loir -/ import Mathlib.Algebra.Group.Commute.Hom import Mathlib.Algebra.Group.Prod import Mathlib.Algebra.Group.Subgroup.Ker import Mathlib.Algebra.Group.Subgroup.Lattice import Mathlib.Order.Disjoint /-! # Canonical homomorphism from a pair of monoids This file defines the construction of the canonical homomorphism from a pair of monoids. Given two morphisms of monoids `f : M →* P` and `g : N →* P` where elements in the images of the two morphisms commute, we obtain a canonical morphism `MonoidHom.noncommCoprod : M × N →* P` whose composition with `inl M N` coincides with `f` and whose composition with `inr M N` coincides with `g`. There is an analogue `MulHom.noncommCoprod` when `f` and `g` are only `MulHom`s. ## Main theorems: * `noncommCoprod_comp_inr` and `noncommCoprod_comp_inl` prove that the compositions of `MonoidHom.noncommCoprod f g _` with `inl M N` and `inr M N` coincide with `f` and `g`. * `comp_noncommCoprod` proves that the composition of a morphism of monoids `h` with `noncommCoprod f g _` coincides with `noncommCoprod (h.comp f) (h.comp g)`. For a product of a family of morphisms of monoids, see `MonoidHom.noncommPiCoprod`. -/ assert_not_exists MonoidWithZero namespace MulHom variable {M N P : Type*} [Mul M] [Mul N] [Semigroup P] (f : M →ₙ* P) (g : N →ₙ* P) /-- Coproduct of two `MulHom`s with the same codomain with `Commute` assumption: `f.noncommCoprod g _ (p : M × N) = f p.1 * g p.2`. (For the commutative case, use `MulHom.coprod`) -/ @[to_additive (attr := simps) /-- Coproduct of two `AddHom`s with the same codomain with `AddCommute` assumption: `f.noncommCoprod g _ (p : M × N) = f p.1 + g p.2`. (For the commutative case, use `AddHom.coprod`) -/] def noncommCoprod (comm : ∀ m n, Commute (f m) (g n)) : M × N →ₙ* P where toFun mn := f mn.fst * g mn.snd map_mul' mn mn' := by simpa using (comm _ _).mul_mul_mul_comm _ _ /-- Variant of `MulHom.noncommCoprod_apply` with the product written in the other direction` -/ @[to_additive /-- Variant of `AddHom.noncommCoprod_apply`, with the sum written in the other direction -/] theorem noncommCoprod_apply' (comm) (mn : M × N) : (f.noncommCoprod g comm) mn = g mn.2 * f mn.1 := by rw [← comm, noncommCoprod_apply] @[to_additive] theorem comp_noncommCoprod {Q : Type*} [Semigroup Q] (h : P →ₙ* Q) (comm : ∀ m n, Commute (f m) (g n)) : h.comp (f.noncommCoprod g comm) = (h.comp f).noncommCoprod (h.comp g) (fun m n ↦ (comm m n).map h) := ext fun _ => map_mul h _ _ end MulHom namespace MonoidHom variable {M N P : Type*} [MulOneClass M] [MulOneClass N] [Monoid P] (f : M →* P) (g : N →* P) (comm : ∀ m n, Commute (f m) (g n)) /-- Coproduct of two `MonoidHom`s with the same codomain, with a commutation assumption: `f.noncommCoprod g _ (p : M × N) = f p.1 * g p.2`. (Noncommutative case; in the commutative case, use `MonoidHom.coprod`.) -/ @[to_additive (attr := simps) /-- Coproduct of two `AddMonoidHom`s with the same codomain, with a commutation assumption: `f.noncommCoprod g (p : M × N) = f p.1 + g p.2`. (Noncommutative case; in the commutative case, use `AddHom.coprod`.) -/] def noncommCoprod : M × N →* P where toFun := fun mn ↦ (f mn.fst) * (g mn.snd) map_one' := by simp only [Prod.fst_one, Prod.snd_one, map_one, mul_one] __ := f.toMulHom.noncommCoprod g.toMulHom comm /-- Variant of `MonoidHom.noncomCoprod_apply` with the product written in the other direction` -/ @[to_additive /-- Variant of `AddMonoidHom.noncomCoprod_apply` with the sum written in the other direction -/] theorem noncommCoprod_apply' (comm) (mn : M × N) : (f.noncommCoprod g comm) mn = g mn.2 * f mn.1 := by rw [← comm, MonoidHom.noncommCoprod_apply] @[to_additive (attr := simp)] theorem noncommCoprod_comp_inl : (f.noncommCoprod g comm).comp (inl M N) = f := ext fun x => by simp @[to_additive (attr := simp)] theorem noncommCoprod_comp_inr : (f.noncommCoprod g comm).comp (inr M N) = g := ext fun x => by simp @[to_additive (attr := simp)] theorem noncommCoprod_unique (f : M × N →* P) : (f.comp (inl M N)).noncommCoprod (f.comp (inr M N)) (fun _ _ => (commute_inl_inr _ _).map f) = f := ext fun x => by simp [inl_apply, inr_apply, ← map_mul] @[to_additive (attr := simp)] theorem noncommCoprod_inl_inr {M N : Type*} [Monoid M] [Monoid N] : (inl M N).noncommCoprod (inr M N) commute_inl_inr = id (M × N) := noncommCoprod_unique <| .id (M × N) @[to_additive] theorem comp_noncommCoprod {Q : Type*} [Monoid Q] (h : P →* Q) : h.comp (f.noncommCoprod g comm) = (h.comp f).noncommCoprod (h.comp g) (fun m n ↦ (comm m n).map h) := ext fun x => by simp section group open Subgroup lemma noncommCoprod_injective {M N P : Type*} [Group M] [Group N] [Group P] (f : M →* P) (g : N →* P) (comm : ∀ (m : M) (n : N), Commute (f m) (g n)) : Function.Injective (noncommCoprod f g comm) ↔ (Function.Injective f ∧ Function.Injective g ∧ _root_.Disjoint f.range g.range) := by simp only [injective_iff_map_eq_one, disjoint_iff_inf_le, noncommCoprod_apply, Prod.forall, Prod.mk_eq_one] refine ⟨fun h ↦ ⟨fun x ↦ ?_, fun x ↦ ?_, ?_⟩, ?_⟩ · simpa using h x 1 · simpa using h 1 x · intro x ⟨⟨y, hy⟩, z, hz⟩ rwa [(h y z⁻¹ (by rw [map_inv, hy, hz, mul_inv_cancel])).1, map_one, eq_comm] at hy · intro ⟨hf, hg, hp⟩ a b h have key := hp ⟨⟨a⁻¹, by rwa [map_inv, inv_eq_iff_mul_eq_one]⟩, b, rfl⟩ exact ⟨hf a (by rwa [key, mul_one] at h), hg b key⟩ lemma noncommCoprod_range {M N P : Type*} [Group M] [Group N] [Group P] (f : M →* P) (g : N →* P) (comm : ∀ (m : M) (n : N), Commute (f m) (g n)) : (noncommCoprod f g comm).range = f.range ⊔ g.range := by apply le_antisymm · rintro - ⟨a, rfl⟩ exact mul_mem (mem_sup_left ⟨a.1, rfl⟩) (mem_sup_right ⟨a.2, rfl⟩) · rw [sup_le_iff] constructor · rintro - ⟨a, rfl⟩ exact ⟨(a, 1), by rw [noncommCoprod_apply, map_one, mul_one]⟩ · rintro - ⟨a, rfl⟩ exact ⟨(1, a), by rw [noncommCoprod_apply, map_one, one_mul]⟩ end group end MonoidHom
Small.lean
/- Copyright (c) 2025 Sophie. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sophie Morel, Antoine Chambert-Loir -/ import Mathlib.Data.Finsupp.ToDFinsupp import Mathlib.Data.DFinsupp.Defs import Mathlib.Logic.Small.Basic /-! # Smallness of the `DFinsupp` type Let `π : ι → Type v`. If `ι` and all the `π i` are `w`-small, this provides a `Small.{w}` instance on `DFinsupp π`. As an application, `σ →₀ R` has a `Small.{v}` instance if `σ` and `R` have one. -/ universe u v w variable {ι : Type u} {π : ι → Type v} [∀ i, Zero (π i)] section Small instance DFinsupp.small [Small.{w} ι] [∀ (i : ι), Small.{w} (π i)] : Small.{w} (DFinsupp π) := small_of_injective (f := fun x j ↦ x j) (fun f f' eq ↦ by ext j; exact congr_fun eq j) instance Finsupp.small {σ : Type*} {R : Type*} [Zero R] [Small.{u} R] [Small.{u} σ] : Small.{u} (σ →₀ R) := by classical exact small_map finsuppEquivDFinsupp end Small
cyclotomic.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 path. From mathcomp Require Import div choice fintype tuple finfun bigop prime. From mathcomp Require Import ssralg poly finset fingroup finalg zmodp cyclic. From mathcomp Require Import ssrnum ssrint archimedean polydiv intdiv mxpoly. From mathcomp Require Import rat vector falgebra fieldext separable galois algC. (******************************************************************************) (* This file provides few basic properties of cyclotomic polynomials. *) (* We define: *) (* cyclotomic z n == the factorization of the nth cyclotomic polynomial in *) (* a ring R in which z is an nth primitive root of unity. *) (* 'Phi_n == the nth cyclotomic polynomial in int. *) (* This library is quite limited, and should be extended in the future. In *) (* particular the irreducibity of 'Phi_n is only stated indirectly, as the *) (* fact that its embedding in the algebraics (algC) is the minimal polynomial *) (* of an nth primitive root of unity. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory Num.Theory. Local Open Scope ring_scope. Section CyclotomicPoly. Section NzRing. Variable R : nzRingType. Definition cyclotomic (z : R) n := \prod_(k < n | coprime k n) ('X - (z ^+ k)%:P). Lemma cyclotomic_monic z n : cyclotomic z n \is monic. Proof. exact: monic_prod_XsubC. Qed. Lemma size_cyclotomic z n : size (cyclotomic z n) = (totient n).+1. Proof. rewrite /cyclotomic -big_filter size_prod_XsubC; congr _.+1. case: big_enumP => _ _ _ [_ ->]. rewrite totient_count_coprime -big_mkcond big_mkord -sum1_card. by apply: eq_bigl => k; rewrite coprime_sym. Qed. End NzRing. Lemma separable_Xn_sub_1 (R : idomainType) n : n%:R != 0 :> R -> @separable_poly R ('X^n - 1). Proof. case: n => [/eqP// | n nz_n]; rewrite unlock linearB /= derivC subr0. rewrite derivXn -scaler_nat coprimepZr //= exprS -scaleN1r coprimep_sym. by rewrite coprimep_addl_mul coprimepZr ?coprimep1 // (signr_eq0 _ 1). Qed. Section Field. Variables (F : fieldType) (n : nat) (z : F). Hypothesis prim_z : n.-primitive_root z. Let n_gt0 := prim_order_gt0 prim_z. Lemma root_cyclotomic x : root (cyclotomic z n) x = n.-primitive_root x. Proof. transitivity (x \in [seq z ^+ i | i : 'I_n in [pred i : 'I_n | coprime i n]]). by rewrite -root_prod_XsubC big_image. apply/imageP/idP=> [[k co_k_n ->] | prim_x]. by rewrite prim_root_exp_coprime. have [k Dx] := prim_rootP prim_z (prim_expr_order prim_x). exists (Ordinal (ltn_pmod k n_gt0)) => /=; last by rewrite prim_expr_mod. by rewrite inE coprime_modl -(prim_root_exp_coprime k prim_z) -Dx. Qed. Lemma prod_cyclotomic : 'X^n - 1 = \prod_(d <- divisors n) cyclotomic (z ^+ (n %/ d)) d. Proof. have in_d d: (d %| n)%N -> val (@inord n d) = d by move/dvdn_leq/inordK=> /= ->. have dv_n k: (n %/ gcdn k n %| n)%N. by rewrite -{3}(divnK (dvdn_gcdr k n)) dvdn_mulr. have [uDn _ inDn] := divisors_correct n_gt0. have defDn: divisors n = map val (map (@inord n) (divisors n)). by rewrite -map_comp map_id_in // => d; rewrite inDn => /in_d. rewrite defDn big_map big_uniq /=; last first. by rewrite -(map_inj_uniq val_inj) -defDn. pose h (k : 'I_n) : 'I_n.+1 := inord (n %/ gcdn k n). rewrite -(factor_Xn_sub_1 prim_z) big_mkord. rewrite (partition_big h (dvdn^~ n)) /= => [|k _]; last by rewrite in_d ?dv_n. apply: eq_big => d; first by rewrite -(mem_map val_inj) -defDn inDn. set q := (n %/ d)%N => d_dv_n. have [q_gt0 d_gt0]: (0 < q /\ 0 < d)%N by apply/andP; rewrite -muln_gt0 divnK. have fP (k : 'I_d): (q * k < n)%N by rewrite divn_mulAC ?ltn_divLR ?ltn_pmul2l. rewrite (reindex (fun k => Ordinal (fP k))); last first. have f'P (k : 'I_n): (k %/ q < d)%N by rewrite ltn_divLR // mulnC divnK. exists (fun k => Ordinal (f'P k)) => [k _ | k /eqnP/=]. by apply: val_inj; rewrite /= mulKn. rewrite in_d // => Dd; apply: val_inj; rewrite /= mulnC divnK // /q -Dd. by rewrite divnA ?mulKn ?dvdn_gcdl ?dvdn_gcdr. apply: eq_big => k; rewrite ?exprM // -val_eqE in_d //=. rewrite -eqn_mul ?dvdn_gcdr ?gcdn_gt0 ?n_gt0 ?orbT //. rewrite -[n in gcdn _ n](divnK d_dv_n) -muln_gcdr mulnCA mulnA divnK //. by rewrite mulnC eqn_mul // divnn n_gt0 eq_sym. Qed. End Field. End CyclotomicPoly. Local Notation ZtoQ := (intr : int -> rat). Local Notation ZtoC := (intr : int -> algC). Local Notation QtoC := (ratr : rat -> algC). Local Notation intrp := (map_poly intr). Local Notation pZtoQ := (map_poly ZtoQ). Local Notation pZtoC := (map_poly ZtoC). Local Notation pQtoC := (map_poly ratr). Local Definition algC_intr_inj := @intr_inj algC. #[local] Hint Resolve algC_intr_inj : core. Local Notation intCK := (@intrKfloor algC). Lemma C_prim_root_exists n : (n > 0)%N -> {z : algC | n.-primitive_root z}. Proof. pose p : {poly algC} := 'X^n - 1; have [r Dp] := closed_field_poly_normal p. move=> n_gt0; apply/sigW; rewrite (monicP _) ?monicXnsubC // scale1r in Dp. have rn1: all n.-unity_root r by apply/allP=> z; rewrite -root_prod_XsubC -Dp. have sz_r: (n < (size r).+1)%N. by rewrite -(size_prod_XsubC r id) -Dp size_XnsubC. have [|z] := hasP (has_prim_root n_gt0 rn1 _ sz_r); last by exists z. by rewrite -separable_prod_XsubC -Dp separable_Xn_sub_1 // pnatr_eq0 -lt0n. Qed. (* (Integral) Cyclotomic polynomials. *) Definition Cyclotomic n : {poly int} := let: exist z _ := C_prim_root_exists (ltn0Sn n.-1) in map_poly Num.floor (cyclotomic z n). Notation "''Phi_' n" := (Cyclotomic n) (at level 8, n at level 2, format "''Phi_' n"). Lemma Cyclotomic_monic n : 'Phi_n \is monic. Proof. rewrite /'Phi_n; case: (C_prim_root_exists _) => z /= _. rewrite monicE lead_coefE coef_map_id0 ?(int_algC_K 0) ?floor0 //. by rewrite size_poly_eq -lead_coefE (monicP (cyclotomic_monic _ _)) (intCK 1). Qed. Lemma Cintr_Cyclotomic n z : n.-primitive_root z -> pZtoC 'Phi_n = cyclotomic z n. Proof. elim/ltn_ind: n z => n IHn z0 prim_z0. rewrite /'Phi_n; case: (C_prim_root_exists _) => z /=. have n_gt0 := prim_order_gt0 prim_z0; rewrite prednK // => prim_z. have [uDn _ inDn] := divisors_correct n_gt0. pose q := \prod_(d <- rem n (divisors n)) 'Phi_d. have mon_q: q \is monic by apply: monic_prod => d _; apply: Cyclotomic_monic. have defXn1: cyclotomic z n * pZtoC q = 'X^n - 1. rewrite (prod_cyclotomic prim_z) (big_rem n) ?inDn //=. rewrite divnn n_gt0 rmorph_prod /=; congr (_ * _). apply: eq_big_seq => d; rewrite mem_rem_uniq ?inE //= inDn => /andP[n'd ddvn]. by rewrite -IHn ?dvdn_prim_root // ltn_neqAle n'd dvdn_leq. have mapXn1 (R1 R2 : nzRingType) (f : {rmorphism R1 -> R2}): map_poly f ('X^n - 1) = 'X^n - 1. - by rewrite rmorphB /= rmorph1 map_polyXn. have nz_q: pZtoC q != 0. by rewrite -size_poly_eq0 size_map_inj_poly // size_poly_eq0 monic_neq0. have [r def_zn]: exists r, cyclotomic z n = pZtoC r. have defZtoC: ZtoC =1 QtoC \o ZtoQ by move=> a; rewrite /= rmorph_int. have /dvdpP[r0 Dr0]: map_poly ZtoQ q %| 'X^n - 1. rewrite -(dvdp_map (@ratr algC)) mapXn1 -map_poly_comp. by rewrite -(eq_map_poly defZtoC) -defXn1 dvdp_mull. have [r [a nz_a Dr]] := rat_poly_scale r0. exists (zprimitive r); apply: (mulIf nz_q); rewrite defXn1. rewrite -rmorphM -(zprimitive_monic mon_q) -zprimitiveM /=. have ->: r * q = a *: ('X^n - 1). apply: (map_inj_poly (intr_inj : injective ZtoQ)) => //. rewrite map_polyZ mapXn1 Dr0 Dr -scalerAl scalerKV ?intr_eq0 //. by rewrite rmorphM. by rewrite zprimitiveZ // zprimitive_monic ?monicXnsubC ?mapXn1. rewrite floorpK; last by apply/polyOverP=> i; rewrite def_zn coef_map /=. pose f e (k : 'I_n) := Ordinal (ltn_pmod (k * e) n_gt0). have [e Dz0] := prim_rootP prim_z (prim_expr_order prim_z0). have co_e_n: coprime e n by rewrite -(prim_root_exp_coprime e prim_z) -Dz0. have injf: injective (f e). apply: can_inj (f (egcdn e n).1) _ => k; apply: val_inj => /=. rewrite modnMml -mulnA -modnMmr -{1}(mul1n e). by rewrite (chinese_modr co_e_n 0) modnMmr muln1 modn_small. rewrite [_ n](reindex_inj injf); apply: eq_big => k /=. by rewrite coprime_modl coprimeMl co_e_n andbT. by rewrite prim_expr_mod // mulnC exprM -Dz0. Qed. Lemma prod_Cyclotomic n : (n > 0)%N -> \prod_(d <- divisors n) 'Phi_d = 'X^n - 1. Proof. move=> n_gt0; have [z prim_z] := C_prim_root_exists n_gt0. apply: (map_inj_poly (intr_inj : injective ZtoC)) => //. rewrite rmorphB rmorph1 rmorph_prod /= map_polyXn (prod_cyclotomic prim_z). apply: eq_big_seq => d; rewrite -dvdn_divisors // => d_dv_n. by rewrite -Cintr_Cyclotomic ?dvdn_prim_root. Qed. Lemma Cyclotomic0 : 'Phi_0 = 1. Proof. rewrite /'Phi_0; case: (C_prim_root_exists _) => z /= _. by rewrite -[1]polyseqK /cyclotomic big_ord0 map_polyE !polyseq1 /= (intCK 1). Qed. Lemma size_Cyclotomic n : size 'Phi_n = (totient n).+1. Proof. have [-> | n_gt0] := posnP n; first by rewrite Cyclotomic0 polyseq1. have [z prim_z] := C_prim_root_exists n_gt0. rewrite -(size_map_inj_poly (can_inj intCK)) //. by rewrite (Cintr_Cyclotomic prim_z) size_cyclotomic. Qed. Lemma minCpoly_cyclotomic n z : n.-primitive_root z -> minCpoly z = cyclotomic z n. Proof. move=> prim_z; have n_gt0 := prim_order_gt0 prim_z. have Dpz := Cintr_Cyclotomic prim_z; set pz := cyclotomic z n in Dpz *. have mon_pz: pz \is monic by apply: cyclotomic_monic. have pz0: root pz z by rewrite root_cyclotomic. have [pf [Dpf mon_pf] dv_pf] := minCpolyP z. have /dvdpP_rat_int[f [af nz_af Df] [g /esym Dfg]]: pf %| pZtoQ 'Phi_n. rewrite -dv_pf; congr (root _ z): pz0; rewrite -Dpz -map_poly_comp. by apply: eq_map_poly => b; rewrite /= rmorph_int. without loss{nz_af} [mon_f mon_g]: af f g Df Dfg / f \is monic /\ g \is monic. move=> IH; pose cf := lead_coef f; pose cg := lead_coef g. have cfg1: cf * cg = 1. by rewrite -lead_coefM Dfg (monicP (Cyclotomic_monic n)). apply: (IH (af *~ cf) (f *~ cg) (g *~ cf)). - by rewrite rmorphMz -scalerMzr scalerMzl -mulrzA cfg1. - by rewrite mulrzAl mulrzAr -mulrzA cfg1. by rewrite !(intz, =^~ scaler_int) !monicE !lead_coefZ mulrC cfg1. have{af} Df: pQtoC pf = pZtoC f. have:= congr1 lead_coef Df. rewrite lead_coefZ lead_coef_map_inj //; last exact: intr_inj. rewrite !(monicP _) // mulr1 Df => <-; rewrite scale1r -map_poly_comp. by apply: eq_map_poly => b; rewrite /= rmorph_int. have [/size1_polyC Dg | g_gt1] := leqP (size g) 1. rewrite monicE Dg lead_coefC in mon_g. by rewrite -Dpz -Dfg Dg (eqP mon_g) mulr1 Dpf. have [zk gzk0]: exists zk, root (pZtoC g) zk. have [rg] := closed_field_poly_normal (pZtoC g). rewrite lead_coef_map_inj // (monicP mon_g) scale1r => Dg. rewrite -(size_map_inj_poly (can_inj intCK)) // Dg in g_gt1. rewrite size_prod_XsubC in g_gt1. by exists rg`_0; rewrite Dg root_prod_XsubC mem_nth. have [k cokn Dzk]: exists2 k, coprime k n & zk = z ^+ k. have: root pz zk by rewrite -Dpz -Dfg rmorphM rootM gzk0 orbT. rewrite -[pz](big_image _ _ _ _ (fun r => 'X - r%:P)) root_prod_XsubC. by case/imageP=> k; exists k. have co_fg (R : idomainType): n%:R != 0 :> R -> @coprimep R (intrp f) (intrp g). move=> nz_n; have: separable_poly (intrp ('X^n - 1) : {poly R}). by rewrite rmorphB rmorph1 /= map_polyXn separable_Xn_sub_1. rewrite -prod_Cyclotomic // (big_rem n) -?dvdn_divisors //= -Dfg. by rewrite !rmorphM /= !separable_mul => /and3P[] /and3P[]. suffices fzk0: root (pZtoC f) zk. have [] // := negP (coprimep_root (co_fg _ _) fzk0). by rewrite pnatr_eq0 -lt0n. move: gzk0 cokn; rewrite {zk}Dzk; elim/ltn_ind: k => k IHk gzk0 cokn. have [|k_gt1] := leqP k 1; last have [p p_pr /dvdnP[k1 Dk]] := pdivP k_gt1. rewrite -[leq k 1](mem_iota 0 2) !inE => /pred2P[k0 | ->]; last first. by rewrite -Df dv_pf. have /eqP := size_Cyclotomic n; rewrite -Dfg size_Mmonic ?monic_neq0 //. rewrite k0 /coprime gcd0n in cokn; rewrite (eqP cokn). rewrite -(size_map_inj_poly (can_inj intCK)) // -Df -Dpf. by rewrite -(subnKC g_gt1) -(subnKC (size_minCpoly z)) !addnS. move: cokn; rewrite Dk coprimeMl => /andP[cok1n]. rewrite prime_coprime // (dvdn_pcharf (pchar_Fp p_pr)) => /co_fg {co_fg}. have pcharFpX: p \in [pchar {poly 'F_p}] by rewrite (rmorph_pchar polyC) ?pchar_Fp. rewrite -(coprimep_pexpr _ _ (prime_gt0 p_pr)) -(pFrobenius_autE pcharFpX). rewrite -[g]comp_polyXr map_comp_poly -horner_map /= pFrobenius_autE -rmorphXn. rewrite -!map_poly_comp (@eq_map_poly _ _ _ (polyC \o *~%R 1)); last first. by move=> a; rewrite /= !rmorph_int. rewrite map_poly_comp -[_.[_]]map_comp_poly /= => co_fg. suffices: coprimep (pZtoC f) (pZtoC (g \Po 'X^p)). move/coprimep_root=> /=/(_ (z ^+ k1))/implyP. rewrite map_comp_poly map_polyXn horner_comp hornerXn. rewrite -exprM -Dk [_ == 0]gzk0 implybF => /negP[]. have: root pz (z ^+ k1). by rewrite root_cyclotomic // prim_root_exp_coprime. rewrite -Dpz -Dfg rmorphM rootM => /orP[] //= /IHk-> //. rewrite -[k1]muln1 Dk ltn_pmul2l ?prime_gt1 //. by have:= ltnW k_gt1; rewrite Dk muln_gt0 => /andP[]. suffices: coprimep f (g \Po 'X^p). case/Bezout_coprimepP=> [[u v]]; rewrite -size_poly_eq1. rewrite -(size_map_inj_poly (can_inj intCK)) // rmorphD !rmorphM /=. rewrite size_poly_eq1 => {}co_fg; apply/Bezout_coprimepP. by exists (pZtoC u, pZtoC v). apply: contraLR co_fg => /coprimepPn[|d]; first exact: monic_neq0. rewrite andbC -size_poly_eq1 dvdp_gcd => /and3P[sz_d]. pose d1 := zprimitive d. have d_dv_mon h: d %| h -> h \is monic -> exists h1, h = d1 * h1. case/Pdiv.Idomain.dvdpP=> [[c h1] /= nz_c Dh] mon_h; exists (zprimitive h1). by rewrite -zprimitiveM mulrC -Dh zprimitiveZ ?zprimitive_monic. case/d_dv_mon=> // f1 Df1 /d_dv_mon[|f2 ->]. rewrite monicE lead_coefE size_comp_poly size_polyXn /=. rewrite comp_polyE coef_sum polySpred ?monic_neq0 //= mulnC. rewrite big_ord_recr /= -lead_coefE (monicP mon_g) scale1r. rewrite -exprM coefXn eqxx big1 ?add0r // => i _. rewrite coefZ -exprM coefXn eqn_pmul2l ?prime_gt0 //. by rewrite eqn_leq leqNgt ltn_ord mulr0. have monFp h: h \is monic -> size (map_poly intr h) = size h. by move=> mon_h; rewrite size_poly_eq // -lead_coefE (monicP mon_h) oner_eq0. apply/coprimepPn; last exists (map_poly intr d1). by rewrite -size_poly_eq0 monFp // size_poly_eq0 monic_neq0. rewrite Df1 !rmorphM dvdp_gcd !dvdp_mulr //= -size_poly_eq1. rewrite monFp ?size_zprimitive //. rewrite monicE [_ d1]intEsg sgz_lead_primitive -zprimitive_eq0 -/d1. rewrite -lead_coef_eq0 -absz_eq0. have/esym/eqP := congr1 (absz \o lead_coef) Df1. by rewrite /= (monicP mon_f) lead_coefM abszM muln_eq1 => /andP[/eqP-> _]. Qed.
FunctorN.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.PInfty /-! # Construction of functors N for the Dold-Kan correspondence In this file, we construct functors `N₁ : SimplicialObject C ⥤ Karoubi (ChainComplex C ℕ)` and `N₂ : Karoubi (SimplicialObject C) ⥤ Karoubi (ChainComplex C ℕ)` for any preadditive category `C`. (The indices of these functors are the number of occurrences of `Karoubi` at the source or the target.) In the case `C` is additive, the functor `N₂` shall be the functor of the equivalence `CategoryTheory.Preadditive.DoldKan.equivalence` defined in `EquivalenceAdditive.lean`. In the case the category `C` is pseudoabelian, the composition of `N₁` with the inverse of the equivalence `ChainComplex C ℕ ⥤ Karoubi (ChainComplex C ℕ)` will be the functor `CategoryTheory.Idempotents.DoldKan.N` of the equivalence of categories `CategoryTheory.Idempotents.DoldKan.equivalence : SimplicialObject C ≌ ChainComplex C ℕ` defined in `EquivalencePseudoabelian.lean`. When the category `C` is abelian, a relation between `N₁` and the normalized Moore complex functor shall be obtained in `Normalized.lean`. (See `Equivalence.lean` for the general strategy of proof of the Dold-Kan equivalence.) -/ open CategoryTheory CategoryTheory.Category CategoryTheory.Idempotents noncomputable section namespace AlgebraicTopology namespace DoldKan variable {C : Type*} [Category C] [Preadditive C] /-- The functor `SimplicialObject C ⥤ Karoubi (ChainComplex C ℕ)` which maps `X` to the formal direct factor of `K[X]` defined by `PInfty`. -/ @[simps] def N₁ : SimplicialObject C ⥤ Karoubi (ChainComplex C ℕ) where obj X := { X := AlternatingFaceMapComplex.obj X p := PInfty idem := PInfty_idem } map f := { f := PInfty ≫ AlternatingFaceMapComplex.map f } /-- The extension of `N₁` to the Karoubi envelope of `SimplicialObject C`. -/ @[simps!] def N₂ : Karoubi (SimplicialObject C) ⥤ Karoubi (ChainComplex C ℕ) := (functorExtension₁ _ _).obj N₁ /-- The canonical isomorphism `toKaroubi (SimplicialObject C) ⋙ N₂ ≅ N₁`. -/ def toKaroubiCompN₂IsoN₁ : toKaroubi (SimplicialObject C) ⋙ N₂ ≅ N₁ := (functorExtension₁CompWhiskeringLeftToKaroubiIso _ _).app N₁ @[simp] lemma toKaroubiCompN₂IsoN₁_hom_app (X : SimplicialObject C) : (toKaroubiCompN₂IsoN₁.hom.app X).f = PInfty := rfl @[simp] lemma toKaroubiCompN₂IsoN₁_inv_app (X : SimplicialObject C) : (toKaroubiCompN₂IsoN₁.inv.app X).f = PInfty := rfl end DoldKan end AlgebraicTopology
zmodp.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 choice eqtype ssrnat seq. From mathcomp Require Import div fintype bigop finset prime fingroup perm. From mathcomp Require Import ssralg finalg countalg. (******************************************************************************) (* Definition of the additive group and ring Zp, represented as 'I_p *) (******************************************************************************) (* Definitions: *) (* From fintype.v: *) (* 'I_p == the subtype of integers less than p, taken here as the type of *) (* the integers mod p. *) (* This file: *) (* inZp == the natural projection from nat into the integers mod p, *) (* represented as 'I_p. Here p is implicit, but MUST be of the *) (* form n.+1. *) (* The operations: *) (* Zp0 == the identity element for addition *) (* Zp1 == the identity element for multiplication, and a generator of *) (* additive group *) (* Zp_opp == inverse function for addition *) (* Zp_add == addition *) (* Zp_mul == multiplication *) (* Zp_inv == inverse function for multiplication *) (* Note that while 'I_n.+1 has canonical finZmodType and finGroupType *) (* structures, only 'I_n.+2 has a canonical ring structure (it has, in fact, *) (* a canonical finComUnitRing structure), and hence an associated *) (* multiplicative unit finGroupType. To mitigate the issues caused by the *) (* trivial "ring" (which is, indeed is NOT a ring in the ssralg/finalg *) (* formalization), we define additional notation: *) (* 'Z_p == the type of integers mod (max p 2); this is always a proper *) (* ring, by constructions. Note that 'Z_p is provably equal to *) (* 'I_p if p > 1, and convertible to 'I_p if p is of the form *) (* n.+2. *) (* Zp p == the subgroup of integers mod (max p 1) in 'Z_p; this is thus *) (* all of 'Z_p if p > 1, and else the trivial group. *) (* units_Zp p == the group of all units of 'Z_p -- i.e., the group of *) (* (multiplicative) automorphisms of Zp p. *) (* We show that Zp and units_Zp are abelian, and compute their orders. *) (* We use a similar technique to represent the prime fields: *) (* 'F_p == the finite field of integers mod the first prime divisor of *) (* maxn p 2. This is provably equal to 'Z_p and 'I_p if p is *) (* provably prime, and indeed convertible to the above if p is *) (* a concrete prime such as 2, 5 or 23. *) (* Note finally that due to the canonical structures it is possible to use *) (* 0%R instead of Zp0, and 1%R instead of Zp1 (for the latter, p must be of *) (* the form n.+2, and 1%R : nat will simplify to 1%N). *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope ring_scope. Section ZpDef. (***********************************************************************) (* *) (* Mod p arithmetic on the finite set {0, 1, 2, ..., p - 1} *) (* *) (***********************************************************************) (* Operations on 'I_p without constraint on p. *) Section Generic. Variable p : nat. Implicit Types i j : 'I_p. Lemma Zp_opp_subproof i : (p - i) %% p < p. Proof. by case: p i => [[]//|k] i; apply/ltn_pmod. Qed. Definition Zp_opp i := Ordinal (Zp_opp_subproof i). Lemma Zp_add_subproof i j : (i + j) %% p < p. Proof. by case: p i j => [[]//|k] i j; apply/ltn_pmod. Qed. Definition Zp_add i j := Ordinal (Zp_add_subproof i j). Lemma Zp_mul_subproof i j : (i * j) %% p < p. Proof. by case: p i j => [[]//|k] i j; apply/ltn_pmod. Qed. Definition Zp_mul i j := Ordinal (Zp_mul_subproof i j). Lemma Zp_inv_subproof i : (egcdn i p).1 %% p < p. Proof. by case: p i => [[]//|k] i; apply/ltn_pmod. Qed. Definition Zp_inv i := if coprime p i then Ordinal (Zp_inv_subproof i) else i. Lemma Zp_addA : associative Zp_add. Proof. by move=> x y z; apply: val_inj; rewrite /= modnDml modnDmr addnA. Qed. Lemma Zp_addC : commutative Zp_add. Proof. by move=> x y; apply: val_inj; rewrite /= addnC. Qed. Lemma Zp_mulC : commutative Zp_mul. Proof. by move=> x y; apply: val_inj; rewrite /= mulnC. Qed. Lemma Zp_mulA : associative Zp_mul. Proof. by move=> x y z; apply: val_inj; rewrite /= modnMml modnMmr mulnA. Qed. Lemma Zp_mul_addr : right_distributive Zp_mul Zp_add. Proof. by move=> x y z; apply: val_inj; rewrite /= modnMmr modnDm mulnDr. Qed. Lemma Zp_mul_addl : left_distributive Zp_mul Zp_add. Proof. by move=> x y z; rewrite -!(Zp_mulC z) Zp_mul_addr. Qed. Lemma Zp_inv_out i : ~~ coprime p i -> Zp_inv i = i. Proof. by rewrite /Zp_inv => /negPf->. Qed. End Generic. Arguments Zp_opp {p}. Arguments Zp_add {p}. Arguments Zp_mul {p}. Arguments Zp_inv {p}. Variable p' : nat. Local Notation p := p'.+1. Implicit Types x y z : 'I_p. (* Standard injection; val (inZp i) = i %% p *) Definition inZp i := Ordinal (ltn_pmod i (ltn0Sn p')). Lemma modZp x : x %% p = x. Proof. by rewrite modn_small ?ltn_ord. Qed. Lemma valZpK x : inZp x = x. Proof. by apply: val_inj; rewrite /= modZp. Qed. (* Operations *) Definition Zp0 : 'I_p := ord0. Definition Zp1 := inZp 1. (* Additive group structure. *) Lemma Zp_add0z : left_id Zp0 Zp_add. Proof. by move=> x; apply: val_inj; rewrite /= modZp. Qed. Lemma Zp_addNz : left_inverse Zp0 Zp_opp Zp_add. Proof. by move=> x; apply: val_inj; rewrite /= modnDml subnK ?modnn // ltnW. Qed. HB.instance Definition _ := GRing.isZmodule.Build 'I_p (@Zp_addA _) (@Zp_addC _) Zp_add0z Zp_addNz. HB.instance Definition _ := [finGroupMixin of 'I_p for +%R]. (* Ring operations *) Lemma Zp_mul1z : left_id Zp1 Zp_mul. Proof. by move=> x; apply: val_inj; rewrite /= modnMml mul1n modZp. Qed. Lemma Zp_mulz1 : right_id Zp1 Zp_mul. Proof. by move=> x; rewrite Zp_mulC Zp_mul1z. Qed. Lemma Zp_mulVz x : coprime p x -> Zp_mul (Zp_inv x) x = Zp1. Proof. move=> co_p_x; apply: val_inj; rewrite /Zp_inv co_p_x /= modnMml. by rewrite -(chinese_modl co_p_x 1 0) /chinese addn0 mul1n mulnC. Qed. Lemma Zp_mulzV x : coprime p x -> Zp_mul x (Zp_inv x) = Zp1. Proof. by move=> Ux; rewrite /= Zp_mulC Zp_mulVz. Qed. Lemma Zp_intro_unit x y : Zp_mul y x = Zp1 -> coprime p x. Proof. case=> yx1; have:= coprimen1 p. by rewrite -coprime_modr -yx1 coprime_modr coprimeMr; case/andP. Qed. Lemma Zp_mulrn x n : x *+ n = inZp (x * n). Proof. apply: val_inj => /=; elim: n => [|n IHn]; first by rewrite muln0 modn_small. by rewrite !GRing.mulrS /= IHn modnDmr mulnS. Qed. Import GroupScope. Lemma Zp_mulgC : @commutative 'I_p _ mulg. Proof. exact: Zp_addC. Qed. Lemma Zp_abelian : abelian [set: 'I_p]. Proof. exact: FinRing.zmod_abelian. Qed. Lemma Zp_expg x n : x ^+ n = inZp (x * n). Proof. exact: Zp_mulrn. Qed. Lemma Zp1_expgz x : Zp1 ^+ x = x. Proof. rewrite Zp_expg; apply/val_inj. by move: (Zp_mul1z x) => /(congr1 val). Qed. Lemma Zp_cycle : setT = <[Zp1]>. Proof. by apply/setP=> x; rewrite -[x]Zp1_expgz inE groupX ?mem_gen ?set11. Qed. Lemma order_Zp1 : #[Zp1] = p. Proof. by rewrite orderE -Zp_cycle cardsT card_ord. Qed. End ZpDef. Arguments Zp0 {p'}. Arguments Zp1 {p'}. Arguments inZp {p'} i. Arguments valZpK {p'} x. (* We redefine fintype.ord1 to specialize it with 0 instead of ord0 *) (* since 'I_n is now canonically a zmodType *) Lemma ord1 : all_equal_to (0 : 'I_1). Proof. exact: ord1. Qed. Lemma lshift0 m n : lshift m (0 : 'I_n.+1) = (0 : 'I_(n + m).+1). Proof. exact: val_inj. Qed. Lemma rshift1 n : @rshift 1 n =1 lift (0 : 'I_n.+1). Proof. by move=> i; apply: val_inj. Qed. Lemma split1 n i : split (i : 'I_(1 + n)) = oapp (@inr _ _) (inl _ 0) (unlift 0 i). Proof. case: unliftP => [i'|] -> /=. by rewrite -rshift1 (unsplitK (inr _ _)). by rewrite -(lshift0 n 0) (unsplitK (inl _ _)). Qed. (* TODO: bigop is imported after zmodp in matrix.v and intdiv.v to prevent these warnings from triggering. We should restore the order of imports when these are removed. *) #[deprecated(since="mathcomp 2.3.0", note="Use bigop.big_ord1 instead.")] Notation big_ord1 := big_ord1 (only parsing). #[deprecated(since="mathcomp 2.3.0", note="Use bigop.big_ord1_cond instead.")] Notation big_ord1_cond := big_ord1_cond (only parsing). Section ZpNzRing. Variable p' : nat. Local Notation p := p'.+2. Lemma Zp_nontrivial : Zp1 != 0 :> 'I_p. Proof. by []. Qed. HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build 'I_p (@Zp_mulA _) (@Zp_mulC _) (@Zp_mul1z _) (@Zp_mul_addl _) Zp_nontrivial. HB.instance Definition _ := GRing.ComNzRing_hasMulInverse.Build 'I_p (@Zp_mulVz _) (@Zp_intro_unit _) (@Zp_inv_out _). Lemma Zp_nat n : n%:R = inZp n :> 'I_p. Proof. by apply: val_inj; rewrite [n%:R]Zp_mulrn /= modnMml mul1n. Qed. Lemma natr_Zp (x : 'I_p) : x%:R = x. Proof. by rewrite Zp_nat valZpK. Qed. Lemma natr_negZp (x : 'I_p) : (- x)%:R = - x. Proof. by apply: val_inj; rewrite /= Zp_nat /= modn_mod. Qed. Import GroupScope. Lemma unit_Zp_mulgC : @commutative {unit 'I_p} _ mulg. Proof. by move=> u v; apply: val_inj; rewrite /= GRing.mulrC. Qed. Lemma unit_Zp_expg (u : {unit 'I_p}) n : val (u ^+ n) = inZp (val u ^ n) :> 'I_p. Proof. apply: val_inj => /=; elim: n => [|n IHn] //. by rewrite expgS /= IHn expnS modnMmr. Qed. End ZpNzRing. Definition Zp_trunc p := p.-2. Notation "''Z_' p" := 'I_(Zp_trunc p).+2 (at level 0, p at level 2, format "''Z_' p") : type_scope. Notation "''F_' p" := 'Z_(pdiv p) (at level 0, p at level 2, format "''F_' p") : type_scope. Arguments natr_Zp {p'} x. Section ZpNzRing. Import GRing.Theory. Lemma add_1_Zp p (x : 'Z_p) : 1 + x = ordS x. Proof. by case: p => [|[|p]] in x *; apply/val_inj. Qed. Lemma add_Zp_1 p (x : 'Z_p) : x + 1 = ordS x. Proof. by rewrite addrC add_1_Zp. Qed. Lemma sub_Zp_1 p (x : 'Z_p) : x - 1 = ord_pred x. Proof. by apply: (addIr 1); rewrite addrNK add_Zp_1 ord_predK. Qed. Lemma add_N1_Zp p (x : 'Z_p) : -1 + x = ord_pred x. Proof. by rewrite addrC sub_Zp_1. Qed. End ZpNzRing. Section Groups. Variable p : nat. Definition Zp := if p > 1 then [set: 'Z_p] else 1%g. Definition units_Zp := [set: {unit 'Z_p}]. Lemma Zp_cast : p > 1 -> (Zp_trunc p).+2 = p. Proof. by case: p => [|[]]. Qed. Lemma val_Zp_nat (p_gt1 : p > 1) n : (n%:R : 'Z_p) = (n %% p)%N :> nat. Proof. by rewrite Zp_nat /= Zp_cast. Qed. Lemma Zp_nat_mod (p_gt1 : p > 1)m : (m %% p)%:R = m%:R :> 'Z_p. Proof. by apply: ord_inj; rewrite !val_Zp_nat // modn_mod. Qed. Lemma pchar_Zp : p > 1 -> p%:R = 0 :> 'Z_p. Proof. by move=> p_gt1; rewrite -Zp_nat_mod ?modnn. Qed. Lemma unitZpE x : p > 1 -> ((x%:R : 'Z_p) \is a GRing.unit) = coprime p x. Proof. move=> p_gt1; rewrite qualifE /=. by rewrite val_Zp_nat ?Zp_cast ?coprime_modr. Qed. Lemma Zp_group_set : group_set Zp. Proof. by rewrite /Zp; case: (p > 1); apply: groupP. Qed. (* FIX ME : is this ok something similar is done in fingroup *) Canonical Zp_group := Group Zp_group_set. Lemma card_Zp : p > 0 -> #|Zp| = p. Proof. rewrite /Zp; case: p => [|[|p']] //= _; first by rewrite cards1. by rewrite cardsT card_ord. Qed. Lemma mem_Zp x : p > 1 -> x \in Zp. Proof. by rewrite /Zp => ->. Qed. Canonical units_Zp_group := [group of units_Zp]. Lemma card_units_Zp : p > 0 -> #|units_Zp| = totient p. Proof. move=> p_gt0; transitivity (totient p.-2.+2); last by case: p p_gt0 => [|[|p']]. rewrite cardsT card_sub -sum1_card big_mkcond /=. by rewrite totient_count_coprime big_mkord. Qed. Lemma units_Zp_abelian : abelian units_Zp. Proof. by apply/centsP=> u _ v _; apply: unit_Zp_mulgC. Qed. End Groups. #[deprecated(since="mathcomp 2.4.0", note="Use pchar_Zp instead.")] Notation char_Zp := (pchar_Zp) (only parsing). (* Field structure for primes. *) Section PrimeField. Open Scope ring_scope. Variable p : nat. Section F_prime. Hypothesis p_pr : prime p. Lemma Fp_Zcast : Zp_trunc (pdiv p) = Zp_trunc p. Proof. by rewrite /pdiv primes_prime. Qed. Lemma Fp_cast : (Zp_trunc (pdiv p)).+2 = p. Proof. by rewrite Fp_Zcast ?Zp_cast ?prime_gt1. Qed. Lemma card_Fp : #|'F_p| = p. Proof. by rewrite card_ord Fp_cast. Qed. Lemma val_Fp_nat n : (n%:R : 'F_p) = (n %% p)%N :> nat. Proof. by rewrite Zp_nat /= Fp_cast. Qed. Lemma Fp_nat_mod m : (m %% p)%:R = m%:R :> 'F_p. Proof. by apply: ord_inj; rewrite !val_Fp_nat // modn_mod. Qed. Lemma pchar_Fp : p \in [pchar 'F_p]. Proof. by rewrite !inE -Fp_nat_mod p_pr ?modnn. Qed. Lemma pchar_Fp_0 : p%:R = 0 :> 'F_p. Proof. exact: GRing.pcharf0 pchar_Fp. Qed. Lemma unitFpE x : ((x%:R : 'F_p) \is a GRing.unit) = coprime p x. Proof. by rewrite pdiv_id // unitZpE // prime_gt1. Qed. End F_prime. Lemma Fp_fieldMixin : GRing.ComUnitRing_isField 'F_p. Proof. constructor => x nzx. rewrite qualifE /= prime_coprime ?gtnNdvd ?lt0n //. case: (ltnP 1 p) => [lt1p | ]; last by case: p => [|[|p']]. by rewrite Zp_cast ?prime_gt1 ?pdiv_prime. Qed. HB.instance Definition _ := Fp_fieldMixin. HB.instance Definition _ := FinRing.isField.Build 'F_p. End PrimeField. Section Sym. Import GRing. Lemma gen_tperm_step n (k : 'I_n.+1) : coprime n.+1 k -> <<[set tperm i (i + k) | i : 'I_n.+1]>>%g = [set: 'S_n.+1]. Proof. case: n k => [|n] k. move=> _; apply/eqP; rewrite eqEsubset subsetT/= -(gen_tperm 0)/= gen_subG. apply/subsetP => s /imsetP[/= [][|//] lt01 _ ->]. have ->: (Ordinal lt01) = 0 by apply/val_inj. by rewrite tperm1 group1. rewrite -unitZpE// natr_Zp => k_unit. apply/eqP; rewrite eqEsubset subsetT/= -(gen_tperm 0)/= gen_subG. apply/subsetP => s /imsetP[/= i _ ->]. rewrite -[i](mulVKr k_unit) -[_ * i]natr_Zp mulr_natr. elim: (val _) => //= {i} [|[|i] IHi]; first by rewrite tperm1 group1. by rewrite mulrSr mem_gen//; apply/imsetP; exists 0. have [->|kS2N0] := eqVneq (k *+ i.+2) 0; first by rewrite tperm1 group1. have kSSneqkS : k *+ i.+2 != k *+ i.+1. rewrite -subr_eq0 -mulrnBr// subSnn mulr1n. by apply: contraTneq k_unit => ->; rewrite unitr0. rewrite -(@tpermJ_tperm _ (k *+ i.+1)) 1?eq_sym//. rewrite groupJ// 1?tpermC// mulrSr 1?tpermC. by rewrite mem_gen//; apply/imsetP; exists (k *+ i.+1). Qed. Lemma perm_addr1X n m (j k : 'I_n.+1) : (perm (addrI m%R) ^+ j)%g k = m *+ j + k. Proof. by rewrite permX (eq_iter (permE _)) iter_addr. Qed. Lemma gen_tpermn_circular_shift n (i j : 'I_n.+2) (c := perm (addrI 1)) : coprime n.+2 (j - i)%R -> <<[set tperm i j ; c]>>%g = [set: 'S_n.+2]. Proof. move=> jBi_coprime; apply/eqP; rewrite eqEsubset subsetT/=. rewrite -(gen_tperm_step jBi_coprime) gen_subG. apply/subsetP => s /imsetP[/= k _ ->]. suff -> : tperm k (k + (j - i)) = (tperm i j ^ c ^+ (k - i)%R)%g. by rewrite groupJ ?groupX ?mem_gen ?inE ?eqxx ?orbT. by rewrite tpermJ !perm_addr1X natr_Zp addrNK addrAC addrA. Qed. End Sym. #[deprecated(since="mathcomp 2.4.0", note="Use pchar_Fp instead.")] Notation char_Fp := (pchar_Fp) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pchar_Fp_0 instead.")] Notation char_Fp_0 := (pchar_Fp_0) (only parsing).
TopologicalAbelianization.lean
/- Copyright (c) 2023 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández -/ import Mathlib.GroupTheory.Commutator.Basic import Mathlib.Tactic.Group import Mathlib.Topology.Algebra.Group.Basic /-! # The topological abelianization of a group. This file defines the topological abelianization of a topological group. ## Main definitions * `TopologicalAbelianization`: defines the topological abelianization of a group `G` as the quotient of `G` by the topological closure of its commutator subgroup.. ## Main results - `instNormalCommutatorClosure` : the topological closure of the commutator of a topological group `G` is a normal subgroup. ## Tags group, topological abelianization -/ variable (G : Type*) [Group G] [TopologicalSpace G] [IsTopologicalGroup G] instance instNormalCommutatorClosure : (commutator G).topologicalClosure.Normal := Subgroup.is_normal_topologicalClosure (commutator G) /-- The topological abelianization of `absoluteGaloisGroup`, that is, the quotient of `absoluteGaloisGroup` by the topological closure of its commutator subgroup. -/ abbrev TopologicalAbelianization := G ⧸ Subgroup.topologicalClosure (commutator G) local notation "G_ab" => TopologicalAbelianization namespace TopologicalAbelianization instance commGroup : CommGroup (G_ab G) where mul_comm := fun x y => Quotient.inductionOn₂' x y fun a b => Quotient.sound' <| QuotientGroup.leftRel_apply.mpr <| by have h : (a * b)⁻¹ * (b * a) = ⁅b⁻¹, a⁻¹⁆ := by group rw [h] exact Subgroup.le_topologicalClosure _ (Subgroup.commutator_mem_commutator (Subgroup.mem_top b⁻¹) (Subgroup.mem_top a⁻¹)) __ : Group (G_ab G) := inferInstance end TopologicalAbelianization
Iterate.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.Logic.Function.Conjugate /-! # Iterations of a function In this file we prove simple properties of `Nat.iterate f n` a.k.a. `f^[n]`: * `iterate_zero`, `iterate_succ`, `iterate_succ'`, `iterate_add`, `iterate_mul`: formulas for `f^[0]`, `f^[n+1]` (two versions), `f^[n+m]`, and `f^[n*m]`; * `iterate_id` : `id^[n]=id`; * `Injective.iterate`, `Surjective.iterate`, `Bijective.iterate` : iterates of an injective/surjective/bijective function belong to the same class; * `LeftInverse.iterate`, `RightInverse.iterate`, `Commute.iterate_left`, `Commute.iterate_right`, `Commute.iterate_iterate`: some properties of pairs of functions survive under iterations * `iterate_fixed`, `Function.Semiconj.iterate_*`, `Function.Semiconj₂.iterate`: if `f` fixes a point (resp., semiconjugates unary/binary operations), then so does `f^[n]`. -/ universe u v variable {α : Type u} {β : Type v} /-- Iterate a function. -/ def Nat.iterate {α : Sort u} (op : α → α) : ℕ → α → α | 0, a => a | succ k, a => iterate op k (op a) @[inherit_doc Nat.iterate] notation:max f "^["n"]" => Nat.iterate f n namespace Function open Function (Commute) variable (f : α → α) @[simp] theorem iterate_zero : f^[0] = id := rfl theorem iterate_zero_apply (x : α) : f^[0] x = x := rfl @[simp] theorem iterate_succ (n : ℕ) : f^[n.succ] = f^[n] ∘ f := rfl theorem iterate_succ_apply (n : ℕ) (x : α) : f^[n.succ] x = f^[n] (f x) := rfl @[simp] theorem iterate_id (n : ℕ) : (id : α → α)^[n] = id := Nat.recOn n rfl fun n ihn ↦ by rw [iterate_succ, ihn, id_comp] theorem iterate_add (m : ℕ) : ∀ n : ℕ, f^[m + n] = f^[m] ∘ f^[n] | 0 => rfl | Nat.succ n => by rw [Nat.add_succ, iterate_succ, iterate_succ, iterate_add m n]; rfl theorem iterate_add_apply (m n : ℕ) (x : α) : f^[m + n] x = f^[m] (f^[n] x) := by rw [iterate_add f m n] rfl -- can be proved by simp but this is shorter and more natural @[simp high] theorem iterate_one : f^[1] = f := funext fun _ ↦ rfl theorem iterate_mul (m : ℕ) : ∀ n, f^[m * n] = f^[m]^[n] | 0 => by simp only [Nat.mul_zero, iterate_zero] | n + 1 => by simp only [Nat.mul_succ, iterate_one, iterate_add, iterate_mul m n] variable {f} theorem iterate_fixed {x} (h : f x = x) (n : ℕ) : f^[n] x = x := Nat.recOn n rfl fun n ihn ↦ by rw [iterate_succ_apply, h, ihn] /-- If a function `g` is invariant under composition with a function `f` (i.e., `g ∘ f = g`), then `g` is invariant under composition with any iterate of `f`. -/ theorem iterate_invariant {g : α → β} (h : g ∘ f = g) (n : ℕ) : g ∘ f^[n] = g := match n with | 0 => by rw [iterate_zero, comp_id] | m + 1 => by rwa [iterate_succ, ← comp_assoc, iterate_invariant h m] theorem Injective.iterate (Hinj : Injective f) (n : ℕ) : Injective f^[n] := Nat.recOn n injective_id fun _ ihn ↦ ihn.comp Hinj theorem Surjective.iterate (Hsurj : Surjective f) (n : ℕ) : Surjective f^[n] := Nat.recOn n surjective_id fun _ ihn ↦ ihn.comp Hsurj theorem Bijective.iterate (Hbij : Bijective f) (n : ℕ) : Bijective f^[n] := ⟨Hbij.1.iterate n, Hbij.2.iterate n⟩ namespace Semiconj theorem iterate_right {f : α → β} {ga : α → α} {gb : β → β} (h : Semiconj f ga gb) (n : ℕ) : Semiconj f ga^[n] gb^[n] := Nat.recOn n id_right fun _ ihn ↦ ihn.comp_right h theorem iterate_left {g : ℕ → α → α} (H : ∀ n, Semiconj f (g n) (g <| n + 1)) (n k : ℕ) : Semiconj f^[n] (g k) (g <| n + k) := by induction n generalizing k with | zero => rw [Nat.zero_add] exact id_left | succ n ihn => rw [Nat.add_right_comm, Nat.add_assoc] exact (H k).trans (ihn (k + 1)) end Semiconj namespace Commute variable {g : α → α} theorem iterate_right (h : Commute f g) (n : ℕ) : Commute f g^[n] := Semiconj.iterate_right h n theorem iterate_left (h : Commute f g) (n : ℕ) : Commute f^[n] g := (h.symm.iterate_right n).symm theorem iterate_iterate (h : Commute f g) (m n : ℕ) : Commute f^[m] g^[n] := (h.iterate_left m).iterate_right n theorem iterate_eq_of_map_eq (h : Commute f g) (n : ℕ) {x} (hx : f x = g x) : f^[n] x = g^[n] x := Nat.recOn n rfl fun n ihn ↦ by simp only [iterate_succ_apply, hx, (h.iterate_left n).eq, ihn, ((refl g).iterate_right n).eq] theorem comp_iterate (h : Commute f g) (n : ℕ) : (f ∘ g)^[n] = f^[n] ∘ g^[n] := by induction n with | zero => rfl | succ n ihn => funext x simp only [ihn, (h.iterate_right n).eq, iterate_succ, comp_apply] variable (f) theorem iterate_self (n : ℕ) : Commute f^[n] f := (refl f).iterate_left n theorem self_iterate (n : ℕ) : Commute f f^[n] := (refl f).iterate_right n theorem iterate_iterate_self (m n : ℕ) : Commute f^[m] f^[n] := (refl f).iterate_iterate m n end Commute theorem Semiconj₂.iterate {f : α → α} {op : α → α → α} (hf : Semiconj₂ f op op) (n : ℕ) : Semiconj₂ f^[n] op op := Nat.recOn n (Semiconj₂.id_left op) fun _ ihn ↦ ihn.comp hf variable (f) theorem iterate_succ' (n : ℕ) : f^[n.succ] = f ∘ f^[n] := by rw [iterate_succ, (Commute.self_iterate f n).comp_eq] theorem iterate_succ_apply' (n : ℕ) (x : α) : f^[n.succ] x = f (f^[n] x) := by rw [iterate_succ'] rfl theorem iterate_pred_comp_of_pos {n : ℕ} (hn : 0 < n) : f^[n.pred] ∘ f = f^[n] := by rw [← iterate_succ, Nat.succ_pred_eq_of_pos hn] theorem comp_iterate_pred_of_pos {n : ℕ} (hn : 0 < n) : f ∘ f^[n.pred] = f^[n] := by rw [← iterate_succ', Nat.succ_pred_eq_of_pos hn] /-- A recursor for the iterate of a function. -/ def Iterate.rec (p : α → Sort*) {f : α → α} (h : ∀ a, p a → p (f a)) {a : α} (ha : p a) (n : ℕ) : p (f^[n] a) := match n with | 0 => ha | m+1 => Iterate.rec p h (h _ ha) m theorem Iterate.rec_zero (p : α → Sort*) {f : α → α} (h : ∀ a, p a → p (f a)) {a : α} (ha : p a) : Iterate.rec p h ha 0 = ha := rfl variable {f} {m n : ℕ} {a : α} theorem LeftInverse.iterate {g : α → α} (hg : LeftInverse g f) (n : ℕ) : LeftInverse g^[n] f^[n] := Nat.recOn n (fun _ ↦ rfl) fun n ihn ↦ by rw [iterate_succ', iterate_succ] exact ihn.comp hg theorem RightInverse.iterate {g : α → α} (hg : RightInverse g f) (n : ℕ) : RightInverse g^[n] f^[n] := LeftInverse.iterate hg n theorem iterate_comm (f : α → α) (m n : ℕ) : f^[n]^[m] = f^[m]^[n] := (iterate_mul _ _ _).symm.trans (Eq.trans (by rw [Nat.mul_comm]) (iterate_mul _ _ _)) theorem iterate_commute (m n : ℕ) : Commute (fun f : α → α ↦ f^[m]) fun f ↦ f^[n] := fun f ↦ iterate_comm f m n lemma iterate_add_eq_iterate (hf : Injective f) : f^[m + n] a = f^[n] a ↔ f^[m] a = a := Iff.trans (by rw [← iterate_add_apply, Nat.add_comm]) (hf.iterate n).eq_iff alias ⟨iterate_cancel_of_add, _⟩ := iterate_add_eq_iterate lemma iterate_cancel (hf : Injective f) (ha : f^[m] a = f^[n] a) : f^[m - n] a = a := by obtain h | h := Nat.le_total m n { simp [Nat.sub_eq_zero_of_le h] } { exact iterate_cancel_of_add hf (by rwa [Nat.sub_add_cancel h]) } theorem involutive_iff_iter_2_eq_id {α} {f : α → α} : Involutive f ↔ f^[2] = id := funext_iff.symm end Function namespace List open Function theorem foldl_const (f : α → α) (a : α) (l : List β) : l.foldl (fun b _ ↦ f b) a = f^[l.length] a := by induction l generalizing a with | nil => rfl | cons b l H => rw [length_cons, foldl, iterate_succ_apply, H] theorem foldr_const (f : β → β) (b : β) : ∀ l : List α, l.foldr (fun _ ↦ f) b = f^[l.length] b | [] => rfl | a :: l => by rw [length_cons, foldr, foldr_const f b l, iterate_succ_apply'] end List
ssrnum.v
From mathcomp Require Export orderedzmod. From mathcomp Require Export numdomain. From mathcomp Require Export numfield. Module Num. Export orderedzmod.Num. Export numdomain.Num. Export numfield.Num. Module Theory. Export orderedzmod.Num.Theory. Export numdomain.Num.Theory. Export numfield.Num.Theory. End Theory. Module Def. Export orderedzmod.Num.Def. Export numdomain.Num.Def. Export numfield.Num.Def. End Def. Module ExtraDef. #[deprecated(since="mathcomp 2.5.0", note="Use Num.Def.sqrtr instead.")] Notation sqrtr := numfield.Num.Def.sqrtr. End ExtraDef. End Num.
GaloisField.lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Alex J. Best, Johan Commelin, Eric Rodriguez, Ruben Van de Velde -/ import Mathlib.Algebra.Algebra.ZMod import Mathlib.FieldTheory.Finite.Basic import Mathlib.FieldTheory.Galois.Basic import Mathlib.RingTheory.Norm.Basic /-! # Galois fields If `p` is a prime number, and `n` a natural number, then `GaloisField p n` is defined as the splitting field of `X^(p^n) - X` over `ZMod p`. It is a finite field with `p ^ n` elements. ## Main definition * `GaloisField p n` is a field with `p ^ n` elements ## Main Results - `GaloisField.algEquivGaloisField`: Any finite field is isomorphic to some Galois field - `FiniteField.algEquivOfCardEq`: Uniqueness of finite fields : algebra isomorphism - `FiniteField.ringEquivOfCardEq`: Uniqueness of finite fields : ring isomorphism -/ noncomputable section open Polynomial Finset open scoped Polynomial instance FiniteField.isSplittingField_sub (K F : Type*) [Field K] [Fintype K] [Field F] [Algebra F K] : IsSplittingField F K (X ^ Fintype.card K - X) where splits' := by have h : (X ^ Fintype.card K - X : K[X]).natDegree = Fintype.card K := FiniteField.X_pow_card_sub_X_natDegree_eq K Fintype.one_lt_card rw [← splits_id_iff_splits, splits_iff_card_roots, Polynomial.map_sub, Polynomial.map_pow, map_X, h, FiniteField.roots_X_pow_card_sub_X K, ← Finset.card_def, Finset.card_univ] adjoin_rootSet' := by classical trans Algebra.adjoin F ((roots (X ^ Fintype.card K - X : K[X])).toFinset : Set K) · simp only [rootSet, aroots, Polynomial.map_pow, map_X, Polynomial.map_sub] · rw [FiniteField.roots_X_pow_card_sub_X, val_toFinset, coe_univ, Algebra.adjoin_univ] theorem galois_poly_separable {K : Type*} [CommRing K] (p q : ℕ) [CharP K p] (h : p ∣ q) : Separable (X ^ q - X : K[X]) := by use 1, X ^ q - X - 1 rw [← CharP.cast_eq_zero_iff K[X] p] at h rw [derivative_sub, derivative_X_pow, derivative_X, C_eq_natCast, h] ring variable (p : ℕ) [Fact p.Prime] (n : ℕ) /-- A finite field with `p ^ n` elements. Every field with the same cardinality is (non-canonically) isomorphic to this field. -/ def GaloisField := SplittingField (X ^ p ^ n - X : (ZMod p)[X]) deriving Inhabited, Field, CharP _ p, Algebra (ZMod p), Finite, FiniteDimensional (ZMod p), IsSplittingField (ZMod p) _ (X ^ p ^ n - X) namespace GaloisField variable (p : ℕ) [h_prime : Fact p.Prime] (n : ℕ) theorem finrank {n} (h : n ≠ 0) : Module.finrank (ZMod p) (GaloisField p n) = n := by haveI : Fintype (GaloisField p n) := Fintype.ofFinite (GaloisField p n) set g_poly := (X ^ p ^ n - X : (ZMod p)[X]) have hp : 1 < p := h_prime.out.one_lt have aux : g_poly ≠ 0 := FiniteField.X_pow_card_pow_sub_X_ne_zero _ h hp have key : Fintype.card (g_poly.rootSet (GaloisField p n)) = g_poly.natDegree := card_rootSet_eq_natDegree (galois_poly_separable p _ (dvd_pow (dvd_refl p) h)) (SplittingField.splits (g_poly : (ZMod p)[X])) have nat_degree_eq : g_poly.natDegree = p ^ n := FiniteField.X_pow_card_pow_sub_X_natDegree_eq _ h hp rw [nat_degree_eq] at key suffices g_poly.rootSet (GaloisField p n) = Set.univ by simp_rw [this, ← Fintype.ofEquiv_card (Equiv.Set.univ _)] at key -- Porting note: prevents `card_eq_pow_finrank` from using a wrong instance for `Fintype` rw [@Module.card_eq_pow_finrank (ZMod p) _ _ _ _ _ (_), ZMod.card] at key exact Nat.pow_right_injective (Nat.Prime.one_lt' p).out key rw [Set.eq_univ_iff_forall] suffices ∀ (x) (hx : x ∈ (⊤ : Subalgebra (ZMod p) (GaloisField p n))), x ∈ (X ^ p ^ n - X : (ZMod p)[X]).rootSet (GaloisField p n) by simpa rw [← SplittingField.adjoin_rootSet] simp_rw [Algebra.mem_adjoin_iff] intro x hx -- We discharge the `p = 0` separately, to avoid typeclass issues on `ZMod p`. cases p; cases hp simp only [g_poly] at aux refine Subring.closure_induction ?_ ?_ ?_ ?_ ?_ ?_ hx <;> simp_rw [mem_rootSet_of_ne aux] · rintro x (⟨r, rfl⟩ | hx) · simp only [map_sub, map_pow, aeval_X] rw [← map_pow, ZMod.pow_card_pow, sub_self] · dsimp only [GaloisField] at hx rwa [mem_rootSet_of_ne aux] at hx · rw [← coeff_zero_eq_aeval_zero'] simp only [coeff_X_pow, coeff_X_zero, sub_zero, _root_.map_eq_zero, ite_eq_right_iff, one_ne_zero, coeff_sub] intro hn exact Nat.not_lt_zero 1 (pow_eq_zero hn.symm ▸ hp) · simp · simp only [aeval_X_pow, aeval_X, map_sub, add_pow_char_pow, sub_eq_zero] intro x y _ _ hx hy rw [hx, hy] · intro x _ hx simp only [g_poly, sub_eq_zero, aeval_X_pow, aeval_X, map_sub, sub_neg_eq_add] at * rw [neg_pow, hx, neg_one_pow_char_pow] simp · simp only [aeval_X_pow, aeval_X, map_sub, mul_pow, sub_eq_zero] intro x y _ _ hx hy rw [hx, hy] theorem card (h : n ≠ 0) : Nat.card (GaloisField p n) = p ^ n := by let b := IsNoetherian.finsetBasis (ZMod p) (GaloisField p n) haveI : Fintype (GaloisField p n) := Fintype.ofFinite (GaloisField p n) rw [Nat.card_eq_fintype_card, Module.card_fintype b, ← Module.finrank_eq_card_basis b, ZMod.card, finrank p h] theorem splits_zmod_X_pow_sub_X : Splits (RingHom.id (ZMod p)) (X ^ p - X) := by have hp : 1 < p := h_prime.out.one_lt have h1 : roots (X ^ p - X : (ZMod p)[X]) = Finset.univ.val := by convert FiniteField.roots_X_pow_card_sub_X (ZMod p) exact (ZMod.card p).symm have h2 := FiniteField.X_pow_card_sub_X_natDegree_eq (ZMod p) hp -- We discharge the `p = 0` separately, to avoid typeclass issues on `ZMod p`. cases p; cases hp rw [splits_iff_card_roots, h1, ← Finset.card_def, Finset.card_univ, h2, ZMod.card] /-- A Galois field with exponent 1 is equivalent to `ZMod` -/ def equivZmodP : GaloisField p 1 ≃ₐ[ZMod p] ZMod p := have h : (X ^ p ^ 1 : (ZMod p)[X]) = X ^ Fintype.card (ZMod p) := by rw [pow_one, ZMod.card p] have inst : IsSplittingField (ZMod p) (ZMod p) (X ^ p ^ 1 - X) := by rw [h]; infer_instance (@IsSplittingField.algEquiv _ (ZMod p) _ _ _ (X ^ p ^ 1 - X : (ZMod p)[X]) inst).symm section Fintype variable {K : Type*} [Field K] [Fintype K] [Algebra (ZMod p) K] theorem _root_.FiniteField.splits_X_pow_card_sub_X : Splits (algebraMap (ZMod p) K) (X ^ Fintype.card K - X) := (FiniteField.isSplittingField_sub K (ZMod p)).splits theorem _root_.FiniteField.isSplittingField_of_card_eq (h : Fintype.card K = p ^ n) : IsSplittingField (ZMod p) K (X ^ p ^ n - X) := h ▸ FiniteField.isSplittingField_sub K (ZMod p) /-- Any finite field is (possibly non canonically) isomorphic to some Galois field. -/ def algEquivGaloisFieldOfFintype (h : Fintype.card K = p ^ n) : K ≃ₐ[ZMod p] GaloisField p n := haveI := FiniteField.isSplittingField_of_card_eq _ _ h IsSplittingField.algEquiv _ _ end Fintype section Finite variable {K : Type*} [Field K] [Algebra (ZMod p) K] theorem _root_.FiniteField.splits_X_pow_nat_card_sub_X [Finite K] : Splits (algebraMap (ZMod p) K) (X ^ Nat.card K - X) := by haveI : Fintype K := Fintype.ofFinite K rw [Nat.card_eq_fintype_card] exact (FiniteField.isSplittingField_sub K (ZMod p)).splits theorem _root_.FiniteField.isSplittingField_of_nat_card_eq (h : Nat.card K = p ^ n) : IsSplittingField (ZMod p) K (X ^ p ^ n - X) := by haveI : Finite K := (Nat.card_pos_iff.mp (h ▸ pow_pos h_prime.1.pos n)).2 haveI : Fintype K := Fintype.ofFinite K rw [← h, Nat.card_eq_fintype_card] exact FiniteField.isSplittingField_sub K (ZMod p) instance (priority := 100) {K K' : Type*} [Field K] [Field K'] [Finite K'] [Algebra K K'] : IsGalois K K' := by cases nonempty_fintype K' obtain ⟨p, hp⟩ := CharP.exists K haveI : CharP K p := hp haveI : CharP K' p := charP_of_injective_algebraMap' K K' p exact IsGalois.of_separable_splitting_field (galois_poly_separable p (Fintype.card K') (let ⟨n, _, hn⟩ := FiniteField.card K' p hn.symm ▸ dvd_pow_self p n.ne_zero)) /-- Any finite field is (possibly non canonically) isomorphic to some Galois field. -/ def algEquivGaloisField (h : Nat.card K = p ^ n) : K ≃ₐ[ZMod p] GaloisField p n := haveI := FiniteField.isSplittingField_of_nat_card_eq _ _ h IsSplittingField.algEquiv _ _ end Finite end GaloisField namespace FiniteField variable {K K' : Type*} [Field K] [Field K'] section norm variable [Algebra K K'] [Finite K'] theorem algebraMap_norm_eq_pow {x : K'} : algebraMap K K' (Algebra.norm K x) = x ^ ((Nat.card K' - 1) / (Nat.card K - 1)) := by have := Finite.of_injective _ (algebraMap K K').injective have := Fintype.ofFinite K have := Fintype.ofFinite K' simp_rw [← Fintype.card_eq_nat_card, Algebra.norm_eq_prod_automorphisms, ← (bijective_frobeniusAlgEquivOfAlgebraic_pow K K').prod_comp, AlgEquiv.coe_pow, coe_frobeniusAlgEquivOfAlgebraic, pow_iterate, Finset.prod_pow_eq_pow_sum, Fin.sum_univ_eq_sum_range, Nat.geomSum_eq Fintype.one_lt_card, ← Module.card_eq_pow_finrank] variable (K K') theorem unitsMap_norm_surjective : Function.Surjective (Units.map <| Algebra.norm K (S := K')) := have := Finite.of_injective_finite_range (algebraMap K K').injective MonoidHom.surjective_of_card_ker_le_div _ <| by simp_rw [Nat.card_units] classical have := Fintype.ofFinite K'ˣ convert IsCyclic.card_pow_eq_one_le (α := K'ˣ) <| Nat.div_pos (Nat.sub_le_sub_right (Nat.card_le_card_of_injective _ (algebraMap K K').injective) _) <| Nat.sub_pos_of_lt Finite.one_lt_card rw [← Set.ncard_coe_finset, ← SetLike.coe_sort_coe, Nat.card_coe_set_eq]; congr; ext simp [Units.ext_iff, ← (algebraMap K K').injective.eq_iff, algebraMap_norm_eq_pow] theorem norm_surjective : Function.Surjective (Algebra.norm K (S := K')) := fun k ↦ by obtain rfl | ne := eq_or_ne k 0 · exact ⟨0, Algebra.norm_zero ..⟩ have ⟨x, eq⟩ := unitsMap_norm_surjective K K' (Units.mk0 k ne) exact ⟨x, congr_arg (·.1) eq⟩ end norm variable [Fintype K] [Fintype K'] /-- Uniqueness of finite fields: Any two finite fields of the same cardinality are (possibly non canonically) isomorphic -/ def algEquivOfCardEq (p : ℕ) [h_prime : Fact p.Prime] [Algebra (ZMod p) K] [Algebra (ZMod p) K'] (hKK' : Fintype.card K = Fintype.card K') : K ≃ₐ[ZMod p] K' := by have : CharP K p := by rw [← Algebra.charP_iff (ZMod p) K p]; exact ZMod.charP p have : CharP K' p := by rw [← Algebra.charP_iff (ZMod p) K' p]; exact ZMod.charP p choose n a hK using FiniteField.card K p choose n' a' hK' using FiniteField.card K' p rw [hK, hK'] at hKK' have hGalK := GaloisField.algEquivGaloisFieldOfFintype p n hK have hK'Gal := (GaloisField.algEquivGaloisFieldOfFintype p n' hK').symm rw [Nat.pow_right_injective h_prime.out.one_lt hKK'] at * exact AlgEquiv.trans hGalK hK'Gal /-- Uniqueness of finite fields: Any two finite fields of the same cardinality are (possibly non canonically) isomorphic -/ def ringEquivOfCardEq (hKK' : Fintype.card K = Fintype.card K') : K ≃+* K' := by choose p _char_p_K using CharP.exists K choose p' _char_p'_K' using CharP.exists K' choose n hp hK using FiniteField.card K p choose n' hp' hK' using FiniteField.card K' p' have hpp' : p = p' := by by_contra hne have h2 := Nat.coprime_pow_primes n n' hp hp' hne rw [(Eq.congr hK hK').mp hKK', Nat.coprime_self, pow_eq_one_iff (PNat.ne_zero n')] at h2 exact Nat.Prime.ne_one hp' h2 rw [← hpp'] at _char_p'_K' haveI := fact_iff.2 hp letI : Algebra (ZMod p) K := ZMod.algebra _ _ letI : Algebra (ZMod p) K' := ZMod.algebra _ _ exact ↑(algEquivOfCardEq p hKK') end FiniteField
primitive_action.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 div seq fintype tuple finset. From mathcomp Require Import fingroup action gseries. (******************************************************************************) (* n-transitive and primitive actions: *) (* [primitive A, on S | to] <=> *) (* A acts on S in a primitive manner, i.e., A is transitive on S and *) (* A does not act on any nontrivial partition of S. *) (* imprimitivity_system A to S Q <=> *) (* Q is a non-trivial primitivity system for the action of A on S via *) (* to, i.e., Q is a non-trivial partition of S on which A acts. *) (* to * n == in the %act scope, the total action induced by the total *) (* action to on n.-tuples. via n_act to n. *) (* n.-dtuple S == the set of n-tuples with distinct values in S. *) (* [transitive^n A, on S | to] <=> *) (* A is n-transitive on S, i.e., A is transitive on n.-dtuple S *) (* == the set of n-tuples with distinct values in S. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Section PrimitiveDef. Variables (aT : finGroupType) (sT : finType). Variables (A : {set aT}) (S : {set sT}) (to : {action aT &-> sT}). Definition imprimitivity_system Q := [&& partition Q S, [acts A, on Q | to^*] & 1 < #|Q| < #|S|]. Definition primitive := [transitive A, on S | to] && ~~ [exists Q, imprimitivity_system Q]. End PrimitiveDef. Arguments imprimitivity_system {aT sT} A%_g S%_g to%_act Q%_g. Arguments primitive {aT sT} A%_g S%_g to%_act. Notation "[ 'primitive' A , 'on' S | to ]" := (primitive A S to) (format "[ 'primitive' A , 'on' S | to ]") : form_scope. Section Primitive. Variables (aT : finGroupType) (sT : finType). Variables (G : {group aT}) (to : {action aT &-> sT}) (S : {set sT}). Lemma trans_prim_astab x : x \in S -> [transitive G, on S | to] -> [primitive G, on S | to] = maximal_eq 'C_G[x | to] G. Proof. move=> Sx trG; rewrite /primitive trG negb_exists. apply/forallP/maximal_eqP=> /= [primG | [_ maxCx] Q]. split=> [|H sCH sHG]; first exact: subsetIl. pose X := orbit to H x; pose Q := orbit (to^*)%act G X. have Xx: x \in X by apply: orbit_refl. have defH: 'N_(G)(X | to) = H. have trH: [transitive H, on X | to] by apply/imsetP; exists x. have sHN: H \subset 'N_G(X | to) by rewrite subsetI sHG atrans_acts. move/(subgroup_transitiveP Xx sHN): (trH) => /= <-. by rewrite mulSGid //= setIAC subIset ?sCH. apply/imsetP; exists x => //; apply/eqP. by rewrite eqEsubset imsetS // acts_sub_orbit ?subsetIr. have [|/proper_card oCH] := eqVproper sCH; [by left | right]. apply/eqP; rewrite eqEcard sHG leqNgt. apply: contra {primG}(primG Q) => oHG; apply/and3P; split; last first. - rewrite card_orbit astab1_set defH -(@ltn_pmul2l #|H|) ?Lagrange // muln1. rewrite oHG -(@ltn_pmul2l #|H|) ?Lagrange // -(card_orbit_stab to G x). by rewrite -(atransP trG x Sx) mulnC card_orbit ltn_pmul2r. - by apply/actsP=> a Ga Y; apply/orbit_transl/mem_orbit. apply/and3P; split; last 1 first. - rewrite orbit_sym; apply/imsetP=> [[a _]] /= defX. by rewrite defX /setact imset0 inE in Xx. - apply/eqP/setP=> y; apply/bigcupP/idP=> [[_ /imsetP[a Ga ->]] | Sy]. case/imsetP=> _ /imsetP[b Hb ->] ->. by rewrite !(actsP (atrans_acts trG)) //; apply: subsetP Hb. case: (atransP2 trG Sx Sy) => a Ga ->. by exists ((to^*)%act X a); apply: imset_f; rewrite // orbit_refl. apply/trivIsetP=> _ _ /imsetP[a Ga ->] /imsetP[b Gb ->]. apply: contraR => /exists_inP[_ /imsetP[_ /imsetP[a1 Ha1 ->] ->]]. case/imsetP=> _ /imsetP[b1 Hb1 ->] /(canLR (actK _ _)) /(canLR (actK _ _)). rewrite -(canF_eq (actKV _ _)) -!actM (sameP eqP astab1P) => /astab1P Cab. rewrite astab1_set (subsetP (subsetIr G _)) //= defH. rewrite -(groupMr _ (groupVr Hb1)) -mulgA -(groupMl _ Ha1). by rewrite (subsetP sCH) // inE Cab !groupM ?groupV // (subsetP sHG). apply/and3P=> [[/and3P[/eqP defS tIQ ntQ]]]; set sto := (to^*)%act => actQ. rewrite !ltnNge -negb_or => /orP[]. pose X := pblock Q x; have Xx: x \in X by rewrite mem_pblock defS. have QX: X \in Q by rewrite pblock_mem ?defS. have toX Y a: Y \in Q -> a \in G -> to x a \in Y -> sto X a = Y. move=> QY Ga Yxa; rewrite -(contraNeq (trivIsetP tIQ Y (sto X a) _ _)) //. by rewrite (actsP actQ). by apply/existsP; exists (to x a); rewrite /= Yxa; apply: imset_f. have defQ: Q = orbit (to^*)%act G X. apply/eqP; rewrite eqEsubset andbC acts_sub_orbit // QX. apply/subsetP=> Y QY. have /set0Pn[y Yy]: Y != set0 by apply: contraNneq ntQ => <-. have Sy: y \in S by rewrite -defS; apply/bigcupP; exists Y. have [a Ga def_y] := atransP2 trG Sx Sy. by apply/imsetP; exists a; rewrite // (toX Y) // -def_y. rewrite defQ card_orbit; case: (maxCx 'C_G[X | sto]%G) => /= [||->|->]. - apply/subsetP=> a /setIP[Ga cxa]; rewrite inE Ga /=. by apply/astab1P; rewrite (toX X) // (astab1P cxa). - exact: subsetIl. - by right; rewrite -card_orbit (atransP trG). by left; rewrite indexgg. Qed. Lemma prim_trans_norm (H : {group aT}) : [primitive G, on S | to] -> H <| G -> H \subset 'C_G(S | to) \/ [transitive H, on S | to]. Proof. move=> primG /andP[sHG nHG]; rewrite subsetI sHG. have [trG _] := andP primG; have [x Sx defS] := imsetP trG. move: primG; rewrite (trans_prim_astab Sx) // => /maximal_eqP[_]. case/(_ ('C_G[x | to] <*> H)%G) => /= [||cxH|]; first exact: joing_subl. - by rewrite join_subG subsetIl. - have{} cxH: H \subset 'C_G[x | to] by rewrite -cxH joing_subr. rewrite subsetI sHG /= in cxH; left; apply/subsetP=> a Ha. apply/astabP=> y Sy; have [b Gb ->] := atransP2 trG Sx Sy. rewrite actCJV [to x (a ^ _)](astab1P _) ?(subsetP cxH) //. by rewrite -mem_conjg (normsP nHG). rewrite norm_joinEl 1?subIset ?nHG //. by move/(subgroup_transitiveP Sx sHG trG); right. Qed. End Primitive. Section NactionDef. Variables (gT : finGroupType) (sT : finType). Variables (to : {action gT &-> sT}) (n : nat). Definition n_act (t : n.-tuple sT) a := [tuple of map (to^~ a) t]. Fact n_act_is_action : is_action setT n_act. Proof. by apply: is_total_action => [t|t a b]; apply: eq_from_tnth => i; rewrite !tnth_map ?act1 ?actM. Qed. Canonical n_act_action := Action n_act_is_action. End NactionDef. Notation "to * n" := (n_act_action to n) : action_scope. Section NTransitive. Variables (gT : finGroupType) (sT : finType). Variables (n : nat) (A : {set gT}) (S : {set sT}) (to : {action gT &-> sT}). Definition dtuple_on := [set t : n.-tuple sT | uniq t & t \subset S]. Definition ntransitive := [transitive A, on dtuple_on | to * n]. Lemma dtuple_onP t : reflect (injective (tnth t) /\ forall i, tnth t i \in S) (t \in dtuple_on). Proof. rewrite inE subset_all -forallb_tnth -[in uniq t]map_tnth_enum /=. by apply: (iffP andP) => -[/injectiveP-f_inj /forallP]. Qed. Lemma n_act_dtuple t a : a \in 'N(S | to) -> t \in dtuple_on -> n_act to t a \in dtuple_on. Proof. move/astabsP=> toSa /dtuple_onP[t_inj St]; apply/dtuple_onP. split=> [i j | i]; rewrite !tnth_map ?[_ \in S]toSa //. by move/act_inj; apply: t_inj. Qed. End NTransitive. Arguments dtuple_on {sT} n%_N S%_g. Arguments ntransitive {gT sT} n%_N A%_g S%_g to%_act. Arguments n_act {gT sT} to {n} t a. Notation "n .-dtuple ( S )" := (dtuple_on n S) (format "n .-dtuple ( S )") : set_scope. Notation "[ 'transitive' ^ n A , 'on' S | to ]" := (ntransitive n A S to) (n at level 8, format "[ 'transitive' ^ n A , 'on' S | to ]") : form_scope. Section NTransitveProp. Variables (gT : finGroupType) (sT : finType). Variables (to : {action gT &-> sT}) (G : {group gT}) (S : {set sT}). Lemma card_uniq_tuple n (t : n.-tuple sT) : uniq t -> #|t| = n. Proof. by move/card_uniqP->; apply: size_tuple. Qed. Lemma n_act0 (t : 0.-tuple sT) a : n_act to t a = [tuple]. Proof. exact: tuple0. Qed. Lemma dtuple_on_add n x (t : n.-tuple sT) : ([tuple of x :: t] \in n.+1.-dtuple(S)) = [&& x \in S, x \notin t & t \in n.-dtuple(S)]. Proof. by rewrite !inE memtE !subset_all -!andbA; do !bool_congr. Qed. Lemma dtuple_on_add_D1 n x (t : n.-tuple sT) : ([tuple of x :: t] \in n.+1.-dtuple(S)) = (x \in S) && (t \in n.-dtuple(S :\ x)). Proof. rewrite dtuple_on_add !inE (andbCA (~~ _)); do 2!congr (_ && _). rewrite -!(eq_subset (in_set [in t])) setDE setIC subsetI; congr (_ && _). by rewrite -setCS setCK sub1set !inE. Qed. Lemma dtuple_on_subset n (S1 S2 : {set sT}) t : S1 \subset S2 -> t \in n.-dtuple(S1) -> t \in n.-dtuple(S2). Proof. by move=> sS12 /[!inE] /andP[-> /subset_trans]; apply. Qed. Lemma n_act_add n x (t : n.-tuple sT) a : n_act to [tuple of x :: t] a = [tuple of to x a :: n_act to t a]. Proof. exact: val_inj. Qed. Lemma ntransitive0 : [transitive^0 G, on S | to]. Proof. have dt0: [tuple] \in 0.-dtuple(S) by rewrite inE memtE subset_all. apply/imsetP; exists [tuple of Nil sT] => //. by apply/setP=> x; rewrite [x]tuple0 orbit_refl. Qed. Lemma ntransitive_weak k m : k <= m -> [transitive^m G, on S | to] -> [transitive^k G, on S | to]. Proof. move/subnKC <-; rewrite addnC; elim: {m}(m - k) => // m IHm. rewrite addSn => tr_m1; apply: IHm; move: {m k}(m + k) tr_m1 => m tr_m1. have ext_t t: t \in dtuple_on m S -> exists x, [tuple of x :: t] \in m.+1.-dtuple(S). - move=> dt. have [sSt | /subsetPn[x Sx ntx]] := boolP (S \subset t); last first. by exists x; rewrite dtuple_on_add andbA /= Sx ntx. case/imsetP: tr_m1 dt => t1 /[!inE] /andP[Ut1 St1] _ /andP[Ut _]. have /subset_leq_card := subset_trans St1 sSt. by rewrite !card_uniq_tuple // ltnn. case/imsetP: (tr_m1); case/tupleP=> [x t]; rewrite dtuple_on_add. case/and3P=> Sx ntx dt; set xt := [tuple of _] => tr_xt. apply/imsetP; exists t => //. apply/setP=> u; apply/idP/imsetP=> [du | [a Ga ->{u}]]. case: (ext_t u du) => y; rewrite tr_xt. by case/imsetP=> a Ga [_ def_u]; exists a => //; apply: val_inj. have: n_act to xt a \in dtuple_on _ S by rewrite tr_xt imset_f. by rewrite n_act_add dtuple_on_add; case/and3P. Qed. Lemma ntransitive1 m : 0 < m -> [transitive^m G, on S | to] -> [transitive G, on S | to]. Proof. have trdom1 x: ([tuple x] \in 1.-dtuple(S)) = (x \in S). by rewrite dtuple_on_add !inE memtE subset_all andbT. move=> m_gt0 /(ntransitive_weak m_gt0) {m m_gt0}. case/imsetP; case/tupleP=> x t0; rewrite {t0}(tuple0 t0) trdom1 => Sx trx. apply/imsetP; exists x => //; apply/setP=> y; rewrite -trdom1 trx. by apply/imsetP/imsetP=> [[a ? [->]]|[a ? ->]]; exists a => //; apply: val_inj. Qed. Lemma ntransitive_primitive m : 1 < m -> [transitive^m G, on S | to] -> [primitive G, on S | to]. Proof. move=> lt1m /(ntransitive_weak lt1m) {m lt1m}tr2G. have trG: [transitive G, on S | to] by apply: ntransitive1 tr2G. have [x Sx _]:= imsetP trG; rewrite (trans_prim_astab Sx trG). apply/maximal_eqP; split=> [|H]; first exact: subsetIl; rewrite subEproper. case/predU1P; first by [left]; case/andP=> sCH /subsetPn[a Ha nCa] sHG. right; rewrite -(subgroup_transitiveP Sx sHG trG _) ?mulSGid //. have actH := subset_trans sHG (atrans_acts trG). pose y := to x a; have Sy: y \in S by rewrite (actsP actH). have{nCa} yx: y != x by rewrite inE (sameP astab1P eqP) (subsetP sHG) in nCa. apply/imsetP; exists y => //; apply/eqP. rewrite eqEsubset acts_sub_orbit // Sy andbT; apply/subsetP=> z Sz. have [-> | zx] := eqVneq z x; first by rewrite orbit_sym mem_orbit. pose ty := [tuple y; x]; pose tz := [tuple z; x]. have [Sty Stz]: ty \in 2.-dtuple(S) /\ tz \in 2.-dtuple(S). by rewrite !inE !memtE !subset_all /= !mem_seq1 !andbT; split; apply/and3P. case: (atransP2 tr2G Sty Stz) => b Gb [->] /esym/astab1P cxb. by rewrite mem_orbit // (subsetP sCH) // inE Gb. Qed. End NTransitveProp. Section NTransitveProp1. Variables (gT : finGroupType) (sT : finType). Variables (to : {action gT &-> sT}) (G : {group gT}) (S : {set sT}). (* This is the forward implication of Aschbacher (15.12).1 *) Theorem stab_ntransitive m x : 0 < m -> x \in S -> [transitive^m.+1 G, on S | to] -> [transitive^m 'C_G[x | to], on S :\ x | to]. Proof. move=> m_gt0 Sx Gtr; have sSxS: S :\ x \subset S by rewrite subsetDl. case: (imsetP Gtr); case/tupleP=> x1 t1; rewrite dtuple_on_add. case/and3P=> Sx1 nt1x1 dt1 trt1; have Gtr1 := ntransitive1 (ltn0Sn _) Gtr. case: (atransP2 Gtr1 Sx1 Sx) => // a Ga x1ax. pose t := n_act to t1 a. have dxt: [tuple of x :: t] \in m.+1.-dtuple(S). by rewrite trt1 x1ax; apply/imsetP; exists a => //; apply: val_inj. apply/imsetP; exists t; first by rewrite dtuple_on_add_D1 Sx in dxt. apply/setP=> t2; apply/idP/imsetP => [dt2|[b]]. have: [tuple of x :: t2] \in dtuple_on _ S by rewrite dtuple_on_add_D1 Sx. case/(atransP2 Gtr dxt)=> b Gb [xbx tbt2]. by exists b; [rewrite inE Gb; apply/astab1P | apply: val_inj]. case/setIP=> Gb /astab1P xbx ->{t2}. rewrite n_act_dtuple //; last by rewrite dtuple_on_add_D1 Sx in dxt. apply/astabsP=> y; rewrite !inE -{1}xbx (inj_eq (act_inj _ _)). by rewrite (actsP (atrans_acts Gtr1)). Qed. (* This is the converse implication of Aschbacher (15.12).1 *) Theorem stab_ntransitiveI m x : x \in S -> [transitive G, on S | to] -> [transitive^m 'C_G[x | to], on S :\ x | to] -> [transitive^m.+1 G, on S | to]. Proof. move=> Sx Gtr Gntr. have t_to_x t: t \in m.+1.-dtuple(S) -> exists2 a, a \in G & exists2 t', t' \in m.-dtuple(S :\ x) & t = n_act to [tuple of x :: t'] a. - case/tupleP: t => y t St. have Sy: y \in S by rewrite dtuple_on_add_D1 in St; case/andP: St. rewrite -(atransP Gtr _ Sy) in Sx; case/imsetP: Sx => a Ga toya. exists a^-1; first exact: groupVr. exists (n_act to t a); last by rewrite n_act_add toya !actK. move/(n_act_dtuple (subsetP (atrans_acts Gtr) a Ga)): St. by rewrite n_act_add -toya dtuple_on_add_D1 => /andP[]. case: (imsetP Gntr) => t dt S_tG; pose xt := [tuple of x :: t]. have dxt: xt \in m.+1.-dtuple(S) by rewrite dtuple_on_add_D1 Sx. apply/imsetP; exists xt => //; apply/setP=> t2. apply/esym; apply/imsetP/idP=> [[a Ga ->] | ]. by apply: n_act_dtuple; rewrite // (subsetP (atrans_acts Gtr)). case/t_to_x=> a2 Ga2 [t2']; rewrite S_tG. case/imsetP=> a /setIP[Ga /astab1P toxa] -> -> {t2 t2'}. by exists (a * a2); rewrite (groupM, actM) //= !n_act_add toxa. Qed. End NTransitveProp1.
Colimit.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.Condensed.Discrete.LocallyConstant import Mathlib.Condensed.Equivalence import Mathlib.Topology.Category.LightProfinite.Extend /-! # The condensed set given by left Kan extension from `FintypeCat` to `Profinite`. This file provides the necessary API to prove that a condensed set `X` is discrete if and only if for every profinite set `S = limᵢSᵢ`, `X(S) ≅ colimᵢX(Sᵢ)`, and the analogous result for light condensed sets. -/ universe u noncomputable section open CategoryTheory Functor Limits FintypeCat CompHausLike.LocallyConstant namespace Condensed section LocallyConstantAsColimit variable {I : Type u} [Category.{u} I] [IsCofiltered I] {F : I ⥤ FintypeCat.{u}} (c : Cone <| F ⋙ toProfinite) (X : Type (u + 1)) /-- The presheaf on `Profinite` of locally constant functions to `X`. -/ abbrev locallyConstantPresheaf : Profinite.{u}ᵒᵖ ⥤ Type (u + 1) := CompHausLike.LocallyConstant.functorToPresheaves.{u, u + 1}.obj X /-- The functor `locallyConstantPresheaf` takes cofiltered limits of finite sets with surjective projection maps to colimits. -/ noncomputable def isColimitLocallyConstantPresheaf (hc : IsLimit c) [∀ i, Epi (c.π.app i)] : IsColimit <| (locallyConstantPresheaf X).mapCocone c.op := by refine Types.FilteredColimit.isColimitOf _ _ ?_ ?_ · intro (f : LocallyConstant c.pt X) obtain ⟨j, h⟩ := Profinite.exists_locallyConstant.{_, u} c hc f exact ⟨⟨j⟩, h⟩ · intro ⟨i⟩ ⟨j⟩ (fi : LocallyConstant _ _) (fj : LocallyConstant _ _) (h : fi.comap (c.π.app i).hom = fj.comap (c.π.app j).hom) obtain ⟨k, ki, kj, _⟩ := IsCofilteredOrEmpty.cone_objs i j refine ⟨⟨k⟩, ki.op, kj.op, ?_⟩ dsimp ext x obtain ⟨x, hx⟩ := ((Profinite.epi_iff_surjective (c.π.app k)).mp inferInstance) x rw [← hx] change fi ((c.π.app k ≫ (F ⋙ toProfinite).map _) x) = fj ((c.π.app k ≫ (F ⋙ toProfinite).map _) x) have h := LocallyConstant.congr_fun h x rwa [c.w, c.w] @[simp] lemma isColimitLocallyConstantPresheaf_desc_apply (hc : IsLimit c) [∀ i, Epi (c.π.app i)] (s : Cocone ((F ⋙ toProfinite).op ⋙ locallyConstantPresheaf X)) (i : I) (f : LocallyConstant (toProfinite.obj (F.obj i)) X) : (isColimitLocallyConstantPresheaf c X hc).desc s (f.comap (c.π.app i).hom) = s.ι.app ⟨i⟩ f := by change ((((locallyConstantPresheaf X).mapCocone c.op).ι.app ⟨i⟩) ≫ (isColimitLocallyConstantPresheaf c X hc).desc s) _ = _ rw [(isColimitLocallyConstantPresheaf c X hc).fac] /-- `isColimitLocallyConstantPresheaf` in the case of `S.asLimit`. -/ noncomputable def isColimitLocallyConstantPresheafDiagram (S : Profinite) : IsColimit <| (locallyConstantPresheaf X).mapCocone S.asLimitCone.op := isColimitLocallyConstantPresheaf _ _ S.asLimit @[simp] lemma isColimitLocallyConstantPresheafDiagram_desc_apply (S : Profinite) (s : Cocone (S.diagram.op ⋙ locallyConstantPresheaf X)) (i : DiscreteQuotient S) (f : LocallyConstant (S.diagram.obj i) X) : (isColimitLocallyConstantPresheafDiagram X S).desc s (f.comap (S.asLimitCone.π.app i).hom) = s.ι.app ⟨i⟩ f := isColimitLocallyConstantPresheaf_desc_apply S.asLimitCone X S.asLimit s i f end LocallyConstantAsColimit /-- Given a presheaf `F` on `Profinite`, `lanPresheaf F` is the left Kan extension of its restriction to finite sets along the inclusion functor of finite sets into `Profinite`. -/ abbrev lanPresheaf (F : Profinite.{u}ᵒᵖ ⥤ Type (u + 1)) : Profinite.{u}ᵒᵖ ⥤ Type (u + 1) := pointwiseLeftKanExtension toProfinite.op (toProfinite.op ⋙ F) /-- To presheaves on `Profinite` whose restrictions to finite sets are isomorphic have isomorphic left Kan extensions. -/ def lanPresheafExt {F G : Profinite.{u}ᵒᵖ ⥤ Type (u + 1)} (i : toProfinite.op ⋙ F ≅ toProfinite.op ⋙ G) : lanPresheaf F ≅ lanPresheaf G := leftKanExtensionUniqueOfIso _ (pointwiseLeftKanExtensionUnit _ _) i _ (pointwiseLeftKanExtensionUnit _ _) @[simp] lemma lanPresheafExt_hom {F G : Profinite.{u}ᵒᵖ ⥤ Type (u + 1)} (S : Profinite.{u}ᵒᵖ) (i : toProfinite.op ⋙ F ≅ toProfinite.op ⋙ G) : (lanPresheafExt i).hom.app S = colimMap (whiskerLeft (CostructuredArrow.proj toProfinite.op S) i.hom) := by simp only [lanPresheaf, pointwiseLeftKanExtension_obj, lanPresheafExt, leftKanExtensionUniqueOfIso_hom, pointwiseLeftKanExtension_desc_app] apply colimit.hom_ext aesop @[simp] lemma lanPresheafExt_inv {F G : Profinite.{u}ᵒᵖ ⥤ Type (u + 1)} (S : Profinite.{u}ᵒᵖ) (i : toProfinite.op ⋙ F ≅ toProfinite.op ⋙ G) : (lanPresheafExt i).inv.app S = colimMap (whiskerLeft (CostructuredArrow.proj toProfinite.op S) i.inv) := by simp only [lanPresheaf, pointwiseLeftKanExtension_obj, lanPresheafExt, leftKanExtensionUniqueOfIso_inv, pointwiseLeftKanExtension_desc_app] apply colimit.hom_ext aesop variable {S : Profinite.{u}} {F : Profinite.{u}ᵒᵖ ⥤ Type (u + 1)} instance : Final <| Profinite.Extend.functorOp S.asLimitCone := Profinite.Extend.functorOp_final S.asLimitCone S.asLimit /-- A presheaf, which takes a profinite set written as a cofiltered limit to the corresponding colimit, agrees with the left Kan extension of its restriction. -/ def lanPresheafIso (hF : IsColimit <| F.mapCocone S.asLimitCone.op) : (lanPresheaf F).obj ⟨S⟩ ≅ F.obj ⟨S⟩ := (Functor.Final.colimitIso (Profinite.Extend.functorOp S.asLimitCone) _).symm ≪≫ (colimit.isColimit _).coconePointUniqueUpToIso hF @[simp] lemma lanPresheafIso_hom (hF : IsColimit <| F.mapCocone S.asLimitCone.op) : (lanPresheafIso hF).hom = colimit.desc _ (Profinite.Extend.cocone _ _) := by simp [lanPresheafIso, Final.colimitIso] rfl /-- `lanPresheafIso` is natural in `S`. -/ def lanPresheafNatIso (hF : ∀ S : Profinite, IsColimit <| F.mapCocone S.asLimitCone.op) : lanPresheaf F ≅ F := NatIso.ofComponents (fun ⟨S⟩ ↦ (lanPresheafIso (hF S))) fun _ ↦ (by simpa using colimit.hom_ext fun _ ↦ (by simp)) @[simp] lemma lanPresheafNatIso_hom_app (hF : ∀ S : Profinite, IsColimit <| F.mapCocone S.asLimitCone.op) (S : Profiniteᵒᵖ) : (lanPresheafNatIso hF).hom.app S = colimit.desc _ (Profinite.Extend.cocone _ _) := by simp [lanPresheafNatIso] /-- `lanPresheaf (locallyConstantPresheaf X)` is a sheaf for the coherent topology on `Profinite`. -/ def lanSheafProfinite (X : Type (u + 1)) : Sheaf (coherentTopology Profinite.{u}) (Type (u + 1)) where val := lanPresheaf (locallyConstantPresheaf X) cond := by rw [Presheaf.isSheaf_of_iso_iff (lanPresheafNatIso fun _ ↦ isColimitLocallyConstantPresheafDiagram _ _)] exact ((CompHausLike.LocallyConstant.functor.{u, u + 1} (hs := fun _ _ _ ↦ ((Profinite.effectiveEpi_tfae _).out 0 2).mp)).obj X).cond /-- `lanPresheaf (locallyConstantPresheaf X)` as a condensed set. -/ def lanCondensedSet (X : Type (u + 1)) : CondensedSet.{u} := (ProfiniteCompHaus.equivalence _).functor.obj (lanSheafProfinite X) variable (F : Profinite.{u}ᵒᵖ ⥤ Type (u + 1)) /-- The functor which takes a finite set to the set of maps into `F(*)` for a presheaf `F` on `Profinite`. -/ @[simps] def finYoneda : FintypeCat.{u}ᵒᵖ ⥤ Type (u + 1) where obj X := X.unop → F.obj (toProfinite.op.obj ⟨of PUnit.{u + 1}⟩) map f g := g ∘ f.unop /-- `locallyConstantPresheaf` restricted to finite sets is isomorphic to `finYoneda F`. -/ @[simps! hom_app] def locallyConstantIsoFinYoneda : toProfinite.op ⋙ (locallyConstantPresheaf (F.obj (toProfinite.op.obj ⟨of PUnit.{u + 1}⟩))) ≅ finYoneda F := NatIso.ofComponents fun Y ↦ { hom := fun f ↦ f.1 inv := fun f ↦ ⟨f, @IsLocallyConstant.of_discrete _ _ _ ⟨rfl⟩ _⟩ } /-- A finite set as a coproduct cocone in `Profinite` over itself. -/ def fintypeCatAsCofan (X : Profinite) : Cofan (fun (_ : X) ↦ (Profinite.of (PUnit.{u + 1}))) := Cofan.mk X (fun x ↦ TopCat.ofHom (ContinuousMap.const _ x)) /-- A finite set is the coproduct of its points in `Profinite`. -/ def fintypeCatAsCofanIsColimit (X : Profinite) [Finite X] : IsColimit (fintypeCatAsCofan X) := by refine mkCofanColimit _ (fun t ↦ TopCat.ofHom ⟨fun x ↦ t.inj x PUnit.unit, ?_⟩) ?_ (fun _ _ h ↦ by ext x; exact CategoryTheory.congr_fun (h x) _) · apply continuous_of_discreteTopology (α := X) · aesop variable [PreservesFiniteProducts F] noncomputable instance (X : Profinite) [Finite X] : PreservesLimitsOfShape (Discrete X) F := let X' := (Countable.toSmall.{0} X).equiv_small.choose let e : X ≃ X' := (Countable.toSmall X).equiv_small.choose_spec.some have : Finite X' := .of_equiv X e preservesLimitsOfShape_of_equiv (Discrete.equivalence e.symm) F /-- Auxiliary definition for `isoFinYoneda`. -/ def isoFinYonedaComponents (X : Profinite.{u}) [Finite X] : F.obj ⟨X⟩ ≅ (X → F.obj ⟨Profinite.of PUnit.{u + 1}⟩) := (isLimitFanMkObjOfIsLimit F _ _ (Cofan.IsColimit.op (fintypeCatAsCofanIsColimit X))).conePointUniqueUpToIso (Types.productLimitCone.{u, u + 1} fun _ ↦ F.obj ⟨Profinite.of PUnit.{u + 1}⟩).2 lemma isoFinYonedaComponents_hom_apply (X : Profinite.{u}) [Finite X] (y : F.obj ⟨X⟩) (x : X) : (isoFinYonedaComponents F X).hom y x = F.map ((Profinite.of PUnit.{u + 1}).const x).op y := rfl lemma isoFinYonedaComponents_inv_comp {X Y : Profinite.{u}} [Finite X] [Finite Y] (f : Y → F.obj ⟨Profinite.of PUnit⟩) (g : X ⟶ Y) : (isoFinYonedaComponents F X).inv (f ∘ g) = F.map g.op ((isoFinYonedaComponents F Y).inv f) := by apply injective_of_mono (isoFinYonedaComponents F X).hom simp only [CategoryTheory.inv_hom_id_apply] ext x rw [isoFinYonedaComponents_hom_apply] simp only [← FunctorToTypes.map_comp_apply, ← op_comp, CompHausLike.const_comp, ← isoFinYonedaComponents_hom_apply, CategoryTheory.inv_hom_id_apply, Function.comp_apply] /-- The restriction of a finite product preserving presheaf `F` on `Profinite` to the category of finite sets is isomorphic to `finYoneda F`. -/ @[simps!] def isoFinYoneda : toProfinite.op ⋙ F ≅ finYoneda F := NatIso.ofComponents (fun X ↦ isoFinYonedaComponents F (toProfinite.obj X.unop)) fun _ ↦ by simp only [comp_obj, op_obj, finYoneda_obj, Functor.comp_map, op_map] ext simp only [types_comp_apply, isoFinYonedaComponents_hom_apply, finYoneda_map, op_obj, Function.comp_apply, ← FunctorToTypes.map_comp_apply] rfl /-- A presheaf `F`, which takes a profinite set written as a cofiltered limit to the corresponding colimit, is isomorphic to the presheaf `LocallyConstant - F(*)`. -/ def isoLocallyConstantOfIsColimit (hF : ∀ S : Profinite, IsColimit <| F.mapCocone S.asLimitCone.op) : F ≅ (locallyConstantPresheaf (F.obj (toProfinite.op.obj ⟨of PUnit.{u + 1}⟩))) := (lanPresheafNatIso hF).symm ≪≫ lanPresheafExt (isoFinYoneda F ≪≫ (locallyConstantIsoFinYoneda F).symm) ≪≫ lanPresheafNatIso fun _ ↦ isColimitLocallyConstantPresheafDiagram _ _ lemma isoLocallyConstantOfIsColimit_inv (X : Profinite.{u}ᵒᵖ ⥤ Type (u + 1)) [PreservesFiniteProducts X] (hX : ∀ S : Profinite.{u}, (IsColimit <| X.mapCocone S.asLimitCone.op)) : (isoLocallyConstantOfIsColimit X hX).inv = (CompHausLike.LocallyConstant.counitApp.{u, u + 1} X) := by dsimp [isoLocallyConstantOfIsColimit] simp only [Category.assoc] rw [Iso.inv_comp_eq] ext S : 2 apply colimit.hom_ext intro ⟨Y, _, g⟩ simp? [locallyConstantIsoFinYoneda, isoFinYoneda, counitApp] says simp only [comp_obj, CostructuredArrow.proj_obj, op_obj, functorToPresheaves_obj_obj, isoFinYoneda, locallyConstantIsoFinYoneda, finYoneda_obj, LocallyConstant.toFun_eq_coe, NatTrans.comp_app, pointwiseLeftKanExtension_obj, lanPresheafExt_inv, Iso.trans_inv, Iso.symm_inv, whiskerLeft_comp, lanPresheafNatIso_hom_app, Opposite.op_unop, colimit.map_desc, colimit.ι_desc, Cocones.precompose_obj_pt, Profinite.Extend.cocone_pt, Cocones.precompose_obj_ι, Category.assoc, const_obj_obj, whiskerLeft_app, NatIso.ofComponents_hom_app, NatIso.ofComponents_inv_app, Profinite.Extend.cocone_ι_app, counitApp, colimit.ι_desc_assoc] erw [(counitApp.{u, u + 1} X).naturality] simp only [← Category.assoc] congr ext f simp only [types_comp_apply, counitApp_app] apply presheaf_ext.{u, u + 1} (X := X) (Y := X) (f := f) intro x rw [incl_of_counitAppApp] simp only [counitAppAppImage] letI : Fintype (fiber.{u, u + 1} f x) := Fintype.ofInjective (sigmaIncl.{u, u + 1} f x).1 Subtype.val_injective apply injective_of_mono (isoFinYonedaComponents X (fiber.{u, u + 1} f x)).hom ext y simp only [isoFinYonedaComponents_hom_apply, ← FunctorToTypes.map_comp_apply, ← op_comp] rw [show (Profinite.of PUnit.{u + 1}).const y ≫ IsTerminal.from _ (fiber f x) = 𝟙 _ from rfl] simp only [op_comp, FunctorToTypes.map_comp_apply, op_id, FunctorToTypes.map_id_apply] rw [← isoFinYonedaComponents_inv_comp X _ (sigmaIncl.{u, u + 1} f x)] simpa [← isoFinYonedaComponents_hom_apply] using x.map_eq_image f y end Condensed namespace LightCondensed section LocallyConstantAsColimit variable {F : ℕᵒᵖ ⥤ FintypeCat.{u}} (c : Cone <| F ⋙ toLightProfinite) (X : Type u) /-- The presheaf on `LightProfinite` of locally constant functions to `X`. -/ abbrev locallyConstantPresheaf : LightProfiniteᵒᵖ ⥤ Type u := CompHausLike.LocallyConstant.functorToPresheaves.{u, u}.obj X /-- The functor `locallyConstantPresheaf` takes sequential limits of finite sets with surjective projection maps to colimits. -/ noncomputable def isColimitLocallyConstantPresheaf (hc : IsLimit c) [∀ i, Epi (c.π.app i)] : IsColimit <| (locallyConstantPresheaf X).mapCocone c.op := by refine Types.FilteredColimit.isColimitOf _ _ ?_ ?_ · intro (f : LocallyConstant c.pt X) obtain ⟨j, h⟩ := Profinite.exists_locallyConstant.{_, 0} (lightToProfinite.mapCone c) (isLimitOfPreserves lightToProfinite hc) f exact ⟨⟨j⟩, h⟩ · intro ⟨i⟩ ⟨j⟩ (fi : LocallyConstant _ _) (fj : LocallyConstant _ _) (h : fi.comap (c.π.app i).hom = fj.comap (c.π.app j).hom) obtain ⟨k, ki, kj, _⟩ := IsCofilteredOrEmpty.cone_objs i j refine ⟨⟨k⟩, ki.op, kj.op, ?_⟩ dsimp ext x obtain ⟨x, hx⟩ := ((LightProfinite.epi_iff_surjective (c.π.app k)).mp inferInstance) x rw [← hx] change fi ((c.π.app k ≫ (F ⋙ toLightProfinite).map _) x) = fj ((c.π.app k ≫ (F ⋙ toLightProfinite).map _) x) have h := LocallyConstant.congr_fun h x rwa [c.w, c.w] @[simp] lemma isColimitLocallyConstantPresheaf_desc_apply (hc : IsLimit c) [∀ i, Epi (c.π.app i)] (s : Cocone ((F ⋙ toLightProfinite).op ⋙ locallyConstantPresheaf X)) (n : ℕᵒᵖ) (f : LocallyConstant (toLightProfinite.obj (F.obj n)) X) : (isColimitLocallyConstantPresheaf c X hc).desc s (f.comap (c.π.app n).hom) = s.ι.app ⟨n⟩ f := by change ((((locallyConstantPresheaf X).mapCocone c.op).ι.app ⟨n⟩) ≫ (isColimitLocallyConstantPresheaf c X hc).desc s) _ = _ rw [(isColimitLocallyConstantPresheaf c X hc).fac] /-- `isColimitLocallyConstantPresheaf` in the case of `S.asLimit`. -/ noncomputable def isColimitLocallyConstantPresheafDiagram (S : LightProfinite) : IsColimit <| (locallyConstantPresheaf X).mapCocone (coconeRightOpOfCone S.asLimitCone) := (Functor.Final.isColimitWhiskerEquiv (opOpEquivalence ℕ).inverse _).symm (isColimitLocallyConstantPresheaf _ _ S.asLimit) @[simp] lemma isColimitLocallyConstantPresheafDiagram_desc_apply (S : LightProfinite) (s : Cocone (S.diagram.rightOp ⋙ locallyConstantPresheaf X)) (n : ℕ) (f : LocallyConstant (S.diagram.obj ⟨n⟩) X) : (isColimitLocallyConstantPresheafDiagram X S).desc s (f.comap (S.asLimitCone.π.app ⟨n⟩).hom) = s.ι.app n f := by change ((((locallyConstantPresheaf X).mapCocone (coconeRightOpOfCone S.asLimitCone)).ι.app n) ≫ (isColimitLocallyConstantPresheafDiagram X S).desc s) _ = _ rw [(isColimitLocallyConstantPresheafDiagram X S).fac] end LocallyConstantAsColimit instance (S : LightProfinite.{u}ᵒᵖ) : HasColimitsOfShape (CostructuredArrow toLightProfinite.op S) (Type u) := hasColimitsOfShape_of_equivalence (asEquivalence (CostructuredArrow.pre Skeleton.incl.op _ S)) /-- Given a presheaf `F` on `LightProfinite`, `lanPresheaf F` is the left Kan extension of its restriction to finite sets along the inclusion functor of finite sets into `Profinite`. -/ abbrev lanPresheaf (F : LightProfinite.{u}ᵒᵖ ⥤ Type u) : LightProfinite.{u}ᵒᵖ ⥤ Type u := pointwiseLeftKanExtension toLightProfinite.op (toLightProfinite.op ⋙ F) /-- To presheaves on `LightProfinite` whose restrictions to finite sets are isomorphic have isomorphic left Kan extensions. -/ def lanPresheafExt {F G : LightProfinite.{u}ᵒᵖ ⥤ Type u} (i : toLightProfinite.op ⋙ F ≅ toLightProfinite.op ⋙ G) : lanPresheaf F ≅ lanPresheaf G := leftKanExtensionUniqueOfIso _ (pointwiseLeftKanExtensionUnit _ _) i _ (pointwiseLeftKanExtensionUnit _ _) @[simp] lemma lanPresheafExt_hom {F G : LightProfinite.{u}ᵒᵖ ⥤ Type u} (S : LightProfinite.{u}ᵒᵖ) (i : toLightProfinite.op ⋙ F ≅ toLightProfinite.op ⋙ G) : (lanPresheafExt i).hom.app S = colimMap (whiskerLeft (CostructuredArrow.proj toLightProfinite.op S) i.hom) := by simp only [lanPresheaf, pointwiseLeftKanExtension_obj, lanPresheafExt, leftKanExtensionUniqueOfIso_hom, pointwiseLeftKanExtension_desc_app] apply colimit.hom_ext aesop @[simp] lemma lanPresheafExt_inv {F G : LightProfinite.{u}ᵒᵖ ⥤ Type u} (S : LightProfinite.{u}ᵒᵖ) (i : toLightProfinite.op ⋙ F ≅ toLightProfinite.op ⋙ G) : (lanPresheafExt i).inv.app S = colimMap (whiskerLeft (CostructuredArrow.proj toLightProfinite.op S) i.inv) := by simp only [lanPresheaf, pointwiseLeftKanExtension_obj, lanPresheafExt, leftKanExtensionUniqueOfIso_inv, pointwiseLeftKanExtension_desc_app] apply colimit.hom_ext aesop variable {S : LightProfinite.{u}} {F : LightProfinite.{u}ᵒᵖ ⥤ Type u} instance : Final <| LightProfinite.Extend.functorOp S.asLimitCone := LightProfinite.Extend.functorOp_final S.asLimitCone S.asLimit /-- A presheaf, which takes a light profinite set written as a sequential limit to the corresponding colimit, agrees with the left Kan extension of its restriction. -/ def lanPresheafIso (hF : IsColimit <| F.mapCocone (coconeRightOpOfCone S.asLimitCone)) : (lanPresheaf F).obj ⟨S⟩ ≅ F.obj ⟨S⟩ := (Functor.Final.colimitIso (LightProfinite.Extend.functorOp S.asLimitCone) _).symm ≪≫ (colimit.isColimit _).coconePointUniqueUpToIso hF @[simp] lemma lanPresheafIso_hom (hF : IsColimit <| F.mapCocone (coconeRightOpOfCone S.asLimitCone)) : (lanPresheafIso hF).hom = colimit.desc _ (LightProfinite.Extend.cocone _ _) := by simp [lanPresheafIso, Final.colimitIso] rfl /-- `lanPresheafIso` is natural in `S`. -/ def lanPresheafNatIso (hF : ∀ S : LightProfinite, IsColimit <| F.mapCocone (coconeRightOpOfCone S.asLimitCone)) : lanPresheaf F ≅ F := by refine NatIso.ofComponents (fun ⟨S⟩ ↦ (lanPresheafIso (hF S))) fun _ ↦ ?_ simp only [lanPresheaf, pointwiseLeftKanExtension_obj, pointwiseLeftKanExtension_map, lanPresheafIso_hom, Opposite.op_unop] exact colimit.hom_ext fun _ ↦ (by simp) @[simp] lemma lanPresheafNatIso_hom_app (hF : ∀ S : LightProfinite, IsColimit <| F.mapCocone (coconeRightOpOfCone S.asLimitCone)) (S : LightProfiniteᵒᵖ) : (lanPresheafNatIso hF).hom.app S = colimit.desc _ (LightProfinite.Extend.cocone _ _) := by simp [lanPresheafNatIso] /-- `lanPresheaf (locallyConstantPresheaf X)` as a light condensed set. -/ def lanLightCondSet (X : Type u) : LightCondSet.{u} where val := lanPresheaf (locallyConstantPresheaf X) cond := by rw [Presheaf.isSheaf_of_iso_iff (lanPresheafNatIso fun _ ↦ isColimitLocallyConstantPresheafDiagram _ _)] exact (CompHausLike.LocallyConstant.functor.{u, u} (hs := fun _ _ _ ↦ ((LightProfinite.effectiveEpi_iff_surjective _).mp)).obj X).cond variable (F : LightProfinite.{u}ᵒᵖ ⥤ Type u) /-- The functor which takes a finite set to the set of maps into `F(*)` for a presheaf `F` on `LightProfinite`. -/ @[simps] def finYoneda : FintypeCat.{u}ᵒᵖ ⥤ Type u where obj X := X.unop → F.obj (toLightProfinite.op.obj ⟨of PUnit.{u + 1}⟩) map f g := g ∘ f.unop /-- `locallyConstantPresheaf` restricted to finite sets is isomorphic to `finYoneda F`. -/ def locallyConstantIsoFinYoneda : toLightProfinite.op ⋙ (locallyConstantPresheaf (F.obj (toLightProfinite.op.obj ⟨of PUnit.{u + 1}⟩))) ≅ finYoneda F := NatIso.ofComponents fun Y ↦ { hom := fun f ↦ f.1 inv := fun f ↦ ⟨f, @IsLocallyConstant.of_discrete _ _ _ ⟨rfl⟩ _⟩ } /-- A finite set as a coproduct cocone in `LightProfinite` over itself. -/ def fintypeCatAsCofan (X : LightProfinite) : Cofan (fun (_ : X) ↦ (LightProfinite.of (PUnit.{u + 1}))) := Cofan.mk X (fun x ↦ TopCat.ofHom (ContinuousMap.const _ x)) /-- A finite set is the coproduct of its points in `LightProfinite`. -/ def fintypeCatAsCofanIsColimit (X : LightProfinite) [Finite X] : IsColimit (fintypeCatAsCofan X) := by refine mkCofanColimit _ (fun t ↦ TopCat.ofHom ⟨fun x ↦ t.inj x PUnit.unit, ?_⟩) ?_ (fun _ _ h ↦ by ext x; exact CategoryTheory.congr_fun (h x) _) · apply continuous_of_discreteTopology (α := X) · aesop variable [PreservesFiniteProducts F] noncomputable instance (X : FintypeCat.{u}) : PreservesLimitsOfShape (Discrete X) F := let X' := (Countable.toSmall.{0} X).equiv_small.choose let e : X ≃ X' := (Countable.toSmall X).equiv_small.choose_spec.some have : Fintype X' := Fintype.ofEquiv X e preservesLimitsOfShape_of_equiv (Discrete.equivalence e.symm) F /-- Auxiliary definition for `isoFinYoneda`. -/ def isoFinYonedaComponents (X : LightProfinite.{u}) [Finite X] : F.obj ⟨X⟩ ≅ (X → F.obj ⟨LightProfinite.of PUnit.{u + 1}⟩) := (isLimitFanMkObjOfIsLimit F _ _ (Cofan.IsColimit.op (fintypeCatAsCofanIsColimit X))).conePointUniqueUpToIso (Types.productLimitCone.{u, u} fun _ ↦ F.obj ⟨LightProfinite.of PUnit.{u + 1}⟩).2 lemma isoFinYonedaComponents_hom_apply (X : LightProfinite.{u}) [Finite X] (y : F.obj ⟨X⟩) (x : X) : (isoFinYonedaComponents F X).hom y x = F.map ((LightProfinite.of PUnit.{u + 1}).const x).op y := rfl lemma isoFinYonedaComponents_inv_comp {X Y : LightProfinite.{u}} [Finite X] [Finite Y] (f : Y → F.obj ⟨LightProfinite.of PUnit⟩) (g : X ⟶ Y) : (isoFinYonedaComponents F X).inv (f ∘ g) = F.map g.op ((isoFinYonedaComponents F Y).inv f) := by apply injective_of_mono (isoFinYonedaComponents F X).hom simp only [CategoryTheory.inv_hom_id_apply] ext x rw [isoFinYonedaComponents_hom_apply] simp only [← FunctorToTypes.map_comp_apply, ← op_comp, CompHausLike.const_comp, ← isoFinYonedaComponents_hom_apply, CategoryTheory.inv_hom_id_apply, Function.comp_apply] /-- The restriction of a finite product preserving presheaf `F` on `Profinite` to the category of finite sets is isomorphic to `finYoneda F`. -/ @[simps!] def isoFinYoneda : toLightProfinite.op ⋙ F ≅ finYoneda F := NatIso.ofComponents (fun X ↦ isoFinYonedaComponents F (toLightProfinite.obj X.unop)) fun _ ↦ by simp only [comp_obj, op_obj, finYoneda_obj, Functor.comp_map, op_map] ext simp only [types_comp_apply, isoFinYonedaComponents_hom_apply, finYoneda_map, op_obj, Function.comp_apply, ← FunctorToTypes.map_comp_apply] rfl /-- A presheaf `F`, which takes a light profinite set written as a sequential limit to the corresponding colimit, is isomorphic to the presheaf `LocallyConstant - F(*)`. -/ def isoLocallyConstantOfIsColimit (hF : ∀ S : LightProfinite, IsColimit <| F.mapCocone (coconeRightOpOfCone S.asLimitCone)) : F ≅ (locallyConstantPresheaf (F.obj (toLightProfinite.op.obj ⟨of PUnit.{u + 1}⟩))) := (lanPresheafNatIso hF).symm ≪≫ lanPresheafExt (isoFinYoneda F ≪≫ (locallyConstantIsoFinYoneda F).symm) ≪≫ lanPresheafNatIso fun _ ↦ isColimitLocallyConstantPresheafDiagram _ _ lemma isoLocallyConstantOfIsColimit_inv (X : LightProfinite.{u}ᵒᵖ ⥤ Type u) [PreservesFiniteProducts X] (hX : ∀ S : LightProfinite.{u}, (IsColimit <| X.mapCocone (coconeRightOpOfCone S.asLimitCone))) : (isoLocallyConstantOfIsColimit X hX).inv = (CompHausLike.LocallyConstant.counitApp.{u, u} X) := by dsimp [isoLocallyConstantOfIsColimit] simp only [Category.assoc] rw [Iso.inv_comp_eq] ext S : 2 apply colimit.hom_ext intro ⟨Y, _, g⟩ simp? [locallyConstantIsoFinYoneda, isoFinYoneda, counitApp] says simp only [comp_obj, CostructuredArrow.proj_obj, op_obj, functorToPresheaves_obj_obj, isoFinYoneda, locallyConstantIsoFinYoneda, finYoneda_obj, LocallyConstant.toFun_eq_coe, NatTrans.comp_app, pointwiseLeftKanExtension_obj, lanPresheafExt_inv, Iso.trans_inv, Iso.symm_inv, whiskerLeft_comp, lanPresheafNatIso_hom_app, Opposite.op_unop, colimit.map_desc, colimit.ι_desc, Cocones.precompose_obj_pt, LightProfinite.Extend.cocone_pt, Cocones.precompose_obj_ι, Category.assoc, const_obj_obj, whiskerLeft_app, NatIso.ofComponents_hom_app, NatIso.ofComponents_inv_app, LightProfinite.Extend.cocone_ι_app, counitApp, colimit.ι_desc_assoc] erw [(counitApp.{u, u} X).naturality] simp only [← Category.assoc] congr ext f simp only [types_comp_apply, counitApp_app] apply presheaf_ext.{u, u} (X := X) (Y := X) (f := f) intro x rw [incl_of_counitAppApp] simp only [counitAppAppImage] letI : Fintype (fiber.{u, u} f x) := Fintype.ofInjective (sigmaIncl.{u, u} f x).1 Subtype.val_injective apply injective_of_mono (isoFinYonedaComponents X (fiber.{u, u} f x)).hom ext y simp only [isoFinYonedaComponents_hom_apply, ← FunctorToTypes.map_comp_apply, ← op_comp] rw [show (LightProfinite.of PUnit.{u + 1}).const y ≫ IsTerminal.from _ (fiber f x) = 𝟙 _ from rfl] simp only [op_comp, FunctorToTypes.map_comp_apply, op_id, FunctorToTypes.map_id_apply] rw [← isoFinYonedaComponents_inv_comp X _ (sigmaIncl.{u, u} f x)] simpa [← isoFinYonedaComponents_hom_apply] using x.map_eq_image f y end LightCondensed
Round.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Kappelmann -/ import Mathlib.Algebra.Order.Floor.Ring import Mathlib.Algebra.Order.Interval.Set.Group /-! # Rounding This file defines the `round` function, which uses the `floor` or `ceil` function to round a number to the nearest integer. ## Main Definitions * `round a`: Nearest integer to `a`. It rounds halves towards infinity. ## Tags rounding -/ assert_not_exists Finset open Set variable {F α β : Type*} open Int /-! ### Round -/ section round section LinearOrderedRing variable [Ring α] [LinearOrder α] [IsStrictOrderedRing α] [FloorRing α] /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round (x : α) : ℤ := if 2 * fract x < 1 then ⌊x⌋ else ⌈x⌉ @[simp] theorem round_zero : round (0 : α) = 0 := by simp [round] @[simp] theorem round_one : round (1 : α) = 1 := by simp [round] @[simp] theorem round_natCast (n : ℕ) : round (n : α) = n := by simp [round] @[simp] theorem round_ofNat (n : ℕ) [n.AtLeastTwo] : round (ofNat(n) : α) = ofNat(n) := round_natCast n @[simp] theorem round_intCast (n : ℤ) : round (n : α) = n := by simp [round] @[simp] theorem round_add_intCast (x : α) (y : ℤ) : round (x + y) = round x + y := by rw [round, round, Int.fract_add_intCast, Int.floor_add_intCast, Int.ceil_add_intCast, ← apply_ite₂, ite_self] @[deprecated (since := "2025-03-23")] alias round_add_int := round_add_intCast @[simp] theorem round_add_one (a : α) : round (a + 1) = round a + 1 := by rw [← round_add_intCast a 1, cast_one] @[simp] theorem round_sub_intCast (x : α) (y : ℤ) : round (x - y) = round x - y := by rw [sub_eq_add_neg] norm_cast rw [round_add_intCast, sub_eq_add_neg] @[deprecated (since := "2025-03-23")] alias round_sub_int := round_sub_intCast @[simp] theorem round_sub_one (a : α) : round (a - 1) = round a - 1 := by rw [← round_sub_intCast a 1, cast_one] @[simp] theorem round_add_natCast (x : α) (y : ℕ) : round (x + y) = round x + y := mod_cast round_add_intCast x y @[deprecated (since := "2025-03-23")] alias round_add_nat := round_add_natCast @[simp] theorem round_add_ofNat (x : α) (n : ℕ) [n.AtLeastTwo] : round (x + ofNat(n)) = round x + ofNat(n) := round_add_natCast x n @[simp] theorem round_sub_natCast (x : α) (y : ℕ) : round (x - y) = round x - y := mod_cast round_sub_intCast x y @[deprecated (since := "2025-03-23")] alias round_sub_nat := round_sub_natCast @[simp] theorem round_sub_ofNat (x : α) (n : ℕ) [n.AtLeastTwo] : round (x - ofNat(n)) = round x - ofNat(n) := round_sub_natCast x n @[simp] theorem round_intCast_add (x : α) (y : ℤ) : round ((y : α) + x) = y + round x := by rw [add_comm, round_add_intCast, add_comm] @[deprecated (since := "2025-03-23")] alias round_int_add := round_intCast_add @[simp] theorem round_natCast_add (x : α) (y : ℕ) : round ((y : α) + x) = y + round x := by rw [add_comm, round_add_natCast, add_comm] @[deprecated (since := "2025-03-23")] alias round_nat_add := round_natCast_add @[simp] theorem round_ofNat_add (n : ℕ) [n.AtLeastTwo] (x : α) : round (ofNat(n) + x) = ofNat(n) + round x := round_natCast_add x n theorem abs_sub_round_eq_min (x : α) : |x - round x| = min (fract x) (1 - fract x) := by simp_rw [round, min_def_lt, two_mul, ← lt_tsub_iff_left] rcases lt_or_ge (fract x) (1 - fract x) with hx | hx · rw [if_pos hx, if_pos hx, self_sub_floor, abs_fract] · have : 0 < fract x := by replace hx : 0 < fract x + fract x := lt_of_lt_of_le zero_lt_one (tsub_le_iff_left.mp hx) simpa only [← two_mul, mul_pos_iff_of_pos_left, zero_lt_two] using hx rw [if_neg (not_lt.mpr hx), if_neg (not_lt.mpr hx), abs_sub_comm, ceil_sub_self_eq this.ne.symm, abs_one_sub_fract] theorem round_le (x : α) (z : ℤ) : |x - round x| ≤ |x - z| := by rw [abs_sub_round_eq_min, min_le_iff] rcases le_or_gt (z : α) x with (hx | hx) <;> [left; right] · conv_rhs => rw [abs_eq_self.mpr (sub_nonneg.mpr hx), ← fract_add_floor x, add_sub_assoc] simpa only [le_add_iff_nonneg_right, sub_nonneg, cast_le] using le_floor.mpr hx · rw [abs_eq_neg_self.mpr (sub_neg.mpr hx).le] conv_rhs => rw [← fract_add_floor x] rw [add_sub_assoc, add_comm, neg_add, neg_sub, le_add_neg_iff_add_le, sub_add_cancel, le_sub_comm] norm_cast exact floor_le_sub_one_iff.mpr hx end LinearOrderedRing section LinearOrderedField variable [Field α] [LinearOrder α] [IsStrictOrderedRing α] [FloorRing α] theorem round_eq (x : α) : round x = ⌊x + 1 / 2⌋ := by simp_rw [round, (by simp only [lt_div_iff₀', two_pos] : 2 * fract x < 1 ↔ fract x < 1 / 2)] rcases lt_or_ge (fract x) (1 / 2) with hx | hx · conv_rhs => rw [← fract_add_floor x, add_assoc, add_left_comm, floor_intCast_add] rw [if_pos hx, left_eq_add, floor_eq_iff, cast_zero, zero_add] constructor · linarith [fract_nonneg x] · linarith · have : ⌊fract x + 1 / 2⌋ = 1 := by rw [floor_eq_iff] constructor · norm_num linarith · norm_num linarith [fract_lt_one x] rw [if_neg (not_lt.mpr hx), ← fract_add_floor x, add_assoc, add_left_comm, floor_intCast_add, ceil_add_intCast, add_comm _ ⌊x⌋, add_right_inj, ceil_eq_iff, this, cast_one, sub_self] constructor · linarith · linarith [fract_lt_one x] @[simp] theorem round_two_inv : round (2⁻¹ : α) = 1 := by simp only [round_eq, ← one_div, add_halves, floor_one] @[simp] theorem round_neg_two_inv : round (-2⁻¹ : α) = 0 := by simp only [round_eq, ← one_div, neg_add_cancel, floor_zero] @[simp] theorem round_eq_zero_iff {x : α} : round x = 0 ↔ x ∈ Ico (-(1 / 2)) ((1 : α) / 2) := by rw [round_eq, floor_eq_zero_iff, add_mem_Ico_iff_left] norm_num theorem abs_sub_round (x : α) : |x - round x| ≤ 1 / 2 := by rw [round_eq, abs_sub_le_iff] have := floor_le (x + 1 / 2) have := lt_floor_add_one (x + 1 / 2) constructor <;> linarith theorem abs_sub_round_div_natCast_eq {m n : ℕ} : |(m : α) / n - round ((m : α) / n)| = ↑(min (m % n) (n - m % n)) / n := by rcases n.eq_zero_or_pos with (rfl | hn) · simp have hn' : 0 < (n : α) := by norm_cast rw [abs_sub_round_eq_min, Nat.cast_min, ← min_div_div_right hn'.le, fract_div_natCast_eq_div_natCast_mod, Nat.cast_sub (m.mod_lt hn).le, sub_div, div_self hn'.ne'] @[bound] theorem sub_half_lt_round (x : α) : x - 1 / 2 < round x := by rw [round_eq x, show x - 1 / 2 = x + 1 / 2 - 1 by linarith] exact Int.sub_one_lt_floor (x + 1 / 2) @[bound] theorem round_le_add_half (x : α) : round x ≤ x + 1 / 2 := by rw [round_eq x] exact Int.floor_le (x + 1 / 2) end LinearOrderedField end round namespace Int variable [Field α] [LinearOrder α] [IsStrictOrderedRing α] [Field β] [LinearOrder β] [IsStrictOrderedRing β] [FloorRing α] [FloorRing β] variable [FunLike F α β] [RingHomClass F α β] {a : α} {b : β} theorem map_round (f : F) (hf : StrictMono f) (a : α) : round (f a) = round a := by simp_rw [round_eq, ← map_floor _ hf, map_add, one_div, map_inv₀, map_ofNat] end Int
NAry.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.Data.Set.Prod /-! # N-ary images of sets This file defines `Set.image2`, the binary image of sets. This is mostly useful to define pointwise operations and `Set.seq`. ## Notes This file is very similar to `Data.Finset.NAry`, to `Order.Filter.NAry`, and to `Data.Option.NAry`. Please keep them in sync. -/ open Function namespace Set variable {α α' β β' γ γ' δ δ' ε ε' ζ ζ' ν : Type*} {f f' : α → β → γ} variable {s s' : Set α} {t t' : Set β} {u : Set γ} {v : Set δ} {a : α} {b : β} theorem mem_image2_iff (hf : Injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t := ⟨by rintro ⟨a', ha', b', hb', h⟩ rcases hf h with ⟨rfl, rfl⟩ exact ⟨ha', hb'⟩, fun ⟨ha, hb⟩ => mem_image2_of_mem ha hb⟩ /-- image2 is monotone with respect to `⊆`. -/ @[gcongr] theorem image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' := by rintro _ ⟨a, ha, b, hb, rfl⟩ exact mem_image2_of_mem (hs ha) (ht hb) theorem image2_subset_left (ht : t ⊆ t') : image2 f s t ⊆ image2 f s t' := image2_subset Subset.rfl ht theorem image2_subset_right (hs : s ⊆ s') : image2 f s t ⊆ image2 f s' t := image2_subset hs Subset.rfl theorem image_subset_image2_left (hb : b ∈ t) : (fun a => f a b) '' s ⊆ image2 f s t := forall_mem_image.2 fun _ ha => mem_image2_of_mem ha hb theorem image_subset_image2_right (ha : a ∈ s) : f a '' t ⊆ image2 f s t := forall_mem_image.2 fun _ => mem_image2_of_mem ha lemma forall_mem_image2 {p : γ → Prop} : (∀ z ∈ image2 f s t, p z) ↔ ∀ x ∈ s, ∀ y ∈ t, p (f x y) := by aesop lemma exists_mem_image2 {p : γ → Prop} : (∃ z ∈ image2 f s t, p z) ↔ ∃ x ∈ s, ∃ y ∈ t, p (f x y) := by aesop @[simp] theorem image2_subset_iff {u : Set γ} : image2 f s t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, f x y ∈ u := forall_mem_image2 theorem image2_subset_iff_left : image2 f s t ⊆ u ↔ ∀ a ∈ s, (fun b => f a b) '' t ⊆ u := by simp_rw [image2_subset_iff, image_subset_iff, subset_def, mem_preimage] theorem image2_subset_iff_right : image2 f s t ⊆ u ↔ ∀ b ∈ t, (fun a => f a b) '' s ⊆ u := by simp_rw [image2_subset_iff, image_subset_iff, subset_def, mem_preimage, @forall₂_swap α] variable (f) @[simp] lemma image_prod : (fun x : α × β ↦ f x.1 x.2) '' s ×ˢ t = image2 f s t := ext fun _ ↦ by simp [and_assoc] @[simp] lemma image_uncurry_prod (s : Set α) (t : Set β) : uncurry f '' s ×ˢ t = image2 f s t := image_prod _ @[simp] lemma image2_mk_eq_prod : image2 Prod.mk s t = s ×ˢ t := ext <| by simp @[simp] lemma image2_curry (f : α × β → γ) (s : Set α) (t : Set β) : image2 (fun a b ↦ f (a, b)) s t = f '' s ×ˢ t := by simp [← image_uncurry_prod, uncurry] theorem image2_swap (s : Set α) (t : Set β) : image2 f s t = image2 (fun a b => f b a) t s := by ext constructor <;> rintro ⟨a, ha, b, hb, rfl⟩ <;> exact ⟨b, hb, a, ha, rfl⟩ variable {f} theorem image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t := by simp_rw [← image_prod, union_prod, image_union] theorem image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' := by rw [← image2_swap, image2_union_left, image2_swap f, image2_swap f] lemma image2_inter_left (hf : Injective2 f) : image2 f (s ∩ s') t = image2 f s t ∩ image2 f s' t := by simp_rw [← image_uncurry_prod, inter_prod, image_inter hf.uncurry] lemma image2_inter_right (hf : Injective2 f) : image2 f s (t ∩ t') = image2 f s t ∩ image2 f s t' := by simp_rw [← image_uncurry_prod, prod_inter, image_inter hf.uncurry] @[simp] theorem image2_empty_left : image2 f ∅ t = ∅ := ext <| by simp @[simp] theorem image2_empty_right : image2 f s ∅ = ∅ := ext <| by simp theorem Nonempty.image2 : s.Nonempty → t.Nonempty → (image2 f s t).Nonempty := fun ⟨_, ha⟩ ⟨_, hb⟩ => ⟨_, mem_image2_of_mem ha hb⟩ @[simp] theorem image2_nonempty_iff : (image2 f s t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := ⟨fun ⟨_, a, ha, b, hb, _⟩ => ⟨⟨a, ha⟩, b, hb⟩, fun h => h.1.image2 h.2⟩ theorem Nonempty.of_image2_left (h : (Set.image2 f s t).Nonempty) : s.Nonempty := (image2_nonempty_iff.1 h).1 theorem Nonempty.of_image2_right (h : (Set.image2 f s t).Nonempty) : t.Nonempty := (image2_nonempty_iff.1 h).2 @[simp] theorem image2_eq_empty_iff : image2 f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by rw [← not_nonempty_iff_eq_empty, image2_nonempty_iff, not_and_or] simp [not_nonempty_iff_eq_empty] theorem Subsingleton.image2 (hs : s.Subsingleton) (ht : t.Subsingleton) (f : α → β → γ) : (image2 f s t).Subsingleton := by rw [← image_prod] apply (hs.prod ht).image theorem image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t := Monotone.map_inf_le (fun _ _ ↦ image2_subset_right) s s' theorem image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' := Monotone.map_inf_le (fun _ _ ↦ image2_subset_left) t t' @[simp] theorem image2_singleton_left : image2 f {a} t = f a '' t := ext fun x => by simp @[simp] theorem image2_singleton_right : image2 f s {b} = (fun a => f a b) '' s := ext fun x => by simp theorem image2_singleton : image2 f {a} {b} = {f a b} := by simp @[simp] theorem image2_insert_left : image2 f (insert a s) t = (fun b => f a b) '' t ∪ image2 f s t := by rw [insert_eq, image2_union_left, image2_singleton_left] @[simp] theorem image2_insert_right : image2 f s (insert b t) = (fun a => f a b) '' s ∪ image2 f s t := by rw [insert_eq, image2_union_right, image2_singleton_right] @[congr] theorem image2_congr (h : ∀ a ∈ s, ∀ b ∈ t, f a b = f' a b) : image2 f s t = image2 f' s t := by ext constructor <;> rintro ⟨a, ha, b, hb, rfl⟩ <;> exact ⟨a, ha, b, hb, by rw [h a ha b hb]⟩ /-- A common special case of `image2_congr` -/ theorem image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t := image2_congr fun a _ b _ => h a b theorem image_image2 (f : α → β → γ) (g : γ → δ) : g '' image2 f s t = image2 (fun a b => g (f a b)) s t := by simp only [← image_prod, image_image] theorem image2_image_left (f : γ → β → δ) (g : α → γ) : image2 f (g '' s) t = image2 (fun a b => f (g a) b) s t := by ext; simp theorem image2_image_right (f : α → γ → δ) (g : β → γ) : image2 f s (g '' t) = image2 (fun a b => f a (g b)) s t := by ext; simp @[simp] theorem image2_left (h : t.Nonempty) : image2 (fun x _ => x) s t = s := by simp [nonempty_def.mp h, Set.ext_iff] @[simp] theorem image2_right (h : s.Nonempty) : image2 (fun _ y => y) s t = t := by simp [nonempty_def.mp h, Set.ext_iff] lemma image2_range (f : α' → β' → γ) (g : α → α') (h : β → β') : image2 f (range g) (range h) = range fun x : α × β ↦ f (g x.1) (h x.2) := by simp_rw [← image_univ, image2_image_left, image2_image_right, ← image_prod, univ_prod_univ] theorem image2_assoc {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image2 f (image2 g s t) u = image2 f' s (image2 g' t u) := eq_of_forall_subset_iff fun _ ↦ by simp only [image2_subset_iff, forall_mem_image2, h_assoc] theorem image2_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image2 f s t = image2 g t s := (image2_swap _ _ _).trans <| by simp_rw [h_comm] theorem image2_left_comm {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : image2 f s (image2 g t u) = image2 g' t (image2 f' s u) := by rw [image2_swap f', image2_swap f] exact image2_assoc fun _ _ _ => h_left_comm _ _ _ theorem image2_right_comm {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : image2 f (image2 g s t) u = image2 g' (image2 f' s u) t := by rw [image2_swap g, image2_swap g'] exact image2_assoc fun _ _ _ => h_right_comm _ _ _ theorem image2_image2_image2_comm {f : ε → ζ → ν} {g : α → β → ε} {h : γ → δ → ζ} {f' : ε' → ζ' → ν} {g' : α → γ → ε'} {h' : β → δ → ζ'} (h_comm : ∀ a b c d, f (g a b) (h c d) = f' (g' a c) (h' b d)) : image2 f (image2 g s t) (image2 h u v) = image2 f' (image2 g' s u) (image2 h' t v) := by ext; constructor · rintro ⟨_, ⟨a, ha, b, hb, rfl⟩, _, ⟨c, hc, d, hd, rfl⟩, rfl⟩ exact ⟨_, ⟨a, ha, c, hc, rfl⟩, _, ⟨b, hb, d, hd, rfl⟩, (h_comm _ _ _ _).symm⟩ · rintro ⟨_, ⟨a, ha, c, hc, rfl⟩, _, ⟨b, hb, d, hd, rfl⟩, rfl⟩ exact ⟨_, ⟨a, ha, b, hb, rfl⟩, _, ⟨c, hc, d, hd, rfl⟩, h_comm _ _ _ _⟩ theorem image_image2_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (image2 f s t).image g = image2 f' (s.image g₁) (t.image g₂) := by simp_rw [image_image2, image2_image_left, image2_image_right, h_distrib] /-- Symmetric statement to `Set.image2_image_left_comm`. -/ theorem image_image2_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (image2 f s t).image g = image2 f' (s.image g') t := (image_image2_distrib h_distrib).trans <| by rw [image_id'] /-- Symmetric statement to `Set.image_image2_right_comm`. -/ theorem image_image2_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (image2 f s t).image g = image2 f' s (t.image g') := (image_image2_distrib h_distrib).trans <| by rw [image_id'] /-- Symmetric statement to `Set.image_image2_distrib_left`. -/ theorem image2_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : image2 f (s.image g) t = (image2 f' s t).image g' := (image_image2_distrib_left fun a b => (h_left_comm a b).symm).symm /-- Symmetric statement to `Set.image_image2_distrib_right`. -/ theorem image_image2_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : image2 f s (t.image g) = (image2 f' s t).image g' := (image_image2_distrib_right fun a b => (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/ theorem image2_distrib_subset_left {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) : image2 f s (image2 g t u) ⊆ image2 g' (image2 f₁ s t) (image2 f₂ s u) := by rintro _ ⟨a, ha, _, ⟨b, hb, c, hc, rfl⟩, rfl⟩ rw [h_distrib] exact mem_image2_of_mem (mem_image2_of_mem ha hb) (mem_image2_of_mem ha hc) /-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/ theorem image2_distrib_subset_right {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) : image2 f (image2 g s t) u ⊆ image2 g' (image2 f₁ s u) (image2 f₂ t u) := by rintro _ ⟨_, ⟨a, ha, b, hb, rfl⟩, c, hc, rfl⟩ rw [h_distrib] exact mem_image2_of_mem (mem_image2_of_mem ha hc) (mem_image2_of_mem hb hc) theorem image_image2_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (image2 f s t).image g = image2 f' (t.image g₁) (s.image g₂) := by rw [image2_swap f] exact image_image2_distrib fun _ _ => h_antidistrib _ _ /-- Symmetric statement to `Set.image2_image_left_anticomm`. -/ theorem image_image2_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (image2 f s t).image g = image2 f' (t.image g') s := (image_image2_antidistrib h_antidistrib).trans <| by rw [image_id'] /-- Symmetric statement to `Set.image_image2_right_anticomm`. -/ theorem image_image2_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (image2 f s t).image g = image2 f' t (s.image g') := (image_image2_antidistrib h_antidistrib).trans <| by rw [image_id'] /-- Symmetric statement to `Set.image_image2_antidistrib_left`. -/ theorem image2_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : image2 f (s.image g) t = (image2 f' t s).image g' := (image_image2_antidistrib_left fun a b => (h_left_anticomm b a).symm).symm /-- Symmetric statement to `Set.image_image2_antidistrib_right`. -/ theorem image_image2_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : image2 f s (t.image g) = (image2 f' t s).image g' := (image_image2_antidistrib_right fun a b => (h_right_anticomm b a).symm).symm /-- If `a` is a left identity for `f : α → β → β`, then `{a}` is a left identity for `Set.image2 f`. -/ lemma image2_left_identity {f : α → β → β} {a : α} (h : ∀ b, f a b = b) (t : Set β) : image2 f {a} t = t := by rw [image2_singleton_left, show f a = id from funext h, image_id] /-- If `b` is a right identity for `f : α → β → α`, then `{b}` is a right identity for `Set.image2 f`. -/ lemma image2_right_identity {f : α → β → α} {b : β} (h : ∀ a, f a b = a) (s : Set α) : image2 f s {b} = s := by rw [image2_singleton_right, funext h, image_id'] theorem image2_inter_union_subset_union : image2 f (s ∩ s') (t ∪ t') ⊆ image2 f s t ∪ image2 f s' t' := by rw [image2_union_right] exact union_subset_union (image2_subset_right inter_subset_left) (image2_subset_right inter_subset_right) theorem image2_union_inter_subset_union : image2 f (s ∪ s') (t ∩ t') ⊆ image2 f s t ∪ image2 f s' t' := by rw [image2_union_left] exact union_subset_union (image2_subset_left inter_subset_left) (image2_subset_left inter_subset_right) theorem image2_inter_union_subset {f : α → α → β} {s t : Set α} (hf : ∀ a b, f a b = f b a) : image2 f (s ∩ t) (s ∪ t) ⊆ image2 f s t := by rw [inter_comm] exact image2_inter_union_subset_union.trans (union_subset (image2_comm hf).subset Subset.rfl) theorem image2_union_inter_subset {f : α → α → β} {s t : Set α} (hf : ∀ a b, f a b = f b a) : image2 f (s ∪ t) (s ∩ t) ⊆ image2 f s t := by rw [image2_comm hf] exact image2_inter_union_subset hf end Set
intdiv.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 choice fintype tuple prime order. From mathcomp Require Import ssralg poly ssrnum ssrint matrix. From mathcomp Require Import polydiv perm zmodp bigop. (******************************************************************************) (* This file provides various results on divisibility of integers. *) (* It defines, for m, n, d : int, *) (* (m %% d)%Z == the remainder of the Euclidean division of m by d; this is *) (* the least non-negative element of the coset m + dZ when *) (* d != 0, and m if d = 0. *) (* (m %/ d)%Z == the quotient of the Euclidean division of m by d, such *) (* that m = (m %/ d)%Z * d + (m %% d)%Z. Since for d != 0 the *) (* remainder is non-negative, (m %/ d)%Z is non-zero for *) (* negative m. *) (* (d %| m)%Z <=> m is divisible by d; dvdz d is the (collective) predicate *) (* for integers divisible by d, and (d %| m)%Z is actually *) (* (transposing) notation for m \in dvdz d. *) (* (m = n %[mod d])%Z, (m == n %[mod d])%Z, (m != n %[mod d])%Z *) (* m and n are (resp. compare, don't compare) equal mod d. *) (* gcdz m n == the (non-negative) greatest common divisor of m and n, *) (* with gcdz 0 0 = 0. *) (* lcmz m n == the (non-negative) least common multiple of m and n. *) (* coprimez m n <=> m and n are coprime. *) (* egcdz m n == the Bezout coefficients of the gcd of m and n: a pair *) (* (u, v) of coprime integers such that u*m + v*n = gcdz m n. *) (* Alternatively, a Bezoutz lemma states such u and v exist. *) (* zchinese m1 m2 n1 n2 == for coprime m1 and m2, a solution to the Chinese *) (* remainder problem for n1 and n2, i.e., and integer n such *) (* that n = n1 %[mod m1] and n = n2 %[mod m2]. *) (* zcontents p == the contents of p : {poly int}, that is, the gcd of the *) (* coefficients of p, with the same sign as the lead *) (* coefficient of p. *) (* zprimitive p == the primitive part of p : {poly int}, i.e., p divided by *) (* its contents. *) (* int_Smith_normal_form :: a theorem asserting the existence of the Smith *) (* normal form for integer matrices. *) (* Note that many of the concepts and results in this file could and perhaps *) (* should be generalized to the more general setting of integral, unique *) (* factorization, principal ideal, or Euclidean domains. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import Order.TTheory GRing.Theory Num.Theory. Local Open Scope ring_scope. Definition divz (m d : int) : int := let: (K, n) := match m with Posz n => (Posz, n) | Negz n => (Negz, n) end in sgz d * K (n %/ `|d|)%N. Definition modz (m d : int) : int := m - divz m d * d. Definition dvdz d m := (`|d| %| `|m|)%N. Definition gcdz m n := (gcdn `|m| `|n|)%:Z. Definition lcmz m n := (lcmn `|m| `|n|)%:Z. Definition egcdz m n : int * int := if m == 0 then (0, (-1) ^+ (n < 0)%R) else let: (u, v) := egcdn `|m| `|n| in (sgz m * u, - (-1) ^+ (n < 0)%R * v%:Z). Definition coprimez m n := (gcdz m n == 1). Infix "%/" := divz : int_scope. Infix "%%" := modz : int_scope. Notation "d %| m" := (m \in dvdz d) : int_scope. Notation "m = n %[mod d ]" := (modz m d = modz n d) : int_scope. Notation "m == n %[mod d ]" := (modz m d == modz n d) : int_scope. Notation "m <> n %[mod d ]" := (modz m d <> modz n d) : int_scope. Notation "m != n %[mod d ]" := (modz m d != modz n d) : int_scope. Lemma divz_nat (n d : nat) : (n %/ d)%Z = (n %/ d)%N. Proof. by case: d => // d; rewrite /divz /= mul1r. Qed. Lemma divzN m d : (m %/ - d)%Z = - (m %/ d)%Z. Proof. by case: m => n; rewrite /divz /= sgzN abszN mulNr. Qed. Lemma divz_abs (m d : int) : (m %/ `|d|)%Z = (-1) ^+ (d < 0)%R * (m %/ d)%Z. Proof. by rewrite {3}[d]intEsign !mulr_sign; case: ifP => -> //; rewrite divzN opprK. Qed. Lemma div0z d : (0 %/ d)%Z = 0. Proof. by rewrite -(canLR (signrMK _) (divz_abs _ _)) (divz_nat 0) div0n mulr0. Qed. Lemma divNz_nat m d : (d > 0)%N -> (Negz m %/ d)%Z = - (m %/ d).+1%:Z. Proof. by case: d => // d _; apply: mul1r. Qed. Lemma divz_eq m d : m = (m %/ d)%Z * d + (m %% d)%Z. Proof. by rewrite addrC subrK. Qed. Lemma modzN m d : (m %% - d)%Z = (m %% d)%Z. Proof. by rewrite /modz divzN mulrNN. Qed. Lemma modz_abs m d : (m %% `|d|%N)%Z = (m %% d)%Z. Proof. by rewrite {2}[d]intEsign mulr_sign; case: ifP; rewrite ?modzN. Qed. Lemma modz_nat (m d : nat) : (m %% d)%Z = (m %% d)%N. Proof. by apply: (canLR (addrK _)); rewrite addrC divz_nat {1}(divn_eq m d). Qed. Lemma modNz_nat m d : (d > 0)%N -> (Negz m %% d)%Z = d%:Z - 1 - (m %% d)%:Z. Proof. rewrite /modz => /divNz_nat->; apply: (canLR (addrK _)). rewrite -!addrA -!opprD -!PoszD -opprB mulnSr !addnA PoszD addrK. by rewrite addnAC -addnA mulnC -divn_eq. Qed. Lemma modz_ge0 m d : d != 0 -> 0 <= (m %% d)%Z. Proof. rewrite -absz_gt0 -modz_abs => d_gt0. case: m => n; rewrite ?modNz_nat ?modz_nat // -addrA -opprD subr_ge0. by rewrite lez_nat ltn_mod. Qed. Lemma divz0 m : (m %/ 0)%Z = 0. Proof. by case: m. Qed. Lemma mod0z d : (0 %% d)%Z = 0. Proof. by rewrite /modz div0z mul0r subrr. Qed. Lemma modz0 m : (m %% 0)%Z = m. Proof. by rewrite /modz mulr0 subr0. Qed. Lemma divz_small m d : 0 <= m < `|d|%:Z -> (m %/ d)%Z = 0. Proof. rewrite -(canLR (signrMK _) (divz_abs _ _)); case: m => // n /divn_small. by rewrite divz_nat => ->; rewrite mulr0. Qed. Lemma divzMDl q m d : d != 0 -> ((q * d + m) %/ d)%Z = q + (m %/ d)%Z. Proof. rewrite neq_lt -oppr_gt0 => nz_d. wlog{nz_d} d_gt0: q d / d > 0; last case: d => // d in d_gt0 *. move=> IH; case/orP: nz_d => /IH// /(_ (- q)). by rewrite mulrNN !divzN -opprD => /oppr_inj. wlog q_gt0: q m / q >= 0; last case: q q_gt0 => // q _. move=> IH; case: q => n; first exact: IH; rewrite NegzE mulNr. by apply: canRL (addKr _) _; rewrite -IH ?addNKr. case: m => n; first by rewrite !divz_nat divnMDl. have [le_qd_n | lt_qd_n] := leqP (q * d) n. rewrite divNz_nat // NegzE -(subnKC le_qd_n) divnMDl //. by rewrite -!addnS !PoszD !opprD !addNKr divNz_nat. rewrite divNz_nat // NegzE -PoszM subzn // divz_nat. apply: canRL (addrK _) _; congr _%:Z; rewrite addnC -divnMDl // mulSnr. rewrite -{3}(subnKC (ltn_pmod n d_gt0)) addnA addnS -divn_eq addnAC. by rewrite subnKC // divnMDl // divn_small ?addn0 // subnSK ?ltn_mod ?leq_subr. Qed. Lemma mulzK m d : d != 0 -> (m * d %/ d)%Z = m. Proof. by move=> d_nz; rewrite -[m * d]addr0 divzMDl // div0z addr0. Qed. Lemma mulKz m d : d != 0 -> (d * m %/ d)%Z = m. Proof. by move=> d_nz; rewrite mulrC mulzK. Qed. Lemma expzB p m n : p != 0 -> (m >= n)%N -> p ^+ (m - n) = (p ^+ m %/ p ^+ n)%Z. Proof. by move=> p_nz /subnK{2}<-; rewrite exprD mulzK // expf_neq0. Qed. Lemma modz1 m : (m %% 1)%Z = 0. Proof. by case: m => n; rewrite (modNz_nat, modz_nat) ?modn1. Qed. Lemma divz1 m : (m %/ 1)%Z = m. Proof. by rewrite -{1}[m]mulr1 mulzK. Qed. Lemma divzz d : (d %/ d)%Z = (d != 0). Proof. by have [-> // | d_nz] := eqVneq; rewrite -{1}[d]mul1r mulzK. Qed. Lemma ltz_pmod m d : d > 0 -> (m %% d)%Z < d. Proof. case: m d => n [] // d d_gt0; first by rewrite modz_nat ltz_nat ltn_pmod. by rewrite modNz_nat // -lezD1 addrAC subrK gerDl oppr_le0. Qed. Lemma ltz_mod m d : d != 0 -> (m %% d)%Z < `|d|. Proof. by rewrite -absz_gt0 -modz_abs => d_gt0; apply: ltz_pmod. Qed. Lemma divzMpl p m d : p > 0 -> (p * m %/ (p * d) = m %/ d)%Z. Proof. case: p => // p p_gt0; wlog d_gt0: d / d > 0; last case: d => // d in d_gt0 *. by move=> IH; case/intP: d => [|d|d]; rewrite ?mulr0 ?divz0 ?mulrN ?divzN ?IH. rewrite {1}(divz_eq m d) mulrDr mulrCA divzMDl ?mulf_neq0 ?gt_eqF // addrC. rewrite divz_small ?add0r // PoszM pmulr_rge0 ?modz_ge0 ?gt_eqF //=. by rewrite ltr_pM2l ?ltz_pmod. Qed. Arguments divzMpl [p m d]. Lemma divzMpr p m d : p > 0 -> (m * p %/ (d * p) = m %/ d)%Z. Proof. by move=> p_gt0; rewrite -!(mulrC p) divzMpl. Qed. Arguments divzMpr [p m d]. Lemma lez_floor m d : d != 0 -> (m %/ d)%Z * d <= m. Proof. by rewrite -subr_ge0; apply: modz_ge0. Qed. (* leq_mod does not extend to negative m. *) Lemma lez_div m d : (`|(m %/ d)%Z| <= `|m|)%N. Proof. wlog d_gt0: d / d > 0; last case: d d_gt0 => // d d_gt0. by move=> IH; case/intP: d => [|n|n]; rewrite ?divz0 ?divzN ?abszN // IH. case: m => n; first by rewrite divz_nat leq_div. by rewrite divNz_nat // NegzE !abszN ltnS leq_div. Qed. Lemma ltz_ceil m d : d > 0 -> m < ((m %/ d)%Z + 1) * d. Proof. by case: d => // d d_gt0; rewrite mulrDl mul1r -ltrBlDl ltz_mod ?gt_eqF. Qed. Lemma ltz_divLR m n d : d > 0 -> ((m %/ d)%Z < n) = (m < n * d). Proof. move=> d_gt0; apply/idP/idP. by rewrite -[_ < n]lezD1 -(ler_pM2r d_gt0); exact/lt_le_trans/ltz_ceil. by rewrite -(ltr_pM2r d_gt0 _ n); apply/le_lt_trans/lez_floor; rewrite gt_eqF. Qed. Lemma lez_divRL m n d : d > 0 -> (m <= (n %/ d)%Z) = (m * d <= n). Proof. by move=> d_gt0; rewrite !leNgt ltz_divLR. Qed. Lemma lez_pdiv2r d : 0 <= d -> {homo divz^~ d : m n / m <= n}. Proof. by case: d => [[|d]|]// _ [] m [] n //; rewrite /divz !mul1r; apply: leq_div2r. Qed. Lemma divz_ge0 m d : d > 0 -> ((m %/ d)%Z >= 0) = (m >= 0). Proof. by case: d m => // d [] n d_gt0; rewrite (divz_nat, divNz_nat). Qed. Lemma divzMA_ge0 m n p : n >= 0 -> (m %/ (n * p) = (m %/ n)%Z %/ p)%Z. Proof. case: n => // [[|n]] _; first by rewrite mul0r !divz0 div0z. wlog p_gt0: p / p > 0; last case: p => // p in p_gt0 *. by case/intP: p => [|p|p] IH; rewrite ?mulr0 ?divz0 ?mulrN ?divzN // IH. rewrite {2}(divz_eq m (n.+1%:Z * p)) mulrA mulrAC !divzMDl // ?gt_eqF //. rewrite [rhs in _ + rhs]divz_small ?addr0 // ltz_divLR // divz_ge0 //. by rewrite mulrC ltz_pmod ?modz_ge0 ?gt_eqF ?pmulr_lgt0. Qed. Lemma modz_small m d : 0 <= m < d -> (m %% d)%Z = m. Proof. by case: m d => //= m [] // d; rewrite modz_nat => /modn_small->. Qed. Lemma modz_mod m d : ((m %% d)%Z = m %[mod d])%Z. Proof. rewrite -!(modz_abs _ d); case: {d}`|d|%N => [|d]; first by rewrite !modz0. by rewrite modz_small ?modz_ge0 ?ltz_mod. Qed. Lemma modzMDl p m d : (p * d + m = m %[mod d])%Z. Proof. have [-> | d_nz] := eqVneq d 0; first by rewrite mulr0 add0r. by rewrite /modz divzMDl // mulrDl opprD addrACA subrr add0r. Qed. Lemma mulz_modr {p m d} : 0 < p -> p * (m %% d)%Z = ((p * m) %% (p * d))%Z. Proof. case: p => // p p_gt0; rewrite mulrBr; apply: canLR (addrK _) _. by rewrite mulrCA -(divzMpl p_gt0) subrK. Qed. Lemma mulz_modl {p m d} : 0 < p -> (m %% d)%Z * p = ((m * p) %% (d * p))%Z. Proof. by rewrite -!(mulrC p); apply: mulz_modr. Qed. Lemma modzDl m d : (d + m = m %[mod d])%Z. Proof. by rewrite -{1}[d]mul1r modzMDl. Qed. Lemma modzDr m d : (m + d = m %[mod d])%Z. Proof. by rewrite addrC modzDl. Qed. Lemma modzz d : (d %% d)%Z = 0. Proof. by rewrite -{1}[d]addr0 modzDl mod0z. Qed. Lemma modzMl p d : (p * d %% d)%Z = 0. Proof. by rewrite -[p * d]addr0 modzMDl mod0z. Qed. Lemma modzMr p d : (d * p %% d)%Z = 0. Proof. by rewrite mulrC modzMl. Qed. Lemma modzDml m n d : ((m %% d)%Z + n = m + n %[mod d])%Z. Proof. by rewrite {2}(divz_eq m d) -[_ * d + _ + n]addrA modzMDl. Qed. Lemma modzDmr m n d : (m + (n %% d)%Z = m + n %[mod d])%Z. Proof. by rewrite !(addrC m) modzDml. Qed. Lemma modzDm m n d : ((m %% d)%Z + (n %% d)%Z = m + n %[mod d])%Z. Proof. by rewrite modzDml modzDmr. Qed. Lemma eqz_modDl p m n d : (p + m == p + n %[mod d])%Z = (m == n %[mod d])%Z. Proof. have [-> | d_nz] := eqVneq d 0; first by rewrite !modz0 (inj_eq (addrI p)). apply/eqP/eqP=> eq_mn; last by rewrite -modzDmr eq_mn modzDmr. by rewrite -(addKr p m) -modzDmr eq_mn modzDmr addKr. Qed. Lemma eqz_modDr p m n d : (m + p == n + p %[mod d])%Z = (m == n %[mod d])%Z. Proof. by rewrite -!(addrC p) eqz_modDl. Qed. Lemma modzMml m n d : ((m %% d)%Z * n = m * n %[mod d])%Z. Proof. by rewrite {2}(divz_eq m d) [in RHS]mulrDl mulrAC modzMDl. Qed. (* FIXME: rewrite pattern *) Lemma modzMmr m n d : (m * (n %% d)%Z = m * n %[mod d])%Z. Proof. by rewrite !(mulrC m) modzMml. Qed. Lemma modzMm m n d : ((m %% d)%Z * (n %% d)%Z = m * n %[mod d])%Z. Proof. by rewrite modzMml modzMmr. Qed. Lemma modzXm k m d : ((m %% d)%Z ^+ k = m ^+ k %[mod d])%Z. Proof. by elim: k => // k IHk; rewrite !exprS -modzMmr IHk modzMm. Qed. Lemma modzNm m d : (- (m %% d)%Z = - m %[mod d])%Z. Proof. by rewrite -mulN1r modzMmr mulN1r. Qed. Lemma modz_absm m d : ((-1) ^+ (m < 0)%R * (m %% d)%Z = `|m|%:Z %[mod d])%Z. Proof. by rewrite modzMmr -abszEsign. Qed. (** Divisibility **) Lemma dvdzE d m : (d %| m)%Z = (`|d| %| `|m|)%N. Proof. by []. Qed. Lemma dvdz0 d : (d %| 0)%Z. Proof. exact: dvdn0. Qed. Lemma dvd0z n : (0 %| n)%Z = (n == 0). Proof. by rewrite -absz_eq0 -dvd0n. Qed. Lemma dvdz1 d : (d %| 1)%Z = (`|d|%N == 1). Proof. exact: dvdn1. Qed. Lemma dvd1z m : (1 %| m)%Z. Proof. exact: dvd1n. Qed. Lemma dvdzz m : (m %| m)%Z. Proof. exact: dvdnn. Qed. Lemma dvdz_mull d m n : (d %| n)%Z -> (d %| m * n)%Z. Proof. by rewrite !dvdzE abszM; apply: dvdn_mull. Qed. Lemma dvdz_mulr d m n : (d %| m)%Z -> (d %| m * n)%Z. Proof. by move=> d_m; rewrite mulrC dvdz_mull. Qed. #[global] Hint Resolve dvdz0 dvd1z dvdzz dvdz_mull dvdz_mulr : core. Lemma dvdz_mul d1 d2 m1 m2 : (d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2)%Z. Proof. by rewrite !dvdzE !abszM; apply: dvdn_mul. Qed. Lemma dvdz_trans n d m : (d %| n -> n %| m -> d %| m)%Z. Proof. by rewrite !dvdzE; apply: dvdn_trans. Qed. Lemma dvdzP d m : reflect (exists q, m = q * d) (d %| m)%Z. Proof. apply: (iffP dvdnP) => [] [q Dm]; last by exists `|q|%N; rewrite Dm abszM. exists ((-1) ^+ (m < 0)%R * q%:Z * (-1) ^+ (d < 0)%R). by rewrite -!mulrA -abszEsign -PoszM -Dm -intEsign. Qed. Arguments dvdzP {d m}. Lemma dvdz_mod0P d m : reflect (m %% d = 0)%Z (d %| m)%Z. Proof. apply: (iffP dvdzP) => [[q ->] | md0]; first by rewrite modzMl. by rewrite (divz_eq m d) md0 addr0; exists (m %/ d)%Z. Qed. Arguments dvdz_mod0P {d m}. Lemma dvdz_eq d m : (d %| m)%Z = ((m %/ d)%Z * d == m). Proof. by rewrite (sameP dvdz_mod0P eqP) subr_eq0 eq_sym. Qed. Lemma divzK d m : (d %| m)%Z -> (m %/ d)%Z * d = m. Proof. by rewrite dvdz_eq => /eqP. Qed. Lemma lez_divLR d m n : 0 < d -> (d %| m)%Z -> ((m %/ d)%Z <= n) = (m <= n * d). Proof. by move=> /ler_pM2r <- /divzK->. Qed. Lemma ltz_divRL d m n : 0 < d -> (d %| m)%Z -> (n < m %/ d)%Z = (n * d < m). Proof. by move=> /ltr_pM2r/(_ n)<- /divzK->. Qed. Lemma eqz_div d m n : d != 0 -> (d %| m)%Z -> (n == m %/ d)%Z = (n * d == m). Proof. by move=> /mulIf/inj_eq <- /divzK->. Qed. Lemma eqz_mul d m n : d != 0 -> (d %| m)%Z -> (m == n * d) = (m %/ d == n)%Z. Proof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqz_div // eq_sym. Qed. Lemma divz_mulAC d m n : (d %| m)%Z -> (m %/ d)%Z * n = (m * n %/ d)%Z. Proof. have [-> | d_nz] := eqVneq d 0; first by rewrite !divz0 mul0r. by move/divzK=> {2} <-; rewrite mulrAC mulzK. Qed. Lemma mulz_divA d m n : (d %| n)%Z -> m * (n %/ d)%Z = (m * n %/ d)%Z. Proof. by move=> dv_d_m; rewrite !(mulrC m) divz_mulAC. Qed. Lemma mulz_divCA d m n : (d %| m)%Z -> (d %| n)%Z -> m * (n %/ d)%Z = n * (m %/ d)%Z. Proof. by move=> dv_d_m dv_d_n; rewrite mulrC divz_mulAC ?mulz_divA. Qed. Lemma divzA m n p : (p %| n -> n %| m * p -> m %/ (n %/ p)%Z = m * p %/ n)%Z. Proof. move/divzK=> p_dv_n; have [->|] := eqVneq n 0; first by rewrite div0z !divz0. rewrite -{1 2}p_dv_n mulf_eq0 => /norP[pn_nz p_nz] /divzK; rewrite mulrA p_dv_n. by move/mulIf=> {1} <- //; rewrite mulzK. Qed. Lemma divzMA m n p : (n * p %| m -> m %/ (n * p) = (m %/ n)%Z %/ p)%Z. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 !divz0. have [-> | nz_n] := eqVneq n 0; first by rewrite mul0r !divz0 div0z. by move/divzK=> {2} <-; rewrite mulrA mulrAC !mulzK. Qed. Lemma divzAC m n p : (n * p %| m -> (m %/ n)%Z %/ p = (m %/ p)%Z %/ n)%Z. Proof. by move=> np_dv_mn; rewrite -!divzMA // mulrC. Qed. Lemma divzMl p m d : p != 0 -> (d %| m -> p * m %/ (p * d) = m %/ d)%Z. Proof. have [-> | nz_d nz_p] := eqVneq d 0; first by rewrite mulr0 !divz0. by move/divzK=> {1}<-; rewrite mulrCA mulzK ?mulf_neq0. Qed. Lemma divzMr p m d : p != 0 -> (d %| m -> m * p %/ (d * p) = m %/ d)%Z. Proof. by rewrite -!(mulrC p); apply: divzMl. Qed. Lemma dvdz_mul2l p d m : p != 0 -> (p * d %| p * m)%Z = (d %| m)%Z. Proof. by rewrite !dvdzE -absz_gt0 !abszM; apply: dvdn_pmul2l. Qed. Arguments dvdz_mul2l [p d m]. Lemma dvdz_mul2r p d m : p != 0 -> (d * p %| m * p)%Z = (d %| m)%Z. Proof. by rewrite !dvdzE -absz_gt0 !abszM; apply: dvdn_pmul2r. Qed. Arguments dvdz_mul2r [p d m]. Lemma dvdz_exp2l p m n : (m <= n)%N -> (p ^+ m %| p ^+ n)%Z. Proof. by rewrite dvdzE !abszX; apply: dvdn_exp2l. Qed. Lemma dvdz_Pexp2l p m n : `|p| > 1 -> (p ^+ m %| p ^+ n)%Z = (m <= n)%N. Proof. by rewrite dvdzE !abszX ltz_nat; apply: dvdn_Pexp2l. Qed. Lemma dvdz_exp2r m n k : (m %| n -> m ^+ k %| n ^+ k)%Z. Proof. by rewrite !dvdzE !abszX; apply: dvdn_exp2r. Qed. Fact dvdz_zmod_closed d : zmod_closed (dvdz d). Proof. split=> [|_ _ /dvdzP[p ->] /dvdzP[q ->]]; first exact: dvdz0. by rewrite -mulrBl dvdz_mull. Qed. HB.instance Definition _ d := GRing.isZmodClosed.Build int (dvdz d) (dvdz_zmod_closed d). Lemma dvdz_exp k d m : (0 < k)%N -> (d %| m -> d %| m ^+ k)%Z. Proof. by case: k => // k _ d_dv_m; rewrite exprS dvdz_mulr. Qed. Lemma eqz_mod_dvd d m n : (m == n %[mod d])%Z = (d %| m - n)%Z. Proof. apply/eqP/dvdz_mod0P=> eq_mn. by rewrite -modzDml eq_mn modzDml subrr mod0z. by rewrite -(subrK n m) -modzDml eq_mn add0r. Qed. Lemma divzDl m n d : (d %| m)%Z -> ((m + n) %/ d)%Z = (m %/ d)%Z + (n %/ d)%Z. Proof. have [-> | d_nz] := eqVneq d 0; first by rewrite !divz0. by move/divzK=> {1}<-; rewrite divzMDl. Qed. Lemma divzDr m n d : (d %| n)%Z -> ((m + n) %/ d)%Z = (m %/ d)%Z + (n %/ d)%Z. Proof. by move=> dv_n; rewrite addrC divzDl // addrC. Qed. Lemma dvdz_pcharf (R : nzRingType) p : p \in [pchar R] -> forall n : int, (p %| n)%Z = (n%:~R == 0 :> R). Proof. move=> pcharRp [] n; rewrite [LHS](dvdn_pcharf pcharRp)//. by rewrite NegzE abszN rmorphN// oppr_eq0. Qed. #[deprecated(since="mathcomp 2.4.0", note="Use dvdz_pcharf instead.")] Notation dvdz_charf chRp := (dvdz_pcharf chRp). (* Greatest common divisor *) Lemma gcdzz m : gcdz m m = `|m|%:Z. Proof. by rewrite /gcdz gcdnn. Qed. Lemma gcdzC : commutative gcdz. Proof. by move=> m n; rewrite /gcdz gcdnC. Qed. Lemma gcd0z m : gcdz 0 m = `|m|%:Z. Proof. by rewrite /gcdz gcd0n. Qed. Lemma gcdz0 m : gcdz m 0 = `|m|%:Z. Proof. by rewrite /gcdz gcdn0. Qed. Lemma gcd1z : left_zero 1 gcdz. Proof. by move=> m; rewrite /gcdz gcd1n. Qed. Lemma gcdz1 : right_zero 1 gcdz. Proof. by move=> m; rewrite /gcdz gcdn1. Qed. Lemma dvdz_gcdr m n : (gcdz m n %| n)%Z. Proof. exact: dvdn_gcdr. Qed. Lemma dvdz_gcdl m n : (gcdz m n %| m)%Z. Proof. exact: dvdn_gcdl. Qed. Lemma gcdz_eq0 m n : (gcdz m n == 0) = (m == 0) && (n == 0). Proof. by rewrite -absz_eq0 eqn0Ngt gcdn_gt0 !negb_or -!eqn0Ngt !absz_eq0. Qed. Lemma gcdNz m n : gcdz (- m) n = gcdz m n. Proof. by rewrite /gcdz abszN. Qed. Lemma gcdzN m n : gcdz m (- n) = gcdz m n. Proof. by rewrite /gcdz abszN. Qed. Lemma gcdz_modr m n : gcdz m (n %% m)%Z = gcdz m n. Proof. rewrite -modz_abs /gcdz; move/absz: m => m. have [-> | m_gt0] := posnP m; first by rewrite modz0. case: n => n; first by rewrite modz_nat gcdn_modr. rewrite modNz_nat // NegzE abszN {2}(divn_eq n m) -addnS gcdnMDl. rewrite -addrA -opprD -intS /=; set m1 := _.+1. have le_m1m: (m1 <= m)%N by apply: ltn_pmod. by rewrite subzn // !(gcdnC m) -{2 3}(subnK le_m1m) gcdnDl gcdnDr gcdnC. Qed. Lemma gcdz_modl m n : gcdz (m %% n)%Z n = gcdz m n. Proof. by rewrite -!(gcdzC n) gcdz_modr. Qed. Lemma gcdzMDl q m n : gcdz m (q * m + n) = gcdz m n. Proof. by rewrite -gcdz_modr modzMDl gcdz_modr. Qed. Lemma gcdzDl m n : gcdz m (m + n) = gcdz m n. Proof. by rewrite -{2}(mul1r m) gcdzMDl. Qed. Lemma gcdzDr m n : gcdz m (n + m) = gcdz m n. Proof. by rewrite addrC gcdzDl. Qed. Lemma gcdzMl n m : gcdz n (m * n) = `|n|%:Z. Proof. by rewrite -[m * n]addr0 gcdzMDl gcdz0. Qed. Lemma gcdzMr n m : gcdz n (n * m) = `|n|%:Z. Proof. by rewrite mulrC gcdzMl. Qed. Lemma gcdz_idPl {m n} : reflect (gcdz m n = `|m|%:Z) (m %| n)%Z. Proof. by apply: (iffP gcdn_idPl) => [<- | []]. Qed. Lemma gcdz_idPr {m n} : reflect (gcdz m n = `|n|%:Z) (n %| m)%Z. Proof. by rewrite gcdzC; apply: gcdz_idPl. Qed. Lemma expz_min e m n : e >= 0 -> e ^+ minn m n = gcdz (e ^+ m) (e ^+ n). Proof. by case: e => // e _; rewrite /gcdz !abszX -expn_min -natz -natrX !natz. Qed. Lemma dvdz_gcd p m n : (p %| gcdz m n)%Z = (p %| m)%Z && (p %| n)%Z. Proof. exact: dvdn_gcd. Qed. Lemma gcdzAC : right_commutative gcdz. Proof. by move=> m n p; rewrite /gcdz gcdnAC. Qed. Lemma gcdzA : associative gcdz. Proof. by move=> m n p; rewrite /gcdz gcdnA. Qed. Lemma gcdzCA : left_commutative gcdz. Proof. by move=> m n p; rewrite /gcdz gcdnCA. Qed. Lemma gcdzACA : interchange gcdz gcdz. Proof. by move=> m n p q; rewrite /gcdz gcdnACA. Qed. Lemma mulz_gcdr m n p : `|m|%:Z * gcdz n p = gcdz (m * n) (m * p). Proof. by rewrite -PoszM muln_gcdr -!abszM. Qed. Lemma mulz_gcdl m n p : gcdz m n * `|p|%:Z = gcdz (m * p) (n * p). Proof. by rewrite -PoszM muln_gcdl -!abszM. Qed. Lemma mulz_divCA_gcd n m : n * (m %/ gcdz n m)%Z = m * (n %/ gcdz n m)%Z. Proof. by rewrite mulz_divCA ?dvdz_gcdl ?dvdz_gcdr. Qed. (* Least common multiple *) Lemma dvdz_lcmr m n : (n %| lcmz m n)%Z. Proof. exact: dvdn_lcmr. Qed. Lemma dvdz_lcml m n : (m %| lcmz m n)%Z. Proof. exact: dvdn_lcml. Qed. Lemma dvdz_lcm d1 d2 m : ((lcmn d1 d2 %| m) = (d1 %| m) && (d2 %| m))%Z. Proof. exact: dvdn_lcm. Qed. Lemma lcmzC : commutative lcmz. Proof. by move=> m n; rewrite /lcmz lcmnC. Qed. Lemma lcm0z : left_zero 0 lcmz. Proof. by move=> x; rewrite /lcmz absz0 lcm0n. Qed. Lemma lcmz0 : right_zero 0 lcmz. Proof. by move=> x; rewrite /lcmz absz0 lcmn0. Qed. Lemma lcmz_ge0 m n : 0 <= lcmz m n. Proof. by []. Qed. Lemma lcmz_neq0 m n : (lcmz m n != 0) = (m != 0) && (n != 0). Proof. have [->|m_neq0] := eqVneq m 0; first by rewrite lcm0z. have [->|n_neq0] := eqVneq n 0; first by rewrite lcmz0. by rewrite gt_eqF// [0 < _]lcmn_gt0 !absz_gt0 m_neq0 n_neq0. Qed. (* Coprime factors *) Lemma coprimezE m n : coprimez m n = coprime `|m| `|n|. Proof. by []. Qed. Lemma coprimez_sym : symmetric coprimez. Proof. by move=> m n; apply: coprime_sym. Qed. Lemma coprimeNz m n : coprimez (- m) n = coprimez m n. Proof. by rewrite coprimezE abszN. Qed. Lemma coprimezN m n : coprimez m (- n) = coprimez m n. Proof. by rewrite coprimezE abszN. Qed. Variant egcdz_spec m n : int * int -> Type := EgcdzSpec u v of u * m + v * n = gcdz m n & coprimez u v : egcdz_spec m n (u, v). Lemma egcdzP m n : egcdz_spec m n (egcdz m n). Proof. rewrite /egcdz; have [-> | m_nz] := eqVneq. by split; [rewrite -abszEsign gcd0z | rewrite coprimezE absz_sign]. have m_gt0 : (`|m| > 0)%N by rewrite absz_gt0. case: egcdnP (coprime_egcdn `|n| m_gt0) => //= u v Duv _ co_uv; split. rewrite !mulNr -!mulrA mulrCA -abszEsg mulrCA -abszEsign. by rewrite -!PoszM Duv addnC PoszD addrK. by rewrite coprimezE abszM absz_sg m_nz mul1n mulNr abszN abszMsign. Qed. Lemma Bezoutz m n : {u : int & {v : int | u * m + v * n = gcdz m n}}. Proof. by exists (egcdz m n).1, (egcdz m n).2; case: egcdzP. Qed. Lemma coprimezP m n : reflect (exists uv, uv.1 * m + uv.2 * n = 1) (coprimez m n). Proof. apply: (iffP eqP) => [<-| [[u v] /= Duv]]. by exists (egcdz m n); case: egcdzP. congr _%:Z; apply: gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m. by rewrite -(dvdzE d 1) -Duv [m]intEsg [n]intEsg rpredD ?dvdz_mull. Qed. Lemma Gauss_dvdz m n p : coprimez m n -> (m * n %| p)%Z = (m %| p)%Z && (n %| p)%Z. Proof. by move/Gauss_dvd <-; rewrite -abszM. Qed. Lemma Gauss_dvdzr m n p : coprimez m n -> (m %| n * p)%Z = (m %| p)%Z. Proof. by rewrite dvdzE abszM => /Gauss_dvdr->. Qed. Lemma Gauss_dvdzl m n p : coprimez m p -> (m %| n * p)%Z = (m %| n)%Z. Proof. by rewrite mulrC; apply: Gauss_dvdzr. Qed. Lemma Gauss_gcdzr p m n : coprimez p m -> gcdz p (m * n) = gcdz p n. Proof. by rewrite /gcdz abszM => /Gauss_gcdr->. Qed. Lemma Gauss_gcdzl p m n : coprimez p n -> gcdz p (m * n) = gcdz p m. Proof. by move=> co_pn; rewrite mulrC Gauss_gcdzr. Qed. Lemma coprimezMr p m n : coprimez p (m * n) = coprimez p m && coprimez p n. Proof. by rewrite -coprimeMr -abszM. Qed. Lemma coprimezMl p m n : coprimez (m * n) p = coprimez m p && coprimez n p. Proof. by rewrite -coprimeMl -abszM. Qed. Lemma coprimez_pexpl k m n : (0 < k)%N -> coprimez (m ^+ k) n = coprimez m n. Proof. by rewrite /coprimez /gcdz abszX; apply: coprime_pexpl. Qed. Lemma coprimez_pexpr k m n : (0 < k)%N -> coprimez m (n ^+ k) = coprimez m n. Proof. by move=> k_gt0; rewrite !(coprimez_sym m) coprimez_pexpl. Qed. Lemma coprimezXl k m n : coprimez m n -> coprimez (m ^+ k) n. Proof. by rewrite /coprimez /gcdz abszX; apply: coprimeXl. Qed. Lemma coprimezXr k m n : coprimez m n -> coprimez m (n ^+ k). Proof. by rewrite !(coprimez_sym m); apply: coprimezXl. Qed. Lemma coprimez_dvdl m n p : (m %| n)%N -> coprimez n p -> coprimez m p. Proof. exact: coprime_dvdl. Qed. Lemma coprimez_dvdr m n p : (m %| n)%N -> coprimez p n -> coprimez p m. Proof. exact: coprime_dvdr. Qed. Lemma dvdz_pexp2r m n k : (k > 0)%N -> (m ^+ k %| n ^+ k)%Z = (m %| n)%Z. Proof. by rewrite dvdzE !abszX; apply: dvdn_pexp2r. Qed. Section Chinese. (***********************************************************************) (* The chinese remainder theorem *) (***********************************************************************) Variables m1 m2 : int. Hypothesis co_m12 : coprimez m1 m2. Lemma zchinese_remainder x y : (x == y %[mod m1 * m2])%Z = (x == y %[mod m1])%Z && (x == y %[mod m2])%Z. Proof. by rewrite !eqz_mod_dvd Gauss_dvdz. Qed. (***********************************************************************) (* A function that solves the chinese remainder problem *) (***********************************************************************) Definition zchinese r1 r2 := r1 * m2 * (egcdz m1 m2).2 + r2 * m1 * (egcdz m1 m2).1. Lemma zchinese_modl r1 r2 : (zchinese r1 r2 = r1 %[mod m1])%Z. Proof. rewrite /zchinese; have [u v /= Duv _] := egcdzP m1 m2. rewrite -{2}[r1]mulr1 -((gcdz _ _ =P 1) co_m12) -Duv. by rewrite mulrDr mulrAC addrC (mulrAC r2) !mulrA !modzMDl. Qed. Lemma zchinese_modr r1 r2 : (zchinese r1 r2 = r2 %[mod m2])%Z. Proof. rewrite /zchinese; have [u v /= Duv _] := egcdzP m1 m2. rewrite -{2}[r2]mulr1 -((gcdz _ _ =P 1) co_m12) -Duv. by rewrite mulrAC modzMDl mulrAC addrC mulrDr !mulrA modzMDl. Qed. Lemma zchinese_mod x : (x = zchinese (x %% m1)%Z (x %% m2)%Z %[mod m1 * m2])%Z. Proof. apply/eqP; rewrite zchinese_remainder //. by rewrite zchinese_modl zchinese_modr !modz_mod !eqxx. Qed. End Chinese. Section ZpolyScale. Definition zcontents (p : {poly int}) : int := sgz (lead_coef p) * \big[gcdn/0]_(i < size p) `|(p`_i)%R|%N. Lemma sgz_contents p : sgz (zcontents p) = sgz (lead_coef p). Proof. rewrite /zcontents mulrC sgzM sgz_id; set d := _%:Z. have [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 mulr0. rewrite gtr0_sgz ?mul1r // ltz_nat polySpred ?big_ord_recr //= -lead_coefE. by rewrite gcdn_gt0 orbC absz_gt0 lead_coef_eq0 nz_p. Qed. Lemma zcontents_eq0 p : (zcontents p == 0) = (p == 0). Proof. by rewrite -sgz_eq0 sgz_contents sgz_eq0 lead_coef_eq0. Qed. Lemma zcontents0 : zcontents 0 = 0. Proof. by apply/eqP; rewrite zcontents_eq0. Qed. Lemma zcontentsZ a p : zcontents (a *: p) = a * zcontents p. Proof. have [-> | nz_a] := eqVneq a 0; first by rewrite scale0r mul0r zcontents0. rewrite {2}[a]intEsg mulrCA -mulrA -PoszM big_distrr /= mulrCA mulrA -sgzM. rewrite -lead_coefZ; congr (_ * _%:Z); rewrite size_scale //. by apply: eq_bigr => i _; rewrite coefZ abszM. Qed. Lemma zcontents_monic p : p \is monic -> zcontents p = 1. Proof. move=> mon_p; rewrite /zcontents polySpred ?monic_neq0 //. by rewrite big_ord_recr /= -lead_coefE (monicP mon_p) gcdn1. Qed. Lemma dvdz_contents a p : (a %| zcontents p)%Z = (p \is a polyOver (dvdz a)). Proof. rewrite dvdzE abszM absz_sg lead_coef_eq0. have [-> | nz_p] := eqVneq; first by rewrite mul0n dvdn0 rpred0. rewrite mul1n; apply/dvdn_biggcdP/(all_nthP 0)=> a_dv_p i ltip /=. exact: (a_dv_p (Ordinal ltip)). exact: a_dv_p. Qed. Lemma map_poly_divzK {a} p : p \is a polyOver (dvdz a) -> a *: map_poly (divz^~ a) p = p. Proof. move/polyOverP=> a_dv_p; apply/polyP=> i. by rewrite coefZ coef_map_id0 ?div0z // mulrC divzK. Qed. Lemma polyOver_dvdzP a p : reflect (exists q, p = a *: q) (p \is a polyOver (dvdz a)). Proof. apply: (iffP idP) => [/map_poly_divzK | [q ->]]. by exists (map_poly (divz^~ a) p). by apply/polyOverP=> i; rewrite coefZ dvdz_mulr. Qed. Definition zprimitive p := map_poly (divz^~ (zcontents p)) p. Lemma zpolyEprim p : p = zcontents p *: zprimitive p. Proof. by rewrite map_poly_divzK // -dvdz_contents. Qed. Lemma zprimitive0 : zprimitive 0 = 0. Proof. by apply/polyP=> i; rewrite coef0 coef_map_id0 ?div0z // zcontents0 divz0. Qed. Lemma zprimitive_eq0 p : (zprimitive p == 0) = (p == 0). Proof. apply/idP/idP=> /eqP p0; first by rewrite [p]zpolyEprim p0 scaler0. by rewrite p0 zprimitive0. Qed. Lemma size_zprimitive p : size (zprimitive p) = size p. Proof. have [-> | ] := eqVneq p 0; first by rewrite zprimitive0. by rewrite {1 3}[p]zpolyEprim scale_poly_eq0 => /norP[/size_scale-> _]. Qed. Lemma sgz_lead_primitive p : sgz (lead_coef (zprimitive p)) = (p != 0). Proof. have [-> | nz_p] := eqVneq; first by rewrite zprimitive0 lead_coef0. apply: (@mulfI _ (sgz (zcontents p))); first by rewrite sgz_eq0 zcontents_eq0. by rewrite -sgzM mulr1 -lead_coefZ -zpolyEprim sgz_contents. Qed. Lemma zcontents_primitive p : zcontents (zprimitive p) = (p != 0). Proof. have [-> | nz_p] := eqVneq; first by rewrite zprimitive0 zcontents0. apply: (@mulfI _ (zcontents p)); first by rewrite zcontents_eq0. by rewrite mulr1 -zcontentsZ -zpolyEprim. Qed. Lemma zprimitive_id p : zprimitive (zprimitive p) = zprimitive p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !zprimitive0. by rewrite {2}[zprimitive p]zpolyEprim zcontents_primitive nz_p scale1r. Qed. Lemma zprimitive_monic p : p \in monic -> zprimitive p = p. Proof. by move=> mon_p; rewrite {2}[p]zpolyEprim zcontents_monic ?scale1r. Qed. Lemma zprimitiveZ a p : a != 0 -> zprimitive (a *: p) = zprimitive p. Proof. have [-> | nz_p nz_a] := eqVneq p 0; first by rewrite scaler0. apply: (@mulfI _ (a * zcontents p)%:P). by rewrite polyC_eq0 mulf_neq0 ?zcontents_eq0. by rewrite -{1}zcontentsZ !mul_polyC -zpolyEprim -scalerA -zpolyEprim. Qed. Lemma zprimitive_min p a q : p != 0 -> p = a *: q -> {b | sgz b = sgz (lead_coef q) & q = b *: zprimitive p}. Proof. move=> nz_p Dp; have /dvdzP/sig_eqW[b Db]: (a %| zcontents p)%Z. by rewrite dvdz_contents; apply/polyOver_dvdzP; exists q. suffices ->: q = b *: zprimitive p. by rewrite lead_coefZ sgzM sgz_lead_primitive nz_p mulr1; exists b. apply: (@mulfI _ a%:P). by apply: contraNneq nz_p; rewrite Dp -mul_polyC => ->; rewrite mul0r. by rewrite !mul_polyC -Dp scalerA mulrC -Db -zpolyEprim. Qed. Lemma zprimitive_irr p a q : p != 0 -> zprimitive p = a *: q -> a = sgz (lead_coef q). Proof. move=> nz_p Dp; have: p = (a * zcontents p) *: q. by rewrite mulrC -scalerA -Dp -zpolyEprim. case/zprimitive_min=> // b <- /eqP. rewrite Dp -{1}[q]scale1r scalerA -subr_eq0 -scalerBl scale_poly_eq0 subr_eq0. have{Dp} /negPf->: q != 0. by apply: contraNneq nz_p; rewrite -zprimitive_eq0 Dp => ->; rewrite scaler0. by case: b a => [[|[|b]] | [|b]] [[|[|a]] | [|a]] //; rewrite mulr0. Qed. Lemma zcontentsM p q : zcontents (p * q) = zcontents p * zcontents q. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, zcontents0). have [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, zcontents0). rewrite -[zcontents q]mulr1 {1}[p]zpolyEprim {1}[q]zpolyEprim. rewrite -scalerAl -scalerAr !zcontentsZ; congr (_ * (_ * _)). rewrite [zcontents _]intEsg sgz_contents lead_coefM sgzM !sgz_lead_primitive. apply/eqP; rewrite nz_p nz_q !mul1r [_ == _]eqn_leq absz_gt0 zcontents_eq0. rewrite mulf_neq0 ?zprimitive_eq0 // andbT leqNgt. apply/negP=> /pdivP[r r_pr r_dv_d]; pose to_r : int -> 'F_r := intr. have nz_prim_r q1: q1 != 0 -> map_poly to_r (zprimitive q1) != 0. move=> nz_q1; apply: contraTneq (prime_gt1 r_pr) => r_dv_q1. rewrite -leqNgt dvdn_leq // -(dvdzE r true) -nz_q1 -zcontents_primitive. rewrite dvdz_contents; apply/polyOverP=> i /=; rewrite dvdzE /=. have /polyP/(_ i)/eqP := r_dv_q1; rewrite coef_map coef0 /=. rewrite {1}[_`_i]intEsign rmorphM /= rmorph_sign /= mulf_eq0 signr_eq0 /=. by rewrite -val_eqE /= val_Fp_nat. suffices{nz_prim_r} /idPn[]: map_poly to_r (zprimitive p * zprimitive q) == 0. by rewrite rmorphM mulf_neq0 ?nz_prim_r. rewrite [_ * _]zpolyEprim [zcontents _]intEsign mulrC -scalerA map_polyZ /=. by rewrite scale_poly_eq0 -val_eqE /= val_Fp_nat ?(eqnP r_dv_d). Qed. Lemma zprimitiveM p q : zprimitive (p * q) = zprimitive p * zprimitive q. Proof. have [pq_0|] := eqVneq (p * q) 0. rewrite pq_0; move/eqP: pq_0; rewrite mulf_eq0. by case/pred2P=> ->; rewrite !zprimitive0 (mul0r, mulr0). rewrite -zcontents_eq0 -polyC_eq0 => /mulfI; apply; rewrite !mul_polyC. by rewrite -zpolyEprim zcontentsM -scalerA scalerAr scalerAl -!zpolyEprim. Qed. Lemma dvdpP_int p q : p %| q -> {r | q = zprimitive p * r}. Proof. case/Pdiv.Idomain.dvdpP/sig2_eqW=> [[c r] /= nz_c Dpr]. exists (zcontents q *: zprimitive r); rewrite -scalerAr. by rewrite -zprimitiveM mulrC -Dpr zprimitiveZ // -zpolyEprim. Qed. End ZpolyScale. (* Integral spans. *) Lemma int_Smith_normal_form m n (M : 'M[int]_(m, n)) : {L : 'M[int]_m & L \in unitmx & {R : 'M[int]_n & R \in unitmx & {d : seq int | sorted dvdz d & M = L *m (\matrix_(i, j) (d`_i *+ (i == j :> nat))) *m R}}}. Proof. move: {2}_.+1 (ltnSn (m + n)) => mn. elim: mn => // mn IHmn in m n M *; rewrite ltnS => le_mn. have [[i j] nzMij | no_ij] := pickP (fun k => M k.1 k.2 != 0); last first. do 2![exists 1%:M; first exact: unitmx1]; exists nil => //=. apply/matrixP=> i j; apply/eqP; rewrite mulmx1 mul1mx mxE nth_nil mul0rn. exact: negbFE (no_ij (i, j)). do [case: m i => [[]//|m] i; case: n j => [[]//|n] j /=] in M nzMij le_mn *. wlog Dj: j M nzMij / j = 0; last rewrite {j}Dj in nzMij. case/(_ 0 (xcol j 0 M)); rewrite ?mxE ?tpermR // => L uL [R uR [d dvD dM]]. exists L => //; exists (xcol j 0 R); last exists d => //=. by rewrite xcolE unitmx_mul uR unitmx_perm. by rewrite xcolE !mulmxA -dM xcolE -mulmxA -perm_mxM tperm2 perm_mx1 mulmx1. move Da: (M i 0) nzMij => a nz_a. have [A leA] := ubnP `|a|; elim: A => // A IHa in a leA m n M i Da nz_a le_mn *. wlog [j a'Mij]: m n M i Da le_mn / {j | ~~ (a %| M i j)%Z}; last first. have nz_j: j != 0 by apply: contraNneq a'Mij => ->; rewrite Da. case: n => [[[]//]|n] in j le_mn nz_j M a'Mij Da *. wlog{nz_j} Dj: j M a'Mij Da / j = 1; last rewrite {j}Dj in a'Mij. case/(_ 1 (xcol j 1 M)); rewrite ?mxE ?tpermR ?tpermD //. move=> L uL [R uR [d dvD dM]]; exists L => //. exists (xcol j 1 R); first by rewrite xcolE unitmx_mul uR unitmx_perm. exists d; rewrite //= xcolE !mulmxA -dM xcolE -mulmxA -perm_mxM tperm2. by rewrite perm_mx1 mulmx1. have [u [v]] := Bezoutz a (M i 1); set b := gcdz _ _ => Db. have{leA} ltA: (`|b| < A)%N. rewrite -ltnS (leq_trans _ leA) // ltnS ltn_neqAle andbC. rewrite dvdn_leq ?absz_gt0 ? dvdn_gcdl //=. by rewrite (contraNneq _ a'Mij) ?dvdzE // => <-; apply: dvdn_gcdr. pose t2 := [fun j : 'I_2 => [tuple _; _]`_j : int]; pose a1 := M i 1. pose Uul := \matrix_(k, j) t2 (t2 u (- (a1 %/ b)%Z) j) (t2 v (a %/ b)%Z j) k. pose U : 'M_(2 + n) := block_mx Uul 0 0 1%:M; pose M1 := M *m U. have{nz_a} nz_b: b != 0 by rewrite gcdz_eq0 (negPf nz_a). have uU: U \in unitmx. rewrite unitmxE det_ublock det1 (expand_det_col _ 0) big_ord_recl big_ord1. do 2!rewrite /cofactor [row' _ _]mx11_scalar !mxE det_scalar1 /=. rewrite mulr1 mul1r mulN1r opprK -[_ + _](mulzK _ nz_b) mulrDl. by rewrite -!mulrA !divzK ?dvdz_gcdl ?dvdz_gcdr // Db divzz nz_b unitr1. have{} Db: M1 i 0 = b. rewrite /M1 -(lshift0 n 1) [U]block_mxEh mul_mx_row row_mxEl. rewrite -[M](@hsubmxK _ _ 2) (@mul_row_col _ _ 2) mulmx0 addr0 !mxE /=. rewrite big_ord_recl big_ord1 !mxE /= [lshift _ _]((_ =P 0) _) // Da. by rewrite [lshift _ _]((_ =P 1) _) // mulrC -(mulrC v). have [L uL [R uR [d dvD dM1]]] := IHa b ltA _ _ M1 i Db nz_b le_mn. exists L => //; exists (R *m invmx U); last exists d => //. by rewrite unitmx_mul uR unitmx_inv. by rewrite mulmxA -dM1 mulmxK. move=> {A leA}IHa; wlog Di: i M Da / i = 0; last rewrite {i}Di in Da. case/(_ 0 (xrow i 0 M)); rewrite ?mxE ?tpermR // => L uL [R uR [d dvD dM]]. exists (xrow i 0 L); first by rewrite xrowE unitmx_mul unitmx_perm. exists R => //; exists d; rewrite //= xrowE -!mulmxA (mulmxA L) -dM xrowE. by rewrite mulmxA -perm_mxM tperm2 perm_mx1 mul1mx. without loss /forallP a_dvM0: / [forall j, a %| M 0%R j]%Z. case: (altP forallP) => [_ IH|/forallPn/sigW/IHa IH _]; exact: IH. without loss{Da a_dvM0} Da: M / forall j, M 0 j = a. pose Uur := col' 0 (\row_j (1 - (M 0%R j %/ a)%Z)). pose U : 'M_(1 + n) := block_mx 1 Uur 0 1%:M; pose M1 := M *m U. have uU: U \in unitmx by rewrite unitmxE det_ublock !det1 mulr1. case/(_ (M *m U)) => [j | L uL [R uR [d dvD dM]]]. rewrite -(lshift0 m 0) -[M](@submxK _ 1 _ 1) (@mulmx_block _ 1 m 1). rewrite (@col_mxEu _ 1) !mulmx1 mulmx0 addr0 [ulsubmx _]mx11_scalar. rewrite mul_scalar_mx !mxE !lshift0 Da. case: splitP => [j0 _ | j1 Dj]; rewrite ?ord1 !mxE // lshift0 rshift1. by rewrite mulrBr mulr1 mulrC divzK ?subrK. exists L => //; exists (R * U^-1); first by rewrite unitmx_mul uR unitmx_inv. by exists d; rewrite //= mulmxA -dM mulmxK. without loss{IHa} /forallP/(_ (_, _))/= a_dvM: / [forall k, a %| M k.1 k.2]%Z. case: (altP forallP) => [_|/forallPn/sigW [[i j] /= a'Mij] _]; first exact. have [|||L uL [R uR [d dvD dM]]] := IHa _ _ M^T j; rewrite ?mxE 1?addnC //. by exists i; rewrite mxE. exists R^T; last exists L^T; rewrite ?unitmx_tr //; exists d => //. rewrite -[M]trmxK dM !trmx_mul mulmxA; congr (_ *m _ *m _). by apply/matrixP=> i1 j1 /[!mxE]; case: eqVneq => // ->. without loss{nz_a a_dvM} a1: M a Da / a = 1. pose M1 := map_mx (divz^~ a) M; case/(_ M1 1)=> // [k|L uL [R uR [d dvD dM]]]. by rewrite !mxE Da divzz nz_a. exists L => //; exists R => //; exists [seq a * x | x <- d]. case: d dvD {dM} => //= x d; elim: d x => //= y d IHd x /andP[dv_xy /IHd]. by rewrite [dvdz _ _]dvdz_mul2l ?[_ \in _]dv_xy. have ->: M = a *: M1 by apply/matrixP=> i j; rewrite !mxE mulrC divzK ?a_dvM. rewrite dM scalemxAl scalemxAr; congr (_ *m _ *m _). apply/matrixP=> i j; rewrite !mxE mulrnAr; congr (_ *+ _). have [lt_i_d | le_d_i] := ltnP i (size d); first by rewrite (nth_map 0). by rewrite !nth_default ?size_map ?mulr0. rewrite {a}a1 -[m.+1]/(1 + m)%N -[n.+1]/(1 + n)%N in M Da *. pose Mu := ursubmx M; pose Ml := dlsubmx M. have{} Da: ulsubmx M = 1 by rewrite [_ M]mx11_scalar !mxE !lshift0 Da. pose M1 := - (Ml *m Mu) + drsubmx M. have [|L uL [R uR [d dvD dM1]]] := IHmn m n M1; first by rewrite -addnS ltnW. exists (block_mx 1 0 Ml L). by rewrite unitmxE det_lblock det_scalar1 mul1r. exists (block_mx 1 Mu 0 R). by rewrite unitmxE det_ublock det_scalar1 mul1r. exists (1 :: d); set D1 := \matrix_(i, j) _ in dM1. by rewrite /= path_min_sorted //; apply/allP => g _; apply: dvd1n. rewrite [D in _ *m D *m _](_ : _ = block_mx 1 0 0 D1); last first. by apply/matrixP=> i j; do 3?[rewrite ?mxE ?ord1 //=; case: splitP => ? ->]. rewrite !mulmx_block !(mul0mx, mulmx0, addr0) !mulmx1 add0r mul1mx -Da -dM1. by rewrite addNKr submxK. Qed.
Preserves.lean
/- Copyright (c) 2025 Robin Carlier. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robin Carlier -/ import Mathlib.CategoryTheory.Functor.KanExtension.Adjunction import Mathlib.CategoryTheory.Limits.Preserves.Basic /-! # Preservation of Kan extensions Given functors `F : A ⥤ B`, `L : B ⥤ C`, and `G : B ⥤ D`, we introduce a typeclass `G.PreservesLeftKanExtension F L` which encodes the fact that the left Kan extension of `F` along `L` is preserved by the functor `G`. When the Kan extension is pointwise, it suffices that `G` preserves (co)limits of the relevant diagrams. We introduce the dual typeclass `G.PreservesRightKanExtension`. -/ namespace CategoryTheory.Functor variable {A B C D : Type*} [Category A] [Category B] [Category C] [Category D] (G : B ⥤ D) (F : A ⥤ B) (L : A ⥤ C) noncomputable section section LeftKanExtension /-- `G.PreservesLeftKanExtension F L` asserts that `G` preserves all left Kan extensions of `F` along `L`. See `PreservesLeftKanExtension.mk_of_preserves_isLeftKanExtension` for a constructor taking a single left Kan extension as input. -/ class PreservesLeftKanExtension where preserves : ∀ (F' : C ⥤ B) (α : F ⟶ L ⋙ F') [IsLeftKanExtension F' α], IsLeftKanExtension (F' ⋙ G) <| whiskerRight α G ≫ (Functor.associator _ _ _).hom /-- Alternative constructor for `PreservesLeftKanExtension`, phrased in terms of `LeftExtension.IsUniversal` instead. See `PreservesLeftKanExtension.mk_of_preserves_isUniversal` for a similar constructor taking as input a single `LeftExtension`. -/ lemma PreservesLeftKanExtension.mk' (preserves : ∀ {E : LeftExtension L F}, E.IsUniversal → Nonempty (LeftExtension.postcompose₂ L F G |>.obj E).IsUniversal) : G.PreservesLeftKanExtension F L where preserves _ _ h := ⟨⟨Limits.IsInitial.equivOfIso (LeftExtension.postcompose₂ObjMkIso _ _) <| (preserves h.nonempty_isUniversal.some).some⟩⟩ /-- Show that `G` preserves left Kan extensions if it maps some left Kan extension to a left Kan extension. -/ lemma PreservesLeftKanExtension.mk_of_preserves_isLeftKanExtension (F' : C ⥤ B) (α : F ⟶ L ⋙ F') [IsLeftKanExtension F' α] (h : IsLeftKanExtension (F' ⋙ G) <| whiskerRight α G ≫ (Functor.associator _ _ _).hom) : G.PreservesLeftKanExtension F L := .mk fun F'' α' h ↦ isLeftKanExtension_of_iso (isoWhiskerRight (leftKanExtensionUnique F' α F'' α') G) (whiskerRight α G ≫ (Functor.associator _ _ _).hom) (whiskerRight α' G ≫ (Functor.associator _ _ _).hom) (by ext x; simp [← G.map_comp]) /-- Show that `G` preserves left Kan extensions if it maps some left Kan extension to a left Kan extension, phrased in terms of `IsUniversal`. -/ lemma PreservesLeftKanExtension.mk_of_preserves_isUniversal (E : LeftExtension L F) (hE : E.IsUniversal) (h : Nonempty (LeftExtension.postcompose₂ L F G |>.obj E).IsUniversal) : G.PreservesLeftKanExtension F L := .mk' G F L fun hE' ↦ ⟨Limits.IsInitial.equivOfIso (LeftExtension.postcompose₂ L F G|>.mapIso <| Limits.IsInitial.uniqueUpToIso hE hE') h.some⟩ attribute [instance] PreservesLeftKanExtension.preserves /-- `G.PreservesLeftKanExtensionAt F L c` asserts that `G` preserves all pointwise left Kan extensions of `F` along `L` at the point `c`. -/ class PreservesPointwiseLeftKanExtensionAt (c : C) where /-- `G` preserves every pointwise extensions of `F` along `L` at `c`. -/ preserves : ∀ (E : LeftExtension L F), E.IsPointwiseLeftKanExtensionAt c → Nonempty ((LeftExtension.postcompose₂ L F G|>.obj E).IsPointwiseLeftKanExtensionAt c) /-- `G.PreservesLeftKanExtension F L` asserts that `G` preserves all pointwise left Kan extensions of `F` along `L`. -/ abbrev PreservesPointwiseLeftKanExtension := ∀ c : C, PreservesPointwiseLeftKanExtensionAt G F L c variable {F L} in /-- Given a pointwise left Kan extension of `F` along `L` at `c`, exhibits `(LeftExtension.whiskerRight L F G).obj E` as a pointwise left Kan extension of `F ⋙ G` along `L` at `c`. -/ def LeftExtension.IsPointwiseLeftKanExtensionAt.postcompose {c : C} [PreservesPointwiseLeftKanExtensionAt G F L c] {E : LeftExtension L F} (hE : E.IsPointwiseLeftKanExtensionAt c) : LeftExtension.postcompose₂ L F G|>.obj E|>.IsPointwiseLeftKanExtensionAt c := PreservesPointwiseLeftKanExtensionAt.preserves E hE|>.some variable {F L} in /-- Given a pointwise left Kan extension of `F` along `L`, exhibits `(LeftExtension.whiskerRight L F G).obj E` as a pointwise left Kan extension of `F ⋙ G` along `L`. -/ def LeftExtension.IsPointwiseLeftKanExtension.postcompose [PreservesPointwiseLeftKanExtension G F L] {E : LeftExtension L F} (hE : E.IsPointwiseLeftKanExtension) : LeftExtension.postcompose₂ L F G|>.obj E|>.IsPointwiseLeftKanExtension := fun c ↦ (hE c).postcompose G /-- The cocone at a point of the whiskering right by `G`of an extension is isomorphic to the action of `G` on the cocone at that point for the original extension. -/ @[simps!] def LeftExtension.coconeAtWhiskerRightIso (E : LeftExtension L F) (c : C) : (LeftExtension.postcompose₂ L F G|>.obj E).coconeAt c ≅ G.mapCocone (E.coconeAt c) := Limits.Cocones.ext (Iso.refl _) /-- If `G` preserves any pointwise left Kan extension of `F` along `L` at `c`, then it preserves all of them. -/ lemma PreservesPointwiseLeftKanExtensionAt.mk' (c : C) {E : LeftExtension L F} (hE : E.IsPointwiseLeftKanExtensionAt c) (hGE : (LeftExtension.postcompose₂ L F G |>.obj E).IsPointwiseLeftKanExtensionAt c) : G.PreservesPointwiseLeftKanExtensionAt F L c where preserves E' hE' := ⟨Limits.IsColimit.ofIsoColimit hGE <| (E.coconeAtWhiskerRightIso G F L c) ≪≫ (Limits.Cocones.functoriality _ _).mapIso (hE.uniqueUpToIso hE') ≪≫ (E'.coconeAtWhiskerRightIso G F L c).symm⟩ instance hasLeftKanExtension_of_preserves [L.HasLeftKanExtension F] [PreservesLeftKanExtension G F L] : L.HasLeftKanExtension (F ⋙ G) := @HasLeftKanExtension.mk _ _ _ _ _ _ _ _ _ _ <| letI : (L.leftKanExtension F).IsLeftKanExtension <| L.leftKanExtensionUnit F := by infer_instance PreservesLeftKanExtension.preserves (L.leftKanExtension F) (L.leftKanExtensionUnit F) instance hasPointwiseLeftKanExtension_of_preserves [L.HasPointwiseLeftKanExtension F] [PreservesPointwiseLeftKanExtension G F L] : L.HasPointwiseLeftKanExtension (F ⋙ G) := (pointwiseLeftKanExtensionIsPointwiseLeftKanExtension L F|>.postcompose G).hasPointwiseLeftKanExtension /-- Extract an isomorphism `(leftKanExtension L F) ⋙ G ≅ leftKanExtension L (F ⋙ G)` when `G` preserves left Kan extensions. -/ def leftKanExtensionCompIsoOfPreserves [PreservesLeftKanExtension G F L] [L.HasLeftKanExtension F] : L.leftKanExtension F ⋙ G ≅ L.leftKanExtension (F ⋙ G) := leftKanExtensionUnique (L.leftKanExtension F ⋙ G) (whiskerRight (L.leftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom) (L.leftKanExtension <| F ⋙ G) (L.leftKanExtensionUnit <| F ⋙ G) section variable [PreservesLeftKanExtension G F L] [L.HasLeftKanExtension F] @[reassoc (attr := simp)] lemma leftKanExtensionCompIsoOfPreserves_hom_fac : whiskerRight (L.leftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom ≫ whiskerLeft L (leftKanExtensionCompIsoOfPreserves G F L).hom = (L.leftKanExtensionUnit <| F ⋙ G) := by simpa [leftKanExtensionCompIsoOfPreserves] using descOfIsLeftKanExtension_fac (α := whiskerRight (L.leftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom) (β := L.leftKanExtensionUnit (F ⋙ G)) @[reassoc (attr := simp)] lemma leftKanExtensionCompIsoOfPreserves_hom_fac_app (a : A) : G.map ((L.leftKanExtensionUnit F).app a) ≫ (G.leftKanExtensionCompIsoOfPreserves F L).hom.app (L.obj a) = (L.leftKanExtensionUnit (F ⋙ G)).app a := by simpa [- leftKanExtensionCompIsoOfPreserves_hom_fac] using NatTrans.congr_app (leftKanExtensionCompIsoOfPreserves_hom_fac G F L) a @[reassoc (attr := simp)] lemma leftKanExtensionCompIsoOfPreserves_inv_fac : (L.leftKanExtensionUnit <| F ⋙ G) ≫ whiskerLeft L (leftKanExtensionCompIsoOfPreserves G F L).inv = whiskerRight (L.leftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom := by simp [leftKanExtensionCompIsoOfPreserves] @[reassoc (attr := simp)] lemma leftKanExtensionCompIsoOfPreserves_inv_fac_app (a : A) : (L.leftKanExtensionUnit (F ⋙ G)).app a ≫ (G.leftKanExtensionCompIsoOfPreserves F L).inv.app (L.obj a) = G.map ((L.leftKanExtensionUnit F).app a) := by simpa [- leftKanExtensionCompIsoOfPreserves_inv_fac] using NatTrans.congr_app (leftKanExtensionCompIsoOfPreserves_inv_fac G F L) a end /-- A functor that preserves the colimit of `CostructuredArrow.proj L c ⋙ F` preserves the pointwise left Kan extension of `F` along `L` at `c`. -/ instance preservesPointwiseLeftKanExtensionAtOfPreservesColimit (c : C) [Limits.PreservesColimit (CostructuredArrow.proj L c ⋙ F) G] : G.PreservesPointwiseLeftKanExtensionAt F L c where preserves E p := ⟨Limits.IsColimit.ofIsoColimit (Limits.PreservesColimit.preserves p).some (E.coconeAtWhiskerRightIso G _ _ c).symm⟩ /-- If there is a pointwise left Kan extension of `F` along `L`, and if `G` preserves them, then `G` preserves left Kan extensions of `F` along `L`. -/ instance preservesPointwiseLKEOfHasPointwiseAndPreservesPointwise [HasPointwiseLeftKanExtension L F] [G.PreservesPointwiseLeftKanExtension F L] : G.PreservesLeftKanExtension F L where preserves F' α _ := (LeftExtension.isPointwiseLeftKanExtensionEquivOfIso (LeftExtension.postcompose₂ObjMkIso G α) <| (isPointwiseLeftKanExtensionOfIsLeftKanExtension F' α).postcompose G).isLeftKanExtension /-- Extract an isomorphism `(pointwiseLeftKanExtension L F) ⋙ G ≅ pointwiseLeftKanExtension L (F ⋙ G)` when `G` preserves left Kan extensions. -/ def pointwiseLeftKanExtensionCompIsoOfPreserves [PreservesPointwiseLeftKanExtension G F L] [L.HasPointwiseLeftKanExtension F] : L.pointwiseLeftKanExtension F ⋙ G ≅ L.pointwiseLeftKanExtension (F ⋙ G) := leftKanExtensionUnique (L.pointwiseLeftKanExtension F ⋙ G) (whiskerRight (L.pointwiseLeftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom) (L.pointwiseLeftKanExtension <| F ⋙ G) (L.pointwiseLeftKanExtensionUnit <| F ⋙ G) section variable [PreservesPointwiseLeftKanExtension G F L] [L.HasPointwiseLeftKanExtension F] @[reassoc (attr := simp)] lemma pointwiseLeftKanExtensionCompIsoOfPreserves_hom_fac : whiskerRight (L.pointwiseLeftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom ≫ whiskerLeft L (pointwiseLeftKanExtensionCompIsoOfPreserves G F L).hom = (L.pointwiseLeftKanExtensionUnit <| F ⋙ G) := by simpa [pointwiseLeftKanExtensionCompIsoOfPreserves] using descOfIsLeftKanExtension_fac (α := whiskerRight (L.pointwiseLeftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom) (β := L.pointwiseLeftKanExtensionUnit <| F ⋙ G) @[reassoc] lemma pointwiseLeftKanExtensionCompIsoOfPreserves_hom_fac_app (a : A) : G.map ((L.pointwiseLeftKanExtensionUnit F).app a) ≫ (G.pointwiseLeftKanExtensionCompIsoOfPreserves F L).hom.app (L.obj a) = (L.pointwiseLeftKanExtensionUnit <| F ⋙ G).app a := by simpa [- pointwiseLeftKanExtensionCompIsoOfPreserves_hom_fac] using NatTrans.congr_app (pointwiseLeftKanExtensionCompIsoOfPreserves_hom_fac G F L) a @[reassoc (attr := simp)] lemma pointwiseLeftKanExtensionCompIsoOfPreserves_inv_fac : (L.pointwiseLeftKanExtensionUnit <| F ⋙ G) ≫ whiskerLeft L (pointwiseLeftKanExtensionCompIsoOfPreserves G F L).inv = whiskerRight (L.pointwiseLeftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom := by simp [pointwiseLeftKanExtensionCompIsoOfPreserves] @[reassoc] lemma pointwiseLeftKanExtensionCompIsoOfPreserves_fac_app (a : A) : (L.pointwiseLeftKanExtensionUnit <| F ⋙ G).app a ≫ (G.pointwiseLeftKanExtensionCompIsoOfPreserves F L).inv.app (L.obj a) = G.map (L.pointwiseLeftKanExtensionUnit F|>.app a) := by simpa [-pointwiseLeftKanExtensionCompIsoOfPreserves_inv_fac] using NatTrans.congr_app (pointwiseLeftKanExtensionCompIsoOfPreserves_inv_fac G F L) a end /-- `G.PreservesLeftKanExtensions L` means that `G : B ⥤ D` preserves all left Kan extensions along `L : A ⥤ C` of every functor `A ⥤ B`. -/ abbrev PreservesLeftKanExtensions := ∀ (F : A ⥤ B), G.PreservesLeftKanExtension F L /-- `G.PreservesPointwiseLeftKanExtensions L` means that `G : B ⥤ D` preserves all pointwise left Kan extensions along `L : A ⥤ C` of every functor `A ⥤ B`. -/ abbrev PreservesPointwiseLeftKanExtensions := ∀ (F : A ⥤ B), G.PreservesPointwiseLeftKanExtension F L /-- Commuting a functor that preserves left Kan extensions with the `lan` functor. -/ @[simps!] def lanCompIsoOfPreserves [G.PreservesLeftKanExtensions L] [∀ F : A ⥤ B, HasLeftKanExtension L F] [∀ F : A ⥤ D, HasLeftKanExtension L F] : L.lan ⋙ (whiskeringRight _ _ _).obj G ≅ (whiskeringRight _ _ _).obj G ⋙ L.lan := NatIso.ofComponents (fun F ↦ leftKanExtensionCompIsoOfPreserves _ _ _) (fun {F F'} η ↦ by apply hom_ext_of_isLeftKanExtension (L.leftKanExtension F ⋙ G) (whiskerRight (L.leftKanExtensionUnit F) G ≫ (Functor.associator _ _ _).hom) dsimp [lan] ext simp [← G.map_comp_assoc]) end LeftKanExtension section RightKanExtension /-- `G.PreservesRightKanExtension F L` asserts that `G` preserves all right Kan extensions of `F` along `L`. See `PreservesRightKanExtension.mk_of_preserves_isRightKanExtension` for a constructor taking a single right Kan extension as input. -/ class PreservesRightKanExtension where preserves : ∀ (F' : C ⥤ B) (α : L ⋙ F' ⟶ F) [IsRightKanExtension F' α], IsRightKanExtension (F' ⋙ G) <| (Functor.associator _ _ _).inv ≫ whiskerRight α G /-- Alternative constructor for `PreservesRightKanExtension`, phrased in terms of `RightExtension.IsUniversal` instead. See `PreservesRightKanExtension.mk_of_preserves_isUniversal` for a similar constructor taking as input a single `RightExtension`. -/ lemma PreservesRightKanExtension.mk' (preserves : ∀ {E : RightExtension L F}, E.IsUniversal → Nonempty (RightExtension.postcompose₂ L F G |>.obj E).IsUniversal) : G.PreservesRightKanExtension F L where preserves _ _ h := ⟨⟨Limits.IsTerminal.equivOfIso (RightExtension.postcompose₂ObjMkIso _ _) <| (preserves h.nonempty_isUniversal.some).some⟩⟩ /-- Show that `G` preserves right Kan extensions if it maps some right Kan extension to a right Kan extension. -/ lemma PreservesRightKanExtension.mk_of_preserves_isRightKanExtension (F' : C ⥤ B) (α : L ⋙ F' ⟶ F) [IsRightKanExtension F' α] (h : IsRightKanExtension (F' ⋙ G) <| (Functor.associator _ _ _).inv ≫ whiskerRight α G) : G.PreservesRightKanExtension F L := .mk fun F'' α' h ↦ isRightKanExtension_of_iso (isoWhiskerRight (rightKanExtensionUnique F' α F'' α') G) ((Functor.associator _ _ _).inv ≫ whiskerRight α G ) ((Functor.associator _ _ _).inv ≫ whiskerRight α' G) (by ext x; simp [← G.map_comp]) /-- Show that `G` preserves right Kan extensions if it maps some right Kan extension to a left Kan extension, phrased in terms of `IsUniversal`. -/ lemma PreservesRightKanExtension.mk_of_preserves_isUniversal (E : RightExtension L F) (hE : E.IsUniversal) (h : Nonempty (RightExtension.postcompose₂ L F G |>.obj E).IsUniversal) : G.PreservesRightKanExtension F L := .mk' G F L fun hE' ↦ ⟨Limits.IsTerminal.equivOfIso (RightExtension.postcompose₂ L F G|>.mapIso <| Limits.IsTerminal.uniqueUpToIso hE hE') h.some⟩ attribute [instance] PreservesRightKanExtension.preserves /-- `G.PreservesRightKanExtensionAt F L c` asserts that `G` preserves all right pointwise right Kan extensions of `F` along `L` at `c`. -/ class PreservesPointwiseRightKanExtensionAt (c : C) where /-- `G` preserves every pointwise extensions of `F` along `L` at `c`. -/ preserves : ∀ (E : RightExtension L F), E.IsPointwiseRightKanExtensionAt c → Nonempty ((RightExtension.postcompose₂ L F G|>.obj E).IsPointwiseRightKanExtensionAt c) /-- `G.PreservesRightKanExtensions L` asserts that `G` preserves all pointwise right Kan extensions of `F` along `L` for every `F`. -/ abbrev PreservesPointwiseRightKanExtension := ∀ c : C, PreservesPointwiseRightKanExtensionAt G F L c variable {F L} in /-- Given a pointwise right Kan extension of `F` along `L` at `c`, exhibits `(RightExtension.whiskerRight L F G).obj E` as a pointwise right Kan extension of `F ⋙ G` along `L` at `c`. -/ def RightExtension.IsPointwiseRightKanExtensionAt.postcompose {c : C} [PreservesPointwiseRightKanExtensionAt G F L c] {E : RightExtension L F} (hE : E.IsPointwiseRightKanExtensionAt c) : RightExtension.postcompose₂ L F G|>.obj E|>.IsPointwiseRightKanExtensionAt c := PreservesPointwiseRightKanExtensionAt.preserves E hE|>.some variable {F L} in /-- Given a pointwise right Kan extension of `F` along `L`, exhibits `(RightExtension.whiskerRight L F G).obj E` as a pointwise right Kan extension of `F ⋙ G` at `L`. -/ def RightExtension.IsPointwiseRightKanExtension.postcompose [PreservesPointwiseRightKanExtension G F L] {E : RightExtension L F} (hE : E.IsPointwiseRightKanExtension) : RightExtension.postcompose₂ L F G|>.obj E|>.IsPointwiseRightKanExtension := fun c ↦ (hE c).postcompose G /-- The cone at a point of the whiskering right by `G`of an extension is isomorphic to the action of `G` on the cone at that point for the original extension. -/ @[simps!] def RightExtension.coneAtWhiskerRightIso (E : RightExtension L F) (c : C) : (RightExtension.postcompose₂ L F G|>.obj E).coneAt c ≅ G.mapCone (E.coneAt c) := Limits.Cones.ext (Iso.refl _) /-- If `G` preserves any pointwise right Kan extension of `F` along `L` at `c`, then it preserves all of them. -/ lemma PreservesPointwiseRightKanExtensionAt.mk' (c : C) {E : RightExtension L F} (hE : E.IsPointwiseRightKanExtensionAt c) (hGE : (RightExtension.postcompose₂ L F G |>.obj E).IsPointwiseRightKanExtensionAt c) : G.PreservesPointwiseRightKanExtensionAt F L c where preserves E' hE' := ⟨Limits.IsLimit.ofIsoLimit hGE <| (E.coneAtWhiskerRightIso G F L c) ≪≫ (Limits.Cones.functoriality _ _).mapIso (hE.uniqueUpToIso hE') ≪≫ (E'.coneAtWhiskerRightIso G F L c).symm⟩ instance hasRightKanExtension_of_preserves [L.HasRightKanExtension F] [PreservesRightKanExtension G F L] : L.HasRightKanExtension (F ⋙ G) := @HasRightKanExtension.mk _ _ _ _ _ _ _ _ _ _ <| letI : (L.rightKanExtension F).IsRightKanExtension <| L.rightKanExtensionCounit F := by infer_instance PreservesRightKanExtension.preserves (L.rightKanExtension F) (L.rightKanExtensionCounit F) instance hasPointwiseRightKanExtension_of_preserves [L.HasPointwiseRightKanExtension F] [PreservesPointwiseRightKanExtension G F L] : L.HasPointwiseRightKanExtension (F ⋙ G) := (pointwiseRightKanExtensionIsPointwiseRightKanExtension L F|>.postcompose G).hasPointwiseRightKanExtension /-- Extract an isomorphism `rightKanExtension L F ⋙ G ≅ rightKanExtension L (F ⋙ G)` when `G` preserves right Kan extensions. -/ def rightKanExtensionCompIsoOfPreserves [PreservesRightKanExtension G F L] [L.HasRightKanExtension F] : L.rightKanExtension F ⋙ G ≅ L.rightKanExtension (F ⋙ G) := rightKanExtensionUnique (L.rightKanExtension F ⋙ G) ((Functor.associator _ _ _).inv ≫ whiskerRight (L.rightKanExtensionCounit F) G) (L.rightKanExtension <| F ⋙ G) (L.rightKanExtensionCounit <| F ⋙ G) section variable [PreservesRightKanExtension G F L] [L.HasRightKanExtension F] @[reassoc (attr := simp)] lemma rightKanExtensionCompIsoOfPreserves_hom_fac : whiskerLeft L (rightKanExtensionCompIsoOfPreserves G F L).hom ≫ (L.rightKanExtensionCounit <| F ⋙ G) = (Functor.associator _ _ _).inv ≫ whiskerRight (L.rightKanExtensionCounit F) G := by simp [rightKanExtensionCompIsoOfPreserves] @[reassoc (attr := simp)] lemma rightKanExtensionCompIsoOfPreserves_hom_fac_app (a : A) : (G.rightKanExtensionCompIsoOfPreserves F L).hom.app (L.obj a) ≫ (L.rightKanExtensionCounit (F ⋙ G)).app a = G.map (L.rightKanExtensionCounit F|>.app a) := by simp [rightKanExtensionCompIsoOfPreserves] @[reassoc (attr := simp)] lemma rightKanExtensionCompIsoOfPreserves_inv_fac : whiskerLeft L (rightKanExtensionCompIsoOfPreserves G F L).inv ≫ ((Functor.associator _ _ _).inv ≫ whiskerRight (L.rightKanExtensionCounit F) G) = (L.rightKanExtensionCounit <| F ⋙ G) := by simp [rightKanExtensionCompIsoOfPreserves] @[reassoc (attr := simp)] lemma rightKanExtensionCompIsoOfPreserves_inv_fac_app (a : A) : (G.rightKanExtensionCompIsoOfPreserves F L).inv.app (L.obj a) ≫ G.map (L.rightKanExtensionCounit F|>.app a) = (L.rightKanExtensionCounit (F ⋙ G)).app a := by simpa [-rightKanExtensionCompIsoOfPreserves_inv_fac] using NatTrans.congr_app (rightKanExtensionCompIsoOfPreserves_inv_fac G F L) a end /-- A functor that preserves the limit of `(StructuredArrow.proj L c ⋙ F)` preserves the pointwise right Kan extension of `F` along `L` at c. -/ instance preservesPointwiseRightKanExtensionAtOfPreservesLimit (c : C) [Limits.PreservesLimit (StructuredArrow.proj c L ⋙ F) G] : G.PreservesPointwiseRightKanExtensionAt F L c where preserves E p := ⟨Limits.IsLimit.ofIsoLimit (Limits.PreservesLimit.preserves p).some (E.coneAtWhiskerRightIso G _ _ c).symm⟩ /-- If there is a pointwise right Kan extension of `F` along `L`, and if `G` preserves them, then `G` preserves right Kan extensions of `F` along `L`. -/ instance preservesPointwiseRKEOfHasPointwiseAndPreservesPointwise [HasPointwiseRightKanExtension L F] [G.PreservesPointwiseRightKanExtension F L] : G.PreservesRightKanExtension F L where preserves F' α _ := (RightExtension.isPointwiseRightKanExtensionEquivOfIso (RightExtension.postcompose₂ObjMkIso G α) <| (isPointwiseRightKanExtensionOfIsRightKanExtension F' α).postcompose G).isRightKanExtension /-- Extract an isomorphism `L.pointwiseRightKanExtension F ⋙ G ≅ L.pointwiseRightKanExtension (F ⋙ G)` when `G` preserves right Kan extensions. -/ def pointwiseRightKanExtensionCompIsoOfPreserves [PreservesPointwiseRightKanExtension G F L] [L.HasPointwiseRightKanExtension F] : L.pointwiseRightKanExtension F ⋙ G ≅ L.pointwiseRightKanExtension (F ⋙ G) := rightKanExtensionUnique (L.pointwiseRightKanExtension F ⋙ G) ((Functor.associator _ _ _).inv ≫ whiskerRight (L.pointwiseRightKanExtensionCounit F) G) (L.pointwiseRightKanExtension <| F ⋙ G) (L.pointwiseRightKanExtensionCounit <| F ⋙ G) section variable [PreservesPointwiseRightKanExtension G F L] [L.HasPointwiseRightKanExtension F] @[reassoc (attr := simp)] lemma pointwiseRightKanExtensionCompIsoOfPreserves_hom_fac : whiskerLeft L (pointwiseRightKanExtensionCompIsoOfPreserves G F L).hom ≫ (L.pointwiseRightKanExtensionCounit <| F ⋙ G) = (Functor.associator _ _ _).inv ≫ whiskerRight (L.pointwiseRightKanExtensionCounit F) G := by simp [pointwiseRightKanExtensionCompIsoOfPreserves] @[reassoc] lemma pointwiseRightKanExtensionCompIsoOfPreserves_hom_fac_app (a : A) : (G.pointwiseRightKanExtensionCompIsoOfPreserves F L).hom.app (L.obj a) ≫ (L.pointwiseRightKanExtensionCounit <| F ⋙ G).app a = G.map (L.pointwiseRightKanExtensionCounit F|>.app a) := by simpa [-pointwiseRightKanExtensionCompIsoOfPreserves_hom_fac] using NatTrans.congr_app (pointwiseRightKanExtensionCompIsoOfPreserves_hom_fac G F L) a @[reassoc (attr := simp)] lemma pointwiseRightKanExtensionCompIsoOfPreserves_inv_fac : whiskerLeft L (pointwiseRightKanExtensionCompIsoOfPreserves G F L).inv ≫ (Functor.associator _ _ _).inv ≫ whiskerRight (L.pointwiseRightKanExtensionCounit F) G = (L.pointwiseRightKanExtensionCounit <| F ⋙ G) := by simp [pointwiseRightKanExtensionCompIsoOfPreserves] @[reassoc] lemma pointwiseRightKanExtensionCompIsoOfPreserves_inv_fac_app (a : A) : (G.pointwiseRightKanExtensionCompIsoOfPreserves F L).inv.app (L.obj a) ≫ G.map (L.pointwiseRightKanExtensionCounit F|>.app a) = (L.pointwiseRightKanExtensionCounit <| F ⋙ G).app a := by simpa [-pointwiseRightKanExtensionCompIsoOfPreserves_inv_fac] using NatTrans.congr_app (pointwiseRightKanExtensionCompIsoOfPreserves_inv_fac G F L) a end /-- `G.PreservesRightKanExtensions L` means that `G : B ⥤ D` preserves all right Kan extensions along `L : A ⥤ C` of every functor `A ⥤ B`. -/ abbrev PreservesRightKanExtensions := ∀ (F : A ⥤ B), G.PreservesRightKanExtension F L /-- `G.PreservesPointwiseRightKanExtensions L` means that `G : B ⥤ D` preserves all pointwise right Kan extensions along `L : A ⥤ C` of every functor `A ⥤ B`. -/ abbrev PreservesPointwiseRightKanExtensions := ∀ (F : A ⥤ B), G.PreservesPointwiseRightKanExtension F L /-- Commuting a functor that preserves right Kan extensions with the `ran` functor. -/ @[simps!] def ranCompIsoOfPreserves [G.PreservesRightKanExtensions L] [∀ F : A ⥤ B, HasRightKanExtension L F] [∀ F : A ⥤ D, HasRightKanExtension L F] : L.ran ⋙ (whiskeringRight _ _ _).obj G ≅ (whiskeringRight _ _ _).obj G ⋙ L.ran := NatIso.ofComponents (fun F ↦ rightKanExtensionCompIsoOfPreserves _ _ _) (fun {F F'} η ↦ by apply hom_ext_of_isRightKanExtension (L.rightKanExtension <| F' ⋙ G) (L.rightKanExtensionCounit <| F' ⋙ G) dsimp [ran] ext simp only [comp_obj, Category.assoc, rightKanExtensionCompIsoOfPreserves_hom_fac, NatTrans.comp_app, whiskerLeft_app, whiskerRight_app, associator_inv_app, Category.id_comp, liftOfIsRightKanExtension_fac, rightKanExtensionCompIsoOfPreserves_hom_fac_assoc, ← G.map_comp] simp) end RightKanExtension end end CategoryTheory.Functor
GameAdd.lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import Mathlib.Data.Sym.Sym2 import Mathlib.Logic.Relation /-! # Game addition relation This file defines, given relations `rα : α → α → Prop` and `rβ : β → β → Prop`, a relation `Prod.GameAdd` on pairs, such that `GameAdd rα rβ x y` iff `x` can be reached from `y` by decreasing either entry (with respect to `rα` and `rβ`). It is so called since it models the subsequency relation on the addition of combinatorial games. We also define `Sym2.GameAdd`, which is the unordered pair analog of `Prod.GameAdd`. ## Main definitions and results - `Prod.GameAdd`: the game addition relation on ordered pairs. - `WellFounded.prod_gameAdd`: formalizes induction on ordered pairs, where exactly one entry decreases at a time. - `Sym2.GameAdd`: the game addition relation on unordered pairs. - `WellFounded.sym2_gameAdd`: formalizes induction on unordered pairs, where exactly one entry decreases at a time. -/ variable {α β : Type*} {rα : α → α → Prop} {rβ : β → β → Prop} {a : α} {b : β} /-! ### `Prod.GameAdd` -/ namespace Prod variable (rα rβ) /-- `Prod.GameAdd rα rβ x y` means that `x` can be reached from `y` by decreasing either entry with respect to the relations `rα` and `rβ`. It is so called, as it models game addition within combinatorial game theory. If `rα a₁ a₂` means that `a₂ ⟶ a₁` is a valid move in game `α`, and `rβ b₁ b₂` means that `b₂ ⟶ b₁` is a valid move in game `β`, then `GameAdd rα rβ` specifies the valid moves in the juxtaposition of `α` and `β`: the player is free to choose one of the games and make a move in it, while leaving the other game unchanged. See `Sym2.GameAdd` for the unordered pair analog. -/ inductive GameAdd : α × β → α × β → Prop | fst {a₁ a₂ b} : rα a₁ a₂ → GameAdd (a₁, b) (a₂, b) | snd {a b₁ b₂} : rβ b₁ b₂ → GameAdd (a, b₁) (a, b₂) theorem gameAdd_iff {rα rβ} {x y : α × β} : GameAdd rα rβ x y ↔ rα x.1 y.1 ∧ x.2 = y.2 ∨ rβ x.2 y.2 ∧ x.1 = y.1 := by constructor · rintro (@⟨a₁, a₂, b, h⟩ | @⟨a, b₁, b₂, h⟩) exacts [Or.inl ⟨h, rfl⟩, Or.inr ⟨h, rfl⟩] · revert x y rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨h, rfl : b₁ = b₂⟩ | ⟨h, rfl : a₁ = a₂⟩) exacts [GameAdd.fst h, GameAdd.snd h] theorem gameAdd_mk_iff {rα rβ} {a₁ a₂ : α} {b₁ b₂ : β} : GameAdd rα rβ (a₁, b₁) (a₂, b₂) ↔ rα a₁ a₂ ∧ b₁ = b₂ ∨ rβ b₁ b₂ ∧ a₁ = a₂ := gameAdd_iff @[simp] theorem gameAdd_swap_swap : ∀ a b : α × β, GameAdd rβ rα a.swap b.swap ↔ GameAdd rα rβ a b := fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => by rw [Prod.swap, Prod.swap, gameAdd_mk_iff, gameAdd_mk_iff, or_comm] theorem gameAdd_swap_swap_mk (a₁ a₂ : α) (b₁ b₂ : β) : GameAdd rα rβ (a₁, b₁) (a₂, b₂) ↔ GameAdd rβ rα (b₁, a₁) (b₂, a₂) := gameAdd_swap_swap rβ rα (b₁, a₁) (b₂, a₂) /-- `Prod.GameAdd` is a subrelation of `Prod.Lex`. -/ theorem gameAdd_le_lex : GameAdd rα rβ ≤ Prod.Lex rα rβ := fun _ _ h => h.rec (Prod.Lex.left _ _) (Prod.Lex.right _) /-- `Prod.RProd` is a subrelation of the transitive closure of `Prod.GameAdd`. -/ theorem rprod_le_transGen_gameAdd : RProd rα rβ ≤ Relation.TransGen (GameAdd rα rβ) | _, _, h => h.rec (by intro _ _ _ _ hα hβ exact Relation.TransGen.tail (Relation.TransGen.single <| GameAdd.fst hα) (GameAdd.snd hβ)) end Prod /-- If `a` is accessible under `rα` and `b` is accessible under `rβ`, then `(a, b)` is accessible under `Prod.GameAdd rα rβ`. Notice that `Prod.lexAccessible` requires the stronger condition `∀ b, Acc rβ b`. -/ theorem Acc.prod_gameAdd (ha : Acc rα a) (hb : Acc rβ b) : Acc (Prod.GameAdd rα rβ) (a, b) := by induction ha generalizing b with | _ a _ iha induction hb with | _ b hb ihb refine Acc.intro _ fun h => ?_ rintro (⟨ra⟩ | ⟨rb⟩) exacts [iha _ ra (Acc.intro b hb), ihb _ rb] /-- The `Prod.GameAdd` relation on well-founded inputs is well-founded. In particular, the sum of two well-founded games is well-founded. -/ theorem WellFounded.prod_gameAdd (hα : WellFounded rα) (hβ : WellFounded rβ) : WellFounded (Prod.GameAdd rα rβ) := ⟨fun ⟨a, b⟩ => (hα.apply a).prod_gameAdd (hβ.apply b)⟩ namespace Prod /-- Recursion on the well-founded `Prod.GameAdd` relation. Note that it's strictly more general to recurse on the lexicographic order instead. -/ def GameAdd.fix {C : α → β → Sort*} (hα : WellFounded rα) (hβ : WellFounded rβ) (IH : ∀ a₁ b₁, (∀ a₂ b₂, GameAdd rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a : α) (b : β) : C a b := @WellFounded.fix (α × β) (fun x => C x.1 x.2) _ (hα.prod_gameAdd hβ) (fun ⟨x₁, x₂⟩ IH' => IH x₁ x₂ fun a' b' => IH' ⟨a', b'⟩) ⟨a, b⟩ theorem GameAdd.fix_eq {C : α → β → Sort*} (hα : WellFounded rα) (hβ : WellFounded rβ) (IH : ∀ a₁ b₁, (∀ a₂ b₂, GameAdd rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a : α) (b : β) : GameAdd.fix hα hβ IH a b = IH a b fun a' b' _ => GameAdd.fix hα hβ IH a' b' := WellFounded.fix_eq _ _ _ /-- Induction on the well-founded `Prod.GameAdd` relation. Note that it's strictly more general to induct on the lexicographic order instead. -/ theorem GameAdd.induction {C : α → β → Prop} : WellFounded rα → WellFounded rβ → (∀ a₁ b₁, (∀ a₂ b₂, GameAdd rα rβ (a₂, b₂) (a₁, b₁) → C a₂ b₂) → C a₁ b₁) → ∀ a b, C a b := GameAdd.fix end Prod /-! ### `Sym2.GameAdd` -/ namespace Sym2 /-- `Sym2.GameAdd rα x y` means that `x` can be reached from `y` by decreasing either entry with respect to the relation `rα`. See `Prod.GameAdd` for the ordered pair analog. -/ def GameAdd (rα : α → α → Prop) : Sym2 α → Sym2 α → Prop := Sym2.lift₂ ⟨fun a₁ b₁ a₂ b₂ => Prod.GameAdd rα rα (a₁, b₁) (a₂, b₂) ∨ Prod.GameAdd rα rα (b₁, a₁) (a₂, b₂), fun a₁ b₁ a₂ b₂ => by dsimp rw [Prod.gameAdd_swap_swap_mk _ _ b₁ b₂ a₁ a₂, Prod.gameAdd_swap_swap_mk _ _ a₁ b₂ b₁ a₂] simp [or_comm]⟩ theorem gameAdd_iff : ∀ {x y : α × α}, GameAdd rα (Sym2.mk x) (Sym2.mk y) ↔ Prod.GameAdd rα rα x y ∨ Prod.GameAdd rα rα x.swap y := by rintro ⟨_, _⟩ ⟨_, _⟩ rfl theorem gameAdd_mk'_iff {a₁ a₂ b₁ b₂ : α} : GameAdd rα s(a₁, b₁) s(a₂, b₂) ↔ Prod.GameAdd rα rα (a₁, b₁) (a₂, b₂) ∨ Prod.GameAdd rα rα (b₁, a₁) (a₂, b₂) := Iff.rfl theorem _root_.Prod.GameAdd.to_sym2 {a₁ a₂ b₁ b₂ : α} (h : Prod.GameAdd rα rα (a₁, b₁) (a₂, b₂)) : Sym2.GameAdd rα s(a₁, b₁) s(a₂, b₂) := gameAdd_mk'_iff.2 <| Or.inl <| h theorem GameAdd.fst {a₁ a₂ b : α} (h : rα a₁ a₂) : GameAdd rα s(a₁, b) s(a₂, b) := (Prod.GameAdd.fst h).to_sym2 theorem GameAdd.snd {a b₁ b₂ : α} (h : rα b₁ b₂) : GameAdd rα s(a, b₁) s(a, b₂) := (Prod.GameAdd.snd h).to_sym2 theorem GameAdd.fst_snd {a₁ a₂ b : α} (h : rα a₁ a₂) : GameAdd rα s(a₁, b) s(b, a₂) := by rw [Sym2.eq_swap] exact GameAdd.snd h theorem GameAdd.snd_fst {a₁ a₂ b : α} (h : rα a₁ a₂) : GameAdd rα s(b, a₁) s(a₂, b) := by rw [Sym2.eq_swap] exact GameAdd.fst h end Sym2 theorem Acc.sym2_gameAdd {a b} (ha : Acc rα a) (hb : Acc rα b) : Acc (Sym2.GameAdd rα) s(a, b) := by induction ha generalizing b with | _ a _ iha induction hb with | _ b hb ihb refine Acc.intro _ fun s => ?_ induction s with | _ c d rw [Sym2.GameAdd] dsimp rintro ((rc | rd) | (rd | rc)) · exact iha c rc ⟨b, hb⟩ · exact ihb d rd · rw [Sym2.eq_swap] exact iha d rd ⟨b, hb⟩ · rw [Sym2.eq_swap] exact ihb c rc /-- The `Sym2.GameAdd` relation on well-founded inputs is well-founded. -/ theorem WellFounded.sym2_gameAdd (h : WellFounded rα) : WellFounded (Sym2.GameAdd rα) := ⟨fun i => Sym2.inductionOn i fun x y => (h.apply x).sym2_gameAdd (h.apply y)⟩ namespace Sym2 attribute [local instance] Sym2.Rel.setoid /-- Recursion on the well-founded `Sym2.GameAdd` relation. -/ def GameAdd.fix {C : α → α → Sort*} (hr : WellFounded rα) (IH : ∀ a₁ b₁, (∀ a₂ b₂, Sym2.GameAdd rα s(a₂, b₂) s(a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a b : α) : C a b := @WellFounded.fix (α × α) (fun x => C x.1 x.2) (fun x y ↦ Prod.GameAdd rα rα x y ∨ Prod.GameAdd rα rα x.swap y) (by simpa [← Sym2.gameAdd_iff] using hr.sym2_gameAdd.onFun) (fun ⟨x₁, x₂⟩ IH' => IH x₁ x₂ fun a' b' => IH' ⟨a', b'⟩) (a, b) theorem GameAdd.fix_eq {C : α → α → Sort*} (hr : WellFounded rα) (IH : ∀ a₁ b₁, (∀ a₂ b₂, Sym2.GameAdd rα s(a₂, b₂) s(a₁, b₁) → C a₂ b₂) → C a₁ b₁) (a b : α) : GameAdd.fix hr IH a b = IH a b fun a' b' _ => GameAdd.fix hr IH a' b' := WellFounded.fix_eq .. /-- Induction on the well-founded `Sym2.GameAdd` relation. -/ theorem GameAdd.induction {C : α → α → Prop} : WellFounded rα → (∀ a₁ b₁, (∀ a₂ b₂, Sym2.GameAdd rα s(a₂, b₂) s(a₁, b₁) → C a₂ b₂) → C a₁ b₁) → ∀ a b, C a b := GameAdd.fix end Sym2
Extend.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.Topology.Category.Profinite.AsLimit import Mathlib.Topology.Category.Profinite.CofilteredLimit import Mathlib.CategoryTheory.Filtered.Final /-! # Extending cones in `Profinite` Let `(Sᵢ)_{i : I}` be a family of finite sets indexed by a cofiltered category `I` and let `S` be its limit in `Profinite`. Let `G` be a functor from `Profinite` to a category `C` and suppose that `G` preserves the limit described above. Suppose further that the projection maps `S ⟶ Sᵢ` are epimorphic for all `i`. Then `G.obj S` is isomorphic to a limit indexed by `StructuredArrow S toProfinite` (see `Profinite.Extend.isLimitCone`). We also provide the dual result for a functor of the form `G : Profiniteᵒᵖ ⥤ C`. We apply this to define `Profinite.diagram'`, `Profinite.asLimitCone'`, and `Profinite.asLimit'`, analogues to their unprimed versions in `Mathlib/Topology/Category/Profinite/AsLimit.lean`, in which the indexing category is `StructuredArrow S toProfinite` instead of `DiscreteQuotient S`. -/ universe u w open CategoryTheory Limits FintypeCat Functor namespace Profinite variable {I : Type u} [SmallCategory I] [IsCofiltered I] {F : I ⥤ FintypeCat.{max u w}} (c : Cone <| F ⋙ toProfinite) /-- A continuous map from a profinite set to a finite set factors through one of the components of the profinite set when written as a cofiltered limit of finite sets. -/ lemma exists_hom (hc : IsLimit c) {X : FintypeCat} (f : c.pt ⟶ toProfinite.obj X) : ∃ (i : I) (g : F.obj i ⟶ X), f = c.π.app i ≫ toProfinite.map g := by let _ : TopologicalSpace X := ⊥ have : DiscreteTopology (toProfinite.obj X) := ⟨rfl⟩ let f' : LocallyConstant c.pt (toProfinite.obj X) := ⟨f, (IsLocallyConstant.iff_continuous _).mpr f.hom.continuous⟩ obtain ⟨i, g, h⟩ := exists_locallyConstant.{_, u} c hc f' refine ⟨i, (g : _ → _), ?_⟩ ext x exact LocallyConstant.congr_fun h x namespace Extend /-- Given a cone in `Profinite`, consisting of finite sets and indexed by a cofiltered category, we obtain a functor from the indexing category to `StructuredArrow c.pt toProfinite`. -/ @[simps] def functor : I ⥤ StructuredArrow c.pt toProfinite where obj i := StructuredArrow.mk (c.π.app i) map f := StructuredArrow.homMk (F.map f) (c.w f) -- We check that the original diagram factors through `Profinite.Extend.functor`. example : functor c ⋙ StructuredArrow.proj c.pt toProfinite ≅ F := Iso.refl _ /-- Given a cone in `Profinite`, consisting of finite sets and indexed by a cofiltered category, we obtain a functor from the opposite of the indexing category to `CostructuredArrow toProfinite.op ⟨c.pt⟩`. -/ @[simps! obj map] def functorOp : Iᵒᵖ ⥤ CostructuredArrow toProfinite.op ⟨c.pt⟩ := (functor c).op ⋙ StructuredArrow.toCostructuredArrow _ _ -- We check that the opposite of the original diagram factors through `Profinite.Extend.functorOp`. example : functorOp c ⋙ CostructuredArrow.proj toProfinite.op ⟨c.pt⟩ ≅ F.op := Iso.refl _ attribute [local instance] uliftCategory in /-- If the projection maps in the cone are epimorphic and the cone is limiting, then `Profinite.Extend.functor` is initial. TODO: investigate how to weaken the assumption `∀ i, Epi (c.π.app i)` to `∀ i, ∃ j (_ : j ⟶ i), Epi (c.π.app j)`. -/ lemma functor_initial (hc : IsLimit c) [∀ i, Epi (c.π.app i)] : Initial (functor c) := by let e : I ≌ ULiftHom.{w} (ULift.{w} I) := ULiftHomULiftCategory.equiv _ suffices (e.inverse ⋙ functor c).Initial from initial_of_equivalence_comp e.inverse (functor c) rw [initial_iff_of_isCofiltered (F := e.inverse ⋙ functor c)] constructor · intro ⟨_, X, (f : c.pt ⟶ _)⟩ obtain ⟨i, g, h⟩ := exists_hom c hc f exact ⟨⟨i⟩, ⟨StructuredArrow.homMk g h.symm⟩⟩ · intro ⟨_, X, (f : c.pt ⟶ _)⟩ ⟨i⟩ ⟨_, (s : F.obj i ⟶ X), (w : f = c.π.app i ≫ _)⟩ ⟨_, (s' : F.obj i ⟶ X), (w' : f = c.π.app i ≫ _)⟩ simp only [StructuredArrow.hom_eq_iff, StructuredArrow.comp_right] refine ⟨⟨i⟩, 𝟙 _, ?_⟩ simp only [CategoryTheory.Functor.map_id] rw [w] at w' exact toProfinite.map_injective <| Epi.left_cancellation _ _ w' /-- If the projection maps in the cone are epimorphic and the cone is limiting, then `Profinite.Extend.functorOp` is final. -/ lemma functorOp_final (hc : IsLimit c) [∀ i, Epi (c.π.app i)] : Final (functorOp c) := by have := functor_initial c hc have : ((StructuredArrow.toCostructuredArrow toProfinite c.pt)).IsEquivalence := (inferInstance : (structuredArrowOpEquivalence _ _).functor.IsEquivalence ) exact Functor.final_comp (functor c).op _ section Limit variable {C : Type*} [Category C] (G : Profinite ⥤ C) /-- Given a functor `G` from `Profinite` and `S : Profinite`, we obtain a cone on `(StructuredArrow.proj S toProfinite ⋙ toProfinite ⋙ G)` with cone point `G.obj S`. Whiskering this cone with `Profinite.Extend.functor c` gives `G.mapCone c` as we check in the example below. -/ @[simps] def cone (S : Profinite) : Cone (StructuredArrow.proj S toProfinite ⋙ toProfinite ⋙ G) where pt := G.obj S π := { app := fun i ↦ G.map i.hom naturality := fun _ _ f ↦ (by simp [← map_comp]) } example : G.mapCone c = (cone G c.pt).whisker (functor c) := rfl /-- If `c` and `G.mapCone c` are limit cones and the projection maps in `c` are epimorphic, then `cone G c.pt` is a limit cone. -/ noncomputable def isLimitCone (hc : IsLimit c) [∀ i, Epi (c.π.app i)] (hc' : IsLimit <| G.mapCone c) : IsLimit (cone G c.pt) := (functor_initial c hc).isLimitWhiskerEquiv _ _ hc' end Limit section Colimit variable {C : Type*} [Category C] (G : Profiniteᵒᵖ ⥤ C) /-- Given a functor `G` from `Profiniteᵒᵖ` and `S : Profinite`, we obtain a cocone on `(CostructuredArrow.proj toProfinite.op ⟨S⟩ ⋙ toProfinite.op ⋙ G)` with cocone point `G.obj ⟨S⟩`. Whiskering this cocone with `Profinite.Extend.functorOp c` gives `G.mapCocone c.op` as we check in the example below. -/ @[simps] def cocone (S : Profinite) : Cocone (CostructuredArrow.proj toProfinite.op ⟨S⟩ ⋙ toProfinite.op ⋙ G) where pt := G.obj ⟨S⟩ ι := { app := fun i ↦ G.map i.hom naturality := fun _ _ f ↦ (by have := f.w simp only [op_obj, const_obj_obj, op_map, CostructuredArrow.right_eq_id, const_obj_map, Category.comp_id] at this simp [← map_comp, this]) } example : G.mapCocone c.op = (cocone G c.pt).whisker (functorOp c) := rfl /-- If `c` is a limit cone, `G.mapCocone c.op` is a colimit cone and the projection maps in `c` are epimorphic, then `cocone G c.pt` is a colimit cone. -/ noncomputable def isColimitCocone (hc : IsLimit c) [∀ i, Epi (c.π.app i)] (hc' : IsColimit <| G.mapCocone c.op) : IsColimit (cocone G c.pt) := (functorOp_final c hc).isColimitWhiskerEquiv _ _ hc' end Colimit end Extend open Extend section ProfiniteAsLimit variable (S : Profinite.{u}) /-- A functor `StructuredArrow S toProfinite ⥤ FintypeCat` whose limit in `Profinite` is isomorphic to `S`. -/ abbrev fintypeDiagram' : StructuredArrow S toProfinite ⥤ FintypeCat := StructuredArrow.proj S toProfinite /-- An abbreviation for `S.fintypeDiagram' ⋙ toProfinite`. -/ abbrev diagram' : StructuredArrow S toProfinite ⥤ Profinite := S.fintypeDiagram' ⋙ toProfinite /-- A cone over `S.diagram'` whose cone point is `S`. -/ abbrev asLimitCone' : Cone (S.diagram') := cone (𝟭 _) S instance (i : DiscreteQuotient S) : Epi (S.asLimitCone.π.app i) := (epi_iff_surjective _).mpr i.proj_surjective /-- `S.asLimitCone'` is a limit cone. -/ noncomputable def asLimit' : IsLimit S.asLimitCone' := isLimitCone _ (𝟭 _) S.asLimit S.asLimit /-- A bundled version of `S.asLimitCone'` and `S.asLimit'`. -/ noncomputable def lim' : LimitCone S.diagram' := ⟨S.asLimitCone', S.asLimit'⟩ end ProfiniteAsLimit end Profinite
Localization.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.RingTheory.Flat.Stability import Mathlib.RingTheory.LocalProperties.Exactness /-! # Flatness and localization In this file we show that localizations are flat, and flatness is a local property. ## Main result * `IsLocalization.flat`: a localization of a commutative ring is flat over it. * `Module.flat_iff_of_isLocalization` : Let `Rₚ` a localization of a commutative ring `R` and `M` be a module over `Rₚ`. Then `M` is flat over `R` if and only if `M` is flat over `Rₚ`. * `Module.flat_of_isLocalized_maximal` : Let `M` be a module over a commutative ring `R`. If the localization of `M` at each maximal ideal `P` is flat over `Rₚ`, then `M` is flat over `R`. * `Module.flat_of_isLocalized_span` : Let `M` be a module over a commutative ring `R` and `S` be a set that spans `R`. If the localization of `M` at each `s : S` is flat over `Localization.Away s`, then `M` is flat over `R`. -/ open IsLocalizedModule LocalizedModule LinearMap TensorProduct variable {R : Type*} (S : Type*) [CommSemiring R] [CommSemiring S] [Algebra R S] variable (p : Submonoid R) [IsLocalization p S] variable (M : Type*) [AddCommMonoid M] [Module R M] [Module S M] [IsScalarTower R S M] include p in theorem IsLocalization.flat : Module.Flat R S := by refine Module.Flat.iff_lTensor_injectiveₛ.mpr fun P _ _ N ↦ ?_ have h := ((range N.subtype).isLocalizedModule S p (TensorProduct.mk R S P 1)).isBaseChange _ S let e := (LinearEquiv.ofInjective _ Subtype.val_injective).lTensor S ≪≫ₗ h.equiv.restrictScalars R have : N.subtype.lTensor S = Submodule.subtype _ ∘ₗ e.toLinearMap := by ext; change _ = (h.equiv _).1; simp [h.equiv_tmul, TensorProduct.smul_tmul'] simpa [this] using e.injective instance Localization.flat : Module.Flat R (Localization p) := IsLocalization.flat _ p namespace Module include p in theorem flat_iff_of_isLocalization : Flat S M ↔ Flat R M := have := isLocalizedModule_id p M S have := IsLocalization.flat S p ⟨fun _ ↦ .trans R S M, fun _ ↦ .of_isLocalizedModule S p .id⟩ variable (Mₚ : ∀ (P : Ideal S) [P.IsMaximal], Type*) [∀ (P : Ideal S) [P.IsMaximal], AddCommMonoid (Mₚ P)] [∀ (P : Ideal S) [P.IsMaximal], Module R (Mₚ P)] [∀ (P : Ideal S) [P.IsMaximal], Module S (Mₚ P)] [∀ (P : Ideal S) [P.IsMaximal], IsScalarTower R S (Mₚ P)] (f : ∀ (P : Ideal S) [P.IsMaximal], M →ₗ[S] Mₚ P) [∀ (P : Ideal S) [P.IsMaximal], IsLocalizedModule.AtPrime P (f P)] include f in theorem flat_of_isLocalized_maximal (H : ∀ (P : Ideal S) [P.IsMaximal], Flat R (Mₚ P)) : Module.Flat R M := by simp_rw [Flat.iff_lTensor_injectiveₛ] at H ⊢ simp_rw [← AlgebraTensorModule.coe_lTensor (A := S)] refine fun _ _ _ N ↦ injective_of_isLocalized_maximal _ (fun P ↦ AlgebraTensorModule.rTensor R _ (f P)) _ (fun P ↦ AlgebraTensorModule.rTensor R _ (f P)) _ fun P hP ↦ ?_ simpa [IsLocalizedModule.map_lTensor] using H P N theorem flat_of_localized_maximal (h : ∀ (P : Ideal R) [P.IsMaximal], Flat R (LocalizedModule P.primeCompl M)) : Flat R M := flat_of_isLocalized_maximal _ _ _ (fun _ _ ↦ mkLinearMap _ _) h variable (s : Set S) (spn : Ideal.span s = ⊤) (Mₛ : ∀ _ : s, Type*) [∀ r : s, AddCommMonoid (Mₛ r)] [∀ r : s, Module R (Mₛ r)] [∀ r : s, Module S (Mₛ r)] [∀ r : s, IsScalarTower R S (Mₛ r)] (g : ∀ r : s, M →ₗ[S] Mₛ r) [∀ r : s, IsLocalizedModule.Away r.1 (g r)] include spn include g in theorem flat_of_isLocalized_span (H : ∀ r : s, Module.Flat R (Mₛ r)) : Module.Flat R M := by simp_rw [Flat.iff_lTensor_injectiveₛ] at H ⊢ simp_rw [← AlgebraTensorModule.coe_lTensor (A := S)] refine fun _ _ _ N ↦ injective_of_isLocalized_span s spn _ (fun r ↦ AlgebraTensorModule.rTensor R _ (g r)) _ (fun r ↦ AlgebraTensorModule.rTensor R _ (g r)) _ fun r ↦ ?_ simpa [IsLocalizedModule.map_lTensor] using H r N theorem flat_of_localized_span (h : ∀ r : s, Flat S (LocalizedModule.Away r.1 M)) : Flat S M := flat_of_isLocalized_span _ _ _ spn _ (fun _ ↦ mkLinearMap _ _) h end Module variable {A B : Type*} [CommRing A] [CommRing B] [Algebra A B] instance [Module.Flat A B] (p : Ideal A) [p.IsPrime] (P : Ideal B) [P.IsPrime] [P.LiesOver p] : Module.Flat (Localization.AtPrime p) (Localization.AtPrime P) := by rw [Module.flat_iff_of_isLocalization (Localization.AtPrime p) p.primeCompl] exact Module.Flat.trans A B (Localization.AtPrime P)
polydiv.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import fintype bigop ssralg poly. (******************************************************************************) (* This file provides a library for the basic theory of Euclidean and pseudo- *) (* Euclidean division for polynomials over non trivial ring structures. *) (* The library defines two versions of the pseudo-euclidean division: one for *) (* coefficients in a (not necessarily commutative) non-trivial ring structure *) (* and one for coefficients equipped with a structure of integral domain. *) (* From the latter we derive the definition of the usual Euclidean division *) (* for coefficients in a field. Only the definition of the pseudo-division *) (* for coefficients in an integral domain is exported by default and benefits *) (* from notations. *) (* Also, the only theory exported by default is the one of division for *) (* polynomials with coefficients in a field. *) (* Other definitions and facts are qualified using name spaces indicating the *) (* hypotheses made on the structure of coefficients and the properties of the *) (* polynomial one divides with. *) (* *) (* Pdiv.Field (exported by the present library): *) (* edivp p q == pseudo-division of p by q with p q : {poly R} where *) (* R is an idomainType. *) (* Computes (k, quo, rem) : nat * {poly r} * {poly R}, *) (* such that size rem < size q and: *) (* + if lead_coef q is not a unit, then: *) (* (lead_coef q ^+ k) *: p = q * quo + rem *) (* + else if lead_coef q is a unit, then: *) (* p = q * quo + rem and k = 0 *) (* p %/ q == quotient (second component) computed by (edivp p q). *) (* p %% q == remainder (third component) computed by (edivp p q). *) (* scalp p q == exponent (first component) computed by (edivp p q). *) (* p %| q == tests the nullity of the remainder of the *) (* pseudo-division of p by q. *) (* rgcdp p q == Pseudo-greater common divisor obtained by performing *) (* the Euclidean algorithm on p and q using redivp as *) (* Euclidean division. *) (* p %= q == p and q are associate polynomials, i.e., p %| q and *) (* q %| p, or equivalently, p = c *: q for some nonzero *) (* constant c. *) (* gcdp p q == Pseudo-greater common divisor obtained by performing *) (* the Euclidean algorithm on p and q using edivp as *) (* Euclidean division. *) (* egcdp p q == The pair of Bezout coefficients: if e := egcdp p q, *) (* then size e.1 <= size q, size e.2 <= size p, and *) (* gcdp p q %= e.1 * p + e.2 * q *) (* coprimep p q == p and q are coprime, i.e., (gcdp p q) is a nonzero *) (* constant. *) (* gdcop q p == greatest divisor of p which is coprime to q. *) (* irreducible_poly p <-> p has only trivial (constant) divisors. *) (* mup x q == multplicity of x as a root of q *) (* *) (* Pdiv.Idomain: theory available for edivp and the related operation under *) (* the sole assumption that the ring of coefficients is canonically an *) (* integral domain (R : idomainType). *) (* *) (* Pdiv.IdomainMonic: theory available for edivp and the related operations *) (* under the assumption that the ring of coefficients is canonically *) (* and integral domain (R : idomainType) an the divisor is monic. *) (* *) (* Pdiv.IdomainUnit: theory available for edivp and the related operations *) (* under the assumption that the ring of coefficients is canonically an *) (* integral domain (R : idomainType) and the leading coefficient of the *) (* divisor is a unit. *) (* *) (* Pdiv.ClosedField: theory available for edivp and the related operation *) (* under the sole assumption that the ring of coefficients is canonically *) (* an algebraically closed field (R : closedField). *) (* *) (* Pdiv.Ring : *) (* redivp p q == pseudo-division of p by q with p q : {poly R} where R is *) (* a nzRingType. *) (* Computes (k, quo, rem) : nat * {poly r} * {poly R}, *) (* such that if rem = 0 then quo * q = p * (lead_coef q ^+ k) *) (* *) (* rdivp p q == quotient (second component) computed by (redivp p q). *) (* rmodp p q == remainder (third component) computed by (redivp p q). *) (* rscalp p q == exponent (first component) computed by (redivp p q). *) (* rdvdp p q == tests the nullity of the remainder of the pseudo-division *) (* of p by q. *) (* rgcdp p q == analogue of gcdp for coefficients in a nzRingType. *) (* rgdcop p q == analogue of gdcop for coefficients in a nzRingType. *) (*rcoprimep p q == analogue of coprimep p q for coefficients in a nzRingType. *) (* *) (* Pdiv.RingComRreg : theory of the operations defined in Pdiv.Ring, when the *) (* ring of coefficients is canonically commutative (R : comNzRingType) and *) (* the leading coefficient of the divisor is both right regular and *) (* commutes as a constant polynomial with the divisor itself *) (* *) (* Pdiv.RingMonic : theory of the operations defined in Pdiv.Ring, under the *) (* assumption that the divisor is monic. *) (* *) (* Pdiv.UnitRing: theory of the operations defined in Pdiv.Ring, when the *) (* ring R of coefficients is canonically with units (R : unitRingType). *) (* *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory. Local Open Scope ring_scope. Reserved Notation "p %= q" (at level 70, no associativity). Local Notation simp := Monoid.simpm. Module Pdiv. Module CommonRing. Section RingPseudoDivision. Variable R : nzRingType. Implicit Types d p q r : {poly R}. (* Pseudo division, defined on an arbitrary ring *) Definition redivp_rec (q : {poly R}) := let sq := size q in let cq := lead_coef q in fix loop (k : nat) (qq r : {poly R})(n : nat) {struct n} := if size r < sq then (k, qq, r) else let m := (lead_coef r) *: 'X^(size r - sq) in let qq1 := qq * cq%:P + m in let r1 := r * cq%:P - m * q in if n is n1.+1 then loop k.+1 qq1 r1 n1 else (k.+1, qq1, r1). Definition redivp_expanded_def p q := if q == 0 then (0, 0, p) else redivp_rec q 0 0 p (size p). Fact redivp_key : unit. Proof. by []. Qed. Definition redivp : {poly R} -> {poly R} -> nat * {poly R} * {poly R} := locked_with redivp_key redivp_expanded_def. Canonical redivp_unlockable := [unlockable fun redivp]. Definition rdivp p q := ((redivp p q).1).2. Definition rmodp p q := (redivp p q).2. Definition rscalp p q := ((redivp p q).1).1. Definition rdvdp p q := rmodp q p == 0. (*Definition rmultp := [rel m d | rdvdp d m].*) Lemma redivp_def p q : redivp p q = (rscalp p q, rdivp p q, rmodp p q). Proof. by rewrite /rscalp /rdivp /rmodp; case: (redivp p q) => [[]] /=. Qed. Lemma rdiv0p p : rdivp 0 p = 0. Proof. rewrite /rdivp unlock; case: ifP => // Hp; rewrite /redivp_rec !size_poly0. by rewrite polySpred ?Hp. Qed. Lemma rdivp0 p : rdivp p 0 = 0. Proof. by rewrite /rdivp unlock eqxx. Qed. Lemma rdivp_small p q : size p < size q -> rdivp p q = 0. Proof. rewrite /rdivp unlock; have [-> | _ ltpq] := eqP; first by rewrite size_poly0. by case: (size p) => [|s]; rewrite /= ltpq. Qed. Lemma leq_rdivp p q : size (rdivp p q) <= size p. Proof. have [/rdivp_small->|] := ltnP (size p) (size q); first by rewrite size_poly0. rewrite /rdivp /rmodp /rscalp unlock. have [->|q0] //= := eqVneq q 0. have: size (0 : {poly R}) <= size p by rewrite size_poly0. move: {2 3 4 6}(size p) (leqnn (size p)) => A. elim: (size p) 0%N (0 : {poly R}) {1 3 4}p (leqnn (size p)) => [|n ihn] k q1 r. by move/size_poly_leq0P->; rewrite /= size_poly0 size_poly_gt0 q0. move=> /= hrn hr hq1 hq; case: ltnP => //= hqr. have sq: 0 < size q by rewrite size_poly_gt0. have sr: 0 < size r by apply: leq_trans sq hqr. apply: ihn => //. - apply/leq_sizeP => j hnj. rewrite coefB -scalerAl coefZ coefXnM ltn_subRL ltnNge. have hj : (size r).-1 <= j by apply: leq_trans hnj; rewrite -ltnS prednK. rewrite [leqLHS]polySpred -?size_poly_gt0 // coefMC. rewrite (leq_ltn_trans hj) /=; last by rewrite -add1n leq_add2r. move: hj; rewrite leq_eqVlt prednK // => /predU1P [<- | hj]. by rewrite -subn1 subnAC subKn // !subn1 !lead_coefE subrr. have/leq_sizeP-> //: size q <= j - (size r - size q). by rewrite subnBA // leq_psubRL // leq_add2r. by move/leq_sizeP: (hj) => -> //; rewrite mul0r mulr0 subr0. - apply: leq_trans (size_polyD _ _) _; rewrite geq_max; apply/andP; split. apply: leq_trans (size_polyMleq _ _) _. by rewrite size_polyC lead_coef_eq0 q0 /= addn1. rewrite size_polyN; apply: leq_trans (size_polyMleq _ _) _. apply: leq_trans hr; rewrite -subn1 leq_subLR -[in (1 + _)%N](subnK hqr). by rewrite addnA leq_add2r add1n -(@size_polyXn R) size_scale_leq. apply: leq_trans (size_polyD _ _) _; rewrite geq_max; apply/andP; split. apply: leq_trans (size_polyMleq _ _) _. by rewrite size_polyC lead_coef_eq0 q0 /= addnS addn0. apply: leq_trans (size_scale_leq _ _) _. by rewrite size_polyXn -subSn // leq_subLR -add1n leq_add. Qed. Lemma rmod0p p : rmodp 0 p = 0. Proof. rewrite /rmodp unlock; case: ifP => // Hp; rewrite /redivp_rec !size_poly0. by rewrite polySpred ?Hp. Qed. Lemma rmodp0 p : rmodp p 0 = p. Proof. by rewrite /rmodp unlock eqxx. Qed. Lemma rscalp_small p q : size p < size q -> rscalp p q = 0. Proof. rewrite /rscalp unlock; case: eqP => _ // spq. by case sp: (size p) => [| s] /=; rewrite spq. Qed. Lemma ltn_rmodp p q : (size (rmodp p q) < size q) = (q != 0). Proof. rewrite /rdivp /rmodp /rscalp unlock; have [->|q0] := eqVneq q 0. by rewrite /= size_poly0 ltn0. elim: (size p) 0%N 0 {1 3}p (leqnn (size p)) => [|n ihn] k q1 r. move/size_poly_leq0P->. by rewrite /= size_poly0 size_poly_gt0 q0 size_poly0 size_poly_gt0. move=> hr /=; case: (ltnP (size r)) => // hsrq; apply/ihn/leq_sizeP => j hnj. rewrite coefB -scalerAl !coefZ coefXnM coefMC ltn_subRL ltnNge. have sq: 0 < size q by rewrite size_poly_gt0. have sr: 0 < size r by apply: leq_trans hsrq. have hj: (size r).-1 <= j by apply: leq_trans hnj; rewrite -ltnS prednK. move: (leq_add sq hj); rewrite add1n prednK // => -> /=. move: hj; rewrite leq_eqVlt prednK // => /predU1P [<- | hj]. by rewrite -predn_sub subKn // !lead_coefE subrr. have/leq_sizeP -> //: size q <= j - (size r - size q). by rewrite subnBA // leq_subRL ?leq_add2r // (leq_trans hj) // leq_addr. by move/leq_sizeP: hj => -> //; rewrite mul0r mulr0 subr0. Qed. Lemma ltn_rmodpN0 p q : q != 0 -> size (rmodp p q) < size q. Proof. by rewrite ltn_rmodp. Qed. Lemma rmodp1 p : rmodp p 1 = 0. Proof. apply/eqP; have := ltn_rmodp p 1. by rewrite !oner_neq0 -size_poly_eq0 size_poly1 ltnS leqn0. Qed. Lemma rmodp_small p q : size p < size q -> rmodp p q = p. Proof. rewrite /rmodp unlock; have [->|_] := eqP; first by rewrite size_poly0. by case sp: (size p) => [| s] Hs /=; rewrite sp Hs /=. Qed. Lemma leq_rmodp m d : size (rmodp m d) <= size m. Proof. have [/rmodp_small -> //|h] := ltnP (size m) (size d). have [->|d0] := eqVneq d 0; first by rewrite rmodp0. by apply: leq_trans h; apply: ltnW; rewrite ltn_rmodp. Qed. Lemma rmodpC p c : c != 0 -> rmodp p c%:P = 0. Proof. move=> Hc; apply/eqP; rewrite -size_poly_leq0 -ltnS. have -> : 1%N = nat_of_bool (c != 0) by rewrite Hc. by rewrite -size_polyC ltn_rmodp polyC_eq0. Qed. Lemma rdvdp0 d : rdvdp d 0. Proof. by rewrite /rdvdp rmod0p. Qed. Lemma rdvd0p n : rdvdp 0 n = (n == 0). Proof. by rewrite /rdvdp rmodp0. Qed. Lemma rdvd0pP n : reflect (n = 0) (rdvdp 0 n). Proof. by apply: (iffP idP); rewrite rdvd0p; move/eqP. Qed. Lemma rdvdpN0 p q : rdvdp p q -> q != 0 -> p != 0. Proof. by move=> pq hq; apply: contraTneq pq => ->; rewrite rdvd0p. Qed. Lemma rdvdp1 d : rdvdp d 1 = (size d == 1). Proof. rewrite /rdvdp; have [->|] := eqVneq d 0. by rewrite rmodp0 size_poly0 (negPf (oner_neq0 _)). rewrite -size_poly_leq0 -ltnS; case: ltngtP => // [|/eqP] hd _. by rewrite rmodp_small ?size_poly1 // oner_eq0. have [c cn0 ->] := size_poly1P _ hd. rewrite /rmodp unlock -size_poly_eq0 size_poly1 /= size_poly1 size_polyC cn0 /=. by rewrite polyC_eq0 (negPf cn0) !lead_coefC !scale1r subrr !size_poly0. Qed. Lemma rdvd1p m : rdvdp 1 m. Proof. by rewrite /rdvdp rmodp1. Qed. Lemma Nrdvdp_small (n d : {poly R}) : n != 0 -> size n < size d -> rdvdp d n = false. Proof. by move=> nn0 hs; rewrite /rdvdp (rmodp_small hs); apply: negPf. Qed. Lemma rmodp_eq0P p q : reflect (rmodp p q = 0) (rdvdp q p). Proof. exact: (iffP eqP). Qed. Lemma rmodp_eq0 p q : rdvdp q p -> rmodp p q = 0. Proof. exact: rmodp_eq0P. Qed. Lemma rdvdp_leq p q : rdvdp p q -> q != 0 -> size p <= size q. Proof. by move=> dvd_pq; rewrite leqNgt; apply: contra => /rmodp_small <-. Qed. Definition rgcdp p q := let: (p1, q1) := if size p < size q then (q, p) else (p, q) in if p1 == 0 then q1 else let fix loop (n : nat) (pp qq : {poly R}) {struct n} := let rr := rmodp pp qq in if rr == 0 then qq else if n is n1.+1 then loop n1 qq rr else rr in loop (size p1) p1 q1. Lemma rgcd0p : left_id 0 rgcdp. Proof. move=> p; rewrite /rgcdp size_poly0 size_poly_gt0 if_neg. case: ifP => /= [_ | nzp]; first by rewrite eqxx. by rewrite polySpred !(rmodp0, nzp) //; case: _.-1 => [|m]; rewrite rmod0p eqxx. Qed. Lemma rgcdp0 : right_id 0 rgcdp. Proof. move=> p; have:= rgcd0p p; rewrite /rgcdp size_poly0 size_poly_gt0. by case: eqVneq => p0; rewrite ?(eqxx, p0) //= eqxx. Qed. Lemma rgcdpE p q : rgcdp p q = if size p < size q then rgcdp (rmodp q p) p else rgcdp (rmodp p q) q. Proof. pose rgcdp_rec := fix rgcdp_rec (n : nat) (pp qq : {poly R}) {struct n} := let rr := rmodp pp qq in if rr == 0 then qq else if n is n1.+1 then rgcdp_rec n1 qq rr else rr. have Irec: forall m n p q, size q <= m -> size q <= n -> size q < size p -> rgcdp_rec m p q = rgcdp_rec n p q. + elim=> [|m Hrec] [|n] //= p1 q1. - move/size_poly_leq0P=> -> _; rewrite size_poly0 size_poly_gt0 rmodp0. by move/negPf->; case: n => [|n] /=; rewrite rmod0p eqxx. - move=> _ /size_poly_leq0P ->; rewrite size_poly0 size_poly_gt0 rmodp0. by move/negPf->; case: m {Hrec} => [|m] /=; rewrite rmod0p eqxx. case: eqVneq => Epq Sm Sn Sq //; have [->|nzq] := eqVneq q1 0. by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite rmod0p eqxx. apply: Hrec; last by rewrite ltn_rmodp. by rewrite -ltnS (leq_trans _ Sm) // ltn_rmodp. by rewrite -ltnS (leq_trans _ Sn) // ltn_rmodp. have [->|nzp] := eqVneq p 0. by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same. have [->|nzq] := eqVneq q 0. by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same. rewrite /rgcdp -/rgcdp_rec !ltn_rmodp (negPf nzp) (negPf nzq) /=. have [ltpq|leqp] := ltnP; rewrite !(negPf nzp, negPf nzq) //= polySpred //=. have [->|nzqp] := eqVneq. by case: (size p) => [|[|s]]; rewrite /= rmodp0 (negPf nzp) // rmod0p eqxx. apply: Irec => //; last by rewrite ltn_rmodp. by rewrite -ltnS -polySpred // (leq_trans _ ltpq) ?leqW // ltn_rmodp. by rewrite ltnW // ltn_rmodp. have [->|nzpq] := eqVneq. by case: (size q) => [|[|s]]; rewrite /= rmodp0 (negPf nzq) // rmod0p eqxx. apply: Irec => //; last by rewrite ltn_rmodp. by rewrite -ltnS -polySpred // (leq_trans _ leqp) // ltn_rmodp. by rewrite ltnW // ltn_rmodp. Qed. Variant comm_redivp_spec m d : nat * {poly R} * {poly R} -> Type := ComEdivnSpec k (q r : {poly R}) of (GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ k)%:P = q * d + r) & (d != 0 -> size r < size d) : comm_redivp_spec m d (k, q, r). Lemma comm_redivpP m d : comm_redivp_spec m d (redivp m d). Proof. rewrite unlock; have [->|Hd] := eqVneq d 0. by constructor; rewrite !(simp, eqxx). have: GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ 0)%:P = 0 * d + m. by rewrite !simp. elim: (size m) 0%N 0 {1 4 6}m (leqnn (size m)) => [|n IHn] k q r Hr /=. move/size_poly_leq0P: Hr ->. suff hsd: size (0: {poly R}) < size d by rewrite hsd => /= ?; constructor. by rewrite size_poly0 size_poly_gt0. case: ltnP => Hlt Heq; first by constructor. apply/IHn=> [|Cda]; last first. rewrite mulrDl addrAC -addrA subrK exprSr polyCM mulrA Heq //. by rewrite mulrDl -mulrA Cda mulrA. apply/leq_sizeP => j Hj; rewrite coefB coefMC -scalerAl coefZ coefXnM. rewrite ltn_subRL ltnNge (leq_trans Hr) /=; last first. by apply: leq_ltn_trans Hj _; rewrite -add1n leq_add2r size_poly_gt0. move: Hj; rewrite leq_eqVlt; case/predU1P => [<-{j} | Hj]; last first. rewrite !nth_default ?simp ?oppr0 ?(leq_trans Hr) //. by rewrite -{1}(subKn Hlt) leq_sub2r // (leq_trans Hr). move: Hr; rewrite leq_eqVlt ltnS; case/predU1P=> Hqq; last first. by rewrite !nth_default ?simp ?oppr0 // -{1}(subKn Hlt) leq_sub2r. rewrite /lead_coef Hqq polySpred // subSS subKn ?addrN //. by rewrite -subn1 leq_subLR add1n -Hqq. Qed. Lemma rmodpp p : GRing.comm p (lead_coef p)%:P -> rmodp p p = 0. Proof. move=> hC; rewrite /rmodp unlock; have [-> //|] := eqVneq. rewrite -size_poly_eq0 /redivp_rec; case sp: (size p)=> [|n] // _. rewrite sp ltnn subnn expr0 hC alg_polyC !simp subrr. by case: n sp => [|n] sp; rewrite size_polyC /= eqxx. Qed. Definition rcoprimep (p q : {poly R}) := size (rgcdp p q) == 1. Fixpoint rgdcop_rec q p n := if n is m.+1 then if rcoprimep p q then p else rgdcop_rec q (rdivp p (rgcdp p q)) m else (q == 0)%:R. Definition rgdcop q p := rgdcop_rec q p (size p). Lemma rgdcop0 q : rgdcop q 0 = (q == 0)%:R. Proof. by rewrite /rgdcop size_poly0. Qed. End RingPseudoDivision. End CommonRing. Module RingComRreg. Import CommonRing. Section ComRegDivisor. Variable R : nzRingType. Variable d : {poly R}. Hypothesis Cdl : GRing.comm d (lead_coef d)%:P. Hypothesis Rreg : GRing.rreg (lead_coef d). Implicit Types p q r : {poly R}. Lemma redivp_eq q r : size r < size d -> let k := (redivp (q * d + r) d).1.1 in let c := (lead_coef d ^+ k)%:P in redivp (q * d + r) d = (k, q * c, r * c). Proof. move=> lt_rd; case: comm_redivpP=> k q1 r1 /(_ Cdl) Heq. have dn0: d != 0 by case: (size d) lt_rd (size_poly_eq0 d) => // n _ <-. move=> /(_ dn0) Hs. have eC : q * d * (lead_coef d ^+ k)%:P = q * (lead_coef d ^+ k)%:P * d. by rewrite -mulrA polyC_exp (commrX k Cdl) mulrA. suff e1 : q1 = q * (lead_coef d ^+ k)%:P. congr (_, _, _) => //=; move/eqP: Heq. by rewrite [_ + r1]addrC -subr_eq e1 mulrDl addrAC eC subrr add0r; move/eqP. have : (q1 - q * (lead_coef d ^+ k)%:P) * d = r * (lead_coef d ^+ k)%:P - r1. apply: (@addIr _ r1); rewrite subrK. apply: (@addrI _ ((q * (lead_coef d ^+ k)%:P) * d)). by rewrite mulrDl mulNr !addrA [_ + (q1 * d)]addrC addrK -eC -mulrDl. move/eqP; rewrite -[_ == _ - _]subr_eq0 rreg_div0 //. by case/andP; rewrite subr_eq0; move/eqP. rewrite size_polyN; apply: (leq_ltn_trans (size_polyD _ _)); rewrite size_polyN. rewrite gtn_max Hs (leq_ltn_trans (size_polyMleq _ _)) //. rewrite size_polyC; case: (_ == _); last by rewrite addnS addn0. by rewrite addn0; apply: leq_ltn_trans lt_rd; case: size. Qed. (* this is a bad name *) Lemma rdivp_eq p : p * (lead_coef d ^+ (rscalp p d))%:P = (rdivp p d) * d + (rmodp p d). Proof. by rewrite /rdivp /rmodp /rscalp; case: comm_redivpP=> k q1 r1 Hc _; apply: Hc. Qed. (* section variables impose an inconvenient order on parameters *) Lemma eq_rdvdp k q1 p: p * ((lead_coef d)^+ k)%:P = q1 * d -> rdvdp d p. Proof. move=> he. have Hnq0 := rreg_lead0 Rreg; set lq := lead_coef d. pose v := rscalp p d; pose m := maxn v k. rewrite /rdvdp -(rreg_polyMC_eq0 _ (@rregX _ _ (m - v) Rreg)). suff: ((rdivp p d) * (lq ^+ (m - v))%:P - q1 * (lq ^+ (m - k))%:P) * d + (rmodp p d) * (lq ^+ (m - v))%:P == 0. rewrite rreg_div0 //; first by case/andP. by rewrite rreg_size ?ltn_rmodp //; exact: rregX. rewrite mulrDl addrAC mulNr -!mulrA polyC_exp -(commrX (m-v) Cdl). rewrite -polyC_exp mulrA -mulrDl -rdivp_eq // [(_ ^+ (m - k))%:P]polyC_exp. rewrite -(commrX (m-k) Cdl) -polyC_exp mulrA -he -!mulrA -!polyCM -/v. by rewrite -!exprD addnC subnK ?leq_maxl // addnC subnK ?subrr ?leq_maxr. Qed. Variant rdvdp_spec p q : {poly R} -> bool -> Type := | Rdvdp k q1 & p * ((lead_coef q)^+ k)%:P = q1 * q : rdvdp_spec p q 0 true | RdvdpN & rmodp p q != 0 : rdvdp_spec p q (rmodp p q) false. (* Is that version useable ? *) Lemma rdvdp_eqP p : rdvdp_spec p d (rmodp p d) (rdvdp d p). Proof. case hdvd: (rdvdp d p); last by apply: RdvdpN; move/rmodp_eq0P/eqP: hdvd. move/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ (rscalp p d) (rdivp p d)). by rewrite rdivp_eq //; move/rmodp_eq0P: (hdvd)->; rewrite addr0. Qed. Lemma rdvdp_mull p : rdvdp d (p * d). Proof. by apply: (@eq_rdvdp 0 p); rewrite expr0 mulr1. Qed. Lemma rmodp_mull p : rmodp (p * d) d = 0. Proof. exact/eqP/rdvdp_mull. Qed. Lemma rmodpp : rmodp d d = 0. Proof. by rewrite -[d in rmodp d _]mul1r rmodp_mull. Qed. Lemma rdivpp : rdivp d d = (lead_coef d ^+ rscalp d d)%:P. Proof. have dn0 : d != 0 by rewrite -lead_coef_eq0 rreg_neq0. move: (rdivp_eq d); rewrite rmodpp addr0. suff ->: GRing.comm d (lead_coef d ^+ rscalp d d)%:P by move/(rreg_lead Rreg)->. by rewrite polyC_exp; apply: commrX. Qed. Lemma rdvdpp : rdvdp d d. Proof. exact/eqP/rmodpp. Qed. Lemma rdivpK p : rdvdp d p -> rdivp p d * d = p * (lead_coef d ^+ rscalp p d)%:P. Proof. by rewrite rdivp_eq /rdvdp; move/eqP->; rewrite addr0. Qed. End ComRegDivisor. End RingComRreg. Module RingMonic. Import CommonRing. Import RingComRreg. Section RingMonic. Variable R : nzRingType. Implicit Types p q r : {poly R}. Section MonicDivisor. Variable d : {poly R}. Hypothesis mond : d \is monic. Lemma redivp_eq q r : size r < size d -> let k := (redivp (q * d + r) d).1.1 in redivp (q * d + r) d = (k, q, r). Proof. case: (monic_comreg mond)=> Hc Hr /(redivp_eq Hc Hr q). by rewrite (eqP mond) => -> /=; rewrite expr1n !mulr1. Qed. Lemma rdivp_eq p : p = rdivp p d * d + rmodp p d. Proof. rewrite -rdivp_eq (eqP mond); last exact: commr1. by rewrite expr1n mulr1. Qed. Lemma rdivpp : rdivp d d = 1. Proof. by case: (monic_comreg mond) => hc hr; rewrite rdivpp // (eqP mond) expr1n. Qed. Lemma rdivp_addl_mul_small q r : size r < size d -> rdivp (q * d + r) d = q. Proof. by move=> Hd; case: (monic_comreg mond)=> Hc Hr; rewrite /rdivp redivp_eq. Qed. Lemma rdivp_addl_mul q r : rdivp (q * d + r) d = q + rdivp r d. Proof. case: (monic_comreg mond)=> Hc Hr; rewrite [r in _ * _ + r]rdivp_eq addrA. by rewrite -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0. Qed. Lemma rdivpDl q r : rdvdp d q -> rdivp (q + r) d = rdivp q d + rdivp r d. Proof. case: (monic_comreg mond)=> Hc Hr; rewrite [r in q + r]rdivp_eq addrA. rewrite [q in q + _ + _]rdivp_eq; move/rmodp_eq0P->. by rewrite addr0 -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0. Qed. Lemma rdivpDr q r : rdvdp d r -> rdivp (q + r) d = rdivp q d + rdivp r d. Proof. by rewrite addrC; move/rdivpDl->; rewrite addrC. Qed. Lemma rdivp_mull p : rdivp (p * d) d = p. Proof. by rewrite -[p * d]addr0 rdivp_addl_mul rdiv0p addr0. Qed. Lemma rmodp_mull p : rmodp (p * d) d = 0. Proof. by apply: rmodp_mull; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. Lemma rmodpp : rmodp d d = 0. Proof. by apply: rmodpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. Lemma rmodp_addl_mul_small q r : size r < size d -> rmodp (q * d + r) d = r. Proof. by move=> Hd; case: (monic_comreg mond)=> Hc Hr; rewrite /rmodp redivp_eq. Qed. Lemma rmodp_id (p : {poly R}) : rmodp (rmodp p d) d = rmodp p d. Proof. by rewrite rmodp_small // ltn_rmodpN0 // monic_neq0. Qed. Lemma rmodpD p q : rmodp (p + q) d = rmodp p d + rmodp q d. Proof. rewrite [p in LHS]rdivp_eq [q in LHS]rdivp_eq addrACA -mulrDl. rewrite rmodp_addl_mul_small //; apply: (leq_ltn_trans (size_polyD _ _)). by rewrite gtn_max !ltn_rmodp // monic_neq0. Qed. Lemma rmodpN p : rmodp (- p) d = - (rmodp p d). Proof. rewrite {1}(rdivp_eq p) opprD // -mulNr rmodp_addl_mul_small //. by rewrite size_polyN ltn_rmodp // monic_neq0. Qed. Lemma rmodpB p q : rmodp (p - q) d = rmodp p d - rmodp q d. Proof. by rewrite rmodpD rmodpN. Qed. Lemma rmodpZ a p : rmodp (a *: p) d = a *: (rmodp p d). Proof. case: (altP (a =P 0%R)) => [-> | cn0]; first by rewrite !scale0r rmod0p. have -> : ((a *: p) = (a *: (rdivp p d)) * d + a *: (rmodp p d))%R. by rewrite -scalerAl -scalerDr -rdivp_eq. rewrite rmodp_addl_mul_small //. rewrite -mul_polyC; apply: leq_ltn_trans (size_polyMleq _ _) _. rewrite size_polyC cn0 addSn add0n /= ltn_rmodp. exact: monic_neq0. Qed. Lemma rmodp_sum (I : Type) (r : seq I) (P : pred I) (F : I -> {poly R}) : rmodp (\sum_(i <- r | P i) F i) d = (\sum_(i <- r | P i) (rmodp (F i) d)). Proof. by elim/big_rec2: _ => [|i p q _ <-]; rewrite ?(rmod0p, rmodpD). Qed. Lemma rmodp_mulmr p q : rmodp (p * (rmodp q d)) d = rmodp (p * q) d. Proof. by rewrite [q in RHS]rdivp_eq mulrDr rmodpD mulrA rmodp_mull add0r. Qed. Lemma rdvdpp : rdvdp d d. Proof. by apply: rdvdpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1]. Qed. (* section variables impose an inconvenient order on parameters *) Lemma eq_rdvdp q1 p : p = q1 * d -> rdvdp d p. Proof. (* this probably means I need to specify impl args for comm_rref_rdvdp *) move=> h; apply: (@eq_rdvdp _ _ _ _ 1 q1); rewrite (eqP mond). - exact: commr1. - exact: rreg1. by rewrite expr1n mulr1. Qed. Lemma rdvdp_mull p : rdvdp d (p * d). Proof. by apply: rdvdp_mull; rewrite (eqP mond) //; [apply: commr1 | apply: rreg1]. Qed. Lemma rdvdpP p : reflect (exists qq, p = qq * d) (rdvdp d p). Proof. case: (monic_comreg mond)=> Hc Hr; apply: (iffP idP) => [|[qq] /eq_rdvdp //]. by case: rdvdp_eqP=> // k qq; rewrite (eqP mond) expr1n mulr1 => ->; exists qq. Qed. Lemma rdivpK p : rdvdp d p -> (rdivp p d) * d = p. Proof. by move=> dvddp; rewrite [RHS]rdivp_eq rmodp_eq0 ?addr0. Qed. End MonicDivisor. Lemma drop_poly_rdivp n p : drop_poly n p = rdivp p 'X^n. Proof. rewrite -[p in RHS](poly_take_drop n) addrC rdivp_addl_mul ?monicXn//. by rewrite rdivp_small ?addr0// size_polyXn ltnS size_take_poly. Qed. Lemma take_poly_rmodp n p : take_poly n p = rmodp p 'X^n. Proof. have mX := monicXn R n; rewrite -[p in RHS](poly_take_drop n) rmodpD//. by rewrite rmodp_small ?rmodp_mull ?addr0// size_polyXn ltnS size_take_poly. Qed. End RingMonic. Section ComRingMonic. Variable R : comNzRingType. Implicit Types p q r : {poly R}. Variable d : {poly R}. Hypothesis mond : d \is monic. Lemma rmodp_mulml p q : rmodp (rmodp p d * q) d = rmodp (p * q) d. Proof. by rewrite [in LHS]mulrC [in RHS]mulrC rmodp_mulmr. Qed. Lemma rmodpX p n : rmodp ((rmodp p d) ^+ n) d = rmodp (p ^+ n) d. Proof. elim: n => [|n IH]; first by rewrite !expr0. rewrite !exprS -rmodp_mulmr // IH rmodp_mulmr //. by rewrite mulrC rmodp_mulmr // mulrC. Qed. Lemma rmodp_compr p q : rmodp (p \Po (rmodp q d)) d = (rmodp (p \Po q) d). Proof. elim/poly_ind: p => [|p c IH]; first by rewrite !comp_polyC !rmod0p. rewrite !comp_polyD !comp_polyM addrC rmodpD //. rewrite mulrC -rmodp_mulmr // IH rmodp_mulmr //. rewrite !comp_polyX !comp_polyC. by rewrite mulrC rmodp_mulmr // -rmodpD // addrC. Qed. End ComRingMonic. End RingMonic. Module Ring. Include CommonRing. Import RingMonic. Section ExtraMonicDivisor. Variable R : nzRingType. Implicit Types d p q r : {poly R}. Lemma rdivp1 p : rdivp p 1 = p. Proof. by rewrite -[p in LHS]mulr1 rdivp_mull // monic1. Qed. Lemma rdvdp_XsubCl p x : rdvdp ('X - x%:P) p = root p x. Proof. have [HcX Hr] := monic_comreg (monicXsubC x). apply/rmodp_eq0P/factor_theorem => [|[p1 ->]]; last exact/rmodp_mull/monicXsubC. move=> e0; exists (rdivp p ('X - x%:P)). by rewrite [LHS](rdivp_eq (monicXsubC x)) e0 addr0. Qed. Lemma polyXsubCP p x : reflect (p.[x] = 0) (rdvdp ('X - x%:P) p). Proof. by apply: (iffP idP); rewrite rdvdp_XsubCl; move/rootP. Qed. Lemma root_factor_theorem p x : root p x = (rdvdp ('X - x%:P) p). Proof. by rewrite rdvdp_XsubCl. Qed. End ExtraMonicDivisor. End Ring. Module ComRing. Import Ring. Import RingComRreg. Section CommutativeRingPseudoDivision. Variable R : comNzRingType. Implicit Types d p q m n r : {poly R}. Variant redivp_spec (m d : {poly R}) : nat * {poly R} * {poly R} -> Type := EdivnSpec k (q r: {poly R}) of (lead_coef d ^+ k) *: m = q * d + r & (d != 0 -> size r < size d) : redivp_spec m d (k, q, r). Lemma redivpP m d : redivp_spec m d (redivp m d). Proof. rewrite redivp_def; constructor; last by move=> dn0; rewrite ltn_rmodp. by rewrite -mul_polyC mulrC rdivp_eq //= /GRing.comm mulrC. Qed. Lemma rdivp_eq d p : (lead_coef d ^+ rscalp p d) *: p = rdivp p d * d + rmodp p d. Proof. by rewrite /rdivp /rmodp /rscalp; case: redivpP=> k q1 r1 Hc _; apply: Hc. Qed. Lemma rdvdp_eqP d p : rdvdp_spec p d (rmodp p d) (rdvdp d p). Proof. case hdvd: (rdvdp d p); last by move/rmodp_eq0P/eqP/RdvdpN: hdvd. move/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ _ (rscalp p d) (rdivp p d)). by rewrite mulrC mul_polyC rdivp_eq; move/rmodp_eq0P: (hdvd)->; rewrite addr0. Qed. Lemma rdvdp_eq q p : rdvdp q p = (lead_coef q ^+ rscalp p q *: p == rdivp p q * q). Proof. rewrite rdivp_eq; apply/rmodp_eq0P/eqP => [->|/eqP]; first by rewrite addr0. by rewrite eq_sym addrC -subr_eq subrr; move/eqP<-. Qed. End CommutativeRingPseudoDivision. End ComRing. Module UnitRing. Import Ring. Section UnitRingPseudoDivision. Variable R : unitRingType. Implicit Type p q r d : {poly R}. Lemma uniq_roots_rdvdp p rs : all (root p) rs -> uniq_roots rs -> rdvdp (\prod_(z <- rs) ('X - z%:P)) p. Proof. move=> rrs /(uniq_roots_prod_XsubC rrs) [q ->]. exact/RingMonic.rdvdp_mull/monic_prod_XsubC. Qed. End UnitRingPseudoDivision. End UnitRing. Module IdomainDefs. Import Ring. Section IDomainPseudoDivisionDefs. Variable R : idomainType. Implicit Type p q r d : {poly R}. Definition edivp_expanded_def p q := let: (k, d, r) as edvpq := redivp p q in if lead_coef q \in GRing.unit then (0, (lead_coef q)^-k *: d, (lead_coef q)^-k *: r) else edvpq. Fact edivp_key : unit. Proof. by []. Qed. Definition edivp := locked_with edivp_key edivp_expanded_def. Canonical edivp_unlockable := [unlockable fun edivp]. Definition divp p q := ((edivp p q).1).2. Definition modp p q := (edivp p q).2. Definition scalp p q := ((edivp p q).1).1. Definition dvdp p q := modp q p == 0. Definition eqp p q := (dvdp p q) && (dvdp q p). End IDomainPseudoDivisionDefs. Notation "m %/ d" := (divp m d) : ring_scope. Notation "m %% d" := (modp m d) : ring_scope. Notation "p %| q" := (dvdp p q) : ring_scope. Notation "p %= q" := (eqp p q) : ring_scope. End IdomainDefs. Module WeakIdomain. Import Ring ComRing UnitRing IdomainDefs. Section WeakTheoryForIDomainPseudoDivision. Variable R : idomainType. Implicit Type p q r d : {poly R}. Lemma edivp_def p q : edivp p q = (scalp p q, divp p q, modp p q). Proof. by rewrite /scalp /divp /modp; case: (edivp p q) => [[]] /=. Qed. Lemma edivp_redivp p q : lead_coef q \in GRing.unit = false -> edivp p q = redivp p q. Proof. by move=> hu; rewrite unlock hu; case: (redivp p q) => [[? ?] ?]. Qed. Lemma divpE p q : p %/ q = if lead_coef q \in GRing.unit then lead_coef q ^- rscalp p q *: rdivp p q else rdivp p q. Proof. by case: ifP; rewrite /divp unlock redivp_def => ->. Qed. Lemma modpE p q : p %% q = if lead_coef q \in GRing.unit then lead_coef q ^- rscalp p q *: (rmodp p q) else rmodp p q. Proof. by case: ifP; rewrite /modp unlock redivp_def => ->. Qed. Lemma scalpE p q : scalp p q = if lead_coef q \in GRing.unit then 0 else rscalp p q. Proof. by case: ifP; rewrite /scalp unlock redivp_def => ->. Qed. Lemma dvdpE p q : p %| q = rdvdp p q. Proof. rewrite /dvdp modpE /rdvdp; case ulcq: (lead_coef p \in GRing.unit)=> //. rewrite -[in LHS]size_poly_eq0 size_scale ?size_poly_eq0 //. by rewrite invr_eq0 expf_neq0 //; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma lc_expn_scalp_neq0 p q : lead_coef q ^+ scalp p q != 0. Proof. have [->|nzq] := eqVneq q 0; last by rewrite expf_neq0 ?lead_coef_eq0. by rewrite /scalp 2!unlock /= eqxx lead_coef0 unitr0 /= oner_neq0. Qed. Hint Resolve lc_expn_scalp_neq0 : core. Variant edivp_spec (m d : {poly R}) : nat * {poly R} * {poly R} -> bool -> Type := |Redivp_spec k (q r: {poly R}) of (lead_coef d ^+ k) *: m = q * d + r & lead_coef d \notin GRing.unit & (d != 0 -> size r < size d) : edivp_spec m d (k, q, r) false |Fedivp_spec (q r: {poly R}) of m = q * d + r & (lead_coef d \in GRing.unit) & (d != 0 -> size r < size d) : edivp_spec m d (0, q, r) true. (* There are several ways to state this fact. The most appropriate statement*) (* might be polished in light of usage. *) Lemma edivpP m d : edivp_spec m d (edivp m d) (lead_coef d \in GRing.unit). Proof. have hC : GRing.comm d (lead_coef d)%:P by rewrite /GRing.comm mulrC. case ud: (lead_coef d \in GRing.unit); last first. rewrite edivp_redivp // redivp_def; constructor; rewrite ?ltn_rmodp // ?ud //. by rewrite rdivp_eq. have cdn0: lead_coef d != 0 by apply: contraTneq ud => ->; rewrite unitr0. rewrite unlock ud redivp_def; constructor => //. rewrite -scalerAl -scalerDr -mul_polyC. have hn0 : (lead_coef d ^+ rscalp m d)%:P != 0. by rewrite polyC_eq0; apply: expf_neq0. apply: (mulfI hn0); rewrite !mulrA -exprVn !polyC_exp -exprMn -polyCM. by rewrite divrr // expr1n mul1r -polyC_exp mul_polyC rdivp_eq. move=> dn0; rewrite size_scale ?ltn_rmodp // -exprVn expf_eq0 negb_and. by rewrite invr_eq0 cdn0 orbT. Qed. Lemma edivp_eq d q r : size r < size d -> lead_coef d \in GRing.unit -> edivp (q * d + r) d = (0, q, r). Proof. have hC : GRing.comm d (lead_coef d)%:P by apply: mulrC. move=> hsrd hu; rewrite unlock hu; case et: (redivp _ _) => [[s qq] rr]. have cdn0 : lead_coef d != 0 by case: eqP hu => //= ->; rewrite unitr0. move: (et); rewrite RingComRreg.redivp_eq //; last exact/rregP. rewrite et /= mulrC (mulrC r) !mul_polyC; case=> <- <-. by rewrite !scalerA mulVr ?scale1r // unitrX. Qed. Lemma divp_eq p q : (lead_coef q ^+ scalp p q) *: p = (p %/ q) * q + (p %% q). Proof. rewrite divpE modpE scalpE. case uq: (lead_coef q \in GRing.unit); last by rewrite rdivp_eq. rewrite expr0 scale1r; have [->|qn0] := eqVneq q 0. by rewrite lead_coef0 expr0n /rscalp unlock eqxx invr1 !scale1r rmodp0 !simp. by rewrite -scalerAl -scalerDr -rdivp_eq scalerA mulVr (scale1r, unitrX). Qed. Lemma dvdp_eq q p : (q %| p) = (lead_coef q ^+ scalp p q *: p == (p %/ q) * q). Proof. rewrite dvdpE rdvdp_eq scalpE divpE; case: ifP => ulcq //. rewrite expr0 scale1r -scalerAl; apply/eqP/eqP => [<- | {2}->]. by rewrite scalerA mulVr ?scale1r // unitrX. by rewrite scalerA mulrV ?scale1r // unitrX. Qed. Lemma divpK d p : d %| p -> p %/ d * d = (lead_coef d ^+ scalp p d) *: p. Proof. by rewrite dvdp_eq; move/eqP->. Qed. Lemma divpKC d p : d %| p -> d * (p %/ d) = (lead_coef d ^+ scalp p d) *: p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdpP q p : reflect (exists2 cqq, cqq.1 != 0 & cqq.1 *: p = cqq.2 * q) (q %| p). Proof. rewrite dvdp_eq; apply: (iffP eqP) => [e | [[c qq] cn0 e]]. by exists (lead_coef q ^+ scalp p q, p %/ q) => //=. apply/eqP; rewrite -dvdp_eq dvdpE. have Ecc: c%:P != 0 by rewrite polyC_eq0. have [->|nz_p] := eqVneq p 0; first by rewrite rdvdp0. pose p1 : {poly R} := lead_coef q ^+ rscalp p q *: qq - c *: (rdivp p q). have E1: c *: rmodp p q = p1 * q. rewrite mulrDl mulNr -scalerAl -e scalerA mulrC -scalerA -scalerAl. by rewrite -scalerBr rdivp_eq addrC addKr. suff: p1 * q == 0 by rewrite -E1 -mul_polyC mulf_eq0 (negPf Ecc). rewrite mulf_eq0; apply/norP; case=> p1_nz q_nz; have:= ltn_rmodp p q. by rewrite q_nz -(size_scale _ cn0) E1 size_mul // polySpred // ltnNge leq_addl. Qed. Lemma mulpK p q : q != 0 -> p * q %/ q = lead_coef q ^+ scalp (p * q) q *: p. Proof. move=> qn0; apply: (rregP qn0); rewrite -scalerAl divp_eq. suff -> : (p * q) %% q = 0 by rewrite addr0. rewrite modpE RingComRreg.rmodp_mull ?scaler0 ?if_same //. by red; rewrite mulrC. by apply/rregP; rewrite lead_coef_eq0. Qed. Lemma mulKp p q : q != 0 -> q * p %/ q = lead_coef q ^+ scalp (p * q) q *: p. Proof. by move=> nzq; rewrite mulrC; apply: mulpK. Qed. Lemma divpp p : p != 0 -> p %/ p = (lead_coef p ^+ scalp p p)%:P. Proof. move=> np0; have := divp_eq p p. suff -> : p %% p = 0 by rewrite addr0 -mul_polyC; move/(mulIf np0). rewrite modpE Ring.rmodpp; last by red; rewrite mulrC. by rewrite scaler0 if_same. Qed. End WeakTheoryForIDomainPseudoDivision. #[global] Hint Resolve lc_expn_scalp_neq0 : core. End WeakIdomain. Module CommonIdomain. Import Ring ComRing UnitRing IdomainDefs WeakIdomain. Section IDomainPseudoDivision. Variable R : idomainType. Implicit Type p q r d m n : {poly R}. Lemma scalp0 p : scalp p 0 = 0. Proof. by rewrite /scalp unlock lead_coef0 unitr0 unlock eqxx. Qed. Lemma divp_small p q : size p < size q -> p %/ q = 0. Proof. move=> spq; rewrite /divp unlock redivp_def /=. by case: ifP; rewrite rdivp_small // scaler0. Qed. Lemma leq_divp p q : (size (p %/ q) <= size p). Proof. rewrite /divp unlock redivp_def /=; case: ifP => ulcq; rewrite ?leq_rdivp //=. rewrite size_scale ?leq_rdivp // -exprVn expf_neq0 // invr_eq0. by case: eqP ulcq => // ->; rewrite unitr0. Qed. Lemma div0p p : 0 %/ p = 0. Proof. by rewrite /divp unlock redivp_def /=; case: ifP; rewrite rdiv0p // scaler0. Qed. Lemma divp0 p : p %/ 0 = 0. Proof. by rewrite /divp unlock redivp_def /=; case: ifP; rewrite rdivp0 // scaler0. Qed. Lemma divp1 m : m %/ 1 = m. Proof. by rewrite divpE lead_coefC unitr1 Ring.rdivp1 expr1n invr1 scale1r. Qed. Lemma modp0 p : p %% 0 = p. Proof. rewrite /modp unlock redivp_def; case: ifP; rewrite rmodp0 //= lead_coef0. by rewrite unitr0. Qed. Lemma mod0p p : 0 %% p = 0. Proof. by rewrite /modp unlock redivp_def /=; case: ifP; rewrite rmod0p // scaler0. Qed. Lemma modp1 p : p %% 1 = 0. Proof. by rewrite /modp unlock redivp_def /=; case: ifP; rewrite rmodp1 // scaler0. Qed. Hint Resolve divp0 divp1 mod0p modp0 modp1 : core. Lemma modp_small p q : size p < size q -> p %% q = p. Proof. move=> spq; rewrite /modp unlock redivp_def; case: ifP; rewrite rmodp_small //. by rewrite /= rscalp_small // expr0 /= invr1 scale1r. Qed. Lemma modpC p c : c != 0 -> p %% c%:P = 0. Proof. move=> cn0; rewrite /modp unlock redivp_def /=; case: ifP; rewrite ?rmodpC //. by rewrite scaler0. Qed. Lemma modp_mull p q : (p * q) %% q = 0. Proof. have [-> | nq0] := eqVneq q 0; first by rewrite modp0 mulr0. have rlcq : GRing.rreg (lead_coef q) by apply/rregP; rewrite lead_coef_eq0. have hC : GRing.comm q (lead_coef q)%:P by red; rewrite mulrC. rewrite modpE; case: ifP => ulcq; rewrite RingComRreg.rmodp_mull //. exact: scaler0. Qed. Lemma modp_mulr d p : (d * p) %% d = 0. Proof. by rewrite mulrC modp_mull. Qed. Lemma modpp d : d %% d = 0. Proof. by rewrite -[d in d %% _]mul1r modp_mull. Qed. Lemma ltn_modp p q : (size (p %% q) < size q) = (q != 0). Proof. rewrite /modp unlock redivp_def /=; case: ifP=> ulcq; rewrite ?ltn_rmodp //=. rewrite size_scale ?ltn_rmodp // -exprVn expf_neq0 // invr_eq0. by case: eqP ulcq => // ->; rewrite unitr0. Qed. Lemma ltn_divpl d q p : d != 0 -> (size (q %/ d) < size p) = (size q < size (p * d)). Proof. move=> dn0. have: (lead_coef d) ^+ (scalp q d) != 0 by apply: lc_expn_scalp_neq0. move/(size_scale q)<-; rewrite divp_eq; have [->|quo0] := eqVneq (q %/ d) 0. rewrite mul0r add0r size_poly0 size_poly_gt0. have [->|pn0] := eqVneq p 0; first by rewrite mul0r size_poly0 ltn0. by rewrite size_mul // (polySpred pn0) addSn ltn_addl // ltn_modp. rewrite size_polyDl; last first. by rewrite size_mul // (polySpred quo0) addSn /= ltn_addl // ltn_modp. have [->|pn0] := eqVneq p 0; first by rewrite mul0r size_poly0 !ltn0. by rewrite !size_mul ?quo0 // (polySpred dn0) !addnS ltn_add2r. Qed. Lemma leq_divpr d p q : d != 0 -> (size p <= size (q %/ d)) = (size (p * d) <= size q). Proof. by move=> dn0; rewrite leqNgt ltn_divpl // -leqNgt. Qed. Lemma divpN0 d p : d != 0 -> (p %/ d != 0) = (size d <= size p). Proof. move=> dn0. by rewrite -[d in RHS]mul1r -leq_divpr // size_polyC oner_eq0 size_poly_gt0. Qed. Lemma size_divp p q : q != 0 -> size (p %/ q) = (size p - (size q).-1)%N. Proof. move=> nq0; case: (leqP (size q) (size p)) => sqp; last first. move: (sqp); rewrite -{1}(ltn_predK sqp) ltnS -subn_eq0 divp_small //. by move/eqP->; rewrite size_poly0. have np0 : p != 0. by rewrite -size_poly_gt0; apply: leq_trans sqp; rewrite size_poly_gt0. have /= := congr1 (size \o @polyseq R) (divp_eq p q). rewrite size_scale; last by rewrite expf_eq0 lead_coef_eq0 (negPf nq0) andbF. have [->|qq0] := eqVneq (p %/ q) 0. by rewrite mul0r add0r=> es; move: nq0; rewrite -(ltn_modp p) -es ltnNge sqp. rewrite size_polyDl. by move->; apply/eqP; rewrite size_mul // (polySpred nq0) addnS /= addnK. rewrite size_mul ?qq0 //. move: nq0; rewrite -(ltn_modp p); move/leq_trans; apply. by rewrite (polySpred qq0) addSn /= leq_addl. Qed. Lemma ltn_modpN0 p q : q != 0 -> size (p %% q) < size q. Proof. by rewrite ltn_modp. Qed. Lemma modp_id p q : (p %% q) %% q = p %% q. Proof. by have [->|qn0] := eqVneq q 0; rewrite ?modp0 // modp_small ?ltn_modp. Qed. Lemma leq_modp m d : size (m %% d) <= size m. Proof. rewrite /modp unlock redivp_def /=; case: ifP; rewrite ?leq_rmodp //. move=> ud; rewrite size_scale ?leq_rmodp // invr_eq0 expf_neq0 //. by apply: contraTneq ud => ->; rewrite unitr0. Qed. Lemma dvdp0 d : d %| 0. Proof. by rewrite /dvdp mod0p. Qed. Hint Resolve dvdp0 : core. Lemma dvd0p p : (0 %| p) = (p == 0). Proof. by rewrite /dvdp modp0. Qed. Lemma dvd0pP p : reflect (p = 0) (0 %| p). Proof. by apply: (iffP idP); rewrite dvd0p; move/eqP. Qed. Lemma dvdpN0 p q : p %| q -> q != 0 -> p != 0. Proof. by move=> pq hq; apply: contraTneq pq => ->; rewrite dvd0p. Qed. Lemma dvdp1 d : (d %| 1) = (size d == 1). Proof. rewrite /dvdp modpE; case ud: (lead_coef d \in GRing.unit); last exact: rdvdp1. rewrite -size_poly_eq0 size_scale; first by rewrite size_poly_eq0 -rdvdp1. by rewrite invr_eq0 expf_neq0 //; apply: contraTneq ud => ->; rewrite unitr0. Qed. Lemma dvd1p m : 1 %| m. Proof. by rewrite /dvdp modp1. Qed. Lemma gtNdvdp p q : p != 0 -> size p < size q -> (q %| p) = false. Proof. by move=> nn0 hs; rewrite /dvdp; rewrite (modp_small hs); apply: negPf. Qed. Lemma modp_eq0P p q : reflect (p %% q = 0) (q %| p). Proof. exact: (iffP eqP). Qed. Lemma modp_eq0 p q : (q %| p) -> p %% q = 0. Proof. exact: modp_eq0P. Qed. Lemma leq_divpl d p q : d %| p -> (size (p %/ d) <= size q) = (size p <= size (q * d)). Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | nd0 hd]. by rewrite divp0 size_poly0 !leq0n. rewrite leq_eqVlt ltn_divpl // (leq_eqVlt (size p)). case lhs: (size p < size (q * d)); rewrite ?orbT ?orbF //. have: (lead_coef d) ^+ (scalp p d) != 0 by rewrite expf_neq0 // lead_coef_eq0. move/(size_scale p)<-; rewrite divp_eq; move/modp_eq0P: hd->; rewrite addr0. have [-> | quon0] := eqVneq (p %/ d) 0. rewrite mul0r size_poly0 2!(eq_sym 0) !size_poly_eq0. by rewrite mulf_eq0 (negPf nd0) orbF. have [-> | nq0] := eqVneq q 0. by rewrite mul0r size_poly0 !size_poly_eq0 mulf_eq0 (negPf nd0) orbF. by rewrite !size_mul // (polySpred nd0) !addnS /= eqn_add2r. Qed. Lemma dvdp_leq p q : q != 0 -> p %| q -> size p <= size q. Proof. move=> nq0 /modp_eq0P. by case: leqP => // /modp_small -> /eqP; rewrite (negPf nq0). Qed. Lemma eq_dvdp c quo q p : c != 0 -> c *: p = quo * q -> q %| p. Proof. move=> cn0; case: (eqVneq p 0) => [->|nz_quo def_quo] //. pose p1 : {poly R} := lead_coef q ^+ scalp p q *: quo - c *: (p %/ q). have E1: c *: (p %% q) = p1 * q. rewrite mulrDl mulNr -scalerAl -def_quo scalerA mulrC -scalerA. by rewrite -scalerAl -scalerBr divp_eq addrAC subrr add0r. rewrite /dvdp; apply/idPn=> m_nz. have: p1 * q != 0 by rewrite -E1 -mul_polyC mulf_neq0 // polyC_eq0. rewrite mulf_eq0; case/norP=> p1_nz q_nz. have := ltn_modp p q; rewrite q_nz -(size_scale (p %% q) cn0) E1. by rewrite size_mul // polySpred // ltnNge leq_addl. Qed. Lemma dvdpp d : d %| d. Proof. by rewrite /dvdp modpp. Qed. Hint Resolve dvdpp : core. Lemma divp_dvd p q : p %| q -> (q %/ p) %| q. Proof. have [-> | np0] := eqVneq p 0; first by rewrite divp0. rewrite dvdp_eq => /eqP h. apply: (@eq_dvdp ((lead_coef p)^+ (scalp q p)) p); last by rewrite mulrC. by rewrite expf_neq0 // lead_coef_eq0. Qed. Lemma dvdp_mull m d n : d %| n -> d %| m * n. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite mulr0 dvdpp. rewrite dvdp_eq => /eqP e. apply: (@eq_dvdp (lead_coef d ^+ scalp n d) (m * (n %/ d))). by rewrite expf_neq0 // lead_coef_eq0. by rewrite scalerAr e mulrA. Qed. Lemma dvdp_mulr n d m : d %| m -> d %| m * n. Proof. by move=> hdm; rewrite mulrC dvdp_mull. Qed. Hint Resolve dvdp_mull dvdp_mulr : core. Lemma dvdp_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2. Proof. case: (eqVneq d1 0) => [-> /dvd0pP -> | d1n0]; first by rewrite !mul0r dvdpp. case: (eqVneq d2 0) => [-> _ /dvd0pP -> | d2n0]; first by rewrite !mulr0. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Hq1. rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Hq2. apply: (@eq_dvdp (c1 * c2) (q1 * q2)). by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. rewrite -scalerA scalerAr scalerAl Hq1 Hq2 -!mulrA. by rewrite [d1 * (q2 * _)]mulrCA. Qed. Lemma dvdp_addr m d n : d %| m -> (d %| m + n) = (d %| n). Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite add0r. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1. apply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 - c2 *: q1) _ _ sn0). rewrite mulrDl -scaleNr -!scalerAl -Eq1 -Eq2 !scalerA. by rewrite mulNr mulrC scaleNr -scalerBr addrC addKr. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 + c2 *: q1) _ _ sn0). by rewrite mulrDl -!scalerAl -Eq1 -Eq2 !scalerA mulrC addrC scalerDr. Qed. Lemma dvdp_addl n d m : d %| n -> (d %| m + n) = (d %| m). Proof. by rewrite addrC; apply: dvdp_addr. Qed. Lemma dvdp_add d m n : d %| m -> d %| n -> d %| m + n. Proof. by move/dvdp_addr->. Qed. Lemma dvdp_add_eq d m n : d %| m + n -> (d %| m) = (d %| n). Proof. by move=> ?; apply/idP/idP; [move/dvdp_addr <-| move/dvdp_addl <-]. Qed. Lemma dvdp_subr d m n : d %| m -> (d %| m - n) = (d %| n). Proof. by move=> ?; apply: dvdp_add_eq; rewrite -addrA addNr simp. Qed. Lemma dvdp_subl d m n : d %| n -> (d %| m - n) = (d %| m). Proof. by move/dvdp_addl<-; rewrite subrK. Qed. Lemma dvdp_sub d m n : d %| m -> d %| n -> d %| m - n. Proof. by move=> *; rewrite dvdp_subl. Qed. Lemma dvdp_mod d n m : d %| n -> (d %| m) = (d %| m %% n). Proof. have [-> | nn0] := eqVneq n 0; first by rewrite modp0. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite modp0. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1. apply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _. have sn0 : c1 * c2 != 0. by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF. pose quo := (c1 * lead_coef n ^+ scalp m n) *: q2 - c2 *: (m %/ n) * q1. move/eqP=> Eq2; apply: (@eq_dvdp _ quo _ _ sn0). rewrite mulrDl mulNr -!scalerAl -!mulrA -Eq1 -Eq2 -scalerAr !scalerA. rewrite mulrC [_ * c2]mulrC mulrA -[((_ * _) * _) *: _]scalerA -scalerBr. by rewrite divp_eq addrC addKr. have sn0 : c1 * c2 * lead_coef n ^+ scalp m n != 0. rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 ?(negPf dn0) ?andbF //. by rewrite (negPf nn0) andbF. move/eqP=> Eq2; apply: (@eq_dvdp _ (c2 *: (m %/ n) * q1 + c1 *: q2) _ _ sn0). rewrite -scalerA divp_eq scalerDr -!scalerA Eq2 scalerAl scalerAr Eq1. by rewrite scalerAl mulrDl mulrA. Qed. Lemma dvdp_trans : transitive (@dvdp R). Proof. move=> n d m. case: (eqVneq d 0) => [-> /dvd0pP -> // | dn0]. case: (eqVneq n 0) => [-> _ /dvd0pP -> // | nn0]. rewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Hq1. rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Hq2. have sn0 : c1 * c2 != 0 by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. apply: (@eq_dvdp _ (q2 * q1) _ _ sn0). by rewrite -scalerA Hq2 scalerAr Hq1 mulrA. Qed. Lemma dvdp_mulIl p q : p %| p * q. Proof. exact/dvdp_mulr/dvdpp. Qed. Lemma dvdp_mulIr p q : q %| p * q. Proof. exact/dvdp_mull/dvdpp. Qed. Lemma dvdp_mul2r r p q : r != 0 -> (p * r %| q * r) = (p %| q). Proof. move=> nzr. have [-> | pn0] := eqVneq p 0. by rewrite mul0r !dvd0p mulf_eq0 (negPf nzr) orbF. have [-> | qn0] := eqVneq q 0; first by rewrite mul0r !dvdp0. apply/idP/idP; last by move=> ?; rewrite dvdp_mul ?dvdpp. rewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> Hx. apply: (@eq_dvdp c x); first by rewrite expf_neq0 // lead_coef_eq0 mulf_neq0. by apply: (mulIf nzr); rewrite -mulrA -scalerAl. Qed. Lemma dvdp_mul2l r p q: r != 0 -> (r * p %| r * q) = (p %| q). Proof. by rewrite ![r * _]mulrC; apply: dvdp_mul2r. Qed. Lemma ltn_divpr d p q : d %| q -> (size p < size (q %/ d)) = (size (p * d) < size q). Proof. by move=> dv_d_q; rewrite !ltnNge leq_divpl. Qed. Lemma dvdp_exp d k p : 0 < k -> d %| p -> d %| (p ^+ k). Proof. by case: k => // k _ d_dv_m; rewrite exprS dvdp_mulr. Qed. Lemma dvdp_exp2l d k l : k <= l -> d ^+ k %| d ^+ l. Proof. by move/subnK <-; rewrite exprD dvdp_mull // ?lead_coef_exp ?unitrX. Qed. Lemma dvdp_Pexp2l d k l : 1 < size d -> (d ^+ k %| d ^+ l) = (k <= l). Proof. move=> sd; case: leqP => [|gt_n_m]; first exact: dvdp_exp2l. have dn0 : d != 0 by rewrite -size_poly_gt0; apply: ltn_trans sd. rewrite gtNdvdp ?expf_neq0 // polySpred ?expf_neq0 // size_exp /=. rewrite [size (d ^+ k)]polySpred ?expf_neq0 // size_exp ltnS ltn_mul2l. by move: sd; rewrite -subn_gt0 subn1; move->. Qed. Lemma dvdp_exp2r p q k : p %| q -> p ^+ k %| q ^+ k. Proof. case: (eqVneq p 0) => [-> /dvd0pP -> // | pn0]. rewrite dvdp_eq; set c := _ ^+ _; set t := _ %/ _; move/eqP=> e. apply: (@eq_dvdp (c ^+ k) (t ^+ k)); first by rewrite !expf_neq0 ?lead_coef_eq0. by rewrite -exprMn -exprZn; congr (_ ^+ k). Qed. Lemma dvdp_exp_sub p q k l: p != 0 -> (p ^+ k %| q * p ^+ l) = (p ^+ (k - l) %| q). Proof. move=> pn0; case: (leqP k l)=> [|/ltnW] hkl. move: (hkl); rewrite -subn_eq0; move/eqP->; rewrite expr0 dvd1p. exact/dvdp_mull/dvdp_exp2l. by rewrite -[in LHS](subnK hkl) exprD dvdp_mul2r // expf_eq0 (negPf pn0) andbF. Qed. Lemma dvdp_XsubCl p x : ('X - x%:P) %| p = root p x. Proof. by rewrite dvdpE; apply: Ring.rdvdp_XsubCl. Qed. Lemma root_dvdp p q x : p %| q -> root p x -> root q x. Proof. by rewrite -!dvdp_XsubCl => /[swap]; exact: dvdp_trans. Qed. Lemma polyXsubCP p x : reflect (p.[x] = 0) (('X - x%:P) %| p). Proof. by rewrite dvdpE; apply: Ring.polyXsubCP. Qed. Lemma eqp_div_XsubC p c : (p == (p %/ ('X - c%:P)) * ('X - c%:P)) = ('X - c%:P %| p). Proof. by rewrite dvdp_eq lead_coefXsubC expr1n scale1r. Qed. Lemma root_factor_theorem p x : root p x = (('X - x%:P) %| p). Proof. by rewrite dvdp_XsubCl. Qed. Lemma uniq_roots_dvdp p rs : all (root p) rs -> uniq_roots rs -> (\prod_(z <- rs) ('X - z%:P)) %| p. Proof. move=> rrs; case/(uniq_roots_prod_XsubC rrs)=> q ->. by apply: dvdp_mull; rewrite // (eqP (monic_prod_XsubC _)) unitr1. Qed. Lemma root_bigmul x (ps : seq {poly R}) : ~~root (\big[*%R/1]_(p <- ps) p) x = all (fun p => ~~ root p x) ps. Proof. elim: ps => [|p ps ihp]; first by rewrite big_nil root1. by rewrite big_cons /= rootM negb_or ihp. Qed. Lemma eqpP m n : reflect (exists2 c12, (c12.1 != 0) && (c12.2 != 0) & c12.1 *: m = c12.2 *: n) (m %= n). Proof. apply: (iffP idP) => [| [[c1 c2]/andP[nz_c1 nz_c2 eq_cmn]]]; last first. rewrite /eqp (@eq_dvdp c2 c1%:P) -?eq_cmn ?mul_polyC // (@eq_dvdp c1 c2%:P)//. by rewrite eq_cmn mul_polyC. case: (eqVneq m 0) => [-> /andP [/dvd0pP -> _] | m_nz]. by exists (1, 1); rewrite ?scaler0 // oner_eq0. case: (eqVneq n 0) => [-> /andP [_ /dvd0pP ->] | n_nz /andP []]. by exists (1, 1); rewrite ?scaler0 // oner_eq0. rewrite !dvdp_eq; set c1 := _ ^+ _; set c2 := _ ^+ _. set q1 := _ %/ _; set q2 := _ %/ _; move/eqP => Hq1 /eqP Hq2; have Hc1 : c1 != 0 by rewrite expf_eq0 lead_coef_eq0 negb_and m_nz orbT. have Hc2 : c2 != 0 by rewrite expf_eq0 lead_coef_eq0 negb_and n_nz orbT. have def_q12: q1 * q2 = (c1 * c2)%:P. apply: (mulIf m_nz); rewrite mulrAC mulrC -Hq1 -scalerAr -Hq2 scalerA. by rewrite -mul_polyC. have: q1 * q2 != 0 by rewrite def_q12 -size_poly_eq0 size_polyC mulf_neq0. rewrite mulf_eq0; case/norP=> nz_q1 nz_q2. have: size q2 <= 1. have:= size_mul nz_q1 nz_q2; rewrite def_q12 size_polyC mulf_neq0 //=. by rewrite polySpred // => ->; rewrite leq_addl. rewrite leq_eqVlt ltnS size_poly_leq0 (negPf nz_q2) orbF. case/size_poly1P=> c cn0 cqe; exists (c2, c); first by rewrite Hc2. by rewrite Hq2 -mul_polyC -cqe. Qed. Lemma eqp_eq p q: p %= q -> (lead_coef q) *: p = (lead_coef p) *: q. Proof. move=> /eqpP [[c1 c2] /= /andP [nz_c1 nz_c2]] eq. have/(congr1 lead_coef) := eq; rewrite !lead_coefZ. move=> eqC; apply/(@mulfI _ c2%:P); rewrite ?polyC_eq0 //. by rewrite !mul_polyC scalerA -eqC mulrC -scalerA eq !scalerA mulrC. Qed. Lemma eqpxx : reflexive (@eqp R). Proof. by move=> p; rewrite /eqp dvdpp. Qed. Hint Resolve eqpxx : core. Lemma eqpW p q : p = q -> p %= q. Proof. by move->; rewrite eqpxx. Qed. Lemma eqp_sym : symmetric (@eqp R). Proof. by move=> p q; rewrite /eqp andbC. Qed. Lemma eqp_trans : transitive (@eqp R). Proof. move=> p q r; case/andP=> Dp pD; case/andP=> Dq qD. by rewrite /eqp (dvdp_trans Dp) // (dvdp_trans qD). Qed. Lemma eqp_ltrans : left_transitive (@eqp R). Proof. exact: sym_left_transitive eqp_sym eqp_trans. Qed. Lemma eqp_rtrans : right_transitive (@eqp R). Proof. exact: sym_right_transitive eqp_sym eqp_trans. Qed. Lemma eqp0 p : (p %= 0) = (p == 0). Proof. by apply/idP/eqP => [/andP [_ /dvd0pP] | -> //]. Qed. Lemma eqp01 : 0 %= (1 : {poly R}) = false. Proof. by rewrite eqp_sym eqp0 oner_eq0. Qed. Lemma eqp_scale p c : c != 0 -> c *: p %= p. Proof. move=> c0; apply/eqpP; exists (1, c); first by rewrite c0 oner_eq0. by rewrite scale1r. Qed. Lemma eqp_size p q : p %= q -> size p = size q. Proof. have [->|Eq] := eqVneq q 0; first by rewrite eqp0; move/eqP->. rewrite eqp_sym; have [->|Ep] := eqVneq p 0; first by rewrite eqp0; move/eqP->. by case/andP => Dp Dq; apply: anti_leq; rewrite !dvdp_leq. Qed. Lemma size_poly_eq1 p : (size p == 1) = (p %= 1). Proof. apply/size_poly1P/idP=> [[c cn0 ep] |]. by apply/eqpP; exists (1, c); rewrite ?oner_eq0 // alg_polyC scale1r. by move/eqp_size; rewrite size_poly1; move/eqP/size_poly1P. Qed. Lemma polyXsubC_eqp1 (x : R) : ('X - x%:P %= 1) = false. Proof. by rewrite -size_poly_eq1 size_XsubC. Qed. Lemma dvdp_eqp1 p q : p %| q -> q %= 1 -> p %= 1. Proof. move=> dpq hq. have sizeq : size q == 1 by rewrite size_poly_eq1. have n0q : q != 0 by case: eqP hq => // ->; rewrite eqp01. rewrite -size_poly_eq1 eqn_leq -{1}(eqP sizeq) dvdp_leq //= size_poly_gt0. by apply/eqP => p0; move: dpq n0q; rewrite p0 dvd0p => ->. Qed. Lemma eqp_dvdr q p d: p %= q -> d %| p = (d %| q). Proof. suff Hmn m n: m %= n -> (d %| m) -> (d %| n). by move=> mn; apply/idP/idP; apply: Hmn=> //; rewrite eqp_sym. by rewrite /eqp; case/andP=> pq qp dp; apply: (dvdp_trans dp). Qed. Lemma eqp_dvdl d2 d1 p : d1 %= d2 -> d1 %| p = (d2 %| p). suff Hmn m n: m %= n -> (m %| p) -> (n %| p). by move=> ?; apply/idP/idP; apply: Hmn; rewrite // eqp_sym. by rewrite /eqp; case/andP=> dd' d'd dp; apply: (dvdp_trans d'd). Qed. Lemma dvdpZr c m n : c != 0 -> m %| c *: n = (m %| n). Proof. by move=> cn0; exact/eqp_dvdr/eqp_scale. Qed. Lemma dvdpZl c m n : c != 0 -> (c *: m %| n) = (m %| n). Proof. by move=> cn0; exact/eqp_dvdl/eqp_scale. Qed. Lemma dvdpNl d p : (- d) %| p = (d %| p). Proof. by rewrite -scaleN1r; apply/eqp_dvdl/eqp_scale; rewrite oppr_eq0 oner_neq0. Qed. Lemma dvdpNr d p : d %| (- p) = (d %| p). Proof. by apply: eqp_dvdr; rewrite -scaleN1r eqp_scale ?oppr_eq0 ?oner_eq0. Qed. Lemma eqp_mul2r r p q : r != 0 -> (p * r %= q * r) = (p %= q). Proof. by move=> nz_r; rewrite /eqp !dvdp_mul2r. Qed. Lemma eqp_mul2l r p q: r != 0 -> (r * p %= r * q) = (p %= q). Proof. by move=> nz_r; rewrite /eqp !dvdp_mul2l. Qed. Lemma eqp_mull r p q: q %= r -> p * q %= p * r. Proof. case/eqpP=> [[c d]] /andP [c0 d0 e]; apply/eqpP; exists (c, d); rewrite ?c0 //. by rewrite scalerAr e -scalerAr. Qed. Lemma eqp_mulr q p r : p %= q -> p * r %= q * r. Proof. by move=> epq; rewrite ![_ * r]mulrC eqp_mull. Qed. Lemma eqp_exp p q k : p %= q -> p ^+ k %= q ^+ k. Proof. move=> pq; elim: k=> [|k ihk]; first by rewrite !expr0 eqpxx. by rewrite !exprS (@eqp_trans (q * p ^+ k)) // (eqp_mulr, eqp_mull). Qed. Lemma polyC_eqp1 (c : R) : (c%:P %= 1) = (c != 0). Proof. apply/eqpP/idP => [[[x y]] |nc0] /=. case: (eqVneq c) => [->|] //= /andP [_] /negPf <- /eqP. by rewrite alg_polyC scaler0 eq_sym polyC_eq0. exists (1, c); first by rewrite nc0 /= oner_neq0. by rewrite alg_polyC scale1r. Qed. Lemma dvdUp d p: d %= 1 -> d %| p. Proof. by move/eqp_dvdl->; rewrite dvd1p. Qed. Lemma dvdp_size_eqp p q : p %| q -> size p == size q = (p %= q). Proof. move=> pq; apply/idP/idP; last by move/eqp_size->. have [->|Hq] := eqVneq q 0; first by rewrite size_poly0 size_poly_eq0 eqp0. have [->|Hp] := eqVneq p 0. by rewrite size_poly0 eq_sym size_poly_eq0 eqp_sym eqp0. move: pq; rewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> eqpq. have /= := congr1 (size \o @polyseq R) eqpq. have cn0 : c != 0 by rewrite expf_neq0 // lead_coef_eq0. rewrite (@eqp_size _ q); last exact: eqp_scale. rewrite size_mul ?p0 // => [-> HH|]; last first. apply/eqP=> HH; move: eqpq; rewrite HH mul0r. by move/eqP; rewrite scale_poly_eq0 (negPf Hq) (negPf cn0). suff: size x == 1%N. case/size_poly1P=> y H1y H2y. by apply/eqpP; exists (y, c); rewrite ?H1y // eqpq H2y mul_polyC. case: (size p) HH (size_poly_eq0 p)=> [|n]; first by case: eqP Hp. by rewrite addnS -add1n eqn_add2r; move/eqP->. Qed. Lemma eqp_root p q : p %= q -> root p =1 root q. Proof. move/eqpP=> [[c d]] /andP [c0 d0 e] x; move/negPf:c0=>c0; move/negPf:d0=>d0. by rewrite rootE -[_==_]orFb -c0 -mulf_eq0 -hornerZ e hornerZ mulf_eq0 d0. Qed. Lemma eqp_rmod_mod p q : rmodp p q %= modp p q. Proof. rewrite modpE eqp_sym; case: ifP => ulcq //. apply: eqp_scale; rewrite invr_eq0 //. by apply: expf_neq0; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma eqp_rdiv_div p q : rdivp p q %= divp p q. Proof. rewrite divpE eqp_sym; case: ifP=> ulcq//; apply: eqp_scale; rewrite invr_eq0//. by apply: expf_neq0; apply: contraTneq ulcq => ->; rewrite unitr0. Qed. Lemma dvd_eqp_divl d p q (dvd_dp : d %| q) (eq_pq : p %= q) : p %/ d %= q %/ d. Proof. case: (eqVneq q 0) eq_pq=> [->|q_neq0]; first by rewrite eqp0=> /eqP->. have d_neq0: d != 0 by apply: contraTneq dvd_dp=> ->; rewrite dvd0p. move=> eq_pq; rewrite -(@eqp_mul2r d) // !divpK // ?(eqp_dvdr _ eq_pq) //. rewrite (eqp_ltrans (eqp_scale _ _)) ?lc_expn_scalp_neq0 //. by rewrite (eqp_rtrans (eqp_scale _ _)) ?lc_expn_scalp_neq0. Qed. Definition gcdp p q := let: (p1, q1) := if size p < size q then (q, p) else (p, q) in if p1 == 0 then q1 else let fix loop (n : nat) (pp qq : {poly R}) {struct n} := let rr := modp pp qq in if rr == 0 then qq else if n is n1.+1 then loop n1 qq rr else rr in loop (size p1) p1 q1. Arguments gcdp : simpl never. Lemma gcd0p : left_id 0 gcdp. Proof. move=> p; rewrite /gcdp size_poly0 size_poly_gt0 if_neg. case: ifP => /= [_ | nzp]; first by rewrite eqxx. by rewrite polySpred !(modp0, nzp) //; case: _.-1 => [|m]; rewrite mod0p eqxx. Qed. Lemma gcdp0 : right_id 0 gcdp. Proof. move=> p; have:= gcd0p p; rewrite /gcdp size_poly0 size_poly_gt0. by case: eqVneq => //= ->; rewrite eqxx. Qed. Lemma gcdpE p q : gcdp p q = if size p < size q then gcdp (modp q p) p else gcdp (modp p q) q. Proof. pose gcdpE_rec := fix gcdpE_rec (n : nat) (pp qq : {poly R}) {struct n} := let rr := modp pp qq in if rr == 0 then qq else if n is n1.+1 then gcdpE_rec n1 qq rr else rr. have Irec: forall k l p q, size q <= k -> size q <= l -> size q < size p -> gcdpE_rec k p q = gcdpE_rec l p q. + elim=> [|m Hrec] [|n] //= p1 q1. - move/size_poly_leq0P=> -> _; rewrite size_poly0 size_poly_gt0 modp0. by move/negPf ->; case: n => [|n] /=; rewrite mod0p eqxx. - move=> _ /size_poly_leq0P ->; rewrite size_poly0 size_poly_gt0 modp0. by move/negPf ->; case: m {Hrec} => [|m] /=; rewrite mod0p eqxx. case: eqP => Epq Sm Sn Sq //; have [->|nzq] := eqVneq q1 0. by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite mod0p eqxx. apply: Hrec; last by rewrite ltn_modp. by rewrite -ltnS (leq_trans _ Sm) // ltn_modp. by rewrite -ltnS (leq_trans _ Sn) // ltn_modp. have [->|nzp] := eqVneq p 0; first by rewrite mod0p modp0 gcd0p gcdp0 if_same. have [->|nzq] := eqVneq q 0; first by rewrite mod0p modp0 gcd0p gcdp0 if_same. rewrite /gcdp !ltn_modp !(negPf nzp, negPf nzq) /=. have [ltpq|leqp] := ltnP; rewrite !(negPf nzp, negPf nzq) /= polySpred //. have [->|nzqp] := eqVneq. by case: (size p) => [|[|s]]; rewrite /= modp0 (negPf nzp) // mod0p eqxx. apply: Irec => //; last by rewrite ltn_modp. by rewrite -ltnS -polySpred // (leq_trans _ ltpq) ?leqW // ltn_modp. by rewrite ltnW // ltn_modp. case: eqVneq => [->|nzpq]. by case: (size q) => [|[|s]]; rewrite /= modp0 (negPf nzq) // mod0p eqxx. apply: Irec => //; rewrite ?ltn_modp //. by rewrite -ltnS -polySpred // (leq_trans _ leqp) // ltn_modp. by rewrite ltnW // ltn_modp. Qed. Lemma size_gcd1p p : size (gcdp 1 p) = 1. Proof. rewrite gcdpE size_polyC oner_eq0 /= modp1; have [|/size1_polyC ->] := ltnP. by rewrite gcd0p size_polyC oner_eq0. have [->|p00] := eqVneq p`_0 0; first by rewrite modp0 gcdp0 size_poly1. by rewrite modpC // gcd0p size_polyC p00. Qed. Lemma size_gcdp1 p : size (gcdp p 1) = 1. Proof. rewrite gcdpE size_polyC oner_eq0 /= modp1 ltnS; case: leqP. by move/size_poly_leq0P->; rewrite gcdp0 modp0 size_polyC oner_eq0. by rewrite gcd0p size_polyC oner_eq0. Qed. Lemma gcdpp : idempotent_op gcdp. Proof. by move=> p; rewrite gcdpE ltnn modpp gcd0p. Qed. Lemma dvdp_gcdlr p q : (gcdp p q %| p) && (gcdp p q %| q). Proof. have [r] := ubnP (minn (size q) (size p)); elim: r => // r IHr in p q *. have [-> | nz_p] := eqVneq p 0; first by rewrite gcd0p dvdpp andbT. have [-> | nz_q] := eqVneq q 0; first by rewrite gcdp0 dvdpp /=. rewrite ltnS gcdpE; case: leqP => [le_pq | lt_pq] le_qr. suffices /IHr/andP[E1 E2]: minn (size q) (size (p %% q)) < r. by rewrite E2 andbT (dvdp_mod _ E2). by rewrite gtn_min orbC (leq_trans _ le_qr) ?ltn_modp. suffices /IHr/andP[E1 E2]: minn (size p) (size (q %% p)) < r. by rewrite E2 (dvdp_mod _ E2). by rewrite gtn_min orbC (leq_trans _ le_qr) ?ltn_modp. Qed. Lemma dvdp_gcdl p q : gcdp p q %| p. Proof. by case/andP: (dvdp_gcdlr p q). Qed. Lemma dvdp_gcdr p q :gcdp p q %| q. Proof. by case/andP: (dvdp_gcdlr p q). Qed. Lemma leq_gcdpl p q : p != 0 -> size (gcdp p q) <= size p. Proof. by move=> pn0; move: (dvdp_gcdl p q); apply: dvdp_leq. Qed. Lemma leq_gcdpr p q : q != 0 -> size (gcdp p q) <= size q. Proof. by move=> qn0; move: (dvdp_gcdr p q); apply: dvdp_leq. Qed. Lemma dvdp_gcd p m n : p %| gcdp m n = (p %| m) && (p %| n). Proof. apply/idP/andP=> [dv_pmn | []]. by rewrite ?(dvdp_trans dv_pmn) ?dvdp_gcdl ?dvdp_gcdr. have [r] := ubnP (minn (size n) (size m)); elim: r => // r IHr in m n *. have [-> | nz_m] := eqVneq m 0; first by rewrite gcd0p. have [-> | nz_n] := eqVneq n 0; first by rewrite gcdp0. rewrite gcdpE ltnS; case: leqP => [le_nm | lt_mn] le_r dv_m dv_n. apply: IHr => //; last by rewrite -(dvdp_mod _ dv_n). by rewrite gtn_min orbC (leq_trans _ le_r) ?ltn_modp. apply: IHr => //; last by rewrite -(dvdp_mod _ dv_m). by rewrite gtn_min orbC (leq_trans _ le_r) ?ltn_modp. Qed. Lemma gcdpC p q : gcdp p q %= gcdp q p. Proof. by rewrite /eqp !dvdp_gcd !dvdp_gcdl !dvdp_gcdr. Qed. Lemma gcd1p p : gcdp 1 p %= 1. Proof. rewrite -size_poly_eq1 gcdpE size_poly1; case: ltnP. by rewrite modp1 gcd0p size_poly1 eqxx. move/size1_polyC=> e; rewrite e. have [->|p00] := eqVneq p`_0 0; first by rewrite modp0 gcdp0 size_poly1. by rewrite modpC // gcd0p size_polyC p00. Qed. Lemma gcdp1 p : gcdp p 1 %= 1. Proof. by rewrite (eqp_ltrans (gcdpC _ _)) gcd1p. Qed. Lemma gcdp_addl_mul p q r: gcdp r (p * r + q) %= gcdp r q. Proof. suff h m n d : gcdp d n %| gcdp d (m * d + n). apply/andP; split => //. by rewrite {2}(_: q = (-p) * r + (p * r + q)) ?H // mulNr addKr. by rewrite dvdp_gcd dvdp_gcdl /= dvdp_addr ?dvdp_gcdr ?dvdp_mull ?dvdp_gcdl. Qed. Lemma gcdp_addl m n : gcdp m (m + n) %= gcdp m n. Proof. by rewrite -[m in m + _]mul1r gcdp_addl_mul. Qed. Lemma gcdp_addr m n : gcdp m (n + m) %= gcdp m n. Proof. by rewrite addrC gcdp_addl. Qed. Lemma gcdp_mull m n : gcdp n (m * n) %= n. Proof. have [-> | nn0] := eqVneq n 0; first by rewrite gcd0p mulr0 eqpxx. have [-> | mn0] := eqVneq m 0; first by rewrite mul0r gcdp0 eqpxx. rewrite gcdpE modp_mull gcd0p size_mul //; case: leqP; last by rewrite eqpxx. rewrite (polySpred mn0) addSn /= -[leqRHS]add0n leq_add2r -ltnS. rewrite -polySpred //= leq_eqVlt ltnS size_poly_leq0 (negPf mn0) orbF. case/size_poly1P=> c cn0 -> {mn0 m}; rewrite mul_polyC. suff -> : n %% (c *: n) = 0 by rewrite gcd0p; apply: eqp_scale. by apply/modp_eq0P; rewrite dvdpZl. Qed. Lemma gcdp_mulr m n : gcdp n (n * m) %= n. Proof. by rewrite mulrC gcdp_mull. Qed. Lemma gcdp_scalel c m n : c != 0 -> gcdp (c *: m) n %= gcdp m n. Proof. move=> cn0; rewrite /eqp dvdp_gcd [gcdp m n %| _]dvdp_gcd !dvdp_gcdr !andbT. apply/andP; split; last first. by apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdpZr. by apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdpZl. Qed. Lemma gcdp_scaler c m n : c != 0 -> gcdp m (c *: n) %= gcdp m n. Proof. move=> cn0; apply: eqp_trans (gcdpC _ _) _. by apply: eqp_trans (gcdp_scalel _ _ _) _ => //; apply: gcdpC. Qed. Lemma dvdp_gcd_idl m n : m %| n -> gcdp m n %= m. Proof. have [-> | mn0] := eqVneq m 0. by rewrite dvd0p => /eqP ->; rewrite gcdp0 eqpxx. rewrite dvdp_eq; move/eqP/(f_equal (gcdp m)) => h. apply: eqp_trans (gcdp_mull (n %/ m) _). by rewrite -h eqp_sym gcdp_scaler // expf_neq0 // lead_coef_eq0. Qed. Lemma dvdp_gcd_idr m n : n %| m -> gcdp m n %= n. Proof. by move/dvdp_gcd_idl; exact/eqp_trans/gcdpC. Qed. Lemma gcdp_exp p k l : gcdp (p ^+ k) (p ^+ l) %= p ^+ minn k l. Proof. case: leqP => [|/ltnW] /subnK <-; rewrite exprD; first exact: gcdp_mull. exact/(eqp_trans (gcdpC _ _))/gcdp_mull. Qed. Lemma gcdp_eq0 p q : gcdp p q == 0 = (p == 0) && (q == 0). Proof. apply/idP/idP; last by case/andP => /eqP -> /eqP ->; rewrite gcdp0. have h m n: gcdp m n == 0 -> (m == 0). by rewrite -(dvd0p m); move/eqP<-; rewrite dvdp_gcdl. by move=> ?; rewrite (h _ q) // (h _ p) // -eqp0 (eqp_ltrans (gcdpC _ _)) eqp0. Qed. Lemma eqp_gcdr p q r : q %= r -> gcdp p q %= gcdp p r. Proof. move=> eqr; rewrite /eqp !(dvdp_gcd, dvdp_gcdl, andbT) /=. by rewrite -(eqp_dvdr _ eqr) dvdp_gcdr (eqp_dvdr _ eqr) dvdp_gcdr. Qed. Lemma eqp_gcdl r p q : p %= q -> gcdp p r %= gcdp q r. Proof. move=> eqr; rewrite /eqp !(dvdp_gcd, dvdp_gcdr, andbT) /=. by rewrite -(eqp_dvdr _ eqr) dvdp_gcdl (eqp_dvdr _ eqr) dvdp_gcdl. Qed. Lemma eqp_gcd p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> gcdp p1 q1 %= gcdp p2 q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_gcdr _ e2) (eqp_gcdl _ e1). Qed. Lemma eqp_rgcd_gcd p q : rgcdp p q %= gcdp p q. Proof. move: {2}(minn (size p) (size q)) (leqnn (minn (size p) (size q))) => n. elim: n p q => [p q|n ihn p q hs]. rewrite leqn0; case: ltnP => _; rewrite size_poly_eq0; move/eqP->. by rewrite gcd0p rgcd0p eqpxx. by rewrite gcdp0 rgcdp0 eqpxx. have [-> | pn0] := eqVneq p 0; first by rewrite gcd0p rgcd0p eqpxx. have [-> | qn0] := eqVneq q 0; first by rewrite gcdp0 rgcdp0 eqpxx. rewrite gcdpE rgcdpE; case: ltnP hs => sp hs. have e := eqp_rmod_mod q p; apply/eqp_trans/ihn: (eqp_gcdl p e). by rewrite (eqp_size e) geq_min -ltnS (leq_trans _ hs) ?ltn_modp. have e := eqp_rmod_mod p q; apply/eqp_trans/ihn: (eqp_gcdl q e). by rewrite (eqp_size e) geq_min -ltnS (leq_trans _ hs) ?ltn_modp. Qed. Lemma gcdp_modl m n : gcdp (m %% n) n %= gcdp m n. Proof. have [/modp_small -> // | lenm] := ltnP (size m) (size n). by rewrite (gcdpE m n) ltnNge lenm. Qed. Lemma gcdp_modr m n : gcdp m (n %% m) %= gcdp m n. Proof. apply: eqp_trans (gcdpC _ _); apply: eqp_trans (gcdp_modl _ _); exact: gcdpC. Qed. Lemma gcdp_def d m n : d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) -> gcdp m n %= d. Proof. move=> dm dn h; rewrite /eqp dvdp_gcd dm dn !andbT. by apply: h; rewrite (dvdp_gcdl, dvdp_gcdr). Qed. Definition coprimep p q := size (gcdp p q) == 1%N. Lemma coprimep_size_gcd p q : coprimep p q -> size (gcdp p q) = 1. Proof. by rewrite /coprimep=> /eqP. Qed. Lemma coprimep_def p q : coprimep p q = (size (gcdp p q) == 1). Proof. done. Qed. Lemma coprimepZl c m n : c != 0 -> coprimep (c *: m) n = coprimep m n. Proof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scalel _ _ _)). Qed. Lemma coprimepZr c m n: c != 0 -> coprimep m (c *: n) = coprimep m n. Proof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scaler _ _ _)). Qed. Lemma coprimepp p : coprimep p p = (size p == 1). Proof. by rewrite coprimep_def gcdpp. Qed. Lemma gcdp_eqp1 p q : gcdp p q %= 1 = coprimep p q. Proof. by rewrite coprimep_def size_poly_eq1. Qed. Lemma coprimep_sym p q : coprimep p q = coprimep q p. Proof. by rewrite -!gcdp_eqp1; apply: eqp_ltrans; rewrite gcdpC. Qed. Lemma coprime1p p : coprimep 1 p. Proof. by rewrite /coprimep -[1%N](size_poly1 R); exact/eqP/eqp_size/gcd1p. Qed. Lemma coprimep1 p : coprimep p 1. Proof. by rewrite coprimep_sym; apply: coprime1p. Qed. Lemma coprimep0 p : coprimep p 0 = (p %= 1). Proof. by rewrite /coprimep gcdp0 size_poly_eq1. Qed. Lemma coprime0p p : coprimep 0 p = (p %= 1). Proof. by rewrite coprimep_sym coprimep0. Qed. (* This is different from coprimeP in div. shall we keep this? *) Lemma coprimepP p q : reflect (forall d, d %| p -> d %| q -> d %= 1) (coprimep p q). Proof. rewrite /coprimep; apply: (iffP idP) => [/eqP hs d dvddp dvddq | h]. have/dvdp_eqp1: d %| gcdp p q by rewrite dvdp_gcd dvddp dvddq. by rewrite -size_poly_eq1 hs; exact. by rewrite size_poly_eq1; case/andP: (dvdp_gcdlr p q); apply: h. Qed. Lemma coprimepPn p q : p != 0 -> reflect (exists d, (d %| gcdp p q) && ~~ (d %= 1)) (~~ coprimep p q). Proof. move=> p0; apply: (iffP idP). by rewrite -gcdp_eqp1=> ng1; exists (gcdp p q); rewrite dvdpp /=. case=> d /andP [dg]; apply: contra; rewrite -gcdp_eqp1=> g1. by move: dg; rewrite (eqp_dvdr _ g1) dvdp1 size_poly_eq1. Qed. Lemma coprimep_dvdl q p r : r %| q -> coprimep p q -> coprimep p r. Proof. move=> rp /coprimepP cpq'; apply/coprimepP => d dp dr. exact/cpq'/(dvdp_trans dr). Qed. Lemma coprimep_dvdr p q r : r %| p -> coprimep p q -> coprimep r q. Proof. by move=> rp; rewrite ![coprimep _ q]coprimep_sym; apply/coprimep_dvdl. Qed. Lemma coprimep_modl p q : coprimep (p %% q) q = coprimep p q. Proof. rewrite !coprimep_def [in RHS]gcdpE. by case: ltnP => // hpq; rewrite modp_small // gcdpE hpq. Qed. Lemma coprimep_modr q p : coprimep q (p %% q) = coprimep q p. Proof. by rewrite ![coprimep q _]coprimep_sym coprimep_modl. Qed. Lemma rcoprimep_coprimep q p : rcoprimep q p = coprimep q p. Proof. by rewrite /coprimep /rcoprimep (eqp_size (eqp_rgcd_gcd _ _)). Qed. Lemma eqp_coprimepr p q r : q %= r -> coprimep p q = coprimep p r. Proof. by rewrite -!gcdp_eqp1; move/(eqp_gcdr p)/eqp_ltrans. Qed. Lemma eqp_coprimepl p q r : q %= r -> coprimep q p = coprimep r p. Proof. by rewrite !(coprimep_sym _ p); apply: eqp_coprimepr. Qed. (* This should be implemented with an extended remainder sequence *) Fixpoint egcdp_rec p q k {struct k} : {poly R} * {poly R} := if k is k'.+1 then if q == 0 then (1, 0) else let: (u, v) := egcdp_rec q (p %% q) k' in (lead_coef q ^+ scalp p q *: v, (u - v * (p %/ q))) else (1, 0). Definition egcdp p q := if size q <= size p then egcdp_rec p q (size q) else let e := egcdp_rec q p (size p) in (e.2, e.1). (* No provable egcd0p *) Lemma egcdp0 p : egcdp p 0 = (1, 0). Proof. by rewrite /egcdp size_poly0. Qed. Lemma egcdp_recP : forall k p q, q != 0 -> size q <= k -> size q <= size p -> let e := (egcdp_rec p q k) in [/\ size e.1 <= size q, size e.2 <= size p & gcdp p q %= e.1 * p + e.2 * q]. Proof. elim=> [|k ihk] p q /= qn0; first by rewrite size_poly_leq0 (negPf qn0). move=> sqSn qsp; rewrite (negPf qn0). have sp : size p > 0 by apply: leq_trans qsp; rewrite size_poly_gt0. have [r0 | rn0] /= := eqVneq (p %%q) 0. rewrite r0 /egcdp_rec; case: k ihk sqSn => [|n] ihn sqSn /=. rewrite !scaler0 !mul0r subr0 add0r mul1r size_poly0 size_poly1. by rewrite dvdp_gcd_idr /dvdp ?r0. rewrite !eqxx mul0r scaler0 /= mul0r add0r subr0 mul1r size_poly0 size_poly1. by rewrite dvdp_gcd_idr /dvdp ?r0 //. have h1 : size (p %% q) <= k. by rewrite -ltnS; apply: leq_trans sqSn; rewrite ltn_modp. have h2 : size (p %% q) <= size q by rewrite ltnW // ltn_modp. have := ihk q (p %% q) rn0 h1 h2. case: (egcdp_rec _ _)=> u v /= => [[ihn'1 ihn'2 ihn'3]]. rewrite gcdpE ltnNge qsp //= (eqp_ltrans (gcdpC _ _)); split; last first. - apply: (eqp_trans ihn'3). rewrite mulrBl addrCA -scalerAl scalerAr -mulrA -mulrBr. by rewrite divp_eq addrAC subrr add0r eqpxx. - apply: (leq_trans (size_polyD _ _)). have [-> | vn0] := eqVneq v 0. rewrite mul0r size_polyN size_poly0 maxn0; apply: leq_trans ihn'1 _. exact: leq_modp. have [-> | qqn0] := eqVneq (p %/ q) 0. rewrite mulr0 size_polyN size_poly0 maxn0; apply: leq_trans ihn'1 _. exact: leq_modp. rewrite geq_max (leq_trans ihn'1) ?leq_modp //= size_polyN size_mul //. move: (ihn'2); rewrite (polySpred vn0) (polySpred qn0). rewrite -(ltn_add2r (size (p %/ q))) !addSn /= ltnS; move/leq_trans; apply. rewrite size_divp // addnBA ?addKn //. by apply: leq_trans qsp; apply: leq_pred. - by rewrite size_scale // lc_expn_scalp_neq0. Qed. Lemma egcdpP p q : p != 0 -> q != 0 -> forall (e := egcdp p q), [/\ size e.1 <= size q, size e.2 <= size p & gcdp p q %= e.1 * p + e.2 * q]. Proof. rewrite /egcdp => pn0 qn0; case: (leqP (size q) (size p)) => /= [|/ltnW] hp. exact: egcdp_recP. case: (egcdp_recP pn0 (leqnn (size p)) hp) => h1 h2 h3; split => //. by rewrite (eqp_ltrans (gcdpC _ _)) addrC. Qed. Lemma egcdpE p q (e := egcdp p q) : gcdp p q %= e.1 * p + e.2 * q. Proof. rewrite {}/e; have [-> /= | qn0] := eqVneq q 0. by rewrite gcdp0 egcdp0 mul1r mulr0 addr0. have [-> | pn0] := eqVneq p 0; last by case: (egcdpP pn0 qn0). by rewrite gcd0p /egcdp size_poly0 size_poly_leq0 (negPf qn0) /= !simp. Qed. Lemma Bezoutp p q : exists u, u.1 * p + u.2 * q %= (gcdp p q). Proof. have [-> | pn0] := eqVneq p 0. by rewrite gcd0p; exists (0, 1); rewrite mul0r mul1r add0r. have [-> | qn0] := eqVneq q 0. by rewrite gcdp0; exists (1, 0); rewrite mul0r mul1r addr0. pose e := egcdp p q; exists e; rewrite eqp_sym. by case: (egcdpP pn0 qn0). Qed. Lemma Bezout_coprimepP p q : reflect (exists u, u.1 * p + u.2 * q %= 1) (coprimep p q). Proof. rewrite -gcdp_eqp1; apply: (iffP idP)=> [g1|]. by case: (Bezoutp p q) => [[u v] Puv]; exists (u, v); apply: eqp_trans g1. case=> [[u v]]; rewrite eqp_sym=> Puv; rewrite /eqp (eqp_dvdr _ Puv). by rewrite dvdp_addr dvdp_mull ?dvdp_gcdl ?dvdp_gcdr //= dvd1p. Qed. Lemma coprimep_root p q x : coprimep p q -> root p x -> q.[x] != 0. Proof. case/Bezout_coprimepP=> [[u v] euv] px0. move/eqpP: euv => [[c1 c2]] /andP /= [c1n0 c2n0 e]. suffices: c1 * (v.[x] * q.[x]) != 0. by rewrite !mulf_eq0 !negb_or c1n0 /=; case/andP. have := f_equal (horner^~ x) e; rewrite /= !hornerZ hornerD. by rewrite !hornerM (eqP px0) mulr0 add0r hornerC mulr1; move->. Qed. Lemma Gauss_dvdpl p q d: coprimep d q -> (d %| p * q) = (d %| p). Proof. move/Bezout_coprimepP=>[[u v] Puv]; apply/idP/idP; last exact: dvdp_mulr. move/(eqp_mull p): Puv; rewrite mulr1 mulrDr eqp_sym=> peq dpq. rewrite (eqp_dvdr _ peq) dvdp_addr; first by rewrite mulrA mulrAC dvdp_mulr. by rewrite mulrA dvdp_mull ?dvdpp. Qed. Lemma Gauss_dvdpr p q d: coprimep d q -> (d %| q * p) = (d %| p). Proof. by rewrite mulrC; apply: Gauss_dvdpl. Qed. (* This could be simplified with the introduction of lcmp *) Lemma Gauss_dvdp m n p : coprimep m n -> (m * n %| p) = (m %| p) && (n %| p). Proof. have [-> | mn0] := eqVneq m 0. by rewrite coprime0p => /eqp_dvdl->; rewrite !mul0r dvd0p dvd1p andbT. have [-> | nn0] := eqVneq n 0. by rewrite coprimep0 => /eqp_dvdl->; rewrite !mulr0 dvd1p. move=> hc; apply/idP/idP => [mnmp | /andP [dmp dnp]]. move/Gauss_dvdpl: hc => <-; move: (dvdp_mull m mnmp); rewrite dvdp_mul2l //. move->; move: (dvdp_mulr n mnmp); rewrite dvdp_mul2r // andbT. exact: dvdp_mulr. move: (dnp); rewrite dvdp_eq. set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> e2. have/esym := Gauss_dvdpl q2 hc; rewrite -e2. have -> : m %| c2 *: p by rewrite -mul_polyC dvdp_mull. rewrite dvdp_eq; set c3 := _ ^+ _; set q3 := _ %/ _; move/eqP=> e3. apply: (@eq_dvdp (c3 * c2) q3). by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0. by rewrite mulrA -e3 -scalerAl -e2 scalerA. Qed. Lemma Gauss_gcdpr p m n : coprimep p m -> gcdp p (m * n) %= gcdp p n. Proof. move=> co_pm; apply/eqP; rewrite /eqp !dvdp_gcd !dvdp_gcdl /= andbC. rewrite dvdp_mull ?dvdp_gcdr // -(@Gauss_dvdpl _ m). by rewrite mulrC dvdp_gcdr. apply/coprimepP=> d; rewrite dvdp_gcd; case/andP=> hdp _ hdm. by move/coprimepP: co_pm; apply. Qed. Lemma Gauss_gcdpl p m n : coprimep p n -> gcdp p (m * n) %= gcdp p m. Proof. by move=> co_pn; rewrite mulrC Gauss_gcdpr. Qed. Lemma coprimepMr p q r : coprimep p (q * r) = (coprimep p q && coprimep p r). Proof. apply/coprimepP/andP=> [hp | [/coprimepP-hq hr]]. by split; apply/coprimepP=> d dp dq; rewrite hp //; [apply/dvdp_mulr | apply/dvdp_mull]. move=> d dp dqr; move/(_ _ dp) in hq. rewrite Gauss_dvdpl in dqr; first exact: hq. by move/coprimep_dvdr: hr; apply. Qed. Lemma coprimepMl p q r: coprimep (q * r) p = (coprimep q p && coprimep r p). Proof. by rewrite ![coprimep _ p]coprimep_sym coprimepMr. Qed. Lemma modp_coprime k u n : k != 0 -> (k * u) %% n %= 1 -> coprimep k n. Proof. move=> kn0 hmod; apply/Bezout_coprimepP. exists (((lead_coef n)^+(scalp (k * u) n) *: u), (- (k * u %/ n))). rewrite -scalerAl mulrC (divp_eq (u * k) n) mulNr -addrAC subrr add0r. by rewrite mulrC. Qed. Lemma coprimep_pexpl k m n : 0 < k -> coprimep (m ^+ k) n = coprimep m n. Proof. case: k => // k _; elim: k => [|k IHk]; first by rewrite expr1. by rewrite exprS coprimepMl -IHk andbb. Qed. Lemma coprimep_pexpr k m n : 0 < k -> coprimep m (n ^+ k) = coprimep m n. Proof. by move=> k_gt0; rewrite !(coprimep_sym m) coprimep_pexpl. Qed. Lemma coprimep_expl k m n : coprimep m n -> coprimep (m ^+ k) n. Proof. by case: k => [|k] co_pm; rewrite ?coprime1p // coprimep_pexpl. Qed. Lemma coprimep_expr k m n : coprimep m n -> coprimep m (n ^+ k). Proof. by rewrite !(coprimep_sym m); apply: coprimep_expl. Qed. Lemma gcdp_mul2l p q r : gcdp (p * q) (p * r) %= (p * gcdp q r). Proof. have [->|hp] := eqVneq p 0; first by rewrite !mul0r gcdp0 eqpxx. rewrite /eqp !dvdp_gcd !dvdp_mul2l // dvdp_gcdr dvdp_gcdl !andbT. move: (Bezoutp q r) => [[u v]] huv. rewrite eqp_sym in huv; rewrite (eqp_dvdr _ (eqp_mull _ huv)). rewrite mulrDr ![p * (_ * _)]mulrCA. by apply: dvdp_add; rewrite dvdp_mull// (dvdp_gcdr, dvdp_gcdl). Qed. Lemma gcdp_mul2r q r p : gcdp (q * p) (r * p) %= gcdp q r * p. Proof. by rewrite ![_ * p]mulrC gcdp_mul2l. Qed. Lemma mulp_gcdr p q r : r * (gcdp p q) %= gcdp (r * p) (r * q). Proof. by rewrite eqp_sym gcdp_mul2l. Qed. Lemma mulp_gcdl p q r : (gcdp p q) * r %= gcdp (p * r) (q * r). Proof. by rewrite eqp_sym gcdp_mul2r. Qed. Lemma coprimep_div_gcd p q : (p != 0) || (q != 0) -> coprimep (p %/ (gcdp p q)) (q %/ gcdp p q). Proof. rewrite -negb_and -gcdp_eq0 -gcdp_eqp1 => gpq0. rewrite -(@eqp_mul2r (gcdp p q)) // mul1r (eqp_ltrans (mulp_gcdl _ _ _)). have: gcdp p q %| p by rewrite dvdp_gcdl. have: gcdp p q %| q by rewrite dvdp_gcdr. rewrite !dvdp_eq => /eqP <- /eqP <-. have lcn0 k : (lead_coef (gcdp p q)) ^+ k != 0. by rewrite expf_neq0 ?lead_coef_eq0. by apply: eqp_gcd; rewrite ?eqp_scale. Qed. Lemma divp_eq0 p q : (p %/ q == 0) = [|| p == 0, q ==0 | size p < size q]. Proof. apply/eqP/idP=> [d0|]; last first. case/or3P; [by move/eqP->; rewrite div0p| by move/eqP->; rewrite divp0|]. by move/divp_small. case: eqVneq => // _; case: eqVneq => // qn0. move: (divp_eq p q); rewrite d0 mul0r add0r. move/(f_equal (fun x : {poly R} => size x)). by rewrite size_scale ?lc_expn_scalp_neq0 // => ->; rewrite ltn_modp qn0 !orbT. Qed. Lemma dvdp_div_eq0 p q : q %| p -> (p %/ q == 0) = (p == 0). Proof. move=> dvdp_qp; have [->|p_neq0] := eqVneq p 0; first by rewrite div0p eqxx. rewrite divp_eq0 ltnNge dvdp_leq // (negPf p_neq0) orbF /=. by apply: contraTF dvdp_qp=> /eqP ->; rewrite dvd0p. Qed. Lemma Bezout_coprimepPn p q : p != 0 -> q != 0 -> reflect (exists2 uv : {poly R} * {poly R}, (0 < size uv.1 < size q) && (0 < size uv.2 < size p) & uv.1 * p = uv.2 * q) (~~ (coprimep p q)). Proof. move=> pn0 qn0; apply: (iffP idP); last first. case=> [[u v] /= /andP [/andP [ps1 s1] /andP [ps2 s2]] e]. have: ~~(size (q * p) <= size (u * p)). rewrite -ltnNge !size_mul // -?size_poly_gt0 // (polySpred pn0) !addnS. by rewrite ltn_add2r. apply: contra => ?; apply: dvdp_leq; rewrite ?mulf_neq0 // -?size_poly_gt0 //. by rewrite mulrC Gauss_dvdp // dvdp_mull // e dvdp_mull. rewrite coprimep_def neq_ltn ltnS size_poly_leq0 gcdp_eq0. rewrite (negPf pn0) (negPf qn0) /=. case sg: (size (gcdp p q)) => [|n] //; case: n sg=> [|n] // sg _. move: (dvdp_gcdl p q); rewrite dvdp_eq; set c1 := _ ^+ _; move/eqP=> hu1. move: (dvdp_gcdr p q); rewrite dvdp_eq; set c2 := _ ^+ _; move/eqP=> hv1. exists (c1 *: (q %/ gcdp p q), c2 *: (p %/ gcdp p q)); last first. by rewrite -!scalerAl !scalerAr hu1 hv1 mulrCA. rewrite !size_scale ?lc_expn_scalp_neq0 //= !size_poly_gt0 !divp_eq0. rewrite gcdp_eq0 !(negPf pn0) !(negPf qn0) /= -!leqNgt leq_gcdpl //. rewrite leq_gcdpr //= !ltn_divpl -?size_poly_eq0 ?sg //. rewrite !size_mul // -?size_poly_eq0 ?sg // ![(_ + n.+2)%N]addnS /=. by rewrite -!(addn1 (size _)) !leq_add2l. Qed. Lemma dvdp_pexp2r m n k : k > 0 -> (m ^+ k %| n ^+ k) = (m %| n). Proof. move=> k_gt0; apply/idP/idP; last exact: dvdp_exp2r. have [-> // | nn0] := eqVneq n 0; have [-> | mn0] := eqVneq m 0. move/prednK: k_gt0=> {1}<-; rewrite exprS mul0r //= !dvd0p expf_eq0. by case/andP=> _ ->. set d := gcdp m n; have := dvdp_gcdr m n; rewrite -/d dvdp_eq. set c1 := _ ^+ _; set n' := _ %/ _; move/eqP=> def_n. have := dvdp_gcdl m n; rewrite -/d dvdp_eq. set c2 := _ ^+ _; set m' := _ %/ _; move/eqP=> def_m. have dn0 : d != 0 by rewrite gcdp_eq0 negb_and nn0 orbT. have c1n0 : c1 != 0 by rewrite !expf_neq0 // lead_coef_eq0. have c2n0 : c2 != 0 by rewrite !expf_neq0 // lead_coef_eq0. have c2k_n0 : c2 ^+ k != 0 by rewrite !expf_neq0 // lead_coef_eq0. rewrite -(@dvdpZr (c1 ^+ k)) ?expf_neq0 ?lead_coef_eq0 //. rewrite -(@dvdpZl (c2 ^+ k)) // -!exprZn def_m def_n !exprMn. rewrite dvdp_mul2r ?expf_neq0 //. have: coprimep (m' ^+ k) (n' ^+ k). by rewrite coprimep_pexpl // coprimep_pexpr // coprimep_div_gcd ?mn0. move/coprimepP=> hc hd. have /size_poly1P [c cn0 em'] : size m' == 1. case: (eqVneq m' 0) def_m => [-> /eqP | m'_n0 def_m]. by rewrite mul0r scale_poly_eq0 (negPf mn0) (negPf c2n0). have := hc _ (dvdpp _) hd; rewrite -size_poly_eq1. rewrite polySpred; last by rewrite expf_eq0 negb_and m'_n0 orbT. by rewrite size_exp eqSS muln_eq0 orbC eqn0Ngt k_gt0 /= -eqSS -polySpred. rewrite -(@dvdpZl c2) // def_m em' mul_polyC dvdpZl //. by rewrite -(@dvdpZr c1) // def_n dvdp_mull. Qed. Lemma root_gcd p q x : root (gcdp p q) x = root p x && root q x. Proof. rewrite /= !root_factor_theorem; apply/idP/andP=> [dg| [dp dq]]. by split; apply: dvdp_trans dg _; rewrite ?(dvdp_gcdl, dvdp_gcdr). have:= Bezoutp p q => [[[u v]]]; rewrite eqp_sym=> e. by rewrite (eqp_dvdr _ e) dvdp_addl dvdp_mull. Qed. Lemma root_biggcd x (ps : seq {poly R}) : root (\big[gcdp/0]_(p <- ps) p) x = all (fun p => root p x) ps. Proof. elim: ps => [|p ps ihp]; first by rewrite big_nil root0. by rewrite big_cons /= root_gcd ihp. Qed. (* "gdcop Q P" is the Greatest Divisor of P which is coprime to Q *) (* if P null, we pose that gdcop returns 1 if Q null, 0 otherwise*) Fixpoint gdcop_rec q p k := if k is m.+1 then if coprimep p q then p else gdcop_rec q (divp p (gcdp p q)) m else (q == 0)%:R. Definition gdcop q p := gdcop_rec q p (size p). Variant gdcop_spec q p : {poly R} -> Type := GdcopSpec r of (dvdp r p) & ((coprimep r q) || (p == 0)) & (forall d, dvdp d p -> coprimep d q -> dvdp d r) : gdcop_spec q p r. Lemma gdcop0 q : gdcop q 0 = (q == 0)%:R. Proof. by rewrite /gdcop size_poly0. Qed. Lemma gdcop_recP q p k : size p <= k -> gdcop_spec q p (gdcop_rec q p k). Proof. elim: k p => [p | k ihk p] /=. move/size_poly_leq0P->. have [->|q0] := eqVneq; split; rewrite ?coprime1p // ?eqxx ?orbT //. by move=> d _; rewrite coprimep0 dvdp1 size_poly_eq1. move=> hs; case cop : (coprimep _ _); first by split; rewrite ?dvdpp ?cop. have [-> | p0] := eqVneq p 0. by rewrite div0p; apply: ihk; rewrite size_poly0 leq0n. have [-> | q0] := eqVneq q 0. rewrite gcdp0 divpp ?p0 //= => {hs ihk}; case: k=> /=. rewrite eqxx; split; rewrite ?dvd1p ?coprimep0 ?eqpxx //=. by move=> d _; rewrite coprimep0 dvdp1 size_poly_eq1. move=> n; rewrite coprimep0 polyC_eqp1 //; rewrite lc_expn_scalp_neq0. split; first by rewrite (@eqp_dvdl 1) ?dvd1p // polyC_eqp1 lc_expn_scalp_neq0. by rewrite coprimep0 polyC_eqp1 // ?lc_expn_scalp_neq0. by move=> d _; rewrite coprimep0; move/eqp_dvdl->; rewrite dvd1p. move: (dvdp_gcdl p q); rewrite dvdp_eq; move/eqP=> e. have sgp : size (gcdp p q) <= size p. by apply: dvdp_leq; rewrite ?gcdp_eq0 ?p0 ?q0 // dvdp_gcdl. have : p %/ gcdp p q != 0; last move/negPf=>p'n0. apply: dvdpN0 (dvdp_mulIl (p %/ gcdp p q) (gcdp p q)) _. by rewrite -e scale_poly_eq0 negb_or lc_expn_scalp_neq0. have gn0 : gcdp p q != 0. apply: dvdpN0 (dvdp_mulIr (p %/ gcdp p q) (gcdp p q)) _. by rewrite -e scale_poly_eq0 negb_or lc_expn_scalp_neq0. have sp' : size (p %/ (gcdp p q)) <= k. rewrite size_divp ?sgp // leq_subLR (leq_trans hs) // -add1n leq_add2r -subn1. by rewrite ltn_subRL add1n ltn_neqAle eq_sym [_ == _]cop size_poly_gt0 gn0. case (ihk _ sp')=> r' dr'p'; first rewrite p'n0 orbF=> cr'q maxr'. constructor=> //=; rewrite ?(negPf p0) ?orbF //. exact/(dvdp_trans dr'p')/divp_dvd/dvdp_gcdl. move=> d dp cdq; apply: maxr'; last by rewrite cdq. case dpq: (d %| gcdp p q). move: (dpq); rewrite dvdp_gcd dp /= => dq; apply: dvdUp. apply: contraLR cdq => nd1; apply/coprimepPn; last first. by exists d; rewrite dvdp_gcd dvdpp dq nd1. by apply: contraNneq p0 => d0; move: dp; rewrite d0 dvd0p. apply: contraLR dp => ndp'. rewrite (@eqp_dvdr ((lead_coef (gcdp p q) ^+ scalp p (gcdp p q))*:p)). by rewrite e; rewrite Gauss_dvdpl //; apply: (coprimep_dvdl (dvdp_gcdr _ _)). by rewrite eqp_sym eqp_scale // lc_expn_scalp_neq0. Qed. Lemma gdcopP q p : gdcop_spec q p (gdcop q p). Proof. by rewrite /gdcop; apply: gdcop_recP. Qed. Lemma coprimep_gdco p q : (q != 0)%B -> coprimep (gdcop p q) p. Proof. by move=> q_neq0; case: gdcopP=> d; rewrite (negPf q_neq0) orbF. Qed. Lemma size2_dvdp_gdco p q d : p != 0 -> size d = 2 -> (d %| (gdcop q p)) = (d %| p) && ~~(d %| q). Proof. have [-> | dn0] := eqVneq d 0; first by rewrite size_poly0. move=> p0 sd; apply/idP/idP. case: gdcopP=> r rp crq maxr dr; move/negPf: (p0)=> p0f. rewrite (dvdp_trans dr) //=. apply: contraL crq => dq; rewrite p0f orbF; apply/coprimepPn. by apply: contraNneq p0 => r0; move: rp; rewrite r0 dvd0p. by exists d; rewrite dvdp_gcd dr dq -size_poly_eq1 sd. case/andP=> dp dq; case: gdcopP=> r rp crq maxr; apply: maxr=> //. apply/coprimepP=> x xd xq. move: (dvdp_leq dn0 xd); rewrite leq_eqVlt sd; case/orP; last first. rewrite ltnS leq_eqVlt ltnS size_poly_leq0 orbC. case/predU1P => [x0|]; last by rewrite -size_poly_eq1. by move: xd; rewrite x0 dvd0p (negPf dn0). by rewrite -sd dvdp_size_eqp //; move/(eqp_dvdl q); rewrite xq (negPf dq). Qed. Lemma dvdp_gdco p q : (gdcop p q) %| q. Proof. by case: gdcopP. Qed. Lemma root_gdco p q x : p != 0 -> root (gdcop q p) x = root p x && ~~(root q x). Proof. move=> p0 /=; rewrite !root_factor_theorem. apply: size2_dvdp_gdco; rewrite ?p0 //. by rewrite size_polyDl size_polyX // size_polyN size_polyC ltnS; case: (x != 0). Qed. Lemma dvdp_comp_poly r p q : (p %| q) -> (p \Po r) %| (q \Po r). Proof. have [-> | pn0] := eqVneq p 0. by rewrite comp_poly0 !dvd0p; move/eqP->; rewrite comp_poly0. rewrite dvdp_eq; set c := _ ^+ _; set s := _ %/ _; move/eqP=> Hq. apply: (@eq_dvdp c (s \Po r)); first by rewrite expf_neq0 // lead_coef_eq0. by rewrite -comp_polyZ Hq comp_polyM. Qed. Lemma gcdp_comp_poly r p q : gcdp p q \Po r %= gcdp (p \Po r) (q \Po r). Proof. apply/andP; split. by rewrite dvdp_gcd !dvdp_comp_poly ?dvdp_gcdl ?dvdp_gcdr. case: (Bezoutp p q) => [[u v]] /andP []. move/(dvdp_comp_poly r) => Huv _. rewrite (dvdp_trans _ Huv) // comp_polyD !comp_polyM. by rewrite dvdp_add // dvdp_mull //; [ exact: dvdp_gcdl | exact: dvdp_gcdr]. Qed. Lemma coprimep_comp_poly r p q : coprimep p q -> coprimep (p \Po r) (q \Po r). Proof. rewrite -!gcdp_eqp1 -!size_poly_eq1 -!dvdp1; move/(dvdp_comp_poly r). rewrite comp_polyC => Hgcd. by apply: dvdp_trans Hgcd; case/andP: (gcdp_comp_poly r p q). Qed. Lemma coprimep_addl_mul p q r : coprimep r (p * r + q) = coprimep r q. Proof. by rewrite !coprimep_def (eqp_size (gcdp_addl_mul _ _ _)). Qed. Definition irreducible_poly p := (size p > 1) * (forall q, size q != 1 -> q %| p -> q %= p) : Prop. Lemma irredp_neq0 p : irreducible_poly p -> p != 0. Proof. by rewrite -size_poly_gt0 => [[/ltnW]]. Qed. Definition apply_irredp p (irr_p : irreducible_poly p) := irr_p.2. Coercion apply_irredp : irreducible_poly >-> Funclass. Lemma modp_XsubC p c : p %% ('X - c%:P) = p.[c]%:P. Proof. have/factor_theorem [q /(canRL (subrK _)) Dp]: root (p - p.[c]%:P) c. by rewrite /root !hornerE subrr. rewrite modpE /= lead_coefXsubC unitr1 expr1n invr1 scale1r [in LHS]Dp. rewrite RingMonic.rmodp_addl_mul_small // ?monicXsubC// size_XsubC size_polyC. by case: (p.[c] == 0). Qed. Lemma coprimep_XsubC p c : coprimep p ('X - c%:P) = ~~ root p c. Proof. rewrite -coprimep_modl modp_XsubC /root -alg_polyC. have [-> | /coprimepZl->] := eqVneq; last exact: coprime1p. by rewrite scale0r /coprimep gcd0p size_XsubC. Qed. Lemma coprimep_XsubC2 (a b : R) : b - a != 0 -> coprimep ('X - a%:P) ('X - b%:P). Proof. by move=> bBa_neq0; rewrite coprimep_XsubC rootE hornerXsubC. Qed. Lemma coprimepX p : coprimep p 'X = ~~ root p 0. Proof. by rewrite -['X]subr0 coprimep_XsubC. Qed. Lemma eqp_monic : {in monic &, forall p q, (p %= q) = (p == q)}. Proof. move=> p q monic_p monic_q; apply/idP/eqP=> [|-> //]. case/eqpP=> [[a b] /= /andP[a_neq0 _] eq_pq]. apply: (@mulfI _ a%:P); first by rewrite polyC_eq0. rewrite !mul_polyC eq_pq; congr (_ *: q); apply: (mulIf (oner_neq0 _)). by rewrite -[in LHS](monicP monic_q) -(monicP monic_p) -!lead_coefZ eq_pq. Qed. Lemma dvdp_mul_XsubC p q c : (p %| ('X - c%:P) * q) = ((if root p c then p %/ ('X - c%:P) else p) %| q). Proof. case: ifPn => [| not_pc0]; last by rewrite Gauss_dvdpr ?coprimep_XsubC. rewrite root_factor_theorem -eqp_div_XsubC mulrC => /eqP{1}->. by rewrite dvdp_mul2l ?polyXsubC_eq0. Qed. Lemma dvdp_prod_XsubC (I : Type) (r : seq I) (F : I -> R) p : p %| \prod_(i <- r) ('X - (F i)%:P) -> {m | p %= \prod_(i <- mask m r) ('X - (F i)%:P)}. Proof. elim: r => [|i r IHr] in p *. by rewrite big_nil dvdp1; exists nil; rewrite // big_nil -size_poly_eq1. rewrite big_cons dvdp_mul_XsubC root_factor_theorem -eqp_div_XsubC. case: eqP => [{2}-> | _] /IHr[m Dp]; last by exists (false :: m). by exists (true :: m); rewrite /= mulrC big_cons eqp_mul2l ?polyXsubC_eq0. Qed. Lemma irredp_XsubC (x : R) : irreducible_poly ('X - x%:P). Proof. split=> [|d size_d d_dv_Xx]; first by rewrite size_XsubC. have: ~ d %= 1 by apply/negP; rewrite -size_poly_eq1. have [|m /=] := @dvdp_prod_XsubC _ [:: x] id d; first by rewrite big_seq1. by case: m => [|[] [|_ _] /=]; rewrite (big_nil, big_seq1). Qed. Lemma irredp_XaddC (x : R) : irreducible_poly ('X + x%:P). Proof. by rewrite -[x]opprK rmorphN; apply: irredp_XsubC. Qed. Lemma irredp_XsubCP d p : irreducible_poly p -> d %| p -> {d %= 1} + {d %= p}. Proof. move=> irred_p dvd_dp; have [] := boolP (_ %= 1); first by left. by rewrite -size_poly_eq1=> /irred_p /(_ dvd_dp); right. Qed. Lemma dvdp_exp_XsubCP (p : {poly R}) (c : R) (n : nat) : reflect (exists2 k, (k <= n)%N & p %= ('X - c%:P) ^+ k) (p %| ('X - c%:P) ^+ n). Proof. apply: (iffP idP) => [|[k lkn /eqp_dvdl->]]; last by rewrite dvdp_exp2l. move=> /Pdiv.WeakIdomain.dvdpP[[/= a q] a_neq0]. have [m [r]] := multiplicity_XsubC p c; have [->|pN0]/= := eqVneq p 0. rewrite mulr0 => _ _ /eqP; rewrite scale_poly_eq0 (negPf a_neq0)/=. by rewrite expf_eq0/= andbC polyXsubC_eq0. move=> rNc ->; rewrite mulrA => eq_qrm; exists m. have: ('X - c%:P) ^+ m %| a *: ('X - c%:P) ^+ n by rewrite eq_qrm dvdp_mull. by rewrite (eqp_dvdr _ (eqp_scale _ _))// dvdp_Pexp2l// size_XsubC. suff /eqP : size r = 1%N. by rewrite size_poly_eq1 => /eqp_mulr/eqp_trans->//; rewrite mul1r eqpxx. have : r %| a *: ('X - c%:P) ^+ n by rewrite eq_qrm mulrAC dvdp_mull. rewrite (eqp_dvdr _ (eqp_scale _ _))//. move: rNc; rewrite -coprimep_XsubC => /(coprimep_expr n) /coprimepP. by move=> /(_ _ (dvdpp _)); rewrite -size_poly_eq1 => /(_ _)/eqP. Qed. End IDomainPseudoDivision. Arguments gcdp : simpl never. #[global] Hint Resolve eqpxx divp0 divp1 mod0p modp0 modp1 : core. #[global] Hint Resolve dvdp_mull dvdp_mulr dvdpp dvdp0 : core. Arguments dvdp_exp_XsubCP {R p c n}. End CommonIdomain. Module Idomain. Include IdomainDefs. Export IdomainDefs. Include WeakIdomain. Include CommonIdomain. End Idomain. Module IdomainMonic. Import Ring ComRing UnitRing IdomainDefs Idomain. Section IdomainMonic. Variable R : idomainType. Implicit Type p d r : {poly R}. Section MonicDivisor. Variable q : {poly R}. Hypothesis monq : q \is monic. Lemma divpE p : p %/ q = rdivp p q. Proof. by rewrite divpE (eqP monq) unitr1 expr1n invr1 scale1r. Qed. Lemma modpE p : p %% q = rmodp p q. Proof. by rewrite modpE (eqP monq) unitr1 expr1n invr1 scale1r. Qed. Lemma scalpE p : scalp p q = 0. Proof. by rewrite scalpE (eqP monq) unitr1. Qed. Lemma divp_eq p : p = (p %/ q) * q + (p %% q). Proof. by rewrite -divp_eq (eqP monq) expr1n scale1r. Qed. Lemma divpp p : q %/ q = 1. Proof. by rewrite divpp ?monic_neq0 // (eqP monq) expr1n. Qed. Lemma dvdp_eq p : (q %| p) = (p == (p %/ q) * q). Proof. by rewrite dvdp_eq (eqP monq) expr1n scale1r. Qed. Lemma dvdpP p : reflect (exists qq, p = qq * q) (q %| p). Proof. apply: (iffP idP); first by rewrite dvdp_eq; move/eqP=> e; exists (p %/ q). by case=> qq ->; rewrite dvdp_mull // dvdpp. Qed. Lemma mulpK p : p * q %/ q = p. Proof. by rewrite mulpK ?monic_neq0 // (eqP monq) expr1n scale1r. Qed. Lemma mulKp p : q * p %/ q = p. Proof. by rewrite mulrC mulpK. Qed. End MonicDivisor. Lemma drop_poly_divp n p : drop_poly n p = p %/ 'X^n. Proof. by rewrite RingMonic.drop_poly_rdivp divpE // monicXn. Qed. Lemma take_poly_modp n p : take_poly n p = p %% 'X^n. Proof. by rewrite RingMonic.take_poly_rmodp modpE // monicXn. Qed. End IdomainMonic. End IdomainMonic. Module IdomainUnit. Import Ring ComRing UnitRing IdomainDefs Idomain. Section UnitDivisor. Variable R : idomainType. Variable d : {poly R}. Hypothesis ulcd : lead_coef d \in GRing.unit. Implicit Type p q r : {poly R}. Lemma divp_eq p : p = (p %/ d) * d + (p %% d). Proof. by have := divp_eq p d; rewrite scalpE ulcd expr0 scale1r. Qed. Lemma edivpP p q r : p = q * d + r -> size r < size d -> q = (p %/ d) /\ r = p %% d. Proof. move=> ep srd; have := divp_eq p; rewrite [LHS]ep. move/eqP; rewrite -subr_eq -addrA addrC eq_sym -subr_eq -mulrBl; move/eqP. have lcdn0 : lead_coef d != 0 by apply: contraTneq ulcd => ->; rewrite unitr0. have [-> /esym /eqP|abs] := eqVneq (p %/ d) q. by rewrite subrr mul0r subr_eq0 => /eqP<-. have hleq : size d <= size ((p %/ d - q) * d). rewrite size_proper_mul; last first. by rewrite mulf_eq0 (negPf lcdn0) orbF lead_coef_eq0 subr_eq0. by move: abs; rewrite -subr_eq0; move/polySpred->; rewrite addSn /= leq_addl. have hlt : size (r - p %% d) < size d. apply: leq_ltn_trans (size_polyD _ _) _. by rewrite gtn_max srd size_polyN ltn_modp -lead_coef_eq0. by move=> e; have:= leq_trans hlt hleq; rewrite e ltnn. Qed. Lemma divpP p q r : p = q * d + r -> size r < size d -> q = (p %/ d). Proof. by move/edivpP=> h; case/h. Qed. Lemma modpP p q r : p = q * d + r -> size r < size d -> r = (p %% d). Proof. by move/edivpP=> h; case/h. Qed. Lemma ulc_eqpP p q : lead_coef q \is a GRing.unit -> reflect (exists2 c : R, c != 0 & p = c *: q) (p %= q). Proof. have [->|] := eqVneq (lead_coef q) 0; first by rewrite unitr0. rewrite lead_coef_eq0 => nz_q ulcq; apply: (iffP idP). have [->|nz_p] := eqVneq p 0; first by rewrite eqp_sym eqp0 (negPf nz_q). move/eqp_eq=> eq; exists (lead_coef p / lead_coef q). by rewrite mulf_neq0 // ?invr_eq0 lead_coef_eq0. by apply/(scaler_injl ulcq); rewrite scalerA mulrCA divrr // mulr1. by case=> c nz_c ->; apply/eqpP; exists (1, c); rewrite ?scale1r ?oner_eq0. Qed. Lemma dvdp_eq p : (d %| p) = (p == p %/ d * d). Proof. apply/eqP/eqP=> [modp0 | ->]; last exact: modp_mull. by rewrite [p in LHS]divp_eq modp0 addr0. Qed. Lemma ucl_eqp_eq p q : lead_coef q \is a GRing.unit -> p %= q -> p = (lead_coef p / lead_coef q) *: q. Proof. move=> ulcq /eqp_eq; move/(congr1 ( *:%R (lead_coef q)^-1 )). by rewrite !scalerA mulrC divrr // scale1r mulrC. Qed. Lemma modpZl c p : (c *: p) %% d = c *: (p %% d). Proof. have [-> | cn0] := eqVneq c 0; first by rewrite !scale0r mod0p. have e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d). by rewrite -scalerAl -scalerDr -divp_eq. suff s: size (c *: (p %% d)) < size d by case: (edivpP e s) => _ ->. rewrite -mul_polyC; apply: leq_ltn_trans (size_polyMleq _ _) _. rewrite size_polyC cn0 addSn add0n /= ltn_modp -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma divpZl c p : (c *: p) %/ d = c *: (p %/ d). Proof. have [-> | cn0] := eqVneq c 0; first by rewrite !scale0r div0p. have e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d). by rewrite -scalerAl -scalerDr -divp_eq. suff s: size (c *: (p %% d)) < size d by case: (edivpP e s) => ->. rewrite -mul_polyC; apply: leq_ltn_trans (size_polyMleq _ _) _. rewrite size_polyC cn0 addSn add0n /= ltn_modp -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma eqp_modpl p q : p %= q -> (p %% d) %= (q %% d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 //= -!modpZl e. Qed. Lemma eqp_divl p q : p %= q -> (p %/ d) %= (q %/ d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!divpZl e. Qed. Lemma modpN p : (- p) %% d = - (p %% d). Proof. by rewrite -mulN1r -[RHS]mulN1r -polyCN !mul_polyC modpZl. Qed. Lemma divpN p : (- p) %/ d = - (p %/ d). Proof. by rewrite -mulN1r -[RHS]mulN1r -polyCN !mul_polyC divpZl. Qed. Lemma modpD p q : (p + q) %% d = p %% d + q %% d. Proof. have/edivpP [] // : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d). by rewrite mulrDl addrACA -!divp_eq. apply: leq_ltn_trans (size_polyD _ _) _. rewrite gtn_max !ltn_modp andbb -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma divpD p q : (p + q) %/ d = p %/ d + q %/ d. Proof. have/edivpP [] // : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d). by rewrite mulrDl addrACA -!divp_eq. apply: leq_ltn_trans (size_polyD _ _) _. rewrite gtn_max !ltn_modp andbb -lead_coef_eq0. by apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma mulpK q : (q * d) %/ d = q. Proof. case/esym/edivpP: (addr0 (q * d)); rewrite // size_poly0 size_poly_gt0. by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0. Qed. Lemma mulKp q : (d * q) %/ d = q. Proof. by rewrite mulrC; apply: mulpK. Qed. Lemma divp_addl_mul_small q r : size r < size d -> (q * d + r) %/ d = q. Proof. by move=> srd; rewrite divpD (divp_small srd) addr0 mulpK. Qed. Lemma modp_addl_mul_small q r : size r < size d -> (q * d + r) %% d = r. Proof. by move=> srd; rewrite modpD modp_mull add0r modp_small. Qed. Lemma divp_addl_mul q r : (q * d + r) %/ d = q + r %/ d. Proof. by rewrite divpD mulpK. Qed. Lemma divpp : d %/ d = 1. Proof. by rewrite -[d in d %/ _]mul1r mulpK. Qed. Lemma leq_divMp m : size (m %/ d * d) <= size m. Proof. case: (eqVneq d 0) ulcd => [->|dn0 _]; first by rewrite lead_coef0 unitr0. have [->|q0] := eqVneq (m %/ d) 0; first by rewrite mul0r size_poly0 leq0n. rewrite {2}(divp_eq m) size_polyDl // size_mul // (polySpred q0) addSn /=. by rewrite ltn_addl // ltn_modp. Qed. Lemma dvdpP p : reflect (exists q, p = q * d) (d %| p). Proof. apply: (iffP idP) => [| [k ->]]; last by apply/eqP; rewrite modp_mull. by rewrite dvdp_eq; move/eqP->; exists (p %/ d). Qed. Lemma divpK p : d %| p -> p %/ d * d = p. Proof. by rewrite dvdp_eq; move/eqP. Qed. Lemma divpKC p : d %| p -> d * (p %/ d) = p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdp_eq_div p q : d %| p -> (q == p %/ d) = (q * d == p). Proof. move/divpK=> {2}<-; apply/eqP/eqP; first by move->. apply/mulIf; rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->. by rewrite unitr0. Qed. Lemma dvdp_eq_mul p q : d %| p -> (p == q * d) = (p %/ d == q). Proof. by move=> dv_d_p; rewrite eq_sym -dvdp_eq_div // eq_sym. Qed. Lemma divp_mulA p q : d %| q -> p * (q %/ d) = p * q %/ d. Proof. move=> hdm; apply/eqP; rewrite eq_sym -dvdp_eq_mul. by rewrite -mulrA divpK. by move/divpK: hdm<-; rewrite mulrA dvdp_mull // dvdpp. Qed. Lemma divp_mulAC m n : d %| m -> m %/ d * n = m * n %/ d. Proof. by move=> hdm; rewrite mulrC (mulrC m); apply: divp_mulA. Qed. Lemma divp_mulCA p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d). Proof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed. Lemma modp_mul p q : (p * (q %% d)) %% d = (p * q) %% d. Proof. by rewrite [q in RHS]divp_eq mulrDr modpD mulrA modp_mull add0r. Qed. End UnitDivisor. #[deprecated(since="mathcomp 2.4.0", note="Renamed to leq_divMp.")] Notation leq_trunc_divp := leq_divMp. Section MoreUnitDivisor. Variable R : idomainType. Variable d : {poly R}. Hypothesis ulcd : lead_coef d \in GRing.unit. Implicit Types p q : {poly R}. Lemma expp_sub m n : n <= m -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n. Proof. by move/subnK=> {2}<-; rewrite exprD mulpK // lead_coef_exp unitrX. Qed. Lemma divp_pmul2l p q : lead_coef q \in GRing.unit -> d * p %/ (d * q) = p %/ q. Proof. move=> uq; rewrite {1}(divp_eq uq p) mulrDr mulrCA divp_addl_mul //; last first. by rewrite lead_coefM unitrM_comm ?ulcd //; red; rewrite mulrC. have dn0 : d != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0. have qn0 : q != 0. by rewrite -lead_coef_eq0; apply: contraTneq uq => ->; rewrite unitr0. have dqn0 : d * q != 0 by rewrite mulf_eq0 negb_or dn0. suff : size (d * (p %% q)) < size (d * q). by rewrite ltnNge -divpN0 // negbK => /eqP ->; rewrite addr0. have [-> | rn0] := eqVneq (p %% q) 0. by rewrite mulr0 size_poly0 size_poly_gt0. by rewrite !size_mul // (polySpred dn0) !addSn /= ltn_add2l ltn_modp. Qed. Lemma divp_pmul2r p q : lead_coef p \in GRing.unit -> q * d %/ (p * d) = q %/ p. Proof. by move=> uq; rewrite -!(mulrC d) divp_pmul2l. Qed. Lemma divp_divl r p q : lead_coef r \in GRing.unit -> lead_coef p \in GRing.unit -> q %/ p %/ r = q %/ (p * r). Proof. move=> ulcr ulcp. have e : q = (q %/ p %/ r) * (p * r) + ((q %/ p) %% r * p + q %% p). by rewrite addrA (mulrC p) mulrA -mulrDl; rewrite -divp_eq //; apply: divp_eq. have pn0 : p != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcp => ->; rewrite unitr0. have rn0 : r != 0. by rewrite -lead_coef_eq0; apply: contraTneq ulcr => ->; rewrite unitr0. have s : size ((q %/ p) %% r * p + q %% p) < size (p * r). have [-> | qn0] := eqVneq ((q %/ p) %% r) 0. rewrite mul0r add0r size_mul // (polySpred rn0) addnS /=. by apply: leq_trans (leq_addr _ _); rewrite ltn_modp. rewrite size_polyDl mulrC. by rewrite !size_mul // (polySpred pn0) !addSn /= ltn_add2l ltn_modp. rewrite size_mul // (polySpred qn0) addnS /=. by apply: leq_trans (leq_addr _ _); rewrite ltn_modp. case: (edivpP _ e s) => //; rewrite lead_coefM unitrM_comm ?ulcp //. by red; rewrite mulrC. Qed. Lemma divpAC p q : lead_coef p \in GRing.unit -> q %/ d %/ p = q %/ p %/ d. Proof. by move=> ulcp; rewrite !divp_divl // mulrC. Qed. Lemma modpZr c p : c \in GRing.unit -> p %% (c *: d) = (p %% d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !modp0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVr // scale1r -(divp_eq ulcd). suff s : size (p %% d) < size (c *: d). by rewrite (modpP _ e s) // -mul_polyC lead_coefM lead_coefC unitrM cn0. by rewrite size_scale ?ltn_modp //; apply: contraTneq cn0 => ->; rewrite unitr0. Qed. Lemma divpZr c p : c \in GRing.unit -> p %/ (c *: d) = c^-1 *: (p %/ d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !divp0 scaler0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVr // scale1r -(divp_eq ulcd). suff s : size (p %% d) < size (c *: d). by rewrite (divpP _ e s) // -mul_polyC lead_coefM lead_coefC unitrM cn0. by rewrite size_scale ?ltn_modp //; apply: contraTneq cn0 => ->; rewrite unitr0. Qed. End MoreUnitDivisor. End IdomainUnit. Module Field. Import Ring ComRing UnitRing. Include IdomainDefs. Export IdomainDefs. Include CommonIdomain. Section FieldDivision. Variable F : fieldType. Implicit Type p q r d : {poly F}. Lemma divp_eq p q : p = (p %/ q) * q + (p %% q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite modp0 mulr0 add0r. by apply: IdomainUnit.divp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_modpP p q d r : p = q * d + r -> size r < size d -> q = (p %/ d) /\ r = p %% d. Proof. move=> he hs; apply: IdomainUnit.edivpP => //; rewrite unitfE lead_coef_eq0. by rewrite -size_poly_gt0; apply: leq_trans hs. Qed. Lemma divpP p q d r : p = q * d + r -> size r < size d -> q = (p %/ d). Proof. by move/divp_modpP=> h; case/h. Qed. Lemma modpP p q d r : p = q * d + r -> size r < size d -> r = (p %% d). Proof. by move/divp_modpP=> h; case/h. Qed. Lemma eqpfP p q : p %= q -> p = (lead_coef p / lead_coef q) *: q. Proof. have [->|nz_q] := eqVneq q 0; first by rewrite eqp0 scaler0 => /eqP ->. by apply/IdomainUnit.ucl_eqp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma dvdp_eq q p : (q %| p) = (p == p %/ q * q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite dvd0p mulr0 eq_sym. by apply: IdomainUnit.dvdp_eq; rewrite unitfE lead_coef_eq0. Qed. Lemma eqpf_eq p q : reflect (exists2 c, c != 0 & p = c *: q) (p %= q). Proof. apply: (iffP idP); last first. case=> c nz_c ->; apply/eqpP. by exists (1, c); rewrite ?scale1r ?oner_eq0. have [->|nz_q] := eqVneq q 0. by rewrite eqp0=> /eqP ->; exists 1; rewrite ?scale1r ?oner_eq0. case/IdomainUnit.ulc_eqpP; first by rewrite unitfE lead_coef_eq0. by move=> c nz_c ->; exists c. Qed. Lemma modpZl c p q : (c *: p) %% q = c *: (p %% q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite !modp0. by apply: IdomainUnit.modpZl; rewrite unitfE lead_coef_eq0. Qed. Lemma mulpK p q : q != 0 -> p * q %/ q = p. Proof. by move=> qn0; rewrite IdomainUnit.mulpK // unitfE lead_coef_eq0. Qed. Lemma mulKp p q : q != 0 -> q * p %/ q = p. Proof. by rewrite mulrC; apply: mulpK. Qed. Lemma divpZl c p q : (c *: p) %/ q = c *: (p %/ q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite !divp0 scaler0. by apply: IdomainUnit.divpZl; rewrite unitfE lead_coef_eq0. Qed. Lemma modpZr c p d : c != 0 -> p %% (c *: d) = (p %% d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !modp0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVf // scale1r -divp_eq. suff s : size (p %% d) < size (c *: d) by rewrite (modpP e s). by rewrite size_scale ?ltn_modp. Qed. Lemma divpZr c p d : c != 0 -> p %/ (c *: d) = c^-1 *: (p %/ d). Proof. case: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !divp0 scaler0. have e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d). by rewrite scalerCA scalerA mulVf // scale1r -divp_eq. suff s : size (p %% d) < size (c *: d) by rewrite (divpP e s). by rewrite size_scale ?ltn_modp. Qed. Lemma eqp_modpl d p q : p %= q -> (p %% d) %= (q %% d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!modpZl e. Qed. Lemma eqp_divl d p q : p %= q -> (p %/ d) %= (q %/ d). Proof. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e]. by apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!divpZl e. Qed. Lemma eqp_modpr d p q : p %= q -> (d %% p) %= (d %% q). Proof. case/eqpP=> [[c1 c2]] /andP [c1n0 c2n0 e]. have -> : p = (c1^-1 * c2) *: q by rewrite -scalerA -e scalerA mulVf // scale1r. by rewrite modpZr ?eqpxx // mulf_eq0 negb_or invr_eq0 c1n0. Qed. Lemma eqp_mod p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> p1 %% q1 %= p2 %% q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_modpl _ e1) (eqp_modpr _ e2). Qed. Lemma eqp_divr (d m n : {poly F}) : m %= n -> (d %/ m) %= (d %/ n). Proof. case/eqpP=> [[c1 c2]] /andP [c1n0 c2n0 e]. have -> : m = (c1^-1 * c2) *: n by rewrite -scalerA -e scalerA mulVf // scale1r. by rewrite divpZr ?eqp_scale // ?invr_eq0 mulf_eq0 negb_or invr_eq0 c1n0. Qed. Lemma eqp_div p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> p1 %/ q1 %= p2 %/ q2. Proof. move=> e1 e2; exact: eqp_trans (eqp_divl _ e1) (eqp_divr _ e2). Qed. Lemma eqp_gdcor p q r : q %= r -> gdcop p q %= gdcop p r. Proof. move=> eqr; rewrite /gdcop (eqp_size eqr). move: (size r)=> n; elim: n p q r eqr => [|n ihn] p q r; first by rewrite eqpxx. move=> eqr /=; rewrite (eqp_coprimepl p eqr); case: ifP => _ //. exact/ihn/eqp_div/eqp_gcdl. Qed. Lemma eqp_gdcol p q r : q %= r -> gdcop q p %= gdcop r p. Proof. move=> eqr; rewrite /gdcop; move: (size p)=> n. elim: n p q r eqr {1 3}p (eqpxx p) => [|n ihn] p q r eqr s esp /=. case: (eqVneq q 0) eqr => [-> | nq0 eqr] /=. by rewrite eqp_sym eqp0 => ->; rewrite eqpxx. by case: (eqVneq r 0) eqr nq0 => [->|]; rewrite ?eqpxx // eqp0 => ->. rewrite (eqp_coprimepr _ eqr) (eqp_coprimepl _ esp); case: ifP=> _ //. exact/ihn/eqp_div/eqp_gcd. Qed. Lemma eqp_rgdco_gdco q p : rgdcop q p %= gdcop q p. Proof. rewrite /rgdcop /gdcop; move: (size p)=> n. elim: n p q {1 3}p {1 3}q (eqpxx p) (eqpxx q) => [|n ihn] p q s t /= sp tq. case: (eqVneq t 0) tq => [-> | nt0 etq]. by rewrite eqp_sym eqp0 => ->; rewrite eqpxx. by case: (eqVneq q 0) etq nt0 => [->|]; rewrite ?eqpxx // eqp0 => ->. rewrite rcoprimep_coprimep (eqp_coprimepl t sp) (eqp_coprimepr p tq). case: ifP=> // _; apply: ihn => //; apply: eqp_trans (eqp_rdiv_div _ _) _. by apply: eqp_div => //; apply: eqp_trans (eqp_rgcd_gcd _ _) _; apply: eqp_gcd. Qed. Lemma modpD d p q : (p + q) %% d = p %% d + q %% d. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite !modp0. by apply: IdomainUnit.modpD; rewrite unitfE lead_coef_eq0. Qed. Lemma modpN p q : (- p) %% q = - (p %% q). Proof. by apply/eqP; rewrite -addr_eq0 -modpD addNr mod0p. Qed. Lemma modNp p q : (- p) %% q = - (p %% q). Proof. exact: modpN. Qed. Lemma divpD d p q : (p + q) %/ d = p %/ d + q %/ d. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite !divp0 addr0. by apply: IdomainUnit.divpD; rewrite unitfE lead_coef_eq0. Qed. Lemma divpN p q : (- p) %/ q = - (p %/ q). Proof. by apply/eqP; rewrite -addr_eq0 -divpD addNr div0p. Qed. Lemma divp_addl_mul_small d q r : size r < size d -> (q * d + r) %/ d = q. Proof. move=> srd; rewrite divpD (divp_small srd) addr0 mulpK // -size_poly_gt0. exact: leq_trans srd. Qed. Lemma modp_addl_mul_small d q r : size r < size d -> (q * d + r) %% d = r. Proof. by move=> srd; rewrite modpD modp_mull add0r modp_small. Qed. Lemma divp_addl_mul d q r : d != 0 -> (q * d + r) %/ d = q + r %/ d. Proof. by move=> dn0; rewrite divpD mulpK. Qed. Lemma divpp d : d != 0 -> d %/ d = 1. Proof. by move=> dn0; apply: IdomainUnit.divpp; rewrite unitfE lead_coef_eq0. Qed. Lemma leq_divMp d m : size (m %/ d * d) <= size m. Proof. have [-> | dn0] := eqVneq d 0; first by rewrite mulr0 size_poly0. by apply: IdomainUnit.leq_divMp; rewrite unitfE lead_coef_eq0. Qed. Lemma divpK d p : d %| p -> p %/ d * d = p. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite mulr0. by apply: IdomainUnit.divpK; rewrite unitfE lead_coef_eq0. Qed. Lemma divpKC d p : d %| p -> d * (p %/ d) = p. Proof. by move=> ?; rewrite mulrC divpK. Qed. Lemma dvdp_eq_div d p q : d != 0 -> d %| p -> (q == p %/ d) = (q * d == p). Proof. by move=> dn0; apply: IdomainUnit.dvdp_eq_div; rewrite unitfE lead_coef_eq0. Qed. Lemma dvdp_eq_mul d p q : d != 0 -> d %| p -> (p == q * d) = (p %/ d == q). Proof. by move=> dn0 dv_d_p; rewrite eq_sym -dvdp_eq_div // eq_sym. Qed. Lemma divp_mulA d p q : d %| q -> p * (q %/ d) = p * q %/ d. Proof. case: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite !divp0 mulr0. by apply: IdomainUnit.divp_mulA; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d. Proof. by move=> hdm; rewrite mulrC (mulrC m); apply: divp_mulA. Qed. Lemma divp_mulCA d p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d). Proof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed. Lemma expp_sub d m n : d != 0 -> m >= n -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n. Proof. by move=> dn0 /subnK=> {2}<-; rewrite exprD mulpK // expf_neq0. Qed. Lemma divp_pmul2l d q p : d != 0 -> q != 0 -> d * p %/ (d * q) = p %/ q. Proof. by move=> dn0 qn0; apply: IdomainUnit.divp_pmul2l; rewrite unitfE lead_coef_eq0. Qed. Lemma divp_pmul2r d p q : d != 0 -> p != 0 -> q * d %/ (p * d) = q %/ p. Proof. by move=> dn0 qn0; rewrite -!(mulrC d) divp_pmul2l. Qed. Lemma divp_divl r p q : q %/ p %/ r = q %/ (p * r). Proof. have [-> | rn0] := eqVneq r 0; first by rewrite mulr0 !divp0. have [-> | pn0] := eqVneq p 0; first by rewrite mul0r !divp0 div0p. by apply: IdomainUnit.divp_divl; rewrite unitfE lead_coef_eq0. Qed. Lemma divpAC d p q : q %/ d %/ p = q %/ p %/ d. Proof. by rewrite !divp_divl // mulrC. Qed. Lemma edivp_def p q : edivp p q = (0, p %/ q, p %% q). Proof. rewrite Idomain.edivp_def; congr (_, _, _); rewrite /scalp 2!unlock /=. have [-> | qn0] := eqVneq; first by rewrite lead_coef0 unitr0. by rewrite unitfE lead_coef_eq0 qn0 /=; case: (redivp_rec _ _ _ _) => [[]]. Qed. Lemma divpE p q : p %/ q = (lead_coef q)^-(rscalp p q) *: (rdivp p q). Proof. have [-> | qn0] := eqVneq q 0; first by rewrite rdivp0 divp0 scaler0. by rewrite Idomain.divpE unitfE lead_coef_eq0 qn0. Qed. Lemma modpE p q : p %% q = (lead_coef q)^-(rscalp p q) *: (rmodp p q). Proof. have [-> | qn0] := eqVneq q 0. by rewrite rmodp0 modp0 /rscalp unlock eqxx lead_coef0 expr0 invr1 scale1r. by rewrite Idomain.modpE unitfE lead_coef_eq0 qn0. Qed. Lemma scalpE p q : scalp p q = 0. Proof. have [-> | qn0] := eqVneq q 0; first by rewrite scalp0. by rewrite Idomain.scalpE unitfE lead_coef_eq0 qn0. Qed. (* Just to have it without importing the weak theory *) Lemma dvdpE p q : p %| q = rdvdp p q. Proof. exact: Idomain.dvdpE. Qed. Variant edivp_spec m d : nat * {poly F} * {poly F} -> Type := EdivpSpec n q r of m = q * d + r & (d != 0) ==> (size r < size d) : edivp_spec m d (n, q, r). Lemma edivpP m d : edivp_spec m d (edivp m d). Proof. rewrite edivp_def; constructor; first exact: divp_eq. by apply/implyP=> dn0; rewrite ltn_modp. Qed. Lemma edivp_eq d q r : size r < size d -> edivp (q * d + r) d = (0, q, r). Proof. move=> srd; apply: Idomain.edivp_eq; rewrite // unitfE lead_coef_eq0. by rewrite -size_poly_gt0; apply: leq_trans srd. Qed. Lemma modp_mul p q m : (p * (q %% m)) %% m = (p * q) %% m. Proof. by rewrite [in RHS](divp_eq q m) mulrDr modpD mulrA modp_mull add0r. Qed. Lemma horner_mod p q x : root q x -> (p %% q).[x] = p.[x]. Proof. by rewrite [in RHS](divp_eq p q) !hornerE => /eqP->; rewrite mulr0 add0r. Qed. Lemma dvdpP p q : reflect (exists qq, p = qq * q) (q %| p). Proof. have [-> | qn0] := eqVneq q 0; last first. by apply: IdomainUnit.dvdpP; rewrite unitfE lead_coef_eq0. by rewrite dvd0p; apply: (iffP eqP) => [->| [? ->]]; [exists 1|]; rewrite mulr0. Qed. Lemma Bezout_eq1_coprimepP p q : reflect (exists u, u.1 * p + u.2 * q = 1) (coprimep p q). Proof. apply: (iffP idP)=> [hpq|]; last first. by case=> -[u v] /= e; apply/Bezout_coprimepP; exists (u, v); rewrite e eqpxx. case/Bezout_coprimepP: hpq => [[u v]] /=. case/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0] e. exists (c2^-1 *: (c1 *: u), c2^-1 *: (c1 *: v)); rewrite /= -!scalerAl. by rewrite -!scalerDr e scalerA mulVf // scale1r. Qed. Lemma dvdp_gdcor p q : q != 0 -> p %| (gdcop q p) * (q ^+ size p). Proof. rewrite /gdcop => nz_q; have [n hsp] := ubnPleq (size p). elim: n => [|n IHn] /= in p hsp *; first by rewrite (negPf nz_q) mul0r dvdp0. have [_ | ncop_pq] := ifPn; first by rewrite dvdp_mulr. have g_gt1: 1 < size (gcdp p q). rewrite ltn_neqAle eq_sym ncop_pq size_poly_gt0 gcdp_eq0. by rewrite negb_and nz_q orbT. have [-> | nz_p] := eqVneq p 0. by rewrite div0p exprSr mulrA dvdp_mulr // IHn // size_poly0. have le_d_p: size (p %/ gcdp p q) < size p. rewrite size_divp -?size_poly_eq0 -(subnKC g_gt1) // add2n /=. by rewrite polySpred // ltnS subSS leq_subr. rewrite -[p in p %| _](divpK (dvdp_gcdl p q)) exprSr mulrA. by rewrite dvdp_mul ?IHn ?dvdp_gcdr // -ltnS (leq_trans le_d_p). Qed. Lemma reducible_cubic_root p q : size p <= 4 -> 1 < size q < size p -> q %| p -> {r | root p r}. Proof. move=> p_le4 /andP[]; rewrite leq_eqVlt eq_sym. have [/poly2_root[x qx0] _ _ | _ /= q_gt2 p_gt_q] := size q =P 2. by exists x; rewrite -!dvdp_XsubCl in qx0 *; apply: (dvdp_trans qx0). case/dvdpP/sig_eqW=> r def_p; rewrite def_p. suffices /poly2_root[x rx0]: size r = 2 by exists x; rewrite rootM rx0. have /norP[nz_r nz_q]: ~~ [|| r == 0 | q == 0]. by rewrite -mulf_eq0 -def_p -size_poly_gt0 (leq_ltn_trans _ p_gt_q). rewrite def_p size_mul // -subn1 leq_subLR ltn_subRL in p_gt_q p_le4. by apply/eqP; rewrite -(eqn_add2r (size q)) eqn_leq (leq_trans p_le4). Qed. Lemma cubic_irreducible p : 1 < size p <= 4 -> (forall x, ~~ root p x) -> irreducible_poly p. Proof. move=> /andP[p_gt1 p_le4] root'p; split=> // q sz_q_neq1 q_dv_p. have nz_p: p != 0 by rewrite -size_poly_gt0 ltnW. have nz_q: q != 0 by apply: contraTneq q_dv_p => ->; rewrite dvd0p. have q_gt1: size q > 1 by rewrite ltn_neqAle eq_sym sz_q_neq1 size_poly_gt0. rewrite -dvdp_size_eqp // eqn_leq dvdp_leq //= leqNgt; apply/negP=> p_gt_q. by have [|x /idPn//] := reducible_cubic_root p_le4 _ q_dv_p; rewrite q_gt1. Qed. Section Multiplicity. Definition mup x q := [arg max_(n > (ord0 : 'I_(size q).+1) | ('X - x%:P) ^+ n %| q) n] : nat. Lemma mup_geq x q n : q != 0 -> (n <= mup x q)%N = (('X - x%:P) ^+ n %| q). Proof. move=> q_neq0; rewrite /mup; symmetry. case: arg_maxnP; rewrite ?expr0 ?dvd1p//= => i i_dvd gti. case: ltnP => [|/dvdp_exp2l/dvdp_trans]; last exact. apply: contraTF => dvdq; rewrite -leqNgt. suff n_small : (n < (size q).+1)%N by exact: (gti (Ordinal n_small)). by rewrite ltnS ltnW// -(size_exp_XsubC _ x) dvdp_leq. Qed. Lemma mup_leq x q n : q != 0 -> (mup x q <= n)%N = ~~ (('X - x%:P) ^+ n.+1 %| q). Proof. by move=> qN0; rewrite leqNgt mup_geq. Qed. Lemma mup_ltn x q n : q != 0 -> (mup x q < n)%N = ~~ (('X - x%:P) ^+ n %| q). Proof. by move=> qN0; rewrite ltnNge mup_geq. Qed. Lemma XsubC_dvd x q : q != 0 -> ('X - x%:P %| q) = (0 < mup x q)%N. Proof. by move=> /mup_geq-/(_ _ 1%N)/esym; apply. Qed. Lemma mup_XsubCX n x y : mup x (('X - y%:P) ^+ n) = (if (y == x) then n else 0)%N. Proof. have Xxn0 : ('X - y%:P) ^+ n != 0 by rewrite ?expf_neq0 ?polyXsubC_eq0. apply/eqP; rewrite eqn_leq mup_leq ?mup_geq//. have [->|Nxy] := eqVneq x y. by rewrite /= dvdpp ?dvdp_Pexp2l ?size_XsubC ?ltnn. by rewrite dvd1p dvdp_XsubCl /root horner_exp !hornerE expf_neq0// subr_eq0. Qed. Lemma mupNroot x q : ~~ root q x -> mup x q = 0%N. Proof. move=> qNx; have qN0 : q != 0 by apply: contraNneq qNx => ->; rewrite root0. by move: qNx; rewrite -dvdp_XsubCl XsubC_dvd// lt0n negbK => /eqP. Qed. Lemma mupMr x q1 q2 : ~~ root q1 x -> mup x (q1 * q2) = mup x q2. Proof. move=> q1Nx; have q1N0 : q1 != 0 by apply: contraNneq q1Nx => ->; rewrite root0. have [->|q2N0] := eqVneq q2 0; first by rewrite mulr0. apply/esym/eqP; rewrite eqn_leq mup_geq ?mulf_neq0// dvdp_mull -?mup_geq//=. rewrite mup_leq ?mulf_neq0// Gauss_dvdpr -?mup_ltn//. by rewrite coprimep_expl// coprimep_sym coprimep_XsubC. Qed. Lemma mupMl x q1 q2 : ~~ root q2 x -> mup x (q1 * q2) = mup x q1. Proof. by rewrite mulrC; apply/mupMr. Qed. Lemma mupM x q1 q2 : q1 != 0 -> q2 != 0 -> mup x (q1 * q2) = (mup x q1 + mup x q2)%N. Proof. move=> q1N0 q2N0; apply/eqP; rewrite eqn_leq mup_leq ?mulf_neq0//. rewrite mup_geq ?mulf_neq0// exprD ?dvdp_mul; do ?by rewrite -mup_geq. have [m1 [r1]] := multiplicity_XsubC q1 x; rewrite q1N0 /= => r1Nx ->. have [m2 [r2]] := multiplicity_XsubC q2 x; rewrite q2N0 /= => r2Nx ->. rewrite !mupMr// ?mup_XsubCX eqxx/= mulrACA exprS exprD. rewrite dvdp_mul2r ?mulf_neq0 ?expf_neq0 ?polyXsubC_eq0//. by rewrite dvdp_XsubCl rootM negb_or r1Nx r2Nx. Qed. Lemma mu_prod_XsubC x (s : seq F) : mup x (\prod_(y <- s) ('X - y%:P)) = count_mem x s. Proof. elim: s => [|y s IHs]; rewrite (big_cons, big_nil)/=. by rewrite mupNroot// root1. rewrite mupM ?polyXsubC_eq0// ?monic_neq0 ?monic_prod_XsubC//. by rewrite IHs (@mup_XsubCX 1). Qed. Lemma prod_XsubC_eq (s t : seq F) : \prod_(x <- s) ('X - x%:P) = \prod_(x <- t) ('X - x%:P) -> perm_eq s t. Proof. move=> eq_prod; apply/allP => x _ /=; apply/eqP. by have /(congr1 (mup x)) := eq_prod; rewrite !mu_prod_XsubC. Qed. End Multiplicity. Section FieldRingMap. Variable rR : nzRingType. Variable f : {rmorphism F -> rR}. Local Notation "p ^f" := (map_poly f p) : ring_scope. Implicit Type a b : {poly F}. Lemma redivp_map a b : redivp a^f b^f = (rscalp a b, (rdivp a b)^f, (rmodp a b)^f). Proof. rewrite /rdivp /rscalp /rmodp !unlock map_poly_eq0 size_map_poly. have [// | q_nz] := ifPn; rewrite -(rmorph0 (map_poly f)) //. have [m _] := ubnPeq (size a); elim: m 0%N 0 a => [|m IHm] qq r a /=. rewrite -!mul_polyC !size_map_poly !lead_coef_map // -(map_polyXn f). by rewrite -!(map_polyC f) -!rmorphM -rmorphB -rmorphD; case: (_ < _). rewrite -!mul_polyC !size_map_poly !lead_coef_map // -(map_polyXn f). by rewrite -!(map_polyC f) -!rmorphM -rmorphB -rmorphD /= IHm; case: (_ < _). Qed. End FieldRingMap. Section FieldMap. Variable rR : idomainType. Variable f : {rmorphism F -> rR}. Local Notation "p ^f" := (map_poly f p) : ring_scope. Implicit Type a b : {poly F}. Lemma edivp_map a b : edivp a^f b^f = (0, (a %/ b)^f, (a %% b)^f). Proof. have [-> | bn0] := eqVneq b 0. rewrite (rmorph0 (map_poly f)) WeakIdomain.edivp_def !modp0 !divp0. by rewrite (rmorph0 (map_poly f)) scalp0. rewrite unlock redivp_map lead_coef_map rmorph_unit; last first. by rewrite unitfE lead_coef_eq0. rewrite modpE divpE !map_polyZ [in RHS]rmorphV ?rmorphXn // unitfE. by rewrite expf_neq0 // lead_coef_eq0. Qed. Lemma scalp_map p q : scalp p^f q^f = scalp p q. Proof. by rewrite /scalp edivp_map edivp_def. Qed. Lemma map_divp p q : (p %/ q)^f = p^f %/ q^f. Proof. by rewrite /divp edivp_map edivp_def. Qed. Lemma map_modp p q : (p %% q)^f = p^f %% q^f. Proof. by rewrite /modp edivp_map edivp_def. Qed. Lemma egcdp_map p q : egcdp (map_poly f p) (map_poly f q) = (map_poly f (egcdp p q).1, map_poly f (egcdp p q).2). Proof. wlog le_qp: p q / size q <= size p. move=> IH; have [/IH// | lt_qp] := leqP (size q) (size p). have /IH := ltnW lt_qp; rewrite /egcdp !size_map_poly ltnW // leqNgt lt_qp /=. by case: (egcdp_rec _ _ _) => u v [-> ->]. rewrite /egcdp !size_map_poly {}le_qp; move: (size q) => n. elim: n => /= [|n IHn] in p q *; first by rewrite rmorph1 rmorph0. rewrite map_poly_eq0; have [_ | nz_q] := ifPn; first by rewrite rmorph1 rmorph0. rewrite -map_modp (IHn q (p %% q)); case: (egcdp_rec _ _ n) => u v /=. rewrite map_polyZ lead_coef_map -rmorphXn scalp_map rmorphB rmorphM. by rewrite -map_divp. Qed. Lemma dvdp_map p q : (p^f %| q^f) = (p %| q). Proof. by rewrite /dvdp -map_modp map_poly_eq0. Qed. Lemma eqp_map p q : (p^f %= q^f) = (p %= q). Proof. by rewrite /eqp !dvdp_map. Qed. Lemma gcdp_map p q : (gcdp p q)^f = gcdp p^f q^f. Proof. wlog lt_p_q: p q / size p < size q. move=> IHpq; case: (ltnP (size p) (size q)) => [|le_q_p]; first exact: IHpq. rewrite gcdpE (gcdpE p^f) !size_map_poly ltnNge le_q_p /= -map_modp. have [-> | q_nz] := eqVneq q 0; first by rewrite rmorph0 !gcdp0. by rewrite IHpq ?ltn_modp. have [m le_q_m] := ubnP (size q); elim: m => // m IHm in p q lt_p_q le_q_m *. rewrite gcdpE (gcdpE p^f) !size_map_poly lt_p_q -map_modp. have [-> | q_nz] := eqVneq p 0; first by rewrite rmorph0 !gcdp0. by rewrite IHm ?(leq_trans lt_p_q) ?ltn_modp. Qed. Lemma coprimep_map p q : coprimep p^f q^f = coprimep p q. Proof. by rewrite -!gcdp_eqp1 -eqp_map rmorph1 gcdp_map. Qed. Lemma gdcop_rec_map p q n : (gdcop_rec p q n)^f = gdcop_rec p^f q^f n. Proof. elim: n p q => [|n IH] => /= p q. by rewrite map_poly_eq0; case: eqP; rewrite ?rmorph1 ?rmorph0. rewrite /coprimep -gcdp_map size_map_poly. by case: eqP => Hq0 //; rewrite -map_divp -IH. Qed. Lemma gdcop_map p q : (gdcop p q)^f = gdcop p^f q^f. Proof. by rewrite /gdcop gdcop_rec_map !size_map_poly. Qed. End FieldMap. End FieldDivision. #[deprecated(since="mathcomp 2.4.0", note="Renamed to leq_divMp.")] Notation leq_trunc_divp := leq_divMp. End Field. Module ClosedField. Import Field. Section closed. Variable F : closedFieldType. Lemma root_coprimep (p q : {poly F}) : (forall x, root p x -> q.[x] != 0) -> coprimep p q. Proof. move=> Ncmn; rewrite -gcdp_eqp1 -size_poly_eq1; apply/closed_rootP. by case=> r; rewrite root_gcd !rootE=> /andP [/Ncmn/negPf->]. Qed. Lemma coprimepP (p q : {poly F}) : reflect (forall x, root p x -> q.[x] != 0) (coprimep p q). Proof. by apply: (iffP idP)=> [/coprimep_root|/root_coprimep]. Qed. End closed. End ClosedField. End Pdiv. Export Pdiv.Field.
Notation.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, Yury Kudryashov, Yaël Dillies -/ import Qq import Mathlib.Lean.PrettyPrinter.Delaborator import Mathlib.Tactic.TypeStar import Mathlib.Tactic.Simps.NotationClass /-! # Notation classes for lattice operations In this file we introduce typeclasses and definitions for lattice operations. ## Main definitions * `HasCompl`: type class for the `ᶜ` notation * `Top`: type class for the `⊤` notation * `Bot`: type class for the `⊥` notation ## Notations * `xᶜ`: complement in a lattice; * `x ⊔ y`: supremum/join, which is notation for `max x y`; * `x ⊓ y`: infimum/meet, which is notation for `min x y`; We implement a delaborator that pretty prints `max x y`/`min x y` as `x ⊔ y`/`x ⊓ y` if and only if the order on `α` does not have a `LinearOrder α` instance (where `x y : α`). This is so that in a lattice we can use the same underlying constants `max`/`min` as in linear orders, while using the more idiomatic notation `x ⊔ y`/`x ⊓ y`. Lemmas about the operators `⊔` and `⊓` should use the names `sup` and `inf` respectively. -/ /-- Set / lattice complement -/ @[notation_class] class HasCompl (α : Type*) where /-- Set / lattice complement -/ compl : α → α export HasCompl (compl) @[inherit_doc] postfix:1024 "ᶜ" => compl /-! ### `Sup` and `Inf` -/ attribute [ext] Min Max /-- The supremum/join operation: `x ⊔ y`. It is notation for `max x y` and should be used when the type is not a linear order. -/ syntax:68 term:68 " ⊔ " term:69 : term /-- The infimum/meet operation: `x ⊓ y`. It is notation for `min x y` and should be used when the type is not a linear order. -/ syntax:69 term:69 " ⊓ " term:70 : term macro_rules | `($a ⊔ $b) => `(Max.max $a $b) | `($a ⊓ $b) => `(Min.min $a $b) namespace Mathlib.Meta open Lean Meta PrettyPrinter Delaborator SubExpr Qq -- irreducible to not confuse Qq @[irreducible] private def linearOrderExpr (u : Level) : Q(Type u → Type u) := .const `LinearOrder [u] private def linearOrderToMax (u : Level) : Q((a : Type u) → $(linearOrderExpr u) a → Max a) := .const `LinearOrder.toMax [u] private def linearOrderToMin (u : Level) : Q((a : Type u) → $(linearOrderExpr u) a → Min a) := .const `LinearOrder.toMin [u] /-- Return `true` if `LinearOrder` is imported and `inst` comes from a `LinearOrder e` instance. We use a `try catch` block to make sure there are no surprising errors during delaboration. -/ private def hasLinearOrder (u : Level) (α : Q(Type u)) (cls : Q(Type u → Type u)) (toCls : Q((α : Type u) → $(linearOrderExpr u) α → $cls α)) (inst : Q($cls $α)) : MetaM Bool := do try withNewMCtxDepth do -- `isDefEq` may call type class search to instantiate `mvar`, so we need the local instances -- In Lean 4.19 the pretty printer clears local instances, so we re-add them here. -- TODO(Jovan): remove withLocalInstances (← getLCtx).decls.toList.reduceOption do let mvar ← mkFreshExprMVarQ q($(linearOrderExpr u) $α) (kind := .synthetic) let inst' : Q($cls $α) := q($toCls $α $mvar) isDefEq inst inst' catch _ => -- For instance, if `LinearOrder` is not yet imported. return false /-- Delaborate `max x y` into `x ⊔ y` if the type is not a linear order. -/ @[delab app.Max.max] def delabSup : Delab := do let_expr f@Max.max α inst _ _ := ← getExpr | failure have u := f.constLevels![0]! if ← hasLinearOrder u α q(Max) q($(linearOrderToMax u)) inst then failure -- use the default delaborator let x ← withNaryArg 2 delab let y ← withNaryArg 3 delab let stx ← `($x ⊔ $y) annotateGoToSyntaxDef stx /-- Delaborate `min x y` into `x ⊓ y` if the type is not a linear order. -/ @[delab app.Min.min] def delabInf : Delab := do let_expr f@Min.min α inst _ _ := ← getExpr | failure have u := f.constLevels![0]! if ← hasLinearOrder u α q(Min) q($(linearOrderToMin u)) inst then failure -- use the default delaborator let x ← withNaryArg 2 delab let y ← withNaryArg 3 delab let stx ← `($x ⊓ $y) annotateGoToSyntaxDef stx end Mathlib.Meta /-- Syntax typeclass for Heyting implication `⇨`. -/ @[notation_class] class HImp (α : Type*) where /-- Heyting implication `⇨` -/ himp : α → α → α /-- Syntax typeclass for Heyting negation `¬`. The difference between `HasCompl` and `HNot` is that the former belongs to Heyting algebras, while the latter belongs to co-Heyting algebras. They are both pseudo-complements, but `compl` underestimates while `HNot` overestimates. In boolean algebras, they are equal. See `hnot_eq_compl`. -/ @[notation_class] class HNot (α : Type*) where /-- Heyting negation `¬` -/ hnot : α → α export HImp (himp) export SDiff (sdiff) export HNot (hnot) /-- Heyting implication -/ infixr:60 " ⇨ " => himp /-- Heyting negation -/ prefix:72 "¬" => hnot /-- Typeclass for the `⊤` (`\top`) notation -/ @[notation_class, ext] class Top (α : Type*) where /-- The top (`⊤`, `\top`) element -/ top : α /-- Typeclass for the `⊥` (`\bot`) notation -/ @[notation_class, ext] class Bot (α : Type*) where /-- The bot (`⊥`, `\bot`) element -/ bot : α /-- The top (`⊤`, `\top`) element -/ notation "⊤" => Top.top /-- The bot (`⊥`, `\bot`) element -/ notation "⊥" => Bot.bot instance (priority := 100) top_nonempty (α : Type*) [Top α] : Nonempty α := ⟨⊤⟩ instance (priority := 100) bot_nonempty (α : Type*) [Bot α] : Nonempty α := ⟨⊥⟩ attribute [match_pattern] Bot.bot Top.top
Lattice.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Data.List.Forall2 import Mathlib.Data.List.TakeDrop import Mathlib.Data.List.Lattice import Mathlib.Data.List.Nodup /-! # List Permutations and list lattice operations. This file develops theory about the `List.Perm` relation and the lattice structure on lists. -/ -- Make sure we don't import algebra assert_not_exists Monoid open Nat namespace List variable {α : Type*} open Perm (swap) variable [DecidableEq α] theorem Perm.bagInter_right {l₁ l₂ : List α} (t : List α) (h : l₁ ~ l₂) : l₁.bagInter t ~ l₂.bagInter t := by induction h generalizing t with | nil => simp | cons x => by_cases x ∈ t <;> simp [*] | swap x y => by_cases h : x = y · simp [h] by_cases xt : x ∈ t <;> by_cases yt : y ∈ t · simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (Ne.symm h), erase_comm, swap] · simp [xt, yt, mt mem_of_mem_erase] · simp [xt, yt, mt mem_of_mem_erase] · simp [xt, yt] | trans _ _ ih_1 ih_2 => exact (ih_1 _).trans (ih_2 _) theorem Perm.bagInter_left (l : List α) {t₁ t₂ : List α} (p : t₁ ~ t₂) : l.bagInter t₁ = l.bagInter t₂ := by induction l generalizing t₁ t₂ p with | nil => simp | cons a l IH => ?_ by_cases h : a ∈ t₁ · simp [h, p.subset h, IH (p.erase _)] · simp [h, mt p.mem_iff.2 h, IH p] theorem Perm.bagInter {l₁ l₂ t₁ t₂ : List α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.bagInter t₁ ~ l₂.bagInter t₂ := ht.bagInter_left l₂ ▸ hl.bagInter_right _ theorem Perm.inter_append {l t₁ t₂ : List α} (h : Disjoint t₁ t₂) : l ∩ (t₁ ++ t₂) ~ l ∩ t₁ ++ l ∩ t₂ := by induction l with | nil => simp | cons x xs l_ih => by_cases h₁ : x ∈ t₁ · have h₂ : x ∉ t₂ := h h₁ simp [*] by_cases h₂ : x ∈ t₂ · simp only [*, inter_cons_of_notMem, false_or, mem_append, inter_cons_of_mem, not_false_iff] refine Perm.trans (Perm.cons _ l_ih) ?_ change [x] ++ xs ∩ t₁ ++ xs ∩ t₂ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ t₂) rw [← List.append_assoc] solve_by_elim [Perm.append_right, perm_append_comm] · simp [*] theorem Perm.take_inter {xs ys : List α} (n : ℕ) (h : xs ~ ys) (h' : ys.Nodup) : xs.take n ~ ys.inter (xs.take n) := by simp only [List.inter] exact Perm.trans (show xs.take n ~ xs.filter (xs.take n).elem by conv_lhs => rw [Nodup.take_eq_filter_mem ((Perm.nodup_iff h).2 h')]) (Perm.filter _ h) theorem Perm.drop_inter {xs ys : List α} (n : ℕ) (h : xs ~ ys) (h' : ys.Nodup) : xs.drop n ~ ys.inter (xs.drop n) := by by_cases h'' : n ≤ xs.length · let n' := xs.length - n have h₀ : n = xs.length - n' := by rwa [Nat.sub_sub_self] have h₁ : xs.drop n = (xs.reverse.take n').reverse := by rw [take_reverse, h₀, reverse_reverse] rw [h₁] apply (reverse_perm _).trans rw [inter_reverse] apply Perm.take_inter _ _ h' apply (reverse_perm _).trans; assumption · have : xs.drop n = [] := by apply eq_nil_of_length_eq_zero rw [length_drop, Nat.sub_eq_zero_iff_le] apply le_of_not_ge h'' simp [this, List.inter] theorem Perm.dropSlice_inter {xs ys : List α} (n m : ℕ) (h : xs ~ ys) (h' : ys.Nodup) : List.dropSlice n m xs ~ ys ∩ List.dropSlice n m xs := by simp only [dropSlice_eq] have : n ≤ n + m := Nat.le_add_right _ _ have h₂ := h.nodup_iff.2 h' apply Perm.trans _ (Perm.inter_append _).symm · exact Perm.append (Perm.take_inter _ h h') (Perm.drop_inter _ h h') · exact disjoint_take_drop h₂ this end List
CongrExclamation.lean
/- Copyright (c) 2023 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Lean.Elab.Tactic.Config import Lean.Elab.Tactic.RCases import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Rfl import Mathlib.Lean.Meta.CongrTheorems import Mathlib.Logic.Basic /-! # The `congr!` tactic This is a more powerful version of the `congr` tactic that knows about more congruence lemmas and can apply to more situations. It is similar to the `congr'` tactic from Mathlib 3. The `congr!` tactic is used by the `convert` and `convert_to` tactics. See the syntax docstring for more details. -/ universe u v open Lean Meta Elab Tactic initialize registerTraceClass `congr! initialize registerTraceClass `congr!.synthesize /-- The configuration for the `congr!` tactic. -/ structure Congr!.Config where /-- If `closePre := true`, then try to close goals before applying congruence lemmas using tactics such as `rfl` and `assumption. These tactics are applied with the transparency level specified by `preTransparency`, which is `.reducible` by default. -/ closePre : Bool := true /-- If `closePost := true`, then try to close goals that remain after no more congruence lemmas can be applied, using the same tactics as `closePre`. These tactics are applied with current tactic transparency level. -/ closePost : Bool := true /-- The transparency level to use when applying a congruence theorem. By default this is `.reducible`, which prevents unfolding of most definitions. -/ transparency : TransparencyMode := TransparencyMode.reducible /-- The transparency level to use when trying to close goals before applying congruence lemmas. This includes trying to prove the goal by `rfl` and using the `assumption` tactic. By default this is `.reducible`, which prevents unfolding of most definitions. -/ preTransparency : TransparencyMode := TransparencyMode.reducible /-- For passes that synthesize a congruence lemma using one side of the equality, we run the pass both for the left-hand side and the right-hand side. If `preferLHS` is `true` then we start with the left-hand side. This can be used to control which side's definitions are expanded when applying the congruence lemma (if `preferLHS = true` then the RHS can be expanded). -/ preferLHS : Bool := true /-- Allow both sides to be partial applications. When false, given an equality `f a b = g x y z` this means we never consider proving `f a = g x y`. In this case, we might still consider `f = g x` if a pass generates a congruence lemma using the left-hand side. Use `sameFun := true` to ensure both sides are applications of the same function (making it be similar to the `congr` tactic). -/ partialApp : Bool := true /-- Whether to require that both sides of an equality be applications of defeq functions. That is, if true, `f a = g x` is only considered if `f` and `g` are defeq (making it be similar to the `congr` tactic). -/ sameFun : Bool := false /-- The maximum number of arguments to consider when doing congruence of function applications. For example, with `f a b c = g w x y z`, setting `maxArgs := some 2` means it will only consider either `f a b = g w x y` and `c = z` or `f a = g w x`, `b = y`, and `c = z`. Setting `maxArgs := none` (the default) means no limit. When the functions are dependent, `maxArgs` can prevent congruence from working at all. In `Fintype.card α = Fintype.card β`, one needs to have `maxArgs` at `2` or higher since there is a `Fintype` instance argument that depends on the first. When there aren't such dependency issues, setting `maxArgs := some 1` causes `congr!` to do congruence on a single argument at a time. This can be used in conjunction with the iteration limit to control exactly how many arguments are to be processed by congruence. -/ maxArgs : Option Nat := none /-- For type arguments that are implicit or have forward dependencies, whether or not `congr!` should generate equalities even if the types do not look plausibly equal. We have a heuristic in the main congruence generator that types `α` and `β` are *plausibly equal* according to the following algorithm: - If the types are both propositions, they are plausibly equal (`Iff`s are plausible). - If the types are from different universes, they are not plausibly equal. - Suppose in whnf we have `α = f a₁ ... aₘ` and `β = g b₁ ... bₘ`. If `f` is not definitionally equal to `g` or `m ≠ n`, then `α` and `β` are not plausibly equal. - If there is some `i` such that `aᵢ` and `bᵢ` are not plausibly equal, then `α` and `β` are not plausibly equal. - Otherwise, `α` and `β` are plausibly equal. The purpose of this is to prevent considering equalities like `ℕ = ℤ` while allowing equalities such as `Fin n = Fin m` or `Subtype p = Subtype q` (so long as these are subtypes of the same type). The way this is implemented is that when the congruence generator is comparing arguments when looking at an equality of function applications, it marks a function parameter as "fixed" if the provided arguments are types that are not plausibly equal. The effect of this is that congruence succeeds only if those arguments are defeq at `transparency` transparency. -/ typeEqs : Bool := false /-- As a last pass, perform eta expansion of both sides of an equality. For example, this transforms a bare `HAdd.hAdd` into `fun x y => x + y`. -/ etaExpand : Bool := false /-- Whether to use the congruence generator that is used by `simp` and `congr`. This generator is more strict, and it does not respect all configuration settings. It does respect `preferLHS`, `partialApp` and `maxArgs` and transparency settings. It acts as if `sameFun := true` and it ignores `typeEqs`. -/ useCongrSimp : Bool := false /-- Whether to use a special congruence lemma for `BEq` instances. This synthesizes `LawfulBEq` instances to discharge equalities of `BEq` instances. -/ beqEq : Bool := true /-- A configuration option that makes `congr!` do the sorts of aggressive unfoldings that `congr` does while also similarly preventing `congr!` from considering partial applications or congruences between different functions being applied. -/ def Congr!.Config.unfoldSameFun : Congr!.Config where partialApp := false sameFun := true transparency := .default preTransparency := .default /-- Whether the given number of arguments is allowed to be considered. -/ def Congr!.Config.numArgsOk (config : Config) (numArgs : Nat) : Bool := numArgs ≤ config.maxArgs.getD numArgs /-- According to the configuration, how many of the arguments in `numArgs` should be considered. -/ def Congr!.Config.maxArgsFor (config : Config) (numArgs : Nat) : Nat := min numArgs (config.maxArgs.getD numArgs) /-- Asserts the given congruence theorem as fresh hypothesis, and then applies it. Return the `fvarId` for the new hypothesis and the new subgoals. We apply it with transparency settings specified by `Congr!.Config.transparency`. -/ private def applyCongrThm? (config : Congr!.Config) (mvarId : MVarId) (congrThmType congrThmProof : Expr) : MetaM (List MVarId) := do trace[congr!] "trying to apply congr lemma {congrThmType}" try let mvarId ← mvarId.assert (← mkFreshUserName `h_congr_thm) congrThmType congrThmProof let (fvarId, mvarId) ← mvarId.intro1P let mvarIds ← withTransparency config.transparency <| mvarId.apply (mkFVar fvarId) { synthAssignedInstances := false } mvarIds.mapM fun mvarId => mvarId.tryClear fvarId catch e => withTraceNode `congr! (fun _ => pure m!"failed to apply congr lemma") do trace[congr!] "{e.toMessageData}" throw e /-- Returns whether or not it's reasonable to consider an equality between types `ty1` and `ty2`. The heuristic is the following: - If `ty1` and `ty2` are in `Prop`, then yes. - If in whnf both `ty1` and `ty2` have the same head and if (recursively) it's reasonable to consider an equality between corresponding type arguments, then yes. - Otherwise, no. This helps keep congr from going too far and generating hypotheses like `ℝ = ℤ`. To keep things from going out of control, there is a `maxDepth`. Additionally, if we do the check with `maxDepth = 0` then the heuristic answers "no". -/ def Congr!.plausiblyEqualTypes (ty1 ty2 : Expr) (maxDepth : Nat := 5) : MetaM Bool := match maxDepth with | 0 => return false | maxDepth + 1 => do -- Props are plausibly equal if (← isProp ty1) && (← isProp ty2) then return true -- Types from different type universes are not plausibly equal. -- This is redundant, but it saves carrying out the remaining checks. unless ← withNewMCtxDepth <| isDefEq (← inferType ty1) (← inferType ty2) do return false -- Now put the types into whnf, check they have the same head, and then recurse on arguments let ty1 ← whnfD ty1 let ty2 ← whnfD ty2 unless ← withNewMCtxDepth <| isDefEq ty1.getAppFn ty2.getAppFn do return false for arg1 in ty1.getAppArgs, arg2 in ty2.getAppArgs do if (← isType arg1) && (← isType arg2) then unless ← plausiblyEqualTypes arg1 arg2 maxDepth do return false return true /-- This is like `Lean.MVarId.hcongr?` but (1) looks at both sides when generating the congruence lemma and (2) inserts additional hypotheses from equalities from previous arguments. It uses `Lean.Meta.mkRichHCongr` to generate the congruence lemmas. If the goal is an `Eq`, it uses `eq_of_heq` first. As a backup strategy, it uses the LHS/RHS method like in `Lean.MVarId.congrSimp?` (where `Congr!.Config.preferLHS` determines which side to try first). This uses a particular side of the target, generates the congruence lemma, then tries applying it. This can make progress with higher transparency settings. To help the unifier, in this mode it assumes both sides have the exact same function. -/ partial def Lean.MVarId.smartHCongr? (config : Congr!.Config) (mvarId : MVarId) : MetaM (Option (List MVarId)) := mvarId.withContext do mvarId.checkNotAssigned `congr! commitWhenSome? do let mvarId ← mvarId.eqOfHEq let some (_, lhs, _, rhs) := (← withReducible mvarId.getType').heq? | return none if let some mvars ← loop mvarId 0 lhs rhs [] [] then return mvars -- The "correct" behavior failed. However, it's often useful -- to apply congruence lemmas while unfolding definitions, which is what the -- basic `congr` tactic does due to limitations in how congruence lemmas are generated. -- We simulate this behavior here by generating congruence lemmas for the LHS and RHS and -- then applying them. trace[congr!] "Default smartHCongr? failed, trying LHS/RHS method" let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs) if let some mvars ← forSide mvarId fst then return mvars else if let some mvars ← forSide mvarId snd then return mvars else return none where loop (mvarId : MVarId) (numArgs : Nat) (lhs rhs : Expr) (lhsArgs rhsArgs : List Expr) : MetaM (Option (List MVarId)) := match lhs.cleanupAnnotations, rhs.cleanupAnnotations with | .app f a, .app f' b => do if not (config.numArgsOk (numArgs + 1)) then return none let lhsArgs' := a :: lhsArgs let rhsArgs' := b :: rhsArgs -- We try to generate a theorem for the maximal number of arguments if let some mvars ← loop mvarId (numArgs + 1) f f' lhsArgs' rhsArgs' then return mvars -- That failing, we now try for the present number of arguments. if not config.partialApp && f.isApp && f'.isApp then -- It's a partial application on both sides though. return none -- The congruence generator only handles the case where both functions have -- definitionally equal types. unless ← withNewMCtxDepth <| isDefEq (← inferType f) (← inferType f') do return none let funDefEq ← withReducible <| withNewMCtxDepth <| isDefEq f f' if config.sameFun && not funDefEq then return none let info ← getFunInfoNArgs f (numArgs + 1) let mut fixed : Array Bool := #[] for larg in lhsArgs', rarg in rhsArgs', pinfo in info.paramInfo do if !config.typeEqs && (!pinfo.isExplicit || pinfo.hasFwdDeps) then -- When `typeEqs = false` then for non-explicit arguments or -- arguments with forward dependencies, we want type arguments -- to be plausibly equal. if ← isType larg then -- ^ since `f` and `f'` have defeq types, this implies `isType rarg`. unless ← Congr!.plausiblyEqualTypes larg rarg do fixed := fixed.push true continue fixed := fixed.push (← withReducible <| withNewMCtxDepth <| isDefEq larg rarg) let cthm ← mkRichHCongr (forceHEq := true) (← inferType f) info (fixedFun := funDefEq) (fixedParams := fixed) -- Now see if the congruence theorem actually applies in this situation by applying it! let (congrThm', congrProof') := if funDefEq then (cthm.type.bindingBody!.instantiate1 f, cthm.proof.beta #[f]) else (cthm.type.bindingBody!.bindingBody!.instantiateRev #[f, f'], cthm.proof.beta #[f, f']) observing? <| applyCongrThm? config mvarId congrThm' congrProof' | _, _ => return none forSide (mvarId : MVarId) (side : Expr) : MetaM (Option (List MVarId)) := do let side := side.cleanupAnnotations if not side.isApp then return none let numArgs := config.maxArgsFor side.getAppNumArgs if not config.partialApp && numArgs < side.getAppNumArgs then return none let mut f := side for _ in [:numArgs] do f := f.appFn!' let info ← getFunInfoNArgs f numArgs let mut fixed : Array Bool := #[] if !config.typeEqs then -- We need some strategy for fixed parameters to keep `forSide` from applying -- in cases where `Congr!.possiblyEqualTypes` suggested not to in the previous pass. for pinfo in info.paramInfo, arg in side.getAppArgs do if pinfo.isProp || !(← isType arg) then fixed := fixed.push false else if pinfo.isExplicit && !pinfo.hasFwdDeps then -- It's fine generating equalities for explicit type arguments without forward -- dependencies. Only allowing these is a little strict, because an argument -- might be something like `Fin n`. We might consider being able to generate -- congruence lemmas that only allow equalities where they can plausibly go, -- but that would take looking at a whole application tree. fixed := fixed.push false else fixed := fixed.push true let cthm ← mkRichHCongr (forceHEq := true) (← inferType f) info (fixedFun := true) (fixedParams := fixed) let congrThm' := cthm.type.bindingBody!.instantiate1 f let congrProof' := cthm.proof.beta #[f] observing? <| applyCongrThm? config mvarId congrThm' congrProof' /-- Like `Lean.MVarId.congr?` but instead of using only the congruence lemma associated to the LHS, it tries the RHS too, in the order specified by `config.preferLHS`. It uses `Lean.Meta.mkCongrSimp?` to generate a congruence lemma, like in the `congr` tactic. Applies the congruence generated congruence lemmas according to `config`. -/ def Lean.MVarId.congrSimp? (config : Congr!.Config) (mvarId : MVarId) : MetaM (Option (List MVarId)) := mvarId.withContext do mvarId.checkNotAssigned `congrSimp? let some (_, lhs, rhs) := (← withReducible mvarId.getType').eq? | return none let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs) if let some mvars ← forSide mvarId fst then return mvars else if let some mvars ← forSide mvarId snd then return mvars else return none where forSide (mvarId : MVarId) (side : Expr) : MetaM (Option (List MVarId)) := commitWhenSome? do let side := side.cleanupAnnotations if not side.isApp then return none let numArgs := config.maxArgsFor side.getAppNumArgs if not config.partialApp && numArgs < side.getAppNumArgs then return none let mut f := side for _ in [:numArgs] do f := f.appFn!' let some congrThm ← mkCongrSimpNArgs f numArgs | return none observing? <| applyCongrThm? config mvarId congrThm.type congrThm.proof /-- Like `mkCongrSimp?` but takes in a specific arity. -/ mkCongrSimpNArgs (f : Expr) (nArgs : Nat) : MetaM (Option CongrTheorem) := do let f := (← Lean.instantiateMVars f).cleanupAnnotations let info ← getFunInfoNArgs f nArgs mkCongrSimpCore? f info (← getCongrSimpKinds f info) (subsingletonInstImplicitRhs := false) /-- Try applying user-provided congruence lemmas. If any are applicable, returns a list of new goals. Tries a congruence lemma associated to the LHS and then, if that failed, the RHS. -/ def Lean.MVarId.userCongr? (config : Congr!.Config) (mvarId : MVarId) : MetaM (Option (List MVarId)) := mvarId.withContext do mvarId.checkNotAssigned `userCongr? let some (lhs, rhs) := (← withReducible mvarId.getType').eqOrIff? | return none let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs) if let some mvars ← forSide fst then return mvars else if let some mvars ← forSide snd then return mvars else return none where forSide (side : Expr) : MetaM (Option (List MVarId)) := do let side := side.cleanupAnnotations if not side.isApp then return none let some name := side.getAppFn.constName? | return none let congrTheorems := (← getSimpCongrTheorems).get name -- Note: congruence theorems are provided in decreasing order of priority. for congrTheorem in congrTheorems do let res ← observing? do let cinfo ← getConstInfo congrTheorem.theoremName let us ← cinfo.levelParams.mapM fun _ => mkFreshLevelMVar let proof := mkConst congrTheorem.theoremName us let ptype ← instantiateTypeLevelParams cinfo.toConstantVal us applyCongrThm? config mvarId ptype proof if let some mvars := res then return mvars return none /-- Try to apply `pi_congr`. This is similar to `Lean.MVar.congrImplies?`. -/ def Lean.MVarId.congrPi? (mvarId : MVarId) : MetaM (Option (List MVarId)) := observing? do withReducible <| mvarId.apply (← mkConstWithFreshMVarLevels `pi_congr) /-- Try to apply `funext`, but only if it is an equality of two functions where at least one is a lambda expression. One thing this check prevents is accidentally applying `funext` to a set equality, but also when doing congruence we don't want to apply `funext` unnecessarily. -/ def Lean.MVarId.obviousFunext? (mvarId : MVarId) : MetaM (Option (List MVarId)) := mvarId.withContext <| observing? do let some (_, lhs, rhs) := (← withReducible mvarId.getType').eq? | failure if not lhs.cleanupAnnotations.isLambda && not rhs.cleanupAnnotations.isLambda then failure mvarId.apply (← mkConstWithFreshMVarLevels ``funext) /-- Try to apply `Function.hfunext`, returning the new goals if it succeeds. Like `Lean.MVarId.obviousFunext?`, we only do so if at least one side of the `HEq` is a lambda. This prevents unfolding of things like `Set`. Need to have `Mathlib/Logic/Function/Basic.lean` imported for this to succeed. -/ def Lean.MVarId.obviousHfunext? (mvarId : MVarId) : MetaM (Option (List MVarId)) := mvarId.withContext <| observing? do let some (_, lhs, _, rhs) := (← withReducible mvarId.getType').heq? | failure if not lhs.cleanupAnnotations.isLambda && not rhs.cleanupAnnotations.isLambda then failure mvarId.apply (← mkConstWithFreshMVarLevels `Function.hfunext) /-- Like `implies_congr` but provides an additional assumption to the second hypothesis. This is a non-dependent version of `pi_congr` that allows the domains to be different. -/ private theorem implies_congr' {α α' : Sort u} {β β' : Sort v} (h : α = α') (h' : α' → β = β') : (α → β) = (α' → β') := by cases h change (∀ (x : α), (fun _ => β) x) = _ rw [funext h'] /-- A version of `Lean.MVarId.congrImplies?` that uses `implies_congr'` instead of `implies_congr`. -/ def Lean.MVarId.congrImplies?' (mvarId : MVarId) : MetaM (Option (List MVarId)) := observing? do let [mvarId₁, mvarId₂] ← mvarId.apply (← mkConstWithFreshMVarLevels ``implies_congr') | throwError "unexpected number of goals" return [mvarId₁, mvarId₂] /-- Try to apply `Subsingleton.helim` if the goal is a `HEq`. Tries synthesizing a `Subsingleton` instance for both the LHS and the RHS. If successful, this reduces proving `@HEq α x β y` to proving `α = β`. -/ def Lean.MVarId.subsingletonHelim? (mvarId : MVarId) : MetaM (Option (List MVarId)) := mvarId.withContext <| observing? do mvarId.checkNotAssigned `subsingletonHelim let some (α, lhs, β, rhs) := (← withReducible mvarId.getType').heq? | failure withSubsingletonAsFast fun elim => do let eqmvar ← mkFreshExprSyntheticOpaqueMVar (← mkEq α β) (← mvarId.getTag) -- First try synthesizing using the left-hand side for the Subsingleton instance if let some pf ← observing? (mkAppM ``FastSubsingleton.helim #[eqmvar, lhs, rhs]) then mvarId.assign <| elim pf return [eqmvar.mvarId!] let eqsymm ← mkAppM ``Eq.symm #[eqmvar] -- Second try synthesizing using the right-hand side for the Subsingleton instance if let some pf ← observing? (mkAppM ``FastSubsingleton.helim #[eqsymm, rhs, lhs]) then mvarId.assign <| elim (← mkAppM ``HEq.symm #[pf]) return [eqmvar.mvarId!] failure /-- Tries to apply `lawful_beq_subsingleton` to prove that two `BEq` instances are equal by synthesizing `LawfulBEq` instances for both. -/ def Lean.MVarId.beqInst? (mvarId : MVarId) : MetaM (Option (List MVarId)) := observing? do withReducible <| mvarId.applyConst ``lawful_beq_subsingleton /-- A list of all the congruence strategies used by `Lean.MVarId.congrCore!`. -/ def Lean.MVarId.congrPasses! : List (String × (Congr!.Config → MVarId → MetaM (Option (List MVarId)))) := [("user congr", userCongr?), ("hcongr lemma", smartHCongr?), ("congr simp lemma", when (·.useCongrSimp) congrSimp?), ("Subsingleton.helim", fun _ => subsingletonHelim?), ("BEq instances", when (·.beqEq) fun _ => beqInst?), ("obvious funext", fun _ => obviousFunext?), ("obvious hfunext", fun _ => obviousHfunext?), ("congr_implies", fun _ => congrImplies?'), ("congr_pi", fun _ => congrPi?)] where /-- Conditionally runs a congruence strategy depending on the predicate `b` applied to the config. -/ when (b : Congr!.Config → Bool) (f : Congr!.Config → MVarId → MetaM (Option (List MVarId))) (config : Congr!.Config) (mvar : MVarId) : MetaM (Option (List MVarId)) := do unless b config do return none f config mvar structure CongrState where /-- Accumulated goals that `congr!` could not handle. -/ goals : Array MVarId /-- Patterns to use when doing intro. -/ patterns : List (TSyntax `rcasesPat) abbrev CongrMetaM := StateRefT CongrState MetaM /-- Pop the next pattern from the current state. -/ def CongrMetaM.nextPattern : CongrMetaM (Option (TSyntax `rcasesPat)) := do modifyGet fun s => if let p :: ps := s.patterns then (p, {s with patterns := ps}) else (none, s) private theorem heq_imp_of_eq_imp {α : Sort*} {x y : α} {p : x ≍ y → Prop} (h : (he : x = y) → p (heq_of_eq he)) (he : x ≍ y) : p he := by cases he exact h rfl private theorem eq_imp_of_iff_imp {x y : Prop} {p : x = y → Prop} (h : (he : x ↔ y) → p (propext he)) (he : x = y) : p he := by cases he exact h Iff.rfl /-- Does `Lean.MVarId.intros` but then cleans up the introduced hypotheses, removing anything that is trivial. If there are any patterns in the current `CongrMetaM` state then instead of `Lean.MVarId.intros` it does `Lean.Elab..Tactic.RCases.rintro`. Cleaning up includes: - deleting hypotheses of the form `x ≍ x`, `x = x`, and `x ↔ x`. - deleting Prop hypotheses that are already in the local context. - converting `x ≍ y` to `x = y` if possible. - converting `x = y` to `x ↔ y` if possible. -/ partial def Lean.MVarId.introsClean (mvarId : MVarId) : CongrMetaM (List MVarId) := loop mvarId where heqImpOfEqImp (mvarId : MVarId) : MetaM (Option MVarId) := observing? <| withReducible do let [mvarId] ← mvarId.apply (← mkConstWithFreshMVarLevels ``heq_imp_of_eq_imp) | failure return mvarId eqImpOfIffImp (mvarId : MVarId) : MetaM (Option MVarId) := observing? <| withReducible do let [mvarId] ← mvarId.apply (← mkConstWithFreshMVarLevels ``eq_imp_of_iff_imp) | failure return mvarId loop (mvarId : MVarId) : CongrMetaM (List MVarId) := mvarId.withContext do let ty ← withReducible <| mvarId.getType' if ty.isForall then let mvarId := (← heqImpOfEqImp mvarId).getD mvarId let mvarId := (← eqImpOfIffImp mvarId).getD mvarId let ty ← withReducible <| mvarId.getType' if ty.isArrow then if ← (isTrivialType ty.bindingDomain! <||> (← getLCtx).anyM (fun decl => do return (← Lean.instantiateMVars decl.type) == ty.bindingDomain!)) then -- Don't intro, clear it let mvar ← mkFreshExprSyntheticOpaqueMVar ty.bindingBody! (← mvarId.getTag) mvarId.assign <| .lam .anonymous ty.bindingDomain! mvar .default return ← loop mvar.mvarId! if let some patt ← CongrMetaM.nextPattern then let gs ← Term.TermElabM.run' <| Lean.Elab.Tactic.RCases.rintro #[patt] none mvarId List.flatten <$> gs.mapM loop else let (_, mvarId) ← mvarId.intro1 loop mvarId else return [mvarId] isTrivialType (ty : Expr) : MetaM Bool := do unless ← Meta.isProp ty do return false let ty ← Lean.instantiateMVars ty if let some (lhs, rhs) := ty.eqOrIff? then if lhs.cleanupAnnotations == rhs.cleanupAnnotations then return true if let some (α, lhs, β, rhs) := ty.heq? then if α.cleanupAnnotations == β.cleanupAnnotations && lhs.cleanupAnnotations == rhs.cleanupAnnotations then return true return false /-- Convert a goal into an `Eq` goal if possible (since we have a better shot at those). Also, if `tryClose := true`, then try to close the goal using an assumption, `Subsingleton.Elim`, or definitional equality. -/ def Lean.MVarId.preCongr! (mvarId : MVarId) (tryClose : Bool) : MetaM (Option MVarId) := do -- Next, turn `HEq` and `Iff` into `Eq` let mvarId ← mvarId.heqOfEq if tryClose then -- This is a good time to check whether we have a relevant hypothesis. if ← mvarId.assumptionCore then return none let mvarId ← mvarId.iffOfEq if tryClose then -- Now try definitional equality. No need to try `mvarId.hrefl` since we already did `heqOfEq`. -- We allow synthetic opaque metavariables to be assigned to fill in `x = _` goals that might -- appear (for example, due to using `convert` with placeholders). try withAssignableSyntheticOpaque mvarId.refl; return none catch _ => pure () -- Now we go for (heterogeneous) equality via subsingleton considerations if ← Lean.Meta.fastSubsingletonElim mvarId then return none if ← mvarId.proofIrrelHeq then return none return some mvarId def Lean.MVarId.congrCore! (config : Congr!.Config) (mvarId : MVarId) : MetaM (Option (List MVarId)) := do mvarId.checkNotAssigned `congr! let s ← saveState /- We do `liftReflToEq` here rather than in `preCongr!` since we don't want to commit to it if there are no relevant congr lemmas. -/ let mvarId ← mvarId.liftReflToEq for (passName, pass) in congrPasses! do try if let some mvarIds ← pass config mvarId then trace[congr!] "pass succeeded: {passName}" return mvarIds catch e => throwTacticEx `congr! mvarId m!"internal error in congruence pass {passName}, {e.toMessageData}" if ← mvarId.isAssigned then throwTacticEx `congr! mvarId s!"congruence pass {passName} assigned metavariable but failed" restoreState s trace[congr!] "no passes succeeded" return none /-- A pass to clean up after `Lean.MVarId.preCongr!` and `Lean.MVarId.congrCore!`. -/ def Lean.MVarId.postCongr! (config : Congr!.Config) (mvarId : MVarId) : MetaM (Option MVarId) := do let some mvarId ← mvarId.preCongr! config.closePost | return none -- Convert `p = q` to `p ↔ q`, which is likely the more useful form: let mvarId ← mvarId.propext if config.closePost then -- `preCongr` sees `p = q`, but now we've put it back into `p ↔ q` form. if ← mvarId.assumptionCore then return none if config.etaExpand then if let some (_, lhs, rhs) := (← withReducible mvarId.getType').eq? then let lhs' ← Meta.etaExpand lhs let rhs' ← Meta.etaExpand rhs return ← mvarId.change (← mkEq lhs' rhs') return mvarId /-- A more insistent version of `Lean.MVarId.congrN`. See the documentation on the `congr!` syntax. The `depth?` argument controls the depth of the recursion. If `none`, then it uses a reasonably large bound that is linear in the expression depth. -/ def Lean.MVarId.congrN! (mvarId : MVarId) (depth? : Option Nat := none) (config : Congr!.Config := {}) (patterns : List (TSyntax `rcasesPat) := []) : MetaM (List MVarId) := do let ty ← withReducible <| mvarId.getType' -- A reasonably large yet practically bounded default recursion depth. let defaultDepth := min 1000000 (8 * (1 + ty.approxDepth.toNat)) let depth := depth?.getD defaultDepth let (_, s) ← go depth depth mvarId |>.run {goals := #[], patterns := patterns} return s.goals.toList where post (mvarId : MVarId) : CongrMetaM Unit := do for mvarId in ← mvarId.introsClean do if let some mvarId ← mvarId.postCongr! config then modify (fun s => {s with goals := s.goals.push mvarId}) else trace[congr!] "Dispatched goal by post-processing step." go (depth : Nat) (n : Nat) (mvarId : MVarId) : CongrMetaM Unit := do for mvarId in ← mvarId.introsClean do if let some mvarId ← withTransparency config.preTransparency <| mvarId.preCongr! config.closePre then match n with | 0 => trace[congr!] "At level {depth - n}, doing post-processing. {mvarId}" post mvarId | n + 1 => trace[congr!] "At level {depth - n}, trying congrCore!. {mvarId}" if let some mvarIds ← mvarId.congrCore! config then mvarIds.forM (go depth n) else post mvarId namespace Congr! declare_config_elab elabConfig Config /-- Equates pieces of the left-hand side of a goal to corresponding pieces of the right-hand side by recursively applying congruence lemmas. For example, with `⊢ f as = g bs` we could get two goals `⊢ f = g` and `⊢ as = bs`. Syntax: ``` congr! congr! n congr! with x y z congr! n with x y z ``` Here, `n` is a natural number and `x`, `y`, `z` are `rintro` patterns (like `h`, `rfl`, `⟨x, y⟩`, `_`, `-`, `(h | h)`, etc.). The `congr!` tactic is similar to `congr` but is more insistent in trying to equate left-hand sides to right-hand sides of goals. Here is a list of things it can try: - If `R` in `⊢ R x y` is a reflexive relation, it will convert the goal to `⊢ x = y` if possible. The list of reflexive relations is maintained using the `@[refl]` attribute. As a special case, `⊢ p ↔ q` is converted to `⊢ p = q` during congruence processing and then returned to `⊢ p ↔ q` form at the end. - If there is a user congruence lemma associated to the goal (for instance, a `@[congr]`-tagged lemma applying to `⊢ List.map f xs = List.map g ys`), then it will use that. - It uses a congruence lemma generator at least as capable as the one used by `congr` and `simp`. If there is a subexpression that can be rewritten by `simp`, then `congr!` should be able to generate an equality for it. - It can do congruences of pi types using lemmas like `implies_congr` and `pi_congr`. - Before applying congruences, it will run the `intros` tactic automatically. The introduced variables can be given names using a `with` clause. This helps when congruence lemmas provide additional assumptions in hypotheses. - When there is an equality between functions, so long as at least one is obviously a lambda, we apply `funext` or `Function.hfunext`, which allows for congruence of lambda bodies. - It can try to close goals using a few strategies, including checking definitional equality, trying to apply `Subsingleton.elim` or `proof_irrel_heq`, and using the `assumption` tactic. The optional parameter is the depth of the recursive applications. This is useful when `congr!` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr!` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr! 2` produces the intended `⊢ x + y = y + x`. The `congr!` tactic also takes a configuration option, for example ```lean congr! (transparency := .default) 2 ``` This overrides the default, which is to apply congruence lemmas at reducible transparency. The `congr!` tactic is aggressive with equating two sides of everything. There is a predefined configuration that uses a different strategy: Try ```lean congr! (config := .unfoldSameFun) ``` This only allows congruences between functions applications of definitionally equal functions, and it applies congruence lemmas at default transparency (rather than just reducible). This is somewhat like `congr`. See `Congr!.Config` for all options. -/ syntax (name := congr!) "congr!" Parser.Tactic.optConfig (ppSpace num)? (" with" (ppSpace colGt rintroPat)*)? : tactic elab_rules : tactic | `(tactic| congr! $cfg:optConfig $[$n]? $[with $ps?*]?) => do let config ← elabConfig cfg let patterns := (Lean.Elab.Tactic.RCases.expandRIntroPats (ps?.getD #[])).toList liftMetaTactic fun g ↦ let depth := n.map (·.getNat) g.congrN! depth config patterns end Congr!
Prod.lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Yury Kudryashov -/ import Mathlib.Algebra.Group.Equiv.Defs import Mathlib.Algebra.Group.Hom.Basic import Mathlib.Algebra.Group.Opposite import Mathlib.Algebra.Group.Torsion import Mathlib.Algebra.Group.Units.Hom import Mathlib.Algebra.Notation.Pi.Defs import Mathlib.Algebra.Notation.Prod import Mathlib.Logic.Equiv.Prod import Mathlib.Tactic.TermCongr /-! # Monoid, group etc structures on `M × N` In this file we define one-binop (`Monoid`, `Group` etc) structures on `M × N`. We also prove trivial `simp` lemmas, and define the following operations on `MonoidHom`s: * `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `Prod.fst` and `Prod.snd` as `MonoidHom`s; * `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid into the product; * `f.prod g` : `M →* N × P`: sends `x` to `(f x, g x)`; * When `P` is commutative, `f.coprod g : M × N →* P` sends `(x, y)` to `f x * g y` (without the commutativity assumption on `P`, see `MonoidHom.noncommPiCoprod`); * `f.prodMap g : M × N → M' × N'`: `Prod.map f g` as a `MonoidHom`, sends `(x, y)` to `(f x, g y)`. ## Main declarations * `mulMulHom`/`mulMonoidHom`: Multiplication bundled as a multiplicative/monoid homomorphism. * `divMonoidHom`: Division bundled as a monoid homomorphism. -/ assert_not_exists MonoidWithZero DenselyOrdered AddMonoidWithOne variable {G : Type*} {H : Type*} {M : Type*} {N : Type*} {P : Type*} namespace Prod @[to_additive] theorem one_mk_mul_one_mk [MulOneClass M] [Mul N] (b₁ b₂ : N) : ((1 : M), b₁) * (1, b₂) = (1, b₁ * b₂) := by rw [mk_mul_mk, mul_one] @[to_additive] theorem mk_one_mul_mk_one [Mul M] [MulOneClass N] (a₁ a₂ : M) : (a₁, (1 : N)) * (a₂, 1) = (a₁ * a₂, 1) := by rw [mk_mul_mk, mul_one] @[to_additive] theorem fst_mul_snd [MulOneClass M] [MulOneClass N] (p : M × N) : (p.fst, 1) * (1, p.snd) = p := Prod.ext (mul_one p.1) (one_mul p.2) @[to_additive] instance [InvolutiveInv M] [InvolutiveInv N] : InvolutiveInv (M × N) := { inv_inv := fun _ => Prod.ext (inv_inv _) (inv_inv _) } @[to_additive] instance instSemigroup [Semigroup M] [Semigroup N] : Semigroup (M × N) where mul_assoc _ _ _ := by ext <;> exact mul_assoc .. @[to_additive] instance instCommSemigroup [CommSemigroup G] [CommSemigroup H] : CommSemigroup (G × H) where mul_comm _ _ := by ext <;> exact mul_comm .. @[to_additive] instance instMulOneClass [MulOneClass M] [MulOneClass N] : MulOneClass (M × N) where one_mul _ := by ext <;> exact one_mul _ mul_one _ := by ext <;> exact mul_one _ @[to_additive] instance instMonoid [Monoid M] [Monoid N] : Monoid (M × N) := { npow := fun z a => ⟨Monoid.npow z a.1, Monoid.npow z a.2⟩, npow_zero := fun _ => Prod.ext (Monoid.npow_zero _) (Monoid.npow_zero _), npow_succ := fun _ _ => Prod.ext (Monoid.npow_succ _ _) (Monoid.npow_succ _ _), one_mul := by simp, mul_one := by simp } instance instIsMulTorsionFree [Monoid M] [Monoid N] [IsMulTorsionFree M] [IsMulTorsionFree N] : IsMulTorsionFree (M × N) where pow_left_injective n hn a b hab := by ext <;> apply pow_left_injective hn; exacts [congr(($hab).1), congr(($hab).2)] @[to_additive Prod.subNegMonoid] instance [DivInvMonoid G] [DivInvMonoid H] : DivInvMonoid (G × H) where div_eq_mul_inv _ _ := by ext <;> exact div_eq_mul_inv .. zpow z a := ⟨DivInvMonoid.zpow z a.1, DivInvMonoid.zpow z a.2⟩ zpow_zero' _ := by ext <;> exact DivInvMonoid.zpow_zero' _ zpow_succ' _ _ := by ext <;> exact DivInvMonoid.zpow_succ' .. zpow_neg' _ _ := by ext <;> exact DivInvMonoid.zpow_neg' .. @[to_additive] instance [DivisionMonoid G] [DivisionMonoid H] : DivisionMonoid (G × H) := { mul_inv_rev := fun _ _ => Prod.ext (mul_inv_rev _ _) (mul_inv_rev _ _), inv_eq_of_mul := fun _ _ h => Prod.ext (inv_eq_of_mul_eq_one_right <| congr_arg fst h) (inv_eq_of_mul_eq_one_right <| congr_arg snd h), inv_inv := by simp } @[to_additive SubtractionCommMonoid] instance [DivisionCommMonoid G] [DivisionCommMonoid H] : DivisionCommMonoid (G × H) := { mul_comm := fun ⟨g₁ , h₁⟩ ⟨_, _⟩ => by rw [mk_mul_mk, mul_comm g₁, mul_comm h₁]; rfl } @[to_additive] instance instGroup [Group G] [Group H] : Group (G × H) where inv_mul_cancel _ := by ext <;> exact inv_mul_cancel _ @[to_additive] instance [Mul G] [Mul H] [IsLeftCancelMul G] [IsLeftCancelMul H] : IsLeftCancelMul (G × H) where mul_left_cancel _ _ _ h := Prod.ext (mul_left_cancel (Prod.ext_iff.1 h).1) (mul_left_cancel (Prod.ext_iff.1 h).2) @[to_additive] instance [Mul G] [Mul H] [IsRightCancelMul G] [IsRightCancelMul H] : IsRightCancelMul (G × H) where mul_right_cancel _ _ _ h := Prod.ext (mul_right_cancel (Prod.ext_iff.1 h).1) (mul_right_cancel (Prod.ext_iff.1 h).2) @[to_additive] instance [Mul G] [Mul H] [IsCancelMul G] [IsCancelMul H] : IsCancelMul (G × H) where @[to_additive] instance [LeftCancelSemigroup G] [LeftCancelSemigroup H] : LeftCancelSemigroup (G × H) := { mul_left_cancel := fun _ _ _ => mul_left_cancel } @[to_additive] instance [RightCancelSemigroup G] [RightCancelSemigroup H] : RightCancelSemigroup (G × H) := { mul_right_cancel := fun _ _ _ => mul_right_cancel } @[to_additive] instance [LeftCancelMonoid M] [LeftCancelMonoid N] : LeftCancelMonoid (M × N) := { mul_one := by simp, one_mul := by simp mul_left_cancel _ _ := by simp } @[to_additive] instance [RightCancelMonoid M] [RightCancelMonoid N] : RightCancelMonoid (M × N) := { mul_one := by simp, one_mul := by simp mul_right_cancel _ _ := by simp } @[to_additive] instance [CancelMonoid M] [CancelMonoid N] : CancelMonoid (M × N) := { mul_right_cancel _ _ := by simp only [mul_left_inj, imp_self, forall_const] } @[to_additive] instance instCommMonoid [CommMonoid M] [CommMonoid N] : CommMonoid (M × N) := { mul_comm := fun ⟨m₁, n₁⟩ ⟨_, _⟩ => by rw [mk_mul_mk, mk_mul_mk, mul_comm m₁, mul_comm n₁] } @[to_additive] instance [CancelCommMonoid M] [CancelCommMonoid N] : CancelCommMonoid (M × N) := { mul_left_cancel _ _ := by simp } @[to_additive] instance instCommGroup [CommGroup G] [CommGroup H] : CommGroup (G × H) := { mul_comm := fun ⟨g₁, h₁⟩ ⟨_, _⟩ => by rw [mk_mul_mk, mk_mul_mk, mul_comm g₁, mul_comm h₁] } end Prod section variable [Mul M] [Mul N] @[to_additive AddSemiconjBy.prod] theorem SemiconjBy.prod {x y z : M × N} (hm : SemiconjBy x.1 y.1 z.1) (hn : SemiconjBy x.2 y.2 z.2) : SemiconjBy x y z := Prod.ext hm hn @[to_additive] theorem Prod.semiconjBy_iff {x y z : M × N} : SemiconjBy x y z ↔ SemiconjBy x.1 y.1 z.1 ∧ SemiconjBy x.2 y.2 z.2 := Prod.ext_iff @[to_additive AddCommute.prod] theorem Commute.prod {x y : M × N} (hm : Commute x.1 y.1) (hn : Commute x.2 y.2) : Commute x y := SemiconjBy.prod hm hn @[to_additive] theorem Prod.commute_iff {x y : M × N} : Commute x y ↔ Commute x.1 y.1 ∧ Commute x.2 y.2 := semiconjBy_iff end namespace MulHom section Prod variable (M N) [Mul M] [Mul N] [Mul P] /-- Given magmas `M`, `N`, the natural projection homomorphism from `M × N` to `M`. -/ @[to_additive /-- Given additive magmas `A`, `B`, the natural projection homomorphism from `A × B` to `A` -/] def fst : M × N →ₙ* M := ⟨Prod.fst, fun _ _ => rfl⟩ /-- Given magmas `M`, `N`, the natural projection homomorphism from `M × N` to `N`. -/ @[to_additive /-- Given additive magmas `A`, `B`, the natural projection homomorphism from `A × B` to `B` -/] def snd : M × N →ₙ* N := ⟨Prod.snd, fun _ _ => rfl⟩ variable {M N} @[to_additive (attr := simp)] theorem coe_fst : ⇑(fst M N) = Prod.fst := rfl @[to_additive (attr := simp)] theorem coe_snd : ⇑(snd M N) = Prod.snd := rfl /-- Combine two `MonoidHom`s `f : M →ₙ* N`, `g : M →ₙ* P` into `f.prod g : M →ₙ* (N × P)` given by `(f.prod g) x = (f x, g x)`. -/ @[to_additive prod /-- Combine two `AddMonoidHom`s `f : AddHom M N`, `g : AddHom M P` into `f.prod g : AddHom M (N × P)` given by `(f.prod g) x = (f x, g x)` -/] protected def prod (f : M →ₙ* N) (g : M →ₙ* P) : M →ₙ* N × P where toFun := Pi.prod f g map_mul' x y := Prod.ext (f.map_mul x y) (g.map_mul x y) @[to_additive coe_prod] theorem coe_prod (f : M →ₙ* N) (g : M →ₙ* P) : ⇑(f.prod g) = Pi.prod f g := rfl @[to_additive (attr := simp) prod_apply] theorem prod_apply (f : M →ₙ* N) (g : M →ₙ* P) (x) : f.prod g x = (f x, g x) := rfl @[to_additive (attr := simp) fst_comp_prod] theorem fst_comp_prod (f : M →ₙ* N) (g : M →ₙ* P) : (fst N P).comp (f.prod g) = f := ext fun _ => rfl @[to_additive (attr := simp) snd_comp_prod] theorem snd_comp_prod (f : M →ₙ* N) (g : M →ₙ* P) : (snd N P).comp (f.prod g) = g := ext fun _ => rfl @[to_additive (attr := simp) prod_unique] theorem prod_unique (f : M →ₙ* N × P) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext fun x => by simp only [prod_apply, coe_fst, coe_snd, comp_apply] end Prod section prodMap variable {M' : Type*} {N' : Type*} [Mul M] [Mul N] [Mul M'] [Mul N'] [Mul P] (f : M →ₙ* M') (g : N →ₙ* N') /-- `Prod.map` as a `MonoidHom`. -/ @[to_additive prodMap /-- `Prod.map` as an `AddMonoidHom` -/] def prodMap : M × N →ₙ* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prodMap_def] theorem prodMap_def : prodMap f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[to_additive (attr := simp) coe_prodMap] theorem coe_prodMap : ⇑(prodMap f g) = Prod.map f g := rfl @[to_additive prod_comp_prodMap] theorem prod_comp_prodMap (f : P →ₙ* M) (g : P →ₙ* N) (f' : M →ₙ* M') (g' : N →ₙ* N') : (f'.prodMap g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prodMap section Coprod variable [Mul M] [Mul N] [CommSemigroup P] (f : M →ₙ* P) (g : N →ₙ* P) /-- Coproduct of two `MulHom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. (Commutative codomain; for the general case, see `MulHom.noncommCoprod`) -/ @[to_additive /-- Coproduct of two `AddHom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`. (Commutative codomain; for the general case, see `AddHom.noncommCoprod`) -/] def coprod : M × N →ₙ* P := f.comp (fst M N) * g.comp (snd M N) @[to_additive (attr := simp)] theorem coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[to_additive] theorem comp_coprod {Q : Type*} [CommSemigroup Q] (h : P →ₙ* Q) (f : M →ₙ* P) (g : N →ₙ* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext fun x => by simp end Coprod end MulHom namespace MonoidHom variable (M N) [MulOneClass M] [MulOneClass N] /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`. -/ @[to_additive /-- Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `A` -/] def fst : M × N →* M := { toFun := Prod.fst, map_one' := rfl, map_mul' := fun _ _ => rfl } /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`. -/ @[to_additive /-- Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `B` -/] def snd : M × N →* N := { toFun := Prod.snd, map_one' := rfl, map_mul' := fun _ _ => rfl } /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/ @[to_additive /-- Given additive monoids `A`, `B`, the natural inclusion homomorphism from `A` to `A × B`. -/] def inl : M →* M × N := { toFun := fun x => (x, 1), map_one' := rfl, map_mul' := fun _ _ => Prod.ext rfl (one_mul 1).symm } /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/ @[to_additive /-- Given additive monoids `A`, `B`, the natural inclusion homomorphism from `B` to `A × B`. -/] def inr : N →* M × N := { toFun := fun y => (1, y), map_one' := rfl, map_mul' := fun _ _ => Prod.ext (one_mul 1).symm rfl } variable {M N} @[to_additive (attr := simp)] theorem coe_fst : ⇑(fst M N) = Prod.fst := rfl @[to_additive (attr := simp)] theorem coe_snd : ⇑(snd M N) = Prod.snd := rfl @[to_additive (attr := simp)] theorem inl_apply (x) : inl M N x = (x, 1) := rfl @[to_additive (attr := simp)] theorem inr_apply (y) : inr M N y = (1, y) := rfl @[to_additive (attr := simp)] theorem fst_comp_inl : (fst M N).comp (inl M N) = id M := rfl @[to_additive (attr := simp)] theorem snd_comp_inl : (snd M N).comp (inl M N) = 1 := rfl @[to_additive (attr := simp)] theorem fst_comp_inr : (fst M N).comp (inr M N) = 1 := rfl @[to_additive (attr := simp)] theorem snd_comp_inr : (snd M N).comp (inr M N) = id N := rfl @[to_additive] theorem commute_inl_inr (m : M) (n : N) : Commute (inl M N m) (inr M N n) := Commute.prod (.one_right m) (.one_left n) section Prod variable [MulOneClass P] /-- Combine two `MonoidHom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P` given by `(f.prod g) x = (f x, g x)`. -/ @[to_additive prod /-- Combine two `AddMonoidHom`s `f : M →+ N`, `g : M →+ P` into `f.prod g : M →+ N × P` given by `(f.prod g) x = (f x, g x)` -/] protected def prod (f : M →* N) (g : M →* P) : M →* N × P where toFun := Pi.prod f g map_one' := Prod.ext f.map_one g.map_one map_mul' x y := Prod.ext (f.map_mul x y) (g.map_mul x y) @[to_additive coe_prod] theorem coe_prod (f : M →* N) (g : M →* P) : ⇑(f.prod g) = Pi.prod f g := rfl @[to_additive (attr := simp) prod_apply] theorem prod_apply (f : M →* N) (g : M →* P) (x) : f.prod g x = (f x, g x) := rfl @[to_additive (attr := simp) fst_comp_prod] theorem fst_comp_prod (f : M →* N) (g : M →* P) : (fst N P).comp (f.prod g) = f := ext fun _ => rfl @[to_additive (attr := simp) snd_comp_prod] theorem snd_comp_prod (f : M →* N) (g : M →* P) : (snd N P).comp (f.prod g) = g := ext fun _ => rfl @[to_additive (attr := simp) prod_unique] theorem prod_unique (f : M →* N × P) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext fun x => by simp only [prod_apply, coe_fst, coe_snd, comp_apply] end Prod section prodMap variable {M' : Type*} {N' : Type*} [MulOneClass M'] [MulOneClass N'] [MulOneClass P] (f : M →* M') (g : N →* N') /-- `Prod.map` as a `MonoidHom`. -/ @[to_additive prodMap /-- `Prod.map` as an `AddMonoidHom`. -/] def prodMap : M × N →* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prodMap_def] theorem prodMap_def : prodMap f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[to_additive (attr := simp) coe_prodMap] theorem coe_prodMap : ⇑(prodMap f g) = Prod.map f g := rfl @[to_additive prod_comp_prodMap] theorem prod_comp_prodMap (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') : (f'.prodMap g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prodMap section Coprod variable [CommMonoid P] (f : M →* P) (g : N →* P) /-- Coproduct of two `MonoidHom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. (Commutative case; for the general case, see `MonoidHom.noncommCoprod`.) -/ @[to_additive /-- Coproduct of two `AddMonoidHom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`. (Commutative case; for the general case, see `AddHom.noncommCoprod`.) -/] def coprod : M × N →* P := f.comp (fst M N) * g.comp (snd M N) @[to_additive (attr := simp)] theorem coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[to_additive (attr := simp)] theorem coprod_comp_inl : (f.coprod g).comp (inl M N) = f := ext fun x => by simp [coprod_apply] @[to_additive (attr := simp)] theorem coprod_comp_inr : (f.coprod g).comp (inr M N) = g := ext fun x => by simp [coprod_apply] @[to_additive (attr := simp)] theorem coprod_unique (f : M × N →* P) : (f.comp (inl M N)).coprod (f.comp (inr M N)) = f := ext fun x => by simp [coprod_apply, inl_apply, inr_apply, ← map_mul] @[to_additive (attr := simp)] theorem coprod_inl_inr {M N : Type*} [CommMonoid M] [CommMonoid N] : (inl M N).coprod (inr M N) = id (M × N) := coprod_unique (id <| M × N) @[to_additive] theorem comp_coprod {Q : Type*} [CommMonoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext fun x => by simp end Coprod end MonoidHom namespace MulEquiv section variable [MulOneClass M] [MulOneClass N] /-- The equivalence between `M × N` and `N × M` given by swapping the components is multiplicative. -/ @[to_additive prodComm /-- The equivalence between `M × N` and `N × M` given by swapping the components is additive. -/] def prodComm : M × N ≃* N × M := { Equiv.prodComm M N with map_mul' := fun ⟨_, _⟩ ⟨_, _⟩ => rfl } @[to_additive (attr := simp) coe_prodComm] theorem coe_prodComm : ⇑(prodComm : M × N ≃* N × M) = Prod.swap := rfl @[to_additive (attr := simp) coe_prodComm_symm] theorem coe_prodComm_symm : ⇑(prodComm : M × N ≃* N × M).symm = Prod.swap := rfl variable [MulOneClass P] /-- The equivalence between `(M × N) × P` and `M × (N × P)` is multiplicative. -/ @[to_additive prodAssoc /-- The equivalence between `(M × N) × P` and `M × (N × P)` is additive. -/] def prodAssoc : (M × N) × P ≃* M × (N × P) := { Equiv.prodAssoc M N P with map_mul' := fun ⟨_, _⟩ ⟨_, _⟩ => rfl } @[to_additive (attr := simp) coe_prodAssoc] theorem coe_prodAssoc : ⇑(prodAssoc : (M × N) × P ≃* M × (N × P)) = Equiv.prodAssoc M N P := rfl @[to_additive (attr := simp) coe_prodAssoc_symm] theorem coe_prodAssoc_symm : ⇑(prodAssoc : (M × N) × P ≃* M × (N × P)).symm = (Equiv.prodAssoc M N P).symm := rfl variable {M' : Type*} {N' : Type*} [MulOneClass N'] [MulOneClass M'] section variable (M N M' N') /-- Four-way commutativity of `Prod`. The name matches `mul_mul_mul_comm`. -/ @[to_additive (attr := simps apply) prodProdProdComm /-- Four-way commutativity of `Prod`. The name matches `mul_mul_mul_comm` -/] def prodProdProdComm : (M × N) × M' × N' ≃* (M × M') × N × N' := { Equiv.prodProdProdComm M N M' N' with toFun := fun mnmn => ((mnmn.1.1, mnmn.2.1), (mnmn.1.2, mnmn.2.2)) invFun := fun mmnn => ((mmnn.1.1, mmnn.2.1), (mmnn.1.2, mmnn.2.2)) map_mul' := fun _mnmn _mnmn' => rfl } @[to_additive (attr := simp) prodProdProdComm_toEquiv] theorem prodProdProdComm_toEquiv : (prodProdProdComm M N M' N' : _ ≃ _) = Equiv.prodProdProdComm M N M' N' := rfl @[simp] theorem prodProdProdComm_symm : (prodProdProdComm M N M' N').symm = prodProdProdComm M M' N N' := rfl end /-- Product of multiplicative isomorphisms; the maps come from `Equiv.prodCongr`. -/ @[to_additive prodCongr /-- Product of additive isomorphisms; the maps come from `Equiv.prodCongr`. -/] def prodCongr (f : M ≃* M') (g : N ≃* N') : M × N ≃* M' × N' := { f.toEquiv.prodCongr g.toEquiv with map_mul' := fun _ _ => Prod.ext (map_mul f _ _) (map_mul g _ _) } /-- Multiplying by the trivial monoid doesn't change the structure. This is the `MulEquiv` version of `Equiv.uniqueProd`. -/ @[to_additive uniqueProd /-- Multiplying by the trivial monoid doesn't change the structure. This is the `AddEquiv` version of `Equiv.uniqueProd`. -/] def uniqueProd [Unique N] : N × M ≃* M := { Equiv.uniqueProd M N with map_mul' := fun _ _ => rfl } /-- Multiplying by the trivial monoid doesn't change the structure. This is the `MulEquiv` version of `Equiv.prodUnique`. -/ @[to_additive prodUnique /-- Multiplying by the trivial monoid doesn't change the structure. This is the `AddEquiv` version of `Equiv.prodUnique`. -/] def prodUnique [Unique N] : M × N ≃* M := { Equiv.prodUnique M N with map_mul' := fun _ _ => rfl } end section variable [Monoid M] [Monoid N] /-- The monoid equivalence between units of a product of two monoids, and the product of the units of each monoid. -/ @[to_additive prodAddUnits /-- The additive monoid equivalence between additive units of a product of two additive monoids, and the product of the additive units of each additive monoid. -/] def prodUnits : (M × N)ˣ ≃* Mˣ × Nˣ where toFun := (Units.map (MonoidHom.fst M N)).prod (Units.map (MonoidHom.snd M N)) invFun u := ⟨(u.1, u.2), (↑u.1⁻¹, ↑u.2⁻¹), by simp, by simp⟩ left_inv u := by simp only [MonoidHom.prod_apply, Units.coe_map, MonoidHom.coe_fst, MonoidHom.coe_snd, Prod.mk.eta, Units.coe_map_inv, Units.mk_val] right_inv := fun ⟨u₁, u₂⟩ => by simp only [Units.map, MonoidHom.coe_fst, Units.inv_eq_val_inv, MonoidHom.coe_snd, MonoidHom.prod_apply, Prod.mk.injEq] exact ⟨rfl, rfl⟩ map_mul' := MonoidHom.map_mul _ @[to_additive] lemma _root_.Prod.isUnit_iff {x : M × N} : IsUnit x ↔ IsUnit x.1 ∧ IsUnit x.2 where mp h := ⟨(prodUnits h.unit).1.isUnit, (prodUnits h.unit).2.isUnit⟩ mpr h := (prodUnits.symm (h.1.unit, h.2.unit)).isUnit end end MulEquiv namespace Units open MulOpposite /-- Canonical homomorphism of monoids from `αˣ` into `α × αᵐᵒᵖ`. Used mainly to define the natural topology of `αˣ`. -/ @[to_additive (attr := simps) /-- Canonical homomorphism of additive monoids from `AddUnits α` into `α × αᵃᵒᵖ`. Used mainly to define the natural topology of `AddUnits α`. -/] def embedProduct (α : Type*) [Monoid α] : αˣ →* α × αᵐᵒᵖ where toFun x := ⟨x, op ↑x⁻¹⟩ map_one' := by simp only [inv_one, Units.val_one, op_one, Prod.mk_eq_one, and_self_iff] map_mul' x y := by simp only [mul_inv_rev, op_mul, Units.val_mul, Prod.mk_mul_mk] @[to_additive] theorem embedProduct_injective (α : Type*) [Monoid α] : Function.Injective (embedProduct α) := fun _ _ h => Units.ext <| (congr_arg Prod.fst h :) end Units /-! ### Multiplication and division as homomorphisms -/ section BundledMulDiv variable {α : Type*} /-- Multiplication as a multiplicative homomorphism. -/ @[to_additive (attr := simps) /-- Addition as an additive homomorphism. -/] def mulMulHom [CommSemigroup α] : α × α →ₙ* α where toFun a := a.1 * a.2 map_mul' _ _ := mul_mul_mul_comm _ _ _ _ /-- Multiplication as a monoid homomorphism. -/ @[to_additive (attr := simps) /-- Addition as an additive monoid homomorphism. -/] def mulMonoidHom [CommMonoid α] : α × α →* α := { mulMulHom with map_one' := mul_one _ } /-- Division as a monoid homomorphism. -/ @[to_additive (attr := simps) /-- Subtraction as an additive monoid homomorphism. -/] def divMonoidHom [DivisionCommMonoid α] : α × α →* α where toFun a := a.1 / a.2 map_one' := div_one _ map_mul' _ _ := mul_div_mul_comm _ _ _ _ end BundledMulDiv
Depth.lean
/- Copyright (c) 2025 Nailin Guan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nailin Guan, Yi Song -/ import Mathlib.Algebra.Module.FinitePresentation import Mathlib.LinearAlgebra.Dual.Lemmas import Mathlib.RingTheory.Ideal.AssociatedPrime.Finiteness import Mathlib.RingTheory.Ideal.AssociatedPrime.Localization import Mathlib.RingTheory.LocalRing.ResidueField.Ideal import Mathlib.RingTheory.Regular.IsSMulRegular import Mathlib.RingTheory.Support /-! # Hom(N,M) is subsingleton iff there exists a smul regular element of M in ann(N) Let `M` and `N` be `R`-modules. In this section we prove that `Hom(N,M)` is subsingleton iff there exist `r : R`, such that `IsSMulRegular M r` and `r ∈ ann(N)`. This is the case if `Depth[I](M) = 0`. # Main Results * `IsSMulRegular.subsingleton_linearMap_iff` : for `R` module `N M`, `Hom(N, M) = 0` iff there is a `M`-regular in `Module.annihilator R N`. -/ open IsLocalRing LinearMap Module namespace IsSMulRegular variable {R M N : Type*} [CommRing R] [AddCommGroup M] [AddCommGroup N] [Module R M] [Module R N] lemma linearMap_subsingleton_of_mem_annihilator {r : R} (reg : IsSMulRegular M r) (mem_ann : r ∈ Module.annihilator R N) : Subsingleton (N →ₗ[R] M) := by apply subsingleton_of_forall_eq 0 (fun f ↦ ext fun x ↦ ?_) have : r • (f x) = r • 0 := by rw [smul_zero, ← map_smul, Module.mem_annihilator.mp mem_ann x, map_zero] simpa using reg this lemma subsingleton_linearMap_iff [IsNoetherianRing R] [Module.Finite R M] [Module.Finite R N] : Subsingleton (N →ₗ[R] M) ↔ ∃ r ∈ Module.annihilator R N, IsSMulRegular M r := by refine ⟨fun hom0 ↦ ?_, fun ⟨r, mem_ann, reg⟩ ↦ linearMap_subsingleton_of_mem_annihilator reg mem_ann⟩ by_cases htrivial : Subsingleton M · exact ⟨0, ⟨Submodule.zero_mem (Module.annihilator R N), IsSMulRegular.zero⟩⟩ · let _ : Nontrivial M := not_subsingleton_iff_nontrivial.mp htrivial by_contra! h have hexist : ∃ p ∈ associatedPrimes R M, Module.annihilator R N ≤ p := by rcases associatedPrimes.nonempty R M with ⟨Ia, hIa⟩ apply (Ideal.subset_union_prime_finite (associatedPrimes.finite R M) Ia Ia _).mp · rw [biUnion_associatedPrimes_eq_compl_regular R M] exact fun r hr ↦ h r hr · exact fun I hin _ _ ↦ IsAssociatedPrime.isPrime hin rcases hexist with ⟨p, pass, hp⟩ let _ := pass.isPrime let p' : PrimeSpectrum R := ⟨p, pass.isPrime⟩ have loc_ne_zero : p' ∈ Module.support R N := Module.mem_support_iff_of_finite.mpr hp rw [Module.mem_support_iff] at loc_ne_zero let Rₚ := Localization.AtPrime p let Nₚ := LocalizedModule p'.asIdeal.primeCompl N let Mₚ := LocalizedModule p'.asIdeal.primeCompl M let Nₚ' := Nₚ ⧸ (IsLocalRing.maximalIdeal (Localization.AtPrime p)) • (⊤ : Submodule Rₚ Nₚ) have ntr : Nontrivial Nₚ' := Submodule.Quotient.nontrivial_of_lt_top _ (Ne.lt_top' (Submodule.top_ne_ideal_smul_of_le_jacobson_annihilator (IsLocalRing.maximalIdeal_le_jacobson (Module.annihilator Rₚ Nₚ)))) let Mₚ' := Mₚ ⧸ (IsLocalRing.maximalIdeal (Localization.AtPrime p)) • (⊤ : Submodule Rₚ Mₚ) let _ : Module p.ResidueField Nₚ' := Module.instQuotientIdealSubmoduleHSMulTop Nₚ (maximalIdeal (Localization.AtPrime p)) have := AssociatePrimes.mem_iff.mp (associatedPrimes.mem_associatePrimes_localizedModule_atPrime_of_mem_associated_primes pass) rcases this.2 with ⟨x, hx⟩ have : Nontrivial (Module.Dual p.ResidueField Nₚ') := by simpa using ntr rcases exists_ne (α := Module.Dual p.ResidueField Nₚ') 0 with ⟨g, hg⟩ let to_res' : Nₚ' →ₗ[Rₚ] p.ResidueField := { __ := g map_smul' r x := by simp only [AddHom.toFun_eq_coe, coe_toAddHom, RingHom.id_apply] convert g.map_smul (Ideal.Quotient.mk _ r) x } let to_res : Nₚ →ₗ[Rₚ] p.ResidueField := to_res'.comp ((maximalIdeal (Localization.AtPrime p)) • (⊤ : Submodule Rₚ Nₚ)).mkQ let i : p.ResidueField →ₗ[Rₚ] Mₚ := Submodule.liftQ _ (LinearMap.toSpanSingleton Rₚ Mₚ x) (le_of_eq hx) have inj1 : Function.Injective i := LinearMap.ker_eq_bot.mp (Submodule.ker_liftQ_eq_bot _ _ _ (le_of_eq hx.symm)) let f := i.comp to_res have f_ne0 : f ≠ 0 := by intro eq0 absurd hg apply LinearMap.ext intro np' induction' np' using Submodule.Quotient.induction_on with np change to_res np = 0 apply inj1 change f np = _ simp [eq0] absurd hom0 let _ := Module.finitePresentation_of_finite R N contrapose! f_ne0 exact (Module.FinitePresentation.linearEquivMapExtendScalars p'.asIdeal.primeCompl).symm.map_eq_zero_iff.mp (Subsingleton.eq_zero _) end IsSMulRegular
Bounded.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.Order.Hom.Basic /-! # Bounded order homomorphisms This file defines (bounded) order homomorphisms. We use the `DFunLike` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `TopHom`: Maps which preserve `⊤`. * `BotHom`: Maps which preserve `⊥`. * `BoundedOrderHom`: Bounded order homomorphisms. Monotone maps which preserve `⊤` and `⊥`. ## Typeclasses * `TopHomClass` * `BotHomClass` * `BoundedOrderHomClass` -/ open Function OrderDual variable {F α β γ δ : Type*} /-- The type of `⊤`-preserving functions from `α` to `β`. -/ structure TopHom (α β : Type*) [Top α] [Top β] where /-- The underlying function. The preferred spelling is `DFunLike.coe`. -/ toFun : α → β /-- The function preserves the top element. The preferred spelling is `map_top`. -/ map_top' : toFun ⊤ = ⊤ /-- The type of `⊥`-preserving functions from `α` to `β`. -/ structure BotHom (α β : Type*) [Bot α] [Bot β] where /-- The underlying function. The preferred spelling is `DFunLike.coe`. -/ toFun : α → β /-- The function preserves the bottom element. The preferred spelling is `map_bot`. -/ map_bot' : toFun ⊥ = ⊥ /-- The type of bounded order homomorphisms from `α` to `β`. -/ structure BoundedOrderHom (α β : Type*) [Preorder α] [Preorder β] [BoundedOrder α] [BoundedOrder β] extends OrderHom α β where /-- The function preserves the top element. The preferred spelling is `map_top`. -/ map_top' : toFun ⊤ = ⊤ /-- The function preserves the bottom element. The preferred spelling is `map_bot`. -/ map_bot' : toFun ⊥ = ⊥ section /-- `TopHomClass F α β` states that `F` is a type of `⊤`-preserving morphisms. You should extend this class when you extend `TopHom`. -/ class TopHomClass (F : Type*) (α β : outParam Type*) [Top α] [Top β] [FunLike F α β] : Prop where /-- A `TopHomClass` morphism preserves the top element. -/ map_top (f : F) : f ⊤ = ⊤ /-- `BotHomClass F α β` states that `F` is a type of `⊥`-preserving morphisms. You should extend this class when you extend `BotHom`. -/ class BotHomClass (F : Type*) (α β : outParam Type*) [Bot α] [Bot β] [FunLike F α β] : Prop where /-- A `BotHomClass` morphism preserves the bottom element. -/ map_bot (f : F) : f ⊥ = ⊥ /-- `BoundedOrderHomClass F α β` states that `F` is a type of bounded order morphisms. You should extend this class when you extend `BoundedOrderHom`. -/ class BoundedOrderHomClass (F α β : Type*) [LE α] [LE β] [BoundedOrder α] [BoundedOrder β] [FunLike F α β] : Prop extends RelHomClass F ((· ≤ ·) : α → α → Prop) ((· ≤ ·) : β → β → Prop) where /-- Morphisms preserve the top element. The preferred spelling is `_root_.map_top`. -/ map_top (f : F) : f ⊤ = ⊤ /-- Morphisms preserve the bottom element. The preferred spelling is `_root_.map_bot`. -/ map_bot (f : F) : f ⊥ = ⊥ end export TopHomClass (map_top) export BotHomClass (map_bot) attribute [simp] map_top map_bot section Hom variable [FunLike F α β] -- See note [lower instance priority] instance (priority := 100) BoundedOrderHomClass.toTopHomClass [LE α] [LE β] [BoundedOrder α] [BoundedOrder β] [BoundedOrderHomClass F α β] : TopHomClass F α β := { ‹BoundedOrderHomClass F α β› with } -- See note [lower instance priority] instance (priority := 100) BoundedOrderHomClass.toBotHomClass [LE α] [LE β] [BoundedOrder α] [BoundedOrder β] [BoundedOrderHomClass F α β] : BotHomClass F α β := { ‹BoundedOrderHomClass F α β› with } end Hom section Equiv variable [EquivLike F α β] -- See note [lower instance priority] instance (priority := 100) OrderIsoClass.toTopHomClass [LE α] [OrderTop α] [PartialOrder β] [OrderTop β] [OrderIsoClass F α β] : TopHomClass F α β := { show OrderHomClass F α β from inferInstance with map_top := fun f => top_le_iff.1 <| (map_inv_le_iff f).1 le_top } -- See note [lower instance priority] instance (priority := 100) OrderIsoClass.toBotHomClass [LE α] [OrderBot α] [PartialOrder β] [OrderBot β] [OrderIsoClass F α β] : BotHomClass F α β := { map_bot := fun f => le_bot_iff.1 <| (le_map_inv_iff f).1 bot_le } -- See note [lower instance priority] instance (priority := 100) OrderIsoClass.toBoundedOrderHomClass [LE α] [BoundedOrder α] [PartialOrder β] [BoundedOrder β] [OrderIsoClass F α β] : BoundedOrderHomClass F α β := { show OrderHomClass F α β from inferInstance, OrderIsoClass.toTopHomClass, OrderIsoClass.toBotHomClass with } @[simp] theorem map_eq_top_iff [LE α] [OrderTop α] [PartialOrder β] [OrderTop β] [OrderIsoClass F α β] (f : F) {a : α} : f a = ⊤ ↔ a = ⊤ := by rw [← map_top f, (EquivLike.injective f).eq_iff] @[simp] theorem map_eq_bot_iff [LE α] [OrderBot α] [PartialOrder β] [OrderBot β] [OrderIsoClass F α β] (f : F) {a : α} : f a = ⊥ ↔ a = ⊥ := by rw [← map_bot f, (EquivLike.injective f).eq_iff] end Equiv variable [FunLike F α β] /-- Turn an element of a type `F` satisfying `TopHomClass F α β` into an actual `TopHom`. This is declared as the default coercion from `F` to `TopHom α β`. -/ @[coe] def TopHomClass.toTopHom [Top α] [Top β] [TopHomClass F α β] (f : F) : TopHom α β := ⟨f, map_top f⟩ instance [Top α] [Top β] [TopHomClass F α β] : CoeTC F (TopHom α β) := ⟨TopHomClass.toTopHom⟩ /-- Turn an element of a type `F` satisfying `BotHomClass F α β` into an actual `BotHom`. This is declared as the default coercion from `F` to `BotHom α β`. -/ @[coe] def BotHomClass.toBotHom [Bot α] [Bot β] [BotHomClass F α β] (f : F) : BotHom α β := ⟨f, map_bot f⟩ instance [Bot α] [Bot β] [BotHomClass F α β] : CoeTC F (BotHom α β) := ⟨BotHomClass.toBotHom⟩ /-- Turn an element of a type `F` satisfying `BoundedOrderHomClass F α β` into an actual `BoundedOrderHom`. This is declared as the default coercion from `F` to `BoundedOrderHom α β`. -/ @[coe] def BoundedOrderHomClass.toBoundedOrderHom [Preorder α] [Preorder β] [BoundedOrder α] [BoundedOrder β] [BoundedOrderHomClass F α β] (f : F) : BoundedOrderHom α β := { (f : α →o β) with toFun := f, map_top' := map_top f, map_bot' := map_bot f } instance [Preorder α] [Preorder β] [BoundedOrder α] [BoundedOrder β] [BoundedOrderHomClass F α β] : CoeTC F (BoundedOrderHom α β) := ⟨BoundedOrderHomClass.toBoundedOrderHom⟩ /-! ### Top homomorphisms -/ namespace TopHom variable [Top α] section Top variable [Top β] [Top γ] [Top δ] instance : FunLike (TopHom α β) α β where coe := TopHom.toFun coe_injective' f g h := by cases f; cases g; congr instance : TopHomClass (TopHom α β) α β where map_top := TopHom.map_top' -- this must come after the coe_to_fun definition initialize_simps_projections TopHom (toFun → apply) @[ext] theorem ext {f g : TopHom α β} (h : ∀ a, f a = g a) : f = g := DFunLike.ext f g h /-- Copy of a `TopHom` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : TopHom α β) (f' : α → β) (h : f' = f) : TopHom α β where toFun := f' map_top' := h.symm ▸ f.map_top' @[simp] theorem coe_copy (f : TopHom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl theorem copy_eq (f : TopHom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := DFunLike.ext' h instance : Inhabited (TopHom α β) := ⟨⟨fun _ => ⊤, rfl⟩⟩ variable (α) /-- `id` as a `TopHom`. -/ protected def id : TopHom α α := ⟨id, rfl⟩ @[simp, norm_cast] theorem coe_id : ⇑(TopHom.id α) = id := rfl variable {α} @[simp] theorem id_apply (a : α) : TopHom.id α a = a := rfl /-- Composition of `TopHom`s as a `TopHom`. -/ def comp (f : TopHom β γ) (g : TopHom α β) : TopHom α γ where toFun := f ∘ g map_top' := by rw [comp_apply, map_top, map_top] @[simp] theorem coe_comp (f : TopHom β γ) (g : TopHom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] theorem comp_apply (f : TopHom β γ) (g : TopHom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] theorem comp_assoc (f : TopHom γ δ) (g : TopHom β γ) (h : TopHom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] theorem comp_id (f : TopHom α β) : f.comp (TopHom.id α) = f := TopHom.ext fun _ => rfl @[simp] theorem id_comp (f : TopHom α β) : (TopHom.id β).comp f = f := TopHom.ext fun _ => rfl @[simp] theorem cancel_right {g₁ g₂ : TopHom β γ} {f : TopHom α β} (hf : Surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨fun h => TopHom.ext <| hf.forall.2 <| DFunLike.ext_iff.1 h, congr_arg (fun g => comp g f)⟩ @[simp] theorem cancel_left {g : TopHom β γ} {f₁ f₂ : TopHom α β} (hg : Injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨fun h => TopHom.ext fun a => hg <| by rw [← TopHom.comp_apply, h, TopHom.comp_apply], congr_arg _⟩ end Top instance instLE [LE β] [Top β] : LE (TopHom α β) where le f g := (f : α → β) ≤ g instance [Preorder β] [Top β] : Preorder (TopHom α β) := Preorder.lift (DFunLike.coe : TopHom α β → α → β) instance [PartialOrder β] [Top β] : PartialOrder (TopHom α β) := PartialOrder.lift _ DFunLike.coe_injective section OrderTop variable [LE β] [OrderTop β] instance : OrderTop (TopHom α β) where top := ⟨⊤, rfl⟩ le_top := fun _ => @le_top (α → β) _ _ _ @[simp] theorem coe_top : ⇑(⊤ : TopHom α β) = ⊤ := rfl @[simp] theorem top_apply (a : α) : (⊤ : TopHom α β) a = ⊤ := rfl end OrderTop section SemilatticeInf variable [SemilatticeInf β] [OrderTop β] (f g : TopHom α β) instance : Min (TopHom α β) := ⟨fun f g => ⟨f ⊓ g, by rw [Pi.inf_apply, map_top, map_top, inf_top_eq]⟩⟩ instance : SemilatticeInf (TopHom α β) := (DFunLike.coe_injective.semilatticeInf _) fun _ _ => rfl @[simp] theorem coe_inf : ⇑(f ⊓ g) = ⇑f ⊓ ⇑g := rfl @[simp] theorem inf_apply (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl end SemilatticeInf section SemilatticeSup variable [SemilatticeSup β] [OrderTop β] (f g : TopHom α β) instance : Max (TopHom α β) := ⟨fun f g => ⟨f ⊔ g, by rw [Pi.sup_apply, map_top, map_top, sup_top_eq]⟩⟩ instance : SemilatticeSup (TopHom α β) := (DFunLike.coe_injective.semilatticeSup _) fun _ _ => rfl @[simp] theorem coe_sup : ⇑(f ⊔ g) = ⇑f ⊔ ⇑g := rfl @[simp] theorem sup_apply (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl end SemilatticeSup instance [Lattice β] [OrderTop β] : Lattice (TopHom α β) := DFunLike.coe_injective.lattice _ (fun _ _ => rfl) fun _ _ => rfl instance [DistribLattice β] [OrderTop β] : DistribLattice (TopHom α β) := DFunLike.coe_injective.distribLattice _ (fun _ _ => rfl) fun _ _ => rfl end TopHom /-! ### Bot homomorphisms -/ namespace BotHom variable [Bot α] section Bot variable [Bot β] [Bot γ] [Bot δ] instance : FunLike (BotHom α β) α β where coe := BotHom.toFun coe_injective' f g h := by cases f; cases g; congr instance : BotHomClass (BotHom α β) α β where map_bot := BotHom.map_bot' -- this must come after the coe_to_fun definition initialize_simps_projections BotHom (toFun → apply) @[ext] theorem ext {f g : BotHom α β} (h : ∀ a, f a = g a) : f = g := DFunLike.ext f g h /-- Copy of a `BotHom` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : BotHom α β) (f' : α → β) (h : f' = f) : BotHom α β where toFun := f' map_bot' := h.symm ▸ f.map_bot' @[simp] theorem coe_copy (f : BotHom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl theorem copy_eq (f : BotHom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := DFunLike.ext' h instance : Inhabited (BotHom α β) := ⟨⟨fun _ => ⊥, rfl⟩⟩ variable (α) /-- `id` as a `BotHom`. -/ protected def id : BotHom α α := ⟨id, rfl⟩ @[simp, norm_cast] theorem coe_id : ⇑(BotHom.id α) = id := rfl variable {α} @[simp] theorem id_apply (a : α) : BotHom.id α a = a := rfl /-- Composition of `BotHom`s as a `BotHom`. -/ def comp (f : BotHom β γ) (g : BotHom α β) : BotHom α γ where toFun := f ∘ g map_bot' := by rw [comp_apply, map_bot, map_bot] @[simp] theorem coe_comp (f : BotHom β γ) (g : BotHom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] theorem comp_apply (f : BotHom β γ) (g : BotHom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] theorem comp_assoc (f : BotHom γ δ) (g : BotHom β γ) (h : BotHom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] theorem comp_id (f : BotHom α β) : f.comp (BotHom.id α) = f := BotHom.ext fun _ => rfl @[simp] theorem id_comp (f : BotHom α β) : (BotHom.id β).comp f = f := BotHom.ext fun _ => rfl @[simp] theorem cancel_right {g₁ g₂ : BotHom β γ} {f : BotHom α β} (hf : Surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨fun h => BotHom.ext <| hf.forall.2 <| DFunLike.ext_iff.1 h, congr_arg (comp · f)⟩ @[simp] theorem cancel_left {g : BotHom β γ} {f₁ f₂ : BotHom α β} (hg : Injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨fun h => BotHom.ext fun a => hg <| by rw [← BotHom.comp_apply, h, BotHom.comp_apply], congr_arg _⟩ end Bot instance instLE [LE β] [Bot β] : LE (BotHom α β) where le f g := (f : α → β) ≤ g instance [Preorder β] [Bot β] : Preorder (BotHom α β) := Preorder.lift (DFunLike.coe : BotHom α β → α → β) instance [PartialOrder β] [Bot β] : PartialOrder (BotHom α β) := PartialOrder.lift _ DFunLike.coe_injective section OrderBot variable [LE β] [OrderBot β] instance : OrderBot (BotHom α β) where bot := ⟨⊥, rfl⟩ bot_le := fun _ => @bot_le (α → β) _ _ _ @[simp] theorem coe_bot : ⇑(⊥ : BotHom α β) = ⊥ := rfl @[simp] theorem bot_apply (a : α) : (⊥ : BotHom α β) a = ⊥ := rfl end OrderBot section SemilatticeInf variable [SemilatticeInf β] [OrderBot β] (f g : BotHom α β) instance : Min (BotHom α β) := ⟨fun f g => ⟨f ⊓ g, by rw [Pi.inf_apply, map_bot, map_bot, inf_bot_eq]⟩⟩ instance : SemilatticeInf (BotHom α β) := (DFunLike.coe_injective.semilatticeInf _) fun _ _ => rfl @[simp] theorem coe_inf : ⇑(f ⊓ g) = ⇑f ⊓ ⇑g := rfl @[simp] theorem inf_apply (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl end SemilatticeInf section SemilatticeSup variable [SemilatticeSup β] [OrderBot β] (f g : BotHom α β) instance : Max (BotHom α β) := ⟨fun f g => ⟨f ⊔ g, by rw [Pi.sup_apply, map_bot, map_bot, sup_bot_eq]⟩⟩ instance : SemilatticeSup (BotHom α β) := (DFunLike.coe_injective.semilatticeSup _) fun _ _ => rfl @[simp] theorem coe_sup : ⇑(f ⊔ g) = ⇑f ⊔ ⇑g := rfl @[simp] theorem sup_apply (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl end SemilatticeSup instance [Lattice β] [OrderBot β] : Lattice (BotHom α β) := DFunLike.coe_injective.lattice _ (fun _ _ => rfl) fun _ _ => rfl instance [DistribLattice β] [OrderBot β] : DistribLattice (BotHom α β) := DFunLike.coe_injective.distribLattice _ (fun _ _ => rfl) fun _ _ => rfl end BotHom /-! ### Bounded order homomorphisms -/ -- TODO: remove this configuration and use the default configuration. initialize_simps_projections BoundedOrderHom (+toOrderHom, -toFun) namespace BoundedOrderHom variable [Preorder α] [Preorder β] [Preorder γ] [Preorder δ] [BoundedOrder α] [BoundedOrder β] [BoundedOrder γ] [BoundedOrder δ] /-- Reinterpret a `BoundedOrderHom` as a `TopHom`. -/ def toTopHom (f : BoundedOrderHom α β) : TopHom α β := { f with } /-- Reinterpret a `BoundedOrderHom` as a `BotHom`. -/ def toBotHom (f : BoundedOrderHom α β) : BotHom α β := { f with } instance : FunLike (BoundedOrderHom α β) α β where coe f := f.toFun coe_injective' f g h := by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr instance : BoundedOrderHomClass (BoundedOrderHom α β) α β where map_rel f := @(f.monotone') map_top f := f.map_top' map_bot f := f.map_bot' @[ext] theorem ext {f g : BoundedOrderHom α β} (h : ∀ a, f a = g a) : f = g := DFunLike.ext f g h /-- Copy of a `BoundedOrderHom` with a new `toFun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : BoundedOrderHom α β) (f' : α → β) (h : f' = f) : BoundedOrderHom α β := { f.toOrderHom.copy f' h, f.toTopHom.copy f' h, f.toBotHom.copy f' h with } @[simp] theorem coe_copy (f : BoundedOrderHom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl theorem copy_eq (f : BoundedOrderHom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := DFunLike.ext' h variable (α) /-- `id` as a `BoundedOrderHom`. -/ protected def id : BoundedOrderHom α α := { OrderHom.id, TopHom.id α, BotHom.id α with } instance : Inhabited (BoundedOrderHom α α) := ⟨BoundedOrderHom.id α⟩ @[simp, norm_cast] theorem coe_id : ⇑(BoundedOrderHom.id α) = id := rfl variable {α} @[simp] theorem id_apply (a : α) : BoundedOrderHom.id α a = a := rfl /-- Composition of `BoundedOrderHom`s as a `BoundedOrderHom`. -/ def comp (f : BoundedOrderHom β γ) (g : BoundedOrderHom α β) : BoundedOrderHom α γ := { f.toOrderHom.comp g.toOrderHom, f.toTopHom.comp g.toTopHom, f.toBotHom.comp g.toBotHom with } @[simp] theorem coe_comp (f : BoundedOrderHom β γ) (g : BoundedOrderHom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] theorem comp_apply (f : BoundedOrderHom β γ) (g : BoundedOrderHom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] theorem coe_comp_orderHom (f : BoundedOrderHom β γ) (g : BoundedOrderHom α β) : (f.comp g : OrderHom α γ) = (f : OrderHom β γ).comp g := rfl @[simp] theorem coe_comp_topHom (f : BoundedOrderHom β γ) (g : BoundedOrderHom α β) : (f.comp g : TopHom α γ) = (f : TopHom β γ).comp g := rfl @[simp] theorem coe_comp_botHom (f : BoundedOrderHom β γ) (g : BoundedOrderHom α β) : (f.comp g : BotHom α γ) = (f : BotHom β γ).comp g := rfl @[simp] theorem comp_assoc (f : BoundedOrderHom γ δ) (g : BoundedOrderHom β γ) (h : BoundedOrderHom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] theorem comp_id (f : BoundedOrderHom α β) : f.comp (BoundedOrderHom.id α) = f := BoundedOrderHom.ext fun _ => rfl @[simp] theorem id_comp (f : BoundedOrderHom α β) : (BoundedOrderHom.id β).comp f = f := BoundedOrderHom.ext fun _ => rfl @[simp] theorem cancel_right {g₁ g₂ : BoundedOrderHom β γ} {f : BoundedOrderHom α β} (hf : Surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨fun h => BoundedOrderHom.ext <| hf.forall.2 <| DFunLike.ext_iff.1 h, congr_arg (fun g => comp g f)⟩ @[simp] theorem cancel_left {g : BoundedOrderHom β γ} {f₁ f₂ : BoundedOrderHom α β} (hg : Injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨fun h => BoundedOrderHom.ext fun a => hg <| by rw [← BoundedOrderHom.comp_apply, h, BoundedOrderHom.comp_apply], congr_arg _⟩ end BoundedOrderHom /-! ### Dual homs -/ namespace TopHom variable [LE α] [OrderTop α] [LE β] [OrderTop β] [LE γ] [OrderTop γ] /-- Reinterpret a top homomorphism as a bot homomorphism between the dual lattices. -/ @[simps] protected def dual : TopHom α β ≃ BotHom αᵒᵈ βᵒᵈ where toFun f := ⟨f, f.map_top'⟩ invFun f := ⟨f, f.map_bot'⟩ @[simp] theorem dual_id : TopHom.dual (TopHom.id α) = BotHom.id _ := rfl @[simp] theorem dual_comp (g : TopHom β γ) (f : TopHom α β) : TopHom.dual (g.comp f) = g.dual.comp (TopHom.dual f) := rfl @[simp] theorem symm_dual_id : TopHom.dual.symm (BotHom.id _) = TopHom.id α := rfl @[simp] theorem symm_dual_comp (g : BotHom βᵒᵈ γᵒᵈ) (f : BotHom αᵒᵈ βᵒᵈ) : TopHom.dual.symm (g.comp f) = (TopHom.dual.symm g).comp (TopHom.dual.symm f) := rfl end TopHom namespace BotHom variable [LE α] [OrderBot α] [LE β] [OrderBot β] [LE γ] [OrderBot γ] /-- Reinterpret a bot homomorphism as a top homomorphism between the dual lattices. -/ @[simps] protected def dual : BotHom α β ≃ TopHom αᵒᵈ βᵒᵈ where toFun f := ⟨f, f.map_bot'⟩ invFun f := ⟨f, f.map_top'⟩ @[simp] theorem dual_id : BotHom.dual (BotHom.id α) = TopHom.id _ := rfl @[simp] theorem dual_comp (g : BotHom β γ) (f : BotHom α β) : BotHom.dual (g.comp f) = g.dual.comp (BotHom.dual f) := rfl @[simp] theorem symm_dual_id : BotHom.dual.symm (TopHom.id _) = BotHom.id α := rfl @[simp] theorem symm_dual_comp (g : TopHom βᵒᵈ γᵒᵈ) (f : TopHom αᵒᵈ βᵒᵈ) : BotHom.dual.symm (g.comp f) = (BotHom.dual.symm g).comp (BotHom.dual.symm f) := rfl end BotHom namespace BoundedOrderHom variable [Preorder α] [BoundedOrder α] [Preorder β] [BoundedOrder β] [Preorder γ] [BoundedOrder γ] /-- Reinterpret a bounded order homomorphism as a bounded order homomorphism between the dual orders. -/ @[simps] protected def dual : BoundedOrderHom α β ≃ BoundedOrderHom αᵒᵈ βᵒᵈ where toFun f := ⟨f.toOrderHom.dual, f.map_bot', f.map_top'⟩ invFun f := ⟨OrderHom.dual.symm f.toOrderHom, f.map_bot', f.map_top'⟩ @[simp] theorem dual_id : (BoundedOrderHom.id α).dual = BoundedOrderHom.id _ := rfl @[simp] theorem dual_comp (g : BoundedOrderHom β γ) (f : BoundedOrderHom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] theorem symm_dual_id : BoundedOrderHom.dual.symm (BoundedOrderHom.id _) = BoundedOrderHom.id α := rfl @[simp] theorem symm_dual_comp (g : BoundedOrderHom βᵒᵈ γᵒᵈ) (f : BoundedOrderHom αᵒᵈ βᵒᵈ) : BoundedOrderHom.dual.symm (g.comp f) = (BoundedOrderHom.dual.symm g).comp (BoundedOrderHom.dual.symm f) := rfl end BoundedOrderHom
eqtype.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. (******************************************************************************) (* Types with a decidable equality *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines two "base" combinatorial structures: *) (* eqType == types with a decidable equality *) (* The HB class is called Equality. *) (* The equality operation on an eqType is proof-irrelevant *) (* (lemma eq_irrelevance). *) (* The main notation is the boolean equality "==", see below. *) (* subType P == types isomorphic to {x : T | P x} *) (* with P : pred T for some type T *) (* The HB class is called SubType. *) (* subEqType P == join of eqType and subType P *) (* The HB class is called SubEquality. *) (* *) (* The eqType interface supports the following operations (in bool_scope): *) (* x == y <=> x compares equal to y (this is a boolean test) *) (* x == y :> T <=> x == y at type T *) (* x != y <=> x and y compare unequal *) (* x != y :> T <=> x and y compare unequal at type T *) (* x =P y :: a proof of reflect (x = y) (x == y); x =P y coerces *) (* to x == y -> x = y *) (* eqbLHS := (X in (X == _))%pattern (for rewriting) *) (* eqbRHS := (X in (_ == X))%pattern (for rewriting) *) (* eq_op == the boolean relation behind the == notation *) (* (see lemma eqE below for generic folding *) (* of equality predicates) *) (* eqP == proof of Equality.axiom eq_op behind the =P notation*) (* Equality.axiom e <-> e : rel T is a valid comparison decision procedure *) (* for type T: reflect (x = y) (e x y) for all x y : T *) (* pred1 a == the singleton predicate [pred x | x == a] *) (* pred2, pred3, pred4 == pair, triple, quad predicates *) (* predC1 a == [pred x | x != a] *) (* [predU1 a & A] == [pred x | (x == a) || (x \in A)] *) (* [predD1 A & a] == [pred x | x != a & x \in A] *) (* predU1 a P, predD1 P a == applicative versions of the above *) (* frel f == the relation associated with f : T -> T *) (* := [rel x y | f x == y] *) (* invariant f k == elements of T whose k-class is f-invariant *) (* := [pred x | k (f x) == k x] with f : T -> T *) (* [fun x : T => e0 with a1 |-> e1, .., a_n |-> e_n] *) (* [eta f with a1 |-> e1, .., a_n |-> e_n] == *) (* the auto-expanding function that maps x = a_i to e_i, and other values *) (* of x to e0 (resp. f x). In the first form the `: T' is optional and x *) (* can occur in a_i or e_i *) (* dfwith f x == fun j => x if j = i, and f j otherwise, given *) (* f : forall k, T k and x : T i *) (* We also define: *) (* tagged_as u v == v cast as T_(tag u) if tag v == tag u, else u *) (* so that u == v <=> (tag u == tag v) && (tagged u == tagged_as u v *) (* etagged i u (p : tag u = i) == (tagged u) cast as T_ i *) (* untag idx i (F : T_ i -> _) u == F (etagged i u _) if tag u = i, else idx *) (* tagged_with i == [pred j | tag j == i], this pred {x : I & T_ x} is useful *) (* to define the sigma type {x in tagged_with i} and the mutual bijections: *) (* tag_with i : T_ i -> {x in tagged_with i} *) (* untag_with i : {x in tagged_with i} -> T_ i *) (* *) (* The subType interface supports the following operations: *) (* \val == the generic injection from a subType S of T into T *) (* For example, if u : {x : T | P}, then val u : T *) (* val is injective because P is proof-irrelevant (P is in bool, *) (* and the is_true coercion expands to P = true). *) (* valP == the generic proof of P (val u) for u : subType P *) (* Sub x Px == The generic constructor for a subType P; Px is a proof of P x *) (* and P should be inferred from the expected return type. *) (* insub x == the generic partial projection of T into a subType S of T *) (* This returns an option S; if S : subType P then *) (* insub x = Some u with val u = x if P x, *) (* None if ~~ P x *) (* The insubP lemma encapsulates this dichotomy. *) (* P should be inferred from the expected return type. *) (* innew x == total (non-option) variant of insub when P = predT *) (* {? x | P} == option {x | P} (syntax for casting insub x) *) (* insubd u0 x == the generic projection with default value u0 *) (* := odflt u0 (insub x) *) (* insigd A0 x == special case of insubd for S == {x | x \in A}, where A0 is *) (* a proof of x0 \in A *) (* insub_eq x == transparent version of insub x that expands to Some/None *) (* when P x can evaluate *) (* *) (* * Sub *) (* ** Specific notations *) (* [isSub of S for S_val] == subtype for S where S_val : S -> T is the *) (* first projection of a type S isomorphic to {x : T | P}; if S_val is *) (* specified, then it replaces the inferred projector. *) (* [isSub for S_val] := [isSub of _ for S_val] *) (* It clones the canonical subType structure for S. *) (* [isNew of S for S_val] == subtype for S where S_val : S -> T is the *) (* projection of a type S isomorphic to T; in this case P must be predT *) (* [isNew for S_val] := [isNew of _ for S_val] *) (* [isSub for S_val by Srect], [isNew for S_val by Srect] == *) (* variants of the above where the eliminator is explicitly provided. *) (* Here S no longer needs to be syntactically identical to {x | P x} or *) (* wrapped T, but it must have a derived constructor S_Sub satisfying an *) (* eliminator Srect identical to the one the Coq Inductive command would *) (* have generated, and S_val (S_Sub x Px) (resp. S_val (S_sub x) for the *) (* newType form) must be convertible to x. *) (* variant of the above when S is a wrapper type for T (so P = predT). *) (* Subtypes inherit the eqType structure of their base types; the generic *) (* structure should be explicitly instantiated using the *) (* [Equality of S by <:] *) (* construct; this pattern is repeated for all the combinatorial interfaces *) (* (Choice, Countable, Finite). *) (* *) (* List of factories with a dedicated alias (not generated automatically): *) (* inj_type injf == alias of T to copy an interface from another T' already *) (* equipped with it and injf : injective f with f : T -> T'*) (* pcan_type fK == alias of T to similarly derive an interface from f and *) (* a left inverse partial function g and fK : pcancel f g *) (* can_type fK == alias of T to similarly derive an interface from f and *) (* a left inverse function g and fK : cancel f g *) (* sub_type sT == alias of sT : subType _ *) (* *) (* comparable T <-> equality on T is decidable. *) (* := forall x y : T, decidable (x = y) *) (* comparableMixin compT == equality mixin for compT : comparable T *) (* *) (* The eqType interface is implemented for most standard datatypes: *) (* bool, unit, void, option, prod (denoted A * B), sum (denoted A + B), *) (* sig (denoted {x | P}), sigT (denoted {i : I & T}). *) (* *) (* We add the following to the standard suffixes documented in ssrbool.v: *) (* 1, 2, 3, 4 -- explicit enumeration predicate for 1 (singleton), 2, 3, or *) (* 4 values *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope eq_scope. Declare Scope fun_delta_scope. Definition eq_axiom T (e : rel T) := forall x y, reflect (x = y) (e x y). HB.mixin Record hasDecEq T := { eq_op : rel T; eqP : eq_axiom eq_op }. #[mathcomp(axiom="eq_axiom"), short(type="eqType")] HB.structure Definition Equality := { T of hasDecEq T }. (* eqE is a generic lemma that can be used to fold back recursive comparisons *) (* after using partial evaluation to simplify comparisons on concrete *) (* instances. The eqE lemma can be used e.g. like so: rewrite !eqE /= -!eqE. *) (* For instance, with the above rewrite, n.+1 == n.+1 gets simplified to *) (* n == n. For this to work, we need to declare equality _mixins_ *) (* as canonical. Canonical declarations remove the need for specific *) (* inverses to eqE (like eqbE, eqnE, eqseqE, etc.) for new recursive *) (* comparisons, but can only be used for manifest mixing with a bespoke *) (* comparison function, and so is incompatible with PcanEqMixin and the like *) (* - this is why the tree_hasDecEq for GenTree.tree in library choice is not *) (* declared Canonical. *) Lemma eqE (T : eqType) x : eq_op x = hasDecEq.eq_op (Equality.class T) x. Proof. by []. Qed. Arguments eqP {T x y} : rename. Delimit Scope eq_scope with EQ. Open Scope eq_scope. Notation "x == y" := (eq_op x y) (no associativity) : bool_scope. Notation "x == y :> T" := ((x : T) == (y : T)) : bool_scope. Notation "x != y" := (~~ (x == y)) (no associativity) : bool_scope. Notation "x != y :> T" := (~~ (x == y :> T)) : bool_scope. Notation "x =P y" := (eqP : reflect (x = y) (x == y)) (at level 70, no associativity) : eq_scope. Notation "x =P y :> T" := (eqP : reflect (x = y :> T) (x == y :> T)) (no associativity) : eq_scope. Notation eqbLHS := (X in (X == _))%pattern. Notation eqbRHS := (X in (_ == X))%pattern. Lemma eq_refl (T : eqType) (x : T) : x == x. Proof. exact/eqP. Qed. Notation eqxx := eq_refl. Lemma eq_sym (T : eqType) (x y : T) : (x == y) = (y == x). Proof. exact/eqP/eqP. Qed. #[global] Hint Resolve eq_refl eq_sym : core. Variant eq_xor_neq (T : eqType) (x y : T) : bool -> bool -> Set := | EqNotNeq of x = y : eq_xor_neq x y true true | NeqNotEq of x != y : eq_xor_neq x y false false. Lemma eqVneq (T : eqType) (x y : T) : eq_xor_neq x y (y == x) (x == y). Proof. by rewrite eq_sym; case: (altP eqP); constructor. Qed. Arguments eqVneq {T} x y, {T x y}. Section Contrapositives. Variables (T1 T2 : eqType). Implicit Types (A : pred T1) (b : bool) (P : Prop) (x : T1) (z : T2). Lemma contraTeq b x y : (x != y -> ~~ b) -> b -> x = y. Proof. by move=> imp hyp; apply/eqP; apply: contraTT hyp. Qed. Lemma contraNeq b x y : (x != y -> b) -> ~~ b -> x = y. Proof. by move=> imp hyp; apply/eqP; apply: contraNT hyp. Qed. Lemma contraFeq b x y : (x != y -> b) -> b = false -> x = y. Proof. by move=> imp /negbT; apply: contraNeq. Qed. Lemma contraPeq P x y : (x != y -> ~ P) -> P -> x = y. Proof. by move=> imp HP; apply: contraTeq isT => /imp /(_ HP). Qed. Lemma contra_not_eq P x y : (x != y -> P) -> ~ P -> x = y. Proof. by move=> imp; apply: contraPeq => /imp HP /(_ HP). Qed. Lemma contra_not_neq P x y : (x = y -> P) -> ~ P -> x != y. Proof. by move=> imp; apply: contra_notN => /eqP. Qed. Lemma contraTneq b x y : (x = y -> ~~ b) -> b -> x != y. Proof. by move=> imp; apply: contraTN => /eqP. Qed. Lemma contraNneq b x y : (x = y -> b) -> ~~ b -> x != y. Proof. by move=> imp; apply: contraNN => /eqP. Qed. Lemma contraFneq b x y : (x = y -> b) -> b = false -> x != y. Proof. by move=> imp /negbT; apply: contraNneq. Qed. Lemma contraPneq P x y : (x = y -> ~ P) -> P -> x != y. Proof. by move=> imp; apply: contraPN => /eqP. Qed. Lemma contra_eqN b x y : (b -> x != y) -> x = y -> ~~ b. Proof. by move=> imp /eqP; apply: contraL. Qed. Lemma contra_eqF b x y : (b -> x != y) -> x = y -> b = false. Proof. by move=> imp /eqP; apply: contraTF. Qed. Lemma contra_eqT b x y : (~~ b -> x != y) -> x = y -> b. Proof. by move=> imp /eqP; apply: contraLR. Qed. Lemma contra_neqN b x y : (b -> x = y) -> x != y -> ~~ b. Proof. by move=> imp; apply: contraNN => /imp->. Qed. Lemma contra_neqF b x y : (b -> x = y) -> x != y -> b = false. Proof. by move=> imp; apply: contraNF => /imp->. Qed. Lemma contra_neqT b x y : (~~ b -> x = y) -> x != y -> b. Proof. by move=> imp; apply: contraNT => /imp->. Qed. Lemma contra_eq_not P x y : (P -> x != y) -> x = y -> ~ P. Proof. by move=> imp /eqP; apply: contraTnot. Qed. Lemma contra_neq_not P x y : (P -> x = y) -> x != y -> ~ P. Proof. by move=> imp;apply: contraNnot => /imp->. Qed. Lemma contra_eq z1 z2 x1 x2 : (x1 != x2 -> z1 != z2) -> z1 = z2 -> x1 = x2. Proof. by move=> imp /eqP; apply: contraTeq. Qed. Lemma contra_neq z1 z2 x1 x2 : (x1 = x2 -> z1 = z2) -> z1 != z2 -> x1 != x2. Proof. by move=> imp; apply: contraNneq => /imp->. Qed. Lemma contra_neq_eq z1 z2 x1 x2 : (x1 != x2 -> z1 = z2) -> z1 != z2 -> x1 = x2. Proof. by move=> imp; apply: contraNeq => /imp->. Qed. Lemma contra_eq_neq z1 z2 x1 x2 : (z1 = z2 -> x1 != x2) -> x1 = x2 -> z1 != z2. Proof. by move=> imp; apply: contra_eqN => /eqP /imp. Qed. Lemma memPn A x : reflect {in A, forall y, y != x} (x \notin A). Proof. apply: (iffP idP) => [notDx y | notDx]; first by apply: contraTneq => ->. exact: contraL (notDx x) _. Qed. Lemma memPnC A x : reflect {in A, forall y, x != y} (x \notin A). Proof. by apply: (iffP (memPn A x)) => A'x y /A'x; rewrite eq_sym. Qed. Lemma ifN_eq R x y vT vF : x != y -> (if x == y then vT else vF) = vF :> R. Proof. exact: ifN. Qed. Lemma ifN_eqC R x y vT vF : x != y -> (if y == x then vT else vF) = vF :> R. Proof. by rewrite eq_sym; apply: ifN. Qed. End Contrapositives. Arguments memPn {T1 A x}. Arguments memPnC {T1 A x}. Theorem eq_irrelevance (T : eqType) x y : forall e1 e2 : x = y :> T, e1 = e2. Proof. pose proj z e := if x =P z is ReflectT e0 then e0 else e. suff: injective (proj y) by rewrite /proj => injp e e'; apply: injp; case: eqP. pose join (e : x = _) := etrans (esym e). apply: can_inj (join x y (proj x (erefl x))) _. by case: y /; case: _ / (proj x _). Qed. Corollary eq_axiomK (T : eqType) (x : T) : all_equal_to (erefl x). Proof. by move=> eq_x_x; apply: eq_irrelevance. Qed. (* We use the module system to circumvent a silly limitation that *) (* forbids using the same constant to coerce to different targets. *) Module Type EqTypePredSig. Parameter sort : eqType -> predArgType. End EqTypePredSig. Module MakeEqTypePred (eqmod : EqTypePredSig). Coercion eqmod.sort : eqType >-> predArgType. End MakeEqTypePred. Module Export EqTypePred := MakeEqTypePred eqtype.Equality. Lemma unit_eqP : Equality.axiom (fun _ _ : unit => true). Proof. by do 2!case; left. Qed. HB.instance Definition _ := hasDecEq.Build unit unit_eqP. (* Comparison for booleans. *) (* This is extensionally equal, but not convertible to Bool.eqb. *) Definition eqb b := addb (~~ b). Lemma eqbP : Equality.axiom eqb. Proof. by do 2!case; constructor. Qed. HB.instance Definition _ := hasDecEq.Build bool eqbP. Lemma eqbE : eqb = eq_op. Proof. by []. Qed. Lemma bool_irrelevance (b : bool) (p1 p2 : b) : p1 = p2. Proof. exact: eq_irrelevance. Qed. Lemma negb_add b1 b2 : ~~ (b1 (+) b2) = (b1 == b2). Proof. by rewrite -addNb. Qed. Lemma negb_eqb b1 b2 : (b1 != b2) = b1 (+) b2. Proof. by rewrite -addNb negbK. Qed. Lemma eqb_id b : (b == true) = b. Proof. by case: b. Qed. Lemma eqbF_neg b : (b == false) = ~~ b. Proof. by case: b. Qed. Lemma eqb_negLR b1 b2 : (~~ b1 == b2) = (b1 == ~~ b2). Proof. by case: b1; case: b2. Qed. (* Equality-based predicates. *) Notation xpred1 := (fun a1 x => x == a1). Notation xpred2 := (fun a1 a2 x => (x == a1) || (x == a2)). Notation xpred3 := (fun a1 a2 a3 x => [|| x == a1, x == a2 | x == a3]). Notation xpred4 := (fun a1 a2 a3 a4 x => [|| x == a1, x == a2, x == a3 | x == a4]). Notation xpredU1 := (fun a1 (p : pred _) x => (x == a1) || p x). Notation xpredC1 := (fun a1 x => x != a1). Notation xpredD1 := (fun (p : pred _) a1 x => (x != a1) && p x). Section EqPred. Variable T : eqType. Definition pred1 (a1 : T) := SimplPred (xpred1 a1). Definition pred2 (a1 a2 : T) := SimplPred (xpred2 a1 a2). Definition pred3 (a1 a2 a3 : T) := SimplPred (xpred3 a1 a2 a3). Definition pred4 (a1 a2 a3 a4 : T) := SimplPred (xpred4 a1 a2 a3 a4). Definition predU1 (a1 : T) p := SimplPred (xpredU1 a1 p). Definition predC1 (a1 : T) := SimplPred (xpredC1 a1). Definition predD1 p (a1 : T) := SimplPred (xpredD1 p a1). Lemma pred1E : pred1 =2 eq_op. Proof. by move=> x y; apply: eq_sym. Qed. Variables (T2 : eqType) (x y : T) (z u : T2) (b : bool). Lemma predU1P : reflect (x = y \/ b) ((x == y) || b). Proof. by apply: (iffP orP); do [case=> [/eqP|]; [left | right]]. Qed. Lemma pred2P : reflect (x = y \/ z = u) ((x == y) || (z == u)). Proof. by apply: (iffP orP); do [case=> /eqP; [left | right]]. Qed. Lemma predD1P : reflect (x <> y /\ b) ((x != y) && b). Proof. by apply: (iffP andP)=> [] [] // /eqP. Qed. Lemma predU1l : x = y -> (x == y) || b. Proof. by move->; rewrite eqxx. Qed. Lemma predU1r : b -> (x == y) || b. Proof. by move->; rewrite orbT. Qed. End EqPred. Arguments predU1P {T x y b}. Arguments pred2P {T T2 x y z u}. Arguments predD1P {T x y b}. Prenex Implicits pred1 pred2 pred3 pred4 predU1 predC1 predD1. Notation "[ 'predU1' x & A ]" := (predU1 x [in A]) (format "[ 'predU1' x & A ]") : function_scope. Notation "[ 'predD1' A & x ]" := (predD1 [in A] x) (format "[ 'predD1' A & x ]") : function_scope. (* Lemmas for reflected equality and functions. *) Section EqFun. Section Exo. Variables (aT rT : eqType) (D : pred aT) (f : aT -> rT) (g : rT -> aT). Lemma inj_eq : injective f -> forall x y, (f x == f y) = (x == y). Proof. by move=> inj_f x y; apply/eqP/eqP=> [|-> //]; apply: inj_f. Qed. Lemma can_eq : cancel f g -> forall x y, (f x == f y) = (x == y). Proof. by move/can_inj; apply: inj_eq. Qed. Lemma bij_eq : bijective f -> forall x y, (f x == f y) = (x == y). Proof. by move/bij_inj; apply: inj_eq. Qed. Lemma can2_eq : cancel f g -> cancel g f -> forall x y, (f x == y) = (x == g y). Proof. by move=> fK gK x y; rewrite -[y in LHS]gK; apply: can_eq. Qed. Lemma inj_in_eq : {in D &, injective f} -> {in D &, forall x y, (f x == f y) = (x == y)}. Proof. by move=> inj_f x y Dx Dy; apply/eqP/eqP=> [|-> //]; apply: inj_f. Qed. Lemma can_in_eq : {in D, cancel f g} -> {in D &, forall x y, (f x == f y) = (x == y)}. Proof. by move/can_in_inj; apply: inj_in_eq. Qed. End Exo. Section Endo. Variable T : eqType. Definition frel f := [rel x y : T | f x == y]. Lemma inv_eq f : involutive f -> forall x y : T, (f x == y) = (x == f y). Proof. by move=> fK; apply: can2_eq. Qed. Lemma eq_frel f f' : f =1 f' -> frel f =2 frel f'. Proof. by move=> eq_f x y; rewrite /= eq_f. Qed. End Endo. Variable aT : Type. (* The invariant of a function f wrt a projection k is the pred of points *) (* that have the same projection as their image. *) Definition invariant (rT : eqType) f (k : aT -> rT) := [pred x | k (f x) == k x]. Variables (rT1 rT2 : eqType) (f : aT -> aT) (h : rT1 -> rT2) (k : aT -> rT1). Lemma invariant_comp : subpred (invariant f k) (invariant f (h \o k)). Proof. by move=> x eq_kfx; rewrite /= (eqP eq_kfx). Qed. Lemma invariant_inj : injective h -> invariant f (h \o k) =1 invariant f k. Proof. by move=> inj_h x; apply: (inj_eq inj_h). Qed. End EqFun. Prenex Implicits frel. (* The coercion to rel must be explicit for derived Notations to unparse. *) Notation coerced_frel f := (rel_of_simpl (frel f)) (only parsing). Section FunWith. Variables (aT : eqType) (rT : Type). Variant fun_delta : Type := FunDelta of aT & rT. Definition fwith x y (f : aT -> rT) := [fun z => if z == x then y else f z]. Definition app_fdelta df f z := let: FunDelta x y := df in if z == x then y else f z. End FunWith. Prenex Implicits fwith. Notation "x |-> y" := (FunDelta x y) (at level 190, no associativity, format "'[hv' x '/ ' |-> y ']'") : fun_delta_scope. Delimit Scope fun_delta_scope with FUN_DELTA. Arguments app_fdelta {aT rT%_type} df%_FUN_DELTA f z. Notation "[ 'fun' z : T => F 'with' d1 , .. , dn ]" := (SimplFunDelta (fun z : T => app_fdelta d1%FUN_DELTA .. (app_fdelta dn%FUN_DELTA (fun _ => F)) ..)) (z name, only parsing) : function_scope. Notation "[ 'fun' z => F 'with' d1 , .. , dn ]" := (SimplFunDelta (fun z => app_fdelta d1%FUN_DELTA .. (app_fdelta dn%FUN_DELTA (fun _ => F)) ..)) (z name, format "'[hv' [ '[' 'fun' z => '/ ' F ']' '/' 'with' '[' d1 , '/' .. , '/' dn ']' ] ']'" ) : function_scope. Notation "[ 'eta' f 'with' d1 , .. , dn ]" := (SimplFunDelta (fun _ => app_fdelta d1%FUN_DELTA .. (app_fdelta dn%FUN_DELTA f) ..)) (format "'[hv' [ '[' 'eta' '/ ' f ']' '/' 'with' '[' d1 , '/' .. , '/' dn ']' ] ']'" ) : function_scope. Section DFunWith. Variables (I : eqType) (T : I -> Type) (f : forall i, T i). Definition dfwith i (x : T i) (j : I) : T j := if (i =P j) is ReflectT ij then ecast j (T j) ij x else f j. Lemma dfwith_in i x : dfwith x i = x. Proof. by rewrite /dfwith; case: eqP => // ii; rewrite eq_axiomK. Qed. Lemma dfwith_out i (x : T i) j : i != j -> dfwith x j = f j. Proof. by rewrite /dfwith; case: eqP. Qed. Variant dfwith_spec i (x : T i) : forall j, T j -> Type:= | DFunWithIn : dfwith_spec x x | DFunWithOut j : i != j -> dfwith_spec x (f j). Lemma dfwithP i (x : T i) (j : I) : dfwith_spec x (dfwith x j). Proof. by case: (eqVneq i j) => [<-|nij]; [rewrite dfwith_in|rewrite dfwith_out//]; constructor. Qed. End DFunWith. Arguments dfwith {I T} f [i] x. (* Various EqType constructions. *) Section ComparableType. Variable T : Type. Definition comparable := forall x y : T, decidable (x = y). Hypothesis compare_T : comparable. Definition compareb x y : bool := compare_T x y. Lemma compareP : Equality.axiom compareb. Proof. by move=> x y; apply: sumboolP. Qed. Definition comparableMixin := hasDecEq.Build T compareP. End ComparableType. Definition eq_comparable (T : eqType) : comparable T := fun x y => decP (x =P y). #[key="sub_sort"] HB.mixin Record isSub (T : Type) (P : pred T) (sub_sort : Type) := { val_subdef : sub_sort -> T; Sub : forall x, P x -> sub_sort; Sub_rect : forall K (_ : forall x Px, K (@Sub x Px)) u, K u; SubK_subproof : forall x Px, val_subdef (@Sub x Px) = x }. #[short(type="subType")] HB.structure Definition SubType (T : Type) (P : pred T) := { S of isSub T P S }. Notation val := (isSub.val_subdef (SubType.on _)). Notation "\val" := (isSub.val_subdef (SubType.on _)) (only parsing). Notation "\val" := (isSub.val_subdef _) (only printing). #[short(type="subEqType")] HB.structure Definition SubEquality T (P : pred T) := { sT of Equality sT & isSub T P sT}. Section SubType. Variables (T : Type) (P : pred T). (* Generic proof that the second property holds by conversion. *) (* The vrefl_rect alias is used to flag generic proofs of the first property. *) Lemma vrefl : forall x, P x -> x = x. Proof. by []. Qed. Definition vrefl_rect := vrefl. Section Theory. Variable sT : subType P. Local Notation val := (isSub.val_subdef (SubType.on sT)). Local Notation Sub := (@Sub _ _ sT). Lemma SubK x Px : val (@Sub x Px) = x. Proof. exact: SubK_subproof. Qed. Variant Sub_spec : sT -> Type := subSpec x Px : Sub_spec (Sub x Px). Lemma SubP u : Sub_spec u. Proof. by elim/(@Sub_rect _ _ sT) : u. Qed. (* BUG in elim? sT could be inferred from u *) Definition insub x := if idP is ReflectT Px then Some (Sub x Px) else None. Definition insubd u0 x := odflt u0 (insub x). Variant insub_spec x : option sT -> Type := | InsubSome u of P x & val u = x : insub_spec x (Some u) | InsubNone of ~~ P x : insub_spec x None. Lemma insubP x : insub_spec x (insub x). Proof. by rewrite /insub; case: {-}_ / idP; [left; rewrite ?SubK | right; apply/negP]. Qed. Lemma insubT x Px : insub x = Some (Sub x Px). Proof. do [case: insubP => [/SubP[y Py] _ <- | /negP// ]; rewrite SubK] in Px *. by rewrite (bool_irrelevance Px Py). Qed. Lemma insubF x : P x = false -> insub x = None. Proof. by move/idP; case: insubP. Qed. Lemma insubN x : ~~ P x -> insub x = None. Proof. by move/negPf/insubF. Qed. Lemma isSome_insub : ([eta insub] : pred T) =1 P. Proof. by apply: fsym => x; case: insubP => // /negPf. Qed. Lemma insubK : ocancel insub val. Proof. by move=> x; case: insubP. Qed. Lemma valP u : P (val u). Proof. by case/SubP: u => x Px; rewrite SubK. Qed. Lemma valK : pcancel val insub. Proof. by case/SubP=> x Px; rewrite SubK; apply: insubT. Qed. Lemma val_inj : injective val. Proof. exact: pcan_inj valK. Qed. Lemma valKd u0 : cancel val (insubd u0). Proof. by move=> u; rewrite /insubd valK. Qed. Lemma val_insubd u0 x : val (insubd u0 x) = if P x then x else val u0. Proof. by rewrite /insubd; case: insubP => [u -> | /negPf->]. Qed. Lemma insubdK u0 : {in P, cancel (insubd u0) val}. Proof. by move=> x Px; rewrite val_insubd [P x]Px. Qed. Let insub_eq_aux x isPx : P x = isPx -> option sT := if isPx as b return _ = b -> _ then fun Px => Some (Sub x Px) else fun=> None. Definition insub_eq x := insub_eq_aux (erefl (P x)). Lemma insub_eqE : insub_eq =1 insub. Proof. rewrite /insub_eq => x; set b := P x; rewrite [in LHS]/b in (Db := erefl b) *. by case: b in Db *; [rewrite insubT | rewrite insubF]. Qed. End Theory. End SubType. (* Arguments val {T P sT} u : rename. *) Arguments Sub {T P sT} x Px : rename. Arguments vrefl {T P} x Px. Arguments vrefl_rect {T P} x Px. Arguments insub {T P sT} x. Arguments insubd {T P sT} u0 x. Arguments insubT [T] P [sT x]. Arguments val_inj {T P sT} [u1 u2] eq_u12 : rename. Arguments valK {T P sT} u : rename. Arguments valKd {T P sT} u0 u : rename. Arguments insubK {T P} sT x. Arguments insubdK {T P sT} u0 [x] Px. Local Notation inlined_sub_rect := (fun K K_S u => let (x, Px) as u return K u := u in K_S x Px). Local Notation inlined_new_rect := (fun K K_S u => let (x) as u return K u := u in K_S x). Reserved Notation "[ 'isSub' 'for' v ]" (format "[ 'isSub' 'for' v ]"). Notation "[ 'isSub' 'for' v ]" := (@isSub.phant_Build _ _ _ v _ inlined_sub_rect vrefl_rect) (only parsing) : form_scope. Notation "[ 'isSub' 'of' T 'for' v ]" := (@isSub.phant_Build _ _ T v _ inlined_sub_rect vrefl_rect) (only parsing) : form_scope. Notation "[ 'isSub' 'for' v 'by' rec ]" := (@isSub.phant_Build _ _ _ v _ rec vrefl) (format "[ 'isSub' 'for' v 'by' rec ]") : form_scope. Notation "[ 'isSub' 'for' v ]" := (@isSub.phant_Build _ _ _ v _ _ _) (only printing, format "[ 'isSub' 'for' v ]") : form_scope. Reserved Notation "[ 'isNew' 'for' v ]" (format "[ 'isNew' 'for' v ]"). Definition NewMixin T U v c Urec sk := let Urec' P IH := Urec P (fun x : T => IH x isT : P _) in @isSub.phant_Build _ _ U v (fun x _ => c x) Urec' sk. Notation "[ 'isNew' 'for' v ]" := (@NewMixin _ _ v _ inlined_new_rect vrefl_rect) (only parsing) : form_scope. Notation "[ 'isNew' 'for' v ]" := (@NewMixin _ _ v _ _ _) (only printing, format "[ 'isNew' 'for' v ]") : form_scope. Notation "[ 'isNew' 'of' T 'for' v ]" := (@NewMixin _ T v _ inlined_new_rect vrefl_rect) (only parsing) : form_scope. Definition innew T nT x := @Sub T predT nT x (erefl true). Arguments innew {T nT}. Lemma innew_val T nT : cancel val (@innew T nT). Proof. by move=> u; apply: val_inj; apply: SubK. Qed. HB.instance Definition _ T (P : pred T) := [isSub of sig P for sval]. (* Shorthand for sigma types over collective predicates. *) Notation "{ x 'in' A }" := {x | x \in A} (x at level 99, format "{ x 'in' A }") : type_scope. Notation "{ x 'in' A | P }" := {x | (x \in A) && P} (x at level 99, format "{ x 'in' A | P }") : type_scope. (* Shorthand for the return type of insub. *) Notation "{ ? x : T | P }" := (option {x : T | is_true P}) (x at level 99, only parsing) : type_scope. Notation "{ ? x | P }" := {? x : _ | P} (x at level 99, format "{ ? x | P }") : type_scope. Notation "{ ? x 'in' A }" := {? x | x \in A} (x at level 99, format "{ ? x 'in' A }") : type_scope. Notation "{ ? x 'in' A | P }" := {? x | (x \in A) && P} (x at level 99, format "{ ? x 'in' A | P }") : type_scope. (* A variant of injection with default that infers a collective predicate *) (* from the membership proof for the default value. *) Definition insigd T (A : mem_pred T) x (Ax : in_mem x A) := insubd (exist [eta A] x Ax). (* There should be a rel definition for the subType equality op, but this *) (* seems to cause the simpl tactic to diverge on expressions involving == *) (* on 4+ nested subTypes in a "strict" position (e.g., after ~~). *) (* Definition feq f := [rel x y | f x == f y]. *) Section TransferType. Variables (T T' : Type) (f : T -> T'). Definition inj_type of injective f : Type := T. Definition pcan_type g of pcancel f g : Type := T. Definition can_type g of cancel f g : Type := T. End TransferType. Section TransferEqType. Variables (T : Type) (eT : eqType) (f : T -> eT). Lemma inj_eqAxiom : injective f -> Equality.axiom (fun x y => f x == f y). Proof. by move=> f_inj x y; apply: (iffP eqP) => [|-> //]; apply: f_inj. Qed. HB.instance Definition _ f_inj := hasDecEq.Build (inj_type f_inj) (inj_eqAxiom f_inj). HB.instance Definition _ g (fK : pcancel f g) := Equality.copy (pcan_type fK) (inj_type (pcan_inj fK)). HB.instance Definition _ g (fK : cancel f g) := Equality.copy (can_type fK) (inj_type (can_inj fK)). Definition deprecated_InjEqMixin f_inj := hasDecEq.Build T (inj_eqAxiom f_inj). Definition deprecated_PcanEqMixin g (fK : pcancel f g) := deprecated_InjEqMixin (pcan_inj fK). Definition deprecated_CanEqMixin g (fK : cancel f g) := deprecated_InjEqMixin (can_inj fK). End TransferEqType. Definition sub_type T (P : pred T) (sT : subType P) : Type := sT. HB.instance Definition _ T (P : pred T) (sT : subType P) := SubType.on (sub_type sT). Section SubEqType. Variables (T : eqType) (P : pred T) (sT : subType P). Local Notation ev_ax := (fun T v => @Equality.axiom T (fun x y => v x == v y)). Lemma val_eqP : ev_ax sT val. Proof. exact: inj_eqAxiom val_inj. Qed. #[hnf] HB.instance Definition _ := Equality.copy (sub_type sT) (pcan_type valK). End SubEqType. Lemma val_eqE (T : eqType) (P : pred T) (sT : subEqType P) (u v : sT) : (val u == val v) = (u == v). Proof. exact/val_eqP/eqP. Qed. Arguments val_eqP {T P sT x y}. Notation "[ 'Equality' 'of' T 'by' <: ]" := (Equality.copy T%type (sub_type T%type)) (format "[ 'Equality' 'of' T 'by' <: ]") : form_scope. HB.instance Definition _ := Equality.copy void (pcan_type (of_voidK unit)). HB.instance Definition _ (T : eqType) (P : pred T) := [Equality of {x | P x} by <:]. Section ProdEqType. Variable T1 T2 : eqType. Definition pair_eq : rel (T1 * T2) := fun u v => (u.1 == v.1) && (u.2 == v.2). Lemma pair_eqP : Equality.axiom pair_eq. Proof. move=> [x1 x2] [y1 y2] /=; apply: (iffP andP) => [[]|[<- <-]] //=. by do 2!move/eqP->. Qed. HB.instance Definition _ := hasDecEq.Build (T1 * T2)%type pair_eqP. Lemma pair_eqE : pair_eq = eq_op :> rel _. Proof. by []. Qed. Lemma xpair_eqE (x1 y1 : T1) (x2 y2 : T2) : ((x1, x2) == (y1, y2)) = ((x1 == y1) && (x2 == y2)). Proof. by []. Qed. Lemma pair_eq1 (u v : T1 * T2) : u == v -> u.1 == v.1. Proof. by case/andP. Qed. Lemma pair_eq2 (u v : T1 * T2) : u == v -> u.2 == v.2. Proof. by case/andP. Qed. End ProdEqType. Arguments pair_eq {T1 T2} u v /. Arguments pair_eqP {T1 T2}. Definition predX T1 T2 (p1 : pred T1) (p2 : pred T2) := [pred z | p1 z.1 & p2 z.2]. Notation "[ 'predX' A1 & A2 ]" := (predX [in A1] [in A2]) (format "[ 'predX' A1 & A2 ]") : function_scope. Section OptionEqType. Variable T : eqType. Definition opt_eq (u v : option T) : bool := oapp (fun x => oapp (eq_op x) false v) (~~ v) u. Lemma opt_eqP : Equality.axiom opt_eq. Proof. case=> [x|] [y|] /=; by [constructor | apply: (iffP eqP) => [|[]] ->]. Qed. HB.instance Definition _ := hasDecEq.Build (option T) opt_eqP. End OptionEqType. Arguments opt_eq {T} !u !v. Section TaggedAs. Variables (I : eqType) (T_ : I -> Type). Implicit Types u v : {i : I & T_ i}. Definition tagged_as u v := if tag u =P tag v is ReflectT eq_uv then eq_rect_r T_ (tagged v) eq_uv else tagged u. Lemma tagged_asE u x : tagged_as u (Tagged T_ x) = x. Proof. by rewrite /tagged_as /=; case: eqP => // eq_uu; rewrite [eq_uu]eq_axiomK. Qed. End TaggedAs. Section EqTagged. Variables (I : eqType) (T_ : I -> Type). Local Notation T := {i : I & T_ i}. Definition etagged i u (p : tag u = i) := ecast i (T_ i) p (tagged u). Implicit Types (i j : I) (u v : T). Lemma eq_from_Tagged i (t s : T_ i) : Tagged T_ t = Tagged T_ s -> t = s. Proof. by move=> /(congr1 (tagged_as (Tagged T_ t))); rewrite !tagged_asE. Qed. Lemma etaggedK i u (p : tag u = i) : Tagged T_ (etagged p) = u. Proof. by case: _ / p; apply: taggedK. Qed. Definition tagged_with i : pred {i : I & T_ i} := [pred j | tag j == i]. Definition untag_with i (x : {x in tagged_with i}) : T_ i := etagged (eqP (valP x)). Definition tag_with i (t : T_ i) : {x in tagged_with i} := exist _ (Tagged T_ t) (eq_refl i). Lemma untag_withK i : cancel (@untag_with i) (@tag_with i). Proof. by case=> -[j /= x eq_ji]; apply/val_inj=> /=; rewrite etaggedK. Qed. #[local] Hint Resolve untag_withK : core. Lemma tag_withK i : cancel (@tag_with i) (@untag_with i). Proof. by move=> x; rewrite /untag_with/= eq_axiomK. Qed. #[local] Hint Resolve tag_withK : core. Lemma tag_with_bij i : bijective (@tag_with i). Proof. by exists (@untag_with i). Qed. Lemma untag_with_bij i : bijective (@untag_with i). Proof. by exists (@tag_with i). Qed. Definition untag (R : Type) (idx : R) (i : I) (F : T_ i -> R) u := if tag u =P i is ReflectT e then F (etagged e) else idx. Lemma untagE (R : Type) (idx : R) (i : I) (F : T_ i -> R) u (e : tag u = i): untag idx F u = F (etagged e). Proof. by rewrite /untag; case: eqP => // p; rewrite (eq_irrelevance p e). Qed. Lemma untag_dflt (R : Type) (idx : R) (i : I) (F : T_ i -> R) u : tag u != i -> untag idx F u = idx. Proof. by rewrite /untag; case: eqP. Qed. Lemma untag_cst (R : Type) (idx : R) (i : I) u : untag idx (fun _ : T_ i => idx) u = idx. Proof. by rewrite /untag; case: eqP. Qed. End EqTagged. Arguments etagged {I T_ i u}. Arguments untag {I T_ R} idx [i]. Arguments tagged_with {I}. Arguments tag_with {I T_}. Arguments untag_with {I T_}. Section TagEqType. Variables (I : eqType) (T_ : I -> eqType). Implicit Types u v : {i : I & T_ i}. Definition tag_eq u v := (tag u == tag v) && (tagged u == tagged_as u v). Lemma tag_eqP : Equality.axiom tag_eq. Proof. rewrite /tag_eq => [] [i x] [j] /=. case: eqP => [<-|Hij] y; last by right; case. by apply: (iffP eqP) => [->|<-]; rewrite tagged_asE. Qed. HB.instance Definition _ := hasDecEq.Build {i : I & T_ i} tag_eqP. Lemma tag_eqE : tag_eq = eq_op. Proof. by []. Qed. Lemma eq_tag u v : u == v -> tag u = tag v. Proof. by move/eqP->. Qed. Lemma eq_Tagged u x :(u == Tagged _ x) = (tagged u == x). Proof. by rewrite -tag_eqE /tag_eq eqxx tagged_asE. Qed. End TagEqType. Arguments tag_eq {I T_} !u !v. Arguments tag_eqP {I T_ x y}. Section SumEqType. Variables T1 T2 : eqType. Implicit Types u v : T1 + T2. Definition sum_eq u v := match u, v with | inl x, inl y | inr x, inr y => x == y | _, _ => false end. Lemma sum_eqP : Equality.axiom sum_eq. Proof. case=> x [] y /=; by [right | apply: (iffP eqP) => [->|[->]]]. Qed. HB.instance Definition _ := hasDecEq.Build (T1 + T2)%type sum_eqP. Lemma sum_eqE : sum_eq = eq_op. Proof. by []. Qed. End SumEqType. Arguments sum_eq {T1 T2} !u !v. Arguments sum_eqP {T1 T2 x y}. Section MonoHomoTheory. Variables (aT rT : eqType) (f : aT -> rT). Variables (aR aR' : rel aT) (rR rR' : rel rT). Hypothesis aR_refl : reflexive aR. Hypothesis rR_refl : reflexive rR. Hypothesis aR'E : forall x y, aR' x y = (x != y) && (aR x y). Hypothesis rR'E : forall x y, rR' x y = (x != y) && (rR x y). Let aRE x y : aR x y = (x == y) || (aR' x y). Proof. by rewrite aR'E; case: eqVneq => //= ->; apply: aR_refl. Qed. Let rRE x y : rR x y = (x == y) || (rR' x y). Proof. by rewrite rR'E; case: eqVneq => //= ->; apply: rR_refl. Qed. Section InDom. Variable D : pred aT. Section DifferentDom. Variable D' : pred aT. Lemma homoW_in : {in D & D', {homo f : x y / aR' x y >-> rR' x y}} -> {in D & D', {homo f : x y / aR x y >-> rR x y}}. Proof. by move=> mf x y xD yD /[!aRE]/orP[/eqP->|/mf]; rewrite rRE ?eqxx// orbC => ->. Qed. Lemma inj_homo_in : {in D & D', injective f} -> {in D & D', {homo f : x y / aR x y >-> rR x y}} -> {in D & D', {homo f : x y / aR' x y >-> rR' x y}}. Proof. move=> fI mf x y xD yD /[!(aR'E, rR'E)] /andP[neq_xy xy]. by rewrite mf ?andbT//; apply: contra_neq neq_xy; apply: fI. Qed. End DifferentDom. Hypothesis aR_anti : antisymmetric aR. Hypothesis rR_anti : antisymmetric rR. Lemma mono_inj_in : {in D &, {mono f : x y / aR x y >-> rR x y}} -> {in D &, injective f}. Proof. by move=> mf x y ?? eqf; apply/aR_anti; rewrite -!mf// eqf rR_refl. Qed. Lemma anti_mono_in : {in D &, {mono f : x y / aR x y >-> rR x y}} -> {in D &, {mono f : x y / aR' x y >-> rR' x y}}. Proof. move=> mf x y ??; rewrite rR'E aR'E mf// (@inj_in_eq _ _ D)//. exact: mono_inj_in. Qed. Lemma total_homo_mono_in : total aR -> {in D &, {homo f : x y / aR' x y >-> rR' x y}} -> {in D &, {mono f : x y / aR x y >-> rR x y}}. Proof. move=> aR_tot mf x y xD yD. have [->|neq_xy] := eqVneq x y; first by rewrite ?eqxx ?aR_refl ?rR_refl. have [xy|] := (boolP (aR x y)); first by rewrite rRE mf ?orbT// aR'E neq_xy. have /orP [->//|] := aR_tot x y. rewrite aRE eq_sym (negPf neq_xy) /= => /mf -/(_ yD xD). rewrite rR'E => /andP[Nfxfy fyfx] _; apply: contra_neqF Nfxfy => fxfy. by apply/rR_anti; rewrite fyfx fxfy. Qed. End InDom. Let D := @predT aT. Lemma homoW : {homo f : x y / aR' x y >-> rR' x y} -> {homo f : x y / aR x y >-> rR x y}. Proof. by move=> mf ???; apply: (@homoW_in D D) => // ????; apply: mf. Qed. Lemma inj_homo : injective f -> {homo f : x y / aR x y >-> rR x y} -> {homo f : x y / aR' x y >-> rR' x y}. Proof. by move=> fI mf ???; apply: (@inj_homo_in D D) => //????; [apply: fI|apply: mf]. Qed. Hypothesis aR_anti : antisymmetric aR. Hypothesis rR_anti : antisymmetric rR. Lemma mono_inj : {mono f : x y / aR x y >-> rR x y} -> injective f. Proof. by move=> mf x y eqf; apply/aR_anti; rewrite -!mf eqf rR_refl. Qed. Lemma anti_mono : {mono f : x y / aR x y >-> rR x y} -> {mono f : x y / aR' x y >-> rR' x y}. Proof. by move=> mf x y; rewrite rR'E aR'E mf inj_eq //; apply: mono_inj. Qed. Lemma total_homo_mono : total aR -> {homo f : x y / aR' x y >-> rR' x y} -> {mono f : x y / aR x y >-> rR x y}. Proof. move=> /(@total_homo_mono_in D rR_anti) hmf hf => x y. by apply: hmf => // ?? _ _; apply: hf. Qed. End MonoHomoTheory.
Pairing.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import Mathlib.Algebra.Notation.Prod import Mathlib.Data.Nat.Sqrt import Mathlib.Data.Set.Lattice.Image /-! # Naturals pairing function This file defines a pairing function for the naturals as follows: ```text 0 1 4 9 16 2 3 5 10 17 6 7 8 11 18 12 13 14 15 19 20 21 22 23 24 ``` It has the advantage of being monotone in both directions and sending `⟦0, n^2 - 1⟧` to `⟦0, n - 1⟧²`. -/ assert_not_exists Monoid open Prod Decidable Function namespace Nat /-- Pairing function for the natural numbers. -/ @[pp_nodot] def pair (a b : ℕ) : ℕ := if a < b then b * b + a else a * a + a + b /-- Unpairing function for the natural numbers. -/ @[pp_nodot] def unpair (n : ℕ) : ℕ × ℕ := let s := sqrt n if n - s * s < s then (n - s * s, s) else (s, n - s * s - s) @[simp] theorem pair_unpair (n : ℕ) : pair (unpair n).1 (unpair n).2 = n := by dsimp only [unpair]; let s := sqrt n have sm : s * s + (n - s * s) = n := Nat.add_sub_cancel' (sqrt_le _) split_ifs with h · simp [s, pair, h, sm] · have hl : n - s * s - s ≤ s := Nat.sub_le_iff_le_add.2 (Nat.sub_le_iff_le_add'.2 <| by rw [← Nat.add_assoc]; apply sqrt_le_add) simp [s, pair, hl.not_gt, Nat.add_assoc, Nat.add_sub_cancel' (le_of_not_gt h), sm] theorem pair_eq_of_unpair_eq {n a b} (H : unpair n = (a, b)) : pair a b = n := by simpa [H] using pair_unpair n @[deprecated (since := "2025-05-24")] alias pair_unpair' := pair_eq_of_unpair_eq @[simp] theorem unpair_pair (a b : ℕ) : unpair (pair a b) = (a, b) := by dsimp only [pair]; split_ifs with h · show unpair (b * b + a) = (a, b) have be : sqrt (b * b + a) = b := sqrt_add_eq _ (le_trans (le_of_lt h) (Nat.le_add_left _ _)) simp [unpair, be, Nat.add_sub_cancel_left, h] · show unpair (a * a + a + b) = (a, b) have ae : sqrt (a * a + (a + b)) = a := by rw [sqrt_add_eq] exact Nat.add_le_add_left (le_of_not_gt h) _ simp [unpair, ae, Nat.add_assoc, Nat.add_sub_cancel_left] /-- An equivalence between `ℕ × ℕ` and `ℕ`. -/ @[simps -fullyApplied] def pairEquiv : ℕ × ℕ ≃ ℕ := ⟨uncurry pair, unpair, fun ⟨a, b⟩ => unpair_pair a b, pair_unpair⟩ theorem surjective_unpair : Surjective unpair := pairEquiv.symm.surjective @[simp] theorem pair_eq_pair {a b c d : ℕ} : pair a b = pair c d ↔ a = c ∧ b = d := pairEquiv.injective.eq_iff.trans (@Prod.ext_iff ℕ ℕ (a, b) (c, d)) theorem unpair_lt {n : ℕ} (n1 : 1 ≤ n) : (unpair n).1 < n := by let s := sqrt n simp only [unpair] by_cases h : n - s * s < s <;> simp [s, h, ↓reduceIte] · exact lt_of_lt_of_le h (sqrt_le_self _) · simp only [not_lt] at h have s0 : 0 < s := sqrt_pos.2 n1 exact lt_of_le_of_lt h (Nat.sub_lt n1 (Nat.mul_pos s0 s0)) @[simp] theorem unpair_zero : unpair 0 = 0 := by rw [unpair] simp theorem unpair_left_le : ∀ n : ℕ, (unpair n).1 ≤ n | 0 => by simp | _ + 1 => le_of_lt (unpair_lt (Nat.succ_pos _)) theorem left_le_pair (a b : ℕ) : a ≤ pair a b := by simpa using unpair_left_le (pair a b) theorem right_le_pair (a b : ℕ) : b ≤ pair a b := by by_cases h : a < b · simpa [pair, h] using le_trans (le_mul_self _) (Nat.le_add_right _ _) · simp [pair, h] theorem unpair_right_le (n : ℕ) : (unpair n).2 ≤ n := by simpa using right_le_pair n.unpair.1 n.unpair.2 theorem pair_lt_pair_left {a₁ a₂} (b) (h : a₁ < a₂) : pair a₁ b < pair a₂ b := by by_cases h₁ : a₁ < b <;> simp [pair, h₁, Nat.add_assoc] · by_cases h₂ : a₂ < b <;> simp [h₂, h] simp? at h₂ says simp only [not_lt] at h₂ apply Nat.add_lt_add_of_le_of_lt · exact Nat.mul_self_le_mul_self h₂ · exact Nat.lt_add_right _ h · simp at h₁ simp only [not_lt_of_gt (lt_of_le_of_lt h₁ h), ite_false] apply add_lt_add · exact Nat.mul_self_lt_mul_self h · apply Nat.add_lt_add_right; assumption theorem pair_lt_pair_right (a) {b₁ b₂} (h : b₁ < b₂) : pair a b₁ < pair a b₂ := by by_cases h₁ : a < b₁ · simpa [pair, h₁, Nat.add_assoc, lt_trans h₁ h, h] using mul_self_lt_mul_self h · simp only [pair, h₁, ↓reduceIte, Nat.add_assoc] by_cases h₂ : a < b₂ <;> simp [h₂, h] simp? at h₁ says simp only [not_lt] at h₁ rw [Nat.add_comm, Nat.add_comm _ a, Nat.add_assoc, Nat.add_lt_add_iff_left] rwa [Nat.add_comm, ← sqrt_lt, sqrt_add_eq] exact le_trans h₁ (Nat.le_add_left _ _) theorem pair_lt_max_add_one_sq (m n : ℕ) : pair m n < (max m n + 1) ^ 2 := by simp only [pair, Nat.pow_two, Nat.mul_add, Nat.add_mul, Nat.mul_one, Nat.one_mul, Nat.add_assoc] split_ifs <;> simp [Nat.le_of_lt, not_lt.1, *] <;> omega theorem max_sq_add_min_le_pair (m n : ℕ) : max m n ^ 2 + min m n ≤ pair m n := by rw [pair] rcases lt_or_ge m n with h | h · rw [if_pos h, max_eq_right h.le, min_eq_left h.le, Nat.pow_two] rw [if_neg h.not_gt, max_eq_left h, min_eq_right h, Nat.pow_two, Nat.add_assoc, Nat.add_le_add_iff_left] exact Nat.le_add_left _ _ theorem add_le_pair (m n : ℕ) : m + n ≤ pair m n := by simp only [pair, Nat.add_assoc] split_ifs · have := le_mul_self n omega · exact Nat.le_add_left _ _ theorem unpair_add_le (n : ℕ) : (unpair n).1 + (unpair n).2 ≤ n := (add_le_pair _ _).trans_eq (pair_unpair _) end Nat open Nat section CompleteLattice theorem iSup_unpair {α} [CompleteLattice α] (f : ℕ → ℕ → α) : ⨆ n : ℕ, f n.unpair.1 n.unpair.2 = ⨆ (i : ℕ) (j : ℕ), f i j := by rw [← (iSup_prod : ⨆ i : ℕ × ℕ, f i.1 i.2 = _), ← Nat.surjective_unpair.iSup_comp] theorem iInf_unpair {α} [CompleteLattice α] (f : ℕ → ℕ → α) : ⨅ n : ℕ, f n.unpair.1 n.unpair.2 = ⨅ (i : ℕ) (j : ℕ), f i j := iSup_unpair (show ℕ → ℕ → αᵒᵈ from f) end CompleteLattice namespace Set theorem iUnion_unpair_prod {α β} {s : ℕ → Set α} {t : ℕ → Set β} : ⋃ n : ℕ, s n.unpair.fst ×ˢ t n.unpair.snd = (⋃ n, s n) ×ˢ ⋃ n, t n := by rw [← Set.iUnion_prod] exact surjective_unpair.iUnion_comp (fun x => s x.fst ×ˢ t x.snd) theorem iUnion_unpair {α} (f : ℕ → ℕ → Set α) : ⋃ n : ℕ, f n.unpair.1 n.unpair.2 = ⋃ (i : ℕ) (j : ℕ), f i j := iSup_unpair f theorem iInter_unpair {α} (f : ℕ → ℕ → Set α) : ⋂ n : ℕ, f n.unpair.1 n.unpair.2 = ⋂ (i : ℕ) (j : ℕ), f i j := iInf_unpair f end Set
Notation3.lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kyle Miller -/ import Lean.Elab.BuiltinCommand import Lean.Elab.MacroArgUtil import Mathlib.Lean.Elab.Term import Mathlib.Lean.PrettyPrinter.Delaborator import Mathlib.Tactic.ScopedNS import Batteries.Linter.UnreachableTactic import Batteries.Util.ExtendedBinder import Batteries.Lean.Syntax /-! # The notation3 macro, simulating Lean 3's notation. -/ -- To fix upstream: -- * bracketedExplicitBinders doesn't support optional types namespace Mathlib.Notation3 open Lean Parser Meta Elab Command PrettyPrinter.Delaborator SubExpr open Batteries.ExtendedBinder initialize registerTraceClass `notation3 /-! ### Syntaxes supporting `notation3` -/ /-- Expands binders into nested combinators. For example, the familiar exists is given by: `expand_binders% (p => Exists p) x y : Nat, x < y` which expands to the same expression as `∃ x y : Nat, x < y` -/ syntax "expand_binders% " "(" ident " => " term ")" extBinders ", " term : term macro_rules | `(expand_binders% ($x => $term) $y:extBinder, $res) => `(expand_binders% ($x => $term) ($y:extBinder), $res) | `(expand_binders% ($_ => $_), $res) => pure res macro_rules | `(expand_binders% ($x => $term) ($y:ident $[: $ty]?) $binders*, $res) => do let ty := ty.getD (← `(_)) term.replaceM fun x' ↦ do unless x == x' do return none `(fun $y:ident : $ty ↦ expand_binders% ($x => $term) $[$binders]*, $res) | `(expand_binders% ($x => $term) (_%$ph $[: $ty]?) $binders*, $res) => do let ty := ty.getD (← `(_)) term.replaceM fun x' ↦ do unless x == x' do return none `(fun _%$ph : $ty ↦ expand_binders% ($x => $term) $[$binders]*, $res) | `(expand_binders% ($x => $term) ($y:binderIdent $pred:binderPred) $binders*, $res) => do let y ← match y with | `(binderIdent| $y:ident) => pure y | `(binderIdent| _) => Term.mkFreshIdent y | _ => Macro.throwUnsupported term.replaceM fun x' ↦ do unless x == x' do return none `(fun $y:ident ↦ expand_binders% ($x => $term) (h : satisfies_binder_pred% $y $pred) $[$binders]*, $res) macro (name := expandFoldl) "expand_foldl% " "(" x:ident ppSpace y:ident " => " term:term ") " init:term:max " [" args:term,* "]" : term => args.getElems.foldlM (init := init) fun res arg ↦ do term.replaceM fun e ↦ return if e == x then some res else if e == y then some arg else none macro (name := expandFoldr) "expand_foldr% " "(" x:ident ppSpace y:ident " => " term:term ") " init:term:max " [" args:term,* "]" : term => args.getElems.foldrM (init := init) fun arg res ↦ do term.replaceM fun e ↦ return if e == x then some arg else if e == y then some res else none /-- Keywording indicating whether to use a left- or right-fold. -/ syntax foldKind := &"foldl" <|> &"foldr" /-- `notation3` argument matching `extBinders`. -/ syntax bindersItem := atomic("(" "..." ")") /-- `notation3` argument simulating a Lean 3 fold notation. -/ syntax foldAction := "(" ident ppSpace strLit "*" (precedence)? " => " foldKind " (" ident ppSpace ident " => " term ") " term ")" /-- `notation3` argument binding a name. -/ syntax identOptScoped := ident (notFollowedBy(":" "(" "scoped") precedence)? (":" "(" "scoped " ident " => " term ")")? /-- `notation3` argument. -/ -- Note: there is deliberately no ppSpace between items -- so that the space in the literals themselves stands out syntax notation3Item := strLit <|> bindersItem <|> identOptScoped <|> foldAction /-! ### Expression matching A more complicated part of `notation3` is the delaborator generator. While `notation` relies on generating app unexpanders, we instead generate a delaborator directly so that we can control how binders are formatted (we want to be able to know the types of binders, whether a lambda is a constant function, and whether it is `Prop`-valued, which are not things we can answer once we pass to app unexpanders). -/ /-- The dynamic state of a `Matcher`. -/ structure MatchState where /-- This stores the assignments of variables to subexpressions (and their contexts) that have been found so far during the course of the matching algorithm. We store the contexts since we need to delaborate expressions after we leave scoping constructs. -/ vars : Std.HashMap Name (SubExpr × LocalContext × LocalInstances) /-- The binders accumulated while matching a `scoped` expression. -/ scopeState : Option (Array (TSyntax ``extBinderParenthesized)) /-- The arrays of delaborated `Term`s accumulated while matching `foldl` and `foldr` expressions. For `foldl`, the arrays are stored in reverse order. -/ foldState : Std.HashMap Name (Array Term) /-- A matcher is a delaboration function that transforms `MatchState`s. -/ def Matcher := MatchState → DelabM MatchState deriving Inhabited /-- The initial state. -/ def MatchState.empty : MatchState where vars := {} scopeState := none foldState := {} /-- Evaluate `f` with the given variable's value as the `SubExpr` and within that subexpression's saved context. Fails if the variable has no value. -/ def MatchState.withVar {α : Type} (s : MatchState) (name : Name) (m : DelabM α) : DelabM α := do let some (se, lctx, linsts) := s.vars[name]? | failure withLCtx lctx linsts <| withTheReader SubExpr (fun _ => se) <| m /-- Delaborate the given variable's value. Fails if the variable has no value. If `checkNot` is provided, then checks that the expression being delaborated is not the given one (this is used to prevent infinite loops). -/ def MatchState.delabVar (s : MatchState) (name : Name) (checkNot? : Option Expr := none) : DelabM Term := s.withVar name do if let some checkNot := checkNot? then guard <| checkNot != (← getExpr) delab /-- Assign a variable to the current `SubExpr`, capturing the local context. -/ def MatchState.captureSubexpr (s : MatchState) (name : Name) : DelabM MatchState := do return {s with vars := s.vars.insert name (← readThe SubExpr, ← getLCtx, ← getLocalInstances)} /-- Get the accumulated array of delaborated terms for a given foldr/foldl. Returns `#[]` if nothing has been pushed yet. -/ def MatchState.getFoldArray (s : MatchState) (name : Name) : Array Term := s.foldState[name]?.getD #[] /-- Get the accumulated array of delaborated terms for a given foldr/foldl. Returns `#[]` if nothing has been pushed yet. -/ def MatchState.getBinders (s : MatchState) : Array (TSyntax ``extBinderParenthesized) := s.scopeState.getD #[] /-- Push a delaborated term onto a foldr/foldl array. -/ def MatchState.pushFold (s : MatchState) (name : Name) (t : Term) : MatchState := let ts := (s.getFoldArray name).push t {s with foldState := s.foldState.insert name ts} /-- Matcher that assigns the current `SubExpr` into the match state; if a value already exists, then it checks for equality. -/ def matchVar (c : Name) : Matcher := fun s => do if let some (se, _, _) := s.vars[c]? then guard <| se.expr == (← getExpr) return s else s.captureSubexpr c /-- Matcher for an expression satisfying a given predicate. -/ def matchExpr (p : Expr → Bool) : Matcher := fun s => do guard <| p (← getExpr) return s /-- Matcher for `Expr.fvar`. It checks that the user name agrees and that the type of the expression is matched by `matchTy`. -/ def matchFVar (userName : Name) (matchTy : Matcher) : Matcher := fun s => do let .fvar fvarId ← getExpr | failure guard <| userName == (← fvarId.getUserName) withType (matchTy s) /-- Matcher that checks that the type of the expression is matched by `matchTy`. -/ def matchTypeOf (matchTy : Matcher) : Matcher := fun s => do withType (matchTy s) /-- Matches raw nat lits. -/ def natLitMatcher (n : Nat) : Matcher := fun s => do guard <| (← getExpr).rawNatLit? == n return s /-- Matches applications. -/ def matchApp (matchFun matchArg : Matcher) : Matcher := fun s => do guard <| (← getExpr).isApp let s ← withAppFn <| matchFun s let s ← withAppArg <| matchArg s return s /-- Matches pi types. The name `n` should be unique, and `matchBody` should use `n` as the `userName` of its fvar. -/ def matchForall (matchDom : Matcher) (matchBody : Expr → Matcher) : Matcher := fun s => do guard <| (← getExpr).isForall let s ← withBindingDomain <| matchDom s let s ← withBindingBodyUnusedName' fun _ arg => matchBody arg s return s /-- Matches lambdas. The `matchBody` takes the fvar introduced when visiting the body. -/ def matchLambda (matchDom : Matcher) (matchBody : Expr → Matcher) : Matcher := fun s => do guard <| (← getExpr).isLambda let s ← withBindingDomain <| matchDom s let s ← withBindingBodyUnusedName' fun _ arg => matchBody arg s return s /-- Adds all the names in `boundNames` to the local context with types that are fresh metavariables. This is used for example when initializing `p` in `(scoped p => ...)` when elaborating `...`. -/ def setupLCtx (lctx : LocalContext) (boundNames : Array Name) : MetaM (LocalContext × Std.HashMap FVarId Name) := do let mut lctx := lctx let mut boundFVars := {} for name in boundNames do let fvarId ← mkFreshFVarId lctx := lctx.mkLocalDecl fvarId name (← withLCtx lctx (← getLocalInstances) mkFreshTypeMVar) boundFVars := boundFVars.insert fvarId name return (lctx, boundFVars) /-- Like `Expr.isType`, but uses logic that normalizes the universe level. Mirrors the core `Sort` delaborator logic. -/ def isType' : Expr → Bool | .sort u => u.dec.isSome | _ => false /-- Represents a key to use when registering the `delab` attribute for a delaborator. We use this to handle overapplication. -/ inductive DelabKey where /-- The key `app.const` or `app` with a specific arity. -/ | app (const : Option Name) (arity : Nat) | other (key : Name) deriving Repr /-- Turns the `DelabKey` into a key that the `delab` attribute accepts. -/ def DelabKey.key : DelabKey → Name | .app none _ => `app | .app (some n) _ => `app ++ n | .other key => key /-- Given an expression, generate a matcher for it. The `boundFVars` hash map records which state variables certain fvars correspond to. The `localFVars` hash map records which local variable the matcher should use for an exact expression match. If it succeeds generating a matcher, returns 1. a list of keys that should be used for the `delab` attribute when defining the elaborator 2. a `Term` that represents a `Matcher` for the given expression `e`. -/ partial def exprToMatcher (boundFVars : Std.HashMap FVarId Name) (localFVars : Std.HashMap FVarId Term) (e : Expr) : OptionT TermElabM (List DelabKey × Term) := do match e with | .mvar .. => return ([], ← `(pure)) | .const n _ => return ([.app n 0], ← ``(matchExpr (Expr.isConstOf · $(quote n)))) | .sort u => /- We should try being more accurate here. Prop / Type / Type _ / Sort _ is at least an OK approximation. We mimic the core Sort delaborator `Lean.PrettyPrinter.Delaborator.delabSort`. -/ let matcher ← if u.isZero then ``(matchExpr Expr.isProp) else if e.isType0 then ``(matchExpr Expr.isType0) else if u.dec.isSome then ``(matchExpr isType') else ``(matchExpr Expr.isSort) return ([.other `sort], matcher) | .fvar fvarId => if let some n := boundFVars[fvarId]? then -- This fvar is a pattern variable. return ([], ← ``(matchVar $(quote n))) else if let some s := localFVars[fvarId]? then -- This fvar is bound by a lambda or forall expression in the pattern itself return ([], ← ``(matchExpr (· == $s))) else let n ← fvarId.getUserName if n.hasMacroScopes then -- Match by just the type; this is likely an unnamed instance for example let (_, m) ← exprToMatcher boundFVars localFVars (← instantiateMVars (← inferType e)) return ([.other `fvar], ← ``(matchTypeOf $m)) else -- This is an fvar from a `variable`. Match by name and type. let (_, m) ← exprToMatcher boundFVars localFVars (← instantiateMVars (← inferType e)) return ([.other `fvar], ← ``(matchFVar $(quote n) $m)) | .app .. => e.withApp fun f args => do let (keys, matchF) ← if let .const n _ := f then pure ([.app n args.size], ← ``(matchExpr (Expr.isConstOf · $(quote n)))) else let (_, matchF) ← exprToMatcher boundFVars localFVars f pure ([.app none args.size], matchF) let mut fty ← inferType f let mut matcher := matchF for arg in args do fty ← whnf fty guard fty.isForall let bi := fty.bindingInfo! fty := fty.bindingBody!.instantiate1 arg if bi.isInstImplicit then -- Assumption: elaborated instances are canonical, so no need to match. -- The type of the instance is already accounted for by the previous arguments -- and the type of `f`. matcher ← ``(matchApp $matcher pure) else let (_, matchArg) ← exprToMatcher boundFVars localFVars arg matcher ← ``(matchApp $matcher $matchArg) return (keys, matcher) | .lit (.natVal n) => return ([.other `lit], ← ``(natLitMatcher $(quote n))) | .forallE n t b bi => let (_, matchDom) ← exprToMatcher boundFVars localFVars t withLocalDecl n bi t fun arg => withFreshMacroScope do let n' ← `(n) let body := b.instantiate1 arg let localFVars' := localFVars.insert arg.fvarId! n' let (_, matchBody) ← exprToMatcher boundFVars localFVars' body return ([.other `forallE], ← ``(matchForall $matchDom (fun $n' => $matchBody))) | .lam n t b bi => let (_, matchDom) ← exprToMatcher boundFVars localFVars t withLocalDecl n bi t fun arg => withFreshMacroScope do let n' ← `(n) let body := b.instantiate1 arg let localFVars' := localFVars.insert arg.fvarId! n' let (_, matchBody) ← exprToMatcher boundFVars localFVars' body return ([.other `lam], ← ``(matchLambda $matchDom (fun $n' => $matchBody))) | _ => trace[notation3] "can't generate matcher for {e}" failure /-- Returns a `Term` that represents a `Matcher` for the given pattern `stx`. The `boundNames` set determines which identifiers are variables in the pattern. Fails in the `OptionT` sense if it comes across something it's unable to handle. Also returns constant names that could serve as a key for a delaborator. For example, if it's for a function `f`, then `app.f`. -/ partial def mkExprMatcher (stx : Term) (boundNames : Array Name) : OptionT TermElabM (List DelabKey × Term) := do let (lctx, boundFVars) ← setupLCtx (← getLCtx) boundNames withLCtx lctx (← getLocalInstances) do let patt ← try Term.elabPattern stx none catch e => logException e trace[notation3] "Could not elaborate pattern{indentD stx}\nError: {e.toMessageData}" -- Convert the exception into an `OptionT` failure so that the `(prettyPrint := false)` -- suggestion appears. failure trace[notation3] "Generating matcher for pattern {patt}" exprToMatcher boundFVars {} patt /-- Matcher for processing `scoped` syntax. Assumes the expression to be matched against is in the `lit` variable. Runs `smatcher`, extracts the resulting `scopeId` variable, processes this value (which must be a lambda) to produce a binder, and loops. -/ partial def matchScoped (lit scopeId : Name) (smatcher : Matcher) : Matcher := go #[] where /-- Variant of `matchScoped` after some number of `binders` have already been captured. -/ go (binders : Array (TSyntax ``extBinderParenthesized)) : Matcher := fun s => do -- `lit` is bound to the SubExpr that the `scoped` syntax produced s.withVar lit do try -- Run `smatcher` at `lit`, clearing the `scopeId` variable so that it can get a fresh value let s ← smatcher {s with vars := s.vars.erase scopeId} s.withVar scopeId do guard (← getExpr).isLambda let prop ← try Meta.isProp (← getExpr).bindingDomain! catch _ => pure false let isDep := (← getExpr).bindingBody!.hasLooseBVar 0 let ppTypes ← getPPOption getPPPiBinderTypes -- the same option controlling ∀ let dom ← withBindingDomain delab withBindingBodyUnusedName fun x => do let x : Ident := ⟨x⟩ let binder ← if prop && !isDep then -- this underscore is used to support binder predicates, since it indicates -- the variable is unused and this binder is safe to merge into another `(extBinderParenthesized|(_ : $dom)) else if prop || ppTypes then `(extBinderParenthesized|($x:ident : $dom)) else `(extBinderParenthesized|($x:ident)) -- Now use the body of the lambda for `lit` for the next iteration let s ← s.captureSubexpr lit -- TODO merge binders as an inverse to `satisfies_binder_pred%` let binders := binders.push binder go binders s catch _ => guard <| !binders.isEmpty if let some binders₂ := s.scopeState then guard <| binders == binders₂ -- TODO: this might be a bit too strict, but it seems to work return s else return {s with scopeState := binders} /-- Create a `Term` that represents a matcher for `scoped` notation. Fails in the `OptionT` sense if a matcher couldn't be constructed. Also returns a delaborator key like in `mkExprMatcher`. Reminder: `$lit:ident : (scoped $scopedId:ident => $scopedTerm:Term)` -/ partial def mkScopedMatcher (lit scopeId : Name) (scopedTerm : Term) (boundNames : Array Name) : OptionT TermElabM (List DelabKey × Term) := do -- Build the matcher for `scopedTerm` with `scopeId` as an additional variable let (keys, smatcher) ← mkExprMatcher scopedTerm (boundNames.push scopeId) return (keys, ← ``(matchScoped $(quote lit) $(quote scopeId) $smatcher)) /-- Matcher for expressions produced by `foldl`. -/ partial def matchFoldl (lit x y : Name) (smatcher : Matcher) (sinit : Matcher) : Matcher := fun s => do s.withVar lit do let expr ← getExpr -- Clear x and y state before running smatcher so it can store new values let s := {s with vars := s.vars |>.erase x |>.erase y} let some s ← try some <$> smatcher s catch _ => pure none | -- We put this here rather than using a big try block to prevent backtracking. -- We have `smatcher` match greedily, and then require that `sinit` *must* succeed sinit s -- y gives the next element of the list let s := s.pushFold lit (← s.delabVar y expr) -- x gives the next lit let some newLit := s.vars[x]? | failure -- If progress was not made, fail if newLit.1.expr == expr then failure -- Progress was made, so recurse let s := {s with vars := s.vars.insert lit newLit} matchFoldl lit x y smatcher sinit s /-- Create a `Term` that represents a matcher for `foldl` notation. Reminder: `( lit ","* => foldl (x y => scopedTerm) init)` -/ partial def mkFoldlMatcher (lit x y : Name) (scopedTerm init : Term) (boundNames : Array Name) : OptionT TermElabM (List DelabKey × Term) := do -- Build the `scopedTerm` matcher with `x` and `y` as additional variables let boundNames' := boundNames |>.push x |>.push y let (keys, smatcher) ← mkExprMatcher scopedTerm boundNames' let (keys', sinit) ← mkExprMatcher init boundNames return (keys ++ keys', ← ``(matchFoldl $(quote lit) $(quote x) $(quote y) $smatcher $sinit)) /-- Create a `Term` that represents a matcher for `foldr` notation. Reminder: `( lit ","* => foldr (x y => scopedTerm) init)` -/ partial def mkFoldrMatcher (lit x y : Name) (scopedTerm init : Term) (boundNames : Array Name) : OptionT TermElabM (List DelabKey × Term) := do -- Build the `scopedTerm` matcher with `x` and `y` as additional variables let boundNames' := boundNames |>.push x |>.push y let (keys, smatcher) ← mkExprMatcher scopedTerm boundNames' let (keys', sinit) ← mkExprMatcher init boundNames -- N.B. by swapping `x` and `y` we can just use the foldl matcher return (keys ++ keys', ← ``(matchFoldl $(quote lit) $(quote y) $(quote x) $smatcher $sinit)) /-! ### The `notation3` command -/ /-- Create a name that we can use for the `syntax` definition, using the algorithm from `notation`. -/ def mkNameFromSyntax (name? : Option (TSyntax ``namedName)) (syntaxArgs : Array (TSyntax `stx)) (attrKind : TSyntax ``Term.attrKind) : CommandElabM Name := do if let some name := name? then match name with | `(namedName| (name := $n)) => return n.getId | _ => pure () let name ← liftMacroM <| mkNameFromParserSyntax `term (mkNullNode syntaxArgs) addMacroScopeIfLocal name attrKind /-- Used when processing different kinds of variables when building the final delaborator. -/ inductive BoundValueType /-- A normal variable, delaborate its expression. -/ | normal /-- A fold variable, use the fold state (but reverse the array). -/ | foldl /-- A fold variable, use the fold state (do not reverse the array). -/ | foldr syntax prettyPrintOpt := "(" &"prettyPrint" " := " (&"true" <|> &"false") ")" /-- Interpret a `prettyPrintOpt`. The default value is `true`. -/ def getPrettyPrintOpt (opt? : Option (TSyntax ``prettyPrintOpt)) : Bool := if let some opt := opt? then match opt with | `(prettyPrintOpt| (prettyPrint := false)) => false | _ => true else true /-- If `pp.tagAppFns` is true and the head of the current expression is a constant, then delaborates the head and uses it for the ref. This causes tokens inside the syntax to refer to this constant. A consequence is that docgen will linkify the tokens. -/ def withHeadRefIfTagAppFns (d : Delab) : Delab := do let tagAppFns ← getPPOption getPPTagAppFns if tagAppFns && (← getExpr).getAppFn.consumeMData.isConst then -- Delaborate the head to register term info and get a syntax we can use for the ref. -- The syntax `f` itself is thrown away. let f ← withNaryFn <| withOptionAtCurrPos `pp.tagAppFns true delab let stx ← withRef f d -- Annotate to ensure that the full syntax still refers to the whole expression. annotateTermInfo stx else d /-- `notation3` declares notation using Lean-3-style syntax. Examples: ``` notation3 "∀ᶠ " (...) " in " f ", " r:(scoped p => Filter.eventually p f) => r notation3 "MyList[" (x", "* => foldr (a b => MyList.cons a b) MyList.nil) "]" => x ``` By default notation is unable to mention any variables defined using `variable`, but `local notation3` is able to use such local variables. Use `notation3 (prettyPrint := false)` to keep the command from generating a pretty printer for the notation. This command can be used in mathlib4 but it has an uncertain future and was created primarily for backward compatibility. -/ elab (name := notation3) doc:(docComment)? attrs?:(Parser.Term.attributes)? attrKind:Term.attrKind "notation3" prec?:(precedence)? name?:(namedName)? prio?:(namedPrio)? pp?:(ppSpace prettyPrintOpt)? items:(ppSpace notation3Item)+ " => " val:term : command => do -- We use raw `Name`s for variables. This maps variable names back to the -- identifiers that appear in `items` let mut boundIdents : Std.HashMap Name Ident := {} -- Replacements to use for the `macro` let mut boundValues : Std.HashMap Name Syntax := {} -- The names of the bound names in order, used when constructing patterns for delaboration. let mut boundNames : Array Name := #[] -- The normal/foldl/foldr type of each variable (for delaborator) let mut boundType : Std.HashMap Name BoundValueType := {} -- Function to update `syntaxArgs` and `pattArgs` using `macroArg` syntax let pushMacro (syntaxArgs : Array (TSyntax `stx)) (pattArgs : Array Syntax) (mac : TSyntax ``macroArg) := do let (syntaxArg, pattArg) ← expandMacroArg mac return (syntaxArgs.push syntaxArg, pattArgs.push pattArg) -- Arguments for the `syntax` command let mut syntaxArgs := #[] -- Arguments for the LHS pattern in the `macro`. Also used to construct the syntax -- when delaborating let mut pattArgs := #[] -- The matchers to assemble into a delaborator let mut matchers := #[] -- Whether we've seen a `(...)` item let mut hasBindersItem := false -- Whether we've seen a `scoped` item let mut hasScoped := false for item in items do match item with | `(notation3Item| $lit:str) => -- Can't use `pushMacro` since it inserts an extra variable into the pattern for `str`, which -- breaks our delaborator syntaxArgs := syntaxArgs.push (← `(stx| $lit:str)) pattArgs := pattArgs.push <| mkAtomFrom lit lit.1.isStrLit?.get! | `(notation3Item| $_:bindersItem) => if hasBindersItem then throwErrorAt item "Cannot have more than one `(...)` item." hasBindersItem := true -- HACK: Lean 3 traditionally puts a space after the main binder atom, resulting in -- notation3 "∑ "(...)", "r:(scoped f => sum f) => r -- but extBinders already has a space before it so we strip the trailing space of "∑ " if let `(stx| $lit:str) := syntaxArgs.back! then syntaxArgs := syntaxArgs.pop.push (← `(stx| $(quote lit.getString.trimRight):str)) (syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs (← `(macroArg| binders:extBinders)) | `(notation3Item| ($id:ident $sep:str* $(prec?)? => $kind ($x $y => $scopedTerm) $init)) => (syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <| ← `(macroArg| $id:ident:sepBy(term $(prec?)?, $sep:str)) -- N.B. `Syntax.getId` returns `.anonymous` for non-idents let scopedTerm' ← scopedTerm.replaceM fun s => pure boundValues[s.getId]? let init' ← init.replaceM fun s => pure boundValues[s.getId]? boundIdents := boundIdents.insert id.getId id match kind with | `(foldKind| foldl) => boundValues := boundValues.insert id.getId <| ← `(expand_foldl% ($x $y => $scopedTerm') $init' [$$(.ofElems $id),*]) boundNames := boundNames.push id.getId boundType := boundType.insert id.getId .foldl matchers := matchers.push <| mkFoldlMatcher id.getId x.getId y.getId scopedTerm init boundNames | `(foldKind| foldr) => boundValues := boundValues.insert id.getId <| ← `(expand_foldr% ($x $y => $scopedTerm') $init' [$$(.ofElems $id),*]) boundNames := boundNames.push id.getId boundType := boundType.insert id.getId .foldr matchers := matchers.push <| mkFoldrMatcher id.getId x.getId y.getId scopedTerm init boundNames | _ => throwUnsupportedSyntax | `(notation3Item| $lit:ident $(prec?)? : (scoped $scopedId:ident => $scopedTerm)) => hasScoped := true (syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <|← `(macroArg| $lit:ident:term $(prec?)?) matchers := matchers.push <| mkScopedMatcher lit.getId scopedId.getId scopedTerm boundNames let scopedTerm' ← scopedTerm.replaceM fun s => pure boundValues[s.getId]? boundIdents := boundIdents.insert lit.getId lit boundValues := boundValues.insert lit.getId <| ← `(expand_binders% ($scopedId => $scopedTerm') $$binders:extBinders, $(⟨lit.1.mkAntiquotNode `term⟩):term) boundNames := boundNames.push lit.getId | `(notation3Item| $lit:ident $(prec?)?) => (syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <|← `(macroArg| $lit:ident:term $(prec?)?) boundIdents := boundIdents.insert lit.getId lit boundValues := boundValues.insert lit.getId <| lit.1.mkAntiquotNode `term boundNames := boundNames.push lit.getId | _stx => throwUnsupportedSyntax if hasScoped && !hasBindersItem then throwError "If there is a `scoped` item then there must be a `(...)` item for binders." -- 1. The `syntax` command let name ← mkNameFromSyntax name? syntaxArgs attrKind elabCommand <| ← `(command| $[$doc]? $(attrs?)? $attrKind syntax $(prec?)? (name := $(Lean.mkIdent name)) $(prio?)? $[$syntaxArgs]* : term) -- 2. The `macro_rules` let currNamespace : Name ← getCurrNamespace -- The `syntax` command puts definitions into the current namespace; we need this -- to make the syntax `pat`. let fullName := currNamespace ++ name trace[notation3] "syntax declaration has name {fullName}" let pat : Term := ⟨mkNode fullName pattArgs⟩ let val' ← val.replaceM fun s => pure boundValues[s.getId]? let mut macroDecl ← `(macro_rules | `($pat) => `($val')) if isLocalAttrKind attrKind then -- For local notation, take section variables into account macroDecl ← `(section set_option quotPrecheck.allowSectionVars true $macroDecl end) elabCommand macroDecl -- 3. Create a delaborator if getPrettyPrintOpt pp? then matchers := matchers.push <| Mathlib.Notation3.mkExprMatcher val boundNames -- The matchers need to run in reverse order, so may as well reverse them here. let matchersM? := (matchers.reverse.mapM id).run -- We let local notations have access to `variable` declarations let matchers? ← if isLocalAttrKind attrKind then runTermElabM fun _ => matchersM? else liftTermElabM matchersM? if let some ms := matchers? then trace[notation3] "Matcher creation succeeded; assembling delaborator" let matcher ← ms.foldrM (fun m t => `($(m.2) >=> $t)) (← `(pure)) trace[notation3] "matcher:{indentD matcher}" let mut result ← `(withHeadRefIfTagAppFns `($pat)) for (name, id) in boundIdents.toArray do match boundType.getD name .normal with | .normal => result ← `(MatchState.delabVar s $(quote name) (some e) >>= fun $id => $result) | .foldl => result ← `(let $id := (MatchState.getFoldArray s $(quote name)).reverse; $result) | .foldr => result ← `(let $id := MatchState.getFoldArray s $(quote name); $result) if hasBindersItem then result ← `(`(extBinders| $$(MatchState.getBinders s)*) >>= fun binders => $result) let delabKeys : List DelabKey := ms.foldr (·.1 ++ ·) [] for key in delabKeys do trace[notation3] "Creating delaborator for key {repr key}" let delabName := name ++ Name.mkSimple s!"delab_{key.key}" let bodyCore ← `(getExpr >>= fun e => $matcher MatchState.empty >>= fun s => $result) let body ← match key with | .app _ arity => ``(withOverApp $(quote arity) $bodyCore) | _ => pure bodyCore elabCommand <| ← `( /-- Pretty printer defined by `notation3` command. -/ def $(Lean.mkIdent delabName) : Delab := whenPPOption getPPNotation <| whenNotPPOption getPPExplicit <| $body -- Avoid scope issues by adding attribute afterwards. attribute [$attrKind delab $(mkIdent key.key)] $(Lean.mkIdent delabName)) trace[notation3] "Defined delaborator {currNamespace ++ delabName}" else logWarning s!"\ Was not able to generate a pretty printer for this notation. \ If you do not expect it to be pretty printable, then you can use \ `notation3 (prettyPrint := false)`. \ If the notation expansion refers to section variables, be sure to do `local notation3`. \ Otherwise, you might be able to adjust the notation expansion to make it matchable; \ pretty printing relies on deriving an expression matcher from the expansion. \ (Use `set_option trace.notation3 true` to get some debug information.)" initialize Batteries.Linter.UnreachableTactic.addIgnoreTacticKind ``«notation3» /-! `scoped[ns]` support -/ macro_rules | `($[$doc]? $(attr)? scoped[$ns] notation3 $(prec)? $(n)? $(prio)? $(pp)? $items* => $t) => `(with_weak_namespace $(mkIdentFrom ns <| rootNamespace ++ ns.getId) $[$doc]? $(attr)? scoped notation3 $(prec)? $(n)? $(prio)? $(pp)? $items* => $t) end Notation3 end Mathlib
Basic.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.Algebra.Subalgebra.Prod import Mathlib.Algebra.Algebra.Subalgebra.Tower import Mathlib.LinearAlgebra.Basis.Basic import Mathlib.LinearAlgebra.Prod /-! # Adjoining elements to form subalgebras This file contains basic results on `Algebra.adjoin`. ## Tags adjoin, algebra -/ assert_not_exists Polynomial universe uR uS uA uB open Module Submodule Subsemiring open scoped Pointwise variable {R : Type uR} {S : Type uS} {A : Type uA} {B : Type uB} namespace Algebra section Semiring variable [CommSemiring R] [CommSemiring S] [Semiring A] [Semiring B] variable [Algebra R S] [Algebra R A] [Algebra S A] [Algebra R B] [IsScalarTower R S A] variable {s t : Set A} variable (R A) variable {A} (s) theorem adjoin_prod_le (s : Set A) (t : Set B) : adjoin R (s ×ˢ t) ≤ (adjoin R s).prod (adjoin R t) := adjoin_le <| Set.prod_mono subset_adjoin subset_adjoin theorem adjoin_inl_union_inr_eq_prod (s) (t) : adjoin R (LinearMap.inl R A B '' (s ∪ {1}) ∪ LinearMap.inr R A B '' (t ∪ {1})) = (adjoin R s).prod (adjoin R t) := by apply le_antisymm · simp only [adjoin_le_iff, Set.insert_subset_iff, Subalgebra.zero_mem, Subalgebra.one_mem, subset_adjoin,-- the rest comes from `squeeze_simp` Set.union_subset_iff, LinearMap.coe_inl, Set.mk_preimage_prod_right, Set.image_subset_iff, SetLike.mem_coe, Set.mk_preimage_prod_left, LinearMap.coe_inr, and_self_iff, Set.union_singleton, Subalgebra.coe_prod] · rintro ⟨a, b⟩ ⟨ha, hb⟩ let P := adjoin R (LinearMap.inl R A B '' (s ∪ {1}) ∪ LinearMap.inr R A B '' (t ∪ {1})) have Ha : (a, (0 : B)) ∈ adjoin R (LinearMap.inl R A B '' (s ∪ {1})) := mem_adjoin_of_map_mul R LinearMap.inl_map_mul ha have Hb : ((0 : A), b) ∈ adjoin R (LinearMap.inr R A B '' (t ∪ {1})) := mem_adjoin_of_map_mul R LinearMap.inr_map_mul hb replace Ha : (a, (0 : B)) ∈ P := adjoin_mono Set.subset_union_left Ha replace Hb : ((0 : A), b) ∈ P := adjoin_mono Set.subset_union_right Hb simpa [P] using Subalgebra.add_mem _ Ha Hb variable (A) in theorem adjoin_algebraMap (s : Set S) : adjoin R (algebraMap S A '' s) = (adjoin R s).map (IsScalarTower.toAlgHom R S A) := adjoin_image R (IsScalarTower.toAlgHom R S A) s theorem adjoin_algebraMap_image_union_eq_adjoin_adjoin (s : Set S) (t : Set A) : adjoin R (algebraMap S A '' s ∪ t) = (adjoin (adjoin R s) t).restrictScalars R := le_antisymm (closure_mono <| Set.union_subset (Set.range_subset_iff.2 fun r => Or.inl ⟨algebraMap R (adjoin R s) r, (IsScalarTower.algebraMap_apply _ _ _ _).symm⟩) (Set.union_subset_union_left _ fun _ ⟨_x, hx, hxs⟩ => hxs ▸ ⟨⟨_, subset_adjoin hx⟩, rfl⟩)) (closure_le.2 <| Set.union_subset (Set.range_subset_iff.2 fun x => adjoin_mono Set.subset_union_left <| Algebra.adjoin_algebraMap R A s ▸ ⟨x, x.prop, rfl⟩) (Set.Subset.trans Set.subset_union_right subset_adjoin)) theorem adjoin_adjoin_of_tower (s : Set A) : adjoin S (adjoin R s : Set A) = adjoin S s := by apply le_antisymm (adjoin_le _) · exact adjoin_mono subset_adjoin · change adjoin R s ≤ (adjoin S s).restrictScalars R refine adjoin_le ?_ -- Porting note: unclear why this was broken have : (Subalgebra.restrictScalars R (adjoin S s) : Set A) = adjoin S s := rfl rw [this] exact subset_adjoin theorem Subalgebra.restrictScalars_adjoin {s : Set A} : (adjoin S s).restrictScalars R = (IsScalarTower.toAlgHom R S A).range ⊔ adjoin R s := by refine le_antisymm (fun _ hx ↦ adjoin_induction (fun x hx ↦ le_sup_right (α := Subalgebra R A) (subset_adjoin hx)) (fun x ↦ le_sup_left (α := Subalgebra R A) ⟨x, rfl⟩) (fun _ _ _ _ ↦ add_mem) (fun _ _ _ _ ↦ mul_mem) <| (Subalgebra.mem_restrictScalars _).mp hx) (sup_le ?_ <| adjoin_le subset_adjoin) rintro _ ⟨x, rfl⟩; exact algebraMap_mem (adjoin S s) x @[simp] theorem adjoin_top {A} [Semiring A] [Algebra S A] (t : Set A) : adjoin (⊤ : Subalgebra R S) t = (adjoin S t).restrictScalars (⊤ : Subalgebra R S) := let equivTop : Subalgebra (⊤ : Subalgebra R S) A ≃o Subalgebra S A := { toFun := fun s => { s with algebraMap_mem' := fun r => s.algebraMap_mem ⟨r, trivial⟩ } invFun := fun s => s.restrictScalars _ left_inv := fun _ => SetLike.coe_injective rfl right_inv := fun _ => SetLike.coe_injective rfl map_rel_iff' := @fun _ _ => Iff.rfl } le_antisymm (adjoin_le <| show t ⊆ adjoin S t from subset_adjoin) (equivTop.symm_apply_le.mpr <| adjoin_le <| show t ⊆ adjoin (⊤ : Subalgebra R S) t from subset_adjoin) end Semiring section CommSemiring variable [CommSemiring R] [CommSemiring A] variable [Algebra R A] {s t : Set A} variable (R s t) theorem adjoin_union_eq_adjoin_adjoin : adjoin R (s ∪ t) = (adjoin (adjoin R s) t).restrictScalars R := by simpa using adjoin_algebraMap_image_union_eq_adjoin_adjoin R s t variable {R} theorem pow_smul_mem_of_smul_subset_of_mem_adjoin [CommSemiring B] [Algebra R B] [Algebra A B] [IsScalarTower R A B] (r : A) (s : Set B) (B' : Subalgebra R B) (hs : r • s ⊆ B') {x : B} (hx : x ∈ adjoin R s) (hr : algebraMap A B r ∈ B') : ∃ n₀ : ℕ, ∀ n ≥ n₀, r ^ n • x ∈ B' := by change x ∈ Subalgebra.toSubmodule (adjoin R s) at hx rw [adjoin_eq_span, Finsupp.mem_span_iff_linearCombination] at hx rcases hx with ⟨l, rfl : (l.sum fun (i : Submonoid.closure s) (c : R) => c • (i : B)) = x⟩ choose n₁ n₂ using fun x : Submonoid.closure s => Submonoid.pow_smul_mem_closure_smul r s x.prop use l.support.sup n₁ intro n hn rw [Finsupp.smul_sum] refine B'.toSubmodule.sum_mem ?_ intro a ha have : n ≥ n₁ a := le_trans (Finset.le_sup ha) hn dsimp only rw [← tsub_add_cancel_of_le this, pow_add, ← smul_smul, ← IsScalarTower.algebraMap_smul A (l a) (a : B), smul_smul (r ^ n₁ a), mul_comm, ← smul_smul, smul_def, map_pow, IsScalarTower.algebraMap_smul] apply Subalgebra.mul_mem _ (Subalgebra.pow_mem _ hr _) _ refine Subalgebra.smul_mem _ ?_ _ change _ ∈ B'.toSubmonoid rw [← Submonoid.closure_eq B'.toSubmonoid] apply Submonoid.closure_mono hs (n₂ a) theorem pow_smul_mem_adjoin_smul (r : R) (s : Set A) {x : A} (hx : x ∈ adjoin R s) : ∃ n₀ : ℕ, ∀ n ≥ n₀, r ^ n • x ∈ adjoin R (r • s) := pow_smul_mem_of_smul_subset_of_mem_adjoin r s _ subset_adjoin hx (Subalgebra.algebraMap_mem _ _) lemma adjoin_nonUnitalSubalgebra_eq_span (s : NonUnitalSubalgebra R A) : Subalgebra.toSubmodule (adjoin R (s : Set A)) = span R {1} ⊔ s.toSubmodule := by rw [adjoin_eq_span, Submonoid.closure_eq_one_union, span_union, ← NonUnitalAlgebra.adjoin_eq_span, NonUnitalAlgebra.adjoin_eq] end CommSemiring end Algebra open Algebra Subalgebra section variable (F E : Type*) {K : Type*} [CommSemiring E] [Semiring K] [SMul F E] [Algebra E K] variable [CommSemiring F] [Algebra F K] [IsScalarTower F E K] (L : Subalgebra F K) {F} /-- If `K / E / F` is a ring extension tower, `L` is a subalgebra of `K / F`, then `E[L]` is generated by any basis of `L / F` as an `E`-module. -/ theorem Subalgebra.adjoin_eq_span_basis {ι : Type*} (bL : Basis ι F L) : toSubmodule (adjoin E (L : Set K)) = span E (Set.range fun i : ι ↦ (bL i).1) := L.adjoin_eq_span_of_eq_span E <| by simpa only [← L.range_val, Submodule.map_span, Submodule.map_top, ← Set.range_comp] using congr_arg (Submodule.map L.val) bL.span_eq.symm theorem Algebra.restrictScalars_adjoin (F : Type*) [CommSemiring F] {E : Type*} [CommSemiring E] [Algebra F E] (K : Subalgebra F E) (S : Set E) : (Algebra.adjoin K S).restrictScalars F = Algebra.adjoin F (K ∪ S) := by conv_lhs => rw [← Algebra.adjoin_eq K, ← Algebra.adjoin_union_eq_adjoin_adjoin] /-- If `E / L / F` and `E / L' / F` are two ring extension towers, `L ≃ₐ[F] L'` is an isomorphism compatible with `E / L` and `E / L'`, then for any subset `S` of `E`, `L[S]` and `L'[S]` are equal as subalgebras of `E / F`. -/ theorem Algebra.restrictScalars_adjoin_of_algEquiv {F E L L' : Type*} [CommSemiring F] [CommSemiring L] [CommSemiring L'] [Semiring E] [Algebra F L] [Algebra L E] [Algebra F L'] [Algebra L' E] [Algebra F E] [IsScalarTower F L E] [IsScalarTower F L' E] (i : L ≃ₐ[F] L') (hi : algebraMap L E = (algebraMap L' E) ∘ i) (S : Set E) : (Algebra.adjoin L S).restrictScalars F = (Algebra.adjoin L' S).restrictScalars F := by apply_fun Subalgebra.toSubsemiring using fun K K' h ↦ by rwa [SetLike.ext'_iff] at h ⊢ change Subsemiring.closure _ = Subsemiring.closure _ rw [hi, Set.range_comp, EquivLike.range_eq_univ, Set.image_univ] end
FundThmCalculus.lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import Mathlib.MeasureTheory.Integral.Bochner.Set /-! # Fundamental theorem of calculus for set integrals This file proves a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integrals. See `Filter.Tendsto.integral_sub_linear_isLittleO_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ ae μ`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.smallSets`, i.e. for any `ε>0` there exists `t ∈ l` such that `‖∫ x in s, f x ∂μ - μ s • c‖ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. -/ open Filter MeasureTheory Topology Asymptotics Metric variable {X E ι : Type*} [MeasurableSpace X] [NormedAddCommGroup E] [NormedSpace ℝ E] [CompleteSpace E] /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ ae μ`, then `∫ x in s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.smallSets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `μ.real (s i)` in the actual statement. Often there is a good formula for `μ.real (s i)`, so the formalization can take an optional argument `m` with this formula and a proof of `(fun i => μ.real (s i)) =ᶠ[li] m`. Without these arguments, `m i = μ.real (s i)` is used in the output. -/ theorem Filter.Tendsto.integral_sub_linear_isLittleO_ae {μ : Measure X} {l : Filter X} [l.IsMeasurablyGenerated] {f : X → E} {b : E} (h : Tendsto f (l ⊓ ae μ) (𝓝 b)) (hfm : StronglyMeasurableAtFilter f l μ) (hμ : μ.FiniteAtFilter l) {s : ι → Set X} {li : Filter ι} (hs : Tendsto s li l.smallSets) (m : ι → ℝ := fun i => μ.real (s i)) (hsμ : (fun i => μ.real (s i)) =ᶠ[li] m := by rfl) : (fun i => (∫ x in s i, f x ∂μ) - m i • b) =o[li] m := by suffices (fun s => (∫ x in s, f x ∂μ) - μ.real s • b) =o[l.smallSets] fun s => μ.real s from (this.comp_tendsto hs).congr' (hsμ.mono fun a ha => by dsimp only [Function.comp_apply] at ha ⊢; rw [ha]) hsμ refine isLittleO_iff.2 fun ε ε₀ => ?_ have : ∀ᶠ s in l.smallSets, ∀ᵐ x ∂μ, x ∈ s → f x ∈ closedBall b ε := eventually_smallSets_eventually.2 (h.eventually <| closedBall_mem_nhds _ ε₀) filter_upwards [hμ.eventually, (hμ.integrableAtFilter_of_tendsto_ae hfm h).eventually, hfm.eventually, this] simp only [mem_closedBall, dist_eq_norm] intro s hμs h_integrable hfm h_norm rw [← setIntegral_const, ← integral_sub h_integrable (integrableOn_const hμs.ne), Real.norm_eq_abs, abs_of_nonneg measureReal_nonneg] exact norm_setIntegral_le_of_norm_le_const_ae' hμs h_norm /-- Fundamental theorem of calculus for set integrals, `nhdsWithin` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a` within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li` provided that `s i` tends to `(𝓝[t] a).smallSets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `μ.real (s i)` in the actual statement. Often there is a good formula for `μ.real (s i)`, so the formalization can take an optional argument `m` with this formula and a proof of `(fun i => μ.real (s i)) =ᶠ[li] m`. Without these arguments, `m i = μ.real (s i)` is used in the output. -/ theorem ContinuousWithinAt.integral_sub_linear_isLittleO_ae [TopologicalSpace X] [OpensMeasurableSpace X] {μ : Measure X} [IsLocallyFiniteMeasure μ] {x : X} {t : Set X} {f : X → E} (hx : ContinuousWithinAt f t x) (ht : MeasurableSet t) (hfm : StronglyMeasurableAtFilter f (𝓝[t] x) μ) {s : ι → Set X} {li : Filter ι} (hs : Tendsto s li (𝓝[t] x).smallSets) (m : ι → ℝ := fun i => μ.real (s i)) (hsμ : (fun i => μ.real (s i)) =ᶠ[li] m := by rfl) : (fun i => (∫ x in s i, f x ∂μ) - m i • f x) =o[li] m := haveI : (𝓝[t] x).IsMeasurablyGenerated := ht.nhdsWithin_isMeasurablyGenerated _ (hx.mono_left inf_le_left).integral_sub_linear_isLittleO_ae hfm (μ.finiteAt_nhdsWithin x t) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).smallSets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `μ.real (s i)` in the actual statement. Often there is a good formula for `μ.real (s i)`, so the formalization can take an optional argument `m` with this formula and a proof of `(fun i => μ.real (s i)) =ᶠ[li] m`. Without these arguments, `m i = μ.real (s i)` is used in the output. -/ theorem ContinuousAt.integral_sub_linear_isLittleO_ae [TopologicalSpace X] [OpensMeasurableSpace X] {μ : Measure X} [IsLocallyFiniteMeasure μ] {x : X} {f : X → E} (hx : ContinuousAt f x) (hfm : StronglyMeasurableAtFilter f (𝓝 x) μ) {s : ι → Set X} {li : Filter ι} (hs : Tendsto s li (𝓝 x).smallSets) (m : ι → ℝ := fun i => μ.real (s i)) (hsμ : (fun i => μ.real (s i)) =ᶠ[li] m := by rfl) : (fun i => (∫ x in s i, f x ∂μ) - m i • f x) =o[li] m := (hx.mono_left inf_le_left).integral_sub_linear_isLittleO_ae hfm (μ.finiteAt_nhds x) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhdsWithin` version: if `μ` is a locally finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).smallSets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `μ.real (s i)` in the actual statement. Often there is a good formula for `μ.real (s i)`, so the formalization can take an optional argument `m` with this formula and a proof of `(fun i => μ.real (s i)) =ᶠ[li] m`. Without these arguments, `m i = μ.real (s i)` is used in the output. -/ theorem ContinuousOn.integral_sub_linear_isLittleO_ae [TopologicalSpace X] [OpensMeasurableSpace X] [SecondCountableTopologyEither X E] {μ : Measure X} [IsLocallyFiniteMeasure μ] {x : X} {t : Set X} {f : X → E} (hft : ContinuousOn f t) (hx : x ∈ t) (ht : MeasurableSet t) {s : ι → Set X} {li : Filter ι} (hs : Tendsto s li (𝓝[t] x).smallSets) (m : ι → ℝ := fun i => μ.real (s i)) (hsμ : (fun i => μ.real (s i)) =ᶠ[li] m := by rfl) : (fun i => (∫ x in s i, f x ∂μ) - m i • f x) =o[li] m := (hft x hx).integral_sub_linear_isLittleO_ae ht ⟨t, self_mem_nhdsWithin, hft.aestronglyMeasurable ht⟩ hs m hsμ
ssrnotations.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) (******************************************************************************) (* - Reserved notation for various arithmetic and algebraic operations: *) (* e.[a1, ..., a_n] evaluation (e.g., polynomials). *) (* e`_i indexing (number list, integer pi-part). *) (* x^-1 inverse (group, field). *) (* x *+ n, x *- n integer multiplier (modules and rings). *) (* x ^+ n, x ^- n integer exponent (groups and rings). *) (* x *: A, A :* x external product (scaling/module product in rings, *) (* left/right cosets in groups). *) (* A :&: B intersection (of sets, groups, subspaces, ...). *) (* A :|: B, a |: B union, union with a singleton (of sets). *) (* A :\: B, A :\ b relative complement (of sets, subspaces, ...). *) (* <<A>>, <[a]> generated group/subspace, generated cycle/line. *) (* 'C[x], 'C_A[x] point centralisers (in groups and F-algebras). *) (* 'C(A), 'C_B(A) centralisers (in groups and matrix and F_algebras). *) (* 'Z(A) centers (in groups and matrix and F-algebras). *) (* m %/ d, m %% d Euclidean division and remainder (nat, polynomials). *) (* d %| m Euclidean divisibility (nat, polynomial). *) (* m = n %[mod d] equality mod d (also defined for <>, ==, and !=). *) (* e^`(n) nth formal derivative (groups, polynomials). *) (* e^`() simple formal derivative (polynomials only). *) (* `|x| norm, absolute value, distance (rings, int, nat). *) (* x <= y ?= iff C x is less than y, and equal iff C holds (nat, rings). *) (* x <= y :> T, etc cast comparison (rings, all comparison operators). *) (* [rec a1, ..., an] standard shorthand for hidden recursor (see prime.v). *) (* The interpretation of these notations is not defined here, but the *) (* declarations help maintain consistency across the library. *) (******************************************************************************) (* Reserved notation for evaluation *) Reserved Notation "e .[ x ]" (left associativity, format "e .[ x ]"). Reserved Notation "e .[ x1 , x2 , .. , xn ]" (left associativity, format "e '[ ' .[ x1 , '/' x2 , '/' .. , '/' xn ] ']'"). (* Reserved notation for subscripting and superscripting *) Reserved Notation "s `_ i" (at level 3, i at level 2, left associativity, format "s `_ i"). Reserved Notation "x ^-1" (left associativity, format "x ^-1"). (* Reserved notation for integer multipliers and exponents *) Reserved Notation "x *+ n" (at level 40, left associativity). Reserved Notation "x *- n" (at level 40, left associativity). Reserved Notation "x ^+ n" (at level 29, left associativity). Reserved Notation "x ^- n" (at level 29, left associativity). (* Reserved notation for external multiplication. *) Reserved Notation "x *: A" (at level 40). Reserved Notation "A :* x" (at level 40). (* Reserved notation for conjugation and lifting of actions to sets. *) Reserved Notation "x ^*" (format "x ^*", left associativity). (* Reserved notation for set-theoretic operations. *) Reserved Notation "A :&: B" (at level 48, left associativity). Reserved Notation "A :|: B" (at level 52, left associativity). Reserved Notation "a |: A" (at level 52, left associativity). Reserved Notation "A :\: B" (at level 50, left associativity). Reserved Notation "A :\ b" (at level 50, left associativity). (* Reserved notation for generated structures *) Reserved Notation "<< A >>" (format "<< A >>"). Reserved Notation "<[ a ] >" (format "<[ a ] >"). (* Reserved notation for the order of an element (group, polynomial, etc) *) Reserved Notation "#[ x ]" (format "#[ x ]"). (* Reserved notation for centralisers and centers. *) Reserved Notation "''C' [ x ]" (format "''C' [ x ]"). Reserved Notation "''C_' A [ x ]" (A at level 2, format "''C_' A [ x ]"). Reserved Notation "''C' ( A )" (format "''C' ( A )"). Reserved Notation "''C_' B ( A )" (B at level 2, format "''C_' B ( A )"). Reserved Notation "''Z' ( A )" (format "''Z' ( A )"). (* Compatibility with group action centraliser notation. *) Reserved Notation "''C_' ( A ) [ x ]". Reserved Notation "''C_' ( B ) ( A )". Reserved Notation "''C' [ x | to ]" (format "''C' [ x | to ]"). Reserved Notation "''C' ( S | to )" (format "''C' ( S | to )"). Reserved Notation "''C_' A [ x | to ]" (A at level 2, format "''C_' A [ x | to ]"). Reserved Notation "''C_' A ( S | to )" (A at level 2, format "''C_' A ( S | to )"). Reserved Notation "''C_' ( A ) [ x | to ]". Reserved Notation "''C_' ( A ) ( S | to )". Reserved Notation "''C_' ( | to ) [ a ]" (format "''C_' ( | to ) [ a ]"). Reserved Notation "''C_' ( G | to ) [ a ]" (format "''C_' ( G | to ) [ a ]"). Reserved Notation "''C_' ( | to ) ( A )" (format "''C_' ( | to ) ( A )"). Reserved Notation "''C_' ( G | to ) ( A )" (format "''C_' ( G | to ) ( A )"). (* Bionomial coefficient *) Reserved Notation "''C' ( n , m )" (format "''C' ( n , m )"). (* Reserved notation for Euclidean division and divisibility. *) Reserved Notation "m %/ d" (at level 40, no associativity). Reserved Notation "m %% d" (at level 40, no associativity). Reserved Notation "m %| d" (at level 70, no associativity). #[warning="-postfix-notation-not-level-1"] Reserved Notation "m = n %[mod d ]" (format "'[hv ' m '/' = n '/' %[mod d ] ']'"). #[warning="-postfix-notation-not-level-1"] Reserved Notation "m == n %[mod d ]" (at level 70, n at next level, format "'[hv ' m '/' == n '/' %[mod d ] ']'"). #[warning="-postfix-notation-not-level-1"] Reserved Notation "m <> n %[mod d ]" (format "'[hv ' m '/' <> n '/' %[mod d ] ']'"). #[warning="-postfix-notation-not-level-1"] Reserved Notation "m != n %[mod d ]" (at level 70, n at next level, format "'[hv ' m '/' != n '/' %[mod d ] ']'"). (* Reserved notation for derivatives. *) Reserved Notation "a ^` ()" (format "a ^` ()"). Reserved Notation "a ^` ( n )" (format "a ^` ( n )"). (* Reserved notation for absolute value. *) Reserved Notation "`| x |" (format "`| x |"). (* Reserved notation for conditional comparison *) Reserved Notation "x <= y ?= 'iff' c" (c at next level, format "x '[hv' <= y '/' ?= 'iff' c ']'"). (* Reserved notation for cast comparison. *) Reserved Notation "x <= y :> T". Reserved Notation "x >= y :> T". Reserved Notation "x < y :> T". Reserved Notation "x > y :> T". Reserved Notation "x <= y ?= 'iff' c :> T" (c at next level, format "x '[hv' <= y '/' ?= 'iff' c :> T ']'"). (* Reserved notation for dot product. *) Reserved Notation "'[ u , v ]" (format "'[hv' ''[' u , '/ ' v ] ']'"). Reserved Notation "'[ u ]" (format "''[' u ]").
CompletePartialOrder.lean
/- Copyright (c) 2023 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import Mathlib.Order.OmegaCompletePartialOrder /-! # Complete Partial Orders This file considers complete partial orders (sometimes called directedly complete partial orders). These are partial orders for which every directed set has a least upper bound. ## Main declarations - `CompletePartialOrder`: Typeclass for (directly) complete partial orders. ## Main statements - `CompletePartialOrder.toOmegaCompletePartialOrder`: A complete partial order is an ω-complete partial order. - `CompleteLattice.toCompletePartialOrder`: A complete lattice is a complete partial order. ## References - [B. A. Davey and H. A. Priestley, Introduction to lattices and order][davey_priestley] ## Tags complete partial order, directedly complete partial order -/ variable {ι : Sort*} {α β : Type*} section CompletePartialOrder /-- Complete partial orders are partial orders where every directed set has a least upper bound. -/ class CompletePartialOrder (α : Type*) extends PartialOrder α, SupSet α where /-- For each directed set `d`, `sSup d` is the least upper bound of `d`. -/ lubOfDirected : ∀ d, DirectedOn (· ≤ ·) d → IsLUB d (sSup d) variable [CompletePartialOrder α] [Preorder β] {f : ι → α} {d : Set α} {a : α} protected lemma DirectedOn.isLUB_sSup : DirectedOn (· ≤ ·) d → IsLUB d (sSup d) := CompletePartialOrder.lubOfDirected _ protected lemma DirectedOn.le_sSup (hd : DirectedOn (· ≤ ·) d) (ha : a ∈ d) : a ≤ sSup d := hd.isLUB_sSup.1 ha protected lemma DirectedOn.sSup_le (hd : DirectedOn (· ≤ ·) d) (ha : ∀ b ∈ d, b ≤ a) : sSup d ≤ a := hd.isLUB_sSup.2 ha protected lemma Directed.le_iSup (hf : Directed (· ≤ ·) f) (i : ι) : f i ≤ ⨆ j, f j := hf.directedOn_range.le_sSup <| Set.mem_range_self _ protected lemma Directed.iSup_le (hf : Directed (· ≤ ·) f) (ha : ∀ i, f i ≤ a) : ⨆ i, f i ≤ a := hf.directedOn_range.sSup_le <| Set.forall_mem_range.2 ha --TODO: We could mimic more `sSup`/`iSup` lemmas /-- Scott-continuity takes on a simpler form in complete partial orders. -/ lemma CompletePartialOrder.scottContinuous {f : α → β} : ScottContinuous f ↔ ∀ ⦃d : Set α⦄, d.Nonempty → DirectedOn (· ≤ ·) d → IsLUB (f '' d) (f (sSup d)) := by refine ⟨fun h d hd₁ hd₂ ↦ h hd₁ hd₂ hd₂.isLUB_sSup, fun h d hne hd a hda ↦ ?_⟩ rw [hda.unique hd.isLUB_sSup] exact h hne hd open OmegaCompletePartialOrder /-- A complete partial order is an ω-complete partial order. -/ instance CompletePartialOrder.toOmegaCompletePartialOrder : OmegaCompletePartialOrder α where ωSup c := ⨆ n, c n le_ωSup c := c.directed.le_iSup ωSup_le c _ := c.directed.iSup_le end CompletePartialOrder /-- A complete lattice is a complete partial order. -/ instance CompleteLattice.toCompletePartialOrder [CompleteLattice α] : CompletePartialOrder α where sSup := sSup lubOfDirected _ _ := isLUB_sSup _
Center.lean
/- Copyright (c) 2023 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Algebra.Star.Basic import Mathlib.Algebra.Star.Pointwise import Mathlib.Algebra.Group.Center /-! # `Set.center`, `Set.centralizer` and the `star` operation -/ variable {R : Type*} [Mul R] [StarMul R] {a : R} {s : Set R} theorem Set.star_mem_center (ha : a ∈ Set.center R) : star a ∈ Set.center R where comm := by simpa only [star_mul, star_star] using fun g => congr_arg star ((mem_center_iff.1 ha).comm <| star g).symm left_assoc b c := calc star a * (b * c) = star a * (star (star b) * star (star c)) := by rw [star_star, star_star] _ = star a * star (star c * star b) := by rw [star_mul] _ = star ((star c * star b) * a) := by rw [← star_mul] _ = star (star c * (star b * a)) := by rw [ha.right_assoc] _ = star (star b * a) * c := by rw [star_mul, star_star] _ = (star a * b) * c := by rw [star_mul, star_star] right_assoc b c := calc b * c * star a = star (a * star (b * c)) := by rw [star_mul, star_star] _ = star (a * (star c * star b)) := by rw [star_mul b] _ = star ((a * star c) * star b) := by rw [ha.left_assoc] _ = b * star (a * star c) := by rw [star_mul, star_star] _ = b * (c * star a) := by rw [star_mul, star_star] theorem Set.star_centralizer : star s.centralizer = (star s).centralizer := by simp_rw [centralizer, ← commute_iff_eq] conv_lhs => simp only [← star_preimage, preimage_setOf_eq, ← commute_star_comm] conv_rhs => simp only [← image_star, forall_mem_image] theorem Set.union_star_self_comm (hcomm : ∀ x ∈ s, ∀ y ∈ s, y * x = x * y) (hcomm_star : ∀ x ∈ s, ∀ y ∈ s, y * star x = star x * y) : ∀ x ∈ s ∪ star s, ∀ y ∈ s ∪ star s, y * x = x * y := by change s ∪ star s ⊆ (s ∪ star s).centralizer simp_rw [centralizer_union, ← star_centralizer, union_subset_iff, subset_inter_iff, star_subset_star, star_subset] exact ⟨⟨hcomm, hcomm_star⟩, ⟨hcomm_star, hcomm⟩⟩ theorem Set.star_mem_centralizer' (h : ∀ a : R, a ∈ s → star a ∈ s) (ha : a ∈ Set.centralizer s) : star a ∈ Set.centralizer s := fun y hy => by simpa using congr_arg star (ha _ (h _ hy)).symm open scoped Pointwise theorem Set.star_mem_centralizer (ha : a ∈ Set.centralizer (s ∪ star s)) : star a ∈ Set.centralizer (s ∪ star s) := Set.star_mem_centralizer' (fun _x hx => hx.elim (fun hx => Or.inr <| Set.star_mem_star.mpr hx) Or.inl) ha
Weight.lean
/- Copyright (c) 2024 Antoine Chambert-Loir, María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Chambert-Loir, María Inés de Frutos-Fernández -/ import Mathlib.Data.Finsupp.Antidiagonal import Mathlib.Data.Finsupp.Order import Mathlib.LinearAlgebra.Finsupp.LinearCombination /-! # weights of Finsupp functions The theory of multivariate polynomials and power series is built on the type `σ →₀ ℕ` which gives the exponents of the monomials. Many aspects of the theory (degree, order, graded ring structure) require to classify these exponents according to their total sum `∑ i, f i`, or variants, and this files provides some API for that. ## Weight We fix a type `σ`, a semiring `R`, an `R`-module `M`, as well as a function `w : σ → M`. (The important case is `R = ℕ`.) - `Finsupp.weight` of a finitely supported function `f : σ →₀ R` with respect to `w`: it is the sum `∑ (f i) • (w i)`. It is an `AddMonoidHom` map defined using `Finsupp.linearCombination`. - `Finsupp.le_weight` says that `f s ≤ f.weight w` when `M = ℕ` - `Finsupp.le_weight_of_ne_zero` says that `w s ≤ f.weight w` for `OrderedAddCommMonoid M`, when `f s ≠ 0` and all `w i` are nonnegative. - `Finsupp.le_weight_of_ne_zero'` is the same statement for `CanonicallyOrderedAddCommMonoid M`. - `NonTorsionWeight`: all values `w s` are non torsion in `M`. - `Finsupp.weight_eq_zero_iff_eq_zero` says that `f.weight w = 0` iff `f = 0` for `NonTorsionWeight w` and `CanonicallyOrderedAddCommMonoid M`. - For `w : σ → ℕ` and `Finite σ`, `Finsupp.finite_of_nat_weight_le` proves that there are finitely many `f : σ →₀ ℕ` of bounded weight. ## Degree - `Finsupp.degree f` is the sum of all `f s`, for `s ∈ f.support`. The present choice is to have it defined as a plain function. - `Finsupp.degree_eq_zero_iff` says that `f.degree = 0` iff `f = 0`. - `Finsupp.le_degree` says that `f s ≤ f.degree`. - `Finsupp.degree_eq_weight_one` says `f.degree = f.weight 1` when `R` is a semiring. This is useful to access the additivity properties of `Finsupp.degree` - For `Finite σ`, `Finsupp.finite_of_degree_le` proves that there are finitely many `f : σ →₀ ℕ` of bounded degree. ## TODO * Maybe `Finsupp.weight w` and `Finsupp.degree` should have similar types, both `AddMonoidHom` or both functions. -/ variable {σ M R : Type*} [Semiring R] (w : σ → M) namespace Finsupp section AddCommMonoid variable [AddCommMonoid M] [Module R M] /-- The `weight` of the finitely supported function `f : σ →₀ R` with respect to `w : σ → M` is the sum `∑ i, f i • w i`. -/ noncomputable def weight : (σ →₀ R) →+ M := (Finsupp.linearCombination R w).toAddMonoidHom theorem weight_apply (f : σ →₀ R) : weight w f = Finsupp.sum f (fun i c => c • w i) := rfl theorem weight_single_index [DecidableEq σ] (s : σ) (c : M) (f : σ →₀ R) : weight (Pi.single s c) f = f s • c := linearCombination_single_index σ M R c s f theorem weight_single_one_apply [DecidableEq σ] (s : σ) (f : σ →₀ R) : weight (Pi.single s 1) f = f s := by rw [weight_single_index, smul_eq_mul, mul_one] theorem weight_single (s : σ) (r : R) : weight w (Finsupp.single s r) = r • w s := Finsupp.linearCombination_single _ _ _ variable (R) in /-- A weight function is nontorsion if its values are not torsion. -/ class NonTorsionWeight (w : σ → M) : Prop where eq_zero_of_smul_eq_zero {r : R} {s : σ} (h : r • w s = 0) : r = 0 variable (R) in /-- Without zero divisors, nonzero weight is a `NonTorsionWeight` -/ theorem nonTorsionWeight_of [NoZeroSMulDivisors R M] (hw : ∀ i : σ, w i ≠ 0) : NonTorsionWeight R w where eq_zero_of_smul_eq_zero {n s} h := by rw [smul_eq_zero, or_iff_not_imp_right] at h exact h (hw s) variable (R) in theorem NonTorsionWeight.ne_zero [Nontrivial R] [NonTorsionWeight R w] (s : σ) : w s ≠ 0 := fun h ↦ by rw [← one_smul R (w s)] at h apply zero_ne_one.symm (α := R) exact NonTorsionWeight.eq_zero_of_smul_eq_zero h variable {w} in lemma weight_sub_single_add {f : σ →₀ ℕ} {i : σ} (hi : f i ≠ 0) : (f - single i 1).weight w + w i = f.weight w := by conv_rhs => rw [← sub_add_single_one_cancel hi, weight_apply] rw [sum_add_index', sum_single_index, one_smul, weight_apply] exacts [zero_smul .., fun _ ↦ zero_smul .., fun _ _ _ ↦ add_smul ..] end AddCommMonoid section OrderedAddCommMonoid theorem le_weight (w : σ → ℕ) {s : σ} (hs : w s ≠ 0) (f : σ →₀ ℕ) : f s ≤ weight w f := by classical simp only [weight_apply, Finsupp.sum] by_cases h : s ∈ f.support · rw [Finset.sum_eq_add_sum_diff_singleton h] refine le_trans ?_ (Nat.le_add_right _ _) apply Nat.le_mul_of_pos_right exact Nat.zero_lt_of_ne_zero hs · simp only [notMem_support_iff] at h rw [h] apply zero_le variable [AddCommMonoid M] [PartialOrder M] [IsOrderedAddMonoid M] (w : σ → M) {R : Type*} [CommSemiring R] [PartialOrder R] [IsOrderedRing R] [CanonicallyOrderedAdd R] [NoZeroDivisors R] [Module R M] instance : SMulPosMono ℕ M := ⟨fun b hb m m' h ↦ by rw [← Nat.add_sub_of_le h, add_smul] exact le_add_of_nonneg_right (nsmul_nonneg hb (m' - m))⟩ variable {w} in theorem le_weight_of_ne_zero (hw : ∀ s, 0 ≤ w s) {s : σ} {f : σ →₀ ℕ} (hs : f s ≠ 0) : w s ≤ weight w f := by classical simp only [weight_apply, Finsupp.sum] trans f s • w s · apply le_smul_of_one_le_left (hw s) exact Nat.one_le_iff_ne_zero.mpr hs · rw [← Finsupp.mem_support_iff] at hs rw [Finset.sum_eq_add_sum_diff_singleton hs] exact le_add_of_nonneg_right <| Finset.sum_nonneg <| fun i _ ↦ nsmul_nonneg (hw i) (f i) end OrderedAddCommMonoid section CanonicallyOrderedAddCommMonoid variable {M : Type*} [AddCommMonoid M] [PartialOrder M] [IsOrderedAddMonoid M] [CanonicallyOrderedAdd M] (w : σ → M) theorem le_weight_of_ne_zero' {s : σ} {f : σ →₀ ℕ} (hs : f s ≠ 0) : w s ≤ weight w f := le_weight_of_ne_zero (fun _ ↦ zero_le _) hs /-- If `M` is a `CanonicallyOrderedAddCommMonoid`, then `weight f` is zero iff `f = 0`. -/ theorem weight_eq_zero_iff_eq_zero (w : σ → M) [NonTorsionWeight ℕ w] {f : σ →₀ ℕ} : weight w f = 0 ↔ f = 0 := by classical constructor · intro h ext s simp only [Finsupp.coe_zero, Pi.zero_apply] by_contra hs apply NonTorsionWeight.ne_zero ℕ w s rw [← nonpos_iff_eq_zero, ← h] exact le_weight_of_ne_zero' w hs · intro h rw [h, map_zero] theorem finite_of_nat_weight_le [Finite σ] (w : σ → ℕ) (hw : ∀ x, w x ≠ 0) (n : ℕ) : {d : σ →₀ ℕ | weight w d ≤ n}.Finite := by classical set fg := Finset.antidiagonal (Finsupp.equivFunOnFinite.symm (Function.const σ n)) with hfg suffices {d : σ →₀ ℕ | weight w d ≤ n} ⊆ ↑(fg.image fun uv => uv.fst) by exact Set.Finite.subset (Finset.finite_toSet _) this intro d hd rw [hfg] simp only [Finset.coe_image, Set.mem_image, Finset.mem_coe, Finset.mem_antidiagonal, Prod.exists, exists_and_right, exists_eq_right] use Finsupp.equivFunOnFinite.symm (Function.const σ n) - d ext x simp only [Finsupp.coe_add, Finsupp.coe_tsub, Pi.add_apply, Pi.sub_apply, Finsupp.equivFunOnFinite_symm_apply_toFun, Function.const_apply] rw [add_comm] apply Nat.sub_add_cancel apply le_trans (le_weight w (hw x) d) simpa only [Set.mem_setOf_eq] using hd end CanonicallyOrderedAddCommMonoid variable {R : Type*} [AddCommMonoid R] /-- The degree of a finsupp function. -/ def degree (d : σ →₀ R) : R := ∑ i ∈ d.support, d i theorem degree_eq_sum [Fintype σ] (f : σ →₀ R) : f.degree = ∑ i, f i := by rw [degree, Finset.sum_subset] <;> simp @[simp] theorem degree_add (a b : σ →₀ R) : (a + b).degree = a.degree + b.degree := sum_add_index' (h := fun _ ↦ id) (congrFun rfl) fun _ _ ↦ congrFun rfl @[simp] theorem degree_single (a : σ) (r : R) : (Finsupp.single a r).degree = r := Finsupp.sum_single_index (h := fun _ => id) rfl @[simp] theorem degree_zero : degree (0 : σ →₀ R) = 0 := by simp [degree] lemma degree_eq_zero_iff {R : Type*} [AddCommMonoid R] [PartialOrder R] [CanonicallyOrderedAdd R] (d : σ →₀ R) : degree d = 0 ↔ d = 0 := by simp only [degree, Finset.sum_eq_zero_iff, mem_support_iff, ne_eq, _root_.not_imp_self, DFunLike.ext_iff, coe_zero, Pi.zero_apply] theorem le_degree {R : Type*} [AddCommMonoid R] [PartialOrder R] [CanonicallyOrderedAdd R] (s : σ) (f : σ →₀ R) : f s ≤ degree f := by by_cases h : s ∈ f.support · exact CanonicallyOrderedAddCommMonoid.single_le_sum h · simp only [notMem_support_iff] at h simp only [h, zero_le] theorem degree_eq_weight_one {R : Type*} [Semiring R] : degree (R := R) (σ := σ) = weight (fun _ ↦ 1) := by ext d simp only [degree, weight_apply, smul_eq_mul, mul_one, Finsupp.sum] theorem finite_of_degree_le [Finite σ] (n : ℕ) : {f : σ →₀ ℕ | degree f ≤ n}.Finite := by simp_rw [degree_eq_weight_one] refine finite_of_nat_weight_le (Function.const σ 1) ?_ n intro _ simp only [Function.const_apply, ne_eq, one_ne_zero, not_false_eq_true] end Finsupp
Add.lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.Analysis.Calculus.FDeriv.Linear import Mathlib.Analysis.Calculus.FDeriv.Comp import Mathlib.Analysis.Calculus.FDeriv.Const /-! # Additive operations on derivatives For detailed documentation of the Fréchet derivative, see the module docstring of `Analysis/Calculus/FDeriv/Basic.lean`. This file contains the usual formulas (and existence assertions) for the derivative of * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions -/ open Filter Asymptotics ContinuousLinearMap noncomputable section section variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] variable {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] variable {f g : E → F} variable {f' g' : E →L[𝕜] F} variable {x : E} variable {s : Set E} variable {L : Filter E} section ConstSMul variable {R : Type*} [Semiring R] [Module R F] [SMulCommClass 𝕜 R F] [ContinuousConstSMul R F] /-! ### Derivative of a function multiplied by a constant -/ @[fun_prop] theorem HasStrictFDerivAt.fun_const_smul (h : HasStrictFDerivAt f f' x) (c : R) : HasStrictFDerivAt (fun x => c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).hasStrictFDerivAt.comp x h @[fun_prop] theorem HasStrictFDerivAt.const_smul (h : HasStrictFDerivAt f f' x) (c : R) : HasStrictFDerivAt (c • f) (c • f') x := h.fun_const_smul c theorem HasFDerivAtFilter.fun_const_smul (h : HasFDerivAtFilter f f' x L) (c : R) : HasFDerivAtFilter (fun x => c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).hasFDerivAtFilter.comp x h tendsto_map theorem HasFDerivAtFilter.const_smul (h : HasFDerivAtFilter f f' x L) (c : R) : HasFDerivAtFilter (c • f) (c • f') x L := h.fun_const_smul c @[fun_prop] nonrec theorem HasFDerivWithinAt.fun_const_smul (h : HasFDerivWithinAt f f' s x) (c : R) : HasFDerivWithinAt (fun x => c • f x) (c • f') s x := h.const_smul c @[fun_prop] nonrec theorem HasFDerivWithinAt.const_smul (h : HasFDerivWithinAt f f' s x) (c : R) : HasFDerivWithinAt (c • f) (c • f') s x := h.const_smul c @[fun_prop] nonrec theorem HasFDerivAt.fun_const_smul (h : HasFDerivAt f f' x) (c : R) : HasFDerivAt (fun x => c • f x) (c • f') x := h.const_smul c @[fun_prop] nonrec theorem HasFDerivAt.const_smul (h : HasFDerivAt f f' x) (c : R) : HasFDerivAt (c • f) (c • f') x := h.const_smul c @[fun_prop] theorem DifferentiableWithinAt.fun_const_smul (h : DifferentiableWithinAt 𝕜 f s x) (c : R) : DifferentiableWithinAt 𝕜 (fun y => c • f y) s x := (h.hasFDerivWithinAt.const_smul c).differentiableWithinAt @[fun_prop] theorem DifferentiableWithinAt.const_smul (h : DifferentiableWithinAt 𝕜 f s x) (c : R) : DifferentiableWithinAt 𝕜 (c • f) s x := h.fun_const_smul c @[fun_prop] theorem DifferentiableAt.fun_const_smul (h : DifferentiableAt 𝕜 f x) (c : R) : DifferentiableAt 𝕜 (fun y => c • f y) x := (h.hasFDerivAt.const_smul c).differentiableAt @[fun_prop] theorem DifferentiableAt.const_smul (h : DifferentiableAt 𝕜 f x) (c : R) : DifferentiableAt 𝕜 (c • f) x := (h.hasFDerivAt.const_smul c).differentiableAt @[fun_prop] theorem DifferentiableOn.fun_const_smul (h : DifferentiableOn 𝕜 f s) (c : R) : DifferentiableOn 𝕜 (fun y => c • f y) s := fun x hx => (h x hx).const_smul c @[fun_prop] theorem DifferentiableOn.const_smul (h : DifferentiableOn 𝕜 f s) (c : R) : DifferentiableOn 𝕜 (c • f) s := fun x hx => (h x hx).const_smul c @[fun_prop] theorem Differentiable.fun_const_smul (h : Differentiable 𝕜 f) (c : R) : Differentiable 𝕜 fun y => c • f y := fun x => (h x).const_smul c @[fun_prop] theorem Differentiable.const_smul (h : Differentiable 𝕜 f) (c : R) : Differentiable 𝕜 (c • f) := fun x => (h x).const_smul c theorem fderivWithin_fun_const_smul (hxs : UniqueDiffWithinAt 𝕜 s x) (h : DifferentiableWithinAt 𝕜 f s x) (c : R) : fderivWithin 𝕜 (fun y => c • f y) s x = c • fderivWithin 𝕜 f s x := (h.hasFDerivWithinAt.const_smul c).fderivWithin hxs theorem fderivWithin_const_smul (hxs : UniqueDiffWithinAt 𝕜 s x) (h : DifferentiableWithinAt 𝕜 f s x) (c : R) : fderivWithin 𝕜 (c • f) s x = c • fderivWithin 𝕜 f s x := fderivWithin_fun_const_smul hxs h c /-- If `c` is invertible, `c • f` is differentiable at `x` within `s` if and only if `f` is. -/ lemma differentiableWithinAt_smul_iff (c : R) [Invertible c] : DifferentiableWithinAt 𝕜 (c • f) s x ↔ DifferentiableWithinAt 𝕜 f s x := by refine ⟨fun h ↦ ?_, fun h ↦ h.const_smul c⟩ apply (h.const_smul ⅟c).congr_of_eventuallyEq ?_ (by simp) filter_upwards with x using by simp /-- A version of `fderivWithin_const_smul` without differentiability hypothesis: in return, the constant `c` must be invertible, i.e. if `R` is a field. -/ theorem fderivWithin_const_smul_of_invertible (c : R) [Invertible c] (hs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (c • f) s x = c • fderivWithin 𝕜 f s x := by by_cases h : DifferentiableWithinAt 𝕜 f s x · exact (h.hasFDerivWithinAt.const_smul c).fderivWithin hs · obtain (rfl | hc) := eq_or_ne c 0 · simp have : ¬DifferentiableWithinAt 𝕜 (c • f) s x := by contrapose! h exact (differentiableWithinAt_smul_iff c).mp h simp [fderivWithin_zero_of_not_differentiableWithinAt h, fderivWithin_zero_of_not_differentiableWithinAt this] /-- Special case of `fderivWithin_const_smul_of_invertible` over a field: any constant is allowed -/ lemma fderivWithin_const_smul_of_field (c : 𝕜) (hs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (c • f) s x = c • fderivWithin 𝕜 f s x := by obtain (rfl | ha) := eq_or_ne c 0 · simp · have : Invertible c := invertibleOfNonzero ha ext x simp [fderivWithin_const_smul_of_invertible c (f := f) hs] @[deprecated (since := "2025-06-14")] alias fderivWithin_const_smul' := fderivWithin_const_smul theorem fderiv_fun_const_smul (h : DifferentiableAt 𝕜 f x) (c : R) : fderiv 𝕜 (fun y => c • f y) x = c • fderiv 𝕜 f x := (h.hasFDerivAt.const_smul c).fderiv theorem fderiv_const_smul (h : DifferentiableAt 𝕜 f x) (c : R) : fderiv 𝕜 (c • f) x = c • fderiv 𝕜 f x := (h.hasFDerivAt.const_smul c).fderiv /-- If `c` is invertible, `c • f` is differentiable at `x` if and only if `f` is. -/ lemma differentiableAt_smul_iff (c : R) [Invertible c] : DifferentiableAt 𝕜 (c • f) x ↔ DifferentiableAt 𝕜 f x := by rw [← differentiableWithinAt_univ, differentiableWithinAt_smul_iff, differentiableWithinAt_univ] /-- A version of `fderiv_const_smul` without differentiability hypothesis: in return, the constant `c` must be invertible, i.e. if `R` is a field. -/ theorem fderiv_const_smul_of_invertible (c : R) [Invertible c] : fderiv 𝕜 (c • f) x = c • fderiv 𝕜 f x := by simp [← fderivWithin_univ, fderivWithin_const_smul_of_invertible c uniqueDiffWithinAt_univ] /-- Special case of `fderiv_const_smul_of_invertible` over a field: any constant is allowed -/ lemma fderiv_const_smul_of_field (c : 𝕜) : fderiv 𝕜 (c • f) = c • fderiv 𝕜 f := by simp_rw [← fderivWithin_univ] ext x simp [fderivWithin_const_smul_of_field c uniqueDiffWithinAt_univ] @[deprecated (since := "2025-06-14")] alias fderiv_const_smul' := fderiv_const_smul end ConstSMul section Add /-! ### Derivative of the sum of two functions -/ @[fun_prop] nonrec theorem HasStrictFDerivAt.fun_add (hf : HasStrictFDerivAt f f' x) (hg : HasStrictFDerivAt g g' x) : HasStrictFDerivAt (fun y => f y + g y) (f' + g') x := .of_isLittleO <| (hf.isLittleO.add hg.isLittleO).congr_left fun y => by simp only [map_sub, add_apply] abel @[fun_prop] nonrec theorem HasStrictFDerivAt.add (hf : HasStrictFDerivAt f f' x) (hg : HasStrictFDerivAt g g' x) : HasStrictFDerivAt (f + g) (f' + g') x := hf.fun_add hg theorem HasFDerivAtFilter.fun_add (hf : HasFDerivAtFilter f f' x L) (hg : HasFDerivAtFilter g g' x L) : HasFDerivAtFilter (fun y => f y + g y) (f' + g') x L := .of_isLittleO <| (hf.isLittleO.add hg.isLittleO).congr_left fun _ => by simp only [map_sub, add_apply] abel theorem HasFDerivAtFilter.add (hf : HasFDerivAtFilter f f' x L) (hg : HasFDerivAtFilter g g' x L) : HasFDerivAtFilter (f + g) (f' + g') x L := hf.fun_add hg @[fun_prop] nonrec theorem HasFDerivWithinAt.fun_add (hf : HasFDerivWithinAt f f' s x) (hg : HasFDerivWithinAt g g' s x) : HasFDerivWithinAt (fun y => f y + g y) (f' + g') s x := hf.add hg @[fun_prop] nonrec theorem HasFDerivWithinAt.add (hf : HasFDerivWithinAt f f' s x) (hg : HasFDerivWithinAt g g' s x) : HasFDerivWithinAt (f + g) (f' + g') s x := hf.add hg @[fun_prop] nonrec theorem HasFDerivAt.fun_add (hf : HasFDerivAt f f' x) (hg : HasFDerivAt g g' x) : HasFDerivAt (fun x => f x + g x) (f' + g') x := hf.add hg @[fun_prop] nonrec theorem HasFDerivAt.add (hf : HasFDerivAt f f' x) (hg : HasFDerivAt g g' x) : HasFDerivAt (f + g) (f' + g') x := hf.add hg @[fun_prop] theorem DifferentiableWithinAt.fun_add (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : DifferentiableWithinAt 𝕜 (fun y => f y + g y) s x := (hf.hasFDerivWithinAt.add hg.hasFDerivWithinAt).differentiableWithinAt @[fun_prop] theorem DifferentiableWithinAt.add (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : DifferentiableWithinAt 𝕜 (f + g) s x := (hf.hasFDerivWithinAt.add hg.hasFDerivWithinAt).differentiableWithinAt @[simp, fun_prop] theorem DifferentiableAt.fun_add (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (fun y => f y + g y) x := (hf.hasFDerivAt.add hg.hasFDerivAt).differentiableAt @[simp, fun_prop] theorem DifferentiableAt.add (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (f + g) x := (hf.hasFDerivAt.add hg.hasFDerivAt).differentiableAt @[fun_prop] theorem DifferentiableOn.fun_add (hf : DifferentiableOn 𝕜 f s) (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (fun y => f y + g y) s := fun x hx => (hf x hx).add (hg x hx) @[fun_prop] theorem DifferentiableOn.add (hf : DifferentiableOn 𝕜 f s) (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (f + g) s := fun x hx => (hf x hx).add (hg x hx) @[simp, fun_prop] theorem Differentiable.fun_add (hf : Differentiable 𝕜 f) (hg : Differentiable 𝕜 g) : Differentiable 𝕜 fun y => f y + g y := fun x => (hf x).add (hg x) @[simp, fun_prop] theorem Differentiable.add (hf : Differentiable 𝕜 f) (hg : Differentiable 𝕜 g) : Differentiable 𝕜 (f + g) := fun x => (hf x).add (hg x) theorem fderivWithin_fun_add (hxs : UniqueDiffWithinAt 𝕜 s x) (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : fderivWithin 𝕜 (fun y => f y + g y) s x = fderivWithin 𝕜 f s x + fderivWithin 𝕜 g s x := (hf.hasFDerivWithinAt.add hg.hasFDerivWithinAt).fderivWithin hxs theorem fderivWithin_add (hxs : UniqueDiffWithinAt 𝕜 s x) (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : fderivWithin 𝕜 (f + g) s x = fderivWithin 𝕜 f s x + fderivWithin 𝕜 g s x := fderivWithin_fun_add hxs hf hg @[deprecated (since := "2025-06-14")] alias fderivWithin_add' := fderivWithin_add theorem fderiv_fun_add (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : fderiv 𝕜 (fun y => f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.hasFDerivAt.add hg.hasFDerivAt).fderiv theorem fderiv_add (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : fderiv 𝕜 (f + g) x = fderiv 𝕜 f x + fderiv 𝕜 g x := fderiv_fun_add hf hg @[deprecated (since := "2025-06-14")] alias fderiv_add' := fderiv_add @[simp] theorem hasFDerivAtFilter_add_const_iff (c : F) : HasFDerivAtFilter (f · + c) f' x L ↔ HasFDerivAtFilter f f' x L := by simp [hasFDerivAtFilter_iff_isLittleOTVS] alias ⟨_, HasFDerivAtFilter.add_const⟩ := hasFDerivAtFilter_add_const_iff @[simp] theorem hasStrictFDerivAt_add_const_iff (c : F) : HasStrictFDerivAt (f · + c) f' x ↔ HasStrictFDerivAt f f' x := by simp [hasStrictFDerivAt_iff_isLittleO] @[fun_prop] alias ⟨_, HasStrictFDerivAt.add_const⟩ := hasStrictFDerivAt_add_const_iff @[simp] theorem hasFDerivWithinAt_add_const_iff (c : F) : HasFDerivWithinAt (f · + c) f' s x ↔ HasFDerivWithinAt f f' s x := hasFDerivAtFilter_add_const_iff c @[fun_prop] alias ⟨_, HasFDerivWithinAt.add_const⟩ := hasFDerivWithinAt_add_const_iff @[simp] theorem hasFDerivAt_add_const_iff (c : F) : HasFDerivAt (f · + c) f' x ↔ HasFDerivAt f f' x := hasFDerivAtFilter_add_const_iff c @[fun_prop] alias ⟨_, HasFDerivAt.add_const⟩ := hasFDerivAt_add_const_iff @[simp] theorem differentiableWithinAt_add_const_iff (c : F) : DifferentiableWithinAt 𝕜 (fun y => f y + c) s x ↔ DifferentiableWithinAt 𝕜 f s x := exists_congr fun _ ↦ hasFDerivWithinAt_add_const_iff c @[fun_prop] alias ⟨_, DifferentiableWithinAt.add_const⟩ := differentiableWithinAt_add_const_iff @[simp] theorem differentiableAt_add_const_iff (c : F) : DifferentiableAt 𝕜 (fun y => f y + c) x ↔ DifferentiableAt 𝕜 f x := exists_congr fun _ ↦ hasFDerivAt_add_const_iff c @[fun_prop] alias ⟨_, DifferentiableAt.add_const⟩ := differentiableAt_add_const_iff @[simp] theorem differentiableOn_add_const_iff (c : F) : DifferentiableOn 𝕜 (fun y => f y + c) s ↔ DifferentiableOn 𝕜 f s := forall₂_congr fun _ _ ↦ differentiableWithinAt_add_const_iff c @[fun_prop] alias ⟨_, DifferentiableOn.add_const⟩ := differentiableOn_add_const_iff @[simp] theorem differentiable_add_const_iff (c : F) : (Differentiable 𝕜 fun y => f y + c) ↔ Differentiable 𝕜 f := forall_congr' fun _ ↦ differentiableAt_add_const_iff c @[fun_prop] alias ⟨_, Differentiable.add_const⟩ := differentiable_add_const_iff @[simp] theorem fderivWithin_add_const (c : F) : fderivWithin 𝕜 (fun y => f y + c) s x = fderivWithin 𝕜 f s x := by classical simp [fderivWithin] @[simp] theorem fderiv_add_const (c : F) : fderiv 𝕜 (fun y => f y + c) x = fderiv 𝕜 f x := by simp only [← fderivWithin_univ, fderivWithin_add_const] @[simp] theorem hasFDerivAtFilter_const_add_iff (c : F) : HasFDerivAtFilter (c + f ·) f' x L ↔ HasFDerivAtFilter f f' x L := by simpa only [add_comm] using hasFDerivAtFilter_add_const_iff c alias ⟨_, HasFDerivAtFilter.const_add⟩ := hasFDerivAtFilter_const_add_iff @[simp] theorem hasStrictFDerivAt_const_add_iff (c : F) : HasStrictFDerivAt (c + f ·) f' x ↔ HasStrictFDerivAt f f' x := by simpa only [add_comm] using hasStrictFDerivAt_add_const_iff c @[fun_prop] alias ⟨_, HasStrictFDerivAt.const_add⟩ := hasStrictFDerivAt_const_add_iff @[simp] theorem hasFDerivWithinAt_const_add_iff (c : F) : HasFDerivWithinAt (c + f ·) f' s x ↔ HasFDerivWithinAt f f' s x := hasFDerivAtFilter_const_add_iff c @[fun_prop] alias ⟨_, HasFDerivWithinAt.const_add⟩ := hasFDerivWithinAt_const_add_iff @[simp] theorem hasFDerivAt_const_add_iff (c : F) : HasFDerivAt (c + f ·) f' x ↔ HasFDerivAt f f' x := hasFDerivAtFilter_const_add_iff c @[fun_prop] alias ⟨_, HasFDerivAt.const_add⟩ := hasFDerivAt_const_add_iff @[simp] theorem differentiableWithinAt_const_add_iff (c : F) : DifferentiableWithinAt 𝕜 (fun y => c + f y) s x ↔ DifferentiableWithinAt 𝕜 f s x := exists_congr fun _ ↦ hasFDerivWithinAt_const_add_iff c @[fun_prop] alias ⟨_, DifferentiableWithinAt.const_add⟩ := differentiableWithinAt_const_add_iff @[simp] theorem differentiableAt_const_add_iff (c : F) : DifferentiableAt 𝕜 (fun y => c + f y) x ↔ DifferentiableAt 𝕜 f x := exists_congr fun _ ↦ hasFDerivAt_const_add_iff c @[fun_prop] alias ⟨_, DifferentiableAt.const_add⟩ := differentiableAt_const_add_iff @[simp] theorem differentiableOn_const_add_iff (c : F) : DifferentiableOn 𝕜 (fun y => c + f y) s ↔ DifferentiableOn 𝕜 f s := forall₂_congr fun _ _ ↦ differentiableWithinAt_const_add_iff c @[fun_prop] alias ⟨_, DifferentiableOn.const_add⟩ := differentiableOn_const_add_iff @[simp] theorem differentiable_const_add_iff (c : F) : (Differentiable 𝕜 fun y => c + f y) ↔ Differentiable 𝕜 f := forall_congr' fun _ ↦ differentiableAt_const_add_iff c @[fun_prop] alias ⟨_, Differentiable.const_add⟩ := differentiable_const_add_iff @[simp] theorem fderivWithin_const_add (c : F) : fderivWithin 𝕜 (fun y => c + f y) s x = fderivWithin 𝕜 f s x := by simpa only [add_comm] using fderivWithin_add_const c @[simp] theorem fderiv_const_add (c : F) : fderiv 𝕜 (fun y => c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] end Add section Sum /-! ### Derivative of a finite sum of functions -/ variable {ι : Type*} {u : Finset ι} {A : ι → E → F} {A' : ι → E →L[𝕜] F} @[fun_prop] theorem HasStrictFDerivAt.fun_sum (h : ∀ i ∈ u, HasStrictFDerivAt (A i) (A' i) x) : HasStrictFDerivAt (fun y => ∑ i ∈ u, A i y) (∑ i ∈ u, A' i) x := by simp only [hasStrictFDerivAt_iff_isLittleO] at * convert IsLittleO.sum h simp [Finset.sum_sub_distrib, ContinuousLinearMap.sum_apply] @[fun_prop] theorem HasStrictFDerivAt.sum (h : ∀ i ∈ u, HasStrictFDerivAt (A i) (A' i) x) : HasStrictFDerivAt (∑ i ∈ u, A i) (∑ i ∈ u, A' i) x := by convert HasStrictFDerivAt.fun_sum h; simp theorem HasFDerivAtFilter.fun_sum (h : ∀ i ∈ u, HasFDerivAtFilter (A i) (A' i) x L) : HasFDerivAtFilter (fun y => ∑ i ∈ u, A i y) (∑ i ∈ u, A' i) x L := by simp only [hasFDerivAtFilter_iff_isLittleO] at * convert IsLittleO.sum h simp [ContinuousLinearMap.sum_apply] theorem HasFDerivAtFilter.sum (h : ∀ i ∈ u, HasFDerivAtFilter (A i) (A' i) x L) : HasFDerivAtFilter (∑ i ∈ u, A i) (∑ i ∈ u, A' i) x L := by convert HasFDerivAtFilter.fun_sum h; simp @[fun_prop] theorem HasFDerivWithinAt.fun_sum (h : ∀ i ∈ u, HasFDerivWithinAt (A i) (A' i) s x) : HasFDerivWithinAt (fun y => ∑ i ∈ u, A i y) (∑ i ∈ u, A' i) s x := HasFDerivAtFilter.fun_sum h @[fun_prop] theorem HasFDerivWithinAt.sum (h : ∀ i ∈ u, HasFDerivWithinAt (A i) (A' i) s x) : HasFDerivWithinAt (∑ i ∈ u, A i) (∑ i ∈ u, A' i) s x := HasFDerivAtFilter.sum h @[fun_prop] theorem HasFDerivAt.fun_sum (h : ∀ i ∈ u, HasFDerivAt (A i) (A' i) x) : HasFDerivAt (fun y => ∑ i ∈ u, A i y) (∑ i ∈ u, A' i) x := HasFDerivAtFilter.fun_sum h @[fun_prop] theorem HasFDerivAt.sum (h : ∀ i ∈ u, HasFDerivAt (A i) (A' i) x) : HasFDerivAt (∑ i ∈ u, A i) (∑ i ∈ u, A' i) x := HasFDerivAtFilter.sum h @[fun_prop] theorem DifferentiableWithinAt.fun_sum (h : ∀ i ∈ u, DifferentiableWithinAt 𝕜 (A i) s x) : DifferentiableWithinAt 𝕜 (fun y => ∑ i ∈ u, A i y) s x := HasFDerivWithinAt.differentiableWithinAt <| HasFDerivWithinAt.fun_sum fun i hi => (h i hi).hasFDerivWithinAt @[fun_prop] theorem DifferentiableWithinAt.sum (h : ∀ i ∈ u, DifferentiableWithinAt 𝕜 (A i) s x) : DifferentiableWithinAt 𝕜 (∑ i ∈ u, A i) s x := HasFDerivWithinAt.differentiableWithinAt <| HasFDerivWithinAt.sum fun i hi => (h i hi).hasFDerivWithinAt @[simp, fun_prop] theorem DifferentiableAt.fun_sum (h : ∀ i ∈ u, DifferentiableAt 𝕜 (A i) x) : DifferentiableAt 𝕜 (fun y => ∑ i ∈ u, A i y) x := HasFDerivAt.differentiableAt <| HasFDerivAt.fun_sum fun i hi => (h i hi).hasFDerivAt @[simp, fun_prop] theorem DifferentiableAt.sum (h : ∀ i ∈ u, DifferentiableAt 𝕜 (A i) x) : DifferentiableAt 𝕜 (∑ i ∈ u, A i) x := HasFDerivAt.differentiableAt <| HasFDerivAt.sum fun i hi => (h i hi).hasFDerivAt @[fun_prop] theorem DifferentiableOn.fun_sum (h : ∀ i ∈ u, DifferentiableOn 𝕜 (A i) s) : DifferentiableOn 𝕜 (fun y => ∑ i ∈ u, A i y) s := fun x hx => DifferentiableWithinAt.fun_sum fun i hi => h i hi x hx @[fun_prop] theorem DifferentiableOn.sum (h : ∀ i ∈ u, DifferentiableOn 𝕜 (A i) s) : DifferentiableOn 𝕜 (∑ i ∈ u, A i) s := fun x hx => DifferentiableWithinAt.sum fun i hi => h i hi x hx @[simp, fun_prop] theorem Differentiable.fun_sum (h : ∀ i ∈ u, Differentiable 𝕜 (A i)) : Differentiable 𝕜 fun y => ∑ i ∈ u, A i y := fun x => DifferentiableAt.fun_sum fun i hi => h i hi x @[simp, fun_prop] theorem Differentiable.sum (h : ∀ i ∈ u, Differentiable 𝕜 (A i)) : Differentiable 𝕜 (∑ i ∈ u, A i) := fun x => DifferentiableAt.sum fun i hi => h i hi x theorem fderivWithin_fun_sum (hxs : UniqueDiffWithinAt 𝕜 s x) (h : ∀ i ∈ u, DifferentiableWithinAt 𝕜 (A i) s x) : fderivWithin 𝕜 (fun y => ∑ i ∈ u, A i y) s x = ∑ i ∈ u, fderivWithin 𝕜 (A i) s x := (HasFDerivWithinAt.fun_sum fun i hi => (h i hi).hasFDerivWithinAt).fderivWithin hxs theorem fderivWithin_sum (hxs : UniqueDiffWithinAt 𝕜 s x) (h : ∀ i ∈ u, DifferentiableWithinAt 𝕜 (A i) s x) : fderivWithin 𝕜 (∑ i ∈ u, A i) s x = ∑ i ∈ u, fderivWithin 𝕜 (A i) s x := (HasFDerivWithinAt.sum fun i hi => (h i hi).hasFDerivWithinAt).fderivWithin hxs theorem fderiv_fun_sum (h : ∀ i ∈ u, DifferentiableAt 𝕜 (A i) x) : fderiv 𝕜 (fun y => ∑ i ∈ u, A i y) x = ∑ i ∈ u, fderiv 𝕜 (A i) x := (HasFDerivAt.fun_sum fun i hi => (h i hi).hasFDerivAt).fderiv theorem fderiv_sum (h : ∀ i ∈ u, DifferentiableAt 𝕜 (A i) x) : fderiv 𝕜 (∑ i ∈ u, A i) x = ∑ i ∈ u, fderiv 𝕜 (A i) x := (HasFDerivAt.sum fun i hi => (h i hi).hasFDerivAt).fderiv end Sum section Neg /-! ### Derivative of the negative of a function -/ @[fun_prop] theorem HasStrictFDerivAt.fun_neg (h : HasStrictFDerivAt f f' x) : HasStrictFDerivAt (fun x => -f x) (-f') x := (-1 : F →L[𝕜] F).hasStrictFDerivAt.comp x h @[fun_prop] theorem HasStrictFDerivAt.neg (h : HasStrictFDerivAt f f' x) : HasStrictFDerivAt (-f) (-f') x := (-1 : F →L[𝕜] F).hasStrictFDerivAt.comp x h theorem HasFDerivAtFilter.fun_neg (h : HasFDerivAtFilter f f' x L) : HasFDerivAtFilter (fun x => -f x) (-f') x L := (-1 : F →L[𝕜] F).hasFDerivAtFilter.comp x h tendsto_map theorem HasFDerivAtFilter.neg (h : HasFDerivAtFilter f f' x L) : HasFDerivAtFilter (-f) (-f') x L := (-1 : F →L[𝕜] F).hasFDerivAtFilter.comp x h tendsto_map @[fun_prop] nonrec theorem HasFDerivWithinAt.fun_neg (h : HasFDerivWithinAt f f' s x) : HasFDerivWithinAt (fun x => -f x) (-f') s x := h.neg @[fun_prop] nonrec theorem HasFDerivWithinAt.neg (h : HasFDerivWithinAt f f' s x) : HasFDerivWithinAt (-f) (-f') s x := h.neg @[fun_prop] nonrec theorem HasFDerivAt.fun_neg (h : HasFDerivAt f f' x) : HasFDerivAt (fun x => -f x) (-f') x := h.neg @[fun_prop] nonrec theorem HasFDerivAt.neg (h : HasFDerivAt f f' x) : HasFDerivAt (-f) (-f') x := h.neg @[fun_prop] theorem DifferentiableWithinAt.fun_neg (h : DifferentiableWithinAt 𝕜 f s x) : DifferentiableWithinAt 𝕜 (fun y => -f y) s x := h.hasFDerivWithinAt.neg.differentiableWithinAt @[fun_prop] theorem DifferentiableWithinAt.neg (h : DifferentiableWithinAt 𝕜 f s x) : DifferentiableWithinAt 𝕜 (-f) s x := h.hasFDerivWithinAt.neg.differentiableWithinAt @[simp] theorem differentiableWithinAt_fun_neg_iff : DifferentiableWithinAt 𝕜 (fun y => -f y) s x ↔ DifferentiableWithinAt 𝕜 f s x := ⟨fun h => by simpa only [neg_neg] using h.fun_neg, fun h => h.neg⟩ @[simp] theorem differentiableWithinAt_neg_iff : DifferentiableWithinAt 𝕜 (-f) s x ↔ DifferentiableWithinAt 𝕜 f s x := ⟨fun h => by simpa only [neg_neg] using h.neg, fun h => h.neg⟩ @[fun_prop] theorem DifferentiableAt.fun_neg (h : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (fun y => -f y) x := h.hasFDerivAt.neg.differentiableAt @[fun_prop] theorem DifferentiableAt.neg (h : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (-f) x := h.hasFDerivAt.neg.differentiableAt @[simp] theorem differentiableAt_fun_neg_iff : DifferentiableAt 𝕜 (fun y => -f y) x ↔ DifferentiableAt 𝕜 f x := ⟨fun h => by simpa only [neg_neg] using h.fun_neg, fun h => h.neg⟩ @[simp] theorem differentiableAt_neg_iff : DifferentiableAt 𝕜 (-f) x ↔ DifferentiableAt 𝕜 f x := ⟨fun h => by simpa only [neg_neg] using h.neg, fun h => h.neg⟩ @[fun_prop] theorem DifferentiableOn.fun_neg (h : DifferentiableOn 𝕜 f s) : DifferentiableOn 𝕜 (fun y => -f y) s := fun x hx => (h x hx).neg @[fun_prop] theorem DifferentiableOn.neg (h : DifferentiableOn 𝕜 f s) : DifferentiableOn 𝕜 (-f) s := fun x hx => (h x hx).neg @[simp] theorem differentiableOn_fun_neg_iff : DifferentiableOn 𝕜 (fun y => -f y) s ↔ DifferentiableOn 𝕜 f s := ⟨fun h => by simpa only [neg_neg] using h.fun_neg, fun h => h.neg⟩ @[simp] theorem differentiableOn_neg_iff : DifferentiableOn 𝕜 (-f) s ↔ DifferentiableOn 𝕜 f s := ⟨fun h => by simpa only [neg_neg] using h.neg, fun h => h.neg⟩ @[fun_prop] theorem Differentiable.fun_neg (h : Differentiable 𝕜 f) : Differentiable 𝕜 fun y => -f y := fun x => (h x).neg @[fun_prop] theorem Differentiable.neg (h : Differentiable 𝕜 f) : Differentiable 𝕜 (-f) := fun x => (h x).neg @[simp] theorem differentiable_fun_neg_iff : (Differentiable 𝕜 fun y => -f y) ↔ Differentiable 𝕜 f := ⟨fun h => by simpa only [neg_neg] using h.fun_neg, fun h => h.neg⟩ @[simp] theorem differentiable_neg_iff : Differentiable 𝕜 (-f) ↔ Differentiable 𝕜 f := ⟨fun h => by simpa only [neg_neg] using h.neg, fun h => h.neg⟩ theorem fderivWithin_fun_neg (hxs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (fun y => -f y) s x = -fderivWithin 𝕜 f s x := by classical by_cases h : DifferentiableWithinAt 𝕜 f s x · exact h.hasFDerivWithinAt.neg.fderivWithin hxs · rw [fderivWithin_zero_of_not_differentiableWithinAt h, fderivWithin_zero_of_not_differentiableWithinAt, neg_zero] simpa theorem fderivWithin_neg (hxs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (-f) s x = -fderivWithin 𝕜 f s x := fderivWithin_fun_neg hxs @[deprecated (since := "2025-06-14")] alias fderivWithin_neg' := fderivWithin_neg @[simp] theorem fderiv_fun_neg : fderiv 𝕜 (fun y => -f y) x = -fderiv 𝕜 f x := by simp only [← fderivWithin_univ, fderivWithin_fun_neg uniqueDiffWithinAt_univ] /-- Version of `fderiv_neg` where the function is written `-f` instead of `fun y ↦ - f y`. -/ theorem fderiv_neg : fderiv 𝕜 (-f) x = -fderiv 𝕜 f x := fderiv_fun_neg @[deprecated (since := "2025-06-14")] alias fderiv_neg' := fderiv_neg end Neg section Sub /-! ### Derivative of the difference of two functions -/ @[fun_prop] theorem HasStrictFDerivAt.fun_sub (hf : HasStrictFDerivAt f f' x) (hg : HasStrictFDerivAt g g' x) : HasStrictFDerivAt (fun x => f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg @[fun_prop] theorem HasStrictFDerivAt.sub (hf : HasStrictFDerivAt f f' x) (hg : HasStrictFDerivAt g g' x) : HasStrictFDerivAt (f - g) (f' - g') x := hf.fun_sub hg theorem HasFDerivAtFilter.fun_sub (hf : HasFDerivAtFilter f f' x L) (hg : HasFDerivAtFilter g g' x L) : HasFDerivAtFilter (fun x => f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem HasFDerivAtFilter.sub (hf : HasFDerivAtFilter f f' x L) (hg : HasFDerivAtFilter g g' x L) : HasFDerivAtFilter (f - g) (f' - g') x L := hf.fun_sub hg @[fun_prop] nonrec theorem HasFDerivWithinAt.fun_sub (hf : HasFDerivWithinAt f f' s x) (hg : HasFDerivWithinAt g g' s x) : HasFDerivWithinAt (fun x => f x - g x) (f' - g') s x := hf.sub hg @[fun_prop] nonrec theorem HasFDerivWithinAt.sub (hf : HasFDerivWithinAt f f' s x) (hg : HasFDerivWithinAt g g' s x) : HasFDerivWithinAt (f - g) (f' - g') s x := hf.sub hg @[fun_prop] nonrec theorem HasFDerivAt.fun_sub (hf : HasFDerivAt f f' x) (hg : HasFDerivAt g g' x) : HasFDerivAt (fun x => f x - g x) (f' - g') x := hf.sub hg @[fun_prop] nonrec theorem HasFDerivAt.sub (hf : HasFDerivAt f f' x) (hg : HasFDerivAt g g' x) : HasFDerivAt (f - g) (f' - g') x := hf.sub hg @[fun_prop] theorem DifferentiableWithinAt.fun_sub (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : DifferentiableWithinAt 𝕜 (fun y => f y - g y) s x := (hf.hasFDerivWithinAt.sub hg.hasFDerivWithinAt).differentiableWithinAt @[fun_prop] theorem DifferentiableWithinAt.sub (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : DifferentiableWithinAt 𝕜 (f - g) s x := hf.fun_sub hg @[simp, fun_prop] theorem DifferentiableAt.fun_sub (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (fun y => f y - g y) x := (hf.hasFDerivAt.sub hg.hasFDerivAt).differentiableAt @[simp, fun_prop] theorem DifferentiableAt.sub (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (f - g) x := hf.fun_sub hg @[simp] lemma DifferentiableAt.fun_add_iff_left (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (fun y => f y + g y) x ↔ DifferentiableAt 𝕜 f x := by refine ⟨fun h ↦ ?_, fun hf ↦ hf.add hg⟩ simpa only [add_sub_cancel_right] using h.fun_sub hg @[simp] lemma DifferentiableAt.add_iff_left (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (f + g) x ↔ DifferentiableAt 𝕜 f x := hg.fun_add_iff_left @[simp] lemma DifferentiableAt.fun_add_iff_right (hg : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (fun y => f y + g y) x ↔ DifferentiableAt 𝕜 g x := by simp only [add_comm (f _), hg.fun_add_iff_left] @[simp] lemma DifferentiableAt.add_iff_right (hg : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (f + g) x ↔ DifferentiableAt 𝕜 g x := hg.fun_add_iff_right @[simp] lemma DifferentiableAt.fun_sub_iff_left (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (fun y => f y - g y) x ↔ DifferentiableAt 𝕜 f x := by simp only [sub_eq_add_neg, differentiableAt_fun_neg_iff, hg, fun_add_iff_left] @[simp] lemma DifferentiableAt.sub_iff_left (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (f - g) x ↔ DifferentiableAt 𝕜 f x := hg.fun_sub_iff_left @[simp] lemma DifferentiableAt.fun_sub_iff_right (hg : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (fun y => f y - g y) x ↔ DifferentiableAt 𝕜 g x := by simp only [sub_eq_add_neg, hg, fun_add_iff_right, differentiableAt_fun_neg_iff] @[simp] lemma DifferentiableAt.sub_iff_right (hg : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (f - g) x ↔ DifferentiableAt 𝕜 g x := hg.fun_sub_iff_right @[fun_prop] theorem DifferentiableOn.fun_sub (hf : DifferentiableOn 𝕜 f s) (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (fun y => f y - g y) s := fun x hx => (hf x hx).sub (hg x hx) @[fun_prop] theorem DifferentiableOn.sub (hf : DifferentiableOn 𝕜 f s) (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (f - g) s := fun x hx => (hf x hx).sub (hg x hx) @[simp] lemma DifferentiableOn.fun_add_iff_left (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (fun y => f y + g y) s ↔ DifferentiableOn 𝕜 f s := by refine ⟨fun h ↦ ?_, fun hf ↦ hf.add hg⟩ simpa only [add_sub_cancel_right] using h.fun_sub hg @[simp] lemma DifferentiableOn.add_iff_left (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (f + g) s ↔ DifferentiableOn 𝕜 f s := hg.fun_add_iff_left @[simp] lemma DifferentiableOn.fun_add_iff_right (hg : DifferentiableOn 𝕜 f s) : DifferentiableOn 𝕜 (fun y => f y + g y) s ↔ DifferentiableOn 𝕜 g s := by simp only [add_comm (f _), hg.fun_add_iff_left] @[simp] lemma DifferentiableOn.add_iff_right (hg : DifferentiableOn 𝕜 f s) : DifferentiableOn 𝕜 (f + g) s ↔ DifferentiableOn 𝕜 g s := hg.fun_add_iff_right @[simp] lemma DifferentiableOn.fun_sub_iff_left (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (fun y => f y - g y) s ↔ DifferentiableOn 𝕜 f s := by simp only [sub_eq_add_neg, differentiableOn_fun_neg_iff, hg, fun_add_iff_left] @[simp] lemma DifferentiableOn.sub_iff_left (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (f - g) s ↔ DifferentiableOn 𝕜 f s := hg.fun_sub_iff_left @[simp] lemma DifferentiableOn.fun_sub_iff_right (hg : DifferentiableOn 𝕜 f s) : DifferentiableOn 𝕜 (fun y => f y - g y) s ↔ DifferentiableOn 𝕜 g s := by simp only [sub_eq_add_neg, differentiableOn_fun_neg_iff, hg, fun_add_iff_right] @[simp] lemma DifferentiableOn.sub_iff_right (hg : DifferentiableOn 𝕜 f s) : DifferentiableOn 𝕜 (f - g) s ↔ DifferentiableOn 𝕜 g s := hg.fun_sub_iff_right @[simp, fun_prop] theorem Differentiable.fun_sub (hf : Differentiable 𝕜 f) (hg : Differentiable 𝕜 g) : Differentiable 𝕜 fun y => f y - g y := fun x => (hf x).sub (hg x) @[simp, fun_prop] theorem Differentiable.sub (hf : Differentiable 𝕜 f) (hg : Differentiable 𝕜 g) : Differentiable 𝕜 (f - g) := fun x => (hf x).sub (hg x) @[simp] lemma Differentiable.fun_add_iff_left (hg : Differentiable 𝕜 g) : Differentiable 𝕜 (fun y => f y + g y) ↔ Differentiable 𝕜 f := by refine ⟨fun h ↦ ?_, fun hf ↦ hf.add hg⟩ simpa only [add_sub_cancel_right] using h.fun_sub hg @[simp] lemma Differentiable.add_iff_left (hg : Differentiable 𝕜 g) : Differentiable 𝕜 (f + g) ↔ Differentiable 𝕜 f := hg.fun_add_iff_left @[simp] lemma Differentiable.fun_add_iff_right (hg : Differentiable 𝕜 f) : Differentiable 𝕜 (fun y => f y + g y) ↔ Differentiable 𝕜 g := by simp only [add_comm (f _), hg.fun_add_iff_left] @[simp] lemma Differentiable.add_iff_right (hg : Differentiable 𝕜 f) : Differentiable 𝕜 (f + g) ↔ Differentiable 𝕜 g := hg.fun_add_iff_right @[simp] lemma Differentiable.fun_sub_iff_left (hg : Differentiable 𝕜 g) : Differentiable 𝕜 (fun y => f y - g y) ↔ Differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_fun_neg_iff, hg, fun_add_iff_left] @[simp] lemma Differentiable.sub_iff_left (hg : Differentiable 𝕜 g) : Differentiable 𝕜 (f - g) ↔ Differentiable 𝕜 f := hg.fun_sub_iff_left @[simp] lemma Differentiable.fun_sub_iff_right (hg : Differentiable 𝕜 f) : Differentiable 𝕜 (fun y => f y - g y) ↔ Differentiable 𝕜 g := by simp only [sub_eq_add_neg, differentiable_fun_neg_iff, hg, fun_add_iff_right] @[simp] lemma Differentiable.sub_iff_right (hg : Differentiable 𝕜 f) : Differentiable 𝕜 (f - g) ↔ Differentiable 𝕜 g := hg.fun_sub_iff_right theorem fderivWithin_fun_sub (hxs : UniqueDiffWithinAt 𝕜 s x) (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : fderivWithin 𝕜 (fun y => f y - g y) s x = fderivWithin 𝕜 f s x - fderivWithin 𝕜 g s x := (hf.hasFDerivWithinAt.sub hg.hasFDerivWithinAt).fderivWithin hxs theorem fderivWithin_sub (hxs : UniqueDiffWithinAt 𝕜 s x) (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : fderivWithin 𝕜 (f - g) s x = fderivWithin 𝕜 f s x - fderivWithin 𝕜 g s x := fderivWithin_fun_sub hxs hf hg @[deprecated (since := "2025-06-14")] alias fderivWithin_sub' := fderivWithin_sub theorem fderiv_fun_sub (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : fderiv 𝕜 (fun y => f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.hasFDerivAt.sub hg.hasFDerivAt).fderiv theorem fderiv_sub (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : fderiv 𝕜 (f - g) x = fderiv 𝕜 f x - fderiv 𝕜 g x := fderiv_fun_sub hf hg @[deprecated (since := "2025-06-14")] alias fderiv_sub' := fderiv_sub @[simp] theorem hasFDerivAtFilter_sub_const_iff (c : F) : HasFDerivAtFilter (f · - c) f' x L ↔ HasFDerivAtFilter f f' x L := by simp only [sub_eq_add_neg, hasFDerivAtFilter_add_const_iff] alias ⟨_, HasFDerivAtFilter.sub_const⟩ := hasFDerivAtFilter_sub_const_iff @[simp] theorem hasStrictFDerivAt_sub_const_iff (c : F) : HasStrictFDerivAt (f · - c) f' x ↔ HasStrictFDerivAt f f' x := by simp only [sub_eq_add_neg, hasStrictFDerivAt_add_const_iff] @[fun_prop] alias ⟨_, HasStrictFDerivAt.sub_const⟩ := hasStrictFDerivAt_sub_const_iff @[simp] theorem hasFDerivWithinAt_sub_const_iff (c : F) : HasFDerivWithinAt (f · - c) f' s x ↔ HasFDerivWithinAt f f' s x := hasFDerivAtFilter_sub_const_iff c @[fun_prop] alias ⟨_, HasFDerivWithinAt.sub_const⟩ := hasFDerivWithinAt_sub_const_iff @[simp] theorem hasFDerivAt_sub_const_iff (c : F) : HasFDerivAt (f · - c) f' x ↔ HasFDerivAt f f' x := hasFDerivAtFilter_sub_const_iff c @[fun_prop] alias ⟨_, HasFDerivAt.sub_const⟩ := hasFDerivAt_sub_const_iff @[fun_prop] theorem hasStrictFDerivAt_sub_const {x : F} (c : F) : HasStrictFDerivAt (· - c) (id 𝕜 F) x := (hasStrictFDerivAt_id x).sub_const c @[fun_prop] theorem hasFDerivAt_sub_const {x : F} (c : F) : HasFDerivAt (· - c) (id 𝕜 F) x := (hasFDerivAt_id x).sub_const c @[fun_prop] theorem DifferentiableWithinAt.sub_const (hf : DifferentiableWithinAt 𝕜 f s x) (c : F) : DifferentiableWithinAt 𝕜 (fun y => f y - c) s x := (hf.hasFDerivWithinAt.sub_const c).differentiableWithinAt @[simp] theorem differentiableWithinAt_sub_const_iff (c : F) : DifferentiableWithinAt 𝕜 (fun y => f y - c) s x ↔ DifferentiableWithinAt 𝕜 f s x := by simp only [sub_eq_add_neg, differentiableWithinAt_add_const_iff] @[fun_prop] theorem DifferentiableAt.sub_const (hf : DifferentiableAt 𝕜 f x) (c : F) : DifferentiableAt 𝕜 (fun y => f y - c) x := (hf.hasFDerivAt.sub_const c).differentiableAt @[fun_prop] theorem DifferentiableOn.sub_const (hf : DifferentiableOn 𝕜 f s) (c : F) : DifferentiableOn 𝕜 (fun y => f y - c) s := fun x hx => (hf x hx).sub_const c @[fun_prop] theorem Differentiable.sub_const (hf : Differentiable 𝕜 f) (c : F) : Differentiable 𝕜 fun y => f y - c := fun x => (hf x).sub_const c theorem fderivWithin_sub_const (c : F) : fderivWithin 𝕜 (fun y => f y - c) s x = fderivWithin 𝕜 f s x := by simp only [sub_eq_add_neg, fderivWithin_add_const] theorem fderiv_sub_const (c : F) : fderiv 𝕜 (fun y => f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] theorem HasFDerivAtFilter.const_sub (hf : HasFDerivAtFilter f f' x L) (c : F) : HasFDerivAtFilter (fun x => c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c @[fun_prop] nonrec theorem HasStrictFDerivAt.const_sub (hf : HasStrictFDerivAt f f' x) (c : F) : HasStrictFDerivAt (fun x => c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c @[fun_prop] nonrec theorem HasFDerivWithinAt.const_sub (hf : HasFDerivWithinAt f f' s x) (c : F) : HasFDerivWithinAt (fun x => c - f x) (-f') s x := hf.const_sub c @[fun_prop] nonrec theorem HasFDerivAt.const_sub (hf : HasFDerivAt f f' x) (c : F) : HasFDerivAt (fun x => c - f x) (-f') x := hf.const_sub c @[fun_prop] theorem DifferentiableWithinAt.const_sub (hf : DifferentiableWithinAt 𝕜 f s x) (c : F) : DifferentiableWithinAt 𝕜 (fun y => c - f y) s x := (hf.hasFDerivWithinAt.const_sub c).differentiableWithinAt @[simp] theorem differentiableWithinAt_const_sub_iff (c : F) : DifferentiableWithinAt 𝕜 (fun y => c - f y) s x ↔ DifferentiableWithinAt 𝕜 f s x := by simp [sub_eq_add_neg] @[fun_prop] theorem DifferentiableAt.const_sub (hf : DifferentiableAt 𝕜 f x) (c : F) : DifferentiableAt 𝕜 (fun y => c - f y) x := (hf.hasFDerivAt.const_sub c).differentiableAt @[fun_prop] theorem DifferentiableOn.const_sub (hf : DifferentiableOn 𝕜 f s) (c : F) : DifferentiableOn 𝕜 (fun y => c - f y) s := fun x hx => (hf x hx).const_sub c @[fun_prop] theorem Differentiable.const_sub (hf : Differentiable 𝕜 f) (c : F) : Differentiable 𝕜 fun y => c - f y := fun x => (hf x).const_sub c theorem fderivWithin_const_sub (hxs : UniqueDiffWithinAt 𝕜 s x) (c : F) : fderivWithin 𝕜 (fun y => c - f y) s x = -fderivWithin 𝕜 f s x := by simp only [sub_eq_add_neg, fderivWithin_const_add, fderivWithin_fun_neg, hxs] theorem fderiv_const_sub (c : F) : fderiv 𝕜 (fun y => c - f y) x = -fderiv 𝕜 f x := by simp only [← fderivWithin_univ, fderivWithin_const_sub uniqueDiffWithinAt_univ] end Sub section CompAdd /-! ### Derivative of the composition with a translation -/ open scoped Pointwise Topology theorem hasFDerivWithinAt_comp_add_left (a : E) : HasFDerivWithinAt (fun x ↦ f (a + x)) f' s x ↔ HasFDerivWithinAt f f' (a +ᵥ s) (a + x) := by have : map (a + ·) (𝓝[s] x) = 𝓝[a +ᵥ s] (a + x) := by simp only [nhdsWithin, Filter.map_inf (add_right_injective a)] simp [← Set.image_vadd] simp [HasFDerivWithinAt, hasFDerivAtFilter_iff_isLittleOTVS, ← this, Function.comp_def] theorem differentiableWithinAt_comp_add_left (a : E) : DifferentiableWithinAt 𝕜 (fun x ↦ f (a + x)) s x ↔ DifferentiableWithinAt 𝕜 f (a +ᵥ s) (a + x) := by simp [DifferentiableWithinAt, hasFDerivWithinAt_comp_add_left] theorem fderivWithin_comp_add_left (a : E) : fderivWithin 𝕜 (fun x ↦ f (a + x)) s x = fderivWithin 𝕜 f (a +ᵥ s) (a + x) := by classical simp only [fderivWithin, hasFDerivWithinAt_comp_add_left, differentiableWithinAt_comp_add_left] theorem hasFDerivWithinAt_comp_add_right (a : E) : HasFDerivWithinAt (fun x ↦ f (x + a)) f' s x ↔ HasFDerivWithinAt f f' (a +ᵥ s) (x + a) := by simpa only [add_comm a] using hasFDerivWithinAt_comp_add_left a theorem differentiableWithinAt_comp_add_right (a : E) : DifferentiableWithinAt 𝕜 (fun x ↦ f (x + a)) s x ↔ DifferentiableWithinAt 𝕜 f (a +ᵥ s) (x + a) := by simp [DifferentiableWithinAt, hasFDerivWithinAt_comp_add_right] theorem fderivWithin_comp_add_right (a : E) : fderivWithin 𝕜 (fun x ↦ f (x + a)) s x = fderivWithin 𝕜 f (a +ᵥ s) (x + a) := by simp only [add_comm _ a, fderivWithin_comp_add_left] theorem hasFDerivAt_comp_add_right (a : E) : HasFDerivAt (fun x ↦ f (x + a)) f' x ↔ HasFDerivAt f f' (x + a) := by simp [← hasFDerivWithinAt_univ, hasFDerivWithinAt_comp_add_right] theorem differentiableAt_comp_add_right (a : E) : DifferentiableAt 𝕜 (fun x ↦ f (x + a)) x ↔ DifferentiableAt 𝕜 f (x + a) := by simp [DifferentiableAt, hasFDerivAt_comp_add_right] theorem fderiv_comp_add_right (a : E) : fderiv 𝕜 (fun x ↦ f (x + a)) x = fderiv 𝕜 f (x + a) := by simp [← fderivWithin_univ, fderivWithin_comp_add_right] theorem hasFDerivAt_comp_add_left (a : E) : HasFDerivAt (fun x ↦ f (a + x)) f' x ↔ HasFDerivAt f f' (a + x) := by simpa [add_comm a] using hasFDerivAt_comp_add_right a theorem differentiableAt_comp_add_left (a : E) : DifferentiableAt 𝕜 (fun x ↦ f (a + x)) x ↔ DifferentiableAt 𝕜 f (a + x) := by simp [DifferentiableAt, hasFDerivAt_comp_add_left] theorem fderiv_comp_add_left (a : E) : fderiv 𝕜 (fun x ↦ f (a + x)) x = fderiv 𝕜 f (a + x) := by simpa [add_comm a] using fderiv_comp_add_right a theorem hasFDerivWithinAt_comp_sub (a : E) : HasFDerivWithinAt (fun x ↦ f (x - a)) f' s x ↔ HasFDerivWithinAt f f' (-a +ᵥ s) (x - a) := by simpa [sub_eq_add_neg] using hasFDerivWithinAt_comp_add_right (-a) theorem differentiableWithinAt_comp_sub (a : E) : DifferentiableWithinAt 𝕜 (fun x ↦ f (x - a)) s x ↔ DifferentiableWithinAt 𝕜 f (-a +ᵥ s) (x - a) := by simp [DifferentiableWithinAt, hasFDerivWithinAt_comp_sub] theorem fderivWithin_comp_sub (a : E) : fderivWithin 𝕜 (fun x ↦ f (x - a)) s x = fderivWithin 𝕜 f (-a +ᵥ s) (x - a) := by simpa [sub_eq_add_neg] using fderivWithin_comp_add_right (-a) theorem hasFDerivAt_comp_sub (a : E) : HasFDerivAt (fun x ↦ f (x - a)) f' x ↔ HasFDerivAt f f' (x - a) := by simp [← hasFDerivWithinAt_univ, hasFDerivWithinAt_comp_sub] theorem differentiableAt_comp_sub (a : E) : DifferentiableAt 𝕜 (fun x ↦ f (x - a)) x ↔ DifferentiableAt 𝕜 f (x - a) := by simp [DifferentiableAt, hasFDerivAt_comp_sub] theorem fderiv_comp_sub (a : E) : fderiv 𝕜 (fun x ↦ f (x - a)) x = fderiv 𝕜 f (x - a) := by simp [← fderivWithin_univ, fderivWithin_comp_sub] end CompAdd end
all_order.v
Require Export order.
frobenius.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div. From mathcomp Require Import fintype bigop prime finset fingroup morphism. From mathcomp Require Import perm action quotient gproduct cyclic center. From mathcomp Require Import pgroup nilpotent sylow hall abelian. (******************************************************************************) (* Definition of Frobenius groups, some basic results, and the Frobenius *) (* theorem on the number of solutions of x ^+ n = 1. *) (* semiregular K H <-> *) (* the internal action of H on K is semiregular, i.e., no nontrivial *) (* elements of H and K commute; note that this is actually a symmetric *) (* condition. *) (* semiprime K H <-> *) (* the internal action of H on K is "prime", i.e., an element of K that *) (* centralises a nontrivial element of H must centralise all of H. *) (* normedTI A G L <=> *) (* A is nonempty, strictly disjoint from its conjugates in G, and has *) (* normaliser L in G. *) (* [Frobenius G = K ><| H] <=> *) (* G is (isomorphic to) a Frobenius group with kernel K and complement *) (* H. This is an effective predicate (in bool), which tests the *) (* equality with the semidirect product, and then the fact that H is a *) (* proper self-normalizing TI-subgroup of G. *) (* [Frobenius G with kernel H] <=> *) (* G is (isomorphic to) a Frobenius group with kernel K; same as above, *) (* but without the semi-direct product. *) (* [Frobenius G with complement H] <=> *) (* G is (isomorphic to) a Frobenius group with complement H; same as *) (* above, but without the semi-direct product. The proof that this form *) (* is equivalent to the above (i.e., the existence of Frobenius *) (* kernels) requires character theory and will only be proved in the *) (* vcharacter.v file. *) (* [Frobenius G] <=> G is a Frobenius group. *) (* Frobenius_action G H S to <-> *) (* The action to of G on S defines an isomorphism of G with a *) (* (permutation) Frobenius group, i.e., to is faithful and transitive *) (* on S, no nontrivial element of G fixes more than one point in S, and *) (* H is the stabilizer of some element of S, and non-trivial. Thus, *) (* Frobenius_action G H S 'P *) (* asserts that G is a Frobenius group in the classic sense. *) (* has_Frobenius_action G H <-> *) (* Frobenius_action G H S to holds for some sT : finType, S : {set st} *) (* and to : {action gT &-> sT}. This is a predicate in Prop, but is *) (* exactly reflected by [Frobenius G with complement H] : bool. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Section Definitions. Variable gT : finGroupType. Implicit Types A G K H L : {set gT}. (* Corresponds to "H acts on K in a regular manner" in B & G. *) Definition semiregular K H := {in H^#, forall x, 'C_K[x] = 1}. (* Corresponds to "H acts on K in a prime manner" in B & G. *) Definition semiprime K H := {in H^#, forall x, 'C_K[x] = 'C_K(H)}. Definition normedTI A G L := [&& A != set0, trivIset (A :^: G) & 'N_G(A) == L]. Definition Frobenius_group_with_complement G H := (H != G) && normedTI H^# G H. Definition Frobenius_group G := [exists H : {group gT}, Frobenius_group_with_complement G H]. Definition Frobenius_group_with_kernel_and_complement G K H := (K ><| H == G) && Frobenius_group_with_complement G H. Definition Frobenius_group_with_kernel G K := [exists H : {group gT}, Frobenius_group_with_kernel_and_complement G K H]. Section FrobeniusAction. Variables G H : {set gT}. Variables (sT : finType) (S : {set sT}) (to : {action gT &-> sT}). Definition Frobenius_action := [/\ [faithful G, on S | to], [transitive G, on S | to], {in G^#, forall x, #|'Fix_(S | to)[x]| <= 1}, H != 1 & exists2 u, u \in S & H = 'C_G[u | to]]. End FrobeniusAction. Variant has_Frobenius_action G H : Prop := hasFrobeniusAction sT S to of @Frobenius_action G H sT S to. End Definitions. Arguments semiregular {gT} K%_g H%_g. Arguments semiprime {gT} K%_g H%_g. Arguments normedTI {gT} A%_g G%_g L%_g. Arguments Frobenius_group_with_complement {gT} G%_g H%_g. Arguments Frobenius_group {gT} G%_g. Arguments Frobenius_group_with_kernel {gT} G%_g K%_g. Arguments Frobenius_group_with_kernel_and_complement {gT} G%_g K%_g H%_g. Arguments Frobenius_action {gT} G%_g H%_g {sT} S%_g to%_act. Arguments has_Frobenius_action {gT} G%_g H%_g. Notation "[ 'Frobenius' G 'with' 'complement' H ]" := (Frobenius_group_with_complement G H) (G at level 50, format "[ 'Frobenius' G 'with' 'complement' H ]") : group_scope. Notation "[ 'Frobenius' G 'with' 'kernel' K ]" := (Frobenius_group_with_kernel G K) (format "[ 'Frobenius' G 'with' 'kernel' K ]") : group_scope. Notation "[ 'Frobenius' G ]" := (Frobenius_group G) (format "[ 'Frobenius' G ]") : group_scope. Notation "[ 'Frobenius' G = K ><| H ]" := (Frobenius_group_with_kernel_and_complement G K H) (K, H at level 35, format "[ 'Frobenius' G = K ><| H ]") : group_scope. Section FrobeniusBasics. Variable gT : finGroupType. Implicit Types (A B : {set gT}) (G H K L R X : {group gT}). Lemma semiregular1l H : semiregular 1 H. Proof. by move=> x _ /=; rewrite setI1g. Qed. Lemma semiregular1r K : semiregular K 1. Proof. by move=> x; rewrite setDv inE. Qed. Lemma semiregular_sym H K : semiregular K H -> semiregular H K. Proof. move=> regH x /setD1P[ntx Kx]; apply: contraNeq ntx. rewrite -subG1 -setD_eq0 -setIDAC => /set0Pn[y /setIP[Hy cxy]]. by rewrite (sameP eqP set1gP) -(regH y Hy) inE Kx cent1C. Qed. Lemma semiregularS K1 K2 A1 A2 : K1 \subset K2 -> A1 \subset A2 -> semiregular K2 A2 -> semiregular K1 A1. Proof. move=> sK12 sA12 regKA2 x /setD1P[ntx /(subsetP sA12)A2x]. by apply/trivgP; rewrite -(regKA2 x) ?inE ?ntx ?setSI. Qed. Lemma semiregular_prime H K : semiregular K H -> semiprime K H. Proof. move=> regH x Hx; apply/eqP; rewrite eqEsubset {1}regH // sub1G. by rewrite -cent_set1 setIS ?centS // sub1set; case/setD1P: Hx. Qed. Lemma semiprime_regular H K : semiprime K H -> 'C_K(H) = 1 -> semiregular K H. Proof. by move=> prKH tiKcH x Hx; rewrite prKH. Qed. Lemma semiprimeS K1 K2 A1 A2 : K1 \subset K2 -> A1 \subset A2 -> semiprime K2 A2 -> semiprime K1 A1. Proof. move=> sK12 sA12 prKA2 x /setD1P[ntx A1x]. apply/eqP; rewrite eqEsubset andbC -{1}cent_set1 setIS ?centS ?sub1set //=. rewrite -(setIidPl sK12) -!setIA prKA2 ?setIS ?centS //. by rewrite !inE ntx (subsetP sA12). Qed. Lemma cent_semiprime H K X : semiprime K H -> X \subset H -> X :!=: 1 -> 'C_K(X) = 'C_K(H). Proof. move=> prKH sXH /trivgPn[x Xx ntx]; apply/eqP. rewrite eqEsubset -{1}(prKH x) ?inE ?(subsetP sXH) ?ntx //=. by rewrite -cent_cycle !setIS ?centS ?cycle_subG. Qed. Lemma stab_semiprime H K X : semiprime K H -> X \subset K -> 'C_H(X) != 1 -> 'C_H(X) = H. Proof. move=> prKH sXK ntCHX; apply/setIidPl; rewrite centsC -subsetIidl. rewrite -{2}(setIidPl sXK) -setIA -(cent_semiprime prKH _ ntCHX) ?subsetIl //. by rewrite !subsetI subxx sXK centsC subsetIr. Qed. Lemma cent_semiregular H K X : semiregular K H -> X \subset H -> X :!=: 1 -> 'C_K(X) = 1. Proof. move=> regKH sXH /trivgPn[x Xx ntx]; apply/trivgP. rewrite -(regKH x) ?inE ?(subsetP sXH) ?ntx ?setIS //=. by rewrite -cent_cycle centS ?cycle_subG. Qed. Lemma regular_norm_dvd_pred K H : H \subset 'N(K) -> semiregular K H -> #|H| %| #|K|.-1. Proof. move=> nKH regH; have actsH: [acts H, on K^# | 'J] by rewrite astabsJ normD1. rewrite (cardsD1 1 K) group1 -(acts_sum_card_orbit actsH) /=. rewrite (eq_bigr (fun _ => #|H|)) ?sum_nat_const ?dvdn_mull //. move=> _ /imsetP[x /setIdP[ntx Kx] ->]; rewrite card_orbit astab1J. rewrite ['C_H[x]](trivgP _) ?indexg1 //=. apply/subsetP=> y /setIP[Hy cxy]; apply: contraR ntx => nty. by rewrite -[[set 1]](regH y) inE ?nty // Kx cent1C. Qed. Lemma regular_norm_coprime K H : H \subset 'N(K) -> semiregular K H -> coprime #|K| #|H|. Proof. move=> nKH regH. by rewrite (coprime_dvdr (regular_norm_dvd_pred nKH regH)) ?coprimenP. Qed. Lemma semiregularJ K H x : semiregular K H -> semiregular (K :^ x) (H :^ x). Proof. move=> regH yx; rewrite -conjD1g => /imsetP[y Hy ->]. by rewrite cent1J -conjIg regH ?conjs1g. Qed. Lemma semiprimeJ K H x : semiprime K H -> semiprime (K :^ x) (H :^ x). Proof. move=> prH yx; rewrite -conjD1g => /imsetP[y Hy ->]. by rewrite cent1J centJ -!conjIg prH. Qed. Lemma normedTI_P A G L : reflect [/\ A != set0, L \subset 'N_G(A) & {in G, forall g, ~~ [disjoint A & A :^ g] -> g \in L}] (normedTI A G L). Proof. apply: (iffP and3P) => [[nzA /trivIsetP tiAG /eqP <-] | [nzA sLN tiAG]]. split=> // g Gg; rewrite inE Gg (sameP normP eqP) /= eq_sym; apply: contraR. by apply: tiAG; rewrite ?mem_orbit ?orbit_refl. have [/set0Pn[a Aa] /subsetIP[_ nAL]] := (nzA, sLN); split=> //; last first. rewrite eqEsubset sLN andbT; apply/subsetP=> x /setIP[Gx nAx]. by apply/tiAG/pred0Pn=> //; exists a; rewrite /= (normP nAx) Aa. apply/trivIsetP=> _ _ /imsetP[x Gx ->] /imsetP[y Gy ->]; apply: contraR. rewrite -setI_eq0 -(mulgKV x y) conjsgM; set g := (y * x^-1)%g. have Gg: g \in G by rewrite groupMl ?groupV. rewrite -conjIg (inj_eq (act_inj 'Js x)) (eq_sym A) (sameP eqP normP). by rewrite -cards_eq0 cardJg cards_eq0 setI_eq0 => /tiAG/(subsetP nAL)->. Qed. Arguments normedTI_P {A G L}. Lemma normedTI_memJ_P A G L : reflect [/\ A != set0, L \subset G & {in A & G, forall a g, (a ^ g \in A) = (g \in L)}] (normedTI A G L). Proof. apply: (iffP normedTI_P) => [[-> /subsetIP[sLG nAL] tiAG] | [-> sLG tiAG]]. split=> // a g Aa Gg; apply/idP/idP=> [Aag | Lg]; last first. by rewrite memJ_norm ?(subsetP nAL). by apply/tiAG/pred0Pn=> //; exists (a ^ g)%g; rewrite /= Aag memJ_conjg. split=> // [ | g Gg /pred0Pn[ag /=]]; last first. by rewrite andbC => /andP[/imsetP[a Aa ->]]; rewrite tiAG. apply/subsetP=> g Lg; have Gg := subsetP sLG g Lg. by rewrite !inE Gg; apply/subsetP=> _ /imsetP[a Aa ->]; rewrite tiAG. Qed. Lemma partition_class_support A G : A != set0 -> trivIset (A :^: G) -> partition (A :^: G) (class_support A G). Proof. rewrite /partition cover_imset -class_supportEr eqxx => nzA ->. by apply: contra nzA => /imsetP[x _ /eqP]; rewrite eq_sym -!cards_eq0 cardJg. Qed. Lemma partition_normedTI A G L : normedTI A G L -> partition (A :^: G) (class_support A G). Proof. by case/and3P=> ntA tiAG _; apply: partition_class_support. Qed. Lemma card_support_normedTI A G L : normedTI A G L -> #|class_support A G| = (#|A| * #|G : L|)%N. Proof. case/and3P=> ntA tiAG /eqP <-; rewrite -card_conjugates mulnC. apply: card_uniform_partition (partition_class_support ntA tiAG). by move=> _ /imsetP[y _ ->]; rewrite cardJg. Qed. Lemma normedTI_S A B G L : A != set0 -> L \subset 'N(A) -> A \subset B -> normedTI B G L -> normedTI A G L. Proof. move=> nzA /subsetP nAL /subsetP sAB /normedTI_memJ_P[nzB sLG tiB]. apply/normedTI_memJ_P; split=> // a x Aa Gx. by apply/idP/idP => [Aax | /nAL/memJ_norm-> //]; rewrite -(tiB a) ?sAB. Qed. Lemma cent1_normedTI A G L : normedTI A G L -> {in A, forall x, 'C_G[x] \subset L}. Proof. case/normedTI_memJ_P=> [_ _ tiAG] x Ax; apply/subsetP=> y /setIP[Gy cxy]. by rewrite -(tiAG x) // /(x ^ y) -(cent1P cxy) mulKg. Qed. Lemma Frobenius_actionP G H : reflect (has_Frobenius_action G H) [Frobenius G with complement H]. Proof. apply: (iffP andP) => [[neqHG] | [sT S to [ffulG transG regG ntH [u Su defH]]]]. case/normedTI_P=> nzH /subsetIP[sHG _] tiHG. suffices: Frobenius_action G H (rcosets H G) 'Rs by apply: hasFrobeniusAction. pose Hfix x := 'Fix_(rcosets H G | 'Rs)[x]. have regG: {in G^#, forall x, #|Hfix x| <= 1}. move=> x /setD1P[ntx Gx]. apply: wlog_neg; rewrite -ltnNge => /ltnW/card_gt0P/=[Hy]. rewrite -(cards1 Hy) => /setIP[/imsetP[y Gy ->{Hy}] cHyx]. apply/subset_leq_card/subsetP=> _ /setIP[/imsetP[z Gz ->] cHzx]. rewrite -!sub_astab1 !astab1_act !sub1set astab1Rs in cHyx cHzx *. rewrite !rcosetE; apply/set1P/rcoset_eqP; rewrite mem_rcoset. apply: tiHG; [by rewrite !in_group | apply/pred0Pn; exists (x ^ y^-1)]. by rewrite conjD1g !inE conjg_eq1 ntx -mem_conjg cHyx conjsgM memJ_conjg. have ntH: H :!=: 1 by rewrite -subG1 -setD_eq0. split=> //; first 1 last; first exact: transRs_rcosets. by exists (val H); rewrite ?orbit_refl // astab1Rs (setIidPr sHG). apply/subsetP=> y /setIP[Gy cHy]; apply: contraR neqHG => nt_y. rewrite (index1g sHG) //; apply/eqP; rewrite eqn_leq indexg_gt0 andbT. apply: leq_trans (regG y _); last by rewrite setDE 2!inE Gy nt_y /=. by rewrite /Hfix (setIidPl _) -1?astabC ?sub1set. have sHG: H \subset G by rewrite defH subsetIl. split. apply: contraNneq ntH => /= defG. suffices defS: S = [set u] by rewrite -(trivgP ffulG) /= defS defH. apply/eqP; rewrite eq_sym eqEcard sub1set Su. by rewrite -(atransP transG u Su) card_orbit -defH defG indexgg cards1. apply/normedTI_P; rewrite setD_eq0 subG1 normD1 subsetI sHG normG. split=> // x Gx; rewrite -setI_eq0 conjD1g defH inE Gx conjIg conjGid //. rewrite -setDIl -setIIr -astab1_act setDIl => /set0Pn[y /setIP[Gy /setD1P[_]]]. case/setIP; rewrite 2!(sameP astab1P afix1P) => cuy cuxy; apply/astab1P. apply: contraTeq (regG y Gy) => cu'x. rewrite (cardD1 u) (cardD1 (to u x)) inE Su cuy inE /= inE cu'x cuxy. by rewrite (actsP (atrans_acts transG)) ?Su. Qed. Section FrobeniusProperties. Variables G H K : {group gT}. Hypothesis frobG : [Frobenius G = K ><| H]. Lemma FrobeniusWker : [Frobenius G with kernel K]. Proof. by apply/existsP; exists H. Qed. Lemma FrobeniusWcompl : [Frobenius G with complement H]. Proof. by case/andP: frobG. Qed. Lemma FrobeniusW : [Frobenius G]. Proof. by apply/existsP; exists H; apply: FrobeniusWcompl. Qed. Lemma Frobenius_context : [/\ K ><| H = G, K :!=: 1, H :!=: 1, K \proper G & H \proper G]. Proof. have [/eqP defG neqHG ntH _] := and4P frobG; rewrite setD_eq0 subG1 in ntH. have ntK: K :!=: 1 by apply: contraNneq neqHG => K1; rewrite -defG K1 sdprod1g. rewrite properEcard properEneq neqHG; have /mulG_sub[-> ->] := sdprodW defG. by rewrite -(sdprod_card defG) ltn_Pmulr ?cardG_gt1. Qed. Lemma Frobenius_partition : partition (gval K |: (H^# :^: K)) G. Proof. have [/eqP defG _ tiHG] := and3P frobG; have [_ tiH1G /eqP defN] := and3P tiHG. have [[_ /mulG_sub[sKG sHG] nKH tiKH] mulHK] := (sdprodP defG, sdprodWC defG). set HG := H^# :^: K; set KHG := _ |: _. have defHG: HG = H^# :^: G. have: 'C_G[H^# | 'Js] * K = G by rewrite astab1Js defN mulHK. move/subgroup_transitiveP/atransP. by apply; rewrite ?atrans_orbit ?orbit_refl. have /and3P[defHK _ nzHG] := partition_normedTI tiHG. rewrite -defHG in defHK nzHG tiH1G. have [tiKHG HG'K]: trivIset KHG /\ gval K \notin HG. apply: trivIsetU1 => // _ /imsetP[x Kx ->]; rewrite -setI_eq0. by rewrite -(conjGid Kx) -conjIg setIDA tiKH setDv conj0g. rewrite /partition andbC tiKHG !inE negb_or nzHG eq_sym -card_gt0 cardG_gt0 /=. rewrite eqEcard; apply/andP; split. rewrite /cover big_setU1 //= subUset sKG -/(cover HG) (eqP defHK). by rewrite class_support_subG // (subset_trans _ sHG) ?subD1set. rewrite -(eqnP tiKHG) big_setU1 //= (eqnP tiH1G) (eqP defHK). rewrite (card_support_normedTI tiHG) -(Lagrange sHG) (cardsD1 1) group1 mulSn. by rewrite leq_add2r -mulHK indexMg -indexgI tiKH indexg1. Qed. Lemma Frobenius_cent1_ker : {in K^#, forall x, 'C_G[x] \subset K}. Proof. have [/eqP defG _ /normedTI_memJ_P[_ _ tiHG]] := and3P frobG. move=> x /setD1P[ntx Kx]; have [_ /mulG_sub[sKG _] _ tiKH] := sdprodP defG. have [/eqP <- _ _] := and3P Frobenius_partition; rewrite big_distrl /=. apply/bigcupsP=> _ /setU1P[|/imsetP[y Ky]] ->; first exact: subsetIl. apply: contraR ntx => /subsetPn[z]; rewrite inE mem_conjg => /andP[Hzy cxz] _. rewrite -(conjg_eq1 x y^-1) -in_set1 -set1gE -tiKH inE andbC. rewrite -(tiHG _ _ Hzy) ?(subsetP sKG) ?in_group // Ky andbT -conjJg. by rewrite /(z ^ x) (cent1P cxz) mulKg. Qed. Lemma Frobenius_reg_ker : semiregular K H. Proof. move=> x /setD1P[ntx Hx]. apply/trivgP/subsetP=> y /setIP[Ky cxy]; apply: contraR ntx => nty. have K1y: y \in K^# by rewrite inE nty. have [/eqP/sdprod_context[_ sHG _ _ tiKH] _] := andP frobG. suffices: x \in K :&: H by rewrite tiKH inE. by rewrite inE (subsetP (Frobenius_cent1_ker K1y)) // inE cent1C (subsetP sHG). Qed. Lemma Frobenius_reg_compl : semiregular H K. Proof. by apply: semiregular_sym; apply: Frobenius_reg_ker. Qed. Lemma Frobenius_dvd_ker1 : #|H| %| #|K|.-1. Proof. apply: regular_norm_dvd_pred Frobenius_reg_ker. by have[/sdprodP[]] := Frobenius_context. Qed. Lemma ltn_odd_Frobenius_ker : odd #|G| -> #|H|.*2 < #|K|. Proof. move/oddSg=> oddG. have [/sdprodW/mulG_sub[sKG sHG] ntK _ _ _] := Frobenius_context. by rewrite dvdn_double_ltn ?oddG ?cardG_gt1 ?Frobenius_dvd_ker1. Qed. Lemma Frobenius_index_dvd_ker1 : #|G : K| %| #|K|.-1. Proof. have[defG _ _ /andP[sKG _] _] := Frobenius_context. by rewrite -divgS // -(sdprod_card defG) mulKn ?Frobenius_dvd_ker1. Qed. Lemma Frobenius_coprime : coprime #|K| #|H|. Proof. by rewrite (coprime_dvdr Frobenius_dvd_ker1) ?coprimenP. Qed. Lemma Frobenius_trivg_cent : 'C_K(H) = 1. Proof. by apply: (cent_semiregular Frobenius_reg_ker); case: Frobenius_context. Qed. Lemma Frobenius_index_coprime : coprime #|K| #|G : K|. Proof. by rewrite (coprime_dvdr Frobenius_index_dvd_ker1) ?coprimenP. Qed. Lemma Frobenius_ker_Hall : Hall G K. Proof. have [_ _ _ /andP[sKG _] _] := Frobenius_context. by rewrite /Hall sKG Frobenius_index_coprime. Qed. Lemma Frobenius_compl_Hall : Hall G H. Proof. have [defG _ _ _ _] := Frobenius_context. by rewrite -(sdprod_Hall defG) Frobenius_ker_Hall. Qed. End FrobeniusProperties. Lemma normedTI_J x A G L : normedTI (A :^ x) (G :^ x) (L :^ x) = normedTI A G L. Proof. rewrite {1}/normedTI normJ -conjIg -(conj0g x) !(can_eq (conjsgK x)). congr [&& _, _ == _ & _]; rewrite /cover (reindex_inj (@conjsg_inj _ x)). by apply: eq_big => Hy; rewrite ?orbit_conjsg ?cardJg. by rewrite bigcupJ cardJg (eq_bigl _ _ (orbit_conjsg _ _ _ _)). Qed. Lemma FrobeniusJcompl x G H : [Frobenius G :^ x with complement H :^ x] = [Frobenius G with complement H]. Proof. by congr (_ && _); rewrite ?(can_eq (conjsgK x)) // -conjD1g normedTI_J. Qed. Lemma FrobeniusJ x G K H : [Frobenius G :^ x = K :^ x ><| H :^ x] = [Frobenius G = K ><| H]. Proof. by congr (_ && _); rewrite ?FrobeniusJcompl // -sdprodJ (can_eq (conjsgK x)). Qed. Lemma FrobeniusJker x G K : [Frobenius G :^ x with kernel K :^ x] = [Frobenius G with kernel K]. Proof. apply/existsP/existsP=> [] [H]; last by exists (H :^ x)%G; rewrite FrobeniusJ. by rewrite -(conjsgKV x H) FrobeniusJ; exists (H :^ x^-1)%G. Qed. Lemma FrobeniusJgroup x G : [Frobenius G :^ x] = [Frobenius G]. Proof. apply/existsP/existsP=> [] [H]. by rewrite -(conjsgKV x H) FrobeniusJcompl; exists (H :^ x^-1)%G. by exists (H :^ x)%G; rewrite FrobeniusJcompl. Qed. Lemma Frobenius_ker_dvd_ker1 G K : [Frobenius G with kernel K] -> #|G : K| %| #|K|.-1. Proof. by case/existsP=> H; apply: Frobenius_index_dvd_ker1. Qed. Lemma Frobenius_ker_coprime G K : [Frobenius G with kernel K] -> coprime #|K| #|G : K|. Proof. by case/existsP=> H; apply: Frobenius_index_coprime. Qed. Lemma Frobenius_semiregularP G K H : K ><| H = G -> K :!=: 1 -> H :!=: 1 -> reflect (semiregular K H) [Frobenius G = K ><| H]. Proof. move=> defG ntK ntH. apply: (iffP idP) => [|regG]; first exact: Frobenius_reg_ker. have [nsKG sHG defKH nKH tiKH]:= sdprod_context defG; have [sKG _]:= andP nsKG. apply/and3P; split; first by rewrite defG. by rewrite eqEcard sHG -(sdprod_card defG) -ltnNge ltn_Pmull ?cardG_gt1. apply/normedTI_memJ_P; rewrite setD_eq0 subG1 sHG -defKH -(normC nKH). split=> // z _ /setD1P[ntz Hz] /mulsgP[y x Hy Kx ->]; rewrite groupMl // !inE. rewrite conjg_eq1 ntz; apply/idP/idP=> [Hzxy | Hx]; last by rewrite !in_group. apply: (subsetP (sub1G H)); have Hzy: z ^ y \in H by apply: groupJ. rewrite -(regG (z ^ y)); last by apply/setD1P; rewrite conjg_eq1. rewrite inE Kx cent1C (sameP cent1P commgP) -in_set1 -[[set 1]]tiKH inE /=. rewrite andbC groupM ?groupV -?conjgM //= commgEr groupMr //. by rewrite memJ_norm ?(subsetP nKH) ?groupV. Qed. Lemma prime_FrobeniusP G K H : K :!=: 1 -> prime #|H| -> reflect (K ><| H = G /\ 'C_K(H) = 1) [Frobenius G = K ><| H]. Proof. move=> ntK H_pr; have ntH: H :!=: 1 by rewrite -cardG_gt1 prime_gt1. have [defG | not_sdG] := eqVneq (K ><| H) G; last first. by apply: (iffP andP) => [] [defG]; rewrite defG ?eqxx in not_sdG. apply: (iffP (Frobenius_semiregularP defG ntK ntH)) => [regH | [_ regH x]]. split=> //; have [x defH] := cyclicP (prime_cyclic H_pr). by rewrite defH cent_cycle regH // !inE defH cycle_id andbT -cycle_eq1 -defH. case/setD1P=> nt_x Hx; apply/trivgP; rewrite -regH setIS //= -cent_cycle. by rewrite centS // prime_meetG // (setIidPr _) ?cycle_eq1 ?cycle_subG. Qed. Lemma Frobenius_subl G K K1 H : K1 :!=: 1 -> K1 \subset K -> H \subset 'N(K1) -> [Frobenius G = K ><| H] -> [Frobenius K1 <*> H = K1 ><| H]. Proof. move=> ntK1 sK1K nK1H frobG; have [_ _ ntH _ _] := Frobenius_context frobG. apply/Frobenius_semiregularP=> //. by rewrite sdprodEY ?coprime_TIg ?(coprimeSg sK1K) ?(Frobenius_coprime frobG). by move=> x /(Frobenius_reg_ker frobG) cKx1; apply/trivgP; rewrite -cKx1 setSI. Qed. Lemma Frobenius_subr G K H H1 : H1 :!=: 1 -> H1 \subset H -> [Frobenius G = K ><| H] -> [Frobenius K <*> H1 = K ><| H1]. Proof. move=> ntH1 sH1H frobG; have [defG ntK _ _ _] := Frobenius_context frobG. apply/Frobenius_semiregularP=> //. have [_ _ /(subset_trans sH1H) nH1K tiHK] := sdprodP defG. by rewrite sdprodEY //; apply/trivgP; rewrite -tiHK setIS. by apply: sub_in1 (Frobenius_reg_ker frobG); apply/subsetP/setSD. Qed. Lemma Frobenius_kerP G K : reflect [/\ K :!=: 1, K \proper G, K <| G & {in K^#, forall x, 'C_G[x] \subset K}] [Frobenius G with kernel K]. Proof. apply: (iffP existsP) => [[H frobG] | [ntK ltKG nsKG regK]]. have [/sdprod_context[nsKG _ _ _ _] ntK _ ltKG _] := Frobenius_context frobG. by split=> //; apply: Frobenius_cent1_ker frobG. have /andP[sKG nKG] := nsKG. have hallK: Hall G K. rewrite /Hall sKG //= coprime_sym coprime_pi' //. apply: sub_pgroup (pgroup_pi K) => p; have [P sylP] := Sylow_exists p G. have [[sPG pP p'GiP] sylPK] := (and3P sylP, Hall_setI_normal nsKG sylP). rewrite -p_rank_gt0 -(rank_Sylow sylPK) rank_gt0 => ntPK. rewrite inE /= -p'natEpi // (pnat_dvd _ p'GiP) ?indexgS //. have /trivgPn[z]: P :&: K :&: 'Z(P) != 1. by rewrite meet_center_nil ?(pgroup_nil pP) ?(normalGI sPG nsKG). rewrite !inE -andbA -sub_cent1=> /and4P[_ Kz _ cPz] ntz. by apply: subset_trans (regK z _); [apply/subsetIP | apply/setD1P]. have /splitsP[H /complP[tiKH defG]] := SchurZassenhaus_split hallK nsKG. have [_ sHG] := mulG_sub defG; have nKH := subset_trans sHG nKG. exists H; apply/Frobenius_semiregularP; rewrite ?sdprodE //. by apply: contraNneq (proper_subn ltKG) => H1; rewrite -defG H1 mulg1. apply: semiregular_sym => x Kx; apply/trivgP; rewrite -tiKH. by rewrite subsetI subsetIl (subset_trans _ (regK x _)) ?setSI. Qed. Lemma set_Frobenius_compl G K H : K ><| H = G -> [Frobenius G with kernel K] -> [Frobenius G = K ><| H]. Proof. move=> defG /Frobenius_kerP[ntK ltKG _ regKG]. apply/Frobenius_semiregularP=> //. by apply: contraTneq ltKG => H_1; rewrite -defG H_1 sdprodg1 properxx. apply: semiregular_sym => y /regKG sCyK. have [_ sHG _ _ tiKH] := sdprod_context defG. by apply/trivgP; rewrite /= -(setIidPr sHG) setIAC -tiKH setSI. Qed. Lemma Frobenius_kerS G K G1 : G1 \subset G -> K \proper G1 -> [Frobenius G with kernel K] -> [Frobenius G1 with kernel K]. Proof. move=> sG1G ltKG1 /Frobenius_kerP[ntK _ /andP[_ nKG] regKG]. apply/Frobenius_kerP; rewrite /normal proper_sub // (subset_trans sG1G) //. by split=> // x /regKG; apply: subset_trans; rewrite setSI. Qed. Lemma Frobenius_action_kernel_def G H K sT S to : K ><| H = G -> @Frobenius_action _ G H sT S to -> K :=: 1 :|: [set x in G | 'Fix_(S | to)[x] == set0]. Proof. move=> defG FrobG. have partG: partition (gval K |: (H^# :^: K)) G. apply: Frobenius_partition; apply/andP; rewrite defG; split=> //. by apply/Frobenius_actionP; apply: hasFrobeniusAction FrobG. have{FrobG} [ffulG transG regG ntH [u Su defH]]:= FrobG. apply/setP=> x /[!inE]; have [-> | ntx] := eqVneq; first exact: group1. rewrite /= -(cover_partition partG) /cover. have neKHy y: gval K <> H^# :^ y. by move/setP/(_ 1); rewrite group1 conjD1g setD11. rewrite big_setU1 /= ?inE; last by apply/imsetP=> [[y _ /neKHy]]. have [nsKG sHG _ _ tiKH] := sdprod_context defG; have [sKG nKG]:= andP nsKG. symmetry; case Kx: (x \in K) => /=. apply/set0Pn=> [[v /setIP[Sv]]]; have [y Gy ->] := atransP2 transG Su Sv. rewrite -sub1set -astabC sub1set astab1_act mem_conjg => Hxy. case/negP: ntx; rewrite -in_set1 -(conjgKV y x) -mem_conjgV conjs1g -tiKH. by rewrite defH setIA inE -mem_conjg (setIidPl sKG) (normsP nKG) ?Kx. apply/andP=> [[/bigcupP[_ /imsetP[y Ky ->] Hyx] /set0Pn[]]]; exists (to u y). rewrite inE (actsP (atrans_acts transG)) ?(subsetP sKG) // Su. rewrite -sub1set -astabC sub1set astab1_act. by rewrite conjD1g defH conjIg !inE in Hyx; case/and3P: Hyx. Qed. End FrobeniusBasics. Arguments normedTI_P {gT A G L}. Arguments normedTI_memJ_P {gT A G L}. Arguments Frobenius_kerP {gT G K}. Lemma Frobenius_coprime_quotient (gT : finGroupType) (G K H N : {group gT}) : K ><| H = G -> N <| G -> coprime #|K| #|H| /\ H :!=: 1%g -> N \proper K /\ {in H^#, forall x, 'C_K[x] \subset N} -> [Frobenius G / N = (K / N) ><| (H / N)]%g. Proof. move=> defG nsNG [coKH ntH] [ltNK regH]. have [[sNK _] [_ /mulG_sub[sKG sHG] _ _]] := (andP ltNK, sdprodP defG). have [_ nNG] := andP nsNG; have nNH := subset_trans sHG nNG. apply/Frobenius_semiregularP; first exact: quotient_coprime_sdprod. - by rewrite quotient_neq1 ?(normalS _ sKG). - by rewrite -(isog_eq1 (quotient_isog _ _)) ?coprime_TIg ?(coprimeSg sNK). move=> _ /(subsetP (quotientD1 _ _))/morphimP[x nNx H1x ->]. rewrite -cent_cycle -quotient_cycle //=. rewrite -strongest_coprime_quotient_cent ?cycle_subG //. - by rewrite cent_cycle quotientS1 ?regH. - by rewrite subIset ?sNK. - rewrite (coprimeSg (subsetIl N _)) ?(coprimeSg sNK) ?(coprimegS _ coKH) //. by rewrite cycle_subG; case/setD1P: H1x. by rewrite orbC abelian_sol ?cycle_abelian. Qed. Section InjmFrobenius. Variables (gT rT : finGroupType) (D G : {group gT}) (f : {morphism D >-> rT}). Implicit Types (H K : {group gT}) (sGD : G \subset D) (injf : 'injm f). Lemma injm_Frobenius_compl H sGD injf : [Frobenius G with complement H] -> [Frobenius f @* G with complement f @* H]. Proof. case/andP=> neqGH /normedTI_P[nzH /subsetIP[sHG _] tiHG]. have sHD := subset_trans sHG sGD; have sH1D := subset_trans (subD1set H 1) sHD. apply/andP; rewrite (can_in_eq (injmK injf)) //; split=> //. apply/normedTI_P; rewrite normD1 -injmD1 // -!cards_eq0 card_injm // in nzH *. rewrite subsetI normG morphimS //; split=> // _ /morphimP[x Dx Gx ->] ti'fHx. rewrite mem_morphim ?tiHG //; apply: contra ti'fHx; rewrite -!setI_eq0 => tiHx. by rewrite -morphimJ // -injmI ?conj_subG // (eqP tiHx) morphim0. Qed. Lemma injm_Frobenius H K sGD injf : [Frobenius G = K ><| H] -> [Frobenius f @* G = f @* K ><| f @* H]. Proof. case/andP=> /eqP defG frobG. by apply/andP; rewrite (injm_sdprod _ injf defG) // eqxx injm_Frobenius_compl. Qed. Lemma injm_Frobenius_ker K sGD injf : [Frobenius G with kernel K] -> [Frobenius f @* G with kernel f @* K]. Proof. case/existsP=> H frobG; apply/existsP. by exists (f @* H)%G; apply: injm_Frobenius. Qed. Lemma injm_Frobenius_group sGD injf : [Frobenius G] -> [Frobenius f @* G]. Proof. case/existsP=> H frobG; apply/existsP; exists (f @* H)%G. exact: injm_Frobenius_compl. Qed. End InjmFrobenius. Theorem Frobenius_Ldiv (gT : finGroupType) (G : {group gT}) n : n %| #|G| -> n %| #|'Ldiv_n(G)|. Proof. move=> nG; move: {2}_.+1 (ltnSn (#|G| %/ n)) => mq. elim: mq => // mq IHm in gT G n nG *; case/dvdnP: nG => q oG. have [q_gt0 n_gt0] : 0 < q /\ 0 < n by apply/andP; rewrite -muln_gt0 -oG. rewrite ltnS oG mulnK // => leqm. have:= q_gt0; rewrite leq_eqVlt => /predU1P[q1 | lt1q]. rewrite -(mul1n n) q1 -oG (setIidPl _) //. by apply/subsetP=> x Gx; rewrite inE -order_dvdn order_dvdG. pose p := pdiv q; have pr_p: prime p by apply: pdiv_prime. have lt1p: 1 < p := prime_gt1 pr_p; have p_gt0 := ltnW lt1p. have{leqm} lt_qp_mq: q %/ p < mq by apply: leq_trans leqm; rewrite ltn_Pdiv. have: n %| #|'Ldiv_(p * n)(G)|. have: p * n %| #|G| by rewrite oG dvdn_pmul2r ?pdiv_dvd. move/IHm=> IH; apply: dvdn_trans (IH _); first exact: dvdn_mull. by rewrite oG divnMr. rewrite -(cardsID 'Ldiv_n()) dvdn_addl. rewrite -setIA ['Ldiv_n(_)](setIidPr _) //. by apply/subsetP=> x; rewrite !inE -!order_dvdn; apply: dvdn_mull. rewrite -setIDA; set A := _ :\: _. have pA x: x \in A -> #[x]`_p = (n`_p * p)%N. rewrite !inE -!order_dvdn => /andP[xn xnp]. rewrite !p_part // -expnSr; congr (p ^ _)%N; apply/eqP. rewrite eqn_leq -{1}addn1 -(pfactorK 1 pr_p) -lognM ?expn1 // mulnC. rewrite dvdn_leq_log ?muln_gt0 ?p_gt0 //= ltnNge; apply: contra xn => xn. move: xnp; rewrite -[#[x]](partnC p) //. rewrite !Gauss_dvd ?coprime_partC //; case/andP=> _. rewrite p_part ?pfactor_dvdn // xn Gauss_dvdr // coprime_sym. exact: pnat_coprime (pnat_id _) (part_pnat _ _). rewrite -(partnC p n_gt0) Gauss_dvd ?coprime_partC //; apply/andP; split. rewrite -sum1_card (partition_big_imset (@cycle _)) /=. apply: dvdn_sum => _ /imsetP[x /setIP[Gx Ax] ->]. rewrite (eq_bigl (generator <[x]>)) => [|y]. rewrite sum1dep_card -totient_gen -[#[x]](partnC p) //. rewrite totient_coprime ?coprime_partC // dvdn_mulr // . by rewrite (pA x Ax) p_part // -expnSr totient_pfactor // dvdn_mull. rewrite /generator eq_sym andbC; case xy: {+}(_ == _) => //. rewrite !inE -!order_dvdn in Ax *. by rewrite -cycle_subG /order -(eqP xy) cycle_subG Gx. rewrite -sum1_card (partition_big_imset (fun x => x.`_p ^: G)) /=. apply: dvdn_sum => _ /imsetP[x /setIP[Gx Ax] ->]. set y := x.`_p; have oy: #[y] = (n`_p * p)%N by rewrite order_constt pA. rewrite (partition_big (fun x => x.`_p) [in y ^: G]) /= => [|z]; last first. by case/andP=> _ /eqP <-; rewrite /= class_refl. pose G' := ('C_G[y] / <[y]>)%G; pose n' := gcdn #|G'| n`_p^'. have n'_gt0: 0 < n' by rewrite gcdn_gt0 cardG_gt0. rewrite (eq_bigr (fun _ => #|'Ldiv_n'(G')|)) => [|_ /imsetP[a Ga ->]]. rewrite sum_nat_const -index_cent1 indexgI. rewrite -(dvdn_pmul2l (cardG_gt0 'C_G[y])) mulnA LagrangeI. have oCy: #|'C_G[y]| = (#[y] * #|G'|)%N. rewrite card_quotient ?subcent1_cycle_norm // Lagrange //. by rewrite subcent1_cycle_sub ?groupX. rewrite oCy -mulnA -(muln_lcm_gcd #|G'|) -/n' mulnA dvdn_mul //. rewrite muln_lcmr -oCy order_constt pA // mulnAC partnC // dvdn_lcm. by rewrite cardSg ?subsetIl // mulnC oG dvdn_pmul2r ?pdiv_dvd. apply: IHm; [exact: dvdn_gcdl | apply: leq_ltn_trans lt_qp_mq]. rewrite -(@divnMr n`_p^') // -muln_lcm_gcd mulnC divnMl //. rewrite leq_divRL // divn_mulAC ?leq_divLR ?dvdn_mulr ?dvdn_lcmr //. rewrite dvdn_leq ?muln_gt0 ?q_gt0 //= mulnC muln_lcmr dvdn_lcm. rewrite -(@dvdn_pmul2l n`_p) // mulnA -oy -oCy mulnCA partnC // -oG. by rewrite cardSg ?subsetIl // dvdn_mul ?pdiv_dvd. pose h := [fun z => coset <[y]> (z ^ a^-1)]. pose h' := [fun Z : coset_of <[y]> => (y * (repr Z).`_p^') ^ a]. rewrite -sum1_card (reindex_onto h h') /= => [|Z]; last first. rewrite conjgK coset_kerl ?cycle_id ?morph_constt ?repr_coset_norm //. rewrite /= coset_reprK 2!inE -order_dvdn dvdn_gcd => /and3P[_ _ p'Z]. by apply: constt_p_elt (pnat_dvd p'Z _); apply: part_pnat. apply: eq_bigl => z; apply/andP/andP=> [[]|[]]. rewrite inE -andbA => /and3P[Gz Az _] /eqP zp_ya. have czy: z ^ a^-1 \in 'C[y]. rewrite -mem_conjg -normJ conjg_set1 -zp_ya. by apply/cent1P; apply: commuteX. have Nz: z ^ a^-1 \in 'N(<[y]>) by apply: subsetP czy; apply: norm_gen. have G'z: h z \in G' by rewrite mem_morphim //= inE groupJ // groupV. rewrite inE G'z inE -order_dvdn dvdn_gcd order_dvdG //=. rewrite /order -morphim_cycle // -quotientE card_quotient ?cycle_subG //. rewrite -(@dvdn_pmul2l #[y]) // Lagrange; last first. by rewrite /= cycleJ cycle_subG mem_conjgV -zp_ya mem_cycle. rewrite oy mulnAC partnC // [#|_|]orderJ; split. by rewrite !inE -!order_dvdn mulnC in Az; case/andP: Az. set Z := coset _ _; have NZ := repr_coset_norm Z; have:= coset_reprK Z. case/kercoset_rcoset=> {NZ}// _ /cycleP[i ->] ->{Z}. rewrite consttM; last exact/commute_sym/commuteX/cent1P. rewrite (constt1P _) ?p_eltNK 1?p_eltX ?p_elt_constt // mul1g. by rewrite conjMg consttJ conjgKV -zp_ya consttC. rewrite 2!inE -order_dvdn; set Z := coset _ _ => /andP[Cz n'Z] /eqP def_z. have Nz: z ^ a^-1 \in 'N(<[y]>). rewrite -def_z conjgK groupMr; first by rewrite -(cycle_subG y) normG. by rewrite groupX ?repr_coset_norm. have{Cz} /setIP[Gz Cz]: z ^ a^-1 \in 'C_G[y]. case/morphimP: Cz => u Nu Cu /kercoset_rcoset[] // _ /cycleP[i ->] ->. by rewrite groupMr // groupX // inE groupX //; apply/cent1P. have{def_z} zp_ya: z.`_p = y ^ a. rewrite -def_z consttJ consttM. rewrite constt_p_elt ?p_elt_constt //. by rewrite (constt1P _) ?p_eltNK ?p_elt_constt ?mulg1. apply: commute_sym; apply/cent1P. by rewrite -def_z conjgK groupMl // in Cz; apply/cent1P. have ozp: #[z ^ a^-1]`_p = #[y] by rewrite -order_constt consttJ zp_ya conjgK. split; rewrite zp_ya // -class_lcoset lcoset_id // eqxx andbT. rewrite -(conjgKV a z) !inE groupJ //= -!order_dvdn orderJ; apply/andP; split. apply: contra (partn_dvd p n_gt0) _. by rewrite ozp -(muln1 n`_p) oy dvdn_pmul2l // dvdn1 neq_ltn lt1p orbT. rewrite -(partnC p n_gt0) mulnCA mulnA -oy -(@partnC p #[_]) // ozp. apply dvdn_mul => //; apply: dvdn_trans (dvdn_trans n'Z (dvdn_gcdr _ _)). rewrite {2}/order -morphim_cycle // -quotientE card_quotient ?cycle_subG //. rewrite -(@dvdn_pmul2l #|<[z ^ a^-1]> :&: <[y]>|) ?cardG_gt0 // LagrangeI. rewrite -[#|<[_]>|](partnC p) ?order_gt0 // dvdn_pmul2r // ozp. by rewrite cardSg ?subsetIr. Qed.
action.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrbool ssrfun ssrnotations eqtype. From mathcomp Require Import ssrnat div seq prime fintype bigop finset. From mathcomp Require Import fingroup morphism perm automorphism quotient. (******************************************************************************) (* Group action: orbits, stabilisers, transitivity. *) (* is_action D to == the function to : T -> aT -> T defines an action *) (* of D : {set aT} on T. *) (* action D T == structure for a function defining an action of D. *) (* act_dom to == the domain D of to : action D rT. *) (* {action: aT &-> T} == structure for a total action. *) (* := action [set: aT] T *) (* TotalAction to1 toM == the constructor for total actions; to1 and toM *) (* are the proofs of the action identities for 1 and *) (* a * b, respectively. *) (* is_groupAction R to == to is a group action on range R: for all a in D, *) (* the permutation induced by to a is in Aut R. Thus *) (* the action of D must be trivial outside R. *) (* groupAction D R == the structure for group actions of D on R. This *) (* is a telescope on action D rT. *) (* gact_range to == the range R of to : groupAction D R. *) (* GroupAction toAut == constructs a groupAction for action to from *) (* toAut : actm to @* D \subset Aut R (actm to is *) (* the morphism to {perm rT} associated to 'to'). *) (* orbit to A x == the orbit of x under the action of A via to. *) (* orbit_transversal to A S == a transversal of the partition orbit to A @: S *) (* of S, provided A acts on S via to. *) (* amove to A x y == the set of a in A whose action sends x to y. *) (* 'C_A[x | to] == the stabiliser of x : rT in A :&: D. *) (* 'C_A(S | to) == the pointwise stabiliser of S : {set rT} in D :&: A. *) (* 'N_A(S | to) == the global stabiliser of S : {set rT} in D :&: A. *) (* 'Fix_(S | to)[a] == the set of fixpoints of a in S. *) (* 'Fix_(S | to)(A) == the set of fixpoints of A in S. *) (* In the first three _A can be omitted and defaults to the domain D of to; *) (* in the last two S can be omitted and defaults to [set: T], so 'Fix_to[a] *) (* is the set of all fixpoints of a. *) (* The domain restriction ensures that stabilisers have a canonical group *) (* structure, but note that 'Fix sets are generally not groups. Indeed, we *) (* provide alternative definitions when to is a group action on R: *) (* 'C_(G | to)(A) == the centraliser in R :&: G of the group action of *) (* D :&: A via to *) (* 'C_(G | to)[a] == the centraliser in R :&: G of a \in D, via to. *) (* These sets are groups when G is; G can be omitted: 'C(|to)(A) is the *) (* centraliser in R of the action of D :&: A via to. *) (* [acts A, on S | to] == A \subset D acts on the set S via to. *) (* {acts A, on S | to} == A acts on the set S (Prop statement). *) (* {acts A, on group G | to} == [acts A, on S | to] /\ G \subset R, i.e., *) (* A \subset D acts on G \subset R, via *) (* to : groupAction D R. *) (* [transitive A, on S | to] == A acts transitively on S. *) (* [faithful A, on S | to] == A acts faithfully on S. *) (* acts_irreducibly to A G == A acts irreducibly via the groupAction to *) (* on the nontrivial group G, i.e., A does *) (* not act on any nontrivial subgroup of G. *) (* Important caveat: the definitions of orbit, amove, 'Fix_(S | to)(A), *) (* transitive and faithful assume that A is a subset of the domain D. As most *) (* of the permutation actions we consider are total this is usually harmless. *) (* (Note that the theory of partial actions is only partially developed.) *) (* In all of the above, to is expected to be the actual action structure, *) (* not merely the function. There is a special scope %act for actions, and *) (* constructions and notations for many classical actions: *) (* 'P == natural action of a permutation group via aperm. *) (* 'J == internal group action (conjugation) via conjg (_ ^ _). *) (* 'R == regular group action (right translation) via mulg (_ * _). *) (* (However, to limit ambiguity, _ * _ is NOT a canonical action.) *) (* to^* == the action induced by to on {set rT} via to^* (== setact to). *) (* 'Js == the internal action on subsets via _ :^ _, equivalent to 'J^*. *) (* 'Rs == the regular action on subsets via rcoset, equivalent to 'R^*. *) (* 'JG == the conjugation action on {group rT} via (_ :^ _)%G. *) (* to / H == the action induced by to on coset_of H via qact to H, and *) (* restricted to (qact_dom to H) == 'N(rcosets H 'N(H) | to^* ). *) (* 'Q == the action induced to cosets by conjugation; the domain is *) (* qact_dom 'J H, which is provably equal to 'N(H). *) (* to %% A == the action of coset_of A via modact to A, with domain D / A *) (* and support restricted to 'C(D :&: A | to). *) (* to \ sAD == the action of A via ract to sAD == to, if sAD : A \subset D. *) (* [Aut G] == the permutation action restricted to Aut G, via autact G. *) (* <[nRA]> == the action of A on R via actby nRA == to in A and on R, and *) (* the trivial action elsewhere; here nRA : [acts A, on R | to] *) (* or nRA : {acts A, on group R | to}. *) (* to^? == the action induced by to on sT : @subType rT P, via subact to *) (* with domain subact_dom P to == 'N([set x | P x] | to). *) (* <<phi>> == the action of phi : D >-> {perm rT}, via mact phi. *) (* to \o f == the composite action (with domain f @*^-1 D) of the action to *) (* with f : {morphism G >-> aT}, via comp_act to f. Here f must *) (* be the actual morphism object (e.g., coset_morphism H), not *) (* the underlying function (e.g., coset H). *) (* The explicit application of an action to is usually written (to%act x a), *) (* but %act can be omitted if to is an abstract action or a set action to^*. *) (* Note that this form will simplify and expose the acting function. *) (* There is a %gact scope for group actions; the notations above are *) (* recognised in %gact when they denote canonical group actions. *) (* Actions can be used to define morphisms: *) (* actperm to == the morphism D >-> {perm rT} induced by to. *) (* actm to a == if a \in D the function on D induced by the action to, else *) (* the identity function. If to is a group action with range R *) (* then actm to a is canonically a morphism on R. *) (* We also define here the restriction operation on permutations (the domain *) (* of this operations is a stabiliser), and local automorphism groups: *) (* restr_perm S p == if p acts on S, the permutation with support in S that *) (* coincides with p on S; else the identity. Note that *) (* restr_perm is a permutation group morphism that maps *) (* Aut G to Aut S when S is a subgroup of G. *) (* Aut_in A G == the local permutation group 'N_A(G | 'P) / 'C_A(G | 'P) *) (* Usually A is an automorphism group, and then Aut_in A G *) (* is isomorphic to a subgroup of Aut G, specifically *) (* restr_perm @* A. *) (* Finally, gproduct.v will provide a semi-direct group construction that *) (* maps an external group action to an internal one; the theory of morphisms *) (* between such products makes use of the following definition: *) (* morph_act to to' f fA <=> the action of to' on the images of f and fA is *) (* the image of the action of to, i.e., for all x and a we *) (* have f (to x a) = to' (f x) (fA a). Note that there is *) (* no mention of the domains of to and to'; if needed, this *) (* predicate should be restricted via the {in ...} notation *) (* and domain conditions should be added. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope action_scope. Declare Scope groupAction_scope. Import GroupScope. Section ActionDef. Variables (aT : finGroupType) (D : {set aT}) (rT : Type). Implicit Types a b : aT. Implicit Type x : rT. Definition act_morph to x := forall a b, to x (a * b) = to (to x a) b. Definition is_action to := left_injective to /\ forall x, {in D &, act_morph to x}. Record action := Action {act :> rT -> aT -> rT; _ : is_action act}. Definition clone_action to := let: Action _ toP := to return {type of Action for to} -> action in fun k => k toP. End ActionDef. (* Need to close the Section here to avoid re-declaring all Argument Scopes *) Delimit Scope action_scope with act. Bind Scope action_scope with action. Arguments act_morph {aT rT%_type} to x%_g. Arguments is_action {aT} D%_g {rT} to. Arguments act {aT D%_g rT%_type} to%_act x%_g a%_g : rename. Arguments clone_action [aT D%_g rT%_type to%_act] _. Notation "{ 'action' aT &-> T }" := (action [set: aT] T) (format "{ 'action' aT &-> T }") : type_scope. Notation "[ 'action' 'of' to ]" := (clone_action (@Action _ _ _ to)) (format "[ 'action' 'of' to ]") : form_scope. Definition act_dom aT D rT of @action aT D rT := D. Section TotalAction. Variables (aT : finGroupType) (rT : Type) (to : rT -> aT -> rT). Hypotheses (to1 : to^~ 1 =1 id) (toM : forall x, act_morph to x). Lemma is_total_action : is_action setT to. Proof. split=> [a | x a b _ _] /=; last by rewrite toM. by apply: can_inj (to^~ a^-1) _ => x; rewrite -toM ?mulgV. Qed. Definition TotalAction := Action is_total_action. End TotalAction. Section ActionDefs. Variables (aT aT' : finGroupType) (D : {set aT}) (D' : {set aT'}). Definition morph_act rT rT' (to : action D rT) (to' : action D' rT') f fA := forall x a, f (to x a) = to' (f x) (fA a). Variable rT : finType. (* Most definitions require a finType structure on rT *) Implicit Type to : action D rT. Implicit Type A : {set aT}. Implicit Type S : {set rT}. Definition actm to a := if a \in D then to^~ a else id. Definition setact to S a := [set to x a | x in S]. Definition orbit to A x := to x @: A. Definition amove to A x y := [set a in A | to x a == y]. Definition afix to A := [set x | A \subset [set a | to x a == x]]. Definition astab S to := D :&: [set a | S \subset [set x | to x a == x]]. Definition astabs S to := D :&: [set a | S \subset to^~ a @^-1: S]. Definition acts_on A S to := {in A, forall a x, (to x a \in S) = (x \in S)}. Definition atrans A S to := S \in orbit to A @: S. Definition faithful A S to := A :&: astab S to \subset [1]. End ActionDefs. Arguments setact {aT D%_g rT} to%_act S%_g a%_g. Arguments orbit {aT D%_g rT} to%_act A%_g x%_g. Arguments amove {aT D%_g rT} to%_act A%_g x%_g y%_g. Arguments afix {aT D%_g rT} to%_act A%_g. Arguments astab {aT D%_g rT} S%_g to%_act. Arguments astabs {aT D%_g rT} S%_g to%_act. Arguments acts_on {aT D%_g rT} A%_g S%_g to%_act. Arguments atrans {aT D%_g rT} A%_g S%_g to%_act. Arguments faithful {aT D%_g rT} A%_g S%_g to%_act. Notation "to ^*" := (setact to) : function_scope. Prenex Implicits orbit amove. Notation "''Fix_' to ( A )" := (afix to A) (to at level 2, format "''Fix_' to ( A )") : group_scope. (* camlp4 grammar factoring *) Notation "''Fix_' ( to ) ( A )" := 'Fix_to(A) (only parsing) : group_scope. Notation "''Fix_' ( S | to ) ( A )" := (S :&: 'Fix_to(A)) (format "''Fix_' ( S | to ) ( A )") : group_scope. Notation "''Fix_' to [ a ]" := ('Fix_to([set a])) (to at level 2, format "''Fix_' to [ a ]") : group_scope. Notation "''Fix_' ( S | to ) [ a ]" := (S :&: 'Fix_to[a]) (format "''Fix_' ( S | to ) [ a ]") : group_scope. Notation "''C' ( S | to )" := (astab S to) : group_scope. Notation "''C_' A ( S | to )" := (A :&: 'C(S | to)) : group_scope. Notation "''C_' ( A ) ( S | to )" := 'C_A(S | to) (only parsing) : group_scope. Notation "''C' [ x | to ]" := ('C([set x] | to)) : group_scope. Notation "''C_' A [ x | to ]" := (A :&: 'C[x | to]) : group_scope. Notation "''C_' ( A ) [ x | to ]" := 'C_A[x | to] (only parsing) : group_scope. Notation "''N' ( S | to )" := (astabs S to) (format "''N' ( S | to )") : group_scope. Notation "''N_' A ( S | to )" := (A :&: 'N(S | to)) (A at level 2, format "''N_' A ( S | to )") : group_scope. Notation "[ 'acts' A , 'on' S | to ]" := (A \subset pred_of_set 'N(S | to)) (format "[ 'acts' A , 'on' S | to ]") : form_scope. Notation "{ 'acts' A , 'on' S | to }" := (acts_on A S to) (format "{ 'acts' A , 'on' S | to }") : type_scope. Notation "[ 'transitive' A , 'on' S | to ]" := (atrans A S to) (format "[ 'transitive' A , 'on' S | to ]") : form_scope. Notation "[ 'faithful' A , 'on' S | to ]" := (faithful A S to) (format "[ 'faithful' A , 'on' S | to ]") : form_scope. Section RawAction. (* Lemmas that do not require the group structure on the action domain. *) (* Some lemmas like actMin would be actually be valid for arbitrary rT, *) (* e.g., for actions on a function type, but would be difficult to use *) (* as a view due to the confusion between parameters and assumptions. *) Variables (aT : finGroupType) (D : {set aT}) (rT : finType) (to : action D rT). Implicit Types (a : aT) (x y : rT) (A B : {set aT}) (S T : {set rT}). Lemma act_inj : left_injective to. Proof. by case: to => ? []. Qed. Arguments act_inj : clear implicits. Lemma actMin x : {in D &, act_morph to x}. Proof. by case: to => ? []. Qed. Lemma actmEfun a : a \in D -> actm to a = to^~ a. Proof. by rewrite /actm => ->. Qed. Lemma actmE a : a \in D -> actm to a =1 to^~ a. Proof. by move=> Da; rewrite actmEfun. Qed. Lemma setactE S a : to^* S a = [set to x a | x in S]. Proof. by []. Qed. Lemma mem_setact S a x : x \in S -> to x a \in to^* S a. Proof. exact: imset_f. Qed. Lemma card_setact S a : #|to^* S a| = #|S|. Proof. by apply: card_imset; apply: act_inj. Qed. Lemma setact_is_action : is_action D to^*. Proof. split=> [a R S eqRS | a b Da Db S]; last first. by rewrite /setact /= -imset_comp; apply: eq_imset => x; apply: actMin. apply/setP=> x; apply/idP/idP=> /(mem_setact a). by rewrite eqRS => /imsetP[y Sy /act_inj->]. by rewrite -eqRS => /imsetP[y Sy /act_inj->]. Qed. Canonical set_action := Action setact_is_action. Lemma orbitE A x : orbit to A x = to x @: A. Proof. by []. Qed. Lemma orbitP A x y : reflect (exists2 a, a \in A & to x a = y) (y \in orbit to A x). Proof. by apply: (iffP imsetP) => [] [a]; exists a. Qed. Lemma mem_orbit A x a : a \in A -> to x a \in orbit to A x. Proof. exact: imset_f. Qed. Lemma afixP A x : reflect (forall a, a \in A -> to x a = x) (x \in 'Fix_to(A)). Proof. rewrite inE; apply: (iffP subsetP) => [xfix a /xfix | xfix a Aa]. by rewrite inE => /eqP. by rewrite inE xfix. Qed. Lemma afixS A B : A \subset B -> 'Fix_to(B) \subset 'Fix_to(A). Proof. by move=> sAB; apply/subsetP=> u /[!inE]; apply: subset_trans. Qed. Lemma afixU A B : 'Fix_to(A :|: B) = 'Fix_to(A) :&: 'Fix_to(B). Proof. by apply/setP=> x; rewrite !inE subUset. Qed. Lemma afix1P a x : reflect (to x a = x) (x \in 'Fix_to[a]). Proof. by rewrite inE sub1set inE; apply: eqP. Qed. Lemma astabIdom S : 'C_D(S | to) = 'C(S | to). Proof. by rewrite setIA setIid. Qed. Lemma astab_dom S : {subset 'C(S | to) <= D}. Proof. by move=> a /setIP[]. Qed. Lemma astab_act S a x : a \in 'C(S | to) -> x \in S -> to x a = x. Proof. rewrite 2!inE => /andP[_ cSa] Sx; apply/eqP. by have /[1!inE] := subsetP cSa x Sx. Qed. Lemma astabS S1 S2 : S1 \subset S2 -> 'C(S2 | to) \subset 'C(S1 | to). Proof. by move=> sS12; apply/subsetP=> x /[!inE] /andP[->]; apply: subset_trans. Qed. Lemma astabsIdom S : 'N_D(S | to) = 'N(S | to). Proof. by rewrite setIA setIid. Qed. Lemma astabs_dom S : {subset 'N(S | to) <= D}. Proof. by move=> a /setIdP[]. Qed. Lemma astabs_act S a x : a \in 'N(S | to) -> (to x a \in S) = (x \in S). Proof. rewrite 2!inE subEproper properEcard => /andP[_]. rewrite (card_preimset _ (act_inj _)) ltnn andbF orbF => /eqP{2}->. by rewrite inE. Qed. Lemma astab_sub S : 'C(S | to) \subset 'N(S | to). Proof. apply/subsetP=> a cSa; rewrite !inE (astab_dom cSa). by apply/subsetP=> x Sx; rewrite inE (astab_act cSa). Qed. Lemma astabsC S : 'N(~: S | to) = 'N(S | to). Proof. apply/setP=> a; apply/idP/idP=> nSa; rewrite !inE (astabs_dom nSa). by rewrite -setCS -preimsetC; apply/subsetP=> x; rewrite inE astabs_act. by rewrite preimsetC setCS; apply/subsetP=> x; rewrite inE astabs_act. Qed. Lemma astabsI S T : 'N(S | to) :&: 'N(T | to) \subset 'N(S :&: T | to). Proof. apply/subsetP=> a; rewrite !inE -!andbA preimsetI => /and4P[-> nSa _ nTa] /=. by rewrite setISS. Qed. Lemma astabs_setact S a : a \in 'N(S | to) -> to^* S a = S. Proof. move=> nSa; apply/eqP; rewrite eqEcard card_setact leqnn andbT. by apply/subsetP=> _ /imsetP[x Sx ->]; rewrite astabs_act. Qed. Lemma astab1_set S : 'C[S | set_action] = 'N(S | to). Proof. apply/setP=> a; apply/idP/idP=> nSa. case/setIdP: nSa => Da; rewrite !inE Da sub1set inE => /eqP defS. by apply/subsetP=> x Sx; rewrite inE -defS mem_setact. by rewrite !inE (astabs_dom nSa) sub1set inE /= astabs_setact. Qed. Lemma astabs_set1 x : 'N([set x] | to) = 'C[x | to]. Proof. apply/eqP; rewrite eqEsubset astab_sub andbC setIS //. by apply/subsetP=> a; rewrite ?(inE,sub1set). Qed. Lemma acts_dom A S : [acts A, on S | to] -> A \subset D. Proof. by move=> nSA; rewrite (subset_trans nSA) ?subsetIl. Qed. Lemma acts_act A S : [acts A, on S | to] -> {acts A, on S | to}. Proof. by move=> nAS a Aa x; rewrite astabs_act ?(subsetP nAS). Qed. Lemma astabCin A S : A \subset D -> (A \subset 'C(S | to)) = (S \subset 'Fix_to(A)). Proof. move=> sAD; apply/subsetP/subsetP=> [sAC x xS | sSF a aA]. by apply/afixP=> a aA; apply: astab_act (sAC _ aA) xS. rewrite !inE (subsetP sAD _ aA); apply/subsetP=> x xS. by move/afixP/(_ _ aA): (sSF _ xS) => /[1!inE] ->. Qed. Section ActsSetop. Variables (A : {set aT}) (S T : {set rT}). Hypotheses (AactS : [acts A, on S | to]) (AactT : [acts A, on T | to]). Lemma astabU : 'C(S :|: T | to) = 'C(S | to) :&: 'C(T | to). Proof. by apply/setP=> a; rewrite !inE subUset; case: (a \in D). Qed. Lemma astabsU : 'N(S | to) :&: 'N(T | to) \subset 'N(S :|: T | to). Proof. by rewrite -(astabsC S) -(astabsC T) -(astabsC (S :|: T)) setCU astabsI. Qed. Lemma astabsD : 'N(S | to) :&: 'N(T | to) \subset 'N(S :\: T| to). Proof. by rewrite setDE -(astabsC T) astabsI. Qed. Lemma actsI : [acts A, on S :&: T | to]. Proof. by apply: subset_trans (astabsI S T); rewrite subsetI AactS. Qed. Lemma actsU : [acts A, on S :|: T | to]. Proof. by apply: subset_trans astabsU; rewrite subsetI AactS. Qed. Lemma actsD : [acts A, on S :\: T | to]. Proof. by apply: subset_trans astabsD; rewrite subsetI AactS. Qed. End ActsSetop. Lemma acts_in_orbit A S x y : [acts A, on S | to] -> y \in orbit to A x -> x \in S -> y \in S. Proof. by move=> nSA/imsetP[a Aa ->{y}] Sx; rewrite (astabs_act _ (subsetP nSA a Aa)). Qed. Lemma subset_faithful A B S : B \subset A -> [faithful A, on S | to] -> [faithful B, on S | to]. Proof. by move=> sAB; apply: subset_trans; apply: setSI. Qed. Section Reindex. Variables (vT : Type) (idx : vT) (op : Monoid.com_law idx) (S : {set rT}). Lemma reindex_astabs a F : a \in 'N(S | to) -> \big[op/idx]_(i in S) F i = \big[op/idx]_(i in S) F (to i a). Proof. move=> nSa; rewrite (reindex_inj (act_inj a)); apply: eq_bigl => x. exact: astabs_act. Qed. Lemma reindex_acts A a F : [acts A, on S | to] -> a \in A -> \big[op/idx]_(i in S) F i = \big[op/idx]_(i in S) F (to i a). Proof. by move=> nSA /(subsetP nSA); apply: reindex_astabs. Qed. End Reindex. End RawAction. Arguments act_inj {aT D rT} to a [x1 x2] : rename. Notation "to ^*" := (set_action to) : action_scope. Arguments orbitP {aT D rT to A x y}. Arguments afixP {aT D rT to A x}. Arguments afix1P {aT D rT to a x}. Arguments reindex_astabs [aT D rT] to [vT idx op S] a [F]. Arguments reindex_acts [aT D rT] to [vT idx op S A a F]. Section PartialAction. (* Lemmas that require a (partial) group domain. *) Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Implicit Types a : aT. Implicit Types x y : rT. Implicit Types A B : {set aT}. Implicit Types G H : {group aT}. Implicit Types S : {set rT}. Lemma act1 x : to x 1 = x. Proof. by apply: (act_inj to 1); rewrite -actMin ?mulg1. Qed. Lemma actKin : {in D, right_loop invg to}. Proof. by move=> a Da /= x; rewrite -actMin ?groupV // mulgV act1. Qed. Lemma actKVin : {in D, rev_right_loop invg to}. Proof. by move=> a Da /= x; rewrite -{2}(invgK a) actKin ?groupV. Qed. Lemma setactVin S a : a \in D -> to^* S a^-1 = to^~ a @^-1: S. Proof. by move=> Da; apply: can2_imset_pre; [apply: actKVin | apply: actKin]. Qed. Lemma actXin x a i : a \in D -> to x (a ^+ i) = iter i (to^~ a) x. Proof. move=> Da; elim: i => /= [|i <-]; first by rewrite act1. by rewrite expgSr actMin ?groupX. Qed. Lemma afix1 : 'Fix_to(1) = setT. Proof. by apply/setP=> x; rewrite !inE sub1set inE act1 eqxx. Qed. Lemma afixD1 G : 'Fix_to(G^#) = 'Fix_to(G). Proof. by rewrite -{2}(setD1K (group1 G)) afixU afix1 setTI. Qed. Lemma orbit_refl G x : x \in orbit to G x. Proof. by rewrite -{1}[x]act1 mem_orbit. Qed. Local Notation orbit_rel A := (fun x y => x \in orbit to A y). Lemma contra_orbit G x y : x \notin orbit to G y -> x != y. Proof. by apply: contraNneq => ->; apply: orbit_refl. Qed. Lemma orbit_in_sym G : G \subset D -> symmetric (orbit_rel G). Proof. move=> sGD; apply: symmetric_from_pre => x y /imsetP[a Ga]. by move/(canLR (actKin (subsetP sGD a Ga))) <-; rewrite mem_orbit ?groupV. Qed. Lemma orbit_in_trans G : G \subset D -> transitive (orbit_rel G). Proof. move=> sGD _ _ z /imsetP[a Ga ->] /imsetP[b Gb ->]. by rewrite -actMin ?mem_orbit ?groupM // (subsetP sGD). Qed. Lemma orbit_in_eqP G x y : G \subset D -> reflect (orbit to G x = orbit to G y) (x \in orbit to G y). Proof. move=> sGD; apply: (iffP idP) => [yGx|<-]; last exact: orbit_refl. by apply/setP=> z; apply/idP/idP=> /orbit_in_trans-> //; rewrite orbit_in_sym. Qed. Lemma orbit_in_transl G x y z : G \subset D -> y \in orbit to G x -> (y \in orbit to G z) = (x \in orbit to G z). Proof. by move=> sGD Gxy; rewrite !(orbit_in_sym sGD _ z) (orbit_in_eqP y x sGD Gxy). Qed. Lemma orbit_act_in x a G : G \subset D -> a \in G -> orbit to G (to x a) = orbit to G x. Proof. by move=> sGD /mem_orbit/orbit_in_eqP->. Qed. Lemma orbit_actr_in x a G y : G \subset D -> a \in G -> (to y a \in orbit to G x) = (y \in orbit to G x). Proof. by move=> sGD /mem_orbit/orbit_in_transl->. Qed. Lemma orbit_inv_in A x y : A \subset D -> (y \in orbit to A^-1 x) = (x \in orbit to A y). Proof. move/subsetP=> sAD; apply/imsetP/imsetP=> [] [a Aa ->]. by exists a^-1; rewrite -?mem_invg ?actKin // -groupV sAD -?mem_invg. by exists a^-1; rewrite ?memV_invg ?actKin // sAD. Qed. Lemma orbit_lcoset_in A a x : A \subset D -> a \in D -> orbit to (a *: A) x = orbit to A (to x a). Proof. move/subsetP=> sAD Da; apply/setP=> y; apply/imsetP/imsetP=> [] [b Ab ->{y}]. by exists (a^-1 * b); rewrite -?actMin ?mulKVg // ?sAD -?mem_lcoset. by exists (a * b); rewrite ?mem_mulg ?set11 ?actMin // sAD. Qed. Lemma orbit_rcoset_in A a x y : A \subset D -> a \in D -> (to y a \in orbit to (A :* a) x) = (y \in orbit to A x). Proof. move=> sAD Da; rewrite -orbit_inv_in ?mul_subG ?sub1set // invMg. by rewrite invg_set1 orbit_lcoset_in ?inv_subG ?groupV ?actKin ?orbit_inv_in. Qed. Lemma orbit_conjsg_in A a x y : A \subset D -> a \in D -> (to y a \in orbit to (A :^ a) (to x a)) = (y \in orbit to A x). Proof. move=> sAD Da; rewrite conjsgE. by rewrite orbit_lcoset_in ?groupV ?mul_subG ?sub1set ?actKin ?orbit_rcoset_in. Qed. Lemma orbit1P G x : reflect (orbit to G x = [set x]) (x \in 'Fix_to(G)). Proof. apply: (iffP afixP) => [xfix | xfix a Ga]. apply/eqP; rewrite eq_sym eqEsubset sub1set -{1}[x]act1 imset_f //=. by apply/subsetP=> y; case/imsetP=> a Ga ->; rewrite inE xfix. by apply/set1P; rewrite -xfix imset_f. Qed. Lemma card_orbit1 G x : #|orbit to G x| = 1%N -> orbit to G x = [set x]. Proof. move=> orb1; apply/eqP; rewrite eq_sym eqEcard {}orb1 cards1. by rewrite sub1set orbit_refl. Qed. Lemma orbit_partition G S : [acts G, on S | to] -> partition (orbit to G @: S) S. Proof. move=> actsGS; have sGD := acts_dom actsGS. have eqiG: {in S & &, equivalence_rel [rel x y | y \in orbit to G x]}. by move=> x y z * /=; rewrite orbit_refl; split=> // /orbit_in_eqP->. congr (partition _ _): (equivalence_partitionP eqiG). apply: eq_in_imset => x Sx; apply/setP=> y. by rewrite inE /= andb_idl // => /acts_in_orbit->. Qed. Definition orbit_transversal A S := transversal (orbit to A @: S) S. Lemma orbit_transversalP G S (P := orbit to G @: S) (X := orbit_transversal G S) : [acts G, on S | to] -> [/\ is_transversal X P S, X \subset S, {in X &, forall x y, (y \in orbit to G x) = (x == y)} & forall x, x \in S -> exists2 a, a \in G & to x a \in X]. Proof. move/orbit_partition; rewrite -/P => partP. have [/eqP defS tiP _] := and3P partP. have trXP: is_transversal X P S := transversalP partP. have sXS: X \subset S := transversal_sub trXP. split=> // [x y Xx Xy /= | x Sx]. have Sx := subsetP sXS x Xx. rewrite -(inj_in_eq (pblock_inj trXP)) // eq_pblock ?defS //. by rewrite (def_pblock tiP (imset_f _ Sx)) ?orbit_refl. have /imsetP[y Xy defxG]: orbit to G x \in pblock P @: X. by rewrite (pblock_transversal trXP) ?imset_f. suffices /orbitP[a Ga def_y]: y \in orbit to G x by exists a; rewrite ?def_y. by rewrite defxG mem_pblock defS (subsetP sXS). Qed. Lemma group_set_astab S : group_set 'C(S | to). Proof. apply/group_setP; split=> [|a b cSa cSb]. by rewrite !inE group1; apply/subsetP=> x _; rewrite inE act1. rewrite !inE groupM ?(@astab_dom _ _ _ to S) //; apply/subsetP=> x Sx. by rewrite inE actMin ?(@astab_dom _ _ _ to S) ?(astab_act _ Sx). Qed. Canonical astab_group S := group (group_set_astab S). Lemma afix_gen_in A : A \subset D -> 'Fix_to(<<A>>) = 'Fix_to(A). Proof. move=> sAD; apply/eqP; rewrite eqEsubset afixS ?sub_gen //=. by rewrite -astabCin gen_subG ?astabCin. Qed. Lemma afix_cycle_in a : a \in D -> 'Fix_to(<[a]>) = 'Fix_to[a]. Proof. by move=> Da; rewrite afix_gen_in ?sub1set. Qed. Lemma afixYin A B : A \subset D -> B \subset D -> 'Fix_to(A <*> B) = 'Fix_to(A) :&: 'Fix_to(B). Proof. by move=> sAD sBD; rewrite afix_gen_in ?afixU // subUset sAD. Qed. Lemma afixMin G H : G \subset D -> H \subset D -> 'Fix_to(G * H) = 'Fix_to(G) :&: 'Fix_to(H). Proof. by move=> sGD sHD; rewrite -afix_gen_in ?mul_subG // genM_join afixYin. Qed. Lemma sub_astab1_in A x : A \subset D -> (A \subset 'C[x | to]) = (x \in 'Fix_to(A)). Proof. by move=> sAD; rewrite astabCin ?sub1set. Qed. Lemma group_set_astabs S : group_set 'N(S | to). Proof. apply/group_setP; split=> [|a b cSa cSb]. by rewrite !inE group1; apply/subsetP=> x Sx; rewrite inE act1. rewrite !inE groupM ?(@astabs_dom _ _ _ to S) //; apply/subsetP=> x Sx. by rewrite inE actMin ?(@astabs_dom _ _ _ to S) ?astabs_act. Qed. Canonical astabs_group S := group (group_set_astabs S). Lemma astab_norm S : 'N(S | to) \subset 'N('C(S | to)). Proof. apply/subsetP=> a nSa; rewrite inE sub_conjg; apply/subsetP=> b cSb. have [Da Db] := (astabs_dom nSa, astab_dom cSb). rewrite mem_conjgV !inE groupJ //; apply/subsetP=> x Sx. rewrite inE !actMin ?groupM ?groupV //. by rewrite (astab_act cSb) ?actKVin ?astabs_act ?groupV. Qed. Lemma astab_normal S : 'C(S | to) <| 'N(S | to). Proof. by rewrite /normal astab_sub astab_norm. Qed. Lemma acts_sub_orbit G S x : [acts G, on S | to] -> (orbit to G x \subset S) = (x \in S). Proof. move/acts_act=> GactS. apply/subsetP/idP=> [| Sx y]; first by apply; apply: orbit_refl. by case/orbitP=> a Ga <-{y}; rewrite GactS. Qed. Lemma acts_orbit G x : G \subset D -> [acts G, on orbit to G x | to]. Proof. move/subsetP=> sGD; apply/subsetP=> a Ga; rewrite !inE sGD //. apply/subsetP=> _ /imsetP[b Gb ->]. by rewrite inE -actMin ?sGD // imset_f ?groupM. Qed. Lemma acts_subnorm_fix A : [acts 'N_D(A), on 'Fix_to(D :&: A) | to]. Proof. apply/subsetP=> a nAa; have [Da _] := setIP nAa; rewrite !inE Da. apply/subsetP=> x Cx /[1!inE]; apply/afixP=> b DAb. have [Db _]:= setIP DAb; rewrite -actMin // conjgCV actMin ?groupJ ?groupV //. by rewrite /= (afixP Cx) // memJ_norm // groupV (subsetP (normsGI _ _) _ nAa). Qed. Lemma atrans_orbit G x : [transitive G, on orbit to G x | to]. Proof. by apply: imset_f; apply: orbit_refl. Qed. Section OrbitStabilizer. Variables (G : {group aT}) (x : rT). Hypothesis sGD : G \subset D. Let ssGD := subsetP sGD. Lemma amove_act a : a \in G -> amove to G x (to x a) = 'C_G[x | to] :* a. Proof. move=> Ga; apply/setP=> b; have Da := ssGD Ga. rewrite mem_rcoset !(inE, sub1set) !groupMr ?groupV //. by case Gb: (b \in G); rewrite //= actMin ?groupV ?ssGD ?(canF_eq (actKVin Da)). Qed. Lemma amove_orbit : amove to G x @: orbit to G x = rcosets 'C_G[x | to] G. Proof. apply/setP => Ha; apply/imsetP/rcosetsP=> [[y] | [a Ga ->]]. by case/imsetP=> b Gb -> ->{Ha y}; exists b => //; rewrite amove_act. by rewrite -amove_act //; exists (to x a); first apply: mem_orbit. Qed. Lemma amoveK : {in orbit to G x, cancel (amove to G x) (fun Ca => to x (repr Ca))}. Proof. move=> _ /orbitP[a Ga <-]; rewrite amove_act //= -[G :&: _]/(gval _). case: repr_rcosetP => b; rewrite !(inE, sub1set)=> /and3P[Gb _ xbx]. by rewrite actMin ?ssGD ?(eqP xbx). Qed. Lemma orbit_stabilizer : orbit to G x = [set to x (repr Ca) | Ca in rcosets 'C_G[x | to] G]. Proof. rewrite -amove_orbit -imset_comp /=; apply/setP=> z. by apply/idP/imsetP=> [xGz | [y xGy ->]]; first exists z; rewrite /= ?amoveK. Qed. Lemma act_reprK : {in rcosets 'C_G[x | to] G, cancel (to x \o repr) (amove to G x)}. Proof. move=> _ /rcosetsP[a Ga ->] /=; rewrite amove_act ?rcoset_repr //. rewrite -[G :&: _]/(gval _); case: repr_rcosetP => b /setIP[Gb _]. exact: groupM. Qed. End OrbitStabilizer. Lemma card_orbit_in G x : G \subset D -> #|orbit to G x| = #|G : 'C_G[x | to]|. Proof. move=> sGD; rewrite orbit_stabilizer 1?card_in_imset //. exact: can_in_inj (act_reprK _). Qed. Lemma card_orbit_in_stab G x : G \subset D -> (#|orbit to G x| * #|'C_G[x | to]|)%N = #|G|. Proof. by move=> sGD; rewrite mulnC card_orbit_in ?Lagrange ?subsetIl. Qed. Lemma acts_sum_card_orbit G S : [acts G, on S | to] -> \sum_(T in orbit to G @: S) #|T| = #|S|. Proof. by move/orbit_partition/card_partition. Qed. Lemma astab_setact_in S a : a \in D -> 'C(to^* S a | to) = 'C(S | to) :^ a. Proof. move=> Da; apply/setP=> b; rewrite mem_conjg !inE -mem_conjg conjGid //. apply: andb_id2l => Db; rewrite sub_imset_pre; apply: eq_subset_r => x. by rewrite !inE !actMin ?groupM ?groupV // invgK (canF_eq (actKVin Da)). Qed. Lemma astab1_act_in x a : a \in D -> 'C[to x a | to] = 'C[x | to] :^ a. Proof. by move=> Da; rewrite -astab_setact_in // /setact imset_set1. Qed. Theorem Frobenius_Cauchy G S : [acts G, on S | to] -> \sum_(a in G) #|'Fix_(S | to)[a]| = (#|orbit to G @: S| * #|G|)%N. Proof. move=> GactS; have sGD := acts_dom GactS. transitivity (\sum_(a in G) \sum_(x in 'Fix_(S | to)[a]) 1%N). by apply: eq_bigr => a _; rewrite -sum1_card. rewrite (exchange_big_dep [in S]) /= => [|a x _]; last by case/setIP. rewrite (set_partition_big _ (orbit_partition GactS)) -sum_nat_const /=. apply: eq_bigr => _ /imsetP[x Sx ->]. rewrite -(card_orbit_in_stab x sGD) -sum_nat_const. apply: eq_bigr => y; rewrite orbit_in_sym // => /imsetP[a Ga defx]. rewrite defx astab1_act_in ?(subsetP sGD) //. rewrite -{2}(conjGid Ga) -conjIg cardJg -sum1_card setIA (setIidPl sGD). by apply: eq_bigl => b; rewrite !(sub1set, inE) -(acts_act GactS Ga) -defx Sx. Qed. Lemma atrans_dvd_index_in G S : G \subset D -> [transitive G, on S | to] -> #|S| %| #|G : 'C_G(S | to)|. Proof. move=> sGD /imsetP[x Sx {1}->]; rewrite card_orbit_in //. by rewrite indexgS // setIS // astabS // sub1set. Qed. Lemma atrans_dvd_in G S : G \subset D -> [transitive G, on S | to] -> #|S| %| #|G|. Proof. move=> sGD transG; apply: dvdn_trans (atrans_dvd_index_in sGD transG) _. exact: dvdn_indexg. Qed. Lemma atransPin G S : G \subset D -> [transitive G, on S | to] -> forall x, x \in S -> orbit to G x = S. Proof. by move=> sGD /imsetP[y _ ->] x; apply/orbit_in_eqP. Qed. Lemma atransP2in G S : G \subset D -> [transitive G, on S | to] -> {in S &, forall x y, exists2 a, a \in G & y = to x a}. Proof. by move=> sGD transG x y /(atransPin sGD transG) <- /imsetP. Qed. Lemma atrans_acts_in G S : G \subset D -> [transitive G, on S | to] -> [acts G, on S | to]. Proof. move=> sGD transG; apply/subsetP=> a Ga; rewrite !inE (subsetP sGD) //. by apply/subsetP=> x /(atransPin sGD transG) <-; rewrite inE imset_f. Qed. Lemma subgroup_transitivePin G H S x : x \in S -> H \subset G -> G \subset D -> [transitive G, on S | to] -> reflect ('C_G[x | to] * H = G) [transitive H, on S | to]. Proof. move=> Sx sHG sGD trG; have sHD := subset_trans sHG sGD. apply: (iffP idP) => [trH | defG]. rewrite group_modr //; apply/setIidPl/subsetP=> a Ga. have Sxa: to x a \in S by rewrite (acts_act (atrans_acts_in sGD trG)). have [b Hb xab]:= atransP2in sHD trH Sxa Sx. have Da := subsetP sGD a Ga; have Db := subsetP sHD b Hb. rewrite -(mulgK b a) mem_mulg ?groupV // !inE groupM //= sub1set inE. by rewrite actMin -?xab. apply/imsetP; exists x => //; apply/setP=> y; rewrite -(atransPin sGD trG Sx). apply/imsetP/imsetP=> [] [a]; last by exists a; first apply: (subsetP sHG). rewrite -defG => /imset2P[c b /setIP[_ cxc] Hb ->] ->. exists b; rewrite ?actMin ?(astab_dom cxc) ?(subsetP sHD) //. by rewrite (astab_act cxc) ?inE. Qed. End PartialAction. Arguments orbit_transversal {aT D%_g rT} to%_act A%_g S%_g. Arguments orbit_in_eqP {aT D rT to G x y}. Arguments orbit1P {aT D rT to G x}. Arguments contra_orbit [aT D rT] to G [x y]. Notation "''C' ( S | to )" := (astab_group to S) : Group_scope. Notation "''C_' A ( S | to )" := (setI_group A 'C(S | to)) : Group_scope. Notation "''C_' ( A ) ( S | to )" := (setI_group A 'C(S | to)) (only parsing) : Group_scope. Notation "''C' [ x | to ]" := (astab_group to [set x%g]) : Group_scope. Notation "''C_' A [ x | to ]" := (setI_group A 'C[x | to]) : Group_scope. Notation "''C_' ( A ) [ x | to ]" := (setI_group A 'C[x | to]) (only parsing) : Group_scope. Notation "''N' ( S | to )" := (astabs_group to S) : Group_scope. Notation "''N_' A ( S | to )" := (setI_group A 'N(S | to)) : Group_scope. Section TotalActions. (* These lemmas are only established for total actions (domain = [set: rT]) *) Variable (aT : finGroupType) (rT : finType). Variable to : {action aT &-> rT}. Implicit Types (a b : aT) (x y z : rT) (A B : {set aT}) (G H : {group aT}). Implicit Type S : {set rT}. Lemma actM x a b : to x (a * b) = to (to x a) b. Proof. by rewrite actMin ?inE. Qed. Lemma actK : right_loop invg to. Proof. by move=> a; apply: actKin; rewrite inE. Qed. Lemma actKV : rev_right_loop invg to. Proof. by move=> a; apply: actKVin; rewrite inE. Qed. Lemma actX x a n : to x (a ^+ n) = iter n (to^~ a) x. Proof. by elim: n => [|n /= <-]; rewrite ?act1 // -actM expgSr. Qed. Lemma actCJ a b x : to (to x a) b = to (to x b) (a ^ b). Proof. by rewrite !actM actK. Qed. Lemma actCJV a b x : to (to x a) b = to (to x (b ^ a^-1)) a. Proof. by rewrite (actCJ _ a) conjgKV. Qed. Lemma orbit_sym G x y : (x \in orbit to G y) = (y \in orbit to G x). Proof. exact/orbit_in_sym/subsetT. Qed. Lemma orbit_trans G x y z : x \in orbit to G y -> y \in orbit to G z -> x \in orbit to G z. Proof. exact/orbit_in_trans/subsetT. Qed. Lemma orbit_eqP G x y : reflect (orbit to G x = orbit to G y) (x \in orbit to G y). Proof. exact/orbit_in_eqP/subsetT. Qed. Lemma orbit_transl G x y z : y \in orbit to G x -> (y \in orbit to G z) = (x \in orbit to G z). Proof. exact/orbit_in_transl/subsetT. Qed. Lemma orbit_act G a x: a \in G -> orbit to G (to x a) = orbit to G x. Proof. exact/orbit_act_in/subsetT. Qed. Lemma orbit_actr G a x y : a \in G -> (to y a \in orbit to G x) = (y \in orbit to G x). Proof. by move/mem_orbit/orbit_transl; apply. Qed. Lemma orbit_eq_mem G x y : (orbit to G x == orbit to G y) = (x \in orbit to G y). Proof. exact: sameP eqP (orbit_eqP G x y). Qed. Lemma orbit_inv A x y : (y \in orbit to A^-1 x) = (x \in orbit to A y). Proof. by rewrite orbit_inv_in ?subsetT. Qed. Lemma orbit_lcoset A a x : orbit to (a *: A) x = orbit to A (to x a). Proof. by rewrite orbit_lcoset_in ?subsetT ?inE. Qed. Lemma orbit_rcoset A a x y : (to y a \in orbit to (A :* a) x) = (y \in orbit to A x). Proof. by rewrite orbit_rcoset_in ?subsetT ?inE. Qed. Lemma orbit_conjsg A a x y : (to y a \in orbit to (A :^ a) (to x a)) = (y \in orbit to A x). Proof. by rewrite orbit_conjsg_in ?subsetT ?inE. Qed. Lemma astabP S a : reflect (forall x, x \in S -> to x a = x) (a \in 'C(S | to)). Proof. apply: (iffP idP) => [cSa x|cSa]; first exact: astab_act. by rewrite !inE; apply/subsetP=> x Sx; rewrite inE cSa. Qed. Lemma astab1P x a : reflect (to x a = x) (a \in 'C[x | to]). Proof. by rewrite !inE sub1set inE; apply: eqP. Qed. Lemma sub_astab1 A x : (A \subset 'C[x | to]) = (x \in 'Fix_to(A)). Proof. by rewrite sub_astab1_in ?subsetT. Qed. Lemma astabC A S : (A \subset 'C(S | to)) = (S \subset 'Fix_to(A)). Proof. by rewrite astabCin ?subsetT. Qed. Lemma afix_cycle a : 'Fix_to(<[a]>) = 'Fix_to[a]. Proof. by rewrite afix_cycle_in ?inE. Qed. Lemma afix_gen A : 'Fix_to(<<A>>) = 'Fix_to(A). Proof. by rewrite afix_gen_in ?subsetT. Qed. Lemma afixM G H : 'Fix_to(G * H) = 'Fix_to(G) :&: 'Fix_to(H). Proof. by rewrite afixMin ?subsetT. Qed. Lemma astabsP S a : reflect (forall x, (to x a \in S) = (x \in S)) (a \in 'N(S | to)). Proof. apply: (iffP idP) => [nSa x|nSa]; first exact: astabs_act. by rewrite !inE; apply/subsetP=> x; rewrite inE nSa. Qed. Lemma card_orbit G x : #|orbit to G x| = #|G : 'C_G[x | to]|. Proof. by rewrite card_orbit_in ?subsetT. Qed. Lemma dvdn_orbit G x : #|orbit to G x| %| #|G|. Proof. by rewrite card_orbit dvdn_indexg. Qed. Lemma card_orbit_stab G x : (#|orbit to G x| * #|'C_G[x | to]|)%N = #|G|. Proof. by rewrite mulnC card_orbit Lagrange ?subsetIl. Qed. Lemma actsP A S : reflect {acts A, on S | to} [acts A, on S | to]. Proof. apply: (iffP idP) => [nSA x|nSA]; first exact: acts_act. by apply/subsetP=> a Aa /[!inE]; apply/subsetP=> x; rewrite inE nSA. Qed. Arguments actsP {A S}. Lemma setact_orbit A x b : to^* (orbit to A x) b = orbit to (A :^ b) (to x b). Proof. apply/setP=> y; apply/idP/idP=> /imsetP[_ /imsetP[a Aa ->] ->{y}]. by rewrite actCJ mem_orbit ?memJ_conjg. by rewrite -actCJ mem_setact ?mem_orbit. Qed. Lemma astab_setact S a : 'C(to^* S a | to) = 'C(S | to) :^ a. Proof. apply/setP=> b; rewrite mem_conjg. apply/astabP/astabP=> stab x => [Sx|]. by rewrite conjgE invgK !actM stab ?actK //; apply/imsetP; exists x. by case/imsetP=> y Sy ->{x}; rewrite -actM conjgCV actM stab. Qed. Lemma astab1_act x a : 'C[to x a | to] = 'C[x | to] :^ a. Proof. by rewrite -astab_setact /setact imset_set1. Qed. Lemma atransP G S : [transitive G, on S | to] -> forall x, x \in S -> orbit to G x = S. Proof. by case/imsetP=> x _ -> y; apply/orbit_eqP. Qed. Lemma atransP2 G S : [transitive G, on S | to] -> {in S &, forall x y, exists2 a, a \in G & y = to x a}. Proof. by move=> GtrS x y /(atransP GtrS) <- /imsetP. Qed. Lemma atrans_acts G S : [transitive G, on S | to] -> [acts G, on S | to]. Proof. move=> GtrS; apply/subsetP=> a Ga; rewrite !inE. by apply/subsetP=> x /(atransP GtrS) <-; rewrite inE imset_f. Qed. Lemma atrans_supgroup G H S : G \subset H -> [transitive G, on S | to] -> [transitive H, on S | to] = [acts H, on S | to]. Proof. move=> sGH trG; apply/idP/idP=> [|actH]; first exact: atrans_acts. case/imsetP: trG => x Sx defS; apply/imsetP; exists x => //. by apply/eqP; rewrite eqEsubset acts_sub_orbit ?Sx // defS imsetS. Qed. Lemma atrans_acts_card G S : [transitive G, on S | to] = [acts G, on S | to] && (#|orbit to G @: S| == 1%N). Proof. apply/idP/andP=> [GtrS | [nSG]]. split; first exact: atrans_acts. rewrite ((_ @: S =P [set S]) _) ?cards1 // eqEsubset sub1set. apply/andP; split=> //; apply/subsetP=> _ /imsetP[x Sx ->]. by rewrite inE (atransP GtrS). rewrite eqn_leq andbC lt0n => /andP[/existsP[X /imsetP[x Sx X_Gx]]]. rewrite (cardD1 X) {X}X_Gx imset_f // ltnS leqn0 => /eqP GtrS. apply/imsetP; exists x => //; apply/eqP. rewrite eqEsubset acts_sub_orbit // Sx andbT. apply/subsetP=> y Sy; have:= card0_eq GtrS (orbit to G y). by rewrite !inE /= imset_f // andbT => /eqP <-; apply: orbit_refl. Qed. Lemma atrans_dvd G S : [transitive G, on S | to] -> #|S| %| #|G|. Proof. by case/imsetP=> x _ ->; apply: dvdn_orbit. Qed. (* This is Aschbacher (5.2) *) Lemma acts_fix_norm A B : A \subset 'N(B) -> [acts A, on 'Fix_to(B) | to]. Proof. move=> nAB; have:= acts_subnorm_fix to B; rewrite !setTI. exact: subset_trans. Qed. Lemma faithfulP A S : reflect (forall a, a \in A -> {in S, to^~ a =1 id} -> a = 1) [faithful A, on S | to]. Proof. apply: (iffP subsetP) => [Cto1 a Aa Ca | Cto1 a]. by apply/set1P; rewrite Cto1 // inE Aa; apply/astabP. by case/setIP=> Aa /astabP Ca; apply/set1P; apply: Cto1. Qed. (* This is the first part of Aschbacher (5.7) *) Lemma astab_trans_gcore G S u : [transitive G, on S | to] -> u \in S -> 'C(S | to) = gcore 'C[u | to] G. Proof. move=> transG Su; apply/eqP; rewrite eqEsubset. rewrite gcore_max ?astabS ?sub1set //=; last first. exact: subset_trans (atrans_acts transG) (astab_norm _ _). apply/subsetP=> x cSx; apply/astabP=> uy. case/(atransP2 transG Su) => y Gy ->{uy}. by apply/astab1P; rewrite astab1_act (bigcapP cSx). Qed. (* This is Aschbacher (5.20) *) Theorem subgroup_transitiveP G H S x : x \in S -> H \subset G -> [transitive G, on S | to] -> reflect ('C_G[x | to] * H = G) [transitive H, on S | to]. Proof. by move=> Sx sHG; apply: subgroup_transitivePin (subsetT G). Qed. (* This is Aschbacher (5.21) *) Lemma trans_subnorm_fixP x G H S : let C := 'C_G[x | to] in let T := 'Fix_(S | to)(H) in [transitive G, on S | to] -> x \in S -> H \subset C -> reflect ((H :^: G) ::&: C = H :^: C) [transitive 'N_G(H), on T | to]. Proof. move=> C T trGS Sx sHC; have actGS := acts_act (atrans_acts trGS). have:= sHC; rewrite subsetI sub_astab1 => /andP[sHG cHx]. have Tx: x \in T by rewrite inE Sx. apply: (iffP idP) => [trN | trC]. apply/setP=> Ha; apply/setIdP/imsetP=> [[]|[a Ca ->{Ha}]]; last first. by rewrite conj_subG //; case/setIP: Ca => Ga _; rewrite imset_f. case/imsetP=> a Ga ->{Ha}; rewrite subsetI !sub_conjg => /andP[_ sHCa]. have Txa: to x a^-1 \in T. by rewrite inE -sub_astab1 astab1_act actGS ?Sx ?groupV. have [b] := atransP2 trN Tx Txa; case/setIP=> Gb nHb cxba. exists (b * a); last by rewrite conjsgM (normP nHb). by rewrite inE groupM //; apply/astab1P; rewrite actM -cxba actKV. apply/imsetP; exists x => //; apply/setP=> y; apply/idP/idP=> [Ty|]. have [Sy cHy]:= setIP Ty; have [a Ga defy] := atransP2 trGS Sx Sy. have: H :^ a^-1 \in H :^: C. rewrite -trC inE subsetI imset_f 1?conj_subG ?groupV // sub_conjgV. by rewrite -astab1_act -defy sub_astab1. case/imsetP=> b /setIP[Gb /astab1P cxb] defHb. rewrite defy -{1}cxb -actM mem_orbit // inE groupM //. by apply/normP; rewrite conjsgM -defHb conjsgKV. case/imsetP=> a /setIP[Ga nHa] ->{y}. by rewrite inE actGS // Sx (acts_act (acts_fix_norm _) nHa). Qed. End TotalActions. Arguments astabP {aT rT to S a}. Arguments orbit_eqP {aT rT to G x y}. Arguments astab1P {aT rT to x a}. Arguments astabsP {aT rT to S a}. Arguments atransP {aT rT to G S}. Arguments actsP {aT rT to A S}. Arguments faithfulP {aT rT to A S}. Section Restrict. Variables (aT : finGroupType) (D : {set aT}) (rT : Type). Variables (to : action D rT) (A : {set aT}). Definition ract of A \subset D := act to. Variable sAD : A \subset D. Lemma ract_is_action : is_action A (ract sAD). Proof. rewrite /ract; case: to => f [injf fM]. by split=> // x; apply: (sub_in2 (subsetP sAD)). Qed. Canonical raction := Action ract_is_action. Lemma ractE : raction =1 to. Proof. by []. Qed. (* Other properties of raction need rT : finType; we defer them *) (* until after the definition of actperm. *) End Restrict. Notation "to \ sAD" := (raction to sAD) (at level 50) : action_scope. Section ActBy. Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Definition actby_cond (A : {set aT}) R (to : action D rT) : Prop := [acts A, on R | to]. Definition actby A R to of actby_cond A R to := fun x a => if (x \in R) && (a \in A) then to x a else x. Variables (A : {group aT}) (R : {set rT}) (to : action D rT). Hypothesis nRA : actby_cond A R to. Lemma actby_is_action : is_action A (actby nRA). Proof. rewrite /actby; split=> [a x y | x a b Aa Ab /=]; last first. rewrite Aa Ab groupM // !andbT actMin ?(subsetP (acts_dom nRA)) //. by case Rx: (x \in R); rewrite ?(acts_act nRA) ?Rx. case Aa: (a \in A); rewrite ?andbF ?andbT //. case Rx: (x \in R); case Ry: (y \in R) => // eqxy; first exact: act_inj eqxy. by rewrite -eqxy (acts_act nRA Aa) Rx in Ry. by rewrite eqxy (acts_act nRA Aa) Ry in Rx. Qed. Canonical action_by := Action actby_is_action. Local Notation "<[nRA]>" := action_by : action_scope. Lemma actbyE x a : x \in R -> a \in A -> <[nRA]>%act x a = to x a. Proof. by rewrite /= /actby => -> ->. Qed. Lemma afix_actby B : 'Fix_<[nRA]>(B) = ~: R :|: 'Fix_to(A :&: B). Proof. apply/setP=> x; rewrite !inE /= /actby. case: (x \in R); last by apply/subsetP=> a _ /[!inE]. apply/subsetP/subsetP=> [cBx a | cABx a Ba] /[!inE]. by case/andP=> Aa /cBx; rewrite inE Aa. by case: ifP => //= Aa; have:= cABx a; rewrite !inE Aa => ->. Qed. Lemma astab_actby S : 'C(S | <[nRA]>) = 'C_A(R :&: S | to). Proof. apply/setP=> a; rewrite setIA (setIidPl (acts_dom nRA)) !inE. case Aa: (a \in A) => //=; apply/subsetP/subsetP=> cRSa x => [|Sx]. by case/setIP=> Rx /cRSa; rewrite !inE actbyE. by have:= cRSa x; rewrite !inE /= /actby Aa Sx; case: (x \in R) => //; apply. Qed. Lemma astabs_actby S : 'N(S | <[nRA]>) = 'N_A(R :&: S | to). Proof. apply/setP=> a; rewrite setIA (setIidPl (acts_dom nRA)) !inE. case Aa: (a \in A) => //=; apply/subsetP/subsetP=> nRSa x => [|Sx]. by case/setIP=> Rx /nRSa; rewrite !inE actbyE ?(acts_act nRA) ?Rx. have:= nRSa x; rewrite !inE /= /actby Aa Sx ?(acts_act nRA) //. by case: (x \in R) => //; apply. Qed. Lemma acts_actby (B : {set aT}) S : [acts B, on S | <[nRA]>] = (B \subset A) && [acts B, on R :&: S | to]. Proof. by rewrite astabs_actby subsetI. Qed. End ActBy. Notation "<[ nRA ] >" := (action_by nRA) : action_scope. Section SubAction. Variables (aT : finGroupType) (D : {group aT}). Variables (rT : finType) (sP : pred rT) (sT : subFinType sP) (to : action D rT). Implicit Type A : {set aT}. Implicit Type u : sT. Implicit Type S : {set sT}. Definition subact_dom := 'N([set x | sP x] | to). Canonical subact_dom_group := [group of subact_dom]. Implicit Type Na : {a | a \in subact_dom}. Lemma sub_act_proof u Na : sP (to (val u) (val Na)). Proof. by case: Na => a /= /(astabs_act (val u)); rewrite !inE valP. Qed. Definition subact u a := if insub a is Some Na then Sub _ (sub_act_proof u Na) else u. Lemma val_subact u a : val (subact u a) = if a \in subact_dom then to (val u) a else val u. Proof. by rewrite /subact -if_neg; case: insubP => [Na|] -> //=; rewrite SubK => ->. Qed. Lemma subact_is_action : is_action subact_dom subact. Proof. split=> [a u v eq_uv | u a b Na Nb]; apply: val_inj. move/(congr1 val): eq_uv; rewrite !val_subact. by case: (a \in _); first move/act_inj. have Da := astabs_dom Na; have Db := astabs_dom Nb. by rewrite !val_subact Na Nb groupM ?actMin. Qed. Canonical subaction := Action subact_is_action. Lemma astab_subact S : 'C(S | subaction) = subact_dom :&: 'C(val @: S | to). Proof. apply/setP=> a; rewrite inE in_setI; apply: andb_id2l => sDa. have [Da _] := setIP sDa; rewrite !inE Da. apply/subsetP/subsetP=> [cSa _ /imsetP[x Sx ->] | cSa x Sx] /[!inE]. by have:= cSa x Sx; rewrite inE -val_eqE val_subact sDa. by have:= cSa _ (imset_f val Sx); rewrite inE -val_eqE val_subact sDa. Qed. Lemma astabs_subact S : 'N(S | subaction) = subact_dom :&: 'N(val @: S | to). Proof. apply/setP=> a; rewrite inE in_setI; apply: andb_id2l => sDa. have [Da _] := setIP sDa; rewrite !inE Da. apply/subsetP/subsetP=> [nSa _ /imsetP[x Sx ->] | nSa x Sx] /[!inE]. by have /[1!inE]/(imset_f val) := nSa x Sx; rewrite val_subact sDa. have /[1!inE]/imsetP[y Sy def_y] := nSa _ (imset_f val Sx). by rewrite ((_ a =P y) _) // -val_eqE val_subact sDa def_y. Qed. Lemma afix_subact A : A \subset subact_dom -> 'Fix_subaction(A) = val @^-1: 'Fix_to(A). Proof. move/subsetP=> sAD; apply/setP=> u. rewrite !inE !(sameP setIidPl eqP); congr (_ == A). apply/setP=> a /[!inE]; apply: andb_id2l => Aa. by rewrite -val_eqE val_subact sAD. Qed. End SubAction. Notation "to ^?" := (subaction _ to) (format "to ^?") : action_scope. Section QuotientAction. Variables (aT : finGroupType) (D : {group aT}) (rT : finGroupType). Variables (to : action D rT) (H : {group rT}). Definition qact_dom := 'N(rcosets H 'N(H) | to^*). Canonical qact_dom_group := [group of qact_dom]. Local Notation subdom := (subact_dom (coset_range H) to^*). Fact qact_subdomE : subdom = qact_dom. Proof. by congr 'N(_|_); apply/setP=> Hx; rewrite !inE genGid. Qed. Lemma qact_proof : qact_dom \subset subdom. Proof. by rewrite qact_subdomE. Qed. Definition qact : coset_of H -> aT -> coset_of H := act (to^*^? \ qact_proof). Canonical quotient_action := [action of qact]. Lemma acts_qact_dom : [acts qact_dom, on 'N(H) | to]. Proof. apply/subsetP=> a nNa; rewrite !inE (astabs_dom nNa); apply/subsetP=> x Nx. have: H :* x \in rcosets H 'N(H) by rewrite -rcosetE imset_f. rewrite inE -(astabs_act _ nNa) => /rcosetsP[y Ny defHy]. have: to x a \in H :* y by rewrite -defHy (imset_f (to^~a)) ?rcoset_refl. by apply: subsetP; rewrite mul_subG ?sub1set ?normG. Qed. Lemma qactEcond x a : x \in 'N(H) -> quotient_action (coset H x) a = coset H (if a \in qact_dom then to x a else x). Proof. move=> Nx; apply: val_inj; rewrite val_subact //= qact_subdomE. have: H :* x \in rcosets H 'N(H) by rewrite -rcosetE imset_f. case nNa: (a \in _); rewrite // -(astabs_act _ nNa). rewrite !val_coset ?(acts_act acts_qact_dom nNa) //=. case/rcosetsP=> y Ny defHy; rewrite defHy; apply: rcoset_eqP. by rewrite rcoset_sym -defHy (imset_f (_^~_)) ?rcoset_refl. Qed. Lemma qactE x a : x \in 'N(H) -> a \in qact_dom -> quotient_action (coset H x) a = coset H (to x a). Proof. by move=> Nx nNa; rewrite qactEcond ?nNa. Qed. Lemma acts_quotient (A : {set aT}) (B : {set rT}) : A \subset 'N_qact_dom(B | to) -> [acts A, on B / H | quotient_action]. Proof. move=> nBA; apply: subset_trans {A}nBA _; apply/subsetP=> a /setIP[dHa nBa]. rewrite inE dHa inE; apply/subsetP=> _ /morphimP[x nHx Bx ->]. rewrite inE /= qactE //. by rewrite mem_morphim ?(acts_act acts_qact_dom) ?(astabs_act _ nBa). Qed. Lemma astabs_quotient (G : {group rT}) : H <| G -> 'N(G / H | quotient_action) = 'N_qact_dom(G | to). Proof. move=> nsHG; have [_ nHG] := andP nsHG. apply/eqP; rewrite eqEsubset acts_quotient // andbT. apply/subsetP=> a nGa; have dHa := astabs_dom nGa; have [Da _]:= setIdP dHa. rewrite inE dHa 2!inE Da; apply/subsetP=> x Gx; have nHx := subsetP nHG x Gx. rewrite -(quotientGK nsHG) 2!inE (acts_act acts_qact_dom) ?nHx //= inE. by rewrite -qactE // (astabs_act _ nGa) mem_morphim. Qed. End QuotientAction. Notation "to / H" := (quotient_action to H) : action_scope. Section ModAction. Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Implicit Types (G : {group aT}) (S : {set rT}). Section GenericMod. Variable H : {group aT}. Local Notation dom := 'N_D(H). Local Notation range := 'Fix_to(D :&: H). Let acts_dom : {acts dom, on range | to} := acts_act (acts_subnorm_fix to H). Definition modact x (Ha : coset_of H) := if x \in range then to x (repr (D :&: Ha)) else x. Lemma modactEcond x a : a \in dom -> modact x (coset H a) = (if x \in range then to x a else x). Proof. case/setIP=> Da Na; case: ifP => Cx; rewrite /modact Cx //. rewrite val_coset // -group_modr ?sub1set //. case: (repr _) / (repr_rcosetP (D :&: H) a) => a' Ha'. by rewrite actMin ?(afixP Cx _ Ha') //; case/setIP: Ha'. Qed. Lemma modactE x a : a \in D -> a \in 'N(H) -> x \in range -> modact x (coset H a) = to x a. Proof. by move=> Da Na Rx; rewrite modactEcond ?Rx // inE Da. Qed. Lemma modact_is_action : is_action (D / H) modact. Proof. split=> [Ha x y | x Ha Hb]; last first. case/morphimP=> a Na Da ->{Ha}; case/morphimP=> b Nb Db ->{Hb}. rewrite -morphM //= !modactEcond // ?groupM ?(introT setIP _) //. by case: ifP => Cx; rewrite ?(acts_dom, Cx, actMin, introT setIP _). case: (set_0Vmem (D :&: Ha)) => [Da0 | [a /setIP[Da NHa]]]. by rewrite /modact Da0 repr_set0 !act1 !if_same. have Na := subsetP (coset_norm _) _ NHa. have NDa: a \in 'N_D(H) by rewrite inE Da. rewrite -(coset_mem NHa) !modactEcond //. do 2![case: ifP]=> Cy Cx // eqxy; first exact: act_inj eqxy. by rewrite -eqxy acts_dom ?Cx in Cy. by rewrite eqxy acts_dom ?Cy in Cx. Qed. Canonical mod_action := Action modact_is_action. Section Stabilizers. Variable S : {set rT}. Hypothesis cSH : H \subset 'C(S | to). Let fixSH : S \subset 'Fix_to(D :&: H). Proof. by rewrite -astabCin ?subsetIl // subIset ?cSH ?orbT. Qed. Lemma astabs_mod : 'N(S | mod_action) = 'N(S | to) / H. Proof. apply/setP=> Ha; apply/idP/morphimP=> [nSa | [a nHa nSa ->]]. case/morphimP: (astabs_dom nSa) => a nHa Da defHa. exists a => //; rewrite !inE Da; apply/subsetP=> x Sx; rewrite !inE. by have:= Sx; rewrite -(astabs_act x nSa) defHa /= modactE ?(subsetP fixSH). have Da := astabs_dom nSa; rewrite !inE mem_quotient //; apply/subsetP=> x Sx. by rewrite !inE /= modactE ?(astabs_act x nSa) ?(subsetP fixSH). Qed. Lemma astab_mod : 'C(S | mod_action) = 'C(S | to) / H. Proof. apply/setP=> Ha; apply/idP/morphimP=> [cSa | [a nHa cSa ->]]. case/morphimP: (astab_dom cSa) => a nHa Da defHa. exists a => //; rewrite !inE Da; apply/subsetP=> x Sx; rewrite !inE. by rewrite -{2}[x](astab_act cSa) // defHa /= modactE ?(subsetP fixSH). have Da := astab_dom cSa; rewrite !inE mem_quotient //; apply/subsetP=> x Sx. by rewrite !inE /= modactE ?(astab_act cSa) ?(subsetP fixSH). Qed. End Stabilizers. Lemma afix_mod G S : H \subset 'C(S | to) -> G \subset 'N_D(H) -> 'Fix_(S | mod_action)(G / H) = 'Fix_(S | to)(G). Proof. move=> cSH /subsetIP[sGD nHG]. apply/eqP; rewrite eqEsubset !subsetI !subsetIl /= -!astabCin ?quotientS //. have cfixH F: H \subset 'C(S :&: F | to). by rewrite (subset_trans cSH) // astabS ?subsetIl. rewrite andbC astab_mod ?quotientS //=; last by rewrite astabCin ?subsetIr. by rewrite -(quotientSGK nHG) //= -astab_mod // astabCin ?quotientS ?subsetIr. Qed. End GenericMod. Lemma modact_faithful G S : [faithful G / 'C_G(S | to), on S | mod_action 'C_G(S | to)]. Proof. rewrite /faithful astab_mod ?subsetIr //=. by rewrite -quotientIG ?subsetIr ?trivg_quotient. Qed. End ModAction. Notation "to %% H" := (mod_action to H) : action_scope. Section ActPerm. (* Morphism to permutations induced by an action. *) Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Variable to : action D rT. Definition actperm a := perm (act_inj to a). Lemma actpermM : {in D &, {morph actperm : a b / a * b}}. Proof. by move=> a b Da Db; apply/permP=> x; rewrite permM !permE actMin. Qed. Canonical actperm_morphism := Morphism actpermM. Lemma actpermE a x : actperm a x = to x a. Proof. by rewrite permE. Qed. Lemma actpermK x a : aperm x (actperm a) = to x a. Proof. exact: actpermE. Qed. Lemma ker_actperm : 'ker actperm = 'C(setT | to). Proof. congr (_ :&: _); apply/setP=> a /[!inE]/=. apply/eqP/subsetP=> [a1 x _ | a1]; first by rewrite inE -actpermE a1 perm1. by apply/permP=> x; apply/eqP; have:= a1 x; rewrite !inE actpermE perm1 => ->. Qed. End ActPerm. Section RestrictActionTheory. Variables (aT : finGroupType) (D : {set aT}) (rT : finType). Variables (to : action D rT). Lemma faithful_isom (A : {group aT}) S (nSA : actby_cond A S to) : [faithful A, on S | to] -> isom A (actperm <[nSA]> @* A) (actperm <[nSA]>). Proof. by move=> ffulAS; apply/isomP; rewrite ker_actperm astab_actby setIT. Qed. Variables (A : {set aT}) (sAD : A \subset D). Lemma ractpermE : actperm (to \ sAD) =1 actperm to. Proof. by move=> a; apply/permP=> x; rewrite !permE. Qed. Lemma afix_ract B : 'Fix_(to \ sAD)(B) = 'Fix_to(B). Proof. by []. Qed. Lemma astab_ract S : 'C(S | to \ sAD) = 'C_A(S | to). Proof. by rewrite setIA (setIidPl sAD). Qed. Lemma astabs_ract S : 'N(S | to \ sAD) = 'N_A(S | to). Proof. by rewrite setIA (setIidPl sAD). Qed. Lemma acts_ract (B : {set aT}) S : [acts B, on S | to \ sAD] = (B \subset A) && [acts B, on S | to]. Proof. by rewrite astabs_ract subsetI. Qed. End RestrictActionTheory. Section MorphAct. (* Action induced by a morphism to permutations. *) Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable phi : {morphism D >-> {perm rT}}. Definition mact x a := phi a x. Lemma mact_is_action : is_action D mact. Proof. split=> [a x y | x a b Da Db]; first exact: perm_inj. by rewrite /mact morphM //= permM. Qed. Canonical morph_action := Action mact_is_action. Lemma mactE x a : morph_action x a = phi a x. Proof. by []. Qed. Lemma injm_faithful : 'injm phi -> [faithful D, on setT | morph_action]. Proof. move/injmP=> phi_inj; apply/subsetP=> a /setIP[Da /astab_act a1]. apply/set1P/phi_inj => //; apply/permP=> x. by rewrite morph1 perm1 -mactE a1 ?inE. Qed. Lemma perm_mact a : actperm morph_action a = phi a. Proof. by apply/permP=> x; rewrite permE. Qed. End MorphAct. Notation "<< phi >>" := (morph_action phi) : action_scope. Section CompAct. Variables (gT aT : finGroupType) (rT : finType). Variables (D : {set aT}) (to : action D rT). Variables (B : {set gT}) (f : {morphism B >-> aT}). Definition comp_act x e := to x (f e). Lemma comp_is_action : is_action (f @*^-1 D) comp_act. Proof. split=> [e | x e1 e2]; first exact: act_inj. move=> /morphpreP[Be1 Dfe1] /morphpreP[Be2 Dfe2]. by rewrite /comp_act morphM ?actMin. Qed. Canonical comp_action := Action comp_is_action. Lemma comp_actE x e : comp_action x e = to x (f e). Proof. by []. Qed. Lemma afix_comp (A : {set gT}) : A \subset B -> 'Fix_comp_action(A) = 'Fix_to(f @* A). Proof. move=> sAB; apply/setP=> x; rewrite !inE /morphim (setIidPr sAB). apply/subsetP/subsetP; first by move=> + _ /imsetP[a + ->] => /[apply]/[!inE]. by move=> + a Aa => /(_ (f a)); rewrite !inE imset_f// => ->. Qed. Lemma astab_comp S : 'C(S | comp_action) = f @*^-1 'C(S | to). Proof. by apply/setP=> x; rewrite !inE -andbA. Qed. Lemma astabs_comp S : 'N(S | comp_action) = f @*^-1 'N(S | to). Proof. by apply/setP=> x; rewrite !inE -andbA. Qed. End CompAct. Notation "to \o f" := (comp_action to f) : action_scope. Section PermAction. (* Natural action of permutation groups. *) Variable rT : finType. Local Notation gT := {perm rT}. Implicit Types a b c : gT. Lemma aperm_is_action : is_action setT (@aperm rT). Proof. by apply: is_total_action => [x|x a b]; rewrite apermE (perm1, permM). Qed. Canonical perm_action := Action aperm_is_action. Lemma porbitE a : porbit a = orbit perm_action <[a]>%g. Proof. by rewrite unlock. Qed. Lemma perm_act1P a : reflect (forall x, aperm x a = x) (a == 1). Proof. apply: (iffP eqP) => [-> x | a1]; first exact: act1. by apply/permP=> x; rewrite -apermE a1 perm1. Qed. Lemma perm_faithful A : [faithful A, on setT | perm_action]. Proof. apply/subsetP=> a /setIP[Da crTa]. by apply/set1P; apply/permP=> x; rewrite -apermE perm1 (astabP crTa) ?inE. Qed. Lemma actperm_id p : actperm perm_action p = p. Proof. by apply/permP=> x; rewrite permE. Qed. End PermAction. Arguments perm_act1P {rT a}. Notation "'P" := (perm_action _) : action_scope. Section ActpermOrbits. Variables (aT : finGroupType) (D : {group aT}) (rT : finType). Variable to : action D rT. Lemma orbit_morphim_actperm (A : {set aT}) : A \subset D -> orbit 'P (actperm to @* A) =1 orbit to A. Proof. move=> sAD x; rewrite morphimEsub // /orbit -imset_comp. by apply: eq_imset => a //=; rewrite actpermK. Qed. Lemma porbit_actperm (a : aT) : a \in D -> porbit (actperm to a) =1 orbit to <[a]>. Proof. move=> Da x. by rewrite porbitE -orbit_morphim_actperm ?cycle_subG ?morphim_cycle. Qed. End ActpermOrbits. Section RestrictPerm. Variables (T : finType) (S : {set T}). Definition restr_perm := actperm (<[subxx 'N(S | 'P)]>). Canonical restr_perm_morphism := [morphism of restr_perm]. Lemma restr_perm_on p : perm_on S (restr_perm p). Proof. apply/subsetP=> x; apply: contraR => notSx. by rewrite permE /= /actby (negPf notSx). Qed. Lemma triv_restr_perm p : p \notin 'N(S | 'P) -> restr_perm p = 1. Proof. move=> not_nSp; apply/permP=> x. by rewrite !permE /= /actby (negPf not_nSp) andbF. Qed. Lemma restr_permE : {in 'N(S | 'P) & S, forall p, restr_perm p =1 p}. Proof. by move=> y x nSp Sx; rewrite /= actpermE actbyE. Qed. Lemma ker_restr_perm : 'ker restr_perm = 'C(S | 'P). Proof. by rewrite ker_actperm astab_actby setIT (setIidPr (astab_sub _ _)). Qed. Lemma im_restr_perm p : restr_perm p @: S = S. Proof. exact: im_perm_on (restr_perm_on p). Qed. Lemma restr_perm_commute s : commute (restr_perm s) s. Proof. have [sC|/triv_restr_perm->] := boolP (s \in 'N(S | 'P)); last first. exact: (commute_sym (commute1 _)). apply/permP => x; have /= xsS := astabsP sC x; rewrite !permM. have [xS|xNS] := boolP (x \in S); first by rewrite ?(restr_permE) ?xsS. by rewrite !(out_perm (restr_perm_on _)) ?xsS. Qed. End RestrictPerm. Section Symmetry. Variables (T : finType) (S : {set T}). Lemma SymE : Sym S = 'C(~: S | 'P). Proof. apply/setP => s; rewrite inE; apply/idP/astabP => [sS x|/= S_id]. by rewrite inE /= apermE => /out_perm->. by apply/subsetP => x; move=> /(contra_neqN (S_id _)); rewrite inE negbK. Qed. End Symmetry. Section AutIn. Variable gT : finGroupType. Definition Aut_in A (B : {set gT}) := 'N_A(B | 'P) / 'C_A(B | 'P). Variables G H : {group gT}. Hypothesis sHG: H \subset G. Lemma Aut_restr_perm a : a \in Aut G -> restr_perm H a \in Aut H. Proof. move=> AutGa. case nHa: (a \in 'N(H | 'P)); last by rewrite triv_restr_perm ?nHa ?group1. rewrite inE restr_perm_on; apply/morphicP=> x y Hx Hy /=. by rewrite !restr_permE ?groupM // -(autmE AutGa) morphM ?(subsetP sHG). Qed. Lemma restr_perm_Aut : restr_perm H @* Aut G \subset Aut H. Proof. by apply/subsetP=> a'; case/morphimP=> a _ AutGa ->{a'}; apply: Aut_restr_perm. Qed. Lemma Aut_in_isog : Aut_in (Aut G) H \isog restr_perm H @* Aut G. Proof. rewrite /Aut_in -ker_restr_perm kerE -morphpreIdom -morphimIdom -kerE /=. by rewrite setIA (setIC _ (Aut G)) first_isog_loc ?subsetIr. Qed. Lemma Aut_sub_fullP : reflect (forall h : {morphism H >-> gT}, 'injm h -> h @* H = H -> exists g : {morphism G >-> gT}, [/\ 'injm g, g @* G = G & {in H, g =1 h}]) (Aut_in (Aut G) H \isog Aut H). Proof. rewrite (isog_transl _ Aut_in_isog) /=; set rG := _ @* _. apply: (iffP idP) => [iso_rG h injh hH| AutHinG]. have: aut injh hH \in rG; last case/morphimP=> g nHg AutGg def_g. suffices ->: rG = Aut H by apply: Aut_aut. by apply/eqP; rewrite eqEcard restr_perm_Aut /= (card_isog iso_rG). exists (autm_morphism AutGg); rewrite injm_autm im_autm; split=> // x Hx. by rewrite -(autE injh hH Hx) def_g actpermE actbyE. suffices ->: rG = Aut H by apply: isog_refl. apply/eqP; rewrite eqEsubset restr_perm_Aut /=. apply/subsetP=> h AutHh; have hH := im_autm AutHh. have [g [injg gG eq_gh]] := AutHinG _ (injm_autm AutHh) hH. have [Ng AutGg]: aut injg gG \in 'N(H | 'P) /\ aut injg gG \in Aut G. rewrite Aut_aut !inE; split=> //; apply/subsetP=> x Hx. by rewrite inE /= /aperm autE ?(subsetP sHG) // -hH eq_gh ?mem_morphim. apply/morphimP; exists (aut injg gG) => //; apply: (eq_Aut AutHh) => [|x Hx]. by rewrite (subsetP restr_perm_Aut) // mem_morphim. by rewrite restr_permE //= /aperm autE ?eq_gh ?(subsetP sHG). Qed. End AutIn. Arguments Aut_in {gT} A%_g B%_g. Section InjmAutIn. Variables (gT rT : finGroupType) (D G H : {group gT}) (f : {morphism D >-> rT}). Hypotheses (injf : 'injm f) (sGD : G \subset D) (sHG : H \subset G). Let sHD := subset_trans sHG sGD. Local Notation fGisom := (Aut_isom injf sGD). Local Notation fHisom := (Aut_isom injf sHD). Local Notation inH := (restr_perm H). Local Notation infH := (restr_perm (f @* H)). Lemma astabs_Aut_isom a : a \in Aut G -> (fGisom a \in 'N(f @* H | 'P)) = (a \in 'N(H | 'P)). Proof. move=> AutGa; rewrite !inE sub_morphim_pre // subsetI sHD /= /aperm. rewrite !(sameP setIidPl eqP) !eqEsubset !subsetIl; apply: eq_subset_r => x. rewrite !inE; apply: andb_id2l => Hx; have Gx: x \in G := subsetP sHG x Hx. have Dax: a x \in D by rewrite (subsetP sGD) // Aut_closed. by rewrite Aut_isomE // -!sub1set -morphim_set1 // injmSK ?sub1set. Qed. Lemma isom_restr_perm a : a \in Aut G -> fHisom (inH a) = infH (fGisom a). Proof. move=> AutGa; case nHa: (a \in 'N(H | 'P)); last first. by rewrite !triv_restr_perm ?astabs_Aut_isom ?nHa ?morph1. apply: (eq_Aut (Aut_Aut_isom injf sHD _)) => [|fx Hfx /=]. by rewrite (Aut_restr_perm (morphimS f sHG)) ?Aut_Aut_isom. have [x Dx Hx def_fx] := morphimP Hfx; have Gx := subsetP sHG x Hx. rewrite {1}def_fx Aut_isomE ?(Aut_restr_perm sHG) //. by rewrite !restr_permE ?astabs_Aut_isom // def_fx Aut_isomE. Qed. Lemma restr_perm_isom : isom (inH @* Aut G) (infH @* Aut (f @* G)) fHisom. Proof. apply: sub_isom; rewrite ?restr_perm_Aut ?injm_Aut_isom //=. rewrite -(im_Aut_isom injf sGD) -!morphim_comp. apply: eq_in_morphim; last exact: isom_restr_perm. (* TODO: investigate why rewrite does not match in the same order *) apply/setP=> a; rewrite in_setI [in RHS]in_setI; apply: andb_id2r => AutGa. (* the middle rewrite was rewrite 2!in_setI *) rewrite /= inE andbC inE (Aut_restr_perm sHG) //=. by symmetry; rewrite inE AutGa inE astabs_Aut_isom. Qed. Lemma injm_Aut_sub : Aut_in (Aut (f @* G)) (f @* H) \isog Aut_in (Aut G) H. Proof. do 2!rewrite isog_sym (isog_transl _ (Aut_in_isog _ _)). by rewrite isog_sym (isom_isog _ _ restr_perm_isom) // restr_perm_Aut. Qed. Lemma injm_Aut_full : (Aut_in (Aut (f @* G)) (f @* H) \isog Aut (f @* H)) = (Aut_in (Aut G) H \isog Aut H). Proof. by rewrite (isog_transl _ injm_Aut_sub) (isog_transr _ (injm_Aut injf sHD)). Qed. End InjmAutIn. Section GroupAction. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Local Notation actT := (action D rT). Definition is_groupAction (to : actT) := {in D, forall a, actperm to a \in Aut R}. Structure groupAction := GroupAction {gact :> actT; _ : is_groupAction gact}. Definition clone_groupAction to := let: GroupAction _ toA := to return {type of GroupAction for to} -> _ in fun k => k toA : groupAction. End GroupAction. Delimit Scope groupAction_scope with gact. Bind Scope groupAction_scope with groupAction. Arguments is_groupAction {aT rT D%_g} R%_g to%_act. Arguments groupAction {aT rT} D%_g R%_g. Arguments gact {aT rT D%_g R%_g} to%_gact : rename. Notation "[ 'groupAction' 'of' to ]" := (clone_groupAction (@GroupAction _ _ _ _ to)) (format "[ 'groupAction' 'of' to ]") : form_scope. Section GroupActionDefs. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Implicit Type A : {set aT}. Implicit Type S : {set rT}. Implicit Type to : groupAction D R. Definition gact_range of groupAction D R := R. Definition gacent to A := 'Fix_(R | to)(D :&: A). Definition acts_on_group A S to := [acts A, on S | to] /\ S \subset R. Coercion actby_cond_group A S to : acts_on_group A S to -> actby_cond A S to := @proj1 _ _. Definition acts_irreducibly A S to := [min S of G | G :!=: 1 & [acts A, on G | to]]. End GroupActionDefs. Arguments gacent {aT rT D%_g R%_g} to%_gact A%_g. Arguments acts_on_group {aT rT D%_g R%_g} A%_g S%_g to%_gact. Arguments acts_irreducibly {aT rT D%_g R%_g} A%_g S%_g to%_gact. Notation "''C_' ( | to ) ( A )" := (gacent to A) : group_scope. Notation "''C_' ( G | to ) ( A )" := (G :&: 'C_(|to)(A)) : group_scope. Notation "''C_' ( | to ) [ a ]" := 'C_(|to)([set a]) : group_scope. Notation "''C_' ( G | to ) [ a ]" := 'C_(G | to)([set a]) : group_scope. Notation "{ 'acts' A , 'on' 'group' G | to }" := (acts_on_group A G to) (format "{ 'acts' A , 'on' 'group' G | to }") : type_scope. Section RawGroupAction. Variables (aT rT : finGroupType) (D : {set aT}) (R : {set rT}). Variable to : groupAction D R. Lemma actperm_Aut : is_groupAction R to. Proof. by case: to. Qed. Lemma im_actperm_Aut : actperm to @* D \subset Aut R. Proof. by apply/subsetP=> _ /morphimP[a _ Da ->]; apply: actperm_Aut. Qed. Lemma gact_out x a : a \in D -> x \notin R -> to x a = x. Proof. by move=> Da Rx; rewrite -actpermE (out_Aut _ Rx) ?actperm_Aut. Qed. Lemma gactM : {in D, forall a, {in R &, {morph to^~ a : x y / x * y}}}. Proof. move=> a Da /= x y; rewrite -!(actpermE to); apply: morphicP x y. by rewrite Aut_morphic ?actperm_Aut. Qed. Lemma actmM a : {in R &, {morph actm to a : x y / x * y}}. Proof. by rewrite /actm; case: ifP => //; apply: gactM. Qed. Canonical act_morphism a := Morphism (actmM a). Lemma morphim_actm : {in D, forall a (S : {set rT}), S \subset R -> actm to a @* S = to^* S a}. Proof. by move=> a Da /= S sSR; rewrite /morphim /= actmEfun ?(setIidPr _). Qed. Variables (a : aT) (A B : {set aT}) (S : {set rT}). Lemma gacentIdom : 'C_(|to)(D :&: A) = 'C_(|to)(A). Proof. by rewrite /gacent setIA setIid. Qed. Lemma gacentIim : 'C_(R | to)(A) = 'C_(|to)(A). Proof. by rewrite setIA setIid. Qed. Lemma gacentS : A \subset B -> 'C_(|to)(B) \subset 'C_(|to)(A). Proof. by move=> sAB; rewrite !(setIS, afixS). Qed. Lemma gacentU : 'C_(|to)(A :|: B) = 'C_(|to)(A) :&: 'C_(|to)(B). Proof. by rewrite -setIIr -afixU -setIUr. Qed. Hypotheses (Da : a \in D) (sAD : A \subset D) (sSR : S \subset R). Lemma gacentE : 'C_(|to)(A) = 'Fix_(R | to)(A). Proof. by rewrite -{2}(setIidPr sAD). Qed. Lemma gacent1E : 'C_(|to)[a] = 'Fix_(R | to)[a]. Proof. by rewrite /gacent [D :&: _](setIidPr _) ?sub1set. Qed. Lemma subgacentE : 'C_(S | to)(A) = 'Fix_(S | to)(A). Proof. by rewrite gacentE setIA (setIidPl sSR). Qed. Lemma subgacent1E : 'C_(S | to)[a] = 'Fix_(S | to)[a]. Proof. by rewrite gacent1E setIA (setIidPl sSR). Qed. End RawGroupAction. Section GroupActionTheory. Variables aT rT : finGroupType. Variables (D : {group aT}) (R : {group rT}) (to : groupAction D R). Implicit Type A B : {set aT}. Implicit Types G H : {group aT}. Implicit Type S : {set rT}. Implicit Types M N : {group rT}. Lemma gact1 : {in D, forall a, to 1 a = 1}. Proof. by move=> a Da; rewrite /= -actmE ?morph1. Qed. Lemma gactV : {in D, forall a, {in R, {morph to^~ a : x / x^-1}}}. Proof. by move=> a Da /= x Rx; move; rewrite -!actmE ?morphV. Qed. Lemma gactX : {in D, forall a n, {in R, {morph to^~ a : x / x ^+ n}}}. Proof. by move=> a Da /= n x Rx; rewrite -!actmE // morphX. Qed. Lemma gactJ : {in D, forall a, {in R &, {morph to^~ a : x y / x ^ y}}}. Proof. by move=> a Da /= x Rx y Ry; rewrite -!actmE // morphJ. Qed. Lemma gactR : {in D, forall a, {in R &, {morph to^~ a : x y / [~ x, y]}}}. Proof. by move=> a Da /= x Rx y Ry; rewrite -!actmE // morphR. Qed. Lemma gact_stable : {acts D, on R | to}. Proof. apply: acts_act; apply/subsetP=> a Da; rewrite !inE Da. apply/subsetP=> x; rewrite inE; apply: contraLR => R'xa. by rewrite -(actKin to Da x) gact_out ?groupV. Qed. Lemma group_set_gacent A : group_set 'C_(|to)(A). Proof. apply/group_setP; split=> [|x y]. by rewrite !inE group1; apply/subsetP=> a /setIP[Da _]; rewrite inE gact1. case/setIP=> Rx /afixP cAx /setIP[Ry /afixP cAy]. rewrite inE groupM //; apply/afixP=> a Aa. by rewrite gactM ?cAx ?cAy //; case/setIP: Aa. Qed. Canonical gacent_group A := Group (group_set_gacent A). Lemma gacent1 : 'C_(|to)(1) = R. Proof. by rewrite /gacent (setIidPr (sub1G _)) afix1 setIT. Qed. Lemma gacent_gen A : A \subset D -> 'C_(|to)(<<A>>) = 'C_(|to)(A). Proof. by move=> sAD; rewrite /gacent ![D :&: _](setIidPr _) ?gen_subG ?afix_gen_in. Qed. Lemma gacentD1 A : 'C_(|to)(A^#) = 'C_(|to)(A). Proof. rewrite -gacentIdom -gacent_gen ?subsetIl // setIDA genD1 ?group1 //. by rewrite gacent_gen ?subsetIl // gacentIdom. Qed. Lemma gacent_cycle a : a \in D -> 'C_(|to)(<[a]>) = 'C_(|to)[a]. Proof. by move=> Da; rewrite gacent_gen ?sub1set. Qed. Lemma gacentY A B : A \subset D -> B \subset D -> 'C_(|to)(A <*> B) = 'C_(|to)(A) :&: 'C_(|to)(B). Proof. by move=> sAD sBD; rewrite gacent_gen ?gacentU // subUset sAD. Qed. Lemma gacentM G H : G \subset D -> H \subset D -> 'C_(|to)(G * H) = 'C_(|to)(G) :&: 'C_(|to)(H). Proof. by move=> sGD sHB; rewrite -gacent_gen ?mul_subG // genM_join gacentY. Qed. Lemma astab1 : 'C(1 | to) = D. Proof. by apply/setP=> x; rewrite ?(inE, sub1set) andb_idr //; move/gact1=> ->. Qed. Lemma astab_range : 'C(R | to) = 'C(setT | to). Proof. apply/eqP; rewrite eqEsubset andbC astabS ?subsetT //=. apply/subsetP=> a cRa; have Da := astab_dom cRa; rewrite !inE Da. apply/subsetP=> x; rewrite -(setUCr R) !inE. by case/orP=> ?; [rewrite (astab_act cRa) | rewrite gact_out]. Qed. Lemma gacentC A S : A \subset D -> S \subset R -> (S \subset 'C_(|to)(A)) = (A \subset 'C(S | to)). Proof. by move=> sAD sSR; rewrite subsetI sSR astabCin // (setIidPr sAD). Qed. Lemma astab_gen S : S \subset R -> 'C(<<S>> | to) = 'C(S | to). Proof. move=> sSR; apply/setP=> a; case Da: (a \in D); last by rewrite !inE Da. by rewrite -!sub1set -!gacentC ?sub1set ?gen_subG. Qed. Lemma astabM M N : M \subset R -> N \subset R -> 'C(M * N | to) = 'C(M | to) :&: 'C(N | to). Proof. move=> sMR sNR; rewrite -astabU -astab_gen ?mul_subG // genM_join. by rewrite astab_gen // subUset sMR. Qed. Lemma astabs1 : 'N(1 | to) = D. Proof. by rewrite astabs_set1 astab1. Qed. Lemma astabs_range : 'N(R | to) = D. Proof. apply/setIidPl; apply/subsetP=> a Da; rewrite inE. by apply/subsetP=> x Rx; rewrite inE gact_stable. Qed. Lemma astabsD1 S : 'N(S^# | to) = 'N(S | to). Proof. case S1: (1 \in S); last first. by rewrite (setDidPl _) // disjoint_sym disjoints_subset sub1set inE S1. apply/eqP; rewrite eqEsubset andbC -{1}astabsIdom -{1}astabs1 setIC astabsD /=. by rewrite -{2}(setD1K S1) -astabsIdom -{1}astabs1 astabsU. Qed. Lemma gacts_range A : A \subset D -> {acts A, on group R | to}. Proof. by move=> sAD; split; rewrite ?astabs_range. Qed. Lemma acts_subnorm_gacent A : A \subset D -> [acts 'N_D(A), on 'C_(| to)(A) | to]. Proof. move=> sAD; rewrite gacentE // actsI ?astabs_range ?subsetIl //. by rewrite -{2}(setIidPr sAD) acts_subnorm_fix. Qed. Lemma acts_subnorm_subgacent A B S : A \subset D -> [acts B, on S | to] -> [acts 'N_B(A), on 'C_(S | to)(A) | to]. Proof. move=> sAD actsB; rewrite actsI //; first by rewrite subIset ?actsB. by rewrite (subset_trans _ (acts_subnorm_gacent sAD)) ?setSI ?(acts_dom actsB). Qed. Lemma acts_gen A S : S \subset R -> [acts A, on S | to] -> [acts A, on <<S>> | to]. Proof. move=> sSR actsA; apply: {A}subset_trans actsA _. apply/subsetP=> a nSa; have Da := astabs_dom nSa; rewrite !inE Da. apply: subset_trans (_ : <<S>> \subset actm to a @*^-1 <<S>>) _. rewrite gen_subG subsetI sSR; apply/subsetP=> x Sx. by rewrite inE /= actmE ?mem_gen // astabs_act. by apply/subsetP=> x /[!inE]; case/andP=> Rx; rewrite /= actmE. Qed. Lemma acts_joing A M N : M \subset R -> N \subset R -> [acts A, on M | to] -> [acts A, on N | to] -> [acts A, on M <*> N | to]. Proof. by move=> sMR sNR nMA nNA; rewrite acts_gen ?actsU // subUset sMR. Qed. Lemma injm_actm a : 'injm (actm to a). Proof. apply/injmP=> x y Rx Ry; rewrite /= /actm; case: ifP => Da //. exact: act_inj. Qed. Lemma im_actm a : actm to a @* R = R. Proof. apply/eqP; rewrite eqEcard (card_injm (injm_actm a)) // leqnn andbT. apply/subsetP=> _ /morphimP[x Rx _ ->] /=. by rewrite /actm; case: ifP => // Da; rewrite gact_stable. Qed. Lemma acts_char G M : G \subset D -> M \char R -> [acts G, on M | to]. Proof. move=> sGD /charP[sMR charM]. apply/subsetP=> a Ga; have Da := subsetP sGD a Ga; rewrite !inE Da. apply/subsetP=> x Mx; have Rx := subsetP sMR x Mx. by rewrite inE -(charM _ (injm_actm a) (im_actm a)) -actmE // mem_morphim. Qed. Lemma gacts_char G M : G \subset D -> M \char R -> {acts G, on group M | to}. (* TODO: investigate why rewrite does not match in the same order *) Proof. by move=> sGD charM; split; rewrite ?acts_char// char_sub. Qed. (* was ending with rewrite (acts_char, char_sub)// *) Section Restrict. Variables (A : {group aT}) (sAD : A \subset D). Lemma ract_is_groupAction : is_groupAction R (to \ sAD). Proof. by move=> a Aa /=; rewrite ractpermE actperm_Aut ?(subsetP sAD). Qed. Canonical ract_groupAction := GroupAction ract_is_groupAction. Lemma gacent_ract B : 'C_(|ract_groupAction)(B) = 'C_(|to)(A :&: B). Proof. by rewrite /gacent afix_ract setIA (setIidPr sAD). Qed. End Restrict. Section ActBy. Variables (A : {group aT}) (G : {group rT}) (nGAg : {acts A, on group G | to}). Lemma actby_is_groupAction : is_groupAction G <[nGAg]>. Proof. move=> a Aa; rewrite /= inE; apply/andP; split. apply/subsetP=> x; apply: contraR => Gx. by rewrite actpermE /= /actby (negbTE Gx). apply/morphicP=> x y Gx Gy; rewrite !actpermE /= /actby Aa groupM ?Gx ?Gy //=. by case nGAg; move/acts_dom; do 2!move/subsetP=> ?; rewrite gactM; auto. Qed. Canonical actby_groupAction := GroupAction actby_is_groupAction. Lemma gacent_actby B : 'C_(|actby_groupAction)(B) = 'C_(G | to)(A :&: B). Proof. rewrite /gacent afix_actby !setIA setIid setIUr setICr set0U. by have [nAG sGR] := nGAg; rewrite (setIidPr (acts_dom nAG)) (setIidPl sGR). Qed. End ActBy. Section Quotient. Variable H : {group rT}. Lemma acts_qact_dom_norm : {acts qact_dom to H, on 'N(H) | to}. Proof. move=> a HDa /= x; rewrite {2}(('N(H) =P to^~ a @^-1: 'N(H)) _) ?inE {x}//. rewrite eqEcard (card_preimset _ (act_inj _ _)) leqnn andbT. apply/subsetP=> x Nx; rewrite inE; move/(astabs_act (H :* x)): HDa. rewrite mem_rcosets mulSGid ?normG // Nx => /rcosetsP[y Ny defHy]. suffices: to x a \in H :* y by apply: subsetP; rewrite mul_subG ?sub1set ?normG. by rewrite -defHy; apply: imset_f; apply: rcoset_refl. Qed. Lemma qact_is_groupAction : is_groupAction (R / H) (to / H). Proof. move=> a HDa /=; have Da := astabs_dom HDa. rewrite inE; apply/andP; split. apply/subsetP=> Hx /=; case: (cosetP Hx) => x Nx ->{Hx}. apply: contraR => R'Hx; rewrite actpermE qactE // gact_out //. by apply: contra R'Hx; apply: mem_morphim. apply/morphicP=> Hx Hy; rewrite !actpermE. case/morphimP=> x Nx Gx ->{Hx}; case/morphimP=> y Ny Gy ->{Hy}. by rewrite -morphM ?qactE ?groupM ?gactM // morphM ?acts_qact_dom_norm. Qed. Canonical quotient_groupAction := GroupAction qact_is_groupAction. Lemma qact_domE : H \subset R -> qact_dom to H = 'N(H | to). Proof. move=> sHR; apply/setP=> a; apply/idP/idP=> nHa; have Da := astabs_dom nHa. rewrite !inE Da; apply/subsetP=> x Hx; rewrite inE -(rcoset1 H). have /rcosetsP[y Ny defHy]: to^~ a @: H \in rcosets H 'N(H). by rewrite (astabs_act _ nHa); apply/rcosetsP; exists 1; rewrite ?mulg1. by rewrite (rcoset_eqP (_ : 1 \in H :* y)) -defHy -1?(gact1 Da) mem_setact. rewrite !inE Da; apply/subsetP=> Hx /[1!inE] /rcosetsP[x Nx ->{Hx}]. apply/imsetP; exists (to x a). case Rx: (x \in R); last by rewrite gact_out ?Rx. rewrite inE; apply/subsetP=> _ /imsetP[y Hy ->]. rewrite -(actKVin to Da y) -gactJ // ?(subsetP sHR, astabs_act, groupV) //. by rewrite memJ_norm // astabs_act ?groupV. apply/eqP; rewrite rcosetE eqEcard. rewrite (card_imset _ (act_inj _ _)) !card_rcoset leqnn andbT. apply/subsetP=> _ /imsetP[y Hxy ->]; rewrite !mem_rcoset in Hxy *. have Rxy := subsetP sHR _ Hxy; rewrite -(mulgKV x y). case Rx: (x \in R); last by rewrite !gact_out ?mulgK // 1?groupMl ?Rx. by rewrite -gactV // -gactM 1?groupMr ?groupV // mulgK astabs_act. Qed. End Quotient. Section Mod. Variable H : {group aT}. Lemma modact_is_groupAction : is_groupAction 'C_(|to)(H) (to %% H). Proof. move=> Ha /morphimP[a Na Da ->]; have NDa: a \in 'N_D(H) by apply/setIP. rewrite inE; apply/andP; split. apply/subsetP=> x; rewrite 2!inE andbC actpermE /= modactEcond //. by apply: contraR; case: ifP => // E Rx; rewrite gact_out. apply/morphicP=> x y /setIP[Rx cHx] /setIP[Ry cHy]. rewrite /= !actpermE /= !modactE ?gactM //. suffices: x * y \in 'C_(|to)(H) by case/setIP. by rewrite groupM //; apply/setIP. Qed. Canonical mod_groupAction := GroupAction modact_is_groupAction. Lemma modgactE x a : H \subset 'C(R | to) -> a \in 'N_D(H) -> (to %% H)%act x (coset H a) = to x a. Proof. move=> cRH NDa /=; have [Da Na] := setIP NDa. have [Rx | notRx] := boolP (x \in R). by rewrite modactE //; apply/afixP=> b /setIP[_ /(subsetP cRH)/astab_act->]. rewrite gact_out //= /modact; case: ifP => // _; rewrite gact_out //. suffices: a \in D :&: coset H a by case/mem_repr/setIP. by rewrite inE Da val_coset // rcoset_refl. Qed. Lemma gacent_mod G M : H \subset 'C(M | to) -> G \subset 'N(H) -> 'C_(M | mod_groupAction)(G / H) = 'C_(M | to)(G). Proof. move=> cMH nHG; rewrite -gacentIdom gacentE ?subsetIl // setICA. have sHD: H \subset D by rewrite (subset_trans cMH) ?subsetIl. rewrite -quotientGI // afix_mod ?setIS // setICA -gacentIim (setIC R) -setIA. rewrite -gacentE ?subsetIl // gacentIdom setICA (setIidPr _) //. by rewrite gacentC // ?(subset_trans cMH) ?astabS ?subsetIl // setICA subsetIl. Qed. Lemma acts_irr_mod G M : H \subset 'C(M | to) -> G \subset 'N(H) -> acts_irreducibly G M to -> acts_irreducibly (G / H) M mod_groupAction. Proof. move=> cMH nHG /mingroupP[/andP[ntM nMG] minM]. apply/mingroupP; rewrite ntM astabs_mod ?quotientS //; split=> // L modL ntL. have cLH: H \subset 'C(L | to) by rewrite (subset_trans cMH) ?astabS //. apply: minM => //; case/andP: modL => ->; rewrite astabs_mod ?quotientSGK //. by rewrite (subset_trans cLH) ?astab_sub. Qed. End Mod. Lemma modact_coset_astab x a : a \in D -> (to %% 'C(R | to))%act x (coset _ a) = to x a. Proof. move=> Da; apply: modgactE => {x}//. rewrite !inE Da; apply/subsetP=> _ /imsetP[c Cc ->]. have Dc := astab_dom Cc; rewrite !inE groupJ //. apply/subsetP=> x Rx; rewrite inE conjgE !actMin ?groupM ?groupV //. by rewrite (astab_act Cc) ?actKVin // gact_stable ?groupV. Qed. Lemma acts_irr_mod_astab G M : acts_irreducibly G M to -> acts_irreducibly (G / 'C_G(M | to)) M (mod_groupAction _). Proof. move=> irrG; have /andP[_ nMG] := mingroupp irrG. apply: acts_irr_mod irrG; first exact: subsetIr. by rewrite normsI ?normG // (subset_trans nMG) // astab_norm. Qed. Section CompAct. Variables (gT : finGroupType) (G : {group gT}) (f : {morphism G >-> aT}). Lemma comp_is_groupAction : is_groupAction R (comp_action to f). Proof. move=> a /morphpreP[Ba Dfa]; apply: etrans (actperm_Aut to Dfa). by congr (_ \in Aut R); apply/permP=> x; rewrite !actpermE. Qed. Canonical comp_groupAction := GroupAction comp_is_groupAction. Lemma gacent_comp U : 'C_(|comp_groupAction)(U) = 'C_(|to)(f @* U). Proof. rewrite /gacent afix_comp ?subIset ?subxx //. by rewrite -(setIC U) (setIC D) morphim_setIpre. Qed. End CompAct. End GroupActionTheory. Notation "''C_' ( | to ) ( A )" := (gacent_group to A) : Group_scope. Notation "''C_' ( G | to ) ( A )" := (setI_group G 'C_(|to)(A)) : Group_scope. Notation "''C_' ( | to ) [ a ]" := (gacent_group to [set a%g]) : Group_scope. Notation "''C_' ( G | to ) [ a ]" := (setI_group G 'C_(|to)[a]) : Group_scope. Notation "to \ sAD" := (ract_groupAction to sAD) : groupAction_scope. Notation "<[ nGA ] >" := (actby_groupAction nGA) : groupAction_scope. Notation "to / H" := (quotient_groupAction to H) : groupAction_scope. Notation "to %% H" := (mod_groupAction to H) : groupAction_scope. Notation "to \o f" := (comp_groupAction to f) : groupAction_scope. (* Operator group isomorphism. *) Section MorphAction. Variables (aT1 aT2 : finGroupType) (rT1 rT2 : finType). Variables (D1 : {group aT1}) (D2 : {group aT2}). Variables (to1 : action D1 rT1) (to2 : action D2 rT2). Variables (A : {set aT1}) (R S : {set rT1}). Variables (h : rT1 -> rT2) (f : {morphism D1 >-> aT2}). Hypotheses (actsDR : {acts D1, on R | to1}) (injh : {in R &, injective h}). Hypothesis defD2 : f @* D1 = D2. Hypotheses (sSR : S \subset R) (sAD1 : A \subset D1). Hypothesis hfJ : {in S & D1, morph_act to1 to2 h f}. Lemma morph_astabs : f @* 'N(S | to1) = 'N(h @: S | to2). Proof. apply/setP=> fx; apply/morphimP/idP=> [[x D1x nSx ->] | nSx]. rewrite 2!inE -{1}defD2 mem_morphim //=; apply/subsetP=> _ /imsetP[u Su ->]. by rewrite inE -hfJ ?imset_f // (astabs_act _ nSx). have [|x D1x _ def_fx] := morphimP (_ : fx \in f @* D1). by rewrite defD2 (astabs_dom nSx). exists x => //; rewrite !inE D1x; apply/subsetP=> u Su. have /imsetP[u' Su' /injh def_u']: h (to1 u x) \in h @: S. by rewrite hfJ // -def_fx (astabs_act _ nSx) imset_f. by rewrite inE def_u' ?actsDR ?(subsetP sSR). Qed. Lemma morph_astab : f @* 'C(S | to1) = 'C(h @: S | to2). Proof. apply/setP=> fx; apply/morphimP/idP=> [[x D1x cSx ->] | cSx]. rewrite 2!inE -{1}defD2 mem_morphim //=; apply/subsetP=> _ /imsetP[u Su ->]. by rewrite inE -hfJ // (astab_act cSx). have [|x D1x _ def_fx] := morphimP (_ : fx \in f @* D1). by rewrite defD2 (astab_dom cSx). exists x => //; rewrite !inE D1x; apply/subsetP=> u Su. rewrite inE -(inj_in_eq injh) ?actsDR ?(subsetP sSR) ?hfJ //. by rewrite -def_fx (astab_act cSx) ?imset_f. Qed. Lemma morph_afix : h @: 'Fix_(S | to1)(A) = 'Fix_(h @: S | to2)(f @* A). Proof. apply/setP=> hu; apply/imsetP/setIP=> [[u /setIP[Su cAu] ->]|]. split; first by rewrite imset_f. by apply/afixP=> _ /morphimP[x D1x Ax ->]; rewrite -hfJ ?(afixP cAu). case=> /imsetP[u Su ->] /afixP c_hu_fA; exists u; rewrite // inE Su. apply/afixP=> x Ax; have Dx := subsetP sAD1 x Ax. by apply: injh; rewrite ?actsDR ?(subsetP sSR) ?hfJ // c_hu_fA ?mem_morphim. Qed. End MorphAction. Section MorphGroupAction. Variables (aT1 aT2 rT1 rT2 : finGroupType). Variables (D1 : {group aT1}) (D2 : {group aT2}). Variables (R1 : {group rT1}) (R2 : {group rT2}). Variables (to1 : groupAction D1 R1) (to2 : groupAction D2 R2). Variables (h : {morphism R1 >-> rT2}) (f : {morphism D1 >-> aT2}). Hypotheses (iso_h : isom R1 R2 h) (iso_f : isom D1 D2 f). Hypothesis hfJ : {in R1 & D1, morph_act to1 to2 h f}. Implicit Types (A : {set aT1}) (S : {set rT1}) (M : {group rT1}). Lemma morph_gastabs S : S \subset R1 -> f @* 'N(S | to1) = 'N(h @* S | to2). Proof. have [[_ defD2] [injh _]] := (isomP iso_f, isomP iso_h). move=> sSR1; rewrite (morphimEsub _ sSR1). apply: (morph_astabs (gact_stable to1) (injmP injh)) => // u x. by move/(subsetP sSR1); apply: hfJ. Qed. Lemma morph_gastab S : S \subset R1 -> f @* 'C(S | to1) = 'C(h @* S | to2). Proof. have [[_ defD2] [injh _]] := (isomP iso_f, isomP iso_h). move=> sSR1; rewrite (morphimEsub _ sSR1). apply: (morph_astab (gact_stable to1) (injmP injh)) => // u x. by move/(subsetP sSR1); apply: hfJ. Qed. Lemma morph_gacent A : A \subset D1 -> h @* 'C_(|to1)(A) = 'C_(|to2)(f @* A). Proof. have [[_ defD2] [injh defR2]] := (isomP iso_f, isomP iso_h). move=> sAD1; rewrite !gacentE //; last by rewrite -defD2 morphimS. rewrite morphimEsub ?subsetIl // -{1}defR2 morphimEdom. exact: (morph_afix (gact_stable to1) (injmP injh)). Qed. Lemma morph_gact_irr A M : A \subset D1 -> M \subset R1 -> acts_irreducibly (f @* A) (h @* M) to2 = acts_irreducibly A M to1. Proof. move=> sAD1 sMR1. have [[injf defD2] [injh defR2]] := (isomP iso_f, isomP iso_h). have h_eq1 := morphim_injm_eq1 injh. apply/mingroupP/mingroupP=> [] [/andP[ntM actAM] minM]. split=> [|U]; first by rewrite -h_eq1 // ntM -(injmSK injf) ?morph_gastabs. case/andP=> ntU acts_fAU sUM; have sUR1 := subset_trans sUM sMR1. apply: (injm_morphim_inj injh) => //; apply: minM; last exact: morphimS. by rewrite h_eq1 // ntU -morph_gastabs ?morphimS. split=> [|U]; first by rewrite h_eq1 // ntM -morph_gastabs ?morphimS. case/andP=> ntU acts_fAU sUhM. have sUhR1 := subset_trans sUhM (morphimS h sMR1). have sU'M: h @*^-1 U \subset M by rewrite sub_morphpre_injm. rewrite /= -(minM _ _ sU'M) ?morphpreK // -h_eq1 ?subsetIl // -(injmSK injf) //. by rewrite morph_gastabs ?(subset_trans sU'M) // morphpreK ?ntU. Qed. End MorphGroupAction. (* Conjugation and right translation actions. *) Section InternalActionDefs. Variable gT : finGroupType. Implicit Type A : {set gT}. Implicit Type G : {group gT}. (* This is not a Canonical action because it is seldom used, and it would *) (* cause too many spurious matches (any group product would be viewed as an *) (* action!). *) Definition mulgr_action := TotalAction (@mulg1 gT) (@mulgA gT). Canonical conjg_action := TotalAction (@conjg1 gT) (@conjgM gT). Lemma conjg_is_groupAction : is_groupAction setT conjg_action. Proof. move=> a _; rewrite inE; apply/andP; split; first by apply/subsetP=> x /[1!inE]. by apply/morphicP=> x y _ _; rewrite !actpermE /= conjMg. Qed. Canonical conjg_groupAction := GroupAction conjg_is_groupAction. Lemma rcoset_is_action : is_action setT (@rcoset gT). Proof. by apply: is_total_action => [A|A x y]; rewrite !rcosetE (mulg1, rcosetM). Qed. Canonical rcoset_action := Action rcoset_is_action. Canonical conjsg_action := TotalAction (@conjsg1 gT) (@conjsgM gT). Lemma conjG_is_action : is_action setT (@conjG_group gT). Proof. apply: is_total_action => [G | G x y]; apply: val_inj; rewrite /= ?act1 //. exact: actM. Qed. Definition conjG_action := Action conjG_is_action. End InternalActionDefs. Notation "'R" := (@mulgr_action _) : action_scope. Notation "'Rs" := (@rcoset_action _) : action_scope. Notation "'J" := (@conjg_action _) : action_scope. Notation "'J" := (@conjg_groupAction _) : groupAction_scope. Notation "'Js" := (@conjsg_action _) : action_scope. Notation "'JG" := (@conjG_action _) : action_scope. Notation "'Q" := ('J / _)%act : action_scope. Notation "'Q" := ('J / _)%gact : groupAction_scope. Section InternalGroupAction. Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Types G H : {group gT}. Implicit Type x : gT. (* Various identities for actions on groups. *) Lemma orbitR G x : orbit 'R G x = x *: G. Proof. by rewrite -lcosetE. Qed. Lemma astab1R x : 'C[x | 'R] = 1. Proof. apply/trivgP/subsetP=> y cxy. by rewrite -(mulKg x y) [x * y](astab1P cxy) mulVg set11. Qed. Lemma astabR G : 'C(G | 'R) = 1. Proof. apply/trivgP/subsetP=> x cGx. by rewrite -(mul1g x) [1 * x](astabP cGx) group1. Qed. Lemma astabsR G : 'N(G | 'R) = G. Proof. apply/setP=> x; rewrite !inE -setactVin ?inE //=. by rewrite -groupV -{1 3}(mulg1 G) rcoset_sym -sub1set -mulGS -!rcosetE. Qed. Lemma atransR G : [transitive G, on G | 'R]. Proof. by rewrite /atrans -{1}(mul1g G) -orbitR imset_f. Qed. Lemma faithfulR G : [faithful G, on G | 'R]. Proof. by rewrite /faithful astabR subsetIr. Qed. Definition Cayley_repr G := actperm <[atrans_acts (atransR G)]>. Theorem Cayley_isom G : isom G (Cayley_repr G @* G) (Cayley_repr G). Proof. exact: faithful_isom (faithfulR G). Qed. Theorem Cayley_isog G : G \isog Cayley_repr G @* G. Proof. exact: isom_isog (Cayley_isom G). Qed. Lemma orbitJ G x : orbit 'J G x = x ^: G. Proof. by []. Qed. Lemma afixJ A : 'Fix_('J)(A) = 'C(A). Proof. apply/setP=> x; apply/afixP/centP=> cAx y Ay /=. by rewrite /commute conjgC cAx. by rewrite conjgE cAx ?mulKg. Qed. Lemma astabJ A : 'C(A |'J) = 'C(A). Proof. apply/setP=> x; apply/astabP/centP=> cAx y Ay /=. by apply: esym; rewrite conjgC cAx. by rewrite conjgE -cAx ?mulKg. Qed. Lemma astab1J x : 'C[x |'J] = 'C[x]. Proof. by rewrite astabJ cent_set1. Qed. Lemma astabsJ A : 'N(A | 'J) = 'N(A). Proof. by apply/setP=> x; rewrite -2!groupV !inE -conjg_preim -sub_conjg. Qed. Lemma setactJ A x : 'J^*%act A x = A :^ x. Proof. by []. Qed. Lemma gacentJ A : 'C_(|'J)(A) = 'C(A). Proof. by rewrite gacentE ?setTI ?subsetT ?afixJ. Qed. Lemma orbitRs G A : orbit 'Rs G A = rcosets A G. Proof. by []. Qed. Lemma sub_afixRs_norms G x A : (G :* x \in 'Fix_('Rs)(A)) = (A \subset G :^ x). Proof. rewrite inE /=; apply: eq_subset_r => a. rewrite inE rcosetE -(can2_eq (rcosetKV x) (rcosetK x)) -!rcosetM. rewrite eqEcard card_rcoset leqnn andbT mulgA (conjgCV x) mulgK. by rewrite -{2 3}(mulGid G) mulGS sub1set -mem_conjg. Qed. Lemma sub_afixRs_norm G x : (G :* x \in 'Fix_('Rs)(G)) = (x \in 'N(G)). Proof. by rewrite sub_afixRs_norms -groupV inE sub_conjgV. Qed. Lemma afixRs_rcosets A G : 'Fix_(rcosets G A | 'Rs)(G) = rcosets G 'N_A(G). Proof. apply/setP=> Gx; apply/setIP/rcosetsP=> [[/rcosetsP[x Ax ->]]|[x]]. by rewrite sub_afixRs_norm => Nx; exists x; rewrite // inE Ax. by case/setIP=> Ax Nx ->; rewrite -{1}rcosetE imset_f // sub_afixRs_norm. Qed. Lemma astab1Rs G : 'C[G : {set gT} | 'Rs] = G. Proof. apply/setP=> x. by apply/astab1P/idP=> /= [<- | Gx]; rewrite rcosetE ?rcoset_refl ?rcoset_id. Qed. Lemma actsRs_rcosets H G : [acts G, on rcosets H G | 'Rs]. Proof. by rewrite -orbitRs acts_orbit ?subsetT. Qed. Lemma transRs_rcosets H G : [transitive G, on rcosets H G | 'Rs]. Proof. by rewrite -orbitRs atrans_orbit. Qed. (* This is the second part of Aschbacher (5.7) *) Lemma astabRs_rcosets H G : 'C(rcosets H G | 'Rs) = gcore H G. Proof. have transGH := transRs_rcosets H G. by rewrite (astab_trans_gcore transGH (orbit_refl _ G _)) astab1Rs. Qed. Lemma orbitJs G A : orbit 'Js G A = A :^: G. Proof. by []. Qed. Lemma astab1Js A : 'C[A | 'Js] = 'N(A). Proof. by apply/setP=> x; apply/astab1P/normP. Qed. Lemma card_conjugates A G : #|A :^: G| = #|G : 'N_G(A)|. Proof. by rewrite card_orbit astab1Js. Qed. Lemma afixJG G A : (G \in 'Fix_('JG)(A)) = (A \subset 'N(G)). Proof. by apply/afixP/normsP=> nG x Ax; apply/eqP; move/eqP: (nG x Ax). Qed. Lemma astab1JG G : 'C[G | 'JG] = 'N(G). Proof. by apply/setP=> x; apply/astab1P/normP=> [/congr_group | /group_inj]. Qed. Lemma dom_qactJ H : qact_dom 'J H = 'N(H). Proof. by rewrite qact_domE ?subsetT ?astabsJ. Qed. Lemma qactJ H (Hy : coset_of H) x : 'Q%act Hy x = if x \in 'N(H) then Hy ^ coset H x else Hy. Proof. case: (cosetP Hy) => y Ny ->{Hy}. by rewrite qactEcond // dom_qactJ; case Nx: (x \in 'N(H)); rewrite ?morphJ. Qed. Lemma actsQ A B H : A \subset 'N(H) -> A \subset 'N(B) -> [acts A, on B / H | 'Q]. Proof. by move=> nHA nBA; rewrite acts_quotient // subsetI dom_qactJ nHA astabsJ. Qed. Lemma astabsQ G H : H <| G -> 'N(G / H | 'Q) = 'N(H) :&: 'N(G). Proof. by move=> nsHG; rewrite astabs_quotient // dom_qactJ astabsJ. Qed. Lemma astabQ H Abar : 'C(Abar |'Q) = coset H @*^-1 'C(Abar). Proof. apply/setP=> x; rewrite inE /= dom_qactJ morphpreE in_setI /=. apply: andb_id2l => Nx; rewrite !inE -sub1set centsC cent_set1. apply: eq_subset_r => {Abar} Hy; rewrite inE qactJ Nx (sameP eqP conjg_fixP). by rewrite (sameP cent1P eqP) (sameP commgP eqP). Qed. Lemma sub_astabQ A H Bbar : (A \subset 'C(Bbar | 'Q)) = (A \subset 'N(H)) && (A / H \subset 'C(Bbar)). Proof. rewrite astabQ -morphpreIdom subsetI; apply: andb_id2l => nHA. by rewrite -sub_quotient_pre. Qed. Lemma sub_astabQR A B H : A \subset 'N(H) -> B \subset 'N(H) -> (A \subset 'C(B / H | 'Q)) = ([~: A, B] \subset H). Proof. move=> nHA nHB; rewrite sub_astabQ nHA /= (sameP commG1P eqP). by rewrite eqEsubset sub1G andbT -quotientR // quotient_sub1 // comm_subG. Qed. Lemma astabQR A H : A \subset 'N(H) -> 'C(A / H | 'Q) = [set x in 'N(H) | [~: [set x], A] \subset H]. Proof. move=> nHA; apply/setP=> x; rewrite astabQ -morphpreIdom 2!inE -astabQ. by case nHx: (x \in _); rewrite //= -sub1set sub_astabQR ?sub1set. Qed. Lemma quotient_astabQ H Abar : 'C(Abar | 'Q) / H = 'C(Abar). Proof. by rewrite astabQ cosetpreK. Qed. Lemma conj_astabQ A H x : x \in 'N(H) -> 'C(A / H | 'Q) :^ x = 'C(A :^ x / H | 'Q). Proof. move=> nHx; apply/setP=> y; rewrite !astabQ mem_conjg !in_setI -mem_conjg. rewrite -normJ (normP nHx) quotientJ //; apply/andb_id2l => nHy. by rewrite !inE centJ morphJ ?groupV ?morphV // -mem_conjg. Qed. Section CardClass. Variable G : {group gT}. Lemma index_cent1 x : #|G : 'C_G[x]| = #|x ^: G|. Proof. by rewrite -astab1J -card_orbit. Qed. Lemma classes_partition : partition (classes G) G. Proof. by apply: orbit_partition; apply/actsP=> x Gx y; apply: groupJr. Qed. Lemma sum_card_class : \sum_(C in classes G) #|C| = #|G|. Proof. by apply: acts_sum_card_orbit; apply/actsP=> x Gx y; apply: groupJr. Qed. Lemma class_formula : \sum_(C in classes G) #|G : 'C_G[repr C]| = #|G|. Proof. rewrite -sum_card_class; apply: eq_bigr => _ /imsetP[x Gx ->]. have: x \in x ^: G by rewrite -{1}(conjg1 x) imset_f. by case/mem_repr/imsetP=> y Gy ->; rewrite index_cent1 classGidl. Qed. Lemma abelian_classP : reflect {in G, forall x, x ^: G = [set x]} (abelian G). Proof. rewrite /abelian -astabJ astabC. by apply: (iffP subsetP) => cGG x Gx; apply/orbit1P; apply: cGG. Qed. Lemma card_classes_abelian : abelian G = (#|classes G| == #|G|). Proof. have cGgt0 C: C \in classes G -> 1 <= #|C| ?= iff (#|C| == 1)%N. by case/imsetP=> x _ ->; rewrite eq_sym -index_cent1. rewrite -sum_card_class -sum1_card (leqif_sum cGgt0). apply/abelian_classP/forall_inP=> [cGG _ /imsetP[x Gx ->]| cGG x Gx]. by rewrite cGG ?cards1. apply/esym/eqP; rewrite eqEcard sub1set cards1 class_refl leq_eqVlt cGG //. exact: imset_f. Qed. End CardClass. End InternalGroupAction. Lemma gacentQ (gT : finGroupType) (H : {group gT}) (A : {set gT}) : 'C_(|'Q)(A) = 'C(A / H). Proof. apply/setP=> Hx; case: (cosetP Hx) => x Nx ->{Hx}. rewrite -sub_cent1 -astab1J astabC sub1set -(quotientInorm H A). have defD: qact_dom 'J H = 'N(H) by rewrite qact_domE ?subsetT ?astabsJ. rewrite !(inE, mem_quotient) //= defD setIC. apply/subsetP/subsetP=> [cAx _ /morphimP[a Na Aa ->] | cAx a Aa]. by move/cAx: Aa; rewrite !inE qactE ?defD ?morphJ. have [_ Na] := setIP Aa; move/implyP: (cAx (coset H a)); rewrite mem_morphim //. by rewrite !inE qactE ?defD ?morphJ. Qed. Section AutAct. Variable (gT : finGroupType) (G : {set gT}). Definition autact := act ('P \ subsetT (Aut G)). Canonical aut_action := [action of autact]. Lemma autactK a : actperm aut_action a = a. Proof. by apply/permP=> x; rewrite permE. Qed. Lemma autact_is_groupAction : is_groupAction G aut_action. Proof. by move=> a Aa /=; rewrite autactK. Qed. Canonical aut_groupAction := GroupAction autact_is_groupAction. Section perm_prime_orbit. Variable (T : finType) (c : {perm T}). Hypothesis Tp : prime #|T|. Hypothesis cc : #[c]%g = #|T|. Let cp : prime #[c]%g. Proof. by rewrite cc. Qed. Lemma perm_prime_atrans : [transitive <[c]>, on setT | 'P]. Proof. apply/imsetP; suff /existsP[x] : [exists x, ~~ (#|orbit 'P <[c]> x| < #[c])]. move=> oxT; suff /eqP orbit_x : orbit 'P <[c]> x == setT by exists x. by rewrite eqEcard subsetT cardsT -cc leqNgt. apply/forallP => olT; have o1 x : #|orbit 'P <[c]> x| == 1%N. by case/primeP: cp => _ /(_ _ (dvdn_orbit 'P _ x))/orP[]//; rewrite ltn_eqF. suff c1 : c = 1%g by rewrite c1 ?order1 in (cp). apply/permP => x; rewrite perm1; apply/set1P. by rewrite -(card_orbit1 (eqP (o1 _))) (mem_orbit 'P) ?cycle_id. Qed. Lemma perm_prime_orbit x : orbit 'P <[c]> x = [set: T]. Proof. by apply: atransP => //; apply: perm_prime_atrans. Qed. Lemma perm_prime_astab x : 'C_<[c]>[x | 'P]%g = 1%g. Proof. by apply/card1_trivg/eqP; rewrite -(@eqn_pmul2l #|orbit 'P <[c]> x|) ?card_orbit_stab ?perm_prime_orbit ?cardsT ?muln1 ?prime_gt0// -cc. Qed. End perm_prime_orbit. End AutAct. Arguments autact {gT} G%_g. Arguments aut_action {gT} G%_g. Arguments aut_groupAction {gT} G%_g. Notation "[ 'Aut' G ]" := (aut_action G) : action_scope. Notation "[ 'Aut' G ]" := (aut_groupAction G) : groupAction_scope.
ChosenFiniteProducts.lean
import Mathlib.CategoryTheory.Sites.Limits import Mathlib.CategoryTheory.Monoidal.Cartesian.FunctorCategory deprecated_module (since := "2025-05-11")
sylow.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 prime bigop finset fingroup morphism. From mathcomp Require Import automorphism quotient action cyclic gproduct . From mathcomp Require Import gfunctor commutator pgroup center nilpotent. (******************************************************************************) (* The Sylow theorem and its consequences, including the Frattini argument, *) (* the nilpotence of p-groups, and the Baer-Suzuki theorem. *) (* This file also defines: *) (* Zgroup G == G is a Z-group, i.e., has only cyclic Sylow p-subgroups. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. (* The mod p lemma for the action of p-groups. *) Section ModP. Variable (aT : finGroupType) (sT : finType) (D : {group aT}). Variable to : action D sT. Lemma pgroup_fix_mod (p : nat) (G : {group aT}) (S : {set sT}) : p.-group G -> [acts G, on S | to] -> #|S| = #|'Fix_(S | to)(G)| %[mod p]. Proof. move=> pG nSG; have sGD: G \subset D := acts_dom nSG. apply/eqP; rewrite -(cardsID 'Fix_to(G)) eqn_mod_dvd (leq_addr, addKn) //. have: [acts G, on S :\: 'Fix_to(G) | to]; last move/acts_sum_card_orbit <-. rewrite actsD // -(setIidPr sGD); apply: subset_trans (acts_subnorm_fix _ _). by rewrite setIS ?normG. apply: dvdn_sum => _ /imsetP[x /setDP[_ nfx] ->]. have [k oGx]: {k | #|orbit to G x| = (p ^ k)%N}. by apply: p_natP; apply: pnat_dvd pG; rewrite card_orbit_in ?dvdn_indexg. case: k oGx => [/card_orbit1 fix_x | k ->]; last by rewrite expnS dvdn_mulr. by case/afixP: nfx => a Ga; apply/set1P; rewrite -fix_x mem_orbit. Qed. End ModP. Section ModularGroupAction. Variables (aT rT : finGroupType) (D : {group aT}) (R : {group rT}). Variables (to : groupAction D R) (p : nat). Implicit Types (G H : {group aT}) (M : {group rT}). Lemma nontrivial_gacent_pgroup G M : p.-group G -> p.-group M -> {acts G, on group M | to} -> M :!=: 1 -> 'C_(M | to)(G) :!=: 1. Proof. move=> pG pM [nMG sMR] ntM; have [p_pr p_dv_M _] := pgroup_pdiv pM ntM. rewrite -cardG_gt1 (leq_trans (prime_gt1 p_pr)) 1?dvdn_leq ?cardG_gt0 //= /dvdn. by rewrite gacentE ?(acts_dom nMG) // setIA (setIidPl sMR) -pgroup_fix_mod. Qed. Lemma pcore_sub_astab_irr G M : p.-group M -> M \subset R -> acts_irreducibly G M to -> 'O_p(G) \subset 'C_G(M | to). Proof. move=> pM sMR /mingroupP[/andP[ntM nMG] minM]. have /andP[sGpG nGpG]: 'O_p(G) <| G := gFnormal _ G. have sGD := acts_dom nMG; have sGpD: 'O_p(G) \subset D := gFsub_trans _ sGD. rewrite subsetI sGpG -gacentC //=; apply/setIidPl; apply: minM (subsetIl _ _). rewrite nontrivial_gacent_pgroup ?pcore_pgroup //=; last first. by split; rewrite ?gFsub_trans. by apply: subset_trans (acts_subnorm_subgacent sGpD nMG); rewrite subsetI subxx. Qed. Lemma pcore_faithful_irr_act G M : p.-group M -> M \subset R -> acts_irreducibly G M to -> [faithful G, on M | to] -> 'O_p(G) = 1. Proof. move=> pM sMR irrG ffulG; apply/trivgP; apply: subset_trans ffulG. exact: pcore_sub_astab_irr. Qed. End ModularGroupAction. Section Sylow. Variables (p : nat) (gT : finGroupType) (G : {group gT}). Implicit Types P Q H K : {group gT}. Theorem Sylow's_theorem : [/\ forall P, [max P | p.-subgroup(G) P] = p.-Sylow(G) P, [transitive G, on 'Syl_p(G) | 'JG], forall P, p.-Sylow(G) P -> #|'Syl_p(G)| = #|G : 'N_G(P)| & prime p -> #|'Syl_p(G)| %% p = 1%N]. Proof. pose maxp A P := [max P | p.-subgroup(A) P]; pose S := [set P | maxp G P]. pose oG := orbit 'JG%act G. have actS: [acts G, on S | 'JG]. apply/subsetP=> x Gx; rewrite 3!inE; apply/subsetP=> P; rewrite 3!inE. exact: max_pgroupJ. have S_pG P: P \in S -> P \subset G /\ p.-group P. by rewrite inE => /maxgroupp/andP[]. have SmaxN P Q: Q \in S -> Q \subset 'N(P) -> maxp 'N_G(P) Q. rewrite inE => /maxgroupP[/andP[sQG pQ] maxQ] nPQ. apply/maxgroupP; rewrite /psubgroup subsetI sQG nPQ. by split=> // R; rewrite subsetI -andbA andbCA => /andP[_]; apply: maxQ. have nrmG P: P \subset G -> P <| 'N_G(P). by move=> sPG; rewrite /normal subsetIr subsetI sPG normG. have sylS P: P \in S -> p.-Sylow('N_G(P)) P. move=> S_P; have [sPG pP] := S_pG P S_P. by rewrite normal_max_pgroup_Hall ?nrmG //; apply: SmaxN; rewrite ?normG. have{SmaxN} defCS P: P \in S -> 'Fix_(S |'JG)(P) = [set P]. move=> S_P; apply/setP=> Q; rewrite {1}in_setI {1}afixJG. apply/andP/set1P=> [[S_Q nQP]|->{Q}]; last by rewrite normG. apply/esym/val_inj; case: (S_pG Q) => //= sQG _. by apply: uniq_normal_Hall (SmaxN Q _ _ _) => //=; rewrite ?sylS ?nrmG. have{defCS} oG_mod: {in S &, forall P Q, #|oG P| = (Q \in oG P) %[mod p]}. move=> P Q S_P S_Q; have [sQG pQ] := S_pG _ S_Q. have soP_S: oG P \subset S by rewrite acts_sub_orbit. have /pgroup_fix_mod-> //: [acts Q, on oG P | 'JG]. apply/actsP=> x /(subsetP sQG) Gx R; apply: orbit_transl. exact: mem_orbit. rewrite -{1}(setIidPl soP_S) -setIA defCS // (cardsD1 Q) setDE. by rewrite -setIA setICr setI0 cards0 addn0 inE set11 andbT. have [P S_P]: exists P, P \in S. have: p.-subgroup(G) 1 by rewrite /psubgroup sub1G pgroup1. by case/(@maxgroup_exists _ (p.-subgroup(G))) => P; exists P; rewrite inE. have trS: [transitive G, on S | 'JG]. apply/imsetP; exists P => //; apply/eqP. rewrite eqEsubset andbC acts_sub_orbit // S_P; apply/subsetP=> Q S_Q. have /[1!inE] /maxgroupP[/andP[_ pP]] := S_P. have [-> max1 | ntP _] := eqVneq P 1%G. move/andP/max1: (S_pG _ S_Q) => Q1. by rewrite (group_inj (Q1 (sub1G Q))) orbit_refl. have:= oG_mod _ _ S_P S_P; rewrite (oG_mod _ Q) // orbit_refl. have p_gt1: p > 1 by apply: prime_gt1; case/pgroup_pdiv: pP. by case: (Q \in oG P) => //; rewrite mod0n modn_small. have oS1: prime p -> #|S| %% p = 1%N. move/prime_gt1 => p_gt1. by rewrite -(atransP trS P S_P) (oG_mod P P) // orbit_refl modn_small. have oSiN Q: Q \in S -> #|S| = #|G : 'N_G(Q)|. by move=> S_Q; rewrite -(atransP trS Q S_Q) card_orbit astab1JG. have sylP: p.-Sylow(G) P. rewrite pHallE; case: (S_pG P) => // -> /= pP. case p_pr: (prime p); last first. rewrite p_part lognE p_pr /= -trivg_card1; apply/idPn=> ntP. by case/pgroup_pdiv: pP p_pr => // ->. rewrite -(LagrangeI G 'N(P)) /= mulnC partnM ?cardG_gt0 // part_p'nat. by rewrite mul1n (card_Hall (sylS P S_P)). by rewrite p'natE // -indexgI -oSiN // /dvdn oS1. have eqS Q: maxp G Q = p.-Sylow(G) Q. apply/idP/idP=> [S_Q|]; last exact: Hall_max. have{} S_Q: Q \in S by rewrite inE. rewrite pHallE -(card_Hall sylP); case: (S_pG Q) => // -> _ /=. by case: (atransP2 trS S_P S_Q) => x _ ->; rewrite cardJg. have ->: 'Syl_p(G) = S by apply/setP=> Q; rewrite 2!inE. by split=> // Q sylQ; rewrite -oSiN ?inE ?eqS. Qed. Lemma max_pgroup_Sylow P : [max P | p.-subgroup(G) P] = p.-Sylow(G) P. Proof. by case Sylow's_theorem. Qed. Lemma Sylow_superset Q : Q \subset G -> p.-group Q -> {P : {group gT} | p.-Sylow(G) P & Q \subset P}. Proof. move=> sQG pQ. have [|P] := @maxgroup_exists _ (p.-subgroup(G)) Q; first exact/andP. by rewrite max_pgroup_Sylow; exists P. Qed. Lemma Sylow_exists : {P : {group gT} | p.-Sylow(G) P}. Proof. by case: (Sylow_superset (sub1G G) (pgroup1 _ p)) => P; exists P. Qed. Lemma Syl_trans : [transitive G, on 'Syl_p(G) | 'JG]. Proof. by case Sylow's_theorem. Qed. Lemma Sylow_trans P Q : p.-Sylow(G) P -> p.-Sylow(G) Q -> exists2 x, x \in G & Q :=: P :^ x. Proof. move=> sylP sylQ; have /[!inE] := (atransP2 Syl_trans) P Q. by case=> // x Gx ->; exists x. Qed. Lemma Sylow_subJ P Q : p.-Sylow(G) P -> Q \subset G -> p.-group Q -> exists2 x, x \in G & Q \subset P :^ x. Proof. move=> sylP sQG pQ; have [Px sylPx] := Sylow_superset sQG pQ. by have [x Gx ->] := Sylow_trans sylP sylPx; exists x. Qed. Lemma Sylow_Jsub P Q : p.-Sylow(G) P -> Q \subset G -> p.-group Q -> exists2 x, x \in G & Q :^ x \subset P. Proof. move=> sylP sQG pQ; have [x Gx] := Sylow_subJ sylP sQG pQ. by exists x^-1; rewrite (groupV, sub_conjgV). Qed. Lemma card_Syl P : p.-Sylow(G) P -> #|'Syl_p(G)| = #|G : 'N_G(P)|. Proof. by case: Sylow's_theorem P. Qed. Lemma card_Syl_dvd : #|'Syl_p(G)| %| #|G|. Proof. by case Sylow_exists => P /card_Syl->; apply: dvdn_indexg. Qed. Lemma card_Syl_mod : prime p -> #|'Syl_p(G)| %% p = 1%N. Proof. by case Sylow's_theorem. Qed. Lemma Frattini_arg H P : G <| H -> p.-Sylow(G) P -> G * 'N_H(P) = H. Proof. case/andP=> sGH nGH sylP; rewrite -normC ?subIset ?nGH ?orbT // -astab1JG. move/subgroup_transitiveP: Syl_trans => ->; rewrite ?inE //. apply/imsetP; exists P; rewrite ?inE //. apply/eqP; rewrite eqEsubset -{1}((atransP Syl_trans) P) ?inE // imsetS //=. by apply/subsetP=> _ /imsetP[x Hx ->]; rewrite inE -(normsP nGH x Hx) pHallJ2. Qed. End Sylow. Section MoreSylow. Variables (gT : finGroupType) (p : nat). Implicit Types G H P : {group gT}. Lemma Sylow_setI_normal G H P : G <| H -> p.-Sylow(H) P -> p.-Sylow(G) (G :&: P). Proof. case/normalP=> sGH nGH sylP; have [Q sylQ] := Sylow_exists p G. have /maxgroupP[/andP[sQG pQ] maxQ] := Hall_max sylQ. have [R sylR sQR] := Sylow_superset (subset_trans sQG sGH) pQ. have [[x Hx ->] pR] := (Sylow_trans sylR sylP, pHall_pgroup sylR). rewrite -(nGH x Hx) -conjIg pHallJ2. have /maxQ-> //: Q \subset G :&: R by rewrite subsetI sQG. by rewrite /psubgroup subsetIl (pgroupS _ pR) ?subsetIr. Qed. Lemma normal_sylowP G : reflect (exists2 P : {group gT}, p.-Sylow(G) P & P <| G) (#|'Syl_p(G)| == 1%N). Proof. apply: (iffP idP) => [syl1 | [P sylP nPG]]; last first. by rewrite (card_Syl sylP) (setIidPl _) (indexgg, normal_norm). have [P sylP] := Sylow_exists p G; exists P => //. rewrite /normal (pHall_sub sylP); apply/setIidPl; apply/eqP. rewrite eqEcard subsetIl -(LagrangeI G 'N(P)) -indexgI /=. by rewrite -(card_Syl sylP) (eqP syl1) muln1. Qed. Lemma trivg_center_pgroup P : p.-group P -> 'Z(P) = 1 -> P :=: 1. Proof. move=> pP Z1; apply/eqP/idPn=> ntP. have{ntP} [p_pr p_dv_P _] := pgroup_pdiv pP ntP. suff: p %| #|'Z(P)| by rewrite Z1 cards1 gtnNdvd ?prime_gt1. by rewrite /center /dvdn -afixJ -pgroup_fix_mod // astabsJ normG. Qed. Lemma p2group_abelian P : p.-group P -> logn p #|P| <= 2 -> abelian P. Proof. move=> pP lePp2; pose Z := 'Z(P); have sZP: Z \subset P := center_sub P. have [/(trivg_center_pgroup pP) ->|] := eqVneq Z 1; first exact: abelian1. case/(pgroup_pdiv (pgroupS sZP pP)) => p_pr _ [k oZ]. apply: cyclic_center_factor_abelian. have [->|] := eqVneq (P / Z) 1; first exact: cyclic1. have pPq := quotient_pgroup 'Z(P) pP; case/(pgroup_pdiv pPq) => _ _ [j oPq]. rewrite prime_cyclic // oPq; case: j oPq lePp2 => //= j. rewrite card_quotient ?gFnorm //. by rewrite -(Lagrange sZP) lognM // => ->; rewrite oZ !pfactorK ?addnS. Qed. Lemma card_p2group_abelian P : prime p -> #|P| = (p ^ 2)%N -> abelian P. Proof. move=> primep oP; have pP: p.-group P by rewrite /pgroup oP pnatX pnat_id. by rewrite (p2group_abelian pP) // oP pfactorK. Qed. Lemma Sylow_transversal_gen (T : {set {group gT}}) G : (forall P, P \in T -> P \subset G) -> (forall p, p \in \pi(G) -> exists2 P, P \in T & p.-Sylow(G) P) -> << \bigcup_(P in T) P >> = G. Proof. move=> G_T T_G; apply/eqP; rewrite eqEcard gen_subG. apply/andP; split; first exact/bigcupsP. apply: dvdn_leq (cardG_gt0 _) _; apply/dvdn_partP=> // q /T_G[P T_P sylP]. by rewrite -(card_Hall sylP); apply: cardSg; rewrite sub_gen // bigcup_sup. Qed. Lemma Sylow_gen G : <<\bigcup_(P : {group gT} | Sylow G P) P>> = G. Proof. set T := [set P : {group gT} | Sylow G P]. rewrite -{2}(@Sylow_transversal_gen T G) => [|P | q _]. - by congr <<_>>; apply: eq_bigl => P; rewrite inE. - by rewrite inE => /and3P[]. by case: (Sylow_exists q G) => P sylP; exists P; rewrite // inE (p_Sylow sylP). Qed. End MoreSylow. Section SomeHall. Variable gT : finGroupType. Implicit Types (p : nat) (pi : nat_pred) (G H K P R : {group gT}). Lemma Hall_pJsub p pi G H P : pi.-Hall(G) H -> p \in pi -> P \subset G -> p.-group P -> exists2 x, x \in G & P :^ x \subset H. Proof. move=> hallH pi_p sPG pP. have [S sylS] := Sylow_exists p H; have sylS_G := subHall_Sylow hallH pi_p sylS. have [x Gx sPxS] := Sylow_Jsub sylS_G sPG pP; exists x => //. exact: subset_trans sPxS (pHall_sub sylS). Qed. Lemma Hall_psubJ p pi G H P : pi.-Hall(G) H -> p \in pi -> P \subset G -> p.-group P -> exists2 x, x \in G & P \subset H :^ x. Proof. move=> hallH pi_p sPG pP; have [x Gx sPxH] := Hall_pJsub hallH pi_p sPG pP. by exists x^-1; rewrite ?groupV -?sub_conjg. Qed. Lemma Hall_setI_normal pi G K H : K <| G -> pi.-Hall(G) H -> pi.-Hall(K) (H :&: K). Proof. move=> nsKG hallH; have [sHG piH _] := and3P hallH. have [sHK_H sHK_K] := (subsetIl H K, subsetIr H K). rewrite pHallE sHK_K /= -(part_pnat_id (pgroupS sHK_H piH)); apply/eqP. rewrite (widen_partn _ (subset_leq_card sHK_K)); apply: eq_bigr => p pi_p. have [P sylP] := Sylow_exists p H. have sylPK := Sylow_setI_normal nsKG (subHall_Sylow hallH pi_p sylP). rewrite -!p_part -(card_Hall sylPK); symmetry; apply: card_Hall. by rewrite (pHall_subl _ sHK_K) //= setIC setSI ?(pHall_sub sylP). Qed. Lemma coprime_mulG_setI_norm H G K R : K * R = G -> G \subset 'N(H) -> coprime #|K| #|R| -> (K :&: H) * (R :&: H) = G :&: H. Proof. move=> defG nHG coKR; apply/eqP; rewrite eqEcard mulG_subG /= -defG. rewrite !setSI ?mulG_subl ?mulG_subr //=. rewrite coprime_cardMg ?(coKR, coprimeSg (subsetIl _ _), coprime_sym) //=. pose pi := \pi(K); have piK: pi.-group K by apply: pgroup_pi. have pi'R: pi^'.-group R by rewrite /pgroup -coprime_pi' /=. have [hallK hallR] := coprime_mulpG_Hall defG piK pi'R. have nsHG: H :&: G <| G by rewrite /normal subsetIr normsI ?normG. rewrite -!(setIC H) defG -(partnC pi (cardG_gt0 _)). rewrite -(card_Hall (Hall_setI_normal nsHG hallR)) /= setICA. rewrite -(card_Hall (Hall_setI_normal nsHG hallK)) /= setICA. by rewrite -defG (setIidPl (mulG_subl _ _)) (setIidPl (mulG_subr _ _)). Qed. End SomeHall. Section Nilpotent. Variable gT : finGroupType. Implicit Types (G H K P L : {group gT}) (p q : nat). Lemma pgroup_nil p P : p.-group P -> nilpotent P. Proof. move: {2}_.+1 (ltnSn #|P|) => n. elim: n gT P => // n IHn pT P; rewrite ltnS=> lePn pP. have [Z1 | ntZ] := eqVneq 'Z(P) 1. by rewrite (trivg_center_pgroup pP Z1) nilpotent1. rewrite -quotient_center_nil IHn ?morphim_pgroup // (leq_trans _ lePn) //. rewrite card_quotient ?normal_norm ?center_normal // -divgS ?subsetIl //. by rewrite ltn_Pdiv // ltnNge -trivg_card_le1. Qed. Lemma pgroup_sol p P : p.-group P -> solvable P. Proof. by move/pgroup_nil; apply: nilpotent_sol. Qed. Lemma small_nil_class G : nil_class G <= 5 -> nilpotent G. Proof. move=> leK5; case: (ltnP 5 #|G|) => [lt5G | leG5 {leK5}]. by rewrite nilpotent_class (leq_ltn_trans leK5). apply: pgroup_nil (pdiv #|G|) _ _; apply/andP; split=> //. by case: #|G| leG5 => //; do 5!case=> //. Qed. Lemma nil_class2 G : (nil_class G <= 2) = (G^`(1) \subset 'Z(G)). Proof. rewrite subsetI der_sub; apply/idP/commG1P=> [clG2 | L3G1]. by apply/(lcn_nil_classP 2); rewrite ?small_nil_class ?(leq_trans clG2). by apply/(lcn_nil_classP 2) => //; apply/lcnP; exists 2. Qed. Lemma nil_class3 G : (nil_class G <= 3) = ('L_3(G) \subset 'Z(G)). Proof. rewrite subsetI lcn_sub; apply/idP/commG1P=> [clG3 | L4G1]. by apply/(lcn_nil_classP 3); rewrite ?small_nil_class ?(leq_trans clG3). by apply/(lcn_nil_classP 3) => //; apply/lcnP; exists 3. Qed. Lemma nilpotent_maxp_normal pi G H : nilpotent G -> [max H | pi.-subgroup(G) H] -> H <| G. Proof. move=> nilG /maxgroupP[/andP[sHG piH] maxH]. have nHN: H <| 'N_G(H) by rewrite normal_subnorm. have{maxH} hallH: pi.-Hall('N_G(H)) H. apply: normal_max_pgroup_Hall => //; apply/maxgroupP. rewrite /psubgroup normal_sub // piH; split=> // K. by rewrite subsetI -andbA andbCA => /andP[_ /maxH]. rewrite /normal sHG; apply/setIidPl/esym. apply: nilpotent_sub_norm; rewrite ?subsetIl ?setIS //= char_norms //. by congr (_ \char _): (pcore_char pi 'N_G(H)); apply: normal_Hall_pcore. Qed. Lemma nilpotent_Hall_pcore pi G H : nilpotent G -> pi.-Hall(G) H -> H :=: 'O_pi(G). Proof. move=> nilG hallH; have maxH := Hall_max hallH; apply/eqP. rewrite eqEsubset pcore_max ?(pHall_pgroup hallH) //. by rewrite (normal_sub_max_pgroup maxH) ?pcore_pgroup ?pcore_normal. exact: nilpotent_maxp_normal maxH. Qed. Lemma nilpotent_pcore_Hall pi G : nilpotent G -> pi.-Hall(G) 'O_pi(G). Proof. move=> nilG; case: (@maxgroup_exists _ (psubgroup pi G) 1) => [|H maxH _]. by rewrite /psubgroup sub1G pgroup1. have hallH := normal_max_pgroup_Hall maxH (nilpotent_maxp_normal nilG maxH). by rewrite -(nilpotent_Hall_pcore nilG hallH). Qed. Lemma nilpotent_pcoreC pi G : nilpotent G -> 'O_pi(G) \x 'O_pi^'(G) = G. Proof. move=> nilG; have trO: 'O_pi(G) :&: 'O_pi^'(G) = 1. by apply: coprime_TIg; apply: (@pnat_coprime pi); apply: pcore_pgroup. rewrite dprodE //. apply/eqP; rewrite eqEcard mul_subG ?pcore_sub // (TI_cardMg trO). by rewrite !(card_Hall (nilpotent_pcore_Hall _ _)) // partnC ?leqnn. rewrite (sameP commG1P trivgP) -trO subsetI commg_subl commg_subr. by rewrite !gFsub_trans ?gFnorm. Qed. Lemma sub_nilpotent_cent2 H K G : nilpotent G -> K \subset G -> H \subset G -> coprime #|K| #|H| -> H \subset 'C(K). Proof. move=> nilG sKG sHG; rewrite coprime_pi' // => p'H. have sub_Gp := sub_Hall_pcore (nilpotent_pcore_Hall _ nilG). have [_ _ cGpp' _] := dprodP (nilpotent_pcoreC \pi(K) nilG). by apply: centSS cGpp'; rewrite sub_Gp ?pgroup_pi. Qed. Lemma pi_center_nilpotent G : nilpotent G -> \pi('Z(G)) = \pi(G). Proof. move=> nilG; apply/eq_piP => /= p. apply/idP/idP=> [|pG]; first exact: (piSg (center_sub _)). move: (pG); rewrite !mem_primes !cardG_gt0; case/andP=> p_pr _. pose Z := 'O_p(G) :&: 'Z(G); have ntZ: Z != 1. rewrite meet_center_nil ?pcore_normal // trivg_card_le1 -ltnNge. rewrite (card_Hall (nilpotent_pcore_Hall p nilG)) p_part. by rewrite (ltn_exp2l 0 _ (prime_gt1 p_pr)) logn_gt0. have pZ: p.-group Z := pgroupS (subsetIl _ _) (pcore_pgroup _ _). have{ntZ pZ} [_ pZ _] := pgroup_pdiv pZ ntZ. by rewrite p_pr (dvdn_trans pZ) // cardSg ?subsetIr. Qed. Lemma Sylow_subnorm p G P : p.-Sylow('N_G(P)) P = p.-Sylow(G) P. Proof. apply/idP/idP=> sylP; last first. apply: pHall_subl (subsetIl _ _) (sylP). by rewrite subsetI normG (pHall_sub sylP). have [/subsetIP[sPG sPN] pP _] := and3P sylP. have [Q sylQ sPQ] := Sylow_superset sPG pP; have [sQG pQ _] := and3P sylQ. rewrite -(nilpotent_sub_norm (pgroup_nil pQ) sPQ) {sylQ}//. rewrite subEproper eq_sym eqEcard subsetI sPQ sPN dvdn_leq //. rewrite -(part_pnat_id (pgroupS (subsetIl _ _) pQ)) (card_Hall sylP). by rewrite partn_dvd // cardSg ?setSI. Qed. End Nilpotent. Lemma nil_class_pgroup (gT : finGroupType) (p : nat) (P : {group gT}) : p.-group P -> nil_class P <= maxn 1 (logn p #|P|).-1. Proof. move=> pP; move def_c: (nil_class P) => c. elim: c => // c IHc in gT P def_c pP *; set e := logn p _. have nilP := pgroup_nil pP; have sZP := center_sub P. have [e_le2 | e_gt2] := leqP e 2. by rewrite -def_c leq_max nil_class1 (p2group_abelian pP). have pPq: p.-group (P / 'Z(P)) by apply: quotient_pgroup. rewrite -(subnKC e_gt2) ltnS (leq_trans (IHc _ _ _ pPq)) //. by rewrite nil_class_quotient_center ?def_c. rewrite geq_max /= -add1n -leq_subLR -subn1 -subnDA -subSS leq_sub2r //. rewrite ltn_log_quotient //= -(setIidPr sZP) meet_center_nil //. by rewrite -nil_class0 def_c. Qed. Definition Zgroup (gT : finGroupType) (A : {set gT}) := [forall (V : {group gT} | Sylow A V), cyclic V]. Section Zgroups. Variables (gT rT : finGroupType) (D : {group gT}) (f : {morphism D >-> rT}). Implicit Types G H K : {group gT}. Lemma ZgroupS G H : H \subset G -> Zgroup G -> Zgroup H. Proof. move=> sHG /forallP zgG; apply/forall_inP=> V /SylowP[p p_pr /and3P[sVH]]. case/(Sylow_superset (subset_trans sVH sHG))=> P sylP sVP _. by have:= zgG P; rewrite (p_Sylow sylP); apply: cyclicS. Qed. Lemma morphim_Zgroup G : Zgroup G -> Zgroup (f @* G). Proof. move=> zgG; wlog sGD: G zgG / G \subset D. by rewrite -morphimIdom; apply; rewrite (ZgroupS _ zgG, subsetIl) ?subsetIr. apply/forall_inP=> fV /SylowP[p pr_p sylfV]. have [P sylP] := Sylow_exists p G. have [|z _ ->] := @Sylow_trans p _ _ (f @* P)%G _ _ sylfV. by apply: morphim_pHall (sylP); apply: subset_trans (pHall_sub sylP) sGD. by rewrite cyclicJ morphim_cyclic ?(forall_inP zgG) //; apply/SylowP; exists p. Qed. Lemma nil_Zgroup_cyclic G : Zgroup G -> nilpotent G -> cyclic G. Proof. have [n] := ubnP #|G|; elim: n G => // n IHn G /ltnSE-leGn ZgG nilG. have [->|[p pr_p pG]] := trivgVpdiv G; first by rewrite -cycle1 cycle_cyclic. have /dprodP[_ defG Cpp' _] := nilpotent_pcoreC p nilG. have /cyclicP[x def_p]: cyclic 'O_p(G). have:= forallP ZgG 'O_p(G)%G. by rewrite (p_Sylow (nilpotent_pcore_Hall p nilG)). have /cyclicP[x' def_p']: cyclic 'O_p^'(G). have sp'G := pcore_sub p^' G. apply: IHn (leq_trans _ leGn) (ZgroupS sp'G _) (nilpotentS sp'G _) => //. rewrite proper_card // properEneq sp'G andbT; case: eqP => //= def_p'. by have:= pcore_pgroup p^' G; rewrite def_p' /pgroup p'natE ?pG. apply/cyclicP; exists (x * x'); rewrite -{}defG def_p def_p' cycleM //. by red; rewrite -(centsP Cpp') // (def_p, def_p') cycle_id. by rewrite /order -def_p -def_p' (@pnat_coprime p) //; apply: pcore_pgroup. Qed. End Zgroups. Arguments Zgroup {gT} A%_g. Section NilPGroups. Variables (p : nat) (gT : finGroupType). Implicit Type G P N : {group gT}. (* B & G 1.22 p.9 *) Lemma normal_pgroup r P N : p.-group P -> N <| P -> r <= logn p #|N| -> exists Q : {group gT}, [/\ Q \subset N, Q <| P & #|Q| = (p ^ r)%N]. Proof. elim: r gT P N => [|r IHr] gTr P N pP nNP le_r. by exists (1%G : {group gTr}); rewrite sub1G normal1 cards1. have [NZ_1 | ntNZ] := eqVneq (N :&: 'Z(P)) 1. by rewrite (TI_center_nil (pgroup_nil pP)) // cards1 logn1 in le_r. have: p.-group (N :&: 'Z(P)) by apply: pgroupS pP; rewrite /= setICA subsetIl. case/pgroup_pdiv=> // p_pr /Cauchy[// | z]. rewrite -cycle_subG !subsetI => /and3P[szN szP cPz] ozp _. have{cPz} nzP: P \subset 'N(<[z]>) by rewrite cents_norm // centsC. have: N / <[z]> <| P / <[z]> by rewrite morphim_normal. case/IHr=> [||Qb [sQNb nQPb]]; first exact: morphim_pgroup. rewrite card_quotient ?(subset_trans (normal_sub nNP)) // -ltnS. apply: (leq_trans le_r); rewrite -(Lagrange szN) [#|_|]ozp. by rewrite lognM // ?prime_gt0 // logn_prime ?eqxx. case/(inv_quotientN _): nQPb sQNb => [|Q -> szQ nQP]; first exact/andP. have nzQ := subset_trans (normal_sub nQP) nzP. rewrite quotientSGK // card_quotient // => sQN izQ. by exists Q; split=> //; rewrite expnS -izQ -ozp Lagrange. Qed. Theorem Baer_Suzuki x G : x \in G -> (forall y, y \in G -> p.-group <<[set x; x ^ y]>>) -> x \in 'O_p(G). Proof. have [n] := ubnP #|G|; elim: n G x => // n IHn G x /ltnSE-leGn Gx pE. set E := x ^: G; have{} pE: {in E &, forall x1 x2, p.-group <<[set x1; x2]>>}. move=> _ _ /imsetP[y1 Gy1 ->] /imsetP[y2 Gy2 ->]. rewrite -(mulgKV y1 y2) conjgM -2!conjg_set1 -conjUg genJ pgroupJ. by rewrite pE // groupMl ?groupV. have sEG: <<E>> \subset G by rewrite gen_subG class_subG. have nEG: G \subset 'N(E) by apply: class_norm. have Ex: x \in E by apply: class_refl. have [P Px sylP]: exists2 P : {group gT}, x \in P & p.-Sylow(<<E>>) P. have sxxE: <<[set x; x]>> \subset <<E>> by rewrite genS // setUid sub1set. have{sxxE} [P sylP sxxP] := Sylow_superset sxxE (pE _ _ Ex Ex). by exists P => //; rewrite (subsetP sxxP) ?mem_gen ?setU11. case sEP: (E \subset P). apply: subsetP Ex; rewrite -gen_subG; apply: pcore_max. by apply: pgroupS (pHall_pgroup sylP); rewrite gen_subG. by rewrite /normal gen_subG class_subG // norms_gen. pose P_yD D := [pred y in E :\: P | p.-group <<y |: D>>]. pose P_D := [pred D : {set gT} | D \subset P :&: E & [exists y, P_yD D y]]. have{Ex Px}: P_D [set x]. rewrite /= sub1set inE Px Ex; apply/existsP=> /=. by case/subsetPn: sEP => y Ey Py; exists y; rewrite inE Ey Py pE. case/(@maxset_exists _ P_D)=> D /maxsetP[]; rewrite {P_yD P_D}/=. rewrite subsetI sub1set -andbA => /and3P[sDP sDE /existsP[y0]]. set B := _ |: D; rewrite inE -andbA => /and3P[Py0 Ey0 pB] maxD Dx. have sDgE: D \subset <<E>> by apply: sub_gen. have sDG: D \subset G by apply: subset_trans sEG. have sBE: B \subset E by rewrite subUset sub1set Ey0. have sBG: <<B>> \subset G by apply: subset_trans (genS _) sEG. have sDB: D \subset B by rewrite subsetUr. have defD: D :=: P :&: <<B>> :&: E. apply/eqP; rewrite eqEsubset ?subsetI sDP sDE sub_gen //=. apply/setUidPl; apply: maxD; last apply: subsetUl. rewrite subUset subsetI sDP sDE setIAC subsetIl. apply/existsP; exists y0; rewrite inE Py0 Ey0 /= setUA -/B. by rewrite -[<<_>>]joing_idl joingE setKI genGid. have nDD: D \subset 'N(D). apply/subsetP=> z Dz; rewrite inE defD. apply/subsetP=> _ /imsetP[y /setIP[PBy Ey] ->]. rewrite inE groupJ // ?inE ?(subsetP sDP) ?mem_gen ?setU1r //= memJ_norm //. exact: (subsetP (subset_trans sDG nEG)). case nDG: (G \subset 'N(D)). apply: subsetP Dx; rewrite -gen_subG pcore_max ?(pgroupS (genS _) pB) //. by rewrite /normal gen_subG sDG norms_gen. have{n leGn IHn nDG} pN: p.-group <<'N_E(D)>>. apply: pgroupS (pcore_pgroup p 'N_G(D)); rewrite gen_subG /=. apply/subsetP=> x1 /setIP[Ex1 Nx1]; apply: IHn => [||y Ny]. - apply: leq_trans leGn; rewrite proper_card // /proper subsetIl. by rewrite subsetI nDG andbF. - by rewrite inE Nx1 (subsetP sEG) ?mem_gen. have Ex1y: x1 ^ y \in E. by rewrite -mem_conjgV (normsP nEG) // groupV; case/setIP: Ny. by apply: pgroupS (genS _) (pE _ _ Ex1 Ex1y); apply/subsetP => u /[!inE]. have [y1 Ny1 Py1]: exists2 y1, y1 \in 'N_E(D) & y1 \notin P. case sNN: ('N_<<B>>('N_<<B>>(D)) \subset 'N_<<B>>(D)). exists y0 => //; have By0: y0 \in <<B>> by rewrite mem_gen ?setU11. rewrite inE Ey0 -By0 -in_setI. by rewrite -['N__(D)](nilpotent_sub_norm (pgroup_nil pB)) ?subsetIl. case/subsetPn: sNN => z /setIP[Bz NNz]; rewrite inE Bz inE. case/subsetPn=> y; rewrite mem_conjg => Dzy Dy. have:= Dzy; rewrite {1}defD; do 2![case/setIP]=> _ Bzy Ezy. have Ey: y \in E by rewrite -(normsP nEG _ (subsetP sBG z Bz)) mem_conjg. have /setIP[By Ny]: y \in 'N_<<B>>(D). by rewrite -(normP NNz) mem_conjg inE Bzy ?(subsetP nDD). exists y; first by rewrite inE Ey. by rewrite defD 2!inE Ey By !andbT in Dy. have [y2 Ny2 Dy2]: exists2 y2, y2 \in 'N_(P :&: E)(D) & y2 \notin D. case sNN: ('N_P('N_P(D)) \subset 'N_P(D)). have [z /= Ez sEzP] := Sylow_Jsub sylP (genS sBE) pB. have Gz: z \in G by apply: subsetP Ez. have /subsetPn[y Bzy Dy]: ~~ (B :^ z \subset D). apply/negP; move/subset_leq_card; rewrite cardJg cardsU1. by rewrite {1}defD 2!inE (negPf Py0) ltnn. exists y => //; apply: subsetP Bzy. rewrite -setIA setICA subsetI sub_conjg (normsP nEG) ?groupV // sBE. have nilP := pgroup_nil (pHall_pgroup sylP). by rewrite -['N__(_)](nilpotent_sub_norm nilP) ?subsetIl // -gen_subG genJ. case/subsetPn: sNN => z /setIP[Pz NNz]; rewrite 2!inE Pz. case/subsetPn=> y Dzy Dy; exists y => //; apply: subsetP Dzy. rewrite -setIA setICA subsetI sub_conjg (normsP nEG) ?groupV //. by rewrite sDE -(normP NNz); rewrite conjSg subsetI sDP. by apply: subsetP Pz; apply: (subset_trans (pHall_sub sylP)). suff{Dy2} Dy2D: y2 |: D = D by rewrite -Dy2D setU11 in Dy2. apply: maxD; last by rewrite subsetUr. case/setIP: Ny2 => PEy2 Ny2; case/setIP: Ny1 => Ey1 Ny1. rewrite subUset sub1set PEy2 subsetI sDP sDE. apply/existsP; exists y1; rewrite inE Ey1 Py1; apply: pgroupS pN. rewrite genS // !subUset !sub1set !in_setI Ey1 Ny1. by case/setIP: PEy2 => _ ->; rewrite Ny2 subsetI sDE. Qed. End NilPGroups.
Lipschitz.lean
/- Copyright (c) 2018 Rohan Mitta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov, Winston Yin -/ import Mathlib.Algebra.Group.End import Mathlib.Tactic.Finiteness import Mathlib.Topology.EMetricSpace.Diam /-! # Lipschitz continuous functions A map `f : α → β` between two (extended) metric spaces is called *Lipschitz continuous* with constant `K ≥ 0` if for all `x, y` we have `edist (f x) (f y) ≤ K * edist x y`. For a metric space, the latter inequality is equivalent to `dist (f x) (f y) ≤ K * dist x y`. There is also a version asserting this inequality only for `x` and `y` in some set `s`. Finally, `f : α → β` is called *locally Lipschitz continuous* if each `x : α` has a neighbourhood on which `f` is Lipschitz continuous (with some constant). In this file we provide various ways to prove that various combinations of Lipschitz continuous functions are Lipschitz continuous. We also prove that Lipschitz continuous functions are uniformly continuous, and that locally Lipschitz functions are continuous. ## Main definitions and lemmas * `LipschitzWith K f`: states that `f` is Lipschitz with constant `K : ℝ≥0` * `LipschitzOnWith K f s`: states that `f` is Lipschitz with constant `K : ℝ≥0` on a set `s` * `LipschitzWith.uniformContinuous`: a Lipschitz function is uniformly continuous * `LipschitzOnWith.uniformContinuousOn`: a function which is Lipschitz on a set `s` is uniformly continuous on `s`. * `LocallyLipschitz f`: states that `f` is locally Lipschitz * `LocallyLipschitzOn f s`: states that `f` is locally Lipschitz on `s`. * `LocallyLipschitz.continuous`: a locally Lipschitz function is continuous. ## Implementation notes The parameter `K` has type `ℝ≥0`. This way we avoid conjunction in the definition and have coercions both to `ℝ` and `ℝ≥0∞`. Constructors whose names end with `'` take `K : ℝ` as an argument, and return `LipschitzWith (Real.toNNReal K) f`. -/ universe u v w x open Filter Function Set Topology NNReal ENNReal Bornology variable {α : Type u} {β : Type v} {γ : Type w} {ι : Type x} section PseudoEMetricSpace variable [PseudoEMetricSpace α] [PseudoEMetricSpace β] {K : ℝ≥0} {s t : Set α} {f : α → β} /-- A function `f` is **Lipschitz continuous** with constant `K ≥ 0` if for all `x, y` we have `dist (f x) (f y) ≤ K * dist x y`. -/ def LipschitzWith (K : ℝ≥0) (f : α → β) := ∀ x y, edist (f x) (f y) ≤ K * edist x y /-- A function `f` is **Lipschitz continuous** with constant `K ≥ 0` **on `s`** if for all `x, y` in `s` we have `dist (f x) (f y) ≤ K * dist x y`. -/ def LipschitzOnWith (K : ℝ≥0) (f : α → β) (s : Set α) := ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → edist (f x) (f y) ≤ K * edist x y /-- `f : α → β` is called **locally Lipschitz continuous** iff every point `x` has a neighbourhood on which `f` is Lipschitz. -/ def LocallyLipschitz (f : α → β) : Prop := ∀ x, ∃ K, ∃ t ∈ 𝓝 x, LipschitzOnWith K f t /-- `f : α → β` is called **locally Lipschitz continuous** on `s` iff every point `x` of `s` has a neighbourhood within `s` on which `f` is Lipschitz. -/ def LocallyLipschitzOn (s : Set α) (f : α → β) : Prop := ∀ ⦃x⦄, x ∈ s → ∃ K, ∃ t ∈ 𝓝[s] x, LipschitzOnWith K f t /-- Every function is Lipschitz on the empty set (with any Lipschitz constant). -/ @[simp] theorem lipschitzOnWith_empty (K : ℝ≥0) (f : α → β) : LipschitzOnWith K f ∅ := fun _ => False.elim @[simp] lemma locallyLipschitzOn_empty (f : α → β) : LocallyLipschitzOn ∅ f := fun _ ↦ False.elim /-- Being Lipschitz on a set is monotone w.r.t. that set. -/ theorem LipschitzOnWith.mono (hf : LipschitzOnWith K f t) (h : s ⊆ t) : LipschitzOnWith K f s := fun _x x_in _y y_in => hf (h x_in) (h y_in) lemma LocallyLipschitzOn.mono (hf : LocallyLipschitzOn t f) (h : s ⊆ t) : LocallyLipschitzOn s f := fun x hx ↦ by obtain ⟨K, u, hu, hfu⟩ := hf (h hx); exact ⟨K, u, nhdsWithin_mono _ h hu, hfu⟩ /-- `f` is Lipschitz iff it is Lipschitz on the entire space. -/ @[simp] lemma lipschitzOnWith_univ : LipschitzOnWith K f univ ↔ LipschitzWith K f := by simp [LipschitzOnWith, LipschitzWith] @[simp] lemma locallyLipschitzOn_univ : LocallyLipschitzOn univ f ↔ LocallyLipschitz f := by simp [LocallyLipschitzOn, LocallyLipschitz] protected lemma LocallyLipschitz.locallyLipschitzOn (h : LocallyLipschitz f) : LocallyLipschitzOn s f := (locallyLipschitzOn_univ.2 h).mono s.subset_univ theorem lipschitzOnWith_iff_restrict : LipschitzOnWith K f s ↔ LipschitzWith K (s.restrict f) := by simp [LipschitzOnWith, LipschitzWith] lemma lipschitzOnWith_restrict {t : Set s} : LipschitzOnWith K (s.restrict f) t ↔ LipschitzOnWith K f (s ∩ Subtype.val '' t) := by simp [LipschitzOnWith] lemma locallyLipschitzOn_iff_restrict : LocallyLipschitzOn s f ↔ LocallyLipschitz (s.restrict f) := by simp only [LocallyLipschitzOn, LocallyLipschitz, SetCoe.forall', lipschitzOnWith_restrict, nhds_subtype_eq_comap_nhdsWithin, mem_comap] congr! with x K constructor · rintro ⟨t, ht, hft⟩ exact ⟨_, ⟨t, ht, Subset.rfl⟩, hft.mono <| inter_subset_right.trans <| image_preimage_subset ..⟩ · rintro ⟨t, ⟨u, hu, hut⟩, hft⟩ exact ⟨s ∩ u, Filter.inter_mem self_mem_nhdsWithin hu, hft.mono fun x hx ↦ ⟨hx.1, ⟨x, hx.1⟩, hut hx.2, rfl⟩⟩ alias ⟨LipschitzOnWith.to_restrict, _⟩ := lipschitzOnWith_iff_restrict alias ⟨LocallyLipschitzOn.restrict, _⟩ := locallyLipschitzOn_iff_restrict lemma Set.MapsTo.lipschitzOnWith_iff_restrict {t : Set β} (h : MapsTo f s t) : LipschitzOnWith K f s ↔ LipschitzWith K (h.restrict f s t) := _root_.lipschitzOnWith_iff_restrict alias ⟨LipschitzOnWith.to_restrict_mapsTo, _⟩ := Set.MapsTo.lipschitzOnWith_iff_restrict end PseudoEMetricSpace namespace LipschitzWith open EMetric variable [PseudoEMetricSpace α] [PseudoEMetricSpace β] [PseudoEMetricSpace γ] variable {K : ℝ≥0} {f : α → β} {x y : α} {r : ℝ≥0∞} {s : Set α} protected theorem lipschitzOnWith (h : LipschitzWith K f) : LipschitzOnWith K f s := fun x _ y _ => h x y theorem edist_le_mul (h : LipschitzWith K f) (x y : α) : edist (f x) (f y) ≤ K * edist x y := h x y theorem edist_le_mul_of_le (h : LipschitzWith K f) (hr : edist x y ≤ r) : edist (f x) (f y) ≤ K * r := (h x y).trans <| mul_left_mono hr theorem edist_lt_mul_of_lt (h : LipschitzWith K f) (hK : K ≠ 0) (hr : edist x y < r) : edist (f x) (f y) < K * r := (h x y).trans_lt <| (ENNReal.mul_lt_mul_left (ENNReal.coe_ne_zero.2 hK) ENNReal.coe_ne_top).2 hr theorem mapsTo_emetric_closedBall (h : LipschitzWith K f) (x : α) (r : ℝ≥0∞) : MapsTo f (closedBall x r) (closedBall (f x) (K * r)) := fun _y hy => h.edist_le_mul_of_le hy theorem mapsTo_emetric_ball (h : LipschitzWith K f) (hK : K ≠ 0) (x : α) (r : ℝ≥0∞) : MapsTo f (ball x r) (ball (f x) (K * r)) := fun _y hy => h.edist_lt_mul_of_lt hK hy theorem edist_lt_top (hf : LipschitzWith K f) {x y : α} (h : edist x y ≠ ⊤) : edist (f x) (f y) < ⊤ := (hf x y).trans_lt (by finiteness) theorem mul_edist_le (h : LipschitzWith K f) (x y : α) : (K⁻¹ : ℝ≥0∞) * edist (f x) (f y) ≤ edist x y := by rw [mul_comm, ← div_eq_mul_inv] exact ENNReal.div_le_of_le_mul' (h x y) protected theorem of_edist_le (h : ∀ x y, edist (f x) (f y) ≤ edist x y) : LipschitzWith 1 f := fun x y => by simp only [ENNReal.coe_one, one_mul, h] protected theorem weaken (hf : LipschitzWith K f) {K' : ℝ≥0} (h : K ≤ K') : LipschitzWith K' f := fun x y => le_trans (hf x y) <| mul_right_mono (ENNReal.coe_le_coe.2 h) theorem ediam_image_le (hf : LipschitzWith K f) (s : Set α) : EMetric.diam (f '' s) ≤ K * EMetric.diam s := by apply EMetric.diam_le rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ exact hf.edist_le_mul_of_le (EMetric.edist_le_diam_of_mem hx hy) theorem edist_lt_of_edist_lt_div (hf : LipschitzWith K f) {x y : α} {d : ℝ≥0∞} (h : edist x y < d / K) : edist (f x) (f y) < d := calc edist (f x) (f y) ≤ K * edist x y := hf x y _ < d := ENNReal.mul_lt_of_lt_div' h /-- A Lipschitz function is uniformly continuous. -/ protected theorem uniformContinuous (hf : LipschitzWith K f) : UniformContinuous f := EMetric.uniformContinuous_iff.2 fun ε εpos => ⟨ε / K, ENNReal.div_pos_iff.2 ⟨ne_of_gt εpos, ENNReal.coe_ne_top⟩, hf.edist_lt_of_edist_lt_div⟩ /-- A Lipschitz function is continuous. -/ protected theorem continuous (hf : LipschitzWith K f) : Continuous f := hf.uniformContinuous.continuous /-- Constant functions are Lipschitz (with any constant). -/ protected theorem const (b : β) : LipschitzWith 0 fun _ : α => b := fun x y => by simp only [edist_self, zero_le] protected theorem const' (b : β) {K : ℝ≥0} : LipschitzWith K fun _ : α => b := fun x y => by simp only [edist_self, zero_le] /-- The identity is 1-Lipschitz. -/ protected theorem id : LipschitzWith 1 (@id α) := LipschitzWith.of_edist_le fun _ _ => le_rfl /-- The inclusion of a subset is 1-Lipschitz. -/ protected theorem subtype_val (s : Set α) : LipschitzWith 1 (Subtype.val : s → α) := LipschitzWith.of_edist_le fun _ _ => le_rfl theorem subtype_mk (hf : LipschitzWith K f) {p : β → Prop} (hp : ∀ x, p (f x)) : LipschitzWith K (fun x => ⟨f x, hp x⟩ : α → { y // p y }) := hf protected theorem eval {α : ι → Type u} [∀ i, PseudoEMetricSpace (α i)] [Fintype ι] (i : ι) : LipschitzWith 1 (Function.eval i : (∀ i, α i) → α i) := LipschitzWith.of_edist_le fun f g => by convert edist_le_pi_edist f g i /-- The restriction of a `K`-Lipschitz function is `K`-Lipschitz. -/ protected theorem restrict (hf : LipschitzWith K f) (s : Set α) : LipschitzWith K (s.restrict f) := fun x y => hf x y /-- The composition of Lipschitz functions is Lipschitz. -/ protected theorem comp {Kf Kg : ℝ≥0} {f : β → γ} {g : α → β} (hf : LipschitzWith Kf f) (hg : LipschitzWith Kg g) : LipschitzWith (Kf * Kg) (f ∘ g) := fun x y => calc edist (f (g x)) (f (g y)) ≤ Kf * edist (g x) (g y) := hf _ _ _ ≤ Kf * (Kg * edist x y) := mul_left_mono (hg _ _) _ = (Kf * Kg : ℝ≥0) * edist x y := by rw [← mul_assoc, ENNReal.coe_mul] theorem comp_lipschitzOnWith {Kf Kg : ℝ≥0} {f : β → γ} {g : α → β} {s : Set α} (hf : LipschitzWith Kf f) (hg : LipschitzOnWith Kg g s) : LipschitzOnWith (Kf * Kg) (f ∘ g) s := lipschitzOnWith_iff_restrict.mpr <| hf.comp hg.to_restrict protected theorem prod_fst : LipschitzWith 1 (@Prod.fst α β) := LipschitzWith.of_edist_le fun _ _ => le_max_left _ _ protected theorem prod_snd : LipschitzWith 1 (@Prod.snd α β) := LipschitzWith.of_edist_le fun _ _ => le_max_right _ _ /-- If `f` and `g` are Lipschitz functions, so is the induced map `f × g` to the product type. -/ protected theorem prodMk {f : α → β} {Kf : ℝ≥0} (hf : LipschitzWith Kf f) {g : α → γ} {Kg : ℝ≥0} (hg : LipschitzWith Kg g) : LipschitzWith (max Kf Kg) fun x => (f x, g x) := by intro x y rw [ENNReal.coe_mono.map_max, Prod.edist_eq, max_mul] exact max_le_max (hf x y) (hg x y) @[deprecated (since := "2025-03-10")] protected alias prod := LipschitzWith.prodMk protected theorem prodMk_left (a : α) : LipschitzWith 1 (Prod.mk a : β → α × β) := by simpa only [max_eq_right zero_le_one] using (LipschitzWith.const a).prodMk LipschitzWith.id @[deprecated (since := "2025-03-10")] protected alias prod_mk_left := LipschitzWith.prodMk_left protected theorem prodMk_right (b : β) : LipschitzWith 1 fun a : α => (a, b) := by simpa only [max_eq_left zero_le_one] using LipschitzWith.id.prodMk (LipschitzWith.const b) @[deprecated (since := "2025-03-10")] protected alias prod_mk_right := LipschitzWith.prodMk_right protected theorem uncurry {f : α → β → γ} {Kα Kβ : ℝ≥0} (hα : ∀ b, LipschitzWith Kα fun a => f a b) (hβ : ∀ a, LipschitzWith Kβ (f a)) : LipschitzWith (Kα + Kβ) (Function.uncurry f) := by rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ simp only [Function.uncurry, ENNReal.coe_add, add_mul] apply le_trans (edist_triangle _ (f a₂ b₁) _) exact add_le_add (le_trans (hα _ _ _) <| mul_left_mono <| le_max_left _ _) (le_trans (hβ _ _ _) <| mul_left_mono <| le_max_right _ _) /-- Iterates of a Lipschitz function are Lipschitz. -/ protected theorem iterate {f : α → α} (hf : LipschitzWith K f) : ∀ n, LipschitzWith (K ^ n) f^[n] | 0 => by simpa only [pow_zero] using LipschitzWith.id | n + 1 => by rw [pow_succ]; exact (LipschitzWith.iterate hf n).comp hf theorem edist_iterate_succ_le_geometric {f : α → α} (hf : LipschitzWith K f) (x n) : edist (f^[n] x) (f^[n+1] x) ≤ edist x (f x) * (K : ℝ≥0∞) ^ n := by rw [iterate_succ, mul_comm] simpa only [ENNReal.coe_pow] using (hf.iterate n) x (f x) protected theorem mul_end {f g : Function.End α} {Kf Kg} (hf : LipschitzWith Kf f) (hg : LipschitzWith Kg g) : LipschitzWith (Kf * Kg) (f * g : Function.End α) := hf.comp hg /-- The product of a list of Lipschitz continuous endomorphisms is a Lipschitz continuous endomorphism. -/ protected theorem list_prod (f : ι → Function.End α) (K : ι → ℝ≥0) (h : ∀ i, LipschitzWith (K i) (f i)) : ∀ l : List ι, LipschitzWith (l.map K).prod (l.map f).prod | [] => by simpa using LipschitzWith.id | i::l => by simp only [List.map_cons, List.prod_cons] exact (h i).mul_end (LipschitzWith.list_prod f K h l) protected theorem pow_end {f : Function.End α} {K} (h : LipschitzWith K f) : ∀ n : ℕ, LipschitzWith (K ^ n) (f ^ n : Function.End α) | 0 => by simpa only [pow_zero] using LipschitzWith.id | n + 1 => by rw [pow_succ, pow_succ] exact (LipschitzWith.pow_end h n).mul_end h end LipschitzWith namespace LipschitzOnWith variable [PseudoEMetricSpace α] [PseudoEMetricSpace β] [PseudoEMetricSpace γ] variable {K : ℝ≥0} {s : Set α} {f : α → β} protected theorem uniformContinuousOn (hf : LipschitzOnWith K f s) : UniformContinuousOn f s := uniformContinuousOn_iff_restrict.mpr hf.to_restrict.uniformContinuous protected theorem continuousOn (hf : LipschitzOnWith K f s) : ContinuousOn f s := hf.uniformContinuousOn.continuousOn theorem edist_le_mul_of_le (h : LipschitzOnWith K f s) {x y : α} (hx : x ∈ s) (hy : y ∈ s) {r : ℝ≥0∞} (hr : edist x y ≤ r) : edist (f x) (f y) ≤ K * r := (h hx hy).trans <| mul_left_mono hr theorem edist_lt_of_edist_lt_div (hf : LipschitzOnWith K f s) {x y : α} (hx : x ∈ s) (hy : y ∈ s) {d : ℝ≥0∞} (hd : edist x y < d / K) : edist (f x) (f y) < d := hf.to_restrict.edist_lt_of_edist_lt_div <| show edist (⟨x, hx⟩ : s) ⟨y, hy⟩ < d / K from hd protected theorem comp {g : β → γ} {t : Set β} {Kg : ℝ≥0} (hg : LipschitzOnWith Kg g t) (hf : LipschitzOnWith K f s) (hmaps : MapsTo f s t) : LipschitzOnWith (Kg * K) (g ∘ f) s := lipschitzOnWith_iff_restrict.mpr <| hg.to_restrict.comp (hf.to_restrict_mapsTo hmaps) /-- If `f` and `g` are Lipschitz on `s`, so is the induced map `f × g` to the product type. -/ protected theorem prodMk {g : α → γ} {Kf Kg : ℝ≥0} (hf : LipschitzOnWith Kf f s) (hg : LipschitzOnWith Kg g s) : LipschitzOnWith (max Kf Kg) (fun x => (f x, g x)) s := by intro _ hx _ hy rw [ENNReal.coe_mono.map_max, Prod.edist_eq, max_mul] exact max_le_max (hf hx hy) (hg hx hy) @[deprecated (since := "2025-03-10")] protected alias prod := LipschitzOnWith.prodMk theorem ediam_image2_le (f : α → β → γ) {K₁ K₂ : ℝ≥0} (s : Set α) (t : Set β) (hf₁ : ∀ b ∈ t, LipschitzOnWith K₁ (f · b) s) (hf₂ : ∀ a ∈ s, LipschitzOnWith K₂ (f a) t) : EMetric.diam (Set.image2 f s t) ≤ ↑K₁ * EMetric.diam s + ↑K₂ * EMetric.diam t := by simp only [EMetric.diam_le_iff, forall_mem_image2] intro a₁ ha₁ b₁ hb₁ a₂ ha₂ b₂ hb₂ refine (edist_triangle _ (f a₂ b₁) _).trans ?_ exact add_le_add ((hf₁ b₁ hb₁ ha₁ ha₂).trans <| mul_left_mono <| EMetric.edist_le_diam_of_mem ha₁ ha₂) ((hf₂ a₂ ha₂ hb₁ hb₂).trans <| mul_left_mono <| EMetric.edist_le_diam_of_mem hb₁ hb₂) end LipschitzOnWith namespace LocallyLipschitz variable [PseudoEMetricSpace α] [PseudoEMetricSpace β] [PseudoEMetricSpace γ] {f : α → β} /-- A Lipschitz function is locally Lipschitz. -/ protected lemma _root_.LipschitzWith.locallyLipschitz {K : ℝ≥0} (hf : LipschitzWith K f) : LocallyLipschitz f := fun _ ↦ ⟨K, univ, Filter.univ_mem, lipschitzOnWith_univ.mpr hf⟩ /-- The identity function is locally Lipschitz. -/ protected lemma id : LocallyLipschitz (@id α) := LipschitzWith.id.locallyLipschitz /-- Constant functions are locally Lipschitz. -/ protected lemma const (b : β) : LocallyLipschitz (fun _ : α ↦ b) := (LipschitzWith.const b).locallyLipschitz /-- A locally Lipschitz function is continuous. (The converse is false: for example, $x ↦ \sqrt{x}$ is continuous, but not locally Lipschitz at 0.) -/ protected theorem continuous {f : α → β} (hf : LocallyLipschitz f) : Continuous f := by rw [continuous_iff_continuousAt] intro x rcases (hf x) with ⟨K, t, ht, hK⟩ exact (hK.continuousOn).continuousAt ht /-- The composition of locally Lipschitz functions is locally Lipschitz. -/ protected lemma comp {f : β → γ} {g : α → β} (hf : LocallyLipschitz f) (hg : LocallyLipschitz g) : LocallyLipschitz (f ∘ g) := by intro x -- g is Lipschitz on t ∋ x, f is Lipschitz on u ∋ g(x) rcases hg x with ⟨Kg, t, ht, hgL⟩ rcases hf (g x) with ⟨Kf, u, hu, hfL⟩ refine ⟨Kf * Kg, t ∩ g⁻¹' u, inter_mem ht (hg.continuous.continuousAt hu), ?_⟩ exact hfL.comp (hgL.mono inter_subset_left) ((mapsTo_preimage g u).mono_left inter_subset_right) /-- If `f` and `g` are locally Lipschitz, so is the induced map `f × g` to the product type. -/ protected lemma prodMk {f : α → β} (hf : LocallyLipschitz f) {g : α → γ} (hg : LocallyLipschitz g) : LocallyLipschitz fun x => (f x, g x) := by intro x rcases hf x with ⟨Kf, t₁, h₁t, hfL⟩ rcases hg x with ⟨Kg, t₂, h₂t, hgL⟩ refine ⟨max Kf Kg, t₁ ∩ t₂, Filter.inter_mem h₁t h₂t, ?_⟩ exact (hfL.mono inter_subset_left).prodMk (hgL.mono inter_subset_right) @[deprecated (since := "2025-03-10")] protected alias prod := LocallyLipschitz.prodMk protected theorem prodMk_left (a : α) : LocallyLipschitz (Prod.mk a : β → α × β) := (LipschitzWith.prodMk_left a).locallyLipschitz @[deprecated (since := "2025-03-10")] protected alias prod_mk_left := LocallyLipschitz.prodMk_left protected theorem prodMk_right (b : β) : LocallyLipschitz (fun a : α => (a, b)) := (LipschitzWith.prodMk_right b).locallyLipschitz @[deprecated (since := "2025-03-10")] protected alias prod_mk_right := LocallyLipschitz.prodMk_right protected theorem iterate {f : α → α} (hf : LocallyLipschitz f) : ∀ n, LocallyLipschitz f^[n] | 0 => by simpa only [pow_zero] using LocallyLipschitz.id | n + 1 => by rw [iterate_add, iterate_one]; exact (hf.iterate n).comp hf protected theorem mul_end {f g : Function.End α} (hf : LocallyLipschitz f) (hg : LocallyLipschitz g) : LocallyLipschitz (f * g : Function.End α) := hf.comp hg protected theorem pow_end {f : Function.End α} (h : LocallyLipschitz f) : ∀ n : ℕ, LocallyLipschitz (f ^ n : Function.End α) | 0 => by simpa only [pow_zero] using LocallyLipschitz.id | n + 1 => by rw [pow_succ] exact (h.pow_end n).mul_end h end LocallyLipschitz namespace LocallyLipschitzOn variable [PseudoEMetricSpace α] [PseudoEMetricSpace β] {f : α → β} {s : Set α} protected lemma continuousOn (hf : LocallyLipschitzOn s f) : ContinuousOn f s := continuousOn_iff_continuous_restrict.2 hf.restrict.continuous end LocallyLipschitzOn /-- Consider a function `f : α × β → γ`. Suppose that it is continuous on each “vertical fiber” `{a} × t`, `a ∈ s`, and is Lipschitz continuous on each “horizontal fiber” `s × {b}`, `b ∈ t` with the same Lipschitz constant `K`. Then it is continuous on `s × t`. Moreover, it suffices to require continuity on vertical fibers for `a` from a subset `s' ⊆ s` that is dense in `s`. The actual statement uses (Lipschitz) continuity of `fun y ↦ f (a, y)` and `fun x ↦ f (x, b)` instead of continuity of `f` on subsets of the product space. -/ theorem continuousOn_prod_of_subset_closure_continuousOn_lipschitzOnWith [PseudoEMetricSpace α] [TopologicalSpace β] [PseudoEMetricSpace γ] (f : α × β → γ) {s s' : Set α} {t : Set β} (hs' : s' ⊆ s) (hss' : s ⊆ closure s') (K : ℝ≥0) (ha : ∀ a ∈ s', ContinuousOn (fun y => f (a, y)) t) (hb : ∀ b ∈ t, LipschitzOnWith K (fun x => f (x, b)) s) : ContinuousOn f (s ×ˢ t) := by rintro ⟨x, y⟩ ⟨hx : x ∈ s, hy : y ∈ t⟩ refine EMetric.nhds_basis_closed_eball.tendsto_right_iff.2 fun ε (ε0 : 0 < ε) => ?_ replace ε0 : 0 < ε / 2 := ENNReal.half_pos ε0.ne' obtain ⟨δ, δpos, hδ⟩ : ∃ δ : ℝ≥0, 0 < δ ∧ (δ : ℝ≥0∞) * ↑(3 * K) < ε / 2 := ENNReal.exists_nnreal_pos_mul_lt ENNReal.coe_ne_top ε0.ne' rw [← ENNReal.coe_pos] at δpos rcases EMetric.mem_closure_iff.1 (hss' hx) δ δpos with ⟨x', hx', hxx'⟩ have A : s ∩ EMetric.ball x δ ∈ 𝓝[s] x := inter_mem_nhdsWithin _ (EMetric.ball_mem_nhds _ δpos) have B : t ∩ { b | edist (f (x', b)) (f (x', y)) ≤ ε / 2 } ∈ 𝓝[t] y := inter_mem self_mem_nhdsWithin (ha x' hx' y hy (EMetric.closedBall_mem_nhds (f (x', y)) ε0)) filter_upwards [nhdsWithin_prod A B] with ⟨a, b⟩ ⟨⟨has, hax⟩, ⟨hbt, hby⟩⟩ calc edist (f (a, b)) (f (x, y)) ≤ edist (f (a, b)) (f (x', b)) + edist (f (x', b)) (f (x', y)) + edist (f (x', y)) (f (x, y)) := edist_triangle4 _ _ _ _ _ ≤ K * (δ + δ) + ε / 2 + K * δ := by gcongr · refine (hb b hbt).edist_le_mul_of_le has (hs' hx') ?_ exact (edist_triangle _ _ _).trans (add_le_add (le_of_lt hax) hxx'.le) · exact hby · exact (hb y hy).edist_le_mul_of_le (hs' hx') hx ((edist_comm _ _).trans_le hxx'.le) _ = δ * ↑(3 * K) + ε / 2 := by push_cast; ring _ ≤ ε / 2 + ε / 2 := by gcongr _ = ε := ENNReal.add_halves _ /-- Consider a function `f : α × β → γ`. Suppose that it is continuous on each “vertical fiber” `{a} × t`, `a ∈ s`, and is Lipschitz continuous on each “horizontal fiber” `s × {b}`, `b ∈ t` with the same Lipschitz constant `K`. Then it is continuous on `s × t`. The actual statement uses (Lipschitz) continuity of `fun y ↦ f (a, y)` and `fun x ↦ f (x, b)` instead of continuity of `f` on subsets of the product space. -/ theorem continuousOn_prod_of_continuousOn_lipschitzOnWith [PseudoEMetricSpace α] [TopologicalSpace β] [PseudoEMetricSpace γ] (f : α × β → γ) {s : Set α} {t : Set β} (K : ℝ≥0) (ha : ∀ a ∈ s, ContinuousOn (fun y => f (a, y)) t) (hb : ∀ b ∈ t, LipschitzOnWith K (fun x => f (x, b)) s) : ContinuousOn f (s ×ˢ t) := continuousOn_prod_of_subset_closure_continuousOn_lipschitzOnWith f Subset.rfl subset_closure K ha hb /-- Consider a function `f : α × β → γ`. Suppose that it is continuous on each “vertical section” `{a} × univ` for `a : α` from a dense set. Suppose that it is Lipschitz continuous on each “horizontal section” `univ × {b}`, `b : β` with the same Lipschitz constant `K`. Then it is continuous. The actual statement uses (Lipschitz) continuity of `fun y ↦ f (a, y)` and `fun x ↦ f (x, b)` instead of continuity of `f` on subsets of the product space. -/ theorem continuous_prod_of_dense_continuous_lipschitzWith [PseudoEMetricSpace α] [TopologicalSpace β] [PseudoEMetricSpace γ] (f : α × β → γ) (K : ℝ≥0) {s : Set α} (hs : Dense s) (ha : ∀ a ∈ s, Continuous fun y => f (a, y)) (hb : ∀ b, LipschitzWith K fun x => f (x, b)) : Continuous f := by simp only [← continuousOn_univ, ← univ_prod_univ, ← lipschitzOnWith_univ] at * exact continuousOn_prod_of_subset_closure_continuousOn_lipschitzOnWith f (subset_univ _) hs.closure_eq.ge K ha fun b _ => hb b /-- Consider a function `f : α × β → γ`. Suppose that it is continuous on each “vertical section” `{a} × univ`, `a : α`, and is Lipschitz continuous on each “horizontal section” `univ × {b}`, `b : β` with the same Lipschitz constant `K`. Then it is continuous. The actual statement uses (Lipschitz) continuity of `fun y ↦ f (a, y)` and `fun x ↦ f (x, b)` instead of continuity of `f` on subsets of the product space. -/ theorem continuous_prod_of_continuous_lipschitzWith [PseudoEMetricSpace α] [TopologicalSpace β] [PseudoEMetricSpace γ] (f : α × β → γ) (K : ℝ≥0) (ha : ∀ a, Continuous fun y => f (a, y)) (hb : ∀ b, LipschitzWith K fun x => f (x, b)) : Continuous f := continuous_prod_of_dense_continuous_lipschitzWith f K dense_univ (fun _ _ ↦ ha _) hb theorem continuousOn_prod_of_subset_closure_continuousOn_lipschitzOnWith' [TopologicalSpace α] [PseudoEMetricSpace β] [PseudoEMetricSpace γ] (f : α × β → γ) {s : Set α} {t t' : Set β} (ht' : t' ⊆ t) (htt' : t ⊆ closure t') (K : ℝ≥0) (ha : ∀ a ∈ s, LipschitzOnWith K (fun y => f (a, y)) t) (hb : ∀ b ∈ t', ContinuousOn (fun x => f (x, b)) s) : ContinuousOn f (s ×ˢ t) := have : ContinuousOn (f ∘ Prod.swap) (t ×ˢ s) := continuousOn_prod_of_subset_closure_continuousOn_lipschitzOnWith _ ht' htt' K hb ha this.comp continuous_swap.continuousOn (mapsTo_swap_prod _ _) theorem continuousOn_prod_of_continuousOn_lipschitzOnWith' [TopologicalSpace α] [PseudoEMetricSpace β] [PseudoEMetricSpace γ] (f : α × β → γ) {s : Set α} {t : Set β} (K : ℝ≥0) (ha : ∀ a ∈ s, LipschitzOnWith K (fun y => f (a, y)) t) (hb : ∀ b ∈ t, ContinuousOn (fun x => f (x, b)) s) : ContinuousOn f (s ×ˢ t) := have : ContinuousOn (f ∘ Prod.swap) (t ×ˢ s) := continuousOn_prod_of_continuousOn_lipschitzOnWith _ K hb ha this.comp continuous_swap.continuousOn (mapsTo_swap_prod _ _) theorem continuous_prod_of_dense_continuous_lipschitzWith' [TopologicalSpace α] [PseudoEMetricSpace β] [PseudoEMetricSpace γ] (f : α × β → γ) (K : ℝ≥0) {t : Set β} (ht : Dense t) (ha : ∀ a, LipschitzWith K fun y => f (a, y)) (hb : ∀ b ∈ t, Continuous fun x => f (x, b)) : Continuous f := have : Continuous (f ∘ Prod.swap) := continuous_prod_of_dense_continuous_lipschitzWith _ K ht hb ha this.comp continuous_swap theorem continuous_prod_of_continuous_lipschitzWith' [TopologicalSpace α] [PseudoEMetricSpace β] [PseudoEMetricSpace γ] (f : α × β → γ) (K : ℝ≥0) (ha : ∀ a, LipschitzWith K fun y => f (a, y)) (hb : ∀ b, Continuous fun x => f (x, b)) : Continuous f := have : Continuous (f ∘ Prod.swap) := continuous_prod_of_continuous_lipschitzWith _ K hb ha this.comp continuous_swap
VecNotation.lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Eric Wieser -/ import Mathlib.Data.Fin.Tuple.Basic /-! # Matrix and vector notation This file defines notation for vectors and matrices. Given `a b c d : α`, the notation allows us to write `![a, b, c, d] : Fin 4 → α`. Nesting vectors gives coefficients of a matrix, so `![![a, b], ![c, d]] : Fin 2 → Fin 2 → α`. In later files we introduce `!![a, b; c, d]` as notation for `Matrix.of ![![a, b], ![c, d]]`. ## Main definitions * `vecEmpty` is the empty vector (or `0` by `n` matrix) `![]` * `vecCons` prepends an entry to a vector, so `![a, b]` is `vecCons a (vecCons b vecEmpty)` ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vecCons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations The main new notation is `![a, b]`, which gets expanded to `vecCons a (vecCons b vecEmpty)`. ## Examples Examples of usage can be found in the `MathlibTest/matrix.lean` file. -/ namespace Matrix universe u variable {α : Type u} section MatrixNotation /-- `![]` is the vector with no entries. -/ def vecEmpty : Fin 0 → α := Fin.elim0 /-- `vecCons h t` prepends an entry `h` to a vector `t`. The inverse functions are `vecHead` and `vecTail`. The notation `![a, b, ...]` expands to `vecCons a (vecCons b ...)`. -/ def vecCons {n : ℕ} (h : α) (t : Fin n → α) : Fin n.succ → α := Fin.cons h t /-- `![...]` notation is used to construct a vector `Fin n → α` using `Matrix.vecEmpty` and `Matrix.vecCons`. For instance, `![a, b, c] : Fin 3` is syntax for `vecCons a (vecCons b (vecCons c vecEmpty))`. Note that this should not be used as syntax for `Matrix` as it generates a term with the wrong type. The `!![a, b; c, d]` syntax (provided by `Matrix.matrixNotation`) should be used instead. -/ syntax (name := vecNotation) "![" term,* "]" : term macro_rules | `(![$term:term, $terms:term,*]) => `(vecCons $term ![$terms,*]) | `(![$term:term]) => `(vecCons $term ![]) | `(![]) => `(vecEmpty) /-- Unexpander for the `![x, y, ...]` notation. -/ @[app_unexpander vecCons] def vecConsUnexpander : Lean.PrettyPrinter.Unexpander | `($_ $term ![$term2, $terms,*]) => `(![$term, $term2, $terms,*]) | `($_ $term ![$term2]) => `(![$term, $term2]) | `($_ $term ![]) => `(![$term]) | _ => throw () /-- Unexpander for the `![]` notation. -/ @[app_unexpander vecEmpty] def vecEmptyUnexpander : Lean.PrettyPrinter.Unexpander | `($_:ident) => `(![]) | _ => throw () /-- `vecHead v` gives the first entry of the vector `v` -/ def vecHead {n : ℕ} (v : Fin n.succ → α) : α := v 0 /-- `vecTail v` gives a vector consisting of all entries of `v` except the first -/ def vecTail {n : ℕ} (v : Fin n.succ → α) : Fin n → α := v ∘ Fin.succ variable {m n : ℕ} /-- Use `![...]` notation for displaying a vector `Fin n → α`, for example: ``` #eval ![1, 2] + ![3, 4] -- ![4, 6] ``` -/ instance _root_.PiFin.hasRepr [Repr α] : Repr (Fin n → α) where reprPrec f _ := Std.Format.bracket "![" (Std.Format.joinSep ((List.finRange n).map fun n => repr (f n)) ("," ++ Std.Format.line)) "]" end MatrixNotation variable {m n o : ℕ} theorem empty_eq (v : Fin 0 → α) : v = ![] := Subsingleton.elim _ _ section Val @[simp] theorem head_fin_const (a : α) : (vecHead fun _ : Fin (n + 1) => a) = a := rfl @[simp] theorem cons_val_zero (x : α) (u : Fin m → α) : vecCons x u 0 = x := rfl theorem cons_val_zero' (h : 0 < m.succ) (x : α) (u : Fin m → α) : vecCons x u ⟨0, h⟩ = x := rfl @[simp] theorem cons_val_succ (x : α) (u : Fin m → α) (i : Fin m) : vecCons x u i.succ = u i := by simp [vecCons] @[simp] theorem cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : Fin m → α) : vecCons x u ⟨i.succ, h⟩ = u ⟨i, Nat.lt_of_succ_lt_succ h⟩ := by simp only [vecCons, Fin.cons, Fin.cases_succ'] section simprocs open Lean Qq /-- Parses a chain of `Matrix.vecCons` calls into elements, leaving everything else in the tail. `let ⟨xs, tailn, tail⟩ ← matchVecConsPrefix n e` decomposes `e : Fin n → _` in the form `vecCons x₀ <| ... <| vecCons xₙ <| tail` where `tail : Fin tailn → _`. -/ partial def matchVecConsPrefix (n : Q(Nat)) (e : Expr) : MetaM <| List Expr × Q(Nat) × Expr := do match_expr ← Meta.whnfR e with | Matrix.vecCons _ n x xs => do let (elems, n', tail) ← matchVecConsPrefix n xs return (x :: elems, n', tail) | _ => return ([], n, e) open Qq in /-- A simproc that handles terms of the form `Matrix.vecCons a f i` where `i` is a numeric literal. In practice, this is most effective at handling `![a, b, c] i`-style terms. -/ dsimproc cons_val (Matrix.vecCons _ _ _) := fun e => do let_expr Matrix.vecCons α en x xs' ei := ← Meta.whnfR e | return .continue let some i := ei.int? | return .continue let (xs, etailn, tail) ← matchVecConsPrefix en xs' let xs := x :: xs -- Determine if the tail is a numeral or only an offset. let (tailn, variadic, etailn) ← do let etailn_whnf : Q(ℕ) ← Meta.whnfD etailn if let Expr.lit (.natVal length) := etailn_whnf then pure (length, false, q(OfNat.ofNat $etailn_whnf)) else if let .some ((base : Q(ℕ)), offset) ← (Meta.isOffset? etailn_whnf).run then let offset_e : Q(ℕ) := mkNatLit offset pure (offset, true, q($base + $offset)) else pure (0, true, etailn) -- Wrap the index if possible, and abort if not let wrapped_i ← if variadic then -- can't wrap as we don't know the length unless 0 ≤ i ∧ i < xs.length + tailn do return .continue pure i.toNat else pure (i % (xs.length + tailn)).toNat if h : wrapped_i < xs.length then return .continue xs[wrapped_i] else -- Within the `tail` let _ ← synthInstanceQ q(NeZero $etailn) have i_lit : Q(ℕ) := mkRawNatLit (wrapped_i - xs.length) return .continue (.some <| .app tail q(OfNat.ofNat $i_lit : Fin $etailn)) end simprocs @[simp] theorem head_cons (x : α) (u : Fin m → α) : vecHead (vecCons x u) = x := rfl @[simp] theorem tail_cons (x : α) (u : Fin m → α) : vecTail (vecCons x u) = u := by ext simp [vecTail] theorem empty_val' {n' : Type*} (j : n') : (fun i => (![] : Fin 0 → n' → α) i j) = ![] := empty_eq _ @[simp] theorem cons_head_tail (u : Fin m.succ → α) : vecCons (vecHead u) (vecTail u) = u := Fin.cons_self_tail _ @[simp] theorem range_cons (x : α) (u : Fin n → α) : Set.range (vecCons x u) = {x} ∪ Set.range u := Set.ext fun y => by simp [Fin.exists_fin_succ, eq_comm] @[simp] theorem range_empty (u : Fin 0 → α) : Set.range u = ∅ := Set.range_eq_empty _ theorem range_cons_empty (x : α) (u : Fin 0 → α) : Set.range (Matrix.vecCons x u) = {x} := by rw [range_cons, range_empty, Set.union_empty] -- simp can prove this (up to commutativity) theorem range_cons_cons_empty (x y : α) (u : Fin 0 → α) : Set.range (vecCons x <| vecCons y u) = {x, y} := by rw [range_cons, range_cons_empty, Set.singleton_union] theorem vecCons_const (a : α) : (vecCons a fun _ : Fin n => a) = fun _ => a := funext <| Fin.forall_iff_succ.2 ⟨rfl, cons_val_succ _ _⟩ theorem vec_single_eq_const (a : α) : ![a] = fun _ => a := let _ : Unique (Fin 1) := inferInstance funext <| Unique.forall_iff.2 rfl /-- `![a, b, ...] 1` is equal to `b`. The simplifier needs a special lemma for length `≥ 2`, in addition to `cons_val_succ`, because `1 : Fin 1 = 0 : Fin 1`. -/ @[simp] theorem cons_val_one (x : α) (u : Fin m.succ → α) : vecCons x u 1 = u 0 := rfl theorem cons_val_two (x : α) (u : Fin m.succ.succ → α) : vecCons x u 2 = vecHead (vecTail u) := rfl lemma cons_val_three (x : α) (u : Fin m.succ.succ.succ → α) : vecCons x u 3 = vecHead (vecTail (vecTail u)) := rfl lemma cons_val_four (x : α) (u : Fin m.succ.succ.succ.succ → α) : vecCons x u 4 = vecHead (vecTail (vecTail (vecTail u))) := rfl @[simp] theorem cons_val_fin_one (x : α) (u : Fin 0 → α) : ∀ (i : Fin 1), vecCons x u i = x := by rw [Fin.forall_fin_one] rfl theorem cons_fin_one (x : α) (u : Fin 0 → α) : vecCons x u = fun _ => x := funext (cons_val_fin_one x u) @[simp] theorem vecCons_inj {x y : α} {u v : Fin n → α} : vecCons x u = vecCons y v ↔ x = y ∧ u = v := Fin.cons_inj open Lean Qq in /-- `mkVecLiteralQ ![x, y, z]` produces the term `q(![$x, $y, $z])`. -/ def _root_.PiFin.mkLiteralQ {u : Level} {α : Q(Type u)} {n : ℕ} (elems : Fin n → Q($α)) : Q(Fin $n → $α) := loop 0 (Nat.zero_le _) q(vecEmpty) where loop (i : ℕ) (hi : i ≤ n) (rest : Q(Fin $i → $α)) : let i' : Nat := i + 1; Q(Fin $(i') → $α) := if h : i < n then loop (i + 1) h q(vecCons $(elems (Fin.rev ⟨i, h⟩)) $rest) else rest attribute [nolint docBlame] _root_.PiFin.mkLiteralQ.loop open Lean Qq in protected instance _root_.PiFin.toExpr [ToLevel.{u}] [ToExpr α] (n : ℕ) : ToExpr (Fin n → α) := have lu := toLevel.{u} have eα : Q(Type $lu) := toTypeExpr α let toTypeExpr := q(Fin $n → $eα) { toTypeExpr, toExpr v := PiFin.mkLiteralQ fun i => show Q($eα) from toExpr (v i) } /-! ### `bit0` and `bit1` indices The following definitions and `simp` lemmas are used to allow numeral-indexed element of a vector given with matrix notation to be extracted by `simp` in Lean 3 (even when the numeral is larger than the number of elements in the vector, which is taken modulo that number of elements by virtue of the semantics of `bit0` and `bit1` and of addition on `Fin n`). -/ /-- `vecAppend ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. This is a variant of `Fin.append` with an additional `ho` argument, which provides control of definitional equality for the vector length. This turns out to be helpful when providing simp lemmas to reduce `![a, b, c] n`, and also means that `vecAppend ho u v 0` is valid. `Fin.append u v 0` is not valid in this case because there is no `Zero (Fin (m + n))` instance. -/ def vecAppend {α : Type*} {o : ℕ} (ho : o = m + n) (u : Fin m → α) (v : Fin n → α) : Fin o → α := Fin.append u v ∘ Fin.cast ho theorem vecAppend_eq_ite {α : Type*} {o : ℕ} (ho : o = m + n) (u : Fin m → α) (v : Fin n → α) : vecAppend ho u v = fun i : Fin o => if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, by omega⟩ := by ext i rw [vecAppend, Fin.append, Function.comp_apply, Fin.addCases] congr with hi simp only [eq_rec_constant] rfl @[simp] theorem vecAppend_apply_zero {α : Type*} {o : ℕ} (ho : o + 1 = m + 1 + n) (u : Fin (m + 1) → α) (v : Fin n → α) : vecAppend ho u v 0 = u 0 := dif_pos _ @[simp] theorem empty_vecAppend (v : Fin n → α) : vecAppend n.zero_add.symm ![] v = v := by ext simp [vecAppend_eq_ite] @[simp] theorem cons_vecAppend (ho : o + 1 = m + 1 + n) (x : α) (u : Fin m → α) (v : Fin n → α) : vecAppend ho (vecCons x u) v = vecCons x (vecAppend (by omega) u v) := by ext i simp_rw [vecAppend_eq_ite] split_ifs with h · rcases i with ⟨⟨⟩ | i, hi⟩ · simp · simp only [Nat.add_lt_add_iff_right] at h simp [h] · rcases i with ⟨⟨⟩ | i, hi⟩ · simp at h · rw [not_lt, Fin.val_mk, Nat.add_le_add_iff_right] at h simp [not_lt.2 h] /-- `vecAlt0 v` gives a vector with half the length of `v`, with only alternate elements (even-numbered). -/ def vecAlt0 (hm : m = n + n) (v : Fin m → α) (k : Fin n) : α := v ⟨(k : ℕ) + k, by omega⟩ /-- `vecAlt1 v` gives a vector with half the length of `v`, with only alternate elements (odd-numbered). -/ def vecAlt1 (hm : m = n + n) (v : Fin m → α) (k : Fin n) : α := v ⟨(k : ℕ) + k + 1, hm.symm ▸ Nat.add_succ_lt_add k.2 k.2⟩ section bits theorem vecAlt0_vecAppend (v : Fin n → α) : vecAlt0 rfl (vecAppend rfl v v) = v ∘ (fun n ↦ n + n) := by ext i simp_rw [Function.comp, vecAlt0, vecAppend_eq_ite] split_ifs with h <;> congr · rw [Fin.val_mk] at h exact (Nat.mod_eq_of_lt h).symm · rw [Fin.val_mk, not_lt] at h simp only [Nat.mod_eq_sub_mod h] refine (Nat.mod_eq_of_lt ?_).symm omega theorem vecAlt1_vecAppend (v : Fin (n + 1) → α) : vecAlt1 rfl (vecAppend rfl v v) = v ∘ (fun n ↦ (n + n) + 1) := by ext i simp_rw [Function.comp, vecAlt1, vecAppend_eq_ite] cases n with | zero => obtain ⟨i, hi⟩ := i simp only [Nat.zero_add, Nat.lt_one_iff] at hi; subst i; rfl | succ n => split_ifs with h <;> congr · simp [Nat.mod_eq_of_lt, h] · rw [Fin.val_mk, not_lt] at h simp only [Nat.mod_add_mod, Nat.mod_eq_sub_mod h, show 1 % (n + 2) = 1 from Nat.mod_eq_of_lt (by omega)] refine (Nat.mod_eq_of_lt ?_).symm omega @[simp] theorem vecHead_vecAlt0 (hm : m + 2 = n + 1 + (n + 1)) (v : Fin (m + 2) → α) : vecHead (vecAlt0 hm v) = v 0 := rfl @[simp] theorem vecHead_vecAlt1 (hm : m + 2 = n + 1 + (n + 1)) (v : Fin (m + 2) → α) : vecHead (vecAlt1 hm v) = v 1 := by simp [vecHead, vecAlt1] theorem cons_vec_bit0_eq_alt0 (x : α) (u : Fin n → α) (i : Fin (n + 1)) : vecCons x u (i + i) = vecAlt0 rfl (vecAppend rfl (vecCons x u) (vecCons x u)) i := by rw [vecAlt0_vecAppend]; rfl theorem cons_vec_bit1_eq_alt1 (x : α) (u : Fin n → α) (i : Fin (n + 1)) : vecCons x u ((i + i) + 1) = vecAlt1 rfl (vecAppend rfl (vecCons x u) (vecCons x u)) i := by rw [vecAlt1_vecAppend]; rfl end bits @[simp] theorem cons_vecAlt0 (h : m + 1 + 1 = n + 1 + (n + 1)) (x y : α) (u : Fin m → α) : vecAlt0 h (vecCons x (vecCons y u)) = vecCons x (vecAlt0 (by omega) u) := by ext i simp_rw [vecAlt0] rcases i with ⟨⟨⟩ | i, hi⟩ · rfl · simp only [← Nat.add_assoc, Nat.add_right_comm, cons_val_succ', vecAlt0] @[simp] theorem empty_vecAlt0 (α) {h} : vecAlt0 h (![] : Fin 0 → α) = ![] := by simp [eq_iff_true_of_subsingleton] @[simp] theorem cons_vecAlt1 (h : m + 1 + 1 = n + 1 + (n + 1)) (x y : α) (u : Fin m → α) : vecAlt1 h (vecCons x (vecCons y u)) = vecCons y (vecAlt1 (by omega) u) := by ext i simp_rw [vecAlt1] rcases i with ⟨⟨⟩ | i, hi⟩ · rfl · simp [vecAlt1, Nat.add_right_comm, ← Nat.add_assoc] @[simp] theorem empty_vecAlt1 (α) {h} : vecAlt1 h (![] : Fin 0 → α) = ![] := by simp [eq_iff_true_of_subsingleton] end Val lemma const_fin1_eq (x : α) : (fun _ : Fin 1 => x) = ![x] := (cons_fin_one x _).symm end Matrix
Tilted.lean
/- Copyright (c) 2025 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import Mathlib.MeasureTheory.Measure.Tilted import Mathlib.Probability.Moments.MGFAnalytic /-! # Results relating `Measure.tilted` to `mgf` and `cgf` For a random variable `X : Ω → ℝ` and a measure `μ`, the tilted measure `μ.tilted (t * X ·)` is linked to the moment generating function (`mgf`) and the cumulant generating function (`cgf`) of `X`. ## Main statements * `integral_tilted_mul_self`: the integral of `X` against the tilted measure `μ.tilted (t * X ·)` is the first derivative of the cumulant generating function of `X` at `t`. `(μ.tilted (t * X ·))[X] = deriv (cgf X μ) t` * `variance_tilted_mul`: the variance of `X` under the tilted measure `μ.tilted (t * X ·)` is the second derivative of the cumulant generating function of `X` at `t`. `Var[X; μ.tilted (t * X ·)] = iteratedDeriv 2 (cgf X μ) t` -/ open MeasureTheory Real Set Finset open scoped NNReal ENNReal ProbabilityTheory variable {Ω : Type*} {mΩ : MeasurableSpace Ω} {μ ν : Measure Ω} {X : Ω → ℝ} {t u : ℝ} namespace ProbabilityTheory section Apply /-! ### Apply lemmas for `tilted` expressed with `mgf` or `cgf`. -/ lemma tilted_mul_apply_mgf' {s : Set Ω} (hs : MeasurableSet s) : μ.tilted (t * X ·) s = ∫⁻ a in s, ENNReal.ofReal (exp (t * X a) / mgf X μ t) ∂μ := by rw [tilted_apply' _ _ hs, mgf] lemma tilted_mul_apply_mgf [SFinite μ] (s : Set Ω) : μ.tilted (t * X ·) s = ∫⁻ a in s, ENNReal.ofReal (exp (t * X a) / mgf X μ t) ∂μ := by rw [tilted_apply, mgf] lemma tilted_mul_apply_cgf' {s : Set Ω} (hs : MeasurableSet s) (ht : Integrable (fun ω ↦ exp (t * X ω)) μ) : μ.tilted (t * X ·) s = ∫⁻ a in s, ENNReal.ofReal (exp (t * X a - cgf X μ t)) ∂μ := by rcases eq_zero_or_neZero μ with rfl | hμ · simp · simp_rw [tilted_mul_apply_mgf' hs, exp_sub, exp_cgf ht] lemma tilted_mul_apply_cgf [SFinite μ] (s : Set Ω) (ht : Integrable (fun ω ↦ exp (t * X ω)) μ) : μ.tilted (t * X ·) s = ∫⁻ a in s, ENNReal.ofReal (exp (t * X a - cgf X μ t)) ∂μ := by rcases eq_zero_or_neZero μ with rfl | hμ · simp · simp_rw [tilted_mul_apply_mgf s, exp_sub, exp_cgf ht] lemma tilted_mul_apply_eq_ofReal_integral_mgf' {s : Set Ω} (hs : MeasurableSet s) : μ.tilted (t * X ·) s = ENNReal.ofReal (∫ a in s, exp (t * X a) / mgf X μ t ∂μ) := by rw [tilted_apply_eq_ofReal_integral' _ hs, mgf] lemma tilted_mul_apply_eq_ofReal_integral_mgf [SFinite μ] (s : Set Ω) : μ.tilted (t * X ·) s = ENNReal.ofReal (∫ a in s, exp (t * X a) / mgf X μ t ∂μ) := by rw [tilted_apply_eq_ofReal_integral _ s, mgf] lemma tilted_mul_apply_eq_ofReal_integral_cgf' {s : Set Ω} (hs : MeasurableSet s) (ht : Integrable (fun ω ↦ exp (t * X ω)) μ) : μ.tilted (t * X ·) s = ENNReal.ofReal (∫ a in s, exp (t * X a - cgf X μ t) ∂μ) := by rcases eq_zero_or_neZero μ with rfl | hμ · simp · simp_rw [tilted_mul_apply_eq_ofReal_integral_mgf' hs, exp_sub] rwa [exp_cgf] lemma tilted_mul_apply_eq_ofReal_integral_cgf [SFinite μ] (s : Set Ω) (ht : Integrable (fun ω ↦ exp (t * X ω)) μ) : μ.tilted (t * X ·) s = ENNReal.ofReal (∫ a in s, exp (t * X a - cgf X μ t) ∂μ) := by rcases eq_zero_or_neZero μ with rfl | hμ · simp · simp_rw [tilted_mul_apply_eq_ofReal_integral_mgf s, exp_sub] rwa [exp_cgf] end Apply section Integral /-! ### Integral of `tilted` expressed with `mgf` or `cgf`. -/ variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] lemma setIntegral_tilted_mul_eq_mgf' (g : Ω → E) {s : Set Ω} (hs : MeasurableSet s) : ∫ x in s, g x ∂(μ.tilted (t * X ·)) = ∫ x in s, (exp (t * X x) / mgf X μ t) • (g x) ∂μ := by rw [setIntegral_tilted' _ _ hs, mgf] lemma setIntegral_tilted_mul_eq_mgf [SFinite μ] (g : Ω → E) (s : Set Ω) : ∫ x in s, g x ∂(μ.tilted (t * X ·)) = ∫ x in s, (exp (t * X x) / mgf X μ t) • (g x) ∂μ := by rw [setIntegral_tilted, mgf] lemma setIntegral_tilted_mul_eq_cgf' (g : Ω → E) {s : Set Ω} (hs : MeasurableSet s) (ht : Integrable (fun ω ↦ exp (t * X ω)) μ) : ∫ x in s, g x ∂(μ.tilted (t * X ·)) = ∫ x in s, exp (t * X x - cgf X μ t) • (g x) ∂μ := by rcases eq_zero_or_neZero μ with rfl | hμ · simp · simp_rw [setIntegral_tilted_mul_eq_mgf' _ hs, exp_sub, exp_cgf ht] lemma setIntegral_tilted_mul_eq_cgf [SFinite μ] (g : Ω → E) (s : Set Ω) (ht : Integrable (fun ω ↦ exp (t * X ω)) μ) : ∫ x in s, g x ∂(μ.tilted (t * X ·)) = ∫ x in s, exp (t * X x - cgf X μ t) • (g x) ∂μ := by rcases eq_zero_or_neZero μ with rfl | hμ · simp · simp_rw [setIntegral_tilted_mul_eq_mgf, exp_sub, exp_cgf ht] lemma integral_tilted_mul_eq_mgf (g : Ω → E) : ∫ ω, g ω ∂(μ.tilted (t * X ·)) = ∫ ω, (exp (t * X ω) / mgf X μ t) • (g ω) ∂μ := by rw [integral_tilted, mgf] lemma integral_tilted_mul_eq_cgf (g : Ω → E) (ht : Integrable (fun ω ↦ exp (t * X ω)) μ) : ∫ ω, g ω ∂(μ.tilted (t * X ·)) = ∫ ω, exp (t * X ω - cgf X μ t) • (g ω) ∂μ := by rcases eq_zero_or_neZero μ with rfl | hμ · simp · simp_rw [integral_tilted_mul_eq_mgf, exp_sub] rwa [exp_cgf] /-- The integral of `X` against the tilted measure `μ.tilted (t * X ·)` is the first derivative of the cumulant generating function of `X` at `t`. -/ lemma integral_tilted_mul_self (ht : t ∈ interior (integrableExpSet X μ)) : (μ.tilted (t * X ·))[X] = deriv (cgf X μ) t := by simp_rw [integral_tilted_mul_eq_mgf, deriv_cgf ht, ← integral_div, smul_eq_mul] congr with ω ring end Integral lemma memLp_tilted_mul (ht : t ∈ interior (integrableExpSet X μ)) (p : ℝ≥0) : MemLp X p (μ.tilted (t * X ·)) := by have hX : AEMeasurable X μ := aemeasurable_of_mem_interior_integrableExpSet ht by_cases hp : p = 0 · simpa [hp] using hX.aestronglyMeasurable.mono_ac (tilted_absolutelyContinuous _ _) refine ⟨hX.aestronglyMeasurable.mono_ac (tilted_absolutelyContinuous _ _), ?_⟩ rw [eLpNorm_lt_top_iff_lintegral_rpow_enorm_lt_top] rotate_left · simp [hp] · simp simp_rw [ENNReal.coe_toReal, ← ofReal_norm_eq_enorm, norm_eq_abs, ENNReal.ofReal_rpow_of_nonneg (x := |X _|) (p := p) (abs_nonneg (X _)) p.2] refine Integrable.lintegral_lt_top ?_ simp_rw [integrable_tilted_iff (interior_subset (s := integrableExpSet X μ) ht), smul_eq_mul, mul_comm] exact integrable_rpow_abs_mul_exp_of_mem_interior_integrableExpSet ht p.2 /-- The variance of `X` under the tilted measure `μ.tilted (t * X ·)` is the second derivative of the cumulant generating function of `X` at `t`. -/ lemma variance_tilted_mul (ht : t ∈ interior (integrableExpSet X μ)) : Var[X; μ.tilted (t * X ·)] = iteratedDeriv 2 (cgf X μ) t := by rw [variance_eq_integral] swap; · exact (memLp_tilted_mul ht 1).aestronglyMeasurable.aemeasurable rw [integral_tilted_mul_self ht, iteratedDeriv_two_cgf_eq_integral ht, integral_tilted_mul_eq_mgf, ← integral_div] simp only [smul_eq_mul] congr with ω ring end ProbabilityTheory
Trim.lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import Mathlib.MeasureTheory.Function.LpSeminorm.Basic /-! # Lp seminorm with respect to trimmed measure In this file we prove basic properties of the Lp-seminorm of a function with respect to the restriction of a measure to a sub-σ-algebra. -/ namespace MeasureTheory open Filter open scoped ENNReal variable {α E ε : Type*} {m m0 : MeasurableSpace α} {p : ℝ≥0∞} {q : ℝ} {μ : Measure α} [NormedAddCommGroup E] [TopologicalSpace ε] [ContinuousENorm ε] theorem eLpNorm'_trim (hm : m ≤ m0) {f : α → ε} (hf : StronglyMeasurable[m] f) : eLpNorm' f q (μ.trim hm) = eLpNorm' f q μ := by simp_rw [eLpNorm'] congr 1 exact lintegral_trim hm (by fun_prop) theorem limsup_trim (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : Measurable[m] f) : limsup f (ae (μ.trim hm)) = limsup f (ae μ) := by simp_rw [limsup_eq] suffices h_set_eq : { a : ℝ≥0∞ | ∀ᵐ n ∂μ.trim hm, f n ≤ a } = { a : ℝ≥0∞ | ∀ᵐ n ∂μ, f n ≤ a } by rw [h_set_eq] ext1 a suffices h_meas_eq : μ { x | ¬f x ≤ a } = μ.trim hm { x | ¬f x ≤ a } by simp_rw [Set.mem_setOf_eq, ae_iff, h_meas_eq] refine (trim_measurableSet_eq hm ?_).symm exact (measurableSet_le hf measurable_const).compl theorem essSup_trim (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : Measurable[m] f) : essSup f (μ.trim hm) = essSup f μ := by simp_rw [essSup] exact limsup_trim hm hf theorem eLpNormEssSup_trim (hm : m ≤ m0) {f : α → ε} (hf : StronglyMeasurable[m] f) : eLpNormEssSup f (μ.trim hm) = eLpNormEssSup f μ := essSup_trim _ (@StronglyMeasurable.enorm _ m _ _ _ _ hf) theorem eLpNorm_trim (hm : m ≤ m0) {f : α → ε} (hf : StronglyMeasurable[m] f) : eLpNorm f p (μ.trim hm) = eLpNorm f p μ := by by_cases h0 : p = 0 · simp [h0] by_cases h_top : p = ∞ · simpa only [h_top, eLpNorm_exponent_top] using eLpNormEssSup_trim hm hf simpa only [eLpNorm_eq_eLpNorm' h0 h_top] using eLpNorm'_trim hm hf theorem eLpNorm_trim_ae (hm : m ≤ m0) {f : α → ε} (hf : AEStronglyMeasurable[m] f (μ.trim hm)) : eLpNorm f p (μ.trim hm) = eLpNorm f p μ := by rw [eLpNorm_congr_ae hf.ae_eq_mk, eLpNorm_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk)] exact eLpNorm_trim hm hf.stronglyMeasurable_mk theorem memLp_of_memLp_trim (hm : m ≤ m0) {f : α → ε} (hf : MemLp f p (μ.trim hm)) : MemLp f p μ := ⟨aestronglyMeasurable_of_aestronglyMeasurable_trim hm hf.1, (le_of_eq (eLpNorm_trim_ae hm hf.1).symm).trans_lt hf.2⟩ @[deprecated (since := "2025-02-21")] alias memℒp_of_memℒp_trim := memLp_of_memLp_trim end MeasureTheory
frobenius.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div. From mathcomp Require Import fintype bigop prime finset fingroup morphism. From mathcomp Require Import perm action quotient gproduct cyclic center. From mathcomp Require Import pgroup nilpotent sylow hall abelian. (******************************************************************************) (* Definition of Frobenius groups, some basic results, and the Frobenius *) (* theorem on the number of solutions of x ^+ n = 1. *) (* semiregular K H <-> *) (* the internal action of H on K is semiregular, i.e., no nontrivial *) (* elements of H and K commute; note that this is actually a symmetric *) (* condition. *) (* semiprime K H <-> *) (* the internal action of H on K is "prime", i.e., an element of K that *) (* centralises a nontrivial element of H must centralise all of H. *) (* normedTI A G L <=> *) (* A is nonempty, strictly disjoint from its conjugates in G, and has *) (* normaliser L in G. *) (* [Frobenius G = K ><| H] <=> *) (* G is (isomorphic to) a Frobenius group with kernel K and complement *) (* H. This is an effective predicate (in bool), which tests the *) (* equality with the semidirect product, and then the fact that H is a *) (* proper self-normalizing TI-subgroup of G. *) (* [Frobenius G with kernel H] <=> *) (* G is (isomorphic to) a Frobenius group with kernel K; same as above, *) (* but without the semi-direct product. *) (* [Frobenius G with complement H] <=> *) (* G is (isomorphic to) a Frobenius group with complement H; same as *) (* above, but without the semi-direct product. The proof that this form *) (* is equivalent to the above (i.e., the existence of Frobenius *) (* kernels) requires character theory and will only be proved in the *) (* vcharacter.v file. *) (* [Frobenius G] <=> G is a Frobenius group. *) (* Frobenius_action G H S to <-> *) (* The action to of G on S defines an isomorphism of G with a *) (* (permutation) Frobenius group, i.e., to is faithful and transitive *) (* on S, no nontrivial element of G fixes more than one point in S, and *) (* H is the stabilizer of some element of S, and non-trivial. Thus, *) (* Frobenius_action G H S 'P *) (* asserts that G is a Frobenius group in the classic sense. *) (* has_Frobenius_action G H <-> *) (* Frobenius_action G H S to holds for some sT : finType, S : {set st} *) (* and to : {action gT &-> sT}. This is a predicate in Prop, but is *) (* exactly reflected by [Frobenius G with complement H] : bool. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Section Definitions. Variable gT : finGroupType. Implicit Types A G K H L : {set gT}. (* Corresponds to "H acts on K in a regular manner" in B & G. *) Definition semiregular K H := {in H^#, forall x, 'C_K[x] = 1}. (* Corresponds to "H acts on K in a prime manner" in B & G. *) Definition semiprime K H := {in H^#, forall x, 'C_K[x] = 'C_K(H)}. Definition normedTI A G L := [&& A != set0, trivIset (A :^: G) & 'N_G(A) == L]. Definition Frobenius_group_with_complement G H := (H != G) && normedTI H^# G H. Definition Frobenius_group G := [exists H : {group gT}, Frobenius_group_with_complement G H]. Definition Frobenius_group_with_kernel_and_complement G K H := (K ><| H == G) && Frobenius_group_with_complement G H. Definition Frobenius_group_with_kernel G K := [exists H : {group gT}, Frobenius_group_with_kernel_and_complement G K H]. Section FrobeniusAction. Variables G H : {set gT}. Variables (sT : finType) (S : {set sT}) (to : {action gT &-> sT}). Definition Frobenius_action := [/\ [faithful G, on S | to], [transitive G, on S | to], {in G^#, forall x, #|'Fix_(S | to)[x]| <= 1}, H != 1 & exists2 u, u \in S & H = 'C_G[u | to]]. End FrobeniusAction. Variant has_Frobenius_action G H : Prop := hasFrobeniusAction sT S to of @Frobenius_action G H sT S to. End Definitions. Arguments semiregular {gT} K%_g H%_g. Arguments semiprime {gT} K%_g H%_g. Arguments normedTI {gT} A%_g G%_g L%_g. Arguments Frobenius_group_with_complement {gT} G%_g H%_g. Arguments Frobenius_group {gT} G%_g. Arguments Frobenius_group_with_kernel {gT} G%_g K%_g. Arguments Frobenius_group_with_kernel_and_complement {gT} G%_g K%_g H%_g. Arguments Frobenius_action {gT} G%_g H%_g {sT} S%_g to%_act. Arguments has_Frobenius_action {gT} G%_g H%_g. Notation "[ 'Frobenius' G 'with' 'complement' H ]" := (Frobenius_group_with_complement G H) (G at level 50, format "[ 'Frobenius' G 'with' 'complement' H ]") : group_scope. Notation "[ 'Frobenius' G 'with' 'kernel' K ]" := (Frobenius_group_with_kernel G K) (format "[ 'Frobenius' G 'with' 'kernel' K ]") : group_scope. Notation "[ 'Frobenius' G ]" := (Frobenius_group G) (format "[ 'Frobenius' G ]") : group_scope. Notation "[ 'Frobenius' G = K ><| H ]" := (Frobenius_group_with_kernel_and_complement G K H) (K, H at level 35, format "[ 'Frobenius' G = K ><| H ]") : group_scope. Section FrobeniusBasics. Variable gT : finGroupType. Implicit Types (A B : {set gT}) (G H K L R X : {group gT}). Lemma semiregular1l H : semiregular 1 H. Proof. by move=> x _ /=; rewrite setI1g. Qed. Lemma semiregular1r K : semiregular K 1. Proof. by move=> x; rewrite setDv inE. Qed. Lemma semiregular_sym H K : semiregular K H -> semiregular H K. Proof. move=> regH x /setD1P[ntx Kx]; apply: contraNeq ntx. rewrite -subG1 -setD_eq0 -setIDAC => /set0Pn[y /setIP[Hy cxy]]. by rewrite (sameP eqP set1gP) -(regH y Hy) inE Kx cent1C. Qed. Lemma semiregularS K1 K2 A1 A2 : K1 \subset K2 -> A1 \subset A2 -> semiregular K2 A2 -> semiregular K1 A1. Proof. move=> sK12 sA12 regKA2 x /setD1P[ntx /(subsetP sA12)A2x]. by apply/trivgP; rewrite -(regKA2 x) ?inE ?ntx ?setSI. Qed. Lemma semiregular_prime H K : semiregular K H -> semiprime K H. Proof. move=> regH x Hx; apply/eqP; rewrite eqEsubset {1}regH // sub1G. by rewrite -cent_set1 setIS ?centS // sub1set; case/setD1P: Hx. Qed. Lemma semiprime_regular H K : semiprime K H -> 'C_K(H) = 1 -> semiregular K H. Proof. by move=> prKH tiKcH x Hx; rewrite prKH. Qed. Lemma semiprimeS K1 K2 A1 A2 : K1 \subset K2 -> A1 \subset A2 -> semiprime K2 A2 -> semiprime K1 A1. Proof. move=> sK12 sA12 prKA2 x /setD1P[ntx A1x]. apply/eqP; rewrite eqEsubset andbC -{1}cent_set1 setIS ?centS ?sub1set //=. rewrite -(setIidPl sK12) -!setIA prKA2 ?setIS ?centS //. by rewrite !inE ntx (subsetP sA12). Qed. Lemma cent_semiprime H K X : semiprime K H -> X \subset H -> X :!=: 1 -> 'C_K(X) = 'C_K(H). Proof. move=> prKH sXH /trivgPn[x Xx ntx]; apply/eqP. rewrite eqEsubset -{1}(prKH x) ?inE ?(subsetP sXH) ?ntx //=. by rewrite -cent_cycle !setIS ?centS ?cycle_subG. Qed. Lemma stab_semiprime H K X : semiprime K H -> X \subset K -> 'C_H(X) != 1 -> 'C_H(X) = H. Proof. move=> prKH sXK ntCHX; apply/setIidPl; rewrite centsC -subsetIidl. rewrite -{2}(setIidPl sXK) -setIA -(cent_semiprime prKH _ ntCHX) ?subsetIl //. by rewrite !subsetI subxx sXK centsC subsetIr. Qed. Lemma cent_semiregular H K X : semiregular K H -> X \subset H -> X :!=: 1 -> 'C_K(X) = 1. Proof. move=> regKH sXH /trivgPn[x Xx ntx]; apply/trivgP. rewrite -(regKH x) ?inE ?(subsetP sXH) ?ntx ?setIS //=. by rewrite -cent_cycle centS ?cycle_subG. Qed. Lemma regular_norm_dvd_pred K H : H \subset 'N(K) -> semiregular K H -> #|H| %| #|K|.-1. Proof. move=> nKH regH; have actsH: [acts H, on K^# | 'J] by rewrite astabsJ normD1. rewrite (cardsD1 1 K) group1 -(acts_sum_card_orbit actsH) /=. rewrite (eq_bigr (fun _ => #|H|)) ?sum_nat_const ?dvdn_mull //. move=> _ /imsetP[x /setIdP[ntx Kx] ->]; rewrite card_orbit astab1J. rewrite ['C_H[x]](trivgP _) ?indexg1 //=. apply/subsetP=> y /setIP[Hy cxy]; apply: contraR ntx => nty. by rewrite -[[set 1]](regH y) inE ?nty // Kx cent1C. Qed. Lemma regular_norm_coprime K H : H \subset 'N(K) -> semiregular K H -> coprime #|K| #|H|. Proof. move=> nKH regH. by rewrite (coprime_dvdr (regular_norm_dvd_pred nKH regH)) ?coprimenP. Qed. Lemma semiregularJ K H x : semiregular K H -> semiregular (K :^ x) (H :^ x). Proof. move=> regH yx; rewrite -conjD1g => /imsetP[y Hy ->]. by rewrite cent1J -conjIg regH ?conjs1g. Qed. Lemma semiprimeJ K H x : semiprime K H -> semiprime (K :^ x) (H :^ x). Proof. move=> prH yx; rewrite -conjD1g => /imsetP[y Hy ->]. by rewrite cent1J centJ -!conjIg prH. Qed. Lemma normedTI_P A G L : reflect [/\ A != set0, L \subset 'N_G(A) & {in G, forall g, ~~ [disjoint A & A :^ g] -> g \in L}] (normedTI A G L). Proof. apply: (iffP and3P) => [[nzA /trivIsetP tiAG /eqP <-] | [nzA sLN tiAG]]. split=> // g Gg; rewrite inE Gg (sameP normP eqP) /= eq_sym; apply: contraR. by apply: tiAG; rewrite ?mem_orbit ?orbit_refl. have [/set0Pn[a Aa] /subsetIP[_ nAL]] := (nzA, sLN); split=> //; last first. rewrite eqEsubset sLN andbT; apply/subsetP=> x /setIP[Gx nAx]. by apply/tiAG/pred0Pn=> //; exists a; rewrite /= (normP nAx) Aa. apply/trivIsetP=> _ _ /imsetP[x Gx ->] /imsetP[y Gy ->]; apply: contraR. rewrite -setI_eq0 -(mulgKV x y) conjsgM; set g := (y * x^-1)%g. have Gg: g \in G by rewrite groupMl ?groupV. rewrite -conjIg (inj_eq (act_inj 'Js x)) (eq_sym A) (sameP eqP normP). by rewrite -cards_eq0 cardJg cards_eq0 setI_eq0 => /tiAG/(subsetP nAL)->. Qed. Arguments normedTI_P {A G L}. Lemma normedTI_memJ_P A G L : reflect [/\ A != set0, L \subset G & {in A & G, forall a g, (a ^ g \in A) = (g \in L)}] (normedTI A G L). Proof. apply: (iffP normedTI_P) => [[-> /subsetIP[sLG nAL] tiAG] | [-> sLG tiAG]]. split=> // a g Aa Gg; apply/idP/idP=> [Aag | Lg]; last first. by rewrite memJ_norm ?(subsetP nAL). by apply/tiAG/pred0Pn=> //; exists (a ^ g)%g; rewrite /= Aag memJ_conjg. split=> // [ | g Gg /pred0Pn[ag /=]]; last first. by rewrite andbC => /andP[/imsetP[a Aa ->]]; rewrite tiAG. apply/subsetP=> g Lg; have Gg := subsetP sLG g Lg. by rewrite !inE Gg; apply/subsetP=> _ /imsetP[a Aa ->]; rewrite tiAG. Qed. Lemma partition_class_support A G : A != set0 -> trivIset (A :^: G) -> partition (A :^: G) (class_support A G). Proof. rewrite /partition cover_imset -class_supportEr eqxx => nzA ->. by apply: contra nzA => /imsetP[x _ /eqP]; rewrite eq_sym -!cards_eq0 cardJg. Qed. Lemma partition_normedTI A G L : normedTI A G L -> partition (A :^: G) (class_support A G). Proof. by case/and3P=> ntA tiAG _; apply: partition_class_support. Qed. Lemma card_support_normedTI A G L : normedTI A G L -> #|class_support A G| = (#|A| * #|G : L|)%N. Proof. case/and3P=> ntA tiAG /eqP <-; rewrite -card_conjugates mulnC. apply: card_uniform_partition (partition_class_support ntA tiAG). by move=> _ /imsetP[y _ ->]; rewrite cardJg. Qed. Lemma normedTI_S A B G L : A != set0 -> L \subset 'N(A) -> A \subset B -> normedTI B G L -> normedTI A G L. Proof. move=> nzA /subsetP nAL /subsetP sAB /normedTI_memJ_P[nzB sLG tiB]. apply/normedTI_memJ_P; split=> // a x Aa Gx. by apply/idP/idP => [Aax | /nAL/memJ_norm-> //]; rewrite -(tiB a) ?sAB. Qed. Lemma cent1_normedTI A G L : normedTI A G L -> {in A, forall x, 'C_G[x] \subset L}. Proof. case/normedTI_memJ_P=> [_ _ tiAG] x Ax; apply/subsetP=> y /setIP[Gy cxy]. by rewrite -(tiAG x) // /(x ^ y) -(cent1P cxy) mulKg. Qed. Lemma Frobenius_actionP G H : reflect (has_Frobenius_action G H) [Frobenius G with complement H]. Proof. apply: (iffP andP) => [[neqHG] | [sT S to [ffulG transG regG ntH [u Su defH]]]]. case/normedTI_P=> nzH /subsetIP[sHG _] tiHG. suffices: Frobenius_action G H (rcosets H G) 'Rs by apply: hasFrobeniusAction. pose Hfix x := 'Fix_(rcosets H G | 'Rs)[x]. have regG: {in G^#, forall x, #|Hfix x| <= 1}. move=> x /setD1P[ntx Gx]. apply: wlog_neg; rewrite -ltnNge => /ltnW/card_gt0P/=[Hy]. rewrite -(cards1 Hy) => /setIP[/imsetP[y Gy ->{Hy}] cHyx]. apply/subset_leq_card/subsetP=> _ /setIP[/imsetP[z Gz ->] cHzx]. rewrite -!sub_astab1 !astab1_act !sub1set astab1Rs in cHyx cHzx *. rewrite !rcosetE; apply/set1P/rcoset_eqP; rewrite mem_rcoset. apply: tiHG; [by rewrite !in_group | apply/pred0Pn; exists (x ^ y^-1)]. by rewrite conjD1g !inE conjg_eq1 ntx -mem_conjg cHyx conjsgM memJ_conjg. have ntH: H :!=: 1 by rewrite -subG1 -setD_eq0. split=> //; first 1 last; first exact: transRs_rcosets. by exists (val H); rewrite ?orbit_refl // astab1Rs (setIidPr sHG). apply/subsetP=> y /setIP[Gy cHy]; apply: contraR neqHG => nt_y. rewrite (index1g sHG) //; apply/eqP; rewrite eqn_leq indexg_gt0 andbT. apply: leq_trans (regG y _); last by rewrite setDE 2!inE Gy nt_y /=. by rewrite /Hfix (setIidPl _) -1?astabC ?sub1set. have sHG: H \subset G by rewrite defH subsetIl. split. apply: contraNneq ntH => /= defG. suffices defS: S = [set u] by rewrite -(trivgP ffulG) /= defS defH. apply/eqP; rewrite eq_sym eqEcard sub1set Su. by rewrite -(atransP transG u Su) card_orbit -defH defG indexgg cards1. apply/normedTI_P; rewrite setD_eq0 subG1 normD1 subsetI sHG normG. split=> // x Gx; rewrite -setI_eq0 conjD1g defH inE Gx conjIg conjGid //. rewrite -setDIl -setIIr -astab1_act setDIl => /set0Pn[y /setIP[Gy /setD1P[_]]]. case/setIP; rewrite 2!(sameP astab1P afix1P) => cuy cuxy; apply/astab1P. apply: contraTeq (regG y Gy) => cu'x. rewrite (cardD1 u) (cardD1 (to u x)) inE Su cuy inE /= inE cu'x cuxy. by rewrite (actsP (atrans_acts transG)) ?Su. Qed. Section FrobeniusProperties. Variables G H K : {group gT}. Hypothesis frobG : [Frobenius G = K ><| H]. Lemma FrobeniusWker : [Frobenius G with kernel K]. Proof. by apply/existsP; exists H. Qed. Lemma FrobeniusWcompl : [Frobenius G with complement H]. Proof. by case/andP: frobG. Qed. Lemma FrobeniusW : [Frobenius G]. Proof. by apply/existsP; exists H; apply: FrobeniusWcompl. Qed. Lemma Frobenius_context : [/\ K ><| H = G, K :!=: 1, H :!=: 1, K \proper G & H \proper G]. Proof. have [/eqP defG neqHG ntH _] := and4P frobG; rewrite setD_eq0 subG1 in ntH. have ntK: K :!=: 1 by apply: contraNneq neqHG => K1; rewrite -defG K1 sdprod1g. rewrite properEcard properEneq neqHG; have /mulG_sub[-> ->] := sdprodW defG. by rewrite -(sdprod_card defG) ltn_Pmulr ?cardG_gt1. Qed. Lemma Frobenius_partition : partition (gval K |: (H^# :^: K)) G. Proof. have [/eqP defG _ tiHG] := and3P frobG; have [_ tiH1G /eqP defN] := and3P tiHG. have [[_ /mulG_sub[sKG sHG] nKH tiKH] mulHK] := (sdprodP defG, sdprodWC defG). set HG := H^# :^: K; set KHG := _ |: _. have defHG: HG = H^# :^: G. have: 'C_G[H^# | 'Js] * K = G by rewrite astab1Js defN mulHK. move/subgroup_transitiveP/atransP. by apply; rewrite ?atrans_orbit ?orbit_refl. have /and3P[defHK _ nzHG] := partition_normedTI tiHG. rewrite -defHG in defHK nzHG tiH1G. have [tiKHG HG'K]: trivIset KHG /\ gval K \notin HG. apply: trivIsetU1 => // _ /imsetP[x Kx ->]; rewrite -setI_eq0. by rewrite -(conjGid Kx) -conjIg setIDA tiKH setDv conj0g. rewrite /partition andbC tiKHG !inE negb_or nzHG eq_sym -card_gt0 cardG_gt0 /=. rewrite eqEcard; apply/andP; split. rewrite /cover big_setU1 //= subUset sKG -/(cover HG) (eqP defHK). by rewrite class_support_subG // (subset_trans _ sHG) ?subD1set. rewrite -(eqnP tiKHG) big_setU1 //= (eqnP tiH1G) (eqP defHK). rewrite (card_support_normedTI tiHG) -(Lagrange sHG) (cardsD1 1) group1 mulSn. by rewrite leq_add2r -mulHK indexMg -indexgI tiKH indexg1. Qed. Lemma Frobenius_cent1_ker : {in K^#, forall x, 'C_G[x] \subset K}. Proof. have [/eqP defG _ /normedTI_memJ_P[_ _ tiHG]] := and3P frobG. move=> x /setD1P[ntx Kx]; have [_ /mulG_sub[sKG _] _ tiKH] := sdprodP defG. have [/eqP <- _ _] := and3P Frobenius_partition; rewrite big_distrl /=. apply/bigcupsP=> _ /setU1P[|/imsetP[y Ky]] ->; first exact: subsetIl. apply: contraR ntx => /subsetPn[z]; rewrite inE mem_conjg => /andP[Hzy cxz] _. rewrite -(conjg_eq1 x y^-1) -in_set1 -set1gE -tiKH inE andbC. rewrite -(tiHG _ _ Hzy) ?(subsetP sKG) ?in_group // Ky andbT -conjJg. by rewrite /(z ^ x) (cent1P cxz) mulKg. Qed. Lemma Frobenius_reg_ker : semiregular K H. Proof. move=> x /setD1P[ntx Hx]. apply/trivgP/subsetP=> y /setIP[Ky cxy]; apply: contraR ntx => nty. have K1y: y \in K^# by rewrite inE nty. have [/eqP/sdprod_context[_ sHG _ _ tiKH] _] := andP frobG. suffices: x \in K :&: H by rewrite tiKH inE. by rewrite inE (subsetP (Frobenius_cent1_ker K1y)) // inE cent1C (subsetP sHG). Qed. Lemma Frobenius_reg_compl : semiregular H K. Proof. by apply: semiregular_sym; apply: Frobenius_reg_ker. Qed. Lemma Frobenius_dvd_ker1 : #|H| %| #|K|.-1. Proof. apply: regular_norm_dvd_pred Frobenius_reg_ker. by have[/sdprodP[]] := Frobenius_context. Qed. Lemma ltn_odd_Frobenius_ker : odd #|G| -> #|H|.*2 < #|K|. Proof. move/oddSg=> oddG. have [/sdprodW/mulG_sub[sKG sHG] ntK _ _ _] := Frobenius_context. by rewrite dvdn_double_ltn ?oddG ?cardG_gt1 ?Frobenius_dvd_ker1. Qed. Lemma Frobenius_index_dvd_ker1 : #|G : K| %| #|K|.-1. Proof. have[defG _ _ /andP[sKG _] _] := Frobenius_context. by rewrite -divgS // -(sdprod_card defG) mulKn ?Frobenius_dvd_ker1. Qed. Lemma Frobenius_coprime : coprime #|K| #|H|. Proof. by rewrite (coprime_dvdr Frobenius_dvd_ker1) ?coprimenP. Qed. Lemma Frobenius_trivg_cent : 'C_K(H) = 1. Proof. by apply: (cent_semiregular Frobenius_reg_ker); case: Frobenius_context. Qed. Lemma Frobenius_index_coprime : coprime #|K| #|G : K|. Proof. by rewrite (coprime_dvdr Frobenius_index_dvd_ker1) ?coprimenP. Qed. Lemma Frobenius_ker_Hall : Hall G K. Proof. have [_ _ _ /andP[sKG _] _] := Frobenius_context. by rewrite /Hall sKG Frobenius_index_coprime. Qed. Lemma Frobenius_compl_Hall : Hall G H. Proof. have [defG _ _ _ _] := Frobenius_context. by rewrite -(sdprod_Hall defG) Frobenius_ker_Hall. Qed. End FrobeniusProperties. Lemma normedTI_J x A G L : normedTI (A :^ x) (G :^ x) (L :^ x) = normedTI A G L. Proof. rewrite {1}/normedTI normJ -conjIg -(conj0g x) !(can_eq (conjsgK x)). congr [&& _, _ == _ & _]; rewrite /cover (reindex_inj (@conjsg_inj _ x)). by apply: eq_big => Hy; rewrite ?orbit_conjsg ?cardJg. by rewrite bigcupJ cardJg (eq_bigl _ _ (orbit_conjsg _ _ _ _)). Qed. Lemma FrobeniusJcompl x G H : [Frobenius G :^ x with complement H :^ x] = [Frobenius G with complement H]. Proof. by congr (_ && _); rewrite ?(can_eq (conjsgK x)) // -conjD1g normedTI_J. Qed. Lemma FrobeniusJ x G K H : [Frobenius G :^ x = K :^ x ><| H :^ x] = [Frobenius G = K ><| H]. Proof. by congr (_ && _); rewrite ?FrobeniusJcompl // -sdprodJ (can_eq (conjsgK x)). Qed. Lemma FrobeniusJker x G K : [Frobenius G :^ x with kernel K :^ x] = [Frobenius G with kernel K]. Proof. apply/existsP/existsP=> [] [H]; last by exists (H :^ x)%G; rewrite FrobeniusJ. by rewrite -(conjsgKV x H) FrobeniusJ; exists (H :^ x^-1)%G. Qed. Lemma FrobeniusJgroup x G : [Frobenius G :^ x] = [Frobenius G]. Proof. apply/existsP/existsP=> [] [H]. by rewrite -(conjsgKV x H) FrobeniusJcompl; exists (H :^ x^-1)%G. by exists (H :^ x)%G; rewrite FrobeniusJcompl. Qed. Lemma Frobenius_ker_dvd_ker1 G K : [Frobenius G with kernel K] -> #|G : K| %| #|K|.-1. Proof. by case/existsP=> H; apply: Frobenius_index_dvd_ker1. Qed. Lemma Frobenius_ker_coprime G K : [Frobenius G with kernel K] -> coprime #|K| #|G : K|. Proof. by case/existsP=> H; apply: Frobenius_index_coprime. Qed. Lemma Frobenius_semiregularP G K H : K ><| H = G -> K :!=: 1 -> H :!=: 1 -> reflect (semiregular K H) [Frobenius G = K ><| H]. Proof. move=> defG ntK ntH. apply: (iffP idP) => [|regG]; first exact: Frobenius_reg_ker. have [nsKG sHG defKH nKH tiKH]:= sdprod_context defG; have [sKG _]:= andP nsKG. apply/and3P; split; first by rewrite defG. by rewrite eqEcard sHG -(sdprod_card defG) -ltnNge ltn_Pmull ?cardG_gt1. apply/normedTI_memJ_P; rewrite setD_eq0 subG1 sHG -defKH -(normC nKH). split=> // z _ /setD1P[ntz Hz] /mulsgP[y x Hy Kx ->]; rewrite groupMl // !inE. rewrite conjg_eq1 ntz; apply/idP/idP=> [Hzxy | Hx]; last by rewrite !in_group. apply: (subsetP (sub1G H)); have Hzy: z ^ y \in H by apply: groupJ. rewrite -(regG (z ^ y)); last by apply/setD1P; rewrite conjg_eq1. rewrite inE Kx cent1C (sameP cent1P commgP) -in_set1 -[[set 1]]tiKH inE /=. rewrite andbC groupM ?groupV -?conjgM //= commgEr groupMr //. by rewrite memJ_norm ?(subsetP nKH) ?groupV. Qed. Lemma prime_FrobeniusP G K H : K :!=: 1 -> prime #|H| -> reflect (K ><| H = G /\ 'C_K(H) = 1) [Frobenius G = K ><| H]. Proof. move=> ntK H_pr; have ntH: H :!=: 1 by rewrite -cardG_gt1 prime_gt1. have [defG | not_sdG] := eqVneq (K ><| H) G; last first. by apply: (iffP andP) => [] [defG]; rewrite defG ?eqxx in not_sdG. apply: (iffP (Frobenius_semiregularP defG ntK ntH)) => [regH | [_ regH x]]. split=> //; have [x defH] := cyclicP (prime_cyclic H_pr). by rewrite defH cent_cycle regH // !inE defH cycle_id andbT -cycle_eq1 -defH. case/setD1P=> nt_x Hx; apply/trivgP; rewrite -regH setIS //= -cent_cycle. by rewrite centS // prime_meetG // (setIidPr _) ?cycle_eq1 ?cycle_subG. Qed. Lemma Frobenius_subl G K K1 H : K1 :!=: 1 -> K1 \subset K -> H \subset 'N(K1) -> [Frobenius G = K ><| H] -> [Frobenius K1 <*> H = K1 ><| H]. Proof. move=> ntK1 sK1K nK1H frobG; have [_ _ ntH _ _] := Frobenius_context frobG. apply/Frobenius_semiregularP=> //. by rewrite sdprodEY ?coprime_TIg ?(coprimeSg sK1K) ?(Frobenius_coprime frobG). by move=> x /(Frobenius_reg_ker frobG) cKx1; apply/trivgP; rewrite -cKx1 setSI. Qed. Lemma Frobenius_subr G K H H1 : H1 :!=: 1 -> H1 \subset H -> [Frobenius G = K ><| H] -> [Frobenius K <*> H1 = K ><| H1]. Proof. move=> ntH1 sH1H frobG; have [defG ntK _ _ _] := Frobenius_context frobG. apply/Frobenius_semiregularP=> //. have [_ _ /(subset_trans sH1H) nH1K tiHK] := sdprodP defG. by rewrite sdprodEY //; apply/trivgP; rewrite -tiHK setIS. by apply: sub_in1 (Frobenius_reg_ker frobG); apply/subsetP/setSD. Qed. Lemma Frobenius_kerP G K : reflect [/\ K :!=: 1, K \proper G, K <| G & {in K^#, forall x, 'C_G[x] \subset K}] [Frobenius G with kernel K]. Proof. apply: (iffP existsP) => [[H frobG] | [ntK ltKG nsKG regK]]. have [/sdprod_context[nsKG _ _ _ _] ntK _ ltKG _] := Frobenius_context frobG. by split=> //; apply: Frobenius_cent1_ker frobG. have /andP[sKG nKG] := nsKG. have hallK: Hall G K. rewrite /Hall sKG //= coprime_sym coprime_pi' //. apply: sub_pgroup (pgroup_pi K) => p; have [P sylP] := Sylow_exists p G. have [[sPG pP p'GiP] sylPK] := (and3P sylP, Hall_setI_normal nsKG sylP). rewrite -p_rank_gt0 -(rank_Sylow sylPK) rank_gt0 => ntPK. rewrite inE /= -p'natEpi // (pnat_dvd _ p'GiP) ?indexgS //. have /trivgPn[z]: P :&: K :&: 'Z(P) != 1. by rewrite meet_center_nil ?(pgroup_nil pP) ?(normalGI sPG nsKG). rewrite !inE -andbA -sub_cent1=> /and4P[_ Kz _ cPz] ntz. by apply: subset_trans (regK z _); [apply/subsetIP | apply/setD1P]. have /splitsP[H /complP[tiKH defG]] := SchurZassenhaus_split hallK nsKG. have [_ sHG] := mulG_sub defG; have nKH := subset_trans sHG nKG. exists H; apply/Frobenius_semiregularP; rewrite ?sdprodE //. by apply: contraNneq (proper_subn ltKG) => H1; rewrite -defG H1 mulg1. apply: semiregular_sym => x Kx; apply/trivgP; rewrite -tiKH. by rewrite subsetI subsetIl (subset_trans _ (regK x _)) ?setSI. Qed. Lemma set_Frobenius_compl G K H : K ><| H = G -> [Frobenius G with kernel K] -> [Frobenius G = K ><| H]. Proof. move=> defG /Frobenius_kerP[ntK ltKG _ regKG]. apply/Frobenius_semiregularP=> //. by apply: contraTneq ltKG => H_1; rewrite -defG H_1 sdprodg1 properxx. apply: semiregular_sym => y /regKG sCyK. have [_ sHG _ _ tiKH] := sdprod_context defG. by apply/trivgP; rewrite /= -(setIidPr sHG) setIAC -tiKH setSI. Qed. Lemma Frobenius_kerS G K G1 : G1 \subset G -> K \proper G1 -> [Frobenius G with kernel K] -> [Frobenius G1 with kernel K]. Proof. move=> sG1G ltKG1 /Frobenius_kerP[ntK _ /andP[_ nKG] regKG]. apply/Frobenius_kerP; rewrite /normal proper_sub // (subset_trans sG1G) //. by split=> // x /regKG; apply: subset_trans; rewrite setSI. Qed. Lemma Frobenius_action_kernel_def G H K sT S to : K ><| H = G -> @Frobenius_action _ G H sT S to -> K :=: 1 :|: [set x in G | 'Fix_(S | to)[x] == set0]. Proof. move=> defG FrobG. have partG: partition (gval K |: (H^# :^: K)) G. apply: Frobenius_partition; apply/andP; rewrite defG; split=> //. by apply/Frobenius_actionP; apply: hasFrobeniusAction FrobG. have{FrobG} [ffulG transG regG ntH [u Su defH]]:= FrobG. apply/setP=> x /[!inE]; have [-> | ntx] := eqVneq; first exact: group1. rewrite /= -(cover_partition partG) /cover. have neKHy y: gval K <> H^# :^ y. by move/setP/(_ 1); rewrite group1 conjD1g setD11. rewrite big_setU1 /= ?inE; last by apply/imsetP=> [[y _ /neKHy]]. have [nsKG sHG _ _ tiKH] := sdprod_context defG; have [sKG nKG]:= andP nsKG. symmetry; case Kx: (x \in K) => /=. apply/set0Pn=> [[v /setIP[Sv]]]; have [y Gy ->] := atransP2 transG Su Sv. rewrite -sub1set -astabC sub1set astab1_act mem_conjg => Hxy. case/negP: ntx; rewrite -in_set1 -(conjgKV y x) -mem_conjgV conjs1g -tiKH. by rewrite defH setIA inE -mem_conjg (setIidPl sKG) (normsP nKG) ?Kx. apply/andP=> [[/bigcupP[_ /imsetP[y Ky ->] Hyx] /set0Pn[]]]; exists (to u y). rewrite inE (actsP (atrans_acts transG)) ?(subsetP sKG) // Su. rewrite -sub1set -astabC sub1set astab1_act. by rewrite conjD1g defH conjIg !inE in Hyx; case/and3P: Hyx. Qed. End FrobeniusBasics. Arguments normedTI_P {gT A G L}. Arguments normedTI_memJ_P {gT A G L}. Arguments Frobenius_kerP {gT G K}. Lemma Frobenius_coprime_quotient (gT : finGroupType) (G K H N : {group gT}) : K ><| H = G -> N <| G -> coprime #|K| #|H| /\ H :!=: 1%g -> N \proper K /\ {in H^#, forall x, 'C_K[x] \subset N} -> [Frobenius G / N = (K / N) ><| (H / N)]%g. Proof. move=> defG nsNG [coKH ntH] [ltNK regH]. have [[sNK _] [_ /mulG_sub[sKG sHG] _ _]] := (andP ltNK, sdprodP defG). have [_ nNG] := andP nsNG; have nNH := subset_trans sHG nNG. apply/Frobenius_semiregularP; first exact: quotient_coprime_sdprod. - by rewrite quotient_neq1 ?(normalS _ sKG). - by rewrite -(isog_eq1 (quotient_isog _ _)) ?coprime_TIg ?(coprimeSg sNK). move=> _ /(subsetP (quotientD1 _ _))/morphimP[x nNx H1x ->]. rewrite -cent_cycle -quotient_cycle //=. rewrite -strongest_coprime_quotient_cent ?cycle_subG //. - by rewrite cent_cycle quotientS1 ?regH. - by rewrite subIset ?sNK. - rewrite (coprimeSg (subsetIl N _)) ?(coprimeSg sNK) ?(coprimegS _ coKH) //. by rewrite cycle_subG; case/setD1P: H1x. by rewrite orbC abelian_sol ?cycle_abelian. Qed. Section InjmFrobenius. Variables (gT rT : finGroupType) (D G : {group gT}) (f : {morphism D >-> rT}). Implicit Types (H K : {group gT}) (sGD : G \subset D) (injf : 'injm f). Lemma injm_Frobenius_compl H sGD injf : [Frobenius G with complement H] -> [Frobenius f @* G with complement f @* H]. Proof. case/andP=> neqGH /normedTI_P[nzH /subsetIP[sHG _] tiHG]. have sHD := subset_trans sHG sGD; have sH1D := subset_trans (subD1set H 1) sHD. apply/andP; rewrite (can_in_eq (injmK injf)) //; split=> //. apply/normedTI_P; rewrite normD1 -injmD1 // -!cards_eq0 card_injm // in nzH *. rewrite subsetI normG morphimS //; split=> // _ /morphimP[x Dx Gx ->] ti'fHx. rewrite mem_morphim ?tiHG //; apply: contra ti'fHx; rewrite -!setI_eq0 => tiHx. by rewrite -morphimJ // -injmI ?conj_subG // (eqP tiHx) morphim0. Qed. Lemma injm_Frobenius H K sGD injf : [Frobenius G = K ><| H] -> [Frobenius f @* G = f @* K ><| f @* H]. Proof. case/andP=> /eqP defG frobG. by apply/andP; rewrite (injm_sdprod _ injf defG) // eqxx injm_Frobenius_compl. Qed. Lemma injm_Frobenius_ker K sGD injf : [Frobenius G with kernel K] -> [Frobenius f @* G with kernel f @* K]. Proof. case/existsP=> H frobG; apply/existsP. by exists (f @* H)%G; apply: injm_Frobenius. Qed. Lemma injm_Frobenius_group sGD injf : [Frobenius G] -> [Frobenius f @* G]. Proof. case/existsP=> H frobG; apply/existsP; exists (f @* H)%G. exact: injm_Frobenius_compl. Qed. End InjmFrobenius. Theorem Frobenius_Ldiv (gT : finGroupType) (G : {group gT}) n : n %| #|G| -> n %| #|'Ldiv_n(G)|. Proof. move=> nG; move: {2}_.+1 (ltnSn (#|G| %/ n)) => mq. elim: mq => // mq IHm in gT G n nG *; case/dvdnP: nG => q oG. have [q_gt0 n_gt0] : 0 < q /\ 0 < n by apply/andP; rewrite -muln_gt0 -oG. rewrite ltnS oG mulnK // => leqm. have:= q_gt0; rewrite leq_eqVlt => /predU1P[q1 | lt1q]. rewrite -(mul1n n) q1 -oG (setIidPl _) //. by apply/subsetP=> x Gx; rewrite inE -order_dvdn order_dvdG. pose p := pdiv q; have pr_p: prime p by apply: pdiv_prime. have lt1p: 1 < p := prime_gt1 pr_p; have p_gt0 := ltnW lt1p. have{leqm} lt_qp_mq: q %/ p < mq by apply: leq_trans leqm; rewrite ltn_Pdiv. have: n %| #|'Ldiv_(p * n)(G)|. have: p * n %| #|G| by rewrite oG dvdn_pmul2r ?pdiv_dvd. move/IHm=> IH; apply: dvdn_trans (IH _); first exact: dvdn_mull. by rewrite oG divnMr. rewrite -(cardsID 'Ldiv_n()) dvdn_addl. rewrite -setIA ['Ldiv_n(_)](setIidPr _) //. by apply/subsetP=> x; rewrite !inE -!order_dvdn; apply: dvdn_mull. rewrite -setIDA; set A := _ :\: _. have pA x: x \in A -> #[x]`_p = (n`_p * p)%N. rewrite !inE -!order_dvdn => /andP[xn xnp]. rewrite !p_part // -expnSr; congr (p ^ _)%N; apply/eqP. rewrite eqn_leq -{1}addn1 -(pfactorK 1 pr_p) -lognM ?expn1 // mulnC. rewrite dvdn_leq_log ?muln_gt0 ?p_gt0 //= ltnNge; apply: contra xn => xn. move: xnp; rewrite -[#[x]](partnC p) //. rewrite !Gauss_dvd ?coprime_partC //; case/andP=> _. rewrite p_part ?pfactor_dvdn // xn Gauss_dvdr // coprime_sym. exact: pnat_coprime (pnat_id _) (part_pnat _ _). rewrite -(partnC p n_gt0) Gauss_dvd ?coprime_partC //; apply/andP; split. rewrite -sum1_card (partition_big_imset (@cycle _)) /=. apply: dvdn_sum => _ /imsetP[x /setIP[Gx Ax] ->]. rewrite (eq_bigl (generator <[x]>)) => [|y]. rewrite sum1dep_card -totient_gen -[#[x]](partnC p) //. rewrite totient_coprime ?coprime_partC // dvdn_mulr // . by rewrite (pA x Ax) p_part // -expnSr totient_pfactor // dvdn_mull. rewrite /generator eq_sym andbC; case xy: {+}(_ == _) => //. rewrite !inE -!order_dvdn in Ax *. by rewrite -cycle_subG /order -(eqP xy) cycle_subG Gx. rewrite -sum1_card (partition_big_imset (fun x => x.`_p ^: G)) /=. apply: dvdn_sum => _ /imsetP[x /setIP[Gx Ax] ->]. set y := x.`_p; have oy: #[y] = (n`_p * p)%N by rewrite order_constt pA. rewrite (partition_big (fun x => x.`_p) [in y ^: G]) /= => [|z]; last first. by case/andP=> _ /eqP <-; rewrite /= class_refl. pose G' := ('C_G[y] / <[y]>)%G; pose n' := gcdn #|G'| n`_p^'. have n'_gt0: 0 < n' by rewrite gcdn_gt0 cardG_gt0. rewrite (eq_bigr (fun _ => #|'Ldiv_n'(G')|)) => [|_ /imsetP[a Ga ->]]. rewrite sum_nat_const -index_cent1 indexgI. rewrite -(dvdn_pmul2l (cardG_gt0 'C_G[y])) mulnA LagrangeI. have oCy: #|'C_G[y]| = (#[y] * #|G'|)%N. rewrite card_quotient ?subcent1_cycle_norm // Lagrange //. by rewrite subcent1_cycle_sub ?groupX. rewrite oCy -mulnA -(muln_lcm_gcd #|G'|) -/n' mulnA dvdn_mul //. rewrite muln_lcmr -oCy order_constt pA // mulnAC partnC // dvdn_lcm. by rewrite cardSg ?subsetIl // mulnC oG dvdn_pmul2r ?pdiv_dvd. apply: IHm; [exact: dvdn_gcdl | apply: leq_ltn_trans lt_qp_mq]. rewrite -(@divnMr n`_p^') // -muln_lcm_gcd mulnC divnMl //. rewrite leq_divRL // divn_mulAC ?leq_divLR ?dvdn_mulr ?dvdn_lcmr //. rewrite dvdn_leq ?muln_gt0 ?q_gt0 //= mulnC muln_lcmr dvdn_lcm. rewrite -(@dvdn_pmul2l n`_p) // mulnA -oy -oCy mulnCA partnC // -oG. by rewrite cardSg ?subsetIl // dvdn_mul ?pdiv_dvd. pose h := [fun z => coset <[y]> (z ^ a^-1)]. pose h' := [fun Z : coset_of <[y]> => (y * (repr Z).`_p^') ^ a]. rewrite -sum1_card (reindex_onto h h') /= => [|Z]; last first. rewrite conjgK coset_kerl ?cycle_id ?morph_constt ?repr_coset_norm //. rewrite /= coset_reprK 2!inE -order_dvdn dvdn_gcd => /and3P[_ _ p'Z]. by apply: constt_p_elt (pnat_dvd p'Z _); apply: part_pnat. apply: eq_bigl => z; apply/andP/andP=> [[]|[]]. rewrite inE -andbA => /and3P[Gz Az _] /eqP zp_ya. have czy: z ^ a^-1 \in 'C[y]. rewrite -mem_conjg -normJ conjg_set1 -zp_ya. by apply/cent1P; apply: commuteX. have Nz: z ^ a^-1 \in 'N(<[y]>) by apply: subsetP czy; apply: norm_gen. have G'z: h z \in G' by rewrite mem_morphim //= inE groupJ // groupV. rewrite inE G'z inE -order_dvdn dvdn_gcd order_dvdG //=. rewrite /order -morphim_cycle // -quotientE card_quotient ?cycle_subG //. rewrite -(@dvdn_pmul2l #[y]) // Lagrange; last first. by rewrite /= cycleJ cycle_subG mem_conjgV -zp_ya mem_cycle. rewrite oy mulnAC partnC // [#|_|]orderJ; split. by rewrite !inE -!order_dvdn mulnC in Az; case/andP: Az. set Z := coset _ _; have NZ := repr_coset_norm Z; have:= coset_reprK Z. case/kercoset_rcoset=> {NZ}// _ /cycleP[i ->] ->{Z}. rewrite consttM; last exact/commute_sym/commuteX/cent1P. rewrite (constt1P _) ?p_eltNK 1?p_eltX ?p_elt_constt // mul1g. by rewrite conjMg consttJ conjgKV -zp_ya consttC. rewrite 2!inE -order_dvdn; set Z := coset _ _ => /andP[Cz n'Z] /eqP def_z. have Nz: z ^ a^-1 \in 'N(<[y]>). rewrite -def_z conjgK groupMr; first by rewrite -(cycle_subG y) normG. by rewrite groupX ?repr_coset_norm. have{Cz} /setIP[Gz Cz]: z ^ a^-1 \in 'C_G[y]. case/morphimP: Cz => u Nu Cu /kercoset_rcoset[] // _ /cycleP[i ->] ->. by rewrite groupMr // groupX // inE groupX //; apply/cent1P. have{def_z} zp_ya: z.`_p = y ^ a. rewrite -def_z consttJ consttM. rewrite constt_p_elt ?p_elt_constt //. by rewrite (constt1P _) ?p_eltNK ?p_elt_constt ?mulg1. apply: commute_sym; apply/cent1P. by rewrite -def_z conjgK groupMl // in Cz; apply/cent1P. have ozp: #[z ^ a^-1]`_p = #[y] by rewrite -order_constt consttJ zp_ya conjgK. split; rewrite zp_ya // -class_lcoset lcoset_id // eqxx andbT. rewrite -(conjgKV a z) !inE groupJ //= -!order_dvdn orderJ; apply/andP; split. apply: contra (partn_dvd p n_gt0) _. by rewrite ozp -(muln1 n`_p) oy dvdn_pmul2l // dvdn1 neq_ltn lt1p orbT. rewrite -(partnC p n_gt0) mulnCA mulnA -oy -(@partnC p #[_]) // ozp. apply dvdn_mul => //; apply: dvdn_trans (dvdn_trans n'Z (dvdn_gcdr _ _)). rewrite {2}/order -morphim_cycle // -quotientE card_quotient ?cycle_subG //. rewrite -(@dvdn_pmul2l #|<[z ^ a^-1]> :&: <[y]>|) ?cardG_gt0 // LagrangeI. rewrite -[#|<[_]>|](partnC p) ?order_gt0 // dvdn_pmul2r // ozp. by rewrite cardSg ?subsetIr. Qed.
NonUnitalNonAssocAlgebra.lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.Algebra.Algebra.NonUnitalHom import Mathlib.Algebra.Lie.Basic /-! # Lie algebras as non-unital, non-associative algebras The definition of Lie algebras uses the `Bracket` typeclass for multiplication whereas we have a separate `Mul` typeclass used for general algebras. It is useful to have a special typeclass for Lie algebras because: * it enables us to use the traditional notation `⁅x, y⁆` for the Lie multiplication, * associative algebras carry a natural Lie algebra structure via the ring commutator and so we need them to carry both `Mul` and `Bracket` simultaneously, * more generally, Poisson algebras (not yet defined) need both typeclasses. However there are times when it is convenient to be able to regard a Lie algebra as a general algebra and we provide some basic definitions for doing so here. ## Main definitions * `CommutatorRing` turns a Lie ring into a `NonUnitalNonAssocRing` by turning its `Bracket` (denoted `⁅ , ⁆`) into a `Mul` (denoted `*`). * `LieHom.toNonUnitalAlgHom` ## Tags lie algebra, non-unital, non-associative -/ universe u v w variable (R : Type u) (L : Type v) [CommRing R] [LieRing L] [LieAlgebra R L] /-- Type synonym for turning a `LieRing` into a `NonUnitalNonAssocRing`. A `LieRing` can be regarded as a `NonUnitalNonAssocRing` by turning its `Bracket` (denoted `⁅, ⁆`) into a `Mul` (denoted `*`). -/ def CommutatorRing (L : Type v) : Type v := L instance : NonUnitalNonAssocRing (CommutatorRing L) := LieRing.toNonUnitalNonAssocRing L namespace LieAlgebra instance (L : Type v) [Nonempty L] : Nonempty (CommutatorRing L) := ‹Nonempty L› instance (L : Type v) [Inhabited L] : Inhabited (CommutatorRing L) := ‹Inhabited L› instance : LieRing (CommutatorRing L) := show LieRing L by infer_instance instance : LieAlgebra R (CommutatorRing L) := show LieAlgebra R L by infer_instance /-- Regarding the `LieRing` of a `LieAlgebra` as a `NonUnitalNonAssocRing`, we can reinterpret the `smul_lie` law as an `IsScalarTower`. -/ instance isScalarTower : IsScalarTower R (CommutatorRing L) (CommutatorRing L) := ⟨smul_lie⟩ /-- Regarding the `LieRing` of a `LieAlgebra` as a `NonUnitalNonAssocRing`, we can reinterpret the `lie_smul` law as an `SMulCommClass`. -/ instance smulCommClass : SMulCommClass R (CommutatorRing L) (CommutatorRing L) := ⟨fun t x y => (lie_smul t x y).symm⟩ end LieAlgebra namespace LieHom variable {R L} variable {L₂ : Type w} [LieRing L₂] [LieAlgebra R L₂] /-- Regarding the `LieRing` of a `LieAlgebra` as a `NonUnitalNonAssocRing`, we can regard a `LieHom` as a `NonUnitalAlgHom`. -/ @[simps] def toNonUnitalAlgHom (f : L →ₗ⁅R⁆ L₂) : CommutatorRing L →ₙₐ[R] CommutatorRing L₂ := { f with toFun := f map_zero' := f.map_zero map_mul' := f.map_lie } theorem toNonUnitalAlgHom_injective : Function.Injective (toNonUnitalAlgHom : _ → CommutatorRing L →ₙₐ[R] CommutatorRing L₂) := fun _ _ h => ext <| NonUnitalAlgHom.congr_fun h end LieHom
ssrnat.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From Corelib Require Import PosDef. From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype. #[export] Set Warnings "-overwriting-delimiting-key". (* remove above line when requiring Rocq >= 9.0 *) (******************************************************************************) (* A version of arithmetic on nat (natural numbers) that is better suited to *) (* small scale reflection than the Coq Arith library. It contains an *) (* extensive equational theory (including, e.g., the AGM inequality), as well *) (* as a congruence tactic. *) (* The following operations and notations are provided: *) (* *) (* successor and predecessor *) (* n.+1, n.+2, n.+3, n.+4 and n.-1, n.-2 *) (* this frees the names "S" and "pred" *) (* *) (* basic arithmetic *) (* m + n, m - n, m * n *) (* Important: m - n denotes TRUNCATED subtraction: m - n = 0 if m <= n. *) (* The definitions use simpl never to prevent undesirable computation *) (* during simplification, but remain compatible with the ones provided in *) (* the Coq.Init.Peano prelude. *) (* For computation, a module NatTrec rebinds all arithmetic notations *) (* to less convenient but also less inefficient tail-recursive functions; *) (* the auxiliary functions used by these versions are flagged with %Nrec. *) (* Also, there is support for input and output of large nat values. *) (* Num 3 082 241 inputs the number 3082241 *) (* [Num of n] outputs the value n *) (* There are coercions num >-> BinNat.N >-> nat; ssrnat rebinds the scope *) (* delimiter for BinNat.N to %num, as it uses the shorter %N for its own *) (* notations (Peano notations are flagged with %coq_nat). *) (* *) (* doubling, halving, and parity *) (* n.*2, n./2, odd n, uphalf n, with uphalf n = n.+1./2 *) (* bool coerces to nat so we can write, e.g., n = odd n + n./2.*2. *) (* *) (* iteration *) (* iter n f x0 == f ( .. (f x0)) *) (* iteri n g x0 == g n.-1 (g ... (g 0 x0)) *) (* iterop n op x x0 == op x (... op x x) (n x's) or x0 if n = 0 *) (* *) (* exponentiation, factorial *) (* m ^ n, n`! *) (* m ^ 1 is convertible to m, and m ^ 2 to m * m *) (* *) (* comparison *) (* m <= n, m < n, m >= n, m > n, m == n, m <= n <= p, etc., *) (* comparisons are BOOLEAN operators, and m == n is the generic eqType *) (* operation. *) (* Most compatibility lemmas are stated as boolean equalities; this keeps *) (* the size of the library down. All the inequalities refer to the same *) (* constant "leq"; in particular m < n is identical to m.+1 <= n. *) (* *) (* -> patterns for contextual rewriting: *) (* leqLHS := (X in (X <= _)%N)%pattern *) (* leqRHS := (X in (_ <= X)%N)%pattern *) (* ltnLHS := (X in (X < _)%N)%pattern *) (* ltnRHS := (X in (_ < X)%N)%pattern *) (* *) (* conditionally strict inequality `leqif' *) (* m <= n ?= iff condition == (m <= n) and ((m == n) = condition) *) (* This is actually a pair of boolean equalities, so rewriting with an *) (* `leqif' lemma can affect several kinds of comparison. The transitivity *) (* lemma for leqif aggregates the conditions, allowing for arguments of *) (* the form ``m <= n <= p <= m, so equality holds throughout''. *) (* *) (* maximum and minimum *) (* maxn m n, minn m n *) (* Note that maxn m n = m + (n - m), due to the truncating subtraction. *) (* Absolute difference (linear distance) between nats is defined in the int *) (* library (in the int.IntDist sublibrary), with the syntax `|m - n|. The *) (* '-' in this notation is the signed integer difference. *) (* *) (* countable choice *) (* ex_minn : forall P : pred nat, (exists n, P n) -> nat *) (* This returns the smallest n such that P n holds. *) (* ex_maxn : forall (P : pred nat) m, *) (* (exists n, P n) -> (forall n, P n -> n <= m) -> nat *) (* This returns the largest n such that P n holds (given an explicit upper *) (* bound). *) (* *) (* This file adds the following suffix conventions to those documented in *) (* ssrbool.v and eqtype.v: *) (* A (infix) -- conjunction, as in *) (* ltn_neqAle : (m < n) = (m != n) && (m <= n). *) (* B -- subtraction, as in subBn : (m - n) - p = m - (n + p). *) (* D -- addition, as in mulnDl : (m + n) * p = m * p + n * p. *) (* M -- multiplication, as in expnMn : (m * n) ^ p = m ^ p * n ^ p. *) (* p (prefix) -- positive, as in *) (* eqn_pmul2l : m > 0 -> (m * n1 == m * n2) = (n1 == n2). *) (* P -- greater than 1, as in *) (* ltn_Pmull : 1 < n -> 0 < m -> m < n * m. *) (* S -- successor, as in addSn : n.+1 + m = (n + m).+1. *) (* V (infix) -- disjunction, as in *) (* leq_eqVlt : (m <= n) = (m == n) || (m < n). *) (* X - exponentiation, as in lognX : logn p (m ^ n) = logn p m * n in *) (* file prime.v (the suffix is not used in this file). *) (* Suffixes that abbreviate operations (D, B, M and X) are used to abbreviate *) (* second-rank operations in equational lemma names that describe left-hand *) (* sides (e.g., mulnDl); they are not used to abbreviate the main operation *) (* of relational lemmas (e.g., leq_add2l). *) (* For the asymmetrical exponentiation operator expn (m ^ n) a right suffix *) (* indicates an operation on the exponent, e.g., expnM : m ^ (n1 * n2) = ...; *) (* a trailing "n" is used to indicate the left operand, e.g., *) (* expnMn : (m1 * m2) ^ n = ... The operands of other operators are selected *) (* using the l/r suffixes. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope coq_nat_scope. (* Disable Coq prelude hints to improve proof script robustness. *) #[global] Remove Hints plus_n_O plus_n_Sm mult_n_O mult_n_Sm : core. (* Declare legacy Arith operators in new scope. *) Delimit Scope coq_nat_scope with coq_nat. Notation "m + n" := (plus m n) : coq_nat_scope. Notation "m - n" := (minus m n) : coq_nat_scope. Notation "m * n" := (mult m n) : coq_nat_scope. Notation "m <= n" := (le m n) : coq_nat_scope. Notation "m < n" := (lt m n) : coq_nat_scope. Notation "m >= n" := (ge m n) : coq_nat_scope. Notation "m > n" := (gt m n) : coq_nat_scope. (* Rebind scope delimiters, reserving a scope for the "recursive", *) (* i.e., unprotected version of operators. *) Delimit Scope N_scope with num. #[warning="-hiding-delimiting-key"] Delimit Scope nat_scope with N. (* Postfix notation for the successor and predecessor functions. *) (* SSreflect uses "pred" for the generic predicate type, and S as *) (* a local bound variable. *) Notation succn := Datatypes.S. Notation predn := Peano.pred. Notation "n .+1" := (succn n) (left associativity, format "n .+1") : nat_scope. Notation "n .+2" := n.+1.+1 (left associativity, format "n .+2") : nat_scope. Notation "n .+3" := n.+2.+1 (left associativity, format "n .+3") : nat_scope. Notation "n .+4" := n.+2.+2 (left associativity, format "n .+4") : nat_scope. Notation "n .-1" := (predn n) (left associativity, format "n .-1") : nat_scope. Notation "n .-2" := n.-1.-1 (left associativity, format "n .-2") : nat_scope. Lemma succnK : cancel succn predn. Proof. by []. Qed. Lemma succn_inj : injective succn. Proof. by move=> n m []. Qed. (* Predeclare postfix doubling/halving operators. *) Reserved Notation "n .*2" (left associativity, format "n .*2"). Reserved Notation "n ./2" (left associativity, format "n ./2"). (* Canonical comparison and eqType for nat. *) Fixpoint eqn m n {struct m} := match m, n with | 0, 0 => true | m'.+1, n'.+1 => eqn m' n' | _, _ => false end. Lemma eqnP : Equality.axiom eqn. Proof. move=> n m; apply: (iffP idP) => [|<-]; last by elim n. by elim: n m => [|n IHn] [|m] //= /IHn->. Qed. HB.instance Definition _ := hasDecEq.Build nat eqnP. Arguments eqn !m !n. Arguments eqnP {x y}. Lemma eqnE : eqn = eq_op. Proof. by []. Qed. Lemma eqSS m n : (m.+1 == n.+1) = (m == n). Proof. by []. Qed. Lemma nat_irrelevance (x y : nat) (E E' : x = y) : E = E'. Proof. exact: eq_irrelevance. Qed. (* Protected addition, with a more systematic set of lemmas. *) Definition addn := plus. Arguments addn : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use addn instead.")] Definition addn_rec := addn. Notation "m + n" := (addn m n) : nat_scope. Lemma addnE : addn = plus. Proof. by []. Qed. Lemma plusE : plus = addn. Proof. by []. Qed. Lemma add0n : left_id 0 addn. Proof. by []. Qed. Lemma addSn m n : m.+1 + n = (m + n).+1. Proof. by []. Qed. Lemma add1n n : 1 + n = n.+1. Proof. by []. Qed. Lemma addn0 : right_id 0 addn. Proof. by move=> n; apply/eqP; elim: n. Qed. Lemma addnS m n : m + n.+1 = (m + n).+1. Proof. by apply/eqP; elim: m. Qed. Lemma addSnnS m n : m.+1 + n = m + n.+1. Proof. by rewrite addnS. Qed. Lemma addnCA : left_commutative addn. Proof. by move=> m n p; elim: m => //= m; rewrite addnS => <-. Qed. Lemma addnC : commutative addn. Proof. by move=> m n; rewrite -[n in LHS]addn0 addnCA addn0. Qed. Lemma addn1 n : n + 1 = n.+1. Proof. by rewrite addnC. Qed. Lemma addnA : associative addn. Proof. by move=> m n p; rewrite (addnC n) addnCA addnC. Qed. Lemma addnAC : right_commutative addn. Proof. by move=> m n p; rewrite -!addnA (addnC n). Qed. Lemma addnCAC m n p : m + n + p = p + n + m. Proof. by rewrite addnC addnA addnAC. Qed. Lemma addnACl m n p: m + n + p = n + (p + m). Proof. by rewrite (addnC m) addnC addnCA. Qed. Lemma addnACA : interchange addn addn. Proof. by move=> m n p q; rewrite -!addnA (addnCA n). Qed. Lemma addn_eq0 m n : (m + n == 0) = (m == 0) && (n == 0). Proof. by case: m; case: n. Qed. Lemma addn_eq1 m n : (m + n == 1) = ((m == 1) && (n == 0)) || ((m == 0) && (n == 1)). Proof. by case: m n => [|[|m]] [|[|n]]. Qed. Lemma eqn_add2l p m n : (p + m == p + n) = (m == n). Proof. by elim: p. Qed. Lemma eqn_add2r p m n : (m + p == n + p) = (m == n). Proof. by rewrite -!(addnC p) eqn_add2l. Qed. Lemma addnI : right_injective addn. Proof. by move=> p m n Heq; apply: eqP; rewrite -(eqn_add2l p) Heq eqxx. Qed. Lemma addIn : left_injective addn. Proof. move=> p m n; rewrite -!(addnC p); apply addnI. Qed. Lemma addn2 m : m + 2 = m.+2. Proof. by rewrite addnC. Qed. Lemma add2n m : 2 + m = m.+2. Proof. by []. Qed. Lemma addn3 m : m + 3 = m.+3. Proof. by rewrite addnC. Qed. Lemma add3n m : 3 + m = m.+3. Proof. by []. Qed. Lemma addn4 m : m + 4 = m.+4. Proof. by rewrite addnC. Qed. Lemma add4n m : 4 + m = m.+4. Proof. by []. Qed. (* Protected, structurally decreasing subtraction, and basic lemmas. *) (* Further properties depend on ordering conditions. *) Definition subn := minus. Arguments subn : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use subn instead.")] Definition subn_rec := subn. Notation "m - n" := (subn m n) : nat_scope. Lemma subnE : subn = minus. Proof. by []. Qed. Lemma minusE : minus = subn. Proof. by []. Qed. Lemma sub0n : left_zero 0 subn. Proof. by []. Qed. Lemma subn0 : right_id 0 subn. Proof. by case. Qed. Lemma subnn : self_inverse 0 subn. Proof. by elim. Qed. Lemma subSS n m : m.+1 - n.+1 = m - n. Proof. by []. Qed. Lemma subn1 n : n - 1 = n.-1. Proof. by case: n => [|[]]. Qed. Lemma subn2 n : (n - 2)%N = n.-2. Proof. by case: n => [|[|[]]]. Qed. Lemma subnDl p m n : (p + m) - (p + n) = m - n. Proof. by elim: p. Qed. Lemma subnDr p m n : (m + p) - (n + p) = m - n. Proof. by rewrite -!(addnC p) subnDl. Qed. Lemma addnK n : cancel (addn^~ n) (subn^~ n). Proof. by move=> m; rewrite (subnDr n m 0) subn0. Qed. Lemma addKn n : cancel (addn n) (subn^~ n). Proof. by move=> m; rewrite addnC addnK. Qed. Lemma subSnn n : n.+1 - n = 1. Proof. exact (addnK n 1). Qed. Lemma subnDA m n p : n - (m + p) = (n - m) - p. Proof. by elim: m n => [|m IHm] []. Qed. Lemma subnAC : right_commutative subn. Proof. by move=> m n p; rewrite -!subnDA addnC. Qed. Lemma subnS m n : m - n.+1 = (m - n).-1. Proof. by rewrite -addn1 subnDA subn1. Qed. Lemma subSKn m n : (m.+1 - n).-1 = m - n. Proof. by rewrite -subnS. Qed. (* Integer ordering, and its interaction with the other operations. *) Definition leq m n := m - n == 0. Notation "m <= n" := (leq m n) : nat_scope. Notation "m < n" := (m.+1 <= n) : nat_scope. Notation "m >= n" := (n <= m) (only parsing) : nat_scope. Notation "m > n" := (n < m) (only parsing) : nat_scope. (* For sorting, etc. *) Definition geq := [rel m n | m >= n]. Definition ltn := [rel m n | m < n]. Definition gtn := [rel m n | m > n]. Notation "m <= n <= p" := ((m <= n) && (n <= p)) : nat_scope. Notation "m < n <= p" := ((m < n) && (n <= p)) : nat_scope. Notation "m <= n < p" := ((m <= n) && (n < p)) : nat_scope. Notation "m < n < p" := ((m < n) && (n < p)) : nat_scope. Lemma ltnS m n : (m < n.+1) = (m <= n). Proof. by []. Qed. Lemma leq0n n : 0 <= n. Proof. by []. Qed. Lemma ltn0Sn n : 0 < n.+1. Proof. by []. Qed. Lemma ltn0 n : n < 0 = false. Proof. by []. Qed. Lemma leqnn n : n <= n. Proof. by elim: n. Qed. #[global] Hint Resolve leqnn : core. Lemma ltnSn n : n < n.+1. Proof. by []. Qed. Lemma eq_leq m n : m = n -> m <= n. Proof. by move->. Qed. Lemma leqnSn n : n <= n.+1. Proof. by elim: n. Qed. #[global] Hint Resolve leqnSn : core. Lemma leq_pred n : n.-1 <= n. Proof. by case: n => /=. Qed. Lemma leqSpred n : n <= n.-1.+1. Proof. by case: n => /=. Qed. Lemma ltn_predL n : (n.-1 < n) = (0 < n). Proof. by case: n => [//|n]; rewrite ltnSn. Qed. Lemma ltn_predRL m n : (m < n.-1) = (m.+1 < n). Proof. by case: n => [//|n]; rewrite succnK. Qed. Lemma ltn_predK m n : m < n -> n.-1.+1 = n. Proof. by case: n. Qed. Lemma prednK n : 0 < n -> n.-1.+1 = n. Proof. exact: ltn_predK. Qed. Lemma leqNgt m n : (m <= n) = ~~ (n < m). Proof. by elim: m n => [|m IHm] []. Qed. Lemma leqVgt m n : (m <= n) || (n < m). Proof. by rewrite leqNgt orNb. Qed. Lemma ltnNge m n : (m < n) = ~~ (n <= m). Proof. by rewrite leqNgt. Qed. Lemma ltnn n : n < n = false. Proof. by rewrite ltnNge leqnn. Qed. Lemma leqn0 n : (n <= 0) = (n == 0). Proof. by case: n. Qed. Lemma lt0n n : (0 < n) = (n != 0). Proof. by case: n. Qed. Lemma lt0n_neq0 n : 0 < n -> n != 0. Proof. by case: n. Qed. Lemma eqn0Ngt n : (n == 0) = ~~ (n > 0). Proof. by case: n. Qed. Lemma neq0_lt0n n : (n == 0) = false -> 0 < n. Proof. by case: n. Qed. #[global] Hint Resolve lt0n_neq0 neq0_lt0n : core. Lemma eqn_leq m n : (m == n) = (m <= n <= m). Proof. by elim: m n => [|m IHm] []. Qed. Lemma anti_leq : antisymmetric leq. Proof. by move=> m n; rewrite -eqn_leq => /eqP. Qed. Lemma neq_ltn m n : (m != n) = (m < n) || (n < m). Proof. by rewrite eqn_leq negb_and orbC -!ltnNge. Qed. Lemma gtn_eqF m n : m < n -> n == m = false. Proof. by rewrite eqn_leq (leqNgt n) => ->. Qed. Lemma ltn_eqF m n : m < n -> m == n = false. Proof. by move/gtn_eqF; rewrite eq_sym. Qed. Lemma ltn_geF m n : m < n -> m >= n = false. Proof. by rewrite (leqNgt n) => ->. Qed. Lemma leq_gtF m n : m <= n -> m > n = false. Proof. by rewrite (ltnNge n) => ->. Qed. Lemma leq_eqVlt m n : (m <= n) = (m == n) || (m < n). Proof. by elim: m n => [|m IHm] []. Qed. Lemma ltn_neqAle m n : (m < n) = (m != n) && (m <= n). Proof. by rewrite ltnNge leq_eqVlt negb_or -leqNgt eq_sym. Qed. Lemma leq_trans n m p : m <= n -> n <= p -> m <= p. Proof. by elim: n m p => [|i IHn] [|m] [|p] //; apply: IHn m p. Qed. Lemma leq_ltn_trans n m p : m <= n -> n < p -> m < p. Proof. by move=> Hmn; apply: leq_trans. Qed. Lemma ltnW m n : m < n -> m <= n. Proof. exact: leq_trans. Qed. #[global] Hint Resolve ltnW : core. Lemma leqW m n : m <= n -> m <= n.+1. Proof. by move=> le_mn; apply: ltnW. Qed. Lemma ltn_trans n m p : m < n -> n < p -> m < p. Proof. by move=> lt_mn /ltnW; apply: leq_trans. Qed. Lemma leq_total m n : (m <= n) || (m >= n). Proof. by rewrite -implyNb -ltnNge; apply/implyP; apply: ltnW. Qed. (* Helper lemmas to support generalized induction over a nat measure. *) (* The idiom for a proof by induction over a measure Mxy : nat involving *) (* variables x, y, ... (e.g., size x + size y) is *) (* have [n leMn] := ubnP Mxy; elim: n => // n IHn in x y ... leMn ... *. *) (* after which the current goal (possibly modified by generalizations in the *) (* in ... part) can be proven with the extra context assumptions *) (* n : nat *) (* IHn : forall x y ..., Mxy < n -> ... -> the_initial_goal *) (* leMn : Mxy < n.+1 *) (* This is preferable to the legacy idiom relying on numerical occurrence *) (* selection, which is fragile if there can be multiple occurrences of x, y, *) (* ... in the measure expression Mxy (e.g., in #|y| with x : finType and *) (* y : {set x}). *) (* The leMn statement is convertible to Mxy <= n; if it is necessary to *) (* have _exactly_ leMn : Mxy <= n, the ltnSE helper lemma may be used as *) (* follows *) (* have [n] := ubnP Mxy; elim: n => // n IHn in x y ... * => /ltnSE-leMn. *) (* We also provide alternative helper lemmas for proofs where the upper *) (* bound appears in the goal, and we assume nonstrict (in)equality. *) (* In either case the proof will have to dispatch an Mxy = 0 case. *) (* have [n defM] := ubnPleq Mxy; elim: n => [|n IHn] in x y ... defM ... *. *) (* yields two subgoals, in which Mxy has been replaced by 0 and n.+1, *) (* with the extra assumption defM : Mxy <= 0 / Mxy <= n.+1, respectively. *) (* The second goal also has the inductive assumption *) (* IHn : forall x y ..., Mxy <= n -> ... -> the_initial_goal[n / Mxy]. *) (* Using ubnPgeq or ubnPeq instead of ubnPleq yields assumptions with *) (* Mxy >= 0/n.+1 or Mxy == 0/n.+1 instead of Mxy <= 0/n.+1, respectively. *) (* These introduce a different kind of induction; for example ubnPgeq M lets *) (* us remember that n < M throughout the induction. *) (* Finally, the ltn_ind lemma provides a generalized induction view for a *) (* property of a single integer (i.e., the case Mxy := x). *) Lemma ubnP m : {n | m < n}. Proof. by exists m.+1. Qed. Lemma ltnSE m n : m < n.+1 -> m <= n. Proof. by []. Qed. Variant ubn_leq_spec m : nat -> Type := UbnLeq n of m <= n : ubn_leq_spec m n. Variant ubn_geq_spec m : nat -> Type := UbnGeq n of m >= n : ubn_geq_spec m n. Variant ubn_eq_spec m : nat -> Type := UbnEq n of m == n : ubn_eq_spec m n. Lemma ubnPleq m : ubn_leq_spec m m. Proof. by []. Qed. Lemma ubnPgeq m : ubn_geq_spec m m. Proof. by []. Qed. Lemma ubnPeq m : ubn_eq_spec m m. Proof. by []. Qed. Lemma ltn_ind P : (forall n, (forall m, m < n -> P m) -> P n) -> forall n, P n. Proof. move=> accP M; have [n leMn] := ubnP M; elim: n => // n IHn in M leMn *. by apply/accP=> p /leq_trans/(_ leMn)/IHn. Qed. (* Link to the legacy comparison predicates. *) Lemma leP m n : reflect (m <= n)%coq_nat (m <= n). Proof. apply: (iffP idP); last by elim: n / => // n _ /leq_trans->. elim: n => [|n IHn]; first by case: m. by rewrite leq_eqVlt ltnS => /predU1P[<- // | /IHn]; right. Qed. Arguments leP {m n}. Lemma le_irrelevance m n le_mn1 le_mn2 : le_mn1 = le_mn2 :> (m <= n)%coq_nat. Proof. elim/ltn_ind: n => n IHn in le_mn1 le_mn2 *; set n1 := n in le_mn1 *. pose def_n : n = n1 := erefl n; transitivity (eq_ind _ _ le_mn2 _ def_n) => //. case: n1 / le_mn1 le_mn2 => [|n1 le_mn1] {n}[|n le_mn2] in (def_n) IHn *. - by rewrite [def_n]eq_axiomK. - by case/leP/idPn: (le_mn2); rewrite -def_n ltnn. - by case/leP/idPn: (le_mn1); rewrite def_n ltnn. case: def_n (def_n) => <-{n1} def_n in le_mn1 *. by rewrite [def_n]eq_axiomK /=; congr le_S; apply: IHn. Qed. Lemma ltP m n : reflect (m < n)%coq_nat (m < n). Proof. exact leP. Qed. Arguments ltP {m n}. Lemma lt_irrelevance m n lt_mn1 lt_mn2 : lt_mn1 = lt_mn2 :> (m < n)%coq_nat. Proof. exact: (@le_irrelevance m.+1). Qed. (* Monotonicity lemmas *) Lemma leq_add2l p m n : (p + m <= p + n) = (m <= n). Proof. by elim: p. Qed. Lemma ltn_add2l p m n : (p + m < p + n) = (m < n). Proof. by rewrite -addnS; apply: leq_add2l. Qed. Lemma leq_add2r p m n : (m + p <= n + p) = (m <= n). Proof. by rewrite -!(addnC p); apply: leq_add2l. Qed. Lemma ltn_add2r p m n : (m + p < n + p) = (m < n). Proof. exact: leq_add2r p m.+1 n. Qed. Lemma leq_add m1 m2 n1 n2 : m1 <= n1 -> m2 <= n2 -> m1 + m2 <= n1 + n2. Proof. by move=> le_mn1 le_mn2; rewrite (@leq_trans (m1 + n2)) ?leq_add2l ?leq_add2r. Qed. Lemma leq_addl m n : n <= m + n. Proof. exact: (leq_add2r n 0). Qed. Lemma leq_addr m n : n <= n + m. Proof. by rewrite addnC leq_addl. Qed. Lemma ltn_addl m n p : m < n -> m < p + n. Proof. by move/leq_trans=> -> //; apply: leq_addl. Qed. Lemma ltn_addr m n p : m < n -> m < n + p. Proof. by move/leq_trans=> -> //; apply: leq_addr. Qed. Lemma addn_gt0 m n : (0 < m + n) = (0 < m) || (0 < n). Proof. by rewrite !lt0n -negb_and addn_eq0. Qed. Lemma subn_gt0 m n : (0 < n - m) = (m < n). Proof. by elim: m n => [|m IHm] [|n] //; apply: IHm n. Qed. Lemma subn_eq0 m n : (m - n == 0) = (m <= n). Proof. by []. Qed. Lemma leq_subLR m n p : (m - n <= p) = (m <= n + p). Proof. by rewrite -subn_eq0 -subnDA. Qed. Lemma leq_subr m n : n - m <= n. Proof. by rewrite leq_subLR leq_addl. Qed. Lemma ltn_subrR m n : (n < n - m) = false. Proof. by rewrite ltnNge leq_subr. Qed. Lemma leq_subrR m n : (n <= n - m) = (m == 0) || (n == 0). Proof. by case: m n => [|m] [|n]; rewrite ?subn0 ?leqnn ?ltn_subrR. Qed. Lemma ltn_subrL m n : (n - m < n) = (0 < m) && (0 < n). Proof. by rewrite ltnNge leq_subrR negb_or !lt0n. Qed. Lemma subnKC m n : m <= n -> m + (n - m) = n. Proof. by elim: m n => [|m IHm] [|n] // /(IHm n) {2}<-. Qed. Lemma addnBn m n : m + (n - m) = m - n + n. Proof. by elim: m n => [|m IHm] [|n] //; rewrite addSn addnS IHm. Qed. Lemma subnK m n : m <= n -> (n - m) + m = n. Proof. by rewrite addnC; apply: subnKC. Qed. Lemma addnBA m n p : p <= n -> m + (n - p) = m + n - p. Proof. by move=> le_pn; rewrite -[in RHS](subnK le_pn) addnA addnK. Qed. Lemma addnBAC m n p : n <= m -> m - n + p = m + p - n. Proof. by move=> le_nm; rewrite addnC addnBA // addnC. Qed. Lemma addnBCA m n p : p <= m -> p <= n -> m + (n - p) = n + (m - p). Proof. by move=> le_pm le_pn; rewrite !addnBA // addnC. Qed. Lemma addnABC m n p : p <= m -> p <= n -> m + (n - p) = m - p + n. Proof. by move=> le_pm le_pn; rewrite addnBA // addnBAC. Qed. Lemma subnBA m n p : p <= n -> m - (n - p) = m + p - n. Proof. by move=> le_pn; rewrite -[in RHS](subnK le_pn) subnDr. Qed. Lemma subnA m n p : p <= n -> n <= m -> m - (n - p) = m - n + p. Proof. by move=> le_pn lr_nm; rewrite addnBAC // subnBA. Qed. Lemma subKn m n : m <= n -> n - (n - m) = m. Proof. by move/subnBA->; rewrite addKn. Qed. Lemma subSn m n : m <= n -> n.+1 - m = (n - m).+1. Proof. by rewrite -add1n => /addnBA <-. Qed. Lemma subnSK m n : m < n -> (n - m.+1).+1 = n - m. Proof. by move/subSn. Qed. Lemma addnCBA m n p : p <= n -> m + (n - p) = n + m - p. Proof. by move=> pn; rewrite (addnC n m) addnBA. Qed. Lemma addnBr_leq n p m : n <= p -> m + (n - p) = m. Proof. by rewrite -subn_eq0 => /eqP->; rewrite addn0. Qed. Lemma addnBl_leq m n p : m <= n -> m - n + p = p. Proof. by rewrite -subn_eq0; move/eqP => ->; rewrite add0n. Qed. Lemma subnDAC m n p : m - (n + p) = m - p - n. Proof. by rewrite addnC subnDA. Qed. Lemma subnCBA m n p : p <= n -> m - (n - p) = p + m - n. Proof. by move=> pn; rewrite addnC subnBA. Qed. Lemma subnBr_leq n p m : n <= p -> m - (n - p) = m. Proof. by rewrite -subn_eq0 => /eqP->; rewrite subn0. Qed. Lemma subnBl_leq m n p : m <= n -> (m - n) - p = 0. Proof. by rewrite -subn_eq0 => /eqP->. Qed. Lemma subnBAC m n p : p <= n -> n <= m -> m - (n - p) = p + (m - n). Proof. by move=> pn nm; rewrite subnA // addnC. Qed. Lemma subDnAC m n p : p <= n -> m + n - p = n - p + m. Proof. by move=> pn; rewrite addnC -addnBAC. Qed. Lemma subDnCA m n p : p <= m -> m + n - p = n + (m - p). Proof. by move=> pm; rewrite addnC -addnBA. Qed. Lemma subDnCAC m n p : m <= p -> m + n - p = n - (p - m). Proof. by move=> mp; rewrite addnC -subnBA. Qed. Lemma addnBC m n : m - n + n = n - m + m. Proof. by rewrite -[in RHS]addnBn addnC. Qed. Lemma addnCB m n : m - n + n = m + (n - m). Proof. by rewrite addnBC addnC. Qed. Lemma addBnAC m n p : n <= m -> m - n + p = p + m - n. Proof. by move=> nm; rewrite [p + m]addnC addnBAC. Qed. Lemma addBnCAC m n p : n <= m -> n <= p -> m - n + p = p - n + m. Proof. by move=> nm np; rewrite addnC addnBA // subDnCA // addnC. Qed. Lemma addBnA m n p : n <= m -> p <= n -> m - n + p = m - (n - p). Proof. by move=> nm pn; rewrite subnBA // -subDnAC // addnC. Qed. Lemma subBnAC m n p : m - n - p = m - (p + n). Proof. by rewrite addnC -subnDA. Qed. Lemma predn_sub m n : (m - n).-1 = (m.-1 - n). Proof. by case: m => // m; rewrite subSKn. Qed. Lemma leq_sub2r p m n : m <= n -> m - p <= n - p. Proof. by move=> le_mn; rewrite leq_subLR (leq_trans le_mn) // -leq_subLR. Qed. Lemma leq_sub2l p m n : m <= n -> p - n <= p - m. Proof. rewrite -(leq_add2r (p - m)) leq_subLR. by apply: leq_trans; rewrite -leq_subLR. Qed. Lemma leq_sub m1 m2 n1 n2 : m1 <= m2 -> n2 <= n1 -> m1 - n1 <= m2 - n2. Proof. by move/(leq_sub2r n1)=> le_m12 /(leq_sub2l m2); apply: leq_trans. Qed. Lemma ltn_sub2r p m n : p < n -> m < n -> m - p < n - p. Proof. by move/subnSK <-; apply: (@leq_sub2r p.+1). Qed. Lemma ltn_sub2l p m n : m < p -> m < n -> p - n < p - m. Proof. by move/subnSK <-; apply: leq_sub2l. Qed. Lemma ltn_subRL m n p : (n < p - m) = (m + n < p). Proof. by rewrite !ltnNge leq_subLR. Qed. Lemma leq_psubRL m n p : 0 < n -> (n <= p - m) = (m + n <= p). Proof. by move=> /prednK<-; rewrite ltn_subRL addnS. Qed. Lemma ltn_psubLR m n p : 0 < p -> (m - n < p) = (m < n + p). Proof. by move=> /prednK<-; rewrite ltnS leq_subLR addnS. Qed. Lemma leq_subRL m n p : m <= p -> (n <= p - m) = (m + n <= p). Proof. by move=> /subnKC{2}<-; rewrite leq_add2l. Qed. Lemma ltn_subLR m n p : n <= m -> (m - n < p) = (m < n + p). Proof. by move=> /subnKC{2}<-; rewrite ltn_add2l. Qed. Lemma leq_subCl m n p : (m - n <= p) = (m - p <= n). Proof. by rewrite !leq_subLR // addnC. Qed. Lemma ltn_subCr m n p : (p < m - n) = (n < m - p). Proof. by rewrite !ltn_subRL // addnC. Qed. Lemma leq_psubCr m n p : 0 < p -> 0 < n -> (p <= m - n) = (n <= m - p). Proof. by move=> p_gt0 n_gt0; rewrite !leq_psubRL // addnC. Qed. Lemma ltn_psubCl m n p : 0 < p -> 0 < n -> (m - n < p) = (m - p < n). Proof. by move=> p_gt0 n_gt0; rewrite !ltn_psubLR // addnC. Qed. Lemma leq_subCr m n p : n <= m -> p <= m -> (p <= m - n) = (n <= m - p). Proof. by move=> np pm; rewrite !leq_subRL // addnC. Qed. Lemma ltn_subCl m n p : n <= m -> p <= m -> (m - n < p) = (m - p < n). Proof. by move=> nm pm; rewrite !ltn_subLR // addnC. Qed. Lemma leq_sub2rE p m n : p <= n -> (m - p <= n - p) = (m <= n). Proof. by move=> pn; rewrite leq_subLR subnKC. Qed. Lemma leq_sub2lE m n p : n <= m -> (m - p <= m - n) = (n <= p). Proof. by move=> nm; rewrite leq_subCl subKn. Qed. Lemma ltn_sub2rE p m n : p <= m -> (m - p < n - p) = (m < n). Proof. by move=> pn; rewrite ltn_subRL addnC subnK. Qed. Lemma ltn_sub2lE m n p : p <= m -> (m - p < m - n) = (n < p). Proof. by move=> pm; rewrite ltn_subCr subKn. Qed. Lemma eqn_sub2rE p m n : p <= m -> p <= n -> (m - p == n - p) = (m == n). Proof. by move=> pm pn; rewrite !eqn_leq !leq_sub2rE. Qed. Lemma eqn_sub2lE m n p : p <= m -> n <= m -> (m - p == m - n) = (p == n). Proof. by move=> pm nm; rewrite !eqn_leq !leq_sub2lE // -!eqn_leq eq_sym. Qed. (* Max and min. *) Definition maxn m n := if m < n then n else m. Definition minn m n := if m < n then m else n. Lemma max0n : left_id 0 maxn. Proof. by case. Qed. Lemma maxn0 : right_id 0 maxn. Proof. by []. Qed. Lemma maxnC : commutative maxn. Proof. by rewrite /maxn; elim=> [|m ih] [] // n; rewrite !ltnS -!fun_if ih. Qed. Lemma maxnE m n : maxn m n = m + (n - m). Proof. rewrite /maxn; elim: m n => [|m ih] [|n]; rewrite ?addn0 //. by rewrite ltnS subSS addSn -ih; case: leq. Qed. Lemma maxnAC : right_commutative maxn. Proof. by move=> m n p; rewrite !maxnE -!addnA !subnDA -!maxnE maxnC. Qed. Lemma maxnA : associative maxn. Proof. by move=> m n p; rewrite !(maxnC m) maxnAC. Qed. Lemma maxnCA : left_commutative maxn. Proof. by move=> m n p; rewrite !maxnA (maxnC m). Qed. Lemma maxnACA : interchange maxn maxn. Proof. by move=> m n p q; rewrite -!maxnA (maxnCA n). Qed. Lemma maxn_idPl {m n} : reflect (maxn m n = m) (m >= n). Proof. by rewrite -subn_eq0 -(eqn_add2l m) addn0 -maxnE; apply: eqP. Qed. Lemma maxn_idPr {m n} : reflect (maxn m n = n) (m <= n). Proof. by rewrite maxnC; apply: maxn_idPl. Qed. Lemma maxnn : idempotent_op maxn. Proof. by move=> n; apply/maxn_idPl. Qed. Lemma leq_max m n1 n2 : (m <= maxn n1 n2) = (m <= n1) || (m <= n2). Proof. without loss le_n21: n1 n2 / n2 <= n1. by case/orP: (leq_total n2 n1) => le_n12; last rewrite maxnC orbC; apply. by rewrite (maxn_idPl le_n21) orb_idr // => /leq_trans->. Qed. Lemma leq_maxl m n : m <= maxn m n. Proof. by rewrite leq_max leqnn. Qed. Lemma leq_maxr m n : n <= maxn m n. Proof. by rewrite maxnC leq_maxl. Qed. Lemma gtn_max m n1 n2 : (m > maxn n1 n2) = (m > n1) && (m > n2). Proof. by rewrite !ltnNge leq_max negb_or. Qed. Lemma geq_max m n1 n2 : (m >= maxn n1 n2) = (m >= n1) && (m >= n2). Proof. by rewrite -ltnS gtn_max. Qed. Lemma maxnSS m n : maxn m.+1 n.+1 = (maxn m n).+1. Proof. by rewrite !maxnE. Qed. Lemma addn_maxl : left_distributive addn maxn. Proof. by move=> m1 m2 n; rewrite !maxnE subnDr addnAC. Qed. Lemma addn_maxr : right_distributive addn maxn. Proof. by move=> m n1 n2; rewrite !(addnC m) addn_maxl. Qed. Lemma subn_maxl : left_distributive subn maxn. Proof. move=> m n p; apply/eqP. rewrite eqn_leq !geq_max !leq_sub2r leq_max ?leqnn ?andbT ?orbT // /maxn. by case: (_ < _); rewrite leqnn // orbT. Qed. Lemma min0n : left_zero 0 minn. Proof. by case. Qed. Lemma minn0 : right_zero 0 minn. Proof. by []. Qed. Lemma minnC : commutative minn. Proof. by rewrite /minn; elim=> [|m ih] [] // n; rewrite !ltnS -!fun_if ih. Qed. Lemma addn_min_max m n : minn m n + maxn m n = m + n. Proof. by rewrite /minn /maxn; case: (m < n) => //; exact: addnC. Qed. Lemma minnE m n : minn m n = m - (m - n). Proof. by rewrite -(subnDl n) -maxnE -addn_min_max addnK minnC. Qed. Lemma minnAC : right_commutative minn. Proof. by move=> m n p; rewrite !minnE -subnDA subnAC -maxnE maxnC maxnE subnAC subnDA. Qed. Lemma minnA : associative minn. Proof. by move=> m n p; rewrite minnC minnAC (minnC n). Qed. Lemma minnCA : left_commutative minn. Proof. by move=> m n p; rewrite !minnA (minnC n). Qed. Lemma minnACA : interchange minn minn. Proof. by move=> m n p q; rewrite -!minnA (minnCA n). Qed. Lemma minn_idPl {m n} : reflect (minn m n = m) (m <= n). Proof. rewrite (sameP maxn_idPr eqP) -(eqn_add2l m) eq_sym -addn_min_max eqn_add2r. exact: eqP. Qed. Lemma minn_idPr {m n} : reflect (minn m n = n) (m >= n). Proof. by rewrite minnC; apply: minn_idPl. Qed. Lemma minnn : idempotent_op minn. Proof. by move=> n; apply/minn_idPl. Qed. Lemma leq_min m n1 n2 : (m <= minn n1 n2) = (m <= n1) && (m <= n2). Proof. wlog le_n21: n1 n2 / n2 <= n1. by case/orP: (leq_total n2 n1) => ?; last rewrite minnC andbC; apply. rewrite /minn ltnNge le_n21 /=; case le_m_n1: (m <= n1) => //=. apply/contraFF: le_m_n1 => /leq_trans; exact. Qed. Lemma gtn_min m n1 n2 : (m > minn n1 n2) = (m > n1) || (m > n2). Proof. by rewrite !ltnNge leq_min negb_and. Qed. Lemma geq_min m n1 n2 : (m >= minn n1 n2) = (m >= n1) || (m >= n2). Proof. by rewrite -ltnS gtn_min. Qed. Lemma ltn_min m n1 n2 : (m < minn n1 n2) = (m < n1) && (m < n2). Proof. exact: leq_min. Qed. Lemma geq_minl m n : minn m n <= m. Proof. by rewrite geq_min leqnn. Qed. Lemma geq_minr m n : minn m n <= n. Proof. by rewrite minnC geq_minl. Qed. Lemma addn_minr : right_distributive addn minn. Proof. by move=> m1 m2 n; rewrite !minnE subnDl addnBA ?leq_subr. Qed. Lemma addn_minl : left_distributive addn minn. Proof. by move=> m1 m2 n; rewrite -!(addnC n) addn_minr. Qed. Lemma subn_minl : left_distributive subn minn. Proof. move=> m n p; apply/eqP. rewrite eqn_leq !leq_min !leq_sub2r geq_min ?leqnn ?orbT //= /minn. by case: (_ < _); rewrite leqnn // orbT. Qed. Lemma minnSS m n : minn m.+1 n.+1 = (minn m n).+1. Proof. by rewrite -(addn_minr 1). Qed. (* Quasi-cancellation (really, absorption) lemmas *) Lemma maxnK m n : minn (maxn m n) m = m. Proof. exact/minn_idPr/leq_maxl. Qed. Lemma maxKn m n : minn n (maxn m n) = n. Proof. exact/minn_idPl/leq_maxr. Qed. Lemma minnK m n : maxn (minn m n) m = m. Proof. exact/maxn_idPr/geq_minl. Qed. Lemma minKn m n : maxn n (minn m n) = n. Proof. exact/maxn_idPl/geq_minr. Qed. (* Distributivity. *) Lemma maxn_minl : left_distributive maxn minn. Proof. move=> m1 m2 n; wlog le_m21: m1 m2 / m2 <= m1. move=> IH; case/orP: (leq_total m2 m1) => /IH //. by rewrite minnC [in R in _ = R]minnC. rewrite (minn_idPr le_m21); apply/esym/minn_idPr. by rewrite geq_max leq_maxr leq_max le_m21. Qed. Lemma maxn_minr : right_distributive maxn minn. Proof. by move=> m n1 n2; rewrite !(maxnC m) maxn_minl. Qed. Lemma minn_maxl : left_distributive minn maxn. Proof. by move=> m1 m2 n; rewrite maxn_minr !maxn_minl -minnA maxnn (maxnC _ n) !maxnK. Qed. Lemma minn_maxr : right_distributive minn maxn. Proof. by move=> m n1 n2; rewrite !(minnC m) minn_maxl. Qed. (* Comparison predicates. *) Variant leq_xor_gtn m n : nat -> nat -> nat -> nat -> bool -> bool -> Set := | LeqNotGtn of m <= n : leq_xor_gtn m n m m n n true false | GtnNotLeq of n < m : leq_xor_gtn m n n n m m false true. Lemma leqP m n : leq_xor_gtn m n (minn n m) (minn m n) (maxn n m) (maxn m n) (m <= n) (n < m). Proof. rewrite (minnC m) /minn (maxnC m) /maxn ltnNge. by case le_mn: (m <= n); constructor; rewrite //= ltnNge le_mn. Qed. Variant ltn_xor_geq m n : nat -> nat -> nat -> nat -> bool -> bool -> Set := | LtnNotGeq of m < n : ltn_xor_geq m n m m n n false true | GeqNotLtn of n <= m : ltn_xor_geq m n n n m m true false. Lemma ltnP m n : ltn_xor_geq m n (minn n m) (minn m n) (maxn n m) (maxn m n) (n <= m) (m < n). Proof. by case: leqP; constructor. Qed. Variant eqn0_xor_gt0 n : bool -> bool -> Set := | Eq0NotPos of n = 0 : eqn0_xor_gt0 n true false | PosNotEq0 of n > 0 : eqn0_xor_gt0 n false true. Lemma posnP n : eqn0_xor_gt0 n (n == 0) (0 < n). Proof. by case: n; constructor. Qed. Variant compare_nat m n : nat -> nat -> nat -> nat -> bool -> bool -> bool -> bool -> bool -> bool -> Set := | CompareNatLt of m < n : compare_nat m n m m n n false false false true false true | CompareNatGt of m > n : compare_nat m n n n m m false false true false true false | CompareNatEq of m = n : compare_nat m n m m m m true true true true false false. Lemma ltngtP m n : compare_nat m n (minn n m) (minn m n) (maxn n m) (maxn m n) (n == m) (m == n) (n <= m) (m <= n) (n < m) (m < n). Proof. rewrite !ltn_neqAle [_ == n]eq_sym; have [mn|] := ltnP m n. by rewrite ltnW // gtn_eqF //; constructor. rewrite leq_eqVlt; case: ltnP; rewrite ?(orbT, orbF) => //= lt_nm eq_nm. by rewrite ltn_eqF //; constructor. by rewrite eq_nm (eqP eq_nm); constructor. Qed. (* Eliminating the idiom for structurally decreasing compare and subtract. *) Lemma subn_if_gt T m n F (E : T) : (if m.+1 - n is m'.+1 then F m' else E) = (if n <= m then F (m - n) else E). Proof. by have [le_nm|/eqnP-> //] := leqP; rewrite -{1}(subnK le_nm) -addSn addnK. Qed. Notation leqLHS := (X in (X <= _)%N)%pattern. Notation leqRHS := (X in (_ <= X)%N)%pattern. Notation ltnLHS := (X in (X < _)%N)%pattern. Notation ltnRHS := (X in (_ < X)%N)%pattern. (* Getting a concrete value from an abstract existence proof. *) Section ExMinn. Variable P : pred nat. Hypothesis exP : exists n, P n. Inductive acc_nat i : Prop := AccNat0 of P i | AccNatS of acc_nat i.+1. Lemma find_ex_minn : {m | P m & forall n, P n -> n >= m}. Proof. have: forall n, P n -> n >= 0 by []. have: acc_nat 0. case exP => n; rewrite -(addn0 n); elim: n 0 => [|n IHn] j; first by left. by rewrite addSnnS; right; apply: IHn. move: 0; fix find_ex_minn 2 => m IHm m_lb; case Pm: (P m); first by exists m. apply: find_ex_minn m.+1 _ _ => [|n Pn]; first by case: IHm; rewrite ?Pm. by rewrite ltn_neqAle m_lb //; case: eqP Pm => // -> /idP[]. Qed. Definition ex_minn := s2val find_ex_minn. Inductive ex_minn_spec : nat -> Type := ExMinnSpec m of P m & (forall n, P n -> n >= m) : ex_minn_spec m. Lemma ex_minnP : ex_minn_spec ex_minn. Proof. by rewrite /ex_minn; case: find_ex_minn. Qed. End ExMinn. Section ExMaxn. Variables (P : pred nat) (m : nat). Hypotheses (exP : exists i, P i) (ubP : forall i, P i -> i <= m). Lemma ex_maxn_subproof : exists i, P (m - i). Proof. by case: exP => i Pi; exists (m - i); rewrite subKn ?ubP. Qed. Definition ex_maxn := m - ex_minn ex_maxn_subproof. Variant ex_maxn_spec : nat -> Type := ExMaxnSpec i of P i & (forall j, P j -> j <= i) : ex_maxn_spec i. Lemma ex_maxnP : ex_maxn_spec ex_maxn. Proof. rewrite /ex_maxn; case: ex_minnP => i Pmi min_i; split=> // j Pj. have le_i_mj: i <= m - j by rewrite min_i // subKn // ubP. rewrite -subn_eq0 subnBA ?(leq_trans le_i_mj) ?leq_subr //. by rewrite addnC -subnBA ?ubP. Qed. End ExMaxn. Lemma eq_ex_minn P Q exP exQ : P =1 Q -> @ex_minn P exP = @ex_minn Q exQ. Proof. move=> eqPQ; case: ex_minnP => m1 Pm1 m1_lb; case: ex_minnP => m2 Pm2 m2_lb. by apply/eqP; rewrite eqn_leq m1_lb (m2_lb, eqPQ) // -eqPQ. Qed. Lemma eq_ex_maxn (P Q : pred nat) m n exP ubP exQ ubQ : P =1 Q -> @ex_maxn P m exP ubP = @ex_maxn Q n exQ ubQ. Proof. move=> eqPQ; case: ex_maxnP => i Pi max_i; case: ex_maxnP => j Pj max_j. by apply/eqP; rewrite eqn_leq max_i ?eqPQ // max_j -?eqPQ. Qed. Section Iteration. Variable T : Type. Implicit Types m n : nat. Implicit Types x y : T. Implicit Types S : {pred T}. Definition iter n f x := let fix loop m := if m is i.+1 then f (loop i) else x in loop n. Definition iteri n f x := let fix loop m := if m is i.+1 then f i (loop i) else x in loop n. Definition iterop n op x := let f i y := if i is 0 then x else op x y in iteri n f. Lemma iterSr n f x : iter n.+1 f x = iter n f (f x). Proof. by elim: n => //= n <-. Qed. Lemma iterS n f x : iter n.+1 f x = f (iter n f x). Proof. by []. Qed. Lemma iterD n m f x : iter (n + m) f x = iter n f (iter m f x). Proof. by elim: n => //= n ->. Qed. Lemma iteriS n f x : iteri n.+1 f x = f n (iteri n f x). Proof. by []. Qed. Lemma iteropS idx n op x : iterop n.+1 op x idx = iter n (op x) x. Proof. by elim: n => //= n ->. Qed. Lemma eq_iter f f' : f =1 f' -> forall n, iter n f =1 iter n f'. Proof. by move=> eq_f n x; elim: n => //= n ->; rewrite eq_f. Qed. Lemma iter_fix n f x : f x = x -> iter n f x = x. Proof. by move=> fixf; elim: n => //= n ->. Qed. Lemma eq_iteri f f' : f =2 f' -> forall n, iteri n f =1 iteri n f'. Proof. by move=> eq_f n x; elim: n => //= n ->; rewrite eq_f. Qed. Lemma eq_iterop n op op' : op =2 op' -> iterop n op =2 iterop n op'. Proof. by move=> eq_op x; apply: eq_iteri; case. Qed. Lemma iter_in f S i : {homo f : x / x \in S} -> {homo iter i f : x / x \in S}. Proof. by move=> f_in x xS; elim: i => [|i /f_in]. Qed. End Iteration. Lemma iter_succn m n : iter n succn m = m + n. Proof. by rewrite addnC; elim: n => //= n ->. Qed. Lemma iter_succn_0 n : iter n succn 0 = n. Proof. exact: iter_succn. Qed. Lemma iter_predn m n : iter n predn m = m - n. Proof. by elim: n m => /= [|n IHn] m; rewrite ?subn0 // IHn subnS. Qed. (* Multiplication. *) Definition muln := mult. Arguments muln : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use muln instead.")] Definition muln_rec := muln. Notation "m * n" := (muln m n) : nat_scope. Lemma multE : mult = muln. Proof. by []. Qed. Lemma mulnE : muln = mult. Proof. by []. Qed. Lemma mul0n : left_zero 0 muln. Proof. by []. Qed. Lemma muln0 : right_zero 0 muln. Proof. by elim. Qed. Lemma mul1n : left_id 1 muln. Proof. exact: addn0. Qed. Lemma mulSn m n : m.+1 * n = n + m * n. Proof. by []. Qed. Lemma mulSnr m n : m.+1 * n = m * n + n. Proof. exact: addnC. Qed. Lemma mulnS m n : m * n.+1 = m + m * n. Proof. by elim: m => // m; rewrite !mulSn !addSn addnCA => ->. Qed. Lemma mulnSr m n : m * n.+1 = m * n + m. Proof. by rewrite addnC mulnS. Qed. Lemma iter_addn m n p : iter n (addn m) p = m * n + p. Proof. by elim: n => /= [|n ->]; rewrite ?muln0 // mulnS addnA. Qed. Lemma iter_addn_0 m n : iter n (addn m) 0 = m * n. Proof. by rewrite iter_addn addn0. Qed. Lemma muln1 : right_id 1 muln. Proof. by move=> n; rewrite mulnSr muln0. Qed. Lemma mulnC : commutative muln. Proof. by move=> m n; elim: m => [|m]; rewrite (muln0, mulnS) // mulSn => ->. Qed. Lemma mulnDl : left_distributive muln addn. Proof. by move=> m1 m2 n; elim: m1 => //= m1 IHm; rewrite -addnA -IHm. Qed. Lemma mulnDr : right_distributive muln addn. Proof. by move=> m n1 n2; rewrite !(mulnC m) mulnDl. Qed. Lemma mulnBl : left_distributive muln subn. Proof. move=> m n [|p]; first by rewrite !muln0. by elim: m n => // [m IHm] [|n] //; rewrite mulSn subnDl -IHm. Qed. Lemma mulnBr : right_distributive muln subn. Proof. by move=> m n p; rewrite !(mulnC m) mulnBl. Qed. Lemma mulnA : associative muln. Proof. by move=> m n p; elim: m => //= m; rewrite mulSn mulnDl => ->. Qed. Lemma mulnCA : left_commutative muln. Proof. by move=> m n1 n2; rewrite !mulnA (mulnC m). Qed. Lemma mulnAC : right_commutative muln. Proof. by move=> m n p; rewrite -!mulnA (mulnC n). Qed. Lemma mulnACA : interchange muln muln. Proof. by move=> m n p q; rewrite -!mulnA (mulnCA n). Qed. Lemma muln_eq0 m n : (m * n == 0) = (m == 0) || (n == 0). Proof. by case: m n => // m [|n] //=; rewrite muln0. Qed. Lemma muln_eq1 m n : (m * n == 1) = (m == 1) && (n == 1). Proof. by case: m n => [|[|m]] [|[|n]] //; rewrite muln0. Qed. Lemma muln_gt0 m n : (0 < m * n) = (0 < m) && (0 < n). Proof. by case: m n => // m [|n] //=; rewrite muln0. Qed. Lemma leq_pmull m n : n > 0 -> m <= n * m. Proof. by move/prednK <-; apply: leq_addr. Qed. Lemma leq_pmulr m n : n > 0 -> m <= m * n. Proof. by move/leq_pmull; rewrite mulnC. Qed. Lemma leq_mul2l m n1 n2 : (m * n1 <= m * n2) = (m == 0) || (n1 <= n2). Proof. by rewrite [LHS]/leq -mulnBr muln_eq0. Qed. Lemma leq_mul2r m n1 n2 : (n1 * m <= n2 * m) = (m == 0) || (n1 <= n2). Proof. by rewrite -!(mulnC m) leq_mul2l. Qed. Lemma leq_mul m1 m2 n1 n2 : m1 <= n1 -> m2 <= n2 -> m1 * m2 <= n1 * n2. Proof. move=> le_mn1 le_mn2; apply (@leq_trans (m1 * n2)). by rewrite leq_mul2l le_mn2 orbT. by rewrite leq_mul2r le_mn1 orbT. Qed. Lemma eqn_mul2l m n1 n2 : (m * n1 == m * n2) = (m == 0) || (n1 == n2). Proof. by rewrite eqn_leq !leq_mul2l -orb_andr -eqn_leq. Qed. Lemma eqn_mul2r m n1 n2 : (n1 * m == n2 * m) = (m == 0) || (n1 == n2). Proof. by rewrite eqn_leq !leq_mul2r -orb_andr -eqn_leq. Qed. Lemma leq_pmul2l m n1 n2 : 0 < m -> (m * n1 <= m * n2) = (n1 <= n2). Proof. by move/prednK=> <-; rewrite leq_mul2l. Qed. Arguments leq_pmul2l [m n1 n2]. Lemma leq_pmul2r m n1 n2 : 0 < m -> (n1 * m <= n2 * m) = (n1 <= n2). Proof. by move/prednK <-; rewrite leq_mul2r. Qed. Arguments leq_pmul2r [m n1 n2]. Lemma eqn_pmul2l m n1 n2 : 0 < m -> (m * n1 == m * n2) = (n1 == n2). Proof. by move/prednK <-; rewrite eqn_mul2l. Qed. Arguments eqn_pmul2l [m n1 n2]. Lemma eqn_pmul2r m n1 n2 : 0 < m -> (n1 * m == n2 * m) = (n1 == n2). Proof. by move/prednK <-; rewrite eqn_mul2r. Qed. Arguments eqn_pmul2r [m n1 n2]. Lemma ltn_mul2l m n1 n2 : (m * n1 < m * n2) = (0 < m) && (n1 < n2). Proof. by rewrite lt0n !ltnNge leq_mul2l negb_or. Qed. Lemma ltn_mul2r m n1 n2 : (n1 * m < n2 * m) = (0 < m) && (n1 < n2). Proof. by rewrite lt0n !ltnNge leq_mul2r negb_or. Qed. Lemma ltn_pmul2l m n1 n2 : 0 < m -> (m * n1 < m * n2) = (n1 < n2). Proof. by move/prednK <-; rewrite ltn_mul2l. Qed. Arguments ltn_pmul2l [m n1 n2]. Lemma ltn_pmul2r m n1 n2 : 0 < m -> (n1 * m < n2 * m) = (n1 < n2). Proof. by move/prednK <-; rewrite ltn_mul2r. Qed. Arguments ltn_pmul2r [m n1 n2]. Lemma ltn_Pmull m n : 1 < n -> 0 < m -> m < n * m. Proof. by move=> lt1n m_gt0; rewrite -[ltnLHS]mul1n ltn_pmul2r. Qed. Lemma ltn_Pmulr m n : 1 < n -> 0 < m -> m < m * n. Proof. by move=> lt1n m_gt0; rewrite mulnC ltn_Pmull. Qed. Lemma ltn_mull m1 m2 n1 n2 : 0 < n2 -> m1 < n1 -> m2 <= n2 -> m1 * m2 < n1 * n2. Proof. move=> n20 lt_mn1 le_mn2. rewrite (@leq_ltn_trans (m1 * n2)) ?leq_mul2l ?le_mn2 ?orbT//. by rewrite ltn_mul2r lt_mn1 n20. Qed. Lemma ltn_mulr m1 m2 n1 n2 : 0 < n1 -> m1 <= n1 -> m2 < n2 -> m1 * m2 < n1 * n2. Proof. by move=> ? ? ?; rewrite mulnC [ltnRHS]mulnC ltn_mull. Qed. Lemma ltn_mul m1 m2 n1 n2 : m1 < n1 -> m2 < n2 -> m1 * m2 < n1 * n2. Proof. by move=> ? lt2; rewrite ltn_mull ?(leq_ltn_trans _ lt2)// ltnW. Qed. Lemma maxnMr : right_distributive muln maxn. Proof. by case=> // m n1 n2; rewrite /maxn (fun_if (muln _)) ltn_pmul2l. Qed. Lemma maxnMl : left_distributive muln maxn. Proof. by move=> m1 m2 n; rewrite -!(mulnC n) maxnMr. Qed. Lemma minnMr : right_distributive muln minn. Proof. by case=> // m n1 n2; rewrite /minn (fun_if (muln _)) ltn_pmul2l. Qed. Lemma minnMl : left_distributive muln minn. Proof. by move=> m1 m2 n; rewrite -!(mulnC n) minnMr. Qed. Lemma iterM (T : Type) (n m : nat) (f : T -> T) : iter (n * m) f =1 iter n (iter m f). Proof. by move=> x; elim: n => //= n <-; rewrite mulSn iterD. Qed. (* Exponentiation. *) Definition expn m n := iterop n muln m 1. Arguments expn : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use expn instead.")] Definition expn_rec := expn. Notation "m ^ n" := (expn m n) : nat_scope. Lemma expnE n m : expn m n = iterop n muln m 1. Proof. by []. Qed. Lemma expn0 m : m ^ 0 = 1. Proof. by []. Qed. Lemma expn1 m : m ^ 1 = m. Proof. by []. Qed. Lemma expnS m n : m ^ n.+1 = m * m ^ n. Proof. by case: n; rewrite ?muln1. Qed. Lemma expnSr m n : m ^ n.+1 = m ^ n * m. Proof. by rewrite mulnC expnS. Qed. Lemma iter_muln m n p : iter n (muln m) p = m ^ n * p. Proof. by elim: n => /= [|n ->]; rewrite ?mul1n // expnS mulnA. Qed. Lemma iter_muln_1 m n : iter n (muln m) 1 = m ^ n. Proof. by rewrite iter_muln muln1. Qed. Lemma exp0n n : 0 < n -> 0 ^ n = 0. Proof. by case: n => [|[]]. Qed. Lemma exp1n n : 1 ^ n = 1. Proof. by elim: n => // n; rewrite expnS mul1n. Qed. Lemma expnD m n1 n2 : m ^ (n1 + n2) = m ^ n1 * m ^ n2. Proof. by elim: n1 => [|n1 IHn]; rewrite !(mul1n, expnS) // IHn mulnA. Qed. Lemma expnMn m1 m2 n : (m1 * m2) ^ n = m1 ^ n * m2 ^ n. Proof. by elim: n => // n IHn; rewrite !expnS IHn -!mulnA (mulnCA m2). Qed. Lemma expnM m n1 n2 : m ^ (n1 * n2) = (m ^ n1) ^ n2. Proof. elim: n1 => [|n1 IHn]; first by rewrite exp1n. by rewrite expnD expnS expnMn IHn. Qed. Lemma expnAC m n1 n2 : (m ^ n1) ^ n2 = (m ^ n2) ^ n1. Proof. by rewrite -!expnM mulnC. Qed. Lemma expn_gt0 m n : (0 < m ^ n) = (0 < m) || (n == 0). Proof. by case: m => [|m]; elim: n => //= n IHn; rewrite expnS // addn_gt0 IHn. Qed. Lemma expn_eq0 m e : (m ^ e == 0) = (m == 0) && (e > 0). Proof. by rewrite !eqn0Ngt expn_gt0 negb_or -lt0n. Qed. Lemma ltn_expl m n : 1 < m -> n < m ^ n. Proof. move=> m_gt1; elim: n => //= n; rewrite -(leq_pmul2l (ltnW m_gt1)) expnS. by apply: leq_trans; apply: ltn_Pmull. Qed. Lemma leq_exp2l m n1 n2 : 1 < m -> (m ^ n1 <= m ^ n2) = (n1 <= n2). Proof. move=> m_gt1; elim: n1 n2 => [|n1 IHn] [|n2] //; last 1 first. - by rewrite !expnS leq_pmul2l ?IHn // ltnW. - by rewrite expn_gt0 ltnW. by rewrite leqNgt (leq_trans m_gt1) // expnS leq_pmulr // expn_gt0 ltnW. Qed. Lemma ltn_exp2l m n1 n2 : 1 < m -> (m ^ n1 < m ^ n2) = (n1 < n2). Proof. by move=> m_gt1; rewrite !ltnNge leq_exp2l. Qed. Lemma eqn_exp2l m n1 n2 : 1 < m -> (m ^ n1 == m ^ n2) = (n1 == n2). Proof. by move=> m_gt1; rewrite !eqn_leq !leq_exp2l. Qed. Lemma expnI m : 1 < m -> injective (expn m). Proof. by move=> m_gt1 e1 e2 /eqP; rewrite eqn_exp2l // => /eqP. Qed. Lemma leq_pexp2l m n1 n2 : 0 < m -> n1 <= n2 -> m ^ n1 <= m ^ n2. Proof. by case: m => [|[|m]] // _; [rewrite !exp1n | rewrite leq_exp2l]. Qed. Lemma ltn_pexp2l m n1 n2 : 0 < m -> m ^ n1 < m ^ n2 -> n1 < n2. Proof. by case: m => [|[|m]] // _; [rewrite !exp1n | rewrite ltn_exp2l]. Qed. Lemma ltn_exp2r m n e : e > 0 -> (m ^ e < n ^ e) = (m < n). Proof. move=> e_gt0; apply/idP/idP=> [|ltmn]. rewrite !ltnNge; apply: contra => lemn. by elim: e {e_gt0} => // e IHe; rewrite !expnS leq_mul. by elim: e e_gt0 => // [[|e] IHe] _; rewrite ?expn1 // ltn_mul // IHe. Qed. Lemma leq_exp2r m n e : e > 0 -> (m ^ e <= n ^ e) = (m <= n). Proof. by move=> e_gt0; rewrite leqNgt ltn_exp2r // -leqNgt. Qed. Lemma eqn_exp2r m n e : e > 0 -> (m ^ e == n ^ e) = (m == n). Proof. by move=> e_gt0; rewrite !eqn_leq !leq_exp2r. Qed. Lemma expIn e : e > 0 -> injective (expn^~ e). Proof. by move=> e_gt1 m n /eqP; rewrite eqn_exp2r // => /eqP. Qed. Lemma iterX (T : Type) (n m : nat) (f : T -> T) : iter (n ^ m) f =1 iter m (iter n) f. Proof. elim: m => //= m ihm x; rewrite expnS iterM; exact/eq_iter. Qed. (* Factorial. *) Fixpoint factorial n := if n is n'.+1 then n * factorial n' else 1. Arguments factorial : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use factorial instead.")] Definition fact_rec := factorial. Notation "n `!" := (factorial n) (at level 1, format "n `!") : nat_scope. Lemma factE n : factorial n = if n is n'.+1 then n * factorial n' else 1. Proof. by case: n. Qed. Lemma fact0 : 0`! = 1. Proof. by []. Qed. Lemma factS n : (n.+1)`! = n.+1 * n`!. Proof. by []. Qed. Lemma fact_gt0 n : n`! > 0. Proof. by elim: n => //= n IHn; rewrite muln_gt0. Qed. Lemma fact_geq n : n <= n`!. Proof. by case: n => // n; rewrite factS -(addn1 n) leq_pmulr ?fact_gt0. Qed. Lemma ltn_fact m n : 0 < m -> m < n -> m`! < n`!. Proof. case: m n => // m n _; elim: n m => // n ih [|m] ?; last by rewrite ltn_mul ?ih. by rewrite -[_.+1]muln1 leq_mul ?fact_gt0. Qed. (* Parity and bits. *) Coercion nat_of_bool (b : bool) := if b then 1 else 0. Lemma leq_b1 (b : bool) : b <= 1. Proof. by case: b. Qed. Lemma addn_negb (b : bool) : ~~ b + b = 1. Proof. by case: b. Qed. Lemma eqb0 (b : bool) : (b == 0 :> nat) = ~~ b. Proof. by case: b. Qed. Lemma eqb1 (b : bool) : (b == 1 :> nat) = b. Proof. by case: b. Qed. Lemma lt0b (b : bool) : (b > 0) = b. Proof. by case: b. Qed. Lemma sub1b (b : bool) : 1 - b = ~~ b. Proof. by case: b. Qed. Lemma mulnb (b1 b2 : bool) : b1 * b2 = b1 && b2. Proof. by case: b1; case: b2. Qed. Lemma mulnbl (b : bool) n : b * n = (if b then n else 0). Proof. by case: b; rewrite ?mul1n. Qed. Lemma mulnbr (b : bool) n : n * b = (if b then n else 0). Proof. by rewrite mulnC mulnbl. Qed. Fixpoint odd n := if n is n'.+1 then ~~ odd n' else false. Lemma oddS n : odd n.+1 = ~~ odd n. Proof. by []. Qed. Lemma oddb (b : bool) : odd b = b. Proof. by case: b. Qed. Lemma oddD m n : odd (m + n) = odd m (+) odd n. Proof. by elim: m => [|m IHn] //=; rewrite -addTb IHn addbA addTb. Qed. Lemma oddB m n : n <= m -> odd (m - n) = odd m (+) odd n. Proof. by move=> le_nm; apply: (@canRL bool) (addbK _) _; rewrite -oddD subnK. Qed. Lemma oddN i m : odd m = false -> i <= m -> odd (m - i) = odd i. Proof. by move=> oddm /oddB ->; rewrite oddm. Qed. Lemma oddM m n : odd (m * n) = odd m && odd n. Proof. by elim: m => //= m IHm; rewrite oddD -addTb andb_addl -IHm. Qed. Lemma oddX m n : odd (m ^ n) = (n == 0) || odd m. Proof. by elim: n => // n IHn; rewrite expnS oddM {}IHn orbC; case odd. Qed. (* Doubling. *) Fixpoint double n := if n is n'.+1 then (double n').+2 else 0. Arguments double : simpl never. #[deprecated(since="mathcomp 2.3.0", note="Use double instead.")] Definition double_rec := double. Notation "n .*2" := (double n) : nat_scope. Lemma doubleE n : double n = if n is n'.+1 then (double n').+2 else 0. Proof. by case: n. Qed. Lemma double0 : 0.*2 = 0. Proof. by []. Qed. Lemma doubleS n : n.+1.*2 = n.*2.+2. Proof. by []. Qed. Lemma double_pred n : n.-1.*2 = n.*2.-2. Proof. by case: n. Qed. Lemma addnn n : n + n = n.*2. Proof. by apply: eqP; elim: n => // n IHn; rewrite addnS. Qed. Lemma mul2n m : 2 * m = m.*2. Proof. by rewrite mulSn mul1n addnn. Qed. Lemma muln2 m : m * 2 = m.*2. Proof. by rewrite mulnC mul2n. Qed. Lemma doubleD m n : (m + n).*2 = m.*2 + n.*2. Proof. by rewrite -!mul2n mulnDr. Qed. Lemma doubleB m n : (m - n).*2 = m.*2 - n.*2. Proof. by elim: m n => [|m IHm] []. Qed. Lemma leq_double m n : (m.*2 <= n.*2) = (m <= n). Proof. by rewrite /leq -doubleB; case (m - n). Qed. Lemma ltn_double m n : (m.*2 < n.*2) = (m < n). Proof. by rewrite 2!ltnNge leq_double. Qed. Lemma ltn_Sdouble m n : (m.*2.+1 < n.*2) = (m < n). Proof. by rewrite -doubleS leq_double. Qed. Lemma leq_Sdouble m n : (m.*2 <= n.*2.+1) = (m <= n). Proof. by rewrite leqNgt ltn_Sdouble -leqNgt. Qed. Lemma odd_double n : odd n.*2 = false. Proof. by rewrite -addnn oddD addbb. Qed. Lemma double_gt0 n : (0 < n.*2) = (0 < n). Proof. by case: n. Qed. Lemma double_eq0 n : (n.*2 == 0) = (n == 0). Proof. by case: n. Qed. Lemma doubleMl m n : (m * n).*2 = m.*2 * n. Proof. by rewrite -!mul2n mulnA. Qed. Lemma doubleMr m n : (m * n).*2 = m * n.*2. Proof. by rewrite -!muln2 mulnA. Qed. (* Halving. *) Fixpoint half (n : nat) : nat := if n is n'.+1 then uphalf n' else n with uphalf (n : nat) : nat := if n is n'.+1 then n'./2.+1 else n where "n ./2" := (half n) : nat_scope. Lemma uphalfE n : uphalf n = n.+1./2. Proof. by []. Qed. Lemma doubleK : cancel double half. Proof. by elim=> //= n ->. Qed. Definition half_double := doubleK. Definition double_inj := can_inj doubleK. Lemma uphalf_double n : uphalf n.*2 = n. Proof. by elim: n => //= n ->. Qed. Lemma uphalf_half n : uphalf n = odd n + n./2. Proof. by elim: n => //= n ->; rewrite addnA addn_negb. Qed. Lemma odd_double_half n : odd n + n./2.*2 = n. Proof. by elim: n => //= n {3}<-; rewrite uphalf_half doubleD; case (odd n). Qed. Lemma halfK n : n./2.*2 = n - odd n. Proof. by rewrite -[n in n - _]odd_double_half addnC addnK. Qed. Lemma uphalfK n : (uphalf n).*2 = odd n + n. Proof. by rewrite uphalfE halfK/=; case: odd; rewrite ?subn1. Qed. Lemma odd_halfK n : odd n -> n./2.*2 = n.-1. Proof. by rewrite halfK => ->; rewrite subn1. Qed. Lemma even_halfK n : ~~ odd n -> n./2.*2 = n. Proof. by rewrite halfK => /negbTE->; rewrite subn0. Qed. Lemma odd_uphalfK n : odd n -> (uphalf n).*2 = n.+1. Proof. by rewrite uphalfK => ->. Qed. Lemma even_uphalfK n : ~~ odd n -> (uphalf n).*2 = n. Proof. by rewrite uphalfK => /negbTE->. Qed. Lemma half_bit_double n (b : bool) : (b + n.*2)./2 = n. Proof. by case: b; rewrite /= (half_double, uphalf_double). Qed. Lemma halfD m n : (m + n)./2 = (odd m && odd n) + (m./2 + n./2). Proof. rewrite -[n in LHS]odd_double_half addnCA. rewrite -[m in LHS]odd_double_half -addnA -doubleD. by do 2!case: odd; rewrite /= ?add0n ?half_double ?uphalf_double. Qed. Lemma half_leq m n : m <= n -> m./2 <= n./2. Proof. by move/subnK <-; rewrite halfD addnA leq_addl. Qed. Lemma geq_half_double m n : (m <= n./2) = (m.*2 <= n). Proof. rewrite -[X in _.*2 <= X]odd_double_half. case: odd; last by rewrite leq_double. by case: m => // m; rewrite doubleS ltnS ltn_double. Qed. Lemma ltn_half_double m n : (m./2 < n) = (m < n.*2). Proof. by rewrite ltnNge geq_half_double -ltnNge. Qed. Lemma leq_half_double m n : (m./2 <= n) = (m <= n.*2.+1). Proof. by case: m => [|[|m]] //; rewrite ltnS ltn_half_double. Qed. Lemma gtn_half_double m n : (n < m./2) = (n.*2.+1 < m). Proof. by rewrite ltnNge leq_half_double -ltnNge. Qed. Lemma half_gt0 n : (0 < n./2) = (1 < n). Proof. by case: n => [|[]]. Qed. Lemma uphalf_leq m n : m <= n -> uphalf m <= uphalf n. Proof. move/subnK <-; rewrite !uphalf_half oddD halfD !addnA. by do 2 case: odd; apply: leq_addl. Qed. Lemma leq_uphalf_double m n : (uphalf m <= n) = (m <= n.*2). Proof. by rewrite uphalfE leq_half_double. Qed. Lemma geq_uphalf_double m n : (m <= uphalf n) = (m.*2 <= n.+1). Proof. by rewrite uphalfE geq_half_double. Qed. Lemma gtn_uphalf_double m n : (n < uphalf m) = (n.*2 < m). Proof. by rewrite uphalfE gtn_half_double. Qed. Lemma ltn_uphalf_double m n : (uphalf m < n) = (m.+1 < n.*2). Proof. by rewrite uphalfE ltn_half_double. Qed. Lemma uphalf_gt0 n : (0 < uphalf n) = (0 < n). Proof. by case: n. Qed. Lemma odd_geq m n : odd n -> (m <= n) = (m./2.*2 <= n). Proof. move=> odd_n; rewrite -[m in LHS]odd_double_half -[n]odd_double_half odd_n. by case: (odd m); rewrite // leq_Sdouble ltnS leq_double. Qed. Lemma odd_ltn m n : odd n -> (n < m) = (n < m./2.*2). Proof. by move=> odd_n; rewrite !ltnNge odd_geq. Qed. Lemma odd_gt0 n : odd n -> n > 0. Proof. by case: n. Qed. Lemma odd_gt2 n : odd n -> n > 1 -> n > 2. Proof. by move=> odd_n n_gt1; rewrite odd_geq. Qed. (* Squares and square identities. *) Lemma mulnn m : m * m = m ^ 2. Proof. by rewrite !expnS muln1. Qed. Lemma sqrnD m n : (m + n) ^ 2 = m ^ 2 + n ^ 2 + 2 * (m * n). Proof. rewrite -!mulnn mul2n mulnDr !mulnDl (mulnC n) -!addnA. by congr (_ + _); rewrite addnA addnn addnC. Qed. Lemma sqrnB m n : n <= m -> (m - n) ^ 2 = m ^ 2 + n ^ 2 - 2 * (m * n). Proof. move/subnK <-; rewrite addnK sqrnD -addnA -addnACA -addnA. by rewrite addnn -mul2n -mulnDr -mulnDl addnK. Qed. Lemma sqrnD_sub m n : n <= m -> (m + n) ^ 2 - 4 * (m * n) = (m - n) ^ 2. Proof. move=> le_nm; rewrite -[4]/(2 * 2) -mulnA mul2n -addnn subnDA. by rewrite sqrnD addnK sqrnB. Qed. Lemma subn_sqr m n : m ^ 2 - n ^ 2 = (m - n) * (m + n). Proof. by rewrite mulnBl !mulnDr addnC (mulnC m) subnDl. Qed. Lemma ltn_sqr m n : (m ^ 2 < n ^ 2) = (m < n). Proof. by rewrite ltn_exp2r. Qed. Lemma leq_sqr m n : (m ^ 2 <= n ^ 2) = (m <= n). Proof. by rewrite leq_exp2r. Qed. Lemma sqrn_gt0 n : (0 < n ^ 2) = (0 < n). Proof. exact: (ltn_sqr 0). Qed. Lemma eqn_sqr m n : (m ^ 2 == n ^ 2) = (m == n). Proof. by rewrite eqn_exp2r. Qed. Lemma sqrn_inj : injective (expn ^~ 2). Proof. exact: expIn. Qed. (* Almost strict inequality: an inequality that is strict unless some *) (* specific condition holds, such as the Cauchy-Schwartz or the AGM *) (* inequality (we only prove the order-2 AGM here; the general one *) (* requires sequences). *) (* We formalize the concept as a rewrite multirule, that can be used *) (* both to rewrite the non-strict inequality to true, and the equality *) (* to the specific condition (for strict inequalities use the ltn_neqAle *) (* lemma); in addition, the conditional equality also coerces to a *) (* non-strict one. *) Definition leqif m n C := ((m <= n) * ((m == n) = C))%type. Notation "m <= n ?= 'iff' C" := (leqif m n C) : nat_scope. Coercion leq_of_leqif m n C (H : m <= n ?= iff C) := H.1 : m <= n. Lemma leqifP m n C : reflect (m <= n ?= iff C) (if C then m == n else m < n). Proof. rewrite ltn_neqAle; apply: (iffP idP) => [|lte]; last by rewrite !lte; case C. by case C => [/eqP-> | /andP[/negPf]]; split=> //; apply: eqxx. Qed. Lemma leqif_refl m C : reflect (m <= m ?= iff C) C. Proof. by apply: (iffP idP) => [-> | <-] //; split; rewrite ?eqxx. Qed. Lemma leqif_trans m1 m2 m3 C12 C23 : m1 <= m2 ?= iff C12 -> m2 <= m3 ?= iff C23 -> m1 <= m3 ?= iff C12 && C23. Proof. move=> ltm12 ltm23; apply/leqifP; rewrite -ltm12. have [->|eqm12] := eqVneq; first by rewrite ltn_neqAle !ltm23 andbT; case C23. by rewrite (@leq_trans m2) ?ltm23 // ltn_neqAle eqm12 ltm12. Qed. Lemma mono_leqif f : {mono f : m n / m <= n} -> forall m n C, (f m <= f n ?= iff C) = (m <= n ?= iff C). Proof. by move=> f_mono m n C; rewrite /leqif !eqn_leq !f_mono. Qed. Lemma leqif_geq m n : m <= n -> m <= n ?= iff (m >= n). Proof. by move=> lemn; split=> //; rewrite eqn_leq lemn. Qed. Lemma leqif_eq m n : m <= n -> m <= n ?= iff (m == n). Proof. by []. Qed. Lemma geq_leqif a b C : a <= b ?= iff C -> (b <= a) = C. Proof. by case=> le_ab; rewrite eqn_leq le_ab. Qed. Lemma ltn_leqif a b C : a <= b ?= iff C -> (a < b) = ~~ C. Proof. by move=> le_ab; rewrite ltnNge (geq_leqif le_ab). Qed. Lemma ltnNleqif x y C : x <= y ?= iff ~~ C -> (x < y) = C. Proof. by move=> /ltn_leqif; rewrite negbK. Qed. Lemma eq_leqif x y C : x <= y ?= iff C -> (x == y) = C. Proof. by move=> /leqifP; case: C ltngtP => [] []. Qed. Lemma eqTleqif x y C : x <= y ?= iff C -> C -> x = y. Proof. by move=> /eq_leqif<-/eqP. Qed. Lemma leqif_add m1 n1 C1 m2 n2 C2 : m1 <= n1 ?= iff C1 -> m2 <= n2 ?= iff C2 -> m1 + m2 <= n1 + n2 ?= iff C1 && C2. Proof. rewrite -(mono_leqif (leq_add2r m2)) -(mono_leqif (leq_add2l n1) m2). exact: leqif_trans. Qed. Lemma leqif_mul m1 n1 C1 m2 n2 C2 : m1 <= n1 ?= iff C1 -> m2 <= n2 ?= iff C2 -> m1 * m2 <= n1 * n2 ?= iff (n1 * n2 == 0) || (C1 && C2). Proof. case: n1 => [|n1] le1; first by case: m1 le1 => [|m1] [_ <-] //. case: n2 m2 => [|n2] [|m2] /=; try by case=> // _ <-; rewrite !muln0 ?andbF. have /leq_pmul2l-/mono_leqif<-: 0 < n1.+1 by []. by apply: leqif_trans; have /leq_pmul2r-/mono_leqif->: 0 < m2.+1. Qed. Lemma nat_Cauchy m n : 2 * (m * n) <= m ^ 2 + n ^ 2 ?= iff (m == n). Proof. without loss le_nm: m n / n <= m. by have [?|/ltnW ?] := leqP n m; last rewrite eq_sym addnC (mulnC m); apply. apply/leqifP; have [-> | ne_mn] := eqVneq; first by rewrite addnn mul2n. by rewrite -subn_gt0 -sqrnB // sqrn_gt0 subn_gt0 ltn_neqAle eq_sym ne_mn. Qed. Lemma nat_AGM2 m n : 4 * (m * n) <= (m + n) ^ 2 ?= iff (m == n). Proof. rewrite -[4]/(2 * 2) -mulnA mul2n -addnn sqrnD; apply/leqifP. by rewrite ltn_add2r eqn_add2r ltn_neqAle !nat_Cauchy; case: eqVneq. Qed. Section ContraLeq. Implicit Types (b : bool) (m n : nat) (P : Prop). Lemma contraTleq b m n : (n < m -> ~~ b) -> (b -> m <= n). Proof. by rewrite ltnNge; apply: contraTT. Qed. Lemma contraTltn b m n : (n <= m -> ~~ b) -> (b -> m < n). Proof. by rewrite ltnNge; apply: contraTN. Qed. Lemma contraPleq P m n : (n < m -> ~ P) -> (P -> m <= n). Proof. by rewrite ltnNge; apply: contraPT. Qed. Lemma contraPltn P m n : (n <= m -> ~ P) -> (P -> m < n). Proof. by rewrite ltnNge; apply: contraPN. Qed. Lemma contraNleq b m n : (n < m -> b) -> (~~ b -> m <= n). Proof. by rewrite ltnNge; apply: contraNT. Qed. Lemma contraNltn b m n : (n <= m -> b) -> (~~ b -> m < n). Proof. by rewrite ltnNge; apply: contraNN. Qed. Lemma contra_not_leq P m n : (n < m -> P) -> (~ P -> m <= n). Proof. by rewrite ltnNge; apply: contra_notT. Qed. Lemma contra_not_ltn P m n : (n <= m -> P) -> (~ P -> m < n). Proof. by rewrite ltnNge; apply: contra_notN. Qed. Lemma contraFleq b m n : (n < m -> b) -> (b = false -> m <= n). Proof. by rewrite ltnNge; apply: contraFT. Qed. Lemma contraFltn b m n : (n <= m -> b) -> (b = false -> m < n). Proof. by rewrite ltnNge; apply: contraFN. Qed. Lemma contra_leqT b m n : (~~ b -> m < n) -> (n <= m -> b). Proof. by rewrite ltnNge; apply: contraTT. Qed. Lemma contra_ltnT b m n : (~~ b -> m <= n) -> (n < m -> b). Proof. by rewrite ltnNge; apply: contraNT. Qed. Lemma contra_leqN b m n : (b -> m < n) -> (n <= m -> ~~ b). Proof. by rewrite ltnNge; apply: contraTN. Qed. Lemma contra_ltnN b m n : (b -> m <= n) -> (n < m -> ~~ b). Proof. by rewrite ltnNge; apply: contraNN. Qed. Lemma contra_leq_not P m n : (P -> m < n) -> (n <= m -> ~ P). Proof. by rewrite ltnNge; apply: contraTnot. Qed. Lemma contra_ltn_not P m n : (P -> m <= n) -> (n < m -> ~ P). Proof. by rewrite ltnNge; apply: contraNnot. Qed. Lemma contra_leqF b m n : (b -> m < n) -> (n <= m -> b = false). Proof. by rewrite ltnNge; apply: contraTF. Qed. Lemma contra_ltnF b m n : (b -> m <= n) -> (n < m -> b = false). Proof. by rewrite ltnNge; apply: contraNF. Qed. Lemma contra_leq m n p q : (q < p -> n < m) -> (m <= n -> p <= q). Proof. by rewrite !ltnNge; apply: contraTT. Qed. Lemma contra_leq_ltn m n p q : (q <= p -> n < m) -> (m <= n -> p < q). Proof. by rewrite !ltnNge; apply: contraTN. Qed. Lemma contra_ltn_leq m n p q : (q < p -> n <= m) -> (m < n -> p <= q). Proof. by rewrite !ltnNge; apply: contraNT. Qed. Lemma contra_ltn m n p q : (q <= p -> n <= m) -> (m < n -> p < q). Proof. by rewrite !ltnNge; apply: contraNN. Qed. End ContraLeq. Section Monotonicity. Variable T : Type. Lemma homo_ltn_in (D : {pred nat}) (f : nat -> T) (r : T -> T -> Prop) : (forall y x z, r x y -> r y z -> r x z) -> {in D &, forall i j k, i < k < j -> k \in D} -> {in D, forall i, i.+1 \in D -> r (f i) (f i.+1)} -> {in D &, {homo f : i j / i < j >-> r i j}}. Proof. move=> r_trans Dcx r_incr i j iD jD lt_ij; move: (lt_ij) (jD) => /subnKC<-. elim: (_ - _) => [|k ihk]; first by rewrite addn0 => Dsi; apply: r_incr. move=> DSiSk [: DSik]; apply: (r_trans _ _ _ (ihk _)); rewrite ?addnS. by abstract: DSik; apply: (Dcx _ _ iD DSiSk); rewrite ltn_addr ?addnS /=. by apply: r_incr; rewrite -?addnS. Qed. Lemma homo_ltn (f : nat -> T) (r : T -> T -> Prop) : (forall y x z, r x y -> r y z -> r x z) -> (forall i, r (f i) (f i.+1)) -> {homo f : i j / i < j >-> r i j}. Proof. by move=> /(@homo_ltn_in predT f) fr fS i j; apply: fr. Qed. Lemma homo_leq_in (D : {pred nat}) (f : nat -> T) (r : T -> T -> Prop) : (forall x, r x x) -> (forall y x z, r x y -> r y z -> r x z) -> {in D &, forall i j k, i < k < j -> k \in D} -> {in D, forall i, i.+1 \in D -> r (f i) (f i.+1)} -> {in D &, {homo f : i j / i <= j >-> r i j}}. Proof. move=> r_refl r_trans Dcx /(homo_ltn_in r_trans Dcx) lt_r i j iD jD. case: ltngtP => [? _||->] //; exact: lt_r. Qed. Lemma homo_leq (f : nat -> T) (r : T -> T -> Prop) : (forall x, r x x) -> (forall y x z, r x y -> r y z -> r x z) -> (forall i, r (f i) (f i.+1)) -> {homo f : i j / i <= j >-> r i j}. Proof. by move=> rrefl /(@homo_leq_in predT f r) fr fS i j; apply: fr. Qed. Section NatToNat. Variable (f : nat -> nat). (****************************************************************************) (* This listing of "Let"s factor out the required premises for the *) (* subsequent lemmas, putting them in the context so that "done" solves the *) (* goals quickly *) (****************************************************************************) Let ltn_neqAle := ltn_neqAle. Let gtn_neqAge x y : (y < x) = (x != y) && (y <= x). Proof. by rewrite ltn_neqAle eq_sym. Qed. Let anti_leq := anti_leq. Let anti_geq : antisymmetric geq. Proof. by move=> m n /=; rewrite andbC => /anti_leq. Qed. Let leq_total := leq_total. Lemma ltnW_homo : {homo f : m n / m < n} -> {homo f : m n / m <= n}. Proof. exact: homoW. Qed. Lemma inj_homo_ltn : injective f -> {homo f : m n / m <= n} -> {homo f : m n / m < n}. Proof. exact: inj_homo. Qed. Lemma ltnW_nhomo : {homo f : m n /~ m < n} -> {homo f : m n /~ m <= n}. Proof. exact: homoW. Qed. Lemma inj_nhomo_ltn : injective f -> {homo f : m n /~ m <= n} -> {homo f : m n /~ m < n}. Proof. exact: inj_homo. Qed. Lemma incn_inj : {mono f : m n / m <= n} -> injective f. Proof. exact: mono_inj. Qed. Lemma decn_inj : {mono f : m n /~ m <= n} -> injective f. Proof. exact: mono_inj. Qed. Lemma leqW_mono : {mono f : m n / m <= n} -> {mono f : m n / m < n}. Proof. exact: anti_mono. Qed. Lemma leqW_nmono : {mono f : m n /~ m <= n} -> {mono f : m n /~ m < n}. Proof. exact: anti_mono. Qed. Lemma leq_mono : {homo f : m n / m < n} -> {mono f : m n / m <= n}. Proof. exact: total_homo_mono. Qed. Lemma leq_nmono : {homo f : m n /~ m < n} -> {mono f : m n /~ m <= n}. Proof. exact: total_homo_mono. Qed. Variables (D D' : {pred nat}). Lemma ltnW_homo_in : {in D & D', {homo f : m n / m < n}} -> {in D & D', {homo f : m n / m <= n}}. Proof. exact: homoW_in. Qed. Lemma ltnW_nhomo_in : {in D & D', {homo f : m n /~ m < n}} -> {in D & D', {homo f : m n /~ m <= n}}. Proof. exact: homoW_in. Qed. Lemma inj_homo_ltn_in : {in D & D', injective f} -> {in D & D', {homo f : m n / m <= n}} -> {in D & D', {homo f : m n / m < n}}. Proof. exact: inj_homo_in. Qed. Lemma inj_nhomo_ltn_in : {in D & D', injective f} -> {in D & D', {homo f : m n /~ m <= n}} -> {in D & D', {homo f : m n /~ m < n}}. Proof. exact: inj_homo_in. Qed. Lemma incn_inj_in : {in D &, {mono f : m n / m <= n}} -> {in D &, injective f}. Proof. exact: mono_inj_in. Qed. Lemma decn_inj_in : {in D &, {mono f : m n /~ m <= n}} -> {in D &, injective f}. Proof. exact: mono_inj_in. Qed. Lemma leqW_mono_in : {in D &, {mono f : m n / m <= n}} -> {in D &, {mono f : m n / m < n}}. Proof. exact: anti_mono_in. Qed. Lemma leqW_nmono_in : {in D &, {mono f : m n /~ m <= n}} -> {in D &, {mono f : m n /~ m < n}}. Proof. exact: anti_mono_in. Qed. Lemma leq_mono_in : {in D &, {homo f : m n / m < n}} -> {in D &, {mono f : m n / m <= n}}. Proof. exact: total_homo_mono_in. Qed. Lemma leq_nmono_in : {in D &, {homo f : m n /~ m < n}} -> {in D &, {mono f : m n /~ m <= n}}. Proof. exact: total_homo_mono_in. Qed. End NatToNat. End Monotonicity. Lemma leq_pfact : {in [pred n | 0 < n] &, {mono factorial : m n / m <= n}}. Proof. by apply: leq_mono_in => n m n0 m0; apply: ltn_fact. Qed. Lemma leq_fact : {homo factorial : m n / m <= n}. Proof. by move=> [m|m n mn]; rewrite ?fact_gt0// leq_pfact// inE (leq_trans _ mn). Qed. Lemma ltn_pfact : {in [pred n | 0 < n] &, {mono factorial : m n / m < n}}. Proof. exact/leqW_mono_in/leq_pfact. Qed. (* Support for larger integers. The normal definitions of +, - and even *) (* IO are unsuitable for Peano integers larger than 2000 or so because *) (* they are not tail-recursive. We provide a workaround module, along *) (* with a rewrite multirule to change the tailrec operators to the *) (* normal ones. We handle IO via the NatBin module, but provide our *) (* own (more efficient) conversion functions. *) Module NatTrec. (* Usage: *) (* Import NatTrec. *) (* in section defining functions, rebinds all *) (* non-tail recursive operators. *) (* rewrite !trecE. *) (* in the correctness proof, restores operators *) Fixpoint add m n := if m is m'.+1 then m' + n.+1 else n where "n + m" := (add n m) : nat_scope. Fixpoint add_mul m n s := if m is m'.+1 then add_mul m' n (n + s) else s. Definition mul m n := if m is m'.+1 then add_mul m' n n else 0. Notation "n * m" := (mul n m) : nat_scope. Fixpoint mul_exp m n p := if n is n'.+1 then mul_exp m n' (m * p) else p. Definition exp m n := if n is n'.+1 then mul_exp m n' m else 1. Notation "n ^ m" := (exp n m) : nat_scope. Local Notation oddn := odd. Fixpoint odd n := if n is n'.+2 then odd n' else eqn n 1. Local Notation doublen := double. Definition double n := if n is n'.+1 then n' + n.+1 else 0. Notation "n .*2" := (double n) : nat_scope. Lemma addE : add =2 addn. Proof. by elim=> //= n IHn m; rewrite IHn addSnnS. Qed. Lemma doubleE : double =1 doublen. Proof. by case=> // n; rewrite -addnn -addE. Qed. Lemma add_mulE n m s : add_mul n m s = addn (muln n m) s. Proof. by elim: n => //= n IHn in m s *; rewrite IHn addE addnCA addnA. Qed. Lemma mulE : mul =2 muln. Proof. by case=> //= n m; rewrite add_mulE addnC. Qed. Lemma mul_expE m n p : mul_exp m n p = muln (expn m n) p. Proof. by elim: n => [|n IHn] in p *; rewrite ?mul1n //= expnS IHn mulE mulnCA mulnA. Qed. Lemma expE : exp =2 expn. Proof. by move=> m [|n] //=; rewrite mul_expE expnS mulnC. Qed. Lemma oddE : odd =1 oddn. Proof. move=> n; rewrite -[n in LHS]odd_double_half addnC. by elim: n./2 => //=; case (oddn n). Qed. Definition trecE := (addE, (doubleE, oddE), (mulE, add_mulE, (expE, mul_expE))). End NatTrec. Notation natTrecE := NatTrec.trecE. Definition N_eqb n m := match n, m with | N0, N0 => true | Npos p, Npos q => Pos.eqb p q | _, _ => false end. Lemma eq_binP : Equality.axiom N_eqb. Proof. move=> p q; apply: (iffP idP) => [|<-]; last by case: p => //; elim. by case: q; case: p => //; elim=> [p IHp|p IHp|] [q|q|] //= /IHp [->]. Qed. HB.instance Definition _ := hasDecEq.Build N eq_binP. Arguments N_eqb !n !m. Section NumberInterpretation. Section Trec. Import NatTrec. Fixpoint nat_of_pos p0 := match p0 with | xO p => (nat_of_pos p).*2 | xI p => (nat_of_pos p).*2.+1 | xH => 1 end. End Trec. Local Coercion nat_of_pos : positive >-> nat. Coercion nat_of_bin b := if b is Npos p then p : nat else 0. Fixpoint pos_of_nat n0 m0 := match n0, m0 with | n.+1, m.+2 => pos_of_nat n m | n.+1, 1 => xO (pos_of_nat n n) | n.+1, 0 => xI (pos_of_nat n n) | 0, _ => xH end. Definition bin_of_nat n0 := if n0 is n.+1 then Npos (pos_of_nat n n) else N0. Lemma bin_of_natK : cancel bin_of_nat nat_of_bin. Proof. have sub2nn n : n.*2 - n = n by rewrite -addnn addKn. case=> //= n; rewrite -[n in RHS]sub2nn. by elim: n {2 4}n => // m IHm [|[|n]] //=; rewrite IHm // natTrecE sub2nn. Qed. Lemma nat_of_binK : cancel nat_of_bin bin_of_nat. Proof. case=> //=; elim=> //= p; case: (nat_of_pos p) => //= n [<-]. by rewrite natTrecE !addnS {2}addnn; elim: {1 3}n. by rewrite natTrecE addnS /= addnS {2}addnn; elim: {1 3}n. Qed. Lemma nat_of_succ_pos p : Pos.succ p = p.+1 :> nat. Proof. by elim: p => //= p ->; rewrite !natTrecE. Qed. Lemma nat_of_add_pos p q : Pos.add p q = p + q :> nat. Proof. apply: @fst _ (Pos.add_carry p q = (p + q).+1 :> nat) _. elim: p q => [p IHp|p IHp|] [q|q|] //=; rewrite !natTrecE //; by rewrite ?IHp ?nat_of_succ_pos ?(doubleS, doubleD, addn1, addnS). Qed. Lemma nat_of_mul_pos p q : Pos.mul p q = p * q :> nat. Proof. elim: p => [p IHp|p IHp|] /=; rewrite ?mul1n //; by rewrite ?nat_of_add_pos /= !natTrecE IHp doubleMl. Qed. End NumberInterpretation. (* Big(ger) nat IO; usage: *) (* Num 1 072 399 *) (* to create large numbers for test cases *) (* Eval compute in [Num of some expression] *) (* to display the result of an expression that *) (* returns a larger integer. *) Record number : Type := Num {bin_of_number :> N}. Definition number_subType := Eval hnf in [isNew for bin_of_number]. HB.instance Definition _ := number_subType. HB.instance Definition _ := [Equality of number by <:]. Notation "[ 'Num' 'of' e ]" := (Num (bin_of_nat e)) (format "[ 'Num' 'of' e ]") : nat_scope. (* A congruence tactic, similar to the boolean one, along with an .+1/+ *) (* normalization tactic. *) Fixpoint pop_succn e := if e is e'.+1 then fun n => pop_succn e' n.+1 else id. Ltac pop_succn e := eval lazy beta iota delta [pop_succn] in (pop_succn e 1). Ltac succn_to_add := match goal with | |- context G [?e.+1] => let x := fresh "NatLit0" in match pop_succn e with | ?n.+1 => pose x := n.+1; let G' := context G [x] in change G' | _ ?e' ?n => pose x := n; let G' := context G [x + e'] in change G' end; succn_to_add; rewrite {}/x | _ => idtac end. Ltac nat_norm := succn_to_add; rewrite ?add0n ?addn0 -?addnA ?(addSn, addnS, add0n, addn0). Ltac nat_congr := first [ apply: (congr1 succn _) | apply: (congr1 predn _) | apply: (congr1 (addn _) _) | apply: (congr1 (subn _) _) | apply: (congr1 (addn^~ _) _) | match goal with |- (?X1 + ?X2 = ?X3) => symmetry; rewrite -1?(addnC X1) -?(addnCA X1); apply: (congr1 (addn X1) _); symmetry end ].