filename
stringlengths
5
42
content
stringlengths
15
319k
RadonNikodym.lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Rémy Degenne -/ import Mathlib.MeasureTheory.Integral.Bochner.ContinuousLinearMap import Mathlib.MeasureTheory.Measure.Decomposition.Lebesgue /-! # Radon-Nikodym theorem This file proves the Radon-Nikodym theorem. The Radon-Nikodym theorem states that, given measures `μ, ν`, if `HaveLebesgueDecomposition μ ν`, then `μ` is absolutely continuous with respect to `ν` if and only if there exists a measurable function `f : α → ℝ≥0∞` such that `μ = fν`. In particular, we have `f = rnDeriv μ ν`. The Radon-Nikodym theorem will allow us to define many important concepts in probability theory, most notably probability cumulative functions. It could also be used to define the conditional expectation of a real function, but we take a different approach (see the file `MeasureTheory/Function/ConditionalExpectation`). ## Main results * `MeasureTheory.Measure.absolutelyContinuous_iff_withDensity_rnDeriv_eq` : the Radon-Nikodym theorem * `MeasureTheory.SignedMeasure.absolutelyContinuous_iff_withDensityᵥ_rnDeriv_eq` : the Radon-Nikodym theorem for signed measures The file also contains properties of `rnDeriv` that use the Radon-Nikodym theorem, notably * `MeasureTheory.Measure.rnDeriv_withDensity_left`: the Radon-Nikodym derivative of `μ.withDensity f` with respect to `ν` is `f * μ.rnDeriv ν`. * `MeasureTheory.Measure.rnDeriv_withDensity_right`: the Radon-Nikodym derivative of `μ` with respect to `ν.withDensity f` is `f⁻¹ * μ.rnDeriv ν`. * `MeasureTheory.Measure.inv_rnDeriv`: `(μ.rnDeriv ν)⁻¹ =ᵐ[μ] ν.rnDeriv μ`. * `MeasureTheory.Measure.setLIntegral_rnDeriv`: `∫⁻ x in s, μ.rnDeriv ν x ∂ν = μ s` if `μ ≪ ν`. There is also a version of this result for the Bochner integral. ## Tags Radon-Nikodym theorem -/ assert_not_exists InnerProductSpace assert_not_exists MeasureTheory.VectorMeasure noncomputable section open scoped MeasureTheory NNReal ENNReal variable {α β : Type*} {m : MeasurableSpace α} namespace MeasureTheory namespace Measure theorem withDensity_rnDeriv_eq (μ ν : Measure α) [HaveLebesgueDecomposition μ ν] (h : μ ≪ ν) : ν.withDensity (rnDeriv μ ν) = μ := by suffices μ.singularPart ν = 0 by conv_rhs => rw [haveLebesgueDecomposition_add μ ν, this, zero_add] exact (singularPart_eq_zero μ ν).mpr h variable {μ ν : Measure α} /-- **The Radon-Nikodym theorem**: Given two measures `μ` and `ν`, if `HaveLebesgueDecomposition μ ν`, then `μ` is absolutely continuous to `ν` if and only if `ν.withDensity (rnDeriv μ ν) = μ`. -/ theorem absolutelyContinuous_iff_withDensity_rnDeriv_eq [HaveLebesgueDecomposition μ ν] : μ ≪ ν ↔ ν.withDensity (rnDeriv μ ν) = μ := ⟨withDensity_rnDeriv_eq μ ν, fun h => h ▸ withDensity_absolutelyContinuous _ _⟩ lemma rnDeriv_pos [HaveLebesgueDecomposition μ ν] (hμν : μ ≪ ν) : ∀ᵐ x ∂μ, 0 < μ.rnDeriv ν x := by rw [← Measure.withDensity_rnDeriv_eq _ _ hμν, ae_withDensity_iff (Measure.measurable_rnDeriv _ _), Measure.withDensity_rnDeriv_eq _ _ hμν] exact ae_of_all _ (fun x hx ↦ lt_of_le_of_ne (zero_le _) hx.symm) lemma rnDeriv_pos' [HaveLebesgueDecomposition ν μ] [SigmaFinite μ] (hμν : μ ≪ ν) : ∀ᵐ x ∂μ, 0 < ν.rnDeriv μ x := by refine (absolutelyContinuous_withDensity_rnDeriv hμν).ae_le ?_ filter_upwards [Measure.rnDeriv_pos (withDensity_absolutelyContinuous μ (ν.rnDeriv μ)), (withDensity_absolutelyContinuous μ (ν.rnDeriv μ)).ae_le (Measure.rnDeriv_withDensity μ (Measure.measurable_rnDeriv ν μ))] with x hx hx2 rwa [← hx2] section rnDeriv_withDensity_leftRight variable {f : α → ℝ≥0∞} /-- Auxiliary lemma for `rnDeriv_withDensity_left`. -/ lemma rnDeriv_withDensity_withDensity_rnDeriv_left (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] (hf_ne_top : ∀ᵐ x ∂μ, f x ≠ ∞) : ((ν.withDensity (μ.rnDeriv ν)).withDensity f).rnDeriv ν =ᵐ[ν] (μ.withDensity f).rnDeriv ν := by conv_rhs => rw [μ.haveLebesgueDecomposition_add ν, add_comm, withDensity_add_measure] have : SigmaFinite ((μ.singularPart ν).withDensity f) := SigmaFinite.withDensity_of_ne_top (ae_mono (Measure.singularPart_le _ _) hf_ne_top) have : SigmaFinite ((ν.withDensity (μ.rnDeriv ν)).withDensity f) := SigmaFinite.withDensity_of_ne_top (ae_mono (Measure.withDensity_rnDeriv_le _ _) hf_ne_top) exact (rnDeriv_add_of_mutuallySingular _ _ _ (mutuallySingular_singularPart μ ν).withDensity).symm /-- Auxiliary lemma for `rnDeriv_withDensity_right`. -/ lemma rnDeriv_withDensity_withDensity_rnDeriv_right (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] (hf : AEMeasurable f ν) (hf_ne_zero : ∀ᵐ x ∂ν, f x ≠ 0) (hf_ne_top : ∀ᵐ x ∂ν, f x ≠ ∞) : (ν.withDensity (μ.rnDeriv ν)).rnDeriv (ν.withDensity f) =ᵐ[ν] μ.rnDeriv (ν.withDensity f) := by conv_rhs => rw [μ.haveLebesgueDecomposition_add ν, add_comm] have hν_ac : ν ≪ ν.withDensity f := withDensity_absolutelyContinuous' hf hf_ne_zero refine hν_ac.ae_eq ?_ have : SigmaFinite (ν.withDensity f) := SigmaFinite.withDensity_of_ne_top hf_ne_top refine (rnDeriv_add_of_mutuallySingular _ _ _ ?_).symm exact ((mutuallySingular_singularPart μ ν).symm.withDensity).symm lemma rnDeriv_withDensity_left_of_absolutelyContinuous {ν : Measure α} [SigmaFinite μ] [SigmaFinite ν] (hμν : μ ≪ ν) (hf : AEMeasurable f ν) : (μ.withDensity f).rnDeriv ν =ᵐ[ν] fun x ↦ f x * μ.rnDeriv ν x := by refine (Measure.eq_rnDeriv₀ ?_ Measure.MutuallySingular.zero_left ?_).symm · exact hf.mul (Measure.measurable_rnDeriv _ _).aemeasurable · ext1 s hs rw [zero_add, withDensity_apply _ hs, withDensity_apply _ hs] conv_lhs => rw [← Measure.withDensity_rnDeriv_eq _ _ hμν] rw [setLIntegral_withDensity_eq_setLIntegral_mul_non_measurable₀ _ _ _ hs] · congr with x rw [mul_comm] simp only [Pi.mul_apply] · refine ae_restrict_of_ae ?_ exact Measure.rnDeriv_lt_top _ _ · exact (Measure.measurable_rnDeriv _ _).aemeasurable lemma rnDeriv_withDensity_left {μ ν : Measure α} [SigmaFinite μ] [SigmaFinite ν] (hfν : AEMeasurable f ν) (hf_ne_top : ∀ᵐ x ∂μ, f x ≠ ∞) : (μ.withDensity f).rnDeriv ν =ᵐ[ν] fun x ↦ f x * μ.rnDeriv ν x := by let μ' := ν.withDensity (μ.rnDeriv ν) have hμ'ν : μ' ≪ ν := withDensity_absolutelyContinuous _ _ have h := rnDeriv_withDensity_left_of_absolutelyContinuous hμ'ν hfν have h1 : μ'.rnDeriv ν =ᵐ[ν] μ.rnDeriv ν := Measure.rnDeriv_withDensity _ (Measure.measurable_rnDeriv _ _) have h2 : (μ'.withDensity f).rnDeriv ν =ᵐ[ν] (μ.withDensity f).rnDeriv ν := by exact rnDeriv_withDensity_withDensity_rnDeriv_left μ ν hf_ne_top filter_upwards [h, h1, h2] with x hx hx1 hx2 rw [← hx2, hx, hx1] /-- Auxiliary lemma for `rnDeriv_withDensity_right`. -/ lemma rnDeriv_withDensity_right_of_absolutelyContinuous {ν : Measure α} [HaveLebesgueDecomposition μ ν] [SigmaFinite ν] (hμν : μ ≪ ν) (hf : AEMeasurable f ν) (hf_ne_zero : ∀ᵐ x ∂ν, f x ≠ 0) (hf_ne_top : ∀ᵐ x ∂ν, f x ≠ ∞) : μ.rnDeriv (ν.withDensity f) =ᵐ[ν] fun x ↦ (f x)⁻¹ * μ.rnDeriv ν x := by have : SigmaFinite (ν.withDensity f) := SigmaFinite.withDensity_of_ne_top hf_ne_top refine (withDensity_absolutelyContinuous' hf hf_ne_zero).ae_eq ?_ refine (Measure.eq_rnDeriv₀ (ν := ν.withDensity f) ?_ Measure.MutuallySingular.zero_left ?_).symm · exact (hf.inv.mono_ac (withDensity_absolutelyContinuous _ _)).mul (Measure.measurable_rnDeriv _ _).aemeasurable · ext1 s hs conv_lhs => rw [← Measure.withDensity_rnDeriv_eq _ _ hμν] rw [zero_add, withDensity_apply _ hs, withDensity_apply _ hs] rw [setLIntegral_withDensity_eq_setLIntegral_mul_non_measurable₀ _ _ _ hs] · simp only [Pi.mul_apply] have : (fun a ↦ f a * ((f a)⁻¹ * μ.rnDeriv ν a)) =ᵐ[ν] μ.rnDeriv ν := by filter_upwards [hf_ne_zero, hf_ne_top] with x hx1 hx2 simp [← mul_assoc, ENNReal.mul_inv_cancel, hx1, hx2] rw [lintegral_congr_ae (ae_restrict_of_ae this)] · refine ae_restrict_of_ae ?_ filter_upwards [hf_ne_top] with x hx using hx.lt_top · exact hf.restrict lemma rnDeriv_withDensity_right (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] (hf : AEMeasurable f ν) (hf_ne_zero : ∀ᵐ x ∂ν, f x ≠ 0) (hf_ne_top : ∀ᵐ x ∂ν, f x ≠ ∞) : μ.rnDeriv (ν.withDensity f) =ᵐ[ν] fun x ↦ (f x)⁻¹ * μ.rnDeriv ν x := by let μ' := ν.withDensity (μ.rnDeriv ν) have h₁ : μ'.rnDeriv (ν.withDensity f) =ᵐ[ν] μ.rnDeriv (ν.withDensity f) := rnDeriv_withDensity_withDensity_rnDeriv_right μ ν hf hf_ne_zero hf_ne_top have h₂ : μ.rnDeriv ν =ᵐ[ν] μ'.rnDeriv ν := (Measure.rnDeriv_withDensity _ (Measure.measurable_rnDeriv _ _)).symm have hμ' := rnDeriv_withDensity_right_of_absolutelyContinuous (withDensity_absolutelyContinuous ν (μ.rnDeriv ν)) hf hf_ne_zero hf_ne_top filter_upwards [h₁, h₂, hμ'] with x hx₁ hx₂ hx_eq rw [← hx₁, hx₂, hx_eq] end rnDeriv_withDensity_leftRight lemma rnDeriv_eq_zero_of_mutuallySingular {ν' : Measure α} [HaveLebesgueDecomposition μ ν'] [SigmaFinite ν'] (h : μ ⟂ₘ ν) (hνν' : ν ≪ ν') : μ.rnDeriv ν' =ᵐ[ν] 0 := by let t := h.nullSet have ht : MeasurableSet t := h.measurableSet_nullSet refine ae_of_ae_restrict_of_ae_restrict_compl t ?_ (by simp [t]) change μ.rnDeriv ν' =ᵐ[ν.restrict t] 0 have : μ.rnDeriv ν' =ᵐ[ν.restrict t] (μ.restrict t).rnDeriv ν' := by have h : (μ.restrict t).rnDeriv ν' =ᵐ[ν] t.indicator (μ.rnDeriv ν') := hνν'.ae_le (rnDeriv_restrict μ ν' ht) rw [Filter.EventuallyEq, ae_restrict_iff' ht] filter_upwards [h] with x hx hxt rw [hx, Set.indicator_of_mem hxt] refine this.trans ?_ simp only [t, MutuallySingular.restrict_nullSet] suffices (0 : Measure α).rnDeriv ν' =ᵐ[ν'] 0 by have h_ac' : ν.restrict t ≪ ν' := restrict_le_self.absolutelyContinuous.trans hνν' exact h_ac'.ae_le this exact rnDeriv_zero _ /-- Auxiliary lemma for `rnDeriv_add_right_of_mutuallySingular`. -/ lemma rnDeriv_add_right_of_absolutelyContinuous_of_mutuallySingular {ν' : Measure α} [HaveLebesgueDecomposition μ ν] [HaveLebesgueDecomposition μ (ν + ν')] [SigmaFinite ν] (hμν : μ ≪ ν) (hνν' : ν ⟂ₘ ν') : μ.rnDeriv (ν + ν') =ᵐ[ν] μ.rnDeriv ν := by let t := hνν'.nullSet have ht : MeasurableSet t := hνν'.measurableSet_nullSet refine ae_of_ae_restrict_of_ae_restrict_compl t (by simp [t]) ?_ change μ.rnDeriv (ν + ν') =ᵐ[ν.restrict tᶜ] μ.rnDeriv ν rw [← withDensity_eq_iff_of_sigmaFinite (μ := ν.restrict tᶜ) (Measure.measurable_rnDeriv _ _).aemeasurable (Measure.measurable_rnDeriv _ _).aemeasurable] have : (ν.restrict tᶜ).withDensity (μ.rnDeriv (ν + ν')) = ((ν + ν').restrict tᶜ).withDensity (μ.rnDeriv (ν + ν')) := by simp [t] rw [this, ← restrict_withDensity ht.compl, ← restrict_withDensity ht.compl, Measure.withDensity_rnDeriv_eq _ _ (hμν.add_right ν'), Measure.withDensity_rnDeriv_eq _ _ hμν] /-- Auxiliary lemma for `rnDeriv_add_right_of_mutuallySingular`. -/ lemma rnDeriv_add_right_of_mutuallySingular' {ν' : Measure α} [SigmaFinite μ] [SigmaFinite ν] [SigmaFinite ν'] (hμν' : μ ⟂ₘ ν') (hνν' : ν ⟂ₘ ν') : μ.rnDeriv (ν + ν') =ᵐ[ν] μ.rnDeriv ν := by have h_ac : ν ≪ ν + ν' := Measure.AbsolutelyContinuous.rfl.add_right _ rw [haveLebesgueDecomposition_add μ ν] have h₁ := rnDeriv_add' (μ.singularPart ν) (ν.withDensity (μ.rnDeriv ν)) (ν + ν') have h₂ := rnDeriv_add' (μ.singularPart ν) (ν.withDensity (μ.rnDeriv ν)) ν refine (Filter.EventuallyEq.trans (h_ac.ae_le h₁) ?_).trans h₂.symm have h₃ := rnDeriv_add_right_of_absolutelyContinuous_of_mutuallySingular (withDensity_absolutelyContinuous ν (μ.rnDeriv ν)) hνν' have h₄ : (μ.singularPart ν).rnDeriv (ν + ν') =ᵐ[ν] 0 := by refine h_ac.ae_eq ?_ simp only [rnDeriv_eq_zero, MutuallySingular.add_right_iff] exact ⟨mutuallySingular_singularPart μ ν, hμν'.singularPart ν⟩ have h₅ : (μ.singularPart ν).rnDeriv ν =ᵐ[ν] 0 := rnDeriv_singularPart μ ν filter_upwards [h₃, h₄, h₅] with x hx₃ hx₄ hx₅ simp only [Pi.add_apply] rw [hx₃, hx₄, hx₅] lemma rnDeriv_add_right_of_mutuallySingular {ν' : Measure α} [SigmaFinite μ] [SigmaFinite ν] [SigmaFinite ν'] (hνν' : ν ⟂ₘ ν') : μ.rnDeriv (ν + ν') =ᵐ[ν] μ.rnDeriv ν := by have h_ac : ν ≪ ν + ν' := Measure.AbsolutelyContinuous.rfl.add_right _ rw [haveLebesgueDecomposition_add μ ν'] have h₁ := rnDeriv_add' (μ.singularPart ν') (ν'.withDensity (μ.rnDeriv ν')) (ν + ν') have h₂ := rnDeriv_add' (μ.singularPart ν') (ν'.withDensity (μ.rnDeriv ν')) ν refine (Filter.EventuallyEq.trans (h_ac.ae_le h₁) ?_).trans h₂.symm have h₃ := rnDeriv_add_right_of_mutuallySingular' (?_ : μ.singularPart ν' ⟂ₘ ν') hνν' · have h₄ : (ν'.withDensity (rnDeriv μ ν')).rnDeriv (ν + ν') =ᵐ[ν] 0 := by refine rnDeriv_eq_zero_of_mutuallySingular ?_ h_ac exact hνν'.symm.withDensity have h₅ : (ν'.withDensity (rnDeriv μ ν')).rnDeriv ν =ᵐ[ν] 0 := by rw [rnDeriv_eq_zero] exact hνν'.symm.withDensity filter_upwards [h₃, h₄, h₅] with x hx₃ hx₄ hx₅ rw [Pi.add_apply, Pi.add_apply, hx₃, hx₄, hx₅] exact mutuallySingular_singularPart μ ν' lemma rnDeriv_withDensity_rnDeriv [SigmaFinite μ] [SigmaFinite ν] (hμν : μ ≪ ν) : μ.rnDeriv (μ.withDensity (ν.rnDeriv μ)) =ᵐ[μ] μ.rnDeriv ν := by conv_rhs => rw [ν.haveLebesgueDecomposition_add μ, add_comm] refine (absolutelyContinuous_withDensity_rnDeriv hμν).ae_eq ?_ exact (rnDeriv_add_right_of_mutuallySingular (Measure.mutuallySingular_singularPart ν μ).symm.withDensity).symm /-- Auxiliary lemma for `inv_rnDeriv`. -/ lemma inv_rnDeriv_aux [HaveLebesgueDecomposition μ ν] [HaveLebesgueDecomposition ν μ] [SigmaFinite μ] (hμν : μ ≪ ν) (hνμ : ν ≪ μ) : (μ.rnDeriv ν)⁻¹ =ᵐ[μ] ν.rnDeriv μ := by suffices μ.withDensity (μ.rnDeriv ν)⁻¹ = μ.withDensity (ν.rnDeriv μ) by calc (μ.rnDeriv ν)⁻¹ =ᵐ[μ] (μ.withDensity (μ.rnDeriv ν)⁻¹).rnDeriv μ := (rnDeriv_withDensity _ (measurable_rnDeriv _ _).inv).symm _ = (μ.withDensity (ν.rnDeriv μ)).rnDeriv μ := by rw [this] _ =ᵐ[μ] ν.rnDeriv μ := rnDeriv_withDensity _ (measurable_rnDeriv _ _) rw [withDensity_rnDeriv_eq _ _ hνμ, ← withDensity_rnDeriv_eq _ _ hμν] conv in ((ν.withDensity (μ.rnDeriv ν)).rnDeriv ν)⁻¹ => rw [withDensity_rnDeriv_eq _ _ hμν] change (ν.withDensity (μ.rnDeriv ν)).withDensity (fun x ↦ (μ.rnDeriv ν x)⁻¹) = ν rw [withDensity_inv_same (measurable_rnDeriv _ _) (by filter_upwards [hνμ.ae_le (rnDeriv_pos hμν)] with x hx using hx.ne') (rnDeriv_ne_top _ _)] lemma inv_rnDeriv [SigmaFinite μ] [SigmaFinite ν] (hμν : μ ≪ ν) : (μ.rnDeriv ν)⁻¹ =ᵐ[μ] ν.rnDeriv μ := by suffices (μ.rnDeriv ν)⁻¹ =ᵐ[μ] (μ.rnDeriv (μ.withDensity (ν.rnDeriv μ)))⁻¹ ∧ ν.rnDeriv μ =ᵐ[μ] (μ.withDensity (ν.rnDeriv μ)).rnDeriv μ by refine (this.1.trans (Filter.EventuallyEq.trans ?_ this.2.symm)) exact Measure.inv_rnDeriv_aux (absolutelyContinuous_withDensity_rnDeriv hμν) (withDensity_absolutelyContinuous _ _) constructor · filter_upwards [rnDeriv_withDensity_rnDeriv hμν] with x hx simp only [Pi.inv_apply, inv_inj] exact hx.symm · exact (Measure.rnDeriv_withDensity μ (Measure.measurable_rnDeriv ν μ)).symm lemma inv_rnDeriv' [SigmaFinite μ] [SigmaFinite ν] (hμν : μ ≪ ν) : (ν.rnDeriv μ)⁻¹ =ᵐ[μ] μ.rnDeriv ν := by filter_upwards [inv_rnDeriv hμν] with x hx; simp only [Pi.inv_apply, ← hx, inv_inv] section integral lemma setLIntegral_rnDeriv_le (s : Set α) : ∫⁻ x in s, μ.rnDeriv ν x ∂ν ≤ μ s := (withDensity_apply_le _ _).trans (Measure.le_iff'.1 (withDensity_rnDeriv_le μ ν) s) lemma lintegral_rnDeriv_le : ∫⁻ x, μ.rnDeriv ν x ∂ν ≤ μ Set.univ := (setLIntegral_univ _).symm ▸ Measure.setLIntegral_rnDeriv_le Set.univ lemma setLIntegral_rnDeriv' [HaveLebesgueDecomposition μ ν] (hμν : μ ≪ ν) {s : Set α} (hs : MeasurableSet s) : ∫⁻ x in s, μ.rnDeriv ν x ∂ν = μ s := by rw [← withDensity_apply _ hs, Measure.withDensity_rnDeriv_eq _ _ hμν] lemma setLIntegral_rnDeriv [HaveLebesgueDecomposition μ ν] [SFinite ν] (hμν : μ ≪ ν) (s : Set α) : ∫⁻ x in s, μ.rnDeriv ν x ∂ν = μ s := by rw [← withDensity_apply' _ s, Measure.withDensity_rnDeriv_eq _ _ hμν] lemma lintegral_rnDeriv [HaveLebesgueDecomposition μ ν] (hμν : μ ≪ ν) : ∫⁻ x, μ.rnDeriv ν x ∂ν = μ Set.univ := by rw [← setLIntegral_univ, setLIntegral_rnDeriv' hμν MeasurableSet.univ] lemma integrableOn_toReal_rnDeriv {s : Set α} (hμs : μ s ≠ ∞) : IntegrableOn (fun x ↦ (μ.rnDeriv ν x).toReal) s ν := by refine integrable_toReal_of_lintegral_ne_top (Measure.measurable_rnDeriv _ _).aemeasurable ?_ exact ((setLIntegral_rnDeriv_le _).trans_lt hμs.lt_top).ne lemma setIntegral_toReal_rnDeriv_eq_withDensity' [SigmaFinite μ] {s : Set α} (hs : MeasurableSet s) : ∫ x in s, (μ.rnDeriv ν x).toReal ∂ν = (ν.withDensity (μ.rnDeriv ν)).real s := by rw [integral_toReal (Measure.measurable_rnDeriv _ _).aemeasurable, measureReal_def] · rw [ENNReal.toReal_eq_toReal_iff, ← withDensity_apply _ hs] simp · exact ae_restrict_of_ae (Measure.rnDeriv_lt_top _ _) lemma setIntegral_toReal_rnDeriv_eq_withDensity [SigmaFinite μ] [SFinite ν] (s : Set α) : ∫ x in s, (μ.rnDeriv ν x).toReal ∂ν = (ν.withDensity (μ.rnDeriv ν)).real s := by rw [integral_toReal (Measure.measurable_rnDeriv _ _).aemeasurable, measureReal_def] · rw [ENNReal.toReal_eq_toReal_iff, ← withDensity_apply' _ s] simp · exact ae_restrict_of_ae (Measure.rnDeriv_lt_top _ _) lemma setIntegral_toReal_rnDeriv_le [SigmaFinite μ] {s : Set α} (hμs : μ s ≠ ∞) : ∫ x in s, (μ.rnDeriv ν x).toReal ∂ν ≤ μ.real s := by set t := toMeasurable μ s with ht have ht_m : MeasurableSet t := measurableSet_toMeasurable μ s have hμt : μ t ≠ ∞ := by rwa [ht, measure_toMeasurable s] calc ∫ x in s, (μ.rnDeriv ν x).toReal ∂ν ≤ ∫ x in t, (μ.rnDeriv ν x).toReal ∂ν := by refine setIntegral_mono_set ?_ ?_ (HasSubset.Subset.eventuallyLE (subset_toMeasurable _ _)) · exact integrableOn_toReal_rnDeriv hμt · exact ae_of_all _ (by simp) _ = (withDensity ν (rnDeriv μ ν)).real t := setIntegral_toReal_rnDeriv_eq_withDensity' ht_m _ ≤ μ.real t := by simp only [measureReal_def] gcongr · exact hμt · apply withDensity_rnDeriv_le _ = μ.real s := by rw [measureReal_def, measureReal_def, measure_toMeasurable s] lemma setIntegral_toReal_rnDeriv' [SigmaFinite μ] [HaveLebesgueDecomposition μ ν] (hμν : μ ≪ ν) {s : Set α} (hs : MeasurableSet s) : ∫ x in s, (μ.rnDeriv ν x).toReal ∂ν = μ.real s := by rw [setIntegral_toReal_rnDeriv_eq_withDensity' hs, Measure.withDensity_rnDeriv_eq _ _ hμν, measureReal_def] lemma setIntegral_toReal_rnDeriv [SigmaFinite μ] [SigmaFinite ν] (hμν : μ ≪ ν) (s : Set α) : ∫ x in s, (μ.rnDeriv ν x).toReal ∂ν = μ.real s := by rw [setIntegral_toReal_rnDeriv_eq_withDensity s, Measure.withDensity_rnDeriv_eq _ _ hμν] lemma integral_toReal_rnDeriv [SigmaFinite μ] [SigmaFinite ν] (hμν : μ ≪ ν) : ∫ x, (μ.rnDeriv ν x).toReal ∂ν = μ.real Set.univ := by rw [← setIntegral_univ, setIntegral_toReal_rnDeriv hμν Set.univ] lemma integral_toReal_rnDeriv' [IsFiniteMeasure μ] [SigmaFinite ν] : ∫ x, (μ.rnDeriv ν x).toReal ∂ν = μ.real Set.univ - (μ.singularPart ν).real Set.univ := by rw [measureReal_def, measureReal_def, ← ENNReal.toReal_sub_of_le (μ.singularPart_le ν Set.univ) (measure_ne_top _ _), ← Measure.sub_apply .univ (Measure.singularPart_le μ ν), Measure.measure_sub_singularPart, ← measureReal_def, ← Measure.setIntegral_toReal_rnDeriv_eq_withDensity, setIntegral_univ] end integral lemma rnDeriv_mul_rnDeriv {κ : Measure α} [SigmaFinite μ] [SigmaFinite ν] [SigmaFinite κ] (hμν : μ ≪ ν) : μ.rnDeriv ν * ν.rnDeriv κ =ᵐ[κ] μ.rnDeriv κ := by refine (rnDeriv_withDensity_left ?_ ?_).symm.trans ?_ · exact (Measure.measurable_rnDeriv _ _).aemeasurable · exact rnDeriv_ne_top _ _ · rw [Measure.withDensity_rnDeriv_eq _ _ hμν] lemma rnDeriv_mul_rnDeriv' {κ : Measure α} [SigmaFinite μ] [SigmaFinite ν] [SigmaFinite κ] (hνκ : ν ≪ κ) : μ.rnDeriv ν * ν.rnDeriv κ =ᵐ[ν] μ.rnDeriv κ := by obtain ⟨h_meas, h_sing, hμν⟩ := Measure.haveLebesgueDecomposition_spec μ ν filter_upwards [hνκ <| Measure.rnDeriv_add' (μ.singularPart ν) (ν.withDensity (μ.rnDeriv ν)) κ, hνκ <| Measure.rnDeriv_withDensity_left_of_absolutelyContinuous hνκ h_meas.aemeasurable, Measure.rnDeriv_eq_zero_of_mutuallySingular h_sing hνκ] with x hx1 hx2 hx3 nth_rw 2 [hμν] rw [hx1, Pi.add_apply, hx2, Pi.mul_apply, hx3, Pi.zero_apply, zero_add] lemma rnDeriv_le_one_of_le (hμν : μ ≤ ν) [SigmaFinite ν] : μ.rnDeriv ν ≤ᵐ[ν] 1 := by refine ae_le_of_forall_setLIntegral_le_of_sigmaFinite (μ.measurable_rnDeriv ν) fun s _ _ ↦ ?_ simp only [Pi.one_apply, MeasureTheory.setLIntegral_one] exact (Measure.setLIntegral_rnDeriv_le s).trans (hμν s) lemma rnDeriv_le_one_iff_le [HaveLebesgueDecomposition μ ν] [SigmaFinite ν] (hμν : μ ≪ ν) : μ.rnDeriv ν ≤ᵐ[ν] 1 ↔ μ ≤ ν := by refine ⟨fun h s ↦ ?_, fun h ↦ rnDeriv_le_one_of_le h⟩ rw [← withDensity_rnDeriv_eq _ _ hμν, withDensity_apply', ← setLIntegral_one] exact setLIntegral_mono_ae aemeasurable_const (h.mono fun _ hh _ ↦ hh) lemma rnDeriv_eq_one_iff_eq [HaveLebesgueDecomposition μ ν] [SigmaFinite ν] (hμν : μ ≪ ν) : μ.rnDeriv ν =ᵐ[ν] 1 ↔ μ = ν := by refine ⟨fun h ↦ ?_, fun h ↦ h ▸ ν.rnDeriv_self⟩ rw [← withDensity_rnDeriv_eq _ _ hμν, withDensity_congr_ae h, withDensity_one] section MeasurableEmbedding variable {mβ : MeasurableSpace β} {f : α → β} lemma _root_.MeasurableEmbedding.rnDeriv_map_aux (hf : MeasurableEmbedding f) (hμν : μ ≪ ν) [SigmaFinite μ] [SigmaFinite ν] : (fun x ↦ (μ.map f).rnDeriv (ν.map f) (f x)) =ᵐ[ν] μ.rnDeriv ν := by refine ae_eq_of_forall_setLIntegral_eq_of_sigmaFinite ?_ ?_ (fun s _ _ ↦ ?_) · exact (Measure.measurable_rnDeriv _ _).comp hf.measurable · exact Measure.measurable_rnDeriv _ _ rw [← hf.lintegral_map, Measure.setLIntegral_rnDeriv hμν] have hs_eq : s = f ⁻¹' (f '' s) := by rw [hf.injective.preimage_image] have : SigmaFinite (ν.map f) := hf.sigmaFinite_map rw [hs_eq, ← hf.restrict_map, Measure.setLIntegral_rnDeriv (hf.absolutelyContinuous_map hμν), hf.map_apply] lemma _root_.MeasurableEmbedding.rnDeriv_map (hf : MeasurableEmbedding f) (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] : (fun x ↦ (μ.map f).rnDeriv (ν.map f) (f x)) =ᵐ[ν] μ.rnDeriv ν := by rw [μ.haveLebesgueDecomposition_add ν, Measure.map_add _ _ hf.measurable] have : SigmaFinite (map f ν) := hf.sigmaFinite_map have : SigmaFinite (map f (μ.singularPart ν)) := hf.sigmaFinite_map have : SigmaFinite (map f (ν.withDensity (μ.rnDeriv ν))) := hf.sigmaFinite_map have h_add := Measure.rnDeriv_add' ((μ.singularPart ν).map f) ((ν.withDensity (μ.rnDeriv ν)).map f) (ν.map f) rw [Filter.EventuallyEq, hf.ae_map_iff, ← Filter.EventuallyEq] at h_add refine h_add.trans ((Measure.rnDeriv_add' _ _ _).trans ?_).symm refine Filter.EventuallyEq.add ?_ ?_ · refine (Measure.rnDeriv_singularPart μ ν).trans ?_ symm suffices (fun x ↦ ((μ.singularPart ν).map f).rnDeriv (ν.map f) x) =ᵐ[ν.map f] 0 by rw [Filter.EventuallyEq, hf.ae_map_iff] at this exact this refine Measure.rnDeriv_eq_zero_of_mutuallySingular ?_ Measure.AbsolutelyContinuous.rfl exact hf.mutuallySingular_map (μ.mutuallySingular_singularPart ν) · exact (hf.rnDeriv_map_aux (withDensity_absolutelyContinuous _ _)).symm lemma _root_.MeasurableEmbedding.map_withDensity_rnDeriv (hf : MeasurableEmbedding f) (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] : (ν.withDensity (μ.rnDeriv ν)).map f = (ν.map f).withDensity ((μ.map f).rnDeriv (ν.map f)) := by ext s hs rw [hf.map_apply, withDensity_apply _ (hf.measurable hs), withDensity_apply _ hs, setLIntegral_map hs (Measure.measurable_rnDeriv _ _) hf.measurable] refine setLIntegral_congr_fun_ae (hf.measurable hs) ?_ filter_upwards [hf.rnDeriv_map μ ν] with a ha _ using ha.symm lemma _root_.MeasurableEmbedding.singularPart_map (hf : MeasurableEmbedding f) (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] : (μ.map f).singularPart (ν.map f) = (μ.singularPart ν).map f := by have h_add : μ.map f = (μ.singularPart ν).map f + (ν.map f).withDensity ((μ.map f).rnDeriv (ν.map f)) := by conv_lhs => rw [μ.haveLebesgueDecomposition_add ν] rw [Measure.map_add _ _ hf.measurable, ← hf.map_withDensity_rnDeriv μ ν] refine (Measure.eq_singularPart (Measure.measurable_rnDeriv _ _) ?_ h_add).symm exact hf.mutuallySingular_map (μ.mutuallySingular_singularPart ν) end MeasurableEmbedding end Measure section IntegralRNDerivMul open Measure variable {α : Type*} {m : MeasurableSpace α} {μ ν : Measure α} theorem lintegral_rnDeriv_mul [HaveLebesgueDecomposition μ ν] (hμν : μ ≪ ν) {f : α → ℝ≥0∞} (hf : AEMeasurable f ν) : ∫⁻ x, μ.rnDeriv ν x * f x ∂ν = ∫⁻ x, f x ∂μ := by nth_rw 2 [← withDensity_rnDeriv_eq μ ν hμν] rw [lintegral_withDensity_eq_lintegral_mul₀ (measurable_rnDeriv μ ν).aemeasurable hf] simp only [Pi.mul_apply] lemma setLIntegral_rnDeriv_mul [HaveLebesgueDecomposition μ ν] (hμν : μ ≪ ν) {f : α → ℝ≥0∞} (hf : AEMeasurable f ν) {s : Set α} (hs : MeasurableSet s) : ∫⁻ x in s, μ.rnDeriv ν x * f x ∂ν = ∫⁻ x in s, f x ∂μ := by nth_rw 2 [← Measure.withDensity_rnDeriv_eq μ ν hμν] rw [setLIntegral_withDensity_eq_lintegral_mul₀ (measurable_rnDeriv μ ν).aemeasurable hf hs] simp only [Pi.mul_apply] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [HaveLebesgueDecomposition μ ν] [SigmaFinite μ] {f : α → E} theorem integrable_rnDeriv_smul_iff (hμν : μ ≪ ν) : Integrable (fun x ↦ (μ.rnDeriv ν x).toReal • f x) ν ↔ Integrable f μ := by nth_rw 2 [← withDensity_rnDeriv_eq μ ν hμν] rw [← integrable_withDensity_iff_integrable_smul' (E := E) (measurable_rnDeriv μ ν) (rnDeriv_lt_top μ ν)] theorem integral_rnDeriv_smul (hμν : μ ≪ ν) : ∫ x, (μ.rnDeriv ν x).toReal • f x ∂ν = ∫ x, f x ∂μ := by rw [← integral_withDensity_eq_integral_toReal_smul (measurable_rnDeriv _ _) (rnDeriv_lt_top _ _), withDensity_rnDeriv_eq _ _ hμν] /-- See also `setIntegral_rnDeriv_smul'` for a version that requires both measures to be σ-finite, but doesn't require `s` to be a measurable set. -/ lemma setIntegral_rnDeriv_smul (hμν : μ ≪ ν) {s : Set α} (hs : MeasurableSet s) : ∫ x in s, (μ.rnDeriv ν x).toReal • f x ∂ν = ∫ x in s, f x ∂μ := by rw [← setIntegral_withDensity_eq_setIntegral_toReal_smul, withDensity_rnDeriv_eq _ _ hμν] exacts [measurable_rnDeriv _ _, ae_restrict_of_ae (rnDeriv_lt_top _ _), hs] omit [HaveLebesgueDecomposition μ ν] in /-- A version of `setIntegral_rnDeriv_smul` that requires both measures to be σ-finite, but doesn't require `s` to be a measurable set. -/ lemma setIntegral_rnDeriv_smul' [SigmaFinite ν] (hμν : μ ≪ ν) (s : Set α) : ∫ x in s, (μ.rnDeriv ν x).toReal • f x ∂ν = ∫ x in s, f x ∂μ := by rw [← setIntegral_withDensity_eq_setIntegral_toReal_smul', withDensity_rnDeriv_eq _ _ hμν] exacts [measurable_rnDeriv _ _, ae_restrict_of_ae (rnDeriv_lt_top _ _)] end IntegralRNDerivMul end MeasureTheory
Field.lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Algebra.Field.Basic import Mathlib.Algebra.Order.Field.Canonical import Mathlib.Algebra.Order.Nonneg.Ring import Mathlib.Data.Nat.Cast.Order.Ring /-! # Semifield structure on the type of nonnegative elements This file defines instances and prove some properties about the nonnegative elements `{x : α // 0 ≤ x}` of an arbitrary type `α`. This is used to derive algebraic structures on `ℝ≥0` and `ℚ≥0` automatically. ## Main declarations * `{x : α // 0 ≤ x}` is a `CanonicallyLinearOrderedSemifield` if `α` is a `LinearOrderedField`. -/ assert_not_exists abs_inv open Set variable {α : Type*} section NNRat variable [Semifield α] [LinearOrder α] [IsStrictOrderedRing α] {a : α} lemma NNRat.cast_nonneg (q : ℚ≥0) : 0 ≤ (q : α) := by rw [cast_def]; exact div_nonneg q.num.cast_nonneg q.den.cast_nonneg lemma nnqsmul_nonneg (q : ℚ≥0) (ha : 0 ≤ a) : 0 ≤ q • a := by rw [NNRat.smul_def]; exact mul_nonneg q.cast_nonneg ha end NNRat namespace Nonneg section LinearOrderedSemifield variable [Semifield α] [LinearOrder α] [IsStrictOrderedRing α] {x y : α} instance inv : Inv { x : α // 0 ≤ x } := ⟨fun x => ⟨x⁻¹, inv_nonneg.2 x.2⟩⟩ @[simp, norm_cast] protected theorem coe_inv (a : { x : α // 0 ≤ x }) : ((a⁻¹ : { x : α // 0 ≤ x }) : α) = (a : α)⁻¹ := rfl @[simp] theorem inv_mk (hx : 0 ≤ x) : (⟨x, hx⟩ : { x : α // 0 ≤ x })⁻¹ = ⟨x⁻¹, inv_nonneg.2 hx⟩ := rfl instance div : Div { x : α // 0 ≤ x } := ⟨fun x y => ⟨x / y, div_nonneg x.2 y.2⟩⟩ @[simp, norm_cast] protected theorem coe_div (a b : { x : α // 0 ≤ x }) : ((a / b : { x : α // 0 ≤ x }) : α) = a / b := rfl @[simp] theorem mk_div_mk (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : { x : α // 0 ≤ x }) / ⟨y, hy⟩ = ⟨x / y, div_nonneg hx hy⟩ := rfl instance zpow : Pow { x : α // 0 ≤ x } ℤ := ⟨fun a n => ⟨(a : α) ^ n, zpow_nonneg a.2 _⟩⟩ @[simp, norm_cast] protected theorem coe_zpow (a : { x : α // 0 ≤ x }) (n : ℤ) : ((a ^ n : { x : α // 0 ≤ x }) : α) = (a : α) ^ n := rfl @[simp] theorem mk_zpow (hx : 0 ≤ x) (n : ℤ) : (⟨x, hx⟩ : { x : α // 0 ≤ x }) ^ n = ⟨x ^ n, zpow_nonneg hx n⟩ := rfl instance instNNRatCast : NNRatCast {x : α // 0 ≤ x} := ⟨fun q ↦ ⟨q, q.cast_nonneg⟩⟩ instance instNNRatSMul : SMul ℚ≥0 {x : α // 0 ≤ x} where smul q a := ⟨q • a, by rw [NNRat.smul_def]; exact mul_nonneg q.cast_nonneg a.2⟩ @[simp, norm_cast] lemma coe_nnratCast (q : ℚ≥0) : (q : {x : α // 0 ≤ x}) = (q : α) := rfl @[simp] lemma mk_nnratCast (q : ℚ≥0) : (⟨q, q.cast_nonneg⟩ : {x : α // 0 ≤ x}) = q := rfl @[simp, norm_cast] lemma coe_nnqsmul (q : ℚ≥0) (a : {x : α // 0 ≤ x}) : ↑(q • a) = (q • a : α) := rfl @[simp] lemma mk_nnqsmul (q : ℚ≥0) (a : α) (ha : 0 ≤ a) : (⟨q • a, by rw [NNRat.smul_def]; exact mul_nonneg q.cast_nonneg ha⟩ : {x : α // 0 ≤ x}) = q • a := rfl instance semifield : Semifield { x : α // 0 ≤ x } := fast_instance% Subtype.coe_injective.semifield _ Nonneg.coe_zero Nonneg.coe_one Nonneg.coe_add Nonneg.coe_mul Nonneg.coe_inv Nonneg.coe_div (fun _ _ => rfl) coe_nnqsmul Nonneg.coe_pow Nonneg.coe_zpow Nonneg.coe_natCast coe_nnratCast end LinearOrderedSemifield instance linearOrderedCommGroupWithZero [Field α] [LinearOrder α] [IsStrictOrderedRing α] : LinearOrderedCommGroupWithZero { x : α // 0 ≤ x } := CanonicallyOrderedAdd.toLinearOrderedCommGroupWithZero end Nonneg
Map.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.Dynamics.Ergodic.MeasurePreserving import Mathlib.MeasureTheory.Integral.Lebesgue.Add /-! # Behavior of the Lebesgue integral under maps -/ namespace MeasureTheory open Set Filter ENNReal SimpleFunc variable {α β : Type*} [MeasurableSpace α] [MeasurableSpace β] {μ : Measure α} {ν : Measure β} section Map open Measure theorem lintegral_map {f : β → ℝ≥0∞} {g : α → β} (hf : Measurable f) (hg : Measurable g) : ∫⁻ a, f a ∂map g μ = ∫⁻ a, f (g a) ∂μ := by rw [lintegral_eq_iSup_eapprox_lintegral hf] simp only [← Function.comp_apply (f := f) (g := g)] rw [lintegral_eq_iSup_eapprox_lintegral (hf.comp hg)] congr with n : 1 convert SimpleFunc.lintegral_map _ hg ext1 x; simp only [eapprox_comp hf hg, coe_comp] theorem lintegral_map' {f : β → ℝ≥0∞} {g : α → β} (hf : AEMeasurable f (Measure.map g μ)) (hg : AEMeasurable g μ) : ∫⁻ a, f a ∂Measure.map g μ = ∫⁻ a, f (g a) ∂μ := calc ∫⁻ a, f a ∂Measure.map g μ = ∫⁻ a, hf.mk f a ∂Measure.map g μ := lintegral_congr_ae hf.ae_eq_mk _ = ∫⁻ a, hf.mk f a ∂Measure.map (hg.mk g) μ := by congr 1 exact Measure.map_congr hg.ae_eq_mk _ = ∫⁻ a, hf.mk f (hg.mk g a) ∂μ := lintegral_map hf.measurable_mk hg.measurable_mk _ = ∫⁻ a, hf.mk f (g a) ∂μ := lintegral_congr_ae <| hg.ae_eq_mk.symm.fun_comp _ _ = ∫⁻ a, f (g a) ∂μ := lintegral_congr_ae (ae_eq_comp hg hf.ae_eq_mk.symm) theorem lintegral_map_le (f : β → ℝ≥0∞) (g : α → β) : ∫⁻ a, f a ∂Measure.map g μ ≤ ∫⁻ a, f (g a) ∂μ := by by_cases hg : AEMeasurable g μ · rw [← iSup_lintegral_measurable_le_eq_lintegral] refine iSup₂_le fun i hi => iSup_le fun h'i => ?_ rw [lintegral_map' hi.aemeasurable hg] exact lintegral_mono fun _ ↦ h'i _ · simp [map_of_not_aemeasurable hg] theorem lintegral_comp {f : β → ℝ≥0∞} {g : α → β} (hf : Measurable f) (hg : Measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂map g μ := (lintegral_map hf hg).symm theorem setLIntegral_map {f : β → ℝ≥0∞} {g : α → β} {s : Set β} (hs : MeasurableSet s) (hf : Measurable f) (hg : Measurable g) : ∫⁻ y in s, f y ∂map g μ = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] theorem lintegral_indicator_const_comp {f : α → β} {s : Set β} (hf : Measurable f) (hs : MeasurableSet s) (c : ℝ≥0∞) : ∫⁻ a, s.indicator (fun _ => c) (f a) ∂μ = c * μ (f ⁻¹' s) := by erw [lintegral_comp (measurable_const.indicator hs) hf] rw [lintegral_indicator_const hs, Measure.map_apply hf hs] /-- If `g : α → β` is a measurable embedding and `f : β → ℝ≥0∞` is any function (not necessarily measurable), then `∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ`. Compare with `lintegral_map` which applies to any measurable `g : α → β` but requires that `f` is measurable as well. -/ theorem _root_.MeasurableEmbedding.lintegral_map {g : α → β} (hg : MeasurableEmbedding g) (f : β → ℝ≥0∞) : ∫⁻ a, f a ∂map g μ = ∫⁻ a, f (g a) ∂μ := by rw [lintegral, lintegral] refine le_antisymm (iSup₂_le fun f₀ hf₀ => ?_) (iSup₂_le fun f₀ hf₀ => ?_) · rw [SimpleFunc.lintegral_map _ hg.measurable] have : (f₀.comp g hg.measurable : α → ℝ≥0∞) ≤ f ∘ g := fun x => hf₀ (g x) exact le_iSup_of_le (comp f₀ g hg.measurable) (by exact le_iSup (α := ℝ≥0∞) _ this) · rw [← f₀.extend_comp_eq hg (const _ 0), ← SimpleFunc.lintegral_map, ← SimpleFunc.lintegral_eq_lintegral, ← lintegral] refine lintegral_mono_ae (hg.ae_map_iff.2 <| Eventually.of_forall fun x => ?_) exact (extend_apply _ _ _ _).trans_le (hf₀ _) /-- The `lintegral` transforms appropriately under a measurable equivalence `g : α ≃ᵐ β`. (Compare `lintegral_map`, which applies to a wider class of functions `g : α → β`, but requires measurability of the function being integrated.) -/ theorem lintegral_map_equiv (f : β → ℝ≥0∞) (g : α ≃ᵐ β) : ∫⁻ a, f a ∂map g μ = ∫⁻ a, f (g a) ∂μ := g.measurableEmbedding.lintegral_map f theorem lintegral_subtype_comap {s : Set α} (hs : MeasurableSet s) (f : α → ℝ≥0∞) : ∫⁻ x : s, f x ∂(μ.comap (↑)) = ∫⁻ x in s, f x ∂μ := by rw [← (MeasurableEmbedding.subtype_coe hs).lintegral_map, map_comap_subtype_coe hs] theorem setLIntegral_subtype {s : Set α} (hs : MeasurableSet s) (t : Set s) (f : α → ℝ≥0∞) : ∫⁻ x in t, f x ∂(μ.comap (↑)) = ∫⁻ x in (↑) '' t, f x ∂μ := by rw [(MeasurableEmbedding.subtype_coe hs).restrict_comap, lintegral_subtype_comap hs, restrict_restrict hs, inter_eq_right.2 (Subtype.coe_image_subset _ _)] end Map namespace MeasurePreserving variable {g : α → β} (hg : MeasurePreserving g μ ν) protected theorem lintegral_map_equiv (f : β → ℝ≥0∞) (g : α ≃ᵐ β) (hg : MeasurePreserving g μ ν) : ∫⁻ a, f a ∂ν = ∫⁻ a, f (g a) ∂μ := by rw [← MeasureTheory.lintegral_map_equiv f g, hg.map_eq] include hg theorem lintegral_comp {f : β → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν := by rw [← hg.map_eq, lintegral_map hf hg.measurable] theorem lintegral_comp_emb (hge : MeasurableEmbedding g) (f : β → ℝ≥0∞) : ∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν := by rw [← hg.map_eq, hge.lintegral_map] theorem setLIntegral_comp_preimage {s : Set β} (hs : MeasurableSet s) {f : β → ℝ≥0∞} (hf : Measurable f) : ∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν := by rw [← hg.map_eq, setLIntegral_map hs hf hg.measurable] theorem setLIntegral_comp_preimage_emb (hge : MeasurableEmbedding g) (f : β → ℝ≥0∞) (s : Set β) : ∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν := by rw [← hg.map_eq, hge.restrict_map, hge.lintegral_map] theorem setLIntegral_comp_emb (hge : MeasurableEmbedding g) (f : β → ℝ≥0∞) (s : Set α) : ∫⁻ a in s, f (g a) ∂μ = ∫⁻ b in g '' s, f b ∂ν := by rw [← hg.setLIntegral_comp_preimage_emb hge, Set.preimage_image_eq _ hge.injective] end MeasurePreserving end MeasureTheory
Point.lean
/- Copyright (c) 2025 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.Formula import Mathlib.LinearAlgebra.FreeModule.Norm import Mathlib.RingTheory.ClassGroup import Mathlib.RingTheory.Polynomial.UniqueFactorization /-! # Nonsingular points and the group law in affine coordinates Let `W` be a Weierstrass curve over a field `F` given by a Weierstrass equation `W(X, Y) = 0` in affine coordinates. The type of nonsingular points `W⟮F⟯` in affine coordinates is an inductive, consisting of the unique point at infinity `𝓞` and nonsingular affine points `(x, y)`. Then `W⟮F⟯` can be endowed with a group law, with `𝓞` as the identity nonsingular point, which is uniquely determined by the formulae in `Mathlib/AlgebraicGeometry/EllipticCurve/Affine/Formula.lean`. With this description, there is an addition-preserving injection between `W⟮F⟯` and the ideal class group of the *affine coordinate ring* `F[W] := F[X, Y] / ⟨W(X, Y)⟩` of `W`. This is given by mapping `𝓞` to the trivial ideal class and a nonsingular affine point `(x, y)` to the ideal class of the invertible ideal `⟨X - x, Y - y⟩`. Proving that this is well-defined and preserves addition reduces to equalities of integral ideals checked in `WeierstrassCurve.Affine.CoordinateRing.XYIdeal_neg_mul` and in `WeierstrassCurve.Affine.CoordinateRing.XYIdeal_mul_XYIdeal` via explicit ideal computations. Now `F[W]` is a free rank two `F[X]`-algebra with basis `{1, Y}`, so every element of `F[W]` is of the form `p + qY` for some `p, q` in `F[X]`, and there is an algebra norm `N : F[W] → F[X]`. Injectivity can then be shown by computing the degree of such a norm `N(p + qY)` in two different ways, which is done in `WeierstrassCurve.Affine.CoordinateRing.degree_norm_smul_basis` and in the auxiliary lemmas in the proof of `WeierstrassCurve.Affine.Point.instAddCommGroup`. This file defines the group law on nonsingular points `W⟮F⟯` in affine coordinates. ## Main definitions * `WeierstrassCurve.Affine.CoordinateRing`: the affine coordinate ring `F[W]`. * `WeierstrassCurve.Affine.CoordinateRing.basis`: the power basis of `F[W]` over `F[X]`. * `WeierstrassCurve.Affine.Point`: a nonsingular point in affine coordinates. * `WeierstrassCurve.Affine.Point.neg`: the negation of a nonsingular point in affine coordinates. * `WeierstrassCurve.Affine.Point.add`: the addition of a nonsingular point in affine coordinates. ## Main statements * `WeierstrassCurve.Affine.CoordinateRing.instIsDomainCoordinateRing`: the affine coordinate ring of a Weierstrass curve is an integral domain. * `WeierstrassCurve.Affine.CoordinateRing.degree_norm_smul_basis`: the degree of the norm of an element in the affine coordinate ring in terms of its power basis. * `WeierstrassCurve.Affine.Point.instAddCommGroup`: the type of nonsingular points `W⟮F⟯` in affine coordinates forms an abelian group under addition. ## Notations * `W⟮K⟯`: the group of nonsingular points on `W` base changed to `K`. ## References * [J Silverman, *The Arithmetic of Elliptic Curves*][silverman2009] * https://drops.dagstuhl.de/storage/00lipics/lipics-vol268-itp2023/LIPIcs.ITP.2023.6/LIPIcs.ITP.2023.6.pdf ## Tags elliptic curve, affine, point, group law, class group -/ open FractionalIdeal (coeIdeal_mul) open Ideal hiding map_mul open Module Polynomial open scoped nonZeroDivisors Polynomial.Bivariate local macro "C_simp" : tactic => `(tactic| simp only [map_ofNat, C_0, C_1, C_neg, C_add, C_sub, C_mul, C_pow]) universe r s u v w namespace WeierstrassCurve variable {R : Type r} {S : Type s} {A F : Type u} {B K : Type v} {L : Type w} [CommRing R] [CommRing S] [CommRing A] [CommRing B] [Field F] [Field K] [Field L] {W' : Affine R} {W : Affine F} namespace Affine /-! ## The affine coordinate ring -/ /-- The affine coordinate ring `R[W] := R[X, Y] / ⟨W(X, Y)⟩` of a Weierstrass curve `W`. -/ abbrev CoordinateRing : Type r := AdjoinRoot W'.polynomial /-- The function field `R(W) := Frac(R[W])` of a Weierstrass curve `W`. -/ abbrev FunctionField : Type r := FractionRing W'.CoordinateRing namespace CoordinateRing noncomputable instance : Algebra R W'.CoordinateRing := Quotient.algebra R noncomputable instance : Algebra R[X] W'.CoordinateRing := Quotient.algebra R[X] instance : IsScalarTower R R[X] W'.CoordinateRing := Quotient.isScalarTower R R[X] _ instance [Subsingleton R] : Subsingleton W'.CoordinateRing := Module.subsingleton R[X] _ variable (W') in /-- The natural ring homomorphism mapping `R[X][Y]` to `R[W]`. -/ noncomputable abbrev mk : R[X][Y] →+* W'.CoordinateRing := AdjoinRoot.mk W'.polynomial open scoped Classical in variable (W') in /-- The power basis `{1, Y}` for `R[W]` over `R[X]`. -/ protected noncomputable def basis : Basis (Fin 2) R[X] W'.CoordinateRing := (subsingleton_or_nontrivial R).by_cases (fun _ => default) fun _ => (AdjoinRoot.powerBasis' monic_polynomial).basis.reindex <| finCongr natDegree_polynomial lemma basis_apply (n : Fin 2) : CoordinateRing.basis W' n = (AdjoinRoot.powerBasis' monic_polynomial).gen ^ (n : ℕ) := by classical nontriviality R rw [CoordinateRing.basis, Or.by_cases, dif_neg <| not_subsingleton R, Basis.reindex_apply, PowerBasis.basis_eq_pow, finCongr_symm_apply, Fin.coe_cast] @[simp] lemma basis_zero : CoordinateRing.basis W' 0 = 1 := by simpa only [basis_apply] using pow_zero _ @[simp] lemma basis_one : CoordinateRing.basis W' 1 = mk W' Y := by simpa only [basis_apply] using pow_one _ lemma coe_basis : (CoordinateRing.basis W' : Fin 2 → W'.CoordinateRing) = ![1, mk W' Y] := by ext n fin_cases n exacts [basis_zero, basis_one] lemma smul (x : R[X]) (y : W'.CoordinateRing) : x • y = mk W' (C x) * y := (algebraMap_smul W'.CoordinateRing x y).symm lemma smul_basis_eq_zero {p q : R[X]} (hpq : p • (1 : W'.CoordinateRing) + q • mk W' Y = 0) : p = 0 ∧ q = 0 := by have h := Fintype.linearIndependent_iff.mp (CoordinateRing.basis W').linearIndependent ![p, q] rw [Fin.sum_univ_succ, basis_zero, Fin.sum_univ_one, Fin.succ_zero_eq_one, basis_one] at h exact ⟨h hpq 0, h hpq 1⟩ lemma exists_smul_basis_eq (x : W'.CoordinateRing) : ∃ p q : R[X], p • (1 : W'.CoordinateRing) + q • mk W' Y = x := by have h := (CoordinateRing.basis W').sum_equivFun x rw [Fin.sum_univ_succ, Fin.sum_univ_one, basis_zero, Fin.succ_zero_eq_one, basis_one] at h exact ⟨_, _, h⟩ lemma smul_basis_mul_C (y : R[X]) (p q : R[X]) : (p • (1 : W'.CoordinateRing) + q • mk W' Y) * mk W' (C y) = (p * y) • (1 : W'.CoordinateRing) + (q * y) • mk W' Y := by simp only [smul, map_mul] ring1 lemma smul_basis_mul_Y (p q : R[X]) : (p • (1 : W'.CoordinateRing) + q • mk W' Y) * mk W' Y = (q * (X ^ 3 + C W'.a₂ * X ^ 2 + C W'.a₄ * X + C W'.a₆)) • (1 : W'.CoordinateRing) + (p - q * (C W'.a₁ * X + C W'.a₃)) • mk W' Y := by have Y_sq : mk W' Y ^ 2 = mk W' (C (X ^ 3 + C W'.a₂ * X ^ 2 + C W'.a₄ * X + C W'.a₆) - C (C W'.a₁ * X + C W'.a₃) * Y) := AdjoinRoot.mk_eq_mk.mpr ⟨1, by rw [polynomial]; ring1⟩ simp only [smul, add_mul, mul_assoc, ← sq, Y_sq, map_sub, map_mul] ring1 variable (W') in /-- The ring homomorphism `R[W] →+* S[W.map f]` induced by a ring homomorphism `f : R →+* S`. -/ noncomputable def map (f : R →+* S) : W'.CoordinateRing →+* (W'.map f).toAffine.CoordinateRing := AdjoinRoot.lift ((AdjoinRoot.of _).comp <| mapRingHom f) ((AdjoinRoot.root (W'.map f).toAffine.polynomial)) <| by rw [← eval₂_map, ← map_polynomial, AdjoinRoot.eval₂_root] lemma map_mk (f : R →+* S) (x : R[X][Y]) : map W' f (mk W' x) = mk (W'.map f) (x.map <| mapRingHom f) := by rw [map, AdjoinRoot.lift_mk, ← eval₂_map] exact AdjoinRoot.aeval_eq <| x.map <| mapRingHom f protected lemma map_smul (f : R →+* S) (x : R[X]) (y : W'.CoordinateRing) : map W' f (x • y) = x.map f • map W' f y := by rw [smul, map_mul, map_mk, map_C, smul] rfl lemma map_injective {f : R →+* S} (hf : Function.Injective f) : Function.Injective <| map W' f := (injective_iff_map_eq_zero _).mpr fun y hy => by obtain ⟨p, q, rfl⟩ := exists_smul_basis_eq y simp_rw [map_add, CoordinateRing.map_smul, map_one, map_mk, map_X] at hy obtain ⟨hp, hq⟩ := smul_basis_eq_zero hy rw [Polynomial.map_eq_zero_iff hf] at hp hq simp_rw [hp, hq, zero_smul, add_zero] instance [IsDomain R] : IsDomain W'.CoordinateRing := have : IsDomain (W'.map <| algebraMap R <| FractionRing R).toAffine.CoordinateRing := AdjoinRoot.isDomain_of_prime irreducible_polynomial.prime (map_injective <| IsFractionRing.injective R <| FractionRing R).isDomain /-! ## Ideals in the affine coordinate ring -/ variable (W') in /-- The class of the element `X - x` in `R[W]` for some `x` in `R`. -/ noncomputable def XClass (x : R) : W'.CoordinateRing := mk W' <| C <| X - C x lemma XClass_ne_zero [Nontrivial R] (x : R) : XClass W' x ≠ 0 := AdjoinRoot.mk_ne_zero_of_natDegree_lt monic_polynomial (C_ne_zero.mpr <| X_sub_C_ne_zero x) <| by rw [natDegree_polynomial, natDegree_C]; norm_num1 variable (W') in /-- The class of the element `Y - y(X)` in `R[W]` for some `y(X)` in `R[X]`. -/ noncomputable def YClass (y : R[X]) : W'.CoordinateRing := mk W' <| Y - C y lemma YClass_ne_zero [Nontrivial R] (y : R[X]) : YClass W' y ≠ 0 := AdjoinRoot.mk_ne_zero_of_natDegree_lt monic_polynomial (X_sub_C_ne_zero y) <| by rw [natDegree_polynomial, natDegree_X_sub_C]; norm_num1 lemma C_addPolynomial (x y ℓ : R) : mk W' (C <| W'.addPolynomial x y ℓ) = mk W' ((Y - C (linePolynomial x y ℓ)) * (W'.negPolynomial - C (linePolynomial x y ℓ))) := AdjoinRoot.mk_eq_mk.mpr ⟨1, by rw [W'.C_addPolynomial, add_sub_cancel_left, mul_one]⟩ lemma C_addPolynomial_slope [DecidableEq F] {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : mk W (C <| W.addPolynomial x₁ y₁ <| W.slope x₁ x₂ y₁ y₂) = -(XClass W x₁ * XClass W x₂ * XClass W (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂)) := congr_arg (mk W) <| W.C_addPolynomial_slope h₁ h₂ hxy variable (W') in /-- The ideal `⟨X - x⟩` of `R[W]` for some `x` in `R`. -/ noncomputable def XIdeal (x : R) : Ideal W'.CoordinateRing := .span {XClass W' x} variable (W') in /-- The ideal `⟨Y - y(X)⟩` of `R[W]` for some `y(X)` in `R[X]`. -/ noncomputable def YIdeal (y : R[X]) : Ideal W'.CoordinateRing := .span {YClass W' y} variable (W') in /-- The ideal `⟨X - x, Y - y(X)⟩` of `R[W]` for some `x` in `R` and `y(X)` in `R[X]`. -/ noncomputable def XYIdeal (x : R) (y : R[X]) : Ideal W'.CoordinateRing := .span {XClass W' x, YClass W' y} /-- The `R`-algebra isomorphism from `R[W] / ⟨X - x, Y - y(X)⟩` to `R` obtained by evaluation at some `y(X)` in `R[X]` and at some `x` in `R` provided that `W(x, y(x)) = 0`. -/ noncomputable def quotientXYIdealEquiv {x : R} {y : R[X]} (h : (W'.polynomial.eval y).eval x = 0) : (W'.CoordinateRing ⧸ XYIdeal W' x y) ≃ₐ[R] R := ((quotientEquivAlgOfEq R <| by simp only [XYIdeal, XClass, YClass, ← Set.image_pair, ← map_span]; rfl).trans <| DoubleQuot.quotQuotEquivQuotOfLEₐ R <| (span_singleton_le_iff_mem _).mpr <| mem_span_C_X_sub_C_X_sub_C_iff_eval_eval_eq_zero.mpr h).trans quotientSpanCXSubCXSubCAlgEquiv lemma XYIdeal_add_eq (x₁ x₂ y₁ ℓ : R) : XYIdeal W' (W'.addX x₁ x₂ ℓ) (C <| W'.addY x₁ x₂ y₁ ℓ) = .span {mk W' <| W'.negPolynomial - C (linePolynomial x₁ y₁ ℓ)} ⊔ XIdeal W' (W'.addX x₁ x₂ ℓ) := by simp only [XYIdeal, XIdeal, XClass, YClass, addY, negAddY, negY, negPolynomial, linePolynomial] rw [sub_sub <| -(Y : R[X][Y]), neg_sub_left (Y : R[X][Y]), map_neg, span_singleton_neg, sup_comm, ← span_insert, ← span_pair_add_mul_right <| mk W' <| C <| C <| W'.a₁ + ℓ, ← map_mul, ← map_add] apply congr_arg (_ ∘ _ ∘ _ ∘ _) C_simp ring1 lemma XYIdeal_eq₁ (x y ℓ : R) : XYIdeal W' x (C y) = XYIdeal W' x (linePolynomial x y ℓ) := by simp only [XYIdeal, XClass, YClass, linePolynomial] rw [← span_pair_add_mul_right <| mk W' <| C <| C <| -ℓ, ← map_mul, ← map_add] apply congr_arg (_ ∘ _ ∘ _ ∘ _) C_simp ring1 lemma XYIdeal_eq₂ [DecidableEq F] {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : XYIdeal W x₂ (C y₂) = XYIdeal W x₂ (linePolynomial x₁ y₁ <| W.slope x₁ x₂ y₁ y₂) := by have hy₂ : y₂ = (linePolynomial x₁ y₁ <| W.slope x₁ x₂ y₁ y₂).eval x₂ := by by_cases hx : x₁ = x₂ · have hy : y₁ ≠ W.negY x₂ y₂ := fun h => hxy ⟨hx, h⟩ rcases hx, Y_eq_of_Y_ne h₁ h₂ hx hy with ⟨rfl, rfl⟩ simp [linePolynomial] · field_simp [linePolynomial, slope_of_X_ne hx, sub_ne_zero_of_ne hx] ring1 nth_rw 1 [hy₂] simp only [XYIdeal, XClass, YClass, linePolynomial] rw [← span_pair_add_mul_right <| mk W <| C <| C <| -W.slope x₁ x₂ y₁ y₂, ← map_mul, ← map_add] apply congr_arg (_ ∘ _ ∘ _ ∘ _) simp only [eval_C, eval_X, eval_add, eval_sub, eval_mul] C_simp ring1 lemma XYIdeal_neg_mul {x y : F} (h : W.Nonsingular x y) : XYIdeal W x (C <| W.negY x y) * XYIdeal W x (C y) = XIdeal W x := by have Y_rw : (Y - C (C y)) * (Y - C (C <| W.negY x y)) - C (X - C x) * (C (X ^ 2 + C (x + W.a₂) * X + C (x ^ 2 + W.a₂ * x + W.a₄)) - C (C W.a₁) * Y) = W.polynomial * 1 := by linear_combination (norm := (rw [negY, polynomial]; C_simp; ring1)) congr_arg C (congr_arg C ((equation_iff ..).mp h.left).symm) simp_rw [XYIdeal, XClass, YClass, span_pair_mul_span_pair, mul_comm, ← map_mul, AdjoinRoot.mk_eq_mk.mpr ⟨1, Y_rw⟩, map_mul, span_insert, ← span_singleton_mul_span_singleton, ← Ideal.mul_sup, ← span_insert] convert mul_top (_ : Ideal W.CoordinateRing) using 2 simp_rw [← Set.image_singleton (f := mk W), ← Set.image_insert_eq, ← map_span] convert map_top (R := F[X][Y]) (mk W) using 1 apply congr_arg simp_rw [eq_top_iff_one, mem_span_insert', mem_span_singleton'] rcases ((nonsingular_iff' ..).mp h).right with hx | hy · let W_X := W.a₁ * y - (3 * x ^ 2 + 2 * W.a₂ * x + W.a₄) refine ⟨C <| C W_X⁻¹ * -(X + C (2 * x + W.a₂)), C <| C <| W_X⁻¹ * W.a₁, 0, C <| C <| W_X⁻¹ * -1, ?_⟩ rw [← mul_right_inj' <| C_ne_zero.mpr <| C_ne_zero.mpr hx] simp only [W_X, mul_add, ← mul_assoc, ← C_mul, mul_inv_cancel₀ hx] C_simp ring1 · let W_Y := 2 * y + W.a₁ * x + W.a₃ refine ⟨0, C <| C W_Y⁻¹, C <| C <| W_Y⁻¹ * -1, 0, ?_⟩ rw [negY, ← mul_right_inj' <| C_ne_zero.mpr <| C_ne_zero.mpr hy] simp only [W_Y, mul_add, ← mul_assoc, ← C_mul, mul_inv_cancel₀ hy] C_simp ring1 lemma XYIdeal_mul_XYIdeal [DecidableEq F] {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : XIdeal W (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂) * (XYIdeal W x₁ (C y₁) * XYIdeal W x₂ (C y₂)) = YIdeal W (linePolynomial x₁ y₁ <| W.slope x₁ x₂ y₁ y₂) * XYIdeal W (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂) (C <| W.addY x₁ x₂ y₁ <| W.slope x₁ x₂ y₁ y₂) := by have sup_rw : ∀ a b c d : Ideal W.CoordinateRing, a ⊔ (b ⊔ (c ⊔ d)) = a ⊔ d ⊔ b ⊔ c := fun _ _ c _ => by rw [← sup_assoc, sup_comm c, sup_sup_sup_comm, ← sup_assoc] rw [XYIdeal_add_eq, XIdeal, mul_comm, XYIdeal_eq₁ x₁ y₁ <| W.slope x₁ x₂ y₁ y₂, XYIdeal, XYIdeal_eq₂ h₁ h₂ hxy, XYIdeal, span_pair_mul_span_pair] simp_rw [span_insert, sup_rw, Ideal.sup_mul, span_singleton_mul_span_singleton] rw [← neg_eq_iff_eq_neg.mpr <| C_addPolynomial_slope h₁ h₂ hxy, span_singleton_neg, C_addPolynomial, map_mul, YClass] simp_rw [mul_comm <| XClass W x₁, mul_assoc, ← span_singleton_mul_span_singleton, ← Ideal.mul_sup] rw [span_singleton_mul_span_singleton, ← span_insert, ← span_pair_add_mul_right <| -(XClass W <| W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂), mul_neg, ← sub_eq_add_neg, ← sub_mul, ← map_sub <| mk W, sub_sub_sub_cancel_right, span_insert, ← span_singleton_mul_span_singleton, ← sup_rw, ← Ideal.sup_mul, ← Ideal.sup_mul] apply congr_arg (_ ∘ _) convert top_mul (_ : Ideal W.CoordinateRing) simp_rw [XClass, ← Set.image_singleton (f := mk W), ← map_span, ← Ideal.map_sup, eq_top_iff_one, mem_map_iff_of_surjective _ AdjoinRoot.mk_surjective, ← span_insert, mem_span_insert', mem_span_singleton'] by_cases hx : x₁ = x₂ · have hy : y₁ ≠ W.negY x₂ y₂ := fun h => hxy ⟨hx, h⟩ rcases hx, Y_eq_of_Y_ne h₁ h₂ hx hy with ⟨rfl, rfl⟩ let y := (y₁ - W.negY x₁ y₁) ^ 2 replace hxy := pow_ne_zero 2 <| sub_ne_zero_of_ne hy refine ⟨1 + C (C <| y⁻¹ * 4) * W.polynomial, ⟨C <| C y⁻¹ * (C 4 * X ^ 2 + C (4 * x₁ + W.b₂) * X + C (4 * x₁ ^ 2 + W.b₂ * x₁ + 2 * W.b₄)), 0, C (C y⁻¹) * (Y - W.negPolynomial), ?_⟩, by rw [map_add, map_one, map_mul <| mk W, AdjoinRoot.mk_self, mul_zero, add_zero]⟩ rw [polynomial, negPolynomial, ← mul_right_inj' <| C_ne_zero.mpr <| C_ne_zero.mpr hxy] simp only [y, mul_add, ← mul_assoc, ← C_mul, mul_inv_cancel₀ hxy] linear_combination (norm := (rw [b₂, b₄, negY]; C_simp; ring1)) -4 * congr_arg C (congr_arg C <| (equation_iff ..).mp h₁) · replace hx := sub_ne_zero_of_ne hx refine ⟨_, ⟨⟨C <| C (x₁ - x₂)⁻¹, C <| C <| (x₁ - x₂)⁻¹ * -1, 0, ?_⟩, map_one _⟩⟩ rw [← mul_right_inj' <| C_ne_zero.mpr <| C_ne_zero.mpr hx] simp only [← mul_assoc, mul_add, ← C_mul, mul_inv_cancel₀ hx] C_simp ring1 /-- The non-zero fractional ideal `⟨X - x, Y - y⟩` of `F(W)` for some `x` and `y` in `F`. -/ noncomputable def XYIdeal' {x y : F} (h : W.Nonsingular x y) : (FractionalIdeal W.CoordinateRing⁰ W.FunctionField)ˣ := Units.mkOfMulEqOne _ _ <| by rw [← mul_assoc, ← coeIdeal_mul, mul_comm <| XYIdeal W .., XYIdeal_neg_mul h, XIdeal, FractionalIdeal.coe_ideal_span_singleton_mul_inv W.FunctionField <| XClass_ne_zero x] lemma XYIdeal'_eq {x y : F} (h : W.Nonsingular x y) : (XYIdeal' h : FractionalIdeal W.CoordinateRing⁰ W.FunctionField) = XYIdeal W x (C y) := rfl lemma mk_XYIdeal'_neg_mul {x y : F} (h : W.Nonsingular x y) : ClassGroup.mk (XYIdeal' <| (nonsingular_neg ..).mpr h) * ClassGroup.mk (XYIdeal' h) = 1 := by rw [← map_mul] exact (ClassGroup.mk_eq_one_of_coe_ideal <| (coeIdeal_mul ..).symm.trans <| FractionalIdeal.coeIdeal_inj.mpr <| XYIdeal_neg_mul h).mpr ⟨_, XClass_ne_zero x, rfl⟩ @[deprecated (since := "2025-02-01")] alias mk_XYIdeal'_mul_mk_XYIdeal'_of_Yeq := mk_XYIdeal'_neg_mul lemma mk_XYIdeal'_mul_mk_XYIdeal' [DecidableEq F] {x₁ x₂ y₁ y₂ : F} (h₁ : W.Nonsingular x₁ y₁) (h₂ : W.Nonsingular x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : ClassGroup.mk (XYIdeal' h₁) * ClassGroup.mk (XYIdeal' h₂) = ClassGroup.mk (XYIdeal' <| nonsingular_add h₁ h₂ hxy) := by rw [← map_mul] exact (ClassGroup.mk_eq_mk_of_coe_ideal (coeIdeal_mul ..).symm <| XYIdeal'_eq _).mpr ⟨_, _, XClass_ne_zero _, YClass_ne_zero _, XYIdeal_mul_XYIdeal h₁.left h₂.left hxy⟩ /-! ## Norms on the affine coordinate ring -/ lemma norm_smul_basis (p q : R[X]) : Algebra.norm R[X] (p • (1 : W'.CoordinateRing) + q • mk W' Y) = p ^ 2 - p * q * (C W'.a₁ * X + C W'.a₃) - q ^ 2 * (X ^ 3 + C W'.a₂ * X ^ 2 + C W'.a₄ * X + C W'.a₆) := by simp_rw [Algebra.norm_eq_matrix_det <| CoordinateRing.basis W', Matrix.det_fin_two, Algebra.leftMulMatrix_eq_repr_mul, basis_zero, mul_one, basis_one, smul_basis_mul_Y, map_add, Finsupp.add_apply, map_smul, Finsupp.smul_apply, ← basis_zero, ← basis_one, Basis.repr_self_apply, if_pos, one_ne_zero, if_false, smul_eq_mul] ring1 lemma coe_norm_smul_basis (p q : R[X]) : Algebra.norm R[X] (p • 1 + q • mk W' Y) = mk W' ((C p + C q * X) * (C p + C q * (-(Y : R[X][Y]) - C (C W'.a₁ * X + C W'.a₃)))) := AdjoinRoot.mk_eq_mk.mpr ⟨C q ^ 2, by simp only [norm_smul_basis, polynomial]; C_simp; ring1⟩ lemma degree_norm_smul_basis [IsDomain R] (p q : R[X]) : (Algebra.norm R[X] <| p • 1 + q • mk W' Y).degree = max (2 • p.degree) (2 • q.degree + 3) := by have hdp : (p ^ 2).degree = 2 • p.degree := degree_pow p 2 have hdpq : (p * q * (C W'.a₁ * X + C W'.a₃)).degree ≤ p.degree + q.degree + 1 := by simpa only [degree_mul] using add_le_add_left degree_linear_le (p.degree + q.degree) have hdq : (q ^ 2 * (X ^ 3 + C W'.a₂ * X ^ 2 + C W'.a₄ * X + C W'.a₆)).degree = 2 • q.degree + 3 := by rw [degree_mul, degree_pow, ← one_mul <| X ^ 3, ← C_1, degree_cubic <| one_ne_zero' R] rw [norm_smul_basis] by_cases hp : p = 0 · simp only [hp, hdq, neg_zero, zero_sub, zero_mul, zero_pow two_ne_zero, degree_neg] exact (max_bot_left _).symm · by_cases hq : q = 0 · simp only [hq, hdp, sub_zero, zero_mul, mul_zero, zero_pow two_ne_zero] exact (max_bot_right _).symm · rw [← not_congr degree_eq_bot] at hp hq -- Porting note: BUG `cases` tactic does not modify assumptions in `hp'` and `hq'` rcases hp' : p.degree with _ | dp -- `hp' : ` should be redundant · exact (hp hp').elim -- `hp'` should be `rfl` · rw [hp'] at hdp hdpq -- line should be redundant rcases hq' : q.degree with _ | dq -- `hq' : ` should be redundant · exact (hq hq').elim -- `hq'` should be `rfl` · rw [hq'] at hdpq hdq -- line should be redundant rcases le_or_gt dp (dq + 1) with hpq | hpq · convert (degree_sub_eq_right_of_degree_lt <| (degree_sub_le _ _).trans_lt <| max_lt_iff.mpr ⟨hdp.trans_lt _, hdpq.trans_lt _⟩).trans (max_eq_right_of_lt _).symm <;> rw [hdq] <;> exact WithBot.coe_lt_coe.mpr <| by dsimp; linarith only [hpq] · rw [sub_sub] convert (degree_sub_eq_left_of_degree_lt <| (degree_add_le _ _).trans_lt <| max_lt_iff.mpr ⟨hdpq.trans_lt _, hdq.trans_lt _⟩).trans (max_eq_left_of_lt _).symm <;> rw [hdp] <;> exact WithBot.coe_lt_coe.mpr <| by dsimp; linarith only [hpq] lemma degree_norm_ne_one [IsDomain R] (x : W'.CoordinateRing) : (Algebra.norm R[X] x).degree ≠ 1 := by rcases exists_smul_basis_eq x with ⟨p, q, rfl⟩ rw [degree_norm_smul_basis] rcases p.degree with (_ | _ | _ | _) <;> cases q.degree any_goals rintro (_ | _) exact (lt_max_of_lt_right <| (cmp_eq_lt_iff ..).mp rfl).ne' lemma natDegree_norm_ne_one [IsDomain R] (x : W'.CoordinateRing) : (Algebra.norm R[X] x).natDegree ≠ 1 := degree_norm_ne_one x ∘ (degree_eq_iff_natDegree_eq_of_pos zero_lt_one).mpr end CoordinateRing /-! ## Nonsingular points in affine coordinates -/ variable (W') in /-- A nonsingular point on a Weierstrass curve `W` in affine coordinates. This is either the unique point at infinity `WeierstrassCurve.Affine.Point.zero` or a nonsingular affine point `WeierstrassCurve.Affine.Point.some (x, y)` satisfying the Weierstrass equation of `W`. -/ inductive Point | zero | some {x y : R} (h : W'.Nonsingular x y) /-- For an algebraic extension `S` of a ring `R`, the type of nonsingular `S`-points on a Weierstrass curve `W` over `R` in affine coordinates. -/ scoped notation3:max W' "⟮" S "⟯" => Affine.Point <| baseChange W' S namespace Point instance : Inhabited W'.Point := ⟨.zero⟩ instance : Zero W'.Point := ⟨.zero⟩ lemma zero_def : 0 = (.zero : W'.Point) := rfl lemma some_ne_zero {x y : R} (h : W'.Nonsingular x y) : Point.some h ≠ 0 := by rintro (_ | _) /-- The negation of a nonsingular point on a Weierstrass curve in affine coordinates. Given a nonsingular point `P` in affine coordinates, use `-P` instead of `neg P`. -/ def neg : W'.Point → W'.Point | 0 => 0 | some h => some <| (nonsingular_neg ..).mpr h instance : Neg W'.Point := ⟨neg⟩ lemma neg_def (P : W'.Point) : -P = P.neg := rfl @[simp] lemma neg_zero : (-0 : W'.Point) = 0 := rfl @[simp] lemma neg_some {x y : R} (h : W'.Nonsingular x y) : -some h = some ((nonsingular_neg ..).mpr h) := rfl instance : InvolutiveNeg W'.Point where neg_neg := by rintro (_ | _) · rfl · simp only [neg_some, negY_negY] /-- The addition of two nonsingular points on a Weierstrass curve in affine coordinates. Given two nonsingular points `P` and `Q` in affine coordinates, use `P + Q` instead of `add P Q`. -/ def add [DecidableEq F] : W.Point → W.Point → W.Point | 0, P => P | P, 0 => P | @some _ _ _ x₁ y₁ h₁, @some _ _ _ x₂ y₂ h₂ => if hxy : x₁ = x₂ ∧ y₁ = W.negY x₂ y₂ then 0 else some <| nonsingular_add h₁ h₂ hxy section add variable [DecidableEq F] instance : Add W.Point := ⟨add⟩ instance : AddZeroClass W.Point := ⟨by rintro (_ | _) <;> rfl, by rintro (_ | _) <;> rfl⟩ lemma add_def (P Q : W.Point) : P + Q = P.add Q := rfl lemma add_some {x₁ x₂ y₁ y₂ : F} (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} : some h₁ + some h₂ = some (nonsingular_add h₁ h₂ hxy) := by simp only [add_def, add, dif_neg hxy] @[deprecated (since := "2025-02-28")] alias add_of_imp := add_some @[simp] lemma add_of_Y_eq {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hx : x₁ = x₂) (hy : y₁ = W.negY x₂ y₂) : some h₁ + some h₂ = 0 := by simpa only [add_def, add] using dif_pos ⟨hx, hy⟩ -- Removing `@[simp]`, because `hy` causes a maximum recursion depth error in the simpNF linter. lemma add_self_of_Y_eq {x₁ y₁ : F} {h₁ : W.Nonsingular x₁ y₁} (hy : y₁ = W.negY x₁ y₁) : some h₁ + some h₁ = 0 := add_of_Y_eq rfl hy -- @[simp] -- Not a good simp lemma, since `hy` is not in simp normal form. lemma add_of_Y_ne {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hy : y₁ ≠ W.negY x₂ y₂) : some h₁ + some h₂ = some (nonsingular_add h₁ h₂ fun hxy => hy hxy.right) := add_some fun hxy => hy hxy.right lemma add_of_Y_ne' {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hy : y₁ ≠ W.negY x₂ y₂) : some h₁ + some h₂ = -some (nonsingular_negAdd h₁ h₂ fun hxy => hy hxy.right) := add_of_Y_ne hy -- @[simp] -- Not a good simp lemma, since `hy` is not in simp normal form. lemma add_self_of_Y_ne {x₁ y₁ : F} {h₁ : W.Nonsingular x₁ y₁} (hy : y₁ ≠ W.negY x₁ y₁) : some h₁ + some h₁ = some (nonsingular_add h₁ h₁ fun hxy => hy hxy.right) := add_of_Y_ne hy lemma add_self_of_Y_ne' {x₁ y₁ : F} {h₁ : W.Nonsingular x₁ y₁} (hy : y₁ ≠ W.negY x₁ y₁) : some h₁ + some h₁ = -some (nonsingular_negAdd h₁ h₁ fun hxy => hy hxy.right) := add_of_Y_ne hy @[simp] lemma add_of_X_ne {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hx : x₁ ≠ x₂) : some h₁ + some h₂ = some (nonsingular_add h₁ h₂ fun hxy => hx hxy.left) := add_some fun hxy => hx hxy.left lemma add_of_X_ne' {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hx : x₁ ≠ x₂) : some h₁ + some h₂ = -some (nonsingular_negAdd h₁ h₂ fun hxy => hx hxy.left) := add_of_X_ne hx variable [DecidableEq K] [DecidableEq L] /-! ## Group law in affine coordinates -/ /-- The group homomorphism mapping a nonsingular affine point `(x, y)` of a Weierstrass curve `W` to the class of the non-zero fractional ideal `⟨X - x, Y - y⟩` in the ideal class group of `F[W]`. -/ @[simps] noncomputable def toClass : W.Point →+ Additive (ClassGroup W.CoordinateRing) where toFun P := match P with | 0 => 0 | some h => Additive.ofMul <| ClassGroup.mk <| CoordinateRing.XYIdeal' h map_zero' := rfl map_add' := by rintro (_ | @⟨x₁, y₁, h₁⟩) (_ | @⟨x₂, y₂, h₂⟩) any_goals simp only [← zero_def, zero_add, add_zero] by_cases hxy : x₁ = x₂ ∧ y₁ = W.negY x₂ y₂ · simp only [hxy.left, hxy.right, add_of_Y_eq rfl rfl] exact (CoordinateRing.mk_XYIdeal'_neg_mul h₂).symm · simp only [add_some hxy] exact (CoordinateRing.mk_XYIdeal'_mul_mk_XYIdeal' h₁ h₂ hxy).symm @[deprecated (since := "2025-02-01")] alias toClassFun := toClass lemma toClass_zero : toClass (0 : W.Point) = 0 := rfl lemma toClass_some {x y : F} (h : W.Nonsingular x y) : toClass (some h) = ClassGroup.mk (CoordinateRing.XYIdeal' h) := rfl private lemma add_eq_zero (P Q : W.Point) : P + Q = 0 ↔ P = -Q := by rcases P, Q with ⟨_ | @⟨x₁, y₁, _⟩, _ | @⟨x₂, y₂, _⟩⟩ any_goals rfl · rw [← zero_def, zero_add, eq_comm (a := 0), neg_eq_iff_eq_neg, neg_zero] · rw [neg_some, some.injEq] constructor · contrapose exact fun hxy => by simpa only [add_some hxy] using some_ne_zero _ · exact fun ⟨hx, hy⟩ => add_of_Y_eq hx hy lemma toClass_eq_zero (P : W.Point) : toClass P = 0 ↔ P = 0 := by constructor · intro hP rcases P with (_ | ⟨h, _⟩) · rfl · rcases (ClassGroup.mk_eq_one_of_coe_ideal <| by rfl).mp hP with ⟨p, h0, hp⟩ apply (p.natDegree_norm_ne_one _).elim rw [← finrank_quotient_span_eq_natDegree_norm (CoordinateRing.basis W) h0, ← (quotientEquivAlgOfEq F hp).toLinearEquiv.finrank_eq, (CoordinateRing.quotientXYIdealEquiv h).toLinearEquiv.finrank_eq, Module.finrank_self] · exact congr_arg toClass lemma toClass_injective : Function.Injective <| toClass (W := W) := by rintro (_ | h) _ hP all_goals rw [← neg_inj, ← add_eq_zero, ← toClass_eq_zero, map_add, ← hP] · exact zero_add 0 · exact CoordinateRing.mk_XYIdeal'_neg_mul h instance : AddCommGroup W.Point where nsmul := nsmulRec zsmul := zsmulRec zero_add := zero_add add_zero := add_zero neg_add_cancel _ := by rw [add_eq_zero] add_comm _ _ := toClass_injective <| by simp only [map_add, add_comm] add_assoc _ _ _ := toClass_injective <| by simp only [map_add, add_assoc] /-! ## Maps and base changes -/ variable [Algebra R S] [Algebra R F] [Algebra S F] [IsScalarTower R S F] [Algebra R K] [Algebra S K] [IsScalarTower R S K] [Algebra R L] [Algebra S L] [IsScalarTower R S L] (f : F →ₐ[S] K) (g : K →ₐ[S] L) /-- The group homomorphism from `W⟮F⟯` to `W⟮K⟯` induced by an algebra homomorphism `f : F →ₐ[S] K`, where `W` is defined over a subring of a ring `S`, and `F` and `K` are field extensions of `S`. -/ noncomputable def map : W'⟮F⟯ →+ W'⟮K⟯ where toFun P := match P with | 0 => 0 | some h => some <| (baseChange_nonsingular _ _ f.injective).mpr h map_zero' := rfl map_add' := by rintro (_ | @⟨x₁, y₁, _⟩) (_ | @⟨x₂, y₂, _⟩) any_goals rfl by_cases hxy : x₁ = x₂ ∧ y₁ = (W'.baseChange F).toAffine.negY x₂ y₂ · rw [add_of_Y_eq hxy.left hxy.right, add_of_Y_eq (congr_arg _ hxy.left) <| by rw [hxy.right, baseChange_negY]] · simp only [add_some hxy, ← baseChange_addX, ← baseChange_addY, ← baseChange_slope] rw [add_some fun h => hxy ⟨f.injective h.1, f.injective (W'.baseChange_negY f .. ▸ h).2⟩] @[deprecated (since := "2025-02-01")] alias mapFun := map lemma map_zero : map f (0 : W'⟮F⟯) = 0 := rfl lemma map_some {x y : F} (h : (W'.baseChange F).toAffine.Nonsingular x y) : map f (some h) = some ((W'.baseChange_nonsingular _ _ f.injective).mpr h) := rfl lemma map_id (P : W'⟮F⟯) : map (Algebra.ofId F F) P = P := by cases P <;> rfl lemma map_map (P : W'⟮F⟯) : map g (map f P) = map (g.comp f) P := by cases P <;> rfl lemma map_injective : Function.Injective <| map (W' := W') f := by rintro (_ | _) (_ | _) h any_goals contradiction · rfl · simpa only [some.injEq] using ⟨f.injective (some.inj h).left, f.injective (some.inj h).right⟩ variable (F K) in /-- The group homomorphism from `W⟮F⟯` to `W⟮K⟯` induced by the base change from `F` to `K`, where `W` is defined over a subring of a ring `S`, and `F` and `K` are field extensions of `S`. -/ noncomputable abbrev baseChange [Algebra F K] [IsScalarTower R F K] : W'⟮F⟯ →+ W'⟮K⟯ := map <| Algebra.ofId F K lemma map_baseChange [Algebra F K] [IsScalarTower R F K] [Algebra F L] [IsScalarTower R F L] (f : K →ₐ[F] L) (P : W'⟮F⟯) : map f (baseChange F K P) = baseChange F L P := by have : Subsingleton (F →ₐ[F] L) := inferInstance convert map_map (Algebra.ofId F K) f P end add end Point end Affine end WeierstrassCurve
AddRelatedDecl.lean
/- Copyright (c) 2023 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison, Floris van Doorn -/ import Mathlib.Init import Lean.Elab.DeclarationRange import Lean.Elab.Term /-! # `addRelatedDecl` -/ open Lean Meta Elab namespace Mathlib.Tactic /-- A helper function for constructing a related declaration from an existing one. This is currently used by the attributes `reassoc` and `elementwise`, and has been factored out to avoid code duplication. Feel free to add features as needed for other applications. This helper: * calls `addDeclarationRangesFromSyntax`, so jump-to-definition works, * copies the `protected` status of the existing declaration, and * supports copying attributes. Arguments: * `src : Name` is the existing declaration that we are modifying. * `suffix : String` will be appended to `src` to form the name of the new declaration. * `ref : Syntax` is the syntax where the user requested the related declaration. * `construct type value levels : MetaM (Expr × List Name)` given the type, value, and universe variables of the original declaration, should construct the value of the new declaration, along with the names of its universe variables. * `attrs` is the attributes that should be applied to both the new and the original declaration, e.g. in the usage `@[reassoc (attr := simp)]`. We apply it to both declarations, to have the same behavior as `to_additive`, and to shorten some attribute commands. Note that `@[elementwise (attr := simp), reassoc (attr := simp)]` will try to apply `simp` twice to the current declaration, but that causes no issues. -/ def addRelatedDecl (src : Name) (suffix : String) (ref : Syntax) (attrs? : Option (Syntax.TSepArray `Lean.Parser.Term.attrInstance ",")) (construct : Expr → Expr → List Name → MetaM (Expr × List Name)) : MetaM Unit := do let tgt := match src with | Name.str n s => Name.mkStr n <| s ++ suffix | x => x addDeclarationRangesFromSyntax tgt (← getRef) ref let info ← getConstInfo src let (newValue, newLevels) ← construct info.type info.value! info.levelParams let newValue ← instantiateMVars newValue let newType ← instantiateMVars (← inferType newValue) match info with | ConstantInfo.thmInfo info => addAndCompile <| .thmDecl { info with levelParams := newLevels, type := newType, name := tgt, value := newValue } | ConstantInfo.defnInfo info => -- Structure fields are created using `def`, even when they are propositional, -- so we don't rely on this to decided whether we should be constructing a `theorem` or a `def`. addAndCompile <| if ← isProp newType then .thmDecl { info with levelParams := newLevels, type := newType, name := tgt, value := newValue } else .defnDecl { info with levelParams := newLevels, type := newType, name := tgt, value := newValue } | _ => throwError "Constant {src} is not a theorem or definition." if isProtected (← getEnv) src then setEnv <| addProtected (← getEnv) tgt inferDefEqAttr tgt let attrs := match attrs? with | some attrs => attrs | none => #[] _ ← Term.TermElabM.run' <| do let attrs ← elabAttrs attrs Term.applyAttributes src attrs Term.applyAttributes tgt attrs end Mathlib.Tactic
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).
GlobalAttributeIn.lean
/- Copyright (c) 2024 Michael Rothgang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Rothgang, Damiano Testa -/ import Lean.Elab.Command -- Import this linter explicitly to ensure that -- this file has a valid copyright header and module docstring. import Mathlib.Tactic.Linter.Header /-! # Linter for `attribute [...] in` declarations Linter for global attributes created via `attribute [...] in` declarations. The syntax `attribute [instance] instName in` can be used to accidentally create a global instance. This is **not** obvious from reading the code, and in fact happened twice during the port, hence, we lint against it. *Example*: before this was discovered, `Mathlib/Topology/Category/TopCat/Basic.lean` contained the following code: ``` attribute [instance] HasForget.instFunLike in instance (X Y : TopCat.{u}) : CoeFun (X ⟶ Y) fun _ => X → Y where coe f := f ``` Despite the `in`, this makes `HasForget.instFunLike` a global instance. This seems to apply to all attributes. For example: ```lean theorem what : False := sorry attribute [simp] what in #guard true -- the `simp` attribute persists example : False := by simp -- `simp` finds `what` theorem who {x y : Nat} : x = y := sorry attribute [ext] who in #guard true -- the `ext` attribute persists example {x y : Nat} : x = y := by ext ``` Therefore, we lint against this pattern on all instances. For *removing* attributes, the `in` works as expected. ```lean /-- error: failed to synthesize Add Nat -/ #guard_msgs in attribute [-instance] instAddNat in #synth Add Nat -- the `instance` persists /-- info: instAddNat -/ #guard_msgs in #synth Add Nat @[simp] theorem what : False := sorry /-- error: simp made no progress -/ #guard_msgs in attribute [-simp] what in example : False := by simp -- the `simp` attribute persists #guard_msgs in example : False := by simp ``` -/ open Lean Elab Command Linter namespace Mathlib.Linter /-- Lint on any occurrence of `attribute [...] name in` which is not `local` or `scoped`: these are a footgun, as the attribute is applied *globally* (despite the `in`). -/ register_option linter.globalAttributeIn : Bool := { defValue := true descr := "enable the globalAttributeIn linter" } namespace globalAttributeInLinter /-- Gets the value of the `linter.globalAttributeIn` option. -/ def getLinterGlobalAttributeIn (o : LinterOptions) : Bool := getLinterValue linter.globalAttributeIn o /-- `getGlobalAttributesIn? cmd` assumes that `cmd` represents a `attribute [...] id in ...` command. If this is the case, then it returns `(id, #[non-local nor scoped attributes])`. Otherwise, it returns `default`. -/ def getGlobalAttributesIn? : Syntax → Option (Ident × Array (TSyntax `attr)) | `(attribute [$x,*] $id in $_) => let xs := x.getElems.filterMap fun a => match a.raw with | `(Parser.Command.eraseAttr| -$_) => none | `(Parser.Term.attrInstance| local $_attr:attr) => none | `(Parser.Term.attrInstance| scoped $_attr:attr) => none | `(attr| $a) => some a (id, xs) | _ => default /-- The `globalAttributeInLinter` linter flags any global attributes generated by an `attribute [...] in` declaration. (This includes the `instance`, `simp` and `ext` attributes.) Despite the `in`, these define *global* instances, which can be rather misleading. Instead, remove the `in` or mark them with `local`. -/ def globalAttributeIn : Linter where run := withSetOptionIn fun stx => do unless getLinterGlobalAttributeIn (← getLinterOptions) do return if (← MonadState.get).messages.hasErrors then return for s in stx.topDown do if let .some (id, nonScopedNorLocal) := getGlobalAttributesIn? s then for attr in nonScopedNorLocal do Linter.logLint linter.globalAttributeIn attr m! "Despite the `in`, the attribute '{attr}' is added globally to '{id}'\n\ please remove the `in` or make this a `local {attr}`" initialize addLinter globalAttributeIn end globalAttributeInLinter end Mathlib.Linter
borelize.lean
import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic set_option autoImplicit true example [TopologicalSpace α] [inst : MeasurableSpace α] [BorelSpace α] : MeasurableSet (∅ : Set α) := by guard_target = @MeasurableSet α inst ∅ borelize α guard_target = @MeasurableSet α (borel α) ∅ apply MeasurableSet.empty example [TopologicalSpace α] : True := by borelize α have h : MeasurableSet (∅ : Set α) := MeasurableSet.empty guard_hyp h : @MeasurableSet α (borel α) ∅ trivial example : True := by obtain ⟨α, ⟨hα⟩⟩ : ∃ α : Type, Nonempty (TopologicalSpace α) := ⟨ℕ, ⟨inferInstance⟩⟩ borelize α have h : MeasurableSet (∅ : Set α) := MeasurableSet.empty guard_hyp h : @MeasurableSet α (borel α) ∅ trivial example : True := by set α := ℕ borelize α have h : MeasurableSet (∅ : Set α) := MeasurableSet.empty guard_hyp h : @MeasurableSet α (borel α) ∅ trivial example : True := by have h1 : MeasurableSet (∅ : Set ℕ) := MeasurableSet.empty guard_hyp h1 : @MeasurableSet ℕ Nat.instMeasurableSpace ∅ borelize ℕ have h2 : MeasurableSet (∅ : Set ℕ) := MeasurableSet.empty guard_hyp h2 : @MeasurableSet ℕ (borel ℕ) ∅ trivial
InvariantForm.lean
/- Copyright (c) 2024 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.Lie.Semisimple.Defs import Mathlib.LinearAlgebra.BilinearForm.Orthogonal /-! # Lie algebras with non-degenerate invariant bilinear forms are semisimple In this file we prove that a finite-dimensional Lie algebra over a field is semisimple if it does not have non-trivial abelian ideals and it admits a non-degenerate reflexive invariant bilinear form. Here a form is *invariant* if it invariant under the Lie bracket in the sense that `⁅x, Φ⁆ = 0` for all `x` or equivalently, `Φ ⁅x, y⁆ z = Φ x ⁅y, z⁆`. ## Main results * `LieAlgebra.InvariantForm.orthogonal`: given a Lie submodule `N` of a Lie module `M`, we define its orthogonal complement with respect to a non-degenerate invariant bilinear form `Φ` as the Lie ideal of elements `x` such that `Φ n x = 0` for all `n ∈ N`. * `LieAlgebra.InvariantForm.isSemisimple_of_nondegenerate`: the main result of this file; a finite-dimensional Lie algebra over a field is semisimple if it does not have non-trivial abelian ideals and admits a non-degenerate invariant reflexive bilinear form. ## References We follow the short and excellent paper [dieudonne1953]. -/ namespace LieAlgebra namespace InvariantForm section ring variable {R L M : Type*} variable [CommRing R] [LieRing L] variable [AddCommGroup M] [Module R M] [LieRingModule L M] variable (Φ : LinearMap.BilinForm R M) (hΦ_nondeg : Φ.Nondegenerate) variable (L) in /-- A bilinear form on a Lie module `M` of a Lie algebra `L` is *invariant* if for all `x : L` and `y z : M` the condition `Φ ⁅x, y⁆ z = -Φ y ⁅x, z⁆` holds. -/ def _root_.LinearMap.BilinForm.lieInvariant : Prop := ∀ (x : L) (y z : M), Φ ⁅x, y⁆ z = -Φ y ⁅x, z⁆ lemma _root_.LinearMap.BilinForm.lieInvariant_iff [LieAlgebra R L] [LieModule R L M] : Φ.lieInvariant L ↔ Φ ∈ LieModule.maxTrivSubmodule R L (LinearMap.BilinForm R M) := by refine ⟨fun h x ↦ ?_, fun h x y z ↦ ?_⟩ · ext y z rw [LieHom.lie_apply, LinearMap.sub_apply, Module.Dual.lie_apply, LinearMap.zero_apply, LinearMap.zero_apply, h, sub_self] · replace h := LinearMap.congr_fun₂ (h x) y z simp only [LieHom.lie_apply, LinearMap.sub_apply, Module.Dual.lie_apply, LinearMap.zero_apply, sub_eq_zero] at h simp [← h] /-- The orthogonal complement of a Lie submodule `N` with respect to an invariant bilinear form `Φ` is the Lie submodule of elements `y` such that `Φ x y = 0` for all `x ∈ N`. -/ @[simps!] def orthogonal (hΦ_inv : Φ.lieInvariant L) (N : LieSubmodule R L M) : LieSubmodule R L M where __ := Φ.orthogonal N lie_mem {x y} := by suffices (∀ n ∈ N, Φ n y = 0) → ∀ n ∈ N, Φ n ⁅x, y⁆ = 0 by simpa only [LinearMap.BilinForm.isOrtho_def, -- and some default simp lemmas AddSubsemigroup.mem_carrier, AddSubmonoid.mem_toSubsemigroup, Submodule.mem_toAddSubmonoid, LinearMap.BilinForm.mem_orthogonal_iff, LieSubmodule.mem_toSubmodule] intro H a ha rw [← neg_eq_zero, ← hΦ_inv] exact H _ <| N.lie_mem ha variable (hΦ_inv : Φ.lieInvariant L) @[simp] lemma orthogonal_toSubmodule (N : LieSubmodule R L M) : (orthogonal Φ hΦ_inv N).toSubmodule = Φ.orthogonal N.toSubmodule := rfl lemma mem_orthogonal (N : LieSubmodule R L M) (y : M) : y ∈ orthogonal Φ hΦ_inv N ↔ ∀ x ∈ N, Φ x y = 0 := by simp [orthogonal, LinearMap.BilinForm.isOrtho_def, LinearMap.BilinForm.mem_orthogonal_iff] variable [LieAlgebra R L] lemma orthogonal_disjoint (Φ : LinearMap.BilinForm R L) (hΦ_nondeg : Φ.Nondegenerate) (hΦ_inv : Φ.lieInvariant L) -- TODO: replace the following assumption by a typeclass assumption `[HasNonAbelianAtoms]` (hL : ∀ I : LieIdeal R L, IsAtom I → ¬IsLieAbelian I) (I : LieIdeal R L) (hI : IsAtom I) : Disjoint I (orthogonal Φ hΦ_inv I) := by rw [disjoint_iff, ← hI.lt_iff, lt_iff_le_and_ne] suffices ¬I ≤ orthogonal Φ hΦ_inv I by simpa intro contra apply hI.1 rw [eq_bot_iff, ← lie_eq_self_of_isAtom_of_nonabelian I hI (hL I hI), LieSubmodule.lieIdeal_oper_eq_span, LieSubmodule.lieSpan_le] rintro _ ⟨x, y, rfl⟩ simp only [LieSubmodule.bot_coe, Set.mem_singleton_iff] apply hΦ_nondeg intro z rw [hΦ_inv, neg_eq_zero] have hyz : ⁅(x : L), z⁆ ∈ I := lie_mem_left _ _ _ _ _ x.2 exact contra hyz y y.2 end ring section field variable {K L M : Type*} variable [Field K] [LieRing L] [LieAlgebra K L] variable [AddCommGroup M] [Module K M] [LieRingModule L M] variable [Module.Finite K L] variable (Φ : LinearMap.BilinForm K L) (hΦ_nondeg : Φ.Nondegenerate) variable (hΦ_inv : Φ.lieInvariant L) (hΦ_refl : Φ.IsRefl) -- TODO: replace the following assumption by a typeclass assumption `[HasNonAbelianAtoms]` variable (hL : ∀ I : LieIdeal K L, IsAtom I → ¬IsLieAbelian I) include hΦ_nondeg hΦ_refl hL open Module Submodule in lemma orthogonal_isCompl_toSubmodule (I : LieIdeal K L) (hI : IsAtom I) : IsCompl I.toSubmodule (orthogonal Φ hΦ_inv I).toSubmodule := by rw [orthogonal_toSubmodule, LinearMap.BilinForm.isCompl_orthogonal_iff_disjoint hΦ_refl, ← orthogonal_toSubmodule _ hΦ_inv, LieSubmodule.disjoint_toSubmodule] exact orthogonal_disjoint Φ hΦ_nondeg hΦ_inv hL I hI open Module Submodule in lemma orthogonal_isCompl (I : LieIdeal K L) (hI : IsAtom I) : IsCompl I (orthogonal Φ hΦ_inv I) := by rw [← LieSubmodule.isCompl_toSubmodule] exact orthogonal_isCompl_toSubmodule Φ hΦ_nondeg hΦ_inv hΦ_refl hL I hI include hΦ_inv lemma restrict_nondegenerate (I : LieIdeal K L) (hI : IsAtom I) : (Φ.restrict I).Nondegenerate := by rw [LinearMap.BilinForm.restrict_nondegenerate_iff_isCompl_orthogonal hΦ_refl] exact orthogonal_isCompl_toSubmodule Φ hΦ_nondeg hΦ_inv hΦ_refl hL I hI lemma restrict_orthogonal_nondegenerate (I : LieIdeal K L) (hI : IsAtom I) : (Φ.restrict (orthogonal Φ hΦ_inv I)).Nondegenerate := by rw [LinearMap.BilinForm.restrict_nondegenerate_iff_isCompl_orthogonal hΦ_refl] simp only [LieIdeal.toLieSubalgebra_toSubmodule, orthogonal_toSubmodule, LinearMap.BilinForm.orthogonal_orthogonal hΦ_nondeg hΦ_refl] exact (orthogonal_isCompl_toSubmodule Φ hΦ_nondeg hΦ_inv hΦ_refl hL I hI).symm open Module Submodule in lemma atomistic : ∀ I : LieIdeal K L, sSup {J : LieIdeal K L | IsAtom J ∧ J ≤ I} = I := by intro I apply le_antisymm · apply sSup_le rintro J ⟨-, hJ'⟩ exact hJ' by_cases hI : I = ⊥ · exact hI.le.trans bot_le obtain ⟨J, hJ, hJI⟩ := (eq_bot_or_exists_atom_le I).resolve_left hI let J' := orthogonal Φ hΦ_inv J suffices I ≤ J ⊔ (J' ⊓ I) by refine this.trans ?_ apply sup_le · exact le_sSup ⟨hJ, hJI⟩ rw [← atomistic (J' ⊓ I)] apply sSup_le_sSup simp only [le_inf_iff, Set.setOf_subset_setOf, and_imp] tauto suffices J ⊔ J' = ⊤ by rw [← sup_inf_assoc_of_le _ hJI, this, top_inf_eq] exact (orthogonal_isCompl Φ hΦ_nondeg hΦ_inv hΦ_refl hL J hJ).codisjoint.eq_top termination_by I => finrank K I decreasing_by apply finrank_lt_finrank_of_lt suffices ¬I ≤ J' by simpa intro hIJ' apply hJ.1 rw [eq_bot_iff] exact orthogonal_disjoint Φ hΦ_nondeg hΦ_inv hL J hJ le_rfl (hJI.trans hIJ') open LieSubmodule in /-- A finite-dimensional Lie algebra over a field is semisimple if it does not have non-trivial abelian ideals and it admits a non-degenerate reflexive invariant bilinear form. Here a form is *invariant* if it is compatible with the Lie bracket: `Φ ⁅x, y⁆ z = Φ x ⁅y, z⁆`. -/ theorem isSemisimple_of_nondegenerate : IsSemisimple K L := by refine ⟨?_, ?_, hL⟩ · simpa using atomistic Φ hΦ_nondeg hΦ_inv hΦ_refl hL ⊤ intro I hI apply (orthogonal_disjoint Φ hΦ_nondeg hΦ_inv hL I hI).mono_right apply sSup_le simp only [Set.mem_diff, Set.mem_setOf_eq, Set.mem_singleton_iff, and_imp] intro J hJ hJI rw [← lie_eq_self_of_isAtom_of_nonabelian J hJ (hL J hJ), lieIdeal_oper_eq_span, lieSpan_le] rintro _ ⟨x, y, rfl⟩ simp only [orthogonal_carrier, Φ.isOrtho_def, Set.mem_setOf_eq] intro z hz rw [← neg_eq_zero, ← hΦ_inv] suffices ⁅(x : L), z⁆ = 0 by simp only [this, map_zero, LinearMap.zero_apply] rw [← LieSubmodule.mem_bot (R := K) (L := L), ← (hJ.disjoint_of_ne hI hJI).eq_bot] apply lie_le_inf exact lie_mem_lie x.2 hz end field end InvariantForm end LieAlgebra
Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import Mathlib.Data.Set.SymmDiff import Mathlib.Order.SuccPred.Relation import Mathlib.Topology.Irreducible /-! # Connected subsets of topological spaces In this file we define connected subsets of a topological spaces and various other properties and classes related to connectivity. ## Main definitions We define the following properties for sets in a topological space: * `IsConnected`: a nonempty set that has no non-trivial open partition. See also the section below in the module doc. * `connectedComponent` is the connected component of an element in the space. We also have a class stating that the whole space satisfies that property: `ConnectedSpace` ## On the definition of connected sets/spaces In informal mathematics, connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `IsPreconnected`. In other words, the only difference is whether the empty space counts as connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open Set Function Topology TopologicalSpace Relation universe u v variable {α : Type u} {β : Type v} {ι : Type*} {X : ι → Type*} [TopologicalSpace α] {s t u v : Set α} section Preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def IsPreconnected (s : Set α) : Prop := ∀ u v : Set α, IsOpen u → IsOpen v → s ⊆ u ∪ v → (s ∩ u).Nonempty → (s ∩ v).Nonempty → (s ∩ (u ∩ v)).Nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def IsConnected (s : Set α) : Prop := s.Nonempty ∧ IsPreconnected s theorem IsConnected.nonempty {s : Set α} (h : IsConnected s) : s.Nonempty := h.1 theorem IsConnected.isPreconnected {s : Set α} (h : IsConnected s) : IsPreconnected s := h.2 theorem IsPreirreducible.isPreconnected {s : Set α} (H : IsPreirreducible s) : IsPreconnected s := fun _ _ hu hv _ => H _ _ hu hv theorem IsIrreducible.isConnected {s : Set α} (H : IsIrreducible s) : IsConnected s := ⟨H.nonempty, H.isPreirreducible.isPreconnected⟩ theorem isPreconnected_empty : IsPreconnected (∅ : Set α) := isPreirreducible_empty.isPreconnected theorem isConnected_singleton {x} : IsConnected ({x} : Set α) := isIrreducible_singleton.isConnected theorem isPreconnected_singleton {x} : IsPreconnected ({x} : Set α) := isConnected_singleton.isPreconnected theorem Set.Subsingleton.isPreconnected {s : Set α} (hs : s.Subsingleton) : IsPreconnected s := hs.induction_on isPreconnected_empty fun _ => isPreconnected_singleton /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem isPreconnected_of_forall {s : Set α} (x : α) (H : ∀ y ∈ s, ∃ t, t ⊆ s ∧ x ∈ t ∧ y ∈ t ∧ IsPreconnected t) : IsPreconnected s := by rintro u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩ have xs : x ∈ s := by rcases H y ys with ⟨t, ts, xt, -, -⟩ exact ts xt -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11215): TODO: use `wlog xu : x ∈ u := hs xs using u v y z, v u z y` cases hs xs with | inl xu => rcases H y ys with ⟨t, ts, xt, yt, ht⟩ have := ht u v hu hv (ts.trans hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩ exact this.imp fun z hz => ⟨ts hz.1, hz.2⟩ | inr xv => rcases H z zs with ⟨t, ts, xt, zt, ht⟩ have := ht v u hv hu (ts.trans <| by rwa [union_comm]) ⟨x, xt, xv⟩ ⟨z, zt, zu⟩ exact this.imp fun _ h => ⟨ts h.1, h.2.2, h.2.1⟩ /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem isPreconnected_of_forall_pair {s : Set α} (H : ∀ x ∈ s, ∀ y ∈ s, ∃ t, t ⊆ s ∧ x ∈ t ∧ y ∈ t ∧ IsPreconnected t) : IsPreconnected s := by rcases eq_empty_or_nonempty s with (rfl | ⟨x, hx⟩) exacts [isPreconnected_empty, isPreconnected_of_forall x fun y => H x hx y] /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem isPreconnected_sUnion (x : α) (c : Set (Set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, IsPreconnected s) : IsPreconnected (⋃₀ c) := by apply isPreconnected_of_forall x rintro y ⟨s, sc, ys⟩ exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ theorem isPreconnected_iUnion {ι : Sort*} {s : ι → Set α} (h₁ : (⋂ i, s i).Nonempty) (h₂ : ∀ i, IsPreconnected (s i)) : IsPreconnected (⋃ i, s i) := Exists.elim h₁ fun f hf => isPreconnected_sUnion f _ hf (forall_mem_range.2 h₂) theorem IsPreconnected.union (x : α) {s t : Set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : IsPreconnected s) (H4 : IsPreconnected t) : IsPreconnected (s ∪ t) := sUnion_pair s t ▸ isPreconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h) <;> assumption) (by rintro r (rfl | rfl | h) <;> assumption) theorem IsPreconnected.union' {s t : Set α} (H : (s ∩ t).Nonempty) (hs : IsPreconnected s) (ht : IsPreconnected t) : IsPreconnected (s ∪ t) := by rcases H with ⟨x, hxs, hxt⟩ exact hs.union x hxs hxt ht theorem IsConnected.union {s t : Set α} (H : (s ∩ t).Nonempty) (Hs : IsConnected s) (Ht : IsConnected t) : IsConnected (s ∪ t) := by rcases H with ⟨x, hx⟩ refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, ?_⟩ exact Hs.isPreconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Ht.isPreconnected /-- The directed sUnion of a set S of preconnected subsets is preconnected. -/ theorem IsPreconnected.sUnion_directed {S : Set (Set α)} (K : DirectedOn (· ⊆ ·) S) (H : ∀ s ∈ S, IsPreconnected s) : IsPreconnected (⋃₀ S) := by rintro u v hu hv Huv ⟨a, ⟨s, hsS, has⟩, hau⟩ ⟨b, ⟨t, htS, hbt⟩, hbv⟩ obtain ⟨r, hrS, hsr, htr⟩ : ∃ r ∈ S, s ⊆ r ∧ t ⊆ r := K s hsS t htS have Hnuv : (r ∩ (u ∩ v)).Nonempty := H _ hrS u v hu hv ((subset_sUnion_of_mem hrS).trans Huv) ⟨a, hsr has, hau⟩ ⟨b, htr hbt, hbv⟩ have Kruv : r ∩ (u ∩ v) ⊆ ⋃₀ S ∩ (u ∩ v) := inter_subset_inter_left _ (subset_sUnion_of_mem hrS) exact Hnuv.mono Kruv /-- The biUnion of a family of preconnected sets is preconnected if the graph determined by whether two sets intersect is preconnected. -/ theorem IsPreconnected.biUnion_of_reflTransGen {ι : Type*} {t : Set ι} {s : ι → Set α} (H : ∀ i ∈ t, IsPreconnected (s i)) (K : ∀ i, i ∈ t → ∀ j, j ∈ t → ReflTransGen (fun i j => (s i ∩ s j).Nonempty ∧ i ∈ t) i j) : IsPreconnected (⋃ n ∈ t, s n) := by let R := fun i j : ι => (s i ∩ s j).Nonempty ∧ i ∈ t have P : ∀ i, i ∈ t → ∀ j, j ∈ t → ReflTransGen R i j → ∃ p, p ⊆ t ∧ i ∈ p ∧ j ∈ p ∧ IsPreconnected (⋃ j ∈ p, s j) := fun i hi j hj h => by induction h with | refl => refine ⟨{i}, singleton_subset_iff.mpr hi, mem_singleton i, mem_singleton i, ?_⟩ rw [biUnion_singleton] exact H i hi | @tail j k _ hjk ih => obtain ⟨p, hpt, hip, hjp, hp⟩ := ih hjk.2 refine ⟨insert k p, insert_subset_iff.mpr ⟨hj, hpt⟩, mem_insert_of_mem k hip, mem_insert k p, ?_⟩ rw [biUnion_insert] refine (H k hj).union' (hjk.1.mono ?_) hp rw [inter_comm] exact inter_subset_inter_right _ (subset_biUnion_of_mem hjp) refine isPreconnected_of_forall_pair ?_ intro x hx y hy obtain ⟨i : ι, hi : i ∈ t, hxi : x ∈ s i⟩ := mem_iUnion₂.1 hx obtain ⟨j : ι, hj : j ∈ t, hyj : y ∈ s j⟩ := mem_iUnion₂.1 hy obtain ⟨p, hpt, hip, hjp, hp⟩ := P i hi j hj (K i hi j hj) exact ⟨⋃ j ∈ p, s j, biUnion_subset_biUnion_left hpt, mem_biUnion hip hxi, mem_biUnion hjp hyj, hp⟩ /-- The biUnion of a family of preconnected sets is preconnected if the graph determined by whether two sets intersect is preconnected. -/ theorem IsConnected.biUnion_of_reflTransGen {ι : Type*} {t : Set ι} {s : ι → Set α} (ht : t.Nonempty) (H : ∀ i ∈ t, IsConnected (s i)) (K : ∀ i, i ∈ t → ∀ j, j ∈ t → ReflTransGen (fun i j : ι => (s i ∩ s j).Nonempty ∧ i ∈ t) i j) : IsConnected (⋃ n ∈ t, s n) := ⟨nonempty_biUnion.2 <| ⟨ht.some, ht.some_mem, (H _ ht.some_mem).nonempty⟩, IsPreconnected.biUnion_of_reflTransGen (fun i hi => (H i hi).isPreconnected) K⟩ /-- Preconnectedness of the iUnion of a family of preconnected sets indexed by the vertices of a preconnected graph, where two vertices are joined when the corresponding sets intersect. -/ theorem IsPreconnected.iUnion_of_reflTransGen {ι : Type*} {s : ι → Set α} (H : ∀ i, IsPreconnected (s i)) (K : ∀ i j, ReflTransGen (fun i j : ι => (s i ∩ s j).Nonempty) i j) : IsPreconnected (⋃ n, s n) := by rw [← biUnion_univ] exact IsPreconnected.biUnion_of_reflTransGen (fun i _ => H i) fun i _ j _ => by simpa [mem_univ] using K i j theorem IsConnected.iUnion_of_reflTransGen {ι : Type*} [Nonempty ι] {s : ι → Set α} (H : ∀ i, IsConnected (s i)) (K : ∀ i j, ReflTransGen (fun i j : ι => (s i ∩ s j).Nonempty) i j) : IsConnected (⋃ n, s n) := ⟨nonempty_iUnion.2 <| Nonempty.elim ‹_› fun i : ι => ⟨i, (H _).nonempty⟩, IsPreconnected.iUnion_of_reflTransGen (fun i => (H i).isPreconnected) K⟩ section SuccOrder open Order variable [LinearOrder β] [SuccOrder β] [IsSuccArchimedean β] /-- The iUnion of connected sets indexed by a type with an archimedean successor (like `ℕ` or `ℤ`) such that any two neighboring sets meet is preconnected. -/ theorem IsPreconnected.iUnion_of_chain {s : β → Set α} (H : ∀ n, IsPreconnected (s n)) (K : ∀ n, (s n ∩ s (succ n)).Nonempty) : IsPreconnected (⋃ n, s n) := IsPreconnected.iUnion_of_reflTransGen H fun _ _ => reflTransGen_of_succ _ (fun i _ => K i) fun i _ => by rw [inter_comm] exact K i /-- The iUnion of connected sets indexed by a type with an archimedean successor (like `ℕ` or `ℤ`) such that any two neighboring sets meet is connected. -/ theorem IsConnected.iUnion_of_chain [Nonempty β] {s : β → Set α} (H : ∀ n, IsConnected (s n)) (K : ∀ n, (s n ∩ s (succ n)).Nonempty) : IsConnected (⋃ n, s n) := IsConnected.iUnion_of_reflTransGen H fun _ _ => reflTransGen_of_succ _ (fun i _ => K i) fun i _ => by rw [inter_comm] exact K i /-- The iUnion of preconnected sets indexed by a subset of a type with an archimedean successor (like `ℕ` or `ℤ`) such that any two neighboring sets meet is preconnected. -/ theorem IsPreconnected.biUnion_of_chain {s : β → Set α} {t : Set β} (ht : OrdConnected t) (H : ∀ n ∈ t, IsPreconnected (s n)) (K : ∀ n : β, n ∈ t → succ n ∈ t → (s n ∩ s (succ n)).Nonempty) : IsPreconnected (⋃ n ∈ t, s n) := by have h1 : ∀ {i j k : β}, i ∈ t → j ∈ t → k ∈ Ico i j → k ∈ t := fun hi hj hk => ht.out hi hj (Ico_subset_Icc_self hk) have h2 : ∀ {i j k : β}, i ∈ t → j ∈ t → k ∈ Ico i j → succ k ∈ t := fun hi hj hk => ht.out hi hj ⟨hk.1.trans <| le_succ _, succ_le_of_lt hk.2⟩ have h3 : ∀ {i j k : β}, i ∈ t → j ∈ t → k ∈ Ico i j → (s k ∩ s (succ k)).Nonempty := fun hi hj hk => K _ (h1 hi hj hk) (h2 hi hj hk) refine IsPreconnected.biUnion_of_reflTransGen H fun i hi j hj => ?_ exact reflTransGen_of_succ _ (fun k hk => ⟨h3 hi hj hk, h1 hi hj hk⟩) fun k hk => ⟨by rw [inter_comm]; exact h3 hj hi hk, h2 hj hi hk⟩ /-- The iUnion of connected sets indexed by a subset of a type with an archimedean successor (like `ℕ` or `ℤ`) such that any two neighboring sets meet is preconnected. -/ theorem IsConnected.biUnion_of_chain {s : β → Set α} {t : Set β} (hnt : t.Nonempty) (ht : OrdConnected t) (H : ∀ n ∈ t, IsConnected (s n)) (K : ∀ n : β, n ∈ t → succ n ∈ t → (s n ∩ s (succ n)).Nonempty) : IsConnected (⋃ n ∈ t, s n) := ⟨nonempty_biUnion.2 <| ⟨hnt.some, hnt.some_mem, (H _ hnt.some_mem).nonempty⟩, IsPreconnected.biUnion_of_chain ht (fun i hi => (H i hi).isPreconnected) K⟩ end SuccOrder /-- Theorem of bark and tree: if a set is within a preconnected set and its closure, then it is preconnected as well. See also `IsConnected.subset_closure`. -/ protected theorem IsPreconnected.subset_closure {s : Set α} {t : Set α} (H : IsPreconnected s) (Kst : s ⊆ t) (Ktcs : t ⊆ closure s) : IsPreconnected t := fun u v hu hv htuv ⟨_y, hyt, hyu⟩ ⟨_z, hzt, hzv⟩ => let ⟨p, hpu, hps⟩ := mem_closure_iff.1 (Ktcs hyt) u hu hyu let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 (Ktcs hzt) v hv hzv let ⟨r, hrs, hruv⟩ := H u v hu hv (Subset.trans Kst htuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ ⟨r, Kst hrs, hruv⟩ /-- Theorem of bark and tree: if a set is within a connected set and its closure, then it is connected as well. See also `IsPreconnected.subset_closure`. -/ protected theorem IsConnected.subset_closure {s : Set α} {t : Set α} (H : IsConnected s) (Kst : s ⊆ t) (Ktcs : t ⊆ closure s) : IsConnected t := ⟨Nonempty.mono Kst H.left, IsPreconnected.subset_closure H.right Kst Ktcs⟩ /-- The closure of a preconnected set is preconnected as well. -/ protected theorem IsPreconnected.closure {s : Set α} (H : IsPreconnected s) : IsPreconnected (closure s) := IsPreconnected.subset_closure H subset_closure Subset.rfl /-- The closure of a connected set is connected as well. -/ protected theorem IsConnected.closure {s : Set α} (H : IsConnected s) : IsConnected (closure s) := IsConnected.subset_closure H subset_closure <| Subset.rfl /-- The image of a preconnected set is preconnected as well. -/ protected theorem IsPreconnected.image [TopologicalSpace β] {s : Set α} (H : IsPreconnected s) (f : α → β) (hf : ContinuousOn f s) : IsPreconnected (f '' s) := by -- Unfold/destruct definitions in hypotheses rintro u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩ rcases continuousOn_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩ rcases continuousOn_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩ -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v' := by rw [image_subset_iff, preimage_union] at huv replace huv := subset_inter huv Subset.rfl rw [union_inter_distrib_right, u'_eq, v'_eq, ← union_inter_distrib_right] at huv exact (subset_inter_iff.1 huv).1 -- Now `s ⊆ u' ∪ v'`, so we can apply `‹IsPreconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).Nonempty := by refine H u' v' hu' hv' huv ⟨x, ?_⟩ ⟨y, ?_⟩ <;> rw [inter_comm] exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ /-- The image of a connected set is connected as well. -/ protected theorem IsConnected.image [TopologicalSpace β] {s : Set α} (H : IsConnected s) (f : α → β) (hf : ContinuousOn f s) : IsConnected (f '' s) := ⟨image_nonempty.mpr H.nonempty, H.isPreconnected.image f hf⟩ theorem isPreconnected_closed_iff {s : Set α} : IsPreconnected s ↔ ∀ t t', IsClosed t → IsClosed t' → s ⊆ t ∪ t' → (s ∩ t).Nonempty → (s ∩ t').Nonempty → (s ∩ (t ∩ t')).Nonempty := ⟨by rintro h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩ rw [← not_disjoint_iff_nonempty_inter, ← subset_compl_iff_disjoint_right, compl_inter] intro h' have xt' : x ∉ t' := (h' xs).resolve_left (absurd xt) have yt : y ∉ t := (h' ys).resolve_right (absurd yt') have := h _ _ ht.isOpen_compl ht'.isOpen_compl h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩ rw [← compl_union] at this exact this.ne_empty htt'.disjoint_compl_right.inter_eq, by rintro h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩ rw [← not_disjoint_iff_nonempty_inter, ← subset_compl_iff_disjoint_right, compl_inter] intro h' have xv : x ∉ v := (h' xs).elim (absurd xu) id have yu : y ∉ u := (h' ys).elim id (absurd yv) have := h _ _ hu.isClosed_compl hv.isClosed_compl h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩ rw [← compl_union] at this exact this.ne_empty huv.disjoint_compl_right.inter_eq⟩ theorem Topology.IsInducing.isPreconnected_image [TopologicalSpace β] {s : Set α} {f : α → β} (hf : IsInducing f) : IsPreconnected (f '' s) ↔ IsPreconnected s := by refine ⟨fun h => ?_, fun h => h.image _ hf.continuous.continuousOn⟩ rintro u v hu' hv' huv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ rcases hf.isOpen_iff.1 hu' with ⟨u, hu, rfl⟩ rcases hf.isOpen_iff.1 hv' with ⟨v, hv, rfl⟩ replace huv : f '' s ⊆ u ∪ v := by rwa [image_subset_iff] rcases h u v hu hv huv ⟨f x, mem_image_of_mem _ hxs, hxu⟩ ⟨f y, mem_image_of_mem _ hys, hyv⟩ with ⟨_, ⟨z, hzs, rfl⟩, hzuv⟩ exact ⟨z, hzs, hzuv⟩ /- TODO: The following lemmas about connection of preimages hold more generally for strict maps (the quotient and subspace topologies of the image agree) whose fibers are preconnected. -/ theorem IsPreconnected.preimage_of_isOpenMap [TopologicalSpace β] {f : α → β} {s : Set β} (hs : IsPreconnected s) (hinj : Function.Injective f) (hf : IsOpenMap f) (hsf : s ⊆ range f) : IsPreconnected (f ⁻¹' s) := fun u v hu hv hsuv hsu hsv => by replace hsf : f '' (f ⁻¹' s) = s := image_preimage_eq_of_subset hsf obtain ⟨_, has, ⟨a, hau, rfl⟩, hav⟩ : (s ∩ (f '' u ∩ f '' v)).Nonempty := by refine hs (f '' u) (f '' v) (hf u hu) (hf v hv) ?_ ?_ ?_ · simpa only [hsf, image_union] using image_mono (f := f) hsuv · simpa only [image_preimage_inter] using hsu.image f · simpa only [image_preimage_inter] using hsv.image f · exact ⟨a, has, hau, hinj.mem_set_image.1 hav⟩ theorem IsPreconnected.preimage_of_isClosedMap [TopologicalSpace β] {s : Set β} (hs : IsPreconnected s) {f : α → β} (hinj : Function.Injective f) (hf : IsClosedMap f) (hsf : s ⊆ range f) : IsPreconnected (f ⁻¹' s) := isPreconnected_closed_iff.2 fun u v hu hv hsuv hsu hsv => by replace hsf : f '' (f ⁻¹' s) = s := image_preimage_eq_of_subset hsf obtain ⟨_, has, ⟨a, hau, rfl⟩, hav⟩ : (s ∩ (f '' u ∩ f '' v)).Nonempty := by refine isPreconnected_closed_iff.1 hs (f '' u) (f '' v) (hf u hu) (hf v hv) ?_ ?_ ?_ · simpa only [hsf, image_union] using image_mono (f := f) hsuv · simpa only [image_preimage_inter] using hsu.image f · simpa only [image_preimage_inter] using hsv.image f · exact ⟨a, has, hau, hinj.mem_set_image.1 hav⟩ theorem IsConnected.preimage_of_isOpenMap [TopologicalSpace β] {s : Set β} (hs : IsConnected s) {f : α → β} (hinj : Function.Injective f) (hf : IsOpenMap f) (hsf : s ⊆ range f) : IsConnected (f ⁻¹' s) := ⟨hs.nonempty.preimage' hsf, hs.isPreconnected.preimage_of_isOpenMap hinj hf hsf⟩ theorem IsConnected.preimage_of_isClosedMap [TopologicalSpace β] {s : Set β} (hs : IsConnected s) {f : α → β} (hinj : Function.Injective f) (hf : IsClosedMap f) (hsf : s ⊆ range f) : IsConnected (f ⁻¹' s) := ⟨hs.nonempty.preimage' hsf, hs.isPreconnected.preimage_of_isClosedMap hinj hf hsf⟩ theorem IsPreconnected.subset_or_subset (hu : IsOpen u) (hv : IsOpen v) (huv : Disjoint u v) (hsuv : s ⊆ u ∪ v) (hs : IsPreconnected s) : s ⊆ u ∨ s ⊆ v := by specialize hs u v hu hv hsuv obtain hsu | hsu := (s ∩ u).eq_empty_or_nonempty · exact Or.inr ((Set.disjoint_iff_inter_eq_empty.2 hsu).subset_right_of_subset_union hsuv) · replace hs := mt (hs hsu) simp_rw [Set.not_nonempty_iff_eq_empty, ← Set.disjoint_iff_inter_eq_empty, disjoint_iff_inter_eq_empty.1 huv] at hs exact Or.inl ((hs s.disjoint_empty).subset_left_of_subset_union hsuv) theorem IsPreconnected.subset_left_of_subset_union (hu : IsOpen u) (hv : IsOpen v) (huv : Disjoint u v) (hsuv : s ⊆ u ∪ v) (hsu : (s ∩ u).Nonempty) (hs : IsPreconnected s) : s ⊆ u := Disjoint.subset_left_of_subset_union hsuv (by by_contra hsv rw [not_disjoint_iff_nonempty_inter] at hsv obtain ⟨x, _, hx⟩ := hs u v hu hv hsuv hsu hsv exact Set.disjoint_iff.1 huv hx) theorem IsPreconnected.subset_right_of_subset_union (hu : IsOpen u) (hv : IsOpen v) (huv : Disjoint u v) (hsuv : s ⊆ u ∪ v) (hsv : (s ∩ v).Nonempty) (hs : IsPreconnected s) : s ⊆ v := hs.subset_left_of_subset_union hv hu huv.symm (union_comm u v ▸ hsuv) hsv /-- If a preconnected set `s` intersects an open set `u`, and limit points of `u` inside `s` are contained in `u`, then the whole set `s` is contained in `u`. -/ theorem IsPreconnected.subset_of_closure_inter_subset (hs : IsPreconnected s) (hu : IsOpen u) (h'u : (s ∩ u).Nonempty) (h : closure u ∩ s ⊆ u) : s ⊆ u := by have A : s ⊆ u ∪ (closure u)ᶜ := by intro x hx by_cases xu : x ∈ u · exact Or.inl xu · right intro h'x exact xu (h (mem_inter h'x hx)) apply hs.subset_left_of_subset_union hu isClosed_closure.isOpen_compl _ A h'u exact disjoint_compl_right.mono_right (compl_subset_compl.2 subset_closure) theorem IsPreconnected.prod [TopologicalSpace β] {s : Set α} {t : Set β} (hs : IsPreconnected s) (ht : IsPreconnected t) : IsPreconnected (s ×ˢ t) := by apply isPreconnected_of_forall_pair rintro ⟨a₁, b₁⟩ ⟨ha₁, hb₁⟩ ⟨a₂, b₂⟩ ⟨ha₂, hb₂⟩ refine ⟨Prod.mk a₁ '' t ∪ flip Prod.mk b₂ '' s, ?_, .inl ⟨b₁, hb₁, rfl⟩, .inr ⟨a₂, ha₂, rfl⟩, ?_⟩ · rintro _ (⟨y, hy, rfl⟩ | ⟨x, hx, rfl⟩) exacts [⟨ha₁, hy⟩, ⟨hx, hb₂⟩] · exact (ht.image _ (by fun_prop)).union (a₁, b₂) ⟨b₂, hb₂, rfl⟩ ⟨a₁, ha₁, rfl⟩ (hs.image _ (Continuous.prodMk_left _).continuousOn) theorem IsConnected.prod [TopologicalSpace β] {s : Set α} {t : Set β} (hs : IsConnected s) (ht : IsConnected t) : IsConnected (s ×ˢ t) := ⟨hs.1.prod ht.1, hs.2.prod ht.2⟩ theorem isPreconnected_univ_pi [∀ i, TopologicalSpace (X i)] {s : ∀ i, Set (X i)} (hs : ∀ i, IsPreconnected (s i)) : IsPreconnected (pi univ s) := by rintro u v uo vo hsuv ⟨f, hfs, hfu⟩ ⟨g, hgs, hgv⟩ classical rcases exists_finset_piecewise_mem_of_mem_nhds (uo.mem_nhds hfu) g with ⟨I, hI⟩ induction I using Finset.induction_on with | empty => refine ⟨g, hgs, ⟨?_, hgv⟩⟩ simpa using hI | insert i I _ ihI => rw [Finset.piecewise_insert] at hI have := I.piecewise_mem_set_pi hfs hgs refine (hsuv this).elim ihI fun h => ?_ set S := update (I.piecewise f g) i '' s i have hsub : S ⊆ pi univ s := by refine image_subset_iff.2 fun z hz => ?_ rwa [update_preimage_univ_pi] exact fun j _ => this j trivial have hconn : IsPreconnected S := (hs i).image _ (continuous_const.update i continuous_id).continuousOn have hSu : (S ∩ u).Nonempty := ⟨_, mem_image_of_mem _ (hfs _ trivial), hI⟩ have hSv : (S ∩ v).Nonempty := ⟨_, ⟨_, this _ trivial, update_eq_self _ _⟩, h⟩ refine (hconn u v uo vo (hsub.trans hsuv) hSu hSv).mono ?_ exact inter_subset_inter_left _ hsub @[simp] theorem isConnected_univ_pi [∀ i, TopologicalSpace (X i)] {s : ∀ i, Set (X i)} : IsConnected (pi univ s) ↔ ∀ i, IsConnected (s i) := by simp only [IsConnected, ← univ_pi_nonempty_iff, forall_and, and_congr_right_iff] refine fun hne => ⟨fun hc i => ?_, isPreconnected_univ_pi⟩ rw [← eval_image_univ_pi hne] exact hc.image _ (continuous_apply _).continuousOn /-- The connected component of a point is the maximal connected set that contains this point. -/ def connectedComponent (x : α) : Set α := ⋃₀ { s : Set α | IsPreconnected s ∧ x ∈ s } open Classical in /-- Given a set `F` in a topological space `α` and a point `x : α`, the connected component of `x` in `F` is the connected component of `x` in the subtype `F` seen as a set in `α`. This definition does not make sense if `x` is not in `F` so we return the empty set in this case. -/ def connectedComponentIn (F : Set α) (x : α) : Set α := if h : x ∈ F then (↑) '' connectedComponent (⟨x, h⟩ : F) else ∅ theorem connectedComponentIn_eq_image {F : Set α} {x : α} (h : x ∈ F) : connectedComponentIn F x = (↑) '' connectedComponent (⟨x, h⟩ : F) := dif_pos h theorem connectedComponentIn_eq_empty {F : Set α} {x : α} (h : x ∉ F) : connectedComponentIn F x = ∅ := dif_neg h theorem mem_connectedComponent {x : α} : x ∈ connectedComponent x := mem_sUnion_of_mem (mem_singleton x) ⟨isPreconnected_singleton, mem_singleton x⟩ theorem mem_connectedComponentIn {x : α} {F : Set α} (hx : x ∈ F) : x ∈ connectedComponentIn F x := by simp [connectedComponentIn_eq_image hx, mem_connectedComponent, hx] theorem connectedComponent_nonempty {x : α} : (connectedComponent x).Nonempty := ⟨x, mem_connectedComponent⟩ theorem connectedComponentIn_nonempty_iff {x : α} {F : Set α} : (connectedComponentIn F x).Nonempty ↔ x ∈ F := by rw [connectedComponentIn] split_ifs <;> simp [connectedComponent_nonempty, *] theorem connectedComponentIn_subset (F : Set α) (x : α) : connectedComponentIn F x ⊆ F := by rw [connectedComponentIn] split_ifs <;> simp theorem isPreconnected_connectedComponent {x : α} : IsPreconnected (connectedComponent x) := isPreconnected_sUnion x _ (fun _ => And.right) fun _ => And.left theorem isPreconnected_connectedComponentIn {x : α} {F : Set α} : IsPreconnected (connectedComponentIn F x) := by rw [connectedComponentIn]; split_ifs · exact IsInducing.subtypeVal.isPreconnected_image.mpr isPreconnected_connectedComponent · exact isPreconnected_empty theorem isConnected_connectedComponent {x : α} : IsConnected (connectedComponent x) := ⟨⟨x, mem_connectedComponent⟩, isPreconnected_connectedComponent⟩ theorem isConnected_connectedComponentIn_iff {x : α} {F : Set α} : IsConnected (connectedComponentIn F x) ↔ x ∈ F := by simp_rw [← connectedComponentIn_nonempty_iff, IsConnected, isPreconnected_connectedComponentIn, and_true] theorem IsPreconnected.subset_connectedComponent {x : α} {s : Set α} (H1 : IsPreconnected s) (H2 : x ∈ s) : s ⊆ connectedComponent x := fun _z hz => mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem IsPreconnected.subset_connectedComponentIn {x : α} {F : Set α} (hs : IsPreconnected s) (hxs : x ∈ s) (hsF : s ⊆ F) : s ⊆ connectedComponentIn F x := by have : IsPreconnected (((↑) : F → α) ⁻¹' s) := by refine IsInducing.subtypeVal.isPreconnected_image.mp ?_ rwa [Subtype.image_preimage_coe, inter_eq_right.mpr hsF] have h2xs : (⟨x, hsF hxs⟩ : F) ∈ (↑) ⁻¹' s := by rw [mem_preimage] exact hxs have := this.subset_connectedComponent h2xs rw [connectedComponentIn_eq_image (hsF hxs)] refine Subset.trans ?_ (image_mono this) rw [Subtype.image_preimage_coe, inter_eq_right.mpr hsF] theorem IsConnected.subset_connectedComponent {x : α} {s : Set α} (H1 : IsConnected s) (H2 : x ∈ s) : s ⊆ connectedComponent x := H1.2.subset_connectedComponent H2 theorem IsPreconnected.connectedComponentIn {x : α} {F : Set α} (h : IsPreconnected F) (hx : x ∈ F) : connectedComponentIn F x = F := (connectedComponentIn_subset F x).antisymm (h.subset_connectedComponentIn hx subset_rfl) theorem connectedComponent_eq {x y : α} (h : y ∈ connectedComponent x) : connectedComponent x = connectedComponent y := eq_of_subset_of_subset (isConnected_connectedComponent.subset_connectedComponent h) (isConnected_connectedComponent.subset_connectedComponent (Set.mem_of_mem_of_subset mem_connectedComponent (isConnected_connectedComponent.subset_connectedComponent h))) theorem connectedComponent_eq_iff_mem {x y : α} : connectedComponent x = connectedComponent y ↔ x ∈ connectedComponent y := ⟨fun h => h ▸ mem_connectedComponent, fun h => (connectedComponent_eq h).symm⟩ theorem connectedComponentIn_eq {x y : α} {F : Set α} (h : y ∈ connectedComponentIn F x) : connectedComponentIn F x = connectedComponentIn F y := by have hx : x ∈ F := connectedComponentIn_nonempty_iff.mp ⟨y, h⟩ simp_rw [connectedComponentIn_eq_image hx] at h ⊢ obtain ⟨⟨y, hy⟩, h2y, rfl⟩ := h simp_rw [connectedComponentIn_eq_image hy, connectedComponent_eq h2y] theorem connectedComponentIn_univ (x : α) : connectedComponentIn univ x = connectedComponent x := subset_antisymm (isPreconnected_connectedComponentIn.subset_connectedComponent <| mem_connectedComponentIn trivial) (isPreconnected_connectedComponent.subset_connectedComponentIn mem_connectedComponent <| subset_univ _) theorem connectedComponent_disjoint {x y : α} (h : connectedComponent x ≠ connectedComponent y) : Disjoint (connectedComponent x) (connectedComponent y) := Set.disjoint_left.2 fun _ h1 h2 => h ((connectedComponent_eq h1).trans (connectedComponent_eq h2).symm) theorem isClosed_connectedComponent {x : α} : IsClosed (connectedComponent x) := closure_subset_iff_isClosed.1 <| isConnected_connectedComponent.closure.subset_connectedComponent <| subset_closure mem_connectedComponent theorem Continuous.image_connectedComponent_subset [TopologicalSpace β] {f : α → β} (h : Continuous f) (a : α) : f '' connectedComponent a ⊆ connectedComponent (f a) := (isConnected_connectedComponent.image f h.continuousOn).subset_connectedComponent ((mem_image f (connectedComponent a) (f a)).2 ⟨a, mem_connectedComponent, rfl⟩) theorem Continuous.image_connectedComponentIn_subset [TopologicalSpace β] {f : α → β} {s : Set α} {a : α} (hf : Continuous f) (hx : a ∈ s) : f '' connectedComponentIn s a ⊆ connectedComponentIn (f '' s) (f a) := (isPreconnected_connectedComponentIn.image _ hf.continuousOn).subset_connectedComponentIn (mem_image_of_mem _ <| mem_connectedComponentIn hx) (image_mono <| connectedComponentIn_subset _ _) theorem Continuous.mapsTo_connectedComponent [TopologicalSpace β] {f : α → β} (h : Continuous f) (a : α) : MapsTo f (connectedComponent a) (connectedComponent (f a)) := mapsTo'.2 <| h.image_connectedComponent_subset a theorem Continuous.mapsTo_connectedComponentIn [TopologicalSpace β] {f : α → β} {s : Set α} (h : Continuous f) {a : α} (hx : a ∈ s) : MapsTo f (connectedComponentIn s a) (connectedComponentIn (f '' s) (f a)) := mapsTo'.2 <| image_connectedComponentIn_subset h hx theorem irreducibleComponent_subset_connectedComponent {x : α} : irreducibleComponent x ⊆ connectedComponent x := isIrreducible_irreducibleComponent.isConnected.subset_connectedComponent mem_irreducibleComponent @[mono] theorem connectedComponentIn_mono (x : α) {F G : Set α} (h : F ⊆ G) : connectedComponentIn F x ⊆ connectedComponentIn G x := by by_cases hx : x ∈ F · rw [connectedComponentIn_eq_image hx, connectedComponentIn_eq_image (h hx), ← show ((↑) : G → α) ∘ inclusion h = (↑) from rfl, image_comp] exact image_mono ((continuous_inclusion h).image_connectedComponent_subset ⟨x, hx⟩) · rw [connectedComponentIn_eq_empty hx] exact Set.empty_subset _ /-- A preconnected space is one where there is no non-trivial open partition. -/ class PreconnectedSpace (α : Type u) [TopologicalSpace α] : Prop where /-- The universal set `Set.univ` in a preconnected space is a preconnected set. -/ isPreconnected_univ : IsPreconnected (univ : Set α) export PreconnectedSpace (isPreconnected_univ) /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class ConnectedSpace (α : Type u) [TopologicalSpace α] : Prop extends PreconnectedSpace α where /-- A connected space is nonempty. -/ toNonempty : Nonempty α attribute [instance 50] ConnectedSpace.toNonempty -- see Note [lower instance priority] -- see Note [lower instance priority] theorem isConnected_univ [ConnectedSpace α] : IsConnected (univ : Set α) := ⟨univ_nonempty, isPreconnected_univ⟩ lemma preconnectedSpace_iff_univ : PreconnectedSpace α ↔ IsPreconnected (univ : Set α) := ⟨fun h ↦ h.1, fun h ↦ ⟨h⟩⟩ lemma connectedSpace_iff_univ : ConnectedSpace α ↔ IsConnected (univ : Set α) := ⟨fun h ↦ ⟨univ_nonempty, h.1.1⟩, fun h ↦ ConnectedSpace.mk (toPreconnectedSpace := ⟨h.2⟩) ⟨h.1.some⟩⟩ theorem isPreconnected_range [TopologicalSpace β] [PreconnectedSpace α] {f : α → β} (h : Continuous f) : IsPreconnected (range f) := @image_univ _ _ f ▸ isPreconnected_univ.image _ h.continuousOn theorem isConnected_range [TopologicalSpace β] [ConnectedSpace α] {f : α → β} (h : Continuous f) : IsConnected (range f) := ⟨range_nonempty f, isPreconnected_range h⟩ theorem Function.Surjective.connectedSpace [ConnectedSpace α] [TopologicalSpace β] {f : α → β} (hf : Surjective f) (hf' : Continuous f) : ConnectedSpace β := by rw [connectedSpace_iff_univ, ← hf.range_eq] exact isConnected_range hf' instance Quotient.instConnectedSpace {s : Setoid α} [ConnectedSpace α] : ConnectedSpace (Quotient s) := Quotient.mk'_surjective.connectedSpace continuous_coinduced_rng theorem DenseRange.preconnectedSpace [TopologicalSpace β] [PreconnectedSpace α] {f : α → β} (hf : DenseRange f) (hc : Continuous f) : PreconnectedSpace β := ⟨hf.closure_eq ▸ (isPreconnected_range hc).closure⟩ theorem connectedSpace_iff_connectedComponent : ConnectedSpace α ↔ ∃ x : α, connectedComponent x = univ := by constructor · rintro ⟨⟨x⟩⟩ exact ⟨x, eq_univ_of_univ_subset <| isPreconnected_univ.subset_connectedComponent (mem_univ x)⟩ · rintro ⟨x, h⟩ haveI : PreconnectedSpace α := ⟨by rw [← h]; exact isPreconnected_connectedComponent⟩ exact ⟨⟨x⟩⟩ theorem preconnectedSpace_iff_connectedComponent : PreconnectedSpace α ↔ ∀ x : α, connectedComponent x = univ := by constructor · intro h x exact eq_univ_of_univ_subset <| isPreconnected_univ.subset_connectedComponent (mem_univ x) · intro h rcases isEmpty_or_nonempty α with hα | hα · exact ⟨by rw [univ_eq_empty_iff.mpr hα]; exact isPreconnected_empty⟩ · exact ⟨by rw [← h (Classical.choice hα)]; exact isPreconnected_connectedComponent⟩ @[simp] theorem PreconnectedSpace.connectedComponent_eq_univ {X : Type*} [TopologicalSpace X] [h : PreconnectedSpace X] (x : X) : connectedComponent x = univ := preconnectedSpace_iff_connectedComponent.mp h x instance [TopologicalSpace β] [PreconnectedSpace α] [PreconnectedSpace β] : PreconnectedSpace (α × β) := ⟨by rw [← univ_prod_univ] exact isPreconnected_univ.prod isPreconnected_univ⟩ instance [TopologicalSpace β] [ConnectedSpace α] [ConnectedSpace β] : ConnectedSpace (α × β) := ⟨inferInstance⟩ instance [∀ i, TopologicalSpace (X i)] [∀ i, PreconnectedSpace (X i)] : PreconnectedSpace (∀ i, X i) := ⟨by rw [← pi_univ univ]; exact isPreconnected_univ_pi fun i => isPreconnected_univ⟩ instance [∀ i, TopologicalSpace (X i)] [∀ i, ConnectedSpace (X i)] : ConnectedSpace (∀ i, X i) := ⟨inferInstance⟩ -- see Note [lower instance priority] instance (priority := 100) PreirreducibleSpace.preconnectedSpace (α : Type u) [TopologicalSpace α] [PreirreducibleSpace α] : PreconnectedSpace α := ⟨isPreirreducible_univ.isPreconnected⟩ -- see Note [lower instance priority] instance (priority := 100) IrreducibleSpace.connectedSpace (α : Type u) [TopologicalSpace α] [IrreducibleSpace α] : ConnectedSpace α where toNonempty := IrreducibleSpace.toNonempty theorem Subtype.preconnectedSpace {s : Set α} (h : IsPreconnected s) : PreconnectedSpace s where isPreconnected_univ := by rwa [← IsInducing.subtypeVal.isPreconnected_image, image_univ, Subtype.range_val] theorem Subtype.connectedSpace {s : Set α} (h : IsConnected s) : ConnectedSpace s where toPreconnectedSpace := Subtype.preconnectedSpace h.isPreconnected toNonempty := h.nonempty.to_subtype theorem isPreconnected_iff_preconnectedSpace {s : Set α} : IsPreconnected s ↔ PreconnectedSpace s := ⟨Subtype.preconnectedSpace, fun h => by simpa using isPreconnected_univ.image ((↑) : s → α) continuous_subtype_val.continuousOn⟩ theorem isConnected_iff_connectedSpace {s : Set α} : IsConnected s ↔ ConnectedSpace s := ⟨Subtype.connectedSpace, fun h => ⟨nonempty_subtype.mp h.2, isPreconnected_iff_preconnectedSpace.mpr h.1⟩⟩ end Preconnected
Star.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Analysis.Calculus.FDeriv.Linear import Mathlib.Analysis.Calculus.FDeriv.Comp import Mathlib.Analysis.Calculus.FDeriv.Equiv import Mathlib.Analysis.CStarAlgebra.Basic import Mathlib.Topology.Algebra.Module.Star /-! # Star operations on derivatives This file contains the usual formulas (and existence assertions) for the Fréchet derivative of the star operation. For detailed documentation of the Fréchet derivative, see the module docstring of `Analysis/Calculus/FDeriv/Basic.lean`. Most of the results in this file only apply when the field that the derivative is respect to has a trivial star operation; which as should be expected rules out `𝕜 = ℂ`. The exceptions are `HasFDerivAt.star_star` and `DifferentiableAt.star_star`, showing that `star ∘ f ∘ star` is differentiable when `f` is (and giving a formula for its derivative). -/ variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] [StarRing 𝕜] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] variable {F : Type*} [NormedAddCommGroup F] [StarAddMonoid F] [NormedSpace 𝕜 F] [StarModule 𝕜 F] [ContinuousStar F] variable {f : E → F} {f' : E →L[𝕜] F} {x : E} {s : Set E} {L : Filter E} section TrivialStar variable [TrivialStar 𝕜] @[fun_prop] protected theorem HasStrictFDerivAt.star (h : HasStrictFDerivAt f f' x) : HasStrictFDerivAt (fun x => star (f x)) (((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L f') x := (starL' 𝕜 : F ≃L[𝕜] F).toContinuousLinearMap.hasStrictFDerivAt.comp x h protected theorem HasFDerivAtFilter.star (h : HasFDerivAtFilter f f' x L) : HasFDerivAtFilter (fun x => star (f x)) (((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L f') x L := (starL' 𝕜 : F ≃L[𝕜] F).toContinuousLinearMap.hasFDerivAtFilter.comp x h Filter.tendsto_map @[fun_prop] protected nonrec theorem HasFDerivWithinAt.star (h : HasFDerivWithinAt f f' s x) : HasFDerivWithinAt (fun x => star (f x)) (((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L f') s x := h.star @[fun_prop] protected nonrec theorem HasFDerivAt.star (h : HasFDerivAt f f' x) : HasFDerivAt (fun x => star (f x)) (((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L f') x := h.star @[fun_prop] protected theorem DifferentiableWithinAt.star (h : DifferentiableWithinAt 𝕜 f s x) : DifferentiableWithinAt 𝕜 (fun y => star (f y)) s x := h.hasFDerivWithinAt.star.differentiableWithinAt @[simp] theorem differentiableWithinAt_star_iff : DifferentiableWithinAt 𝕜 (fun y => star (f y)) s x ↔ DifferentiableWithinAt 𝕜 f s x := (starL' 𝕜 : F ≃L[𝕜] F).comp_differentiableWithinAt_iff @[fun_prop] protected theorem DifferentiableAt.star (h : DifferentiableAt 𝕜 f x) : DifferentiableAt 𝕜 (fun y => star (f y)) x := h.hasFDerivAt.star.differentiableAt @[simp] theorem differentiableAt_star_iff : DifferentiableAt 𝕜 (fun y => star (f y)) x ↔ DifferentiableAt 𝕜 f x := (starL' 𝕜 : F ≃L[𝕜] F).comp_differentiableAt_iff @[fun_prop] protected theorem DifferentiableOn.star (h : DifferentiableOn 𝕜 f s) : DifferentiableOn 𝕜 (fun y => star (f y)) s := fun x hx => (h x hx).star @[simp] theorem differentiableOn_star_iff : DifferentiableOn 𝕜 (fun y => star (f y)) s ↔ DifferentiableOn 𝕜 f s := (starL' 𝕜 : F ≃L[𝕜] F).comp_differentiableOn_iff @[fun_prop] protected theorem Differentiable.star (h : Differentiable 𝕜 f) : Differentiable 𝕜 fun y => star (f y) := fun x => (h x).star @[simp] theorem differentiable_star_iff : (Differentiable 𝕜 fun y => star (f y)) ↔ Differentiable 𝕜 f := (starL' 𝕜 : F ≃L[𝕜] F).comp_differentiable_iff theorem fderivWithin_star (hxs : UniqueDiffWithinAt 𝕜 s x) : fderivWithin 𝕜 (fun y => star (f y)) s x = ((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L fderivWithin 𝕜 f s x := (starL' 𝕜 : F ≃L[𝕜] F).comp_fderivWithin hxs @[simp] theorem fderiv_star : fderiv 𝕜 (fun y => star (f y)) x = ((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L fderiv 𝕜 f x := (starL' 𝕜 : F ≃L[𝕜] F).comp_fderiv end TrivialStar section NontrivialStar /-! ## Composing on the left and right with `star` -/ variable [StarAddMonoid E] [StarModule 𝕜 E] [ContinuousStar E] [NormedStarGroup 𝕜] /-- If `f` has derivative `f'` at `z`, then `star ∘ f ∘ star` has derivative `starL ∘ f' ∘ starL` at `star z`. -/ @[fun_prop] lemma HasFDerivAt.star_star {f : E → F} {z : E} {f' : E →L[𝕜] F} (hf : HasFDerivAt f f' z) : HasFDerivAt (star ∘ f ∘ star) ((starL 𝕜).toContinuousLinearMap.comp <| f'.comp (starL 𝕜).toContinuousLinearMap) (star z) := .comp_semilinear (starL 𝕜).toContinuousLinearMap (starL 𝕜).toContinuousLinearMap (by simpa using hf) /-- If `f` is differentiable at `z`, then `star ∘ f ∘ star` is differentiable at `star z`. -/ @[fun_prop] lemma DifferentiableAt.star_star {f : E → F} {z : E} (hf : DifferentiableAt 𝕜 f z) : DifferentiableAt 𝕜 (star ∘ f ∘ star) (star z) := hf.hasFDerivAt.star_star.differentiableAt end NontrivialStar
vector.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 fintype bigop finfun tuple. From mathcomp Require Import ssralg matrix mxalgebra zmodp. (******************************************************************************) (* Finite dimensional vector spaces *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* vectType R == interface structure for finite dimensional (more *) (* precisely, detachable) vector spaces over R, which *) (* should be at least a nzRingType *) (* The HB class is called Vector. *) (* Vector.axiom n M <-> type M is linearly isomorphic to 'rV_n *) (* := {v2r : M -> 'rV_n| linear v2r & bijective v2r} *) (* {vspace vT} == the type of (detachable) subspaces of vT; vT *) (* should have a vectType structure over a fieldType *) (* subvs_of U == the subtype of elements of V in the subspace U *) (* This is canonically a vectType. *) (* vsval u == linear injection of u : subvs_of U into V *) (* vsproj U v == linear projection of v : V in subvs U *) (* rVof e v == row vector in 'rV_(\dim vT) of coordinates of *) (* v : vT in the basis e *) (* vecof e v == vector in vT whose coordinates in the basis e are *) (* given by v : 'rV_(\dim vT) *) (* Note that this is the inverse of rVof. *) (* mxof e e' f == \dim uT * \dim vT matrix of the linear function *) (* f : 'Hom(uT, vT) in the bases e of uT and e' of vT,*) (* acting on row vectors *) (* hommx e f M == linear function in 'Hom(uT, vT) whose matrix *) (* in the bases e and f is M : 'M_(\dim uT, \dim vT) *) (* Note that this is the inverse of mxof. *) (* vsof e M == the subspace of vT generated by the rows of M, *) (* seen as coordinates in the basis e *) (* msof e U == matrix whose rows, seen as coordinates in the *) (* basis e, generate the subspace U of vT *) (* Note that this is the inverse of vsof. *) (* 'Hom(aT, rT) == the type of linear functions (homomorphisms) from *) (* aT to rT, where aT and rT are vectType structures *) (* Elements of 'Hom(aT, rT) coerce to Coq functions. *) (* linfun f == a vector linear function in 'Hom(aT, rT) that *) (* coincides with f : aT -> rT when f is linear *) (* 'End(vT) == endomorphisms of vT (:= 'Hom(vT, vT)) *) (* --> The types subvs_of U, 'Hom(aT, rT), 'End(vT), K^o, 'M[K]_(m, n), *) (* vT * wT, {ffun I -> vT}, vT ^ n all have canonical vectType instances. *) (* *) (* Functions: *) (* <[v]>%VS == the vector space generated by v (a line if v != 0) *) (* 0%VS == the trivial vector subspace *) (* fullv, {:vT} == the complete vector subspace (displays as fullv) *) (* (U + V)%VS == the join (sum) of two subspaces U and V *) (* (U :&: V)%VS == intersection of vector subspaces U and V *) (* (U^C)%VS == a complement of the vector subspace U *) (* (U :\: V)%VS == a local complement to U :& V in the subspace U *) (* \dim U == dimension of a vector space U *) (* span X, <<X>>%VS == the subspace spanned by the vector sequence X *) (* coord X i v == i'th coordinate of v on X, when v \in <<X>>%VS and *) (* where X : n.-tuple vT and i : 'I_n *) (* Note that coord X i is a scalar function. *) (* vpick U == a nonzero element of U if U= 0%VS, or 0 if U = 0 *) (* vbasis U == a (\dim U).-tuple that is a basis of U *) (* \1%VF == the identity linear function *) (* (f \o g)%VF == the composite of two linear functions f and g *) (* (f^-1)%VF == a linear function that is a right inverse to the *) (* linear function f on the codomain of f *) (* (f @: U)%VS == the image of U by the linear function f *) (* (f @^-1: U)%VS == the pre-image of U by the linear function f *) (* lker f == the kernel of the linear function f *) (* limg f == the image of the linear function f *) (* fixedSpace f == the fixed space of a linear endomorphism f *) (* daddv_pi U V == projection onto U along V if U and V are disjoint; *) (* daddv_pi U V + daddv_pi V U is then a projection *) (* onto the direct sum (U + V)%VS *) (* projv U == projection onto U (along U^C, := daddv_pi U U^C) *) (* addv_pi1 U V == projection onto the subspace U :\: V of U along V *) (* addv_pi2 U V == projection onto V along U :\: V; note that *) (* addv_pi1 U V and addv_pi2 U V are (asymmetrical) *) (* complementary projections on (U + V)%VS *) (* sumv_pi_for defV i == for defV : V = (V \sum_(j <- r | P j) Vs j)%VS, *) (* j ranging over an eqType, this is a projection on *) (* a subspace of Vs i, along a complement in V, such *) (* that \sum_(j <- r | P j) sumv_pi_for defV j is a *) (* projection onto V if filter P r is duplicate-free *) (* (e.g., when V := \sum_(j | P j) Vs j) *) (* sumv_pi V i == notation the above when defV == erefl V, and V is *) (* convertible to \sum_(j <- r | P j) Vs j)%VS *) (* leigenspace f a == linear eigenspace of the linear function f for *) (* the (potential) eigenvalue a *) (* *) (* Predicates: *) (* v \in U == v belongs to U (:= (<[v]> <= U)%VS) *) (* (U <= V)%VS == U is a subspace of V *) (* free B == B is a sequence of nonzero linearly independent *) (* vectors *) (* basis_of U b == b is a basis of the subspace U *) (* directv S == S is the expression for a direct sum of subspaces *) (* leigenvalue f a == a is a linear eigenvalue of the linear function f *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope vspace_scope. Declare Scope lfun_scope. Local Open Scope ring_scope. Reserved Notation "{ 'vspace' T }" (format "{ 'vspace' T }"). Reserved Notation "''Hom' ( T , rT )" (format "''Hom' ( T , rT )"). Reserved Notation "''End' ( T )" (format "''End' ( T )"). Reserved Notation "\dim A" (at level 10, A at level 8, format "\dim A"). Delimit Scope vspace_scope with VS. Import GRing.Theory. (* Finite dimension vector space *) Definition vector_axiom_def (R : nzRingType) n (V : lmodType R) := {v2r : V -> 'rV[R]_n | linear v2r & bijective v2r}. Arguments vector_axiom_def [R] n%_N V%_type. HB.mixin Record Lmodule_hasFinDim (R : nzRingType) (V : Type) of GRing.Lmodule R V := { dim : nat; vector_subdef : vector_axiom_def dim V }. #[mathcomp(axiom="vector_axiom_def"), short(type="vectType")] HB.structure Definition Vector (R : nzRingType) := { V of Lmodule_hasFinDim R V & GRing.Lmodule R V }. #[deprecated(since="mathcomp 2.2.0", note="Use Vector.axiom instead.")] Notation vector_axiom := Vector.axiom. Arguments dim {R} s. (* FIXME: S/space and H/hom were defined behind the module Vector * * Perhaps we should change their names to avoid conflicts. *) Section OtherDefs. Local Coercion dim : Vector.type >-> nat. Inductive space (K : fieldType) (vT : Vector.type K) := Space (mx : 'M[K]_vT) & <<mx>>%MS == mx. Inductive hom (R : nzRingType) (vT wT : Vector.type R) := Hom of 'M[R]_(vT, wT). End OtherDefs. (* /FIXME *) Module Import VectorExports. Bind Scope ring_scope with Vector.sort. Arguments space [K] vT%_type. Notation "{ 'vspace' vT }" := (space vT) : type_scope. Notation "''Hom' ( aT , rT )" := (hom aT rT) : type_scope. Notation "''End' ( vT )" := (hom vT vT) : type_scope. Prenex Implicits Hom. Delimit Scope vspace_scope with VS. Bind Scope vspace_scope with space. Delimit Scope lfun_scope with VF. Bind Scope lfun_scope with hom. End VectorExports. (* The contents of this module exposes the matrix encodings, and should *) (* therefore not be used outside of the vector library implementation. *) Module VectorInternalTheory. Section Iso. Variables (R : nzRingType) (vT rT : vectType R). Local Coercion dim : Vector.type >-> nat. Fact v2r_subproof : Vector.axiom vT vT. Proof. exact: vector_subdef. Qed. Definition v2r := s2val v2r_subproof. Let v2r_bij : bijective v2r := s2valP' v2r_subproof. Fact r2v_subproof : {r2v | cancel r2v v2r}. Proof. have r2vP r: {v | v2r v = r}. by apply: sig_eqW; have [v _ vK] := v2r_bij; exists (v r). by exists (fun r => sval (r2vP r)) => r; case: (r2vP r). Qed. Definition r2v := sval r2v_subproof. Lemma r2vK : cancel r2v v2r. Proof. exact: svalP r2v_subproof. Qed. Lemma r2v_inj : injective r2v. Proof. exact: can_inj r2vK. Qed. Lemma v2rK : cancel v2r r2v. Proof. by have/bij_can_sym:= r2vK; apply. Qed. Lemma v2r_inj : injective v2r. Proof. exact: can_inj v2rK. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R vT 'rV_vT _ v2r (GRing.semilinear_linear (s2valP v2r_subproof)). HB.instance Definition _ := GRing.isSemilinear.Build R 'rV_vT vT _ r2v (GRing.semilinear_linear (can2_linear v2rK r2vK)). End Iso. Section Vspace. Variables (K : fieldType) (vT : vectType K). Local Coercion dim : Vector.type >-> nat. Definition b2mx n (X : n.-tuple vT) := \matrix_i v2r (tnth X i). Lemma b2mxK n (X : n.-tuple vT) i : r2v (row i (b2mx X)) = X`_i. Proof. by rewrite rowK v2rK -tnth_nth. Qed. Definition vs2mx (U : @space K vT) := let: Space mx _ := U in mx. Lemma gen_vs2mx (U : {vspace vT}) : <<vs2mx U>>%MS = vs2mx U. Proof. by apply/eqP; rewrite /vs2mx; case: U. Qed. Fact mx2vs_subproof m (A : 'M[K]_(m, vT)) : <<(<<A>>)>>%MS == <<A>>%MS. Proof. by rewrite genmx_id. Qed. Definition mx2vs {m} A : {vspace vT} := Space (@mx2vs_subproof m A). HB.instance Definition _ := [isSub of {vspace vT} for vs2mx]. Lemma vs2mxK : cancel vs2mx mx2vs. Proof. by move=> v; apply: val_inj; rewrite /= gen_vs2mx. Qed. Lemma mx2vsK m (M : 'M_(m, vT)) : (vs2mx (mx2vs M) :=: M)%MS. Proof. exact: genmxE. Qed. End Vspace. Section Hom. Variables (R : nzRingType) (aT rT : vectType R). Definition f2mx (f : 'Hom(aT, rT)) := let: Hom A := f in A. HB.instance Definition _ : isSub _ _ 'Hom(aT, rT) := [isNew for f2mx]. End Hom. Arguments mx2vs {K vT m%_N} A%_MS. Prenex Implicits v2r r2v v2rK r2vK b2mx vs2mx vs2mxK f2mx. End VectorInternalTheory. Export VectorExports. Import VectorInternalTheory. Section VspaceDefs. Variables (K : fieldType) (vT : vectType K). Implicit Types (u : vT) (X : seq vT) (U V : {vspace vT}). HB.instance Definition _ := [Choice of {vspace vT} by <:]. Definition dimv U := \rank (vs2mx U). Definition subsetv U V := (vs2mx U <= vs2mx V)%MS. Definition vline u := mx2vs (v2r u). (* Vspace membership is defined as line inclusion. *) Definition pred_of_vspace (U : space vT) : {pred vT} := fun v => (vs2mx (vline v) <= vs2mx U)%MS. Canonical vspace_predType := @PredType _ (unkeyed {vspace vT}) pred_of_vspace. Definition fullv : {vspace vT} := mx2vs 1%:M. Definition addv U V := mx2vs (vs2mx U + vs2mx V). Definition capv U V := mx2vs (vs2mx U :&: vs2mx V). Definition complv U := mx2vs (vs2mx U)^C. Definition diffv U V := mx2vs (vs2mx U :\: vs2mx V). Definition vpick U := r2v (nz_row (vs2mx U)). Fact span_key : unit. Proof. by []. Qed. Definition span_expanded_def X := mx2vs (b2mx (in_tuple X)). Definition span := locked_with span_key span_expanded_def. Canonical span_unlockable := [unlockable fun span]. Definition vbasis_def U := [tuple r2v (row i (row_base (vs2mx U))) | i < dimv U]. Definition vbasis := locked_with span_key vbasis_def. Canonical vbasis_unlockable := [unlockable fun vbasis]. (* coord and directv are defined in the VectorTheory section. *) Definition free X := dimv (span X) == size X. Definition basis_of U X := (span X == U) && free X. End VspaceDefs. Coercion pred_of_vspace : space >-> pred_sort. Notation "\dim U" := (dimv U) : nat_scope. Notation "U <= V" := (subsetv U V) : vspace_scope. Notation "U <= V <= W" := (subsetv U V && subsetv V W) : vspace_scope. Notation "<[ v ] >" := (vline v) : vspace_scope. Notation "<< X >>" := (span X) : vspace_scope. Notation "0" := (vline 0) : vspace_scope. Arguments fullv {K vT}. Prenex Implicits subsetv addv capv complv diffv span free basis_of. Notation "U + V" := (addv U V) : vspace_scope. Notation "U :&: V" := (capv U V) : vspace_scope. Notation "U ^C" := (complv U) : vspace_scope. Notation "U :\: V" := (diffv U V) : vspace_scope. Notation "{ : vT }" := (@fullv _ vT) (only parsing) : vspace_scope. Notation "\sum_ ( i <- r | P ) U" := (\big[addv/0%VS]_(i <- r | P%B) U%VS) : vspace_scope. Notation "\sum_ ( i <- r ) U" := (\big[addv/0%VS]_(i <- r) U%VS) : vspace_scope. Notation "\sum_ ( m <= i < n | P ) U" := (\big[addv/0%VS]_(m <= i < n | P%B) U%VS) : vspace_scope. Notation "\sum_ ( m <= i < n ) U" := (\big[addv/0%VS]_(m <= i < n) U%VS) : vspace_scope. Notation "\sum_ ( i | P ) U" := (\big[addv/0%VS]_(i | P%B) U%VS) : vspace_scope. Notation "\sum_ i U" := (\big[addv/0%VS]_i U%VS) : vspace_scope. Notation "\sum_ ( i : t | P ) U" := (\big[addv/0%VS]_(i : t | P%B) U%VS) (only parsing) : vspace_scope. Notation "\sum_ ( i : t ) U" := (\big[addv/0%VS]_(i : t) U%VS) (only parsing) : vspace_scope. Notation "\sum_ ( i < n | P ) U" := (\big[addv/0%VS]_(i < n | P%B) U%VS) : vspace_scope. Notation "\sum_ ( i < n ) U" := (\big[addv/0%VS]_(i < n) U%VS) : vspace_scope. Notation "\sum_ ( i 'in' A | P ) U" := (\big[addv/0%VS]_(i in A | P%B) U%VS) : vspace_scope. Notation "\sum_ ( i 'in' A ) U" := (\big[addv/0%VS]_(i in A) U%VS) : vspace_scope. Notation "\bigcap_ ( i <- r | P ) U" := (\big[capv/fullv]_(i <- r | P%B) U%VS) : vspace_scope. Notation "\bigcap_ ( i <- r ) U" := (\big[capv/fullv]_(i <- r) U%VS) : vspace_scope. Notation "\bigcap_ ( m <= i < n | P ) U" := (\big[capv/fullv]_(m <= i < n | P%B) U%VS) : vspace_scope. Notation "\bigcap_ ( m <= i < n ) U" := (\big[capv/fullv]_(m <= i < n) U%VS) : vspace_scope. Notation "\bigcap_ ( i | P ) U" := (\big[capv/fullv]_(i | P%B) U%VS) : vspace_scope. Notation "\bigcap_ i U" := (\big[capv/fullv]_i U%VS) : vspace_scope. Notation "\bigcap_ ( i : t | P ) U" := (\big[capv/fullv]_(i : t | P%B) U%VS) (only parsing) : vspace_scope. Notation "\bigcap_ ( i : t ) U" := (\big[capv/fullv]_(i : t) U%VS) (only parsing) : vspace_scope. Notation "\bigcap_ ( i < n | P ) U" := (\big[capv/fullv]_(i < n | P%B) U%VS) : vspace_scope. Notation "\bigcap_ ( i < n ) U" := (\big[capv/fullv]_(i < n) U%VS) : vspace_scope. Notation "\bigcap_ ( i 'in' A | P ) U" := (\big[capv/fullv]_(i in A | P%B) U%VS) : vspace_scope. Notation "\bigcap_ ( i 'in' A ) U" := (\big[capv/fullv]_(i in A) U%VS) : vspace_scope. Section VectorTheory. Variables (K : fieldType) (vT : vectType K). Implicit Types (a : K) (u v w : vT) (X Y : seq vT) (U V W : {vspace vT}). Local Notation subV := (@subsetv K vT) (only parsing). Local Notation addV := (@addv K vT) (only parsing). Local Notation capV := (@capv K vT) (only parsing). (* begin hide *) (* Internal theory facts *) Let vs2mxP U V : reflect (U = V) (vs2mx U == vs2mx V)%MS. Proof. by rewrite (sameP genmxP eqP) !gen_vs2mx; apply: eqP. Qed. Let memvK v U : (v \in U) = (v2r v <= vs2mx U)%MS. Proof. by rewrite -genmxE. Qed. Let mem_r2v rv U : (r2v rv \in U) = (rv <= vs2mx U)%MS. Proof. by rewrite memvK r2vK. Qed. Let vs2mx0 : @vs2mx K vT 0 = 0. Proof. by rewrite /= linear0 genmx0. Qed. Let vs2mxD U V : vs2mx (U + V) = (vs2mx U + vs2mx V)%MS. Proof. by rewrite /= genmx_adds !gen_vs2mx. Qed. Let vs2mx_sum := big_morph _ vs2mxD vs2mx0. Let vs2mxI U V : vs2mx (U :&: V) = (vs2mx U :&: vs2mx V)%MS. Proof. by rewrite /= genmx_cap !gen_vs2mx. Qed. Let vs2mxF : vs2mx {:vT} = 1%:M. Proof. by rewrite /= genmx1. Qed. Let row_b2mx n (X : n.-tuple vT) i : row i (b2mx X) = v2r X`_i. Proof. by rewrite -tnth_nth rowK. Qed. Let span_b2mx n (X : n.-tuple vT) : span X = mx2vs (b2mx X). Proof. by rewrite unlock tvalK; case: _ / (esym _). Qed. Let mul_b2mx n (X : n.-tuple vT) (rk : 'rV_n) : \sum_i rk 0 i *: X`_i = r2v (rk *m b2mx X). Proof. rewrite mulmx_sum_row linear_sum; apply: eq_bigr => i _. by rewrite row_b2mx linearZ /= v2rK. Qed. Let lin_b2mx n (X : n.-tuple vT) k : \sum_(i < n) k i *: X`_i = r2v (\row_i k i *m b2mx X). Proof. by rewrite -mul_b2mx; apply: eq_bigr => i _; rewrite mxE. Qed. Let free_b2mx n (X : n.-tuple vT) : free X = row_free (b2mx X). Proof. by rewrite /free /dimv span_b2mx genmxE size_tuple. Qed. (* end hide *) Lemma memvE v U : (v \in U) = (<[v]> <= U)%VS. Proof. by []. Qed. Lemma vlineP v1 v2 : reflect (exists k, v1 = k *: v2) (v1 \in <[v2]>)%VS. Proof. apply: (iffP idP) => [|[k ->]]; rewrite memvK genmxE ?linearZ ?scalemx_sub //. by case/sub_rVP=> k; rewrite -linearZ => /v2r_inj->; exists k. Qed. Fact memv_submod_closed U : submod_closed U. Proof. split=> [|a u v]; rewrite !memvK 1?linear0 1?sub0mx // => Uu Uv. by rewrite linearP addmx_sub ?scalemx_sub. Qed. HB.instance Definition _ (U : {vspace vT}) := GRing.isSubmodClosed.Build K vT (pred_of_vspace U) (memv_submod_closed U). Lemma mem0v U : 0 \in U. Proof. exact: rpred0. Qed. Lemma memvN U v : (- v \in U) = (v \in U). Proof. exact: rpredN. Qed. Lemma memvD U : {in U &, forall u v, u + v \in U}. Proof. exact: rpredD. Qed. Lemma memvB U : {in U &, forall u v, u - v \in U}. Proof. exact: rpredB. Qed. Lemma memvZ U k : {in U, forall v, k *: v \in U}. Proof. exact: rpredZ. Qed. Lemma memv_suml I r (P : pred I) vs U : (forall i, P i -> vs i \in U) -> \sum_(i <- r | P i) vs i \in U. Proof. exact: rpred_sum. Qed. Lemma memv_line u : u \in <[u]>%VS. Proof. by apply/vlineP; exists 1; rewrite scale1r. Qed. Lemma subvP U V : reflect {subset U <= V} (U <= V)%VS. Proof. apply: (iffP rV_subP) => sU12 u. by rewrite !memvE /subsetv !genmxE => /sU12. by have:= sU12 (r2v u); rewrite !memvE /subsetv !genmxE r2vK. Qed. Lemma subvv U : (U <= U)%VS. Proof. exact/subvP. Qed. Hint Resolve subvv : core. Lemma subv_trans : transitive subV. Proof. by move=> U V W /subvP sUV /subvP sVW; apply/subvP=> u /sUV/sVW. Qed. Lemma subv_anti : antisymmetric subV. Proof. by move=> U V; apply/vs2mxP. Qed. Lemma eqEsubv U V : (U == V) = (U <= V <= U)%VS. Proof. by apply/eqP/idP=> [-> | /subv_anti//]; rewrite subvv. Qed. Lemma vspaceP U V : U =i V <-> U = V. Proof. split=> [eqUV | -> //]; apply/subv_anti/andP. by split; apply/subvP=> v; rewrite eqUV. Qed. Lemma subvPn {U V} : reflect (exists2 u, u \in U & u \notin V) (~~ (U <= V)%VS). Proof. apply: (iffP idP) => [|[u Uu]]; last by apply: contra => /subvP->. case/row_subPn=> i; set vi := row i _ => V'vi. by exists (r2v vi); rewrite memvK r2vK ?row_sub. Qed. (* Empty space. *) Lemma sub0v U : (0 <= U)%VS. Proof. exact: mem0v. Qed. Lemma subv0 U : (U <= 0)%VS = (U == 0%VS). Proof. by rewrite eqEsubv sub0v andbT. Qed. Lemma memv0 v : v \in 0%VS = (v == 0). Proof. by apply/idP/eqP=> [/vlineP[k ->] | ->]; rewrite (scaler0, mem0v). Qed. (* Full space *) Lemma subvf U : (U <= fullv)%VS. Proof. by rewrite /subsetv vs2mxF submx1. Qed. Lemma memvf v : v \in fullv. Proof. exact: subvf. Qed. (* Picking a non-zero vector in a subspace. *) Lemma memv_pick U : vpick U \in U. Proof. by rewrite mem_r2v nz_row_sub. Qed. Lemma vpick0 U : (vpick U == 0) = (U == 0%VS). Proof. by rewrite -memv0 mem_r2v -subv0 /subV vs2mx0 !submx0 nz_row_eq0. Qed. (* Sum of subspaces. *) Lemma subv_add U V W : (U + V <= W)%VS = (U <= W)%VS && (V <= W)%VS. Proof. by rewrite /subV vs2mxD addsmx_sub. Qed. Lemma addvS U1 U2 V1 V2 : (U1 <= U2 -> V1 <= V2 -> U1 + V1 <= U2 + V2)%VS. Proof. by rewrite /subV !vs2mxD; apply: addsmxS. Qed. Lemma addvSl U V : (U <= U + V)%VS. Proof. by rewrite /subV vs2mxD addsmxSl. Qed. Lemma addvSr U V : (V <= U + V)%VS. Proof. by rewrite /subV vs2mxD addsmxSr. Qed. Lemma addvC : commutative addV. Proof. by move=> U V; apply/vs2mxP; rewrite !vs2mxD addsmxC submx_refl. Qed. Lemma addvA : associative addV. Proof. by move=> U V W; apply/vs2mxP; rewrite !vs2mxD addsmxA submx_refl. Qed. Lemma addv_idPl {U V}: reflect (U + V = U)%VS (V <= U)%VS. Proof. by rewrite /subV (sameP addsmx_idPl eqmxP) -vs2mxD; apply: vs2mxP. Qed. Lemma addv_idPr {U V} : reflect (U + V = V)%VS (U <= V)%VS. Proof. by rewrite addvC; apply: addv_idPl. Qed. Lemma addvv : idempotent_op addV. Proof. by move=> U; apply/addv_idPl. Qed. Lemma add0v : left_id 0%VS addV. Proof. by move=> U; apply/addv_idPr/sub0v. Qed. Lemma addv0 : right_id 0%VS addV. Proof. by move=> U; apply/addv_idPl/sub0v. Qed. Lemma sumfv : left_zero fullv addV. Proof. by move=> U; apply/addv_idPl/subvf. Qed. Lemma addvf : right_zero fullv addV. Proof. by move=> U; apply/addv_idPr/subvf. Qed. HB.instance Definition _ := Monoid.isComLaw.Build {vspace vT} 0%VS addv addvA addvC add0v. Lemma memv_add u v U V : u \in U -> v \in V -> u + v \in (U + V)%VS. Proof. by rewrite !memvK genmxE linearD; apply: addmx_sub_adds. Qed. Lemma memv_addP {w U V} : reflect (exists2 u, u \in U & exists2 v, v \in V & w = u + v) (w \in U + V)%VS. Proof. apply: (iffP idP) => [|[u Uu [v Vv ->]]]; last exact: memv_add. rewrite memvK genmxE => /sub_addsmxP[r /(canRL v2rK)->]. rewrite linearD /=; set u := r2v _; set v := r2v _. by exists u; last exists v; rewrite // mem_r2v submxMl. Qed. Section BigSum. Variable I : finType. Implicit Type P : pred I. Lemma sumv_sup i0 P U Vs : P i0 -> (U <= Vs i0)%VS -> (U <= \sum_(i | P i) Vs i)%VS. Proof. by move=> Pi0 /subv_trans-> //; rewrite (bigD1 i0) ?addvSl. Qed. Arguments sumv_sup i0 [P U Vs]. Lemma subv_sumP {P Us V} : reflect (forall i, P i -> Us i <= V)%VS (\sum_(i | P i) Us i <= V)%VS. Proof. apply: (iffP idP) => [sUV i Pi | sUV]. by apply: subv_trans sUV; apply: sumv_sup Pi _. by elim/big_rec: _ => [|i W Pi sWV]; rewrite ?sub0v // subv_add sUV. Qed. Lemma memv_sumr P vs (Us : I -> {vspace vT}) : (forall i, P i -> vs i \in Us i) -> \sum_(i | P i) vs i \in (\sum_(i | P i) Us i)%VS. Proof. by move=> Uv; apply/rpred_sum=> i Pi; apply/(sumv_sup i Pi)/Uv. Qed. Lemma memv_sumP {P} {Us : I -> {vspace vT}} {v} : reflect (exists2 vs, forall i, P i -> vs i \in Us i & v = \sum_(i | P i) vs i) (v \in \sum_(i | P i) Us i)%VS. Proof. apply: (iffP idP) => [|[vs Uv ->]]; last exact: memv_sumr. rewrite memvK vs2mx_sum => /sub_sumsmxP[r /(canRL v2rK)->]. pose f i := r2v (r i *m vs2mx (Us i)); rewrite linear_sum /=. by exists f => //= i _; rewrite mem_r2v submxMl. Qed. End BigSum. (* Intersection *) Lemma subv_cap U V W : (U <= V :&: W)%VS = (U <= V)%VS && (U <= W)%VS. Proof. by rewrite /subV vs2mxI sub_capmx. Qed. Lemma capvS U1 U2 V1 V2 : (U1 <= U2 -> V1 <= V2 -> U1 :&: V1 <= U2 :&: V2)%VS. Proof. by rewrite /subV !vs2mxI; apply: capmxS. Qed. Lemma capvSl U V : (U :&: V <= U)%VS. Proof. by rewrite /subV vs2mxI capmxSl. Qed. Lemma capvSr U V : (U :&: V <= V)%VS. Proof. by rewrite /subV vs2mxI capmxSr. Qed. Lemma capvC : commutative capV. Proof. by move=> U V; apply/vs2mxP; rewrite !vs2mxI capmxC submx_refl. Qed. Lemma capvA : associative capV. Proof. by move=> U V W; apply/vs2mxP; rewrite !vs2mxI capmxA submx_refl. Qed. Lemma capv_idPl {U V} : reflect (U :&: V = U)%VS (U <= V)%VS. Proof. by rewrite /subV(sameP capmx_idPl eqmxP) -vs2mxI; apply: vs2mxP. Qed. Lemma capv_idPr {U V} : reflect (U :&: V = V)%VS (V <= U)%VS. Proof. by rewrite capvC; apply: capv_idPl. Qed. Lemma capvv : idempotent_op capV. Proof. by move=> U; apply/capv_idPl. Qed. Lemma cap0v : left_zero 0%VS capV. Proof. by move=> U; apply/capv_idPl/sub0v. Qed. Lemma capv0 : right_zero 0%VS capV. Proof. by move=> U; apply/capv_idPr/sub0v. Qed. Lemma capfv : left_id fullv capV. Proof. by move=> U; apply/capv_idPr/subvf. Qed. Lemma capvf : right_id fullv capV. Proof. by move=> U; apply/capv_idPl/subvf. Qed. HB.instance Definition _ := Monoid.isComLaw.Build {vspace vT} fullv capv capvA capvC capfv. Lemma memv_cap w U V : (w \in U :&: V)%VS = (w \in U) && (w \in V). Proof. by rewrite !memvE subv_cap. Qed. Lemma memv_capP {w U V} : reflect (w \in U /\ w \in V) (w \in U :&: V)%VS. Proof. by rewrite memv_cap; apply: andP. Qed. Lemma vspace_modl U V W : (U <= W -> U + (V :&: W) = (U + V) :&: W)%VS. Proof. by move=> sUV; apply/vs2mxP; rewrite !(vs2mxD, vs2mxI); apply/eqmxP/matrix_modl. Qed. Lemma vspace_modr U V W : (W <= U -> (U :&: V) + W = U :&: (V + W))%VS. Proof. by rewrite -!(addvC W) !(capvC U); apply: vspace_modl. Qed. Section BigCap. Variable I : finType. Implicit Type P : pred I. Lemma bigcapv_inf i0 P Us V : P i0 -> (Us i0 <= V -> \bigcap_(i | P i) Us i <= V)%VS. Proof. by move=> Pi0; apply: subv_trans; rewrite (bigD1 i0) ?capvSl. Qed. Lemma subv_bigcapP {P U Vs} : reflect (forall i, P i -> U <= Vs i)%VS (U <= \bigcap_(i | P i) Vs i)%VS. Proof. apply: (iffP idP) => [sUV i Pi | sUV]. by rewrite (subv_trans sUV) ?(bigcapv_inf Pi). by elim/big_rec: _ => [|i W Pi]; rewrite ?subvf // subv_cap sUV. Qed. End BigCap. (* Complement *) Lemma addv_complf U : (U + U^C)%VS = fullv. Proof. apply/vs2mxP; rewrite vs2mxD -gen_vs2mx -genmx_adds !genmxE submx1 sub1mx. exact: addsmx_compl_full. Qed. Lemma capv_compl U : (U :&: U^C = 0)%VS. Proof. apply/val_inj; rewrite [val]/= vs2mx0 vs2mxI -gen_vs2mx -genmx_cap. by rewrite capmx_compl genmx0. Qed. (* Difference *) Lemma diffvSl U V : (U :\: V <= U)%VS. Proof. by rewrite /subV genmxE diffmxSl. Qed. Lemma capv_diff U V : ((U :\: V) :&: V = 0)%VS. Proof. apply/val_inj; rewrite [val]/= vs2mx0 vs2mxI -(gen_vs2mx V) -genmx_cap. by rewrite capmx_diff genmx0. Qed. Lemma addv_diff_cap U V : (U :\: V + U :&: V)%VS = U. Proof. apply/vs2mxP; rewrite vs2mxD -genmx_adds !genmxE. exact/eqmxP/addsmx_diff_cap_eq. Qed. Lemma addv_diff U V : (U :\: V + V = U + V)%VS. Proof. by rewrite -{2}(addv_diff_cap U V) -addvA (addv_idPr (capvSr U V)). Qed. (* Subspace dimension. *) Lemma dimv0 : \dim (0%VS : {vspace vT}) = 0. Proof. by rewrite /dimv vs2mx0 mxrank0. Qed. Lemma dimv_eq0 U : (\dim U == 0) = (U == 0%VS). Proof. by rewrite /dimv /= mxrank_eq0 [in RHS]/eq_op /= linear0 genmx0. Qed. Lemma dimvf : \dim {:vT} = dim vT. Proof. by rewrite /dimv vs2mxF mxrank1. Qed. Lemma dim_vline v : \dim <[v]> = (v != 0). Proof. by rewrite /dimv mxrank_gen rank_rV (can2_eq v2rK r2vK) linear0. Qed. Lemma dimvS U V : (U <= V)%VS -> \dim U <= \dim V. Proof. exact: mxrankS. Qed. Lemma dimv_leqif_sup U V : (U <= V)%VS -> \dim U <= \dim V ?= iff (V <= U)%VS. Proof. exact: mxrank_leqif_sup. Qed. Lemma dimv_leqif_eq U V : (U <= V)%VS -> \dim U <= \dim V ?= iff (U == V). Proof. by rewrite eqEsubv; apply: mxrank_leqif_eq. Qed. Lemma eqEdim U V : (U == V) = (U <= V)%VS && (\dim V <= \dim U). Proof. by apply/idP/andP=> [/eqP | [/dimv_leqif_eq/geq_leqif]] ->. Qed. Lemma dimv_compl U : \dim U^C = (\dim {:vT} - \dim U)%N. Proof. by rewrite dimvf /dimv mxrank_gen mxrank_compl. Qed. Lemma dimv_cap_compl U V : (\dim (U :&: V) + \dim (U :\: V))%N = \dim U. Proof. by rewrite /dimv !mxrank_gen mxrank_cap_compl. Qed. Lemma dimv_sum_cap U V : (\dim (U + V) + \dim (U :&: V) = \dim U + \dim V)%N. Proof. by rewrite /dimv !mxrank_gen mxrank_sum_cap. Qed. Lemma dimv_disjoint_sum U V : (U :&: V = 0)%VS -> \dim (U + V) = (\dim U + \dim V)%N. Proof. by move=> dxUV; rewrite -dimv_sum_cap dxUV dimv0 addn0. Qed. Lemma dimv_add_leqif U V : \dim (U + V) <= \dim U + \dim V ?= iff (U :&: V <= 0)%VS. Proof. by rewrite /dimv /subV !mxrank_gen vs2mx0 genmxE; apply: mxrank_adds_leqif. Qed. Lemma diffv_eq0 U V : (U :\: V == 0)%VS = (U <= V)%VS. Proof. rewrite -dimv_eq0 -(eqn_add2l (\dim (U :&: V))) addn0 dimv_cap_compl eq_sym. by rewrite (dimv_leqif_eq (capvSl _ _)) (sameP capv_idPl eqP). Qed. Lemma dimv_leq_sum I r (P : pred I) (Us : I -> {vspace vT}) : \dim (\sum_(i <- r | P i) Us i) <= \sum_(i <- r | P i) \dim (Us i). Proof. elim/big_rec2: _ => [|i d vs _ le_vs_d]; first by rewrite dim_vline eqxx. by apply: (leq_trans (dimv_add_leqif _ _)); rewrite leq_add2l. Qed. Section SumExpr. (* The vector direct sum theory clones the interface types of the matrix *) (* direct sum theory (see mxalgebra for the technical details), but *) (* nevetheless reuses much of the matrix theory. *) Structure addv_expr := Sumv { addv_val :> wrapped {vspace vT}; addv_dim : wrapped nat; _ : mxsum_spec (vs2mx (unwrap addv_val)) (unwrap addv_dim) }. (* Piggyback on mxalgebra theory. *) Definition vs2mx_sum_expr_subproof (S : addv_expr) : mxsum_spec (vs2mx (unwrap S)) (unwrap (addv_dim S)). Proof. by case: S. Qed. Canonical vs2mx_sum_expr S := ProperMxsumExpr (vs2mx_sum_expr_subproof S). Canonical trivial_addv U := @Sumv (Wrap U) (Wrap (\dim U)) (TrivialMxsum _). Structure proper_addv_expr := ProperSumvExpr { proper_addv_val :> {vspace vT}; proper_addv_dim :> nat; _ : mxsum_spec (vs2mx proper_addv_val) proper_addv_dim }. Definition proper_addvP (S : proper_addv_expr) := let: ProperSumvExpr _ _ termS := S return mxsum_spec (vs2mx S) S in termS. Canonical proper_addv (S : proper_addv_expr) := @Sumv (wrap (S : {vspace vT})) (wrap (S : nat)) (proper_addvP S). Section Binary. Variables S1 S2 : addv_expr. Fact binary_addv_subproof : mxsum_spec (vs2mx (unwrap S1 + unwrap S2)) (unwrap (addv_dim S1) + unwrap (addv_dim S2)). Proof. by rewrite vs2mxD; apply: proper_mxsumP. Qed. Canonical binary_addv_expr := ProperSumvExpr binary_addv_subproof. End Binary. Section Nary. Variables (I : Type) (r : seq I) (P : pred I) (S_ : I -> addv_expr). Fact nary_addv_subproof : mxsum_spec (vs2mx (\sum_(i <- r | P i) unwrap (S_ i))) (\sum_(i <- r | P i) unwrap (addv_dim (S_ i))). Proof. by rewrite vs2mx_sum; apply: proper_mxsumP. Qed. Canonical nary_addv_expr := ProperSumvExpr nary_addv_subproof. End Nary. Definition directv_def S of phantom {vspace vT} (unwrap (addv_val S)) := \dim (unwrap S) == unwrap (addv_dim S). End SumExpr. Local Notation directv A := (directv_def (Phantom {vspace _} A%VS)). Lemma directvE (S : addv_expr) : directv (unwrap S) = (\dim (unwrap S) == unwrap (addv_dim S)). Proof. by []. Qed. Lemma directvP {S : proper_addv_expr} : reflect (\dim S = S :> nat) (directv S). Proof. exact: eqnP. Qed. Lemma directv_trivial U : directv (unwrap (@trivial_addv U)). Proof. exact: eqxx. Qed. Lemma dimv_sum_leqif (S : addv_expr) : \dim (unwrap S) <= unwrap (addv_dim S) ?= iff directv (unwrap S). Proof. rewrite directvE; case: S => [[U] [d] /= defUd]; split=> //=. rewrite /dimv; elim: {1}_ {U}_ d / defUd => // m1 m2 A1 A2 r1 r2 _ leA1 _ leA2. by apply: leq_trans (leq_add leA1 leA2); rewrite mxrank_adds_leqif. Qed. Lemma directvEgeq (S : addv_expr) : directv (unwrap S) = (\dim (unwrap S) >= unwrap (addv_dim S)). Proof. by rewrite leq_eqVlt ltnNge eq_sym !dimv_sum_leqif orbF. Qed. Section BinaryDirect. Lemma directv_addE (S1 S2 : addv_expr) : directv (unwrap S1 + unwrap S2) = [&& directv (unwrap S1), directv (unwrap S2) & unwrap S1 :&: unwrap S2 == 0]%VS. Proof. by rewrite /directv_def /dimv vs2mxD -mxdirectE mxdirect_addsE -vs2mxI -vs2mx0. Qed. Lemma directv_addP {U V} : reflect (U :&: V = 0)%VS (directv (U + V)). Proof. by rewrite directv_addE !directv_trivial; apply: eqP. Qed. Lemma directv_add_unique {U V} : reflect (forall u1 u2 v1 v2, u1 \in U -> u2 \in U -> v1 \in V -> v2 \in V -> (u1 + v1 == u2 + v2) = ((u1, v1) == (u2, v2))) (directv (U + V)). Proof. apply: (iffP directv_addP) => [dxUV u1 u2 v1 v2 Uu1 Uu2 Vv1 Vv2 | dxUV]. apply/idP/idP=> [| /eqP[-> ->] //]; rewrite -subr_eq0 opprD addrACA addr_eq0. move/eqP=> eq_uv; rewrite xpair_eqE -subr_eq0 eq_uv oppr_eq0 subr_eq0 andbb. by rewrite -subr_eq0 -memv0 -dxUV memv_cap -memvN -eq_uv !memvB. apply/eqP; rewrite -subv0; apply/subvP=> v /memv_capP[U1v U2v]. by rewrite memv0 -[v == 0]andbb {1}eq_sym -xpair_eqE -dxUV ?mem0v // addrC. Qed. End BinaryDirect. Section NaryDirect. Context {I : finType} {P : pred I}. Lemma directv_sumP {Us : I -> {vspace vT}} : reflect (forall i, P i -> Us i :&: (\sum_(j | P j && (j != i)) Us j) = 0)%VS (directv (\sum_(i | P i) Us i)). Proof. rewrite directvE /= /dimv vs2mx_sum -mxdirectE; apply: (equivP mxdirect_sumsP). by do [split=> dxU i /dxU; rewrite -vs2mx_sum -vs2mxI -vs2mx0] => [/val_inj|->]. Qed. Lemma directv_sumE {Ss : I -> addv_expr} (xunwrap := unwrap) : reflect [/\ forall i, P i -> directv (unwrap (Ss i)) & directv (\sum_(i | P i) xunwrap (Ss i))] (directv (\sum_(i | P i) unwrap (Ss i))). Proof. by rewrite !directvE /= /dimv 2!{1}vs2mx_sum -!mxdirectE; apply: mxdirect_sumsE. Qed. Lemma directv_sum_independent {Us : I -> {vspace vT}} : reflect (forall us, (forall i, P i -> us i \in Us i) -> \sum_(i | P i) us i = 0 -> (forall i, P i -> us i = 0)) (directv (\sum_(i | P i) Us i)). Proof. apply: (iffP directv_sumP) => [dxU us Uu u_0 i Pi | dxU i Pi]. apply/eqP; rewrite -memv0 -(dxU i Pi) memv_cap Uu //= -memvN -sub0r -{1}u_0. by rewrite (bigD1 i) //= [_ - us i]addrC addKr memv_sumr // => j /andP[/Uu]. apply/eqP; rewrite -subv0; apply/subvP=> v. rewrite memv_cap memv0 => /andP[Uiv /memv_sumP[us Uu Dv]]. have: \sum_(j | P j) [eta us with i |-> - v] j = 0. rewrite (bigD1 i) //= eqxx {1}Dv addrC -sumrB big1 // => j /andP[_ i'j]. by rewrite (negPf i'j) subrr. move/dxU/(_ i Pi); rewrite /= eqxx -oppr_eq0 => -> // j Pj. by have [-> | i'j] := eqVneq; rewrite ?memvN // Uu ?Pj. Qed. Lemma directv_sum_unique {Us : I -> {vspace vT}} : reflect (forall us vs, (forall i, P i -> us i \in Us i) -> (forall i, P i -> vs i \in Us i) -> (\sum_(i | P i) us i == \sum_(i | P i) vs i) = [forall (i | P i), us i == vs i]) (directv (\sum_(i | P i) Us i)). Proof. apply: (iffP directv_sum_independent) => [dxU us vs Uu Uv | dxU us Uu u_0 i Pi]. apply/idP/forall_inP=> [|eq_uv]; last by apply/eqP/eq_bigr => i /eq_uv/eqP. rewrite -subr_eq0 -sumrB => /eqP/dxU eq_uv i Pi. by rewrite -subr_eq0 eq_uv // => j Pj; apply: memvB; move: j Pj. apply/eqP; have:= esym (dxU us \0 Uu _); rewrite u_0 big1_eq eqxx. by move/(_ _)/forall_inP=> -> // j _; apply: mem0v. Qed. End NaryDirect. (* Linear span generated by a list of vectors *) Lemma memv_span X v : v \in X -> v \in <<X>>%VS. Proof. by case/seq_tnthP=> i {v}->; rewrite unlock memvK genmxE (eq_row_sub i) // rowK. Qed. Lemma memv_span1 v : v \in <<[:: v]>>%VS. Proof. by rewrite memv_span ?mem_head. Qed. Lemma dim_span X : \dim <<X>> <= size X. Proof. by rewrite unlock /dimv genmxE rank_leq_row. Qed. Lemma span_subvP {X U} : reflect {subset X <= U} (<<X>> <= U)%VS. Proof. rewrite /subV [@span _ _]unlock genmxE. apply: (iffP row_subP) => /= [sXU | sXU i]. by move=> _ /seq_tnthP[i ->]; have:= sXU i; rewrite rowK memvK. by rewrite rowK -memvK sXU ?mem_tnth. Qed. Lemma sub_span X Y : {subset X <= Y} -> (<<X>> <= <<Y>>)%VS. Proof. by move=> sXY; apply/span_subvP=> v /sXY/memv_span. Qed. Lemma eq_span X Y : X =i Y -> (<<X>> = <<Y>>)%VS. Proof. by move=> eqXY; apply: subv_anti; rewrite !sub_span // => u; rewrite eqXY. Qed. Lemma span_def X : span X = (\sum_(u <- X) <[u]>)%VS. Proof. apply/subv_anti/andP; split. by apply/span_subvP=> v Xv; rewrite (big_rem v) // memvE addvSl. by rewrite big_tnth; apply/subv_sumP=> i _; rewrite -memvE memv_span ?mem_tnth. Qed. Lemma span_nil : (<<Nil vT>> = 0)%VS. Proof. by rewrite span_def big_nil. Qed. Lemma span_seq1 v : (<<[:: v]>> = <[v]>)%VS. Proof. by rewrite span_def big_seq1. Qed. Lemma span_cons v X : (<<v :: X>> = <[v]> + <<X>>)%VS. Proof. by rewrite !span_def big_cons. Qed. Lemma span_cat X Y : (<<X ++ Y>> = <<X>> + <<Y>>)%VS. Proof. by rewrite !span_def big_cat. Qed. (* Coordinates function; should perhaps be generalized to nat indices. *) Definition coord_expanded_def n (X : n.-tuple vT) i v := (v2r v *m pinvmx (b2mx X)) 0 i. Definition coord := locked_with span_key coord_expanded_def. Canonical coord_unlockable := [unlockable fun coord]. Fact coord_is_scalar n (X : n.-tuple vT) i : scalar (coord X i). Proof. by move=> k u v; rewrite unlock linearP mulmxDl -scalemxAl !mxE. Qed. HB.instance Definition _ n Xn i := GRing.isSemilinear.Build K vT K _ (coord Xn i) (GRing.semilinear_linear (@coord_is_scalar n Xn i)). Lemma coord_span n (X : n.-tuple vT) v : v \in span X -> v = \sum_i coord X i v *: X`_i. Proof. rewrite memvK span_b2mx genmxE => Xv. by rewrite unlock_with mul_b2mx mulmxKpV ?v2rK. Qed. Lemma coord0 i v : coord [tuple 0] i v = 0. Proof. rewrite unlock /pinvmx rank_rV; case: negP => [[] | _]. by apply/eqP/rowP=> j; rewrite !mxE (tnth_nth 0) /= linear0 mxE. by rewrite pid_mx_0 !(mulmx0, mul0mx) mxE. Qed. (* Free generator sequences. *) Lemma nil_free : free (Nil vT). Proof. by rewrite /free span_nil dimv0. Qed. Lemma seq1_free v : free [:: v] = (v != 0). Proof. by rewrite /free span_seq1 dim_vline; case: (~~ _). Qed. Lemma perm_free X Y : perm_eq X Y -> free X = free Y. Proof. by move=> eqXY; rewrite /free (perm_size eqXY) (eq_span (perm_mem eqXY)). Qed. Lemma free_directv X : free X = (0 \notin X) && directv (\sum_(v <- X) <[v]>). Proof. have leXi i (v := tnth (in_tuple X) i): true -> \dim <[v]> <= 1 ?= iff (v != 0). by rewrite -seq1_free -span_seq1 => _; apply/leqif_eq/dim_span. have [_ /=] := leqif_trans (dimv_sum_leqif _) (leqif_sum leXi). rewrite sum1_card card_ord !directvE /= /free andbC span_def !(big_tnth _ _ X). by congr (_ = _ && _); rewrite -has_pred1 -all_predC -big_all big_tnth big_andE. Qed. Lemma free_not0 v X : free X -> v \in X -> v != 0. Proof. by rewrite free_directv andbC => /andP[_ /memPn]; apply. Qed. Lemma freeP n (X : n.-tuple vT) : reflect (forall k, \sum_(i < n) k i *: X`_i = 0 -> (forall i, k i = 0)) (free X). Proof. rewrite free_b2mx; apply: (iffP idP) => [t_free k kt0 i | t_free]. suffices /rowP/(_ i): \row_i k i = 0 by rewrite !mxE. by apply/(row_free_inj t_free)/r2v_inj; rewrite mul0mx -lin_b2mx kt0 linear0. rewrite -kermx_eq0; apply/rowV0P=> rk /sub_kermxP kt0. by apply/rowP=> i; rewrite mxE {}t_free // mul_b2mx kt0 linear0. Qed. Lemma coord_free n (X : n.-tuple vT) (i j : 'I_n) : free X -> coord X j (X`_i) = (i == j)%:R. Proof. rewrite unlock free_b2mx => /row_freeP[Ct CtK]; rewrite -row_b2mx. rewrite -row_mul -[pinvmx _]mulmx1 -CtK (mulmxA (b2mx X)) (mulmxA _ _ Ct). by rewrite mulmxKpV // CtK !mxE. Qed. Lemma coord_sum_free n (X : n.-tuple vT) k j : free X -> coord X j (\sum_(i < n) k i *: X`_i) = k j. Proof. move=> Xfree; rewrite linear_sum (bigD1 j) 1?linearZ //= coord_free // eqxx. rewrite mulr1 big1 ?addr0 // => i /negPf j'i. by rewrite linearZ /= coord_free // j'i mulr0. Qed. Lemma cat_free X Y : free (X ++ Y) = [&& free X, free Y & directv (<<X>> + <<Y>>)]. Proof. rewrite !free_directv mem_cat directvE /= !big_cat -directvE /= directv_addE /=. rewrite negb_or -!andbA; do !bool_congr; rewrite -!span_def. by rewrite (sameP eqP directv_addP). Qed. Lemma catl_free Y X : free (X ++ Y) -> free X. Proof. by rewrite cat_free => /and3P[]. Qed. Lemma catr_free X Y : free (X ++ Y) -> free Y. Proof. by rewrite cat_free => /and3P[]. Qed. Lemma filter_free p X : free X -> free (filter p X). Proof. rewrite -(perm_free (etrans (perm_filterC p X _) (perm_refl X))). exact: catl_free. Qed. Lemma free_cons v X : free (v :: X) = (v \notin <<X>>)%VS && free X. Proof. rewrite (cat_free [:: v]) seq1_free directvEgeq /= span_seq1 dim_vline. case: eqP => [-> | _] /=; first by rewrite mem0v. rewrite andbC ltnNge (geq_leqif (dimv_leqif_sup _)) ?addvSr //. by rewrite subv_add subvv andbT -memvE. Qed. Lemma freeE n (X : n.-tuple vT) : free X = [forall i : 'I_n, X`_i \notin <<drop i.+1 X>>%VS]. Proof. case: X => X /= /eqP <-{n}; rewrite -(big_andE xpredT) /=. elim: X => [|v X IH_X] /=; first by rewrite nil_free big_ord0. by rewrite free_cons IH_X big_ord_recl drop0. Qed. Lemma freeNE n (X : n.-tuple vT) : ~~ free X = [exists i : 'I_n, X`_i \in <<drop i.+1 X>>%VS]. Proof. by rewrite freeE -negb_exists negbK. Qed. Lemma free_uniq X : free X -> uniq X. Proof. elim: X => //= v b IH_X; rewrite free_cons => /andP[X'v /IH_X->]. by rewrite (contra _ X'v) // => /memv_span. Qed. Lemma free_span X v (sumX := fun k => \sum_(x <- X) k x *: x) : free X -> v \in <<X>>%VS -> {k | v = sumX k & forall k1, v = sumX k1 -> {in X, k1 =1 k}}. Proof. rewrite -{2}[X]in_tupleE => freeX /coord_span def_v. pose k x := oapp (fun i => coord (in_tuple X) i v) 0 (insub (index x X)). exists k => [|k1 {}def_v _ /(nthP 0)[i ltiX <-]]. rewrite /sumX (big_nth 0) big_mkord def_v; apply: eq_bigr => i _. by rewrite /k index_uniq ?free_uniq // valK. rewrite /k /= index_uniq ?free_uniq // insubT //= def_v. by rewrite /sumX (big_nth 0) big_mkord coord_sum_free. Qed. Lemma linear_of_free (rT : lmodType K) X (fX : seq rT) : {f : {linear vT -> rT} | free X -> size fX = size X -> map f X = fX}. Proof. pose f u := \sum_i coord (in_tuple X) i u *: fX`_i. have lin_f: linear f. move=> k u v; rewrite scaler_sumr -big_split; apply: eq_bigr => i _. by rewrite /= scalerA -scalerDl linearP. pose flM := GRing.isLinear.Build _ _ _ _ f lin_f. pose fL : {linear _ -> _} := HB.pack f flM. exists fL => freeX eq_szX. apply/esym/(@eq_from_nth _ 0); rewrite ?size_map eq_szX // => i ltiX. rewrite (nth_map 0) //= /f (bigD1 (Ordinal ltiX)) //=. rewrite big1 => [|j /negbTE neqji]; rewrite (coord_free (Ordinal _)) //. by rewrite eqxx scale1r addr0. by rewrite eq_sym neqji scale0r. Qed. (* Subspace bases *) Lemma span_basis U X : basis_of U X -> <<X>>%VS = U. Proof. by case/andP=> /eqP. Qed. Lemma basis_free U X : basis_of U X -> free X. Proof. by case/andP. Qed. Lemma coord_basis U n (X : n.-tuple vT) v : basis_of U X -> v \in U -> v = \sum_i coord X i v *: X`_i. Proof. by move/span_basis <-; apply: coord_span. Qed. Lemma nil_basis : basis_of 0 (Nil vT). Proof. by rewrite /basis_of span_nil eqxx nil_free. Qed. Lemma seq1_basis v : v != 0 -> basis_of <[v]> [:: v]. Proof. by move=> nz_v; rewrite /basis_of span_seq1 // eqxx seq1_free. Qed. Lemma basis_not0 x U X : basis_of U X -> x \in X -> x != 0. Proof. by move/basis_free/free_not0; apply. Qed. Lemma basis_mem x U X : basis_of U X -> x \in X -> x \in U. Proof. by move/span_basis=> <- /memv_span. Qed. Lemma cat_basis U V X Y : directv (U + V) -> basis_of U X -> basis_of V Y -> basis_of (U + V) (X ++ Y). Proof. move=> dxUV /andP[/eqP defU freeX] /andP[/eqP defV freeY]. by rewrite /basis_of span_cat cat_free defU defV // eqxx freeX freeY. Qed. Lemma size_basis U n (X : n.-tuple vT) : basis_of U X -> \dim U = n. Proof. by case/andP=> /eqP <- /eqnP->; apply: size_tuple. Qed. Lemma basisEdim X U : basis_of U X = (U <= <<X>>)%VS && (size X <= \dim U). Proof. apply/andP/idP=> [[defU /eqnP <-]| ]; first by rewrite -eqEdim eq_sym. case/andP=> sUX leXU; have leXX := dim_span X. rewrite /free eq_sym eqEdim sUX eqn_leq !(leq_trans leXX) //. by rewrite (leq_trans leXU) ?dimvS. Qed. Lemma basisEfree X U : basis_of U X = [&& free X, (<<X>> <= U)%VS & \dim U <= size X]. Proof. by rewrite andbC; apply: andb_id2r => freeX; rewrite eqEdim (eqnP freeX). Qed. Lemma perm_basis X Y U : perm_eq X Y -> basis_of U X = basis_of U Y. Proof. move=> eqXY; congr ((_ == _) && _); last exact: perm_free. exact/eq_span/perm_mem. Qed. Lemma vbasisP U : basis_of U (vbasis U). Proof. rewrite /basis_of free_b2mx span_b2mx (sameP eqP (vs2mxP _ _)) !genmxE. have ->: b2mx (vbasis U) = row_base (vs2mx U). by apply/row_matrixP=> i; rewrite unlock rowK tnth_mktuple r2vK. by rewrite row_base_free !eq_row_base submx_refl. Qed. Lemma vbasis_mem v U : v \in (vbasis U) -> v \in U. Proof. exact: basis_mem (vbasisP _). Qed. Lemma coord_vbasis v U : v \in U -> v = \sum_(i < \dim U) coord (vbasis U) i v *: (vbasis U)`_i. Proof. exact: coord_basis (vbasisP U). Qed. Section BigSumBasis. Variables (I : finType) (P : pred I) (Xs : I -> seq vT). Lemma span_bigcat : (<<\big[cat/[::]]_(i | P i) Xs i>> = \sum_(i | P i) <<Xs i>>)%VS. Proof. by rewrite (big_morph _ span_cat span_nil). Qed. Lemma bigcat_free : directv (\sum_(i | P i) <<Xs i>>) -> (forall i, P i -> free (Xs i)) -> free (\big[cat/[::]]_(i | P i) Xs i). Proof. rewrite /free directvE /= span_bigcat => /directvP-> /= freeXs. rewrite (big_morph _ (@size_cat _) (erefl _)) /=. by apply/eqP/eq_bigr=> i /freeXs/eqP. Qed. Lemma bigcat_basis Us (U := (\sum_(i | P i) Us i)%VS) : directv U -> (forall i, P i -> basis_of (Us i) (Xs i)) -> basis_of U (\big[cat/[::]]_(i | P i) Xs i). Proof. move=> dxU XsUs; rewrite /basis_of span_bigcat. have defUs i: P i -> span (Xs i) = Us i by case/XsUs/andP=> /eqP. rewrite (eq_bigr _ defUs) eqxx bigcat_free // => [|_ /XsUs/andP[]//]. apply/directvP; rewrite /= (eq_bigr _ defUs) (directvP dxU) /=. by apply/eq_bigr=> i /defUs->. Qed. End BigSumBasis. End VectorTheory. #[global] Hint Resolve subvv : core. Arguments subvP {K vT U V}. Arguments addv_idPl {K vT U V}. Arguments addv_idPr {K vT U V}. Arguments memv_addP {K vT w U V }. Arguments sumv_sup [K vT I] i0 [P U Vs]. Arguments memv_sumP {K vT I P Us v}. Arguments subv_sumP {K vT I P Us V}. Arguments capv_idPl {K vT U V}. Arguments capv_idPr {K vT U V}. Arguments memv_capP {K vT w U V}. Arguments bigcapv_inf [K vT I] i0 [P Us V]. Arguments subv_bigcapP {K vT I P U Vs}. Arguments directvP {K vT S}. Arguments directv_addP {K vT U V}. Arguments directv_add_unique {K vT U V}. Arguments directv_sumP {K vT I P Us}. Arguments directv_sumE {K vT I P Ss}. Arguments directv_sum_independent {K vT I P Us}. Arguments directv_sum_unique {K vT I P Us}. Arguments span_subvP {K vT X U}. Arguments freeP {K vT n X}. Prenex Implicits coord. Notation directv S := (directv_def (Phantom _ S%VS)). (* Linear functions over a vectType *) Section LfunDefs. Variable R : nzRingType. Implicit Types aT vT rT : vectType R. Fact lfun_key : unit. Proof. by []. Qed. Definition fun_of_lfun_def aT rT (f : 'Hom(aT, rT)) := r2v \o mulmxr (f2mx f) \o v2r. Definition fun_of_lfun := locked_with lfun_key fun_of_lfun_def. Canonical fun_of_lfun_unlockable := [unlockable fun fun_of_lfun]. Definition linfun_def aT rT (f : aT -> rT) := Hom (lin1_mx (v2r \o f \o r2v)). Definition linfun := locked_with lfun_key linfun_def. Canonical linfun_unlockable := [unlockable fun linfun]. Definition id_lfun vT := @linfun vT vT idfun. Definition comp_lfun aT vT rT (f : 'Hom(vT, rT)) (g : 'Hom(aT, vT)) := linfun (fun_of_lfun f \o fun_of_lfun g). End LfunDefs. Coercion fun_of_lfun : hom >-> Funclass. Notation "\1" := (@id_lfun _ _) : lfun_scope. Notation "f \o g" := (comp_lfun f g) : lfun_scope. Section LfunVspaceDefs. Variable K : fieldType. Implicit Types aT rT : vectType K. Definition inv_lfun aT rT (f : 'Hom(aT, rT)) := Hom (pinvmx (f2mx f)). Definition lker aT rT (f : 'Hom(aT, rT)) := mx2vs (kermx (f2mx f)). Fact lfun_img_key : unit. Proof. by []. Qed. Definition lfun_img_def aT rT f (U : {vspace aT}) : {vspace rT} := mx2vs (vs2mx U *m f2mx f). Definition lfun_img := locked_with lfun_img_key lfun_img_def. Canonical lfun_img_unlockable := [unlockable fun lfun_img]. Definition lfun_preim aT rT (f : 'Hom(aT, rT)) W := (lfun_img (inv_lfun f) (W :&: lfun_img f fullv) + lker f)%VS. End LfunVspaceDefs. Prenex Implicits linfun lfun_img lker lfun_preim. Notation "f ^-1" := (inv_lfun f) : lfun_scope. Notation "f @: U" := (lfun_img f%VF%R U) (at level 24) : vspace_scope. Notation "f @^-1: W" := (lfun_preim f%VF%R W) (at level 24) : vspace_scope. Notation limg f := (lfun_img f fullv). Section LfunZmodType. Variables (R : nzRingType) (aT rT : vectType R). Implicit Types f g h : 'Hom(aT, rT). HB.instance Definition _ := [Choice of 'Hom(aT, rT) by <:]. Fact lfun_is_linear f : linear f. Proof. by rewrite unlock; apply: linearP. Qed. HB.instance Definition _ (f : hom aT rT) := GRing.isSemilinear.Build R aT rT _ f (GRing.semilinear_linear (lfun_is_linear f)). Lemma lfunE (ff : {linear aT -> rT}) : linfun ff =1 ff. Proof. by move=> v; rewrite 2!unlock /= mul_rV_lin1 /= !v2rK. Qed. Lemma fun_of_lfunK : cancel (@fun_of_lfun R aT rT) linfun. Proof. move=> f; apply/val_inj/row_matrixP=> i. by rewrite 2!unlock /= !rowE mul_rV_lin1 /= !r2vK. Qed. Lemma lfunP f g : f =1 g <-> f = g. Proof. split=> [eq_fg | -> //]; rewrite -[f]fun_of_lfunK -[g]fun_of_lfunK unlock. by apply/val_inj/row_matrixP=> i; rewrite !rowE !mul_rV_lin1 /= eq_fg. Qed. Definition zero_lfun : 'Hom(aT, rT) := linfun \0. Definition add_lfun f g := linfun (f \+ g). Definition opp_lfun f := linfun (-%R \o f). Fact lfun_addA : associative add_lfun. Proof. by move=> f g h; apply/lfunP=> v; rewrite !lfunE /= !lfunE addrA. Qed. Fact lfun_addC : commutative add_lfun. Proof. by move=> f g; apply/lfunP=> v; rewrite !lfunE /= addrC. Qed. Fact lfun_add0 : left_id zero_lfun add_lfun. Proof. by move=> f; apply/lfunP=> v; rewrite lfunE /= lfunE add0r. Qed. Lemma lfun_addN : left_inverse zero_lfun opp_lfun add_lfun. Proof. by move=> f; apply/lfunP=> v; rewrite !lfunE /= lfunE addNr. Qed. HB.instance Definition _ := GRing.isZmodule.Build 'Hom(aT, rT) lfun_addA lfun_addC lfun_add0 lfun_addN. Lemma zero_lfunE x : (0 : 'Hom(aT, rT)) x = 0. Proof. exact: lfunE. Qed. Lemma add_lfunE f g x : (f + g) x = f x + g x. Proof. exact: lfunE. Qed. Lemma opp_lfunE f x : (- f) x = - f x. Proof. exact: lfunE. Qed. Lemma sum_lfunE I (r : seq I) (P : pred I) (fs : I -> 'Hom(aT, rT)) x : (\sum_(i <- r | P i) fs i) x = \sum_(i <- r | P i) fs i x. Proof. by elim/big_rec2: _ => [|i _ f _ <-]; rewrite lfunE. Qed. End LfunZmodType. Arguments fun_of_lfunK {R aT rT}. Section LfunVectType. Variables (R : comNzRingType) (aT rT : vectType R). Implicit Types f : 'Hom(aT, rT). Definition scale_lfun k f := linfun (k \*: f). Local Infix "*:l" := scale_lfun (at level 40). Fact lfun_scaleA k1 k2 f : k1 *:l (k2 *:l f) = (k1 * k2) *:l f. Proof. by apply/lfunP=> v; rewrite !lfunE /= lfunE scalerA. Qed. Fact lfun_scale1 f : 1 *:l f = f. Proof. by apply/lfunP=> v; rewrite lfunE /= scale1r. Qed. Fact lfun_scaleDr k f1 f2 : k *:l (f1 + f2) = k *:l f1 + k *:l f2. Proof. by apply/lfunP=> v; rewrite !lfunE /= !lfunE scalerDr. Qed. Fact lfun_scaleDl f k1 k2 : (k1 + k2) *:l f = k1 *:l f + k2 *:l f. Proof. by apply/lfunP=> v; rewrite !lfunE /= !lfunE scalerDl. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build _ 'Hom(aT, rT) lfun_scaleA lfun_scale1 lfun_scaleDr lfun_scaleDl. Lemma scale_lfunE k f x : (k *: f) x = k *: f x. Proof. exact: lfunE. Qed. Fact lfun_vect_iso : Vector.axiom (dim aT * dim rT) 'Hom(aT, rT). Proof. exists (mxvec \o f2mx) => [a f g|]. rewrite /= -linearP /= -[A in _ = mxvec A]/(f2mx (Hom _)). congr (mxvec (f2mx _)); apply/lfunP=> v; do 2!rewrite lfunE /=. by rewrite unlock /= -linearP mulmxDr scalemxAr. apply: Bijective (Hom \o vec_mx) _ _ => [[A]|A] /=; last exact: vec_mxK. by rewrite mxvecK. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build _ 'Hom(aT, rT) lfun_vect_iso. End LfunVectType. Section CompLfun. Variables (R : nzRingType) (wT aT vT rT : vectType R). Implicit Types (f : 'Hom(vT, rT)) (g : 'Hom(aT, vT)) (h : 'Hom(wT, aT)). Lemma id_lfunE u: \1%VF u = u :> aT. Proof. exact: lfunE. Qed. Lemma comp_lfunE f g u : (f \o g)%VF u = f (g u). Proof. exact: lfunE. Qed. Lemma comp_lfunA f g h : (f \o (g \o h) = (f \o g) \o h)%VF. Proof. by apply/lfunP=> u; do !rewrite lfunE /=. Qed. Lemma comp_lfun1l f : (\1 \o f)%VF = f. Proof. by apply/lfunP=> u; do !rewrite lfunE /=. Qed. Lemma comp_lfun1r f : (f \o \1)%VF = f. Proof. by apply/lfunP=> u; do !rewrite lfunE /=. Qed. Lemma comp_lfun0l g : (0 \o g)%VF = 0 :> 'Hom(aT, rT). Proof. by apply/lfunP=> u; do !rewrite lfunE /=. Qed. Lemma comp_lfun0r f : (f \o 0)%VF = 0 :> 'Hom(aT, rT). Proof. by apply/lfunP=> u; do !rewrite lfunE /=; rewrite linear0. Qed. Lemma comp_lfunDl f1 f2 g : ((f1 + f2) \o g = (f1 \o g) + (f2 \o g))%VF. Proof. by apply/lfunP=> u; do !rewrite lfunE /=. Qed. Lemma comp_lfunDr f g1 g2 : (f \o (g1 + g2) = (f \o g1) + (f \o g2))%VF. Proof. by apply/lfunP=> u; do !rewrite lfunE /=; rewrite linearD. Qed. Lemma comp_lfunNl f g : ((- f) \o g = - (f \o g))%VF. Proof. by apply/lfunP=> u; do !rewrite lfunE /=. Qed. Lemma comp_lfunNr f g : (f \o (- g) = - (f \o g))%VF. Proof. by apply/lfunP=> u; do !rewrite lfunE /=; rewrite linearN. Qed. End CompLfun. Definition lfun_simp := (comp_lfunE, scale_lfunE, opp_lfunE, add_lfunE, sum_lfunE, lfunE). Section ScaleCompLfun. Variables (R : comNzRingType) (aT vT rT : vectType R). Implicit Types (f : 'Hom(vT, rT)) (g : 'Hom(aT, vT)). Lemma comp_lfunZl k f g : (k *: (f \o g) = (k *: f) \o g)%VF. Proof. by apply/lfunP=> u; do !rewrite lfunE /=. Qed. Lemma comp_lfunZr k f g : (k *: (f \o g) = f \o (k *: g))%VF. Proof. by apply/lfunP=> u; do !rewrite lfunE /=; rewrite linearZ. Qed. End ScaleCompLfun. Section LinearImage. Variables (K : fieldType) (aT rT : vectType K). Implicit Types (f g : 'Hom(aT, rT)) (U V : {vspace aT}) (W : {vspace rT}). Lemma limgS f U V : (U <= V)%VS -> (f @: U <= f @: V)%VS. Proof. by rewrite unlock /subsetv !genmxE; apply: submxMr. Qed. Lemma limg_line f v : (f @: <[v]> = <[f v]>)%VS. Proof. apply/eqP; rewrite 2!unlock eqEsubv /subsetv /= r2vK !genmxE. by rewrite !(eqmxMr _ (genmxE _)) submx_refl. Qed. Lemma limg0 f : (f @: 0 = 0)%VS. Proof. by rewrite limg_line linear0. Qed. Lemma memv_img f v U : v \in U -> f v \in (f @: U)%VS. Proof. by move=> Uv; rewrite memvE -limg_line limgS. Qed. Lemma memv_imgP f w U : reflect (exists2 u, u \in U & w = f u) (w \in f @: U)%VS. Proof. apply: (iffP idP) => [|[u Uu ->]]; last exact: memv_img. rewrite 2!unlock memvE /subsetv !genmxE => /submxP[ku Drw]. exists (r2v (ku *m vs2mx U)); last by rewrite /= r2vK -mulmxA -Drw v2rK. by rewrite memvE /subsetv !genmxE r2vK submxMl. Qed. Lemma lim0g U : (0 @: U = 0 :> {vspace rT})%VS. Proof. apply/eqP; rewrite -subv0; apply/subvP=> _ /memv_imgP[u _ ->]. by rewrite lfunE rpred0. Qed. Lemma eq_in_limg V f g : {in V, f =1 g} -> (f @: V = g @: V)%VS. Proof. move=> eq_fg; apply/vspaceP=> y. by apply/memv_imgP/memv_imgP=> [][x Vx ->]; exists x; rewrite ?eq_fg. Qed. Lemma limgD f : {morph lfun_img f : U V / U + V}%VS. Proof. move=> U V; apply/eqP; rewrite unlock eqEsubv /subsetv /= -genmx_adds. by rewrite !genmxE !(eqmxMr _ (genmxE _)) !addsmxMr submx_refl. Qed. Lemma limg_sum f I r (P : pred I) Us : (f @: (\sum_(i <- r | P i) Us i) = \sum_(i <- r | P i) f @: Us i)%VS. Proof. exact: (big_morph _ (limgD f) (limg0 f)). Qed. Lemma limg_cap f U V : (f @: (U :&: V) <= f @: U :&: f @: V)%VS. Proof. by rewrite subv_cap !limgS ?capvSl ?capvSr. Qed. Lemma limg_bigcap f I r (P : pred I) Us : (f @: (\bigcap_(i <- r | P i) Us i) <= \bigcap_(i <- r | P i) f @: Us i)%VS. Proof. elim/big_rec2: _ => [|i V U _ sUV]; first exact: subvf. by rewrite (subv_trans (limg_cap f _ U)) ?capvS. Qed. Lemma limg_span f X : (f @: <<X>> = <<map f X>>)%VS. Proof. by rewrite !span_def big_map limg_sum; apply: eq_bigr => x _; rewrite limg_line. Qed. Lemma subset_limgP f U (r : seq rT) : {subset r <= (f @: U)%VS} <-> (exists2 a, all (mem U) a & r = map f a). Proof. split => [|[{}r /allP/= rE ->] _ /mapP[x xr ->]]; last by rewrite memv_img ?rE. move=> /(_ _ _)/memv_imgP/sig2_eqW-/(all_sig_cond (0 : aT))[f' f'P]. exists (map f' r); first by apply/allP => _ /mapP [x /f'P[? ?] ->]. by symmetry; rewrite -map_comp; apply: map_id_in => x /f'P[]. Qed. Lemma lfunPn f g : reflect (exists u, f u != g u) (f != g). Proof. apply: (iffP idP) => [f'g|[x]]; last by apply: contraNneq => /lfunP->. suffices /subvPn[_ /memv_imgP[u _ ->]]: ~~ (limg (f - g) <= 0)%VS. by rewrite lfunE /= lfunE /= memv0 subr_eq0; exists u. apply: contra f'g => /subvP fg0; apply/eqP/lfunP=> u; apply/eqP. by rewrite -subr_eq0 -opp_lfunE -add_lfunE -memv0 fg0 ?memv_img ?memvf. Qed. Lemma inv_lfun_def f : (f \o f^-1 \o f)%VF = f. Proof. apply/lfunP=> u; do !rewrite lfunE /=; rewrite unlock /= !r2vK. by rewrite mulmxKpV ?submxMl. Qed. Lemma limg_lfunVK f : {in limg f, cancel f^-1%VF f}. Proof. by move=> _ /memv_imgP[u _ ->]; rewrite -!comp_lfunE inv_lfun_def. Qed. Lemma lkerE f U : (U <= lker f)%VS = (f @: U == 0)%VS. Proof. rewrite unlock -dimv_eq0 /dimv /subsetv !genmxE mxrank_eq0. by rewrite (sameP sub_kermxP eqP). Qed. Lemma memv_ker f v : (v \in lker f) = (f v == 0). Proof. by rewrite -memv0 !memvE subv0 lkerE limg_line. Qed. Lemma eqlfunP f g v : reflect (f v = g v) (v \in lker (f - g)). Proof. by rewrite memv_ker !lfun_simp subr_eq0; apply: eqP. Qed. Lemma eqlfun_inP V f g : reflect {in V, f =1 g} (V <= lker (f - g))%VS. Proof. by apply: (iffP subvP) => E x /E/eqlfunP. Qed. Lemma limg_ker_compl f U : (f @: (U :\: lker f) = f @: U)%VS. Proof. rewrite -{2}(addv_diff_cap U (lker f)) limgD; apply/esym/addv_idPl. by rewrite (subv_trans _ (sub0v _)) // subv0 -lkerE capvSr. Qed. Lemma limg_ker_dim f U : (\dim (U :&: lker f) + \dim (f @: U) = \dim U)%N. Proof. rewrite unlock /dimv /= genmx_cap genmx_id -genmx_cap !genmxE. by rewrite addnC mxrank_mul_ker. Qed. Lemma limg_dim_eq f U : (U :&: lker f = 0)%VS -> \dim (f @: U) = \dim U. Proof. by rewrite -(limg_ker_dim f U) => ->; rewrite dimv0. Qed. Lemma limg_basis_of f U X : (U :&: lker f = 0)%VS -> basis_of U X -> basis_of (f @: U) (map f X). Proof. move=> injUf /andP[/eqP defU /eqnP freeX]. by rewrite /basis_of /free size_map -limg_span -freeX defU limg_dim_eq ?eqxx. Qed. Lemma lker0P f : reflect (injective f) (lker f == 0%VS). Proof. rewrite -subv0; apply: (iffP subvP) => [injf u v eq_fuv | injf u]. apply/eqP; rewrite -subr_eq0 -memv0 injf //. by rewrite memv_ker linearB /= eq_fuv subrr. by rewrite memv_ker memv0 -(inj_eq injf) linear0. Qed. Lemma limg_ker0 f U V : lker f == 0%VS -> (f @: U <= f @: V)%VS = (U <= V)%VS. Proof. move/lker0P=> injf; apply/idP/idP=> [/subvP sfUV | ]; last exact: limgS. by apply/subvP=> u Uu; have /memv_imgP[v Vv /injf->] := sfUV _ (memv_img f Uu). Qed. Lemma eq_limg_ker0 f U V : lker f == 0%VS -> (f @: U == f @: V)%VS = (U == V). Proof. by move=> injf; rewrite !eqEsubv !limg_ker0. Qed. Lemma lker0_lfunK f : lker f == 0%VS -> cancel f f^-1%VF. Proof. by move/lker0P=> injf u; apply: injf; rewrite limg_lfunVK ?memv_img ?memvf. Qed. Lemma lker0_compVf f : lker f == 0%VS -> (f^-1 \o f = \1)%VF. Proof. by move/lker0_lfunK=> fK; apply/lfunP=> u; rewrite !lfunE /= fK. Qed. Lemma lker0_img_cap f U V : lker f == 0%VS -> (f @: (U :&: V) = f @: U :&: f @: V)%VS. Proof. move=> kf0; apply/eqP; rewrite eqEsubv limg_cap/=; apply/subvP => x. rewrite memv_cap => /andP[/memv_imgP[u uU ->]] /memv_imgP[v vV]. by move=> /(lker0P _ kf0) eq_uv; rewrite memv_img// memv_cap uU eq_uv vV. Qed. End LinearImage. Arguments memv_imgP {K aT rT f w U}. Arguments lfunPn {K aT rT f g}. Arguments lker0P {K aT rT f}. Arguments eqlfunP {K aT rT f g v}. Arguments eqlfun_inP {K aT rT V f g}. Arguments limg_lfunVK {K aT rT f} [x] f_x. Section FixedSpace. Variables (K : fieldType) (vT : vectType K). Implicit Types (f : 'End(vT)) (U : {vspace vT}). Definition fixedSpace f : {vspace vT} := lker (f - \1%VF). Lemma fixedSpaceP f a : reflect (f a = a) (a \in fixedSpace f). Proof. by rewrite memv_ker add_lfunE opp_lfunE id_lfunE subr_eq0; apply: eqP. Qed. Lemma fixedSpacesP f U : reflect {in U, f =1 id} (U <= fixedSpace f)%VS. Proof. by apply: (iffP subvP) => cUf x /cUf/fixedSpaceP. Qed. Lemma fixedSpace_limg f U : (U <= fixedSpace f -> f @: U = U)%VS. Proof. move/fixedSpacesP=> cUf; apply/vspaceP=> x. by apply/memv_imgP/idP=> [[{}x Ux ->] | Ux]; last exists x; rewrite ?cUf. Qed. Lemma fixedSpace_id : fixedSpace \1 = {:vT}%VS. Proof. by apply/vspaceP=> x; rewrite memvf; apply/fixedSpaceP; rewrite lfunE. Qed. End FixedSpace. Arguments fixedSpaceP {K vT f a}. Arguments fixedSpacesP {K vT f U}. Section LinAut. Variables (K : fieldType) (vT : vectType K) (f : 'End(vT)). Hypothesis kerf0 : lker f == 0%VS. Lemma lker0_limgf : limg f = fullv. Proof. by apply/eqP; rewrite eqEdim subvf limg_dim_eq //= (eqP kerf0) capv0. Qed. Lemma lker0_lfunVK : cancel f^-1%VF f. Proof. by move=> u; rewrite limg_lfunVK // lker0_limgf memvf. Qed. Lemma lker0_compfV : (f \o f^-1 = \1)%VF. Proof. by apply/lfunP=> u; rewrite !lfunE /= lker0_lfunVK. Qed. Lemma lker0_compVKf aT g : (f \o (f^-1 \o g))%VF = g :> 'Hom(aT, vT). Proof. by rewrite comp_lfunA lker0_compfV comp_lfun1l. Qed. Lemma lker0_compKf aT g : (f^-1 \o (f \o g))%VF = g :> 'Hom(aT, vT). Proof. by rewrite comp_lfunA lker0_compVf ?comp_lfun1l. Qed. Lemma lker0_compfK rT h : ((h \o f) \o f^-1)%VF = h :> 'Hom(vT, rT). Proof. by rewrite -comp_lfunA lker0_compfV comp_lfun1r. Qed. Lemma lker0_compfVK rT h : ((h \o f^-1) \o f)%VF = h :> 'Hom(vT, rT). Proof. by rewrite -comp_lfunA lker0_compVf ?comp_lfun1r. Qed. End LinAut. Section LinearImageComp. Variables (K : fieldType) (aT vT rT : vectType K). Implicit Types (f : 'Hom(aT, vT)) (g : 'Hom(vT, rT)) (U : {vspace aT}). Lemma lim1g U : (\1 @: U)%VS = U. Proof. have /andP[/eqP <- _] := vbasisP U; rewrite limg_span map_id_in // => u _. by rewrite lfunE. Qed. Lemma limg_comp f g U : ((g \o f) @: U = g @: (f @: U))%VS. Proof. have /andP[/eqP <- _] := vbasisP U; rewrite !limg_span; congr (span _). by rewrite -map_comp; apply/eq_map => u; rewrite lfunE. Qed. End LinearImageComp. Section LinearPreimage. Variables (K : fieldType) (aT rT : vectType K). Implicit Types (f : 'Hom(aT, rT)) (U : {vspace aT}) (V W : {vspace rT}). Lemma lpreim_cap_limg f W : (f @^-1: (W :&: limg f))%VS = (f @^-1: W)%VS. Proof. by rewrite /lfun_preim -capvA capvv. Qed. Lemma lpreim0 f : (f @^-1: 0)%VS = lker f. Proof. by rewrite /lfun_preim cap0v limg0 add0v. Qed. Lemma lpreimS f V W : (V <= W)%VS-> (f @^-1: V <= f @^-1: W)%VS. Proof. by move=> sVW; rewrite addvS // limgS // capvS. Qed. Lemma lpreimK f W : (W <= limg f)%VS -> (f @: (f @^-1: W))%VS = W. Proof. move=> sWf; rewrite limgD (capv_idPl sWf) // -limg_comp. have /eqP->: (f @: lker f == 0)%VS by rewrite -lkerE. have /andP[/eqP defW _] := vbasisP W; rewrite addv0 -defW limg_span. rewrite map_id_in // => x Xx; rewrite lfunE /= limg_lfunVK //. by apply: span_subvP Xx; rewrite defW. Qed. Lemma memv_preim f u W : (f u \in W) = (u \in f @^-1: W)%VS. Proof. apply/idP/idP=> [Wfu | /(memv_img f)]; last first. by rewrite -lpreim_cap_limg lpreimK ?capvSr // => /memv_capP[]. rewrite -[u](addNKr (f^-1%VF (f u))) memv_add ?memv_img //. by rewrite memv_cap Wfu memv_img ?memvf. by rewrite memv_ker addrC linearB /= subr_eq0 limg_lfunVK ?memv_img ?memvf. Qed. End LinearPreimage. Arguments lpreimK {K aT rT f} [W] fW. Section LfunAlgebra. (* This section is a bit of a place holder: the instances we build here can't *) (* be canonical because we are missing an interface for proper vectTypes, *) (* would sit between Vector and Falgebra. For now, we just supply structure *) (* definitions here and supply actual instances for F-algebras in a submodule *) (* of the algebra library (there is currently no actual use of the End(vT) *) (* algebra structure). Also note that the unit ring structure is missing. *) Variables (R : comNzRingType) (vT : vectType R). Hypothesis vT_proper : dim vT > 0. Fact lfun1_neq0 : \1%VF != 0 :> 'End(vT). Proof. apply/eqP=> /lfunP/(_ (r2v (const_mx 1))); rewrite !lfunE /= => /(canRL r2vK). by move=> /rowP/(_ (Ordinal vT_proper))/eqP; rewrite linear0 !mxE oner_eq0. Qed. Prenex Implicits comp_lfunA comp_lfun1l comp_lfun1r comp_lfunDl comp_lfunDr. (* FIXME: as explained above, the following structures should not be declared * * as canonical, so mixins and structures are built separately, and we * * don't use HB.instance Definition _ := ... * * This is ok, but maybe we could introduce an alias *) Definition lfun_comp_nzRingMixin := GRing.Zmodule_isNzRing.Build 'End(vT) comp_lfunA comp_lfun1l comp_lfun1r comp_lfunDl comp_lfunDr lfun1_neq0. #[deprecated(since="mathcomp 2.4.0", note="Use lfun_comp_nzRingMixin instead.")] Notation lfun_comp_ringMixin := (lfun_comp_nzRingMixin) (only parsing). Definition lfun_comp_nzRingType : nzRingType := HB.pack 'End(vT) lfun_comp_nzRingMixin. #[deprecated(since="mathcomp 2.4.0", note="Use lfun_comp_nzRingType instead.")] Notation lfun_comp_ringType := (lfun_comp_nzRingType) (only parsing). (* In the standard endomorphism ring product is categorical composition. *) Definition lfun_nzRingType : nzRingType := lfun_comp_nzRingType^c. #[deprecated(since="mathcomp 2.4.0", note="Use lfun_nzRingType instead.")] Notation lfun_ringType := (lfun_nzRingType) (only parsing). Definition lfun_lalgMixin := GRing.Lmodule_isLalgebra.Build R lfun_nzRingType (fun k x y => comp_lfunZr k y x). Definition lfun_lalgType : lalgType R := HB.pack 'End(vT) lfun_nzRingType lfun_lalgMixin. Definition lfun_algMixin := GRing.Lalgebra_isAlgebra.Build R lfun_lalgType (fun k x y => comp_lfunZl k y x). Definition lfun_algType : algType R := HB.pack 'End(vT) lfun_lalgType lfun_algMixin. End LfunAlgebra. Section Projection. Variables (K : fieldType) (vT : vectType K). Implicit Types U V : {vspace vT}. Definition daddv_pi U V := Hom (proj_mx (vs2mx U) (vs2mx V)). Definition projv U := daddv_pi U U^C. Definition addv_pi1 U V := daddv_pi (U :\: V) V. Definition addv_pi2 U V := daddv_pi V (U :\: V). Lemma memv_pi U V w : (daddv_pi U V) w \in U. Proof. by rewrite unlock memvE /subsetv genmxE /= r2vK proj_mx_sub. Qed. Lemma memv_proj U w : projv U w \in U. Proof. exact: memv_pi. Qed. Lemma memv_pi1 U V w : (addv_pi1 U V) w \in U. Proof. by rewrite (subvP (diffvSl U V)) ?memv_pi. Qed. Lemma memv_pi2 U V w : (addv_pi2 U V) w \in V. Proof. exact: memv_pi. Qed. Lemma daddv_pi_id U V u : (U :&: V = 0)%VS -> u \in U -> daddv_pi U V u = u. Proof. move/eqP; rewrite -dimv_eq0 memvE /subsetv /dimv !genmxE mxrank_eq0 => /eqP. by move=> dxUV Uu; rewrite unlock /= proj_mx_id ?v2rK. Qed. Lemma daddv_pi_proj U V w (pi := daddv_pi U V) : (U :&: V = 0)%VS -> pi (pi w) = pi w. Proof. by move/daddv_pi_id=> -> //; apply: memv_pi. Qed. Lemma daddv_pi_add U V w : (U :&: V = 0)%VS -> (w \in U + V)%VS -> daddv_pi U V w + daddv_pi V U w = w. Proof. move/eqP; rewrite -dimv_eq0 memvE /subsetv /dimv !genmxE mxrank_eq0 => /eqP. by move=> dxUW UVw; rewrite unlock /= -linearD /= add_proj_mx ?v2rK. Qed. Lemma projv_id U u : u \in U -> projv U u = u. Proof. exact: daddv_pi_id (capv_compl _). Qed. Lemma projv_proj U w : projv U (projv U w) = projv U w. Proof. exact: daddv_pi_proj (capv_compl _). Qed. Lemma memv_projC U w : w - projv U w \in (U^C)%VS. Proof. rewrite -{1}[w](daddv_pi_add (capv_compl U)) ?addv_complf ?memvf //. by rewrite addrC addKr memv_pi. Qed. Lemma limg_proj U : limg (projv U) = U. Proof. apply/vspaceP=> u; apply/memv_imgP/idP=> [[u1 _ ->] | ]; first exact: memv_proj. by exists (projv U u); rewrite ?projv_id ?memv_img ?memvf. Qed. Lemma lker_proj U : lker (projv U) = (U^C)%VS. Proof. apply/eqP; rewrite eqEdim andbC; apply/andP; split. by rewrite dimv_compl -(limg_ker_dim (projv U) fullv) limg_proj addnK capfv. by apply/subvP=> v; rewrite memv_ker -{2}[v]subr0 => /eqP <-; apply: memv_projC. Qed. Lemma addv_pi1_proj U V w (pi1 := addv_pi1 U V) : pi1 (pi1 w) = pi1 w. Proof. by rewrite daddv_pi_proj // capv_diff. Qed. Lemma addv_pi2_id U V v : v \in V -> addv_pi2 U V v = v. Proof. by apply: daddv_pi_id; rewrite capvC capv_diff. Qed. Lemma addv_pi2_proj U V w (pi2 := addv_pi2 U V) : pi2 (pi2 w) = pi2 w. Proof. by rewrite addv_pi2_id ?memv_pi2. Qed. Lemma addv_pi1_pi2 U V w : w \in (U + V)%VS -> addv_pi1 U V w + addv_pi2 U V w = w. Proof. by rewrite -addv_diff; exact/daddv_pi_add/capv_diff. Qed. Section Sumv_Pi. Variables (I : eqType) (r0 : seq I) (P : pred I) (Vs : I -> {vspace vT}). Let sumv_pi_rec i := fix loop r := if r is j :: r1 then let V1 := (\sum_(k <- r1) Vs k)%VS in if j == i then addv_pi1 (Vs j) V1 else (loop r1 \o addv_pi2 (Vs j) V1)%VF else 0. Notation sumV := (\sum_(i <- r0 | P i) Vs i)%VS. Definition sumv_pi_for V of V = sumV := fun i => sumv_pi_rec i (filter P r0). Variables (V : {vspace vT}) (defV : V = sumV). Lemma memv_sum_pi i v : sumv_pi_for defV i v \in Vs i. Proof. rewrite /sumv_pi_for. elim: (filter P r0) v => [|j r IHr] v /=; first by rewrite lfunE mem0v. by case: eqP => [->|_]; rewrite ?lfunE ?memv_pi1 /=. Qed. Lemma sumv_pi_uniq_sum v : uniq (filter P r0) -> v \in V -> \sum_(i <- r0 | P i) sumv_pi_for defV i v = v. Proof. rewrite /sumv_pi_for defV -!(big_filter r0 P). elim: (filter P r0) v => [|i r IHr] v /= => [_ | /andP[r'i /IHr{}IHr]]. by rewrite !big_nil memv0 => /eqP. rewrite !big_cons eqxx => /addv_pi1_pi2; congr (_ + _ = v). rewrite -[_ v]IHr ?memv_pi2 //; apply: eq_big_seq => j /=. by case: eqP => [<- /idPn | _]; rewrite ?lfunE. Qed. End Sumv_Pi. End Projection. Prenex Implicits daddv_pi projv addv_pi1 addv_pi2. Notation sumv_pi V := (sumv_pi_for (erefl V)). Section SumvPi. Variable (K : fieldType) (vT : vectType K). Lemma sumv_pi_sum (I : finType) (P : pred I) Vs v (V : {vspace vT}) (defV : V = (\sum_(i | P i) Vs i)%VS) : v \in V -> \sum_(i | P i) sumv_pi_for defV i v = v :> vT. Proof. by apply: sumv_pi_uniq_sum; have [e _ []] := big_enumP. Qed. Lemma sumv_pi_nat_sum m n (P : pred nat) Vs v (V : {vspace vT}) (defV : V = (\sum_(m <= i < n | P i) Vs i)%VS) : v \in V -> \sum_(m <= i < n | P i) sumv_pi_for defV i v = v :> vT. Proof. by apply: sumv_pi_uniq_sum; apply/filter_uniq/iota_uniq. Qed. End SumvPi. Section SubVector. (* Turn a {vspace V} into a vectType *) Variable (K : fieldType) (vT : vectType K) (U : {vspace vT}). Inductive subvs_of : predArgType := Subvs u & u \in U. Definition vsval w : vT := let: Subvs u _ := w in u. HB.instance Definition _ := [isSub of subvs_of for vsval]. HB.instance Definition _ := [Choice of subvs_of by <:]. HB.instance Definition _ := [SubChoice_isSubZmodule of subvs_of by <:]. HB.instance Definition _ := [SubZmodule_isSubLmodule of subvs_of by <:]. Lemma subvsP w : vsval w \in U. Proof. exact: valP. Qed. Lemma subvs_inj : injective vsval. Proof. exact: val_inj. Qed. Lemma congr_subvs u v : u = v -> vsval u = vsval v. Proof. exact: congr1. Qed. Lemma vsval_is_linear : linear vsval. Proof. by []. Qed. HB.instance Definition _ := GRing.isSemilinear.Build K subvs_of vT _ vsval (GRing.semilinear_linear vsval_is_linear). Fact vsproj_key : unit. Proof. by []. Qed. Definition vsproj_def u := Subvs (memv_proj U u). Definition vsproj := locked_with vsproj_key vsproj_def. Canonical vsproj_unlockable := [unlockable fun vsproj]. Lemma vsprojK : {in U, cancel vsproj vsval}. Proof. by rewrite unlock; apply: projv_id. Qed. Lemma vsvalK : cancel vsval vsproj. Proof. by move=> w; apply/val_inj/vsprojK/subvsP. Qed. Lemma vsproj_is_linear : linear vsproj. Proof. by move=> k w1 w2; apply: val_inj; rewrite unlock /= linearP. Qed. HB.instance Definition _ := GRing.isSemilinear.Build K vT subvs_of _ vsproj (GRing.semilinear_linear vsproj_is_linear). Fact subvs_vect_iso : Vector.axiom (\dim U) subvs_of. Proof. exists (fun w => \row_i coord (vbasis U) i (vsval w)). by move=> k w1 w2; apply/rowP=> i; rewrite !mxE linearP. exists (fun rw : 'rV_(\dim U) => vsproj (\sum_i rw 0 i *: (vbasis U)`_i)). move=> w /=; congr (vsproj _ = w): (vsvalK w). by rewrite {1}(coord_vbasis (subvsP w)); apply: eq_bigr => i _; rewrite mxE. move=> rw; apply/rowP=> i; rewrite mxE vsprojK. by rewrite coord_sum_free ?(basis_free (vbasisP U)). by apply: rpred_sum => j _; rewrite rpredZ ?vbasis_mem ?memt_nth. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build K subvs_of subvs_vect_iso. Lemma SubvsE x (xU : x \in U) : Subvs xU = vsproj x. Proof. by apply/val_inj; rewrite /= vsprojK. Qed. End SubVector. Prenex Implicits vsval vsproj vsvalK. Arguments subvs_inj {K vT U} [x1 x2]. Arguments vsprojK {K vT U} [x] Ux. Section MatrixVectType. Variables (R : nzRingType) (m n : nat). (* The apparently useless => /= in line 1 of the proof performs some evar *) (* expansions that the Ltac interpretation of exists is incapable of doing. *) Fact matrix_vect_iso : Vector.axiom (m * n) 'M[R]_(m, n). Proof. exists mxvec => /=; first exact: linearP. by exists vec_mx; [apply: mxvecK | apply: vec_mxK]. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build _ 'M[R]_(m, n) matrix_vect_iso. Lemma dim_matrix : dim 'M[R]_(m, n) = m * n. Proof. by []. Qed. End MatrixVectType. (* A ring is a one-dimension vector space *) Section RegularVectType. Variable R : nzRingType. Fact regular_vect_iso : Vector.axiom 1 R^o. Proof. exists (fun a => a%:M) => [a b c|]; first by rewrite rmorphD scale_scalar_mx. by exists (fun A : 'M_1 => A 0 0) => [a | A]; rewrite ?mxE // -mx11_scalar. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build _ R^o regular_vect_iso. End RegularVectType. (* External direct product of two vectTypes. *) Section ProdVector. Variables (R : nzRingType) (vT1 vT2 : vectType R). Fact pair_vect_iso : Vector.axiom (dim vT1 + dim vT2) (vT1 * vT2). Proof. pose p2r (u : vT1 * vT2) := row_mx (v2r u.1) (v2r u.2). pose r2p w := (r2v (lsubmx w) : vT1, r2v (rsubmx w) : vT2). have r2pK : cancel r2p p2r by move=> w; rewrite /p2r !r2vK hsubmxK. have p2rK : cancel p2r r2p by case=> u v; rewrite /r2p row_mxKl row_mxKr !v2rK. have r2p_lin: linear r2p by move=> a u v; congr (_ , _); rewrite /= !linearP. pose r2plM := GRing.isLinear.Build _ _ _ _ r2p r2p_lin. pose r2pL : {linear _ -> _} := HB.pack r2p r2plM. by exists p2r; [apply: (@can2_linear _ _ _ r2pL) | exists r2p]. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build _ (vT1 * vT2)%type pair_vect_iso. End ProdVector. (* Function from a finType into a ring form a vectype. *) Section FunVectType. Variable (I : finType) (R : nzRingType) (vT : vectType R). (* Type unification with exist is again a problem in this proof. *) Fact ffun_vect_iso : Vector.axiom (#|I| * dim vT) {ffun I -> vT}. Proof. pose fr (f : {ffun I -> vT}) := mxvec (\matrix_(i < #|I|) v2r (f (enum_val i))). exists fr => /= [k f g|]. rewrite -linearP; congr mxvec; apply/matrixP=> i j. by rewrite !mxE !ffunE linearP !mxE. exists (fun r => [ffun i => r2v (row (enum_rank i) (vec_mx r)) : vT]) => [g|r]. by apply/ffunP=> i; rewrite ffunE mxvecK rowK v2rK enum_rankK. by apply/(canLR vec_mxK)/matrixP=> i j; rewrite mxE ffunE r2vK enum_valK mxE. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build _ {ffun I -> vT} ffun_vect_iso. End FunVectType. (* Solving a tuple of linear equations. *) Section Solver. Variable (K : fieldType) (vT : vectType K). Variables (n : nat) (lhs : n.-tuple 'End(vT)) (rhs : n.-tuple vT). Let lhsf u := finfun ((tnth lhs)^~ u). Definition vsolve_eq U := finfun (tnth rhs) \in (linfun lhsf @: U)%VS. Lemma vsolve_eqP (U : {vspace vT}) : reflect (exists2 u, u \in U & forall i, tnth lhs i u = tnth rhs i) (vsolve_eq U). Proof. have lhsZ: linear lhsf by move=> a u v; apply/ffunP=> i; rewrite !ffunE linearP. pose lhslM := GRing.isLinear.Build _ _ _ _ lhsf lhsZ. pose lhsL : {linear _ -> _} := HB.pack lhsf lhslM. apply: (iffP memv_imgP) => [] [u Uu sol_u]; exists u => //. by move=> i; rewrite -[tnth rhs i]ffunE sol_u (lfunE lhsL) ffunE. by apply/ffunP=> i; rewrite (lfunE lhsL) !ffunE sol_u. Qed. End Solver. Section lfunP. Variable (F : fieldType). Context {uT vT : vectType F}. Local Notation m := (\dim {:uT}). Local Notation n := (\dim {:vT}). Lemma span_lfunP (U : seq uT) (phi psi : 'Hom(uT,vT)) : {in <<U>>%VS, phi =1 psi} <-> {in U, phi =1 psi}. Proof. split=> eq_phi_psi u uU; first by rewrite eq_phi_psi ?memv_span. rewrite [u](@coord_span _ _ _ (in_tuple U))// !linear_sum/=. by apply: eq_bigr=> i _; rewrite 2!linearZ/= eq_phi_psi// ?mem_nth. Qed. Lemma fullv_lfunP (U : seq uT) (phi psi : 'Hom(uT,vT)) : <<U>>%VS = fullv -> phi = psi <-> {in U, phi =1 psi}. Proof. by move=> Uf; split=> [->//|/span_lfunP]; rewrite Uf=> /(_ _ (memvf _))-/lfunP. Qed. End lfunP. Module passmx. Section passmx. Variable (F : fieldType). Section vecmx. Context {vT : vectType F}. Local Notation n := (\dim {:vT}). Variables (e : n.-tuple vT). Definition rVof (v : vT) := \row_i coord e i v. Lemma rVof_linear : linear rVof. Proof. by move=> x v1 v2; apply/rowP=> i; rewrite !mxE linearP. Qed. HB.instance Definition _ := GRing.isSemilinear.Build F _ _ _ rVof (GRing.semilinear_linear rVof_linear). Lemma coord_rVof i v : coord e i v = rVof v 0 i. Proof. by rewrite !mxE. Qed. Definition vecof (v : 'rV_n) := \sum_i v 0 i *: e`_i. Lemma vecof_delta i : vecof (delta_mx 0 i) = e`_i. Proof. rewrite /vecof (bigD1 i)//= mxE !eqxx scale1r big1 ?addr0// => j neq_ji. by rewrite mxE (negPf neq_ji) andbF scale0r. Qed. Lemma vecof_linear : linear vecof. Proof. move=> x v1 v2; rewrite linear_sum -big_split/=. by apply: eq_bigr => i _/=; rewrite !mxE scalerDl scalerA. Qed. HB.instance Definition _ := GRing.isSemilinear.Build F _ _ _ vecof (GRing.semilinear_linear vecof_linear). Variable e_basis : basis_of {:vT} e. Lemma rVofK : cancel rVof vecof. Proof. move=> v; rewrite [v in RHS](coord_basis e_basis) ?memvf//. by apply: eq_bigr => i; rewrite !mxE. Qed. Lemma vecofK : cancel vecof rVof. Proof. move=> v; apply/rowP=> i; rewrite !(lfunE, mxE). by rewrite coord_sum_free ?(basis_free e_basis). Qed. Lemma rVofE (i : 'I_n) : rVof e`_i = delta_mx 0 i. Proof. apply/rowP=> k; rewrite !mxE. by rewrite eqxx coord_free ?(basis_free e_basis)// eq_sym. Qed. Lemma coord_vecof i v : coord e i (vecof v) = v 0 i. Proof. by rewrite coord_rVof vecofK. Qed. Lemma rVof_eq0 v : (rVof v == 0) = (v == 0). Proof. by rewrite -(inj_eq (can_inj vecofK)) rVofK linear0. Qed. Lemma vecof_eq0 v : (vecof v == 0) = (v == 0). Proof. by rewrite -(inj_eq (can_inj rVofK)) vecofK linear0. Qed. End vecmx. Section hommx. Context {uT vT : vectType F}. Local Notation m := (\dim {:uT}). Local Notation n := (\dim {:vT}). Variables (e : m.-tuple uT) (e' : n.-tuple vT). Definition mxof (h : 'Hom(uT, vT)) := lin1_mx (rVof e' \o h \o vecof e). Lemma mxof_linear : linear mxof. Proof. move=> x h1 h2; apply/matrixP=> i j; do !rewrite ?lfunE/= ?mxE. by rewrite linearP. Qed. HB.instance Definition _ := GRing.isSemilinear.Build F _ _ _ mxof (GRing.semilinear_linear mxof_linear). Definition funmx (M : 'M[F]_(m, n)) u := vecof e' (rVof e u *m M). Lemma funmx_linear M : linear (funmx M). Proof. by rewrite /funmx => x u v; rewrite linearP mulmxDl -scalemxAl linearP. Qed. HB.instance Definition _ M := GRing.isSemilinear.Build F _ _ _ (funmx M) (GRing.semilinear_linear (funmx_linear M)). Definition hommx M : 'Hom(uT, vT) := linfun (funmx M). Lemma hommx_linear : linear hommx. Proof. rewrite /hommx; move=> x A B; apply/lfunP=> u; do !rewrite lfunE/=. by rewrite /funmx mulmxDr -scalemxAr linearP. Qed. HB.instance Definition _ M := GRing.isSemilinear.Build F _ _ _ hommx (GRing.semilinear_linear hommx_linear). Hypothesis e_basis: basis_of {:uT} e. Hypothesis f_basis: basis_of {:vT} e'. Lemma mxofK : cancel mxof hommx. Proof. by move=> h; apply/lfunP=> u; rewrite lfunE/= /funmx mul_rV_lin1/= !rVofK. Qed. Lemma hommxK : cancel hommx mxof. Proof. move=> M; apply/matrixP => i j; rewrite !mxE/= lfunE/=. by rewrite /funmx vecofK// -rowE coord_vecof// mxE. Qed. Lemma mul_mxof phi u : u *m mxof phi = rVof e' (phi (vecof e u)). Proof. by rewrite mul_rV_lin1/=. Qed. Lemma hommxE M u : hommx M u = vecof e' (rVof e u *m M). Proof. by rewrite -[M in RHS]hommxK mul_mxof !rVofK//. Qed. Lemma rVof_mul M u : rVof e u *m M = rVof e' (hommx M u). Proof. by rewrite hommxE vecofK. Qed. Lemma hom_vecof (phi : 'Hom(uT, vT)) u : phi (vecof e u) = vecof e' (u *m mxof phi). Proof. by rewrite mul_mxof rVofK. Qed. Lemma rVof_app (phi : 'Hom(uT, vT)) u : rVof e' (phi u) = rVof e u *m mxof phi. Proof. by rewrite mul_mxof !rVofK. Qed. Lemma vecof_mul M u : vecof e' (u *m M) = hommx M (vecof e u). Proof. by rewrite hommxE vecofK. Qed. Lemma mxof_eq0 phi : (mxof phi == 0) = (phi == 0). Proof. by rewrite -(inj_eq (can_inj hommxK)) mxofK linear0. Qed. Lemma hommx_eq0 M : (hommx M == 0) = (M == 0). Proof. by rewrite -(inj_eq (can_inj mxofK)) hommxK linear0. Qed. End hommx. Section hommx_comp. Context {uT vT wT : vectType F}. Local Notation m := (\dim {:uT}). Local Notation n := (\dim {:vT}). Local Notation p := (\dim {:wT}). Variables (e : m.-tuple uT) (f : n.-tuple vT) (g : p.-tuple wT). Hypothesis e_basis: basis_of {:uT} e. Hypothesis f_basis: basis_of {:vT} f. Hypothesis g_basis: basis_of {:wT} g. Lemma mxof_comp (phi : 'Hom(uT, vT)) (psi : 'Hom(vT, wT)) : mxof e g (psi \o phi)%VF = mxof e f phi *m mxof f g psi. Proof. apply/matrixP => i k; rewrite !(mxE, comp_lfunE, lfunE) /=. rewrite [phi _](coord_basis f_basis) ?memvf// 2!linear_sum/=. by apply: eq_bigr => j _ /=; rewrite !mxE !linearZ/= !vecof_delta. Qed. Lemma hommx_mul (A : 'M_(m,n)) (B : 'M_(n, p)) : hommx e g (A *m B) = (hommx f g B \o hommx e f A)%VF. Proof. by apply: (can_inj (mxofK e_basis g_basis)); rewrite mxof_comp !hommxK. Qed. End hommx_comp. Section vsms. Context {vT : vectType F}. Local Notation n := (\dim {:vT}). Variables (e : n.-tuple vT). Definition msof (V : {vspace vT}) : 'M_n := mxof e e (projv V). (* alternative *) (* (\sum_(v <- vbasis V) <<rVof e v>>)%MS. *) Definition vsof (M : 'M[F]_n) := limg (hommx e e M). (* alternative *) (* <<[seq vecof e (row i M) | i : 'I_n]>>%VS. *) Lemma mxof1 : free e -> mxof e e \1 = 1%:M. Proof. by move=> eF; apply/matrixP=> i j; rewrite !mxE vecof_delta lfunE coord_free. Qed. Hypothesis e_basis : basis_of {:vT} e. Lemma hommx1 : hommx e e 1%:M = \1%VF. Proof. by rewrite -mxof1 ?(basis_free e_basis)// mxofK. Qed. Lemma msofK : cancel msof vsof. Proof. by rewrite /msof /vsof; move=> V; rewrite mxofK// limg_proj. Qed. Lemma mem_vecof u (V : {vspace vT}) : (vecof e u \in V) = (u <= msof V)%MS. Proof. apply/idP/submxP=> [|[v ->{u}]]; last by rewrite -hom_vecof// memv_proj. rewrite -[V in X in X -> _]msofK => /memv_imgP[v _]. by move=> /(canRL (vecofK _)) ->//; rewrite -rVof_mul//; eexists. Qed. Lemma rVof_sub u M : (rVof e u <= M)%MS = (u \in vsof M). Proof. apply/submxP/memv_imgP => [[v /(canRL (rVofK _)) ->//]|[v _ ->]]{u}. by exists (vecof e v); rewrite ?memvf// -vecof_mul. by exists (rVof e v); rewrite -rVof_mul. Qed. Lemma vsof_sub M V : (vsof M <= V)%VS = (M <= msof V)%MS. Proof. apply/subvP/rV_subP => [MsubV _/submxP[u ->]|VsubM _/memv_imgP[u _ ->]]. by rewrite -mem_vecof MsubV// -rVof_sub vecofK// submxMl. by rewrite -[V]msofK -rVof_sub VsubM// -rVof_mul// submxMl. Qed. Lemma msof_sub V M : (msof V <= M)%MS = (V <= vsof M)%VS. Proof. apply/rV_subP/subvP => [VsubM v vV|MsubV _/submxP[u ->]]. by rewrite -rVof_sub VsubM// -mem_vecof rVofK. by rewrite mul_mxof rVof_sub MsubV// memv_proj. Qed. Lemma vsofK M : (msof (vsof M) == M)%MS. Proof. by rewrite msof_sub -vsof_sub subvv. Qed. Lemma sub_msof : {mono msof : V V' / (V <= V')%VS >-> (V <= V')%MS}. Proof. by move=> V V'; rewrite msof_sub msofK. Qed. Lemma sub_vsof : {mono vsof : M M' / (M <= M')%MS >-> (M <= M')%VS}. Proof. by move=> M M'; rewrite vsof_sub (eqmxP (vsofK _)). Qed. Lemma msof0 : msof 0 = 0. Proof. apply/eqP; rewrite -submx0; apply/rV_subP => v. by rewrite -mem_vecof memv0 vecof_eq0// => /eqP->; rewrite sub0mx. Qed. Lemma vsof0 : vsof 0 = 0%VS. Proof. by apply/vspaceP=> v; rewrite memv0 -rVof_sub submx0 rVof_eq0. Qed. Lemma msof_eq0 V : (msof V == 0) = (V == 0%VS). Proof. by rewrite -(inj_eq (can_inj msofK)) msof0. Qed. Lemma vsof_eq0 M : (vsof M == 0%VS) = (M == 0). Proof. rewrite (sameP eqP eqmx0P) -!(eqmxP (vsofK M)) (sameP eqmx0P eqP) -msof0. by rewrite (inj_eq (can_inj msofK)). Qed. End vsms. Section eigen. Context {uT : vectType F}. Definition leigenspace (phi : 'End(uT)) a := lker (phi - a *: \1%VF). Definition leigenvalue phi a := leigenspace phi a != 0%VS. Local Notation m := (\dim {:uT}). Variables (e : m.-tuple uT). Hypothesis e_basis: basis_of {:uT} e. Let e_free := basis_free e_basis. Lemma lker_ker phi : lker phi = vsof e (kermx (mxof e e phi)). Proof. apply/vspaceP => v; rewrite memv_ker -rVof_sub// (sameP sub_kermxP eqP). by rewrite -rVof_app// rVof_eq0. Qed. Lemma limgE phi : limg phi = vsof e (mxof e e phi). Proof. apply/vspaceP => v; rewrite -rVof_sub//. apply/memv_imgP/submxP => [[u _ ->]|[u /(canRL (rVofK _)) ->//]]. by exists (rVof e u); rewrite -rVof_app. by exists (vecof e u); rewrite ?memvf// -hom_vecof. Qed. Lemma leigenspaceE f a : leigenspace f a = vsof e (eigenspace (mxof e e f) a). Proof. by rewrite [LHS]lker_ker linearB linearZ/= mxof1// scalemx1. Qed. End eigen. End passmx. End passmx.
Get.lean
/- Copyright (c) 2019 mathlib community. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Wojciech Nawrocki -/ import Mathlib.Data.Num.Basic import Mathlib.Data.Ordering.Basic import Mathlib.Data.Tree.Basic /-! # Binary tree get operation In this file we define `Tree.indexOf`, `Tree.get`, and `Tree.getOrElse`. These definitions were moved from the main file to avoid a dependency on `Num`. ## References <https://leanprover-community.github.io/archive/stream/113488-general/topic/tactic.20question.html#170999997> -/ namespace Tree variable {α : Type*} /-- Finds the index of an element in the tree assuming the tree has been constructed according to the provided decidable order on its elements. If it hasn't, the result will be incorrect. If it has, but the element is not in the tree, returns none. -/ def indexOf (lt : α → α → Prop) [DecidableRel lt] (x : α) : Tree α → Option PosNum | nil => none | node a t₁ t₂ => match cmpUsing lt x a with | Ordering.lt => PosNum.bit0 <$> indexOf lt x t₁ | Ordering.eq => some PosNum.one | Ordering.gt => PosNum.bit1 <$> indexOf lt x t₂ /-- Retrieves an element uniquely determined by a `PosNum` from the tree, taking the following path to get to the element: - `bit0` - go to left child - `bit1` - go to right child - `PosNum.one` - retrieve from here -/ def get : PosNum → Tree α → Option α | _, nil => none | PosNum.one, node a _t₁ _t₂ => some a | PosNum.bit0 n, node _a t₁ _t₂ => t₁.get n | PosNum.bit1 n, node _a _t₁ t₂ => t₂.get n /-- Retrieves an element from the tree, or the provided default value if the index is invalid. See `Tree.get`. -/ def getOrElse (n : PosNum) (t : Tree α) (v : α) : α := (t.get n).getD v end Tree
LocalizationAway.lean
/- Copyright (c) 2025 Christian Merten. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christian Merten -/ import Mathlib.RingTheory.Extension.Presentation.Basic /-! # Cotangent and localization away Let `R → S → T` be algebras such that `T` is the localization of `S` away from one element, where `S` is generated over `R` by `P` with kernel `I` and `Q` is the canonical `S`-presentation of `T`. Denote by `J` the kernel of the composition `R[X,Y] → T`. ## Main results - `Algebra.Generators.liftBaseChange_injective`: `T ⊗[S] (I/I²) → J/J²` is injective if `T` is the localization of `S` away from an element. -/ open TensorProduct MvPolynomial namespace Algebra.Generators variable {R S T ι : Type*} [CommRing R] [CommRing S] [Algebra R S] [CommRing T] [Algebra R T] [Algebra S T] [IsScalarTower R S T] variable (g : S) [IsLocalization.Away g T] (P : Generators R S ι) lemma comp_localizationAway_ker (P : Generators R S ι) (f : P.Ring) (h : algebraMap P.Ring S f = g) : ((Generators.localizationAway g).comp P).ker = Ideal.map ((Generators.localizationAway (S := T) g).toComp P).toAlgHom P.ker ⊔ Ideal.span {rename Sum.inr f * X (Sum.inl ()) - 1} := by have : (localizationAway (S := T) g).ker = Ideal.map ((localizationAway g).ofComp P).toAlgHom (Ideal.span {MvPolynomial.rename Sum.inr f * MvPolynomial.X (Sum.inl ()) - 1}) := by rw [Ideal.map_span, Set.image_singleton, map_sub, map_mul, map_one, ker_localizationAway, Hom.toAlgHom_X, toAlgHom_ofComp_rename, h, ofComp_val, Sum.elim_inl] rw [ker_comp_eq_sup, Algebra.Generators.map_toComp_ker, this, Ideal.comap_map_of_surjective _ (toAlgHom_ofComp_surjective _ P), ← RingHom.ker_eq_comap_bot, ← sup_assoc] simp variable (T) in /-- If `R[X] → S` generates `S`, `T` is the localization of `S` away from `g` and `f` is a pre-image of `g` in `R[X]`, this is the `R`-algebra map `R[X,Y] →ₐ[R] (R[X]/I²)[1/f]` defined via mapping `Y` to `1/f`. -/ noncomputable def compLocalizationAwayAlgHom : ((Generators.localizationAway g (S := T)).comp P).Ring →ₐ[R] Localization.Away (Ideal.Quotient.mk (P.ker ^ 2) (P.σ g)) := aeval (R := R) (S₁ := Localization.Away _) (Sum.elim (fun _ ↦ IsLocalization.Away.invSelf <| (Ideal.Quotient.mk (P.ker ^ 2) (P.σ g))) (fun i : ι ↦ algebraMap P.Ring _ (X i))) @[simp] lemma compLocalizationAwayAlgHom_toAlgHom_toComp (x : P.Ring) : compLocalizationAwayAlgHom T g P (((localizationAway g (S := T)).toComp P).toAlgHom x) = algebraMap P.Ring _ x := by simp only [toComp_toAlgHom, compLocalizationAwayAlgHom, comp, localizationAway, AlgHom.toRingHom_eq_coe, aeval_rename, Sum.elim_comp_inr, ← IsScalarTower.toAlgHom_apply (R := R), ← comp_aeval_apply, aeval_X_left_apply] @[simp] lemma compLocalizationAwayAlgHom_X_inl : compLocalizationAwayAlgHom T g P (X (Sum.inl ())) = IsLocalization.Away.invSelf ((Ideal.Quotient.mk (P.ker ^ 2)) (P.σ g)) := by simp [compLocalizationAwayAlgHom] lemma compLocalizationAwayAlgHom_relation_eq_zero : compLocalizationAwayAlgHom T g P (rename Sum.inr (P.σ g) * X (Sum.inl ()) - 1) = 0 := by rw [map_sub, map_one, map_mul, ← toComp_toAlgHom (Generators.localizationAway g (S := T)) P] change (compLocalizationAwayAlgHom T g P) (((localizationAway g).toComp P).toAlgHom _) * _ - _ = _ rw [compLocalizationAwayAlgHom_toAlgHom_toComp, compLocalizationAwayAlgHom_X_inl, IsScalarTower.algebraMap_apply P.Ring (P.Ring ⧸ P.ker ^ 2) (Localization.Away _)] simp lemma sq_ker_comp_le_ker_compLocalizationAwayAlgHom : ((localizationAway g (S := T)).comp P).ker ^ 2 ≤ RingHom.ker (compLocalizationAwayAlgHom T g P) := by have hsple {x} (hx : x ∈ Ideal.span {(rename Sum.inr) (P.σ g) * X (Sum.inl ()) - 1}) : (compLocalizationAwayAlgHom T g P) x = 0 := by obtain ⟨a, rfl⟩ := Ideal.mem_span_singleton.mp hx rw [map_mul, compLocalizationAwayAlgHom_relation_eq_zero, zero_mul] rw [comp_localizationAway_ker _ _ (P.σ g) (by simp), sq, Ideal.sup_mul, Ideal.mul_sup, Ideal.mul_sup] apply sup_le · apply sup_le · rw [← Ideal.map_mul, Ideal.map_le_iff_le_comap, ← sq] intro x hx simp only [Ideal.mem_comap, RingHom.mem_ker, compLocalizationAwayAlgHom_toAlgHom_toComp (T := T) g P x] rw [IsScalarTower.algebraMap_apply P.Ring (P.Ring ⧸ P.ker ^ 2) (Localization.Away _), Ideal.Quotient.algebraMap_eq, Ideal.Quotient.eq_zero_iff_mem.mpr hx, map_zero] · rw [Ideal.mul_le] intro x hx y hy simp [hsple hy] · apply sup_le <;> · rw [Ideal.mul_le] intro x hx y hy simp [hsple hx] /-- Let `R → S → T` be algebras such that `T` is the localization of `S` away from one element, where `S` is generated over `R` by `P` with kernel `I` and `Q` is the canonical `S`-presentation of `T`. Denote by `J` the kernel of the composition `R[X,Y] → T`. Then `T ⊗[S] (I/I²) → J/J²` is injective. -/ @[stacks 08JZ "part of (1)"] lemma liftBaseChange_injective_of_isLocalizationAway : Function.Injective (LinearMap.liftBaseChange T (Extension.Cotangent.map ((Generators.localizationAway g (S := T)).toComp P).toExtensionHom)) := by set Q := Generators.localizationAway g (S := T) algebraize [((Generators.localizationAway g (S := T)).toComp P).toAlgHom.toRingHom] let f : P.Ring ⧸ P.ker ^ 2 := P.σ g let π := compLocalizationAwayAlgHom T g P refine IsLocalizedModule.injective_of_map_zero (Submonoid.powers g) (TensorProduct.mk S T P.toExtension.Cotangent 1) (fun x hx ↦ ?_) obtain ⟨x, rfl⟩ := Algebra.Extension.Cotangent.mk_surjective x suffices h : algebraMap P.Ring (Localization.Away f) x.val = 0 by rw [IsScalarTower.algebraMap_apply _ (P.Ring ⧸ P.ker ^ 2) _, IsLocalization.map_eq_zero_iff (Submonoid.powers f) (Localization.Away f)] at h obtain ⟨⟨m, ⟨n, rfl⟩⟩, hm⟩ := h rw [IsLocalizedModule.eq_zero_iff (Submonoid.powers g)] use ⟨g ^ n, n, rfl⟩ dsimp [f] at hm rw [← map_pow, ← map_mul, Ideal.Quotient.eq_zero_iff_mem] at hm simp only [Submonoid.smul_def] rw [show g = algebraMap P.Ring S (P.σ g) by simp, ← map_pow, algebraMap_smul, ← map_smul, Extension.Cotangent.mk_eq_zero_iff] simpa using hm rw [← compLocalizationAwayAlgHom_toAlgHom_toComp (T := T)] apply sq_ker_comp_le_ker_compLocalizationAwayAlgHom simpa only [LinearEquiv.coe_coe, LinearMap.ringLmapEquivSelf_symm_apply, mk_apply, lift.tmul, LinearMap.coe_restrictScalars, LinearMap.coe_smulRight, Module.End.one_apply, LinearMap.smul_apply, one_smul, Algebra.Extension.Cotangent.map_mk, Extension.Cotangent.mk_eq_zero_iff] using hx end Algebra.Generators
Defs.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Yaël Dillies -/ import Mathlib.Data.Set.Operations import Mathlib.Logic.Function.Iterate import Mathlib.Order.Basic import Mathlib.Tactic.Coe import Mathlib.Util.AssertExists /-! # Monotonicity This file defines (strictly) monotone/antitone functions. Contrary to standard mathematical usage, "monotone"/"mono" here means "increasing", not "increasing or decreasing". We use "antitone"/"anti" to mean "decreasing". ## Definitions * `Monotone f`: A function `f` between two preorders is monotone if `a ≤ b` implies `f a ≤ f b`. * `Antitone f`: A function `f` between two preorders is antitone if `a ≤ b` implies `f b ≤ f a`. * `MonotoneOn f s`: Same as `Monotone f`, but for all `a, b ∈ s`. * `AntitoneOn f s`: Same as `Antitone f`, but for all `a, b ∈ s`. * `StrictMono f` : A function `f` between two preorders is strictly monotone if `a < b` implies `f a < f b`. * `StrictAnti f` : A function `f` between two preorders is strictly antitone if `a < b` implies `f b < f a`. * `StrictMonoOn f s`: Same as `StrictMono f`, but for all `a, b ∈ s`. * `StrictAntiOn f s`: Same as `StrictAnti f`, but for all `a, b ∈ s`. ## Implementation notes Some of these definitions used to only require `LE α` or `LT α`. The advantage of this is unclear and it led to slight elaboration issues. Now, everything requires `Preorder α` and seems to work fine. Related Zulip discussion: https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Order.20diamond/near/254353352. ## Tags monotone, strictly monotone, antitone, strictly antitone, increasing, strictly increasing, decreasing, strictly decreasing -/ assert_not_exists Nat.instLinearOrder Int.instLinearOrder open Function OrderDual universe u v w variable {ι : Type*} {α : Type u} {β : Type v} {γ : Type w} {δ : Type*} {π : ι → Type*} section MonotoneDef variable [Preorder α] [Preorder β] /-- A function `f` is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def Monotone (f : α → β) : Prop := ∀ ⦃a b⦄, a ≤ b → f a ≤ f b /-- A function `f` is antitone if `a ≤ b` implies `f b ≤ f a`. -/ def Antitone (f : α → β) : Prop := ∀ ⦃a b⦄, a ≤ b → f b ≤ f a /-- A function `f` is monotone on `s` if, for all `a, b ∈ s`, `a ≤ b` implies `f a ≤ f b`. -/ def MonotoneOn (f : α → β) (s : Set α) : Prop := ∀ ⦃a⦄ (_ : a ∈ s) ⦃b⦄ (_ : b ∈ s), a ≤ b → f a ≤ f b /-- A function `f` is antitone on `s` if, for all `a, b ∈ s`, `a ≤ b` implies `f b ≤ f a`. -/ def AntitoneOn (f : α → β) (s : Set α) : Prop := ∀ ⦃a⦄ (_ : a ∈ s) ⦃b⦄ (_ : b ∈ s), a ≤ b → f b ≤ f a /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def StrictMono (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b /-- A function `f` is strictly antitone if `a < b` implies `f b < f a`. -/ def StrictAnti (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f b < f a /-- A function `f` is strictly monotone on `s` if, for all `a, b ∈ s`, `a < b` implies `f a < f b`. -/ def StrictMonoOn (f : α → β) (s : Set α) : Prop := ∀ ⦃a⦄ (_ : a ∈ s) ⦃b⦄ (_ : b ∈ s), a < b → f a < f b /-- A function `f` is strictly antitone on `s` if, for all `a, b ∈ s`, `a < b` implies `f b < f a`. -/ def StrictAntiOn (f : α → β) (s : Set α) : Prop := ∀ ⦃a⦄ (_ : a ∈ s) ⦃b⦄ (_ : b ∈ s), a < b → f b < f a end MonotoneDef section Decidable variable [Preorder α] [Preorder β] {f : α → β} {s : Set α} instance [i : Decidable (∀ a b, a ≤ b → f a ≤ f b)] : Decidable (Monotone f) := i instance [i : Decidable (∀ a b, a ≤ b → f b ≤ f a)] : Decidable (Antitone f) := i instance [i : Decidable (∀ a ∈ s, ∀ b ∈ s, a ≤ b → f a ≤ f b)] : Decidable (MonotoneOn f s) := i instance [i : Decidable (∀ a ∈ s, ∀ b ∈ s, a ≤ b → f b ≤ f a)] : Decidable (AntitoneOn f s) := i instance [i : Decidable (∀ a b, a < b → f a < f b)] : Decidable (StrictMono f) := i instance [i : Decidable (∀ a b, a < b → f b < f a)] : Decidable (StrictAnti f) := i instance [i : Decidable (∀ a ∈ s, ∀ b ∈ s, a < b → f a < f b)] : Decidable (StrictMonoOn f s) := i instance [i : Decidable (∀ a ∈ s, ∀ b ∈ s, a < b → f b < f a)] : Decidable (StrictAntiOn f s) := i end Decidable /-! ### Monotonicity in function spaces -/ section Preorder variable [Preorder α] theorem Monotone.comp_le_comp_left [Preorder β] {f : β → α} {g h : γ → β} (hf : Monotone f) (le_gh : g ≤ h) : LE.le.{max w u} (f ∘ g) (f ∘ h) := fun x ↦ hf (le_gh x) variable [Preorder γ] theorem monotone_lam {f : α → β → γ} (hf : ∀ b, Monotone fun a ↦ f a b) : Monotone f := fun _ _ h b ↦ hf b h theorem monotone_app (f : β → α → γ) (b : β) (hf : Monotone fun a b ↦ f b a) : Monotone (f b) := fun _ _ h ↦ hf h b theorem antitone_lam {f : α → β → γ} (hf : ∀ b, Antitone fun a ↦ f a b) : Antitone f := fun _ _ h b ↦ hf b h theorem antitone_app (f : β → α → γ) (b : β) (hf : Antitone fun a b ↦ f b a) : Antitone (f b) := fun _ _ h ↦ hf h b end Preorder theorem Function.monotone_eval {ι : Type u} {α : ι → Type v} [∀ i, Preorder (α i)] (i : ι) : Monotone (Function.eval i : (∀ i, α i) → α i) := fun _ _ H ↦ H i /-! ### Monotonicity hierarchy -/ section Preorder variable [Preorder α] section Preorder variable [Preorder β] {f : α → β} {a b : α} /-! These four lemmas are there to strip off the semi-implicit arguments `⦃a b : α⦄`. This is useful when you do not want to apply a `Monotone` assumption (i.e. your goal is `a ≤ b → f a ≤ f b`). However if you find yourself writing `hf.imp h`, then you should have written `hf h` instead. -/ theorem Monotone.imp (hf : Monotone f) (h : a ≤ b) : f a ≤ f b := hf h theorem Antitone.imp (hf : Antitone f) (h : a ≤ b) : f b ≤ f a := hf h theorem StrictMono.imp (hf : StrictMono f) (h : a < b) : f a < f b := hf h theorem StrictAnti.imp (hf : StrictAnti f) (h : a < b) : f b < f a := hf h protected theorem Monotone.monotoneOn (hf : Monotone f) (s : Set α) : MonotoneOn f s := fun _ _ _ _ ↦ hf.imp protected theorem Antitone.antitoneOn (hf : Antitone f) (s : Set α) : AntitoneOn f s := fun _ _ _ _ ↦ hf.imp @[simp] theorem monotoneOn_univ : MonotoneOn f Set.univ ↔ Monotone f := ⟨fun h _ _ ↦ h trivial trivial, fun h ↦ h.monotoneOn _⟩ @[simp] theorem antitoneOn_univ : AntitoneOn f Set.univ ↔ Antitone f := ⟨fun h _ _ ↦ h trivial trivial, fun h ↦ h.antitoneOn _⟩ protected theorem StrictMono.strictMonoOn (hf : StrictMono f) (s : Set α) : StrictMonoOn f s := fun _ _ _ _ ↦ hf.imp protected theorem StrictAnti.strictAntiOn (hf : StrictAnti f) (s : Set α) : StrictAntiOn f s := fun _ _ _ _ ↦ hf.imp @[simp] theorem strictMonoOn_univ : StrictMonoOn f Set.univ ↔ StrictMono f := ⟨fun h _ _ ↦ h trivial trivial, fun h ↦ h.strictMonoOn _⟩ @[simp] theorem strictAntiOn_univ : StrictAntiOn f Set.univ ↔ StrictAnti f := ⟨fun h _ _ ↦ h trivial trivial, fun h ↦ h.strictAntiOn _⟩ end Preorder section PartialOrder variable [PartialOrder β] {f : α → β} theorem Monotone.strictMono_of_injective (h₁ : Monotone f) (h₂ : Injective f) : StrictMono f := fun _ _ h ↦ (h₁ h.le).lt_of_ne fun H ↦ h.ne <| h₂ H theorem Antitone.strictAnti_of_injective (h₁ : Antitone f) (h₂ : Injective f) : StrictAnti f := fun _ _ h ↦ (h₁ h.le).lt_of_ne fun H ↦ h.ne <| h₂ H.symm end PartialOrder end Preorder section PartialOrder variable [PartialOrder α] [Preorder β] {f : α → β} {s : Set α} theorem monotone_iff_forall_lt : Monotone f ↔ ∀ ⦃a b⦄, a < b → f a ≤ f b := forall₂_congr fun _ _ ↦ ⟨fun hf h ↦ hf h.le, fun hf h ↦ h.eq_or_lt.elim (fun H ↦ (congr_arg _ H).le) hf⟩ theorem antitone_iff_forall_lt : Antitone f ↔ ∀ ⦃a b⦄, a < b → f b ≤ f a := forall₂_congr fun _ _ ↦ ⟨fun hf h ↦ hf h.le, fun hf h ↦ h.eq_or_lt.elim (fun H ↦ (congr_arg _ H).ge) hf⟩ theorem monotoneOn_iff_forall_lt : MonotoneOn f s ↔ ∀ ⦃a⦄ (_ : a ∈ s) ⦃b⦄ (_ : b ∈ s), a < b → f a ≤ f b := ⟨fun hf _ ha _ hb h ↦ hf ha hb h.le, fun hf _ ha _ hb h ↦ h.eq_or_lt.elim (fun H ↦ (congr_arg _ H).le) (hf ha hb)⟩ theorem antitoneOn_iff_forall_lt : AntitoneOn f s ↔ ∀ ⦃a⦄ (_ : a ∈ s) ⦃b⦄ (_ : b ∈ s), a < b → f b ≤ f a := ⟨fun hf _ ha _ hb h ↦ hf ha hb h.le, fun hf _ ha _ hb h ↦ h.eq_or_lt.elim (fun H ↦ (congr_arg _ H).ge) (hf ha hb)⟩ -- `Preorder α` isn't strong enough: if the preorder on `α` is an equivalence relation, -- then `StrictMono f` is vacuously true. protected theorem StrictMonoOn.monotoneOn (hf : StrictMonoOn f s) : MonotoneOn f s := monotoneOn_iff_forall_lt.2 fun _ ha _ hb h ↦ (hf ha hb h).le protected theorem StrictAntiOn.antitoneOn (hf : StrictAntiOn f s) : AntitoneOn f s := antitoneOn_iff_forall_lt.2 fun _ ha _ hb h ↦ (hf ha hb h).le protected theorem StrictMono.monotone (hf : StrictMono f) : Monotone f := monotone_iff_forall_lt.2 fun _ _ h ↦ (hf h).le protected theorem StrictAnti.antitone (hf : StrictAnti f) : Antitone f := antitone_iff_forall_lt.2 fun _ _ h ↦ (hf h).le end PartialOrder /-! ### Monotonicity from and to subsingletons -/ namespace Subsingleton variable [Preorder α] [Preorder β] protected theorem monotone [Subsingleton α] (f : α → β) : Monotone f := fun _ _ _ ↦ (congr_arg _ <| Subsingleton.elim _ _).le protected theorem antitone [Subsingleton α] (f : α → β) : Antitone f := fun _ _ _ ↦ (congr_arg _ <| Subsingleton.elim _ _).le theorem monotone' [Subsingleton β] (f : α → β) : Monotone f := fun _ _ _ ↦ (Subsingleton.elim _ _).le theorem antitone' [Subsingleton β] (f : α → β) : Antitone f := fun _ _ _ ↦ (Subsingleton.elim _ _).le protected theorem strictMono [Subsingleton α] (f : α → β) : StrictMono f := fun _ _ h ↦ (h.ne <| Subsingleton.elim _ _).elim protected theorem strictAnti [Subsingleton α] (f : α → β) : StrictAnti f := fun _ _ h ↦ (h.ne <| Subsingleton.elim _ _).elim end Subsingleton /-! ### Miscellaneous monotonicity results -/ theorem monotone_id [Preorder α] : Monotone (id : α → α) := fun _ _ ↦ id theorem monotoneOn_id [Preorder α] {s : Set α} : MonotoneOn id s := fun _ _ _ _ ↦ id theorem strictMono_id [Preorder α] : StrictMono (id : α → α) := fun _ _ ↦ id theorem strictMonoOn_id [Preorder α] {s : Set α} : StrictMonoOn id s := fun _ _ _ _ ↦ id theorem monotone_const [Preorder α] [Preorder β] {c : β} : Monotone fun _ : α ↦ c := fun _ _ _ ↦ le_rfl theorem monotoneOn_const [Preorder α] [Preorder β] {c : β} {s : Set α} : MonotoneOn (fun _ : α ↦ c) s := fun _ _ _ _ _ ↦ le_rfl theorem antitone_const [Preorder α] [Preorder β] {c : β} : Antitone fun _ : α ↦ c := fun _ _ _ ↦ le_refl c theorem antitoneOn_const [Preorder α] [Preorder β] {c : β} {s : Set α} : AntitoneOn (fun _ : α ↦ c) s := fun _ _ _ _ _ ↦ le_rfl theorem strictMono_of_le_iff_le [Preorder α] [Preorder β] {f : α → β} (h : ∀ x y, x ≤ y ↔ f x ≤ f y) : StrictMono f := fun _ _ ↦ (lt_iff_lt_of_le_iff_le' (h _ _) (h _ _)).1 theorem strictAnti_of_le_iff_le [Preorder α] [Preorder β] {f : α → β} (h : ∀ x y, x ≤ y ↔ f y ≤ f x) : StrictAnti f := fun _ _ ↦ (lt_iff_lt_of_le_iff_le' (h _ _) (h _ _)).1 theorem injective_of_lt_imp_ne [LinearOrder α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : Injective f := by intro x y hf rcases lt_trichotomy x y with (hxy | rfl | hxy) · exact absurd hf <| h _ _ hxy · rfl · exact absurd hf.symm <| h _ _ hxy theorem injective_of_le_imp_le [PartialOrder α] [Preorder β] (f : α → β) (h : ∀ {x y}, f x ≤ f y → x ≤ y) : Injective f := fun _ _ hxy ↦ (h hxy.le).antisymm (h hxy.ge) /-! ### Monotonicity under composition -/ section Composition variable [Preorder α] [Preorder β] [Preorder γ] {g : β → γ} {f : α → β} {s : Set α} {t : Set β} protected theorem Monotone.comp (hg : Monotone g) (hf : Monotone f) : Monotone (g ∘ f) := fun _ _ h ↦ hg (hf h) theorem Monotone.comp_antitone (hg : Monotone g) (hf : Antitone f) : Antitone (g ∘ f) := fun _ _ h ↦ hg (hf h) protected theorem Antitone.comp (hg : Antitone g) (hf : Antitone f) : Monotone (g ∘ f) := fun _ _ h ↦ hg (hf h) theorem Antitone.comp_monotone (hg : Antitone g) (hf : Monotone f) : Antitone (g ∘ f) := fun _ _ h ↦ hg (hf h) protected theorem Monotone.iterate {f : α → α} (hf : Monotone f) (n : ℕ) : Monotone f^[n] := Nat.recOn n monotone_id fun _ h ↦ h.comp hf protected theorem Monotone.comp_monotoneOn (hg : Monotone g) (hf : MonotoneOn f s) : MonotoneOn (g ∘ f) s := fun _ ha _ hb h ↦ hg (hf ha hb h) theorem Monotone.comp_antitoneOn (hg : Monotone g) (hf : AntitoneOn f s) : AntitoneOn (g ∘ f) s := fun _ ha _ hb h ↦ hg (hf ha hb h) protected theorem Antitone.comp_antitoneOn (hg : Antitone g) (hf : AntitoneOn f s) : MonotoneOn (g ∘ f) s := fun _ ha _ hb h ↦ hg (hf ha hb h) theorem Antitone.comp_monotoneOn (hg : Antitone g) (hf : MonotoneOn f s) : AntitoneOn (g ∘ f) s := fun _ ha _ hb h ↦ hg (hf ha hb h) protected theorem StrictMono.comp (hg : StrictMono g) (hf : StrictMono f) : StrictMono (g ∘ f) := fun _ _ h ↦ hg (hf h) theorem StrictMono.comp_strictAnti (hg : StrictMono g) (hf : StrictAnti f) : StrictAnti (g ∘ f) := fun _ _ h ↦ hg (hf h) protected theorem StrictAnti.comp (hg : StrictAnti g) (hf : StrictAnti f) : StrictMono (g ∘ f) := fun _ _ h ↦ hg (hf h) theorem StrictAnti.comp_strictMono (hg : StrictAnti g) (hf : StrictMono f) : StrictAnti (g ∘ f) := fun _ _ h ↦ hg (hf h) protected theorem StrictMono.iterate {f : α → α} (hf : StrictMono f) (n : ℕ) : StrictMono f^[n] := Nat.recOn n strictMono_id fun _ h ↦ h.comp hf protected theorem StrictMono.comp_strictMonoOn (hg : StrictMono g) (hf : StrictMonoOn f s) : StrictMonoOn (g ∘ f) s := fun _ ha _ hb h ↦ hg (hf ha hb h) theorem StrictMono.comp_strictAntiOn (hg : StrictMono g) (hf : StrictAntiOn f s) : StrictAntiOn (g ∘ f) s := fun _ ha _ hb h ↦ hg (hf ha hb h) protected theorem StrictAnti.comp_strictAntiOn (hg : StrictAnti g) (hf : StrictAntiOn f s) : StrictMonoOn (g ∘ f) s := fun _ ha _ hb h ↦ hg (hf ha hb h) theorem StrictAnti.comp_strictMonoOn (hg : StrictAnti g) (hf : StrictMonoOn f s) : StrictAntiOn (g ∘ f) s := fun _ ha _ hb h ↦ hg (hf ha hb h) lemma StrictMonoOn.comp (hg : StrictMonoOn g t) (hf : StrictMonoOn f s) (hs : Set.MapsTo f s t) : StrictMonoOn (g ∘ f) s := fun _x hx _y hy hxy ↦ hg (hs hx) (hs hy) <| hf hx hy hxy lemma StrictMonoOn.comp_strictAntiOn (hg : StrictMonoOn g t) (hf : StrictAntiOn f s) (hs : Set.MapsTo f s t) : StrictAntiOn (g ∘ f) s := fun _x hx _y hy hxy ↦ hg (hs hy) (hs hx) <| hf hx hy hxy lemma StrictAntiOn.comp (hg : StrictAntiOn g t) (hf : StrictAntiOn f s) (hs : Set.MapsTo f s t) : StrictMonoOn (g ∘ f) s := fun _x hx _y hy hxy ↦ hg (hs hy) (hs hx) <| hf hx hy hxy lemma StrictAntiOn.comp_strictMonoOn (hg : StrictAntiOn g t) (hf : StrictMonoOn f s) (hs : Set.MapsTo f s t) : StrictAntiOn (g ∘ f) s := fun _x hx _y hy hxy ↦ hg (hs hx) (hs hy) <| hf hx hy hxy end Composition /-! ### Monotonicity in linear orders -/ section LinearOrder variable [LinearOrder α] section Preorder variable [Preorder β] {f : α → β} {s : Set α} open Ordering theorem Monotone.reflect_lt (hf : Monotone f) {a b : α} (h : f a < f b) : a < b := lt_of_not_ge fun h' ↦ h.not_ge (hf h') theorem Antitone.reflect_lt (hf : Antitone f) {a b : α} (h : f a < f b) : b < a := lt_of_not_ge fun h' ↦ h.not_ge (hf h') theorem MonotoneOn.reflect_lt (hf : MonotoneOn f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) (h : f a < f b) : a < b := lt_of_not_ge fun h' ↦ h.not_ge <| hf hb ha h' theorem AntitoneOn.reflect_lt (hf : AntitoneOn f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) (h : f a < f b) : b < a := lt_of_not_ge fun h' ↦ h.not_ge <| hf ha hb h' end Preorder end LinearOrder theorem Subtype.mono_coe [Preorder α] (t : Set α) : Monotone ((↑) : Subtype t → α) := fun _ _ ↦ id theorem Subtype.strictMono_coe [Preorder α] (t : Set α) : StrictMono ((↑) : Subtype t → α) := fun _ _ ↦ id section Preorder variable [Preorder α] [Preorder β] [Preorder γ] [Preorder δ] {f : α → γ} {g : β → δ} theorem monotone_fst : Monotone (@Prod.fst α β) := fun _ _ ↦ And.left theorem monotone_snd : Monotone (@Prod.snd α β) := fun _ _ ↦ And.right theorem monotone_prodMk_iff {f : γ → α} {g : γ → β} : Monotone (fun x => (f x, g x)) ↔ Monotone f ∧ Monotone g := by simp_rw [Monotone, Prod.mk_le_mk, forall_and] theorem Monotone.prodMk {f : γ → α} {g : γ → β} (hf : Monotone f) (hg : Monotone g) : Monotone (fun x => (f x, g x)) := monotone_prodMk_iff.2 ⟨hf, hg⟩ theorem Monotone.prodMap (hf : Monotone f) (hg : Monotone g) : Monotone (Prod.map f g) := fun _ _ h ↦ ⟨hf h.1, hg h.2⟩ @[deprecated (since := "2025-04-18")] alias Monotone.prod_map := Monotone.prodMap theorem Antitone.prodMap (hf : Antitone f) (hg : Antitone g) : Antitone (Prod.map f g) := fun _ _ h ↦ ⟨hf h.1, hg h.2⟩ @[deprecated (since := "2025-04-18")] alias Antitone.prod_map := Antitone.prodMap lemma monotone_prod_iff {h : α × β → γ} : Monotone h ↔ (∀ a, Monotone (fun b => h (a, b))) ∧ (∀ b, Monotone (fun a => h (a, b))) where mp h := ⟨fun _ _ _ hab => h (Prod.mk_le_mk_iff_right.mpr hab), fun _ _ _ hab => h (Prod.mk_le_mk_iff_left.mpr hab)⟩ mpr h _ _ hab := le_trans (h.1 _ (Prod.mk_le_mk.mp hab).2) (h.2 _ (Prod.mk_le_mk.mp hab).1) lemma antitone_prod_iff {h : α × β → γ} : Antitone h ↔ (∀ a, Antitone (fun b => h (a, b))) ∧ (∀ b, Antitone (fun a => h (a, b))) where mp h := ⟨fun _ _ _ hab => h (Prod.mk_le_mk_iff_right.mpr hab), fun _ _ _ hab => h (Prod.mk_le_mk_iff_left.mpr hab)⟩ mpr h _ _ hab := le_trans (h.1 _ (Prod.mk_le_mk.mp hab).2) (h.2 _ (Prod.mk_le_mk.mp hab).1) end Preorder section PartialOrder variable [PartialOrder α] [PartialOrder β] [Preorder γ] [Preorder δ] {f : α → γ} {g : β → δ} theorem StrictMono.prodMap (hf : StrictMono f) (hg : StrictMono g) : StrictMono (Prod.map f g) := fun a b ↦ by simp only [Prod.lt_iff] exact Or.imp (And.imp hf.imp hg.monotone.imp) (And.imp hf.monotone.imp hg.imp) @[deprecated (since := "2025-04-18")] alias StrictMono.prod_map := StrictMono.prodMap theorem StrictAnti.prodMap (hf : StrictAnti f) (hg : StrictAnti g) : StrictAnti (Prod.map f g) := fun a b ↦ by simp only [Prod.lt_iff] exact Or.imp (And.imp hf.imp hg.antitone.imp) (And.imp hf.antitone.imp hg.imp) @[deprecated (since := "2025-04-18")] alias StrictAnti.prod_map := StrictAnti.prodMap end PartialOrder /-! ### Pi types -/ namespace Function variable [Preorder α] [DecidableEq ι] [∀ i, Preorder (π i)] {f : ∀ i, π i} {i : ι} -- Porting note: Dot notation breaks in `f.update i` theorem update_mono : Monotone (update f i) := fun _ _ => update_le_update_iff'.2 theorem update_strictMono : StrictMono (update f i) := fun _ _ => update_lt_update_iff.2 theorem const_mono : Monotone (const β : α → β → α) := fun _ _ h _ ↦ h theorem const_strictMono [Nonempty β] : StrictMono (const β : α → β → α) := fun _ _ ↦ const_lt_const.2 end Function section apply variable {β : ι → Type*} [∀ i, Preorder (β i)] [Preorder α] {f : α → ∀ i, β i} lemma monotone_iff_apply₂ : Monotone f ↔ ∀ i, Monotone (f · i) := by simp [Monotone, Pi.le_def, @forall_swap ι] lemma antitone_iff_apply₂ : Antitone f ↔ ∀ i, Antitone (f · i) := by simp [Antitone, Pi.le_def, @forall_swap ι] alias ⟨Monotone.apply₂, Monotone.of_apply₂⟩ := monotone_iff_apply₂ alias ⟨Antitone.apply₂, Antitone.of_apply₂⟩ := antitone_iff_apply₂ end apply
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).
Small.lean
/- Copyright (c) 2025 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, Maria-Inés de Frutos-Fernandez -/ import Mathlib.LinearAlgebra.Finsupp.LinearCombination import Mathlib.RingTheory.FiniteType import Mathlib.LinearAlgebra.DFinsupp import Mathlib.Algebra.Algebra.Subalgebra.Basic import Mathlib.LinearAlgebra.Basis.Cardinality import Mathlib.LinearAlgebra.StdBasis import Mathlib.RingTheory.Finiteness.Basic import Mathlib.RingTheory.MvPolynomial.Basic import Mathlib.Data.DFinsupp.Small /-! # Smallness properties of modules and algebras -/ universe u namespace Submodule variable {R M : Type*} [Semiring R] [AddCommMonoid M] [Module R M] instance small_sup {P Q : Submodule R M} [smallP : Small.{u} P] [smallQ : Small.{u} Q] : Small.{u} (P ⊔ Q : Submodule R M) := by rw [Submodule.sup_eq_range] exact small_range _ instance : SemilatticeSup {P : Submodule R M // Small.{u} P} where sup := fun P Q ↦ ⟨P.val ⊔ Q.val, small_sup (smallP := P.property) (smallQ := Q.property)⟩ le_sup_left := fun P Q ↦ by rw [← Subtype.coe_le_coe]; exact le_sup_left le_sup_right := fun P Q ↦ by rw [← Subtype.coe_le_coe]; exact le_sup_right sup_le := fun _ _ _ hPR hQR ↦ by rw [← Subtype.coe_le_coe] at hPR hQR ⊢ exact sup_le hPR hQR instance : Inhabited {P : Submodule R M // Small.{u} P} where default := ⟨⊥, inferInstance⟩ instance small_iSup {ι : Type*} {P : ι → Submodule R M} [Small.{u} ι] [∀ i, Small.{u} (P i)] : Small.{u} (iSup P : Submodule R M) := by classical rw [iSup_eq_range_dfinsupp_lsum] apply small_range theorem FG.small [Small.{u} R] (P : Submodule R M) (hP : P.FG) : Small.{u} P := by rw [fg_iff_exists_fin_generating_family] at hP obtain ⟨n, s, rfl⟩ := hP rw [← Fintype.range_linearCombination] apply small_range variable (R M) in theorem _root_.Module.Finite.small [Small.{u} R] [Module.Finite R M] : Small.{u} M := by have : Small.{u} (⊤ : Submodule R M) := FG.small _ (Module.finite_def.mp inferInstance) rwa [← small_univ_iff] instance small_span_singleton [Small.{u} R] (m : M) : Small.{u} (span R {m}) := FG.small _ (fg_span_singleton _) theorem small_span [Small.{u} R] (s : Set M) [Small.{u} s] : Small.{u} (span R s) := by suffices span R s = iSup (fun i : s ↦ span R ({(↑i : M)} : Set M)) by rw [this] apply small_iSup simp [← Submodule.span_iUnion] end Submodule variable {R S : Type*} [CommSemiring R] [CommSemiring S] [Algebra R S] namespace Algebra open MvPolynomial AlgHom instance small_adjoin [Small.{u} R] {s : Set S} [Small.{u} s] : Small.{u} (adjoin R s : Subalgebra R S) := by rw [Algebra.adjoin_eq_range] apply small_range theorem _root_.Subalgebra.FG.small [Small.{u} R] {A : Subalgebra R S} (fgS : A.FG) : Small.{u} A := by obtain ⟨s, hs, rfl⟩ := fgS exact small_adjoin theorem FiniteType.small [Small.{u} R] [Algebra.FiniteType R S] : Small.{u} S := by have : Small.{u} (⊤ : Subalgebra R S) := Subalgebra.FG.small Algebra.FiniteType.out rwa [← small_univ_iff] end Algebra
NoncommPiCoprod.lean
/- Copyright (c) 2022 Joachim Breitner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joachim Breitner -/ import Mathlib.GroupTheory.OrderOfElement import Mathlib.Data.Nat.GCD.BigOperators import Mathlib.Order.SupIndep /-! # Canonical homomorphism from a finite family of monoids This file defines the construction of the canonical homomorphism from a family of monoids. Given a family of morphisms `ϕ i : N i →* M` for each `i : ι` where elements in the images of different morphisms commute, we obtain a canonical morphism `MonoidHom.noncommPiCoprod : (Π i, N i) →* M` that coincides with `ϕ` ## Main definitions * `MonoidHom.noncommPiCoprod : (Π i, N i) →* M` is the main homomorphism * `Subgroup.noncommPiCoprod : (Π i, H i) →* G` is the specialization to `H i : Subgroup G` and the subgroup embedding. ## Main theorems * `MonoidHom.noncommPiCoprod` coincides with `ϕ i` when restricted to `N i` * `MonoidHom.noncommPiCoprod_mrange`: The range of `MonoidHom.noncommPiCoprod` is `⨆ (i : ι), (ϕ i).mrange` * `MonoidHom.noncommPiCoprod_range`: The range of `MonoidHom.noncommPiCoprod` is `⨆ (i : ι), (ϕ i).range` * `Subgroup.noncommPiCoprod_range`: The range of `Subgroup.noncommPiCoprod` is `⨆ (i : ι), H i`. * `MonoidHom.injective_noncommPiCoprod_of_iSupIndep`: in the case of groups, `pi_hom.hom` is injective if the `ϕ` are injective and the ranges of the `ϕ` are independent. * `MonoidHom.independent_range_of_coprime_order`: If the `N i` have coprime orders, then the ranges of the `ϕ` are independent. * `Subgroup.independent_of_coprime_order`: If commuting normal subgroups `H i` have coprime orders, they are independent. -/ assert_not_exists Field namespace Subgroup variable {G : Type*} [Group G] /-- `Finset.noncommProd` is “injective” in `f` if `f` maps into independent subgroups. This generalizes (one direction of) `Subgroup.disjoint_iff_mul_eq_one`. -/ @[to_additive /-- `Finset.noncommSum` is “injective” in `f` if `f` maps into independent subgroups. This generalizes (one direction of) `AddSubgroup.disjoint_iff_add_eq_zero`. -/] theorem eq_one_of_noncommProd_eq_one_of_iSupIndep {ι : Type*} (s : Finset ι) (f : ι → G) (comm) (K : ι → Subgroup G) (hind : iSupIndep K) (hmem : ∀ x ∈ s, f x ∈ K x) (heq1 : s.noncommProd f comm = 1) : ∀ i ∈ s, f i = 1 := by classical revert heq1 induction s using Finset.induction_on with | empty => simp | insert i s hnotMem ih => have hcomm := comm.mono (Finset.coe_subset.2 <| Finset.subset_insert _ _) simp only [Finset.forall_mem_insert] at hmem have hmem_bsupr : s.noncommProd f hcomm ∈ ⨆ i ∈ (s : Set ι), K i := by refine Subgroup.noncommProd_mem _ _ ?_ intro x hx have : K x ≤ ⨆ i ∈ (s : Set ι), K i := le_iSup₂ (f := fun i _ => K i) x hx exact this (hmem.2 x hx) intro heq1 rw [Finset.noncommProd_insert_of_notMem _ _ _ _ hnotMem] at heq1 have hnotMem' : i ∉ (s : Set ι) := by simpa obtain ⟨heq1i : f i = 1, heq1S : s.noncommProd f _ = 1⟩ := Subgroup.disjoint_iff_mul_eq_one.mp (hind.disjoint_biSup hnotMem') hmem.1 hmem_bsupr heq1 intro i h simp only [Finset.mem_insert] at h rcases h with (rfl | h) · exact heq1i · refine ih hcomm hmem.2 heq1S _ h end Subgroup section FamilyOfMonoids variable {M : Type*} [Monoid M] -- We have a family of monoids -- The fintype assumption is not always used, but declared here, to keep things in order variable {ι : Type*} [Fintype ι] variable {N : ι → Type*} [∀ i, Monoid (N i)] -- And morphisms ϕ into G variable (ϕ : ∀ i : ι, N i →* M) -- We assume that the elements of different morphism commute variable (hcomm : Pairwise fun i j => ∀ x y, Commute (ϕ i x) (ϕ j y)) namespace MonoidHom /-- The canonical homomorphism from a family of monoids. -/ @[to_additive /-- The canonical homomorphism from a family of additive monoids. See also `LinearMap.lsum` for a linear version without the commutativity assumption. -/] def noncommPiCoprod : (∀ i : ι, N i) →* M where toFun f := Finset.univ.noncommProd (fun i => ϕ i (f i)) fun _ _ _ _ h => hcomm h _ _ map_one' := by apply (Finset.noncommProd_eq_pow_card _ _ _ _ _).trans (one_pow _) simp map_mul' f g := by classical convert @Finset.noncommProd_mul_distrib _ _ _ _ (fun i => ϕ i (f i)) (fun i => ϕ i (g i)) _ _ _ · exact map_mul _ _ _ · rintro i - j - h exact hcomm h _ _ variable {hcomm} @[to_additive (attr := simp)] theorem noncommPiCoprod_mulSingle [DecidableEq ι] (i : ι) (y : N i) : noncommPiCoprod ϕ hcomm (Pi.mulSingle i y) = ϕ i y := by change Finset.univ.noncommProd (fun j => ϕ j (Pi.mulSingle i y j)) (fun _ _ _ _ h => hcomm h _ _) = ϕ i y rw [← Finset.insert_erase (Finset.mem_univ i)] rw [Finset.noncommProd_insert_of_notMem _ _ _ _ (Finset.notMem_erase i _)] rw [Pi.mulSingle_eq_same] rw [Finset.noncommProd_eq_pow_card] · rw [one_pow] exact mul_one _ · intro j hj simp only [Finset.mem_erase] at hj simp [hj] /-- The universal property of `MonoidHom.noncommPiCoprod` Given monoid morphisms `φᵢ : Nᵢ → M` whose images pairwise commute, there exists a unique monoid morphism `φ : Πᵢ Nᵢ → M` that induces the `φᵢ`, and it is given by `MonoidHom.noncommPiCoprod`. -/ @[to_additive /-- The universal property of `MonoidHom.noncommPiCoprod` Given monoid morphisms `φᵢ : Nᵢ → M` whose images pairwise commute, there exists a unique monoid morphism `φ : Πᵢ Nᵢ → M` that induces the `φᵢ`, and it is given by `AddMonoidHom.noncommPiCoprod`. -/] def noncommPiCoprodEquiv [DecidableEq ι] : { ϕ : ∀ i, N i →* M // Pairwise fun i j => ∀ x y, Commute (ϕ i x) (ϕ j y) } ≃ ((∀ i, N i) →* M) where toFun ϕ := noncommPiCoprod ϕ.1 ϕ.2 invFun f := ⟨fun i => f.comp (MonoidHom.mulSingle N i), fun _ _ hij x y => Commute.map (Pi.mulSingle_commute hij x y) f⟩ left_inv ϕ := by ext simp only [coe_comp, Function.comp_apply, mulSingle_apply, noncommPiCoprod_mulSingle] right_inv f := pi_ext fun i x => by simp only [noncommPiCoprod_mulSingle, coe_comp, Function.comp_apply, mulSingle_apply] @[to_additive] theorem noncommPiCoprod_mrange : MonoidHom.mrange (noncommPiCoprod ϕ hcomm) = ⨆ i : ι, MonoidHom.mrange (ϕ i) := by letI := Classical.decEq ι apply le_antisymm · rintro x ⟨f, rfl⟩ refine Submonoid.noncommProd_mem _ _ _ (fun _ _ _ _ h => hcomm h _ _) (fun i _ => ?_) apply Submonoid.mem_sSup_of_mem · use i simp · refine iSup_le ?_ rintro i x ⟨y, rfl⟩ exact ⟨Pi.mulSingle i y, noncommPiCoprod_mulSingle _ _ _⟩ @[to_additive] lemma commute_noncommPiCoprod {m : M} (comm : ∀ i (x : N i), Commute m ((ϕ i x))) (h : (i : ι) → N i) : Commute m (MonoidHom.noncommPiCoprod ϕ hcomm h) := by dsimp only [MonoidHom.noncommPiCoprod, MonoidHom.coe_mk, OneHom.coe_mk] apply Finset.noncommProd_induction · exact fun x y ↦ Commute.mul_right · exact Commute.one_right _ · exact fun x _ ↦ comm x (h x) @[to_additive] lemma noncommPiCoprod_apply (h : (i : ι) → N i) : MonoidHom.noncommPiCoprod ϕ hcomm h = Finset.noncommProd Finset.univ (fun i ↦ ϕ i (h i)) (Pairwise.set_pairwise (fun ⦃i j⦄ a ↦ hcomm a (h i) (h j)) _) := by dsimp only [MonoidHom.noncommPiCoprod, MonoidHom.coe_mk, OneHom.coe_mk] /-- Given monoid morphisms `φᵢ : Nᵢ → M` and `f : M → P`, if we have sufficient commutativity, then `f ∘ (∐ᵢ φᵢ) = ∐ᵢ (f ∘ φᵢ)` -/ @[to_additive] theorem comp_noncommPiCoprod {P : Type*} [Monoid P] {f : M →* P} (hcomm' : Pairwise fun i j => ∀ x y, Commute (f.comp (ϕ i) x) (f.comp (ϕ j) y) := Pairwise.mono hcomm (fun i j ↦ forall_imp (fun x h y ↦ by simp only [MonoidHom.coe_comp, Function.comp_apply, Commute.map (h y) f]))) : f.comp (MonoidHom.noncommPiCoprod ϕ hcomm) = MonoidHom.noncommPiCoprod (fun i ↦ f.comp (ϕ i)) hcomm' := MonoidHom.ext fun _ ↦ by simp only [MonoidHom.noncommPiCoprod, MonoidHom.coe_comp, MonoidHom.coe_mk, OneHom.coe_mk, Function.comp_apply, Finset.map_noncommProd] end MonoidHom end FamilyOfMonoids section FamilyOfGroups variable {G : Type*} [Group G] variable {ι : Type*} variable {H : ι → Type*} [∀ i, Group (H i)] variable (ϕ : ∀ i : ι, H i →* G) namespace MonoidHom -- The subgroup version of `MonoidHom.noncommPiCoprod_mrange` @[to_additive] theorem noncommPiCoprod_range [Fintype ι] {hcomm : Pairwise fun i j : ι => ∀ (x : H i) (y : H j), Commute (ϕ i x) (ϕ j y)} : (noncommPiCoprod ϕ hcomm).range = ⨆ i : ι, (ϕ i).range := by letI := Classical.decEq ι apply le_antisymm · rintro x ⟨f, rfl⟩ refine Subgroup.noncommProd_mem _ (fun _ _ _ _ h => hcomm h _ _) ?_ intro i _hi apply Subgroup.mem_sSup_of_mem · use i simp · refine iSup_le ?_ rintro i x ⟨y, rfl⟩ exact ⟨Pi.mulSingle i y, noncommPiCoprod_mulSingle _ _ _⟩ @[to_additive] theorem injective_noncommPiCoprod_of_iSupIndep [Fintype ι] {hcomm : Pairwise fun i j : ι => ∀ (x : H i) (y : H j), Commute (ϕ i x) (ϕ j y)} (hind : iSupIndep fun i => (ϕ i).range) (hinj : ∀ i, Function.Injective (ϕ i)) : Function.Injective (noncommPiCoprod ϕ hcomm) := by classical apply (MonoidHom.ker_eq_bot_iff _).mp rw [eq_bot_iff] intro f heq1 have : ∀ i, i ∈ Finset.univ → ϕ i (f i) = 1 := Subgroup.eq_one_of_noncommProd_eq_one_of_iSupIndep _ _ (fun _ _ _ _ h => hcomm h _ _) _ hind (by simp) heq1 ext i apply hinj simp [this i (Finset.mem_univ i)] @[to_additive] theorem independent_range_of_coprime_order (hcomm : Pairwise fun i j : ι => ∀ (x : H i) (y : H j), Commute (ϕ i x) (ϕ j y)) [Finite ι] [∀ i, Fintype (H i)] (hcoprime : Pairwise fun i j => Nat.Coprime (Fintype.card (H i)) (Fintype.card (H j))) : iSupIndep fun i => (ϕ i).range := by cases nonempty_fintype ι letI := Classical.decEq ι rintro i rw [disjoint_iff_inf_le] rintro f ⟨hxi, hxp⟩ dsimp at hxi hxp rw [iSup_subtype', ← noncommPiCoprod_range] at hxp rotate_left · intro _ _ hj apply hcomm exact hj ∘ Subtype.ext obtain ⟨g, hgf⟩ := hxp obtain ⟨g', hg'f⟩ := hxi have hxi : orderOf f ∣ Fintype.card (H i) := by rw [← hg'f] exact (orderOf_map_dvd _ _).trans orderOf_dvd_card have hxp : orderOf f ∣ ∏ j : { j // j ≠ i }, Fintype.card (H j) := by rw [← hgf, ← Fintype.card_pi] exact (orderOf_map_dvd _ _).trans orderOf_dvd_card change f = 1 rw [← pow_one f, ← orderOf_dvd_iff_pow_eq_one] obtain ⟨c, hc⟩ := Nat.dvd_gcd hxp hxi use c rw [← hc] symm rw [← Nat.coprime_iff_gcd_eq_one, Nat.coprime_fintype_prod_left_iff, Subtype.forall] intro j h exact hcoprime h end MonoidHom end FamilyOfGroups namespace Subgroup -- We have a family of subgroups variable {G : Type*} [Group G] variable {ι : Type*} {H : ι → Subgroup G} section CommutingSubgroups -- We assume that the elements of different subgroups commute -- with `hcomm : Pairwise fun i j : ι => ∀ x y : G, x ∈ H i → y ∈ H j → Commute x y` @[to_additive] theorem commute_subtype_of_commute (hcomm : Pairwise fun i j : ι => ∀ x y : G, x ∈ H i → y ∈ H j → Commute x y) (i j : ι) (hne : i ≠ j) : ∀ (x : H i) (y : H j), Commute ((H i).subtype x) ((H j).subtype y) := by rintro ⟨x, hx⟩ ⟨y, hy⟩ exact hcomm hne x y hx hy @[to_additive] theorem independent_of_coprime_order (hcomm : Pairwise fun i j : ι => ∀ x y : G, x ∈ H i → y ∈ H j → Commute x y) [Finite ι] [∀ i, Fintype (H i)] (hcoprime : Pairwise fun i j => Nat.Coprime (Fintype.card (H i)) (Fintype.card (H j))) : iSupIndep H := by simpa using MonoidHom.independent_range_of_coprime_order (fun i => (H i).subtype) (commute_subtype_of_commute hcomm) hcoprime variable [Fintype ι] /-- The canonical homomorphism from a family of subgroups where elements from different subgroups commute -/ @[to_additive /-- The canonical homomorphism from a family of additive subgroups where elements from different subgroups commute -/] def noncommPiCoprod (hcomm : Pairwise fun i j : ι => ∀ x y : G, x ∈ H i → y ∈ H j → Commute x y) : (∀ i : ι, H i) →* G := MonoidHom.noncommPiCoprod (fun i => (H i).subtype) (commute_subtype_of_commute hcomm) @[to_additive (attr := simp)] theorem noncommPiCoprod_mulSingle [DecidableEq ι] {hcomm : Pairwise fun i j : ι => ∀ x y : G, x ∈ H i → y ∈ H j → Commute x y}(i : ι) (y : H i) : noncommPiCoprod hcomm (Pi.mulSingle i y) = y := by apply MonoidHom.noncommPiCoprod_mulSingle @[to_additive] theorem noncommPiCoprod_range {hcomm : Pairwise fun i j : ι => ∀ x y : G, x ∈ H i → y ∈ H j → Commute x y} : (noncommPiCoprod hcomm).range = ⨆ i : ι, H i := by simp [noncommPiCoprod, MonoidHom.noncommPiCoprod_range] @[to_additive] theorem injective_noncommPiCoprod_of_iSupIndep {hcomm : Pairwise fun i j : ι => ∀ x y : G, x ∈ H i → y ∈ H j → Commute x y} (hind : iSupIndep H) : Function.Injective (noncommPiCoprod hcomm) := by apply MonoidHom.injective_noncommPiCoprod_of_iSupIndep · simpa using hind · intro i exact Subtype.coe_injective @[to_additive] theorem noncommPiCoprod_apply (comm) (u : (i : ι) → H i) : Subgroup.noncommPiCoprod comm u = Finset.noncommProd Finset.univ (fun i ↦ u i) (fun i _ j _ h ↦ comm h _ _ (u i).prop (u j).prop) := by simp only [Subgroup.noncommPiCoprod, MonoidHom.noncommPiCoprod, coe_subtype, MonoidHom.coe_mk, OneHom.coe_mk] end CommutingSubgroups end Subgroup
Lattice.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.Data.Fintype.Lattice import Mathlib.RingTheory.Finiteness.Basic /-! # Finite suprema of finite modules -/ namespace Submodule open Module variable {R V} [Ring R] [AddCommGroup V] [Module R V] /-- The submodule generated by a supremum of finite dimensional submodules, indexed by a finite sort is finite-dimensional. -/ instance finite_iSup {ι : Sort*} [Finite ι] (S : ι → Submodule R V) [∀ i, Module.Finite R (S i)] : Module.Finite R ↑(⨆ i, S i) := by cases nonempty_fintype (PLift ι) rw [← iSup_plift_down, ← Finset.sup_univ_eq_iSup] exact Submodule.finite_finset_sup _ _ end Submodule
FloorPow.lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Algebra.Order.Field.GeomSum import Mathlib.Analysis.SpecificLimits.Basic import Mathlib.Analysis.SpecialFunctions.Pow.Real /-! # Results on discretized exponentials We state several auxiliary results pertaining to sequences of the form `⌊c^n⌋₊`. * `tendsto_div_of_monotone_of_tendsto_div_floor_pow`: If a monotone sequence `u` is such that `u ⌊c^n⌋₊ / ⌊c^n⌋₊` converges to a limit `l` for all `c > 1`, then `u n / n` tends to `l`. * `sum_div_nat_floor_pow_sq_le_div_sq`: The sum of `1/⌊c^i⌋₊^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative constant. -/ open Filter Finset open Topology /-- If a monotone sequence `u` is such that `u n / n` tends to a limit `l` along subsequences with exponential growth rate arbitrarily close to `1`, then `u n / n` tends to `l`. -/ theorem tendsto_div_of_monotone_of_exists_subseq_tendsto_div (u : ℕ → ℝ) (l : ℝ) (hmono : Monotone u) (hlim : ∀ a : ℝ, 1 < a → ∃ c : ℕ → ℕ, (∀ᶠ n in atTop, (c (n + 1) : ℝ) ≤ a * c n) ∧ Tendsto c atTop atTop ∧ Tendsto (fun n => u (c n) / c n) atTop (𝓝 l)) : Tendsto (fun n => u n / n) atTop (𝓝 l) := by /- To check the result up to some `ε > 0`, we use a sequence `c` for which the ratio `c (N+1) / c N` is bounded by `1 + ε`. Sandwiching a given `n` between two consecutive values of `c`, say `c N` and `c (N+1)`, one can then bound `u n / n` from above by `u (c N) / c (N - 1)` and from below by `u (c (N - 1)) / c N` (using that `u` is monotone), which are both comparable to the limit `l` up to `1 + ε`. We give a version of this proof by clearing out denominators first, to avoid discussing the sign of different quantities. -/ have lnonneg : 0 ≤ l := by rcases hlim 2 one_lt_two with ⟨c, _, ctop, clim⟩ have : Tendsto (fun n => u 0 / c n) atTop (𝓝 0) := tendsto_const_nhds.div_atTop (tendsto_natCast_atTop_iff.2 ctop) apply le_of_tendsto_of_tendsto' this clim fun n => ?_ gcongr exact hmono (zero_le _) have A : ∀ ε : ℝ, 0 < ε → ∀ᶠ n in atTop, u n - n * l ≤ ε * (1 + ε + l) * n := by intro ε εpos rcases hlim (1 + ε) ((lt_add_iff_pos_right _).2 εpos) with ⟨c, cgrowth, ctop, clim⟩ have L : ∀ᶠ n in atTop, u (c n) - c n * l ≤ ε * c n := by rw [← tendsto_sub_nhds_zero_iff, ← Asymptotics.isLittleO_one_iff ℝ, Asymptotics.isLittleO_iff] at clim filter_upwards [clim εpos, ctop (Ioi_mem_atTop 0)] with n hn cnpos' have cnpos : 0 < c n := cnpos' calc u (c n) - c n * l = (u (c n) / c n - l) * c n := by simp only [cnpos.ne', Ne, Nat.cast_eq_zero, not_false_iff, field_simps] _ ≤ ε * c n := by gcongr refine (le_abs_self _).trans ?_ simpa using hn obtain ⟨a, ha⟩ : ∃ a : ℕ, ∀ b : ℕ, a ≤ b → (c (b + 1) : ℝ) ≤ (1 + ε) * c b ∧ u (c b) - c b * l ≤ ε * c b := eventually_atTop.1 (cgrowth.and L) let M := ((Finset.range (a + 1)).image fun i => c i).max' (by simp) filter_upwards [Ici_mem_atTop M] with n hn have exN : ∃ N, n < c N := by rcases (tendsto_atTop.1 ctop (n + 1)).exists with ⟨N, hN⟩ exact ⟨N, by omega⟩ let N := Nat.find exN have ncN : n < c N := Nat.find_spec exN have aN : a + 1 ≤ N := by by_contra! h have cNM : c N ≤ M := by apply le_max' apply mem_image_of_mem exact mem_range.2 h exact lt_irrefl _ ((cNM.trans hn).trans_lt ncN) have Npos : 0 < N := lt_of_lt_of_le Nat.succ_pos' aN have cNn : c (N - 1) ≤ n := by have : N - 1 < N := Nat.pred_lt Npos.ne' simpa only [not_lt] using Nat.find_min exN this have IcN : (c N : ℝ) ≤ (1 + ε) * c (N - 1) := by have A : a ≤ N - 1 := by apply @Nat.le_of_add_le_add_right a 1 (N - 1) rw [Nat.sub_add_cancel Npos] exact aN have B : N - 1 + 1 = N := Nat.succ_pred_eq_of_pos Npos have := (ha _ A).1 rwa [B] at this calc u n - n * l ≤ u (c N) - c (N - 1) * l := by gcongr; exact hmono ncN.le _ = u (c N) - c N * l + (c N - c (N - 1)) * l := by ring _ ≤ ε * c N + ε * c (N - 1) * l := by gcongr · exact (ha N (a.le_succ.trans aN)).2 · linarith only [IcN] _ ≤ ε * ((1 + ε) * c (N - 1)) + ε * c (N - 1) * l := by gcongr _ = ε * (1 + ε + l) * c (N - 1) := by ring _ ≤ ε * (1 + ε + l) * n := by gcongr have B : ∀ ε : ℝ, 0 < ε → ∀ᶠ n : ℕ in atTop, (n : ℝ) * l - u n ≤ ε * (1 + l) * n := by intro ε εpos rcases hlim (1 + ε) ((lt_add_iff_pos_right _).2 εpos) with ⟨c, cgrowth, ctop, clim⟩ have L : ∀ᶠ n : ℕ in atTop, (c n : ℝ) * l - u (c n) ≤ ε * c n := by rw [← tendsto_sub_nhds_zero_iff, ← Asymptotics.isLittleO_one_iff ℝ, Asymptotics.isLittleO_iff] at clim filter_upwards [clim εpos, ctop (Ioi_mem_atTop 0)] with n hn cnpos' have cnpos : 0 < c n := cnpos' calc (c n : ℝ) * l - u (c n) = -(u (c n) / c n - l) * c n := by simp only [cnpos.ne', Ne, Nat.cast_eq_zero, not_false_iff, neg_sub, field_simps] _ ≤ ε * c n := by gcongr refine le_trans (neg_le_abs _) ?_ simpa using hn obtain ⟨a, ha⟩ : ∃ a : ℕ, ∀ b : ℕ, a ≤ b → (c (b + 1) : ℝ) ≤ (1 + ε) * c b ∧ (c b : ℝ) * l - u (c b) ≤ ε * c b := eventually_atTop.1 (cgrowth.and L) let M := ((Finset.range (a + 1)).image fun i => c i).max' (by simp) filter_upwards [Ici_mem_atTop M] with n hn have exN : ∃ N, n < c N := by rcases (tendsto_atTop.1 ctop (n + 1)).exists with ⟨N, hN⟩ exact ⟨N, by omega⟩ let N := Nat.find exN have ncN : n < c N := Nat.find_spec exN have aN : a + 1 ≤ N := by by_contra! h have cNM : c N ≤ M := by apply le_max' apply mem_image_of_mem exact mem_range.2 h exact lt_irrefl _ ((cNM.trans hn).trans_lt ncN) have Npos : 0 < N := lt_of_lt_of_le Nat.succ_pos' aN have aN' : a ≤ N - 1 := by apply @Nat.le_of_add_le_add_right a 1 (N - 1) rw [Nat.sub_add_cancel Npos] exact aN have cNn : c (N - 1) ≤ n := by have : N - 1 < N := Nat.pred_lt Npos.ne' simpa only [not_lt] using Nat.find_min exN this calc (n : ℝ) * l - u n ≤ c N * l - u (c (N - 1)) := by gcongr exact hmono cNn _ ≤ (1 + ε) * c (N - 1) * l - u (c (N - 1)) := by gcongr have B : N - 1 + 1 = N := Nat.succ_pred_eq_of_pos Npos simpa [B] using (ha _ aN').1 _ = c (N - 1) * l - u (c (N - 1)) + ε * c (N - 1) * l := by ring _ ≤ ε * c (N - 1) + ε * c (N - 1) * l := add_le_add (ha _ aN').2 le_rfl _ = ε * (1 + l) * c (N - 1) := by ring _ ≤ ε * (1 + l) * n := by gcongr refine tendsto_order.2 ⟨fun d hd => ?_, fun d hd => ?_⟩ · obtain ⟨ε, hε, εpos⟩ : ∃ ε : ℝ, d + ε * (1 + l) < l ∧ 0 < ε := by have L : Tendsto (fun ε => d + ε * (1 + l)) (𝓝[>] 0) (𝓝 (d + 0 * (1 + l))) := by apply Tendsto.mono_left _ nhdsWithin_le_nhds exact tendsto_const_nhds.add (tendsto_id.mul tendsto_const_nhds) simp only [zero_mul, add_zero] at L exact (((tendsto_order.1 L).2 l hd).and self_mem_nhdsWithin).exists filter_upwards [B ε εpos, Ioi_mem_atTop 0] with n hn npos simp_rw [div_eq_inv_mul] calc d < (n : ℝ)⁻¹ * n * (l - ε * (1 + l)) := by rw [inv_mul_cancel₀, one_mul] · linarith only [hε] · exact Nat.cast_ne_zero.2 (ne_of_gt npos) _ = (n : ℝ)⁻¹ * (n * l - ε * (1 + l) * n) := by ring _ ≤ (n : ℝ)⁻¹ * u n := by gcongr; linarith only [hn] · obtain ⟨ε, hε, εpos⟩ : ∃ ε : ℝ, l + ε * (1 + ε + l) < d ∧ 0 < ε := by have L : Tendsto (fun ε => l + ε * (1 + ε + l)) (𝓝[>] 0) (𝓝 (l + 0 * (1 + 0 + l))) := by apply Tendsto.mono_left _ nhdsWithin_le_nhds exact tendsto_const_nhds.add (tendsto_id.mul ((tendsto_const_nhds.add tendsto_id).add tendsto_const_nhds)) simp only [zero_mul, add_zero] at L exact (((tendsto_order.1 L).2 d hd).and self_mem_nhdsWithin).exists filter_upwards [A ε εpos, Ioi_mem_atTop 0] with n hn (npos : 0 < n) calc u n / n ≤ (n * l + ε * (1 + ε + l) * n) / n := by gcongr; linarith only [hn] _ = (l + ε * (1 + ε + l)) := by field_simp; ring _ < d := hε /-- If a monotone sequence `u` is such that `u ⌊c^n⌋₊ / ⌊c^n⌋₊` converges to a limit `l` for all `c > 1`, then `u n / n` tends to `l`. It is even enough to have the assumption for a sequence of `c`s converging to `1`. -/ theorem tendsto_div_of_monotone_of_tendsto_div_floor_pow (u : ℕ → ℝ) (l : ℝ) (hmono : Monotone u) (c : ℕ → ℝ) (cone : ∀ k, 1 < c k) (clim : Tendsto c atTop (𝓝 1)) (hc : ∀ k, Tendsto (fun n : ℕ => u ⌊c k ^ n⌋₊ / ⌊c k ^ n⌋₊) atTop (𝓝 l)) : Tendsto (fun n => u n / n) atTop (𝓝 l) := by apply tendsto_div_of_monotone_of_exists_subseq_tendsto_div u l hmono intro a ha obtain ⟨k, hk⟩ : ∃ k, c k < a := ((tendsto_order.1 clim).2 a ha).exists refine ⟨fun n => ⌊c k ^ n⌋₊, ?_, (tendsto_nat_floor_atTop (α := ℝ)).comp (tendsto_pow_atTop_atTop_of_one_lt (cone k)), hc k⟩ have H : ∀ n : ℕ, (0 : ℝ) < ⌊c k ^ n⌋₊ := by intro n refine zero_lt_one.trans_le ?_ simp only [Nat.one_le_cast, Nat.one_le_floor_iff, one_le_pow₀ (cone k).le] have A : Tendsto (fun n : ℕ => (⌊c k ^ (n + 1)⌋₊ : ℝ) / c k ^ (n + 1) * c k / (⌊c k ^ n⌋₊ / c k ^ n)) atTop (𝓝 (1 * c k / 1)) := by refine Tendsto.div (Tendsto.mul ?_ tendsto_const_nhds) ?_ one_ne_zero · refine tendsto_nat_floor_div_atTop.comp ?_ exact (tendsto_pow_atTop_atTop_of_one_lt (cone k)).comp (tendsto_add_atTop_nat 1) · refine tendsto_nat_floor_div_atTop.comp ?_ exact tendsto_pow_atTop_atTop_of_one_lt (cone k) have B : Tendsto (fun n : ℕ => (⌊c k ^ (n + 1)⌋₊ : ℝ) / ⌊c k ^ n⌋₊) atTop (𝓝 (c k)) := by simp only [one_mul, div_one] at A convert A using 1 ext1 n field_simp [(zero_lt_one.trans (cone k)).ne', (H n).ne'] ring filter_upwards [(tendsto_order.1 B).2 a hk] with n hn exact (div_le_iff₀ (H n)).1 hn.le /-- The sum of `1/(c^i)^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative constant. -/ theorem sum_div_pow_sq_le_div_sq (N : ℕ) {j : ℝ} (hj : 0 < j) {c : ℝ} (hc : 1 < c) : (∑ i ∈ range N with j < c ^ i, (1 : ℝ) / (c ^ i) ^ 2) ≤ c ^ 3 * (c - 1)⁻¹ / j ^ 2 := by have cpos : 0 < c := zero_lt_one.trans hc have A : (0 : ℝ) < c⁻¹ ^ 2 := sq_pos_of_pos (inv_pos.2 cpos) have B : c ^ 2 * ((1 : ℝ) - c⁻¹ ^ 2)⁻¹ ≤ c ^ 3 * (c - 1)⁻¹ := by rw [← div_eq_mul_inv, ← div_eq_mul_inv, div_le_div_iff₀ _ (sub_pos.2 hc)] swap · exact sub_pos.2 (pow_lt_one₀ (inv_nonneg.2 cpos.le) (inv_lt_one_of_one_lt₀ hc) two_ne_zero) have : c ^ 3 = c ^ 2 * c := by ring simp only [mul_sub, this, mul_one, inv_pow, sub_le_sub_iff_left] rw [mul_assoc, mul_comm c, ← mul_assoc, mul_inv_cancel₀ (sq_pos_of_pos cpos).ne', one_mul] simpa using pow_right_mono₀ hc.le one_le_two have C : c⁻¹ ^ 2 < 1 := pow_lt_one₀ (inv_nonneg.2 cpos.le) (inv_lt_one_of_one_lt₀ hc) two_ne_zero calc (∑ i ∈ range N with j < c ^ i, (1 : ℝ) / (c ^ i) ^ 2) ≤ ∑ i ∈ Ico ⌊Real.log j / Real.log c⌋₊ N, (1 : ℝ) / (c ^ i) ^ 2 := by gcongr intro i hi simp only [mem_filter, mem_range] at hi simp only [hi.1, mem_Ico, and_true] apply Nat.floor_le_of_le apply le_of_lt rw [div_lt_iff₀ (Real.log_pos hc), ← Real.log_pow] exact Real.log_lt_log hj hi.2 _ = ∑ i ∈ Ico ⌊Real.log j / Real.log c⌋₊ N, (c⁻¹ ^ 2) ^ i := by congr 1 with i simp [← pow_mul, mul_comm] _ ≤ (c⁻¹ ^ 2) ^ ⌊Real.log j / Real.log c⌋₊ / ((1 : ℝ) - c⁻¹ ^ 2) := geom_sum_Ico_le_of_lt_one (sq_nonneg _) C _ ≤ (c⁻¹ ^ 2) ^ (Real.log j / Real.log c - 1) / ((1 : ℝ) - c⁻¹ ^ 2) := by gcongr · exact sub_nonneg.2 C.le · rw [← Real.rpow_natCast] exact Real.rpow_le_rpow_of_exponent_ge A C.le (Nat.sub_one_lt_floor _).le _ = c ^ 2 * ((1 : ℝ) - c⁻¹ ^ 2)⁻¹ / j ^ 2 := by have I : (c⁻¹ ^ 2) ^ (Real.log j / Real.log c) = (1 : ℝ) / j ^ 2 := by apply Real.log_injOn_pos (Real.rpow_pos_of_pos A _) · rw [Set.mem_Ioi]; positivity rw [Real.log_rpow A] simp only [one_div, Real.log_inv, Real.log_pow, mul_neg, neg_inj] field_simp [(Real.log_pos hc).ne'] ring rw [Real.rpow_sub A, I] have : c ^ 2 - 1 ≠ 0 := (sub_pos.2 (one_lt_pow₀ hc two_ne_zero)).ne' simp ring _ ≤ c ^ 3 * (c - 1)⁻¹ / j ^ 2 := by gcongr theorem mul_pow_le_nat_floor_pow {c : ℝ} (hc : 1 < c) (i : ℕ) : (1 - c⁻¹) * c ^ i ≤ ⌊c ^ i⌋₊ := by have cpos : 0 < c := zero_lt_one.trans hc rcases eq_or_ne i 0 with (rfl | hi) · simp only [pow_zero, Nat.floor_one, Nat.cast_one, mul_one, sub_le_self_iff, inv_nonneg, cpos.le] calc (1 - c⁻¹) * c ^ i = c ^ i - c ^ i * c⁻¹ := by ring _ ≤ c ^ i - 1 := by gcongr simpa only [← div_eq_mul_inv, one_le_div cpos, pow_one] using le_self_pow₀ hc.le hi _ ≤ ⌊c ^ i⌋₊ := (Nat.sub_one_lt_floor _).le /-- The sum of `1/⌊c^i⌋₊^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative constant. -/ theorem sum_div_nat_floor_pow_sq_le_div_sq (N : ℕ) {j : ℝ} (hj : 0 < j) {c : ℝ} (hc : 1 < c) : (∑ i ∈ range N with j < ⌊c ^ i⌋₊, (1 : ℝ) / (⌊c ^ i⌋₊ : ℝ) ^ 2) ≤ c ^ 5 * (c - 1)⁻¹ ^ 3 / j ^ 2 := by have cpos : 0 < c := zero_lt_one.trans hc have A : 0 < 1 - c⁻¹ := sub_pos.2 (inv_lt_one_of_one_lt₀ hc) calc (∑ i ∈ range N with j < ⌊c ^ i⌋₊, (1 : ℝ) / (⌊c ^ i⌋₊ : ℝ) ^ 2) ≤ ∑ i ∈ range N with j < c ^ i, (1 : ℝ) / (⌊c ^ i⌋₊ : ℝ) ^ 2 := by gcongr exact fun k hk ↦ hk.trans_le <| Nat.floor_le (by positivity) _ ≤ ∑ i ∈ range N with j < c ^ i, (1 - c⁻¹)⁻¹ ^ 2 * ((1 : ℝ) / (c ^ i) ^ 2) := by gcongr with i rw [mul_div_assoc', mul_one, div_le_div_iff₀]; rotate_left · apply sq_pos_of_pos refine zero_lt_one.trans_le ?_ simp only [Nat.le_floor, one_le_pow₀, hc.le, Nat.one_le_cast, Nat.cast_one] · exact sq_pos_of_pos (pow_pos cpos _) rw [one_mul, ← mul_pow] gcongr rw [← div_eq_inv_mul, le_div_iff₀ A, mul_comm] exact mul_pow_le_nat_floor_pow hc i _ ≤ (1 - c⁻¹)⁻¹ ^ 2 * (c ^ 3 * (c - 1)⁻¹) / j ^ 2 := by rw [← mul_sum, ← mul_div_assoc'] gcongr exact sum_div_pow_sq_le_div_sq N hj hc _ = c ^ 5 * (c - 1)⁻¹ ^ 3 / j ^ 2 := by congr 1 field_simp [(sub_pos.2 hc).ne'] ring!
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.Measure.Typeclasses.SFinite /-! # Restriction of a measure to a sub-σ-algebra ## Main definitions * `MeasureTheory.Measure.trim`: restriction of a measure to a sub-sigma algebra. -/ open scoped ENNReal namespace MeasureTheory variable {α : Type*} /-- Restriction of a measure to a sub-σ-algebra. It is common to see a measure `μ` on a measurable space structure `m0` as being also a measure on any `m ≤ m0`. Since measures in mathlib have to be trimmed to the measurable space, `μ` itself cannot be a measure on `m`, hence the definition of `μ.trim hm`. This notion is related to `OuterMeasure.trim`, see the lemma `toOuterMeasure_trim_eq_trim_toOuterMeasure`. -/ noncomputable def Measure.trim {m m0 : MeasurableSpace α} (μ : @Measure α m0) (hm : m ≤ m0) : @Measure α m := @OuterMeasure.toMeasure α m μ.toOuterMeasure (hm.trans (le_toOuterMeasure_caratheodory μ)) @[simp] theorem trim_eq_self [MeasurableSpace α] {μ : Measure α} : μ.trim le_rfl = μ := by simp [Measure.trim] variable {m m0 : MeasurableSpace α} {μ : Measure α} {s : Set α} theorem toOuterMeasure_trim_eq_trim_toOuterMeasure (μ : Measure α) (hm : m ≤ m0) : @Measure.toOuterMeasure _ m (μ.trim hm) = @OuterMeasure.trim _ m μ.toOuterMeasure := by rw [Measure.trim, toMeasure_toOuterMeasure (ms := m)] @[simp] theorem zero_trim (hm : m ≤ m0) : (0 : Measure α).trim hm = (0 : @Measure α m) := by simp [Measure.trim, @OuterMeasure.toMeasure_zero _ m] theorem trim_measurableSet_eq (hm : m ≤ m0) (hs : @MeasurableSet α m s) : μ.trim hm s = μ s := by rw [Measure.trim, toMeasure_apply (ms := m) _ _ hs, Measure.coe_toOuterMeasure] theorem le_trim (hm : m ≤ m0) : μ s ≤ μ.trim hm s := by simp_rw [Measure.trim] exact @le_toMeasure_apply _ m _ _ _ lemma trim_eq_map (hm : m ≤ m0) : μ.trim hm = @Measure.map _ _ _ m id μ := by refine @Measure.ext α m _ _ (fun s hs ↦ ?_) rw [Measure.map_apply (measurable_id'' hm) hs, trim_measurableSet_eq hm hs, Set.preimage_id] lemma trim_add {ν : Measure α} (hm : m ≤ m0) : (μ + ν).trim hm = μ.trim hm + ν.trim hm := @Measure.ext _ m _ _ (fun s hs ↦ by simp [trim_measurableSet_eq hm hs]) theorem measure_eq_zero_of_trim_eq_zero (hm : m ≤ m0) (h : μ.trim hm s = 0) : μ s = 0 := le_antisymm ((le_trim hm).trans (le_of_eq h)) (zero_le _) theorem measure_trim_toMeasurable_eq_zero {hm : m ≤ m0} (hs : μ.trim hm s = 0) : μ (@toMeasurable α m (μ.trim hm) s) = 0 := measure_eq_zero_of_trim_eq_zero hm (by rwa [@measure_toMeasurable _ m]) theorem ae_of_ae_trim (hm : m ≤ m0) {μ : Measure α} {P : α → Prop} (h : ∀ᵐ x ∂μ.trim hm, P x) : ∀ᵐ x ∂μ, P x := measure_eq_zero_of_trim_eq_zero hm h theorem ae_eq_of_ae_eq_trim {E} {hm : m ≤ m0} {f₁ f₂ : α → E} (h12 : f₁ =ᵐ[μ.trim hm] f₂) : f₁ =ᵐ[μ] f₂ := measure_eq_zero_of_trim_eq_zero hm h12 theorem ae_le_of_ae_le_trim {E} [LE E] {hm : m ≤ m0} {f₁ f₂ : α → E} (h12 : f₁ ≤ᵐ[μ.trim hm] f₂) : f₁ ≤ᵐ[μ] f₂ := measure_eq_zero_of_trim_eq_zero hm h12 theorem trim_trim {m₁ m₂ : MeasurableSpace α} {hm₁₂ : m₁ ≤ m₂} {hm₂ : m₂ ≤ m0} : (μ.trim hm₂).trim hm₁₂ = μ.trim (hm₁₂.trans hm₂) := by refine @Measure.ext _ m₁ _ _ (fun t ht => ?_) rw [trim_measurableSet_eq hm₁₂ ht, trim_measurableSet_eq (hm₁₂.trans hm₂) ht, trim_measurableSet_eq hm₂ (hm₁₂ t ht)] theorem restrict_trim (hm : m ≤ m0) (μ : Measure α) (hs : @MeasurableSet α m s) : @Measure.restrict α m (μ.trim hm) s = (μ.restrict s).trim hm := by refine @Measure.ext _ m _ _ (fun t ht => ?_) rw [@Measure.restrict_apply α m _ _ _ ht, trim_measurableSet_eq hm ht, Measure.restrict_apply (hm t ht), trim_measurableSet_eq hm (@MeasurableSet.inter α m t s ht hs)] instance isFiniteMeasure_trim (hm : m ≤ m0) [IsFiniteMeasure μ] : IsFiniteMeasure (μ.trim hm) where measure_univ_lt_top := by rw [trim_measurableSet_eq hm (@MeasurableSet.univ _ m)] exact measure_lt_top _ _ theorem sigmaFiniteTrim_mono {m m₂ m0 : MeasurableSpace α} {μ : Measure α} (hm : m ≤ m0) (hm₂ : m₂ ≤ m) [SigmaFinite (μ.trim (hm₂.trans hm))] : SigmaFinite (μ.trim hm) := by refine ⟨⟨?_⟩⟩ refine { set := spanningSets (μ.trim (hm₂.trans hm)) set_mem := fun _ => Set.mem_univ _ finite := fun i => ?_ spanning := iUnion_spanningSets _ } calc (μ.trim hm) (spanningSets (μ.trim (hm₂.trans hm)) i) = ((μ.trim hm).trim hm₂) (spanningSets (μ.trim (hm₂.trans hm)) i) := by rw [@trim_measurableSet_eq α m₂ m (μ.trim hm) _ hm₂ (measurableSet_spanningSets _ _)] _ = (μ.trim (hm₂.trans hm)) (spanningSets (μ.trim (hm₂.trans hm)) i) := by rw [@trim_trim _ _ μ _ _ hm₂ hm] _ < ∞ := measure_spanningSets_lt_top _ _ theorem sigmaFinite_trim_bot_iff : SigmaFinite (μ.trim bot_le) ↔ IsFiniteMeasure μ := by rw [sigmaFinite_bot_iff] refine ⟨fun h => ⟨?_⟩, fun h => ⟨?_⟩⟩ <;> have h_univ := h.measure_univ_lt_top · rwa [trim_measurableSet_eq bot_le MeasurableSet.univ] at h_univ · rwa [trim_measurableSet_eq bot_le MeasurableSet.univ] lemma Measure.AbsolutelyContinuous.trim {ν : Measure α} (hμν : μ ≪ ν) (hm : m ≤ m0) : μ.trim hm ≪ ν.trim hm := by refine Measure.AbsolutelyContinuous.mk (fun s hs hsν ↦ ?_) rw [trim_measurableSet_eq hm hs] at hsν ⊢ exact hμν hsν end MeasureTheory
Semiconj.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland -/ import Mathlib.Algebra.Group.Semiconj.Defs import Mathlib.Algebra.Ring.Defs /-! # Semirings and rings This file gives lemmas about semirings, rings and domains. This is analogous to `Mathlib/Algebra/Group/Basic.lean`, the difference being that the former is about `+` and `*` separately, while the present file is about their interaction. For the definitions of semirings and rings see `Mathlib/Algebra/Ring/Defs.lean`. -/ universe u variable {R : Type u} open Function namespace SemiconjBy @[simp] theorem add_right [Distrib R] {a x y x' y' : R} (h : SemiconjBy a x y) (h' : SemiconjBy a x' y') : SemiconjBy a (x + x') (y + y') := by simp only [SemiconjBy, left_distrib, right_distrib, h.eq, h'.eq] @[simp] theorem add_left [Distrib R] {a b x y : R} (ha : SemiconjBy a x y) (hb : SemiconjBy b x y) : SemiconjBy (a + b) x y := by simp only [SemiconjBy, left_distrib, right_distrib, ha.eq, hb.eq] section variable [Mul R] [HasDistribNeg R] {a x y : R} theorem neg_right (h : SemiconjBy a x y) : SemiconjBy a (-x) (-y) := by simp only [SemiconjBy, h.eq, neg_mul, mul_neg] @[simp] theorem neg_right_iff : SemiconjBy a (-x) (-y) ↔ SemiconjBy a x y := ⟨fun h => neg_neg x ▸ neg_neg y ▸ h.neg_right, SemiconjBy.neg_right⟩ theorem neg_left (h : SemiconjBy a x y) : SemiconjBy (-a) x y := by simp only [SemiconjBy, h.eq, neg_mul, mul_neg] @[simp] theorem neg_left_iff : SemiconjBy (-a) x y ↔ SemiconjBy a x y := ⟨fun h => neg_neg a ▸ h.neg_left, SemiconjBy.neg_left⟩ end section variable [MulOneClass R] [HasDistribNeg R] theorem neg_one_right (a : R) : SemiconjBy a (-1) (-1) := by simp theorem neg_one_left (x : R) : SemiconjBy (-1) x x := by simp end section variable [NonUnitalNonAssocRing R] {a b x y x' y' : R} @[simp] theorem sub_right (h : SemiconjBy a x y) (h' : SemiconjBy a x' y') : SemiconjBy a (x - x') (y - y') := by simpa only [sub_eq_add_neg] using h.add_right h'.neg_right @[simp] theorem sub_left (ha : SemiconjBy a x y) (hb : SemiconjBy b x y) : SemiconjBy (a - b) x y := by simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left end end SemiconjBy
Minimal.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, Peter Nelson -/ import Mathlib.Order.Antichain /-! # Minimality and Maximality This file proves basic facts about minimality and maximality of an element with respect to a predicate `P` on an ordered type `α`. ## Implementation Details This file underwent a refactor from a version where minimality and maximality were defined using sets rather than predicates, and with an unbundled order relation rather than a `LE` instance. A side effect is that it has become less straightforward to state that something is minimal with respect to a relation that is *not* defeq to the default `LE`. One possible way would be with a type synonym, and another would be with an ad hoc `LE` instance and `@` notation. This was not an issue in practice anywhere in mathlib at the time of the refactor, but it may be worth re-examining this to make it easier in the future; see the TODO below. ## TODO * In the linearly ordered case, versions of lemmas like `minimal_mem_image` will hold with `MonotoneOn`/`AntitoneOn` assumptions rather than the stronger `x ≤ y ↔ f x ≤ f y` assumptions. * `Set.maximal_iff_forall_insert` and `Set.minimal_iff_forall_diff_singleton` will generalize to lemmas about covering in the case of an `IsStronglyAtomic`/`IsStronglyCoatomic` order. * `Finset` versions of the lemmas about sets. * API to allow for easily expressing min/maximality with respect to an arbitrary non-`LE` relation. * API for `MinimalFor`/`MaximalFor` -/ assert_not_exists CompleteLattice open Set OrderDual variable {ι α : Type*} section LE variable [LE α] {f : ι → α} {i j : ι} @[simp] lemma minimalFor_eq_iff : MinimalFor (· = j) f i ↔ i = j := by simp +contextual [MinimalFor] @[simp] lemma maximalFor_eq_iff : MaximalFor (· = j) f i ↔ i = j := by simp +contextual [MaximalFor] end LE variable {P Q : α → Prop} {a x y : α} section LE variable [LE α] @[simp] lemma minimalFor_id : MinimalFor P id x ↔ Minimal P x := .rfl @[simp] lemma maximalFor_id : MaximalFor P id x ↔ Maximal P x := .rfl @[simp] theorem minimal_toDual : Minimal (fun x ↦ P (ofDual x)) (toDual x) ↔ Maximal P x := Iff.rfl alias ⟨Minimal.of_dual, Minimal.dual⟩ := minimal_toDual @[simp] theorem maximal_toDual : Maximal (fun x ↦ P (ofDual x)) (toDual x) ↔ Minimal P x := Iff.rfl alias ⟨Maximal.of_dual, Maximal.dual⟩ := maximal_toDual @[simp] theorem minimal_false : ¬ Minimal (fun _ ↦ False) x := by simp [Minimal] @[simp] theorem maximal_false : ¬ Maximal (fun _ ↦ False) x := by simp [Maximal] @[simp] theorem minimal_true : Minimal (fun _ ↦ True) x ↔ IsMin x := by simp [IsMin, Minimal] @[simp] theorem maximal_true : Maximal (fun _ ↦ True) x ↔ IsMax x := minimal_true (α := αᵒᵈ) @[simp] theorem minimal_subtype {x : Subtype Q} : Minimal (fun x ↦ P x.1) x ↔ Minimal (P ⊓ Q) x := by obtain ⟨x, hx⟩ := x simp only [Minimal, Subtype.forall, Subtype.mk_le_mk, Pi.inf_apply, inf_Prop_eq] tauto @[simp] theorem maximal_subtype {x : Subtype Q} : Maximal (fun x ↦ P x.1) x ↔ Maximal (P ⊓ Q) x := minimal_subtype (α := αᵒᵈ) theorem maximal_true_subtype {x : Subtype P} : Maximal (fun _ ↦ True) x ↔ Maximal P x := by obtain ⟨x, hx⟩ := x simp [Maximal, hx] theorem minimal_true_subtype {x : Subtype P} : Minimal (fun _ ↦ True) x ↔ Minimal P x := by obtain ⟨x, hx⟩ := x simp [Minimal, hx] @[simp] theorem minimal_minimal : Minimal (Minimal P) x ↔ Minimal P x := ⟨fun h ↦ h.prop, fun h ↦ ⟨h, fun _ hy hyx ↦ h.le_of_le hy.prop hyx⟩⟩ @[simp] theorem maximal_maximal : Maximal (Maximal P) x ↔ Maximal P x := minimal_minimal (α := αᵒᵈ) /-- If `P` is down-closed, then minimal elements satisfying `P` are exactly the globally minimal elements satisfying `P`. -/ theorem minimal_iff_isMin (hP : ∀ ⦃x y⦄, P y → x ≤ y → P x) : Minimal P x ↔ P x ∧ IsMin x := ⟨fun h ↦ ⟨h.prop, fun _ h' ↦ h.le_of_le (hP h.prop h') h'⟩, fun h ↦ ⟨h.1, fun _ _ h' ↦ h.2 h'⟩⟩ /-- If `P` is up-closed, then maximal elements satisfying `P` are exactly the globally maximal elements satisfying `P`. -/ theorem maximal_iff_isMax (hP : ∀ ⦃x y⦄, P y → y ≤ x → P x) : Maximal P x ↔ P x ∧ IsMax x := ⟨fun h ↦ ⟨h.prop, fun _ h' ↦ h.le_of_ge (hP h.prop h') h'⟩, fun h ↦ ⟨h.1, fun _ _ h' ↦ h.2 h'⟩⟩ theorem Minimal.mono (h : Minimal P x) (hle : Q ≤ P) (hQ : Q x) : Minimal Q x := ⟨hQ, fun y hQy ↦ h.le_of_le (hle y hQy)⟩ theorem Maximal.mono (h : Maximal P x) (hle : Q ≤ P) (hQ : Q x) : Maximal Q x := ⟨hQ, fun y hQy ↦ h.le_of_ge (hle y hQy)⟩ theorem Minimal.and_right (h : Minimal P x) (hQ : Q x) : Minimal (fun x ↦ P x ∧ Q x) x := h.mono (fun _ ↦ And.left) ⟨h.prop, hQ⟩ theorem Minimal.and_left (h : Minimal P x) (hQ : Q x) : Minimal (fun x ↦ (Q x ∧ P x)) x := h.mono (fun _ ↦ And.right) ⟨hQ, h.prop⟩ theorem Maximal.and_right (h : Maximal P x) (hQ : Q x) : Maximal (fun x ↦ (P x ∧ Q x)) x := h.mono (fun _ ↦ And.left) ⟨h.prop, hQ⟩ theorem Maximal.and_left (h : Maximal P x) (hQ : Q x) : Maximal (fun x ↦ (Q x ∧ P x)) x := h.mono (fun _ ↦ And.right) ⟨hQ, h.prop⟩ @[simp] theorem minimal_eq_iff : Minimal (· = y) x ↔ x = y := by simp +contextual [Minimal] @[simp] theorem maximal_eq_iff : Maximal (· = y) x ↔ x = y := by simp +contextual [Maximal] theorem not_minimal_iff (hx : P x) : ¬ Minimal P x ↔ ∃ y, P y ∧ y ≤ x ∧ ¬ (x ≤ y) := by simp [Minimal, hx] theorem not_maximal_iff (hx : P x) : ¬ Maximal P x ↔ ∃ y, P y ∧ x ≤ y ∧ ¬ (y ≤ x) := not_minimal_iff (α := αᵒᵈ) hx theorem Minimal.or (h : Minimal (fun x ↦ P x ∨ Q x) x) : Minimal P x ∨ Minimal Q x := by obtain ⟨h | h, hmin⟩ := h · exact .inl ⟨h, fun y hy hyx ↦ hmin (Or.inl hy) hyx⟩ exact .inr ⟨h, fun y hy hyx ↦ hmin (Or.inr hy) hyx⟩ theorem Maximal.or (h : Maximal (fun x ↦ P x ∨ Q x) x) : Maximal P x ∨ Maximal Q x := Minimal.or (α := αᵒᵈ) h theorem minimal_and_iff_right_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) : Minimal (fun x ↦ P x ∧ Q x) x ↔ (Minimal P x) ∧ Q x := by simp_rw [and_iff_left_of_imp (fun x ↦ hPQ x), iff_self_and] exact fun h ↦ hPQ h.prop theorem minimal_and_iff_left_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) : Minimal (fun x ↦ Q x ∧ P x) x ↔ Q x ∧ (Minimal P x) := by simp_rw [iff_comm, and_comm, minimal_and_iff_right_of_imp hPQ, and_comm] theorem maximal_and_iff_right_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) : Maximal (fun x ↦ P x ∧ Q x) x ↔ (Maximal P x) ∧ Q x := minimal_and_iff_right_of_imp (α := αᵒᵈ) hPQ theorem maximal_and_iff_left_of_imp (hPQ : ∀ ⦃x⦄, P x → Q x) : Maximal (fun x ↦ Q x ∧ P x) x ↔ Q x ∧ (Maximal P x) := minimal_and_iff_left_of_imp (α := αᵒᵈ) hPQ end LE section Preorder variable [Preorder α] theorem minimal_iff_forall_lt : Minimal P x ↔ P x ∧ ∀ ⦃y⦄, y < x → ¬ P y := by simp [Minimal, lt_iff_le_not_ge, imp.swap] theorem maximal_iff_forall_gt : Maximal P x ↔ P x ∧ ∀ ⦃y⦄, x < y → ¬ P y := minimal_iff_forall_lt (α := αᵒᵈ) theorem Minimal.not_prop_of_lt (h : Minimal P x) (hlt : y < x) : ¬ P y := (minimal_iff_forall_lt.1 h).2 hlt theorem Maximal.not_prop_of_gt (h : Maximal P x) (hlt : x < y) : ¬ P y := (maximal_iff_forall_gt.1 h).2 hlt theorem Minimal.not_lt (h : Minimal P x) (hy : P y) : ¬(y < x) := fun hlt ↦ h.not_prop_of_lt hlt hy theorem Maximal.not_gt (h : Maximal P x) (hy : P y) : ¬(x < y) := fun hlt ↦ h.not_prop_of_gt hlt hy @[simp] theorem minimal_le_iff : Minimal (· ≤ y) x ↔ x ≤ y ∧ IsMin x := minimal_iff_isMin (fun _ _ h h' ↦ h'.trans h) @[simp] theorem maximal_ge_iff : Maximal (y ≤ ·) x ↔ y ≤ x ∧ IsMax x := minimal_le_iff (α := αᵒᵈ) @[simp] theorem minimal_lt_iff : Minimal (· < y) x ↔ x < y ∧ IsMin x := minimal_iff_isMin (fun _ _ h h' ↦ h'.trans_lt h) @[simp] theorem maximal_gt_iff : Maximal (y < ·) x ↔ y < x ∧ IsMax x := minimal_lt_iff (α := αᵒᵈ) theorem not_minimal_iff_exists_lt (hx : P x) : ¬ Minimal P x ↔ ∃ y, y < x ∧ P y := by simp_rw [not_minimal_iff hx, lt_iff_le_not_ge, and_comm] alias ⟨exists_lt_of_not_minimal, _⟩ := not_minimal_iff_exists_lt theorem not_maximal_iff_exists_gt (hx : P x) : ¬ Maximal P x ↔ ∃ y, x < y ∧ P y := not_minimal_iff_exists_lt (α := αᵒᵈ) hx alias ⟨exists_gt_of_not_maximal, _⟩ := not_maximal_iff_exists_gt section WellFoundedLT variable [WellFoundedLT α] lemma exists_minimalFor_of_wellFoundedLT (P : ι → Prop) (f : ι → α) (hP : ∃ i, P i) : ∃ i, MinimalFor P f i := by simpa [not_lt_iff_le_imp_ge, InvImage] using (instIsWellFoundedInvImage (· < ·) f).wf.has_min _ hP lemma exists_minimal_of_wellFoundedLT (P : α → Prop) (hP : ∃ a, P a) : ∃ a, Minimal P a := exists_minimalFor_of_wellFoundedLT P id hP lemma exists_minimal_le_of_wellFoundedLT (P : α → Prop) (a : α) (ha : P a) : ∃ b ≤ a, Minimal P b := by obtain ⟨b, ⟨hba, hb⟩, hbmin⟩ := exists_minimal_of_wellFoundedLT (fun b ↦ b ≤ a ∧ P b) ⟨a, le_rfl, ha⟩ exact ⟨b, hba, hb, fun c hc hcb ↦ hbmin ⟨hcb.trans hba, hc⟩ hcb⟩ end WellFoundedLT section WellFoundedGT variable [WellFoundedGT α] lemma exists_maximalFor_of_wellFoundedGT (P : ι → Prop) (f : ι → α) (hP : ∃ i, P i) : ∃ i, MaximalFor P f i := exists_minimalFor_of_wellFoundedLT (α := αᵒᵈ) P f hP lemma exists_maximal_of_wellFoundedGT (P : α → Prop) (hP : ∃ a, P a) : ∃ a, Maximal P a := exists_minimal_of_wellFoundedLT (α := αᵒᵈ) P hP lemma exists_maximal_ge_of_wellFoundedGT (P : α → Prop) (a : α) (ha : P a) : ∃ b, a ≤ b ∧ Maximal P b := exists_minimal_le_of_wellFoundedLT (α := αᵒᵈ) P a ha end WellFoundedGT end Preorder section PartialOrder variable [PartialOrder α] theorem Minimal.eq_of_ge (hx : Minimal P x) (hy : P y) (hge : y ≤ x) : x = y := (hx.2 hy hge).antisymm hge theorem Minimal.eq_of_le (hx : Minimal P x) (hy : P y) (hle : y ≤ x) : y = x := (hx.eq_of_ge hy hle).symm theorem Maximal.eq_of_le (hx : Maximal P x) (hy : P y) (hle : x ≤ y) : x = y := hle.antisymm <| hx.2 hy hle theorem Maximal.eq_of_ge (hx : Maximal P x) (hy : P y) (hge : x ≤ y) : y = x := (hx.eq_of_le hy hge).symm theorem minimal_iff : Minimal P x ↔ P x ∧ ∀ ⦃y⦄, P y → y ≤ x → x = y := ⟨fun h ↦ ⟨h.1, fun _ ↦ h.eq_of_ge⟩, fun h ↦ ⟨h.1, fun _ hy hle ↦ (h.2 hy hle).le⟩⟩ theorem maximal_iff : Maximal P x ↔ P x ∧ ∀ ⦃y⦄, P y → x ≤ y → x = y := minimal_iff (α := αᵒᵈ) theorem minimal_mem_iff {s : Set α} : Minimal (· ∈ s) x ↔ x ∈ s ∧ ∀ ⦃y⦄, y ∈ s → y ≤ x → x = y := minimal_iff theorem maximal_mem_iff {s : Set α} : Maximal (· ∈ s) x ↔ x ∈ s ∧ ∀ ⦃y⦄, y ∈ s → x ≤ y → x = y := maximal_iff /-- If `P y` holds, and everything satisfying `P` is above `y`, then `y` is the unique minimal element satisfying `P`. -/ theorem minimal_iff_eq (hy : P y) (hP : ∀ ⦃x⦄, P x → y ≤ x) : Minimal P x ↔ x = y := ⟨fun h ↦ h.eq_of_ge hy (hP h.prop), by rintro rfl; exact ⟨hy, fun z hz _ ↦ hP hz⟩⟩ /-- If `P y` holds, and everything satisfying `P` is below `y`, then `y` is the unique maximal element satisfying `P`. -/ theorem maximal_iff_eq (hy : P y) (hP : ∀ ⦃x⦄, P x → x ≤ y) : Maximal P x ↔ x = y := minimal_iff_eq (α := αᵒᵈ) hy hP @[simp] theorem minimal_ge_iff : Minimal (y ≤ ·) x ↔ x = y := minimal_iff_eq rfl.le fun _ ↦ id @[simp] theorem maximal_le_iff : Maximal (· ≤ y) x ↔ x = y := maximal_iff_eq rfl.le fun _ ↦ id theorem minimal_iff_minimal_of_imp_of_forall (hPQ : ∀ ⦃x⦄, Q x → P x) (h : ∀ ⦃x⦄, P x → ∃ y, y ≤ x ∧ Q y) : Minimal P x ↔ Minimal Q x := by refine ⟨fun h' ↦ ⟨?_, fun y hy hyx ↦ h'.le_of_le (hPQ hy) hyx⟩, fun h' ↦ ⟨hPQ h'.prop, fun y hy hyx ↦ ?_⟩⟩ · obtain ⟨y, hyx, hy⟩ := h h'.prop rwa [((h'.le_of_le (hPQ hy)) hyx).antisymm hyx] obtain ⟨z, hzy, hz⟩ := h hy exact (h'.le_of_le hz (hzy.trans hyx)).trans hzy theorem maximal_iff_maximal_of_imp_of_forall (hPQ : ∀ ⦃x⦄, Q x → P x) (h : ∀ ⦃x⦄, P x → ∃ y, x ≤ y ∧ Q y) : Maximal P x ↔ Maximal Q x := minimal_iff_minimal_of_imp_of_forall (α := αᵒᵈ) hPQ h end PartialOrder section Subset variable {P : Set α → Prop} {s t : Set α} theorem Minimal.eq_of_superset (h : Minimal P s) (ht : P t) (hts : t ⊆ s) : s = t := h.eq_of_ge ht hts theorem Maximal.eq_of_subset (h : Maximal P s) (ht : P t) (hst : s ⊆ t) : s = t := h.eq_of_le ht hst theorem Minimal.eq_of_subset (h : Minimal P s) (ht : P t) (hts : t ⊆ s) : t = s := h.eq_of_le ht hts theorem Maximal.eq_of_superset (h : Maximal P s) (ht : P t) (hst : s ⊆ t) : t = s := h.eq_of_ge ht hst theorem minimal_subset_iff : Minimal P s ↔ P s ∧ ∀ ⦃t⦄, P t → t ⊆ s → s = t := _root_.minimal_iff theorem maximal_subset_iff : Maximal P s ↔ P s ∧ ∀ ⦃t⦄, P t → s ⊆ t → s = t := _root_.maximal_iff theorem minimal_subset_iff' : Minimal P s ↔ P s ∧ ∀ ⦃t⦄, P t → t ⊆ s → s ⊆ t := Iff.rfl theorem maximal_subset_iff' : Maximal P s ↔ P s ∧ ∀ ⦃t⦄, P t → s ⊆ t → t ⊆ s := Iff.rfl theorem not_minimal_subset_iff (hs : P s) : ¬ Minimal P s ↔ ∃ t, t ⊂ s ∧ P t := not_minimal_iff_exists_lt hs theorem not_maximal_subset_iff (hs : P s) : ¬ Maximal P s ↔ ∃ t, s ⊂ t ∧ P t := not_maximal_iff_exists_gt hs theorem Set.minimal_iff_forall_ssubset : Minimal P s ↔ P s ∧ ∀ ⦃t⦄, t ⊂ s → ¬ P t := minimal_iff_forall_lt theorem Minimal.not_prop_of_ssubset (h : Minimal P s) (ht : t ⊂ s) : ¬ P t := (minimal_iff_forall_lt.1 h).2 ht theorem Minimal.not_ssubset (h : Minimal P s) (ht : P t) : ¬ t ⊂ s := h.not_lt ht theorem Maximal.mem_of_prop_insert (h : Maximal P s) (hx : P (insert x s)) : x ∈ s := h.eq_of_subset hx (subset_insert _ _) ▸ mem_insert .. theorem Minimal.notMem_of_prop_diff_singleton (h : Minimal P s) (hx : P (s \ {x})) : x ∉ s := fun hxs ↦ ((h.eq_of_superset hx diff_subset).subset hxs).2 rfl @[deprecated (since := "2025-05-23")] alias Minimal.not_mem_of_prop_diff_singleton := Minimal.notMem_of_prop_diff_singleton theorem Set.minimal_iff_forall_diff_singleton (hP : ∀ ⦃s t⦄, P t → t ⊆ s → P s) : Minimal P s ↔ P s ∧ ∀ x ∈ s, ¬ P (s \ {x}) := ⟨fun h ↦ ⟨h.1, fun _ hx hP ↦ h.notMem_of_prop_diff_singleton hP hx⟩, fun h ↦ ⟨h.1, fun _ ht hts x hxs ↦ by_contra fun hxt ↦ h.2 x hxs (hP ht <| subset_diff_singleton hts hxt)⟩⟩ theorem Set.exists_diff_singleton_of_not_minimal (hP : ∀ ⦃s t⦄, P t → t ⊆ s → P s) (hs : P s) (h : ¬ Minimal P s) : ∃ x ∈ s, P (s \ {x}) := by simpa [Set.minimal_iff_forall_diff_singleton hP, hs] using h theorem Set.maximal_iff_forall_ssuperset : Maximal P s ↔ P s ∧ ∀ ⦃t⦄, s ⊂ t → ¬ P t := maximal_iff_forall_gt theorem Maximal.not_prop_of_ssuperset (h : Maximal P s) (ht : s ⊂ t) : ¬ P t := (maximal_iff_forall_gt.1 h).2 ht theorem Maximal.not_ssuperset (h : Maximal P s) (ht : P t) : ¬ s ⊂ t := h.not_gt ht theorem Set.maximal_iff_forall_insert (hP : ∀ ⦃s t⦄, P t → s ⊆ t → P s) : Maximal P s ↔ P s ∧ ∀ x ∉ s, ¬ P (insert x s) := by simp only [not_imp_not] exact ⟨fun h ↦ ⟨h.1, fun x ↦ h.mem_of_prop_insert⟩, fun h ↦ ⟨h.1, fun t ht hst x hxt ↦ h.2 x (hP ht <| insert_subset hxt hst)⟩⟩ theorem Set.exists_insert_of_not_maximal (hP : ∀ ⦃s t⦄, P t → s ⊆ t → P s) (hs : P s) (h : ¬ Maximal P s) : ∃ x ∉ s, P (insert x s) := by simpa [Set.maximal_iff_forall_insert hP, hs] using h /- TODO : generalize `minimal_iff_forall_diff_singleton` and `maximal_iff_forall_insert` to `IsStronglyCoatomic`/`IsStronglyAtomic` orders. -/ end Subset section Set variable {s t : Set α} section Preorder variable [Preorder α] theorem setOf_minimal_subset (s : Set α) : {x | Minimal (· ∈ s) x} ⊆ s := sep_subset .. theorem setOf_maximal_subset (s : Set α) : {x | Maximal (· ∈ s) x} ⊆ s := sep_subset .. theorem Set.Subsingleton.maximal_mem_iff (h : s.Subsingleton) : Maximal (· ∈ s) x ↔ x ∈ s := by obtain (rfl | ⟨x, rfl⟩) := h.eq_empty_or_singleton <;> simp theorem Set.Subsingleton.minimal_mem_iff (h : s.Subsingleton) : Minimal (· ∈ s) x ↔ x ∈ s := by obtain (rfl | ⟨x, rfl⟩) := h.eq_empty_or_singleton <;> simp theorem IsLeast.minimal (h : IsLeast s x) : Minimal (· ∈ s) x := ⟨h.1, fun _b hb _ ↦ h.2 hb⟩ theorem IsGreatest.maximal (h : IsGreatest s x) : Maximal (· ∈ s) x := ⟨h.1, fun _b hb _ ↦ h.2 hb⟩ theorem IsAntichain.minimal_mem_iff (hs : IsAntichain (· ≤ ·) s) : Minimal (· ∈ s) x ↔ x ∈ s := ⟨fun h ↦ h.prop, fun h ↦ ⟨h, fun _ hys hyx ↦ (hs.eq hys h hyx).symm.le⟩⟩ theorem IsAntichain.maximal_mem_iff (hs : IsAntichain (· ≤ ·) s) : Maximal (· ∈ s) x ↔ x ∈ s := hs.to_dual.minimal_mem_iff /-- If `t` is an antichain shadowing and including the set of maximal elements of `s`, then `t` *is* the set of maximal elements of `s`. -/ theorem IsAntichain.eq_setOf_maximal (ht : IsAntichain (· ≤ ·) t) (h : ∀ x, Maximal (· ∈ s) x → x ∈ t) (hs : ∀ a ∈ t, ∃ b, b ≤ a ∧ Maximal (· ∈ s) b) : {x | Maximal (· ∈ s) x} = t := by refine Set.ext fun x ↦ ⟨h _, fun hx ↦ ?_⟩ obtain ⟨y, hyx, hy⟩ := hs x hx rwa [← ht.eq (h y hy) hx hyx] /-- If `t` is an antichain shadowed by and including the set of minimal elements of `s`, then `t` *is* the set of minimal elements of `s`. -/ theorem IsAntichain.eq_setOf_minimal (ht : IsAntichain (· ≤ ·) t) (h : ∀ x, Minimal (· ∈ s) x → x ∈ t) (hs : ∀ a ∈ t, ∃ b, a ≤ b ∧ Minimal (· ∈ s) b) : {x | Minimal (· ∈ s) x} = t := ht.to_dual.eq_setOf_maximal h hs end Preorder section PartialOrder variable [PartialOrder α] theorem setOf_maximal_antichain (P : α → Prop) : IsAntichain (· ≤ ·) {x | Maximal P x} := fun _ hx _ ⟨hy, _⟩ hne hle ↦ hne (hle.antisymm <| hx.2 hy hle) theorem setOf_minimal_antichain (P : α → Prop) : IsAntichain (· ≤ ·) {x | Minimal P x} := (setOf_maximal_antichain (α := αᵒᵈ) P).swap theorem IsLeast.minimal_iff (h : IsLeast s a) : Minimal (· ∈ s) x ↔ x = a := ⟨fun h' ↦ h'.eq_of_ge h.1 (h.2 h'.prop), fun h' ↦ h' ▸ h.minimal⟩ theorem IsGreatest.maximal_iff (h : IsGreatest s a) : Maximal (· ∈ s) x ↔ x = a := ⟨fun h' ↦ h'.eq_of_le h.1 (h.2 h'.prop), fun h' ↦ h' ▸ h.maximal⟩ end PartialOrder end Set section Image variable [Preorder α] {β : Type*} [Preorder β] {s : Set α} {t : Set β} section Function variable {f : α → β} theorem minimal_mem_image_monotone (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) (hx : Minimal (· ∈ s) x) : Minimal (· ∈ f '' s) (f x) := by refine ⟨mem_image_of_mem f hx.prop, ?_⟩ rintro _ ⟨y, hy, rfl⟩ rw [hf hx.prop hy, hf hy hx.prop] exact hx.le_of_le hy theorem maximal_mem_image_monotone (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) (hx : Maximal (· ∈ s) x) : Maximal (· ∈ f '' s) (f x) := minimal_mem_image_monotone (α := αᵒᵈ) (β := βᵒᵈ) (s := s) (fun _ _ hx hy ↦ hf hy hx) hx theorem minimal_mem_image_monotone_iff (ha : a ∈ s) (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) : Minimal (· ∈ f '' s) (f a) ↔ Minimal (· ∈ s) a := by refine ⟨fun h ↦ ⟨ha, fun y hys ↦ ?_⟩, minimal_mem_image_monotone hf⟩ rw [← hf ha hys, ← hf hys ha] exact h.le_of_le (mem_image_of_mem f hys) theorem maximal_mem_image_monotone_iff (ha : a ∈ s) (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) : Maximal (· ∈ f '' s) (f a) ↔ Maximal (· ∈ s) a := minimal_mem_image_monotone_iff (α := αᵒᵈ) (β := βᵒᵈ) (s := s) ha fun _ _ hx hy ↦ hf hy hx theorem minimal_mem_image_antitone (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) (hx : Minimal (· ∈ s) x) : Maximal (· ∈ f '' s) (f x) := minimal_mem_image_monotone (β := βᵒᵈ) (fun _ _ h h' ↦ hf h' h) hx theorem maximal_mem_image_antitone (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) (hx : Maximal (· ∈ s) x) : Minimal (· ∈ f '' s) (f x) := maximal_mem_image_monotone (β := βᵒᵈ) (fun _ _ h h' ↦ hf h' h) hx theorem minimal_mem_image_antitone_iff (ha : a ∈ s) (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) : Minimal (· ∈ f '' s) (f a) ↔ Maximal (· ∈ s) a := maximal_mem_image_monotone_iff (β := βᵒᵈ) ha (fun _ _ h h' ↦ hf h' h) theorem maximal_mem_image_antitone_iff (ha : a ∈ s) (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) : Maximal (· ∈ f '' s) (f a) ↔ Minimal (· ∈ s) a := minimal_mem_image_monotone_iff (β := βᵒᵈ) ha (fun _ _ h h' ↦ hf h' h) theorem image_monotone_setOf_minimal (hf : ∀ ⦃x y⦄, P x → P y → (f x ≤ f y ↔ x ≤ y)) : f '' {x | Minimal P x} = {x | Minimal (∃ x₀, P x₀ ∧ f x₀ = ·) x} := by refine Set.ext fun x ↦ ⟨?_, fun h ↦ ?_⟩ · rintro ⟨x, (hx : Minimal _ x), rfl⟩ exact (minimal_mem_image_monotone_iff hx.prop hf).2 hx obtain ⟨y, hy, rfl⟩ := (mem_setOf_eq ▸ h).prop exact mem_image_of_mem _ <| (minimal_mem_image_monotone_iff (s := setOf P) hy hf).1 h theorem image_monotone_setOf_maximal (hf : ∀ ⦃x y⦄, P x → P y → (f x ≤ f y ↔ x ≤ y)) : f '' {x | Maximal P x} = {x | Maximal (∃ x₀, P x₀ ∧ f x₀ = ·) x} := image_monotone_setOf_minimal (α := αᵒᵈ) (β := βᵒᵈ) (fun _ _ hx hy ↦ hf hy hx) theorem image_antitone_setOf_minimal (hf : ∀ ⦃x y⦄, P x → P y → (f x ≤ f y ↔ y ≤ x)) : f '' {x | Minimal P x} = {x | Maximal (∃ x₀, P x₀ ∧ f x₀ = ·) x} := image_monotone_setOf_minimal (β := βᵒᵈ) (fun _ _ hx hy ↦ hf hy hx) theorem image_antitone_setOf_maximal (hf : ∀ ⦃x y⦄, P x → P y → (f x ≤ f y ↔ y ≤ x)) : f '' {x | Maximal P x} = {x | Minimal (∃ x₀, P x₀ ∧ f x₀ = ·) x} := image_monotone_setOf_maximal (β := βᵒᵈ) (fun _ _ hx hy ↦ hf hy hx) theorem image_monotone_setOf_minimal_mem (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) : f '' {x | Minimal (· ∈ s) x} = {x | Minimal (· ∈ f '' s) x} := image_monotone_setOf_minimal hf theorem image_monotone_setOf_maximal_mem (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ x ≤ y)) : f '' {x | Maximal (· ∈ s) x} = {x | Maximal (· ∈ f '' s) x} := image_monotone_setOf_maximal hf theorem image_antitone_setOf_minimal_mem (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) : f '' {x | Minimal (· ∈ s) x} = {x | Maximal (· ∈ f '' s) x} := image_antitone_setOf_minimal hf theorem image_antitone_setOf_maximal_mem (hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → (f x ≤ f y ↔ y ≤ x)) : f '' {x | Maximal (· ∈ s) x} = {x | Minimal (· ∈ f '' s) x} := image_antitone_setOf_maximal hf end Function namespace OrderEmbedding variable {f : α ↪o β} {t : Set β} theorem minimal_mem_image (f : α ↪o β) (hx : Minimal (· ∈ s) x) : Minimal (· ∈ f '' s) (f x) := _root_.minimal_mem_image_monotone (by simp [f.le_iff_le]) hx theorem maximal_mem_image (f : α ↪o β) (hx : Maximal (· ∈ s) x) : Maximal (· ∈ f '' s) (f x) := _root_.maximal_mem_image_monotone (by simp [f.le_iff_le]) hx theorem minimal_mem_image_iff (ha : a ∈ s) : Minimal (· ∈ f '' s) (f a) ↔ Minimal (· ∈ s) a := _root_.minimal_mem_image_monotone_iff ha (by simp [f.le_iff_le]) theorem maximal_mem_image_iff (ha : a ∈ s) : Maximal (· ∈ f '' s) (f a) ↔ Maximal (· ∈ s) a := _root_.maximal_mem_image_monotone_iff ha (by simp [f.le_iff_le]) theorem minimal_apply_mem_inter_range_iff : Minimal (· ∈ t ∩ range f) (f x) ↔ Minimal (fun x ↦ f x ∈ t) x := by refine ⟨fun h ↦ ⟨h.prop.1, fun y hy ↦ ?_⟩, fun h ↦ ⟨⟨h.prop, by simp⟩, ?_⟩⟩ · rw [← f.le_iff_le, ← f.le_iff_le] exact h.le_of_le ⟨hy, by simp⟩ rintro _ ⟨hyt, ⟨y, rfl⟩⟩ simp_rw [f.le_iff_le] exact h.le_of_le hyt theorem maximal_apply_mem_inter_range_iff : Maximal (· ∈ t ∩ range f) (f x) ↔ Maximal (fun x ↦ f x ∈ t) x := f.dual.minimal_apply_mem_inter_range_iff theorem minimal_apply_mem_iff (ht : t ⊆ Set.range f) : Minimal (· ∈ t) (f x) ↔ Minimal (fun x ↦ f x ∈ t) x := by rw [← f.minimal_apply_mem_inter_range_iff, inter_eq_self_of_subset_left ht] theorem maximal_apply_iff (ht : t ⊆ Set.range f) : Maximal (· ∈ t) (f x) ↔ Maximal (fun x ↦ f x ∈ t) x := f.dual.minimal_apply_mem_iff ht @[simp] theorem image_setOf_minimal : f '' {x | Minimal (· ∈ s) x} = {x | Minimal (· ∈ f '' s) x} := _root_.image_monotone_setOf_minimal (by simp [f.le_iff_le]) @[simp] theorem image_setOf_maximal : f '' {x | Maximal (· ∈ s) x} = {x | Maximal (· ∈ f '' s) x} := _root_.image_monotone_setOf_maximal (by simp [f.le_iff_le]) theorem inter_preimage_setOf_minimal_eq_of_subset (hts : t ⊆ f '' s) : x ∈ s ∩ f ⁻¹' {y | Minimal (· ∈ t) y} ↔ Minimal (· ∈ s ∩ f ⁻¹' t) x := by simp_rw [mem_inter_iff, preimage_setOf_eq, mem_setOf_eq, mem_preimage, f.minimal_apply_mem_iff (hts.trans (image_subset_range _ _)), minimal_and_iff_left_of_imp (fun _ hx ↦ f.injective.mem_set_image.1 <| hts hx)] theorem inter_preimage_setOf_maximal_eq_of_subset (hts : t ⊆ f '' s) : x ∈ s ∩ f ⁻¹' {y | Maximal (· ∈ t) y} ↔ Maximal (· ∈ s ∩ f ⁻¹' t) x := f.dual.inter_preimage_setOf_minimal_eq_of_subset hts end OrderEmbedding namespace OrderIso theorem image_setOf_minimal (f : α ≃o β) (P : α → Prop) : f '' {x | Minimal P x} = {x | Minimal (fun x ↦ P (f.symm x)) x} := by convert _root_.image_monotone_setOf_minimal (f := f) (by simp [f.le_iff_le]) aesop theorem image_setOf_maximal (f : α ≃o β) (P : α → Prop) : f '' {x | Maximal P x} = {x | Maximal (fun x ↦ P (f.symm x)) x} := by convert _root_.image_monotone_setOf_maximal (f := f) (by simp [f.le_iff_le]) aesop theorem map_minimal_mem (f : s ≃o t) (hx : Minimal (· ∈ s) x) : Minimal (· ∈ t) (f ⟨x, hx.prop⟩) := by simpa only [show t = range (Subtype.val ∘ f) by simp, mem_univ, minimal_true_subtype, hx, true_imp_iff, image_univ] using OrderEmbedding.minimal_mem_image (f.toOrderEmbedding.trans (OrderEmbedding.subtype t)) (s := univ) (x := ⟨x, hx.prop⟩) theorem map_maximal_mem (f : s ≃o t) (hx : Maximal (· ∈ s) x) : Maximal (· ∈ t) (f ⟨x, hx.prop⟩) := by simpa only [show t = range (Subtype.val ∘ f) by simp, mem_univ, maximal_true_subtype, hx, true_imp_iff, image_univ] using OrderEmbedding.maximal_mem_image (f.toOrderEmbedding.trans (OrderEmbedding.subtype t)) (s := univ) (x := ⟨x, hx.prop⟩) /-- If two sets are order isomorphic, their minimals are also order isomorphic. -/ def mapSetOfMinimal (f : s ≃o t) : {x | Minimal (· ∈ s) x} ≃o {x | Minimal (· ∈ t) x} where toFun x := ⟨f ⟨x, x.2.1⟩, f.map_minimal_mem x.2⟩ invFun x := ⟨f.symm ⟨x, x.2.1⟩, f.symm.map_minimal_mem x.2⟩ left_inv x := Subtype.ext (congr_arg Subtype.val <| f.left_inv ⟨x, x.2.1⟩ :) right_inv x := Subtype.ext (congr_arg Subtype.val <| f.right_inv ⟨x, x.2.1⟩ :) map_rel_iff' := f.map_rel_iff /-- If two sets are order isomorphic, their maximals are also order isomorphic. -/ def mapSetOfMaximal (f : s ≃o t) : {x | Maximal (· ∈ s) x} ≃o {x | Maximal (· ∈ t) x} where toFun x := ⟨f ⟨x, x.2.1⟩, f.map_maximal_mem x.2⟩ invFun x := ⟨f.symm ⟨x, x.2.1⟩, f.symm.map_maximal_mem x.2⟩ left_inv x := Subtype.ext (congr_arg Subtype.val <| f.left_inv ⟨x, x.2.1⟩ :) right_inv x := Subtype.ext (congr_arg Subtype.val <| f.right_inv ⟨x, x.2.1⟩ :) map_rel_iff' := f.map_rel_iff /-- If two sets are antitonically order isomorphic, their minimals/maximals are too. -/ def setOfMinimalIsoSetOfMaximal (f : s ≃o tᵒᵈ) : {x | Minimal (· ∈ s) x} ≃o {x | Maximal (· ∈ t) (ofDual x)} where toFun x := ⟨(f ⟨x.1, x.2.1⟩).1, ((show s ≃o ofDual ⁻¹' t from f).mapSetOfMinimal x).2⟩ invFun x := ⟨(f.symm ⟨x.1, x.2.1⟩).1, ((show ofDual ⁻¹' t ≃o s from f.symm).mapSetOfMinimal x).2⟩ __ := (show s ≃o ofDual⁻¹' t from f).mapSetOfMinimal /-- If two sets are antitonically order isomorphic, their maximals/minimals are too. -/ def setOfMaximalIsoSetOfMinimal (f : s ≃o tᵒᵈ) : {x | Maximal (· ∈ s) x} ≃o {x | Minimal (· ∈ t) (ofDual x)} where toFun x := ⟨(f ⟨x.1, x.2.1⟩).1, ((show s ≃o ofDual ⁻¹' t from f).mapSetOfMaximal x).2⟩ invFun x := ⟨(f.symm ⟨x.1, x.2.1⟩).1, ((show ofDual ⁻¹' t ≃o s from f.symm).mapSetOfMaximal x).2⟩ __ := (show s ≃o ofDual⁻¹' t from f).mapSetOfMaximal end OrderIso end Image section Interval variable [PartialOrder α] {a b : α} theorem minimal_mem_Icc (hab : a ≤ b) : Minimal (· ∈ Icc a b) x ↔ x = a := minimal_iff_eq ⟨rfl.le, hab⟩ (fun _ ↦ And.left) theorem maximal_mem_Icc (hab : a ≤ b) : Maximal (· ∈ Icc a b) x ↔ x = b := maximal_iff_eq ⟨hab, rfl.le⟩ (fun _ ↦ And.right) theorem minimal_mem_Ico (hab : a < b) : Minimal (· ∈ Ico a b) x ↔ x = a := minimal_iff_eq ⟨rfl.le, hab⟩ (fun _ ↦ And.left) theorem maximal_mem_Ioc (hab : a < b) : Maximal (· ∈ Ioc a b) x ↔ x = b := maximal_iff_eq ⟨hab, rfl.le⟩ (fun _ ↦ And.right) /- Note : The one-sided interval versions of these lemmas are unnecessary, since `simp` handles them with `maximal_le_iff` and `minimal_ge_iff`. -/ end Interval
Choose.lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Floris van Doorn, Mario Carneiro, Reid Barton, Johan Commelin -/ import Mathlib.Util.Tactic import Mathlib.Logic.Function.Basic /-! # `choose` tactic Performs Skolemization, that is, given `h : ∀ a:α, ∃ b:β, p a b |- G` produces `f : α → β, hf: ∀ a, p a (f a) |- G`. TODO: switch to `rcases` syntax: `choose ⟨i, j, h₁ -⟩ := expr`. -/ open Lean Meta Elab Tactic namespace Mathlib.Tactic.Choose /-- Given `α : Sort u`, `nonemp : Nonempty α`, `p : α → Prop`, a context of free variables `ctx`, and a pair of an element `val : α` and `spec : p val`, `mk_sometimes u α nonemp p ctx (val, spec)` produces another pair `val', spec'` such that `val'` does not have any free variables from elements of `ctx` whose types are propositions. This is done by applying `Function.sometimes` to abstract over all the propositional arguments. -/ def mk_sometimes (u : Level) (α nonemp p : Expr) : List Expr → Expr × Expr → MetaM (Expr × Expr) | [], (val, spec) => pure (val, spec) | (e :: ctx), (val, spec) => do let (val, spec) ← mk_sometimes u α nonemp p ctx (val, spec) let t ← inferType e let b ← isProp t if b then do let val' ← mkLambdaFVars #[e] val pure (mkApp4 (Expr.const ``Function.sometimes [Level.zero, u]) t α nonemp val', mkApp7 (Expr.const ``Function.sometimes_spec [u]) t α nonemp p val' e spec) else pure (val, spec) /-- Results of searching for nonempty instances, to eliminate dependencies on propositions (`choose!`). `success` means we found at least one instance; `failure ts` means we didn't find instances for any `t ∈ ts`. (`failure []` means we didn't look for instances at all.) Rationale: `choose!` means we are expected to succeed at least once in eliminating dependencies on propositions. -/ inductive ElimStatus | success | failure (ts : List Expr) /-- Combine two statuses, keeping a success from either side or merging the failures. -/ def ElimStatus.merge : ElimStatus → ElimStatus → ElimStatus | success, _ => success | _, success => success | failure ts₁, failure ts₂ => failure (ts₁ ++ ts₂) /-- `mkFreshNameFrom orig base` returns `mkFreshUserName base` if ``orig = `_`` and `orig` otherwise. -/ def mkFreshNameFrom (orig base : Name) : CoreM Name := if orig = `_ then mkFreshUserName base else pure orig /-- Changes `(h : ∀ xs, ∃ a:α, p a) ⊢ g` to `(d : ∀ xs, a) ⊢ (s : ∀ xs, p (d xs)) → g` and `(h : ∀ xs, p xs ∧ q xs) ⊢ g` to `(d : ∀ xs, p xs) ⊢ (s : ∀ xs, q xs) → g`. `choose1` returns a tuple of - the error result (see `ElimStatus`) - the data new free variable that was "chosen" - the new goal (which contains the spec of the data as domain of an arrow type) If `nondep` is true and `α` is inhabited, then it will remove the dependency of `d` on all propositional assumptions in `xs`. For example if `ys` are propositions then `(h : ∀ xs ys, ∃ a:α, p a) ⊢ g` becomes `(d : ∀ xs, a) (s : ∀ xs ys, p (d xs)) ⊢ g`. -/ def choose1 (g : MVarId) (nondep : Bool) (h : Option Expr) (data : Name) : MetaM (ElimStatus × Expr × MVarId) := do let (g, h) ← match h with | some e => pure (g, e) | none => do let (e, g) ← g.intro1P pure (g, .fvar e) g.withContext do let h ← instantiateMVars h let t ← inferType h forallTelescopeReducing t fun ctx t ↦ do (← withTransparency .all (whnf t)).withApp fun | .const ``Exists [u], #[α, p] => do let data ← mkFreshNameFrom data ((← p.getBinderName).getD `h) let ((neFail : ElimStatus), (nonemp : Option Expr)) ← if nondep then let ne := (Expr.const ``Nonempty [u]).app α let m ← mkFreshExprMVar ne let mut g' := m.mvarId! for e in ctx do if (← isProof e) then continue let ty ← whnf (← inferType e) let nety := (Expr.const ``Nonempty [u]).app ty let neval := mkApp2 (Expr.const ``Nonempty.intro [u]) ty e g' ← g'.assert .anonymous nety neval (_, g') ← g'.intros g'.withContext do match ← synthInstance? (← g'.getType) with | some e => do g'.assign e let m ← instantiateMVars m pure (.success, some m) | none => pure (.failure [ne], none) else pure (.failure [], none) let ctx' ← if nonemp.isSome then ctx.filterM (not <$> isProof ·) else pure ctx let dataTy ← mkForallFVars ctx' α let mut dataVal := mkApp3 (.const ``Classical.choose [u]) α p (mkAppN h ctx) let mut specVal := mkApp3 (.const ``Classical.choose_spec [u]) α p (mkAppN h ctx) if let some nonemp := nonemp then (dataVal, specVal) ← mk_sometimes u α nonemp p ctx.toList (dataVal, specVal) dataVal ← mkLambdaFVars ctx' dataVal specVal ← mkLambdaFVars ctx specVal let (fvar, g) ← withLocalDeclD .anonymous dataTy fun d ↦ do let specTy ← mkForallFVars ctx (p.app (mkAppN d ctx')).headBeta g.withContext <| withLocalDeclD data dataTy fun d' ↦ do let mvarTy ← mkArrow (specTy.replaceFVar d d') (← g.getType) let newMVar ← mkFreshExprSyntheticOpaqueMVar mvarTy (← g.getTag) g.assign <| mkApp2 (← mkLambdaFVars #[d'] newMVar) dataVal specVal pure (d', newMVar.mvarId!) let g ← match h with | .fvar v => g.clear v | _ => pure g return (neFail, fvar, g) | .const ``And _, #[p, q] => do let data ← mkFreshNameFrom data `h let e1 ← mkLambdaFVars ctx <| mkApp3 (.const ``And.left []) p q (mkAppN h ctx) let e2 ← mkLambdaFVars ctx <| mkApp3 (.const ``And.right []) p q (mkAppN h ctx) let t1 ← inferType e1 let t2 ← inferType e2 let (fvar, g) ← (← (← g.assert .anonymous t2 e2).assert data t1 e1).intro1P let g ← match h with | .fvar v => g.clear v | _ => pure g return (.success, .fvar fvar, g) -- TODO: support Σ, ×, or even any inductive type with 1 constructor ? | _, _ => throwError "expected a term of the shape `∀ xs, ∃ a, p xs a` or `∀ xs, p xs ∧ q xs`" /-- A wrapper around `choose1` that parses identifiers and adds variable info to new variables. -/ def choose1WithInfo (g : MVarId) (nondep : Bool) (h : Option Expr) (data : TSyntax ``binderIdent) : MetaM (ElimStatus × MVarId) := do let n := if let `(binderIdent| $n:ident) := data then n.getId else `_ let (status, fvar, g) ← choose1 g nondep h n g.withContext <| fvar.addLocalVarInfoForBinderIdent data pure (status, g) /-- A loop around `choose1`. The main entry point for the `choose` tactic. -/ def elabChoose (nondep : Bool) (h : Option Expr) : List (TSyntax ``binderIdent) → ElimStatus → MVarId → MetaM MVarId | [], _, _ => throwError "expect list of variables" | [n], status, g => match nondep, status with | true, .failure tys => do -- We expected some elimination, but it didn't happen. let mut msg := m!"choose!: failed to synthesize any nonempty instances" for ty in tys do msg := msg ++ m!"{(← mkFreshExprMVar ty).mvarId!}" throwError msg | _, _ => do let (fvar, g) ← match n with | `(binderIdent| $n:ident) => g.intro n.getId | _ => g.intro1 g.withContext <| (Expr.fvar fvar).addLocalVarInfoForBinderIdent n return g | n::ns, status, g => do let (status', g) ← choose1WithInfo g nondep h n elabChoose nondep none ns (status.merge status') g /-- * `choose a b h h' using hyp` takes a hypothesis `hyp` of the form `∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b ∧ Q x y a b` for some `P Q : X → Y → A → B → Prop` and outputs into context a function `a : X → Y → A`, `b : X → Y → B` and two assumptions: `h : ∀ (x : X) (y : Y), P x y (a x y) (b x y)` and `h' : ∀ (x : X) (y : Y), Q x y (a x y) (b x y)`. It also works with dependent versions. * `choose! a b h h' using hyp` does the same, except that it will remove dependency of the functions on propositional arguments if possible. For example if `Y` is a proposition and `A` and `B` are nonempty in the above example then we will instead get `a : X → A`, `b : X → B`, and the assumptions `h : ∀ (x : X) (y : Y), P x y (a x) (b x)` and `h' : ∀ (x : X) (y : Y), Q x y (a x) (b x)`. The `using hyp` part can be omitted, which will effectively cause `choose` to start with an `intro hyp`. Examples: ``` example (h : ∀ n m : ℕ, ∃ i j, m = n + i ∨ m + j = n) : True := by choose i j h using h guard_hyp i : ℕ → ℕ → ℕ guard_hyp j : ℕ → ℕ → ℕ guard_hyp h : ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n trivial ``` ``` example (h : ∀ i : ℕ, i < 7 → ∃ j, i < j ∧ j < i+i) : True := by choose! f h h' using h guard_hyp f : ℕ → ℕ guard_hyp h : ∀ (i : ℕ), i < 7 → i < f i guard_hyp h' : ∀ (i : ℕ), i < 7 → f i < i + i trivial ``` -/ syntax (name := choose) "choose" "!"? (ppSpace colGt binderIdent)+ (" using " term)? : tactic elab_rules : tactic | `(tactic| choose $[!%$b]? $[$ids]* $[using $h]?) => withMainContext do let h ← h.mapM (Elab.Tactic.elabTerm · none) let g ← elabChoose b.isSome h ids.toList (.failure []) (← getMainGoal) replaceMainGoal [g] @[inherit_doc choose] syntax "choose!" (ppSpace colGt binderIdent)+ (" using " term)? : tactic macro_rules | `(tactic| choose! $[$ids]* $[using $h]?) => `(tactic| choose ! $[$ids]* $[using $h]?) end Mathlib.Tactic.Choose
Whiskering.lean
import Mathlib.Algebra.Category.ModuleCat.Colimits import Mathlib.Algebra.Category.ModuleCat.Limits import Mathlib.Algebra.Category.ModuleCat.FilteredColimits import Mathlib.CategoryTheory.Sites.Equivalence universe u open CategoryTheory GrothendieckTopology section Small variable {C : Type u} [SmallCategory C] (J : GrothendieckTopology C) (R : Type u) [Ring R] example : HasSheafCompose J (forget (ModuleCat.{u} R)) := inferInstance end Small section Large variable {C : Type (u + 1)} [LargeCategory C] (J : GrothendieckTopology C) example (R : Type (u + 1)) [Ring R] : HasSheafCompose J (forget (ModuleCat.{u+1} R)) := inferInstance variable [EssentiallySmall.{u} C] example (R : Type u) [Ring R] : HasSheafCompose J (forget (ModuleCat.{u} R)) := inferInstance end Large
Unitization.lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.CStarAlgebra.Classes import Mathlib.Analysis.Normed.Algebra.Unitization /-! # The minimal unitization of a C⋆-algebra This file shows that when `E` is a C⋆-algebra (over a densely normed field `𝕜`), that the minimal `Unitization` is as well. In order to ensure that the norm structure is available, we must first show that every C⋆-algebra is a `RegularNormedAlgebra`. In addition, we show that in a `RegularNormedAlgebra` which is a `StarRing` for which the involution is isometric, that multiplication on the right is also an isometry (i.e., `Isometry (ContinuousLinearMap.mul 𝕜 E).flip`). -/ open ContinuousLinearMap local postfix:max "⋆" => star variable (𝕜 : Type*) {E : Type*} namespace ContinuousLinearMap variable [NontriviallyNormedField 𝕜] [NonUnitalNormedRing E] [StarRing E] [NormedStarGroup E] variable [NormedSpace 𝕜 E] [IsScalarTower 𝕜 E E] [SMulCommClass 𝕜 E E] [RegularNormedAlgebra 𝕜 E] lemma opNorm_mul_flip_apply (a : E) : ‖(mul 𝕜 E).flip a‖ = ‖a‖ := by refine le_antisymm (opNorm_le_bound _ (norm_nonneg _) fun b => by simpa only [mul_comm] using norm_mul_le b a) ?_ suffices ‖mul 𝕜 E (star a)‖ ≤ ‖(mul 𝕜 E).flip a‖ by simpa only [ge_iff_le, opNorm_mul_apply, norm_star] using this refine opNorm_le_bound _ (norm_nonneg _) fun b => ?_ calc ‖mul 𝕜 E (star a) b‖ = ‖(mul 𝕜 E).flip a (star b)‖ := by simpa only [mul_apply', flip_apply, star_mul, star_star] using norm_star (star b * a) _ ≤ ‖(mul 𝕜 E).flip a‖ * ‖b‖ := by simpa only [flip_apply, mul_apply', norm_star] using le_opNorm ((mul 𝕜 E).flip a) (star b) lemma opNNNorm_mul_flip_apply (a : E) : ‖(mul 𝕜 E).flip a‖₊ = ‖a‖₊ := Subtype.ext (opNorm_mul_flip_apply 𝕜 a) variable (E) lemma isometry_mul_flip : Isometry (mul 𝕜 E).flip := AddMonoidHomClass.isometry_of_norm _ (opNorm_mul_flip_apply 𝕜) end ContinuousLinearMap variable [DenselyNormedField 𝕜] [NonUnitalNormedRing E] [StarRing E] [CStarRing E] variable [NormedSpace 𝕜 E] [IsScalarTower 𝕜 E E] [SMulCommClass 𝕜 E E] variable (E) /-- A C⋆-algebra over a densely normed field is a regular normed algebra. -/ instance CStarRing.instRegularNormedAlgebra : RegularNormedAlgebra 𝕜 E where isometry_mul' := AddMonoidHomClass.isometry_of_norm (mul 𝕜 E) fun a => NNReal.eq_iff.mp <| show ‖mul 𝕜 E a‖₊ = ‖a‖₊ by rw [← sSup_unitClosedBall_eq_nnnorm] refine csSup_eq_of_forall_le_of_forall_lt_exists_gt ?_ ?_ fun r hr => ?_ · exact (Metric.nonempty_closedBall.mpr zero_le_one).image _ · rintro - ⟨x, hx, rfl⟩ exact ((mul 𝕜 E a).unit_le_opNorm x <| mem_closedBall_zero_iff.mp hx).trans (opNorm_mul_apply_le 𝕜 E a) · have ha : 0 < ‖a‖₊ := zero_le'.trans_lt hr rw [← inv_inv ‖a‖₊, NNReal.lt_inv_iff_mul_lt (inv_ne_zero ha.ne')] at hr obtain ⟨k, hk₁, hk₂⟩ := NormedField.exists_lt_nnnorm_lt 𝕜 (mul_lt_mul_of_pos_right hr <| inv_pos.2 ha) refine ⟨_, ⟨k • star a, ?_, rfl⟩, ?_⟩ · simpa only [mem_closedBall_zero_iff, norm_smul, one_mul, norm_star] using (NNReal.le_inv_iff_mul_le ha.ne').1 (one_mul ‖a‖₊⁻¹ ▸ hk₂.le : ‖k‖₊ ≤ ‖a‖₊⁻¹) · simp only [map_smul, nnnorm_smul, mul_apply', CStarRing.nnnorm_self_mul_star] rwa [← div_lt_iff₀ (mul_pos ha ha), div_eq_mul_inv, mul_inv, ← mul_assoc] section CStarProperty variable [StarRing 𝕜] [StarModule 𝕜 E] variable {E} /-- This is the key lemma used to establish the instance `Unitization.instCStarRing` (i.e., proving that the norm on `Unitization 𝕜 E` satisfies the C⋆-property). We split this one out so that declaring the `CStarRing` instance doesn't time out. -/ theorem Unitization.norm_splitMul_snd_sq (x : Unitization 𝕜 E) : ‖(Unitization.splitMul 𝕜 E x).snd‖ ^ 2 ≤ ‖(Unitization.splitMul 𝕜 E (star x * x)).snd‖ := by /- The key idea is that we can use `sSup_unitClosedBall_eq_norm` to make this about applying this linear map to elements of norm at most one. There is a bit of `sqrt` and `sq` shuffling that needs to occur, which is primarily just an annoyance. -/ refine (Real.le_sqrt (norm_nonneg _) (norm_nonneg _)).mp ?_ simp only [Unitization.splitMul_apply] rw [← sSup_unitClosedBall_eq_norm] refine csSup_le ((Metric.nonempty_closedBall.2 zero_le_one).image _) ?_ rintro - ⟨b, hb, rfl⟩ simp only -- rewrite to a more convenient form; this is where we use the C⋆-property rw [← Real.sqrt_sq (norm_nonneg _), Real.sqrt_le_sqrt_iff (norm_nonneg _), sq, ← CStarRing.norm_star_mul_self, ContinuousLinearMap.add_apply, star_add, mul_apply', Algebra.algebraMap_eq_smul_one, ContinuousLinearMap.smul_apply, ContinuousLinearMap.one_apply, star_mul, star_smul, add_mul, smul_mul_assoc, ← mul_smul_comm, mul_assoc, ← mul_add, ← sSup_unitClosedBall_eq_norm] refine (norm_mul_le _ _).trans ?_ calc _ ≤ ‖star x.fst • (x.fst • b + x.snd * b) + star x.snd * (x.fst • b + x.snd * b)‖ := by nth_rewrite 2 [← one_mul ‖_ + _‖] gcongr exact (norm_star b).symm ▸ mem_closedBall_zero_iff.1 hb _ ≤ sSup (_ '' Metric.closedBall 0 1) := le_csSup ?_ ⟨b, hb, ?_⟩ -- now we just check the side conditions for `le_csSup`. There is nothing of interest here. · refine ⟨‖(star x * x).fst‖ + ‖(star x * x).snd‖, ?_⟩ rintro _ ⟨y, hy, rfl⟩ refine (norm_add_le _ _).trans ?_ gcongr · rw [Algebra.algebraMap_eq_smul_one] refine (norm_smul _ _).trans_le ?_ simpa only [mul_one] using mul_le_mul_of_nonneg_left (mem_closedBall_zero_iff.1 hy) (norm_nonneg (star x * x).fst) · exact (unit_le_opNorm _ y <| mem_closedBall_zero_iff.1 hy).trans (opNorm_mul_apply_le _ _ _) · simp only [ContinuousLinearMap.add_apply, mul_apply', Unitization.snd_star, Unitization.snd_mul, Unitization.fst_mul, Unitization.fst_star, Algebra.algebraMap_eq_smul_one, smul_apply, one_apply, smul_add, mul_add, add_mul] simp only [smul_smul, smul_mul_assoc, ← add_assoc, ← mul_assoc, mul_smul_comm] variable {𝕜} variable [CStarRing 𝕜] /-- The norm on `Unitization 𝕜 E` satisfies the C⋆-property -/ instance Unitization.instCStarRing : CStarRing (Unitization 𝕜 E) where norm_mul_self_le x := by -- rewrite both sides as a `⊔` simp only [Unitization.norm_def, Prod.norm_def] -- Show that `(Unitization.splitMul 𝕜 E x).snd` satisfies the C⋆-property, in two stages: have h₁ : ∀ x : Unitization 𝕜 E, ‖(Unitization.splitMul 𝕜 E x).snd‖ ≤ ‖(Unitization.splitMul 𝕜 E (star x)).snd‖ := by simp only [Unitization.splitMul_apply, Unitization.snd_star, Unitization.fst_star] intro x /- split based on whether the term inside the norm is zero or not. If so, it's trivial. If not, then apply `norm_splitMul_snd_sq` and cancel one copy of the norm -/ by_cases h : algebraMap 𝕜 (E →L[𝕜] E) x.fst + mul 𝕜 E x.snd = 0 · simp only [h, norm_zero] exact norm_nonneg _ · have : ‖(Unitization.splitMul 𝕜 E x).snd‖ ^ 2 ≤ ‖(Unitization.splitMul 𝕜 E (star x)).snd‖ * ‖(Unitization.splitMul 𝕜 E x).snd‖ := (norm_splitMul_snd_sq 𝕜 x).trans <| by rw [map_mul, Prod.snd_mul] exact norm_mul_le _ _ rw [sq] at this rw [← Ne, ← norm_pos_iff] at h simp only [Unitization.splitMul_apply, Unitization.snd_star, Unitization.fst_star] at this exact (mul_le_mul_right h).mp this -- in this step we make use of the key lemma `norm_splitMul_snd_sq` have h₂ : ‖(Unitization.splitMul 𝕜 E (star x * x)).snd‖ = ‖(Unitization.splitMul 𝕜 E x).snd‖ ^ 2 := by refine le_antisymm ?_ (norm_splitMul_snd_sq 𝕜 x) rw [map_mul, Prod.snd_mul] exact (norm_mul_le _ _).trans <| by rw [sq] gcongr simpa only [star_star] using h₁ (star x) -- Show that `(Unitization.splitMul 𝕜 E x).fst` satisfies the C⋆-property have h₃ : ‖(Unitization.splitMul 𝕜 E (star x * x)).fst‖ = ‖(Unitization.splitMul 𝕜 E x).fst‖ ^ 2 := by simp only [Unitization.splitMul_apply, Unitization.fst_mul, Unitization.fst_star, norm_mul, norm_star, sq] rw [h₂, h₃] /- use the definition of the norm, and split into cases based on whether the norm in the first coordinate is bigger or smaller than the norm in the second coordinate. -/ by_cases h : ‖(Unitization.splitMul 𝕜 E x).fst‖ ≤ ‖(Unitization.splitMul 𝕜 E x).snd‖ · rw [sq, sq, sup_eq_right.mpr h, sup_eq_right.mpr (mul_self_le_mul_self (norm_nonneg _) h)] · replace h := (not_le.mp h).le rw [sq, sq, sup_eq_left.mpr h, sup_eq_left.mpr (mul_self_le_mul_self (norm_nonneg _) h)] /-- The minimal unitization (over `ℂ`) of a C⋆-algebra, equipped with the C⋆-norm. When `A` is unital, `A⁺¹ ≃⋆ₐ[ℂ] (ℂ × A)`. -/ scoped[CStarAlgebra] postfix:max "⁺¹" => Unitization ℂ noncomputable instance Unitization.instCStarAlgebra {A : Type*} [NonUnitalCStarAlgebra A] : CStarAlgebra (Unitization ℂ A) where noncomputable instance Unitization.instCommCStarAlgebra {A : Type*} [NonUnitalCommCStarAlgebra A] : CommCStarAlgebra (Unitization ℂ A) where end CStarProperty
Sober.lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Topology.Sets.Closeds import Mathlib.Topology.Sets.OpenCover /-! # Sober spaces A quasi-sober space is a topological space where every irreducible closed subset has a generic point. A sober space is a quasi-sober space where every irreducible closed subset has a *unique* generic point. This is if and only if the space is T0, and thus sober spaces can be stated via `[QuasiSober α] [T0Space α]`. ## Main definition * `IsGenericPoint` : `x` is the generic point of `S` if `S` is the closure of `x`. * `QuasiSober` : A space is quasi-sober if every irreducible closed subset has a generic point. * `genericPoints` : The set of generic points of irreducible components. -/ open Set variable {α β : Type*} [TopologicalSpace α] [TopologicalSpace β] section genericPoint /-- `x` is a generic point of `S` if `S` is the closure of `x`. -/ @[stacks 004X "(1)"] def IsGenericPoint (x : α) (S : Set α) : Prop := closure ({x} : Set α) = S theorem isGenericPoint_def {x : α} {S : Set α} : IsGenericPoint x S ↔ closure ({x} : Set α) = S := Iff.rfl theorem IsGenericPoint.def {x : α} {S : Set α} (h : IsGenericPoint x S) : closure ({x} : Set α) = S := h theorem isGenericPoint_closure {x : α} : IsGenericPoint x (closure ({x} : Set α)) := refl _ variable {x y : α} {S U Z : Set α} theorem isGenericPoint_iff_specializes : IsGenericPoint x S ↔ ∀ y, x ⤳ y ↔ y ∈ S := by simp only [specializes_iff_mem_closure, IsGenericPoint, Set.ext_iff] namespace IsGenericPoint theorem specializes_iff_mem (h : IsGenericPoint x S) : x ⤳ y ↔ y ∈ S := isGenericPoint_iff_specializes.1 h y protected theorem specializes (h : IsGenericPoint x S) (h' : y ∈ S) : x ⤳ y := h.specializes_iff_mem.2 h' protected theorem mem (h : IsGenericPoint x S) : x ∈ S := h.specializes_iff_mem.1 specializes_rfl protected theorem isClosed (h : IsGenericPoint x S) : IsClosed S := h.def ▸ isClosed_closure protected theorem isIrreducible (h : IsGenericPoint x S) : IsIrreducible S := h.def ▸ isIrreducible_singleton.closure protected theorem inseparable (h : IsGenericPoint x S) (h' : IsGenericPoint y S) : Inseparable x y := (h.specializes h'.mem).antisymm (h'.specializes h.mem) /-- In a T₀ space, each set has at most one generic point. -/ protected theorem eq [T0Space α] (h : IsGenericPoint x S) (h' : IsGenericPoint y S) : x = y := (h.inseparable h').eq theorem mem_open_set_iff (h : IsGenericPoint x S) (hU : IsOpen U) : x ∈ U ↔ (S ∩ U).Nonempty := ⟨fun h' => ⟨x, h.mem, h'⟩, fun ⟨_y, hyS, hyU⟩ => (h.specializes hyS).mem_open hU hyU⟩ theorem disjoint_iff (h : IsGenericPoint x S) (hU : IsOpen U) : Disjoint S U ↔ x ∉ U := by rw [h.mem_open_set_iff hU, ← not_disjoint_iff_nonempty_inter, Classical.not_not] theorem mem_closed_set_iff (h : IsGenericPoint x S) (hZ : IsClosed Z) : x ∈ Z ↔ S ⊆ Z := by rw [← h.def, hZ.closure_subset_iff, singleton_subset_iff] protected theorem image (h : IsGenericPoint x S) {f : α → β} (hf : Continuous f) : IsGenericPoint (f x) (closure (f '' S)) := by rw [isGenericPoint_def, ← h.def, ← image_singleton, closure_image_closure hf] end IsGenericPoint theorem isGenericPoint_iff_forall_closed (hS : IsClosed S) (hxS : x ∈ S) : IsGenericPoint x S ↔ ∀ Z : Set α, IsClosed Z → x ∈ Z → S ⊆ Z := by have : closure {x} ⊆ S := closure_minimal (singleton_subset_iff.2 hxS) hS simp_rw [IsGenericPoint, subset_antisymm_iff, this, true_and, closure, subset_sInter_iff, mem_setOf_eq, and_imp, singleton_subset_iff] end genericPoint section Sober /-- A space is sober if every irreducible closed subset has a generic point. -/ @[mk_iff, stacks 004X "(3)"] class QuasiSober (α : Type*) [TopologicalSpace α] : Prop where sober : ∀ {S : Set α}, IsIrreducible S → IsClosed S → ∃ x, IsGenericPoint x S /-- A generic point of the closure of an irreducible space. -/ noncomputable def IsIrreducible.genericPoint [QuasiSober α] {S : Set α} (hS : IsIrreducible S) : α := (QuasiSober.sober hS.closure isClosed_closure).choose theorem IsIrreducible.isGenericPoint_genericPoint_closure [QuasiSober α] {S : Set α} (hS : IsIrreducible S) : IsGenericPoint hS.genericPoint (closure S) := (QuasiSober.sober hS.closure isClosed_closure).choose_spec theorem IsIrreducible.isGenericPoint_genericPoint [QuasiSober α] {S : Set α} (hS : IsIrreducible S) (hS' : IsClosed S) : IsGenericPoint hS.genericPoint S := by convert hS.isGenericPoint_genericPoint_closure; exact hS'.closure_eq.symm @[simp] theorem IsIrreducible.genericPoint_closure_eq [QuasiSober α] {S : Set α} (hS : IsIrreducible S) : closure ({hS.genericPoint} : Set α) = closure S := hS.isGenericPoint_genericPoint_closure theorem IsIrreducible.closure_genericPoint [QuasiSober α] {S : Set α} (hS : IsIrreducible S) (hS' : IsClosed S) : closure ({hS.genericPoint} : Set α) = S := hS.isGenericPoint_genericPoint_closure.trans hS'.closure_eq variable (α) /-- A generic point of a sober irreducible space. -/ noncomputable def genericPoint [QuasiSober α] [IrreducibleSpace α] : α := (IrreducibleSpace.isIrreducible_univ α).genericPoint theorem genericPoint_spec [QuasiSober α] [IrreducibleSpace α] : IsGenericPoint (genericPoint α) univ := by simpa using (IrreducibleSpace.isIrreducible_univ α).isGenericPoint_genericPoint_closure @[simp] theorem genericPoint_closure [QuasiSober α] [IrreducibleSpace α] : closure ({genericPoint α} : Set α) = univ := genericPoint_spec α variable {α} theorem genericPoint_specializes [QuasiSober α] [IrreducibleSpace α] (x : α) : genericPoint α ⤳ x := (IsIrreducible.isGenericPoint_genericPoint_closure _).specializes (by simp) attribute [local instance] specializationOrder /-- The closed irreducible subsets of a sober space bijects with the points of the space. -/ noncomputable def irreducibleSetEquivPoints [QuasiSober α] [T0Space α] : TopologicalSpace.IrreducibleCloseds α ≃o α where toFun s := s.2.genericPoint invFun x := ⟨closure ({x} : Set α), isIrreducible_singleton.closure, isClosed_closure⟩ left_inv s := by refine TopologicalSpace.IrreducibleCloseds.ext ?_ simp only [IsIrreducible.genericPoint_closure_eq, TopologicalSpace.IrreducibleCloseds.coe_mk, closure_eq_iff_isClosed.mpr s.3] rfl right_inv x := isIrreducible_singleton.closure.isGenericPoint_genericPoint_closure.eq (by rw [closure_closure]; exact isGenericPoint_closure) map_rel_iff' := by rintro ⟨s, hs, hs'⟩ ⟨t, ht, ht'⟩ refine specializes_iff_closure_subset.trans ?_ simp rfl lemma Topology.IsClosedEmbedding.quasiSober {f : α → β} (hf : IsClosedEmbedding f) [QuasiSober β] : QuasiSober α where sober hS hS' := by have hS'' := hS.image f hf.continuous.continuousOn obtain ⟨x, hx⟩ := QuasiSober.sober hS'' (hf.isClosedMap _ hS') obtain ⟨y, -, rfl⟩ := hx.mem use y apply image_injective.mpr hf.injective rw [← hx.def, ← hf.closure_image_eq, image_singleton] theorem Topology.IsOpenEmbedding.quasiSober {f : α → β} (hf : IsOpenEmbedding f) [QuasiSober β] : QuasiSober α where sober hS hS' := by have hS'' := hS.image f hf.continuous.continuousOn obtain ⟨x, hx⟩ := QuasiSober.sober hS''.closure isClosed_closure obtain ⟨T, hT, rfl⟩ := hf.isInducing.isClosed_iff.mp hS' rw [image_preimage_eq_inter_range] at hx hS'' have hxT : x ∈ T := by rw [← hT.closure_eq] exact closure_mono inter_subset_left hx.mem obtain ⟨y, rfl⟩ : x ∈ range f := by rw [hx.mem_open_set_iff hf.isOpen_range] refine Nonempty.mono ?_ hS''.1 simpa using subset_closure use y change _ = _ rw [hf.isEmbedding.closure_eq_preimage_closure_image, image_singleton, show _ = _ from hx] apply image_injective.mpr hf.injective ext z simp only [image_preimage_eq_inter_range, mem_inter_iff, and_congr_left_iff] exact fun hy => ⟨fun h => hT.closure_eq ▸ closure_mono inter_subset_left h, fun h => subset_closure ⟨h, hy⟩⟩ lemma TopologicalSpace.IsOpenCover.quasiSober_iff_forall {ι : Type*} {U : ι → Opens α} (hU : TopologicalSpace.IsOpenCover U) : QuasiSober α ↔ ∀ i, QuasiSober (U i) := by refine ⟨fun h i ↦ (U i).isOpenEmbedding'.quasiSober, fun hU' ↦ (quasiSober_iff _).mpr ?_⟩ · rintro t ⟨⟨x, hx⟩, h⟩ h' obtain ⟨i, hi⟩ := hU.exists_mem x have H : IsIrreducible ((↑) ⁻¹' t : Set (U i)) := ⟨⟨⟨x, hi⟩, hx⟩, h.preimage (U i).isOpenEmbedding'⟩ use H.genericPoint apply le_antisymm · simpa [h'.closure_subset_iff, h'.closure_eq] using continuous_subtype_val.closure_preimage_subset _ H.isGenericPoint_genericPoint_closure.mem rw [← image_singleton, ← closure_image_closure continuous_subtype_val, H.isGenericPoint_genericPoint_closure.def] refine (subset_closure_inter_of_isPreirreducible_of_isOpen h (U i).isOpen ⟨x, ⟨hx, hi⟩⟩).trans (closure_mono ?_) simpa only [inter_comm t, ← Subtype.image_preimage_coe] using Set.image_mono subset_closure lemma TopologicalSpace.IsOpenCover.quasiSober {ι : Type*} {U : ι → Opens α} (hU : TopologicalSpace.IsOpenCover U) [∀ i, QuasiSober (U i)] : QuasiSober α := hU.quasiSober_iff_forall.mpr ‹_› /-- A space is quasi-sober if it can be covered by open quasi-sober subsets. -/ theorem quasiSober_of_open_cover (S : Set (Set α)) (hS : ∀ s : S, IsOpen (s : Set α)) [∀ s : S, QuasiSober s] (hS' : ⋃₀ S = ⊤) : QuasiSober α := TopologicalSpace.IsOpenCover.quasiSober (U := fun s : S ↦ ⟨s, hS s⟩) <| by simpa [TopologicalSpace.IsOpenCover, ← SetLike.coe_set_eq, sUnion_eq_iUnion] using hS' /-- Any Hausdorff space is a quasi-sober space because any irreducible set is a singleton. -/ instance (priority := 100) T2Space.quasiSober [T2Space α] : QuasiSober α where sober h _ := by obtain ⟨x, rfl⟩ := isIrreducible_iff_singleton.mp h exact ⟨x, closure_singleton⟩ end Sober section genericPoints variable (α) in /-- The set of generic points of irreducible components. -/ def genericPoints : Set α := { x | closure {x} ∈ irreducibleComponents α } namespace genericPoints /-- The irreducible component of a generic point -/ def component (x : genericPoints α) : irreducibleComponents α := ⟨closure {x.1}, x.2⟩ lemma isGenericPoint (x : genericPoints α) : IsGenericPoint x.1 (component x).1 := rfl lemma component_injective [T0Space α] : Function.Injective (component (α := α)) := fun x y e ↦ Subtype.ext ((isGenericPoint x).eq (e ▸ isGenericPoint y)) /-- The generic point of an irreducible component. -/ noncomputable def ofComponent [QuasiSober α] (x : irreducibleComponents α) : genericPoints α := ⟨x.2.1.genericPoint, show _ ∈ irreducibleComponents α from (x.2.1.isGenericPoint_genericPoint (isClosed_of_mem_irreducibleComponents x.1 x.2)).symm ▸ x.2⟩ lemma isGenericPoint_ofComponent [QuasiSober α] (x : irreducibleComponents α) : IsGenericPoint (ofComponent x).1 x := x.2.1.isGenericPoint_genericPoint (isClosed_of_mem_irreducibleComponents x.1 x.2) @[simp] lemma component_ofComponent [QuasiSober α] (x : irreducibleComponents α) : component (ofComponent x) = x := Subtype.ext (isGenericPoint_ofComponent x) @[simp] lemma ofComponent_component [T0Space α] [QuasiSober α] (x : genericPoints α) : ofComponent (component x) = x := component_injective (component_ofComponent _) lemma component_surjective [QuasiSober α] : Function.Surjective (component (α := α)) := Function.HasRightInverse.surjective ⟨ofComponent, component_ofComponent⟩ lemma finite [T0Space α] (h : (irreducibleComponents α).Finite) : (genericPoints α).Finite := @Finite.of_injective _ _ h _ component_injective /-- In a sober space, the generic points corresponds bijectively to irreducible components -/ @[simps] noncomputable def equiv [T0Space α] [QuasiSober α] : genericPoints α ≃ irreducibleComponents α := ⟨component, ofComponent, ofComponent_component, component_ofComponent⟩ lemma closure [QuasiSober α] : closure (genericPoints α) = Set.univ := by refine Set.eq_univ_iff_forall.mpr fun x ↦ Set.subset_def.mp ?_ x mem_irreducibleComponent refine (isGenericPoint_ofComponent ⟨_, irreducibleComponent_mem_irreducibleComponents x⟩).symm.trans_subset (closure_mono ?_) exact Set.singleton_subset_iff.mpr (ofComponent _).2 end genericPoints lemma genericPoints_eq_singleton [QuasiSober α] [IrreducibleSpace α] [T0Space α] : genericPoints α = {genericPoint α} := by ext x rw [genericPoints, irreducibleComponents_eq_singleton] exact ⟨((genericPoint_spec α).eq · |>.symm), (· ▸ genericPoint_spec α)⟩ end genericPoints
Ring.lean
/- Copyright (c) 2022 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Kevin Klinge, Andrew Yang -/ import Mathlib.Algebra.Algebra.Defs import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.GroupWithZero.NonZeroDivisors import Mathlib.Algebra.Module.End import Mathlib.RingTheory.OreLocalization.Basic /-! # Module and Ring instances of Ore Localizations The `Monoid` and `DistribMulAction` instances and additive versions are provided in `Mathlib/RingTheory/OreLocalization/Basic.lean`. -/ assert_not_exists Subgroup universe u namespace OreLocalization section Module variable {R : Type*} [Semiring R] {S : Submonoid R} [OreSet S] variable {X : Type*} [AddCommMonoid X] [Module R X] protected theorem zero_smul (x : X[S⁻¹]) : (0 : R[S⁻¹]) • x = 0 := by induction' x with r s rw [OreLocalization.zero_def, oreDiv_smul_char 0 r 1 s 0 1 (by simp)]; simp protected theorem add_smul (y z : R[S⁻¹]) (x : X[S⁻¹]) : (y + z) • x = y • x + z • x := by induction' x with r₁ s₁ induction' y with r₂ s₂ induction' z with r₃ s₃ rcases oreDivAddChar' r₂ r₃ s₂ s₃ with ⟨ra, sa, ha, q⟩ rw [q] clear q rw [OreLocalization.expand' r₂ s₂ sa] rcases oreDivSMulChar' (sa • r₂) r₁ (sa * s₂) s₁ with ⟨rb, sb, hb, q⟩ rw [q] clear q have hs₃rasb : sb * ra * s₃ ∈ S := by rw [mul_assoc, ← ha] norm_cast apply SetLike.coe_mem rw [OreLocalization.expand _ _ _ hs₃rasb] have ha' : ↑((sb * sa) * s₂) = sb * ra * s₃ := by simp [ha, mul_assoc] rw [← Subtype.coe_eq_of_eq_mk ha'] rcases oreDivSMulChar' ((sb * ra) • r₃) r₁ (sb * sa * s₂) s₁ with ⟨rc, sc, hc, hc'⟩ rw [hc'] rw [oreDiv_add_char _ _ 1 sc (by simp [mul_assoc])] rw [OreLocalization.expand' (sa • r₂ + ra • r₃) (sa * s₂) (sc * sb)] simp only [smul_eq_mul, one_smul, Submonoid.smul_def, mul_add, Submonoid.coe_mul] at hb hc ⊢ rw [mul_assoc, hb, mul_assoc, ← mul_assoc _ ra, hc, ← mul_assoc, ← add_mul] rw [OreLocalization.smul_cancel'] simp only [add_smul, ← mul_assoc, smul_smul] end Module section Semiring variable {R : Type*} [Semiring R] {S : Submonoid R} [OreSet S] attribute [local instance] OreLocalization.oreEqv protected theorem zero_mul (x : R[S⁻¹]) : 0 * x = 0 := OreLocalization.zero_smul x protected theorem mul_zero (x : R[S⁻¹]) : x * 0 = 0 := OreLocalization.smul_zero x protected theorem left_distrib (x y z : R[S⁻¹]) : x * (y + z) = x * y + x * z := OreLocalization.smul_add _ _ _ theorem right_distrib (x y z : R[S⁻¹]) : (x + y) * z = x * z + y * z := OreLocalization.add_smul _ _ _ instance : Semiring R[S⁻¹] where __ := inferInstanceAs (MonoidWithZero (R[S⁻¹])) __ := inferInstanceAs (AddCommMonoid (R[S⁻¹])) left_distrib := OreLocalization.left_distrib right_distrib := right_distrib variable {X : Type*} [AddCommMonoid X] [Module R X] instance : Module R[S⁻¹] X[S⁻¹] where add_smul := OreLocalization.add_smul zero_smul := OreLocalization.zero_smul instance {R₀} [Semiring R₀] [Module R₀ X] [Module R₀ R] [IsScalarTower R₀ R X] [IsScalarTower R₀ R R] : Module R₀ X[S⁻¹] where add_smul r s x := by simp only [← smul_one_oreDiv_one_smul, add_smul, ← add_oreDiv] zero_smul x := by rw [← smul_one_oreDiv_one_smul, zero_smul, zero_oreDiv, zero_smul] @[simp] lemma nsmul_eq_nsmul (n : ℕ) (x : X[S⁻¹]) : letI inst := OreLocalization.instModuleOfIsScalarTower (R₀ := ℕ) (R := R) (X := X) (S := S) HSMul.hSMul (self := @instHSMul _ _ inst.toSMul) n x = n • x := by letI inst := OreLocalization.instModuleOfIsScalarTower (R₀ := ℕ) (R := R) (X := X) (S := S) exact congr($(AddCommMonoid.uniqueNatModule.2 inst).smul n x) /-- The ring homomorphism from `R` to `R[S⁻¹]`, mapping `r : R` to the fraction `r /ₒ 1`. -/ @[simps!] def numeratorRingHom : R →+* R[S⁻¹] where __ := numeratorHom map_zero' := by with_unfolding_all exact OreLocalization.zero_def map_add' _ _ := add_oreDiv.symm instance {R₀} [CommSemiring R₀] [Algebra R₀ R] : Algebra R₀ R[S⁻¹] where __ := inferInstanceAs (Module R₀ R[S⁻¹]) algebraMap := numeratorRingHom.comp (algebraMap R₀ R) commutes' r x := by induction' x using OreLocalization.ind with r₁ s₁ dsimp rw [mul_div_one, oreDiv_mul_char _ _ _ _ (algebraMap R₀ R r) s₁ (Algebra.commutes _ _).symm, Algebra.commutes, mul_one] smul_def' r x := by dsimp rw [Algebra.algebraMap_eq_smul_one, ← smul_eq_mul, smul_one_oreDiv_one_smul] section UMP variable {T : Type*} [Semiring T] variable (f : R →+* T) (fS : S →* Units T) variable (hf : ∀ s : S, f s = fS s) /-- The universal lift from a ring homomorphism `f : R →+* T`, which maps elements in `S` to units of `T`, to a ring homomorphism `R[S⁻¹] →+* T`. This extends the construction on monoids. -/ def universalHom : R[S⁻¹] →+* T := { universalMulHom f.toMonoidHom fS hf with map_zero' := by simp only [RingHom.toMonoidHom_eq_coe, OneHom.toFun_eq_coe, MonoidHom.toOneHom_coe] rw [OreLocalization.zero_def, universalMulHom_apply] simp map_add' := fun x y => by simp only [RingHom.toMonoidHom_eq_coe, OneHom.toFun_eq_coe, MonoidHom.toOneHom_coe] induction' x with r₁ s₁ induction' y with r₂ s₂ rcases oreDivAddChar' r₁ r₂ s₁ s₂ with ⟨r₃, s₃, h₃, h₃'⟩ rw [h₃'] clear h₃' simp only [smul_eq_mul, universalMulHom_apply, MonoidHom.coe_coe, Submonoid.smul_def] simp only [mul_inv_rev, MonoidHom.map_mul, RingHom.map_add, RingHom.map_mul, Units.val_mul] rw [mul_add, mul_assoc, ← mul_assoc _ (f s₃), hf, ← Units.val_mul] simp only [one_mul, inv_mul_cancel, Units.val_one] congr 1 rw [← mul_assoc] congr 1 norm_cast at h₃ have h₃' := Subtype.coe_eq_of_eq_mk h₃ rw [← Units.val_mul, ← mul_inv_rev, ← fS.map_mul, h₃'] rw [Units.inv_mul_eq_iff_eq_mul, Units.eq_mul_inv_iff_mul_eq, ← hf, ← hf] simp only [map_mul] } theorem universalHom_apply {r : R} {s : S} : universalHom f fS hf (r /ₒ s) = ((fS s)⁻¹ : Units T) * f r := rfl theorem universalHom_commutes {r : R} : universalHom f fS hf (numeratorHom r) = f r := by simp [numeratorHom_apply, universalHom_apply] theorem universalHom_unique (φ : R[S⁻¹] →+* T) (huniv : ∀ r : R, φ (numeratorHom r) = f r) : φ = universalHom f fS hf := RingHom.coe_monoidHom_injective <| universalMulHom_unique (RingHom.toMonoidHom f) fS hf (↑φ) huniv end UMP end Semiring section Ring variable {R : Type*} [Ring R] {S : Submonoid R} [OreSet S] variable {X : Type*} [AddCommGroup X] [Module R X] instance : Ring R[S⁻¹] where __ := inferInstanceAs (Semiring R[S⁻¹]) __ := inferInstanceAs (AddGroup R[S⁻¹]) @[simp] lemma zsmul_eq_zsmul (n : ℤ) (x : X[S⁻¹]) : letI inst := OreLocalization.instModuleOfIsScalarTower (R₀ := ℤ) (R := R) (X := X) (S := S) HSMul.hSMul (self := @instHSMul _ _ inst.toSMul) n x = n • x := by letI inst := OreLocalization.instModuleOfIsScalarTower (R₀ := ℤ) (R := R) (X := X) (S := S) exact congr($(AddCommGroup.uniqueIntModule.2 inst).smul n x) open nonZeroDivisors theorem numeratorHom_inj (hS : S ≤ nonZeroDivisorsLeft R) : Function.Injective (numeratorHom : R → R[S⁻¹]) := fun r₁ r₂ h => by rw [numeratorHom_apply, numeratorHom_apply, oreDiv_eq_iff] at h rcases h with ⟨u, v, h₁, h₂⟩ simp only [S.coe_one, mul_one, Submonoid.smul_def, smul_eq_mul] at h₁ h₂ rw [← h₂, ← sub_eq_zero, ← mul_sub] at h₁ exact (sub_eq_zero.mp (hS u.2 _ h₁)).symm theorem subsingleton_iff : Subsingleton R[S⁻¹] ↔ 0 ∈ S := by rw [← subsingleton_iff_zero_eq_one, OreLocalization.one_def, OreLocalization.zero_def, oreDiv_eq_iff] simp theorem nontrivial_iff : Nontrivial R[S⁻¹] ↔ 0 ∉ S := by rw [← not_subsingleton_iff_nontrivial, subsingleton_iff] theorem nontrivial_of_nonZeroDivisorsLeft [Nontrivial R] (hS : S ≤ nonZeroDivisorsLeft R) : Nontrivial R[S⁻¹] := nontrivial_iff.mpr (fun e ↦ one_ne_zero <| hS e 1 (zero_mul _)) theorem nontrivial_of_nonZeroDivisorsRight [Nontrivial R] (hS : S ≤ nonZeroDivisorsRight R) : Nontrivial R[S⁻¹] := nontrivial_iff.mpr (fun e ↦ one_ne_zero <| hS e 1 (mul_zero _)) theorem nontrivial_of_nonZeroDivisors [Nontrivial R] (hS : S ≤ R⁰) : Nontrivial R[S⁻¹] := nontrivial_of_nonZeroDivisorsLeft (hS.trans inf_le_left) end Ring noncomputable section DivisionRing open nonZeroDivisors variable {R : Type*} [Ring R] [Nontrivial R] [OreSet R⁰] instance nontrivial : Nontrivial R[R⁰⁻¹] := nontrivial_of_nonZeroDivisors (refl R⁰) variable [NoZeroDivisors R] open Classical in /-- The inversion of Ore fractions for a ring without zero divisors, satisfying `0⁻¹ = 0` and `(r /ₒ r')⁻¹ = r' /ₒ r` for `r ≠ 0`. -/ @[irreducible] protected def inv : R[R⁰⁻¹] → R[R⁰⁻¹] := liftExpand (fun r s => if hr : r = (0 : R) then (0 : R[R⁰⁻¹]) else s /ₒ ⟨r, mem_nonZeroDivisors_of_ne_zero hr⟩) (by intro r t s hst by_cases hr : r = 0 · simp [hr] · by_cases ht : t = 0 · exfalso apply nonZeroDivisors.coe_ne_zero ⟨_, hst⟩ simp [ht] · simp only [hr, ht, dif_neg, not_false_iff, or_self_iff, mul_eq_zero, smul_eq_mul] apply OreLocalization.expand) instance inv' : Inv R[R⁰⁻¹] := ⟨OreLocalization.inv⟩ open Classical in protected theorem inv_def {r : R} {s : R⁰} : (r /ₒ s)⁻¹ = if hr : r = (0 : R) then (0 : R[R⁰⁻¹]) else s /ₒ ⟨r, mem_nonZeroDivisors_of_ne_zero hr⟩ := by with_unfolding_all rfl protected theorem mul_inv_cancel (x : R[R⁰⁻¹]) (h : x ≠ 0) : x * x⁻¹ = 1 := by induction' x with r s rw [OreLocalization.inv_def, OreLocalization.one_def] have hr : r ≠ 0 := by rintro rfl simp at h simp only [hr] with_unfolding_all apply OreLocalization.mul_inv ⟨r, _⟩ protected theorem inv_zero : (0 : R[R⁰⁻¹])⁻¹ = 0 := by rw [OreLocalization.zero_def, OreLocalization.inv_def] simp instance : DivisionRing R[R⁰⁻¹] where mul_inv_cancel := OreLocalization.mul_inv_cancel inv_zero := OreLocalization.inv_zero nnqsmul := _ nnqsmul_def := fun _ _ => rfl qsmul := _ qsmul_def := fun _ _ => rfl end DivisionRing section CommSemiring variable {R : Type*} [CommSemiring R] {S : Submonoid R} [OreSet S] instance : CommSemiring R[S⁻¹] where __ := inferInstanceAs (Semiring R[S⁻¹]) __ := inferInstanceAs (CommMonoid R[S⁻¹]) end CommSemiring section CommRing variable {R : Type*} [CommRing R] {S : Submonoid R} [OreSet S] instance : CommRing R[S⁻¹] where __ := inferInstanceAs (Ring R[S⁻¹]) __ := inferInstanceAs (CommMonoid R[S⁻¹]) end CommRing section Field open nonZeroDivisors variable {R : Type*} [CommRing R] [Nontrivial R] [NoZeroDivisors R] [OreSet R⁰] noncomputable instance : Field R[R⁰⁻¹] where __ := inferInstanceAs (DivisionRing R[R⁰⁻¹]) __ := inferInstanceAs (CommMonoid R[R⁰⁻¹]) end Field end OreLocalization
Star.lean
/- Copyright (c) 2024 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.Order.Group.Abs import Mathlib.Algebra.Order.Monoid.Submonoid import Mathlib.Algebra.Order.Ring.Basic import Mathlib.Algebra.Order.Ring.Int import Mathlib.Algebra.Order.Star.Basic /-! # Star ordered ring structure on `ℤ` This file shows that `ℤ` is a `StarOrderedRing`. -/ open AddSubmonoid Set namespace Int @[simp] lemma addSubmonoid_closure_range_pow {n : ℕ} (hn : Even n) : closure (range fun x : ℤ ↦ x ^ n) = nonneg _ := by refine le_antisymm (closure_le.2 <| range_subset_iff.2 hn.pow_nonneg) fun x hx ↦ ?_ have : x = x.natAbs • 1 ^ n := by simpa [eq_comm (a := x)] using hx rw [this] exact nsmul_mem (subset_closure <| mem_range_self _) _ @[simp] lemma addSubmonoid_closure_range_mul_self : closure (range fun x : ℤ ↦ x * x) = nonneg _ := by simpa only [sq] using addSubmonoid_closure_range_pow even_two instance instStarOrderedRing : StarOrderedRing ℤ where le_iff a b := by simp [eq_comm, le_iff_exists_nonneg_add (a := a)] end Int
WithLp.lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Eric Wieser -/ import Mathlib.Analysis.Calculus.ContDiff.Operations import Mathlib.Analysis.Normed.Lp.PiLp /-! # Derivatives on `WithLp` -/ section PiLp open ContinuousLinearMap variable {𝕜 ι : Type*} {E : ι → Type*} {H : Type*} variable [NontriviallyNormedField 𝕜] [NormedAddCommGroup H] [∀ i, NormedAddCommGroup (E i)] [∀ i, NormedSpace 𝕜 (E i)] [NormedSpace 𝕜 H] [Fintype ι] (p) [Fact (1 ≤ p)] {n : WithTop ℕ∞} {f : H → PiLp p E} {f' : H →L[𝕜] PiLp p E} {t : Set H} {y : H} theorem contDiffWithinAt_piLp : ContDiffWithinAt 𝕜 n f t y ↔ ∀ i, ContDiffWithinAt 𝕜 n (fun x => f x i) t y := by rw [← (PiLp.continuousLinearEquiv p 𝕜 E).comp_contDiffWithinAt_iff, contDiffWithinAt_pi] rfl @[fun_prop] theorem contDiffWithinAt_piLp' (hf : ∀ i, ContDiffWithinAt 𝕜 n (fun x => f x i) t y) : ContDiffWithinAt 𝕜 n f t y := (contDiffWithinAt_piLp p).2 hf @[fun_prop] theorem contDiffWithinAt_piLp_apply {i : ι} {t : Set (PiLp p E)} {y : PiLp p E} : ContDiffWithinAt 𝕜 n (fun f : PiLp p E => f i) t y := (contDiffWithinAt_piLp p).1 contDiffWithinAt_id i theorem contDiffAt_piLp : ContDiffAt 𝕜 n f y ↔ ∀ i, ContDiffAt 𝕜 n (fun x => f x i) y := by rw [← (PiLp.continuousLinearEquiv p 𝕜 E).comp_contDiffAt_iff, contDiffAt_pi] rfl @[fun_prop] theorem contDiffAt_piLp' (hf : ∀ i, ContDiffAt 𝕜 n (fun x => f x i) y) : ContDiffAt 𝕜 n f y := (contDiffAt_piLp p).2 hf @[fun_prop] theorem contDiffAt_piLp_apply {i : ι} {y : PiLp p E} : ContDiffAt 𝕜 n (fun f : PiLp p E => f i) y := (contDiffAt_piLp p).1 contDiffAt_id i theorem contDiffOn_piLp : ContDiffOn 𝕜 n f t ↔ ∀ i, ContDiffOn 𝕜 n (fun x => f x i) t := by rw [← (PiLp.continuousLinearEquiv p 𝕜 E).comp_contDiffOn_iff, contDiffOn_pi] rfl @[fun_prop] theorem contDiffOn_piLp' (hf : ∀ i, ContDiffOn 𝕜 n (fun x => f x i) t) : ContDiffOn 𝕜 n f t := (contDiffOn_piLp p).2 hf @[fun_prop] theorem contDiffOn_piLp_apply {i : ι} {t : Set (PiLp p E)} : ContDiffOn 𝕜 n (fun f : PiLp p E => f i) t := (contDiffOn_piLp p).1 contDiffOn_id i theorem contDiff_piLp : ContDiff 𝕜 n f ↔ ∀ i, ContDiff 𝕜 n fun x => f x i := by rw [← (PiLp.continuousLinearEquiv p 𝕜 E).comp_contDiff_iff, contDiff_pi] rfl @[fun_prop] theorem contDiff_piLp' (hf : ∀ i, ContDiff 𝕜 n (fun x => f x i)) : ContDiff 𝕜 n f := (contDiff_piLp p).2 hf @[fun_prop] theorem contDiff_piLp_apply {i : ι} : ContDiff 𝕜 n (fun f : PiLp p E => f i) := (contDiff_piLp p).1 contDiff_id i end PiLp
Presheaf.lean
/- Copyright (c) 2024 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.CategoryTheory.Limits.FilteredColimitCommutesFiniteLimit import Mathlib.CategoryTheory.Limits.Elements /-! # Finite-limit-preserving presheaves In this file we prove that if `C` is a small finitely cocomplete category and `A : Cᵒᵖ ⥤ Type u` is a presheaf, then `CostructuredArrow yoneda A` is filtered (equivalently, the category of elements of `A` is cofiltered) if and only if `A` preserves finite limits. This is one of the keys steps of establishing the equivalence `Ind C ≌ (Cᵒᵖ ⥤ₗ Type u)` (here, `Cᵒᵖ ⥤ₗ Type u` is the category of left exact functors) for a *small* finitely cocomplete category `C`. ## Implementation notes In the entire file, we are careful about details like functor associativity to ensure that we do not end up in situations where we have morphisms like `colimit.ι F i ≫ f`, where the domain of `f` is `colimit G` where `F` and `G` are definitionally equal but not syntactically equal. In these situations, lemmas about `colimit.ι G i ≫ f` cannot be applied using `rw` and `simp`, forcing the use of `erw`. In particular, for us this means that `HasColimit.isoOfNatIso (Iso.refl _)` is better than `Iso.refl _` and that we should be very particular about functor associativity. The theorem is also true for large categories and the proof given here generalizes to this case on paper. However, our infrastructure for commuting finite limits of shape `J` and filtered colimits of shape `K` is fundamentally not equipped to deal with the case where not all limits of shape `K` exist. In fact, not even the definition `colimitLimitToLimitColimit` can be written down if not all limits of shape `K` exist. Refactoring this to the level of generality we need would be a major undertaking. Since the application to the category of Ind-objects only require the case where `C` is small, we leave this as a TODO. ## References * [M. Kashiwara, P. Schapira, *Categories and Sheaves*][Kashiwara2006], Proposition 3.3.13 * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1], Proposition 6.1.2 -/ open CategoryTheory Limits Functor universe v u namespace CategoryTheory.Limits section LargeCategory variable {C : Type u} [Category.{v} C] [HasFiniteColimits C] (A : Cᵒᵖ ⥤ Type v) /-- If `C` is a finitely cocomplete category and `A : Cᵒᵖ ⥤ Type u` is a presheaf that preserves finite limits, then `CostructuredArrow yoneda A` is filtered. One direction of Proposition 3.3.13 of [Kashiwara2006]. -/ theorem isFiltered_costructuredArrow_yoneda_of_preservesFiniteLimits [PreservesFiniteLimits A] : IsFiltered (CostructuredArrow yoneda A) := by suffices IsCofiltered A.Elements from IsFiltered.of_equivalence (CategoryOfElements.costructuredArrowYonedaEquivalence _) suffices HasFiniteLimits A.Elements from IsCofiltered.of_hasFiniteLimits A.Elements exact ⟨fun J _ _ => inferInstance⟩ end LargeCategory variable {C : Type u} [SmallCategory C] [HasFiniteColimits C] variable (A : Cᵒᵖ ⥤ Type u) namespace PreservesFiniteLimitsOfIsFilteredCostructuredArrowYonedaAux variable {J : Type} [SmallCategory J] [FinCategory J] (K : J ⥤ Cᵒᵖ) /-- (Implementation) This is the bifunctor we will apply "filtered colimits commute with finite limits" to. -/ def functorToInterchange : J ⥤ CostructuredArrow yoneda A ⥤ Type u := K ⋙ coyoneda ⋙ (whiskeringLeft _ _ _).obj (CostructuredArrow.proj _ _) /-- (Implementation) The definition of `functorToInterchange`. -/ @[simps!] def functorToInterchangeIso : functorToInterchange A K ≅ K ⋙ coyoneda ⋙ (whiskeringLeft _ _ _).obj (CostructuredArrow.proj _ _) := Iso.refl _ /-- (Implementation) One way to express the flipped version of our functor. We choose this association because the type of `Presheaf.tautologicalCocone` is `Cocone (CostructuredArrow.proj yoneda P ⋙ yoneda)`, so this association will show up in the proof. -/ @[simps!] def flipFunctorToInterchange : (functorToInterchange A K).flip ≅ ((CostructuredArrow.proj yoneda A ⋙ yoneda) ⋙ (whiskeringLeft J Cᵒᵖ (Type u)).obj K) := Iso.refl _ /-- (Implementation) A natural isomorphism we will need to construct `iso`. -/ @[simps! -fullyApplied hom_app] noncomputable def isoAux : (CostructuredArrow.proj yoneda A ⋙ yoneda ⋙ (evaluation Cᵒᵖ (Type u)).obj (limit K)) ≅ ((coyoneda ⋙ (whiskeringLeft (CostructuredArrow yoneda A) C (Type u)).obj (CostructuredArrow.proj yoneda A)).obj (limit K)) := Iso.refl _ /-- (Implementation) The isomorphism that proves that `A` preserves finite limits. -/ noncomputable def iso [IsFiltered (CostructuredArrow yoneda A)] : A.obj (limit K) ≅ limit (K ⋙ A) := calc A.obj (limit K) ≅ (colimit (CostructuredArrow.proj yoneda A ⋙ yoneda)).obj (limit K) := (IsColimit.coconePointUniqueUpToIso (Presheaf.isColimitTautologicalCocone A) (colimit.isColimit _)).app _ _ ≅ colimit (((CostructuredArrow.proj yoneda A) ⋙ yoneda) ⋙ (evaluation _ _).obj (limit K)) := (colimitObjIsoColimitCompEvaluation _ _) _ ≅ colimit ((CostructuredArrow.proj yoneda A) ⋙ yoneda ⋙ (evaluation _ _).obj (limit K)) := HasColimit.isoOfNatIso (Functor.associator _ _ _) _ ≅ colimit ((coyoneda ⋙ (whiskeringLeft _ _ _).obj (CostructuredArrow.proj yoneda A)).obj (limit K)) := HasColimit.isoOfNatIso (isoAux A K) _ ≅ colimit (limit (K ⋙ (coyoneda ⋙ (whiskeringLeft _ _ _).obj (CostructuredArrow.proj _ _)))) := HasColimit.isoOfNatIso (preservesLimitIso _ _) _ ≅ colimit (limit (functorToInterchange A K)) := HasColimit.isoOfNatIso (HasLimit.isoOfNatIso (functorToInterchangeIso A K).symm) _ ≅ limit (colimit (functorToInterchange A K).flip) := colimitLimitIso _ _ ≅ limit (colimit ((CostructuredArrow.proj yoneda A ⋙ yoneda) ⋙ (whiskeringLeft _ _ _).obj K)) := HasLimit.isoOfNatIso (HasColimit.isoOfNatIso (flipFunctorToInterchange A K)) _ ≅ limit (K ⋙ colimit (CostructuredArrow.proj yoneda A ⋙ yoneda)) := HasLimit.isoOfNatIso (colimitCompWhiskeringLeftIsoCompColimit (CostructuredArrow.proj yoneda A ⋙ yoneda) K) _ ≅ limit (K ⋙ A) := HasLimit.isoOfNatIso (isoWhiskerLeft _ (IsColimit.coconePointUniqueUpToIso (colimit.isColimit _) (Presheaf.isColimitTautologicalCocone A))) theorem iso_hom [IsFiltered (CostructuredArrow yoneda A)] : (iso A K).hom = limit.post K A := by -- We will have to use `ι_colimitLimitIso_limit_π` eventually, so let's start by -- transforming the goal into something from a colimit to a limit so that we can apply -- `limit.hom_ext` and `colimit.hom_ext`. dsimp [iso, -Iso.app_hom] simp only [Category.assoc] rw [Eq.comm, ← Iso.inv_comp_eq, ← Iso.inv_comp_eq] refine limit.hom_ext (fun j => colimit.hom_ext (fun i => ?_)) simp only [Category.assoc] -- `simp` is not too helpful here because we will need to apply `NatTrans.comp_app_assoc` -- backwards at certain points, so we rewrite the term manually. rw [HasLimit.isoOfNatIso_hom_π, HasLimit.isoOfNatIso_hom_π_assoc, limit.post_π, colimitObjIsoColimitCompEvaluation_ι_inv_assoc (CostructuredArrow.proj yoneda A ⋙ yoneda), Iso.app_inv, ← NatTrans.comp_app_assoc, colimit.comp_coconePointUniqueUpToIso_inv, Presheaf.tautologicalCocone_ι_app, HasColimit.isoOfNatIso_ι_hom_assoc, HasLimit.isoOfNatIso_hom_π_assoc, HasColimit.isoOfNatIso_ι_hom_assoc, HasColimit.isoOfNatIso_ι_hom_assoc, HasColimit.isoOfNatIso_ι_hom_assoc, ι_colimitLimitIso_limit_π_assoc, isoAux_hom_app, ← NatTrans.comp_app_assoc, ← NatTrans.comp_app_assoc, Category.assoc, HasLimit.isoOfNatIso_hom_π, preservesLimitIso_hom_π_assoc, Iso.symm_hom, ← NatTrans.comp_app_assoc, HasColimit.isoOfNatIso_ι_hom, ← NatTrans.comp_app_assoc, Category.assoc, ι_colimitCompWhiskeringLeftIsoCompColimit_hom, NatTrans.comp_app, Category.assoc, isoWhiskerLeft_hom, NatTrans.comp_app, Category.assoc, ← NatTrans.comp_app, ← whiskerLeft_comp, colimit.comp_coconePointUniqueUpToIso_hom] have := i.hom.naturality (limit.π K j) dsimp only [yoneda_obj_obj, Functor.const_obj_obj] at this rw [← this] ext simp theorem isIso_post [IsFiltered (CostructuredArrow yoneda A)] : IsIso (limit.post K A) := iso_hom A K ▸ inferInstance end PreservesFiniteLimitsOfIsFilteredCostructuredArrowYonedaAux attribute [local instance] PreservesFiniteLimitsOfIsFilteredCostructuredArrowYonedaAux.isIso_post /-- If `C` is a small finitely cocomplete category and `A : Cᵒᵖ ⥤ Type u` is a presheaf such that `CostructuredArrow yoneda A` is filtered, then `A` preserves finite limits. One direction of Proposition 3.3.13 of [Kashiwara2006]. -/ lemma preservesFiniteLimits_of_isFiltered_costructuredArrow_yoneda [IsFiltered (CostructuredArrow yoneda A)] : PreservesFiniteLimits A where preservesFiniteLimits _ _ _ := ⟨fun {_} => preservesLimit_of_isIso_post _ _⟩ /-- If `C` is a small finitely cocomplete category and `A : Cᵒᵖ ⥤ Type u` is a presheaf, then `CostructuredArrow yoneda A` is filtered if and only if `A` preserves finite limits. Proposition 3.3.13 of [Kashiwara2006]. -/ theorem isFiltered_costructuredArrow_yoneda_iff_nonempty_preservesFiniteLimits : IsFiltered (CostructuredArrow yoneda A) ↔ PreservesFiniteLimits A := ⟨fun _ => preservesFiniteLimits_of_isFiltered_costructuredArrow_yoneda A, fun _ => isFiltered_costructuredArrow_yoneda_of_preservesFiniteLimits A⟩ end CategoryTheory.Limits
Basic.lean
/- Copyright (c) 2024 Floris van Doorn and Hannah Scholz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Hannah Scholz -/ import Mathlib.Analysis.NormedSpace.Real import Mathlib.Data.ENat.Basic import Mathlib.Logic.Equiv.PartialEquiv import Mathlib.Topology.MetricSpace.ProperSpace.Real /-! # CW complexes This file defines (relative) CW complexes and proves basic properties about them using the classical approach of Whitehead. A CW complex is a topological space that is made by gluing closed disks of different dimensions together. ## Main definitions * `RelCWComplex C D`: the class of CW structures on a subspace `C` relative to a base set `D` of a topological space `X`. * `CWComplex C`: an abbreviation for `RelCWComplex C ∅`. The class of CW structures on a subspace `C` of the topological space `X`. * `openCell n`: indexed family of all open cells of dimension `n`. * `closedCell n`: indexed family of all closed cells of dimension `n`. * `cellFrontier n`: indexed family of the boundaries of cells of dimension `n`. * `skeleton C n`: the `n`-skeleton of the (relative) CW complex `C`. ## Main statements * `iUnion_openCell_eq_skeleton`: the skeletons can also be seen as a union of open cells. * `cellFrontier_subset_finite_openCell`: the edge of a cell is contained in a finite union of open cells of a lower dimension. ## Implementation notes * We use the historical definition of CW complexes, due to Whitehead: a CW complex is a collection of cells with attaching maps - all cells are subspaces of one ambient topological space. This way, we avoid having to work with a lot of different topological spaces. On the other hand, it requires the union of all cells to be closed. If that is not the case, you need to consider that union as a subspace of itself. * For a categorical approach that defines CW complexes via colimits and transfinite compositions, see `Mathlib/Topology/CWComplex/Abstract/Basic.lean`. The two approaches are equivalent but serve different purposes: * This approach is more convenient for concrete geometric arguments * The categorical approach is more suitable for abstract arguments and generalizations * The definition `RelCWComplex` does not require `X` to be a Hausdorff space. A lot of the lemmas will however require this property. * This definition is a class to ease working with different constructions and their properties. Overall this means that being a CW complex is treated more like a property than data. * The natural number is explicit in `openCell`, `closedCell` and `cellFrontier` because `cell n` and `cell m` might be the same type in an explicit CW complex even when `n` and `m` are different. * `CWComplex` is a separate class from `RelCWComplex`. This not only gives absolute CW complexes a better constructor but also aids typeclass inference: a construction on relative CW complexes may yield a base that for the special case of CW complexes is provably equal to the empty set but not definitionally so. In that case we define an instance specifically for absolute CW complexes and want this to be inferred over the relative version. Since the base is an `outParam` this is especially necessary since you cannot provide typeclass inference with a specified base. But having the type `CWComplex` be separate from `RelCWComplex` makes this specification possible. * For a similar reason to the previous bullet point we make the instance `CWComplex.instRelCWComplex` have high priority. For example, when talking about the type of cells `cell C` of an absolute CW complex `C`, this actually refers to `RelCWComplex.cell C` through this instance. Again, we want typeclass inference to first consider absolute CW structures. * For statements, the auxiliary construction `skeletonLT` is preferred over `skeleton` as it makes the base case of inductions easier. The statement about `skeleton` should then be derived from the one about `skeletonLT`. ## References * [A. Hatcher, *Algebraic Topology*][hatcher02] -/ noncomputable section open Metric Set namespace Topology /-- A CW complex of a topological space `X` relative to another subspace `D` is the data of its *`n`-cells* `cell n i` for each `n : ℕ` along with *attaching maps* that satisfy a number of properties with the most important being closure-finiteness (`mapsTo`) and weak topology (`closed'`). Note that this definition requires `C` and `D` to be closed subspaces. If `C` is not closed choose `X` to be `C`. -/ class RelCWComplex.{u} {X : Type u} [TopologicalSpace X] (C : Set X) (D : outParam (Set X)) where /-- The indexing type of the cells of dimension `n`. -/ cell (n : ℕ) : Type u /-- The characteristic map of the `n`-cell given by the index `i`. This map is a bijection when restricting to `ball 0 1`, where we consider `(Fin n → ℝ)` endowed with the maximum metric. -/ map (n : ℕ) (i : cell n) : PartialEquiv (Fin n → ℝ) X /-- The source of every characteristic map of dimension `n` is `(ball 0 1 : Set (Fin n → ℝ))`. -/ source_eq (n : ℕ) (i : cell n) : (map n i).source = ball 0 1 /-- The characteristic maps are continuous when restricting to `closedBall 0 1`. -/ continuousOn (n : ℕ) (i : cell n) : ContinuousOn (map n i) (closedBall 0 1) /-- The inverse of the restriction to `ball 0 1` is continuous on the image. -/ continuousOn_symm (n : ℕ) (i : cell n) : ContinuousOn (map n i).symm (map n i).target /-- The open cells are pairwise disjoint. Use `RelCWComplex.pairwiseDisjoint` or `RelCWComplex.disjoint_openCell_of_ne` instead. -/ pairwiseDisjoint' : (univ : Set (Σ n, cell n)).PairwiseDisjoint (fun ni ↦ map ni.1 ni.2 '' ball 0 1) /-- All open cells are disjoint with the base. Use `RelCWComplex.disjointBase` instead. -/ disjointBase' (n : ℕ) (i : cell n) : Disjoint (map n i '' ball 0 1) D /-- The boundary of a cell is contained in the union of the base with a finite union of closed cells of a lower dimension. Use `RelCWComplex.cellFrontier_subset_base_union_finite_closedCell` instead. -/ mapsTo (n : ℕ) (i : cell n) : ∃ I : Π m, Finset (cell m), MapsTo (map n i) (sphere 0 1) (D ∪ ⋃ (m < n) (j ∈ I m), map m j '' closedBall 0 1) /-- A CW complex has weak topology, i.e. a set `A` in `X` is closed iff its intersection with every closed cell and `D` is closed. Use `RelCWComplex.closed` instead. -/ closed' (A : Set X) (hAC : A ⊆ C) : ((∀ n j, IsClosed (A ∩ map n j '' closedBall 0 1)) ∧ IsClosed (A ∩ D)) → IsClosed A /-- The base `D` is closed. -/ isClosedBase : IsClosed D /-- The union of all closed cells equals `C`. Use `RelCWComplex.union` instead. -/ union' : D ∪ ⋃ (n : ℕ) (j : cell n), map n j '' closedBall 0 1 = C @[deprecated (since := "2025-02-20")] alias RelCWComplex.mapsto := Topology.RelCWComplex.mapsTo /-- Characterizing when a subspace `C` of a topological space `X` is a CW complex. Note that this requires `C` to be closed. If `C` is not closed choose `X` to be `C`. -/ class CWComplex.{u} {X : Type u} [TopologicalSpace X] (C : Set X) where /-- The indexing type of the cells of dimension `n`. -/ protected cell (n : ℕ) : Type u /-- The characteristic map of the `n`-cell given by the index `i`. This map is a bijection when restricting to `ball 0 1`, where we consider `(Fin n → ℝ)` endowed with the maximum metric. -/ protected map (n : ℕ) (i : cell n) : PartialEquiv (Fin n → ℝ) X /-- The source of every characteristic map of dimension `n` is `(ball 0 1 : Set (Fin n → ℝ))`. -/ protected source_eq (n : ℕ) (i : cell n) : (map n i).source = ball 0 1 /-- The characteristic maps are continuous when restricting to `closedBall 0 1`. -/ protected continuousOn (n : ℕ) (i : cell n) : ContinuousOn (map n i) (closedBall 0 1) /-- The inverse of the restriction to `ball 0 1` is continuous on the image. -/ protected continuousOn_symm (n : ℕ) (i : cell n) : ContinuousOn (map n i).symm (map n i).target /-- The open cells are pairwise disjoint. Use `CWComplex.pairwiseDisjoint` or `CWComplex.disjoint_openCell_of_ne` instead. -/ protected pairwiseDisjoint' : (univ : Set (Σ n, cell n)).PairwiseDisjoint (fun ni ↦ map ni.1 ni.2 '' ball 0 1) /-- The boundary of a cell is contained in a finite union of closed cells of a lower dimension. Use `CWComplex.mapsTo` or `CWComplex.cellFrontier_subset_finite_closedCell` instead. -/ protected mapsTo' (n : ℕ) (i : cell n) : ∃ I : Π m, Finset (cell m), MapsTo (map n i) (sphere 0 1) (⋃ (m < n) (j ∈ I m), map m j '' closedBall 0 1) /-- A CW complex has weak topology, i.e. a set `A` in `X` is closed iff its intersection with every closed cell is closed. Use `CWComplex.closed` instead. -/ protected closed' (A : Set X) (hAC : A ⊆ C) : (∀ n j, IsClosed (A ∩ map n j '' closedBall 0 1)) → IsClosed A /-- The union of all closed cells equals `C`. Use `CWComplex.union` instead. -/ protected union' : ⋃ (n : ℕ) (j : cell n), map n j '' closedBall 0 1 = C @[simps -isSimp] instance (priority := high) CWComplex.instRelCWComplex {X : Type*} [TopologicalSpace X] (C : Set X) [CWComplex C] : RelCWComplex C ∅ where cell := CWComplex.cell C map := CWComplex.map source_eq := CWComplex.source_eq continuousOn := CWComplex.continuousOn continuousOn_symm := CWComplex.continuousOn_symm pairwiseDisjoint' := CWComplex.pairwiseDisjoint' disjointBase' := by simp [disjoint_empty] mapsTo := by simpa only [empty_union] using CWComplex.mapsTo' closed' := by simpa only [inter_empty, isClosed_empty, and_true] using CWComplex.closed' isClosedBase := isClosed_empty union' := by simpa only [empty_union] using CWComplex.union' /-- A relative CW complex with an empty base is an absolute CW complex. -/ @[simps -isSimp] def RelCWComplex.toCWComplex {X : Type*} [TopologicalSpace X] (C : Set X) [RelCWComplex C ∅] : CWComplex C where cell := cell C map := map source_eq := source_eq continuousOn := continuousOn continuousOn_symm := continuousOn_symm pairwiseDisjoint' := pairwiseDisjoint' mapsTo' := by simpa using mapsTo (C := C) closed' := by simpa using closed' (C := C) union' := by simpa using union' (C := C) lemma RelCWComplex.toCWComplex_eq {X : Type*} [TopologicalSpace X] (C : Set X) [h : RelCWComplex C ∅] : (toCWComplex C).instRelCWComplex = h := rfl variable {X : Type*} [t : TopologicalSpace X] {C D : Set X} /-- The open `n`-cell given by the index `i`. Use this instead of `map n i '' ball 0 1` whenever possible. -/ def RelCWComplex.openCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : Set X := map n i '' ball 0 1 /-- The closed `n`-cell given by the index `i`. Use this instead of `map n i '' closedBall 0 1` whenever possible. -/ def RelCWComplex.closedCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : Set X := map n i '' closedBall 0 1 /-- The boundary of the `n`-cell given by the index `i`. Use this instead of `map n i '' sphere 0 1` whenever possible. -/ def RelCWComplex.cellFrontier [RelCWComplex C D] (n : ℕ) (i : cell C n) : Set X := map n i '' sphere 0 1 namespace CWComplex export RelCWComplex (cell map source_eq continuousOn continuousOn_symm mapsTo isClosedBase openCell closedCell cellFrontier) end CWComplex lemma CWComplex.mapsTo [CWComplex C] (n : ℕ) (i : cell C n) : ∃ I : Π m, Finset (cell C m), MapsTo (map n i) (sphere 0 1) (⋃ (m < n) (j ∈ I m), map m j '' closedBall 0 1) := by have := RelCWComplex.mapsTo n i simp_rw [empty_union] at this exact this @[deprecated (since := "2025-02-20")] alias CWComplex.mapsto := Topology.CWComplex.mapsTo lemma RelCWComplex.pairwiseDisjoint [RelCWComplex C D] : (univ : Set (Σ n, cell C n)).PairwiseDisjoint (fun ni ↦ openCell ni.1 ni.2) := RelCWComplex.pairwiseDisjoint' lemma RelCWComplex.disjointBase [RelCWComplex C D] (n : ℕ) (i : cell C n) : Disjoint (openCell n i) D := RelCWComplex.disjointBase' n i lemma RelCWComplex.disjoint_openCell_of_ne [RelCWComplex C D] {n m : ℕ} {i : cell C n} {j : cell C m} (ne : (⟨n, i⟩ : Σ n, cell C n) ≠ ⟨m, j⟩) : Disjoint (openCell n i) (openCell m j) := pairwiseDisjoint (mem_univ _) (mem_univ _) ne lemma RelCWComplex.cellFrontier_subset_base_union_finite_closedCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : ∃ I : Π m, Finset (cell C m), cellFrontier n i ⊆ D ∪ ⋃ (m < n) (j ∈ I m), closedCell m j := by rcases mapsTo n i with ⟨I, hI⟩ use I rw [mapsTo'] at hI exact hI lemma CWComplex.cellFrontier_subset_finite_closedCell [CWComplex C] (n : ℕ) (i : cell C n) : ∃ I : Π m, Finset (cell C m), cellFrontier n i ⊆ ⋃ (m < n) (j ∈ I m), closedCell m j := by rcases RelCWComplex.mapsTo n i with ⟨I, hI⟩ use I rw [mapsTo', empty_union] at hI exact hI lemma RelCWComplex.union [RelCWComplex C D] : D ∪ ⋃ (n : ℕ) (j : cell C n), closedCell n j = C := RelCWComplex.union' lemma CWComplex.union [CWComplex C] : ⋃ (n : ℕ) (j : cell C n), closedCell n j = C := by have := RelCWComplex.union' (C := C) (D := ∅) rw [empty_union] at this exact this lemma RelCWComplex.openCell_subset_closedCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : openCell n i ⊆ closedCell n i := image_mono Metric.ball_subset_closedBall lemma RelCWComplex.cellFrontier_subset_closedCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : cellFrontier n i ⊆ closedCell n i := image_mono Metric.sphere_subset_closedBall lemma RelCWComplex.cellFrontier_union_openCell_eq_closedCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : cellFrontier n i ∪ openCell n i = closedCell n i := by rw [cellFrontier, openCell, closedCell, ← image_union] congrm map n i '' ?_ exact sphere_union_ball lemma RelCWComplex.map_zero_mem_openCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : map n i 0 ∈ openCell n i := by apply mem_image_of_mem simp only [mem_ball, dist_self, zero_lt_one] lemma RelCWComplex.map_zero_mem_closedCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : map n i 0 ∈ closedCell n i := openCell_subset_closedCell _ _ (map_zero_mem_openCell _ _) /-- This is an auxiliary lemma used to prove `RelCWComplex.eq_of_eq_union_iUnion`. -/ private lemma RelCWComplex.subset_of_eq_union_iUnion [RelCWComplex C D] (I J : Π n, Set (cell C n)) (hIJ : D ∪ ⋃ (n : ℕ) (j : I n), openCell (C := C) n j = D ∪ ⋃ (n : ℕ) (j : J n), openCell (C := C) n j) (n : ℕ) : I n ⊆ J n := by intro i hi by_contra hJ have h : openCell n i ⊆ D ∪ ⋃ n, ⋃ (j : J n), openCell (C := C) n j := hIJ.symm ▸ subset_union_of_subset_right (subset_iUnion_of_subset n (subset_iUnion_of_subset ⟨i, hi⟩ (subset_refl (openCell n i)))) D have h' : Disjoint (openCell n i) (D ∪ ⋃ n, ⋃ (j : J n), openCell (C := C) n j) := by simp_rw [disjoint_union_right, disjoint_iUnion_right] exact ⟨disjointBase n i, fun m j ↦ disjoint_openCell_of_ne (by aesop)⟩ rw [disjoint_of_subset_iff_left_eq_empty h] at h' exact notMem_empty _ (h' ▸ map_zero_mem_openCell n i) lemma RelCWComplex.eq_of_eq_union_iUnion [RelCWComplex C D] (I J : Π n, Set (cell C n)) (hIJ : D ∪ ⋃ (n : ℕ) (j : I n), openCell (C := C) n j = D ∪ ⋃ (n : ℕ) (j : J n), openCell (C := C) n j) : I = J := by ext n x exact ⟨fun h ↦ subset_of_eq_union_iUnion I J hIJ n h, fun h ↦ subset_of_eq_union_iUnion J I hIJ.symm n h⟩ lemma CWComplex.eq_of_eq_union_iUnion [CWComplex C] (I J : Π n, Set (cell C n)) (hIJ : ⋃ (n : ℕ) (j : I n), openCell (C := C) n j = ⋃ (n : ℕ) (j : J n), openCell (C := C) n j) : I = J := by apply RelCWComplex.eq_of_eq_union_iUnion simp_rw [empty_union, hIJ] lemma RelCWComplex.isCompact_closedCell [RelCWComplex C D] {n : ℕ} {i : cell C n} : IsCompact (closedCell n i) := (isCompact_closedBall _ _).image_of_continuousOn (continuousOn n i) lemma RelCWComplex.isClosed_closedCell [RelCWComplex C D] [T2Space X] {n : ℕ} {i : cell C n} : IsClosed (closedCell n i) := isCompact_closedCell.isClosed lemma RelCWComplex.isCompact_cellFrontier [RelCWComplex C D] {n : ℕ} {i : cell C n} : IsCompact (cellFrontier n i) := (isCompact_sphere _ _).image_of_continuousOn ((continuousOn n i).mono sphere_subset_closedBall) lemma RelCWComplex.isClosed_cellFrontier [RelCWComplex C D] [T2Space X] {n : ℕ} {i : cell C n} : IsClosed (cellFrontier n i) := isCompact_cellFrontier.isClosed lemma RelCWComplex.closure_openCell_eq_closedCell [RelCWComplex C D] [T2Space X] {n : ℕ} {j : cell C n} : closure (openCell n j) = closedCell n j := by apply subset_antisymm (isClosed_closedCell.closure_subset_iff.2 (openCell_subset_closedCell n j)) rw [closedCell, ← closure_ball 0 (by exact one_ne_zero)] apply ContinuousOn.image_closure rw [closure_ball 0 (by exact one_ne_zero)] exact continuousOn n j lemma RelCWComplex.closed (C : Set X) {D : Set X} [RelCWComplex C D] [T2Space X] (A : Set X) (asubc : A ⊆ C) : IsClosed A ↔ (∀ n (j : cell C n), IsClosed (A ∩ closedCell n j)) ∧ IsClosed (A ∩ D) := by refine ⟨?_, closed' A asubc⟩ exact fun closedA ↦ ⟨fun _ _ ↦ closedA.inter isClosed_closedCell, closedA.inter (isClosedBase C)⟩ lemma CWComplex.closed (C : Set X) [CWComplex C] [T2Space X] (A : Set X) (asubc : A ⊆ C) : IsClosed A ↔ ∀ n (j : cell C n), IsClosed (A ∩ closedCell n j) := by have := RelCWComplex.closed C A asubc simp_all lemma RelCWComplex.closedCell_subset_complex [RelCWComplex C D] (n : ℕ) (j : cell C n) : closedCell n j ⊆ C := by simp_rw [← union] exact subset_union_of_subset_right (subset_iUnion₂ _ _) _ lemma RelCWComplex.openCell_subset_complex [RelCWComplex C D] (n : ℕ) (j : cell C n) : openCell n j ⊆ C := (openCell_subset_closedCell _ _).trans (closedCell_subset_complex _ _) lemma RelCWComplex.cellFrontier_subset_complex [RelCWComplex C D] (n : ℕ) (j : cell C n) : cellFrontier n j ⊆ C := (cellFrontier_subset_closedCell n j).trans (closedCell_subset_complex n j) lemma RelCWComplex.closedCell_zero_eq_singleton [RelCWComplex C D] {j : cell C 0} : closedCell 0 j = {map 0 j ![]} := by simp [closedCell, Matrix.empty_eq] lemma RelCWComplex.openCell_zero_eq_singleton [RelCWComplex C D] {j : cell C 0} : openCell 0 j = {map 0 j ![]} := by simp [openCell, Matrix.empty_eq] lemma RelCWComplex.cellFrontier_zero_eq_empty [RelCWComplex C D] {j : cell C 0} : cellFrontier 0 j = ∅ := by simp [cellFrontier, sphere_eq_empty_of_subsingleton] lemma RelCWComplex.base_subset_complex [RelCWComplex C D] : D ⊆ C := by simp_rw [← union] exact subset_union_left lemma RelCWComplex.isClosed [T2Space X] [RelCWComplex C D] : IsClosed C := by rw [closed C C (by rfl)] constructor · intros rw [inter_eq_right.2 (closedCell_subset_complex _ _)] exact isClosed_closedCell · rw [inter_eq_right.2 base_subset_complex] exact isClosedBase C /-- A helper lemma that is essentially the same as `RelCWComplex.iUnion_openCell_eq_skeletonLT`. Use that lemma instead. -/ private lemma RelCWComplex.iUnion_openCell_eq_iUnion_closedCell [RelCWComplex C D] (n : ℕ∞) : D ∪ ⋃ (m : ℕ) (_ : m < n) (j : cell C m), openCell m j = D ∪ ⋃ (m : ℕ) (_ : m < n) (j : cell C m), closedCell m j := by apply subset_antisymm · apply union_subset · exact subset_union_left · apply iUnion₂_subset fun m hm ↦ iUnion_subset fun j ↦ ?_ apply subset_union_of_subset_right apply subset_iUnion₂_of_subset m hm apply subset_iUnion_of_subset j exact openCell_subset_closedCell m j · apply union_subset subset_union_left refine iUnion₂_subset fun m hm ↦ iUnion_subset fun j ↦ ?_ rw [← cellFrontier_union_openCell_eq_closedCell] apply union_subset · induction m using Nat.case_strong_induction_on with | hz => simp [cellFrontier_zero_eq_empty] | hi m hm' => obtain ⟨I, hI⟩ := cellFrontier_subset_base_union_finite_closedCell (m + 1) j apply hI.trans apply union_subset subset_union_left apply iUnion₂_subset fun l hl ↦ iUnion₂_subset fun i _ ↦ ?_ rw [← cellFrontier_union_openCell_eq_closedCell] apply union_subset · exact (hm' l (Nat.le_of_lt_succ hl) ((ENat.coe_lt_coe.2 hl).trans hm) i) · apply subset_union_of_subset_right exact subset_iUnion₂_of_subset l ((ENat.coe_lt_coe.2 hl).trans hm) <| subset_iUnion _ i · exact subset_union_of_subset_right (subset_iUnion₂_of_subset m hm (subset_iUnion _ j)) _ lemma RelCWComplex.union_iUnion_openCell_eq_complex [RelCWComplex C D] : D ∪ ⋃ (n : ℕ) (j : cell C n), openCell n j = C := by suffices D ∪ ⋃ n, ⋃ (j : cell C n), openCell n j = D ∪ ⋃ (m : ℕ) (_ : m < (⊤ : ℕ∞)) (j : cell C m), closedCell m j by simpa [union] using this simp_rw [← RelCWComplex.iUnion_openCell_eq_iUnion_closedCell, ENat.coe_lt_top, iUnion_true] lemma CWComplex.iUnion_openCell_eq_complex [CWComplex C] : ⋃ (n : ℕ) (j : cell C n), openCell n j = C := by simpa using RelCWComplex.union_iUnion_openCell_eq_complex (C := C) (D := ∅) /-- The contrapositive of `disjoint_openCell_of_ne`. -/ lemma RelCWComplex.eq_of_not_disjoint_openCell [RelCWComplex C D] {n : ℕ} {j : cell C n} {m : ℕ} {i : cell C m} (h : ¬ Disjoint (openCell n j) (openCell m i)) : (⟨n, j⟩ : (Σ n, cell C n)) = ⟨m, i⟩ := by contrapose! h exact disjoint_openCell_of_ne h lemma RelCWComplex.disjoint_base_iUnion_openCell [RelCWComplex C D] : Disjoint D (⋃ (n : ℕ) (j : cell C n), openCell n j) := by simp_rw [disjoint_iff_inter_eq_empty, inter_iUnion, iUnion_eq_empty] intro n i rw [inter_comm, (disjointBase n i).inter_eq] /-- If for all `m ≤ n` and every `i : cell C m` the intersection `A ∩ closedCell m j` is closed and `A ∩ D` is closed then `A ∩ cellFrontier (n + 1) j` is closed for every `j : cell C (n + 1)`. -/ lemma RelCWComplex.isClosed_inter_cellFrontier_succ_of_le_isClosed_inter_closedCell [RelCWComplex C D] [T2Space X] {A : Set X} {n : ℕ} (hn : ∀ m ≤ n, ∀ (j : cell C m), IsClosed (A ∩ closedCell m j)) (j : cell C (n + 1)) (hD : IsClosed (A ∩ D)) : IsClosed (A ∩ cellFrontier (n + 1) j) := by -- this is a consequence of `cellFrontier_subset_base_union_finite_closedCell` obtain ⟨I, hI⟩ := cellFrontier_subset_base_union_finite_closedCell (n + 1) j rw [← inter_eq_right.2 hI, ← inter_assoc] refine IsClosed.inter ?_ isClosed_cellFrontier simp_rw [inter_union_distrib_left, inter_iUnion, ← iUnion_subtype (fun m ↦ m < n + 1) (fun m ↦ ⋃ i ∈ I m, A ∩ closedCell m i)] apply hD.union apply isClosed_iUnion_of_finite intro ⟨m, mlt⟩ rw [← iUnion_subtype (fun i ↦ i ∈ I m) (fun i ↦ A ∩ closedCell m i.1)] exact isClosed_iUnion_of_finite (fun ⟨j, _⟩ ↦ hn m (Nat.le_of_lt_succ mlt) j) lemma CWComplex.isClosed_inter_cellFrontier_succ_of_le_isClosed_inter_closedCell [CWComplex C] [T2Space X] {A : Set X} {n : ℕ} (hn : ∀ m ≤ n, ∀ (j : cell C m), IsClosed (A ∩ closedCell m j)) (j : cell C (n + 1)) : IsClosed (A ∩ cellFrontier (n + 1) j) := RelCWComplex.isClosed_inter_cellFrontier_succ_of_le_isClosed_inter_closedCell hn j (by simp only [inter_empty, isClosed_empty]) /-- If for every cell either `A ∩ openCell n j` or `A ∩ closedCell n j` is closed then `A` is closed. -/ lemma RelCWComplex.isClosed_of_isClosed_inter_openCell_or_isClosed_inter_closedCell [RelCWComplex C D] [T2Space X] {A : Set X} (hAC : A ⊆ C) (hDA : IsClosed (A ∩ D)) (h : ∀ n (_ : 0 < n), ∀ (j : cell C n), IsClosed (A ∩ openCell n j) ∨ IsClosed (A ∩ closedCell n j)) : IsClosed A := by rw [closed C A hAC] refine ⟨?_, hDA⟩ intro n j induction n using Nat.case_strong_induction_on with | hz => rw [closedCell_zero_eq_singleton] exact isClosed_inter_singleton | hi n hn => specialize h n.succ n.zero_lt_succ j rcases h with h1 | h2 · rw [← cellFrontier_union_openCell_eq_closedCell, inter_union_distrib_left] exact (isClosed_inter_cellFrontier_succ_of_le_isClosed_inter_closedCell hn j hDA).union h1 · exact h2 /-- If for every cell either `A ∩ openCell n j` or `A ∩ closedCell n j` is closed then `A` is closed. -/ lemma CWComplex.isClosed_of_isClosed_inter_openCell_or_isClosed_inter_closedCell [CWComplex C] [T2Space X] {A : Set X} (hAC : A ⊆ C) (h : ∀ n (_ : 0 < n), ∀ (j : cell C n), IsClosed (A ∩ openCell n j) ∨ IsClosed (A ∩ closedCell n j)) : IsClosed A := RelCWComplex.isClosed_of_isClosed_inter_openCell_or_isClosed_inter_closedCell hAC (by simp) h /-- A version of `cellFrontier_subset_base_union_finite_closedCell` using open cells: The boundary of a cell is contained in a finite union of open cells of a lower dimension. -/ lemma RelCWComplex.cellFrontier_subset_finite_openCell [RelCWComplex C D] (n : ℕ) (i : cell C n) : ∃ I : Π m, Finset (cell C m), cellFrontier n i ⊆ D ∪ (⋃ (m < n) (j ∈ I m), openCell m j) := by induction n using Nat.case_strong_induction_on with | hz => simp [cellFrontier_zero_eq_empty] | hi n hn => -- We apply `cellFrontier_subset_base_union_finite_closedCell` once and then apply -- the induction hypothesis to the finitely many cells that -- `cellFrontier_subset_base_union_finite_closedCell` gives us. classical obtain ⟨J, hJ⟩ := cellFrontier_subset_base_union_finite_closedCell n.succ i choose p hp using hn let I m := J m ∪ ((Finset.range n.succ).biUnion (fun l ↦ (J l).biUnion (fun y ↦ if h : l ≤ n then p l h y m else ∅))) use I intro x hx specialize hJ hx simp only [mem_union, mem_iUnion, exists_prop] at hJ ⊢ rcases hJ with hJ | hJ · exact .inl hJ obtain ⟨l, hln, j, hj, hxj⟩ := hJ rw [← cellFrontier_union_openCell_eq_closedCell] at hxj rcases hxj with hxj | hxj · specialize hp l (Nat.le_of_lt_succ hln) j hxj simp_rw [mem_union, mem_iUnion, exists_prop] at hp refine .imp_right (fun ⟨k, hkl, i, hi, hxi⟩ ↦ ⟨k, lt_trans hkl hln, i, ?_, hxi⟩) hp simp only [Nat.succ_eq_add_one, Finset.mem_union, Finset.mem_biUnion, Finset.mem_range, I] exact .inr ⟨l, hln, j, hj, by simp [Nat.le_of_lt_succ hln, hi]⟩ · right use l, hln, j simp only [Nat.succ_eq_add_one, Finset.mem_union, I] exact ⟨Or.intro_left _ hj, hxj⟩ /-- A version of `cellFrontier_subset_finite_closedCell` using open cells: The boundary of a cell is contained in a finite union of open cells of a lower dimension. -/ lemma CWComplex.cellFrontier_subset_finite_openCell [CWComplex C] (n : ℕ) (i : cell C n) : ∃ I : Π m, Finset (cell C m), cellFrontier n i ⊆ ⋃ (m < n) (j ∈ I m), openCell m j := by simpa using RelCWComplex.cellFrontier_subset_finite_openCell n i /-- A non-standard definition of the `n`-skeleton of a CW complex for `n ∈ ℕ ∪ {∞}`. This allows the base case of induction to be about the base instead of being about the union of the base and some points. The standard `skeleton` is defined in terms of `skeletonLT`. `skeletonLT` is preferred in statements. You should then derive the statement about `skeleton`. -/ def RelCWComplex.skeletonLT (C : Set X) {D : Set X} [RelCWComplex C D] (n : ℕ∞) : Set X := D ∪ ⋃ (m : ℕ) (_ : m < n) (j : cell C m), closedCell m j /-- The `n`-skeleton of a CW complex, for `n ∈ ℕ ∪ {∞}`. For statements use `skeletonLT` instead and then derive the statement about `skeleton`. -/ def RelCWComplex.skeleton (C : Set X) {D : Set X} [RelCWComplex C D] (n : ℕ∞) : Set X := skeletonLT C (n + 1) namespace CWComplex export RelCWComplex (skeletonLT skeleton) end CWComplex lemma RelCWComplex.skeletonLT_zero_eq_base [RelCWComplex C D] : skeletonLT C 0 = D := by simp only [skeletonLT, ENat.not_lt_zero, iUnion_of_empty, iUnion_empty, union_empty] lemma CWComplex.skeletonLT_zero_eq_empty [CWComplex C] : skeletonLT C 0 = ∅ := RelCWComplex.skeletonLT_zero_eq_base @[simp] lemma RelCWComplex.skeletonLT_top [RelCWComplex C D] : skeletonLT C ⊤ = C := by simp [skeletonLT, union] @[simp] lemma RelCWComplex.skeleton_top [RelCWComplex C D] : skeleton C ⊤ = C := skeletonLT_top lemma RelCWComplex.skeletonLT_mono [RelCWComplex C D] {n m : ℕ∞} (h : m ≤ n) : skeletonLT C m ⊆ skeletonLT C n := by apply union_subset_union_right intro x xmem simp_rw [mem_iUnion, exists_prop] at xmem ⊢ obtain ⟨l, lltm, xmeml⟩ := xmem exact ⟨l, lt_of_lt_of_le lltm h, xmeml⟩ lemma RelCWComplex.skeletonLT_monotone [RelCWComplex C D] : Monotone (skeletonLT C) := fun _ _ h ↦ skeletonLT_mono h lemma RelCWComplex.skeleton_mono [RelCWComplex C D] {n m : ℕ∞} (h : m ≤ n) : skeleton C m ⊆ skeleton C n := skeletonLT_mono (add_le_add_right h 1) lemma RelCWComplex.skeleton_monotone [RelCWComplex C D] : Monotone (skeleton C) := fun _ _ h ↦ skeleton_mono h lemma RelCWComplex.skeletonLT_subset_complex [RelCWComplex C D] {n : ℕ∞} : skeletonLT C n ⊆ C := by simp_rw [← skeletonLT_top (C := C) (D := D)] exact skeletonLT_mono (OrderTop.le_top n) lemma RelCWComplex.skeleton_subset_complex [RelCWComplex C D] {n : ℕ∞} : skeleton C n ⊆ C := skeletonLT_subset_complex lemma RelCWComplex.closedCell_subset_skeletonLT [RelCWComplex C D] (n : ℕ) (j : cell C n) : closedCell n j ⊆ skeletonLT C (n + 1) := by intro x xmem right simp_rw [mem_iUnion, exists_prop] refine ⟨n, (by norm_cast; exact lt_add_one n), ⟨j,xmem⟩⟩ lemma RelCWComplex.closedCell_subset_skeleton [RelCWComplex C D] (n : ℕ) (j : cell C n) : closedCell n j ⊆ skeleton C n := closedCell_subset_skeletonLT n j lemma RelCWComplex.openCell_subset_skeletonLT [RelCWComplex C D] (n : ℕ) (j : cell C n) : openCell n j ⊆ skeletonLT C (n + 1) := (openCell_subset_closedCell _ _).trans (closedCell_subset_skeletonLT _ _) lemma RelCWComplex.openCell_subset_skeleton [RelCWComplex C D] (n : ℕ) (j : cell C n) : openCell n j ⊆ skeleton C n := (openCell_subset_closedCell _ _).trans (closedCell_subset_skeleton _ _) lemma RelCWComplex.cellFrontier_subset_skeletonLT [RelCWComplex C D] (n : ℕ) (j : cell C n) : cellFrontier n j ⊆ skeletonLT C n := by obtain ⟨I, hI⟩ := cellFrontier_subset_base_union_finite_closedCell n j apply subset_trans hI apply union_subset_union_right intro x xmem simp only [mem_iUnion, exists_prop] at xmem ⊢ obtain ⟨i, iltn, j, _, xmem⟩ := xmem exact ⟨i, by norm_cast, j, xmem⟩ lemma RelCWComplex.cellFrontier_subset_skeleton [RelCWComplex C D] (n : ℕ) (j : cell C (n + 1)) : cellFrontier (n + 1) j ⊆ skeleton C n := cellFrontier_subset_skeletonLT _ _ lemma RelCWComplex.iUnion_cellFrontier_subset_skeletonLT [RelCWComplex C D] (l : ℕ) : ⋃ (j : cell C l), cellFrontier l j ⊆ skeletonLT C l := iUnion_subset (fun _ ↦ cellFrontier_subset_skeletonLT _ _) lemma RelCWComplex.iUnion_cellFrontier_subset_skeleton [RelCWComplex C D] (l : ℕ) : ⋃ (j : cell C l), cellFrontier l j ⊆ skeleton C l := (iUnion_cellFrontier_subset_skeletonLT l).trans (skeletonLT_mono le_self_add) lemma RelCWComplex.base_subset_skeletonLT [RelCWComplex C D] (n : ℕ∞) : D ⊆ skeletonLT C n := subset_union_left lemma RelCWComplex.base_subset_skeleton [RelCWComplex C D] (n : ℕ∞) : D ⊆ skeleton C n := base_subset_skeletonLT (n + 1) lemma RelCWComplex.skeletonLT_union_iUnion_closedCell_eq_skeletonLT_succ [RelCWComplex C D] (n : ℕ) : skeletonLT C n ∪ ⋃ (j : cell C n), closedCell n j = skeletonLT C (n + 1) := by rw [skeletonLT, skeletonLT, union_assoc] congr norm_cast exact (biUnion_lt_succ _ _).symm lemma RelCWComplex.skeleton_union_iUnion_closedCell_eq_skeleton_succ [RelCWComplex C D] (n : ℕ) : skeleton C n ∪ ⋃ (j : cell C (n + 1)), closedCell (n + 1) j = skeleton C (n + 1) := skeletonLT_union_iUnion_closedCell_eq_skeletonLT_succ _ /-- A version of the definition of `skeletonLT` with open cells. -/ lemma RelCWComplex.iUnion_openCell_eq_skeletonLT [RelCWComplex C D] (n : ℕ∞) : D ∪ ⋃ (m : ℕ) (_ : m < n) (j : cell C m), openCell m j = skeletonLT C n := RelCWComplex.iUnion_openCell_eq_iUnion_closedCell n lemma CWComplex.iUnion_openCell_eq_skeletonLT [CWComplex C] (n : ℕ∞) : ⋃ (m : ℕ) (_ : m < n) (j : cell C m), openCell m j = skeletonLT C n := by rw [← RelCWComplex.iUnion_openCell_eq_skeletonLT, empty_union] lemma RelCWComplex.iUnion_openCell_eq_skeleton [RelCWComplex C D] (n : ℕ∞) : D ∪ ⋃ (m : ℕ) (_ : m < n + 1) (j : cell C m), openCell m j = skeleton C n := iUnion_openCell_eq_skeletonLT _ lemma CWComplex.iUnion_openCell_eq_skeleton [CWComplex C] (n : ℕ∞) : ⋃ (m : ℕ) (_ : m < n + 1) (j : cell C m), openCell m j = skeleton C n := iUnion_openCell_eq_skeletonLT _ lemma RelCWComplex.iUnion_skeletonLT_eq_complex [RelCWComplex C D] : ⋃ (n : ℕ), skeletonLT C n = C := by apply subset_antisymm (iUnion_subset_iff.2 fun _ ↦ skeletonLT_subset_complex) simp_rw [← union_iUnion_openCell_eq_complex, union_subset_iff, iUnion₂_subset_iff] exact ⟨subset_iUnion_of_subset 0 (base_subset_skeletonLT ↑0), fun n i ↦ subset_iUnion_of_subset _ (openCell_subset_skeletonLT n i)⟩ lemma RelCWComplex.iUnion_skeleton_eq_complex [RelCWComplex C D] : ⋃ (n : ℕ), skeleton C n = C := by apply subset_antisymm (iUnion_subset_iff.2 fun _ ↦ skeleton_subset_complex) simp_rw [← union_iUnion_openCell_eq_complex, union_subset_iff, iUnion₂_subset_iff] exact ⟨subset_iUnion_of_subset 0 (base_subset_skeleton ↑0), fun n i ↦ subset_iUnion_of_subset _ (openCell_subset_skeleton n i)⟩ lemma RelCWComplex.mem_skeletonLT_iff [RelCWComplex C D] {n : ℕ∞} {x : X} : x ∈ skeletonLT C n ↔ x ∈ D ∨ ∃ (m : ℕ) (_ : m < n) (j : cell C m), x ∈ openCell m j := by simp [← iUnion_openCell_eq_skeletonLT] lemma CWComplex.mem_skeletonLT_iff [CWComplex C] {n : ℕ∞} {x : X} : x ∈ skeletonLT C n ↔ ∃ (m : ℕ) (_ : m < n) (j : cell C m), x ∈ openCell m j := by simp [← iUnion_openCell_eq_skeletonLT] lemma RelCWComplex.mem_skeleton_iff [RelCWComplex C D] {n : ℕ∞} {x : X} : x ∈ skeleton C n ↔ x ∈ D ∨ ∃ (m : ℕ) (_ : m ≤ n) (j : cell C m), x ∈ openCell m j := by rw [skeleton, mem_skeletonLT_iff] suffices ∀ (m : ℕ), m < n + 1 ↔ m ≤ n by simp_rw [this] intro m cases n · simp · rw [← Nat.cast_one, ← Nat.cast_add, Nat.cast_lt, Nat.cast_le, Order.lt_add_one_iff] lemma CWComplex.exists_mem_openCell_of_mem_skeleton [CWComplex C] {n : ℕ∞} {x : X} : x ∈ skeleton C n ↔ ∃ (m : ℕ) (_ : m ≤ n) (j : cell C m), x ∈ openCell m j := by rw [RelCWComplex.mem_skeleton_iff, mem_empty_iff_false, false_or] /-- A skeleton and an open cell of a higher dimension are disjoint. -/ lemma RelCWComplex.disjoint_skeletonLT_openCell [RelCWComplex C D] {n : ℕ∞} {m : ℕ} {j : cell C m} (hnm : n ≤ m) : Disjoint (skeletonLT C n) (openCell m j) := by -- This is a consequence of `iUnion_openCell_eq_skeletonLT` and `disjoint_openCell_of_ne` simp_rw [← iUnion_openCell_eq_skeletonLT, disjoint_union_left, disjoint_iUnion_left] refine ⟨(disjointBase m j).symm, ?_⟩ intro l hln i apply disjoint_openCell_of_ne intro simp_all only [Sigma.mk.inj_iff] exact (lt_self_iff_false m).mp (ENat.coe_lt_coe.1 (hln.trans_le hnm)) /-- A skeleton and an open cell of a higher dimension are disjoint. -/ lemma RelCWComplex.disjoint_skeleton_openCell [RelCWComplex C D] {n : ℕ∞} {m : ℕ} {j : cell C m} (nlem : n < m) : Disjoint (skeleton C n) (openCell m j) := disjoint_skeletonLT_openCell (Order.add_one_le_of_lt nlem) /-- A skeleton intersected with a closed cell of a higher dimension is the skeleton intersected with the boundary of the cell. -/ lemma RelCWComplex.skeletonLT_inter_closedCell_eq_skeletonLT_inter_cellFrontier [RelCWComplex C D] {n : ℕ∞} {m : ℕ} {j : cell C m} (hnm : n ≤ m) : skeletonLT C n ∩ closedCell m j = skeletonLT C n ∩ cellFrontier m j := by refine subset_antisymm ?_ (inter_subset_inter_right _ (cellFrontier_subset_closedCell _ _)) rw [← cellFrontier_union_openCell_eq_closedCell, inter_union_distrib_left] apply union_subset (by rfl) rw [(disjoint_skeletonLT_openCell hnm).inter_eq] exact empty_subset _ /-- Version of `skeletonLT_inter_closedCell_eq_skeletonLT_inter_cellFrontier` using `skeleton`. -/ lemma RelCWComplex.skeleton_inter_closedCell_eq_skeleton_inter_cellFrontier [RelCWComplex C D] {n : ℕ∞} {m : ℕ} {j : cell C m} (hnm : n < m) : skeleton C n ∩ closedCell m j = skeleton C n ∩ cellFrontier m j := skeletonLT_inter_closedCell_eq_skeletonLT_inter_cellFrontier (Order.add_one_le_of_lt hnm) lemma RelCWComplex.disjoint_interior_base_closedCell [T2Space X] [RelCWComplex C D] {n : ℕ} {j : cell C n} : Disjoint (interior D) (closedCell n j) := by rw [disjoint_iff_inter_eq_empty] by_contra h push_neg at h rw [← closure_openCell_eq_closedCell, inter_comm, closure_inter_open_nonempty_iff isOpen_interior] at h rcases h with ⟨x, xmemcell, xmemD⟩ suffices x ∈ skeletonLT C 0 ∩ openCell n j by rwa [(disjoint_skeletonLT_openCell n.cast_nonneg').inter_eq] at this exact ⟨base_subset_skeletonLT 0 (interior_subset xmemD), xmemcell⟩ lemma RelCWComplex.disjoint_interior_base_iUnion_closedCell [T2Space X] [RelCWComplex C D] : Disjoint (interior D) (⋃ (n : ℕ) (j : cell C n), closedCell n j) := by simp_rw [disjoint_iff_inter_eq_empty, inter_iUnion, disjoint_interior_base_closedCell.inter_eq, iUnion_empty] namespace CWComplex export RelCWComplex (pairwiseDisjoint disjoint_openCell_of_ne openCell_subset_closedCell cellFrontier_subset_closedCell cellFrontier_union_openCell_eq_closedCell map_zero_mem_openCell map_zero_mem_closedCell isCompact_closedCell isClosed_closedCell isCompact_cellFrontier isClosed_cellFrontier closure_openCell_eq_closedCell skeletonLT_top skeleton_top skeletonLT_mono skeleton_mono skeletonLT_monotone skeleton_monotone skeletonLT_subset_complex skeleton_subset_complex closedCell_subset_skeletonLT closedCell_subset_skeleton closedCell_subset_complex openCell_subset_skeletonLT openCell_subset_skeleton openCell_subset_complex cellFrontier_subset_skeletonLT cellFrontier_subset_skeleton cellFrontier_subset_complex iUnion_cellFrontier_subset_skeletonLT iUnion_cellFrontier_subset_skeleton closedCell_zero_eq_singleton openCell_zero_eq_singleton cellFrontier_zero_eq_empty isClosed skeletonLT_union_iUnion_closedCell_eq_skeletonLT_succ skeleton_union_iUnion_closedCell_eq_skeleton_succ iUnion_skeletonLT_eq_complex iUnion_skeleton_eq_complex eq_of_not_disjoint_openCell disjoint_skeletonLT_openCell disjoint_skeleton_openCell skeletonLT_inter_closedCell_eq_skeletonLT_inter_cellFrontier skeleton_inter_closedCell_eq_skeleton_inter_cellFrontier) end CWComplex end Topology
Presheaf.lean
/- Copyright (c) 2024 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.Algebra.Category.ModuleCat.Presheaf import Mathlib.Algebra.Category.ModuleCat.Differentials.Basic /-! # The presheaf of differentials of a presheaf of modules In this file, we define the type `M.Derivation φ` of derivations with values in a presheaf of `R`-modules `M` relative to a morphism of `φ : S ⟶ F.op ⋙ R` of presheaves of commutative rings over categories `C` and `D` that are related by a functor `F : C ⥤ D`. We formalize the notion of universal derivation. Geometrically, if `f : X ⟶ S` is a morphism of schemes (or more generally a morphism of commutative ringed spaces), we would like to apply these definitions in the case where `F` is the pullback functor from open subsets of `S` to open subsets of `X` and `φ` is the morphism $O_S ⟶ f_* O_X$. In order to prove that there exists a universal derivation, the target of which shall be called the presheaf of relative differentials of `φ`, we first study the case where `F` is the identity functor. In this case where we have a morphism of presheaves of commutative rings `φ' : S' ⟶ R`, we construct a derivation `DifferentialsConstruction.derivation'` which is universal. Then, the general case (TODO) shall be obtained by observing that derivations for `S ⟶ F.op ⋙ R` identify to derivations for `S' ⟶ R` where `S'` is the pullback by `F` of the presheaf of commutative rings `S` (the data is the same: it suffices to show that the two vanishing conditions `d_app` are equivalent). -/ universe v u v₁ v₂ u₁ u₂ open CategoryTheory variable {C : Type u₁} [Category.{v₁} C] {D : Type u₂} [Category.{v₂} D] namespace PresheafOfModules variable {S : Cᵒᵖ ⥤ CommRingCat.{u}} {F : C ⥤ D} {S' R : Dᵒᵖ ⥤ CommRingCat.{u}} (M N : PresheafOfModules.{v} (R ⋙ forget₂ _ _)) (φ : S ⟶ F.op ⋙ R) (φ' : S' ⟶ R) /-- Given a morphism of presheaves of commutative rings `φ : S ⟶ F.op ⋙ R`, this is the type of relative `φ`-derivation of a presheaf of `R`-modules `M`. -/ @[ext] structure Derivation where /-- the underlying additive map `R.obj X →+ M.obj X` of a derivation -/ d {X : Dᵒᵖ} : R.obj X →+ M.obj X d_mul {X : Dᵒᵖ} (a b : R.obj X) : d (a * b) = a • d b + b • d a := by cat_disch d_map {X Y : Dᵒᵖ} (f : X ⟶ Y) (x : R.obj X) : d (R.map f x) = M.map f (d x) := by cat_disch d_app {X : Cᵒᵖ} (a : S.obj X) : d (φ.app X a) = 0 := by cat_disch namespace Derivation -- Note: `d_app` cannot be a simp lemma because `dsimp` would -- simplify the composition of functors `R ⋙ forget₂ _ _` attribute [simp] d_mul d_map variable {M N φ} lemma congr_d {d d' : M.Derivation φ} (h : d = d') {X : Dᵒᵖ} (b : R.obj X) : d.d b = d'.d b := by rw [h] variable (d : M.Derivation φ) @[simp] lemma d_one (X : Dᵒᵖ) : d.d (X := X) 1 = 0 := by simpa using d.d_mul (X := X) 1 1 /-- The postcomposition of a derivation by a morphism of presheaves of modules. -/ @[simps! d_apply] def postcomp (f : M ⟶ N) : N.Derivation φ where d := (f.app _).hom.toAddMonoidHom.comp d.d d_map {X Y} g x := by simpa using naturality_apply f g (d.d x) d_app {X} a := by dsimp erw [d_app] rw [map_zero] /-- The universal property that a derivation `d : M.Derivation φ` must satisfy so that the presheaf of modules `M` can be considered as the presheaf of (relative) differentials of a presheaf of commutative rings `φ : S ⟶ F.op ⋙ R`. -/ structure Universal where /-- An absolute derivation of `M'` descends as a morphism `M ⟶ M'`. -/ desc {M' : PresheafOfModules (R ⋙ forget₂ CommRingCat RingCat)} (d' : M'.Derivation φ) : M ⟶ M' fac {M' : PresheafOfModules (R ⋙ forget₂ CommRingCat RingCat)} (d' : M'.Derivation φ) : d.postcomp (desc d') = d' := by cat_disch postcomp_injective {M' : PresheafOfModules (R ⋙ forget₂ CommRingCat RingCat)} (φ φ' : M ⟶ M') (h : d.postcomp φ = d.postcomp φ') : φ = φ' := by cat_disch attribute [simp] Universal.fac instance : Subsingleton d.Universal where allEq h₁ h₂ := by suffices ∀ {M' : PresheafOfModules (R ⋙ forget₂ CommRingCat RingCat)} (d' : M'.Derivation φ), h₁.desc d' = h₂.desc d' by cases h₁ cases h₂ simp only [Universal.mk.injEq] ext : 2 apply this intro M' d' apply h₁.postcomp_injective simp end Derivation /-- The property that there exists a universal derivation for a morphism of presheaves of commutative rings `S ⟶ F.op ⋙ R`. -/ class HasDifferentials : Prop where exists_universal_derivation : ∃ (M : PresheafOfModules.{u} (R ⋙ forget₂ _ _)) (d : M.Derivation φ), Nonempty d.Universal /-- Given a morphism of presheaves of commutative rings `φ : S ⟶ R`, this is the type of relative `φ`-derivation of a presheaf of `R`-modules `M`. -/ abbrev Derivation' : Type _ := M.Derivation (F := 𝟭 D) φ' namespace Derivation' variable {M φ'} @[simp] nonrec lemma d_app (d : M.Derivation' φ') {X : Dᵒᵖ} (a : S'.obj X) : d.d (φ'.app X a) = 0 := d.d_app _ /-- The derivation relative to the morphism of commutative rings `φ'.app X` induced by a derivation relative to a morphism of presheaves of commutative rings. -/ noncomputable def app (d : M.Derivation' φ') (X : Dᵒᵖ) : (M.obj X).Derivation (φ'.app X) := ModuleCat.Derivation.mk (fun b ↦ d.d b) @[simp] lemma app_apply (d : M.Derivation' φ') {X : Dᵒᵖ} (b : R.obj X) : (d.app X).d b = d.d b := rfl section variable (d : ∀ (X : Dᵒᵖ), (M.obj X).Derivation (φ'.app X)) /-- Given a morphism of presheaves of commutative rings `φ'`, this is the in derivation `M.Derivation' φ'` that is given by a compatible family of derivations with values in the modules `M.obj X` for all `X`. -/ def mk (d_map : ∀ ⦃X Y : Dᵒᵖ⦄ (f : X ⟶ Y) (x : R.obj X), (d Y).d ((R.map f) x) = (M.map f) ((d X).d x)) : M.Derivation' φ' where d {X} := AddMonoidHom.mk' (d X).d (by simp) variable (d_map : ∀ ⦃X Y : Dᵒᵖ⦄ (f : X ⟶ Y) (x : R.obj X), (d Y).d ((R.map f) x) = (M.map f) ((d X).d x)) @[simp] lemma mk_app (X : Dᵒᵖ) : (mk d d_map).app X = d X := rfl /-- Constructor for `Derivation.Universal` in the case `F` is the identity functor. -/ def Universal.mk {d : M.Derivation' φ'} (desc : ∀ {M' : PresheafOfModules (R ⋙ forget₂ _ _)} (_ : M'.Derivation' φ'), M ⟶ M') (fac : ∀ {M' : PresheafOfModules (R ⋙ forget₂ _ _)} (d' : M'.Derivation' φ'), d.postcomp (desc d') = d') (postcomp_injective : ∀ {M' : PresheafOfModules (R ⋙ forget₂ _ _)} (α β : M ⟶ M'), d.postcomp α = d.postcomp β → α = β) : d.Universal where desc := desc fac := fac postcomp_injective := postcomp_injective end end Derivation' namespace DifferentialsConstruction /-- The presheaf of relative differentials of a morphism of presheaves of commutative rings. -/ @[simps -isSimp] noncomputable def relativeDifferentials' : PresheafOfModules.{u} (R ⋙ forget₂ _ _) where obj X := CommRingCat.KaehlerDifferential (φ'.app X) -- Have to hint `g' := R.map f` below, or it gets unfolded weirdly. map f := CommRingCat.KaehlerDifferential.map (g' := R.map f) (φ'.naturality f) -- Without `dsimp`, `ext` doesn't pick up the right lemmas. map_id _ := by dsimp; ext; simp map_comp _ _ := by dsimp; ext; simp attribute [simp] relativeDifferentials'_obj @[simp] lemma relativeDifferentials'_map_d {X Y : Dᵒᵖ} (f : X ⟶ Y) (x : R.obj X) : DFunLike.coe (α := CommRingCat.KaehlerDifferential (φ'.app X)) (β := fun _ ↦ CommRingCat.KaehlerDifferential (φ'.app Y)) (ModuleCat.Hom.hom (R := ↑(R.obj X)) ((relativeDifferentials' φ').map f)) (CommRingCat.KaehlerDifferential.d x) = CommRingCat.KaehlerDifferential.d (R.map f x) := CommRingCat.KaehlerDifferential.map_d (φ'.naturality f) _ /-- The universal derivation. -/ noncomputable def derivation' : (relativeDifferentials' φ').Derivation' φ' := Derivation'.mk (fun X ↦ CommRingCat.KaehlerDifferential.D (φ'.app X)) (fun _ _ f x ↦ (relativeDifferentials'_map_d φ' f x).symm) /-- The derivation `Derivation' φ'` is universal. -/ noncomputable def isUniversal' : (derivation' φ').Universal := Derivation'.Universal.mk (fun {M'} d' ↦ { app := fun X ↦ (d'.app X).desc naturality := fun {X Y} f ↦ CommRingCat.KaehlerDifferential.ext (fun b ↦ by dsimp rw [ModuleCat.Derivation.desc_d, Derivation'.app_apply] erw [relativeDifferentials'_map_d φ' f] simp) }) (fun {M'} d' ↦ by ext X b apply ModuleCat.Derivation.desc_d) (fun {M} α β h ↦ by ext1 X exact CommRingCat.KaehlerDifferential.ext (Derivation.congr_d h)) instance : HasDifferentials (F := 𝟭 D) φ' := ⟨_, _, ⟨isUniversal' φ'⟩⟩ end DifferentialsConstruction end PresheafOfModules
Cotangent.lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Algebra.Module.Torsion import Mathlib.Algebra.Ring.Idempotent import Mathlib.LinearAlgebra.Dimension.Finite import Mathlib.LinearAlgebra.Dimension.FreeAndStrongRankCondition import Mathlib.LinearAlgebra.FiniteDimensional.Defs import Mathlib.RingTheory.Filtration import Mathlib.RingTheory.Ideal.Operations import Mathlib.RingTheory.LocalRing.ResidueField.Basic import Mathlib.RingTheory.Nakayama /-! # The module `I ⧸ I ^ 2` In this file, we provide special API support for the module `I ⧸ I ^ 2`. The official definition is a quotient module of `I`, but the alternative definition as an ideal of `R ⧸ I ^ 2` is also given, and the two are `R`-equivalent as in `Ideal.cotangentEquivIdeal`. Additional support is also given to the cotangent space `m ⧸ m ^ 2` of a local ring. -/ namespace Ideal -- Porting note: universes need to be explicit to avoid bad universe levels in `quotCotangent` universe u v w variable {R : Type u} {S : Type v} {S' : Type w} [CommRing R] [CommSemiring S] [Algebra S R] variable [CommSemiring S'] [Algebra S' R] [Algebra S S'] [IsScalarTower S S' R] (I : Ideal R) /-- `I ⧸ I ^ 2` as a quotient of `I`. -/ def Cotangent : Type _ := I ⧸ (I • ⊤ : Submodule R I) deriving Inhabited, AddCommGroup, Module (R ⧸ I) deriving instance Module S, IsScalarTower S S' for Cotangent I variable [IsNoetherian R I] in deriving instance IsNoetherian R for Cotangent I /-- The quotient map from `I` to `I ⧸ I ^ 2`. -/ @[simps! -isSimp apply] def toCotangent : I →ₗ[R] I.Cotangent := Submodule.mkQ _ theorem map_toCotangent_ker : (LinearMap.ker I.toCotangent).map I.subtype = I ^ 2 := by rw [Ideal.toCotangent, Submodule.ker_mkQ, pow_two, Submodule.map_smul'' I ⊤ (Submodule.subtype I), Algebra.id.smul_eq_mul, Submodule.map_subtype_top] theorem mem_toCotangent_ker {x : I} : x ∈ LinearMap.ker I.toCotangent ↔ (x : R) ∈ I ^ 2 := by rw [← I.map_toCotangent_ker] simp theorem toCotangent_eq {x y : I} : I.toCotangent x = I.toCotangent y ↔ (x - y : R) ∈ I ^ 2 := by rw [← sub_eq_zero] exact I.mem_toCotangent_ker theorem toCotangent_eq_zero (x : I) : I.toCotangent x = 0 ↔ (x : R) ∈ I ^ 2 := I.mem_toCotangent_ker theorem toCotangent_surjective : Function.Surjective I.toCotangent := Submodule.mkQ_surjective _ theorem toCotangent_range : LinearMap.range I.toCotangent = ⊤ := Submodule.range_mkQ _ theorem cotangent_subsingleton_iff : Subsingleton I.Cotangent ↔ IsIdempotentElem I := by constructor · intro H refine (pow_two I).symm.trans (le_antisymm (Ideal.pow_le_self two_ne_zero) ?_) exact fun x hx => (I.toCotangent_eq_zero ⟨x, hx⟩).mp (Subsingleton.elim _ _) · exact fun e => ⟨fun x y => Quotient.inductionOn₂' x y fun x y => I.toCotangent_eq.mpr <| ((pow_two I).trans e).symm ▸ I.sub_mem x.prop y.prop⟩ /-- The inclusion map `I ⧸ I ^ 2` to `R ⧸ I ^ 2`. -/ def cotangentToQuotientSquare : I.Cotangent →ₗ[R] R ⧸ I ^ 2 := Submodule.mapQ (I • ⊤) (I ^ 2) I.subtype (by rw [← Submodule.map_le_iff_le_comap, Submodule.map_smul'', Submodule.map_top, Submodule.range_subtype, smul_eq_mul, pow_two] ) theorem to_quotient_square_comp_toCotangent : I.cotangentToQuotientSquare.comp I.toCotangent = (I ^ 2).mkQ.comp (Submodule.subtype I) := LinearMap.ext fun _ => rfl @[simp] theorem toCotangent_to_quotient_square (x : I) : I.cotangentToQuotientSquare (I.toCotangent x) = (I ^ 2).mkQ x := rfl lemma Cotangent.smul_eq_zero_of_mem {I : Ideal R} {x} (hx : x ∈ I) (m : I.Cotangent) : x • m = 0 := by obtain ⟨m, rfl⟩ := Ideal.toCotangent_surjective _ m rw [← map_smul, Ideal.toCotangent_eq_zero, pow_two] exact Ideal.mul_mem_mul hx m.2 lemma isTorsionBySet_cotangent : Module.IsTorsionBySet R I.Cotangent I := fun m x ↦ m.smul_eq_zero_of_mem x.2 /-- `I ⧸ I ^ 2` as an ideal of `R ⧸ I ^ 2`. -/ def cotangentIdeal (I : Ideal R) : Ideal (R ⧸ I ^ 2) := Submodule.map (Quotient.mk (I ^ 2)|>.toSemilinearMap) I theorem cotangentIdeal_square (I : Ideal R) : I.cotangentIdeal ^ 2 = ⊥ := by rw [eq_bot_iff, pow_two I.cotangentIdeal, ← smul_eq_mul] intro x hx refine Submodule.smul_induction_on hx ?_ ?_ · rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩; apply (Submodule.Quotient.eq _).mpr _ rw [sub_zero, pow_two]; exact Ideal.mul_mem_mul hx hy · intro x y hx hy; exact add_mem hx hy lemma mk_mem_cotangentIdeal {I : Ideal R} {x : R} : Quotient.mk (I ^ 2) x ∈ I.cotangentIdeal ↔ x ∈ I := by refine ⟨fun ⟨y, hy, e⟩ ↦ ?_, fun h ↦ ⟨x, h, rfl⟩⟩ simpa using sub_mem hy (Ideal.pow_le_self two_ne_zero ((Ideal.Quotient.mk_eq_mk_iff_sub_mem _ _).mp e)) lemma comap_cotangentIdeal (I : Ideal R) : I.cotangentIdeal.comap (Quotient.mk (I ^ 2)) = I := Ideal.ext fun _ ↦ mk_mem_cotangentIdeal theorem range_cotangentToQuotientSquare : LinearMap.range I.cotangentToQuotientSquare = I.cotangentIdeal.restrictScalars R := by trans LinearMap.range (I.cotangentToQuotientSquare.comp I.toCotangent) · rw [LinearMap.range_comp, I.toCotangent_range, Submodule.map_top] · rw [to_quotient_square_comp_toCotangent, LinearMap.range_comp, I.range_subtype]; ext; rfl /-- The equivalence of the two definitions of `I / I ^ 2`, either as the quotient of `I` or the ideal of `R / I ^ 2`. -/ noncomputable def cotangentEquivIdeal : I.Cotangent ≃ₗ[R] I.cotangentIdeal := by refine { LinearMap.codRestrict (I.cotangentIdeal.restrictScalars R) I.cotangentToQuotientSquare fun x => by rw [← range_cotangentToQuotientSquare]; exact LinearMap.mem_range_self _ _, Equiv.ofBijective _ ⟨?_, ?_⟩ with } · rintro x y e replace e := congr_arg Subtype.val e obtain ⟨x, rfl⟩ := I.toCotangent_surjective x obtain ⟨y, rfl⟩ := I.toCotangent_surjective y rw [I.toCotangent_eq] dsimp only [toCotangent_to_quotient_square, Submodule.mkQ_apply] at e rwa [Submodule.Quotient.eq] at e · rintro ⟨_, x, hx, rfl⟩ exact ⟨I.toCotangent ⟨x, hx⟩, Subtype.ext rfl⟩ @[simp] theorem cotangentEquivIdeal_apply (x : I.Cotangent) : ↑(I.cotangentEquivIdeal x) = I.cotangentToQuotientSquare x := rfl theorem cotangentEquivIdeal_symm_apply (x : R) (hx : x ∈ I) : -- Note: https://github.com/leanprover-community/mathlib4/pull/8386 had to specify `(R₂ := R)` because `I.toCotangent` suggested `R ⧸ I^2` instead I.cotangentEquivIdeal.symm ⟨(I ^ 2).mkQ x, -- timeout (200000 heartbeats) without `by exact` by exact Submodule.mem_map_of_mem (F := R →ₗ[R] R ⧸ I ^ 2) (f := (I ^ 2).mkQ) hx⟩ = I.toCotangent (R := R) ⟨x, hx⟩ := by apply I.cotangentEquivIdeal.injective rw [I.cotangentEquivIdeal.apply_symm_apply] ext rfl variable {A B : Type*} [CommRing A] [CommRing B] [Algebra R A] [Algebra R B] /-- The lift of `f : A →ₐ[R] B` to `A ⧸ J ^ 2 →ₐ[R] B` with `J` being the kernel of `f`. -/ def _root_.AlgHom.kerSquareLift (f : A →ₐ[R] B) : A ⧸ RingHom.ker f.toRingHom ^ 2 →ₐ[R] B := by refine { Ideal.Quotient.lift (RingHom.ker f.toRingHom ^ 2) f.toRingHom ?_ with commutes' := ?_ } · intro a ha; exact Ideal.pow_le_self two_ne_zero ha · intro r rw [IsScalarTower.algebraMap_apply R A, RingHom.toFun_eq_coe, Ideal.Quotient.algebraMap_eq, Ideal.Quotient.lift_mk] exact f.map_algebraMap r theorem _root_.AlgHom.ker_kerSquareLift (f : A →ₐ[R] B) : RingHom.ker f.kerSquareLift.toRingHom = (RingHom.ker f.toRingHom).cotangentIdeal := by apply le_antisymm · intro x hx; obtain ⟨x, rfl⟩ := Ideal.Quotient.mk_surjective x; exact ⟨x, hx, rfl⟩ · rintro _ ⟨x, hx, rfl⟩; exact hx instance Algebra.kerSquareLift : Algebra (R ⧸ (RingHom.ker (algebraMap R A) ^ 2)) A := (Algebra.ofId R A).kerSquareLift.toAlgebra instance [Algebra A B] [IsScalarTower R A B] : IsScalarTower R (A ⧸ (RingHom.ker (algebraMap A B) ^ 2)) B := IsScalarTower.of_algebraMap_eq' (IsScalarTower.toAlgHom R A B).kerSquareLift.comp_algebraMap.symm /-- The quotient ring of `I ⧸ I ^ 2` is `R ⧸ I`. -/ def quotCotangent : (R ⧸ I ^ 2) ⧸ I.cotangentIdeal ≃+* R ⧸ I := by refine (Ideal.quotEquivOfEq (Ideal.map_eq_submodule_map _ _).symm).trans ?_ refine (DoubleQuot.quotQuotEquivQuotSup _ _).trans ?_ exact Ideal.quotEquivOfEq (sup_eq_right.mpr <| Ideal.pow_le_self two_ne_zero) /-- The map `I/I² → J/J²` if `I ≤ f⁻¹(J)`. -/ def mapCotangent (I₁ : Ideal A) (I₂ : Ideal B) (f : A →ₐ[R] B) (h : I₁ ≤ I₂.comap f) : I₁.Cotangent →ₗ[R] I₂.Cotangent := by refine Submodule.mapQ ((I₁ • ⊤ : Submodule A I₁).restrictScalars R) ((I₂ • ⊤ : Submodule B I₂).restrictScalars R) ?_ ?_ · exact f.toLinearMap.restrict (p := I₁.restrictScalars R) (q := I₂.restrictScalars R) h · intro x hx rw [Submodule.restrictScalars_mem] at hx refine Submodule.smul_induction_on hx ?_ (fun _ _ ↦ add_mem) rintro a ha ⟨b, hb⟩ - simp only [SetLike.mk_smul_mk, smul_eq_mul, Submodule.mem_comap, Submodule.restrictScalars_mem] convert (Submodule.smul_mem_smul (M := I₂) (r := f a) (n := ⟨f b, h hb⟩) (h ha) (Submodule.mem_top)) using 1 ext exact map_mul f a b @[simp] lemma mapCotangent_toCotangent (I₁ : Ideal A) (I₂ : Ideal B) (f : A →ₐ[R] B) (h : I₁ ≤ I₂.comap f) (x : I₁) : Ideal.mapCotangent I₁ I₂ f h (Ideal.toCotangent I₁ x) = Ideal.toCotangent I₂ ⟨f x, h x.2⟩ := rfl end Ideal namespace IsLocalRing variable (R : Type*) [CommRing R] [IsLocalRing R] /-- The `A ⧸ I`-vector space `I ⧸ I ^ 2`. -/ abbrev CotangentSpace : Type _ := (maximalIdeal R).Cotangent instance : Module (ResidueField R) (CotangentSpace R) := inferInstanceAs <| Module (R ⧸ maximalIdeal R) _ instance : IsScalarTower R (ResidueField R) (CotangentSpace R) := inferInstanceAs <| IsScalarTower R (R ⧸ maximalIdeal R) _ instance [IsNoetherianRing R] : FiniteDimensional (ResidueField R) (CotangentSpace R) := Module.Finite.of_restrictScalars_finite R _ _ variable {R} lemma subsingleton_cotangentSpace_iff [IsNoetherianRing R] : Subsingleton (CotangentSpace R) ↔ IsField R := by refine (maximalIdeal R).cotangent_subsingleton_iff.trans ?_ rw [IsLocalRing.isField_iff_maximalIdeal_eq, Ideal.isIdempotentElem_iff_eq_bot_or_top_of_isLocalRing] simp [(maximalIdeal.isMaximal R).ne_top] lemma CotangentSpace.map_eq_top_iff [IsNoetherianRing R] {M : Submodule R (maximalIdeal R)} : M.map (maximalIdeal R).toCotangent = ⊤ ↔ M = ⊤ := by refine ⟨fun H ↦ eq_top_iff.mpr ?_, by rintro rfl; simp [Ideal.toCotangent_range]⟩ refine (Submodule.map_le_map_iff_of_injective (Submodule.injective_subtype _) _ _).mp ?_ rw [Submodule.map_top, Submodule.range_subtype] apply Submodule.le_of_le_smul_of_le_jacobson_bot (IsNoetherian.noetherian _) (IsLocalRing.jacobson_eq_maximalIdeal _ bot_ne_top).ge rw [smul_eq_mul, ← pow_two, ← Ideal.map_toCotangent_ker, ← Submodule.map_sup, ← Submodule.comap_map_eq, H, Submodule.comap_top, Submodule.map_top, Submodule.range_subtype] lemma CotangentSpace.span_image_eq_top_iff [IsNoetherianRing R] {s : Set (maximalIdeal R)} : Submodule.span (ResidueField R) ((maximalIdeal R).toCotangent '' s) = ⊤ ↔ Submodule.span R s = ⊤ := by rw [← map_eq_top_iff, ← (Submodule.restrictScalars_injective R ..).eq_iff, Submodule.restrictScalars_span] · simp only [Ideal.toCotangent_apply, Submodule.restrictScalars_top, Submodule.map_span] · exact Ideal.Quotient.mk_surjective open Module lemma finrank_cotangentSpace_eq_zero_iff [IsNoetherianRing R] : finrank (ResidueField R) (CotangentSpace R) = 0 ↔ IsField R := by rw [finrank_zero_iff, subsingleton_cotangentSpace_iff] lemma finrank_cotangentSpace_eq_zero (R) [Field R] : finrank (ResidueField R) (CotangentSpace R) = 0 := finrank_cotangentSpace_eq_zero_iff.mpr (Field.toIsField R) open Submodule in theorem finrank_cotangentSpace_le_one_iff [IsNoetherianRing R] : finrank (ResidueField R) (CotangentSpace R) ≤ 1 ↔ (maximalIdeal R).IsPrincipal := by rw [Module.finrank_le_one_iff_top_isPrincipal, isPrincipal_iff, (maximalIdeal R).toCotangent_surjective.exists, isPrincipal_iff] simp_rw [← Set.image_singleton, eq_comm (a := ⊤), CotangentSpace.span_image_eq_top_iff, ← (map_injective_of_injective (injective_subtype _)).eq_iff, map_span, Set.image_singleton, Submodule.map_top, range_subtype, eq_comm (a := maximalIdeal R)] exact ⟨fun ⟨x, h⟩ ↦ ⟨_, h⟩, fun ⟨x, h⟩ ↦ ⟨⟨x, h ▸ subset_span (Set.mem_singleton x)⟩, h⟩⟩ end IsLocalRing
NatAntidiagonal.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.Order.Antidiag.Prod import Mathlib.Algebra.Order.Group.Nat import Mathlib.Data.Multiset.NatAntidiagonal /-! # Antidiagonals in ℕ × ℕ as finsets This file defines the antidiagonals of ℕ × ℕ as finsets: the `n`-th antidiagonal is the finset of pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more generally for sums going from `0` to `n`. ## Notes This refines files `Data.List.NatAntidiagonal` and `Data.Multiset.NatAntidiagonal`, providing an instance enabling `Finset.antidiagonal` on `Nat`. -/ assert_not_exists Field open Function namespace Finset namespace Nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i, j)` such that `i + j = n`. -/ instance instHasAntidiagonal : HasAntidiagonal ℕ where antidiagonal n := ⟨Multiset.Nat.antidiagonal n, Multiset.Nat.nodup_antidiagonal n⟩ mem_antidiagonal {n} {xy} := by rw [mem_def, Multiset.Nat.mem_antidiagonal] lemma antidiagonal_eq_map (n : ℕ) : antidiagonal n = (range (n + 1)).map ⟨fun i ↦ (i, n - i), fun _ _ h ↦ (Prod.ext_iff.1 h).1⟩ := rfl lemma antidiagonal_eq_map' (n : ℕ) : antidiagonal n = (range (n + 1)).map ⟨fun i ↦ (n - i, i), fun _ _ h ↦ (Prod.ext_iff.1 h).2⟩ := by rw [← map_swap_antidiagonal, antidiagonal_eq_map, map_map]; rfl lemma antidiagonal_eq_image (n : ℕ) : antidiagonal n = (range (n + 1)).image fun i ↦ (i, n - i) := by simp only [antidiagonal_eq_map, map_eq_image, Function.Embedding.coeFn_mk] lemma antidiagonal_eq_image' (n : ℕ) : antidiagonal n = (range (n + 1)).image fun i ↦ (n - i, i) := by simp only [antidiagonal_eq_map', map_eq_image, Function.Embedding.coeFn_mk] /-- The cardinality of the antidiagonal of `n` is `n + 1`. -/ @[simp] theorem card_antidiagonal (n : ℕ) : (antidiagonal n).card = n + 1 := by simp [antidiagonal] /-- The antidiagonal of `0` is the list `[(0, 0)]` -/ @[simp] theorem antidiagonal_zero : antidiagonal 0 = {(0, 0)} := rfl theorem antidiagonal_succ (n : ℕ) : antidiagonal (n + 1) = cons (0, n + 1) ((antidiagonal n).map (Embedding.prodMap ⟨Nat.succ, Nat.succ_injective⟩ (Embedding.refl _))) (by simp) := by apply eq_of_veq rw [cons_val, map_val] apply Multiset.Nat.antidiagonal_succ theorem antidiagonal_succ' (n : ℕ) : antidiagonal (n + 1) = cons (n + 1, 0) ((antidiagonal n).map (Embedding.prodMap (Embedding.refl _) ⟨Nat.succ, Nat.succ_injective⟩)) (by simp) := by apply eq_of_veq rw [cons_val, map_val] exact Multiset.Nat.antidiagonal_succ' theorem antidiagonal_succ_succ' {n : ℕ} : antidiagonal (n + 2) = cons (0, n + 2) (cons (n + 2, 0) ((antidiagonal n).map (Embedding.prodMap ⟨Nat.succ, Nat.succ_injective⟩ ⟨Nat.succ, Nat.succ_injective⟩)) <| by simp) (by simp) := by simp_rw [antidiagonal_succ (n + 1), antidiagonal_succ', Finset.map_cons, map_map] rfl theorem antidiagonal.fst_lt {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.1 < n + 1 := Nat.lt_succ_of_le <| antidiagonal.fst_le hlk theorem antidiagonal.snd_lt {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.2 < n + 1 := Nat.lt_succ_of_le <| antidiagonal.snd_le hlk @[simp] lemma antidiagonal_filter_snd_le_of_le {n k : ℕ} (h : k ≤ n) : {a ∈ antidiagonal n | a.snd ≤ k} = (antidiagonal k).map (Embedding.prodMap ⟨_, add_left_injective (n - k)⟩ (Embedding.refl ℕ)) := by ext ⟨i, j⟩ suffices i + j = n ∧ j ≤ k ↔ ∃ a, a + j = k ∧ a + (n - k) = i by simpa refine ⟨fun hi ↦ ⟨k - j, tsub_add_cancel_of_le hi.2, ?_⟩, ?_⟩ · rw [add_comm, tsub_add_eq_add_tsub h, ← hi.1, add_assoc, Nat.add_sub_of_le hi.2, add_tsub_cancel_right] · rintro ⟨l, hl, rfl⟩ refine ⟨?_, hl ▸ Nat.le_add_left j l⟩ rw [add_assoc, add_comm, add_assoc, add_comm j l, hl] exact Nat.sub_add_cancel h @[simp] lemma antidiagonal_filter_fst_le_of_le {n k : ℕ} (h : k ≤ n) : {a ∈ antidiagonal n | a.fst ≤ k} = (antidiagonal k).map (Embedding.prodMap (Embedding.refl ℕ) ⟨_, add_left_injective (n - k)⟩) := by have aux₁ : fun a ↦ a.fst ≤ k = (fun a ↦ a.snd ≤ k) ∘ (Equiv.prodComm ℕ ℕ).symm := rfl have aux₂ : ∀ i j, (∃ a b, a + b = k ∧ b = i ∧ a + (n - k) = j) ↔ ∃ a b, a + b = k ∧ a = i ∧ b + (n - k) = j := fun i j ↦ by rw [exists_comm]; exact exists₂_congr (fun a b ↦ by rw [add_comm]) rw [← map_prodComm_antidiagonal] simp_rw [aux₁, ← map_filter, antidiagonal_filter_snd_le_of_le h, map_map] ext ⟨i, j⟩ simpa using aux₂ i j @[simp] lemma antidiagonal_filter_le_fst_of_le {n k : ℕ} (h : k ≤ n) : {a ∈ antidiagonal n | k ≤ a.fst} = (antidiagonal (n - k)).map (Embedding.prodMap ⟨_, add_left_injective k⟩ (Embedding.refl ℕ)) := by ext ⟨i, j⟩ suffices i + j = n ∧ k ≤ i ↔ ∃ a, a + j = n - k ∧ a + k = i by simpa refine ⟨fun hi ↦ ⟨i - k, ?_, tsub_add_cancel_of_le hi.2⟩, ?_⟩ · rw [← Nat.sub_add_comm hi.2, hi.1] · rintro ⟨l, hl, rfl⟩ refine ⟨?_, Nat.le_add_left k l⟩ rw [add_right_comm, hl] exact tsub_add_cancel_of_le h @[simp] lemma antidiagonal_filter_le_snd_of_le {n k : ℕ} (h : k ≤ n) : {a ∈ antidiagonal n | k ≤ a.snd} = (antidiagonal (n - k)).map (Embedding.prodMap (Embedding.refl ℕ) ⟨_, add_left_injective k⟩) := by have aux₁ : fun a ↦ k ≤ a.snd = (fun a ↦ k ≤ a.fst) ∘ (Equiv.prodComm ℕ ℕ).symm := rfl have aux₂ : ∀ i j, (∃ a b, a + b = n - k ∧ b = i ∧ a + k = j) ↔ ∃ a b, a + b = n - k ∧ a = i ∧ b + k = j := fun i j ↦ by rw [exists_comm]; exact exists₂_congr (fun a b ↦ by rw [add_comm]) rw [← map_prodComm_antidiagonal] simp_rw [aux₁, ← map_filter, antidiagonal_filter_le_fst_of_le h, map_map] ext ⟨i, j⟩ simpa using aux₂ i j /-- The set `antidiagonal n` is equivalent to `Fin (n+1)`, via the first projection. -/ @[simps] def antidiagonalEquivFin (n : ℕ) : antidiagonal n ≃ Fin (n + 1) where toFun := fun ⟨⟨i, _⟩, h⟩ ↦ ⟨i, antidiagonal.fst_lt h⟩ invFun := fun ⟨i, h⟩ ↦ ⟨⟨i, n - i⟩, by rw [mem_antidiagonal, add_comm, Nat.sub_add_cancel] exact Nat.le_of_lt_succ h⟩ end Nat end Finset
Indicator.lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import Mathlib.Analysis.SpecialFunctions.Pow.Continuity import Mathlib.MeasureTheory.Function.LpSpace.Basic import Mathlib.MeasureTheory.Measure.Real import Mathlib.Order.Filter.IndicatorFunction /-! # Indicator of a set as an element of `Lp` For a set `s` with `(hs : MeasurableSet s)` and `(hμs : μ s < ∞)`, we build `indicatorConstLp p hs hμs c`, the element of `Lp` corresponding to `s.indicator (fun _ => c)`. ## Main definitions * `MeasureTheory.indicatorConstLp`: Indicator of a set as an element of `Lp`. * `MeasureTheory.Lp.const`: Constant function as an element of `Lp` for a finite measure. -/ noncomputable section open MeasureTheory Filter open scoped NNReal ENNReal Topology symmDiff variable {α E : Type*} {m : MeasurableSpace α} {p : ℝ≥0∞} {μ : Measure α} [NormedAddCommGroup E] namespace MeasureTheory /-- The `eLpNorm` of the indicator of a set is uniformly small if the set itself has small measure, for any `p < ∞`. Given here as an existential `∀ ε > 0, ∃ η > 0, ...` to avoid later management of `ℝ≥0∞`-arithmetic. -/ theorem exists_eLpNorm_indicator_le (hp : p ≠ ∞) (c : E) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ η : ℝ≥0, 0 < η ∧ ∀ s : Set α, μ s ≤ η → eLpNorm (s.indicator fun _ => c) p μ ≤ ε := by rcases eq_or_ne p 0 with (rfl | h'p) · exact ⟨1, zero_lt_one, fun s _ => by simp⟩ have hp₀ : 0 < p := bot_lt_iff_ne_bot.2 h'p have hp₀' : 0 ≤ 1 / p.toReal := div_nonneg zero_le_one ENNReal.toReal_nonneg have hp₀'' : 0 < p.toReal := ENNReal.toReal_pos hp₀.ne' hp obtain ⟨η, hη_pos, hη_le⟩ : ∃ η : ℝ≥0, 0 < η ∧ ‖c‖ₑ * (η : ℝ≥0∞) ^ (1 / p.toReal) ≤ ε := by have : Filter.Tendsto (fun x : ℝ≥0 => ((‖c‖₊ * x ^ (1 / p.toReal) : ℝ≥0) : ℝ≥0∞)) (𝓝 0) (𝓝 (0 : ℝ≥0)) := by rw [ENNReal.tendsto_coe] convert (NNReal.continuousAt_rpow_const (Or.inr hp₀')).tendsto.const_mul _ simp [hp₀''.ne'] have hε' : 0 < ε := hε.bot_lt obtain ⟨δ, hδ, hδε'⟩ := NNReal.nhds_zero_basis.eventually_iff.mp (this.eventually_le_const hε') obtain ⟨η, hη, hηδ⟩ := exists_between hδ refine ⟨η, hη, ?_⟩ simpa only [← ENNReal.coe_rpow_of_nonneg _ hp₀', enorm, ← ENNReal.coe_mul] using hδε' hηδ refine ⟨η, hη_pos, fun s hs => ?_⟩ refine (eLpNorm_indicator_const_le _ _).trans (le_trans ?_ hη_le) exact mul_le_mul_left' (ENNReal.rpow_le_rpow hs hp₀') _ section Topology variable {X : Type*} [TopologicalSpace X] [MeasurableSpace X] {μ : Measure X} [IsFiniteMeasureOnCompacts μ] /-- A bounded measurable function with compact support is in L^p. -/ theorem _root_.HasCompactSupport.memLp_of_bound {f : X → E} (hf : HasCompactSupport f) (h2f : AEStronglyMeasurable f μ) (C : ℝ) (hfC : ∀ᵐ x ∂μ, ‖f x‖ ≤ C) : MemLp f p μ := by have := memLp_top_of_bound h2f C hfC exact this.mono_exponent_of_measure_support_ne_top (fun x ↦ image_eq_zero_of_notMem_tsupport) (hf.measure_lt_top.ne) le_top @[deprecated (since := "2025-02-21")] alias _root_.HasCompactSupport.memℒp_of_bound := _root_.HasCompactSupport.memLp_of_bound /-- A continuous function with compact support is in L^p. -/ theorem _root_.Continuous.memLp_of_hasCompactSupport [OpensMeasurableSpace X] {f : X → E} (hf : Continuous f) (h'f : HasCompactSupport f) : MemLp f p μ := by have := hf.memLp_top_of_hasCompactSupport h'f μ exact this.mono_exponent_of_measure_support_ne_top (fun x ↦ image_eq_zero_of_notMem_tsupport) (h'f.measure_lt_top.ne) le_top @[deprecated (since := "2025-02-21")] alias _root_.Continuous.memℒp_of_hasCompactSupport := _root_.Continuous.memLp_of_hasCompactSupport end Topology section IndicatorConstLp open Set Function variable {s : Set α} {hs : MeasurableSet s} {hμs : μ s ≠ ∞} {c : E} /-- Indicator of a set as an element of `Lp`. -/ def indicatorConstLp (p : ℝ≥0∞) (hs : MeasurableSet s) (hμs : μ s ≠ ∞) (c : E) : Lp E p μ := MemLp.toLp (s.indicator fun _ => c) (memLp_indicator_const p hs c (Or.inr hμs)) /-- A version of `Set.indicator_add` for `MeasureTheory.indicatorConstLp` -/ theorem indicatorConstLp_add {c' : E} : indicatorConstLp p hs hμs c + indicatorConstLp p hs hμs c' = indicatorConstLp p hs hμs (c + c') := by simp_rw [indicatorConstLp, ← MemLp.toLp_add, indicator_add] rfl /-- A version of `Set.indicator_sub` for `MeasureTheory.indicatorConstLp` -/ theorem indicatorConstLp_sub {c' : E} : indicatorConstLp p hs hμs c - indicatorConstLp p hs hμs c' = indicatorConstLp p hs hμs (c - c') := by simp_rw [indicatorConstLp, ← MemLp.toLp_sub, indicator_sub] rfl theorem indicatorConstLp_coeFn : ⇑(indicatorConstLp p hs hμs c) =ᵐ[μ] s.indicator fun _ => c := MemLp.coeFn_toLp (memLp_indicator_const p hs c (Or.inr hμs)) theorem indicatorConstLp_coeFn_mem : ∀ᵐ x : α ∂μ, x ∈ s → indicatorConstLp p hs hμs c x = c := indicatorConstLp_coeFn.mono fun _x hx hxs => hx.trans (Set.indicator_of_mem hxs _) theorem indicatorConstLp_coeFn_notMem : ∀ᵐ x : α ∂μ, x ∉ s → indicatorConstLp p hs hμs c x = 0 := indicatorConstLp_coeFn.mono fun _x hx hxs => hx.trans (Set.indicator_of_notMem hxs _) @[deprecated (since := "2025-05-24")] alias indicatorConstLp_coeFn_nmem := indicatorConstLp_coeFn_notMem theorem norm_indicatorConstLp (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : ‖indicatorConstLp p hs hμs c‖ = ‖c‖ * μ.real s ^ (1 / p.toReal) := by rw [Lp.norm_def, eLpNorm_congr_ae indicatorConstLp_coeFn, eLpNorm_indicator_const hs hp_ne_zero hp_ne_top, ENNReal.toReal_mul, measureReal_def, ENNReal.toReal_rpow, toReal_enorm] theorem norm_indicatorConstLp_top (hμs_ne_zero : μ s ≠ 0) : ‖indicatorConstLp ∞ hs hμs c‖ = ‖c‖ := by rw [Lp.norm_def, eLpNorm_congr_ae indicatorConstLp_coeFn, eLpNorm_indicator_const' hs hμs_ne_zero ENNReal.top_ne_zero, ENNReal.toReal_top, _root_.div_zero, ENNReal.rpow_zero, mul_one, toReal_enorm] theorem norm_indicatorConstLp' (hp_pos : p ≠ 0) (hμs_pos : μ s ≠ 0) : ‖indicatorConstLp p hs hμs c‖ = ‖c‖ * μ.real s ^ (1 / p.toReal) := by by_cases hp_top : p = ∞ · rw [hp_top, ENNReal.toReal_top, _root_.div_zero, Real.rpow_zero, mul_one] exact norm_indicatorConstLp_top hμs_pos · exact norm_indicatorConstLp hp_pos hp_top theorem norm_indicatorConstLp_le : ‖indicatorConstLp p hs hμs c‖ ≤ ‖c‖ * μ.real s ^ (1 / p.toReal) := by rw [indicatorConstLp, Lp.norm_toLp] refine ENNReal.toReal_le_of_le_ofReal (by positivity) ?_ refine (eLpNorm_indicator_const_le _ _).trans_eq ?_ rw [ENNReal.ofReal_mul (norm_nonneg _), ofReal_norm, measureReal_def, ENNReal.toReal_rpow, ENNReal.ofReal_toReal] finiteness theorem nnnorm_indicatorConstLp_le : ‖indicatorConstLp p hs hμs c‖₊ ≤ ‖c‖₊ * (μ s).toNNReal ^ (1 / p.toReal) := norm_indicatorConstLp_le theorem enorm_indicatorConstLp_le : ‖indicatorConstLp p hs hμs c‖ₑ ≤ ‖c‖ₑ * μ s ^ (1 / p.toReal) := by simpa [ENNReal.coe_rpow_of_nonneg, ENNReal.coe_toNNReal hμs, Lp.enorm_def, ← enorm_eq_nnnorm] using ENNReal.coe_le_coe.2 <| nnnorm_indicatorConstLp_le (c := c) (hμs := hμs) theorem edist_indicatorConstLp_eq_enorm {t : Set α} {ht : MeasurableSet t} {hμt : μ t ≠ ∞} : edist (indicatorConstLp p hs hμs c) (indicatorConstLp p ht hμt c) = ‖indicatorConstLp p (hs.symmDiff ht) (measure_symmDiff_ne_top hμs hμt) c‖ₑ := by unfold indicatorConstLp rw [Lp.edist_toLp_toLp, eLpNorm_indicator_sub_indicator, Lp.enorm_toLp] theorem dist_indicatorConstLp_eq_norm {t : Set α} {ht : MeasurableSet t} {hμt : μ t ≠ ∞} : dist (indicatorConstLp p hs hμs c) (indicatorConstLp p ht hμt c) = ‖indicatorConstLp p (hs.symmDiff ht) (measure_symmDiff_ne_top hμs hμt) c‖ := by -- Squeezed for performance reasons simp only [Lp.dist_edist, edist_indicatorConstLp_eq_enorm, enorm, ENNReal.coe_toReal, Lp.coe_nnnorm] /-- A family of `indicatorConstLp` functions tends to an `indicatorConstLp`, if the underlying sets tend to the set in the sense of the measure of the symmetric difference. -/ theorem tendsto_indicatorConstLp_set [hp₁ : Fact (1 ≤ p)] {β : Type*} {l : Filter β} {t : β → Set α} {ht : ∀ b, MeasurableSet (t b)} {hμt : ∀ b, μ (t b) ≠ ∞} (hp : p ≠ ∞) (h : Tendsto (fun b ↦ μ (t b ∆ s)) l (𝓝 0)) : Tendsto (fun b ↦ indicatorConstLp p (ht b) (hμt b) c) l (𝓝 (indicatorConstLp p hs hμs c)) := by rw [tendsto_iff_dist_tendsto_zero] have hp₀ : p ≠ 0 := (one_pos.trans_le hp₁.out).ne' simp only [dist_indicatorConstLp_eq_norm, norm_indicatorConstLp hp₀ hp] convert tendsto_const_nhds.mul (((ENNReal.tendsto_toReal ENNReal.zero_ne_top).comp h).rpow_const _) · simp [ENNReal.toReal_eq_zero_iff, hp, hp₀] · simp /-- A family of `indicatorConstLp` functions is continuous in the parameter, if `μ (s y ∆ s x)` tends to zero as `y` tends to `x` for all `x`. -/ theorem continuous_indicatorConstLp_set [Fact (1 ≤ p)] {X : Type*} [TopologicalSpace X] {s : X → Set α} {hs : ∀ x, MeasurableSet (s x)} {hμs : ∀ x, μ (s x) ≠ ∞} (hp : p ≠ ∞) (h : ∀ x, Tendsto (fun y ↦ μ (s y ∆ s x)) (𝓝 x) (𝓝 0)) : Continuous fun x ↦ indicatorConstLp p (hs x) (hμs x) c := continuous_iff_continuousAt.2 fun x ↦ tendsto_indicatorConstLp_set hp (h x) @[simp] theorem indicatorConstLp_empty : indicatorConstLp p MeasurableSet.empty (by simp : μ ∅ ≠ ∞) c = 0 := by simp only [indicatorConstLp, Set.indicator_empty', MemLp.toLp_zero] theorem indicatorConstLp_inj {s t : Set α} (hs : MeasurableSet s) (hsμ : μ s ≠ ∞) (ht : MeasurableSet t) (htμ : μ t ≠ ∞) {c : E} (hc : c ≠ 0) : indicatorConstLp p hs hsμ c = indicatorConstLp p ht htμ c ↔ s =ᵐ[μ] t := by simp_rw [← indicator_const_eventuallyEq hc, indicatorConstLp, MemLp.toLp_eq_toLp_iff] theorem memLp_add_of_disjoint {f g : α → E} (h : Disjoint (support f) (support g)) (hf : StronglyMeasurable f) (hg : StronglyMeasurable g) : MemLp (f + g) p μ ↔ MemLp f p μ ∧ MemLp g p μ := by borelize E refine ⟨fun hfg => ⟨?_, ?_⟩, fun h => h.1.add h.2⟩ · rw [← Set.indicator_add_eq_left h]; exact hfg.indicator (measurableSet_support hf.measurable) · rw [← Set.indicator_add_eq_right h]; exact hfg.indicator (measurableSet_support hg.measurable) @[deprecated (since := "2025-02-21")] alias memℒp_add_of_disjoint := memLp_add_of_disjoint /-- The indicator of a disjoint union of two sets is the sum of the indicators of the sets. -/ theorem indicatorConstLp_disjoint_union {s t : Set α} (hs : MeasurableSet s) (ht : MeasurableSet t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (hst : Disjoint s t) (c : E) : indicatorConstLp p (hs.union ht) (measure_union_ne_top hμs hμt) c = indicatorConstLp p hs hμs c + indicatorConstLp p ht hμt c := by ext1 grw [Lp.coeFn_add, indicatorConstLp_coeFn] refine EventuallyEq.trans ?_ (EventuallyEq.fun_add indicatorConstLp_coeFn.symm indicatorConstLp_coeFn.symm) rw [Set.indicator_union_of_disjoint hst] end IndicatorConstLp section const variable (μ p) variable [IsFiniteMeasure μ] (c : E) /-- Constant function as an element of `MeasureTheory.Lp` for a finite measure. -/ protected def Lp.const : E →+ Lp E p μ where toFun c := ⟨AEEqFun.const α c, const_mem_Lp α μ c⟩ map_zero' := rfl map_add' _ _ := rfl lemma Lp.coeFn_const : Lp.const p μ c =ᵐ[μ] Function.const α c := AEEqFun.coeFn_const α c @[simp] lemma Lp.const_val : (Lp.const p μ c).1 = AEEqFun.const α c := rfl @[simp] lemma MemLp.toLp_const : MemLp.toLp _ (memLp_const c) = Lp.const p μ c := rfl @[deprecated (since := "2025-02-21")] alias Memℒp.toLp_const := MemLp.toLp_const @[simp] lemma indicatorConstLp_univ : indicatorConstLp p .univ (measure_ne_top μ _) c = Lp.const p μ c := by rw [← MemLp.toLp_const, indicatorConstLp] simp only [Set.indicator_univ] theorem Lp.norm_const [NeZero μ] (hp_zero : p ≠ 0) : ‖Lp.const p μ c‖ = ‖c‖ * μ.real Set.univ ^ (1 / p.toReal) := by have := NeZero.ne μ rw [← MemLp.toLp_const, Lp.norm_toLp, eLpNorm_const] <;> try assumption rw [measureReal_def, ENNReal.toReal_mul, toReal_enorm, ← ENNReal.toReal_rpow] theorem Lp.norm_const' (hp_zero : p ≠ 0) (hp_top : p ≠ ∞) : ‖Lp.const p μ c‖ = ‖c‖ * μ.real Set.univ ^ (1 / p.toReal) := by rw [← MemLp.toLp_const, Lp.norm_toLp, eLpNorm_const'] <;> try assumption rw [measureReal_def, ENNReal.toReal_mul, toReal_enorm, ← ENNReal.toReal_rpow] theorem Lp.norm_const_le : ‖Lp.const p μ c‖ ≤ ‖c‖ * μ.real Set.univ ^ (1 / p.toReal) := by rw [← indicatorConstLp_univ] exact norm_indicatorConstLp_le /-- `MeasureTheory.Lp.const` as a `LinearMap`. -/ @[simps] protected def Lp.constₗ (𝕜 : Type*) [NormedRing 𝕜] [Module 𝕜 E] [IsBoundedSMul 𝕜 E] : E →ₗ[𝕜] Lp E p μ where toFun := Lp.const p μ map_add' := map_add _ map_smul' _ _ := rfl /-- `MeasureTheory.Lp.const` as a `ContinuousLinearMap`. -/ @[simps! apply] protected def Lp.constL (𝕜 : Type*) [NormedRing 𝕜] [Module 𝕜 E] [IsBoundedSMul 𝕜 E] [Fact (1 ≤ p)] : E →L[𝕜] Lp E p μ := (Lp.constₗ p μ 𝕜).mkContinuous (μ.real Set.univ ^ (1 / p.toReal)) fun _ ↦ (Lp.norm_const_le _ _ _).trans_eq (mul_comm _ _) theorem Lp.norm_constL_le (𝕜 : Type*) [NontriviallyNormedField 𝕜] [NormedSpace 𝕜 E] [Fact (1 ≤ p)] : ‖(Lp.constL p μ 𝕜 : E →L[𝕜] Lp E p μ)‖ ≤ μ.real Set.univ ^ (1 / p.toReal) := LinearMap.mkContinuous_norm_le _ (by positivity) _ end const namespace Lp variable {β : Type*} [MeasurableSpace β] {μb : MeasureTheory.Measure β} {f : α → β} theorem indicatorConstLp_compMeasurePreserving {s : Set β} (hs : MeasurableSet s) (hμs : μb s ≠ ∞) (c : E) (hf : MeasurePreserving f μ μb) : Lp.compMeasurePreserving f hf (indicatorConstLp p hs hμs c) = indicatorConstLp p (hs.preimage hf.measurable) (by rwa [hf.measure_preimage hs.nullMeasurableSet]) c := rfl end Lp theorem indicatorConstLp_eq_toSpanSingleton_compLp {s : Set α} [NormedSpace ℝ E] (hs : MeasurableSet s) (hμs : μ s ≠ ∞) (x : E) : indicatorConstLp 2 hs hμs x = (ContinuousLinearMap.toSpanSingleton ℝ x).compLp (indicatorConstLp 2 hs hμs (1 : ℝ)) := by ext1 refine indicatorConstLp_coeFn.trans ?_ have h_compLp := (ContinuousLinearMap.toSpanSingleton ℝ x).coeFn_compLp (indicatorConstLp 2 hs hμs (1 : ℝ)) rw [← EventuallyEq] at h_compLp refine EventuallyEq.trans ?_ h_compLp.symm refine (@indicatorConstLp_coeFn _ _ _ 2 μ _ s hs hμs (1 : ℝ)).mono fun y hy => ?_ dsimp only rw [hy] simp_rw [ContinuousLinearMap.toSpanSingleton_apply] by_cases hy_mem : y ∈ s <;> simp [hy_mem] end MeasureTheory
Kernels.lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.Algebra.Category.ModuleCat.EpiMono import Mathlib.CategoryTheory.ConcreteCategory.Elementwise /-! # The concrete (co)kernels in the category of modules are (co)kernels in the categorical sense. -/ open CategoryTheory CategoryTheory.Limits universe u v namespace ModuleCat variable {R : Type u} [Ring R] section variable {M N : ModuleCat.{v} R} (f : M ⟶ N) /-- The kernel cone induced by the concrete kernel. -/ def kernelCone : KernelFork f := KernelFork.ofι (ofHom (LinearMap.ker f.hom).subtype) <| by aesop /-- The kernel of a linear map is a kernel in the categorical sense. -/ def kernelIsLimit : IsLimit (kernelCone f) := Fork.IsLimit.mk _ (fun s => ofHom <| -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11036): broken dot notation on LinearMap.ker LinearMap.codRestrict (LinearMap.ker f.hom) (Fork.ι s).hom fun c => LinearMap.mem_ker.2 <| by -- This used to be `rw`, but we need `erw` after https://github.com/leanprover/lean4/pull/2644 erw [← ConcreteCategory.comp_apply] rw [Fork.condition, HasZeroMorphisms.comp_zero (Fork.ι s) N] rfl) (fun _ => hom_ext <| LinearMap.subtype_comp_codRestrict _ _ _) fun s m h => hom_ext <| LinearMap.ext fun x => Subtype.ext_iff_val.2 (by simp [← h]; rfl) /-- The cokernel cocone induced by the projection onto the quotient. -/ def cokernelCocone : CokernelCofork f := CokernelCofork.ofπ (ofHom (LinearMap.range f.hom).mkQ) <| hom_ext <| LinearMap.range_mkQ_comp _ /-- The projection onto the quotient is a cokernel in the categorical sense. -/ def cokernelIsColimit : IsColimit (cokernelCocone f) := Cofork.IsColimit.mk _ (fun s => ofHom <| (LinearMap.range f.hom).liftQ (Cofork.π s).hom <| LinearMap.range_le_ker_iff.2 <| ModuleCat.hom_ext_iff.mp <| CokernelCofork.condition s) (fun s => hom_ext <| (LinearMap.range f.hom).liftQ_mkQ (Cofork.π s).hom _) fun s m h => by -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11036): broken dot notation haveI : Epi (ofHom (LinearMap.range f.hom).mkQ) := (epi_iff_range_eq_top _).mpr (Submodule.range_mkQ _) -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11036): broken dot notation apply (cancel_epi (ofHom (LinearMap.range f.hom).mkQ)).1 exact h end /-- The category of R-modules has kernels, given by the inclusion of the kernel submodule. -/ theorem hasKernels_moduleCat : HasKernels (ModuleCat R) := ⟨fun f => HasLimit.mk ⟨_, kernelIsLimit f⟩⟩ /-- The category of R-modules has cokernels, given by the projection onto the quotient. -/ theorem hasCokernels_moduleCat : HasCokernels (ModuleCat R) := ⟨fun f => HasColimit.mk ⟨_, cokernelIsColimit f⟩⟩ open ModuleCat attribute [local instance] hasKernels_moduleCat attribute [local instance] hasCokernels_moduleCat variable {G H : ModuleCat.{v} R} (f : G ⟶ H) /-- The categorical kernel of a morphism in `ModuleCat` agrees with the usual module-theoretical kernel. -/ noncomputable def kernelIsoKer {G H : ModuleCat.{v} R} (f : G ⟶ H) : -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11036): broken dot notation kernel f ≅ ModuleCat.of R (LinearMap.ker f.hom) := limit.isoLimitCone ⟨_, kernelIsLimit f⟩ -- We now show this isomorphism commutes with the inclusion of the kernel into the source. @[simp, elementwise] -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11036): broken dot notation theorem kernelIsoKer_inv_kernel_ι : (kernelIsoKer f).inv ≫ kernel.ι f = ofHom (LinearMap.ker f.hom).subtype := limit.isoLimitCone_inv_π _ _ @[simp, elementwise] theorem kernelIsoKer_hom_ker_subtype : -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11036): broken dot notation (kernelIsoKer f).hom ≫ ofHom (LinearMap.ker f.hom).subtype = kernel.ι f := IsLimit.conePointUniqueUpToIso_inv_comp _ (limit.isLimit _) WalkingParallelPair.zero /-- The categorical cokernel of a morphism in `ModuleCat` agrees with the usual module-theoretical quotient. -/ noncomputable def cokernelIsoRangeQuotient {G H : ModuleCat.{v} R} (f : G ⟶ H) : -- Porting note (https://github.com/leanprover-community/mathlib4/pull/11036): broken dot notation cokernel f ≅ ModuleCat.of R (H ⧸ LinearMap.range f.hom) := colimit.isoColimitCocone ⟨_, cokernelIsColimit f⟩ -- We now show this isomorphism commutes with the projection of target to the cokernel. @[simp, elementwise] theorem cokernel_π_cokernelIsoRangeQuotient_hom : cokernel.π f ≫ (cokernelIsoRangeQuotient f).hom = ofHom (LinearMap.range f.hom).mkQ := colimit.isoColimitCocone_ι_hom _ _ @[simp, elementwise] theorem range_mkQ_cokernelIsoRangeQuotient_inv : ofHom (LinearMap.range f.hom).mkQ ≫ (cokernelIsoRangeQuotient f).inv = cokernel.π f := colimit.isoColimitCocone_ι_inv ⟨_, cokernelIsColimit f⟩ WalkingParallelPair.one theorem cokernel_π_ext {M N : ModuleCat.{u} R} (f : M ⟶ N) {x y : N} (m : M) (w : x = y + f m) : cokernel.π f x = cokernel.π f y := by subst w simpa only [map_add, add_eq_left] using cokernel.condition_apply f m end ModuleCat
OfScalars.lean
/- Copyright (c) 2024 Edward Watine. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Edward Watine -/ import Mathlib.Analysis.Analytic.ConvergenceRadius /-! # Scalar series This file contains API for analytic functions `∑ cᵢ • xⁱ` defined in terms of scalars `c₀, c₁, c₂, …`. ## Main definitions / results: * `FormalMultilinearSeries.ofScalars`: the formal power series `∑ cᵢ • xⁱ`. * `FormalMultilinearSeries.ofScalarsSum`: the sum of such a power series, if it exists, and zero otherwise. * `FormalMultilinearSeries.ofScalars_radius_eq_(zero/inv/top)_of_tendsto`: the ratio test for an analytic function defined in terms of a formal power series `∑ cᵢ • xⁱ`. * `FormalMultilinearSeries.ofScalars_radius_eq_inv_of_tendsto_ENNReal`: the ratio test for an analytic function using `ENNReal` division for all values `ℝ≥0∞`. -/ namespace FormalMultilinearSeries section Field open ContinuousMultilinearMap variable {𝕜 : Type*} (E : Type*) [Field 𝕜] [Ring E] [Algebra 𝕜 E] [TopologicalSpace E] [IsTopologicalRing E] {c : ℕ → 𝕜} /-- Formal power series of `∑ cᵢ • xⁱ` for some scalar field `𝕜` and ring algebra `E` -/ def ofScalars (c : ℕ → 𝕜) : FormalMultilinearSeries 𝕜 E E := fun n ↦ c n • ContinuousMultilinearMap.mkPiAlgebraFin 𝕜 n E @[simp] theorem ofScalars_eq_zero [Nontrivial E] (n : ℕ) : ofScalars E c n = 0 ↔ c n = 0 := by rw [ofScalars, smul_eq_zero (c := c n) (x := ContinuousMultilinearMap.mkPiAlgebraFin 𝕜 n E)] refine or_iff_left (ContinuousMultilinearMap.ext_iff.1.mt <| not_forall_of_exists_not ?_) use fun _ ↦ 1 simp @[simp] theorem ofScalars_eq_zero_of_scalar_zero {n : ℕ} (hc : c n = 0) : ofScalars E c n = 0 := by rw [ofScalars, hc, zero_smul 𝕜 (ContinuousMultilinearMap.mkPiAlgebraFin 𝕜 n E)] @[simp] theorem ofScalars_series_eq_zero [Nontrivial E] : ofScalars E c = 0 ↔ c = 0 := by simp [FormalMultilinearSeries.ext_iff, funext_iff] variable (𝕜) in @[simp] theorem ofScalars_series_eq_zero_of_scalar_zero : ofScalars E (0 : ℕ → 𝕜) = 0 := by simp [FormalMultilinearSeries.ext_iff] @[simp] theorem ofScalars_series_of_subsingleton [Subsingleton E] : ofScalars E c = 0 := by simp_rw [FormalMultilinearSeries.ext_iff, ofScalars, ContinuousMultilinearMap.ext_iff] exact fun _ _ ↦ Subsingleton.allEq _ _ variable (𝕜) in theorem ofScalars_series_injective [Nontrivial E] : Function.Injective (ofScalars E (𝕜 := 𝕜)) := by intro _ _ refine Function.mtr fun h ↦ ?_ simp_rw [FormalMultilinearSeries.ext_iff, ofScalars, ContinuousMultilinearMap.ext_iff, ContinuousMultilinearMap.smul_apply] push_neg obtain ⟨n, hn⟩ := Function.ne_iff.1 h refine ⟨n, fun _ ↦ 1, ?_⟩ simp only [mkPiAlgebraFin_apply, List.ofFn_const, List.prod_replicate, one_pow, ne_eq] exact (smul_left_injective 𝕜 one_ne_zero).ne hn variable (c) @[simp] theorem ofScalars_series_eq_iff [Nontrivial E] (c' : ℕ → 𝕜) : ofScalars E c = ofScalars E c' ↔ c = c' := ⟨fun e => ofScalars_series_injective 𝕜 E e, _root_.congrArg _⟩ theorem ofScalars_apply_zero (n : ℕ) : ofScalars E c n (fun _ => 0) = Pi.single (M := fun _ => E) 0 (c 0 • 1) n := by rw [ofScalars] cases n <;> simp @[simp] lemma coeff_ofScalars {𝕜 : Type*} [NontriviallyNormedField 𝕜] {p : ℕ → 𝕜} {n : ℕ} : (FormalMultilinearSeries.ofScalars 𝕜 p).coeff n = p n := by simp [FormalMultilinearSeries.coeff, FormalMultilinearSeries.ofScalars, List.prod_ofFn] theorem ofScalars_add (c' : ℕ → 𝕜) : ofScalars E (c + c') = ofScalars E c + ofScalars E c' := by unfold ofScalars simp_rw [Pi.add_apply, Pi.add_def _ _] exact funext fun n ↦ Module.add_smul (c n) (c' n) (ContinuousMultilinearMap.mkPiAlgebraFin 𝕜 n E) theorem ofScalars_smul (x : 𝕜) : ofScalars E (x • c) = x • ofScalars E c := by unfold ofScalars simp [Pi.smul_def x _, smul_smul] variable (𝕜) in /-- The submodule generated by scalar series on `FormalMultilinearSeries 𝕜 E E`. -/ def ofScalarsSubmodule : Submodule 𝕜 (FormalMultilinearSeries 𝕜 E E) where carrier := {ofScalars E f | f} add_mem' := fun ⟨c, hc⟩ ⟨c', hc'⟩ ↦ ⟨c + c', hc' ▸ hc ▸ ofScalars_add E c c'⟩ zero_mem' := ⟨0, ofScalars_series_eq_zero_of_scalar_zero 𝕜 E⟩ smul_mem' := fun x _ ⟨c, hc⟩ ↦ ⟨x • c, hc ▸ ofScalars_smul E c x⟩ variable {E} theorem ofScalars_apply_eq (x : E) (n : ℕ) : ofScalars E c n (fun _ ↦ x) = c n • x ^ n := by simp [ofScalars] /-- This naming follows the convention of `NormedSpace.expSeries_apply_eq'`. -/ theorem ofScalars_apply_eq' (x : E) : (fun n ↦ ofScalars E c n (fun _ ↦ x)) = fun n ↦ c n • x ^ n := by simp [ofScalars] /-- The sum of the formal power series. Takes the value `0` outside the radius of convergence. -/ noncomputable def ofScalarsSum := (ofScalars E c).sum theorem ofScalars_sum_eq (x : E) : ofScalarsSum c x = ∑' n, c n • x ^ n := tsum_congr fun n => ofScalars_apply_eq c x n theorem ofScalarsSum_eq_tsum : ofScalarsSum c = fun (x : E) => ∑' n : ℕ, c n • x ^ n := funext (ofScalars_sum_eq c) @[simp] theorem ofScalarsSum_zero : ofScalarsSum c (0 : E) = c 0 • 1 := by simp [ofScalarsSum_eq_tsum, ← ofScalars_apply_eq, ofScalars_apply_zero] @[simp] theorem ofScalarsSum_of_subsingleton [Subsingleton E] {x : E} : ofScalarsSum c x = 0 := by simp [Subsingleton.eq_zero x, Subsingleton.eq_zero (1 : E)] @[simp] theorem ofScalarsSum_op [T2Space E] (x : E) : ofScalarsSum c (MulOpposite.op x) = MulOpposite.op (ofScalarsSum c x) := by simp [ofScalars_sum_eq, ← MulOpposite.op_pow, ← MulOpposite.op_smul, tsum_op] @[simp] theorem ofScalarsSum_unop [T2Space E] (x : Eᵐᵒᵖ) : ofScalarsSum c (MulOpposite.unop x) = MulOpposite.unop (ofScalarsSum c x) := by simp [ofScalars_sum_eq, ← MulOpposite.unop_pow, ← MulOpposite.unop_smul, tsum_unop] end Field section Seminormed open Filter ENNReal open scoped Topology NNReal variable {𝕜 : Type*} (E : Type*) [NontriviallyNormedField 𝕜] [SeminormedRing E] [NormedAlgebra 𝕜 E] (c : ℕ → 𝕜) (n : ℕ) theorem ofScalars_norm_eq_mul : ‖ofScalars E c n‖ = ‖c n‖ * ‖ContinuousMultilinearMap.mkPiAlgebraFin 𝕜 n E‖ := by rw [ofScalars, norm_smul] theorem ofScalars_norm_le (hn : n > 0) : ‖ofScalars E c n‖ ≤ ‖c n‖ := by simp only [ofScalars_norm_eq_mul] exact (mul_le_of_le_one_right (norm_nonneg _) (ContinuousMultilinearMap.norm_mkPiAlgebraFin_le_of_pos hn)) @[simp] theorem ofScalars_norm [NormOneClass E] : ‖ofScalars E c n‖ = ‖c n‖ := by simp [ofScalars_norm_eq_mul] end Seminormed section Normed open Filter ENNReal open scoped Topology NNReal variable {𝕜 : Type*} (E : Type*) [NontriviallyNormedField 𝕜] [NormedRing E] [NormedAlgebra 𝕜 E] (c : ℕ → 𝕜) (n : ℕ) private theorem tendsto_succ_norm_div_norm {r r' : ℝ≥0} (hr' : r' ≠ 0) (hc : Tendsto (fun n ↦ ‖c n.succ‖ / ‖c n‖) atTop (𝓝 r)) : Tendsto (fun n ↦ ‖‖c (n + 1)‖ * r' ^ (n + 1)‖ / ‖‖c n‖ * r' ^ n‖) atTop (𝓝 ↑(r' * r)) := by simp_rw [norm_mul, norm_norm, mul_div_mul_comm, ← norm_div, pow_succ, mul_div_right_comm, div_self (pow_ne_zero _ (NNReal.coe_ne_zero.mpr hr')), one_mul, norm_div, NNReal.norm_eq] exact mul_comm r' r ▸ hc.mul tendsto_const_nhds theorem ofScalars_radius_ge_inv_of_tendsto {r : ℝ≥0} (hr : r ≠ 0) (hc : Tendsto (fun n ↦ ‖c n.succ‖ / ‖c n‖) atTop (𝓝 r)) : (ofScalars E c).radius ≥ ofNNReal r⁻¹ := by refine le_of_forall_nnreal_lt (fun r' hr' ↦ ?_) rw [coe_lt_coe, NNReal.lt_inv_iff_mul_lt hr] at hr' by_cases hrz : r' = 0 · simp [hrz] apply FormalMultilinearSeries.le_radius_of_summable_norm refine Summable.of_norm_bounded_eventually (g := fun n ↦ ‖‖c n‖ * r' ^ n‖) ?_ ?_ · refine summable_of_ratio_test_tendsto_lt_one hr' ?_ ?_ · refine (hc.eventually_ne (NNReal.coe_ne_zero.mpr hr)).mp (Eventually.of_forall ?_) aesop · simp_rw [norm_norm] exact tendsto_succ_norm_div_norm c hrz hc · filter_upwards [eventually_cofinite_ne 0] with n hn simp only [norm_mul, norm_norm, norm_pow, NNReal.norm_eq] gcongr exact ofScalars_norm_le E c n (Nat.pos_iff_ne_zero.mpr hn) /-- The radius of convergence of a scalar series is the inverse of the non-zero limit `fun n ↦ ‖c n.succ‖ / ‖c n‖`. -/ theorem ofScalars_radius_eq_inv_of_tendsto [NormOneClass E] {r : ℝ≥0} (hr : r ≠ 0) (hc : Tendsto (fun n ↦ ‖c n.succ‖ / ‖c n‖) atTop (𝓝 r)) : (ofScalars E c).radius = ofNNReal r⁻¹ := by refine le_antisymm ?_ (ofScalars_radius_ge_inv_of_tendsto E c hr hc) refine le_of_forall_nnreal_lt (fun r' hr' ↦ ?_) rw [coe_le_coe, NNReal.le_inv_iff_mul_le hr] have := FormalMultilinearSeries.summable_norm_mul_pow _ hr' contrapose! this apply not_summable_of_ratio_test_tendsto_gt_one this simp_rw [ofScalars_norm] exact tendsto_succ_norm_div_norm c (by aesop) hc /-- A convenience lemma restating the result of `ofScalars_radius_eq_inv_of_tendsto` under the inverse ratio. -/ theorem ofScalars_radius_eq_of_tendsto [NormOneClass E] {r : NNReal} (hr : r ≠ 0) (hc : Tendsto (fun n ↦ ‖c n‖ / ‖c n.succ‖) atTop (𝓝 r)) : (ofScalars E c).radius = ofNNReal r := by suffices Tendsto (fun n ↦ ‖c n.succ‖ / ‖c n‖) atTop (𝓝 r⁻¹) by convert ofScalars_radius_eq_inv_of_tendsto E c (inv_ne_zero hr) this simp convert hc.inv₀ (NNReal.coe_ne_zero.mpr hr) using 1 simp /-- The ratio test stating that if `‖c n.succ‖ / ‖c n‖` tends to zero, the radius is unbounded. This requires that the coefficients are eventually non-zero as `‖c n.succ‖ / 0 = 0` by convention. -/ theorem ofScalars_radius_eq_top_of_tendsto (hc : ∀ᶠ n in atTop, c n ≠ 0) (hc' : Tendsto (fun n ↦ ‖c n.succ‖ / ‖c n‖) atTop (𝓝 0)) : (ofScalars E c).radius = ⊤ := by refine radius_eq_top_of_summable_norm _ fun r' ↦ ?_ by_cases hrz : r' = 0 · apply Summable.comp_nat_add (k := 1) simp [hrz] exact (summable_const_iff 0).mpr rfl · refine Summable.of_norm_bounded_eventually (g := fun n ↦ ‖‖c n‖ * r' ^ n‖) ?_ ?_ · apply summable_of_ratio_test_tendsto_lt_one zero_lt_one (hc.mp (Eventually.of_forall ?_)) · simp only [norm_norm] exact mul_zero (_ : ℝ) ▸ tendsto_succ_norm_div_norm _ hrz (NNReal.coe_zero ▸ hc') · aesop · filter_upwards [eventually_cofinite_ne 0] with n hn simp only [norm_mul, norm_norm, norm_pow, NNReal.norm_eq] gcongr exact ofScalars_norm_le E c n (Nat.pos_iff_ne_zero.mpr hn) /-- If `‖c n.succ‖ / ‖c n‖` is unbounded, then the radius of convergence is zero. -/ theorem ofScalars_radius_eq_zero_of_tendsto [NormOneClass E] (hc : Tendsto (fun n ↦ ‖c n.succ‖ / ‖c n‖) atTop atTop) : (ofScalars E c).radius = 0 := by suffices (ofScalars E c).radius ≤ 0 by aesop refine le_of_forall_nnreal_lt (fun r hr ↦ ?_) rw [← coe_zero, coe_le_coe] have := FormalMultilinearSeries.summable_norm_mul_pow _ hr contrapose! this apply not_summable_of_ratio_norm_eventually_ge one_lt_two · contrapose! hc apply not_tendsto_atTop_of_tendsto_nhds (a:=0) rw [not_frequently] at hc apply Tendsto.congr' ?_ tendsto_const_nhds filter_upwards [hc] with n hc' rw [ofScalars_norm, norm_mul, norm_norm, not_ne_iff, mul_eq_zero] at hc' cases hc' <;> aesop · filter_upwards [hc.eventually_ge_atTop (2*r⁻¹), eventually_ne_atTop 0] with n hc hn simp only [ofScalars_norm, norm_mul, norm_norm, norm_pow, NNReal.norm_eq] rw [mul_comm ‖c n‖, ← mul_assoc, ← div_le_div_iff₀, mul_div_assoc] · convert hc rw [pow_succ, div_mul_cancel_left₀, NNReal.coe_inv] aesop · aesop · refine Ne.lt_of_le (fun hr' ↦ Not.elim ?_ hc) (norm_nonneg _) rw [← hr'] simp [this] /-- This theorem combines the results of the special cases above, using `ENNReal` division to remove the requirement that the ratio is eventually non-zero. -/ theorem ofScalars_radius_eq_inv_of_tendsto_ENNReal [NormOneClass E] {r : ℝ≥0∞} (hc' : Tendsto (fun n ↦ ENNReal.ofReal ‖c n.succ‖ / ENNReal.ofReal ‖c n‖) atTop (𝓝 r)) : (ofScalars E c).radius = r⁻¹ := by rcases ENNReal.trichotomy r with (hr | hr | hr) · simp_rw [hr, inv_zero] at hc' ⊢ by_cases h : (∀ᶠ (n : ℕ) in atTop, c n ≠ 0) · apply ofScalars_radius_eq_top_of_tendsto E c h ?_ refine Tendsto.congr' ?_ <| (tendsto_toReal zero_ne_top).comp hc' filter_upwards [h] simp · apply (ofScalars E c).radius_eq_top_of_eventually_eq_zero simp only [eventually_atTop, not_exists, not_forall, not_not] at h ⊢ obtain ⟨ti, hti⟩ := eventually_atTop.mp (hc'.eventually_ne zero_ne_top) obtain ⟨zi, hzi, z⟩ := h ti refine ⟨zi, Nat.le_induction (ofScalars_eq_zero_of_scalar_zero E z) fun n hmn a ↦ ?_⟩ nontriviality E simp only [ofScalars_eq_zero] at a ⊢ contrapose! hti exact ⟨n, hzi.trans hmn, ENNReal.div_eq_top.mpr (by simp [a, hti])⟩ · simp_rw [hr, inv_top] at hc' ⊢ apply ofScalars_radius_eq_zero_of_tendsto E c ((tendsto_add_atTop_iff_nat 1).mp ?_) refine tendsto_ofReal_nhds_top.mp (Tendsto.congr' ?_ ((tendsto_add_atTop_iff_nat 1).mpr hc')) filter_upwards [hc'.eventually_ne top_ne_zero] with n hn apply (ofReal_div_of_pos (Ne.lt_of_le (Ne.symm ?_) (norm_nonneg _))).symm aesop · have hr' := toReal_ne_zero.mp hr.ne.symm have hr'' := toNNReal_ne_zero.mpr hr' -- this result could go in ENNReal convert ofScalars_radius_eq_inv_of_tendsto E c hr'' ?_ · simp [ENNReal.coe_inv hr'', ENNReal.coe_toNNReal (toReal_ne_zero.mp hr.ne.symm).2] · simp_rw [ENNReal.coe_toNNReal_eq_toReal] refine Tendsto.congr' ?_ <| (tendsto_toReal hr'.2).comp hc' filter_upwards [hc'.eventually_ne hr'.1, hc'.eventually_ne hr'.2] simp end Normed end FormalMultilinearSeries
HeytAlg.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.Category.BddDistLat import Mathlib.Order.Heyting.Hom /-! # The category of Heyting algebras This file defines `HeytAlg`, the category of Heyting algebras. -/ universe u open CategoryTheory Opposite Order /-- The category of Heyting algebras. -/ structure HeytAlg where /-- The underlying Heyting algebra. -/ carrier : Type* [str : HeytingAlgebra carrier] attribute [instance] HeytAlg.str initialize_simps_projections HeytAlg (carrier → coe, -str) namespace HeytAlg instance : CoeSort HeytAlg (Type _) := ⟨HeytAlg.carrier⟩ attribute [coe] HeytAlg.carrier /-- Construct a bundled `HeytAlg` from the underlying type and typeclass. -/ abbrev of (X : Type*) [HeytingAlgebra X] : HeytAlg := ⟨X⟩ /-- The type of morphisms in `HeytAlg R`. -/ @[ext] structure Hom (X Y : HeytAlg.{u}) where private mk :: /-- The underlying `HeytingHom`. -/ hom' : HeytingHom X Y instance : Category HeytAlg.{u} where Hom X Y := Hom X Y id X := ⟨HeytingHom.id X⟩ comp f g := ⟨g.hom'.comp f.hom'⟩ instance : ConcreteCategory HeytAlg (HeytingHom · ·) where hom := Hom.hom' ofHom := Hom.mk /-- Turn a morphism in `HeytAlg` back into a `HeytingHom`. -/ abbrev Hom.hom {X Y : HeytAlg.{u}} (f : Hom X Y) := ConcreteCategory.hom (C := HeytAlg) f /-- Typecheck a `HeytingHom` as a morphism in `HeytAlg`. -/ abbrev ofHom {X Y : Type u} [HeytingAlgebra X] [HeytingAlgebra Y] (f : HeytingHom X Y) : of X ⟶ of Y := ConcreteCategory.ofHom (C := HeytAlg) f variable {R} in /-- Use the `ConcreteCategory.hom` projection for `@[simps]` lemmas. -/ def Hom.Simps.hom (X Y : HeytAlg.{u}) (f : Hom X Y) := f.hom initialize_simps_projections Hom (hom' → hom) /-! The results below duplicate the `ConcreteCategory` simp lemmas, but we can keep them for `dsimp`. -/ @[simp] lemma coe_id {X : HeytAlg} : (𝟙 X : X → X) = id := rfl @[simp] lemma coe_comp {X Y Z : HeytAlg} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g : X → Z) = g ∘ f := rfl @[simp] lemma forget_map {X Y : HeytAlg} (f : X ⟶ Y) : (forget HeytAlg).map f = f := rfl @[ext] lemma ext {X Y : HeytAlg} {f g : X ⟶ Y} (w : ∀ x : X, f x = g x) : f = g := ConcreteCategory.hom_ext _ _ w -- This is not `simp` to avoid rewriting in types of terms. theorem coe_of (X : Type u) [HeytingAlgebra X] : (HeytAlg.of X : Type u) = X := rfl @[simp] lemma hom_id {X : HeytAlg} : (𝟙 X : X ⟶ X).hom = HeytingHom.id _ := rfl /- Provided for rewriting. -/ lemma id_apply (X : HeytAlg) (x : X) : (𝟙 X : X ⟶ X) x = x := by simp @[simp] lemma hom_comp {X Y Z : HeytAlg} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).hom = g.hom.comp f.hom := rfl /- Provided for rewriting. -/ lemma comp_apply {X Y Z : HeytAlg} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := by simp @[ext] lemma hom_ext {X Y : HeytAlg} {f g : X ⟶ Y} (hf : f.hom = g.hom) : f = g := Hom.ext hf @[simp] lemma hom_ofHom {X Y : Type u} [HeytingAlgebra X] [HeytingAlgebra Y] (f : HeytingHom X Y) : (ofHom f).hom = f := rfl @[simp] lemma ofHom_hom {X Y : HeytAlg} (f : X ⟶ Y) : ofHom (Hom.hom f) = f := rfl @[simp] lemma ofHom_id {X : Type u} [HeytingAlgebra X] : ofHom (HeytingHom.id _) = 𝟙 (of X) := rfl @[simp] lemma ofHom_comp {X Y Z : Type u} [HeytingAlgebra X] [HeytingAlgebra Y] [HeytingAlgebra Z] (f : HeytingHom X Y) (g : HeytingHom Y Z) : ofHom (g.comp f) = ofHom f ≫ ofHom g := rfl lemma ofHom_apply {X Y : Type u} [HeytingAlgebra X] [HeytingAlgebra Y] (f : HeytingHom X Y) (x : X) : (ofHom f) x = f x := rfl lemma inv_hom_apply {X Y : HeytAlg} (e : X ≅ Y) (x : X) : e.inv (e.hom x) = x := by simp lemma hom_inv_apply {X Y : HeytAlg} (e : X ≅ Y) (s : Y) : e.hom (e.inv s) = s := by simp instance : Inhabited HeytAlg := ⟨of PUnit⟩ @[simps] instance hasForgetToLat : HasForget₂ HeytAlg BddDistLat where forget₂.obj X := .of X forget₂.map f := BddDistLat.ofHom f.hom /-- Constructs an isomorphism of Heyting algebras from an order isomorphism between them. -/ @[simps] def Iso.mk {α β : HeytAlg.{u}} (e : α ≃o β) : α ≅ β where hom := ofHom e inv := ofHom e.symm hom_inv_id := by ext; exact e.symm_apply_apply _ inv_hom_id := by ext; exact e.apply_symm_apply _ end HeytAlg
VectorSpace.lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Mathlib.Algebra.Group.UniqueProds.Basic import Mathlib.LinearAlgebra.Basis.VectorSpace /-! # A `ℚ`-vector space has `TwoUniqueSums`. -/ variable {G : Type*} /-- Any `ℚ`-vector space has `TwoUniqueSums`, because it is isomorphic to some `(Basis.ofVectorSpaceIndex ℚ G) →₀ ℚ` by choosing a basis, and `ℚ` already has `TwoUniqueSums` because it's ordered. -/ instance [AddCommGroup G] [Module ℚ G] : TwoUniqueSums G := TwoUniqueSums.of_injective_addHom _ (Module.Basis.ofVectorSpace ℚ G).repr.injective inferInstance
Dyadic.lean
/- Copyright (c) 2021 Apurva Nakade. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Apurva Nakade -/ import Mathlib.Algebra.Algebra.Defs import Mathlib.Algebra.Order.Group.Basic import Mathlib.Algebra.Ring.Regular import Mathlib.GroupTheory.MonoidLocalization.Away import Mathlib.RingTheory.Localization.Defs import Mathlib.SetTheory.Game.Birthday import Mathlib.SetTheory.Surreal.Multiplication import Mathlib.Tactic.Linarith import Mathlib.Tactic.Linter.DeprecatedModule deprecated_module "This module is now at `CombinatorialGames.Surreal.Dyadic` in the CGT repo <https://github.com/vihdzp/combinatorial-games>" (since := "2025-08-06") /-! # Dyadic numbers Dyadic numbers are obtained by localizing ℤ away from 2. They are the initial object in the category of rings with no 2-torsion. ## Dyadic surreal numbers We construct dyadic surreal numbers using the canonical map from ℤ[2 ^ {-1}] to surreals. As we currently do not have a ring structure on `Surreal` we construct this map explicitly. Once we have the ring structure, this map can be constructed directly by sending `2 ^ {-1}` to `half`. ## Embeddings The above construction gives us an abelian group embedding of ℤ into `Surreal`. The goal is to extend this to an embedding of dyadic rationals into `Surreal` and use Cauchy sequences of dyadic rational numbers to construct an ordered field embedding of ℝ into `Surreal`. -/ universe u namespace SetTheory namespace PGame /-- For a natural number `n`, the pre-game `powHalf (n + 1)` is recursively defined as `{0 | powHalf n}`. These are the explicit expressions of powers of `1 / 2`. By definition, we have `powHalf 0 = 1` and `powHalf 1 ≈ 1 / 2` and we prove later on that `powHalf (n + 1) + powHalf (n + 1) ≈ powHalf n`. -/ def powHalf : ℕ → PGame | 0 => 1 | n + 1 => ⟨PUnit, PUnit, 0, fun _ => powHalf n⟩ @[simp] theorem powHalf_zero : powHalf 0 = 1 := rfl theorem powHalf_leftMoves (n) : (powHalf n).LeftMoves = PUnit := by cases n <;> rfl theorem powHalf_zero_rightMoves : (powHalf 0).RightMoves = PEmpty := rfl theorem powHalf_succ_rightMoves (n) : (powHalf (n + 1)).RightMoves = PUnit := rfl @[simp] theorem powHalf_moveLeft (n i) : (powHalf n).moveLeft i = 0 := by cases n <;> cases i <;> rfl @[simp] theorem powHalf_succ_moveRight (n i) : (powHalf (n + 1)).moveRight i = powHalf n := rfl instance uniquePowHalfLeftMoves (n) : Unique (powHalf n).LeftMoves := by cases n <;> exact PUnit.instUnique instance isEmpty_powHalf_zero_rightMoves : IsEmpty (powHalf 0).RightMoves := inferInstanceAs (IsEmpty PEmpty) instance uniquePowHalfSuccRightMoves (n) : Unique (powHalf (n + 1)).RightMoves := PUnit.instUnique @[simp] theorem birthday_half : birthday (powHalf 1) = 2 := by rw [birthday_def]; simp /-- For all natural numbers `n`, the pre-games `powHalf n` are numeric. -/ theorem numeric_powHalf (n) : (powHalf n).Numeric := by induction n with | zero => exact numeric_one | succ n hn => constructor · simpa using hn.moveLeft_lt default · exact ⟨fun _ => numeric_zero, fun _ => hn⟩ theorem powHalf_succ_lt_powHalf (n : ℕ) : powHalf (n + 1) < powHalf n := (numeric_powHalf (n + 1)).lt_moveRight default theorem powHalf_succ_le_powHalf (n : ℕ) : powHalf (n + 1) ≤ powHalf n := (powHalf_succ_lt_powHalf n).le theorem powHalf_le_one (n : ℕ) : powHalf n ≤ 1 := by induction n with | zero => exact le_rfl | succ n hn => exact (powHalf_succ_le_powHalf n).trans hn theorem powHalf_succ_lt_one (n : ℕ) : powHalf (n + 1) < 1 := (powHalf_succ_lt_powHalf n).trans_le <| powHalf_le_one n theorem powHalf_pos (n : ℕ) : 0 < powHalf n := by rw [← lf_iff_lt numeric_zero (numeric_powHalf n), zero_lf_le]; simp theorem zero_le_powHalf (n : ℕ) : 0 ≤ powHalf n := (powHalf_pos n).le theorem add_powHalf_succ_self_eq_powHalf (n) : powHalf (n + 1) + powHalf (n + 1) ≈ powHalf n := by induction n using Nat.strong_induction_on with | _ n hn constructor <;> rw [le_iff_forall_lf] <;> constructor · rintro (⟨⟨⟩⟩ | ⟨⟨⟩⟩) <;> apply lf_of_lt · calc 0 + powHalf n.succ ≈ powHalf n.succ := zero_add_equiv _ _ < powHalf n := powHalf_succ_lt_powHalf n · calc powHalf n.succ + 0 ≈ powHalf n.succ := add_zero_equiv _ _ < powHalf n := powHalf_succ_lt_powHalf n · rcases n with - | n · rintro ⟨⟩ rintro ⟨⟩ apply lf_of_moveRight_le swap · exact Sum.inl default calc powHalf n.succ + powHalf (n.succ + 1) ≤ powHalf n.succ + powHalf n.succ := add_le_add_left (powHalf_succ_le_powHalf _) _ _ ≈ powHalf n := hn _ (Nat.lt_succ_self n) · simp only [powHalf_moveLeft, forall_const] apply lf_of_lt calc 0 ≈ 0 + 0 := Equiv.symm (add_zero_equiv 0) _ ≤ powHalf n.succ + 0 := add_le_add_right (zero_le_powHalf _) _ _ < powHalf n.succ + powHalf n.succ := add_lt_add_left (powHalf_pos _) _ · rintro (⟨⟨⟩⟩ | ⟨⟨⟩⟩) <;> apply lf_of_lt · calc powHalf n ≈ powHalf n + 0 := Equiv.symm (add_zero_equiv _) _ < powHalf n + powHalf n.succ := add_lt_add_left (powHalf_pos _) _ · calc powHalf n ≈ 0 + powHalf n := Equiv.symm (zero_add_equiv _) _ < powHalf n.succ + powHalf n := add_lt_add_right (powHalf_pos _) _ theorem half_add_half_equiv_one : powHalf 1 + powHalf 1 ≈ 1 := add_powHalf_succ_self_eq_powHalf 0 end PGame end SetTheory namespace Surreal open SetTheory PGame /-- Powers of the surreal number `half`. -/ def powHalf (n : ℕ) : Surreal := ⟦⟨PGame.powHalf n, PGame.numeric_powHalf n⟩⟧ @[simp] theorem powHalf_zero : powHalf 0 = 1 := rfl @[simp] theorem double_powHalf_succ_eq_powHalf (n : ℕ) : 2 * powHalf (n + 1) = powHalf n := by rw [two_mul]; exact Quotient.sound (PGame.add_powHalf_succ_self_eq_powHalf n) @[simp] theorem nsmul_pow_two_powHalf (n : ℕ) : 2 ^ n * powHalf n = 1 := by induction n with | zero => simp only [pow_zero, powHalf_zero, mul_one] | succ n hn => rw [← hn, ← double_powHalf_succ_eq_powHalf n, ← mul_assoc (2 ^ n) 2 (powHalf (n + 1)), pow_succ', mul_comm 2 (2 ^ n)] @[simp] theorem nsmul_pow_two_powHalf' (n k : ℕ) : 2 ^ n * powHalf (n + k) = powHalf k := by induction k with | zero => simp only [add_zero, Surreal.nsmul_pow_two_powHalf, Surreal.powHalf_zero] | succ k hk => rw [← double_powHalf_succ_eq_powHalf (n + k), ← double_powHalf_succ_eq_powHalf k, ← mul_assoc, mul_comm (2 ^ n) 2, mul_assoc] at hk rw [← zsmul_eq_zsmul_iff' two_ne_zero] simpa only [zsmul_eq_mul, Int.cast_ofNat] theorem zsmul_pow_two_powHalf (m : ℤ) (n k : ℕ) : (m * 2 ^ n) * powHalf (n + k) = m * powHalf k := by rw [mul_assoc] congr exact nsmul_pow_two_powHalf' n k theorem dyadic_aux {m₁ m₂ : ℤ} {y₁ y₂ : ℕ} (h₂ : m₁ * 2 ^ y₁ = m₂ * 2 ^ y₂) : m₁ * powHalf y₂ = m₂ * powHalf y₁ := by revert m₁ m₂ wlog h : y₁ ≤ y₂ · intro m₁ m₂ aux; exact (this (le_of_not_ge h) aux.symm).symm intro m₁ m₂ h₂ obtain ⟨c, rfl⟩ := le_iff_exists_add.mp h rw [add_comm, pow_add, ← mul_assoc, mul_eq_mul_right_iff] at h₂ rcases h₂ with h₂ | h₂ · rw [h₂, add_comm] simp_rw [Int.cast_mul, Int.cast_pow, Int.cast_ofNat, zsmul_pow_two_powHalf m₂ c y₁] · have := Nat.one_le_pow y₁ 2 Nat.succ_pos' norm_cast at h₂; omega /-- The additive monoid morphism `dyadicMap` sends ⟦⟨m, 2^n⟩⟧ to m • half ^ n. -/ noncomputable def dyadicMap : Localization.Away (2 : ℤ) →+ Surreal where toFun x := (Localization.liftOn x fun x y => x * powHalf (Submonoid.log y)) <| by intro m₁ m₂ n₁ n₂ h₁ obtain ⟨⟨n₃, y₃, hn₃⟩, h₂⟩ := Localization.r_iff_exists.mp h₁ simp only [mul_eq_mul_left_iff] at h₂ cases h₂ · obtain ⟨a₁, ha₁⟩ := n₁.prop obtain ⟨a₂, ha₂⟩ := n₂.prop simp only at ha₁ ha₂ ⊢ have hn₁ : n₁ = Submonoid.pow 2 a₁ := Subtype.ext ha₁.symm have hn₂ : n₂ = Submonoid.pow 2 a₂ := Subtype.ext ha₂.symm have h₂ : 1 < (2 : ℤ).natAbs := one_lt_two rw [hn₁, hn₂, Submonoid.log_pow_int_eq_self h₂, Submonoid.log_pow_int_eq_self h₂] apply dyadic_aux rwa [ha₁, ha₂, mul_comm, mul_comm m₂] · have : (1 : ℤ) ≤ 2 ^ y₃ := mod_cast Nat.one_le_pow y₃ 2 Nat.succ_pos' linarith map_zero' := by simp_rw [Localization.liftOn_zero _ _, Int.cast_zero, zero_mul] map_add' x y := Localization.induction_on₂ x y <| by rintro ⟨a, ⟨b, ⟨b', rfl⟩⟩⟩ ⟨c, ⟨d, ⟨d', rfl⟩⟩⟩ have h₂ : 1 < (2 : ℤ).natAbs := one_lt_two have hpow₂ := Submonoid.log_pow_int_eq_self h₂ simp_rw [Submonoid.pow_apply] at hpow₂ simp_rw [Localization.add_mk, Localization.liftOn_mk, Submonoid.log_mul (Int.pow_right_injective h₂), hpow₂] simp only [Int.cast_add, Int.cast_mul, Int.cast_pow, Int.cast_ofNat] calc (2 ^ b' * c + 2 ^ d' * a) * powHalf (b' + d') = (c * 2 ^ b') * powHalf (b' + d') + (a * 2 ^ d') * powHalf (d' + b') := by simp only [right_distrib, mul_comm, add_comm] _ = c * powHalf d' + a * powHalf b' := by simp only [zsmul_pow_two_powHalf] _ = a * powHalf b' + c * powHalf d' := add_comm _ _ @[simp] theorem dyadicMap_apply (m : ℤ) (p : Submonoid.powers (2 : ℤ)) : dyadicMap (IsLocalization.mk' (Localization (Submonoid.powers 2)) m p) = m * powHalf (Submonoid.log p) := by rw [← Localization.mk_eq_mk']; rfl theorem dyadicMap_apply_pow (m : ℤ) (n : ℕ) : dyadicMap (IsLocalization.mk' (Localization (Submonoid.powers 2)) m (Submonoid.pow 2 n)) = m • powHalf n := by rw [dyadicMap_apply, @Submonoid.log_pow_int_eq_self 2 one_lt_two] simp only [zsmul_eq_mul] @[simp] theorem dyadicMap_apply_pow' (m : ℤ) (n : ℕ) : m * Surreal.powHalf (Submonoid.log (Submonoid.pow (2 : ℤ) n)) = m * powHalf n := by rw [@Submonoid.log_pow_int_eq_self 2 one_lt_two] /-- We define dyadic surreals as the range of the map `dyadicMap`. -/ def dyadic : Set Surreal := Set.range dyadicMap -- We conclude with some ideas for further work on surreals; these would make fun projects. -- TODO show that the map from dyadic rationals to surreals is injective -- TODO map the reals into the surreals, using dyadic Dedekind cuts -- TODO show this is a group homomorphism, and injective -- TODO show the maps from the dyadic rationals and from the reals -- into the surreals are multiplicative end Surreal
IntermediateField.lean
/- Copyright (c) 2024 Jiedong Jiang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jiedong Jiang -/ import Mathlib.FieldTheory.IntermediateField.Adjoin.Defs import Mathlib.Topology.Algebra.Field /-! # Continuous actions related to intermediate fields In this file we define the instances related to continuous actions of intermediate fields. The topology on intermediate fields is already defined in earlier file `Mathlib/Topology/Algebra/Field.lean` as the subspace topology. -/ variable {K L : Type*} [Field K] [Field L] [Algebra K L] [TopologicalSpace L] [IsTopologicalRing L] variable (X : Type*) [TopologicalSpace X] [MulAction L X] [ContinuousSMul L X] variable (M : IntermediateField K L) instance IntermediateField.continuousSMul (M : IntermediateField K L) : ContinuousSMul M X := M.toSubfield.continuousSMul X instance IntermediateField.botContinuousSMul (M : IntermediateField K L) : ContinuousSMul (⊥ : IntermediateField K L) M := Topology.IsInducing.continuousSMul (X := L) (N := (⊥ : IntermediateField K L)) (Y := M) (M := (⊥ : IntermediateField K L)) Topology.IsInducing.subtypeVal continuous_id rfl
Interval.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.Data.Finset.Finsupp import Mathlib.Data.Finsupp.Order import Mathlib.Order.Interval.Finset.Basic /-! # Finite intervals of finitely supported functions This file provides the `LocallyFiniteOrder` instance for `ι →₀ α` when `α` itself is locally finite and calculates the cardinality of its finite intervals. ## Main declarations * `Finsupp.rangeSingleton`: Postcomposition with `Singleton.singleton` on `Finset` as a `Finsupp`. * `Finsupp.rangeIcc`: Postcomposition with `Finset.Icc` as a `Finsupp`. Both these definitions use the fact that `0 = {0}` to ensure that the resulting function is finitely supported. -/ noncomputable section open Finset Finsupp Function Pointwise variable {ι α : Type*} namespace Finsupp section RangeSingleton variable [Zero α] {f : ι →₀ α} {i : ι} {a : α} /-- Pointwise `Singleton.singleton` bundled as a `Finsupp`. -/ @[simps] def rangeSingleton (f : ι →₀ α) : ι →₀ Finset α where toFun i := {f i} support := f.support mem_support_toFun i := by rw [← not_iff_not, notMem_support_iff, not_ne_iff] exact singleton_injective.eq_iff.symm theorem mem_rangeSingleton_apply_iff : a ∈ f.rangeSingleton i ↔ a = f i := mem_singleton end RangeSingleton section RangeIcc variable [Zero α] [PartialOrder α] [LocallyFiniteOrder α] [DecidableEq ι] variable {f g : ι →₀ α} {i : ι} {a : α} /-- Pointwise `Finset.Icc` bundled as a `Finsupp`. -/ @[simps toFun] def rangeIcc (f g : ι →₀ α) : ι →₀ Finset α where toFun i := Icc (f i) (g i) support := f.support ∪ g.support mem_support_toFun i := by rw [mem_union, ← not_iff_not, not_or, notMem_support_iff, notMem_support_iff, not_ne_iff] exact Icc_eq_singleton_iff.symm lemma coe_rangeIcc (f g : ι →₀ α) : rangeIcc f g i = Icc (f i) (g i) := rfl @[simp] theorem rangeIcc_support (f g : ι →₀ α) : (rangeIcc f g).support = f.support ∪ g.support := rfl theorem mem_rangeIcc_apply_iff : a ∈ f.rangeIcc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc end RangeIcc section PartialOrder variable [PartialOrder α] [Zero α] [LocallyFiniteOrder α] [DecidableEq ι] [DecidableEq α] variable (f g : ι →₀ α) instance instLocallyFiniteOrder : LocallyFiniteOrder (ι →₀ α) := LocallyFiniteOrder.ofIcc (ι →₀ α) (fun f g => (f.support ∪ g.support).finsupp <| f.rangeIcc g) fun f g x => by refine (mem_finsupp_iff_of_support_subset <| Finset.subset_of_eq <| rangeIcc_support _ _).trans ?_ simp_rw [mem_rangeIcc_apply_iff] exact forall_and theorem Icc_eq : Icc f g = (f.support ∪ g.support).finsupp (f.rangeIcc g) := rfl theorem card_Icc : #(Icc f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)):= by simp_rw [Icc_eq, card_finsupp, coe_rangeIcc] theorem card_Ico : #(Ico f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] theorem card_Ioc : #(Ioc f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] theorem card_Ioo : #(Ioo f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end PartialOrder section Lattice variable [Lattice α] [Zero α] [LocallyFiniteOrder α] (f g : ι →₀ α) open scoped Classical in theorem card_uIcc : #(uIcc f g) = ∏ i ∈ f.support ∪ g.support, #(uIcc (f i) (g i)) := by rw [← support_inf_union_support_sup]; exact card_Icc (_ : ι →₀ α) _ end Lattice section CanonicallyOrdered variable [AddCommMonoid α] [PartialOrder α] [CanonicallyOrderedAdd α] [OrderBot α] [LocallyFiniteOrder α] variable [DecidableEq ι] [DecidableEq α] (f : ι →₀ α) theorem card_Iic : #(Iic f) = ∏ i ∈ f.support, #(Iic (f i)) := by classical simp_rw [Iic_eq_Icc, card_Icc, Finsupp.bot_eq_zero, support_zero, empty_union, zero_apply, bot_eq_zero] theorem card_Iio : #(Iio f) = ∏ i ∈ f.support, #(Iic (f i)) - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic] end CanonicallyOrdered end Finsupp
Localization.lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.RingTheory.Ideal.MinimalPrime.Basic import Mathlib.RingTheory.Localization.AtPrime.Basic /-! # Minimal primes and localization We provide various results concerning the minimal primes above an ideal that needs the theory of localizations ## Main results - `Ideal.exists_minimalPrimes_comap_eq` If `p` is a minimal prime over `f ⁻¹ I`, then it is the preimage of some minimal prime over `I`. - `Ideal.minimalPrimes_eq_comap`: The minimal primes over `I` are precisely the preimages of minimal primes of `R ⧸ I`. - `IsLocalization.minimalPrimes_comap`: If `A` is a localization of `R` with respect to the submonoid `S`, `J` is an ideal of `A`, then the minimal primes over the preimage of `J` (under `R →+* A`) are exactly the preimages of the minimal primes over `J`. - `IsLocalization.minimalPrimes_map`: If `A` is a localization of `R` with respect to the submonoid `S`, `J` is an ideal of `R`, then the minimal primes over the span of the image of `J` (under `R →+* A`) are exactly the ideals of `A` such that the preimage of which is a minimal prime over `J`. - `Localization.AtPrime.prime_unique_of_minimal`: When localizing at a minimal prime ideal `I`, the resulting ring only has a single prime ideal. -/ section variable {R S : Type*} [CommSemiring R] [CommSemiring S] {I J : Ideal R} theorem Ideal.iUnion_minimalPrimes : ⋃ p ∈ I.minimalPrimes, p = { x | ∃ y ∉ I.radical, x * y ∈ I.radical } := by classical ext x simp only [Set.mem_iUnion, SetLike.mem_coe, exists_prop, Set.mem_setOf_eq] constructor · rintro ⟨p, ⟨⟨hp₁, hp₂⟩, hp₃⟩, hxp⟩ have : p.map (algebraMap R (Localization.AtPrime p)) ≤ (I.map (algebraMap _ _)).radical := by rw [Ideal.radical_eq_sInf, le_sInf_iff] rintro q ⟨hq', hq⟩ obtain ⟨h₁, h₂⟩ := ((IsLocalization.AtPrime.orderIsoOfPrime _ p) ⟨q, hq⟩).2 rw [Ideal.map_le_iff_le_comap] at hq' ⊢ exact hp₃ ⟨h₁, hq'⟩ h₂ obtain ⟨n, hn⟩ := this (Ideal.mem_map_of_mem _ hxp) rw [IsLocalization.mem_map_algebraMap_iff (M := p.primeCompl)] at hn obtain ⟨⟨a, b⟩, hn⟩ := hn rw [← map_pow, ← map_mul, IsLocalization.eq_iff_exists p.primeCompl] at hn obtain ⟨t, ht⟩ := hn refine ⟨t * b, fun h ↦ (t * b).2 (hp₁.radical_le_iff.mpr hp₂ h), n + 1, ?_⟩ simp only at ht have : (x * (t.1 * b.1)) ^ (n + 1) = (t.1 ^ n * b.1 ^ n * x * t.1) * a := by rw [mul_assoc, ← ht]; ring rw [this] exact I.mul_mem_left _ a.2 · rintro ⟨y, hy, hx⟩ obtain ⟨p, hp, hyp⟩ : ∃ p ∈ I.minimalPrimes, y ∉ p := by simpa [← Ideal.sInf_minimalPrimes] using hy refine ⟨p, hp, (hp.1.1.mem_or_mem ?_).resolve_right hyp⟩ exact hp.1.1.radical_le_iff.mpr hp.1.2 hx theorem Ideal.exists_mul_mem_of_mem_minimalPrimes {p : Ideal R} (hp : p ∈ I.minimalPrimes) {x : R} (hx : x ∈ p) : ∃ y ∉ I, x * y ∈ I := by classical obtain ⟨y, hy, n, hx⟩ := Ideal.iUnion_minimalPrimes.subset (Set.mem_biUnion hp hx) have H : ∃ m, x ^ m * y ^ n ∈ I := ⟨n, mul_pow x y n ▸ hx⟩ have : Nat.find H ≠ 0 := fun h ↦ hy ⟨n, by simpa only [h, pow_zero, one_mul] using Nat.find_spec H⟩ refine ⟨x ^ (Nat.find H - 1) * y ^ n, Nat.find_min H (Nat.sub_one_lt this), ?_⟩ rw [← mul_assoc, ← pow_succ', tsub_add_cancel_of_le (Nat.one_le_iff_ne_zero.mpr this)] exact Nat.find_spec H /-- minimal primes are contained in zero divisors. -/ lemma Ideal.disjoint_nonZeroDivisors_of_mem_minimalPrimes {p : Ideal R} (hp : p ∈ minimalPrimes R) : Disjoint (p : Set R) (nonZeroDivisors R) := by simp_rw [Set.disjoint_left, SetLike.mem_coe, mem_nonZeroDivisors_iff_right, not_forall, exists_prop, @and_comm (_ * _ = _), ← mul_comm] exact fun _ ↦ Ideal.exists_mul_mem_of_mem_minimalPrimes hp theorem Ideal.exists_comap_eq_of_mem_minimalPrimes {I : Ideal S} (f : R →+* S) (p) (H : p ∈ (I.comap f).minimalPrimes) : ∃ p' : Ideal S, p'.IsPrime ∧ I ≤ p' ∧ p'.comap f = p := have := H.1.1 have ⟨p', hIp', hp', le⟩ := exists_ideal_comap_le_prime p I H.1.2 ⟨p', hp', hIp', le.antisymm (H.2 ⟨inferInstance, comap_mono hIp'⟩ le)⟩ @[stacks 00FK] theorem Ideal.exists_comap_eq_of_mem_minimalPrimes_of_injective {f : R →+* S} (hf : Function.Injective f) (p) (H : p ∈ minimalPrimes R) : ∃ p' : Ideal S, p'.IsPrime ∧ p'.comap f = p := have ⟨p', hp', _, eq⟩ := exists_comap_eq_of_mem_minimalPrimes f (I := ⊥) p <| by rwa [comap_bot_of_injective f hf] ⟨p', hp', eq⟩ theorem Ideal.exists_minimalPrimes_comap_eq {I : Ideal S} (f : R →+* S) (p) (H : p ∈ (I.comap f).minimalPrimes) : ∃ p' ∈ I.minimalPrimes, Ideal.comap f p' = p := by obtain ⟨p', h₁, h₂, h₃⟩ := Ideal.exists_comap_eq_of_mem_minimalPrimes f p H obtain ⟨q, hq, hq'⟩ := Ideal.exists_minimalPrimes_le h₂ refine ⟨q, hq, Eq.symm ?_⟩ have := hq.1.1 have := (Ideal.comap_mono hq').trans_eq h₃ exact (H.2 ⟨inferInstance, Ideal.comap_mono hq.1.2⟩ this).antisymm this theorem Ideal.minimalPrimes_comap_subset (f : R →+* S) (J : Ideal S) : (J.comap f).minimalPrimes ⊆ Ideal.comap f '' J.minimalPrimes := fun p hp ↦ Ideal.exists_minimalPrimes_comap_eq f p hp end section variable {R S : Type*} [CommRing R] [CommRing S] {I J : Ideal R} theorem Ideal.minimal_primes_comap_of_surjective {f : R →+* S} (hf : Function.Surjective f) {I J : Ideal S} (h : J ∈ I.minimalPrimes) : J.comap f ∈ (I.comap f).minimalPrimes := by have := h.1.1 refine ⟨⟨inferInstance, Ideal.comap_mono h.1.2⟩, ?_⟩ rintro K ⟨hK, e₁⟩ e₂ have : RingHom.ker f ≤ K := (Ideal.comap_mono bot_le).trans e₁ rw [← sup_eq_left.mpr this, RingHom.ker_eq_comap_bot, ← Ideal.comap_map_of_surjective f hf] apply Ideal.comap_mono _ apply h.2 _ _ · exact ⟨Ideal.map_isPrime_of_surjective hf this, Ideal.le_map_of_comap_le_of_surjective f hf e₁⟩ · exact Ideal.map_le_of_le_comap e₂ theorem Ideal.comap_minimalPrimes_eq_of_surjective {f : R →+* S} (hf : Function.Surjective f) (I : Ideal S) : (I.comap f).minimalPrimes = Ideal.comap f '' I.minimalPrimes := by ext J constructor · intro H obtain ⟨p, h, rfl⟩ := Ideal.exists_minimalPrimes_comap_eq f J H exact ⟨p, h, rfl⟩ · rintro ⟨J, hJ, rfl⟩ exact Ideal.minimal_primes_comap_of_surjective hf hJ lemma Ideal.minimalPrimes_map_of_surjective {S : Type*} [CommRing S] {f : R →+* S} (hf : Function.Surjective f) (I : Ideal R) : (I.map f).minimalPrimes = Ideal.map f '' (I ⊔ (RingHom.ker f)).minimalPrimes := by apply Set.image_injective.mpr (Ideal.comap_injective_of_surjective f hf) rw [← Ideal.comap_minimalPrimes_eq_of_surjective hf, ← Set.image_comp, Ideal.comap_map_of_surjective f hf, Set.image_congr, Set.image_id, RingHom.ker] intro x hx exact (Ideal.comap_map_of_surjective f hf _).trans (sup_eq_left.mpr <| le_sup_right.trans hx.1.2) theorem Ideal.minimalPrimes_eq_comap : I.minimalPrimes = Ideal.comap (Ideal.Quotient.mk I) '' minimalPrimes (R ⧸ I) := by rw [minimalPrimes, ← Ideal.comap_minimalPrimes_eq_of_surjective Ideal.Quotient.mk_surjective, ← RingHom.ker_eq_comap_bot, Ideal.mk_ker] end section variable {R : Type*} [CommSemiring R] (S : Submonoid R) (A : Type*) [CommSemiring A] [Algebra R A] theorem IsLocalization.minimalPrimes_map [IsLocalization S A] (J : Ideal R) : (J.map (algebraMap R A)).minimalPrimes = Ideal.comap (algebraMap R A) ⁻¹' J.minimalPrimes := by ext p constructor · intro hp haveI := hp.1.1 refine ⟨⟨Ideal.IsPrime.comap _, Ideal.map_le_iff_le_comap.mp hp.1.2⟩, ?_⟩ rintro I hI e have hI' : Disjoint (S : Set R) I := Set.disjoint_of_subset_right e ((IsLocalization.isPrime_iff_isPrime_disjoint S A _).mp hp.1.1).2 refine (Ideal.comap_mono <| hp.2 ⟨?_, Ideal.map_mono hI.2⟩ (Ideal.map_le_iff_le_comap.mpr e)).trans_eq ?_ · exact IsLocalization.isPrime_of_isPrime_disjoint S A I hI.1 hI' · exact IsLocalization.comap_map_of_isPrime_disjoint S A _ hI.1 hI' · intro hp refine ⟨⟨?_, Ideal.map_le_iff_le_comap.mpr hp.1.2⟩, ?_⟩ · rw [IsLocalization.isPrime_iff_isPrime_disjoint S A, IsLocalization.disjoint_comap_iff S] refine ⟨hp.1.1, ?_⟩ rintro rfl exact hp.1.1.ne_top rfl · intro I hI e rw [← IsLocalization.map_comap S A I, ← IsLocalization.map_comap S A p] haveI := hI.1 exact Ideal.map_mono (hp.2 ⟨Ideal.IsPrime.comap _, Ideal.map_le_iff_le_comap.mp hI.2⟩ (Ideal.comap_mono e)) theorem IsLocalization.minimalPrimes_comap [IsLocalization S A] (J : Ideal A) : (J.comap (algebraMap R A)).minimalPrimes = Ideal.comap (algebraMap R A) '' J.minimalPrimes := by conv_rhs => rw [← map_comap S A J, minimalPrimes_map S] refine (Set.image_preimage_eq_iff.mpr ?_).symm exact subset_trans (Ideal.minimalPrimes_comap_subset (algebraMap R A) J) (by simp) end
RingDivision.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Kim Morrison, Jens Wagemaker, Johan Commelin -/ import Mathlib.Algebra.Polynomial.AlgebraMap import Mathlib.Algebra.Polynomial.Div import Mathlib.RingTheory.Coprime.Basic /-! # Theory of univariate polynomials We prove basic results about univariate polynomials. -/ assert_not_exists Ideal.map noncomputable section open Polynomial open Finset namespace Polynomial universe u v w z variable {R : Type u} {S : Type v} {T : Type w} {a b : R} {n : ℕ} section CommRing variable [CommRing R] {p q : R[X]} section variable [Semiring S] theorem natDegree_pos_of_aeval_root [Algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ x : R, algebraMap R S x = 0 → x = 0) : 0 < p.natDegree := natDegree_pos_of_eval₂_root hp (algebraMap R S) hz inj theorem degree_pos_of_aeval_root [Algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ x : R, algebraMap R S x = 0 → x = 0) : 0 < p.degree := natDegree_pos_iff_degree_pos.mp (natDegree_pos_of_aeval_root hp hz inj) end theorem smul_modByMonic (c : R) (p : R[X]) : c • p %ₘ q = c • (p %ₘ q) := by by_cases hq : q.Monic · rcases subsingleton_or_nontrivial R with hR | hR · simp only [eq_iff_true_of_subsingleton] · exact (div_modByMonic_unique (c • (p /ₘ q)) (c • (p %ₘ q)) hq ⟨by rw [mul_smul_comm, ← smul_add, modByMonic_add_div p hq], (degree_smul_le _ _).trans_lt (degree_modByMonic_lt _ hq)⟩).2 · simp_rw [modByMonic_eq_of_not_monic _ hq] /-- `_ %ₘ q` as an `R`-linear map. -/ @[simps] def modByMonicHom (q : R[X]) : R[X] →ₗ[R] R[X] where toFun p := p %ₘ q map_add' := add_modByMonic map_smul' := smul_modByMonic theorem mem_ker_modByMonic (hq : q.Monic) {p : R[X]} : p ∈ LinearMap.ker (modByMonicHom q) ↔ q ∣ p := LinearMap.mem_ker.trans (modByMonic_eq_zero_iff_dvd hq) section variable [Ring S] theorem aeval_modByMonic_eq_self_of_root [Algebra R S] {p q : R[X]} (hq : q.Monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := by --`eval₂_modByMonic_eq_self_of_root` doesn't work here as it needs commutativity rw [modByMonic_eq_sub_mul_div p hq, map_sub, map_mul, hx, zero_mul, sub_zero] end end CommRing section NoZeroDivisors variable [Semiring R] [NoZeroDivisors R] {p q : R[X]} theorem trailingDegree_mul : (p * q).trailingDegree = p.trailingDegree + q.trailingDegree := by by_cases hp : p = 0 · rw [hp, zero_mul, trailingDegree_zero, top_add] by_cases hq : q = 0 · rw [hq, mul_zero, trailingDegree_zero, add_top] · rw [trailingDegree_eq_natTrailingDegree hp, trailingDegree_eq_natTrailingDegree hq, trailingDegree_eq_natTrailingDegree (mul_ne_zero hp hq), natTrailingDegree_mul hp hq] apply WithTop.coe_add end NoZeroDivisors section CommRing variable [CommRing R] theorem rootMultiplicity_eq_rootMultiplicity {p : R[X]} {t : R} : p.rootMultiplicity t = (p.comp (X + C t)).rootMultiplicity 0 := by classical simp_rw [rootMultiplicity_eq_multiplicity, comp_X_add_C_eq_zero_iff] congr 1 rw [C_0, sub_zero] convert (multiplicity_map_eq <| algEquivAevalXAddC t).symm using 2 simp [C_eq_algebraMap] /-- See `Polynomial.rootMultiplicity_eq_natTrailingDegree'` for the special case of `t = 0`. -/ theorem rootMultiplicity_eq_natTrailingDegree {p : R[X]} {t : R} : p.rootMultiplicity t = (p.comp (X + C t)).natTrailingDegree := rootMultiplicity_eq_rootMultiplicity.trans rootMultiplicity_eq_natTrailingDegree' section nonZeroDivisors open scoped nonZeroDivisors theorem Monic.mem_nonZeroDivisors {p : R[X]} (h : p.Monic) : p ∈ R[X]⁰ := mem_nonzeroDivisors_of_coeff_mem _ (h.coeff_natDegree ▸ one_mem R⁰) theorem mem_nonZeroDivisors_of_leadingCoeff {p : R[X]} (h : p.leadingCoeff ∈ R⁰) : p ∈ R[X]⁰ := mem_nonzeroDivisors_of_coeff_mem _ h theorem mem_nonZeroDivisors_of_trailingCoeff {p : R[X]} (h : p.trailingCoeff ∈ R⁰) : p ∈ R[X]⁰ := mem_nonzeroDivisors_of_coeff_mem _ h end nonZeroDivisors theorem natDegree_pos_of_monic_of_aeval_eq_zero [Nontrivial R] [Semiring S] [Algebra R S] [FaithfulSMul R S] {p : R[X]} (hp : p.Monic) {x : S} (hx : aeval x p = 0) : 0 < p.natDegree := natDegree_pos_of_aeval_root (Monic.ne_zero hp) hx ((injective_iff_map_eq_zero (algebraMap R S)).mp (FaithfulSMul.algebraMap_injective R S)) theorem rootMultiplicity_mul_X_sub_C_pow {p : R[X]} {a : R} {n : ℕ} (h : p ≠ 0) : (p * (X - C a) ^ n).rootMultiplicity a = p.rootMultiplicity a + n := by have h2 := monic_X_sub_C a |>.pow n |>.mul_left_ne_zero h refine le_antisymm ?_ ?_ · rw [rootMultiplicity_le_iff h2, add_assoc, add_comm n, ← add_assoc, pow_add, dvd_cancel_right_mem_nonZeroDivisors (monic_X_sub_C a |>.pow n |>.mem_nonZeroDivisors)] exact pow_rootMultiplicity_not_dvd h a · rw [le_rootMultiplicity_iff h2, pow_add] exact mul_dvd_mul_right (pow_rootMultiplicity_dvd p a) _ /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ theorem rootMultiplicity_X_sub_C_pow [Nontrivial R] (a : R) (n : ℕ) : rootMultiplicity a ((X - C a) ^ n) = n := by have := rootMultiplicity_mul_X_sub_C_pow (a := a) (n := n) C.map_one_ne_zero rwa [rootMultiplicity_C, map_one, one_mul, zero_add] at this theorem rootMultiplicity_X_sub_C_self [Nontrivial R] {x : R} : rootMultiplicity x (X - C x) = 1 := pow_one (X - C x) ▸ rootMultiplicity_X_sub_C_pow x 1 -- Porting note: swapped instance argument order theorem rootMultiplicity_X_sub_C [Nontrivial R] [DecidableEq R] {x y : R} : rootMultiplicity x (X - C y) = if x = y then 1 else 0 := by split_ifs with hxy · rw [hxy] exact rootMultiplicity_X_sub_C_self exact rootMultiplicity_eq_zero (mt root_X_sub_C.mp (Ne.symm hxy)) theorem rootMultiplicity_mul' {p q : R[X]} {x : R} (hpq : (p /ₘ (X - C x) ^ p.rootMultiplicity x).eval x * (q /ₘ (X - C x) ^ q.rootMultiplicity x).eval x ≠ 0) : rootMultiplicity x (p * q) = rootMultiplicity x p + rootMultiplicity x q := by simp_rw [eval_divByMonic_eq_trailingCoeff_comp] at hpq simp_rw [rootMultiplicity_eq_natTrailingDegree, mul_comp, natTrailingDegree_mul' hpq] theorem Monic.neg_one_pow_natDegree_mul_comp_neg_X {p : R[X]} (hp : p.Monic) : ((-1) ^ p.natDegree * p.comp (-X)).Monic := by simp only [Monic] calc ((-1) ^ p.natDegree * p.comp (-X)).leadingCoeff = (p.comp (-X) * C ((-1) ^ p.natDegree)).leadingCoeff := by simp [mul_comm] _ = 1 := by apply monic_mul_C_of_leadingCoeff_mul_eq_one simp [← pow_add, hp] variable [IsDomain R] {p q : R[X]} theorem degree_eq_degree_of_associated (h : Associated p q) : degree p = degree q := by let ⟨u, hu⟩ := h simp [hu.symm] theorem prime_X_sub_C (r : R) : Prime (X - C r) := ⟨X_sub_C_ne_zero r, not_isUnit_X_sub_C r, fun _ _ => by simp_rw [dvd_iff_isRoot, IsRoot.def, eval_mul, mul_eq_zero] exact id⟩ theorem prime_X : Prime (X : R[X]) := by convert prime_X_sub_C (0 : R) simp theorem Monic.prime_of_degree_eq_one (hp1 : degree p = 1) (hm : Monic p) : Prime p := have : p = X - C (-p.coeff 0) := by simpa [hm.leadingCoeff] using eq_X_add_C_of_degree_eq_one hp1 this.symm ▸ prime_X_sub_C _ theorem irreducible_X_sub_C (r : R) : Irreducible (X - C r) := (prime_X_sub_C r).irreducible theorem irreducible_X : Irreducible (X : R[X]) := Prime.irreducible prime_X theorem Monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : Monic p) : Irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible lemma aeval_ne_zero_of_isCoprime {R} [CommSemiring R] [Nontrivial S] [Semiring S] [Algebra R S] {p q : R[X]} (h : IsCoprime p q) (s : S) : aeval s p ≠ 0 ∨ aeval s q ≠ 0 := by by_contra! hpq rcases h with ⟨_, _, h⟩ apply_fun aeval s at h simp only [map_add, map_mul, map_one, hpq.left, hpq.right, mul_zero, add_zero, zero_ne_one] at h theorem isCoprime_X_sub_C_of_isUnit_sub {R} [CommRing R] {a b : R} (h : IsUnit (a - b)) : IsCoprime (X - C a) (X - C b) := ⟨-C h.unit⁻¹.val, C h.unit⁻¹.val, by rw [neg_mul_comm, ← left_distrib, neg_add_eq_sub, sub_sub_sub_cancel_left, ← C_sub, ← C_mul] rw [← C_1] congr exact h.val_inv_mul⟩ open scoped Function in -- required for scoped `on` notation theorem pairwise_coprime_X_sub_C {K} [Field K] {I : Type v} {s : I → K} (H : Function.Injective s) : Pairwise (IsCoprime on fun i : I => X - C (s i)) := fun _ _ hij => isCoprime_X_sub_C_of_isUnit_sub (sub_ne_zero_of_ne <| H.ne hij).isUnit theorem rootMultiplicity_mul {p q : R[X]} {x : R} (hpq : p * q ≠ 0) : rootMultiplicity x (p * q) = rootMultiplicity x p + rootMultiplicity x q := by classical have hp : p ≠ 0 := left_ne_zero_of_mul hpq have hq : q ≠ 0 := right_ne_zero_of_mul hpq rw [rootMultiplicity_eq_multiplicity (p * q), if_neg hpq, rootMultiplicity_eq_multiplicity p, if_neg hp, rootMultiplicity_eq_multiplicity q, if_neg hq, multiplicity_mul (prime_X_sub_C x) (finiteMultiplicity_X_sub_C _ hpq)] open Multiset in theorem exists_multiset_roots [DecidableEq R] : ∀ {p : R[X]} (_ : p ≠ 0), ∃ s : Multiset R, (Multiset.card s : WithBot ℕ) ≤ degree p ∧ ∀ a, s.count a = rootMultiplicity a p | p, hp => haveI := Classical.propDecidable (∃ x, IsRoot p x) if h : ∃ x, IsRoot p x then let ⟨x, hx⟩ := h have hpd : 0 < degree p := degree_pos_of_root hp hx have hd0 : p /ₘ (X - C x) ≠ 0 := fun h => by rw [← mul_divByMonic_eq_iff_isRoot.2 hx, h, mul_zero] at hp; exact hp rfl have wf : degree (p /ₘ (X - C x)) < degree p := degree_divByMonic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ by decide) let ⟨t, htd, htr⟩ := @exists_multiset_roots _ (p /ₘ (X - C x)) hd0 have hdeg : degree (X - C x) ≤ degree p := by rw [degree_X_sub_C, degree_eq_natDegree hp] rw [degree_eq_natDegree hp] at hpd exact WithBot.coe_le_coe.2 (WithBot.coe_lt_coe.1 hpd) have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (divByMonic_eq_zero_iff (monic_X_sub_C x)).1 <| not_lt.2 hdeg ⟨x ::ₘ t, calc (card (x ::ₘ t) : WithBot ℕ) = Multiset.card t + 1 := by congr exact mod_cast Multiset.card_cons _ _ _ ≤ degree p := by rw [← degree_add_divByMonic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm] exact add_le_add (le_refl (1 : WithBot ℕ)) htd, by intro a conv_rhs => rw [← mul_divByMonic_eq_iff_isRoot.mpr hx] rw [rootMultiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), rootMultiplicity_X_sub_C, ← htr a] split_ifs with ha · rw [ha, count_cons_self, add_comm] · rw [count_cons_of_ne ha, zero_add]⟩ else ⟨0, (degree_eq_natDegree hp).symm ▸ WithBot.coe_le_coe.2 (Nat.zero_le _), by intro a rw [count_zero, rootMultiplicity_eq_zero (not_exists.mp h a)]⟩ termination_by p => natDegree p decreasing_by { simp_wf apply (Nat.cast_lt (α := WithBot ℕ)).mp simp only [degree_eq_natDegree hp, degree_eq_natDegree hd0] at wf assumption} end CommRing end Polynomial
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, Jujian Zhang, Yongle Hu -/ import Mathlib.Algebra.Colimit.TensorProduct import Mathlib.Algebra.DirectSum.Finsupp import Mathlib.Algebra.DirectSum.Module import Mathlib.Algebra.Exact import Mathlib.Algebra.Module.CharacterModule import Mathlib.Algebra.Module.Injective import Mathlib.Algebra.Module.Projective import Mathlib.LinearAlgebra.DirectSum.TensorProduct import Mathlib.LinearAlgebra.FreeModule.Basic import Mathlib.LinearAlgebra.TensorProduct.RightExactness import Mathlib.RingTheory.Finiteness.Small import Mathlib.RingTheory.TensorProduct.Finite /-! # Flat modules A module `M` over a commutative semiring `R` is *mono-flat* if for all monomorphisms of modules (i.e., injective linear maps) `N →ₗ[R] P`, the canonical map `N ⊗ M → P ⊗ M` is injective (cf. [Katsov2004], [KatsovNam2011]). To show a module is mono-flat, it suffices to check inclusions of finitely generated submodules `N` into finitely generated modules `P`, and `P` can be further assumed to lie in the same universe as `R`. `M` is flat if `· ⊗ M` preserves finite limits (equivalently, pullbacks, or equalizers). If `R` is a ring, an `R`-module `M` is flat if and only if it is mono-flat, and to show a module is flat, it suffices to check inclusions of finitely generated ideals into `R`. See <https://stacks.math.columbia.edu/tag/00HD>. Currently, `Module.Flat` is defined to be equivalent to mono-flatness over a semiring. It is left as a TODO item to introduce the genuine flatness over semirings and rename the current `Module.Flat` to `Module.MonoFlat`. ## Main declaration * `Module.Flat`: the predicate asserting that an `R`-module `M` is flat. ## Main theorems * `Module.Flat.of_retract`: retracts of flat modules are flat * `Module.Flat.of_linearEquiv`: modules linearly equivalent to a flat modules are flat * `Module.Flat.directSum`: arbitrary direct sums of flat modules are flat * `Module.Flat.of_free`: free modules are flat * `Module.Flat.of_projective`: projective modules are flat * `Module.Flat.preserves_injective_linearMap`: If `M` is a flat module then tensoring with `M` preserves injectivity of linear maps. This lemma is fully universally polymorphic in all arguments, i.e. `R`, `M` and linear maps `N → N'` can all have different universe levels. * `Module.Flat.iff_rTensor_preserves_injective_linearMap`: a module is flat iff tensoring modules in the higher universe preserves injectivity . * `Module.Flat.lTensor_exact`: If `M` is a flat module then tensoring with `M` is an exact functor. This lemma is fully universally polymorphic in all arguments, i.e. `R`, `M` and linear maps `N → N' → N''` can all have different universe levels. * `Module.Flat.iff_lTensor_exact`: a module is flat iff tensoring modules in the higher universe is an exact functor. ## TODO * Generalize flatness to noncommutative semirings. -/ universe v' u v w open TensorProduct namespace Module open Function (Surjective) open LinearMap Submodule DirectSum section Semiring /-! ### Flatness over a semiring -/ variable {R : Type u} {M : Type v} {N P Q : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] [AddCommMonoid P] [Module R P] [AddCommMonoid Q] [Module R Q] theorem _root_.LinearMap.rTensor_injective_of_fg {f : N →ₗ[R] P} (h : ∀ (N' : Submodule R N) (P' : Submodule R P), N'.FG → P'.FG → ∀ h : N' ≤ P'.comap f, Function.Injective ((f.restrict h).rTensor M)) : Function.Injective (f.rTensor M) := fun x y eq ↦ by have ⟨N', Nfg, sub⟩ := Submodule.exists_fg_le_subset_range_rTensor_subtype {x, y} (by simp) obtain ⟨x, rfl⟩ := sub (.inl rfl) obtain ⟨y, rfl⟩ := sub (.inr rfl) simp_rw [← rTensor_comp_apply, show f ∘ₗ N'.subtype = (N'.map f).subtype ∘ₗ f.submoduleMap N' from rfl, rTensor_comp_apply] at eq have ⟨P', Pfg, le, eq⟩ := (Nfg.map _).exists_rTensor_fg_inclusion_eq eq simp_rw [← rTensor_comp_apply] at eq rw [h _ _ Nfg Pfg (map_le_iff_le_comap.mp le) eq] lemma _root_.LinearMap.rTensor_injective_iff_subtype {f : N →ₗ[R] P} (hf : Function.Injective f) (e : P ≃ₗ[R] Q) : Function.Injective (f.rTensor M) ↔ Function.Injective ((range <| e.toLinearMap ∘ₗ f).subtype.rTensor M) := by simp_rw [← EquivLike.injective_comp <| (LinearEquiv.ofInjective (e.toLinearMap ∘ₗ f) (e.injective.comp hf)).rTensor M, ← EquivLike.comp_injective _ (e.rTensor M), ← LinearEquiv.coe_coe, ← coe_comp, LinearEquiv.coe_rTensor, ← rTensor_comp] rfl variable (R M) in /-- An `R`-module `M` is flat if for every finitely generated submodule `N` of every finitely generated `R`-module `P` in the same universe as `R`, the canonical map `N ⊗ M → P ⊗ M` is injective. This implies the same is true for arbitrary `R`-modules `N` and `P` and injective linear maps `N →ₗ[R] P`, see `Flat.rTensor_preserves_injective_linearMap`. To show a module over a ring `R` is flat, it suffices to consider the case `P = R`, see `Flat.iff_rTensor_injective`. -/ @[mk_iff] class Flat : Prop where out ⦃P : Type u⦄ [AddCommMonoid P] [Module R P] [Module.Finite R P] (N : Submodule R P) : N.FG → Function.Injective (N.subtype.rTensor M) namespace Flat /-- If `M` is a flat module, then `f ⊗ 𝟙 M` is injective for all injective linear maps `f`. -/ theorem rTensor_preserves_injective_linearMap [Flat R M] (f : N →ₗ[R] P) (hf : Function.Injective f) : Function.Injective (f.rTensor M) := by refine rTensor_injective_of_fg fun N P Nfg Pfg le ↦ ?_ rw [← Finite.iff_fg] at Nfg Pfg have := Finite.small R P let se := (Shrink.linearEquiv R P).symm have := Module.Finite.equiv se rw [rTensor_injective_iff_subtype (fun _ _ ↦ (Subtype.ext <| hf <| Subtype.ext_iff.mp ·)) se] exact (flat_iff R M).mp ‹_› _ (Finite.iff_fg.mp inferInstance) /-- If `M` is a flat module, then `𝟙 M ⊗ f` is injective for all injective linear maps `f`. -/ theorem lTensor_preserves_injective_linearMap [Flat R M] (f : N →ₗ[R] P) (hf : Function.Injective f) : Function.Injective (f.lTensor M) := (f.lTensor_inj_iff_rTensor_inj M).2 (rTensor_preserves_injective_linearMap f hf) /-- `M` is flat if and only if `f ⊗ 𝟙 M` is injective whenever `f` is an injective linear map in a universe that `R` fits in. -/ lemma iff_rTensor_preserves_injective_linearMapₛ [Small.{v'} R] : Flat R M ↔ ∀ ⦃N N' : Type v'⦄ [AddCommMonoid N] [AddCommMonoid N'] [Module R N] [Module R N'] (f : N →ₗ[R] N'), Function.Injective f → Function.Injective (f.rTensor M) := ⟨by introv _; apply rTensor_preserves_injective_linearMap, fun h ↦ ⟨fun P _ _ _ _ _ ↦ by have := Finite.small.{v'} R P rw [rTensor_injective_iff_subtype Subtype.val_injective (Shrink.linearEquiv R P).symm] exact h _ Subtype.val_injective⟩⟩ /-- `M` is flat if and only if `𝟙 M ⊗ f` is injective whenever `f` is an injective linear map in a universe that `R` fits in. -/ lemma iff_lTensor_preserves_injective_linearMapₛ [Small.{v'} R] : Flat R M ↔ ∀ ⦃N N' : Type v'⦄ [AddCommMonoid N] [AddCommMonoid N'] [Module R N] [Module R N'] (f : N →ₗ[R] N'), Function.Injective f → Function.Injective (f.lTensor M) := by simp_rw [iff_rTensor_preserves_injective_linearMapₛ, LinearMap.lTensor_inj_iff_rTensor_inj] /-- An easier-to-use version of `Module.flat_iff`, with finiteness conditions removed. -/ lemma iff_rTensor_injectiveₛ : Flat R M ↔ ∀ ⦃P : Type u⦄ [AddCommMonoid P] [Module R P] (N : Submodule R P), Function.Injective (N.subtype.rTensor M) := ⟨fun _ _ _ _ _ ↦ rTensor_preserves_injective_linearMap _ Subtype.val_injective, fun h ↦ ⟨fun _ _ _ _ _ _ ↦ h _⟩⟩ lemma iff_lTensor_injectiveₛ : Flat R M ↔ ∀ ⦃P : Type u⦄ [AddCommMonoid P] [Module R P] (N : Submodule R P), Function.Injective (N.subtype.lTensor M) := by simp_rw [iff_rTensor_injectiveₛ, LinearMap.lTensor_inj_iff_rTensor_inj] instance instSubalgebraToSubmodule {S : Type v} [Semiring S] [Algebra R S] (A : Subalgebra R S) [Flat R A] : Flat R A.toSubmodule := ‹Flat R A› instance self : Flat R R where out _ _ _ _ I _ := by rw [← (TensorProduct.rid R I).symm.injective_comp, ← (TensorProduct.rid R _).comp_injective] convert Subtype.coe_injective using 1 ext; simp /-- A retract of a flat `R`-module is flat. -/ lemma of_retract [f : Flat R M] (i : N →ₗ[R] M) (r : M →ₗ[R] N) (h : r.comp i = LinearMap.id) : Flat R N := by rw [iff_rTensor_injectiveₛ] at * refine fun P _ _ Q ↦ .of_comp (f := lTensor P i) ?_ rw [← coe_comp, lTensor_comp_rTensor, ← rTensor_comp_lTensor, coe_comp] refine (f Q).comp (Function.RightInverse.injective (g := lTensor Q r) fun x ↦ ?_) simp [← comp_apply, ← lTensor_comp, h] /-- A `R`-module linearly equivalent to a flat `R`-module is flat. -/ lemma of_linearEquiv [Flat R M] (e : N ≃ₗ[R] M) : Flat R N := of_retract e.toLinearMap e.symm (by simp) /-- If an `R`-module `M` is linearly equivalent to another `R`-module `N`, then `M` is flat if and only if `N` is flat. -/ lemma equiv_iff (e : M ≃ₗ[R] N) : Flat R M ↔ Flat R N := ⟨fun _ ↦ of_linearEquiv e.symm, fun _ ↦ of_linearEquiv e⟩ instance ulift [Flat R M] : Flat R (ULift.{v'} M) := of_linearEquiv ULift.moduleEquiv -- Making this an instance causes an infinite sequence `M → ULift M → ULift (ULift M) → ...`. lemma of_ulift [Flat R (ULift.{v'} M)] : Flat R M := of_linearEquiv ULift.moduleEquiv.symm instance shrink [Small.{v'} M] [Flat R M] : Flat R (Shrink.{v'} M) := of_linearEquiv (Shrink.linearEquiv R M) -- Making this an instance causes an infinite sequence `M → Shrink M → Shrink (Shrink M) → ...`. lemma of_shrink [Small.{v'} M] [Flat R (Shrink.{v'} M)] : Flat R M := of_linearEquiv (Shrink.linearEquiv R M).symm section DirectSum variable {ι : Type v} {M : ι → Type w} [Π i, AddCommMonoid (M i)] [Π i, Module R (M i)] theorem directSum_iff : Flat R (⨁ i, M i) ↔ ∀ i, Flat R (M i) := by classical simp_rw [iff_rTensor_injectiveₛ, ← EquivLike.comp_injective _ (directSumRight R _ _), ← LinearEquiv.coe_coe, ← coe_comp, directSumRight_comp_rTensor, coe_comp, LinearEquiv.coe_coe, EquivLike.injective_comp, lmap_injective] constructor <;> (intro h; intros; apply h) theorem dfinsupp_iff : Flat R (Π₀ i, M i) ↔ ∀ i, Flat R (M i) := directSum_iff .. /-- A direct sum of flat `R`-modules is flat. -/ instance directSum [∀ i, Flat R (M i)] : Flat R (⨁ i, M i) := directSum_iff.mpr ‹_› instance dfinsupp [∀ i, Flat R (M i)] : Flat R (Π₀ i, M i) := dfinsupp_iff.mpr ‹_› end DirectSum /-- Free `R`-modules over discrete types are flat. -/ instance finsupp (ι : Type v) : Flat R (ι →₀ R) := by classical exact of_linearEquiv (finsuppLEquivDirectSum R R ι) instance of_projective [Projective R M] : Flat R M := have ⟨e, he⟩:= Module.projective_def'.mp ‹_› of_retract _ _ he instance of_free [Free R M] : Flat R M := inferInstance instance {S} [CommSemiring S] [Algebra R S] [Module S M] [IsScalarTower R S M] [Flat S M] [Flat R N] : Flat S (M ⊗[R] N) := iff_rTensor_injectiveₛ.mpr fun P _ _ I ↦ by letI := RestrictScalars.moduleOrig R S P change Submodule S (RestrictScalars R S P) at I change Function.Injective (rTensor _ I.subtype) simpa [AlgebraTensorModule.rTensor_tensor] using rTensor_preserves_injective_linearMap (.restrictScalars R <| I.subtype.rTensor M) (rTensor_preserves_injective_linearMap _ I.injective_subtype) example [Flat R M] [Flat R N] : Flat R (M ⊗[R] N) := inferInstance theorem linearIndependent_one_tmul {S} [Semiring S] [Algebra R S] [Flat R S] {ι} {v : ι → M} (hv : LinearIndependent R v) : LinearIndependent S ((1 : S) ⊗ₜ[R] v ·) := by classical rw [LinearIndependent, ← LinearMap.coe_restrictScalars R, Finsupp.linearCombination_one_tmul] simpa using lTensor_preserves_injective_linearMap _ hv end Flat end Semiring namespace Flat /-! ### Flatness over a ring -/ variable {R : Type u} {M : Type v} [CommRing R] [AddCommGroup M] [Module R M] variable {N : Type w} [AddCommGroup N] [Module R N] /-- `M` is flat if and only if `f ⊗ 𝟙 M` is injective whenever `f` is an injective linear map. See `Module.Flat.iff_rTensor_preserves_injective_linearMap` to specialize the universe of `N, N', N''` to `Type (max u v)`. -/ lemma iff_rTensor_preserves_injective_linearMap' [Small.{v'} R] : Flat R M ↔ ∀ ⦃N N' : Type v'⦄ [AddCommGroup N] [AddCommGroup N'] [Module R N] [Module R N'] (f : N →ₗ[R] N'), Function.Injective f → Function.Injective (f.rTensor M) := ⟨by introv _; apply rTensor_preserves_injective_linearMap, fun h ↦ iff_rTensor_preserves_injective_linearMapₛ.mpr fun P N _ _ _ _ ↦ by letI := Module.addCommMonoidToAddCommGroup R (M := P) letI := Module.addCommMonoidToAddCommGroup R (M := N) apply h⟩ /-- `M` is flat if and only if `f ⊗ 𝟙 M` is injective whenever `f` is an injective linear map. See `Module.Flat.iff_rTensor_preserves_injective_linearMap'` to generalize the universe of `N, N', N''` to any universe that is higher than `R` and `M`. -/ lemma iff_rTensor_preserves_injective_linearMap : Flat R M ↔ ∀ ⦃N N' : Type (max u v)⦄ [AddCommGroup N] [AddCommGroup N'] [Module R N] [Module R N'] (f : N →ₗ[R] N'), Function.Injective f → Function.Injective (f.rTensor M) := iff_rTensor_preserves_injective_linearMap' /-- `M` is flat if and only if `𝟙 M ⊗ f` is injective whenever `f` is an injective linear map. See `Module.Flat.iff_lTensor_preserves_injective_linearMap` to specialize the universe of `N, N', N''` to `Type (max u v)`. -/ lemma iff_lTensor_preserves_injective_linearMap' [Small.{v'} R] : Flat R M ↔ ∀ ⦃N N' : Type v'⦄ [AddCommGroup N] [AddCommGroup N'] [Module R N] [Module R N'] (f : N →ₗ[R] N'), Function.Injective f → Function.Injective (f.lTensor M) := by simp_rw [iff_rTensor_preserves_injective_linearMap', LinearMap.lTensor_inj_iff_rTensor_inj] /-- `M` is flat if and only if `𝟙 M ⊗ f` is injective whenever `f` is an injective linear map. See `Module.Flat.iff_lTensor_preserves_injective_linearMap'` to generalize the universe of `N, N', N''` to any universe that is higher than `R` and `M`. -/ lemma iff_lTensor_preserves_injective_linearMap : Flat R M ↔ ∀ ⦃N N' : Type (max u v)⦄ [AddCommGroup N] [AddCommGroup N'] [Module R N] [Module R N'] (f : N →ₗ[R] N'), Function.Injective f → Function.Injective (f.lTensor M) := iff_lTensor_preserves_injective_linearMap' /-- Define the character module of `M` to be `M →+ ℚ ⧸ ℤ`. The character module of `M` is an injective module if and only if `f ⊗ 𝟙 M` is injective for any linear map `f` in the same universe as `M`. -/ lemma injective_characterModule_iff_rTensor_preserves_injective_linearMap : Module.Injective R (CharacterModule M) ↔ ∀ ⦃N N' : Type v⦄ [AddCommGroup N] [AddCommGroup N'] [Module R N] [Module R N'] (f : N →ₗ[R] N'), Function.Injective f → Function.Injective (f.rTensor M) := by simp_rw [injective_iff, rTensor_injective_iff_lcomp_surjective, Surjective, DFunLike.ext_iff]; rfl /-- `CharacterModule M` is an injective module iff `M` is flat. See [Lambek_1964] for a self-contained proof. -/ theorem iff_characterModule_injective [Small.{v} R] : Flat R M ↔ Module.Injective R (CharacterModule M) := by rw [injective_characterModule_iff_rTensor_preserves_injective_linearMap, iff_rTensor_preserves_injective_linearMap'] /-- `CharacterModule M` is Baer iff `M` is flat. -/ theorem iff_characterModule_baer : Flat R M ↔ Baer R (CharacterModule M) := by rw [equiv_iff (N := ULift.{u} M) ULift.moduleEquiv.symm, iff_characterModule_injective, ← Baer.iff_injective, Baer.congr (CharacterModule.congr ULift.moduleEquiv)] /-- An `R`-module `M` is flat iff for all ideals `I` of `R`, the tensor product of the inclusion `I → R` and the identity `M → M` is injective. See `iff_rTensor_injective` to restrict to finitely generated ideals `I`. -/ theorem iff_rTensor_injective' : Flat R M ↔ ∀ I : Ideal R, Function.Injective (rTensor M I.subtype) := by simp_rw [iff_characterModule_baer, Baer, rTensor_injective_iff_lcomp_surjective, Surjective, DFunLike.ext_iff, Subtype.forall] rfl /-- The `lTensor`-variant of `iff_rTensor_injective'`. . -/ theorem iff_lTensor_injective' : Flat R M ↔ ∀ (I : Ideal R), Function.Injective (lTensor M I.subtype) := by simpa [← comm_comp_rTensor_comp_comm_eq] using iff_rTensor_injective' /-- A module `M` over a ring `R` is flat iff for all finitely generated ideals `I` of `R`, the tensor product of the inclusion `I → R` and the identity `M → M` is injective. See `iff_rTensor_injective'` to extend to all ideals `I`. -/ lemma iff_rTensor_injective : Flat R M ↔ ∀ ⦃I : Ideal R⦄, I.FG → Function.Injective (I.subtype.rTensor M) := by refine iff_rTensor_injective'.trans ⟨fun h I _ ↦ h I, fun h I ↦ (injective_iff_map_eq_zero _).mpr fun x hx ↦ ?_⟩ obtain ⟨J, hfg, hle, y, rfl⟩ := Submodule.exists_fg_le_eq_rTensor_inclusion x rw [← rTensor_comp_apply] at hx rw [(injective_iff_map_eq_zero _).mp (h hfg) y hx, map_zero] /-- The `lTensor`-variant of `iff_rTensor_injective`. -/ theorem iff_lTensor_injective : Flat R M ↔ ∀ ⦃I : Ideal R⦄, I.FG → Function.Injective (I.subtype.lTensor M) := by simpa [← comm_comp_rTensor_comp_comm_eq] using iff_rTensor_injective /-- An `R`-module `M` is flat if for all finitely generated ideals `I` of `R`, the canonical map `I ⊗ M →ₗ M` is injective. -/ lemma iff_lift_lsmul_comp_subtype_injective : Flat R M ↔ ∀ ⦃I : Ideal R⦄, I.FG → Function.Injective (TensorProduct.lift ((lsmul R M).comp I.subtype)) := by simp [iff_rTensor_injective, ← lid_comp_rTensor] variable (M) in /-- If `M` is flat then `M ⊗ -` is an exact functor. -/ lemma lTensor_exact [Flat R M] ⦃N N' N'' : Type*⦄ [AddCommGroup N] [AddCommGroup N'] [AddCommGroup N''] [Module R N] [Module R N'] [Module R N''] ⦃f : N →ₗ[R] N'⦄ ⦃g : N' →ₗ[R] N''⦄ (exact : Function.Exact f g) : Function.Exact (f.lTensor M) (g.lTensor M) := by let π : N' →ₗ[R] N' ⧸ LinearMap.range f := Submodule.mkQ _ let ι : N' ⧸ LinearMap.range f →ₗ[R] N'' := Submodule.subtype _ ∘ₗ (LinearMap.quotKerEquivRange g).toLinearMap ∘ₗ Submodule.quotEquivOfEq (LinearMap.range f) (LinearMap.ker g) (LinearMap.exact_iff.mp exact).symm suffices exact1 : Function.Exact (f.lTensor M) (π.lTensor M) by rw [show g = ι.comp π from rfl, lTensor_comp] exact exact1.comp_injective _ (lTensor_preserves_injective_linearMap ι <| by simpa [ι, - Subtype.val_injective] using Subtype.val_injective) (map_zero _) exact _root_.lTensor_exact _ (fun x ↦ by simp [π]) Quotient.mk''_surjective variable (M) in /-- If `M` is flat then `- ⊗ M` is an exact functor. -/ lemma rTensor_exact [Flat R M] ⦃N N' N'' : Type*⦄ [AddCommGroup N] [AddCommGroup N'] [AddCommGroup N''] [Module R N] [Module R N'] [Module R N''] ⦃f : N →ₗ[R] N'⦄ ⦃g : N' →ₗ[R] N''⦄ (exact : Function.Exact f g) : Function.Exact (f.rTensor M) (g.rTensor M) := by let π : N' →ₗ[R] N' ⧸ LinearMap.range f := Submodule.mkQ _ let ι : N' ⧸ LinearMap.range f →ₗ[R] N'' := Submodule.subtype _ ∘ₗ (LinearMap.quotKerEquivRange g).toLinearMap ∘ₗ Submodule.quotEquivOfEq (LinearMap.range f) (LinearMap.ker g) (LinearMap.exact_iff.mp exact).symm suffices exact1 : Function.Exact (f.rTensor M) (π.rTensor M) by rw [show g = ι.comp π from rfl, rTensor_comp] exact exact1.comp_injective _ (rTensor_preserves_injective_linearMap ι <| by simpa [ι, - Subtype.val_injective] using Subtype.val_injective) (map_zero _) exact _root_.rTensor_exact M (fun x ↦ by simp [π]) Quotient.mk''_surjective /-- `M` is flat if and only if `M ⊗ -` is an exact functor. See `Module.Flat.iff_lTensor_exact` to specialize the universe of `N, N', N''` to `Type (max u v)`. -/ theorem iff_lTensor_exact' [Small.{v'} R] : Flat R M ↔ ∀ ⦃N N' N'' : Type v'⦄ [AddCommGroup N] [AddCommGroup N'] [AddCommGroup N''] [Module R N] [Module R N'] [Module R N''] ⦃f : N →ₗ[R] N'⦄ ⦃g : N' →ₗ[R] N''⦄, Function.Exact f g → Function.Exact (f.lTensor M) (g.lTensor M) := by refine ⟨fun _ ↦ lTensor_exact _, fun H ↦ iff_lTensor_preserves_injective_linearMap'.mpr fun N' N'' _ _ _ _ L hL ↦ LinearMap.ker_eq_bot |>.mp <| eq_bot_iff |>.mpr fun x (hx : _ = 0) ↦ ?_⟩ simpa [Eq.comm] using @H PUnit N' N'' _ _ _ _ _ _ 0 L (fun x ↦ by simp_rw [Set.mem_range, LinearMap.zero_apply, exists_const] exact (L.map_eq_zero_iff hL).trans eq_comm) x |>.mp hx /-- `M` is flat if and only if `M ⊗ -` is an exact functor. See `Module.Flat.iff_lTensor_exact'` to generalize the universe of `N, N', N''` to any universe that is higher than `R` and `M`. -/ theorem iff_lTensor_exact : Flat R M ↔ ∀ ⦃N N' N'' : Type (max u v)⦄ [AddCommGroup N] [AddCommGroup N'] [AddCommGroup N''] [Module R N] [Module R N'] [Module R N''] ⦃f : N →ₗ[R] N'⦄ ⦃g : N' →ₗ[R] N''⦄, Function.Exact f g → Function.Exact (f.lTensor M) (g.lTensor M) := iff_lTensor_exact' /-- `M` is flat if and only if `- ⊗ M` is an exact functor. See `Module.Flat.iff_rTensor_exact` to specialize the universe of `N, N', N''` to `Type (max u v)`. -/ theorem iff_rTensor_exact' [Small.{v'} R] : Flat R M ↔ ∀ ⦃N N' N'' : Type v'⦄ [AddCommGroup N] [AddCommGroup N'] [AddCommGroup N''] [Module R N] [Module R N'] [Module R N''] ⦃f : N →ₗ[R] N'⦄ ⦃g : N' →ₗ[R] N''⦄, Function.Exact f g → Function.Exact (f.rTensor M) (g.rTensor M) := by refine ⟨fun _ ↦ rTensor_exact _, fun H ↦ iff_rTensor_preserves_injective_linearMap'.mpr fun N' N'' _ _ _ _ f hf ↦ LinearMap.ker_eq_bot |>.mp <| eq_bot_iff |>.mpr fun x (hx : _ = 0) ↦ ?_⟩ simpa [Eq.comm] using @H PUnit N' N'' _ _ _ _ _ _ 0 f (fun x ↦ by simp_rw [Set.mem_range, LinearMap.zero_apply, exists_const] exact (f.map_eq_zero_iff hf).trans eq_comm) x |>.mp hx /-- `M` is flat if and only if `- ⊗ M` is an exact functor. See `Module.Flat.iff_rTensor_exact'` to generalize the universe of `N, N', N''` to any universe that is higher than `R` and `M`. -/ theorem iff_rTensor_exact : Flat R M ↔ ∀ ⦃N N' N'' : Type (max u v)⦄ [AddCommGroup N] [AddCommGroup N'] [AddCommGroup N''] [Module R N] [Module R N'] [Module R N''] ⦃f : N →ₗ[R] N'⦄ ⦃g : N' →ₗ[R] N''⦄, Function.Exact f g → Function.Exact (f.rTensor M) (g.rTensor M) := iff_rTensor_exact' end Flat end Module section Injective variable {R S A B : Type*} [CommSemiring R] [Semiring A] [Algebra R A] [Semiring B] [Algebra R B] [CommSemiring S] [Algebra S A] [SMulCommClass R S A] namespace Algebra.TensorProduct theorem includeLeft_injective [Module.Flat R A] (hb : Function.Injective (algebraMap R B)) : Function.Injective (includeLeft : A →ₐ[S] A ⊗[R] B) := by convert Module.Flat.lTensor_preserves_injective_linearMap (M := A) (Algebra.linearMap R B) hb |>.comp (_root_.TensorProduct.rid R A).symm.injective ext; simp theorem includeRight_injective [Module.Flat R B] (ha : Function.Injective (algebraMap R A)) : Function.Injective (includeRight : B →ₐ[R] A ⊗[R] B) := by convert Module.Flat.rTensor_preserves_injective_linearMap (M := B) (Algebra.linearMap R A) ha |>.comp (_root_.TensorProduct.lid R B).symm.injective ext; simp end Algebra.TensorProduct end Injective section Nontrivial variable (R : Type*) [CommSemiring R] namespace TensorProduct variable (M N : Type*) [AddCommMonoid M] [AddCommMonoid N] [Module R M] [Module R N] /-- If `M`, `N` are `R`-modules, there exists an injective `R`-linear map from `R` to `N`, and `M` is a nontrivial flat `R`-module, then `M ⊗[R] N` is nontrivial. -/ theorem nontrivial_of_linearMap_injective_of_flat_left (f : R →ₗ[R] N) (h : Function.Injective f) [Module.Flat R M] [Nontrivial M] : Nontrivial (M ⊗[R] N) := Module.Flat.lTensor_preserves_injective_linearMap (M := M) f h |>.comp (TensorProduct.rid R M).symm.injective |>.nontrivial /-- If `M`, `N` are `R`-modules, there exists an injective `R`-linear map from `R` to `M`, and `N` is a nontrivial flat `R`-module, then `M ⊗[R] N` is nontrivial. -/ theorem nontrivial_of_linearMap_injective_of_flat_right (f : R →ₗ[R] M) (h : Function.Injective f) [Module.Flat R N] [Nontrivial N] : Nontrivial (M ⊗[R] N) := Module.Flat.rTensor_preserves_injective_linearMap (M := N) f h |>.comp (TensorProduct.lid R N).symm.injective |>.nontrivial variable {R M N} variable {P Q : Type*} [AddCommMonoid P] [Module R P] [AddCommMonoid Q] [Module R Q] /-- Tensor product of injective maps are injective under some flatness conditions. Also see `TensorProduct.map_injective_of_flat_flat'` and `TensorProduct.map_injective_of_flat_flat_of_isDomain` for different flatness conditions. -/ lemma map_injective_of_flat_flat (f : P →ₗ[R] M) (g : Q →ₗ[R] N) [Module.Flat R M] [Module.Flat R Q] (hf : Function.Injective f) (hg : Function.Injective g) : Function.Injective (TensorProduct.map f g) := by rw [← LinearMap.lTensor_comp_rTensor] exact (Module.Flat.lTensor_preserves_injective_linearMap g hg).comp (Module.Flat.rTensor_preserves_injective_linearMap f hf) /-- Tensor product of injective maps are injective under some flatness conditions. Also see `TensorProduct.map_injective_of_flat_flat` and `TensorProduct.map_injective_of_flat_flat_of_isDomain` for different flatness conditions. -/ lemma map_injective_of_flat_flat' (f : P →ₗ[R] M) (g : Q →ₗ[R] N) [Module.Flat R P] [Module.Flat R N] (hf : Function.Injective f) (hg : Function.Injective g) : Function.Injective (TensorProduct.map f g) := by rw [← LinearMap.rTensor_comp_lTensor] exact (Module.Flat.rTensor_preserves_injective_linearMap f hf).comp (Module.Flat.lTensor_preserves_injective_linearMap g hg) variable {ι κ : Type*} {v : ι → M} {w : κ → N} {s : Set ι} {t : Set κ} /-- Tensor product of linearly independent families is linearly independent under some flatness conditions. The flatness condition could be removed over domains. See `LinearIndependent.tmul_of_isDomain`. -/ lemma _root_.LinearIndependent.tmul_of_flat_left [Module.Flat R M] (hv : LinearIndependent R v) (hw : LinearIndependent R w) : LinearIndependent R fun i : ι × κ ↦ v i.1 ⊗ₜ[R] w i.2 := by rw [LinearIndependent] convert (TensorProduct.map_injective_of_flat_flat _ _ hv hw).comp (finsuppTensorFinsupp' _ _ _).symm.injective rw [← LinearEquiv.coe_toLinearMap, ← LinearMap.coe_comp] congr! ext i simp [finsuppTensorFinsupp'_symm_single_eq_single_one_tmul] /-- Tensor product of linearly independent families is linearly independent under some flatness conditions. The flatness condition could be removed over domains. See `LinearIndepOn.tmul_of_isDomain`. -/ nonrec lemma LinearIndepOn.tmul_of_flat_left [Module.Flat R M] (hv : LinearIndepOn R v s) (hw : LinearIndepOn R w t) : LinearIndepOn R (fun i : ι × κ ↦ v i.1 ⊗ₜ[R] w i.2) (s ×ˢ t) := ((hv.tmul_of_flat_left hw).comp _ (Equiv.Set.prod _ _).injective:) /-- Tensor product of linearly independent families is linearly independent under some flatness conditions. The flatness condition could be removed over domains. See `LinearIndependent.tmul_of_isDomain`. -/ lemma _root_.LinearIndependent.tmul_of_flat_right [Module.Flat R N] (hv : LinearIndependent R v) (hw : LinearIndependent R w) : LinearIndependent R fun i : ι × κ ↦ v i.1 ⊗ₜ[R] w i.2 := (((TensorProduct.comm R N M).toLinearMap.linearIndependent_iff_of_injOn (TensorProduct.comm R N M).injective.injOn).mpr (hw.tmul_of_flat_left hv)).comp Prod.swap Prod.swap_bijective.injective /-- Tensor product of linearly independent families is linearly independent under some flatness conditions. The flatness condition could be removed over domains. See `LinearIndepOn.tmul_of_isDomain`. -/ nonrec lemma LinearIndepOn.tmul_of_flat_right [Module.Flat R N] (hv : LinearIndepOn R v s) (hw : LinearIndepOn R w t) : LinearIndepOn R (fun i : ι × κ ↦ v i.1 ⊗ₜ[R] w i.2) (s ×ˢ t) := ((hv.tmul_of_flat_right hw).comp _ (Equiv.Set.prod _ _).injective:) variable (p : Submodule R M) (q : Submodule R N) /-- If p and q are submodules of M and N respectively, and M and q are flat, then `p ⊗ q → M ⊗ N` is injective. -/ theorem _root_.Module.Flat.tensorProduct_mapIncl_injective_of_right [Module.Flat R M] [Module.Flat R q] : Function.Injective (mapIncl p q) := TensorProduct.map_injective_of_flat_flat _ _ p.subtype_injective q.subtype_injective /-- If p and q are submodules of M and N respectively, and N and p are flat, then `p ⊗ q → M ⊗ N` is injective. -/ theorem _root_.Module.Flat.tensorProduct_mapIncl_injective_of_left [Module.Flat R p] [Module.Flat R N] : Function.Injective (mapIncl p q) := TensorProduct.map_injective_of_flat_flat' _ _ p.subtype_injective q.subtype_injective end TensorProduct namespace Algebra.TensorProduct variable (A B : Type*) [Semiring A] [Semiring B] [Algebra R A] [Algebra R B] /-- If `A`, `B` are `R`-algebras, `R` injects into `B`, and `A` is a nontrivial flat `R`-algebra, then `A ⊗[R] B` is nontrivial. -/ theorem nontrivial_of_algebraMap_injective_of_flat_left (h : Function.Injective (algebraMap R B)) [Module.Flat R A] [Nontrivial A] : Nontrivial (A ⊗[R] B) := TensorProduct.nontrivial_of_linearMap_injective_of_flat_left R A B (Algebra.linearMap R B) h /-- If `A`, `B` are `R`-algebras, `R` injects into `A`, and `B` is a nontrivial flat `R`-algebra, then `A ⊗[R] B` is nontrivial. -/ theorem nontrivial_of_algebraMap_injective_of_flat_right (h : Function.Injective (algebraMap R A)) [Module.Flat R B] [Nontrivial B] : Nontrivial (A ⊗[R] B) := TensorProduct.nontrivial_of_linearMap_injective_of_flat_right R A B (Algebra.linearMap R A) h end Algebra.TensorProduct end Nontrivial
Classes.lean
/- Copyright (c) 2024 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.Complex.Basic import Mathlib.Algebra.Star.NonUnitalSubalgebra /-! # Classes of C⋆-algebras This file defines classes for complex C⋆-algebras. These are (unital or non-unital, commutative or noncommutative) Banach algebra over `ℂ` with an antimultiplicative conjugate-linear involution (`star`) satisfying the C⋆-identity `∥star x * x∥ = ∥x∥ ^ 2`. ## Notes These classes are not defined in `Mathlib/Analysis/CStarAlgebra/Basic.lean` because they require heavier imports. -/ /-- The class of non-unital (complex) C⋆-algebras. -/ class NonUnitalCStarAlgebra (A : Type*) extends NonUnitalNormedRing A, StarRing A, CompleteSpace A, CStarRing A, NormedSpace ℂ A, IsScalarTower ℂ A A, SMulCommClass ℂ A A, StarModule ℂ A where /-- The class of non-unital commutative (complex) C⋆-algebras. -/ class NonUnitalCommCStarAlgebra (A : Type*) extends NonUnitalNormedCommRing A, NonUnitalCStarAlgebra A /-- The class of unital (complex) C⋆-algebras. -/ class CStarAlgebra (A : Type*) extends NormedRing A, StarRing A, CompleteSpace A, CStarRing A, NormedAlgebra ℂ A, StarModule ℂ A where /-- The class of unital commutative (complex) C⋆-algebras. -/ class CommCStarAlgebra (A : Type*) extends NormedCommRing A, CStarAlgebra A instance (priority := 100) CStarAlgebra.toNonUnitalCStarAlgebra (A : Type*) [CStarAlgebra A] : NonUnitalCStarAlgebra A where instance (priority := 100) CommCStarAlgebra.toNonUnitalCommCStarAlgebra (A : Type*) [CommCStarAlgebra A] : NonUnitalCommCStarAlgebra A where noncomputable instance StarSubalgebra.cstarAlgebra {S A : Type*} [CStarAlgebra A] [SetLike S A] [SubringClass S A] [SMulMemClass S ℂ A] [StarMemClass S A] (s : S) [h_closed : IsClosed (s : Set A)] : CStarAlgebra s where toCompleteSpace := h_closed.completeSpace_coe norm_mul_self_le x := CStarRing.norm_star_mul_self (x := (x : A)) |>.symm.le noncomputable instance StarSubalgebra.commCStarAlgebra {S A : Type*} [CommCStarAlgebra A] [SetLike S A] [SubringClass S A] [SMulMemClass S ℂ A] [StarMemClass S A] (s : S) [h_closed : IsClosed (s : Set A)] : CommCStarAlgebra s where toCompleteSpace := h_closed.completeSpace_coe norm_mul_self_le x := CStarRing.norm_star_mul_self (x := (x : A)) |>.symm.le mul_comm _ _ := Subtype.ext <| mul_comm _ _ noncomputable instance NonUnitalStarSubalgebra.nonUnitalCStarAlgebra {S A : Type*} [NonUnitalCStarAlgebra A] [SetLike S A] [NonUnitalSubringClass S A] [SMulMemClass S ℂ A] [StarMemClass S A] (s : S) [h_closed : IsClosed (s : Set A)] : NonUnitalCStarAlgebra s where toCompleteSpace := h_closed.completeSpace_coe norm_mul_self_le x := CStarRing.norm_star_mul_self (x := (x : A)) |>.symm.le noncomputable instance NonUnitalStarSubalgebra.nonUnitalCommCStarAlgebra {S A : Type*} [NonUnitalCommCStarAlgebra A] [SetLike S A] [NonUnitalSubringClass S A] [SMulMemClass S ℂ A] [StarMemClass S A] (s : S) [h_closed : IsClosed (s : Set A)] : NonUnitalCommCStarAlgebra s where toCompleteSpace := h_closed.completeSpace_coe norm_mul_self_le x := CStarRing.norm_star_mul_self (x := (x : A)) |>.symm.le mul_comm _ _ := Subtype.ext <| mul_comm _ _ noncomputable instance : CommCStarAlgebra ℂ where section Pi variable {ι : Type*} {A : ι → Type*} [Fintype ι] instance [(i : ι) → NonUnitalCStarAlgebra (A i)] : NonUnitalCStarAlgebra (Π i, A i) where instance [(i : ι) → NonUnitalCommCStarAlgebra (A i)] : NonUnitalCommCStarAlgebra (Π i, A i) where noncomputable instance [(i : ι) → CStarAlgebra (A i)] : CStarAlgebra (Π i, A i) where noncomputable instance [(i : ι) → CommCStarAlgebra (A i)] : CommCStarAlgebra (Π i, A i) where end Pi section Prod variable {A B : Type*} instance [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : NonUnitalCStarAlgebra (A × B) where instance [NonUnitalCommCStarAlgebra A] [NonUnitalCommCStarAlgebra B] : NonUnitalCommCStarAlgebra (A × B) where noncomputable instance [CStarAlgebra A] [CStarAlgebra B] : CStarAlgebra (A × B) where noncomputable instance [CommCStarAlgebra A] [CommCStarAlgebra B] : CommCStarAlgebra (A × B) where end Prod namespace MulOpposite variable {A : Type*} instance [NonUnitalCStarAlgebra A] : NonUnitalCStarAlgebra Aᵐᵒᵖ where instance [NonUnitalCommCStarAlgebra A] : NonUnitalCommCStarAlgebra Aᵐᵒᵖ where noncomputable instance [CStarAlgebra A] : CStarAlgebra Aᵐᵒᵖ where noncomputable instance [CommCStarAlgebra A] : CommCStarAlgebra Aᵐᵒᵖ where end MulOpposite
Basic.lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import Mathlib.RingTheory.LocalRing.Defs import Mathlib.RingTheory.Ideal.Nonunits /-! # Local rings We prove basic properties of local rings. -/ variable {R S : Type*} namespace IsLocalRing section Semiring variable [Semiring R] theorem of_isUnit_or_isUnit_of_isUnit_add [Nontrivial R] (h : ∀ a b : R, IsUnit (a + b) → IsUnit a ∨ IsUnit b) : IsLocalRing R := ⟨fun {a b} hab => h a b <| hab.symm ▸ isUnit_one⟩ /-- A semiring is local if it is nontrivial and the set of nonunits is closed under the addition. -/ theorem of_nonunits_add [Nontrivial R] (h : ∀ a b : R, a ∈ nonunits R → b ∈ nonunits R → a + b ∈ nonunits R) : IsLocalRing R where isUnit_or_isUnit_of_add_one {a b} hab := or_iff_not_and_not.2 fun H => h a b H.1 H.2 <| hab.symm ▸ isUnit_one end Semiring section CommSemiring variable [CommSemiring R] /-- A semiring is local if it has a unique maximal ideal. -/ theorem of_unique_max_ideal (h : ∃! I : Ideal R, I.IsMaximal) : IsLocalRing R := @of_nonunits_add _ _ (nontrivial_of_ne (0 : R) 1 <| let ⟨I, Imax, _⟩ := h fun H : 0 = 1 => Imax.1.1 <| I.eq_top_iff_one.2 <| H ▸ I.zero_mem) fun x y hx hy H => let ⟨I, Imax, Iuniq⟩ := h let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy have xmemI : x ∈ I := Iuniq Ix Ixmax ▸ Hx have ymemI : y ∈ I := Iuniq Iy Iymax ▸ Hy Imax.1.1 <| I.eq_top_of_isUnit_mem (I.add_mem xmemI ymemI) H theorem of_unique_nonzero_prime (h : ∃! P : Ideal R, P ≠ ⊥ ∧ Ideal.IsPrime P) : IsLocalRing R := of_unique_max_ideal (by rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩ refine ⟨P, ⟨⟨hPnot_top, ?_⟩⟩, fun M hM => hPunique _ ⟨?_, Ideal.IsMaximal.isPrime hM⟩⟩ · refine Ideal.maximal_of_no_maximal fun M hPM hM => ne_of_lt hPM ?_ exact (hPunique _ ⟨ne_bot_of_gt hPM, Ideal.IsMaximal.isPrime hM⟩).symm · rintro rfl exact hPnot_top (hM.1.2 P (bot_lt_iff_ne_bot.2 hPnonzero))) variable [IsLocalRing R] theorem isUnit_or_isUnit_of_isUnit_add {a b : R} (h : IsUnit (a + b)) : IsUnit a ∨ IsUnit b := by rcases h with ⟨u, hu⟩ rw [← Units.inv_mul_eq_one, mul_add] at hu apply Or.imp _ _ (isUnit_or_isUnit_of_add_one hu) <;> exact isUnit_of_mul_isUnit_right theorem nonunits_add {a b : R} (ha : a ∈ nonunits R) (hb : b ∈ nonunits R) : a + b ∈ nonunits R := fun H => not_or_intro ha hb (isUnit_or_isUnit_of_isUnit_add H) end CommSemiring section Ring variable [Ring R] theorem of_isUnit_or_isUnit_one_sub_self [Nontrivial R] (h : ∀ a : R, IsUnit a ∨ IsUnit (1 - a)) : IsLocalRing R := ⟨fun {a b} hab => add_sub_cancel_left a b ▸ hab.symm ▸ h a⟩ end Ring section CommRing variable [CommRing R] [IsLocalRing R] theorem isUnit_or_isUnit_one_sub_self (a : R) : IsUnit a ∨ IsUnit (1 - a) := isUnit_or_isUnit_of_isUnit_add <| (add_sub_cancel a 1).symm ▸ isUnit_one theorem isUnit_of_mem_nonunits_one_sub_self (a : R) (h : 1 - a ∈ nonunits R) : IsUnit a := or_iff_not_imp_right.1 (isUnit_or_isUnit_one_sub_self a) h theorem isUnit_one_sub_self_of_mem_nonunits (a : R) (h : a ∈ nonunits R) : IsUnit (1 - a) := or_iff_not_imp_left.1 (isUnit_or_isUnit_one_sub_self a) h theorem of_surjective' [Ring S] [Nontrivial S] (f : R →+* S) (hf : Function.Surjective f) : IsLocalRing S := of_isUnit_or_isUnit_one_sub_self (by intro b obtain ⟨a, rfl⟩ := hf b apply (isUnit_or_isUnit_one_sub_self a).imp <| RingHom.isUnit_map _ rw [← f.map_one, ← f.map_sub] apply f.isUnit_map) end CommRing end IsLocalRing namespace Field variable (K : Type*) [Field K] -- see Note [lower instance priority] instance (priority := 100) : IsLocalRing K := by classical exact IsLocalRing.of_isUnit_or_isUnit_one_sub_self fun a => if h : a = 0 then Or.inr (by rw [h, sub_zero]; exact isUnit_one) else Or.inl <| IsUnit.mk0 a h end Field
DMatrix.lean
/- Copyright (c) 2021 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.Algebra.Group.Hom.Defs import Mathlib.Algebra.Group.Pi.Basic /-! # Dependent-typed matrices -/ universe u u' v w z /-- `DMatrix m n` is the type of dependently typed matrices whose rows are indexed by the type `m` and whose columns are indexed by the type `n`. In most applications `m` and `n` are finite types. -/ def DMatrix (m : Type u) (n : Type u') (α : m → n → Type v) : Type max u u' v := ∀ i j, α i j variable {m n : Type*} variable {α : m → n → Type v} namespace DMatrix section Ext variable {M N : DMatrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨fun h => funext fun i => funext <| h i, fun h => by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end Ext /-- `M.map f` is the DMatrix obtained by applying `f` to each entry of the matrix `M`. -/ def map (M : DMatrix m n α) {β : m → n → Type w} (f : ∀ ⦃i j⦄, α i j → β i j) : DMatrix m n β := fun i j => f (M i j) @[simp] theorem map_apply {M : DMatrix m n α} {β : m → n → Type w} {f : ∀ ⦃i j⦄, α i j → β i j} {i : m} {j : n} : M.map f i j = f (M i j) := rfl @[simp] theorem map_map {M : DMatrix m n α} {β : m → n → Type w} {γ : m → n → Type z} {f : ∀ ⦃i j⦄, α i j → β i j} {g : ∀ ⦃i j⦄, β i j → γ i j} : (M.map f).map g = M.map fun _ _ x => g (f x) := by ext; simp /-- The transpose of a dmatrix. -/ def transpose (M : DMatrix m n α) : DMatrix n m fun j i => α i j | x, y => M y x @[inherit_doc] scoped postfix:1024 "ᵀ" => DMatrix.transpose /-- `DMatrix.col u` is the column matrix whose entries are given by `u`. -/ def col {α : m → Type v} (w : ∀ i, α i) : DMatrix m Unit fun i _j => α i | x, _y => w x /-- `DMatrix.row u` is the row matrix whose entries are given by `u`. -/ def row {α : n → Type v} (v : ∀ j, α j) : DMatrix Unit n fun _i j => α j | _x, y => v y instance [∀ i j, Inhabited (α i j)] : Inhabited (DMatrix m n α) := inferInstanceAs <| Inhabited <| ∀ i j, α i j instance [∀ i j, Add (α i j)] : Add (DMatrix m n α) := inferInstanceAs <| Add <| ∀ i j, α i j instance [∀ i j, AddSemigroup (α i j)] : AddSemigroup (DMatrix m n α) := inferInstanceAs <| AddSemigroup <| ∀ i j, α i j instance [∀ i j, AddCommSemigroup (α i j)] : AddCommSemigroup (DMatrix m n α) := inferInstanceAs <| AddCommSemigroup <| ∀ i j, α i j instance [∀ i j, Zero (α i j)] : Zero (DMatrix m n α) := inferInstanceAs <| Zero <| ∀ i j, α i j instance [∀ i j, AddMonoid (α i j)] : AddMonoid (DMatrix m n α) := inferInstanceAs <| AddMonoid <| ∀ i j, α i j instance [∀ i j, AddCommMonoid (α i j)] : AddCommMonoid (DMatrix m n α) := inferInstanceAs <| AddCommMonoid <| ∀ i j, α i j instance [∀ i j, Neg (α i j)] : Neg (DMatrix m n α) := inferInstanceAs <| Neg <| ∀ i j, α i j instance [∀ i j, Sub (α i j)] : Sub (DMatrix m n α) := inferInstanceAs <| Sub <| ∀ i j, α i j instance [∀ i j, AddGroup (α i j)] : AddGroup (DMatrix m n α) := inferInstanceAs <| AddGroup <| ∀ i j, α i j instance [∀ i j, AddCommGroup (α i j)] : AddCommGroup (DMatrix m n α) := inferInstanceAs <| AddCommGroup <| ∀ i j, α i j instance [∀ i j, Unique (α i j)] : Unique (DMatrix m n α) := inferInstanceAs <| Unique <| ∀ i j, α i j instance [∀ i j, Subsingleton (α i j)] : Subsingleton (DMatrix m n α) := inferInstanceAs <| Subsingleton <| ∀ i j, α i j @[simp] theorem zero_apply [∀ i j, Zero (α i j)] (i j) : (0 : DMatrix m n α) i j = 0 := rfl @[simp] theorem neg_apply [∀ i j, Neg (α i j)] (M : DMatrix m n α) (i j) : (-M) i j = -M i j := rfl @[simp] theorem add_apply [∀ i j, Add (α i j)] (M N : DMatrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl @[simp] theorem sub_apply [∀ i j, Sub (α i j)] (M N : DMatrix m n α) (i j) : (M - N) i j = M i j - N i j := rfl @[simp] theorem map_zero [∀ i j, Zero (α i j)] {β : m → n → Type w} [∀ i j, Zero (β i j)] {f : ∀ ⦃i j⦄, α i j → β i j} (h : ∀ i j, f (0 : α i j) = 0) : (0 : DMatrix m n α).map f = 0 := by ext; simp [h] theorem map_add [∀ i j, AddMonoid (α i j)] {β : m → n → Type w} [∀ i j, AddMonoid (β i j)] (f : ∀ ⦃i j⦄, α i j →+ β i j) (M N : DMatrix m n α) : ((M + N).map fun i j => @f i j) = (M.map fun i j => @f i j) + N.map fun i j => @f i j := by ext; simp theorem map_sub [∀ i j, AddGroup (α i j)] {β : m → n → Type w} [∀ i j, AddGroup (β i j)] (f : ∀ ⦃i j⦄, α i j →+ β i j) (M N : DMatrix m n α) : ((M - N).map fun i j => @f i j) = (M.map fun i j => @f i j) - N.map fun i j => @f i j := by ext; simp instance subsingleton_of_empty_left [IsEmpty m] : Subsingleton (DMatrix m n α) := ⟨fun M N => by ext i exact isEmptyElim i⟩ instance subsingleton_of_empty_right [IsEmpty n] : Subsingleton (DMatrix m n α) := ⟨fun M N => by ext i j; exact isEmptyElim j⟩ end DMatrix /-- The `AddMonoidHom` between spaces of dependently typed matrices induced by an `AddMonoidHom` between their coefficients. -/ def AddMonoidHom.mapDMatrix [∀ i j, AddMonoid (α i j)] {β : m → n → Type w} [∀ i j, AddMonoid (β i j)] (f : ∀ ⦃i j⦄, α i j →+ β i j) : DMatrix m n α →+ DMatrix m n β where toFun M := M.map fun i j => @f i j map_zero' := by simp map_add' := DMatrix.map_add f @[simp] theorem AddMonoidHom.mapDMatrix_apply [∀ i j, AddMonoid (α i j)] {β : m → n → Type w} [∀ i j, AddMonoid (β i j)] (f : ∀ ⦃i j⦄, α i j →+ β i j) (M : DMatrix m n α) : AddMonoidHom.mapDMatrix f M = M.map fun i j => @f i j := rfl
test_regular_conv.v
From mathcomp Require Import all_boot all_order all_algebra all_field. Section regular. Import GRing. Goal forall R : ringType, [the lalgType R of R^o] = R :> ringType. Proof. by move=> [? []]. Qed. Goal forall R : comRingType, [the algType R of R^o] = R :> ringType. Proof. by move=> [? []]. Qed. Goal forall R : comRingType, [the comAlgType R of R^o] = R :> ringType. Proof. by move=> [? []]. Qed. Goal forall R : comUnitRingType, [the unitAlgType R of R^o] = R :> unitRingType. Proof. by move=> [? []]. Qed. Goal forall R : comUnitRingType, [the comUnitAlgType R of R^o] = R :> comUnitRingType. Proof. by move=> [? []]. Qed. Goal forall R : comUnitRingType, [the falgType R of R^o] = R :> unitRingType. Proof. by move=> [? []]. Qed. Goal forall K : fieldType, [the fieldExtType K of K^o] = K :> fieldType. Proof. by move=> [? []]. Qed. End regular.
BaireMeasurable.lean
/- Copyright (c) 2024 Felix Weilacher. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Felix Weilacher -/ import Mathlib.Topology.LocallyClosed import Mathlib.MeasureTheory.MeasurableSpace.EventuallyMeasurable import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic /-! # Baire category and Baire measurable sets This file defines some of the basic notions of Baire category and Baire measurable sets. ## Main definitions First, we define the notation `=ᵇ`. This denotes eventual equality with respect to the filter of `residual` sets in a topological space. A set `s` in a topological space `α` is called a `BaireMeasurableSet` or said to have the *property of Baire* if it satisfies either of the following equivalent conditions: * There is a *Borel* set `u` such that `s =ᵇ u`. (This is our definition) * There is an *open* set `u` such that `s =ᵇ u`. (See `BaireMeasurableSet.residual_eq_open`) -/ variable (α : Type*) {β : Type*} [TopologicalSpace α] [TopologicalSpace β] open Topology /-- Notation for `=ᶠ[residual _]`. That is, eventual equality with respect to the filter of residual sets. -/ scoped[Topology] notation:50 f " =ᵇ " g:50 => Filter.EventuallyEq (residual _) f g /-- Notation to say that a property of points in a topological space holds almost everywhere in the sense of Baire category. That is, on a residual set. -/ scoped[Topology] notation3 "∀ᵇ " (...) ", " r:(scoped p => Filter.Eventually p <| residual _) => r /-- Notation to say that a property of points in a topological space holds on a non meager set. -/ scoped[Topology] notation3 "∃ᵇ " (...) ", " r:(scoped p => Filter.Frequently p <| residual _) => r variable {α} theorem coborder_mem_residual {s : Set α} (hs : IsLocallyClosed s) : coborder s ∈ residual α := residual_of_dense_open hs.isOpen_coborder dense_coborder theorem closure_residualEq {s : Set α} (hs : IsLocallyClosed s) : closure s =ᵇ s := by rw [Filter.eventuallyEq_set] filter_upwards [coborder_mem_residual hs] with x hx nth_rewrite 2 [← closure_inter_coborder (s := s)] simp [hx] /-- We say a set is a `BaireMeasurableSet` if it differs from some Borel set by a meager set. This forms a σ-algebra. It is equivalent, and a more standard definition, to say that the set differs from some *open* set by a meager set. See `BaireMeasurableSet.iff_residualEq_isOpen` -/ def BaireMeasurableSet (s : Set α) : Prop := @MeasurableSet _ (eventuallyMeasurableSpace (borel _) (residual _)) s variable {s t : Set α} namespace BaireMeasurableSet theorem of_mem_residual (h : s ∈ residual _) : BaireMeasurableSet s := eventuallyMeasurableSet_of_mem_filter (α := α) h theorem _root_.MeasurableSet.baireMeasurableSet [MeasurableSpace α] [BorelSpace α] (h : MeasurableSet s) : BaireMeasurableSet s := by borelize α exact h.eventuallyMeasurableSet theorem _root_.IsOpen.baireMeasurableSet (h : IsOpen s) : BaireMeasurableSet s := by borelize α exact h.measurableSet.baireMeasurableSet theorem compl (h : BaireMeasurableSet s) : BaireMeasurableSet sᶜ := MeasurableSet.compl h theorem of_compl (h : BaireMeasurableSet sᶜ) : BaireMeasurableSet s := MeasurableSet.of_compl h theorem _root_.IsMeagre.baireMeasurableSet (h : IsMeagre s) : BaireMeasurableSet s := (of_mem_residual h).of_compl theorem iUnion {ι : Sort*} [Countable ι] {s : ι → Set α} (h : ∀ i, BaireMeasurableSet (s i)) : BaireMeasurableSet (⋃ i, s i) := MeasurableSet.iUnion h theorem biUnion {ι : Type*} {s : ι → Set α} {t : Set ι} (ht : t.Countable) (h : ∀ i ∈ t, BaireMeasurableSet (s i)) : BaireMeasurableSet (⋃ i ∈ t, s i) := MeasurableSet.biUnion ht h theorem sUnion {s : Set (Set α)} (hs : s.Countable) (h : ∀ t ∈ s, BaireMeasurableSet t) : BaireMeasurableSet (⋃₀ s) := MeasurableSet.sUnion hs h theorem iInter {ι : Sort*} [Countable ι] {s : ι → Set α} (h : ∀ i, BaireMeasurableSet (s i)) : BaireMeasurableSet (⋂ i, s i) := MeasurableSet.iInter h theorem biInter {ι : Type*} {s : ι → Set α} {t : Set ι} (ht : t.Countable) (h : ∀ i ∈ t, BaireMeasurableSet (s i)) : BaireMeasurableSet (⋂ i ∈ t, s i) := MeasurableSet.biInter ht h theorem sInter {s : Set (Set α)} (hs : s.Countable) (h : ∀ t ∈ s, BaireMeasurableSet t) : BaireMeasurableSet (⋂₀ s) := MeasurableSet.sInter hs h theorem union (hs : BaireMeasurableSet s) (ht : BaireMeasurableSet t) : BaireMeasurableSet (s ∪ t) := MeasurableSet.union hs ht theorem inter (hs : BaireMeasurableSet s) (ht : BaireMeasurableSet t) : BaireMeasurableSet (s ∩ t) := MeasurableSet.inter hs ht theorem diff (hs : BaireMeasurableSet s) (ht : BaireMeasurableSet t) : BaireMeasurableSet (s \ t) := MeasurableSet.diff hs ht theorem congr (hs : BaireMeasurableSet s) (h : s =ᵇ t) : BaireMeasurableSet t := EventuallyMeasurableSet.congr (α := α) hs h.symm end BaireMeasurableSet open Filter /-- Any Borel set differs from some open set by a meager set. -/ theorem MeasurableSet.residualEq_isOpen [MeasurableSpace α] [BorelSpace α] (h : MeasurableSet s) : ∃ u : Set α, IsOpen u ∧ s =ᵇ u := by induction s, h using MeasurableSet.induction_on_open with | isOpen U hU => exact ⟨U, hU, .rfl⟩ | compl s _ ihs => obtain ⟨U, Uo, hsU⟩ := ihs use (closure U)ᶜ, isClosed_closure.isOpen_compl exact .compl <| hsU.trans <| .symm <| closure_residualEq Uo.isLocallyClosed | iUnion f _ _ ihf => choose u uo su using ihf exact ⟨⋃ i, u i, isOpen_iUnion uo, EventuallyEq.countable_iUnion su⟩ /-- Any `BaireMeasurableSet` differs from some open set by a meager set. -/ theorem BaireMeasurableSet.residualEq_isOpen (h : BaireMeasurableSet s) : ∃ u : Set α, (IsOpen u) ∧ s =ᵇ u := by borelize α rcases h with ⟨t, ht, hst⟩ rcases ht.residualEq_isOpen with ⟨u, hu, htu⟩ exact ⟨u, hu, hst.trans htu⟩ /-- A set is Baire measurable if and only if it differs from some open set by a meager set. -/ theorem BaireMeasurableSet.iff_residualEq_isOpen : BaireMeasurableSet s ↔ ∃ u : Set α, (IsOpen u) ∧ s =ᵇ u := ⟨fun h => h.residualEq_isOpen , fun ⟨_, uo, ueq⟩ => uo.baireMeasurableSet.congr ueq.symm⟩ section Map open Set variable {f : α → β} theorem tendsto_residual_of_isOpenMap (hc : Continuous f) (ho : IsOpenMap f) : Tendsto f (residual α) (residual β) := by apply le_countableGenerate_iff_of_countableInterFilter.mpr rintro t ⟨ht, htd⟩ exact residual_of_dense_open (ht.preimage hc) (htd.preimage ho) /-- The preimage of a meager set under a continuous open map is meager. -/ theorem IsMeagre.preimage_of_isOpenMap (hc : Continuous f) (ho : IsOpenMap f) {s : Set β} (h : IsMeagre s) : IsMeagre (f ⁻¹' s) := tendsto_residual_of_isOpenMap hc ho h /-- The preimage of a `BaireMeasurableSet` under a continuous open map is Baire measurable. -/ theorem BaireMeasurableSet.preimage (hc : Continuous f) (ho : IsOpenMap f) {s : Set β} (h : BaireMeasurableSet s) : BaireMeasurableSet (f ⁻¹' s) := by rcases h with ⟨u, hu, hsu⟩ refine ⟨f ⁻¹' u, ?_, hsu.filter_mono <| tendsto_residual_of_isOpenMap hc ho⟩ borelize α β exact hc.measurable hu theorem Homeomorph.residual_map_eq (h : α ≃ₜ β) : (residual α).map h = residual β := by refine le_antisymm (tendsto_residual_of_isOpenMap h.continuous h.isOpenMap) (le_map ?_) simp_rw [← preimage_symm] exact tendsto_residual_of_isOpenMap h.symm.continuous h.symm.isOpenMap end Map
Real.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 -/ import Mathlib.MeasureTheory.Constructions.BorelSpace.Order import Mathlib.MeasureTheory.MeasurableSpace.Prod import Mathlib.MeasureTheory.Measure.Typeclasses.NoAtoms import Mathlib.Topology.Instances.Real.Lemmas /-! # Borel (measurable) spaces ℝ, ℝ≥0, ℝ≥0∞ ## Main statements * `borel_eq_generateFrom_Ixx_rat` (where Ixx is one of {Ioo, Ioi, Iio, Ici, Iic): the Borel sigma algebra on ℝ is generated by intervals with rational endpoints; * `isPiSystem_Ixx_rat` (where Ixx is one of {Ioo, Ioi, Iio, Ici, Iic): intervals with rational endpoints form a pi system on ℝ; * `measurable_real_toNNReal`, `measurable_coe_nnreal_real`, `measurable_coe_nnreal_ennreal`, `ENNReal.measurable_ofReal`, `ENNReal.measurable_toReal`: measurability of various coercions between ℝ, ℝ≥0, and ℝ≥0∞; * `Measurable.real_toNNReal`, `Measurable.coe_nnreal_real`, `Measurable.coe_nnreal_ennreal`, `Measurable.ennreal_ofReal`, `Measurable.ennreal_toNNReal`, `Measurable.ennreal_toReal`: measurability of functions composed with various coercions between ℝ, ℝ≥0, and ℝ≥0∞ (also similar results for a.e.-measurability); * `Measurable.ennreal*` : measurability of special cases for arithmetic operations on `ℝ≥0∞`. -/ open Set Filter MeasureTheory MeasurableSpace open scoped Topology NNReal ENNReal universe u v w x y variable {α β γ δ : Type*} {ι : Sort y} {s t u : Set α} namespace Real theorem borel_eq_generateFrom_Ioo_rat : borel ℝ = .generateFrom (⋃ (a : ℚ) (b : ℚ) (_ : a < b), {Ioo (a : ℝ) (b : ℝ)}) := isTopologicalBasis_Ioo_rat.borel_eq_generateFrom theorem borel_eq_generateFrom_Iio_rat : borel ℝ = .generateFrom (⋃ a : ℚ, {Iio (a : ℝ)}) := by rw [borel_eq_generateFrom_Iio] refine le_antisymm (generateFrom_le ?_) (generateFrom_mono <| iUnion_subset fun q ↦ singleton_subset_iff.mpr <| mem_range_self _) rintro _ ⟨a, rfl⟩ have : IsLUB (range ((↑) : ℚ → ℝ) ∩ Iio a) a := by simp [isLUB_iff_le_iff, mem_upperBounds, ← le_iff_forall_rat_lt_imp_le] rw [← this.biUnion_Iio_eq, ← image_univ, ← image_inter_preimage, univ_inter, biUnion_image] exact MeasurableSet.biUnion (to_countable _) fun b _ => GenerateMeasurable.basic (Iio (b : ℝ)) (by simp) theorem borel_eq_generateFrom_Ioi_rat : borel ℝ = .generateFrom (⋃ a : ℚ, {Ioi (a : ℝ)}) := by rw [borel_eq_generateFrom_Ioi] refine le_antisymm (generateFrom_le ?_) (generateFrom_mono <| iUnion_subset fun q ↦ singleton_subset_iff.mpr <| mem_range_self _) rintro _ ⟨a, rfl⟩ have : IsGLB (range ((↑) : ℚ → ℝ) ∩ Ioi a) a := by simp [isGLB_iff_le_iff, mem_lowerBounds, ← le_iff_forall_lt_rat_imp_le] rw [← this.biUnion_Ioi_eq, ← image_univ, ← image_inter_preimage, univ_inter, biUnion_image] exact MeasurableSet.biUnion (to_countable _) fun b _ => GenerateMeasurable.basic (Ioi (b : ℝ)) (by simp) theorem borel_eq_generateFrom_Iic_rat : borel ℝ = .generateFrom (⋃ a : ℚ, {Iic (a : ℝ)}) := by rw [borel_eq_generateFrom_Ioi_rat, iUnion_singleton_eq_range, iUnion_singleton_eq_range] refine le_antisymm (generateFrom_le ?_) (generateFrom_le ?_) <;> rintro _ ⟨q, rfl⟩ <;> dsimp only <;> [rw [← compl_Iic]; rw [← compl_Ioi]] <;> exact MeasurableSet.compl (GenerateMeasurable.basic _ (mem_range_self q)) theorem borel_eq_generateFrom_Ici_rat : borel ℝ = .generateFrom (⋃ a : ℚ, {Ici (a : ℝ)}) := by rw [borel_eq_generateFrom_Iio_rat, iUnion_singleton_eq_range, iUnion_singleton_eq_range] refine le_antisymm (generateFrom_le ?_) (generateFrom_le ?_) <;> rintro _ ⟨q, rfl⟩ <;> dsimp only <;> [rw [← compl_Ici]; rw [← compl_Iio]] <;> exact MeasurableSet.compl (GenerateMeasurable.basic _ (mem_range_self q)) theorem isPiSystem_Ioo_rat : IsPiSystem (⋃ (a : ℚ) (b : ℚ) (_ : a < b), {Ioo (a : ℝ) (b : ℝ)}) := by convert isPiSystem_Ioo ((↑) : ℚ → ℝ) ((↑) : ℚ → ℝ) ext x simp [eq_comm] theorem isPiSystem_Iio_rat : IsPiSystem (⋃ a : ℚ, {Iio (a : ℝ)}) := by convert isPiSystem_image_Iio (((↑) : ℚ → ℝ) '' univ) ext x simp only [iUnion_singleton_eq_range, mem_range, image_univ, mem_image, exists_exists_eq_and] theorem isPiSystem_Ioi_rat : IsPiSystem (⋃ a : ℚ, {Ioi (a : ℝ)}) := by convert isPiSystem_image_Ioi (((↑) : ℚ → ℝ) '' univ) ext x simp only [iUnion_singleton_eq_range, mem_range, image_univ, mem_image, exists_exists_eq_and] theorem isPiSystem_Iic_rat : IsPiSystem (⋃ a : ℚ, {Iic (a : ℝ)}) := by convert isPiSystem_image_Iic (((↑) : ℚ → ℝ) '' univ) ext x simp only [iUnion_singleton_eq_range, mem_range, image_univ, mem_image, exists_exists_eq_and] theorem isPiSystem_Ici_rat : IsPiSystem (⋃ a : ℚ, {Ici (a : ℝ)}) := by convert isPiSystem_image_Ici (((↑) : ℚ → ℝ) '' univ) ext x simp only [iUnion_singleton_eq_range, mem_range, image_univ, mem_image, exists_exists_eq_and] /-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals with rational endpoints for a locally finite measure `μ` on `ℝ`. -/ def finiteSpanningSetsInIooRat (μ : Measure ℝ) [IsLocallyFiniteMeasure μ] : μ.FiniteSpanningSetsIn (⋃ (a : ℚ) (b : ℚ) (_ : a < b), {Ioo (a : ℝ) (b : ℝ)}) where set n := Ioo (-(n + 1)) (n + 1) set_mem n := by simp only [mem_iUnion, mem_singleton_iff] refine ⟨-(n + 1 : ℕ), n + 1, ?_, by simp⟩ -- TODO: norm_cast fails here? push_cast exact neg_lt_self n.cast_add_one_pos finite _ := measure_Ioo_lt_top spanning := iUnion_eq_univ_iff.2 fun x => ⟨⌊|x|⌋₊, neg_lt.1 ((neg_le_abs x).trans_lt (Nat.lt_floor_add_one _)), (le_abs_self x).trans_lt (Nat.lt_floor_add_one _)⟩ theorem measure_ext_Ioo_rat {μ ν : Measure ℝ} [IsLocallyFiniteMeasure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := (finiteSpanningSetsInIooRat μ).ext borel_eq_generateFrom_Ioo_rat isPiSystem_Ioo_rat <| by simp only [mem_iUnion, mem_singleton_iff] rintro _ ⟨a, b, -, rfl⟩ apply h end Real variable {mα : MeasurableSpace α} @[measurability, fun_prop] theorem measurable_real_toNNReal : Measurable Real.toNNReal := continuous_real_toNNReal.measurable @[measurability, fun_prop] theorem Measurable.real_toNNReal {f : α → ℝ} (hf : Measurable f) : Measurable fun x => Real.toNNReal (f x) := measurable_real_toNNReal.comp hf @[measurability, fun_prop] theorem AEMeasurable.real_toNNReal {f : α → ℝ} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => Real.toNNReal (f x)) μ := measurable_real_toNNReal.comp_aemeasurable hf @[measurability] theorem measurable_coe_nnreal_real : Measurable ((↑) : ℝ≥0 → ℝ) := NNReal.continuous_coe.measurable @[measurability, fun_prop] theorem Measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : Measurable f) : Measurable fun x => (f x : ℝ) := measurable_coe_nnreal_real.comp hf @[measurability, fun_prop] theorem AEMeasurable.coe_nnreal_real {f : α → ℝ≥0} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => (f x : ℝ)) μ := measurable_coe_nnreal_real.comp_aemeasurable hf @[measurability] theorem measurable_coe_nnreal_ennreal : Measurable ((↑) : ℝ≥0 → ℝ≥0∞) := ENNReal.continuous_coe.measurable @[measurability, fun_prop] theorem Measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : Measurable f) : Measurable fun x => (f x : ℝ≥0∞) := ENNReal.continuous_coe.measurable.comp hf @[measurability, fun_prop] theorem AEMeasurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => (f x : ℝ≥0∞)) μ := ENNReal.continuous_coe.measurable.comp_aemeasurable hf @[measurability, fun_prop] theorem Measurable.ennreal_ofReal {f : α → ℝ} (hf : Measurable f) : Measurable fun x => ENNReal.ofReal (f x) := ENNReal.continuous_ofReal.measurable.comp hf @[measurability, fun_prop] lemma AEMeasurable.ennreal_ofReal {f : α → ℝ} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x ↦ ENNReal.ofReal (f x)) μ := ENNReal.continuous_ofReal.measurable.comp_aemeasurable hf @[simp, norm_cast] theorem measurable_coe_nnreal_real_iff {f : α → ℝ≥0} : Measurable (fun x => f x : α → ℝ) ↔ Measurable f := ⟨fun h => by simpa only [Real.toNNReal_coe] using h.real_toNNReal, Measurable.coe_nnreal_real⟩ @[simp, norm_cast] theorem aemeasurable_coe_nnreal_real_iff {f : α → ℝ≥0} {μ : Measure α} : AEMeasurable (fun x => f x : α → ℝ) μ ↔ AEMeasurable f μ := ⟨fun h ↦ by simpa only [Real.toNNReal_coe] using h.real_toNNReal, AEMeasurable.coe_nnreal_real⟩ /-- The set of finite `ℝ≥0∞` numbers is `MeasurableEquiv` to `ℝ≥0`. -/ def MeasurableEquiv.ennrealEquivNNReal : { r : ℝ≥0∞ | r ≠ ∞ } ≃ᵐ ℝ≥0 := ENNReal.neTopHomeomorphNNReal.toMeasurableEquiv namespace ENNReal theorem measurable_of_measurable_nnreal {f : ℝ≥0∞ → α} (h : Measurable fun p : ℝ≥0 => f p) : Measurable f := measurable_of_measurable_on_compl_singleton ∞ (MeasurableEquiv.ennrealEquivNNReal.symm.measurable_comp_iff.1 h) /-- `ℝ≥0∞` is `MeasurableEquiv` to `ℝ≥0 ⊕ Unit`. -/ def ennrealEquivSum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ Unit := { Equiv.optionEquivSumPUnit ℝ≥0 with measurable_toFun := measurable_of_measurable_nnreal measurable_inl measurable_invFun := measurable_fun_sum measurable_coe_nnreal_ennreal (@measurable_const ℝ≥0∞ Unit _ _ ∞) } open Function (uncurry) theorem measurable_of_measurable_nnreal_prod {_ : MeasurableSpace β} {_ : MeasurableSpace γ} {f : ℝ≥0∞ × β → γ} (H₁ : Measurable fun p : ℝ≥0 × β => f (p.1, p.2)) (H₂ : Measurable fun x => f (∞, x)) : Measurable f := let e : ℝ≥0∞ × β ≃ᵐ (ℝ≥0 × β) ⊕ (Unit × β) := (ennrealEquivSum.prodCongr (MeasurableEquiv.refl β)).trans (MeasurableEquiv.sumProdDistrib _ _ _) e.symm.measurable_comp_iff.1 <| measurable_fun_sum H₁ (H₂.comp measurable_id.snd) theorem measurable_of_measurable_nnreal_nnreal {_ : MeasurableSpace β} {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : Measurable fun p : ℝ≥0 × ℝ≥0 => f (p.1, p.2)) (h₂ : Measurable fun r : ℝ≥0 => f (∞, r)) (h₃ : Measurable fun r : ℝ≥0 => f (r, ∞)) : Measurable f := measurable_of_measurable_nnreal_prod (measurable_swap_iff.1 <| measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nnreal h₂) @[measurability] theorem measurable_ofReal : Measurable ENNReal.ofReal := ENNReal.continuous_ofReal.measurable @[measurability] theorem measurable_toReal : Measurable ENNReal.toReal := ENNReal.measurable_of_measurable_nnreal measurable_coe_nnreal_real @[measurability] theorem measurable_toNNReal : Measurable ENNReal.toNNReal := ENNReal.measurable_of_measurable_nnreal measurable_id instance instMeasurableMul₂ : MeasurableMul₂ ℝ≥0∞ := by refine ⟨measurable_of_measurable_nnreal_nnreal ?_ ?_ ?_⟩ · simp only [← ENNReal.coe_mul, measurable_mul.coe_nnreal_ennreal] · simp only [ENNReal.top_mul', ENNReal.coe_eq_zero] exact measurable_const.piecewise (measurableSet_singleton _) measurable_const · simp only [ENNReal.mul_top', ENNReal.coe_eq_zero] exact measurable_const.piecewise (measurableSet_singleton _) measurable_const instance instMeasurableSub₂ : MeasurableSub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal <;> simp [tsub_eq_zero_of_le]; exact continuous_sub.measurable.coe_nnreal_ennreal⟩ instance instMeasurableInv : MeasurableInv ℝ≥0∞ := ⟨continuous_inv.measurable⟩ instance : MeasurableSMul ℝ≥0 ℝ≥0∞ where measurable_const_smul _ := by simp_rw [ENNReal.smul_def]; exact measurable_const_smul _ measurable_smul_const _ := by simp_rw [ENNReal.smul_def] exact measurable_coe_nnreal_ennreal.mul_const _ /-- A limit (over a general filter) of measurable `ℝ≥0∞` valued functions is measurable. -/ theorem measurable_of_tendsto' {ι : Type*} {f : ι → α → ℝ≥0∞} {g : α → ℝ≥0∞} (u : Filter ι) [NeBot u] [IsCountablyGenerated u] (hf : ∀ i, Measurable (f i)) (lim : Tendsto f u (𝓝 g)) : Measurable g := by rcases u.exists_seq_tendsto with ⟨x, hx⟩ rw [tendsto_pi_nhds] at lim have : (fun y => liminf (fun n => (f (x n) y : ℝ≥0∞)) atTop) = g := by ext1 y exact ((lim y).comp hx).liminf_eq rw [← this] change Measurable fun y => liminf (fun n => (f (x n) y : ℝ≥0∞)) atTop exact .liminf fun n => hf (x n) /-- A sequential limit of measurable `ℝ≥0∞` valued functions is measurable. -/ theorem measurable_of_tendsto {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞} (hf : ∀ i, Measurable (f i)) (lim : Tendsto f atTop (𝓝 g)) : Measurable g := measurable_of_tendsto' atTop hf lim /-- A limit (over a general filter) of a.e.-measurable `ℝ≥0∞` valued functions is a.e.-measurable. -/ lemma aemeasurable_of_tendsto' {ι : Type*} {f : ι → α → ℝ≥0∞} {g : α → ℝ≥0∞} {μ : Measure α} (u : Filter ι) [NeBot u] [IsCountablyGenerated u] (hf : ∀ i, AEMeasurable (f i) μ) (hlim : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) u (𝓝 (g a))) : AEMeasurable g μ := by rcases u.exists_seq_tendsto with ⟨v, hv⟩ have h'f : ∀ n, AEMeasurable (f (v n)) μ := fun n ↦ hf (v n) set p : α → (ℕ → ℝ≥0∞) → Prop := fun x f' ↦ Tendsto f' atTop (𝓝 (g x)) have hp : ∀ᵐ x ∂μ, p x fun n ↦ f (v n) x := by filter_upwards [hlim] with x hx using hx.comp hv classical set aeSeqLim := fun x ↦ ite (x ∈ aeSeqSet h'f p) (g x) (⟨f (v 0) x⟩ : Nonempty ℝ≥0∞).some refine ⟨aeSeqLim, measurable_of_tendsto' atTop (aeSeq.measurable h'f p) (tendsto_pi_nhds.mpr fun x ↦ ?_), ?_⟩ · unfold aeSeqLim simp_rw [aeSeq] split_ifs with hx · simp_rw [aeSeq.mk_eq_fun_of_mem_aeSeqSet h'f hx] exact aeSeq.fun_prop_of_mem_aeSeqSet h'f hx · exact tendsto_const_nhds · exact (ite_ae_eq_of_measure_compl_zero g (fun x ↦ (⟨f (v 0) x⟩ : Nonempty ℝ≥0∞).some) (aeSeqSet h'f p) (aeSeq.measure_compl_aeSeqSet_eq_zero h'f hp)).symm /-- A limit of a.e.-measurable `ℝ≥0∞` valued functions is a.e.-measurable. -/ lemma aemeasurable_of_tendsto {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞} {μ : Measure α} (hf : ∀ i, AEMeasurable (f i) μ) (hlim : ∀ᵐ a ∂μ, Tendsto (fun i ↦ f i a) atTop (𝓝 (g a))) : AEMeasurable g μ := aemeasurable_of_tendsto' atTop hf hlim end ENNReal @[measurability, fun_prop] theorem Measurable.ennreal_toNNReal {f : α → ℝ≥0∞} (hf : Measurable f) : Measurable fun x => (f x).toNNReal := ENNReal.measurable_toNNReal.comp hf @[measurability, fun_prop] theorem AEMeasurable.ennreal_toNNReal {f : α → ℝ≥0∞} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => (f x).toNNReal) μ := ENNReal.measurable_toNNReal.comp_aemeasurable hf @[simp, norm_cast] theorem measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} : (Measurable fun x => (f x : ℝ≥0∞)) ↔ Measurable f := ⟨fun h => h.ennreal_toNNReal, fun h => h.coe_nnreal_ennreal⟩ @[simp, norm_cast] theorem aemeasurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} {μ : Measure α} : AEMeasurable (fun x => (f x : ℝ≥0∞)) μ ↔ AEMeasurable f μ := ⟨fun h => h.ennreal_toNNReal, fun h => h.coe_nnreal_ennreal⟩ @[measurability, fun_prop] theorem Measurable.ennreal_toReal {f : α → ℝ≥0∞} (hf : Measurable f) : Measurable fun x => ENNReal.toReal (f x) := ENNReal.measurable_toReal.comp hf @[measurability, fun_prop] theorem AEMeasurable.ennreal_toReal {f : α → ℝ≥0∞} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => ENNReal.toReal (f x)) μ := ENNReal.measurable_toReal.comp_aemeasurable hf /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability, fun_prop] theorem Measurable.ennreal_tsum {ι} [Countable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, Measurable (f i)) : Measurable fun x => ∑' i, f i x := by simp_rw [ENNReal.tsum_eq_iSup_sum] exact .iSup fun s ↦ s.measurable_fun_sum fun i _ => h i @[measurability, fun_prop] theorem Measurable.ennreal_tsum' {ι} [Countable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, Measurable (f i)) : Measurable (∑' i, f i) := by convert Measurable.ennreal_tsum h with x exact tsum_apply (Pi.summable.2 fun _ => ENNReal.summable) @[measurability, fun_prop] theorem Measurable.nnreal_tsum {ι} [Countable ι] {f : ι → α → ℝ≥0} (h : ∀ i, Measurable (f i)) : Measurable fun x => ∑' i, f i x := by simp_rw [NNReal.tsum_eq_toNNReal_tsum] exact (Measurable.ennreal_tsum fun i => (h i).coe_nnreal_ennreal).ennreal_toNNReal @[measurability, fun_prop] theorem AEMeasurable.ennreal_tsum {ι} [Countable ι] {f : ι → α → ℝ≥0∞} {μ : Measure α} (h : ∀ i, AEMeasurable (f i) μ) : AEMeasurable (fun x => ∑' i, f i x) μ := by simp_rw [ENNReal.tsum_eq_iSup_sum] exact .iSup fun s ↦ Finset.aemeasurable_fun_sum s fun i _ => h i @[measurability, fun_prop] theorem AEMeasurable.nnreal_tsum {α : Type*} {_ : MeasurableSpace α} {ι : Type*} [Countable ι] {f : ι → α → NNReal} {μ : Measure α} (h : ∀ i : ι, AEMeasurable (f i) μ) : AEMeasurable (fun x : α => ∑' i : ι, f i x) μ := by simp_rw [NNReal.tsum_eq_toNNReal_tsum] exact (AEMeasurable.ennreal_tsum fun i => (h i).coe_nnreal_ennreal).ennreal_toNNReal @[measurability, fun_prop] theorem measurable_coe_real_ereal : Measurable ((↑) : ℝ → EReal) := continuous_coe_real_ereal.measurable @[measurability] theorem Measurable.coe_real_ereal {f : α → ℝ} (hf : Measurable f) : Measurable fun x => (f x : EReal) := measurable_coe_real_ereal.comp hf @[measurability] theorem AEMeasurable.coe_real_ereal {f : α → ℝ} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => (f x : EReal)) μ := measurable_coe_real_ereal.comp_aemeasurable hf /-- The set of finite `EReal` numbers is `MeasurableEquiv` to `ℝ`. -/ def MeasurableEquiv.erealEquivReal : ({⊥, ⊤}ᶜ : Set EReal) ≃ᵐ ℝ := EReal.neBotTopHomeomorphReal.toMeasurableEquiv theorem EReal.measurable_of_measurable_real {f : EReal → α} (h : Measurable fun p : ℝ => f p) : Measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (MeasurableEquiv.erealEquivReal.symm.measurable_comp_iff.1 h) @[measurability] theorem measurable_ereal_toReal : Measurable EReal.toReal := EReal.measurable_of_measurable_real (by simpa using measurable_id) @[measurability, fun_prop] theorem Measurable.ereal_toReal {f : α → EReal} (hf : Measurable f) : Measurable fun x => (f x).toReal := measurable_ereal_toReal.comp hf @[measurability, fun_prop] theorem AEMeasurable.ereal_toReal {f : α → EReal} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => (f x).toReal) μ := measurable_ereal_toReal.comp_aemeasurable hf @[measurability] theorem measurable_coe_ennreal_ereal : Measurable ((↑) : ℝ≥0∞ → EReal) := continuous_coe_ennreal_ereal.measurable @[measurability, fun_prop] theorem Measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : Measurable f) : Measurable fun x => (f x : EReal) := measurable_coe_ennreal_ereal.comp hf @[measurability, fun_prop] theorem AEMeasurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => (f x : EReal)) μ := measurable_coe_ennreal_ereal.comp_aemeasurable hf @[measurability] theorem measurable_ereal_toENNReal : Measurable EReal.toENNReal := EReal.measurable_of_measurable_real (by simpa using ENNReal.measurable_ofReal) @[measurability, fun_prop] theorem Measurable.ereal_toENNReal {f : α → EReal} (hf : Measurable f) : Measurable fun x => (f x).toENNReal := measurable_ereal_toENNReal.comp hf @[measurability, fun_prop] theorem AEMeasurable.ereal_toENNReal {f : α → EReal} {μ : Measure α} (hf : AEMeasurable f μ) : AEMeasurable (fun x => (f x).toENNReal) μ := measurable_ereal_toENNReal.comp_aemeasurable hf namespace NNReal instance : MeasurableSMul₂ ℝ≥0 ℝ≥0∞ where measurable_smul := show Measurable fun r : ℝ≥0 × ℝ≥0∞ ↦ (r.1 : ℝ≥0) * r.2 by fun_prop /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. -/ theorem measurable_of_tendsto' {ι} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : Filter ι) [NeBot u] [IsCountablyGenerated u] (hf : ∀ i, Measurable (f i)) (lim : Tendsto f u (𝓝 g)) : Measurable g := by simp_rw [← measurable_coe_nnreal_ennreal_iff] at hf ⊢ refine ENNReal.measurable_of_tendsto' u hf ?_ rw [tendsto_pi_nhds] at lim ⊢ exact fun x => (ENNReal.continuous_coe.tendsto (g x)).comp (lim x) /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ theorem measurable_of_tendsto {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, Measurable (f i)) (lim : Tendsto f atTop (𝓝 g)) : Measurable g := measurable_of_tendsto' atTop hf lim end NNReal namespace EReal lemma measurableEmbedding_coe : MeasurableEmbedding Real.toEReal := isOpenEmbedding_coe.measurableEmbedding instance : MeasurableAdd₂ EReal := ⟨EReal.lowerSemicontinuous_add.measurable⟩ section MeasurableMul variable {α β γ : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} {mγ : MeasurableSpace γ} lemma measurable_of_real_prod {f : EReal × β → γ} (h_real : Measurable fun p : ℝ × β ↦ f (p.1, p.2)) (h_bot : Measurable fun x ↦ f (⊥, x)) (h_top : Measurable fun x ↦ f (⊤, x)) : Measurable f := .of_union₃_range_cover (measurableEmbedding_prodMk_left _) (measurableEmbedding_prodMk_left _) (measurableEmbedding_coe.prodMap .id) (by simp [-univ_subset_iff, subset_def, EReal.forall]) h_bot h_top h_real lemma measurable_of_real_real {f : EReal × EReal → β} (h_real : Measurable fun p : ℝ × ℝ ↦ f (p.1, p.2)) (h_bot_left : Measurable fun r : ℝ ↦ f (⊥, r)) (h_top_left : Measurable fun r : ℝ ↦ f (⊤, r)) (h_bot_right : Measurable fun r : ℝ ↦ f (r, ⊥)) (h_top_right : Measurable fun r : ℝ ↦ f (r, ⊤)) : Measurable f := by refine measurable_of_real_prod ?_ ?_ ?_ · refine measurable_swap_iff.mp <| measurable_of_real_prod ?_ h_bot_right h_top_right exact h_real.comp measurable_swap · exact measurable_of_measurable_real h_bot_left · exact measurable_of_measurable_real h_top_left private lemma measurable_const_mul (c : EReal) : Measurable fun (x : EReal) ↦ c * x := by refine measurable_of_measurable_real ?_ have h1 : (fun (p : ℝ) ↦ (⊥ : EReal) * p) = fun p ↦ if p = 0 then (0 : EReal) else (if p < 0 then ⊤ else ⊥) := by ext p split_ifs with h1 h2 · simp [h1] · rw [bot_mul_coe_of_neg h2] · rw [bot_mul_coe_of_pos] exact lt_of_le_of_ne (not_lt.mp h2) (Ne.symm h1) have h2 : Measurable fun (p : ℝ) ↦ if p = 0 then (0 : EReal) else if p < 0 then ⊤ else ⊥ := by refine Measurable.piecewise (measurableSet_singleton _) measurable_const ?_ exact Measurable.piecewise measurableSet_Iio measurable_const measurable_const induction c with | bot => rwa [h1] | coe c => exact (measurable_id.const_mul _).coe_real_ereal | top => simp_rw [← neg_bot, neg_mul] apply Measurable.neg rwa [h1] instance : MeasurableMul₂ EReal := by refine ⟨measurable_of_real_real ?_ ?_ ?_ ?_ ?_⟩ · exact (measurable_fst.mul measurable_snd).coe_real_ereal · exact (measurable_const_mul _).comp measurable_coe_real_ereal · exact (measurable_const_mul _).comp measurable_coe_real_ereal · simp_rw [mul_comm _ ⊥] exact (measurable_const_mul _).comp measurable_coe_real_ereal · simp_rw [mul_comm _ ⊤] exact (measurable_const_mul _).comp measurable_coe_real_ereal end MeasurableMul end EReal /-- If a function `f : α → ℝ≥0` is measurable and the measure is σ-finite, then there exists spanning measurable sets with finite measure on which `f` is bounded. See also `StronglyMeasurable.exists_spanning_measurableSet_norm_le` for functions into normed groups. -/ theorem exists_spanning_measurableSet_le {f : α → ℝ≥0} (hf : Measurable f) (μ : Measure α) [SigmaFinite μ] : ∃ s : ℕ → Set α, (∀ n, MeasurableSet (s n) ∧ μ (s n) < ∞ ∧ ∀ x ∈ s n, f x ≤ n) ∧ ⋃ i, s i = Set.univ := by let sigma_finite_sets := spanningSets μ let norm_sets := fun n : ℕ => { x | f x ≤ n } have norm_sets_spanning : ⋃ n, norm_sets n = Set.univ := by ext1 x simp only [Set.mem_iUnion, Set.mem_univ, iff_true] exact exists_nat_ge (f x) let sets n := sigma_finite_sets n ∩ norm_sets n have h_meas : ∀ n, MeasurableSet (sets n) := by refine fun n => MeasurableSet.inter ?_ ?_ · exact measurableSet_spanningSets μ n · exact hf measurableSet_Iic have h_finite : ∀ n, μ (sets n) < ∞ := by refine fun n => (measure_mono Set.inter_subset_left).trans_lt ?_ exact measure_spanningSets_lt_top μ n refine ⟨sets, fun n => ⟨h_meas n, h_finite n, ?_⟩, ?_⟩ · exact fun x hx => hx.2 · have : ⋃ i, sigma_finite_sets i ∩ norm_sets i = (⋃ i, sigma_finite_sets i) ∩ ⋃ i, norm_sets i := by refine Set.iUnion_inter_of_monotone (monotone_spanningSets μ) fun i j hij x => ?_ simp only [norm_sets, Set.mem_setOf_eq] refine fun hif => hif.trans ?_ exact mod_cast hij rw [this, norm_sets_spanning, iUnion_spanningSets μ, Set.inter_univ] variable (μ : Measure ℝ) [IsFiniteMeasureOnCompacts μ] lemma tendsto_measure_Icc_nhdsWithin_right' (b : ℝ) : Tendsto (fun δ ↦ μ (Icc (b - δ) (b + δ))) (𝓝[>] (0 : ℝ)) (𝓝 (μ {b})) := by rw [Real.singleton_eq_inter_Icc] apply tendsto_measure_biInter_gt (fun r hr ↦ nullMeasurableSet_Icc) · intro r s _rpos hrs exact Icc_subset_Icc (by linarith) (by linarith) · exact ⟨1, zero_lt_one, isCompact_Icc.measure_ne_top⟩ lemma tendsto_measure_Icc_nhdsWithin_right (b : ℝ) : Tendsto (fun δ ↦ μ (Icc (b - δ) (b + δ))) (𝓝[≥] (0 : ℝ)) (𝓝 (μ {b})) := by simp only [← nhdsGT_sup_nhdsWithin_singleton, nhdsWithin_singleton, tendsto_sup, tendsto_measure_Icc_nhdsWithin_right' μ b, true_and, tendsto_pure_left] intro s hs simpa using mem_of_mem_nhds hs lemma tendsto_measure_Icc [NoAtoms μ] (b : ℝ) : Tendsto (fun δ ↦ μ (Icc (b - δ) (b + δ))) (𝓝 (0 : ℝ)) (𝓝 0) := by rw [← nhdsLT_sup_nhdsGE, tendsto_sup] constructor · apply tendsto_const_nhds.congr' filter_upwards [self_mem_nhdsWithin] with r (hr : r < 0) rw [Icc_eq_empty (by linarith), measure_empty] · simpa only [measure_singleton] using tendsto_measure_Icc_nhdsWithin_right μ b
Pointwise.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.GroupWithZero.Subgroup import Mathlib.Algebra.Ring.Subring.Basic import Mathlib.Algebra.Ring.Subsemiring.Pointwise /-! # Pointwise instances on `Subring`s This file provides the action `Subring.pointwiseMulAction` which matches the action of `mulActionSet`. This actions is available in the `Pointwise` locale. ## Implementation notes This file is almost identical to the file `Mathlib/Algebra/Ring/Subsemiring/Pointwise.lean`. Where possible, try to keep them in sync. -/ open Set variable {M R : Type*} namespace Subring section Monoid variable [Monoid M] [Ring R] [MulSemiringAction M R] /-- The action on a subring corresponding to applying the action to every element. This is available as an instance in the `Pointwise` locale. -/ protected def pointwiseMulAction : MulAction M (Subring R) where smul a S := S.map (MulSemiringAction.toRingHom _ _ a) one_smul S := (congr_arg (fun f => S.map f) (RingHom.ext <| one_smul M)).trans S.map_id mul_smul _ _ S := (congr_arg (fun f => S.map f) (RingHom.ext <| mul_smul _ _)).trans (S.map_map _ _).symm scoped[Pointwise] attribute [instance] Subring.pointwiseMulAction open Pointwise theorem pointwise_smul_def {a : M} (S : Subring R) : a • S = S.map (MulSemiringAction.toRingHom _ _ a) := rfl @[simp] theorem coe_pointwise_smul (m : M) (S : Subring R) : ↑(m • S) = m • (S : Set R) := rfl @[simp] theorem pointwise_smul_toAddSubgroup (m : M) (S : Subring R) : (m • S).toAddSubgroup = m • S.toAddSubgroup := rfl @[simp] theorem pointwise_smul_toSubsemiring (m : M) (S : Subring R) : (m • S).toSubsemiring = m • S.toSubsemiring := rfl theorem smul_mem_pointwise_smul (m : M) (r : R) (S : Subring R) : r ∈ S → m • r ∈ m • S := (Set.smul_mem_smul_set : _ → _ ∈ m • (S : Set R)) instance : CovariantClass M (Subring R) HSMul.hSMul LE.le := ⟨fun _ _ => image_mono⟩ theorem mem_smul_pointwise_iff_exists (m : M) (r : R) (S : Subring R) : r ∈ m • S ↔ ∃ s : R, s ∈ S ∧ m • s = r := (Set.mem_smul_set : r ∈ m • (S : Set R) ↔ _) @[simp] theorem smul_bot (a : M) : a • (⊥ : Subring R) = ⊥ := map_bot _ theorem smul_sup (a : M) (S T : Subring R) : a • (S ⊔ T) = a • S ⊔ a • T := map_sup _ _ _ theorem smul_closure (a : M) (s : Set R) : a • closure s = closure (a • s) := RingHom.map_closure _ _ instance pointwise_central_scalar [MulSemiringAction Mᵐᵒᵖ R] [IsCentralScalar M R] : IsCentralScalar M (Subring R) := ⟨fun _ S => (congr_arg fun f => S.map f) <| RingHom.ext <| op_smul_eq_smul _⟩ end Monoid section Group variable [Group M] [Ring R] [MulSemiringAction M R] open Pointwise @[simp] theorem smul_mem_pointwise_smul_iff {a : M} {S : Subring R} {x : R} : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff theorem mem_pointwise_smul_iff_inv_smul_mem {a : M} {S : Subring R} {x : R} : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem theorem mem_inv_pointwise_smul_iff {a : M} {S : Subring R} {x : R} : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff @[simp] theorem pointwise_smul_le_pointwise_smul_iff {a : M} {S T : Subring R} : a • S ≤ a • T ↔ S ≤ T := smul_set_subset_smul_set_iff theorem pointwise_smul_subset_iff {a : M} {S T : Subring R} : a • S ≤ T ↔ S ≤ a⁻¹ • T := smul_set_subset_iff_subset_inv_smul_set theorem subset_pointwise_smul_iff {a : M} {S T : Subring R} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_smul_set_iff /-! TODO: add `equivSMul` like we have for subgroup. -/ end Group section GroupWithZero variable [GroupWithZero M] [Ring R] [MulSemiringAction M R] open Pointwise @[simp] theorem smul_mem_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) (S : Subring R) (x : R) : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff₀ ha (S : Set R) x theorem mem_pointwise_smul_iff_inv_smul_mem₀ {a : M} (ha : a ≠ 0) (S : Subring R) (x : R) : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem₀ ha (S : Set R) x theorem mem_inv_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) (S : Subring R) (x : R) : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff₀ ha (S : Set R) x @[simp] theorem pointwise_smul_le_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) {S T : Subring R} : a • S ≤ a • T ↔ S ≤ T := smul_set_subset_smul_set_iff₀ ha theorem pointwise_smul_le_iff₀ {a : M} (ha : a ≠ 0) {S T : Subring R} : a • S ≤ T ↔ S ≤ a⁻¹ • T := smul_set_subset_iff₀ ha theorem le_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) {S T : Subring R} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_smul_set_iff₀ ha end GroupWithZero end Subring
Card.lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Kim Morrison -/ import Mathlib.GroupTheory.Coset.Basic import Mathlib.SetTheory.Cardinal.Finite /-! # Lagrange's theorem: the order of a subgroup divides the order of the group. * `Subgroup.card_subgroup_dvd_card`: Lagrange's theorem (for multiplicative groups); there is an analogous version for additive groups -/ assert_not_exists Field open scoped Pointwise variable {α : Type*} [Group α] {s : Subgroup α} namespace QuotientGroup @[to_additive] instance fintype [Fintype α] (s : Subgroup α) [DecidableRel (leftRel s).r] : Fintype (α ⧸ s) := Quotient.fintype (leftRel s) @[to_additive] instance fintypeQuotientRightRel [Fintype (α ⧸ s)] : Fintype (Quotient (QuotientGroup.rightRel s)) := .ofEquiv (α ⧸ s) (QuotientGroup.quotientRightRelEquivQuotientLeftRel s).symm variable (s) in @[to_additive] lemma card_quotient_rightRel [Fintype (α ⧸ s)] : Fintype.card (Quotient (QuotientGroup.rightRel s)) = Fintype.card (α ⧸ s) := Fintype.ofEquiv_card (QuotientGroup.quotientRightRelEquivQuotientLeftRel s).symm end QuotientGroup namespace Subgroup @[to_additive AddSubgroup.card_eq_card_quotient_mul_card_addSubgroup] theorem card_eq_card_quotient_mul_card_subgroup (s : Subgroup α) : Nat.card α = Nat.card (α ⧸ s) * Nat.card s := by rw [← Nat.card_prod]; exact Nat.card_congr Subgroup.groupEquivQuotientProdSubgroup @[to_additive] lemma card_mul_eq_card_subgroup_mul_card_quotient (s : Subgroup α) (t : Set α) : Nat.card (t * s : Set α) = Nat.card s * Nat.card (t.image (↑) : Set (α ⧸ s)) := by rw [← Nat.card_prod, Nat.card_congr] apply Equiv.trans _ (QuotientGroup.preimageMkEquivSubgroupProdSet _ _) rw [QuotientGroup.preimage_image_mk] convert Equiv.refl ↑(t * s) aesop (add simp [Set.mem_mul]) /-- **Lagrange's Theorem**: The order of a subgroup divides the order of its ambient group. -/ @[to_additive /-- **Lagrange's Theorem**: The order of an additive subgroup divides the order of its ambient additive group. -/] theorem card_subgroup_dvd_card (s : Subgroup α) : Nat.card s ∣ Nat.card α := by classical simp [card_eq_card_quotient_mul_card_subgroup s, @dvd_mul_left ℕ] @[to_additive] theorem card_quotient_dvd_card (s : Subgroup α) : Nat.card (α ⧸ s) ∣ Nat.card α := by simp [card_eq_card_quotient_mul_card_subgroup s, @dvd_mul_right ℕ] variable {H : Type*} [Group H] @[to_additive] theorem card_dvd_of_injective (f : α →* H) (hf : Function.Injective f) : Nat.card α ∣ Nat.card H := by classical calc Nat.card α = Nat.card (f.range : Subgroup H) := Nat.card_congr (Equiv.ofInjective f hf) _ ∣ Nat.card H := card_subgroup_dvd_card _ @[to_additive] theorem card_dvd_of_le {H K : Subgroup α} (hHK : H ≤ K) : Nat.card H ∣ Nat.card K := card_dvd_of_injective (inclusion hHK) (inclusion_injective hHK) @[to_additive] theorem card_comap_dvd_of_injective (K : Subgroup H) (f : α →* H) (hf : Function.Injective f) : Nat.card (K.comap f) ∣ Nat.card K := calc Nat.card (K.comap f) = Nat.card ((K.comap f).map f) := Nat.card_congr (equivMapOfInjective _ _ hf).toEquiv _ ∣ Nat.card K := card_dvd_of_le (map_comap_le _ _) end Subgroup
NormalForms.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.Tactic.Zify import Mathlib.Data.List.Sort import Mathlib.Tactic.Linarith import Mathlib.Tactic.NormNum.Ineq import Mathlib.Tactic.Ring.Basic /-! # Normal forms for morphisms in `SimplexCategoryGenRel`. In this file, we establish that `P_δ` and `P_σ` morphisms in `SimplexCategoryGenRel` each admits a normal form. In both cases, the normal forms are encoded as an integer `m`, and a strictly increasing lists of integers `[i₀,…,iₙ]` such that `iₖ ≤ m + k` for all `k`. We define a predicate `isAdmissible m : List ℕ → Prop` encoding this property. And provide some lemmas to help work with such lists. Normal forms for `P_σ` morphisms are encoded by `m`-admissible lists, in which case the list `[i₀,…,iₙ]` represents the morphism `σ iₙ ≫ ⋯ ≫ σ i₀ : .mk (m + n) ⟶ .mk n`. Normal forms for `P_δ` morphisms are encoded by `(m + 1)`-admissible lists, in which case the list `[i₀,…,iₙ]` represents the morphism `δ i₀ ≫ ⋯ ≫ δ iₙ : .mk n ⟶ .mk (m + n)`. The results in this file are to be treated as implementation-only, and they only serve as stepping stones towards proving that the canonical functor `toSimplexCategory : SimplexCategoryGenRel ⥤ SimplexCategory` is an equivalence. ## References: * [Kerodon Tag 04FQ](https://kerodon.net/tag/04FQ) * [Kerodon Tag 04FT](https://kerodon.net/tag/04FT) ## TODOs: - Show that every `P_σ` admits a unique normal form. - Show that every `P_δ` admits a unique normal form. -/ namespace SimplexCategoryGenRel section AdmissibleLists -- Impl. note: We are not bundling admissible lists as a subtype of `List ℕ` so that it remains -- easier to perform inductive constructions and proofs on such lists, and we instead bundle -- propositions asserting that various List constructions produce admissible lists. variable (m : ℕ) /-- A list of natural numbers [i₀, ⋯, iₙ]) is said to be `m`-admissible (for `m : ℕ`) if `i₀ < ⋯ < iₙ` and `iₖ ≤ m + k` for all `k`. -/ def IsAdmissible (L : List ℕ) : Prop := List.Sorted (· < ·) L ∧ ∀ (k : ℕ), (h : k < L.length) → L[k] ≤ m + k namespace IsAdmissible lemma nil : IsAdmissible m [] := by simp [IsAdmissible] variable {m} lemma sorted {L : List ℕ} (hL : IsAdmissible m L) : L.Sorted (· < ·) := hL.1 lemma le {L : List ℕ} (hL : IsAdmissible m L) : ∀ (k : ℕ), (h : k < L.length) → L[k] ≤ m + k := hL.2 /-- If `(a :: l)` is `m`-admissible then a is less than all elements of `l` -/ lemma head_lt (a : ℕ) (L : List ℕ) (hl : IsAdmissible m (a :: L)) : ∀ a' ∈ L, a < a' := fun i hi ↦ (List.sorted_cons.mp hl.sorted).left i hi /-- If `L` is a `(m + 1)`-admissible list, and `a` is natural number such that a ≤ m and a < L[0], then `a::L` is `m`-admissible -/ lemma cons (L : List ℕ) (hL : IsAdmissible (m + 1) L) (a : ℕ) (ha : a ≤ m) (ha' : (_ : 0 < L.length) → a < L[0]) : IsAdmissible m (a :: L) := by cases L with | nil => constructor <;> simp [ha] | cons head tail => simp only [List.length_cons, lt_add_iff_pos_left, add_pos_iff, Nat.lt_one_iff, pos_of_gt, or_true, List.getElem_cons_zero, forall_const] at ha' simp only [IsAdmissible, List.sorted_cons, List.mem_cons, forall_eq_or_imp] constructor <;> repeat constructor · exact ha' · rw [← List.forall_getElem] intro i hi exact ha'.trans <| (List.sorted_cons.mp hL.sorted).left tail[i] <| List.getElem_mem hi · exact List.sorted_cons.mp hL.sorted · rintro ⟨_ | _⟩ hi · simp [ha] · haveI := hL.le _ <| Nat.lt_of_succ_lt_succ hi rw [List.getElem_cons_succ] omega /-- The tail of an `m`-admissible list is (m+1)-admissible. -/ lemma tail (a : ℕ) (l : List ℕ) (h : IsAdmissible m (a::l)) : IsAdmissible (m + 1) l := by refine ⟨(List.sorted_cons.mp h.sorted).right, ?_⟩ intro k _ simpa [Nat.add_assoc, Nat.add_comm 1] using h.le (k + 1) (by simpa) /-- An element of a `m`-admissible list, as an element of the appropriate `Fin` -/ @[simps] def getElemAsFin {L : List ℕ} (hl : IsAdmissible m L) (k : ℕ) (hK : k < L.length) : Fin (m + k + 1) := Fin.mk L[k] <| Nat.le_iff_lt_add_one.mp (by simp [hl.le]) /-- The head of an `m`-admissible list. -/ @[simps!] def head (a : ℕ) (L : List ℕ) (hl : IsAdmissible m (a :: L)) : Fin (m + 1) := hl.getElemAsFin 0 (by simp) end IsAdmissible /-- The construction `simplicialInsert` describes inserting an element in a list of integer and moving it to its "right place" according to the simplicial relations. Somewhat miraculously, the algorithm is the same for the first or the fifth simplicial relations, making it "valid" when we treat the list as a normal form for a morphism satisfying `P_δ`, or for a morphism satisfying `P_σ`! This is similar in nature to `List.orderedInsert`, but note that we increment one of the element every time we perform an exchange, making it a different construction. -/ def simplicialInsert (a : ℕ) : List ℕ → List ℕ | [] => [a] | b :: l => if a < b then a :: b :: l else b :: simplicialInsert (a + 1) l /-- `simplicialInsert` just adds one to the length. -/ lemma simplicialInsert_length (a : ℕ) (L : List ℕ) : (simplicialInsert a L).length = L.length + 1 := by induction L generalizing a with | nil => rfl | cons head tail h_rec => dsimp only [simplicialInsert, List.length_cons] split_ifs with h <;> simp only [List.length_cons, h_rec (a + 1)] /-- `simplicialInsert` preserves admissibility -/ theorem simplicialInsert_isAdmissible (L : List ℕ) (hL : IsAdmissible (m + 1) L) (j : ℕ) (hj : j < m + 1) : IsAdmissible m <| simplicialInsert j L := by induction L generalizing j m with | nil => constructor <;> simp [simplicialInsert, j.le_of_lt_add_one hj] | cons a L h_rec => dsimp only [simplicialInsert] split_ifs with ha · exact .cons _ hL _ (j.le_of_lt_add_one hj) (fun _ ↦ ha) · refine IsAdmissible.cons _ ?_ _ (not_lt.mp ha |>.trans <| j.le_of_lt_add_one hj) ?_ · refine h_rec _ (.tail a L hL) _ (by simp [hj]) · rw [not_lt, Nat.le_iff_lt_add_one] at ha intro u cases L with | nil => simp [simplicialInsert, ha] | cons a' l' => dsimp only [simplicialInsert] split_ifs · exact ha · exact (List.sorted_cons_cons.mp hL.sorted).1 end AdmissibleLists end SimplexCategoryGenRel
Range.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, Kyle Miller -/ import Mathlib.Data.Fintype.EquivFin import Mathlib.Data.ULift /-! # Finiteness of `Set.range` ## Implementation notes Each result in this file should come in three forms: a `Fintype` instance, a `Finite` instance and a `Set.Finite` constructor. ## Tags finite sets -/ assert_not_exists OrderedRing MonoidWithZero open Set Function universe u v w x variable {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace Set /-! ### Fintype instances Every instance here should have a corresponding `Set.Finite` constructor in the next section. -/ section FintypeInstances instance fintypeRange [DecidableEq α] (f : ι → α) [Fintype (PLift ι)] : Fintype (range f) := Fintype.ofFinset (Finset.univ.image <| f ∘ PLift.down) <| by simp end FintypeInstances end Set /-! ### Finite instances There is seemingly some overlap between the following instances and the `Fintype` instances in `Data.Set.Finite`. While every `Fintype` instance gives a `Finite` instance, those instances that depend on `Fintype` or `Decidable` instances need an additional `Finite` instance to be able to generally apply. Some set instances do not appear here since they are consequences of others, for example `Subtype.Finite` for subsets of a finite type. -/ namespace Finite.Set instance finite_range (f : ι → α) [Finite ι] : Finite (range f) := by classical haveI := Fintype.ofFinite (PLift ι) infer_instance instance finite_replacement [Finite α] (f : α → β) : Finite {f x | x : α} := Finite.Set.finite_range f end Finite.Set namespace Set /-! ### Constructors for `Set.Finite` Every constructor here should have a corresponding `Fintype` instance in the previous section (or in the `Fintype` module). The implementation of these constructors ideally should be no more than `Set.toFinite`, after possibly setting up some `Fintype` and classical `Decidable` instances. -/ section SetFiniteConstructors theorem finite_range (f : ι → α) [Finite ι] : (range f).Finite := toFinite _ theorem Finite.dependent_image {s : Set α} (hs : s.Finite) (F : ∀ i ∈ s, β) : {y : β | ∃ x hx, F x hx = y}.Finite := by have := hs.to_subtype simpa [range] using finite_range fun x : s => F x x.2 end SetFiniteConstructors end Set
Basic.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Group.Torsion import Mathlib.Algebra.Notation.Pi.Basic import Mathlib.Data.FunLike.Basic import Mathlib.Logic.Function.Iterate import Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.Set import Mathlib.Util.AssertExists import Mathlib.Logic.Nontrivial.Basic /-! # Type tags that turn additive structures into multiplicative, and vice versa We define two type tags: * `Additive α`: turns any multiplicative structure on `α` into the corresponding additive structure on `Additive α`; * `Multiplicative α`: turns any additive structure on `α` into the corresponding multiplicative structure on `Multiplicative α`. We also define instances `Additive.*` and `Multiplicative.*` that actually transfer the structures. ## See also This file is similar to `Order.Synonym`. -/ assert_not_exists MonoidWithZero DenselyOrdered MonoidHom Finite universe u v variable {α : Type u} {β : Type v} /-- If `α` carries some multiplicative structure, then `Additive α` carries the corresponding additive structure. -/ def Additive (α : Type*) := α /-- If `α` carries some additive structure, then `Multiplicative α` carries the corresponding multiplicative structure. -/ def Multiplicative (α : Type*) := α namespace Additive /-- Reinterpret `x : α` as an element of `Additive α`. -/ def ofMul : α ≃ Additive α := ⟨fun x => x, fun x => x, fun _ => rfl, fun _ => rfl⟩ /-- Reinterpret `x : Additive α` as an element of `α`. -/ def toMul : Additive α ≃ α := ofMul.symm @[simp] theorem ofMul_symm_eq : (@ofMul α).symm = toMul := rfl @[simp] theorem toMul_symm_eq : (@toMul α).symm = ofMul := rfl @[ext] lemma ext {a b : Additive α} (hab : a.toMul = b.toMul) : a = b := hab @[simp] protected lemma «forall» {p : Additive α → Prop} : (∀ a, p a) ↔ ∀ a, p (ofMul a) := Iff.rfl @[simp] protected lemma «exists» {p : Additive α → Prop} : (∃ a, p a) ↔ ∃ a, p (ofMul a) := Iff.rfl /-- Recursion principle for `Additive`, supported by `cases` and `induction`. -/ @[elab_as_elim, cases_eliminator, induction_eliminator] def rec {motive : Additive α → Sort*} (ofMul : ∀ a, motive (ofMul a)) : ∀ a, motive a := fun a => ofMul (a.toMul) end Additive namespace Multiplicative /-- Reinterpret `x : α` as an element of `Multiplicative α`. -/ def ofAdd : α ≃ Multiplicative α := ⟨fun x => x, fun x => x, fun _ => rfl, fun _ => rfl⟩ /-- Reinterpret `x : Multiplicative α` as an element of `α`. -/ def toAdd : Multiplicative α ≃ α := ofAdd.symm @[simp] theorem ofAdd_symm_eq : (@ofAdd α).symm = toAdd := rfl @[simp] theorem toAdd_symm_eq : (@toAdd α).symm = ofAdd := rfl @[ext] lemma ext {a b : Multiplicative α} (hab : a.toAdd = b.toAdd) : a = b := hab @[simp] protected lemma «forall» {p : Multiplicative α → Prop} : (∀ a, p a) ↔ ∀ a, p (ofAdd a) := Iff.rfl @[simp] protected lemma «exists» {p : Multiplicative α → Prop} : (∃ a, p a) ↔ ∃ a, p (ofAdd a) := Iff.rfl /-- Recursion principle for `Multiplicative`, supported by `cases` and `induction`. -/ @[elab_as_elim, cases_eliminator, induction_eliminator] def rec {motive : Multiplicative α → Sort*} (ofAdd : ∀ a, motive (ofAdd a)) : ∀ a, motive a := fun a => ofAdd (a.toAdd) end Multiplicative open Additive (ofMul toMul) open Multiplicative (ofAdd toAdd) @[simp] theorem toAdd_ofAdd (x : α) : (ofAdd x).toAdd = x := rfl @[simp] theorem ofAdd_toAdd (x : Multiplicative α) : ofAdd x.toAdd = x := rfl @[simp] theorem toMul_ofMul (x : α) : (ofMul x).toMul = x := rfl @[simp] theorem ofMul_toMul (x : Additive α) : ofMul x.toMul = x := rfl instance [Subsingleton α] : Subsingleton (Additive α) := toMul.injective.subsingleton instance [Subsingleton α] : Subsingleton (Multiplicative α) := toAdd.injective.subsingleton instance [Inhabited α] : Inhabited (Additive α) := ⟨ofMul default⟩ instance [Inhabited α] : Inhabited (Multiplicative α) := ⟨ofAdd default⟩ instance [Unique α] : Unique (Additive α) := toMul.unique instance [Unique α] : Unique (Multiplicative α) := toAdd.unique instance [h : DecidableEq α] : DecidableEq (Multiplicative α) := h instance [h : DecidableEq α] : DecidableEq (Additive α) := h instance Additive.instNontrivial [Nontrivial α] : Nontrivial (Additive α) := ofMul.injective.nontrivial instance Multiplicative.instNontrivial [Nontrivial α] : Nontrivial (Multiplicative α) := ofAdd.injective.nontrivial instance Additive.add [Mul α] : Add (Additive α) where add x y := ofMul (x.toMul * y.toMul) instance Multiplicative.mul [Add α] : Mul (Multiplicative α) where mul x y := ofAdd (x.toAdd + y.toAdd) @[simp] theorem ofAdd_add [Add α] (x y : α) : ofAdd (x + y) = ofAdd x * ofAdd y := rfl @[simp] theorem toAdd_mul [Add α] (x y : Multiplicative α) : (x * y).toAdd = x.toAdd + y.toAdd := rfl @[simp] theorem ofMul_mul [Mul α] (x y : α) : ofMul (x * y) = ofMul x + ofMul y := rfl @[simp] theorem toMul_add [Mul α] (x y : Additive α) : (x + y).toMul = x.toMul * y.toMul := rfl instance Additive.addSemigroup [Semigroup α] : AddSemigroup (Additive α) := { Additive.add with add_assoc := @mul_assoc α _ } instance Multiplicative.semigroup [AddSemigroup α] : Semigroup (Multiplicative α) := { Multiplicative.mul with mul_assoc := @add_assoc α _ } instance Additive.addCommSemigroup [CommSemigroup α] : AddCommSemigroup (Additive α) := { Additive.addSemigroup with add_comm := @mul_comm α _ } instance Multiplicative.commSemigroup [AddCommSemigroup α] : CommSemigroup (Multiplicative α) := { Multiplicative.semigroup with mul_comm := @add_comm α _ } instance Additive.isLeftCancelAdd [Mul α] [IsLeftCancelMul α] : IsLeftCancelAdd (Additive α) := ⟨@mul_left_cancel α _ _⟩ instance Multiplicative.isLeftCancelMul [Add α] [IsLeftCancelAdd α] : IsLeftCancelMul (Multiplicative α) := ⟨@add_left_cancel α _ _⟩ instance Additive.isRightCancelAdd [Mul α] [IsRightCancelMul α] : IsRightCancelAdd (Additive α) := ⟨fun _ _ _ ↦ @mul_right_cancel α _ _ _ _ _⟩ instance Multiplicative.isRightCancelMul [Add α] [IsRightCancelAdd α] : IsRightCancelMul (Multiplicative α) := ⟨fun _ _ _ ↦ @add_right_cancel α _ _ _ _ _⟩ instance Additive.isCancelAdd [Mul α] [IsCancelMul α] : IsCancelAdd (Additive α) := ⟨⟩ instance Multiplicative.isCancelMul [Add α] [IsCancelAdd α] : IsCancelMul (Multiplicative α) := ⟨⟩ instance Additive.addLeftCancelSemigroup [LeftCancelSemigroup α] : AddLeftCancelSemigroup (Additive α) := { Additive.addSemigroup, Additive.isLeftCancelAdd with } instance Multiplicative.leftCancelSemigroup [AddLeftCancelSemigroup α] : LeftCancelSemigroup (Multiplicative α) := { Multiplicative.semigroup, Multiplicative.isLeftCancelMul with } instance Additive.addRightCancelSemigroup [RightCancelSemigroup α] : AddRightCancelSemigroup (Additive α) := { Additive.addSemigroup, Additive.isRightCancelAdd with } instance Multiplicative.rightCancelSemigroup [AddRightCancelSemigroup α] : RightCancelSemigroup (Multiplicative α) := { Multiplicative.semigroup, Multiplicative.isRightCancelMul with } instance [One α] : Zero (Additive α) := ⟨Additive.ofMul 1⟩ @[simp] theorem ofMul_one [One α] : @Additive.ofMul α 1 = 0 := rfl @[simp] theorem ofMul_eq_zero {A : Type*} [One A] {x : A} : Additive.ofMul x = 0 ↔ x = 1 := Iff.rfl @[simp] theorem toMul_zero [One α] : (0 : Additive α).toMul = 1 := rfl @[simp] lemma toMul_eq_one {α : Type*} [One α] {x : Additive α} : x.toMul = 1 ↔ x = 0 := Iff.rfl instance [Zero α] : One (Multiplicative α) := ⟨Multiplicative.ofAdd 0⟩ @[simp] theorem ofAdd_zero [Zero α] : @Multiplicative.ofAdd α 0 = 1 := rfl @[simp] theorem ofAdd_eq_one {A : Type*} [Zero A] {x : A} : Multiplicative.ofAdd x = 1 ↔ x = 0 := Iff.rfl @[simp] theorem toAdd_one [Zero α] : (1 : Multiplicative α).toAdd = 0 := rfl @[simp] lemma toAdd_eq_zero {α : Type*} [Zero α] {x : Multiplicative α} : x.toAdd = 0 ↔ x = 1 := Iff.rfl instance Additive.addZeroClass [MulOneClass α] : AddZeroClass (Additive α) where zero := 0 add := (· + ·) zero_add := @one_mul α _ add_zero := @mul_one α _ instance Multiplicative.mulOneClass [AddZeroClass α] : MulOneClass (Multiplicative α) where one := 1 mul := (· * ·) one_mul := @zero_add α _ mul_one := @add_zero α _ instance Additive.addMonoid [h : Monoid α] : AddMonoid (Additive α) := { Additive.addZeroClass, Additive.addSemigroup with nsmul := @Monoid.npow α h nsmul_zero := @Monoid.npow_zero α h nsmul_succ := @Monoid.npow_succ α h } instance Multiplicative.monoid [h : AddMonoid α] : Monoid (Multiplicative α) := { Multiplicative.mulOneClass, Multiplicative.semigroup with npow := @AddMonoid.nsmul α h npow_zero := @AddMonoid.nsmul_zero α h npow_succ := @AddMonoid.nsmul_succ α h } @[simp] theorem ofMul_pow [Monoid α] (n : ℕ) (a : α) : ofMul (a ^ n) = n • ofMul a := rfl @[simp] theorem toMul_nsmul [Monoid α] (n : ℕ) (a : Additive α) : (n • a).toMul = a.toMul ^ n := rfl @[simp] theorem ofAdd_nsmul [AddMonoid α] (n : ℕ) (a : α) : ofAdd (n • a) = ofAdd a ^ n := rfl @[simp] theorem toAdd_pow [AddMonoid α] (a : Multiplicative α) (n : ℕ) : (a ^ n).toAdd = n • a.toAdd := rfl instance Additive.addLeftCancelMonoid [LeftCancelMonoid α] : AddLeftCancelMonoid (Additive α) := { Additive.addMonoid, Additive.addLeftCancelSemigroup with } instance Multiplicative.leftCancelMonoid [AddLeftCancelMonoid α] : LeftCancelMonoid (Multiplicative α) := { Multiplicative.monoid, Multiplicative.leftCancelSemigroup with } instance Additive.addRightCancelMonoid [RightCancelMonoid α] : AddRightCancelMonoid (Additive α) := { Additive.addMonoid, Additive.addRightCancelSemigroup with } instance Multiplicative.rightCancelMonoid [AddRightCancelMonoid α] : RightCancelMonoid (Multiplicative α) := { Multiplicative.monoid, Multiplicative.rightCancelSemigroup with } instance Additive.addCommMonoid [CommMonoid α] : AddCommMonoid (Additive α) := { Additive.addMonoid, Additive.addCommSemigroup with } instance Multiplicative.commMonoid [AddCommMonoid α] : CommMonoid (Multiplicative α) := { Multiplicative.monoid, Multiplicative.commSemigroup with } instance Additive.instAddCancelCommMonoid [CancelCommMonoid α] : AddCancelCommMonoid (Additive α) where instance Multiplicative.instCancelCommMonoid [AddCancelCommMonoid α] : CancelCommMonoid (Multiplicative α) where instance Additive.neg [Inv α] : Neg (Additive α) := ⟨fun x => ofAdd x.toMul⁻¹⟩ @[simp] theorem ofMul_inv [Inv α] (x : α) : ofMul x⁻¹ = -ofMul x := rfl @[simp] theorem toMul_neg [Inv α] (x : Additive α) : (-x).toMul = x.toMul⁻¹ := rfl instance Multiplicative.inv [Neg α] : Inv (Multiplicative α) := ⟨fun x => ofMul (-x.toAdd)⟩ @[simp] theorem ofAdd_neg [Neg α] (x : α) : ofAdd (-x) = (ofAdd x)⁻¹ := rfl @[simp] theorem toAdd_inv [Neg α] (x : Multiplicative α) : x⁻¹.toAdd = -x.toAdd := rfl instance Additive.sub [Div α] : Sub (Additive α) where sub x y := ofMul (x.toMul / y.toMul) instance Multiplicative.div [Sub α] : Div (Multiplicative α) where div x y := ofAdd (x.toAdd - y.toAdd) @[simp] theorem ofAdd_sub [Sub α] (x y : α) : ofAdd (x - y) = ofAdd x / ofAdd y := rfl @[simp] theorem toAdd_div [Sub α] (x y : Multiplicative α) : (x / y).toAdd = x.toAdd - y.toAdd := rfl @[simp] theorem ofMul_div [Div α] (x y : α) : ofMul (x / y) = ofMul x - ofMul y := rfl @[simp] theorem toMul_sub [Div α] (x y : Additive α) : (x - y).toMul = x.toMul / y.toMul := rfl instance Additive.involutiveNeg [InvolutiveInv α] : InvolutiveNeg (Additive α) := { Additive.neg with neg_neg := @inv_inv α _ } instance Multiplicative.involutiveInv [InvolutiveNeg α] : InvolutiveInv (Multiplicative α) := { Multiplicative.inv with inv_inv := @neg_neg α _ } instance Additive.subNegMonoid [DivInvMonoid α] : SubNegMonoid (Additive α) := { Additive.neg, Additive.sub, Additive.addMonoid with sub_eq_add_neg := @div_eq_mul_inv α _ zsmul := @DivInvMonoid.zpow α _ zsmul_zero' := @DivInvMonoid.zpow_zero' α _ zsmul_succ' := @DivInvMonoid.zpow_succ' α _ zsmul_neg' := @DivInvMonoid.zpow_neg' α _ } instance Multiplicative.divInvMonoid [SubNegMonoid α] : DivInvMonoid (Multiplicative α) := { Multiplicative.inv, Multiplicative.div, Multiplicative.monoid with div_eq_mul_inv := @sub_eq_add_neg α _ zpow := @SubNegMonoid.zsmul α _ zpow_zero' := @SubNegMonoid.zsmul_zero' α _ zpow_succ' := @SubNegMonoid.zsmul_succ' α _ zpow_neg' := @SubNegMonoid.zsmul_neg' α _ } @[simp] theorem ofMul_zpow [DivInvMonoid α] (z : ℤ) (a : α) : ofMul (a ^ z) = z • ofMul a := rfl @[simp] theorem toMul_zsmul [DivInvMonoid α] (z : ℤ) (a : Additive α) : (z • a).toMul = a.toMul ^ z := rfl @[simp] theorem ofAdd_zsmul [SubNegMonoid α] (z : ℤ) (a : α) : ofAdd (z • a) = ofAdd a ^ z := rfl @[simp] theorem toAdd_zpow [SubNegMonoid α] (a : Multiplicative α) (z : ℤ) : (a ^ z).toAdd = z • a.toAdd := rfl instance Additive.subtractionMonoid [DivisionMonoid α] : SubtractionMonoid (Additive α) := { Additive.subNegMonoid, Additive.involutiveNeg with neg_add_rev := @mul_inv_rev α _ neg_eq_of_add := @inv_eq_of_mul_eq_one_right α _ } instance Multiplicative.divisionMonoid [SubtractionMonoid α] : DivisionMonoid (Multiplicative α) := { Multiplicative.divInvMonoid, Multiplicative.involutiveInv with mul_inv_rev := @neg_add_rev α _ inv_eq_of_mul := @neg_eq_of_add_eq_zero_right α _ } instance Additive.subtractionCommMonoid [DivisionCommMonoid α] : SubtractionCommMonoid (Additive α) := { Additive.subtractionMonoid, Additive.addCommSemigroup with } instance Multiplicative.divisionCommMonoid [SubtractionCommMonoid α] : DivisionCommMonoid (Multiplicative α) := { Multiplicative.divisionMonoid, Multiplicative.commSemigroup with } instance Additive.addGroup [Group α] : AddGroup (Additive α) := { Additive.subNegMonoid with neg_add_cancel := @inv_mul_cancel α _ } instance Multiplicative.group [AddGroup α] : Group (Multiplicative α) := { Multiplicative.divInvMonoid with inv_mul_cancel := @neg_add_cancel α _ } instance Additive.addCommGroup [CommGroup α] : AddCommGroup (Additive α) := { Additive.addGroup, Additive.addCommMonoid with } instance Multiplicative.commGroup [AddCommGroup α] : CommGroup (Multiplicative α) := { Multiplicative.group, Multiplicative.commMonoid with } instance [Monoid α] [IsMulTorsionFree α] : IsAddTorsionFree (Additive α) where nsmul_right_injective _ := pow_left_injective (M := α) instance [AddMonoid α] [IsAddTorsionFree α] : IsMulTorsionFree (Multiplicative α) where pow_left_injective _ := nsmul_right_injective (M := α) /-- If `α` has some multiplicative structure and coerces to a function, then `Additive α` should also coerce to the same function. This allows `Additive` to be used on bundled function types with a multiplicative structure, which is often used for composition, without affecting the behavior of the function itself. -/ instance Additive.coeToFun {α : Type*} {β : α → Sort*} [CoeFun α β] : CoeFun (Additive α) fun a => β a.toMul := ⟨fun a => CoeFun.coe a.toMul⟩ /-- If `α` has some additive structure and coerces to a function, then `Multiplicative α` should also coerce to the same function. This allows `Multiplicative` to be used on bundled function types with an additive structure, which is often used for composition, without affecting the behavior of the function itself. -/ instance Multiplicative.coeToFun {α : Type*} {β : α → Sort*} [CoeFun α β] : CoeFun (Multiplicative α) fun a => β a.toAdd := ⟨fun a => CoeFun.coe a.toAdd⟩ lemma Pi.mulSingle_multiplicativeOfAdd_eq {ι : Type*} [DecidableEq ι] {M : ι → Type*} [(i : ι) → AddMonoid (M i)] (i : ι) (a : M i) (j : ι) : Pi.mulSingle (M := fun i ↦ Multiplicative (M i)) i (.ofAdd a) j = .ofAdd (Pi.single i a j) := by rcases eq_or_ne j i with rfl | h · simp only [mulSingle_eq_same, single_eq_same] · simp only [mulSingle, ne_eq, h, not_false_eq_true, Function.update_of_ne, one_apply, single, zero_apply, ofAdd_zero] lemma Pi.single_additiveOfMul_eq {ι : Type*} [DecidableEq ι] {M : ι → Type*} [(i : ι) → Monoid (M i)] (i : ι) (a : M i) (j : ι) : Pi.single (M := fun i ↦ Additive (M i)) i (.ofMul a) j = .ofMul (Pi.mulSingle i a j) := by rcases eq_or_ne j i with rfl | h · simp only [mulSingle_eq_same, single_eq_same] · simp only [single, ne_eq, h, not_false_eq_true, Function.update_of_ne, zero_apply, mulSingle, one_apply, ofMul_one]
Distinguished.lean
/- Copyright (c) 2024 Nailin Guan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nailin Guan -/ import Mathlib.RingTheory.Polynomial.Eisenstein.Basic import Mathlib.RingTheory.PowerSeries.Order /-! # Distinguished polynomial In this file we define the predicate `Polynomial.IsDistinguishedAt` and develop the most basic lemmas about it. -/ open scoped Polynomial open PowerSeries Ideal Quotient variable {R : Type*} [CommRing R] /-- Given an ideal `I` of a commutative ring `R`, we say that a polynomial `f : R[X]` is *Distinguished at `I`* if `f` is monic and `IsWeaklyEisensteinAt I`. i.e. `f` is of the form `xⁿ + a₁xⁿ⁻¹ + ⋯ + aₙ` with `aᵢ ∈ I` for all `i`. -/ structure Polynomial.IsDistinguishedAt (f : R[X]) (I : Ideal R) : Prop extends f.IsWeaklyEisensteinAt I where monic : f.Monic namespace Polynomial.IsDistinguishedAt lemma mul {f f' : R[X]} {I : Ideal R} (hf : f.IsDistinguishedAt I) (hf' : f'.IsDistinguishedAt I) : (f * f').IsDistinguishedAt I := ⟨hf.toIsWeaklyEisensteinAt.mul hf'.toIsWeaklyEisensteinAt, hf.monic.mul hf'.monic⟩ lemma map_eq_X_pow {f : R[X]} {I : Ideal R} (distinguish : f.IsDistinguishedAt I) : f.map (Ideal.Quotient.mk I) = Polynomial.X ^ f.natDegree := by ext i by_cases ne : i = f.natDegree · simp [ne, distinguish.monic] · rcases lt_or_gt_of_ne ne with lt|gt · simpa [ne, eq_zero_iff_mem] using (distinguish.mem lt) · simp [ne, Polynomial.coeff_eq_zero_of_natDegree_lt gt] @[deprecated (since := "2025-04-27")] alias _root_.IsDistinguishedAt.map_eq_X_pow := map_eq_X_pow section degree_eq_order_map variable {I : Ideal R} (f h : R⟦X⟧) {g : R[X]} lemma map_ne_zero_of_eq_mul (distinguish : g.IsDistinguishedAt I) (notMem : PowerSeries.constantCoeff R h ∉ I) (eq : f = g * h) : f.map (Ideal.Quotient.mk I) ≠ 0 := fun H ↦ by have mapf : f.map (Ideal.Quotient.mk I) = (Polynomial.X ^ g.natDegree : (R ⧸ I)[X]) * h.map (Ideal.Quotient.mk I) := by simp [← map_eq_X_pow distinguish, eq] apply_fun PowerSeries.coeff _ g.natDegree at H simp [mapf, PowerSeries.coeff_X_pow_mul', eq_zero_iff_mem, notMem] at H lemma degree_eq_coe_lift_order_map (distinguish : g.IsDistinguishedAt I) (notMem : PowerSeries.constantCoeff R h ∉ I) (eq : f = g * h) : g.degree = (f.map (Ideal.Quotient.mk I)).order.lift (order_finite_iff_ne_zero.2 (distinguish.map_ne_zero_of_eq_mul f h notMem eq)) := by have : Nontrivial R := _root_.nontrivial_iff.mpr ⟨0, PowerSeries.constantCoeff R h, ne_of_mem_of_not_mem I.zero_mem notMem⟩ rw [Polynomial.degree_eq_natDegree distinguish.monic.ne_zero, Nat.cast_inj, ← ENat.coe_inj, ENat.coe_lift, Eq.comm, PowerSeries.order_eq_nat] have mapf : f.map (Ideal.Quotient.mk I) = (Polynomial.X ^ g.natDegree : (R ⧸ I)[X]) * h.map (Ideal.Quotient.mk I) := by simp [← map_eq_X_pow distinguish, eq] constructor · simp [mapf, PowerSeries.coeff_X_pow_mul', eq_zero_iff_mem, notMem] · intro i hi simp [mapf, PowerSeries.coeff_X_pow_mul', hi] @[deprecated (since := "2025-04-27")] alias _root_.IsDistinguishedAt.degree_eq_order_map := degree_eq_coe_lift_order_map @[deprecated (since := "2025-05-19")] alias degree_eq_order_map := degree_eq_coe_lift_order_map lemma coe_natDegree_eq_order_map (distinguish : g.IsDistinguishedAt I) (notMem : PowerSeries.constantCoeff R h ∉ I) (eq : f = g * h) : g.natDegree = (f.map (Ideal.Quotient.mk I)).order := by rw [natDegree, distinguish.degree_eq_coe_lift_order_map f h notMem eq] exact ENat.coe_lift _ <| order_finite_iff_ne_zero.2 <| distinguish.map_ne_zero_of_eq_mul f h notMem eq end degree_eq_order_map end Polynomial.IsDistinguishedAt
LocallySmall.lean
/- Copyright (c) 2024 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.CategoryTheory.Limits.Preserves.Ulift import Mathlib.CategoryTheory.Limits.IndYoneda import Mathlib.CategoryTheory.Limits.Indization.IndObject /-! # There are only `v`-many natural transformations between Ind-objects We provide the instance `LocallySmall.{v} (FullSubcategory (IsIndObject (C := C)))`, which will serve as the basis for our definition of the category of Ind-objects. ## Future work The equivalence established here serves as the basis for a well-known calculation of hom-sets of ind-objects as a limit of a colimit. -/ open CategoryTheory Limits Opposite universe v v₁ v₂ u u₁ u₂ variable {C : Type u} [Category.{v} C] namespace CategoryTheory section variable {I : Type u₁} [Category.{v₁} I] [HasColimitsOfShape I (Type v)] [HasLimitsOfShape Iᵒᵖ (Type v)] variable {J : Type u₂} [Category.{v₂} J] [HasLimitsOfShape Iᵒᵖ (Type (max u v))] variable (F : I ⥤ C) (G : Cᵒᵖ ⥤ Type v) /-- Variant of `colimitYonedaHomIsoLimitOp`: natural transformations with domain `colimit (F ⋙ yoneda)` are equivalent to a limit in a lower universe. -/ noncomputable def colimitYonedaHomEquiv : (colimit (F ⋙ yoneda) ⟶ G) ≃ limit (F.op ⋙ G) := Equiv.symm <| Equiv.ulift.symm.trans <| Equiv.symm <| Iso.toEquiv <| calc (colimit (F ⋙ yoneda) ⟶ G) ≅ limit (F.op ⋙ G ⋙ uliftFunctor.{u}) := colimitYonedaHomIsoLimitOp _ _ _ ≅ limit ((F.op ⋙ G) ⋙ uliftFunctor.{u}) := HasLimit.isoOfNatIso (Functor.associator _ _ _).symm _ ≅ uliftFunctor.{u}.obj (limit (F.op ⋙ G)) := (preservesLimitIso _ _).symm @[simp] theorem colimitYonedaHomEquiv_π_apply (η : colimit (F ⋙ yoneda) ⟶ G) (i : Iᵒᵖ) : limit.π (F.op ⋙ G) i (colimitYonedaHomEquiv F G η) = η.app (op (F.obj i.unop)) ((colimit.ι (F ⋙ yoneda) i.unop).app _ (𝟙 _)) := by simp only [Functor.comp_obj, Functor.op_obj, colimitYonedaHomEquiv, uliftFunctor_obj, Iso.trans_def, Iso.trans_assoc, Iso.toEquiv_comp, Equiv.symm_trans_apply, Equiv.symm_symm, Equiv.trans_apply, Iso.toEquiv_fun, Iso.symm_hom, Equiv.ulift_apply] have (a : _) := congrArg ULift.down (congrFun (preservesLimitIso_inv_π uliftFunctor.{u, v} (F.op ⋙ G) i) a) dsimp at this rw [this, ← types_comp_apply (HasLimit.isoOfNatIso _).hom (limit.π _ _), HasLimit.isoOfNatIso_hom_π] simp instance : Small.{v} (colimit (F ⋙ yoneda) ⟶ G) where equiv_small := ⟨_, ⟨colimitYonedaHomEquiv F G⟩⟩ end instance : LocallySmall.{v} (ObjectProperty.FullSubcategory (IsIndObject (C := C))) where hom_small X Y := by obtain ⟨⟨P⟩⟩ := X.2 obtain ⟨⟨Q⟩⟩ := Y.2 let e₁ := IsColimit.coconePointUniqueUpToIso (P.isColimit) (colimit.isColimit _) let e₂ := IsColimit.coconePointUniqueUpToIso (Q.isColimit) (colimit.isColimit _) let e₃ := Iso.homCongr e₁ e₂ dsimp only [colimit.cocone_x] at e₃ exact small_map e₃ end CategoryTheory
Embedding.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.MeasureTheory.MeasurableSpace.Constructions import Mathlib.Tactic.FunProp /-! # Measurable embeddings and equivalences A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. ## Main definitions * `MeasurableEmbedding`: a map `f : α → β` is called a *measurable embedding* if it is injective, measurable, and sends measurable sets to measurable sets. * `MeasurableEquiv`: an equivalence `α ≃ β` is a *measurable equivalence* if its forward and inverse functions are measurable. We prove a multitude of elementary lemmas about these, and one more substantial theorem: * `MeasurableEmbedding.schroederBernstein`: the **measurable Schröder-Bernstein Theorem**: given measurable embeddings `α → β` and `β → α`, we can find a measurable equivalence `α ≃ᵐ β`. ## Notation * We write `α ≃ᵐ β` for measurable equivalences between the measurable spaces `α` and `β`. This should not be confused with `≃ₘ` which is used for diffeomorphisms between manifolds. ## Tags measurable equivalence, measurable embedding -/ open Set Function Equiv MeasureTheory universe uι variable {α β γ δ δ' : Type*} {ι : Sort uι} {s t u : Set α} /-- A map `f : α → β` is called a *measurable embedding* if it is injective, measurable, and sends measurable sets to measurable sets. The latter assumption can be replaced with “`f` has measurable inverse `g : Set.range f → α`”, see `MeasurableEmbedding.measurable_rangeSplitting`, `MeasurableEmbedding.of_measurable_inverse_range`, and `MeasurableEmbedding.of_measurable_inverse`. One more interpretation: `f` is a measurable embedding if it defines a measurable equivalence to its range and the range is a measurable set. One implication is formalized as `MeasurableEmbedding.equivRange`; the other one follows from `MeasurableEquiv.measurableEmbedding`, `MeasurableEmbedding.subtype_coe`, and `MeasurableEmbedding.comp`. -/ structure MeasurableEmbedding [MeasurableSpace α] [MeasurableSpace β] (f : α → β) : Prop where /-- A measurable embedding is injective. -/ protected injective : Injective f /-- A measurable embedding is a measurable function. -/ protected measurable : Measurable f /-- The image of a measurable set under a measurable embedding is a measurable set. -/ protected measurableSet_image' : ∀ ⦃s⦄, MeasurableSet s → MeasurableSet (f '' s) attribute [fun_prop] MeasurableEmbedding.measurable namespace MeasurableEmbedding variable {mα : MeasurableSpace α} [MeasurableSpace β] [MeasurableSpace γ] {f : α → β} {g : β → γ} theorem measurableSet_image (hf : MeasurableEmbedding f) : MeasurableSet (f '' s) ↔ MeasurableSet s := ⟨fun h => by simpa only [hf.injective.preimage_image] using hf.measurable h, fun h => hf.measurableSet_image' h⟩ theorem id : MeasurableEmbedding (id : α → α) := ⟨injective_id, measurable_id, fun s hs => by rwa [image_id]⟩ theorem comp (hg : MeasurableEmbedding g) (hf : MeasurableEmbedding f) : MeasurableEmbedding (g ∘ f) := ⟨hg.injective.comp hf.injective, hg.measurable.comp hf.measurable, fun s hs => by rwa [image_comp, hg.measurableSet_image, hf.measurableSet_image]⟩ theorem subtype_coe (hs : MeasurableSet s) : MeasurableEmbedding ((↑) : s → α) where injective := Subtype.coe_injective measurable := measurable_subtype_coe measurableSet_image' := fun _ => MeasurableSet.subtype_image hs theorem measurableSet_range (hf : MeasurableEmbedding f) : MeasurableSet (range f) := by rw [← image_univ] exact hf.measurableSet_image' MeasurableSet.univ theorem measurableSet_preimage (hf : MeasurableEmbedding f) {s : Set β} : MeasurableSet (f ⁻¹' s) ↔ MeasurableSet (s ∩ range f) := by rw [← image_preimage_eq_inter_range, hf.measurableSet_image] theorem measurable_rangeSplitting (hf : MeasurableEmbedding f) : Measurable (rangeSplitting f) := fun s hs => by rwa [preimage_rangeSplitting hf.injective, ← (subtype_coe hf.measurableSet_range).measurableSet_image, ← image_comp, coe_comp_rangeFactorization, hf.measurableSet_image] theorem measurable_extend (hf : MeasurableEmbedding f) {g : α → γ} {g' : β → γ} (hg : Measurable g) (hg' : Measurable g') : Measurable (extend f g g') := by refine measurable_of_restrict_of_restrict_compl hf.measurableSet_range ?_ ?_ · rw [restrict_extend_range] simpa only [rangeSplitting] using hg.comp hf.measurable_rangeSplitting · rw [restrict_extend_compl_range] exact hg'.comp measurable_subtype_coe theorem exists_measurable_extend (hf : MeasurableEmbedding f) {g : α → γ} (hg : Measurable g) (hne : β → Nonempty γ) : ∃ g' : β → γ, Measurable g' ∧ g' ∘ f = g := ⟨extend f g fun x => Classical.choice (hne x), hf.measurable_extend hg (measurable_const' fun _ _ => rfl), funext fun _ => hf.injective.extend_apply _ _ _⟩ theorem measurable_comp_iff (hg : MeasurableEmbedding g) : Measurable (g ∘ f) ↔ Measurable f := by refine ⟨fun H => ?_, hg.measurable.comp⟩ suffices Measurable ((rangeSplitting g ∘ rangeFactorization g) ∘ f) by rwa [(rightInverse_rangeSplitting hg.injective).comp_eq_id] at this exact hg.measurable_rangeSplitting.comp H.subtype_mk end MeasurableEmbedding section gluing variable {α₁ α₂ α₃ : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} {mα₁ : MeasurableSpace α₁} {mα₂ : MeasurableSpace α₂} {mα₃ : MeasurableSpace α₃} {i₁ : α₁ → α} {i₂ : α₂ → α} {i₃ : α₃ → α} {s : Set α} {f : α → β} lemma MeasurableSet.of_union_range_cover (hi₁ : MeasurableEmbedding i₁) (hi₂ : MeasurableEmbedding i₂) (h : univ ⊆ range i₁ ∪ range i₂) (hs₁ : MeasurableSet (i₁ ⁻¹' s)) (hs₂ : MeasurableSet (i₂ ⁻¹' s)) : MeasurableSet s := by convert (hi₁.measurableSet_image' hs₁).union (hi₂.measurableSet_image' hs₂) simp [image_preimage_eq_range_inter, ← union_inter_distrib_right,univ_subset_iff.1 h] lemma MeasurableSet.of_union₃_range_cover (hi₁ : MeasurableEmbedding i₁) (hi₂ : MeasurableEmbedding i₂) (hi₃ : MeasurableEmbedding i₃) (h : univ ⊆ range i₁ ∪ range i₂ ∪ range i₃) (hs₁ : MeasurableSet (i₁ ⁻¹' s)) (hs₂ : MeasurableSet (i₂ ⁻¹' s)) (hs₃ : MeasurableSet (i₃ ⁻¹' s)) : MeasurableSet s := by convert (hi₁.measurableSet_image' hs₁).union (hi₂.measurableSet_image' hs₂) |>.union (hi₃.measurableSet_image' hs₃) simp [image_preimage_eq_range_inter, ← union_inter_distrib_right, univ_subset_iff.1 h] lemma Measurable.of_union_range_cover (hi₁ : MeasurableEmbedding i₁) (hi₂ : MeasurableEmbedding i₂) (h : univ ⊆ range i₁ ∪ range i₂) (hf₁ : Measurable (f ∘ i₁)) (hf₂ : Measurable (f ∘ i₂)) : Measurable f := fun _s hs ↦ .of_union_range_cover hi₁ hi₂ h (hf₁ hs) (hf₂ hs) lemma Measurable.of_union₃_range_cover (hi₁ : MeasurableEmbedding i₁) (hi₂ : MeasurableEmbedding i₂) (hi₃ : MeasurableEmbedding i₃) (h : univ ⊆ range i₁ ∪ range i₂ ∪ range i₃) (hf₁ : Measurable (f ∘ i₁)) (hf₂ : Measurable (f ∘ i₂)) (hf₃ : Measurable (f ∘ i₃)) : Measurable f := fun _s hs ↦ .of_union₃_range_cover hi₁ hi₂ hi₃ h (hf₁ hs) (hf₂ hs) (hf₃ hs) end gluing theorem MeasurableSet.exists_measurable_proj {_ : MeasurableSpace α} (hs : MeasurableSet s) (hne : s.Nonempty) : ∃ f : α → s, Measurable f ∧ ∀ x : s, f x = x := let ⟨f, hfm, hf⟩ := (MeasurableEmbedding.subtype_coe hs).exists_measurable_extend measurable_id fun _ => hne.to_subtype ⟨f, hfm, congr_fun hf⟩ /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure MeasurableEquiv (α β : Type*) [MeasurableSpace α] [MeasurableSpace β] extends α ≃ β where /-- The forward function of a measurable equivalence is measurable. -/ measurable_toFun : Measurable toEquiv /-- The inverse function of a measurable equivalence is measurable. -/ measurable_invFun : Measurable toEquiv.symm @[inherit_doc] infixl:25 " ≃ᵐ " => MeasurableEquiv namespace MeasurableEquiv variable [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ] theorem toEquiv_injective : Injective (toEquiv : α ≃ᵐ β → α ≃ β) := by rintro ⟨e₁, _, _⟩ ⟨e₂, _, _⟩ (rfl : e₁ = e₂) rfl instance instEquivLike : EquivLike (α ≃ᵐ β) α β where coe e := e.toEquiv inv e := e.toEquiv.symm left_inv e := e.toEquiv.left_inv right_inv e := e.toEquiv.right_inv coe_injective' _ _ he _ := toEquiv_injective <| DFunLike.ext' he @[simp] theorem coe_toEquiv (e : α ≃ᵐ β) : (e.toEquiv : α → β) = e := rfl @[measurability, fun_prop] protected theorem measurable (e : α ≃ᵐ β) : Measurable (e : α → β) := e.measurable_toFun @[simp] theorem coe_mk (e : α ≃ β) (h1 : Measurable e) (h2 : Measurable e.symm) : ((⟨e, h1, h2⟩ : α ≃ᵐ β) : α → β) = e := rfl /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [MeasurableSpace α] : α ≃ᵐ α where toEquiv := Equiv.refl α measurable_toFun := measurable_id measurable_invFun := measurable_id instance instInhabited : Inhabited (α ≃ᵐ α) := ⟨refl α⟩ /-- The composition of equivalences between measurable spaces. -/ def trans (ab : α ≃ᵐ β) (bc : β ≃ᵐ γ) : α ≃ᵐ γ where toEquiv := ab.toEquiv.trans bc.toEquiv measurable_toFun := bc.measurable_toFun.comp ab.measurable_toFun measurable_invFun := ab.measurable_invFun.comp bc.measurable_invFun theorem coe_trans (ab : α ≃ᵐ β) (bc : β ≃ᵐ γ) : ⇑(ab.trans bc) = bc ∘ ab := rfl /-- The inverse of an equivalence between measurable spaces. -/ def symm (ab : α ≃ᵐ β) : β ≃ᵐ α where toEquiv := ab.toEquiv.symm measurable_toFun := ab.measurable_invFun measurable_invFun := ab.measurable_toFun @[simp] theorem coe_toEquiv_symm (e : α ≃ᵐ β) : (e.toEquiv.symm : β → α) = e.symm := rfl /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def Simps.apply (h : α ≃ᵐ β) : α → β := h /-- See Note [custom simps projection] -/ def Simps.symm_apply (h : α ≃ᵐ β) : β → α := h.symm initialize_simps_projections MeasurableEquiv (toFun → apply, invFun → symm_apply) @[ext] theorem ext {e₁ e₂ : α ≃ᵐ β} (h : (e₁ : α → β) = e₂) : e₁ = e₂ := DFunLike.ext' h @[simp] theorem symm_mk (e : α ≃ β) (h1 : Measurable e) (h2 : Measurable e.symm) : (⟨e, h1, h2⟩ : α ≃ᵐ β).symm = ⟨e.symm, h2, h1⟩ := rfl attribute [simps! apply toEquiv] trans refl @[simp] theorem symm_symm (e : α ≃ᵐ β) : e.symm.symm = e := rfl theorem symm_bijective : Function.Bijective (MeasurableEquiv.symm : (α ≃ᵐ β) → β ≃ᵐ α) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ @[simp] theorem symm_refl (α : Type*) [MeasurableSpace α] : (refl α).symm = refl α := rfl @[simp] theorem symm_comp_self (e : α ≃ᵐ β) : e.symm ∘ e = id := funext e.left_inv @[simp] theorem self_comp_symm (e : α ≃ᵐ β) : e ∘ e.symm = id := funext e.right_inv @[simp] theorem apply_symm_apply (e : α ≃ᵐ β) (y : β) : e (e.symm y) = y := e.right_inv y @[simp] theorem symm_apply_apply (e : α ≃ᵐ β) (x : α) : e.symm (e x) = x := e.left_inv x @[simp] theorem symm_trans_self (e : α ≃ᵐ β) : e.symm.trans e = refl β := ext e.self_comp_symm @[simp] theorem self_trans_symm (e : α ≃ᵐ β) : e.trans e.symm = refl α := ext e.symm_comp_self protected theorem surjective (e : α ≃ᵐ β) : Surjective e := e.toEquiv.surjective protected theorem bijective (e : α ≃ᵐ β) : Bijective e := e.toEquiv.bijective protected theorem injective (e : α ≃ᵐ β) : Injective e := e.toEquiv.injective @[simp] theorem symm_preimage_preimage (e : α ≃ᵐ β) (s : Set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.toEquiv.symm_preimage_preimage s theorem image_eq_preimage (e : α ≃ᵐ β) (s : Set α) : e '' s = e.symm ⁻¹' s := e.toEquiv.image_eq_preimage s lemma preimage_symm (e : α ≃ᵐ β) (s : Set α) : e.symm ⁻¹' s = e '' s := (image_eq_preimage _ _).symm lemma image_symm (e : α ≃ᵐ β) (s : Set β) : e.symm '' s = e ⁻¹' s := by rw [← symm_symm e, preimage_symm, symm_symm] lemma eq_image_iff_symm_image_eq (e : α ≃ᵐ β) (s : Set β) (t : Set α) : s = e '' t ↔ e.symm '' s = t := by rw [← coe_toEquiv, Equiv.eq_image_iff_symm_image_eq, coe_toEquiv_symm] @[simp] lemma image_preimage (e : α ≃ᵐ β) (s : Set β) : e '' (e ⁻¹' s) = s := by rw [← coe_toEquiv, Equiv.image_preimage] @[simp] lemma preimage_image (e : α ≃ᵐ β) (s : Set α) : e ⁻¹' (e '' s) = s := by rw [← coe_toEquiv, Equiv.preimage_image] @[simp] theorem measurableSet_preimage (e : α ≃ᵐ β) {s : Set β} : MeasurableSet (e ⁻¹' s) ↔ MeasurableSet s := ⟨fun h => by simpa only [symm_preimage_preimage] using e.symm.measurable h, fun h => e.measurable h⟩ @[simp] theorem measurableSet_image (e : α ≃ᵐ β) : MeasurableSet (e '' s) ↔ MeasurableSet s := by rw [image_eq_preimage, measurableSet_preimage] @[simp] theorem map_eq (e : α ≃ᵐ β) : MeasurableSpace.map e ‹_› = ‹_› := e.measurable.le_map.antisymm' fun _s ↦ e.measurableSet_preimage.1 /-- A measurable equivalence is a measurable embedding. -/ protected theorem measurableEmbedding (e : α ≃ᵐ β) : MeasurableEmbedding e where injective := e.injective measurable := e.measurable measurableSet_image' := fun _ => e.measurableSet_image.2 /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : MeasurableSpace α] [i₂ : MeasurableSpace β] (h : α = β) (hi : i₁ ≍ i₂) : α ≃ᵐ β where toEquiv := Equiv.cast h measurable_toFun := by subst h subst hi exact measurable_id measurable_invFun := by subst h subst hi exact measurable_id /-- Measurable equivalence between `ULift α` and `α`. -/ def ulift.{u, v} {α : Type u} [MeasurableSpace α] : ULift.{v, u} α ≃ᵐ α := ⟨Equiv.ulift, measurable_down, measurable_up⟩ protected theorem measurable_comp_iff {f : β → γ} (e : α ≃ᵐ β) : Measurable (f ∘ e) ↔ Measurable f := Iff.intro (fun hfe => by have : Measurable (f ∘ (e.symm.trans e).toEquiv) := hfe.comp e.symm.measurable rwa [coe_toEquiv, symm_trans_self] at this) fun h => h.comp e.measurable /-- Any two types with unique elements are measurably equivalent. -/ def ofUniqueOfUnique (α β : Type*) [MeasurableSpace α] [MeasurableSpace β] [Unique α] [Unique β] : α ≃ᵐ β where toEquiv := ofUnique α β measurable_toFun := Subsingleton.measurable measurable_invFun := Subsingleton.measurable variable [MeasurableSpace δ] in /-- Products of equivalent measurable spaces are equivalent. -/ def prodCongr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α × γ ≃ᵐ β × δ where toEquiv := .prodCongr ab.toEquiv cd.toEquiv measurable_toFun := (ab.measurable_toFun.comp measurable_id.fst).prodMk (cd.measurable_toFun.comp measurable_id.snd) measurable_invFun := (ab.measurable_invFun.comp measurable_id.fst).prodMk (cd.measurable_invFun.comp measurable_id.snd) /-- Products of measurable spaces are symmetric. -/ def prodComm : α × β ≃ᵐ β × α where toEquiv := .prodComm α β measurable_toFun := measurable_id.snd.prodMk measurable_id.fst measurable_invFun := measurable_id.snd.prodMk measurable_id.fst /-- Products of measurable spaces are associative. -/ def prodAssoc : (α × β) × γ ≃ᵐ α × β × γ where toEquiv := .prodAssoc α β γ measurable_toFun := measurable_fst.fst.prodMk <| measurable_fst.snd.prodMk measurable_snd measurable_invFun := (measurable_fst.prodMk measurable_snd.fst).prodMk measurable_snd.snd /-- `PUnit` is a left identity for product of measurable spaces up to a measurable equivalence. -/ def punitProd : PUnit × α ≃ᵐ α where toEquiv := Equiv.punitProd α measurable_toFun := measurable_snd measurable_invFun := measurable_prodMk_left /-- `PUnit` is a right identity for product of measurable spaces up to a measurable equivalence. -/ def prodPUnit : α × PUnit ≃ᵐ α where toEquiv := Equiv.prodPUnit α measurable_toFun := measurable_fst measurable_invFun := measurable_prodMk_right variable [MeasurableSpace δ] in /-- Sums of measurable spaces are symmetric. -/ def sumCongr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α ⊕ γ ≃ᵐ β ⊕ δ where toEquiv := .sumCongr ab.toEquiv cd.toEquiv measurable_toFun := ab.measurable.sumMap cd.measurable measurable_invFun := ab.symm.measurable.sumMap cd.symm.measurable /-- `s ×ˢ t ≃ (s × t)` as measurable spaces. -/ def Set.prod (s : Set α) (t : Set β) : ↥(s ×ˢ t) ≃ᵐ s × t where toEquiv := Equiv.Set.prod s t measurable_toFun := measurable_id.subtype_val.fst.subtype_mk.prodMk measurable_id.subtype_val.snd.subtype_mk measurable_invFun := Measurable.subtype_mk <| measurable_id.fst.subtype_val.prodMk measurable_id.snd.subtype_val /-- `univ α ≃ α` as measurable spaces. -/ def Set.univ (α : Type*) [MeasurableSpace α] : (univ : Set α) ≃ᵐ α where toEquiv := Equiv.Set.univ α measurable_toFun := measurable_id.subtype_val measurable_invFun := measurable_id.subtype_mk /-- `{a} ≃ Unit` as measurable spaces. -/ def Set.singleton (a : α) : ({a} : Set α) ≃ᵐ Unit where toEquiv := Equiv.Set.singleton a measurable_toFun := measurable_const measurable_invFun := measurable_const /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def Set.rangeInl : (range Sum.inl : Set (α ⊕ β)) ≃ᵐ α where toEquiv := Equiv.Set.rangeInl α β measurable_toFun s (hs : MeasurableSet s) := by refine ⟨_, hs.inl_image, Set.ext ?_⟩ simp measurable_invFun := Measurable.subtype_mk measurable_inl /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def Set.rangeInr : (range Sum.inr : Set (α ⊕ β)) ≃ᵐ β where toEquiv := Equiv.Set.rangeInr α β measurable_toFun s (hs : MeasurableSet s) := by refine ⟨_, hs.inr_image, Set.ext ?_⟩ simp measurable_invFun := Measurable.subtype_mk measurable_inr /-- Products distribute over sums (on the right) as measurable spaces. -/ def sumProdDistrib (α β γ) [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ] : (α ⊕ β) × γ ≃ᵐ (α × γ) ⊕ (β × γ) where toEquiv := .sumProdDistrib α β γ measurable_toFun := by refine measurable_of_measurable_union_cover (range Sum.inl ×ˢ (univ : Set γ)) (range Sum.inr ×ˢ (univ : Set γ)) (measurableSet_range_inl.prod MeasurableSet.univ) (measurableSet_range_inr.prod MeasurableSet.univ) (by rintro ⟨a | b, c⟩ <;> simp [Set.prod_eq]) ?_ ?_ · refine (Set.prod (range Sum.inl) univ).symm.measurable_comp_iff.1 ?_ refine (prodCongr Set.rangeInl (Set.univ _)).symm.measurable_comp_iff.1 ?_ exact measurable_inl · refine (Set.prod (range Sum.inr) univ).symm.measurable_comp_iff.1 ?_ refine (prodCongr Set.rangeInr (Set.univ _)).symm.measurable_comp_iff.1 ?_ exact measurable_inr measurable_invFun := measurable_fun_sum ((measurable_inl.comp measurable_fst).prodMk measurable_snd) ((measurable_inr.comp measurable_fst).prodMk measurable_snd) /-- Products distribute over sums (on the left) as measurable spaces. -/ def prodSumDistrib (α β γ) [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ] : α × (β ⊕ γ) ≃ᵐ (α × β) ⊕ (α × γ) := prodComm.trans <| (sumProdDistrib _ _ _).trans <| sumCongr prodComm prodComm /-- Products distribute over sums as measurable spaces. -/ def sumProdSum (α β γ δ) [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ] [MeasurableSpace δ] : (α ⊕ β) × (γ ⊕ δ) ≃ᵐ ((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ)) := (sumProdDistrib _ _ _).trans <| sumCongr (prodSumDistrib _ _ _) (prodSumDistrib _ _ _) variable {π π' : δ' → Type*} [∀ x, MeasurableSpace (π x)] [∀ x, MeasurableSpace (π' x)] /-- A family of measurable equivalences `Π a, β₁ a ≃ᵐ β₂ a` generates a measurable equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def piCongrRight (e : ∀ a, π a ≃ᵐ π' a) : (∀ a, π a) ≃ᵐ ∀ a, π' a where toEquiv := .piCongrRight fun a => (e a).toEquiv measurable_toFun := measurable_pi_lambda _ fun i => (e i).measurable_toFun.comp (measurable_pi_apply i) measurable_invFun := measurable_pi_lambda _ fun i => (e i).measurable_invFun.comp (measurable_pi_apply i) variable (π) in /-- Moving a dependent type along an equivalence of coordinates, as a measurable equivalence. -/ def piCongrLeft (f : δ ≃ δ') : (∀ b, π (f b)) ≃ᵐ ∀ a, π a where __ := Equiv.piCongrLeft π f measurable_toFun := measurable_piCongrLeft f measurable_invFun := by rw [measurable_pi_iff] exact fun i => measurable_pi_apply (f i) theorem coe_piCongrLeft (f : δ ≃ δ') : ⇑(MeasurableEquiv.piCongrLeft π f) = f.piCongrLeft π := by rfl lemma piCongrLeft_apply_apply {ι ι' : Type*} (e : ι ≃ ι') {β : ι' → Type*} [∀ i', MeasurableSpace (β i')] (x : (i : ι) → β (e i)) (i : ι) : piCongrLeft (fun i' ↦ β i') e x (e i) = x i := by rw [piCongrLeft, coe_mk, Equiv.piCongrLeft_apply_apply] /-- The isomorphism `(γ → α × β) ≃ (γ → α) × (γ → β)` as a measurable equivalence. -/ def arrowProdEquivProdArrow (α β γ : Type*) [MeasurableSpace α] [MeasurableSpace β] : (γ → α × β) ≃ᵐ (γ → α) × (γ → β) where __ := Equiv.arrowProdEquivProdArrow γ _ _ measurable_toFun := by dsimp [Equiv.arrowProdEquivProdArrow] fun_prop measurable_invFun := by dsimp [Equiv.arrowProdEquivProdArrow] fun_prop /-- The measurable equivalence `(α₁ → β₁) ≃ᵐ (α₂ → β₂)` induced by `α₁ ≃ α₂` and `β₁ ≃ᵐ β₂`. -/ def arrowCongr' {α₁ β₁ α₂ β₂ : Type*} [MeasurableSpace β₁] [MeasurableSpace β₂] (hα : α₁ ≃ α₂) (hβ : β₁ ≃ᵐ β₂) : (α₁ → β₁) ≃ᵐ (α₂ → β₂) where __ := Equiv.arrowCongr' hα hβ measurable_toFun _ h := by exact MeasurableSet.preimage h <| measurable_pi_iff.mpr fun _ ↦ hβ.measurable.comp' (measurable_pi_apply _) measurable_invFun _ h := by exact MeasurableSet.preimage h <| measurable_pi_iff.mpr fun _ ↦ hβ.symm.measurable.comp' (measurable_pi_apply _) /-- Pi-types are measurably equivalent to iterated products. -/ @[simps! -fullyApplied] def piMeasurableEquivTProd [DecidableEq δ'] {l : List δ'} (hnd : l.Nodup) (h : ∀ i, i ∈ l) : (∀ i, π i) ≃ᵐ List.TProd π l where toEquiv := List.TProd.piEquivTProd hnd h measurable_toFun := measurable_tProd_mk l measurable_invFun := measurable_tProd_elim' h variable (π) in /-- The measurable equivalence `(∀ i, π i) ≃ᵐ π ⋆` when the domain of `π` only contains `⋆` -/ @[simps! -fullyApplied] def piUnique [Unique δ'] : (∀ i, π i) ≃ᵐ π default where toEquiv := Equiv.piUnique π measurable_toFun := measurable_pi_apply _ measurable_invFun := measurable_uniqueElim /-- If `α` has a unique term, then the type of function `α → β` is measurably equivalent to `β`. -/ @[simps! -fullyApplied] def funUnique (α β : Type*) [Unique α] [MeasurableSpace β] : (α → β) ≃ᵐ β := MeasurableEquiv.piUnique _ /-- The space `Π i : Fin 2, α i` is measurably equivalent to `α 0 × α 1`. -/ @[simps! -fullyApplied] def piFinTwo (α : Fin 2 → Type*) [∀ i, MeasurableSpace (α i)] : (∀ i, α i) ≃ᵐ α 0 × α 1 where toEquiv := piFinTwoEquiv α measurable_toFun := Measurable.prod (measurable_pi_apply _) (measurable_pi_apply _) measurable_invFun := measurable_pi_iff.2 <| Fin.forall_fin_two.2 ⟨measurable_fst, measurable_snd⟩ /-- The space `Fin 2 → α` is measurably equivalent to `α × α`. -/ @[simps! -fullyApplied] def finTwoArrow : (Fin 2 → α) ≃ᵐ α × α := piFinTwo fun _ => α /-- Measurable equivalence between `Π j : Fin (n + 1), α j` and `α i × Π j : Fin n, α (Fin.succAbove i j)`. Measurable version of `Fin.insertNthEquiv`. -/ @[simps! -fullyApplied] def piFinSuccAbove {n : ℕ} (α : Fin (n + 1) → Type*) [∀ i, MeasurableSpace (α i)] (i : Fin (n + 1)) : (∀ j, α j) ≃ᵐ α i × ∀ j, α (i.succAbove j) where toEquiv := (Fin.insertNthEquiv α i).symm measurable_toFun := (measurable_pi_apply i).prodMk <| measurable_pi_iff.2 fun _ => measurable_pi_apply _ measurable_invFun := measurable_pi_iff.2 <| i.forall_iff_succAbove.2 ⟨by simp [measurable_fst], fun j => by simpa using (measurable_pi_apply _).comp measurable_snd⟩ variable (π) /-- Measurable equivalence between (dependent) functions on a type and pairs of functions on `{i // p i}` and `{i // ¬p i}`. See also `Equiv.piEquivPiSubtypeProd`. -/ @[simps! -fullyApplied] def piEquivPiSubtypeProd (p : δ' → Prop) [DecidablePred p] : (∀ i, π i) ≃ᵐ (∀ i : Subtype p, π i) × ∀ i : { i // ¬p i }, π i where toEquiv := .piEquivPiSubtypeProd p π measurable_toFun := measurable_piEquivPiSubtypeProd π p measurable_invFun := measurable_piEquivPiSubtypeProd_symm π p /-- The measurable equivalence between the pi type over a sum type and a product of pi-types. This is similar to `MeasurableEquiv.piEquivPiSubtypeProd`. -/ def sumPiEquivProdPi (α : δ ⊕ δ' → Type*) [∀ i, MeasurableSpace (α i)] : (∀ i, α i) ≃ᵐ (∀ i, α (.inl i)) × ∀ i', α (.inr i') where __ := Equiv.sumPiEquivProdPi α measurable_toFun := by apply Measurable.prod <;> rw [measurable_pi_iff] <;> rintro i <;> apply measurable_pi_apply measurable_invFun := by rw [measurable_pi_iff]; rintro (i | i) · exact measurable_pi_iff.1 measurable_fst _ · exact measurable_pi_iff.1 measurable_snd _ theorem coe_sumPiEquivProdPi (α : δ ⊕ δ' → Type*) [∀ i, MeasurableSpace (α i)] : ⇑(MeasurableEquiv.sumPiEquivProdPi α) = Equiv.sumPiEquivProdPi α := by rfl theorem coe_sumPiEquivProdPi_symm (α : δ ⊕ δ' → Type*) [∀ i, MeasurableSpace (α i)] : ⇑(MeasurableEquiv.sumPiEquivProdPi α).symm = (Equiv.sumPiEquivProdPi α).symm := by rfl /-- The measurable equivalence for (dependent) functions on an Option type `(∀ i : Option δ, α i) ≃ᵐ (∀ (i : δ), α i) × α none`. -/ def piOptionEquivProd {δ : Type*} (α : Option δ → Type*) [∀ i, MeasurableSpace (α i)] : (∀ i, α i) ≃ᵐ (∀ (i : δ), α i) × α none := let e : Option δ ≃ δ ⊕ Unit := Equiv.optionEquivSumPUnit δ let em1 : ((i : δ ⊕ Unit) → α (e.symm i)) ≃ᵐ ((a : Option δ) → α a) := MeasurableEquiv.piCongrLeft α e.symm let em2 : ((i : δ ⊕ Unit) → α (e.symm i)) ≃ᵐ ((i : δ) → α (e.symm (Sum.inl i))) × ((i' : Unit) → α (e.symm (Sum.inr i'))) := MeasurableEquiv.sumPiEquivProdPi (fun i ↦ α (e.symm i)) let em3 : ((i : δ) → α (e.symm (Sum.inl i))) × ((i' : Unit) → α (e.symm (Sum.inr i'))) ≃ᵐ ((i : δ) → α (some i)) × α none := MeasurableEquiv.prodCongr (MeasurableEquiv.refl ((i : δ) → α (e.symm (Sum.inl i)))) (MeasurableEquiv.piUnique fun i ↦ α (e.symm (Sum.inr i))) em1.symm.trans <| em2.trans em3 /-- The measurable equivalence `(∀ i : s, π i) × (∀ i : t, π i) ≃ᵐ (∀ i : s ∪ t, π i)` for disjoint finsets `s` and `t`. `Equiv.piFinsetUnion` as a measurable equivalence. -/ def piFinsetUnion [DecidableEq δ'] {s t : Finset δ'} (h : Disjoint s t) : ((∀ i : s, π i) × ∀ i : t, π i) ≃ᵐ ∀ i : (s ∪ t : Finset δ'), π i := letI e := Finset.union s t h MeasurableEquiv.sumPiEquivProdPi (fun b ↦ π (e b)) |>.symm.trans <| .piCongrLeft (fun i : ↥(s ∪ t) ↦ π i) e /-- If `s` is a measurable set in a measurable space, that space is equivalent to the sum of `s` and `sᶜ`. -/ def sumCompl {s : Set α} [DecidablePred (· ∈ s)] (hs : MeasurableSet s) : s ⊕ (sᶜ : Set α) ≃ᵐ α where toEquiv := .sumCompl (· ∈ s) measurable_toFun := measurable_subtype_coe.sumElim measurable_subtype_coe measurable_invFun := Measurable.dite measurable_inl measurable_inr hs /-- Convert a measurable involutive function `f` to a measurable permutation with `toFun = invFun = f`. See also `Function.Involutive.toPerm`. -/ @[simps toEquiv] def ofInvolutive (f : α → α) (hf : Involutive f) (hf' : Measurable f) : α ≃ᵐ α where toEquiv := hf.toPerm measurable_toFun := hf' measurable_invFun := hf' @[simp] theorem ofInvolutive_apply (f : α → α) (hf : Involutive f) (hf' : Measurable f) (a : α) : ofInvolutive f hf hf' a = f a := rfl @[simp] theorem ofInvolutive_symm (f : α → α) (hf : Involutive f) (hf' : Measurable f) : (ofInvolutive f hf hf').symm = ofInvolutive f hf hf' := rfl end MeasurableEquiv namespace MeasurableEmbedding variable [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ] {f : α → β} {g : β → α} @[simp] theorem comap_eq (hf : MeasurableEmbedding f) : MeasurableSpace.comap f ‹_› = ‹_› := hf.measurable.comap_le.antisymm fun _s h ↦ ⟨_, hf.measurableSet_image' h, hf.injective.preimage_image _⟩ theorem iff_comap_eq : MeasurableEmbedding f ↔ Injective f ∧ MeasurableSpace.comap f ‹_› = ‹_› ∧ MeasurableSet (range f) := ⟨fun hf ↦ ⟨hf.injective, hf.comap_eq, hf.measurableSet_range⟩, fun hf ↦ { injective := hf.1 measurable := by rw [← hf.2.1]; exact comap_measurable f measurableSet_image' := by rw [← hf.2.1] rintro _ ⟨s, hs, rfl⟩ simpa only [image_preimage_eq_inter_range] using hs.inter hf.2.2 }⟩ /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is a measurable embedding -/ noncomputable def equivImage (s : Set α) (hf : MeasurableEmbedding f) : s ≃ᵐ f '' s where toEquiv := Equiv.Set.image f s hf.injective measurable_toFun := (hf.measurable.comp measurable_id.subtype_val).subtype_mk measurable_invFun := by rintro t ⟨u, hu, rfl⟩ simpa [preimage_preimage, Set.image_symm_preimage hf.injective] using measurable_subtype_coe (hf.measurableSet_image' hu) /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is a measurable embedding -/ noncomputable def equivRange (hf : MeasurableEmbedding f) : α ≃ᵐ range f := (MeasurableEquiv.Set.univ _).symm.trans <| (hf.equivImage univ).trans <| MeasurableEquiv.cast (by rw [image_univ]) (by rw [image_univ]) theorem of_measurable_inverse_on_range {g : range f → α} (hf₁ : Measurable f) (hf₂ : MeasurableSet (range f)) (hg : Measurable g) (H : LeftInverse g (rangeFactorization f)) : MeasurableEmbedding f := by set e : α ≃ᵐ range f := ⟨⟨rangeFactorization f, g, H, H.rightInverse_of_surjective surjective_onto_range⟩, hf₁.subtype_mk, hg⟩ exact (MeasurableEmbedding.subtype_coe hf₂).comp e.measurableEmbedding theorem of_measurable_inverse (hf₁ : Measurable f) (hf₂ : MeasurableSet (range f)) (hg : Measurable g) (H : LeftInverse g f) : MeasurableEmbedding f := of_measurable_inverse_on_range hf₁ hf₂ (hg.comp measurable_subtype_coe) H /-- The **measurable Schröder-Bernstein Theorem**: given measurable embeddings `α → β` and `β → α`, we can find a measurable equivalence `α ≃ᵐ β`. -/ noncomputable def schroederBernstein {f : α → β} {g : β → α} (hf : MeasurableEmbedding f) (hg : MeasurableEmbedding g) : α ≃ᵐ β := by let F : Set α → Set α := fun A => (g '' (f '' A)ᶜ)ᶜ -- We follow the proof of the usual SB theorem in mathlib, -- the crux of which is finding a fixed point of this F. -- However, we must find this fixed point manually instead of invoking Knaster-Tarski -- in order to make sure it is measurable. suffices Σ' A : Set α, MeasurableSet A ∧ F A = A by classical rcases this with ⟨A, Ameas, Afp⟩ let B := f '' A have Bmeas : MeasurableSet B := hf.measurableSet_image' Ameas refine (MeasurableEquiv.sumCompl Ameas).symm.trans (MeasurableEquiv.trans ?_ (MeasurableEquiv.sumCompl Bmeas)) apply MeasurableEquiv.sumCongr (hf.equivImage _) have : Aᶜ = g '' Bᶜ := by apply compl_injective rw [← Afp] simp [F, B] rw [this] exact (hg.equivImage _).symm have Fmono : ∀ {A B}, A ⊆ B → F A ⊆ F B := fun h => compl_subset_compl.mpr <| Set.image_mono <| compl_subset_compl.mpr <| Set.image_mono h let X : ℕ → Set α := fun n => F^[n] univ refine ⟨iInter X, ?_, ?_⟩ · refine MeasurableSet.iInter fun n ↦ ?_ induction n with | zero => exact MeasurableSet.univ | succ n ih => rw [Function.iterate_succ', Function.comp_apply] exact (hg.measurableSet_image' (hf.measurableSet_image' ih).compl).compl apply subset_antisymm · apply subset_iInter intro n cases n · exact subset_univ _ rw [Function.iterate_succ', Function.comp_apply] exact Fmono (iInter_subset _ _) rintro x hx ⟨y, hy, rfl⟩ rw [mem_iInter] at hx apply hy rw [hf.injective.injOn.image_iInter_eq] rw [mem_iInter] intro n specialize hx n.succ rw [Function.iterate_succ', Function.comp_apply] at hx by_contra h apply hx exact ⟨y, h, rfl⟩ @[simp] lemma equivRange_apply (hf : MeasurableEmbedding f) (x : α) : hf.equivRange x = ⟨f x, mem_range_self x⟩ := by suffices f x = (hf.equivRange x).1 by simp [this] simp [MeasurableEmbedding.equivRange, MeasurableEquiv.cast, MeasurableEquiv.Set.univ, MeasurableEmbedding.equivImage] @[simp] lemma equivRange_symm_apply_mk (hf : MeasurableEmbedding f) (x : α) : hf.equivRange.symm ⟨f x, mem_range_self x⟩ = x := by nth_rw 3 [← hf.equivRange.symm_apply_apply x] rw [hf.equivRange_apply] /-- The left-inverse of a `MeasurableEmbedding` -/ protected noncomputable def invFun [Nonempty α] (hf : MeasurableEmbedding f) (x : β) : α := open Classical in if hx : x ∈ range f then hf.equivRange.symm ⟨x, hx⟩ else (Nonempty.some inferInstance) @[fun_prop, measurability] lemma measurable_invFun [Nonempty α] (hf : MeasurableEmbedding f) : Measurable (hf.invFun : β → α) := open Classical in Measurable.dite (by fun_prop) measurable_const hf.measurableSet_range lemma leftInverse_invFun [Nonempty α] (hf : MeasurableEmbedding f) : hf.invFun.LeftInverse f := by intro x simp [MeasurableEmbedding.invFun] end MeasurableEmbedding theorem MeasurableSpace.comap_compl {m' : MeasurableSpace β} [BooleanAlgebra β] (h : Measurable (compl : β → β)) (f : α → β) : MeasurableSpace.comap (fun a => (f a)ᶜ) inferInstance = MeasurableSpace.comap f inferInstance := by rw [← Function.comp_def, ← MeasurableSpace.comap_comp] congr exact (MeasurableEquiv.ofInvolutive _ compl_involutive h).measurableEmbedding.comap_eq @[simp] theorem MeasurableSpace.comap_not (p : α → Prop) : MeasurableSpace.comap (fun a ↦ ¬p a) inferInstance = MeasurableSpace.comap p inferInstance := MeasurableSpace.comap_compl (fun _ _ ↦ measurableSet_top) _
DirectLimit.lean
/- Copyright (c) 2023 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import Mathlib.Algebra.Colimit.Module import Mathlib.LinearAlgebra.TensorProduct.Basic /-! # Tensor product and direct limits commute with each other. Given a family of `R`-modules `Gᵢ` with a family of compatible `R`-linear maps `fᵢⱼ : Gᵢ → Gⱼ` for every `i ≤ j` and another `R`-module `M`, we have `(limᵢ Gᵢ) ⊗ M` and `lim (Gᵢ ⊗ M)` are isomorphic as `R`-modules. ## Main definitions: * `TensorProduct.directLimitLeft : DirectLimit G f ⊗[R] M ≃ₗ[R] DirectLimit (G · ⊗[R] M) (f ▷ M)` * `TensorProduct.directLimitRight : M ⊗[R] DirectLimit G f ≃ₗ[R] DirectLimit (M ⊗[R] G ·) (M ◁ f)` -/ open TensorProduct Module Module.DirectLimit variable {R : Type*} [CommSemiring R] variable {ι : Type*} variable [DecidableEq ι] [Preorder ι] variable {G : ι → Type*} variable [∀ i, AddCommMonoid (G i)] [∀ i, Module R (G i)] variable (f : ∀ i j, i ≤ j → G i →ₗ[R] G j) variable (M : Type*) [AddCommMonoid M] [Module R M] -- alluding to the notation in `CategoryTheory.Monoidal` local notation M " ◁ " f => fun i j h ↦ LinearMap.lTensor M (f _ _ h) local notation f " ▷ " N => fun i j h ↦ LinearMap.rTensor N (f _ _ h) namespace TensorProduct /-- the map `limᵢ (Gᵢ ⊗ M) → (limᵢ Gᵢ) ⊗ M` induced by the family of maps `Gᵢ ⊗ M → (limᵢ Gᵢ) ⊗ M` given by `gᵢ ⊗ m ↦ [gᵢ] ⊗ m`. -/ noncomputable def fromDirectLimit : DirectLimit (G · ⊗[R] M) (f ▷ M) →ₗ[R] DirectLimit G f ⊗[R] M := Module.DirectLimit.lift _ _ _ _ (fun _ ↦ (of _ _ _ _ _).rTensor M) fun _ _ _ x ↦ by refine x.induction_on ?_ ?_ ?_ <;> aesop variable {M} in @[simp] lemma fromDirectLimit_of_tmul {i : ι} (g : G i) (m : M) : fromDirectLimit f M (of _ _ _ _ i (g ⊗ₜ m)) = (of _ _ _ f i g) ⊗ₜ m := lift_of (G := (G · ⊗[R] M)) _ _ (g ⊗ₜ m) /-- the map `(limᵢ Gᵢ) ⊗ M → limᵢ (Gᵢ ⊗ M)` from the bilinear map `limᵢ Gᵢ → M → limᵢ (Gᵢ ⊗ M)` given by the family of maps `Gᵢ → M → limᵢ (Gᵢ ⊗ M)` where `gᵢ ↦ m ↦ [gᵢ ⊗ m]` -/ noncomputable def toDirectLimit : DirectLimit G f ⊗[R] M →ₗ[R] DirectLimit (G · ⊗[R] M) (f ▷ M) := TensorProduct.lift <| Module.DirectLimit.lift _ _ _ _ (fun i ↦ (TensorProduct.mk R _ _).compr₂ (of R ι _ (fun _i _j h ↦ (f _ _ h).rTensor M) i)) fun _ _ _ g ↦ DFunLike.ext _ _ (of_f (G := (G · ⊗[R] M)) (x := g ⊗ₜ ·)) variable {M} in @[simp] lemma toDirectLimit_tmul_of {i : ι} (g : G i) (m : M) : (toDirectLimit f M <| (of _ _ G f i g) ⊗ₜ m) = (of _ _ _ _ i (g ⊗ₜ m)) := by rw [toDirectLimit, lift.tmul, lift_of] rfl attribute [local ext] TensorProduct.ext in /-- `limᵢ (Gᵢ ⊗ M)` and `(limᵢ Gᵢ) ⊗ M` are isomorphic as modules -/ noncomputable def directLimitLeft : DirectLimit G f ⊗[R] M ≃ₗ[R] DirectLimit (G · ⊗[R] M) (f ▷ M) := LinearEquiv.ofLinear (toDirectLimit f M) (fromDirectLimit f M) (by ext; simp) (by ext; simp) @[simp] lemma directLimitLeft_tmul_of {i : ι} (g : G i) (m : M) : directLimitLeft f M (of _ _ _ _ _ g ⊗ₜ m) = of _ _ _ (f ▷ M) _ (g ⊗ₜ m) := toDirectLimit_tmul_of f g m @[simp] lemma directLimitLeft_symm_of_tmul {i : ι} (g : G i) (m : M) : (directLimitLeft f M).symm (of _ _ _ _ _ (g ⊗ₜ m)) = of _ _ _ f _ g ⊗ₜ m := fromDirectLimit_of_tmul f g m lemma directLimitLeft_rTensor_of {i : ι} (x : G i ⊗[R] M) : directLimitLeft f M (LinearMap.rTensor M (of ..) x) = of _ _ _ (f ▷ M) _ x := x.induction_on (by simp) (by simp+contextual) (by simp+contextual) /-- `M ⊗ (limᵢ Gᵢ)` and `limᵢ (M ⊗ Gᵢ)` are isomorphic as modules -/ noncomputable def directLimitRight : M ⊗[R] DirectLimit G f ≃ₗ[R] DirectLimit (M ⊗[R] G ·) (M ◁ f) := TensorProduct.comm _ _ _ ≪≫ₗ directLimitLeft f M ≪≫ₗ Module.DirectLimit.congr (fun _ ↦ TensorProduct.comm _ _ _) (fun i j h ↦ TensorProduct.ext <| DFunLike.ext _ _ <| by aesop) @[simp] lemma directLimitRight_tmul_of {i : ι} (m : M) (g : G i) : directLimitRight f M (m ⊗ₜ of _ _ _ _ _ g) = of _ _ _ _ i (m ⊗ₜ g) := by simp [directLimitRight, congr_apply_of] @[simp] lemma directLimitRight_symm_of_tmul {i : ι} (m : M) (g : G i) : (directLimitRight f M).symm (of _ _ _ _ _ (m ⊗ₜ g)) = m ⊗ₜ of _ _ _ f _ g := by simp [directLimitRight, congr_symm_apply_of] variable [DirectedSystem G (f · · ·)] instance : DirectedSystem (G · ⊗[R] M) (f ▷ M) where map_self i x := by convert LinearMap.rTensor_id_apply M (G i) x; ext; apply DirectedSystem.map_self' map_map _ _ _ _ _ x := by convert ← (LinearMap.rTensor_comp_apply M _ _ x).symm; ext; apply DirectedSystem.map_map' f instance : DirectedSystem (M ⊗[R] G ·) (M ◁ f) where map_self i x := by convert LinearMap.lTensor_id_apply M _ x; ext; apply DirectedSystem.map_self' map_map _ _ _ h₁ h₂ x := by convert ← (LinearMap.lTensor_comp_apply M _ _ x).symm; ext; apply DirectedSystem.map_map' f end TensorProduct
Basic.lean
/- Copyright (c) 2024 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Unique import Mathlib.Topology.ContinuousMap.ContinuousSqrt import Mathlib.Topology.ContinuousMap.StoneWeierstrass /-! # The positive (and negative) parts of a selfadjoint element in a C⋆-algebra This file defines the positive and negative parts of a selfadjoint element in a C⋆-algebra via the continuous functional calculus and develops the basic API, including the uniqueness of the positive and negative parts. -/ open scoped NNReal section NonUnital variable {A : Type*} [NonUnitalRing A] [Module ℝ A] [SMulCommClass ℝ A A] [IsScalarTower ℝ A A] variable [StarRing A] [TopologicalSpace A] variable [NonUnitalContinuousFunctionalCalculus ℝ A IsSelfAdjoint] namespace CStarAlgebra noncomputable instance : PosPart A where posPart := cfcₙ (·⁺ : ℝ → ℝ) noncomputable instance : NegPart A where negPart := cfcₙ (·⁻ : ℝ → ℝ) end CStarAlgebra namespace CFC lemma posPart_def (a : A) : a⁺ = cfcₙ (·⁺ : ℝ → ℝ) a := rfl lemma negPart_def (a : A) : a⁻ = cfcₙ (·⁻ : ℝ → ℝ) a := rfl @[simp] lemma posPart_zero : (0 : A)⁺ = 0 := by simp [posPart_def] @[simp] lemma negPart_zero : (0 : A)⁻ = 0 := by simp [negPart_def] lemma posPart_eq_zero_of_not_isSelfAdjoint {a : A} (ha : ¬IsSelfAdjoint a) : a⁺ = 0 := cfcₙ_apply_of_not_predicate a ha lemma negPart_eq_zero_of_not_isSelfAdjoint {a : A} (ha : ¬IsSelfAdjoint a) : a⁻ = 0 := cfcₙ_apply_of_not_predicate a ha @[simp] lemma posPart_mul_negPart (a : A) : a⁺ * a⁻ = 0 := by rw [posPart_def, negPart_def] by_cases ha : IsSelfAdjoint a · rw [← cfcₙ_mul _ _, ← cfcₙ_zero ℝ a] refine cfcₙ_congr (fun x _ ↦ ?_) simp only [_root_.posPart_def, _root_.negPart_def] simpa using le_total x 0 · simp [cfcₙ_apply_of_not_predicate a ha] @[simp] lemma negPart_mul_posPart (a : A) : a⁻ * a⁺ = 0 := by rw [posPart_def, negPart_def] by_cases ha : IsSelfAdjoint a · rw [← cfcₙ_mul _ _, ← cfcₙ_zero ℝ a] refine cfcₙ_congr (fun x _ ↦ ?_) simp only [_root_.posPart_def, _root_.negPart_def] simpa using le_total 0 x · simp [cfcₙ_apply_of_not_predicate a ha] lemma posPart_sub_negPart (a : A) (ha : IsSelfAdjoint a := by cfc_tac) : a⁺ - a⁻ = a := by rw [posPart_def, negPart_def] rw [← cfcₙ_sub _ _] conv_rhs => rw [← cfcₙ_id ℝ a] congr! 2 with exact _root_.posPart_sub_negPart _ section Unique variable [T2Space A] @[simp] lemma posPart_neg (a : A) : (-a)⁺ = a⁻ := by by_cases ha : IsSelfAdjoint a · rw [posPart_def, negPart_def, ← cfcₙ_comp_neg _ _] congr! 2 · have ha' : ¬ IsSelfAdjoint (-a) := fun h ↦ ha (by simpa using h.neg) rw [posPart_def, negPart_def, cfcₙ_apply_of_not_predicate a ha, cfcₙ_apply_of_not_predicate _ ha'] @[simp] lemma negPart_neg (a : A) : (-a)⁻ = a⁺ := by rw [← eq_comm, ← sub_eq_zero, ← posPart_neg, neg_neg, sub_self] section SMul variable [StarModule ℝ A] @[simp] lemma posPart_smul {r : ℝ≥0} {a : A} : (r • a)⁺ = r • a⁺ := by by_cases ha : IsSelfAdjoint a · simp only [CFC.posPart_def, NNReal.smul_def] rw [← cfcₙ_comp_smul .., ← cfcₙ_smul ..] refine cfcₙ_congr fun x hx ↦ ?_ simp [_root_.posPart_def, mul_max_of_nonneg] · obtain (rfl | hr) := eq_or_ne r 0 · simp · have := (not_iff_not.mpr <| (IsSelfAdjoint.all r).smul_iff hr.isUnit (x := a)) |>.mpr ha simp [CFC.posPart_def, cfcₙ_apply_of_not_predicate a ha, cfcₙ_apply_of_not_predicate _ this] @[simp] lemma negPart_smul {r : ℝ≥0} {a : A} : (r • a)⁻ = r • a⁻ := by simpa using posPart_smul (r := r) (a := -a) lemma posPart_smul_of_nonneg {r : ℝ} (hr : 0 ≤ r) {a : A} : (r • a)⁺ = r • a⁺ := posPart_smul (r := ⟨r, hr⟩) lemma posPart_smul_of_nonpos {r : ℝ} (hr : r ≤ 0) {a : A} : (r • a)⁺ = -r • a⁻ := by nth_rw 1 [← neg_neg r] rw [neg_smul, ← smul_neg, posPart_smul_of_nonneg (neg_nonneg.mpr hr), posPart_neg] lemma negPart_smul_of_nonneg {r : ℝ} (hr : 0 ≤ r) {a : A} : (r • a)⁻ = r • a⁻ := by conv_lhs => rw [← neg_neg r, neg_smul, negPart_neg, posPart_smul_of_nonpos (by simpa), neg_neg] lemma negPart_smul_of_nonpos {r : ℝ} (hr : r ≤ 0) {a : A} : (r • a)⁻ = -r • a⁺ := by conv_lhs => rw [← neg_neg r, neg_smul, negPart_neg, posPart_smul_of_nonneg (by simpa)] end SMul end Unique variable [PartialOrder A] [StarOrderedRing A] @[aesop norm apply (rule_sets := [CStarAlgebra])] lemma posPart_nonneg (a : A) : 0 ≤ a⁺ := cfcₙ_nonneg (fun x _ ↦ by positivity) @[aesop norm apply (rule_sets := [CStarAlgebra])] lemma negPart_nonneg (a : A) : 0 ≤ a⁻ := cfcₙ_nonneg (fun x _ ↦ by positivity) lemma posPart_eq_of_eq_sub_negPart {a b : A} (hab : a = b - a⁻) (hb : 0 ≤ b := by cfc_tac) : a⁺ = b := by have ha := hab.symm ▸ hb.isSelfAdjoint.sub (negPart_nonneg a).isSelfAdjoint nth_rw 1 [← posPart_sub_negPart a] at hab simpa using hab lemma negPart_eq_of_eq_PosPart_sub {a c : A} (hac : a = a⁺ - c) (hc : 0 ≤ c := by cfc_tac) : a⁻ = c := by have ha := hac.symm ▸ (posPart_nonneg a).isSelfAdjoint.sub hc.isSelfAdjoint nth_rw 1 [← posPart_sub_negPart a] at hac simpa using hac lemma le_posPart {a : A} (ha : IsSelfAdjoint a := by cfc_tac) : a ≤ a⁺ := by simpa [posPart_sub_negPart a] using sub_le_self a⁺ (negPart_nonneg a) lemma neg_negPart_le {a : A} (ha : IsSelfAdjoint a := by cfc_tac) : -a⁻ ≤ a := by simpa only [posPart_sub_negPart a, ← sub_eq_add_neg] using le_add_of_nonneg_left (a := -a⁻) (posPart_nonneg a) variable [NonnegSpectrumClass ℝ A] lemma posPart_eq_self (a : A) : a⁺ = a ↔ 0 ≤ a := by refine ⟨fun ha ↦ ha ▸ posPart_nonneg a, fun ha ↦ ?_⟩ conv_rhs => rw [← cfcₙ_id ℝ a] rw [posPart_def] refine cfcₙ_congr (fun x hx ↦ ?_) simpa [_root_.posPart_def] using quasispectrum_nonneg_of_nonneg a ha x hx lemma negPart_eq_zero_iff (a : A) (ha : IsSelfAdjoint a := by cfc_tac) : a⁻ = 0 ↔ 0 ≤ a := by rw [← posPart_eq_self, eq_comm (b := a)] nth_rw 2 [← posPart_sub_negPart a] simp lemma negPart_eq_neg (a : A) : a⁻ = -a ↔ a ≤ 0 := by rw [← neg_inj, neg_neg, eq_comm] refine ⟨fun ha ↦ by rw [ha, neg_nonpos]; exact negPart_nonneg a, fun ha ↦ ?_⟩ rw [← neg_nonneg] at ha rw [negPart_def, ← cfcₙ_neg] have _ : IsSelfAdjoint a := neg_neg a ▸ (IsSelfAdjoint.neg <| .of_nonneg ha) conv_lhs => rw [← cfcₙ_id ℝ a] refine cfcₙ_congr fun x hx ↦ ?_ rw [Unitization.quasispectrum_eq_spectrum_inr ℝ, ← neg_neg x, ← Set.mem_neg, spectrum.neg_eq, ← Unitization.inr_neg, ← Unitization.quasispectrum_eq_spectrum_inr ℝ] at hx rw [← neg_eq_iff_eq_neg, eq_comm] simpa using quasispectrum_nonneg_of_nonneg _ ha _ hx lemma posPart_eq_zero_iff (a : A) (ha : IsSelfAdjoint a := by cfc_tac) : a⁺ = 0 ↔ a ≤ 0 := by rw [← negPart_eq_neg, eq_comm (b := -a)] nth_rw 2 [← posPart_sub_negPart a] simp local notation "σₙ" => quasispectrum open ContinuousMapZero variable [IsTopologicalRing A] [T2Space A] open NonUnitalContinuousFunctionalCalculus in /-- The positive and negative parts of a selfadjoint element `a` are unique. That is, if `a = b - c` is the difference of nonnegative elements whose product is zero, then these are precisely `a⁺` and `a⁻`. -/ lemma posPart_negPart_unique {a b c : A} (habc : a = b - c) (hbc : b * c = 0) (hb : 0 ≤ b := by cfc_tac) (hc : 0 ≤ c := by cfc_tac) : a⁺ = b ∧ a⁻ = c := by /- The key idea is to show that `cfcₙ f a = cfcₙ f b + cfcₙ f (-c)` for all real-valued `f` continuous on the union of the spectra of `a`, `b`, and `-c`. Then apply this to `f = (·⁺)`. The equality holds because both sides constitute star homomorphisms which agree on `f = id` since `a = b - c`. -/ /- `a`, `b`, `-c` are selfadjoint. -/ have hb' : IsSelfAdjoint b := .of_nonneg hb have hc' : IsSelfAdjoint (-c) := .neg <| .of_nonneg hc have ha : IsSelfAdjoint a := habc ▸ hb'.sub <| .of_nonneg hc /- It suffices to show `b = a⁺` since `a⁺ - a⁻ = a = b - c` -/ rw [and_iff_left_of_imp ?of_b_eq] case of_b_eq => rintro rfl exact negPart_eq_of_eq_PosPart_sub habc hc /- `s := σₙ ℝ a ∪ σₙ ℝ b ∪ σₙ ℝ (-c)` is compact and each of these sets are subsets of `s`. Moreover, `0 ∈ s`. -/ let s := σₙ ℝ a ∪ σₙ ℝ b ∪ σₙ ℝ (-c) have hs : CompactSpace s := by refine isCompact_iff_compactSpace.mp <| (IsCompact.union ?_ ?_).union ?_ all_goals exact isCompact_quasispectrum _ obtain ⟨has, hbs, hcs⟩ : σₙ ℝ a ⊆ s ∧ σₙ ℝ b ⊆ s ∧ σₙ ℝ (-c) ⊆ s := by grind let zero : Zero s := ⟨0, by aesop⟩ have s0 : (0 : s) = (0 : ℝ) := rfl /- The continuous functional calculi for functions `f g : C(s, ℝ)₀` applied to `b` and `(-c)` are orthogonal (i.e., the product is always zero). -/ have mul₁ (f g : C(s, ℝ)₀) : (cfcₙHomSuperset hb' hbs f) * (cfcₙHomSuperset hc' hcs g) = 0 := by refine f.nonUnitalStarAlgHom_apply_mul_eq_zero s0 _ _ ?id ?star_id (cfcₙHomSuperset_continuous hb' hbs) case' star_id => rw [star_trivial] all_goals refine g.mul_nonUnitalStarAlgHom_apply_eq_zero s0 _ _ ?_ ?_ (cfcₙHomSuperset_continuous hc' hcs) all_goals simp only [zero, star_trivial, cfcₙHomSuperset_id' hb' hbs, cfcₙHomSuperset_id' hc' hcs, mul_neg, hbc, neg_zero] have mul₂ (f g : C(s, ℝ)₀) : (cfcₙHomSuperset hc' hcs f) * (cfcₙHomSuperset hb' hbs g) = 0 := by simpa only [star_mul, star_zero, ← map_star, star_trivial] using congr(star $(mul₁ g f)) /- `fun f ↦ cfcₙ f b + cfcₙ f (-c)` defines a star homomorphism `ψ : C(s, ℝ)₀ →⋆ₙₐ[ℝ] A` which agrees with the star homomorphism `cfcₙ · a : C(s, ℝ)₀ →⋆ₙₐ[ℝ] A` since `cfcₙ id a = a = b - c = cfcₙ id b + cfcₙ id (-c)`. -/ let ψ : C(s, ℝ)₀ →⋆ₙₐ[ℝ] A := { (cfcₙHomSuperset hb' hbs : C(s, ℝ)₀ →ₗ[ℝ] A) + (cfcₙHomSuperset hc' hcs : C(s, ℝ)₀ →ₗ[ℝ] A) with toFun := cfcₙHomSuperset hb' hbs + cfcₙHomSuperset hc' hcs map_zero' := by simp [-cfcₙHomSuperset_apply] map_mul' := fun f g ↦ by simp only [zero, Pi.add_apply, map_mul, mul_add, add_mul, mul₂, add_zero, mul₁, zero_add] map_star' := fun f ↦ by simp [← map_star] } have key : (cfcₙHomSuperset ha has) = ψ := have : ContinuousMapZero.UniqueHom ℝ A := inferInstance ContinuousMapZero.UniqueHom.eq_of_continuous_of_map_id s rfl (cfcₙHomSuperset ha has) ψ (cfcₙHomSuperset_continuous ha has) ((cfcₙHomSuperset_continuous hb' hbs).add (cfcₙHomSuperset_continuous hc' hcs)) (by simpa [zero, ψ, -cfcₙHomSuperset_apply, cfcₙHomSuperset_id, sub_eq_add_neg] using habc) /- Applying the equality of star homomorphisms to the function `(·⁺ : ℝ → ℝ)` we find that `b = cfcₙ id b + cfcₙ 0 (-c) = cfcₙ (·⁺) b - cfcₙ (·⁺) (-c) = cfcₙ (·⁺) a = a⁺`, where the second equality follows because these functions are equal on the spectra of `b` and `-c`, respectively, since `0 ≤ b` and `-c ≤ 0`. -/ let f : C(s, ℝ)₀ := ⟨⟨(·⁺), by fun_prop⟩, by simp [s0]⟩ replace key := congr($key f) simp only [cfcₙHomSuperset_apply, NonUnitalStarAlgHom.coe_mk', NonUnitalAlgHom.coe_mk, ψ, Pi.add_apply, cfcₙHom_eq_cfcₙ_extend (·⁺)] at key symm calc b = cfcₙ (id : ℝ → ℝ) b + cfcₙ (0 : ℝ → ℝ) (-c) := by simp [cfcₙ_id ℝ b] _ = _ := by congr! 1 all_goals refine cfcₙ_congr fun x hx ↦ Eq.symm ?_ lift x to σₙ ℝ _ using hx simp only [zero, Subtype.val_injective.extend_apply, comp_apply, coe_mk, ContinuousMap.coe_mk, Subtype.map_coe, id_eq, _root_.posPart_eq_self, f, Pi.zero_apply, posPart_eq_zero] · exact quasispectrum_nonneg_of_nonneg b hb x.val x.property · obtain ⟨x, hx⟩ := x simp only [← neg_nonneg] rw [Unitization.quasispectrum_eq_spectrum_inr ℝ (-c), Unitization.inr_neg, ← spectrum.neg_eq, Set.mem_neg, ← Unitization.quasispectrum_eq_spectrum_inr ℝ c] at hx exact quasispectrum_nonneg_of_nonneg c hc _ hx _ = _ := key.symm _ = a⁺ := by refine cfcₙ_congr fun x hx ↦ ?_ lift x to σₙ ℝ a using hx simp [zero, f] end CFC end NonUnital section Unital namespace CFC variable {A : Type*} [Ring A] [Algebra ℝ A] [StarRing A] [TopologicalSpace A] variable [ContinuousFunctionalCalculus ℝ A IsSelfAdjoint] variable [T2Space A] @[simp] lemma posPart_one : (1 : A)⁺ = 1 := by rw [CFC.posPart_def, cfcₙ_eq_cfc] simp @[simp] lemma negPart_one : (1 : A)⁻ = 0 := by rw [CFC.negPart_def, cfcₙ_eq_cfc] simp @[simp] lemma posPart_algebraMap (r : ℝ) : (algebraMap ℝ A r)⁺ = algebraMap ℝ A r⁺ := by rw [CFC.posPart_def, cfcₙ_eq_cfc] simp @[simp] lemma negPart_algebraMap (r : ℝ) : (algebraMap ℝ A r)⁻ = algebraMap ℝ A r⁻ := by rw [CFC.negPart_def, cfcₙ_eq_cfc] simp open NNReal in @[simp] lemma posPart_algebraMap_nnreal (r : ℝ≥0) : (algebraMap ℝ≥0 A r)⁺ = algebraMap ℝ≥0 A r := by rw [CFC.posPart_def, cfcₙ_eq_cfc, IsScalarTower.algebraMap_apply ℝ≥0 ℝ A] simp open NNReal in @[simp] lemma posPart_natCast (n : ℕ) : (n : A)⁺ = n := by rw [← map_natCast (algebraMap ℝ≥0 A), posPart_algebraMap_nnreal] end CFC end Unital section SpanNonneg variable {A : Type*} [NonUnitalRing A] [Module ℂ A] [SMulCommClass ℂ A A] [IsScalarTower ℂ A A] variable [StarRing A] [TopologicalSpace A] [StarModule ℂ A] variable [NonUnitalContinuousFunctionalCalculus ℝ A IsSelfAdjoint] open Submodule Complex open scoped ComplexStarModule lemma CStarAlgebra.linear_combination_nonneg (x : A) : ((ℜ x : A)⁺ - (ℜ x : A)⁻) + (I • (ℑ x : A)⁺ - I • (ℑ x : A)⁻) = x := by rw [CFC.posPart_sub_negPart _ (ℜ x).2, ← smul_sub, CFC.posPart_sub_negPart _ (ℑ x).2, realPart_add_I_smul_imaginaryPart x] variable [PartialOrder A] [StarOrderedRing A] /-- A C⋆-algebra is spanned by its nonnegative elements. -/ lemma CStarAlgebra.span_nonneg : Submodule.span ℂ {a : A | 0 ≤ a} = ⊤ := by refine eq_top_iff.mpr fun x _ => ?_ rw [← CStarAlgebra.linear_combination_nonneg x] apply_rules [sub_mem, Submodule.smul_mem, add_mem] all_goals refine subset_span ?_ first | apply CFC.negPart_nonneg | apply CFC.posPart_nonneg end SpanNonneg
finfun.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 fintype tuple. (******************************************************************************) (* This file implements a type for functions with a finite domain: *) (* {ffun aT -> rT} where aT should have a finType structure, *) (* {ffun forall x : aT, rT} for dependent functions over a finType aT, *) (* and {ffun funT} where funT expands to a product over a finType. *) (* Any eqType, choiceType, countType and finType structures on rT extend to *) (* {ffun aT -> rT} as Leibnitz equality and extensional equalities coincide. *) (* (T ^ n)%type is notation for {ffun 'I_n -> T}, which is isomorphic *) (* to n.-tuple T, but is structurally positive and thus can be used to *) (* define inductive types, e.g., Inductive tree := node n of tree ^ n (see *) (* mid-file for an expanded example). *) (* --> More generally, {ffun fT} is always structurally positive. *) (* {ffun fT} inherits combinatorial structures of rT, i.e., eqType, *) (* choiceType, countType, and finType. However, due to some limitations of *) (* the Coq 8.9 unification code the structures are only inherited in the *) (* NON dependent case, when rT does not depend on x. *) (* For f : {ffun fT} with fT := forall x : aT, rT we define *) (* f x == the image of x under f (f coerces to a CiC function) *) (* --> The coercion is structurally decreasing, e.g., Coq will accept *) (* Fixpoint size t := let: node n f := t in sumn (codom (size \o f)) + 1. *) (* as structurally decreasing on t of the inductive tree type above. *) (* {dffun fT} == alias for {ffun fT} that inherits combinatorial *) (* structures on rT, when rT DOES depend on x. *) (* total_fun g == the function induced by a dependent function g of type *) (* forall x, rT on the total space {x : aT & rT}. *) (* := fun x => Tagged (fun x => rT) (g x). *) (* tfgraph f == the total function graph of f, i.e., the #|aT|.-tuple *) (* of all the (dependent pair) values of total_fun f. *) (* finfun g == the f extensionally equal to g, and the RECOMMENDED *) (* interface for building elements of {ffun fT}. *) (* [ffun x : aT => E] := finfun (fun x : aT => E). *) (* There should be an explicit type constraint on E if *) (* type does not depend on x, due to the Coq unification *) (* limitations referred to above. *) (* ffun0 aT0 == the trivial finfun, from a proof aT0 that #|aT| = 0. *) (* f \in family F == f belongs to the family F (f x \in F x for all x) *) (* There are additional operations for non-dependent finite functions, *) (* i.e., f in {ffun aT -> rT}. *) (* [ffun x => E] := finfun (fun x => E). *) (* The type of E must not depend on x; this restriction *) (* is a mitigation of the aforementioned Coq unification *) (* limitations. *) (* [ffun=> E] := [ffun _ => E] (E should not have a dependent type). *) (* fgraph f == the function graph of f, i.e., the #|aT|.-tuple *) (* listing the values of f x, for x ranging over enum aT. *) (* Finfun G == the finfun f whose (simple) function graph is G. *) (* f \in ffun_on R == the range of f is a subset of R. *) (* y.-support f == the y-support of f, i.e., [pred x | f x != y]. *) (* Thus, y.-support f \subset D means f has y-support D. *) (* We will put Notation support := 0.-support in ssralg. *) (* f \in pffun_on y D R == f is a y-partial function from D to R: *) (* f has y-support D and f x \in R for all x \in D. *) (* f \in pfamily y D F == f belongs to the y-partial family from D to F: *) (* f has y-support D and f x \in F x for all x \in D. *) (* fprod I T_ == alternative construct to {ffun forall i : I, T_ i} for *) (* the finite product of finTypes, in a set-theoretic way *) (* := Record fprod I T_ := FProd *) (* { fprod_fun : {ffun I -> {i : I & T_ i}} ; *) (* fprod_prop : [forall i : I, tag (fprod_fun i) == i] }. *) (* fprod I T_ is endowed with a finType structure and allow these operations: *) (* [fprod i : I => F] == the dependent fprod function built from fun i:I => F *) (* := fprod_of_fun (fun i : I => F) *) (* [fprod : I => F] == [fprod _ : I => F] *) (* [fprod i => F] == [fprod i : _ => F] *) (* [fprod => F] == [fprod _ : _ => F] *) (* These fprod terms coerce into vanilla dependent functions via the coercion *) (* fun_of_fprod I T_ : fprod I T_ -> (forall i : I, T_ i). *) (* We also define the mutual bijections: *) (* fprod_of_dffun : {dffun forall i : I, T_ i} -> fprod I T_ *) (* dffun_of_fprod : fprod I T_ -> {dffun forall i : I, T_ i} *) (* of_family_tagged_with : {x in family (tagged_with T_)} -> fprod I T_ *) (* to_family_tagged_with : fprod I T_ -> {x in family (tagged_with T_)} *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Section Def. Variables (aT : finType) (rT : aT -> Type). Inductive finfun_on : seq aT -> Type := | finfun_nil : finfun_on [::] | finfun_cons x s of rT x & finfun_on s : finfun_on (x :: s). Local Fixpoint finfun_rec (g : forall x, rT x) s : finfun_on s := if s is x1 :: s1 then finfun_cons (g x1) (finfun_rec g s1) else finfun_nil. Local Fixpoint fun_of_fin_rec x s (f_s : finfun_on s) : x \in s -> rT x := if f_s is finfun_cons x1 s1 y1 f_s1 then if eqP is ReflectT Dx in reflect _ Dxb return Dxb || (x \in s1) -> rT x then fun=> ecast x (rT x) (esym Dx) y1 else fun_of_fin_rec f_s1 else fun isF => False_rect (rT x) (notF isF). Variant finfun_of (ph : phant (forall x, rT x)) : predArgType := FinfunOf of finfun_on (enum aT). Definition dfinfun_of ph := finfun_of ph. Definition fun_of_fin ph (f : finfun_of ph) x := let: FinfunOf f_aT := f in fun_of_fin_rec f_aT (mem_enum aT x). End Def. Coercion fun_of_fin : finfun_of >-> Funclass. Identity Coercion unfold_dfinfun_of : dfinfun_of >-> finfun_of. Arguments fun_of_fin {aT rT ph} f x. Notation "{ 'ffun' fT }" := (finfun_of (Phant fT)) (format "{ 'ffun' '[hv' fT ']' }") : type_scope. Notation "{ 'dffun' fT }" := (dfinfun_of (Phant fT)) (format "{ 'dffun' '[hv' fT ']' }") : type_scope. Definition exp_finIndexType n : finType := 'I_n. Notation "T ^ n" := (@finfun_of (exp_finIndexType n) (fun=> T) (Phant _)) : type_scope. Local Notation finPi aT rT := (forall x : Finite.sort aT, rT x) (only parsing). HB.lock Definition finfun aT rT g := FinfunOf (Phant (finPi aT rT)) (finfun_rec g (enum aT)). Canonical finfun_unlock := Unlockable finfun.unlock. Arguments finfun {aT rT} g. Notation "[ 'ffun' x : aT => E ]" := (finfun (fun x : aT => E)) (x name) : function_scope. Notation "[ 'ffun' x => E ]" := (@finfun _ (fun=> _) (fun x => E)) (x name, format "[ 'ffun' x => E ]") : function_scope. Notation "[ 'ffun' => E ]" := [ffun _ => E] (format "[ 'ffun' => E ]") : function_scope. (* Example outcommented. (* Examples of using finite functions as containers in recursive inductive *) (* types, and making use of the fact that the type and accessor are *) (* structurally positive and decreasing, respectively. *) Unset Elimination Schemes. Inductive tree := node n of tree ^ n. Fixpoint size t := let: node n f := t in sumn (codom (size \o f)) + 1. Example tree_step (K : tree -> Type) := forall n st (t := node st) & forall i : 'I_n, K (st i), K t. Example tree_rect K (Kstep : tree_step K) : forall t, K t. Proof. by fix IHt 1 => -[n st]; apply/Kstep=> i; apply: IHt. Defined. (* An artificial example use of dependent functions. *) Inductive tri_tree n := tri_row of {ffun forall i : 'I_n, tri_tree i}. Fixpoint tri_size n (t : tri_tree n) := let: tri_row f := t in sumn [seq tri_size (f i) | i : 'I_n] + 1. Example tri_tree_step (K : forall n, tri_tree n -> Type) := forall n st (t := tri_row st) & forall i : 'I_n, K i (st i), K n t. Example tri_tree_rect K (Kstep : tri_tree_step K) : forall n t, K n t. Proof. by fix IHt 2 => n [st]; apply/Kstep=> i; apply: IHt. Defined. Set Elimination Schemes. (* End example. *) *) (* The correspondence between finfun_of and CiC dependent functions. *) Section DepPlainTheory. Variables (aT : finType) (rT : aT -> Type). Notation fT := {ffun finPi aT rT}. Implicit Type f : fT. Fact ffun0 (aT0 : #|aT| = 0) : fT. Proof. by apply/finfun=> x; have:= card0_eq aT0 x. Qed. Lemma ffunE g x : (finfun g : fT) x = g x. Proof. rewrite unlock /=; set s := enum aT; set s_x : mem_seq s x := mem_enum _ _. by elim: s s_x => //= x1 s IHs; case: eqP => [|_]; [case: x1 / | apply: IHs]. Qed. Lemma ffunP (f1 f2 : fT) : (forall x, f1 x = f2 x) <-> f1 = f2. Proof. suffices ffunK f g: (forall x, f x = g x) -> f = finfun g. by split=> [/ffunK|] -> //; apply/esym/ffunK. case: f => f Dg; rewrite unlock; congr FinfunOf. have{} Dg x (aTx : mem_seq (enum aT) x): g x = fun_of_fin_rec f aTx. by rewrite -Dg /= (bool_irrelevance (mem_enum _ _) aTx). elim: (enum aT) / f (enum_uniq aT) => //= x1 s y f IHf /andP[s'x1 Us] in Dg *. rewrite Dg ?eqxx //=; case: eqP => // /eq_axiomK-> /= _. rewrite {}IHf // => x s_x; rewrite Dg ?s_x ?orbT //. by case: eqP (memPn s'x1 x s_x) => // _ _ /(bool_irrelevance s_x) <-. Qed. Lemma ffunK : @cancel (finPi aT rT) fT fun_of_fin finfun. Proof. by move=> f; apply/ffunP=> x; rewrite ffunE. Qed. Lemma eq_dffun (g1 g2 : forall x, rT x) : (forall x, g1 x = g2 x) -> finfun g1 = finfun g2. Proof. by move=> eq_g; apply/ffunP => x; rewrite !ffunE eq_g. Qed. Definition total_fun g x := Tagged rT (g x : rT x). Definition tfgraph f := codom_tuple (total_fun f). Lemma codom_tffun f : codom (total_fun f) = tfgraph f. Proof. by []. Qed. Local Definition tfgraph_inv (G : #|aT|.-tuple {x : aT & rT x}) : option fT := if eqfunP isn't ReflectT Dtg then None else Some [ffun x => ecast x (rT x) (Dtg x) (tagged (tnth G (enum_rank x)))]. Local Lemma tfgraphK : pcancel tfgraph tfgraph_inv. Proof. move=> f; have Dg x: tnth (tfgraph f) (enum_rank x) = total_fun f x. by rewrite tnth_map -[tnth _ _]enum_val_nth enum_rankK. rewrite /tfgraph_inv; case: eqfunP => /= [Dtg | [] x]; last by rewrite Dg. congr (Some _); apply/ffunP=> x; rewrite ffunE. by rewrite Dg in (Dx := Dtg x) *; rewrite eq_axiomK. Qed. Lemma tfgraph_inj : injective tfgraph. Proof. exact: pcan_inj tfgraphK. Qed. Definition family_mem mF := [pred f : fT | [forall x, in_mem (f x) (mF x)]]. Variables (pT : forall x, predType (rT x)) (F : forall x, pT x). (* Helper for defining notation for function families. *) Local Definition fmem F x := mem (F x : pT x). Lemma familyP f : reflect (forall x, f x \in F x) (f \in family_mem (fmem F)). Proof. exact: forallP. Qed. End DepPlainTheory. Arguments ffunK {aT rT} f : rename. Arguments ffun0 {aT rT} aT0. Arguments eq_dffun {aT rT} [g1] g2 eq_g12. Arguments total_fun {aT rT} g x. Arguments tfgraph {aT rT} f. Arguments tfgraphK {aT rT} f : rename. Arguments tfgraph_inj {aT rT} [f1 f2] : rename. Arguments fmem {aT rT pT} F x /. Arguments familyP {aT rT pT F f}. Notation family F := (family_mem (fmem F)). Section InheritedStructures. Variable aT : finType. Notation dffun_aT rT rS := {dffun forall x : aT, rT x : rS}. #[hnf] HB.instance Definition _ rT := Equality.copy (dffun_aT rT eqType) (pcan_type tfgraphK). #[hnf] HB.instance Definition _ (rT : eqType) := Equality.copy {ffun aT -> rT} {dffun forall _, rT}. #[hnf] HB.instance Definition _ rT := Choice.copy (dffun_aT rT choiceType) (pcan_type tfgraphK). #[hnf] HB.instance Definition _ (rT : choiceType) := Choice.copy {ffun aT -> rT} {dffun forall _, rT}. #[hnf] HB.instance Definition _ rT := Countable.copy (dffun_aT rT countType) (pcan_type tfgraphK). #[hnf] HB.instance Definition _ (rT : countType) := Countable.copy {ffun aT -> rT} {dffun forall _, rT}. #[hnf] HB.instance Definition _ rT := Finite.copy (dffun_aT rT finType) (pcan_type tfgraphK). #[hnf] HB.instance Definition _ (rT : finType) := Finite.copy {ffun aT -> rT} {dffun forall _, rT}. End InheritedStructures. Section FinFunTuple. Context {T : Type} {n : nat}. Definition tuple_of_finfun (f : T ^ n) : n.-tuple T := [tuple f i | i < n]. Definition finfun_of_tuple (t : n.-tuple T) : (T ^ n) := [ffun i => tnth t i]. Lemma finfun_of_tupleK : cancel finfun_of_tuple tuple_of_finfun. Proof. by move=> t; apply: eq_from_tnth => i; rewrite tnth_map ffunE tnth_ord_tuple. Qed. Lemma tuple_of_finfunK : cancel tuple_of_finfun finfun_of_tuple. Proof. by move=> f; apply/ffunP => i; rewrite ffunE tnth_map tnth_ord_tuple. Qed. End FinFunTuple. Section FunPlainTheory. Variables (aT : finType) (rT : Type). Notation fT := {ffun aT -> rT}. Implicit Types (f : fT) (R : pred rT). Definition fgraph f := codom_tuple f. Definition Finfun (G : #|aT|.-tuple rT) := [ffun x => tnth G (enum_rank x)]. Lemma tnth_fgraph f i : tnth (fgraph f) i = f (enum_val i). Proof. by rewrite tnth_map /tnth -enum_val_nth. Qed. Lemma FinfunK : cancel Finfun fgraph. Proof. by move=> G; apply/eq_from_tnth=> i; rewrite tnth_fgraph ffunE enum_valK. Qed. Lemma fgraphK : cancel fgraph Finfun. Proof. by move=> f; apply/ffunP=> x; rewrite ffunE tnth_fgraph enum_rankK. Qed. Lemma fgraph_ffun0 aT0 : fgraph (ffun0 aT0) = nil :> seq rT. Proof. by apply/nilP/eqP; rewrite size_tuple. Qed. Lemma codom_ffun f : codom f = fgraph f. Proof. by []. Qed. Lemma tagged_tfgraph f : @map _ rT tagged (tfgraph f) = fgraph f. Proof. by rewrite -map_comp. Qed. Lemma eq_ffun (g1 g2 : aT -> rT) : g1 =1 g2 -> finfun g1 = finfun g2. Proof. exact: eq_dffun. Qed. Lemma fgraph_codom f : fgraph f = codom_tuple f. Proof. exact/esym/val_inj/codom_ffun. Qed. Definition ffun_on_mem (mR : mem_pred rT) := family_mem (fun _ : aT => mR). Lemma ffun_onP R f : reflect (forall x, f x \in R) (f \in ffun_on_mem (mem R)). Proof. exact: forallP. Qed. End FunPlainTheory. Arguments Finfun {aT rT} G. Arguments fgraph {aT rT} f. Arguments FinfunK {aT rT} G : rename. Arguments fgraphK {aT rT} f : rename. Arguments eq_ffun {aT rT} [g1] g2 eq_g12. Arguments ffun_onP {aT rT R f}. Notation ffun_on R := (ffun_on_mem _ (mem R)). Notation "@ 'ffun_on' aT R" := (ffun_on R : simpl_pred (finfun_of (Phant (aT -> id _)))) (at level 10, aT, R at level 9). Lemma nth_fgraph_ord T n (x0 : T) (i : 'I_n) f : nth x0 (fgraph f) i = f i. Proof. by rewrite -[i in RHS]enum_rankK -tnth_fgraph (tnth_nth x0) enum_rank_ord. Qed. (*****************************************************************************) Section Support. Variables (aT : Type) (rT : eqType). Definition support_for y (f : aT -> rT) := [pred x | f x != y]. Lemma supportE x y f : (x \in support_for y f) = (f x != y). Proof. by []. Qed. End Support. Notation "y .-support" := (support_for y) (at level 1, format "y .-support") : function_scope. Section EqTheory. Variables (aT : finType) (rT : eqType). Notation fT := {ffun aT -> rT}. Implicit Types (y : rT) (D : {pred aT}) (R : {pred rT}) (f : fT). Lemma supportP y D g : reflect (forall x, x \notin D -> g x = y) (y.-support g \subset D). Proof. by (apply: (iffP subsetP) => Dg x; [apply: contraNeq|apply: contraR]) => /Dg->. Qed. Definition pfamily_mem y mD (mF : aT -> mem_pred rT) := family (fun i : aT => if in_mem i mD then pred_of_simpl (mF i) else pred1 y). Lemma pfamilyP (pT : predType rT) y D (F : aT -> pT) f : reflect (y.-support f \subset D /\ {in D, forall x, f x \in F x}) (f \in pfamily_mem y (mem D) (fmem F)). Proof. apply: (iffP familyP) => [/= f_pfam | [/supportP f_supp f_fam] x]. split=> [|x Ax]; last by have:= f_pfam x; rewrite Ax. by apply/subsetP=> x; case: ifP (f_pfam x) => //= _ fx0 /negP[]. by case: ifPn => Ax /=; rewrite inE /= (f_fam, f_supp). Qed. Definition pffun_on_mem y mD mR := pfamily_mem y mD (fun _ => mR). Lemma pffun_onP y D R f : reflect (y.-support f \subset D /\ {subset image f D <= R}) (f \in pffun_on_mem y (mem D) (mem R)). Proof. apply: (iffP (pfamilyP y D (fun _ => R) f)) => [] [-> f_fam]; split=> //. by move=> _ /imageP[x Ax ->]; apply: f_fam. by move=> x Ax; apply: f_fam; apply/imageP; exists x. Qed. End EqTheory. Arguments supportP {aT rT y D g}. Arguments pfamilyP {aT rT pT y D F f}. Arguments pffun_onP {aT rT y D R f}. Notation pfamily y D F := (pfamily_mem y (mem D) (fmem F)). Notation pffun_on y D R := (pffun_on_mem y (mem D) (mem R)). (*****************************************************************************) Section FinDepTheory. Variables (aT : finType) (rT : aT -> finType). Notation fT := {dffun forall x : aT, rT x}. Lemma card_family (F : forall x, pred (rT x)) : #|(family F : simpl_pred fT)| = foldr muln 1 [seq #|F x| | x : aT]. Proof. rewrite /image_mem; set E := enum aT in (uniqE := enum_uniq aT) *. have trivF x: x \notin E -> #|F x| = 1 by rewrite mem_enum. elim: E uniqE => /= [_ | x0 E IH_E /andP[E'x0 uniqE]] in F trivF *. have /fin_all_exists[f0 Ff0] x: exists y0, F x =i pred1 y0. have /pred0Pn[y Fy]: #|F x| != 0 by rewrite trivF. by exists y; apply/fsym/subset_cardP; rewrite ?subset_pred1 // card1 trivF. apply: eq_card1 (finfun f0 : fT) _ _ => f; apply/familyP/eqP=> [Ff | {f}-> x]. by apply/ffunP=> x; have /[!(Ff0, ffunE)]/eqP := Ff x. by rewrite ffunE Ff0 inE /=. have [y0 Fxy0 | Fx00] := pickP (F x0); last first. by rewrite !eq_card0 // => f; apply: contraFF (Fx00 (f x0))=> /familyP; apply. pose F1 x := if eqP is ReflectT Dx then xpred1 (ecast x (rT x) Dx y0) else F x. transitivity (#|[predX F x0 & family F1 : pred fT]|); last first. rewrite cardX {}IH_E {uniqE}// => [|x E'x]; last first. rewrite /F1; case: eqP => [Dx | /nesym/eqP-x0'x]; first exact: card1. by rewrite trivF // negb_or x0'x. congr (_ * foldr _ _ _); apply/eq_in_map=> x Ex. by rewrite /F1; case: eqP => // Dx0; rewrite Dx0 Ex in E'x0. pose g yf : fT := let: (y, f) := yf : rT x0 * fT in [ffun x => if eqP is ReflectT Dx then ecast x (rT x) Dx y else f x]. have gK: cancel (fun f : fT => (f x0, g (y0, f))) g. by move=> f; apply/ffunP=> x; rewrite !ffunE; case: eqP => //; case: x /. rewrite -(card_image (can_inj gK)); apply: eq_card => [] [y f] /=. apply/imageP/andP=> [[f1 /familyP/=Ff1] [-> ->]| [/=Fx0y /familyP/=Ff]]. split=> //; apply/familyP=> x; rewrite ffunE /F1 /=. by case: eqP => // Dx; apply: eqxx. exists (g (y, f)). by apply/familyP=> x; have:= Ff x; rewrite ffunE /F1; case: eqP; [case: x /|]. congr (_, _); first by rewrite /= ffunE; case: eqP => // Dx; rewrite eq_axiomK. by apply/ffunP=> x; have:= Ff x; rewrite !ffunE /F1; case: eqP => // Dx /eqP. Qed. Lemma card_dep_ffun : #|fT| = foldr muln 1 [seq #|rT x| | x : aT]. Proof. by rewrite -card_family; apply/esym/eq_card=> f; apply/familyP. Qed. End FinDepTheory. Section FinFunTheory. Variables aT rT : finType. Notation fT := {ffun aT -> rT}. Implicit Types (D : {pred aT}) (R : {pred rT}) (F : aT -> pred rT). Lemma card_pfamily y0 D F : #|pfamily y0 D F| = foldr muln 1 [seq #|F x| | x in D]. Proof. rewrite card_family !/(image _ _) /(enum D) -enumT /=. by elim: (enum aT) => //= x E ->; have [// | D'x] := ifP; rewrite card1 mul1n. Qed. Lemma card_pffun_on y0 D R : #|pffun_on y0 D R| = #|R| ^ #|D|. Proof. rewrite (cardE D) card_pfamily /image_mem. by elim: (enum D) => //= _ e ->; rewrite expnS. Qed. Lemma card_ffun_on R : #|@ffun_on aT R| = #|R| ^ #|aT|. Proof. rewrite card_family /image_mem cardT. by elim: (enum aT) => //= _ e ->; rewrite expnS. Qed. Lemma card_ffun : #|fT| = #|rT| ^ #|aT|. Proof. by rewrite -card_ffun_on; apply/esym/eq_card=> f; apply/forallP. Qed. End FinFunTheory. Section DependentFiniteProduct. Variables (I : finType) (T_ : I -> finType). Notation fprod_type := (forall i : I, T_ i) (only parsing). (* Definition of [fprod] := dependent product of finTypes *) Record fprod : predArgType := FProd { fprod_fun : {ffun I -> {i : I & T_ i}} ; fprod_prop : [forall i : I, tag (fprod_fun i) == i] }. Lemma tag_fprod_fun (f : fprod) i : tag (fprod_fun f i) = i. Proof. by have /'forall_eqP/(_ i) := fprod_prop f. Qed. Definition fun_of_fprod (f : fprod) : fprod_type := fun i => etagged ('forall_eqP (fprod_prop f) i). Coercion fun_of_fprod : fprod >-> Funclass. #[hnf] HB.instance Definition _ := [isSub for fprod_fun]. #[hnf] HB.instance Definition _ := [Finite of fprod by <:]. Lemma fprod_of_prod_type_subproof (f : fprod_type) : [forall i : I, tag ([ffun i => Tagged T_ (f i)] i) == i]. Proof. by apply/'forall_eqP => i /=; rewrite ffunE. Qed. Definition fprod_of_fun (f : fprod_type) : fprod := FProd (fprod_of_prod_type_subproof f). Lemma fprodK : cancel fun_of_fprod fprod_of_fun. Proof. rewrite /fun_of_fprod /fprod_of_fun; case=> f fP. by apply/val_inj/ffunP => i /=; rewrite !ffunE etaggedK. Qed. Lemma fprodE g i : fprod_of_fun g i = g i. Proof. rewrite /fprod_of_fun /fun_of_fprod/=. by move: ('forall_eqP _ _); rewrite ffunE/= => e; rewrite eq_axiomK. Qed. Lemma fprodP (f1 f2 : fprod) : (forall x, f1 x = f2 x) <-> f1 = f2. Proof. split=> [eq_f12|->//]; rewrite -[f1]fprodK -[f2]fprodK. by apply/val_inj/ffunP => i; rewrite !ffunE eq_f12. Qed. Definition dffun_of_fprod (f : fprod) : {dffun forall i : I, T_ i} := [ffun x => f x]. Definition fprod_of_dffun (f : {dffun forall i : I, T_ i}) : fprod := fprod_of_fun f. Lemma dffun_of_fprodK : cancel dffun_of_fprod fprod_of_dffun. Proof. by move=> f; apply/fprodP=> i; rewrite fprodE ffunE. Qed. #[local] Hint Resolve dffun_of_fprodK : core. Lemma fprod_of_dffunK : cancel fprod_of_dffun dffun_of_fprod. Proof. by move=> f; apply/ffunP => i; rewrite !ffunE fprodE. Qed. #[local] Hint Resolve fprod_of_dffunK : core. Lemma dffun_of_fprod_bij : bijective dffun_of_fprod. Proof. by exists fprod_of_dffun. Qed. Lemma fprod_of_dffun_bij : bijective fprod_of_dffun. Proof. by exists dffun_of_fprod. Qed. Definition to_family_tagged_with (f : fprod) : {x in family (tagged_with T_)} := exist _ (fprod_fun f) (fprod_prop f). Definition of_family_tagged_with (f : {x in family (tagged_with T_)}) : fprod := FProd (valP f). Lemma to_family_tagged_withK : cancel to_family_tagged_with of_family_tagged_with. Proof. by case=> f fP; apply/val_inj. Qed. #[local] Hint Resolve to_family_tagged_withK : core. Lemma of_family_tagged_withK : cancel of_family_tagged_with to_family_tagged_with. Proof. by case=> f fP; apply/val_inj. Qed. #[local] Hint Resolve of_family_tagged_withK : core. Lemma to_family_tagged_with_bij : bijective to_family_tagged_with. Proof. by exists of_family_tagged_with. Qed. Lemma of_family_tagged_with_bij : bijective of_family_tagged_with. Proof. by exists to_family_tagged_with. Qed. Lemma etaggedE (a : fprod) (i : I) (e : tag (fprod_fun a i) = i) : etagged e = a i. Proof. by case: a e => //= f fP e; congr etagged; apply: eq_irrelevance. Qed. End DependentFiniteProduct. Arguments to_family_tagged_with {I T_}. Arguments of_family_tagged_with {I T_}. Notation "[ 'fprod' i : I => F ]" := (fprod_of_fun (fun i : I => F)) (i name, only parsing) : function_scope. Notation "[ 'fprod' : I => F ]" := (fprod_of_fun (fun _ : I => F)) (only parsing) : function_scope. Notation "[ 'fprod' i => F ]" := [fprod i : _ => F] (i name, format "[ 'fprod' i => F ]") : function_scope. Notation "[ 'fprod' => F ]" := [fprod : _ => F] (format "[ 'fprod' => F ]") : function_scope.
Basic.lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.Analysis.Calculus.ContDiff.Operations import Mathlib.Analysis.Normed.Module.FiniteDimension /-! # Infinitely smooth "bump" functions A smooth bump function is an infinitely smooth function `f : E → ℝ` supported on a ball that is equal to `1` on a ball of smaller radius. These functions have many uses in real analysis. E.g., - they can be used to construct a smooth partition of unity which is a very useful tool; - they can be used to approximate a continuous function by infinitely smooth functions. There are two classes of spaces where bump functions are guaranteed to exist: inner product spaces and finite dimensional spaces. In this file we define a typeclass `HasContDiffBump` saying that a normed space has a family of smooth bump functions with certain properties. We also define a structure `ContDiffBump` that holds the center and radii of the balls from above. An element `f : ContDiffBump c` can be coerced to a function which is an infinitely smooth function such that - `f` is equal to `1` in `Metric.closedBall c f.rIn`; - `support f = Metric.ball c f.rOut`; - `0 ≤ f x ≤ 1` for all `x`. ## Main Definitions - `ContDiffBump (c : E)`: a structure holding data needed to construct an infinitely smooth bump function. - `ContDiffBumpBase (E : Type*)`: a family of infinitely smooth bump functions that can be used to construct coercion of a `ContDiffBump (c : E)` to a function. - `HasContDiffBump (E : Type*)`: a typeclass saying that `E` has a `ContDiffBumpBase`. Two instances of this typeclass (for inner product spaces and for finite dimensional spaces) are provided elsewhere. ## Keywords smooth function, smooth bump function -/ noncomputable section open Function Set Filter open scoped Topology Filter ContDiff variable {E X : Type*} /-- `f : ContDiffBump c`, where `c` is a point in a normed vector space, is a bundled smooth function such that - `f` is equal to `1` in `Metric.closedBall c f.rIn`; - `support f = Metric.ball c f.rOut`; - `0 ≤ f x ≤ 1` for all `x`. The structure `ContDiffBump` contains the data required to construct the function: real numbers `rIn`, `rOut`, and proofs of `0 < rIn < rOut`. The function itself is available through `CoeFun` when the space is nice enough, i.e., satisfies the `HasContDiffBump` typeclass. -/ structure ContDiffBump (c : E) where /-- real numbers `0 < rIn < rOut` -/ (rIn rOut : ℝ) rIn_pos : 0 < rIn rIn_lt_rOut : rIn < rOut /-- The base function from which one will construct a family of bump functions. One could add more properties if they are useful and satisfied in the examples of inner product spaces and finite dimensional vector spaces, notably derivative norm control in terms of `R - 1`. TODO: do we ever need `f x = 1 ↔ ‖x‖ ≤ 1`? -/ structure ContDiffBumpBase (E : Type*) [NormedAddCommGroup E] [NormedSpace ℝ E] where /-- The function underlying this family of bump functions -/ toFun : ℝ → E → ℝ mem_Icc : ∀ (R : ℝ) (x : E), toFun R x ∈ Icc (0 : ℝ) 1 symmetric : ∀ (R : ℝ) (x : E), toFun R (-x) = toFun R x smooth : ContDiffOn ℝ ∞ (uncurry toFun) (Ioi (1 : ℝ) ×ˢ (univ : Set E)) eq_one : ∀ R : ℝ, 1 < R → ∀ x : E, ‖x‖ ≤ 1 → toFun R x = 1 support : ∀ R : ℝ, 1 < R → Function.support (toFun R) = Metric.ball (0 : E) R /-- A class registering that a real vector space admits bump functions. This will be instantiated first for inner product spaces, and then for finite-dimensional normed spaces. We use a specific class instead of `Nonempty (ContDiffBumpBase E)` for performance reasons. -/ class HasContDiffBump (E : Type*) [NormedAddCommGroup E] [NormedSpace ℝ E] : Prop where out : Nonempty (ContDiffBumpBase E) /-- In a space with `C^∞` bump functions, register some function that will be used as a basis to construct bump functions of arbitrary size around any point. -/ def someContDiffBumpBase (E : Type*) [NormedAddCommGroup E] [NormedSpace ℝ E] [hb : HasContDiffBump E] : ContDiffBumpBase E := Nonempty.some hb.out namespace ContDiffBump theorem rOut_pos {c : E} (f : ContDiffBump c) : 0 < f.rOut := f.rIn_pos.trans f.rIn_lt_rOut theorem one_lt_rOut_div_rIn {c : E} (f : ContDiffBump c) : 1 < f.rOut / f.rIn := by rw [one_lt_div f.rIn_pos] exact f.rIn_lt_rOut instance (c : E) : Inhabited (ContDiffBump c) := ⟨⟨1, 2, zero_lt_one, one_lt_two⟩⟩ variable [NormedAddCommGroup E] [NormedSpace ℝ E] [NormedAddCommGroup X] [NormedSpace ℝ X] [HasContDiffBump E] {c : E} (f : ContDiffBump c) {x : E} {n : ℕ∞} /-- The function defined by `f : ContDiffBump c`. Use automatic coercion to function instead. -/ @[coe] def toFun {c : E} (f : ContDiffBump c) : E → ℝ := (someContDiffBumpBase E).toFun (f.rOut / f.rIn) ∘ fun x ↦ (f.rIn⁻¹ • (x - c)) instance : CoeFun (ContDiffBump c) fun _ => E → ℝ := ⟨toFun⟩ protected theorem apply (x : E) : f x = (someContDiffBumpBase E).toFun (f.rOut / f.rIn) (f.rIn⁻¹ • (x - c)) := rfl protected theorem sub (x : E) : f (c - x) = f (c + x) := by simp [f.apply, ContDiffBumpBase.symmetric] protected theorem neg (f : ContDiffBump (0 : E)) (x : E) : f (-x) = f x := by simp_rw [← zero_sub, f.sub, zero_add] open Metric theorem one_of_mem_closedBall (hx : x ∈ closedBall c f.rIn) : f x = 1 := by apply ContDiffBumpBase.eq_one _ _ f.one_lt_rOut_div_rIn simpa only [norm_smul, Real.norm_eq_abs, abs_inv, abs_of_nonneg f.rIn_pos.le, ← div_eq_inv_mul, div_le_one f.rIn_pos] using mem_closedBall_iff_norm.1 hx theorem nonneg : 0 ≤ f x := (ContDiffBumpBase.mem_Icc (someContDiffBumpBase E) _ _).1 /-- A version of `ContDiffBump.nonneg` with `x` explicit -/ theorem nonneg' (x : E) : 0 ≤ f x := f.nonneg theorem le_one : f x ≤ 1 := (ContDiffBumpBase.mem_Icc (someContDiffBumpBase E) _ _).2 theorem support_eq : Function.support f = Metric.ball c f.rOut := by simp only [toFun, support_comp_eq_preimage, ContDiffBumpBase.support _ _ f.one_lt_rOut_div_rIn] ext x simp only [mem_ball_iff_norm, sub_zero, norm_smul, mem_preimage, Real.norm_eq_abs, abs_inv, abs_of_pos f.rIn_pos, ← div_eq_inv_mul, div_lt_div_iff_of_pos_right f.rIn_pos] theorem tsupport_eq : tsupport f = closedBall c f.rOut := by simp_rw [tsupport, f.support_eq, closure_ball _ f.rOut_pos.ne'] theorem pos_of_mem_ball (hx : x ∈ ball c f.rOut) : 0 < f x := f.nonneg.lt_of_ne' <| by rwa [← support_eq, mem_support] at hx theorem zero_of_le_dist (hx : f.rOut ≤ dist x c) : f x = 0 := by rwa [← notMem_support, support_eq, mem_ball, not_lt] protected theorem hasCompactSupport [FiniteDimensional ℝ E] : HasCompactSupport f := by simp_rw [HasCompactSupport, f.tsupport_eq, isCompact_closedBall] theorem eventuallyEq_one_of_mem_ball (h : x ∈ ball c f.rIn) : f =ᶠ[𝓝 x] 1 := mem_of_superset (closedBall_mem_nhds_of_mem h) fun _ ↦ f.one_of_mem_closedBall theorem eventuallyEq_one : f =ᶠ[𝓝 c] 1 := f.eventuallyEq_one_of_mem_ball (mem_ball_self f.rIn_pos) /-- `ContDiffBump` is `𝒞ⁿ` in all its arguments. -/ protected theorem _root_.ContDiffWithinAt.contDiffBump {c g : X → E} {s : Set X} {f : ∀ x, ContDiffBump (c x)} {x : X} (hc : ContDiffWithinAt ℝ n c s x) (hr : ContDiffWithinAt ℝ n (fun x => (f x).rIn) s x) (hR : ContDiffWithinAt ℝ n (fun x => (f x).rOut) s x) (hg : ContDiffWithinAt ℝ n g s x) : ContDiffWithinAt ℝ n (fun x => f x (g x)) s x := by change ContDiffWithinAt ℝ n (uncurry (someContDiffBumpBase E).toFun ∘ fun x : X => ((f x).rOut / (f x).rIn, (f x).rIn⁻¹ • (g x - c x))) s x refine (((someContDiffBumpBase E).smooth.contDiffAt ?_).of_le (mod_cast le_top)).comp_contDiffWithinAt x ?_ · exact prod_mem_nhds (Ioi_mem_nhds (f x).one_lt_rOut_div_rIn) univ_mem · exact (hR.div hr (f x).rIn_pos.ne').prodMk ((hr.inv (f x).rIn_pos.ne').smul (hg.sub hc)) /-- `ContDiffBump` is `𝒞ⁿ` in all its arguments. -/ protected nonrec theorem _root_.ContDiffAt.contDiffBump {c g : X → E} {f : ∀ x, ContDiffBump (c x)} {x : X} (hc : ContDiffAt ℝ n c x) (hr : ContDiffAt ℝ n (fun x => (f x).rIn) x) (hR : ContDiffAt ℝ n (fun x => (f x).rOut) x) (hg : ContDiffAt ℝ n g x) : ContDiffAt ℝ n (fun x => f x (g x)) x := hc.contDiffBump hr hR hg theorem _root_.ContDiff.contDiffBump {c g : X → E} {f : ∀ x, ContDiffBump (c x)} (hc : ContDiff ℝ n c) (hr : ContDiff ℝ n fun x => (f x).rIn) (hR : ContDiff ℝ n fun x => (f x).rOut) (hg : ContDiff ℝ n g) : ContDiff ℝ n fun x => f x (g x) := by rw [contDiff_iff_contDiffAt] at * exact fun x => (hc x).contDiffBump (hr x) (hR x) (hg x) protected theorem contDiff : ContDiff ℝ n f := contDiff_const.contDiffBump contDiff_const contDiff_const contDiff_id protected theorem contDiffAt : ContDiffAt ℝ n f x := f.contDiff.contDiffAt protected theorem contDiffWithinAt {s : Set E} : ContDiffWithinAt ℝ n f s x := f.contDiffAt.contDiffWithinAt protected theorem continuous : Continuous f := contDiff_zero.mp f.contDiff end ContDiffBump
vcharacter.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path. From mathcomp Require Import div choice fintype tuple finfun bigop prime order. From mathcomp Require Import ssralg poly finset fingroup morphism perm. From mathcomp Require Import automorphism quotient finalg action gproduct. From mathcomp Require Import zmodp commutator cyclic center pgroup sylow. From mathcomp Require Import frobenius vector ssrnum ssrint archimedean intdiv. From mathcomp Require Import algC algnum classfun character integral_char. (******************************************************************************) (* This file provides basic notions of virtual character theory: *) (* 'Z[S, A] == collective predicate for the phi that are Z-linear *) (* combinations of elements of S : seq 'CF(G) and have *) (* support in A : {set gT}. *) (* 'Z[S] == collective predicate for the Z-linear combinations of *) (* elements of S. *) (* 'Z[irr G] == the collective predicate for virtual characters. *) (* dirr G == the collective predicate for normal virtual characters, *) (* i.e., virtual characters of norm 1: *) (* mu \in dirr G <=> m \in 'Z[irr G] and '[mu] = 1 *) (* <=> mu or - mu \in irr G. *) (* --> othonormal subsets of 'Z[irr G] are contained in dirr G. *) (* dIirr G == an index type for normal virtual characters. *) (* dchi i == the normal virtual character of index i. *) (* of_irr i == the (unique) irreducible constituent of dchi i: *) (* dchi i = 'chi_(of_irr i) or - 'chi_(of_irr i). *) (* ndirr i == the index of - dchi i. *) (* dirr1 G == the normal virtual character index of 1 : 'CF(G), the *) (* principal character. *) (* dirr_dIirr j f == the index i (or dirr1 G if it does not exist) such that *) (* dchi i = f j. *) (* dirr_constt phi == the normal virtual character constituents of phi: *) (* i \in dirr_constt phi <=> [dchi i, phi] > 0. *) (* to_dirr phi i == the normal virtual character constituent of phi with an *) (* irreducible constituent i, when i \in irr_constt phi. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import Order.TTheory GroupScope GRing.Theory Num.Theory. Local Open Scope ring_scope. Section Basics. Variables (gT : finGroupType) (B : {set gT}) (S : seq 'CF(B)) (A : {set gT}). Definition Zchar : {pred 'CF(B)} := [pred phi in 'CF(B, A) | dec_Cint_span (in_tuple S) phi]. Lemma cfun0_zchar : 0 \in Zchar. Proof. rewrite inE mem0v; apply/sumboolP; exists 0. by rewrite big1 // => i _; rewrite ffunE. Qed. Fact Zchar_zmod : zmod_closed Zchar. Proof. split; first exact: cfun0_zchar. move=> phi xi /andP[Aphi /sumboolP[a Da]] /andP[Axi /sumboolP[b Db]]. rewrite inE rpredB // Da Db -sumrB; apply/sumboolP; exists (a - b). by apply: eq_bigr => i _; rewrite -mulrzBr !ffunE. Qed. HB.instance Definition _ := GRing.isZmodClosed.Build (classfun B) Zchar Zchar_zmod. Lemma scale_zchar a phi : a \in Num.int -> phi \in Zchar -> a *: phi \in Zchar. Proof. by case/intrP=> m -> Zphi; rewrite scaler_int rpredMz. Qed. End Basics. Notation "''Z[' S , A ]" := (Zchar S A) (format "''Z[' S , A ]") : group_scope. Notation "''Z[' S ]" := 'Z[S, setT] (format "''Z[' S ]") : group_scope. Section Zchar. Variables (gT : finGroupType) (G : {group gT}). Implicit Types (A B : {set gT}) (S : seq 'CF(G)). Lemma zchar_split S A phi : phi \in 'Z[S, A] = (phi \in 'Z[S]) && (phi \in 'CF(G, A)). Proof. by rewrite !inE cfun_onT andbC. Qed. Lemma zcharD1E phi S : (phi \in 'Z[S, G^#]) = (phi \in 'Z[S]) && (phi 1%g == 0). Proof. by rewrite zchar_split cfunD1E. Qed. Lemma zcharD1 phi S A : (phi \in 'Z[S, A^#]) = (phi \in 'Z[S, A]) && (phi 1%g == 0). Proof. by rewrite zchar_split cfun_onD1 andbA -zchar_split. Qed. Lemma zcharW S A : {subset 'Z[S, A] <= 'Z[S]}. Proof. by move=> phi; rewrite zchar_split => /andP[]. Qed. Lemma zchar_on S A : {subset 'Z[S, A] <= 'CF(G, A)}. Proof. by move=> phi /andP[]. Qed. Lemma zchar_onS A B S : A \subset B -> {subset 'Z[S, A] <= 'Z[S, B]}. Proof. move=> sAB phi; rewrite zchar_split (zchar_split _ B) => /andP[->]. exact: cfun_onS. Qed. Lemma zchar_onG S : 'Z[S, G] =i 'Z[S]. Proof. by move=> phi; rewrite zchar_split cfun_onG andbT. Qed. Lemma irr_vchar_on A : {subset 'Z[irr G, A] <= 'CF(G, A)}. Proof. exact: zchar_on. Qed. Lemma support_zchar S A phi : phi \in 'Z[S, A] -> support phi \subset A. Proof. by move/zchar_on; rewrite cfun_onE. Qed. Lemma mem_zchar_on S A phi : phi \in 'CF(G, A) -> phi \in S -> phi \in 'Z[S, A]. Proof. move=> Aphi /(@tnthP _ _ (in_tuple S))[i Dphi]; rewrite inE /= {}Aphi {phi}Dphi. apply/sumboolP; exists [ffun j => (j == i)%:Z]. rewrite (bigD1 i) //= ffunE eqxx (tnth_nth 0) big1 ?addr0 // => j i'j. by rewrite ffunE (negPf i'j). Qed. (* A special lemma is needed because trivial fails to use the cfun_onT Hint. *) Lemma mem_zchar S phi : phi \in S -> phi \in 'Z[S]. Proof. by move=> Sphi; rewrite mem_zchar_on ?cfun_onT. Qed. Lemma zchar_nth_expansion S A phi : phi \in 'Z[S, A] -> {z | forall i, z i \in Num.int & phi = \sum_(i < size S) z i *: S`_i}. Proof. case/andP=> _ /sumboolP/sig_eqW[/= z ->]; exists (intr \o z) => //=. by apply: eq_bigr => i _; rewrite scaler_int. Qed. Lemma zchar_tuple_expansion n (S : n.-tuple 'CF(G)) A phi : phi \in 'Z[S, A] -> {z | forall i, z i \in Num.int & phi = \sum_(i < n) z i *: S`_i}. Proof. by move/zchar_nth_expansion; rewrite size_tuple. Qed. (* A pure seq version with the extra hypothesis of S's unicity. *) Lemma zchar_expansion S A phi : uniq S -> phi \in 'Z[S, A] -> {z | forall xi, z xi \in Num.int & phi = \sum_(xi <- S) z xi *: xi}. Proof. move=> Suniq /zchar_nth_expansion[z Zz ->] /=. pose zS xi := oapp z 0 (insub (index xi S)). exists zS => [xi | ]; rewrite {}/zS; first by case: (insub _) => /=. rewrite (big_nth 0) big_mkord; apply: eq_bigr => i _; congr (_ *: _). by rewrite index_uniq // valK. Qed. Lemma zchar_span S A : {subset 'Z[S, A] <= <<S>>%VS}. Proof. move=> _ /zchar_nth_expansion[z Zz ->] /=. by apply: rpred_sum => i _; rewrite rpredZ // memv_span ?mem_nth. Qed. Lemma zchar_trans S1 S2 A B : {subset S1 <= 'Z[S2, B]} -> {subset 'Z[S1, A] <= 'Z[S2, A]}. Proof. move=> sS12 phi; rewrite !(zchar_split _ A) andbC => /andP[->]; rewrite andbT. case/zchar_nth_expansion=> z Zz ->; apply: rpred_sum => i _. by rewrite scale_zchar // (@zcharW _ B) ?sS12 ?mem_nth. Qed. Lemma zchar_trans_on S1 S2 A : {subset S1 <= 'Z[S2, A]} -> {subset 'Z[S1] <= 'Z[S2, A]}. Proof. move=> sS12 _ /zchar_nth_expansion[z Zz ->]; apply: rpred_sum => i _. by rewrite scale_zchar // sS12 ?mem_nth. Qed. Lemma zchar_sub_irr S A : {subset S <= 'Z[irr G]} -> {subset 'Z[S, A] <= 'Z[irr G, A]}. Proof. exact: zchar_trans. Qed. Lemma zchar_subset S1 S2 A : {subset S1 <= S2} -> {subset 'Z[S1, A] <= 'Z[S2, A]}. Proof. move=> sS12; apply: zchar_trans setT _ => // f /sS12 S2f. by rewrite mem_zchar. Qed. Lemma zchar_subseq S1 S2 A : subseq S1 S2 -> {subset 'Z[S1, A] <= 'Z[S2, A]}. Proof. by move/mem_subseq; apply: zchar_subset. Qed. Lemma zchar_filter S A (p : pred 'CF(G)) : {subset 'Z[filter p S, A] <= 'Z[S, A]}. Proof. by apply: zchar_subset=> f; apply/mem_subseq/filter_subseq. Qed. End Zchar. Section VChar. Variables (gT : finGroupType) (G : {group gT}). Implicit Types (A B : {set gT}) (phi chi : 'CF(G)) (S : seq 'CF(G)). Lemma char_vchar chi : chi \is a character -> chi \in 'Z[irr G]. Proof. case/char_sum_irr=> r ->; apply: rpred_sum => i _. by rewrite mem_zchar ?mem_tnth. Qed. Lemma irr_vchar i : 'chi[G]_i \in 'Z[irr G]. Proof. exact/char_vchar/irr_char. Qed. Lemma cfun1_vchar : 1 \in 'Z[irr G]. Proof. by rewrite -irr0 irr_vchar. Qed. Lemma vcharP phi : reflect (exists2 chi1, chi1 \is a character & exists2 chi2, chi2 \is a character & phi = chi1 - chi2) (phi \in 'Z[irr G]). Proof. apply: (iffP idP) => [| [a Na [b Nb ->]]]; last by rewrite rpredB ?char_vchar. case/zchar_tuple_expansion=> z Zz ->; rewrite (bigID (fun i => 0 <= z i)) /=. set chi1 := \sum_(i | _) _; set nchi2 := \sum_(i | _) _. exists chi1; last exists (- nchi2); last by rewrite opprK. apply: rpred_sum => i zi_ge0; rewrite -tnth_nth rpredZ_nat ?irr_char //. by rewrite natrEint Zz. rewrite -sumrN rpred_sum // => i zi_lt0; rewrite -scaleNr -tnth_nth. rewrite rpredZ_nat ?irr_char // natrEint rpredN Zz oppr_ge0 ltW //. by rewrite real_ltNge ?Rreal_int. Qed. Lemma Aint_vchar phi x : phi \in 'Z[irr G] -> phi x \in Aint. Proof. case/vcharP=> [chi1 Nchi1 [chi2 Nchi2 ->]]. by rewrite !cfunE rpredB ?Aint_char. Qed. Lemma Cint_vchar1 phi : phi \in 'Z[irr G] -> phi 1%g \in Num.int. Proof. case/vcharP=> phi1 Nphi1 [phi2 Nphi2 ->]. by rewrite !cfunE rpredB // rpred_nat_num ?Cnat_char1. Qed. Lemma Cint_cfdot_vchar_irr i phi : phi \in 'Z[irr G] -> '[phi, 'chi_i] \in Num.int. Proof. case/vcharP=> chi1 Nchi1 [chi2 Nchi2 ->]. by rewrite cfdotBl rpredB // rpred_nat_num ?Cnat_cfdot_char_irr. Qed. Lemma cfdot_vchar_r phi psi : psi \in 'Z[irr G] -> '[phi, psi] = \sum_i '[phi, 'chi_i] * '[psi, 'chi_i]. Proof. move=> Zpsi; rewrite cfdot_sum_irr; apply: eq_bigr => i _; congr (_ * _). by rewrite aut_intr ?Cint_cfdot_vchar_irr. Qed. Lemma Cint_cfdot_vchar : {in 'Z[irr G] &, forall phi psi, '[phi, psi] \in Num.int}. Proof. move=> phi psi Zphi Zpsi; rewrite /= cfdot_vchar_r // rpred_sum // => k _. by rewrite rpredM ?Cint_cfdot_vchar_irr. Qed. Lemma Cnat_cfnorm_vchar : {in 'Z[irr G], forall phi, '[phi] \in Num.nat}. Proof. by move=> phi Zphi; rewrite /= natrEint cfnorm_ge0 Cint_cfdot_vchar. Qed. Fact vchar_mulr_closed : mulr_closed 'Z[irr G]. Proof. split; first exact: cfun1_vchar. move=> _ _ /vcharP[xi1 Nxi1 [xi2 Nxi2 ->]] /vcharP[xi3 Nxi3 [xi4 Nxi4 ->]]. by rewrite mulrBl !mulrBr !(rpredB, rpredD) // char_vchar ?rpredM. Qed. HB.instance Definition _ := GRing.isMulClosed.Build (classfun G) 'Z[irr G] vchar_mulr_closed. Lemma mul_vchar A : {in 'Z[irr G, A] &, forall phi psi, phi * psi \in 'Z[irr G, A]}. Proof. move=> phi psi; rewrite zchar_split => /andP[Zphi Aphi] /zcharW Zpsi. rewrite zchar_split rpredM //; apply/cfun_onP=> x A'x. by rewrite cfunE (cfun_onP Aphi) ?mul0r. Qed. Section CfdotPairwiseOrthogonal. Variables (M : {group gT}) (S : seq 'CF(G)) (nu : 'CF(G) -> 'CF(M)). Hypotheses (Inu : {in 'Z[S] &, isometry nu}) (oSS : pairwise_orthogonal S). Let freeS := orthogonal_free oSS. Let uniqS : uniq S := free_uniq freeS. Let Z_S : {subset S <= 'Z[S]}. Proof. by move=> phi; apply: mem_zchar. Qed. Let notS0 : 0 \notin S. Proof. by case/andP: oSS. Qed. Let dotSS := proj2 (pairwise_orthogonalP oSS). Lemma map_pairwise_orthogonal : pairwise_orthogonal (map nu S). Proof. have inj_nu: {in S &, injective nu}. move=> phi psi Sphi Spsi /= eq_nu; apply: contraNeq (memPn notS0 _ Sphi). by rewrite -cfnorm_eq0 -Inu ?Z_S // {2}eq_nu Inu ?Z_S // => /dotSS->. have notSnu0: 0 \notin map nu S. apply: contra notS0 => /mapP[phi Sphi /esym/eqP]. by rewrite -cfnorm_eq0 Inu ?Z_S // cfnorm_eq0 => /eqP <-. apply/pairwise_orthogonalP; split; first by rewrite /= notSnu0 map_inj_in_uniq. move=> _ _ /mapP[phi Sphi ->] /mapP[psi Spsi ->]. by rewrite (inj_in_eq inj_nu) // Inu ?Z_S //; apply: dotSS. Qed. Lemma cfproj_sum_orthogonal P z phi : phi \in S -> '[\sum_(xi <- S | P xi) z xi *: nu xi, nu phi] = if P phi then z phi * '[phi] else 0. Proof. move=> Sphi; have defS := perm_to_rem Sphi. rewrite cfdot_suml (perm_big _ defS) big_cons /= cfdotZl Inu ?Z_S //. rewrite big1_seq ?addr0 // => xi; rewrite mem_rem_uniq ?inE //. by case/and3P=> _ neq_xi Sxi; rewrite cfdotZl Inu ?Z_S // dotSS ?mulr0. Qed. Lemma cfdot_sum_orthogonal z1 z2 : '[\sum_(xi <- S) z1 xi *: nu xi, \sum_(xi <- S) z2 xi *: nu xi] = \sum_(xi <- S) z1 xi * (z2 xi)^* * '[xi]. Proof. rewrite cfdot_sumr; apply: eq_big_seq => phi Sphi. by rewrite cfdotZr cfproj_sum_orthogonal // mulrCA mulrA. Qed. Lemma cfnorm_sum_orthogonal z : '[\sum_(xi <- S) z xi *: nu xi] = \sum_(xi <- S) `|z xi| ^+ 2 * '[xi]. Proof. by rewrite cfdot_sum_orthogonal; apply: eq_bigr => xi _; rewrite normCK. Qed. Lemma cfnorm_orthogonal : '[\sum_(xi <- S) nu xi] = \sum_(xi <- S) '[xi]. Proof. rewrite -(eq_bigr _ (fun _ _ => scale1r _)) cfnorm_sum_orthogonal. by apply: eq_bigr => xi; rewrite normCK conjC1 !mul1r. Qed. End CfdotPairwiseOrthogonal. Lemma orthogonal_span S phi : pairwise_orthogonal S -> phi \in <<S>>%VS -> {z | z = fun xi => '[phi, xi] / '[xi] & phi = \sum_(xi <- S) z xi *: xi}. Proof. move=> oSS /free_span[|c -> _]; first exact: orthogonal_free. set z := fun _ => _ : algC; exists z => //; apply: eq_big_seq => u Su. rewrite /z cfproj_sum_orthogonal // mulfK // cfnorm_eq0. by rewrite (memPn _ u Su); case/andP: oSS. Qed. Section CfDotOrthonormal. Variables (M : {group gT}) (S : seq 'CF(G)) (nu : 'CF(G) -> 'CF(M)). Hypotheses (Inu : {in 'Z[S] &, isometry nu}) (onS : orthonormal S). Let oSS := orthonormal_orthogonal onS. Let freeS := orthogonal_free oSS. Let nS1 : {in S, forall phi, '[phi] = 1}. Proof. by move=> phi Sphi; case/orthonormalP: onS => _ -> //; rewrite eqxx. Qed. Lemma map_orthonormal : orthonormal (map nu S). Proof. rewrite !orthonormalE map_pairwise_orthogonal // andbT. by apply/allP=> _ /mapP[xi Sxi ->]; rewrite /= Inu ?nS1 // mem_zchar. Qed. Lemma cfproj_sum_orthonormal z phi : phi \in S -> '[\sum_(xi <- S) z xi *: nu xi, nu phi] = z phi. Proof. by move=> Sphi; rewrite cfproj_sum_orthogonal // nS1 // mulr1. Qed. Lemma cfdot_sum_orthonormal z1 z2 : '[\sum_(xi <- S) z1 xi *: xi, \sum_(xi <- S) z2 xi *: xi] = \sum_(xi <- S) z1 xi * (z2 xi)^*. Proof. rewrite cfdot_sum_orthogonal //; apply: eq_big_seq => phi /nS1->. by rewrite mulr1. Qed. Lemma cfnorm_sum_orthonormal z : '[\sum_(xi <- S) z xi *: nu xi] = \sum_(xi <- S) `|z xi| ^+ 2. Proof. rewrite cfnorm_sum_orthogonal //. by apply: eq_big_seq => xi /nS1->; rewrite mulr1. Qed. Lemma cfnorm_map_orthonormal : '[\sum_(xi <- S) nu xi] = (size S)%:R. Proof. by rewrite cfnorm_orthogonal // (eq_big_seq _ nS1) big_tnth sumr_const card_ord. Qed. Lemma orthonormal_span phi : phi \in <<S>>%VS -> {z | z = fun xi => '[phi, xi] & phi = \sum_(xi <- S) z xi *: xi}. Proof. case/orthogonal_span=> // _ -> {2}->; set z := fun _ => _ : algC. by exists z => //; apply: eq_big_seq => xi /nS1->; rewrite divr1. Qed. End CfDotOrthonormal. Lemma cfnorm_orthonormal S : orthonormal S -> '[\sum_(xi <- S) xi] = (size S)%:R. Proof. exact: cfnorm_map_orthonormal. Qed. Lemma vchar_orthonormalP S : {subset S <= 'Z[irr G]} -> reflect (exists I : {set Iirr G}, exists b : Iirr G -> bool, perm_eq S [seq (-1) ^+ b i *: 'chi_i | i in I]) (orthonormal S). Proof. move=> vcS; apply: (equivP orthonormalP). split=> [[uniqS oSS] | [I [b defS]]]; last first. split=> [|xi1 xi2]; rewrite ?(perm_mem defS). rewrite (perm_uniq defS) map_inj_uniq ?enum_uniq // => i j /eqP. by rewrite eq_signed_irr => /andP[_ /eqP]. case/mapP=> [i _ ->] /mapP[j _ ->]; rewrite eq_signed_irr. rewrite cfdotZl cfdotZr rmorph_sign mulrA cfdot_irr -signr_addb mulr_natr. by rewrite mulrb andbC; case: eqP => //= ->; rewrite addbb eqxx. pose I := [set i | ('chi_i \in S) || (- 'chi_i \in S)]. pose b i := - 'chi_i \in S; exists I, b. apply: uniq_perm => // [|xi]. rewrite map_inj_uniq ?enum_uniq // => i j /eqP. by rewrite eq_signed_irr => /andP[_ /eqP]. apply/idP/mapP=> [Sxi | [i Ii ->{xi}]]; last first. move: Ii; rewrite mem_enum inE orbC -/(b i). by case b_i: (b i); rewrite (scale1r, scaleN1r). have: '[xi] = 1 by rewrite oSS ?eqxx. have vc_xi := vcS _ Sxi; rewrite cfdot_sum_irr. case/natr_sum_eq1 => [i _ | i [_ /eqP norm_xi_i xi_i'_0]]. by rewrite -normCK rpredX // natr_norm_int ?Cint_cfdot_vchar_irr. suffices def_xi: xi = (-1) ^+ b i *: 'chi_i. exists i; rewrite // mem_enum inE -/(b i) orbC. by case: (b i) def_xi Sxi => // ->; rewrite scale1r. move: Sxi; rewrite [xi]cfun_sum_cfdot (bigD1 i) //. rewrite big1 //= ?addr0 => [|j ne_ji]; last first. apply/eqP; rewrite scaler_eq0 -normr_eq0 -[_ == 0](expf_eq0 _ 2) normCK. by rewrite xi_i'_0 ?eqxx. have:= norm_xi_i; rewrite (aut_intr _ (Cint_cfdot_vchar_irr _ _)) //. rewrite -subr_eq0 subr_sqr_1 mulf_eq0 subr_eq0 addr_eq0 /b scaler_sign. case/pred2P=> ->; last by rewrite scaleN1r => ->. rewrite scale1r => Sxi; case: ifP => // SNxi. have:= oSS _ _ Sxi SNxi; rewrite cfdotNr cfdot_irr eqxx; case: eqP => // _. by move/eqP; rewrite oppr_eq0 oner_eq0. Qed. Lemma vchar_norm1P phi : phi \in 'Z[irr G] -> '[phi] = 1 -> exists b : bool, exists i : Iirr G, phi = (-1) ^+ b *: 'chi_i. Proof. move=> Zphi phiN1. have: orthonormal phi by rewrite /orthonormal/= phiN1 eqxx. case/vchar_orthonormalP=> [xi /predU1P[->|] // | I [b def_phi]]. have: phi \in (phi : seq _) := mem_head _ _. by rewrite (perm_mem def_phi) => /mapP[i _ ->]; exists (b i), i. Qed. Lemma zchar_small_norm phi n : phi \in 'Z[irr G] -> '[phi] = n%:R -> (n < 4)%N -> {S : n.-tuple 'CF(G) | [/\ orthonormal S, {subset S <= 'Z[irr G]} & phi = \sum_(xi <- S) xi]}. Proof. move=> Zphi def_n lt_n_4. pose S := [seq '[phi, 'chi_i] *: 'chi_i | i in irr_constt phi]. have def_phi: phi = \sum_(xi <- S) xi. rewrite big_image big_mkcond {1}[phi]cfun_sum_cfdot. by apply: eq_bigr => i _; rewrite if_neg; case: eqP => // ->; rewrite scale0r. have orthS: orthonormal S. apply/orthonormalP; split=> [|_ _ /mapP[i phi_i ->] /mapP[j _ ->]]. rewrite map_inj_in_uniq ?enum_uniq // => i j; rewrite mem_enum => phi_i _. by move/eqP; rewrite eq_scaled_irr (negbTE phi_i) => /andP[_ /= /eqP]. rewrite eq_scaled_irr cfdotZl cfdotZr cfdot_irr mulrA mulr_natr mulrb. rewrite mem_enum in phi_i; rewrite (negbTE phi_i) andbC; case: eqP => // <-. have /natrP[m def_m] := natr_norm_int (Cint_cfdot_vchar_irr i Zphi). apply/eqP; rewrite eqxx /= -normCK def_m -natrX eqr_nat eqn_leq lt0n. rewrite expn_eq0 andbT -eqC_nat -def_m normr_eq0 [~~ _]phi_i andbT. rewrite (leq_exp2r _ 1) // -ltnS -(@ltn_exp2r _ _ 2) //. apply: leq_ltn_trans lt_n_4; rewrite -leC_nat -def_n natrX. rewrite cfdot_sum_irr (bigD1 i) //= -normCK def_m addrC -subr_ge0 addrK. by rewrite sumr_ge0 // => ? _; apply: mul_conjC_ge0. have <-: size S = n. by apply/eqP; rewrite -eqC_nat -def_n def_phi cfnorm_orthonormal. exists (in_tuple S); split=> // _ /mapP[i _ ->]. by rewrite scale_zchar ?irr_vchar // Cint_cfdot_vchar_irr. Qed. Lemma vchar_norm2 phi : phi \in 'Z[irr G, G^#] -> '[phi] = 2 -> exists i, exists2 j, j != i & phi = 'chi_i - 'chi_j. Proof. rewrite zchar_split cfunD1E => /andP[Zphi phi1_0]. case/zchar_small_norm => // [[[|chi [|xi [|?]]] //= S2]]. case=> /andP[/and3P[Nchi Nxi _] /= ochi] /allP/and3P[Zchi Zxi _]. rewrite big_cons big_seq1 => def_phi. have [b [i def_chi]] := vchar_norm1P Zchi (eqP Nchi). have [c [j def_xi]] := vchar_norm1P Zxi (eqP Nxi). have neq_ji: j != i. apply: contraTneq ochi; rewrite !andbT def_chi def_xi => ->. rewrite cfdotZl cfdotZr rmorph_sign cfnorm_irr mulr1 -signr_addb. by rewrite signr_eq0. have neq_bc: b != c. apply: contraTneq phi1_0; rewrite def_phi def_chi def_xi => ->. rewrite -scalerDr !cfunE mulf_eq0 signr_eq0 eq_le lt_geF //. by rewrite ltr_pDl ?irr1_gt0. rewrite {}def_phi {}def_chi {}def_xi !scaler_sign. case: b c neq_bc => [|] [|] // _; last by exists i, j. by exists j, i; rewrite 1?eq_sym // addrC. Qed. End VChar. Section Isometries. Variables (gT : finGroupType) (L G : {group gT}) (S : seq 'CF(L)). Implicit Type nu : {additive 'CF(L) -> 'CF(G)}. Lemma Zisometry_of_cfnorm (tauS : seq 'CF(G)) : pairwise_orthogonal S -> pairwise_orthogonal tauS -> map cfnorm tauS = map cfnorm S -> {subset tauS <= 'Z[irr G]} -> {tau : {linear 'CF(L) -> 'CF(G)} | map tau S = tauS & {in 'Z[S], isometry tau, to 'Z[irr G]}}. Proof. move=> oSS oTT /isometry_of_cfnorm[||tau defT Itau] // Z_T; exists tau => //. split=> [|_ /zchar_nth_expansion[u Zu ->]]. by apply: sub_in2 Itau; apply: zchar_span. rewrite big_seq linear_sum rpred_sum // => xi Sxi. by rewrite linearZ scale_zchar ?Z_T // -defT map_f ?mem_nth. Qed. Lemma Zisometry_of_iso f : free S -> {in S, isometry f, to 'Z[irr G]} -> {tau : {linear 'CF(L) -> 'CF(G)} | {in S, tau =1 f} & {in 'Z[S], isometry tau, to 'Z[irr G]}}. Proof. move=> freeS [If Zf]; have [tau Dtau Itau] := isometry_of_free freeS If. exists tau => //; split; first by apply: sub_in2 Itau; apply: zchar_span. move=> _ /zchar_nth_expansion[a Za ->]; rewrite linear_sum rpred_sum // => i _. by rewrite linearZ rpredZ_int ?Dtau ?Zf ?mem_nth. Qed. Lemma Zisometry_inj A nu : {in 'Z[S, A] &, isometry nu} -> {in 'Z[S, A] &, injective nu}. Proof. by move/isometry_raddf_inj; apply; apply: rpredB. Qed. Lemma isometry_in_zchar nu : {in S &, isometry nu} -> {in 'Z[S] &, isometry nu}. Proof. move=> Inu _ _ /zchar_nth_expansion[u Zu ->] /zchar_nth_expansion[v Zv ->]. rewrite !raddf_sum; apply: eq_bigr => j _ /=. rewrite !cfdot_suml; apply: eq_bigr => i _. by rewrite !raddfZ_int //= !cfdotZl !cfdotZr Inu ?mem_nth. Qed. End Isometries. Section AutVchar. Variables (u : {rmorphism algC -> algC}) (gT : finGroupType) (G : {group gT}). Local Notation "alpha ^u" := (cfAut u alpha). Implicit Type (S : seq 'CF(G)) (phi chi : 'CF(G)). Lemma cfAut_zchar S A psi : cfAut_closed u S -> psi \in 'Z[S, A] -> psi^u \in 'Z[S, A]. Proof. rewrite zchar_split => SuS /andP[/zchar_nth_expansion[z Zz Dpsi] Apsi]. rewrite zchar_split cfAut_on {}Apsi {psi}Dpsi rmorph_sum rpred_sum //= => i _. by rewrite cfAutZ_Cint // scale_zchar // mem_zchar ?SuS ?mem_nth. Qed. Lemma cfAut_vchar A psi : psi \in 'Z[irr G, A] -> psi^u \in 'Z[irr G, A]. Proof. by apply: cfAut_zchar; apply: irr_aut_closed. Qed. Lemma sub_aut_zchar S A psi : {subset S <= 'Z[irr G]} -> psi \in 'Z[S, A] -> psi^u \in 'Z[S, A] -> psi - psi^u \in 'Z[S, A^#]. Proof. move=> Z_S Spsi Spsi_u; rewrite zcharD1 !cfunE subr_eq0 rpredB //=. by rewrite aut_intr // Cint_vchar1 // (zchar_trans Z_S) ?(zcharW Spsi). Qed. Lemma conjC_vcharAut chi x : chi \in 'Z[irr G] -> (u (chi x))^* = u (chi x)^*. Proof. case/vcharP=> chi1 Nchi1 [chi2 Nchi2 ->]. by rewrite !cfunE !rmorphB !conjC_charAut. Qed. Lemma cfdot_aut_vchar phi chi : chi \in 'Z[irr G] -> '[phi^u , chi^u] = u '[phi, chi]. Proof. by case/vcharP=> chi1 Nchi1 [chi2 Nchi2 ->]; rewrite !raddfB /= !cfdot_aut_char. Qed. Lemma vchar_aut A chi : (chi^u \in 'Z[irr G, A]) = (chi \in 'Z[irr G, A]). Proof. rewrite !(zchar_split _ A) cfAut_on; congr (_ && _). apply/idP/idP=> [Zuchi|]; last exact: cfAut_vchar. rewrite [chi]cfun_sum_cfdot rpred_sum // => i _. rewrite scale_zchar ?irr_vchar //. by rewrite -(intr_aut u) -cfdot_aut_irr -aut_IirrE Cint_cfdot_vchar_irr. Qed. End AutVchar. Definition cfConjC_vchar := cfAut_vchar conjC. Section MoreVchar. Variables (gT : finGroupType) (G H : {group gT}). Lemma cfRes_vchar phi : phi \in 'Z[irr G] -> 'Res[H] phi \in 'Z[irr H]. Proof. case/vcharP=> xi1 Nx1 [xi2 Nxi2 ->]. by rewrite raddfB rpredB ?char_vchar ?cfRes_char. Qed. Lemma cfRes_vchar_on A phi : H \subset G -> phi \in 'Z[irr G, A] -> 'Res[H] phi \in 'Z[irr H, A]. Proof. rewrite zchar_split => sHG /andP[Zphi Aphi]; rewrite zchar_split cfRes_vchar //. apply/cfun_onP=> x /(cfun_onP Aphi); rewrite !cfunElock !genGid sHG => ->. exact: mul0rn. Qed. Lemma cfInd_vchar phi : phi \in 'Z[irr H] -> 'Ind[G] phi \in 'Z[irr G]. Proof. move=> /vcharP[xi1 Nx1 [xi2 Nxi2 ->]]. by rewrite raddfB rpredB ?char_vchar ?cfInd_char. Qed. Lemma sub_conjC_vchar A phi : phi \in 'Z[irr G, A] -> phi - (phi^*)%CF \in 'Z[irr G, A^#]. Proof. move=> Zphi; rewrite sub_aut_zchar ?cfAut_zchar // => _ /irrP[i ->]. exact: irr_vchar. exact: cfConjC_irr. Qed. Lemma Frobenius_kernel_exists : [Frobenius G with complement H] -> {K : {group gT} | [Frobenius G = K ><| H]}. Proof. move=> frobG; have [_ ntiHG] := andP frobG. have [[_ sHG regGH][_ tiHG /eqP defNH]] := (normedTI_memJ_P ntiHG, and3P ntiHG). suffices /sigW[K defG]: exists K, gval K ><| H == G by exists K; apply/andP. pose K1 := G :\: cover (H^# :^: G). have oK1: #|K1| = #|G : H|. rewrite cardsD (setIidPr _); last first. rewrite cover_imset; apply/bigcupsP=> x Gx. by rewrite sub_conjg conjGid ?groupV // (subset_trans (subsetDl _ _)). rewrite (cover_partition (partition_normedTI ntiHG)) -(Lagrange sHG). by rewrite (card_support_normedTI ntiHG) (cardsD1 1%g) group1 mulSn addnK. suffices extG i: {j | {in H, 'chi[G]_j =1 'chi[H]_i} & K1 \subset cfker 'chi_j}. pose K := [group of \bigcap_i cfker 'chi_(s2val (extG i))]. have nKH: H \subset 'N(K). by apply/norms_bigcap/bigcapsP=> i _; apply: subset_trans (cfker_norm _). have tiKH: K :&: H = 1%g. apply/trivgP; rewrite -(TI_cfker_irr H) /= setIC; apply/bigcapsP=> i _. apply/subsetP=> x /setIP[Hx /bigcapP/(_ i isT)/=]; rewrite !cfkerEirr !inE. by case: (extG i) => /= j def_j _; rewrite !def_j. exists K; rewrite sdprodE // eqEcard TI_cardMg // mul_subG //=; last first. by rewrite (bigcap_min (0 : Iirr H)) ?cfker_sub. rewrite -(Lagrange sHG) mulnC leq_pmul2r // -oK1 subset_leq_card //. by apply/bigcapsP=> i _; case: (extG i). case i0: (i == 0). exists 0 => [x Hx|]; last by rewrite irr0 cfker_cfun1 subsetDl. by rewrite (eqP i0) !irr0 !cfun1E // (subsetP sHG) ?Hx. have ochi1: '['chi_i, 1] = 0 by rewrite -irr0 cfdot_irr i0. pose a := 'chi_i 1%g; have Za: a \in Num.int by rewrite intrE Cnat_irr1. pose theta := 'chi_i - a%:A; pose phi := 'Ind[G] theta + a%:A. have /cfun_onP theta0: theta \in 'CF(H, H^#). by rewrite cfunD1E !cfunE cfun11 mulr1 subrr. have RItheta: 'Res ('Ind[G] theta) = theta. apply/cfun_inP=> x Hx; rewrite cfResE ?cfIndE // (big_setID H) /= addrC. apply: canLR (mulKf (neq0CG H)) _; rewrite (setIidPr sHG) mulr_natl. rewrite big1 ?add0r => [|y /setDP[/regGH tiHy H'y]]; last first. have [-> | ntx] := eqVneq x 1%g; first by rewrite conj1g theta0 ?inE ?eqxx. by rewrite theta0 ?tiHy // !inE ntx. by rewrite -sumr_const; apply: eq_bigr => y Hy; rewrite cfunJ. have ophi1: '[phi, 1] = 0. rewrite cfdotDl -cfdot_Res_r cfRes_cfun1 // cfdotBl !cfdotZl !cfnorm1. by rewrite ochi1 add0r addNr. have{ochi1} n1phi: '[phi] = 1. have: '[phi - a%:A] = '[theta] by rewrite addrK -cfdot_Res_l RItheta. rewrite !cfnormBd ?cfnormZ ?cfdotZr ?ophi1 ?ochi1 ?mulr0 //. by rewrite !cfnorm1 cfnorm_irr => /addIr. have Zphi: phi \in 'Z[irr G]. by rewrite rpredD ?cfInd_vchar ?rpredB ?irr_vchar // scale_zchar ?rpred1. have def_phi: {in H, phi =1 'chi_i}. move=> x Hx /=; rewrite !cfunE -[_ x](cfResE _ sHG) ?RItheta //. by rewrite !cfunE !cfun1E ?(subsetP sHG) ?Hx ?subrK. have [j def_chi_j]: {j | 'chi_j = phi}. apply/sig_eqW; have [[] [j]] := vchar_norm1P Zphi n1phi; last first. by rewrite scale1r; exists j. move/cfunP/(_ 1%g)/eqP; rewrite scaleN1r def_phi // cfunE -addr_eq0 eq_le. by rewrite lt_geF // ltr_pDl ?irr1_gt0. exists j; rewrite ?cfkerEirr def_chi_j //; apply/subsetP => x /setDP[Gx notHx]. rewrite inE cfunE def_phi // cfunE -/a cfun1E // Gx mulr1 cfIndE //. rewrite big1 ?mulr0 ?add0r // => y Gy; apply/theta0/(contra _ notHx) => Hxy. by rewrite -(conjgK y x) cover_imset -class_supportEr imset2_f ?groupV. Qed. End MoreVchar. Definition dirr (gT : finGroupType) (B : {set gT}) : {pred 'CF(B)} := [pred f | (f \in irr B) || (- f \in irr B)]. Arguments dirr {gT}. Section Norm1vchar. Variables (gT : finGroupType) (G : {group gT}). Fact dirr_oppr_closed : oppr_closed (dirr G). Proof. by move=> xi; rewrite !inE opprK orbC. Qed. HB.instance Definition _ := GRing.isOppClosed.Build (classfun G) (dirr G) dirr_oppr_closed. Lemma dirr_opp v : (- v \in dirr G) = (v \in dirr G). Proof. exact: rpredN. Qed. Lemma dirr_sign n v : ((-1)^+ n *: v \in dirr G) = (v \in dirr G). Proof. exact: rpredZsign. Qed. Lemma irr_dirr i : 'chi_i \in dirr G. Proof. by rewrite !inE mem_irr. Qed. Lemma dirrP f : reflect (exists b : bool, exists i, f = (-1) ^+ b *: 'chi_i) (f \in dirr G). Proof. apply: (iffP idP) => [| [b [i ->]]]; last by rewrite dirr_sign irr_dirr. case/orP=> /irrP[i Hf]; first by exists false, i; rewrite scale1r. by exists true, i; rewrite scaleN1r -Hf opprK. Qed. (* This should perhaps be the definition of dirr. *) Lemma dirrE phi : phi \in dirr G = (phi \in 'Z[irr G]) && ('[phi] == 1). Proof. apply/dirrP/andP=> [[b [i ->]] | [Zphi /eqP/vchar_norm1P]]; last exact. by rewrite rpredZsign irr_vchar cfnorm_sign cfnorm_irr. Qed. Lemma cfdot_dirr f g : f \in dirr G -> g \in dirr G -> '[f, g] = (if f == - g then -1 else (f == g)%:R). Proof. case/dirrP=> [b1 [i1 ->]] /dirrP[b2 [i2 ->]]. rewrite cfdotZl cfdotZr rmorph_sign mulrA -signr_addb cfdot_irr. rewrite -scaleNr -signrN !eq_scaled_irr signr_eq0 !(inj_eq signr_inj) /=. by rewrite -!negb_add addbN mulr_sign -mulNrn mulrb; case: ifP. Qed. Lemma dirr_norm1 phi : phi \in 'Z[irr G] -> '[phi] = 1 -> phi \in dirr G. Proof. by rewrite dirrE => -> -> /=. Qed. Lemma dirr_aut u phi : (cfAut u phi \in dirr G) = (phi \in dirr G). Proof. rewrite !dirrE vchar_aut; apply: andb_id2l => /cfdot_aut_vchar->. exact: fmorph_eq1. Qed. Definition dIirr (B : {set gT}) := (bool * (Iirr B))%type. Definition dirr1 (B : {set gT}) : dIirr B := (false, 0). Definition ndirr (B : {set gT}) (i : dIirr B) : dIirr B := (~~ i.1, i.2). Lemma ndirr_diff (i : dIirr G) : ndirr i != i. Proof. by case: i => [] [|] i. Qed. Lemma ndirrK : involutive (@ndirr G). Proof. by move=> [b i]; rewrite /ndirr /= negbK. Qed. Lemma ndirr_inj : injective (@ndirr G). Proof. exact: (inv_inj ndirrK). Qed. Definition dchi (B : {set gT}) (i : dIirr B) : 'CF(B) := (-1)^+ i.1 *: 'chi_i.2. Lemma dchi1 : dchi (dirr1 G) = 1. Proof. by rewrite /dchi scale1r irr0. Qed. Lemma dirr_dchi i : dchi i \in dirr G. Proof. by apply/dirrP; exists i.1; exists i.2. Qed. Lemma dIrrP phi : reflect (exists i, phi = dchi i) (phi \in dirr G). Proof. by apply: (iffP idP)=> [/dirrP[b]|] [i ->]; [exists (b, i) | apply: dirr_dchi]. Qed. Lemma dchi_ndirrE (i : dIirr G) : dchi (ndirr i) = - dchi i. Proof. by case: i => [b i]; rewrite /ndirr /dchi signrN scaleNr. Qed. Lemma cfdot_dchi (i j : dIirr G) : '[dchi i, dchi j] = (i == j)%:R - (i == ndirr j)%:R. Proof. case: i => bi i; case: j => bj j; rewrite cfdot_dirr ?dirr_dchi // !xpair_eqE. rewrite -dchi_ndirrE !eq_scaled_irr signr_eq0 !(inj_eq signr_inj) /=. by rewrite -!negb_add addbN negbK; case: andP => [[->]|]; rewrite ?subr0 ?add0r. Qed. Lemma dchi_vchar i : dchi i \in 'Z[irr G]. Proof. by case: i => b i; rewrite rpredZsign irr_vchar. Qed. Lemma cfnorm_dchi (i : dIirr G) : '[dchi i] = 1. Proof. by case: i => b i; rewrite cfnorm_sign cfnorm_irr. Qed. Lemma dirr_inj : injective (@dchi G). Proof. case=> b1 i1 [b2 i2] /eqP; rewrite eq_scaled_irr (inj_eq signr_inj) /=. by rewrite signr_eq0 -xpair_eqE => /eqP. Qed. Definition dirr_dIirr (B : {set gT}) J (f : J -> 'CF(B)) j : dIirr B := odflt (dirr1 B) [pick i | dchi i == f j]. Lemma dirr_dIirrPE J (f : J -> 'CF(G)) (P : pred J) : (forall j, P j -> f j \in dirr G) -> forall j, P j -> dchi (dirr_dIirr f j) = f j. Proof. rewrite /dirr_dIirr => dirrGf j Pj; case: pickP => [i /eqP //|]. by have /dIrrP[i-> /(_ i)/eqP] := dirrGf j Pj. Qed. Lemma dirr_dIirrE J (f : J -> 'CF(G)) : (forall j, f j \in dirr G) -> forall j, dchi (dirr_dIirr f j) = f j. Proof. by move=> dirrGf j; apply: (@dirr_dIirrPE _ _ xpredT). Qed. Definition dirr_constt (B : {set gT}) (phi: 'CF(B)) : {set (dIirr B)} := [set i | 0 < '[phi, dchi i]]. Lemma dirr_consttE (phi : 'CF(G)) (i : dIirr G) : (i \in dirr_constt phi) = (0 < '[phi, dchi i]). Proof. by rewrite inE. Qed. Lemma Cnat_dirr (phi : 'CF(G)) i : phi \in 'Z[irr G] -> i \in dirr_constt phi -> '[phi, dchi i] \in Num.nat. Proof. move=> PiZ; rewrite natrEint dirr_consttE andbC => /ltW -> /=. by case: i => b i; rewrite cfdotZr rmorph_sign rpredMsign Cint_cfdot_vchar_irr. Qed. Lemma dirr_constt_oppr (i : dIirr G) (phi : 'CF(G)) : (i \in dirr_constt (-phi)) = (ndirr i \in dirr_constt phi). Proof. by rewrite !dirr_consttE dchi_ndirrE cfdotNl cfdotNr. Qed. Lemma dirr_constt_oppI (phi: 'CF(G)) : dirr_constt phi :&: dirr_constt (-phi) = set0. Proof. apply/setP=> i; rewrite inE !dirr_consttE cfdotNl inE. apply/idP=> /andP [L1 L2]; have := ltr_pDl L1 L2. by rewrite subrr lt_def eqxx. Qed. Lemma dirr_constt_oppl (phi: 'CF(G)) i : i \in dirr_constt phi -> (ndirr i) \notin dirr_constt phi. Proof. by rewrite !dirr_consttE dchi_ndirrE cfdotNr oppr_gt0 => /ltW /le_gtF ->. Qed. Definition to_dirr (B : {set gT}) (phi : 'CF(B)) (i : Iirr B) : dIirr B := ('[phi, 'chi_i] < 0, i). Definition of_irr (B : {set gT}) (i : dIirr B) : Iirr B := i.2. Lemma irr_constt_to_dirr (phi: 'CF(G)) i : phi \in 'Z[irr G] -> (i \in irr_constt phi) = (to_dirr phi i \in dirr_constt phi). Proof. move=> Zphi; rewrite irr_consttE dirr_consttE cfdotZr rmorph_sign /=. by rewrite -real_normrEsign ?normr_gt0 ?Rreal_int // Cint_cfdot_vchar_irr. Qed. Lemma to_dirrK (phi: 'CF(G)) : cancel (to_dirr phi) (@of_irr G). Proof. by []. Qed. Lemma of_irrK (phi: 'CF(G)) : {in dirr_constt phi, cancel (@of_irr G) (to_dirr phi)}. Proof. case=> b i; rewrite dirr_consttE cfdotZr rmorph_sign /= /to_dirr mulr_sign. by rewrite fun_if oppr_gt0; case: b => [|/ltW/le_gtF] ->. Qed. Lemma cfdot_todirrE (phi: 'CF(G)) i (phi_i := dchi (to_dirr phi i)) : '[phi, phi_i] *: phi_i = '[phi, 'chi_i] *: 'chi_i. Proof. by rewrite cfdotZr rmorph_sign mulrC -scalerA signrZK. Qed. Lemma cfun_sum_dconstt (phi : 'CF(G)) : phi \in 'Z[irr G] -> phi = \sum_(i in dirr_constt phi) '[phi, dchi i] *: dchi i. Proof. move=> PiZ; rewrite [LHS]cfun_sum_constt. rewrite (reindex (to_dirr phi))=> [/= |]; last first. by exists (@of_irr _)=> //; apply: of_irrK . by apply: eq_big => i; rewrite ?irr_constt_to_dirr // cfdot_todirrE. Qed. Lemma cnorm_dconstt (phi : 'CF(G)) : phi \in 'Z[irr G] -> '[phi] = \sum_(i in dirr_constt phi) '[phi, dchi i] ^+ 2. Proof. move=> PiZ; rewrite {1 2}(cfun_sum_dconstt PiZ). rewrite cfdot_suml; apply: eq_bigr=> i IiD. rewrite cfdot_sumr (bigD1 i) //= big1 ?addr0 => [|j /andP [JiD IdJ]]. rewrite cfdotZr cfdotZl cfdot_dchi eqxx eq_sym (negPf (ndirr_diff i)). by rewrite subr0 mulr1 aut_natr ?Cnat_dirr. rewrite cfdotZr cfdotZl cfdot_dchi eq_sym (negPf IdJ) -natrB ?mulr0 //. by rewrite (negPf (contraNneq _ (dirr_constt_oppl JiD))) => // <-. Qed. Lemma dirr_small_norm (phi : 'CF(G)) n : phi \in 'Z[irr G] -> '[phi] = n%:R -> (n < 4)%N -> [/\ #|dirr_constt phi| = n, dirr_constt phi :&: dirr_constt (- phi) = set0 & phi = \sum_(i in dirr_constt phi) dchi i]. Proof. move=> PiZ Pln; rewrite ltnNge -leC_nat => Nl4. suffices Fd i: i \in dirr_constt phi -> '[phi, dchi i] = 1. split; last 2 [by apply/setP=> u; rewrite !inE cfdotNl oppr_gt0 lt_asym]. apply/eqP; rewrite -eqC_nat -sumr_const -Pln (cnorm_dconstt PiZ). by apply/eqP/eq_bigr=> i Hi; rewrite Fd // expr1n. rewrite {1}[phi]cfun_sum_dconstt //. by apply: eq_bigr => i /Fd->; rewrite scale1r. move=> IiD; apply: contraNeq Nl4 => phi_i_neq1. rewrite -Pln cnorm_dconstt // (bigD1 i) ?ler_wpDr ?sumr_ge0 //=. by move=> j /andP[JiD _]; rewrite exprn_ge0 ?natr_ge0 ?Cnat_dirr. have /natrP[m Dm] := Cnat_dirr PiZ IiD; rewrite Dm -natrX ler_nat (leq_sqr 2). by rewrite ltn_neqAle eq_sym -eqC_nat -ltC_nat -Dm phi_i_neq1 -dirr_consttE. Qed. Lemma cfdot_sum_dchi (phi1 phi2 : 'CF(G)) : '[\sum_(i in dirr_constt phi1) dchi i, \sum_(i in dirr_constt phi2) dchi i] = #|dirr_constt phi1 :&: dirr_constt phi2|%:R - #|dirr_constt phi1 :&: dirr_constt (- phi2)|%:R. Proof. rewrite addrC (big_setID (dirr_constt (- phi2))) /= cfdotDl; congr (_ + _). rewrite cfdot_suml -sumr_const -sumrN; apply: eq_bigr => i /setIP[p1i p2i]. rewrite cfdot_sumr (bigD1 (ndirr i)) -?dirr_constt_oppr //= dchi_ndirrE. rewrite cfdotNr cfnorm_dchi big1 ?addr0 // => j /andP[p2j i'j]. rewrite cfdot_dchi -(inv_eq ndirrK) [in rhs in - rhs]eq_sym (negPf i'j) subr0. rewrite (negPf (contraTneq _ p2i)) // => ->. by rewrite dirr_constt_oppr dirr_constt_oppl. rewrite cfdot_sumr (big_setID (dirr_constt phi1)) setIC /= addrC. rewrite big1 ?add0r => [|j /setDP[p2j p1'j]]; last first. rewrite cfdot_suml big1 // => i /setDP[p1i p2'i]. rewrite cfdot_dchi (negPf (contraTneq _ p1i)) => [|-> //]. rewrite (negPf (contraNneq _ p2'i)) ?subrr // => ->. by rewrite dirr_constt_oppr ndirrK. rewrite -sumr_const; apply: eq_bigr => i /setIP[p1i p2i]; rewrite cfdot_suml. rewrite (bigD1 i) /=; last by rewrite inE dirr_constt_oppr dirr_constt_oppl. rewrite cfnorm_dchi big1 ?addr0 // => j /andP[/setDP[p1j _] i'j]. rewrite cfdot_dchi (negPf i'j) (negPf (contraTneq _ p1j)) ?subrr // => ->. exact: dirr_constt_oppl. Qed. Lemma cfdot_dirr_eq1 : {in dirr G &, forall phi psi, ('[phi, psi] == 1) = (phi == psi)}. Proof. move=> _ _ /dirrP[b1 [i1 ->]] /dirrP[b2 [i2 ->]]. rewrite eq_signed_irr cfdotZl cfdotZr rmorph_sign cfdot_irr mulrA -signr_addb. rewrite pmulrn -rmorphMsign (eqr_int _ _ 1) -negb_add. by case: (b1 (+) b2) (i1 == i2) => [] []. Qed. Lemma cfdot_add_dirr_eq1 : {in dirr G & &, forall phi1 phi2 psi, '[phi1 + phi2, psi] = 1 -> psi = phi1 \/ psi = phi2}. Proof. move=> _ _ _ /dirrP[b1 [i1 ->]] /dirrP[b2 [i2 ->]] /dirrP[c [j ->]] /eqP. rewrite cfdotDl !cfdotZl !cfdotZr !rmorph_sign !cfdot_irr !mulrA -!signr_addb. rewrite 2!{1}signrE !mulrBl !mul1r -!natrM addrCA -subr_eq0 -!addrA. rewrite -!opprD addrA subr_eq0 -mulrSr -!natrD eqr_nat => eq_phi_psi. apply/pred2P; rewrite /= !eq_signed_irr -!negb_add !(eq_sym j) !(addbC c). by case: (i1 == j) eq_phi_psi; case: (i2 == j); do 2!case: (_ (+) c). Qed. End Norm1vchar. Prenex Implicits ndirr ndirrK to_dirr to_dirrK of_irr. Arguments of_irrK {gT G phi} [i] phi_i : rename.
CofilteredLimit.lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import Mathlib.Topology.Category.Profinite.Basic import Mathlib.Topology.LocallyConstant.Basic import Mathlib.Topology.DiscreteQuotient import Mathlib.Topology.Category.TopCat.Limits.Cofiltered import Mathlib.Topology.Category.TopCat.Limits.Konig /-! # Cofiltered limits of profinite sets. This file contains some theorems about cofiltered limits of profinite sets. ## Main Results - `exists_isClopen_of_cofiltered` shows that any clopen set in a cofiltered limit of profinite sets is the pullback of a clopen set from one of the factors in the limit. - `exists_locally_constant` shows that any locally constant function from a cofiltered limit of profinite sets factors through one of the components. -/ namespace Profinite open CategoryTheory Limits universe u v variable {J : Type v} [SmallCategory J] [IsCofiltered J] {F : J ⥤ Profinite.{max u v}} (C : Cone F) /-- If `X` is a cofiltered limit of profinite sets, then any clopen subset of `X` arises from a clopen set in one of the terms in the limit. -/ theorem exists_isClopen_of_cofiltered {U : Set C.pt} (hC : IsLimit C) (hU : IsClopen U) : ∃ (j : J) (V : Set (F.obj j)), IsClopen V ∧ U = C.π.app j ⁻¹' V := by -- First, we have the topological basis of the cofiltered limit obtained by pulling back -- clopen sets from the factors in the limit. By continuity, all such sets are again clopen. have hB := TopCat.isTopologicalBasis_cofiltered_limit.{u, v} (F ⋙ Profinite.toTopCat) (Profinite.toTopCat.mapCone C) (isLimitOfPreserves _ hC) (fun j => {W | IsClopen W}) ?_ (fun i => isClopen_univ) (fun i U1 U2 hU1 hU2 => hU1.inter hU2) ?_ rotate_left · intro i change TopologicalSpace.IsTopologicalBasis {W : Set (F.obj i) | IsClopen W} apply isTopologicalBasis_isClopen · rintro i j f V (hV : IsClopen _) exact ⟨hV.1.preimage ((F ⋙ toTopCat).map f).hom.continuous, hV.2.preimage ((F ⋙ toTopCat).map f).hom.continuous⟩ -- Porting note: `<;> continuity` fails -- Using this, since `U` is open, we can write `U` as a union of clopen sets all of which -- are preimages of clopens from the factors in the limit. obtain ⟨S, hS, h⟩ := hB.open_eq_sUnion hU.2 clear hB let j : S → J := fun s => (hS s.2).choose let V : ∀ s : S, Set (F.obj (j s)) := fun s => (hS s.2).choose_spec.choose have hV : ∀ s : S, IsClopen (V s) ∧ s.1 = C.π.app (j s) ⁻¹' V s := fun s => (hS s.2).choose_spec.choose_spec -- Since `U` is also closed, hence compact, it is covered by finitely many of the -- clopens constructed in the previous step. have hUo : ∀ (i : ↑S), IsOpen ((fun s ↦ (C.π.app (j s)) ⁻¹' V s) i) := by intro s exact (hV s).1.2.preimage (C.π.app (j s)).hom.continuous have hsU : U ⊆ ⋃ (i : ↑S), (fun s ↦ C.π.app (j s) ⁻¹' V s) i := by dsimp only rw [h] rintro x ⟨T, hT, hx⟩ refine ⟨_, ⟨⟨T, hT⟩, rfl⟩, ?_⟩ dsimp only rwa [← (hV ⟨T, hT⟩).2] have := hU.1.isCompact.elim_finite_subcover (fun s : S => C.π.app (j s) ⁻¹' V s) hUo hsU -- Porting note: same remark as after `hB` -- We thus obtain a finite set `G : Finset J` and a clopen set of `F.obj j` for each -- `j ∈ G` such that `U` is the union of the preimages of these clopen sets. obtain ⟨G, hG⟩ := this -- Since `J` is cofiltered, we can find a single `j0` dominating all the `j ∈ G`. -- Pulling back all of the sets from the previous step to `F.obj j0` and taking a union, -- we obtain a clopen set in `F.obj j0` which works. classical obtain ⟨j0, hj0⟩ := IsCofiltered.inf_objs_exists (G.image j) let f : ∀ s ∈ G, j0 ⟶ j s := fun s hs => (hj0 (Finset.mem_image.mpr ⟨s, hs, rfl⟩)).some let W : S → Set (F.obj j0) := fun s => if hs : s ∈ G then F.map (f s hs) ⁻¹' V s else Set.univ -- Conclude, using the `j0` and the clopen set of `F.obj j0` obtained above. refine ⟨j0, ⋃ (s : S) (_ : s ∈ G), W s, ?_, ?_⟩ · apply isClopen_biUnion_finset intro s hs dsimp [W] rw [dif_pos hs] exact ⟨(hV s).1.1.preimage (F.map _).hom.continuous, (hV s).1.2.preimage (F.map _).hom.continuous⟩ · ext x constructor · intro hx simp_rw [W, Set.preimage_iUnion, Set.mem_iUnion] obtain ⟨_, ⟨s, rfl⟩, _, ⟨hs, rfl⟩, hh⟩ := hG hx refine ⟨s, hs, ?_⟩ rwa [dif_pos hs, ← Set.preimage_comp, ← CompHausLike.coe_comp, C.w] · intro hx simp_rw [W, Set.preimage_iUnion, Set.mem_iUnion] at hx obtain ⟨s, hs, hx⟩ := hx rw [h] refine ⟨s.1, s.2, ?_⟩ rw [(hV s).2] rwa [dif_pos hs, ← Set.preimage_comp, ← CompHausLike.coe_comp, C.w] at hx theorem exists_locallyConstant_fin_two (hC : IsLimit C) (f : LocallyConstant C.pt (Fin 2)) : ∃ (j : J) (g : LocallyConstant (F.obj j) (Fin 2)), f = g.comap (C.π.app _).hom := by let U := f ⁻¹' {0} have hU : IsClopen U := f.isLocallyConstant.isClopen_fiber _ obtain ⟨j, V, hV, h⟩ := exists_isClopen_of_cofiltered C hC hU classical use j, LocallyConstant.ofIsClopen hV apply LocallyConstant.locallyConstant_eq_of_fiber_zero_eq simp only [Fin.isValue, Functor.const_obj_obj, LocallyConstant.coe_comap, Set.preimage_comp, LocallyConstant.ofIsClopen_fiber_zero] exact h open Classical in theorem exists_locallyConstant_finite_aux {α : Type*} [Finite α] (hC : IsLimit C) (f : LocallyConstant C.pt α) : ∃ (j : J) (g : LocallyConstant (F.obj j) (α → Fin 2)), (f.map fun a b => if a = b then (0 : Fin 2) else 1) = g.comap (C.π.app _).hom := by cases nonempty_fintype α let ι : α → α → Fin 2 := fun x y => if x = y then 0 else 1 let ff := (f.map ι).flip have hff := fun a : α => exists_locallyConstant_fin_two _ hC (ff a) choose j g h using hff let G : Finset J := Finset.univ.image j obtain ⟨j0, hj0⟩ := IsCofiltered.inf_objs_exists G have hj : ∀ a, j a ∈ (Finset.univ.image j : Finset J) := by grind let fs : ∀ a : α, j0 ⟶ j a := fun a => (hj0 (hj a)).some let gg : α → LocallyConstant (F.obj j0) (Fin 2) := fun a => (g a).comap (F.map (fs _)).hom let ggg := LocallyConstant.unflip gg refine ⟨j0, ggg, ?_⟩ have : f.map ι = LocallyConstant.unflip (f.map ι).flip := by simp rw [this]; clear this have : LocallyConstant.comap (C.π.app j0).hom ggg = LocallyConstant.unflip (LocallyConstant.comap (C.π.app j0).hom ggg).flip := by simp rw [this]; clear this congr 1 ext1 a change ff a = _ rw [h] dsimp ext1 x change _ = (g a) ((C.π.app j0 ≫ F.map (fs a)) x) rw [C.w]; rfl theorem exists_locallyConstant_finite_nonempty {α : Type*} [Finite α] [Nonempty α] (hC : IsLimit C) (f : LocallyConstant C.pt α) : ∃ (j : J) (g : LocallyConstant (F.obj j) α), f = g.comap (C.π.app _).hom := by inhabit α obtain ⟨j, gg, h⟩ := exists_locallyConstant_finite_aux _ hC f classical let ι : α → α → Fin 2 := fun a b => if a = b then 0 else 1 let σ : (α → Fin 2) → α := fun f => if h : ∃ a : α, ι a = f then h.choose else default refine ⟨j, gg.map σ, ?_⟩ ext x simp only [Functor.const_obj_obj, LocallyConstant.coe_comap, LocallyConstant.map_apply, Function.comp_apply] dsimp [σ] have h1 : ι (f x) = gg (C.π.app j x) := by change f.map (fun a b => if a = b then (0 : Fin 2) else 1) x = _ rw [h] rfl have h2 : ∃ a : α, ι a = gg (C.π.app j x) := ⟨f x, h1⟩ rw [dif_pos] swap · assumption apply_fun ι · rw [h2.choose_spec] exact h1 · intro a b hh have hhh := congr_fun hh a dsimp [ι] at hhh rw [if_pos rfl] at hhh split_ifs at hhh with hh1 · exact hh1.symm · exact False.elim (bot_ne_top hhh) /-- Any locally constant function from a cofiltered limit of profinite sets factors through one of the components. -/ theorem exists_locallyConstant {α : Type*} (hC : IsLimit C) (f : LocallyConstant C.pt α) : ∃ (j : J) (g : LocallyConstant (F.obj j) α), f = g.comap (C.π.app _).hom := by let S := f.discreteQuotient let ff : S → α := f.lift cases isEmpty_or_nonempty S · suffices ∃ j, IsEmpty (F.obj j) by refine this.imp fun j hj => ?_ refine ⟨⟨hj.elim, fun A => ?_⟩, ?_⟩ · suffices (fun a ↦ IsEmpty.elim hj a) ⁻¹' A = ∅ by rw [this] exact isOpen_empty exact @Set.eq_empty_of_isEmpty _ hj _ · ext x exact hj.elim' (C.π.app j x) simp only [← not_nonempty_iff, ← not_forall] intro h haveI : ∀ j : J, Nonempty ((F ⋙ Profinite.toTopCat).obj j) := h haveI : ∀ j : J, T2Space ((F ⋙ Profinite.toTopCat).obj j) := fun j => (inferInstance : T2Space (F.obj j)) haveI : ∀ j : J, CompactSpace ((F ⋙ Profinite.toTopCat).obj j) := fun j => (inferInstance : CompactSpace (F.obj j)) have cond := TopCat.nonempty_limitCone_of_compact_t2_cofiltered_system.{u} (F ⋙ Profinite.toTopCat) suffices Nonempty C.pt from IsEmpty.false (S.proj this.some) let D := Profinite.toTopCat.mapCone C have hD : IsLimit D := isLimitOfPreserves Profinite.toTopCat hC have CD := (hD.conePointUniqueUpToIso (TopCat.limitConeIsLimit.{v, max u v} _)).inv exact cond.map CD · let f' : LocallyConstant C.pt S := ⟨S.proj, S.proj_isLocallyConstant⟩ obtain ⟨j, g', hj⟩ := exists_locallyConstant_finite_nonempty _ hC f' refine ⟨j, ⟨ff ∘ g', g'.isLocallyConstant.comp _⟩, ?_⟩ ext1 t apply_fun fun e => e t at hj dsimp at hj ⊢ rw [← hj] rfl end Profinite
Cofinal.lean
/- Copyright (c) 2024 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import Mathlib.Order.GaloisConnection.Basic import Mathlib.Order.Interval.Set.Basic import Mathlib.Order.WellFounded /-! # Cofinal sets A set `s` in an ordered type `α` is cofinal when for every `a : α` there exists an element of `s` greater or equal to it. This file provides a basic API for the `IsCofinal` predicate. For the cofinality of a set as a cardinal, see `Mathlib/SetTheory/Cardinal/Cofinality.lean`. ## TODO - Define `Order.cof` in terms of `Cofinal`. - Deprecate `Order.Cofinal` in favor of this predicate. -/ variable {α β : Type*} section LE variable [LE α] theorem IsCofinal.of_isEmpty [IsEmpty α] (s : Set α) : IsCofinal s := fun a ↦ isEmptyElim a theorem isCofinal_empty_iff : IsCofinal (∅ : Set α) ↔ IsEmpty α := by refine ⟨fun h ↦ ⟨fun a ↦ ?_⟩, fun h ↦ .of_isEmpty _⟩ simpa using h a theorem IsCofinal.singleton_top [OrderTop α] : IsCofinal {(⊤ : α)} := fun _ ↦ ⟨⊤, Set.mem_singleton _, le_top⟩ theorem IsCofinal.mono {s t : Set α} (h : s ⊆ t) (hs : IsCofinal s) : IsCofinal t := by intro a obtain ⟨b, hb, hb'⟩ := hs a exact ⟨b, h hb, hb'⟩ end LE section Preorder variable [Preorder α] theorem IsCofinal.univ : IsCofinal (@Set.univ α) := fun a ↦ ⟨a, ⟨⟩, le_rfl⟩ instance : Inhabited {s : Set α // IsCofinal s} := ⟨_, .univ⟩ /-- A cofinal subset of a cofinal subset is cofinal. -/ theorem IsCofinal.trans {s : Set α} {t : Set s} (hs : IsCofinal s) (ht : IsCofinal t) : IsCofinal (Subtype.val '' t) := by intro a obtain ⟨b, hb, hb'⟩ := hs a obtain ⟨c, hc, hc'⟩ := ht ⟨b, hb⟩ exact ⟨c, Set.mem_image_of_mem _ hc, hb'.trans hc'⟩ theorem GaloisConnection.map_cofinal [Preorder β] {f : β → α} {g : α → β} (h : GaloisConnection f g) {s : Set α} (hs : IsCofinal s) : IsCofinal (g '' s) := by intro a obtain ⟨b, hb, hb'⟩ := hs (f a) exact ⟨g b, Set.mem_image_of_mem _ hb, h.le_iff_le.1 hb'⟩ theorem OrderIso.map_cofinal [Preorder β] (e : α ≃o β) {s : Set α} (hs : IsCofinal s) : IsCofinal (e '' s) := e.symm.to_galoisConnection.map_cofinal hs end Preorder section PartialOrder variable [PartialOrder α] theorem IsCofinal.mem_of_isMax {s : Set α} {a : α} (ha : IsMax a) (hs : IsCofinal s) : a ∈ s := by obtain ⟨b, hb, hb'⟩ := hs a rwa [ha.eq_of_ge hb'] at hb theorem IsCofinal.top_mem [OrderTop α] {s : Set α} (hs : IsCofinal s) : ⊤ ∈ s := hs.mem_of_isMax isMax_top @[simp] theorem isCofinal_iff_top_mem [OrderTop α] {s : Set α} : IsCofinal s ↔ ⊤ ∈ s := ⟨IsCofinal.top_mem, fun hs _ ↦ ⟨⊤, hs, le_top⟩⟩ end PartialOrder section LinearOrder variable [LinearOrder α] theorem not_isCofinal_iff {s : Set α} : ¬ IsCofinal s ↔ ∃ x, ∀ y ∈ s, y < x := by simp [IsCofinal] theorem BddAbove.of_not_isCofinal {s : Set α} (h : ¬ IsCofinal s) : BddAbove s := by rw [not_isCofinal_iff] at h obtain ⟨x, h⟩ := h exact ⟨x, fun y hy ↦ (h y hy).le⟩ theorem IsCofinal.of_not_bddAbove {s : Set α} (h : ¬ BddAbove s) : IsCofinal s := by contrapose! h exact .of_not_isCofinal h /-- In a linear order with no maximum, cofinal sets are the same as unbounded sets. -/ theorem not_isCofinal_iff_bddAbove [NoMaxOrder α] {s : Set α} : ¬ IsCofinal s ↔ BddAbove s := by use .of_not_isCofinal rw [not_isCofinal_iff] rintro ⟨x, h⟩ obtain ⟨z, hz⟩ := exists_gt x exact ⟨z, fun y hy ↦ (h hy).trans_lt hz⟩ /-- In a linear order with no maximum, cofinal sets are the same as unbounded sets. -/ theorem not_bddAbove_iff_isCofinal [NoMaxOrder α] {s : Set α} : ¬ BddAbove s ↔ IsCofinal s := not_iff_comm.1 not_isCofinal_iff_bddAbove /-- The set of "records" (the smallest inputs yielding the highest values) with respect to a well-ordering of `α` is a cofinal set. -/ theorem isCofinal_setOf_imp_lt (r : α → α → Prop) [h : IsWellFounded α r] : IsCofinal { a | ∀ b, r b a → b < a } := by intro a obtain ⟨b, hb, hb'⟩ := h.wf.has_min (Set.Ici a) Set.nonempty_Ici refine ⟨b, fun c hc ↦ ?_, hb⟩ by_contra! hc' exact hb' c (hb.trans hc') hc end LinearOrder
Sign.lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Eric Wieser -/ import Mathlib.Data.Real.Basic import Mathlib.Tactic.NormNum.Inv /-! # Real sign function This file introduces and contains some results about `Real.sign` which maps negative real numbers to -1, positive real numbers to 1, and 0 to 0. ## Main definitions * `Real.sign r` is $\begin{cases} -1 & \text{if } r < 0, \\ ~~\, 0 & \text{if } r = 0, \\ ~~\, 1 & \text{if } r > 0. \end{cases}$ ## Tags sign function -/ namespace Real /-- The sign function that maps negative real numbers to -1, positive numbers to 1, and 0 otherwise. -/ noncomputable def sign (r : ℝ) : ℝ := if r < 0 then -1 else if 0 < r then 1 else 0 theorem sign_of_neg {r : ℝ} (hr : r < 0) : sign r = -1 := by rw [sign, if_pos hr] theorem sign_of_pos {r : ℝ} (hr : 0 < r) : sign r = 1 := by rw [sign, if_pos hr, if_neg hr.not_gt] @[simp] theorem sign_zero : sign 0 = 0 := by rw [sign, if_neg (lt_irrefl _), if_neg (lt_irrefl _)] @[simp] theorem sign_one : sign 1 = 1 := sign_of_pos <| by simp theorem sign_apply_eq (r : ℝ) : sign r = -1 ∨ sign r = 0 ∨ sign r = 1 := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · exact Or.inl <| sign_of_neg hn · exact Or.inr <| Or.inl <| sign_zero · exact Or.inr <| Or.inr <| sign_of_pos hp /-- This lemma is useful for working with `ℝˣ` -/ theorem sign_apply_eq_of_ne_zero (r : ℝ) (h : r ≠ 0) : sign r = -1 ∨ sign r = 1 := h.lt_or_gt.imp sign_of_neg sign_of_pos @[simp] theorem sign_eq_zero_iff {r : ℝ} : sign r = 0 ↔ r = 0 := by refine ⟨fun h => ?_, fun h => h.symm ▸ sign_zero⟩ obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · rw [sign_of_neg hn, neg_eq_zero] at h exact (one_ne_zero h).elim · rfl · rw [sign_of_pos hp] at h exact (one_ne_zero h).elim theorem sign_intCast (z : ℤ) : sign (z : ℝ) = ↑(Int.sign z) := by obtain hn | rfl | hp := lt_trichotomy z (0 : ℤ) · rw [sign_of_neg (Int.cast_lt_zero.mpr hn), Int.sign_eq_neg_one_of_neg hn, Int.cast_neg, Int.cast_one] · rw [Int.cast_zero, sign_zero, Int.sign_zero, Int.cast_zero] · rw [sign_of_pos (Int.cast_pos.mpr hp), Int.sign_eq_one_of_pos hp, Int.cast_one] theorem sign_neg {r : ℝ} : sign (-r) = -sign r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · rw [sign_of_neg hn, sign_of_pos (neg_pos.mpr hn), neg_neg] · rw [sign_zero, neg_zero, sign_zero] · rw [sign_of_pos hp, sign_of_neg (neg_lt_zero.mpr hp)] theorem sign_mul_nonneg (r : ℝ) : 0 ≤ sign r * r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · rw [sign_of_neg hn] exact mul_nonneg_of_nonpos_of_nonpos (by simp) hn.le · rw [mul_zero] · rw [sign_of_pos hp, one_mul] exact hp.le theorem sign_mul_pos_of_ne_zero (r : ℝ) (hr : r ≠ 0) : 0 < sign r * r := by refine lt_of_le_of_ne (sign_mul_nonneg r) fun h => hr ?_ have hs0 := (zero_eq_mul.mp h).resolve_right hr exact sign_eq_zero_iff.mp hs0 @[simp] theorem inv_sign (r : ℝ) : (sign r)⁻¹ = sign r := by obtain hn | hz | hp := sign_apply_eq r · rw [hn] norm_num · rw [hz] exact inv_zero · rw [hp] exact inv_one @[simp] theorem sign_inv (r : ℝ) : sign r⁻¹ = sign r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · rw [sign_of_neg hn, sign_of_neg (inv_lt_zero.mpr hn)] · rw [sign_zero, inv_zero, sign_zero] · rw [sign_of_pos hp, sign_of_pos (inv_pos.mpr hp)] end Real
monoid.v
From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype choice ssrnat seq. From mathcomp Require Import bigop fintype finfun. (******************************************************************************) (* Group-like structures *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines the following algebraic structures: *) (* *) (* magmaType == magma *) (* The HB class is called Magma. *) (* ChoiceMagma.type == join of magmaType and choiceType *) (* The HB class is called ChoiceMagma. *) (* semigroupType == associative magma *) (* The HB class is called Semigroup. *) (* baseUMagmaType == pointed magma *) (* The HB class is called BaseUMagma. *) (* ChoiceBaseUMagma.type == join of baseUMagmaType and choiceType *) (* The HB class is called ChoiceBaseUMagma. *) (* umagmaType == unitary magma *) (* The HB class is called UMagma. *) (* monoidType == monoid *) (* The HB class is called Monoid. *) (* baseGroupType == pointed magma with an inversion operator *) (* The HB class is called BaseGroup. *) (* groupType == group *) (* The HB class is called Group. *) (* *) (* and their joins with subType: *) (* *) (* subMagmaType V P == join of magmaType and subType (P : pred V) such *) (* that val is multiplicative *) (* The HB class is called SubMagma. *) (* subSemigroupType V P == join of semigroupType and subType (P : pred V) *) (* such that val is multiplicative *) (* The HB class is called SubSemigroup. *) (* subBaseUMagmaType V P == join of baseUMagmaType and subType (P : pred V) *) (* such that val is multiplicative and preserves 1 *) (* The HB class is called SubBaseUMagma. *) (* subUMagmaType V P == join of UMagmaType and subType (P : pred V) *) (* such that val is multiplicative and preserves 1 *) (* The HB class is called SubUMagma. *) (* subMonoidType V P == join of monoidType and subType (P : pred V) *) (* such that val is multiplicative and preserves 1 *) (* The HB class is called SubMonoid. *) (* subGroupType V P == join of groupType and subType (P : pred V) *) (* such that val is multiplicative and preserves 1 *) (* The HB class is called SubGroup. *) (* *) (* Morphisms between the above structures: *) (* *) (* Multiplicative.type G H == multiplicative functions between magmaType *) (* instances G and H *) (* UMagmaMorphism.type G H == multiplicative functions preserving 1 between *) (* baseUMagmaType instances G and H *) (* *) (* 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: *) (* * magmaType (magmas): *) (* x * y == the product of x and y *) (* commute x y <-> x and y commute (i.e. x * y = y * x) *) (* mulg_closed S <-> collective predicate S is closed under *) (* multiplication *) (* *) (* * baseUMagmaType (pointed magmas): *) (* 1 == the unit of a unitary magma *) (* x ^+ n == x to the power n, 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 *) (* \prod<range> e == iterated product for a baseUMagmaType (cf bigop.v)*) (* umagma_closed S <-> collective predicate S is closed under *) (* multiplication and contains 1 *) (* *) (* * monoidType (monoids): *) (* monoid_closed S := umagma_closed S *) (* *) (* * baseGroupType (pointed magmas with an inversion operator): *) (* x ^-1 == the inverse of x *) (* x / y == x * (y ^- 1) *) (* x ^- n == (x ^+ n)^-1 *) (* x ^ y := y^-1 * (x * y) *) (* == the conjugate of x by y *) (* [~ x, y] := x^-1 * (y^-1 * (x * y) *) (* == the commutator of x and y *) (* invg_closed S <-> collective predicate S is closed under inversion *) (* divg_closed S <-> collective predicate S is closed under division *) (* group_closed S <-> collective predicate S is closed under division *) (* and contains 1 *) (* *) (* In addition to this structure hierarchy, we also develop a separate, *) (* *) (* * Multiplicative (magma morphisms): *) (* {multiplicative U -> V} == the interface type for magma morphisms, i.e. *) (* functions from U to V which maps * in U to * in *) (* V; both U and V must have magmaType instances *) (* := GRing.RMorphism.type R S *) (* *) (* * UMagmaMorphism (unitary magma morphisms): *) (* monoid_morphism f <-> f of type U -> V is a multiplicative monoid *) (* morphism, i.e., f maps 1 and * in U to 1 and *) (* * in V, respectively. U and V must have *) (* canonical baseUMagmaType instances. *) (*Algebra.UMagmaMorphism.type == the interface type for unitary magma *) (* morphisms; both U and V must have magmaType *) (* instances *) (* *) (* Notations are defined in scope group_scope (delimiter %g) *) (* This library also extends the conventional suffixes described in library *) (* ssrbool.v with the following: *) (* 1 -- unitary magma 1, as in mulg1 : x * 1 = x *) (* M -- magma multiplication, as in conjgM : x ^ (y * z) = (x ^ y) ^ z *) (* Mn -- ring by nat multiplication, as in expgMn : *) (* (x * y) ^+ n = x ^+ n * y ^+ n *) (* V -- group inverse, as in expVgn : (x^-1) ^+ n = x ^- n *) (* F -- group division, as in invgF : (x / y)^-1 = y / x *) (* X -- unitary magma exponentiation, as in conjXg : *) (* (x ^+ n) ^ y = (x ^ y) ^+ n *) (* J -- group conjugation, as in conjJg : (x ^ y) ^ z = (x ^ z) ^ y ^ z *) (* R -- group commutator, as in conjRg : [~ x, y] ^ z = [~ x ^ z, y ^ z] *) (* The operator suffixes D, B, M and X are also used for the corresponding *) (* operations on nat, as in expgnDr : x ^+ (m + n) = x ^+ m * x ^+ n. For the *) (* binary power operator, a trailing "n" suffix is used to indicate the *) (* operator suffix applies to the left-hand group argument, as in *) (* expg1n : 1 ^+ n = 1 vs. expg1 : x ^+ 1 = x. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "*%g" (at level 0). Reserved Notation "\1" (at level 0). Reserved Notation "f \* g" (at level 40, left associativity). Reserved Notation "'{' 'multiplicative' G '->' H '}'" (at level 0, G at level 98, H at level 99, format "{ 'multiplicative' G -> H }"). Declare Scope group_scope. Delimit Scope group_scope with g. Local Open Scope group_scope. HB.mixin Record hasMul G := { mul : G -> G -> G }. #[short(type="magmaType")] HB.structure Definition Magma := {G of hasMul G}. Bind Scope group_scope with Magma.sort. HB.structure Definition ChoiceMagma := {G of Magma G & Choice G}. Bind Scope group_scope with ChoiceMagma.sort. Local Notation "*%g" := (@mul _) : function_scope. Local Notation "x * y" := (mul x y) : group_scope. Section MagmaTheory. Variable G : magmaType. Implicit Types x y : G. Definition commute x y := x * y = y * x. Lemma commute_refl x : commute x x. Proof. by []. Qed. Lemma commute_sym x y : commute x y -> commute y x. Proof. by []. Qed. Section ClosedPredicates. Variable S : {pred G}. Definition mulg_closed := {in S &, forall u v, u * v \in S}. End ClosedPredicates. End MagmaTheory. HB.mixin Record Magma_isSemigroup G of Magma G := { mulgA : associative (@mul G) }. #[short(type="semigroupType")] HB.structure Definition Semigroup := {G of Magma_isSemigroup G & ChoiceMagma G}. HB.factory Record isSemigroup G of Choice G := { mul : G -> G -> G; mulgA : associative mul }. HB.builders Context G of isSemigroup G. HB.instance Definition _ := hasMul.Build G mul. HB.instance Definition _ := Magma_isSemigroup.Build G mulgA. HB.end. Bind Scope group_scope with Semigroup.sort. Section SemigroupTheory. Variable G : semigroupType. Implicit Types x y : G. Lemma commuteM x y z : commute x y -> commute x z -> commute x (y * z). Proof. by move=> cxy cxz; rewrite /commute -mulgA -cxz !mulgA cxy. Qed. End SemigroupTheory. HB.mixin Record hasOne G := { one : G }. #[short(type="baseUMagmaType")] HB.structure Definition BaseUMagma := {G of hasOne G & Magma G}. Bind Scope group_scope with BaseUMagma.sort. HB.structure Definition ChoiceBaseUMagma := {G of BaseUMagma G & Choice G}. Bind Scope group_scope with ChoiceBaseUMagma.sort. Local Notation "1" := (@one _) : group_scope. Local Notation "s `_ i" := (nth 1 s i) : group_scope. Local Notation "\prod_ ( i <- r | P ) F" := (\big[*%g/1]_(i <- r | P) F). Local Notation "\prod_ ( i | P ) F" := (\big[*%g/1]_(i | P) F). Local Notation "\prod_ ( i 'in' A ) F" := (\big[*%g/1]_(i in A) F). Local Notation "\prod_ ( m <= i < n ) F" := (\big[*%g/1%g]_(m <= i < n) F%g). Definition natexp (G : baseUMagmaType) (x : G) n : G := iterop n *%g x 1. Arguments natexp : simpl never. Local Notation "x ^+ n" := (natexp x n) : group_scope. Section baseUMagmaTheory. Variable G : baseUMagmaType. Implicit Types x : G. Lemma expg0 x : x ^+ 0 = 1. Proof. by []. Qed. Lemma expg1 x : x ^+ 1 = x. Proof. by []. Qed. Lemma expg2 x : x ^+ 2 = x * x. Proof. by []. Qed. Lemma expgSS x n : x ^+ n.+2 = x * x ^+ n.+1. Proof. by []. Qed. Lemma expgb x (b : bool) : x ^+ b = (if b then x else 1). Proof. by case: b. Qed. Section ClosedPredicates. Variable S : {pred G}. Definition umagma_closed := 1 \in S /\ mulg_closed S. End ClosedPredicates. End baseUMagmaTheory. HB.mixin Record BaseUMagma_isUMagma G of BaseUMagma G := { mul1g : left_id one (@mul G); mulg1 : right_id one (@mul G) }. HB.factory Record Magma_isUMagma G of Magma G := { one : G; mul1g : left_id one (@mul G); mulg1 : right_id one (@mul G) }. HB.builders Context G of Magma_isUMagma G. HB.instance Definition _ := hasOne.Build G one. #[warning="-HB.no-new-instance"] HB.instance Definition _ := BaseUMagma_isUMagma.Build G mul1g mulg1. HB.end. #[short(type="umagmaType")] HB.structure Definition UMagma := {G of Magma_isUMagma G & ChoiceMagma G}. Bind Scope group_scope with UMagma.sort. Section UMagmaTheory. Variable G : umagmaType. Implicit Types x y : G. Lemma expgS x n : x ^+ n.+1 = x * x ^+ n. Proof. by case: n => //=; rewrite mulg1. Qed. Lemma expg1n n : 1 ^+ n = 1 :> G. Proof. by elim: n => // n IHn; rewrite expgS mul1g. Qed. Lemma commute1 x : commute x 1. Proof. by rewrite /commute mulg1 mul1g. Qed. End UMagmaTheory. #[short(type="monoidType")] HB.structure Definition Monoid := {G of Magma_isUMagma G & Semigroup G}. HB.factory Record Semigroup_isMonoid G of Semigroup G := { one : G; mul1g : left_id one mul; mulg1 : right_id one mul }. HB.builders Context G of Semigroup_isMonoid G. HB.instance Definition _ := Magma_isUMagma.Build G mul1g mulg1. HB.end. HB.factory Record UMagma_isMonoid G of UMagma G := { mulgA : associative (@mul G) }. HB.builders Context G of UMagma_isMonoid G. HB.instance Definition _ := Magma_isSemigroup.Build G mulgA. HB.end. HB.factory Record isMonoid G of Choice G := { mul : G -> G -> G; one : G; mulgA : associative mul; mul1g : left_id one mul; mulg1 : right_id one mul }. HB.builders Context G of isMonoid G. HB.instance Definition _ := hasMul.Build G mul. HB.instance Definition _ := Magma_isSemigroup.Build G mulgA. HB.instance Definition _ := Magma_isUMagma.Build G mul1g mulg1. HB.end. #[export] HB.instance Definition _ (G : monoidType) := Monoid.isLaw.Build G 1 *%g mulgA mul1g mulg1. Bind Scope group_scope with Monoid.sort. Section MonoidTheory. Variable G : monoidType. Implicit Types x y : G. Lemma expgSr x n : x ^+ n.+1 = x ^+ n * x. Proof. elim: n => [|n IHn]; first by rewrite mul1g. by rewrite expgS [in LHS]IHn expgS mulgA. Qed. Lemma expgnDr x m n : x ^+ (m + n) = x ^+ m * x ^+ n. Proof. elim: m => [|m IHm]; first by rewrite mul1g. by rewrite 2!expgS IHm mulgA. Qed. Lemma expgnA x m n : x ^+ (m * n) = x ^+ m ^+ n. Proof. by rewrite mulnC; elim: n => //= n IHn; rewrite expgS expgnDr IHn. Qed. Lemma expgnAC x m n : x ^+ m ^+ n = x ^+ n ^+ m. Proof. by rewrite -2!expgnA mulnC. Qed. Lemma iter_mulg n x y : iter n ( *%g x) y = x ^+ n * y. Proof. by elim: n => [|n IHn]; rewrite ?mul1g //= IHn expgS mulgA. Qed. Lemma iter_mulg_1 n x : iter n ( *%g x) 1 = x ^+ n. Proof. by rewrite iter_mulg mulg1. Qed. Lemma prodg_const (I : finType) (A : pred I) x : \prod_(i in A) x = x ^+ #|A|. Proof. by rewrite big_const -Monoid.iteropE. Qed. Lemma prodg_const_nat n m x : \prod_(n <= i < m) x = x ^+ (m - n). Proof. by rewrite big_const_nat -Monoid.iteropE. Qed. Lemma prodgXr x I r P (F : I -> nat) : \prod_(i <- r | P i) x ^+ F i = x ^+ (\sum_(i <- r | P i) F i). Proof. by rewrite (big_morph _ (expgnDr _) (erefl _)). Qed. Lemma commute_prod (I : Type) (s : seq I) (P : pred I) (F : I -> G) x : (forall i, P i -> commute x (F i)) -> commute x (\prod_(i <- s | P i) F i). Proof. exact: (big_ind _ (commute1 x) (@commuteM _ x)). Qed. Lemma prodgM_commute {I : eqType} r (P : pred I) (F H : I -> G) : (forall i j, P i -> P j -> commute (F i) (H j)) -> \prod_(i <- r | P i) (F i * H i) = \prod_(i <- r | P i) F i * \prod_(i <- r | P i) H i. Proof. move=> FH; elim: r => [|i r IHr]; rewrite !(big_nil, big_cons) ?mulg1//. case: ifPn => // Pi; rewrite IHr !mulgA; congr (_ * _); rewrite -!mulgA. by rewrite commute_prod // => j Pj; apply/commute_sym/FH. Qed. Lemma prodgMl_commute {I : finType} (A : pred I) (x : G) F : (forall i, A i -> commute x (F i)) -> \prod_(i in A) (x * F i) = x ^+ #|A| * \prod_(i in A) F i. Proof. by move=> xF; rewrite prodgM_commute ?prodg_const// => i j _ /xF. Qed. Lemma prodgMr_commute {I : finType} (A : pred I) (x : G) F : (forall i, A i -> commute x (F i)) -> \prod_(i in A) (F i * x) = \prod_(i in A) F i * x ^+ #|A|. Proof. by move=> xF; rewrite prodgM_commute ?prodg_const// => i j /xF. Qed. Lemma commuteX x y n : commute x y -> commute x (y ^+ n). Proof. by move=> cxy; case: n; [apply: commute1 | elim=> // n; apply: commuteM]. Qed. Lemma commuteX2 x y m n : commute x y -> commute (x ^+ m) (y ^+ n). Proof. by move=> cxy; apply/commuteX/commute_sym/commuteX. Qed. Lemma expgMn x y n : commute x y -> (x * y) ^+ n = x ^+ n * y ^+ n. Proof. move=> cxy; elim: n => [|n IHn]; first by rewrite mulg1. by rewrite !expgS IHn -mulgA (mulgA y) (commuteX _ (commute_sym cxy)) !mulgA. Qed. End MonoidTheory. Notation monoid_closed := umagma_closed. HB.mixin Record hasInv G := { inv : G -> G }. #[short(type="baseGroupType")] HB.structure Definition BaseGroup := {G of hasInv G & BaseUMagma G}. Bind Scope group_scope with BaseGroup.sort. HB.mixin Record Monoid_isGroup G of BaseGroup G := { mulVg : left_inverse one inv (@mul G); mulgV : right_inverse one inv (@mul G) }. #[short(type="groupType")] HB.structure Definition Group := {G of Monoid_isGroup G & BaseGroup G & Monoid G}. HB.factory Record isGroup G of Choice G := { one : G; inv : G -> G; mul : G -> G -> G; mulgA : associative mul; mul1g : left_id one mul; mulg1 : right_id one mul; mulVg : left_inverse one inv mul; mulgV : right_inverse one inv mul }. HB.builders Context G of isGroup G. HB.instance Definition _ := hasMul.Build G mul. HB.instance Definition _ := Magma_isSemigroup.Build G mulgA. HB.instance Definition _ := Magma_isUMagma.Build G mul1g mulg1. HB.instance Definition _ := hasInv.Build G inv. HB.instance Definition _ := Monoid_isGroup.Build G mulVg mulgV. HB.end. Bind Scope group_scope with Group.sort. Local Notation "x ^-1" := (inv x) : group_scope. Local Notation "x / y" := (x * y^-1) : group_scope. Local Notation "x ^- n" := ((x ^+ n)^-1) : group_scope. Definition conjg (G : groupType) (x y : G) := y^-1 * (x * y). Local Notation "x ^ y" := (conjg x y) : group_scope. Definition commg (G : groupType) (x y : G) := x^-1 * (conjg x y). Local Notation "[~ x , y ]" := (commg x y) : group_scope. Section GroupTheory. Variable G : groupType. Implicit Types x y : G. Definition divgg := @mulgV G. Lemma mulKg : @left_loop G G (@inv G) *%g. Proof. by move=> x y; rewrite mulgA mulVg mul1g. Qed. Lemma mulVKg : @rev_left_loop G G (@inv G) *%g. Proof. by move=> x y ; rewrite mulgA mulgV mul1g. Qed. Lemma mulgK : @right_loop G G (@inv G) *%g. Proof. by move=> x y; rewrite -mulgA mulgV mulg1. Qed. Lemma mulgVK : @rev_right_loop G G (@inv G) *%g. Proof. by move=> x y ; rewrite -mulgA mulVg mulg1. Qed. Definition divgK := mulgVK. Lemma mulgI : @right_injective G G G *%g. Proof. by move=> x; apply: can_inj (mulKg x). Qed. Lemma mulIg : @left_injective G G G *%g. Proof. by move=> x; apply: can_inj (mulgK x). Qed. Lemma invgK : @involutive G (@inv G). Proof. by move=> x; rewrite -[LHS](mulVKg x) divgg mulg1. Qed. Lemma invg_inj : @injective G G (@inv G). Proof. exact: inv_inj invgK. Qed. Lemma divgI : @right_injective G G G (fun x y => x / y). Proof. by move=> x y z /mulgI/invg_inj. Qed. Lemma divIg : @left_injective G G G (fun x y => x / y). Proof. by move=> x y z /mulIg. Qed. Lemma invg1 : 1 ^-1 = 1 :> G. Proof. by rewrite -[LHS]mul1g divgg. Qed. Lemma invg_eq1 x : (x ^-1 == 1) = (x == 1). Proof. by rewrite (inv_eq invgK) invg1. Qed. Lemma divg1 x : x / 1 = x. Proof. by rewrite invg1 mulg1. Qed. Lemma div1g x : 1 / x = x^-1. Proof. by rewrite mul1g. Qed. Lemma invgF x y : (x / y)^-1 = y / x. Proof. by apply/(canRL (mulgK x))/(@divIg y); rewrite -mulgA mulVg divgg. Qed. Lemma invgM : {morph (@inv G): x y / x * y >-> y * x : G}. Proof. by move=> x y; rewrite -[y in LHS]invgK invgF. Qed. Lemma prodgV I r (P : pred I) (E : I -> G) : \prod_(i <- r | P i) (E i)^-1 = (\prod_(i <- rev r | P i) E i)^-1. Proof. elim: r => [|x r IHr]; first by rewrite !big_nil invg1. rewrite big_cons rev_cons big_rcons/= IHr. by case: ifP => _; rewrite ?mulg1// invgM. Qed. Lemma divKg x y : commute x y -> x / (x / y) = y. Proof. by move=> xyC; rewrite invgF mulgA xyC mulgK. Qed. (* TOTHINK : This does not have the same form as addrKA in ssralg.v *) Lemma mulgKA z x y : (x * z) / (y * z) = x / y. Proof. by rewrite invgM mulgA mulgK. Qed. Lemma divgKA z x y : (x / z) * (z * y) = x * y. Proof. by rewrite mulgA mulgVK. Qed. Lemma mulg1_eq x y : x * y = 1 -> x^-1 = y. Proof. by rewrite -[x^-1]mulg1 => <-; rewrite mulKg. Qed. Lemma divg1_eq x y : x / y = 1 -> x = y. Proof. by move/mulg1_eq/invg_inj. Qed. Lemma divg_eq x y z : (x / z == y) = (x == y * z). Proof. exact: can2_eq (divgK z) (mulgK z) x y. Qed. Lemma divg_eq1 x y : (x / y == 1) = (x == y). Proof. by rewrite divg_eq mul1g. Qed. Lemma mulg_eq1 x y : (x * y == 1) = (x == y^-1). Proof. by rewrite -[y in LHS]invgK divg_eq1. Qed. Lemma eqg_inv x y : (x^-1 == y^-1) = (x == y). Proof. exact: can_eq invgK x y. Qed. Lemma eqg_invLR x y : (x^-1 == y) = (x == y^-1). Proof. exact: inv_eq invgK x y. Qed. Lemma commuteV x y : commute x y -> commute x y^-1. Proof. by move=> cxy; apply: (@mulIg y); rewrite mulgVK -mulgA cxy mulKg. Qed. Lemma expVgn x n : (x^-1) ^+ n = x ^- n. Proof. apply/esym/mulg1_eq; rewrite -expgMn; first by rewrite divgg expg1n. exact/commuteV. Qed. Lemma expgnFr x m n : n <= m -> x ^+ (m - n) = x ^+ m / x ^+ n. Proof. by move=> lenm; rewrite -[in RHS](subnK lenm) expgnDr mulgK. Qed. Lemma expgnFl x y n : commute x y -> (x / y) ^+ n = x ^+ n / y ^+ n. Proof. by move=> xyC; rewrite expgMn 1?expVgn; last exact/commuteV. Qed. Lemma conjgE x y : x ^ y = y^-1 * (x * y). Proof. by []. Qed. Lemma conjgC x y : x * y = y * x ^ y. Proof. by rewrite mulVKg. Qed. Lemma conjgCV x y : x * y = y ^ x^-1 * x. Proof. by rewrite -mulgA mulgVK invgK. Qed. Lemma conjg1 x : x ^ 1 = x. Proof. by rewrite conjgE commute1 mulKg. Qed. Lemma conj1g x : 1 ^ x = 1. Proof. by rewrite conjgE mul1g mulVg. Qed. Lemma conjMg x y z : (x * y) ^ z = x ^ z * y ^ z. Proof. by rewrite !conjgE !mulgA mulgK. Qed. Lemma conjgM x y z : x ^ (y * z) = (x ^ y) ^ z. Proof. by rewrite !conjgE invgM !mulgA. Qed. Lemma conjVg x y : x^-1 ^ y = (x ^ y)^-1. Proof. by rewrite !conjgE !invgM invgK mulgA. Qed. Lemma conjJg x y z : (x ^ y) ^ z = (x ^ z) ^ y ^ z. Proof. by rewrite 2!conjMg conjVg. Qed. Lemma conjXg x y n : (x ^+ n) ^ y = (x ^ y) ^+ n. Proof. by elim: n => [|n IHn]; rewrite ?conj1g // !expgS conjMg IHn. Qed. Lemma conjgK : @right_loop G G (@inv G) (@conjg G). Proof. by move=> y x; rewrite -conjgM mulgV conjg1. Qed. Lemma conjgKV : @rev_right_loop G G (@inv G) (@conjg G). Proof. by move=> y x; rewrite -conjgM mulVg conjg1. Qed. Lemma conjg_inj : @left_injective G G G (@conjg G). Proof. by move=> y; apply: can_inj (conjgK y). Qed. Lemma conjg_eq1 x y : (x ^ y == 1) = (x == 1). Proof. by rewrite (can2_eq (conjgK _) (conjgKV _)) conj1g. Qed. Lemma commgEl x y : [~ x, y] = x^-1 * x ^ y. Proof. by []. Qed. Lemma commgEr x y : [~ x, y] = y^-1 ^ x * y. Proof. by rewrite -!mulgA. Qed. Lemma commgC x y : x * y = y * x * [~ x, y]. Proof. by rewrite -mulgA !mulVKg. Qed. Lemma commgCV x y : x * y = [~ x^-1, y^-1] * (y * x). Proof. by rewrite commgEl !mulgA !invgK !mulgVK. Qed. Lemma conjRg x y z : [~ x, y] ^ z = [~ x ^ z, y ^ z]. Proof. by rewrite !conjMg !conjVg. Qed. Lemma invgR x y : [~ x, y]^-1 = [~ y, x]. Proof. by rewrite commgEr conjVg invgM invgK. Qed. Lemma commgP x y : reflect (commute x y) ([~ x, y] == 1). Proof. rewrite [[~ x, y]]mulgA -invgM mulg_eq1 eqg_inv eq_sym; apply: eqP. Qed. Lemma conjg_fix x y : x ^ y == x = ([~ x, y] == 1). Proof. by rewrite mulg_eq1 eqg_inv. Qed. Lemma conjg_fixP x y : reflect (x ^ y = x) ([~ x, y] == 1). Proof. by rewrite -conjg_fix; apply: eqP. Qed. Lemma commg1_sym x y : ([~ x, y] == 1) = ([~ y, x] == 1). Proof. by rewrite -invgR (inv_eq invgK) invg1. Qed. Lemma commg1 x : [~ x, 1] = 1. Proof. exact/eqP/commgP/commute1. Qed. Lemma comm1g x : [~ 1, x] = 1. Proof. by rewrite -invgR commg1 invg1. Qed. Lemma commgg x : [~ x, x] = 1. Proof. exact/eqP/commgP. Qed. Lemma commgXg x n : [~ x, x ^+ n] = 1. Proof. exact/eqP/commgP/commuteX. Qed. Lemma commgVg x : [~ x, x^-1] = 1. Proof. exact/eqP/commgP/commuteV. Qed. Lemma commgXVg x n : [~ x, x ^- n] = 1. Proof. exact/eqP/commgP/commuteV/commuteX. Qed. Section ClosedPredicates. Variable S : {pred G}. Definition invg_closed := {in S, forall u, u^-1 \in S}. Definition divg_closed := {in S &, forall u v, u / v \in S}. Definition group_closed := 1 \in S /\ divg_closed. Lemma group_closedV : group_closed -> invg_closed. Proof. by move=> [S1 SB] x /(SB 1)-/(_ S1); rewrite div1g. Qed. Lemma group_closedM : group_closed -> mulg_closed S. Proof. move=> /[dup]-[S1 SB] /group_closedV SV x y xS /SV yS. rewrite -[y]invgK; exact: SB. Qed. End ClosedPredicates. End GroupTheory. (* Morphism hierarchy. *) HB.mixin Record isMultiplicative (G H : magmaType) (apply : G -> H) := { gmulfM : {morph apply : x y / x * y} }. HB.structure Definition Multiplicative (G H : magmaType) := {f of isMultiplicative G H f}. (* TODO: define pointedTypes and generalize this to pointedTypes. *) HB.mixin Record Multiplicative_isUMagmaMorphism (G H : baseUMagmaType) (f : G -> H) := { gmulf1 : f 1 = 1 }. HB.structure Definition UMagmaMorphism (G H : baseUMagmaType) := {f of Multiplicative_isUMagmaMorphism G H f & isMultiplicative G H f}. Definition monoid_morphism (G H : baseUMagmaType) (f : G -> H) : Prop := (f 1 = 1) * {morph f : x y / x * y}. HB.factory Record isUMagmaMorphism (G H : baseUMagmaType) (f : G -> H) := { monoid_morphism_subproof : monoid_morphism f }. HB.builders Context G H apply of isUMagmaMorphism G H apply. HB.instance Definition _ := isMultiplicative.Build G H apply monoid_morphism_subproof.2. HB.instance Definition _ := Multiplicative_isUMagmaMorphism.Build G H apply monoid_morphism_subproof.1. HB.end. HB.factory Record isGroupMorphism (G H : groupType) (f : G -> H) := { gmulfF : {morph f : x y / x / y} }. HB.builders Context G H apply of isGroupMorphism G H apply. Local Lemma gmulf1 : apply 1 = 1. Proof. by rewrite -[1]divg1 gmulfF divgg. Qed. Local Lemma gmulfM : {morph apply : x y / x * y}. Proof. move=> x y; rewrite -[y in LHS] invgK -[y^-1]mul1g. by rewrite !gmulfF gmulf1 div1g invgK. Qed. HB.instance Definition _ := isMultiplicative.Build G H apply gmulfM. HB.instance Definition _ := Multiplicative_isUMagmaMorphism.Build G H apply gmulf1. HB.end. Module MultiplicativeExports. Notation "{ 'multiplicative' U -> V }" := (Multiplicative.type U%type V%type) : type_scope. End MultiplicativeExports. HB.export MultiplicativeExports. (* FIXME: The instance below makes sure that the join instance between *) (* Multiplicative.type and UMagmaMorphism.type is declared in both directions.*) (* HB should do this automatically. *) #[non_forgetful_inheritance] HB.instance Definition _ G H (f : UMagmaMorphism.type G H) := UMagmaMorphism.on (Multiplicative.sort f). Section LiftedMagma. Variables (T : Type) (G : magmaType). Definition mul_fun (f g : T -> G) x := f x * g x. End LiftedMagma. Section LiftedBaseUMagma. Variables (T : Type) (G : baseUMagmaType). Definition one_fun : T -> G := fun=> 1. End LiftedBaseUMagma. Local Notation "\1" := (one_fun _) : function_scope. Local Notation "f \* g" := (mul_fun f g) : function_scope. Arguments one_fun {_} G _ /. Arguments mul_fun {_ _} f g _ /. Section MorphismTheory. Section Magma. Variables (G H : magmaType) (f : {multiplicative G -> H}). Lemma can2_gmulfM f' : cancel f f' -> cancel f' f -> {morph f' : x y / x * y}. Proof. by move=> fK f'K x y; apply: (canLR fK); rewrite gmulfM !f'K. Qed. Lemma gmulf_commute x y : commute x y -> commute (f x) (f y). Proof. by move=> xy; rewrite /commute -!gmulfM xy. Qed. End Magma. Section UMagma. Variables (G H : umagmaType) (f : UMagmaMorphism.type G H). Lemma gmulf_eq1 x : injective f -> (f x == 1) = (x == 1). Proof. by move=> /inj_eq <-; rewrite gmulf1. Qed. Lemma can2_gmulf1 f' : cancel f f' -> cancel f' f -> f' 1 = 1. Proof. by move=> fK f'K; apply: (canLR fK); rewrite gmulf1. Qed. Lemma gmulfXn n : {morph f : x / x ^+ n}. Proof. by elim: n => [|[|n] IHn] x /=; rewrite ?(gmulf1, gmulfM) // IHn. Qed. Lemma gmulf_prod I r (P : pred I) E : f (\prod_(i <- r | P i) E i) = \prod_(i <- r | P i) f (E i). Proof. exact: (big_morph f gmulfM gmulf1). Qed. End UMagma. Section Group. Variables (G H : groupType) (f : UMagmaMorphism.type G H). Lemma gmulfV : {morph f : x / x^-1}. Proof. by move=> x; apply/divg1_eq; rewrite invgK -gmulfM mulVg gmulf1. Qed. Lemma gmulfF : {morph f : x y / x / y}. Proof. by move=> x y; rewrite gmulfM gmulfV. Qed. Lemma gmulf_inj : (forall x, f x = 1 -> x = 1) -> injective f. Proof. by move=> fI x y xy; apply/divg1_eq/fI; rewrite gmulfF xy divgg. Qed. Lemma gmulfXVn n : {morph f : x / x ^- n}. Proof. by move=> x /=; rewrite gmulfV gmulfXn. Qed. Lemma gmulfJ : {morph f : x y / x ^ y}. Proof. by move=> x y; rewrite !gmulfM/= gmulfV. Qed. Lemma gmulfR : {morph f : x y / [~ x, y]}. Proof. by move=> x y; rewrite !gmulfM/= !gmulfV. Qed. End Group. Section MulFun. Variables (G H K : magmaType). Variables (f g : {multiplicative H -> K}) (h : {multiplicative G -> H}). Fact idfun_gmulfM : {morph @idfun G : x y / x * y}. Proof. by []. Qed. HB.instance Definition _ := isMultiplicative.Build G G idfun idfun_gmulfM. Fact comp_gmulfM : {morph f \o h : x y / x * y}. Proof. by move=> x y /=; rewrite !gmulfM. Qed. HB.instance Definition _ := isMultiplicative.Build G K (f \o h) comp_gmulfM. End MulFun. Section Mul1Fun. Variables (G : magmaType) (H : umagmaType). Fact idfun_gmulf1 : idfun 1 = 1 :> H. Proof. by []. Qed. HB.instance Definition _ := Multiplicative_isUMagmaMorphism.Build H H idfun idfun_gmulf1. Fact one_fun_gmulfM : {morph @one_fun G H : x y / x * y}. Proof. by move=> x y; rewrite mulg1. Qed. HB.instance Definition _ := isMultiplicative.Build G H (@one_fun G H) one_fun_gmulfM. End Mul1Fun. Section Mul11Fun. Variables (G H K : umagmaType). Variables (f g : UMagmaMorphism.type H K) (h : UMagmaMorphism.type G H). Fact comp_gmulf1 : (f \o h) 1 = 1. Proof. by rewrite /= !gmulf1. Qed. #[warning="-HB.no-new-instance"] HB.instance Definition _ := Multiplicative_isUMagmaMorphism.Build G K (f \o h) comp_gmulf1. Fact one_fun_gmulf1 : @one_fun G H 1 = 1. Proof. by []. Qed. HB.instance Definition _ := Multiplicative_isUMagmaMorphism.Build G H (@one_fun G H) one_fun_gmulf1. Fact mul_fun_gmulf1 : (f \* g) 1 = 1. Proof. by rewrite /= !gmulf1 mulg1. Qed. End Mul11Fun. End MorphismTheory. (* Mixins for stability properties *) HB.mixin Record isMulClosed (G : magmaType) (S : {pred G}) := { gpredM : mulg_closed S }. HB.mixin Record isMul1Closed (G : baseUMagmaType) (S : {pred G}) := { gpred1 : 1 \in S }. HB.mixin Record isInvClosed (G : groupType) (S : {pred G}) := { gpredVr : invg_closed S }. (* Structures for stability properties *) #[short(type="mulgClosed")] HB.structure Definition MulClosed G := {S of isMulClosed G S}. #[short(type="umagmaClosed")] HB.structure Definition UMagmaClosed G := {S of isMul1Closed G S & isMulClosed G S}. #[short(type="invgClosed")] HB.structure Definition InvClosed G := {S of isInvClosed G S}. #[short(type="groupClosed")] HB.structure Definition GroupClosed G := {S of isInvClosed G S & isMul1Closed G S & isMulClosed G S}. Section UMagmaPred. Variables (G : baseUMagmaType). Section UMagma. Variables S : umagmaClosed G. Lemma gpred_prod I r (P : pred I) F : (forall i, P i -> F i \in S) -> \prod_(i <- r | P i) F i \in S. Proof. by move=> IH; elim/big_ind: _; [apply: gpred1 | apply: gpredM |]. Qed. Lemma gpredXn n : {in S, forall u, u ^+ n \in S}. Proof. by move=> x xS; elim: n => [|[//|n] IHn]; [exact: gpred1 | exact: gpredM]. Qed. End UMagma. End UMagmaPred. Section GroupPred. Variables (G : groupType). Lemma gpredV (S : invgClosed G) : {mono (@inv G): u / u \in S}. Proof. by move=> u; apply/idP/idP=> /gpredVr; rewrite ?invgK; apply. Qed. Section Group. Variables S : groupClosed G. Lemma gpredF : {in S &, forall u v, u / v \in S}. Proof. by move=> x y xS yS; rewrite gpredM// gpredV. Qed. Lemma gpredFC u v : u / v \in S = (v / u \in S). Proof. by rewrite -gpredV invgF. Qed. Lemma gpredXNn n: {in S, forall u, u ^- n \in S}. Proof. by move=> x xS; apply/gpredVr/gpredXn. Qed. Lemma gpredMr x y : x \in S -> (y * x \in S) = (y \in S). Proof. move=> Sx; apply/idP/idP => [Sxy|/gpredM-> //]. by rewrite -(mulgK x y) gpredF. Qed. Lemma gpredMl x y : x \in S -> (x * y \in S) = (y \in S). Proof. move=> Sx; apply/idP/idP => [Sxy|/(gpredM x y Sx)//]. by rewrite -(mulKg x y) gpredM// gpredV. Qed. Lemma gpredFr x y : x \in S -> (y / x \in S) = (y \in S). Proof. by rewrite -gpredV; apply: gpredMr. Qed. Lemma gpredFl x y : x \in S -> (x / y \in S) = (y \in S). Proof. by rewrite -(gpredV S y); apply: gpredMl. Qed. Lemma gpredJ x y : x \in S -> y \in S -> x ^ y \in S. Proof. by move=> xS yS; apply/gpredM; [apply/gpredVr|apply/gpredM]. Qed. Lemma gpredR x y : x \in S -> y \in S -> [~ x, y] \in S. Proof. by move=> xS yS; apply/gpredM; [apply/gpredVr|apply/gpredJ]. Qed. End Group. End GroupPred. HB.mixin Record isSubMagma (G : magmaType) (S : pred G) H of SubType G S H & Magma H := { valM_subproof : {morph (val : H -> G) : x y / x * y} }. #[short(type="subMagmaType")] HB.structure Definition SubMagma (G : magmaType) S := { H of SubChoice G S H & Magma H & isSubMagma G S H }. Section subMagma. Context (G : magmaType) (S : pred G) (H : subMagmaType S). Notation val := (val : H -> G). HB.instance Definition _ := isMultiplicative.Build H G val valM_subproof. Lemma valM : {morph val : x y / x * y}. Proof. exact: gmulfM. Qed. End subMagma. HB.factory Record SubChoice_isSubMagma (G : magmaType) S H of SubChoice G S H := { mulg_closed_subproof : mulg_closed S }. HB.builders Context G S H of SubChoice_isSubMagma G S H. HB.instance Definition _ := isMulClosed.Build G S mulg_closed_subproof. Let inH v Sv : H := Sub v Sv. Let mulH (u1 u2 : H) := inH (gpredM _ _ (valP u1) (valP u2)). HB.instance Definition _ := hasMul.Build H mulH. Lemma valM : {morph (val : H -> G) : x y / x * y}. Proof. by move=> x y; rewrite SubK. Qed. HB.instance Definition _ := isSubMagma.Build G S H valM. HB.end. #[short(type="subSemigroupType")] HB.structure Definition SubSemigroup (G : semigroupType) S := { H of SubMagma G S H & Semigroup H}. HB.factory Record SubChoice_isSubSemigroup (G : semigroupType) S H of SubChoice G S H := { mulg_closed_subproof : mulg_closed S }. HB.builders Context G S H of SubChoice_isSubSemigroup G S H. HB.instance Definition _ := SubChoice_isSubMagma.Build G S H mulg_closed_subproof. Lemma mulgA : associative (@mul H). Proof. by move=> x y z; apply/val_inj; rewrite !valM mulgA. Qed. HB.instance Definition _ := isSemigroup.Build H mulgA. HB.end. HB.mixin Record isSubBaseUMagma (G : baseUMagmaType) (S : pred G) H of SubMagma G S H & BaseUMagma H := { val1_subproof : (val : H -> G) 1 = 1 }. #[short(type="subBaseUMagmaType")] HB.structure Definition SubBaseUMagma (G : umagmaType) S := { H of SubMagma G S H & BaseUMagma H & isSubBaseUMagma G S H}. #[short(type="subUMagmaType")] HB.structure Definition SubUMagma (G : umagmaType) S := { H of SubMagma G S H & UMagma H & isSubBaseUMagma G S H}. Section subUMagma. Context (G : umagmaType) (S : pred G) (H : subUMagmaType S). Notation val := (val : H -> G). HB.instance Definition _ := Multiplicative_isUMagmaMorphism.Build H G val val1_subproof. Lemma val1 : val 1 = 1. Proof. exact: gmulf1. Qed. End subUMagma. HB.factory Record SubChoice_isSubUMagma (G : umagmaType) S H of SubChoice G S H := { umagma_closed_subproof : umagma_closed S }. HB.builders Context G S H of SubChoice_isSubUMagma G S H. HB.instance Definition _ := SubChoice_isSubMagma.Build G S H (snd umagma_closed_subproof). Let inH v Sv : H := Sub v Sv. Let oneH := inH (fst umagma_closed_subproof). HB.instance Definition _ := hasOne.Build H oneH. Lemma val1 : (val : H -> G) 1 = 1. Proof. exact/SubK. Qed. HB.instance Definition _ := isSubBaseUMagma.Build G S H val1. Lemma mul1g : left_id 1 (@mul H). Proof. by move=> x; apply/val_inj; rewrite valM val1 mul1g. Qed. Lemma mulg1 : right_id 1 (@mul H). Proof. by move=> x; apply/val_inj; rewrite valM val1 mulg1. Qed. HB.instance Definition _ := BaseUMagma_isUMagma.Build H mul1g mulg1. HB.end. #[short(type="subMonoidType")] HB.structure Definition SubMonoid (G : monoidType) S := { H of SubUMagma G S H & Monoid H}. HB.factory Record SubChoice_isSubMonoid (G : monoidType) S H of SubChoice G S H := { monoid_closed_subproof : monoid_closed S }. HB.builders Context G S H of SubChoice_isSubMonoid G S H. HB.instance Definition _ := SubChoice_isSubUMagma.Build G S H monoid_closed_subproof. HB.instance Definition _ := SubChoice_isSubSemigroup.Build G S H (snd monoid_closed_subproof). HB.end. #[short(type="subGroupType")] HB.structure Definition SubGroup (G : groupType) S := { H of SubUMagma G S H & Group H}. HB.factory Record SubChoice_isSubGroup (G : groupType) S H of SubChoice G S H := { group_closed_subproof : group_closed S }. HB.builders Context G S H of SubChoice_isSubGroup G S H. Lemma umagma_closed : umagma_closed S. Proof. split; first exact/(fst group_closed_subproof). exact/group_closedM/group_closed_subproof. Qed. HB.instance Definition _ := SubChoice_isSubMonoid.Build G S H umagma_closed. HB.instance Definition _ := isInvClosed.Build G S (group_closedV group_closed_subproof). Let inH v Sv : H := Sub v Sv. Let invH (u : H) := inH (gpredVr _ (valP u)). HB.instance Definition _ := hasInv.Build H invH. Lemma mulVg : left_inverse 1%g invH *%g. Proof. by move=> x; apply/val_inj; rewrite valM SubK mulVg val1. Qed. Lemma mulgV : right_inverse 1%g invH *%g. Proof. by move=> x; apply/val_inj; rewrite valM SubK mulgV val1. Qed. HB.instance Definition _ := Monoid_isGroup.Build H mulVg mulgV. HB.end. (* Lifting Structure from the codomain of finfuns. *) Section FinFunMagma. Variable (aT : finType) (rT : magmaType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_mul f g := [ffun a => f a * g a]. HB.instance Definition _ := hasMul.Build {ffun aT -> rT} ffun_mul. End FinFunMagma. (* FIXME: HB.saturate *) HB.instance Definition _ (aT : finType) (rT : ChoiceMagma.type) := Magma.on {ffun aT -> rT}. Section FinFunSemigroup. Variable (aT : finType) (rT : semigroupType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_mulgA : associative (@ffun_mul aT rT). Proof. by move=> f1 f2 f3; apply/ffunP=> a; rewrite !ffunE mulgA. Qed. HB.instance Definition _ := isSemigroup.Build {ffun aT -> rT} ffun_mulgA. End FinFunSemigroup. Section FinFunBaseUMagma. Variable (aT : finType) (rT : baseUMagmaType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_one := [ffun a : aT => (1 : rT)]. HB.instance Definition _ := hasOne.Build {ffun aT -> rT} ffun_one. End FinFunBaseUMagma. (* FIXME: HB.saturate *) HB.instance Definition _ (aT : finType) (rT : ChoiceBaseUMagma.type) := BaseUMagma.on {ffun aT -> rT}. Section FinFunUMagma. Variable (aT : finType) (rT : umagmaType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_mul1g : left_id (@ffun_one aT rT) *%g. Proof. by move=> f; apply/ffunP => a; rewrite !ffunE mul1g. Qed. Fact ffun_mulg1 : right_id (@ffun_one aT rT) *%g. Proof. by move=> f; apply/ffunP => a; rewrite !ffunE mulg1. Qed. HB.instance Definition _ := Magma_isUMagma.Build {ffun aT -> rT} ffun_mul1g ffun_mulg1. End FinFunUMagma. (* FIXME: HB.saturate *) HB.instance Definition _ (aT : finType) (rT : monoidType) := UMagma.on {ffun aT -> rT}. Section FinFunBaseGroup. Variable (aT : finType) (rT : baseGroupType). Implicit Types f g : {ffun aT -> rT}. Definition ffun_inv f := [ffun a => (f a)^-1]. HB.instance Definition _ := hasInv.Build {ffun aT -> rT} ffun_inv. End FinFunBaseGroup. Section FinFunGroup. Variable (aT : finType) (rT : groupType). Implicit Types f g : {ffun aT -> rT}. Fact ffun_mulVg : left_inverse (@ffun_one aT rT) (@ffun_inv _ _) (@ffun_mul _ _). Proof. by move=> f; apply/ffunP=> a; rewrite !ffunE mulVg. Qed. Fact ffun_mulgV : right_inverse (@ffun_one aT rT) (@ffun_inv _ _) (@ffun_mul _ _). Proof. by move=> f; apply/ffunP=> a; rewrite !ffunE mulgV. Qed. HB.instance Definition _ := Monoid_isGroup.Build {ffun aT -> rT} ffun_mulVg ffun_mulgV. End FinFunGroup. (* External direct product *) Section PairMagma. Variables G H : magmaType. Definition mul_pair (x y : G * H) := (x.1 * y.1, x.2 * y.2). HB.instance Definition _ := hasMul.Build (G * H)%type mul_pair. Fact fst_is_multiplicative : {morph fst : x y / x * y}. Proof. by []. Qed. HB.instance Definition _ := isMultiplicative.Build _ _ fst fst_is_multiplicative. Fact snd_is_multiplicative : {morph snd : x y / x * y}. Proof. by []. Qed. HB.instance Definition _ := isMultiplicative.Build _ _ snd snd_is_multiplicative. End PairMagma. Section PairSemigroup. Variables G H : semigroupType. Lemma pair_mulgA : associative (@mul (G * H)%type). Proof. by move=> x y z; congr (_, _); apply/mulgA. Qed. HB.instance Definition _ := Magma_isSemigroup.Build (G * H)%type pair_mulgA. End PairSemigroup. Section PairBaseUMagma. Variables G H : baseUMagmaType. Definition one_pair : G * H := (1, 1). HB.instance Definition _ := hasOne.Build (G * H)%type one_pair. Fact fst_is_umagma_morphism : fst (1 : G * H) = 1. Proof. by []. Qed. HB.instance Definition _ := Multiplicative_isUMagmaMorphism.Build _ _ fst fst_is_umagma_morphism. Fact snd_is_umagma_morphism : snd (1 : G * H) = 1. Proof. by []. Qed. HB.instance Definition _ := Multiplicative_isUMagmaMorphism.Build _ _ snd snd_is_umagma_morphism. End PairBaseUMagma. Section PairUMagma. Variables G H : umagmaType. Lemma pair_mul1g : left_id (@one_pair G H) *%g. Proof. by move=> [x y]; congr (_, _); rewrite mul1g. Qed. Lemma pair_mulg1 : right_id (@one_pair G H) *%g. Proof. by move=> [x y]; congr (_, _); rewrite mulg1. Qed. HB.instance Definition _ := BaseUMagma_isUMagma.Build (G * H)%type pair_mul1g pair_mulg1. End PairUMagma. (* FIXME: HB.saturate *) HB.instance Definition _ (G H : ChoiceMagma.type) := Magma.on (G * H)%type. HB.instance Definition _ (G H : ChoiceBaseUMagma.type) := BaseUMagma.on (G * H)%type. HB.instance Definition _ (G H : monoidType) := Semigroup.on (G * H)%type. (* /FIXME *) Section PairBaseGroup. Variables G H : baseGroupType. Definition inv_pair (u : G * H) := (u.1 ^-1, u.2 ^-1). HB.instance Definition _ := hasInv.Build (G * H)%type inv_pair. End PairBaseGroup. Section PairGroup. Variables G H : groupType. Lemma pair_mulVg : left_inverse one (@inv_pair G H) mul. Proof. by move=> x; congr (_, _); apply/mulVg. Qed. Lemma pair_mulgV : right_inverse one (@inv_pair G H) mul. Proof. by move=> x; congr (_, _); apply/mulgV. Qed. HB.instance Definition _ := Monoid_isGroup.Build (G * H)%type pair_mulVg pair_mulgV. End PairGroup.
Datatypes.lean
/- Copyright (c) 2024 Vasily Nesterov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Vasily Nesterov -/ import Mathlib.Init import Batteries.Data.Rat.Basic import Std.Data.HashMap.Basic /-! # Datatypes for the Simplex Algorithm implementation -/ namespace Mathlib.Tactic.Linarith.SimplexAlgorithm /-- Specification for matrix types over ℚ which can be used in the Gauss Elimination and the Simplex Algorithm. It was introduced to unify dense matrices and sparse matrices. -/ class UsableInSimplexAlgorithm (α : Nat → Nat → Type) where /-- Returns `mat[i, j]`. -/ getElem {n m : Nat} (mat : α n m) (i j : Nat) : Rat /-- Sets `mat[i, j]`. -/ setElem {n m : Nat} (mat : α n m) (i j : Nat) (v : Rat) : α n m /-- Returns the list of elements of `mat` in the form `(i, j, mat[i, j])`. -/ getValues {n m : Nat} (mat : α n m) : List (Nat × Nat × Rat) /-- Creates a matrix from a list of elements in the form `(i, j, mat[i, j])`. -/ ofValues {n m : Nat} (values : List (Nat × Nat × Rat)) : α n m /-- Swaps two rows. -/ swapRows {n m : Nat} (mat : α n m) (i j : Nat) : α n m /-- Subtracts `i`-th row multiplied by `coef` from `j`-th row. -/ subtractRow {n m : Nat} (mat : α n m) (i j : Nat) (coef : Rat) : α n m /-- Divides the `i`-th row by `coef`. -/ divideRow {n m : Nat} (mat : α n m) (i : Nat) (coef : Rat) : α n m export UsableInSimplexAlgorithm (setElem getValues ofValues swapRows subtractRow divideRow) instance (n m : Nat) (matType : Nat → Nat → Type) [UsableInSimplexAlgorithm matType] : GetElem (matType n m) (Nat × Nat) Rat fun _ p => p.1 < n ∧ p.2 < m where getElem mat p _ := UsableInSimplexAlgorithm.getElem mat p.1 p.2 /-- Structure for matrices over ℚ. So far it is just a 2d-array carrying dimensions (that are supposed to match with the actual dimensions of `data`), but the plan is to add some `Prop`-data and make the structure strict and safe. Note: we avoid using `Matrix` because it is far more efficient to store a matrix as its entries than as function between `Fin`-s. -/ structure DenseMatrix (n m : Nat) where /-- The content of the matrix. -/ data : Array (Array Rat) instance : UsableInSimplexAlgorithm DenseMatrix where getElem mat i j := mat.data[i]![j]! setElem mat i j v := ⟨mat.data.modify i fun row => row.set! j v⟩ getValues mat := mat.data.zipIdx.foldl (init := []) fun acc (row, i) => let rowVals := Array.toList <| row.zipIdx.filterMap fun (v, j) => if v != 0 then .some (i, j, v) else .none rowVals ++ acc ofValues {n m : Nat} vals : DenseMatrix _ _ := Id.run do let mut data : Array (Array Rat) := Array.replicate n <| Array.replicate m 0 for ⟨i, j, v⟩ in vals do data := data.modify i fun row => row.set! j v return ⟨data⟩ swapRows mat i j := ⟨mat.data.swapIfInBounds i j⟩ subtractRow mat i j coef := let newData : Array (Array Rat) := mat.data.modify j fun row => Array.zipWith (fun x y => x - coef * y) row mat.data[i]! ⟨newData⟩ divideRow mat i coef := ⟨mat.data.modify i (·.map (· / coef))⟩ /-- Structure for sparse matrices over ℚ, implemented as an array of hashmaps, containing only nonzero values. -/ structure SparseMatrix (n m : Nat) where /-- The content of the matrix. -/ data : Array <| Std.HashMap Nat Rat instance : UsableInSimplexAlgorithm SparseMatrix where getElem mat i j := mat.data[i]!.getD j 0 setElem mat i j v := if v == 0 then ⟨mat.data.modify i fun row => row.erase j⟩ else ⟨mat.data.modify i fun row => row.insert j v⟩ getValues mat := mat.data.zipIdx.foldl (init := []) fun acc (row, i) => let rowVals := row.toList.map fun (j, v) => (i, j, v) rowVals ++ acc ofValues {n _ : Nat} vals := Id.run do let mut data : Array (Std.HashMap Nat Rat) := Array.replicate n ∅ for ⟨i, j, v⟩ in vals do if v != 0 then data := data.modify i fun row => row.insert j v return ⟨data⟩ swapRows mat i j := ⟨mat.data.swapIfInBounds i j⟩ subtractRow mat i j coef := let newData := mat.data.modify j fun row => mat.data[i]!.fold (fun cur k val => let newVal := (cur.getD k 0) - coef * val if newVal != 0 then cur.insert k newVal else cur.erase k ) row ⟨newData⟩ divideRow mat i coef := let newData : Array (Std.HashMap Nat Rat) := mat.data.modify i fun row => row.fold (fun cur k v => cur.insert k (v / coef)) row ⟨newData⟩ /-- `Tableau` is a structure the Simplex Algorithm operates on. The `i`-th row of `mat` expresses the variable `basic[i]` as a linear combination of variables from `free`. -/ structure Tableau (matType : Nat → Nat → Type) [UsableInSimplexAlgorithm matType] where /-- Array containing the basic variables' indexes -/ basic : Array Nat /-- Array containing the free variables' indexes -/ free : Array Nat /-- Matrix of coefficients the basic variables expressed through the free ones. -/ mat : matType basic.size free.size end Mathlib.Tactic.Linarith.SimplexAlgorithm
finset.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 div seq. From mathcomp Require Import choice fintype finfun bigop. (******************************************************************************) (* This file defines a type for sets over a finite Type, similar to the type *) (* of functions over a finite Type defined in finfun.v (indeed, based in it): *) (* {set T} where T must have a finType structure. *) (* We equip {set T} itself with a finType structure, hence Leibnitz and *) (* extensional equalities coincide on {set T}, and we can form {set {set T}}. *) (* If A, B : {set T} and P : {set {set T}}, we define: *) (* x \in A == x belongs to A (i.e., {set T} implements predType, *) (* by coercion to pred_sort) *) (* mem A == the predicate corresponding to A *) (* finset p == the set corresponding to a predicate p *) (* [set x | P] == the set containing the x such that P is true (x may *) (* appear in P) *) (* [set x | P & Q] := [set x | P && Q] *) (* [set x in A] == the set containing the x in a collective predicate A *) (* [set x in A | P] == the set containing the x in A such that P is true *) (* [set x in A | P & Q] := [set x in A | P && Q] *) (* All these have typed variants [set x : T | P], [set x : T in A], etc. *) (* set0 == the empty set *) (* [set: T] or setT == the full set (the A containing all x : T) *) (* [set x] == the singleton {x} *) (* [set~ x] == the complement of the singleton {x} *) (* [set:: s] == the set spanned by the sequence s *) (* [set a1; a2;...; an] := a1 |: [set a2] :|: ... :|: [set an] *) (* A :|: B == the union of A and B *) (* x |: A == A with the element x added (:= [set x] :|: A) *) (* A :&: B == the intersection of A and B *) (* ~: A == the complement of A *) (* A :\: B == the difference A minus B *) (* A :\ x == A with the element x removed (:= A :\: [set x]) *) (* \bigcup_<range> A == the union of all A, for i in <range> (i is bound in *) (* A, see bigop.v) *) (* \bigcap_<range> A == the intersection of all A, for i in <range> *) (* cover P == the union of the set of sets P *) (* trivIset P <=> the elements of P are pairwise disjoint *) (* partition P A <=> P is a partition of A *) (* pblock P x == a block of P containing x, or else set0 *) (* equivalence_partition R D == the partition induced on D by the relation R *) (* (provided R is an equivalence relation in D) *) (* preim_partition f D == the partition induced on D by the equivalence *) (* [rel x y | f x == f y] *) (* is_transversal X P D <=> X is a transversal of the partition P of D *) (* transversal P D == a transversal of P, provided P is a partition of D *) (* transversal_repr x0 X B == a representative of B \in P selected by the *) (* transversal X of P, or else x0 *) (* powerset A == the set of all subset of the set A *) (* P ::&: A == those sets in P that are subsets of the set A *) (* setX A1 A2 == cartesian product of A1 and A2 *) (* := [set u | u.1 \in A1 & u.2 \in A2] *) (* setXn I f A == indexed cartesian product of *) (* A : forall i : I, {set f i} *) (* f @^-1: A == the preimage of the collective predicate A under f *) (* f @: A == the image set of the collective predicate A by f *) (* f @2:(A, B) == the image set of A x B by the binary function f *) (* [set E | x in A] == the set of all the values of the expression E, for x *) (* drawn from the collective predicate A *) (* [set E | x in A & P] == the set of values of E for x drawn from A, such *) (* that P is true *) (* [set E | x in A, y in B] == the set of values of E for x drawn from A and *) (* and y drawn from B; B may depend on x *) (* [set E | x in A, y in B & P] == the set of values of E for x drawn from A *) (* y drawn from B, such that P is true *) (* [set E | x : T] == the set of all values of E, with x in type T *) (* [set E | x : T & P] == the set of values of E for x : T s.t. P is true *) (* [set E | x : T, y : U in B], [set E | x : T, y : U in B & P], *) (* [set E | x : T in A, y : U], [set E | x : T in A, y : U & P], *) (* [set E | x : T, y : U], [set E | x : T, y : U & P] *) (* == type-ranging versions of the binary comprehensions *) (* [set E | x : T in A], [set E | x in A, y], [set E | x, y & P], etc. *) (* == typed and untyped variants of the comprehensions above*) (* The types may be required as type inference processes *) (* E before considering A or B. Note that type casts in *) (* the binary comprehension must either be both present *) (* or absent and that there are no untyped variants for *) (* single-type comprehension as Coq parsing confuses *) (* [x | P] and [E | x]. *) (* minset p A == A is a minimal set satisfying p *) (* maxset p A == A is a maximal set satisfying p *) (* unset1 A == [pick x in A] if #|A| == 1, else None *) (* fprod_pick I T_ p == pick a function of type (forall i : I, T_ i) provided *) (* a proof p of 0 < #|fprod I T_| is given *) (* ftagged I T_ p f i == untag (fprod_pick I T_ p) i (fun x=>x) (f i), useful *) (* to lift f : {ffun I -> {i : I & T_ i}} (akin to FProd's building blocks) *) (* to a vanilla dependent function of type (forall i : I, T_ i). *) (* Provided a monotonous function F : {set T} -> {set T}, we get fixpoints *) (* fixset F := iter #|T| F set0 *) (* == the least fixpoint of F *) (* == the minimal set such that F X == X *) (* fix_order F x == the minimum number of iterations so that *) (* x is in iter (fix_order F x) F set0 *) (* funsetC F := fun X => ~: F (~: X) *) (* cofixset F == the greatest fixpoint of F *) (* == the maximal set such that F X == X *) (* := ~: fixset (funsetC F) *) (* We also provide notations A :=: B, A :<>: B, A :==: B, A :!=: B, A :=P: B *) (* that specialize A = B, A <> B, A == B, etc., to {set _}. This is useful *) (* for subtypes of {set T}, such as {group T}, that coerce to {set T}. *) (* We give many lemmas on these operations, on card, and on set inclusion. *) (* In addition to the standard suffixes described in ssrbool.v, we associate *) (* the following suffixes to set operations: *) (* 0 -- the empty set, as in in_set0 : (x \in set0) = false *) (* T -- the full set, as in in_setT : x \in [set: T] *) (* 1 -- a singleton set, as in in_set1 : (x \in [set a]) = (x == a) *) (* 2 -- an unordered pair, as in *) (* in_set2 : (x \in [set a; b]) = (x == a) || (x == b) *) (* C -- complement, as in setCK : ~: ~: A = A *) (* I -- intersection, as in setIid : A :&: A = A *) (* U -- union, as in setUid : A :|: A = A *) (* D -- difference, as in setDv : A :\: A = set0 *) (* S -- a subset argument, as in *) (* setIS: B \subset C -> A :&: B \subset A :&: C *) (* These suffixes are sometimes preceded with an `s' to distinguish them from *) (* their basic ssrbool interpretation, e.g., *) (* card1 : #|pred1 x| = 1 and cards1 : #|[set x]| = 1 *) (* We also use a trailing `r' to distinguish a right-hand complement from *) (* commutativity, e.g., *) (* setIC : A :&: B = B :&: A and setICr : A :&: ~: A = set0. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope set_scope. Section SetType. Variable T : finType. Inductive set_type : predArgType := FinSet of {ffun pred T}. Definition finfun_of_set A := let: FinSet f := A in f. Definition set_of := set_type. Identity Coercion type_of_set_of : set_of >-> set_type. Definition set_isSub := Eval hnf in [isNew for finfun_of_set]. HB.instance Definition _ := set_isSub. HB.instance Definition _ := [Finite of set_type by <:]. End SetType. Delimit Scope set_scope with SET. Bind Scope set_scope with set_type. Bind Scope set_scope with set_of. Open Scope set_scope. Arguments set_of T%_type. Arguments finfun_of_set {T} A%_SET. Notation "{ 'set' T }" := (set_of T) (format "{ 'set' T }") : type_scope. (* We later define several subtypes that coerce to set; for these it is *) (* preferable to state equalities at the {set _} level, even when comparing *) (* subtype values, because the primitive "injection" tactic tends to diverge *) (* on complex types (e.g., quotient groups). We provide some parse-only *) (* notation to make this technicality less obstructive. *) Notation "A :=: B" := (A = B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. Notation "A :<>: B" := (A <> B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. Notation "A :==: B" := (A == B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. Notation "A :!=: B" := (A != B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. Notation "A :=P: B" := (A =P B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. HB.lock Definition finset (T : finType) (P : pred T) : {set T} := @FinSet T (finfun P). Canonical finset_unlock := Unlockable finset.unlock. (* The weird type of pred_of_set is imposed by the syntactic restrictions on *) (* coercion declarations; it is unfortunately not possible to use a functor *) (* to retype the declaration, because this triggers an ugly bug in the Coq *) (* coercion chaining code. *) HB.lock Definition pred_of_set T (A : set_type T) : fin_pred_sort (predPredType T) := val A. Canonical pred_of_set_unlock := Unlockable pred_of_set.unlock. Notation "[ 'set' x : T | P ]" := (finset (fun x : T => P%B)) (x at level 99, only parsing) : set_scope. Notation "[ 'set' x | P ]" := [set x : _ | P] (P at level 99, format "[ 'set' x | P ]") : set_scope. Notation "[ 'set' x 'in' A ]" := [set x | x \in A] (format "[ 'set' x 'in' A ]") : set_scope. Notation "[ 'set' x : T 'in' A ]" := [set x : T | x \in A] (only parsing) : set_scope. Notation "[ 'set' x : T | P & Q ]" := [set x : T | P && Q] (only parsing) : set_scope. Notation "[ 'set' x | P & Q ]" := [set x | P && Q ] (P at level 99, format "[ 'set' x | P & Q ]") : set_scope. Notation "[ 'set' x : T 'in' A | P ]" := [set x : T | x \in A & P] (only parsing) : set_scope. Notation "[ 'set' x 'in' A | P ]" := [set x | x \in A & P] (format "[ 'set' x 'in' A | P ]") : set_scope. Notation "[ 'set' x 'in' A | P & Q ]" := [set x in A | P && Q] (format "[ 'set' x 'in' A | P & Q ]") : set_scope. Notation "[ 'set' x : T 'in' A | P & Q ]" := [set x : T in A | P && Q] (only parsing) : set_scope. Notation "[ 'set' :: s ]" := (finset [in pred_of_seq s]) (format "[ 'set' :: s ]") : set_scope. (* This lets us use set and subtypes of set, like group or coset_of, both as *) (* collective predicates and as arguments of the \pi(_) notation. *) Coercion pred_of_set: set_type >-> fin_pred_sort. (* Declare pred_of_set as a canonical instance of topred, but use the *) (* coercion to resolve mem A to @mem (predPredType T) (pred_of_set A). *) Canonical set_predType T := @PredType _ (unkeyed (set_type T)) (@pred_of_set T). Section BasicSetTheory. Variable T : finType. Implicit Types (x : T) (A B : {set T}) (pA : pred T). HB.instance Definition _ := Finite.on {set T}. Lemma in_set pA x : x \in finset pA = pA x. Proof. by rewrite [@finset]unlock unlock [x \in _]ffunE. Qed. Lemma setP A B : A =i B <-> A = B. Proof. by split=> [eqAB|-> //]; apply/val_inj/ffunP=> x; have:= eqAB x; rewrite unlock. Qed. Definition set0 := [set x : T | false]. Definition setTfor := [set x : T | true]. Lemma in_setT x : x \in setTfor. Proof. by rewrite in_set. Qed. Lemma eqsVneq A B : eq_xor_neq A B (B == A) (A == B). Proof. exact: eqVneq. Qed. Lemma eq_finset (pA pB : pred T) : pA =1 pB -> finset pA = finset pB. Proof. by move=> eq_p; apply/setP => x; rewrite !(in_set, inE) eq_p. Qed. End BasicSetTheory. Arguments eqsVneq {T} A B, {T A B}. Arguments set0 {T}. Arguments setTfor T%_type. Arguments eq_finset {T} [pA] pB eq_pAB. #[global] Hint Resolve in_setT : core. Notation "[ 'set' : T ]" := (setTfor T) (format "[ 'set' : T ]") : set_scope. Notation setT := [set: _] (only parsing). HB.lock Definition set1 (T : finType) (a : T) := [set x | x == a]. Section setOpsDefs. Variable T : finType. Implicit Types (a x : T) (A B D : {set T}) (P : {set {set T}}). Definition setU A B := [set x | (x \in A) || (x \in B)]. Definition setI A B := [set x in A | x \in B]. Definition setC A := [set x | x \notin A]. Definition setD A B := [set x | x \notin B & x \in A]. Definition ssetI P D := [set A in P | A \subset D]. Definition powerset D := [set A : {set T} | A \subset D]. End setOpsDefs. Notation "[ 'set' a ]" := (set1 a) (a at level 99, format "[ 'set' a ]") : set_scope. Notation "[ 'set' a : T ]" := [set (a : T)] (a at level 99, format "[ 'set' a : T ]") : set_scope. Notation "A :|: B" := (setU A B) : set_scope. Notation "a |: A" := ([set a] :|: A) : set_scope. (* This is left-associative due to historical limitations of the .. Notation. *) Notation "[ 'set' a1 ; a2 ; .. ; an ]" := (setU .. (a1 |: [set a2]) .. [set an]) (format "[ 'set' a1 ; a2 ; .. ; an ]") : set_scope. Notation "A :&: B" := (setI A B) : set_scope. Notation "~: A" := (setC A) (at level 35, right associativity) : set_scope. Notation "[ 'set' ~ a ]" := (~: [set a]) (format "[ 'set' ~ a ]") : set_scope. Notation "A :\: B" := (setD A B) : set_scope. Notation "A :\ a" := (A :\: [set a]) : set_scope. Notation "P ::&: D" := (ssetI P D) (at level 48) : set_scope. Section setOps. Variable T : finType. Implicit Types (a x : T) (A B C D : {set T}) (pA pB pC : pred T). Lemma eqEsubset A B : (A == B) = (A \subset B) && (B \subset A). Proof. by apply/eqP/subset_eqP=> /setP. Qed. Lemma subEproper A B : A \subset B = (A == B) || (A \proper B). Proof. by rewrite eqEsubset -andb_orr orbN andbT. Qed. Lemma eqVproper A B : A \subset B -> A = B \/ A \proper B. Proof. by rewrite subEproper => /predU1P. Qed. Lemma properEneq A B : A \proper B = (A != B) && (A \subset B). Proof. by rewrite andbC eqEsubset negb_and andb_orr andbN. Qed. Lemma proper_neq A B : A \proper B -> A != B. Proof. by rewrite properEneq; case/andP. Qed. Lemma eqEproper A B : (A == B) = (A \subset B) && ~~ (A \proper B). Proof. by rewrite negb_and negbK andb_orr andbN eqEsubset. Qed. Lemma eqEcard A B : (A == B) = (A \subset B) && (#|B| <= #|A|). Proof. rewrite eqEsubset; apply: andb_id2l => sAB. by rewrite (geq_leqif (subset_leqif_card sAB)). Qed. Lemma properEcard A B : (A \proper B) = (A \subset B) && (#|A| < #|B|). Proof. by rewrite properEneq ltnNge andbC eqEcard; case: (A \subset B). Qed. Lemma subset_leqif_cards A B : A \subset B -> (#|A| <= #|B| ?= iff (A == B)). Proof. by move=> sAB; rewrite eqEsubset sAB; apply: subset_leqif_card. Qed. Lemma in_set0 x : x \in set0 = false. Proof. by rewrite in_set. Qed. Lemma sub0set A : set0 \subset A. Proof. by apply/subsetP=> x; rewrite in_set. Qed. Lemma subset0 A : (A \subset set0) = (A == set0). Proof. by rewrite eqEsubset sub0set andbT. Qed. Lemma proper0 A : (set0 \proper A) = (A != set0). Proof. by rewrite properE sub0set subset0. Qed. Lemma subset_neq0 A B : A \subset B -> A != set0 -> B != set0. Proof. by rewrite -!proper0 => sAB /proper_sub_trans->. Qed. Lemma set_0Vmem A : (A = set0) + {x : T | x \in A}. Proof. case: (pickP (mem A)) => [x Ax | A0]; [by right; exists x | left]. by apply/setP=> x; rewrite in_set; apply: A0. Qed. Lemma set_enum A : [set x | x \in enum A] = A. Proof. by apply/setP => x; rewrite in_set mem_enum. Qed. Lemma enum_set0 : enum set0 = [::] :> seq T. Proof. by rewrite (eq_enum (in_set _)) enum0. Qed. Lemma subsetT A : A \subset setT. Proof. by apply/subsetP=> x; rewrite in_set. Qed. Lemma subsetT_hint mA : subset mA (mem [set: T]). Proof. by rewrite unlock; apply/pred0P=> x; rewrite !inE in_set. Qed. Hint Resolve subsetT_hint : core. Lemma subTset A : (setT \subset A) = (A == setT). Proof. by rewrite eqEsubset subsetT. Qed. Lemma properT A : (A \proper setT) = (A != setT). Proof. by rewrite properEneq subsetT andbT. Qed. Lemma set1P x a : reflect (x = a) (x \in [set a]). Proof. by rewrite set1.unlock in_set; apply: eqP. Qed. Lemma enum_setT : enum [set: T] = Finite.enum T. Proof. by rewrite (eq_enum (in_set _)) enumT. Qed. Lemma in_set1 x a : (x \in [set a]) = (x == a). Proof. by rewrite set1.unlock in_set. Qed. Definition inE := (in_set, in_set1, inE). Lemma set11 x : x \in [set x]. Proof. by rewrite !inE. Qed. Lemma set1_inj : injective (@set1 T). Proof. by move=> a b eqsab; apply/set1P; rewrite -eqsab set11. Qed. Lemma enum_set1 a : enum [set a] = [:: a]. Proof. by rewrite set1.unlock (eq_enum (in_set _)) enum1. Qed. Lemma setU1P x a B : reflect (x = a \/ x \in B) (x \in a |: B). Proof. by rewrite !inE; apply: predU1P. Qed. Lemma in_setU1 x a B : (x \in a |: B) = (x == a) || (x \in B). Proof. by rewrite !inE. Qed. Lemma set_nil : [set:: nil] = @set0 T. Proof. by rewrite -enum_set0 set_enum. Qed. Lemma set_seq1 a : [set:: [:: a]] = [set a]. Proof. by rewrite -enum_set1 set_enum. Qed. Lemma set_cons a s : [set:: a :: s] = a |: [set:: s]. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma setU11 x B : x \in x |: B. Proof. by rewrite !inE eqxx. Qed. Lemma setU1r x a B : x \in B -> x \in a |: B. Proof. by move=> Bx; rewrite !inE predU1r. Qed. (* We need separate lemmas for the explicit enumerations since they *) (* associate on the left. *) Lemma set1Ul x A b : x \in A -> x \in A :|: [set b]. Proof. by move=> Ax; rewrite !inE Ax. Qed. Lemma set1Ur A b : b \in A :|: [set b]. Proof. by rewrite !inE eqxx orbT. Qed. Lemma in_setC1 x a : (x \in [set~ a]) = (x != a). Proof. by rewrite !inE. Qed. Lemma setC11 x : (x \in [set~ x]) = false. Proof. by rewrite !inE eqxx. Qed. Lemma setD1P x A b : reflect (x != b /\ x \in A) (x \in A :\ b). Proof. by rewrite !inE; apply: andP. Qed. Lemma in_setD1 x A b : (x \in A :\ b) = (x != b) && (x \in A) . Proof. by rewrite !inE. Qed. Lemma setD11 b A : (b \in A :\ b) = false. Proof. by rewrite !inE eqxx. Qed. Lemma setD1K a A : a \in A -> a |: (A :\ a) = A. Proof. by move=> Aa; apply/setP=> x /[!inE]; case: eqP => // ->. Qed. Lemma setU1K a B : a \notin B -> (a |: B) :\ a = B. Proof. by move/negPf=> nBa; apply/setP=> x /[!inE]; case: eqP => // ->. Qed. Lemma set2P x a b : reflect (x = a \/ x = b) (x \in [set a; b]). Proof. by rewrite !inE; apply: pred2P. Qed. Lemma in_set2 x a b : (x \in [set a; b]) = (x == a) || (x == b). Proof. by rewrite !inE. Qed. Lemma set21 a b : a \in [set a; b]. Proof. by rewrite !inE eqxx. Qed. Lemma set22 a b : b \in [set a; b]. Proof. by rewrite !inE eqxx orbT. Qed. Lemma setUP x A B : reflect (x \in A \/ x \in B) (x \in A :|: B). Proof. by rewrite !inE; apply: orP. Qed. Lemma in_setU x A B : (x \in A :|: B) = (x \in A) || (x \in B). Proof. exact: in_set. Qed. Lemma setUC A B : A :|: B = B :|: A. Proof. by apply/setP => x; rewrite !inE orbC. Qed. Lemma setUS A B C : A \subset B -> C :|: A \subset C :|: B. Proof. move=> sAB; apply/subsetP=> x; rewrite !inE. by case: (x \in C) => //; apply: (subsetP sAB). Qed. Lemma setSU A B C : A \subset B -> A :|: C \subset B :|: C. Proof. by move=> sAB; rewrite -!(setUC C) setUS. Qed. Lemma setUSS A B C D : A \subset C -> B \subset D -> A :|: B \subset C :|: D. Proof. by move=> /(setSU B) /subset_trans sAC /(setUS C)/sAC. Qed. Lemma set0U A : set0 :|: A = A. Proof. by apply/setP => x; rewrite !inE orFb. Qed. Lemma setU0 A : A :|: set0 = A. Proof. by rewrite setUC set0U. Qed. Lemma setUA A B C : A :|: (B :|: C) = A :|: B :|: C. Proof. by apply/setP => x; rewrite !inE orbA. Qed. Lemma setUCA A B C : A :|: (B :|: C) = B :|: (A :|: C). Proof. by rewrite !setUA (setUC B). Qed. Lemma setUAC A B C : A :|: B :|: C = A :|: C :|: B. Proof. by rewrite -!setUA (setUC B). Qed. Lemma setUACA A B C D : (A :|: B) :|: (C :|: D) = (A :|: C) :|: (B :|: D). Proof. by rewrite -!setUA (setUCA B). Qed. Lemma setTU A : setT :|: A = setT. Proof. by apply/setP => x; rewrite !inE orTb. Qed. Lemma setUT A : A :|: setT = setT. Proof. by rewrite setUC setTU. Qed. Lemma setUid A : A :|: A = A. Proof. by apply/setP=> x; rewrite inE orbb. Qed. Lemma setUUl A B C : A :|: B :|: C = (A :|: C) :|: (B :|: C). Proof. by rewrite setUA !(setUAC _ C) -(setUA _ C) setUid. Qed. Lemma setUUr A B C : A :|: (B :|: C) = (A :|: B) :|: (A :|: C). Proof. by rewrite !(setUC A) setUUl. Qed. (* intersection *) (* setIdP is a generalisation of setIP that applies to comprehensions. *) Lemma setIdP x pA pB : reflect (pA x /\ pB x) (x \in [set y | pA y & pB y]). Proof. by rewrite !inE; apply: andP. Qed. Lemma setId2P x pA pB pC : reflect [/\ pA x, pB x & pC x] (x \in [set y | pA y & pB y && pC y]). Proof. by rewrite !inE; apply: and3P. Qed. Lemma setIdE A pB : [set x in A | pB x] = A :&: [set x | pB x]. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma setIP x A B : reflect (x \in A /\ x \in B) (x \in A :&: B). Proof. exact: (iffP (@setIdP _ _ _)). Qed. Lemma in_setI x A B : (x \in A :&: B) = (x \in A) && (x \in B). Proof. exact: in_set. Qed. Lemma setIC A B : A :&: B = B :&: A. Proof. by apply/setP => x; rewrite !inE andbC. Qed. Lemma setIS A B C : A \subset B -> C :&: A \subset C :&: B. Proof. move=> sAB; apply/subsetP=> x; rewrite !inE. by case: (x \in C) => //; apply: (subsetP sAB). Qed. Lemma setSI A B C : A \subset B -> A :&: C \subset B :&: C. Proof. by move=> sAB; rewrite -!(setIC C) setIS. Qed. Lemma setISS A B C D : A \subset C -> B \subset D -> A :&: B \subset C :&: D. Proof. by move=> /(setSI B) /subset_trans sAC /(setIS C) /sAC. Qed. Lemma setTI A : setT :&: A = A. Proof. by apply/setP => x; rewrite !inE andTb. Qed. Lemma setIT A : A :&: setT = A. Proof. by rewrite setIC setTI. Qed. Lemma set0I A : set0 :&: A = set0. Proof. by apply/setP => x; rewrite !inE andFb. Qed. Lemma setI0 A : A :&: set0 = set0. Proof. by rewrite setIC set0I. Qed. Lemma setIA A B C : A :&: (B :&: C) = A :&: B :&: C. Proof. by apply/setP=> x; rewrite !inE andbA. Qed. Lemma setICA A B C : A :&: (B :&: C) = B :&: (A :&: C). Proof. by rewrite !setIA (setIC A). Qed. Lemma setIAC A B C : A :&: B :&: C = A :&: C :&: B. Proof. by rewrite -!setIA (setIC B). Qed. Lemma setIACA A B C D : (A :&: B) :&: (C :&: D) = (A :&: C) :&: (B :&: D). Proof. by rewrite -!setIA (setICA B). Qed. Lemma setIid A : A :&: A = A. Proof. by apply/setP=> x; rewrite inE andbb. Qed. Lemma setIIl A B C : A :&: B :&: C = (A :&: C) :&: (B :&: C). Proof. by rewrite setIA !(setIAC _ C) -(setIA _ C) setIid. Qed. Lemma setIIr A B C : A :&: (B :&: C) = (A :&: B) :&: (A :&: C). Proof. by rewrite !(setIC A) setIIl. Qed. (* distribute /cancel *) Lemma setIUr A B C : A :&: (B :|: C) = (A :&: B) :|: (A :&: C). Proof. by apply/setP=> x; rewrite !inE andb_orr. Qed. Lemma setIUl A B C : (A :|: B) :&: C = (A :&: C) :|: (B :&: C). Proof. by apply/setP=> x; rewrite !inE andb_orl. Qed. Lemma setUIr A B C : A :|: (B :&: C) = (A :|: B) :&: (A :|: C). Proof. by apply/setP=> x; rewrite !inE orb_andr. Qed. Lemma setUIl A B C : (A :&: B) :|: C = (A :|: C) :&: (B :|: C). Proof. by apply/setP=> x; rewrite !inE orb_andl. Qed. Lemma setUK A B : (A :|: B) :&: A = A. Proof. by apply/setP=> x; rewrite !inE orbK. Qed. Lemma setKU A B : A :&: (B :|: A) = A. Proof. by apply/setP=> x; rewrite !inE orKb. Qed. Lemma setIK A B : (A :&: B) :|: A = A. Proof. by apply/setP=> x; rewrite !inE andbK. Qed. Lemma setKI A B : A :|: (B :&: A) = A. Proof. by apply/setP=> x; rewrite !inE andKb. Qed. (* complement *) Lemma setCP x A : reflect (~ x \in A) (x \in ~: A). Proof. by rewrite !inE; apply: negP. Qed. Lemma in_setC x A : (x \in ~: A) = (x \notin A). Proof. exact: in_set. Qed. Lemma setCK : involutive (@setC T). Proof. by move=> A; apply/setP=> x; rewrite !inE negbK. Qed. Lemma setC_inj : injective (@setC T). Proof. exact: can_inj setCK. Qed. Lemma subsets_disjoint A B : (A \subset B) = [disjoint A & ~: B]. Proof. by rewrite subset_disjoint; apply: eq_disjoint_r => x; rewrite !inE. Qed. Lemma disjoints_subset A B : [disjoint A & B] = (A \subset ~: B). Proof. by rewrite subsets_disjoint setCK. Qed. Lemma powersetCE A B : (A \in powerset (~: B)) = [disjoint A & B]. Proof. by rewrite inE disjoints_subset. Qed. Lemma setCS A B : (~: A \subset ~: B) = (B \subset A). Proof. by rewrite !subsets_disjoint setCK disjoint_sym. Qed. Lemma setCU A B : ~: (A :|: B) = ~: A :&: ~: B. Proof. by apply/setP=> x; rewrite !inE negb_or. Qed. Lemma setCI A B : ~: (A :&: B) = ~: A :|: ~: B. Proof. by apply/setP=> x; rewrite !inE negb_and. Qed. Lemma setUCr A : A :|: ~: A = setT. Proof. by apply/setP=> x; rewrite !inE orbN. Qed. Lemma setICr A : A :&: ~: A = set0. Proof. by apply/setP=> x; rewrite !inE andbN. Qed. Lemma setC0 : ~: set0 = [set: T]. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma setCT : ~: [set: T] = set0. Proof. by rewrite -setC0 setCK. Qed. Lemma properC A B : (~: B \proper ~: A) = (A \proper B). Proof. by rewrite !properE !setCS. Qed. (* difference *) Lemma setDP A B x : reflect (x \in A /\ x \notin B) (x \in A :\: B). Proof. by rewrite inE andbC; apply: andP. Qed. Lemma in_setD A B x : (x \in A :\: B) = (x \notin B) && (x \in A). Proof. exact: in_set. Qed. Lemma setDE A B : A :\: B = A :&: ~: B. Proof. by apply/setP => x; rewrite !inE andbC. Qed. Lemma setSD A B C : A \subset B -> A :\: C \subset B :\: C. Proof. by rewrite !setDE; apply: setSI. Qed. Lemma setDS A B C : A \subset B -> C :\: B \subset C :\: A. Proof. by rewrite !setDE -setCS; apply: setIS. Qed. Lemma setDSS A B C D : A \subset C -> D \subset B -> A :\: B \subset C :\: D. Proof. by move=> /(setSD B) /subset_trans sAC /(setDS C) /sAC. Qed. Lemma setD0 A : A :\: set0 = A. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma set0D A : set0 :\: A = set0. Proof. by apply/setP=> x; rewrite !inE andbF. Qed. Lemma setDT A : A :\: setT = set0. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma setTD A : setT :\: A = ~: A. Proof. by apply/setP=> x; rewrite !inE andbT. Qed. Lemma setDv A : A :\: A = set0. Proof. by apply/setP=> x; rewrite !inE andNb. Qed. Lemma setCD A B : ~: (A :\: B) = ~: A :|: B. Proof. by rewrite !setDE setCI setCK. Qed. Lemma setID A B : A :&: B :|: A :\: B = A. Proof. by rewrite setDE -setIUr setUCr setIT. Qed. Lemma setDUl A B C : (A :|: B) :\: C = (A :\: C) :|: (B :\: C). Proof. by rewrite !setDE setIUl. Qed. Lemma setDUr A B C : A :\: (B :|: C) = (A :\: B) :&: (A :\: C). Proof. by rewrite !setDE setCU setIIr. Qed. Lemma setDIl A B C : (A :&: B) :\: C = (A :\: C) :&: (B :\: C). Proof. by rewrite !setDE setIIl. Qed. Lemma setIDA A B C : A :&: (B :\: C) = (A :&: B) :\: C. Proof. by rewrite !setDE setIA. Qed. Lemma setIDAC A B C : (A :\: B) :&: C = (A :&: C) :\: B. Proof. by rewrite !setDE setIAC. Qed. Lemma setDIr A B C : A :\: (B :&: C) = (A :\: B) :|: (A :\: C). Proof. by rewrite !setDE setCI setIUr. Qed. Lemma setDDl A B C : (A :\: B) :\: C = A :\: (B :|: C). Proof. by rewrite !setDE setCU setIA. Qed. Lemma setDDr A B C : A :\: (B :\: C) = (A :\: B) :|: (A :&: C). Proof. by rewrite !setDE setCI setIUr setCK. Qed. (* powerset *) Lemma powersetE A B : (A \in powerset B) = (A \subset B). Proof. by rewrite inE. Qed. Lemma powersetS A B : (powerset A \subset powerset B) = (A \subset B). Proof. apply/subsetP/idP=> [sAB | sAB C /[!inE]/subset_trans->//]. by rewrite -powersetE sAB // inE. Qed. Lemma powerset0 : powerset set0 = [set set0] :> {set {set T}}. Proof. by apply/setP=> A; rewrite set1.unlock !inE subset0. Qed. Lemma powersetT : powerset [set: T] = [set: {set T}]. Proof. by apply/setP=> A; rewrite !inE subsetT. Qed. Lemma setI_powerset P A : P :&: powerset A = P ::&: A. Proof. by apply/setP=> B; rewrite !inE. Qed. (* cardinal lemmas for sets *) Lemma cardsE pA : #|[set x in pA]| = #|pA|. Proof. exact/eq_card/in_set. Qed. Lemma sum1dep_card pA : \sum_(x | pA x) 1 = #|[set x | pA x]|. Proof. by rewrite sum1_card cardsE. Qed. Lemma sum_nat_cond_const pA n : \sum_(x | pA x) n = #|[set x | pA x]| * n. Proof. by rewrite sum_nat_const cardsE. Qed. Lemma cards0 : #|@set0 T| = 0. Proof. by rewrite cardsE card0. Qed. Lemma cards_eq0 A : (#|A| == 0) = (A == set0). Proof. by rewrite (eq_sym A) eqEcard sub0set cards0 leqn0. Qed. Lemma set0Pn A : reflect (exists x, x \in A) (A != set0). Proof. by rewrite -cards_eq0; apply: existsP. Qed. Lemma set0_Nexists A : (A == set0) = ~~ [exists x, x \in A]. Proof. by rewrite -(sameP (set0Pn _) existsP) negbK. Qed. Lemma card_gt0 A : (0 < #|A|) = (A != set0). Proof. by rewrite lt0n cards_eq0. Qed. Lemma cards0_eq A : #|A| = 0 -> A = set0. Proof. by move=> A_0; apply/setP=> x; rewrite inE (card0_eq A_0). Qed. Lemma cards1 x : #|[set x]| = 1. Proof. by rewrite set1.unlock cardsE card1. Qed. Lemma cardsUI A B : #|A :|: B| + #|A :&: B| = #|A| + #|B|. Proof. by rewrite !cardsE cardUI. Qed. Lemma cardsU A B : #|A :|: B| = #|A| + #|B| - #|A :&: B|. Proof. by rewrite -cardsUI addnK. Qed. Lemma cardsI A B : #|A :&: B| = #|A| + #|B| - #|A :|: B|. Proof. by rewrite -cardsUI addKn. Qed. Lemma cardsT : #|[set: T]| = #|T|. Proof. by rewrite cardsE. Qed. Lemma cardsID B A : #|A :&: B| + #|A :\: B| = #|A|. Proof. by rewrite !cardsE cardID. Qed. Lemma cardsD A B : #|A :\: B| = #|A| - #|A :&: B|. Proof. by rewrite -(cardsID B A) addKn. Qed. Lemma cardsC A : #|A| + #|~: A| = #|T|. Proof. by rewrite cardsE cardC. Qed. Lemma cardsCs A : #|A| = #|T| - #|~: A|. Proof. by rewrite -(cardsC A) addnK. Qed. Lemma cardsU1 a A : #|a |: A| = (a \notin A) + #|A|. Proof. by rewrite -cardU1; apply: eq_card=> x; rewrite !inE. Qed. Lemma cards2 a b : #|[set a; b]| = (a != b).+1. Proof. by rewrite -card2; apply: eq_card=> x; rewrite !inE. Qed. Lemma cardsC1 a : #|[set~ a]| = #|T|.-1. Proof. by rewrite -(cardC1 a); apply: eq_card=> x; rewrite !inE. Qed. Lemma cardsD1 a A : #|A| = (a \in A) + #|A :\ a|. Proof. by rewrite (cardD1 a); congr (_ + _); apply: eq_card => x; rewrite !inE. Qed. (* other inclusions *) Lemma subsetIl A B : A :&: B \subset A. Proof. by apply/subsetP=> x /[!inE] /andP[]. Qed. Lemma subsetIr A B : A :&: B \subset B. Proof. by apply/subsetP=> x /[!inE] /andP[]. Qed. Lemma subsetUl A B : A \subset A :|: B. Proof. by apply/subsetP=> x /[!inE] ->. Qed. Lemma subsetUr A B : B \subset A :|: B. Proof. by apply/subsetP=> x; rewrite inE orbC => ->. Qed. Lemma subsetU1 x A : A \subset x |: A. Proof. exact: subsetUr. Qed. Lemma subsetDl A B : A :\: B \subset A. Proof. by rewrite setDE subsetIl. Qed. Lemma subD1set A x : A :\ x \subset A. Proof. by rewrite subsetDl. Qed. Lemma subsetDr A B : A :\: B \subset ~: B. Proof. by rewrite setDE subsetIr. Qed. Lemma sub1set A x : ([set x] \subset A) = (x \in A). Proof. by rewrite -subset_pred1; apply: eq_subset=> y; rewrite !inE. Qed. Variant cards_eq_spec A : seq T -> {set T} -> nat -> Type := | CardEq (s : seq T) & uniq s : cards_eq_spec A s [set x | x \in s] (size s). Lemma cards_eqP A : cards_eq_spec A (enum A) A #|A|. Proof. by move: (enum A) (cardE A) (set_enum A) (enum_uniq A) => s -> <-; constructor. Qed. Lemma cards1P A : reflect (exists x, A = [set x]) (#|A| == 1). Proof. apply: (iffP idP) => [|[x ->]]; last by rewrite cards1. by have [[|x []]// _] := cards_eqP; exists x; apply/setP => y; rewrite !inE. Qed. Lemma cards2P A : reflect (exists x y : T, x != y /\ A = [set x; y]) (#|A| == 2). Proof. apply: (iffP idP) => [|[x] [y] [xy ->]]; last by rewrite cards2 xy. have [[|x [|y []]]//=] := cards_eqP; rewrite !inE andbT => neq_xy. by exists x, y; split=> //; apply/setP => z; rewrite !inE. Qed. Lemma subset1 A x : (A \subset [set x]) = (A == [set x]) || (A == set0). Proof. rewrite eqEcard cards1 -cards_eq0 orbC andbC. by case: posnP => // A0; rewrite (cards0_eq A0) sub0set. Qed. Lemma powerset1 x : powerset [set x] = [set set0; [set x]]. Proof. by apply/setP=> A; rewrite inE subset1 orbC set1.unlock !inE. Qed. Lemma setIidPl A B : reflect (A :&: B = A) (A \subset B). Proof. apply: (iffP subsetP) => [sAB | <- x /setIP[] //]. by apply/setP=> x /[1!inE]; apply/andb_idr/sAB. Qed. Arguments setIidPl {A B}. Lemma setIidPr A B : reflect (A :&: B = B) (B \subset A). Proof. by rewrite setIC; apply: setIidPl. Qed. Lemma cardsDS A B : B \subset A -> #|A :\: B| = #|A| - #|B|. Proof. by rewrite cardsD => /setIidPr->. Qed. Lemma setUidPl A B : reflect (A :|: B = A) (B \subset A). Proof. by rewrite -setCS (sameP setIidPl eqP) -setCU (inj_eq setC_inj); apply: eqP. Qed. Lemma setUidPr A B : reflect (A :|: B = B) (A \subset B). Proof. by rewrite setUC; apply: setUidPl. Qed. Lemma setDidPl A B : reflect (A :\: B = A) [disjoint A & B]. Proof. by rewrite setDE disjoints_subset; apply: setIidPl. Qed. Lemma subIset A B C : (B \subset A) || (C \subset A) -> (B :&: C \subset A). Proof. by case/orP; apply: subset_trans; rewrite (subsetIl, subsetIr). Qed. Lemma subsetI A B C : (A \subset B :&: C) = (A \subset B) && (A \subset C). Proof. rewrite !(sameP setIidPl eqP) setIA; have [-> //|] := eqVneq (A :&: B) A. by apply: contraNF => /eqP <-; rewrite -setIA -setIIl setIAC. Qed. Lemma subsetIP A B C : reflect (A \subset B /\ A \subset C) (A \subset B :&: C). Proof. by rewrite subsetI; apply: andP. Qed. Lemma subsetIidl A B : (A \subset A :&: B) = (A \subset B). Proof. by rewrite subsetI subxx. Qed. Lemma subsetIidr A B : (B \subset A :&: B) = (B \subset A). Proof. by rewrite setIC subsetIidl. Qed. Lemma powersetI A B : powerset (A :&: B) = powerset A :&: powerset B. Proof. by apply/setP=> C; rewrite !inE subsetI. Qed. Lemma subUset A B C : (B :|: C \subset A) = (B \subset A) && (C \subset A). Proof. by rewrite -setCS setCU subsetI !setCS. Qed. Lemma subsetU A B C : (A \subset B) || (A \subset C) -> A \subset B :|: C. Proof. by rewrite -!(setCS _ A) setCU; apply: subIset. Qed. Lemma subUsetP A B C : reflect (A \subset C /\ B \subset C) (A :|: B \subset C). Proof. by rewrite subUset; apply: andP. Qed. Lemma subsetC A B : (A \subset ~: B) = (B \subset ~: A). Proof. by rewrite -setCS setCK. Qed. Lemma subCset A B : (~: A \subset B) = (~: B \subset A). Proof. by rewrite -setCS setCK. Qed. Lemma subsetD A B C : (A \subset B :\: C) = (A \subset B) && [disjoint A & C]. Proof. by rewrite setDE subsetI -disjoints_subset. Qed. Lemma subDset A B C : (A :\: B \subset C) = (A \subset B :|: C). Proof. apply/subsetP/subsetP=> sABC x; rewrite !inE. by case Bx: (x \in B) => // Ax; rewrite sABC ?inE ?Bx. by case Bx: (x \in B) => // /sABC; rewrite inE Bx. Qed. Lemma subsetDP A B C : reflect (A \subset B /\ [disjoint A & C]) (A \subset B :\: C). Proof. by rewrite subsetD; apply: andP. Qed. Lemma setU_eq0 A B : (A :|: B == set0) = (A == set0) && (B == set0). Proof. by rewrite -!subset0 subUset. Qed. Lemma setD_eq0 A B : (A :\: B == set0) = (A \subset B). Proof. by rewrite -subset0 subDset setU0. Qed. Lemma setI_eq0 A B : (A :&: B == set0) = [disjoint A & B]. Proof. by rewrite disjoints_subset -setD_eq0 setDE setCK. Qed. Lemma eq0_subset B A : (A == set0) = (A \subset B) && (A \subset ~: B). Proof. by rewrite -subsetI setICr subset0. Qed. Lemma disjoint_setI0 A B : [disjoint A & B] -> A :&: B = set0. Proof. by rewrite -setI_eq0; move/eqP. Qed. Lemma subsetC_disjoint A B : [disjoint A & B] -> forall C, C != set0 -> C \subset A -> ~~ (C \subset B). Proof. move=> dAB C + CA; apply: contra_neqN => CB. by apply/eqP; rewrite -subset0 -(disjoint_setI0 dAB) subsetI CA CB. Qed. Lemma disjoints1 A x : [disjoint [set x] & A] = (x \notin A). Proof. by rewrite (@eq_disjoint1 _ x) // => y; rewrite !inE. Qed. Lemma subsetD1 A B x : (A \subset B :\ x) = (A \subset B) && (x \notin A). Proof. by rewrite setDE subsetI subsetC sub1set inE. Qed. Lemma subsetD1P A B x : reflect (A \subset B /\ x \notin A) (A \subset B :\ x). Proof. by rewrite subsetD1; apply: andP. Qed. Lemma properD1 A x : x \in A -> A :\ x \proper A. Proof. move=> Ax; rewrite properE subsetDl; apply/subsetPn; exists x=> //. by rewrite in_setD1 Ax eqxx. Qed. Lemma properIr A B : ~~ (B \subset A) -> A :&: B \proper B. Proof. by move=> nsAB; rewrite properE subsetIr subsetI negb_and nsAB. Qed. Lemma properIl A B : ~~ (A \subset B) -> A :&: B \proper A. Proof. by move=> nsBA; rewrite properE subsetIl subsetI negb_and nsBA orbT. Qed. Lemma properUr A B : ~~ (A \subset B) -> B \proper A :|: B. Proof. by rewrite properE subsetUr subUset subxx /= andbT. Qed. Lemma properUl A B : ~~ (B \subset A) -> A \proper A :|: B. Proof. by move=> not_sBA; rewrite setUC properUr. Qed. Lemma proper1set A x : ([set x] \proper A) -> (x \in A). Proof. by move/proper_sub; rewrite sub1set. Qed. Lemma properIset A B C : (B \proper A) || (C \proper A) -> (B :&: C \proper A). Proof. by case/orP; apply: sub_proper_trans; rewrite (subsetIl, subsetIr). Qed. Lemma properI A B C : (A \proper B :&: C) -> (A \proper B) && (A \proper C). Proof. move=> pAI; apply/andP. by split; apply: (proper_sub_trans pAI); rewrite (subsetIl, subsetIr). Qed. Lemma properU A B C : (B :|: C \proper A) -> (B \proper A) && (C \proper A). Proof. move=> pUA; apply/andP. by split; apply: sub_proper_trans pUA; rewrite (subsetUr, subsetUl). Qed. Lemma properD A B C : (A \proper B :\: C) -> (A \proper B) && [disjoint A & C]. Proof. by rewrite setDE disjoints_subset => /properI/andP[-> /proper_sub]. Qed. Lemma properCr A B : (A \proper ~: B) = (B \proper ~: A). Proof. by rewrite -properC setCK. Qed. Lemma properCl A B : (~: A \proper B) = (~: B \proper A). Proof. by rewrite -properC setCK. Qed. (* relationship with seq *) Lemma enum_setU A B : perm_eq (enum (A :|: B)) (undup (enum A ++ enum B)). Proof. apply: uniq_perm; rewrite ?enum_uniq ?undup_uniq//. by move=> i; rewrite mem_undup mem_enum inE mem_cat !mem_enum. Qed. Lemma enum_setI A B : perm_eq (enum (A :&: B)) (filter [in B] (enum A)). Proof. apply: uniq_perm; rewrite ?enum_uniq// 1?filter_uniq// ?enum_uniq//. by move=> x; rewrite /= mem_enum mem_filter inE mem_enum andbC. Qed. Lemma has_set1 pA A a : has pA (enum [set a]) = pA a. Proof. by rewrite enum_set1 has_seq1. Qed. Lemma has_setU pA A B : has pA (enum (A :|: B)) = (has pA (enum A)) || (has pA (enum B)). Proof. by rewrite (perm_has _ (enum_setU _ _)) has_undup has_cat. Qed. Lemma all_set1 pA A a : all pA (enum [set a]) = pA a. Proof. by rewrite enum_set1 all_seq1. Qed. Lemma all_setU pA A B : all pA (enum (A :|: B)) = (all pA (enum A)) && (all pA (enum B)). Proof. by rewrite (perm_all _ (enum_setU _ _)) all_undup all_cat. Qed. End setOps. Arguments set1P {T x a}. Arguments set1_inj {T} [x1 x2]. Arguments set2P {T x a b}. Arguments setIdP {T x pA pB}. Arguments setIP {T x A B}. Arguments setU1P {T x a B}. Arguments setD1P {T x A b}. Arguments setUP {T x A B}. Arguments setDP {T A B x}. Arguments cards1P {T A}. Arguments setCP {T x A}. Arguments setIidPl {T A B}. Arguments setIidPr {T A B}. Arguments setUidPl {T A B}. Arguments setUidPr {T A B}. Arguments setDidPl {T A B}. Arguments subsetIP {T A B C}. Arguments subUsetP {T A B C}. Arguments subsetDP {T A B C}. Arguments subsetD1P {T A B x}. Prenex Implicits set1. #[global] Hint Extern 0 (is_true (subset _ (mem (pred_of_set (setTfor _))))) => solve [apply: subsetT_hint] : core. Section setOpsAlgebra. Import Monoid. Variable T : finType. HB.instance Definition _ := isComLaw.Build {set T} [set: T] (@setI T) (@setIA T) (@setIC T) (@setTI T). HB.instance Definition _ := isMulLaw.Build {set T} set0 (@setI T) (@set0I T) (@setI0 T). HB.instance Definition _ := isComLaw.Build {set T} set0 (@setU T) (@setUA T) (@setUC T) (@set0U T). HB.instance Definition _ := isMulLaw.Build {set T} [set: T] (@setU T) (@setTU T) (@setUT T). HB.instance Definition _ := isAddLaw.Build {set T} (@setU T) (@setI T) (@setUIl T) (@setUIr T). HB.instance Definition _ := isAddLaw.Build {set T} (@setI T) (@setU T) (@setIUl T) (@setIUr T). End setOpsAlgebra. Section CartesianProd. Variables fT1 fT2 : finType. Variables (A1 : {set fT1}) (A2 : {set fT2}). Definition setX := [set u | u.1 \in A1 & u.2 \in A2]. Lemma in_setX x1 x2 : ((x1, x2) \in setX) = (x1 \in A1) && (x2 \in A2). Proof. by rewrite inE. Qed. Lemma setXP x1 x2 : reflect (x1 \in A1 /\ x2 \in A2) ((x1, x2) \in setX). Proof. by rewrite inE; apply: andP. Qed. Lemma cardsX : #|setX| = #|A1| * #|A2|. Proof. by rewrite cardsE cardX. Qed. End CartesianProd. Arguments setXP {fT1 fT2 A1 A2 x1 x2}. Section CartesianNProd. Variables (I : finType) (fT : I -> finType). Variables (A : forall i, {set fT i}). Implicit Types (x : {dffun forall i, fT i}). Definition setXn := [set x : {dffun _} in family A]. Lemma in_setXn x : (x \in setXn) = [forall i, x i \in A i]. Proof. by rewrite inE. Qed. Lemma setXnP x : reflect (forall i, x i \in A i) (x \in setXn). Proof. by rewrite inE; apply: forallP. Qed. Lemma cardsXn : #|setXn| = \prod_i #|A i|. Proof. by rewrite cardsE card_family foldrE big_map big_enum. Qed. End CartesianNProd. Arguments setXnP {I fT A x}. HB.lock Definition imset (aT rT : finType) f mD := [set y in @image_mem aT rT f mD]. Canonical imset_unlock := Unlockable imset.unlock. HB.lock Definition imset2 (aT1 aT2 rT : finType) f (D1 : mem_pred aT1) (D2 : _ -> mem_pred aT2) := [set y in @image_mem _ rT (uncurry f) (mem [pred u | D1 u.1 & D2 u.1 u.2])]. Canonical imset2_unlock := Unlockable imset2.unlock. Definition preimset (aT : finType) rT f (R : mem_pred rT) := [set x : aT | in_mem (f x) R]. Notation "f @^-1: A" := (preimset f (mem A)) (at level 24) : set_scope. Notation "f @: A" := (imset f (mem A)) (at level 24) : set_scope. Notation "f @2: ( A , B )" := (imset2 f (mem A) (fun _ => mem B)) (at level 24, format "f @2: ( A , B )") : set_scope. (* Comprehensions *) Notation "[ 'set' E | x 'in' A ]" := ((fun x => E) @: A) (format "[ '[hv' 'set' E '/ ' | x 'in' A ] ']'") : set_scope. Notation "[ 'set' E | x 'in' A & P ]" := [set E | x in pred_of_set [set x in A | P]] (format "[ '[hv' 'set' E '/ ' | x 'in' A '/ ' & P ] ']'") : set_scope. Notation "[ 'set' E | x 'in' A , y 'in' B ]" := (imset2 (fun x y => E) (mem A) (fun x => mem B)) (y at level 99, format "[ '[hv' 'set' E '/ ' | x 'in' A , '/ ' y 'in' B ] ']'" ) : set_scope. Notation "[ 'set' E | x 'in' A , y 'in' B & P ]" := [set E | x in A, y in pred_of_set [set y in B | P]] (format "[ '[hv' 'set' E '/ ' | x 'in' A , '/ ' y 'in' B '/ ' & P ] ']'" ) : set_scope. (* Typed variants *) Notation "[ 'set' E | x : T 'in' A ]" := ((fun x : T => E) @: A) (only parsing) : set_scope. Notation "[ 'set' E | x : T 'in' A & P ]" := [set E | x : T in [set x : T in A | P]] (only parsing) : set_scope. Notation "[ 'set' E | x : T 'in' A , y : U 'in' B ]" := (imset2 (fun (x : T) (y : U) => E) (mem A) (fun (x : T) => mem B)) (y at level 99, only parsing) : set_scope. Notation "[ 'set' E | x : T 'in' A , y : U 'in' B & P ]" := [set E | x : T in A, y : U in [set y : U in B | P]] (only parsing) : set_scope. (* Comprehensions over a type *) Local Notation predOfType T := (pred_of_simpl (@pred_of_argType T)). Notation "[ 'set' E | x : T ]" := [set E | x : T in predOfType T] (format "[ '[hv' 'set' E '/ ' | x : T ] ']'") : set_scope. Notation "[ 'set' E | x : T & P ]" := [set E | x : T in pred_of_set [set x : T | P]] (format "[ '[hv' 'set' E '/ ' | x : T '/ ' & P ] ']'") : set_scope. Notation "[ 'set' E | x : T , y : U 'in' B ]" := [set E | x : T in predOfType T, y : U in B] (y at level 99, format "[ '[hv' 'set' E '/ ' | x : T , '/ ' y : U 'in' B ] ']'") : set_scope. Notation "[ 'set' E | x : T , y : U 'in' B & P ]" := [set E | x : T, y : U in pred_of_set [set y in B | P]] (format "[ '[hv ' 'set' E '/' | x : T , '/ ' y : U 'in' B '/' & P ] ']'" ) : set_scope. Notation "[ 'set' E | x : T 'in' A , y : U ]" := [set E | x : T in A, y : U in predOfType U] (format "[ '[hv' 'set' E '/ ' | x : T 'in' A , '/ ' y : U ] ']'") : set_scope. Notation "[ 'set' E | x : T 'in' A , y : U & P ]" := [set E | x : T in A, y : U in pred_of_set [set y in P]] (format "[ '[hv' 'set' E '/ ' | x : T 'in' A , '/ ' y : U & P ] ']'") : set_scope. Notation "[ 'set' E | x : T , y : U ]" := [set E | x : T, y : U in predOfType U] (format "[ '[hv' 'set' E '/ ' | x : T , '/ ' y : U ] ']'") : set_scope. Notation "[ 'set' E | x : T , y : U & P ]" := [set E | x : T, y : U in pred_of_set [set y in P]] (format "[ '[hv' 'set' E '/ ' | x : T , '/ ' y : U & P ] ']'") : set_scope. (* Untyped variants *) Notation "[ 'set' E | x , y 'in' B ]" := [set E | x : _, y : _ in B] (y at level 99, only parsing) : set_scope. Notation "[ 'set' E | x , y 'in' B & P ]" := [set E | x : _, y : _ in B & P] (only parsing) : set_scope. Notation "[ 'set' E | x 'in' A , y ]" := [set E | x : _ in A, y : _] (only parsing) : set_scope. Notation "[ 'set' E | x 'in' A , y & P ]" := [set E | x : _ in A, y : _ & P] (only parsing) : set_scope. Notation "[ 'set' E | x , y ]" := [set E | x : _, y : _] (only parsing) : set_scope. Notation "[ 'set' E | x , y & P ]" := [set E | x : _, y : _ & P ] (only parsing) : set_scope. Section FunImage. Variables aT aT2 : finType. Section ImsetTheory. Variable rT : finType. Section ImsetProp. Variables (f : aT -> rT) (f2 : aT -> aT2 -> rT). Lemma imsetP D y : reflect (exists2 x, in_mem x D & y = f x) (y \in imset f D). Proof. by rewrite [@imset]unlock inE; apply: imageP. Qed. Variant imset2_spec D1 D2 y : Prop := Imset2spec x1 x2 of in_mem x1 D1 & in_mem x2 (D2 x1) & y = f2 x1 x2. Lemma imset2P D1 D2 y : reflect (imset2_spec D1 D2 y) (y \in imset2 f2 D1 D2). Proof. rewrite [@imset2]unlock inE. apply: (iffP imageP) => [[[x1 x2] Dx12] | [x1 x2 Dx1 Dx2]] -> {y}. by case/andP: Dx12; exists x1 x2. by exists (x1, x2); rewrite //= !inE Dx1. Qed. Lemma imset_f (D : {pred aT}) x : x \in D -> f x \in f @: D. Proof. by move=> Dx; apply/imsetP; exists x. Qed. Lemma mem_imset (D : {pred aT}) x : injective f -> f x \in f @: D = (x \in D). Proof. by move=> f_inj; apply/imsetP/idP;[case=> [y] ? /f_inj -> | move=> ?; exists x]. Qed. Lemma imset0 : f @: set0 = set0. Proof. by apply/setP => y /[!inE]; apply/imsetP => -[x /[!inE]]. Qed. Lemma imset_eq0 (A : {set aT}) : (f @: A == set0) = (A == set0). Proof. have [-> | [x Ax]] := set_0Vmem A; first by rewrite imset0 !eqxx. by rewrite -!cards_eq0 (cardsD1 x) Ax (cardsD1 (f x)) imset_f. Qed. Lemma imset_set1 x : f @: [set x] = [set f x]. Proof. apply/setP => y. by apply/imsetP/set1P=> [[x' /set1P-> //]| ->]; exists x; rewrite ?set11. Qed. Lemma imset_inj : injective f -> injective (fun A : {set aT} => f @: A). Proof. move=> inj_f A B => /setP E; apply/setP => x. by rewrite -(mem_imset A x inj_f) E mem_imset. Qed. Lemma imset_disjoint (A B : {pred aT}) : injective f -> [disjoint f @: A & f @: B] = [disjoint A & B]. Proof. move=> inj_f; apply/pred0Pn/pred0Pn => /= [[_ /andP[/imsetP[x xA ->]] xB]|]. by exists x; rewrite xA -(mem_imset B x inj_f). by move=> [x /andP[xA xB]]; exists (f x); rewrite !mem_imset ?xA. Qed. Lemma imset2_f (D : {pred aT}) (D2 : aT -> {pred aT2}) x x2 : x \in D -> x2 \in D2 x -> f2 x x2 \in [set f2 y y2 | y in D, y2 in D2 y]. Proof. by move=> Dx Dx2; apply/imset2P; exists x x2. Qed. Lemma mem_imset2 (D : {pred aT}) (D2 : aT -> {pred aT2}) x x2 : injective2 f2 -> (f2 x x2 \in [set f2 y y2 | y in D, y2 in D2 y]) = (x \in D) && (x2 \in D2 x). Proof. move=> inj2_f; apply/imset2P/andP => [|[xD xD2]]; last by exists x x2. by move => [x' x2' xD xD2 eq_f2]; case: (inj2_f _ _ _ _ eq_f2) => -> ->. Qed. Lemma sub_imset_pre (A : {pred aT}) (B : {pred rT}) : (f @: A \subset B) = (A \subset f @^-1: B). Proof. apply/subsetP/subsetP=> [sfAB x Ax | sAf'B fx]. by rewrite inE sfAB ?imset_f. by move=> /imsetP[a + ->] => /sAf'B /[!inE]. Qed. Lemma preimsetS (A B : {pred rT}) : A \subset B -> (f @^-1: A) \subset (f @^-1: B). Proof. by move=> sAB; apply/subsetP=> y /[!inE]; apply: subsetP. Qed. Lemma preimset0 : f @^-1: set0 = set0. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma preimsetT : f @^-1: setT = setT. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma preimsetI (A B : {set rT}) : f @^-1: (A :&: B) = (f @^-1: A) :&: (f @^-1: B). Proof. by apply/setP=> y; rewrite !inE. Qed. Lemma preimsetU (A B : {set rT}) : f @^-1: (A :|: B) = (f @^-1: A) :|: (f @^-1: B). Proof. by apply/setP=> y; rewrite !inE. Qed. Lemma preimsetD (A B : {set rT}) : f @^-1: (A :\: B) = (f @^-1: A) :\: (f @^-1: B). Proof. by apply/setP=> y; rewrite !inE. Qed. Lemma preimsetC (A : {set rT}) : f @^-1: (~: A) = ~: f @^-1: A. Proof. by apply/setP=> y; rewrite !inE. Qed. Lemma imsetS (A B : {pred aT}) : A \subset B -> f @: A \subset f @: B. Proof. move=> sAB; apply/subsetP => _ /imsetP[x Ax ->]. by apply/imsetP; exists x; rewrite ?(subsetP sAB). Qed. Lemma imset_proper (A B : {set aT}) : {in B &, injective f} -> A \proper B -> f @: A \proper f @: B. Proof. move=> injf /properP[sAB [x Bx nAx]]; rewrite properE imsetS //=. apply: contra nAx => sfBA. have: f x \in f @: A by rewrite (subsetP sfBA) ?imset_f. by case/imsetP=> y Ay /injf-> //; apply: subsetP sAB y Ay. Qed. Lemma preimset_proper (A B : {set rT}) : B \subset codom f -> A \proper B -> (f @^-1: A) \proper (f @^-1: B). Proof. move=> sBc /properP[sAB [u Bu nAu]]; rewrite properE preimsetS //=. by apply/subsetPn; exists (iinv (subsetP sBc _ Bu)); rewrite inE /= f_iinv. Qed. Lemma imsetU (A B : {set aT}) : f @: (A :|: B) = (f @: A) :|: (f @: B). Proof. apply/eqP; rewrite eqEsubset subUset. rewrite 2?imsetS (andbT, subsetUl, subsetUr) // andbT. apply/subsetP=> _ /imsetP[x ABx ->]; apply/setUP. by case/setUP: ABx => [Ax | Bx]; [left | right]; apply/imsetP; exists x. Qed. Lemma imsetU1 a (A : {set aT}) : f @: (a |: A) = f a |: (f @: A). Proof. by rewrite imsetU imset_set1. Qed. Lemma imsetI (A B : {set aT}) : {in A & B, injective f} -> f @: (A :&: B) = f @: A :&: f @: B. Proof. move=> injf; apply/eqP; rewrite eqEsubset subsetI. rewrite 2?imsetS (andTb, subsetIl, subsetIr) //=. apply/subsetP=> _ /setIP[/imsetP[x Ax ->] /imsetP[z Bz /injf eqxz]]. by rewrite imset_f // inE Ax eqxz. Qed. Lemma imset2Sl (A B : {pred aT}) (C : {pred aT2}) : A \subset B -> f2 @2: (A, C) \subset f2 @2: (B, C). Proof. move=> sAB; apply/subsetP=> _ /imset2P[x y Ax Cy ->]. by apply/imset2P; exists x y; rewrite ?(subsetP sAB). Qed. Lemma imset2Sr (A B : {pred aT2}) (C : {pred aT}) : A \subset B -> f2 @2: (C, A) \subset f2 @2: (C, B). Proof. move=> sAB; apply/subsetP=> _ /imset2P[x y Ax Cy ->]. by apply/imset2P; exists x y; rewrite ?(subsetP sAB). Qed. Lemma imset2S (A B : {pred aT}) (A2 B2 : {pred aT2}) : A \subset B -> A2 \subset B2 -> f2 @2: (A, A2) \subset f2 @2: (B, B2). Proof. by move=> /(imset2Sl B2) sBA /(imset2Sr A)/subset_trans->. Qed. End ImsetProp. Implicit Types (f g : aT -> rT) (D : {pred aT}) (R : {pred rT}). Lemma eq_preimset f g R : f =1 g -> f @^-1: R = g @^-1: R. Proof. by move=> eqfg; apply/setP => y; rewrite !inE eqfg. Qed. Lemma eq_imset f g D : f =1 g -> f @: D = g @: D. Proof. move=> eqfg; apply/setP=> y. by apply/imsetP/imsetP=> [] [x Dx ->]; exists x; rewrite ?eqfg. Qed. Lemma eq_in_imset f g D : {in D, f =1 g} -> f @: D = g @: D. Proof. move=> eqfg; apply/setP => y. by apply/imsetP/imsetP=> [] [x Dx ->]; exists x; rewrite ?eqfg. Qed. Lemma eq_in_imset2 (f g : aT -> aT2 -> rT) (D : {pred aT}) (D2 : {pred aT2}) : {in D & D2, f =2 g} -> f @2: (D, D2) = g @2: (D, D2). Proof. move=> eqfg; apply/setP => y. by apply/imset2P/imset2P=> [] [x x2 Dx Dx2 ->]; exists x x2; rewrite ?eqfg. Qed. End ImsetTheory. Lemma imset2_pair (A : {set aT}) (B : {set aT2}) : [set (x, y) | x in A, y in B] = setX A B. Proof. apply/setP=> [[x y]]; rewrite !inE /=. by apply/imset2P/andP=> [[_ _ _ _ [-> ->]//]| []]; exists x y. Qed. Lemma setXS (A1 B1 : {set aT}) (A2 B2 : {set aT2}) : A1 \subset B1 -> A2 \subset B2 -> setX A1 A2 \subset setX B1 B2. Proof. by move=> sAB1 sAB2; rewrite -!imset2_pair imset2S. Qed. End FunImage. Arguments imsetP {aT rT f D y}. Arguments imset2P {aT aT2 rT f2 D1 D2 y}. Arguments imset_disjoint {aT rT f A B}. Section unset1. Variable (I : finType). Implicit Types (i : I) (A : {set I}). Lemma pick_set1 i0 : [pick x in [set i0]] = Some i0. Proof. by case: pickP => [i /[!inE]/eqP-> | /(_ i0)/[!(inE, eqxx)]]. Qed. Definition unset1 A : option I := if #|A| == 1 then [pick x in A] else None. Lemma set1K : pcancel set1 unset1. Proof. by move=> i; rewrite /unset1 cards1 eqxx pick_set1. Qed. Lemma omap_unset1K A : #|A| = 1 -> omap set1 (unset1 A) = Some A. Proof. by move=> /eqP/cards1P[i ->]; rewrite set1K. Qed. Lemma unset10 : unset1 set0 = None. Proof. by rewrite /unset1 cards0. Qed. Lemma unset1N1 A : #|A| != 1 -> unset1 A = None. Proof. by move=> AN1; rewrite /unset1 ifN. Qed. Lemma unset1K : ocancel unset1 set1. Proof. move=> A; rewrite /unset1. by case: ifPn => // /cards1P[i ->]/=; rewrite pick_set1. Qed. End unset1. Arguments unset1 {I}. Lemma setXnS (I : finType) (T : I -> finType) (A B : forall i, {set T i}) : (forall i, A i \subset B i) -> setXn A \subset setXn B. Proof. move=> sAB; apply/subsetP => x /setXnP xA. by apply/setXnP => i; apply/subsetP: (xA i). Qed. Lemma eq_setXn (I : finType) (T : I -> finType) (A B : forall i, {set T i}) : (forall i, A i = B i) -> setXn A = setXn B. Proof. by move=> eqAB; apply/eqP; rewrite eqEsubset !setXnS// => j; rewrite eqAB. Qed. Section BigOpsAnyOp. Variables (R : Type) (x : R) (op : R -> R -> R). Variables I : finType. Implicit Type F : I -> R. Lemma big_set0 F : \big[op/x]_(i in set0) F i = x. Proof. by apply: big_pred0 => i; rewrite inE. Qed. Lemma big_set1E j F : \big[op/x]_(i in [set j]) F i = op (F j) x. Proof. by rewrite -big_pred1_eq_id; apply: eq_bigl => i; apply: in_set1. Qed. Lemma big_set (A : pred I) F : \big[op/x]_(i in [set i | A i]) (F i) = \big[op/x]_(i in A) (F i). Proof. by apply: eq_bigl => i; rewrite inE. Qed. End BigOpsAnyOp. Section BigOpsSemiGroup. Variables (R : Type) (op : SemiGroup.com_law R). Variable (le : rel R). Hypotheses (le_refl : reflexive le) (le_incr : forall x y, le x (op x y)). Context [x : R]. Lemma subset_le_big_cond (I : finType) (A A' P P' : {pred I}) (F : I -> R) : [set i in A | P i] \subset [set i in A' | P' i] -> le (\big[op/x]_(i in A | P i) F i) (\big[op/x]_(i in A' | P' i) F i). Proof. by move=> /subsetP AP; apply: sub_le_big => // i; have /[!inE] := AP i. Qed. Lemma big_imset_idem [I J : finType] (h : I -> J) (A : pred I) F : idempotent_op op -> \big[op/x]_(j in h @: A) F j = \big[op/x]_(i in A) F (h i). Proof. rewrite -!big_image => op_idem; rewrite -big_undup// -[RHS]big_undup//. apply/perm_big/perm_undup => j; apply/imageP. have [mem_j | /imageP mem_j] := boolP (j \in [seq h j | j in A]). - by exists j => //; apply/imsetP; apply: imageP mem_j. - by case=> k /imsetP [i j_in_A ->] eq_i; apply: mem_j; exists i. Qed. End BigOpsSemiGroup. Section BigOps. Variables (R : Type) (idx : R). Variables (op : Monoid.law idx) (aop : Monoid.com_law idx). Variables (times : Monoid.mul_law idx) (plus : Monoid.add_law idx times). Variables I J : finType. Implicit Type A B : {set I}. Implicit Type h : I -> J. Implicit Type P : pred I. Implicit Type F : I -> R. Lemma big_set1 a F : \big[op/idx]_(i in [set a]) F i = F a. Proof. by apply: big_pred1 => i; rewrite !inE. Qed. Lemma big_setID A B F : \big[aop/idx]_(i in A) F i = aop (\big[aop/idx]_(i in A :&: B) F i) (\big[aop/idx]_(i in A :\: B) F i). Proof. rewrite (bigID [in B]) setDE. by congr (aop _ _); apply: eq_bigl => i; rewrite !inE. Qed. Lemma big_setIDcond A B P F : \big[aop/idx]_(i in A | P i) F i = aop (\big[aop/idx]_(i in A :&: B | P i) F i) (\big[aop/idx]_(i in A :\: B | P i) F i). Proof. by rewrite !big_mkcondr; apply: big_setID. Qed. Lemma big_setD1 a A F : a \in A -> \big[aop/idx]_(i in A) F i = aop (F a) (\big[aop/idx]_(i in A :\ a) F i). Proof. move=> Aa; rewrite (bigD1 a Aa); congr (aop _). by apply: eq_bigl => x; rewrite !inE andbC. Qed. Lemma big_setU1 a A F : a \notin A -> \big[aop/idx]_(i in a |: A) F i = aop (F a) (\big[aop/idx]_(i in A) F i). Proof. by move=> notAa; rewrite (@big_setD1 a) ?setU11 //= setU1K. Qed. Lemma big_subset_idem_cond A B P F : idempotent_op aop -> A \subset B -> aop (\big[aop/idx]_(i in A | P i) F i) (\big[aop/idx]_(i in B | P i) F i) = \big[aop/idx]_(i in B | P i) F i. Proof. by move=> idaop /setIidPr <-; rewrite (big_setIDcond B A) Monoid.mulmA /= idaop. Qed. Lemma big_subset_idem A B F : idempotent_op aop -> A \subset B -> aop (\big[aop/idx]_(i in A) F i) (\big[aop/idx]_(i in B) F i) = \big[aop/idx]_(i in B) F i. Proof. by rewrite -2!big_condT; apply: big_subset_idem_cond. Qed. Lemma big_setU_cond A B P F : idempotent_op aop -> \big[aop/idx]_(i in A :|: B | P i) F i = aop (\big[aop/idx]_(i in A | P i) F i) (\big[aop/idx]_(i in B | P i) F i). Proof. move=> idemaop; rewrite (big_setIDcond _ A) setUK setDUl setDv set0U. rewrite (big_setIDcond B A) Monoid.mulmCA Monoid.mulmA /=. by rewrite (@big_subset_idem_cond (B :&: A)) // subsetIr. Qed. Lemma big_setU A B F : idempotent_op aop -> \big[aop/idx]_(i in A :|: B) F i = aop (\big[aop/idx]_(i in A) F i) (\big[aop/idx]_(i in B) F i). Proof. by rewrite -3!big_condT; apply: big_setU_cond. Qed. Lemma big_imset h (A : {pred I}) G : {in A &, injective h} -> \big[aop/idx]_(j in h @: A) G j = \big[aop/idx]_(i in A) G (h i). Proof. move=> injh; pose hA := mem (image h A). rewrite (eq_bigl hA) => [|j]; last exact/imsetP/imageP. pose h' := omap (fun u : {j | hA j} => iinv (svalP u)) \o insub. rewrite (reindex_omap h h') => [|j hAj]; rewrite {}/h'/= ?insubT/= ?f_iinv//. apply: eq_bigl => i; case: insubP => [u /= -> def_u | nhAhi]; last first. by apply/andP/idP => [[]//| Ai]; case/imageP: nhAhi; exists i. set i' := iinv _; have Ai' : i' \in A := mem_iinv (svalP u). by apply/eqP/idP => [[<-] // | Ai]; congr Some; apply: injh; rewrite ?f_iinv. Qed. Lemma big_imset_cond h (A : {pred I}) (P : pred J) G : {in A &, injective h} -> \big[aop/idx]_(j in h @: A | P j) G j = \big[aop/idx]_(i in A | P (h i)) G (h i). Proof. by move=> h_inj; rewrite 2!big_mkcondr big_imset. Qed. Lemma partition_big_imset h (A : {pred I}) F : \big[aop/idx]_(i in A) F i = \big[aop/idx]_(j in h @: A) \big[aop/idx]_(i in A | h i == j) F i. Proof. by apply: partition_big => i Ai; apply/imsetP; exists i. Qed. Lemma big_cards1 (f : {set I} -> R) : \big[aop/idx]_(A : {set I} | #|A| == 1) f A = \big[aop/idx]_(i : I) f [set i]. Proof. rewrite (reindex_omap set1 unset1) => [|A /cards1P[i ->] /[!set1K]//]. by apply: eq_bigl => i; rewrite set1K cards1 !eqxx. Qed. End BigOps. Lemma bigA_distr (R : Type) (zero one : R) (mul : Monoid.mul_law zero) (add : Monoid.add_law zero mul) (I : finType) (F G : I -> R) : \big[mul/one]_i add (F i) (G i) = \big[add/zero]_(J in {set I}) \big[mul/one]_i (if i \in J then F i else G i). Proof. under eq_bigr => i _ do rewrite -(big_bool _ (fun b => if b then F i else G i)). rewrite bigA_distr_bigA. set f := fun J : {set I} => val J. transitivity (\big[add/zero]_(f0 in (imset f (mem setT))) \big[mul/one]_i (if f0 i then F i else G i)). suff <-: setT = imset f (mem setT) by apply: congr_big=>// i; rewrite in_setT. apply/esym/eqP; rewrite -subTset; apply/subsetP => b _. by apply/imsetP; exists (FinSet b). rewrite big_imset; last by case=> g; case=> h _ _; rewrite /f => /= ->. apply: congr_big => //; case=> g; first exact: in_setT. by move=> _; apply: eq_bigr => i _; congr (if _ then _ else _); rewrite unlock. Qed. Arguments big_setID [R idx aop I A]. Arguments big_setD1 [R idx aop I] a [A F]. Arguments big_setU1 [R idx aop I] a [A F]. Arguments big_imset [R idx aop I J h A]. Arguments partition_big_imset [R idx aop I J]. Section Fun2Set1. Variables aT1 aT2 rT : finType. Variables (f : aT1 -> aT2 -> rT). Lemma imset2_set1l x1 (D2 : {pred aT2}) : f @2: ([set x1], D2) = f x1 @: D2. Proof. apply/setP=> y; apply/imset2P/imsetP=> [[x x2 /set1P->]| [x2 Dx2 ->]]. by exists x2. by exists x1 x2; rewrite ?set11. Qed. Lemma imset2_set1r x2 (D1 : {pred aT1}) : f @2: (D1, [set x2]) = f^~ x2 @: D1. Proof. apply/setP=> y; apply/imset2P/imsetP=> [[x1 x Dx1 /set1P->]| [x1 Dx1 ->]]. by exists x1. by exists x1 x2; rewrite ?set11. Qed. End Fun2Set1. Section CardFunImage. Variables aT aT2 rT : finType. Variables (f : aT -> rT) (g : rT -> aT) (f2 : aT -> aT2 -> rT). Variables (D : {pred aT}) (D2 : {pred aT}). Lemma imset_card : #|f @: D| = #|image f D|. Proof. by rewrite [@imset]unlock cardsE. Qed. Lemma leq_imset_card : #|f @: D| <= #|D|. Proof. by rewrite imset_card leq_image_card. Qed. Lemma card_in_imset : {in D &, injective f} -> #|f @: D| = #|D|. Proof. by move=> injf; rewrite imset_card card_in_image. Qed. Lemma card_imset : injective f -> #|f @: D| = #|D|. Proof. by move=> injf; rewrite imset_card card_image. Qed. Lemma imset_injP : reflect {in D &, injective f} (#|f @: D| == #|D|). Proof. by rewrite [@imset]unlock cardsE; apply: image_injP. Qed. Lemma can2_in_imset_pre : {in D, cancel f g} -> {on D, cancel g & f} -> f @: D = g @^-1: D. Proof. move=> fK gK; apply/setP=> y; rewrite inE. by apply/imsetP/idP=> [[x Ax ->] | Agy]; last exists (g y); rewrite ?(fK, gK). Qed. Lemma can2_imset_pre : cancel f g -> cancel g f -> f @: D = g @^-1: D. Proof. by move=> fK gK; apply: can2_in_imset_pre; apply: in1W. Qed. End CardFunImage. Arguments imset_injP {aT rT f D}. Lemma on_card_preimset (aT rT : finType) (f : aT -> rT) (R : {pred rT}) : {on R, bijective f} -> #|f @^-1: R| = #|R|. Proof. case=> g fK gK; rewrite -(can2_in_imset_pre gK) // card_in_imset //. exact: can_in_inj gK. Qed. Lemma can_imset_pre (T : finType) f g (A : {set T}) : cancel f g -> f @: A = g @^-1: A :> {set T}. Proof. move=> fK; apply: can2_imset_pre => // x. suffices fx: x \in codom f by rewrite -(f_iinv fx) fK. exact/(subset_cardP (card_codom (can_inj fK)))/subsetP. Qed. Lemma imset_id (T : finType) (A : {set T}) : [set x | x in A] = A. Proof. by apply/setP=> x; rewrite (@can_imset_pre _ _ id) ?inE. Qed. Lemma card_preimset (T : finType) (f : T -> T) (A : {set T}) : injective f -> #|f @^-1: A| = #|A|. Proof. move=> injf; apply: on_card_preimset; apply: onW_bij. have ontof: _ \in codom f by apply/(subset_cardP (card_codom injf))/subsetP. by exists (fun x => iinv (ontof x)) => x; rewrite (f_iinv, iinv_f). Qed. Lemma card_powerset (T : finType) (A : {set T}) : #|powerset A| = 2 ^ #|A|. Proof. rewrite -card_bool -(card_pffun_on false) -(card_imset _ val_inj). apply: eq_card => f; pose sf := false.-support f; pose D := finset sf. have sDA: (D \subset A) = (sf \subset A) by apply: eq_subset; apply: in_set. have eq_sf x : sf x = f x by rewrite /= negb_eqb addbF. have valD: val D = f by rewrite /D unlock; apply/ffunP=> x; rewrite ffunE eq_sf. apply/imsetP/pffun_onP=> [[B] | [sBA _]]; last by exists D; rewrite // inE ?sDA. by rewrite inE -sDA -valD => sBA /val_inj->. Qed. Section FunImageComp. Variables T T' U : finType. Lemma imset_comp (f : T' -> U) (g : T -> T') (H : {pred T}) : (f \o g) @: H = f @: (g @: H). Proof. apply/setP/subset_eqP/andP. split; apply/subsetP=> _ /imsetP[x0 Hx0 ->]; apply/imsetP. by exists (g x0); first apply: imset_f. by move/imsetP: Hx0 => [x1 Hx1 ->]; exists x1. Qed. End FunImageComp. Notation "\bigcup_ ( i <- r | P ) F" := (\big[@setU _/set0]_(i <- r | P) F%SET) : set_scope. Notation "\bigcup_ ( i <- r ) F" := (\big[@setU _/set0]_(i <- r) F%SET) : set_scope. Notation "\bigcup_ ( m <= i < n | P ) F" := (\big[@setU _/set0]_(m <= i < n | P%B) F%SET) : set_scope. Notation "\bigcup_ ( m <= i < n ) F" := (\big[@setU _/set0]_(m <= i < n) F%SET) : set_scope. Notation "\bigcup_ ( i | P ) F" := (\big[@setU _/set0]_(i | P%B) F%SET) : set_scope. Notation "\bigcup_ i F" := (\big[@setU _/set0]_i F%SET) : set_scope. Notation "\bigcup_ ( i : t | P ) F" := (\big[@setU _/set0]_(i : t | P%B) F%SET) (only parsing): set_scope. Notation "\bigcup_ ( i : t ) F" := (\big[@setU _/set0]_(i : t) F%SET) (only parsing) : set_scope. Notation "\bigcup_ ( i < n | P ) F" := (\big[@setU _/set0]_(i < n | P%B) F%SET) : set_scope. Notation "\bigcup_ ( i < n ) F" := (\big[@setU _/set0]_ (i < n) F%SET) : set_scope. Notation "\bigcup_ ( i 'in' A | P ) F" := (\big[@setU _/set0]_(i in A | P%B) F%SET) : set_scope. Notation "\bigcup_ ( i 'in' A ) F" := (\big[@setU _/set0]_(i in A) F%SET) : set_scope. Notation "\bigcap_ ( i <- r | P ) F" := (\big[@setI _/setT]_(i <- r | P%B) F%SET) : set_scope. Notation "\bigcap_ ( i <- r ) F" := (\big[@setI _/setT]_(i <- r) F%SET) : set_scope. Notation "\bigcap_ ( m <= i < n | P ) F" := (\big[@setI _/setT]_(m <= i < n | P%B) F%SET) : set_scope. Notation "\bigcap_ ( m <= i < n ) F" := (\big[@setI _/setT]_(m <= i < n) F%SET) : set_scope. Notation "\bigcap_ ( i | P ) F" := (\big[@setI _/setT]_(i | P%B) F%SET) : set_scope. Notation "\bigcap_ i F" := (\big[@setI _/setT]_i F%SET) : set_scope. Notation "\bigcap_ ( i : t | P ) F" := (\big[@setI _/setT]_(i : t | P%B) F%SET) (only parsing): set_scope. Notation "\bigcap_ ( i : t ) F" := (\big[@setI _/setT]_(i : t) F%SET) (only parsing) : set_scope. Notation "\bigcap_ ( i < n | P ) F" := (\big[@setI _/setT]_(i < n | P%B) F%SET) : set_scope. Notation "\bigcap_ ( i < n ) F" := (\big[@setI _/setT]_(i < n) F%SET) : set_scope. Notation "\bigcap_ ( i 'in' A | P ) F" := (\big[@setI _/setT]_(i in A | P%B) F%SET) : set_scope. Notation "\bigcap_ ( i 'in' A ) F" := (\big[@setI _/setT]_(i in A) F%SET) : set_scope. Section BigSetOps. Variables T I : finType. Implicit Types (U : {pred T}) (P : pred I) (A B : {set I}) (F : I -> {set T}). (* It is very hard to use this lemma, because the unification fails to *) (* defer the F j pattern (even though it's a Miller pattern!). *) Lemma bigcup_sup j P F : P j -> F j \subset \bigcup_(i | P i) F i. Proof. by move=> Pj; rewrite (bigD1 j) //= subsetUl. Qed. Lemma bigcup_max j U P F : P j -> U \subset F j -> U \subset \bigcup_(i | P i) F i. Proof. by move=> Pj sUF; apply: subset_trans (bigcup_sup _ Pj). Qed. Lemma bigcupP x P F : reflect (exists2 i, P i & x \in F i) (x \in \bigcup_(i | P i) F i). Proof. apply: (iffP idP) => [|[i Pi]]; last first. by apply: subsetP x; apply: bigcup_sup. by elim/big_rec: _ => [|i _ Pi _ /setUP[|//]]; [rewrite inE | exists i]. Qed. Lemma bigcupsP U P F : reflect (forall i, P i -> F i \subset U) (\bigcup_(i | P i) F i \subset U). Proof. apply: (iffP idP) => [sFU i Pi| sFU]. by apply: subset_trans sFU; apply: bigcup_sup. by apply/subsetP=> x /bigcupP[i Pi]; apply: (subsetP (sFU i Pi)). Qed. Lemma bigcup0P P F : reflect (forall i, P i -> F i = set0) (\bigcup_(i | P i) F i == set0). Proof. rewrite -subset0; apply: (iffP (bigcupsP _ _ _)) => sub0 i /sub0; last by move->. by rewrite subset0 => /eqP. Qed. Lemma bigcup_disjointP U P F : reflect (forall i : I, P i -> [disjoint U & F i]) [disjoint U & \bigcup_(i | P i) F i]. Proof. apply: (iffP idP) => [dUF i Pp|dUF]. by apply: disjointWr dUF; apply: bigcup_sup. rewrite disjoint_sym disjoint_subset. by apply/bigcupsP=> i /dUF; rewrite disjoint_sym disjoint_subset. Qed. Lemma bigcup_disjoint U P F : (forall i, P i -> [disjoint U & F i]) -> [disjoint U & \bigcup_(i | P i) F i]. Proof. by move/bigcup_disjointP. Qed. Lemma bigcup_setU A B F : \bigcup_(i in A :|: B) F i = (\bigcup_(i in A) F i) :|: (\bigcup_ (i in B) F i). Proof. apply/setP=> x; apply/bigcupP/setUP=> [[i] | ]. by case/setUP; [left | right]; apply/bigcupP; exists i. by case=> /bigcupP[i Pi]; exists i; rewrite // inE Pi ?orbT. Qed. Lemma bigcup_seq r F : \bigcup_(i <- r) F i = \bigcup_(i in r) F i. Proof. elim: r => [|i r IHr]; first by rewrite big_nil big_pred0. rewrite big_cons {}IHr; case r_i: (i \in r). rewrite (setUidPr _) ?bigcup_sup //. by apply: eq_bigl => j /[!inE]; case: eqP => // ->. rewrite (bigD1 i (mem_head i r)) /=; congr (_ :|: _). by apply: eq_bigl => j /=; rewrite andbC; case: eqP => // ->. Qed. (* Unlike its setU counterpart, this lemma is useable. *) Lemma bigcap_inf j P F : P j -> \bigcap_(i | P i) F i \subset F j. Proof. by move=> Pj; rewrite (bigD1 j) //= subsetIl. Qed. Lemma bigcap_min j U P F : P j -> F j \subset U -> \bigcap_(i | P i) F i \subset U. Proof. by move=> Pj; apply: subset_trans (bigcap_inf _ Pj). Qed. Lemma bigcapsP U P F : reflect (forall i, P i -> U \subset F i) (U \subset \bigcap_(i | P i) F i). Proof. apply: (iffP idP) => [sUF i Pi | sUF]. by apply: subset_trans sUF _; apply: bigcap_inf. elim/big_rec: _ => [|i V Pi sUV]; apply/subsetP=> x Ux; rewrite inE //. by rewrite !(subsetP _ x Ux) ?sUF. Qed. Lemma bigcapP x P F : reflect (forall i, P i -> x \in F i) (x \in \bigcap_(i | P i) F i). Proof. rewrite -sub1set. by apply: (iffP (bigcapsP _ _ _)) => Fx i /Fx; rewrite sub1set. Qed. Lemma setC_bigcup J r (P : pred J) (F : J -> {set T}) : ~: (\bigcup_(j <- r | P j) F j) = \bigcap_(j <- r | P j) ~: F j. Proof. by apply: big_morph => [A B|]; rewrite ?setC0 ?setCU. Qed. Lemma setC_bigcap J r (P : pred J) (F : J -> {set T}) : ~: (\bigcap_(j <- r | P j) F j) = \bigcup_(j <- r | P j) ~: F j. Proof. by apply: big_morph => [A B|]; rewrite ?setCT ?setCI. Qed. Lemma bigcap_setU A B F : (\bigcap_(i in A :|: B) F i) = (\bigcap_(i in A) F i) :&: (\bigcap_(i in B) F i). Proof. by apply: setC_inj; rewrite setCI !setC_bigcap bigcup_setU. Qed. Lemma bigcap_seq r F : \bigcap_(i <- r) F i = \bigcap_(i in r) F i. Proof. by apply: setC_inj; rewrite !setC_bigcap bigcup_seq. Qed. End BigSetOps. Arguments bigcup_sup [T I] j [P F]. Arguments bigcup_max [T I] j [U P F]. Arguments bigcupP {T I x P F}. Arguments bigcupsP {T I U P F}. Arguments bigcup_disjointP {T I U P F}. Arguments bigcap_inf [T I] j [P F]. Arguments bigcap_min [T I] j [U P F]. Arguments bigcapP {T I x P F}. Arguments bigcapsP {T I U P F}. Section ImsetCurry. Variables (aT1 aT2 rT : finType) (f : aT1 -> aT2 -> rT). Section Curry. Variables (A1 : {set aT1}) (A2 : {set aT2}). Variables (D1 : {pred aT1}) (D2 : {pred aT2}). Lemma curry_imset2X : f @2: (A1, A2) = uncurry f @: (setX A1 A2). Proof. rewrite [@imset]unlock unlock; apply/setP=> x; rewrite !in_set; congr (x \in _). by apply: eq_image => u //=; rewrite !inE. Qed. Lemma curry_imset2l : f @2: (D1, D2) = \bigcup_(x1 in D1) f x1 @: D2. Proof. apply/setP=> y; apply/imset2P/bigcupP => [[x1 x2 Dx1 Dx2 ->{y}] | [x1 Dx1]]. by exists x1; rewrite // imset_f. by case/imsetP=> x2 Dx2 ->{y}; exists x1 x2. Qed. Lemma curry_imset2r : f @2: (D1, D2) = \bigcup_(x2 in D2) f^~ x2 @: D1. Proof. apply/setP=> y; apply/imset2P/bigcupP => [[x1 x2 Dx1 Dx2 ->{y}] | [x2 Dx2]]. by exists x2; rewrite // (imset_f (f^~ x2)). by case/imsetP=> x1 Dx1 ->{y}; exists x1 x2. Qed. End Curry. Lemma imset2Ul (A B : {set aT1}) (C : {set aT2}) : f @2: (A :|: B, C) = f @2: (A, C) :|: f @2: (B, C). Proof. by rewrite !curry_imset2l bigcup_setU. Qed. Lemma imset2Ur (A : {set aT1}) (B C : {set aT2}) : f @2: (A, B :|: C) = f @2: (A, B) :|: f @2: (A, C). Proof. by rewrite !curry_imset2r bigcup_setU. Qed. End ImsetCurry. Section Partitions. Variables T I : finType. Implicit Types (x y z : T) (A B D X : {set T}) (P Q : {set {set T}}). Implicit Types (J : pred I) (F : I -> {set T}). Definition cover P := \bigcup_(B in P) B. Definition pblock P x := odflt set0 (pick [pred B in P | x \in B]). Definition trivIset P := \sum_(B in P) #|B| == #|cover P|. Definition partition P D := [&& cover P == D, trivIset P & set0 \notin P]. Definition is_transversal X P D := [&& partition P D, X \subset D & [forall B in P, #|X :&: B| == 1]]. Definition transversal P D := [set odflt x [pick y in pblock P x] | x in D]. Definition transversal_repr x0 X B := odflt x0 [pick x in X :&: B]. Lemma leq_card_setU A B : #|A :|: B| <= #|A| + #|B| ?= iff [disjoint A & B]. Proof. rewrite -(addn0 #|_|) -setI_eq0 -cards_eq0 -cardsUI eq_sym. by rewrite (mono_leqif (leq_add2l _)). Qed. Lemma leq_card_cover P : #|cover P| <= \sum_(A in P) #|A| ?= iff trivIset P. Proof. split; last exact: eq_sym. rewrite /cover; elim/big_rec2: _ => [|A n U _ leUn]; first by rewrite cards0. by rewrite (leq_trans (leq_card_setU A U).1) ?leq_add2l. Qed. Lemma imset_cover (T' : finType) P (f : T -> T') : [set f x | x in cover P] = \bigcup_(i in P) [set f x | x in i]. Proof. apply/setP=> y; apply/imsetP/bigcupP => [|[A AP /imsetP[x xA ->]]]. by move=> [x /bigcupP[A AP xA] ->]; exists A => //; rewrite imset_f. by exists x => //; apply/bigcupP; exists A. Qed. Lemma cover1 A : cover [set A] = A. Proof. by rewrite /cover big_set1. Qed. Lemma trivIset1 A : trivIset [set A]. Proof. by rewrite /trivIset cover1 big_set1. Qed. Lemma trivIsetP P : reflect {in P &, forall A B, A != B -> [disjoint A & B]} (trivIset P). Proof. rewrite -[P]set_enum; elim: {P}(enum _) (enum_uniq P) => [_ | A e IHe] /=. by rewrite /trivIset /cover !big_set0 cards0; left=> A; rewrite inE. case/andP; rewrite set_cons -(in_set (fun B => B \in e)) => PA {}/IHe. move: {e}[set x in e] PA => P PA IHP. rewrite /trivIset /cover !big_setU1 //= eq_sym. have:= leq_card_cover P; rewrite -(mono_leqif (leq_add2l #|A|)). move/(leqif_trans (leq_card_setU _ _))->; rewrite disjoints_subset setC_bigcup. case: bigcapsP => [disjA | meetA]; last first. right=> [tI]; case: meetA => B PB; rewrite -disjoints_subset. by rewrite tI ?setU11 ?setU1r //; apply: contraNneq PA => ->. apply: (iffP IHP) => [] tI B C PB PC; last by apply: tI; apply: setU1r. by case/setU1P: PC PB => [->|PC] /setU1P[->|PB]; try by [apply: tI | case/eqP]; first rewrite disjoint_sym; rewrite disjoints_subset disjA. Qed. Lemma trivIsetS P Q : P \subset Q -> trivIset Q -> trivIset P. Proof. by move/subsetP/sub_in2=> sPQ /trivIsetP/sPQ/trivIsetP. Qed. Lemma trivIsetD P Q : trivIset P -> trivIset (P :\: Q). Proof. move/trivIsetP => tP; apply/trivIsetP => A B /setDP[TA _] /setDP[TB _]; exact: tP. Qed. Lemma trivIsetU P Q : trivIset Q -> trivIset P -> [disjoint cover Q & cover P] -> trivIset (Q :|: P). Proof. move => /trivIsetP tQ /trivIsetP tP dQP; apply/trivIsetP => A B. move => /setUP[?|?] /setUP[?|?]; first [exact:tQ|exact:tP|move => _]. by apply: disjointW dQP; rewrite bigcup_sup. by rewrite disjoint_sym; apply: disjointW dQP; rewrite bigcup_sup. Qed. Lemma coverD1 P B : trivIset P -> B \in P -> cover (P :\ B) = cover P :\: B. Proof. move/trivIsetP => tP SP; apply/setP => x; rewrite inE. apply/bigcupP/idP => [[A /setD1P [ADS AP] xA]|/andP[xNS /bigcupP[A AP xA]]]. by rewrite (disjointFr (tP _ _ _ _ ADS)) //=; apply/bigcupP; exists A. by exists A; rewrite // !inE AP andbT; apply: contraNneq xNS => <-. Qed. Lemma trivIsetI P D : trivIset P -> trivIset (P ::&: D). Proof. by apply: trivIsetS; rewrite -setI_powerset subsetIl. Qed. Lemma cover_setI P D : cover (P ::&: D) \subset cover P :&: D. Proof. by apply/bigcupsP=> A /setIdP[PA sAD]; rewrite subsetI sAD andbT (bigcup_max A). Qed. Lemma mem_pblock P x : (x \in pblock P x) = (x \in cover P). Proof. rewrite /pblock; apply/esym/bigcupP. case: pickP => /= [A /andP[PA Ax]| noA]; first by rewrite Ax; exists A. by rewrite inE => [[A PA Ax]]; case/andP: (noA A). Qed. Lemma pblock_mem P x : x \in cover P -> pblock P x \in P. Proof. by rewrite -mem_pblock /pblock; case: pickP => [A /andP[]| _] //=; rewrite inE. Qed. Lemma def_pblock P B x : trivIset P -> B \in P -> x \in B -> pblock P x = B. Proof. move/trivIsetP=> tiP PB Bx; have Px: x \in cover P by apply/bigcupP; exists B. apply: (contraNeq (tiP _ _ _ PB)); first by rewrite pblock_mem. by apply/pred0Pn; exists x; rewrite /= mem_pblock Px. Qed. Lemma same_pblock P x y : trivIset P -> x \in pblock P y -> pblock P x = pblock P y. Proof. rewrite {1 3}/pblock => tI; case: pickP => [A|]; last by rewrite inE. by case/andP=> PA _{y} /= Ax; apply: def_pblock. Qed. Lemma eq_pblock P x y : trivIset P -> x \in cover P -> (pblock P x == pblock P y) = (y \in pblock P x). Proof. move=> tiP Px; apply/eqP/idP=> [eq_xy | /same_pblock-> //]. move: Px; rewrite -mem_pblock eq_xy /pblock. by case: pickP => [B /andP[] // | _] /[1!inE]. Qed. Lemma trivIsetU1 A P : {in P, forall B, [disjoint A & B]} -> trivIset P -> set0 \notin P -> trivIset (A |: P) /\ A \notin P. Proof. move=> tiAP tiP notPset0; split; last first. apply: contra notPset0 => P_A. by have:= tiAP A P_A; rewrite -setI_eq0 setIid => /eqP <-. apply/trivIsetP=> B1 B2 /setU1P[->|PB1] /setU1P[->|PB2]; by [apply: (trivIsetP _ tiP) | rewrite ?eqxx // ?(tiAP, disjoint_sym)]. Qed. Lemma cover_imset J F : cover (F @: J) = \bigcup_(i in J) F i. Proof. apply/setP=> x. apply/bigcupP/bigcupP=> [[_ /imsetP[i Ji ->]] | [i]]; first by exists i. by exists (F i); first apply: imset_f. Qed. Lemma trivIimset J F (P := F @: J) : {in J &, forall i j, j != i -> [disjoint F i & F j]} -> set0 \notin P -> trivIset P /\ {in J &, injective F}. Proof. move=> tiF notPset0; split=> [|i j Ji Jj /= eqFij]. apply/trivIsetP=> _ _ /imsetP[i Ji ->] /imsetP[j Jj ->] neqFij. by rewrite tiF // (contraNneq _ neqFij) // => ->. apply: contraNeq notPset0 => neq_ij; apply/imsetP; exists i => //; apply/eqP. by rewrite eq_sym -[F i]setIid setI_eq0 {1}eqFij tiF. Qed. Lemma cover_partition P D : partition P D -> cover P = D. Proof. by case/and3P=> /eqP. Qed. Lemma partition0 P D : partition P D -> set0 \in P = false. Proof. case/and3P => _ _. by apply: contraNF. Qed. Lemma partition_neq0 P D B : partition P D -> B \in P -> B != set0. Proof. by move=> partP; apply: contraTneq => ->; rewrite (partition0 partP). Qed. Lemma partition_trivIset P D : partition P D -> trivIset P. Proof. by case/and3P. Qed. Lemma partitionS P D B : partition P D -> B \in P -> B \subset D. Proof. by move=> partP BP; rewrite -(cover_partition partP); apply: bigcup_max BP _. Qed. Lemma partitionD1 P D B : partition P D -> B \in P -> partition (P :\ B) (D :\: B). Proof. case/and3P => /eqP covP trivP set0P SP. by rewrite /partition inE (negbTE set0P) trivIsetD ?coverD1 -?covP ?eqxx ?andbF. Qed. Lemma partitionU1 P D B : partition P D -> B != set0 -> [disjoint B & D] -> partition (B |: P) (B :|: D). Proof. case/and3P => /eqP covP trivP set0P BD0 disSD. rewrite /partition !inE (negbTE set0P) orbF [_ == B]eq_sym BD0 andbT. rewrite /cover bigcup_setU /= big_set1 -covP eqxx /=. by move: disSD; rewrite -covP=> /bigcup_disjointP/trivIsetU1 => -[]. Qed. Lemma partition_set0 P : partition P set0 = (P == set0). Proof. apply/and3P/eqP => [[/bigcup0P covP _ ]|->]; last first. by rewrite /partition inE /trivIset/cover !big_set0 cards0 !eqxx. by apply: contraNeq => /set0Pn[B BP]; rewrite -(covP B BP). Qed. Lemma card_partition P D : partition P D -> #|D| = \sum_(A in P) #|A|. Proof. by case/and3P=> /eqP <- /eqnP. Qed. Lemma card_uniform_partition n P D : {in P, forall A, #|A| = n} -> partition P D -> #|D| = #|P| * n. Proof. by move=> uniP /card_partition->; rewrite -sum_nat_const; apply: eq_bigr. Qed. Lemma partition_pigeonhole P D A : partition P D -> #|P| <= #|A| -> A \subset D -> {in P, forall B, #|A :&: B| <= 1} -> {in P, forall B, A :&: B != set0}. Proof. move=> partP card_A_P /subsetP subAD sub1; apply/forall_inP. apply: contraTT card_A_P => /forall_inPn [B BP]; rewrite negbK => AB0. rewrite -!ltnNge -(setD1K BP) cardsU1 !inE eqxx /= add1n ltnS. have [tP covP] := (partition_trivIset partP,cover_partition partP). have APx x : x \in A -> x \in pblock P x by rewrite mem_pblock covP; apply: subAD. have inj_f : {in A &, injective (pblock P)}. move=> x y xA yA /eqP; rewrite eq_pblock ?covP ?subAD // => Pxy. apply: (@card_le1_eqP _ (A :&: pblock P x)); rewrite ?inE ?Pxy ?APx ?andbT //. by apply: sub1; rewrite pblock_mem ?covP ?subAD. rewrite -(card_in_imset inj_f); apply: subset_leq_card. apply/subsetP => ? /imsetP[x xA ->]. rewrite !inE pblock_mem ?covP ?subAD ?andbT //. by apply: contraTneq AB0 => <-; apply/set0Pn; exists x; rewrite inE APx ?andbT. Qed. Section BigOps. Variables (R : Type) (idx : R) (op : Monoid.com_law idx). Let rhs_cond P K E := \big[op/idx]_(A in P) \big[op/idx]_(x in A | K x) E x. Let rhs P E := \big[op/idx]_(A in P) \big[op/idx]_(x in A) E x. Lemma big_trivIset_cond P (K : pred T) (E : T -> R) : trivIset P -> \big[op/idx]_(x in cover P | K x) E x = rhs_cond P K E. Proof. move=> tiP; rewrite (partition_big (pblock P) [in P]) -/op => /= [|x]. apply: eq_bigr => A PA; apply: eq_bigl => x; rewrite andbAC; congr (_ && _). rewrite -mem_pblock; apply/andP/idP=> [[Px /eqP <- //] | Ax]. by rewrite (def_pblock tiP PA Ax). by case/andP=> Px _; apply: pblock_mem. Qed. Lemma big_trivIset P (E : T -> R) : trivIset P -> \big[op/idx]_(x in cover P) E x = rhs P E. Proof. have biginT := eq_bigl _ _ (fun _ => andbT _) => tiP. by rewrite -biginT big_trivIset_cond //; apply: eq_bigr => A _; apply: biginT. Qed. Lemma set_partition_big_cond P D (K : pred T) (E : T -> R) : partition P D -> \big[op/idx]_(x in D | K x) E x = rhs_cond P K E. Proof. by case/and3P=> /eqP <- tI_P _; apply: big_trivIset_cond. Qed. Lemma set_partition_big P D (E : T -> R) : partition P D -> \big[op/idx]_(x in D) E x = rhs P E. Proof. by case/and3P=> /eqP <- tI_P _; apply: big_trivIset. Qed. Lemma partition_disjoint_bigcup (F : I -> {set T}) E : (forall i j, i != j -> [disjoint F i & F j]) -> \big[op/idx]_(x in \bigcup_i F i) E x = \big[op/idx]_i \big[op/idx]_(x in F i) E x. Proof. move=> disjF; pose P := [set F i | i in I & F i != set0]. have trivP: trivIset P. apply/trivIsetP=> _ _ /imsetP[i _ ->] /imsetP[j _ ->] neqFij. by apply: disjF; apply: contraNneq neqFij => ->. have ->: \bigcup_i F i = cover P. apply/esym; rewrite cover_imset big_mkcond; apply: eq_bigr => i _. by rewrite inE; case: eqP. rewrite big_trivIset // /rhs big_imset => [|i j _ /setIdP[_ notFj0] eqFij]. rewrite big_mkcond; apply: eq_bigr => i _; rewrite inE. by case: eqP => //= ->; rewrite big_set0. by apply: contraNeq (disjF _ _) _; rewrite -setI_eq0 eqFij setIid. Qed. End BigOps. Section Equivalence. Variables (R : rel T) (D : {set T}). Let Px x := [set y in D | R x y]. Definition equivalence_partition := [set Px x | x in D]. Local Notation P := equivalence_partition. Hypothesis eqiR : {in D & &, equivalence_rel R}. Let Pxx x : x \in D -> x \in Px x. Proof. by move=> Dx; rewrite !inE Dx (eqiR Dx Dx). Qed. Let PPx x : x \in D -> Px x \in P := fun Dx => imset_f _ Dx. Lemma equivalence_partitionP : partition P D. Proof. have defD: cover P == D. rewrite eqEsubset; apply/andP; split. by apply/bigcupsP=> _ /imsetP[x Dx ->]; rewrite /Px setIdE subsetIl. by apply/subsetP=> x Dx; apply/bigcupP; exists (Px x); rewrite (Pxx, PPx). have tiP: trivIset P. apply/trivIsetP=> _ _ /imsetP[x Dx ->] /imsetP[y Dy ->]; apply: contraR. case/pred0Pn=> z /andP[] /[!inE] /andP[Dz Rxz] /andP[_ Ryz]. apply/eqP/setP=> t /[!inE]; apply: andb_id2l => Dt. by rewrite (eqiR Dx Dz Dt) // (eqiR Dy Dz Dt). rewrite /partition tiP defD /=. by apply/imsetP=> [[x /Pxx Px_x Px0]]; rewrite -Px0 inE in Px_x. Qed. Lemma pblock_equivalence_partition : {in D &, forall x y, (y \in pblock P x) = R x y}. Proof. have [_ tiP _] := and3P equivalence_partitionP. by move=> x y Dx Dy; rewrite /= (def_pblock tiP (PPx Dx) (Pxx Dx)) inE Dy. Qed. End Equivalence. Lemma pblock_equivalence P D : partition P D -> {in D & &, equivalence_rel (fun x y => y \in pblock P x)}. Proof. case/and3P=> /eqP <- tiP _ x y z Px Py Pz. by rewrite mem_pblock; split=> // /same_pblock->. Qed. Lemma equivalence_partition_pblock P D : partition P D -> equivalence_partition (fun x y => y \in pblock P x) D = P. Proof. case/and3P=> /eqP <-{D} tiP notP0; apply/setP=> B /=; set D := cover P. have defP x: x \in D -> [set y in D | y \in pblock P x] = pblock P x. by move=> Dx; apply/setIidPr; rewrite (bigcup_max (pblock P x)) ?pblock_mem. apply/imsetP/idP=> [[x Px ->{B}] | PB]; first by rewrite defP ?pblock_mem. have /set0Pn[x Bx]: B != set0 := memPn notP0 B PB. have Px: x \in cover P by apply/bigcupP; exists B. by exists x; rewrite // defP // (def_pblock tiP PB Bx). Qed. Section Preim. Variables (rT : eqType) (f : T -> rT). Definition preim_partition := equivalence_partition (fun x y => f x == f y). Lemma preim_partitionP D : partition (preim_partition D) D. Proof. by apply/equivalence_partitionP; split=> // /eqP->. Qed. End Preim. Lemma preim_partition_pblock P D : partition P D -> preim_partition (pblock P) D = P. Proof. move=> partP; have [/eqP defD tiP _] := and3P partP. rewrite -{2}(equivalence_partition_pblock partP); apply: eq_in_imset => x Dx. by apply/setP=> y; rewrite !inE eq_pblock ?defD. Qed. Lemma transversalP P D : partition P D -> is_transversal (transversal P D) P D. Proof. case/and3P=> /eqP <- tiP notP0; apply/and3P; split; first exact/and3P. apply/subsetP=> _ /imsetP[x Px ->]; case: pickP => //= y Pxy. by apply/bigcupP; exists (pblock P x); rewrite ?pblock_mem //. apply/forall_inP=> B PB; have /set0Pn[x Bx]: B != set0 := memPn notP0 B PB. apply/cards1P; exists (odflt x [pick y in pblock P x]); apply/esym/eqP. rewrite eqEsubset sub1set !inE -andbA; apply/andP; split. by apply/imset_f/bigcupP; exists B. rewrite (def_pblock tiP PB Bx); case def_y: _ / pickP => [y By | /(_ x)/idP//]. rewrite By /=; apply/subsetP=> _ /setIP[/imsetP[z Pz ->]]. case: {1}_ / pickP => [t zPt Bt | /(_ z)/idP[]]; last by rewrite mem_pblock. by rewrite -(same_pblock tiP zPt) (def_pblock tiP PB Bt) def_y inE. Qed. Section Transversals. Variables (X : {set T}) (P : {set {set T}}) (D : {set T}). Hypothesis trPX : is_transversal X P D. Lemma transversal_sub : X \subset D. Proof. by case/and3P: trPX. Qed. Let tiP : trivIset P. Proof. by case/andP: trPX => /and3P[]. Qed. Let sXP : {subset X <= cover P}. Proof. by case/and3P: trPX => /andP[/eqP-> _] /subsetP. Qed. Let trX : {in P, forall B, #|X :&: B| == 1}. Proof. by case/and3P: trPX => _ _ /forall_inP. Qed. Lemma setI_transversal_pblock x0 B : B \in P -> X :&: B = [set transversal_repr x0 X B]. Proof. by case/trX/cards1P=> x defXB; rewrite /transversal_repr defXB /pick enum_set1. Qed. Lemma repr_mem_pblock x0 B : B \in P -> transversal_repr x0 X B \in B. Proof. by move=> PB; rewrite -sub1set -setI_transversal_pblock ?subsetIr. Qed. Lemma repr_mem_transversal x0 B : B \in P -> transversal_repr x0 X B \in X. Proof. by move=> PB; rewrite -sub1set -setI_transversal_pblock ?subsetIl. Qed. Lemma transversal_reprK x0 : {in P, cancel (transversal_repr x0 X) (pblock P)}. Proof. by move=> B PB; rewrite /= (def_pblock tiP PB) ?repr_mem_pblock. Qed. Lemma pblockK x0 : {in X, cancel (pblock P) (transversal_repr x0 X)}. Proof. move=> x Xx; have /bigcupP[B PB Bx] := sXP Xx; rewrite (def_pblock tiP PB Bx). by apply/esym/set1P; rewrite -setI_transversal_pblock // inE Xx. Qed. Lemma pblock_inj : {in X &, injective (pblock P)}. Proof. by move=> x0; apply: (can_in_inj (pblockK x0)). Qed. Lemma pblock_transversal : pblock P @: X = P. Proof. apply/setP=> B; apply/imsetP/idP=> [[x Xx ->] | PB]. by rewrite pblock_mem ?sXP. have /cards1P[x0 _] := trX PB; set x := transversal_repr x0 X B. by exists x; rewrite ?transversal_reprK ?repr_mem_transversal. Qed. Lemma card_transversal : #|X| = #|P|. Proof. by rewrite -pblock_transversal card_in_imset //; apply: pblock_inj. Qed. Lemma im_transversal_repr x0 : transversal_repr x0 X @: P = X. Proof. rewrite -{2}[X]imset_id -pblock_transversal -imset_comp. by apply: eq_in_imset; apply: pblockK. Qed. End Transversals. End Partitions. Arguments trivIsetP {T P}. Arguments big_trivIset_cond [T R idx op] P [K E]. Arguments set_partition_big_cond [T R idx op] P [D K E]. Arguments big_trivIset [T R idx op] P [E]. Arguments set_partition_big [T R idx op] P [D E]. Prenex Implicits cover trivIset partition pblock. Lemma partition_partition (T : finType) (D : {set T}) P Q : partition P D -> partition Q P -> partition (cover @: Q) D /\ {in Q &, injective cover}. Proof. move=> /and3P[/eqP defG tiP notP0] /and3P[/eqP defP tiQ notQ0]. have sQP E: E \in Q -> {subset E <= P}. by move=> Q_E; apply/subsetP; rewrite -defP (bigcup_max E). rewrite /partition cover_imset -(big_trivIset _ tiQ) defP -defG eqxx /= andbC. have{} notQ0: set0 \notin cover @: Q. apply: contra notP0 => /imsetP[E Q_E E0]. have /set0Pn[/= A E_A] := memPn notQ0 E Q_E. congr (_ \in P): (sQP E Q_E A E_A). by apply/eqP; rewrite -subset0 E0 (bigcup_max A). rewrite notQ0; apply: trivIimset => // E F Q_E Q_F. apply: contraR => /pred0Pn[x /andP[/bigcupP[A E_A Ax] /bigcupP[B F_B Bx]]]. rewrite -(def_pblock tiQ Q_E E_A) -(def_pblock tiP _ Ax) ?(sQP E) //. by rewrite -(def_pblock tiQ Q_F F_B) -(def_pblock tiP _ Bx) ?(sQP F). Qed. Lemma indexed_partition (I T : finType) (J : {pred I}) (B : I -> {set T}) : let P := [set B i | i in J] in {in J &, forall i j : I, j != i -> [disjoint B i & B j]} -> (forall i : I, J i -> B i != set0) -> partition P (cover P) /\ {in J &, injective B}. Proof. move=> P disjB inhB; have s0NP : set0 \notin P. by apply/negP => /imsetP[x xI /eqP]; apply/negP; rewrite eq_sym inhB. by rewrite /partition eqxx s0NP andbT /=; apply: trivIimset. Qed. Section PartitionImage. Variables (T : finType) (P : {set {set T}}) (D : {set T}). Variables (T' : finType) (f : T -> T') (inj_f : injective f). Let fP := [set f @: (B : {set T}) | B in P]. Lemma imset_trivIset : trivIset fP = trivIset P. Proof. apply/trivIsetP/trivIsetP => [trivP A B AP BP|]. - rewrite -(imset_disjoint inj_f) -(inj_eq (imset_inj inj_f)). by apply: trivP; rewrite imset_f. - move=> trivP ? ? /imsetP[A AP ->] /imsetP[B BP ->]. by rewrite (inj_eq (imset_inj inj_f)) imset_disjoint //; apply: trivP. Qed. Lemma imset0mem : (set0 \in fP) = (set0 \in P). Proof. apply/imsetP/idP => [[A AP /esym/eqP]|P0]; last by exists set0; rewrite ?imset0. by rewrite imset_eq0 => /eqP<-. Qed. Lemma imset_partition : partition fP (f @: D) = partition P D. Proof. suff cov: (cover fP == f @:D) = (cover P == D). by rewrite /partition -imset_trivIset imset0mem cov. by rewrite /fP cover_imset -imset_cover (inj_eq (imset_inj inj_f)). Qed. End PartitionImage. (**********************************************************************) (* *) (* Maximum and minimum (sub)set with respect to a given pred *) (* *) (**********************************************************************) Section MaxSetMinSet. Variable T : finType. Notation sT := {set T}. Implicit Types A B C : sT. Implicit Type P : pred sT. Definition minset P A := [forall (B : sT | B \subset A), (B == A) == P B]. Lemma minset_eq P1 P2 A : P1 =1 P2 -> minset P1 A = minset P2 A. Proof. by move=> eP12; apply: eq_forallb => B; rewrite eP12. Qed. Lemma minsetP P A : reflect ((P A) /\ (forall B, P B -> B \subset A -> B = A)) (minset P A). Proof. apply: (iffP forallP) => [minA | [PA minA] B]. split; first by have:= minA A; rewrite subxx eqxx /= => /eqP. by move=> B PB sBA; have:= minA B; rewrite PB sBA /= eqb_id => /eqP. by apply/implyP=> sBA; apply/eqP; apply/eqP/idP=> [-> // | /minA]; apply. Qed. Arguments minsetP {P A}. Lemma minsetp P A : minset P A -> P A. Proof. by case/minsetP. Qed. Lemma minsetinf P A B : minset P A -> P B -> B \subset A -> B = A. Proof. by case/minsetP=> _; apply. Qed. Lemma ex_minset P : (exists A, P A) -> {A | minset P A}. Proof. move=> exP; pose pS n := [pred B | P B & #|B| == n]. pose p n := ~~ pred0b (pS n); have{exP}: exists n, p n. by case: exP => A PA; exists #|A|; apply/existsP; exists A; rewrite /= PA /=. case/ex_minnP=> n /pred0P; case: (pickP (pS n)) => // A /andP[PA] /eqP <-{n} _. move=> minA; exists A => //; apply/minsetP; split=> // B PB sBA; apply/eqP. by rewrite eqEcard sBA minA //; apply/pred0Pn; exists B; rewrite /= PB /=. Qed. Lemma minset_exists P C : P C -> {A | minset P A & A \subset C}. Proof. move=> PC; have{PC}: exists A, P A && (A \subset C) by exists C; rewrite PC /=. case/ex_minset=> A /minsetP[/andP[PA sAC] minA]; exists A => //; apply/minsetP. by split=> // B PB sBA; rewrite (minA B) // PB (subset_trans sBA). Qed. (* The 'locked_with' allows Coq to find the value of P by unification. *) Fact maxset_key : unit. Proof. by []. Qed. Definition maxset P A := minset (fun B => locked_with maxset_key P (~: B)) (~: A). Lemma maxset_eq P1 P2 A : P1 =1 P2 -> maxset P1 A = maxset P2 A. Proof. by move=> eP12; apply: minset_eq => x /=; rewrite !unlock_with eP12. Qed. Lemma maxminset P A : maxset P A = minset [pred B | P (~: B)] (~: A). Proof. by rewrite /maxset unlock. Qed. Lemma minmaxset P A : minset P A = maxset [pred B | P (~: B)] (~: A). Proof. by rewrite /maxset unlock setCK; apply: minset_eq => B /=; rewrite setCK. Qed. Lemma maxsetP P A : reflect ((P A) /\ (forall B, P B -> A \subset B -> B = A)) (maxset P A). Proof. apply: (iffP minsetP); rewrite ?setCK unlock_with => [] [PA minA]. by split=> // B PB sAB; rewrite -[B]setCK [~: B]minA (setCK, setCS). by split=> // B PB' sBA'; rewrite -(minA _ PB') -1?setCS setCK. Qed. Lemma maxsetp P A : maxset P A -> P A. Proof. by case/maxsetP. Qed. Lemma maxsetsup P A B : maxset P A -> P B -> A \subset B -> B = A. Proof. by case/maxsetP=> _; apply. Qed. Lemma ex_maxset P : (exists A, P A) -> {A | maxset P A}. Proof. move=> exP; have{exP}: exists A, P (~: A). by case: exP => A PA; exists (~: A); rewrite setCK. by case/ex_minset=> A minA; exists (~: A); rewrite /maxset unlock setCK. Qed. Lemma maxset_exists P C : P C -> {A : sT | maxset P A & C \subset A}. Proof. move=> PC; pose P' B := P (~: B); have: P' (~: C) by rewrite /P' setCK. case/minset_exists=> B; rewrite -[B]setCK setCS. by exists (~: B); rewrite // /maxset unlock. Qed. End MaxSetMinSet. Arguments setCK {T}. Arguments minsetP {T P A}. Arguments maxsetP {T P A}. Prenex Implicits minset maxset. Section SetFixpoint. Section Least. Variables (T : finType) (F : {set T} -> {set T}). Hypothesis (F_mono : {homo F : X Y / X \subset Y}). Let n := #|T|. Let iterF i := iter i F set0. Lemma subset_iterS i : iterF i \subset iterF i.+1. Proof. by elim: i => [| i IHi]; rewrite /= ?sub0set ?F_mono. Qed. Lemma subset_iter : {homo iterF : i j / i <= j >-> i \subset j}. Proof. by apply: homo_leq => //[? ? ?|]; [apply: subset_trans|apply: subset_iterS]. Qed. Definition fixset := iterF n. Lemma fixsetK : F fixset = fixset. Proof. suff /'exists_eqP[x /= e]: [exists k : 'I_n.+1, iterF k == iterF k.+1]. by rewrite /fixset -(subnK (leq_ord x)) /iterF iterD iter_fix. apply: contraT => /existsPn /(_ (Ordinal _)) /= neq_iter. suff iter_big k : k <= n.+1 -> k <= #|iter k F set0|. by have := iter_big _ (leqnn _); rewrite ltnNge max_card. elim: k => [|k IHk] k_lt //=; apply: (leq_ltn_trans (IHk (ltnW k_lt))). by rewrite proper_card// properEneq// subset_iterS neq_iter. Qed. Hint Resolve fixsetK : core. Lemma minset_fix : minset [pred X | F X == X] fixset. Proof. apply/minsetP; rewrite inE fixsetK eqxx; split=> // X /eqP FXeqX Xsubfix. apply/eqP; rewrite eqEsubset Xsubfix/=. suff: fixset \subset iter n F X by rewrite iter_fix. by rewrite /fixset; elim: n => //= [|m IHm]; rewrite ?sub0set ?F_mono. Qed. Lemma fixsetKn k : iter k F fixset = fixset. Proof. by rewrite iter_fix. Qed. Lemma iter_sub_fix k : iterF k \subset fixset. Proof. have [/subset_iter //|/ltnW/subnK<-] := leqP k n; by rewrite /iterF iterD fixsetKn. Qed. Lemma fix_order_proof x : x \in fixset -> exists n, x \in iterF n. Proof. by move=> x_fix; exists n. Qed. Definition fix_order (x : T) := if (x \in fixset) =P true isn't ReflectT x_fix then 0 else (ex_minn (fix_order_proof x_fix)). Lemma fix_order_le_max (x : T) : fix_order x <= n. Proof. rewrite /fix_order; case: eqP => //= x_in. by case: ex_minnP => //= ? ?; apply. Qed. Lemma in_iter_fix_orderE (x : T) : (x \in iterF (fix_order x)) = (x \in fixset). Proof. rewrite /fix_order; case: eqP => [x_in | /negP/negPf-> /[1!inE]//]. by case: ex_minnP => m ->; rewrite x_in. Qed. Lemma fix_order_gt0 (x : T) : (fix_order x > 0) = (x \in fixset). Proof. rewrite /fix_order; case: eqP => [x_in | /negP/negPf->//]. by rewrite x_in; case: ex_minnP => -[/[!inE] | m]. Qed. Lemma fix_order_eq0 (x : T) : (fix_order x == 0) = (x \notin fixset). Proof. by rewrite -fix_order_gt0 -ltnNge ltnS leqn0. Qed. Lemma in_iter_fixE (x : T) k : (x \in iterF k) = (0 < fix_order x <= k). Proof. rewrite /fix_order; case: eqP => //= [x_in|/negP xNin]; last first. by apply: contraNF xNin; apply/subsetP/iter_sub_fix. case: ex_minnP => -[/[!inE]//|m] xm mP. by apply/idP/idP=> [/mP//|lt_mk]; apply: subsetP xm; apply: subset_iter. Qed. Lemma in_iter (x : T) k : x \in fixset -> fix_order x <= k -> x \in iterF k. Proof. by move=> x_in xk; rewrite in_iter_fixE fix_order_gt0 x_in xk. Qed. Lemma notin_iter (x : T) k : k < fix_order x -> x \notin iterF k. Proof. by move=> k_le; rewrite in_iter_fixE negb_and orbC -ltnNge k_le. Qed. Lemma fix_order_small x k : x \in iterF k -> fix_order x <= k. Proof. by rewrite in_iter_fixE => /andP[]. Qed. Lemma fix_order_big x k : x \in fixset -> x \notin iterF k -> fix_order x > k. Proof. by move=> x_in; rewrite in_iter_fixE fix_order_gt0 x_in /= -ltnNge. Qed. Lemma le_fix_order (x y : T) : y \in iterF (fix_order x) -> fix_order y <= fix_order x. Proof. exact: fix_order_small. Qed. End Least. Section Greatest. Variables (T : finType) (F : {set T} -> {set T}). Hypothesis (F_mono : {homo F : X Y / X \subset Y}). Definition funsetC X := ~: (F (~: X)). Lemma funsetC_mono : {homo funsetC : X Y / X \subset Y}. Proof. by move=> *; rewrite subCset setCK F_mono// subCset setCK. Qed. Hint Resolve funsetC_mono : core. Definition cofixset := ~: fixset funsetC. Lemma cofixsetK : F cofixset = cofixset. Proof. by rewrite /cofixset -[in RHS]fixsetK ?setCK. Qed. Lemma maxset_cofix : maxset [pred X | F X == X] cofixset. Proof. rewrite maxminset setCK. rewrite (@minset_eq _ _ [pred X | funsetC X == X]) ?minset_fix//. by move=> X /=; rewrite (can2_eq setCK setCK). Qed. End Greatest. End SetFixpoint. Section FProd. Variables (I : finType) (T_ : I -> finType). Lemma card_fprod : #|fprod T_| = \prod_(i : I) #|T_ i|. Proof. rewrite card_sub (card_family (tagged_with T_)) foldrE big_image/=. apply: eq_bigr => i _/=; rewrite -card_sig; apply/esym. exact: bij_eq_card (tag_with_bij T_ i). Qed. Definition fprod_pick : 0 < #|fprod T_| -> forall i : I, T_ i. Proof. by rewrite card_fprod => /[swap] i /gt0_prodn/(_ i isT) /card_gt0P/sigW[]. Qed. Definition ftagged (T_gt0 : 0 < #|fprod T_|) (f : {ffun I -> {i : I & T_ i}}) (i : I) := @untag I T_ (T_ i) (fprod_pick T_gt0 i) i id (f i). Lemma ftaggedE t T_gt0 i : ftagged T_gt0 (fprod_fun t) i = t i. Proof. by rewrite /ftagged untagE ?tag_fprod_fun// => e; rewrite etaggedE. Qed. End FProd. Section BigTag. Variables (R : Type) (idx : R) (op : Monoid.com_law idx). Variables (I : finType) (T_ : I -> finType). Lemma big_tag_cond (Q_ : forall i, {pred T_ i}) (P_ : forall i : I, T_ i -> R) (i : I) : \big[op/idx]_(j in Q_ i) P_ i j = \big[op/idx]_(j in tagged_with T_ i | untag true (Q_ i) j) untag idx (P_ i) j. Proof. rewrite (big_sub_cond (tagged_with T_ i)). rewrite (reindex (tag_with i)); last exact/onW_bij/tag_with_bij. by apply: eq_big => [x|x Qix]; rewrite ?untagE. Qed. Lemma big_tag (P_ : forall i : I, T_ i -> R) (i : I) : \big[op/idx]_(j : T_ i) P_ i j = \big[op/idx]_(j in tagged_with T_ i) untag idx (P_ i) j. Proof. by rewrite big_tag_cond; under eq_bigl do rewrite untag_cst ?andbT. Qed. End BigTag. Arguments big_tag_cond [R idx op I T_] _ _ _. Arguments big_tag [R idx op I T_] _ _. Section BigFProd. Variables (R : Type) (zero one : R) (times : R -> R -> R). Variables (plus : Monoid.add_law zero times). Variables (I : finType) (T_ : I -> finType). Variables (P_ : forall i : I, {ffun T_ i -> R}). Let T := fprod T_. Lemma big_fprod_dep (Q : {pred {ffun I -> {i : I & (T_ i)}}}) : \big[plus/zero]_(t : T | Q (fprod_fun t)) \big[times/one]_(i : I) P_ i (t i) = \big[plus/zero]_(g in family (tagged_with T_) | Q g) \big[times/one]_(i : I) (untag zero (P_ i) (g i)). Proof. rewrite (reindex (@of_family_tagged_with _ T_)); last first. exact/onW_bij/of_family_tagged_with_bij. rewrite [in RHS]big_sub_cond; apply/esym/eq_bigr => -[/= f fP] Qf. apply: eq_bigr => i _; rewrite /fun_of_fprod/=. by case: (f i) ('forall_eqP _ _) => //= j t; case: _ /; rewrite untagE. Qed. Lemma big_fprod : \big[plus/zero]_(t : T) \big[times/one]_(i in I) P_ i (t i) = \big[plus/zero]_(g in family (tagged_with T_)) \big[times/one]_(i : I) (untag zero (P_ i) (g i)). Proof. by rewrite (big_fprod_dep predT) big_mkcondr. Qed. End BigFProd.
RingHom.lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Jireh Loreaux -/ import Mathlib.Algebra.Divisibility.Hom import Mathlib.Algebra.Ring.Hom.Defs import Mathlib.Data.Set.Insert /-! # Additional lemmas about homomorphisms of semirings and rings These lemmas were in `Mathlib/Algebra/Hom/Ring/Defs.lean` and have now been deprecated. -/ assert_not_exists RelIso Field open Function variable {α β : Type*} namespace RingHom section variable {_ : NonAssocSemiring α} {_ : NonAssocSemiring β} (f : α →+* β) /-- `f : α →+* β` has a trivial codomain iff its range is `{0}`. -/ @[deprecated "Use range_eq_singleton_iff and codomain_trivial_iff_range_trivial" (since := "2025-06-09")] theorem codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ Set.range f = {0} := f.codomain_trivial_iff_range_trivial.trans ⟨fun h => Set.ext fun y => ⟨fun ⟨x, hx⟩ => by simp [← hx, h x], fun hy => ⟨0, by simpa using hy.symm⟩⟩, fun h x => Set.mem_singleton_iff.mp (h ▸ Set.mem_range_self x)⟩ end section Semiring variable [Semiring α] [Semiring β] @[deprecated map_dvd (since := "2025-06-09")] protected theorem map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := map_dvd f end Semiring end RingHom
DeriveToExpr.lean
import Lean namespace DeriveToExprTests open Lean -- set_option trace.Elab.Deriving.toExpr true inductive MyMaybe (α : Type u) | none | some (x : α) deriving ToExpr run_cmd Elab.Command.liftTermElabM do guard <| "MyMaybe.some 2" == s!"{← Lean.PrettyPrinter.ppExpr <| toExpr (MyMaybe.some 2)}" run_cmd Elab.Command.liftTermElabM do Meta.check <| toExpr (MyMaybe.some 2) deriving instance ToExpr for ULift run_cmd Elab.Command.liftTermElabM do let e := toExpr (MyMaybe.none : MyMaybe (ULift.{1,0} Nat)) let ty := toTypeExpr (MyMaybe (ULift.{1,0} Nat)) Meta.check e Meta.check ty guard <| ← Meta.isDefEq (← Meta.inferType e) ty guard <| (← Meta.getLevel ty) == Level.zero.succ.succ run_cmd Elab.Command.liftTermElabM do Meta.check <| toExpr <| (MyMaybe.some (ULift.up 2) : MyMaybe (ULift.{1,0} Nat)) deriving instance ToExpr for List inductive Foo | l (x : List Foo) deriving ToExpr run_cmd Elab.Command.liftTermElabM <| Meta.check <| toExpr (Foo.l [Foo.l [], Foo.l [Foo.l []]]) /-- error: failed to synthesize ToExpr (Bool → Nat) Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command. -/ #guard_msgs in inductive Bar | func (x : Bool → Nat) deriving ToExpr def boolFunHelper (x y : α) (b : Bool) : α := if b then x else y instance {α : Type u} [ToExpr α] [ToLevel.{u+1}] : ToExpr (Bool → α) where toExpr g := mkApp3 (.const ``boolFunHelper [toLevel.{u+1}]) (toTypeExpr α) (toExpr <| g true) (toExpr <| g false) toTypeExpr := .forallE `x (.const ``Bool []) (toTypeExpr α) .default deriving instance ToExpr for Bar example : True := by run_tac do let f : Bool → Nat | false => 0 | true => 1 let e := toExpr <| Bar.func f Meta.check e guard <| ← Meta.isDefEq (← Meta.inferType e) (toTypeExpr Bar) trivial mutual inductive A | a deriving ToExpr inductive B | b deriving ToExpr end run_cmd Elab.Command.liftTermElabM do Meta.check <| toExpr A.a Meta.check <| toExpr B.b mutual inductive C | c (x : List D) deriving ToExpr inductive D | b (y : List C) deriving ToExpr end -- An incomplete `ToExpr` instance just to finish deriving `ToExpr` for `Expr`. instance : ToExpr MData where toExpr _ := mkConst ``MData.empty toTypeExpr := mkConst ``MData deriving instance ToExpr for FVarId deriving instance ToExpr for MVarId deriving instance ToExpr for LevelMVarId deriving instance ToExpr for Level deriving instance ToExpr for BinderInfo deriving instance ToExpr for Literal deriving instance ToExpr for Expr run_cmd Elab.Command.liftTermElabM do Meta.check <| toExpr <| toExpr [1,2,3] end DeriveToExprTests
finfield.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 fintype div tuple bigop prime finset fingroup. From mathcomp Require Import ssralg poly polydiv morphism action countalg. From mathcomp Require Import finalg zmodp cyclic center pgroup abelian matrix. From mathcomp Require Import mxpoly vector falgebra fieldext separable galois. From mathcomp Require ssrnum ssrint archimedean algC cyclotomic. (******************************************************************************) (* Additional constructions and results on finite fields *) (* *) (* FinFieldExtType L == a FinFieldType structure on the carrier of L, *) (* where L IS a fieldExtType F structure for an *) (* F that has a finFieldType structure. This *) (* does not take any existing finType structure *) (* on L; this should not be made canonical *) (* FinSplittingFieldType F L == a SplittingFieldType F structure on the *) (* carrier of L, where L IS a fieldExtType F for *) (* an F with a finFieldType structure; this *) (* should not be made canonical *) (* finvect_type vT == alias of vT : vecType R equipped with *) (* canonical instances for finType, finNzRing, *) (* etc structures (including FinFieldExtType *) (* above) for abstract vectType, falgType and *) (* fieldExtType over a finFieldType *) (* pPrimeCharType pcharRp == the carrier of a nzRingType R such that *) (* pcharRp : p \in [pchar R] holds. This type has*) (* canonical nzRingType, ..., fieldType *) (* structures compatible with those of R, as well*) (* as canonical lmodType 'F_p, ..., algType 'F_p *) (* structures, plus an falgType structure if R *) (* is a finUnitRingType and a splittingFieldType *) (* structure if R is a finFieldType *) (* FinSplittingFieldFor nz_p == sigma-pair whose sval is a splittingFieldType *) (* that is the splitting field for p : {poly F} *) (* over F : finFieldType, given nz_p : p != 0 *) (* PrimePowerField pr_p k_gt0 == sigma2-triple whose s2val is a finFieldType *) (* of characteristic p and order m = p ^ k, *) (* given pr_p : prime p and k_gt0 : k > 0 *) (* FinDomainFieldType domR == a finFieldType structure on a finUnitRingType *) (* R, given domR : GRing.IntegralDomain.axiom R. *) (* This is intended to be used inside proofs, *) (* where one cannot declare Canonical instances *) (* Otherwise one should construct explicitly the *) (* intermediate structures using the ssralg and *) (* finalg constructors, and finDomain_mulrC domR *) (* finDomain_fieldP domR to prove commutativity *) (* and field axioms (the former is Wedderburn's *) (* little theorem). *) (* FinDomainSplittingFieldType domR pcharRp == a splittingFieldType structure *) (* that repackages the two constructions above *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope GRing.Theory FinRing.Theory. Local Open Scope ring_scope. Section FinNzRing. Variable R : finNzRingType. Lemma finNzRing_nontrivial : [set: R] != 1%g. Proof. by apply/trivgPn; exists 1; rewrite ?inE ?oner_neq0. Qed. Lemma finNzRing_gt1 : 1 < #|R|. Proof. by rewrite -cardsT cardG_gt1 finNzRing_nontrivial. Qed. End FinNzRing. #[deprecated(since="mathcomp 2.4.0", note="Use finNzRing_nontrivial instead.")] Notation finRing_nontrivial := (finNzRing_nontrivial) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use finNzRing_gt1 instead.")] Notation finRing_gt1 := (finNzRing_gt1) (only parsing). Section FinField. Variable F : finFieldType. Lemma card_finField_unit : #|[set: {unit F}]| = #|F|.-1. Proof. by rewrite -(cardC1 0) cardsT card_sub; apply: eq_card => x; rewrite unitfE. Qed. Definition finField_unit x (nz_x : x != 0) := FinRing.unit F (etrans (unitfE x) nz_x). Lemma expf_card x : x ^+ #|F| = x :> F. Proof. rewrite -[RHS]mulr1 -(ltn_predK (finNzRing_gt1 F)) exprS. apply/eqP; rewrite -subr_eq0 -mulrBr mulf_eq0 subr_eq0 -implyNb -unitfE. apply/implyP=> Ux; rewrite -(val_unitX _ (Sub x _)) -val_unit1 val_eqE. by rewrite -order_dvdn -card_finField_unit order_dvdG ?inE. Qed. Lemma finField_genPoly : 'X^#|F| - 'X = \prod_x ('X - x%:P) :> {poly F}. Proof. set n := #|F|; set oppX := - 'X; set pF := LHS. have le_oppX_n: size oppX <= n by rewrite size_polyN size_polyX finNzRing_gt1. have: size pF = (size (enum F)).+1 by rewrite -cardE size_polyDl size_polyXn. move/all_roots_prod_XsubC->; last by rewrite uniq_rootsE enum_uniq. by rewrite big_enum lead_coefDl ?size_polyXn // lead_coefXn scale1r. by apply/allP=> x _; rewrite rootE !hornerE expf_card subrr. Qed. Lemma finPcharP : {p | prime p & p \in [pchar F]}. Proof. pose e := exponent [set: F]; have e_gt0: e > 0 by apply: exponent_gt0. have: e%:R == 0 :> F by rewrite -zmodXgE expg_exponent // inE. by case/natf0_pchar/sigW=> // p pcharFp; exists p; rewrite ?(pcharf_prime pcharFp). Qed. Lemma finField_is_abelem : is_abelem [set: F]. Proof. have [p pr_p pcharFp] := finPcharP. by apply/is_abelemP; exists p; last apply: fin_ring_pchar_abelem. Qed. Lemma card_finPcharP p n : #|F| = (p ^ n)%N -> prime p -> p \in [pchar F]. Proof. move=> oF pr_p; rewrite inE pr_p -order_dvdn. rewrite (abelem_order_p finField_is_abelem) ?inE ?oner_neq0 //=. have n_gt0: n > 0 by rewrite -(ltn_exp2l _ _ (prime_gt1 pr_p)) -oF finNzRing_gt1. by rewrite cardsT oF -(prednK n_gt0) pdiv_pfactor. Qed. End FinField. #[deprecated(since="mathcomp 2.4.0", note="Use finPcharP instead.")] Notation finCharP := (finPcharP) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use card_finPcharP instead.")] Notation card_finCharP := (card_finPcharP) (only parsing). Section CardVspace. Variables (F : finFieldType) (T : finType). Section Vector. Variable cvT : Vector F T. Let vT := Vector.Pack cvT. Lemma card_vspace (V : {vspace vT}) : #|V| = (#|F| ^ \dim V)%N. Proof. set n := \dim V; pose V2rV v := \row_i coord (vbasis V) i v. pose rV2V (rv : 'rV_n) := \sum_i rv 0 i *: (vbasis V)`_i. have rV2V_K: cancel rV2V V2rV. have freeV: free (vbasis V) := basis_free (vbasisP V). by move=> rv; apply/rowP=> i; rewrite mxE coord_sum_free. rewrite -[n]mul1n -card_mx -(card_imset _ (can_inj rV2V_K)). apply: eq_card => v; apply/idP/imsetP=> [/coord_vbasis-> | [rv _ ->]]. by exists (V2rV v) => //; apply: eq_bigr => i _; rewrite mxE. by apply: (@rpred_sum vT) => i _; rewrite rpredZ ?vbasis_mem ?memt_nth. Qed. Lemma card_vspacef : #|{: vT}%VS| = #|T|. Proof. by apply: eq_card => v; rewrite (@memvf _ vT). Qed. End Vector. Variable caT : Falgebra F T. Let aT := Falgebra.Pack caT. Lemma card_vspace1 : #|(1%VS : {vspace aT})| = #|F|. Proof. by rewrite card_vspace (dimv1 aT). Qed. End CardVspace. Definition finvect_type (vT : Type) : predArgType := vT. Section FinVector. Variables (R : finNzRingType) (vT : vectType R). Local Notation fvT := (finvect_type vT). HB.instance Definition _ := Vector.on fvT. HB.instance Definition _ := isCountable.Build fvT (pcan_pickleK (can_pcan VectorInternalTheory.v2rK)). HB.instance Definition _ := isFinite.Build fvT (pcan_enumP (can_pcan (VectorInternalTheory.v2rK : @cancel _ fvT _ _))). End FinVector. HB.instance Definition _ (F : finFieldType) (aT : falgType F) := Falgebra.on (finvect_type aT). Section FinFieldExt. Variables (F : finFieldType) (fT : fieldExtType F). Local Notation ffT := (finvect_type fT). HB.instance Definition _ := FieldExt.on ffT. Lemma ffT_splitting_subproof : SplittingField.axiom ffT. Proof. exists ('X^#|ffT| - 'X). by rewrite (@rpredB {poly fT}) 1?rpredX ?polyOverX. exists (enum ffT); first by rewrite big_enum finField_genPoly eqpxx. by apply/vspaceP=> x; rewrite memvf seqv_sub_adjoin ?mem_enum. Qed. HB.instance Definition _ := FieldExt_isSplittingField.Build F ffT ffT_splitting_subproof. End FinFieldExt. Definition FinSplittingFieldType (F : finFieldType) (fT : fieldExtType F) := HB.pack_for (splittingFieldType F) fT (SplittingField.on (finvect_type fT)). Definition FinFieldExtType (F : finFieldType) (fT : fieldExtType F) := HB.pack_for finFieldType (FinSplittingFieldType fT) (FinRing.Field.on (finvect_type fT)). Arguments FinSplittingFieldType : clear implicits. Section PrimeChar. Variable p : nat. Section PrimeCharRing. Variable R0 : nzRingType. Definition pPrimeCharType of p \in [pchar R0] : predArgType := R0. Hypothesis pcharRp : p \in [pchar R0]. Local Notation R := (pPrimeCharType pcharRp). Implicit Types (a b : 'F_p) (x y : R). HB.instance Definition _ := GRing.NzRing.on R. Definition pprimeChar_scale a x := a%:R * x. Local Infix "*p':" := pprimeChar_scale (at level 40). Let natrFp n : (inZp n : 'F_p)%:R = n%:R :> R. Proof. rewrite [in RHS](divn_eq n p) natrD mulrnA (mulrn_pchar pcharRp) add0r. by rewrite /= (Fp_cast (pcharf_prime pcharRp)). Qed. Lemma pprimeChar_scaleA a b x : a *p': (b *p': x) = (a * b) *p': x. Proof. by rewrite /pprimeChar_scale mulrA -natrM natrFp. Qed. Lemma pprimeChar_scale1 : left_id 1 pprimeChar_scale. Proof. by move=> x; rewrite /pprimeChar_scale mul1r. Qed. Lemma pprimeChar_scaleDr : right_distributive pprimeChar_scale +%R. Proof. by move=> a x y /=; rewrite /pprimeChar_scale mulrDr. Qed. Lemma pprimeChar_scaleDl x : {morph pprimeChar_scale^~ x: a b / a + b}. Proof. by move=> a b; rewrite /pprimeChar_scale natrFp natrD mulrDl. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build 'F_p R pprimeChar_scaleA pprimeChar_scale1 pprimeChar_scaleDr pprimeChar_scaleDl. Lemma pprimeChar_scaleAl (a : 'F_p) (u v : R) : a *: (u * v) = (a *: u) * v. Proof. by apply: mulrA. Qed. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build 'F_p R pprimeChar_scaleAl. Lemma pprimeChar_scaleAr (a : 'F_p) (x y : R) : a *: (x * y) = x * (a *: y). Proof. by rewrite ![a *: _]mulr_natl mulrnAr. Qed. HB.instance Definition _ := GRing.Lalgebra_isAlgebra.Build 'F_p R pprimeChar_scaleAr. End PrimeCharRing. Local Notation type := @pPrimeCharType. (* TODO: automatize parameter inference to do all of these *) HB.instance Definition _ (R : unitRingType) pcharRp := GRing.UnitRing.on (type R pcharRp). HB.instance Definition _ (R : comNzRingType) pcharRp := GRing.ComNzRing.on (type R pcharRp). HB.instance Definition _ (R : comUnitRingType) pcharRp := GRing.ComUnitRing.on (type R pcharRp). HB.instance Definition _ (R : idomainType) pcharRp := GRing.IntegralDomain.on (type R pcharRp). HB.instance Definition _ (R : fieldType) pcharRp := GRing.Field.on (type R pcharRp). Section FinNzRing. Variables (R0 : finNzRingType) (pcharRp : p \in [pchar R0]). Local Notation R := (type _ pcharRp). HB.instance Definition _ := FinGroup.on R. Let pr_p : prime p. Proof. exact: pcharf_prime pcharRp. Qed. Lemma pprimeChar_abelem : p.-abelem [set: R]. Proof. exact: fin_Fp_lmod_abelem. Qed. Lemma pprimeChar_pgroup : p.-group [set: R]. Proof. by case/and3P: pprimeChar_abelem. Qed. Lemma order_pprimeChar x : x != 0 :> R -> #[x]%g = p. Proof. by apply: (abelem_order_p pprimeChar_abelem); rewrite inE. Qed. Let n := logn p #|R|. Lemma card_pprimeChar : #|R| = (p ^ n)%N. Proof. by rewrite /n -cardsT {1}(card_pgroup pprimeChar_pgroup). Qed. Lemma pprimeChar_vectAxiom : Vector.axiom n R. Proof. have /isog_isom/=[f /isomP[injf im_f]]: [set: R] \isog [set: 'rV['F_p]_n]. rewrite (@isog_abelem_card _ _ p) fin_Fp_lmod_abelem //=. by rewrite !cardsT card_pprimeChar card_mx mul1n card_Fp. exists f; last by exists (invm injf) => x; rewrite ?invmE ?invmK ?im_f ?inE. move=> a x y; rewrite [a *: _]mulr_natl morphM ?morphX ?inE // zmodXgE. by congr (_ + _); rewrite -scaler_nat natr_Zp. Qed. HB.instance Definition _ := Lmodule_hasFinDim.Build 'F_p R pprimeChar_vectAxiom. Lemma pprimeChar_dimf : \dim {: R : vectType 'F_p } = n. Proof. by rewrite dimvf. Qed. End FinNzRing. HB.instance Definition _ (R : finUnitRingType) pcharRp := FinRing.UnitRing.on (type R pcharRp). HB.instance Definition _ (R : finComNzRingType) pcharRp := FinRing.ComNzRing.on (type R pcharRp). HB.instance Definition _ (R : finComUnitRingType) pcharRp := FinRing.ComUnitRing.on (type R pcharRp). HB.instance Definition _ (R : finIdomainType) pcharRp := FinRing.IntegralDomain.on (type R pcharRp). Section FinField. Variables (F0 : finFieldType) (pcharFp : p \in [pchar F0]). Local Notation F := (type _ pcharFp). HB.instance Definition _ := Finite.on F. HB.instance Definition _ := SplittingField.copy F (finvect_type F). End FinField. End PrimeChar. #[deprecated(since="mathcomp 2.4.0", note="Use pPrimeCharType instead.")] Notation PrimeCharType := (pPrimeCharType) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scale instead.")] Notation primeChar_scale := (pprimeChar_scale) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleA instead.")] Notation primeChar_scaleA := (pprimeChar_scaleA) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scale1 instead.")] Notation primeChar_scale1 := (pprimeChar_scale1) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleDr instead.")] Notation primeChar_scaleDr := (pprimeChar_scaleDr) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleDl instead.")] Notation primeChar_scaleDl := (pprimeChar_scaleDl) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleAl instead.")] Notation primeChar_scaleAl := (pprimeChar_scaleAl) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_scaleAr instead.")] Notation primeChar_scaleAr := (pprimeChar_scaleAr) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_abelem instead.")] Notation primeChar_abelem := (pprimeChar_abelem) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_pgroup instead.")] Notation primeChar_pgroup := (pprimeChar_pgroup) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use order_pprimeChar instead.")] Notation order_primeChar := (order_pprimeChar) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use card_pprimeChar instead.")] Notation card_primeChar := (card_pprimeChar) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_vectAxiom instead.")] Notation primeChar_vectAxiom := (pprimeChar_vectAxiom) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pprimeChar_dimf instead.")] Notation primeChar_dimf := (pprimeChar_dimf) (only parsing). Section FinSplittingField. Variable F : finFieldType. (* By card_vspace order K = #|K| for any finType structure on L; however we *) (* do not want to impose the FinVector instance here. *) Let order (L : vectType F) (K : {vspace L}) := (#|F| ^ \dim K)%N. Section FinGalois. Variable L : splittingFieldType F. Implicit Types (a b : F) (x y : L) (K E : {subfield L}). Let galL K : galois K {:L}. Proof. without loss {K} ->: K / K = 1%AS. by move=> IH_K; apply: galoisS (IH_K _ (erefl _)); rewrite sub1v subvf. apply/splitting_galoisField; pose finL := FinFieldExtType L. exists ('X^#|finL| - 'X); split; first by rewrite rpredB 1?rpredX ?polyOverX. rewrite (finField_genPoly finL) -big_enum /=. by rewrite separable_prod_XsubC ?(enum_uniq finL). exists (enum finL). by rewrite (@big_enum _ _ _ _ finL) (finField_genPoly finL) eqpxx. by apply/vspaceP=> x; rewrite memvf seqv_sub_adjoin ?(mem_enum finL). Qed. Fact galLgen K : {alpha | generator 'Gal({:L} / K) alpha & forall x, alpha x = x ^+ order K}. Proof. without loss{K} ->: K / K = 1%AS; last rewrite /order dimv1 expn1. case/(_ 1%AS)=> // alpha /eqP-defGalL; rewrite /order dimv1 expn1 => Dalpha. exists (alpha ^+ \dim K)%g => [|x]; last first. elim: (\dim K) => [|n IHn]; first by rewrite gal_id. by rewrite expgSr galM ?memvf // IHn Dalpha expnSr exprM. have sGalLK: 'Gal({:L} / K) \subset <[alpha]> by rewrite -defGalL galS ?sub1v. rewrite /generator {sGalLK}(eq_subG_cyclic _ sGalLK) ?cycle_cyclic ?cycleX //. rewrite -orderE orderXdiv orderE -defGalL -?{1}galois_dim ?dimv1 ?divn1 //. by rewrite field_dimS ?subvf. pose f x := x ^+ #|F|. have idfP x: reflect (f x = x) (x \in 1%VS). apply: (iffP (vlineP _ _)) => [[a ->] | xFx]. by rewrite -in_algE -[LHS]rmorphXn expf_card. pose q := map_poly (in_alg L) ('X^#|F| - 'X). have: root q x. rewrite /q rmorphB /= map_polyXn map_polyX. by rewrite rootE !(hornerE, hornerXn) [x ^+ _]xFx subrr. have{q} ->: q = \prod_(z <- [seq b%:A | b : F]) ('X - z%:P). rewrite /q finField_genPoly rmorph_prod big_image /=. by apply: eq_bigr => b _; rewrite rmorphB /= map_polyX map_polyC. by rewrite root_prod_XsubC => /mapP[a]; exists a. have fA : zmod_morphism f. rewrite /f => x y; rewrite ?exprMn ?expr1n //. have [p _ pcharFp] := finPcharP F; rewrite (card_pprimeChar pcharFp). elim: (logn _ _) => // n IHn; rewrite expnSr !exprM {}IHn. by rewrite -(pchar_lalg L) in pcharFp; rewrite -pFrobenius_autE rmorphB. have fM : monoid_morphism f. by rewrite /f; split=> [|x y]; rewrite ?exprMn ?expr1n //. have fZ: scalable f. move=> a x; rewrite -[in LHS]mulr_algl fM. by rewrite (idfP _ _) ?mulr_algl ?memvZ // memv_line. pose faM := GRing.isZmodMorphism.Build _ _ f fA. pose fmM := GRing.isMonoidMorphism.Build _ _ f fM. pose flM := GRing.isScalable.Build _ _ _ _ f fZ. pose fLRM : {lrmorphism _ -> _} := HB.pack f faM fmM flM. have /kAut_to_gal[alpha galLalpha Dalpha]: kAut 1 {:L} (linfun fLRM). rewrite kAutfE; apply/kHomP_tmp; split=> [x /idfP | x y _ _]; rewrite !lfunE //=. exact: (rmorphM fLRM). have{} Dalpha: alpha =1 f by move=> a; rewrite -Dalpha ?memvf ?lfunE. suffices <-: fixedField [set alpha] = 1%AS. by rewrite gal_generated /generator; exists alpha. apply/vspaceP=> x; apply/fixedFieldP/idfP; rewrite ?memvf // => id_x. by rewrite -Dalpha id_x ?set11. by move=> _ /set1P->; rewrite Dalpha. Qed. Lemma finField_galois K E : (K <= E)%VS -> galois K E. Proof. move=> sKE; have /galois_fixedField <- := galL E. rewrite normal_fixedField_galois // -sub_abelian_normal ?galS //. apply: abelianS (galS _ (sub1v _)) _. by have [alpha /('Gal(_ / _) =P _)-> _] := galLgen 1; apply: cycle_abelian. Qed. Lemma finField_galois_generator K E : (K <= E)%VS -> {alpha | generator 'Gal(E / K) alpha & {in E, forall x, alpha x = x ^+ order K}}. Proof. move=> sKE; have [alpha defGalLK Dalpha] := galLgen K. have inKL_E: (K <= E <= {:L})%VS by rewrite sKE subvf. have nKE: normalField K E by have/and3P[] := finField_galois sKE. have galLKalpha: alpha \in 'Gal({:L} / K). by rewrite (('Gal(_ / _) =P _) defGalLK) cycle_id. exists (normalField_cast _ alpha) => [|x Ex]; last first. by rewrite (normalField_cast_eq inKL_E). rewrite /generator -(morphim_cycle (normalField_cast_morphism inKL_E nKE)) //. by rewrite -((_ =P <[alpha]>) defGalLK) normalField_img. Qed. End FinGalois. Lemma Fermat's_little_theorem (L : fieldExtType F) (K : {subfield L}) a : (a \in K) = (a ^+ order K == a). Proof. move: K a; wlog [{}L -> K a]: L / exists galL : splittingFieldType F, L = galL. by pose galL := FinSplittingFieldType F L => /(_ galL); apply; exists galL. have /galois_fixedField fixLK := finField_galois (subvf K). have [alpha defGalLK Dalpha] := finField_galois_generator (subvf K). rewrite -Dalpha ?memvf // -{1}fixLK (('Gal(_ / _) =P _) defGalLK). rewrite /cycle -gal_generated (galois_fixedField _) ?fixedField_galois //. by apply/fixedFieldP/eqP=> [|-> | alpha_x _ /set1P->]; rewrite ?memvf ?set11. Qed. End FinSplittingField. Section FinFieldExists. (* While the existence of finite splitting fields and of finite fields of *) (* arbitrary prime power order is mathematically straightforward, it is *) (* technically challenging to formalize in Coq. The Coq typechecker performs *) (* poorly for some of the deeply nested dependent types used in the *) (* construction, such as polynomials over extensions of extensions of finite *) (* fields. Any conversion in a nested structure parameter incurs a huge *) (* overhead as it is shared across term comparison by call-by-need evalution. *) (* The proof of FinSplittingFieldFor is contrived to mitigate this effect: *) (* the abbreviation map_poly_extField alone divides by 3 the proof checking *) (* time, by reducing the number of occurrences of field(Ext)Type structures *) (* in the subgoals; the successive, apparently redundant 'suffices' localize *) (* some of the conversions to smaller subgoals, yielding a further 8-fold *) (* time gain. In particular, we construct the splitting field as a subtype *) (* of a recursive construction rather than prove that the latter yields *) (* precisely a splitting field. *) (* The apparently redundant type annotation reduces checking time by 30%. *) Let map_poly_extField (F : fieldType) (L : fieldExtType F) := map_poly (in_alg L) : {poly F} -> {poly L}. Local Notation "p ^%:A" := (map_poly_extField _ p) (format "p ^%:A") : ring_scope. Lemma FinSplittingFieldFor (F : finFieldType) (p : {poly F}) : p != 0 -> {L : splittingFieldType F | splittingFieldFor 1 p^%:A {:L}}. Proof. have mapXsubC (f : {rmorphism _ -> _}) x: map_poly f ('X - x%:P) = 'X - (f x)%:P. by rewrite rmorphB /= map_polyX map_polyC. move=> nz_p; pose splits q := {zs | q %= \prod_(z <- zs) ('X - z%:P)}. suffices [L splitLp]: {L : fieldExtType F | splittingFieldFor 1 p^%:A {:L}}. by exists (FinSplittingFieldType F L). suffices [L [ys Dp]]: {L : fieldExtType F & splits L p^%:A}. pose Lp := subvs_of <<1 & ys>>; pose toL := linfun (vsval : Lp -> L). have [zs Dys]: {zs | map toL zs = ys}. exists (map (vsproj _) ys); rewrite -map_comp map_id_in // => y ys_y. by rewrite /= lfunE /= vsprojK ?seqv_sub_adjoin. exists Lp, zs. set lhs := (lhs in lhs %= _); set rhs := (rhs in _ %= rhs). suffices: map_poly toL lhs %= map_poly toL rhs by rewrite eqp_map. rewrite -Dys big_map in Dp; apply: etrans Dp; apply: congr2. by rewrite -map_poly_comp; apply/eq_map_poly=> x; apply: rmorph_alg. by rewrite rmorph_prod; apply/eq_bigr=> z _; apply mapXsubC. set Lzs := LHS; pose Lys := (toL @: Lzs)%VS; apply/vspaceP=> u. have: val u \in Lys by rewrite /Lys aimg_adjoin_seq aimg1 Dys (valP u). by case/memv_imgP=> v Lzs_v; rewrite memvf lfunE => /val_inj->. move: {2}_.+1 (ltnSn (size p)) => n; elim: n => // n IHn in F p nz_p * => lbn. have [Cp|C'p] := leqP (size p) 1. exists F^o, [::]. by rewrite big_nil -size_poly_eq1 size_map_poly eqn_leq Cp size_poly_gt0. have [r r_dv_p irr_r]: {r | r %| p & irreducible_poly r}. pose rVp (v : 'rV_n) (r := rVpoly v) := (1 < size r) && (r %| p). have [v0 Dp]: {v0 | rVpoly v0 = p & rVp v0}. by exists (poly_rV p); rewrite /rVp poly_rV_K ?C'p /=. case/(arg_minnP (size \o rVpoly))=> /= v; set r := rVpoly v. case/andP=> C'r r_dv_p min_r; exists r => //; split=> // q C'q q_dv_r. have nz_r: r != 0 by rewrite -size_poly_gt0 ltnW. have le_q_r: size q <= size r by rewrite dvdp_leq. have [u Dq]: {u : 'rV_n | rVpoly u = q}. by exists (poly_rV q); rewrite poly_rV_K ?(leq_trans le_q_r) ?size_poly. rewrite -dvdp_size_eqp // eqn_leq le_q_r -Dq min_r // /rVp Dq. rewrite ltn_neqAle eq_sym C'q size_poly_gt0 (dvdpN0 q_dv_r) //=. exact: dvdp_trans q_dv_r r_dv_p. have{irr_r} [K _ [x rx0 defK]] := irredp_FAdjoin irr_r. have{r rx0 r_dv_p} /factor_theorem/sig_eqW[q Dp]: root p^%:A x. by rewrite -(divpK r_dv_p) [_^%:A]rmorphM rootM rx0 orbT. have Dszp: size p = size (q * ('X - x%:P)) by rewrite -Dp size_map_poly. have nz_q: q != 0. by move: nz_p; rewrite -size_poly_eq0 Dszp size_poly_eq0 mulf_eq0 => /norP[]. have [L [zs Dq]]: {L : fieldExtType K & splits L q^%:A}. apply: (IHn (FinFieldExtType K) q nz_q). by rewrite ltnS Dszp size_mul ?polyXsubC_eq0 ?size_XsubC ?addn2 in lbn. suffices: splits L p^%:A^%:A. rewrite -[_^%:A]map_poly_comp. (* TODO_HB : had to give the F explicitly *) rewrite -(eq_map_poly (fun a : F => baseField_scaleE a 1)). by exists (baseFieldType L). exists (x%:A :: zs); rewrite big_cons; set rhs := _ * _. by rewrite Dp mulrC [_^%:A]rmorphM /= mapXsubC /= eqp_mull. Qed. Lemma pPrimePowerField p k (m := (p ^ k)%N) : prime p -> 0 < k -> {Fm : finFieldType | p \in [pchar Fm] & #|Fm| = m}. Proof. move=> pr_p k_gt0; have m_gt1: m > 1 by rewrite (ltn_exp2l 0) ?prime_gt1. have m_gt0 := ltnW m_gt1; have m1_gt0: m.-1 > 0 by rewrite -ltnS prednK. pose q := 'X^m - 'X; have Dq R: q R = ('X^(m.-1) - 1) * ('X - 0). by rewrite subr0 mulrBl mul1r -exprSr prednK. have /FinSplittingFieldFor[/= L splitLq]: q 'F_p != 0. by rewrite Dq monic_neq0 ?rpredM ?monicXsubC ?monicXnsubC. rewrite [_^%:A]rmorphB rmorphXn /= map_polyX -/(q L) in splitLq. have pcharL: p \in [pchar L] by rewrite pchar_lalg pchar_Fp. pose Fm := FinFieldExtType L; exists Fm => //. have /finField_galois_generator[/= a _ Da]: (1 <= {:L})%VS by apply: sub1v. pose Em := fixedSpace (a ^+ k)%g; rewrite card_Fp //= dimv1 expn1 in Da. have{splitLq} [zs DqL defL] := splitLq. have Uzs: uniq zs. rewrite -separable_prod_XsubC -(eqp_separable DqL) Dq separable_root andbC. rewrite /root !hornerE subr_eq0 eq_sym expr0n gtn_eqF ?oner_eq0 //=. rewrite cyclotomic.separable_Xn_sub_1 // -subn1 natrB // subr_eq0. by rewrite natrX pcharf0 // expr0n gtn_eqF // eq_sym oner_eq0. suffices /eq_card->: Fm =i zs. apply: succn_inj; rewrite (card_uniqP _) //= -(size_prod_XsubC _ id). by rewrite -(eqp_size DqL) size_polyDl size_polyXn // size_polyN size_polyX. have in_zs: zs =i Em. move=> z; rewrite -root_prod_XsubC -(eqp_root DqL) (sameP fixedSpaceP eqP). rewrite /root !hornerE subr_eq0 /= /m; congr (_ == z). elim: (k) => [|i IHi]; first by rewrite gal_id. by rewrite expgSr expnSr exprM IHi galM ?Da ?memvf. suffices defEm: Em = {:L}%VS by move=> z; rewrite in_zs defEm memvf. apply/eqP; rewrite eqEsubv subvf -defL -[Em]subfield_closed agenvS //. by rewrite subv_add sub1v; apply/span_subvP=> z; rewrite in_zs. Qed. End FinFieldExists. #[deprecated(since="mathcomp 2.4.0", note="Use pPrimePowerField instead.")] Notation PrimePowerField := (pPrimePowerField) (only parsing). Section FinDomain. Import order ssrnum ssrint archimedean algC cyclotomic Order.TTheory Num.Theory. Local Infix "%|" := dvdn. (* Hide polynomial divisibility. *) Variable R : finUnitRingType. Hypothesis domR : GRing.integral_domain_axiom R. Implicit Types x y : R. Let lregR x : x != 0 -> GRing.lreg x. Proof. by move=> xnz; apply: mulrI0_lreg => y /domR/orP[/idPn | /eqP]. Qed. Lemma finDomain_field : GRing.field_axiom R. Proof. move=> x /lregR-regx; apply/unitrP; exists (invF regx 1). by split; first apply: (regx); rewrite ?mulrA f_invF // mulr1 mul1r. Qed. (* This is Witt's proof of Wedderburn's little theorem. *) Theorem finDomain_mulrC : @commutative R R *%R. Proof. have fieldR := finDomain_field. have [p p_pr pcharRp]: exists2 p, prime p & p \in [pchar R]. have [e /prod_prime_decomp->]: {e | (e > 0)%N & e%:R == 0 :> R}. by exists #|[set: R]%G|; rewrite // -order_dvdn order_dvdG ?inE. rewrite big_seq; elim/big_rec: _ => [|[p m] /= n]; first by rewrite oner_eq0. case/mem_prime_decomp=> p_pr _ _ IHn. elim: m => [|m IHm]; rewrite ?mul1n {IHn}// expnS -mulnA natrM. by case/eqP/domR/orP=> //; exists p; last apply/andP. pose Rp := pPrimeCharType pcharRp; pose L : {vspace Rp} := fullv. pose G := [set: {unit R}]; pose ofG : {unit R} -> Rp := val. pose projG (E : {vspace Rp}) := [preim ofG of E]. have inG t nzt: Sub t (finDomain_field nzt) \in G by rewrite inE. have card_projG E: #|projG E| = (p ^ \dim E - 1)%N. transitivity #|E|.-1; last by rewrite subn1 card_vspace card_Fp. rewrite (cardD1 0) mem0v (card_preim val_inj) /=. apply: eq_card => x; congr (_ && _); rewrite [LHS]codom_val. by apply/idP/idP=> [/(memPn _ _)-> | /fieldR]; rewrite ?unitr0. pose C u := 'C[ofG u]%AS; pose Q := 'C(L)%AS; pose q := (p ^ \dim Q)%N. have defC u: 'C[u] =i projG (C u). by move=> v; rewrite cent1E !inE (sameP cent1vP eqP). have defQ: 'Z(G) =i projG Q. move=> u /[!inE]. apply/centP/centvP=> cGu v _; last exact/val_inj/cGu/memvf. by have [-> | /inG/cGu[]] := eqVneq v 0; first by rewrite commr0. have q_gt1: (1 < q)%N by rewrite (ltn_exp2l 0) ?prime_gt1 ?adim_gt0. pose n := \dim_Q L; have oG: #|G| = (q ^ n - 1)%N. rewrite -expnM mulnC divnK ?skew_field_dimS ?subvf // -card_projG. by apply: eq_card => u; rewrite !inE memvf. have oZ: #|'Z(G)| = (q - 1)%N by rewrite -card_projG; apply: eq_card. suffices n_le1: (n <= 1)%N. move=> u v; apply/centvsP: (memvf (u : Rp)) (memvf (v : Rp)) => {u v}. rewrite -(geq_leqif (dimv_leqif_sup (subvf Q))) -/L. by rewrite leq_divLR ?mul1n ?skew_field_dimS ?subvf in n_le1. without loss n_gt1: / (1 < n)%N by rewrite ltnNge; apply: wlog_neg. have [q_gt0 n_gt0] := (ltnW q_gt1, ltnW n_gt1). have [z z_prim] := C_prim_root_exists n_gt0. have zn1: z ^+ n = 1 by apply: prim_expr_order. have /eqP-n1z: `|z| == 1 by rewrite -(pexpr_eq1 n_gt0) // -normrX zn1 normr1. suffices /eqP/normCBeq[t n1t [Dq Dz]]: `|q%:R - z : algC| == `|q%:R : algC| - `|z|. suffices z1: z == 1 by rewrite leq_eqVlt -dvdn1 (prim_order_dvd z_prim) z1. by rewrite Dz n1z mul1r -(eqr_pMn2r q_gt0) Dq normr_nat mulr_natl. pose aq d : algC := (cyclotomic (z ^+ (n %/ d)) d).[q%:R]. suffices: `|aq n| <= (q - 1)%:R. rewrite eq_le lerB_dist andbT n1z normr_nat natrB //; apply: le_trans. rewrite {}/aq horner_prod divnn n_gt0 expr1 normr_prod. rewrite (bigD1 (Ordinal n_gt1)) ?coprime1n //= !hornerE ler_peMr //. elim/big_ind: _ => // [|d _]; first exact: mulr_ege1. rewrite !hornerE; apply: le_trans (lerB_dist _ _). by rewrite normr_nat normrX n1z expr1n lerBDl (leC_nat 2). have Zaq d: d %| n -> aq d \in Num.int. move/(dvdn_prim_root z_prim)=> zd_prim. rewrite rpred_horner ?rpred_nat //= -Cintr_Cyclotomic //. by apply/polyOverP=> i; rewrite coef_map ?rpred_int. suffices: (aq n %| (q - 1)%:R)%C. rewrite {1}[aq n]intrEsign ?Zaq // -(rpredMsign _ (aq n < 0)%R). rewrite dvdC_mul2l ?signr_eq0 //. have /natrP[m ->]: `|aq n| \in Num.nat by rewrite natr_norm_int ?Zaq. by rewrite leC_nat dvdC_nat; apply: dvdn_leq; rewrite subn_gt0. have prod_aq m: m %| n -> \prod_(d < n.+1 | d %| m) aq d = (q ^ m - 1)%:R. move=> m_dv_n; transitivity ('X^m - 1).[q%:R : algC]; last first. by rewrite !hornerE -natrX natrB ?expn_gt0 ?prime_gt0. rewrite (prod_cyclotomic (dvdn_prim_root z_prim m_dv_n)). have def_divm: perm_eq (divisors m) [seq d <- index_iota 0 n.+1 | d %| m]. rewrite uniq_perm ?divisors_uniq ?filter_uniq ?iota_uniq // => d. rewrite -dvdn_divisors ?(dvdn_gt0 n_gt0) // mem_filter mem_iota ltnS /=. by apply/esym/andb_idr=> d_dv_m; rewrite dvdn_leq ?(dvdn_trans d_dv_m). rewrite (perm_big _ def_divm) big_filter big_mkord horner_prod. by apply: eq_bigr => d d_dv_m; rewrite -exprM muln_divA ?divnK. have /rpredBl<-: (aq n %| #|G|%:R)%C. rewrite oG -prod_aq // (bigD1 ord_max) //= dvdC_mulr //. by apply: rpred_prod => d /andP[/Zaq]. rewrite center_class_formula addrC oZ natrD addKr natr_sum /=. apply: rpred_sum => _ /imsetP[u /setDP[_ Z'u] ->]; rewrite -/G /=. have sQC: (Q <= C u)%VS by apply/subvP=> v /centvP-cLv; apply/cent1vP/cLv/memvf. have{sQC} /dvdnP[m Dm]: \dim Q %| \dim (C u) by apply: skew_field_dimS. have m_dv_n: m %| n by rewrite dvdn_divRL // -?Dm ?skew_field_dimS ?subvf. have m_gt0: (0 < m)%N := dvdn_gt0 n_gt0 m_dv_n. have{Dm} oCu: #|'C[u]| = (q ^ m - 1)%N. by rewrite -expnM mulnC -Dm (eq_card (defC u)) card_projG. have ->: #|u ^: G|%:R = \prod_(d < n.+1 | d %| n) (aq d / aq d ^+ (d %| m)). rewrite -index_cent1 natf_indexg ?subsetT //= setTI prodf_div prod_aq // -oG. congr (_ / _); rewrite big_mkcond oCu -prod_aq //= big_mkcond /=. by apply: eq_bigr => d _; case: ifP => [/dvdn_trans->| _]; rewrite ?if_same. rewrite (bigD1 ord_max) //= [n %| m](contraNF _ Z'u) => [|n_dv_m]; last first. rewrite -sub_cent1 subEproper eq_sym eqEcard subsetT oG oCu leq_sub2r //. by rewrite leq_exp2l // dvdn_leq. rewrite divr1 dvdC_mulr //; apply/rpred_prod => d /andP[/Zaq-Zaqd _]. have [-> | nz_aqd] := eqVneq (aq d) 0; first by rewrite mul0r /=. by rewrite -[aq d]expr1 -exprB ?leq_b1 ?unitfE ?rpredX. Qed. Definition FinDomainFieldType : finFieldType := let cC := GRing.PzRing_hasCommutativeMul.Build R finDomain_mulrC in let cR : comUnitRingType := HB.pack R cC in let iC := GRing.ComUnitRing_isIntegral.Build cR domR in let iR : finIdomainType := HB.pack cR iC in let fC := GRing.UnitRing_isField.Build iR finDomain_field in HB.pack iR fC. Definition FinDomainSplittingFieldType_pchar p (pcharRp : p \in [pchar R]) := SplittingField.clone 'F_p R (@pPrimeCharType p FinDomainFieldType pcharRp). End FinDomain. #[deprecated(since="mathcomp 2.4.0", note="Use FinDomainSplittingFieldType_pchar instead.")] Notation FinDomainSplittingFieldType := (FinDomainSplittingFieldType_pchar) (only parsing).
MvPolynomial.lean
/- Copyright (c) 2024 Antoine Chambert-Loir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Chambert-Loir -/ import Mathlib.LinearAlgebra.DirectSum.Finsupp import Mathlib.Algebra.MvPolynomial.Eval import Mathlib.RingTheory.TensorProduct.Basic import Mathlib.Algebra.MvPolynomial.Equiv import Mathlib.RingTheory.IsTensorProduct /-! # Tensor Product of (multivariate) polynomial rings Let `Semiring R`, `Algebra R S` and `Module R N`. * `MvPolynomial.rTensor` gives the linear equivalence `MvPolynomial σ S ⊗[R] N ≃ₗ[R] (σ →₀ ℕ) →₀ (S ⊗[R] N)` characterized, for `p : MvPolynomial σ S`, `n : N` and `d : σ →₀ ℕ`, by `rTensor (p ⊗ₜ[R] n) d = (coeff d p) ⊗ₜ[R] n` * `MvPolynomial.scalarRTensor` gives the linear equivalence `MvPolynomial σ R ⊗[R] N ≃ₗ[R] (σ →₀ ℕ) →₀ N` such that `MvPolynomial.scalarRTensor (p ⊗ₜ[R] n) d = coeff d p • n` for `p : MvPolynomial σ R`, `n : N` and `d : σ →₀ ℕ`, by * `MvPolynomial.rTensorAlgHom`, the algebra morphism from the tensor product of a polynomial algebra by an algebra to a polynomial algebra * `MvPolynomial.rTensorAlgEquiv`, `MvPolynomial.scalarRTensorAlgEquiv`, the tensor product of a polynomial algebra by an algebra is algebraically equivalent to a polynomial algebra ## TODO : * `MvPolynomial.rTensor` could be phrased in terms of `AddMonoidAlgebra`, and `MvPolynomial.rTensor` then has `smul` by the polynomial algebra. * `MvPolynomial.rTensorAlgHom` and `MvPolynomial.scalarRTensorAlgEquiv` are morphisms for the algebra structure by `MvPolynomial σ R`. -/ universe u v noncomputable section namespace MvPolynomial open DirectSum TensorProduct open Set LinearMap Submodule variable {R : Type u} {N : Type v} [CommSemiring R] variable {σ : Type*} variable {S : Type*} [CommSemiring S] [Algebra R S] section Module variable [DecidableEq σ] variable [AddCommMonoid N] [Module R N] /-- The tensor product of a polynomial ring by a module is linearly equivalent to a Finsupp of a tensor product -/ noncomputable def rTensor : MvPolynomial σ S ⊗[R] N ≃ₗ[S] (σ →₀ ℕ) →₀ (S ⊗[R] N) := TensorProduct.finsuppLeft' _ _ _ _ _ lemma rTensor_apply_tmul (p : MvPolynomial σ S) (n : N) : rTensor (p ⊗ₜ[R] n) = p.sum (fun i m ↦ Finsupp.single i (m ⊗ₜ[R] n)) := TensorProduct.finsuppLeft_apply_tmul p n lemma rTensor_apply_tmul_apply (p : MvPolynomial σ S) (n : N) (d : σ →₀ ℕ) : rTensor (p ⊗ₜ[R] n) d = (coeff d p) ⊗ₜ[R] n := TensorProduct.finsuppLeft_apply_tmul_apply p n d lemma rTensor_apply_monomial_tmul (e : σ →₀ ℕ) (s : S) (n : N) (d : σ →₀ ℕ) : rTensor (monomial e s ⊗ₜ[R] n) d = if e = d then s ⊗ₜ[R] n else 0 := by simp only [rTensor_apply_tmul_apply, coeff_monomial, ite_tmul] lemma rTensor_apply_X_tmul (s : σ) (n : N) (d : σ →₀ ℕ) : rTensor (X s ⊗ₜ[R] n) d = if Finsupp.single s 1 = d then (1 : S) ⊗ₜ[R] n else 0 := by rw [rTensor_apply_tmul_apply, coeff_X', ite_tmul] lemma rTensor_apply (t : MvPolynomial σ S ⊗[R] N) (d : σ →₀ ℕ) : rTensor t d = ((lcoeff S d).restrictScalars R).rTensor N t := TensorProduct.finsuppLeft_apply t d @[simp] lemma rTensor_symm_apply_single (d : σ →₀ ℕ) (s : S) (n : N) : rTensor.symm (Finsupp.single d (s ⊗ₜ n)) = (monomial d s) ⊗ₜ[R] n := TensorProduct.finsuppLeft_symm_apply_single (R := R) d s n /-- The tensor product of the polynomial algebra by a module is linearly equivalent to a Finsupp of that module -/ noncomputable def scalarRTensor : MvPolynomial σ R ⊗[R] N ≃ₗ[R] (σ →₀ ℕ) →₀ N := TensorProduct.finsuppScalarLeft _ _ _ lemma scalarRTensor_apply_tmul (p : MvPolynomial σ R) (n : N) : scalarRTensor (p ⊗ₜ[R] n) = p.sum (fun i m ↦ Finsupp.single i (m • n)) := TensorProduct.finsuppScalarLeft_apply_tmul p n lemma scalarRTensor_apply_tmul_apply (p : MvPolynomial σ R) (n : N) (d : σ →₀ ℕ) : scalarRTensor (p ⊗ₜ[R] n) d = coeff d p • n := TensorProduct.finsuppScalarLeft_apply_tmul_apply p n d lemma scalarRTensor_apply_monomial_tmul (e : σ →₀ ℕ) (r : R) (n : N) (d : σ →₀ ℕ) : scalarRTensor (monomial e r ⊗ₜ[R] n) d = if e = d then r • n else 0 := by rw [scalarRTensor_apply_tmul_apply, coeff_monomial, ite_smul, zero_smul] lemma scalarRTensor_apply_X_tmul_apply (s : σ) (n : N) (d : σ →₀ ℕ) : scalarRTensor (X s ⊗ₜ[R] n) d = if Finsupp.single s 1 = d then n else 0 := by rw [scalarRTensor_apply_tmul_apply, coeff_X', ite_smul, one_smul, zero_smul] lemma scalarRTensor_symm_apply_single (d : σ →₀ ℕ) (n : N) : scalarRTensor.symm (Finsupp.single d n) = (monomial d 1) ⊗ₜ[R] n := TensorProduct.finsuppScalarLeft_symm_apply_single d n end Module section Algebra variable [CommSemiring N] [Algebra R N] /-- The algebra morphism from a tensor product of a polynomial algebra by an algebra to a polynomial algebra -/ noncomputable def rTensorAlgHom : (MvPolynomial σ S) ⊗[R] N →ₐ[S] MvPolynomial σ (S ⊗[R] N) := Algebra.TensorProduct.lift (mapAlgHom Algebra.TensorProduct.includeLeft) ((IsScalarTower.toAlgHom R (S ⊗[R] N) _).comp Algebra.TensorProduct.includeRight) (fun p n => by simp [commute_iff_eq, algebraMap_eq, mul_comm]) @[simp] lemma coeff_rTensorAlgHom_tmul (p : MvPolynomial σ S) (n : N) (d : σ →₀ ℕ) : coeff d (rTensorAlgHom (p ⊗ₜ[R] n)) = (coeff d p) ⊗ₜ[R] n := by rw [rTensorAlgHom, Algebra.TensorProduct.lift_tmul] rw [AlgHom.coe_comp, IsScalarTower.coe_toAlgHom', Function.comp_apply, Algebra.TensorProduct.includeRight_apply] rw [algebraMap_eq, mul_comm, coeff_C_mul] simp [mapAlgHom, coeff_map] section DecidableEq variable [DecidableEq σ] lemma coeff_rTensorAlgHom_monomial_tmul (e : σ →₀ ℕ) (s : S) (n : N) (d : σ →₀ ℕ) : coeff d (rTensorAlgHom (monomial e s ⊗ₜ[R] n)) = if e = d then s ⊗ₜ[R] n else 0 := by simp [ite_tmul] lemma rTensorAlgHom_toLinearMap : (rTensorAlgHom : MvPolynomial σ S ⊗[R] N →ₐ[S] MvPolynomial σ (S ⊗[R] N)).toLinearMap = rTensor.toLinearMap := by ext d n e dsimp only [AlgebraTensorModule.curry_apply, TensorProduct.curry_apply, LinearMap.coe_restrictScalars, AlgHom.toLinearMap_apply] simp only [coe_comp, Function.comp_apply, AlgebraTensorModule.curry_apply, curry_apply, LinearMap.coe_restrictScalars, AlgHom.toLinearMap_apply] rw [coeff_rTensorAlgHom_tmul] simp only [coeff] exact (finsuppLeft_apply_tmul_apply _ _ _).symm lemma rTensorAlgHom_apply_eq (p : MvPolynomial σ S ⊗[R] N) : rTensorAlgHom (S := S) p = rTensor p := by rw [← AlgHom.toLinearMap_apply, rTensorAlgHom_toLinearMap] rfl /-- The tensor product of a polynomial algebra by an algebra is algebraically equivalent to a polynomial algebra -/ noncomputable def rTensorAlgEquiv : (MvPolynomial σ S) ⊗[R] N ≃ₐ[S] MvPolynomial σ (S ⊗[R] N) := by apply AlgEquiv.ofLinearEquiv rTensor · simp only [Algebra.TensorProduct.one_def] apply symm rw [← LinearEquiv.symm_apply_eq] exact finsuppLeft_symm_apply_single (R := R) (0 : σ →₀ ℕ) (1 : S) (1 : N) · intro x y erw [← rTensorAlgHom_apply_eq (S := S)] simp only [map_mul, rTensorAlgHom_apply_eq] rfl @[simp] lemma rTensorAlgEquiv_apply (x : (MvPolynomial σ S) ⊗[R] N) : rTensorAlgEquiv x = rTensorAlgHom x := by rw [← AlgHom.coe_coe, ← AlgEquiv.toAlgHom_eq_coe] congr 1 ext _ d <;> simpa [rTensorAlgEquiv] using rTensor_apply_tmul_apply _ _ d /-- The tensor product of the polynomial algebra by an algebra is algebraically equivalent to a polynomial algebra with coefficients in that algebra -/ noncomputable def scalarRTensorAlgEquiv : MvPolynomial σ R ⊗[R] N ≃ₐ[R] MvPolynomial σ N := rTensorAlgEquiv.trans (mapAlgEquiv σ (Algebra.TensorProduct.lid R N)) end DecidableEq variable (R) variable (A : Type*) [CommSemiring A] [Algebra R A] /-- Tensoring `MvPolynomial σ R` on the left by an `R`-algebra `A` is algebraically equivalent to `MvPolynomial σ A`. -/ noncomputable def algebraTensorAlgEquiv : A ⊗[R] MvPolynomial σ R ≃ₐ[A] MvPolynomial σ A := AlgEquiv.ofAlgHom (Algebra.TensorProduct.lift (Algebra.ofId A (MvPolynomial σ A)) (MvPolynomial.mapAlgHom <| Algebra.ofId R A) (fun _ _ ↦ Commute.all _ _)) (aeval (fun s ↦ 1 ⊗ₜ X s)) (by ext s; simp) (by ext s; simp) @[simp] lemma algebraTensorAlgEquiv_tmul (a : A) (p : MvPolynomial σ R) : algebraTensorAlgEquiv R A (a ⊗ₜ p) = a • MvPolynomial.map (algebraMap R A) p := by simp [algebraTensorAlgEquiv, Algebra.smul_def] rfl @[simp] lemma algebraTensorAlgEquiv_symm_X (s : σ) : (algebraTensorAlgEquiv R A).symm (X s) = 1 ⊗ₜ X s := by simp [algebraTensorAlgEquiv] @[simp] lemma algebraTensorAlgEquiv_symm_monomial (m : σ →₀ ℕ) (a : A) : (algebraTensorAlgEquiv R A).symm (monomial m a) = a ⊗ₜ monomial m 1 := by apply @Finsupp.induction σ ℕ _ _ m · simp [algebraTensorAlgEquiv] · intro i n f _ _ hfa simp only [algebraTensorAlgEquiv, AlgEquiv.ofAlgHom_symm_apply] at hfa ⊢ simp only [add_comm, monomial_add_single, map_mul, map_pow, aeval_X, Algebra.TensorProduct.tmul_pow, one_pow, hfa] nth_rw 2 [← mul_one a] rw [Algebra.TensorProduct.tmul_mul_tmul] lemma aeval_one_tmul (f : σ → S) (p : MvPolynomial σ R) : (aeval fun x ↦ (1 ⊗ₜ[R] f x : N ⊗[R] S)) p = 1 ⊗ₜ[R] (aeval f) p := by induction p using MvPolynomial.induction_on with | C a => simp only [algHom_C, Algebra.TensorProduct.algebraMap_apply] rw [← mul_one ((algebraMap R N) a), ← Algebra.smul_def, smul_tmul, Algebra.smul_def, mul_one] | add p q hp hq => simp [hp, hq, tmul_add] | mul_X p i h => simp [h] section Pushout attribute [local instance] algebraMvPolynomial instance : Algebra.IsPushout R S (MvPolynomial σ R) (MvPolynomial σ S) where out := .of_equiv (algebraTensorAlgEquiv R S).toLinearEquiv fun _ ↦ by simp instance : Algebra.IsPushout R (MvPolynomial σ R) S (MvPolynomial σ S) := .symm inferInstance end Pushout end Algebra end MvPolynomial end
Indization.lean
/- Copyright (c) 2025 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.CategoryTheory.Abelian.GrothendieckAxioms.FunctorCategory import Mathlib.CategoryTheory.Abelian.GrothendieckAxioms.Types import Mathlib.CategoryTheory.Abelian.Indization import Mathlib.CategoryTheory.Limits.Indization.Category import Mathlib.CategoryTheory.Generator.Indization import Mathlib.CategoryTheory.Abelian.GrothendieckCategory.Basic /-! # AB axioms in the category of ind-objects We show that `Ind C` satisfies Grothendieck's axiom AB5 if `C` has finite limits and deduce that `Ind C` is Grothendieck abelian if `C` is small and abelian. -/ universe v u namespace CategoryTheory.Limits section variable {C : Type u} [Category.{v} C] instance {J : Type v} [SmallCategory J] [IsFiltered J] [HasFiniteLimits C] : HasExactColimitsOfShape J (Ind C) := HasExactColimitsOfShape.domain_of_functor J (Ind.inclusion C) instance [HasFiniteLimits C] : AB5 (Ind C) where ofShape _ _ _ := inferInstance end section variable {C : Type u} [SmallCategory C] [Abelian C] instance isGrothendieckAbelian_ind : IsGrothendieckAbelian.{u} (Ind C) where hasSeparator := ⟨⟨_, Ind.isSeparator_range_yoneda⟩⟩ end end CategoryTheory.Limits
preorder.v
(* (c) Copyright 2006-2019 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat choice seq. From mathcomp Require Import path fintype tuple bigop finset div prime finfun. From mathcomp Require Import finset. (******************************************************************************) (* Types equipped with order relations *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file and order.v define types equipped with order relations. *) (* *) (* * How to use preorders in MathComp? *) (* Use the module PreorderTheory implementing the theories (located in the *) (* module Order):$ *) (* To access the definitions, notations, and the theory from, say, *) (* "Order.Xyz", insert "Import Order.Xyz." at the top of your scripts. You can*) (* also "Import Order.Def." to enjoy shorter notations (e.g., min instead of *) (* Order.min, nondecreasing instead of Order.nondecreasing, etc.). *) (* *) (* In order to reason about abstract orders, notations are accessible by *) (* opening the scope "order_scope" bound to the delimiting key "O"; however, *) (* when dealing with another notation scope providing order notations for *) (* a concrete instance (e.g., "ring_scope"), it is not recommended to open *) (* "order_scope" at the same time. *) (* *) (* * Control of inference (parsing) and printing *) (* One characteristic of ordered types is that one carrier type may have *) (* several orders. For example, natural numbers can be totally or partially *) (* ordered by the less than or equal relation, the divisibility relation, and *) (* their dual relations. Therefore, we need a way to control inference of *) (* ordered type instances and printing of generic relations and operations on *) (* ordered types. As a rule of thumb, we use the carrier type or its "alias" *) (* (named copy) to control inference (using canonical structures), and use a *) (* "display" to control the printing of notations. *) (* *) (* Each generic interface and operation for ordered types has, as its first *) (* argument, a "display" of type Order.disp_t. For example, the less than or *) (* equal relation has type: *) (* Order.le : forall {d : Order.disp_t} {T : porderType d}, rel T, *) (* where porderType d is the structure of partially ordered types with *) (* display d. (@Order.le dvd_display _ m n) is printed as m %| n because *) (* ordered type instances associated to the display dvd_display is intended *) (* to represent natural numbers partially ordered by the divisibility *) (* relation. *) (* *) (* We stress that order structure inference can be triggered only from the *) (* carrier type (or its alias), but not the display. For example, writing *) (* m %| n for m and n of type nat does not trigger an inference of the *) (* divisibility relation on natural numbers, which is associated to an alias *) (* natdvd for nat; such an inference should be triggered through the use of *) (* the corresponding alias, i.e., (m : natdvd) %| n. In other words, displays *) (* are merely used to inform the user and the notation mechanism of what the *) (* inference did; they are not additional input for the inference. *) (* *) (* See below for various aliases and their associated displays. *) (* *) (* NB: algebra/ssrnum.v provides the display ring_display to change the *) (* scope of the usual notations to ring_scope. *) (* *) (* Instantiating d with Disp tt tt or an unknown display will lead to a *) (* default display for notations. *) (* *) (* Alternative notation displays can be defined by : *) (* 1. declaring a new opaque definition of type unit. Using the idiom *) (* `Fact my_display : Order.disp_t. Proof. exact: Disp tt tt. Qed.` *) (* 2. using this symbol to tag canonical porderType structures using *) (* `HB.instance Definition _ := isPOrder.Build my_display my_type ...`, *) (* 3. declaring notations for the main operations of this library, by *) (* setting the first argument of the definition to the display, e.g. *) (* `Notation my_syndef_le x y := @Order.le my_display _ x y.` or *) (* `Notation "x <=< y" := @Order.lt my_display _ x y (at level ...).` *) (* Non overloaded notations will default to the default display. *) (* We suggest the user to refer to the example of natdvd below as a guideline *) (* example to add their own displays. *) (* *) (* * Interfaces *) (* We provide the following interfaces for types equipped with an order: *) (* *) (* preorderType d == the type of preordered types *) (* The HB class is called Preorder. *) (* bPreorderType d == preorderType with a bottom element (\bot) *) (* The HB class is called BPreorder. *) (* tPreorderType d == preorderType with a top element (\top) *) (* The HB class is called TPreorder. *) (* tbPreorderType d == preorderType with both a top and a bottom *) (* The HB class is called TBPreorder. *) (* finPreorderType d == the type of partially preordered finite types *) (* The HB class is called FinPreorder. *) (* finBPreorderType d == finPreorderType with a bottom element *) (* The HB class is called FinBPreorder. *) (* finTPreorderType d == finPreorderType with a top element *) (* The HB class is called FinTPreorder. *) (* finTBPreorderType d == finPreorderType with both a top and a bottom *) (* The HB class is called FinTBPreorder. *) (* *) (* and their joins with subType: *) (* *) (* subPreorder d T P d' == join of preorderType d' and subType *) (* (P : pred T) such that val is monotonic *) (* The HB class is called SubPreorder. *) (* *) (* Morphisms between the above structures: *) (* *) (* OrderMorphism.type d T d' T' == nondecreasing function between the two *) (* preorder *) (* := {omorphism T -> T'} *) (* *) (* TODO: Check this section * Useful lemmas: *) (* On orderType, leP, ltP, and ltgtP are the three main lemmas for case *) (* analysis. *) (* On porderType, one may use comparableP, comparable_leP, comparable_ltP, *) (* and comparable_ltgtP, which are the four main lemmas for case analysis. *) (* *) (* * Order relations and operations: *) (* In general, an overloaded relation or operation on ordered types takes the *) (* following arguments: *) (* 1. a display d of type Order.disp_t, *) (* 2. an instance T of the minimal structure it operates on, and *) (* 3. operands. *) (* Here is the exhaustive list of all such operations together with their *) (* default notation (defined in order_scope unless specified otherwise). *) (* *) (* For T of type preorderType d, x and y of type T, and C of type bool: *) (* x <= y := @Order.le d T x y *) (* <-> x is less than or equal to y. *) (* x < y := @Order.lt d T x y *) (* <-> x is less than y, i.e., (y != x) && (x <= y). *) (* x >= y := y <= x *) (* <-> x is greater than or equal to y. *) (* x > y := y < x *) (* <-> x is greater than y. *) (* x >=< y := @Order.comparable d T x y (:= (x <= y) || (y <= x)) *) (* <-> x and y are comparable. *) (* x >< y := ~~ x >=< y *) (* <-> x and y are incomparable. *) (* x <= y ?= iff C := @Order.leif d T x y C (:= (x <= y) * ((x == y) = C)) *) (* <-> x is less than y, or equal iff C is true. *) (* x < y ?<= if C := @Order.lteif d T x y C (:= if C then x <= y else x < y)*) (* <-> x is smaller than y, and strictly if C is false. *) (* Order.min x y := if x < y then x else y *) (* Order.max x y := if x < y then y else x *) (* f \min g == the function x |-> Order.min (f x) (g x); *) (* f \min g simplifies on application. *) (* f \max g == the function x |-> Order.max (f x) (g x); *) (* f \max g simplifies on application. *) (* nondecreasing f <-> the function f : T -> T' is nondecreasing, *) (* where T and T' are porderType *) (* := {homo f : x y / x <= y} *) (* Unary (partially applied) versions of order notations: *) (* >= y := @Order.le d T y *) (* == a predicate characterizing elements greater than or *) (* equal to y *) (* > y := @Order.lt d T y *) (* <= y := @Order.ge d T y *) (* < y := @Order.gt d T y *) (* >=< y := [pred x | @Order.comparable d T x y] *) (* >< y := [pred x | ~~ @Order.comparable d T x y] *) (* 0-ary versions of order notations (in function_scope): *) (* <=%O := @Order.le d T *) (* <%O := @Order.lt d T *) (* >=%O := @Order.ge d T *) (* >%O := @Order.gt d T *) (* >=<%O := @Order.comparable d T *) (* <?=%O := @Order.leif d T *) (* <?<=%O := @Order.lteif d T *) (* -> These conventions are compatible with Haskell's, *) (* where ((< y) x) = (x < y) = ((<) x y), *) (* except that we write <%O instead of (<). *) (* *) (* For T of type bPreorderType d: *) (* \bot := @Order.bottom d T *) (* == the bottom element of type T *) (* For T of type tPreorderType d: *) (* \top := @Order.top d T *) (* == the top element of type T *) (* *) (* For preorderType we provide the following operations: *) (* [arg min_(i < i0 | P) M] == a value i : T minimizing M : R, 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. *) (* with head symbols Order.arg_min and Order.arg_max *) (* The user may use extremumP or extremum_inP to eliminate them. *) (* *) (* -> patterns for contextual rewriting: *) (* leLHS := (X in (X <= _)%O)%pattern *) (* leRHS := (X in (_ <= X)%O)%pattern *) (* ltLHS := (X in (X < _)%O)%pattern *) (* ltRHS := (X in (_ < X)%O)%pattern *) (* *) (* We provide aliases for various types and their displays: *) (* natdvd := nat (associated with display dvd_display) *) (* == an alias for nat which is canonically ordered using *) (* divisibility predicate dvdn *) (* Notation %|, %<|, gcd, lcm are used instead of *) (* <=, <, meet and join. *) (* T^d := dual T, *) (* where dual is a new definition for (fun T => T) *) (* (associated with dual_display d where d is a display) *) (* == an alias for T, such that if T is canonically *) (* ordered, then T^d is canonically ordered with the *) (* dual order, and displayed with an extra ^d in the *) (* notation, i.e., <=^d, <^d, >=<^d, ><^d, `&`^d, `|`^d *) (* are used and displayed instead of *) (* <=, <, >=<, ><, `&`, `|` *) (* T *prod[d] T' := T * T' *) (* == an alias for the cartesian product such that, *) (* if T and T' are canonically ordered, *) (* then T *prod[d] T' is canonically ordered in product *) (* order, i.e., *) (* (x1, x2) <= (y1, y2) = (x1 <= y1) && (x2 <= y2), *) (* and displayed in display d *) (* T *p T' := T *prod[prod_display d d'] T' *) (* where d and d' are the displays of T and T', *) (* respectively, and prod_display adds an extra ^p to *) (* all notations *) (* T *lexi[d] T' := T * T' *) (* == an alias for the cartesian product such that, *) (* if T and T' are canonically ordered, *) (* then T *lexi[d] T' is canonically ordered in *) (* lexicographic order, *) (* i.e., (x1, x2) <= (y1, y2) = *) (* (x1 <= y1) && ((x1 >= y1) ==> (x2 <= y2)) *) (* and (x1, x2) < (y1, y2) = *) (* (x1 <= y1) && ((x1 >= y1) ==> (x2 < y2)) *) (* and displayed in display d *) (* T *l T' := T *lexi[lexi_display d d'] T' *) (* where d and d' are the displays of T and T', *) (* respectively, and lexi_display adds an extra ^l to *) (* all notations *) (* seqprod_with d T := seq T *) (* == an alias for seq, such that if T is canonically *) (* ordered, then seqprod_with d T is canonically ordered *) (* in product order, i.e., *) (* [:: x1, .., xn] <= [y1, .., yn] = *) (* (x1 <= y1) && ... && (xn <= yn) *) (* and displayed in display d *) (* n.-tupleprod[d] T == same with n.tuple T *) (* seqprod T := seqprod_with (seqprod_display d) T *) (* where d is the display of T, and seqprod_display adds *) (* an extra ^sp to all notations *) (* n.-tupleprod T := n.-tuple[seqprod_display d] T *) (* where d is the display of T *) (* seqlexi_with d T := seq T *) (* == an alias for seq, such that if T is canonically *) (* ordered, then seqprod_with d T is canonically ordered *) (* in lexicographic order, i.e., *) (* [:: x1, .., xn] <= [y1, .., yn] = *) (* (x1 <= x2) && ((x1 >= y1) ==> ((x2 <= y2) && ...)) *) (* and displayed in display d *) (* n.-tuplelexi[d] T == same with n.tuple T *) (* seqlexi T := lexiprod_with (seqlexi_display d) T *) (* where d is the display of T, and seqlexi_display adds *) (* an extra ^sl to all notations *) (* n.-tuplelexi T := n.-tuple[seqlexi_display d] T *) (* where d is the display of T *) (* {subset[d] T} := {set T} *) (* == an alias for set which is canonically ordered by the *) (* subset order and displayed in display d *) (* {subset T} := {subset[subset_display] T} *) (* *) (* The following notations are provided to build substructures: *) (* [SubChoice_isSubPreorder of U by <: with disp] == *) (* [SubChoice_isSubPreorder of U by <:] == preorderType mixin for a subType *) (* whose base type is a preorderType *) (* *) (* We provide expected instances of ordered types for bool, nat (for leq and *) (* and dvdn), 'I_n, 'I_n.+1 (with a top and bottom), nat for dvdn, *) (* T *prod[disp] T', T *lexi[disp] T', {t : T & T' x} (with lexicographic *) (* ordering), seqprod_with d T (using product order), seqlexi_with d T *) (* (with lexicographic ordering), n.-tupleprod[disp] (using product order), *) (* n.-tuplelexi[d] T (with lexicographic ordering), on {subset[disp] T} *) (* (using subset order) and all possible finite type instances. *) (* (Use `HB.about type` to discover the instances on type.) *) (* *) (* In order to get a canonical order on prod, seq, tuple or set, one may *) (* import modules DefaultProdOrder or DefaultProdLexiOrder, *) (* DefaultSeqProdOrder or DefaultSeqLexiOrder, *) (* DefaultTupleProdOrder or DefaultTupleLexiOrder, *) (* and DefaultSetSubsetOrder. *) (* *) (* We also provide specialized versions of some theorems from path.v. *) (* *) (* We provide Order.enum_val, Order.enum_rank, and Order.enum_rank_in, which *) (* are monotonic variations of enum_val, enum_rank, and enum_rank_in *) (* whenever the type is porderType, and their monotonicity is provided if *) (* this order is total. The theory is in the module Order (Order.enum_valK, *) (* Order.enum_rank_inK, etc) but Order.Enum can be imported to shorten these. *) (* *) (* We provide an opaque monotonous bijection tagnat.sig / tagnat.rank between *) (* the finite types {i : 'I_n & 'I_(p_ i)} and 'I_(\sum_i p_ i): *) (* tagnat.sig : 'I_(\sum_i p_ i) -> {i : 'I_n & 'I_(p_ i)} *) (* tagnat.rank : {i : 'I_n & 'I_(p_ i)} -> 'I_(\sum_i p_ i) *) (* tagnat.sig1 : 'I_(\sum_i p_ i) -> 'I_n *) (* tagnat.sig2 : forall p : 'I_(\sum_i p_ i), 'I_(p_ (tagnat.sig1 p)) *) (* tagnat.Rank : forall i, 'I_(p_ i) -> 'I_(\sum_i p_ i) *) (* *) (* Acknowledgments: This file is based on prior work by D. Dreyer, G. *) (* Gonthier, A. Nanevski, P-Y Strub, B. Ziliani *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope order_scope. Delimit Scope order_scope with O. Local Open Scope order_scope. Reserved Notation "<= y" (at level 35). Reserved Notation ">= y" (at level 35). Reserved Notation "< y" (at level 35). Reserved Notation "> y" (at level 35). Reserved Notation "<= y :> T" (at level 35, y at next level). Reserved Notation ">= y :> T" (at level 35, y at next level). Reserved Notation "< y :> T" (at level 35, y at next level). Reserved Notation "> y :> T" (at level 35, y at next level). Reserved Notation "x >=< y" (at level 70, no associativity). Reserved Notation ">=< y" (at level 35). Reserved Notation ">=< y :> T" (at level 35, y at next level). Reserved Notation "x >< y" (at level 70, no associativity). Reserved Notation ">< x" (at level 35). Reserved Notation ">< y :> T" (at level 35, y at next level). Reserved Notation "f \min g" (at level 50, left associativity). Reserved Notation "f \max g" (at level 50, left associativity). Reserved Notation "x < y ?<= 'if' c" (c at next level, format "x '[hv' < y '/' ?<= 'if' c ']'"). Reserved Notation "x < y ?<= 'if' c :> T" ( format "x '[hv' < y '/' ?<= 'if' c :> T ']'"). (* Reserved notations for bottom/top elements *) Reserved Notation "\bot". Reserved Notation "\top". (* Reserved notations for dual order *) Reserved Notation "x <=^d y" (at level 70, y at next level). Reserved Notation "x >=^d y" (at level 70, y at next level). Reserved Notation "x <^d y" (at level 70, y at next level). Reserved Notation "x >^d y" (at level 70, y at next level). Reserved Notation "x <=^d y :> T" (at level 70, y at next level). Reserved Notation "x >=^d y :> T" (at level 70, y at next level). Reserved Notation "x <^d y :> T" (at level 70, y at next level). Reserved Notation "x >^d y :> T" (at level 70, y at next level). Reserved Notation "<=^d y" (at level 35). Reserved Notation ">=^d y" (at level 35). Reserved Notation "<^d y" (at level 35). Reserved Notation ">^d y" (at level 35). Reserved Notation "<=^d y :> T" (at level 35, y at next level). Reserved Notation ">=^d y :> T" (at level 35, y at next level). Reserved Notation "<^d y :> T" (at level 35, y at next level). Reserved Notation ">^d y :> T" (at level 35, y at next level). Reserved Notation "x >=<^d y" (at level 70, no associativity). Reserved Notation ">=<^d y" (at level 35). Reserved Notation ">=<^d y :> T" (at level 35, y at next level). Reserved Notation "x ><^d y" (at level 70, no associativity). Reserved Notation "><^d x" (at level 35). Reserved Notation "><^d y :> T" (at level 35, y at next level). Reserved Notation "x <=^d y <=^d z" (at level 70, y, z at next level). Reserved Notation "x <^d y <=^d z" (at level 70, y, z at next level). Reserved Notation "x <=^d y <^d z" (at level 70, y, z at next level). Reserved Notation "x <^d y <^d z" (at level 70, y, z at next level). Reserved Notation "x <=^d y ?= 'iff' c" (at level 70, y, c at next level, format "x '[hv' <=^d y '/' ?= 'iff' c ']'"). Reserved Notation "x <=^d y ?= 'iff' c :> T" (at level 70, y, c at next level, format "x '[hv' <=^d y '/' ?= 'iff' c :> T ']'"). Reserved Notation "x <^d y ?<= 'if' c" (at level 70, y, c at next level, format "x '[hv' <^d y '/' ?<= 'if' c ']'"). Reserved Notation "x <^d y ?<= 'if' c :> T" (at level 70, y, c at next level, format "x '[hv' <^d y '/' ?<= 'if' c :> T ']'"). Reserved Notation "\bot^d". Reserved Notation "\top^d". (* Reserved notations for product ordering of prod *) Reserved Notation "x <=^p y" (at level 70, y at next level). Reserved Notation "x >=^p y" (at level 70, y at next level). Reserved Notation "x <^p y" (at level 70, y at next level). Reserved Notation "x >^p y" (at level 70, y at next level). Reserved Notation "x <=^p y :> T" (at level 70, y at next level). Reserved Notation "x >=^p y :> T" (at level 70, y at next level). Reserved Notation "x <^p y :> T" (at level 70, y at next level). Reserved Notation "x >^p y :> T" (at level 70, y at next level). Reserved Notation "<=^p y" (at level 35). Reserved Notation ">=^p y" (at level 35). Reserved Notation "<^p y" (at level 35). Reserved Notation ">^p y" (at level 35). Reserved Notation "<=^p y :> T" (at level 35, y at next level). Reserved Notation ">=^p y :> T" (at level 35, y at next level). Reserved Notation "<^p y :> T" (at level 35, y at next level). Reserved Notation ">^p y :> T" (at level 35, y at next level). Reserved Notation "x >=<^p y" (at level 70, no associativity). Reserved Notation ">=<^p x" (at level 35). Reserved Notation ">=<^p y :> T" (at level 35, y at next level). Reserved Notation "x ><^p y" (at level 70, no associativity). Reserved Notation "><^p x" (at level 35). Reserved Notation "><^p y :> T" (at level 35, y at next level). Reserved Notation "x <=^p y <=^p z" (at level 70, y, z at next level). Reserved Notation "x <^p y <=^p z" (at level 70, y, z at next level). Reserved Notation "x <=^p y <^p z" (at level 70, y, z at next level). Reserved Notation "x <^p y <^p z" (at level 70, y, z at next level). Reserved Notation "x <=^p y ?= 'iff' c" (at level 70, y, c at next level, format "x '[hv' <=^p y '/' ?= 'iff' c ']'"). Reserved Notation "x <=^p y ?= 'iff' c :> T" (at level 70, y, c at next level, format "x '[hv' <=^p y '/' ?= 'iff' c :> T ']'"). Reserved Notation "\bot^p". Reserved Notation "\top^p". (* Reserved notations for product ordering of seq *) Reserved Notation "x <=^sp y" (at level 70, y at next level). Reserved Notation "x >=^sp y" (at level 70, y at next level). Reserved Notation "x <^sp y" (at level 70, y at next level). Reserved Notation "x >^sp y" (at level 70, y at next level). Reserved Notation "x <=^sp y :> T" (at level 70, y at next level). Reserved Notation "x >=^sp y :> T" (at level 70, y at next level). Reserved Notation "x <^sp y :> T" (at level 70, y at next level). Reserved Notation "x >^sp y :> T" (at level 70, y at next level). Reserved Notation "<=^sp y" (at level 35). Reserved Notation ">=^sp y" (at level 35). Reserved Notation "<^sp y" (at level 35). Reserved Notation ">^sp y" (at level 35). Reserved Notation "<=^sp y :> T" (at level 35, y at next level). Reserved Notation ">=^sp y :> T" (at level 35, y at next level). Reserved Notation "<^sp y :> T" (at level 35, y at next level). Reserved Notation ">^sp y :> T" (at level 35, y at next level). Reserved Notation "x >=<^sp y" (at level 70, no associativity). Reserved Notation ">=<^sp x" (at level 35). Reserved Notation ">=<^sp y :> T" (at level 35, y at next level). Reserved Notation "x ><^sp y" (at level 70, no associativity). Reserved Notation "><^sp x" (at level 35). Reserved Notation "><^sp y :> T" (at level 35, y at next level). Reserved Notation "x <=^sp y <=^sp z" (at level 70, y, z at next level). Reserved Notation "x <^sp y <=^sp z" (at level 70, y, z at next level). Reserved Notation "x <=^sp y <^sp z" (at level 70, y, z at next level). Reserved Notation "x <^sp y <^sp z" (at level 70, y, z at next level). Reserved Notation "x <=^sp y ?= 'iff' c" (at level 70, y, c at next level, format "x '[hv' <=^sp y '/' ?= 'iff' c ']'"). Reserved Notation "x <=^sp y ?= 'iff' c :> T" (at level 70, y, c at next level, format "x '[hv' <=^sp y '/' ?= 'iff' c :> T ']'"). Reserved Notation "\bot^sp". Reserved Notation "\top^sp". (* Reserved notations for lexicographic ordering of prod *) Reserved Notation "x <=^l y" (at level 70, y at next level). Reserved Notation "x >=^l y" (at level 70, y at next level). Reserved Notation "x <^l y" (at level 70, y at next level). Reserved Notation "x >^l y" (at level 70, y at next level). Reserved Notation "x <=^l y :> T" (at level 70, y at next level). Reserved Notation "x >=^l y :> T" (at level 70, y at next level). Reserved Notation "x <^l y :> T" (at level 70, y at next level). Reserved Notation "x >^l y :> T" (at level 70, y at next level). Reserved Notation "<=^l y" (at level 35). Reserved Notation ">=^l y" (at level 35). Reserved Notation "<^l y" (at level 35). Reserved Notation ">^l y" (at level 35). Reserved Notation "<=^l y :> T" (at level 35, y at next level). Reserved Notation ">=^l y :> T" (at level 35, y at next level). Reserved Notation "<^l y :> T" (at level 35, y at next level). Reserved Notation ">^l y :> T" (at level 35, y at next level). Reserved Notation "x >=<^l y" (at level 70, no associativity). Reserved Notation ">=<^l x" (at level 35). Reserved Notation ">=<^l y :> T" (at level 35, y at next level). Reserved Notation "x ><^l y" (at level 70, no associativity). Reserved Notation "><^l x" (at level 35). Reserved Notation "><^l y :> T" (at level 35, y at next level). Reserved Notation "x <=^l y <=^l z" (at level 70, y, z at next level). Reserved Notation "x <^l y <=^l z" (at level 70, y, z at next level). Reserved Notation "x <=^l y <^l z" (at level 70, y, z at next level). Reserved Notation "x <^l y <^l z" (at level 70, y, z at next level). Reserved Notation "x <=^l y ?= 'iff' c" (at level 70, y, c at next level, format "x '[hv' <=^l y '/' ?= 'iff' c ']'"). Reserved Notation "x <=^l y ?= 'iff' c :> T" (at level 70, y, c at next level, format "x '[hv' <=^l y '/' ?= 'iff' c :> T ']'"). Reserved Notation "\bot^l". Reserved Notation "\top^l". (* Reserved notations for lexicographic ordering of seq *) Reserved Notation "x <=^sl y" (at level 70, y at next level). Reserved Notation "x >=^sl y" (at level 70, y at next level). Reserved Notation "x <^sl y" (at level 70, y at next level). Reserved Notation "x >^sl y" (at level 70, y at next level). Reserved Notation "x <=^sl y :> T" (at level 70, y at next level). Reserved Notation "x >=^sl y :> T" (at level 70, y at next level). Reserved Notation "x <^sl y :> T" (at level 70, y at next level). Reserved Notation "x >^sl y :> T" (at level 70, y at next level). Reserved Notation "<=^sl y" (at level 35). Reserved Notation ">=^sl y" (at level 35). Reserved Notation "<^sl y" (at level 35). Reserved Notation ">^sl y" (at level 35). Reserved Notation "<=^sl y :> T" (at level 35, y at next level). Reserved Notation ">=^sl y :> T" (at level 35, y at next level). Reserved Notation "<^sl y :> T" (at level 35, y at next level). Reserved Notation ">^sl y :> T" (at level 35, y at next level). Reserved Notation "x >=<^sl y" (at level 70, no associativity). Reserved Notation ">=<^sl x" (at level 35). Reserved Notation ">=<^sl y :> T" (at level 35, y at next level). Reserved Notation "x ><^sl y" (at level 70, no associativity). Reserved Notation "><^sl x" (at level 35). Reserved Notation "><^sl y :> T" (at level 35, y at next level). Reserved Notation "x <=^sl y <=^sl z" (at level 70, y, z at next level). Reserved Notation "x <^sl y <=^sl z" (at level 70, y, z at next level). Reserved Notation "x <=^sl y <^sl z" (at level 70, y, z at next level). Reserved Notation "x <^sl y <^sl z" (at level 70, y, z at next level). Reserved Notation "x <=^sl y ?= 'iff' c" (at level 70, y, c at next level, format "x '[hv' <=^sl y '/' ?= 'iff' c ']'"). Reserved Notation "x <=^sl y ?= 'iff' c :> T" (at level 70, y, c at next level, format "x '[hv' <=^sl y '/' ?= 'iff' c :> T ']'"). Reserved Notation "\bot^sl". Reserved Notation "\top^sl". (* Reserved notations for divisibility *) Reserved Notation "x %<| y" (at level 70, no associativity). Reserved Notation "\min_ i F" (at level 34, F at level 41, i at level 0, format "'[' \min_ i '/ ' F ']'"). Reserved Notation "\min_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \min_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\min_ ( i <- r ) F" (F at level 41, format "'[' \min_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\min_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \min_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\min_ ( m <= i < n ) F" (F at level 41, format "'[' \min_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\min_ ( i | P ) F" (F at level 41, format "'[' \min_ ( i | P ) '/ ' F ']'"). Reserved Notation "\min_ ( i : t | P ) F" (F at level 41). Reserved Notation "\min_ ( i : t ) F" (F at level 41). Reserved Notation "\min_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \min_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\min_ ( i < n ) F" (F at level 41, format "'[' \min_ ( i < n ) F ']'"). Reserved Notation "\min_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \min_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\min_ ( i 'in' A ) F" (F at level 41, format "'[' \min_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\max_ i F" (at level 34, F at level 41, i at level 0, format "'[' \max_ i '/ ' F ']'"). Reserved Notation "\max_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \max_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\max_ ( i <- r ) F" (F at level 41, format "'[' \max_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\max_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \max_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\max_ ( m <= i < n ) F" (F at level 41, format "'[' \max_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\max_ ( i | P ) F" (F at level 41, format "'[' \max_ ( i | P ) '/ ' F ']'"). Reserved Notation "\max_ ( i : t | P ) F" (F at level 41). Reserved Notation "\max_ ( i : t ) F" (F at level 41). Reserved Notation "\max_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \max_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\max_ ( i < n ) F" (F at level 41, format "'[' \max_ ( i < n ) F ']'"). Reserved Notation "\max_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \max_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\max_ ( i 'in' A ) F" (F at level 41, format "'[' \max_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\min^d_ i F" (at level 41, F at level 41, i at level 0, format "'[' \min^d_ i '/ ' F ']'"). Reserved Notation "\min^d_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \min^d_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\min^d_ ( i <- r ) F" (F at level 41, r at level 60, format "'[' \min^d_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\min^d_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \min^d_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\min^d_ ( m <= i < n ) F" (F at level 41, format "'[' \min^d_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\min^d_ ( i | P ) F" (F at level 41, format "'[' \min^d_ ( i | P ) '/ ' F ']'"). Reserved Notation "\min^d_ ( i : t | P ) F" (F at level 41). Reserved Notation "\min^d_ ( i : t ) F" (F at level 41). Reserved Notation "\min^d_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \min^d_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\min^d_ ( i < n ) F" (F at level 41, format "'[' \min^d_ ( i < n ) F ']'"). Reserved Notation "\min^d_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \min^d_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\min^d_ ( i 'in' A ) F" (F at level 41, format "'[' \min^d_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\max^d_ i F" (at level 41, F at level 41, i at level 0, format "'[' \max^d_ i '/ ' F ']'"). Reserved Notation "\max^d_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \max^d_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\max^d_ ( i <- r ) F" (F at level 41, r at level 60, format "'[' \max^d_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\max^d_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \max^d_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\max^d_ ( m <= i < n ) F" (F at level 41, format "'[' \max^d_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\max^d_ ( i | P ) F" (F at level 41, format "'[' \max^d_ ( i | P ) '/ ' F ']'"). Reserved Notation "\max^d_ ( i : t | P ) F" (F at level 41). Reserved Notation "\max^d_ ( i : t ) F" (F at level 41). Reserved Notation "\max^d_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \max^d_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\max^d_ ( i < n ) F" (F at level 41, format "'[' \max^d_ ( i < n ) F ']'"). Reserved Notation "\max^d_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \max^d_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\max^d_ ( i 'in' A ) F" (F at level 41, format "'[' \max^d_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "'{' 'omorphism' U '->' V '}'" (at level 0, U at level 98, V at level 99, format "{ 'omorphism' U -> V }"). Module Order. #[projections(primitive)] Record disp_t := Disp {d1 : unit; d2 : unit}. #[key="T", primitive] HB.mixin Record isDuallyPreorder (d : disp_t) T of Equality T := { le : rel T; lt : rel T; lt_def : forall x y, lt x y = (le x y) && ~~ (le y x); gt_def : forall x y, lt y x = (le y x) && ~~ (le x y); le_refl : reflexive le; ge_refl : reflexive (fun x y => le y x); le_trans : transitive le; ge_trans : transitive (fun x y => le y x); }. #[short(type="preorderType")] HB.structure Definition Preorder (d : disp_t) := { T of Choice T & isDuallyPreorder d T }. #[key="T", primitive] HB.mixin Record hasBottom d T of Preorder d T := { bottom : T; le0x : forall x, le bottom x; }. #[key="T", primitive] HB.mixin Record hasTop d T of Preorder d T := { top : T; lex1 : forall x, le x top; }. #[short(type="bPreorderType")] HB.structure Definition BPreorder d := { T of hasBottom d T & Preorder d T }. #[short(type="tPreorderType")] HB.structure Definition TPreorder d := { T of hasTop d T & Preorder d T }. #[short(type="tbPreorderType")] HB.structure Definition TBPreorder d := { T of hasTop d T & BPreorder d T }. Section PreorderDef. Variable (disp : disp_t) (T : preorderType disp). Local Notation "x <= y" := (le x y) : order_scope. Local Notation "x < y" := (lt x y) : order_scope. Definition comparable : rel T := fun (x y : T) => (x <= y) || (y <= x). Local Notation "x >=< y" := (comparable x y) : order_scope. Local Notation "x >< y" := (~~ (x >=< y)) : order_scope. Definition ge : simpl_rel T := [rel x y | y <= x]. Definition gt : simpl_rel T := [rel x y | y < x]. Definition leif (x y : T) C : Prop := ((x <= y) * ((x == y) = C))%type. Definition le_of_leif x y C (le_xy : @leif x y C) := le_xy.1 : le x y. Definition lteif (x y : T) C := if C then x <= y else x < y. Variant le_xor_gt (x y : T) : T -> T -> T -> T -> bool -> bool -> Set := | LeNotGt of x <= y : le_xor_gt x y x x y y true false | GtNotLe of y < x : le_xor_gt x y y y x x false true. Variant lt_xor_ge (x y : T) : T -> T -> T -> T -> bool -> bool -> Set := | LtNotGe of x < y : lt_xor_ge x y x x y y false true | GeNotLt of y <= x : lt_xor_ge x y y y x x true false. Definition min (x y : T) := if x < y then x else y. Definition max (x y : T) := if x < y then y else x. Variant compare (x y : T) : T -> T -> T -> T -> bool -> bool -> bool -> bool -> bool -> bool -> Set := | CompareLt of x < y : compare x y x x y y false false false true false true | CompareGt of y < x : compare x y y y x x false false true false true false | CompareEq of x = y : compare x y x x x x true true true true false false. Variant incompare (x y : T) : T -> T -> T -> T -> bool -> bool -> bool -> bool -> bool -> bool -> bool -> bool -> Set := | InCompareLt of x < y : incompare x y x x y y false false false true false true true true | InCompareGt of y < x : incompare x y y y x x false false true false true false true true | InCompare of x >< y : incompare x y x y y x false false false false false false false false | InCompareEq of x = y : incompare x y x x x x true true true true false false true true. Definition arg_min {I : finType} := @extremum T I le. Definition arg_max {I : finType} := @extremum T I ge. (* Lifted min/max operations. *) Section LiftedPreorder. Variable T' : Type. Implicit Type f : T' -> T. Definition min_fun f g x := min (f x) (g x). Definition max_fun f g x := max (f x) (g x). End LiftedPreorder. Definition nondecreasing disp' (T' : preorderType disp') (f : T -> T') : Prop := {homo f : x y / x <= y}. End PreorderDef. Prenex Implicits lt le leif lteif. Arguments ge {_ _}. Arguments gt {_ _}. Arguments min {_ _}. Arguments max {_ _}. Arguments comparable {_ _}. Arguments min_fun {_ _ _} f g _ /. Arguments max_fun {_ _ _} f g _ /. Module Import Def. Notation nondecreasing := nondecreasing. Notation min := min. Notation max := max. End Def. Module Import PreOSyntax. Notation "<=%O" := le : function_scope. Notation ">=%O" := ge : function_scope. Notation "<%O" := lt : function_scope. Notation ">%O" := gt : function_scope. Notation "<?=%O" := leif : function_scope. Notation "<?<=%O" := lteif : function_scope. Notation ">=<%O" := comparable : function_scope. Notation "><%O" := (fun x y => ~~ (comparable x y)) : function_scope. Notation "<= y" := (ge y) : order_scope. Notation "<= y :> T" := (<= (y : T)) (only parsing) : order_scope. Notation ">= y" := (le y) : order_scope. Notation ">= y :> T" := (>= (y : T)) (only parsing) : order_scope. Notation "< y" := (gt y) : order_scope. Notation "< y :> T" := (< (y : T)) (only parsing) : order_scope. Notation "> y" := (lt y) : order_scope. Notation "> y :> T" := (> (y : T)) (only parsing) : order_scope. Notation "x <= y" := (le x y) : order_scope. Notation "x <= y :> T" := ((x : T) <= (y : T)) (only parsing) : order_scope. Notation "x >= y" := (y <= x) (only parsing) : order_scope. Notation "x >= y :> T" := ((x : T) >= (y : T)) (only parsing) : order_scope. Notation "x < y" := (lt x y) : order_scope. Notation "x < y :> T" := ((x : T) < (y : T)) (only parsing) : order_scope. Notation "x > y" := (y < x) (only parsing) : order_scope. Notation "x > y :> T" := ((x : T) > (y : T)) (only parsing) : order_scope. Notation "x <= y <= z" := ((x <= y) && (y <= z)) : order_scope. Notation "x < y <= z" := ((x < y) && (y <= z)) : order_scope. Notation "x <= y < z" := ((x <= y) && (y < z)) : order_scope. Notation "x < y < z" := ((x < y) && (y < z)) : order_scope. Notation "x <= y ?= 'iff' C" := (leif x y C) : order_scope. Notation "x <= y ?= 'iff' C :> T" := ((x : T) <= (y : T) ?= iff C) (only parsing) : order_scope. Notation "x < y ?<= 'if' C" := (lteif x y C) : order_scope. Notation "x < y ?<= 'if' C :> T" := ((x : T) < (y : T) ?<= if C) (only parsing) : order_scope. Notation ">=< y" := [pred x | comparable x y] : order_scope. Notation ">=< y :> T" := (>=< (y : T)) (only parsing) : order_scope. Notation "x >=< y" := (comparable x y) : order_scope. Notation ">< y" := [pred x | ~~ comparable x y] : order_scope. Notation ">< y :> T" := (>< (y : T)) (only parsing) : order_scope. Notation "x >< y" := (~~ (comparable x y)) : order_scope. 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 ]") : order_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 ]") : order_scope. Notation "[ 'arg' 'min_' ( i < i0 ) F ]" := [arg min_(i < i0 | true) F] (i0 at level 10, format "[ 'arg' 'min_' ( i < i0 ) F ]") : order_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 ]") : order_scope. Notation "[ 'arg' 'max_' ( i > i0 'in' A ) F ]" := [arg max_(i > i0 | i \in A) F] (i, i0 at level 10, format "[ 'arg' 'max_' ( i > i0 'in' A ) F ]") : order_scope. Notation "[ 'arg' 'max_' ( i > i0 ) F ]" := [arg max_(i > i0 | true) F] (i, i0 at level 10, format "[ 'arg' 'max_' ( i > i0 ) F ]") : order_scope. Notation "f \min g" := (min_fun f g) : function_scope. Notation "f \max g" := (max_fun f g) : function_scope. Notation leLHS := (X in (X <= _)%O)%pattern. Notation leRHS := (X in (_ <= X)%O)%pattern. Notation ltLHS := (X in (X < _)%O)%pattern. Notation ltRHS := (X in (_ < X)%O)%pattern. Notation "\bot" := bottom : order_scope. Notation "\top" := top : order_scope. End PreOSyntax. HB.export PreOSyntax. Module PreOCoercions. Coercion le_of_leif : leif >-> is_true. End PreOCoercions. HB.export PreOCoercions. (**********) (* FINITE *) (**********) #[short(type="finPreorderType")] HB.structure Definition FinPreorder d := { T of Finite T & Preorder d T }. #[short(type="finBPreorderType")] HB.structure Definition FinBPreorder d := { T of FinPreorder d T & hasBottom d T }. #[short(type="finTPreorderType")] HB.structure Definition FinTPreorder d := { T of FinPreorder d T & hasTop d T }. #[short(type="finTBPreorderType")] HB.structure Definition FinTBPreorder d := { T of FinBPreorder d T & hasTop d T }. (********) (* DUAL *) (********) Definition dual T : Type := T. Definition dual_display (d : disp_t) := {| d1 := d2 d; d2 := d1 d |}. Notation dual_le := (@le (dual_display _) _). Notation dual_lt := (@lt (dual_display _) _). Notation dual_comparable := (@comparable (dual_display _) _). Notation dual_ge := (@ge (dual_display _) _). Notation dual_gt := (@gt (dual_display _) _). Notation dual_leif := (@leif (dual_display _) _). Notation dual_lteif := (@lteif (dual_display _) _). Notation dual_max := (@max (dual_display _) _). Notation dual_min := (@min (dual_display _) _). Notation dual_bottom := (@bottom (dual_display _) _). Notation dual_top := (@top (dual_display _) _). Module Import DualSyntax. Notation "T ^d" := (dual T) (format "T ^d") : type_scope. Notation "<=^d%O" := dual_le : function_scope. Notation ">=^d%O" := dual_ge : function_scope. Notation "<^d%O" := dual_lt : function_scope. Notation ">^d%O" := dual_gt : function_scope. Notation "<?=^d%O" := dual_leif : function_scope. Notation "<?<=^d%O" := dual_lteif : function_scope. Notation ">=<^d%O" := dual_comparable : function_scope. Notation "><^d%O" := (fun x y => ~~ dual_comparable x y) : function_scope. Notation "<=^d y" := (>=^d%O y) : order_scope. Notation "<=^d y :> T" := (<=^d (y : T)) (only parsing) : order_scope. Notation ">=^d y" := (<=^d%O y) : order_scope. Notation ">=^d y :> T" := (>=^d (y : T)) (only parsing) : order_scope. Notation "<^d y" := (>^d%O y) : order_scope. Notation "<^d y :> T" := (<^d (y : T)) (only parsing) : order_scope. Notation ">^d y" := (<^d%O y) : order_scope. Notation ">^d y :> T" := (>^d (y : T)) (only parsing) : order_scope. Notation "x <=^d y" := (<=^d%O x y) : order_scope. Notation "x <=^d y :> T" := ((x : T) <=^d (y : T)) (only parsing) : order_scope. Notation "x >=^d y" := (y <=^d x) (only parsing) : order_scope. Notation "x >=^d y :> T" := ((x : T) >=^d (y : T)) (only parsing) : order_scope. Notation "x <^d y" := (<^d%O x y) : order_scope. Notation "x <^d y :> T" := ((x : T) <^d (y : T)) (only parsing) : order_scope. Notation "x >^d y" := (y <^d x) (only parsing) : order_scope. Notation "x >^d y :> T" := ((x : T) >^d (y : T)) (only parsing) : order_scope. Notation "x <=^d y <=^d z" := ((x <=^d y) && (y <=^d z)) : order_scope. Notation "x <^d y <=^d z" := ((x <^d y) && (y <=^d z)) : order_scope. Notation "x <=^d y <^d z" := ((x <=^d y) && (y <^d z)) : order_scope. Notation "x <^d y <^d z" := ((x <^d y) && (y <^d z)) : order_scope. Notation "x <=^d y ?= 'iff' C" := (<?=^d%O x y C) : order_scope. Notation "x <=^d y ?= 'iff' C :> T" := ((x : T) <=^d (y : T) ?= iff C) (only parsing) : order_scope. Notation "x <^d y ?<= 'if' C" := (<?<=^d%O x y C) : order_scope. Notation "x <^d y ?<= 'if' C :> T" := ((x : T) <^d (y : T) ?<= if C) (only parsing) : order_scope. Notation ">=<^d x" := (>=<^d%O x) : order_scope. Notation ">=<^d y :> T" := (>=<^d (y : T)) (only parsing) : order_scope. Notation "x >=<^d y" := (>=<^d%O x y) : order_scope. Notation "><^d y" := [pred x | ~~ dual_comparable x y] : order_scope. Notation "><^d y :> T" := (><^d (y : T)) (only parsing) : order_scope. Notation "x ><^d y" := (~~ (><^d%O x y)) : order_scope. Notation "\bot^d" := dual_bottom : order_scope. Notation "\top^d" := dual_top : order_scope. End DualSyntax. Module DualPreorder. HB.instance Definition _ (T : eqType) := Equality.on T^d. HB.instance Definition _ (T : choiceType) := Choice.on T^d. HB.instance Definition _ (T : countType) := Countable.on T^d. HB.instance Definition _ (T : finType) := Finite.on T^d. HB.instance Definition _ (d : disp_t) (T : preorderType d) := isDuallyPreorder.Build (dual_display d) T^d gt_def lt_def ge_refl le_refl ge_trans le_trans. Lemma leEdual (d : disp_t) (T : preorderType d) (x y : T) : (x <=^d y :> T^d) = (y <= x). Proof. by []. Qed. Lemma ltEdual (d : disp_t) (T : preorderType d) (x y : T) : (x <^d y :> T^d) = (y < x). Proof. by []. Qed. HB.instance Definition _ d (T : tPreorderType d) := hasBottom.Build (dual_display d) T^d lex1. Lemma botEdual d (T : tPreorderType d) : (dual_bottom : T^d) = \top :> T. Proof. by []. Qed. HB.instance Definition _ d (T : bPreorderType d) := hasTop.Build (dual_display d) T^d le0x. Lemma topEdual d (T : bPreorderType d) : (dual_top : T^d) = \bot :> T. Proof. by []. Qed. End DualPreorder. HB.export DualPreorder. (**********) (* THEORY *) (**********) Module Import PreorderTheory. Section PreorderTheory. Context {disp : disp_t} {T : preorderType disp}. Implicit Types (x y : T) (s : seq T). Definition nondecreasing disp' (T' : preorderType disp') (f : T -> T') : Prop := {homo f : x y / x <= y}. Lemma geE x y : ge x y = (y <= x). Proof. by []. Qed. Lemma gtE x y : gt x y = (y < x). Proof. by []. Qed. Lemma lexx (x : T) : x <= x. Proof. exact: le_refl. Qed. Hint Resolve lexx : core. Definition le_refl : reflexive le := lexx. Definition ge_refl : reflexive ge := lexx. Hint Resolve le_refl : core. Lemma le_trans: transitive (<=%O : rel T). Proof. exact: le_trans. Qed. Lemma ge_trans: transitive (>=%O : rel T). Proof. by move=> ? ? ? ? /le_trans; apply. Qed. Lemma le_le_trans x y z t : z <= x -> y <= t -> x <= y -> z <= t. Proof. by move=> + /(le_trans _)/[apply]; apply: le_trans. Qed. Lemma lt_le_def x y: (x < y) = (x <= y) && ~~ (y <= x). Proof. exact: lt_def. Qed. Lemma ltxx x: x < x = false. Proof. by rewrite lt_le_def andbN. Qed. Definition lt_irreflexive : irreflexive lt := ltxx. Hint Resolve lt_irreflexive : core. Definition ltexx := (lexx, ltxx). Lemma lt_eqF x y: x < y -> x == y = false. Proof. by apply: contraTF => /eqP ->; rewrite ltxx. Qed. Lemma gt_eqF x y : y < x -> x == y = false. Proof. by move=> /lt_eqF; rewrite eq_sym. Qed. Lemma ltW x y: x < y -> x <= y. Proof. by rewrite lt_le_def => /andP[]. Qed. Lemma lt_le_trans y x z: x < y -> y <= z -> x < z. Proof. rewrite !lt_le_def => /andP[] xy /negP yx yz. apply/andP; split; first exact/(le_trans xy). by apply/negP => /(le_trans yz). Qed. Lemma lt_trans: transitive (<%O : rel T). Proof. by move=> y x z le1 /ltW le2; apply/(@lt_le_trans y). Qed. Lemma le_lt_trans y x z: x <= y -> y < z -> x < z. Proof. rewrite !lt_le_def => xy /andP[] yz /negP zy. apply/andP; split; first exact/(le_trans xy). by apply/negP => /(fun zx => le_trans zx xy). Qed. Lemma lt_nsym x y : x < y -> y < x -> False. Proof. by move=> xy /(lt_trans xy); rewrite ltxx. Qed. Lemma lt_asym x y : x < y < x = false. Proof. by apply/negP => /andP []; apply: lt_nsym. Qed. Lemma le_gtF x y: x <= y -> y < x = false. Proof. by move=> le_xy; apply/negP => /lt_le_trans /(_ le_xy); rewrite ltxx. Qed. Lemma lt_geF x y : x < y -> y <= x = false. Proof. by apply: contraTF => /le_gtF ->. Qed. Definition lt_gtF x y hxy := le_gtF (@ltW x y hxy). Lemma lt_leAnge x y : (x < y) = (x <= y) && ~~ (y <= x). Proof. exact: lt_le_def. Qed. Lemma lt_le_asym x y : x < y <= x = false. Proof. by apply/negP; move=> /andP[] xy /(lt_le_trans xy); rewrite ltxx. Qed. Lemma le_lt_asym x y : x <= y < x = false. Proof. by rewrite andbC lt_le_asym. Qed. Lemma le_path_min x s : path <=%O x s -> all (>= x) s. Proof. exact/order_path_min/le_trans. Qed. Lemma lt_path_min x s : path <%O x s -> all (> x) s. Proof. exact/order_path_min/lt_trans. Qed. Lemma le_path_sortedE x s : path <=%O x s = all (>= x) s && sorted <=%O s. Proof. exact/path_sortedE/le_trans. Qed. Lemma lt_path_sortedE x s : path <%O x s = all (> x) s && sorted <%O s. Proof. exact/path_sortedE/lt_trans. Qed. Lemma le_sorted_pairwise s : sorted <=%O s = pairwise <=%O s. Proof. exact/sorted_pairwise/le_trans. Qed. Lemma lt_sorted_pairwise s : sorted <%O s = pairwise <%O s. Proof. exact/sorted_pairwise/lt_trans. Qed. Lemma le_path_pairwise x s : path <=%O x s = pairwise <=%O (x :: s). Proof. exact/path_pairwise/le_trans. Qed. Lemma lt_path_pairwise x s : path <%O x s = pairwise <%O (x :: s). Proof. exact/path_pairwise/lt_trans. Qed. Lemma lt_sorted_is_uniq_le s : sorted <%O s -> uniq s && sorted <=%O s. Proof. rewrite le_sorted_pairwise lt_sorted_pairwise uniq_pairwise -pairwise_relI. apply/sub_pairwise => x y/= /[dup] + /ltW ->. by case: eqVneq => // ->; rewrite ltxx. Qed. Lemma le_sorted_mask m s : sorted <=%O s -> sorted <=%O (mask m s). Proof. exact/sorted_mask/le_trans. Qed. Lemma lt_sorted_mask m s : sorted <%O s -> sorted <%O (mask m s). Proof. exact/sorted_mask/lt_trans. Qed. Lemma le_sorted_filter a s : sorted <=%O s -> sorted <=%O (filter a s). Proof. exact/sorted_filter/le_trans. Qed. Lemma lt_sorted_filter a s : sorted <%O s -> sorted <%O (filter a s). Proof. exact/sorted_filter/lt_trans. Qed. Lemma le_path_mask x m s : path <=%O x s -> path <=%O x (mask m s). Proof. exact/path_mask/le_trans. Qed. Lemma lt_path_mask x m s : path <%O x s -> path <%O x (mask m s). Proof. exact/path_mask/lt_trans. Qed. Lemma le_path_filter x a s : path <=%O x s -> path <=%O x (filter a s). Proof. exact/path_filter/le_trans. Qed. Lemma lt_path_filter x a s : path <%O x s -> path <%O x (filter a s). Proof. exact/path_filter/lt_trans. Qed. Lemma le_sorted_ltn_nth (x0 : T) (s : seq T) : sorted <=%O s -> {in [pred n | (n < size s)%N] &, {homo nth x0 s : i j / (i < j)%N >-> i <= j}}. Proof. exact/sorted_ltn_nth/le_trans. Qed. Lemma le_sorted_leq_nth (x0 : T) (s : seq T) : sorted <=%O s -> {in [pred n | (n < size s)%N] &, {homo nth x0 s : i j / (i <= j)%N >-> i <= j}}. Proof. exact/sorted_leq_nth/le_refl/le_trans. Qed. Lemma lt_sorted_leq_nth (x0 : T) (s : seq T) : sorted <%O s -> {in [pred n | (n < size s)%N] &, {mono nth x0 s : i j / (i <= j)%N >-> i <= j}}. Proof. move=> /[dup] lt_s /lt_sorted_is_uniq_le /andP[s_uniq le_s] i j ilt jlt. case/boolP: (i <= j)%N; first exact/le_sorted_leq_nth. rewrite -ltnNge => /(sorted_ltn_nth lt_trans x0 lt_s j i jlt ilt). by rewrite lt_le_def => /andP[_] /negPf. Qed. Lemma lt_sorted_ltn_nth (x0 : T) (s : seq T) : sorted <%O s -> {in [pred n | (n < size s)%N] &, {mono nth x0 s : i j / (i < j)%N >-> i < j}}. Proof. move=> ss i j ilt jlt. rewrite lt_le_def (lt_sorted_leq_nth x0 ss)// (lt_sorted_leq_nth x0 ss)//. by rewrite -ltnNge andbC ltn_neqAle -andbA andbb. Qed. Lemma subseq_le_path x s1 s2 : subseq s1 s2 -> path <=%O x s2 -> path <=%O x s1. Proof. exact/subseq_path/le_trans. Qed. Lemma subseq_lt_path x s1 s2 : subseq s1 s2 -> path <%O x s2 -> path <%O x s1. Proof. exact/subseq_path/lt_trans. Qed. Lemma subseq_le_sorted s1 s2 : subseq s1 s2 -> sorted <=%O s2 -> sorted <=%O s1. Proof. exact/subseq_sorted/le_trans. Qed. Lemma subseq_lt_sorted s1 s2 : subseq s1 s2 -> sorted <%O s2 -> sorted <%O s1. Proof. exact/subseq_sorted/lt_trans. Qed. Lemma lt_sorted_uniq s : sorted <%O s -> uniq s. Proof. exact/sorted_uniq/ltxx/lt_trans. Qed. Lemma lt_sorted_eq s1 s2 : sorted <%O s1 -> sorted <%O s2 -> s1 =i s2 -> s1 = s2. Proof. exact/irr_sorted_eq/ltxx/lt_trans. Qed. Lemma filter_lt_nth x0 s i : sorted <%O s -> (i < size s)%N -> [seq x <- s | x < nth x0 s i] = take i s. Proof. move=> ss i_lt/=; rewrite -[X in filter _ X](mkseq_nth x0) filter_map. under eq_in_filter => j do [rewrite ?mem_iota => j_s /=; rewrite lt_sorted_ltn_nth//]. by rewrite (filter_iota_ltn 0) ?map_nth_iota0 // ltnW. Qed. Lemma count_lt_nth x0 s i : sorted <%O s -> (i < size s)%N -> count (< nth x0 s i) s = i. Proof. by move=> ss i_lt; rewrite -size_filter/= filter_lt_nth// size_take i_lt. Qed. Lemma filter_le_nth x0 s i : sorted <%O s -> (i < size s)%N -> [seq x <- s | x <= nth x0 s i] = take i.+1 s. Proof. move=> ss i_lt/=; rewrite -[X in filter _ X](mkseq_nth x0) filter_map. under eq_in_filter => j do [rewrite ?mem_iota => j_s /=; rewrite lt_sorted_leq_nth//]. by rewrite (filter_iota_leq 0)// map_nth_iota0. Qed. Lemma count_le_nth x0 s i : sorted <%O s -> (i < size s)%N -> count (<= nth x0 s i) s = i.+1. Proof. by move=> ss i_lt; rewrite -size_filter/= filter_le_nth// size_takel. Qed. Lemma sorted_filter_lt x s : sorted <=%O s -> [seq y <- s | y < x] = take (count (< x) s) s. Proof. elim: s => [//|y s IHs]/=; rewrite (path_sortedE le_trans) => /andP[le_y_s ss]. case: ifP => [|ltyxF]; rewrite IHs//. rewrite (@eq_in_count _ _ pred0) ?count_pred0/= ?take0// => z. by move=> /(allP le_y_s) yz; apply: contraFF ltyxF; apply: le_lt_trans. Qed. Lemma sorted_filter_le x s : sorted <=%O s -> [seq y <- s | y <= x] = take (count (<= x) s) s. Proof. elim: s => [//|y s IHs]/=; rewrite (path_sortedE le_trans) => /andP[le_y_s ss]. case: ifP => [|leyxF]; rewrite IHs//. rewrite (@eq_in_count _ _ pred0) ?count_pred0/= ?take0// => z. by move=> /(allP le_y_s) yz; apply: contraFF leyxF; apply: le_trans. Qed. Lemma nth_count_le x x0 s i : sorted <=%O s -> (i < count (<= x) s)%N -> nth x0 s i <= x. Proof. move=> ss iltc; rewrite -(nth_take _ iltc) -sorted_filter_le //. by apply/(all_nthP _ (filter_all (<= x) _)); rewrite size_filter. Qed. Lemma nth_count_lt x x0 s i : sorted <=%O s -> (i < count (< x) s)%N -> nth x0 s i < x. Proof. move=> ss iltc; rewrite -(nth_take _ iltc) -sorted_filter_lt //. by apply/(all_nthP _ (filter_all (< x) _)); rewrite size_filter. Qed. Lemma sort_le_id s : sorted <=%O s -> sort <=%O s = s. Proof. exact/sorted_sort/le_trans. Qed. Lemma sort_lt_id s : sorted <%O s -> sort <%O s = s. Proof. exact/sorted_sort/lt_trans. Qed. Lemma comparable_leNgt x y : x >=< y -> (x <= y) = ~~ (y < x). Proof. rewrite /comparable lt_le_def. by case: (x <= y) => //=; case: (y <= x). Qed. Lemma comparable_ltNge x y : x >=< y -> (x < y) = ~~ (y <= x). Proof. rewrite /comparable lt_le_def. by case: (x <= y) => //=; case: (y <= x). Qed. Lemma comparable_sym x y : (y >=< x) = (x >=< y). Proof. by rewrite /comparable orbC. Qed. Lemma comparablexx x : x >=< x. Proof. by rewrite /comparable lexx. Qed. Lemma incomparable_eqF x y : (x >< y) -> (x == y) = false. Proof. by apply: contraNF => /eqP ->; rewrite comparablexx. Qed. Lemma incomparable_leF x y : (x >< y) -> (x <= y) = false. Proof. by apply: contraNF; rewrite /comparable => ->. Qed. Lemma incomparable_ltF x y : (x >< y) -> (x < y) = false. Proof. by rewrite lt_le_def => /incomparable_leF ->. Qed. Lemma le_comparable (x y : T) : x <= y -> x >=< y. Proof. by rewrite /comparable => ->. Qed. Lemma lt_comparable (x y : T) : x < y -> x >=< y. Proof. by rewrite /comparable => /ltW ->. Qed. Lemma ge_comparable (x y : T) : y <= x -> x >=< y. Proof. by rewrite /comparable orbC => ->. Qed. Lemma gt_comparable (x y : T) : y < x -> x >=< y. Proof. by rewrite /comparable orbC => /ltW ->. Qed. (* leif *) Lemma leif_refl x C : reflect (x <= x ?= iff C) C. Proof. by apply: (iffP idP) => [-> | <-] //; split; rewrite ?eqxx. Qed. Lemma eq_leif x y C : x <= y ?= iff C -> (x == y) = C. Proof. by move=> []. Qed. Lemma eqTleif x y C : x <= y ?= iff C -> C -> x = y. Proof. by move=> [] _ <- /eqP. Qed. (* lteif *) Lemma lteif_trans x y z C1 C2 : x < y ?<= if C1 -> y < z ?<= if C2 -> x < z ?<= if C1 && C2. Proof. case: C1 C2 => [][]; [exact: le_trans | exact: le_lt_trans | exact: lt_le_trans | exact: lt_trans]. Qed. Lemma lteifxx x C : (x < x ?<= if C) = C. Proof. by case: C; rewrite /= ltexx. Qed. Lemma lteifNF x y C : y < x ?<= if ~~ C -> x < y ?<= if C = false. Proof. by case: C => [/lt_geF|/le_gtF]. Qed. Lemma lteifS x y C : x < y -> x < y ?<= if C. Proof. by case: C => //= /ltW. Qed. Lemma lteifT x y : x < y ?<= if true = (x <= y). Proof. by []. Qed. Lemma lteifF x y : x < y ?<= if false = (x < y). Proof. by []. Qed. Lemma lteif_orb x y : {morph lteif x y : p q / p || q}. Proof. case=> [][] /=. - by rewrite orbb. - by case/boolP: (x < y) => [/ltW -> //|_]; rewrite orbF. - by case/boolP: (x < y) => [/ltW ->|]. - by rewrite orbb. Qed. Lemma lteif_andb x y : {morph lteif x y : p q / p && q}. Proof. case=> [][] /=. - by rewrite andbb. - by rewrite lt_le_def andbA andbb. - by rewrite andbC lt_le_def andbA andbb. - by rewrite andbb. Qed. Lemma lteif_imply C1 C2 x y : C1 ==> C2 -> x < y ?<= if C1 -> x < y ?<= if C2. Proof. by case: C1 C2 => [][] //= _ /ltW. Qed. Lemma lteifW C x y : x < y ?<= if C -> x <= y. Proof. by case: C => // /ltW. Qed. Lemma ltrW_lteif C x y : x < y -> x < y ?<= if C. Proof. by case: C => // /ltW. Qed. (* min and max *) Lemma minElt x y : min x y = if x < y then x else y. Proof. by []. Qed. Lemma maxElt x y : max x y = if x < y then y else x. Proof. by []. Qed. Lemma minxx : idempotent_op (min : T -> T -> T). Proof. by rewrite /min => x; rewrite ltxx. Qed. Lemma maxxx : idempotent_op (max : T -> T -> T). Proof. by rewrite /max => x; rewrite ltxx. Qed. Lemma min_minKx x y : min (min x y) y = min x y. Proof. by rewrite !(fun_if, if_arg) ltxx/=; case: (x < y). Qed. Lemma min_minxK x y : min x (min x y) = min x y. Proof. by rewrite !(fun_if, if_arg) ltxx/=; case: (x < y). Qed. Lemma max_maxKx x y : max (max x y) y = max x y. Proof. by rewrite !(fun_if, if_arg) ltxx/=; case: (x < y). Qed. Lemma max_maxxK x y : max x (max x y) = max x y. Proof. by rewrite !(fun_if, if_arg) ltxx/=; case: (x < y). Qed. Lemma comparable_minl z : {in >=< z &, forall x y, min x y >=< z}. Proof. by move=> x y cmp_xz cmp_yz; rewrite /min; case: ifP. Qed. Lemma comparable_minr z : {in >=<%O z &, forall x y, z >=< min x y}. Proof. by move=> x y cmp_xz cmp_yz; rewrite /min; case: ifP. Qed. Lemma comparable_maxl z : {in >=< z &, forall x y, max x y >=< z}. Proof. by move=> x y cmp_xz cmp_yz; rewrite /max; case: ifP. Qed. Lemma comparable_maxr z : {in >=<%O z &, forall x y, z >=< max x y}. Proof. by move=> x y cmp_xz cmp_yz; rewrite /max; case: ifP. Qed. Section Comparable2. Variables (z x y : T) (cmp_xy : x >=< y). Lemma comparable_le_min : (z <= min x y) = (z <= x) && (z <= y). Proof. move: cmp_xy; rewrite /min /comparable lt_le_def. case/boolP: (x <= y) => xy/=; case/boolP: (y <= x) => yx//= _. - by rewrite andbC; case/boolP: (z <= y) => zy //=; apply/esym/(le_trans zy). - by case/boolP: (z <= x) => zx //=; apply/esym/(le_trans zx). - by rewrite andbC; case/boolP: (z <= y) => zy //=; apply/esym/(le_trans zy). Qed. Lemma comparable_ge_min : (min x y <= z) = (x <= z) || (y <= z). Proof. move: cmp_xy; rewrite /min /comparable lt_le_def. case/boolP: (x <= y) => xy/=; case/boolP: (y <= x) => yx//= _. - rewrite orbC; case/boolP: (y <= z) => //= /negP yz. by apply/esym/negP => /(le_trans yx). - by case/boolP: (x <= z) => //= /negP xz; apply/esym/negP => /(le_trans xy). - rewrite orbC; case/boolP: (y <= z) => //= /negP yz. by apply/esym/negP => /(le_trans yx). Qed. Lemma comparable_lt_min : (z < min x y) = (z < x) && (z < y). Proof. move: cmp_xy; rewrite /min /comparable !lt_le_def. case/boolP: (x <= y) => xy/=; case/boolP: (y <= x) => yx//= _. - rewrite -!lt_le_def; case/boolP: (z < x) => //= /negP zx. by apply/negP => zy; apply/zx/(lt_le_trans zy). - rewrite -!lt_le_def; case/boolP: (z < x) => //= zx; apply/esym/(lt_trans zx). by rewrite lt_le_def xy yx. - rewrite -!lt_le_def andbC; case/boolP: (z < y) => //= zy; apply/esym/(lt_trans zy). by rewrite lt_le_def xy yx. Qed. Lemma comparable_gt_min : (min x y < z) = (x < z) || (y < z). Proof. move: cmp_xy; rewrite /min /comparable !lt_le_def. case/boolP: (x <= y) => xy/=; case/boolP: (y <= x) => yx//= _. - rewrite -!lt_le_def orbC; case/boolP: (y < z) => //= /negP yz. by apply/esym/negP => xz; apply/yz/(le_lt_trans yx). - rewrite -!lt_le_def; case/boolP: (x < z) => //= /negP xz. by apply/esym/negP => yz; apply/xz/(le_lt_trans xy). - rewrite -!lt_le_def orbC; case/boolP: (y < z) => //= /negP yz. by apply/esym/negP => xz; apply/yz/(le_lt_trans yx). Qed. Lemma comparable_le_max : (z <= max x y) = (z <= x) || (z <= y). Proof. move: cmp_xy; rewrite /max /comparable lt_le_def. case/boolP: (x <= y) => xy/=; case/boolP: (y <= x) => yx//= _. - case/boolP: (z <= x) => //= /negP zx. by apply/esym/negP => zy; apply/zx/(le_trans zy). - rewrite orbC; case/boolP: (z <= y) => //= /negP zy. by apply/esym/negP => zx; apply/zy/(le_trans zx). - case/boolP: (z <= x) => //= /negP zx. by apply/esym/negP => zy; apply/zx/(le_trans zy). Qed. Lemma comparable_ge_max : (max x y <= z) = (x <= z) && (y <= z). Proof. move: cmp_xy; rewrite /max /comparable lt_le_def. case/boolP: (x <= y) => xy/=; case/boolP: (y <= x) => yx//= _. - case/boolP: (x <= z) => //= xz. by apply/esym/(le_trans yx). - rewrite andbC; case/boolP: (y <= z) => //= yz. by apply/esym/(le_trans xy). - case/boolP: (x <= z) => //= xz. by apply/esym/(le_trans yx). Qed. Lemma comparable_lt_max : (z < max x y) = (z < x) || (z < y). Proof. move: cmp_xy; rewrite /max /comparable !lt_le_def. case/boolP: (x <= y) => xy/=; case/boolP: (y <= x) => yx//= _. - rewrite -!lt_le_def; case/boolP: (z < x) => //= /negP zx. by apply/esym/negP => zy; apply/zx/(lt_le_trans zy). - rewrite -!lt_le_def orbC; case/boolP: (z < y) => //= /negP zy. by apply/esym/negP => zx; apply/zy/(lt_le_trans zx). - rewrite -!lt_le_def; case/boolP: (z < x) => //= /negP zx. by apply/esym/negP => zy; apply/zx/(lt_le_trans zy). Qed. Lemma comparable_gt_max : (max x y < z) = (x < z) && (y < z). Proof. move: cmp_xy; rewrite /max /comparable !lt_le_def. case/boolP: (x <= y) => xy/=; case/boolP: (y <= x) => yx//= _. - rewrite -!lt_le_def; case/boolP: (x < z) => //= xz. by apply/esym/(le_lt_trans yx). - rewrite -!lt_le_def andbC; case/boolP: (y < z) => //= yz. by apply/esym/(le_lt_trans xy). - rewrite -!lt_le_def; case/boolP: (x < z) => //= xz. by apply/esym/(le_lt_trans yx). Qed. Lemma comparable_minxK : max (min x y) y = y. Proof. by rewrite !(fun_if, if_arg) ltxx/=; case: (x < y). Qed. Lemma comparable_minKx : max x (min x y) = x. Proof. by rewrite !(fun_if, if_arg) ltxx/=; case: (x < y). Qed. Lemma comparable_maxxK : min (max x y) y = y. Proof. by rewrite !(fun_if, if_arg) ltxx/=; case: (x < y). Qed. Lemma comparable_maxKx : min x (max x y) = x. Proof. by rewrite !(fun_if, if_arg) ltxx/=; case: (x < y). Qed. Lemma comparable_lteif_minr C : (z < min x y ?<= if C) = (z < x ?<= if C) && (z < y ?<= if C). Proof. by case: C; rewrite /= (comparable_le_min, comparable_lt_min). Qed. Lemma comparable_lteif_minl C : (min x y < z ?<= if C) = (x < z ?<= if C) || (y < z ?<= if C). Proof. by case: C; rewrite /= (comparable_ge_min, comparable_gt_min). Qed. Lemma comparable_lteif_maxr C : (z < max x y ?<= if C) = (z < x ?<= if C) || (z < y ?<= if C). Proof. by case: C; rewrite /= (comparable_le_max, comparable_lt_max). Qed. Lemma comparable_lteif_maxl C : (max x y < z ?<= if C) = (x < z ?<= if C) && (y < z ?<= if C). Proof. by case: C; rewrite /= (comparable_ge_max, comparable_gt_max). Qed. End Comparable2. Section Comparable3. Variables (x y z : T) (cmp_xy : x >=< y) (cmp_xz : x >=< z) (cmp_yz : y >=< z). Lemma comparable_minA : min x (min y z) = min (min x y) z. Proof. move: cmp_xy cmp_xz cmp_yz; rewrite !(fun_if, if_arg)/= !lt_le_def. case/boolP: (x <= y) => xy; case/boolP: (y <= x) => yx; case/boolP: (x <= z) => xz; case/boolP: (z <= x) => zx; case/boolP: (y <= z) => yz; case/boolP: (z <= y) => zy //= _ _ _. - by move: zx; rewrite (le_trans zy yx). - by move: zx; rewrite (le_trans zy yx). - by move: zy; rewrite (le_trans zx xy). - by move: zy; rewrite (le_trans zx xy). - by move: zx; rewrite (le_trans zy yx). - by move: zx; rewrite (le_trans zy yx). Qed. Lemma comparable_maxA : max x (max y z) = max (max x y) z. Proof. move: cmp_xy cmp_xz cmp_yz; rewrite !(fun_if, if_arg)/= !lt_le_def. case/boolP: (x <= y) => xy; case/boolP: (y <= x) => yx; case/boolP: (x <= z) => xz; case/boolP: (z <= x) => zx; case/boolP: (y <= z) => yz; case/boolP: (z <= y) => zy //= _ _ _. - by move: zx; rewrite (le_trans zy yx). - by move: zx; rewrite (le_trans zy yx). - by move: zy; rewrite (le_trans zx xy). - by move: zy; rewrite (le_trans zx xy). - by move: zx; rewrite (le_trans zy yx). - by move: zx; rewrite (le_trans zy yx). Qed. Lemma comparable_min_maxl : min (max x y) z = max (min x z) (min y z). Proof. move: cmp_xy cmp_xz cmp_yz; rewrite !(fun_if, if_arg)/= !lt_le_def. case/boolP: (x <= y) => xy; case/boolP: (y <= x) => yx; case/boolP: (x <= z) => xz; case/boolP: (z <= x) => zx; case/boolP: (y <= z) => yz; case/boolP: (z <= y) => zy; rewrite ?lexx => //= _ _ _. - by move: zx; rewrite (le_trans zy yx). - by move: zx; rewrite (le_trans zy yx). - by move: zy; rewrite (le_trans zx xy). - by move: zy; rewrite (le_trans zx xy). - by move: zx; rewrite (le_trans zy yx). - by move: zx; rewrite (le_trans zy yx). Qed. Lemma comparable_max_minr : max x (min y z) = min (max x y) (max x z). Proof. move: cmp_xy cmp_xz cmp_yz; rewrite !(fun_if, if_arg)/= !lt_le_def. case/boolP: (x <= y) => xy; case/boolP: (y <= x) => yx; case/boolP: (x <= z) => xz; case/boolP: (z <= x) => zx; case/boolP: (y <= z) => yz; case/boolP: (z <= y) => zy; rewrite ?lexx => //= _ _ _. - by move: zx; rewrite (le_trans zy yx). - by move: zx; rewrite (le_trans zy yx). - by move: zy; rewrite (le_trans zx xy). - by move: zy; rewrite (le_trans zx xy). - by move: zx; rewrite (le_trans zy yx). - by move: zx; rewrite (le_trans zy yx). Qed. End Comparable3. Section ArgExtremum. Context (I : finType) (i0 : I) (P : {pred I}) (F : I -> T) (Pi0 : P i0). Hypothesis F_comparable : {in P &, forall i j, F i >=< F j}. Lemma comparable_arg_minP: extremum_spec <=%O P F (arg_min i0 P F). Proof. by apply: extremum_inP => // [x _|y x z _ _ _]; [apply: lexx|apply: le_trans]. Qed. Lemma comparable_arg_maxP: extremum_spec >=%O P F (arg_max i0 P F). Proof. apply: extremum_inP => // [x _|y x z _ _ _|]; [exact: lexx|exact: ge_trans|]. by move=> x y xP yP; rewrite orbC [_ || _]F_comparable. Qed. End ArgExtremum. (* monotonicity *) Lemma comparable_bigl x x0 op I (P : pred I) F (s : seq I) : {in >=< x &, forall y z, op y z >=< x} -> x0 >=< x -> {in P, forall i, F i >=< x} -> \big[op/x0]_(i <- s | P i) F i >=< x. Proof. by move=> *; elim/big_ind : _. Qed. Lemma comparable_bigr x x0 op I (P : pred I) F (s : seq I) : {in >=<%O x &, forall y z, x >=< op y z} -> x >=< x0 -> {in P, forall i, x >=< F i} -> x >=< \big[op/x0]_(i <- s | P i) F i. Proof. by move=> *; elim/big_ind : _. Qed. Section bigminmax. Variables (I : Type) (r : seq I) (f : I -> T) (x0 x : T) (P : pred I). Lemma bigmax_lt : x0 < x -> (forall i, P i -> f i < x) -> \big[max/x0]_(i <- r | P i) f i < x. Proof. by move=> ? ?; elim/big_ind: _ => // *; rewrite maxElt; case: ifPn. Qed. Lemma lt_bigmin : x < x0 -> (forall i, P i -> x < f i) -> x < \big[min/x0]_(i <- r | P i) f i. Proof. by move=> ? ?; elim/big_ind: _ => // *; rewrite minElt; case: ifPn. Qed. End bigminmax. End PreorderTheory. #[global] Hint Resolve comparable_minr comparable_minl : core. #[global] Hint Resolve comparable_maxr comparable_maxl : core. Section ContraTheory. Context {disp1 disp2 : disp_t} {T1 : preorderType disp1} {T2 : preorderType disp2}. Implicit Types (x y : T1) (z t : T2) (b : bool) (m n : nat) (P : Prop). Lemma comparable_contraTle b x y : x >=< y -> (y < x -> ~~ b) -> (b -> x <= y). Proof. by move=> /comparable_leNgt ->; case: (y < x); case: b. Qed. Lemma comparable_contraTlt b x y : x >=< y -> (y <= x -> ~~ b) -> (b -> x < y). Proof. by move=> /comparable_ltNge ->; case: (y <= x); case: b. Qed. Lemma comparable_contraPle P x y : x >=< y -> (y < x -> ~ P) -> (P -> x <= y). Proof. by move=> /comparable_leNgt -> np p; apply/negP => /np. Qed. Lemma comparable_contraPlt P x y : x >=< y -> (y <= x -> ~ P) -> (P -> x < y). Proof. by move=> /comparable_ltNge -> np p; apply/negP => /np. Qed. Lemma comparable_contraNle b x y : x >=< y -> (y < x -> b) -> (~~ b -> x <= y). Proof. by move=> /comparable_leNgt ->; case: (y < x); case: b. Qed. Lemma comparable_contraNlt b x y : x >=< y -> (y <= x -> b) -> (~~ b -> x < y). Proof. by move=> /comparable_ltNge ->; case: (y <= x); case: b. Qed. Lemma comparable_contra_not_le P x y : x >=< y -> (y < x -> P) -> (~ P -> x <= y). Proof. by move=> /comparable_leNgt -> np p; apply/negP => /np. Qed. Lemma comparable_contra_not_lt P x y : x >=< y -> (y <= x -> P) -> (~ P -> x < y). Proof. by move=> /comparable_ltNge -> np p; apply/negP => /np. Qed. Lemma comparable_contraFle b x y : x >=< y -> (y < x -> b) -> (b = false -> x <= y). Proof. by move=> /comparable_leNgt -> np /negP p; apply/negP => /np. Qed. Lemma comparable_contraFlt b x y : x >=< y -> (y <= x -> b) -> (b = false -> x < y). Proof. by move=> /comparable_ltNge -> np /negP p; apply/negP => /np. Qed. Lemma comparable_contra_leq_le m n x y : x >=< y -> (y < x -> (n < m)%N) -> ((m <= n)%N -> x <= y). Proof. by rewrite ltnNge; apply/comparable_contraTle. Qed. Lemma comparable_contra_leq_lt m n x y : x >=< y -> (y <= x -> (n < m)%N) -> ((m <= n)%N -> x < y). Proof. by rewrite ltnNge; apply/comparable_contraTlt. Qed. Lemma comparable_contra_ltn_le m n x y : x >=< y -> (y < x -> (n <= m)%N) -> ((m < n)%N -> x <= y). Proof. by rewrite ltnNge; apply/comparable_contraNle. Qed. Lemma comparable_contra_ltn_lt m n x y : x >=< y -> (y <= x -> (n <= m)%N) -> ((m < n)%N -> x < y). Proof. by rewrite ltnNge; apply/comparable_contraNlt. Qed. Lemma comparable_contra_le x y z t : z >=< t -> (t < z -> y < x) -> (x <= y -> z <= t). Proof. rewrite /comparable lt_le_def; case: (z <= t) => //= -> /(_ erefl) yx. by move=> /(lt_le_trans yx); rewrite ltxx. Qed. Lemma comparable_contra_le_lt x y z t : z >=< t -> (t <= z -> y < x) -> (x <= y -> z < t). Proof. rewrite /comparable [z < t]lt_le_def orbC; case: (t <= z) => /= [_|-> //]. by move=> /(_ erefl) yx /(lt_le_trans yx); rewrite ltxx. Qed. Lemma comparable_contra_lt_le x y z t : z >=< t -> (t < z -> y <= x) -> (x < y -> z <= t). Proof. rewrite /comparable lt_le_def; case: (z <= t) => //= -> /(_ erefl) yx. by move=> /(le_lt_trans yx); rewrite ltxx. Qed. Lemma comparable_contra_lt x y z t : z >=< t -> (t <= z -> y <= x) -> (x < y -> z < t). Proof. rewrite /comparable [z < t]lt_le_def orbC; case: (t <= z) => /= [_|-> //]. by move=> /(_ erefl) yx /(le_lt_trans yx); rewrite ltxx. Qed. End ContraTheory. Section PreorderMonotonyTheory. Context {disp disp' : disp_t}. Context {T : preorderType disp} {T' : preorderType disp'}. Implicit Types (m n p : nat) (x y z : T) (u v w : T'). Variables (D D' : {pred T}) (f : T -> T'). Hint Resolve lexx lt_le_def : core. Lemma leW_mono : {mono f : x y / x <= y} -> {mono f : x y / x < y}. Proof. by move=> fmono x y; rewrite !lt_le_def !fmono. Qed. Lemma leW_nmono : {mono f : x y /~ x <= y} -> {mono f : x y /~ x < y}. Proof. by move=> fmono x y; rewrite !lt_le_def !fmono. Qed. Lemma leW_mono_in : {in D &, {mono f : x y / x <= y}} -> {in D &, {mono f : x y / x < y}}. Proof. by move=> fmono x y xD yD; rewrite !lt_le_def !fmono. Qed. Lemma leW_nmono_in : {in D &, {mono f : x y /~ x <= y}} -> {in D &, {mono f : x y /~ x < y}}. Proof. by move=> fmono x y xD yD; rewrite !lt_le_def !fmono. Qed. End PreorderMonotonyTheory. End PreorderTheory. #[global] Hint Resolve lexx le_refl ltxx lt_irreflexive ltW lt_eqF : core. Arguments leif_refl {disp T x C}. Module Import BPreorderTheory. Section BPreorderTheory. Context {disp : disp_t} {T : bPreorderType disp}. Implicit Types (x y : T). Lemma le0x x : \bot <= x. Proof. exact: le0x. Qed. Lemma ltx0 x : (x < \bot) = false. Proof. exact/le_gtF/le0x. Qed. End BPreorderTheory. End BPreorderTheory. Module Import TPreorderTheory. Section TPreorderTheory. Context {disp : disp_t} {T : tPreorderType disp}. Implicit Types (x y : T). Lemma lex1 x : x <= \top. Proof. exact: lex1. Qed. Lemma lt1x x : (\top < x) = false. Proof. exact: (@ltx0 _ T^d). Qed. End TPreorderTheory. End TPreorderTheory. #[global] Hint Extern 0 (is_true (\bot <= _)) => exact: le0x : core. #[global] Hint Extern 0 (is_true (_ <= \top)) => exact: lex1 : core. (*************) (* FACTORIES *) (*************) (* preorder *) HB.factory Record isPreorder (d : disp_t) T of Equality T := { le : rel T; lt : rel T; lt_def : forall x y, lt x y = (le x y) && ~~ (le y x); le_refl : reflexive le; le_trans : transitive le; }. HB.builders Context (d : disp_t) T of isPreorder d T. (* TODO: print nice error message when keyed type is not provided *) Let ge_trans : transitive (fun x y => le y x). Proof. by move=> x y z /[swap]; apply: le_trans. Qed. #[warning="-HB.no-new-instance"] HB.instance Definition _ := @isDuallyPreorder.Build d T le _ lt_def (fun x y => lt_def y x) le_refl le_refl le_trans ge_trans. HB.end. HB.factory Record Le_isPreorder (d : disp_t) T of Equality T := { le : rel T; le_refl : reflexive le; le_trans : transitive le; }. HB.builders Context (d : disp_t) T of Le_isPreorder d T. (* TODO: print nice error message when keyed type is not provided *) #[warning="-HB.no-new-instance"] HB.instance Definition _ := @isPreorder.Build d T le _ (fun _ _ => erefl) le_refl le_trans. HB.end. HB.factory Record LtLe_isPreorder (d : disp_t) T of Equality T := { le : rel T; lt : rel T; le_def : forall x y, le x y = (x == y) || lt x y; lt_irr : irreflexive lt; lt_trans : transitive lt; }. HB.builders Context (d : disp_t) T of LtLe_isPreorder d T. Let le_refl : reflexive le. Proof. by move=> x; rewrite le_def eqxx. Qed. Let le_trans : transitive le. Proof. move=> y x z; rewrite !le_def; case: (eqVneq x y) => [->|]//= neq_xy. by case: (eqVneq y z) => /= [<- ->|_ /lt_trans yx /yx ->]; rewrite orbT. Qed. Let lt_le_def x y : lt x y = (le x y) && ~~ (le y x). Proof. rewrite !le_def eq_sym; have [->|_ /=] := eqVneq x y; first by rewrite lt_irr. case/boolP: (lt x y) => //= xy; apply/esym/negP => /(lt_trans xy). by rewrite lt_irr. Qed. #[warning="-HB.no-new-instance"] HB.instance Definition _ := @isPreorder.Build d T le lt lt_le_def le_refl le_trans . HB.end. HB.factory Record Lt_isPreorder (d : disp_t) T of Equality T := { lt : rel T; lt_irr : irreflexive lt; lt_trans : transitive lt; }. HB.builders Context (d : disp_t) (T : Type) of Lt_isPreorder d T. #[warning="-HB.no-new-instance"] HB.instance Definition _ := @LtLe_isPreorder.Build d T _ lt (fun _ _ => erefl) lt_irr lt_trans. HB.end. Module PreCancelPartial. Section PreCancelPartial. Variables (disp : disp_t) (T : choiceType). Variables (disp' : disp_t) (T' : preorderType disp') (f : T -> T'). Definition le (x y : T) := f x <= f y. Definition lt (x y : T) := f x < f y. Fact refl : reflexive le. Proof. by move=> ?; apply: lexx. Qed. Fact trans : transitive le. Proof. by move=> ? ? ?; apply: le_trans. Qed. Fact ge_trans : transitive (fun x y => le y x). Proof. by move=> ? ? ?; apply: ge_trans. Qed. Fact lt_le_def x y : lt x y = le x y && ~~ le y x. Proof. exact: lt_le_def. Qed. Definition PrePcan := isPreorder.Build disp T lt_le_def refl trans. End PreCancelPartial. End PreCancelPartial. (* FIXME Fail #[export] HB.instance Definition _ (disp : disp_t) (T : choiceType) (disp' : disp_t) (T' : porderType disp') (f : T -> T') (f_inj : injective f): isPreorder disp (inj_type f_inj) := @PreCancelPartial.PrePcan disp (inj_type f_inj) disp' T' f. *) #[export] HB.instance Definition _ (disp : disp_t) (T : Type) (disp' : disp_t) (T' : preorderType disp') (f : T -> T') (f' : T' -> option T) (f_can : pcancel f f') : isPreorder disp (pcan_type f_can) := @PreCancelPartial.PrePcan disp (pcan_type f_can) disp' T' f. #[export] HB.instance Definition _ (disp : disp_t) (T : Type) (disp' : disp_t) (T' : preorderType disp') (f : T -> T') (f' : T' -> T) (f_can : cancel f f') : isPreorder disp (can_type f_can) := @PreCancelPartial.PrePcan disp (can_type f_can) disp' T' f. (* Morphism hierarchy. *) Definition order_morphism d (T : preorderType d) d' (T' : preorderType d') (f : T -> T') : Prop := {mono f : x y / x <= y}. HB.mixin Record isOrderMorphism d (T : preorderType d) d' (T' : preorderType d') (apply : T -> T') := { omorph_le_subproof : {homo apply : x y / x <= y} ; }. HB.structure Definition OrderMorphism d (T : preorderType d) d' (T' : preorderType d') := {f of isOrderMorphism d T d' T' f}. Module OrderMorphismExports. Notation "{ 'omorphism' T -> T' }" := (@OrderMorphism.type _ T%type _ T'%type) : type_scope. End OrderMorphismExports. HB.export OrderMorphismExports. Module Import OrderMorphismTheory. Section OrderMorphismTheory. Lemma omorph_le (d : disp_t) (T : preorderType d) (d' : disp_t) (T' : preorderType d') (f : {omorphism T -> T'}) : {homo f : x y / x <= y}. Proof. exact: omorph_le_subproof. Qed. Section IdCompFun. Variables (d : disp_t) (T : preorderType d) (d' : disp_t) (T' : preorderType d'). Variables (d'' : disp_t) (T'' : preorderType d''). Variables (f : {omorphism T' -> T''}) (g : {omorphism T -> T'}). Fact idfun_is_nondecreasing : nondecreasing (@idfun T). Proof. by []. Qed. #[export] HB.instance Definition _ := isOrderMorphism.Build d T d T idfun idfun_is_nondecreasing. Fact comp_is_nondecreasing : nondecreasing (f \o g). Proof. by move=> ? ? ?; do 2 apply: omorph_le. Qed. #[export] HB.instance Definition _ := isOrderMorphism.Build d T d'' T'' (f \o g) comp_is_nondecreasing. End IdCompFun. End OrderMorphismTheory. End OrderMorphismTheory. HB.mixin Record isSubPreorder d (T : preorderType d) (S : pred T) d' U of SubType T S U & Preorder d' U := { le_val : {mono (val : U -> T) : x y / x <= y}; }. #[short(type="subPreorder")] HB.structure Definition SubPreorder d (T : preorderType d) S d' := { U of SubEquality T S U & Preorder d' U & isSubPreorder d T S d' U }. Module Import SubPreorderTheory. Section SubPreorderTheory. Context (d : disp_t) (T : preorderType d) (S : pred T). Context (d' : disp_t) (U : SubPreorder.type S d'). Local Notation val := (val : U -> T). #[deprecated(since="mathcomp 2.3.0", note="Use le_val instead.")] Lemma leEsub x y : (x <= y) = (val x <= val y). Proof. by rewrite le_val. Qed. Lemma lt_val : {mono val : x y / x < y}. Proof. by move=> x y; rewrite !lt_leAnge !le_val. Qed. #[deprecated(since="mathcomp 2.3.0", note="Use lt_val instead.")] Lemma ltEsub x y : (x < y) = (val x < val y). Proof. by rewrite lt_val. Qed. Lemma le_wval : {homo val : x y / x <= y}. Proof. exact/mono2W/le_val. Qed. Lemma lt_wval : {homo val : x y / x < y}. Proof. exact/mono2W/lt_val. Qed. HB.instance Definition _ := isOrderMorphism.Build d' U d T val le_wval. End SubPreorderTheory. Arguments lt_val {d T S d' U} x y. Arguments le_wval {d T S d' U} x y. Arguments lt_wval {d T S d' U} x y. End SubPreorderTheory. HB.factory Record SubChoice_isSubPreorder d (T : preorderType d) S (d' : disp_t) U of SubChoice T S U := {}. HB.builders Context d T S d' U of SubChoice_isSubPreorder d T S d' U. HB.instance Definition _ : isPreorder d' U := @PreCancelPartial.PrePcan d' U d T val. Fact valD : order_morphism (val : U -> T). Proof. by []. Qed. HB.instance Definition _ := isSubPreorder.Build d T S d' U valD. HB.end. Module SubOrderExports. Notation "[ 'SubChoice_isSubPreorder' 'of' U 'by' <: ]" := (SubChoice_isSubPreorder.Build _ _ _ _ U) (at level 0, format "[ 'SubChoice_isSubPreorder' 'of' U 'by' <: ]") : form_scope. Notation "[ 'SubChoice_isSubPreorder' 'of' U 'by' <: 'with' disp ]" := (SubChoice_isSubPreorder.Build _ _ _ disp U) (at level 0, format "[ 'SubChoice_isSubPreorder' 'of' U 'by' <: 'with' disp ]") : form_scope. End SubOrderExports. HB.export SubOrderExports. (*************) (* INSTANCES *) (*************) (********************) (* Instances on nat *) (********************) (******************************************************************************) (* This is an example of creation of multiple instances on the same type, *) (* with distinct displays, using natural numbers. *) (* We declare two distinct canonical orders: *) (* - leq which is total, and where meet and join are minn and maxn, on nat *) (* - dvdn which is partial, and where meet and join are gcdn and lcmn, *) (* on natdvd *) (******************************************************************************) (******************************************************************************) (* The Module NatOrder defines leq as the canonical order on the type nat, *) (* i.e., without creating an alias. We define and use nat_display and proceed *) (* like a standard canonical structure declaration, except that we use this *) (* display. We also use a single factory LeOrderMixin to instantiate three *) (* different canonical declarations porderType, distrLatticeType, orderType. *) (* We finish by providing theorems to convert the operations of ordered and *) (* lattice types to their definition without structure abstraction. *) (******************************************************************************) Module NatOrder. Section NatOrder. Fact nat_display : disp_t. Proof. exact. Qed. Lemma ltn_def x y : (x < y)%N = (x <= y)%N && ~~ (y <= x)%N. Proof. by rewrite -ltnNge andbC; case: (ltnP x y) => //= /ltnW. Qed. #[export] HB.instance Definition _ := isPreorder.Build nat_display nat ltn_def leqnn leq_trans. #[export] HB.instance Definition _ := hasBottom.Build nat_display nat leq0n. Lemma leEnat : le = leq. Proof. by []. Qed. Lemma ltEnat : lt = ltn. Proof. by []. Qed. Lemma minEnat : min = minn. Proof. by []. Qed. Lemma maxEnat : max = maxn. Proof. by []. Qed. Lemma botEnat : \bot = 0%N :> nat. Proof. by []. Qed. End NatOrder. Module Exports. HB.reexport NatOrder. Definition leEnat := leEnat. Definition ltEnat := ltEnat. Definition minEnat := minEnat. Definition maxEnat := maxEnat. Definition botEnat := botEnat. End Exports. End NatOrder. HB.export NatOrder.Exports. Module NatMonotonyTheory. Section NatMonotonyTheory. Context {disp : disp_t} {T : preorderType disp}. Variables (D : {pred nat}) (f : nat -> T). Hypothesis Dconvex : {in D &, forall i j k, i < k < j -> k \in D}. Lemma homo_ltn_lt_in : {in D, forall i, i.+1 \in D -> f i < f i.+1} -> {in D &, {homo f : i j / i < j}}. Proof. by apply: homo_ltn_in Dconvex; apply: lt_trans. Qed. Lemma nondecn_inP : {in D, forall i, i.+1 \in D -> f i <= f i.+1} -> {in D &, {homo f : i j / i <= j}}. Proof. by apply: homo_leq_in Dconvex => //; apply: le_trans. Qed. Lemma nhomo_ltn_lt_in : {in D, forall i, i.+1 \in D -> f i > f i.+1} -> {in D &, {homo f : i j /~ i < j}}. Proof. move=> f_dec; apply: homo_sym_in. by apply: homo_ltn_in Dconvex f_dec => ? ? ? ? /lt_trans->. Qed. Lemma nonincn_inP : {in D, forall i, i.+1 \in D -> f i >= f i.+1} -> {in D &, {homo f : i j /~ i <= j}}. Proof. move=> /= f_dec; apply: homo_sym_in. by apply: homo_leq_in Dconvex f_dec => //= ? ? ? ? /le_trans->. Qed. Lemma homo_ltn_lt : (forall i, f i < f i.+1) -> {homo f : i j / i < j}. Proof. by apply: homo_ltn; apply: lt_trans. Qed. Lemma nondecnP : (forall i, f i <= f i.+1) -> {homo f : i j / i <= j}. Proof. by apply: homo_leq => //; apply: le_trans. Qed. Lemma nhomo_ltn_lt : (forall i, f i > f i.+1) -> {homo f : i j /~ i < j}. Proof. move=> f_dec; apply: homo_sym. by apply: homo_ltn f_dec => ? ? ? ? /lt_trans->. Qed. Lemma nonincnP : (forall i, f i >= f i.+1) -> {homo f : i j /~ i <= j}. Proof. move=> /= f_dec; apply: homo_sym. by apply: homo_leq f_dec => //= ? ? ? ? /le_trans->. Qed. End NatMonotonyTheory. Arguments homo_ltn_lt_in {disp T} [D f]. Arguments nondecn_inP {disp T} [D f]. Arguments nhomo_ltn_lt_in {disp T} [D f]. Arguments nonincn_inP {disp T} [D f]. Arguments homo_ltn_lt {disp T} [f]. Arguments nondecnP {disp T} [f]. Arguments nhomo_ltn_lt {disp T} [f]. Arguments nonincnP {disp T} [f]. End NatMonotonyTheory. (****************************************************************************) (* The Module DvdSyntax introduces a new set of notations using the newly *) (* created display dvd_display. We first define the display as an opaque *) (* definition of type disp_t, and we use it as the first argument of the *) (* operator which display we want to change from the default one (here le, *) (* lt, dvd sdvd, meet, join, top and bottom, as well as big op notations on *) (* gcd and lcm). This notations will now be used for any ordered type which *) (* first parameter is set to dvd_display. *) (****************************************************************************) Fact dvd_display : disp_t. Proof. exact. Qed. Module DvdSyntax. Notation dvd := (@le dvd_display _). Notation "@ 'dvd' T" := (@le dvd_display T) (at level 10, T at level 8, only parsing) : function_scope. Notation sdvd := (@lt dvd_display _). Notation "@ 'sdvd' T" := (@lt dvd_display T) (at level 10, T at level 8, only parsing) : function_scope. Notation "x %| y" := (dvd x y) : order_scope. Notation "x %<| y" := (sdvd x y) : order_scope. Notation nat0 := (@top dvd_display _). Notation nat1 := (@bottom dvd_display _). End DvdSyntax. (******************************************************************************) (* The Module NatDvd defines dvdn as the canonical order on NatDvd.t, which *) (* is abbreviated using the notation natdvd at the end of the module. *) (* We use the newly defined dvd_display, described above. *) (* We first recover structures that are common to both nat and natdvd *) (* (eqType, choiceType, countType) through the copy mechanism, then we use *) (* a single factory MeetJoinMixin to instantiate both porderType and *) (* distrLatticeType canonical structures, and end with top and bottom. *) (* We finish by providing theorems to convert the operations of ordered and *) (* lattice types to their definition without structure abstraction. *) (******************************************************************************) Module NatDvd. Section NatDvd. Implicit Types (m n p : nat). Definition t := nat. #[export] HB.instance Definition _ := Choice.copy t nat. (* Note that this where the dvd_display is associated with the type NatDvd.t. *) #[export] HB.instance Definition _ := @Le_isPreorder.Build dvd_display t dvdn dvdnn dvdn_trans. (* NatDvd.t is associated below with the notation "natdvd". *) #[export] HB.instance Definition _ := @hasBottom.Build _ t 1 dvd1n. #[export] HB.instance Definition _ := @hasTop.Build _ t 0 dvdn0. Import DvdSyntax. Lemma dvdE : dvd = dvdn :> rel t. Proof. by []. Qed. Lemma nat1E : nat1 = 1%N :> t. Proof. by []. Qed. Lemma nat0E : nat0 = 0%N :> t. Proof. by []. Qed. End NatDvd. Module Exports. HB.reexport NatDvd. Notation natdvd := t. Definition dvdEnat := dvdE. Definition nat1E := nat1E. Definition nat0E := nat0E. End Exports. End NatDvd. HB.export NatDvd.Exports. (************************) (* Instances on ordinal *) (************************) Module OrdinalOrder. Section OrdinalOrder. Fact ord_display : disp_t. Proof. exact. Qed. Section PossiblyTrivial. Context (n : nat). #[export] HB.instance Definition _ := [SubChoice_isSubPreorder of 'I_n by <: with ord_display]. Lemma leEord : (le : rel 'I_n) = leq. Proof. by []. Qed. Lemma ltEord : (lt : rel 'I_n) = (fun m n => m < n)%N. Proof. by []. Qed. End PossiblyTrivial. Section NonTrivial. Context (n' : nat). Let n := n'.+1. #[export] HB.instance Definition _ := @hasBottom.Build _ 'I_n ord0 leq0n. #[export] HB.instance Definition _ := @hasTop.Build _ 'I_n ord_max (@leq_ord _). Lemma botEord : \bot = ord0. Proof. by []. Qed. Lemma topEord : \top = ord_max. Proof. by []. Qed. End NonTrivial. End OrdinalOrder. Module Exports. HB.reexport OrdinalOrder. Definition leEord := leEord. Definition ltEord := ltEord. Definition botEord := botEord. Definition topEord := topEord. End Exports. End OrdinalOrder. HB.export OrdinalOrder.Exports. (*********************) (* Instances on bool *) (*********************) Module BoolOrder. Section BoolOrder. Implicit Types (x y : bool). Fact bool_display : disp_t. Proof. exact. Qed. Fact ltn_def x y : (x < y)%N = (x <= y)%N && ~~ (y <= x)%N. Proof. by case: x y => [] []. Qed. #[export] HB.instance Definition _ := @isPreorder.Build bool_display bool _ _ ltn_def leqnn leq_trans. #[export] HB.instance Definition _ := @hasBottom.Build _ bool false leq0n. #[export] HB.instance Definition _ := @hasTop.Build _ bool true leq_b1. Lemma leEbool : le = (leq : rel bool). Proof. by []. Qed. Lemma ltEbool x y : (x < y) = (x < y)%N. Proof. by []. Qed. End BoolOrder. Module Exports. HB.reexport BoolOrder. Definition leEbool := leEbool. Definition ltEbool := ltEbool. End Exports. End BoolOrder. HB.export BoolOrder.Exports. (******************************) (* Definition of prod_display *) (******************************) Fact prod_display_unit (_ _ : unit) : unit. Proof. exact: tt. Qed. Definition prod_display (displ dispr : disp_t) : disp_t := Disp (prod_display_unit (d1 displ) (d1 dispr)) (prod_display_unit (d2 displ) (d2 dispr)). Fact seqprod_display (disp : disp_t) : disp_t. Proof. exact: disp. Qed. Module Import ProdSyntax. Notation "<=^p%O" := (@le (prod_display _ _) _) : function_scope. Notation ">=^p%O" := (@ge (prod_display _ _) _) : function_scope. Notation ">=^p%O" := (@ge (prod_display _ _) _) : function_scope. Notation "<^p%O" := (@lt (prod_display _ _) _) : function_scope. Notation ">^p%O" := (@gt (prod_display _ _) _) : function_scope. Notation "<?=^p%O" := (@leif (prod_display _ _) _) : function_scope. Notation ">=<^p%O" := (@comparable (prod_display _ _) _) : function_scope. Notation "><^p%O" := (fun x y => ~~ (@comparable (prod_display _ _) _ x y)) : function_scope. Notation "<=^p y" := (>=^p%O y) : order_scope. Notation "<=^p y :> T" := (<=^p (y : T)) (only parsing) : order_scope. Notation ">=^p y" := (<=^p%O y) : order_scope. Notation ">=^p y :> T" := (>=^p (y : T)) (only parsing) : order_scope. Notation "<^p y" := (>^p%O y) : order_scope. Notation "<^p y :> T" := (<^p (y : T)) (only parsing) : order_scope. Notation ">^p y" := (<^p%O y) : order_scope. Notation ">^p y :> T" := (>^p (y : T)) (only parsing) : order_scope. Notation "x <=^p y" := (<=^p%O x y) : order_scope. Notation "x <=^p y :> T" := ((x : T) <=^p (y : T)) (only parsing) : order_scope. Notation "x >=^p y" := (y <=^p x) (only parsing) : order_scope. Notation "x >=^p y :> T" := ((x : T) >=^p (y : T)) (only parsing) : order_scope. Notation "x <^p y" := (<^p%O x y) : order_scope. Notation "x <^p y :> T" := ((x : T) <^p (y : T)) (only parsing) : order_scope. Notation "x >^p y" := (y <^p x) (only parsing) : order_scope. Notation "x >^p y :> T" := ((x : T) >^p (y : T)) (only parsing) : order_scope. Notation "x <=^p y <=^p z" := ((x <=^p y) && (y <=^p z)) : order_scope. Notation "x <^p y <=^p z" := ((x <^p y) && (y <=^p z)) : order_scope. Notation "x <=^p y <^p z" := ((x <=^p y) && (y <^p z)) : order_scope. Notation "x <^p y <^p z" := ((x <^p y) && (y <^p z)) : order_scope. Notation "x <=^p y ?= 'iff' C" := (<?=^p%O x y C) : order_scope. Notation "x <=^p y ?= 'iff' C :> T" := ((x : T) <=^p (y : T) ?= iff C) (only parsing) : order_scope. Notation ">=<^p y" := [pred x | >=<^p%O x y] : order_scope. Notation ">=<^p y :> T" := (>=<^p (y : T)) (only parsing) : order_scope. Notation "x >=<^p y" := (>=<^p%O x y) : order_scope. Notation "><^p y" := [pred x | ~~ (>=<^p%O x y)] : order_scope. Notation "><^p y :> T" := (><^p (y : T)) (only parsing) : order_scope. Notation "x ><^p y" := (~~ (><^p%O x y)) : order_scope. End ProdSyntax. Module Import SeqProdSyntax. Notation "<=^sp%O" := (@le (seqprod_display _) _) : function_scope. Notation ">=^sp%O" := (@ge (seqprod_display _) _) : function_scope. Notation ">=^sp%O" := (@ge (seqprod_display _) _) : function_scope. Notation "<^sp%O" := (@lt (seqprod_display _) _) : function_scope. Notation ">^sp%O" := (@gt (seqprod_display _) _) : function_scope. Notation "<?=^sp%O" := (@leif (seqprod_display _) _) : function_scope. Notation ">=<^sp%O" := (@comparable (seqprod_display _) _) : function_scope. Notation "><^sp%O" := (fun x y => ~~ (@comparable (seqprod_display _) _ x y)) : function_scope. Notation "<=^sp y" := (>=^sp%O y) : order_scope. Notation "<=^sp y :> T" := (<=^sp (y : T)) (only parsing) : order_scope. Notation ">=^sp y" := (<=^sp%O y) : order_scope. Notation ">=^sp y :> T" := (>=^sp (y : T)) (only parsing) : order_scope. Notation "<^sp y" := (>^sp%O y) : order_scope. Notation "<^sp y :> T" := (<^sp (y : T)) (only parsing) : order_scope. Notation ">^sp y" := (<^sp%O y) : order_scope. Notation ">^sp y :> T" := (>^sp (y : T)) (only parsing) : order_scope. Notation "x <=^sp y" := (<=^sp%O x y) : order_scope. Notation "x <=^sp y :> T" := ((x : T) <=^sp (y : T)) (only parsing) : order_scope. Notation "x >=^sp y" := (y <=^sp x) (only parsing) : order_scope. Notation "x >=^sp y :> T" := ((x : T) >=^sp (y : T)) (only parsing) : order_scope. Notation "x <^sp y" := (<^sp%O x y) : order_scope. Notation "x <^sp y :> T" := ((x : T) <^sp (y : T)) (only parsing) : order_scope. Notation "x >^sp y" := (y <^sp x) (only parsing) : order_scope. Notation "x >^sp y :> T" := ((x : T) >^sp (y : T)) (only parsing) : order_scope. Notation "x <=^sp y <=^sp z" := ((x <=^sp y) && (y <=^sp z)) : order_scope. Notation "x <^sp y <=^sp z" := ((x <^sp y) && (y <=^sp z)) : order_scope. Notation "x <=^sp y <^sp z" := ((x <=^sp y) && (y <^sp z)) : order_scope. Notation "x <^sp y <^sp z" := ((x <^sp y) && (y <^sp z)) : order_scope. Notation "x <=^sp y ?= 'iff' C" := (<?=^sp%O x y C) : order_scope. Notation "x <=^sp y ?= 'iff' C :> T" := ((x : T) <=^sp (y : T) ?= iff C) (only parsing) : order_scope. Notation ">=<^sp y" := [pred x | >=<^sp%O x y] : order_scope. Notation ">=<^sp y :> T" := (>=<^sp (y : T)) (only parsing) : order_scope. Notation "x >=<^sp y" := (>=<^sp%O x y) : order_scope. Notation "><^sp y" := [pred x | ~~ (>=<^sp%O x y)] : order_scope. Notation "><^sp y :> T" := (><^sp (y : T)) (only parsing) : order_scope. Notation "x ><^sp y" := (~~ (><^sp%O x y)) : order_scope. End SeqProdSyntax. (******************************) (* Definition of lexi_display *) (******************************) Fact lexi_display (disp _ : disp_t) : disp_t. Proof. exact: disp. Qed. Fact seqlexi_display (disp : disp_t) : disp_t. Proof. exact: disp. Qed. Module Import LexiSyntax. Notation "<=^l%O" := (@le (lexi_display _ _) _) : function_scope. Notation ">=^l%O" := (@ge (lexi_display _ _) _) : function_scope. Notation ">=^l%O" := (@ge (lexi_display _ _) _) : function_scope. Notation "<^l%O" := (@lt (lexi_display _ _) _) : function_scope. Notation ">^l%O" := (@gt (lexi_display _ _) _) : function_scope. Notation "<?=^l%O" := (@leif (lexi_display _ _) _) : function_scope. Notation ">=<^l%O" := (@comparable (lexi_display _ _) _) : function_scope. Notation "><^l%O" := (fun x y => ~~ (@comparable (lexi_display _ _) _ x y)) : function_scope. Notation "<=^l y" := (>=^l%O y) : order_scope. Notation "<=^l y :> T" := (<=^l (y : T)) (only parsing) : order_scope. Notation ">=^l y" := (<=^l%O y) : order_scope. Notation ">=^l y :> T" := (>=^l (y : T)) (only parsing) : order_scope. Notation "<^l y" := (>^l%O y) : order_scope. Notation "<^l y :> T" := (<^l (y : T)) (only parsing) : order_scope. Notation ">^l y" := (<^l%O y) : order_scope. Notation ">^l y :> T" := (>^l (y : T)) (only parsing) : order_scope. Notation "x <=^l y" := (<=^l%O x y) : order_scope. Notation "x <=^l y :> T" := ((x : T) <=^l (y : T)) (only parsing) : order_scope. Notation "x >=^l y" := (y <=^l x) (only parsing) : order_scope. Notation "x >=^l y :> T" := ((x : T) >=^l (y : T)) (only parsing) : order_scope. Notation "x <^l y" := (<^l%O x y) : order_scope. Notation "x <^l y :> T" := ((x : T) <^l (y : T)) (only parsing) : order_scope. Notation "x >^l y" := (y <^l x) (only parsing) : order_scope. Notation "x >^l y :> T" := ((x : T) >^l (y : T)) (only parsing) : order_scope. Notation "x <=^l y <=^l z" := ((x <=^l y) && (y <=^l z)) : order_scope. Notation "x <^l y <=^l z" := ((x <^l y) && (y <=^l z)) : order_scope. Notation "x <=^l y <^l z" := ((x <=^l y) && (y <^l z)) : order_scope. Notation "x <^l y <^l z" := ((x <^l y) && (y <^l z)) : order_scope. Notation "x <=^l y ?= 'iff' C" := (<?=^l%O x y C) : order_scope. Notation "x <=^l y ?= 'iff' C :> T" := ((x : T) <=^l (y : T) ?= iff C) (only parsing) : order_scope. Notation ">=<^l y" := [pred x | >=<^l%O x y] : order_scope. Notation ">=<^l y :> T" := (>=<^l (y : T)) (only parsing) : order_scope. Notation "x >=<^l y" := (>=<^l%O x y) : order_scope. Notation "><^l y" := [pred x | ~~ (>=<^l%O x y)] : order_scope. Notation "><^l y :> T" := (><^l (y : T)) (only parsing) : order_scope. Notation "x ><^l y" := (~~ (><^l%O x y)) : order_scope. End LexiSyntax. Module Import SeqLexiSyntax. Notation "<=^l%O" := (@le (seqlexi_display _ _) _) : function_scope. Notation ">=^l%O" := (@ge (seqlexi_display _ _) _) : function_scope. Notation ">=^l%O" := (@ge (seqlexi_display _ _) _) : function_scope. Notation "<^l%O" := (@lt (seqlexi_display _ _) _) : function_scope. Notation ">^l%O" := (@gt (seqlexi_display _ _) _) : function_scope. Notation "<?=^l%O" := (@leif (seqlexi_display _ _) _) : function_scope. Notation ">=<^l%O" := (@comparable (seqlexi_display _ _) _) : function_scope. Notation "><^l%O" := (fun x y => ~~ (@comparable (seqlexi_display _ _) _ x y)) : function_scope. Notation "<=^l y" := (>=^l%O y) : order_scope. Notation "<=^l y :> T" := (<=^l (y : T)) (only parsing) : order_scope. Notation ">=^l y" := (<=^l%O y) : order_scope. Notation ">=^l y :> T" := (>=^l (y : T)) (only parsing) : order_scope. Notation "<^l y" := (>^l%O y) : order_scope. Notation "<^l y :> T" := (<^l (y : T)) (only parsing) : order_scope. Notation ">^l y" := (<^l%O y) : order_scope. Notation ">^l y :> T" := (>^l (y : T)) (only parsing) : order_scope. Notation "x <=^l y" := (<=^l%O x y) : order_scope. Notation "x <=^l y :> T" := ((x : T) <=^l (y : T)) (only parsing) : order_scope. Notation "x >=^l y" := (y <=^l x) (only parsing) : order_scope. Notation "x >=^l y :> T" := ((x : T) >=^l (y : T)) (only parsing) : order_scope. Notation "x <^l y" := (<^l%O x y) : order_scope. Notation "x <^l y :> T" := ((x : T) <^l (y : T)) (only parsing) : order_scope. Notation "x >^l y" := (y <^l x) (only parsing) : order_scope. Notation "x >^l y :> T" := ((x : T) >^l (y : T)) (only parsing) : order_scope. Notation "x <=^l y <=^l z" := ((x <=^l y) && (y <=^l z)) : order_scope. Notation "x <^l y <=^l z" := ((x <^l y) && (y <=^l z)) : order_scope. Notation "x <=^l y <^l z" := ((x <=^l y) && (y <^l z)) : order_scope. Notation "x <^l y <^l z" := ((x <^l y) && (y <^l z)) : order_scope. Notation "x <=^l y ?= 'iff' C" := (<?=^l%O x y C) : order_scope. Notation "x <=^l y ?= 'iff' C :> T" := ((x : T) <=^l (y : T) ?= iff C) (only parsing) : order_scope. Notation ">=<^l y" := [pred x | >=<^l%O x y] : order_scope. Notation ">=<^l y :> T" := (>=<^l (y : T)) (only parsing) : order_scope. Notation "x >=<^l y" := (>=<^l%O x y) : order_scope. Notation "><^l y" := [pred x | ~~ (>=<^l%O x y)] : order_scope. Notation "><^l y :> T" := (><^l (y : T)) (only parsing) : order_scope. Notation "x ><^l y" := (~~ (><^l%O x y)) : order_scope. End SeqLexiSyntax. (************************************************) (* We declare an alias of the cartesian product *) (* which has canonical product order. *) (************************************************) Module ProdOrder. Local Open Scope type_scope. (* FIXME *) Definition type (disp : disp_t) (T T' : Type) := T * T'. Definition type_ (disp1 disp2 : disp_t) (T : preorderType disp1) (T' : preorderType disp2) := type (prod_display disp1 disp2) T T'. Section Basis. Context {disp : disp_t}. Local Notation "T * T'" := (type disp T T') : type_scope. #[export] HB.instance Definition _ (T T' : eqType) := Equality.on (T * T'). #[export] HB.instance Definition _ (T T' : choiceType) := Choice.on (T * T'). #[export] HB.instance Definition _ (T T' : countType) := Countable.on (T * T'). #[export] HB.instance Definition _ (T T' : finType) := Finite.on (T * T'). End Basis. Section Preorder. Context (disp1 disp2 : disp_t). Context (T1 : preorderType disp1) (T2 : preorderType disp2). Implicit Types (x y : T1 * T2). Let le x y := (x.1 <= y.1) && (x.2 <= y.2). Let lt x y := (x.1 < y.1) && (x.2 <= y.2) || (x.1 <= y.1) && (x.2 < y.2). Fact lt_def x y : lt x y = le x y && ~~ le y x. Proof. rewrite /lt /le !lt_leAnge -andbA -andb_orr. by rewrite [~~ _ && _]andbC -andb_orr andbA negb_and. Qed. Fact refl : reflexive le. Proof. by move=> ?; rewrite /le !lexx. Qed. Fact trans : transitive le. Proof. rewrite /le => y x z /andP [] hxy ? /andP [] /(le_trans hxy) ->. by apply: le_trans. Qed. End Preorder. Section Preorder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : preorderType disp1) (T2 : preorderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Let T1' : Type := T1. HB.instance Definition _ := Preorder.on T1'. Let T2' : Type := T2. HB.instance Definition _ := Preorder.on T2'. Definition le x y := (x.1 <= y.1) && (x.2 <= y.2). Definition lt x y := (x.1 < y.1) && (x.2 <= y.2) || (x.1 <= y.1) && (x.2 < y.2). #[export] HB.instance Definition _ := @isDuallyPreorder.Build disp3 (T1 * T2) le lt (@lt_def _ _ T1' T2') (@lt_def _ _ T1^d T2^d) (@refl _ _ T1' T2') (@refl _ _ T1^d T2^d) (@trans _ _ T1' T2') (@trans _ _ T1^d T2^d). Lemma leEprod x y : (x <= y) = (x.1 <= y.1) && (x.2 <= y.2). Proof. by []. Qed. Lemma ltEprod x y : (x < y) = (x.1 < y.1) && (x.2 <= y.2) || (x.1 <= y.1) && (x.2 < y.2). Proof. rewrite lt_leAnge !leEprod negb_and andb_orr andbAC -lt_leAnge -andbA. by rewrite -lt_leAnge. Qed. Lemma le_pair (x1 y1 : T1) (x2 y2 : T2) : (x1, x2) <= (y1, y2) :> T1 * T2 = (x1 <= y1) && (x2 <= y2). Proof. by []. Qed. Lemma lt_pair (x1 y1 : T1) (x2 y2 : T2) : (x1, x2) < (y1, y2) :> T1 * T2 = (x1 < y1) && (x2 <= y2) || (x1 <= y1) && (x2 < y2). Proof. exact/ltEprod. Qed. End Preorder. Section BPreorder. Context (disp1 disp2 : disp_t). Context (T1 : bPreorderType disp1) (T2 : bPreorderType disp2). Local Notation "T1 * T2" := (type (Disp tt tt) T1 T2) : type_scope. Implicit Types (x : T1 * T2). Fact le0x x : (\bot, \bot) <= x :> T1 * T2. Proof. by rewrite leEprod !le0x. Qed. End BPreorder. Section BPreorder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : bPreorderType disp1) (T2 : bPreorderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Let T1' : Type := T1. HB.instance Definition _ := BPreorder.on T1'. Let T2' : Type := T2. HB.instance Definition _ := BPreorder.on T2'. #[export] HB.instance Definition _ := @hasBottom.Build disp3 (T1 * T2) (\bot, \bot) (@le0x _ _ T1' T2'). Lemma botEprod : \bot = (\bot, \bot) :> T1 * T2. Proof. by []. Qed. End BPreorder. Section TPreorder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : tPreorderType disp1) (T2 : tPreorderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. #[export] HB.instance Definition _ := @hasTop.Build disp3 (T1 * T2) (\top, \top) (@le0x _ _ T1^d T2^d). Lemma topEprod : \top = (\top, \top) :> T1 * T2. Proof. by []. Qed. End TPreorder. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tbPreorderType disp1) (T2 : tbPreorderType disp2) := Preorder.on (type disp3 T1 T2). (* FIXME: use HB.saturate *) Section FinPreorder. Context (disp1 disp2 disp3 : disp_t). #[export] HB.instance Definition _ (T1 : finPreorderType disp1) (T2 : finPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finBPreorderType disp1) (T2 : finBPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTPreorderType disp1) (T2 : finTPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTBPreorderType disp1) (T2 : finTBPreorderType disp2) := Preorder.on (type disp3 T1 T2). End FinPreorder. Module Exports. HB.reexport ProdOrder. Notation "T *prod[ d ] T'" := (type d T T') (at level 70, d at next level, format "T *prod[ d ] T'") : type_scope. Notation "T *p T'" := (type_ T T') (at level 70, format "T *p T'") : type_scope. Definition leEprod := @leEprod. Definition ltEprod := @ltEprod. Definition le_pair := @le_pair. Definition lt_pair := @lt_pair. Definition botEprod := @botEprod. Definition topEprod := @topEprod. End Exports. End ProdOrder. HB.export ProdOrder.Exports. Module DefaultProdOrder. Section DefaultProdOrder. Context {disp1 disp2 : disp_t}. Let prod T1 T2 := T1 *prod[prod_display disp1 disp2] T2. (* FIXME: Scopes of arguments are broken in several places. *) (* FIXME: Declaring a bunch of copies is still a bit painful. *) HB.instance Definition _ (T : preorderType disp1) (T' : preorderType disp2) := Preorder.copy (T * T')%type (T *p T'). HB.instance Definition _ (T1 : bPreorderType disp1) (T2 : bPreorderType disp2) := BPreorder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tPreorderType disp1) (T2 : tPreorderType disp2) := TPreorder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : tbPreorderType disp1) (T2 : tbPreorderType disp2) := TBPreorder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finPreorderType disp1) (T2 : finPreorderType disp2) := FinPreorder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finBPreorderType disp1) (T2 : finBPreorderType disp2) := FinBPreorder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finTPreorderType disp1) (T2 : finTPreorderType disp2) := FinTPreorder.copy (T1 * T2)%type (prod T1 T2). HB.instance Definition _ (T1 : finTBPreorderType disp1) (T2 : finTBPreorderType disp2) := FinTBPreorder.copy (T1 * T2)%type (prod T1 T2). End DefaultProdOrder. End DefaultProdOrder. (*************************************************) (* We declare an alias of the cartesian product, *) (* which has canonical lexicographic order. *) (*************************************************) Module ProdLexiOrder. Local Open Scope type_scope. (* FIXME *) Definition type (disp : disp_t) (T T' : Type) := T * T'. Definition type_ (disp1 disp2 : disp_t) (T : preorderType disp1) (T' : preorderType disp2) := type (lexi_display disp1 disp2) T T'. Section Basis. Context {disp : disp_t}. Local Notation "T * T'" := (type disp T T') : type_scope. #[export] HB.instance Definition _ (T T' : eqType) := Equality.on (T * T'). #[export] HB.instance Definition _ (T T' : choiceType) := Choice.on (T * T'). #[export] HB.instance Definition _ (T T' : countType) := Countable.on (T * T'). #[export] HB.instance Definition _ (T T' : finType) := Finite.on (T * T'). End Basis. Section Preorder. Context (disp1 disp2 : disp_t). Context (T1 : preorderType disp1) (T2 : preorderType disp2). Implicit Types (x y : T1 * T2). Let le x y := (x.1 <= y.1) && ((x.1 >= y.1) ==> (x.2 <= y.2)). Let lt x y := (x.1 <= y.1) && ((x.1 >= y.1) ==> (x.2 < y.2)). Fact refl : reflexive le. Proof. by move=> ?; rewrite /le !lexx. Qed. Fact trans : transitive le. Proof. move=> y x z /andP [hxy /implyP hxy'] /andP [hyz /implyP hyz']. rewrite /le (le_trans hxy) //=; apply/implyP => hzx. by apply/le_trans/hxy'/(le_trans hyz): (hyz' (le_trans hzx hxy)). Qed. Fact lt_le_def x y : lt x y = le x y && ~~ le y x. Proof. rewrite /lt /le; case: x y => [x1 x2] [y1 y2]/=. case/boolP: (x1 <= y1); case/boolP: (y1 <= x1) => //= _ _. exact/lt_le_def. Qed. End Preorder. Section Preorder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : preorderType disp1) (T2 : preorderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Implicit Types (x y : T1 * T2). Let T1' : Type := T1. HB.instance Definition _ := Preorder.on T1'. Let T2' : Type := T2. HB.instance Definition _ := Preorder.on T2'. Definition le x y := (x.1 <= y.1) && ((x.1 >= y.1) ==> (x.2 <= y.2)). Definition lt x y := (x.1 <= y.1) && ((x.1 >= y.1) ==> (x.2 < y.2)). #[export] HB.instance Definition _ := @isDuallyPreorder.Build disp3 (T1 * T2) le lt (@lt_le_def _ _ T1' T2') (@lt_le_def _ _ T1^d T2^d) (@refl _ _ T1' T2') (@refl _ _ T1^d T2^d) (@trans _ _ T1' T2') (@trans _ _ T1^d T2^d). Lemma leEprodlexi x y : (x <= y) = (x.1 <= y.1) && ((x.1 >= y.1) ==> (x.2 <= y.2)). Proof. by []. Qed. Lemma ltEprodlexi x y : (x < y) = (x.1 <= y.1) && ((x.1 >= y.1) ==> (x.2 < y.2)). Proof. by []. Qed. Lemma lexi_pair (x1 y1 : T1) (x2 y2 : T2) : (x1, x2) <= (y1, y2) :> T1 * T2 = (x1 <= y1) && ((x1 >= y1) ==> (x2 <= y2)). Proof. by []. Qed. Lemma ltxi_pair (x1 y1 : T1) (x2 y2 : T2) : (x1, x2) < (y1, y2) :> T1 * T2 = (x1 <= y1) && ((x1 >= y1) ==> (x2 < y2)). Proof. by []. Qed. End Preorder. Section BPreorder. Context (disp1 disp2 : disp_t). Context (T1 : bPreorderType disp1) (T2 : bPreorderType disp2). Local Notation "T1 * T2" := (type (Disp tt tt) T1 T2) : type_scope. Implicit Types (x : T1 * T2). Fact le0x x : (\bot, \bot) <= x :> T1 * T2. Proof. by rewrite leEprodlexi !le0x implybT. Qed. End BPreorder. Section BPreorder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : bPreorderType disp1) (T2 : bPreorderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. Let T1' : Type := T1. HB.instance Definition _ := BPreorder.on T1'. Let T2' : Type := T2. HB.instance Definition _ := BPreorder.on T2'. #[export] HB.instance Definition _ := @hasBottom.Build disp3 (T1 * T2) (\bot, \bot) (@le0x _ _ T1' T2'). Lemma botEprodlexi : \bot = (\bot, \bot) :> T1 * T2. Proof. by []. Qed. End BPreorder. Section TPreorder. Context (disp1 disp2 disp3 : disp_t). Context (T1 : tPreorderType disp1) (T2 : tPreorderType disp2). Local Notation "T1 * T2" := (type disp3 T1 T2) : type_scope. #[export] HB.instance Definition _ := @hasTop.Build disp3 (T1 * T2) (\top, \top) (@le0x _ _ T1^d T2^d). Lemma topEprodlexi : \top = (\top, \top) :> T1 * T2. Proof. by []. Qed. End TPreorder. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (disp1 disp2 disp3 : disp_t) (T1 : tbPreorderType disp1) (T2 : tbPreorderType disp2) := Preorder.on (type disp3 T1 T2). Lemma sub_prod_lexi (disp1 disp2 disp3 disp4 : disp_t) (T1 : preorderType disp1) (T2 : preorderType disp2) : subrel (<=%O : rel (T1 *prod[disp3] T2)) (<=%O : rel (type disp4 T1 T2)). Proof. case=> [x1 x2] [y1 y2]; rewrite leEprod leEprodlexi /= => /andP[] -> ->. exact: implybT. Qed. (* FIXME: use HB.saturate *) Section ProdLexiOrder. Context (disp1 disp2 disp3 : disp_t). #[export, warning="-HB.no-new-instance"] HB.instance Definition _ (T1 : bPreorderType disp1) (T2 : bPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export, warning="-HB.no-new-instance"] HB.instance Definition _ (T1 : tPreorderType disp1) (T2 : tPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export, warning="-HB.no-new-instance"] HB.instance Definition _ (T1 : tbPreorderType disp1) (T2 : tbPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finPreorderType disp1) (T2 : finPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finBPreorderType disp1) (T2 : finBPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTPreorderType disp1) (T2 : finTPreorderType disp2) := Preorder.on (type disp3 T1 T2). #[export] HB.instance Definition _ (T1 : finTBPreorderType disp1) (T2 : finTBPreorderType disp2) := Preorder.on (type disp3 T1 T2). End ProdLexiOrder. Module Exports. HB.reexport ProdLexiOrder. Notation "T *lexi[ d ] T'" := (type d T T') (at level 70, d at next level, format "T *lexi[ d ] T'") : type_scope. Notation "T *l T'" := (type_ T T') (at level 70, format "T *l T'") : type_scope. Definition leEprodlexi := @leEprodlexi. Definition ltEprodlexi := @ltEprodlexi. Definition lexi_pair := @lexi_pair. Definition ltxi_pair := @ltxi_pair. Definition topEprodlexi := @topEprodlexi. Definition botEprodlexi := @botEprodlexi. Definition sub_prod_lexi := @sub_prod_lexi. End Exports. End ProdLexiOrder. HB.export ProdLexiOrder.Exports. Module DefaultProdLexiOrder. Section DefaultProdLexiOrder. Context {disp1 disp2 : disp_t}. Let prodlexi T1 T2 := T1 *lexi[lexi_display disp1 disp2] T2. (* FIXME: Scopes of arguments are broken in several places. *) (* FIXME: Declaring a bunch of copies is still a bit painful. *) HB.instance Definition _ (T1 : preorderType disp1) (T2 : preorderType disp2) := Preorder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : bPreorderType disp1) (T2 : bPreorderType disp2) := BPreorder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : tPreorderType disp1) (T2 : tPreorderType disp2) := TPreorder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : tbPreorderType disp1) (T2 : tbPreorderType disp2) := TBPreorder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finPreorderType disp1) (T2 : finPreorderType disp2) := FinPreorder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finBPreorderType disp1) (T2 : finBPreorderType disp2) := FinBPreorder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finTPreorderType disp1) (T2 : finTPreorderType disp2) := FinTPreorder.copy (T1 * T2)%type (prodlexi T1 T2). HB.instance Definition _ (T1 : finTBPreorderType disp1) (T2 : finTBPreorderType disp2) := FinTBPreorder.copy (T1 * T2)%type (prodlexi T1 T2). End DefaultProdLexiOrder. End DefaultProdLexiOrder. (*****************************************) (* We declare an alias of the sequences, *) (* which has canonical product order. *) (*****************************************) Module SeqProdOrder. Section SeqProdOrder. Definition type (disp : disp_t) T := seq T. Definition type_ (disp : disp_t) (T : preorderType disp) := type (seqprod_display disp) T. Context {disp disp' : disp_t}. Local Notation seq := (type disp'). #[export] HB.instance Definition _ (T : eqType) := Equality.on (seq T). #[export] HB.instance Definition _ (T : choiceType) := Choice.on (seq T). #[export] HB.instance Definition _ (T : countType) := Countable.on (seq T). Section Preorder. Context (T : preorderType disp). Implicit Types (s : seq T). Fixpoint le s1 s2 := if s1 isn't x1 :: s1' then true else if s2 isn't x2 :: s2' then false else (x1 <= x2) && le s1' s2'. Fact refl : reflexive le. Proof. by elim=> //= ? ? ?; rewrite !lexx. Qed. Fact trans : transitive le. Proof. elim=> [|y ys ihs] [|x xs] [|z zs] //= /andP[xy xys] /andP[yz yzs]. by rewrite (le_trans xy)// ihs. Qed. #[export] HB.instance Definition _ := isPreorder.Build disp' (seq T) (rrefl _) refl trans. Lemma leEseq s1 s2 : s1 <= s2 = if s1 isn't x1 :: s1' then true else if s2 isn't x2 :: s2' then false else (x1 <= x2) && (s1' <= s2' :> seq _). Proof. by case: s1. Qed. Lemma le0s s : [::] <= s :> seq _. Proof. by []. Qed. Lemma les0 s : s <= [::] = (s == [::]). Proof. by rewrite leEseq. Qed. Lemma le_cons x1 s1 x2 s2 : x1 :: s1 <= x2 :: s2 :> seq _ = (x1 <= x2) && (s1 <= s2). Proof. by []. Qed. #[export] HB.instance Definition _ := hasBottom.Build _ (seq T) le0s. Lemma botEseq : \bot = [::] :> seq T. Proof. by []. Qed. End Preorder. End SeqProdOrder. Module Exports. HB.reexport SeqProdOrder. Notation seqprod_with := type. Notation seqprod := type_. Definition leEseq := @leEseq. Definition le0s := @le0s. Definition les0 := @les0. Definition le_cons := @le_cons. Definition botEseq := @botEseq. End Exports. End SeqProdOrder. HB.export SeqProdOrder.Exports. Module DefaultSeqProdOrder. Section DefaultSeqProdOrder. Context {disp : disp_t}. Notation seqprod := (seqprod_with (seqprod_display disp)). HB.instance Definition _ (T : preorderType disp) := Preorder.copy (seq T) (seqprod T). HB.instance Definition _ (T : preorderType disp) := BPreorder.copy (seq T) (seqprod T). End DefaultSeqProdOrder. End DefaultSeqProdOrder. (*********************************************) (* We declare an alias of the sequences, *) (* which has canonical lexicographic order. *) (*********************************************) Module SeqLexiOrder. Section SeqLexiOrder. Definition type (disp : disp_t) T := seq T. Definition type_ (disp : disp_t) (T : preorderType disp) := type (seqlexi_display disp) T. Context {disp disp' : disp_t}. Local Notation seq := (type disp'). #[export] HB.instance Definition _ (T : eqType) := Equality.on (seq T). #[export] HB.instance Definition _ (T : choiceType) := Choice.on (seq T). #[export] HB.instance Definition _ (T : countType) := Countable.on (seq T). Section Preorder. Context (T : preorderType disp). Implicit Types (s : seq T). Fixpoint le s1 s2 := if s1 isn't x1 :: s1' then true else if s2 isn't x2 :: s2' then false else (x1 <= x2) && ((x1 >= x2) ==> le s1' s2'). Fixpoint lt s1 s2 := if s2 isn't x2 :: s2' then false else if s1 isn't x1 :: s1' then true else (x1 <= x2) && ((x1 >= x2) ==> lt s1' s2'). Fact refl: reflexive le. Proof. by elim => [|x s ih] //=; rewrite lexx. Qed. Fact trans: transitive le. Proof. elim=> [|y sy ihs] [|x sx] [|z sz] //= /andP[] xy /implyP yx /andP[] yz /implyP zy /=. rewrite (le_trans xy yz)/=; apply/implyP => zx. apply/ihs; first exact/yx/(le_trans yz zx). exact/zy/(le_trans zx xy). Qed. Lemma lt_le_def s1 s2 : lt s1 s2 = le s1 s2 && ~~ le s2 s1. Proof. elim: s1 s2 => [|x s1 ihs1] [|y s2]//=; rewrite ihs1. by case: (x <= y); case (y <= x). Qed. #[export] HB.instance Definition _ := isPreorder.Build disp' (seq T) lt_le_def refl trans. Lemma leEseqlexi s1 s2 : s1 <= s2 = if s1 isn't x1 :: s1' then true else if s2 isn't x2 :: s2' then false else (x1 <= x2) && ((x1 >= x2) ==> (s1' <= s2' :> seq T)). Proof. by case: s1. Qed. Lemma ltEseqlexi s1 s2 : s1 < s2 = if s2 isn't x2 :: s2' then false else if s1 isn't x1 :: s1' then true else (x1 <= x2) && ((x1 >= x2) ==> (s1' < s2' :> seq T)). Proof. by case: s1. Qed. Lemma lexi0s s : [::] <= s :> seq T. Proof. by []. Qed. Lemma lexis0 s : s <= [::] = (s == [::]). Proof. by rewrite leEseqlexi. Qed. Lemma ltxi0s s : ([::] < s :> seq T) = (s != [::]). Proof. by case: s. Qed. Lemma ltxis0 s : s < [::] = false. Proof. by rewrite ltEseqlexi. Qed. Lemma lexi_cons x1 s1 x2 s2 : x1 :: s1 <= x2 :: s2 :> seq T = (x1 <= x2) && ((x1 >= x2) ==> (s1 <= s2)). Proof. by []. Qed. Lemma ltxi_cons x1 s1 x2 s2 : x1 :: s1 < x2 :: s2 :> seq T = (x1 <= x2) && ((x1 >= x2) ==> (s1 < s2)). Proof. by []. Qed. Lemma lexi_lehead x s1 y s2 : x :: s1 <= y :: s2 :> seq T -> x <= y. Proof. by rewrite lexi_cons => /andP[]. Qed. Lemma ltxi_lehead x s1 y s2 : x :: s1 < y :: s2 :> seq T -> x <= y. Proof. by rewrite ltxi_cons => /andP[]. Qed. Lemma eqhead_lexiE (x : T) s1 s2 : (x :: s1 <= x :: s2 :> seq _) = (s1 <= s2). Proof. by rewrite lexi_cons lexx. Qed. Lemma eqhead_ltxiE (x : T) s1 s2 : (x :: s1 < x :: s2 :> seq _) = (s1 < s2). Proof. by rewrite ltxi_cons lexx. Qed. #[export] HB.instance Definition _ := hasBottom.Build _ (seq T) lexi0s. End Preorder. Lemma sub_seqprod_lexi d (T : preorderType disp) : subrel (<=%O : rel (seqprod_with d T)) (<=%O : rel (seq T)). Proof. elim=> [|x1 s1 ihs1] [|x2 s2]//=; rewrite le_cons lexi_cons /=. by move=> /andP[-> /ihs1->]; rewrite implybT. Qed. End SeqLexiOrder. Module Exports. HB.reexport SeqLexiOrder. Notation seqlexi_with := type. Notation seqlexi := type_. Definition leEseqlexi := @leEseqlexi. Definition lexi0s := @lexi0s. Definition lexis0 := @lexis0. Definition lexi_cons := @lexi_cons. Definition lexi_lehead := @lexi_lehead. Definition eqhead_lexiE := @eqhead_lexiE. Definition ltEseqltxi := @ltEseqlexi. Definition ltxi0s := @ltxi0s. Definition ltxis0 := @ltxis0. Definition ltxi_cons := @ltxi_cons. Definition ltxi_lehead := @ltxi_lehead. Definition eqhead_ltxiE := @eqhead_ltxiE. Definition sub_seqprod_lexi := @sub_seqprod_lexi. End Exports. End SeqLexiOrder. HB.export SeqLexiOrder.Exports. Module DefaultSeqLexiOrder. Section DefaultSeqLexiOrder. Context {disp : disp_t}. Notation seqlexi := (seqlexi_with (seqlexi_display disp)). HB.instance Definition _ (T : preorderType disp) := Preorder.copy (seq T) (seqlexi T). HB.instance Definition _ (T : preorderType disp) := BPreorder.copy (seq T) (seqlexi T). End DefaultSeqLexiOrder. End DefaultSeqLexiOrder. (***************************************) (* We declare an alias of the tuples, *) (* which has canonical product order. *) (***************************************) Module TupleProdOrder. Import DefaultSeqProdOrder. Section TupleProdOrder. Definition type (disp : disp_t) n T := n.-tuple T. Definition type_ (disp : disp_t) n (T : preorderType disp) := type (seqprod_display disp) n T. Context {disp disp' : disp_t}. Local Notation "n .-tuple" := (type disp' n) : type_scope. Section Basics. Context (n : nat). #[export] HB.instance Definition _ (T : eqType) := Equality.on (n.-tuple T). #[export] HB.instance Definition _ (T : eqType) := SubEquality.on (n.-tuple T). #[export] HB.instance Definition _ (T : choiceType) := SubChoice.on (n.-tuple T). #[export] HB.instance Definition _ (T : countType) := SubCountable.on (n.-tuple T). #[export] HB.instance Definition _ (T : finType) := SubFinite.on (n.-tuple T). End Basics. Section Preorder. Implicit Types (n : nat) (T : preorderType disp). (* FIXME: this instance should be dualizable, but then we should not depend *) (* on the subtype mechanism, because the pointwise order on seq cannot be the *) (* dual of itself. *) #[export] HB.instance Definition _ n T := [SubChoice_isSubPreorder of n.-tuple T by <: with disp']. Lemma leEtprod n T (t1 t2 : n.-tuple T) : t1 <= t2 = [forall i, tnth t1 i <= tnth t2 i]. Proof. elim: n => [|n IHn] in t1 t2 *. by rewrite tuple0 [t2]tuple0/= lexx; symmetry; apply/forallP => []. case: (tupleP t1) (tupleP t2) => [x1 {}t1] [x2 {}t2]. rewrite [_ <= _]le_cons [t1 <= t2 :> seq _]IHn. apply/idP/forallP => [/andP[lex12 /forallP/= let12 i]|lext12]. by case: (unliftP ord0 i) => [j ->|->]//; rewrite !tnthS. rewrite (lext12 ord0)/=; apply/forallP=> i. by have := lext12 (lift ord0 i); rewrite !tnthS. Qed. Lemma ltEtprod n T (t1 t2 : n.-tuple T) : t1 < t2 = [exists i, tnth t1 i < tnth t2 i] && [forall i, tnth t1 i <= tnth t2 i]. Proof. rewrite lt_leAnge !leEtprod negb_forall andbC. apply/andP/andP => -[] /existsP[x] xlt le; split=> //; apply/existsP; exists x. rewrite lt_leAnge xlt. by move: le => /forallP ->. by move: xlt; rewrite lt_leAnge => /andP[]. Qed. End Preorder. Section BPreorder. Context (n : nat) (T : bPreorderType disp). Implicit Types (t : n.-tuple T). Fact le0x t : [tuple \bot | _ < n] <= t :> n.-tuple T. Proof. by rewrite leEtprod; apply/forallP => i; rewrite tnth_mktuple le0x. Qed. #[export] HB.instance Definition _ := hasBottom.Build _ (n.-tuple T) le0x. Lemma botEtprod : \bot = [tuple \bot | _ < n] :> n.-tuple T. Proof. by []. Qed. End BPreorder. Section TPreorder. Context (n : nat) (T : tPreorderType disp). Implicit Types (t : n.-tuple T). Fact lex1 t : t <= [tuple \top | _ < n] :> n.-tuple T. Proof. by rewrite leEtprod; apply/forallP => i; rewrite tnth_mktuple lex1. Qed. #[export] HB.instance Definition _ := hasTop.Build _ (n.-tuple T) lex1. Lemma topEtprod : \top = [tuple \top | _ < n] :> n.-tuple T. Proof. by []. Qed. End TPreorder. (* FIXME: use HB.saturate *) #[export] HB.instance Definition _ (n : nat) (T : tbPreorderType disp) := Preorder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finPreorderType disp) := Preorder.on (n.-tuple T). #[export, warning="-HB.no-new-instance"] HB.instance Definition _ (n : nat) (T : finPreorderType disp) := Preorder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finBPreorderType disp) := Preorder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTPreorderType disp) := Preorder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : finTBPreorderType disp) := Preorder.on (n.-tuple T). End TupleProdOrder. Module Exports. HB.reexport TupleProdOrder. Notation "n .-tupleprod[ disp ]" := (type disp n) (format "n .-tupleprod[ disp ]") : type_scope. Notation "n .-tupleprod" := (type_ n) (format "n .-tupleprod") : type_scope. Definition leEtprod := @leEtprod. Definition ltEtprod := @ltEtprod. Definition botEtprod := @botEtprod. Definition topEtprod := @topEtprod. End Exports. End TupleProdOrder. HB.export TupleProdOrder.Exports. Module DefaultTupleProdOrder. Section DefaultTupleProdOrder. Context {disp : disp_t}. Notation "n .-tupleprod" := n.-tupleprod[seqprod_display disp]. HB.instance Definition _ n (T : preorderType disp) := Preorder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : bPreorderType disp) := BPreorder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tPreorderType disp) := TPreorder.copy (n.-tuple T) (n.-tupleprod T). HB.instance Definition _ n (T : tbPreorderType disp) := TBPreorder.copy (n.-tuple T) (n.-tupleprod T). End DefaultTupleProdOrder. End DefaultTupleProdOrder. (*********************************************) (* We declare an alias of the tuples, *) (* which has canonical lexicographic order. *) (*********************************************) Module TupleLexiOrder. Section TupleLexiOrder. Import DefaultSeqLexiOrder. Definition type (disp : disp_t) n T := n.-tuple T. Definition type_ (disp : disp_t) n (T : preorderType disp) := type (seqlexi_display disp) n T. Context {disp disp' : disp_t}. Local Notation "n .-tuple" := (type disp' n) : type_scope. Section Basics. Context (n : nat). #[export] HB.instance Definition _ (T : eqType) := Equality.on (n.-tuple T). #[export] HB.instance Definition _ (T : choiceType) := SubChoice.on (n.-tuple T). #[export] HB.instance Definition _ (T : countType) := SubCountable.on (n.-tuple T). #[export] HB.instance Definition _ (T : finType) := SubFinite.on (n.-tuple T). End Basics. Section Preorder. Implicit Types (T : preorderType disp). #[export, warning="-HB.no-new-instance"] HB.instance Definition _ n T := SubChoice.on (n.-tuple T). #[export] HB.instance Definition _ n T := [SubChoice_isSubPreorder of n.-tuple T by <: with disp']. End Preorder. Section BPreorder. Context (n : nat) (T : bPreorderType disp). Implicit Types (t : n.-tuple T). Fact le0x t : [tuple \bot | _ < n] <= t :> n.-tuple T. Proof. by apply: sub_seqprod_lexi; apply: le0x (t : n.-tupleprod T). Qed. #[export] HB.instance Definition _ := hasBottom.Build _ (n.-tuple T) le0x. Lemma botEtlexi : \bot = [tuple \bot | _ < n] :> n.-tuple T. Proof. by []. Qed. End BPreorder. Section TPreorder. Context (n : nat) (T : tPreorderType disp). Implicit Types (t : n.-tuple T). Fact lex1 t : t <= [tuple \top | _ < n]. Proof. by apply: sub_seqprod_lexi; apply: lex1 (t : n.-tupleprod T). Qed. #[export] HB.instance Definition _ := hasTop.Build _ (n.-tuple T) lex1. Lemma topEtlexi : \top = [tuple \top | _ < n] :> n.-tuple T. Proof. by []. Qed. End TPreorder. (* FIXME: use HB.saturate *) #[export, warning="-HB.no-new-instance"] HB.instance Definition _ (n : nat) (T : bPreorderType disp) := Preorder.on (n.-tuple T). #[export, warning="-HB.no-new-instance"] HB.instance Definition _ (n : nat) (T : tPreorderType disp) := Preorder.on (n.-tuple T). #[export] HB.instance Definition _ (n : nat) (T : tbPreorderType disp) := Preorder.on (n.-tuple T). Lemma sub_tprod_lexi d n (T : preorderType disp) : subrel (<=%O : rel (n.-tupleprod[d] T)) (<=%O : rel (n.-tuple T)). Proof. exact: sub_seqprod_lexi. Qed. End TupleLexiOrder. Module Exports. HB.reexport TupleLexiOrder. Notation "n .-tuplelexi[ disp ]" := (type disp n) (format "n .-tuplelexi[ disp ]") : type_scope. Notation "n .-tuplelexi" := (type_ n) (format "n .-tuplelexi") : type_scope. Definition topEtlexi := @topEtlexi. Definition botEtlexi := @botEtlexi. Definition sub_tprod_lexi := @sub_tprod_lexi. End Exports. End TupleLexiOrder. HB.export TupleLexiOrder.Exports. Module DefaultTupleLexiOrder. Section DefaultTupleLexiOrder. Context {disp : disp_t}. Notation "n .-tuplelexi" := n.-tuplelexi[seqlexi_display disp]. HB.instance Definition _ n (T : preorderType disp) := Preorder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : bPreorderType disp) := BPreorder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : tPreorderType disp) := TPreorder.copy (n.-tuple T) (n.-tuplelexi T). HB.instance Definition _ n (T : tbPreorderType disp) := TBPreorder.copy (n.-tuple T) (n.-tuplelexi T). End DefaultTupleLexiOrder. End DefaultTupleLexiOrder. (*********************************************) (* We declare an alias of the sets, *) (* which is canonically ordered by inclusion *) (*********************************************) Module SetSubsetOrder. Section SetSubsetOrder. Fact subset_display : disp_t. Proof. exact. Qed. Definition type (disp : disp_t) (T : finType) := {set T}. Context {disp : disp_t} {T : finType}. Local Notation "{ 'subset' T }" := (type disp T). Implicit Type (A B C : {subset T}). Lemma le_def A B : A \subset B = (A :&: B == A). Proof. exact/setIidPl/eqP. Qed. #[export] HB.instance Definition _ := Choice.on {subset T}. #[export] HB.instance Definition _ := Le_isPreorder.Build disp {subset T} (@subxx _ _) (fun A B => @subset_trans _ B A). #[export] HB.instance Definition _ := hasBottom.Build disp {subset T} (@sub0set _). #[export] HB.instance Definition _ := hasTop.Build disp {subset T} (@subsetT _). Lemma leEsubset A B : (A <= B) = (A \subset B). Proof. by []. Qed. End SetSubsetOrder. Module Exports. Arguments type disp T%_type. Notation "{ 'subset' [ d ] T }" := (type d T) (d at next level, format "{ 'subset' [ d ] T }") : type_scope. Notation "{ 'subset' T }" := {subset[subset_display] T} (format "{ 'subset' T }") : type_scope. HB.reexport. Definition leEsubset := @leEsubset. End Exports. End SetSubsetOrder. Export SetSubsetOrder.Exports. Module DefaultSetSubsetOrder. HB.instance Definition _ (T : finType) := TBPreorder.copy {set T} {subset T}. End DefaultSetSubsetOrder. Notation enum A := (sort <=%O (enum A)). Section Enum. Variables (d : disp_t) (T : finPreorderType d). Lemma cardE (A : {pred T}) : #|A| = size (enum A). Proof. by rewrite size_sort cardE. Qed. Lemma mem_enum (A : {pred T}) : enum A =i A. Proof. by move=> x; rewrite mem_sort mem_enum. Qed. Lemma enum_uniq (A : {pred T}) : uniq (enum A). Proof. by rewrite sort_uniq enum_uniq. Qed. Lemma cardT : #|T| = size (enum T). Proof. by rewrite cardT size_sort. Qed. Lemma enumT : enum T = sort <=%O (Finite.enum T). Proof. by rewrite enumT. Qed. Lemma enum0 : enum (pred0 : {pred T}) = [::]. Proof. by rewrite enum0. Qed. Lemma enum1 (x : T) : enum (pred1 x) = [:: x]. Proof. by rewrite enum1. Qed. Lemma eq_enum (A B : {pred T}) : A =i B -> enum A = enum B. Proof. by move=> /eq_enum->. Qed. Lemma eq_cardT (A : {pred T}) : A =i predT -> #|A| = size (enum T). Proof. by move=> /eq_enum<-; rewrite cardE. Qed. Lemma set_enum (A : {set T}) : [set x in enum A] = A. Proof. by apply/setP => x; rewrite inE mem_enum. Qed. Lemma enum_set0 : enum (set0 : {set T}) = [::]. Proof. by rewrite enum_set0. Qed. Lemma enum_setT : enum [set: T] = sort <=%O (Finite.enum T). Proof. by rewrite enum_setT. Qed. Lemma enum_set1 (a : T) : enum [set a] = [:: a]. Proof. by rewrite enum_set1. Qed. End Enum. Section Ordinal. Import OrdinalOrder.Exports. Lemma enum_ord n : enum 'I_n = fintype.enum 'I_n. Proof. rewrite (sorted_sort le_trans)// -(@sorted_map _ _ (val : 'I_n -> nat))/=. by rewrite val_enum_ord iota_sorted. Qed. Lemma val_enum_ord n : [seq val i | i <- enum 'I_n] = iota 0 n. Proof. by rewrite enum_ord val_enum_ord. Qed. Lemma size_enum_ord n : size (enum 'I_n) = n. Proof. by rewrite -cardE card_ord. Qed. Lemma nth_enum_ord (n : nat) (i0 : 'I_n) (m : nat) : (m < n)%N -> nth i0 (enum 'I_n) m = m :> nat. Proof. by move=> lemn; rewrite enum_ord nth_enum_ord. Qed. Lemma nth_ord_enum (n : nat) (i0 i : 'I_n) : nth i0 (enum 'I_n) i = i. Proof. by rewrite enum_ord nth_ord_enum. Qed. Lemma index_enum_ord (n : nat) (i : 'I_n) : index i (enum 'I_n) = i. Proof. by rewrite enum_ord index_enum_ord. Qed. End Ordinal. Lemma mono_sorted_enum d d' (T : finPreorderType d) (T' : preorderType d') (f : T -> T') : total (<=%O : rel T) -> {mono f : x y / (x <= y)%O} -> sorted <=%O [seq f x | x <- enum T]. Proof. move=> /sort_sorted ss_sorted lef; wlog [x0 x'0] : / (T * T')%type. by case: (enum T) => // x ? => /(_ (x, f x)). rewrite (sorted_pairwise le_trans). apply/(pairwiseP x'0) => i j; rewrite !inE !size_map -!cardT. move=> ilt jlt ij; rewrite !(nth_map x0) -?cardT// lef. by rewrite (sorted_leq_nth le_trans le_refl) ?inE -?cardT// 1?ltnW. Qed. (* This module should be exported on demand, as in module tagnat below *) Module Import EnumVal. Section EnumVal. Import OrdinalOrder.Exports. Variables (d : disp_t) (T : finPreorderType d). Implicit Types (x : T) (A : {pred T}). Definition enum_rank_in x0 A (Ax0 : x0 \in A) x := insubd (Ordinal (@enum_rank_subproof _ x0 A Ax0)) (index x (enum A)). Definition enum_rank x := @enum_rank_in x T (erefl true) x. Definition enum_val A i := nth (@enum_default _ A i) (enum A) i. Prenex Implicits enum_val. Lemma enum_valP A i : @enum_val A i \in A. Proof. suff: enum_val i \in enum A by rewrite mem_enum. by apply: mem_nth; rewrite -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 *. Qed. Lemma nth_enum_rank_in x00 x0 A Ax0 : {in A, cancel (@enum_rank_in x0 A Ax0) (nth x00 (enum A))}. Proof. move=> x Ax; rewrite /= 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 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 x0 A Ax0). Proof. move=> x; apply: ord_inj; rewrite 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. End EnumVal. Arguments enum_val {d T A}. Arguments enum_rank {d T}. End EnumVal. Notation enum_val := enum_val. Notation enum_rank_in := enum_rank_in. Notation enum_rank := enum_rank. Notation enum_valP := enum_valP. Notation enum_val_nth := enum_val_nth. Notation nth_enum_rank_in := nth_enum_rank_in. Notation nth_enum_rank := nth_enum_rank. Notation enum_rankK_in := enum_rankK_in. Notation enum_rankK := enum_rankK. Notation enum_valK_in := enum_valK_in. Notation enum_valK := enum_valK. Notation enum_rank_inj := enum_rank_inj. Notation enum_val_inj := enum_val_inj. Notation enum_val_bij_in := enum_val_bij_in. Notation eq_enum_rank_in := eq_enum_rank_in. Notation enum_rank_in_inj := enum_rank_in_inj. Notation enum_rank_bij := enum_rank_bij. Notation enum_val_bij := enum_val_bij. Module Syntax. Export PreOSyntax. Export DualSyntax. Export DvdSyntax. End Syntax. Module Theory. Export PreorderTheory. Export PreOCoercions. Export BPreorderTheory. Export TPreorderTheory. Export DualPreorder. (* FIXME? *) Export OrderMorphismTheory. Export SubPreorderTheory. End Theory. Module Exports. HB.reexport. End Exports. End Order. Export Order.Exports. Export Order.Syntax. Export Order.Preorder.Exports. Export Order.BPreorder.Exports. Export Order.TPreorder.Exports. Export Order.TBPreorder.Exports. Export Order.FinPreorder.Exports. Export Order.FinBPreorder.Exports. Export Order.FinTPreorder.Exports. Export Order.FinTBPreorder.Exports. (* FIXME: check if covered by Order.Exports *) (* Export Order.NatOrder.Exports. *) (* Export Order.NatMonotonyTheory. *) (* Export Order.NatDvd.Exports. *) (* Export Order.OrdinalOrder.Exports. *) (* Export Order.BoolOrder.Exports. *) (* Export Order.ProdOrder.Exports. *) (* Export Order.SigmaOrder.Exports. *) (* Export Order.ProdLexiOrder.Exports. *) (* Export Order.SeqProdOrder.Exports. *) (* Export Order.SeqLexiOrder.Exports. *) (* Export Order.TupleProdOrder.Exports. *) (* Export Order.TupleLexiOrder.Exports. *) Module DefaultProdOrder := Order.DefaultProdOrder. Module DefaultSeqProdOrder := Order.DefaultSeqProdOrder. Module DefaultTupleProdOrder := Order.DefaultTupleProdOrder. Module DefaultProdLexiOrder := Order.DefaultProdLexiOrder. Module DefaultSeqLexiOrder := Order.DefaultSeqLexiOrder. Module DefaultTupleLexiOrder := Order.DefaultTupleLexiOrder.
Basic.lean
/- Copyright (c) 2020 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import Mathlib.Algebra.Algebra.Spectrum.Basic import Mathlib.Algebra.Module.LinearMap.Basic import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas import Mathlib.LinearAlgebra.GeneralLinearGroup import Mathlib.RingTheory.Nilpotent.Basic import Mathlib.RingTheory.Nilpotent.Defs import Mathlib.RingTheory.Nilpotent.Lemmas import Mathlib.Tactic.Peel /-! # Eigenvectors and eigenvalues This file defines eigenspaces, eigenvalues, and eigenvalues, as well as their generalized counterparts. We follow Axler's approach [axler2015] because it allows us to derive many properties without choosing a basis and without using matrices. An eigenspace of a linear map `f` for a scalar `μ` is the kernel of the map `(f - μ • id)`. The nonzero elements of an eigenspace are eigenvectors `x`. They have the property `f x = μ • x`. If there are eigenvectors for a scalar `μ`, the scalar `μ` is called an eigenvalue. There is no consensus in the literature whether `0` is an eigenvector. Our definition of `HasEigenvector` permits only nonzero vectors. For an eigenvector `x` that may also be `0`, we write `x ∈ f.eigenspace μ`. A generalized eigenspace of a linear map `f` for a natural number `k` and a scalar `μ` is the kernel of the map `(f - μ • id) ^ k`. The nonzero elements of a generalized eigenspace are generalized eigenvectors `x`. If there are generalized eigenvectors for a natural number `k` and a scalar `μ`, the scalar `μ` is called a generalized eigenvalue. The fact that the eigenvalues are the roots of the minimal polynomial is proved in `LinearAlgebra.Eigenspace.Minpoly`. The existence of eigenvalues over an algebraically closed field (and the fact that the generalized eigenspaces then span) is deferred to `LinearAlgebra.Eigenspace.IsAlgClosed`. ## References * [Sheldon Axler, *Linear Algebra Done Right*][axler2015] * https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors ## Tags eigenspace, eigenvector, eigenvalue, eigen -/ universe u v w namespace Module namespace End open Module Set variable {K R : Type v} {V M : Type w} [CommRing R] [AddCommGroup M] [Module R M] [Field K] [AddCommGroup V] [Module K V] /-- The submodule `genEigenspace f μ k` for a linear map `f`, a scalar `μ`, and a number `k : ℕ∞` is the kernel of `(f - μ • id) ^ k` if `k` is a natural number (see Def 8.10 of [axler2015]), or the union of all these kernels if `k = ∞`. A generalized eigenspace for some exponent `k` is contained in the generalized eigenspace for exponents larger than `k`. -/ def genEigenspace (f : End R M) (μ : R) : ℕ∞ →o Submodule R M where toFun k := ⨆ l : ℕ, ⨆ _ : l ≤ k, LinearMap.ker ((f - μ • 1) ^ l) monotone' _ _ hkl := biSup_mono fun _ hi ↦ hi.trans hkl lemma mem_genEigenspace {f : End R M} {μ : R} {k : ℕ∞} {x : M} : x ∈ f.genEigenspace μ k ↔ ∃ l : ℕ, l ≤ k ∧ x ∈ LinearMap.ker ((f - μ • 1) ^ l) := by have : Nonempty {l : ℕ // l ≤ k} := ⟨⟨0, zero_le _⟩⟩ have : Directed (ι := { i : ℕ // i ≤ k }) (· ≤ ·) fun i ↦ LinearMap.ker ((f - μ • 1) ^ (i : ℕ)) := Monotone.directed_le fun m n h ↦ by simpa using (f - μ • 1).iterateKer.monotone h simp_rw [genEigenspace, OrderHom.coe_mk, LinearMap.mem_ker, iSup_subtype', Submodule.mem_iSup_of_directed _ this, LinearMap.mem_ker, Subtype.exists, exists_prop] lemma genEigenspace_directed {f : End R M} {μ : R} {k : ℕ∞} : Directed (· ≤ ·) (fun l : {l : ℕ // l ≤ k} ↦ f.genEigenspace μ l) := by have aux : Monotone ((↑) : {l : ℕ // l ≤ k} → ℕ∞) := fun x y h ↦ by simpa using h exact ((genEigenspace f μ).monotone.comp aux).directed_le lemma mem_genEigenspace_nat {f : End R M} {μ : R} {k : ℕ} {x : M} : x ∈ f.genEigenspace μ k ↔ x ∈ LinearMap.ker ((f - μ • 1) ^ k) := by rw [mem_genEigenspace] constructor · rintro ⟨l, hl, hx⟩ simp only [Nat.cast_le] at hl exact (f - μ • 1).iterateKer.monotone hl hx · intro hx exact ⟨k, le_rfl, hx⟩ lemma mem_genEigenspace_top {f : End R M} {μ : R} {x : M} : x ∈ f.genEigenspace μ ⊤ ↔ ∃ k : ℕ, x ∈ LinearMap.ker ((f - μ • 1) ^ k) := by simp [mem_genEigenspace] lemma genEigenspace_nat {f : End R M} {μ : R} {k : ℕ} : f.genEigenspace μ k = LinearMap.ker ((f - μ • 1) ^ k) := by ext; simp [mem_genEigenspace_nat] lemma genEigenspace_eq_iSup_genEigenspace_nat (f : End R M) (μ : R) (k : ℕ∞) : f.genEigenspace μ k = ⨆ l : {l : ℕ // l ≤ k}, f.genEigenspace μ l := by simp_rw [genEigenspace_nat, genEigenspace, OrderHom.coe_mk, iSup_subtype] lemma genEigenspace_top (f : End R M) (μ : R) : f.genEigenspace μ ⊤ = ⨆ k : ℕ, f.genEigenspace μ k := by rw [genEigenspace_eq_iSup_genEigenspace_nat, iSup_subtype] simp only [le_top, iSup_pos] lemma genEigenspace_one {f : End R M} {μ : R} : f.genEigenspace μ 1 = LinearMap.ker (f - μ • 1) := by rw [← Nat.cast_one, genEigenspace_nat, pow_one] @[simp] lemma mem_genEigenspace_one {f : End R M} {μ : R} {x : M} : x ∈ f.genEigenspace μ 1 ↔ f x = μ • x := by rw [genEigenspace_one, LinearMap.mem_ker, LinearMap.sub_apply, sub_eq_zero, LinearMap.smul_apply, Module.End.one_apply] -- `simp` can prove this using `genEigenspace_zero` lemma mem_genEigenspace_zero {f : End R M} {μ : R} {x : M} : x ∈ f.genEigenspace μ 0 ↔ x = 0 := by rw [← Nat.cast_zero, mem_genEigenspace_nat, pow_zero, LinearMap.mem_ker, Module.End.one_apply] @[simp] lemma genEigenspace_zero {f : End R M} {μ : R} : f.genEigenspace μ 0 = ⊥ := by ext; apply mem_genEigenspace_zero @[simp] lemma genEigenspace_zero_nat (f : End R M) (k : ℕ) : f.genEigenspace 0 k = LinearMap.ker (f ^ k) := by ext; simp [mem_genEigenspace_nat] /-- Let `M` be an `R`-module, and `f` an `R`-linear endomorphism of `M`, and let `μ : R` and `k : ℕ∞` be given. Then `x : M` satisfies `HasUnifEigenvector f μ k x` if `x ∈ f.genEigenspace μ k` and `x ≠ 0`. For `k = 1`, this means that `x` is an eigenvector of `f` with eigenvalue `μ`. -/ def HasUnifEigenvector (f : End R M) (μ : R) (k : ℕ∞) (x : M) : Prop := x ∈ f.genEigenspace μ k ∧ x ≠ 0 /-- Let `M` be an `R`-module, and `f` an `R`-linear endomorphism of `M`. Then `μ : R` and `k : ℕ∞` satisfy `HasUnifEigenvalue f μ k` if `f.genEigenspace μ k ≠ ⊥`. For `k = 1`, this means that `μ` is an eigenvalue of `f`. -/ def HasUnifEigenvalue (f : End R M) (μ : R) (k : ℕ∞) : Prop := f.genEigenspace μ k ≠ ⊥ /-- Let `M` be an `R`-module, and `f` an `R`-linear endomorphism of `M`. For `k : ℕ∞`, we define `UnifEigenvalues f k` to be the type of all `μ : R` that satisfy `f.HasUnifEigenvalue μ k`. For `k = 1` this is the type of all eigenvalues of `f`. -/ def UnifEigenvalues (f : End R M) (k : ℕ∞) : Type _ := { μ : R // f.HasUnifEigenvalue μ k } /-- The underlying value of a bundled eigenvalue. -/ @[coe] def UnifEigenvalues.val (f : Module.End R M) (k : ℕ∞) : UnifEigenvalues f k → R := Subtype.val instance UnifEigenvalues.instCoeOut {f : Module.End R M} (k : ℕ∞) : CoeOut (UnifEigenvalues f k) R where coe := UnifEigenvalues.val f k instance UnivEigenvalues.instDecidableEq [DecidableEq R] (f : Module.End R M) (k : ℕ∞) : DecidableEq (UnifEigenvalues f k) := inferInstanceAs (DecidableEq (Subtype (fun x : R ↦ f.HasUnifEigenvalue x k))) lemma HasUnifEigenvector.hasUnifEigenvalue {f : End R M} {μ : R} {k : ℕ∞} {x : M} (h : f.HasUnifEigenvector μ k x) : f.HasUnifEigenvalue μ k := by rw [HasUnifEigenvalue, Submodule.ne_bot_iff] use x; exact h lemma HasUnifEigenvector.apply_eq_smul {f : End R M} {μ : R} {x : M} (hx : f.HasUnifEigenvector μ 1 x) : f x = μ • x := mem_genEigenspace_one.mp hx.1 lemma HasUnifEigenvector.pow_apply {f : End R M} {μ : R} {v : M} (hv : f.HasUnifEigenvector μ 1 v) (n : ℕ) : (f ^ n) v = μ ^ n • v := by induction n <;> simp [*, pow_succ f, hv.apply_eq_smul, smul_smul, pow_succ' μ] theorem HasUnifEigenvalue.exists_hasUnifEigenvector {f : End R M} {μ : R} {k : ℕ∞} (hμ : f.HasUnifEigenvalue μ k) : ∃ v, f.HasUnifEigenvector μ k v := Submodule.exists_mem_ne_zero_of_ne_bot hμ lemma HasUnifEigenvalue.pow {f : End R M} {μ : R} (h : f.HasUnifEigenvalue μ 1) (n : ℕ) : (f ^ n).HasUnifEigenvalue (μ ^ n) 1 := by rw [HasUnifEigenvalue, Submodule.ne_bot_iff] obtain ⟨m : M, hm⟩ := h.exists_hasUnifEigenvector exact ⟨m, by simpa [mem_genEigenspace_one] using hm.pow_apply n, hm.2⟩ /-- A nilpotent endomorphism has nilpotent eigenvalues. See also `LinearMap.isNilpotent_trace_of_isNilpotent`. -/ lemma HasUnifEigenvalue.isNilpotent_of_isNilpotent [NoZeroSMulDivisors R M] {f : End R M} (hfn : IsNilpotent f) {μ : R} (hf : f.HasUnifEigenvalue μ 1) : IsNilpotent μ := by obtain ⟨m : M, hm⟩ := hf.exists_hasUnifEigenvector obtain ⟨n : ℕ, hn : f ^ n = 0⟩ := hfn exact ⟨n, by simpa [hn, hm.2, eq_comm (a := (0 : M))] using hm.pow_apply n⟩ lemma HasUnifEigenvalue.mem_spectrum {f : End R M} {μ : R} (hμ : HasUnifEigenvalue f μ 1) : μ ∈ spectrum R f := by refine spectrum.mem_iff.mpr fun h_unit ↦ ?_ set f' := LinearMap.GeneralLinearGroup.toLinearEquiv h_unit.unit rcases hμ.exists_hasUnifEigenvector with ⟨v, hv⟩ refine hv.2 ((LinearMap.ker_eq_bot'.mp f'.ker) v (?_ : μ • v - f v = 0)) rw [hv.apply_eq_smul, sub_self] lemma hasUnifEigenvalue_iff_mem_spectrum [FiniteDimensional K V] {f : End K V} {μ : K} : f.HasUnifEigenvalue μ 1 ↔ μ ∈ spectrum K f := by rw [spectrum.mem_iff, IsUnit.sub_iff, LinearMap.isUnit_iff_ker_eq_bot, HasUnifEigenvalue, genEigenspace_one, ne_eq, not_iff_not] simp [Submodule.ext_iff, LinearMap.mem_ker] alias ⟨_, HasUnifEigenvalue.of_mem_spectrum⟩ := hasUnifEigenvalue_iff_mem_spectrum lemma genEigenspace_div (f : End K V) (a b : K) (hb : b ≠ 0) : genEigenspace f (a / b) 1 = LinearMap.ker (b • f - a • 1) := calc genEigenspace f (a / b) 1 = genEigenspace f (b⁻¹ * a) 1 := by rw [div_eq_mul_inv, mul_comm] _ = LinearMap.ker (f - (b⁻¹ * a) • 1) := by rw [genEigenspace_one] _ = LinearMap.ker (f - b⁻¹ • a • 1) := by rw [smul_smul] _ = LinearMap.ker (b • (f - b⁻¹ • a • 1)) := by rw [LinearMap.ker_smul _ b hb] _ = LinearMap.ker (b • f - a • 1) := by rw [smul_sub, smul_inv_smul₀ hb] /-- The generalized eigenrange for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ∞` is the range of `(f - μ • id) ^ k` if `k` is a natural number, or the infimum of these ranges if `k = ∞`. -/ def genEigenrange (f : End R M) (μ : R) (k : ℕ∞) : Submodule R M := ⨅ l : ℕ, ⨅ (_ : l ≤ k), LinearMap.range ((f - μ • 1) ^ l) lemma genEigenrange_nat {f : End R M} {μ : R} {k : ℕ} : f.genEigenrange μ k = LinearMap.range ((f - μ • 1) ^ k) := by ext x simp only [genEigenrange, Nat.cast_le, Submodule.mem_iInf, LinearMap.mem_range] constructor · intro h exact h _ le_rfl · rintro ⟨x, rfl⟩ i hi have : k = i + (k - i) := by omega rw [this, pow_add] exact ⟨_, rfl⟩ /-- The exponent of a generalized eigenvalue is never 0. -/ lemma HasUnifEigenvalue.exp_ne_zero {f : End R M} {μ : R} {k : ℕ} (h : f.HasUnifEigenvalue μ k) : k ≠ 0 := by rintro rfl simp [HasUnifEigenvalue, Nat.cast_zero, genEigenspace_zero] at h /-- If there exists a natural number `k` such that the kernel of `(f - μ • id) ^ k` is the maximal generalized eigenspace, then this value is the least such `k`. If not, this value is not meaningful. -/ noncomputable def maxUnifEigenspaceIndex (f : End R M) (μ : R) := monotonicSequenceLimitIndex <| (f.genEigenspace μ).comp <| WithTop.coeOrderHom.toOrderHom /-- For an endomorphism of a Noetherian module, the maximal eigenspace is always of the form kernel `(f - μ • id) ^ k` for some `k`. -/ lemma genEigenspace_top_eq_maxUnifEigenspaceIndex [IsNoetherian R M] (f : End R M) (μ : R) : genEigenspace f μ ⊤ = f.genEigenspace μ (maxUnifEigenspaceIndex f μ) := by have := WellFoundedGT.iSup_eq_monotonicSequenceLimit <| (f.genEigenspace μ).comp <| WithTop.coeOrderHom.toOrderHom convert this using 1 simp only [genEigenspace, OrderHom.coe_mk, le_top, iSup_pos, OrderHom.comp_coe, Function.comp_def] rw [iSup_prod', iSup_subtype', ← sSup_range, ← sSup_range] congr 1 aesop lemma genEigenspace_le_genEigenspace_maxUnifEigenspaceIndex [IsNoetherian R M] (f : End R M) (μ : R) (k : ℕ∞) : f.genEigenspace μ k ≤ f.genEigenspace μ (maxUnifEigenspaceIndex f μ) := by rw [← genEigenspace_top_eq_maxUnifEigenspaceIndex] exact (f.genEigenspace μ).monotone le_top /-- Generalized eigenspaces for exponents at least `finrank K V` are equal to each other. -/ theorem genEigenspace_eq_genEigenspace_maxUnifEigenspaceIndex_of_le [IsNoetherian R M] (f : End R M) (μ : R) {k : ℕ} (hk : maxUnifEigenspaceIndex f μ ≤ k) : f.genEigenspace μ k = f.genEigenspace μ (maxUnifEigenspaceIndex f μ) := le_antisymm (genEigenspace_le_genEigenspace_maxUnifEigenspaceIndex _ _ _) ((f.genEigenspace μ).monotone <| by simpa using hk) /-- A generalized eigenvalue for some exponent `k` is also a generalized eigenvalue for exponents larger than `k`. -/ lemma HasUnifEigenvalue.le {f : End R M} {μ : R} {k m : ℕ∞} (hm : k ≤ m) (hk : f.HasUnifEigenvalue μ k) : f.HasUnifEigenvalue μ m := by unfold HasUnifEigenvalue at * contrapose! hk rw [← le_bot_iff, ← hk] exact (f.genEigenspace _).monotone hm /-- A generalized eigenvalue for some exponent `k` is also a generalized eigenvalue for positive exponents. -/ lemma HasUnifEigenvalue.lt {f : End R M} {μ : R} {k m : ℕ∞} (hm : 0 < m) (hk : f.HasUnifEigenvalue μ k) : f.HasUnifEigenvalue μ m := by apply HasUnifEigenvalue.le (k := 1) (Order.one_le_iff_pos.mpr hm) intro contra; apply hk rw [genEigenspace_one, LinearMap.ker_eq_bot] at contra rw [eq_bot_iff] intro x hx rw [mem_genEigenspace] at hx rcases hx with ⟨l, -, hx⟩ rwa [LinearMap.ker_eq_bot.mpr] at hx rw [Module.End.coe_pow (f - μ • 1) l] exact Function.Injective.iterate contra l /-- Generalized eigenvalues are actually just eigenvalues. -/ @[simp] lemma hasUnifEigenvalue_iff_hasUnifEigenvalue_one {f : End R M} {μ : R} {k : ℕ∞} (hk : 0 < k) : f.HasUnifEigenvalue μ k ↔ f.HasUnifEigenvalue μ 1 := ⟨HasUnifEigenvalue.lt zero_lt_one, HasUnifEigenvalue.lt hk⟩ lemma maxUnifEigenspaceIndex_le_finrank [FiniteDimensional K V] (f : End K V) (μ : K) : maxUnifEigenspaceIndex f μ ≤ finrank K V := by apply Nat.sInf_le intro n hn apply le_antisymm · exact (f.genEigenspace μ).monotone <| WithTop.coeOrderHom.monotone hn · change (f.genEigenspace μ) n ≤ (f.genEigenspace μ) (finrank K V) rw [genEigenspace_nat, genEigenspace_nat] apply ker_pow_le_ker_pow_finrank /-- Every generalized eigenvector is a generalized eigenvector for exponent `finrank K V`. (Lemma 8.11 of [axler2015]) -/ lemma genEigenspace_le_genEigenspace_finrank [FiniteDimensional K V] (f : End K V) (μ : K) (k : ℕ∞) : f.genEigenspace μ k ≤ f.genEigenspace μ (finrank K V) := by calc f.genEigenspace μ k ≤ f.genEigenspace μ ⊤ := (f.genEigenspace _).monotone le_top _ ≤ f.genEigenspace μ (finrank K V) := by rw [genEigenspace_top_eq_maxUnifEigenspaceIndex] exact (f.genEigenspace _).monotone <| by simpa using maxUnifEigenspaceIndex_le_finrank f μ /-- Generalized eigenspaces for exponents at least `finrank K V` are equal to each other. -/ theorem genEigenspace_eq_genEigenspace_finrank_of_le [FiniteDimensional K V] (f : End K V) (μ : K) {k : ℕ} (hk : finrank K V ≤ k) : f.genEigenspace μ k = f.genEigenspace μ (finrank K V) := le_antisymm (genEigenspace_le_genEigenspace_finrank _ _ _) ((f.genEigenspace μ).monotone <| by simpa using hk) lemma mapsTo_genEigenspace_of_comm {f g : End R M} (h : Commute f g) (μ : R) (k : ℕ∞) : MapsTo g (f.genEigenspace μ k) (f.genEigenspace μ k) := by intro x hx simp only [SetLike.mem_coe, mem_genEigenspace, LinearMap.mem_ker] at hx ⊢ rcases hx with ⟨l, hl, hx⟩ replace h : Commute ((f - μ • (1 : End R M)) ^ l) g := (h.sub_left <| Algebra.commute_algebraMap_left μ g).pow_left l use l, hl rw [← LinearMap.comp_apply, ← Module.End.mul_eq_comp, h.eq, Module.End.mul_eq_comp, LinearMap.comp_apply, hx, map_zero] /-- The restriction of `f - μ • 1` to the `k`-fold generalized `μ`-eigenspace is nilpotent. -/ lemma isNilpotent_restrict_genEigenspace_nat (f : End R M) (μ : R) (k : ℕ) (h : MapsTo (f - μ • (1 : End R M)) (f.genEigenspace μ k) (f.genEigenspace μ k) := mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f μ) μ k) : IsNilpotent ((f - μ • 1).restrict h) := by use k ext ⟨x, hx⟩ rw [mem_genEigenspace_nat] at hx rw [LinearMap.zero_apply, ZeroMemClass.coe_zero, ZeroMemClass.coe_eq_zero, Module.End.pow_restrict, LinearMap.restrict_apply] ext simpa /-- The restriction of `f - μ • 1` to the generalized `μ`-eigenspace is nilpotent. -/ lemma isNilpotent_restrict_genEigenspace_top [IsNoetherian R M] (f : End R M) (μ : R) (h : MapsTo (f - μ • (1 : End R M)) (f.genEigenspace μ ⊤) (f.genEigenspace μ ⊤) := mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f μ) μ _) : IsNilpotent ((f - μ • 1).restrict h) := by apply isNilpotent_restrict_of_le on_goal 2 => apply isNilpotent_restrict_genEigenspace_nat f μ (maxUnifEigenspaceIndex f μ) rw [genEigenspace_top_eq_maxUnifEigenspaceIndex] /-- The submodule `eigenspace f μ` for a linear map `f` and a scalar `μ` consists of all vectors `x` such that `f x = μ • x`. (Def 5.36 of [axler2015]). -/ abbrev eigenspace (f : End R M) (μ : R) : Submodule R M := f.genEigenspace μ 1 lemma eigenspace_def {f : End R M} {μ : R} : f.eigenspace μ = LinearMap.ker (f - μ • 1) := by rw [eigenspace, genEigenspace_one] @[simp] theorem eigenspace_zero (f : End R M) : f.eigenspace 0 = LinearMap.ker f := by simp only [eigenspace, ← Nat.cast_one (R := ℕ∞), genEigenspace_zero_nat, pow_one] /-- A nonzero element of an eigenspace is an eigenvector. (Def 5.7 of [axler2015]) -/ abbrev HasEigenvector (f : End R M) (μ : R) (x : M) : Prop := HasUnifEigenvector f μ 1 x lemma hasEigenvector_iff {f : End R M} {μ : R} {x : M} : f.HasEigenvector μ x ↔ x ∈ f.eigenspace μ ∧ x ≠ 0 := Iff.rfl /-- A scalar `μ` is an eigenvalue for a linear map `f` if there are nonzero vectors `x` such that `f x = μ • x`. (Def 5.5 of [axler2015]). -/ abbrev HasEigenvalue (f : End R M) (a : R) : Prop := HasUnifEigenvalue f a 1 lemma hasEigenvalue_iff {f : End R M} {μ : R} : f.HasEigenvalue μ ↔ f.eigenspace μ ≠ ⊥ := Iff.rfl /-- The eigenvalues of the endomorphism `f`, as a subtype of `R`. -/ abbrev Eigenvalues (f : End R M) : Type _ := UnifEigenvalues f 1 @[coe] abbrev Eigenvalues.val (f : Module.End R M) : Eigenvalues f → R := UnifEigenvalues.val f 1 theorem hasEigenvalue_of_hasEigenvector {f : End R M} {μ : R} {x : M} (h : HasEigenvector f μ x) : HasEigenvalue f μ := h.hasUnifEigenvalue theorem mem_eigenspace_iff {f : End R M} {μ : R} {x : M} : x ∈ eigenspace f μ ↔ f x = μ • x := mem_genEigenspace_one nonrec theorem HasEigenvector.apply_eq_smul {f : End R M} {μ : R} {x : M} (hx : f.HasEigenvector μ x) : f x = μ • x := hx.apply_eq_smul nonrec theorem HasEigenvector.pow_apply {f : End R M} {μ : R} {v : M} (hv : f.HasEigenvector μ v) (n : ℕ) : (f ^ n) v = μ ^ n • v := hv.pow_apply n theorem HasEigenvalue.exists_hasEigenvector {f : End R M} {μ : R} (hμ : f.HasEigenvalue μ) : ∃ v, f.HasEigenvector μ v := Submodule.exists_mem_ne_zero_of_ne_bot hμ nonrec lemma HasEigenvalue.pow {f : End R M} {μ : R} (h : f.HasEigenvalue μ) (n : ℕ) : (f ^ n).HasEigenvalue (μ ^ n) := h.pow n /-- A nilpotent endomorphism has nilpotent eigenvalues. See also `LinearMap.isNilpotent_trace_of_isNilpotent`. -/ nonrec lemma HasEigenvalue.isNilpotent_of_isNilpotent [NoZeroSMulDivisors R M] {f : End R M} (hfn : IsNilpotent f) {μ : R} (hf : f.HasEigenvalue μ) : IsNilpotent μ := hf.isNilpotent_of_isNilpotent hfn nonrec theorem HasEigenvalue.mem_spectrum {f : End R M} {μ : R} (hμ : HasEigenvalue f μ) : μ ∈ spectrum R f := hμ.mem_spectrum theorem hasEigenvalue_iff_mem_spectrum [FiniteDimensional K V] {f : End K V} {μ : K} : f.HasEigenvalue μ ↔ μ ∈ spectrum K f := hasUnifEigenvalue_iff_mem_spectrum alias ⟨_, HasEigenvalue.of_mem_spectrum⟩ := hasEigenvalue_iff_mem_spectrum theorem eigenspace_div (f : End K V) (a b : K) (hb : b ≠ 0) : eigenspace f (a / b) = LinearMap.ker (b • f - algebraMap K (End K V) a) := genEigenspace_div f a b hb /-- A nonzero element of a generalized eigenspace is a generalized eigenvector. (Def 8.9 of [axler2015]) -/ abbrev HasGenEigenvector (f : End R M) (μ : R) (k : ℕ) (x : M) : Prop := HasUnifEigenvector f μ k x lemma hasGenEigenvector_iff {f : End R M} {μ : R} {k : ℕ} {x : M} : f.HasGenEigenvector μ k x ↔ x ∈ f.genEigenspace μ k ∧ x ≠ 0 := Iff.rfl /-- A scalar `μ` is a generalized eigenvalue for a linear map `f` and an exponent `k ∈ ℕ` if there are generalized eigenvectors for `f`, `k`, and `μ`. -/ abbrev HasGenEigenvalue (f : End R M) (μ : R) (k : ℕ) : Prop := HasUnifEigenvalue f μ k lemma hasGenEigenvalue_iff {f : End R M} {μ : R} {k : ℕ} : f.HasGenEigenvalue μ k ↔ f.genEigenspace μ k ≠ ⊥ := Iff.rfl /-- The exponent of a generalized eigenvalue is never 0. -/ theorem exp_ne_zero_of_hasGenEigenvalue {f : End R M} {μ : R} {k : ℕ} (h : f.HasGenEigenvalue μ k) : k ≠ 0 := HasUnifEigenvalue.exp_ne_zero h /-- The union of the kernels of `(f - μ • id) ^ k` over all `k`. -/ abbrev maxGenEigenspace (f : End R M) (μ : R) : Submodule R M := genEigenspace f μ ⊤ lemma iSup_genEigenspace_eq (f : End R M) (μ : R) : ⨆ k : ℕ, (f.genEigenspace μ) k = f.maxGenEigenspace μ := by simp_rw [maxGenEigenspace, genEigenspace_top] theorem genEigenspace_le_maximal (f : End R M) (μ : R) (k : ℕ) : f.genEigenspace μ k ≤ f.maxGenEigenspace μ := (f.genEigenspace μ).monotone le_top @[simp] theorem mem_maxGenEigenspace (f : End R M) (μ : R) (m : M) : m ∈ f.maxGenEigenspace μ ↔ ∃ k : ℕ, ((f - μ • (1 : End R M)) ^ k) m = 0 := mem_genEigenspace_top /-- If there exists a natural number `k` such that the kernel of `(f - μ • id) ^ k` is the maximal generalized eigenspace, then this value is the least such `k`. If not, this value is not meaningful. -/ noncomputable abbrev maxGenEigenspaceIndex (f : End R M) (μ : R) := maxUnifEigenspaceIndex f μ /-- For an endomorphism of a Noetherian module, the maximal eigenspace is always of the form kernel `(f - μ • id) ^ k` for some `k`. -/ theorem maxGenEigenspace_eq [IsNoetherian R M] (f : End R M) (μ : R) : maxGenEigenspace f μ = f.genEigenspace μ (maxGenEigenspaceIndex f μ) := genEigenspace_top_eq_maxUnifEigenspaceIndex _ _ /-- A generalized eigenvalue for some exponent `k` is also a generalized eigenvalue for exponents larger than `k`. -/ theorem hasGenEigenvalue_of_hasGenEigenvalue_of_le {f : End R M} {μ : R} {k : ℕ} {m : ℕ} (hm : k ≤ m) (hk : f.HasGenEigenvalue μ k) : f.HasGenEigenvalue μ m := hk.le <| by simpa using hm /-- The eigenspace is a subspace of the generalized eigenspace. -/ theorem eigenspace_le_genEigenspace {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) : f.eigenspace μ ≤ f.genEigenspace μ k := (f.genEigenspace _).monotone <| by simpa using Nat.succ_le_of_lt hk theorem eigenspace_le_maxGenEigenspace {f : End R M} {μ : R} : f.eigenspace μ ≤ f.maxGenEigenspace μ := (f.genEigenspace _).monotone <| OrderTop.le_top _ /-- All eigenvalues are generalized eigenvalues. -/ theorem hasGenEigenvalue_of_hasEigenvalue {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) (hμ : f.HasEigenvalue μ) : f.HasGenEigenvalue μ k := hμ.lt <| by simpa using hk /-- All generalized eigenvalues are eigenvalues. -/ theorem hasEigenvalue_of_hasGenEigenvalue {f : End R M} {μ : R} {k : ℕ} (hμ : f.HasGenEigenvalue μ k) : f.HasEigenvalue μ := hμ.lt zero_lt_one /-- Generalized eigenvalues are actually just eigenvalues. -/ theorem hasGenEigenvalue_iff_hasEigenvalue {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) : f.HasGenEigenvalue μ k ↔ f.HasEigenvalue μ := by simp [hk] theorem maxGenEigenspace_eq_genEigenspace_finrank [FiniteDimensional K V] (f : End K V) (μ : K) : f.maxGenEigenspace μ = f.genEigenspace μ (finrank K V) := by apply le_antisymm _ <| (f.genEigenspace μ).monotone le_top rw [genEigenspace_top_eq_maxUnifEigenspaceIndex] apply genEigenspace_le_genEigenspace_finrank f μ lemma mapsTo_maxGenEigenspace_of_comm {f g : End R M} (h : Commute f g) (μ : R) : MapsTo g ↑(f.maxGenEigenspace μ) ↑(f.maxGenEigenspace μ) := mapsTo_genEigenspace_of_comm h μ ⊤ /-- The restriction of `f - μ • 1` to the `k`-fold generalized `μ`-eigenspace is nilpotent. -/ lemma isNilpotent_restrict_sub_algebraMap (f : End R M) (μ : R) (k : ℕ) (h : MapsTo (f - algebraMap R (End R M) μ) (f.genEigenspace μ k) (f.genEigenspace μ k) := mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f μ) μ k) : IsNilpotent ((f - algebraMap R (End R M) μ).restrict h) := isNilpotent_restrict_genEigenspace_nat _ _ _ /-- The restriction of `f - μ • 1` to the generalized `μ`-eigenspace is nilpotent. -/ lemma isNilpotent_restrict_maxGenEigenspace_sub_algebraMap [IsNoetherian R M] (f : End R M) (μ : R) (h : MapsTo (f - algebraMap R (End R M) μ) ↑(f.maxGenEigenspace μ) ↑(f.maxGenEigenspace μ) := mapsTo_maxGenEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f μ) μ) : IsNilpotent ((f - algebraMap R (End R M) μ).restrict h) := by apply isNilpotent_restrict_of_le (q := f.genEigenspace μ (maxUnifEigenspaceIndex f μ)) _ (isNilpotent_restrict_genEigenspace_nat f μ (maxUnifEigenspaceIndex f μ)) rw [maxGenEigenspace_eq] lemma disjoint_genEigenspace [NoZeroSMulDivisors R M] (f : End R M) {μ₁ μ₂ : R} (hμ : μ₁ ≠ μ₂) (k l : ℕ∞) : Disjoint (f.genEigenspace μ₁ k) (f.genEigenspace μ₂ l) := by rw [genEigenspace_eq_iSup_genEigenspace_nat, genEigenspace_eq_iSup_genEigenspace_nat] simp_rw [genEigenspace_directed.disjoint_iSup_left, genEigenspace_directed.disjoint_iSup_right] rintro ⟨k, -⟩ ⟨l, -⟩ nontriviality M have := NoZeroSMulDivisors.isReduced R M rw [disjoint_iff] set p := f.genEigenspace μ₁ k ⊓ f.genEigenspace μ₂ l by_contra hp replace hp : Nontrivial p := Submodule.nontrivial_iff_ne_bot.mpr hp let f₁ : End R p := (f - algebraMap R (End R M) μ₁).restrict <| MapsTo.inter_inter (mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f μ₁) μ₁ k) (mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f μ₁) μ₂ l) let f₂ : End R p := (f - algebraMap R (End R M) μ₂).restrict <| MapsTo.inter_inter (mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f μ₂) μ₁ k) (mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f μ₂) μ₂ l) have : IsNilpotent (f₂ - f₁) := by apply Commute.isNilpotent_sub (x := f₂) (y := f₁) _ (isNilpotent_restrict_of_le inf_le_right _) (isNilpotent_restrict_of_le inf_le_left _) · ext; simp [f₁, f₂, smul_sub, sub_sub, smul_comm μ₁, add_sub_left_comm] apply mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f _) apply isNilpotent_restrict_genEigenspace_nat apply mapsTo_genEigenspace_of_comm (Algebra.mul_sub_algebraMap_commutes f _) apply isNilpotent_restrict_genEigenspace_nat have hf₁₂ : f₂ - f₁ = algebraMap R (End R p) (μ₁ - μ₂) := by ext; simp [f₁, f₂] rw [hf₁₂, IsNilpotent.map_iff (FaithfulSMul.algebraMap_injective R (End R p)), isNilpotent_iff_eq_zero, sub_eq_zero] at this contradiction lemma injOn_genEigenspace [NoZeroSMulDivisors R M] (f : End R M) (k : ℕ∞) : InjOn (f.genEigenspace · k) {μ | f.genEigenspace μ k ≠ ⊥} := by rintro μ₁ _ μ₂ hμ₂ hμ₁₂ by_contra contra apply hμ₂ simpa only [hμ₁₂, disjoint_self] using f.disjoint_genEigenspace contra k k lemma injOn_maxGenEigenspace [NoZeroSMulDivisors R M] (f : End R M) : InjOn (f.maxGenEigenspace ·) {μ | f.maxGenEigenspace μ ≠ ⊥} := injOn_genEigenspace f ⊤ theorem independent_genEigenspace [NoZeroSMulDivisors R M] (f : End R M) (k : ℕ∞) : iSupIndep (f.genEigenspace · k) := by classical suffices ∀ μ₁ (s : Finset R), μ₁ ∉ s → Disjoint (f.genEigenspace μ₁ k) (s.sup fun μ ↦ f.genEigenspace μ k) by simp_rw [iSupIndep_iff_supIndep_of_injOn (injOn_genEigenspace f k), Finset.supIndep_iff_disjoint_erase] exact fun s μ _ ↦ this _ _ (s.notMem_erase μ) intro μ₁ s induction s using Finset.induction_on with | empty => simp | insert μ₂ s _ ih => intro hμ₁₂ obtain ⟨hμ₁₂ : μ₁ ≠ μ₂, hμ₁ : μ₁ ∉ s⟩ := by rwa [Finset.mem_insert, not_or] at hμ₁₂ specialize ih hμ₁ rw [Finset.sup_insert, disjoint_iff, Submodule.eq_bot_iff] rintro x ⟨hx, hx'⟩ simp only [SetLike.mem_coe] at hx hx' suffices x ∈ genEigenspace f μ₂ k by rw [← Submodule.mem_bot (R := R), ← (f.disjoint_genEigenspace hμ₁₂ k k).eq_bot] exact ⟨hx, this⟩ obtain ⟨y, hy, z, hz, rfl⟩ := Submodule.mem_sup.mp hx'; clear hx' let g := f - μ₂ • 1 simp_rw [mem_genEigenspace, ← exists_prop] at hy ⊢ peel hy with l hlk hl simp only [LinearMap.mem_ker] at hl have hyz : (g ^ l) (y + z) ∈ (f.genEigenspace μ₁ k) ⊓ s.sup fun μ ↦ f.genEigenspace μ k := by refine ⟨f.mapsTo_genEigenspace_of_comm (g := g ^ l) ?_ μ₁ k hx, ?_⟩ · exact Algebra.mul_sub_algebraMap_pow_commutes f μ₂ l · rw [SetLike.mem_coe, map_add, hl, zero_add] suffices (s.sup fun μ ↦ f.genEigenspace μ k).map (g ^ l) ≤ s.sup fun μ ↦ f.genEigenspace μ k by exact this (Submodule.mem_map_of_mem hz) simp_rw [Finset.sup_eq_iSup, Submodule.map_iSup (ι := R), Submodule.map_iSup (ι := _ ∈ s)] refine iSup₂_mono fun μ _ ↦ ?_ rintro - ⟨u, hu, rfl⟩ refine f.mapsTo_genEigenspace_of_comm ?_ μ k hu exact Algebra.mul_sub_algebraMap_pow_commutes f μ₂ l rwa [ih.eq_bot, Submodule.mem_bot] at hyz theorem independent_maxGenEigenspace [NoZeroSMulDivisors R M] (f : End R M) : iSupIndep f.maxGenEigenspace := by apply independent_genEigenspace /-- The eigenspaces of a linear operator form an independent family of subspaces of `M`. That is, any eigenspace has trivial intersection with the span of all the other eigenspaces. -/ theorem eigenspaces_iSupIndep [NoZeroSMulDivisors R M] (f : End R M) : iSupIndep f.eigenspace := (f.independent_genEigenspace 1).mono fun _ ↦ le_rfl /-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly independent. -/ theorem eigenvectors_linearIndependent' {ι : Type*} [NoZeroSMulDivisors R M] (f : End R M) (μ : ι → R) (hμ : Function.Injective μ) (v : ι → M) (h_eigenvec : ∀ i, f.HasEigenvector (μ i) (v i)) : LinearIndependent R v := f.eigenspaces_iSupIndep.comp hμ |>.linearIndependent _ (fun i ↦ h_eigenvec i |>.left) (fun i ↦ h_eigenvec i |>.right) /-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly independent. (Lemma 5.10 of [axler2015]) We use the eigenvalues as indexing set to ensure that there is only one eigenvector for each eigenvalue in the image of `xs`. See `Module.End.eigenvectors_linearIndependent'` for an indexed variant. -/ theorem eigenvectors_linearIndependent [NoZeroSMulDivisors R M] (f : End R M) (μs : Set R) (xs : μs → M) (h_eigenvec : ∀ μ : μs, f.HasEigenvector μ (xs μ)) : LinearIndependent R xs := f.eigenvectors_linearIndependent' (fun μ : μs ↦ μ) Subtype.coe_injective _ h_eigenvec /-- If `f` maps a subspace `p` into itself, then the generalized eigenspace of the restriction of `f` to `p` is the part of the generalized eigenspace of `f` that lies in `p`. -/ theorem genEigenspace_restrict (f : End R M) (p : Submodule R M) (k : ℕ∞) (μ : R) (hfp : ∀ x : M, x ∈ p → f x ∈ p) : genEigenspace (LinearMap.restrict f hfp) μ k = Submodule.comap p.subtype (f.genEigenspace μ k) := by ext x suffices ∀ l : ℕ, genEigenspace (LinearMap.restrict f hfp) μ l = Submodule.comap p.subtype (f.genEigenspace μ l) by simp_rw [mem_genEigenspace, ← mem_genEigenspace_nat, this, Submodule.mem_comap, mem_genEigenspace (k := k), mem_genEigenspace_nat] intro l simp only [genEigenspace_nat, ← LinearMap.ker_comp] induction l with | zero => rw [pow_zero, pow_zero, Module.End.one_eq_id] apply (Submodule.ker_subtype _).symm | succ l ih => erw [pow_succ, pow_succ, LinearMap.ker_comp, LinearMap.ker_comp, ih, ← LinearMap.ker_comp, LinearMap.comp_assoc] lemma _root_.Submodule.inf_genEigenspace (f : End R M) (p : Submodule R M) {k : ℕ∞} {μ : R} (hfp : ∀ x : M, x ∈ p → f x ∈ p) : p ⊓ f.genEigenspace μ k = (genEigenspace (LinearMap.restrict f hfp) μ k).map p.subtype := by rw [f.genEigenspace_restrict _ _ _ hfp, Submodule.map_comap_eq, Submodule.range_subtype] lemma mapsTo_restrict_maxGenEigenspace_restrict_of_mapsTo {p : Submodule R M} (f g : End R M) (hf : MapsTo f p p) (hg : MapsTo g p p) {μ₁ μ₂ : R} (h : MapsTo f (g.maxGenEigenspace μ₁) (g.maxGenEigenspace μ₂)) : MapsTo (f.restrict hf) (maxGenEigenspace (g.restrict hg) μ₁) (maxGenEigenspace (g.restrict hg) μ₂) := by intro x hx simp_rw [SetLike.mem_coe, mem_maxGenEigenspace, ← LinearMap.restrict_smul_one _, LinearMap.restrict_sub _, Module.End.pow_restrict _, LinearMap.restrict_apply, Submodule.mk_eq_zero, ← mem_maxGenEigenspace] at hx ⊢ exact h hx /-- If `p` is an invariant submodule of an endomorphism `f`, then the `μ`-eigenspace of the restriction of `f` to `p` is a submodule of the `μ`-eigenspace of `f`. -/ theorem eigenspace_restrict_le_eigenspace (f : End R M) {p : Submodule R M} (hfp : ∀ x ∈ p, f x ∈ p) (μ : R) : (eigenspace (f.restrict hfp) μ).map p.subtype ≤ f.eigenspace μ := by rintro a ⟨x, hx, rfl⟩ simp only [SetLike.mem_coe, mem_eigenspace_iff, LinearMap.restrict_apply] at hx ⊢ exact congr_arg Subtype.val hx /-- Generalized eigenrange and generalized eigenspace for exponent `finrank K V` are disjoint. -/ theorem generalized_eigenvec_disjoint_range_ker [FiniteDimensional K V] (f : End K V) (μ : K) : Disjoint (f.genEigenrange μ (finrank K V)) (f.genEigenspace μ (finrank K V)) := by have h := calc Submodule.comap ((f - μ • 1) ^ finrank K V) (f.genEigenspace μ (finrank K V)) = LinearMap.ker ((f - algebraMap _ _ μ) ^ finrank K V * (f - algebraMap K (End K V) μ) ^ finrank K V) := by rw [genEigenspace_nat, ← LinearMap.ker_comp]; rfl _ = f.genEigenspace μ (finrank K V + finrank K V : ℕ) := by simp_rw [← pow_add, genEigenspace_nat]; rfl _ = f.genEigenspace μ (finrank K V) := by rw [genEigenspace_eq_genEigenspace_finrank_of_le]; omega rw [disjoint_iff_inf_le, genEigenrange_nat, LinearMap.range_eq_map, Submodule.map_inf_eq_map_inf_comap, top_inf_eq, h, genEigenspace_nat] apply Submodule.map_comap_le /-- If an invariant subspace `p` of an endomorphism `f` is disjoint from the `μ`-eigenspace of `f`, then the restriction of `f` to `p` has trivial `μ`-eigenspace. -/ theorem eigenspace_restrict_eq_bot {f : End R M} {p : Submodule R M} (hfp : ∀ x ∈ p, f x ∈ p) {μ : R} (hμp : Disjoint (f.eigenspace μ) p) : eigenspace (f.restrict hfp) μ = ⊥ := by rw [eq_bot_iff] intro x hx simpa using hμp.le_bot ⟨eigenspace_restrict_le_eigenspace f hfp μ ⟨x, hx, rfl⟩, x.prop⟩ /-- The generalized eigenspace of an eigenvalue has positive dimension for positive exponents. -/ theorem pos_finrank_genEigenspace_of_hasEigenvalue [FiniteDimensional K V] {f : End K V} {k : ℕ} {μ : K} (hx : f.HasEigenvalue μ) (hk : 0 < k) : 0 < finrank K (f.genEigenspace μ k) := calc 0 = finrank K (⊥ : Submodule K V) := by rw [finrank_bot] _ < finrank K (f.eigenspace μ) := Submodule.finrank_lt_finrank_of_lt (bot_lt_iff_ne_bot.2 hx) _ ≤ finrank K (f.genEigenspace μ k) := Submodule.finrank_mono ((f.genEigenspace μ).monotone (by simpa using Nat.succ_le_of_lt hk)) /-- A linear map maps a generalized eigenrange into itself. -/ theorem map_genEigenrange_le {f : End K V} {μ : K} {n : ℕ} : Submodule.map f (f.genEigenrange μ n) ≤ f.genEigenrange μ n := calc Submodule.map f (f.genEigenrange μ n) = LinearMap.range (f * (f - algebraMap _ _ μ) ^ n) := by rw [genEigenrange_nat]; exact (LinearMap.range_comp _ _).symm _ = LinearMap.range ((f - algebraMap _ _ μ) ^ n * f) := by rw [Algebra.mul_sub_algebraMap_pow_commutes] _ = Submodule.map ((f - algebraMap _ _ μ) ^ n) (LinearMap.range f) := LinearMap.range_comp _ _ _ ≤ f.genEigenrange μ n := by rw [genEigenrange_nat]; apply LinearMap.map_le_range lemma genEigenspace_le_smul (f : Module.End R M) (μ t : R) (k : ℕ∞) : (f.genEigenspace μ k) ≤ (t • f).genEigenspace (t * μ) k := by intro m hm simp_rw [mem_genEigenspace, ← exists_prop, LinearMap.mem_ker] at hm ⊢ peel hm with l hlk hl rw [mul_smul, ← smul_sub, smul_pow, LinearMap.smul_apply, hl, smul_zero] lemma genEigenspace_inf_le_add (f₁ f₂ : End R M) (μ₁ μ₂ : R) (k₁ k₂ : ℕ∞) (h : Commute f₁ f₂) : (f₁.genEigenspace μ₁ k₁) ⊓ (f₂.genEigenspace μ₂ k₂) ≤ (f₁ + f₂).genEigenspace (μ₁ + μ₂) (k₁ + k₂) := by intro m hm simp only [Submodule.mem_inf, mem_genEigenspace, LinearMap.mem_ker] at hm ⊢ obtain ⟨⟨l₁, hlk₁, hl₁⟩, ⟨l₂, hlk₂, hl₂⟩⟩ := hm use l₁ + l₂ have : f₁ + f₂ - (μ₁ + μ₂) • 1 = (f₁ - μ₁ • 1) + (f₂ - μ₂ • 1) := by rw [add_smul]; exact add_sub_add_comm f₁ f₂ (μ₁ • 1) (μ₂ • 1) replace h : Commute (f₁ - μ₁ • 1) (f₂ - μ₂ • 1) := (h.sub_right <| Algebra.commute_algebraMap_right μ₂ f₁).sub_left (Algebra.commute_algebraMap_left μ₁ _) rw [this, h.add_pow', LinearMap.coeFn_sum, Finset.sum_apply] constructor · simpa only [Nat.cast_add] using add_le_add hlk₁ hlk₂ refine Finset.sum_eq_zero fun ⟨i, j⟩ hij ↦ ?_ suffices (((f₁ - μ₁ • 1) ^ i) * ((f₂ - μ₂ • 1) ^ j)) m = 0 by rw [LinearMap.smul_apply, this, smul_zero] rw [Finset.mem_antidiagonal] at hij obtain hi|hj : l₁ ≤ i ∨ l₂ ≤ j := by omega · rw [(h.pow_pow i j).eq, Module.End.mul_apply, Module.End.pow_map_zero_of_le hi hl₁, LinearMap.map_zero] · rw [Module.End.mul_apply, Module.End.pow_map_zero_of_le hj hl₂, LinearMap.map_zero] lemma map_smul_of_iInf_genEigenspace_ne_bot [NoZeroSMulDivisors R M] {L F : Type*} [SMul R L] [FunLike F L (End R M)] [MulActionHomClass F R L (End R M)] (f : F) (μ : L → R) (k : ℕ∞) (h_ne : ⨅ x, (f x).genEigenspace (μ x) k ≠ ⊥) (t : R) (x : L) : μ (t • x) = t • μ x := by by_contra contra let g : L → Submodule R M := fun x ↦ (f x).genEigenspace (μ x) k have : ⨅ x, g x ≤ g x ⊓ g (t • x) := le_inf_iff.mpr ⟨iInf_le g x, iInf_le g (t • x)⟩ refine h_ne <| eq_bot_iff.mpr (le_trans this (disjoint_iff_inf_le.mp ?_)) apply Disjoint.mono_left (genEigenspace_le_smul (f x) (μ x) t k) simp only [g, map_smul] exact disjoint_genEigenspace (t • f x) (Ne.symm contra) k k lemma map_add_of_iInf_genEigenspace_ne_bot_of_commute [NoZeroSMulDivisors R M] {L F : Type*} [Add L] [FunLike F L (End R M)] [AddHomClass F L (End R M)] (f : F) (μ : L → R) (k : ℕ∞) (h_ne : ⨅ x, (f x).genEigenspace (μ x) k ≠ ⊥) (h : ∀ x y, Commute (f x) (f y)) (x y : L) : μ (x + y) = μ x + μ y := by by_contra contra let g : L → Submodule R M := fun x ↦ (f x).genEigenspace (μ x) k have : ⨅ x, g x ≤ (g x ⊓ g y) ⊓ g (x + y) := le_inf_iff.mpr ⟨le_inf_iff.mpr ⟨iInf_le g x, iInf_le g y⟩, iInf_le g (x + y)⟩ refine h_ne <| eq_bot_iff.mpr (le_trans this (disjoint_iff_inf_le.mp ?_)) apply Disjoint.mono_left (genEigenspace_inf_le_add (f x) (f y) (μ x) (μ y) k k (h x y)) simp only [g, map_add] exact disjoint_genEigenspace (f x + f y) (Ne.symm contra) _ k end End end Module
Roth.lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Combinatorics.Additive.AP.Three.Defs import Mathlib.Combinatorics.Additive.Corner.Defs import Mathlib.Combinatorics.SimpleGraph.Triangle.Removal import Mathlib.Combinatorics.SimpleGraph.Triangle.Tripartite /-! # The corners theorem and Roth's theorem This file proves the corners theorem and Roth's theorem on arithmetic progressions of length three. ## References * [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] * [Wikipedia, *Corners theorem*](https://en.wikipedia.org/wiki/Corners_theorem) -/ open Finset SimpleGraph TripartiteFromTriangles open Function hiding graph open Fintype (card) variable {G : Type*} [AddCommGroup G] {A : Finset (G × G)} {a b c : G} {n : ℕ} {ε : ℝ} namespace Corners /-- The triangle indices for the proof of the corners theorem construction. -/ private def triangleIndices (A : Finset (G × G)) : Finset (G × G × G) := A.map ⟨fun (a, b) ↦ (a, b, a + b), by rintro ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ ⟨⟩; rfl⟩ @[simp] private lemma mk_mem_triangleIndices : (a, b, c) ∈ triangleIndices A ↔ (a, b) ∈ A ∧ c = a + b := by simp only [triangleIndices, Prod.ext_iff, mem_map, Embedding.coeFn_mk, Prod.exists, eq_comm] refine ⟨?_, fun h ↦ ⟨_, _, h.1, rfl, rfl, h.2⟩⟩ rintro ⟨_, _, h₁, rfl, rfl, h₂⟩ exact ⟨h₁, h₂⟩ @[simp] private lemma card_triangleIndices : #(triangleIndices A) = #A := card_map _ private instance triangleIndices.instExplicitDisjoint : ExplicitDisjoint (triangleIndices A) := by constructor all_goals simp only [mk_mem_triangleIndices, and_imp] rintro a b _ a' - rfl - h' simp [*] at * <;> assumption private lemma noAccidental (hs : IsCornerFree (A : Set (G × G))) : NoAccidental (triangleIndices A) where eq_or_eq_or_eq a a' b b' c c' ha hb hc := by simp only [mk_mem_triangleIndices] at ha hb hc exact .inl <| hs ⟨hc.1, hb.1, ha.1, hb.2.symm.trans ha.2⟩ private lemma farFromTriangleFree_graph [Fintype G] [DecidableEq G] (hε : ε * card G ^ 2 ≤ #A) : (graph <| triangleIndices A).FarFromTriangleFree (ε / 9) := by refine farFromTriangleFree _ ?_ simp_rw [card_triangleIndices, mul_comm_div, Nat.cast_pow, Nat.cast_add] ring_nf simpa only [mul_comm] using hε end Corners variable [Fintype G] open Corners /-- An explicit form for the constant in the corners theorem. Note that this depends on `SzemerediRegularity.bound`, which is a tower-type exponential. This means `cornersTheoremBound` is in practice absolutely tiny. -/ noncomputable def cornersTheoremBound (ε : ℝ) : ℕ := ⌊(triangleRemovalBound (ε / 9) * 27)⁻¹⌋₊ + 1 /-- The **corners theorem** for finite abelian groups. The maximum density of a corner-free set in `G × G` goes to zero as `|G|` tends to infinity. -/ theorem corners_theorem (ε : ℝ) (hε : 0 < ε) (hG : cornersTheoremBound ε ≤ card G) (A : Finset (G × G)) (hAε : ε * card G ^ 2 ≤ #A) : ¬ IsCornerFree (A : Set (G × G)) := by rintro hA rw [cornersTheoremBound, Nat.add_one_le_iff] at hG have hε₁ : ε ≤ 1 := by have := hAε.trans (Nat.cast_le.2 A.card_le_univ) simp only [sq, Nat.cast_mul, Fintype.card_prod] at this rwa [mul_le_iff_le_one_left] at this positivity have := noAccidental hA rw [Nat.floor_lt' (by positivity), inv_lt_iff_one_lt_mul₀'] at hG swap · have : ε / 9 ≤ 1 := by linarith positivity refine hG.not_ge (le_of_mul_le_mul_right ?_ (by positivity : (0 : ℝ) < card G ^ 2)) classical have h₁ := (farFromTriangleFree_graph hAε).le_card_cliqueFinset rw [card_triangles, card_triangleIndices] at h₁ convert h₁.trans (Nat.cast_le.2 <| card_le_univ _) using 1 <;> simp <;> ring open Fin.NatCast in -- TODO: refactor to avoid needing the coercion /-- The **corners theorem** for `ℕ`. The maximum density of a corner-free set in `{1, ..., n} × {1, ..., n}` goes to zero as `n` tends to infinity. -/ theorem corners_theorem_nat (hε : 0 < ε) (hn : cornersTheoremBound (ε / 9) ≤ n) (A : Finset (ℕ × ℕ)) (hAn : A ⊆ range n ×ˢ range n) (hAε : ε * n ^ 2 ≤ #A) : ¬ IsCornerFree (A : Set (ℕ × ℕ)) := by rintro hA rw [← coe_subset, coe_product] at hAn have : A = Prod.map Fin.val Fin.val '' (Prod.map Nat.cast Nat.cast '' A : Set (Fin (2 * n).succ × Fin (2 * n).succ)) := by rw [Set.image_image, Set.image_congr, Set.image_id] simp only [mem_coe, Nat.succ_eq_add_one, Prod.map_apply, Fin.val_natCast, id_eq, Prod.forall, Prod.mk.injEq, Nat.mod_succ_eq_iff_lt] rintro a b hab have := hAn hab simp at this omega rw [this] at hA have := Fin.isAddFreimanIso_Iio two_ne_zero (le_refl (2 * n)) have := hA.of_image this.isAddFreimanHom Fin.val_injective.injOn <| by refine Set.image_subset_iff.2 <| hAn.trans fun x hx ↦ ?_ simp only [coe_range, Set.mem_prod, Set.mem_Iio] at hx exact ⟨Fin.natCast_strictMono (by omega) hx.1, Fin.natCast_strictMono (by omega) hx.2⟩ rw [← coe_image] at this refine corners_theorem (ε / 9) (by positivity) (by simp; omega) _ ?_ this calc _ = ε / 9 * (2 * n + 1) ^ 2 := by simp _ ≤ ε / 9 * (2 * n + n) ^ 2 := by gcongr; simp; unfold cornersTheoremBound at hn; omega _ = ε * n ^ 2 := by ring _ ≤ #A := hAε _ = _ := by rw [card_image_of_injOn] have : Set.InjOn Nat.cast (range n) := (CharP.natCast_injOn_Iio (Fin (2 * n).succ) (2 * n).succ).mono (by simp; omega) exact (this.prodMap this).mono hAn /-- **Roth's theorem** for finite abelian groups. The maximum density of a 3AP-free set in `G` goes to zero as `|G|` tends to infinity. -/ theorem roth_3ap_theorem (ε : ℝ) (hε : 0 < ε) (hG : cornersTheoremBound ε ≤ card G) (A : Finset G) (hAε : ε * card G ≤ #A) : ¬ ThreeAPFree (A : Set G) := by rintro hA classical let B : Finset (G × G) := univ.filter fun (x, y) ↦ y - x ∈ A have : ε * card G ^ 2 ≤ #B := by calc _ = card G * (ε * card G) := by ring _ ≤ card G * #A := by gcongr _ = #B := ?_ norm_cast rw [← card_univ, ← card_product] exact card_equiv ((Equiv.refl _).prodShear fun a ↦ Equiv.addLeft a) (by simp [B]) obtain ⟨x₁, y₁, x₂, y₂, hx₁y₁, hx₁y₂, hx₂y₁, hxy, hx₁x₂⟩ : ∃ x₁ y₁ x₂ y₂, y₁ - x₁ ∈ A ∧ y₂ - x₁ ∈ A ∧ y₁ - x₂ ∈ A ∧ x₁ + y₂ = x₂ + y₁ ∧ x₁ ≠ x₂ := by simpa [IsCornerFree, isCorner_iff, B, -exists_and_left, -exists_and_right] using corners_theorem ε hε hG B this have := hA hx₂y₁ hx₁y₁ hx₁y₂ <| by -- TODO: This really ought to just be `by linear_combination h` rw [sub_add_sub_comm, add_comm, add_sub_add_comm, add_right_cancel_iff, sub_eq_sub_iff_add_eq_add, add_comm, hxy, add_comm] exact hx₁x₂ <| by simpa using this.symm open Fin.NatCast in -- TODO: refactor to avoid needing the coercion /-- **Roth's theorem** for `ℕ`. The maximum density of a 3AP-free set in `{1, ..., n}` goes to zero as `n` tends to infinity. -/ theorem roth_3ap_theorem_nat (ε : ℝ) (hε : 0 < ε) (hG : cornersTheoremBound (ε / 3) ≤ n) (A : Finset ℕ) (hAn : A ⊆ range n) (hAε : ε * n ≤ #A) : ¬ ThreeAPFree (A : Set ℕ) := by rintro hA rw [← coe_subset, coe_range] at hAn have : A = Fin.val '' (Nat.cast '' A : Set (Fin (2 * n).succ)) := by rw [Set.image_image, Set.image_congr, Set.image_id] simp only [mem_coe, Nat.succ_eq_add_one, Fin.val_natCast, id_eq, Nat.mod_succ_eq_iff_lt] rintro a ha have := hAn ha simp at this omega rw [this] at hA have := Fin.isAddFreimanIso_Iio two_ne_zero (le_refl (2 * n)) have := hA.of_image this.isAddFreimanHom Fin.val_injective.injOn <| Set.image_subset_iff.2 <| hAn.trans fun x hx ↦ Fin.natCast_strictMono (by omega) <| by simpa only [coe_range, Set.mem_Iio] using hx rw [← coe_image] at this refine roth_3ap_theorem (ε / 3) (by positivity) (by simp; omega) _ ?_ this calc _ = ε / 3 * (2 * n + 1) := by simp _ ≤ ε / 3 * (2 * n + n) := by gcongr; simp; unfold cornersTheoremBound at hG; omega _ = ε * n := by ring _ ≤ #A := hAε _ = _ := by rw [card_image_of_injOn] exact (CharP.natCast_injOn_Iio (Fin (2 * n).succ) (2 * n).succ).mono <| hAn.trans <| by simp; omega open Asymptotics Filter /-- **Roth's theorem** for `ℕ` as an asymptotic statement. The maximum density of a 3AP-free set in `{1, ..., n}` goes to zero as `n` tends to infinity. -/ theorem rothNumberNat_isLittleO_id : IsLittleO atTop (fun N ↦ (rothNumberNat N : ℝ)) (fun N ↦ (N : ℝ)) := by simp only [isLittleO_iff, eventually_atTop, RCLike.norm_natCast] refine fun ε hε ↦ ⟨cornersTheoremBound (ε / 3), fun n hn ↦ ?_⟩ obtain ⟨A, hs₁, hs₂, hs₃⟩ := rothNumberNat_spec n rw [← hs₂, ← not_lt] exact fun hδn ↦ roth_3ap_theorem_nat ε hε hn _ hs₁ hδn.le hs₃
Reflection.lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Data.Fin.VecNotation import Mathlib.Algebra.BigOperators.Fin /-! # Lemmas for tuples `Fin m → α` This file contains alternative definitions of common operators on vectors which expand definitionally to the expected expression when evaluated on `![]` notation. This allows "proof by reflection", where we prove `f = ![f 0, f 1]` by defining `FinVec.etaExpand f` to be equal to the RHS definitionally, and then prove that `f = etaExpand f`. The definitions in this file should normally not be used directly; the intent is for the corresponding `*_eq` lemmas to be used in a place where they are definitionally unfolded. ## Main definitions * `FinVec.seq` * `FinVec.map` * `FinVec.sum` * `FinVec.etaExpand` -/ assert_not_exists Field namespace FinVec variable {m : ℕ} {α β : Type*} /-- Evaluate `FinVec.seq f v = ![(f 0) (v 0), (f 1) (v 1), ...]` -/ def seq : ∀ {m}, (Fin m → α → β) → (Fin m → α) → Fin m → β | 0, _, _ => ![] | _ + 1, f, v => Matrix.vecCons (f 0 (v 0)) (seq (Matrix.vecTail f) (Matrix.vecTail v)) @[simp] theorem seq_eq : ∀ {m} (f : Fin m → α → β) (v : Fin m → α), seq f v = fun i => f i (v i) | 0, _, _ => Subsingleton.elim _ _ | n + 1, f, v => funext fun i => by simp_rw [seq, seq_eq] refine i.cases ?_ fun i => ?_ · rfl · rw [Matrix.cons_val_succ] rfl example {f₁ f₂ : α → β} (a₁ a₂ : α) : seq ![f₁, f₂] ![a₁, a₂] = ![f₁ a₁, f₂ a₂] := rfl /-- `FinVec.map f v = ![f (v 0), f (v 1), ...]` -/ def map (f : α → β) {m} : (Fin m → α) → Fin m → β := seq fun _ => f /-- This can be used to prove ```lean example {f : α → β} (a₁ a₂ : α) : f ∘ ![a₁, a₂] = ![f a₁, f a₂] := (map_eq _ _).symm ``` -/ @[simp] theorem map_eq (f : α → β) {m} (v : Fin m → α) : map f v = f ∘ v := seq_eq _ _ example {f : α → β} (a₁ a₂ : α) : f ∘ ![a₁, a₂] = ![f a₁, f a₂] := (map_eq _ _).symm /-- Expand `v` to `![v 0, v 1, ...]` -/ def etaExpand {m} (v : Fin m → α) : Fin m → α := map id v /-- This can be used to prove ```lean example (a : Fin 2 → α) : a = ![a 0, a 1] := (etaExpand_eq _).symm ``` -/ @[simp] theorem etaExpand_eq {m} (v : Fin m → α) : etaExpand v = v := map_eq id v example (a : Fin 2 → α) : a = ![a 0, a 1] := (etaExpand_eq _).symm /-- `∀` with better defeq for `∀ x : Fin m → α, P x`. -/ def Forall : ∀ {m} (_ : (Fin m → α) → Prop), Prop | 0, P => P ![] | _ + 1, P => ∀ x : α, Forall fun v => P (Matrix.vecCons x v) /-- This can be used to prove ```lean example (P : (Fin 2 → α) → Prop) : (∀ f, P f) ↔ ∀ a₀ a₁, P ![a₀, a₁] := (forall_iff _).symm ``` -/ @[simp] theorem forall_iff : ∀ {m} (P : (Fin m → α) → Prop), Forall P ↔ ∀ x, P x | 0, P => by simp only [Forall, Fin.forall_fin_zero_pi] rfl | .succ n, P => by simp only [Forall, forall_iff, Fin.forall_fin_succ_pi, Matrix.vecCons] example (P : (Fin 2 → α) → Prop) : (∀ f, P f) ↔ ∀ a₀ a₁, P ![a₀, a₁] := (forall_iff _).symm /-- `∃` with better defeq for `∃ x : Fin m → α, P x`. -/ def Exists : ∀ {m} (_ : (Fin m → α) → Prop), Prop | 0, P => P ![] | _ + 1, P => ∃ x : α, Exists fun v => P (Matrix.vecCons x v) /-- This can be used to prove ```lean example (P : (Fin 2 → α) → Prop) : (∃ f, P f) ↔ ∃ a₀ a₁, P ![a₀, a₁] := (exists_iff _).symm ``` -/ theorem exists_iff : ∀ {m} (P : (Fin m → α) → Prop), Exists P ↔ ∃ x, P x | 0, P => by simp only [Exists, Fin.exists_fin_zero_pi, Matrix.vecEmpty] rfl | .succ n, P => by simp only [Exists, exists_iff, Fin.exists_fin_succ_pi, Matrix.vecCons] example (P : (Fin 2 → α) → Prop) : (∃ f, P f) ↔ ∃ a₀ a₁, P ![a₀, a₁] := (exists_iff _).symm /-- `Finset.univ.sum` with better defeq for `Fin`. -/ def sum [Add α] [Zero α] : ∀ {m} (_ : Fin m → α), α | 0, _ => 0 | 1, v => v 0 | _ + 2, v => sum (fun i => v (Fin.castSucc i)) + v (Fin.last _) -- `to_additive` without `existing` fails, see -- https://leanprover.zulipchat.com/#narrow/channel/287929-mathlib4/topic/to_additive.20complains.20about.20equation.20lemmas/near/508910537 /-- `Finset.univ.prod` with better defeq for `Fin`. -/ @[to_additive existing] def prod [Mul α] [One α] : ∀ {m} (_ : Fin m → α), α | 0, _ => 1 | 1, v => v 0 | _ + 2, v => prod (fun i => v (Fin.castSucc i)) * v (Fin.last _) /-- This can be used to prove ```lean example [CommMonoid α] (a : Fin 3 → α) : ∏ i, a i = a 0 * a 1 * a 2 := (prod_eq _).symm ``` -/ @[to_additive (attr := simp) /-- This can be used to prove ```lean example [AddCommMonoid α] (a : Fin 3 → α) : ∑ i, a i = a 0 + a 1 + a 2 := (sum_eq _).symm ``` -/] theorem prod_eq [CommMonoid α] : ∀ {m} (a : Fin m → α), prod a = ∏ i, a i | 0, _ => rfl | 1, a => (Fintype.prod_unique a).symm | n + 2, a => by rw [Fin.prod_univ_castSucc, prod, prod_eq] example [CommMonoid α] (a : Fin 3 → α) : ∏ i, a i = a 0 * a 1 * a 2 := (prod_eq _).symm example [AddCommMonoid α] (a : Fin 3 → α) : ∑ i, a i = a 0 + a 1 + a 2 := (sum_eq _).symm section Meta open Lean Meta Qq /-- Produce a term of the form `f 0 * f 1 * ... * f (n - 1)` and an application of `FinVec.prod_eq` that shows it is equal to `∏ i, f i`. -/ def mkProdEqQ {u : Level} {α : Q(Type u)} (inst : Q(CommMonoid $α)) (n : ℕ) (f : Q(Fin $n → $α)) : MetaM <| (val : Q($α)) × Q(∏ i, $f i = $val) := do match n with | 0 => return ⟨q((1 : $α)), q(Fin.prod_univ_zero $f)⟩ | m + 1 => let nezero : Q(NeZero ($m + 1)) := q(⟨Nat.succ_ne_zero _⟩) let val ← makeRHS (m + 1) f nezero (m + 1) let _ : $val =Q FinVec.prod $f := ⟨⟩ return ⟨q($val), q(FinVec.prod_eq $f |>.symm)⟩ where /-- Creates the expression `f 0 * f 1 * ... * f (n - 1)`. -/ makeRHS (n : ℕ) (f : Q(Fin $n → $α)) (nezero : Q(NeZero $n)) (k : ℕ) : MetaM Q($α) := do match k with | 0 => failure | 1 => pure q($f 0) | m + 1 => let pre ← makeRHS n f nezero m let mRaw : Q(ℕ) := mkRawNatLit m pure q($pre * $f (OfNat.ofNat $mRaw)) /-- Produce a term of the form `f 0 + f 1 + ... + f (n - 1)` and an application of `FinVec.sum_eq` that shows it is equal to `∑ i, f i`. -/ def mkSumEqQ {u : Level} {α : Q(Type u)} (inst : Q(AddCommMonoid $α)) (n : ℕ) (f : Q(Fin $n → $α)) : MetaM <| (val : Q($α)) × Q(∑ i, $f i = $val) := do match n with | 0 => return ⟨q((0 : $α)), q(Fin.sum_univ_zero $f)⟩ | m + 1 => let nezero : Q(NeZero ($m + 1)) := q(⟨Nat.succ_ne_zero _⟩) let val ← makeRHS (m + 1) f nezero (m + 1) let _ : $val =Q FinVec.sum $f := ⟨⟩ return ⟨q($val), q(FinVec.sum_eq $f |>.symm)⟩ where /-- Creates the expression `f 0 + f 1 + ... + f (n - 1)`. -/ makeRHS (n : ℕ) (f : Q(Fin $n → $α)) (nezero : Q(NeZero $n)) (k : ℕ) : MetaM Q($α) := do match k with | 0 => failure | 1 => pure q($f 0) | m + 1 => let pre ← makeRHS n f nezero m let mRaw : Q(ℕ) := mkRawNatLit m pure q($pre + $f (OfNat.ofNat $mRaw)) end Meta end FinVec namespace Fin open Qq Lean FinVec /-- Rewrites `∏ i : Fin n, f i` as `f 0 * f 1 * ... * f (n - 1)` when `n` is a numeral. -/ simproc_decl prod_univ_ofNat (∏ _ : Fin _, _) := .ofQ fun u _ e => do match u, e with | .succ _, ~q(@Finset.prod (Fin $n) _ $inst (@Finset.univ _ $instF) $f) => do match (generalizing := false) n.nat? with | .none => return .continue | .some nVal => let ⟨res, pf⟩ ← mkProdEqQ inst nVal f let ⟨_⟩ ← assertDefEqQ q($instF) q(Fin.fintype _) have _ : $n =Q $nVal := ⟨⟩ return .visit <| .mk q($res) <| some q($pf) | _, _ => return .continue /-- Rewrites `∑ i : Fin n, f i` as `f 0 + f 1 + ... + f (n - 1)` when `n` is a numeral. -/ simproc_decl sum_univ_ofNat (∑ _ : Fin _, _) := .ofQ fun u _ e => do match u, e with | .succ _, ~q(@Finset.sum (Fin $n) _ $inst (@Finset.univ _ $instF) $f) => do match n.nat? with | .none => return .continue | .some nVal => let ⟨res, pf⟩ ← mkSumEqQ inst nVal f let ⟨_⟩ ← assertDefEqQ q($instF) q(Fin.fintype _) have _ : $n =Q $nVal := ⟨⟩ return .visit <| .mk q($res) <| some q($pf) | _, _ => return .continue end Fin
AdjointAction.lean
/- Copyright (c) 2024 Frédéric Marbach. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Marbach -/ import Mathlib.Algebra.Lie.Abelian import Mathlib.Algebra.Lie.Derivation.Basic import Mathlib.Algebra.Lie.OfAssociative /-! # Adjoint action of a Lie algebra on itself This file defines the *adjoint action* of a Lie algebra on itself, and establishes basic properties. ## Main definitions - `LieDerivation.ad`: The adjoint action of a Lie algebra `L` on itself, seen as a morphism of Lie algebras from `L` to the Lie algebra of its derivations. The adjoint action is also defined in the `Mathlib/Algebra/Lie/OfAssociative.lean` file, under the name `LieAlgebra.ad`, as the morphism with values in the endormophisms of `L`. ## Main statements - `LieDerivation.coe_ad_apply_eq_ad_apply`: when seen as endomorphisms, both definitions coincide, - `LieDerivation.ad_ker_eq_center`: the kernel of the adjoint action is the center of `L`, - `LieDerivation.lie_der_ad_eq_ad_der`: the commutator of a derivation `D` and `ad x` is `ad (D x)`, - `LieDerivation.ad_isIdealMorphism`: the range of the adjoint action is an ideal of the derivations. -/ namespace LieDerivation section AdjointAction variable (R L : Type*) [CommRing R] [LieRing L] [LieAlgebra R L] /-- The adjoint action of a Lie algebra `L` on itself, seen as a morphism of Lie algebras from `L` to its derivations. Note the minus sign: this is chosen to so that `ad ⁅x, y⁆ = ⁅ad x, ad y⁆`. -/ @[simps!] def ad : L →ₗ⁅R⁆ LieDerivation R L L := { __ := - inner R L L map_lie' := by intro x y ext z simp only [AddHom.toFun_eq_coe, LinearMap.coe_toAddHom, LinearMap.neg_apply, coe_neg, Pi.neg_apply, inner_apply_apply, commutator_apply] rw [leibniz_lie, neg_lie, neg_lie, ← lie_skew x] abel } variable {R L} /-- The definitions `LieDerivation.ad` and `LieAlgebra.ad` agree. -/ @[simp] lemma coe_ad_apply_eq_ad_apply (x : L) : ad R L x = LieAlgebra.ad R L x := by ext; simp lemma ad_apply_lieDerivation (x : L) (D : LieDerivation R L L) : ad R L (D x) = - ⁅x, D⁆ := rfl lemma lie_ad (x : L) (D : LieDerivation R L L) : ⁅ad R L x, D⁆ = ⁅x, D⁆ := by ext; simp variable (R L) in /-- The kernel of the adjoint action on a Lie algebra is equal to its center. -/ lemma ad_ker_eq_center : (ad R L).ker = LieAlgebra.center R L := by ext x rw [← LieAlgebra.self_module_ker_eq_center, LieHom.mem_ker, LieModule.mem_ker] simp [DFunLike.ext_iff] /-- If the center of a Lie algebra is trivial, then the adjoint action is injective. -/ lemma injective_ad_of_center_eq_bot (h : LieAlgebra.center R L = ⊥) : Function.Injective (ad R L) := by rw [← LieHom.ker_eq_bot, ad_ker_eq_center, h] /-- The commutator of a derivation `D` and a derivation of the form `ad x` is `ad (D x)`. -/ lemma lie_der_ad_eq_ad_der (D : LieDerivation R L L) (x : L) : ⁅D, ad R L x⁆ = ad R L (D x) := by rw [ad_apply_lieDerivation, ← lie_ad, lie_skew] variable (R L) in /-- The range of the adjoint action homomorphism from a Lie algebra `L` to the Lie algebra of its derivations is an ideal of the latter. -/ lemma ad_isIdealMorphism : (ad R L).IsIdealMorphism := by simp_rw [LieHom.isIdealMorphism_iff, lie_der_ad_eq_ad_der] tauto /-- A derivation `D` belongs to the ideal range of the adjoint action iff it is of the form `ad x` for some `x` in the Lie algebra `L`. -/ lemma mem_ad_idealRange_iff {D : LieDerivation R L L} : D ∈ (ad R L).idealRange ↔ ∃ x : L, ad R L x = D := (ad R L).mem_idealRange_iff (ad_isIdealMorphism R L) lemma maxTrivSubmodule_eq_bot_of_center_eq_bot (h : LieAlgebra.center R L = ⊥) : LieModule.maxTrivSubmodule R L (LieDerivation R L L) = ⊥ := by refine (LieSubmodule.eq_bot_iff _).mpr fun D hD ↦ ext fun x ↦ ?_ have : ad R L (D x) = 0 := by rw [LieModule.mem_maxTrivSubmodule] at hD simp [ad_apply_lieDerivation, hD] rw [← LieHom.mem_ker, ad_ker_eq_center, h, LieSubmodule.mem_bot] at this simp [this] end AdjointAction end LieDerivation
Productive.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.WSeq.Relation /-! # Productive weak sequences This file defines the property of a weak sequence being productive as never stalling – the next output always comes after a finite time. Given a productive weak sequence, a regular sequence (`Seq`) can be derived from it using `toSeq`. -/ universe u namespace Stream'.WSeq variable {α : Type u} open Function /-- A weak sequence is *productive* if it never stalls forever - there are always a finite number of `think`s between `cons` constructors. The sequence itself is allowed to be infinite though. -/ class Productive (s : WSeq α) : Prop where get?_terminates : ∀ n, (get? s n).Terminates theorem productive_iff (s : WSeq α) : Productive s ↔ ∀ n, (get? s n).Terminates := ⟨fun h => h.1, fun h => ⟨h⟩⟩ instance get?_terminates (s : WSeq α) [h : Productive s] : ∀ n, (get? s n).Terminates := h.get?_terminates instance head_terminates (s : WSeq α) [Productive s] : (head s).Terminates := s.get?_terminates 0 instance productive_tail (s : WSeq α) [Productive s] : Productive (tail s) := ⟨fun n => by rw [get?_tail]; infer_instance⟩ instance productive_dropn (s : WSeq α) [Productive s] (n) : Productive (drop s n) := ⟨fun m => by rw [← get?_add]; infer_instance⟩ open Computation instance productive_ofSeq (s : Seq α) : Productive (ofSeq s) := ⟨fun n => by rw [get?_ofSeq]; infer_instance⟩ theorem productive_congr {s t : WSeq α} (h : s ~ʷ t) : Productive s ↔ Productive t := by simp only [productive_iff]; exact forall_congr' fun n => terminates_congr <| get?_congr h _ /-- Given a productive weak sequence, we can collapse all the `think`s to produce a sequence. -/ def toSeq (s : WSeq α) [Productive s] : Seq α := ⟨fun n => (get? s n).get, fun {n} h => by cases e : Computation.get (get? s (n + 1)) · assumption have := Computation.mem_of_get_eq _ e simp? [get?] at this h says simp only [get?] at this h obtain ⟨a', h'⟩ := head_some_of_head_tail_some this have := mem_unique h' (@Computation.mem_of_get_eq _ _ _ _ h) contradiction⟩ theorem toSeq_ofSeq (s : Seq α) : toSeq (ofSeq s) = s := by apply Subtype.eq; funext n dsimp [toSeq]; apply get_eq_of_mem rw [get?_ofSeq]; apply ret_mem end Stream'.WSeq
Connect.lean
/- Copyright (c) 2025 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.RestrictionHomology /-! # Connecting a chain complex and a cochain complex Given a chain complex `K`: `... ⟶ K.X 2 ⟶ K.X 1 ⟶ K.X 0`, a cochain complex `L`: `L.X 0 ⟶ L.X 1 ⟶ L.X 2 ⟶ ...`, a morphism `d₀ : K.X 0 ⟶ L.X 0` satisfying the identifies `K.d 1 0 ≫ d₀ = 0` and `d₀ ≫ L.d 0 1 = 0`, we construct a cochain complex indexed by `ℤ` of the form `... ⟶ K.X 2 ⟶ K.X 1 ⟶ K.X 0 ⟶ L.X 0 ⟶ L.X 1 ⟶ L.X 2 ⟶ ...`, where `K.X 0` lies in degree `-1` and `L.X 0` in degree `0`. ## Main definitions Say `K : ChainComplex C ℕ` and `L : CochainComplex C ℕ`, so `... ⟶ K₂ ⟶ K₁ ⟶ K₀` and `L⁰ ⟶ L¹ ⟶ L² ⟶ ...`. * `ConnectData K L`: an auxiliary structure consisting of `d₀ : K₀ ⟶ L⁰` "connecting" the complexes and proofs that the induced maps `K₁ ⟶ K₀ ⟶ L⁰` and `K₀ ⟶ L⁰ ⟶ L¹` are both zero. Now say `h : ConnectData K L`. * `CochainComplex.ConnectData.cochainComplex h` : the induced ℤ-indexed complex `... ⟶ K₁ ⟶ K₀ ⟶ L⁰ ⟶ L¹ ⟶ ...` * `CochainComplex.ConnectData.homologyIsoPos h (n : ℕ) (m : ℤ)` : if `m = n + 1`, the isomorphism `h.cochainComplex.homology m ≅ L.homology (n + 1)` * `CochainComplex.ConnectData.homologyIsoNeg h (n : ℕ) (m : ℤ)` : if `m = -(n + 2)`, the isomorphism `h.cochainComplex.homology m ≅ K.homology (n + 1)` ## TODO * Computation of `h.cochainComplex.homology k` when `k = 0` or `k = -1`. -/ universe v u open CategoryTheory Limits variable {C : Type u} [Category.{v} C] [HasZeroMorphisms C] namespace CochainComplex variable (K : ChainComplex C ℕ) (L : CochainComplex C ℕ) /-- Given `K : ChainComplex C ℕ` and `L : CochainComplex C ℕ`, this data allows to connect `K` and `L` in order to get a cochain complex indexed by `ℤ`, see `ConnectData.cochainComplex`. -/ structure ConnectData where /-- the differential which connect `K` and `L` -/ d₀ : K.X 0 ⟶ L.X 0 comp_d₀ : K.d 1 0 ≫ d₀ = 0 d₀_comp : d₀ ≫ L.d 0 1 = 0 namespace ConnectData attribute [reassoc (attr := simp)] comp_d₀ d₀_comp variable {K L} (h : ConnectData K L) variable (K L) in /-- Auxiliary definition for `ConnectData.cochainComplex`. -/ def X : ℤ → C | .ofNat n => L.X n | .negSucc n => K.X n @[simp] lemma X_ofNat (n : ℕ) : X K L n = L.X n := rfl @[simp] lemma X_negSucc (n : ℕ) : X K L (.negSucc n) = K.X n := rfl @[simp] lemma X_zero : X K L 0 = L.X 0 := rfl @[simp] lemma X_negOne : X K L (-1) = K.X 0 := rfl /-- Auxiliary definition for `ConnectData.cochainComplex`. -/ def d : ∀ (n m : ℤ), X K L n ⟶ X K L m | .ofNat n, .ofNat m => L.d n m | .negSucc n, .negSucc m => K.d n m | .negSucc 0, .ofNat 0 => h.d₀ | .ofNat _, .negSucc _ => 0 | .negSucc _, .ofNat _ => 0 @[simp] lemma d_ofNat (n m : ℕ) : h.d n m = L.d n m := rfl @[simp] lemma d_negSucc (n m : ℕ) : h.d (.negSucc n) (.negSucc m) = K.d n m := by simp [d] @[simp] lemma d_sub_one_zero : h.d (-1) 0 = h.d₀ := rfl @[simp] lemma d_zero_one : h.d 0 1 = L.d 0 1 := rfl @[simp] lemma d_sub_two_sub_one : h.d (-2) (-1) = K.d 1 0 := rfl lemma shape (n m : ℤ) (hnm : n + 1 ≠ m) : h.d n m = 0 := match n, m with | .ofNat n, .ofNat m => L.shape _ _ (by simp at hnm ⊢; omega) | .negSucc n, .negSucc m => by simpa only [d_negSucc] using K.shape n m (by simp at hnm ⊢; omega) | .negSucc 0, .ofNat 0 => by simp at hnm | .ofNat _, .negSucc m => rfl | .negSucc n, .ofNat m => by obtain _ | n := n · obtain _ | m := m · simp at hnm · rfl · rfl @[reassoc (attr := simp)] lemma d_comp_d (n m p : ℤ) : h.d n m ≫ h.d m p = 0 := by by_cases hnm : n + 1 = m; swap · rw [h.shape n m hnm, zero_comp] by_cases hmp : m + 1 = p; swap · rw [h.shape m p hmp, comp_zero] obtain n | (_ | _ | n) := n · obtain rfl : m = .ofNat (n + 1) := by simp [← hnm] obtain rfl : p = .ofNat (n + 2) := by simp [← hmp]; omega simp only [Int.ofNat_eq_coe, X_ofNat, d_ofNat, HomologicalComplex.d_comp_d] · obtain rfl : m = 0 := by omega obtain rfl : p = 1 := by omega simp · obtain rfl : m = -1 := by omega obtain rfl : p = 0 := by omega simp · obtain rfl : m = .negSucc (n + 1) := by omega obtain rfl : p = .negSucc n := by omega simp /-- Given `h : ConnectData K L` where `K : ChainComplex C ℕ` and `L : CochainComplex C ℕ`, this is the cochain complex indexed by `ℤ` obtained by connecting `K` and `L`: `... ⟶ K.X 2 ⟶ K.X 1 ⟶ K.X 0 ⟶ L.X 0 ⟶ L.X 1 ⟶ L.X 2 ⟶ ...`. -/ @[simps] def cochainComplex : CochainComplex C ℤ where X := X K L d := h.d shape := h.shape open HomologicalComplex /-- If `h : ConnectData K L`, then `h.cochainComplex` identifies to `L` in degrees `≥ 0`. -/ @[simps!] def restrictionGEIso : h.cochainComplex.restriction (ComplexShape.embeddingUpIntGE 0) ≅ L := Hom.isoOfComponents (fun n ↦ h.cochainComplex.restrictionXIso (ComplexShape.embeddingUpIntGE 0) (i := n) (i' := n) (by simp)) (by rintro n _ rfl dsimp only rw [restriction_d_eq (e := (ComplexShape.embeddingUpIntGE 0)) _ (i' := n) (j' := (n + 1 : ℕ)) (by simp) (by simp), cochainComplex_d, h.d_ofNat] simp) /-- If `h : ConnectData K L`, then `h.cochainComplex` identifies to `K` in degrees `≤ -1`. -/ @[simps!] def restrictionLEIso : h.cochainComplex.restriction (ComplexShape.embeddingUpIntLE (-1)) ≅ K := Hom.isoOfComponents (fun n ↦ h.cochainComplex.restrictionXIso (ComplexShape.embeddingUpIntLE (-1)) (i := n) (i' := .negSucc n) (by dsimp; omega)) (by rintro _ n rfl dsimp only rw [restriction_d_eq (e := (ComplexShape.embeddingUpIntLE (-1))) _ (i' := Int.negSucc (n + 1)) (j' := Int.negSucc n) (by dsimp; omega) (by dsimp; omega), cochainComplex_d, d_negSucc] simp) /-- Given `h : ConnectData K L` and `n : ℕ`, the homology of `h.cochainComplex` in degree `n + 1` identifies to the homology of `L` in degree `n + 1`. -/ noncomputable def homologyIsoPos (n : ℕ) (m : ℤ) [h.cochainComplex.HasHomology m] [L.HasHomology (n + 1)] (hm : m = (n + 1 : ℕ)) : h.cochainComplex.homology m ≅ L.homology (n + 1) := have := hasHomology_of_iso h.restrictionGEIso.symm (n + 1) (h.cochainComplex.restrictionHomologyIso (ComplexShape.embeddingUpIntGE 0) n (n + 1) (n + 2) (by simp) (by simp) (i' := m - 1) (j' := m) (k' := m + 1) (by simp; omega) (by simp; omega) (by simp; omega) (by simp) (by simp)).symm ≪≫ HomologicalComplex.homologyMapIso h.restrictionGEIso (n + 1) /-- Given `h : ConnectData K L` and `n : ℕ`, the homology of `h.cochainComplex` in degree `-(n + 2)` identifies to the homology of `K` in degree `n + 1`. -/ noncomputable def homologyIsoNeg (n : ℕ) (m : ℤ) [h.cochainComplex.HasHomology m] [K.HasHomology (n + 1)] (hm : m = -(n + 2 : ℕ)) : h.cochainComplex.homology m ≅ K.homology (n + 1) := have := hasHomology_of_iso h.restrictionLEIso.symm (n + 1) (h.cochainComplex.restrictionHomologyIso (ComplexShape.embeddingUpIntLE (-1)) (n + 2) (n + 1) n (by simp) (by simp) (i' := m - 1) (j' := m) (k' := m + 1) (by simp; omega) (by simp; omega) (by simp; omega) (by simp) (by simp)).symm ≪≫ HomologicalComplex.homologyMapIso h.restrictionLEIso (n + 1) end ConnectData end CochainComplex
Multivariate.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import Mathlib.Data.Fin.Fin2 import Mathlib.Data.TypeVec import Mathlib.Logic.Equiv.Defs /-! # Functors between the category of tuples of types, and the category Type Features: * `MvFunctor n` : the type class of multivariate functors * `f <$$> x` : notation for map -/ universe u v w open MvFunctor /-- Multivariate functors, i.e. functor between the category of type vectors and the category of Type -/ class MvFunctor {n : ℕ} (F : TypeVec n → Type*) where /-- Multivariate map, if `f : α ⟹ β` and `x : F α` then `f <$$> x : F β`. -/ map : ∀ {α β : TypeVec n}, α ⟹ β → F α → F β /-- Multivariate map, if `f : α ⟹ β` and `x : F α` then `f <$$> x : F β` -/ scoped[MvFunctor] infixr:100 " <$$> " => MvFunctor.map variable {n : ℕ} namespace MvFunctor variable {α β : TypeVec.{u} n} {F : TypeVec.{u} n → Type v} [MvFunctor F] /-- predicate lifting over multivariate functors -/ def LiftP {α : TypeVec n} (P : ∀ i, α i → Prop) (x : F α) : Prop := ∃ u : F (fun i => Subtype (P i)), (fun i => @Subtype.val _ (P i)) <$$> u = x /-- relational lifting over multivariate functors -/ def LiftR {α : TypeVec n} (R : ∀ ⦃i⦄, α i → α i → Prop) (x y : F α) : Prop := ∃ u : F (fun i => { p : α i × α i // R p.fst p.snd }), (fun i (t : { p : α i × α i // R p.fst p.snd }) => t.val.fst) <$$> u = x ∧ (fun i (t : { p : α i × α i // R p.fst p.snd }) => t.val.snd) <$$> u = y /-- given `x : F α` and a projection `i` of type vector `α`, `supp x i` is the set of `α.i` contained in `x` -/ def supp {α : TypeVec n} (x : F α) (i : Fin2 n) : Set (α i) := { y : α i | ∀ ⦃P⦄, LiftP P x → P i y } theorem of_mem_supp {α : TypeVec n} {x : F α} {P : ∀ ⦃i⦄, α i → Prop} (h : LiftP P x) (i : Fin2 n) : ∀ y ∈ supp x i, P y := fun _y hy => hy h end MvFunctor /-- laws for `MvFunctor` -/ class LawfulMvFunctor {n : ℕ} (F : TypeVec n → Type*) [MvFunctor F] : Prop where /-- `map` preserved identities, i.e., maps identity on `α` to identity on `F α` -/ id_map : ∀ {α : TypeVec n} (x : F α), TypeVec.id <$$> x = x /-- `map` preserves compositions -/ comp_map : ∀ {α β γ : TypeVec n} (g : α ⟹ β) (h : β ⟹ γ) (x : F α), (h ⊚ g) <$$> x = h <$$> g <$$> x open Nat TypeVec namespace MvFunctor export LawfulMvFunctor (comp_map) open LawfulMvFunctor variable {α β γ : TypeVec.{u} n} variable {F : TypeVec.{u} n → Type v} [MvFunctor F] variable (P : α ⟹ «repeat» n Prop) (R : α ⊗ α ⟹ «repeat» n Prop) /-- adapt `MvFunctor.LiftP` to accept predicates as arrows -/ def LiftP' : F α → Prop := MvFunctor.LiftP fun i x => ofRepeat <| P i x /-- adapt `MvFunctor.LiftR` to accept relations as arrows -/ def LiftR' : F α → F α → Prop := MvFunctor.LiftR @fun i x y => ofRepeat <| R i <| TypeVec.prod.mk _ x y variable [LawfulMvFunctor F] @[simp] theorem id_map (x : F α) : TypeVec.id <$$> x = x := LawfulMvFunctor.id_map x @[simp] theorem id_map' (x : F α) : (fun _i a => a) <$$> x = x := id_map x theorem map_map (g : α ⟹ β) (h : β ⟹ γ) (x : F α) : h <$$> g <$$> x = (h ⊚ g) <$$> x := Eq.symm <| comp_map _ _ _ section LiftP' variable (F) in theorem exists_iff_exists_of_mono {P : F α → Prop} {q : F β → Prop} (f : α ⟹ β) (g : β ⟹ α) (h₀ : f ⊚ g = TypeVec.id) (h₁ : ∀ u : F α, P u ↔ q (f <$$> u)) : (∃ u : F α, P u) ↔ ∃ u : F β, q u := by constructor <;> rintro ⟨u, h₂⟩ · refine ⟨f <$$> u, ?_⟩ apply (h₁ u).mp h₂ · refine ⟨g <$$> u, ?_⟩ rw [h₁] simp only [MvFunctor.map_map, h₀, LawfulMvFunctor.id_map, h₂] theorem LiftP_def (x : F α) : LiftP' P x ↔ ∃ u : F (Subtype_ P), subtypeVal P <$$> u = x := exists_iff_exists_of_mono F _ _ (toSubtype_of_subtype P) (by simp [MvFunctor.map_map]) theorem LiftR_def (x y : F α) : LiftR' R x y ↔ ∃ u : F (Subtype_ R), (TypeVec.prod.fst ⊚ subtypeVal R) <$$> u = x ∧ (TypeVec.prod.snd ⊚ subtypeVal R) <$$> u = y := exists_iff_exists_of_mono _ _ _ (toSubtype'_of_subtype' R) (by simp only [map_map, comp_assoc, subtypeVal_toSubtype'] simp +unfoldPartialApp [comp]) end LiftP' end MvFunctor namespace MvFunctor section LiftPLastPredIff variable {F : TypeVec.{u} (n + 1) → Type*} [MvFunctor F] [LawfulMvFunctor F] {α : TypeVec.{u} n} variable {β : Type u} variable (pp : β → Prop) private def f : ∀ n α, (fun i : Fin2 (n + 1) => { p_1 // ofRepeat (PredLast' α pp i p_1) }) ⟹ fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i // PredLast α pp p_1 } | _, α, Fin2.fs i, x => ⟨x.val, cast (by simp only [PredLast]; erw [const_iff_true]) x.property⟩ | _, _, Fin2.fz, x => ⟨x.val, x.property⟩ private def g : ∀ n α, (fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i // PredLast α pp p_1 }) ⟹ fun i : Fin2 (n + 1) => { p_1 // ofRepeat (PredLast' α pp i p_1) } | _, α, Fin2.fs i, x => ⟨x.val, cast (by simp only [PredLast]; erw [const_iff_true]) x.property⟩ | _, _, Fin2.fz, x => ⟨x.val, x.property⟩ theorem LiftP_PredLast_iff {β} (P : β → Prop) (x : F (α ::: β)) : LiftP' (PredLast' _ P) x ↔ LiftP (PredLast _ P) x := by dsimp only [LiftP, LiftP'] apply exists_iff_exists_of_mono F (f _ n α) (g _ n α) · ext i ⟨x, _⟩ cases i <;> rfl · intros rw [MvFunctor.map_map] dsimp +unfoldPartialApp [(· ⊚ ·)] suffices (fun i => Subtype.val) = (fun i x => (MvFunctor.f P n α i x).val) by rw [this] ext i ⟨x, _⟩ cases i <;> rfl variable (rr : β → β → Prop) private def f' : ∀ n α, (fun i : Fin2 (n + 1) => { p_1 : _ × _ // ofRepeat (RelLast' α rr i (TypeVec.prod.mk _ p_1.fst p_1.snd)) }) ⟹ fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i × _ // RelLast α rr p_1.fst p_1.snd } | _, α, Fin2.fs i, x => ⟨x.val, cast (by simp only [RelLast]; erw [repeatEq_iff_eq]) x.property⟩ | _, _, Fin2.fz, x => ⟨x.val, x.property⟩ private def g' : ∀ n α, (fun i : Fin2 (n + 1) => { p_1 : (α ::: β) i × _ // RelLast α rr p_1.fst p_1.snd }) ⟹ fun i : Fin2 (n + 1) => { p_1 : _ × _ // ofRepeat (RelLast' α rr i (TypeVec.prod.mk _ p_1.1 p_1.2)) } | _, α, Fin2.fs i, x => ⟨x.val, cast (by simp only [RelLast]; erw [repeatEq_iff_eq]) x.property⟩ | _, _, Fin2.fz, x => ⟨x.val, x.property⟩ theorem LiftR_RelLast_iff (x y : F (α ::: β)) : LiftR' (RelLast' _ rr) x y ↔ LiftR (RelLast _ rr) x y := by dsimp only [LiftR, LiftR'] apply exists_iff_exists_of_mono F (f' rr _ _) (g' rr _ _) · ext i ⟨x, _⟩ : 2 cases i <;> rfl · intros simp +unfoldPartialApp only [map_map, TypeVec.comp] -- Porting note: proof was -- rw [MvFunctor.map_map, MvFunctor.map_map, (· ⊚ ·), (· ⊚ ·)] -- congr <;> ext i ⟨x, _⟩ <;> cases i <;> rfl suffices (fun i t => t.val.fst) = ((fun i x => (MvFunctor.f' rr n α i x).val.fst)) ∧ (fun i t => t.val.snd) = ((fun i x => (MvFunctor.f' rr n α i x).val.snd)) by rw [this.1, this.2] constructor <;> ext i ⟨x, _⟩ <;> cases i <;> rfl end LiftPLastPredIff /-- Any type function that is (extensionally) equivalent to a functor, is itself a functor -/ def ofEquiv {F F' : TypeVec.{u} n → Type*} [MvFunctor F'] (eqv : ∀ α, F α ≃ F' α) : MvFunctor F where map f x := (eqv _).symm <| f <$$> eqv _ x end MvFunctor
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.
LocalizerMorphism.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.CategoryTheory.Localization.Equivalence /-! # Morphisms of localizers A morphism of localizers consists of a functor `F : C₁ ⥤ C₂` between two categories equipped with morphism properties `W₁` and `W₂` such that `F` sends morphisms in `W₁` to morphisms in `W₂`. If `Φ : LocalizerMorphism W₁ W₂`, and that `L₁ : C₁ ⥤ D₁` and `L₂ : C₂ ⥤ D₂` are localization functors for `W₁` and `W₂`, the induced functor `D₁ ⥤ D₂` is denoted `Φ.localizedFunctor L₁ L₂`; we introduce the condition `Φ.IsLocalizedEquivalence` which expresses that this functor is an equivalence of categories. This condition is independent of the choice of the localized categories. ## References * [Bruno Kahn and Georges Maltsiniotis, *Structures de dérivabilité*][KahnMaltsiniotis2008] -/ universe v₁ v₂ v₃ v₄ v₄' v₅ v₅' v₆ u₁ u₂ u₃ u₄ u₄' u₅ u₅' u₆ namespace CategoryTheory open Localization Functor variable {C₁ : Type u₁} {C₂ : Type u₂} {C₃ : Type u₃} {D₁ : Type u₄} {D₂ : Type u₅} [Category.{v₁} C₁] [Category.{v₂} C₂] [Category.{v₃} C₃] [Category.{v₄} D₁] [Category.{v₅} D₂] (W₁ : MorphismProperty C₁) (W₂ : MorphismProperty C₂) (W₃ : MorphismProperty C₃) /-- If `W₁ : MorphismProperty C₁` and `W₂ : MorphismProperty C₂`, a `LocalizerMorphism W₁ W₂` is the datum of a functor `C₁ ⥤ C₂` which sends morphisms in `W₁` to morphisms in `W₂` -/ structure LocalizerMorphism where /-- a functor between the two categories -/ functor : C₁ ⥤ C₂ /-- the functor is compatible with the `MorphismProperty` -/ map : W₁ ≤ W₂.inverseImage functor namespace LocalizerMorphism variable {W₁ W₂} in /-- Constructor for localizer morphisms given by a functor `F : C₁ ⥤ C₂` under the stronger assumption that the classes of morphisms `W₁` and `W₂` satisfy `W₁ = W₂.inverseImage F`. -/ @[simps] def ofEq {F : C₁ ⥤ C₂} (hW : W₁ = W₂.inverseImage F) : LocalizerMorphism W₁ W₂ where functor := F map := by rw [hW] /-- The identity functor as a morphism of localizers. -/ @[simps] def id : LocalizerMorphism W₁ W₁ where functor := 𝟭 C₁ map _ _ _ hf := hf variable {W₁ W₂ W₃} /-- The composition of two localizers morphisms. -/ @[simps] def comp (Φ : LocalizerMorphism W₁ W₂) (Ψ : LocalizerMorphism W₂ W₃) : LocalizerMorphism W₁ W₃ where functor := Φ.functor ⋙ Ψ.functor map _ _ _ hf := Ψ.map _ (Φ.map _ hf) variable (Φ : LocalizerMorphism W₁ W₂) /-- The opposite localizer morphism `LocalizerMorphism W₁.op W₂.op` deduced from `Φ : LocalizerMorphism W₁ W₂`. -/ @[simps] def op : LocalizerMorphism W₁.op W₂.op where functor := Φ.functor.op map _ _ _ hf := Φ.map _ hf variable (L₁ : C₁ ⥤ D₁) [L₁.IsLocalization W₁] (L₂ : C₂ ⥤ D₂) [L₂.IsLocalization W₂] lemma inverts : W₁.IsInvertedBy (Φ.functor ⋙ L₂) := fun _ _ _ hf => Localization.inverts L₂ W₂ _ (Φ.map _ hf) /-- When `Φ : LocalizerMorphism W₁ W₂` and that `L₁` and `L₂` are localization functors for `W₁` and `W₂`, then `Φ.localizedFunctor L₁ L₂` is the induced functor on the localized categories. -/ noncomputable def localizedFunctor : D₁ ⥤ D₂ := lift (Φ.functor ⋙ L₂) (Φ.inverts _) L₁ noncomputable instance liftingLocalizedFunctor : Lifting L₁ W₁ (Φ.functor ⋙ L₂) (Φ.localizedFunctor L₁ L₂) := by dsimp [localizedFunctor] infer_instance /-- The 2-commutative square expressing that `Φ.localizedFunctor L₁ L₂` lifts the functor `Φ.functor` -/ noncomputable instance catCommSq : CatCommSq Φ.functor L₁ L₂ (Φ.localizedFunctor L₁ L₂) := CatCommSq.mk (Lifting.iso _ W₁ _ _).symm variable (G : D₁ ⥤ D₂) section variable [CatCommSq Φ.functor L₁ L₂ G] {D₁' : Type u₄'} {D₂' : Type u₅'} [Category.{v₄'} D₁'] [Category.{v₅'} D₂'] (L₁' : C₁ ⥤ D₁') (L₂' : C₂ ⥤ D₂') [L₁'.IsLocalization W₁] [L₂'.IsLocalization W₂] (G' : D₁' ⥤ D₂') [CatCommSq Φ.functor L₁' L₂' G'] include W₁ W₂ Φ L₁ L₂ L₁' L₂' /-- If a localizer morphism induces an equivalence on some choice of localized categories, it will be so for any choice of localized categories. -/ lemma isEquivalence_imp [G.IsEquivalence] : G'.IsEquivalence := let E₁ := Localization.uniq L₁ L₁' W₁ let E₂ := Localization.uniq L₂ L₂' W₂ let e : L₁ ⋙ G ⋙ E₂.functor ≅ L₁ ⋙ E₁.functor ⋙ G' := calc L₁ ⋙ G ⋙ E₂.functor ≅ Φ.functor ⋙ L₂ ⋙ E₂.functor := (associator _ _ _).symm ≪≫ isoWhiskerRight (CatCommSq.iso Φ.functor L₁ L₂ G).symm E₂.functor ≪≫ associator _ _ _ _ ≅ Φ.functor ⋙ L₂' := isoWhiskerLeft Φ.functor (compUniqFunctor L₂ L₂' W₂) _ ≅ L₁' ⋙ G' := CatCommSq.iso Φ.functor L₁' L₂' G' _ ≅ L₁ ⋙ E₁.functor ⋙ G' := isoWhiskerRight (compUniqFunctor L₁ L₁' W₁).symm G' ≪≫ associator _ _ _ have := Functor.isEquivalence_of_iso (liftNatIso L₁ W₁ _ _ (G ⋙ E₂.functor) (E₁.functor ⋙ G') e) Functor.isEquivalence_of_comp_left E₁.functor G' lemma isEquivalence_iff : G.IsEquivalence ↔ G'.IsEquivalence := ⟨fun _ => Φ.isEquivalence_imp L₁ L₂ G L₁' L₂' G', fun _ => Φ.isEquivalence_imp L₁' L₂' G' L₁ L₂ G⟩ end /-- Condition that a `LocalizerMorphism` induces an equivalence on the localized categories -/ class IsLocalizedEquivalence : Prop where /-- the induced functor on the constructed localized categories is an equivalence -/ isEquivalence : (Φ.localizedFunctor W₁.Q W₂.Q).IsEquivalence lemma IsLocalizedEquivalence.mk' [CatCommSq Φ.functor L₁ L₂ G] [G.IsEquivalence] : Φ.IsLocalizedEquivalence where isEquivalence := by rw [Φ.isEquivalence_iff W₁.Q W₂.Q (Φ.localizedFunctor W₁.Q W₂.Q) L₁ L₂ G] exact inferInstance /-- If a `LocalizerMorphism` is a localized equivalence, then any compatible functor between the localized categories is an equivalence. -/ lemma isEquivalence [h : Φ.IsLocalizedEquivalence] [CatCommSq Φ.functor L₁ L₂ G] : G.IsEquivalence := (by rw [Φ.isEquivalence_iff L₁ L₂ G W₁.Q W₂.Q (Φ.localizedFunctor W₁.Q W₂.Q)] exact h.isEquivalence) /-- If a `LocalizerMorphism` is a localized equivalence, then the induced functor on the localized categories is an equivalence -/ instance localizedFunctor_isEquivalence [Φ.IsLocalizedEquivalence] : (Φ.localizedFunctor L₁ L₂).IsEquivalence := Φ.isEquivalence L₁ L₂ _ /-- When `Φ : LocalizerMorphism W₁ W₂`, if the composition `Φ.functor ⋙ L₂` is a localization functor for `W₁`, then `Φ` is a localized equivalence. -/ lemma IsLocalizedEquivalence.of_isLocalization_of_isLocalization [(Φ.functor ⋙ L₂).IsLocalization W₁] : IsLocalizedEquivalence Φ := by have : CatCommSq Φ.functor (Φ.functor ⋙ L₂) L₂ (𝟭 D₂) := CatCommSq.mk (rightUnitor _).symm exact IsLocalizedEquivalence.mk' Φ (Φ.functor ⋙ L₂) L₂ (𝟭 D₂) /-- When the underlying functor `Φ.functor` of `Φ : LocalizerMorphism W₁ W₂` is an equivalence of categories and that `W₁` and `W₂` essentially correspond to each other via this equivalence, then `Φ` is a localized equivalence. -/ lemma IsLocalizedEquivalence.of_equivalence [Φ.functor.IsEquivalence] (h : W₂ ≤ W₁.map Φ.functor) : IsLocalizedEquivalence Φ := by haveI : Functor.IsLocalization (Φ.functor ⋙ MorphismProperty.Q W₂) W₁ := by refine Functor.IsLocalization.of_equivalence_source W₂.Q W₂ (Φ.functor ⋙ W₂.Q) W₁ (asEquivalence Φ.functor).symm ?_ (Φ.inverts W₂.Q) ((associator _ _ _).symm ≪≫ isoWhiskerRight ((Equivalence.unitIso _).symm) _ ≪≫ leftUnitor _) erw [W₁.isoClosure.inverseImage_equivalence_functor_eq_map_inverse] rw [MorphismProperty.map_isoClosure] exact h exact IsLocalizedEquivalence.of_isLocalization_of_isLocalization Φ W₂.Q instance IsLocalizedEquivalence.isLocalization [Φ.IsLocalizedEquivalence] : (Φ.functor ⋙ L₂).IsLocalization W₁ := Functor.IsLocalization.of_iso _ ((Φ.catCommSq W₁.Q L₂).iso).symm lemma isLocalizedEquivalence_of_unit_of_unit (Ψ : LocalizerMorphism W₂ W₁) (ε₁ : 𝟭 C₁ ⟶ Φ.functor ⋙ Ψ.functor) (ε₂ : 𝟭 C₂ ⟶ Ψ.functor ⋙ Φ.functor) (hε₁ : ∀ X₁, W₁ (ε₁.app X₁)) (hε₂ : ∀ X₂, W₂ (ε₂.app X₂)) : Φ.IsLocalizedEquivalence where isEquivalence := by have : IsIso (whiskerRight ε₁ W₁.Q) := by rw [NatTrans.isIso_iff_isIso_app] exact fun _ ↦ Localization.inverts W₁.Q W₁ _ (hε₁ _) have : IsIso (whiskerRight ε₂ W₂.Q) := by rw [NatTrans.isIso_iff_isIso_app] exact fun _ ↦ Localization.inverts W₂.Q W₂ _ (hε₂ _) refine (Localization.equivalence W₁.Q W₁ W₂.Q W₂ (Φ.functor ⋙ W₂.Q) (Φ.localizedFunctor W₁.Q W₂.Q) (Ψ.functor ⋙ W₁.Q) (Ψ.localizedFunctor W₂.Q W₁.Q) ?_ ?_).isEquivalence_functor · exact Functor.associator _ _ _ ≪≫ isoWhiskerLeft _ (CatCommSq.iso Ψ.functor W₂.Q W₁.Q _).symm ≪≫ (Functor.associator _ _ _).symm ≪≫ (asIso (whiskerRight ε₁ W₁.Q)).symm ≪≫ Functor.leftUnitor _ · exact Functor.associator _ _ _ ≪≫ isoWhiskerLeft _ (CatCommSq.iso Φ.functor W₁.Q W₂.Q _).symm ≪≫ (Functor.associator _ _ _).symm ≪≫ (asIso (whiskerRight ε₂ W₂.Q)).symm ≪≫ Functor.leftUnitor _ /-- The localizer morphism from `W₁.arrow` to `W₂.arrow` that is induced by `Φ : LocalizerMorphism W₁ W₂`. -/ @[simps] def arrow : LocalizerMorphism W₁.arrow W₂.arrow where functor := Φ.functor.mapArrow map _ _ _ hf := ⟨Φ.map _ hf.1, Φ.map _ hf.2⟩ end LocalizerMorphism end CategoryTheory
finset.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 div seq. From mathcomp Require Import choice fintype finfun bigop. (******************************************************************************) (* This file defines a type for sets over a finite Type, similar to the type *) (* of functions over a finite Type defined in finfun.v (indeed, based in it): *) (* {set T} where T must have a finType structure. *) (* We equip {set T} itself with a finType structure, hence Leibnitz and *) (* extensional equalities coincide on {set T}, and we can form {set {set T}}. *) (* If A, B : {set T} and P : {set {set T}}, we define: *) (* x \in A == x belongs to A (i.e., {set T} implements predType, *) (* by coercion to pred_sort) *) (* mem A == the predicate corresponding to A *) (* finset p == the set corresponding to a predicate p *) (* [set x | P] == the set containing the x such that P is true (x may *) (* appear in P) *) (* [set x | P & Q] := [set x | P && Q] *) (* [set x in A] == the set containing the x in a collective predicate A *) (* [set x in A | P] == the set containing the x in A such that P is true *) (* [set x in A | P & Q] := [set x in A | P && Q] *) (* All these have typed variants [set x : T | P], [set x : T in A], etc. *) (* set0 == the empty set *) (* [set: T] or setT == the full set (the A containing all x : T) *) (* [set x] == the singleton {x} *) (* [set~ x] == the complement of the singleton {x} *) (* [set:: s] == the set spanned by the sequence s *) (* [set a1; a2;...; an] := a1 |: [set a2] :|: ... :|: [set an] *) (* A :|: B == the union of A and B *) (* x |: A == A with the element x added (:= [set x] :|: A) *) (* A :&: B == the intersection of A and B *) (* ~: A == the complement of A *) (* A :\: B == the difference A minus B *) (* A :\ x == A with the element x removed (:= A :\: [set x]) *) (* \bigcup_<range> A == the union of all A, for i in <range> (i is bound in *) (* A, see bigop.v) *) (* \bigcap_<range> A == the intersection of all A, for i in <range> *) (* cover P == the union of the set of sets P *) (* trivIset P <=> the elements of P are pairwise disjoint *) (* partition P A <=> P is a partition of A *) (* pblock P x == a block of P containing x, or else set0 *) (* equivalence_partition R D == the partition induced on D by the relation R *) (* (provided R is an equivalence relation in D) *) (* preim_partition f D == the partition induced on D by the equivalence *) (* [rel x y | f x == f y] *) (* is_transversal X P D <=> X is a transversal of the partition P of D *) (* transversal P D == a transversal of P, provided P is a partition of D *) (* transversal_repr x0 X B == a representative of B \in P selected by the *) (* transversal X of P, or else x0 *) (* powerset A == the set of all subset of the set A *) (* P ::&: A == those sets in P that are subsets of the set A *) (* setX A1 A2 == cartesian product of A1 and A2 *) (* := [set u | u.1 \in A1 & u.2 \in A2] *) (* setXn I f A == indexed cartesian product of *) (* A : forall i : I, {set f i} *) (* f @^-1: A == the preimage of the collective predicate A under f *) (* f @: A == the image set of the collective predicate A by f *) (* f @2:(A, B) == the image set of A x B by the binary function f *) (* [set E | x in A] == the set of all the values of the expression E, for x *) (* drawn from the collective predicate A *) (* [set E | x in A & P] == the set of values of E for x drawn from A, such *) (* that P is true *) (* [set E | x in A, y in B] == the set of values of E for x drawn from A and *) (* and y drawn from B; B may depend on x *) (* [set E | x in A, y in B & P] == the set of values of E for x drawn from A *) (* y drawn from B, such that P is true *) (* [set E | x : T] == the set of all values of E, with x in type T *) (* [set E | x : T & P] == the set of values of E for x : T s.t. P is true *) (* [set E | x : T, y : U in B], [set E | x : T, y : U in B & P], *) (* [set E | x : T in A, y : U], [set E | x : T in A, y : U & P], *) (* [set E | x : T, y : U], [set E | x : T, y : U & P] *) (* == type-ranging versions of the binary comprehensions *) (* [set E | x : T in A], [set E | x in A, y], [set E | x, y & P], etc. *) (* == typed and untyped variants of the comprehensions above*) (* The types may be required as type inference processes *) (* E before considering A or B. Note that type casts in *) (* the binary comprehension must either be both present *) (* or absent and that there are no untyped variants for *) (* single-type comprehension as Coq parsing confuses *) (* [x | P] and [E | x]. *) (* minset p A == A is a minimal set satisfying p *) (* maxset p A == A is a maximal set satisfying p *) (* unset1 A == [pick x in A] if #|A| == 1, else None *) (* fprod_pick I T_ p == pick a function of type (forall i : I, T_ i) provided *) (* a proof p of 0 < #|fprod I T_| is given *) (* ftagged I T_ p f i == untag (fprod_pick I T_ p) i (fun x=>x) (f i), useful *) (* to lift f : {ffun I -> {i : I & T_ i}} (akin to FProd's building blocks) *) (* to a vanilla dependent function of type (forall i : I, T_ i). *) (* Provided a monotonous function F : {set T} -> {set T}, we get fixpoints *) (* fixset F := iter #|T| F set0 *) (* == the least fixpoint of F *) (* == the minimal set such that F X == X *) (* fix_order F x == the minimum number of iterations so that *) (* x is in iter (fix_order F x) F set0 *) (* funsetC F := fun X => ~: F (~: X) *) (* cofixset F == the greatest fixpoint of F *) (* == the maximal set such that F X == X *) (* := ~: fixset (funsetC F) *) (* We also provide notations A :=: B, A :<>: B, A :==: B, A :!=: B, A :=P: B *) (* that specialize A = B, A <> B, A == B, etc., to {set _}. This is useful *) (* for subtypes of {set T}, such as {group T}, that coerce to {set T}. *) (* We give many lemmas on these operations, on card, and on set inclusion. *) (* In addition to the standard suffixes described in ssrbool.v, we associate *) (* the following suffixes to set operations: *) (* 0 -- the empty set, as in in_set0 : (x \in set0) = false *) (* T -- the full set, as in in_setT : x \in [set: T] *) (* 1 -- a singleton set, as in in_set1 : (x \in [set a]) = (x == a) *) (* 2 -- an unordered pair, as in *) (* in_set2 : (x \in [set a; b]) = (x == a) || (x == b) *) (* C -- complement, as in setCK : ~: ~: A = A *) (* I -- intersection, as in setIid : A :&: A = A *) (* U -- union, as in setUid : A :|: A = A *) (* D -- difference, as in setDv : A :\: A = set0 *) (* S -- a subset argument, as in *) (* setIS: B \subset C -> A :&: B \subset A :&: C *) (* These suffixes are sometimes preceded with an `s' to distinguish them from *) (* their basic ssrbool interpretation, e.g., *) (* card1 : #|pred1 x| = 1 and cards1 : #|[set x]| = 1 *) (* We also use a trailing `r' to distinguish a right-hand complement from *) (* commutativity, e.g., *) (* setIC : A :&: B = B :&: A and setICr : A :&: ~: A = set0. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope set_scope. Section SetType. Variable T : finType. Inductive set_type : predArgType := FinSet of {ffun pred T}. Definition finfun_of_set A := let: FinSet f := A in f. Definition set_of := set_type. Identity Coercion type_of_set_of : set_of >-> set_type. Definition set_isSub := Eval hnf in [isNew for finfun_of_set]. HB.instance Definition _ := set_isSub. HB.instance Definition _ := [Finite of set_type by <:]. End SetType. Delimit Scope set_scope with SET. Bind Scope set_scope with set_type. Bind Scope set_scope with set_of. Open Scope set_scope. Arguments set_of T%_type. Arguments finfun_of_set {T} A%_SET. Notation "{ 'set' T }" := (set_of T) (format "{ 'set' T }") : type_scope. (* We later define several subtypes that coerce to set; for these it is *) (* preferable to state equalities at the {set _} level, even when comparing *) (* subtype values, because the primitive "injection" tactic tends to diverge *) (* on complex types (e.g., quotient groups). We provide some parse-only *) (* notation to make this technicality less obstructive. *) Notation "A :=: B" := (A = B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. Notation "A :<>: B" := (A <> B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. Notation "A :==: B" := (A == B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. Notation "A :!=: B" := (A != B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. Notation "A :=P: B" := (A =P B :> {set _}) (at level 70, no associativity, only parsing) : set_scope. HB.lock Definition finset (T : finType) (P : pred T) : {set T} := @FinSet T (finfun P). Canonical finset_unlock := Unlockable finset.unlock. (* The weird type of pred_of_set is imposed by the syntactic restrictions on *) (* coercion declarations; it is unfortunately not possible to use a functor *) (* to retype the declaration, because this triggers an ugly bug in the Coq *) (* coercion chaining code. *) HB.lock Definition pred_of_set T (A : set_type T) : fin_pred_sort (predPredType T) := val A. Canonical pred_of_set_unlock := Unlockable pred_of_set.unlock. Notation "[ 'set' x : T | P ]" := (finset (fun x : T => P%B)) (x at level 99, only parsing) : set_scope. Notation "[ 'set' x | P ]" := [set x : _ | P] (P at level 99, format "[ 'set' x | P ]") : set_scope. Notation "[ 'set' x 'in' A ]" := [set x | x \in A] (format "[ 'set' x 'in' A ]") : set_scope. Notation "[ 'set' x : T 'in' A ]" := [set x : T | x \in A] (only parsing) : set_scope. Notation "[ 'set' x : T | P & Q ]" := [set x : T | P && Q] (only parsing) : set_scope. Notation "[ 'set' x | P & Q ]" := [set x | P && Q ] (P at level 99, format "[ 'set' x | P & Q ]") : set_scope. Notation "[ 'set' x : T 'in' A | P ]" := [set x : T | x \in A & P] (only parsing) : set_scope. Notation "[ 'set' x 'in' A | P ]" := [set x | x \in A & P] (format "[ 'set' x 'in' A | P ]") : set_scope. Notation "[ 'set' x 'in' A | P & Q ]" := [set x in A | P && Q] (format "[ 'set' x 'in' A | P & Q ]") : set_scope. Notation "[ 'set' x : T 'in' A | P & Q ]" := [set x : T in A | P && Q] (only parsing) : set_scope. Notation "[ 'set' :: s ]" := (finset [in pred_of_seq s]) (format "[ 'set' :: s ]") : set_scope. (* This lets us use set and subtypes of set, like group or coset_of, both as *) (* collective predicates and as arguments of the \pi(_) notation. *) Coercion pred_of_set: set_type >-> fin_pred_sort. (* Declare pred_of_set as a canonical instance of topred, but use the *) (* coercion to resolve mem A to @mem (predPredType T) (pred_of_set A). *) Canonical set_predType T := @PredType _ (unkeyed (set_type T)) (@pred_of_set T). Section BasicSetTheory. Variable T : finType. Implicit Types (x : T) (A B : {set T}) (pA : pred T). HB.instance Definition _ := Finite.on {set T}. Lemma in_set pA x : x \in finset pA = pA x. Proof. by rewrite [@finset]unlock unlock [x \in _]ffunE. Qed. Lemma setP A B : A =i B <-> A = B. Proof. by split=> [eqAB|-> //]; apply/val_inj/ffunP=> x; have:= eqAB x; rewrite unlock. Qed. Definition set0 := [set x : T | false]. Definition setTfor := [set x : T | true]. Lemma in_setT x : x \in setTfor. Proof. by rewrite in_set. Qed. Lemma eqsVneq A B : eq_xor_neq A B (B == A) (A == B). Proof. exact: eqVneq. Qed. Lemma eq_finset (pA pB : pred T) : pA =1 pB -> finset pA = finset pB. Proof. by move=> eq_p; apply/setP => x; rewrite !(in_set, inE) eq_p. Qed. End BasicSetTheory. Arguments eqsVneq {T} A B, {T A B}. Arguments set0 {T}. Arguments setTfor T%_type. Arguments eq_finset {T} [pA] pB eq_pAB. #[global] Hint Resolve in_setT : core. Notation "[ 'set' : T ]" := (setTfor T) (format "[ 'set' : T ]") : set_scope. Notation setT := [set: _] (only parsing). HB.lock Definition set1 (T : finType) (a : T) := [set x | x == a]. Section setOpsDefs. Variable T : finType. Implicit Types (a x : T) (A B D : {set T}) (P : {set {set T}}). Definition setU A B := [set x | (x \in A) || (x \in B)]. Definition setI A B := [set x in A | x \in B]. Definition setC A := [set x | x \notin A]. Definition setD A B := [set x | x \notin B & x \in A]. Definition ssetI P D := [set A in P | A \subset D]. Definition powerset D := [set A : {set T} | A \subset D]. End setOpsDefs. Notation "[ 'set' a ]" := (set1 a) (a at level 99, format "[ 'set' a ]") : set_scope. Notation "[ 'set' a : T ]" := [set (a : T)] (a at level 99, format "[ 'set' a : T ]") : set_scope. Notation "A :|: B" := (setU A B) : set_scope. Notation "a |: A" := ([set a] :|: A) : set_scope. (* This is left-associative due to historical limitations of the .. Notation. *) Notation "[ 'set' a1 ; a2 ; .. ; an ]" := (setU .. (a1 |: [set a2]) .. [set an]) (format "[ 'set' a1 ; a2 ; .. ; an ]") : set_scope. Notation "A :&: B" := (setI A B) : set_scope. Notation "~: A" := (setC A) (at level 35, right associativity) : set_scope. Notation "[ 'set' ~ a ]" := (~: [set a]) (format "[ 'set' ~ a ]") : set_scope. Notation "A :\: B" := (setD A B) : set_scope. Notation "A :\ a" := (A :\: [set a]) : set_scope. Notation "P ::&: D" := (ssetI P D) (at level 48) : set_scope. Section setOps. Variable T : finType. Implicit Types (a x : T) (A B C D : {set T}) (pA pB pC : pred T). Lemma eqEsubset A B : (A == B) = (A \subset B) && (B \subset A). Proof. by apply/eqP/subset_eqP=> /setP. Qed. Lemma subEproper A B : A \subset B = (A == B) || (A \proper B). Proof. by rewrite eqEsubset -andb_orr orbN andbT. Qed. Lemma eqVproper A B : A \subset B -> A = B \/ A \proper B. Proof. by rewrite subEproper => /predU1P. Qed. Lemma properEneq A B : A \proper B = (A != B) && (A \subset B). Proof. by rewrite andbC eqEsubset negb_and andb_orr andbN. Qed. Lemma proper_neq A B : A \proper B -> A != B. Proof. by rewrite properEneq; case/andP. Qed. Lemma eqEproper A B : (A == B) = (A \subset B) && ~~ (A \proper B). Proof. by rewrite negb_and negbK andb_orr andbN eqEsubset. Qed. Lemma eqEcard A B : (A == B) = (A \subset B) && (#|B| <= #|A|). Proof. rewrite eqEsubset; apply: andb_id2l => sAB. by rewrite (geq_leqif (subset_leqif_card sAB)). Qed. Lemma properEcard A B : (A \proper B) = (A \subset B) && (#|A| < #|B|). Proof. by rewrite properEneq ltnNge andbC eqEcard; case: (A \subset B). Qed. Lemma subset_leqif_cards A B : A \subset B -> (#|A| <= #|B| ?= iff (A == B)). Proof. by move=> sAB; rewrite eqEsubset sAB; apply: subset_leqif_card. Qed. Lemma in_set0 x : x \in set0 = false. Proof. by rewrite in_set. Qed. Lemma sub0set A : set0 \subset A. Proof. by apply/subsetP=> x; rewrite in_set. Qed. Lemma subset0 A : (A \subset set0) = (A == set0). Proof. by rewrite eqEsubset sub0set andbT. Qed. Lemma proper0 A : (set0 \proper A) = (A != set0). Proof. by rewrite properE sub0set subset0. Qed. Lemma subset_neq0 A B : A \subset B -> A != set0 -> B != set0. Proof. by rewrite -!proper0 => sAB /proper_sub_trans->. Qed. Lemma set_0Vmem A : (A = set0) + {x : T | x \in A}. Proof. case: (pickP (mem A)) => [x Ax | A0]; [by right; exists x | left]. by apply/setP=> x; rewrite in_set; apply: A0. Qed. Lemma set_enum A : [set x | x \in enum A] = A. Proof. by apply/setP => x; rewrite in_set mem_enum. Qed. Lemma enum_set0 : enum set0 = [::] :> seq T. Proof. by rewrite (eq_enum (in_set _)) enum0. Qed. Lemma subsetT A : A \subset setT. Proof. by apply/subsetP=> x; rewrite in_set. Qed. Lemma subsetT_hint mA : subset mA (mem [set: T]). Proof. by rewrite unlock; apply/pred0P=> x; rewrite !inE in_set. Qed. Hint Resolve subsetT_hint : core. Lemma subTset A : (setT \subset A) = (A == setT). Proof. by rewrite eqEsubset subsetT. Qed. Lemma properT A : (A \proper setT) = (A != setT). Proof. by rewrite properEneq subsetT andbT. Qed. Lemma set1P x a : reflect (x = a) (x \in [set a]). Proof. by rewrite set1.unlock in_set; apply: eqP. Qed. Lemma enum_setT : enum [set: T] = Finite.enum T. Proof. by rewrite (eq_enum (in_set _)) enumT. Qed. Lemma in_set1 x a : (x \in [set a]) = (x == a). Proof. by rewrite set1.unlock in_set. Qed. Definition inE := (in_set, in_set1, inE). Lemma set11 x : x \in [set x]. Proof. by rewrite !inE. Qed. Lemma set1_inj : injective (@set1 T). Proof. by move=> a b eqsab; apply/set1P; rewrite -eqsab set11. Qed. Lemma enum_set1 a : enum [set a] = [:: a]. Proof. by rewrite set1.unlock (eq_enum (in_set _)) enum1. Qed. Lemma setU1P x a B : reflect (x = a \/ x \in B) (x \in a |: B). Proof. by rewrite !inE; apply: predU1P. Qed. Lemma in_setU1 x a B : (x \in a |: B) = (x == a) || (x \in B). Proof. by rewrite !inE. Qed. Lemma set_nil : [set:: nil] = @set0 T. Proof. by rewrite -enum_set0 set_enum. Qed. Lemma set_seq1 a : [set:: [:: a]] = [set a]. Proof. by rewrite -enum_set1 set_enum. Qed. Lemma set_cons a s : [set:: a :: s] = a |: [set:: s]. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma setU11 x B : x \in x |: B. Proof. by rewrite !inE eqxx. Qed. Lemma setU1r x a B : x \in B -> x \in a |: B. Proof. by move=> Bx; rewrite !inE predU1r. Qed. (* We need separate lemmas for the explicit enumerations since they *) (* associate on the left. *) Lemma set1Ul x A b : x \in A -> x \in A :|: [set b]. Proof. by move=> Ax; rewrite !inE Ax. Qed. Lemma set1Ur A b : b \in A :|: [set b]. Proof. by rewrite !inE eqxx orbT. Qed. Lemma in_setC1 x a : (x \in [set~ a]) = (x != a). Proof. by rewrite !inE. Qed. Lemma setC11 x : (x \in [set~ x]) = false. Proof. by rewrite !inE eqxx. Qed. Lemma setD1P x A b : reflect (x != b /\ x \in A) (x \in A :\ b). Proof. by rewrite !inE; apply: andP. Qed. Lemma in_setD1 x A b : (x \in A :\ b) = (x != b) && (x \in A) . Proof. by rewrite !inE. Qed. Lemma setD11 b A : (b \in A :\ b) = false. Proof. by rewrite !inE eqxx. Qed. Lemma setD1K a A : a \in A -> a |: (A :\ a) = A. Proof. by move=> Aa; apply/setP=> x /[!inE]; case: eqP => // ->. Qed. Lemma setU1K a B : a \notin B -> (a |: B) :\ a = B. Proof. by move/negPf=> nBa; apply/setP=> x /[!inE]; case: eqP => // ->. Qed. Lemma set2P x a b : reflect (x = a \/ x = b) (x \in [set a; b]). Proof. by rewrite !inE; apply: pred2P. Qed. Lemma in_set2 x a b : (x \in [set a; b]) = (x == a) || (x == b). Proof. by rewrite !inE. Qed. Lemma set21 a b : a \in [set a; b]. Proof. by rewrite !inE eqxx. Qed. Lemma set22 a b : b \in [set a; b]. Proof. by rewrite !inE eqxx orbT. Qed. Lemma setUP x A B : reflect (x \in A \/ x \in B) (x \in A :|: B). Proof. by rewrite !inE; apply: orP. Qed. Lemma in_setU x A B : (x \in A :|: B) = (x \in A) || (x \in B). Proof. exact: in_set. Qed. Lemma setUC A B : A :|: B = B :|: A. Proof. by apply/setP => x; rewrite !inE orbC. Qed. Lemma setUS A B C : A \subset B -> C :|: A \subset C :|: B. Proof. move=> sAB; apply/subsetP=> x; rewrite !inE. by case: (x \in C) => //; apply: (subsetP sAB). Qed. Lemma setSU A B C : A \subset B -> A :|: C \subset B :|: C. Proof. by move=> sAB; rewrite -!(setUC C) setUS. Qed. Lemma setUSS A B C D : A \subset C -> B \subset D -> A :|: B \subset C :|: D. Proof. by move=> /(setSU B) /subset_trans sAC /(setUS C)/sAC. Qed. Lemma set0U A : set0 :|: A = A. Proof. by apply/setP => x; rewrite !inE orFb. Qed. Lemma setU0 A : A :|: set0 = A. Proof. by rewrite setUC set0U. Qed. Lemma setUA A B C : A :|: (B :|: C) = A :|: B :|: C. Proof. by apply/setP => x; rewrite !inE orbA. Qed. Lemma setUCA A B C : A :|: (B :|: C) = B :|: (A :|: C). Proof. by rewrite !setUA (setUC B). Qed. Lemma setUAC A B C : A :|: B :|: C = A :|: C :|: B. Proof. by rewrite -!setUA (setUC B). Qed. Lemma setUACA A B C D : (A :|: B) :|: (C :|: D) = (A :|: C) :|: (B :|: D). Proof. by rewrite -!setUA (setUCA B). Qed. Lemma setTU A : setT :|: A = setT. Proof. by apply/setP => x; rewrite !inE orTb. Qed. Lemma setUT A : A :|: setT = setT. Proof. by rewrite setUC setTU. Qed. Lemma setUid A : A :|: A = A. Proof. by apply/setP=> x; rewrite inE orbb. Qed. Lemma setUUl A B C : A :|: B :|: C = (A :|: C) :|: (B :|: C). Proof. by rewrite setUA !(setUAC _ C) -(setUA _ C) setUid. Qed. Lemma setUUr A B C : A :|: (B :|: C) = (A :|: B) :|: (A :|: C). Proof. by rewrite !(setUC A) setUUl. Qed. (* intersection *) (* setIdP is a generalisation of setIP that applies to comprehensions. *) Lemma setIdP x pA pB : reflect (pA x /\ pB x) (x \in [set y | pA y & pB y]). Proof. by rewrite !inE; apply: andP. Qed. Lemma setId2P x pA pB pC : reflect [/\ pA x, pB x & pC x] (x \in [set y | pA y & pB y && pC y]). Proof. by rewrite !inE; apply: and3P. Qed. Lemma setIdE A pB : [set x in A | pB x] = A :&: [set x | pB x]. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma setIP x A B : reflect (x \in A /\ x \in B) (x \in A :&: B). Proof. exact: (iffP (@setIdP _ _ _)). Qed. Lemma in_setI x A B : (x \in A :&: B) = (x \in A) && (x \in B). Proof. exact: in_set. Qed. Lemma setIC A B : A :&: B = B :&: A. Proof. by apply/setP => x; rewrite !inE andbC. Qed. Lemma setIS A B C : A \subset B -> C :&: A \subset C :&: B. Proof. move=> sAB; apply/subsetP=> x; rewrite !inE. by case: (x \in C) => //; apply: (subsetP sAB). Qed. Lemma setSI A B C : A \subset B -> A :&: C \subset B :&: C. Proof. by move=> sAB; rewrite -!(setIC C) setIS. Qed. Lemma setISS A B C D : A \subset C -> B \subset D -> A :&: B \subset C :&: D. Proof. by move=> /(setSI B) /subset_trans sAC /(setIS C) /sAC. Qed. Lemma setTI A : setT :&: A = A. Proof. by apply/setP => x; rewrite !inE andTb. Qed. Lemma setIT A : A :&: setT = A. Proof. by rewrite setIC setTI. Qed. Lemma set0I A : set0 :&: A = set0. Proof. by apply/setP => x; rewrite !inE andFb. Qed. Lemma setI0 A : A :&: set0 = set0. Proof. by rewrite setIC set0I. Qed. Lemma setIA A B C : A :&: (B :&: C) = A :&: B :&: C. Proof. by apply/setP=> x; rewrite !inE andbA. Qed. Lemma setICA A B C : A :&: (B :&: C) = B :&: (A :&: C). Proof. by rewrite !setIA (setIC A). Qed. Lemma setIAC A B C : A :&: B :&: C = A :&: C :&: B. Proof. by rewrite -!setIA (setIC B). Qed. Lemma setIACA A B C D : (A :&: B) :&: (C :&: D) = (A :&: C) :&: (B :&: D). Proof. by rewrite -!setIA (setICA B). Qed. Lemma setIid A : A :&: A = A. Proof. by apply/setP=> x; rewrite inE andbb. Qed. Lemma setIIl A B C : A :&: B :&: C = (A :&: C) :&: (B :&: C). Proof. by rewrite setIA !(setIAC _ C) -(setIA _ C) setIid. Qed. Lemma setIIr A B C : A :&: (B :&: C) = (A :&: B) :&: (A :&: C). Proof. by rewrite !(setIC A) setIIl. Qed. (* distribute /cancel *) Lemma setIUr A B C : A :&: (B :|: C) = (A :&: B) :|: (A :&: C). Proof. by apply/setP=> x; rewrite !inE andb_orr. Qed. Lemma setIUl A B C : (A :|: B) :&: C = (A :&: C) :|: (B :&: C). Proof. by apply/setP=> x; rewrite !inE andb_orl. Qed. Lemma setUIr A B C : A :|: (B :&: C) = (A :|: B) :&: (A :|: C). Proof. by apply/setP=> x; rewrite !inE orb_andr. Qed. Lemma setUIl A B C : (A :&: B) :|: C = (A :|: C) :&: (B :|: C). Proof. by apply/setP=> x; rewrite !inE orb_andl. Qed. Lemma setUK A B : (A :|: B) :&: A = A. Proof. by apply/setP=> x; rewrite !inE orbK. Qed. Lemma setKU A B : A :&: (B :|: A) = A. Proof. by apply/setP=> x; rewrite !inE orKb. Qed. Lemma setIK A B : (A :&: B) :|: A = A. Proof. by apply/setP=> x; rewrite !inE andbK. Qed. Lemma setKI A B : A :|: (B :&: A) = A. Proof. by apply/setP=> x; rewrite !inE andKb. Qed. (* complement *) Lemma setCP x A : reflect (~ x \in A) (x \in ~: A). Proof. by rewrite !inE; apply: negP. Qed. Lemma in_setC x A : (x \in ~: A) = (x \notin A). Proof. exact: in_set. Qed. Lemma setCK : involutive (@setC T). Proof. by move=> A; apply/setP=> x; rewrite !inE negbK. Qed. Lemma setC_inj : injective (@setC T). Proof. exact: can_inj setCK. Qed. Lemma subsets_disjoint A B : (A \subset B) = [disjoint A & ~: B]. Proof. by rewrite subset_disjoint; apply: eq_disjoint_r => x; rewrite !inE. Qed. Lemma disjoints_subset A B : [disjoint A & B] = (A \subset ~: B). Proof. by rewrite subsets_disjoint setCK. Qed. Lemma powersetCE A B : (A \in powerset (~: B)) = [disjoint A & B]. Proof. by rewrite inE disjoints_subset. Qed. Lemma setCS A B : (~: A \subset ~: B) = (B \subset A). Proof. by rewrite !subsets_disjoint setCK disjoint_sym. Qed. Lemma setCU A B : ~: (A :|: B) = ~: A :&: ~: B. Proof. by apply/setP=> x; rewrite !inE negb_or. Qed. Lemma setCI A B : ~: (A :&: B) = ~: A :|: ~: B. Proof. by apply/setP=> x; rewrite !inE negb_and. Qed. Lemma setUCr A : A :|: ~: A = setT. Proof. by apply/setP=> x; rewrite !inE orbN. Qed. Lemma setICr A : A :&: ~: A = set0. Proof. by apply/setP=> x; rewrite !inE andbN. Qed. Lemma setC0 : ~: set0 = [set: T]. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma setCT : ~: [set: T] = set0. Proof. by rewrite -setC0 setCK. Qed. Lemma properC A B : (~: B \proper ~: A) = (A \proper B). Proof. by rewrite !properE !setCS. Qed. (* difference *) Lemma setDP A B x : reflect (x \in A /\ x \notin B) (x \in A :\: B). Proof. by rewrite inE andbC; apply: andP. Qed. Lemma in_setD A B x : (x \in A :\: B) = (x \notin B) && (x \in A). Proof. exact: in_set. Qed. Lemma setDE A B : A :\: B = A :&: ~: B. Proof. by apply/setP => x; rewrite !inE andbC. Qed. Lemma setSD A B C : A \subset B -> A :\: C \subset B :\: C. Proof. by rewrite !setDE; apply: setSI. Qed. Lemma setDS A B C : A \subset B -> C :\: B \subset C :\: A. Proof. by rewrite !setDE -setCS; apply: setIS. Qed. Lemma setDSS A B C D : A \subset C -> D \subset B -> A :\: B \subset C :\: D. Proof. by move=> /(setSD B) /subset_trans sAC /(setDS C) /sAC. Qed. Lemma setD0 A : A :\: set0 = A. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma set0D A : set0 :\: A = set0. Proof. by apply/setP=> x; rewrite !inE andbF. Qed. Lemma setDT A : A :\: setT = set0. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma setTD A : setT :\: A = ~: A. Proof. by apply/setP=> x; rewrite !inE andbT. Qed. Lemma setDv A : A :\: A = set0. Proof. by apply/setP=> x; rewrite !inE andNb. Qed. Lemma setCD A B : ~: (A :\: B) = ~: A :|: B. Proof. by rewrite !setDE setCI setCK. Qed. Lemma setID A B : A :&: B :|: A :\: B = A. Proof. by rewrite setDE -setIUr setUCr setIT. Qed. Lemma setDUl A B C : (A :|: B) :\: C = (A :\: C) :|: (B :\: C). Proof. by rewrite !setDE setIUl. Qed. Lemma setDUr A B C : A :\: (B :|: C) = (A :\: B) :&: (A :\: C). Proof. by rewrite !setDE setCU setIIr. Qed. Lemma setDIl A B C : (A :&: B) :\: C = (A :\: C) :&: (B :\: C). Proof. by rewrite !setDE setIIl. Qed. Lemma setIDA A B C : A :&: (B :\: C) = (A :&: B) :\: C. Proof. by rewrite !setDE setIA. Qed. Lemma setIDAC A B C : (A :\: B) :&: C = (A :&: C) :\: B. Proof. by rewrite !setDE setIAC. Qed. Lemma setDIr A B C : A :\: (B :&: C) = (A :\: B) :|: (A :\: C). Proof. by rewrite !setDE setCI setIUr. Qed. Lemma setDDl A B C : (A :\: B) :\: C = A :\: (B :|: C). Proof. by rewrite !setDE setCU setIA. Qed. Lemma setDDr A B C : A :\: (B :\: C) = (A :\: B) :|: (A :&: C). Proof. by rewrite !setDE setCI setIUr setCK. Qed. (* powerset *) Lemma powersetE A B : (A \in powerset B) = (A \subset B). Proof. by rewrite inE. Qed. Lemma powersetS A B : (powerset A \subset powerset B) = (A \subset B). Proof. apply/subsetP/idP=> [sAB | sAB C /[!inE]/subset_trans->//]. by rewrite -powersetE sAB // inE. Qed. Lemma powerset0 : powerset set0 = [set set0] :> {set {set T}}. Proof. by apply/setP=> A; rewrite set1.unlock !inE subset0. Qed. Lemma powersetT : powerset [set: T] = [set: {set T}]. Proof. by apply/setP=> A; rewrite !inE subsetT. Qed. Lemma setI_powerset P A : P :&: powerset A = P ::&: A. Proof. by apply/setP=> B; rewrite !inE. Qed. (* cardinal lemmas for sets *) Lemma cardsE pA : #|[set x in pA]| = #|pA|. Proof. exact/eq_card/in_set. Qed. Lemma sum1dep_card pA : \sum_(x | pA x) 1 = #|[set x | pA x]|. Proof. by rewrite sum1_card cardsE. Qed. Lemma sum_nat_cond_const pA n : \sum_(x | pA x) n = #|[set x | pA x]| * n. Proof. by rewrite sum_nat_const cardsE. Qed. Lemma cards0 : #|@set0 T| = 0. Proof. by rewrite cardsE card0. Qed. Lemma cards_eq0 A : (#|A| == 0) = (A == set0). Proof. by rewrite (eq_sym A) eqEcard sub0set cards0 leqn0. Qed. Lemma set0Pn A : reflect (exists x, x \in A) (A != set0). Proof. by rewrite -cards_eq0; apply: existsP. Qed. Lemma set0_Nexists A : (A == set0) = ~~ [exists x, x \in A]. Proof. by rewrite -(sameP (set0Pn _) existsP) negbK. Qed. Lemma card_gt0 A : (0 < #|A|) = (A != set0). Proof. by rewrite lt0n cards_eq0. Qed. Lemma cards0_eq A : #|A| = 0 -> A = set0. Proof. by move=> A_0; apply/setP=> x; rewrite inE (card0_eq A_0). Qed. Lemma cards1 x : #|[set x]| = 1. Proof. by rewrite set1.unlock cardsE card1. Qed. Lemma cardsUI A B : #|A :|: B| + #|A :&: B| = #|A| + #|B|. Proof. by rewrite !cardsE cardUI. Qed. Lemma cardsU A B : #|A :|: B| = #|A| + #|B| - #|A :&: B|. Proof. by rewrite -cardsUI addnK. Qed. Lemma cardsI A B : #|A :&: B| = #|A| + #|B| - #|A :|: B|. Proof. by rewrite -cardsUI addKn. Qed. Lemma cardsT : #|[set: T]| = #|T|. Proof. by rewrite cardsE. Qed. Lemma cardsID B A : #|A :&: B| + #|A :\: B| = #|A|. Proof. by rewrite !cardsE cardID. Qed. Lemma cardsD A B : #|A :\: B| = #|A| - #|A :&: B|. Proof. by rewrite -(cardsID B A) addKn. Qed. Lemma cardsC A : #|A| + #|~: A| = #|T|. Proof. by rewrite cardsE cardC. Qed. Lemma cardsCs A : #|A| = #|T| - #|~: A|. Proof. by rewrite -(cardsC A) addnK. Qed. Lemma cardsU1 a A : #|a |: A| = (a \notin A) + #|A|. Proof. by rewrite -cardU1; apply: eq_card=> x; rewrite !inE. Qed. Lemma cards2 a b : #|[set a; b]| = (a != b).+1. Proof. by rewrite -card2; apply: eq_card=> x; rewrite !inE. Qed. Lemma cardsC1 a : #|[set~ a]| = #|T|.-1. Proof. by rewrite -(cardC1 a); apply: eq_card=> x; rewrite !inE. Qed. Lemma cardsD1 a A : #|A| = (a \in A) + #|A :\ a|. Proof. by rewrite (cardD1 a); congr (_ + _); apply: eq_card => x; rewrite !inE. Qed. (* other inclusions *) Lemma subsetIl A B : A :&: B \subset A. Proof. by apply/subsetP=> x /[!inE] /andP[]. Qed. Lemma subsetIr A B : A :&: B \subset B. Proof. by apply/subsetP=> x /[!inE] /andP[]. Qed. Lemma subsetUl A B : A \subset A :|: B. Proof. by apply/subsetP=> x /[!inE] ->. Qed. Lemma subsetUr A B : B \subset A :|: B. Proof. by apply/subsetP=> x; rewrite inE orbC => ->. Qed. Lemma subsetU1 x A : A \subset x |: A. Proof. exact: subsetUr. Qed. Lemma subsetDl A B : A :\: B \subset A. Proof. by rewrite setDE subsetIl. Qed. Lemma subD1set A x : A :\ x \subset A. Proof. by rewrite subsetDl. Qed. Lemma subsetDr A B : A :\: B \subset ~: B. Proof. by rewrite setDE subsetIr. Qed. Lemma sub1set A x : ([set x] \subset A) = (x \in A). Proof. by rewrite -subset_pred1; apply: eq_subset=> y; rewrite !inE. Qed. Variant cards_eq_spec A : seq T -> {set T} -> nat -> Type := | CardEq (s : seq T) & uniq s : cards_eq_spec A s [set x | x \in s] (size s). Lemma cards_eqP A : cards_eq_spec A (enum A) A #|A|. Proof. by move: (enum A) (cardE A) (set_enum A) (enum_uniq A) => s -> <-; constructor. Qed. Lemma cards1P A : reflect (exists x, A = [set x]) (#|A| == 1). Proof. apply: (iffP idP) => [|[x ->]]; last by rewrite cards1. by have [[|x []]// _] := cards_eqP; exists x; apply/setP => y; rewrite !inE. Qed. Lemma cards2P A : reflect (exists x y : T, x != y /\ A = [set x; y]) (#|A| == 2). Proof. apply: (iffP idP) => [|[x] [y] [xy ->]]; last by rewrite cards2 xy. have [[|x [|y []]]//=] := cards_eqP; rewrite !inE andbT => neq_xy. by exists x, y; split=> //; apply/setP => z; rewrite !inE. Qed. Lemma subset1 A x : (A \subset [set x]) = (A == [set x]) || (A == set0). Proof. rewrite eqEcard cards1 -cards_eq0 orbC andbC. by case: posnP => // A0; rewrite (cards0_eq A0) sub0set. Qed. Lemma powerset1 x : powerset [set x] = [set set0; [set x]]. Proof. by apply/setP=> A; rewrite inE subset1 orbC set1.unlock !inE. Qed. Lemma setIidPl A B : reflect (A :&: B = A) (A \subset B). Proof. apply: (iffP subsetP) => [sAB | <- x /setIP[] //]. by apply/setP=> x /[1!inE]; apply/andb_idr/sAB. Qed. Arguments setIidPl {A B}. Lemma setIidPr A B : reflect (A :&: B = B) (B \subset A). Proof. by rewrite setIC; apply: setIidPl. Qed. Lemma cardsDS A B : B \subset A -> #|A :\: B| = #|A| - #|B|. Proof. by rewrite cardsD => /setIidPr->. Qed. Lemma setUidPl A B : reflect (A :|: B = A) (B \subset A). Proof. by rewrite -setCS (sameP setIidPl eqP) -setCU (inj_eq setC_inj); apply: eqP. Qed. Lemma setUidPr A B : reflect (A :|: B = B) (A \subset B). Proof. by rewrite setUC; apply: setUidPl. Qed. Lemma setDidPl A B : reflect (A :\: B = A) [disjoint A & B]. Proof. by rewrite setDE disjoints_subset; apply: setIidPl. Qed. Lemma subIset A B C : (B \subset A) || (C \subset A) -> (B :&: C \subset A). Proof. by case/orP; apply: subset_trans; rewrite (subsetIl, subsetIr). Qed. Lemma subsetI A B C : (A \subset B :&: C) = (A \subset B) && (A \subset C). Proof. rewrite !(sameP setIidPl eqP) setIA; have [-> //|] := eqVneq (A :&: B) A. by apply: contraNF => /eqP <-; rewrite -setIA -setIIl setIAC. Qed. Lemma subsetIP A B C : reflect (A \subset B /\ A \subset C) (A \subset B :&: C). Proof. by rewrite subsetI; apply: andP. Qed. Lemma subsetIidl A B : (A \subset A :&: B) = (A \subset B). Proof. by rewrite subsetI subxx. Qed. Lemma subsetIidr A B : (B \subset A :&: B) = (B \subset A). Proof. by rewrite setIC subsetIidl. Qed. Lemma powersetI A B : powerset (A :&: B) = powerset A :&: powerset B. Proof. by apply/setP=> C; rewrite !inE subsetI. Qed. Lemma subUset A B C : (B :|: C \subset A) = (B \subset A) && (C \subset A). Proof. by rewrite -setCS setCU subsetI !setCS. Qed. Lemma subsetU A B C : (A \subset B) || (A \subset C) -> A \subset B :|: C. Proof. by rewrite -!(setCS _ A) setCU; apply: subIset. Qed. Lemma subUsetP A B C : reflect (A \subset C /\ B \subset C) (A :|: B \subset C). Proof. by rewrite subUset; apply: andP. Qed. Lemma subsetC A B : (A \subset ~: B) = (B \subset ~: A). Proof. by rewrite -setCS setCK. Qed. Lemma subCset A B : (~: A \subset B) = (~: B \subset A). Proof. by rewrite -setCS setCK. Qed. Lemma subsetD A B C : (A \subset B :\: C) = (A \subset B) && [disjoint A & C]. Proof. by rewrite setDE subsetI -disjoints_subset. Qed. Lemma subDset A B C : (A :\: B \subset C) = (A \subset B :|: C). Proof. apply/subsetP/subsetP=> sABC x; rewrite !inE. by case Bx: (x \in B) => // Ax; rewrite sABC ?inE ?Bx. by case Bx: (x \in B) => // /sABC; rewrite inE Bx. Qed. Lemma subsetDP A B C : reflect (A \subset B /\ [disjoint A & C]) (A \subset B :\: C). Proof. by rewrite subsetD; apply: andP. Qed. Lemma setU_eq0 A B : (A :|: B == set0) = (A == set0) && (B == set0). Proof. by rewrite -!subset0 subUset. Qed. Lemma setD_eq0 A B : (A :\: B == set0) = (A \subset B). Proof. by rewrite -subset0 subDset setU0. Qed. Lemma setI_eq0 A B : (A :&: B == set0) = [disjoint A & B]. Proof. by rewrite disjoints_subset -setD_eq0 setDE setCK. Qed. Lemma eq0_subset B A : (A == set0) = (A \subset B) && (A \subset ~: B). Proof. by rewrite -subsetI setICr subset0. Qed. Lemma disjoint_setI0 A B : [disjoint A & B] -> A :&: B = set0. Proof. by rewrite -setI_eq0; move/eqP. Qed. Lemma subsetC_disjoint A B : [disjoint A & B] -> forall C, C != set0 -> C \subset A -> ~~ (C \subset B). Proof. move=> dAB C + CA; apply: contra_neqN => CB. by apply/eqP; rewrite -subset0 -(disjoint_setI0 dAB) subsetI CA CB. Qed. Lemma disjoints1 A x : [disjoint [set x] & A] = (x \notin A). Proof. by rewrite (@eq_disjoint1 _ x) // => y; rewrite !inE. Qed. Lemma subsetD1 A B x : (A \subset B :\ x) = (A \subset B) && (x \notin A). Proof. by rewrite setDE subsetI subsetC sub1set inE. Qed. Lemma subsetD1P A B x : reflect (A \subset B /\ x \notin A) (A \subset B :\ x). Proof. by rewrite subsetD1; apply: andP. Qed. Lemma properD1 A x : x \in A -> A :\ x \proper A. Proof. move=> Ax; rewrite properE subsetDl; apply/subsetPn; exists x=> //. by rewrite in_setD1 Ax eqxx. Qed. Lemma properIr A B : ~~ (B \subset A) -> A :&: B \proper B. Proof. by move=> nsAB; rewrite properE subsetIr subsetI negb_and nsAB. Qed. Lemma properIl A B : ~~ (A \subset B) -> A :&: B \proper A. Proof. by move=> nsBA; rewrite properE subsetIl subsetI negb_and nsBA orbT. Qed. Lemma properUr A B : ~~ (A \subset B) -> B \proper A :|: B. Proof. by rewrite properE subsetUr subUset subxx /= andbT. Qed. Lemma properUl A B : ~~ (B \subset A) -> A \proper A :|: B. Proof. by move=> not_sBA; rewrite setUC properUr. Qed. Lemma proper1set A x : ([set x] \proper A) -> (x \in A). Proof. by move/proper_sub; rewrite sub1set. Qed. Lemma properIset A B C : (B \proper A) || (C \proper A) -> (B :&: C \proper A). Proof. by case/orP; apply: sub_proper_trans; rewrite (subsetIl, subsetIr). Qed. Lemma properI A B C : (A \proper B :&: C) -> (A \proper B) && (A \proper C). Proof. move=> pAI; apply/andP. by split; apply: (proper_sub_trans pAI); rewrite (subsetIl, subsetIr). Qed. Lemma properU A B C : (B :|: C \proper A) -> (B \proper A) && (C \proper A). Proof. move=> pUA; apply/andP. by split; apply: sub_proper_trans pUA; rewrite (subsetUr, subsetUl). Qed. Lemma properD A B C : (A \proper B :\: C) -> (A \proper B) && [disjoint A & C]. Proof. by rewrite setDE disjoints_subset => /properI/andP[-> /proper_sub]. Qed. Lemma properCr A B : (A \proper ~: B) = (B \proper ~: A). Proof. by rewrite -properC setCK. Qed. Lemma properCl A B : (~: A \proper B) = (~: B \proper A). Proof. by rewrite -properC setCK. Qed. (* relationship with seq *) Lemma enum_setU A B : perm_eq (enum (A :|: B)) (undup (enum A ++ enum B)). Proof. apply: uniq_perm; rewrite ?enum_uniq ?undup_uniq//. by move=> i; rewrite mem_undup mem_enum inE mem_cat !mem_enum. Qed. Lemma enum_setI A B : perm_eq (enum (A :&: B)) (filter [in B] (enum A)). Proof. apply: uniq_perm; rewrite ?enum_uniq// 1?filter_uniq// ?enum_uniq//. by move=> x; rewrite /= mem_enum mem_filter inE mem_enum andbC. Qed. Lemma has_set1 pA A a : has pA (enum [set a]) = pA a. Proof. by rewrite enum_set1 has_seq1. Qed. Lemma has_setU pA A B : has pA (enum (A :|: B)) = (has pA (enum A)) || (has pA (enum B)). Proof. by rewrite (perm_has _ (enum_setU _ _)) has_undup has_cat. Qed. Lemma all_set1 pA A a : all pA (enum [set a]) = pA a. Proof. by rewrite enum_set1 all_seq1. Qed. Lemma all_setU pA A B : all pA (enum (A :|: B)) = (all pA (enum A)) && (all pA (enum B)). Proof. by rewrite (perm_all _ (enum_setU _ _)) all_undup all_cat. Qed. End setOps. Arguments set1P {T x a}. Arguments set1_inj {T} [x1 x2]. Arguments set2P {T x a b}. Arguments setIdP {T x pA pB}. Arguments setIP {T x A B}. Arguments setU1P {T x a B}. Arguments setD1P {T x A b}. Arguments setUP {T x A B}. Arguments setDP {T A B x}. Arguments cards1P {T A}. Arguments setCP {T x A}. Arguments setIidPl {T A B}. Arguments setIidPr {T A B}. Arguments setUidPl {T A B}. Arguments setUidPr {T A B}. Arguments setDidPl {T A B}. Arguments subsetIP {T A B C}. Arguments subUsetP {T A B C}. Arguments subsetDP {T A B C}. Arguments subsetD1P {T A B x}. Prenex Implicits set1. #[global] Hint Extern 0 (is_true (subset _ (mem (pred_of_set (setTfor _))))) => solve [apply: subsetT_hint] : core. Section setOpsAlgebra. Import Monoid. Variable T : finType. HB.instance Definition _ := isComLaw.Build {set T} [set: T] (@setI T) (@setIA T) (@setIC T) (@setTI T). HB.instance Definition _ := isMulLaw.Build {set T} set0 (@setI T) (@set0I T) (@setI0 T). HB.instance Definition _ := isComLaw.Build {set T} set0 (@setU T) (@setUA T) (@setUC T) (@set0U T). HB.instance Definition _ := isMulLaw.Build {set T} [set: T] (@setU T) (@setTU T) (@setUT T). HB.instance Definition _ := isAddLaw.Build {set T} (@setU T) (@setI T) (@setUIl T) (@setUIr T). HB.instance Definition _ := isAddLaw.Build {set T} (@setI T) (@setU T) (@setIUl T) (@setIUr T). End setOpsAlgebra. Section CartesianProd. Variables fT1 fT2 : finType. Variables (A1 : {set fT1}) (A2 : {set fT2}). Definition setX := [set u | u.1 \in A1 & u.2 \in A2]. Lemma in_setX x1 x2 : ((x1, x2) \in setX) = (x1 \in A1) && (x2 \in A2). Proof. by rewrite inE. Qed. Lemma setXP x1 x2 : reflect (x1 \in A1 /\ x2 \in A2) ((x1, x2) \in setX). Proof. by rewrite inE; apply: andP. Qed. Lemma cardsX : #|setX| = #|A1| * #|A2|. Proof. by rewrite cardsE cardX. Qed. End CartesianProd. Arguments setXP {fT1 fT2 A1 A2 x1 x2}. Section CartesianNProd. Variables (I : finType) (fT : I -> finType). Variables (A : forall i, {set fT i}). Implicit Types (x : {dffun forall i, fT i}). Definition setXn := [set x : {dffun _} in family A]. Lemma in_setXn x : (x \in setXn) = [forall i, x i \in A i]. Proof. by rewrite inE. Qed. Lemma setXnP x : reflect (forall i, x i \in A i) (x \in setXn). Proof. by rewrite inE; apply: forallP. Qed. Lemma cardsXn : #|setXn| = \prod_i #|A i|. Proof. by rewrite cardsE card_family foldrE big_map big_enum. Qed. End CartesianNProd. Arguments setXnP {I fT A x}. HB.lock Definition imset (aT rT : finType) f mD := [set y in @image_mem aT rT f mD]. Canonical imset_unlock := Unlockable imset.unlock. HB.lock Definition imset2 (aT1 aT2 rT : finType) f (D1 : mem_pred aT1) (D2 : _ -> mem_pred aT2) := [set y in @image_mem _ rT (uncurry f) (mem [pred u | D1 u.1 & D2 u.1 u.2])]. Canonical imset2_unlock := Unlockable imset2.unlock. Definition preimset (aT : finType) rT f (R : mem_pred rT) := [set x : aT | in_mem (f x) R]. Notation "f @^-1: A" := (preimset f (mem A)) (at level 24) : set_scope. Notation "f @: A" := (imset f (mem A)) (at level 24) : set_scope. Notation "f @2: ( A , B )" := (imset2 f (mem A) (fun _ => mem B)) (at level 24, format "f @2: ( A , B )") : set_scope. (* Comprehensions *) Notation "[ 'set' E | x 'in' A ]" := ((fun x => E) @: A) (format "[ '[hv' 'set' E '/ ' | x 'in' A ] ']'") : set_scope. Notation "[ 'set' E | x 'in' A & P ]" := [set E | x in pred_of_set [set x in A | P]] (format "[ '[hv' 'set' E '/ ' | x 'in' A '/ ' & P ] ']'") : set_scope. Notation "[ 'set' E | x 'in' A , y 'in' B ]" := (imset2 (fun x y => E) (mem A) (fun x => mem B)) (y at level 99, format "[ '[hv' 'set' E '/ ' | x 'in' A , '/ ' y 'in' B ] ']'" ) : set_scope. Notation "[ 'set' E | x 'in' A , y 'in' B & P ]" := [set E | x in A, y in pred_of_set [set y in B | P]] (format "[ '[hv' 'set' E '/ ' | x 'in' A , '/ ' y 'in' B '/ ' & P ] ']'" ) : set_scope. (* Typed variants *) Notation "[ 'set' E | x : T 'in' A ]" := ((fun x : T => E) @: A) (only parsing) : set_scope. Notation "[ 'set' E | x : T 'in' A & P ]" := [set E | x : T in [set x : T in A | P]] (only parsing) : set_scope. Notation "[ 'set' E | x : T 'in' A , y : U 'in' B ]" := (imset2 (fun (x : T) (y : U) => E) (mem A) (fun (x : T) => mem B)) (y at level 99, only parsing) : set_scope. Notation "[ 'set' E | x : T 'in' A , y : U 'in' B & P ]" := [set E | x : T in A, y : U in [set y : U in B | P]] (only parsing) : set_scope. (* Comprehensions over a type *) Local Notation predOfType T := (pred_of_simpl (@pred_of_argType T)). Notation "[ 'set' E | x : T ]" := [set E | x : T in predOfType T] (format "[ '[hv' 'set' E '/ ' | x : T ] ']'") : set_scope. Notation "[ 'set' E | x : T & P ]" := [set E | x : T in pred_of_set [set x : T | P]] (format "[ '[hv' 'set' E '/ ' | x : T '/ ' & P ] ']'") : set_scope. Notation "[ 'set' E | x : T , y : U 'in' B ]" := [set E | x : T in predOfType T, y : U in B] (y at level 99, format "[ '[hv' 'set' E '/ ' | x : T , '/ ' y : U 'in' B ] ']'") : set_scope. Notation "[ 'set' E | x : T , y : U 'in' B & P ]" := [set E | x : T, y : U in pred_of_set [set y in B | P]] (format "[ '[hv ' 'set' E '/' | x : T , '/ ' y : U 'in' B '/' & P ] ']'" ) : set_scope. Notation "[ 'set' E | x : T 'in' A , y : U ]" := [set E | x : T in A, y : U in predOfType U] (format "[ '[hv' 'set' E '/ ' | x : T 'in' A , '/ ' y : U ] ']'") : set_scope. Notation "[ 'set' E | x : T 'in' A , y : U & P ]" := [set E | x : T in A, y : U in pred_of_set [set y in P]] (format "[ '[hv' 'set' E '/ ' | x : T 'in' A , '/ ' y : U & P ] ']'") : set_scope. Notation "[ 'set' E | x : T , y : U ]" := [set E | x : T, y : U in predOfType U] (format "[ '[hv' 'set' E '/ ' | x : T , '/ ' y : U ] ']'") : set_scope. Notation "[ 'set' E | x : T , y : U & P ]" := [set E | x : T, y : U in pred_of_set [set y in P]] (format "[ '[hv' 'set' E '/ ' | x : T , '/ ' y : U & P ] ']'") : set_scope. (* Untyped variants *) Notation "[ 'set' E | x , y 'in' B ]" := [set E | x : _, y : _ in B] (y at level 99, only parsing) : set_scope. Notation "[ 'set' E | x , y 'in' B & P ]" := [set E | x : _, y : _ in B & P] (only parsing) : set_scope. Notation "[ 'set' E | x 'in' A , y ]" := [set E | x : _ in A, y : _] (only parsing) : set_scope. Notation "[ 'set' E | x 'in' A , y & P ]" := [set E | x : _ in A, y : _ & P] (only parsing) : set_scope. Notation "[ 'set' E | x , y ]" := [set E | x : _, y : _] (only parsing) : set_scope. Notation "[ 'set' E | x , y & P ]" := [set E | x : _, y : _ & P ] (only parsing) : set_scope. Section FunImage. Variables aT aT2 : finType. Section ImsetTheory. Variable rT : finType. Section ImsetProp. Variables (f : aT -> rT) (f2 : aT -> aT2 -> rT). Lemma imsetP D y : reflect (exists2 x, in_mem x D & y = f x) (y \in imset f D). Proof. by rewrite [@imset]unlock inE; apply: imageP. Qed. Variant imset2_spec D1 D2 y : Prop := Imset2spec x1 x2 of in_mem x1 D1 & in_mem x2 (D2 x1) & y = f2 x1 x2. Lemma imset2P D1 D2 y : reflect (imset2_spec D1 D2 y) (y \in imset2 f2 D1 D2). Proof. rewrite [@imset2]unlock inE. apply: (iffP imageP) => [[[x1 x2] Dx12] | [x1 x2 Dx1 Dx2]] -> {y}. by case/andP: Dx12; exists x1 x2. by exists (x1, x2); rewrite //= !inE Dx1. Qed. Lemma imset_f (D : {pred aT}) x : x \in D -> f x \in f @: D. Proof. by move=> Dx; apply/imsetP; exists x. Qed. Lemma mem_imset (D : {pred aT}) x : injective f -> f x \in f @: D = (x \in D). Proof. by move=> f_inj; apply/imsetP/idP;[case=> [y] ? /f_inj -> | move=> ?; exists x]. Qed. Lemma imset0 : f @: set0 = set0. Proof. by apply/setP => y /[!inE]; apply/imsetP => -[x /[!inE]]. Qed. Lemma imset_eq0 (A : {set aT}) : (f @: A == set0) = (A == set0). Proof. have [-> | [x Ax]] := set_0Vmem A; first by rewrite imset0 !eqxx. by rewrite -!cards_eq0 (cardsD1 x) Ax (cardsD1 (f x)) imset_f. Qed. Lemma imset_set1 x : f @: [set x] = [set f x]. Proof. apply/setP => y. by apply/imsetP/set1P=> [[x' /set1P-> //]| ->]; exists x; rewrite ?set11. Qed. Lemma imset_inj : injective f -> injective (fun A : {set aT} => f @: A). Proof. move=> inj_f A B => /setP E; apply/setP => x. by rewrite -(mem_imset A x inj_f) E mem_imset. Qed. Lemma imset_disjoint (A B : {pred aT}) : injective f -> [disjoint f @: A & f @: B] = [disjoint A & B]. Proof. move=> inj_f; apply/pred0Pn/pred0Pn => /= [[_ /andP[/imsetP[x xA ->]] xB]|]. by exists x; rewrite xA -(mem_imset B x inj_f). by move=> [x /andP[xA xB]]; exists (f x); rewrite !mem_imset ?xA. Qed. Lemma imset2_f (D : {pred aT}) (D2 : aT -> {pred aT2}) x x2 : x \in D -> x2 \in D2 x -> f2 x x2 \in [set f2 y y2 | y in D, y2 in D2 y]. Proof. by move=> Dx Dx2; apply/imset2P; exists x x2. Qed. Lemma mem_imset2 (D : {pred aT}) (D2 : aT -> {pred aT2}) x x2 : injective2 f2 -> (f2 x x2 \in [set f2 y y2 | y in D, y2 in D2 y]) = (x \in D) && (x2 \in D2 x). Proof. move=> inj2_f; apply/imset2P/andP => [|[xD xD2]]; last by exists x x2. by move => [x' x2' xD xD2 eq_f2]; case: (inj2_f _ _ _ _ eq_f2) => -> ->. Qed. Lemma sub_imset_pre (A : {pred aT}) (B : {pred rT}) : (f @: A \subset B) = (A \subset f @^-1: B). Proof. apply/subsetP/subsetP=> [sfAB x Ax | sAf'B fx]. by rewrite inE sfAB ?imset_f. by move=> /imsetP[a + ->] => /sAf'B /[!inE]. Qed. Lemma preimsetS (A B : {pred rT}) : A \subset B -> (f @^-1: A) \subset (f @^-1: B). Proof. by move=> sAB; apply/subsetP=> y /[!inE]; apply: subsetP. Qed. Lemma preimset0 : f @^-1: set0 = set0. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma preimsetT : f @^-1: setT = setT. Proof. by apply/setP=> x; rewrite !inE. Qed. Lemma preimsetI (A B : {set rT}) : f @^-1: (A :&: B) = (f @^-1: A) :&: (f @^-1: B). Proof. by apply/setP=> y; rewrite !inE. Qed. Lemma preimsetU (A B : {set rT}) : f @^-1: (A :|: B) = (f @^-1: A) :|: (f @^-1: B). Proof. by apply/setP=> y; rewrite !inE. Qed. Lemma preimsetD (A B : {set rT}) : f @^-1: (A :\: B) = (f @^-1: A) :\: (f @^-1: B). Proof. by apply/setP=> y; rewrite !inE. Qed. Lemma preimsetC (A : {set rT}) : f @^-1: (~: A) = ~: f @^-1: A. Proof. by apply/setP=> y; rewrite !inE. Qed. Lemma imsetS (A B : {pred aT}) : A \subset B -> f @: A \subset f @: B. Proof. move=> sAB; apply/subsetP => _ /imsetP[x Ax ->]. by apply/imsetP; exists x; rewrite ?(subsetP sAB). Qed. Lemma imset_proper (A B : {set aT}) : {in B &, injective f} -> A \proper B -> f @: A \proper f @: B. Proof. move=> injf /properP[sAB [x Bx nAx]]; rewrite properE imsetS //=. apply: contra nAx => sfBA. have: f x \in f @: A by rewrite (subsetP sfBA) ?imset_f. by case/imsetP=> y Ay /injf-> //; apply: subsetP sAB y Ay. Qed. Lemma preimset_proper (A B : {set rT}) : B \subset codom f -> A \proper B -> (f @^-1: A) \proper (f @^-1: B). Proof. move=> sBc /properP[sAB [u Bu nAu]]; rewrite properE preimsetS //=. by apply/subsetPn; exists (iinv (subsetP sBc _ Bu)); rewrite inE /= f_iinv. Qed. Lemma imsetU (A B : {set aT}) : f @: (A :|: B) = (f @: A) :|: (f @: B). Proof. apply/eqP; rewrite eqEsubset subUset. rewrite 2?imsetS (andbT, subsetUl, subsetUr) // andbT. apply/subsetP=> _ /imsetP[x ABx ->]; apply/setUP. by case/setUP: ABx => [Ax | Bx]; [left | right]; apply/imsetP; exists x. Qed. Lemma imsetU1 a (A : {set aT}) : f @: (a |: A) = f a |: (f @: A). Proof. by rewrite imsetU imset_set1. Qed. Lemma imsetI (A B : {set aT}) : {in A & B, injective f} -> f @: (A :&: B) = f @: A :&: f @: B. Proof. move=> injf; apply/eqP; rewrite eqEsubset subsetI. rewrite 2?imsetS (andTb, subsetIl, subsetIr) //=. apply/subsetP=> _ /setIP[/imsetP[x Ax ->] /imsetP[z Bz /injf eqxz]]. by rewrite imset_f // inE Ax eqxz. Qed. Lemma imset2Sl (A B : {pred aT}) (C : {pred aT2}) : A \subset B -> f2 @2: (A, C) \subset f2 @2: (B, C). Proof. move=> sAB; apply/subsetP=> _ /imset2P[x y Ax Cy ->]. by apply/imset2P; exists x y; rewrite ?(subsetP sAB). Qed. Lemma imset2Sr (A B : {pred aT2}) (C : {pred aT}) : A \subset B -> f2 @2: (C, A) \subset f2 @2: (C, B). Proof. move=> sAB; apply/subsetP=> _ /imset2P[x y Ax Cy ->]. by apply/imset2P; exists x y; rewrite ?(subsetP sAB). Qed. Lemma imset2S (A B : {pred aT}) (A2 B2 : {pred aT2}) : A \subset B -> A2 \subset B2 -> f2 @2: (A, A2) \subset f2 @2: (B, B2). Proof. by move=> /(imset2Sl B2) sBA /(imset2Sr A)/subset_trans->. Qed. End ImsetProp. Implicit Types (f g : aT -> rT) (D : {pred aT}) (R : {pred rT}). Lemma eq_preimset f g R : f =1 g -> f @^-1: R = g @^-1: R. Proof. by move=> eqfg; apply/setP => y; rewrite !inE eqfg. Qed. Lemma eq_imset f g D : f =1 g -> f @: D = g @: D. Proof. move=> eqfg; apply/setP=> y. by apply/imsetP/imsetP=> [] [x Dx ->]; exists x; rewrite ?eqfg. Qed. Lemma eq_in_imset f g D : {in D, f =1 g} -> f @: D = g @: D. Proof. move=> eqfg; apply/setP => y. by apply/imsetP/imsetP=> [] [x Dx ->]; exists x; rewrite ?eqfg. Qed. Lemma eq_in_imset2 (f g : aT -> aT2 -> rT) (D : {pred aT}) (D2 : {pred aT2}) : {in D & D2, f =2 g} -> f @2: (D, D2) = g @2: (D, D2). Proof. move=> eqfg; apply/setP => y. by apply/imset2P/imset2P=> [] [x x2 Dx Dx2 ->]; exists x x2; rewrite ?eqfg. Qed. End ImsetTheory. Lemma imset2_pair (A : {set aT}) (B : {set aT2}) : [set (x, y) | x in A, y in B] = setX A B. Proof. apply/setP=> [[x y]]; rewrite !inE /=. by apply/imset2P/andP=> [[_ _ _ _ [-> ->]//]| []]; exists x y. Qed. Lemma setXS (A1 B1 : {set aT}) (A2 B2 : {set aT2}) : A1 \subset B1 -> A2 \subset B2 -> setX A1 A2 \subset setX B1 B2. Proof. by move=> sAB1 sAB2; rewrite -!imset2_pair imset2S. Qed. End FunImage. Arguments imsetP {aT rT f D y}. Arguments imset2P {aT aT2 rT f2 D1 D2 y}. Arguments imset_disjoint {aT rT f A B}. Section unset1. Variable (I : finType). Implicit Types (i : I) (A : {set I}). Lemma pick_set1 i0 : [pick x in [set i0]] = Some i0. Proof. by case: pickP => [i /[!inE]/eqP-> | /(_ i0)/[!(inE, eqxx)]]. Qed. Definition unset1 A : option I := if #|A| == 1 then [pick x in A] else None. Lemma set1K : pcancel set1 unset1. Proof. by move=> i; rewrite /unset1 cards1 eqxx pick_set1. Qed. Lemma omap_unset1K A : #|A| = 1 -> omap set1 (unset1 A) = Some A. Proof. by move=> /eqP/cards1P[i ->]; rewrite set1K. Qed. Lemma unset10 : unset1 set0 = None. Proof. by rewrite /unset1 cards0. Qed. Lemma unset1N1 A : #|A| != 1 -> unset1 A = None. Proof. by move=> AN1; rewrite /unset1 ifN. Qed. Lemma unset1K : ocancel unset1 set1. Proof. move=> A; rewrite /unset1. by case: ifPn => // /cards1P[i ->]/=; rewrite pick_set1. Qed. End unset1. Arguments unset1 {I}. Lemma setXnS (I : finType) (T : I -> finType) (A B : forall i, {set T i}) : (forall i, A i \subset B i) -> setXn A \subset setXn B. Proof. move=> sAB; apply/subsetP => x /setXnP xA. by apply/setXnP => i; apply/subsetP: (xA i). Qed. Lemma eq_setXn (I : finType) (T : I -> finType) (A B : forall i, {set T i}) : (forall i, A i = B i) -> setXn A = setXn B. Proof. by move=> eqAB; apply/eqP; rewrite eqEsubset !setXnS// => j; rewrite eqAB. Qed. Section BigOpsAnyOp. Variables (R : Type) (x : R) (op : R -> R -> R). Variables I : finType. Implicit Type F : I -> R. Lemma big_set0 F : \big[op/x]_(i in set0) F i = x. Proof. by apply: big_pred0 => i; rewrite inE. Qed. Lemma big_set1E j F : \big[op/x]_(i in [set j]) F i = op (F j) x. Proof. by rewrite -big_pred1_eq_id; apply: eq_bigl => i; apply: in_set1. Qed. Lemma big_set (A : pred I) F : \big[op/x]_(i in [set i | A i]) (F i) = \big[op/x]_(i in A) (F i). Proof. by apply: eq_bigl => i; rewrite inE. Qed. End BigOpsAnyOp. Section BigOpsSemiGroup. Variables (R : Type) (op : SemiGroup.com_law R). Variable (le : rel R). Hypotheses (le_refl : reflexive le) (le_incr : forall x y, le x (op x y)). Context [x : R]. Lemma subset_le_big_cond (I : finType) (A A' P P' : {pred I}) (F : I -> R) : [set i in A | P i] \subset [set i in A' | P' i] -> le (\big[op/x]_(i in A | P i) F i) (\big[op/x]_(i in A' | P' i) F i). Proof. by move=> /subsetP AP; apply: sub_le_big => // i; have /[!inE] := AP i. Qed. Lemma big_imset_idem [I J : finType] (h : I -> J) (A : pred I) F : idempotent_op op -> \big[op/x]_(j in h @: A) F j = \big[op/x]_(i in A) F (h i). Proof. rewrite -!big_image => op_idem; rewrite -big_undup// -[RHS]big_undup//. apply/perm_big/perm_undup => j; apply/imageP. have [mem_j | /imageP mem_j] := boolP (j \in [seq h j | j in A]). - by exists j => //; apply/imsetP; apply: imageP mem_j. - by case=> k /imsetP [i j_in_A ->] eq_i; apply: mem_j; exists i. Qed. End BigOpsSemiGroup. Section BigOps. Variables (R : Type) (idx : R). Variables (op : Monoid.law idx) (aop : Monoid.com_law idx). Variables (times : Monoid.mul_law idx) (plus : Monoid.add_law idx times). Variables I J : finType. Implicit Type A B : {set I}. Implicit Type h : I -> J. Implicit Type P : pred I. Implicit Type F : I -> R. Lemma big_set1 a F : \big[op/idx]_(i in [set a]) F i = F a. Proof. by apply: big_pred1 => i; rewrite !inE. Qed. Lemma big_setID A B F : \big[aop/idx]_(i in A) F i = aop (\big[aop/idx]_(i in A :&: B) F i) (\big[aop/idx]_(i in A :\: B) F i). Proof. rewrite (bigID [in B]) setDE. by congr (aop _ _); apply: eq_bigl => i; rewrite !inE. Qed. Lemma big_setIDcond A B P F : \big[aop/idx]_(i in A | P i) F i = aop (\big[aop/idx]_(i in A :&: B | P i) F i) (\big[aop/idx]_(i in A :\: B | P i) F i). Proof. by rewrite !big_mkcondr; apply: big_setID. Qed. Lemma big_setD1 a A F : a \in A -> \big[aop/idx]_(i in A) F i = aop (F a) (\big[aop/idx]_(i in A :\ a) F i). Proof. move=> Aa; rewrite (bigD1 a Aa); congr (aop _). by apply: eq_bigl => x; rewrite !inE andbC. Qed. Lemma big_setU1 a A F : a \notin A -> \big[aop/idx]_(i in a |: A) F i = aop (F a) (\big[aop/idx]_(i in A) F i). Proof. by move=> notAa; rewrite (@big_setD1 a) ?setU11 //= setU1K. Qed. Lemma big_subset_idem_cond A B P F : idempotent_op aop -> A \subset B -> aop (\big[aop/idx]_(i in A | P i) F i) (\big[aop/idx]_(i in B | P i) F i) = \big[aop/idx]_(i in B | P i) F i. Proof. by move=> idaop /setIidPr <-; rewrite (big_setIDcond B A) Monoid.mulmA /= idaop. Qed. Lemma big_subset_idem A B F : idempotent_op aop -> A \subset B -> aop (\big[aop/idx]_(i in A) F i) (\big[aop/idx]_(i in B) F i) = \big[aop/idx]_(i in B) F i. Proof. by rewrite -2!big_condT; apply: big_subset_idem_cond. Qed. Lemma big_setU_cond A B P F : idempotent_op aop -> \big[aop/idx]_(i in A :|: B | P i) F i = aop (\big[aop/idx]_(i in A | P i) F i) (\big[aop/idx]_(i in B | P i) F i). Proof. move=> idemaop; rewrite (big_setIDcond _ A) setUK setDUl setDv set0U. rewrite (big_setIDcond B A) Monoid.mulmCA Monoid.mulmA /=. by rewrite (@big_subset_idem_cond (B :&: A)) // subsetIr. Qed. Lemma big_setU A B F : idempotent_op aop -> \big[aop/idx]_(i in A :|: B) F i = aop (\big[aop/idx]_(i in A) F i) (\big[aop/idx]_(i in B) F i). Proof. by rewrite -3!big_condT; apply: big_setU_cond. Qed. Lemma big_imset h (A : {pred I}) G : {in A &, injective h} -> \big[aop/idx]_(j in h @: A) G j = \big[aop/idx]_(i in A) G (h i). Proof. move=> injh; pose hA := mem (image h A). rewrite (eq_bigl hA) => [|j]; last exact/imsetP/imageP. pose h' := omap (fun u : {j | hA j} => iinv (svalP u)) \o insub. rewrite (reindex_omap h h') => [|j hAj]; rewrite {}/h'/= ?insubT/= ?f_iinv//. apply: eq_bigl => i; case: insubP => [u /= -> def_u | nhAhi]; last first. by apply/andP/idP => [[]//| Ai]; case/imageP: nhAhi; exists i. set i' := iinv _; have Ai' : i' \in A := mem_iinv (svalP u). by apply/eqP/idP => [[<-] // | Ai]; congr Some; apply: injh; rewrite ?f_iinv. Qed. Lemma big_imset_cond h (A : {pred I}) (P : pred J) G : {in A &, injective h} -> \big[aop/idx]_(j in h @: A | P j) G j = \big[aop/idx]_(i in A | P (h i)) G (h i). Proof. by move=> h_inj; rewrite 2!big_mkcondr big_imset. Qed. Lemma partition_big_imset h (A : {pred I}) F : \big[aop/idx]_(i in A) F i = \big[aop/idx]_(j in h @: A) \big[aop/idx]_(i in A | h i == j) F i. Proof. by apply: partition_big => i Ai; apply/imsetP; exists i. Qed. Lemma big_cards1 (f : {set I} -> R) : \big[aop/idx]_(A : {set I} | #|A| == 1) f A = \big[aop/idx]_(i : I) f [set i]. Proof. rewrite (reindex_omap set1 unset1) => [|A /cards1P[i ->] /[!set1K]//]. by apply: eq_bigl => i; rewrite set1K cards1 !eqxx. Qed. End BigOps. Lemma bigA_distr (R : Type) (zero one : R) (mul : Monoid.mul_law zero) (add : Monoid.add_law zero mul) (I : finType) (F G : I -> R) : \big[mul/one]_i add (F i) (G i) = \big[add/zero]_(J in {set I}) \big[mul/one]_i (if i \in J then F i else G i). Proof. under eq_bigr => i _ do rewrite -(big_bool _ (fun b => if b then F i else G i)). rewrite bigA_distr_bigA. set f := fun J : {set I} => val J. transitivity (\big[add/zero]_(f0 in (imset f (mem setT))) \big[mul/one]_i (if f0 i then F i else G i)). suff <-: setT = imset f (mem setT) by apply: congr_big=>// i; rewrite in_setT. apply/esym/eqP; rewrite -subTset; apply/subsetP => b _. by apply/imsetP; exists (FinSet b). rewrite big_imset; last by case=> g; case=> h _ _; rewrite /f => /= ->. apply: congr_big => //; case=> g; first exact: in_setT. by move=> _; apply: eq_bigr => i _; congr (if _ then _ else _); rewrite unlock. Qed. Arguments big_setID [R idx aop I A]. Arguments big_setD1 [R idx aop I] a [A F]. Arguments big_setU1 [R idx aop I] a [A F]. Arguments big_imset [R idx aop I J h A]. Arguments partition_big_imset [R idx aop I J]. Section Fun2Set1. Variables aT1 aT2 rT : finType. Variables (f : aT1 -> aT2 -> rT). Lemma imset2_set1l x1 (D2 : {pred aT2}) : f @2: ([set x1], D2) = f x1 @: D2. Proof. apply/setP=> y; apply/imset2P/imsetP=> [[x x2 /set1P->]| [x2 Dx2 ->]]. by exists x2. by exists x1 x2; rewrite ?set11. Qed. Lemma imset2_set1r x2 (D1 : {pred aT1}) : f @2: (D1, [set x2]) = f^~ x2 @: D1. Proof. apply/setP=> y; apply/imset2P/imsetP=> [[x1 x Dx1 /set1P->]| [x1 Dx1 ->]]. by exists x1. by exists x1 x2; rewrite ?set11. Qed. End Fun2Set1. Section CardFunImage. Variables aT aT2 rT : finType. Variables (f : aT -> rT) (g : rT -> aT) (f2 : aT -> aT2 -> rT). Variables (D : {pred aT}) (D2 : {pred aT}). Lemma imset_card : #|f @: D| = #|image f D|. Proof. by rewrite [@imset]unlock cardsE. Qed. Lemma leq_imset_card : #|f @: D| <= #|D|. Proof. by rewrite imset_card leq_image_card. Qed. Lemma card_in_imset : {in D &, injective f} -> #|f @: D| = #|D|. Proof. by move=> injf; rewrite imset_card card_in_image. Qed. Lemma card_imset : injective f -> #|f @: D| = #|D|. Proof. by move=> injf; rewrite imset_card card_image. Qed. Lemma imset_injP : reflect {in D &, injective f} (#|f @: D| == #|D|). Proof. by rewrite [@imset]unlock cardsE; apply: image_injP. Qed. Lemma can2_in_imset_pre : {in D, cancel f g} -> {on D, cancel g & f} -> f @: D = g @^-1: D. Proof. move=> fK gK; apply/setP=> y; rewrite inE. by apply/imsetP/idP=> [[x Ax ->] | Agy]; last exists (g y); rewrite ?(fK, gK). Qed. Lemma can2_imset_pre : cancel f g -> cancel g f -> f @: D = g @^-1: D. Proof. by move=> fK gK; apply: can2_in_imset_pre; apply: in1W. Qed. End CardFunImage. Arguments imset_injP {aT rT f D}. Lemma on_card_preimset (aT rT : finType) (f : aT -> rT) (R : {pred rT}) : {on R, bijective f} -> #|f @^-1: R| = #|R|. Proof. case=> g fK gK; rewrite -(can2_in_imset_pre gK) // card_in_imset //. exact: can_in_inj gK. Qed. Lemma can_imset_pre (T : finType) f g (A : {set T}) : cancel f g -> f @: A = g @^-1: A :> {set T}. Proof. move=> fK; apply: can2_imset_pre => // x. suffices fx: x \in codom f by rewrite -(f_iinv fx) fK. exact/(subset_cardP (card_codom (can_inj fK)))/subsetP. Qed. Lemma imset_id (T : finType) (A : {set T}) : [set x | x in A] = A. Proof. by apply/setP=> x; rewrite (@can_imset_pre _ _ id) ?inE. Qed. Lemma card_preimset (T : finType) (f : T -> T) (A : {set T}) : injective f -> #|f @^-1: A| = #|A|. Proof. move=> injf; apply: on_card_preimset; apply: onW_bij. have ontof: _ \in codom f by apply/(subset_cardP (card_codom injf))/subsetP. by exists (fun x => iinv (ontof x)) => x; rewrite (f_iinv, iinv_f). Qed. Lemma card_powerset (T : finType) (A : {set T}) : #|powerset A| = 2 ^ #|A|. Proof. rewrite -card_bool -(card_pffun_on false) -(card_imset _ val_inj). apply: eq_card => f; pose sf := false.-support f; pose D := finset sf. have sDA: (D \subset A) = (sf \subset A) by apply: eq_subset; apply: in_set. have eq_sf x : sf x = f x by rewrite /= negb_eqb addbF. have valD: val D = f by rewrite /D unlock; apply/ffunP=> x; rewrite ffunE eq_sf. apply/imsetP/pffun_onP=> [[B] | [sBA _]]; last by exists D; rewrite // inE ?sDA. by rewrite inE -sDA -valD => sBA /val_inj->. Qed. Section FunImageComp. Variables T T' U : finType. Lemma imset_comp (f : T' -> U) (g : T -> T') (H : {pred T}) : (f \o g) @: H = f @: (g @: H). Proof. apply/setP/subset_eqP/andP. split; apply/subsetP=> _ /imsetP[x0 Hx0 ->]; apply/imsetP. by exists (g x0); first apply: imset_f. by move/imsetP: Hx0 => [x1 Hx1 ->]; exists x1. Qed. End FunImageComp. Notation "\bigcup_ ( i <- r | P ) F" := (\big[@setU _/set0]_(i <- r | P) F%SET) : set_scope. Notation "\bigcup_ ( i <- r ) F" := (\big[@setU _/set0]_(i <- r) F%SET) : set_scope. Notation "\bigcup_ ( m <= i < n | P ) F" := (\big[@setU _/set0]_(m <= i < n | P%B) F%SET) : set_scope. Notation "\bigcup_ ( m <= i < n ) F" := (\big[@setU _/set0]_(m <= i < n) F%SET) : set_scope. Notation "\bigcup_ ( i | P ) F" := (\big[@setU _/set0]_(i | P%B) F%SET) : set_scope. Notation "\bigcup_ i F" := (\big[@setU _/set0]_i F%SET) : set_scope. Notation "\bigcup_ ( i : t | P ) F" := (\big[@setU _/set0]_(i : t | P%B) F%SET) (only parsing): set_scope. Notation "\bigcup_ ( i : t ) F" := (\big[@setU _/set0]_(i : t) F%SET) (only parsing) : set_scope. Notation "\bigcup_ ( i < n | P ) F" := (\big[@setU _/set0]_(i < n | P%B) F%SET) : set_scope. Notation "\bigcup_ ( i < n ) F" := (\big[@setU _/set0]_ (i < n) F%SET) : set_scope. Notation "\bigcup_ ( i 'in' A | P ) F" := (\big[@setU _/set0]_(i in A | P%B) F%SET) : set_scope. Notation "\bigcup_ ( i 'in' A ) F" := (\big[@setU _/set0]_(i in A) F%SET) : set_scope. Notation "\bigcap_ ( i <- r | P ) F" := (\big[@setI _/setT]_(i <- r | P%B) F%SET) : set_scope. Notation "\bigcap_ ( i <- r ) F" := (\big[@setI _/setT]_(i <- r) F%SET) : set_scope. Notation "\bigcap_ ( m <= i < n | P ) F" := (\big[@setI _/setT]_(m <= i < n | P%B) F%SET) : set_scope. Notation "\bigcap_ ( m <= i < n ) F" := (\big[@setI _/setT]_(m <= i < n) F%SET) : set_scope. Notation "\bigcap_ ( i | P ) F" := (\big[@setI _/setT]_(i | P%B) F%SET) : set_scope. Notation "\bigcap_ i F" := (\big[@setI _/setT]_i F%SET) : set_scope. Notation "\bigcap_ ( i : t | P ) F" := (\big[@setI _/setT]_(i : t | P%B) F%SET) (only parsing): set_scope. Notation "\bigcap_ ( i : t ) F" := (\big[@setI _/setT]_(i : t) F%SET) (only parsing) : set_scope. Notation "\bigcap_ ( i < n | P ) F" := (\big[@setI _/setT]_(i < n | P%B) F%SET) : set_scope. Notation "\bigcap_ ( i < n ) F" := (\big[@setI _/setT]_(i < n) F%SET) : set_scope. Notation "\bigcap_ ( i 'in' A | P ) F" := (\big[@setI _/setT]_(i in A | P%B) F%SET) : set_scope. Notation "\bigcap_ ( i 'in' A ) F" := (\big[@setI _/setT]_(i in A) F%SET) : set_scope. Section BigSetOps. Variables T I : finType. Implicit Types (U : {pred T}) (P : pred I) (A B : {set I}) (F : I -> {set T}). (* It is very hard to use this lemma, because the unification fails to *) (* defer the F j pattern (even though it's a Miller pattern!). *) Lemma bigcup_sup j P F : P j -> F j \subset \bigcup_(i | P i) F i. Proof. by move=> Pj; rewrite (bigD1 j) //= subsetUl. Qed. Lemma bigcup_max j U P F : P j -> U \subset F j -> U \subset \bigcup_(i | P i) F i. Proof. by move=> Pj sUF; apply: subset_trans (bigcup_sup _ Pj). Qed. Lemma bigcupP x P F : reflect (exists2 i, P i & x \in F i) (x \in \bigcup_(i | P i) F i). Proof. apply: (iffP idP) => [|[i Pi]]; last first. by apply: subsetP x; apply: bigcup_sup. by elim/big_rec: _ => [|i _ Pi _ /setUP[|//]]; [rewrite inE | exists i]. Qed. Lemma bigcupsP U P F : reflect (forall i, P i -> F i \subset U) (\bigcup_(i | P i) F i \subset U). Proof. apply: (iffP idP) => [sFU i Pi| sFU]. by apply: subset_trans sFU; apply: bigcup_sup. by apply/subsetP=> x /bigcupP[i Pi]; apply: (subsetP (sFU i Pi)). Qed. Lemma bigcup0P P F : reflect (forall i, P i -> F i = set0) (\bigcup_(i | P i) F i == set0). Proof. rewrite -subset0; apply: (iffP (bigcupsP _ _ _)) => sub0 i /sub0; last by move->. by rewrite subset0 => /eqP. Qed. Lemma bigcup_disjointP U P F : reflect (forall i : I, P i -> [disjoint U & F i]) [disjoint U & \bigcup_(i | P i) F i]. Proof. apply: (iffP idP) => [dUF i Pp|dUF]. by apply: disjointWr dUF; apply: bigcup_sup. rewrite disjoint_sym disjoint_subset. by apply/bigcupsP=> i /dUF; rewrite disjoint_sym disjoint_subset. Qed. Lemma bigcup_disjoint U P F : (forall i, P i -> [disjoint U & F i]) -> [disjoint U & \bigcup_(i | P i) F i]. Proof. by move/bigcup_disjointP. Qed. Lemma bigcup_setU A B F : \bigcup_(i in A :|: B) F i = (\bigcup_(i in A) F i) :|: (\bigcup_ (i in B) F i). Proof. apply/setP=> x; apply/bigcupP/setUP=> [[i] | ]. by case/setUP; [left | right]; apply/bigcupP; exists i. by case=> /bigcupP[i Pi]; exists i; rewrite // inE Pi ?orbT. Qed. Lemma bigcup_seq r F : \bigcup_(i <- r) F i = \bigcup_(i in r) F i. Proof. elim: r => [|i r IHr]; first by rewrite big_nil big_pred0. rewrite big_cons {}IHr; case r_i: (i \in r). rewrite (setUidPr _) ?bigcup_sup //. by apply: eq_bigl => j /[!inE]; case: eqP => // ->. rewrite (bigD1 i (mem_head i r)) /=; congr (_ :|: _). by apply: eq_bigl => j /=; rewrite andbC; case: eqP => // ->. Qed. (* Unlike its setU counterpart, this lemma is useable. *) Lemma bigcap_inf j P F : P j -> \bigcap_(i | P i) F i \subset F j. Proof. by move=> Pj; rewrite (bigD1 j) //= subsetIl. Qed. Lemma bigcap_min j U P F : P j -> F j \subset U -> \bigcap_(i | P i) F i \subset U. Proof. by move=> Pj; apply: subset_trans (bigcap_inf _ Pj). Qed. Lemma bigcapsP U P F : reflect (forall i, P i -> U \subset F i) (U \subset \bigcap_(i | P i) F i). Proof. apply: (iffP idP) => [sUF i Pi | sUF]. by apply: subset_trans sUF _; apply: bigcap_inf. elim/big_rec: _ => [|i V Pi sUV]; apply/subsetP=> x Ux; rewrite inE //. by rewrite !(subsetP _ x Ux) ?sUF. Qed. Lemma bigcapP x P F : reflect (forall i, P i -> x \in F i) (x \in \bigcap_(i | P i) F i). Proof. rewrite -sub1set. by apply: (iffP (bigcapsP _ _ _)) => Fx i /Fx; rewrite sub1set. Qed. Lemma setC_bigcup J r (P : pred J) (F : J -> {set T}) : ~: (\bigcup_(j <- r | P j) F j) = \bigcap_(j <- r | P j) ~: F j. Proof. by apply: big_morph => [A B|]; rewrite ?setC0 ?setCU. Qed. Lemma setC_bigcap J r (P : pred J) (F : J -> {set T}) : ~: (\bigcap_(j <- r | P j) F j) = \bigcup_(j <- r | P j) ~: F j. Proof. by apply: big_morph => [A B|]; rewrite ?setCT ?setCI. Qed. Lemma bigcap_setU A B F : (\bigcap_(i in A :|: B) F i) = (\bigcap_(i in A) F i) :&: (\bigcap_(i in B) F i). Proof. by apply: setC_inj; rewrite setCI !setC_bigcap bigcup_setU. Qed. Lemma bigcap_seq r F : \bigcap_(i <- r) F i = \bigcap_(i in r) F i. Proof. by apply: setC_inj; rewrite !setC_bigcap bigcup_seq. Qed. End BigSetOps. Arguments bigcup_sup [T I] j [P F]. Arguments bigcup_max [T I] j [U P F]. Arguments bigcupP {T I x P F}. Arguments bigcupsP {T I U P F}. Arguments bigcup_disjointP {T I U P F}. Arguments bigcap_inf [T I] j [P F]. Arguments bigcap_min [T I] j [U P F]. Arguments bigcapP {T I x P F}. Arguments bigcapsP {T I U P F}. Section ImsetCurry. Variables (aT1 aT2 rT : finType) (f : aT1 -> aT2 -> rT). Section Curry. Variables (A1 : {set aT1}) (A2 : {set aT2}). Variables (D1 : {pred aT1}) (D2 : {pred aT2}). Lemma curry_imset2X : f @2: (A1, A2) = uncurry f @: (setX A1 A2). Proof. rewrite [@imset]unlock unlock; apply/setP=> x; rewrite !in_set; congr (x \in _). by apply: eq_image => u //=; rewrite !inE. Qed. Lemma curry_imset2l : f @2: (D1, D2) = \bigcup_(x1 in D1) f x1 @: D2. Proof. apply/setP=> y; apply/imset2P/bigcupP => [[x1 x2 Dx1 Dx2 ->{y}] | [x1 Dx1]]. by exists x1; rewrite // imset_f. by case/imsetP=> x2 Dx2 ->{y}; exists x1 x2. Qed. Lemma curry_imset2r : f @2: (D1, D2) = \bigcup_(x2 in D2) f^~ x2 @: D1. Proof. apply/setP=> y; apply/imset2P/bigcupP => [[x1 x2 Dx1 Dx2 ->{y}] | [x2 Dx2]]. by exists x2; rewrite // (imset_f (f^~ x2)). by case/imsetP=> x1 Dx1 ->{y}; exists x1 x2. Qed. End Curry. Lemma imset2Ul (A B : {set aT1}) (C : {set aT2}) : f @2: (A :|: B, C) = f @2: (A, C) :|: f @2: (B, C). Proof. by rewrite !curry_imset2l bigcup_setU. Qed. Lemma imset2Ur (A : {set aT1}) (B C : {set aT2}) : f @2: (A, B :|: C) = f @2: (A, B) :|: f @2: (A, C). Proof. by rewrite !curry_imset2r bigcup_setU. Qed. End ImsetCurry. Section Partitions. Variables T I : finType. Implicit Types (x y z : T) (A B D X : {set T}) (P Q : {set {set T}}). Implicit Types (J : pred I) (F : I -> {set T}). Definition cover P := \bigcup_(B in P) B. Definition pblock P x := odflt set0 (pick [pred B in P | x \in B]). Definition trivIset P := \sum_(B in P) #|B| == #|cover P|. Definition partition P D := [&& cover P == D, trivIset P & set0 \notin P]. Definition is_transversal X P D := [&& partition P D, X \subset D & [forall B in P, #|X :&: B| == 1]]. Definition transversal P D := [set odflt x [pick y in pblock P x] | x in D]. Definition transversal_repr x0 X B := odflt x0 [pick x in X :&: B]. Lemma leq_card_setU A B : #|A :|: B| <= #|A| + #|B| ?= iff [disjoint A & B]. Proof. rewrite -(addn0 #|_|) -setI_eq0 -cards_eq0 -cardsUI eq_sym. by rewrite (mono_leqif (leq_add2l _)). Qed. Lemma leq_card_cover P : #|cover P| <= \sum_(A in P) #|A| ?= iff trivIset P. Proof. split; last exact: eq_sym. rewrite /cover; elim/big_rec2: _ => [|A n U _ leUn]; first by rewrite cards0. by rewrite (leq_trans (leq_card_setU A U).1) ?leq_add2l. Qed. Lemma imset_cover (T' : finType) P (f : T -> T') : [set f x | x in cover P] = \bigcup_(i in P) [set f x | x in i]. Proof. apply/setP=> y; apply/imsetP/bigcupP => [|[A AP /imsetP[x xA ->]]]. by move=> [x /bigcupP[A AP xA] ->]; exists A => //; rewrite imset_f. by exists x => //; apply/bigcupP; exists A. Qed. Lemma cover1 A : cover [set A] = A. Proof. by rewrite /cover big_set1. Qed. Lemma trivIset1 A : trivIset [set A]. Proof. by rewrite /trivIset cover1 big_set1. Qed. Lemma trivIsetP P : reflect {in P &, forall A B, A != B -> [disjoint A & B]} (trivIset P). Proof. rewrite -[P]set_enum; elim: {P}(enum _) (enum_uniq P) => [_ | A e IHe] /=. by rewrite /trivIset /cover !big_set0 cards0; left=> A; rewrite inE. case/andP; rewrite set_cons -(in_set (fun B => B \in e)) => PA {}/IHe. move: {e}[set x in e] PA => P PA IHP. rewrite /trivIset /cover !big_setU1 //= eq_sym. have:= leq_card_cover P; rewrite -(mono_leqif (leq_add2l #|A|)). move/(leqif_trans (leq_card_setU _ _))->; rewrite disjoints_subset setC_bigcup. case: bigcapsP => [disjA | meetA]; last first. right=> [tI]; case: meetA => B PB; rewrite -disjoints_subset. by rewrite tI ?setU11 ?setU1r //; apply: contraNneq PA => ->. apply: (iffP IHP) => [] tI B C PB PC; last by apply: tI; apply: setU1r. by case/setU1P: PC PB => [->|PC] /setU1P[->|PB]; try by [apply: tI | case/eqP]; first rewrite disjoint_sym; rewrite disjoints_subset disjA. Qed. Lemma trivIsetS P Q : P \subset Q -> trivIset Q -> trivIset P. Proof. by move/subsetP/sub_in2=> sPQ /trivIsetP/sPQ/trivIsetP. Qed. Lemma trivIsetD P Q : trivIset P -> trivIset (P :\: Q). Proof. move/trivIsetP => tP; apply/trivIsetP => A B /setDP[TA _] /setDP[TB _]; exact: tP. Qed. Lemma trivIsetU P Q : trivIset Q -> trivIset P -> [disjoint cover Q & cover P] -> trivIset (Q :|: P). Proof. move => /trivIsetP tQ /trivIsetP tP dQP; apply/trivIsetP => A B. move => /setUP[?|?] /setUP[?|?]; first [exact:tQ|exact:tP|move => _]. by apply: disjointW dQP; rewrite bigcup_sup. by rewrite disjoint_sym; apply: disjointW dQP; rewrite bigcup_sup. Qed. Lemma coverD1 P B : trivIset P -> B \in P -> cover (P :\ B) = cover P :\: B. Proof. move/trivIsetP => tP SP; apply/setP => x; rewrite inE. apply/bigcupP/idP => [[A /setD1P [ADS AP] xA]|/andP[xNS /bigcupP[A AP xA]]]. by rewrite (disjointFr (tP _ _ _ _ ADS)) //=; apply/bigcupP; exists A. by exists A; rewrite // !inE AP andbT; apply: contraNneq xNS => <-. Qed. Lemma trivIsetI P D : trivIset P -> trivIset (P ::&: D). Proof. by apply: trivIsetS; rewrite -setI_powerset subsetIl. Qed. Lemma cover_setI P D : cover (P ::&: D) \subset cover P :&: D. Proof. by apply/bigcupsP=> A /setIdP[PA sAD]; rewrite subsetI sAD andbT (bigcup_max A). Qed. Lemma mem_pblock P x : (x \in pblock P x) = (x \in cover P). Proof. rewrite /pblock; apply/esym/bigcupP. case: pickP => /= [A /andP[PA Ax]| noA]; first by rewrite Ax; exists A. by rewrite inE => [[A PA Ax]]; case/andP: (noA A). Qed. Lemma pblock_mem P x : x \in cover P -> pblock P x \in P. Proof. by rewrite -mem_pblock /pblock; case: pickP => [A /andP[]| _] //=; rewrite inE. Qed. Lemma def_pblock P B x : trivIset P -> B \in P -> x \in B -> pblock P x = B. Proof. move/trivIsetP=> tiP PB Bx; have Px: x \in cover P by apply/bigcupP; exists B. apply: (contraNeq (tiP _ _ _ PB)); first by rewrite pblock_mem. by apply/pred0Pn; exists x; rewrite /= mem_pblock Px. Qed. Lemma same_pblock P x y : trivIset P -> x \in pblock P y -> pblock P x = pblock P y. Proof. rewrite {1 3}/pblock => tI; case: pickP => [A|]; last by rewrite inE. by case/andP=> PA _{y} /= Ax; apply: def_pblock. Qed. Lemma eq_pblock P x y : trivIset P -> x \in cover P -> (pblock P x == pblock P y) = (y \in pblock P x). Proof. move=> tiP Px; apply/eqP/idP=> [eq_xy | /same_pblock-> //]. move: Px; rewrite -mem_pblock eq_xy /pblock. by case: pickP => [B /andP[] // | _] /[1!inE]. Qed. Lemma trivIsetU1 A P : {in P, forall B, [disjoint A & B]} -> trivIset P -> set0 \notin P -> trivIset (A |: P) /\ A \notin P. Proof. move=> tiAP tiP notPset0; split; last first. apply: contra notPset0 => P_A. by have:= tiAP A P_A; rewrite -setI_eq0 setIid => /eqP <-. apply/trivIsetP=> B1 B2 /setU1P[->|PB1] /setU1P[->|PB2]; by [apply: (trivIsetP _ tiP) | rewrite ?eqxx // ?(tiAP, disjoint_sym)]. Qed. Lemma cover_imset J F : cover (F @: J) = \bigcup_(i in J) F i. Proof. apply/setP=> x. apply/bigcupP/bigcupP=> [[_ /imsetP[i Ji ->]] | [i]]; first by exists i. by exists (F i); first apply: imset_f. Qed. Lemma trivIimset J F (P := F @: J) : {in J &, forall i j, j != i -> [disjoint F i & F j]} -> set0 \notin P -> trivIset P /\ {in J &, injective F}. Proof. move=> tiF notPset0; split=> [|i j Ji Jj /= eqFij]. apply/trivIsetP=> _ _ /imsetP[i Ji ->] /imsetP[j Jj ->] neqFij. by rewrite tiF // (contraNneq _ neqFij) // => ->. apply: contraNeq notPset0 => neq_ij; apply/imsetP; exists i => //; apply/eqP. by rewrite eq_sym -[F i]setIid setI_eq0 {1}eqFij tiF. Qed. Lemma cover_partition P D : partition P D -> cover P = D. Proof. by case/and3P=> /eqP. Qed. Lemma partition0 P D : partition P D -> set0 \in P = false. Proof. case/and3P => _ _. by apply: contraNF. Qed. Lemma partition_neq0 P D B : partition P D -> B \in P -> B != set0. Proof. by move=> partP; apply: contraTneq => ->; rewrite (partition0 partP). Qed. Lemma partition_trivIset P D : partition P D -> trivIset P. Proof. by case/and3P. Qed. Lemma partitionS P D B : partition P D -> B \in P -> B \subset D. Proof. by move=> partP BP; rewrite -(cover_partition partP); apply: bigcup_max BP _. Qed. Lemma partitionD1 P D B : partition P D -> B \in P -> partition (P :\ B) (D :\: B). Proof. case/and3P => /eqP covP trivP set0P SP. by rewrite /partition inE (negbTE set0P) trivIsetD ?coverD1 -?covP ?eqxx ?andbF. Qed. Lemma partitionU1 P D B : partition P D -> B != set0 -> [disjoint B & D] -> partition (B |: P) (B :|: D). Proof. case/and3P => /eqP covP trivP set0P BD0 disSD. rewrite /partition !inE (negbTE set0P) orbF [_ == B]eq_sym BD0 andbT. rewrite /cover bigcup_setU /= big_set1 -covP eqxx /=. by move: disSD; rewrite -covP=> /bigcup_disjointP/trivIsetU1 => -[]. Qed. Lemma partition_set0 P : partition P set0 = (P == set0). Proof. apply/and3P/eqP => [[/bigcup0P covP _ ]|->]; last first. by rewrite /partition inE /trivIset/cover !big_set0 cards0 !eqxx. by apply: contraNeq => /set0Pn[B BP]; rewrite -(covP B BP). Qed. Lemma card_partition P D : partition P D -> #|D| = \sum_(A in P) #|A|. Proof. by case/and3P=> /eqP <- /eqnP. Qed. Lemma card_uniform_partition n P D : {in P, forall A, #|A| = n} -> partition P D -> #|D| = #|P| * n. Proof. by move=> uniP /card_partition->; rewrite -sum_nat_const; apply: eq_bigr. Qed. Lemma partition_pigeonhole P D A : partition P D -> #|P| <= #|A| -> A \subset D -> {in P, forall B, #|A :&: B| <= 1} -> {in P, forall B, A :&: B != set0}. Proof. move=> partP card_A_P /subsetP subAD sub1; apply/forall_inP. apply: contraTT card_A_P => /forall_inPn [B BP]; rewrite negbK => AB0. rewrite -!ltnNge -(setD1K BP) cardsU1 !inE eqxx /= add1n ltnS. have [tP covP] := (partition_trivIset partP,cover_partition partP). have APx x : x \in A -> x \in pblock P x by rewrite mem_pblock covP; apply: subAD. have inj_f : {in A &, injective (pblock P)}. move=> x y xA yA /eqP; rewrite eq_pblock ?covP ?subAD // => Pxy. apply: (@card_le1_eqP _ (A :&: pblock P x)); rewrite ?inE ?Pxy ?APx ?andbT //. by apply: sub1; rewrite pblock_mem ?covP ?subAD. rewrite -(card_in_imset inj_f); apply: subset_leq_card. apply/subsetP => ? /imsetP[x xA ->]. rewrite !inE pblock_mem ?covP ?subAD ?andbT //. by apply: contraTneq AB0 => <-; apply/set0Pn; exists x; rewrite inE APx ?andbT. Qed. Section BigOps. Variables (R : Type) (idx : R) (op : Monoid.com_law idx). Let rhs_cond P K E := \big[op/idx]_(A in P) \big[op/idx]_(x in A | K x) E x. Let rhs P E := \big[op/idx]_(A in P) \big[op/idx]_(x in A) E x. Lemma big_trivIset_cond P (K : pred T) (E : T -> R) : trivIset P -> \big[op/idx]_(x in cover P | K x) E x = rhs_cond P K E. Proof. move=> tiP; rewrite (partition_big (pblock P) [in P]) -/op => /= [|x]. apply: eq_bigr => A PA; apply: eq_bigl => x; rewrite andbAC; congr (_ && _). rewrite -mem_pblock; apply/andP/idP=> [[Px /eqP <- //] | Ax]. by rewrite (def_pblock tiP PA Ax). by case/andP=> Px _; apply: pblock_mem. Qed. Lemma big_trivIset P (E : T -> R) : trivIset P -> \big[op/idx]_(x in cover P) E x = rhs P E. Proof. have biginT := eq_bigl _ _ (fun _ => andbT _) => tiP. by rewrite -biginT big_trivIset_cond //; apply: eq_bigr => A _; apply: biginT. Qed. Lemma set_partition_big_cond P D (K : pred T) (E : T -> R) : partition P D -> \big[op/idx]_(x in D | K x) E x = rhs_cond P K E. Proof. by case/and3P=> /eqP <- tI_P _; apply: big_trivIset_cond. Qed. Lemma set_partition_big P D (E : T -> R) : partition P D -> \big[op/idx]_(x in D) E x = rhs P E. Proof. by case/and3P=> /eqP <- tI_P _; apply: big_trivIset. Qed. Lemma partition_disjoint_bigcup (F : I -> {set T}) E : (forall i j, i != j -> [disjoint F i & F j]) -> \big[op/idx]_(x in \bigcup_i F i) E x = \big[op/idx]_i \big[op/idx]_(x in F i) E x. Proof. move=> disjF; pose P := [set F i | i in I & F i != set0]. have trivP: trivIset P. apply/trivIsetP=> _ _ /imsetP[i _ ->] /imsetP[j _ ->] neqFij. by apply: disjF; apply: contraNneq neqFij => ->. have ->: \bigcup_i F i = cover P. apply/esym; rewrite cover_imset big_mkcond; apply: eq_bigr => i _. by rewrite inE; case: eqP. rewrite big_trivIset // /rhs big_imset => [|i j _ /setIdP[_ notFj0] eqFij]. rewrite big_mkcond; apply: eq_bigr => i _; rewrite inE. by case: eqP => //= ->; rewrite big_set0. by apply: contraNeq (disjF _ _) _; rewrite -setI_eq0 eqFij setIid. Qed. End BigOps. Section Equivalence. Variables (R : rel T) (D : {set T}). Let Px x := [set y in D | R x y]. Definition equivalence_partition := [set Px x | x in D]. Local Notation P := equivalence_partition. Hypothesis eqiR : {in D & &, equivalence_rel R}. Let Pxx x : x \in D -> x \in Px x. Proof. by move=> Dx; rewrite !inE Dx (eqiR Dx Dx). Qed. Let PPx x : x \in D -> Px x \in P := fun Dx => imset_f _ Dx. Lemma equivalence_partitionP : partition P D. Proof. have defD: cover P == D. rewrite eqEsubset; apply/andP; split. by apply/bigcupsP=> _ /imsetP[x Dx ->]; rewrite /Px setIdE subsetIl. by apply/subsetP=> x Dx; apply/bigcupP; exists (Px x); rewrite (Pxx, PPx). have tiP: trivIset P. apply/trivIsetP=> _ _ /imsetP[x Dx ->] /imsetP[y Dy ->]; apply: contraR. case/pred0Pn=> z /andP[] /[!inE] /andP[Dz Rxz] /andP[_ Ryz]. apply/eqP/setP=> t /[!inE]; apply: andb_id2l => Dt. by rewrite (eqiR Dx Dz Dt) // (eqiR Dy Dz Dt). rewrite /partition tiP defD /=. by apply/imsetP=> [[x /Pxx Px_x Px0]]; rewrite -Px0 inE in Px_x. Qed. Lemma pblock_equivalence_partition : {in D &, forall x y, (y \in pblock P x) = R x y}. Proof. have [_ tiP _] := and3P equivalence_partitionP. by move=> x y Dx Dy; rewrite /= (def_pblock tiP (PPx Dx) (Pxx Dx)) inE Dy. Qed. End Equivalence. Lemma pblock_equivalence P D : partition P D -> {in D & &, equivalence_rel (fun x y => y \in pblock P x)}. Proof. case/and3P=> /eqP <- tiP _ x y z Px Py Pz. by rewrite mem_pblock; split=> // /same_pblock->. Qed. Lemma equivalence_partition_pblock P D : partition P D -> equivalence_partition (fun x y => y \in pblock P x) D = P. Proof. case/and3P=> /eqP <-{D} tiP notP0; apply/setP=> B /=; set D := cover P. have defP x: x \in D -> [set y in D | y \in pblock P x] = pblock P x. by move=> Dx; apply/setIidPr; rewrite (bigcup_max (pblock P x)) ?pblock_mem. apply/imsetP/idP=> [[x Px ->{B}] | PB]; first by rewrite defP ?pblock_mem. have /set0Pn[x Bx]: B != set0 := memPn notP0 B PB. have Px: x \in cover P by apply/bigcupP; exists B. by exists x; rewrite // defP // (def_pblock tiP PB Bx). Qed. Section Preim. Variables (rT : eqType) (f : T -> rT). Definition preim_partition := equivalence_partition (fun x y => f x == f y). Lemma preim_partitionP D : partition (preim_partition D) D. Proof. by apply/equivalence_partitionP; split=> // /eqP->. Qed. End Preim. Lemma preim_partition_pblock P D : partition P D -> preim_partition (pblock P) D = P. Proof. move=> partP; have [/eqP defD tiP _] := and3P partP. rewrite -{2}(equivalence_partition_pblock partP); apply: eq_in_imset => x Dx. by apply/setP=> y; rewrite !inE eq_pblock ?defD. Qed. Lemma transversalP P D : partition P D -> is_transversal (transversal P D) P D. Proof. case/and3P=> /eqP <- tiP notP0; apply/and3P; split; first exact/and3P. apply/subsetP=> _ /imsetP[x Px ->]; case: pickP => //= y Pxy. by apply/bigcupP; exists (pblock P x); rewrite ?pblock_mem //. apply/forall_inP=> B PB; have /set0Pn[x Bx]: B != set0 := memPn notP0 B PB. apply/cards1P; exists (odflt x [pick y in pblock P x]); apply/esym/eqP. rewrite eqEsubset sub1set !inE -andbA; apply/andP; split. by apply/imset_f/bigcupP; exists B. rewrite (def_pblock tiP PB Bx); case def_y: _ / pickP => [y By | /(_ x)/idP//]. rewrite By /=; apply/subsetP=> _ /setIP[/imsetP[z Pz ->]]. case: {1}_ / pickP => [t zPt Bt | /(_ z)/idP[]]; last by rewrite mem_pblock. by rewrite -(same_pblock tiP zPt) (def_pblock tiP PB Bt) def_y inE. Qed. Section Transversals. Variables (X : {set T}) (P : {set {set T}}) (D : {set T}). Hypothesis trPX : is_transversal X P D. Lemma transversal_sub : X \subset D. Proof. by case/and3P: trPX. Qed. Let tiP : trivIset P. Proof. by case/andP: trPX => /and3P[]. Qed. Let sXP : {subset X <= cover P}. Proof. by case/and3P: trPX => /andP[/eqP-> _] /subsetP. Qed. Let trX : {in P, forall B, #|X :&: B| == 1}. Proof. by case/and3P: trPX => _ _ /forall_inP. Qed. Lemma setI_transversal_pblock x0 B : B \in P -> X :&: B = [set transversal_repr x0 X B]. Proof. by case/trX/cards1P=> x defXB; rewrite /transversal_repr defXB /pick enum_set1. Qed. Lemma repr_mem_pblock x0 B : B \in P -> transversal_repr x0 X B \in B. Proof. by move=> PB; rewrite -sub1set -setI_transversal_pblock ?subsetIr. Qed. Lemma repr_mem_transversal x0 B : B \in P -> transversal_repr x0 X B \in X. Proof. by move=> PB; rewrite -sub1set -setI_transversal_pblock ?subsetIl. Qed. Lemma transversal_reprK x0 : {in P, cancel (transversal_repr x0 X) (pblock P)}. Proof. by move=> B PB; rewrite /= (def_pblock tiP PB) ?repr_mem_pblock. Qed. Lemma pblockK x0 : {in X, cancel (pblock P) (transversal_repr x0 X)}. Proof. move=> x Xx; have /bigcupP[B PB Bx] := sXP Xx; rewrite (def_pblock tiP PB Bx). by apply/esym/set1P; rewrite -setI_transversal_pblock // inE Xx. Qed. Lemma pblock_inj : {in X &, injective (pblock P)}. Proof. by move=> x0; apply: (can_in_inj (pblockK x0)). Qed. Lemma pblock_transversal : pblock P @: X = P. Proof. apply/setP=> B; apply/imsetP/idP=> [[x Xx ->] | PB]. by rewrite pblock_mem ?sXP. have /cards1P[x0 _] := trX PB; set x := transversal_repr x0 X B. by exists x; rewrite ?transversal_reprK ?repr_mem_transversal. Qed. Lemma card_transversal : #|X| = #|P|. Proof. by rewrite -pblock_transversal card_in_imset //; apply: pblock_inj. Qed. Lemma im_transversal_repr x0 : transversal_repr x0 X @: P = X. Proof. rewrite -{2}[X]imset_id -pblock_transversal -imset_comp. by apply: eq_in_imset; apply: pblockK. Qed. End Transversals. End Partitions. Arguments trivIsetP {T P}. Arguments big_trivIset_cond [T R idx op] P [K E]. Arguments set_partition_big_cond [T R idx op] P [D K E]. Arguments big_trivIset [T R idx op] P [E]. Arguments set_partition_big [T R idx op] P [D E]. Prenex Implicits cover trivIset partition pblock. Lemma partition_partition (T : finType) (D : {set T}) P Q : partition P D -> partition Q P -> partition (cover @: Q) D /\ {in Q &, injective cover}. Proof. move=> /and3P[/eqP defG tiP notP0] /and3P[/eqP defP tiQ notQ0]. have sQP E: E \in Q -> {subset E <= P}. by move=> Q_E; apply/subsetP; rewrite -defP (bigcup_max E). rewrite /partition cover_imset -(big_trivIset _ tiQ) defP -defG eqxx /= andbC. have{} notQ0: set0 \notin cover @: Q. apply: contra notP0 => /imsetP[E Q_E E0]. have /set0Pn[/= A E_A] := memPn notQ0 E Q_E. congr (_ \in P): (sQP E Q_E A E_A). by apply/eqP; rewrite -subset0 E0 (bigcup_max A). rewrite notQ0; apply: trivIimset => // E F Q_E Q_F. apply: contraR => /pred0Pn[x /andP[/bigcupP[A E_A Ax] /bigcupP[B F_B Bx]]]. rewrite -(def_pblock tiQ Q_E E_A) -(def_pblock tiP _ Ax) ?(sQP E) //. by rewrite -(def_pblock tiQ Q_F F_B) -(def_pblock tiP _ Bx) ?(sQP F). Qed. Lemma indexed_partition (I T : finType) (J : {pred I}) (B : I -> {set T}) : let P := [set B i | i in J] in {in J &, forall i j : I, j != i -> [disjoint B i & B j]} -> (forall i : I, J i -> B i != set0) -> partition P (cover P) /\ {in J &, injective B}. Proof. move=> P disjB inhB; have s0NP : set0 \notin P. by apply/negP => /imsetP[x xI /eqP]; apply/negP; rewrite eq_sym inhB. by rewrite /partition eqxx s0NP andbT /=; apply: trivIimset. Qed. Section PartitionImage. Variables (T : finType) (P : {set {set T}}) (D : {set T}). Variables (T' : finType) (f : T -> T') (inj_f : injective f). Let fP := [set f @: (B : {set T}) | B in P]. Lemma imset_trivIset : trivIset fP = trivIset P. Proof. apply/trivIsetP/trivIsetP => [trivP A B AP BP|]. - rewrite -(imset_disjoint inj_f) -(inj_eq (imset_inj inj_f)). by apply: trivP; rewrite imset_f. - move=> trivP ? ? /imsetP[A AP ->] /imsetP[B BP ->]. by rewrite (inj_eq (imset_inj inj_f)) imset_disjoint //; apply: trivP. Qed. Lemma imset0mem : (set0 \in fP) = (set0 \in P). Proof. apply/imsetP/idP => [[A AP /esym/eqP]|P0]; last by exists set0; rewrite ?imset0. by rewrite imset_eq0 => /eqP<-. Qed. Lemma imset_partition : partition fP (f @: D) = partition P D. Proof. suff cov: (cover fP == f @:D) = (cover P == D). by rewrite /partition -imset_trivIset imset0mem cov. by rewrite /fP cover_imset -imset_cover (inj_eq (imset_inj inj_f)). Qed. End PartitionImage. (**********************************************************************) (* *) (* Maximum and minimum (sub)set with respect to a given pred *) (* *) (**********************************************************************) Section MaxSetMinSet. Variable T : finType. Notation sT := {set T}. Implicit Types A B C : sT. Implicit Type P : pred sT. Definition minset P A := [forall (B : sT | B \subset A), (B == A) == P B]. Lemma minset_eq P1 P2 A : P1 =1 P2 -> minset P1 A = minset P2 A. Proof. by move=> eP12; apply: eq_forallb => B; rewrite eP12. Qed. Lemma minsetP P A : reflect ((P A) /\ (forall B, P B -> B \subset A -> B = A)) (minset P A). Proof. apply: (iffP forallP) => [minA | [PA minA] B]. split; first by have:= minA A; rewrite subxx eqxx /= => /eqP. by move=> B PB sBA; have:= minA B; rewrite PB sBA /= eqb_id => /eqP. by apply/implyP=> sBA; apply/eqP; apply/eqP/idP=> [-> // | /minA]; apply. Qed. Arguments minsetP {P A}. Lemma minsetp P A : minset P A -> P A. Proof. by case/minsetP. Qed. Lemma minsetinf P A B : minset P A -> P B -> B \subset A -> B = A. Proof. by case/minsetP=> _; apply. Qed. Lemma ex_minset P : (exists A, P A) -> {A | minset P A}. Proof. move=> exP; pose pS n := [pred B | P B & #|B| == n]. pose p n := ~~ pred0b (pS n); have{exP}: exists n, p n. by case: exP => A PA; exists #|A|; apply/existsP; exists A; rewrite /= PA /=. case/ex_minnP=> n /pred0P; case: (pickP (pS n)) => // A /andP[PA] /eqP <-{n} _. move=> minA; exists A => //; apply/minsetP; split=> // B PB sBA; apply/eqP. by rewrite eqEcard sBA minA //; apply/pred0Pn; exists B; rewrite /= PB /=. Qed. Lemma minset_exists P C : P C -> {A | minset P A & A \subset C}. Proof. move=> PC; have{PC}: exists A, P A && (A \subset C) by exists C; rewrite PC /=. case/ex_minset=> A /minsetP[/andP[PA sAC] minA]; exists A => //; apply/minsetP. by split=> // B PB sBA; rewrite (minA B) // PB (subset_trans sBA). Qed. (* The 'locked_with' allows Coq to find the value of P by unification. *) Fact maxset_key : unit. Proof. by []. Qed. Definition maxset P A := minset (fun B => locked_with maxset_key P (~: B)) (~: A). Lemma maxset_eq P1 P2 A : P1 =1 P2 -> maxset P1 A = maxset P2 A. Proof. by move=> eP12; apply: minset_eq => x /=; rewrite !unlock_with eP12. Qed. Lemma maxminset P A : maxset P A = minset [pred B | P (~: B)] (~: A). Proof. by rewrite /maxset unlock. Qed. Lemma minmaxset P A : minset P A = maxset [pred B | P (~: B)] (~: A). Proof. by rewrite /maxset unlock setCK; apply: minset_eq => B /=; rewrite setCK. Qed. Lemma maxsetP P A : reflect ((P A) /\ (forall B, P B -> A \subset B -> B = A)) (maxset P A). Proof. apply: (iffP minsetP); rewrite ?setCK unlock_with => [] [PA minA]. by split=> // B PB sAB; rewrite -[B]setCK [~: B]minA (setCK, setCS). by split=> // B PB' sBA'; rewrite -(minA _ PB') -1?setCS setCK. Qed. Lemma maxsetp P A : maxset P A -> P A. Proof. by case/maxsetP. Qed. Lemma maxsetsup P A B : maxset P A -> P B -> A \subset B -> B = A. Proof. by case/maxsetP=> _; apply. Qed. Lemma ex_maxset P : (exists A, P A) -> {A | maxset P A}. Proof. move=> exP; have{exP}: exists A, P (~: A). by case: exP => A PA; exists (~: A); rewrite setCK. by case/ex_minset=> A minA; exists (~: A); rewrite /maxset unlock setCK. Qed. Lemma maxset_exists P C : P C -> {A : sT | maxset P A & C \subset A}. Proof. move=> PC; pose P' B := P (~: B); have: P' (~: C) by rewrite /P' setCK. case/minset_exists=> B; rewrite -[B]setCK setCS. by exists (~: B); rewrite // /maxset unlock. Qed. End MaxSetMinSet. Arguments setCK {T}. Arguments minsetP {T P A}. Arguments maxsetP {T P A}. Prenex Implicits minset maxset. Section SetFixpoint. Section Least. Variables (T : finType) (F : {set T} -> {set T}). Hypothesis (F_mono : {homo F : X Y / X \subset Y}). Let n := #|T|. Let iterF i := iter i F set0. Lemma subset_iterS i : iterF i \subset iterF i.+1. Proof. by elim: i => [| i IHi]; rewrite /= ?sub0set ?F_mono. Qed. Lemma subset_iter : {homo iterF : i j / i <= j >-> i \subset j}. Proof. by apply: homo_leq => //[? ? ?|]; [apply: subset_trans|apply: subset_iterS]. Qed. Definition fixset := iterF n. Lemma fixsetK : F fixset = fixset. Proof. suff /'exists_eqP[x /= e]: [exists k : 'I_n.+1, iterF k == iterF k.+1]. by rewrite /fixset -(subnK (leq_ord x)) /iterF iterD iter_fix. apply: contraT => /existsPn /(_ (Ordinal _)) /= neq_iter. suff iter_big k : k <= n.+1 -> k <= #|iter k F set0|. by have := iter_big _ (leqnn _); rewrite ltnNge max_card. elim: k => [|k IHk] k_lt //=; apply: (leq_ltn_trans (IHk (ltnW k_lt))). by rewrite proper_card// properEneq// subset_iterS neq_iter. Qed. Hint Resolve fixsetK : core. Lemma minset_fix : minset [pred X | F X == X] fixset. Proof. apply/minsetP; rewrite inE fixsetK eqxx; split=> // X /eqP FXeqX Xsubfix. apply/eqP; rewrite eqEsubset Xsubfix/=. suff: fixset \subset iter n F X by rewrite iter_fix. by rewrite /fixset; elim: n => //= [|m IHm]; rewrite ?sub0set ?F_mono. Qed. Lemma fixsetKn k : iter k F fixset = fixset. Proof. by rewrite iter_fix. Qed. Lemma iter_sub_fix k : iterF k \subset fixset. Proof. have [/subset_iter //|/ltnW/subnK<-] := leqP k n; by rewrite /iterF iterD fixsetKn. Qed. Lemma fix_order_proof x : x \in fixset -> exists n, x \in iterF n. Proof. by move=> x_fix; exists n. Qed. Definition fix_order (x : T) := if (x \in fixset) =P true isn't ReflectT x_fix then 0 else (ex_minn (fix_order_proof x_fix)). Lemma fix_order_le_max (x : T) : fix_order x <= n. Proof. rewrite /fix_order; case: eqP => //= x_in. by case: ex_minnP => //= ? ?; apply. Qed. Lemma in_iter_fix_orderE (x : T) : (x \in iterF (fix_order x)) = (x \in fixset). Proof. rewrite /fix_order; case: eqP => [x_in | /negP/negPf-> /[1!inE]//]. by case: ex_minnP => m ->; rewrite x_in. Qed. Lemma fix_order_gt0 (x : T) : (fix_order x > 0) = (x \in fixset). Proof. rewrite /fix_order; case: eqP => [x_in | /negP/negPf->//]. by rewrite x_in; case: ex_minnP => -[/[!inE] | m]. Qed. Lemma fix_order_eq0 (x : T) : (fix_order x == 0) = (x \notin fixset). Proof. by rewrite -fix_order_gt0 -ltnNge ltnS leqn0. Qed. Lemma in_iter_fixE (x : T) k : (x \in iterF k) = (0 < fix_order x <= k). Proof. rewrite /fix_order; case: eqP => //= [x_in|/negP xNin]; last first. by apply: contraNF xNin; apply/subsetP/iter_sub_fix. case: ex_minnP => -[/[!inE]//|m] xm mP. by apply/idP/idP=> [/mP//|lt_mk]; apply: subsetP xm; apply: subset_iter. Qed. Lemma in_iter (x : T) k : x \in fixset -> fix_order x <= k -> x \in iterF k. Proof. by move=> x_in xk; rewrite in_iter_fixE fix_order_gt0 x_in xk. Qed. Lemma notin_iter (x : T) k : k < fix_order x -> x \notin iterF k. Proof. by move=> k_le; rewrite in_iter_fixE negb_and orbC -ltnNge k_le. Qed. Lemma fix_order_small x k : x \in iterF k -> fix_order x <= k. Proof. by rewrite in_iter_fixE => /andP[]. Qed. Lemma fix_order_big x k : x \in fixset -> x \notin iterF k -> fix_order x > k. Proof. by move=> x_in; rewrite in_iter_fixE fix_order_gt0 x_in /= -ltnNge. Qed. Lemma le_fix_order (x y : T) : y \in iterF (fix_order x) -> fix_order y <= fix_order x. Proof. exact: fix_order_small. Qed. End Least. Section Greatest. Variables (T : finType) (F : {set T} -> {set T}). Hypothesis (F_mono : {homo F : X Y / X \subset Y}). Definition funsetC X := ~: (F (~: X)). Lemma funsetC_mono : {homo funsetC : X Y / X \subset Y}. Proof. by move=> *; rewrite subCset setCK F_mono// subCset setCK. Qed. Hint Resolve funsetC_mono : core. Definition cofixset := ~: fixset funsetC. Lemma cofixsetK : F cofixset = cofixset. Proof. by rewrite /cofixset -[in RHS]fixsetK ?setCK. Qed. Lemma maxset_cofix : maxset [pred X | F X == X] cofixset. Proof. rewrite maxminset setCK. rewrite (@minset_eq _ _ [pred X | funsetC X == X]) ?minset_fix//. by move=> X /=; rewrite (can2_eq setCK setCK). Qed. End Greatest. End SetFixpoint. Section FProd. Variables (I : finType) (T_ : I -> finType). Lemma card_fprod : #|fprod T_| = \prod_(i : I) #|T_ i|. Proof. rewrite card_sub (card_family (tagged_with T_)) foldrE big_image/=. apply: eq_bigr => i _/=; rewrite -card_sig; apply/esym. exact: bij_eq_card (tag_with_bij T_ i). Qed. Definition fprod_pick : 0 < #|fprod T_| -> forall i : I, T_ i. Proof. by rewrite card_fprod => /[swap] i /gt0_prodn/(_ i isT) /card_gt0P/sigW[]. Qed. Definition ftagged (T_gt0 : 0 < #|fprod T_|) (f : {ffun I -> {i : I & T_ i}}) (i : I) := @untag I T_ (T_ i) (fprod_pick T_gt0 i) i id (f i). Lemma ftaggedE t T_gt0 i : ftagged T_gt0 (fprod_fun t) i = t i. Proof. by rewrite /ftagged untagE ?tag_fprod_fun// => e; rewrite etaggedE. Qed. End FProd. Section BigTag. Variables (R : Type) (idx : R) (op : Monoid.com_law idx). Variables (I : finType) (T_ : I -> finType). Lemma big_tag_cond (Q_ : forall i, {pred T_ i}) (P_ : forall i : I, T_ i -> R) (i : I) : \big[op/idx]_(j in Q_ i) P_ i j = \big[op/idx]_(j in tagged_with T_ i | untag true (Q_ i) j) untag idx (P_ i) j. Proof. rewrite (big_sub_cond (tagged_with T_ i)). rewrite (reindex (tag_with i)); last exact/onW_bij/tag_with_bij. by apply: eq_big => [x|x Qix]; rewrite ?untagE. Qed. Lemma big_tag (P_ : forall i : I, T_ i -> R) (i : I) : \big[op/idx]_(j : T_ i) P_ i j = \big[op/idx]_(j in tagged_with T_ i) untag idx (P_ i) j. Proof. by rewrite big_tag_cond; under eq_bigl do rewrite untag_cst ?andbT. Qed. End BigTag. Arguments big_tag_cond [R idx op I T_] _ _ _. Arguments big_tag [R idx op I T_] _ _. Section BigFProd. Variables (R : Type) (zero one : R) (times : R -> R -> R). Variables (plus : Monoid.add_law zero times). Variables (I : finType) (T_ : I -> finType). Variables (P_ : forall i : I, {ffun T_ i -> R}). Let T := fprod T_. Lemma big_fprod_dep (Q : {pred {ffun I -> {i : I & (T_ i)}}}) : \big[plus/zero]_(t : T | Q (fprod_fun t)) \big[times/one]_(i : I) P_ i (t i) = \big[plus/zero]_(g in family (tagged_with T_) | Q g) \big[times/one]_(i : I) (untag zero (P_ i) (g i)). Proof. rewrite (reindex (@of_family_tagged_with _ T_)); last first. exact/onW_bij/of_family_tagged_with_bij. rewrite [in RHS]big_sub_cond; apply/esym/eq_bigr => -[/= f fP] Qf. apply: eq_bigr => i _; rewrite /fun_of_fprod/=. by case: (f i) ('forall_eqP _ _) => //= j t; case: _ /; rewrite untagE. Qed. Lemma big_fprod : \big[plus/zero]_(t : T) \big[times/one]_(i in I) P_ i (t i) = \big[plus/zero]_(g in family (tagged_with T_)) \big[times/one]_(i : I) (untag zero (P_ i) (g i)). Proof. by rewrite (big_fprod_dep predT) big_mkcondr. Qed. End BigFProd.
mxred.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 div. From mathcomp Require Import choice fintype finfun bigop fingroup perm order. From mathcomp Require Import ssralg zmodp matrix mxalgebra poly polydiv mxpoly. (*****************************************************************************) (* In this file, we prove diagonalization theorems. For this purpose, we *) (* define conjugation, similarity and diagonalizability. *) (* *) (* conjmx V f := V *m f *m pinvmx V *) (* == the conjugation of f by V, i.e. "the" matrix of f *) (* in the basis of row vectors of V. *) (* Although this makes sense only when f stabilizes V, *) (* the definition can be stated more generally. *) (* similar_to P A C == where P is a base change matrix, A is a matrix, *) (* and C is a class of matrices, *) (* this states that conjmx P A is in C, *) (* which means A is similar to a matrix in C. *) (* *) (* From the latter, we derive serveral related notions: *) (* similar P A B := similar_to P A (pred1 B) *) (* == A is similar to B, with base change matrix P *) (* similar_in D A B == A is similar to B, *) (* with a base change matrix in D *) (* similar_in_to D A C == A is similar to a matrix in the class C, *) (* with a base change matrix in D *) (* all_similar_to D As C == all the matrices in the sequence As are similar *) (* to some matrix in the class C, *) (* with a base change matrix in D. *) (* *) (* We also specialize the class C, to diagonalizability: *) (* similar_diag P A := (similar_to P A is_diag_mx). *) (* diagonalizable_in D A := (similar_in_to D A is_diag_mx). *) (* diagonalizable A := (diagonalizable_in unitmx A). *) (* codiagonalizable_in D As := (all_similar_to D As is_diag_mx). *) (* codiagonalizable As := (codiagonalizable_in unitmx As). *) (* *) (* The main results of this file are: *) (* diagonalizablePeigen: *) (* a matrix is diagonalizable iff there is a sequence *) (* of scalars r, such that the sum of the associated *) (* eigenspaces is full. *) (* diagonalizableP: *) (* a matrix is diagonalizable iff its minimal polynomial *) (* divides a split polynomial with simple roots. *) (* codiagonalizableP: *) (* a sequence of matrices are diagonalizable in the same basis *) (* iff they are all diagonalizable and commute pairwize. *) (* *) (* We also specialize the class C, to trigonalizablility: *) (* similar_trig P A := (similar_to P A is_trig_mx). *) (* trigonalizable_in D A := (similar_in_to D A is_trig_mx). *) (* trigonalizable A := (trigonalizable_in unitmx A). *) (* cotrigonalizable_in D As := (all_similar_to D As is_trig_mx). *) (* cotrigonalizable As := (cotrigonalizable_in unitmx As). *) (* The theory of trigonalization is however not developed in this file. *) (*****************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory. Import Monoid.Theory. Local Open Scope ring_scope. Section ConjMx. Context {F : fieldType}. Definition conjmx (m n : nat) (V : 'M_(m, n)) (f : 'M[F]_n) : 'M_m := V *m f *m pinvmx V. Notation restrictmx V := (conjmx (row_base V)). Lemma stablemx_comp (m n p : nat) (V : 'M[F]_(m, n)) (W : 'M_(n, p)) (f : 'M_p) : stablemx W f -> stablemx V (conjmx W f) -> stablemx (V *m W) f. Proof. by move=> Wf /(submxMr W); rewrite -mulmxA mulmxKpV// mulmxA. Qed. Lemma stablemx_restrict m n (A : 'M[F]_n) (V : 'M_n) (W : 'M_(m, \rank V)): stablemx V A -> stablemx W (restrictmx V A) = stablemx (W *m row_base V) A. Proof. move=> A_stabV; rewrite mulmxA -[in RHS]mulmxA. rewrite -(submxMfree _ W (row_base_free V)) mulmxKpV //. by rewrite mulmx_sub ?stablemx_row_base. Qed. Lemma conjmxM (m n : nat) (V : 'M[F]_(m, n)) : {in [pred f | stablemx V f] &, {morph conjmx V : f g / f *m g}}. Proof. move=> f g; rewrite !inE => Vf Vg /=. by rewrite /conjmx 2!mulmxA mulmxA mulmxKpV ?stablemx_row_base. Qed. Lemma conjMmx (m n p : nat) (V : 'M[F]_(m, n)) (W : 'M_(n, p)) (f : 'M_p) : row_free (V *m W) -> stablemx W f -> stablemx V (conjmx W f) -> conjmx (V *m W) f = conjmx V (conjmx W f). Proof. move=> rfVW Wf VWf; apply: (row_free_inj rfVW); rewrite mulmxKpV ?stablemx_comp//. by rewrite mulmxA mulmxKpV// -[RHS]mulmxA mulmxKpV ?mulmxA. Qed. Lemma conjuMmx (m n : nat) (V : 'M[F]_m) (W : 'M_(m, n)) (f : 'M_n) : V \in unitmx -> row_free W -> stablemx W f -> conjmx (V *m W) f = conjmx V (conjmx W f). Proof. move=> Vu rfW Wf; rewrite conjMmx ?stablemx_unit//. by rewrite /row_free mxrankMfree// -/(row_free V) row_free_unit. Qed. Lemma conjMumx (m n : nat) (V : 'M[F]_(m, n)) (W f : 'M_n) : W \in unitmx -> row_free V -> stablemx V (conjmx W f) -> conjmx (V *m W) f = conjmx V (conjmx W f). Proof. move=> Wu rfW Wf; rewrite conjMmx ?stablemx_unit//. by rewrite /row_free mxrankMfree ?row_free_unit. Qed. Lemma conjuMumx (n : nat) (V W f : 'M[F]_n) : V \in unitmx -> W \in unitmx -> conjmx (V *m W) f = conjmx V (conjmx W f). Proof. by move=> Vu Wu; rewrite conjuMmx ?stablemx_unit ?row_free_unit. Qed. Lemma conjmx_scalar (m n : nat) (V : 'M[F]_(m, n)) (a : F) : row_free V -> conjmx V a%:M = a%:M. Proof. by move=> rfV; rewrite /conjmx scalar_mxC mulmxKp. Qed. Lemma conj0mx (m n : nat) f : conjmx (0 : 'M[F]_(m, n)) f = 0. Proof. by rewrite /conjmx !mul0mx. Qed. Lemma conjmx0 (m n : nat) (V : 'M[F]_(m, n)) : conjmx V 0 = 0. Proof. by rewrite /conjmx mulmx0 mul0mx. Qed. Lemma conjumx (n : nat) (V : 'M_n) (f : 'M[F]_n) : V \in unitmx -> conjmx V f = V *m f *m invmx V. Proof. by move=> uV; rewrite /conjmx pinvmxE. Qed. Lemma conj1mx (n : nat) (f : 'M[F]_n) : conjmx 1%:M f = f. Proof. by rewrite conjumx ?unitmx1// invmx1 mulmx1 mul1mx. Qed. Lemma conjVmx (n : nat) (V : 'M_n) (f : 'M[F]_n) : V \in unitmx -> conjmx (invmx V) f = invmx V *m f *m V. Proof. by move=> Vunit; rewrite conjumx ?invmxK ?unitmx_inv. Qed. Lemma conjmxK (n : nat) (V f : 'M[F]_n) : V \in unitmx -> conjmx (invmx V) (conjmx V f) = f. Proof. by move=> Vu; rewrite -conjuMumx ?unitmx_inv// mulVmx ?conj1mx. Qed. Lemma conjmxVK (n : nat) (V f : 'M[F]_n) : V \in unitmx -> conjmx V (conjmx (invmx V) f) = f. Proof. by move=> Vu; rewrite -conjuMumx ?unitmx_inv// mulmxV ?conj1mx. Qed. Lemma horner_mx_conj m n p (B : 'M[F]_(n.+1, m.+1)) (f : 'M_m.+1) : row_free B -> stablemx B f -> horner_mx (conjmx B f) p = conjmx B (horner_mx f p). Proof. move=> B_free B_stab; rewrite/conjmx; elim/poly_ind: p => [|p c]. by rewrite !rmorph0 mulmx0 mul0mx. rewrite !(rmorphD, rmorphM)/= !(horner_mx_X, horner_mx_C) => ->. rewrite [_ * _]mulmxA [_ *m (B *m _)]mulmxA mulmxKpV ?horner_mx_stable//. apply: (row_free_inj B_free); rewrite [_ *m B]mulmxDl. pose stablemxE := (stablemxD, stablemxM, stablemxC, horner_mx_stable). by rewrite !mulmxKpV -?[B *m _ *m _]mulmxA ?stablemxE// mulmxDr -scalar_mxC. Qed. Lemma horner_mx_uconj n p (B : 'M[F]_(n.+1)) (f : 'M_n.+1) : B \is a GRing.unit -> horner_mx (B *m f *m invmx B) p = B *m horner_mx f p *m invmx B. Proof. move=> B_unit; rewrite -!conjumx//. by rewrite horner_mx_conj ?row_free_unit ?stablemx_unit. Qed. Lemma horner_mx_uconjC n p (B : 'M[F]_(n.+1)) (f : 'M_n.+1) : B \is a GRing.unit -> horner_mx (invmx B *m f *m B) p = invmx B *m horner_mx f p *m B. Proof. move=> B_unit; rewrite -[X in _ *m X](invmxK B). by rewrite horner_mx_uconj ?invmxK ?unitmx_inv. Qed. Lemma mxminpoly_conj m n (V : 'M[F]_(m.+1, n.+1)) (f : 'M_n.+1) : row_free V -> stablemx V f -> mxminpoly (conjmx V f) %| mxminpoly f. Proof. by move=> *; rewrite mxminpoly_min// horner_mx_conj// mx_root_minpoly conjmx0. Qed. Lemma mxminpoly_uconj n (V : 'M[F]_(n.+1)) (f : 'M_n.+1) : V \in unitmx -> mxminpoly (conjmx V f) = mxminpoly f. Proof. have simp := (row_free_unit, stablemx_unit, unitmx_inv, unitmx1). move=> Vu; apply/eqP; rewrite -eqp_monic ?mxminpoly_monic// /eqp. apply/andP; split; first by rewrite mxminpoly_conj ?simp. by rewrite -[f in X in X %| _](conjmxK _ Vu) mxminpoly_conj ?simp. Qed. Section fixed_stablemx_space. Variables (m n : nat). Implicit Types (V : 'M[F]_(m, n)) (f : 'M[F]_n). Implicit Types (a : F) (p : {poly F}). Section Sub. Variable (k : nat). Implicit Types (W : 'M[F]_(k, m)). Lemma sub_kermxpoly_conjmx V f p W : stablemx V f -> row_free V -> (W <= kermxpoly (conjmx V f) p)%MS = (W *m V <= kermxpoly f p)%MS. Proof. move: n m => [|n'] [|m']// in V f W *; rewrite ?thinmx0// => fV rfV. - by rewrite /row_free mxrank0 in rfV. - by rewrite mul0mx !sub0mx. - apply/sub_kermxP/sub_kermxP; rewrite horner_mx_conj//; last first. by move=> /(congr1 (mulmxr (pinvmx V)))/=; rewrite mul0mx !mulmxA. move=> /(congr1 (mulmxr V))/=; rewrite ![W *m _]mulmxA ?mul0mx mulmxKpV//. by rewrite -mulmxA mulmx_sub// horner_mx_stable//. Qed. Lemma sub_eigenspace_conjmx V f a W : stablemx V f -> row_free V -> (W <= eigenspace (conjmx V f) a)%MS = (W *m V <= eigenspace f a)%MS. Proof. by move=> fV rfV; rewrite !eigenspace_poly sub_kermxpoly_conjmx. Qed. End Sub. Lemma eigenpoly_conjmx V f : stablemx V f -> row_free V -> {subset eigenpoly (conjmx V f) <= eigenpoly f}. Proof. move=> fV rfV a /eigenpolyP [x]; rewrite sub_kermxpoly_conjmx//. move=> xV_le_fa x_neq0; apply/eigenpolyP. by exists (x *m V); rewrite ?mulmx_free_eq0. Qed. Lemma eigenvalue_conjmx V f : stablemx V f -> row_free V -> {subset eigenvalue (conjmx V f) <= eigenvalue f}. Proof. by move=> fV rfV a; rewrite ![_ \in _]eigenvalue_poly; apply: eigenpoly_conjmx. Qed. Lemma conjmx_eigenvalue a V f : (V <= eigenspace f a)%MS -> row_free V -> conjmx V f = a%:M. Proof. by move=> /eigenspaceP Vfa rfV; rewrite /conjmx Vfa -mul_scalar_mx mulmxKp. Qed. End fixed_stablemx_space. End ConjMx. Notation restrictmx V := (conjmx (row_base V)). Definition similar_to {F : fieldType} {m n} (P : 'M_(m, n)) A (C : {pred 'M[F]_m}) := C (conjmx P A). Notation similar P A B := (similar_to P A (PredOfSimpl.coerce (pred1 B))). Notation similar_in D A B := (exists2 P, P \in D & similar P A B). Notation similar_in_to D A C := (exists2 P, P \in D & similar_to P A C). Notation all_similar_to D As C := (exists2 P, P \in D & all [pred A | similar_to P A C] As). Notation similar_diag P A := (similar_to P A is_diag_mx). Notation diagonalizable_in D A := (similar_in_to D A is_diag_mx). Notation diagonalizable A := (diagonalizable_in unitmx A). Notation codiagonalizable_in D As := (all_similar_to D As is_diag_mx). Notation codiagonalizable As := (codiagonalizable_in unitmx As). Notation similar_trig P A := (similar_to P A is_trig_mx). Notation trigonalizable_in D A := (similar_in_to D A is_trig_mx). Notation trigonalizable A := (trigonalizable_in unitmx A). Notation cotrigonalizable_in D As := (all_similar_to D As is_trig_mx). Notation cotrigonalizable As := (cotrigonalizable_in unitmx As). Section Similarity. Context {F : fieldType}. Lemma similarPp m n {P : 'M[F]_(m, n)} {A B} : stablemx P A -> similar P A B -> P *m A = B *m P. Proof. by move=> stablemxPA /eqP <-; rewrite mulmxKpV. Qed. Lemma similarW m n {P : 'M[F]_(m, n)} {A B} : row_free P -> P *m A = B *m P -> similar P A B. Proof. by rewrite /similar_to/= /conjmx => fP ->; rewrite mulmxKp. Qed. Section Similar. Context {n : nat}. Implicit Types (f g p : 'M[F]_n) (fs : seq 'M[F]_n) (d : 'rV[F]_n). Lemma similarP {p f g} : p \in unitmx -> reflect (p *m f = g *m p) (similar p f g). Proof. move=> p_unit; apply: (iffP idP); first exact/similarPp/stablemx_unit. by apply: similarW; rewrite row_free_unit. Qed. Lemma similarRL {p f g} : p \in unitmx -> reflect (g = p *m f *m invmx p) (similar p f g). Proof. by move=> ?; apply: (iffP eqP); rewrite conjumx. Qed. Lemma similarLR {p f g} : p \in unitmx -> reflect (f = conjmx (invmx p) g) (similar p f g). Proof. by move=> pu; rewrite conjVmx//; apply: (iffP (similarRL pu)) => ->; rewrite !mulmxA ?(mulmxK, mulmxKV, mulVmx, mulmxV, mul1mx, mulmx1). Qed. End Similar. Lemma similar_mxminpoly {n} {p f g : 'M[F]_n.+1} : p \in unitmx -> similar p f g -> mxminpoly f = mxminpoly g. Proof. by move=> pu /eqP<-; rewrite mxminpoly_uconj. Qed. Lemma similar_diag_row_base m n (P : 'M[F]_(m, n)) (A : 'M_n) : similar_diag (row_base P) A = is_diag_mx (restrictmx P A). Proof. by []. Qed. Lemma similar_diagPp m n (P : 'M[F]_(m, n)) A : reflect (forall i j : 'I__, i != j :> nat -> conjmx P A i j = 0) (similar_diag P A). Proof. exact: @is_diag_mxP. Qed. Lemma similar_diagP n (P : 'M[F]_n) A : P \in unitmx -> reflect (forall i j : 'I__, i != j :> nat -> (P *m A *m invmx P) i j = 0) (similar_diag P A). Proof. by move=> Pu; rewrite -conjumx//; exact: is_diag_mxP. Qed. Lemma similar_diagPex {m} {n} {P : 'M[F]_(m, n)} {A} : reflect (exists D, similar P A (diag_mx D)) (similar_diag P A). Proof. by apply: (iffP (diag_mxP _)) => -[D]/eqP; exists D. Qed. Lemma similar_diagLR n {P : 'M[F]_n} {A} : P \in unitmx -> reflect (exists D, A = conjmx (invmx P) (diag_mx D)) (similar_diag P A). Proof. by move=> Punit; apply: (iffP similar_diagPex) => -[D /(similarLR Punit)]; exists D. Qed. Lemma similar_diag_mxminpoly {n} {p f : 'M[F]_n.+1} (rs := undup [seq conjmx p f i i | i <- enum 'I_n.+1]) : p \in unitmx -> similar_diag p f -> mxminpoly f = \prod_(r <- rs) ('X - r%:P). Proof. rewrite /rs => pu /(similar_diagLR pu)[d {f rs}->]. rewrite mxminpoly_uconj ?unitmx_inv// mxminpoly_diag. by rewrite [in RHS](@eq_map _ _ _ (d 0))// => i; rewrite conjmxVK// mxE eqxx. Qed. End Similarity. Lemma similar_diag_sum (F : fieldType) (m n : nat) (p_ : 'I_n -> nat) (V_ : forall i, 'M[F]_(p_ i, m)) (f : 'M[F]_m) : mxdirect (\sum_i <<V_ i>>) -> (forall i, stablemx (V_ i) f) -> (forall i, row_free (V_ i)) -> similar_diag (\mxcol_i V_ i) f = [forall i, similar_diag (V_ i) f]. Proof. move=> Vd Vf rfV; have aVf : stablemx (\mxcol_i V_ i) f. rewrite (eqmx_stable _ (eqmx_col _)) stablemx_sums//. by move=> i; rewrite (eqmx_stable _ (genmxE _)). apply/similar_diagPex/'forall_similar_diagPex => /= [[D /(similarPp aVf) +] i|/(_ _)/sigW Dof]. rewrite mxcol_mul -[D]submxrowK diag_mxrow mul_mxdiag_mxcol. move=> /eq_mxcolP/(_ i); set D0 := (submxrow _ _) => VMeq. by exists D0; apply/similarW. exists (\mxrow_i tag (Dof i)); apply/similarW. rewrite -row_leq_rank eqmx_col (mxdirectP Vd)/=. by under [X in (_ <= X)%N]eq_bigr do rewrite genmxE (eqP (rfV _)). rewrite mxcol_mul diag_mxrow mul_mxdiag_mxcol; apply: eq_mxcol => i. by case: Dof => /= k /(similarPp); rewrite Vf => /(_ isT) ->. Qed. Section Diag. Variable (F : fieldType). Lemma codiagonalizable1 n (A : 'M[F]_n) : codiagonalizable [:: A] <-> diagonalizable A. Proof. by split=> -[P Punit PA]; exists P; move: PA; rewrite //= andbT. Qed. Lemma codiagonalizablePfull n (As : seq 'M[F]_n) : codiagonalizable As <-> exists m, exists2 P : 'M_(m, n), row_full P & all [pred A | similar_diag P A] As. Proof. split => [[P Punit SPA]|[m [P Pfull SPA]]]. by exists n => //; exists P; rewrite ?row_full_unit. have Qfull := fullrowsub_unit Pfull. exists (rowsub (fullrankfun Pfull) P) => //; apply/allP => A AAs/=. have /allP /(_ _ AAs)/= /similar_diagPex[d /similarPp] := SPA. rewrite submx_full// => /(_ isT) PA_eq. apply/similar_diagPex; exists (colsub (fullrankfun Pfull) d). apply/similarP => //; apply/row_matrixP => i. rewrite !row_mul row_diag_mx -scalemxAl -rowE !row_rowsub !mxE. have /(congr1 (row (fullrankfun Pfull i))) := PA_eq. by rewrite !row_mul row_diag_mx -scalemxAl -rowE => ->. Qed. Lemma codiagonalizable_on m n (V_ : 'I_n -> 'M[F]_m) (As : seq 'M[F]_m) : (\sum_i V_ i :=: 1%:M)%MS -> mxdirect (\sum_i V_ i) -> (forall i, all (fun A => stablemx (V_ i) A) As) -> (forall i, codiagonalizable (map (restrictmx (V_ i)) As)) -> codiagonalizable As. Proof. move=> V1 Vdirect /(_ _)/allP AV /(_ _) /sig2W/= Pof. pose P_ i := tag (Pof i). have P_unit i : P_ i \in unitmx by rewrite /P_; case: {+}Pof. have P_diag i A : A \in As -> similar_diag (P_ i *m row_base (V_ i)) A. move=> AAs; rewrite /P_; case: {+}Pof => /= P Punit. rewrite all_map => /allP/(_ A AAs); rewrite /similar_to/=. by rewrite conjuMmx ?row_base_free ?stablemx_row_base ?AV. pose P := \mxcol_i (P_ i *m row_base (V_ i)). have P_full i : row_full (P_ i) by rewrite row_full_unit. have PrV i : (P_ i *m row_base (V_ i) :=: V_ i)%MS. exact/(eqmx_trans _ (eq_row_base _))/eqmxMfull. apply/codiagonalizablePfull; eexists _; last exists P; rewrite /=. - rewrite -sub1mx eqmx_col. by under eq_bigr do rewrite (eq_genmx (PrV _)); rewrite -genmx_sums genmxE V1. apply/allP => A AAs /=; rewrite similar_diag_sum. - by apply/forallP => i; apply: P_diag. - rewrite mxdirectE/=. under eq_bigr do rewrite (eq_genmx (PrV _)); rewrite -genmx_sums genmxE V1. by under eq_bigr do rewrite genmxE PrV; rewrite -(mxdirectP Vdirect)//= V1. - by move=> i; rewrite (eqmx_stable _ (PrV _)) ?AV. - by move=> i; rewrite /row_free eqmxMfull ?eq_row_base ?row_full_unit. Qed. Lemma diagonalizable_diag {n} (d : 'rV[F]_n) : diagonalizable (diag_mx d). Proof. by exists 1%:M; rewrite ?unitmx1// /similar_to conj1mx diag_mx_is_diag. Qed. Hint Resolve diagonalizable_diag : core. Lemma diagonalizable_scalar {n} (a : F) : diagonalizable (a%:M : 'M_n). Proof. by rewrite -diag_const_mx. Qed. Hint Resolve diagonalizable_scalar : core. Lemma diagonalizable0 {n} : diagonalizable (0 : 'M[F]_n). Proof. by rewrite (_ : 0 = 0%:M)//; apply/matrixP => i j; rewrite !mxE// mul0rn. Qed. Hint Resolve diagonalizable0 : core. Lemma diagonalizablePeigen {n} {f : 'M[F]_n} : diagonalizable f <-> exists2 rs, uniq rs & (\sum_(r <- rs) eigenspace f r :=: 1%:M)%MS. Proof. split=> [df|[rs urs rsP]]. suff [rs rsP] : exists rs, (\sum_(r <- rs) eigenspace f r :=: 1%:M)%MS. exists (undup rs); rewrite ?undup_uniq//; apply: eqmx_trans rsP. elim: rs => //= r rs IHrs; rewrite big_cons. case: ifPn => in_rs; rewrite ?big_cons; last exact: adds_eqmx. apply/(eqmx_trans IHrs)/eqmx_sym/addsmx_idPr. have rrs : (index r rs < size rs)%N by rewrite index_mem. rewrite (big_nth 0) big_mkord (sumsmx_sup (Ordinal rrs)) ?nth_index//. move: df => [P Punit /(similar_diagLR Punit)[d ->]]. exists [seq d 0 i | i <- enum 'I_n]; rewrite big_image/=. apply: (@eqmx_trans _ _ _ _ _ _ P); apply/eqmxP; rewrite ?sub1mx ?submx1 ?row_full_unit//. rewrite submx_full ?row_full_unit//=. apply/row_subP => i; rewrite rowE (sumsmx_sup i)//. apply/eigenspaceP; rewrite conjVmx// !mulmxA mulmxK//. by rewrite -rowE row_diag_mx scalemxAl. have mxdirect_eigenspaces : mxdirect (\sum_(i < size rs) eigenspace f rs`_i). apply: mxdirect_sum_eigenspace => i j _ _ rsij; apply/val_inj. by apply: uniqP rsij; rewrite ?inE. rewrite (big_nth 0) big_mkord in rsP; apply/codiagonalizable1. apply/(codiagonalizable_on _ mxdirect_eigenspaces) => // i/=. case: n => [|n] in f {mxdirect_eigenspaces} rsP *. by rewrite thinmx0 sub0mx. by rewrite comm_mx_stable_eigenspace. apply/codiagonalizable1. by rewrite (@conjmx_eigenvalue _ _ _ rs`_i) ?eq_row_base ?row_base_free. Qed. Lemma diagonalizableP n' (n := n'.+1) (f : 'M[F]_n) : diagonalizable f <-> exists2 rs, uniq rs & mxminpoly f %| \prod_(x <- rs) ('X - x%:P). Proof. split=> [[P Punit /similar_diagPex[d /(similarLR Punit)->]]|]. rewrite mxminpoly_uconj ?unitmx_inv// mxminpoly_diag. by eexists; [|by []]; rewrite undup_uniq. move=> [rs rsU rsP]; apply: diagonalizablePeigen.2. exists rs => //. rewrite (big_nth 0) big_mkord (eq_bigr _ (fun _ _ => eigenspace_poly _ _)). apply: (eqmx_trans (eqmx_sym (kermxpoly_prod _ _)) (kermxpoly_min _)). by move=> i j _ _; rewrite coprimep_XsubC root_XsubC nth_uniq. by rewrite (big_nth 0) big_mkord in rsP. Qed. Lemma diagonalizable_conj_diag m n (V : 'M[F]_(m, n)) (d : 'rV[F]_n) : stablemx V (diag_mx d) -> row_free V -> diagonalizable (conjmx V (diag_mx d)). Proof. (move: m n => [|m] [|n] in V d *; rewrite ?thinmx0; [by []|by []| |]) => Vd rdV. - by rewrite /row_free mxrank0 in rdV. - apply/diagonalizableP; pose u := undup [seq d 0 i | i <- enum 'I_n.+1]. exists u; first by rewrite undup_uniq. by rewrite (dvdp_trans (mxminpoly_conj rdV _))// mxminpoly_diag. Qed. Lemma codiagonalizableP n (fs : seq 'M[F]_n) : {in fs &, forall f g, comm_mx f g} /\ (forall f, f \in fs -> diagonalizable f) <-> codiagonalizable fs. Proof. split => [cdfs|[P Punit /allP/= fsD]]/=; last first. split; last by exists P; rewrite // fsD. move=> f g ffs gfs; move=> /(_ _ _)/similar_diagPex/sigW in fsD. have [[df /similarLR->//] [dg /similarLR->//]] := (fsD _ ffs, fsD _ gfs). by rewrite /comm_mx -!conjmxM 1?diag_mxC// inE stablemx_unit ?unitmx_inv. move: cdfs => [/(rwP (all_comm_mxP _)).1 cdfs1 cdfs2]. have [k] := ubnP (size fs); elim: k => [|k IHk]//= in n fs cdfs1 cdfs2 *. case: fs cdfs1 cdfs2 => [|f fs]//=; first by exists 1%:M; rewrite ?unitmx1. rewrite ltnS all_comm_mx_cons => /andP[/allP/(_ _ _)/eqP ffsC fsC dffs] fsk. have /diagonalizablePeigen [rs urs rs1] := dffs _ (mem_head _ _). rewrite (big_nth 0) big_mkord in rs1. have efg (i : 'I_(size rs)) g : g \in f :: fs -> stablemx (eigenspace f rs`_i) g. case: n => [|n'] in g f fs ffsC fsC {dffs rs1 fsk} * => g_ffs. by rewrite thinmx0 sub0mx. rewrite comm_mx_stable_eigenspace//. by move: g_ffs; rewrite !inE => /predU1P [->//|/ffsC]. apply/(@codiagonalizable_on _ _ _ (_ :: _) rs1) => [|i|i /=]. - apply: mxdirect_sum_eigenspace => i j _ _ rsij; apply/val_inj. by apply: uniqP rsij; rewrite ?inE. - by apply/allP => g g_ffs; rewrite efg. rewrite (@conjmx_eigenvalue _ _ _ rs`_i) ?eq_row_base ?row_base_free//. set gs := map _ _; suff [P Punit /= Pgs] : codiagonalizable gs. exists P; rewrite /= ?Pgs ?andbT// /similar_to. by rewrite conjmx_scalar ?mx_scalar_is_diag// row_free_unit. apply: IHk; rewrite ?size_map/= ?ltnS//. apply/all_comm_mxP => _ _ /mapP[/= g gfs ->] /mapP[/= h hfs ->]. rewrite -!conjmxM ?inE ?stablemx_row_base ?efg ?inE ?gfs ?hfs ?orbT//. by rewrite (all_comm_mxP _ fsC). move=> _ /mapP[/= g gfs ->]. have: stablemx (row_base (eigenspace f rs`_i)) g. by rewrite stablemx_row_base efg// inE gfs orbT. have := dffs g; rewrite inE gfs orbT => /(_ isT) [P Punit]. move=> /similar_diagPex[D /(similarLR Punit)->] sePD. have rfeP : row_free (row_base (eigenspace f rs`_i) *m invmx P). by rewrite /row_free mxrankMfree ?row_free_unit ?unitmx_inv// eq_row_base. rewrite -conjMumx ?unitmx_inv ?row_base_free//. apply/diagonalizable_conj_diag => //. by rewrite stablemx_comp// stablemx_unit ?unitmx_inv. Qed. End Diag.
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).
Op.lean
/- Copyright (c) 2025 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer -/ import Mathlib.CategoryTheory.Category.Cat import Mathlib.CategoryTheory.Opposites /-! # The dualizing functor on `Cat` We define a (strict) functor `opFunctor` and an equivalence assigning opposite categories to categories. We then show that this functor is strictly involutive and that it induces an equivalence on `Cat`. -/ universe v₁ v₂ u₁ u₂ namespace CategoryTheory namespace Cat /-- The endofunctor `Cat ⥤ Cat` assigning to each category its opposite category. -/ @[simps] def opFunctor : Cat.{v₁, u₁} ⥤ Cat.{v₁, u₁} where obj C := .of Cᵒᵖ map := Functor.op /-- The natural isomorphism between the double application of `Cat.opFunctor` and the identity functor on `Cat`. -/ @[simps!] def opFunctorInvolutive : opFunctor.{v₁, u₁} ⋙ opFunctor.{v₁, u₁} ≅ 𝟭 _ := NatIso.ofComponents (fun C => .mk (unopUnop C) (opOp C)) /-- The equivalence `Cat ≌ Cat` associating each category with its opposite category. -/ @[simps] def opEquivalence : Cat.{v₁, u₁} ≌ Cat.{v₁, u₁} where functor := opFunctor inverse := opFunctor unitIso := NatIso.ofComponents (fun _ => Iso.mk (opOp _) (unopUnop _)) counitIso := NatIso.ofComponents (fun _ => Iso.mk (unopUnop _) (opOp _)) end Cat end CategoryTheory
InjectiveSeminorm.lean
/- Copyright (c) 2024 Sophie Morel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sophie Morel -/ import Mathlib.Analysis.NormedSpace.PiTensorProduct.ProjectiveSeminorm import Mathlib.LinearAlgebra.Isomorphisms /-! # Injective seminorm on the tensor of a finite family of normed spaces. Let `𝕜` be a nontrivially normed field and `E` be a family of normed `𝕜`-vector spaces `Eᵢ`, indexed by a finite type `ι`. We define a seminorm on `⨂[𝕜] i, Eᵢ`, which we call the "injective seminorm". It is chosen to satisfy the following property: for every normed `𝕜`-vector space `F`, the linear equivalence `MultilinearMap 𝕜 E F ≃ₗ[𝕜] (⨂[𝕜] i, Eᵢ) →ₗ[𝕜] F` expressing the universal property of the tensor product induces an isometric linear equivalence `ContinuousMultilinearMap 𝕜 E F ≃ₗᵢ[𝕜] (⨂[𝕜] i, Eᵢ) →L[𝕜] F`. The idea is the following: Every normed `𝕜`-vector space `F` defines a linear map from `⨂[𝕜] i, Eᵢ` to `ContinuousMultilinearMap 𝕜 E F →ₗ[𝕜] F`, which sends `x` to the map `f ↦ f.lift x`. Thanks to `PiTensorProduct.norm_eval_le_projectiveSeminorm`, this map lands in `ContinuousMultilinearMap 𝕜 E F →L[𝕜] F`. As this last space has a natural operator (semi)norm, we get an induced seminorm on `⨂[𝕜] i, Eᵢ`, which, by `PiTensorProduct.norm_eval_le_projectiveSeminorm`, is bounded above by the projective seminorm `PiTensorProduct.projectiveSeminorm`. We then take the `sup` of these seminorms as `F` varies; as this family of seminorms is bounded, its `sup` has good properties. In fact, we cannot take the `sup` over all normed spaces `F` because of set-theoretical issues, so we only take spaces `F` in the same universe as `⨂[𝕜] i, Eᵢ`. We prove in `norm_eval_le_injectiveSeminorm` that this gives the same result, because every multilinear map from `E = Πᵢ Eᵢ` to `F` factors though a normed vector space in the same universe as `⨂[𝕜] i, Eᵢ`. We then prove the universal property and the functoriality of `⨂[𝕜] i, Eᵢ` as a normed vector space. ## Main definitions * `PiTensorProduct.toDualContinuousMultilinearMap`: The `𝕜`-linear map from `⨂[𝕜] i, Eᵢ` to `ContinuousMultilinearMap 𝕜 E F →L[𝕜] F` sending `x` to the map `f ↦ f x`. * `PiTensorProduct.injectiveSeminorm`: The injective seminorm on `⨂[𝕜] i, Eᵢ`. * `PiTensorProduct.liftEquiv`: The bijection between `ContinuousMultilinearMap 𝕜 E F` and `(⨂[𝕜] i, Eᵢ) →L[𝕜] F`, as a continuous linear equivalence. * `PiTensorProduct.liftIsometry`: The bijection between `ContinuousMultilinearMap 𝕜 E F` and `(⨂[𝕜] i, Eᵢ) →L[𝕜] F`, as an isometric linear equivalence. * `PiTensorProduct.tprodL`: The canonical continuous multilinear map from `E = Πᵢ Eᵢ` to `⨂[𝕜] i, Eᵢ`. * `PiTensorProduct.mapL`: The continuous linear map from `⨂[𝕜] i, Eᵢ` to `⨂[𝕜] i, E'ᵢ` induced by a family of continuous linear maps `Eᵢ →L[𝕜] E'ᵢ`. * `PiTensorProduct.mapLMultilinear`: The continuous multilinear map from `Πᵢ (Eᵢ →L[𝕜] E'ᵢ)` to `(⨂[𝕜] i, Eᵢ) →L[𝕜] (⨂[𝕜] i, E'ᵢ)` sending a family `f` to `PiTensorProduct.mapL f`. ## Main results * `PiTensorProduct.norm_eval_le_injectiveSeminorm`: The main property of the injective seminorm on `⨂[𝕜] i, Eᵢ`: for every `x` in `⨂[𝕜] i, Eᵢ` and every continuous multilinear map `f` from `E = Πᵢ Eᵢ` to a normed space `F`, we have `‖f.lift x‖ ≤ ‖f‖ * injectiveSeminorm x `. * `PiTensorProduct.mapL_opNorm`: If `f` is a family of continuous linear maps `fᵢ : Eᵢ →L[𝕜] Fᵢ`, then `‖PiTensorProduct.mapL f‖ ≤ ∏ i, ‖fᵢ‖`. * `PiTensorProduct.mapLMultilinear_opNorm` : If `F` is a normed vecteor space, then `‖mapLMultilinear 𝕜 E F‖ ≤ 1`. ## TODO * If all `Eᵢ` are separated and satisfy `SeparatingDual`, then the seminorm on `⨂[𝕜] i, Eᵢ` is a norm. This uses the construction of a basis of the `PiTensorProduct`, hence depends on PR https://github.com/leanprover-community/mathlib4/pull/11156. It should probably go in a separate file. * Adapt the remaining functoriality constructions/properties from `PiTensorProduct`. -/ universe uι u𝕜 uE uF variable {ι : Type uι} [Fintype ι] variable {𝕜 : Type u𝕜} [NontriviallyNormedField 𝕜] variable {E : ι → Type uE} [∀ i, SeminormedAddCommGroup (E i)] [∀ i, NormedSpace 𝕜 (E i)] variable {F : Type uF} [SeminormedAddCommGroup F] [NormedSpace 𝕜 F] open scoped TensorProduct namespace PiTensorProduct section seminorm variable (F) in /-- The linear map from `⨂[𝕜] i, Eᵢ` to `ContinuousMultilinearMap 𝕜 E F →L[𝕜] F` sending `x` in `⨂[𝕜] i, Eᵢ` to the map `f ↦ f.lift x`. -/ @[simps!] noncomputable def toDualContinuousMultilinearMap : (⨂[𝕜] i, E i) →ₗ[𝕜] ContinuousMultilinearMap 𝕜 E F →L[𝕜] F where toFun x := LinearMap.mkContinuous ((LinearMap.flip (lift (R := 𝕜) (s := E) (E := F)).toLinearMap x) ∘ₗ ContinuousMultilinearMap.toMultilinearMapLinear) (projectiveSeminorm x) (fun _ ↦ by simp only [LinearMap.coe_comp, Function.comp_apply, ContinuousMultilinearMap.toMultilinearMapLinear_apply, LinearMap.flip_apply, LinearEquiv.coe_coe] exact norm_eval_le_projectiveSeminorm _ _ _) map_add' x y := by ext _ simp only [map_add, LinearMap.mkContinuous_apply, LinearMap.coe_comp, Function.comp_apply, ContinuousMultilinearMap.toMultilinearMapLinear_apply, LinearMap.add_apply, LinearMap.flip_apply, LinearEquiv.coe_coe, ContinuousLinearMap.add_apply] map_smul' a x := by ext _ simp only [map_smul, LinearMap.mkContinuous_apply, LinearMap.coe_comp, Function.comp_apply, ContinuousMultilinearMap.toMultilinearMapLinear_apply, LinearMap.smul_apply, LinearMap.flip_apply, LinearEquiv.coe_coe, RingHom.id_apply, ContinuousLinearMap.coe_smul', Pi.smul_apply] theorem toDualContinuousMultilinearMap_le_projectiveSeminorm (x : ⨂[𝕜] i, E i) : ‖toDualContinuousMultilinearMap F x‖ ≤ projectiveSeminorm x := by simp only [toDualContinuousMultilinearMap, LinearMap.coe_mk, AddHom.coe_mk] apply LinearMap.mkContinuous_norm_le _ (apply_nonneg _ _) /-- The injective seminorm on `⨂[𝕜] i, Eᵢ`. Morally, it sends `x` in `⨂[𝕜] i, Eᵢ` to the `sup` of the operator norms of the `PiTensorProduct.toDualContinuousMultilinearMap F x`, for all normed vector spaces `F`. In fact, we only take in the same universe as `⨂[𝕜] i, Eᵢ`, and then prove in `PiTensorProduct.norm_eval_le_injectiveSeminorm` that this gives the same result. -/ noncomputable irreducible_def injectiveSeminorm : Seminorm 𝕜 (⨂[𝕜] i, E i) := sSup {p | ∃ (G : Type (max uι u𝕜 uE)) (_ : SeminormedAddCommGroup G) (_ : NormedSpace 𝕜 G), p = Seminorm.comp (normSeminorm 𝕜 (ContinuousMultilinearMap 𝕜 E G →L[𝕜] G)) (toDualContinuousMultilinearMap G (𝕜 := 𝕜) (E := E))} lemma dualSeminorms_bounded : BddAbove {p | ∃ (G : Type (max uι u𝕜 uE)) (_ : SeminormedAddCommGroup G) (_ : NormedSpace 𝕜 G), p = Seminorm.comp (normSeminorm 𝕜 (ContinuousMultilinearMap 𝕜 E G →L[𝕜] G)) (toDualContinuousMultilinearMap G (𝕜 := 𝕜) (E := E))} := by existsi projectiveSeminorm rw [mem_upperBounds] simp only [Set.mem_setOf_eq, forall_exists_index] intro p G _ _ hp rw [hp] intro x simp only [Seminorm.comp_apply, coe_normSeminorm] exact toDualContinuousMultilinearMap_le_projectiveSeminorm _ theorem injectiveSeminorm_apply (x : ⨂[𝕜] i, E i) : injectiveSeminorm x = ⨆ p : {p | ∃ (G : Type (max uι u𝕜 uE)) (_ : SeminormedAddCommGroup G) (_ : NormedSpace 𝕜 G), p = Seminorm.comp (normSeminorm 𝕜 (ContinuousMultilinearMap 𝕜 E G →L[𝕜] G)) (toDualContinuousMultilinearMap G (𝕜 := 𝕜) (E := E))}, p.1 x := by simpa only [injectiveSeminorm, Set.coe_setOf, Set.mem_setOf_eq] using Seminorm.sSup_apply dualSeminorms_bounded theorem norm_eval_le_injectiveSeminorm (f : ContinuousMultilinearMap 𝕜 E F) (x : ⨂[𝕜] i, E i) : ‖lift f.toMultilinearMap x‖ ≤ ‖f‖ * injectiveSeminorm x := by /- If `F` were in `Type (max uι u𝕜 uE)` (which is the type of `⨂[𝕜] i, E i`), then the property that we want to prove would hold by definition of `injectiveSeminorm`. This is not necessarily true, but we will show that there exists a normed vector space `G` in `Type (max uι u𝕜 uE)` and an injective isometry from `G` to `F` such that `f` factors through a continuous multilinear map `f'` from `E = Π i, E i` to `G`, to which we can apply the definition of `injectiveSeminorm`. The desired inequality for `f` then follows immediately. The idea is very simple: the multilinear map `f` corresponds by `PiTensorProduct.lift` to a linear map from `⨂[𝕜] i, E i` to `F`, say `l`. We want to take `G` to be the image of `l`, with the norm induced from that of `F`; to make sure that we are in the correct universe, it is actually more convenient to take `G` equal to the coimage of `l` (i.e. the quotient of `⨂[𝕜] i, E i` by the kernel of `l`), which is canonically isomorphic to its image by `LinearMap.quotKerEquivRange`. -/ set G := (⨂[𝕜] i, E i) ⧸ LinearMap.ker (lift f.toMultilinearMap) set G' := LinearMap.range (lift f.toMultilinearMap) set e := LinearMap.quotKerEquivRange (lift f.toMultilinearMap) letI := SeminormedAddCommGroup.induced G G' e letI := NormedSpace.induced 𝕜 G G' e set f'₀ := lift.symm (e.symm.toLinearMap ∘ₗ LinearMap.rangeRestrict (lift f.toMultilinearMap)) have hf'₀ : ∀ (x : Π (i : ι), E i), ‖f'₀ x‖ ≤ ‖f‖ * ∏ i, ‖x i‖ := fun x ↦ by change ‖e (f'₀ x)‖ ≤ _ simp only [lift_symm, LinearMap.compMultilinearMap_apply, LinearMap.coe_comp, LinearEquiv.coe_coe, Function.comp_apply, LinearEquiv.apply_symm_apply, Submodule.coe_norm, LinearMap.codRestrict_apply, lift.tprod, ContinuousMultilinearMap.coe_coe, e, f'₀] exact f.le_opNorm x set f' := MultilinearMap.mkContinuous f'₀ ‖f‖ hf'₀ have hnorm : ‖f'‖ ≤ ‖f‖ := (f'.opNorm_le_iff (norm_nonneg f)).mpr hf'₀ have heq : e (lift f'.toMultilinearMap x) = lift f.toMultilinearMap x := by induction x using PiTensorProduct.induction_on with | smul_tprod => simp only [lift_symm, map_smul, lift.tprod, ContinuousMultilinearMap.coe_coe, MultilinearMap.coe_mkContinuous, LinearMap.compMultilinearMap_apply, LinearMap.coe_comp, LinearEquiv.coe_coe, Function.comp_apply, LinearEquiv.apply_symm_apply, SetLike.val_smul, LinearMap.codRestrict_apply, f', f'₀] | add _ _ hx hy => simp only [map_add, Submodule.coe_add, hx, hy] suffices h : ‖lift f'.toMultilinearMap x‖ ≤ ‖f'‖ * injectiveSeminorm x by change ‖(e (lift f'.toMultilinearMap x)).1‖ ≤ _ at h rw [heq] at h exact le_trans h (mul_le_mul_of_nonneg_right hnorm (apply_nonneg _ _)) have hle : Seminorm.comp (normSeminorm 𝕜 (ContinuousMultilinearMap 𝕜 E G →L[𝕜] G)) (toDualContinuousMultilinearMap G (𝕜 := 𝕜) (E := E)) ≤ injectiveSeminorm := by simp only [injectiveSeminorm] refine le_csSup dualSeminorms_bounded ?_ rw [Set.mem_setOf] existsi G, inferInstance, inferInstance rfl refine le_trans ?_ (mul_le_mul_of_nonneg_left (hle x) (norm_nonneg f')) simp only [Seminorm.comp_apply, coe_normSeminorm, ← toDualContinuousMultilinearMap_apply_apply] rw [mul_comm] exact ContinuousLinearMap.le_opNorm _ _ theorem injectiveSeminorm_le_projectiveSeminorm : injectiveSeminorm (𝕜 := 𝕜) (E := E) ≤ projectiveSeminorm := by rw [injectiveSeminorm] refine csSup_le ?_ ?_ · existsi 0 simp only [Set.mem_setOf_eq] existsi PUnit, inferInstance, inferInstance ext x simp only [Seminorm.zero_apply, Seminorm.comp_apply, coe_normSeminorm] rw [Subsingleton.elim (toDualContinuousMultilinearMap PUnit x) 0, norm_zero] · intro p hp simp only [Set.mem_setOf_eq] at hp obtain ⟨G, _, _, h⟩ := hp rw [h]; intro x; simp only [Seminorm.comp_apply, coe_normSeminorm] exact toDualContinuousMultilinearMap_le_projectiveSeminorm _ theorem injectiveSeminorm_tprod_le (m : Π (i : ι), E i) : injectiveSeminorm (⨂ₜ[𝕜] i, m i) ≤ ∏ i, ‖m i‖ := le_trans (injectiveSeminorm_le_projectiveSeminorm _) (projectiveSeminorm_tprod_le m) noncomputable instance : SeminormedAddCommGroup (⨂[𝕜] i, E i) := AddGroupSeminorm.toSeminormedAddCommGroup injectiveSeminorm.toAddGroupSeminorm noncomputable instance : NormedSpace 𝕜 (⨂[𝕜] i, E i) where norm_smul_le a x := by change injectiveSeminorm.toFun (a • x) ≤ _ rw [injectiveSeminorm.smul'] rfl variable (𝕜 E F) /-- The linear equivalence between `ContinuousMultilinearMap 𝕜 E F` and `(⨂[𝕜] i, Eᵢ) →L[𝕜] F` induced by `PiTensorProduct.lift`, for every normed space `F`. -/ @[simps] noncomputable def liftEquiv : ContinuousMultilinearMap 𝕜 E F ≃ₗ[𝕜] (⨂[𝕜] i, E i) →L[𝕜] F where toFun f := LinearMap.mkContinuous (lift f.toMultilinearMap) ‖f‖ fun x ↦ norm_eval_le_injectiveSeminorm f x map_add' f g := by ext _; simp only [ContinuousMultilinearMap.toMultilinearMap_add, map_add, LinearMap.mkContinuous_apply, LinearMap.add_apply, ContinuousLinearMap.add_apply] map_smul' a f := by ext _; simp only [ContinuousMultilinearMap.toMultilinearMap_smul, map_smul, LinearMap.mkContinuous_apply, LinearMap.smul_apply, RingHom.id_apply, ContinuousLinearMap.coe_smul', Pi.smul_apply] invFun l := MultilinearMap.mkContinuous (lift.symm l.toLinearMap) ‖l‖ fun x ↦ by simp only [lift_symm, LinearMap.compMultilinearMap_apply, ContinuousLinearMap.coe_coe] exact ContinuousLinearMap.le_opNorm_of_le _ (injectiveSeminorm_tprod_le x) left_inv f := by ext x; simp only [LinearMap.mkContinuous_coe, LinearEquiv.symm_apply_apply, MultilinearMap.coe_mkContinuous, ContinuousMultilinearMap.coe_coe] right_inv l := by rw [← ContinuousLinearMap.coe_inj] apply PiTensorProduct.ext; ext m simp only [lift_symm, LinearMap.mkContinuous_coe, LinearMap.compMultilinearMap_apply, lift.tprod, ContinuousMultilinearMap.coe_coe, MultilinearMap.coe_mkContinuous, ContinuousLinearMap.coe_coe] /-- For a normed space `F`, we have constructed in `PiTensorProduct.liftEquiv` the canonical linear equivalence between `ContinuousMultilinearMap 𝕜 E F` and `(⨂[𝕜] i, Eᵢ) →L[𝕜] F` (induced by `PiTensorProduct.lift`). Here we give the upgrade of this equivalence to an isometric linear equivalence; in particular, it is a continuous linear equivalence. -/ noncomputable def liftIsometry : ContinuousMultilinearMap 𝕜 E F ≃ₗᵢ[𝕜] (⨂[𝕜] i, E i) →L[𝕜] F := { liftEquiv 𝕜 E F with norm_map' := by intro f refine le_antisymm ?_ ?_ · simp only [liftEquiv_apply] exact LinearMap.mkContinuous_norm_le _ (norm_nonneg f) _ · conv_lhs => rw [← (liftEquiv 𝕜 E F).symm_apply_apply f] rw [liftEquiv_symm_apply] exact MultilinearMap.mkContinuous_norm_le _ (norm_nonneg _) _ } variable {𝕜 E F} @[simp] theorem liftIsometry_apply_apply (f : ContinuousMultilinearMap 𝕜 E F) (x : ⨂[𝕜] i, E i) : liftIsometry 𝕜 E F f x = lift f.toMultilinearMap x := by simp only [liftIsometry, LinearIsometryEquiv.coe_mk, liftEquiv_apply, LinearMap.mkContinuous_apply] variable (𝕜) in /-- The canonical continuous multilinear map from `E = Πᵢ Eᵢ` to `⨂[𝕜] i, Eᵢ`. -/ @[simps!] noncomputable def tprodL : ContinuousMultilinearMap 𝕜 E (⨂[𝕜] i, E i) := (liftIsometry 𝕜 E _).symm (ContinuousLinearMap.id 𝕜 _) @[simp] theorem tprodL_coe : (tprodL 𝕜).toMultilinearMap = tprod 𝕜 (s := E) := by ext m simp only [ContinuousMultilinearMap.coe_coe, tprodL_toFun] @[simp] theorem liftIsometry_symm_apply (l : (⨂[𝕜] i, E i) →L[𝕜] F) : (liftIsometry 𝕜 E F).symm l = l.compContinuousMultilinearMap (tprodL 𝕜) := by ext m change (liftEquiv 𝕜 E F).symm l m = _ simp only [liftEquiv_symm_apply, lift_symm, MultilinearMap.coe_mkContinuous, LinearMap.compMultilinearMap_apply, ContinuousLinearMap.coe_coe, ContinuousLinearMap.compContinuousMultilinearMap_coe, Function.comp_apply, tprodL_toFun] @[simp] theorem liftIsometry_tprodL : liftIsometry 𝕜 E _ (tprodL 𝕜) = ContinuousLinearMap.id 𝕜 (⨂[𝕜] i, E i) := by ext _ simp only [liftIsometry_apply_apply, tprodL_coe, lift_tprod, LinearMap.id_coe, id_eq, ContinuousLinearMap.coe_id'] end seminorm section map variable {E' E'' : ι → Type*} variable [∀ i, SeminormedAddCommGroup (E' i)] [∀ i, NormedSpace 𝕜 (E' i)] variable [∀ i, SeminormedAddCommGroup (E'' i)] [∀ i, NormedSpace 𝕜 (E'' i)] variable (g : Π i, E' i →L[𝕜] E'' i) (f : Π i, E i →L[𝕜] E' i) /-- Let `Eᵢ` and `E'ᵢ` be two families of normed `𝕜`-vector spaces. Let `f` be a family of continuous `𝕜`-linear maps between `Eᵢ` and `E'ᵢ`, i.e. `f : Πᵢ Eᵢ →L[𝕜] E'ᵢ`, then there is an induced continuous linear map `⨂ᵢ Eᵢ → ⨂ᵢ E'ᵢ` by `⨂ aᵢ ↦ ⨂ fᵢ aᵢ`. -/ noncomputable def mapL : (⨂[𝕜] i, E i) →L[𝕜] ⨂[𝕜] i, E' i := liftIsometry 𝕜 E _ <| (tprodL 𝕜).compContinuousLinearMap f @[simp] theorem mapL_coe : (mapL f).toLinearMap = map (fun i ↦ (f i).toLinearMap) := by ext simp only [mapL, LinearMap.compMultilinearMap_apply, ContinuousLinearMap.coe_coe, liftIsometry_apply_apply, lift.tprod, ContinuousMultilinearMap.coe_coe, ContinuousMultilinearMap.compContinuousLinearMap_apply, tprodL_toFun, map_tprod] @[simp] theorem mapL_apply (x : ⨂[𝕜] i, E i) : mapL f x = map (fun i ↦ (f i).toLinearMap) x := by induction x using PiTensorProduct.induction_on with | smul_tprod => simp only [mapL, map_smul, liftIsometry_apply_apply, lift.tprod, ContinuousMultilinearMap.coe_coe, ContinuousMultilinearMap.compContinuousLinearMap_apply, tprodL_toFun, map_tprod, ContinuousLinearMap.coe_coe] | add _ _ hx hy => simp only [map_add, hx, hy] /-- Given submodules `pᵢ ⊆ Eᵢ`, this is the natural map: `⨂[𝕜] i, pᵢ → ⨂[𝕜] i, Eᵢ`. This is the continuous version of `PiTensorProduct.mapIncl`. -/ @[simp] noncomputable def mapLIncl (p : Π i, Submodule 𝕜 (E i)) : (⨂[𝕜] i, p i) →L[𝕜] ⨂[𝕜] i, E i := mapL fun (i : ι) ↦ (p i).subtypeL theorem mapL_comp : mapL (fun (i : ι) ↦ g i ∘L f i) = mapL g ∘L mapL f := by apply ContinuousLinearMap.coe_injective ext simp only [mapL_coe, ContinuousLinearMap.coe_comp, LinearMap.compMultilinearMap_apply, map_tprod, LinearMap.coe_comp, ContinuousLinearMap.coe_coe, Function.comp_apply] theorem liftIsometry_comp_mapL (h : ContinuousMultilinearMap 𝕜 E' F) : liftIsometry 𝕜 E' F h ∘L mapL f = liftIsometry 𝕜 E F (h.compContinuousLinearMap f) := by apply ContinuousLinearMap.coe_injective ext simp only [ContinuousLinearMap.coe_comp, mapL_coe, LinearMap.compMultilinearMap_apply, LinearMap.coe_comp, ContinuousLinearMap.coe_coe, Function.comp_apply, map_tprod, liftIsometry_apply_apply, lift.tprod, ContinuousMultilinearMap.coe_coe, ContinuousMultilinearMap.compContinuousLinearMap_apply] @[simp] theorem mapL_id : mapL (fun i ↦ ContinuousLinearMap.id 𝕜 (E i)) = ContinuousLinearMap.id _ _ := by apply ContinuousLinearMap.coe_injective ext simp only [mapL_coe, ContinuousLinearMap.coe_id, map_id, LinearMap.compMultilinearMap_apply, LinearMap.id_coe, id_eq] @[simp] theorem mapL_one : mapL (fun (i : ι) ↦ (1 : E i →L[𝕜] E i)) = 1 := mapL_id theorem mapL_mul (f₁ f₂ : Π i, E i →L[𝕜] E i) : mapL (fun i ↦ f₁ i * f₂ i) = mapL f₁ * mapL f₂ := mapL_comp f₁ f₂ /-- Upgrading `PiTensorProduct.mapL` to a `MonoidHom` when `E = E'`. -/ @[simps] noncomputable def mapLMonoidHom : (Π i, E i →L[𝕜] E i) →* ((⨂[𝕜] i, E i) →L[𝕜] ⨂[𝕜] i, E i) where toFun := mapL map_one' := mapL_one map_mul' := mapL_mul @[simp] protected theorem mapL_pow (f : Π i, E i →L[𝕜] E i) (n : ℕ) : mapL (f ^ n) = mapL f ^ n := MonoidHom.map_pow mapLMonoidHom f n -- We redeclare `ι` here, and later dependent arguments, -- to avoid the `[Fintype ι]` assumption present throughout the rest of the file. open Function in private theorem mapL_add_smul_aux {ι : Type uι} {E : ι → Type uE} [(i : ι) → SeminormedAddCommGroup (E i)] [(i : ι) → NormedSpace 𝕜 (E i)] {E' : ι → Type u_1} [(i : ι) → SeminormedAddCommGroup (E' i)] [(i : ι) → NormedSpace 𝕜 (E' i)] (f : (i : ι) → E i →L[𝕜] E' i) [DecidableEq ι] (i : ι) (u : E i →L[𝕜] E' i) : (fun j ↦ (update f i u j).toLinearMap) = update (fun j ↦ (f j).toLinearMap) i u.toLinearMap := by symm rw [update_eq_iff] grind [Function.update_of_ne, Function.update_self] open Function in protected theorem mapL_add [DecidableEq ι] (i : ι) (u v : E i →L[𝕜] E' i) : mapL (update f i (u + v)) = mapL (update f i u) + mapL (update f i v) := by ext x simp only [mapL_apply, mapL_add_smul_aux, ContinuousLinearMap.coe_add, PiTensorProduct.map_update_add, LinearMap.add_apply, ContinuousLinearMap.add_apply] open Function in protected theorem mapL_smul [DecidableEq ι] (i : ι) (c : 𝕜) (u : E i →L[𝕜] E' i) : mapL (update f i (c • u)) = c • mapL (update f i u) := by ext x simp only [mapL_apply, mapL_add_smul_aux, ContinuousLinearMap.coe_smul, PiTensorProduct.map_update_smul, LinearMap.smul_apply, ContinuousLinearMap.coe_smul', Pi.smul_apply] theorem mapL_opNorm : ‖mapL f‖ ≤ ∏ i, ‖f i‖ := by rw [ContinuousLinearMap.opNorm_le_iff (by positivity)] intro x rw [mapL, liftIsometry] simp only [LinearIsometryEquiv.coe_mk, liftEquiv_apply, LinearMap.mkContinuous_apply] refine le_trans (norm_eval_le_injectiveSeminorm _ _) (mul_le_mul_of_nonneg_right ?_ (norm_nonneg x)) rw [ContinuousMultilinearMap.opNorm_le_iff (Finset.prod_nonneg (fun _ _ ↦ norm_nonneg _))] intro m simp only [ContinuousMultilinearMap.compContinuousLinearMap_apply] refine le_trans (injectiveSeminorm_tprod_le (fun i ↦ (f i) (m i))) ?_ rw [← Finset.prod_mul_distrib] exact Finset.prod_le_prod (fun _ _ ↦ norm_nonneg _) (fun _ _ ↦ ContinuousLinearMap.le_opNorm _ _ ) variable (𝕜 E E') /-- The tensor of a family of linear maps from `Eᵢ` to `E'ᵢ`, as a continuous multilinear map of the family. -/ @[simps!] noncomputable def mapLMultilinear : ContinuousMultilinearMap 𝕜 (fun (i : ι) ↦ E i →L[𝕜] E' i) ((⨂[𝕜] i, E i) →L[𝕜] ⨂[𝕜] i, E' i) := MultilinearMap.mkContinuous { toFun := mapL map_update_smul' := fun _ _ _ _ ↦ PiTensorProduct.mapL_smul _ _ _ _ map_update_add' := fun _ _ _ _ ↦ PiTensorProduct.mapL_add _ _ _ _ } 1 (fun f ↦ by rw [one_mul]; exact mapL_opNorm f) variable {𝕜 E E'} theorem mapLMultilinear_opNorm : ‖mapLMultilinear 𝕜 E E'‖ ≤ 1 := MultilinearMap.mkContinuous_norm_le _ zero_le_one _ end map end PiTensorProduct
test_guard.v
From mathcomp Require Import all_boot. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Inductive tree := Node { children : seq tree }. Inductive ptree (T : Type) := singleton of T | branch of list (ptree T). (* has *) Fixpoint tree_has (T : Type) (p : pred T) (t : ptree T) : bool := match t with | singleton x => p x | branch ts => has (tree_has p) ts end. (* all *) Fixpoint tree_all (T : Type) (p : pred T) (t : ptree T) : bool := match t with | singleton x => p x | branch ts => all (tree_all p) ts end. (* map *) Fixpoint traverse_id (t : tree) : tree := Node (map traverse_id (children t)). (* foldr *) Fixpoint tree_foldr (T R : Type) (f : T -> R -> R) (z : R) (t : ptree T) : R := match t with | singleton x => f x z | branch ts => foldr (fun t z' => tree_foldr f z' t) z ts end. (* foldl *) Fixpoint tree_foldl (T R : Type) (f : R -> T -> R) (z : R) (t : ptree T) : R := match t with | singleton x => f z x | branch ts => foldl (tree_foldl f) z ts end. (* all2 *) Fixpoint eq_tree (x y : tree) {struct x} : bool := all2 eq_tree (children x) (children y).
Exactness.lean
/- Copyright (c) 2024 Sihan Su. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sihan Su, Yongle Hu, Yi Song -/ import Mathlib.Algebra.Exact import Mathlib.RingTheory.LocalProperties.Submodule import Mathlib.RingTheory.Localization.Away.Basic import Mathlib.Algebra.Module.LocalizedModule.AtPrime import Mathlib.Algebra.Module.LocalizedModule.Away /-! # Local properties about linear maps In this file, we show that injectivity, surjectivity, bijectivity and exactness of linear maps are local properties. More precisely, we show that these can be checked at maximal ideals and on standard covers. -/ open Submodule LocalizedModule Ideal LinearMap section isLocalized_maximal open IsLocalizedModule variable {R M N L : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] [AddCommMonoid L] [Module R L] variable (Mₚ : ∀ (P : Ideal R) [P.IsMaximal], Type*) [∀ (P : Ideal R) [P.IsMaximal], AddCommMonoid (Mₚ P)] [∀ (P : Ideal R) [P.IsMaximal], Module R (Mₚ P)] (f : ∀ (P : Ideal R) [P.IsMaximal], M →ₗ[R] Mₚ P) [∀ (P : Ideal R) [P.IsMaximal], IsLocalizedModule.AtPrime P (f P)] (Nₚ : ∀ (P : Ideal R) [P.IsMaximal], Type*) [∀ (P : Ideal R) [P.IsMaximal], AddCommMonoid (Nₚ P)] [∀ (P : Ideal R) [P.IsMaximal], Module R (Nₚ P)] (g : ∀ (P : Ideal R) [P.IsMaximal], N →ₗ[R] Nₚ P) [∀ (P : Ideal R) [P.IsMaximal], IsLocalizedModule.AtPrime P (g P)] (Lₚ : ∀ (P : Ideal R) [P.IsMaximal], Type*) [∀ (P : Ideal R) [P.IsMaximal], AddCommMonoid (Lₚ P)] [∀ (P : Ideal R) [P.IsMaximal], Module R (Lₚ P)] (h : ∀ (P : Ideal R) [P.IsMaximal], L →ₗ[R] Lₚ P) [∀ (P : Ideal R) [P.IsMaximal], IsLocalizedModule.AtPrime P (h P)] (F : M →ₗ[R] N) (G : N →ₗ[R] L) theorem injective_of_isLocalized_maximal (H : ∀ (P : Ideal R) [P.IsMaximal], Function.Injective (map P.primeCompl (f P) (g P) F)) : Function.Injective F := fun x y eq ↦ Module.eq_of_localization_maximal _ f _ _ fun P _ ↦ H P <| by simp [eq] theorem surjective_of_isLocalized_maximal (H : ∀ (P : Ideal R) [P.IsMaximal], Function.Surjective (map P.primeCompl (f P) (g P) F)) : Function.Surjective F := range_eq_top.mp <| eq_top_of_localization₀_maximal Nₚ g _ <| fun P _ ↦ (range_localizedMap_eq_localized₀_range _ (f P) (g P) F).symm.trans <| range_eq_top.mpr <| H P theorem bijective_of_isLocalized_maximal (H : ∀ (P : Ideal R) [P.IsMaximal], Function.Bijective (map P.primeCompl (f P) (g P) F)) : Function.Bijective F := ⟨injective_of_isLocalized_maximal Mₚ f Nₚ g F fun J _ ↦ (H J).1, surjective_of_isLocalized_maximal Mₚ f Nₚ g F fun J _ ↦ (H J).2⟩ theorem exact_of_isLocalized_maximal (H : ∀ (J : Ideal R) [J.IsMaximal], Function.Exact (map J.primeCompl (f J) (g J) F) (map J.primeCompl (g J) (h J) G)) : Function.Exact F G := by simp only [LinearMap.exact_iff] at H ⊢ apply eq_of_localization₀_maximal Nₚ g intro J hJ rw [← LinearMap.range_localizedMap_eq_localized₀_range _ (f J) (g J) F, ← LinearMap.ker_localizedMap_eq_localized₀_ker J.primeCompl (g J) (h J) G] have := SetLike.ext_iff.mp <| H J ext x simp only [mem_range, mem_ker] at this ⊢ exact this x end isLocalized_maximal section localized_maximal variable {R M N L : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] [AddCommMonoid L] [Module R L] (f : M →ₗ[R] N) (g : N →ₗ[R] L) theorem injective_of_localized_maximal (h : ∀ (J : Ideal R) [J.IsMaximal], Function.Injective (map J.primeCompl f)) : Function.Injective f := injective_of_isLocalized_maximal _ (fun _ _ ↦ mkLinearMap _ _) _ (fun _ _ ↦ mkLinearMap _ _) f h theorem surjective_of_localized_maximal (h : ∀ (J : Ideal R) [J.IsMaximal], Function.Surjective (map J.primeCompl f)) : Function.Surjective f := surjective_of_isLocalized_maximal _ (fun _ _ ↦ mkLinearMap _ _) _ (fun _ _ ↦ mkLinearMap _ _) f h theorem bijective_of_localized_maximal (h : ∀ (J : Ideal R) [J.IsMaximal], Function.Bijective (map J.primeCompl f)) : Function.Bijective f := ⟨injective_of_localized_maximal _ fun J _ ↦ (h J).1, surjective_of_localized_maximal _ fun J _ ↦ (h J).2⟩ theorem exact_of_localized_maximal (h : ∀ (J : Ideal R) [J.IsMaximal], Function.Exact (map J.primeCompl f) (map J.primeCompl g)) : Function.Exact f g := exact_of_isLocalized_maximal _ (fun _ _ ↦ mkLinearMap _ _) _ (fun _ _ ↦ mkLinearMap _ _) _ (fun _ _ ↦ mkLinearMap _ _) f g h end localized_maximal section isLocalized_span open IsLocalizedModule variable {R M N L : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] [AddCommMonoid L] [Module R L] (s : Set R) (spn : Ideal.span s = ⊤) include spn variable (Mₚ : ∀ _ : s, Type*) [∀ r : s, AddCommMonoid (Mₚ r)] [∀ r : s, Module R (Mₚ r)] (f : ∀ r : s, M →ₗ[R] Mₚ r) [∀ r : s, IsLocalizedModule.Away r.1 (f r)] (Nₚ : ∀ _ : s, Type*) [∀ r : s, AddCommMonoid (Nₚ r)] [∀ r : s, Module R (Nₚ r)] (g : ∀ r : s, N →ₗ[R] Nₚ r) [∀ r : s, IsLocalizedModule.Away r.1 (g r)] (Lₚ : ∀ _ : s, Type*) [∀ r : s, AddCommMonoid (Lₚ r)] [∀ r : s, Module R (Lₚ r)] (h : ∀ r : s, L →ₗ[R] Lₚ r) [∀ r : s, IsLocalizedModule.Away r.1 (h r)] (F : M →ₗ[R] N) (G : N →ₗ[R] L) theorem injective_of_isLocalized_span (H : ∀ r : s, Function.Injective (map (.powers r.1) (f r) (g r) F)) : Function.Injective F := fun x y eq ↦ Module.eq_of_isLocalized_span _ spn _ f _ _ fun P ↦ H P <| by simp [eq] theorem surjective_of_isLocalized_span (H : ∀ r : s, Function.Surjective (map (.powers r.1) (f r) (g r) F)) : Function.Surjective F := range_eq_top.mp <| eq_top_of_isLocalized₀_span s spn Nₚ g fun r ↦ (range_localizedMap_eq_localized₀_range _ (f r) (g r) F).symm.trans <| range_eq_top.mpr <| H r theorem bijective_of_isLocalized_span (H : ∀ r : s, Function.Bijective (map (.powers r.1) (f r) (g r) F)) : Function.Bijective F := ⟨injective_of_isLocalized_span _ spn Mₚ f Nₚ g F fun r ↦ (H r).1, surjective_of_isLocalized_span _ spn Mₚ f Nₚ g F fun r ↦ (H r).2⟩ lemma exact_of_isLocalized_span (H : ∀ r : s, Function.Exact (map (.powers r.1) (f r) (g r) F) (map (.powers r.1) (g r) (h r) G)) : Function.Exact F G := by simp only [LinearMap.exact_iff] at H ⊢ apply Submodule.eq_of_isLocalized₀_span s spn Nₚ g intro r rw [← LinearMap.range_localizedMap_eq_localized₀_range _ (f r) (g r) F] rw [← LinearMap.ker_localizedMap_eq_localized₀_ker (.powers r.1) (g r) (h r) G] have := SetLike.ext_iff.mp <| H r ext x simp only [mem_range, mem_ker] at this ⊢ exact this x end isLocalized_span section localized_span variable {R M N L : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] [AddCommMonoid L] [Module R L] (s : Set R) (spn : span s = ⊤) (f : M →ₗ[R] N) (g : N →ₗ[R] L) include spn theorem injective_of_localized_span (h : ∀ r : s, Function.Injective (map (.powers r.1) f)) : Function.Injective f := injective_of_isLocalized_span s spn _ (fun _ ↦ mkLinearMap _ _) _ (fun _ ↦ mkLinearMap _ _) f h theorem surjective_of_localized_span (h : ∀ r : s, Function.Surjective (map (.powers r.1) f)) : Function.Surjective f := surjective_of_isLocalized_span s spn _ (fun _ ↦ mkLinearMap _ _) _ (fun _ ↦ mkLinearMap _ _) f h theorem bijective_of_localized_span (h : ∀ r : s, Function.Bijective (map (.powers r.1) f)) : Function.Bijective f := ⟨injective_of_localized_span _ spn _ fun r ↦ (h r).1, surjective_of_localized_span _ spn _ fun r ↦ (h r).2⟩ lemma exact_of_localized_span (h : ∀ r : s, Function.Exact (map (.powers r.1) f) (map (.powers r.1) g)) : Function.Exact f g := exact_of_isLocalized_span s spn _ (fun _ ↦ mkLinearMap _ _) _ (fun _ ↦ mkLinearMap _ _) _ (fun _ ↦ mkLinearMap _ _) f g h end localized_span
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.
Preorder.lean
/- Copyright (c) 2017 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Kim Morrison, Johannes Hölzl, Reid Barton -/ import Mathlib.CategoryTheory.Equivalence import Mathlib.CategoryTheory.EqToHom import Mathlib.Order.Hom.Basic import Mathlib.Data.ULift /-! # Preorders as categories We install a category instance on any preorder. This is not to be confused with the category _of_ preorders, defined in `Order.Category.Preorder`. We show that monotone functions between preorders correspond to functors of the associated categories. ## Main definitions * `homOfLE` and `leOfHom` provide translations between inequalities in the preorder, and morphisms in the associated category. * `Monotone.functor` is the functor associated to a monotone function. -/ universe u v namespace Preorder open CategoryTheory -- see Note [lower instance priority] /-- The category structure coming from a preorder. There is a morphism `X ⟶ Y` if and only if `X ≤ Y`. Because we don't allow morphisms to live in `Prop`, we have to define `X ⟶ Y` as `ULift (PLift (X ≤ Y))`. See `CategoryTheory.homOfLE` and `CategoryTheory.leOfHom`. -/ @[stacks 00D3] instance (priority := 100) smallCategory (α : Type u) [Preorder α] : SmallCategory α where Hom U V := ULift (PLift (U ≤ V)) id X := ⟨⟨le_refl X⟩⟩ comp f g := ⟨⟨le_trans _ _ _ f.down.down g.down.down⟩⟩ instance subsingleton_hom {α : Type u} [Preorder α] (U V : α) : Subsingleton (U ⟶ V) := ⟨fun _ _ => ULift.ext _ _ (Subsingleton.elim _ _ )⟩ end Preorder namespace CategoryTheory open Opposite variable {X : Type u} [Preorder X] /-- Express an inequality as a morphism in the corresponding preorder category. -/ def homOfLE {x y : X} (h : x ≤ y) : x ⟶ y := ULift.up (PLift.up h) @[inherit_doc homOfLE] abbrev _root_.LE.le.hom := @homOfLE @[simp] theorem homOfLE_refl {x : X} (h : x ≤ x) : h.hom = 𝟙 x := rfl @[simp] theorem homOfLE_comp {x y z : X} (h : x ≤ y) (k : y ≤ z) : homOfLE h ≫ homOfLE k = homOfLE (h.trans k) := rfl /-- Extract the underlying inequality from a morphism in a preorder category. -/ theorem leOfHom {x y : X} (h : x ⟶ y) : x ≤ y := h.down.down @[nolint defLemma, inherit_doc leOfHom] abbrev _root_.Quiver.Hom.le := @leOfHom @[simp] theorem homOfLE_leOfHom {x y : X} (h : x ⟶ y) : h.le.hom = h := rfl lemma homOfLE_isIso_of_eq {x y : X} (h : x ≤ y) (heq : x = y) : IsIso (homOfLE h) := ⟨homOfLE (le_of_eq heq.symm), by simp⟩ @[simp, reassoc] lemma homOfLE_comp_eqToHom {a b c : X} (hab : a ≤ b) (hbc : b = c) : homOfLE hab ≫ eqToHom hbc = homOfLE (hab.trans (le_of_eq hbc)) := rfl @[simp, reassoc] lemma eqToHom_comp_homOfLE {a b c : X} (hab : a = b) (hbc : b ≤ c) : eqToHom hab ≫ homOfLE hbc = homOfLE ((le_of_eq hab).trans hbc) := rfl @[simp, reassoc] lemma homOfLE_op_comp_eqToHom {a b c : X} (hab : b ≤ a) (hbc : op b = op c) : (homOfLE hab).op ≫ eqToHom hbc = (homOfLE ((le_of_eq (op_injective hbc.symm)).trans hab)).op := rfl @[simp, reassoc] lemma eqToHom_comp_homOfLE_op {a b c : X} (hab : op a = op b) (hbc : c ≤ b) : eqToHom hab ≫ (homOfLE hbc).op = (homOfLE (hbc.trans (le_of_eq (op_injective hab.symm)))).op := rfl /-- Construct a morphism in the opposite of a preorder category from an inequality. -/ def opHomOfLE {x y : Xᵒᵖ} (h : unop x ≤ unop y) : y ⟶ x := (homOfLE h).op theorem le_of_op_hom {x y : Xᵒᵖ} (h : x ⟶ y) : unop y ≤ unop x := h.unop.le instance uniqueToTop [OrderTop X] {x : X} : Unique (x ⟶ ⊤) where default := homOfLE le_top uniq := fun a => by rfl instance uniqueFromBot [OrderBot X] {x : X} : Unique (⊥ ⟶ x) where default := homOfLE bot_le uniq := fun a => by rfl variable (X) in /-- The equivalence of categories from the order dual of a preordered type `X` to the opposite category of the preorder `X`. -/ @[simps] def orderDualEquivalence : Xᵒᵈ ≌ Xᵒᵖ where functor := { obj := fun x => op (OrderDual.ofDual x) map := fun f => (homOfLE (leOfHom f)).op } inverse := { obj := fun x => OrderDual.toDual x.unop map := fun f => (homOfLE (leOfHom f.unop)) } unitIso := Iso.refl _ counitIso := Iso.refl _ end CategoryTheory section open CategoryTheory variable {X : Type u} {Y : Type v} [Preorder X] [Preorder Y] /-- A monotone function between preorders induces a functor between the associated categories. -/ def Monotone.functor {f : X → Y} (h : Monotone f) : X ⥤ Y where obj := f map g := CategoryTheory.homOfLE (h g.le) @[simp] theorem Monotone.functor_obj {f : X → Y} (h : Monotone f) : h.functor.obj = f := rfl -- Faithfulness is automatic because preorder categories are thin instance (f : X ↪o Y) : f.monotone.functor.Full where map_surjective h := ⟨homOfLE (f.map_rel_iff.1 h.le), rfl⟩ /-- The equivalence of categories `X ≌ Y` induced by `e : X ≃o Y`. -/ @[simps] def OrderIso.equivalence (e : X ≃o Y) : X ≌ Y where functor := e.monotone.functor inverse := e.symm.monotone.functor unitIso := NatIso.ofComponents (fun _ ↦ eqToIso (by simp)) counitIso := NatIso.ofComponents (fun _ ↦ eqToIso (by simp)) end section Preorder variable {X : Type u} {Y : Type v} [Preorder X] [Preorder Y] namespace CategoryTheory.Functor /-- A functor between preorder categories is monotone. -/ @[mono] theorem monotone (f : X ⥤ Y) : Monotone f.obj := fun _ _ hxy => (f.map hxy.hom).le /-- A functor `X ⥤ Y` between preorder categories as an `OrderHom`. -/ @[simps!] def toOrderHom (F : X ⥤ Y) : X →o Y where toFun := F.obj monotone' := F.monotone end CategoryTheory.Functor namespace OrderHom open CategoryTheory /-- An `OrderHom` as a functor `X ⥤ Y` between preorder categories. -/ abbrev toFunctor (f : X →o Y) : X ⥤ Y := f.monotone.functor /-- The equivalence between `X →o Y` and the type of functors `X ⥤ Y` between preorder categories `X` and `Y`. -/ @[simps] def equivFunctor : (X →o Y) ≃ (X ⥤ Y) where toFun := toFunctor invFun F := F.toOrderHom /-- The categorical equivalence between the category of monotone functions `X →o Y` and the category of functors `X ⥤ Y`, where `X` and `Y` are preorder categories. -/ @[simps! functor_obj_obj inverse_obj unitIso_hom_app unitIso_inv_app counitIso_inv_app_app counitIso_hom_app_app] def equivalenceFunctor : (X →o Y) ≌ (X ⥤ Y) where functor := { obj f := f.toFunctor map f := { app x := homOfLE <| leOfHom f x } } inverse := { obj F := F.toOrderHom map f := homOfLE fun x ↦ leOfHom <| f.app x } unitIso := Iso.refl _ counitIso := Iso.refl _ end OrderHom end Preorder section PartialOrder namespace CategoryTheory variable {X : Type u} {Y : Type v} [PartialOrder X] [PartialOrder Y] theorem Iso.to_eq {x y : X} (f : x ≅ y) : x = y := le_antisymm f.hom.le f.inv.le /-- A categorical equivalence between partial orders is just an order isomorphism. -/ def Equivalence.toOrderIso (e : X ≌ Y) : X ≃o Y where toFun := e.functor.obj invFun := e.inverse.obj left_inv a := (e.unitIso.app a).to_eq.symm right_inv b := (e.counitIso.app b).to_eq map_rel_iff' {a a'} := ⟨fun h => ((Equivalence.unit e).app a ≫ e.inverse.map h.hom ≫ (Equivalence.unitInv e).app a').le, fun h : a ≤ a' => (e.functor.map h.hom).le⟩ -- `@[simps]` on `Equivalence.toOrderIso` produces lemmas that fail the `simpNF` linter, -- so we provide them by hand: @[simp] theorem Equivalence.toOrderIso_apply (e : X ≌ Y) (x : X) : e.toOrderIso x = e.functor.obj x := rfl @[simp] theorem Equivalence.toOrderIso_symm_apply (e : X ≌ Y) (y : Y) : e.toOrderIso.symm y = e.inverse.obj y := rfl end CategoryTheory end PartialOrder open CategoryTheory lemma PartialOrder.isIso_iff_eq {X : Type u} [PartialOrder X] {a b : X} (f : a ⟶ b) : IsIso f ↔ a = b := by constructor · intro _ exact (asIso f).to_eq · rintro rfl rw [Subsingleton.elim f (𝟙 _)] infer_instance
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 ].
Bifunctor.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.CategoryTheory.Localization.Prod import Mathlib.CategoryTheory.Functor.Currying /-! # Lifting of bifunctors In this file, in the context of the localization of categories, we extend the notion of lifting of functors to the case of bifunctors. As the localization of categories behaves well with respect to finite products of categories (when the classes of morphisms contain identities), all the definitions for bifunctors `C₁ ⥤ C₂ ⥤ E` are obtained by reducing to the case of functors `(C₁ × C₂) ⥤ E` by using currying and uncurrying. Given morphism properties `W₁ : MorphismProperty C₁` and `W₂ : MorphismProperty C₂`, and a functor `F : C₁ ⥤ C₂ ⥤ E`, we define `MorphismProperty.IsInvertedBy₂ W₁ W₂ F` as the condition that the functor `uncurry.obj F : C₁ × C₂ ⥤ E` inverts `W₁.prod W₂`. If `L₁ : C₁ ⥤ D₁` and `L₂ : C₂ ⥤ D₂` are localization functors for `W₁` and `W₂` respectively, and `F : C₁ ⥤ C₂ ⥤ E` satisfies `MorphismProperty.IsInvertedBy₂ W₁ W₂ F`, we introduce `Localization.lift₂ F hF L₁ L₂ : D₁ ⥤ D₂ ⥤ E` which is a bifunctor which lifts `F`. -/ namespace CategoryTheory open Category Functor variable {C₁ C₂ D₁ D₂ E E' : Type*} [Category C₁] [Category C₂] [Category D₁] [Category D₂] [Category E] [Category E'] namespace MorphismProperty /-- Classes of morphisms `W₁ : MorphismProperty C₁` and `W₂ : MorphismProperty C₂` are said to be inverted by `F : C₁ ⥤ C₂ ⥤ E` if `W₁.prod W₂` is inverted by the functor `uncurry.obj F : C₁ × C₂ ⥤ E`. -/ def IsInvertedBy₂ (W₁ : MorphismProperty C₁) (W₂ : MorphismProperty C₂) (F : C₁ ⥤ C₂ ⥤ E) : Prop := (W₁.prod W₂).IsInvertedBy (uncurry.obj F) end MorphismProperty namespace Localization section variable (L₁ : C₁ ⥤ D₁) (L₂ : C₂ ⥤ D₂) /-- Given functors `L₁ : C₁ ⥤ D₁`, `L₂ : C₂ ⥤ D₂`, morphisms properties `W₁` on `C₁` and `W₂` on `C₂`, and functors `F : C₁ ⥤ C₂ ⥤ E` and `F' : D₁ ⥤ D₂ ⥤ E`, we say `Lifting₂ L₁ L₂ W₁ W₂ F F'` holds if `F` is induced by `F'`, up to an isomorphism. -/ class Lifting₂ (W₁ : MorphismProperty C₁) (W₂ : MorphismProperty C₂) (F : C₁ ⥤ C₂ ⥤ E) (F' : D₁ ⥤ D₂ ⥤ E) where /-- the isomorphism `(((whiskeringLeft₂ E).obj L₁).obj L₂).obj F' ≅ F` expressing that `F` is induced by `F'` up to an isomorphism -/ iso' : (((whiskeringLeft₂ E).obj L₁).obj L₂).obj F' ≅ F variable (W₁ : MorphismProperty C₁) (W₂ : MorphismProperty C₂) (F : C₁ ⥤ C₂ ⥤ E) (F' : D₁ ⥤ D₂ ⥤ E) [Lifting₂ L₁ L₂ W₁ W₂ F F'] /-- The isomorphism `(((whiskeringLeft₂ E).obj L₁).obj L₂).obj F' ≅ F` when `Lifting₂ L₁ L₂ W₁ W₂ F F'` holds. -/ noncomputable def Lifting₂.iso : (((whiskeringLeft₂ E).obj L₁).obj L₂).obj F' ≅ F := Lifting₂.iso' W₁ W₂ /-- If `Lifting₂ L₁ L₂ W₁ W₂ F F'` holds, then `Lifting L₂ W₂ (F.obj X₁) (F'.obj (L₁.obj X₁))` holds for any `X₁ : C₁`. -/ noncomputable def Lifting₂.fst (X₁ : C₁) : Lifting L₂ W₂ (F.obj X₁) (F'.obj (L₁.obj X₁)) where iso' := ((evaluation _ _).obj X₁).mapIso (Lifting₂.iso L₁ L₂ W₁ W₂ F F') noncomputable instance Lifting₂.flip : Lifting₂ L₂ L₁ W₂ W₁ F.flip F'.flip where iso' := (flipFunctor _ _ _).mapIso (Lifting₂.iso L₁ L₂ W₁ W₂ F F') /-- If `Lifting₂ L₁ L₂ W₁ W₂ F F'` holds, then `Lifting L₁ W₁ (F.flip.obj X₂) (F'.flip.obj (L₂.obj X₂))` holds for any `X₂ : C₂`. -/ noncomputable def Lifting₂.snd (X₂ : C₂) : Lifting L₁ W₁ (F.flip.obj X₂) (F'.flip.obj (L₂.obj X₂)) := Lifting₂.fst L₂ L₁ W₂ W₁ F.flip F'.flip X₂ noncomputable instance Lifting₂.uncurry [Lifting₂ L₁ L₂ W₁ W₂ F F'] : Lifting (L₁.prod L₂) (W₁.prod W₂) (uncurry.obj F) (uncurry.obj F') where iso' := Functor.uncurry.mapIso (Lifting₂.iso L₁ L₂ W₁ W₂ F F') end section variable (F : C₁ ⥤ C₂ ⥤ E) {W₁ : MorphismProperty C₁} {W₂ : MorphismProperty C₂} (hF : MorphismProperty.IsInvertedBy₂ W₁ W₂ F) (L₁ : C₁ ⥤ D₁) (L₂ : C₂ ⥤ D₂) [L₁.IsLocalization W₁] [L₂.IsLocalization W₂] [W₁.ContainsIdentities] [W₂.ContainsIdentities] /-- Given localization functor `L₁ : C₁ ⥤ D₁` and `L₂ : C₂ ⥤ D₂` with respect to `W₁ : MorphismProperty C₁` and `W₂ : MorphismProperty C₂` respectively, and a bifunctor `F : C₁ ⥤ C₂ ⥤ E` which inverts `W₁` and `W₂`, this is the induced localized bifunctor `D₁ ⥤ D₂ ⥤ E`. -/ noncomputable def lift₂ : D₁ ⥤ D₂ ⥤ E := curry.obj (lift (uncurry.obj F) hF (L₁.prod L₂)) noncomputable instance : Lifting₂ L₁ L₂ W₁ W₂ F (lift₂ F hF L₁ L₂) where iso' := (curryObjProdComp _ _ _).symm ≪≫ curry.mapIso (fac (uncurry.obj F) hF (L₁.prod L₂)) ≪≫ currying.unitIso.symm.app F noncomputable instance Lifting₂.liftingLift₂ (X₁ : C₁) : Lifting L₂ W₂ (F.obj X₁) ((lift₂ F hF L₁ L₂).obj (L₁.obj X₁)) := Lifting₂.fst _ _ W₁ _ _ _ _ noncomputable instance Lifting₂.liftingLift₂Flip (X₂ : C₂) : Lifting L₁ W₁ (F.flip.obj X₂) ((lift₂ F hF L₁ L₂).flip.obj (L₂.obj X₂)) := Lifting₂.snd _ _ _ W₂ _ _ _ lemma lift₂_iso_hom_app_app₁ (X₁ : C₁) (X₂ : C₂) : ((Lifting₂.iso L₁ L₂ W₁ W₂ F (lift₂ F hF L₁ L₂)).hom.app X₁).app X₂ = (Lifting.iso L₂ W₂ (F.obj X₁) ((lift₂ F hF L₁ L₂).obj (L₁.obj X₁))).hom.app X₂ := rfl lemma lift₂_iso_hom_app_app₂ (X₁ : C₁) (X₂ : C₂) : ((Lifting₂.iso L₁ L₂ W₁ W₂ F (lift₂ F hF L₁ L₂)).hom.app X₁).app X₂ = (Lifting.iso L₁ W₁ (F.flip.obj X₂) ((lift₂ F hF L₁ L₂).flip.obj (L₂.obj X₂))).hom.app X₁ := rfl end section variable (L₁ : C₁ ⥤ D₁) (L₂ : C₂ ⥤ D₂) (W₁ : MorphismProperty C₁) (W₂ : MorphismProperty C₂) [L₁.IsLocalization W₁] [L₂.IsLocalization W₂] [W₁.ContainsIdentities] [W₂.ContainsIdentities] (F₁ F₂ : C₁ ⥤ C₂ ⥤ E) (F₁' F₂' : D₁ ⥤ D₂ ⥤ E) [Lifting₂ L₁ L₂ W₁ W₂ F₁ F₁'] [Lifting₂ L₁ L₂ W₁ W₂ F₂ F₂'] /-- The natural transformation `F₁' ⟶ F₂'` of bifunctors induced by a natural transformation `τ : F₁ ⟶ F₂` when `Lifting₂ L₁ L₂ W₁ W₂ F₁ F₁'` and `Lifting₂ L₁ L₂ W₁ W₂ F₂ F₂'` hold. -/ noncomputable def lift₂NatTrans (τ : F₁ ⟶ F₂) : F₁' ⟶ F₂' := fullyFaithfulUncurry.preimage (liftNatTrans (L₁.prod L₂) (W₁.prod W₂) (uncurry.obj F₁) (uncurry.obj F₂) (uncurry.obj F₁') (uncurry.obj F₂') (uncurry.map τ)) @[simp] theorem lift₂NatTrans_app_app (τ : F₁ ⟶ F₂) (X₁ : C₁) (X₂ : C₂) : ((lift₂NatTrans L₁ L₂ W₁ W₂ F₁ F₂ F₁' F₂' τ).app (L₁.obj X₁)).app (L₂.obj X₂) = ((Lifting₂.iso L₁ L₂ W₁ W₂ F₁ F₁').hom.app X₁).app X₂ ≫ (τ.app X₁).app X₂ ≫ ((Lifting₂.iso L₁ L₂ W₁ W₂ F₂ F₂').inv.app X₁).app X₂ := by dsimp [lift₂NatTrans, fullyFaithfulUncurry, Equivalence.fullyFaithfulFunctor] simp only [comp_id, id_comp] exact liftNatTrans_app _ _ _ _ (uncurry.obj F₁') (uncurry.obj F₂') (uncurry.map τ) ⟨X₁, X₂⟩ variable {F₁' F₂'} in include W₁ W₂ in theorem natTrans₂_ext {τ τ' : F₁' ⟶ F₂'} (h : ∀ (X₁ : C₁) (X₂ : C₂), (τ.app (L₁.obj X₁)).app (L₂.obj X₂) = (τ'.app (L₁.obj X₁)).app (L₂.obj X₂)) : τ = τ' := uncurry.map_injective (natTrans_ext (L₁.prod L₂) (W₁.prod W₂) (fun _ ↦ h _ _)) /-- The natural isomorphism `F₁' ≅ F₂'` of bifunctors induced by a natural isomorphism `e : F₁ ≅ F₂` when `Lifting₂ L₁ L₂ W₁ W₂ F₁ F₁'` and `Lifting₂ L₁ L₂ W₁ W₂ F₂ F₂'` hold. -/ noncomputable def lift₂NatIso (e : F₁ ≅ F₂) : F₁' ≅ F₂' where hom := lift₂NatTrans L₁ L₂ W₁ W₂ F₁ F₂ F₁' F₂' e.hom inv := lift₂NatTrans L₁ L₂ W₁ W₂ F₂ F₁ F₂' F₁' e.inv hom_inv_id := natTrans₂_ext L₁ L₂ W₁ W₂ (by simp) inv_hom_id := natTrans₂_ext L₁ L₂ W₁ W₂ (by simp) end end Localization end CategoryTheory
peel.lean
import Mathlib.Tactic.Peel import Mathlib.Topology.Instances.Real.Lemmas open Filter Topology /-! ## General usage -/ example (p q : Nat → Prop) (h₁ : ∀ x, p x) (h₂ : ∀ x, p x → q x) : ∀ y, q y := by peel 1 h₁ rename_i y guard_target =ₐ q y exact h₂ _ this example (p q : Nat → Prop) (h₁ : ∀ {x}, p x) (h₂ : ∀ x, p x → q x) : ∀ y, q y := by peel 1 h₁ rename_i y guard_target =ₐ q y exact h₂ _ this example (p q : Nat → Nat → Prop) (h₁ : ∀ {x y}, p x y) (h₂ : ∀ x y, p x y → q x y) : ∀ u v, q u v := by peel 2 h₁ rename_i u v guard_target =ₐ q u v exact h₂ _ _ this example (p q : Nat → Prop) (h₁ : ∀ x, p x) (h₂ : ∀ x, p x → q x) : ∀ y, q y := by peel h₁ rename_i y guard_target =ₐ q y exact h₂ _ this example (p q : Nat → Prop) (h₁ : ∀ x, p x) (h₂ : ∀ x, p x → q x) : ∀ y, q y := by peel h₁ using h₂ _ this example (p q : Nat → Nat → Prop) (h₁ : ∀ x y, p x y) (h₂ : ∀ x y, p x y → q x y) : ∀ u v, q u v := by peel h₁ rename_i u v guard_target =ₐ q u v exact h₂ _ _ this example (p q : Nat → Prop) (h₁ : ∀ x, p x) (h₂ : ∀ x, p x → q x) : ∀ y, q y := by peel h₁ with foo rename_i y guard_target =ₐ q y exact h₂ _ foo example (p q : Nat → Prop) (h₁ : ∀ x, p x) (h₂ : ∀ x, p x → q x) : ∀ y, q y := by peel h₁ with w foo guard_target =ₐ q w exact h₂ w foo example (p q : Nat → Prop) (h₁ : ∀ x, p x) (h₂ : ∀ x, p x → q x) : ∀ y, q y := by peel h₁ with _ foo rename_i w guard_target =ₐ q w exact h₂ w foo example (p q : Nat → Prop) (h₁ : ∀ x, p x) (h₂ : ∀ x, p x → q x) : ∀ y, q y := by peel h₁ with w _ guard_target =ₐ q w exact h₂ w this example (p q : Nat → Nat → Prop) (h₁ : ∀ x y, p x y) (h₂ : ∀ x y, p x y → q x y) : ∀ u v, q u v := by peel h₁ with s t h_peel guard_target =ₐ q s t exact h₂ s t h_peel example (p q : Nat → Prop) (h : ∀ y, p y) (h₁ : ∀ z, p z → q z) : ∀ x, q x := by peel h rename_i x guard_target =ₐ q x exact h₁ _ <| by assumption example (p q : Nat → Prop) (h : ∃ y, p y) (h₁ : ∀ z, p z → q z) : ∃ x, q x := by peel h with a h guard_target =ₐ q a exact h₁ a h example (x y : ℝ) (h : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x + n = y + ε) : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x - ε = y - n := by peel h with ε hε N n hn h_peel guard_target =ₐ x - ε = y - n linarith set_option linter.unusedTactic false in example (x y : ℝ) (h : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x + n = y + ε) : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x - ε = y - n := by peel h fail_if_success peel 2 this peel 0 this fail_if_success peel this linarith example (p q : ℝ → ℝ → Prop) (h : ∀ ε > 0, ∃ δ > 0, p ε δ) (hpq : ∀ x y, x > 0 → y > 0 → p x y → q x y) : ∀ ε > 0, ∃ δ > 0, q ε δ := by peel h with ε hε δ hδ h guard_target =ₐ q ε δ exact hpq ε δ hε hδ h example (p q : ℝ → ℝ → Prop) (h : ∀ ε > 0, ∃ δ > 0, p ε δ) (hpq : ∀ x y, x > 0 → y > 0 → p x y → q x y) : ∀ ε > 0, ∃ δ > 0, q ε δ := by peel h with ε hε δ hδ h using hpq ε δ hε hδ h example (x y : ℝ) : (∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x + n = y + ε) ↔ ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x - ε = y - n := by peel 5 constructor all_goals intro linarith /-! ## Usage after other tactics and with multiple goals -/ example : (∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1 / (n + 1 : ℚ) < ε) ↔ ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1 / (n + 1 : ℚ) ≤ ε := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · peel 5 h exact this.le · intro ε hε peel 3 h (ε / 2) (half_pos hε) exact this.trans_lt (half_lt_self hε) example : (∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1 / (n + 1 : ℚ) < ε) ↔ ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1 / (n + 1 : ℚ) ≤ ε := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · peel 5 h using this.le · intro ε hε peel 3 h (ε / 2) (half_pos hε) using this.trans_lt (half_lt_self hε) /-! ## Use with `↔` goals -/ example (x y : ℚ) (h : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x + n = y + ε) : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x - ε = y - n := by intro ε hε peel 3 (h ε hε) rename_i _ n _ guard_hyp this : x + ↑n = y + ε guard_target =ₐ x - ε = y - n linarith example (x y : ℝ) : (∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x + n = y + ε) ↔ ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x - ε = y - n := by peel with ε hε N n hn constructor all_goals intro linarith example : (∃ k > 0, ∃ n ≥ k, n = k) ↔ ∃ k > 0, ∃ n ≥ k, k = n := by peel 4 exact eq_comm /-! ## Eventually and frequently -/ example {f : ℝ → ℝ} (h : ∀ x : ℝ, ∀ᶠ y in 𝓝 x, |f y - f x| ≤ |y - x|) : ∀ x : ℝ, ∀ᶠ y in 𝓝 x, |f y - f x| ^ 2 ≤ |y - x| ^ 2 := by peel h with h_peel x y gcongr example (α : Type*) (f g : Filter α) (p q : α → α → Prop) (h : ∀ᶠ x in f, ∃ᶠ y in g, p x y) (h₁ : ∀ x y, p x y → q x y) : ∀ᶠ x in f, ∃ᶠ y in g, q x y := by peel h with x y h_peel exact h₁ x y h_peel example (α : Type*) (f : Filter α) (p q : α → Prop) (h : ∀ᶠ x in f, p x) (h₁ : ∀ x, p x → q x) : ∀ᶠ x in f, q x := by peel h with x h_peel exact h₁ x h_peel /-! ## Type classes -/ example {R : Type*} [CommRing R] (h : ∀ x : R, ∃ y : R, x + y = 2) : ∀ x : R, ∃ y : R, (x + y) ^ 2 = 4 := by peel 2 h rw [this] ring example {G : Type*} [Group G] [TopologicalSpace G] [IsTopologicalGroup G] (h : ∀ᶠ x in 𝓝 (1 : G), ∃ᶠ y in 𝓝 x, x * y⁻¹ = 1) : ∀ᶠ x in 𝓝 (1 : G), ∃ᶠ y in 𝓝 x, x ^ 2 = y ^ 2 := by peel h with a b h_peel observe : a = b⁻¹⁻¹ simp [this] /-! ## Unfolding definitions -/ example {α β γ : Type*} {f : α → β} {g : β → γ} (h : Function.Injective (g ∘ f)) : Function.Injective f := by peel 2 h with x y _ intro hf apply this congrm(g $hf) example {α β γ : Type*} {f : α → β} {g : β → γ} (h : Function.Surjective (g ∘ f)) : Function.Surjective g := by peel 1 h with y _ fail_if_success peel this obtain ⟨x, rfl⟩ := this exact ⟨f x, rfl⟩ def toInf (f : ℕ → ℕ) : Prop := ∀ m, ∃ n, ∀ n' ≥ n, m ≤ f n' example (f : ℕ → ℕ) (h : toInf f) : toInf (fun n => 2 * f n) := by peel h with this m n n' h dsimp linarith /-! ## Error messages -/ /-- error: Tactic 'peel' could not match quantifiers in x = y and x = y -/ #guard_msgs in example (x y : ℝ) (h : x = y) : x = y := by peel h /-- error: Tactic 'peel' could not match quantifiers in ∃ y, ∀ (x : ℕ), x ≠ y and ∀ (x : ℕ), ∃ y, x ≠ y -/ #guard_msgs in example (h : ∃ y : ℕ, ∀ x, x ≠ y) : ∀ x : ℕ, ∃ y, x ≠ y := by peel h /-- error: Tactic 'peel' could not match quantifiers in ∀ (n : ℕ), 0 ≤ n and ∀ (n : ℤ), 0 ≤ n -/ #guard_msgs in example (h : ∀ n : ℕ, 0 ≤ n) : ∀ n : ℤ, 0 ≤ n := by peel h /-- error: Tactic 'peel' could not match quantifiers in ∃ n, 0 ≤ n and ∃ n, 0 ≤ n -/ #guard_msgs in example (h : ∃ n : ℕ, 0 ≤ n) : ∃ n : ℤ, 0 ≤ n := by peel 1 h /-- error: Tactic 'peel' could not match quantifiers in ∃ᶠ (n : ℕ) in atTop, 0 ≤ n and ∃ᶠ (n : ℕ) in atBot, 0 ≤ n -/ #guard_msgs in example (h : ∃ᶠ n : ℕ in atTop, 0 ≤ n) : ∃ᶠ n : ℕ in atBot, 0 ≤ n := by peel 1 h /-- error: Tactic 'peel' could not match quantifiers in ∀ᶠ (n : ℕ) in atTop, 0 ≤ n and ∀ᶠ (n : ℕ) in atBot, 0 ≤ n -/ #guard_msgs in example (h : ∀ᶠ n : ℕ in atTop, 0 ≤ n) : ∀ᶠ n : ℕ in atBot, 0 ≤ n := by peel 1 h /-! Testing **gcongr** on peel goals -/ example (p q : ℝ → ℝ → Prop) (h : ∀ ε > 0, ∃ δ > 0, p ε δ) (hpq : ∀ x y, x > 0 → y > 0 → p x y → q x y) : ∀ ε > 0, ∃ δ > 0, q ε δ := by revert h gcongr with ε hε δ hδ exact hpq ε δ hε hδ example (x y : ℚ) (h : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x + n = y + ε) : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, x - ε = y - n := by revert h gcongr ∀ ε > 0, ∃ N, ∀ n ≥ _, ?_ with ε hε _ n hn intro this guard_hyp this : x + ↑n = y + ε guard_target =ₐ x - ε = y - n linarith example {f : ℝ → ℝ} (h : ∀ x : ℝ, ∀ᶠ y in 𝓝 x, |f y - f x| ≤ |y - x|) : ∀ x : ℝ, ∀ᶠ y in 𝓝 x, |f y - f x| ^ 2 ≤ |y - x| ^ 2 := by revert h gcongr ∀ x, ∀ᶠ y in _, ?_ intro gcongr example (α : Type*) (f g : Filter α) (p q : α → α → Prop) (h : ∀ᶠ x in f, ∃ᶠ y in g, p x y) (h₁ : ∀ x y, p x y → q x y) : ∀ᶠ x in f, ∃ᶠ y in g, q x y := by revert h gcongr apply h₁
MulEquivHaarChar.lean
/- Copyright (c) 2025 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import Mathlib.MeasureTheory.Measure.Haar.Unique /-! # Scaling Haar measure by a continuous isomorphism If `G` is a locally compact topological group and `μ` is a regular Haar measure on `G`, then an isomorphism `φ : G ≃ₜ* G` scales this measure by some positive real constant which we call `mulEquivHaarChar φ`. ## Main definitions * `mulEquivHaarChar φ`: the positive real such that `(mulEquivHaarChar φ) • map φ μ = μ` for `μ` a regular Haar measure. * `addEquivAddHaarChar φ`: the additive version. -/ open MeasureTheory.Measure open scoped NNReal Pointwise ENNReal namespace MeasureTheory variable {G : Type*} [Group G] [TopologicalSpace G] [MeasurableSpace G] [BorelSpace G] [IsTopologicalGroup G] [LocallyCompactSpace G] /-- If `φ : G ≃ₜ* G` then `mulEquivHaarChar φ` is the positive real factor by which `φ` scales Haar measures on `G`. -/ @[to_additive /-- If `φ : A ≃ₜ+ A` then `addEquivAddHaarChar φ` is the positive real factor by which `φ` scales Haar measures on `A`. -/] noncomputable def mulEquivHaarChar (φ : G ≃ₜ* G) : ℝ≥0 := haarScalarFactor haar (haar.map φ) @[to_additive] lemma mulEquivHaarChar_pos (φ : G ≃ₜ* G) : 0 < mulEquivHaarChar φ := haarScalarFactor_pos_of_isHaarMeasure _ _ @[to_additive] lemma mulEquivHaarChar_eq (μ : Measure G) [IsHaarMeasure μ] [Regular μ] (φ : G ≃ₜ* G) : mulEquivHaarChar φ = haarScalarFactor μ (μ.map φ) := by have smul := isMulLeftInvariant_eq_smul_of_regular haar μ unfold mulEquivHaarChar conv => enter [1, 1] rw [smul] conv => enter [1, 2, 2] rw [smul] simp_rw [MeasureTheory.Measure.map_smul] exact haarScalarFactor_smul_smul _ _ (haarScalarFactor_pos_of_isHaarMeasure haar μ).ne' @[to_additive addEquivAddHaarChar_smul_map] lemma mulEquivHaarChar_smul_map (μ : Measure G) [IsHaarMeasure μ] [Regular μ] (φ : G ≃ₜ* G) : mulEquivHaarChar φ • μ.map φ = μ := by rw [mulEquivHaarChar_eq μ φ] have : Regular (map φ μ) := Regular.map φ.toHomeomorph exact (isMulLeftInvariant_eq_smul_of_regular μ (map φ μ)).symm @[to_additive addEquivAddHaarChar_smul_eq_comap] lemma mulEquivHaarChar_smul_eq_comap (μ : Measure G) [IsHaarMeasure μ] [Regular μ] (φ : G ≃ₜ* G) : (mulEquivHaarChar φ) • μ = μ.comap φ := by let e := φ.toHomeomorph.toMeasurableEquiv rw [show ⇑φ = ⇑e from rfl, ← e.map_symm, show ⇑e.symm = ⇑φ.symm from rfl] have : (map (φ.symm) μ).Regular := Regular.map φ.symm.toHomeomorph rw [← mulEquivHaarChar_smul_map (map φ.symm μ) φ, map_map] · simp · fun_prop · fun_prop @[to_additive addEquivAddHaarChar_smul_integral_map] lemma mulEquivHaarChar_smul_integral_map (μ : Measure G) [IsHaarMeasure μ] [Regular μ] {f : G → ℝ} (φ : G ≃ₜ* G) : mulEquivHaarChar φ • ∫ a, f a ∂(μ.map φ) = ∫ a, f a ∂μ := by nth_rw 2 [← mulEquivHaarChar_smul_map μ φ] simp @[to_additive integral_comap_eq_addEquivAddHaarChar_smul] lemma integral_comap_eq_mulEquivHaarChar_smul (μ : Measure G) [IsHaarMeasure μ] [Regular μ] {f : G → ℝ} (φ : G ≃ₜ* G) : ∫ a, f a ∂(μ.comap φ) = mulEquivHaarChar φ • ∫ a, f a ∂μ := by let e := φ.toHomeomorph.toMeasurableEquiv change ∫ a, f a ∂(comap e μ) = mulEquivHaarChar φ • ∫ a, f a ∂μ have : (map (e.symm) μ).IsHaarMeasure := φ.symm.isHaarMeasure_map μ have : (map (e.symm) μ).Regular := Regular.map φ.symm.toHomeomorph rw [← e.map_symm, ← mulEquivHaarChar_smul_integral_map (map e.symm μ) φ, map_map (by exact φ.toHomeomorph.toMeasurableEquiv.measurable) e.symm.measurable] -- congr -- breaks to_additive rw [show ⇑φ ∘ ⇑e.symm = id by ext; simp [e]] simp @[to_additive addEquivAddHaarChar_smul_preimage] lemma mulEquivHaarChar_smul_preimage (μ : Measure G) [IsHaarMeasure μ] [Regular μ] {X : Set G} (φ : G ≃ₜ* G) : mulEquivHaarChar φ • μ (φ ⁻¹' X) = μ X := by nth_rw 2 [← mulEquivHaarChar_smul_map μ φ] simp only [smul_apply, nnreal_smul_coe_apply] exact congr_arg _ <| (MeasurableEquiv.map_apply φ.toMeasurableEquiv X).symm @[to_additive (attr := simp)] lemma mulEquivHaarChar_refl : mulEquivHaarChar (ContinuousMulEquiv.refl G) = 1 := by simp [mulEquivHaarChar, Function.id_def] @[to_additive] lemma mulEquivHaarChar_trans {φ ψ : G ≃ₜ* G} : mulEquivHaarChar (ψ.trans φ) = mulEquivHaarChar ψ * mulEquivHaarChar φ := by rw [mulEquivHaarChar_eq haar ψ, mulEquivHaarChar_eq haar (ψ.trans φ)] have hφ : Measurable φ := by fun_prop have hψ : Measurable ψ := by fun_prop simp_rw [ContinuousMulEquiv.coe_trans, ← map_map hφ hψ] have h_reg : (haar.map ψ).Regular := Regular.map ψ.toHomeomorph rw [MeasureTheory.Measure.haarScalarFactor_eq_mul haar (haar.map ψ), ← mulEquivHaarChar_eq (haar.map ψ)] end MeasureTheory
Commute.lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.GroupWithZero.Commute import Mathlib.Algebra.Ring.Commute /-! # Cast of natural numbers: lemmas about `Commute` -/ variable {α : Type*} namespace Nat section Commute variable [NonAssocSemiring α] theorem cast_commute (n : ℕ) (x : α) : Commute (n : α) x := by induction n with | zero => rw [Nat.cast_zero]; exact Commute.zero_left x | succ n ihn => rw [Nat.cast_succ]; exact ihn.add_left (Commute.one_left x) theorem _root_.Commute.ofNat_left (n : ℕ) [n.AtLeastTwo] (x : α) : Commute (OfNat.ofNat n) x := n.cast_commute x theorem cast_comm (n : ℕ) (x : α) : (n : α) * x = x * n := (cast_commute n x).eq theorem commute_cast (x : α) (n : ℕ) : Commute x n := (n.cast_commute x).symm theorem _root_.Commute.ofNat_right (x : α) (n : ℕ) [n.AtLeastTwo] : Commute x (OfNat.ofNat n) := n.commute_cast x end Commute end Nat namespace SemiconjBy variable [Semiring α] {a x y : α} @[simp] lemma natCast_mul_right (h : SemiconjBy a x y) (n : ℕ) : SemiconjBy a (n * x) (n * y) := SemiconjBy.mul_right (Nat.commute_cast _ _) h @[simp] lemma natCast_mul_left (h : SemiconjBy a x y) (n : ℕ) : SemiconjBy (n * a) x y := SemiconjBy.mul_left (Nat.cast_commute _ _) h lemma natCast_mul_natCast_mul (h : SemiconjBy a x y) (m n : ℕ) : SemiconjBy (m * a) (n * x) (n * y) := by simp [h] end SemiconjBy namespace Commute variable [Semiring α] {a b : α} @[simp] lemma natCast_mul_right (h : Commute a b) (n : ℕ) : Commute a (n * b) := SemiconjBy.natCast_mul_right h n @[simp] lemma natCast_mul_left (h : Commute a b) (n : ℕ) : Commute (n * a) b := SemiconjBy.natCast_mul_left h n lemma natCast_mul_natCast_mul (h : Commute a b) (m n : ℕ) : Commute (m * a) (n * b) := by simp [h] variable (a) (m n : ℕ) lemma self_natCast_mul : Commute a (n * a) := (Commute.refl a).natCast_mul_right n lemma natCast_mul_self : Commute (n * a) a := (Commute.refl a).natCast_mul_left n lemma self_natCast_mul_natCast_mul : Commute (m * a) (n * a) := (Commute.refl a).natCast_mul_natCast_mul m n end Commute