path
stringlengths
11
71
content
stringlengths
75
124k
LinearAlgebra\QuadraticForm\TensorProduct.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.LinearAlgebra.BilinearForm.TensorProduct import Mathlib.LinearAlgebra.QuadraticForm.Basic /-! # The quadratic form on a tensor product ## Main definitions * `QuadraticForm.tensorDistrib (Q₁ ⊗ₜ Q₂)`: the quadratic form on `M₁ ⊗ M₂` constructed by applying `Q₁` on `M₁` and `Q₂` on `M₂`. This construction is not available in characteristic two. -/ universe uR uA uM₁ uM₂ variable {R : Type uR} {A : Type uA} {M₁ : Type uM₁} {M₂ : Type uM₂} open TensorProduct open LinearMap (BilinMap) open LinearMap (BilinForm) open QuadraticMap namespace QuadraticForm section CommRing variable [CommRing R] [CommRing A] variable [AddCommGroup M₁] [AddCommGroup M₂] variable [Algebra R A] [Module R M₁] [Module A M₁] variable [SMulCommClass R A M₁] [IsScalarTower R A M₁] variable [Module R M₂] section InvertibleTwo variable [Invertible (2 : R)] variable (R A) in /-- The tensor product of two quadratic forms injects into quadratic forms on tensor products. Note this is heterobasic; the quadratic form on the left can take values in a larger ring than the one on the right. -/ -- `noncomputable` is a performance workaround for mathlib4#7103 noncomputable def tensorDistrib : QuadraticForm A M₁ ⊗[R] QuadraticForm R M₂ →ₗ[A] QuadraticForm A (M₁ ⊗[R] M₂) := letI : Invertible (2 : A) := (Invertible.map (algebraMap R A) 2).copy 2 (map_ofNat _ _).symm -- while `letI`s would produce a better term than `let`, they would make this already-slow -- definition even slower. let toQ := BilinMap.toQuadraticMapLinearMap A A (M₁ ⊗[R] M₂) let tmulB := BilinMap.tensorDistrib R A (M₁ := M₁) (M₂ := M₂) let toB := AlgebraTensorModule.map (QuadraticMap.associated : QuadraticForm A M₁ →ₗ[A] BilinForm A M₁) (QuadraticMap.associated : QuadraticForm R M₂ →ₗ[R] BilinForm R M₂) toQ ∘ₗ tmulB ∘ₗ toB -- TODO: make the RHS `MulOpposite.op (Q₂ m₂) • Q₁ m₁` so that this has a nicer defeq for -- `R = A` of `Q₁ m₁ * Q₂ m₂`. @[simp] theorem tensorDistrib_tmul (Q₁ : QuadraticForm A M₁) (Q₂ : QuadraticForm R M₂) (m₁ : M₁) (m₂ : M₂) : tensorDistrib R A (Q₁ ⊗ₜ Q₂) (m₁ ⊗ₜ m₂) = Q₂ m₂ • Q₁ m₁ := letI : Invertible (2 : A) := (Invertible.map (algebraMap R A) 2).copy 2 (map_ofNat _ _).symm (BilinMap.tensorDistrib_tmul _ _ _ _ _ _).trans <| congr_arg₂ _ (associated_eq_self_apply _ _ _) (associated_eq_self_apply _ _ _) /-- The tensor product of two quadratic forms, a shorthand for dot notation. -/ -- `noncomputable` is a performance workaround for mathlib4#7103 protected noncomputable abbrev tmul (Q₁ : QuadraticForm A M₁) (Q₂ : QuadraticForm R M₂) : QuadraticForm A (M₁ ⊗[R] M₂) := tensorDistrib R A (Q₁ ⊗ₜ[R] Q₂) theorem associated_tmul [Invertible (2 : A)] (Q₁ : QuadraticForm A M₁) (Q₂ : QuadraticForm R M₂) : associated (R := A) (Q₁.tmul Q₂) = (associated (R := A) Q₁).tmul (associated (R := R) Q₂) := by rw [QuadraticForm.tmul, tensorDistrib, BilinMap.tmul] dsimp have : Subsingleton (Invertible (2 : A)) := inferInstance convert associated_left_inverse A ((associated_isSymm A Q₁).tmul (associated_isSymm R Q₂)) theorem polarBilin_tmul [Invertible (2 : A)] (Q₁ : QuadraticForm A M₁) (Q₂ : QuadraticForm R M₂) : polarBilin (Q₁.tmul Q₂) = ⅟(2 : A) • (polarBilin Q₁).tmul (polarBilin Q₂) := by simp_rw [← two_nsmul_associated A, ← two_nsmul_associated R, BilinMap.tmul, tmul_smul, ← smul_tmul', map_nsmul, associated_tmul] rw [smul_comm (_ : A) (_ : ℕ), ← smul_assoc, two_smul _ (_ : A), invOf_two_add_invOf_two, one_smul] variable (A) in /-- The base change of a quadratic form. -/ -- `noncomputable` is a performance workaround for mathlib4#7103 protected noncomputable def baseChange (Q : QuadraticForm R M₂) : QuadraticForm A (A ⊗[R] M₂) := QuadraticForm.tmul (R := R) (A := A) (M₁ := A) (M₂ := M₂) (QuadraticMap.sq (R := A)) Q @[simp] theorem baseChange_tmul (Q : QuadraticForm R M₂) (a : A) (m₂ : M₂) : Q.baseChange A (a ⊗ₜ m₂) = Q m₂ • (a * a) := tensorDistrib_tmul _ _ _ _ theorem associated_baseChange [Invertible (2 : A)] (Q : QuadraticForm R M₂) : associated (R := A) (Q.baseChange A) = (associated (R := R) Q).baseChange A := by dsimp only [QuadraticForm.baseChange, LinearMap.baseChange] rw [associated_tmul (QuadraticMap.sq (R := A)) Q, associated_sq] exact rfl theorem polarBilin_baseChange [Invertible (2 : A)] (Q : QuadraticForm R M₂) : polarBilin (Q.baseChange A) = (polarBilin Q).baseChange A := by rw [QuadraticForm.baseChange, BilinMap.baseChange, polarBilin_tmul, BilinMap.tmul, ← LinearMap.map_smul, smul_tmul', ← two_nsmul_associated R, coe_associatedHom, associated_sq, smul_comm, ← smul_assoc, two_smul, invOf_two_add_invOf_two, one_smul] end InvertibleTwo /-- If two quadratic forms from `A ⊗[R] M₂` agree on elements of the form `1 ⊗ m`, they are equal. In other words, if a base change exists for a quadratic form, it is unique. Note that unlike `QuadraticForm.baseChange`, this does not need `Invertible (2 : R)`. -/ @[ext] theorem baseChange_ext ⦃Q₁ Q₂ : QuadraticForm A (A ⊗[R] M₂)⦄ (h : ∀ m, Q₁ (1 ⊗ₜ m) = Q₂ (1 ⊗ₜ m)) : Q₁ = Q₂ := by replace h (a m) : Q₁ (a ⊗ₜ m) = Q₂ (a ⊗ₜ m) := by rw [← mul_one a, ← smul_eq_mul, ← smul_tmul', QuadraticMap.map_smul, QuadraticMap.map_smul, h] ext x induction x with | tmul => simp [h] | zero => simp | add x y hx hy => have : Q₁.polarBilin = Q₂.polarBilin := by ext dsimp [polar] rw [← TensorProduct.tmul_add, h, h, h] replace := congr($this x y) dsimp [polar] at this linear_combination this + hx + hy end CommRing end QuadraticForm
LinearAlgebra\QuadraticForm\QuadraticModuleCat\Monoidal.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.CategoryTheory.Monoidal.Transport import Mathlib.Algebra.Category.ModuleCat.Monoidal.Basic import Mathlib.LinearAlgebra.QuadraticForm.QuadraticModuleCat import Mathlib.LinearAlgebra.QuadraticForm.TensorProduct.Isometries /-! # The monoidal category structure on quadratic R-modules The monoidal structure is simply the structure on the underlying modules, where the tensor product of two modules is equipped with the form constructed via `QuadraticForm.tmul`. As with the monoidal structure on `ModuleCat`, the universe level of the modules must be at least the universe level of the ring, so that we have a monoidal unit. For now, we simplify by insisting both universe levels are the same. ## Implementation notes This file essentially mirrors `Mathlib/Algebra/Category/AlgebraCat/Monoidal.lean`. -/ suppress_compilation open CategoryTheory open scoped MonoidalCategory universe v u variable {R : Type u} [CommRing R] [Invertible (2 : R)] namespace QuadraticModuleCat open QuadraticMap open QuadraticForm namespace instMonoidalCategory /-- Auxiliary definition used to build `QuadraticModuleCat.instMonoidalCategory`. -/ @[simps! form] noncomputable abbrev tensorObj (X Y : QuadraticModuleCat.{u} R) : QuadraticModuleCat.{u} R := of (X.form.tmul Y.form) /-- Auxiliary definition used to build `QuadraticModuleCat.instMonoidalCategory`. We want this up front so that we can re-use it to define `whiskerLeft` and `whiskerRight`. -/ noncomputable abbrev tensorHom {W X Y Z : QuadraticModuleCat.{u} R} (f : W ⟶ X) (g : Y ⟶ Z) : tensorObj W Y ⟶ tensorObj X Z := ⟨f.toIsometry.tmul g.toIsometry⟩ open MonoidalCategory end instMonoidalCategory open instMonoidalCategory instance : MonoidalCategoryStruct (QuadraticModuleCat.{u} R) where tensorObj := instMonoidalCategory.tensorObj whiskerLeft X _ _ f := tensorHom (𝟙 X) f whiskerRight {X₁ X₂} (f : X₁ ⟶ X₂) Y := tensorHom f (𝟙 Y) tensorHom := tensorHom tensorUnit := of (sq (R := R)) associator X Y Z := ofIso (tensorAssoc X.form Y.form Z.form) leftUnitor X := ofIso (tensorLId X.form) rightUnitor X := ofIso (tensorRId X.form) @[simp] theorem toModuleCat_tensor (X Y : QuadraticModuleCat.{u} R) : (X ⊗ Y).toModuleCat = X.toModuleCat ⊗ Y.toModuleCat := rfl theorem forget₂_map_associator_hom (X Y Z : QuadraticModuleCat.{u} R) : (forget₂ (QuadraticModuleCat R) (ModuleCat R)).map (α_ X Y Z).hom = (α_ X.toModuleCat Y.toModuleCat Z.toModuleCat).hom := rfl theorem forget₂_map_associator_inv (X Y Z : QuadraticModuleCat.{u} R) : (forget₂ (QuadraticModuleCat R) (ModuleCat R)).map (α_ X Y Z).inv = (α_ X.toModuleCat Y.toModuleCat Z.toModuleCat).inv := rfl noncomputable instance instMonoidalCategory : MonoidalCategory (QuadraticModuleCat.{u} R) := Monoidal.induced (forget₂ (QuadraticModuleCat R) (ModuleCat R)) { μIso := fun X Y => Iso.refl _ εIso := Iso.refl _ leftUnitor_eq := fun X => by simp only [forget₂_obj, forget₂_map, Iso.refl_symm, Iso.trans_assoc, Iso.trans_hom, Iso.refl_hom, tensorIso_hom, MonoidalCategory.tensorHom_id] dsimp only [toModuleCat_tensor, ModuleCat.of_coe] erw [MonoidalCategory.id_whiskerRight] simp rfl rightUnitor_eq := fun X => by simp only [forget₂_obj, forget₂_map, Iso.refl_symm, Iso.trans_assoc, Iso.trans_hom, Iso.refl_hom, tensorIso_hom, MonoidalCategory.id_tensorHom] dsimp only [toModuleCat_tensor, ModuleCat.of_coe] erw [MonoidalCategory.whiskerLeft_id] simp rfl associator_eq := fun X Y Z => by dsimp only [forget₂_obj, forget₂_map_associator_hom] simp only [eqToIso_refl, Iso.refl_trans, Iso.refl_symm, Iso.trans_hom, tensorIso_hom, Iso.refl_hom, MonoidalCategory.tensor_id] dsimp only [toModuleCat_tensor, ModuleCat.of_coe] rw [Category.id_comp, Category.id_comp, Category.comp_id, MonoidalCategory.tensor_id, Category.id_comp] } variable (R) in /-- `forget₂ (QuadraticModuleCat R) (ModuleCat R)` as a monoidal functor. -/ def toModuleCatMonoidalFunctor : MonoidalFunctor (QuadraticModuleCat.{u} R) (ModuleCat.{u} R) := by unfold instMonoidalCategory exact Monoidal.fromInduced (forget₂ (QuadraticModuleCat R) (ModuleCat R)) _ instance : (toModuleCatMonoidalFunctor R).Faithful := forget₂_faithful _ _ end QuadraticModuleCat
LinearAlgebra\QuadraticForm\QuadraticModuleCat\Symmetric.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.LinearAlgebra.QuadraticForm.QuadraticModuleCat.Monoidal import Mathlib.Algebra.Category.ModuleCat.Monoidal.Symmetric /-! # The monoidal structure on `QuadraticModuleCat` is symmetric. In this file we show: * `QuadraticModuleCat.instSymmetricCategory : SymmetricCategory (QuadraticModuleCat.{u} R)` ## Implementation notes This file essentially mirrors `Mathlib/Algebra/Category/AlgebraCat/Symmetric.lean`. -/ suppress_compilation open CategoryTheory universe v u variable {R : Type u} [CommRing R] [Invertible (2 : R)] namespace QuadraticModuleCat open QuadraticForm instance : BraidedCategory (QuadraticModuleCat.{u} R) := braidedCategoryOfFaithful (toModuleCatMonoidalFunctor R) (fun X Y => ofIso <| tensorComm X.form Y.form) (by aesop_cat) variable (R) in /-- `forget₂ (QuadraticModuleCat R) (ModuleCat R)` as a braided functor. -/ @[simps toMonoidalFunctor] def toModuleCatBraidedFunctor : BraidedFunctor (QuadraticModuleCat.{u} R) (ModuleCat.{u} R) where toMonoidalFunctor := toModuleCatMonoidalFunctor R instance : (toModuleCatBraidedFunctor R).Faithful := forget₂_faithful _ _ instance instSymmetricCategory : SymmetricCategory (QuadraticModuleCat.{u} R) := symmetricCategoryOfFaithful (toModuleCatBraidedFunctor R) end QuadraticModuleCat
LinearAlgebra\QuadraticForm\TensorProduct\Isometries.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.LinearAlgebra.QuadraticForm.TensorProduct import Mathlib.LinearAlgebra.QuadraticForm.IsometryEquiv /-! # Linear equivalences of tensor products as isometries These results are separate from the definition of `QuadraticForm.tmul` as that file is very slow. ## Main definitions * `QuadraticForm.Isometry.tmul`: `TensorProduct.map` as a `QuadraticForm.Isometry` * `QuadraticForm.tensorComm`: `TensorProduct.comm` as a `QuadraticForm.IsometryEquiv` * `QuadraticForm.tensorAssoc`: `TensorProduct.assoc` as a `QuadraticForm.IsometryEquiv` * `QuadraticForm.tensorRId`: `TensorProduct.rid` as a `QuadraticForm.IsometryEquiv` * `QuadraticForm.tensorLId`: `TensorProduct.lid` as a `QuadraticForm.IsometryEquiv` -/ suppress_compilation universe uR uM₁ uM₂ uM₃ uM₄ variable {R : Type uR} {M₁ : Type uM₁} {M₂ : Type uM₂} {M₃ : Type uM₃} {M₄ : Type uM₄} open scoped TensorProduct open QuadraticMap namespace QuadraticForm variable [CommRing R] variable [AddCommGroup M₁] [AddCommGroup M₂] [AddCommGroup M₃] [AddCommGroup M₄] variable [Module R M₁] [Module R M₂] [Module R M₃] [Module R M₄] [Invertible (2 : R)] @[simp] theorem tmul_comp_tensorMap {Q₁ : QuadraticForm R M₁} {Q₂ : QuadraticForm R M₂} {Q₃ : QuadraticForm R M₃} {Q₄ : QuadraticForm R M₄} (f : Q₁ →qᵢ Q₂) (g : Q₃ →qᵢ Q₄) : (Q₂.tmul Q₄).comp (TensorProduct.map f.toLinearMap g.toLinearMap) = Q₁.tmul Q₃ := by have h₁ : Q₁ = Q₂.comp f.toLinearMap := QuadraticMap.ext fun x => (f.map_app x).symm have h₃ : Q₃ = Q₄.comp g.toLinearMap := QuadraticMap.ext fun x => (g.map_app x).symm refine (QuadraticMap.associated_rightInverse R).injective ?_ ext m₁ m₃ m₁' m₃' simp [-associated_apply, h₁, h₃, associated_tmul] @[simp] theorem tmul_tensorMap_apply {Q₁ : QuadraticForm R M₁} {Q₂ : QuadraticForm R M₂} {Q₃ : QuadraticForm R M₃} {Q₄ : QuadraticForm R M₄} (f : Q₁ →qᵢ Q₂) (g : Q₃ →qᵢ Q₄) (x : M₁ ⊗[R] M₃) : Q₂.tmul Q₄ (TensorProduct.map f.toLinearMap g.toLinearMap x) = Q₁.tmul Q₃ x := DFunLike.congr_fun (tmul_comp_tensorMap f g) x namespace Isometry /-- `TensorProduct.map` for `Quadraticform.Isometry`s -/ def _root_.QuadraticMap.Isometry.tmul {Q₁ : QuadraticForm R M₁} {Q₂ : QuadraticForm R M₂} {Q₃ : QuadraticForm R M₃} {Q₄ : QuadraticForm R M₄} (f : Q₁ →qᵢ Q₂) (g : Q₃ →qᵢ Q₄) : (Q₁.tmul Q₃) →qᵢ (Q₂.tmul Q₄) where toLinearMap := TensorProduct.map f.toLinearMap g.toLinearMap map_app' := tmul_tensorMap_apply f g @[simp] theorem _root_.QuadraticMap.Isometry.tmul_apply {Q₁ : QuadraticForm R M₁} {Q₂ : QuadraticForm R M₂} {Q₃ : QuadraticForm R M₃} {Q₄ : QuadraticForm R M₄} (f : Q₁ →qᵢ Q₂) (g : Q₃ →qᵢ Q₄) (x : M₁ ⊗[R] M₃) : f.tmul g x = TensorProduct.map f.toLinearMap g.toLinearMap x := rfl end Isometry section tensorComm @[simp] theorem tmul_comp_tensorComm (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) : (Q₂.tmul Q₁).comp (TensorProduct.comm R M₁ M₂) = Q₁.tmul Q₂ := by refine (QuadraticMap.associated_rightInverse R).injective ?_ ext m₁ m₂ m₁' m₂' dsimp [-associated_apply] simp only [associated_tmul, QuadraticMap.associated_comp] exact mul_comm _ _ @[simp] theorem tmul_tensorComm_apply (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) (x : M₁ ⊗[R] M₂) : Q₂.tmul Q₁ (TensorProduct.comm R M₁ M₂ x) = Q₁.tmul Q₂ x := DFunLike.congr_fun (tmul_comp_tensorComm Q₁ Q₂) x /-- `TensorProduct.comm` preserves tensor products of quadratic forms. -/ @[simps toLinearEquiv] def tensorComm (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) : (Q₁.tmul Q₂).IsometryEquiv (Q₂.tmul Q₁) where toLinearEquiv := TensorProduct.comm R M₁ M₂ map_app' := tmul_tensorComm_apply Q₁ Q₂ @[simp] lemma tensorComm_apply (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) (x : M₁ ⊗[R] M₂) : tensorComm Q₁ Q₂ x = TensorProduct.comm R M₁ M₂ x := rfl @[simp] lemma tensorComm_symm (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) : (tensorComm Q₁ Q₂).symm = tensorComm Q₂ Q₁ := rfl end tensorComm section tensorAssoc @[simp] theorem tmul_comp_tensorAssoc (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) (Q₃ : QuadraticForm R M₃) : (Q₁.tmul (Q₂.tmul Q₃)).comp (TensorProduct.assoc R M₁ M₂ M₃) = (Q₁.tmul Q₂).tmul Q₃ := by refine (QuadraticMap.associated_rightInverse R).injective ?_ ext m₁ m₂ m₁' m₂' m₁'' m₂'' dsimp [-associated_apply] simp only [associated_tmul, QuadraticMap.associated_comp] exact mul_assoc _ _ _ @[simp] theorem tmul_tensorAssoc_apply (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) (Q₃ : QuadraticForm R M₃) (x : (M₁ ⊗[R] M₂) ⊗[R] M₃) : Q₁.tmul (Q₂.tmul Q₃) (TensorProduct.assoc R M₁ M₂ M₃ x) = (Q₁.tmul Q₂).tmul Q₃ x := DFunLike.congr_fun (tmul_comp_tensorAssoc Q₁ Q₂ Q₃) x /-- `TensorProduct.assoc` preserves tensor products of quadratic forms. -/ @[simps toLinearEquiv] def tensorAssoc (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) (Q₃ : QuadraticForm R M₃) : ((Q₁.tmul Q₂).tmul Q₃).IsometryEquiv (Q₁.tmul (Q₂.tmul Q₃)) where toLinearEquiv := TensorProduct.assoc R M₁ M₂ M₃ map_app' := tmul_tensorAssoc_apply Q₁ Q₂ Q₃ @[simp] lemma tensorAssoc_apply (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) (Q₃ : QuadraticForm R M₃) (x : (M₁ ⊗[R] M₂) ⊗[R] M₃) : tensorAssoc Q₁ Q₂ Q₃ x = TensorProduct.assoc R M₁ M₂ M₃ x := rfl @[simp] lemma tensorAssoc_symm_apply (Q₁ : QuadraticForm R M₁) (Q₂ : QuadraticForm R M₂) (Q₃ : QuadraticForm R M₃) (x : M₁ ⊗[R] (M₂ ⊗[R] M₃)) : (tensorAssoc Q₁ Q₂ Q₃).symm x = (TensorProduct.assoc R M₁ M₂ M₃).symm x := rfl end tensorAssoc section tensorRId theorem comp_tensorRId_eq (Q₁ : QuadraticForm R M₁) : Q₁.comp (TensorProduct.rid R M₁) = Q₁.tmul (sq (R := R)) := by refine (QuadraticMap.associated_rightInverse R).injective ?_ ext m₁ m₁' dsimp [-associated_apply] simp only [associated_tmul, QuadraticMap.associated_comp] simp [-associated_apply, one_mul] @[simp] theorem tmul_tensorRId_apply (Q₁ : QuadraticForm R M₁) (x : M₁ ⊗[R] R) : Q₁ (TensorProduct.rid R M₁ x) = Q₁.tmul (sq (R := R)) x := DFunLike.congr_fun (comp_tensorRId_eq Q₁) x /-- `TensorProduct.rid` preserves tensor products of quadratic forms. -/ @[simps toLinearEquiv] def tensorRId (Q₁ : QuadraticForm R M₁) : (Q₁.tmul (sq (R := R))).IsometryEquiv Q₁ where toLinearEquiv := TensorProduct.rid R M₁ map_app' := tmul_tensorRId_apply Q₁ @[simp] lemma tensorRId_apply (Q₁ : QuadraticForm R M₁) (x : M₁ ⊗[R] R) : tensorRId Q₁ x = TensorProduct.rid R M₁ x := rfl @[simp] lemma tensorRId_symm_apply (Q₁ : QuadraticForm R M₁) (x : M₁) : (tensorRId Q₁).symm x = (TensorProduct.rid R M₁).symm x := rfl end tensorRId section tensorLId theorem comp_tensorLId_eq (Q₂ : QuadraticForm R M₂) : Q₂.comp (TensorProduct.lid R M₂) = QuadraticForm.tmul (sq (R := R)) Q₂ := by refine (QuadraticMap.associated_rightInverse R).injective ?_ ext m₂ m₂' dsimp [-associated_apply] simp only [associated_tmul, QuadraticMap.associated_comp] simp [-associated_apply, mul_one] @[simp] theorem tmul_tensorLId_apply (Q₂ : QuadraticForm R M₂) (x : R ⊗[R] M₂) : Q₂ (TensorProduct.lid R M₂ x) = QuadraticForm.tmul (sq (R := R)) Q₂ x := DFunLike.congr_fun (comp_tensorLId_eq Q₂) x /-- `TensorProduct.lid` preserves tensor products of quadratic forms. -/ @[simps toLinearEquiv] def tensorLId (Q₂ : QuadraticForm R M₂) : (QuadraticForm.tmul (sq (R := R)) Q₂).IsometryEquiv Q₂ where toLinearEquiv := TensorProduct.lid R M₂ map_app' := tmul_tensorLId_apply Q₂ @[simp] lemma tensorLId_apply (Q₂ : QuadraticForm R M₂) (x : R ⊗[R] M₂) : tensorLId Q₂ x = TensorProduct.lid R M₂ x := rfl @[simp] lemma tensorLId_symm_apply (Q₂ : QuadraticForm R M₂) (x : M₂) : (tensorLId Q₂).symm x = (TensorProduct.lid R M₂).symm x := rfl end tensorLId end QuadraticForm
LinearAlgebra\RootSystem\Basic.lean
/- Copyright (c) 2023 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash, Deepro Choudhury, Scott Carnahan -/ import Mathlib.LinearAlgebra.RootSystem.Defs /-! # Root data and root systems This file contains basic results for root systems and root data. ## Main definitions / results: * `RootPairing.ext`: In characteristic zero if there is no torsion, the correspondence between roots and coroots is unique. * `RootSystem.ext`: In characteristic zero if there is no torsion, a root system is determined entirely by its roots. * `RootPairing.mk'`: In characteristic zero if there is no torsion, to check that two finite familes of of roots and coroots form a root pairing, it is sufficient to check that they are stable under reflections. * `RootSystem.mk'`: In characteristic zero if there is no torsion, to check that a finite family of roots form a root system, we do not need to check that the coroots are stable under reflections since this follows from the corresponding property for the roots. ## TODO * Derived properties of pairs, e.g., (ultra)parallel linearly independent pairs generate infinite dihedral groups. * Properties of Weyl group (faithful action on roots, finiteness for finite `ι`) * Conditions for existence of Weyl-invariant form (e.g., finiteness). -/ open Set Function open Module hiding reflection open Submodule (span) open AddSubgroup (zmultiples) noncomputable section variable {ι R M N : Type*} [CommRing R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N] namespace RootPairing section reflection_perm variable (p : PerfectPairing R M N) (root : ι ↪ M) (coroot : ι ↪ N) (i j : ι) (h : ∀ i, MapsTo (preReflection (root i) (p.toLin.flip (coroot i))) (range root) (range root)) private theorem exist_eq_reflection_of_mapsTo : ∃ k, root k = (preReflection (root i) (p.toLin.flip (coroot i))) (root j) := h i (mem_range_self j) variable (hp : ∀ i, p.toLin (root i) (coroot i) = 2) private theorem choose_choose_eq_of_mapsTo : (exist_eq_reflection_of_mapsTo p root coroot i (exist_eq_reflection_of_mapsTo p root coroot i j h).choose h).choose = j := by refine root.injective ?_ rw [(exist_eq_reflection_of_mapsTo p root coroot i _ h).choose_spec, (exist_eq_reflection_of_mapsTo p root coroot i j h).choose_spec] apply involutive_preReflection (x := root i) (hp i) /-- The bijection on the indexing set induced by reflection. -/ @[simps] protected def equiv_of_mapsTo : ι ≃ ι where toFun j := (exist_eq_reflection_of_mapsTo p root coroot i j h).choose invFun j := (exist_eq_reflection_of_mapsTo p root coroot i j h).choose left_inv j := choose_choose_eq_of_mapsTo p root coroot i j h hp right_inv j := choose_choose_eq_of_mapsTo p root coroot i j h hp end reflection_perm variable [Finite ι] (P : RootPairing ι R M N) (i j : ι) /-- Even though the roots may not span, coroots are distinguished by their pairing with the roots. The proof depends crucially on the fact that there are finitely-many roots. Modulo trivial generalisations, this statement is exactly Lemma 1.1.4 on page 87 of SGA 3 XXI. -/ lemma injOn_dualMap_subtype_span_root_coroot [NoZeroSMulDivisors ℤ M] : InjOn ((span R (range P.root)).subtype.dualMap ∘ₗ P.toLin.flip) (range P.coroot) := by have := injOn_dualMap_subtype_span_range_range (finite_range P.root) (c := P.toLin.flip ∘ P.coroot) P.root_coroot_two P.mapsTo_reflection_root rintro - ⟨i, rfl⟩ - ⟨j, rfl⟩ hij exact P.bijectiveRight.injective <| this (mem_range_self i) (mem_range_self j) hij /-- In characteristic zero if there is no torsion, the correspondence between roots and coroots is unique. Formally, the point is that the hypothesis `hc` depends only on the range of the coroot mappings. -/ @[ext] protected lemma ext [CharZero R] [NoZeroSMulDivisors R M] {P₁ P₂ : RootPairing ι R M N} (he : P₁.toLin = P₂.toLin) (hr : P₁.root = P₂.root) (hc : range P₁.coroot = range P₂.coroot) : P₁ = P₂ := by have hp (hc' : P₁.coroot = P₂.coroot) : P₁.reflection_perm = P₂.reflection_perm := by ext i j refine P₁.root.injective ?_ conv_rhs => rw [hr] rw [root_reflection_perm, root_reflection_perm] simp only [hr, he, hc', reflection_apply] suffices P₁.coroot = P₂.coroot by cases' P₁ with p₁; cases' P₂ with p₂; cases p₁; cases p₂; congr; exact hp this have := NoZeroSMulDivisors.int_of_charZero R M ext i apply P₁.injOn_dualMap_subtype_span_root_coroot (mem_range_self i) (hc ▸ mem_range_self i) simp only [LinearMap.coe_comp, LinearEquiv.coe_coe, comp_apply] apply Dual.eq_of_preReflection_mapsTo' (P₁.ne_zero i) (finite_range P₁.root) · exact Submodule.subset_span (mem_range_self i) · exact P₁.coroot_root_two i · exact P₁.mapsTo_reflection_root i · exact hr ▸ he ▸ P₂.coroot_root_two i · exact hr ▸ he ▸ P₂.mapsTo_reflection_root i private lemma coroot_eq_coreflection_of_root_eq' [CharZero R] [NoZeroSMulDivisors R M] (p : PerfectPairing R M N) (root : ι ↪ M) (coroot : ι ↪ N) (hp : ∀ i, p.toLin (root i) (coroot i) = 2) (hr : ∀ i, MapsTo (preReflection (root i) (p.toLin.flip (coroot i))) (range root) (range root)) (hc : ∀ i, MapsTo (preReflection (coroot i) (p.toLin (root i))) (range coroot) (range coroot)) {i j k : ι} (hk : root k = preReflection (root i) (p.toLin.flip (coroot i)) (root j)) : coroot k = preReflection (coroot i) (p.toLin (root i)) (coroot j) := by set α := root i set β := root j set α' := coroot i set β' := coroot j set sα := preReflection α (p.toLin.flip α') set sβ := preReflection β (p.toLin.flip β') let sα' := preReflection α' (p.toLin α) have hij : preReflection (sα β) (p.toLin.flip (sα' β')) = sα ∘ₗ sβ ∘ₗ sα := by ext have hpi : (p.toLin.flip (coroot i)) (root i) = 2 := by rw [LinearMap.flip_apply, hp i] simp [α, β, α', β', sα, sβ, sα', ← preReflection_preReflection β (p.toLin.flip β') hpi, preReflection_apply] have hk₀ : root k ≠ 0 := fun h ↦ by simpa [h] using hp k obtain ⟨l, hl⟩ := hc i (mem_range_self j) rw [← hl] have hkl : (p.toLin.flip (coroot l)) (root k) = 2 := by simp [hl, hk, preReflection_apply, mul_sub, mul_two, β', α, α', β, sα, hp i, hp j] rw [mul_comm (p.toLin (root i) (coroot j))] abel suffices p.toLin.flip (coroot k) = p.toLin.flip (coroot l) from p.bijectiveRight.injective this have _i : NoZeroSMulDivisors ℤ M := NoZeroSMulDivisors.int_of_charZero R M have := injOn_dualMap_subtype_span_range_range (finite_range root) (c := p.toLin.flip ∘ coroot) hp hr apply this (mem_range_self k) (mem_range_self l) refine Dual.eq_of_preReflection_mapsTo' hk₀ (finite_range root) (Submodule.subset_span <| mem_range_self k) (hp k) (hr k) hkl ?_ rw [comp_apply, hl, hk, hij] exact (hr i).comp <| (hr j).comp (hr i) /-- In characteristic zero if there is no torsion, to check that two finite familes of of roots and coroots form a root pairing, it is sufficient to check that they are stable under reflections. -/ def mk' [Finite ι] [CharZero R] [NoZeroSMulDivisors R M] (p : PerfectPairing R M N) (root : ι ↪ M) (coroot : ι ↪ N) (hp : ∀ i, p.toLin (root i) (coroot i) = 2) (hr : ∀ i, MapsTo (preReflection (root i) (p.toLin.flip (coroot i))) (range root) (range root)) (hc : ∀ i, MapsTo (preReflection (coroot i) (p.toLin (root i))) (range coroot) (range coroot)) : RootPairing ι R M N where toPerfectPairing := p root := root coroot := coroot root_coroot_two := hp reflection_perm i := RootPairing.equiv_of_mapsTo p root coroot i hr hp reflection_perm_root i j := by rw [equiv_of_mapsTo_apply, (exist_eq_reflection_of_mapsTo p root coroot i j hr).choose_spec, preReflection_apply, LinearMap.flip_apply] reflection_perm_coroot i j := by refine (coroot_eq_coreflection_of_root_eq' p root coroot hp hr hc ?_).symm rw [equiv_of_mapsTo_apply, (exist_eq_reflection_of_mapsTo p root coroot i j hr).choose_spec] end RootPairing namespace RootSystem open RootPairing variable [Finite ι] (P : RootSystem ι R M N) /-- In characteristic zero if there is no torsion, a finite root system is determined entirely by its roots. -/ @[ext] protected lemma ext [CharZero R] [NoZeroSMulDivisors R M] {P₁ P₂ : RootSystem ι R M N} (he : P₁.toLin = P₂.toLin) (hr : P₁.root = P₂.root) : P₁ = P₂ := by suffices ∀ P₁ P₂ : RootSystem ι R M N, P₁.toLin = P₂.toLin → P₁.root = P₂.root → range P₁.coroot ⊆ range P₂.coroot by have h₁ := this P₁ P₂ he hr have h₂ := this P₂ P₁ he.symm hr.symm cases' P₁ with P₁ cases' P₂ with P₂ congr exact RootPairing.ext he hr (le_antisymm h₁ h₂) clear! P₁ P₂ rintro P₁ P₂ he hr - ⟨i, rfl⟩ use i apply P₁.bijectiveRight.injective apply Dual.eq_of_preReflection_mapsTo (P₁.ne_zero i) (finite_range P₁.root) P₁.span_eq_top · exact hr ▸ he ▸ P₂.coroot_root_two i · exact hr ▸ he ▸ P₂.mapsTo_reflection_root i · exact P₁.coroot_root_two i · exact P₁.mapsTo_reflection_root i private lemma coroot_eq_coreflection_of_root_eq_of_span_eq_top [CharZero R] [NoZeroSMulDivisors R M] (p : PerfectPairing R M N) (root : ι ↪ M) (coroot : ι ↪ N) (hp : ∀ i, p.toLin (root i) (coroot i) = 2) (hs : ∀ i, MapsTo (preReflection (root i) (p.toLin.flip (coroot i))) (range root) (range root)) (hsp : span R (range root) = ⊤) {i j k : ι} (hk : root k = preReflection (root i) (p.toLin.flip (coroot i)) (root j)) : coroot k = preReflection (coroot i) (p.toLin (root i)) (coroot j) := by set α := root i set β := root j set α' := coroot i set β' := coroot j set sα := preReflection α (p.toLin.flip α') set sβ := preReflection β (p.toLin.flip β') let sα' := preReflection α' (p.toLin α) have hij : preReflection (sα β) (p.toLin.flip (sα' β')) = sα ∘ₗ sβ ∘ₗ sα := by ext have hpi : (p.toLin.flip (coroot i)) (root i) = 2 := by rw [LinearMap.flip_apply, hp i] simp [α, β, α', β', sα, sβ, sα', ← preReflection_preReflection β (p.toLin.flip β') hpi, preReflection_apply] -- v4.7.0-rc1 issues have hk₀ : root k ≠ 0 := fun h ↦ by simpa [h] using hp k apply p.bijectiveRight.injective apply Dual.eq_of_preReflection_mapsTo hk₀ (finite_range root) hsp (hp k) (hs k) · simp [α, β, α', β', sα, sβ, sα', hk, preReflection_apply, hp i, hp j, mul_two, mul_comm (p.toLin α β')] ring -- v4.7.0-rc1 issues · rw [hk, hij] exact (hs i).comp <| (hs j).comp (hs i) /-- In characteristic zero if there is no torsion, to check that a finite family of roots form a root system, we do not need to check that the coroots are stable under reflections since this follows from the corresponding property for the roots. -/ def mk' [CharZero R] [NoZeroSMulDivisors R M] (p : PerfectPairing R M N) (root : ι ↪ M) (coroot : ι ↪ N) (hp : ∀ i, p.toLin (root i) (coroot i) = 2) (hs : ∀ i, MapsTo (preReflection (root i) (p.toLin.flip (coroot i))) (range root) (range root)) (hsp : span R (range root) = ⊤) : RootSystem ι R M N where span_eq_top := hsp toRootPairing := RootPairing.mk' p root coroot hp hs <| by rintro i - ⟨j, rfl⟩ use RootPairing.equiv_of_mapsTo p root coroot i hs hp j refine (coroot_eq_coreflection_of_root_eq_of_span_eq_top p root coroot hp hs hsp ?_) rw [equiv_of_mapsTo_apply, (exist_eq_reflection_of_mapsTo p root coroot i j hs).choose_spec] end RootSystem
LinearAlgebra\RootSystem\Defs.lean
/- Copyright (c) 2023 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash, Deepro Choudhury, Scott Carnahan -/ import Mathlib.LinearAlgebra.PerfectPairing import Mathlib.LinearAlgebra.Reflection /-! # Root data and root systems This file contains basic definitions for root systems and root data. ## Main definitions: * `RootPairing`: Given two perfectly-paired `R`-modules `M` and `N` (over some commutative ring `R`) a root pairing with indexing set `ι` is the data of an `ι`-indexed subset of `M` ("the roots") an `ι`-indexed subset of `N` ("the coroots"), and an `ι`-indexed set of permutations of `ι` such that each root-coroot pair evaluates to `2`, and the permutation attached to each element of `ι` is compatible with the reflections on the corresponding roots and coroots. * `RootDatum`: A root datum is a root pairing for which the roots and coroots take values in finitely-generated free Abelian groups. * `RootSystem`: A root system is a root pairing for which the roots span their ambient module. * `RootPairing.IsCrystallographic`: A root pairing is said to be crystallographic if the pairing between a root and coroot is always an integer. * `RootPairing.IsReduced`: A root pairing is said to be reduced if it never contains the double of a root. ## TODO * Put more API theorems in the Defs file. * Introduce the Weyl Group, and its action on the indexing set. * Base change of root pairings (may need flatness). * Isomorphism of root pairings. * Crystallographic root systems are isomorphic to base changes of root systems over `ℤ`: Take `M₀` and `N₀` to be the `ℤ`-span of roots and coroots. ## Implementation details A root datum is sometimes defined as two subsets: roots and coroots, together with a bijection between them, subject to hypotheses. However the hypotheses ensure that the bijection is unique and so the question arises of whether this bijection should be part of the data of a root datum or whether one should merely assert its existence. For root systems, things are even more extreme: the coroots are uniquely determined by the roots. Furthermore a root system induces a canonical non-degenerate bilinear form on the ambient space and many informal accounts even include this form as part of the data. We have opted for a design in which some of the uniquely-determined data is included: the bijection between roots and coroots is (implicitly) included and the coroots are included for root systems. Empirically this seems to be by far the most convenient design and by providing extensionality lemmas expressing the uniqueness we expect to get the best of both worlds. Furthermore, we require roots and coroots to be injections from a base indexing type `ι` rather than subsets of their codomains. This design was chosen to avoid the bijection between roots and coroots being a dependently-typed object. A third option would be to have the roots and coroots be subsets but to avoid having a dependently-typed bijection by defining it globally with junk value `0` outside of the roots and coroots. This would work but lacks the convenient symmetry that the chosen design enjoys: by introducing the indexing type `ι`, one does not have to pick a direction (`roots → coroots` or `coroots → roots`) for the forward direction of the bijection. Besides, providing the user with the additional definitional power to specify an indexing type `ι` is a benefit and the junk-value pattern is a cost. As a final point of divergence from the classical literature, we make the reflection permutation on roots and coroots explicit, rather than specifying only that reflection preserves the sets of roots and coroots. This is necessary when working with infinite root systems, where the coroots are not uniquely determined by the roots, because without it, the reflection permutations on roots and coroots may not correspond. For this purpose, we define a map from `ι` to permutations on `ι`, and require that it is compatible with reflections and coreflections. -/ open Set Function open Module hiding reflection open Submodule (span) open AddSubgroup (zmultiples) noncomputable section variable (ι R M N : Type*) [CommRing R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N] /-- Given two perfectly-paired `R`-modules `M` and `N`, a root pairing with indexing set `ι` is the data of an `ι`-indexed subset of `M` ("the roots"), an `ι`-indexed subset of `N` ("the coroots"), and an `ι`-indexed set of permutations of `ι`, such that each root-coroot pair evaluates to `2`, and the permutation attached to each element of `ι` is compatible with the reflections on the corresponding roots and coroots. It exists to allow for a convenient unification of the theories of root systems and root data. -/ structure RootPairing extends PerfectPairing R M N := /-- A parametrized family of vectors, called roots. -/ root : ι ↪ M /-- A parametrized family of dual vectors, called coroots. -/ coroot : ι ↪ N root_coroot_two : ∀ i, toLin (root i) (coroot i) = 2 /-- A parametrized family of permutations, induced by reflection. -/ reflection_perm : ι → (ι ≃ ι) reflection_perm_root : ∀ i j, root j - toLin (root j) (coroot i) • root i = root (reflection_perm i j) reflection_perm_coroot : ∀ i j, coroot j - toLin (root i) (coroot j) • coroot i = coroot (reflection_perm i j) /-- A root datum is a root pairing with coefficients in the integers and for which the root and coroot spaces are finitely-generated free Abelian groups. Note that the latter assumptions `[Free ℤ X₁] [Finite ℤ X₁] [Free ℤ X₂] [Finite ℤ X₂]` should be supplied as mixins. -/ abbrev RootDatum (X₁ X₂ : Type*) [AddCommGroup X₁] [AddCommGroup X₂] := RootPairing ι ℤ X₁ X₂ /-- A root system is a root pairing for which the roots span their ambient module. Note that this is slightly more general than the usual definition in the sense that `N` is not required to be the dual of `M`. -/ structure RootSystem extends RootPairing ι R M N := span_eq_top : span R (range root) = ⊤ namespace RootPairing variable {ι R M N} variable (P : RootPairing ι R M N) (i j : ι) lemma ne_zero [CharZero R] : (P.root i : M) ≠ 0 := fun h ↦ by simpa [h] using P.root_coroot_two i lemma ne_zero' [CharZero R] : (P.coroot i : N) ≠ 0 := fun h ↦ by simpa [h] using P.root_coroot_two i /-- If we interchange the roles of `M` and `N`, we still have a root pairing. -/ protected def flip : RootPairing ι R N M := { P.toPerfectPairing.flip with root := P.coroot coroot := P.root root_coroot_two := P.root_coroot_two reflection_perm := P.reflection_perm reflection_perm_root := P.reflection_perm_coroot reflection_perm_coroot := P.reflection_perm_root } @[simp] lemma flip_flip : P.flip.flip = P := rfl /-- This is the pairing between roots and coroots. -/ def pairing : R := P.toLin (P.root i) (P.coroot j) @[simp] lemma root_coroot_eq_pairing : P.toLin (P.root i) (P.coroot j) = P.pairing i j := rfl lemma coroot_root_eq_pairing : P.toLin.flip (P.coroot i) (P.root j) = P.pairing j i := by simp @[simp] lemma pairing_same : P.pairing i i = 2 := P.root_coroot_two i lemma coroot_root_two : P.toLin.flip (P.coroot i) (P.root i) = 2 := by simp /-- The reflection associated to a root. -/ def reflection : M ≃ₗ[R] M := Module.reflection (P.flip.root_coroot_two i) @[simp] lemma root_reflection_perm (j : ι) : P.root (P.reflection_perm i j) = (P.reflection i) (P.root j) := (P.reflection_perm_root i j).symm theorem mapsTo_reflection_root : MapsTo (P.reflection i) (range P.root) (range P.root) := by rintro - ⟨j, rfl⟩ exact P.root_reflection_perm i j ▸ mem_range_self (P.reflection_perm i j) lemma reflection_apply (x : M) : P.reflection i x = x - (P.toLin x (P.coroot i)) • P.root i := rfl lemma reflection_apply_root : P.reflection i (P.root j) = P.root j - (P.pairing j i) • P.root i := rfl @[simp] lemma reflection_apply_self : P.reflection i (P.root i) = - P.root i := Module.reflection_apply_self (P.coroot_root_two i) @[simp] lemma reflection_same (x : M) : P.reflection i (P.reflection i x) = x := Module.involutive_reflection (P.coroot_root_two i) x lemma bijOn_reflection_root : BijOn (P.reflection i) (range P.root) (range P.root) := Module.bijOn_reflection_of_mapsTo _ <| P.mapsTo_reflection_root i @[simp] lemma reflection_image_eq : P.reflection i '' (range P.root) = range P.root := (P.bijOn_reflection_root i).image_eq /-- The reflection associated to a coroot. -/ def coreflection : N ≃ₗ[R] N := Module.reflection (P.root_coroot_two i) @[simp] lemma coroot_reflection_perm (j : ι) : P.coroot (P.reflection_perm i j) = (P.coreflection i) (P.coroot j) := (P.reflection_perm_coroot i j).symm theorem mapsTo_coreflection_coroot : MapsTo (P.coreflection i) (range P.coroot) (range P.coroot) := by rintro - ⟨j, rfl⟩ exact P.coroot_reflection_perm i j ▸ mem_range_self (P.reflection_perm i j) lemma coreflection_apply (f : N) : P.coreflection i f = f - (P.toLin (P.root i) f) • P.coroot i := rfl lemma coreflection_apply_coroot : P.coreflection i (P.coroot j) = P.coroot j - (P.pairing i j) • P.coroot i := rfl @[simp] lemma coreflection_apply_self : P.coreflection i (P.coroot i) = - P.coroot i := Module.reflection_apply_self (P.flip.coroot_root_two i) @[simp] lemma coreflection_same (x : N) : P.coreflection i (P.coreflection i x) = x := Module.involutive_reflection (P.flip.coroot_root_two i) x lemma bijOn_coreflection_coroot : BijOn (P.coreflection i) (range P.coroot) (range P.coroot) := bijOn_reflection_root P.flip i @[simp] lemma coreflection_image_eq : P.coreflection i '' (range P.coroot) = range P.coroot := (P.bijOn_coreflection_coroot i).image_eq lemma coreflection_eq_flip_reflection : P.coreflection i = P.flip.reflection i := rfl lemma reflection_dualMap_eq_coreflection : (P.reflection i).dualMap ∘ₗ P.toLin.flip = P.toLin.flip ∘ₗ P.coreflection i := by ext n m simp [coreflection_apply, reflection_apply, mul_comm (P.toLin m (P.coroot i))] lemma coroot_eq_coreflection_of_root_eq {i j k : ι} (hk : P.root k = P.reflection i (P.root j)) : P.coroot k = P.coreflection i (P.coroot j) := by rw [← P.root_reflection_perm, EmbeddingLike.apply_eq_iff_eq] at hk rw [← P.coroot_reflection_perm, hk] /-- A root pairing is said to be crystallographic if the pairing between a root and coroot is always an integer. -/ def IsCrystallographic : Prop := ∀ i, MapsTo (P.toLin (P.root i)) (range P.coroot) (zmultiples (1 : R)) lemma isCrystallographic_iff : P.IsCrystallographic ↔ ∀ i j, ∃ z : ℤ, z = P.pairing i j := by rw [IsCrystallographic] refine ⟨fun h i j ↦ ?_, fun h i _ ⟨j, hj⟩ ↦ ?_⟩ · simpa [AddSubgroup.mem_zmultiples_iff] using h i (mem_range_self j) · simpa [← hj, AddSubgroup.mem_zmultiples_iff] using h i j /-- A root pairing is said to be reduced if any linearly dependent pair of roots is related by a sign. -/ def IsReduced : Prop := ∀ i j, ¬ LinearIndependent R ![P.root i, P.root j] → (P.root i = P.root j ∨ P.root i = - P.root j) lemma isReduced_iff : P.IsReduced ↔ ∀ i j : ι, i ≠ j → ¬ LinearIndependent R ![P.root i, P.root j] → P.root i = - P.root j := by rw [IsReduced] refine ⟨fun h i j hij hLin ↦ ?_, fun h i j hLin ↦ ?_⟩ · specialize h i j hLin simp_all only [ne_eq, EmbeddingLike.apply_eq_iff_eq, false_or] · by_cases h' : i = j · exact Or.inl (congrArg P.root h') · exact Or.inr (h i j h' hLin) /-- The Coxeter Weight of a pair gives the weight of an edge in a Coxeter diagram, when it is finite. It is `4 cos² θ`, where `θ` describes the dihedral angle between hyperplanes. -/ def coxeterWeight : R := pairing P i j * pairing P j i lemma coxeterWeight_swap : coxeterWeight P i j = coxeterWeight P j i := by simp only [coxeterWeight, mul_comm] /-- Two roots are orthogonal when they are fixed by each others' reflections. -/ def IsOrthogonal : Prop := pairing P i j = 0 ∧ pairing P j i = 0 lemma IsOrthogonal.symm : IsOrthogonal P i j ↔ IsOrthogonal P j i := by simp only [IsOrthogonal, and_comm] lemma isOrthogonal_comm (h : IsOrthogonal P i j) : Commute (P.reflection i) (P.reflection j) := by rw [Commute, SemiconjBy] ext v replace h : P.pairing i j = 0 ∧ P.pairing j i = 0 := by simpa [IsOrthogonal] using h erw [LinearMap.mul_apply, LinearMap.mul_apply] simp only [LinearEquiv.coe_coe, reflection_apply, map_sub, map_smul, root_coroot_eq_pairing, zero_smul, sub_zero, h] abel end RootPairing
LinearAlgebra\RootSystem\RootPositive.lean
/- Copyright (c) 2024 Scott Carnahan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Carnahan -/ import Mathlib.LinearAlgebra.RootSystem.Defs /-! # Root-positive bilinear forms on root pairings This file contains basic results on Weyl-invariant inner products for root systems and root data. We introduce a Prop-valued mixin class for a root pairing and bilinear form, specifying reflection-invariance, symmetry, and strict positivity on all roots. We show that root-positive forms display the same sign behavior as the canonical pairing between roots and coroots. Root-positive forms show up naturally as the invariant forms for symmetrizable Kac-Moody Lie algebras. In the finite case, the canonical polarization yields a root-positive form that is positive semi-definite on weight space and positive-definite on the span of roots. ## Main definitions: * `IsRootPositive`: A prop-valued mixin class for root pairings with bilinear forms, specifying the form is symmetric, reflection-invariant, and all roots have strictly positive norm. ## Main results: * `pairing_pos_iff` and `pairing_zero_iff` : sign relations between `P.pairing` and the form `B`. * `coxeter_weight_non_neg` : All pairs of roots have non-negative Coxeter weight. * `orthogonal_of_coxeter_weight_zero` : If Coxeter weight vanishes, then the roots are orthogonal. ## TODO * Invariance under the Weyl group. -/ noncomputable section variable {ι R M N : Type*} namespace RootPairing variable [LinearOrderedCommRing R] [AddCommGroup M] [Module R M] [AddCommGroup N] [Module R N] /-- A Prop-valued class for a bilinear form to be compatible with a root pairing. -/ class IsRootPositive (P : RootPairing ι R M N) (B : M →ₗ[R] M →ₗ[R] R) : Prop where zero_lt_apply_root : ∀ i, 0 < B (P.root i) (P.root i) symm : ∀ x y, B x y = B y x apply_reflection_eq : ∀ i x y, B (P.reflection i x) (P.reflection i y) = B x y variable {P : RootPairing ι R M N} (B : M →ₗ[R] M →ₗ[R] R) [IsRootPositive P B] (i j : ι) lemma two_mul_apply_root_root : 2 * B (P.root i) (P.root j) = P.pairing i j * B (P.root j) (P.root j) := by rw [two_mul, ← eq_sub_iff_add_eq] nth_rw 1 [← IsRootPositive.apply_reflection_eq (P := P) (B := B) j (P.root i) (P.root j)] rw [reflection_apply, reflection_apply_self, root_coroot_eq_pairing, LinearMap.map_sub₂, LinearMap.map_smul₂, smul_eq_mul, LinearMap.map_neg, LinearMap.map_neg, mul_neg, neg_sub_neg] @[simp] lemma zero_lt_apply_root_root_iff : 0 < B (P.root i) (P.root j) ↔ 0 < P.pairing i j := by refine ⟨fun h ↦ (mul_pos_iff_of_pos_right (IsRootPositive.zero_lt_apply_root (P := P) (B := B) j)).mp ?_, fun h ↦ (mul_pos_iff_of_pos_left zero_lt_two).mp ?_⟩ · rw [← two_mul_apply_root_root] exact mul_pos zero_lt_two h · rw [two_mul_apply_root_root] exact mul_pos h (IsRootPositive.zero_lt_apply_root (P := P) (B := B) j) lemma zero_lt_pairing_iff : 0 < P.pairing i j ↔ 0 < P.pairing j i := by rw [← zero_lt_apply_root_root_iff B, IsRootPositive.symm P, zero_lt_apply_root_root_iff] lemma coxeterWeight_non_neg : 0 ≤ P.coxeterWeight i j := by dsimp [coxeterWeight] by_cases h : 0 < P.pairing i j · exact le_of_lt <| mul_pos h ((zero_lt_pairing_iff B i j).mp h) · have hn : ¬ 0 < P.pairing j i := fun hc ↦ h ((zero_lt_pairing_iff B i j).mpr hc) simp_all only [not_lt, ge_iff_le] exact mul_nonneg_of_nonpos_of_nonpos h hn @[simp] lemma apply_root_root_zero_iff : B (P.root i) (P.root j) = 0 ↔ P.pairing i j = 0 := by refine ⟨fun hB => ?_, fun hP => ?_⟩ · have h2 : 2 * (B (P.root i)) (P.root j) = 0 := mul_eq_zero_of_right 2 hB rw [two_mul_apply_root_root] at h2 exact eq_zero_of_ne_zero_of_mul_right_eq_zero (IsRootPositive.zero_lt_apply_root j).ne' h2 · have h2 : 2 * B (P.root i) (P.root j) = 0 := by rw [two_mul_apply_root_root, hP, zero_mul] exact (mul_eq_zero.mp h2).resolve_left two_ne_zero lemma pairing_zero_iff : P.pairing i j = 0 ↔ P.pairing j i = 0 := by rw [← apply_root_root_zero_iff B, IsRootPositive.symm P, apply_root_root_zero_iff B] lemma coxeterWeight_zero_iff_isOrthogonal : P.coxeterWeight i j = 0 ↔ P.IsOrthogonal i j := by rw [coxeterWeight, mul_eq_zero] refine ⟨fun h => ?_, fun h => Or.inl h.1⟩ rcases h with h | h · exact ⟨h, (pairing_zero_iff B i j).mp h⟩ · exact ⟨(pairing_zero_iff B j i).mp h, h⟩ end RootPairing
LinearAlgebra\TensorAlgebra\Basic.lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import Mathlib.Algebra.FreeAlgebra import Mathlib.Algebra.RingQuot import Mathlib.Algebra.TrivSqZeroExt import Mathlib.Algebra.Algebra.Operations import Mathlib.LinearAlgebra.Multilinear.Basic /-! # Tensor Algebras Given a commutative semiring `R`, and an `R`-module `M`, we construct the tensor algebra of `M`. This is the free `R`-algebra generated (`R`-linearly) by the module `M`. ## Notation 1. `TensorAlgebra R M` is the tensor algebra itself. It is endowed with an R-algebra structure. 2. `TensorAlgebra.ι R` is the canonical R-linear map `M → TensorAlgebra R M`. 3. Given a linear map `f : M → A` to an R-algebra `A`, `lift R f` is the lift of `f` to an `R`-algebra morphism `TensorAlgebra R M → A`. ## Theorems 1. `ι_comp_lift` states that the composition `(lift R f) ∘ (ι R)` is identical to `f`. 2. `lift_unique` states that whenever an R-algebra morphism `g : TensorAlgebra R M → A` is given whose composition with `ι R` is `f`, then one has `g = lift R f`. 3. `hom_ext` is a variant of `lift_unique` in the form of an extensionality theorem. 4. `lift_comp_ι` is a combination of `ι_comp_lift` and `lift_unique`. It states that the lift of the composition of an algebra morphism with `ι` is the algebra morphism itself. ## Implementation details As noted above, the tensor algebra of `M` is constructed as the free `R`-algebra generated by `M`, modulo the additional relations making the inclusion of `M` into an `R`-linear map. -/ variable (R : Type*) [CommSemiring R] variable (M : Type*) [AddCommMonoid M] [Module R M] namespace TensorAlgebra /-- An inductively defined relation on `Pre R M` used to force the initial algebra structure on the associated quotient. -/ inductive Rel : FreeAlgebra R M → FreeAlgebra R M → Prop -- force `ι` to be linear | add {a b : M} : Rel (FreeAlgebra.ι R (a + b)) (FreeAlgebra.ι R a + FreeAlgebra.ι R b) | smul {r : R} {a : M} : Rel (FreeAlgebra.ι R (r • a)) (algebraMap R (FreeAlgebra R M) r * FreeAlgebra.ι R a) end TensorAlgebra /-- The tensor algebra of the module `M` over the commutative semiring `R`. -/ def TensorAlgebra := RingQuot (TensorAlgebra.Rel R M) -- Porting note: Expanded `deriving Inhabited, Semiring, Algebra` instance : Inhabited (TensorAlgebra R M) := RingQuot.instInhabited _ instance : Semiring (TensorAlgebra R M) := RingQuot.instSemiring _ -- `IsScalarTower` is not needed, but the instance isn't really canonical without it. @[nolint unusedArguments] instance instAlgebra {R A M} [CommSemiring R] [AddCommMonoid M] [CommSemiring A] [Algebra R A] [Module R M] [Module A M] [IsScalarTower R A M] : Algebra R (TensorAlgebra A M) := RingQuot.instAlgebra _ -- verify there is no diamond -- but doesn't work at `reducible_and_instances` #10906 example : (Semiring.toNatAlgebra : Algebra ℕ (TensorAlgebra R M)) = instAlgebra := rfl instance {R S A M} [CommSemiring R] [CommSemiring S] [AddCommMonoid M] [CommSemiring A] [Algebra R A] [Algebra S A] [Module R M] [Module S M] [Module A M] [IsScalarTower R A M] [IsScalarTower S A M] : SMulCommClass R S (TensorAlgebra A M) := RingQuot.instSMulCommClass _ instance {R S A M} [CommSemiring R] [CommSemiring S] [AddCommMonoid M] [CommSemiring A] [SMul R S] [Algebra R A] [Algebra S A] [Module R M] [Module S M] [Module A M] [IsScalarTower R A M] [IsScalarTower S A M] [IsScalarTower R S A] : IsScalarTower R S (TensorAlgebra A M) := RingQuot.instIsScalarTower _ namespace TensorAlgebra instance {S : Type*} [CommRing S] [Module S M] : Ring (TensorAlgebra S M) := RingQuot.instRing (Rel S M) -- verify there is no diamond -- but doesn't work at `reducible_and_instances` #10906 variable (S M : Type) [CommRing S] [AddCommGroup M] [Module S M] in example : (Ring.toIntAlgebra _ : Algebra ℤ (TensorAlgebra S M)) = instAlgebra := rfl variable {M} /-- The canonical linear map `M →ₗ[R] TensorAlgebra R M`. -/ irreducible_def ι : M →ₗ[R] TensorAlgebra R M := { toFun := fun m => RingQuot.mkAlgHom R _ (FreeAlgebra.ι R m) map_add' := fun x y => by rw [← map_add (RingQuot.mkAlgHom R (Rel R M))] exact RingQuot.mkAlgHom_rel R Rel.add map_smul' := fun r x => by rw [← map_smul (RingQuot.mkAlgHom R (Rel R M))] exact RingQuot.mkAlgHom_rel R Rel.smul } theorem ringQuot_mkAlgHom_freeAlgebra_ι_eq_ι (m : M) : RingQuot.mkAlgHom R (Rel R M) (FreeAlgebra.ι R m) = ι R m := by rw [ι] rfl -- Porting note: Changed `irreducible_def` to `def` to get `@[simps symm_apply]` to work /-- Given a linear map `f : M → A` where `A` is an `R`-algebra, `lift R f` is the unique lift of `f` to a morphism of `R`-algebras `TensorAlgebra R M → A`. -/ @[simps symm_apply] def lift {A : Type*} [Semiring A] [Algebra R A] : (M →ₗ[R] A) ≃ (TensorAlgebra R M →ₐ[R] A) := { toFun := RingQuot.liftAlgHom R ∘ fun f => ⟨FreeAlgebra.lift R (⇑f), fun x y (h : Rel R M x y) => by induction h <;> simp only [Algebra.smul_def, FreeAlgebra.lift_ι_apply, LinearMap.map_smulₛₗ, RingHom.id_apply, map_mul, AlgHom.commutes, map_add]⟩ invFun := fun F => F.toLinearMap.comp (ι R) left_inv := fun f => by rw [ι] ext1 x exact (RingQuot.liftAlgHom_mkAlgHom_apply _ _ _ _).trans (FreeAlgebra.lift_ι_apply f x) right_inv := fun F => RingQuot.ringQuot_ext' _ _ _ <| FreeAlgebra.hom_ext <| funext fun x => by rw [ι] exact (RingQuot.liftAlgHom_mkAlgHom_apply _ _ _ _).trans (FreeAlgebra.lift_ι_apply _ _) } variable {R} @[simp] theorem ι_comp_lift {A : Type*} [Semiring A] [Algebra R A] (f : M →ₗ[R] A) : (lift R f).toLinearMap.comp (ι R) = f := by convert (lift R).symm_apply_apply f @[simp] theorem lift_ι_apply {A : Type*} [Semiring A] [Algebra R A] (f : M →ₗ[R] A) (x) : lift R f (ι R x) = f x := by conv_rhs => rw [← ι_comp_lift f] rfl @[simp] theorem lift_unique {A : Type*} [Semiring A] [Algebra R A] (f : M →ₗ[R] A) (g : TensorAlgebra R M →ₐ[R] A) : g.toLinearMap.comp (ι R) = f ↔ g = lift R f := by rw [← (lift R).symm_apply_eq] simp only [lift, Equiv.coe_fn_symm_mk] -- Marking `TensorAlgebra` irreducible makes `Ring` instances inaccessible on quotients. -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 -- For now, we avoid this by not marking it irreducible. @[simp] theorem lift_comp_ι {A : Type*} [Semiring A] [Algebra R A] (g : TensorAlgebra R M →ₐ[R] A) : lift R (g.toLinearMap.comp (ι R)) = g := by rw [← lift_symm_apply] exact (lift R).apply_symm_apply g /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {A : Type*} [Semiring A] [Algebra R A] {f g : TensorAlgebra R M →ₐ[R] A} (w : f.toLinearMap.comp (ι R) = g.toLinearMap.comp (ι R)) : f = g := by rw [← lift_symm_apply, ← lift_symm_apply] at w exact (lift R).symm.injective w -- This proof closely follows `FreeAlgebra.induction` /-- If `C` holds for the `algebraMap` of `r : R` into `TensorAlgebra R M`, the `ι` of `x : M`, and is preserved under addition and muliplication, then it holds for all of `TensorAlgebra R M`. -/ @[elab_as_elim] theorem induction {C : TensorAlgebra R M → Prop} (algebraMap : ∀ r, C (algebraMap R (TensorAlgebra R M) r)) (ι : ∀ x, C (ι R x)) (mul : ∀ a b, C a → C b → C (a * b)) (add : ∀ a b, C a → C b → C (a + b)) (a : TensorAlgebra R M) : C a := by -- the arguments are enough to construct a subalgebra, and a mapping into it from M let s : Subalgebra R (TensorAlgebra R M) := { carrier := C mul_mem' := @mul add_mem' := @add algebraMap_mem' := algebraMap } -- Porting note: Added `h`. `h` is needed for `of`. let h : AddCommMonoid s := inferInstanceAs (AddCommMonoid (Subalgebra.toSubmodule s)) let of : M →ₗ[R] s := (TensorAlgebra.ι R).codRestrict (Subalgebra.toSubmodule s) ι -- the mapping through the subalgebra is the identity have of_id : AlgHom.id R (TensorAlgebra R M) = s.val.comp (lift R of) := by ext simp only [AlgHom.toLinearMap_id, LinearMap.id_comp, AlgHom.comp_toLinearMap, LinearMap.coe_comp, Function.comp_apply, AlgHom.toLinearMap_apply, lift_ι_apply, Subalgebra.coe_val] erw [LinearMap.codRestrict_apply] -- finding a proof is finding an element of the subalgebra rw [← AlgHom.id_apply (R := R) a, of_id] exact Subtype.prop (lift R of a) /-- The left-inverse of `algebraMap`. -/ def algebraMapInv : TensorAlgebra R M →ₐ[R] R := lift R (0 : M →ₗ[R] R) variable (M) theorem algebraMap_leftInverse : Function.LeftInverse algebraMapInv (algebraMap R <| TensorAlgebra R M) := fun x => by simp [algebraMapInv] @[simp] theorem algebraMap_inj (x y : R) : algebraMap R (TensorAlgebra R M) x = algebraMap R (TensorAlgebra R M) y ↔ x = y := (algebraMap_leftInverse M).injective.eq_iff @[simp] theorem algebraMap_eq_zero_iff (x : R) : algebraMap R (TensorAlgebra R M) x = 0 ↔ x = 0 := map_eq_zero_iff (algebraMap _ _) (algebraMap_leftInverse _).injective @[simp] theorem algebraMap_eq_one_iff (x : R) : algebraMap R (TensorAlgebra R M) x = 1 ↔ x = 1 := map_eq_one_iff (algebraMap _ _) (algebraMap_leftInverse _).injective /-- A `TensorAlgebra` over a nontrivial semiring is nontrivial. -/ instance [Nontrivial R] : Nontrivial (TensorAlgebra R M) := (algebraMap_leftInverse M).injective.nontrivial variable {M} /-- The canonical map from `TensorAlgebra R M` into `TrivSqZeroExt R M` that sends `TensorAlgebra.ι` to `TrivSqZeroExt.inr`. -/ def toTrivSqZeroExt [Module Rᵐᵒᵖ M] [IsCentralScalar R M] : TensorAlgebra R M →ₐ[R] TrivSqZeroExt R M := lift R (TrivSqZeroExt.inrHom R M) @[simp] theorem toTrivSqZeroExt_ι (x : M) [Module Rᵐᵒᵖ M] [IsCentralScalar R M] : toTrivSqZeroExt (ι R x) = TrivSqZeroExt.inr x := lift_ι_apply _ _ /-- The left-inverse of `ι`. As an implementation detail, we implement this using `TrivSqZeroExt` which has a suitable algebra structure. -/ def ιInv : TensorAlgebra R M →ₗ[R] M := by letI : Module Rᵐᵒᵖ M := Module.compHom _ ((RingHom.id R).fromOpposite mul_comm) haveI : IsCentralScalar R M := ⟨fun r m => rfl⟩ exact (TrivSqZeroExt.sndHom R M).comp toTrivSqZeroExt.toLinearMap theorem ι_leftInverse : Function.LeftInverse ιInv (ι R : M → TensorAlgebra R M) := fun x ↦ by simp [ιInv] variable (R) @[simp] theorem ι_inj (x y : M) : ι R x = ι R y ↔ x = y := ι_leftInverse.injective.eq_iff @[simp] theorem ι_eq_zero_iff (x : M) : ι R x = 0 ↔ x = 0 := by rw [← ι_inj R x 0, LinearMap.map_zero] variable {R} @[simp] theorem ι_eq_algebraMap_iff (x : M) (r : R) : ι R x = algebraMap R _ r ↔ x = 0 ∧ r = 0 := by refine ⟨fun h => ?_, ?_⟩ · letI : Module Rᵐᵒᵖ M := Module.compHom _ ((RingHom.id R).fromOpposite mul_comm) haveI : IsCentralScalar R M := ⟨fun r m => rfl⟩ have hf0 : toTrivSqZeroExt (ι R x) = (0, x) := lift_ι_apply _ _ rw [h, AlgHom.commutes] at hf0 have : r = 0 ∧ 0 = x := Prod.ext_iff.1 hf0 exact this.symm.imp_left Eq.symm · rintro ⟨rfl, rfl⟩ rw [LinearMap.map_zero, RingHom.map_zero] @[simp] theorem ι_ne_one [Nontrivial R] (x : M) : ι R x ≠ 1 := by rw [← (algebraMap R (TensorAlgebra R M)).map_one, Ne, ι_eq_algebraMap_iff] exact one_ne_zero ∘ And.right /-- The generators of the tensor algebra are disjoint from its scalars. -/ theorem ι_range_disjoint_one : Disjoint (LinearMap.range (ι R : M →ₗ[R] TensorAlgebra R M)) (1 : Submodule R (TensorAlgebra R M)) := by rw [Submodule.disjoint_def] rintro _ ⟨x, hx⟩ ⟨r, rfl⟩ rw [Algebra.linearMap_apply, ι_eq_algebraMap_iff] at hx rw [hx.2, map_zero] variable (R M) /-- Construct a product of `n` elements of the module within the tensor algebra. See also `PiTensorProduct.tprod`. -/ def tprod (n : ℕ) : MultilinearMap R (fun _ : Fin n => M) (TensorAlgebra R M) := (MultilinearMap.mkPiAlgebraFin R n (TensorAlgebra R M)).compLinearMap fun _ => ι R @[simp] theorem tprod_apply {n : ℕ} (x : Fin n → M) : tprod R M n x = (List.ofFn fun i => ι R (x i)).prod := rfl variable {R M} end TensorAlgebra namespace FreeAlgebra variable {R M} /-- The canonical image of the `FreeAlgebra` in the `TensorAlgebra`, which maps `FreeAlgebra.ι R x` to `TensorAlgebra.ι R x`. -/ def toTensor : FreeAlgebra R M →ₐ[R] TensorAlgebra R M := FreeAlgebra.lift R (TensorAlgebra.ι R) @[simp] theorem toTensor_ι (m : M) : FreeAlgebra.toTensor (FreeAlgebra.ι R m) = TensorAlgebra.ι R m := by simp [toTensor] end FreeAlgebra
LinearAlgebra\TensorAlgebra\Basis.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.LinearAlgebra.TensorAlgebra.Basic import Mathlib.LinearAlgebra.FreeAlgebra /-! # A basis for `TensorAlgebra R M` ## Main definitions * `TensorAlgebra.equivMonoidAlgebra b : TensorAlgebra R M ≃ₐ[R] FreeAlgebra R κ`: the isomorphism given by a basis `b : Basis κ R M`. * `Basis.tensorAlgebra b : Basis (FreeMonoid κ) R (TensorAlgebra R M)`: the basis on the tensor algebra given by a basis `b : Basis κ R M`. ## Main results * `TensorAlgebra.instFreeModule`: the tensor algebra over `M` is free when `M` is * `TensorAlgebra.rank_eq` -/ namespace TensorAlgebra universe uκ uR uM variable {κ : Type uκ} {R : Type uR} {M : Type uM} section CommSemiring variable [CommSemiring R] [AddCommMonoid M] [Module R M] /-- A basis provides an algebra isomorphism with the free algebra, replacing each basis vector with its index. -/ noncomputable def equivFreeAlgebra (b : Basis κ R M) : TensorAlgebra R M ≃ₐ[R] FreeAlgebra R κ := AlgEquiv.ofAlgHom (TensorAlgebra.lift _ (Finsupp.total _ _ _ (FreeAlgebra.ι _) ∘ₗ b.repr.toLinearMap)) (FreeAlgebra.lift _ (ι R ∘ b)) (by ext; simp) (hom_ext <| b.ext fun i => by simp) @[simp] lemma equivFreeAlgebra_ι_apply (b : Basis κ R M) (i : κ) : equivFreeAlgebra b (ι R (b i)) = FreeAlgebra.ι R i := (TensorAlgebra.lift_ι_apply _ _).trans <| by simp @[simp] lemma equivFreeAlgebra_symm_ι (b : Basis κ R M) (i : κ) : (equivFreeAlgebra b).symm (FreeAlgebra.ι R i) = ι R (b i) := (equivFreeAlgebra b).toEquiv.symm_apply_eq.mpr <| equivFreeAlgebra_ι_apply b i |>.symm /-- A basis on `M` can be lifted to a basis on `TensorAlgebra R M` -/ @[simps! repr_apply] noncomputable def _root_.Basis.tensorAlgebra (b : Basis κ R M) : Basis (FreeMonoid κ) R (TensorAlgebra R M) := (FreeAlgebra.basisFreeMonoid R κ).map <| (equivFreeAlgebra b).symm.toLinearEquiv /-- `TensorAlgebra R M` is free when `M` is. -/ instance instModuleFree [Module.Free R M] : Module.Free R (TensorAlgebra R M) := let ⟨⟨_κ, b⟩⟩ := Module.Free.exists_basis (R := R) (M := M) .of_basis b.tensorAlgebra /-- The `TensorAlgebra` of a free module over a commutative semiring with no zero-divisors has no zero-divisors. -/ instance instNoZeroDivisors [NoZeroDivisors R] [Module.Free R M] : NoZeroDivisors (TensorAlgebra R M) := have ⟨⟨κ, b⟩⟩ := ‹Module.Free R M› (equivFreeAlgebra b).toMulEquiv.noZeroDivisors end CommSemiring section CommRing variable [CommRing R] [AddCommGroup M] [Module R M] /-- The `TensorAlgebra` of a free module over an integral domain is a domain. -/ instance instIsDomain [IsDomain R] [Module.Free R M] : IsDomain (TensorAlgebra R M) := NoZeroDivisors.to_isDomain _ attribute [pp_with_univ] Cardinal.lift open Cardinal in lemma rank_eq [Nontrivial R] [Module.Free R M] : Module.rank R (TensorAlgebra R M) = Cardinal.lift.{uR} (sum fun n ↦ Module.rank R M ^ n) := by let ⟨⟨κ, b⟩⟩ := Module.Free.exists_basis (R := R) (M := M) rw [(equivFreeAlgebra b).toLinearEquiv.rank_eq, FreeAlgebra.rank_eq, mk_list_eq_sum_pow, Basis.mk_eq_rank'' b] end CommRing end TensorAlgebra
LinearAlgebra\TensorAlgebra\Grading.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.LinearAlgebra.TensorAlgebra.Basic import Mathlib.RingTheory.GradedAlgebra.Basic /-! # Results about the grading structure of the tensor algebra The main result is `TensorAlgebra.gradedAlgebra`, which says that the tensor algebra is a ℕ-graded algebra. -/ suppress_compilation namespace TensorAlgebra variable {R M : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] open scoped DirectSum variable (R M) /-- A version of `TensorAlgebra.ι` that maps directly into the graded structure. This is primarily an auxiliary construction used to provide `TensorAlgebra.gradedAlgebra`. -/ nonrec def GradedAlgebra.ι : M →ₗ[R] ⨁ i : ℕ, ↥(LinearMap.range (ι R : M →ₗ[_] _) ^ i) := DirectSum.lof R ℕ (fun i => ↥(LinearMap.range (ι R : M →ₗ[_] _) ^ i)) 1 ∘ₗ (ι R).codRestrict _ fun m => by simpa only [pow_one] using LinearMap.mem_range_self _ m theorem GradedAlgebra.ι_apply (m : M) : GradedAlgebra.ι R M m = DirectSum.of (fun (i : ℕ) => ↥(LinearMap.range (TensorAlgebra.ι R : M →ₗ[_] _) ^ i)) 1 ⟨TensorAlgebra.ι R m, by simpa only [pow_one] using LinearMap.mem_range_self _ m⟩ := rfl variable {R M} /-- The tensor algebra is graded by the powers of the submodule `(TensorAlgebra.ι R).range`. -/ instance gradedAlgebra : GradedAlgebra ((LinearMap.range (ι R : M →ₗ[R] TensorAlgebra R M) ^ ·) : ℕ → Submodule R _) := GradedAlgebra.ofAlgHom _ (lift R <| GradedAlgebra.ι R M) (by ext m dsimp only [LinearMap.comp_apply, AlgHom.toLinearMap_apply, AlgHom.comp_apply, AlgHom.id_apply] rw [lift_ι_apply, GradedAlgebra.ι_apply R M, DirectSum.coeAlgHom_of, Subtype.coe_mk]) fun i x => by cases' x with x hx dsimp only [Subtype.coe_mk, DirectSum.lof_eq_of] -- Porting note: use new `induction using` support that failed in Lean 3 induction hx using Submodule.pow_induction_on_left' with | algebraMap r => rw [AlgHom.commutes, DirectSum.algebraMap_apply]; rfl | add x y i hx hy ihx ihy => -- Note: #8386 had to specialize `map_add` to avoid a timeout -- (the extra typeclass search seems to have pushed this already slow proof over the edge) rw [map_add, ihx, ihy, ← AddMonoidHom.map_add] rfl | mem_mul m hm i x hx ih => obtain ⟨_, rfl⟩ := hm rw [map_mul, ih, lift_ι_apply, GradedAlgebra.ι_apply R M, DirectSum.of_mul_of] exact DirectSum.of_eq_of_gradedMonoid_eq (Sigma.subtype_ext (add_comm _ _) rfl) end TensorAlgebra
LinearAlgebra\TensorAlgebra\ToTensorPower.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.LinearAlgebra.TensorAlgebra.Basic import Mathlib.LinearAlgebra.TensorPower /-! # Tensor algebras as direct sums of tensor powers In this file we show that `TensorAlgebra R M` is isomorphic to a direct sum of tensor powers, as `TensorAlgebra.equivDirectSum`. -/ suppress_compilation open scoped DirectSum TensorProduct variable {R M : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] namespace TensorPower /-- The canonical embedding from a tensor power to the tensor algebra -/ def toTensorAlgebra {n} : ⨂[R]^n M →ₗ[R] TensorAlgebra R M := PiTensorProduct.lift (TensorAlgebra.tprod R M n) @[simp] theorem toTensorAlgebra_tprod {n} (x : Fin n → M) : TensorPower.toTensorAlgebra (PiTensorProduct.tprod R x) = TensorAlgebra.tprod R M n x := PiTensorProduct.lift.tprod _ @[simp] theorem toTensorAlgebra_gOne : TensorPower.toTensorAlgebra (@GradedMonoid.GOne.one _ (fun n => ⨂[R]^n M) _ _) = 1 := TensorPower.toTensorAlgebra_tprod _ @[simp] theorem toTensorAlgebra_gMul {i j} (a : (⨂[R]^i) M) (b : (⨂[R]^j) M) : TensorPower.toTensorAlgebra (@GradedMonoid.GMul.mul _ (fun n => ⨂[R]^n M) _ _ _ _ a b) = TensorPower.toTensorAlgebra a * TensorPower.toTensorAlgebra b := by -- change `a` and `b` to `tprod R a` and `tprod R b` rw [TensorPower.gMul_eq_coe_linearMap, ← LinearMap.compr₂_apply, ← @LinearMap.mul_apply' R, ← LinearMap.compl₂_apply, ← LinearMap.comp_apply] refine LinearMap.congr_fun (LinearMap.congr_fun ?_ a) b clear! a b ext (a b) -- Porting note: pulled the next two lines out of the long `simp only` below. simp only [LinearMap.compMultilinearMap_apply] rw [LinearMap.compr₂_apply, ← gMul_eq_coe_linearMap] simp only [LinearMap.compr₂_apply, LinearMap.mul_apply', LinearMap.compl₂_apply, LinearMap.comp_apply, LinearMap.compMultilinearMap_apply, PiTensorProduct.lift.tprod, TensorPower.tprod_mul_tprod, TensorPower.toTensorAlgebra_tprod, TensorAlgebra.tprod_apply, ← gMul_eq_coe_linearMap] refine Eq.trans ?_ List.prod_append congr -- Porting note: `erw` for `Function.comp` erw [← List.map_ofFn _ (TensorAlgebra.ι R), ← List.map_ofFn _ (TensorAlgebra.ι R), ← List.map_ofFn _ (TensorAlgebra.ι R), ← List.map_append, List.ofFn_fin_append] @[simp] theorem toTensorAlgebra_galgebra_toFun (r : R) : TensorPower.toTensorAlgebra (DirectSum.GAlgebra.toFun (R := R) (A := fun n => ⨂[R]^n M) r) = algebraMap _ _ r := by rw [TensorPower.galgebra_toFun_def, TensorPower.algebraMap₀_eq_smul_one, LinearMap.map_smul, TensorPower.toTensorAlgebra_gOne, Algebra.algebraMap_eq_smul_one] end TensorPower namespace TensorAlgebra /-- The canonical map from a direct sum of tensor powers to the tensor algebra. -/ def ofDirectSum : (⨁ n, ⨂[R]^n M) →ₐ[R] TensorAlgebra R M := DirectSum.toAlgebra _ _ (fun _ => TensorPower.toTensorAlgebra) TensorPower.toTensorAlgebra_gOne (fun {_ _} => TensorPower.toTensorAlgebra_gMul) @[simp] theorem ofDirectSum_of_tprod {n} (x : Fin n → M) : ofDirectSum (DirectSum.of _ n (PiTensorProduct.tprod R x)) = tprod R M n x := (DirectSum.toAddMonoid_of (fun _ ↦ LinearMap.toAddMonoidHom TensorPower.toTensorAlgebra) _ _).trans (TensorPower.toTensorAlgebra_tprod _) /-- The canonical map from the tensor algebra to a direct sum of tensor powers. -/ def toDirectSum : TensorAlgebra R M →ₐ[R] ⨁ n, ⨂[R]^n M := TensorAlgebra.lift R <| DirectSum.lof R ℕ (fun n => ⨂[R]^n M) _ ∘ₗ (LinearEquiv.symm <| PiTensorProduct.subsingletonEquiv (0 : Fin 1) : M ≃ₗ[R] _).toLinearMap @[simp] theorem toDirectSum_ι (x : M) : toDirectSum (ι R x) = DirectSum.of (fun n => ⨂[R]^n M) _ (PiTensorProduct.tprod R fun _ : Fin 1 => x) := TensorAlgebra.lift_ι_apply _ _ theorem ofDirectSum_comp_toDirectSum : ofDirectSum.comp toDirectSum = AlgHom.id R (TensorAlgebra R M) := by ext simp [DirectSum.lof_eq_of, tprod_apply] @[simp] theorem ofDirectSum_toDirectSum (x : TensorAlgebra R M) : ofDirectSum (TensorAlgebra.toDirectSum x) = x := AlgHom.congr_fun ofDirectSum_comp_toDirectSum x @[simp, nolint simpNF] -- see std4#365 for the simpNF issue theorem mk_reindex_cast {n m : ℕ} (h : n = m) (x : ⨂[R]^n M) : GradedMonoid.mk (A := fun i => (⨂[R]^i) M) m (PiTensorProduct.reindex R (fun _ ↦ M) (Equiv.cast <| congr_arg Fin h) x) = GradedMonoid.mk n x := Eq.symm (PiTensorProduct.gradedMonoid_eq_of_reindex_cast h rfl) @[simp] theorem mk_reindex_fin_cast {n m : ℕ} (h : n = m) (x : ⨂[R]^n M) : GradedMonoid.mk (A := fun i => (⨂[R]^i) M) m (PiTensorProduct.reindex R (fun _ ↦ M) (finCongr h) x) = GradedMonoid.mk n x := by rw [finCongr_eq_equivCast, mk_reindex_cast h] /-- The product of tensor products made of a single vector is the same as a single product of all the vectors. -/ theorem _root_.TensorPower.list_prod_gradedMonoid_mk_single (n : ℕ) (x : Fin n → M) : ((List.finRange n).map fun a => (GradedMonoid.mk _ (PiTensorProduct.tprod R fun _ : Fin 1 => x a) : GradedMonoid fun n => ⨂[R]^n M)).prod = GradedMonoid.mk n (PiTensorProduct.tprod R x) := by refine Fin.consInduction ?_ ?_ x <;> clear x · rw [List.finRange_zero, List.map_nil, List.prod_nil] rfl · intro n x₀ x ih rw [List.finRange_succ_eq_map, List.map_cons, List.prod_cons, List.map_map] simp_rw [Function.comp, Fin.cons_zero, Fin.cons_succ] rw [ih, GradedMonoid.mk_mul_mk, TensorPower.tprod_mul_tprod] refine TensorPower.gradedMonoid_eq_of_cast (add_comm _ _) ?_ dsimp only [GradedMonoid.mk] rw [TensorPower.cast_tprod] simp_rw [Fin.append_left_eq_cons, Function.comp] congr 1 with i theorem toDirectSum_tensorPower_tprod {n} (x : Fin n → M) : toDirectSum (tprod R M n x) = DirectSum.of _ n (PiTensorProduct.tprod R x) := by rw [tprod_apply, map_list_prod, List.map_ofFn] simp_rw [Function.comp, toDirectSum_ι] rw [DirectSum.list_prod_ofFn_of_eq_dProd] apply DirectSum.of_eq_of_gradedMonoid_eq rw [GradedMonoid.mk_list_dProd] rw [TensorPower.list_prod_gradedMonoid_mk_single] theorem toDirectSum_comp_ofDirectSum : toDirectSum.comp ofDirectSum = AlgHom.id R (⨁ n, ⨂[R]^n M) := by ext simp [DirectSum.lof_eq_of, -tprod_apply, toDirectSum_tensorPower_tprod] @[simp] theorem toDirectSum_ofDirectSum (x : ⨁ n, ⨂[R]^n M) : TensorAlgebra.toDirectSum (ofDirectSum x) = x := AlgHom.congr_fun toDirectSum_comp_ofDirectSum x /-- The tensor algebra is isomorphic to a direct sum of tensor powers. -/ @[simps!] def equivDirectSum : TensorAlgebra R M ≃ₐ[R] ⨁ n, ⨂[R]^n M := AlgEquiv.ofAlgHom toDirectSum ofDirectSum toDirectSum_comp_ofDirectSum ofDirectSum_comp_toDirectSum end TensorAlgebra
LinearAlgebra\TensorProduct\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, Mario Carneiro -/ import Mathlib.Algebra.Module.Submodule.Bilinear import Mathlib.Algebra.Module.Equiv.Basic import Mathlib.GroupTheory.Congruence.Basic import Mathlib.Tactic.Abel import Mathlib.Tactic.SuppressCompilation /-! # Tensor product of modules over commutative semirings. This file constructs the tensor product of modules over commutative semirings. Given a semiring `R` and modules over it `M` and `N`, the standard construction of the tensor product is `TensorProduct R M N`. It is also a module over `R`. It comes with a canonical bilinear map `TensorProduct.mk R M N : M →ₗ[R] N →ₗ[R] TensorProduct R M N`. Given any bilinear map `f : M →ₗ[R] N →ₗ[R] P`, there is a unique linear map `TensorProduct.lift f : TensorProduct R M N →ₗ[R] P` whose composition with the canonical bilinear map `TensorProduct.mk` is the given bilinear map `f`. Uniqueness is shown in the theorem `TensorProduct.lift.unique`. ## Notation * This file introduces the notation `M ⊗ N` and `M ⊗[R] N` for the tensor product space `TensorProduct R M N`. * It introduces the notation `m ⊗ₜ n` and `m ⊗ₜ[R] n` for the tensor product of two elements, otherwise written as `TensorProduct.tmul R m n`. ## Tags bilinear, tensor, tensor product -/ suppress_compilation section Semiring variable {R : Type*} [CommSemiring R] variable {R' : Type*} [Monoid R'] variable {R'' : Type*} [Semiring R''] variable {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} {T : Type*} variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] variable [AddCommMonoid Q] [AddCommMonoid S] [AddCommMonoid T] variable [Module R M] [Module R N] [Module R Q] [Module R S] [Module R T] variable [DistribMulAction R' M] variable [Module R'' M] variable (M N) namespace TensorProduct section variable (R) /-- The relation on `FreeAddMonoid (M × N)` that generates a congruence whose quotient is the tensor product. -/ inductive Eqv : FreeAddMonoid (M × N) → FreeAddMonoid (M × N) → Prop | of_zero_left : ∀ n : N, Eqv (.of (0, n)) 0 | of_zero_right : ∀ m : M, Eqv (.of (m, 0)) 0 | of_add_left : ∀ (m₁ m₂ : M) (n : N), Eqv (.of (m₁, n) + .of (m₂, n)) (.of (m₁ + m₂, n)) | of_add_right : ∀ (m : M) (n₁ n₂ : N), Eqv (.of (m, n₁) + .of (m, n₂)) (.of (m, n₁ + n₂)) | of_smul : ∀ (r : R) (m : M) (n : N), Eqv (.of (r • m, n)) (.of (m, r • n)) | add_comm : ∀ x y, Eqv (x + y) (y + x) end end TensorProduct variable (R) /-- The tensor product of two modules `M` and `N` over the same commutative semiring `R`. The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open scoped TensorProduct`. -/ def TensorProduct : Type _ := (addConGen (TensorProduct.Eqv R M N)).Quotient variable {R} set_option quotPrecheck false in @[inherit_doc TensorProduct] scoped[TensorProduct] infixl:100 " ⊗ " => TensorProduct _ @[inherit_doc] scoped[TensorProduct] notation:100 M " ⊗[" R "] " N:100 => TensorProduct R M N namespace TensorProduct section Module protected instance add : Add (M ⊗[R] N) := (addConGen (TensorProduct.Eqv R M N)).hasAdd instance addZeroClass : AddZeroClass (M ⊗[R] N) := { (addConGen (TensorProduct.Eqv R M N)).addMonoid with /- The `toAdd` field is given explicitly as `TensorProduct.add` for performance reasons. This avoids any need to unfold `Con.addMonoid` when the type checker is checking that instance diagrams commute -/ toAdd := TensorProduct.add _ _ } instance addSemigroup : AddSemigroup (M ⊗[R] N) := { (addConGen (TensorProduct.Eqv R M N)).addMonoid with toAdd := TensorProduct.add _ _ } instance addCommSemigroup : AddCommSemigroup (M ⊗[R] N) := { (addConGen (TensorProduct.Eqv R M N)).addMonoid with toAddSemigroup := TensorProduct.addSemigroup _ _ add_comm := fun x y => AddCon.induction_on₂ x y fun _ _ => Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.add_comm _ _ } instance : Inhabited (M ⊗[R] N) := ⟨0⟩ variable (R) {M N} /-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`, accessed by `open scoped TensorProduct`. -/ def tmul (m : M) (n : N) : M ⊗[R] N := AddCon.mk' _ <| FreeAddMonoid.of (m, n) variable {R} /-- The canonical function `M → N → M ⊗ N`. -/ infixl:100 " ⊗ₜ " => tmul _ /-- The canonical function `M → N → M ⊗ N`. -/ notation:100 x " ⊗ₜ[" R "] " y:100 => tmul R x y -- Porting note: make the arguments of induction_on explicit @[elab_as_elim, induction_eliminator] protected theorem induction_on {motive : M ⊗[R] N → Prop} (z : M ⊗[R] N) (zero : motive 0) (tmul : ∀ x y, motive <| x ⊗ₜ[R] y) (add : ∀ x y, motive x → motive y → motive (x + y)) : motive z := AddCon.induction_on z fun x => FreeAddMonoid.recOn x zero fun ⟨m, n⟩ y ih => by rw [AddCon.coe_add] exact add _ _ (tmul ..) ih /-- Lift an `R`-balanced map to the tensor product. A map `f : M →+ N →+ P` additive in both components is `R`-balanced, or middle linear with respect to `R`, if scalar multiplication in either argument is equivalent, `f (r • m) n = f m (r • n)`. Note that strictly the first action should be a right-action by `R`, but for now `R` is commutative so it doesn't matter. -/ -- TODO: use this to implement `lift` and `SMul.aux`. For now we do not do this as it causes -- performance issues elsewhere. def liftAddHom (f : M →+ N →+ P) (hf : ∀ (r : R) (m : M) (n : N), f (r • m) n = f m (r • n)) : M ⊗[R] N →+ P := (addConGen (TensorProduct.Eqv R M N)).lift (FreeAddMonoid.lift (fun mn : M × N => f mn.1 mn.2)) <| AddCon.addConGen_le fun x y hxy => match x, y, hxy with | _, _, .of_zero_left n => (AddCon.ker_rel _).2 <| by simp_rw [map_zero, FreeAddMonoid.lift_eval_of, map_zero, AddMonoidHom.zero_apply] | _, _, .of_zero_right m => (AddCon.ker_rel _).2 <| by simp_rw [map_zero, FreeAddMonoid.lift_eval_of, map_zero] | _, _, .of_add_left m₁ m₂ n => (AddCon.ker_rel _).2 <| by simp_rw [map_add, FreeAddMonoid.lift_eval_of, map_add, AddMonoidHom.add_apply] | _, _, .of_add_right m n₁ n₂ => (AddCon.ker_rel _).2 <| by simp_rw [map_add, FreeAddMonoid.lift_eval_of, map_add] | _, _, .of_smul s m n => (AddCon.ker_rel _).2 <| by rw [FreeAddMonoid.lift_eval_of, FreeAddMonoid.lift_eval_of, hf] | _, _, .add_comm x y => (AddCon.ker_rel _).2 <| by simp_rw [map_add, add_comm] @[simp] theorem liftAddHom_tmul (f : M →+ N →+ P) (hf : ∀ (r : R) (m : M) (n : N), f (r • m) n = f m (r • n)) (m : M) (n : N) : liftAddHom f hf (m ⊗ₜ n) = f m n := rfl variable (M) @[simp] theorem zero_tmul (n : N) : (0 : M) ⊗ₜ[R] n = 0 := Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_zero_left _ variable {M} theorem add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n := Eq.symm <| Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_add_left _ _ _ variable (N) @[simp] theorem tmul_zero (m : M) : m ⊗ₜ[R] (0 : N) = 0 := Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_zero_right _ variable {N} theorem tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ := Eq.symm <| Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_add_right _ _ _ instance uniqueLeft [Subsingleton M] : Unique (M ⊗[R] N) where default := 0 uniq z := z.induction_on rfl (fun x y ↦ by rw [Subsingleton.elim x 0, zero_tmul]; rfl) <| by rintro _ _ rfl rfl; apply add_zero instance uniqueRight [Subsingleton N] : Unique (M ⊗[R] N) where default := 0 uniq z := z.induction_on rfl (fun x y ↦ by rw [Subsingleton.elim y 0, tmul_zero]; rfl) <| by rintro _ _ rfl rfl; apply add_zero section variable (R R' M N) /-- A typeclass for `SMul` structures which can be moved across a tensor product. This typeclass is generated automatically from an `IsScalarTower` instance, but exists so that we can also add an instance for `AddCommGroup.toIntModule`, allowing `z •` to be moved even if `R` does not support negation. Note that `Module R' (M ⊗[R] N)` is available even without this typeclass on `R'`; it's only needed if `TensorProduct.smul_tmul`, `TensorProduct.smul_tmul'`, or `TensorProduct.tmul_smul` is used. -/ class CompatibleSMul [DistribMulAction R' N] : Prop where smul_tmul : ∀ (r : R') (m : M) (n : N), (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) end /-- Note that this provides the default `CompatibleSMul R R M N` instance through `IsScalarTower.left`. -/ instance (priority := 100) CompatibleSMul.isScalarTower [SMul R' R] [IsScalarTower R' R M] [DistribMulAction R' N] [IsScalarTower R' R N] : CompatibleSMul R R' M N := ⟨fun r m n => by conv_lhs => rw [← one_smul R m] conv_rhs => rw [← one_smul R n] rw [← smul_assoc, ← smul_assoc] exact Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_smul _ _ _⟩ /-- `smul` can be moved from one side of the product to the other . -/ theorem smul_tmul [DistribMulAction R' N] [CompatibleSMul R R' M N] (r : R') (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) := CompatibleSMul.smul_tmul _ _ _ -- Porting note: This is added as a local instance for `SMul.aux`. -- For some reason type-class inference in Lean 3 unfolded this definition. private def addMonoidWithWrongNSMul : AddMonoid (M ⊗[R] N) := { (addConGen (TensorProduct.Eqv R M N)).addMonoid with } attribute [local instance] addMonoidWithWrongNSMul in /-- Auxiliary function to defining scalar multiplication on tensor product. -/ def SMul.aux {R' : Type*} [SMul R' M] (r : R') : FreeAddMonoid (M × N) →+ M ⊗[R] N := FreeAddMonoid.lift fun p : M × N => (r • p.1) ⊗ₜ p.2 theorem SMul.aux_of {R' : Type*} [SMul R' M] (r : R') (m : M) (n : N) : SMul.aux r (.of (m, n)) = (r • m) ⊗ₜ[R] n := rfl variable [SMulCommClass R R' M] [SMulCommClass R R'' M] /-- Given two modules over a commutative semiring `R`, if one of the factors carries a (distributive) action of a second type of scalars `R'`, which commutes with the action of `R`, then the tensor product (over `R`) carries an action of `R'`. This instance defines this `R'` action in the case that it is the left module which has the `R'` action. Two natural ways in which this situation arises are: * Extension of scalars * A tensor product of a group representation with a module not carrying an action Note that in the special case that `R = R'`, since `R` is commutative, we just get the usual scalar action on a tensor product of two modules. This special case is important enough that, for performance reasons, we define it explicitly below. -/ instance leftHasSMul : SMul R' (M ⊗[R] N) := ⟨fun r => (addConGen (TensorProduct.Eqv R M N)).lift (SMul.aux r : _ →+ M ⊗[R] N) <| AddCon.addConGen_le fun x y hxy => match x, y, hxy with | _, _, .of_zero_left n => (AddCon.ker_rel _).2 <| by simp_rw [map_zero, SMul.aux_of, smul_zero, zero_tmul] | _, _, .of_zero_right m => (AddCon.ker_rel _).2 <| by simp_rw [map_zero, SMul.aux_of, tmul_zero] | _, _, .of_add_left m₁ m₂ n => (AddCon.ker_rel _).2 <| by simp_rw [map_add, SMul.aux_of, smul_add, add_tmul] | _, _, .of_add_right m n₁ n₂ => (AddCon.ker_rel _).2 <| by simp_rw [map_add, SMul.aux_of, tmul_add] | _, _, .of_smul s m n => (AddCon.ker_rel _).2 <| by rw [SMul.aux_of, SMul.aux_of, ← smul_comm, smul_tmul] | _, _, .add_comm x y => (AddCon.ker_rel _).2 <| by simp_rw [map_add, add_comm]⟩ instance : SMul R (M ⊗[R] N) := TensorProduct.leftHasSMul protected theorem smul_zero (r : R') : r • (0 : M ⊗[R] N) = 0 := AddMonoidHom.map_zero _ protected theorem smul_add (r : R') (x y : M ⊗[R] N) : r • (x + y) = r • x + r • y := AddMonoidHom.map_add _ _ _ protected theorem zero_smul (x : M ⊗[R] N) : (0 : R'') • x = 0 := have : ∀ (r : R'') (m : M) (n : N), r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := fun _ _ _ => rfl x.induction_on (by rw [TensorProduct.smul_zero]) (fun m n => by rw [this, zero_smul, zero_tmul]) fun x y ihx ihy => by rw [TensorProduct.smul_add, ihx, ihy, add_zero] protected theorem one_smul (x : M ⊗[R] N) : (1 : R') • x = x := have : ∀ (r : R') (m : M) (n : N), r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := fun _ _ _ => rfl x.induction_on (by rw [TensorProduct.smul_zero]) (fun m n => by rw [this, one_smul]) fun x y ihx ihy => by rw [TensorProduct.smul_add, ihx, ihy] protected theorem add_smul (r s : R'') (x : M ⊗[R] N) : (r + s) • x = r • x + s • x := have : ∀ (r : R'') (m : M) (n : N), r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := fun _ _ _ => rfl x.induction_on (by simp_rw [TensorProduct.smul_zero, add_zero]) (fun m n => by simp_rw [this, add_smul, add_tmul]) fun x y ihx ihy => by simp_rw [TensorProduct.smul_add] rw [ihx, ihy, add_add_add_comm] instance addMonoid : AddMonoid (M ⊗[R] N) := { TensorProduct.addZeroClass _ _ with toAddSemigroup := TensorProduct.addSemigroup _ _ toZero := (TensorProduct.addZeroClass _ _).toZero nsmul := fun n v => n • v nsmul_zero := by simp [TensorProduct.zero_smul] nsmul_succ := by simp only [TensorProduct.one_smul, TensorProduct.add_smul, add_comm, forall_const] } instance addCommMonoid : AddCommMonoid (M ⊗[R] N) := { TensorProduct.addCommSemigroup _ _ with toAddMonoid := TensorProduct.addMonoid } instance leftDistribMulAction : DistribMulAction R' (M ⊗[R] N) := have : ∀ (r : R') (m : M) (n : N), r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := fun _ _ _ => rfl { smul_add := fun r x y => TensorProduct.smul_add r x y mul_smul := fun r s x => x.induction_on (by simp_rw [TensorProduct.smul_zero]) (fun m n => by simp_rw [this, mul_smul]) fun x y ihx ihy => by simp_rw [TensorProduct.smul_add] rw [ihx, ihy] one_smul := TensorProduct.one_smul smul_zero := TensorProduct.smul_zero } instance : DistribMulAction R (M ⊗[R] N) := TensorProduct.leftDistribMulAction theorem smul_tmul' (r : R') (m : M) (n : N) : r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := rfl @[simp] theorem tmul_smul [DistribMulAction R' N] [CompatibleSMul R R' M N] (r : R') (x : M) (y : N) : x ⊗ₜ (r • y) = r • x ⊗ₜ[R] y := (smul_tmul _ _ _).symm theorem smul_tmul_smul (r s : R) (m : M) (n : N) : (r • m) ⊗ₜ[R] (s • n) = (r * s) • m ⊗ₜ[R] n := by simp_rw [smul_tmul, tmul_smul, mul_smul] instance leftModule : Module R'' (M ⊗[R] N) := { add_smul := TensorProduct.add_smul zero_smul := TensorProduct.zero_smul } instance : Module R (M ⊗[R] N) := TensorProduct.leftModule instance [Module R''ᵐᵒᵖ M] [IsCentralScalar R'' M] : IsCentralScalar R'' (M ⊗[R] N) where op_smul_eq_smul r x := x.induction_on (by rw [smul_zero, smul_zero]) (fun x y => by rw [smul_tmul', smul_tmul', op_smul_eq_smul]) fun x y hx hy => by rw [smul_add, smul_add, hx, hy] section -- Like `R'`, `R'₂` provides a `DistribMulAction R'₂ (M ⊗[R] N)` variable {R'₂ : Type*} [Monoid R'₂] [DistribMulAction R'₂ M] variable [SMulCommClass R R'₂ M] /-- `SMulCommClass R' R'₂ M` implies `SMulCommClass R' R'₂ (M ⊗[R] N)` -/ instance smulCommClass_left [SMulCommClass R' R'₂ M] : SMulCommClass R' R'₂ (M ⊗[R] N) where smul_comm r' r'₂ x := TensorProduct.induction_on x (by simp_rw [TensorProduct.smul_zero]) (fun m n => by simp_rw [smul_tmul', smul_comm]) fun x y ihx ihy => by simp_rw [TensorProduct.smul_add]; rw [ihx, ihy] variable [SMul R'₂ R'] /-- `IsScalarTower R'₂ R' M` implies `IsScalarTower R'₂ R' (M ⊗[R] N)` -/ instance isScalarTower_left [IsScalarTower R'₂ R' M] : IsScalarTower R'₂ R' (M ⊗[R] N) := ⟨fun s r x => x.induction_on (by simp) (fun m n => by rw [smul_tmul', smul_tmul', smul_tmul', smul_assoc]) fun x y ihx ihy => by rw [smul_add, smul_add, smul_add, ihx, ihy]⟩ variable [DistribMulAction R'₂ N] [DistribMulAction R' N] variable [CompatibleSMul R R'₂ M N] [CompatibleSMul R R' M N] /-- `IsScalarTower R'₂ R' N` implies `IsScalarTower R'₂ R' (M ⊗[R] N)` -/ instance isScalarTower_right [IsScalarTower R'₂ R' N] : IsScalarTower R'₂ R' (M ⊗[R] N) := ⟨fun s r x => x.induction_on (by simp) (fun m n => by rw [← tmul_smul, ← tmul_smul, ← tmul_smul, smul_assoc]) fun x y ihx ihy => by rw [smul_add, smul_add, smul_add, ihx, ihy]⟩ end /-- A short-cut instance for the common case, where the requirements for the `compatible_smul` instances are sufficient. -/ instance isScalarTower [SMul R' R] [IsScalarTower R' R M] : IsScalarTower R' R (M ⊗[R] N) := TensorProduct.isScalarTower_left -- or right variable (R M N) /-- The canonical bilinear map `M → N → M ⊗[R] N`. -/ def mk : M →ₗ[R] N →ₗ[R] M ⊗[R] N := LinearMap.mk₂ R (· ⊗ₜ ·) add_tmul (fun c m n => by simp_rw [smul_tmul, tmul_smul]) tmul_add tmul_smul variable {R M N} @[simp] theorem mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl theorem ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [Decidable P] : (if P then x₁ else 0) ⊗ₜ[R] x₂ = if P then x₁ ⊗ₜ x₂ else 0 := by split_ifs <;> simp theorem tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [Decidable P] : (x₁ ⊗ₜ[R] if P then x₂ else 0) = if P then x₁ ⊗ₜ x₂ else 0 := by split_ifs <;> simp section theorem sum_tmul {α : Type*} (s : Finset α) (m : α → M) (n : N) : (∑ a ∈ s, m a) ⊗ₜ[R] n = ∑ a ∈ s, m a ⊗ₜ[R] n := by classical induction' s using Finset.induction with a s has ih h · simp · simp [Finset.sum_insert has, add_tmul, ih] theorem tmul_sum (m : M) {α : Type*} (s : Finset α) (n : α → N) : (m ⊗ₜ[R] ∑ a ∈ s, n a) = ∑ a ∈ s, m ⊗ₜ[R] n a := by classical induction' s using Finset.induction with a s has ih h · simp · simp [Finset.sum_insert has, tmul_add, ih] end variable (R M N) /-- The simple (aka pure) elements span the tensor product. -/ theorem span_tmul_eq_top : Submodule.span R { t : M ⊗[R] N | ∃ m n, m ⊗ₜ n = t } = ⊤ := by ext t; simp only [Submodule.mem_top, iff_true_iff] refine t.induction_on ?_ ?_ ?_ · exact Submodule.zero_mem _ · intro m n apply Submodule.subset_span use m, n · intro t₁ t₂ ht₁ ht₂ exact Submodule.add_mem _ ht₁ ht₂ @[simp] theorem map₂_mk_top_top_eq_top : Submodule.map₂ (mk R M N) ⊤ ⊤ = ⊤ := by rw [← top_le_iff, ← span_tmul_eq_top, Submodule.map₂_eq_span_image2] exact Submodule.span_mono fun _ ⟨m, n, h⟩ => ⟨m, trivial, n, trivial, h⟩ theorem exists_eq_tmul_of_forall (x : TensorProduct R M N) (h : ∀ (m₁ m₂ : M) (n₁ n₂ : N), ∃ m n, m₁ ⊗ₜ n₁ + m₂ ⊗ₜ n₂ = m ⊗ₜ[R] n) : ∃ m n, x = m ⊗ₜ n := by induction x with | zero => use 0, 0 rw [TensorProduct.zero_tmul] | tmul m n => use m, n | add x y h₁ h₂ => obtain ⟨m₁, n₁, rfl⟩ := h₁ obtain ⟨m₂, n₂, rfl⟩ := h₂ apply h end Module variable [Module R P] section UMP variable {M N} variable (f : M →ₗ[R] N →ₗ[R] P) /-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def liftAux : M ⊗[R] N →+ P := liftAddHom (LinearMap.toAddMonoidHom'.comp <| f.toAddMonoidHom) fun r m n => by dsimp; rw [LinearMap.map_smul₂, map_smul] theorem liftAux_tmul (m n) : liftAux f (m ⊗ₜ n) = f m n := rfl variable {f} @[simp] theorem liftAux.smul (r : R) (x) : liftAux f (r • x) = r • liftAux f x := TensorProduct.induction_on x (smul_zero _).symm (fun p q => by simp_rw [← tmul_smul, liftAux_tmul, (f p).map_smul]) fun p q ih1 ih2 => by simp_rw [smul_add, (liftAux f).map_add, ih1, ih2, smul_add] variable (f) /-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift : M ⊗[R] N →ₗ[R] P := { liftAux f with map_smul' := liftAux.smul } variable {f} @[simp] theorem lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := rfl @[simp] theorem lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := rfl theorem ext' {g h : M ⊗[R] N →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := LinearMap.ext fun z => TensorProduct.induction_on z (by simp_rw [LinearMap.map_zero]) H fun x y ihx ihy => by rw [g.map_add, h.map_add, ihx, ihy] theorem lift.unique {g : M ⊗[R] N →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := ext' fun m n => by rw [H, lift.tmul] theorem lift_mk : lift (mk R M N) = LinearMap.id := Eq.symm <| lift.unique fun _ _ => rfl theorem lift_compr₂ (g : P →ₗ[R] Q) : lift (f.compr₂ g) = g.comp (lift f) := Eq.symm <| lift.unique fun _ _ => by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ[R] P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂ f, lift_mk, LinearMap.comp_id] /-- This used to be an `@[ext]` lemma, but it fails very slowly when the `ext` tactic tries to apply it in some cases, notably when one wants to show equality of two linear maps. The `@[ext]` attribute is now added locally where it is needed. Using this as the `@[ext]` lemma instead of `TensorProduct.ext'` allows `ext` to apply lemmas specific to `M →ₗ _` and `N →ₗ _`. See note [partially-applied ext lemmas]. -/ theorem ext {g h : M ⊗ N →ₗ[R] P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] attribute [local ext high] ext example : M → N → (M → N → P) → P := fun m => flip fun f => f m variable (R M N P) /-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P := LinearMap.flip <| lift <| LinearMap.lflip.comp (LinearMap.flip LinearMap.id) variable {R M N P} @[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : uncurry R M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, LinearMap.flip_apply, lift.tmul]; rfl variable (R M N P) /-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift.equiv : (M →ₗ[R] N →ₗ[R] P) ≃ₗ[R] M ⊗[R] N →ₗ[R] P := { uncurry R M N P with invFun := fun f => (mk R M N).compr₂ f left_inv := fun _ => LinearMap.ext₂ fun _ _ => lift.tmul _ _ right_inv := fun _ => ext' fun _ _ => lift.tmul _ _ } @[simp] theorem lift.equiv_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : lift.equiv R M N P f (m ⊗ₜ n) = f m n := uncurry_apply f m n @[simp] theorem lift.equiv_symm_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : (lift.equiv R M N P).symm f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P := (lift.equiv R M N P).symm variable {R M N P} @[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : lcurry R M N P f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def curry (f : M ⊗[R] N →ₗ[R] P) : M →ₗ[R] N →ₗ[R] P := lcurry R M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl theorem curry_injective : Function.Injective (curry : (M ⊗[R] N →ₗ[R] P) → M →ₗ[R] N →ₗ[R] P) := fun _ _ H => ext H theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q} (H : ∀ x y z, g (x ⊗ₜ y ⊗ₜ z) = h (x ⊗ₜ y ⊗ₜ z)) : g = h := by ext x y z exact H x y z -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, g (w ⊗ₜ x ⊗ₜ y ⊗ₜ z) = h (w ⊗ₜ x ⊗ₜ y ⊗ₜ z)) : g = h := by ext w x y z exact H w x y z /-- Two linear maps (M ⊗ N) ⊗ (P ⊗ Q) → S which agree on all elements of the form (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) are equal. -/ theorem ext_fourfold' {φ ψ : (M ⊗[R] N) ⊗[R] P ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, φ (w ⊗ₜ x ⊗ₜ (y ⊗ₜ z)) = ψ (w ⊗ₜ x ⊗ₜ (y ⊗ₜ z))) : φ = ψ := by ext m n p q exact H m n p q end UMP variable {M N} section variable (R M) /-- The base ring is a left identity for the tensor product of modules, up to linear equivalence. -/ protected def lid : R ⊗[R] M ≃ₗ[R] M := LinearEquiv.ofLinear (lift <| LinearMap.lsmul R M) (mk R R M 1) (LinearMap.ext fun _ => by simp) (ext' fun r m => by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one]) end @[simp] theorem lid_tmul (m : M) (r : R) : (TensorProduct.lid R M : R ⊗ M → M) (r ⊗ₜ m) = r • m := rfl @[simp] theorem lid_symm_apply (m : M) : (TensorProduct.lid R M).symm m = 1 ⊗ₜ m := rfl section variable (R M N) /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm : M ⊗[R] N ≃ₗ[R] N ⊗[R] M := LinearEquiv.ofLinear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext' fun _ _ => rfl) (ext' fun _ _ => rfl) @[simp] theorem comm_tmul (m : M) (n : N) : (TensorProduct.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] theorem comm_symm_tmul (m : M) (n : N) : (TensorProduct.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl lemma lift_comp_comm_eq (f : M →ₗ[R] N →ₗ[R] P) : lift f ∘ₗ TensorProduct.comm R N M = lift f.flip := ext rfl end section variable (R M) /-- The base ring is a right identity for the tensor product of modules, up to linear equivalence. -/ protected def rid : M ⊗[R] R ≃ₗ[R] M := LinearEquiv.trans (TensorProduct.comm R M R) (TensorProduct.lid R M) end @[simp] theorem rid_tmul (m : M) (r : R) : (TensorProduct.rid R M) (m ⊗ₜ r) = r • m := rfl @[simp] theorem rid_symm_apply (m : M) : (TensorProduct.rid R M).symm m = m ⊗ₜ 1 := rfl variable (R) in theorem lid_eq_rid : TensorProduct.lid R R = TensorProduct.rid R R := LinearEquiv.toLinearMap_injective <| ext' mul_comm open LinearMap section variable (R M N P) /-- The associator for tensor product of R-modules, as a linear equivalence. -/ protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] N ⊗[R] P := by refine LinearEquiv.ofLinear (lift <| lift <| comp (lcurry R _ _ _) <| mk _ _ _) (lift <| comp (uncurry R _ _ _) <| curry <| mk _ _ _) (ext <| LinearMap.ext fun m => ext' fun n p => ?_) (ext <| flip_inj <| LinearMap.ext fun p => ext' fun m n => ?_) <;> repeat' first |rw [lift.tmul]|rw [compr₂_apply]|rw [comp_apply]|rw [mk_apply]|rw [flip_apply] |rw [lcurry_apply]|rw [uncurry_apply]|rw [curry_apply]|rw [id_apply] end @[simp] theorem assoc_tmul (m : M) (n : N) (p : P) : (TensorProduct.assoc R M N P) (m ⊗ₜ n ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl @[simp] theorem assoc_symm_tmul (m : M) (n : N) (p : P) : (TensorProduct.assoc R M N P).symm (m ⊗ₜ (n ⊗ₜ p)) = m ⊗ₜ n ⊗ₜ p := rfl /-- The tensor product of a pair of linear maps between modules. -/ def map (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : M ⊗[R] N →ₗ[R] P ⊗[R] Q := lift <| comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl /-- Given linear maps `f : M → P`, `g : N → Q`, if we identify `M ⊗ N` with `N ⊗ M` and `P ⊗ Q` with `Q ⊗ P`, then this lemma states that `f ⊗ g = g ⊗ f`. -/ lemma map_comp_comm_eq (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map f g ∘ₗ TensorProduct.comm R N M = TensorProduct.comm R Q P ∘ₗ map g f := ext rfl lemma map_comm (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (x : N ⊗[R] M) : map f g (TensorProduct.comm R N M x) = TensorProduct.comm R Q P (map g f x) := DFunLike.congr_fun (map_comp_comm_eq _ _) _ /-- Given linear maps `f : M → Q`, `g : N → S`, and `h : P → T`, if we identify `(M ⊗ N) ⊗ P` with `M ⊗ (N ⊗ P)` and `(Q ⊗ S) ⊗ T` with `Q ⊗ (S ⊗ T)`, then this lemma states that `f ⊗ (g ⊗ h) = (f ⊗ g) ⊗ h`. -/ lemma map_map_comp_assoc_eq (f : M →ₗ[R] Q) (g : N →ₗ[R] S) (h : P →ₗ[R] T) : map f (map g h) ∘ₗ TensorProduct.assoc R M N P = TensorProduct.assoc R Q S T ∘ₗ map (map f g) h := ext <| ext <| LinearMap.ext fun _ => LinearMap.ext fun _ => LinearMap.ext fun _ => rfl lemma map_map_assoc (f : M →ₗ[R] Q) (g : N →ₗ[R] S) (h : P →ₗ[R] T) (x : (M ⊗[R] N) ⊗[R] P) : map f (map g h) (TensorProduct.assoc R M N P x) = TensorProduct.assoc R Q S T (map (map f g) h x) := DFunLike.congr_fun (map_map_comp_assoc_eq _ _ _) _ /-- Given linear maps `f : M → Q`, `g : N → S`, and `h : P → T`, if we identify `M ⊗ (N ⊗ P)` with `(M ⊗ N) ⊗ P` and `Q ⊗ (S ⊗ T)` with `(Q ⊗ S) ⊗ T`, then this lemma states that `(f ⊗ g) ⊗ h = f ⊗ (g ⊗ h)`. -/ lemma map_map_comp_assoc_symm_eq (f : M →ₗ[R] Q) (g : N →ₗ[R] S) (h : P →ₗ[R] T) : map (map f g) h ∘ₗ (TensorProduct.assoc R M N P).symm = (TensorProduct.assoc R Q S T).symm ∘ₗ map f (map g h) := ext <| LinearMap.ext fun _ => ext <| LinearMap.ext fun _ => LinearMap.ext fun _ => rfl lemma map_map_assoc_symm (f : M →ₗ[R] Q) (g : N →ₗ[R] S) (h : P →ₗ[R] T) (x : M ⊗[R] (N ⊗[R] P)) : map (map f g) h ((TensorProduct.assoc R M N P).symm x) = (TensorProduct.assoc R Q S T).symm (map f (map g h) x) := DFunLike.congr_fun (map_map_comp_assoc_symm_eq _ _ _) _ theorem map_range_eq_span_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : range (map f g) = Submodule.span R { t | ∃ m n, f m ⊗ₜ g n = t } := by simp only [← Submodule.map_top, ← span_tmul_eq_top, Submodule.map_span, Set.mem_image, Set.mem_setOf_eq] congr; ext t constructor · rintro ⟨_, ⟨⟨m, n, rfl⟩, rfl⟩⟩ use m, n simp only [map_tmul] · rintro ⟨m, n, rfl⟩ refine ⟨_, ⟨⟨m, n, rfl⟩, ?_⟩⟩ simp only [map_tmul] /-- Given submodules `p ⊆ P` and `q ⊆ Q`, this is the natural map: `p ⊗ q → P ⊗ Q`. -/ @[simp] def mapIncl (p : Submodule R P) (q : Submodule R Q) : p ⊗[R] q →ₗ[R] P ⊗[R] Q := map p.subtype q.subtype lemma range_mapIncl (p : Submodule R P) (q : Submodule R Q) : LinearMap.range (mapIncl p q) = Submodule.span R (Set.image2 (· ⊗ₜ ·) p q) := by rw [mapIncl, map_range_eq_span_tmul] congr; ext; simp theorem map₂_eq_range_lift_comp_mapIncl (f : P →ₗ[R] Q →ₗ[R] M) (p : Submodule R P) (q : Submodule R Q) : Submodule.map₂ f p q = LinearMap.range (lift f ∘ₗ mapIncl p q) := by simp_rw [LinearMap.range_comp, range_mapIncl, Submodule.map_span, Set.image_image2, Submodule.map₂_eq_span_image2, lift.tmul] section variable {P' Q' : Type*} variable [AddCommMonoid P'] [Module R P'] variable [AddCommMonoid Q'] [Module R Q'] theorem map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) : map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) := ext' fun _ _ => rfl lemma range_mapIncl_mono {p p' : Submodule R P} {q q' : Submodule R Q} (hp : p ≤ p') (hq : q ≤ q') : LinearMap.range (mapIncl p q) ≤ LinearMap.range (mapIncl p' q') := by simp_rw [range_mapIncl] exact Submodule.span_mono (Set.image2_subset hp hq) theorem lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (lift i).comp (map f g) = lift ((i.comp f).compl₂ g) := ext' fun _ _ => rfl attribute [local ext high] ext @[simp] theorem map_id : map (id : M →ₗ[R] M) (id : N →ₗ[R] N) = .id := by ext simp only [mk_apply, id_coe, compr₂_apply, _root_.id, map_tmul] @[simp] theorem map_one : map (1 : M →ₗ[R] M) (1 : N →ₗ[R] N) = 1 := map_id theorem map_mul (f₁ f₂ : M →ₗ[R] M) (g₁ g₂ : N →ₗ[R] N) : map (f₁ * f₂) (g₁ * g₂) = map f₁ g₁ * map f₂ g₂ := map_comp f₁ f₂ g₁ g₂ @[simp] protected theorem map_pow (f : M →ₗ[R] M) (g : N →ₗ[R] N) (n : ℕ) : map f g ^ n = map (f ^ n) (g ^ n) := by induction' n with n ih · simp only [Nat.zero_eq, pow_zero, map_one] · simp only [pow_succ', ih, map_mul] theorem map_add_left (f₁ f₂ : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (f₁ + f₂) g = map f₁ g + map f₂ g := by ext simp only [add_tmul, compr₂_apply, mk_apply, map_tmul, add_apply] theorem map_add_right (f : M →ₗ[R] P) (g₁ g₂ : N →ₗ[R] Q) : map f (g₁ + g₂) = map f g₁ + map f g₂ := by ext simp only [tmul_add, compr₂_apply, mk_apply, map_tmul, add_apply] theorem map_smul_left (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (r • f) g = r • map f g := by ext simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul] theorem map_smul_right (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map f (r • g) = r • map f g := by ext simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul] variable (R M N P Q) /-- The tensor product of a pair of linear maps between modules, bilinear in both maps. -/ def mapBilinear : (M →ₗ[R] P) →ₗ[R] (N →ₗ[R] Q) →ₗ[R] M ⊗[R] N →ₗ[R] P ⊗[R] Q := LinearMap.mk₂ R map map_add_left map_smul_left map_add_right map_smul_right /-- The canonical linear map from `P ⊗[R] (M →ₗ[R] Q)` to `(M →ₗ[R] P ⊗[R] Q)` -/ def lTensorHomToHomLTensor : P ⊗[R] (M →ₗ[R] Q) →ₗ[R] M →ₗ[R] P ⊗[R] Q := TensorProduct.lift (llcomp R M Q _ ∘ₗ mk R P Q) /-- The canonical linear map from `(M →ₗ[R] P) ⊗[R] Q` to `(M →ₗ[R] P ⊗[R] Q)` -/ def rTensorHomToHomRTensor : (M →ₗ[R] P) ⊗[R] Q →ₗ[R] M →ₗ[R] P ⊗[R] Q := TensorProduct.lift (llcomp R M P _ ∘ₗ (mk R P Q).flip).flip /-- The linear map from `(M →ₗ P) ⊗ (N →ₗ Q)` to `(M ⊗ N →ₗ P ⊗ Q)` sending `f ⊗ₜ g` to the `TensorProduct.map f g`, the tensor product of the two maps. -/ def homTensorHomMap : (M →ₗ[R] P) ⊗[R] (N →ₗ[R] Q) →ₗ[R] M ⊗[R] N →ₗ[R] P ⊗[R] Q := lift (mapBilinear R M N P Q) variable {R M N P Q} /-- This is a binary version of `TensorProduct.map`: Given a bilinear map `f : M ⟶ P ⟶ Q` and a bilinear map `g : N ⟶ S ⟶ T`, if we think `f` and `g` as linear maps with two inputs, then `map₂ f g` is a bilinear map taking two inputs `M ⊗ N → P ⊗ S → Q ⊗ S` defined by `map₂ f g (m ⊗ n) (p ⊗ s) = f m p ⊗ g n s`. Mathematically, `TensorProduct.map₂` is defined as the composition `M ⊗ N -map→ Hom(P, Q) ⊗ Hom(S, T) -homTensorHomMap→ Hom(P ⊗ S, Q ⊗ T)`. -/ def map₂ (f : M →ₗ[R] P →ₗ[R] Q) (g : N →ₗ[R] S →ₗ[R] T) : M ⊗[R] N →ₗ[R] P ⊗[R] S →ₗ[R] Q ⊗[R] T := homTensorHomMap R _ _ _ _ ∘ₗ map f g @[simp] theorem mapBilinear_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : mapBilinear R M N P Q f g = map f g := rfl @[simp] theorem lTensorHomToHomLTensor_apply (p : P) (f : M →ₗ[R] Q) (m : M) : lTensorHomToHomLTensor R M P Q (p ⊗ₜ f) m = p ⊗ₜ f m := rfl @[simp] theorem rTensorHomToHomRTensor_apply (f : M →ₗ[R] P) (q : Q) (m : M) : rTensorHomToHomRTensor R M P Q (f ⊗ₜ q) m = f m ⊗ₜ q := rfl @[simp] theorem homTensorHomMap_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : homTensorHomMap R M N P Q (f ⊗ₜ g) = map f g := rfl @[simp] theorem map₂_apply_tmul (f : M →ₗ[R] P →ₗ[R] Q) (g : N →ₗ[R] S →ₗ[R] T) (m : M) (n : N) : map₂ f g (m ⊗ₜ n) = map (f m) (g n) := rfl @[simp] theorem map_zero_left (g : N →ₗ[R] Q) : map (0 : M →ₗ[R] P) g = 0 := (mapBilinear R M N P Q).map_zero₂ _ @[simp] theorem map_zero_right (f : M →ₗ[R] P) : map f (0 : N →ₗ[R] Q) = 0 := (mapBilinear R M N P Q _).map_zero end /-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/ def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗[R] N ≃ₗ[R] P ⊗[R] Q := LinearEquiv.ofLinear (map f g) (map f.symm g.symm) (ext' fun m n => by simp) (ext' fun m n => by simp) @[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl @[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) : (congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q := rfl theorem congr_symm (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : (congr f g).symm = congr f.symm g.symm := rfl @[simp] theorem congr_refl_refl : congr (.refl R M) (.refl R N) = .refl R _ := LinearEquiv.toLinearMap_injective <| ext' fun _ _ ↦ rfl theorem congr_trans (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (f' : P ≃ₗ[R] S) (g' : Q ≃ₗ[R] T) : congr (f ≪≫ₗ f') (g ≪≫ₗ g') = congr f g ≪≫ₗ congr f' g' := LinearEquiv.toLinearMap_injective <| map_comp _ _ _ _ theorem congr_mul (f : M ≃ₗ[R] M) (g : N ≃ₗ[R] N) (f' : M ≃ₗ[R] M) (g' : N ≃ₗ[R] N) : congr (f * f') (g * g') = congr f g * congr f' g' := congr_trans _ _ _ _ @[simp] theorem congr_pow (f : M ≃ₗ[R] M) (g : N ≃ₗ[R] N) (n : ℕ) : congr f g ^ n = congr (f ^ n) (g ^ n) := by induction n with | zero => exact congr_refl_refl.symm | succ n ih => simp_rw [pow_succ, ih, congr_mul] @[simp] theorem congr_zpow (f : M ≃ₗ[R] M) (g : N ≃ₗ[R] N) (n : ℤ) : congr f g ^ n = congr (f ^ n) (g ^ n) := by induction n with | ofNat n => exact congr_pow _ _ _ | negSucc n => simp_rw [zpow_negSucc, congr_pow]; exact congr_symm _ _ variable (R M N P Q) /-- A tensor product analogue of `mul_left_comm`. -/ def leftComm : M ⊗[R] N ⊗[R] P ≃ₗ[R] N ⊗[R] M ⊗[R] P := let e₁ := (TensorProduct.assoc R M N P).symm let e₂ := congr (TensorProduct.comm R M N) (1 : P ≃ₗ[R] P) let e₃ := TensorProduct.assoc R N M P e₁ ≪≫ₗ (e₂ ≪≫ₗ e₃) variable {M N P Q} @[simp] theorem leftComm_tmul (m : M) (n : N) (p : P) : leftComm R M N P (m ⊗ₜ (n ⊗ₜ p)) = n ⊗ₜ (m ⊗ₜ p) := rfl @[simp] theorem leftComm_symm_tmul (m : M) (n : N) (p : P) : (leftComm R M N P).symm (n ⊗ₜ (m ⊗ₜ p)) = m ⊗ₜ (n ⊗ₜ p) := rfl variable (M N P Q) /-- This special case is worth defining explicitly since it is useful for defining multiplication on tensor products of modules carrying multiplications (e.g., associative rings, Lie rings, ...). E.g., suppose `M = P` and `N = Q` and that `M` and `N` carry bilinear multiplications: `M ⊗ M → M` and `N ⊗ N → N`. Using `map`, we can define `(M ⊗ M) ⊗ (N ⊗ N) → M ⊗ N` which, when combined with this definition, yields a bilinear multiplication on `M ⊗ N`: `(M ⊗ N) ⊗ (M ⊗ N) → M ⊗ N`. In particular we could use this to define the multiplication in the `TensorProduct.semiring` instance (currently defined "by hand" using `TensorProduct.mul`). See also `mul_mul_mul_comm`. -/ def tensorTensorTensorComm : (M ⊗[R] N) ⊗[R] P ⊗[R] Q ≃ₗ[R] (M ⊗[R] P) ⊗[R] N ⊗[R] Q := let e₁ := TensorProduct.assoc R M N (P ⊗[R] Q) let e₂ := congr (1 : M ≃ₗ[R] M) (leftComm R N P Q) let e₃ := (TensorProduct.assoc R M P (N ⊗[R] Q)).symm e₁ ≪≫ₗ (e₂ ≪≫ₗ e₃) variable {M N P Q} @[simp] theorem tensorTensorTensorComm_tmul (m : M) (n : N) (p : P) (q : Q) : tensorTensorTensorComm R M N P Q (m ⊗ₜ n ⊗ₜ (p ⊗ₜ q)) = m ⊗ₜ p ⊗ₜ (n ⊗ₜ q) := rfl -- Porting note: the proof here was `rfl` but that caused a timeout. @[simp] theorem tensorTensorTensorComm_symm : (tensorTensorTensorComm R M N P Q).symm = tensorTensorTensorComm R M P N Q := by ext; rfl variable (M N P Q) /-- This special case is useful for describing the interplay between `dualTensorHomEquiv` and composition of linear maps. E.g., composition of linear maps gives a map `(M → N) ⊗ (N → P) → (M → P)`, and applying `dual_tensor_hom_equiv.symm` to the three hom-modules gives a map `(M.dual ⊗ N) ⊗ (N.dual ⊗ P) → (M.dual ⊗ P)`, which agrees with the application of `contractRight` on `N ⊗ N.dual` after the suitable rebracketting. -/ def tensorTensorTensorAssoc : (M ⊗[R] N) ⊗[R] P ⊗[R] Q ≃ₗ[R] (M ⊗[R] N ⊗[R] P) ⊗[R] Q := (TensorProduct.assoc R (M ⊗[R] N) P Q).symm ≪≫ₗ congr (TensorProduct.assoc R M N P) (1 : Q ≃ₗ[R] Q) variable {M N P Q} @[simp] theorem tensorTensorTensorAssoc_tmul (m : M) (n : N) (p : P) (q : Q) : tensorTensorTensorAssoc R M N P Q (m ⊗ₜ n ⊗ₜ (p ⊗ₜ q)) = m ⊗ₜ (n ⊗ₜ p) ⊗ₜ q := rfl @[simp] theorem tensorTensorTensorAssoc_symm_tmul (m : M) (n : N) (p : P) (q : Q) : (tensorTensorTensorAssoc R M N P Q).symm (m ⊗ₜ (n ⊗ₜ p) ⊗ₜ q) = m ⊗ₜ n ⊗ₜ (p ⊗ₜ q) := rfl end TensorProduct open scoped TensorProduct variable [Module R P] namespace LinearMap variable {N} /-- `LinearMap.lTensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/ def lTensor (f : N →ₗ[R] P) : M ⊗[R] N →ₗ[R] M ⊗[R] P := TensorProduct.map id f /-- `LinearMap.rTensor M f : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/ def rTensor (f : N →ₗ[R] P) : N ⊗[R] M →ₗ[R] P ⊗[R] M := TensorProduct.map f id variable (g : P →ₗ[R] Q) (f : N →ₗ[R] P) @[simp] theorem lTensor_tmul (m : M) (n : N) : f.lTensor M (m ⊗ₜ n) = m ⊗ₜ f n := rfl @[simp] theorem rTensor_tmul (m : M) (n : N) : f.rTensor M (n ⊗ₜ m) = f n ⊗ₜ m := rfl @[simp] theorem lTensor_comp_mk (m : M) : f.lTensor M ∘ₗ TensorProduct.mk R M N m = TensorProduct.mk R M P m ∘ₗ f := rfl @[simp] theorem rTensor_comp_flip_mk (m : M) : f.rTensor M ∘ₗ (TensorProduct.mk R N M).flip m = (TensorProduct.mk R P M).flip m ∘ₗ f := rfl lemma comm_comp_rTensor_comp_comm_eq (g : N →ₗ[R] P) : TensorProduct.comm R P Q ∘ₗ rTensor Q g ∘ₗ TensorProduct.comm R Q N = lTensor Q g := TensorProduct.ext rfl lemma comm_comp_lTensor_comp_comm_eq (g : N →ₗ[R] P) : TensorProduct.comm R Q P ∘ₗ lTensor Q g ∘ₗ TensorProduct.comm R N Q = rTensor Q g := TensorProduct.ext rfl /-- Given a linear map `f : N → P`, `f ⊗ M` is injective if and only if `M ⊗ f` is injective. -/ theorem lTensor_inj_iff_rTensor_inj : Function.Injective (lTensor M f) ↔ Function.Injective (rTensor M f) := by simp [← comm_comp_rTensor_comp_comm_eq] /-- Given a linear map `f : N → P`, `f ⊗ M` is surjective if and only if `M ⊗ f` is surjective. -/ theorem lTensor_surj_iff_rTensor_surj : Function.Surjective (lTensor M f) ↔ Function.Surjective (rTensor M f) := by simp [← comm_comp_rTensor_comp_comm_eq] /-- Given a linear map `f : N → P`, `f ⊗ M` is bijective if and only if `M ⊗ f` is bijective. -/ theorem lTensor_bij_iff_rTensor_bij : Function.Bijective (lTensor M f) ↔ Function.Bijective (rTensor M f) := by simp [← comm_comp_rTensor_comp_comm_eq] open TensorProduct attribute [local ext high] TensorProduct.ext /-- `lTensorHom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def lTensorHom : (N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] M ⊗[R] P where toFun := lTensor M map_add' f g := by ext x y simp only [compr₂_apply, mk_apply, add_apply, lTensor_tmul, tmul_add] map_smul' r f := by dsimp ext x y simp only [compr₂_apply, mk_apply, tmul_smul, smul_apply, lTensor_tmul] /-- `rTensorHom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `f ⊗ M`. -/ def rTensorHom : (N →ₗ[R] P) →ₗ[R] N ⊗[R] M →ₗ[R] P ⊗[R] M where toFun f := f.rTensor M map_add' f g := by ext x y simp only [compr₂_apply, mk_apply, add_apply, rTensor_tmul, add_tmul] map_smul' r f := by dsimp ext x y simp only [compr₂_apply, mk_apply, smul_tmul, tmul_smul, smul_apply, rTensor_tmul] @[simp] theorem coe_lTensorHom : (lTensorHom M : (N →ₗ[R] P) → M ⊗[R] N →ₗ[R] M ⊗[R] P) = lTensor M := rfl @[simp] theorem coe_rTensorHom : (rTensorHom M : (N →ₗ[R] P) → N ⊗[R] M →ₗ[R] P ⊗[R] M) = rTensor M := rfl @[simp] theorem lTensor_add (f g : N →ₗ[R] P) : (f + g).lTensor M = f.lTensor M + g.lTensor M := (lTensorHom M).map_add f g @[simp] theorem rTensor_add (f g : N →ₗ[R] P) : (f + g).rTensor M = f.rTensor M + g.rTensor M := (rTensorHom M).map_add f g @[simp] theorem lTensor_zero : lTensor M (0 : N →ₗ[R] P) = 0 := (lTensorHom M).map_zero @[simp] theorem rTensor_zero : rTensor M (0 : N →ₗ[R] P) = 0 := (rTensorHom M).map_zero @[simp] theorem lTensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).lTensor M = r • f.lTensor M := (lTensorHom M).map_smul r f @[simp] theorem rTensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).rTensor M = r • f.rTensor M := (rTensorHom M).map_smul r f theorem lTensor_comp : (g.comp f).lTensor M = (g.lTensor M).comp (f.lTensor M) := by ext m n simp only [compr₂_apply, mk_apply, comp_apply, lTensor_tmul] theorem lTensor_comp_apply (x : M ⊗[R] N) : (g.comp f).lTensor M x = (g.lTensor M) ((f.lTensor M) x) := by rw [lTensor_comp, coe_comp]; rfl theorem rTensor_comp : (g.comp f).rTensor M = (g.rTensor M).comp (f.rTensor M) := by ext m n simp only [compr₂_apply, mk_apply, comp_apply, rTensor_tmul] theorem rTensor_comp_apply (x : N ⊗[R] M) : (g.comp f).rTensor M x = (g.rTensor M) ((f.rTensor M) x) := by rw [rTensor_comp, coe_comp]; rfl theorem lTensor_mul (f g : Module.End R N) : (f * g).lTensor M = f.lTensor M * g.lTensor M := lTensor_comp M f g theorem rTensor_mul (f g : Module.End R N) : (f * g).rTensor M = f.rTensor M * g.rTensor M := rTensor_comp M f g variable (N) @[simp] theorem lTensor_id : (id : N →ₗ[R] N).lTensor M = id := map_id -- `simp` can prove this. theorem lTensor_id_apply (x : M ⊗[R] N) : (LinearMap.id : N →ₗ[R] N).lTensor M x = x := by rw [lTensor_id, id_coe, _root_.id] @[simp] theorem rTensor_id : (id : N →ₗ[R] N).rTensor M = id := map_id -- `simp` can prove this. theorem rTensor_id_apply (x : N ⊗[R] M) : (LinearMap.id : N →ₗ[R] N).rTensor M x = x := by rw [rTensor_id, id_coe, _root_.id] @[simp] theorem lTensor_smul_action (r : R) : (DistribMulAction.toLinearMap R N r).lTensor M = DistribMulAction.toLinearMap R (M ⊗[R] N) r := (lTensor_smul M r LinearMap.id).trans (congrArg _ (lTensor_id M N)) @[simp] theorem rTensor_smul_action (r : R) : (DistribMulAction.toLinearMap R N r).rTensor M = DistribMulAction.toLinearMap R (N ⊗[R] M) r := (rTensor_smul M r LinearMap.id).trans (congrArg _ (rTensor_id M N)) variable {N} theorem lid_comp_rTensor (f : N →ₗ[R] R) : (TensorProduct.lid R M).comp (rTensor M f) = lift ((lsmul R M).comp f) := ext' fun _ _ ↦ rfl @[simp] theorem lTensor_comp_rTensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g.lTensor P).comp (f.rTensor N) = map f g := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem rTensor_comp_lTensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f.rTensor Q).comp (g.lTensor M) = map f g := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem map_comp_rTensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (f' : S →ₗ[R] M) : (map f g).comp (f'.rTensor _) = map (f.comp f') g := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem map_comp_lTensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (g' : S →ₗ[R] N) : (map f g).comp (g'.lTensor _) = map f (g.comp g') := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem rTensor_comp_map (f' : P →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f'.rTensor _).comp (map f g) = map (f'.comp f) g := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem lTensor_comp_map (g' : Q →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g'.lTensor _).comp (map f g) = map f (g'.comp g) := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] variable {M} @[simp] theorem rTensor_pow (f : M →ₗ[R] M) (n : ℕ) : f.rTensor N ^ n = (f ^ n).rTensor N := by have h := TensorProduct.map_pow f (id : N →ₗ[R] N) n rwa [id_pow] at h @[simp] theorem lTensor_pow (f : N →ₗ[R] N) (n : ℕ) : f.lTensor M ^ n = (f ^ n).lTensor M := by have h := TensorProduct.map_pow (id : M →ₗ[R] M) f n rwa [id_pow] at h end LinearMap namespace LinearEquiv variable {N} /-- `LinearEquiv.lTensor M f : M ⊗ N ≃ₗ M ⊗ P` is the natural linear equivalence induced by `f : N ≃ₗ P`. -/ def lTensor (f : N ≃ₗ[R] P) : M ⊗[R] N ≃ₗ[R] M ⊗[R] P := TensorProduct.congr (refl R M) f /-- `LinearEquiv.rTensor M f : N₁ ⊗ M ≃ₗ N₂ ⊗ M` is the natural linear equivalence induced by `f : N₁ ≃ₗ N₂`. -/ def rTensor (f : N ≃ₗ[R] P) : N ⊗[R] M ≃ₗ[R] P ⊗[R] M := TensorProduct.congr f (refl R M) variable (g : P ≃ₗ[R] Q) (f : N ≃ₗ[R] P) (m : M) (n : N) (p : P) (x : M ⊗[R] N) (y : N ⊗[R] M) @[simp] theorem coe_lTensor : lTensor M f = (f : N →ₗ[R] P).lTensor M := rfl @[simp] theorem coe_lTensor_symm : (lTensor M f).symm = (f.symm : P →ₗ[R] N).lTensor M := rfl @[simp] theorem coe_rTensor : rTensor M f = (f : N →ₗ[R] P).rTensor M := rfl @[simp] theorem coe_rTensor_symm : (rTensor M f).symm = (f.symm : P →ₗ[R] N).rTensor M := rfl @[simp] theorem lTensor_tmul : f.lTensor M (m ⊗ₜ n) = m ⊗ₜ f n := rfl @[simp] theorem lTensor_symm_tmul : (f.lTensor M).symm (m ⊗ₜ p) = m ⊗ₜ f.symm p := rfl @[simp] theorem rTensor_tmul : f.rTensor M (n ⊗ₜ m) = f n ⊗ₜ m := rfl @[simp] theorem rTensor_symm_tmul : (f.rTensor M).symm (p ⊗ₜ m) = f.symm p ⊗ₜ m := rfl lemma comm_trans_rTensor_trans_comm_eq (g : N ≃ₗ[R] P) : TensorProduct.comm R Q N ≪≫ₗ rTensor Q g ≪≫ₗ TensorProduct.comm R P Q = lTensor Q g := toLinearMap_injective <| TensorProduct.ext rfl lemma comm_trans_lTensor_trans_comm_eq (g : N ≃ₗ[R] P) : TensorProduct.comm R N Q ≪≫ₗ lTensor Q g ≪≫ₗ TensorProduct.comm R Q P = rTensor Q g := toLinearMap_injective <| TensorProduct.ext rfl theorem lTensor_trans : (f ≪≫ₗ g).lTensor M = f.lTensor M ≪≫ₗ g.lTensor M := toLinearMap_injective <| LinearMap.lTensor_comp M _ _ theorem lTensor_trans_apply : (f ≪≫ₗ g).lTensor M x = g.lTensor M (f.lTensor M x) := LinearMap.lTensor_comp_apply M _ _ x theorem rTensor_trans : (f ≪≫ₗ g).rTensor M = f.rTensor M ≪≫ₗ g.rTensor M := toLinearMap_injective <| LinearMap.rTensor_comp M _ _ theorem rTensor_trans_apply : (f ≪≫ₗ g).rTensor M y = g.rTensor M (f.rTensor M y) := LinearMap.rTensor_comp_apply M _ _ y theorem lTensor_mul (f g : N ≃ₗ[R] N) : (f * g).lTensor M = f.lTensor M * g.lTensor M := lTensor_trans M f g theorem rTensor_mul (f g : N ≃ₗ[R] N) : (f * g).rTensor M = f.rTensor M * g.rTensor M := rTensor_trans M f g variable (N) @[simp] theorem lTensor_refl : (refl R N).lTensor M = refl R _ := TensorProduct.congr_refl_refl theorem lTensor_refl_apply : (refl R N).lTensor M x = x := by rw [lTensor_refl, refl_apply] @[simp] theorem rTensor_refl : (refl R N).rTensor M = refl R _ := TensorProduct.congr_refl_refl theorem rTensor_refl_apply : (refl R N).rTensor M y = y := by rw [rTensor_refl, refl_apply] variable {N} @[simp] theorem rTensor_trans_lTensor (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : f.rTensor N ≪≫ₗ g.lTensor P = TensorProduct.congr f g := toLinearMap_injective <| LinearMap.lTensor_comp_rTensor M _ _ @[simp] theorem lTensor_trans_rTensor (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : g.lTensor M ≪≫ₗ f.rTensor Q = TensorProduct.congr f g := toLinearMap_injective <| LinearMap.rTensor_comp_lTensor M _ _ @[simp] theorem rTensor_trans_congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (f' : S ≃ₗ[R] M) : f'.rTensor _ ≪≫ₗ TensorProduct.congr f g = TensorProduct.congr (f' ≪≫ₗ f) g := toLinearMap_injective <| LinearMap.map_comp_rTensor M _ _ _ @[simp] theorem lTensor_trans_congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (g' : S ≃ₗ[R] N) : g'.lTensor _ ≪≫ₗ TensorProduct.congr f g = TensorProduct.congr f (g' ≪≫ₗ g) := toLinearMap_injective <| LinearMap.map_comp_lTensor M _ _ _ @[simp] theorem congr_trans_rTensor (f' : P ≃ₗ[R] S) (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : TensorProduct.congr f g ≪≫ₗ f'.rTensor _ = TensorProduct.congr (f ≪≫ₗ f') g := toLinearMap_injective <| LinearMap.rTensor_comp_map M _ _ _ @[simp] theorem congr_trans_lTensor (g' : Q ≃ₗ[R] S) (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : TensorProduct.congr f g ≪≫ₗ g'.lTensor _ = TensorProduct.congr f (g ≪≫ₗ g') := toLinearMap_injective <| LinearMap.lTensor_comp_map M _ _ _ variable {M} @[simp] theorem rTensor_pow (f : M ≃ₗ[R] M) (n : ℕ) : f.rTensor N ^ n = (f ^ n).rTensor N := by simpa only [one_pow] using TensorProduct.congr_pow f (1 : N ≃ₗ[R] N) n @[simp] theorem rTensor_zpow (f : M ≃ₗ[R] M) (n : ℤ) : f.rTensor N ^ n = (f ^ n).rTensor N := by simpa only [one_zpow] using TensorProduct.congr_zpow f (1 : N ≃ₗ[R] N) n @[simp] theorem lTensor_pow (f : N ≃ₗ[R] N) (n : ℕ) : f.lTensor M ^ n = (f ^ n).lTensor M := by simpa only [one_pow] using TensorProduct.congr_pow (1 : M ≃ₗ[R] M) f n @[simp] theorem lTensor_zpow (f : N ≃ₗ[R] N) (n : ℤ) : f.lTensor M ^ n = (f ^ n).lTensor M := by simpa only [one_zpow] using TensorProduct.congr_zpow (1 : M ≃ₗ[R] M) f n end LinearEquiv end Semiring section Ring variable {R : Type*} [CommSemiring R] variable {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variable [AddCommGroup M] [AddCommGroup N] [AddCommGroup P] [AddCommGroup Q] [AddCommGroup S] variable [Module R M] [Module R N] [Module R P] [Module R Q] [Module R S] namespace TensorProduct open TensorProduct open LinearMap variable (R) /-- Auxiliary function to defining negation multiplication on tensor product. -/ def Neg.aux : M ⊗[R] N →ₗ[R] M ⊗[R] N := lift <| (mk R M N).comp (-LinearMap.id) variable {R} instance neg : Neg (M ⊗[R] N) where neg := Neg.aux R protected theorem add_left_neg (x : M ⊗[R] N) : -x + x = 0 := x.induction_on (by rw [add_zero]; apply (Neg.aux R).map_zero) (fun x y => by convert (add_tmul (R := R) (-x) x y).symm; rw [add_left_neg, zero_tmul]) fun x y hx hy => by suffices -x + x + (-y + y) = 0 by rw [← this] unfold Neg.neg neg simp only rw [map_add] abel rw [hx, hy, add_zero] instance addCommGroup : AddCommGroup (M ⊗[R] N) := { TensorProduct.addCommMonoid with neg := Neg.neg sub := _ sub_eq_add_neg := fun _ _ => rfl add_left_neg := fun x => TensorProduct.add_left_neg x zsmul := fun n v => n • v zsmul_zero' := by simp [TensorProduct.zero_smul] zsmul_succ' := by simp [add_comm, TensorProduct.one_smul, TensorProduct.add_smul] zsmul_neg' := fun n x => by change (-n.succ : ℤ) • x = -(((n : ℤ) + 1) • x) rw [← zero_add (_ • x), ← TensorProduct.add_left_neg ((n.succ : ℤ) • x), add_assoc, ← add_smul, ← sub_eq_add_neg, sub_self, zero_smul, add_zero] rfl } theorem neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -m ⊗ₜ[R] n := rfl theorem tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -m ⊗ₜ[R] n := (mk R M N _).map_neg _ theorem tmul_sub (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ - n₂) = m ⊗ₜ[R] n₁ - m ⊗ₜ[R] n₂ := (mk R M N _).map_sub _ _ theorem sub_tmul (m₁ m₂ : M) (n : N) : (m₁ - m₂) ⊗ₜ n = m₁ ⊗ₜ[R] n - m₂ ⊗ₜ[R] n := (mk R M N).map_sub₂ _ _ _ /-- While the tensor product will automatically inherit a ℤ-module structure from `AddCommGroup.toIntModule`, that structure won't be compatible with lemmas like `tmul_smul` unless we use a `ℤ-Module` instance provided by `TensorProduct.left_module`. When `R` is a `Ring` we get the required `TensorProduct.compatible_smul` instance through `IsScalarTower`, but when it is only a `Semiring` we need to build it from scratch. The instance diamond in `compatible_smul` doesn't matter because it's in `Prop`. -/ instance CompatibleSMul.int : CompatibleSMul R ℤ M N := ⟨fun r m n => Int.induction_on r (by simp) (fun r ih => by simpa [add_smul, tmul_add, add_tmul] using ih) fun r ih => by simpa [sub_smul, tmul_sub, sub_tmul] using ih⟩ instance CompatibleSMul.unit {S} [Monoid S] [DistribMulAction S M] [DistribMulAction S N] [CompatibleSMul R S M N] : CompatibleSMul R Sˣ M N := ⟨fun s m n => (CompatibleSMul.smul_tmul (s : S) m n : _)⟩ end TensorProduct namespace LinearMap @[simp] theorem lTensor_sub (f g : N →ₗ[R] P) : (f - g).lTensor M = f.lTensor M - g.lTensor M := by simp_rw [← coe_lTensorHom] exact (lTensorHom (R := R) (N := N) (P := P) M).map_sub f g @[simp] theorem rTensor_sub (f g : N →ₗ[R] P) : (f - g).rTensor M = f.rTensor M - g.rTensor M := by simp only [← coe_rTensorHom] exact (rTensorHom (R := R) (N := N) (P := P) M).map_sub f g @[simp] theorem lTensor_neg (f : N →ₗ[R] P) : (-f).lTensor M = -f.lTensor M := by simp only [← coe_lTensorHom] exact (lTensorHom (R := R) (N := N) (P := P) M).map_neg f @[simp] theorem rTensor_neg (f : N →ₗ[R] P) : (-f).rTensor M = -f.rTensor M := by simp only [← coe_rTensorHom] exact (rTensorHom (R := R) (N := N) (P := P) M).map_neg f end LinearMap end Ring
LinearAlgebra\TensorProduct\Basis.lean
/- Copyright (c) 2021 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer -/ import Mathlib.LinearAlgebra.DirectSum.Finsupp import Mathlib.LinearAlgebra.FinsuppVectorSpace /-! # Bases and dimensionality of tensor products of modules These can not go into `LinearAlgebra.TensorProduct` since they depend on `LinearAlgebra.FinsuppVectorSpace` which in turn imports `LinearAlgebra.TensorProduct`. -/ noncomputable section open Set LinearMap Submodule open scoped TensorProduct section CommSemiring variable {R : Type*} {S : Type*} {M : Type*} {N : Type*} {ι : Type*} {κ : Type*} [CommSemiring R] [Semiring S] [Algebra R S] [AddCommMonoid M] [Module R M] [Module S M] [IsScalarTower R S M] [AddCommMonoid N] [Module R N] /-- If `b : ι → M` and `c : κ → N` are bases then so is `fun i ↦ b i.1 ⊗ₜ c i.2 : ι × κ → M ⊗ N`. -/ def Basis.tensorProduct (b : Basis ι S M) (c : Basis κ R N) : Basis (ι × κ) S (M ⊗[R] N) := Finsupp.basisSingleOne.map ((TensorProduct.AlgebraTensorModule.congr b.repr c.repr).trans <| (finsuppTensorFinsupp R S _ _ _ _).trans <| Finsupp.lcongr (Equiv.refl _) (TensorProduct.AlgebraTensorModule.rid R S S)).symm @[simp] theorem Basis.tensorProduct_apply (b : Basis ι S M) (c : Basis κ R N) (i : ι) (j : κ) : Basis.tensorProduct b c (i, j) = b i ⊗ₜ c j := by simp [Basis.tensorProduct] theorem Basis.tensorProduct_apply' (b : Basis ι S M) (c : Basis κ R N) (i : ι × κ) : Basis.tensorProduct b c i = b i.1 ⊗ₜ c i.2 := by simp [Basis.tensorProduct] @[simp] theorem Basis.tensorProduct_repr_tmul_apply (b : Basis ι S M) (c : Basis κ R N) (m : M) (n : N) (i : ι) (j : κ) : (Basis.tensorProduct b c).repr (m ⊗ₜ n) (i, j) = c.repr n j • b.repr m i := by simp [Basis.tensorProduct, mul_comm] variable (S : Type*) [Semiring S] [Algebra R S] /-- The lift of an `R`-basis of `M` to an `S`-basis of the base change `S ⊗[R] M`. -/ noncomputable def Basis.baseChange (b : Basis ι R M) : Basis ι S (S ⊗[R] M) := ((Basis.singleton Unit S).tensorProduct b).reindex (Equiv.punitProd ι) @[simp] lemma Basis.baseChange_repr_tmul (b : Basis ι R M) (x y i) : (b.baseChange S).repr (x ⊗ₜ y) i = b.repr y i • x := by simp [Basis.baseChange, Basis.tensorProduct] @[simp] lemma Basis.baseChange_apply (b : Basis ι R M) (i) : b.baseChange S i = 1 ⊗ₜ b i := by simp [Basis.baseChange, Basis.tensorProduct] end CommSemiring end
LinearAlgebra\TensorProduct\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.DirectLimit /-! # 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*} [CommRing R] variable {ι : Type*} variable [DecidableEq ι] [Preorder ι] variable {G : ι → Type*} variable [∀ i, AddCommGroup (G i)] [∀ i, Module R (G i)] variable (f : ∀ i j, i ≤ j → G i →ₗ[R] G j) variable (M : Type*) [AddCommGroup 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 := 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 <| 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 variable [IsDirected ι (· ≤ ·)] /-- `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) := by refine LinearEquiv.ofLinear (toDirectLimit f M) (fromDirectLimit f M) ?_ ?_ <;> cases isEmpty_or_nonempty ι · ext; subsingleton · refine DFunLike.ext _ _ fun x ↦ x.induction_on fun i g ↦ g.induction_on ?_ ?_ ?_ <;> aesop · ext; subsingleton · exact ext (DFunLike.ext _ _ fun g ↦ DFunLike.ext _ _ fun _ ↦ g.induction_on <| by aesop) @[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 /-- `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 i ↦ 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] end TensorProduct
LinearAlgebra\TensorProduct\Finiteness.lean
/- Copyright (c) 2024 Jz Pan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jz Pan -/ import Mathlib.LinearAlgebra.TensorProduct.Basic import Mathlib.RingTheory.Finiteness /-! # Some finiteness results of tensor product This file contains some finiteness results of tensor product. - `TensorProduct.exists_multiset`, `TensorProduct.exists_finsupp_left`, `TensorProduct.exists_finsupp_right`, `TensorProduct.exists_finset`: any element of `M ⊗[R] N` can be written as a finite sum of pure tensors. See also `TensorProduct.span_tmul_eq_top`. - `TensorProduct.exists_finite_submodule_left_of_finite`, `TensorProduct.exists_finite_submodule_right_of_finite`, `TensorProduct.exists_finite_submodule_of_finite`: any finite subset of `M ⊗[R] N` is contained in `M' ⊗[R] N`, resp. `M ⊗[R] N'`, resp. `M' ⊗[R] N'`, for some finitely generated submodules `M'` and `N'` of `M` and `N`, respectively. - `TensorProduct.exists_finite_submodule_left_of_finite'`, `TensorProduct.exists_finite_submodule_right_of_finite'`, `TensorProduct.exists_finite_submodule_of_finite'`: variation of the above results where `M` and `N` are already submodules. ## Tags tensor product, finitely generated -/ open scoped TensorProduct open Submodule variable {R M N : Type*} variable [CommSemiring R] [AddCommMonoid M] [AddCommMonoid N] [Module R M] [Module R N] variable {M₁ M₂ : Submodule R M} {N₁ N₂ : Submodule R N} namespace TensorProduct /-- For any element `x` of `M ⊗[R] N`, there exists a (finite) multiset `{ (m_i, n_i) }` of `M × N`, such that `x` is equal to the sum of `m_i ⊗ₜ[R] n_i`. -/ theorem exists_multiset (x : M ⊗[R] N) : ∃ S : Multiset (M × N), x = (S.map fun i ↦ i.1 ⊗ₜ[R] i.2).sum := by induction x with | zero => exact ⟨0, by simp⟩ | tmul x y => exact ⟨{(x, y)}, by simp⟩ | add x y hx hy => obtain ⟨Sx, hx⟩ := hx obtain ⟨Sy, hy⟩ := hy exact ⟨Sx + Sy, by rw [Multiset.map_add, Multiset.sum_add, hx, hy]⟩ /-- For any element `x` of `M ⊗[R] N`, there exists a finite subset `{ (m_i, n_i) }` of `M × N` such that each `m_i` is distinct (we represent it as an element of `M →₀ N`), such that `x` is equal to the sum of `m_i ⊗ₜ[R] n_i`. -/ theorem exists_finsupp_left (x : M ⊗[R] N) : ∃ S : M →₀ N, x = S.sum fun m n ↦ m ⊗ₜ[R] n := by induction x with | zero => exact ⟨0, by simp⟩ | tmul x y => exact ⟨Finsupp.single x y, by simp⟩ | add x y hx hy => obtain ⟨Sx, hx⟩ := hx obtain ⟨Sy, hy⟩ := hy use Sx + Sy rw [hx, hy] exact (Finsupp.sum_add_index' (by simp) TensorProduct.tmul_add).symm /-- For any element `x` of `M ⊗[R] N`, there exists a finite subset `{ (m_i, n_i) }` of `M × N` such that each `n_i` is distinct (we represent it as an element of `N →₀ M`), such that `x` is equal to the sum of `m_i ⊗ₜ[R] n_i`. -/ theorem exists_finsupp_right (x : M ⊗[R] N) : ∃ S : N →₀ M, x = S.sum fun n m ↦ m ⊗ₜ[R] n := by obtain ⟨S, h⟩ := exists_finsupp_left (TensorProduct.comm R M N x) refine ⟨S, (TensorProduct.comm R M N).injective ?_⟩ simp_rw [h, Finsupp.sum, map_sum, comm_tmul] /-- For any element `x` of `M ⊗[R] N`, there exists a finite subset `{ (m_i, n_i) }` of `M × N`, such that `x` is equal to the sum of `m_i ⊗ₜ[R] n_i`. -/ theorem exists_finset (x : M ⊗[R] N) : ∃ S : Finset (M × N), x = S.sum fun i ↦ i.1 ⊗ₜ[R] i.2 := by obtain ⟨S, h⟩ := exists_finsupp_left x use S.graph rw [h, Finsupp.sum] apply Finset.sum_nbij' (fun m ↦ ⟨m, S m⟩) Prod.fst <;> simp /-- For a finite subset `s` of `M ⊗[R] N`, there are finitely generated submodules `M'` and `N'` of `M` and `N`, respectively, such that `s` is contained in the image of `M' ⊗[R] N'` in `M ⊗[R] N`. -/ theorem exists_finite_submodule_of_finite (s : Set (M ⊗[R] N)) (hs : s.Finite) : ∃ (M' : Submodule R M) (N' : Submodule R N), Module.Finite R M' ∧ Module.Finite R N' ∧ s ⊆ LinearMap.range (mapIncl M' N') := by simp_rw [Module.Finite.iff_fg] refine hs.induction_on ⟨_, _, fg_bot, fg_bot, Set.empty_subset _⟩ ?_ rintro a s - - ⟨M', N', hM', hN', h⟩ refine TensorProduct.induction_on a ?_ (fun x y ↦ ?_) fun x y hx hy ↦ ?_ · exact ⟨M', N', hM', hN', Set.insert_subset (zero_mem _) h⟩ · refine ⟨_, _, hM'.sup (fg_span_singleton x), hN'.sup (fg_span_singleton y), Set.insert_subset ?_ fun z hz ↦ ?_⟩ · exact ⟨⟨x, mem_sup_right (mem_span_singleton_self x)⟩ ⊗ₜ ⟨y, mem_sup_right (mem_span_singleton_self y)⟩, rfl⟩ · exact range_mapIncl_mono le_sup_left le_sup_left (h hz) · obtain ⟨M₁', N₁', hM₁', hN₁', h₁⟩ := hx obtain ⟨M₂', N₂', hM₂', hN₂', h₂⟩ := hy refine ⟨_, _, hM₁'.sup hM₂', hN₁'.sup hN₂', Set.insert_subset (add_mem ?_ ?_) fun z hz ↦ ?_⟩ · exact range_mapIncl_mono le_sup_left le_sup_left (h₁ (Set.mem_insert x s)) · exact range_mapIncl_mono le_sup_right le_sup_right (h₂ (Set.mem_insert y s)) · exact range_mapIncl_mono le_sup_left le_sup_left (h₁ (Set.subset_insert x s hz)) /-- For a finite subset `s` of `M ⊗[R] N`, there exists a finitely generated submodule `M'` of `M`, such that `s` is contained in the image of `M' ⊗[R] N` in `M ⊗[R] N`. -/ theorem exists_finite_submodule_left_of_finite (s : Set (M ⊗[R] N)) (hs : s.Finite) : ∃ M' : Submodule R M, Module.Finite R M' ∧ s ⊆ LinearMap.range (M'.subtype.rTensor N) := by obtain ⟨M', _, hfin, _, h⟩ := exists_finite_submodule_of_finite s hs refine ⟨M', hfin, ?_⟩ rw [mapIncl, ← LinearMap.rTensor_comp_lTensor] at h exact h.trans (LinearMap.range_comp_le_range _ _) /-- For a finite subset `s` of `M ⊗[R] N`, there exists a finitely generated submodule `N'` of `N`, such that `s` is contained in the image of `M ⊗[R] N'` in `M ⊗[R] N`. -/ theorem exists_finite_submodule_right_of_finite (s : Set (M ⊗[R] N)) (hs : s.Finite) : ∃ N' : Submodule R N, Module.Finite R N' ∧ s ⊆ LinearMap.range (N'.subtype.lTensor M) := by obtain ⟨_, N', _, hfin, h⟩ := exists_finite_submodule_of_finite s hs refine ⟨N', hfin, ?_⟩ rw [mapIncl, ← LinearMap.lTensor_comp_rTensor] at h exact h.trans (LinearMap.range_comp_le_range _ _) /-- Variation of `TensorProduct.exists_finite_submodule_of_finite` where `M` and `N` are already submodules. -/ theorem exists_finite_submodule_of_finite' (s : Set (M₁ ⊗[R] N₁)) (hs : s.Finite) : ∃ (M' : Submodule R M) (N' : Submodule R N) (hM : M' ≤ M₁) (hN : N' ≤ N₁), Module.Finite R M' ∧ Module.Finite R N' ∧ s ⊆ LinearMap.range (TensorProduct.map (inclusion hM) (inclusion hN)) := by obtain ⟨M', N', _, _, h⟩ := exists_finite_submodule_of_finite s hs have hM := map_subtype_le M₁ M' have hN := map_subtype_le N₁ N' refine ⟨_, _, hM, hN, .map _ _, .map _ _, ?_⟩ rw [mapIncl, show M'.subtype = inclusion hM ∘ₗ M₁.subtype.submoduleMap M' by ext; simp, show N'.subtype = inclusion hN ∘ₗ N₁.subtype.submoduleMap N' by ext; simp, map_comp] at h exact h.trans (LinearMap.range_comp_le_range _ _) /-- Variation of `TensorProduct.exists_finite_submodule_left_of_finite` where `M` and `N` are already submodules. -/ theorem exists_finite_submodule_left_of_finite' (s : Set (M₁ ⊗[R] N₁)) (hs : s.Finite) : ∃ (M' : Submodule R M) (hM : M' ≤ M₁), Module.Finite R M' ∧ s ⊆ LinearMap.range ((inclusion hM).rTensor N₁) := by obtain ⟨M', _, hM, _, hfin, _, h⟩ := exists_finite_submodule_of_finite' s hs refine ⟨M', hM, hfin, ?_⟩ rw [← LinearMap.rTensor_comp_lTensor] at h exact h.trans (LinearMap.range_comp_le_range _ _) /-- Variation of `TensorProduct.exists_finite_submodule_right_of_finite` where `M` and `N` are already submodules. -/ theorem exists_finite_submodule_right_of_finite' (s : Set (M₁ ⊗[R] N₁)) (hs : s.Finite) : ∃ (N' : Submodule R N) (hN : N' ≤ N₁), Module.Finite R N' ∧ s ⊆ LinearMap.range ((inclusion hN).lTensor M₁) := by obtain ⟨_, N', _, hN, _, hfin, h⟩ := exists_finite_submodule_of_finite' s hs refine ⟨N', hN, hfin, ?_⟩ rw [← LinearMap.lTensor_comp_rTensor] at h exact h.trans (LinearMap.range_comp_le_range _ _) end TensorProduct
LinearAlgebra\TensorProduct\Matrix.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.Data.Matrix.Kronecker import Mathlib.LinearAlgebra.Matrix.ToLin import Mathlib.LinearAlgebra.TensorProduct.Basis /-! # Connections between `TensorProduct` and `Matrix` This file contains results about the matrices corresponding to maps between tensor product types, where the correspondence is induced by `Basis.tensorProduct` Notably, `TensorProduct.toMatrix_map` shows that taking the tensor product of linear maps is equivalent to taking the Kronecker product of their matrix representations. -/ variable {R : Type*} {M N P M' N' : Type*} {ι κ τ ι' κ' : Type*} variable [DecidableEq ι] [DecidableEq κ] [DecidableEq τ] variable [Fintype ι] [Fintype κ] [Fintype τ] [Finite ι'] [Finite κ'] variable [CommRing R] variable [AddCommGroup M] [AddCommGroup N] [AddCommGroup P] variable [AddCommGroup M'] [AddCommGroup N'] variable [Module R M] [Module R N] [Module R P] [Module R M'] [Module R N'] variable (bM : Basis ι R M) (bN : Basis κ R N) (bP : Basis τ R P) variable (bM' : Basis ι' R M') (bN' : Basis κ' R N') open Kronecker open Matrix LinearMap /-- The linear map built from `TensorProduct.map` corresponds to the matrix built from `Matrix.kronecker`. -/ theorem TensorProduct.toMatrix_map (f : M →ₗ[R] M') (g : N →ₗ[R] N') : toMatrix (bM.tensorProduct bN) (bM'.tensorProduct bN') (TensorProduct.map f g) = toMatrix bM bM' f ⊗ₖ toMatrix bN bN' g := by ext ⟨i, j⟩ ⟨i', j'⟩ simp_rw [Matrix.kroneckerMap_apply, toMatrix_apply, Basis.tensorProduct_apply, TensorProduct.map_tmul, Basis.tensorProduct_repr_tmul_apply] exact mul_comm _ _ /-- The matrix built from `Matrix.kronecker` corresponds to the linear map built from `TensorProduct.map`. -/ theorem Matrix.toLin_kronecker (A : Matrix ι' ι R) (B : Matrix κ' κ R) : toLin (bM.tensorProduct bN) (bM'.tensorProduct bN') (A ⊗ₖ B) = TensorProduct.map (toLin bM bM' A) (toLin bN bN' B) := by rw [← LinearEquiv.eq_symm_apply, toLin_symm, TensorProduct.toMatrix_map, toMatrix_toLin, toMatrix_toLin] /-- `TensorProduct.comm` corresponds to a permutation of the identity matrix. -/ theorem TensorProduct.toMatrix_comm : toMatrix (bM.tensorProduct bN) (bN.tensorProduct bM) (TensorProduct.comm R M N) = (1 : Matrix (ι × κ) (ι × κ) R).submatrix Prod.swap _root_.id := by ext ⟨i, j⟩ ⟨i', j'⟩ simp only [toMatrix_apply, Basis.tensorProduct_apply, LinearEquiv.coe_coe, comm_tmul, Basis.tensorProduct_repr_tmul_apply, Basis.repr_self, Finsupp.single_apply, @eq_comm _ i', @eq_comm _ j', smul_eq_mul, mul_ite, mul_one, mul_zero, ← ite_and, and_comm, submatrix_apply, Matrix.one_apply, Prod.swap_prod_mk, id_eq, Prod.mk.injEq] /-- `TensorProduct.assoc` corresponds to a permutation of the identity matrix. -/ theorem TensorProduct.toMatrix_assoc : toMatrix ((bM.tensorProduct bN).tensorProduct bP) (bM.tensorProduct (bN.tensorProduct bP)) (TensorProduct.assoc R M N P) = (1 : Matrix (ι × κ × τ) (ι × κ × τ) R).submatrix _root_.id (Equiv.prodAssoc _ _ _) := by ext ⟨i, j, k⟩ ⟨⟨i', j'⟩, k'⟩ simp only [toMatrix_apply, Basis.tensorProduct_apply, LinearEquiv.coe_coe, assoc_tmul, Basis.tensorProduct_repr_tmul_apply, Basis.repr_self, Finsupp.single_apply, @eq_comm _ k', @eq_comm _ j', smul_eq_mul, mul_ite, mul_one, mul_zero, ← ite_and, @eq_comm _ i', submatrix_apply, Matrix.one_apply, id_eq, Equiv.prodAssoc_apply, Prod.mk.injEq]
LinearAlgebra\TensorProduct\Opposite.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.RingTheory.TensorProduct.Basic import Mathlib.Algebra.Algebra.Opposite /-! # `MulOpposite` distributes over `⊗` The main result in this file is: * `Algebra.TensorProduct.opAlgEquiv R S A B : Aᵐᵒᵖ ⊗[R] Bᵐᵒᵖ ≃ₐ[S] (A ⊗[R] B)ᵐᵒᵖ` -/ suppress_compilation open scoped TensorProduct variable (R S A B : Type*) variable [CommSemiring R] [CommSemiring S] [Semiring A] [Semiring B] variable [Algebra R S] [Algebra R A] [Algebra R B] [Algebra S A] variable [IsScalarTower R S A] namespace Algebra.TensorProduct open MulOpposite /-- `MulOpposite` distributes over `TensorProduct`. Note this is an `S`-algebra morphism, where `A/S/R` is a tower of algebras. -/ def opAlgEquiv : Aᵐᵒᵖ ⊗[R] Bᵐᵒᵖ ≃ₐ[S] (A ⊗[R] B)ᵐᵒᵖ := letI e₁ : Aᵐᵒᵖ ⊗[R] Bᵐᵒᵖ ≃ₗ[S] (A ⊗[R] B)ᵐᵒᵖ := TensorProduct.AlgebraTensorModule.congr (opLinearEquiv S).symm (opLinearEquiv R).symm ≪≫ₗ opLinearEquiv S letI e₂ : A ⊗[R] B ≃ₗ[S] (Aᵐᵒᵖ ⊗[R] Bᵐᵒᵖ)ᵐᵒᵖ := TensorProduct.AlgebraTensorModule.congr (opLinearEquiv S) (opLinearEquiv R) ≪≫ₗ opLinearEquiv S AlgEquiv.ofAlgHom (algHomOfLinearMapTensorProduct e₁.toLinearMap (fun a₁ a₂ b₁ b₂ => unop_injective (by with_unfolding_all rfl)) (unop_injective rfl)) (AlgHom.opComm <| algHomOfLinearMapTensorProduct e₂.toLinearMap (fun a₁ a₂ b₁ b₂ => unop_injective (by with_unfolding_all rfl)) (unop_injective rfl)) (AlgHom.op.symm.injective <| by ext <;> rfl) (by ext <;> rfl) theorem opAlgEquiv_apply (x : Aᵐᵒᵖ ⊗[R] Bᵐᵒᵖ) : opAlgEquiv R S A B x = op (_root_.TensorProduct.map (opLinearEquiv R).symm.toLinearMap (opLinearEquiv R).symm.toLinearMap x) := rfl theorem opAlgEquiv_symm_apply (x : (A ⊗[R] B)ᵐᵒᵖ) : (opAlgEquiv R S A B).symm x = _root_.TensorProduct.map (opLinearEquiv R).toLinearMap (opLinearEquiv R).toLinearMap x.unop := rfl @[simp] theorem opAlgEquiv_tmul (a : Aᵐᵒᵖ) (b : Bᵐᵒᵖ) : opAlgEquiv R S A B (a ⊗ₜ[R] b) = op (a.unop ⊗ₜ b.unop) := rfl @[simp] theorem opAlgEquiv_symm_tmul (a : A) (b : B) : (opAlgEquiv R S A B).symm (op <| a ⊗ₜ[R] b) = op a ⊗ₜ op b := rfl end Algebra.TensorProduct
LinearAlgebra\TensorProduct\Pi.lean
/- Copyright (c) 2024 Judith Ludwig, Christian Merten. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Judith Ludwig, Christian Merten -/ import Mathlib.LinearAlgebra.TensorProduct.Tower import Mathlib.LinearAlgebra.Pi /-! # Tensor product and products In this file we examine the behaviour of the tensor product with arbitrary and finite products. Let `S` be an `R`-algebra, `N` an `S`-module and `ι` an index type. We then have a natural map `TensorProduct.piScalarRightHom`: `N ⊗[R] (ι → R) →ₗ[S] (ι → N)` In general, this is not an isomorphism, but if `ι` is finite, then it is and it is packaged as `TensorProduct.piScalarRight`. ## Notes See `Mathlib.LinearAlgebra.TensorProduct.Prod` for binary products. -/ variable (R : Type*) [CommSemiring R] variable (S : Type*) [CommSemiring S] [Algebra R S] variable (N : Type*) [AddCommMonoid N] [Module R N] [Module S N] [IsScalarTower R S N] variable (ι : Type*) open LinearMap namespace TensorProduct private def piScalarRightHomBil : N →ₗ[S] (ι → R) →ₗ[R] (ι → N) where toFun n := LinearMap.compLeft (toSpanSingleton R N n) ι map_add' x y := by ext i j simp map_smul' s x := by ext i j dsimp only [coe_comp, coe_single, Function.comp_apply, compLeft_apply, toSpanSingleton_apply, RingHom.id_apply, smul_apply, Pi.smul_apply] rw [← IsScalarTower.smul_assoc, _root_.Algebra.smul_def, mul_comm, mul_smul] simp /-- For any `R`-module `N` and index type `ι`, there is a natural linear map `N ⊗[R] (ι → R) →ₗ (ι → N)`. This map is an isomorphism if `ι` is finite. -/ noncomputable def piScalarRightHom : N ⊗[R] (ι → R) →ₗ[S] (ι → N) := AlgebraTensorModule.lift <| piScalarRightHomBil R S N ι @[simp] lemma piScalarRightHom_tmul (x : N) (f : ι → R) : piScalarRightHom R S N ι (x ⊗ₜ f) = (fun j ↦ f j • x) := by ext j simp [piScalarRightHom, piScalarRightHomBil] variable [Fintype ι] [DecidableEq ι] private noncomputable def piScalarRightInv : (ι → N) →ₗ[S] N ⊗[R] (ι → R) := LinearMap.lsum S (fun _ ↦ N) S <| fun i ↦ { toFun := fun n ↦ n ⊗ₜ Pi.single i 1 map_add' := fun x y ↦ by simp [add_tmul] map_smul' := fun s x ↦ rfl } @[simp] private lemma piScalarRightInv_single (x : N) (i : ι) : piScalarRightInv R S N ι (Pi.single i x) = x ⊗ₜ Pi.single i 1 := by simp [piScalarRightInv, Pi.single_apply, TensorProduct.ite_tmul] /-- For any `R`-module `N` and finite index type `ι`, `N ⊗[R] (ι → R)` is canonically isomorphic to `ι → N`. -/ noncomputable def piScalarRight : N ⊗[R] (ι → R) ≃ₗ[S] (ι → N) := LinearEquiv.ofLinear (piScalarRightHom R S N ι) (piScalarRightInv R S N ι) (by ext i x j; simp [Pi.single_apply]) (by ext x i; simp [Pi.single_apply_smul]) @[simp] lemma piScalarRight_apply (x : N ⊗[R] (ι → R)) : piScalarRight R S N ι x = piScalarRightHom R S N ι x := by rfl @[simp] lemma piScalarRight_symm_single (x : N) (i : ι) : (piScalarRight R S N ι).symm (Pi.single i x) = x ⊗ₜ Pi.single i 1 := by simp [piScalarRight] end TensorProduct
LinearAlgebra\TensorProduct\Prod.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.LinearAlgebra.TensorProduct.Basic import Mathlib.LinearAlgebra.Prod /-! # Tensor products of products This file shows that taking `TensorProduct`s commutes with taking `Prod`s in both arguments. ## Main results * `TensorProduct.prodLeft` * `TensorProduct.prodRight` ## Notes See `Mathlib.LinearAlgebra.TensorProduct.Pi` for arbitrary products. -/ universe uR uM₁ uM₂ uM₃ variable (R : Type uR) (M₁ : Type uM₁) (M₂ : Type uM₂) (M₃ : Type uM₃) suppress_compilation namespace TensorProduct variable [CommSemiring R] [AddCommMonoid M₁] [AddCommMonoid M₂] [AddCommMonoid M₃] variable [Module R M₁] [Module R M₂] [Module R M₃] attribute [ext] TensorProduct.ext /-- Tensor products distribute over a product on the right. -/ def prodRight : M₁ ⊗[R] (M₂ × M₃) ≃ₗ[R] ((M₁ ⊗[R] M₂) × (M₁ ⊗[R] M₃)) := LinearEquiv.ofLinear (lift <| LinearMap.prodMapLinear R M₂ M₃ (M₁ ⊗[R] M₂) (M₁ ⊗[R] M₃) R ∘ₗ LinearMap.prod (mk _ _ _) (mk _ _ _)) (LinearMap.coprod (LinearMap.lTensor _ <| LinearMap.inl _ _ _) (LinearMap.lTensor _ <| LinearMap.inr _ _ _)) (by ext <;> simp) (by ext <;> simp) @[simp] theorem prodRight_tmul (m₁ : M₁) (m₂ : M₂) (m₃ : M₃) : prodRight R M₁ M₂ M₃ (m₁ ⊗ₜ (m₂, m₃)) = (m₁ ⊗ₜ m₂, m₁ ⊗ₜ m₃) := rfl @[simp] theorem prodRight_symm_tmul (m₁ : M₁) (m₂ : M₂) (m₃ : M₃) : (prodRight R M₁ M₂ M₃).symm (m₁ ⊗ₜ m₂, m₁ ⊗ₜ m₃) = (m₁ ⊗ₜ (m₂, m₃)) := (LinearEquiv.symm_apply_eq _).mpr rfl /-- Tensor products distribute over a product on the left . -/ def prodLeft : (M₁ × M₂) ⊗[R] M₃ ≃ₗ[R] ((M₁ ⊗[R] M₃) × (M₂ ⊗[R] M₃)) := TensorProduct.comm _ _ _ ≪≫ₗ TensorProduct.prodRight R _ _ _ ≪≫ₗ (TensorProduct.comm R _ _).prod (TensorProduct.comm R _ _) @[simp] theorem prodLeft_tmul (m₁ : M₁) (m₂ : M₂) (m₃ : M₃) : prodLeft R M₁ M₂ M₃ ((m₁, m₂) ⊗ₜ m₃) = (m₁ ⊗ₜ m₃, m₂ ⊗ₜ m₃) := rfl @[simp] theorem prodLeft_symm_tmul (m₁ : M₁) (m₂ : M₂) (m₃ : M₃) : (prodLeft R M₁ M₂ M₃).symm (m₁ ⊗ₜ m₃, m₂ ⊗ₜ m₃) = ((m₁, m₂) ⊗ₜ m₃) := (LinearEquiv.symm_apply_eq _).mpr rfl end TensorProduct
LinearAlgebra\TensorProduct\RightExactness.lean
/- Copyright (c) 2023 Antoine Chambert-Loir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Chambert-Loir -/ import Mathlib.Algebra.Exact import Mathlib.RingTheory.TensorProduct.Basic /-! # Right-exactness properties of tensor product ## Modules * `LinearMap.rTensor_surjective` asserts that when one tensors a surjective map on the right, one still gets a surjective linear map. More generally, `LinearMap.rTensor_range` computes the range of `LinearMap.rTensor` * `LinearMap.lTensor_surjective` asserts that when one tensors a surjective map on the left, one still gets a surjective linear map. More generally, `LinearMap.lTensor_range` computes the range of `LinearMap.lTensor` * `TensorProduct.rTensor_exact` says that when one tensors a short exact sequence on the right, one still gets a short exact sequence (right-exactness of `TensorProduct.rTensor`), and `rTensor.equiv` gives the LinearEquiv that follows from this combined with `LinearMap.rTensor_surjective`. * `TensorProduct.lTensor_exact` says that when one tensors a short exact sequence on the left, one still gets a short exact sequence (right-exactness of `TensorProduct.rTensor`) and `lTensor.equiv` gives the LinearEquiv that follows from this combined with `LinearMap.lTensor_surjective`. * For `N : Submodule R M`, `LinearMap.exact_subtype_mkQ N` says that the inclusion of the submodule and the quotient map form an exact pair, and `lTensor_mkQ` compute `ker (lTensor Q (N.mkQ))` and similarly for `rTensor_mkQ` * `TensorProduct.map_ker` computes the kernel of `TensorProduct.map f g'` in the presence of two short exact sequences. The proofs are those of [bourbaki1989] (chap. 2, §3, n°6) ## Algebras In the case of a tensor product of algebras, these results can be particularized to compute some kernels. * `Algebra.TensorProduct.ker_map` computes the kernel of `Algebra.TensorProduct.map f g` * `Algebra.TensorProduct.lTensor_ker` and `Algebra.TensorProduct.rTensor_ker` compute the kernels of `Algebra.TensorProduct.map f id` and `Algebra.TensorProduct.map id g` ## Note on implementation * All kernels are computed by applying the first isomorphism theorem and establishing some isomorphisms. * The proofs are essentially done twice, once for `lTensor` and then for `rTensor`. It is possible to apply `TensorProduct.flip` to deduce one of them from the other. However, this approach will lead to different isomorphisms, and it is not quicker. * The proofs of `Ideal.map_includeLeft_eq` and `Ideal.map_includeRight_eq` could be easier if `I ⊗[R] B` was naturally an `A ⊗[R] B` module, and the map to `A ⊗[R] B` was known to be linear. This depends on the B-module structure on a tensor product whose use rapidly conflicts with everything… ## TODO * Treat the noncommutative case * Treat the case of modules over semirings (For a possible definition of an exact sequence of commutative semigroups, see [Grillet-1969b], Pierre-Antoine Grillet, *The tensor product of commutative semigroups*, Trans. Amer. Math. Soc. 138 (1969), 281-293, doi:10.1090/S0002-9947-1969-0237688-1 .) -/ section Modules open TensorProduct LinearMap section Semiring variable {R : Type*} [CommSemiring R] {M N P Q : Type*} [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] [AddCommMonoid Q] [Module R M] [Module R N] [Module R P] [Module R Q] {f : M →ₗ[R] N} (g : N →ₗ[R] P) lemma le_comap_range_lTensor (q : Q) : LinearMap.range g ≤ (LinearMap.range (lTensor Q g)).comap (TensorProduct.mk R Q P q) := by rintro x ⟨n, rfl⟩ exact ⟨q ⊗ₜ[R] n, rfl⟩ lemma le_comap_range_rTensor (q : Q) : LinearMap.range g ≤ (LinearMap.range (rTensor Q g)).comap ((TensorProduct.mk R P Q).flip q) := by rintro x ⟨n, rfl⟩ exact ⟨n ⊗ₜ[R] q, rfl⟩ variable (Q) {g} /-- If `g` is surjective, then `lTensor Q g` is surjective -/ theorem LinearMap.lTensor_surjective (hg : Function.Surjective g) : Function.Surjective (lTensor Q g) := by intro z induction z with | zero => exact ⟨0, map_zero _⟩ | tmul q p => obtain ⟨n, rfl⟩ := hg p exact ⟨q ⊗ₜ[R] n, rfl⟩ | add x y hx hy => obtain ⟨x, rfl⟩ := hx obtain ⟨y, rfl⟩ := hy exact ⟨x + y, map_add _ _ _⟩ theorem LinearMap.lTensor_range : range (lTensor Q g) = range (lTensor Q (Submodule.subtype (range g))) := by have : g = (Submodule.subtype _).comp g.rangeRestrict := rfl nth_rewrite 1 [this] rw [lTensor_comp] apply range_comp_of_range_eq_top rw [range_eq_top] apply lTensor_surjective rw [← range_eq_top, range_rangeRestrict] /-- If `g` is surjective, then `rTensor Q g` is surjective -/ theorem LinearMap.rTensor_surjective (hg : Function.Surjective g) : Function.Surjective (rTensor Q g) := by intro z induction z with | zero => exact ⟨0, map_zero _⟩ | tmul p q => obtain ⟨n, rfl⟩ := hg p exact ⟨n ⊗ₜ[R] q, rfl⟩ | add x y hx hy => obtain ⟨x, rfl⟩ := hx obtain ⟨y, rfl⟩ := hy exact ⟨x + y, map_add _ _ _⟩ theorem LinearMap.rTensor_range : range (rTensor Q g) = range (rTensor Q (Submodule.subtype (range g))) := by have : g = (Submodule.subtype _).comp g.rangeRestrict := rfl nth_rewrite 1 [this] rw [rTensor_comp] apply range_comp_of_range_eq_top rw [range_eq_top] apply rTensor_surjective rw [← range_eq_top, range_rangeRestrict] end Semiring variable {R M N P : Type*} [CommRing R] [AddCommGroup M] [AddCommGroup N] [AddCommGroup P] [Module R M] [Module R N] [Module R P] open Function variable {f : M →ₗ[R] N} {g : N →ₗ[R] P} (Q : Type*) [AddCommGroup Q] [Module R Q] (hfg : Exact f g) (hg : Function.Surjective g) /-- The direct map in `lTensor.equiv` -/ noncomputable def lTensor.toFun : Q ⊗[R] N ⧸ LinearMap.range (lTensor Q f) →ₗ[R] Q ⊗[R] P := Submodule.liftQ _ (lTensor Q g) <| by rw [LinearMap.range_le_iff_comap, ← LinearMap.ker_comp, ← lTensor_comp, hfg.linearMap_comp_eq_zero, lTensor_zero, ker_zero] /-- The inverse map in `lTensor.equiv_of_rightInverse` (computably, given a right inverse)-/ noncomputable def lTensor.inverse_of_rightInverse {h : P → N} (hgh : Function.RightInverse h g) : Q ⊗[R] P →ₗ[R] Q ⊗[R] N ⧸ LinearMap.range (lTensor Q f) := TensorProduct.lift <| LinearMap.flip <| { toFun := fun p ↦ Submodule.mkQ _ ∘ₗ ((TensorProduct.mk R _ _).flip (h p)) map_add' := fun p p' => LinearMap.ext fun q => (Submodule.Quotient.eq _).mpr <| by change q ⊗ₜ[R] (h (p + p')) - (q ⊗ₜ[R] (h p) + q ⊗ₜ[R] (h p')) ∈ range (lTensor Q f) rw [← TensorProduct.tmul_add, ← TensorProduct.tmul_sub] apply le_comap_range_lTensor f rw [exact_iff] at hfg simp only [← hfg, mem_ker, map_sub, map_add, hgh _, sub_self] map_smul' := fun r p => LinearMap.ext fun q => (Submodule.Quotient.eq _).mpr <| by change q ⊗ₜ[R] (h (r • p)) - r • q ⊗ₜ[R] (h p) ∈ range (lTensor Q f) rw [← TensorProduct.tmul_smul, ← TensorProduct.tmul_sub] apply le_comap_range_lTensor f rw [exact_iff] at hfg simp only [← hfg, mem_ker, map_sub, map_smul, hgh _, sub_self] } lemma lTensor.inverse_of_rightInverse_apply {h : P → N} (hgh : Function.RightInverse h g) (y : Q ⊗[R] N) : (lTensor.inverse_of_rightInverse Q hfg hgh) ((lTensor Q g) y) = Submodule.Quotient.mk (p := (LinearMap.range (lTensor Q f))) y := by simp only [← LinearMap.comp_apply, ← Submodule.mkQ_apply] rw [exact_iff] at hfg apply LinearMap.congr_fun apply TensorProduct.ext' intro n q simp? [lTensor.inverse_of_rightInverse] says simp only [inverse_of_rightInverse, coe_comp, Function.comp_apply, lTensor_tmul, lift.tmul, flip_apply, coe_mk, AddHom.coe_mk, mk_apply, Submodule.mkQ_apply] rw [Submodule.Quotient.eq, ← TensorProduct.tmul_sub] apply le_comap_range_lTensor f n rw [← hfg, mem_ker, map_sub, sub_eq_zero, hgh] lemma lTensor.inverse_of_rightInverse_comp_lTensor {h : P → N} (hgh : Function.RightInverse h g) : (lTensor.inverse_of_rightInverse Q hfg hgh).comp (lTensor Q g) = Submodule.mkQ (p := LinearMap.range (lTensor Q f)) := by rw [LinearMap.ext_iff] intro y simp only [coe_comp, Function.comp_apply, Submodule.mkQ_apply, lTensor.inverse_of_rightInverse_apply] /-- The inverse map in `lTensor.equiv` -/ noncomputable def lTensor.inverse : Q ⊗[R] P →ₗ[R] Q ⊗[R] N ⧸ LinearMap.range (lTensor Q f) := lTensor.inverse_of_rightInverse Q hfg (Function.rightInverse_surjInv hg) lemma lTensor.inverse_apply (y : Q ⊗[R] N) : (lTensor.inverse Q hfg hg) ((lTensor Q g) y) = Submodule.Quotient.mk (p := (LinearMap.range (lTensor Q f))) y := by rw [lTensor.inverse, lTensor.inverse_of_rightInverse_apply] lemma lTensor.inverse_comp_lTensor : (lTensor.inverse Q hfg hg).comp (lTensor Q g) = Submodule.mkQ (p := LinearMap.range (lTensor Q f)) := by rw [lTensor.inverse, lTensor.inverse_of_rightInverse_comp_lTensor] /-- For a surjective `f : N →ₗ[R] P`, the natural equivalence between `Q ⊗ N ⧸ (image of ker f)` to `Q ⊗ P` (computably, given a right inverse) -/ noncomputable def lTensor.linearEquiv_of_rightInverse {h : P → N} (hgh : Function.RightInverse h g) : ((Q ⊗[R] N) ⧸ (LinearMap.range (lTensor Q f))) ≃ₗ[R] (Q ⊗[R] P) := { toLinearMap := lTensor.toFun Q hfg invFun := lTensor.inverse_of_rightInverse Q hfg hgh left_inv := fun y ↦ by simp only [lTensor.toFun, AddHom.toFun_eq_coe, coe_toAddHom] obtain ⟨y, rfl⟩ := Submodule.mkQ_surjective _ y simp only [Submodule.mkQ_apply, Submodule.liftQ_apply, lTensor.inverse_of_rightInverse_apply] right_inv := fun z ↦ by simp only [AddHom.toFun_eq_coe, coe_toAddHom] obtain ⟨y, rfl⟩ := lTensor_surjective Q (hgh.surjective) z rw [lTensor.inverse_of_rightInverse_apply] simp only [lTensor.toFun, Submodule.liftQ_apply] } /-- For a surjective `f : N →ₗ[R] P`, the natural equivalence between `Q ⊗ N ⧸ (image of ker f)` to `Q ⊗ P` -/ noncomputable def lTensor.equiv : ((Q ⊗[R] N) ⧸ (LinearMap.range (lTensor Q f))) ≃ₗ[R] (Q ⊗[R] P) := lTensor.linearEquiv_of_rightInverse Q hfg (Function.rightInverse_surjInv hg) /-- Tensoring an exact pair on the left gives an exact pair -/ theorem lTensor_exact : Exact (lTensor Q f) (lTensor Q g) := by rw [exact_iff, ← Submodule.ker_mkQ (p := range (lTensor Q f)), ← lTensor.inverse_comp_lTensor Q hfg hg] apply symm apply LinearMap.ker_comp_of_ker_eq_bot rw [LinearMap.ker_eq_bot] exact (lTensor.equiv Q hfg hg).symm.injective /-- Right-exactness of tensor product -/ lemma lTensor_mkQ (N : Submodule R M) : ker (lTensor Q (N.mkQ)) = range (lTensor Q N.subtype) := by rw [← exact_iff] exact lTensor_exact Q (LinearMap.exact_subtype_mkQ N) (Submodule.mkQ_surjective N) /-- The direct map in `rTensor.equiv` -/ noncomputable def rTensor.toFun : N ⊗[R] Q ⧸ range (rTensor Q f) →ₗ[R] P ⊗[R] Q := Submodule.liftQ _ (rTensor Q g) <| by rw [range_le_iff_comap, ← ker_comp, ← rTensor_comp, hfg.linearMap_comp_eq_zero, rTensor_zero, ker_zero] /-- The inverse map in `rTensor.equiv_of_rightInverse` (computably, given a right inverse) -/ noncomputable def rTensor.inverse_of_rightInverse {h : P → N} (hgh : Function.RightInverse h g) : P ⊗[R] Q →ₗ[R] N ⊗[R] Q ⧸ LinearMap.range (rTensor Q f) := TensorProduct.lift { toFun := fun p ↦ Submodule.mkQ _ ∘ₗ TensorProduct.mk R _ _ (h p) map_add' := fun p p' => LinearMap.ext fun q => (Submodule.Quotient.eq _).mpr <| by change h (p + p') ⊗ₜ[R] q - (h p ⊗ₜ[R] q + h p' ⊗ₜ[R] q) ∈ range (rTensor Q f) rw [← TensorProduct.add_tmul, ← TensorProduct.sub_tmul] apply le_comap_range_rTensor f rw [exact_iff] at hfg simp only [← hfg, mem_ker, map_sub, map_add, hgh _, sub_self] map_smul' := fun r p => LinearMap.ext fun q => (Submodule.Quotient.eq _).mpr <| by change h (r • p) ⊗ₜ[R] q - r • h p ⊗ₜ[R] q ∈ range (rTensor Q f) rw [TensorProduct.smul_tmul', ← TensorProduct.sub_tmul] apply le_comap_range_rTensor f rw [exact_iff] at hfg simp only [← hfg, mem_ker, map_sub, map_smul, hgh _, sub_self] } lemma rTensor.inverse_of_rightInverse_apply {h : P → N} (hgh : Function.RightInverse h g) (y : N ⊗[R] Q) : (rTensor.inverse_of_rightInverse Q hfg hgh) ((rTensor Q g) y) = Submodule.Quotient.mk (p := LinearMap.range (rTensor Q f)) y := by simp only [← LinearMap.comp_apply, ← Submodule.mkQ_apply] rw [exact_iff] at hfg apply LinearMap.congr_fun apply TensorProduct.ext' intro n q simp? [rTensor.inverse_of_rightInverse] says simp only [inverse_of_rightInverse, coe_comp, Function.comp_apply, rTensor_tmul, lift.tmul, coe_mk, AddHom.coe_mk, mk_apply, Submodule.mkQ_apply] rw [Submodule.Quotient.eq, ← TensorProduct.sub_tmul] apply le_comap_range_rTensor f rw [← hfg, mem_ker, map_sub, sub_eq_zero, hgh] lemma rTensor.inverse_of_rightInverse_comp_rTensor {h : P → N} (hgh : Function.RightInverse h g) : (rTensor.inverse_of_rightInverse Q hfg hgh).comp (rTensor Q g) = Submodule.mkQ (p := LinearMap.range (rTensor Q f)) := by rw [LinearMap.ext_iff] intro y simp only [coe_comp, Function.comp_apply, Submodule.mkQ_apply, rTensor.inverse_of_rightInverse_apply] /-- The inverse map in `rTensor.equiv` -/ noncomputable def rTensor.inverse : P ⊗[R] Q →ₗ[R] N ⊗[R] Q ⧸ LinearMap.range (rTensor Q f) := rTensor.inverse_of_rightInverse Q hfg (Function.rightInverse_surjInv hg) lemma rTensor.inverse_apply (y : N ⊗[R] Q) : (rTensor.inverse Q hfg hg) ((rTensor Q g) y) = Submodule.Quotient.mk (p := LinearMap.range (rTensor Q f)) y := by rw [rTensor.inverse, rTensor.inverse_of_rightInverse_apply] lemma rTensor.inverse_comp_rTensor : (rTensor.inverse Q hfg hg).comp (rTensor Q g) = Submodule.mkQ (p := LinearMap.range (rTensor Q f)) := by rw [rTensor.inverse, rTensor.inverse_of_rightInverse_comp_rTensor] /-- For a surjective `f : N →ₗ[R] P`, the natural equivalence between `N ⊗[R] Q ⧸ (range (rTensor Q f))` and `P ⊗[R] Q` (computably, given a right inverse) -/ noncomputable def rTensor.linearEquiv_of_rightInverse {h : P → N} (hgh : Function.RightInverse h g) : ((N ⊗[R] Q) ⧸ (range (rTensor Q f))) ≃ₗ[R] (P ⊗[R] Q) := { toLinearMap := rTensor.toFun Q hfg invFun := rTensor.inverse_of_rightInverse Q hfg hgh left_inv := fun y ↦ by simp only [rTensor.toFun, AddHom.toFun_eq_coe, coe_toAddHom] obtain ⟨y, rfl⟩ := Submodule.mkQ_surjective _ y simp only [Submodule.mkQ_apply, Submodule.liftQ_apply, rTensor.inverse_of_rightInverse_apply] right_inv := fun z ↦ by simp only [AddHom.toFun_eq_coe, coe_toAddHom] obtain ⟨y, rfl⟩ := rTensor_surjective Q hgh.surjective z rw [rTensor.inverse_of_rightInverse_apply] simp only [rTensor.toFun, Submodule.liftQ_apply] } /-- For a surjective `f : N →ₗ[R] P`, the natural equivalence between `N ⊗[R] Q ⧸ (range (rTensor Q f))` and `P ⊗[R] Q` -/ noncomputable def rTensor.equiv : ((N ⊗[R] Q) ⧸ (LinearMap.range (rTensor Q f))) ≃ₗ[R] (P ⊗[R] Q) := rTensor.linearEquiv_of_rightInverse Q hfg (Function.rightInverse_surjInv hg) /-- Tensoring an exact pair on the right gives an exact pair -/ theorem rTensor_exact : Exact (rTensor Q f) (rTensor Q g) := by rw [exact_iff, ← Submodule.ker_mkQ (p := range (rTensor Q f)), ← rTensor.inverse_comp_rTensor Q hfg hg] apply symm apply ker_comp_of_ker_eq_bot rw [ker_eq_bot] exact (rTensor.equiv Q hfg hg).symm.injective /-- Right-exactness of tensor product (`rTensor`) -/ lemma rTensor_mkQ (N : Submodule R M) : ker (rTensor Q (N.mkQ)) = range (rTensor Q N.subtype) := by rw [← exact_iff] exact rTensor_exact Q (LinearMap.exact_subtype_mkQ N) (Submodule.mkQ_surjective N) variable {M' N' P' : Type*} [AddCommGroup M'] [AddCommGroup N'] [AddCommGroup P'] [Module R M'] [Module R N'] [Module R P'] {f' : M' →ₗ[R] N'} {g' : N' →ₗ[R] P'} (hfg' : Exact f' g') (hg' : Function.Surjective g') theorem TensorProduct.map_surjective : Function.Surjective (TensorProduct.map g g') := by rw [← lTensor_comp_rTensor, coe_comp] exact Function.Surjective.comp (lTensor_surjective _ hg') (rTensor_surjective _ hg) /-- Kernel of a product map (right-exactness of tensor product) -/ theorem TensorProduct.map_ker : ker (TensorProduct.map g g') = range (lTensor N f') ⊔ range (rTensor N' f) := by rw [← lTensor_comp_rTensor] rw [ker_comp] rw [← Exact.linearMap_ker_eq (rTensor_exact N' hfg hg)] rw [← Submodule.comap_map_eq] apply congr_arg₂ _ rfl rw [range_eq_map, ← Submodule.map_comp, rTensor_comp_lTensor, Submodule.map_top] rw [← lTensor_comp_rTensor, range_eq_map, Submodule.map_comp, Submodule.map_top] rw [range_eq_top.mpr (rTensor_surjective M' hg), Submodule.map_top] rw [Exact.linearMap_ker_eq (lTensor_exact P hfg' hg')] variable (M) variable (R) in theorem TensorProduct.mk_surjective (S) [Semiring S] [Algebra R S] (h : Surjective (algebraMap R S)) : Surjective (TensorProduct.mk R S M 1) := by rw [← LinearMap.range_eq_top, ← top_le_iff, ← TensorProduct.span_tmul_eq_top, Submodule.span_le] rintro _ ⟨x, y, rfl⟩ obtain ⟨x, rfl⟩ := h x rw [Algebra.algebraMap_eq_smul_one, smul_tmul] exact ⟨x • y, rfl⟩ /-- Left tensoring a module with a quotient of the ring is the same as quotienting that module by the corresponding submodule. -/ noncomputable def quotTensorEquivQuotSMul (I : Ideal R) : (R ⧸ I) ⊗[R] M ≃ₗ[R] M ⧸ (I • ⊤ : Submodule R M) := (rTensor.equiv M (exact_subtype_mkQ I) I.mkQ_surjective).symm.trans <| Submodule.Quotient.equiv _ _ (TensorProduct.lid R M) <| Eq.trans (LinearMap.range_comp _ _).symm <| Eq.trans ((Submodule.topEquiv.lTensor I).range_comp _).symm <| Eq.symm <| Eq.trans (map₂_eq_range_lift_comp_mapIncl _ _ _) <| congrArg _ (TensorProduct.ext' (fun _ _ => rfl)) /-- Right tensoring a module with a quotient of the ring is the same as quotienting that module by the corresponding submodule. -/ noncomputable def tensorQuotEquivQuotSMul (I : Ideal R) : M ⊗[R] (R ⧸ I) ≃ₗ[R] M ⧸ (I • ⊤ : Submodule R M) := TensorProduct.comm R M _ ≪≫ₗ quotTensorEquivQuotSMul M I variable {M} @[simp] lemma quotTensorEquivQuotSMul_mk_tmul (I : Ideal R) (r : R) (x : M) : quotTensorEquivQuotSMul M I (Ideal.Quotient.mk I r ⊗ₜ[R] x) = Submodule.Quotient.mk (r • x) := (quotTensorEquivQuotSMul M I).eq_symm_apply.mp <| Eq.trans (congrArg (· ⊗ₜ[R] x) <| Eq.trans (congrArg (Ideal.Quotient.mk I) (Eq.trans (smul_eq_mul R) (mul_one r))).symm <| Submodule.Quotient.mk_smul I r 1) <| smul_tmul r _ x lemma quotTensorEquivQuotSMul_comp_mkQ_rTensor (I : Ideal R) : quotTensorEquivQuotSMul M I ∘ₗ I.mkQ.rTensor M = (I • ⊤ : Submodule R M).mkQ ∘ₗ TensorProduct.lid R M := TensorProduct.ext' (quotTensorEquivQuotSMul_mk_tmul I) @[simp] lemma quotTensorEquivQuotSMul_symm_mk (I : Ideal R) (x : M) : (quotTensorEquivQuotSMul M I).symm (Submodule.Quotient.mk x) = 1 ⊗ₜ[R] x := rfl lemma quotTensorEquivQuotSMul_symm_comp_mkQ (I : Ideal R) : (quotTensorEquivQuotSMul M I).symm ∘ₗ (I • ⊤ : Submodule R M).mkQ = TensorProduct.mk R (R ⧸ I) M 1 := LinearMap.ext (quotTensorEquivQuotSMul_symm_mk I) lemma quotTensorEquivQuotSMul_comp_mk (I : Ideal R) : quotTensorEquivQuotSMul M I ∘ₗ TensorProduct.mk R (R ⧸ I) M 1 = Submodule.mkQ (I • ⊤) := Eq.symm <| (LinearEquiv.toLinearMap_symm_comp_eq _ _).mp <| quotTensorEquivQuotSMul_symm_comp_mkQ I @[simp] lemma tensorQuotEquivQuotSMul_tmul_mk (I : Ideal R) (x : M) (r : R) : tensorQuotEquivQuotSMul M I (x ⊗ₜ[R] Ideal.Quotient.mk I r) = Submodule.Quotient.mk (r • x) := quotTensorEquivQuotSMul_mk_tmul I r x lemma tensorQuotEquivQuotSMul_comp_mkQ_lTensor (I : Ideal R) : tensorQuotEquivQuotSMul M I ∘ₗ I.mkQ.lTensor M = (I • ⊤ : Submodule R M).mkQ ∘ₗ TensorProduct.rid R M := TensorProduct.ext' (tensorQuotEquivQuotSMul_tmul_mk I) @[simp] lemma tensorQuotEquivQuotSMul_symm_mk (I : Ideal R) (x : M) : (tensorQuotEquivQuotSMul M I).symm (Submodule.Quotient.mk x) = x ⊗ₜ[R] 1 := rfl lemma tensorQuotEquivQuotSMul_symm_comp_mkQ (I : Ideal R) : (tensorQuotEquivQuotSMul M I).symm ∘ₗ (I • ⊤ : Submodule R M).mkQ = (TensorProduct.mk R M (R ⧸ I)).flip 1 := LinearMap.ext (tensorQuotEquivQuotSMul_symm_mk I) lemma tensorQuotEquivQuotSMul_comp_mk (I : Ideal R) : tensorQuotEquivQuotSMul M I ∘ₗ (TensorProduct.mk R M (R ⧸ I)).flip 1 = Submodule.mkQ (I • ⊤) := Eq.symm <| (LinearEquiv.toLinearMap_symm_comp_eq _ _).mp <| tensorQuotEquivQuotSMul_symm_comp_mkQ I end Modules section Algebras open Algebra.TensorProduct open scoped TensorProduct variable {R : Type*} [CommSemiring R] {A B : Type*} [Semiring A] [Semiring B] [Algebra R A] [Algebra R B] /-- The ideal of `A ⊗[R] B` generated by `I` is the image of `I ⊗[R] B` -/ lemma Ideal.map_includeLeft_eq (I : Ideal A) : (I.map (Algebra.TensorProduct.includeLeft : A →ₐ[R] A ⊗[R] B)).restrictScalars R = LinearMap.range (LinearMap.rTensor B (Submodule.subtype (I.restrictScalars R))) := by rw [← Submodule.carrier_inj] apply le_antisymm · intro x simp only [AddSubsemigroup.mem_carrier, AddSubmonoid.mem_toSubsemigroup, Submodule.mem_toAddSubmonoid, Submodule.restrictScalars_mem, LinearMap.mem_range] intro hx rw [Ideal.map, ← submodule_span_eq] at hx refine Submodule.span_induction hx ?_ ?_ ?_ ?_ · intro x simp only [includeLeft_apply, Set.mem_image, SetLike.mem_coe] rintro ⟨y, hy, rfl⟩ use ⟨y, hy⟩ ⊗ₜ[R] 1 rfl · use 0 simp only [map_zero] · rintro x y ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩ use x + y simp only [map_add] · rintro a x ⟨x, hx, rfl⟩ induction a with | zero => use 0 simp only [map_zero, smul_eq_mul, zero_mul] | tmul a b => induction x with | zero => use 0 simp only [map_zero, smul_eq_mul, mul_zero] | tmul x y => use (a • x) ⊗ₜ[R] (b * y) simp only [LinearMap.lTensor_tmul, Submodule.coeSubtype, smul_eq_mul, tmul_mul_tmul] with_unfolding_all rfl | add x y hx hy => obtain ⟨x', hx'⟩ := hx obtain ⟨y', hy'⟩ := hy use x' + y' simp only [map_add, hx', smul_add, hy'] | add a b ha hb => obtain ⟨x', ha'⟩ := ha obtain ⟨y', hb'⟩ := hb use x' + y' simp only [map_add, ha', add_smul, hb'] · rintro x ⟨y, rfl⟩ induction y with | zero => rw [map_zero] apply zero_mem | tmul a b => simp only [LinearMap.rTensor_tmul, Submodule.coeSubtype] suffices (a : A) ⊗ₜ[R] b = ((1 : A) ⊗ₜ[R] b) * ((a : A) ⊗ₜ[R] (1 : B)) by simp only [AddSubsemigroup.mem_carrier, AddSubmonoid.mem_toSubsemigroup, Submodule.mem_toAddSubmonoid, Submodule.restrictScalars_mem] rw [this] apply Ideal.mul_mem_left -- Note: adding `includeLeft` as a hint fixes a timeout #8386 apply Ideal.mem_map_of_mem includeLeft exact Submodule.coe_mem a simp only [Submodule.coe_restrictScalars, Algebra.TensorProduct.tmul_mul_tmul, mul_one, one_mul] | add x y hx hy => rw [map_add] apply Submodule.add_mem _ hx hy /-- The ideal of `A ⊗[R] B` generated by `I` is the image of `A ⊗[R] I` -/ lemma Ideal.map_includeRight_eq (I : Ideal B) : (I.map (Algebra.TensorProduct.includeRight : B →ₐ[R] A ⊗[R] B)).restrictScalars R = LinearMap.range (LinearMap.lTensor A (Submodule.subtype (I.restrictScalars R))) := by rw [← Submodule.carrier_inj] apply le_antisymm · intro x simp only [AddSubsemigroup.mem_carrier, AddSubmonoid.mem_toSubsemigroup, Submodule.mem_toAddSubmonoid, Submodule.restrictScalars_mem, LinearMap.mem_range] intro hx rw [Ideal.map, ← submodule_span_eq] at hx refine Submodule.span_induction hx ?_ ?_ ?_ ?_ · intro x simp only [includeRight_apply, Set.mem_image, SetLike.mem_coe] rintro ⟨y, hy, rfl⟩ use 1 ⊗ₜ[R] ⟨y, hy⟩ rfl · use 0 simp only [map_zero] · rintro x y ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩ use x + y simp only [map_add] · rintro a x ⟨x, hx, rfl⟩ induction a with | zero => use 0 simp only [map_zero, smul_eq_mul, zero_mul] | tmul a b => induction x with | zero => use 0 simp only [map_zero, smul_eq_mul, mul_zero] | tmul x y => use (a * x) ⊗ₜ[R] (b •y) simp only [LinearMap.lTensor_tmul, Submodule.coeSubtype, smul_eq_mul, tmul_mul_tmul] rfl | add x y hx hy => obtain ⟨x', hx'⟩ := hx obtain ⟨y', hy'⟩ := hy use x' + y' simp only [map_add, hx', smul_add, hy'] | add a b ha hb => obtain ⟨x', ha'⟩ := ha obtain ⟨y', hb'⟩ := hb use x' + y' simp only [map_add, ha', add_smul, hb'] · rintro x ⟨y, rfl⟩ induction y with | zero => rw [map_zero] apply zero_mem | tmul a b => simp only [LinearMap.lTensor_tmul, Submodule.coeSubtype] suffices a ⊗ₜ[R] (b : B) = (a ⊗ₜ[R] (1 : B)) * ((1 : A) ⊗ₜ[R] (b : B)) by rw [this] simp only [AddSubsemigroup.mem_carrier, AddSubmonoid.mem_toSubsemigroup, Submodule.mem_toAddSubmonoid, Submodule.restrictScalars_mem] apply Ideal.mul_mem_left -- Note: adding `includeRight` as a hint fixes a timeout #8386 apply Ideal.mem_map_of_mem includeRight exact Submodule.coe_mem b simp only [Submodule.coe_restrictScalars, Algebra.TensorProduct.tmul_mul_tmul, mul_one, one_mul] | add x y hx hy => rw [map_add] apply Submodule.add_mem _ hx hy -- Now, we can prove the right exactness properties of the tensor product, -- in its versions for algebras variable {R : Type*} [CommRing R] {A B C D : Type*} [Ring A] [Ring B] [Ring C] [Ring D] [Algebra R A] [Algebra R B] [Algebra R C] [Algebra R D] (f : A →ₐ[R] B) (g : C →ₐ[R] D) /-- If `g` is surjective, then the kernel of `(id A) ⊗ g` is generated by the kernel of `g` -/ lemma Algebra.TensorProduct.lTensor_ker (hg : Function.Surjective g) : RingHom.ker (map (AlgHom.id R A) g) = (RingHom.ker g).map (Algebra.TensorProduct.includeRight : C →ₐ[R] A ⊗[R] C) := by rw [← Submodule.restrictScalars_inj R] have : (RingHom.ker (map (AlgHom.id R A) g)).restrictScalars R = LinearMap.ker (LinearMap.lTensor A (AlgHom.toLinearMap g)) := rfl rw [this, Ideal.map_includeRight_eq] rw [(lTensor_exact A g.toLinearMap.exact_subtype_ker_map hg).linearMap_ker_eq] rfl /-- If `f` is surjective, then the kernel of `f ⊗ (id B)` is generated by the kernel of `f` -/ lemma Algebra.TensorProduct.rTensor_ker (hf : Function.Surjective f) : RingHom.ker (map f (AlgHom.id R C)) = (RingHom.ker f).map (Algebra.TensorProduct.includeLeft : A →ₐ[R] A ⊗[R] C) := by rw [← Submodule.restrictScalars_inj R] have : (RingHom.ker (map f (AlgHom.id R C))).restrictScalars R = LinearMap.ker (LinearMap.rTensor C (AlgHom.toLinearMap f)) := rfl rw [this, Ideal.map_includeLeft_eq] rw [(rTensor_exact C f.toLinearMap.exact_subtype_ker_map hf).linearMap_ker_eq] rfl /-- If `f` and `g` are surjective morphisms of algebras, then the kernel of `Algebra.TensorProduct.map f g` is generated by the kernels of `f` and `g` -/ theorem Algebra.TensorProduct.map_ker (hf : Function.Surjective f) (hg : Function.Surjective g) : RingHom.ker (map f g) = (RingHom.ker f).map (Algebra.TensorProduct.includeLeft : A →ₐ[R] A ⊗[R] C) ⊔ (RingHom.ker g).map (Algebra.TensorProduct.includeRight : C →ₐ[R] A ⊗[R] C) := by -- rewrite map f g as the composition of two maps have : map f g = (map f (AlgHom.id R D)).comp (map (AlgHom.id R A) g) := ext rfl rfl rw [this] -- this needs some rewriting to RingHom simp only [AlgHom.coe_ker, AlgHom.comp_toRingHom] rw [← RingHom.comap_ker] simp only [← AlgHom.coe_ker] -- apply one step of exactness rw [← Algebra.TensorProduct.lTensor_ker _ hg, RingHom.ker_eq_comap_bot (map (AlgHom.id R A) g)] rw [← Ideal.comap_map_of_surjective (map (AlgHom.id R A) g) (LinearMap.lTensor_surjective A hg)] -- apply the other step of exactness rw [Algebra.TensorProduct.rTensor_ker _ hf] apply congr_arg₂ _ rfl simp only [AlgHom.coe_ideal_map, Ideal.map_map] rw [← AlgHom.comp_toRingHom, Algebra.TensorProduct.map_comp_includeLeft] rfl end Algebras
LinearAlgebra\TensorProduct\Subalgebra.lean
/- Copyright (c) 2024 Jz Pan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jz Pan -/ import Mathlib.LinearAlgebra.TensorProduct.Submodule import Mathlib.RingTheory.TensorProduct.Basic import Mathlib.LinearAlgebra.FreeModule.StrongRankCondition /-! # Some results on tensor product of subalgebras ## Linear maps induced by multiplication for subalgebras Let `R` be a commutative ring, `S` be a commutative `R`-algebra. Let `A` and `B` be `R`-subalgebras in `S` (`Subalgebra R S`). We define some linear maps induced by the multiplication in `S`, which are mainly used in the definition of linearly disjointness. - `Subalgebra.mulMap`: the natural `R`-algebra homomorphism `A ⊗[R] B →ₐ[R] S` induced by the multiplication in `S`, whose image is `A ⊔ B` (`Subalgebra.mulMap_range`). - `Subalgebra.mulMap'`: the natural `R`-algebra homomorphism `A ⊗[R] B →ₗ[R] A ⊔ B` induced by multiplication in `S`, which is surjective (`Subalgebra.mulMap'_surjective`). - `Subalgebra.lTensorBot`, `Subalgebra.rTensorBot`: the natural isomorphism of `R`-algebras between `i(R) ⊗[R] A` and `A`, resp. `A ⊗[R] i(R)` and `A`, induced by multiplication in `S`, here `i : R → S` is the structure map. They generalize `Algebra.TensorProduct.lid` and `Algebra.TensorProduct.rid`, as `i(R)` is not necessarily isomorphic to `R`. They are `Subalgebra` versions of `Submodule.lTensorOne` and `Submodule.rTensorOne`. -/ open scoped TensorProduct open FiniteDimensional noncomputable section universe u v w namespace Subalgebra variable {R : Type u} {S : Type v} section Semiring variable [CommSemiring R] [Semiring S] [Algebra R S] variable (A : Subalgebra R S) /-- If `A` is a subalgebra of `S/R`, there is the natural `R`-algebra isomorphism between `i(R) ⊗[R] A` and `A` induced by multiplication in `S`, here `i : R → S` is the structure map. This generalizes `Algebra.TensorProduct.lid` as `i(R)` is not necessarily isomorphic to `R`. This is the `Subalgebra` version of `Submodule.lTensorOne` -/ def lTensorBot : (⊥ : Subalgebra R S) ⊗[R] A ≃ₐ[R] A := by refine Algebra.TensorProduct.algEquivOfLinearEquivTensorProduct (toSubmodule A).lTensorOne ?_ ?_ · rintro x y a b obtain ⟨x', hx⟩ := Algebra.mem_bot.1 x.2 replace hx : algebraMap R _ x' = x := Subtype.val_injective hx obtain ⟨y', hy⟩ := Algebra.mem_bot.1 y.2 replace hy : algebraMap R _ y' = y := Subtype.val_injective hy rw [← hx, ← hy, ← map_mul] erw [(toSubmodule A).lTensorOne_tmul x' a, (toSubmodule A).lTensorOne_tmul y' b, (toSubmodule A).lTensorOne_tmul (x' * y') (a * b)] rw [Algebra.mul_smul_comm, Algebra.smul_mul_assoc, smul_smul, mul_comm x' y'] · exact Submodule.lTensorOne_one_tmul _ variable {A} @[simp] theorem lTensorBot_tmul (x : R) (a : A) : A.lTensorBot (algebraMap R _ x ⊗ₜ[R] a) = x • a := (toSubmodule A).lTensorOne_tmul x a @[simp] theorem lTensorBot_one_tmul (a : A) : A.lTensorBot (1 ⊗ₜ[R] a) = a := (toSubmodule A).lTensorOne_one_tmul a @[simp] theorem lTensorBot_symm_apply (a : A) : A.lTensorBot.symm a = 1 ⊗ₜ[R] a := rfl variable (A) /-- If `A` is a subalgebra of `S/R`, there is the natural `R`-algebra isomorphism between `A ⊗[R] i(R)` and `A` induced by multiplication in `S`, here `i : R → S` is the structure map. This generalizes `Algebra.TensorProduct.rid` as `i(R)` is not necessarily isomorphic to `R`. This is the `Subalgebra` version of `Submodule.rTensorOne` -/ def rTensorBot : A ⊗[R] (⊥ : Subalgebra R S) ≃ₐ[R] A := by refine Algebra.TensorProduct.algEquivOfLinearEquivTensorProduct (toSubmodule A).rTensorOne ?_ ?_ · rintro a b x y obtain ⟨x', hx⟩ := Algebra.mem_bot.1 x.2 replace hx : algebraMap R _ x' = x := Subtype.val_injective hx obtain ⟨y', hy⟩ := Algebra.mem_bot.1 y.2 replace hy : algebraMap R _ y' = y := Subtype.val_injective hy rw [← hx, ← hy, ← map_mul] erw [(toSubmodule A).rTensorOne_tmul x' a, (toSubmodule A).rTensorOne_tmul y' b, (toSubmodule A).rTensorOne_tmul (x' * y') (a * b)] rw [Algebra.mul_smul_comm, Algebra.smul_mul_assoc, smul_smul, mul_comm x' y'] · exact Submodule.rTensorOne_tmul_one _ variable {A} @[simp] theorem rTensorBot_tmul (x : R) (a : A) : A.rTensorBot (a ⊗ₜ[R] algebraMap R _ x) = x • a := (toSubmodule A).rTensorOne_tmul x a @[simp] theorem rTensorBot_tmul_one (a : A) : A.rTensorBot (a ⊗ₜ[R] 1) = a := (toSubmodule A).rTensorOne_tmul_one a @[simp] theorem rTensorBot_symm_apply (a : A) : A.rTensorBot.symm a = a ⊗ₜ[R] 1 := rfl variable (A) @[simp] theorem comm_trans_lTensorBot : (Algebra.TensorProduct.comm R _ _).trans A.lTensorBot = A.rTensorBot := AlgEquiv.toLinearEquiv_injective (toSubmodule A).comm_trans_lTensorOne @[simp] theorem comm_trans_rTensorBot : (Algebra.TensorProduct.comm R _ _).trans A.rTensorBot = A.lTensorBot := AlgEquiv.toLinearEquiv_injective (toSubmodule A).comm_trans_rTensorOne end Semiring section CommSemiring variable [CommSemiring R] [CommSemiring S] [Algebra R S] variable (A B : Subalgebra R S) /-- If `A` and `B` are subalgebras in a commutative algebra `S` over `R`, there is the natural `R`-algebra homomorphism `A ⊗[R] B →ₐ[R] S` induced by multiplication in `S`. -/ def mulMap : A ⊗[R] B →ₐ[R] S := Algebra.TensorProduct.productMap A.val B.val @[simp] theorem mulMap_tmul (a : A) (b : B) : mulMap A B (a ⊗ₜ[R] b) = a.1 * b.1 := rfl theorem mulMap_toLinearMap : (A.mulMap B).toLinearMap = (toSubmodule A).mulMap (toSubmodule B) := rfl theorem mulMap_comm : mulMap B A = (mulMap A B).comp (Algebra.TensorProduct.comm R B A) := by ext <;> simp theorem mulMap_range : (A.mulMap B).range = A ⊔ B := by simp_rw [mulMap, Algebra.TensorProduct.productMap_range, Subalgebra.range_val] theorem mulMap_bot_left_eq : mulMap ⊥ A = A.val.comp A.lTensorBot.toAlgHom := AlgHom.toLinearMap_injective (toSubmodule A).mulMap_one_left_eq theorem mulMap_bot_right_eq : mulMap A ⊥ = A.val.comp A.rTensorBot.toAlgHom := AlgHom.toLinearMap_injective (toSubmodule A).mulMap_one_right_eq /-- If `A` and `B` are subalgebras in a commutative algebra `S` over `R`, there is the natural `R`-algebra homomorphism `A ⊗[R] B →ₐ[R] A ⊔ B` induced by multiplication in `S`, which is surjective (`Subalgebra.mulMap'_surjective`). -/ def mulMap' : A ⊗[R] B →ₐ[R] ↥(A ⊔ B) := (equivOfEq _ _ (mulMap_range A B)).toAlgHom.comp (mulMap A B).rangeRestrict variable {A B} in @[simp] theorem val_mulMap'_tmul (a : A) (b : B) : (mulMap' A B (a ⊗ₜ[R] b) : S) = a.1 * b.1 := rfl theorem mulMap'_surjective : Function.Surjective (mulMap' A B) := by simp_rw [mulMap', AlgEquiv.toAlgHom_eq_coe, AlgHom.coe_comp, AlgHom.coe_coe, EquivLike.comp_surjective, AlgHom.rangeRestrict_surjective] end CommSemiring section CommRing variable [CommRing R] [CommRing S] [Algebra R S] variable (A B : Subalgebra R S) /-- If `A` and `B` are subalgebras of a commutative `R`-algebra `S`, both of them are free `R`-algebras, then the rank of `A ⊔ B` is less than or equal to the product of that of `A` and `B`. -/ theorem rank_sup_le_of_free [Module.Free R A] [Module.Free R B] : Module.rank R ↥(A ⊔ B) ≤ Module.rank R A * Module.rank R B := by nontriviality R rw [← rank_tensorProduct', ← mulMap_range] exact rank_range_le (A.mulMap B).toLinearMap /-- If `A` and `B` are subalgebras of a commutative `R`-algebra `S`, both of them are free `R`-algebras, then the `FiniteDimensional.finrank` of `A ⊔ B` is less than or equal to the product of that of `A` and `B`. -/ theorem finrank_sup_le_of_free [Module.Free R A] [Module.Free R B] : finrank R ↥(A ⊔ B) ≤ finrank R A * finrank R B := by nontriviality R using finrank by_cases h : Module.Finite R A ∧ Module.Finite R B · obtain ⟨_, _⟩ := h rw [← finrank_tensorProduct, ← mulMap_range] exact (A.mulMap B).toLinearMap.finrank_range_le wlog hA : ¬ Module.Finite R A generalizing A B · have := this B A (fun h' ↦ h h'.symm) (not_and.1 h (of_not_not hA)) rwa [sup_comm, mul_comm] at this rw [← Module.rank_lt_alpeh0_iff, not_lt] at hA have := LinearMap.rank_le_of_injective _ <| Submodule.inclusion_injective <| show toSubmodule A ≤ toSubmodule (A ⊔ B) by simp rw [show finrank R A = 0 from Cardinal.toNat_apply_of_aleph0_le hA, show finrank R ↥(A ⊔ B) = 0 from Cardinal.toNat_apply_of_aleph0_le (hA.trans this), zero_mul] end CommRing end Subalgebra
LinearAlgebra\TensorProduct\Submodule.lean
/- Copyright (c) 2024 Jz Pan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jz Pan -/ import Mathlib.LinearAlgebra.DirectSum.Finsupp import Mathlib.Algebra.Algebra.Operations import Mathlib.Algebra.Algebra.Subalgebra.Basic /-! # Some results on tensor product of submodules ## Linear maps induced by multiplication for submodules Let `R` be a commutative ring, `S` be an `R`-algebra (not necessarily commutative). Let `M` and `N` be `R`-submodules in `S` (`Submodule R S`). We define some linear maps induced by the multiplication in `S` (see also `LinearMap.mul'`), which are mainly used in the definition of linearly disjointness (`Submodule.LinearDisjoint`). - `Submodule.mulMap`: the natural `R`-linear map `M ⊗[R] N →ₗ[R] S` induced by the multiplication in `S`, whose image is `M * N` (`Submodule.mulMap_range`). - `Submodule.mulMap'`: the natural map `M ⊗[R] N →ₗ[R] M * N` induced by multiplication in `S`, which is surjective (`Submodule.mulMap'_surjective`). - `Submodule.lTensorOne`, `Submodule.rTensorOne`: the natural isomorphism of `R`-modules between `i(R) ⊗[R] N` and `N`, resp. `M ⊗[R] i(R)` and `M`, induced by multiplication in `S`, here `i : R → S` is the structure map. They generalize `TensorProduct.lid` and `TensorProduct.rid`, as `i(R)` is not necessarily isomorphic to `R`. Note that we use `⊥ : Subalgebra R S` instead of `1 : Submodule R S`, since the map `R →ₗ[R] (1 : Submodule R S)` is not defined directly in mathlib yet. There are also `Submodule.mulLeftMap` and `Submodule.mulRightMap`, defined in earlier files. -/ open scoped TensorProduct noncomputable section universe u v w namespace Submodule variable {R : Type u} {S : Type v} section Semiring variable [CommSemiring R] [Semiring S] [Algebra R S] variable (M N : Submodule R S) -- can't use `LinearMap.mul' R S ∘ₗ TensorProduct.mapIncl M N` since it is not defeq to -- `Subalgebra.mulMap` which is `(Algebra.TensorProduct.productMap A.val B.val).toLinearMap` /-- If `M` and `N` are submodules in an algebra `S` over `R`, there is the natural `R`-linear map `M ⊗[R] N →ₗ[R] S` induced by multiplication in `S`. -/ def mulMap : M ⊗[R] N →ₗ[R] S := TensorProduct.lift ((LinearMap.mul R S).domRestrict₁₂ M N) @[simp] theorem mulMap_tmul (m : M) (n : N) : mulMap M N (m ⊗ₜ[R] n) = m.1 * n.1 := rfl theorem mulMap_op : mulMap (equivOpposite.symm (MulOpposite.op M)) (equivOpposite.symm (MulOpposite.op N)) = (MulOpposite.opLinearEquiv R).toLinearMap ∘ₗ mulMap N M ∘ₗ (TensorProduct.congr (LinearEquiv.ofSubmodule' (MulOpposite.opLinearEquiv R).symm M) (LinearEquiv.ofSubmodule' (MulOpposite.opLinearEquiv R).symm N) ≪≫ₗ TensorProduct.comm R M N).toLinearMap := TensorProduct.ext' fun _ _ ↦ rfl theorem mulMap_comm_of_commute (hc : ∀ (m : M) (n : N), Commute m.1 n.1) : mulMap N M = mulMap M N ∘ₗ TensorProduct.comm R N M := by refine TensorProduct.ext' fun n m ↦ ?_ simp_rw [LinearMap.comp_apply, LinearEquiv.coe_coe, TensorProduct.comm_tmul, mulMap_tmul] exact (hc m n).symm variable {M} in theorem mulMap_comp_rTensor {M' : Submodule R S} (hM : M' ≤ M) : mulMap M N ∘ₗ (inclusion hM).rTensor N = mulMap M' N := TensorProduct.ext' fun _ _ ↦ rfl variable {N} in theorem mulMap_comp_lTensor {N' : Submodule R S} (hN : N' ≤ N) : mulMap M N ∘ₗ (inclusion hN).lTensor M = mulMap M N' := TensorProduct.ext' fun _ _ ↦ rfl variable {M N} in theorem mulMap_comp_map_inclusion {M' N' : Submodule R S} (hM : M' ≤ M) (hN : N' ≤ N) : mulMap M N ∘ₗ TensorProduct.map (inclusion hM) (inclusion hN) = mulMap M' N' := TensorProduct.ext' fun _ _ ↦ rfl theorem mulMap_eq_mul'_comp_mapIncl : mulMap M N = .mul' R S ∘ₗ TensorProduct.mapIncl M N := TensorProduct.ext' fun _ _ ↦ rfl theorem mulMap_range : LinearMap.range (mulMap M N) = M * N := by refine le_antisymm ?_ (mul_le.2 fun m hm n hn ↦ ⟨⟨m, hm⟩ ⊗ₜ[R] ⟨n, hn⟩, rfl⟩) rintro _ ⟨x, rfl⟩ induction x with | zero => rw [_root_.map_zero]; exact zero_mem _ | tmul a b => exact mul_mem_mul a.2 b.2 | add a b ha hb => rw [_root_.map_add]; exact add_mem ha hb /-- If `M` and `N` are submodules in an algebra `S` over `R`, there is the natural `R`-linear map `M ⊗[R] N →ₗ[R] M * N` induced by multiplication in `S`, which is surjective (`Submodule.mulMap'_surjective`). -/ def mulMap' : M ⊗[R] N →ₗ[R] ↥(M * N) := (LinearEquiv.ofEq _ _ (mulMap_range M N)).toLinearMap ∘ₗ (mulMap M N).rangeRestrict variable {M N} in @[simp] theorem val_mulMap'_tmul (m : M) (n : N) : (mulMap' M N (m ⊗ₜ[R] n) : S) = m.1 * n.1 := rfl theorem mulMap'_surjective : Function.Surjective (mulMap' M N) := by simp_rw [mulMap', LinearMap.coe_comp, LinearEquiv.coe_coe, EquivLike.comp_surjective, LinearMap.surjective_rangeRestrict] /-- If `N` is a submodule in an algebra `S` over `R`, there is the natural `R`-linear map `i(R) ⊗[R] N →ₗ[R] N` induced by multiplication in `S`, here `i : R → S` is the structure map. This is promoted to an isomorphism of `R`-modules as `Submodule.lTensorOne`. Use that instead. -/ def lTensorOne' : (⊥ : Subalgebra R S) ⊗[R] N →ₗ[R] N := show (1 : Submodule R S) ⊗[R] N →ₗ[R] N from (LinearEquiv.ofEq _ _ (by rw [mulMap_range, one_mul])).toLinearMap ∘ₗ (mulMap _ N).rangeRestrict variable {N} in @[simp] theorem lTensorOne'_tmul (y : R) (n : N) : N.lTensorOne' (algebraMap R _ y ⊗ₜ[R] n) = y • n := Subtype.val_injective <| by simp_rw [lTensorOne', LinearMap.coe_comp, LinearEquiv.coe_coe, Function.comp_apply, LinearEquiv.coe_ofEq_apply, LinearMap.codRestrict_apply, SetLike.val_smul, Algebra.smul_def] exact mulMap_tmul 1 N _ _ variable {N} in @[simp] theorem lTensorOne'_one_tmul (n : N) : N.lTensorOne' (1 ⊗ₜ[R] n) = n := by simpa using lTensorOne'_tmul 1 n /-- If `N` is a submodule in an algebra `S` over `R`, there is the natural isomorphism of `R`-modules between `i(R) ⊗[R] N` and `N` induced by multiplication in `S`, here `i : R → S` is the structure map. This generalizes `TensorProduct.lid` as `i(R)` is not necessarily isomorphic to `R`. -/ def lTensorOne : (⊥ : Subalgebra R S) ⊗[R] N ≃ₗ[R] N := LinearEquiv.ofLinear N.lTensorOne' (TensorProduct.mk R (⊥ : Subalgebra R S) N 1) (by ext; simp) <| TensorProduct.ext' fun r n ↦ by change 1 ⊗ₜ[R] lTensorOne' N _ = r ⊗ₜ[R] n obtain ⟨x, h⟩ := Algebra.mem_bot.1 r.2 replace h : algebraMap R _ x = r := Subtype.val_injective h rw [← h, lTensorOne'_tmul, ← TensorProduct.smul_tmul, Algebra.smul_def, mul_one] variable {N} in @[simp] theorem lTensorOne_tmul (y : R) (n : N) : N.lTensorOne (algebraMap R _ y ⊗ₜ[R] n) = y • n := N.lTensorOne'_tmul y n variable {N} in @[simp] theorem lTensorOne_one_tmul (n : N) : N.lTensorOne (1 ⊗ₜ[R] n) = n := N.lTensorOne'_one_tmul n variable {N} in @[simp] theorem lTensorOne_symm_apply (n : N) : N.lTensorOne.symm n = 1 ⊗ₜ[R] n := rfl theorem mulMap_one_left_eq : mulMap 1 N = N.subtype ∘ₗ N.lTensorOne.toLinearMap := TensorProduct.ext' fun _ _ ↦ rfl /-- If `M` is a submodule in an algebra `S` over `R`, there is the natural `R`-linear map `M ⊗[R] i(R) →ₗ[R] M` induced by multiplication in `S`, here `i : R → S` is the structure map. This is promoted to an isomorphism of `R`-modules as `Submodule.rTensorOne`. Use that instead. -/ def rTensorOne' : M ⊗[R] (⊥ : Subalgebra R S) →ₗ[R] M := show M ⊗[R] (1 : Submodule R S) →ₗ[R] M from (LinearEquiv.ofEq _ _ (by rw [mulMap_range, mul_one])).toLinearMap ∘ₗ (mulMap M _).rangeRestrict variable {M} in @[simp] theorem rTensorOne'_tmul (y : R) (m : M) : M.rTensorOne' (m ⊗ₜ[R] algebraMap R _ y) = y • m := Subtype.val_injective <| by simp_rw [rTensorOne', LinearMap.coe_comp, LinearEquiv.coe_coe, Function.comp_apply, LinearEquiv.coe_ofEq_apply, LinearMap.codRestrict_apply, SetLike.val_smul] rw [Algebra.smul_def, Algebra.commutes] exact mulMap_tmul M 1 _ _ variable {M} in @[simp] theorem rTensorOne'_tmul_one (m : M) : M.rTensorOne' (m ⊗ₜ[R] 1) = m := by simpa using rTensorOne'_tmul 1 m /-- If `M` is a submodule in an algebra `S` over `R`, there is the natural isomorphism of `R`-modules between `M ⊗[R] i(R)` and `M` induced by multiplication in `S`, here `i : R → S` is the structure map. This generalizes `TensorProduct.rid` as `i(R)` is not necessarily isomorphic to `R`. -/ def rTensorOne : M ⊗[R] (⊥ : Subalgebra R S) ≃ₗ[R] M := LinearEquiv.ofLinear M.rTensorOne' ((TensorProduct.comm R _ _).toLinearMap ∘ₗ TensorProduct.mk R (⊥ : Subalgebra R S) M 1) (by ext; simp) <| TensorProduct.ext' fun n r ↦ by change rTensorOne' M _ ⊗ₜ[R] 1 = n ⊗ₜ[R] r obtain ⟨x, h⟩ := Algebra.mem_bot.1 r.2 replace h : algebraMap R _ x = r := Subtype.val_injective h rw [← h, rTensorOne'_tmul, TensorProduct.smul_tmul, Algebra.smul_def, mul_one] variable {M} in @[simp] theorem rTensorOne_tmul (y : R) (m : M) : M.rTensorOne (m ⊗ₜ[R] algebraMap R _ y) = y • m := M.rTensorOne'_tmul y m variable {M} in @[simp] theorem rTensorOne_tmul_one (m : M) : M.rTensorOne (m ⊗ₜ[R] 1) = m := M.rTensorOne'_tmul_one m variable {M} in @[simp] theorem rTensorOne_symm_apply (m : M) : M.rTensorOne.symm m = m ⊗ₜ[R] 1 := rfl theorem mulMap_one_right_eq : mulMap M 1 = M.subtype ∘ₗ M.rTensorOne.toLinearMap := TensorProduct.ext' fun _ _ ↦ rfl @[simp] theorem comm_trans_lTensorOne : (TensorProduct.comm R _ _).trans M.lTensorOne = M.rTensorOne := by refine LinearEquiv.toLinearMap_injective <| TensorProduct.ext' fun m r ↦ ?_ obtain ⟨x, h⟩ := Algebra.mem_bot.1 r.2 replace h : algebraMap R _ x = r := Subtype.val_injective h rw [← h]; simp @[simp] theorem comm_trans_rTensorOne : (TensorProduct.comm R _ _).trans M.rTensorOne = M.lTensorOne := by refine LinearEquiv.toLinearMap_injective <| TensorProduct.ext' fun r m ↦ ?_ obtain ⟨x, h⟩ := Algebra.mem_bot.1 r.2 replace h : algebraMap R _ x = r := Subtype.val_injective h rw [← h]; simp variable {M} in theorem mulLeftMap_eq_mulMap_comp {ι : Type*} [DecidableEq ι] (m : ι → M) : mulLeftMap N m = mulMap M N ∘ₗ LinearMap.rTensor N (Finsupp.total ι M R m) ∘ₗ (TensorProduct.finsuppScalarLeft R N ι).symm.toLinearMap := by ext; simp variable {N} in theorem mulRightMap_eq_mulMap_comp {ι : Type*} [DecidableEq ι] (n : ι → N) : mulRightMap M n = mulMap M N ∘ₗ LinearMap.lTensor M (Finsupp.total ι N R n) ∘ₗ (TensorProduct.finsuppScalarRight R M ι).symm.toLinearMap := by ext; simp end Semiring section CommSemiring variable [CommSemiring R] [CommSemiring S] [Algebra R S] variable (M N : Submodule R S) theorem mulMap_comm : mulMap N M = (mulMap M N).comp (TensorProduct.comm R N M).toLinearMap := mulMap_comm_of_commute M N fun _ _ ↦ mul_comm _ _ end CommSemiring end Submodule
LinearAlgebra\TensorProduct\Tower.lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin, Eric Wieser -/ import Mathlib.Algebra.Algebra.Tower import Mathlib.LinearAlgebra.TensorProduct.Basic /-! # The `A`-module structure on `M ⊗[R] N` When `M` is both an `R`-module and an `A`-module, and `Algebra R A`, then many of the morphisms preserve the actions by `A`. The `Module` instance itself is provided elsewhere as `TensorProduct.leftModule`. This file provides more general versions of the definitions already in `LinearAlgebra/TensorProduct`. In this file, we use the convention that `M`, `N`, `P`, `Q` are all `R`-modules, but only `M` and `P` are simultaneously `A`-modules. ## Main definitions * `TensorProduct.AlgebraTensorModule.curry` * `TensorProduct.AlgebraTensorModule.uncurry` * `TensorProduct.AlgebraTensorModule.lcurry` * `TensorProduct.AlgebraTensorModule.lift` * `TensorProduct.AlgebraTensorModule.lift.equiv` * `TensorProduct.AlgebraTensorModule.mk` * `TensorProduct.AlgebraTensorModule.map` * `TensorProduct.AlgebraTensorModule.mapBilinear` * `TensorProduct.AlgebraTensorModule.congr` * `TensorProduct.AlgebraTensorModule.rid` * `TensorProduct.AlgebraTensorModule.homTensorHomMap` * `TensorProduct.AlgebraTensorModule.assoc` * `TensorProduct.AlgebraTensorModule.leftComm` * `TensorProduct.AlgebraTensorModule.rightComm` * `TensorProduct.AlgebraTensorModule.tensorTensorTensorComm` ## Implementation notes We could thus consider replacing the less general definitions with these ones. If we do this, we probably should still implement the less general ones as abbreviations to the more general ones with fewer type arguments. -/ suppress_compilation namespace TensorProduct namespace AlgebraTensorModule universe uR uA uB uM uN uP uQ uP' uQ' variable {R : Type uR} {A : Type uA} {B : Type uB} variable {M : Type uM} {N : Type uN} {P : Type uP} {Q : Type uQ} {P' : Type uP'} {Q' : Type uQ'} open LinearMap open Algebra (lsmul) section Semiring variable [CommSemiring R] [Semiring A] [Semiring B] [Algebra R A] [Algebra R B] variable [AddCommMonoid M] [Module R M] [Module A M] variable [IsScalarTower R A M] variable [AddCommMonoid N] [Module R N] variable [AddCommMonoid P] [Module R P] [Module A P] variable [IsScalarTower R A P] variable [AddCommMonoid Q] [Module R Q] variable [AddCommMonoid P'] [Module R P'] [Module A P'] [Module B P'] variable [IsScalarTower R A P'] [IsScalarTower R B P'] [SMulCommClass A B P'] variable [AddCommMonoid Q'] [Module R Q'] theorem smul_eq_lsmul_rTensor (a : A) (x : M ⊗[R] N) : a • x = (lsmul R R M a).rTensor N x := rfl /-- Heterobasic version of `TensorProduct.curry`: Given a linear map `M ⊗[R] N →[A] P`, compose it with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` to form a bilinear map `M →[A] N →[R] P`. -/ @[simps] nonrec def curry (f : M ⊗[R] N →ₗ[A] P) : M →ₗ[A] N →ₗ[R] P := { curry (f.restrictScalars R) with toFun := curry (f.restrictScalars R) map_smul' := fun c x => LinearMap.ext fun y => f.map_smul c (x ⊗ₜ y) } theorem restrictScalars_curry (f : M ⊗[R] N →ₗ[A] P) : restrictScalars R (curry f) = TensorProduct.curry (f.restrictScalars R) := rfl /-- Just as `TensorProduct.ext` is marked `ext` instead of `TensorProduct.ext'`, this is a better `ext` lemma than `TensorProduct.AlgebraTensorModule.ext` below. See note [partially-applied ext lemmas]. -/ @[ext high] nonrec theorem curry_injective : Function.Injective (curry : (M ⊗ N →ₗ[A] P) → M →ₗ[A] N →ₗ[R] P) := fun _ _ h => LinearMap.restrictScalars_injective R <| curry_injective <| (congr_arg (LinearMap.restrictScalars R) h : _) theorem ext {g h : M ⊗[R] N →ₗ[A] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := curry_injective <| LinearMap.ext₂ H /-- Heterobasic version of `TensorProduct.lift`: Constructing a linear map `M ⊗[R] N →[A] P` given a bilinear map `M →[A] N →[R] P` with the property that its composition with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` is the given bilinear map `M →[A] N →[R] P`. -/ nonrec def lift (f : M →ₗ[A] N →ₗ[R] P) : M ⊗[R] N →ₗ[A] P := { lift (f.restrictScalars R) with map_smul' := fun c => show ∀ x : M ⊗[R] N, (lift (f.restrictScalars R)).comp (lsmul R R _ c) x = (lsmul R R _ c).comp (lift (f.restrictScalars R)) x from LinearMap.ext_iff.1 <| TensorProduct.ext' fun x y => by simp only [comp_apply, Algebra.lsmul_coe, smul_tmul', lift.tmul, coe_restrictScalars, f.map_smul, smul_apply] } -- Porting note: autogenerated lemma unfolded to `liftAux` @[simp] theorem lift_apply (f : M →ₗ[A] N →ₗ[R] P) (a : M ⊗[R] N) : AlgebraTensorModule.lift f a = TensorProduct.lift (LinearMap.restrictScalars R f) a := rfl @[simp] theorem lift_tmul (f : M →ₗ[A] N →ₗ[R] P) (x : M) (y : N) : lift f (x ⊗ₜ y) = f x y := rfl variable (R A B M N P Q) section variable [Module B P] [IsScalarTower R B P] [SMulCommClass A B P] /-- Heterobasic version of `TensorProduct.uncurry`: Linearly constructing a linear map `M ⊗[R] N →[A] P` given a bilinear map `M →[A] N →[R] P` with the property that its composition with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` is the given bilinear map `M →[A] N →[R] P`. -/ @[simps] def uncurry : (M →ₗ[A] N →ₗ[R] P) →ₗ[B] M ⊗[R] N →ₗ[A] P where toFun := lift map_add' _ _ := ext fun x y => by simp only [lift_tmul, add_apply] map_smul' _ _ := ext fun x y => by simp only [lift_tmul, smul_apply, RingHom.id_apply] /-- Heterobasic version of `TensorProduct.lcurry`: Given a linear map `M ⊗[R] N →[A] P`, compose it with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` to form a bilinear map `M →[A] N →[R] P`. -/ @[simps] def lcurry : (M ⊗[R] N →ₗ[A] P) →ₗ[B] M →ₗ[A] N →ₗ[R] P where toFun := curry map_add' _ _ := rfl map_smul' _ _ := rfl /-- Heterobasic version of `TensorProduct.lift.equiv`: A linear equivalence constructing a linear map `M ⊗[R] N →[A] P` given a bilinear map `M →[A] N →[R] P` with the property that its composition with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` is the given bilinear map `M →[A] N →[R] P`. -/ def lift.equiv : (M →ₗ[A] N →ₗ[R] P) ≃ₗ[B] M ⊗[R] N →ₗ[A] P := LinearEquiv.ofLinear (uncurry R A B M N P) (lcurry R A B M N P) (LinearMap.ext fun _ => ext fun x y => lift_tmul _ x y) (LinearMap.ext fun f => LinearMap.ext fun x => LinearMap.ext fun y => lift_tmul f x y) /-- Heterobasic version of `TensorProduct.mk`: The canonical bilinear map `M →[A] N →[R] M ⊗[R] N`. -/ @[simps! apply] nonrec def mk : M →ₗ[A] N →ₗ[R] M ⊗[R] N := { mk R M N with map_smul' := fun _ _ => rfl } variable {R A B M N P Q} /-- Heterobasic version of `TensorProduct.map` -/ def map (f : M →ₗ[A] P) (g : N →ₗ[R] Q) : M ⊗[R] N →ₗ[A] P ⊗[R] Q := lift <| { toFun := fun h => h ∘ₗ g, map_add' := fun h₁ h₂ => LinearMap.add_comp g h₂ h₁, map_smul' := fun c h => LinearMap.smul_comp c h g } ∘ₗ mk R A P Q ∘ₗ f @[simp] theorem map_tmul (f : M →ₗ[A] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl @[simp] theorem map_id : map (id : M →ₗ[A] M) (id : N →ₗ[R] N) = .id := ext fun _ _ => rfl theorem map_comp (f₂ : P →ₗ[A] P') (f₁ : M →ₗ[A] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) : map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) := ext fun _ _ => rfl @[simp] protected theorem map_one : map (1 : M →ₗ[A] M) (1 : N →ₗ[R] N) = 1 := map_id protected theorem map_mul (f₁ f₂ : M →ₗ[A] M) (g₁ g₂ : N →ₗ[R] N) : map (f₁ * f₂) (g₁ * g₂) = map f₁ g₁ * map f₂ g₂ := map_comp _ _ _ _ theorem map_add_left (f₁ f₂ : M →ₗ[A] P) (g : N →ₗ[R] Q) : map (f₁ + f₂) g = map f₁ g + map f₂ g := by ext simp_rw [curry_apply, TensorProduct.curry_apply, restrictScalars_apply, add_apply, map_tmul, add_apply, add_tmul] theorem map_add_right (f : M →ₗ[A] P) (g₁ g₂ : N →ₗ[R] Q) : map f (g₁ + g₂) = map f g₁ + map f g₂ := by ext simp_rw [curry_apply, TensorProduct.curry_apply, restrictScalars_apply, add_apply, map_tmul, add_apply, tmul_add] theorem map_smul_right (r : R) (f : M →ₗ[A] P) (g : N →ₗ[R] Q) : map f (r • g) = r • map f g := by ext simp_rw [curry_apply, TensorProduct.curry_apply, restrictScalars_apply, smul_apply, map_tmul, smul_apply, tmul_smul] theorem map_smul_left (b : B) (f : M →ₗ[A] P) (g : N →ₗ[R] Q) : map (b • f) g = b • map f g := by ext simp_rw [curry_apply, TensorProduct.curry_apply, restrictScalars_apply, smul_apply, map_tmul, smul_apply, smul_tmul'] variable (R A B M N P Q) /-- Heterobasic version of `TensorProduct.map_bilinear` -/ def mapBilinear : (M →ₗ[A] P) →ₗ[B] (N →ₗ[R] Q) →ₗ[R] (M ⊗[R] N →ₗ[A] P ⊗[R] Q) := LinearMap.mk₂' _ _ map map_add_left map_smul_left map_add_right map_smul_right variable {R A B M N P Q} @[simp] theorem mapBilinear_apply (f : M →ₗ[A] P) (g : N →ₗ[R] Q) : mapBilinear R A B M N P Q f g = map f g := rfl variable (R A B M N P Q) /-- Heterobasic version of `TensorProduct.homTensorHomMap` -/ def homTensorHomMap : ((M →ₗ[A] P) ⊗[R] (N →ₗ[R] Q)) →ₗ[B] (M ⊗[R] N →ₗ[A] P ⊗[R] Q) := lift <| mapBilinear R A B M N P Q variable {R A B M N P Q} @[simp] theorem homTensorHomMap_apply (f : M →ₗ[A] P) (g : N →ₗ[R] Q) : homTensorHomMap R A B M N P Q (f ⊗ₜ g) = map f g := rfl /-- Heterobasic version of `TensorProduct.congr` -/ def congr (f : M ≃ₗ[A] P) (g : N ≃ₗ[R] Q) : (M ⊗[R] N) ≃ₗ[A] (P ⊗[R] Q) := LinearEquiv.ofLinear (map f g) (map f.symm g.symm) (ext fun _m _n => congr_arg₂ (· ⊗ₜ ·) (f.apply_symm_apply _) (g.apply_symm_apply _)) (ext fun _m _n => congr_arg₂ (· ⊗ₜ ·) (f.symm_apply_apply _) (g.symm_apply_apply _)) @[simp] theorem congr_refl : congr (.refl A M) (.refl R N) = .refl A _ := LinearEquiv.toLinearMap_injective <| map_id theorem congr_trans (f₁ : M ≃ₗ[A] P) (f₂ : P ≃ₗ[A] P') (g₁ : N ≃ₗ[R] Q) (g₂ : Q ≃ₗ[R] Q') : congr (f₁.trans f₂) (g₁.trans g₂) = (congr f₁ g₁).trans (congr f₂ g₂) := LinearEquiv.toLinearMap_injective <| map_comp _ _ _ _ theorem congr_symm (f : M ≃ₗ[A] P) (g : N ≃ₗ[R] Q) : congr f.symm g.symm = (congr f g).symm := rfl @[simp] theorem congr_one : congr (1 : M ≃ₗ[A] M) (1 : N ≃ₗ[R] N) = 1 := congr_refl theorem congr_mul (f₁ f₂ : M ≃ₗ[A] M) (g₁ g₂ : N ≃ₗ[R] N) : congr (f₁ * f₂) (g₁ * g₂) = congr f₁ g₁ * congr f₂ g₂ := congr_trans _ _ _ _ @[simp] theorem congr_tmul (f : M ≃ₗ[A] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl @[simp] theorem congr_symm_tmul (f : M ≃ₗ[A] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) : (congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q := rfl variable (R A M) /-- Heterobasic version of `TensorProduct.rid`. -/ protected def rid : M ⊗[R] R ≃ₗ[A] M := LinearEquiv.ofLinear (lift <| Algebra.lsmul _ _ _ |>.toLinearMap |>.flip) (mk R A M R |>.flip 1) (LinearMap.ext <| one_smul _) (ext fun _ _ => smul_tmul _ _ _ |>.trans <| congr_arg _ <| mul_one _) theorem rid_eq_rid : AlgebraTensorModule.rid R R M = TensorProduct.rid R M := LinearEquiv.toLinearMap_injective <| TensorProduct.ext' fun _ _ => rfl variable {R M} in @[simp] theorem rid_tmul (r : R) (m : M) : AlgebraTensorModule.rid R A M (m ⊗ₜ r) = r • m := rfl variable {M} in @[simp] theorem rid_symm_apply (m : M) : (AlgebraTensorModule.rid R A M).symm m = m ⊗ₜ 1 := rfl end end Semiring section CommSemiring variable [CommSemiring R] [CommSemiring A] [Semiring B] [Algebra R A] [Algebra R B] variable [AddCommMonoid M] [Module R M] [Module A M] [Module B M] variable [IsScalarTower R A M] [IsScalarTower R B M] [SMulCommClass A B M] variable [AddCommMonoid N] [Module R N] variable [AddCommMonoid P] [Module A P] variable [AddCommMonoid Q] [Module R Q] variable (R A B M N P Q) attribute [local ext high] TensorProduct.ext section assoc variable [Module R P] [IsScalarTower R A P] variable [Algebra A B] [IsScalarTower A B M] /-- Heterobasic version of `TensorProduct.assoc`: `B`-linear equivalence between `(M ⊗[A] P) ⊗[R] Q` and `M ⊗[A] (P ⊗[R] Q)`. Note this is especially useful with `A = R` (where it is a "more linear" version of `TensorProduct.assoc`), or with `B = A`. -/ def assoc : (M ⊗[A] P) ⊗[R] Q ≃ₗ[B] M ⊗[A] (P ⊗[R] Q) := LinearEquiv.ofLinear (lift <| lift <| lcurry R A B P Q _ ∘ₗ mk A B M (P ⊗[R] Q)) (lift <| uncurry R A B P Q _ ∘ₗ curry (mk R B _ Q)) (by ext; rfl) (by ext; rfl) variable {M P N Q} @[simp] theorem assoc_tmul (m : M) (p : P) (q : Q) : assoc R A B M P Q ((m ⊗ₜ p) ⊗ₜ q) = m ⊗ₜ (p ⊗ₜ q) := rfl @[simp] theorem assoc_symm_tmul (m : M) (p : P) (q : Q) : (assoc R A B M P Q).symm (m ⊗ₜ (p ⊗ₜ q)) = (m ⊗ₜ p) ⊗ₜ q := rfl end assoc section cancelBaseChange variable [Algebra A B] [IsScalarTower A B M] /-- `B`-linear equivalence between `M ⊗[A] (A ⊗[R] N)` and `M ⊗[R] N`. In particular useful with `B = A`. -/ def cancelBaseChange : M ⊗[A] (A ⊗[R] N) ≃ₗ[B] M ⊗[R] N := by letI g : (M ⊗[A] A) ⊗[R] N ≃ₗ[B] M ⊗[R] N := AlgebraTensorModule.congr (AlgebraTensorModule.rid A B M) (LinearEquiv.refl R N) exact (AlgebraTensorModule.assoc R A B M A N).symm ≪≫ₗ g variable {M P N Q} @[simp] theorem cancelBaseChange_tmul (m : M) (n : N) (a : A) : cancelBaseChange R A B M N (m ⊗ₜ (a ⊗ₜ n)) = (a • m) ⊗ₜ n := rfl @[simp] theorem cancelBaseChange_symm_tmul (m : M) (n : N) : (cancelBaseChange R A B M N).symm (m ⊗ₜ n) = m ⊗ₜ (1 ⊗ₜ n) := rfl end cancelBaseChange section leftComm variable [Module R P] [IsScalarTower R A P] /-- Heterobasic version of `TensorProduct.leftComm` -/ def leftComm : M ⊗[A] (P ⊗[R] Q) ≃ₗ[A] P ⊗[A] (M ⊗[R] Q) := let e₁ := (assoc R A A M P Q).symm let e₂ := congr (TensorProduct.comm A M P) (1 : Q ≃ₗ[R] Q) let e₃ := assoc R A A P M Q e₁ ≪≫ₗ e₂ ≪≫ₗ e₃ variable {M N P Q} @[simp] theorem leftComm_tmul (m : M) (p : P) (q : Q) : leftComm R A M P Q (m ⊗ₜ (p ⊗ₜ q)) = p ⊗ₜ (m ⊗ₜ q) := rfl @[simp] theorem leftComm_symm_tmul (m : M) (p : P) (q : Q) : (leftComm R A M P Q).symm (p ⊗ₜ (m ⊗ₜ q)) = m ⊗ₜ (p ⊗ₜ q) := rfl end leftComm section rightComm /-- A tensor product analogue of `mul_right_comm`. -/ def rightComm : (M ⊗[A] P) ⊗[R] Q ≃ₗ[A] (M ⊗[R] Q) ⊗[A] P := LinearEquiv.ofLinear (lift <| TensorProduct.lift <| LinearMap.flip <| lcurry R A A M Q ((M ⊗[R] Q) ⊗[A] P) ∘ₗ (mk A A (M ⊗[R] Q) P).flip) (TensorProduct.lift <| lift <| LinearMap.flip <| (TensorProduct.lcurry A M P ((M ⊗[A] P) ⊗[R] Q)).restrictScalars R ∘ₗ (mk R A (M ⊗[A] P) Q).flip) -- explicit `Eq.refl`s here help with performance, but also make it clear that the `ext` are -- letting us prove the result as an equality of pure tensors. (TensorProduct.ext <| ext fun m q => LinearMap.ext fun p => Eq.refl <| (m ⊗ₜ[R] q) ⊗ₜ[A] p) (curry_injective <| TensorProduct.ext' fun m p => LinearMap.ext fun q => Eq.refl <| (m ⊗ₜ[A] p) ⊗ₜ[R] q) variable {M N P Q} @[simp] theorem rightComm_tmul (m : M) (p : P) (q : Q) : rightComm R A M P Q ((m ⊗ₜ p) ⊗ₜ q) = (m ⊗ₜ q) ⊗ₜ p := rfl @[simp] theorem rightComm_symm_tmul (m : M) (p : P) (q : Q) : (rightComm R A M P Q).symm ((m ⊗ₜ q) ⊗ₜ p) = (m ⊗ₜ p) ⊗ₜ q := rfl end rightComm section tensorTensorTensorComm variable [Module R P] [IsScalarTower R A P] /-- Heterobasic version of `tensorTensorTensorComm`. -/ def tensorTensorTensorComm : (M ⊗[R] N) ⊗[A] (P ⊗[R] Q) ≃ₗ[A] (M ⊗[A] P) ⊗[R] (N ⊗[R] Q) := (assoc R A A (M ⊗[R] N) P Q).symm ≪≫ₗ congr (rightComm R A M P N).symm (1 : Q ≃ₗ[R] Q) ≪≫ₗ assoc R _ _ (M ⊗[A] P) N Q variable {M N P Q} @[simp] theorem tensorTensorTensorComm_tmul (m : M) (n : N) (p : P) (q : Q) : tensorTensorTensorComm R A M N P Q ((m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q)) = (m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q) := rfl @[simp] theorem tensorTensorTensorComm_symm_tmul (m : M) (n : N) (p : P) (q : Q) : (tensorTensorTensorComm R A M N P Q).symm ((m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q)) = (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) := rfl end tensorTensorTensorComm end CommSemiring end AlgebraTensorModule end TensorProduct namespace Submodule open TensorProduct variable {R M : Type*} (A : Type*) [CommSemiring R] [Semiring A] [Algebra R A] [AddCommMonoid M] [Module R M] (p : Submodule R M) /-- If `A` is an `R`-algebra, any `R`-submodule `p` of an `R`-module `M` may be pushed forward to an `A`-submodule of `A ⊗ M`. This "base change" operation is also known as "extension of scalars". -/ def baseChange : Submodule A (A ⊗[R] M) := span A <| p.map (TensorProduct.mk R A M 1) @[simp] lemma baseChange_bot : (⊥ : Submodule R M).baseChange A = ⊥ := by simp [baseChange] @[simp] lemma baseChange_top : (⊤ : Submodule R M).baseChange A = ⊤ := by rw [baseChange, map_top, eq_top_iff'] intro x refine x.induction_on (by simp) (fun a y ↦ ?_) (fun _ _ ↦ Submodule.add_mem _) rw [← mul_one a, ← smul_eq_mul, ← smul_tmul'] refine smul_mem _ _ (subset_span ?_) simp variable {A p} in lemma tmul_mem_baseChange_of_mem (a : A) {m : M} (hm : m ∈ p) : a ⊗ₜ[R] m ∈ p.baseChange A := by rw [← mul_one a, ← smul_eq_mul, ← smul_tmul'] exact smul_mem (baseChange A p) a (subset_span ⟨m, hm, rfl⟩) @[simp] lemma baseChange_span (s : Set M) : (span R s).baseChange A = span A (TensorProduct.mk R A M 1 '' s) := by simp only [baseChange, map_coe] refine le_antisymm (span_le.mpr ?_) (span_mono <| Set.image_subset _ subset_span) rintro - ⟨m : M, hm : m ∈ span R s, rfl⟩ apply span_induction (p := fun m' ↦ (1 : A) ⊗ₜ[R] m' ∈ span A (TensorProduct.mk R A M 1 '' s)) hm · intro m hm exact subset_span ⟨m, hm, rfl⟩ · simp · intro m₁ m₂ hm₁ hm₂ rw [tmul_add] exact Submodule.add_mem _ hm₁ hm₂ · intro r m' hm' rw [tmul_smul, ← one_smul A ((1 : A) ⊗ₜ[R] m'), ← smul_assoc] exact smul_mem _ (r • 1) hm' end Submodule
LinearAlgebra\TensorProduct\Vanishing.lean
/- Copyright (c) 2024 Mitchell Lee. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Lee -/ import Mathlib.LinearAlgebra.TensorProduct.RightExactness import Mathlib.LinearAlgebra.TensorProduct.Finiteness /-! # Vanishing of elements in a tensor product of two modules Let $M$ and $N$ be modules over a commutative ring $R$. Recall that every element of $M \otimes N$ can be written as a finite sum $\sum_{i} m_i \otimes n_i$ of pure tensors (`TensorProduct.exists_finset`). We would like to determine under what circumstances such an expression vanishes. Let us say that an expression $\sum_{i \in \iota} m_i \otimes n_i$ in $M \otimes N$ *vanishes trivially* (`TensorProduct.VanishesTrivially`) if there exist a finite index type $\kappa$, elements $(y_j)_{j \in \kappa}$ of $N$, and elements $(a_{ij})_{i \in \iota, j \in \kappa}$ of $R$ such that for all $i$, $$n_i = \sum_j a_{ij} y_j$$ and for all $j$, $$\sum_{i} a_{ij} m_i = 0.$$ (The terminology "trivial" comes from [Stacks 00HK](https://stacks.math.columbia.edu/tag/00HK).) It is not difficult to show (`TensorProduct.sum_tmul_eq_zero_of_vanishesTrivially`) that if $\sum_i m_i \otimes n_i$ vanishes trivially, then it vanishes; that is, $\sum_i m_i \otimes n_i = 0$. The *equational criterion for vanishing* (`TensorProduct.vanishesTrivially_iff_sum_tmul_eq_zero`), which appears as [A. Altman and S. Kleiman, *A term of commutative algebra* (Lemma 8.16)][altman2021term], states that if the elements $m_i$ generate the module $M$, then $\sum_i m_i \otimes n_i = 0$ if and only if the expression $\sum_i m_i \otimes n_i$ vanishes trivially. We also prove the following generalization (`TensorProduct.vanishesTrivially_iff_sum_tmul_eq_zero_of_rTensor_injective`). If the submodule $M' \subseteq M$ generated by the $m_i$ satisfies the property that the induced map $M' \otimes N \to M \otimes N$ is injective, then $\sum_i m_i \otimes n_i = 0$ if and only if the expression $\sum_i m_i \otimes n_i$ vanishes trivially. (In the case that $M = R$, this yields the *equational criterion for flatness* `Module.Flat.iff_forall_isTrivialRelation`.) Conversely (`TensorProduct.rTensor_injective_of_forall_vanishesTrivially`), suppose that for every equation $\sum_i m_i \otimes n_i = 0$, the expression $\sum_i m_i \otimes n_i$ vanishes trivially. Then the induced map $M' \otimes N \to M \otimes N$ is injective for every submodule $M' \subseteq M$. ## References * [A. Altman and S. Kleiman, *A term of commutative algebra* (Lemma 8.16)][altman2021term] ## TODO * Prove the same theorems with $M$ and $N$ swapped. * Prove the same theorems with universe polymorphism. -/ universe u variable (R : Type u) [CommRing R] variable {M : Type u} [AddCommGroup M] [Module R M] variable {N : Type u} [AddCommGroup N] [Module R N] open DirectSum LinearMap Function Submodule namespace TensorProduct variable {ι : Type u} [Fintype ι] {m : ι → M} {n : ι → N} variable (m n) in /-- An expression $\sum_i m_i \otimes n_i$ in $M \otimes N$ *vanishes trivially* if there exist a finite index type $\kappa$, elements $(y_j)_{j \in \kappa}$ of $N$, and elements $(a_{ij})_{i \in \iota, j \in \kappa}$ of $R$ such that for all $i$, $$n_i = \sum_j a_{ij} y_j$$ and for all $j$, $$\sum_{i} a_{ij} m_i = 0.$$ Note that this condition is not symmetric in $M$ and $N$. (The terminology "trivial" comes from [Stacks 00HK](https://stacks.math.columbia.edu/tag/00HK).)-/ abbrev VanishesTrivially : Prop := ∃ (κ : Type u) (_ : Fintype κ) (a : ι → κ → R) (y : κ → N), (∀ i, n i = ∑ j, a i j • y j) ∧ ∀ j, ∑ i, a i j • m i = 0 /-- **Equational criterion for vanishing** [A. Altman and S. Kleiman, *A term of commutative algebra* (Lemma 8.16)][altman2021term], backward direction. If the expression $\sum_i m_i \otimes n_i$ vanishes trivially, then it vanishes. That is, $\sum_i m_i \otimes n_i = 0$. -/ theorem sum_tmul_eq_zero_of_vanishesTrivially (hmn : VanishesTrivially R m n) : ∑ i, m i ⊗ₜ n i = (0 : M ⊗[R] N) := by obtain ⟨κ, _, a, y, h₁, h₂⟩ := hmn simp_rw [h₁, tmul_sum, tmul_smul] rw [Finset.sum_comm] simp_rw [← tmul_smul, ← smul_tmul, ← sum_tmul, h₂, zero_tmul, Finset.sum_const_zero] /-- **Equational criterion for vanishing** [A. Altman and S. Kleiman, *A term of commutative algebra* (Lemma 8.16)][altman2021term], forward direction. Assume that the $m_i$ generate $M$. If the expression $\sum_i m_i \otimes n_i$ vanishes, then it vanishes trivially. -/ theorem vanishesTrivially_of_sum_tmul_eq_zero (hm : Submodule.span R (Set.range m) = ⊤) (hmn : ∑ i, m i ⊗ₜ n i = (0 : M ⊗[R] N)) : VanishesTrivially R m n := by -- Define a map $G \colon R^\iota \to M$ whose matrix entries are the $m_i$. It is surjective. set G : (ι →₀ R) →ₗ[R] M := Finsupp.total ι M R m with hG have G_basis_eq (i : ι) : G (Finsupp.single i 1) = m i := by simp [hG, toModule_lof] have G_surjective : Surjective G := by apply LinearMap.range_eq_top.mp apply top_le_iff.mp rw [← hm] apply Submodule.span_le.mpr rintro _ ⟨i, rfl⟩ use Finsupp.single i 1, G_basis_eq i /- Consider the element $\sum_i e_i \otimes n_i$ of $R^\iota \otimes N$. It is in the kernel of $R^\iota \otimes N \to M \otimes N$. -/ set en : (ι →₀ R) ⊗[R] N := ∑ i, Finsupp.single i 1 ⊗ₜ n i with hen have en_mem_ker : en ∈ ker (rTensor N G) := by simp [hen, G_basis_eq, hmn] -- We have an exact sequence $\ker G \to R^\iota \to M \to 0$. have exact_ker_subtype : Exact (ker G).subtype G := G.exact_subtype_ker_map -- Tensor the exact sequence with $N$. have exact_rTensor_ker_subtype : Exact (rTensor N (ker G).subtype) (rTensor N G) := rTensor_exact (M := ↥(ker G)) N exact_ker_subtype G_surjective /- We conclude that $\sum_i e_i \otimes n_i$ is in the range of $\ker G \otimes N \to R^\iota \otimes N$. -/ have en_mem_range : en ∈ range (rTensor N (ker G).subtype) := exact_rTensor_ker_subtype.linearMap_ker_eq ▸ en_mem_ker /- There is an element of in $\ker G \otimes N$ that maps to $\sum_i e_i \otimes n_i$. Write it as a finite sum of pure tensors. -/ obtain ⟨kn, hkn⟩ := en_mem_range obtain ⟨ma, rfl : kn = ∑ kj ∈ ma, kj.1 ⊗ₜ[R] kj.2⟩ := exists_finset kn use ↑↑ma, FinsetCoe.fintype ma /- Let $\sum_j k_j \otimes y_j$ be the sum obtained in the previous step. In order to show that $\sum_i m_i \otimes n_i$ vanishes trivially, it suffices to prove that there exist $(a_{ij})_{i, j}$ such that for all $i$, $$n_i = \sum_j a_{ij} y_j$$ and for all $j$, $$\sum_{i} a_{ij} m_i = 0.$$ For this, take $a_{ij}$ to be the coefficient of $e_i$ in $k_j$. -/ use fun i ⟨⟨kj, _⟩, _⟩ ↦ (kj : ι →₀ R) i use fun ⟨⟨_, yj⟩, _⟩ ↦ yj constructor · intro i classical apply_fun finsuppScalarLeft R N ι at hkn apply_fun (· i) at hkn symm at hkn simp only [map_sum, finsuppScalarLeft_apply_tmul, zero_smul, Finsupp.single_zero, Finsupp.sum_single_index, one_smul, Finsupp.finset_sum_apply, Finsupp.single_apply, Finset.sum_ite_eq', Finset.mem_univ, ↓reduceIte, rTensor_tmul, coeSubtype, Finsupp.sum_apply, Finsupp.sum_ite_eq', Finsupp.mem_support_iff, ne_eq, ite_not, en] at hkn simp only [Finset.univ_eq_attach, Finset.sum_attach ma (fun x ↦ (x.1 : ι →₀ R) i • x.2)] convert hkn using 2 with x _ split · next h'x => rw [h'x, zero_smul] · rfl · rintro ⟨⟨⟨k, hk⟩, _⟩, _⟩ simpa only [hG, Finsupp.total_apply, zero_smul, implies_true, Finsupp.sum_fintype] using mem_ker.mp hk /-- **Equational criterion for vanishing** [A. Altman and S. Kleiman, *A term of commutative algebra* (Lemma 8.16)][altman2021term]. Assume that the $m_i$ generate $M$. Then the expression $\sum_i m_i \otimes n_i$ vanishes trivially if and only if it vanishes. -/ theorem vanishesTrivially_iff_sum_tmul_eq_zero (hm : Submodule.span R (Set.range m) = ⊤) : VanishesTrivially R m n ↔ ∑ i, m i ⊗ₜ n i = (0 : M ⊗[R] N) := ⟨sum_tmul_eq_zero_of_vanishesTrivially R, vanishesTrivially_of_sum_tmul_eq_zero R hm⟩ /-- **Equational criterion for vanishing** [A. Altman and S. Kleiman, *A term of commutative algebra* (Lemma 8.16)][altman2021term], forward direction, generalization. Assume that the submodule $M' \subseteq M$ generated by the $m_i$ satisfies the property that the map $M' \otimes N \to M \otimes N$ is injective. If the expression $\sum_i m_i \otimes n_i$ vanishes, then it vanishes trivially. -/ theorem vanishesTrivially_of_sum_tmul_eq_zero_of_rTensor_injective (hm : Injective (rTensor N (span R (Set.range m)).subtype)) (hmn : ∑ i, m i ⊗ₜ n i = (0 : M ⊗[R] N)) : VanishesTrivially R m n := by -- Restrict `m` on the codomain to $M'$, then apply `vanishesTrivially_of_sum_tmul_eq_zero`. have mem_M' i : m i ∈ span R (Set.range m) := subset_span ⟨i, rfl⟩ set m' : ι → span R (Set.range m) := Subtype.coind m mem_M' with m'_eq have hm' : span R (Set.range m') = ⊤ := by apply map_injective_of_injective (injective_subtype (span R (Set.range m))) rw [Submodule.map_span, Submodule.map_top, range_subtype, coeSubtype, ← Set.range_comp] rfl have hm'n : ∑ i, m' i ⊗ₜ n i = (0 : span R (Set.range m) ⊗[R] N) := by apply hm simp only [m'_eq, map_sum, rTensor_tmul, coeSubtype, Subtype.coind_coe, _root_.map_zero, hmn] have : VanishesTrivially R m' n := vanishesTrivially_of_sum_tmul_eq_zero R hm' hm'n unfold VanishesTrivially at this ⊢ convert this with κ _ a y j convert (injective_iff_map_eq_zero' _).mp (injective_subtype (span R (Set.range m))) _ simp [m'_eq] /-- **Equational criterion for vanishing** [A. Altman and S. Kleiman, *A term of commutative algebra* (Lemma 8.16)][altman2021term], generalization. Assume that the submodule $M' \subseteq M$ generated by the $m_i$ satisfies the property that the map $M' \otimes N \to M \otimes N$ is injective. Then the expression $\sum_i m_i \otimes n_i$ vanishes trivially if and only if it vanishes. -/ theorem vanishesTrivially_iff_sum_tmul_eq_zero_of_rTensor_injective (hm : Injective (rTensor N (span R (Set.range m)).subtype)) : VanishesTrivially R m n ↔ ∑ i, m i ⊗ₜ n i = (0 : M ⊗[R] N) := ⟨sum_tmul_eq_zero_of_vanishesTrivially R, vanishesTrivially_of_sum_tmul_eq_zero_of_rTensor_injective R hm⟩ /-- Converse of `TensorProduct.vanishesTrivially_of_sum_tmul_eq_zero_of_rTensor_injective`. Assume that every expression $\sum_i m_i \otimes n_i$ which vanishes also vanishes trivially. Then, for every submodule $M' \subseteq M$, the map $M' \otimes N \to M \otimes N$ is injective. -/ theorem rTensor_injective_of_forall_vanishesTrivially (hMN : ∀ {ι : Type u} [Fintype ι] {m : ι → M} {n : ι → N}, ∑ i, m i ⊗ₜ n i = (0 : M ⊗[R] N) → VanishesTrivially R m n) (M' : Submodule R M) : Injective (rTensor N M'.subtype) := by apply (injective_iff_map_eq_zero _).mpr rintro x hx obtain ⟨s, rfl⟩ := exists_finset x rw [← Finset.sum_attach] apply sum_tmul_eq_zero_of_vanishesTrivially simp only [map_sum, rTensor_tmul, coeSubtype] at hx have := hMN ((Finset.sum_attach s _).trans hx) unfold VanishesTrivially at this ⊢ convert this with κ _ a y j symm convert (injective_iff_map_eq_zero' _).mp (injective_subtype M') _ simp /-- Every expression $\sum_i m_i \otimes n_i$ which vanishes also vanishes trivially if and only if for every submodule $M' \subseteq M$, the map $M' \otimes N \to M \otimes N$ is injective. -/ theorem forall_vanishesTrivially_iff_forall_rTensor_injective : (∀ {ι : Type u} [Fintype ι] {m : ι → M} {n : ι → N}, ∑ i, m i ⊗ₜ n i = (0 : M ⊗[R] N) → VanishesTrivially R m n) ↔ ∀ M' : Submodule R M, Injective (rTensor N M'.subtype) := by constructor · intro h exact rTensor_injective_of_forall_vanishesTrivially R h · intro h ι _ m n hmn exact vanishesTrivially_of_sum_tmul_eq_zero_of_rTensor_injective R (h _) hmn /-- Every expression $\sum_i m_i \otimes n_i$ which vanishes also vanishes trivially if and only if for every finitely generated submodule $M' \subseteq M$, the map $M' \otimes N \to M \otimes N$ is injective. -/ theorem forall_vanishesTrivially_iff_forall_FG_rTensor_injective : (∀ {ι : Type u} [Fintype ι] {m : ι → M} {n : ι → N}, ∑ i, m i ⊗ₜ n i = (0 : M ⊗[R] N) → VanishesTrivially R m n) ↔ ∀ (M' : Submodule R M) (_ : M'.FG), Injective (rTensor N M'.subtype) := by constructor · intro h M' _ exact rTensor_injective_of_forall_vanishesTrivially R h M' · intro h ι _ m n hmn exact vanishesTrivially_of_sum_tmul_eq_zero_of_rTensor_injective R (h _ (fg_span (Set.finite_range _))) hmn /-- If the map $M' \otimes N \to M \otimes N$ is injective for every finitely generated submodule $M' \subseteq M$, then it is in fact injective for every submodule $M' \subseteq M$. -/ theorem rTensor_injective_of_forall_FG_rTensor_injective (hMN : ∀ (M' : Submodule R M) (_ : M'.FG), Injective (rTensor N M'.subtype)) (M' : Submodule R M) : Injective (rTensor N M'.subtype) := (forall_vanishesTrivially_iff_forall_rTensor_injective R).mp ((forall_vanishesTrivially_iff_forall_FG_rTensor_injective R).mpr hMN) M' end TensorProduct
LinearAlgebra\TensorProduct\Graded\External.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.Data.Int.Order.Units import Mathlib.Data.ZMod.IntUnitsPower import Mathlib.RingTheory.TensorProduct.Basic import Mathlib.LinearAlgebra.DirectSum.TensorProduct import Mathlib.Algebra.DirectSum.Algebra /-! # Graded tensor products over graded algebras The graded tensor product $A \hat\otimes_R B$ is imbued with a multiplication defined on homogeneous tensors by: $$(a \otimes b) \cdot (a' \otimes b') = (-1)^{\deg a' \deg b} (a \cdot a') \otimes (b \cdot b')$$ where $A$ and $B$ are algebras graded by `ℕ`, `ℤ`, or `ZMod 2` (or more generally, any index that satisfies `Module ι (Additive ℤˣ)`). The results for internally-graded algebras (via `GradedAlgebra`) are elsewhere, as is the type `GradedTensorProduct`. ## Main results * `TensorProduct.gradedComm`: the symmetric braiding operator on the tensor product of externally-graded rings. * `TensorProduct.gradedMul`: the previously-described multiplication on externally-graded rings, as a bilinear map. ## Implementation notes Rather than implementing the multiplication directly as above, we first implement the canonical non-trivial braiding sending $a \otimes b$ to $(-1)^{\deg a' \deg b} (b \otimes a)$, as the multiplication follows trivially from this after some point-free nonsense. ## References * https://math.stackexchange.com/q/202718/1896 * [*Algebra I*, Bourbaki : Chapter III, §4.7, example (2)][bourbaki1989] -/ suppress_compilation open scoped TensorProduct DirectSum variable {R ι A B : Type*} namespace TensorProduct variable [CommSemiring ι] [Module ι (Additive ℤˣ)] [DecidableEq ι] variable (𝒜 : ι → Type*) (ℬ : ι → Type*) variable [CommRing R] variable [∀ i, AddCommGroup (𝒜 i)] [∀ i, AddCommGroup (ℬ i)] variable [∀ i, Module R (𝒜 i)] [∀ i, Module R (ℬ i)] -- this helps with performance instance (i : ι × ι) : Module R (𝒜 (Prod.fst i) ⊗[R] ℬ (Prod.snd i)) := TensorProduct.leftModule open DirectSum (lof) variable (R) section gradedComm local notation "𝒜ℬ" => (fun i : ι × ι => 𝒜 (Prod.fst i) ⊗[R] ℬ (Prod.snd i)) local notation "ℬ𝒜" => (fun i : ι × ι => ℬ (Prod.fst i) ⊗[R] 𝒜 (Prod.snd i)) /-- Auxliary construction used to build `TensorProduct.gradedComm`. This operates on direct sums of tensors instead of tensors of direct sums. -/ def gradedCommAux : DirectSum _ 𝒜ℬ →ₗ[R] DirectSum _ ℬ𝒜 := by refine DirectSum.toModule R _ _ fun i => ?_ have o := DirectSum.lof R _ ℬ𝒜 i.swap have s : ℤˣ := ((-1 : ℤˣ)^(i.1* i.2 : ι) : ℤˣ) exact (s • o) ∘ₗ (TensorProduct.comm R _ _).toLinearMap @[simp] theorem gradedCommAux_lof_tmul (i j : ι) (a : 𝒜 i) (b : ℬ j) : gradedCommAux R 𝒜 ℬ (lof R _ 𝒜ℬ (i, j) (a ⊗ₜ b)) = (-1 : ℤˣ)^(j * i) • lof R _ ℬ𝒜 (j, i) (b ⊗ₜ a) := by rw [gradedCommAux] dsimp simp [mul_comm i j] @[simp] theorem gradedCommAux_comp_gradedCommAux : gradedCommAux R 𝒜 ℬ ∘ₗ gradedCommAux R ℬ 𝒜 = LinearMap.id := by ext i a b dsimp rw [gradedCommAux_lof_tmul, LinearMap.map_smul_of_tower, gradedCommAux_lof_tmul, smul_smul, mul_comm i.2 i.1, Int.units_mul_self, one_smul] /-- The braiding operation for tensor products of externally `ι`-graded algebras. This sends $a ⊗ b$ to $(-1)^{\deg a' \deg b} (b ⊗ a)$. -/ def gradedComm : (⨁ i, 𝒜 i) ⊗[R] (⨁ i, ℬ i) ≃ₗ[R] (⨁ i, ℬ i) ⊗[R] (⨁ i, 𝒜 i) := by refine TensorProduct.directSum R R 𝒜 ℬ ≪≫ₗ ?_ ≪≫ₗ (TensorProduct.directSum R R ℬ 𝒜).symm exact LinearEquiv.ofLinear (gradedCommAux _ _ _) (gradedCommAux _ _ _) (gradedCommAux_comp_gradedCommAux _ _ _) (gradedCommAux_comp_gradedCommAux _ _ _) /-- The braiding is symmetric. -/ @[simp] theorem gradedComm_symm : (gradedComm R 𝒜 ℬ).symm = gradedComm R ℬ 𝒜 := by rw [gradedComm, gradedComm, LinearEquiv.trans_symm, LinearEquiv.symm_symm] ext rfl theorem gradedComm_of_tmul_of (i j : ι) (a : 𝒜 i) (b : ℬ j) : gradedComm R 𝒜 ℬ (lof R _ 𝒜 i a ⊗ₜ lof R _ ℬ j b) = (-1 : ℤˣ)^(j * i) • (lof R _ ℬ _ b ⊗ₜ lof R _ 𝒜 _ a) := by rw [gradedComm] dsimp only [LinearEquiv.trans_apply, LinearEquiv.ofLinear_apply] rw [TensorProduct.directSum_lof_tmul_lof, gradedCommAux_lof_tmul, Units.smul_def, -- Note: #8386 specialized `map_smul` to `LinearEquiv.map_smul` to avoid timeouts. ← Int.cast_smul_eq_zsmul R, LinearEquiv.map_smul, TensorProduct.directSum_symm_lof_tmul, Int.cast_smul_eq_zsmul, ← Units.smul_def] theorem gradedComm_tmul_of_zero (a : ⨁ i, 𝒜 i) (b : ℬ 0) : gradedComm R 𝒜 ℬ (a ⊗ₜ lof R _ ℬ 0 b) = lof R _ ℬ _ b ⊗ₜ a := by suffices (gradedComm R 𝒜 ℬ).toLinearMap ∘ₗ (TensorProduct.mk R (⨁ i, 𝒜 i) (⨁ i, ℬ i)).flip (lof R _ ℬ 0 b) = TensorProduct.mk R _ _ (lof R _ ℬ 0 b) from DFunLike.congr_fun this a ext i a dsimp rw [gradedComm_of_tmul_of, zero_mul, uzpow_zero, one_smul] theorem gradedComm_of_zero_tmul (a : 𝒜 0) (b : ⨁ i, ℬ i) : gradedComm R 𝒜 ℬ (lof R _ 𝒜 0 a ⊗ₜ b) = b ⊗ₜ lof R _ 𝒜 _ a := by suffices (gradedComm R 𝒜 ℬ).toLinearMap ∘ₗ (TensorProduct.mk R (⨁ i, 𝒜 i) (⨁ i, ℬ i)) (lof R _ 𝒜 0 a) = (TensorProduct.mk R _ _).flip (lof R _ 𝒜 0 a) from DFunLike.congr_fun this b ext i b dsimp rw [gradedComm_of_tmul_of, mul_zero, uzpow_zero, one_smul] theorem gradedComm_tmul_one [DirectSum.GRing ℬ] (a : ⨁ i, 𝒜 i) : gradedComm R 𝒜 ℬ (a ⊗ₜ 1) = 1 ⊗ₜ a := gradedComm_tmul_of_zero _ _ _ _ _ theorem gradedComm_one_tmul [DirectSum.GRing 𝒜] (b : ⨁ i, ℬ i) : gradedComm R 𝒜 ℬ (1 ⊗ₜ b) = b ⊗ₜ 1 := gradedComm_of_zero_tmul _ _ _ _ _ @[simp, nolint simpNF] -- linter times out theorem gradedComm_one [DirectSum.GRing 𝒜] [DirectSum.GRing ℬ] : gradedComm R 𝒜 ℬ 1 = 1 := gradedComm_one_tmul _ _ _ _ theorem gradedComm_tmul_algebraMap [DirectSum.GRing ℬ] [DirectSum.GAlgebra R ℬ] (a : ⨁ i, 𝒜 i) (r : R) : gradedComm R 𝒜 ℬ (a ⊗ₜ algebraMap R _ r) = algebraMap R _ r ⊗ₜ a := gradedComm_tmul_of_zero _ _ _ _ _ theorem gradedComm_algebraMap_tmul [DirectSum.GRing 𝒜] [DirectSum.GAlgebra R 𝒜] (r : R) (b : ⨁ i, ℬ i) : gradedComm R 𝒜 ℬ (algebraMap R _ r ⊗ₜ b) = b ⊗ₜ algebraMap R _ r := gradedComm_of_zero_tmul _ _ _ _ _ theorem gradedComm_algebraMap [DirectSum.GRing 𝒜] [DirectSum.GRing ℬ] [DirectSum.GAlgebra R 𝒜] [DirectSum.GAlgebra R ℬ] (r : R) : gradedComm R 𝒜 ℬ (algebraMap R _ r) = algebraMap R _ r := (gradedComm_algebraMap_tmul R 𝒜 ℬ r 1).trans (Algebra.TensorProduct.algebraMap_apply' r).symm end gradedComm variable [DirectSum.GRing 𝒜] [DirectSum.GRing ℬ] variable [DirectSum.GAlgebra R 𝒜] [DirectSum.GAlgebra R ℬ] open TensorProduct (assoc map) in /-- The multiplication operation for tensor products of externally `ι`-graded algebras. -/ noncomputable irreducible_def gradedMul : letI AB := DirectSum _ 𝒜 ⊗[R] DirectSum _ ℬ letI : Module R AB := TensorProduct.leftModule AB →ₗ[R] AB →ₗ[R] AB := by refine TensorProduct.curry ?_ refine map (LinearMap.mul' R (⨁ i, 𝒜 i)) (LinearMap.mul' R (⨁ i, ℬ i)) ∘ₗ ?_ refine (assoc R _ _ _).symm.toLinearMap ∘ₗ .lTensor _ ?_ ∘ₗ (assoc R _ _ _).toLinearMap refine (assoc R _ _ _).toLinearMap ∘ₗ .rTensor _ ?_ ∘ₗ (assoc R _ _ _).symm.toLinearMap exact (gradedComm _ _ _).toLinearMap theorem tmul_of_gradedMul_of_tmul (j₁ i₂ : ι) (a₁ : ⨁ i, 𝒜 i) (b₁ : ℬ j₁) (a₂ : 𝒜 i₂) (b₂ : ⨁ i, ℬ i) : gradedMul R 𝒜 ℬ (a₁ ⊗ₜ lof R _ ℬ j₁ b₁) (lof R _ 𝒜 i₂ a₂ ⊗ₜ b₂) = (-1 : ℤˣ)^(j₁ * i₂) • ((a₁ * lof R _ 𝒜 _ a₂) ⊗ₜ (lof R _ ℬ _ b₁ * b₂)) := by rw [gradedMul] dsimp only [curry_apply, LinearMap.coe_comp, LinearEquiv.coe_coe, Function.comp_apply, assoc_tmul, map_tmul, LinearMap.id_coe, id_eq, assoc_symm_tmul, LinearMap.rTensor_tmul, LinearMap.lTensor_tmul] rw [mul_comm j₁ i₂, gradedComm_of_tmul_of] -- the tower smul lemmas elaborate too slowly rw [Units.smul_def, Units.smul_def, ← Int.cast_smul_eq_zsmul R, ← Int.cast_smul_eq_zsmul R] -- Note: #8386 had to specialize `map_smul` to avoid timeouts. rw [← smul_tmul', LinearEquiv.map_smul, tmul_smul, LinearEquiv.map_smul, LinearMap.map_smul] dsimp variable {R} theorem algebraMap_gradedMul (r : R) (x : (⨁ i, 𝒜 i) ⊗[R] (⨁ i, ℬ i)) : gradedMul R 𝒜 ℬ (algebraMap R _ r ⊗ₜ 1) x = r • x := by suffices gradedMul R 𝒜 ℬ (algebraMap R _ r ⊗ₜ 1) = DistribMulAction.toLinearMap R _ r by exact DFunLike.congr_fun this x ext ia a ib b dsimp erw [tmul_of_gradedMul_of_tmul] rw [zero_mul, uzpow_zero, one_smul, smul_tmul'] erw [one_mul, _root_.Algebra.smul_def] theorem one_gradedMul (x : (⨁ i, 𝒜 i) ⊗[R] (⨁ i, ℬ i)) : gradedMul R 𝒜 ℬ 1 x = x := by -- Note: #8386 had to specialize `map_one` to avoid timeouts. simpa only [RingHom.map_one, one_smul] using algebraMap_gradedMul 𝒜 ℬ 1 x theorem gradedMul_algebraMap (x : (⨁ i, 𝒜 i) ⊗[R] (⨁ i, ℬ i)) (r : R) : gradedMul R 𝒜 ℬ x (algebraMap R _ r ⊗ₜ 1) = r • x := by suffices (gradedMul R 𝒜 ℬ).flip (algebraMap R _ r ⊗ₜ 1) = DistribMulAction.toLinearMap R _ r by exact DFunLike.congr_fun this x ext dsimp erw [tmul_of_gradedMul_of_tmul] rw [mul_zero, uzpow_zero, one_smul, smul_tmul'] erw [mul_one, _root_.Algebra.smul_def, Algebra.commutes] rfl theorem gradedMul_one (x : (⨁ i, 𝒜 i) ⊗[R] (⨁ i, ℬ i)) : gradedMul R 𝒜 ℬ x 1 = x := by -- Note: #8386 had to specialize `map_one` to avoid timeouts. simpa only [RingHom.map_one, one_smul] using gradedMul_algebraMap 𝒜 ℬ x 1 theorem gradedMul_assoc (x y z : DirectSum _ 𝒜 ⊗[R] DirectSum _ ℬ) : gradedMul R 𝒜 ℬ (gradedMul R 𝒜 ℬ x y) z = gradedMul R 𝒜 ℬ x (gradedMul R 𝒜 ℬ y z) := by let mA := gradedMul R 𝒜 ℬ -- restate as an equality of morphisms so that we can use `ext` suffices LinearMap.llcomp R _ _ _ mA ∘ₗ mA = (LinearMap.llcomp R _ _ _ LinearMap.lflip <| LinearMap.llcomp R _ _ _ mA.flip ∘ₗ mA).flip by exact DFunLike.congr_fun (DFunLike.congr_fun (DFunLike.congr_fun this x) y) z ext ixa xa ixb xb iya ya iyb yb iza za izb zb dsimp [mA] simp_rw [tmul_of_gradedMul_of_tmul, Units.smul_def, ← Int.cast_smul_eq_zsmul R, LinearMap.map_smul₂, LinearMap.map_smul, DirectSum.lof_eq_of, DirectSum.of_mul_of, ← DirectSum.lof_eq_of R, tmul_of_gradedMul_of_tmul, DirectSum.lof_eq_of, ← DirectSum.of_mul_of, ← DirectSum.lof_eq_of R, mul_assoc] simp_rw [Int.cast_smul_eq_zsmul R, ← Units.smul_def, smul_smul, ← uzpow_add, add_mul, mul_add] congr 2 abel theorem gradedComm_gradedMul (x y : DirectSum _ 𝒜 ⊗[R] DirectSum _ ℬ) : gradedComm R 𝒜 ℬ (gradedMul R 𝒜 ℬ x y) = gradedMul R ℬ 𝒜 (gradedComm R 𝒜 ℬ x) (gradedComm R 𝒜 ℬ y) := by suffices (gradedMul R 𝒜 ℬ).compr₂ (gradedComm R 𝒜 ℬ).toLinearMap = (gradedMul R ℬ 𝒜 ∘ₗ (gradedComm R 𝒜 ℬ).toLinearMap).compl₂ (gradedComm R 𝒜 ℬ).toLinearMap from LinearMap.congr_fun₂ this x y ext i₁ a₁ j₁ b₁ i₂ a₂ j₂ b₂ dsimp rw [gradedComm_of_tmul_of, gradedComm_of_tmul_of, tmul_of_gradedMul_of_tmul] -- Note: #8386 had to specialize `map_smul` to avoid timeouts. simp_rw [Units.smul_def, ← Int.cast_smul_eq_zsmul R, LinearEquiv.map_smul, LinearMap.map_smul, LinearMap.smul_apply] simp_rw [Int.cast_smul_eq_zsmul R, ← Units.smul_def, DirectSum.lof_eq_of, DirectSum.of_mul_of, ← DirectSum.lof_eq_of R, gradedComm_of_tmul_of, tmul_of_gradedMul_of_tmul, smul_smul, DirectSum.lof_eq_of, ← DirectSum.of_mul_of, ← DirectSum.lof_eq_of R] simp_rw [← uzpow_add, mul_add, add_mul, mul_comm i₁ j₂] congr 1 abel_nf rw [two_nsmul, uzpow_add, uzpow_add, Int.units_mul_self, one_mul] end TensorProduct
LinearAlgebra\TensorProduct\Graded\Internal.lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.LinearAlgebra.TensorProduct.Graded.External import Mathlib.RingTheory.GradedAlgebra.Basic import Mathlib.GroupTheory.GroupAction.Ring /-! # Graded tensor products over graded algebras The graded tensor product $A \hat\otimes_R B$ is imbued with a multiplication defined on homogeneous tensors by: $$(a \otimes b) \cdot (a' \otimes b') = (-1)^{\deg a' \deg b} (a \cdot a') \otimes (b \cdot b')$$ where $A$ and $B$ are algebras graded by `ℕ`, `ℤ`, or `ι` (or more generally, any index that satisfies `Module ι (Additive ℤˣ)`). ## Main results * `GradedTensorProduct R 𝒜 ℬ`: for families of submodules of `A` and `B` that form a graded algebra, this is a type alias for `A ⊗[R] B` with the appropriate multiplication. * `GradedTensorProduct.instAlgebra`: the ring structure induced by this multiplication. * `GradedTensorProduct.liftEquiv`: a universal property for graded tensor products ## Notation * `𝒜 ᵍ⊗[R] ℬ` is notation for `GradedTensorProduct R 𝒜 ℬ`. * `a ᵍ⊗ₜ b` is notation for `GradedTensorProduct.tmul _ a b`. ## References * https://math.stackexchange.com/q/202718/1896 * [*Algebra I*, Bourbaki : Chapter III, §4.7, example (2)][bourbaki1989] ## Implementation notes We cannot put the multiplication on `A ⊗[R] B` directly as it would conflict with the existing multiplication defined without the $(-1)^{\deg a' \deg b}$ term. Furthermore, the ring `A` may not have a unique graduation, and so we need the chosen graduation `𝒜` to appear explicitly in the type. ## TODO * Show that the tensor product of graded algebras is itself a graded algebra. * Determine if replacing the synonym with a single-field structure improves performance. -/ suppress_compilation open scoped TensorProduct variable {R ι A B : Type*} variable [CommSemiring ι] [Module ι (Additive ℤˣ)] [DecidableEq ι] variable [CommRing R] [Ring A] [Ring B] [Algebra R A] [Algebra R B] variable (𝒜 : ι → Submodule R A) (ℬ : ι → Submodule R B) variable [GradedAlgebra 𝒜] [GradedAlgebra ℬ] open DirectSum variable (R) in /-- A Type synonym for `A ⊗[R] B`, but with multiplication as `TensorProduct.gradedMul`. This has notation `𝒜 ᵍ⊗[R] ℬ`. -/ @[nolint unusedArguments] def GradedTensorProduct (𝒜 : ι → Submodule R A) (ℬ : ι → Submodule R B) [GradedAlgebra 𝒜] [GradedAlgebra ℬ] : Type _ := A ⊗[R] B namespace GradedTensorProduct open TensorProduct @[inherit_doc GradedTensorProduct] scoped[TensorProduct] notation:100 𝒜 " ᵍ⊗[" R "] " ℬ:100 => GradedTensorProduct R 𝒜 ℬ instance instAddCommGroupWithOne : AddCommGroupWithOne (𝒜 ᵍ⊗[R] ℬ) := Algebra.TensorProduct.instAddCommGroupWithOne instance : Module R (𝒜 ᵍ⊗[R] ℬ) := TensorProduct.leftModule variable (R) in /-- The casting equivalence to move between regular and graded tensor products. -/ def of : A ⊗[R] B ≃ₗ[R] 𝒜 ᵍ⊗[R] ℬ := LinearEquiv.refl _ _ @[simp] theorem of_one : of R 𝒜 ℬ 1 = 1 := rfl @[simp] theorem of_symm_one : (of R 𝒜 ℬ).symm 1 = 1 := rfl @[simp] theorem of_symm_of (x : A ⊗[R] B) : (of R 𝒜 ℬ).symm (of R 𝒜 ℬ x) = x := rfl @[simp] theorem symm_of_of (x : 𝒜 ᵍ⊗[R] ℬ) : of R 𝒜 ℬ ((of R 𝒜 ℬ).symm x) = x := rfl /-- Two linear maps from the graded tensor product agree if they agree on the underlying tensor product. -/ @[ext] theorem hom_ext {M} [AddCommMonoid M] [Module R M] ⦃f g : 𝒜 ᵍ⊗[R] ℬ →ₗ[R] M⦄ (h : f ∘ₗ of R 𝒜 ℬ = (g ∘ₗ of R 𝒜 ℬ : A ⊗[R] B →ₗ[R] M)) : f = g := h variable (R) {𝒜 ℬ} in /-- The graded tensor product of two elements of graded rings. -/ abbrev tmul (a : A) (b : B) : 𝒜 ᵍ⊗[R] ℬ := of R 𝒜 ℬ (a ⊗ₜ b) @[inherit_doc] notation:100 x " ᵍ⊗ₜ" y:100 => tmul _ x y @[inherit_doc] notation:100 x " ᵍ⊗ₜ[" R "] " y:100 => tmul R x y variable (R) in /-- An auxiliary construction to move between the graded tensor product of internally-graded objects and the tensor product of direct sums. -/ noncomputable def auxEquiv : (𝒜 ᵍ⊗[R] ℬ) ≃ₗ[R] (⨁ i, 𝒜 i) ⊗[R] (⨁ i, ℬ i) := let fA := (decomposeAlgEquiv 𝒜).toLinearEquiv let fB := (decomposeAlgEquiv ℬ).toLinearEquiv (of R 𝒜 ℬ).symm.trans (TensorProduct.congr fA fB) theorem auxEquiv_tmul (a : A) (b : B) : auxEquiv R 𝒜 ℬ (a ᵍ⊗ₜ b) = decompose 𝒜 a ⊗ₜ decompose ℬ b := rfl theorem auxEquiv_one : auxEquiv R 𝒜 ℬ 1 = 1 := by rw [← of_one, Algebra.TensorProduct.one_def, auxEquiv_tmul 𝒜 ℬ, DirectSum.decompose_one, DirectSum.decompose_one, Algebra.TensorProduct.one_def] theorem auxEquiv_symm_one : (auxEquiv R 𝒜 ℬ).symm 1 = 1 := (LinearEquiv.symm_apply_eq _).mpr (auxEquiv_one _ _).symm /-- Auxiliary construction used to build the `Mul` instance and get distributivity of `+` and `\smul`. -/ noncomputable def mulHom : (𝒜 ᵍ⊗[R] ℬ) →ₗ[R] (𝒜 ᵍ⊗[R] ℬ) →ₗ[R] (𝒜 ᵍ⊗[R] ℬ) := by letI fAB1 := auxEquiv R 𝒜 ℬ have := ((gradedMul R (𝒜 ·) (ℬ ·)).compl₁₂ fAB1.toLinearMap fAB1.toLinearMap).compr₂ fAB1.symm.toLinearMap exact this theorem mulHom_apply (x y : 𝒜 ᵍ⊗[R] ℬ) : mulHom 𝒜 ℬ x y = (auxEquiv R 𝒜 ℬ).symm (gradedMul R (𝒜 ·) (ℬ ·) (auxEquiv R 𝒜 ℬ x) (auxEquiv R 𝒜 ℬ y)) := rfl /-- The multipication on the graded tensor product. See `GradedTensorProduct.coe_mul_coe` for a characterization on pure tensors. -/ instance : Mul (𝒜 ᵍ⊗[R] ℬ) where mul x y := mulHom 𝒜 ℬ x y theorem mul_def (x y : 𝒜 ᵍ⊗[R] ℬ) : x * y = mulHom 𝒜 ℬ x y := rfl -- Before #8386 this was `@[simp]` but it times out when we try to apply it. theorem auxEquiv_mul (x y : 𝒜 ᵍ⊗[R] ℬ) : auxEquiv R 𝒜 ℬ (x * y) = gradedMul R (𝒜 ·) (ℬ ·) (auxEquiv R 𝒜 ℬ x) (auxEquiv R 𝒜 ℬ y) := LinearEquiv.eq_symm_apply _ |>.mp rfl instance instMonoid : Monoid (𝒜 ᵍ⊗[R] ℬ) where mul_one x := by rw [mul_def, mulHom_apply, auxEquiv_one, gradedMul_one, LinearEquiv.symm_apply_apply] one_mul x := by rw [mul_def, mulHom_apply, auxEquiv_one, one_gradedMul, LinearEquiv.symm_apply_apply] mul_assoc x y z := by simp_rw [mul_def, mulHom_apply, LinearEquiv.apply_symm_apply] rw [gradedMul_assoc] instance instRing : Ring (𝒜 ᵍ⊗[R] ℬ) where __ := instAddCommGroupWithOne 𝒜 ℬ __ := instMonoid 𝒜 ℬ right_distrib x y z := by simp_rw [mul_def, LinearMap.map_add₂] left_distrib x y z := by simp_rw [mul_def, map_add] mul_zero x := by simp_rw [mul_def, map_zero] zero_mul x := by simp_rw [mul_def, LinearMap.map_zero₂] /-- The characterization of this multiplication on partially homogenous elements. -/ theorem tmul_coe_mul_coe_tmul {j₁ i₂ : ι} (a₁ : A) (b₁ : ℬ j₁) (a₂ : 𝒜 i₂) (b₂ : B) : (a₁ ᵍ⊗ₜ[R] (b₁ : B) * (a₂ : A) ᵍ⊗ₜ[R] b₂ : 𝒜 ᵍ⊗[R] ℬ) = (-1 : ℤˣ)^(j₁ * i₂) • ((a₁ * a₂ : A) ᵍ⊗ₜ (b₁ * b₂ : B)) := by dsimp only [mul_def, mulHom_apply, of_symm_of] dsimp [auxEquiv, tmul] erw [decompose_coe, decompose_coe] simp_rw [← lof_eq_of R] rw [tmul_of_gradedMul_of_tmul] simp_rw [lof_eq_of R] rw [LinearEquiv.symm_symm] -- Note: #8386 had to specialize `map_smul` to `LinearEquiv.map_smul` rw [@Units.smul_def _ _ (_) (_), ← Int.cast_smul_eq_zsmul R, LinearEquiv.map_smul, map_smul, Int.cast_smul_eq_zsmul R, ← @Units.smul_def _ _ (_) (_)] rw [congr_symm_tmul] dsimp simp_rw [decompose_symm_mul, decompose_symm_of, Equiv.symm_apply_apply] /-- A special case for when `b₁` has grade 0. -/ theorem tmul_zero_coe_mul_coe_tmul {i₂ : ι} (a₁ : A) (b₁ : ℬ 0) (a₂ : 𝒜 i₂) (b₂ : B) : (a₁ ᵍ⊗ₜ[R] (b₁ : B) * (a₂ : A) ᵍ⊗ₜ[R] b₂ : 𝒜 ᵍ⊗[R] ℬ) = ((a₁ * a₂ : A) ᵍ⊗ₜ (b₁ * b₂ : B)) := by rw [tmul_coe_mul_coe_tmul, zero_mul, uzpow_zero, one_smul] /-- A special case for when `a₂` has grade 0. -/ theorem tmul_coe_mul_zero_coe_tmul {j₁ : ι} (a₁ : A) (b₁ : ℬ j₁) (a₂ : 𝒜 0) (b₂ : B) : (a₁ ᵍ⊗ₜ[R] (b₁ : B) * (a₂ : A) ᵍ⊗ₜ[R] b₂ : 𝒜 ᵍ⊗[R] ℬ) = ((a₁ * a₂ : A) ᵍ⊗ₜ (b₁ * b₂ : B)) := by rw [tmul_coe_mul_coe_tmul, mul_zero, uzpow_zero, one_smul] theorem tmul_one_mul_coe_tmul {i₂ : ι} (a₁ : A) (a₂ : 𝒜 i₂) (b₂ : B) : (a₁ ᵍ⊗ₜ[R] (1 : B) * (a₂ : A) ᵍ⊗ₜ[R] b₂ : 𝒜 ᵍ⊗[R] ℬ) = (a₁ * a₂ : A) ᵍ⊗ₜ (b₂ : B) := by convert tmul_zero_coe_mul_coe_tmul 𝒜 ℬ a₁ (@GradedMonoid.GOne.one _ (ℬ ·) _ _) a₂ b₂ rw [SetLike.coe_gOne, one_mul] theorem tmul_coe_mul_one_tmul {j₁ : ι} (a₁ : A) (b₁ : ℬ j₁) (b₂ : B) : (a₁ ᵍ⊗ₜ[R] (b₁ : B) * (1 : A) ᵍ⊗ₜ[R] b₂ : 𝒜 ᵍ⊗[R] ℬ) = (a₁ : A) ᵍ⊗ₜ (b₁ * b₂ : B) := by convert tmul_coe_mul_zero_coe_tmul 𝒜 ℬ a₁ b₁ (@GradedMonoid.GOne.one _ (𝒜 ·) _ _) b₂ rw [SetLike.coe_gOne, mul_one] theorem tmul_one_mul_one_tmul (a₁ : A) (b₂ : B) : (a₁ ᵍ⊗ₜ[R] (1 : B) * (1 : A) ᵍ⊗ₜ[R] b₂ : 𝒜 ᵍ⊗[R] ℬ) = (a₁ : A) ᵍ⊗ₜ (b₂ : B) := by convert tmul_coe_mul_zero_coe_tmul 𝒜 ℬ a₁ (@GradedMonoid.GOne.one _ (ℬ ·) _ _) (@GradedMonoid.GOne.one _ (𝒜 ·) _ _) b₂ · rw [SetLike.coe_gOne, mul_one] · rw [SetLike.coe_gOne, one_mul] /-- The ring morphism `A →+* A ⊗[R] B` sending `a` to `a ⊗ₜ 1`. -/ @[simps] def includeLeftRingHom : A →+* 𝒜 ᵍ⊗[R] ℬ where toFun a := a ᵍ⊗ₜ 1 map_zero' := by simp map_add' := by simp [tmul, TensorProduct.add_tmul] map_one' := rfl map_mul' a₁ a₂ := by dsimp classical rw [← DirectSum.sum_support_decompose 𝒜 a₂, Finset.mul_sum] simp_rw [tmul, sum_tmul, map_sum, Finset.mul_sum] congr ext i rw [← SetLike.coe_gOne ℬ, tmul_coe_mul_coe_tmul, zero_mul, uzpow_zero, one_smul, SetLike.coe_gOne, one_mul] instance instAlgebra : Algebra R (𝒜 ᵍ⊗[R] ℬ) where toRingHom := (includeLeftRingHom 𝒜 ℬ).comp (algebraMap R A) commutes' r x := by dsimp [mul_def, mulHom_apply, auxEquiv_tmul] simp_rw [DirectSum.decompose_algebraMap, DirectSum.decompose_one, algebraMap_gradedMul, gradedMul_algebraMap] smul_def' r x := by dsimp [mul_def, mulHom_apply, auxEquiv_tmul] simp_rw [DirectSum.decompose_algebraMap, DirectSum.decompose_one, algebraMap_gradedMul] -- Qualified `map_smul` to avoid a TC timeout #8386 erw [LinearMap.map_smul] erw [LinearEquiv.symm_apply_apply] lemma algebraMap_def (r : R) : algebraMap R (𝒜 ᵍ⊗[R] ℬ) r = algebraMap R A r ᵍ⊗ₜ[R] 1 := rfl theorem tmul_algebraMap_mul_coe_tmul {i₂ : ι} (a₁ : A) (r : R) (a₂ : 𝒜 i₂) (b₂ : B) : (a₁ ᵍ⊗ₜ[R] algebraMap R B r * (a₂ : A) ᵍ⊗ₜ[R] b₂ : 𝒜 ᵍ⊗[R] ℬ) = (a₁ * a₂ : A) ᵍ⊗ₜ (algebraMap R B r * b₂ : B) := tmul_zero_coe_mul_coe_tmul 𝒜 ℬ a₁ (GAlgebra.toFun (A := (ℬ ·)) r) a₂ b₂ theorem tmul_coe_mul_algebraMap_tmul {j₁ : ι} (a₁ : A) (b₁ : ℬ j₁) (r : R) (b₂ : B) : (a₁ ᵍ⊗ₜ[R] (b₁ : B) * algebraMap R A r ᵍ⊗ₜ[R] b₂ : 𝒜 ᵍ⊗[R] ℬ) = (a₁ * algebraMap R A r : A) ᵍ⊗ₜ (b₁ * b₂ : B) := tmul_coe_mul_zero_coe_tmul 𝒜 ℬ a₁ b₁ (GAlgebra.toFun (A := (𝒜 ·)) r) b₂ /-- The algebra morphism `A →ₐ[R] A ⊗[R] B` sending `a` to `a ⊗ₜ 1`. -/ @[simps!] def includeLeft : A →ₐ[R] 𝒜 ᵍ⊗[R] ℬ where toRingHom := includeLeftRingHom 𝒜 ℬ commutes' _ := rfl /-- The algebra morphism `B →ₐ[R] A ⊗[R] B` sending `b` to `1 ⊗ₜ b`. -/ @[simps!] def includeRight : B →ₐ[R] (𝒜 ᵍ⊗[R] ℬ) := AlgHom.ofLinearMap (R := R) (A := B) (B := 𝒜 ᵍ⊗[R] ℬ) (f := { toFun := fun b => 1 ᵍ⊗ₜ b map_add' := by simp [tmul, TensorProduct.tmul_add] map_smul' := by simp [tmul, TensorProduct.tmul_smul] }) (map_one := rfl) (map_mul := by rw [LinearMap.map_mul_iff] refine DirectSum.decompose_lhom_ext ℬ fun i₁ => ?_ ext b₁ b₂ : 2 dsimp rw [tmul_coe_mul_one_tmul]) lemma algebraMap_def' (r : R) : algebraMap R (𝒜 ᵍ⊗[R] ℬ) r = 1 ᵍ⊗ₜ[R] algebraMap R B r := (includeRight 𝒜 ℬ).commutes r |>.symm variable {C} [Ring C] [Algebra R C] /-- The forwards direction of the universal property; an algebra morphism out of the graded tensor product can be assembed from maps on each component that (anti)commute on pure elements of the corresponding graded algebras. -/ def lift (f : A →ₐ[R] C) (g : B →ₐ[R] C) (h_anti_commutes : ∀ ⦃i j⦄ (a : 𝒜 i) (b : ℬ j), f a * g b = (-1 : ℤˣ)^(j * i) • (g b * f a)) : (𝒜 ᵍ⊗[R] ℬ) →ₐ[R] C := AlgHom.ofLinearMap (LinearMap.mul' R C ∘ₗ (TensorProduct.map f.toLinearMap g.toLinearMap) ∘ₗ ((of R 𝒜 ℬ).symm : 𝒜 ᵍ⊗[R] ℬ →ₗ[R] A ⊗[R] B)) (by dsimp [Algebra.TensorProduct.one_def] simp only [_root_.map_one, mul_one]) (by rw [LinearMap.map_mul_iff] ext a₁ : 3 refine DirectSum.decompose_lhom_ext ℬ fun j₁ => ?_ ext b₁ : 3 refine DirectSum.decompose_lhom_ext 𝒜 fun i₂ => ?_ ext a₂ b₂ : 2 dsimp rw [tmul_coe_mul_coe_tmul] rw [@Units.smul_def _ _ (_) (_), ← Int.cast_smul_eq_zsmul R, map_smul, map_smul, map_smul] rw [Int.cast_smul_eq_zsmul R, ← @Units.smul_def _ _ (_) (_)] rw [of_symm_of, map_tmul, LinearMap.mul'_apply] simp_rw [AlgHom.toLinearMap_apply, _root_.map_mul] simp_rw [mul_assoc (f a₁), ← mul_assoc _ _ (g b₂), h_anti_commutes, mul_smul_comm, smul_mul_assoc, smul_smul, Int.units_mul_self, one_smul]) @[simp] theorem lift_tmul (f : A →ₐ[R] C) (g : B →ₐ[R] C) (h_anti_commutes : ∀ ⦃i j⦄ (a : 𝒜 i) (b : ℬ j), f a * g b = (-1 : ℤˣ)^(j * i) • (g b * f a)) (a : A) (b : B) : lift 𝒜 ℬ f g h_anti_commutes (a ᵍ⊗ₜ b) = f a * g b := rfl /-- The universal property of the graded tensor product; every algebra morphism uniquely factors as a pair of algebra morphisms that anticommute with respect to the grading. -/ def liftEquiv : { fg : (A →ₐ[R] C) × (B →ₐ[R] C) // ∀ ⦃i j⦄ (a : 𝒜 i) (b : ℬ j), fg.1 a * fg.2 b = (-1 : ℤˣ)^(j * i) • (fg.2 b * fg.1 a)} ≃ ((𝒜 ᵍ⊗[R] ℬ) →ₐ[R] C) where toFun fg := lift 𝒜 ℬ _ _ fg.prop invFun F := ⟨(F.comp (includeLeft 𝒜 ℬ), F.comp (includeRight 𝒜 ℬ)), fun i j a b => by dsimp rw [← _root_.map_mul, ← _root_.map_mul F, tmul_coe_mul_coe_tmul, one_mul, mul_one, AlgHom.map_smul_of_tower, tmul_one_mul_one_tmul, smul_smul, Int.units_mul_self, one_smul]⟩ left_inv fg := by ext <;> (dsimp; simp only [_root_.map_one, mul_one, one_mul]) right_inv F := by apply AlgHom.toLinearMap_injective ext dsimp rw [← _root_.map_mul, tmul_one_mul_one_tmul] /-- Two algebra morphism from the graded tensor product agree if their compositions with the left and right inclusions agree. -/ @[ext] lemma algHom_ext ⦃f g : (𝒜 ᵍ⊗[R] ℬ) →ₐ[R] C⦄ (ha : f.comp (includeLeft 𝒜 ℬ) = g.comp (includeLeft 𝒜 ℬ)) (hb : f.comp (includeRight 𝒜 ℬ) = g.comp (includeRight 𝒜 ℬ)) : f = g := (liftEquiv 𝒜 ℬ).symm.injective <| Subtype.ext <| Prod.ext ha hb /-- The non-trivial symmetric braiding, sending $a \otimes b$ to $(-1)^{\deg a' \deg b} (b \otimes a)$. -/ def comm : (𝒜 ᵍ⊗[R] ℬ) ≃ₐ[R] (ℬ ᵍ⊗[R] 𝒜) := AlgEquiv.ofLinearEquiv (auxEquiv R 𝒜 ℬ ≪≫ₗ gradedComm R _ _ ≪≫ₗ (auxEquiv R ℬ 𝒜).symm) (by dsimp simp_rw [auxEquiv_one, gradedComm_one, auxEquiv_symm_one]) (fun x y => by dsimp simp_rw [auxEquiv_mul, gradedComm_gradedMul, LinearEquiv.symm_apply_eq, ← gradedComm_gradedMul, auxEquiv_mul, LinearEquiv.apply_symm_apply, gradedComm_gradedMul]) lemma auxEquiv_comm (x : 𝒜 ᵍ⊗[R] ℬ) : auxEquiv R ℬ 𝒜 (comm 𝒜 ℬ x) = gradedComm R (𝒜 ·) (ℬ ·) (auxEquiv R 𝒜 ℬ x) := LinearEquiv.eq_symm_apply _ |>.mp rfl @[simp] lemma comm_coe_tmul_coe {i j : ι} (a : 𝒜 i) (b : ℬ j) : comm 𝒜 ℬ (a ᵍ⊗ₜ b) = (-1 : ℤˣ)^(j * i) • (b ᵍ⊗ₜ a : ℬ ᵍ⊗[R] 𝒜) := (auxEquiv R ℬ 𝒜).injective <| by simp_rw [auxEquiv_comm, auxEquiv_tmul, decompose_coe, ← lof_eq_of R, gradedComm_of_tmul_of, @Units.smul_def _ _ (_) (_), ← Int.cast_smul_eq_zsmul R] -- Qualified `map_smul` to avoid a TC timeout #8386 erw [LinearMap.map_smul, auxEquiv_tmul] simp_rw [decompose_coe, lof_eq_of] end GradedTensorProduct
Logic\Basic.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.Init.Algebra.Classes import Mathlib.Tactic.Attr.Register import Mathlib.Tactic.Basic import Batteries.Logic import Batteries.Util.LibraryNote import Batteries.Tactic.Lint.Basic import Mathlib.Data.Nat.Notation import Mathlib.Data.Int.Notation /-! # Basic logic properties This file is one of the earliest imports in mathlib. ## Implementation notes Theorems that require decidability hypotheses are in the namespace `Decidable`. Classical versions are in the namespace `Classical`. -/ open Function attribute [local instance 10] Classical.propDecidable section Miscellany -- Porting note: the following `inline` attributes have been omitted, -- on the assumption that this issue has been dealt with properly in Lean 4. -- /- We add the `inline` attribute to optimize VM computation using these declarations. -- For example, `if p ∧ q then ... else ...` will not evaluate the decidability -- of `q` if `p` is false. -/ -- attribute [inline] -- And.decidable Or.decidable Decidable.false Xor.decidable Iff.decidable Decidable.true -- Implies.decidable Not.decidable Ne.decidable Bool.decidableEq Decidable.toBool attribute [simp] cast_eq cast_heq imp_false /-- An identity function with its main argument implicit. This will be printed as `hidden` even if it is applied to a large term, so it can be used for elision, as done in the `elide` and `unelide` tactics. -/ abbrev hidden {α : Sort*} {a : α} := a variable {α : Sort*} instance (priority := 10) decidableEq_of_subsingleton [Subsingleton α] : DecidableEq α := fun a b ↦ isTrue (Subsingleton.elim a b) instance [Subsingleton α] (p : α → Prop) : Subsingleton (Subtype p) := ⟨fun ⟨x, _⟩ ⟨y, _⟩ ↦ by cases Subsingleton.elim x y; rfl⟩ theorem congr_heq {α β γ : Sort _} {f : α → γ} {g : β → γ} {x : α} {y : β} (h₁ : HEq f g) (h₂ : HEq x y) : f x = g y := by cases h₂; cases h₁; rfl theorem congr_arg_heq {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → HEq (f a₁) (f a₂) | _, _, rfl => HEq.rfl @[simp] theorem eq_iff_eq_cancel_left {b c : α} : (∀ {a}, a = b ↔ a = c) ↔ b = c := ⟨fun h ↦ by rw [← h], fun h a ↦ by rw [h]⟩ @[simp] theorem eq_iff_eq_cancel_right {a b : α} : (∀ {c}, a = c ↔ b = c) ↔ a = b := ⟨fun h ↦ by rw [h], fun h a ↦ by rw [h]⟩ lemma ne_and_eq_iff_right {a b c : α} (h : b ≠ c) : a ≠ b ∧ a = c ↔ a = c := and_iff_right_of_imp (fun h2 => h2.symm ▸ h.symm) /-- Wrapper for adding elementary propositions to the type class systems. Warning: this can easily be abused. See the rest of this docstring for details. Certain propositions should not be treated as a class globally, but sometimes it is very convenient to be able to use the type class system in specific circumstances. For example, `ZMod p` is a field if and only if `p` is a prime number. In order to be able to find this field instance automatically by type class search, we have to turn `p.prime` into an instance implicit assumption. On the other hand, making `Nat.prime` a class would require a major refactoring of the library, and it is questionable whether making `Nat.prime` a class is desirable at all. The compromise is to add the assumption `[Fact p.prime]` to `ZMod.field`. In particular, this class is not intended for turning the type class system into an automated theorem prover for first order logic. -/ class Fact (p : Prop) : Prop where /-- `Fact.out` contains the unwrapped witness for the fact represented by the instance of `Fact p`. -/ out : p library_note "fact non-instances"/-- In most cases, we should not have global instances of `Fact`; typeclass search only reads the head symbol and then tries any instances, which means that adding any such instance will cause slowdowns everywhere. We instead make them as lemmata and make them local instances as required. -/ theorem Fact.elim {p : Prop} (h : Fact p) : p := h.1 theorem fact_iff {p : Prop} : Fact p ↔ p := ⟨fun h ↦ h.1, fun h ↦ ⟨h⟩⟩ instance {p : Prop} [Decidable p] : Decidable (Fact p) := decidable_of_iff _ fact_iff.symm /-- Swaps two pairs of arguments to a function. -/ abbrev Function.swap₂ {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {φ : ∀ i₁, κ₁ i₁ → ∀ i₂, κ₂ i₂ → Sort*} (f : ∀ i₁ j₁ i₂ j₂, φ i₁ j₁ i₂ j₂) (i₂ j₂ i₁ j₁) : φ i₁ j₁ i₂ j₂ := f i₁ j₁ i₂ j₂ -- Porting note: these don't work as intended any more -- /-- If `x : α . tac_name` then `x.out : α`. These are definitionally equal, but this can -- nevertheless be useful for various reasons, e.g. to apply further projection notation or in an -- argument to `simp`. -/ -- def autoParam'.out {α : Sort*} {n : Name} (x : autoParam' α n) : α := x -- /-- If `x : α := d` then `x.out : α`. These are definitionally equal, but this can -- nevertheless be useful for various reasons, e.g. to apply further projection notation or in an -- argument to `simp`. -/ -- def optParam.out {α : Sort*} {d : α} (x : α := d) : α := x end Miscellany open Function /-! ### Declarations about propositional connectives -/ section Propositional /-! ### Declarations about `implies` -/ instance : IsRefl Prop Iff := ⟨Iff.refl⟩ instance : IsTrans Prop Iff := ⟨fun _ _ _ ↦ Iff.trans⟩ alias Iff.imp := imp_congr -- This is a duplicate of `Classical.imp_iff_right_iff`. Deprecate? theorem imp_iff_right_iff {a b : Prop} : (a → b ↔ b) ↔ a ∨ b := Decidable.imp_iff_right_iff -- This is a duplicate of `Classical.and_or_imp`. Deprecate? theorem and_or_imp {a b c : Prop} : a ∧ b ∨ (a → c) ↔ a → b ∨ c := Decidable.and_or_imp /-- Provide modus tollens (`mt`) as dot notation for implications. -/ protected theorem Function.mt {a b : Prop} : (a → b) → ¬b → ¬a := mt /-! ### Declarations about `not` -/ alias dec_em := Decidable.em theorem dec_em' (p : Prop) [Decidable p] : ¬p ∨ p := (dec_em p).symm alias em := Classical.em theorem em' (p : Prop) : ¬p ∨ p := (em p).symm theorem or_not {p : Prop} : p ∨ ¬p := em _ theorem Decidable.eq_or_ne {α : Sort*} (x y : α) [Decidable (x = y)] : x = y ∨ x ≠ y := dec_em <| x = y theorem Decidable.ne_or_eq {α : Sort*} (x y : α) [Decidable (x = y)] : x ≠ y ∨ x = y := dec_em' <| x = y theorem eq_or_ne {α : Sort*} (x y : α) : x = y ∨ x ≠ y := em <| x = y theorem ne_or_eq {α : Sort*} (x y : α) : x ≠ y ∨ x = y := em' <| x = y theorem by_contradiction {p : Prop} : (¬p → False) → p := Decidable.by_contradiction theorem by_cases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := if hp : p then hpq hp else hnpq hp alias by_contra := by_contradiction library_note "decidable namespace"/-- In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely. The `Decidable` namespace contains versions of lemmas from the root namespace that explicitly attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs. You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if `Classical.choice` appears in the list. -/ library_note "decidable arguments"/-- As mathlib is primarily classical, if the type signature of a `def` or `lemma` does not require any `Decidable` instances to state, it is preferable not to introduce any `Decidable` instances that are needed in the proof as arguments, but rather to use the `classical` tactic as needed. In the other direction, when `Decidable` instances do appear in the type signature, it is better to use explicitly introduced ones rather than allowing Lean to automatically infer classical ones, as these may cause instance mismatch errors later. -/ export Classical (not_not) attribute [simp] not_not variable {a b : Prop} theorem of_not_not {a : Prop} : ¬¬a → a := by_contra theorem not_ne_iff {α : Sort*} {a b : α} : ¬a ≠ b ↔ a = b := not_not theorem of_not_imp : ¬(a → b) → a := Decidable.of_not_imp alias Not.decidable_imp_symm := Decidable.not_imp_symm theorem Not.imp_symm : (¬a → b) → ¬b → a := Not.decidable_imp_symm theorem not_imp_comm : ¬a → b ↔ ¬b → a := Decidable.not_imp_comm @[simp] theorem not_imp_self : ¬a → a ↔ a := Decidable.not_imp_self theorem Imp.swap {a b : Sort*} {c : Prop} : a → b → c ↔ b → a → c := ⟨fun h x y ↦ h y x, fun h x y ↦ h y x⟩ alias Iff.not := not_congr theorem Iff.not_left (h : a ↔ ¬b) : ¬a ↔ b := h.not.trans not_not theorem Iff.not_right (h : ¬a ↔ b) : a ↔ ¬b := not_not.symm.trans h.not protected lemma Iff.ne {α β : Sort*} {a b : α} {c d : β} : (a = b ↔ c = d) → (a ≠ b ↔ c ≠ d) := Iff.not lemma Iff.ne_left {α β : Sort*} {a b : α} {c d : β} : (a = b ↔ c ≠ d) → (a ≠ b ↔ c = d) := Iff.not_left lemma Iff.ne_right {α β : Sort*} {a b : α} {c d : β} : (a ≠ b ↔ c = d) → (a = b ↔ c ≠ d) := Iff.not_right /-! ### Declarations about `Xor'` -/ @[simp] theorem xor_true : Xor' True = Not := by simp (config := { unfoldPartialApp := true }) [Xor'] @[simp] theorem xor_false : Xor' False = id := by ext; simp [Xor'] theorem xor_comm (a b : Prop) : Xor' a b = Xor' b a := by simp [Xor', and_comm, or_comm] instance : Std.Commutative Xor' := ⟨xor_comm⟩ @[simp] theorem xor_self (a : Prop) : Xor' a a = False := by simp [Xor'] @[simp] theorem xor_not_left : Xor' (¬a) b ↔ (a ↔ b) := by by_cases a <;> simp [*] @[simp] theorem xor_not_right : Xor' a (¬b) ↔ (a ↔ b) := by by_cases a <;> simp [*] theorem xor_not_not : Xor' (¬a) (¬b) ↔ Xor' a b := by simp [Xor', or_comm, and_comm] protected theorem Xor'.or (h : Xor' a b) : a ∨ b := h.imp And.left And.left /-! ### Declarations about `and` -/ alias Iff.and := and_congr alias ⟨And.rotate, _⟩ := and_rotate theorem and_symm_right {α : Sort*} (a b : α) (p : Prop) : p ∧ a = b ↔ p ∧ b = a := by simp [eq_comm] theorem and_symm_left {α : Sort*} (a b : α) (p : Prop) : a = b ∧ p ↔ b = a ∧ p := by simp [eq_comm] /-! ### Declarations about `or` -/ alias Iff.or := or_congr alias ⟨Or.rotate, _⟩ := or_rotate theorem Or.elim3 {c d : Prop} (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := Or.elim h ha fun h₂ ↦ Or.elim h₂ hb hc theorem Or.imp3 {d e c f : Prop} (had : a → d) (hbe : b → e) (hcf : c → f) : a ∨ b ∨ c → d ∨ e ∨ f := Or.imp had <| Or.imp hbe hcf export Classical (or_iff_not_imp_left or_iff_not_imp_right) theorem not_or_of_imp : (a → b) → ¬a ∨ b := Decidable.not_or_of_imp -- See Note [decidable namespace] protected theorem Decidable.or_not_of_imp [Decidable a] (h : a → b) : b ∨ ¬a := dite _ (Or.inl ∘ h) Or.inr theorem or_not_of_imp : (a → b) → b ∨ ¬a := Decidable.or_not_of_imp theorem imp_iff_not_or : a → b ↔ ¬a ∨ b := Decidable.imp_iff_not_or theorem imp_iff_or_not {b a : Prop} : b → a ↔ a ∨ ¬b := Decidable.imp_iff_or_not theorem not_imp_not : ¬a → ¬b ↔ b → a := Decidable.not_imp_not theorem imp_and_neg_imp_iff (p q : Prop) : (p → q) ∧ (¬p → q) ↔ q := by simp /-- Provide the reverse of modus tollens (`mt`) as dot notation for implications. -/ protected theorem Function.mtr : (¬a → ¬b) → b → a := not_imp_not.mp theorem or_congr_left' {c a b : Prop} (h : ¬c → (a ↔ b)) : a ∨ c ↔ b ∨ c := Decidable.or_congr_left' h theorem or_congr_right' {c : Prop} (h : ¬a → (b ↔ c)) : a ∨ b ↔ a ∨ c := Decidable.or_congr_right' h /-! ### Declarations about distributivity -/ /-! Declarations about `iff` -/ alias Iff.iff := iff_congr -- @[simp] -- FIXME simp ignores proof rewrites theorem iff_mpr_iff_true_intro {P : Prop} (h : P) : Iff.mpr (iff_true_intro h) True.intro = h := rfl theorem imp_or {a b c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) := Decidable.imp_or theorem imp_or' {a : Sort*} {b c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) := Decidable.imp_or' theorem not_imp : ¬(a → b) ↔ a ∧ ¬b := Decidable.not_imp_iff_and_not theorem peirce (a b : Prop) : ((a → b) → a) → a := Decidable.peirce _ _ theorem not_iff_not : (¬a ↔ ¬b) ↔ (a ↔ b) := Decidable.not_iff_not theorem not_iff_comm : (¬a ↔ b) ↔ (¬b ↔ a) := Decidable.not_iff_comm theorem not_iff : ¬(a ↔ b) ↔ (¬a ↔ b) := Decidable.not_iff theorem iff_not_comm : (a ↔ ¬b) ↔ (b ↔ ¬a) := Decidable.iff_not_comm theorem iff_iff_and_or_not_and_not : (a ↔ b) ↔ a ∧ b ∨ ¬a ∧ ¬b := Decidable.iff_iff_and_or_not_and_not theorem iff_iff_not_or_and_or_not : (a ↔ b) ↔ (¬a ∨ b) ∧ (a ∨ ¬b) := Decidable.iff_iff_not_or_and_or_not theorem not_and_not_right : ¬(a ∧ ¬b) ↔ a → b := Decidable.not_and_not_right /-! ### De Morgan's laws -/ /-- One of **de Morgan's laws**: the negation of a conjunction is logically equivalent to the disjunction of the negations. -/ theorem not_and_or : ¬(a ∧ b) ↔ ¬a ∨ ¬b := Decidable.not_and_iff_or_not_not theorem or_iff_not_and_not : a ∨ b ↔ ¬(¬a ∧ ¬b) := Decidable.or_iff_not_and_not theorem and_iff_not_or_not : a ∧ b ↔ ¬(¬a ∨ ¬b) := Decidable.and_iff_not_or_not @[simp] theorem not_xor (P Q : Prop) : ¬Xor' P Q ↔ (P ↔ Q) := by simp only [not_and, Xor', not_or, not_not, ← iff_iff_implies_and_implies] theorem xor_iff_not_iff (P Q : Prop) : Xor' P Q ↔ ¬ (P ↔ Q) := (not_xor P Q).not_right theorem xor_iff_iff_not : Xor' a b ↔ (a ↔ ¬b) := by simp only [← @xor_not_right a, not_not] theorem xor_iff_not_iff' : Xor' a b ↔ (¬a ↔ b) := by simp only [← @xor_not_left _ b, not_not] end Propositional /-! ### Declarations about equality -/ alias Membership.mem.ne_of_not_mem := ne_of_mem_of_not_mem alias Membership.mem.ne_of_not_mem' := ne_of_mem_of_not_mem' section Equality -- todo: change name theorem forall_cond_comm {α} {s : α → Prop} {p : α → α → Prop} : (∀ a, s a → ∀ b, s b → p a b) ↔ ∀ a b, s a → s b → p a b := ⟨fun h a b ha hb ↦ h a ha b hb, fun h a ha b hb ↦ h a b ha hb⟩ theorem forall_mem_comm {α β} [Membership α β] {s : β} {p : α → α → Prop} : (∀ a (_ : a ∈ s) b (_ : b ∈ s), p a b) ↔ ∀ a b, a ∈ s → b ∈ s → p a b := forall_cond_comm @[deprecated (since := "2024-03-23")] alias ball_cond_comm := forall_cond_comm @[deprecated (since := "2024-03-23")] alias ball_mem_comm := forall_mem_comm lemma ne_of_eq_of_ne {α : Sort*} {a b c : α} (h₁ : a = b) (h₂ : b ≠ c) : a ≠ c := h₁.symm ▸ h₂ lemma ne_of_ne_of_eq {α : Sort*} {a b c : α} (h₁ : a ≠ b) (h₂ : b = c) : a ≠ c := h₂ ▸ h₁ alias Eq.trans_ne := ne_of_eq_of_ne alias Ne.trans_eq := ne_of_ne_of_eq theorem eq_equivalence {α : Sort*} : Equivalence (@Eq α) := ⟨Eq.refl, @Eq.symm _, @Eq.trans _⟩ -- These were migrated to Batteries but the `@[simp]` attributes were (mysteriously?) removed. attribute [simp] eq_mp_eq_cast eq_mpr_eq_cast -- @[simp] -- FIXME simp ignores proof rewrites theorem congr_refl_left {α β : Sort*} (f : α → β) {a b : α} (h : a = b) : congr (Eq.refl f) h = congr_arg f h := rfl -- @[simp] -- FIXME simp ignores proof rewrites theorem congr_refl_right {α β : Sort*} {f g : α → β} (h : f = g) (a : α) : congr h (Eq.refl a) = congr_fun h a := rfl -- @[simp] -- FIXME simp ignores proof rewrites theorem congr_arg_refl {α β : Sort*} (f : α → β) (a : α) : congr_arg f (Eq.refl a) = Eq.refl (f a) := rfl -- @[simp] -- FIXME simp ignores proof rewrites theorem congr_fun_rfl {α β : Sort*} (f : α → β) (a : α) : congr_fun (Eq.refl f) a = Eq.refl (f a) := rfl -- @[simp] -- FIXME simp ignores proof rewrites theorem congr_fun_congr_arg {α β γ : Sort*} (f : α → β → γ) {a a' : α} (p : a = a') (b : β) : congr_fun (congr_arg f p) b = congr_arg (fun a ↦ f a b) p := rfl theorem Eq.rec_eq_cast {α : Sort _} {P : α → Sort _} {x y : α} (h : x = y) (z : P x) : h ▸ z = cast (congr_arg P h) z := by induction h; rfl theorem eqRec_heq' {α : Sort*} {a' : α} {motive : (a : α) → a' = a → Sort*} (p : motive a' (rfl : a' = a')) {a : α} (t : a' = a) : HEq (@Eq.rec α a' motive p a t) p := by subst t; rfl set_option autoImplicit true in theorem rec_heq_of_heq {C : α → Sort*} {x : C a} {y : β} (e : a = b) (h : HEq x y) : HEq (e ▸ x) y := by subst e; exact h set_option autoImplicit true in theorem rec_heq_iff_heq {C : α → Sort*} {x : C a} {y : β} {e : a = b} : HEq (e ▸ x) y ↔ HEq x y := by subst e; rfl set_option autoImplicit true in theorem heq_rec_iff_heq {C : α → Sort*} {x : β} {y : C a} {e : a = b} : HEq x (e ▸ y) ↔ HEq x y := by subst e; rfl end Equality /-! ### Declarations about quantifiers -/ section Quantifiers section Dependent variable {α : Sort*} {β : α → Sort*} {γ : ∀ a, β a → Sort*} {δ : ∀ a b, γ a b → Sort*} {ε : ∀ a b c, δ a b c → Sort*} theorem pi_congr {β' : α → Sort _} (h : ∀ a, β a = β' a) : (∀ a, β a) = ∀ a, β' a := (funext h : β = β') ▸ rfl -- Porting note: some higher order lemmas such as `forall₂_congr` and `exists₂_congr` -- were moved to `Batteries` theorem forall₂_imp {p q : ∀ a, β a → Prop} (h : ∀ a b, p a b → q a b) : (∀ a b, p a b) → ∀ a b, q a b := forall_imp fun i ↦ forall_imp <| h i theorem forall₃_imp {p q : ∀ a b, γ a b → Prop} (h : ∀ a b c, p a b c → q a b c) : (∀ a b c, p a b c) → ∀ a b c, q a b c := forall_imp fun a ↦ forall₂_imp <| h a theorem Exists₂.imp {p q : ∀ a, β a → Prop} (h : ∀ a b, p a b → q a b) : (∃ a b, p a b) → ∃ a b, q a b := Exists.imp fun a ↦ Exists.imp <| h a theorem Exists₃.imp {p q : ∀ a b, γ a b → Prop} (h : ∀ a b c, p a b c → q a b c) : (∃ a b c, p a b c) → ∃ a b c, q a b c := Exists.imp fun a ↦ Exists₂.imp <| h a end Dependent variable {α β : Sort*} {p q : α → Prop} theorem forall_swap {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y := ⟨fun f x y ↦ f y x, fun f x y ↦ f y x⟩ theorem forall₂_swap {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {p : ∀ i₁, κ₁ i₁ → ∀ i₂, κ₂ i₂ → Prop} : (∀ i₁ j₁ i₂ j₂, p i₁ j₁ i₂ j₂) ↔ ∀ i₂ j₂ i₁ j₁, p i₁ j₁ i₂ j₂ := ⟨swap₂, swap₂⟩ /-- We intentionally restrict the type of `α` in this lemma so that this is a safer to use in simp than `forall_swap`. -/ theorem imp_forall_iff {α : Type*} {p : Prop} {q : α → Prop} : (p → ∀ x, q x) ↔ ∀ x, p → q x := forall_swap theorem exists_swap {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y := ⟨fun ⟨x, y, h⟩ ↦ ⟨y, x, h⟩, fun ⟨y, x, h⟩ ↦ ⟨x, y, h⟩⟩ export Classical (not_forall) theorem not_forall_not : (¬∀ x, ¬p x) ↔ ∃ x, p x := Decidable.not_forall_not export Classical (not_exists_not) lemma forall_or_exists_not (P : α → Prop) : (∀ a, P a) ∨ ∃ a, ¬ P a := by rw [← not_forall]; exact em _ lemma exists_or_forall_not (P : α → Prop) : (∃ a, P a) ∨ ∀ a, ¬ P a := by rw [← not_exists]; exact em _ theorem forall_imp_iff_exists_imp {α : Sort*} {p : α → Prop} {b : Prop} [ha : Nonempty α] : (∀ x, p x) → b ↔ ∃ x, p x → b := by let ⟨a⟩ := ha refine ⟨fun h ↦ not_forall_not.1 fun h' ↦ ?_, fun ⟨x, hx⟩ h ↦ hx (h x)⟩ exact if hb : b then h' a fun _ ↦ hb else hb <| h fun x ↦ (_root_.not_imp.1 (h' x)).1 @[mfld_simps] theorem forall_true_iff : (α → True) ↔ True := imp_true_iff _ -- Unfortunately this causes simp to loop sometimes, so we -- add the 2 and 3 cases as simp lemmas instead theorem forall_true_iff' (h : ∀ a, p a ↔ True) : (∀ a, p a) ↔ True := iff_true_intro fun _ ↦ of_iff_true (h _) -- This is not marked `@[simp]` because `implies_true : (α → True) = True` works theorem forall₂_true_iff {β : α → Sort*} : (∀ a, β a → True) ↔ True := by simp -- This is not marked `@[simp]` because `implies_true : (α → True) = True` works theorem forall₃_true_iff {β : α → Sort*} {γ : ∀ a, β a → Sort*} : (∀ (a) (b : β a), γ a b → True) ↔ True := by simp @[simp] theorem exists_unique_iff_exists [Subsingleton α] {p : α → Prop} : (∃! x, p x) ↔ ∃ x, p x := ⟨fun h ↦ h.exists, Exists.imp fun x hx ↦ ⟨hx, fun y _ ↦ Subsingleton.elim y x⟩⟩ -- forall_forall_const is no longer needed theorem exists_unique_const {b : Prop} (α : Sort*) [i : Nonempty α] [Subsingleton α] : (∃! _ : α, b) ↔ b := by simp theorem Decidable.and_forall_ne [DecidableEq α] (a : α) {p : α → Prop} : (p a ∧ ∀ b, b ≠ a → p b) ↔ ∀ b, p b := by simp only [← @forall_eq _ p a, ← forall_and, ← or_imp, Decidable.em, forall_const] theorem and_forall_ne (a : α) : (p a ∧ ∀ b, b ≠ a → p b) ↔ ∀ b, p b := Decidable.and_forall_ne a theorem Ne.ne_or_ne {x y : α} (z : α) (h : x ≠ y) : x ≠ z ∨ y ≠ z := not_and_or.1 <| mt (and_imp.2 (· ▸ ·)) h.symm @[simp] theorem exists_unique_eq {a' : α} : ∃! a, a = a' := by simp only [eq_comm, ExistsUnique, and_self, forall_eq', exists_eq'] @[simp] theorem exists_unique_eq' {a' : α} : ∃! a, a' = a := by simp only [ExistsUnique, and_self, forall_eq', exists_eq'] @[simp] theorem exists_apply_eq_apply' (f : α → β) (a' : α) : ∃ a, f a' = f a := ⟨a', rfl⟩ @[simp] lemma exists_apply_eq_apply2 {α β γ} {f : α → β → γ} {a : α} {b : β} : ∃ x y, f x y = f a b := ⟨a, b, rfl⟩ @[simp] lemma exists_apply_eq_apply2' {α β γ} {f : α → β → γ} {a : α} {b : β} : ∃ x y, f a b = f x y := ⟨a, b, rfl⟩ @[simp] lemma exists_apply_eq_apply3 {α β γ δ} {f : α → β → γ → δ} {a : α} {b : β} {c : γ} : ∃ x y z, f x y z = f a b c := ⟨a, b, c, rfl⟩ @[simp] lemma exists_apply_eq_apply3' {α β γ δ} {f : α → β → γ → δ} {a : α} {b : β} {c : γ} : ∃ x y z, f a b c = f x y z := ⟨a, b, c, rfl⟩ -- Porting note: an alternative workaround theorem: theorem exists_apply_eq (a : α) (b : β) : ∃ f : α → β, f a = b := ⟨fun _ ↦ b, rfl⟩ @[simp] theorem exists_exists_and_eq_and {f : α → β} {p : α → Prop} {q : β → Prop} : (∃ b, (∃ a, p a ∧ f a = b) ∧ q b) ↔ ∃ a, p a ∧ q (f a) := ⟨fun ⟨_, ⟨a, ha, hab⟩, hb⟩ ↦ ⟨a, ha, hab.symm ▸ hb⟩, fun ⟨a, hp, hq⟩ ↦ ⟨f a, ⟨a, hp, rfl⟩, hq⟩⟩ @[simp] theorem exists_exists_eq_and {f : α → β} {p : β → Prop} : (∃ b, (∃ a, f a = b) ∧ p b) ↔ ∃ a, p (f a) := ⟨fun ⟨_, ⟨a, ha⟩, hb⟩ ↦ ⟨a, ha.symm ▸ hb⟩, fun ⟨a, ha⟩ ↦ ⟨f a, ⟨a, rfl⟩, ha⟩⟩ @[simp] theorem exists_exists_and_exists_and_eq_and {α β γ : Type*} {f : α → β → γ} {p : α → Prop} {q : β → Prop} {r : γ → Prop} : (∃ c, (∃ a, p a ∧ ∃ b, q b ∧ f a b = c) ∧ r c) ↔ ∃ a, p a ∧ ∃ b, q b ∧ r (f a b) := ⟨fun ⟨_, ⟨a, ha, b, hb, hab⟩, hc⟩ ↦ ⟨a, ha, b, hb, hab.symm ▸ hc⟩, fun ⟨a, ha, b, hb, hab⟩ ↦ ⟨f a b, ⟨a, ha, b, hb, rfl⟩, hab⟩⟩ @[simp] theorem exists_exists_exists_and_eq {α β γ : Type*} {f : α → β → γ} {p : γ → Prop} : (∃ c, (∃ a, ∃ b, f a b = c) ∧ p c) ↔ ∃ a, ∃ b, p (f a b) := ⟨fun ⟨_, ⟨a, b, hab⟩, hc⟩ ↦ ⟨a, b, hab.symm ▸ hc⟩, fun ⟨a, b, hab⟩ ↦ ⟨f a b, ⟨a, b, rfl⟩, hab⟩⟩ theorem forall_apply_eq_imp_iff' {f : α → β} {p : β → Prop} : (∀ a b, f a = b → p b) ↔ ∀ a, p (f a) := by simp theorem forall_eq_apply_imp_iff' {f : α → β} {p : β → Prop} : (∀ a b, b = f a → p b) ↔ ∀ a, p (f a) := by simp theorem exists₂_comm {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {p : ∀ i₁, κ₁ i₁ → ∀ i₂, κ₂ i₂ → Prop} : (∃ i₁ j₁ i₂ j₂, p i₁ j₁ i₂ j₂) ↔ ∃ i₂ j₂ i₁ j₁, p i₁ j₁ i₂ j₂ := by simp only [@exists_comm (κ₁ _), @exists_comm ι₁] theorem And.exists {p q : Prop} {f : p ∧ q → Prop} : (∃ h, f h) ↔ ∃ hp hq, f ⟨hp, hq⟩ := ⟨fun ⟨h, H⟩ ↦ ⟨h.1, h.2, H⟩, fun ⟨hp, hq, H⟩ ↦ ⟨⟨hp, hq⟩, H⟩⟩ theorem forall_or_of_or_forall {α : Sort*} {p : α → Prop} {b : Prop} (h : b ∨ ∀ x, p x) (x : α) : b ∨ p x := h.imp_right fun h₂ ↦ h₂ x -- See Note [decidable namespace] protected theorem Decidable.forall_or_left {q : Prop} {p : α → Prop} [Decidable q] : (∀ x, q ∨ p x) ↔ q ∨ ∀ x, p x := ⟨fun h ↦ if hq : q then Or.inl hq else Or.inr fun x ↦ (h x).resolve_left hq, forall_or_of_or_forall⟩ theorem forall_or_left {q} {p : α → Prop} : (∀ x, q ∨ p x) ↔ q ∨ ∀ x, p x := Decidable.forall_or_left -- See Note [decidable namespace] protected theorem Decidable.forall_or_right {q} {p : α → Prop} [Decidable q] : (∀ x, p x ∨ q) ↔ (∀ x, p x) ∨ q := by simp [or_comm, Decidable.forall_or_left] theorem forall_or_right {q} {p : α → Prop} : (∀ x, p x ∨ q) ↔ (∀ x, p x) ∨ q := Decidable.forall_or_right theorem exists_unique_prop {p q : Prop} : (∃! _ : p, q) ↔ p ∧ q := by simp @[simp] theorem exists_unique_false : ¬∃! _ : α, False := fun ⟨_, h, _⟩ ↦ h theorem Exists.fst {b : Prop} {p : b → Prop} : Exists p → b | ⟨h, _⟩ => h theorem Exists.snd {b : Prop} {p : b → Prop} : ∀ h : Exists p, p h.fst | ⟨_, h⟩ => h theorem Prop.exists_iff {p : Prop → Prop} : (∃ h, p h) ↔ p False ∨ p True := ⟨fun ⟨h₁, h₂⟩ ↦ by_cases (fun H : h₁ ↦ .inr <| by simpa only [H] using h₂) (fun H ↦ .inl <| by simpa only [H] using h₂), fun h ↦ h.elim (.intro _) (.intro _)⟩ theorem Prop.forall_iff {p : Prop → Prop} : (∀ h, p h) ↔ p False ∧ p True := ⟨fun H ↦ ⟨H _, H _⟩, fun ⟨h₁, h₂⟩ h ↦ by by_cases H : h <;> simpa only [H]⟩ theorem exists_iff_of_forall {p : Prop} {q : p → Prop} (h : ∀ h, q h) : (∃ h, q h) ↔ p := ⟨Exists.fst, fun H ↦ ⟨H, h H⟩⟩ theorem exists_unique_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃! h' : p, q h') ↔ q h := @exists_unique_const (q h) p ⟨h⟩ _ theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬p → ¬∃ h' : p, q h' := mt Exists.fst /- See `IsEmpty.exists_iff` for the `False` version of `exists_true_left`. -/ -- Porting note: `@[congr]` commented out for now. -- @[congr] theorem forall_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) ↔ ∀ h : p', q' (hp.2 h) := ⟨fun h1 h2 ↦ (hq _).1 (h1 (hp.2 h2)), fun h1 h2 ↦ (hq _).2 (h1 (hp.1 h2))⟩ -- Porting note: `@[congr]` commented out for now. -- @[congr] theorem forall_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) = ∀ h : p', q' (hp.2 h) := propext (forall_prop_congr hq hp) lemma imp_congr_eq {a b c d : Prop} (h₁ : a = c) (h₂ : b = d) : (a → b) = (c → d) := propext (imp_congr h₁.to_iff h₂.to_iff) lemma imp_congr_ctx_eq {a b c d : Prop} (h₁ : a = c) (h₂ : c → b = d) : (a → b) = (c → d) := propext (imp_congr_ctx h₁.to_iff fun hc ↦ (h₂ hc).to_iff) lemma eq_true_intro {a : Prop} (h : a) : a = True := propext (iff_true_intro h) lemma eq_false_intro {a : Prop} (h : ¬a) : a = False := propext (iff_false_intro h) -- FIXME: `alias` creates `def Iff.eq := propext` instead of `lemma Iff.eq := propext` @[nolint defLemma] alias Iff.eq := propext lemma iff_eq_eq {a b : Prop} : (a ↔ b) = (a = b) := propext ⟨propext, Eq.to_iff⟩ -- They were not used in Lean 3 and there are already lemmas with those names in Lean 4 /-- See `IsEmpty.forall_iff` for the `False` version. -/ @[simp] theorem forall_true_left (p : True → Prop) : (∀ x, p x) ↔ p True.intro := forall_prop_of_true _ theorem ExistsUnique.elim₂ {α : Sort*} {p : α → Sort*} [∀ x, Subsingleton (p x)] {q : ∀ (x) (_ : p x), Prop} {b : Prop} (h₂ : ∃! x, ∃! h : p x, q x h) (h₁ : ∀ (x) (h : p x), q x h → (∀ (y) (hy : p y), q y hy → y = x) → b) : b := by simp only [exists_unique_iff_exists] at h₂ apply h₂.elim exact fun x ⟨hxp, hxq⟩ H ↦ h₁ x hxp hxq fun y hyp hyq ↦ H y ⟨hyp, hyq⟩ theorem ExistsUnique.intro₂ {α : Sort*} {p : α → Sort*} [∀ x, Subsingleton (p x)] {q : ∀ (x : α) (_ : p x), Prop} (w : α) (hp : p w) (hq : q w hp) (H : ∀ (y) (hy : p y), q y hy → y = w) : ∃! x, ∃! hx : p x, q x hx := by simp only [exists_unique_iff_exists] exact ExistsUnique.intro w ⟨hp, hq⟩ fun y ⟨hyp, hyq⟩ ↦ H y hyp hyq theorem ExistsUnique.exists₂ {α : Sort*} {p : α → Sort*} {q : ∀ (x : α) (_ : p x), Prop} (h : ∃! x, ∃! hx : p x, q x hx) : ∃ (x : _) (hx : p x), q x hx := h.exists.imp fun _ hx ↦ hx.exists theorem ExistsUnique.unique₂ {α : Sort*} {p : α → Sort*} [∀ x, Subsingleton (p x)] {q : ∀ (x : α) (_ : p x), Prop} (h : ∃! x, ∃! hx : p x, q x hx) {y₁ y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ := by simp only [exists_unique_iff_exists] at h exact h.unique ⟨hpy₁, hqy₁⟩ ⟨hpy₂, hqy₂⟩ end Quantifiers /-! ### Classical lemmas -/ namespace Classical -- use shortened names to avoid conflict when classical namespace is open. /-- Any prop `p` is decidable classically. A shorthand for `Classical.propDecidable`. -/ noncomputable def dec (p : Prop) : Decidable p := by infer_instance variable {α : Sort*} {p : α → Prop} /-- Any predicate `p` is decidable classically. -/ noncomputable def decPred (p : α → Prop) : DecidablePred p := by infer_instance /-- Any relation `p` is decidable classically. -/ noncomputable def decRel (p : α → α → Prop) : DecidableRel p := by infer_instance /-- Any type `α` has decidable equality classically. -/ noncomputable def decEq (α : Sort*) : DecidableEq α := by infer_instance /-- Construct a function from a default value `H0`, and a function to use if there exists a value satisfying the predicate. -/ -- @[elab_as_elim] -- FIXME noncomputable def existsCases {α C : Sort*} {p : α → Prop} (H0 : C) (H : ∀ a, p a → C) : C := if h : ∃ a, p a then H (Classical.choose h) (Classical.choose_spec h) else H0 theorem some_spec₂ {α : Sort*} {p : α → Prop} {h : ∃ a, p a} (q : α → Prop) (hpq : ∀ a, p a → q a) : q (choose h) := hpq _ <| choose_spec _ /-- A version of `Classical.indefiniteDescription` which is definitionally equal to a pair. In Lean 4, this definition is defeq to `Classical.indefiniteDescription`, so it is deprecated. -/ @[deprecated Classical.indefiniteDescription (since := "2024-07-04")] noncomputable def subtype_of_exists {α : Type*} {P : α → Prop} (h : ∃ x, P x) : { x // P x } := ⟨Classical.choose h, Classical.choose_spec h⟩ /-- A version of `byContradiction` that uses types instead of propositions. -/ protected noncomputable def byContradiction' {α : Sort*} (H : ¬(α → False)) : α := Classical.choice <| (peirce _ False) fun h ↦ (H fun a ↦ h ⟨a⟩).elim /-- `Classical.byContradiction'` is equivalent to lean's axiom `Classical.choice`. -/ def choice_of_byContradiction' {α : Sort*} (contra : ¬(α → False) → α) : Nonempty α → α := fun H ↦ contra H.elim @[simp] lemma choose_eq (a : α) : @Exists.choose _ (· = a) ⟨a, rfl⟩ = a := @choose_spec _ (· = a) _ @[simp] lemma choose_eq' (a : α) : @Exists.choose _ (a = ·) ⟨a, rfl⟩ = a := (@choose_spec _ (a = ·) _).symm end Classical /-- This function has the same type as `Exists.recOn`, and can be used to case on an equality, but `Exists.recOn` can only eliminate into Prop, while this version eliminates into any universe using the axiom of choice. -/ -- @[elab_as_elim] -- FIXME noncomputable def Exists.classicalRecOn {α : Sort*} {p : α → Prop} (h : ∃ a, p a) {C : Sort*} (H : ∀ a, p a → C) : C := H (Classical.choose h) (Classical.choose_spec h) /-! ### Declarations about bounded quantifiers -/ section BoundedQuantifiers variable {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop} theorem bex_def : (∃ (x : _) (_ : p x), q x) ↔ ∃ x, p x ∧ q x := ⟨fun ⟨x, px, qx⟩ ↦ ⟨x, px, qx⟩, fun ⟨x, px, qx⟩ ↦ ⟨x, px, qx⟩⟩ theorem BEx.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b | ⟨a, h₁, h₂⟩, h' => h' a h₁ h₂ theorem BEx.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ (x : _) (h : p x), P x h := ⟨a, h₁, h₂⟩ @[deprecated exists_eq_left (since := "2024-04-06")] theorem bex_eq_left {a : α} : (∃ (x : _) (_ : x = a), p x) ↔ p a := by simp only [exists_prop, exists_eq_left] @[deprecated (since := "2024-04-06")] alias ball_congr := forall₂_congr @[deprecated (since := "2024-04-06")] alias bex_congr := exists₂_congr theorem BAll.imp_right (H : ∀ x h, P x h → Q x h) (h₁ : ∀ x h, P x h) (x h) : Q x h := H _ _ <| h₁ _ _ theorem BEx.imp_right (H : ∀ x h, P x h → Q x h) : (∃ x h, P x h) → ∃ x h, Q x h | ⟨_, _, h'⟩ => ⟨_, _, H _ _ h'⟩ theorem BAll.imp_left (H : ∀ x, p x → q x) (h₁ : ∀ x, q x → r x) (x) (h : p x) : r x := h₁ _ <| H _ h theorem BEx.imp_left (H : ∀ x, p x → q x) : (∃ (x : _) (_ : p x), r x) → ∃ (x : _) (_ : q x), r x | ⟨x, hp, hr⟩ => ⟨x, H _ hp, hr⟩ @[deprecated id (since := "2024-03-23")] theorem ball_of_forall (h : ∀ x, p x) (x) : p x := h x @[deprecated forall_imp (since := "2024-03-23")] theorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x := h x <| H x theorem exists_mem_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ (x : _) (_ : p x), q x | ⟨x, hq⟩ => ⟨x, H x, hq⟩ theorem exists_of_exists_mem : (∃ (x : _) (_ : p x), q x) → ∃ x, q x | ⟨x, _, hq⟩ => ⟨x, hq⟩ theorem exists₂_imp : (∃ x h, P x h) → b ↔ ∀ x h, P x h → b := by simp @[deprecated (since := "2024-03-23")] alias bex_of_exists := exists_mem_of_exists @[deprecated (since := "2024-03-23")] alias exists_of_bex := exists_of_exists_mem @[deprecated (since := "2024-03-23")] alias bex_imp := exists₂_imp theorem not_exists_mem : (¬∃ x h, P x h) ↔ ∀ x h, ¬P x h := exists₂_imp theorem not_forall₂_of_exists₂_not : (∃ x h, ¬P x h) → ¬∀ x h, P x h | ⟨x, h, hp⟩, al => hp <| al x h -- See Note [decidable namespace] protected theorem Decidable.not_forall₂ [Decidable (∃ x h, ¬P x h)] [∀ x h, Decidable (P x h)] : (¬∀ x h, P x h) ↔ ∃ x h, ¬P x h := ⟨Not.decidable_imp_symm fun nx x h ↦ nx.decidable_imp_symm fun h' ↦ ⟨x, h, h'⟩, not_forall₂_of_exists₂_not⟩ theorem not_forall₂ : (¬∀ x h, P x h) ↔ ∃ x h, ¬P x h := Decidable.not_forall₂ theorem forall₂_and : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ ∀ x h, Q x h := Iff.trans (forall_congr' fun _ ↦ forall_and) forall_and theorem forall_and_left [Nonempty α] (q : Prop) (p : α → Prop) : (∀ x, q ∧ p x) ↔ (q ∧ ∀ x, p x) := by rw [forall_and, forall_const] theorem forall_and_right [Nonempty α] (p : α → Prop) (q : Prop) : (∀ x, p x ∧ q) ↔ (∀ x, p x) ∧ q := by rw [forall_and, forall_const] theorem exists_mem_or : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ ∃ x h, Q x h := Iff.trans (exists_congr fun _ ↦ exists_or) exists_or theorem forall₂_or_left : (∀ x, p x ∨ q x → r x) ↔ (∀ x, p x → r x) ∧ ∀ x, q x → r x := Iff.trans (forall_congr' fun _ ↦ or_imp) forall_and theorem exists_mem_or_left : (∃ (x : _) (_ : p x ∨ q x), r x) ↔ (∃ (x : _) (_ : p x), r x) ∨ ∃ (x : _) (_ : q x), r x := by simp only [exists_prop] exact Iff.trans (exists_congr fun x ↦ or_and_right) exists_or end BoundedQuantifiers section ite variable {α : Sort*} {σ : α → Sort*} {P Q R : Prop} [Decidable P] [Decidable Q] {a b c : α} {A : P → α} {B : ¬P → α} theorem dite_eq_iff : dite P A B = c ↔ (∃ h, A h = c) ∨ ∃ h, B h = c := by by_cases P <;> simp [*, exists_prop_of_true, exists_prop_of_false] theorem ite_eq_iff : ite P a b = c ↔ P ∧ a = c ∨ ¬P ∧ b = c := dite_eq_iff.trans <| by rw [exists_prop, exists_prop] theorem eq_ite_iff : a = ite P b c ↔ P ∧ a = b ∨ ¬P ∧ a = c := eq_comm.trans <| ite_eq_iff.trans <| (Iff.rfl.and eq_comm).or (Iff.rfl.and eq_comm) theorem dite_eq_iff' : dite P A B = c ↔ (∀ h, A h = c) ∧ ∀ h, B h = c := ⟨fun he ↦ ⟨fun h ↦ (dif_pos h).symm.trans he, fun h ↦ (dif_neg h).symm.trans he⟩, fun he ↦ (em P).elim (fun h ↦ (dif_pos h).trans <| he.1 h) fun h ↦ (dif_neg h).trans <| he.2 h⟩ theorem ite_eq_iff' : ite P a b = c ↔ (P → a = c) ∧ (¬P → b = c) := dite_eq_iff' theorem dite_ne_left_iff : dite P (fun _ ↦ a) B ≠ a ↔ ∃ h, a ≠ B h := by rw [Ne, dite_eq_left_iff, not_forall] exact exists_congr fun h ↦ by rw [ne_comm] theorem dite_ne_right_iff : (dite P A fun _ ↦ b) ≠ b ↔ ∃ h, A h ≠ b := by simp only [Ne, dite_eq_right_iff, not_forall] theorem ite_ne_left_iff : ite P a b ≠ a ↔ ¬P ∧ a ≠ b := dite_ne_left_iff.trans <| by rw [exists_prop] theorem ite_ne_right_iff : ite P a b ≠ b ↔ P ∧ a ≠ b := dite_ne_right_iff.trans <| by rw [exists_prop] protected theorem Ne.dite_eq_left_iff (h : ∀ h, a ≠ B h) : dite P (fun _ ↦ a) B = a ↔ P := dite_eq_left_iff.trans ⟨fun H ↦ of_not_not fun h' ↦ h h' (H h').symm, fun h H ↦ (H h).elim⟩ protected theorem Ne.dite_eq_right_iff (h : ∀ h, A h ≠ b) : (dite P A fun _ ↦ b) = b ↔ ¬P := dite_eq_right_iff.trans ⟨fun H h' ↦ h h' (H h'), fun h' H ↦ (h' H).elim⟩ protected theorem Ne.ite_eq_left_iff (h : a ≠ b) : ite P a b = a ↔ P := Ne.dite_eq_left_iff fun _ ↦ h protected theorem Ne.ite_eq_right_iff (h : a ≠ b) : ite P a b = b ↔ ¬P := Ne.dite_eq_right_iff fun _ ↦ h protected theorem Ne.dite_ne_left_iff (h : ∀ h, a ≠ B h) : dite P (fun _ ↦ a) B ≠ a ↔ ¬P := dite_ne_left_iff.trans <| exists_iff_of_forall h protected theorem Ne.dite_ne_right_iff (h : ∀ h, A h ≠ b) : (dite P A fun _ ↦ b) ≠ b ↔ P := dite_ne_right_iff.trans <| exists_iff_of_forall h protected theorem Ne.ite_ne_left_iff (h : a ≠ b) : ite P a b ≠ a ↔ ¬P := Ne.dite_ne_left_iff fun _ ↦ h protected theorem Ne.ite_ne_right_iff (h : a ≠ b) : ite P a b ≠ b ↔ P := Ne.dite_ne_right_iff fun _ ↦ h variable (P Q a b) theorem dite_eq_or_eq : (∃ h, dite P A B = A h) ∨ ∃ h, dite P A B = B h := if h : _ then .inl ⟨h, dif_pos h⟩ else .inr ⟨h, dif_neg h⟩ theorem ite_eq_or_eq : ite P a b = a ∨ ite P a b = b := if h : _ then .inl (if_pos h) else .inr (if_neg h) /-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function applied to each of the branches. -/ theorem apply_dite₂ {α β γ : Sort*} (f : α → β → γ) (P : Prop) [Decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) : f (dite P a b) (dite P c d) = dite P (fun h ↦ f (a h) (c h)) fun h ↦ f (b h) (d h) := by by_cases h : P <;> simp [h] /-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function applied to each of the branches. -/ theorem apply_ite₂ {α β γ : Sort*} (f : α → β → γ) (P : Prop) [Decidable P] (a b : α) (c d : β) : f (ite P a b) (ite P c d) = ite P (f a c) (f b d) := apply_dite₂ f P (fun _ ↦ a) (fun _ ↦ b) (fun _ ↦ c) fun _ ↦ d /-- A 'dite' producing a `Pi` type `Π a, σ a`, applied to a value `a : α` is a `dite` that applies either branch to `a`. -/ theorem dite_apply (f : P → ∀ a, σ a) (g : ¬P → ∀ a, σ a) (a : α) : (dite P f g) a = dite P (fun h ↦ f h a) fun h ↦ g h a := by by_cases h : P <;> simp [h] /-- A 'ite' producing a `Pi` type `Π a, σ a`, applied to a value `a : α` is a `ite` that applies either branch to `a`. -/ theorem ite_apply (f g : ∀ a, σ a) (a : α) : (ite P f g) a = ite P (f a) (g a) := dite_apply P (fun _ ↦ f) (fun _ ↦ g) a section variable [Decidable Q] theorem ite_and : ite (P ∧ Q) a b = ite P (ite Q a b) b := by by_cases hp : P <;> by_cases hq : Q <;> simp [hp, hq] theorem dite_dite_comm {B : Q → α} {C : ¬P → ¬Q → α} (h : P → ¬Q) : (if p : P then A p else if q : Q then B q else C p q) = if q : Q then B q else if p : P then A p else C p q := dite_eq_iff'.2 ⟨ fun p ↦ by rw [dif_neg (h p), dif_pos p], fun np ↦ by congr; funext _; rw [dif_neg np]⟩ theorem ite_ite_comm (h : P → ¬Q) : (if P then a else if Q then b else c) = if Q then b else if P then a else c := dite_dite_comm P Q h end variable {P Q} theorem ite_prop_iff_or : (if P then Q else R) ↔ (P ∧ Q ∨ ¬ P ∧ R) := by by_cases p : P <;> simp [p] theorem dite_prop_iff_or {Q : P → Prop} {R : ¬P → Prop} [Decidable P] : dite P Q R ↔ (∃ p, Q p) ∨ (∃ p, R p) := by by_cases h : P <;> simp [h, exists_prop_of_false, exists_prop_of_true] -- TODO make this a simp lemma in a future PR theorem ite_prop_iff_and : (if P then Q else R) ↔ ((P → Q) ∧ (¬ P → R)) := by by_cases p : P <;> simp [p] theorem dite_prop_iff_and {Q : P → Prop} {R : ¬P → Prop} [Decidable P] : dite P Q R ↔ (∀ h, Q h) ∧ (∀ h, R h) := by by_cases h : P <;> simp [h, forall_prop_of_false, forall_prop_of_true] end ite theorem not_beq_of_ne {α : Type*} [BEq α] [LawfulBEq α] {a b : α} (ne : a ≠ b) : ¬(a == b) := fun h => ne (eq_of_beq h) theorem beq_eq_decide {α : Type*} [BEq α] [LawfulBEq α] {a b : α} : (a == b) = decide (a = b) := by rw [← beq_iff_eq a b] cases a == b <;> simp @[ext] theorem beq_ext {α : Type*} (inst1 : BEq α) (inst2 : BEq α) (h : ∀ x y, @BEq.beq _ inst1 x y = @BEq.beq _ inst2 x y) : inst1 = inst2 := by have ⟨beq1⟩ := inst1 have ⟨beq2⟩ := inst2 congr funext x y exact h x y theorem lawful_beq_subsingleton {α : Type*} (inst1 : BEq α) (inst2 : BEq α) [@LawfulBEq α inst1] [@LawfulBEq α inst2] : inst1 = inst2 := by apply beq_ext intro x y simp only [beq_eq_decide]
Logic\Denumerable.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.Data.Fintype.Card import Mathlib.Data.List.MinMax import Mathlib.Data.Nat.Order.Lemmas import Mathlib.Logic.Encodable.Basic /-! # Denumerable types This file defines denumerable (countably infinite) types as a typeclass extending `Encodable`. This is used to provide explicit encode/decode functions from and to `ℕ`, with the information that those functions are inverses of each other. ## Implementation notes This property already has a name, namely `α ≃ ℕ`, but here we are interested in using it as a typeclass. -/ assert_not_exists OrderedSemiring variable {α β : Type*} /-- A denumerable type is (constructively) bijective with `ℕ`. Typeclass equivalent of `α ≃ ℕ`. -/ class Denumerable (α : Type*) extends Encodable α where /-- `decode` and `encode` are inverses. -/ decode_inv : ∀ n, ∃ a ∈ decode n, encode a = n open Nat namespace Denumerable section variable [Denumerable α] [Denumerable β] open Encodable theorem decode_isSome (α) [Denumerable α] (n : ℕ) : (decode (α := α) n).isSome := Option.isSome_iff_exists.2 <| (decode_inv n).imp fun _ => And.left /-- Returns the `n`-th element of `α` indexed by the decoding. -/ def ofNat (α) [Denumerable α] (n : ℕ) : α := Option.get _ (decode_isSome α n) @[simp] theorem decode_eq_ofNat (α) [Denumerable α] (n : ℕ) : decode (α := α) n = some (ofNat α n) := Option.eq_some_of_isSome _ @[simp] theorem ofNat_of_decode {n b} (h : decode (α := α) n = some b) : ofNat (α := α) n = b := Option.some.inj <| (decode_eq_ofNat _ _).symm.trans h @[simp] theorem encode_ofNat (n) : encode (ofNat α n) = n := by obtain ⟨a, h, e⟩ := decode_inv (α := α) n rwa [ofNat_of_decode h] @[simp] theorem ofNat_encode (a) : ofNat α (encode a) = a := ofNat_of_decode (encodek _) /-- A denumerable type is equivalent to `ℕ`. -/ def eqv (α) [Denumerable α] : α ≃ ℕ := ⟨encode, ofNat α, ofNat_encode, encode_ofNat⟩ -- See Note [lower instance priority] instance (priority := 100) : Infinite α := Infinite.of_surjective _ (eqv α).surjective /-- A type equivalent to `ℕ` is denumerable. -/ def mk' {α} (e : α ≃ ℕ) : Denumerable α where encode := e decode := some ∘ e.symm encodek _ := congr_arg some (e.symm_apply_apply _) decode_inv _ := ⟨_, rfl, e.apply_symm_apply _⟩ /-- Denumerability is conserved by equivalences. This is transitivity of equivalence the denumerable way. -/ def ofEquiv (α) {β} [Denumerable α] (e : β ≃ α) : Denumerable β := { Encodable.ofEquiv _ e with decode_inv := fun n => by -- Porting note: replaced `simp` simp_rw [Option.mem_def, decode_ofEquiv e, encode_ofEquiv e, decode_eq_ofNat, Option.map_some', Option.some_inj, exists_eq_left', Equiv.apply_symm_apply, Denumerable.encode_ofNat] } @[simp] theorem ofEquiv_ofNat (α) {β} [Denumerable α] (e : β ≃ α) (n) : @ofNat β (ofEquiv _ e) n = e.symm (ofNat α n) := by -- Porting note: added `letI` letI := ofEquiv _ e refine ofNat_of_decode ?_ rw [decode_ofEquiv e] simp /-- All denumerable types are equivalent. -/ def equiv₂ (α β) [Denumerable α] [Denumerable β] : α ≃ β := (eqv α).trans (eqv β).symm instance nat : Denumerable ℕ := ⟨fun _ => ⟨_, rfl, rfl⟩⟩ @[simp] theorem ofNat_nat (n) : ofNat ℕ n = n := rfl /-- If `α` is denumerable, then so is `Option α`. -/ instance option : Denumerable (Option α) := ⟨fun n => by cases n with | zero => refine ⟨none, ?_, encode_none⟩ rw [decode_option_zero, Option.mem_def] | succ n => refine ⟨some (ofNat α n), ?_, ?_⟩ · rw [decode_option_succ, decode_eq_ofNat, Option.map_some', Option.mem_def] rw [encode_some, encode_ofNat]⟩ set_option linter.deprecated false in /-- If `α` and `β` are denumerable, then so is their sum. -/ instance sum : Denumerable (α ⊕ β) := ⟨fun n => by suffices ∃ a ∈ @decodeSum α β _ _ n, encodeSum a = bit (bodd n) (div2 n) by simpa [bit_decomp] simp only [decodeSum, boddDiv2_eq, decode_eq_ofNat, Option.some.injEq, Option.map_some', Option.mem_def, Sum.exists] cases bodd n <;> simp [decodeSum, bit, encodeSum, Nat.two_mul]⟩ section Sigma variable {γ : α → Type*} [∀ a, Denumerable (γ a)] /-- A denumerable collection of denumerable types is denumerable. -/ instance sigma : Denumerable (Sigma γ) := ⟨fun n => by simp [decodeSigma]⟩ @[simp] theorem sigma_ofNat_val (n : ℕ) : ofNat (Sigma γ) n = ⟨ofNat α (unpair n).1, ofNat (γ _) (unpair n).2⟩ := Option.some.inj <| by rw [← decode_eq_ofNat, decode_sigma_val]; simp end Sigma /-- If `α` and `β` are denumerable, then so is their product. -/ instance prod : Denumerable (α × β) := ofEquiv _ (Equiv.sigmaEquivProd α β).symm -- Porting note: removed @[simp] - simp can prove it theorem prod_ofNat_val (n : ℕ) : ofNat (α × β) n = (ofNat α (unpair n).1, ofNat β (unpair n).2) := by simp @[simp] theorem prod_nat_ofNat : ofNat (ℕ × ℕ) = unpair := by funext; simp instance int : Denumerable ℤ := Denumerable.mk' Equiv.intEquivNat instance pnat : Denumerable ℕ+ := Denumerable.mk' Equiv.pnatEquivNat /-- The lift of a denumerable type is denumerable. -/ instance ulift : Denumerable (ULift α) := ofEquiv _ Equiv.ulift /-- The lift of a denumerable type is denumerable. -/ instance plift : Denumerable (PLift α) := ofEquiv _ Equiv.plift /-- If `α` is denumerable, then `α × α` and `α` are equivalent. -/ def pair : α × α ≃ α := equiv₂ _ _ end end Denumerable namespace Nat.Subtype open Function Encodable /-! ### Subsets of `ℕ` -/ variable {s : Set ℕ} [Infinite s] section Classical open scoped Classical theorem exists_succ (x : s) : ∃ n, (x : ℕ) + n + 1 ∈ s := _root_.by_contradiction fun h => have : ∀ (a : ℕ) (_ : a ∈ s), a < x + 1 := fun a ha => lt_of_not_ge fun hax => h ⟨a - (x + 1), by rwa [add_right_comm, Nat.add_sub_cancel' hax]⟩ Fintype.false ⟨(((Multiset.range (succ x)).filter (· ∈ s)).pmap (fun (y : ℕ) (hy : y ∈ s) => Subtype.mk y hy) (by simp [-Multiset.range_succ])).toFinset, by simpa [Subtype.ext_iff_val, Multiset.mem_filter, -Multiset.range_succ] ⟩ end Classical variable [DecidablePred (· ∈ s)] /-- Returns the next natural in a set, according to the usual ordering of `ℕ`. -/ def succ (x : s) : s := have h : ∃ m, (x : ℕ) + m + 1 ∈ s := exists_succ x ⟨↑x + Nat.find h + 1, Nat.find_spec h⟩ theorem succ_le_of_lt {x y : s} (h : y < x) : succ y ≤ x := have hx : ∃ m, (y : ℕ) + m + 1 ∈ s := exists_succ _ let ⟨k, hk⟩ := Nat.exists_eq_add_of_lt h have : Nat.find hx ≤ k := Nat.find_min' _ (hk ▸ x.2) show (y : ℕ) + Nat.find hx + 1 ≤ x by omega theorem le_succ_of_forall_lt_le {x y : s} (h : ∀ z < x, z ≤ y) : x ≤ succ y := have hx : ∃ m, (y : ℕ) + m + 1 ∈ s := exists_succ _ show (x : ℕ) ≤ (y : ℕ) + Nat.find hx + 1 from le_of_not_gt fun hxy => (h ⟨_, Nat.find_spec hx⟩ hxy).not_lt <| (by omega : (y : ℕ) < (y : ℕ) + Nat.find hx + 1) theorem lt_succ_self (x : s) : x < succ x := calc -- Porting note: replaced `x + _`, added type annotations (x : ℕ) ≤ (x + Nat.find (exists_succ x) : ℕ) := le_add_right .. _ < (succ x : ℕ) := Nat.lt_succ_self (x + _) theorem lt_succ_iff_le {x y : s} : x < succ y ↔ x ≤ y := ⟨fun h => le_of_not_gt fun h' => not_le_of_gt h (succ_le_of_lt h'), fun h => lt_of_le_of_lt h (lt_succ_self _)⟩ /-- Returns the `n`-th element of a set, according to the usual ordering of `ℕ`. -/ def ofNat (s : Set ℕ) [DecidablePred (· ∈ s)] [Infinite s] : ℕ → s | 0 => ⊥ | n + 1 => succ (ofNat s n) theorem ofNat_surjective_aux : ∀ {x : ℕ} (hx : x ∈ s), ∃ n, ofNat s n = ⟨x, hx⟩ | x => fun hx => by set t : List s := ((List.range x).filter fun y => y ∈ s).pmap (fun (y : ℕ) (hy : y ∈ s) => ⟨y, hy⟩) (by intros a ha; simpa using (List.mem_filter.mp ha).2) with ht have hmt : ∀ {y : s}, y ∈ t ↔ y < ⟨x, hx⟩ := by simp [List.mem_filter, Subtype.ext_iff_val, ht] have wf : ∀ m : s, List.maximum t = m → ↑m < x := fun m hmax => by simpa using hmt.mp (List.maximum_mem hmax) cases' hmax : List.maximum t with m · refine ⟨0, le_antisymm bot_le (le_of_not_gt fun h => List.not_mem_nil (⊥ : s) ?_)⟩ rwa [← List.maximum_eq_bot.1 hmax, hmt] cases' ofNat_surjective_aux m.2 with a ha refine ⟨a + 1, le_antisymm ?_ ?_⟩ <;> rw [ofNat] · refine succ_le_of_lt ?_ rw [ha] exact wf _ hmax · refine le_succ_of_forall_lt_le fun z hz => ?_ rw [ha] cases m exact List.le_maximum_of_mem (hmt.2 hz) hmax decreasing_by tauto theorem ofNat_surjective : Surjective (ofNat s) := fun ⟨_, hx⟩ => ofNat_surjective_aux hx @[simp] theorem ofNat_range : Set.range (ofNat s) = Set.univ := ofNat_surjective.range_eq @[simp] theorem coe_comp_ofNat_range : Set.range ((↑) ∘ ofNat s : ℕ → ℕ) = s := by rw [Set.range_comp Subtype.val, ofNat_range, Set.image_univ, Subtype.range_coe] private def toFunAux (x : s) : ℕ := (List.range x).countP (· ∈ s) private theorem toFunAux_eq {s : Set ℕ} [DecidablePred (· ∈ s)] (x : s) : toFunAux x = ((Finset.range x).filter (· ∈ s)).card := by rw [toFunAux, List.countP_eq_length_filter] rfl open Finset private theorem right_inverse_aux : ∀ n, toFunAux (ofNat s n) = n | 0 => by rw [toFunAux_eq, card_eq_zero, eq_empty_iff_forall_not_mem] rintro n hn rw [mem_filter, ofNat, mem_range] at hn exact bot_le.not_lt (show (⟨n, hn.2⟩ : s) < ⊥ from hn.1) | n + 1 => by have ih : toFunAux (ofNat s n) = n := right_inverse_aux n have h₁ : (ofNat s n : ℕ) ∉ (range (ofNat s n)).filter (· ∈ s) := by simp have h₂ : (range (succ (ofNat s n))).filter (· ∈ s) = insert ↑(ofNat s n) ((range (ofNat s n)).filter (· ∈ s)) := by simp only [Finset.ext_iff, mem_insert, mem_range, mem_filter] exact fun m => ⟨fun h => by simp only [h.2, and_true_iff] exact Or.symm (lt_or_eq_of_le ((@lt_succ_iff_le _ _ _ ⟨m, h.2⟩ _).1 h.1)), fun h => h.elim (fun h => h.symm ▸ ⟨lt_succ_self _, (ofNat s n).prop⟩) fun h => ⟨h.1.trans (lt_succ_self _), h.2⟩⟩ simp only [toFunAux_eq, ofNat, range_succ] at ih ⊢ conv => rhs rw [← ih, ← card_insert_of_not_mem h₁, ← h₂] /-- Any infinite set of naturals is denumerable. -/ def denumerable (s : Set ℕ) [DecidablePred (· ∈ s)] [Infinite s] : Denumerable s := Denumerable.ofEquiv ℕ { toFun := toFunAux invFun := ofNat s left_inv := leftInverse_of_surjective_of_rightInverse ofNat_surjective right_inverse_aux right_inv := right_inverse_aux } end Nat.Subtype namespace Denumerable open Encodable /-- An infinite encodable type is denumerable. -/ def ofEncodableOfInfinite (α : Type*) [Encodable α] [Infinite α] : Denumerable α := by letI := @decidableRangeEncode α _ letI : Infinite (Set.range (@encode α _)) := Infinite.of_injective _ (Equiv.ofInjective _ encode_injective).injective letI := Nat.Subtype.denumerable (Set.range (@encode α _)) exact Denumerable.ofEquiv (Set.range (@encode α _)) (equivRangeEncode α) end Denumerable /-- See also `nonempty_encodable`, `nonempty_fintype`. -/ theorem nonempty_denumerable (α : Type*) [Countable α] [Infinite α] : Nonempty (Denumerable α) := (nonempty_encodable α).map fun h => @Denumerable.ofEncodableOfInfinite _ h _ theorem nonempty_denumerable_iff {α : Type*} : Nonempty (Denumerable α) ↔ Countable α ∧ Infinite α := ⟨fun ⟨_⟩ ↦ ⟨inferInstance, inferInstance⟩, fun ⟨_, _⟩ ↦ nonempty_denumerable _⟩ instance nonempty_equiv_of_countable [Countable α] [Infinite α] [Countable β] [Infinite β] : Nonempty (α ≃ β) := by cases nonempty_denumerable α cases nonempty_denumerable β exact ⟨(Denumerable.eqv _).trans (Denumerable.eqv _).symm⟩
Logic\Hydra.lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import Mathlib.Data.Finsupp.Lex import Mathlib.Data.Finsupp.Multiset import Mathlib.Order.GameAdd /-! # Termination of a hydra game This file deals with the following version of the hydra game: each head of the hydra is labelled by an element in a type `α`, and when you cut off one head with label `a`, it grows back an arbitrary but finite number of heads, all labelled by elements smaller than `a` with respect to a well-founded relation `r` on `α`. We show that no matter how (in what order) you choose cut off the heads, the game always terminates, i.e. all heads will eventually be cut off (but of course it can last arbitrarily long, i.e. takes an arbitrary finite number of steps). This result is stated as the well-foundedness of the `CutExpand` relation defined in this file: we model the heads of the hydra as a multiset of elements of `α`, and the valid "moves" of the game are modelled by the relation `CutExpand r` on `Multiset α`: `CutExpand r s' s` is true iff `s'` is obtained by removing one head `a ∈ s` and adding back an arbitrary multiset `t` of heads such that all `a' ∈ t` satisfy `r a' a`. We follow the proof by Peter LeFanu Lumsdaine at https://mathoverflow.net/a/229084/3332. TODO: formalize the relations corresponding to more powerful (e.g. Kirby–Paris and Buchholz) hydras, and prove their well-foundedness. -/ namespace Relation open Multiset Prod variable {α : Type*} /-- The relation that specifies valid moves in our hydra game. `CutExpand r s' s` means that `s'` is obtained by removing one head `a ∈ s` and adding back an arbitrary multiset `t` of heads such that all `a' ∈ t` satisfy `r a' a`. This is most directly translated into `s' = s.erase a + t`, but `Multiset.erase` requires `DecidableEq α`, so we use the equivalent condition `s' + {a} = s + t` instead, which is also easier to verify for explicit multisets `s'`, `s` and `t`. We also don't include the condition `a ∈ s` because `s' + {a} = s + t` already guarantees `a ∈ s + t`, and if `r` is irreflexive then `a ∉ t`, which is the case when `r` is well-founded, the case we are primarily interested in. The lemma `Relation.cutExpand_iff` below converts between this convenient definition and the direct translation when `r` is irreflexive. -/ def CutExpand (r : α → α → Prop) (s' s : Multiset α) : Prop := ∃ (t : Multiset α) (a : α), (∀ a' ∈ t, r a' a) ∧ s' + {a} = s + t variable {r : α → α → Prop} theorem cutExpand_le_invImage_lex [DecidableEq α] [IsIrrefl α r] : CutExpand r ≤ InvImage (Finsupp.Lex (rᶜ ⊓ (· ≠ ·)) (· < ·)) toFinsupp := by rintro s t ⟨u, a, hr, he⟩ replace hr := fun a' ↦ mt (hr a') classical refine ⟨a, fun b h ↦ ?_, ?_⟩ <;> simp_rw [toFinsupp_apply] · apply_fun count b at he simpa only [count_add, count_singleton, if_neg h.2, add_zero, count_eq_zero.2 (hr b h.1)] using he · apply_fun count a at he simp only [count_add, count_singleton_self, count_eq_zero.2 (hr _ (irrefl_of r a)), add_zero] at he exact he ▸ Nat.lt_succ_self _ theorem cutExpand_singleton {s x} (h : ∀ x' ∈ s, r x' x) : CutExpand r s {x} := ⟨s, x, h, add_comm s _⟩ theorem cutExpand_singleton_singleton {x' x} (h : r x' x) : CutExpand r {x'} {x} := cutExpand_singleton fun a h ↦ by rwa [mem_singleton.1 h] theorem cutExpand_add_left {t u} (s) : CutExpand r (s + t) (s + u) ↔ CutExpand r t u := exists₂_congr fun _ _ ↦ and_congr Iff.rfl <| by rw [add_assoc, add_assoc, add_left_cancel_iff] lemma cutExpand_add_right {s' s} (t) : CutExpand r (s' + t) (s + t) ↔ CutExpand r s' s := by convert cutExpand_add_left t using 2 <;> apply add_comm theorem cutExpand_iff [DecidableEq α] [IsIrrefl α r] {s' s : Multiset α} : CutExpand r s' s ↔ ∃ (t : Multiset α) (a : α), (∀ a' ∈ t, r a' a) ∧ a ∈ s ∧ s' = s.erase a + t := by simp_rw [CutExpand, add_singleton_eq_iff] refine exists₂_congr fun t a ↦ ⟨?_, ?_⟩ · rintro ⟨ht, ha, rfl⟩ obtain h | h := mem_add.1 ha exacts [⟨ht, h, erase_add_left_pos t h⟩, (@irrefl α r _ a (ht a h)).elim] · rintro ⟨ht, h, rfl⟩ exact ⟨ht, mem_add.2 (Or.inl h), (erase_add_left_pos t h).symm⟩ theorem not_cutExpand_zero [IsIrrefl α r] (s) : ¬CutExpand r s 0 := by classical rw [cutExpand_iff] rintro ⟨_, _, _, ⟨⟩, _⟩ lemma cutExpand_zero {x} : CutExpand r 0 {x} := ⟨0, x, nofun, add_comm 0 _⟩ /-- For any relation `r` on `α`, multiset addition `Multiset α × Multiset α → Multiset α` is a fibration between the game sum of `CutExpand r` with itself and `CutExpand r` itself. -/ theorem cutExpand_fibration (r : α → α → Prop) : Fibration (GameAdd (CutExpand r) (CutExpand r)) (CutExpand r) fun s ↦ s.1 + s.2 := by rintro ⟨s₁, s₂⟩ s ⟨t, a, hr, he⟩; dsimp at he ⊢ classical obtain ⟨ha, rfl⟩ := add_singleton_eq_iff.1 he rw [add_assoc, mem_add] at ha obtain h | h := ha · refine ⟨(s₁.erase a + t, s₂), GameAdd.fst ⟨t, a, hr, ?_⟩, ?_⟩ · rw [add_comm, ← add_assoc, singleton_add, cons_erase h] · rw [add_assoc s₁, erase_add_left_pos _ h, add_right_comm, add_assoc] · refine ⟨(s₁, (s₂ + t).erase a), GameAdd.snd ⟨t, a, hr, ?_⟩, ?_⟩ · rw [add_comm, singleton_add, cons_erase h] · rw [add_assoc, erase_add_right_pos _ h] /-- `CutExpand` preserves leftward-closedness under a relation. -/ lemma cutExpand_closed [IsIrrefl α r] (p : α → Prop) (h : ∀ {a' a}, r a' a → p a → p a') : ∀ {s' s}, CutExpand r s' s → (∀ a ∈ s, p a) → ∀ a ∈ s', p a := by intros s' s classical rw [cutExpand_iff] rintro ⟨t, a, hr, ha, rfl⟩ hsp a' h' obtain (h'|h') := mem_add.1 h' exacts [hsp a' (mem_of_mem_erase h'), h (hr a' h') (hsp a ha)] lemma cutExpand_double {a a₁ a₂} (h₁ : r a₁ a) (h₂ : r a₂ a) : CutExpand r {a₁, a₂} {a} := cutExpand_singleton <| by simp only [insert_eq_cons, mem_cons, mem_singleton, forall_eq_or_imp, forall_eq] tauto lemma cutExpand_pair_left {a' a b} (hr : r a' a) : CutExpand r {a', b} {a, b} := (cutExpand_add_right {b}).2 (cutExpand_singleton_singleton hr) lemma cutExpand_pair_right {a b' b} (hr : r b' b) : CutExpand r {a, b'} {a, b} := (cutExpand_add_left {a}).2 (cutExpand_singleton_singleton hr) lemma cutExpand_double_left {a a₁ a₂ b} (h₁ : r a₁ a) (h₂ : r a₂ a) : CutExpand r {a₁, a₂, b} {a, b} := (cutExpand_add_right {b}).2 (cutExpand_double h₁ h₂) /-- A multiset is accessible under `CutExpand` if all its singleton subsets are, assuming `r` is irreflexive. -/ theorem acc_of_singleton [IsIrrefl α r] {s : Multiset α} (hs : ∀ a ∈ s, Acc (CutExpand r) {a}) : Acc (CutExpand r) s := by induction s using Multiset.induction with | empty => exact Acc.intro 0 fun s h ↦ (not_cutExpand_zero s h).elim | cons a s ihs => rw [← s.singleton_add a] rw [forall_mem_cons] at hs exact (hs.1.prod_gameAdd <| ihs fun a ha ↦ hs.2 a ha).of_fibration _ (cutExpand_fibration r) /-- A singleton `{a}` is accessible under `CutExpand r` if `a` is accessible under `r`, assuming `r` is irreflexive. -/ theorem _root_.Acc.cutExpand [IsIrrefl α r] {a : α} (hacc : Acc r a) : Acc (CutExpand r) {a} := by induction' hacc with a h ih refine Acc.intro _ fun s ↦ ?_ classical simp only [cutExpand_iff, mem_singleton] rintro ⟨t, a, hr, rfl, rfl⟩ refine acc_of_singleton fun a' ↦ ?_ rw [erase_singleton, zero_add] exact ih a' ∘ hr a' /-- `CutExpand r` is well-founded when `r` is. -/ theorem _root_.WellFounded.cutExpand (hr : WellFounded r) : WellFounded (CutExpand r) := ⟨have := hr.isIrrefl; fun _ ↦ acc_of_singleton fun a _ ↦ (hr.apply a).cutExpand⟩ end Relation
Logic\IsEmpty.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.Logic.Function.Basic /-! # Types that are empty In this file we define a typeclass `IsEmpty`, which expresses that a type has no elements. ## Main declaration * `IsEmpty`: a typeclass that expresses that a type is empty. -/ variable {α β γ : Sort*} /-- `IsEmpty α` expresses that `α` is empty. -/ class IsEmpty (α : Sort*) : Prop where protected false : α → False instance instIsEmptyEmpty : IsEmpty Empty := ⟨Empty.elim⟩ instance instIsEmptyPEmpty : IsEmpty PEmpty := ⟨PEmpty.elim⟩ instance : IsEmpty False := ⟨id⟩ instance Fin.isEmpty : IsEmpty (Fin 0) := ⟨fun n ↦ Nat.not_lt_zero n.1 n.2⟩ instance Fin.isEmpty' : IsEmpty (Fin Nat.zero) := Fin.isEmpty protected theorem Function.isEmpty [IsEmpty β] (f : α → β) : IsEmpty α := ⟨fun x ↦ IsEmpty.false (f x)⟩ theorem Function.Surjective.isEmpty [IsEmpty α] {f : α → β} (hf : f.Surjective) : IsEmpty β := ⟨fun y ↦ let ⟨x, _⟩ := hf y; IsEmpty.false x⟩ instance {p : α → Sort*} [h : Nonempty α] [∀ x, IsEmpty (p x)] : IsEmpty (∀ x, p x) := h.elim fun x ↦ Function.isEmpty <| Function.eval x instance PProd.isEmpty_left [IsEmpty α] : IsEmpty (PProd α β) := Function.isEmpty PProd.fst instance PProd.isEmpty_right [IsEmpty β] : IsEmpty (PProd α β) := Function.isEmpty PProd.snd instance Prod.isEmpty_left {α β} [IsEmpty α] : IsEmpty (α × β) := Function.isEmpty Prod.fst instance Prod.isEmpty_right {α β} [IsEmpty β] : IsEmpty (α × β) := Function.isEmpty Prod.snd instance Quot.instIsEmpty {α : Sort*} [IsEmpty α] {r : α → α → Prop} : IsEmpty (Quot r) := Function.Surjective.isEmpty Quot.exists_rep instance Quotient.instIsEmpty {α : Sort*} [IsEmpty α] {s : Setoid α} : IsEmpty (Quotient s) := Quot.instIsEmpty instance [IsEmpty α] [IsEmpty β] : IsEmpty (α ⊕' β) := ⟨fun x ↦ PSum.rec IsEmpty.false IsEmpty.false x⟩ instance instIsEmptySum {α β} [IsEmpty α] [IsEmpty β] : IsEmpty (α ⊕ β) := ⟨fun x ↦ Sum.rec IsEmpty.false IsEmpty.false x⟩ /-- subtypes of an empty type are empty -/ instance [IsEmpty α] (p : α → Prop) : IsEmpty (Subtype p) := ⟨fun x ↦ IsEmpty.false x.1⟩ /-- subtypes by an all-false predicate are false. -/ theorem Subtype.isEmpty_of_false {p : α → Prop} (hp : ∀ a, ¬p a) : IsEmpty (Subtype p) := ⟨fun x ↦ hp _ x.2⟩ /-- subtypes by false are false. -/ instance Subtype.isEmpty_false : IsEmpty { _a : α // False } := Subtype.isEmpty_of_false fun _ ↦ id instance Sigma.isEmpty_left {α} [IsEmpty α] {E : α → Type*} : IsEmpty (Sigma E) := Function.isEmpty Sigma.fst example [h : Nonempty α] [IsEmpty β] : IsEmpty (α → β) := by infer_instance /-- Eliminate out of a type that `IsEmpty` (without using projection notation). -/ @[elab_as_elim] def isEmptyElim [IsEmpty α] {p : α → Sort*} (a : α) : p a := (IsEmpty.false a).elim theorem isEmpty_iff : IsEmpty α ↔ α → False := ⟨@IsEmpty.false α, IsEmpty.mk⟩ namespace IsEmpty open Function universe u in /-- Eliminate out of a type that `IsEmpty` (using projection notation). -/ @[elab_as_elim] protected def elim {α : Sort u} (_ : IsEmpty α) {p : α → Sort*} (a : α) : p a := isEmptyElim a /-- Non-dependent version of `IsEmpty.elim`. Helpful if the elaborator cannot elaborate `h.elim a` correctly. -/ protected def elim' {β : Sort*} (h : IsEmpty α) (a : α) : β := (h.false a).elim protected theorem prop_iff {p : Prop} : IsEmpty p ↔ ¬p := isEmpty_iff variable [IsEmpty α] @[simp] theorem forall_iff {p : α → Prop} : (∀ a, p a) ↔ True := iff_true_intro isEmptyElim @[simp] theorem exists_iff {p : α → Prop} : (∃ a, p a) ↔ False := iff_false_intro fun ⟨x, _⟩ ↦ IsEmpty.false x -- see Note [lower instance priority] instance (priority := 100) : Subsingleton α := ⟨isEmptyElim⟩ end IsEmpty @[simp] theorem not_nonempty_iff : ¬Nonempty α ↔ IsEmpty α := ⟨fun h ↦ ⟨fun x ↦ h ⟨x⟩⟩, fun h1 h2 ↦ h2.elim h1.elim⟩ @[simp] theorem not_isEmpty_iff : ¬IsEmpty α ↔ Nonempty α := not_iff_comm.mp not_nonempty_iff @[simp] theorem isEmpty_Prop {p : Prop} : IsEmpty p ↔ ¬p := by simp only [← not_nonempty_iff, nonempty_Prop] @[simp] theorem isEmpty_pi {π : α → Sort*} : IsEmpty (∀ a, π a) ↔ ∃ a, IsEmpty (π a) := by simp only [← not_nonempty_iff, Classical.nonempty_pi, not_forall] theorem isEmpty_fun : IsEmpty (α → β) ↔ Nonempty α ∧ IsEmpty β := by rw [isEmpty_pi, ← exists_true_iff_nonempty, ← exists_and_right, true_and] @[simp] theorem nonempty_fun : Nonempty (α → β) ↔ IsEmpty α ∨ Nonempty β := not_iff_not.mp <| by rw [not_or, not_nonempty_iff, not_nonempty_iff, isEmpty_fun, not_isEmpty_iff] @[simp] theorem isEmpty_sigma {α} {E : α → Type*} : IsEmpty (Sigma E) ↔ ∀ a, IsEmpty (E a) := by simp only [← not_nonempty_iff, nonempty_sigma, not_exists] @[simp] theorem isEmpty_psigma {α} {E : α → Sort*} : IsEmpty (PSigma E) ↔ ∀ a, IsEmpty (E a) := by simp only [← not_nonempty_iff, nonempty_psigma, not_exists] @[simp] theorem isEmpty_subtype (p : α → Prop) : IsEmpty (Subtype p) ↔ ∀ x, ¬p x := by simp only [← not_nonempty_iff, nonempty_subtype, not_exists] @[simp] theorem isEmpty_prod {α β : Type*} : IsEmpty (α × β) ↔ IsEmpty α ∨ IsEmpty β := by simp only [← not_nonempty_iff, nonempty_prod, not_and_or] @[simp] theorem isEmpty_pprod : IsEmpty (PProd α β) ↔ IsEmpty α ∨ IsEmpty β := by simp only [← not_nonempty_iff, nonempty_pprod, not_and_or] @[simp] theorem isEmpty_sum {α β} : IsEmpty (α ⊕ β) ↔ IsEmpty α ∧ IsEmpty β := by simp only [← not_nonempty_iff, nonempty_sum, not_or] @[simp] theorem isEmpty_psum {α β} : IsEmpty (α ⊕' β) ↔ IsEmpty α ∧ IsEmpty β := by simp only [← not_nonempty_iff, nonempty_psum, not_or] @[simp] theorem isEmpty_ulift {α} : IsEmpty (ULift α) ↔ IsEmpty α := by simp only [← not_nonempty_iff, nonempty_ulift] @[simp] theorem isEmpty_plift {α} : IsEmpty (PLift α) ↔ IsEmpty α := by simp only [← not_nonempty_iff, nonempty_plift] theorem wellFounded_of_isEmpty {α} [IsEmpty α] (r : α → α → Prop) : WellFounded r := ⟨isEmptyElim⟩ variable (α) theorem isEmpty_or_nonempty : IsEmpty α ∨ Nonempty α := (em <| IsEmpty α).elim Or.inl <| Or.inr ∘ not_isEmpty_iff.mp @[simp] theorem not_isEmpty_of_nonempty [h : Nonempty α] : ¬IsEmpty α := not_isEmpty_iff.mpr h variable {α} theorem Function.extend_of_isEmpty [IsEmpty α] (f : α → β) (g : α → γ) (h : β → γ) : Function.extend f g h = h := funext fun _ ↦ (Function.extend_apply' _ _ _) fun ⟨a, _⟩ ↦ isEmptyElim a
Logic\Lemmas.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.Logic.Basic import Mathlib.Tactic.Convert import Mathlib.Tactic.SplitIfs import Mathlib.Tactic.Tauto /-! # More basic logic properties A few more logic lemmas. These are in their own file, rather than `Logic.Basic`, because it is convenient to be able to use the `tauto` or `split_ifs` tactics. ## Implementation notes We spell those lemmas out with `dite` and `ite` rather than the `if then else` notation because this would result in less delta-reduced statements. -/ theorem iff_assoc {a b c : Prop} : ((a ↔ b) ↔ c) ↔ (a ↔ (b ↔ c)) := by tauto theorem iff_left_comm {a b c : Prop} : (a ↔ (b ↔ c)) ↔ (b ↔ (a ↔ c)) := by tauto theorem iff_right_comm {a b c : Prop} : ((a ↔ b) ↔ c) ↔ ((a ↔ c) ↔ b) := by tauto protected alias ⟨HEq.eq, Eq.heq⟩ := heq_iff_eq variable {α : Sort*} {p q r : Prop} [Decidable p] [Decidable q] {a b c : α} theorem dite_dite_distrib_left {a : p → α} {b : ¬p → q → α} {c : ¬p → ¬q → α} : (dite p a fun hp ↦ dite q (b hp) (c hp)) = dite q (fun hq ↦ (dite p a) fun hp ↦ b hp hq) fun hq ↦ (dite p a) fun hp ↦ c hp hq := by split_ifs <;> rfl theorem dite_dite_distrib_right {a : p → q → α} {b : p → ¬q → α} {c : ¬p → α} : dite p (fun hp ↦ dite q (a hp) (b hp)) c = dite q (fun hq ↦ dite p (fun hp ↦ a hp hq) c) fun hq ↦ dite p (fun hp ↦ b hp hq) c := by split_ifs <;> rfl theorem ite_dite_distrib_left {a : α} {b : q → α} {c : ¬q → α} : ite p a (dite q b c) = dite q (fun hq ↦ ite p a <| b hq) fun hq ↦ ite p a <| c hq := dite_dite_distrib_left theorem ite_dite_distrib_right {a : q → α} {b : ¬q → α} {c : α} : ite p (dite q a b) c = dite q (fun hq ↦ ite p (a hq) c) fun hq ↦ ite p (b hq) c := dite_dite_distrib_right theorem dite_ite_distrib_left {a : p → α} {b : ¬p → α} {c : ¬p → α} : (dite p a fun hp ↦ ite q (b hp) (c hp)) = ite q (dite p a b) (dite p a c) := dite_dite_distrib_left theorem dite_ite_distrib_right {a : p → α} {b : p → α} {c : ¬p → α} : dite p (fun hp ↦ ite q (a hp) (b hp)) c = ite q (dite p a c) (dite p b c) := dite_dite_distrib_right theorem ite_ite_distrib_left : ite p a (ite q b c) = ite q (ite p a b) (ite p a c) := dite_dite_distrib_left theorem ite_ite_distrib_right : ite p (ite q a b) c = ite q (ite p a c) (ite p b c) := dite_dite_distrib_right lemma Prop.forall {f : Prop → Prop} : (∀ p, f p) ↔ f True ∧ f False := ⟨fun h ↦ ⟨h _, h _⟩, by rintro ⟨h₁, h₀⟩ p; by_cases hp : p <;> simp only [hp] <;> assumption⟩ lemma Prop.exists {f : Prop → Prop} : (∃ p, f p) ↔ f True ∨ f False := ⟨fun ⟨p, h⟩ ↦ by refine (em p).imp ?_ ?_ <;> intro H <;> convert h <;> simp [H], by rintro (h | h) <;> exact ⟨_, h⟩⟩
Logic\Nonempty.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Algebra.Group.ZeroOne import Mathlib.Logic.Function.Defs /-! # Nonempty types This file proves a few extra facts about `Nonempty`, which is defined in core Lean. ## Main declarations * `Nonempty.some`: Extracts a witness of nonemptiness using choice. Takes `Nonempty α` explicitly. * `Classical.arbitrary`: Extracts a witness of nonemptiness using choice. Takes `Nonempty α` as an instance. -/ section variable {α β : Sort*} @[simp] theorem Nonempty.forall {α} {p : Nonempty α → Prop} : (∀ h : Nonempty α, p h) ↔ ∀ a, p ⟨a⟩ := Iff.intro (fun h _ ↦ h _) fun h ⟨a⟩ ↦ h a @[simp] theorem Nonempty.exists {α} {p : Nonempty α → Prop} : (∃ h : Nonempty α, p h) ↔ ∃ a, p ⟨a⟩ := Iff.intro (fun ⟨⟨a⟩, h⟩ ↦ ⟨a, h⟩) fun ⟨a, h⟩ ↦ ⟨⟨a⟩, h⟩ theorem exists_true_iff_nonempty {α : Sort*} : (∃ _ : α, True) ↔ Nonempty α := Iff.intro (fun ⟨a, _⟩ ↦ ⟨a⟩) fun ⟨a⟩ ↦ ⟨a, trivial⟩ @[simp] theorem nonempty_Prop {p : Prop} : Nonempty p ↔ p := Iff.intro (fun ⟨h⟩ ↦ h) fun h ↦ ⟨h⟩ theorem Nonempty.imp {α} {p : Prop} : (Nonempty α → p) ↔ (α → p) := Nonempty.forall theorem not_nonempty_iff_imp_false {α : Sort*} : ¬Nonempty α ↔ α → False := Nonempty.imp @[simp] theorem nonempty_psigma {α} {β : α → Sort*} : Nonempty (PSigma β) ↔ ∃ a : α, Nonempty (β a) := Iff.intro (fun ⟨⟨a, c⟩⟩ ↦ ⟨a, ⟨c⟩⟩) fun ⟨a, ⟨c⟩⟩ ↦ ⟨⟨a, c⟩⟩ @[simp] theorem nonempty_subtype {α} {p : α → Prop} : Nonempty (Subtype p) ↔ ∃ a : α, p a := Iff.intro (fun ⟨⟨a, h⟩⟩ ↦ ⟨a, h⟩) fun ⟨a, h⟩ ↦ ⟨⟨a, h⟩⟩ @[simp] theorem nonempty_pprod {α β} : Nonempty (PProd α β) ↔ Nonempty α ∧ Nonempty β := Iff.intro (fun ⟨⟨a, b⟩⟩ ↦ ⟨⟨a⟩, ⟨b⟩⟩) fun ⟨⟨a⟩, ⟨b⟩⟩ ↦ ⟨⟨a, b⟩⟩ @[simp] theorem nonempty_psum {α β} : Nonempty (α ⊕' β) ↔ Nonempty α ∨ Nonempty β := Iff.intro (fun ⟨h⟩ ↦ match h with | PSum.inl a => Or.inl ⟨a⟩ | PSum.inr b => Or.inr ⟨b⟩) fun h ↦ match h with | Or.inl ⟨a⟩ => ⟨PSum.inl a⟩ | Or.inr ⟨b⟩ => ⟨PSum.inr b⟩ @[simp] theorem nonempty_plift {α} : Nonempty (PLift α) ↔ Nonempty α := Iff.intro (fun ⟨⟨a⟩⟩ ↦ ⟨a⟩) fun ⟨a⟩ ↦ ⟨⟨a⟩⟩ /-- Using `Classical.choice`, lifts a (`Prop`-valued) `Nonempty` instance to a (`Type`-valued) `Inhabited` instance. `Classical.inhabited_of_nonempty` already exists, in `Init/Classical.lean`, but the assumption is not a type class argument, which makes it unsuitable for some applications. -/ noncomputable def Classical.inhabited_of_nonempty' {α} [h : Nonempty α] : Inhabited α := ⟨Classical.choice h⟩ /-- Using `Classical.choice`, extracts a term from a `Nonempty` type. -/ protected noncomputable abbrev Nonempty.some {α} (h : Nonempty α) : α := Classical.choice h /-- Using `Classical.choice`, extracts a term from a `Nonempty` type. -/ protected noncomputable abbrev Classical.arbitrary (α) [h : Nonempty α] : α := Classical.choice h /-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty. `Nonempty` cannot be a `functor`, because `Functor` is restricted to `Type`. -/ theorem Nonempty.map {α β} (f : α → β) : Nonempty α → Nonempty β | ⟨h⟩ => ⟨f h⟩ protected theorem Nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : Nonempty α → Nonempty β → Nonempty γ | ⟨x⟩, ⟨y⟩ => ⟨f x y⟩ protected theorem Nonempty.congr {α β} (f : α → β) (g : β → α) : Nonempty α ↔ Nonempty β := ⟨Nonempty.map f, Nonempty.map g⟩ theorem Nonempty.elim_to_inhabited {α : Sort*} [h : Nonempty α] {p : Prop} (f : Inhabited α → p) : p := h.elim <| f ∘ Inhabited.mk protected instance Prod.instNonempty {α β} [h : Nonempty α] [h2 : Nonempty β] : Nonempty (α × β) := h.elim fun g ↦ h2.elim fun g2 ↦ ⟨⟨g, g2⟩⟩ protected instance Pi.instNonempty {ι : Sort*} {α : ι → Sort*} [∀ i, Nonempty (α i)] : Nonempty (∀ i, α i) := ⟨fun _ ↦ Classical.arbitrary _⟩ theorem Classical.nonempty_pi {ι} {α : ι → Sort*} : Nonempty (∀ i, α i) ↔ ∀ i, Nonempty (α i) := ⟨fun ⟨f⟩ a ↦ ⟨f a⟩, @Pi.instNonempty _ _⟩ theorem subsingleton_of_not_nonempty {α : Sort*} (h : ¬Nonempty α) : Subsingleton α := ⟨fun x ↦ False.elim <| not_nonempty_iff_imp_false.mp h x⟩ theorem Function.Surjective.nonempty [h : Nonempty β] {f : α → β} (hf : Function.Surjective f) : Nonempty α := let ⟨y⟩ := h let ⟨x, _⟩ := hf y ⟨x⟩ end section variable {α β : Type*} {γ : α → Type*} instance (priority := 20) Zero.instNonempty [Zero α] : Nonempty α := ⟨0⟩ instance (priority := 20) One.instNonempty [One α] : Nonempty α := ⟨1⟩ @[simp] theorem nonempty_sigma : Nonempty (Σa : α, γ a) ↔ ∃ a : α, Nonempty (γ a) := Iff.intro (fun ⟨⟨a, c⟩⟩ ↦ ⟨a, ⟨c⟩⟩) fun ⟨a, ⟨c⟩⟩ ↦ ⟨⟨a, c⟩⟩ @[simp] theorem nonempty_sum : Nonempty (α ⊕ β) ↔ Nonempty α ∨ Nonempty β := Iff.intro (fun ⟨h⟩ ↦ match h with | Sum.inl a => Or.inl ⟨a⟩ | Sum.inr b => Or.inr ⟨b⟩) fun h ↦ match h with | Or.inl ⟨a⟩ => ⟨Sum.inl a⟩ | Or.inr ⟨b⟩ => ⟨Sum.inr b⟩ @[simp] theorem nonempty_prod : Nonempty (α × β) ↔ Nonempty α ∧ Nonempty β := Iff.intro (fun ⟨⟨a, b⟩⟩ ↦ ⟨⟨a⟩, ⟨b⟩⟩) fun ⟨⟨a⟩, ⟨b⟩⟩ ↦ ⟨⟨a, b⟩⟩ @[simp] theorem nonempty_ulift : Nonempty (ULift α) ↔ Nonempty α := Iff.intro (fun ⟨⟨a⟩⟩ ↦ ⟨a⟩) fun ⟨a⟩ ↦ ⟨⟨a⟩⟩ end
Logic\Pairwise.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Logic.Function.Basic import Mathlib.Init.Set import Mathlib.Tactic.Common /-! # Relations holding pairwise This file defines pairwise relations. ## Main declarations * `Pairwise`: `Pairwise r` states that `r i j` for all `i ≠ j`. * `Set.Pairwise`: `s.Pairwise r` states that `r i j` for all `i ≠ j` with `i, j ∈ s`. -/ open Set Function variable {α β γ ι ι' : Type*} {r p q : α → α → Prop} section Pairwise variable {f g : ι → α} {s t u : Set α} {a b : α} /-- A relation `r` holds pairwise if `r i j` for all `i ≠ j`. -/ def Pairwise (r : α → α → Prop) := ∀ ⦃i j⦄, i ≠ j → r i j theorem Pairwise.mono (hr : Pairwise r) (h : ∀ ⦃i j⦄, r i j → p i j) : Pairwise p := fun _i _j hij => h <| hr hij protected theorem Pairwise.eq (h : Pairwise r) : ¬r a b → a = b := not_imp_comm.1 <| @h _ _ protected lemma Subsingleton.pairwise [Subsingleton α] : Pairwise r := fun _ _ h ↦ False.elim <| h.elim <| Subsingleton.elim _ _ theorem Function.injective_iff_pairwise_ne : Injective f ↔ Pairwise ((· ≠ ·) on f) := forall₂_congr fun _i _j => not_imp_not.symm alias ⟨Function.Injective.pairwise_ne, _⟩ := Function.injective_iff_pairwise_ne lemma Pairwise.comp_of_injective (hr : Pairwise r) {f : β → α} (hf : Injective f) : Pairwise (r on f) := fun _ _ h ↦ hr <| hf.ne h lemma Pairwise.of_comp_of_surjective {f : β → α} (hr : Pairwise (r on f)) (hf : Surjective f) : Pairwise r := hf.forall₂.2 fun _ _ h ↦ hr <| ne_of_apply_ne f h lemma Function.Bijective.pairwise_comp_iff {f : β → α} (hf : Bijective f) : Pairwise (r on f) ↔ Pairwise r := ⟨fun hr ↦ hr.of_comp_of_surjective hf.surjective, fun hr ↦ hr.comp_of_injective hf.injective⟩ namespace Set /-- The relation `r` holds pairwise on the set `s` if `r x y` for all *distinct* `x y ∈ s`. -/ protected def Pairwise (s : Set α) (r : α → α → Prop) := ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → x ≠ y → r x y theorem pairwise_of_forall (s : Set α) (r : α → α → Prop) (h : ∀ a b, r a b) : s.Pairwise r := fun a _ b _ _ => h a b theorem Pairwise.imp_on (h : s.Pairwise r) (hrp : s.Pairwise fun ⦃a b : α⦄ => r a b → p a b) : s.Pairwise p := fun _a ha _b hb hab => hrp ha hb hab <| h ha hb hab theorem Pairwise.imp (h : s.Pairwise r) (hpq : ∀ ⦃a b : α⦄, r a b → p a b) : s.Pairwise p := h.imp_on <| pairwise_of_forall s _ hpq protected theorem Pairwise.eq (hs : s.Pairwise r) (ha : a ∈ s) (hb : b ∈ s) (h : ¬r a b) : a = b := of_not_not fun hab => h <| hs ha hb hab theorem _root_.Reflexive.set_pairwise_iff (hr : Reflexive r) : s.Pairwise r ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → r a b := forall₄_congr fun a _ _ _ => or_iff_not_imp_left.symm.trans <| or_iff_right_of_imp <| Eq.ndrec <| hr a theorem Pairwise.on_injective (hs : s.Pairwise r) (hf : Function.Injective f) (hfs : ∀ x, f x ∈ s) : Pairwise (r on f) := fun i j hij => hs (hfs i) (hfs j) (hf.ne hij) end Set theorem Pairwise.set_pairwise (h : Pairwise r) (s : Set α) : s.Pairwise r := fun _ _ _ _ w => h w end Pairwise
Logic\Relation.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 -/ import Mathlib.Logic.Function.Basic import Mathlib.Logic.Relator import Mathlib.Init.Data.Quot import Mathlib.Tactic.Cases import Mathlib.Tactic.Use import Mathlib.Tactic.MkIffOfInductiveProp import Mathlib.Tactic.SimpRw /-! # Relation closures This file defines the reflexive, transitive, and reflexive transitive closures of relations. It also proves some basic results on definitions such as `EqvGen`. Note that this is about unbundled relations, that is terms of types of the form `α → β → Prop`. For the bundled version, see `Rel`. ## Definitions * `Relation.ReflGen`: Reflexive closure. `ReflGen r` relates everything `r` related, plus for all `a` it relates `a` with itself. So `ReflGen r a b ↔ r a b ∨ a = b`. * `Relation.TransGen`: Transitive closure. `TransGen r` relates everything `r` related transitively. So `TransGen r a b ↔ ∃ x₀ ... xₙ, r a x₀ ∧ r x₀ x₁ ∧ ... ∧ r xₙ b`. * `Relation.ReflTransGen`: Reflexive transitive closure. `ReflTransGen r` relates everything `r` related transitively, plus for all `a` it relates `a` with itself. So `ReflTransGen r a b ↔ (∃ x₀ ... xₙ, r a x₀ ∧ r x₀ x₁ ∧ ... ∧ r xₙ b) ∨ a = b`. It is the same as the reflexive closure of the transitive closure, or the transitive closure of the reflexive closure. In terms of rewriting systems, this means that `a` can be rewritten to `b` in a number of rewrites. * `Relation.Comp`: Relation composition. We provide notation `∘r`. For `r : α → β → Prop` and `s : β → γ → Prop`, `r ∘r s`relates `a : α` and `c : γ` iff there exists `b : β` that's related to both. * `Relation.Map`: Image of a relation under a pair of maps. For `r : α → β → Prop`, `f : α → γ`, `g : β → δ`, `Map r f g` is the relation `γ → δ → Prop` relating `f a` and `g b` for all `a`, `b` related by `r`. * `Relation.Join`: Join of a relation. For `r : α → α → Prop`, `Join r a b ↔ ∃ c, r a c ∧ r b c`. In terms of rewriting systems, this means that `a` and `b` can be rewritten to the same term. -/ open Function variable {α β γ δ ε ζ : Type*} section NeImp variable {r : α → α → Prop} theorem IsRefl.reflexive [IsRefl α r] : Reflexive r := fun x ↦ IsRefl.refl x /-- To show a reflexive relation `r : α → α → Prop` holds over `x y : α`, it suffices to show it holds when `x ≠ y`. -/ theorem Reflexive.rel_of_ne_imp (h : Reflexive r) {x y : α} (hr : x ≠ y → r x y) : r x y := by by_cases hxy : x = y · exact hxy ▸ h x · exact hr hxy /-- If a reflexive relation `r : α → α → Prop` holds over `x y : α`, then it holds whether or not `x ≠ y`. -/ theorem Reflexive.ne_imp_iff (h : Reflexive r) {x y : α} : x ≠ y → r x y ↔ r x y := ⟨h.rel_of_ne_imp, fun hr _ ↦ hr⟩ /-- If a reflexive relation `r : α → α → Prop` holds over `x y : α`, then it holds whether or not `x ≠ y`. Unlike `Reflexive.ne_imp_iff`, this uses `[IsRefl α r]`. -/ theorem reflexive_ne_imp_iff [IsRefl α r] {x y : α} : x ≠ y → r x y ↔ r x y := IsRefl.reflexive.ne_imp_iff protected theorem Symmetric.iff (H : Symmetric r) (x y : α) : r x y ↔ r y x := ⟨fun h ↦ H h, fun h ↦ H h⟩ theorem Symmetric.flip_eq (h : Symmetric r) : flip r = r := funext₂ fun _ _ ↦ propext <| h.iff _ _ theorem Symmetric.swap_eq : Symmetric r → swap r = r := Symmetric.flip_eq theorem flip_eq_iff : flip r = r ↔ Symmetric r := ⟨fun h _ _ ↦ (congr_fun₂ h _ _).mp, Symmetric.flip_eq⟩ theorem swap_eq_iff : swap r = r ↔ Symmetric r := flip_eq_iff end NeImp section Comap variable {r : β → β → Prop} theorem Reflexive.comap (h : Reflexive r) (f : α → β) : Reflexive (r on f) := fun a ↦ h (f a) theorem Symmetric.comap (h : Symmetric r) (f : α → β) : Symmetric (r on f) := fun _ _ hab ↦ h hab theorem Transitive.comap (h : Transitive r) (f : α → β) : Transitive (r on f) := fun _ _ _ hab hbc ↦ h hab hbc theorem Equivalence.comap (h : Equivalence r) (f : α → β) : Equivalence (r on f) := ⟨h.reflexive.comap f, @(h.symmetric.comap f), @(h.transitive.comap f)⟩ end Comap namespace Relation section Comp variable {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop} /-- The composition of two relations, yielding a new relation. The result relates a term of `α` and a term of `γ` if there is an intermediate term of `β` related to both. -/ def Comp (r : α → β → Prop) (p : β → γ → Prop) (a : α) (c : γ) : Prop := ∃ b, r a b ∧ p b c @[inherit_doc] local infixr:80 " ∘r " => Relation.Comp theorem comp_eq : r ∘r (· = ·) = r := funext fun _ ↦ funext fun b ↦ propext <| Iff.intro (fun ⟨_, h, Eq⟩ ↦ Eq ▸ h) fun h ↦ ⟨b, h, rfl⟩ theorem eq_comp : (· = ·) ∘r r = r := funext fun a ↦ funext fun _ ↦ propext <| Iff.intro (fun ⟨_, Eq, h⟩ ↦ Eq.symm ▸ h) fun h ↦ ⟨a, rfl, h⟩ theorem iff_comp {r : Prop → α → Prop} : (· ↔ ·) ∘r r = r := by have : (· ↔ ·) = (· = ·) := by funext a b; exact iff_eq_eq rw [this, eq_comp] theorem comp_iff {r : α → Prop → Prop} : r ∘r (· ↔ ·) = r := by have : (· ↔ ·) = (· = ·) := by funext a b; exact iff_eq_eq rw [this, comp_eq] theorem comp_assoc : (r ∘r p) ∘r q = r ∘r p ∘r q := by funext a d apply propext constructor · exact fun ⟨c, ⟨b, hab, hbc⟩, hcd⟩ ↦ ⟨b, hab, c, hbc, hcd⟩ · exact fun ⟨b, hab, c, hbc, hcd⟩ ↦ ⟨c, ⟨b, hab, hbc⟩, hcd⟩ theorem flip_comp : flip (r ∘r p) = flip p ∘r flip r := by funext c a apply propext constructor · exact fun ⟨b, hab, hbc⟩ ↦ ⟨b, hbc, hab⟩ · exact fun ⟨b, hbc, hab⟩ ↦ ⟨b, hab, hbc⟩ end Comp section Fibration variable (rα : α → α → Prop) (rβ : β → β → Prop) (f : α → β) /-- A function `f : α → β` is a fibration between the relation `rα` and `rβ` if for all `a : α` and `b : β`, whenever `b : β` and `f a` are related by `rβ`, `b` is the image of some `a' : α` under `f`, and `a'` and `a` are related by `rα`. -/ def Fibration := ∀ ⦃a b⦄, rβ b (f a) → ∃ a', rα a' a ∧ f a' = b variable {rα rβ} /-- If `f : α → β` is a fibration between relations `rα` and `rβ`, and `a : α` is accessible under `rα`, then `f a` is accessible under `rβ`. -/ theorem _root_.Acc.of_fibration (fib : Fibration rα rβ f) {a} (ha : Acc rα a) : Acc rβ (f a) := by induction' ha with a _ ih refine Acc.intro (f a) fun b hr ↦ ?_ obtain ⟨a', hr', rfl⟩ := fib hr exact ih a' hr' theorem _root_.Acc.of_downward_closed (dc : ∀ {a b}, rβ b (f a) → ∃ c, f c = b) (a : α) (ha : Acc (InvImage rβ f) a) : Acc rβ (f a) := ha.of_fibration f fun a _ h ↦ let ⟨a', he⟩ := dc h -- Porting note: Lean 3 did not need the motive ⟨a', he.substr (p := fun x ↦ rβ x (f a)) h, he⟩ end Fibration section Map variable {r : α → β → Prop} {f : α → γ} {g : β → δ} {c : γ} {d : δ} /-- The map of a relation `r` through a pair of functions pushes the relation to the codomains of the functions. The resulting relation is defined by having pairs of terms related if they have preimages related by `r`. -/ protected def Map (r : α → β → Prop) (f : α → γ) (g : β → δ) : γ → δ → Prop := fun c d ↦ ∃ a b, r a b ∧ f a = c ∧ g b = d lemma map_apply : Relation.Map r f g c d ↔ ∃ a b, r a b ∧ f a = c ∧ g b = d := Iff.rfl @[simp] lemma map_map (r : α → β → Prop) (f₁ : α → γ) (g₁ : β → δ) (f₂ : γ → ε) (g₂ : δ → ζ) : Relation.Map (Relation.Map r f₁ g₁) f₂ g₂ = Relation.Map r (f₂ ∘ f₁) (g₂ ∘ g₁) := by ext a b simp_rw [Relation.Map, Function.comp_apply, ← exists_and_right, @exists_comm γ, @exists_comm δ] refine exists₂_congr fun a b ↦ ⟨?_, fun h ↦ ⟨_, _, ⟨⟨h.1, rfl, rfl⟩, h.2⟩⟩⟩ rintro ⟨_, _, ⟨hab, rfl, rfl⟩, h⟩ exact ⟨hab, h⟩ @[simp] lemma map_apply_apply (hf : Injective f) (hg : Injective g) (r : α → β → Prop) (a : α) (b : β) : Relation.Map r f g (f a) (g b) ↔ r a b := by simp [Relation.Map, hf.eq_iff, hg.eq_iff] @[simp] lemma map_id_id (r : α → β → Prop) : Relation.Map r id id = r := by ext; simp [Relation.Map] instance [Decidable (∃ a b, r a b ∧ f a = c ∧ g b = d)] : Decidable (Relation.Map r f g c d) := ‹Decidable _› end Map variable {r : α → α → Prop} {a b c d : α} /-- `ReflTransGen r`: reflexive transitive closure of `r` -/ @[mk_iff ReflTransGen.cases_tail_iff] inductive ReflTransGen (r : α → α → Prop) (a : α) : α → Prop | refl : ReflTransGen r a a | tail {b c} : ReflTransGen r a b → r b c → ReflTransGen r a c attribute [refl] ReflTransGen.refl /-- `ReflGen r`: reflexive closure of `r` -/ @[mk_iff] inductive ReflGen (r : α → α → Prop) (a : α) : α → Prop | refl : ReflGen r a a | single {b} : r a b → ReflGen r a b attribute [mk_iff] TransGen attribute [refl] ReflGen.refl namespace ReflGen theorem to_reflTransGen : ∀ {a b}, ReflGen r a b → ReflTransGen r a b | a, _, refl => by rfl | a, b, single h => ReflTransGen.tail ReflTransGen.refl h theorem mono {p : α → α → Prop} (hp : ∀ a b, r a b → p a b) : ∀ {a b}, ReflGen r a b → ReflGen p a b | a, _, ReflGen.refl => by rfl | a, b, single h => single (hp a b h) instance : IsRefl α (ReflGen r) := ⟨@refl α r⟩ end ReflGen namespace ReflTransGen @[trans] theorem trans (hab : ReflTransGen r a b) (hbc : ReflTransGen r b c) : ReflTransGen r a c := by induction hbc with | refl => assumption | tail _ hcd hac => exact hac.tail hcd theorem single (hab : r a b) : ReflTransGen r a b := refl.tail hab theorem head (hab : r a b) (hbc : ReflTransGen r b c) : ReflTransGen r a c := by induction hbc with | refl => exact refl.tail hab | tail _ hcd hac => exact hac.tail hcd theorem symmetric (h : Symmetric r) : Symmetric (ReflTransGen r) := by intro x y h induction' h with z w _ b c · rfl · apply Relation.ReflTransGen.head (h b) c theorem cases_tail : ReflTransGen r a b → b = a ∨ ∃ c, ReflTransGen r a c ∧ r c b := (cases_tail_iff r a b).1 @[elab_as_elim] theorem head_induction_on {P : ∀ a : α, ReflTransGen r a b → Prop} {a : α} (h : ReflTransGen r a b) (refl : P b refl) (head : ∀ {a c} (h' : r a c) (h : ReflTransGen r c b), P c h → P a (h.head h')) : P a h := by induction h with | refl => exact refl | @tail b c _ hbc ih => apply ih · exact head hbc _ refl · exact fun h1 h2 ↦ head h1 (h2.tail hbc) @[elab_as_elim] theorem trans_induction_on {P : ∀ {a b : α}, ReflTransGen r a b → Prop} {a b : α} (h : ReflTransGen r a b) (ih₁ : ∀ a, @P a a refl) (ih₂ : ∀ {a b} (h : r a b), P (single h)) (ih₃ : ∀ {a b c} (h₁ : ReflTransGen r a b) (h₂ : ReflTransGen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) : P h := by induction h with | refl => exact ih₁ a | tail hab hbc ih => exact ih₃ hab (single hbc) ih (ih₂ hbc) theorem cases_head (h : ReflTransGen r a b) : a = b ∨ ∃ c, r a c ∧ ReflTransGen r c b := by induction h using Relation.ReflTransGen.head_induction_on · left rfl · right exact ⟨_, by assumption, by assumption⟩ theorem cases_head_iff : ReflTransGen r a b ↔ a = b ∨ ∃ c, r a c ∧ ReflTransGen r c b := by use cases_head rintro (rfl | ⟨c, hac, hcb⟩) · rfl · exact head hac hcb theorem total_of_right_unique (U : Relator.RightUnique r) (ab : ReflTransGen r a b) (ac : ReflTransGen r a c) : ReflTransGen r b c ∨ ReflTransGen r c b := by induction' ab with b d _ bd IH · exact Or.inl ac · rcases IH with (IH | IH) · rcases cases_head IH with (rfl | ⟨e, be, ec⟩) · exact Or.inr (single bd) · cases U bd be exact Or.inl ec · exact Or.inr (IH.tail bd) end ReflTransGen namespace TransGen theorem to_reflTransGen {a b} (h : TransGen r a b) : ReflTransGen r a b := by induction' h with b h b c _ bc ab · exact ReflTransGen.single h · exact ReflTransGen.tail ab bc -- Porting note: in Lean 3 this function was called `to_refl` which seems wrong. theorem trans_left (hab : TransGen r a b) (hbc : ReflTransGen r b c) : TransGen r a c := by induction hbc with | refl => assumption | tail _ hcd hac => exact hac.tail hcd instance : Trans (TransGen r) (ReflTransGen r) (TransGen r) := ⟨trans_left⟩ @[trans] theorem trans (hab : TransGen r a b) (hbc : TransGen r b c) : TransGen r a c := trans_left hab hbc.to_reflTransGen instance : Trans (TransGen r) (TransGen r) (TransGen r) := ⟨trans⟩ theorem head' (hab : r a b) (hbc : ReflTransGen r b c) : TransGen r a c := trans_left (single hab) hbc theorem tail' (hab : ReflTransGen r a b) (hbc : r b c) : TransGen r a c := by induction hab generalizing c with | refl => exact single hbc | tail _ hdb IH => exact tail (IH hdb) hbc theorem head (hab : r a b) (hbc : TransGen r b c) : TransGen r a c := head' hab hbc.to_reflTransGen @[elab_as_elim] theorem head_induction_on {P : ∀ a : α, TransGen r a b → Prop} {a : α} (h : TransGen r a b) (base : ∀ {a} (h : r a b), P a (single h)) (ih : ∀ {a c} (h' : r a c) (h : TransGen r c b), P c h → P a (h.head h')) : P a h := by induction h with | single h => exact base h | @tail b c _ hbc h_ih => apply h_ih · exact fun h ↦ ih h (single hbc) (base hbc) · exact fun hab hbc ↦ ih hab _ @[elab_as_elim] theorem trans_induction_on {P : ∀ {a b : α}, TransGen r a b → Prop} {a b : α} (h : TransGen r a b) (base : ∀ {a b} (h : r a b), P (single h)) (ih : ∀ {a b c} (h₁ : TransGen r a b) (h₂ : TransGen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) : P h := by induction h with | single h => exact base h | tail hab hbc h_ih => exact ih hab (single hbc) h_ih (base hbc) theorem trans_right (hab : ReflTransGen r a b) (hbc : TransGen r b c) : TransGen r a c := by induction hbc with | single hbc => exact tail' hab hbc | tail _ hcd hac => exact hac.tail hcd instance : Trans (ReflTransGen r) (TransGen r) (TransGen r) := ⟨trans_right⟩ theorem tail'_iff : TransGen r a c ↔ ∃ b, ReflTransGen r a b ∧ r b c := by refine ⟨fun h ↦ ?_, fun ⟨b, hab, hbc⟩ ↦ tail' hab hbc⟩ cases' h with _ hac b _ hab hbc · exact ⟨_, by rfl, hac⟩ · exact ⟨_, hab.to_reflTransGen, hbc⟩ theorem head'_iff : TransGen r a c ↔ ∃ b, r a b ∧ ReflTransGen r b c := by refine ⟨fun h ↦ ?_, fun ⟨b, hab, hbc⟩ ↦ head' hab hbc⟩ induction h with | single hac => exact ⟨_, hac, by rfl⟩ | tail _ hbc IH => rcases IH with ⟨d, had, hdb⟩ exact ⟨_, had, hdb.tail hbc⟩ end TransGen section reflGen lemma reflGen_eq_self (hr : Reflexive r) : ReflGen r = r := by ext x y simpa only [reflGen_iff, or_iff_right_iff_imp] using fun h ↦ h ▸ hr y lemma reflexive_reflGen : Reflexive (ReflGen r) := fun _ ↦ .refl lemma reflGen_minimal {r' : α → α → Prop} (hr' : Reflexive r') (h : ∀ x y, r x y → r' x y) {x y : α} (hxy : ReflGen r x y) : r' x y := by simpa [reflGen_eq_self hr'] using ReflGen.mono h hxy end reflGen section TransGen theorem transGen_eq_self (trans : Transitive r) : TransGen r = r := funext fun a ↦ funext fun b ↦ propext <| ⟨fun h ↦ by induction h with | single hc => exact hc | tail _ hcd hac => exact trans hac hcd, TransGen.single⟩ theorem transitive_transGen : Transitive (TransGen r) := fun _ _ _ ↦ TransGen.trans instance : IsTrans α (TransGen r) := ⟨@TransGen.trans α r⟩ theorem transGen_idem : TransGen (TransGen r) = TransGen r := transGen_eq_self transitive_transGen theorem TransGen.lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → p (f a) (f b)) (hab : TransGen r a b) : TransGen p (f a) (f b) := by induction hab with | single hac => exact TransGen.single (h a _ hac) | tail _ hcd hac => exact TransGen.tail hac (h _ _ hcd) theorem TransGen.lift' {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → TransGen p (f a) (f b)) (hab : TransGen r a b) : TransGen p (f a) (f b) := by simpa [transGen_idem] using hab.lift f h theorem TransGen.closed {p : α → α → Prop} : (∀ a b, r a b → TransGen p a b) → TransGen r a b → TransGen p a b := TransGen.lift' id lemma TransGen.closed' {P : α → Prop} (dc : ∀ {a b}, r a b → P b → P a) {a b : α} (h : TransGen r a b) : P b → P a := h.head_induction_on dc fun hr _ hi ↦ dc hr ∘ hi theorem TransGen.mono {p : α → α → Prop} : (∀ a b, r a b → p a b) → TransGen r a b → TransGen p a b := TransGen.lift id lemma transGen_minimal {r' : α → α → Prop} (hr' : Transitive r') (h : ∀ x y, r x y → r' x y) {x y : α} (hxy : TransGen r x y) : r' x y := by simpa [transGen_eq_self hr'] using TransGen.mono h hxy theorem TransGen.swap (h : TransGen r b a) : TransGen (swap r) a b := by induction' h with b h b c _ hbc ih · exact TransGen.single h · exact ih.head hbc theorem transGen_swap : TransGen (swap r) a b ↔ TransGen r b a := ⟨TransGen.swap, TransGen.swap⟩ end TransGen section ReflTransGen open ReflTransGen theorem reflTransGen_iff_eq (h : ∀ b, ¬r a b) : ReflTransGen r a b ↔ b = a := by rw [cases_head_iff]; simp [h, eq_comm] theorem reflTransGen_iff_eq_or_transGen : ReflTransGen r a b ↔ b = a ∨ TransGen r a b := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · cases' h with c _ hac hcb · exact Or.inl rfl · exact Or.inr (TransGen.tail' hac hcb) · rcases h with (rfl | h) · rfl · exact h.to_reflTransGen theorem ReflTransGen.lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → p (f a) (f b)) (hab : ReflTransGen r a b) : ReflTransGen p (f a) (f b) := ReflTransGen.trans_induction_on hab (fun _ ↦ refl) (ReflTransGen.single ∘ h _ _) fun _ _ ↦ trans theorem ReflTransGen.mono {p : α → α → Prop} : (∀ a b, r a b → p a b) → ReflTransGen r a b → ReflTransGen p a b := ReflTransGen.lift id theorem reflTransGen_eq_self (refl : Reflexive r) (trans : Transitive r) : ReflTransGen r = r := funext fun a ↦ funext fun b ↦ propext <| ⟨fun h ↦ by induction' h with b c _ h₂ IH · apply refl · exact trans IH h₂, single⟩ lemma reflTransGen_minimal {r' : α → α → Prop} (hr₁ : Reflexive r') (hr₂ : Transitive r') (h : ∀ x y, r x y → r' x y) {x y : α} (hxy : ReflTransGen r x y) : r' x y := by simpa [reflTransGen_eq_self hr₁ hr₂] using ReflTransGen.mono h hxy theorem reflexive_reflTransGen : Reflexive (ReflTransGen r) := fun _ ↦ refl theorem transitive_reflTransGen : Transitive (ReflTransGen r) := fun _ _ _ ↦ trans instance : IsRefl α (ReflTransGen r) := ⟨@ReflTransGen.refl α r⟩ instance : IsTrans α (ReflTransGen r) := ⟨@ReflTransGen.trans α r⟩ theorem reflTransGen_idem : ReflTransGen (ReflTransGen r) = ReflTransGen r := reflTransGen_eq_self reflexive_reflTransGen transitive_reflTransGen theorem ReflTransGen.lift' {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → ReflTransGen p (f a) (f b)) (hab : ReflTransGen r a b) : ReflTransGen p (f a) (f b) := by simpa [reflTransGen_idem] using hab.lift f h theorem reflTransGen_closed {p : α → α → Prop} : (∀ a b, r a b → ReflTransGen p a b) → ReflTransGen r a b → ReflTransGen p a b := ReflTransGen.lift' id theorem ReflTransGen.swap (h : ReflTransGen r b a) : ReflTransGen (swap r) a b := by induction' h with b c _ hbc ih · rfl · exact ih.head hbc theorem reflTransGen_swap : ReflTransGen (swap r) a b ↔ ReflTransGen r b a := ⟨ReflTransGen.swap, ReflTransGen.swap⟩ @[simp] lemma reflGen_transGen : ReflGen (TransGen r) = ReflTransGen r := by ext x y simp_rw [reflTransGen_iff_eq_or_transGen, reflGen_iff] @[simp] lemma transGen_reflGen : TransGen (ReflGen r) = ReflTransGen r := by ext x y refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · simpa [reflTransGen_idem] using TransGen.to_reflTransGen <| TransGen.mono (fun _ _ ↦ ReflGen.to_reflTransGen) h · obtain (rfl | h) := reflTransGen_iff_eq_or_transGen.mp h · exact .single .refl · exact TransGen.mono (fun _ _ ↦ .single) h @[simp] lemma reflTransGen_reflGen : ReflTransGen (ReflGen r) = ReflTransGen r := by simp only [← transGen_reflGen, reflGen_eq_self reflexive_reflGen] @[simp] lemma reflTransGen_transGen : ReflTransGen (TransGen r) = ReflTransGen r := by simp only [← reflGen_transGen, transGen_idem] lemma reflTransGen_eq_transGen (hr : Reflexive r) : ReflTransGen r = TransGen r := by rw [← transGen_reflGen, reflGen_eq_self hr] lemma reflTransGen_eq_reflGen (hr : Transitive r) : ReflTransGen r = ReflGen r := by rw [← reflGen_transGen, transGen_eq_self hr] end ReflTransGen /-- The join of a relation on a single type is a new relation for which pairs of terms are related if there is a third term they are both related to. For example, if `r` is a relation representing rewrites in a term rewriting system, then *confluence* is the property that if `a` rewrites to both `b` and `c`, then `join r` relates `b` and `c` (see `Relation.church_rosser`). -/ def Join (r : α → α → Prop) : α → α → Prop := fun a b ↦ ∃ c, r a c ∧ r b c section Join open ReflTransGen ReflGen /-- A sufficient condition for the Church-Rosser property. -/ theorem church_rosser (h : ∀ a b c, r a b → r a c → ∃ d, ReflGen r b d ∧ ReflTransGen r c d) (hab : ReflTransGen r a b) (hac : ReflTransGen r a c) : Join (ReflTransGen r) b c := by induction hab with | refl => exact ⟨c, hac, refl⟩ | @tail d e _ hde ih => rcases ih with ⟨b, hdb, hcb⟩ have : ∃ a, ReflTransGen r e a ∧ ReflGen r b a := by clear hcb induction hdb with | refl => exact ⟨e, refl, ReflGen.single hde⟩ | @tail f b _ hfb ih => rcases ih with ⟨a, hea, hfa⟩ cases' hfa with _ hfa · exact ⟨b, hea.tail hfb, ReflGen.refl⟩ · rcases h _ _ _ hfb hfa with ⟨c, hbc, hac⟩ exact ⟨c, hea.trans hac, hbc⟩ rcases this with ⟨a, hea, hba⟩ cases' hba with _ hba · exact ⟨b, hea, hcb⟩ · exact ⟨a, hea, hcb.tail hba⟩ theorem join_of_single (h : Reflexive r) (hab : r a b) : Join r a b := ⟨b, hab, h b⟩ theorem symmetric_join : Symmetric (Join r) := fun _ _ ⟨c, hac, hcb⟩ ↦ ⟨c, hcb, hac⟩ theorem reflexive_join (h : Reflexive r) : Reflexive (Join r) := fun a ↦ ⟨a, h a, h a⟩ theorem transitive_join (ht : Transitive r) (h : ∀ a b c, r a b → r a c → Join r b c) : Transitive (Join r) := fun _ b _ ⟨x, hax, hbx⟩ ⟨y, hby, hcy⟩ ↦ let ⟨z, hxz, hyz⟩ := h b x y hbx hby ⟨z, ht hax hxz, ht hcy hyz⟩ theorem equivalence_join (hr : Reflexive r) (ht : Transitive r) (h : ∀ a b c, r a b → r a c → Join r b c) : Equivalence (Join r) := ⟨reflexive_join hr, @symmetric_join _ _, @transitive_join _ _ ht h⟩ theorem equivalence_join_reflTransGen (h : ∀ a b c, r a b → r a c → ∃ d, ReflGen r b d ∧ ReflTransGen r c d) : Equivalence (Join (ReflTransGen r)) := equivalence_join reflexive_reflTransGen transitive_reflTransGen fun _ _ _ ↦ church_rosser h theorem join_of_equivalence {r' : α → α → Prop} (hr : Equivalence r) (h : ∀ a b, r' a b → r a b) : Join r' a b → r a b | ⟨_, hac, hbc⟩ => hr.trans (h _ _ hac) (hr.symm <| h _ _ hbc) theorem reflTransGen_of_transitive_reflexive {r' : α → α → Prop} (hr : Reflexive r) (ht : Transitive r) (h : ∀ a b, r' a b → r a b) (h' : ReflTransGen r' a b) : r a b := by induction' h' with b c _ hbc ih · exact hr _ · exact ht ih (h _ _ hbc) theorem reflTransGen_of_equivalence {r' : α → α → Prop} (hr : Equivalence r) : (∀ a b, r' a b → r a b) → ReflTransGen r' a b → r a b := reflTransGen_of_transitive_reflexive hr.1 (fun _ _ _ ↦ hr.trans) end Join end Relation section EqvGen variable {r : α → α → Prop} {a b : α} theorem Equivalence.eqvGen_iff (h : Equivalence r) : EqvGen r a b ↔ r a b := Iff.intro (by intro h induction h with | rel => assumption | refl => exact h.1 _ | symm => apply h.symm; assumption | trans _ _ _ _ _ hab hbc => exact h.trans hab hbc) (EqvGen.rel a b) theorem Equivalence.eqvGen_eq (h : Equivalence r) : EqvGen r = r := funext fun _ ↦ funext fun _ ↦ propext <| h.eqvGen_iff theorem EqvGen.mono {r p : α → α → Prop} (hrp : ∀ a b, r a b → p a b) (h : EqvGen r a b) : EqvGen p a b := by induction h with | rel a b h => exact EqvGen.rel _ _ (hrp _ _ h) | refl => exact EqvGen.refl _ | symm a b _ ih => exact EqvGen.symm _ _ ih | trans a b c _ _ hab hbc => exact EqvGen.trans _ _ _ hab hbc end EqvGen
Logic\Relator.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Logic.Function.Defs /-! # Relator for functions, pairs, sums, and lists. -/ namespace Relator universe u₁ u₂ v₁ v₂ /- TODO(johoelzl): * should we introduce relators of datatypes as recursive function or as inductive predicate? For now we stick to the recursor approach. * relation lift for datatypes, Π, Σ, set, and subtype types * proof composition and identity laws * implement method to derive relators from datatype -/ section variable {α : Sort u₁} {β : Sort u₂} {γ : Sort v₁} {δ : Sort v₂} variable (R : α → β → Prop) (S : γ → δ → Prop) /-- The binary relations `R : α → β → Prop` and `S : γ → δ → Prop` induce a binary relation on functions `LiftFun : (α → γ) → (β → δ) → Prop`. -/ def LiftFun (f : α → γ) (g : β → δ) : Prop := ∀⦃a b⦄, R a b → S (f a) (g b) /-- `(R ⇒ S) f g` means `LiftFun R S f g`. -/ infixr:40 " ⇒ " => LiftFun end section variable {α : Type u₁} {β : Type u₂} (R : α → β → Prop) /-- A relation is "right total" if every element appears on the right. -/ def RightTotal : Prop := ∀ b, ∃ a, R a b /-- A relation is "left total" if every element appears on the left. -/ def LeftTotal : Prop := ∀ a, ∃ b, R a b /-- A relation is "bi-total" if it is both right total and left total. -/ def BiTotal : Prop := LeftTotal R ∧ RightTotal R /-- A relation is "left unique" if every element on the right is paired with at most one element on the left. -/ def LeftUnique : Prop := ∀ ⦃a b c⦄, R a c → R b c → a = b /-- A relation is "right unique" if every element on the left is paired with at most one element on the right. -/ def RightUnique : Prop := ∀ ⦃a b c⦄, R a b → R a c → b = c /-- A relation is "bi-unique" if it is both left unique and right unique. -/ def BiUnique : Prop := LeftUnique R ∧ RightUnique R variable {R} lemma RightTotal.rel_forall (h : RightTotal R) : ((R ⇒ (· → ·)) ⇒ (· → ·)) (fun p => ∀i, p i) (fun q => ∀i, q i) := fun _ _ Hrel H b => Exists.elim (h b) (fun _ Rab => Hrel Rab (H _)) lemma LeftTotal.rel_exists (h : LeftTotal R) : ((R ⇒ (· → ·)) ⇒ (· → ·)) (fun p => ∃i, p i) (fun q => ∃i, q i) := fun _ _ Hrel ⟨a, pa⟩ => (h a).imp fun _ Rab => Hrel Rab pa lemma BiTotal.rel_forall (h : BiTotal R) : ((R ⇒ Iff) ⇒ Iff) (fun p => ∀i, p i) (fun q => ∀i, q i) := fun _ _ Hrel => ⟨fun H b => Exists.elim (h.right b) (fun _ Rab => (Hrel Rab).mp (H _)), fun H a => Exists.elim (h.left a) (fun _ Rab => (Hrel Rab).mpr (H _))⟩ lemma BiTotal.rel_exists (h : BiTotal R) : ((R ⇒ Iff) ⇒ Iff) (fun p => ∃i, p i) (fun q => ∃i, q i) := fun _ _ Hrel => ⟨fun ⟨a, pa⟩ => (h.left a).imp fun _ Rab => (Hrel Rab).1 pa, fun ⟨b, qb⟩ => (h.right b).imp fun _ Rab => (Hrel Rab).2 qb⟩ lemma left_unique_of_rel_eq {eq' : β → β → Prop} (he : (R ⇒ (R ⇒ Iff)) Eq eq') : LeftUnique R := fun a b c (ac : R a c) (bc : R b c) => (he ac bc).mpr ((he bc bc).mp rfl) end lemma rel_imp : (Iff ⇒ (Iff ⇒ Iff)) (· → ·) (· → ·) := fun _ _ h _ _ l => imp_congr h l lemma rel_not : (Iff ⇒ Iff) Not Not := fun _ _ h => not_congr h lemma bi_total_eq {α : Type u₁} : Relator.BiTotal (@Eq α) := { left := fun a => ⟨a, rfl⟩, right := fun a => ⟨a, rfl⟩ } variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variable {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop} lemma LeftUnique.flip (h : LeftUnique r) : RightUnique (flip r) := fun _ _ _ h₁ h₂ => h h₁ h₂ lemma rel_and : ((·↔·) ⇒ (·↔·) ⇒ (·↔·)) (·∧·) (·∧·) := fun _ _ h₁ _ _ h₂ => and_congr h₁ h₂ lemma rel_or : ((·↔·) ⇒ (·↔·) ⇒ (·↔·)) (·∨·) (·∨·) := fun _ _ h₁ _ _ h₂ => or_congr h₁ h₂ lemma rel_iff : ((·↔·) ⇒ (·↔·) ⇒ (·↔·)) (·↔·) (·↔·) := fun _ _ h₁ _ _ h₂ => iff_congr h₁ h₂ lemma rel_eq {r : α → β → Prop} (hr : BiUnique r) : (r ⇒ r ⇒ (·↔·)) (·=·) (·=·) := fun _ _ h₁ _ _ h₂ => ⟨fun h => hr.right h₁ <| h.symm ▸ h₂, fun h => hr.left h₁ <| h.symm ▸ h₂⟩ open Function variable {α : Type*} {r₁₁ : α → α → Prop} {r₁₂ : α → β → Prop} {r₂₁ : β → α → Prop} {r₂₃ : β → γ → Prop} {r₁₃ : α → γ → Prop} namespace LeftTotal protected lemma refl (hr : ∀ a : α, r₁₁ a a) : LeftTotal r₁₁ := fun a ↦ ⟨a, hr _⟩ protected lemma symm (hr : ∀ (a : α) (b : β), r₁₂ a b → r₂₁ b a) : LeftTotal r₁₂ → RightTotal r₂₁ := fun h a ↦ (h a).imp (fun _ ↦ hr _ _) protected lemma trans (hr : ∀ (a : α) (b : β) (c : γ), r₁₂ a b → r₂₃ b c → r₁₃ a c) : LeftTotal r₁₂ → LeftTotal r₂₃ → LeftTotal r₁₃ := fun h₁ h₂ a ↦ let ⟨b, hab⟩ := h₁ a; let ⟨c, hbc⟩ := h₂ b; ⟨c, hr _ _ _ hab hbc⟩ end LeftTotal namespace RightTotal protected lemma refl (hr : ∀ a : α, r₁₁ a a) : RightTotal r₁₁ := LeftTotal.refl hr protected lemma symm (hr : ∀ (a : α) (b : β), r₁₂ a b → r₂₁ b a) : RightTotal r₁₂ → LeftTotal r₂₁ := LeftTotal.symm (fun _ _ ↦ hr _ _) protected lemma trans (hr : ∀ (a : α) (b : β) (c : γ), r₁₂ a b → r₂₃ b c → r₁₃ a c) : RightTotal r₁₂ → RightTotal r₂₃ → RightTotal r₁₃ := swap <| LeftTotal.trans (fun _ _ _ ↦ swap <| hr _ _ _) end RightTotal namespace BiTotal protected lemma refl (hr : ∀ a : α, r₁₁ a a) : BiTotal r₁₁ := ⟨LeftTotal.refl hr, RightTotal.refl hr⟩ protected lemma symm (hr : ∀ (a : α) (b : β), r₁₂ a b → r₂₁ b a) : BiTotal r₁₂ → BiTotal r₂₁ := fun h ↦ ⟨h.2.symm hr, h.1.symm hr⟩ protected lemma trans (hr : ∀ (a : α) (b : β) (c : γ), r₁₂ a b → r₂₃ b c → r₁₃ a c) : BiTotal r₁₂ → BiTotal r₂₃ → BiTotal r₁₃ := fun h₁ h₂ ↦ ⟨h₁.1.trans hr h₂.1, h₁.2.trans hr h₂.2⟩ end BiTotal end Relator
Logic\Unique.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.Logic.IsEmpty import Mathlib.Init.Logic import Mathlib.Tactic.Inhabit /-! # Types with a unique term In this file we define a typeclass `Unique`, which expresses that a type has a unique term. In other words, a type that is `Inhabited` and a `Subsingleton`. ## Main declaration * `Unique`: a typeclass that expresses that a type has a unique term. ## Main statements * `Unique.mk'`: an inhabited subsingleton type is `Unique`. This can not be an instance because it would lead to loops in typeclass inference. * `Function.Surjective.unique`: if the domain of a surjective function is `Unique`, then its codomain is `Unique` as well. * `Function.Injective.subsingleton`: if the codomain of an injective function is `Subsingleton`, then its domain is `Subsingleton` as well. * `Function.Injective.unique`: if the codomain of an injective function is `Subsingleton` and its domain is `Inhabited`, then its domain is `Unique`. ## Implementation details The typeclass `Unique α` is implemented as a type, rather than a `Prop`-valued predicate, for good definitional properties of the default term. -/ universe u v w /-- `Unique α` expresses that `α` is a type with a unique term `default`. This is implemented as a type, rather than a `Prop`-valued predicate, for good definitional properties of the default term. -/ @[ext] structure Unique (α : Sort u) extends Inhabited α where /-- In a `Unique` type, every term is equal to the default element (from `Inhabited`). -/ uniq : ∀ a : α, a = default attribute [class] Unique -- The simplifier can already prove this using `eq_iff_true_of_subsingleton` attribute [nolint simpNF] Unique.mk.injEq theorem unique_iff_exists_unique (α : Sort u) : Nonempty (Unique α) ↔ ∃! _ : α, True := ⟨fun ⟨u⟩ ↦ ⟨u.default, trivial, fun a _ ↦ u.uniq a⟩, fun ⟨a, _, h⟩ ↦ ⟨⟨⟨a⟩, fun _ ↦ h _ trivial⟩⟩⟩ theorem unique_subtype_iff_exists_unique {α} (p : α → Prop) : Nonempty (Unique (Subtype p)) ↔ ∃! a, p a := ⟨fun ⟨u⟩ ↦ ⟨u.default.1, u.default.2, fun a h ↦ congr_arg Subtype.val (u.uniq ⟨a, h⟩)⟩, fun ⟨a, ha, he⟩ ↦ ⟨⟨⟨⟨a, ha⟩⟩, fun ⟨b, hb⟩ ↦ by congr exact he b hb⟩⟩⟩ /-- Given an explicit `a : α` with `Subsingleton α`, we can construct a `Unique α` instance. This is a def because the typeclass search cannot arbitrarily invent the `a : α` term. Nevertheless, these instances are all equivalent by `Unique.Subsingleton.unique`. See note [reducible non-instances]. -/ abbrev uniqueOfSubsingleton {α : Sort*} [Subsingleton α] (a : α) : Unique α where default := a uniq _ := Subsingleton.elim _ _ instance PUnit.unique : Unique PUnit.{u} where default := PUnit.unit uniq x := subsingleton x _ -- Porting note: -- This should not require a nolint, -- but it is currently failing due to a problem in the linter discussed at -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/.60simpNF.60.20error.20.22unknown.20metavariable.22 @[simp, nolint simpNF] theorem PUnit.default_eq_unit : (default : PUnit) = PUnit.unit := rfl /-- Every provable proposition is unique, as all proofs are equal. -/ def uniqueProp {p : Prop} (h : p) : Unique.{0} p where default := h uniq _ := rfl instance : Unique True := uniqueProp trivial namespace Unique open Function section variable {α : Sort*} [Unique α] -- see Note [lower instance priority] instance (priority := 100) : Inhabited α := toInhabited ‹Unique α› theorem eq_default (a : α) : a = default := uniq _ a theorem default_eq (a : α) : default = a := (uniq _ a).symm -- see Note [lower instance priority] instance (priority := 100) instSubsingleton : Subsingleton α := subsingleton_of_forall_eq _ eq_default theorem forall_iff {p : α → Prop} : (∀ a, p a) ↔ p default := ⟨fun h ↦ h _, fun h x ↦ by rwa [Unique.eq_default x]⟩ theorem exists_iff {p : α → Prop} : Exists p ↔ p default := ⟨fun ⟨a, ha⟩ ↦ eq_default a ▸ ha, Exists.intro default⟩ end variable {α : Sort*} @[ext] protected theorem subsingleton_unique' : ∀ h₁ h₂ : Unique α, h₁ = h₂ | ⟨⟨x⟩, h⟩, ⟨⟨y⟩, _⟩ => by congr; rw [h x, h y] instance subsingleton_unique : Subsingleton (Unique α) := ⟨Unique.subsingleton_unique'⟩ /-- Construct `Unique` from `Inhabited` and `Subsingleton`. Making this an instance would create a loop in the class inheritance graph. -/ abbrev mk' (α : Sort u) [h₁ : Inhabited α] [Subsingleton α] : Unique α := { h₁ with uniq := fun _ ↦ Subsingleton.elim _ _ } end Unique theorem unique_iff_subsingleton_and_nonempty (α : Sort u) : Nonempty (Unique α) ↔ Subsingleton α ∧ Nonempty α := ⟨fun ⟨u⟩ ↦ by constructor <;> exact inferInstance, fun ⟨hs, hn⟩ ↦ ⟨by inhabit α; exact Unique.mk' α⟩⟩ variable {α : Sort*} @[simp] theorem Pi.default_def {β : α → Sort v} [∀ a, Inhabited (β a)] : @default (∀ a, β a) _ = fun a : α ↦ @default (β a) _ := rfl theorem Pi.default_apply {β : α → Sort v} [∀ a, Inhabited (β a)] (a : α) : @default (∀ a, β a) _ a = default := rfl instance Pi.unique {β : α → Sort v} [∀ a, Unique (β a)] : Unique (∀ a, β a) where uniq := fun _ ↦ funext fun _ ↦ Unique.eq_default _ /-- There is a unique function on an empty domain. -/ instance Pi.uniqueOfIsEmpty [IsEmpty α] (β : α → Sort v) : Unique (∀ a, β a) where default := isEmptyElim uniq _ := funext isEmptyElim theorem eq_const_of_subsingleton {β : Sort*} [Subsingleton α] (f : α → β) (a : α) : f = Function.const α (f a) := funext fun x ↦ Subsingleton.elim x a ▸ rfl theorem eq_const_of_unique {β : Sort*} [Unique α] (f : α → β) : f = Function.const α (f default) := eq_const_of_subsingleton .. theorem heq_const_of_unique [Unique α] {β : α → Sort v} (f : ∀ a, β a) : HEq f (Function.const α (f default)) := (Function.hfunext rfl) fun i _ _ ↦ by rw [Subsingleton.elim i default]; rfl namespace Function variable {β : Sort*} {f : α → β} /-- If the codomain of an injective function is a subsingleton, then the domain is a subsingleton as well. -/ protected theorem Injective.subsingleton (hf : Injective f) [Subsingleton β] : Subsingleton α := ⟨fun _ _ ↦ hf <| Subsingleton.elim _ _⟩ /-- If the domain of a surjective function is a subsingleton, then the codomain is a subsingleton as well. -/ protected theorem Surjective.subsingleton [Subsingleton α] (hf : Surjective f) : Subsingleton β := ⟨hf.forall₂.2 fun x y ↦ congr_arg f <| Subsingleton.elim x y⟩ /-- If the domain of a surjective function is a singleton, then the codomain is a singleton as well. -/ protected def Surjective.unique {α : Sort u} (f : α → β) (hf : Surjective f) [Unique.{u} α] : Unique β := @Unique.mk' _ ⟨f default⟩ hf.subsingleton /-- If `α` is inhabited and admits an injective map to a subsingleton type, then `α` is `Unique`. -/ protected def Injective.unique [Inhabited α] [Subsingleton β] (hf : Injective f) : Unique α := @Unique.mk' _ _ hf.subsingleton /-- If a constant function is surjective, then the codomain is a singleton. -/ def Surjective.uniqueOfSurjectiveConst (α : Type*) {β : Type*} (b : β) (h : Function.Surjective (Function.const α b)) : Unique β := @uniqueOfSubsingleton _ (subsingleton_of_forall_eq b <| h.forall.mpr fun _ ↦ rfl) b end Function section Pi variable {ι : Sort*} {α : ι → Sort*} /-- Given one value over a unique, we get a dependent function. -/ def uniqueElim [Unique ι] (x : α (default : ι)) (i : ι) : α i := by rw [Unique.eq_default i] exact x @[simp] theorem uniqueElim_default {_ : Unique ι} (x : α (default : ι)) : uniqueElim x (default : ι) = x := rfl @[simp] theorem uniqueElim_const {β : Sort*} {_ : Unique ι} (x : β) (i : ι) : uniqueElim (α := fun _ ↦ β) x i = x := rfl end Pi -- TODO: Mario turned this off as a simp lemma in Batteries, wanting to profile it. attribute [local simp] eq_iff_true_of_subsingleton in theorem Unique.bijective {A B} [Unique A] [Unique B] {f : A → B} : Function.Bijective f := by rw [Function.bijective_iff_has_inverse] refine ⟨default, ?_, ?_⟩ <;> intro x <;> simp namespace Option /-- `Option α` is a `Subsingleton` if and only if `α` is empty. -/ theorem subsingleton_iff_isEmpty {α : Type u} : Subsingleton (Option α) ↔ IsEmpty α := ⟨fun h ↦ ⟨fun x ↦ Option.noConfusion <| @Subsingleton.elim _ h x none⟩, fun h ↦ ⟨fun x y ↦ Option.casesOn x (Option.casesOn y rfl fun x ↦ h.elim x) fun x ↦ h.elim x⟩⟩ instance {α} [IsEmpty α] : Unique (Option α) := @Unique.mk' _ _ (subsingleton_iff_isEmpty.2 ‹_›) end Option section Subtype variable {α : Sort u} instance Unique.subtypeEq (y : α) : Unique { x // x = y } where default := ⟨y, rfl⟩ uniq := fun ⟨x, hx⟩ ↦ by congr instance Unique.subtypeEq' (y : α) : Unique { x // y = x } where default := ⟨y, rfl⟩ uniq := fun ⟨x, hx⟩ ↦ by subst hx; congr end Subtype
Logic\UnivLE.lean
/- Copyright (c) 2023 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Logic.Small.Defs /-! # UnivLE A proposition expressing a universe inequality. `UnivLE.{u, v}` expresses that `u ≤ v`, in the form `∀ α : Type u, Small.{v} α`. See the doc-string for the comparison with an alternative stronger definition. -/ set_option autoImplicit true noncomputable section /-- A class expressing a universe inequality. `UnivLE.{u, v}` expresses that `u ≤ v`. There used to be a stronger definition `∀ α : Type max u v, Small.{v} α` that immediately implies `Small.{v} ((α : Type u) → (β : Type v))` which is essential for proving that `Type v` has `Type u`-indexed limits when `u ≤ v`. However the current weaker condition `∀ α : Type u, Small.{v} α` also implies the same, so we switched to use it for its simplicity and transitivity. The strong definition easily implies the weaker definition (see below), but we can not prove the reverse implication. This is because in Lean's type theory, while `max u v` is at least at big as `u` and `v`, it could be bigger than both! See also `Mathlib.CategoryTheory.UnivLE` for the statement that the stronger definition is equivalent to `EssSurj (uliftFunctor : Type v ⥤ Type max u v)`. -/ @[pp_with_univ] abbrev UnivLE.{u, v} : Prop := ∀ α : Type u, Small.{v} α example : UnivLE.{u, u} := inferInstance example : UnivLE.{u, u+1} := inferInstance example : UnivLE.{0, u} := inferInstance /- This is useless as an instance due to https://github.com/leanprover/lean4/issues/2297 -/ theorem univLE_max : UnivLE.{u, max u v} := fun α ↦ small_max.{v} α theorem Small.trans_univLE.{u, v} (α : Type w) [hα : Small.{u} α] [h : UnivLE.{u, v}] : Small.{v} α := let ⟨β, ⟨f⟩⟩ := hα.equiv_small let ⟨_, ⟨g⟩⟩ := (h β).equiv_small ⟨_, ⟨f.trans g⟩⟩ theorem UnivLE.trans [UnivLE.{u, v}] [UnivLE.{v, w}] : UnivLE.{u, w} := fun α ↦ Small.trans_univLE α /- This is the crucial instance that subsumes `univLE_max`. -/ instance univLE_of_max [UnivLE.{max u v, v}] : UnivLE.{u, v} := @UnivLE.trans univLE_max.{v,u} ‹_› /- When `small_Pi` from `Mathlib.Logic.Small.Basic` is imported, we have : -/ -- example (α : Type u) (β : Type v) [UnivLE.{u, v}] : Small.{v} (α → β) := inferInstance example : ¬ UnivLE.{u+1, u} := by simp only [small_iff, not_forall, not_exists, not_nonempty_iff] exact ⟨Type u, fun α => ⟨fun f => Function.not_surjective_Type.{u, u} f.symm f.symm.surjective⟩⟩
Logic\Embedding\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 -/ import Mathlib.Data.Option.Basic import Mathlib.Data.Prod.PProd import Mathlib.Logic.Equiv.Basic /-! # Injective functions -/ universe u v w x namespace Function -- Porting note(#5171): this linter isn't ported yet. -- @[nolint has_nonempty_instance] /-- `α ↪ β` is a bundled injective function. -/ structure Embedding (α : Sort*) (β : Sort*) where /-- An embedding as a function. Use coercion instead. -/ toFun : α → β /-- An embedding is an injective function. Use `Function.Embedding.injective` instead. -/ inj' : Injective toFun /-- An embedding, a.k.a. a bundled injective function. -/ infixr:25 " ↪ " => Embedding instance {α : Sort u} {β : Sort v} : FunLike (α ↪ β) α β where coe := Embedding.toFun coe_injective' f g h := by { cases f; cases g; congr } instance {α : Sort u} {β : Sort v} : EmbeddingLike (α ↪ β) α β where injective' := Embedding.inj' initialize_simps_projections Embedding (toFun → apply) -- Porting note: this needs `tactic.lift`. --instance {α β : Sort*} : CanLift (α → β) (α ↪ β) coeFn Injective where prf f hf := ⟨⟨f, hf⟩, rfl⟩ theorem exists_surjective_iff {α β : Sort*} : (∃ f : α → β, Surjective f) ↔ Nonempty (α → β) ∧ Nonempty (β ↪ α) := ⟨fun ⟨f, h⟩ ↦ ⟨⟨f⟩, ⟨⟨_, injective_surjInv h⟩⟩⟩, fun ⟨h, ⟨e⟩⟩ ↦ (nonempty_fun.mp h).elim (fun _ ↦ ⟨isEmptyElim, (isEmptyElim <| e ·)⟩) fun _ ↦ ⟨_, invFun_surjective e.inj'⟩⟩ instance {α β : Sort*} : CanLift (α → β) (α ↪ β) (↑) Injective where prf _ h := ⟨⟨_, h⟩, rfl⟩ end Function section Equiv variable {α : Sort u} {β : Sort v} (f : α ≃ β) /-- Convert an `α ≃ β` to `α ↪ β`. This is also available as a coercion `Equiv.coeEmbedding`. The explicit `Equiv.toEmbedding` version is preferred though, since the coercion can have issues inferring the type of the resulting embedding. For example: ```lean -- Works: example (s : Finset (Fin 3)) (f : Equiv.Perm (Fin 3)) : s.map f.toEmbedding = s.map f := by simp -- Error, `f` has type `Fin 3 ≃ Fin 3` but is expected to have type `Fin 3 ↪ ?m_1 : Type ?` example (s : Finset (Fin 3)) (f : Equiv.Perm (Fin 3)) : s.map f = s.map f.toEmbedding := by simp ``` -/ protected def Equiv.toEmbedding : α ↪ β := ⟨f, f.injective⟩ @[simp] theorem Equiv.coe_toEmbedding : (f.toEmbedding : α → β) = f := rfl theorem Equiv.toEmbedding_apply (a : α) : f.toEmbedding a = f a := rfl theorem Equiv.toEmbedding_injective : Function.Injective (Equiv.toEmbedding : (α ≃ β) → (α ↪ β)) := fun _ _ h ↦ by rwa [DFunLike.ext'_iff] at h ⊢ instance Equiv.coeEmbedding : Coe (α ≃ β) (α ↪ β) := ⟨Equiv.toEmbedding⟩ @[instance] abbrev Equiv.Perm.coeEmbedding : Coe (Equiv.Perm α) (α ↪ α) := Equiv.coeEmbedding -- Porting note : `theorem Equiv.coe_eq_to_embedding : ↑f = f.toEmbedding` is a -- syntactic tautology in Lean 4 end Equiv namespace Function namespace Embedding theorem coe_injective {α β} : @Injective (α ↪ β) (α → β) (fun f ↦ ↑f) := DFunLike.coe_injective @[ext] theorem ext {α β} {f g : Embedding α β} (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h instance {α β : Sort*} [IsEmpty α] : Unique (α ↪ β) where default := ⟨isEmptyElim, Function.injective_of_subsingleton _⟩ uniq := by intro; ext v; exact isEmptyElim v @[simp] theorem toFun_eq_coe {α β} (f : α ↪ β) : toFun f = f := rfl @[simp] theorem coeFn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl @[simp] theorem mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f := rfl protected theorem injective {α β} (f : α ↪ β) : Injective f := EmbeddingLike.injective f theorem apply_eq_iff_eq {α β} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y := EmbeddingLike.apply_eq_iff_eq f /-- The identity map as a `Function.Embedding`. -/ @[refl, simps (config := { simpRhs := true })] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ /-- Composition of `f : α ↪ β` and `g : β ↪ γ`. -/ @[trans, simps (config := { simpRhs := true })] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.injective.comp f.injective⟩ instance : Trans Embedding Embedding Embedding := ⟨Embedding.trans⟩ @[simp] theorem equiv_toEmbedding_trans_symm_toEmbedding {α β : Sort*} (e : α ≃ β) : e.toEmbedding.trans e.symm.toEmbedding = Embedding.refl _ := by ext simp @[simp] theorem equiv_symm_toEmbedding_trans_toEmbedding {α β : Sort*} (e : α ≃ β) : e.symm.toEmbedding.trans e.toEmbedding = Embedding.refl _ := by ext simp /-- Transfer an embedding along a pair of equivalences. -/ @[simps! (config := { fullyApplied := false, simpRhs := true })] protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : β ↪ δ := (Equiv.toEmbedding e₁.symm).trans (f.trans e₂.toEmbedding) /-- A right inverse `surjInv` of a surjective function as an `Embedding`. -/ protected noncomputable def ofSurjective {α β} (f : β → α) (hf : Surjective f) : α ↪ β := ⟨surjInv hf, injective_surjInv _⟩ /-- Convert a surjective `Embedding` to an `Equiv` -/ protected noncomputable def equivOfSurjective {α β} (f : α ↪ β) (hf : Surjective f) : α ≃ β := Equiv.ofBijective f ⟨f.injective, hf⟩ /-- There is always an embedding from an empty type. -/ protected def ofIsEmpty {α β} [IsEmpty α] : α ↪ β := ⟨isEmptyElim, isEmptyElim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def setValue {α β : Sort*} (f : α ↪ β) (a : α) (b : β) [∀ a', Decidable (a' = a)] [∀ a', Decidable (f a' = b)] : α ↪ β := ⟨fun a' => if a' = a then b else if f a' = b then f a else f a', by intro x y (h : ite _ _ _ = ite _ _ _) split_ifs at h <;> (try subst b) <;> (try simp only [f.injective.eq_iff] at *) <;> cc⟩ @[simp] theorem setValue_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', Decidable (a' = a)] [∀ a', Decidable (f a' = b)] : setValue f a b a = b := by simp [setValue] @[simp] theorem setValue_eq_iff {α β} (f : α ↪ β) {a a' : α} {b : β} [∀ a', Decidable (a' = a)] [∀ a', Decidable (f a' = b)] : setValue f a b a' = b ↔ a' = a := (setValue f a b).injective.eq_iff' <| setValue_eq .. /-- Embedding into `Option α` using `some`. -/ @[simps (config := .asFn)] protected def some {α} : α ↪ Option α := ⟨some, Option.some_injective α⟩ -- Porting note: Lean 4 unfolds coercion `α → Option α` to `some`, so there is no separate -- `Function.Embedding.coeOption`. /-- A version of `Option.map` for `Function.Embedding`s. -/ @[simps (config := .asFn)] def optionMap {α β} (f : α ↪ β) : Option α ↪ Option β := ⟨Option.map f, Option.map_injective f.injective⟩ /-- Embedding of a `Subtype`. -/ def subtype {α} (p : α → Prop) : Subtype p ↪ α := ⟨Subtype.val, fun _ _ => Subtype.ext⟩ @[simp] theorem coe_subtype {α} (p : α → Prop) : ↑(subtype p) = Subtype.val := rfl /-- `Quotient.out` as an embedding. -/ noncomputable def quotientOut (α) [s : Setoid α] : Quotient s ↪ α := ⟨_, Quotient.out_injective⟩ @[simp] theorem coe_quotientOut (α) [Setoid α] : ↑(quotientOut α) = Quotient.out := rfl /-- Choosing an element `b : β` gives an embedding of `PUnit` into `β`. -/ def punit {β : Sort*} (b : β) : PUnit ↪ β := ⟨fun _ => b, by rintro ⟨⟩ ⟨⟩ _ rfl⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ @[simps] def sectl (α : Sort _) {β : Sort _} (b : β) : α ↪ α × β := ⟨fun a => (a, b), fun _ _ h => congr_arg Prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ @[simps] def sectr {α : Sort _} (a : α) (β : Sort _) : β ↪ α × β := ⟨fun b => (a, b), fun _ _ h => congr_arg Prod.snd h⟩ /-- If `e₁` and `e₂` are embeddings, then so is `Prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prodMap {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨Prod.map e₁ e₂, e₁.injective.prodMap e₂.injective⟩ @[simp] theorem coe_prodMap {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : e₁.prodMap e₂ = Prod.map e₁ e₂ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `fun ⟨a, b⟩ ↦ ⟨e₁ a, e₂ b⟩ : PProd α γ → PProd β δ`. -/ def pprodMap {α β γ δ : Sort*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : PProd α γ ↪ PProd β δ := ⟨fun x => ⟨e₁ x.1, e₂ x.2⟩, e₁.injective.pprod_map e₂.injective⟩ section Sum open Sum /-- If `e₁` and `e₂` are embeddings, then so is `Sum.map e₁ e₂`. -/ def sumMap {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨Sum.map e₁ e₂, e₁.injective.sum_map e₂.injective⟩ @[simp] theorem coe_sumMap {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : sumMap e₁ e₂ = Sum.map e₁ e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ @[simps] def inl {α β : Type*} : α ↪ α ⊕ β := ⟨Sum.inl, fun _ _ => Sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ @[simps] def inr {α β : Type*} : β ↪ α ⊕ β := ⟨Sum.inr, fun _ _ => Sum.inr.inj⟩ end Sum section Sigma variable {α α' : Type*} {β : α → Type*} {β' : α' → Type*} /-- `Sigma.mk` as a `Function.Embedding`. -/ @[simps apply] def sigmaMk (a : α) : β a ↪ Σx, β x := ⟨Sigma.mk a, sigma_mk_injective⟩ /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `Sigma.map f g` is an embedding. -/ @[simps apply] def sigmaMap (f : α ↪ α') (g : ∀ a, β a ↪ β' (f a)) : (Σa, β a) ↪ Σa', β' a' := ⟨Sigma.map f fun a => g a, f.injective.sigma_map fun a => (g a).injective⟩ end Sigma /-- Define an embedding `(Π a : α, β a) ↪ (Π a : α, γ a)` from a family of embeddings `e : Π a, (β a ↪ γ a)`. This embedding sends `f` to `fun a ↦ e a (f a)`. -/ @[simps] def piCongrRight {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (∀ a, β a) ↪ ∀ a, γ a := ⟨fun f a => e a (f a), fun _ _ h => funext fun a => (e a).injective (congr_fun h a)⟩ /-- An embedding `e : α ↪ β` defines an embedding `(γ → α) ↪ (γ → β)` that sends each `f` to `e ∘ f`. -/ def arrowCongrRight {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ γ → β := piCongrRight fun _ => e @[simp] theorem arrowCongrRight_apply {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) (f : γ → α) : arrowCongrRight e f = e ∘ f := rfl /-- An embedding `e : α ↪ β` defines an embedding `(α → γ) ↪ (β → γ)` for any inhabited type `γ`. This embedding sends each `f : α → γ` to a function `g : β → γ` such that `g ∘ e = f` and `g y = default` whenever `y ∉ range e`. -/ noncomputable def arrowCongrLeft {α : Sort u} {β : Sort v} {γ : Sort w} [Inhabited γ] (e : α ↪ β) : (α → γ) ↪ β → γ := ⟨fun f => extend e f default, fun f₁ f₂ h => funext fun x => by simpa only [e.injective.extend_apply] using congr_fun h (e x)⟩ /-- Restrict both domain and codomain of an embedding. -/ protected def subtypeMap {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀ ⦃x⦄, p x → q (f x)) : { x : α // p x } ↪ { y : β // q y } := ⟨Subtype.map f h, Subtype.map_injective h f.2⟩ open Set theorem swap_apply {α β : Type*} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (x y z : α) : Equiv.swap (f x) (f y) (f z) = f (Equiv.swap x y z) := f.injective.swap_apply x y z theorem swap_comp {α β : Type*} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (x y : α) : Equiv.swap (f x) (f y) ∘ f = f ∘ Equiv.swap x y := f.injective.swap_comp x y end Embedding end Function namespace Equiv open Function Embedding /-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding set. -/ @[simps!] def asEmbedding {β α : Sort*} {p : β → Prop} (e : α ≃ Subtype p) : α ↪ β := e.toEmbedding.trans (subtype p) /-- The type of embeddings `α ↪ β` is equivalent to the subtype of all injective functions `α → β`. -/ def subtypeInjectiveEquivEmbedding (α β : Sort*) : { f : α → β // Injective f } ≃ (α ↪ β) where toFun f := ⟨f.val, f.property⟩ invFun f := ⟨f, f.injective⟩ left_inv _ := rfl right_inv _ := rfl -- Porting note: in Lean 3 this had `@[congr]` /-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁` is equivalent to the type of embeddings `α₂ ↪ β₂`. -/ @[simps apply] def embeddingCongr {α β γ δ : Sort*} (h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) where toFun f := f.congr h h' invFun f := f.congr h.symm h'.symm left_inv x := by ext simp right_inv x := by ext simp @[simp] theorem embeddingCongr_refl {α β : Sort*} : embeddingCongr (Equiv.refl α) (Equiv.refl β) = Equiv.refl (α ↪ β) := rfl @[simp] theorem embeddingCongr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : embeddingCongr (e₁.trans e₂) (e₁'.trans e₂') = (embeddingCongr e₁ e₁').trans (embeddingCongr e₂ e₂') := rfl @[simp] theorem embeddingCongr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (embeddingCongr e₁ e₂).symm = embeddingCongr e₁.symm e₂.symm := rfl theorem embeddingCongr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) : Equiv.embeddingCongr ea ec (f.trans g) = (Equiv.embeddingCongr ea eb f).trans (Equiv.embeddingCongr eb ec g) := by ext simp @[simp] theorem refl_toEmbedding {α : Type*} : (Equiv.refl α).toEmbedding = Embedding.refl α := rfl @[simp] theorem trans_toEmbedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).toEmbedding = e.toEmbedding.trans f.toEmbedding := rfl end Equiv section Subtype variable {α : Type*} /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/ def subtypeOrLeftEmbedding (p q : α → Prop) [DecidablePred p] : { x // p x ∨ q x } ↪ { x // p x } ⊕ { x // q x } := ⟨fun x => if h : p x then Sum.inl ⟨x, h⟩ else Sum.inr ⟨x, x.prop.resolve_left h⟩, by intro x y dsimp only split_ifs <;> simp [Subtype.ext_iff]⟩ theorem subtypeOrLeftEmbedding_apply_left {p q : α → Prop} [DecidablePred p] (x : { x // p x ∨ q x }) (hx : p x) : subtypeOrLeftEmbedding p q x = Sum.inl ⟨x, hx⟩ := dif_pos hx theorem subtypeOrLeftEmbedding_apply_right {p q : α → Prop} [DecidablePred p] (x : { x // p x ∨ q x }) (hx : ¬p x) : subtypeOrLeftEmbedding p q x = Sum.inr ⟨x, x.prop.resolve_left hx⟩ := dif_neg hx /-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`, if `p x → q x` for all `x : α`. -/ @[simps] def Subtype.impEmbedding (p q : α → Prop) (h : ∀ x, p x → q x) : { x // p x } ↪ { x // q x } := ⟨fun x => ⟨x, h x x.prop⟩, fun x y => by simp [Subtype.ext_iff]⟩ end Subtype
Logic\Embedding\Set.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.Data.Set.Notation import Mathlib.Order.SetNotation import Mathlib.Logic.Embedding.Basic import Mathlib.Logic.Pairwise import Mathlib.Data.Set.Image /-! # Interactions between embeddings and sets. -/ universe u v w x open Set Set.Notation section Equiv variable {α : Sort u} {β : Sort v} (f : α ≃ β) @[simp] theorem Equiv.asEmbedding_range {α β : Sort _} {p : β → Prop} (e : α ≃ Subtype p) : Set.range e.asEmbedding = setOf p := Set.ext fun x ↦ ⟨fun ⟨y, h⟩ ↦ h ▸ Subtype.coe_prop (e y), fun hs ↦ ⟨e.symm ⟨x, hs⟩, by simp⟩⟩ end Equiv namespace Function namespace Embedding /-- Embedding into `WithTop α`. -/ @[simps] def coeWithTop {α} : α ↪ WithTop α := { Embedding.some with toFun := WithTop.some } /-- Given an embedding `f : α ↪ β` and a point outside of `Set.range f`, construct an embedding `Option α ↪ β`. -/ @[simps] def optionElim {α β} (f : α ↪ β) (x : β) (h : x ∉ Set.range f) : Option α ↪ β := ⟨Option.elim' x f, Option.injective_iff.2 ⟨f.2, h⟩⟩ /-- Equivalence between embeddings of `Option α` and a sigma type over the embeddings of `α`. -/ @[simps] def optionEmbeddingEquiv (α β) : (Option α ↪ β) ≃ Σ f : α ↪ β, ↥(Set.range f)ᶜ where toFun f := ⟨coeWithTop.trans f, f none, fun ⟨x, hx⟩ ↦ Option.some_ne_none x <| f.injective hx⟩ invFun f := f.1.optionElim f.2 f.2.2 left_inv f := ext <| by rintro (_ | _) <;> simp [Option.coe_def]; rfl right_inv := fun ⟨f, y, hy⟩ ↦ by ext <;> simp [Option.coe_def]; rfl /-- Restrict the codomain of an embedding. -/ def codRestrict {α β} (p : Set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨fun a ↦ ⟨f a, H a⟩, fun _ _ h ↦ f.injective (congr_arg Subtype.val h)⟩ @[simp] theorem codRestrict_apply {α β} (p) (f : α ↪ β) (H a) : codRestrict p f H a = ⟨f a, H a⟩ := rfl open Set /-- `Set.image` as an embedding `Set α ↪ Set β`. -/ @[simps apply] protected def image {α β} (f : α ↪ β) : Set α ↪ Set β := ⟨image f, f.2.image_injective⟩ end Embedding end Function namespace Set /-- The injection map is an embedding between subsets. -/ @[simps apply_coe] def embeddingOfSubset {α} (s t : Set α) (h : s ⊆ t) : s ↪ t := ⟨fun x ↦ ⟨x.1, h x.2⟩, fun ⟨x, hx⟩ ⟨y, hy⟩ h ↦ by congr injection h⟩ end Set section Subtype variable {α : Type*} /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` is equivalent to a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right, when `Disjoint p q`. See also `Equiv.sumCompl`, for when `IsCompl p q`. -/ @[simps apply] def subtypeOrEquiv (p q : α → Prop) [DecidablePred p] (h : Disjoint p q) : { x // p x ∨ q x } ≃ { x // p x } ⊕ { x // q x } where toFun := subtypeOrLeftEmbedding p q invFun := Sum.elim (Subtype.impEmbedding _ _ fun x hx ↦ (Or.inl hx : p x ∨ q x)) (Subtype.impEmbedding _ _ fun x hx ↦ (Or.inr hx : p x ∨ q x)) left_inv x := by by_cases hx : p x · rw [subtypeOrLeftEmbedding_apply_left _ hx] simp [Subtype.ext_iff] · rw [subtypeOrLeftEmbedding_apply_right _ hx] simp [Subtype.ext_iff] right_inv x := by cases x with | inl x => simp only [Sum.elim_inl] rw [subtypeOrLeftEmbedding_apply_left] · simp · simpa using x.prop | inr x => simp only [Sum.elim_inr] rw [subtypeOrLeftEmbedding_apply_right] · simp · suffices ¬p x by simpa intro hp simpa using h.le_bot x ⟨hp, x.prop⟩ @[simp] theorem subtypeOrEquiv_symm_inl (p q : α → Prop) [DecidablePred p] (h : Disjoint p q) (x : { x // p x }) : (subtypeOrEquiv p q h).symm (Sum.inl x) = ⟨x, Or.inl x.prop⟩ := rfl @[simp] theorem subtypeOrEquiv_symm_inr (p q : α → Prop) [DecidablePred p] (h : Disjoint p q) (x : { x // q x }) : (subtypeOrEquiv p q h).symm (Sum.inr x) = ⟨x, Or.inr x.prop⟩ := rfl end Subtype section Disjoint variable {α ι : Type*} {s t r : Set α} /-- For disjoint `s t : Set α`, the natural injection from `↑s ⊕ ↑t` to `α`. -/ @[simps] def Function.Embedding.sumSet (h : Disjoint s t) : s ⊕ t ↪ α where toFun := Sum.elim (↑) (↑) inj' := by rintro (⟨a, ha⟩ | ⟨a, ha⟩) (⟨b, hb⟩ | ⟨b, hb⟩) · simp [Subtype.val_inj] · simpa using h.ne_of_mem ha hb · simpa using h.symm.ne_of_mem ha hb simp [Subtype.val_inj] @[norm_cast] lemma Function.Embedding.coe_sumSet (h : Disjoint s t) : (Function.Embedding.sumSet h : s ⊕ t → α) = Sum.elim (↑) (↑) := rfl @[simp] theorem Function.Embedding.sumSet_preimage_inl (h : Disjoint s t) : .inl ⁻¹' (Function.Embedding.sumSet h ⁻¹' r) = r ∩ s := by simp [Set.ext_iff] @[simp] theorem Function.Embedding.sumSet_preimage_inr (h : Disjoint s t) : .inr ⁻¹' (Function.Embedding.sumSet h ⁻¹' r) = r ∩ t := by simp [Set.ext_iff] @[simp] theorem Function.Embedding.sumSet_range {s t : Set α} (h : Disjoint s t) : range (Function.Embedding.sumSet h) = s ∪ t := by simp [Set.ext_iff] /-- For an indexed family `s : ι → Set α` of disjoint sets, the natural injection from the sigma-type `(i : ι) × ↑(s i)` to `α`. -/ @[simps] def Function.Embedding.sigmaSet {s : ι → Set α} (h : Pairwise (Disjoint on s)) : (i : ι) × s i ↪ α where toFun x := x.2.1 inj' := by rintro ⟨i, x, hx⟩ ⟨j, -, hx'⟩ rfl obtain rfl : i = j := h.eq (not_disjoint_iff.2 ⟨_, hx, hx'⟩) rfl @[norm_cast] lemma Function.Embedding.coe_sigmaSet {s : ι → Set α} (h) : (Function.Embedding.sigmaSet h : ((i : ι) × s i) → α) = fun x ↦ x.2.1 := rfl @[simp] theorem Function.Embedding.sigmaSet_preimage {s : ι → Set α} (h : Pairwise (Disjoint on s)) (i : ι) (r : Set α) : Sigma.mk i ⁻¹' (Function.Embedding.sigmaSet h ⁻¹' r) = r ∩ s i := by simp [Set.ext_iff] @[simp] theorem Function.Embedding.sigmaSet_range {s : ι → Set α} (h : Pairwise (Disjoint on s)) : Set.range (Function.Embedding.sigmaSet h) = ⋃ i, s i := by simp [Set.ext_iff] end Disjoint
Logic\Encodable\Basic.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import Mathlib.Data.Countable.Defs import Mathlib.Data.Fin.Basic import Mathlib.Data.Nat.Find import Mathlib.Data.PNat.Equiv import Mathlib.Logic.Equiv.Nat import Mathlib.Order.Directed import Mathlib.Order.RelIso.Basic /-! # Encodable types This file defines encodable (constructively countable) types as a typeclass. This is used to provide explicit encode/decode functions from and to `ℕ`, with the information that those functions are inverses of each other. The difference with `Denumerable` is that finite types are encodable. For infinite types, `Encodable` and `Denumerable` agree. ## Main declarations * `Encodable α`: States that there exists an explicit encoding function `encode : α → ℕ` with a partial inverse `decode : ℕ → Option α`. * `decode₂`: Version of `decode` that is equal to `none` outside of the range of `encode`. Useful as we do not require this in the definition of `decode`. * `ULower α`: Any encodable type has an equivalent type living in the lowest universe, namely a subtype of `ℕ`. `ULower α` finds it. ## Implementation notes The point of asking for an explicit partial inverse `decode : ℕ → Option α` to `encode : α → ℕ` is to make the range of `encode` decidable even when the finiteness of `α` is not. -/ open Option List Nat Function /-- Constructively countable type. Made from an explicit injection `encode : α → ℕ` and a partial inverse `decode : ℕ → Option α`. Note that finite types *are* countable. See `Denumerable` if you wish to enforce infiniteness. -/ class Encodable (α : Type*) where /-- Encoding from Type α to ℕ -/ encode : α → ℕ -- Porting note: was `decode [] : ℕ → Option α`. This means that `decode` does not take the type --explicitly in Lean4 /-- Decoding from ℕ to Option α-/ decode : ℕ → Option α /-- Invariant relationship between encoding and decoding-/ encodek : ∀ a, decode (encode a) = some a attribute [simp] Encodable.encodek namespace Encodable variable {α : Type*} {β : Type*} universe u theorem encode_injective [Encodable α] : Function.Injective (@encode α _) | x, y, e => Option.some.inj <| by rw [← encodek, e, encodek] @[simp] theorem encode_inj [Encodable α] {a b : α} : encode a = encode b ↔ a = b := encode_injective.eq_iff -- The priority of the instance below is less than the priorities of `Subtype.Countable` -- and `Quotient.Countable` instance (priority := 400) countable [Encodable α] : Countable α where exists_injective_nat' := ⟨_,encode_injective⟩ theorem surjective_decode_iget (α : Type*) [Encodable α] [Inhabited α] : Surjective fun n => ((Encodable.decode n).iget : α) := fun x => ⟨Encodable.encode x, by simp_rw [Encodable.encodek]⟩ /-- An encodable type has decidable equality. Not set as an instance because this is usually not the best way to infer decidability. -/ def decidableEqOfEncodable (α) [Encodable α] : DecidableEq α | _, _ => decidable_of_iff _ encode_inj /-- If `α` is encodable and there is an injection `f : β → α`, then `β` is encodable as well. -/ def ofLeftInjection [Encodable α] (f : β → α) (finv : α → Option β) (linv : ∀ b, finv (f b) = some b) : Encodable β := ⟨fun b => encode (f b), fun n => (decode n).bind finv, fun b => by simp [Encodable.encodek, linv]⟩ /-- If `α` is encodable and `f : β → α` is invertible, then `β` is encodable as well. -/ def ofLeftInverse [Encodable α] (f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : Encodable β := ofLeftInjection f (some ∘ finv) fun b => congr_arg some (linv b) /-- Encodability is preserved by equivalence. -/ def ofEquiv (α) [Encodable α] (e : β ≃ α) : Encodable β := ofLeftInverse e e.symm e.left_inv -- Porting note: removing @[simp], too powerful theorem encode_ofEquiv {α β} [Encodable α] (e : β ≃ α) (b : β) : @encode _ (ofEquiv _ e) b = encode (e b) := rfl -- Porting note: removing @[simp], too powerful theorem decode_ofEquiv {α β} [Encodable α] (e : β ≃ α) (n : ℕ) : @decode _ (ofEquiv _ e) n = (decode n).map e.symm := show Option.bind _ _ = Option.map _ _ by rw [Option.map_eq_bind] instance _root_.Nat.encodable : Encodable ℕ := ⟨id, some, fun _ => rfl⟩ @[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl @[simp 1100] theorem decode_nat (n : ℕ) : decode n = some n := rfl instance (priority := 100) _root_.IsEmpty.toEncodable [IsEmpty α] : Encodable α := ⟨isEmptyElim, fun _ => none, isEmptyElim⟩ instance _root_.PUnit.encodable : Encodable PUnit := ⟨fun _ => 0, fun n => Nat.casesOn n (some PUnit.unit) fun _ => none, fun _ => by simp⟩ @[simp] theorem encode_star : encode PUnit.unit = 0 := rfl @[simp] theorem decode_unit_zero : decode 0 = some PUnit.unit := rfl @[simp] theorem decode_unit_succ (n) : decode (succ n) = (none : Option PUnit) := rfl /-- If `α` is encodable, then so is `Option α`. -/ instance _root_.Option.encodable {α : Type*} [h : Encodable α] : Encodable (Option α) := ⟨fun o => Option.casesOn o Nat.zero fun a => succ (encode a), fun n => Nat.casesOn n (some none) fun m => (decode m).map some, fun o => by cases o <;> dsimp; simp [encodek, Nat.succ_ne_zero]⟩ @[simp] theorem encode_none [Encodable α] : encode (@none α) = 0 := rfl @[simp] theorem encode_some [Encodable α] (a : α) : encode (some a) = succ (encode a) := rfl @[simp] theorem decode_option_zero [Encodable α] : (decode 0 : Option (Option α))= some none := rfl @[simp] theorem decode_option_succ [Encodable α] (n) : (decode (succ n) : Option (Option α)) = (decode n).map some := rfl /-- Failsafe variant of `decode`. `decode₂ α n` returns the preimage of `n` under `encode` if it exists, and returns `none` if it doesn't. This requirement could be imposed directly on `decode` but is not to help make the definition easier to use. -/ def decode₂ (α) [Encodable α] (n : ℕ) : Option α := (decode n).bind (Option.guard fun a => encode a = n) theorem mem_decode₂' [Encodable α] {n : ℕ} {a : α} : a ∈ decode₂ α n ↔ a ∈ decode n ∧ encode a = n := by simpa [decode₂, bind_eq_some] using ⟨fun ⟨_, h₁, rfl, h₂⟩ => ⟨h₁, h₂⟩, fun ⟨h₁, h₂⟩ => ⟨_, h₁, rfl, h₂⟩⟩ theorem mem_decode₂ [Encodable α] {n : ℕ} {a : α} : a ∈ decode₂ α n ↔ encode a = n := mem_decode₂'.trans (and_iff_right_of_imp fun e => e ▸ encodek _) theorem decode₂_eq_some [Encodable α] {n : ℕ} {a : α} : decode₂ α n = some a ↔ encode a = n := mem_decode₂ @[simp] theorem decode₂_encode [Encodable α] (a : α) : decode₂ α (encode a) = some a := by ext simp [mem_decode₂, eq_comm, decode₂_eq_some] theorem decode₂_ne_none_iff [Encodable α] {n : ℕ} : decode₂ α n ≠ none ↔ n ∈ Set.range (encode : α → ℕ) := by simp_rw [Set.range, Set.mem_setOf_eq, Ne, Option.eq_none_iff_forall_not_mem, Encodable.mem_decode₂, not_forall, not_not] theorem decode₂_is_partial_inv [Encodable α] : IsPartialInv encode (decode₂ α) := fun _ _ => mem_decode₂ theorem decode₂_inj [Encodable α] {n : ℕ} {a₁ a₂ : α} (h₁ : a₁ ∈ decode₂ α n) (h₂ : a₂ ∈ decode₂ α n) : a₁ = a₂ := encode_injective <| (mem_decode₂.1 h₁).trans (mem_decode₂.1 h₂).symm theorem encodek₂ [Encodable α] (a : α) : decode₂ α (encode a) = some a := mem_decode₂.2 rfl /-- The encoding function has decidable range. -/ def decidableRangeEncode (α : Type*) [Encodable α] : DecidablePred (· ∈ Set.range (@encode α _)) := fun x => decidable_of_iff (Option.isSome (decode₂ α x)) ⟨fun h => ⟨Option.get _ h, by rw [← decode₂_is_partial_inv (Option.get _ h), Option.some_get]⟩, fun ⟨n, hn⟩ => by rw [← hn, encodek₂]; exact rfl⟩ /-- An encodable type is equivalent to the range of its encoding function. -/ def equivRangeEncode (α : Type*) [Encodable α] : α ≃ Set.range (@encode α _) where toFun := fun a : α => ⟨encode a, Set.mem_range_self _⟩ invFun n := Option.get _ (show isSome (decode₂ α n.1) by cases' n.2 with x hx; rw [← hx, encodek₂]; exact rfl) left_inv a := by dsimp; rw [← Option.some_inj, Option.some_get, encodek₂] right_inv := fun ⟨n, x, hx⟩ => by apply Subtype.eq dsimp conv => rhs rw [← hx] rw [encode_injective.eq_iff, ← Option.some_inj, Option.some_get, ← hx, encodek₂] /-- A type with unique element is encodable. This is not an instance to avoid diamonds. -/ def _root_.Unique.encodable [Unique α] : Encodable α := ⟨fun _ => 0, fun _ => some default, Unique.forall_iff.2 rfl⟩ section Sum variable [Encodable α] [Encodable β] -- Porting note: removing bit0 and bit1 /-- Explicit encoding function for the sum of two encodable types. -/ def encodeSum : α ⊕ β → ℕ | Sum.inl a => 2 * encode a | Sum.inr b => 2 * encode b + 1 /-- Explicit decoding function for the sum of two encodable types. -/ def decodeSum (n : ℕ) : Option (α ⊕ β) := match boddDiv2 n with | (false, m) => (decode m : Option α).map Sum.inl | (_, m) => (decode m : Option β).map Sum.inr /-- If `α` and `β` are encodable, then so is their sum. -/ instance _root_.Sum.encodable : Encodable (α ⊕ β) := ⟨encodeSum, decodeSum, fun s => by cases s <;> simp [encodeSum, div2_val, decodeSum, encodek]⟩ -- Porting note: removing bit0 and bit1 from statement @[simp] theorem encode_inl (a : α) : @encode (α ⊕ β) _ (Sum.inl a) = 2 * (encode a) := rfl -- Porting note: removing bit0 and bit1 from statement @[simp] theorem encode_inr (b : β) : @encode (α ⊕ β) _ (Sum.inr b) = 2 * (encode b) + 1 := rfl @[simp] theorem decode_sum_val (n : ℕ) : (decode n : Option (α ⊕ β)) = decodeSum n := rfl end Sum instance _root_.Bool.encodable : Encodable Bool := ofEquiv (Unit ⊕ Unit) Equiv.boolEquivPUnitSumPUnit @[simp] theorem encode_true : encode true = 1 := rfl @[simp] theorem encode_false : encode false = 0 := rfl @[simp] theorem decode_zero : (decode 0 : Option Bool) = some false := rfl @[simp] theorem decode_one : (decode 1 : Option Bool) = some true := rfl theorem decode_ge_two (n) (h : 2 ≤ n) : (decode n : Option Bool) = none := by suffices decodeSum n = none by change (decodeSum n).bind _ = none rw [this] rfl have : 1 ≤ n / 2 := by rw [Nat.le_div_iff_mul_le] exacts [h, by decide] cases' exists_eq_succ_of_ne_zero (_root_.ne_of_gt this) with m e simp only [decodeSum, boddDiv2_eq, div2_val]; cases bodd n <;> simp [e] noncomputable instance _root_.Prop.encodable : Encodable Prop := ofEquiv Bool Equiv.propEquivBool section Sigma variable {γ : α → Type*} [Encodable α] [∀ a, Encodable (γ a)] /-- Explicit encoding function for `Sigma γ` -/ def encodeSigma : Sigma γ → ℕ | ⟨a, b⟩ => pair (encode a) (encode b) /-- Explicit decoding function for `Sigma γ` -/ def decodeSigma (n : ℕ) : Option (Sigma γ) := let (n₁, n₂) := unpair n (decode n₁).bind fun a => (decode n₂).map <| Sigma.mk a instance _root_.Sigma.encodable : Encodable (Sigma γ) := ⟨encodeSigma, decodeSigma, fun ⟨a, b⟩ => by simp [encodeSigma, decodeSigma, unpair_pair, encodek]⟩ @[simp] theorem decode_sigma_val (n : ℕ) : (decode n : Option (Sigma γ)) = (decode n.unpair.1).bind fun a => (decode n.unpair.2).map <| Sigma.mk a := rfl @[simp] theorem encode_sigma_val (a b) : @encode (Sigma γ) _ ⟨a, b⟩ = pair (encode a) (encode b) := rfl end Sigma section Prod variable [Encodable α] [Encodable β] /-- If `α` and `β` are encodable, then so is their product. -/ instance Prod.encodable : Encodable (α × β) := ofEquiv _ (Equiv.sigmaEquivProd α β).symm @[simp] theorem decode_prod_val (n : ℕ) : (@decode (α × β) _ n : Option (α × β)) = (decode n.unpair.1).bind fun a => (decode n.unpair.2).map <| Prod.mk a := by simp only [decode_ofEquiv, Equiv.symm_symm, decode_sigma_val] cases (decode n.unpair.1 : Option α) <;> cases (decode n.unpair.2 : Option β) <;> rfl @[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) = pair (encode a) (encode b) := rfl end Prod section Subtype open Subtype Decidable variable {P : α → Prop} [encA : Encodable α] [decP : DecidablePred P] /-- Explicit encoding function for a decidable subtype of an encodable type -/ def encodeSubtype : { a : α // P a } → ℕ | ⟨v,_⟩ => encode v /-- Explicit decoding function for a decidable subtype of an encodable type -/ def decodeSubtype (v : ℕ) : Option { a : α // P a } := (decode v).bind fun a => if h : P a then some ⟨a, h⟩ else none /-- A decidable subtype of an encodable type is encodable. -/ instance _root_.Subtype.encodable : Encodable { a : α // P a } := ⟨encodeSubtype, decodeSubtype, fun ⟨v, h⟩ => by simp [encodeSubtype, decodeSubtype, encodek, h]⟩ theorem Subtype.encode_eq (a : Subtype P) : encode a = encode a.val := by cases a; rfl end Subtype instance _root_.Fin.encodable (n) : Encodable (Fin n) := ofEquiv _ Fin.equivSubtype instance _root_.Int.encodable : Encodable ℤ := ofEquiv _ Equiv.intEquivNat instance _root_.PNat.encodable : Encodable ℕ+ := ofEquiv _ Equiv.pnatEquivNat /-- The lift of an encodable type is encodable -/ instance _root_.ULift.encodable [Encodable α] : Encodable (ULift α) := ofEquiv _ Equiv.ulift /-- The lift of an encodable type is encodable. -/ instance _root_.PLift.encodable [Encodable α] : Encodable (PLift α) := ofEquiv _ Equiv.plift /-- If `β` is encodable and there is an injection `f : α → β`, then `α` is encodable as well. -/ noncomputable def ofInj [Encodable β] (f : α → β) (hf : Injective f) : Encodable α := ofLeftInjection f (partialInv f) fun _ => (partialInv_of_injective hf _ _).2 rfl /-- If `α` is countable, then it has a (non-canonical) `Encodable` structure. -/ noncomputable def ofCountable (α : Type*) [Countable α] : Encodable α := Nonempty.some <| let ⟨f, hf⟩ := exists_injective_nat α ⟨ofInj f hf⟩ @[simp] theorem nonempty_encodable : Nonempty (Encodable α) ↔ Countable α := ⟨fun ⟨h⟩ => @Encodable.countable α h, fun h => ⟨@ofCountable _ h⟩⟩ end Encodable /-- See also `nonempty_fintype`, `nonempty_denumerable`. -/ theorem nonempty_encodable (α : Type*) [Countable α] : Nonempty (Encodable α) := ⟨Encodable.ofCountable _⟩ instance : Countable ℕ+ := by delta PNat; infer_instance -- short-circuit instance search section ULower attribute [local instance] Encodable.decidableRangeEncode /-- `ULower α : Type` is an equivalent type in the lowest universe, given `Encodable α`. -/ def ULower (α : Type*) [Encodable α] : Type := Set.range (Encodable.encode : α → ℕ) instance {α : Type*} [Encodable α] : DecidableEq (ULower α) := by delta ULower; exact Encodable.decidableEqOfEncodable _ instance {α : Type*} [Encodable α] : Encodable (ULower α) := by delta ULower; infer_instance end ULower namespace ULower variable (α : Type*) [Encodable α] /-- The equivalence between the encodable type `α` and `ULower α : Type`. -/ def equiv : α ≃ ULower α := Encodable.equivRangeEncode α variable {α} /-- Lowers an `a : α` into `ULower α`. -/ def down (a : α) : ULower α := equiv α a instance [Inhabited α] : Inhabited (ULower α) := ⟨down default⟩ /-- Lifts an `a : ULower α` into `α`. -/ def up (a : ULower α) : α := (equiv α).symm a @[simp] theorem down_up {a : ULower α} : down a.up = a := Equiv.right_inv _ _ @[simp] theorem up_down {a : α} : (down a).up = a := by simp [up, down,Equiv.left_inv _ _, Equiv.symm_apply_apply] @[simp] theorem up_eq_up {a b : ULower α} : a.up = b.up ↔ a = b := Equiv.apply_eq_iff_eq _ @[simp] theorem down_eq_down {a b : α} : down a = down b ↔ a = b := Equiv.apply_eq_iff_eq _ @[ext] protected theorem ext {a b : ULower α} : a.up = b.up → a = b := up_eq_up.1 end ULower /- Choice function for encodable types and decidable predicates. We provide the following API choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α := choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ namespace Encodable section FindA variable {α : Type*} (p : α → Prop) [Encodable α] [DecidablePred p] private def good : Option α → Prop | some a => p a | none => False private def decidable_good : DecidablePred (good p) := fun n => by cases n <;> unfold good <;> dsimp <;> infer_instance attribute [local instance] decidable_good open Encodable variable {p} /-- Constructive choice function for a decidable subtype of an encodable type. -/ def chooseX (h : ∃ x, p x) : { a : α // p a } := have : ∃ n, good p (decode n) := let ⟨w, pw⟩ := h ⟨encode w, by simp [good, encodek, pw]⟩ match (motive := ∀ o, good p o → { a // p a }) _, Nat.find_spec this with | some a, h => ⟨a, h⟩ /-- Constructive choice function for a decidable predicate over an encodable type. -/ def choose (h : ∃ x, p x) : α := (chooseX h).1 theorem choose_spec (h : ∃ x, p x) : p (choose h) := (chooseX h).2 end FindA /-- A constructive version of `Classical.axiom_of_choice` for `Encodable` types. -/ theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : ∀ x, β x → Prop} [∀ a, Encodable (β a)] [∀ x y, Decidable (R x y)] (H : ∀ x, ∃ y, R x y) : ∃ f : ∀ a, β a, ∀ x, R x (f x) := ⟨fun x => choose (H x), fun x => choose_spec (H x)⟩ /-- A constructive version of `Classical.skolem` for `Encodable` types. -/ theorem skolem {α : Type*} {β : α → Type*} {P : ∀ x, β x → Prop} [∀ a, Encodable (β a)] [∀ x y, Decidable (P x y)] : (∀ x, ∃ y, P x y) ↔ ∃ f : ∀ a, β a, ∀ x, P x (f x) := ⟨axiom_of_choice, fun ⟨_, H⟩ x => ⟨_, H x⟩⟩ /- There is a total ordering on the elements of an encodable type, induced by the map to ℕ. -/ /-- The `encode` function, viewed as an embedding. -/ def encode' (α) [Encodable α] : α ↪ ℕ := ⟨Encodable.encode, Encodable.encode_injective⟩ instance {α} [Encodable α] : IsAntisymm _ (Encodable.encode' α ⁻¹'o (· ≤ ·)) := (RelEmbedding.preimage _ _).isAntisymm instance {α} [Encodable α] : IsTotal _ (Encodable.encode' α ⁻¹'o (· ≤ ·)) := (RelEmbedding.preimage _ _).isTotal end Encodable namespace Directed open Encodable variable {α : Type*} {β : Type*} [Encodable α] [Inhabited α] /-- Given a `Directed r` function `f : α → β` defined on an encodable inhabited type, construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))` and `r (f a) (f (x (encode a + 1))`. -/ protected noncomputable def sequence {r : β → β → Prop} (f : α → β) (hf : Directed r f) : ℕ → α | 0 => default | n + 1 => let p := Directed.sequence f hf n match (decode n : Option α) with | none => Classical.choose (hf p p) | some a => Classical.choose (hf p a) theorem sequence_mono_nat {r : β → β → Prop} {f : α → β} (hf : Directed r f) (n : ℕ) : r (f (hf.sequence f n)) (f (hf.sequence f (n + 1))) := by dsimp [Directed.sequence] generalize hf.sequence f n = p cases' (decode n : Option α) with a · exact (Classical.choose_spec (hf p p)).1 · exact (Classical.choose_spec (hf p a)).1 theorem rel_sequence {r : β → β → Prop} {f : α → β} (hf : Directed r f) (a : α) : r (f a) (f (hf.sequence f (encode a + 1))) := by simp only [Directed.sequence, add_eq, add_zero, encodek, and_self] exact (Classical.choose_spec (hf _ a)).2 variable [Preorder β] {f : α → β} section variable (hf : Directed (· ≤ ·) f) theorem sequence_mono : Monotone (f ∘ hf.sequence f) := monotone_nat_of_le_succ <| hf.sequence_mono_nat theorem le_sequence (a : α) : f a ≤ f (hf.sequence f (encode a + 1)) := hf.rel_sequence a end section variable (hf : Directed (· ≥ ·) f) theorem sequence_anti : Antitone (f ∘ hf.sequence f) := antitone_nat_of_succ_le <| hf.sequence_mono_nat theorem sequence_le (a : α) : f (hf.sequence f (Encodable.encode a + 1)) ≤ f a := hf.rel_sequence a end end Directed section Quotient open Encodable Quotient variable {α : Type*} {s : Setoid α} [@DecidableRel α (· ≈ ·)] [Encodable α] /-- Representative of an equivalence class. This is a computable version of `Quot.out` for a setoid on an encodable type. -/ def Quotient.rep (q : Quotient s) : α := choose (exists_rep q) theorem Quotient.rep_spec (q : Quotient s) : ⟦q.rep⟧ = q := choose_spec (exists_rep q) /-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/ def encodableQuotient : Encodable (Quotient s) := ⟨fun q => encode q.rep, fun n => Quotient.mk'' <$> decode n, by rintro ⟨l⟩; dsimp; rw [encodek]; exact congr_arg some ⟦l⟧.rep_spec⟩ end Quotient
Logic\Encodable\Lattice.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Logic.Encodable.Basic import Mathlib.Logic.Pairwise import Mathlib.Data.Set.Subsingleton /-! # Lattice operations on encodable types Lemmas about lattice and set operations on encodable types ## Implementation Notes This is a separate file, to avoid unnecessary imports in basic files. Previously some of these results were in the `MeasureTheory` folder. -/ open Set namespace Encodable variable {α : Type*} {β : Type*} [Encodable β] theorem iSup_decode₂ [CompleteLattice α] (f : β → α) : ⨆ (i : ℕ) (b ∈ decode₂ β i), f b = (⨆ b, f b) := by rw [iSup_comm] simp only [mem_decode₂, iSup_iSup_eq_right] theorem iUnion_decode₂ (f : β → Set α) : ⋃ (i : ℕ) (b ∈ decode₂ β i), f b = ⋃ b, f b := iSup_decode₂ f /- Porting note: `@[elab_as_elim]` gives `unexpected eliminator resulting type`. -/ --@[elab_as_elim] theorem iUnion_decode₂_cases {f : β → Set α} {C : Set α → Prop} (H0 : C ∅) (H1 : ∀ b, C (f b)) {n} : C (⋃ b ∈ decode₂ β n, f b) := match decode₂ β n with | none => by simp only [Option.mem_def, iUnion_of_empty, iUnion_empty] apply H0 | some b => by convert H1 b simp [Set.ext_iff] theorem iUnion_decode₂_disjoint_on {f : β → Set α} (hd : Pairwise (Disjoint on f)) : Pairwise (Disjoint on fun i => ⋃ b ∈ decode₂ β i, f b) := by rintro i j ij refine disjoint_left.mpr fun x => ?_ suffices ∀ a, encode a = i → x ∈ f a → ∀ b, encode b = j → x ∉ f b by simpa [decode₂_eq_some] rintro a rfl ha b rfl hb exact (hd (mt (congr_arg encode) ij)).le_bot ⟨ha, hb⟩ end Encodable
Logic\Equiv\Array.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.Data.Vector.Basic import Mathlib.Logic.Equiv.List /-! # Equivalences involving `Array` -/ /- Porting note: The following commented-out definitions only made sense for the mathlib3 datatypes `d_array` and `array`. `d_array` (a dependent array) does not yet (as of Jun 27 2023) have a corresponding datatype in lean4/std4/mathlib4; `array` was length-indexed and therefore more similar to `Vector`, which may be reimplemented in terms of `Array` internally anyway in the future. However, we have tried to align `array` with `Array` where possible nonetheless, and therefore we introduce the "right" equivalence for `Array` (`arrayEquivList`) and align the instances `array.encodable`, `array.countable` with `Array.encodable`, `Array.countable` respectively. -/ namespace Equiv -- /-- The natural equivalence between length-`n` heterogeneous arrays -- and dependent functions from `Fin n`. -/ -- def darrayEquivFin {n : ℕ} (α : Fin n → Type*) : DArray n α ≃ ∀ i, α i := -- ⟨DArray.read, DArray.mk, fun ⟨f⟩ => rfl, fun f => rfl⟩ -- /-- The natural equivalence between length-`n` arrays and functions from `Fin n`. -/ -- def array'EquivFin (n : ℕ) (α : Type*) : Array' n α ≃ (Fin n → α) := -- darrayEquivFin _ -- /-- The natural equivalence between length-`n` vectors and length-`n` arrays. -/ -- def vectorEquivArray' (α : Type*) (n : ℕ) : Vector α n ≃ Array' n α := -- (vectorEquivFin _ _).trans (array'EquivFin _ _).symm /-- The natural equivalence between arrays and lists. -/ def arrayEquivList (α : Type*) : Array α ≃ List α := ⟨Array.data, Array.mk, fun _ => rfl, fun _ => rfl⟩ end Equiv /- Porting note: removed instances for what would be ported as `Traversable (Array α)` and `LawfulTraversable (Array α)`. These would 1. be implemented directly in terms of `Array` functionality for efficiency, rather than being the traversal of some other type transported along an equivalence to `Array α` (as the traversable instance for `array` was) 2. belong in `Mathlib.Control.Traversable.Instances` instead of this file. -/ -- namespace Array' -- open Function -- variable {n : ℕ} -- instance : Traversable (Array' n) := -- @Equiv.traversable (flip Vector n) _ (fun α => Equiv.vectorEquivArray α n) _ -- instance : LawfulTraversable (Array' n) := -- @Equiv.isLawfulTraversable (flip Vector n) _ (fun α => Equiv.vectorEquivArray α n) _ _ -- end Array' /-- If `α` is encodable, then so is `Array α`. -/ instance Array.encodable {α} [Encodable α] : Encodable (Array α) := Encodable.ofEquiv _ (Equiv.arrayEquivList _) /-- If `α` is countable, then so is `Array α`. -/ instance Array.countable {α} [Countable α] : Countable (Array α) := Countable.of_equiv _ (Equiv.arrayEquivList α).symm
Logic\Equiv\Basic.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import Mathlib.Data.Bool.Basic import Mathlib.Data.Option.Defs import Mathlib.Data.Prod.Basic import Mathlib.Data.Sigma.Basic import Mathlib.Data.Subtype import Mathlib.Data.Sum.Basic import Mathlib.Init.Data.Sigma.Basic import Mathlib.Logic.Equiv.Defs import Mathlib.Logic.Function.Conjugate import Mathlib.Tactic.Coe import Mathlib.Tactic.Lift import Mathlib.Tactic.Convert import Mathlib.Tactic.Contrapose import Mathlib.Tactic.GeneralizeProofs import Mathlib.Tactic.SimpRw import Mathlib.Tactic.CC /-! # Equivalence between types In this file we continue the work on equivalences begun in `Logic/Equiv/Defs.lean`, defining * canonical isomorphisms between various types: e.g., - `Equiv.sumEquivSigmaBool` is the canonical equivalence between the sum of two types `α ⊕ β` and the sigma-type `Σ b : Bool, b.casesOn α β`; - `Equiv.prodSumDistrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum satisfy the distributive law up to a canonical equivalence; * operations on equivalences: e.g., - `Equiv.prodCongr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and `eb : β₁ ≃ β₂` using `Prod.map`. More definitions of this kind can be found in other files. E.g., `Data/Equiv/TransferInstance.lean` does it for many algebraic type classes like `Group`, `Module`, etc. ## Tags equivalence, congruence, bijective map -/ set_option autoImplicit true universe u open Function namespace Equiv /-- `PProd α β` is equivalent to `α × β` -/ @[simps apply symm_apply] def pprodEquivProd : PProd α β ≃ α × β where toFun x := (x.1, x.2) invFun x := ⟨x.1, x.2⟩ left_inv := fun _ => rfl right_inv := fun _ => rfl /-- Product of two equivalences, in terms of `PProd`. If `α ≃ β` and `γ ≃ δ`, then `PProd α γ ≃ PProd β δ`. -/ -- Porting note: in Lean 3 this had `@[congr]` @[simps apply] def pprodCongr (e₁ : α ≃ β) (e₂ : γ ≃ δ) : PProd α γ ≃ PProd β δ where toFun x := ⟨e₁ x.1, e₂ x.2⟩ invFun x := ⟨e₁.symm x.1, e₂.symm x.2⟩ left_inv := fun ⟨x, y⟩ => by simp right_inv := fun ⟨x, y⟩ => by simp /-- Combine two equivalences using `PProd` in the domain and `Prod` in the codomain. -/ @[simps! apply symm_apply] def pprodProd (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : PProd α₁ β₁ ≃ α₂ × β₂ := (ea.pprodCongr eb).trans pprodEquivProd /-- Combine two equivalences using `PProd` in the codomain and `Prod` in the domain. -/ @[simps! apply symm_apply] def prodPProd (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ × β₁ ≃ PProd α₂ β₂ := (ea.symm.pprodProd eb.symm).symm /-- `PProd α β` is equivalent to `PLift α × PLift β` -/ @[simps! apply symm_apply] def pprodEquivProdPLift : PProd α β ≃ PLift α × PLift β := Equiv.plift.symm.pprodProd Equiv.plift.symm /-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. This is `Prod.map` as an equivalence. -/ -- Porting note: in Lean 3 there was also a @[congr] tag @[simps (config := .asFn) apply] def prodCongr (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨Prod.map e₁ e₂, Prod.map e₁.symm e₂.symm, fun ⟨a, b⟩ => by simp, fun ⟨a, b⟩ => by simp⟩ @[simp] theorem prodCongr_symm (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (prodCongr e₁ e₂).symm = prodCongr e₁.symm e₂.symm := rfl /-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. This is `Prod.swap` as an equivalence. -/ def prodComm (α β) : α × β ≃ β × α := ⟨Prod.swap, Prod.swap, Prod.swap_swap, Prod.swap_swap⟩ @[simp] theorem coe_prodComm (α β) : (⇑(prodComm α β) : α × β → β × α) = Prod.swap := rfl @[simp] theorem prodComm_apply (x : α × β) : prodComm α β x = x.swap := rfl @[simp] theorem prodComm_symm (α β) : (prodComm α β).symm = prodComm β α := rfl /-- Type product is associative up to an equivalence. -/ @[simps] def prodAssoc (α β γ) : (α × β) × γ ≃ α × β × γ := ⟨fun p => (p.1.1, p.1.2, p.2), fun p => ((p.1, p.2.1), p.2.2), fun ⟨⟨_, _⟩, _⟩ => rfl, fun ⟨_, ⟨_, _⟩⟩ => rfl⟩ /-- Four-way commutativity of `prod`. The name matches `mul_mul_mul_comm`. -/ @[simps apply] def prodProdProdComm (α β γ δ : Type*) : (α × β) × γ × δ ≃ (α × γ) × β × δ where toFun abcd := ((abcd.1.1, abcd.2.1), (abcd.1.2, abcd.2.2)) invFun acbd := ((acbd.1.1, acbd.2.1), (acbd.1.2, acbd.2.2)) left_inv := fun ⟨⟨_a, _b⟩, ⟨_c, _d⟩⟩ => rfl right_inv := fun ⟨⟨_a, _c⟩, ⟨_b, _d⟩⟩ => rfl @[simp] theorem prodProdProdComm_symm (α β γ δ : Type*) : (prodProdProdComm α β γ δ).symm = prodProdProdComm α γ β δ := rfl /-- `γ`-valued functions on `α × β` are equivalent to functions `α → β → γ`. -/ @[simps (config := .asFn)] def curry (α β γ) : (α × β → γ) ≃ (α → β → γ) where toFun := Function.curry invFun := uncurry left_inv := uncurry_curry right_inv := curry_uncurry section /-- `PUnit` is a right identity for type product up to an equivalence. -/ @[simps] def prodPUnit (α) : α × PUnit ≃ α := ⟨fun p => p.1, fun a => (a, PUnit.unit), fun ⟨_, PUnit.unit⟩ => rfl, fun _ => rfl⟩ /-- `PUnit` is a left identity for type product up to an equivalence. -/ @[simps!] def punitProd (α) : PUnit × α ≃ α := calc PUnit × α ≃ α × PUnit := prodComm _ _ _ ≃ α := prodPUnit _ /-- `PUnit` is a right identity for dependent type product up to an equivalence. -/ @[simps] def sigmaPUnit (α) : (_ : α) × PUnit ≃ α := ⟨fun p => p.1, fun a => ⟨a, PUnit.unit⟩, fun ⟨_, PUnit.unit⟩ => rfl, fun _ => rfl⟩ /-- Any `Unique` type is a right identity for type product up to equivalence. -/ def prodUnique (α β) [Unique β] : α × β ≃ α := ((Equiv.refl α).prodCongr <| equivPUnit.{_,1} β).trans <| prodPUnit α @[simp] theorem coe_prodUnique [Unique β] : (⇑(prodUnique α β) : α × β → α) = Prod.fst := rfl theorem prodUnique_apply [Unique β] (x : α × β) : prodUnique α β x = x.1 := rfl @[simp] theorem prodUnique_symm_apply [Unique β] (x : α) : (prodUnique α β).symm x = (x, default) := rfl /-- Any `Unique` type is a left identity for type product up to equivalence. -/ def uniqueProd (α β) [Unique β] : β × α ≃ α := ((equivPUnit.{_,1} β).prodCongr <| Equiv.refl α).trans <| punitProd α @[simp] theorem coe_uniqueProd [Unique β] : (⇑(uniqueProd α β) : β × α → α) = Prod.snd := rfl theorem uniqueProd_apply [Unique β] (x : β × α) : uniqueProd α β x = x.2 := rfl @[simp] theorem uniqueProd_symm_apply [Unique β] (x : α) : (uniqueProd α β).symm x = (default, x) := rfl /-- Any family of `Unique` types is a right identity for dependent type product up to equivalence. -/ def sigmaUnique (α) (β : α → Type*) [∀ a, Unique (β a)] : (a : α) × (β a) ≃ α := (Equiv.sigmaCongrRight fun a ↦ equivPUnit.{_,1} (β a)).trans <| sigmaPUnit α @[simp] theorem coe_sigmaUnique {β : α → Type*} [∀ a, Unique (β a)] : (⇑(sigmaUnique α β) : (a : α) × (β a) → α) = Sigma.fst := rfl theorem sigmaUnique_apply {β : α → Type*} [∀ a, Unique (β a)] (x : (a : α) × β a) : sigmaUnique α β x = x.1 := rfl @[simp] theorem sigmaUnique_symm_apply {β : α → Type*} [∀ a, Unique (β a)] (x : α) : (sigmaUnique α β).symm x = ⟨x, default⟩ := rfl /-- `Empty` type is a right absorbing element for type product up to an equivalence. -/ def prodEmpty (α) : α × Empty ≃ Empty := equivEmpty _ /-- `Empty` type is a left absorbing element for type product up to an equivalence. -/ def emptyProd (α) : Empty × α ≃ Empty := equivEmpty _ /-- `PEmpty` type is a right absorbing element for type product up to an equivalence. -/ def prodPEmpty (α) : α × PEmpty ≃ PEmpty := equivPEmpty _ /-- `PEmpty` type is a left absorbing element for type product up to an equivalence. -/ def pemptyProd (α) : PEmpty × α ≃ PEmpty := equivPEmpty _ end section open Sum /-- `PSum` is equivalent to `Sum`. -/ def psumEquivSum (α β) : α ⊕' β ≃ α ⊕ β where toFun s := PSum.casesOn s inl inr invFun := Sum.elim PSum.inl PSum.inr left_inv s := by cases s <;> rfl right_inv s := by cases s <;> rfl /-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. This is `Sum.map` as an equivalence. -/ @[simps apply] def sumCongr (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ := ⟨Sum.map ea eb, Sum.map ea.symm eb.symm, fun x => by simp, fun x => by simp⟩ /-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕' β ≃ α' ⊕' β'`. -/ def psumCongr (e₁ : α ≃ β) (e₂ : γ ≃ δ) : α ⊕' γ ≃ β ⊕' δ where toFun x := PSum.casesOn x (PSum.inl ∘ e₁) (PSum.inr ∘ e₂) invFun x := PSum.casesOn x (PSum.inl ∘ e₁.symm) (PSum.inr ∘ e₂.symm) left_inv := by rintro (x | x) <;> simp right_inv := by rintro (x | x) <;> simp /-- Combine two `Equiv`s using `PSum` in the domain and `Sum` in the codomain. -/ def psumSum (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕' β₁ ≃ α₂ ⊕ β₂ := (ea.psumCongr eb).trans (psumEquivSum _ _) /-- Combine two `Equiv`s using `Sum` in the domain and `PSum` in the codomain. -/ def sumPSum (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕' β₂ := (ea.symm.psumSum eb.symm).symm @[simp] theorem sumCongr_trans (e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) : (Equiv.sumCongr e f).trans (Equiv.sumCongr g h) = Equiv.sumCongr (e.trans g) (f.trans h) := by ext i cases i <;> rfl @[simp] theorem sumCongr_symm (e : α ≃ β) (f : γ ≃ δ) : (Equiv.sumCongr e f).symm = Equiv.sumCongr e.symm f.symm := rfl @[simp] theorem sumCongr_refl : Equiv.sumCongr (Equiv.refl α) (Equiv.refl β) = Equiv.refl (α ⊕ β) := by ext i cases i <;> rfl /-- A subtype of a sum is equivalent to a sum of subtypes. -/ def subtypeSum {p : α ⊕ β → Prop} : {c // p c} ≃ {a // p (Sum.inl a)} ⊕ {b // p (Sum.inr b)} where toFun c := match h : c.1 with | Sum.inl a => Sum.inl ⟨a, h ▸ c.2⟩ | Sum.inr b => Sum.inr ⟨b, h ▸ c.2⟩ invFun c := match c with | Sum.inl a => ⟨Sum.inl a, a.2⟩ | Sum.inr b => ⟨Sum.inr b, b.2⟩ left_inv := by rintro ⟨a | b, h⟩ <;> rfl right_inv := by rintro (a | b) <;> rfl namespace Perm /-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/ abbrev sumCongr (ea : Equiv.Perm α) (eb : Equiv.Perm β) : Equiv.Perm (α ⊕ β) := Equiv.sumCongr ea eb @[simp] theorem sumCongr_apply (ea : Equiv.Perm α) (eb : Equiv.Perm β) (x : α ⊕ β) : sumCongr ea eb x = Sum.map (⇑ea) (⇑eb) x := Equiv.sumCongr_apply ea eb x -- Porting note: it seems the general theorem about `Equiv` is now applied, so there's no need -- to have this version also have `@[simp]`. Similarly for below. theorem sumCongr_trans (e : Equiv.Perm α) (f : Equiv.Perm β) (g : Equiv.Perm α) (h : Equiv.Perm β) : (sumCongr e f).trans (sumCongr g h) = sumCongr (e.trans g) (f.trans h) := Equiv.sumCongr_trans e f g h theorem sumCongr_symm (e : Equiv.Perm α) (f : Equiv.Perm β) : (sumCongr e f).symm = sumCongr e.symm f.symm := Equiv.sumCongr_symm e f theorem sumCongr_refl : sumCongr (Equiv.refl α) (Equiv.refl β) = Equiv.refl (α ⊕ β) := Equiv.sumCongr_refl end Perm /-- `Bool` is equivalent the sum of two `PUnit`s. -/ def boolEquivPUnitSumPUnit : Bool ≃ PUnit.{u + 1} ⊕ PUnit.{v + 1} := ⟨fun b => b.casesOn (inl PUnit.unit) (inr PUnit.unit) , Sum.elim (fun _ => false) fun _ => true, fun b => by cases b <;> rfl, fun s => by rcases s with (⟨⟨⟩⟩ | ⟨⟨⟩⟩) <;> rfl⟩ /-- Sum of types is commutative up to an equivalence. This is `Sum.swap` as an equivalence. -/ @[simps (config := .asFn) apply] def sumComm (α β) : α ⊕ β ≃ β ⊕ α := ⟨Sum.swap, Sum.swap, Sum.swap_swap, Sum.swap_swap⟩ @[simp] theorem sumComm_symm (α β) : (sumComm α β).symm = sumComm β α := rfl /-- Sum of types is associative up to an equivalence. -/ def sumAssoc (α β γ) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨Sum.elim (Sum.elim Sum.inl (Sum.inr ∘ Sum.inl)) (Sum.inr ∘ Sum.inr), Sum.elim (Sum.inl ∘ Sum.inl) <| Sum.elim (Sum.inl ∘ Sum.inr) Sum.inr, by rintro (⟨_ | _⟩ | _) <;> rfl, by rintro (_ | ⟨_ | _⟩) <;> rfl⟩ @[simp] theorem sumAssoc_apply_inl_inl (a) : sumAssoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sumAssoc_apply_inl_inr (b) : sumAssoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sumAssoc_apply_inr (c) : sumAssoc α β γ (inr c) = inr (inr c) := rfl @[simp] theorem sumAssoc_symm_apply_inl {α β γ} (a) : (sumAssoc α β γ).symm (inl a) = inl (inl a) := rfl @[simp] theorem sumAssoc_symm_apply_inr_inl {α β γ} (b) : (sumAssoc α β γ).symm (inr (inl b)) = inl (inr b) := rfl @[simp] theorem sumAssoc_symm_apply_inr_inr {α β γ} (c) : (sumAssoc α β γ).symm (inr (inr c)) = inr c := rfl /-- Sum with `IsEmpty` is equivalent to the original type. -/ @[simps symm_apply] def sumEmpty (α β) [IsEmpty β] : α ⊕ β ≃ α where toFun := Sum.elim id isEmptyElim invFun := inl left_inv s := by rcases s with (_ | x) · rfl · exact isEmptyElim x right_inv _ := rfl @[simp] theorem sumEmpty_apply_inl [IsEmpty β] (a : α) : sumEmpty α β (Sum.inl a) = a := rfl /-- The sum of `IsEmpty` with any type is equivalent to that type. -/ @[simps! symm_apply] def emptySum (α β) [IsEmpty α] : α ⊕ β ≃ β := (sumComm _ _).trans <| sumEmpty _ _ @[simp] theorem emptySum_apply_inr [IsEmpty α] (b : β) : emptySum α β (Sum.inr b) = b := rfl /-- `Option α` is equivalent to `α ⊕ PUnit` -/ def optionEquivSumPUnit (α) : Option α ≃ α ⊕ PUnit := ⟨fun o => o.elim (inr PUnit.unit) inl, fun s => s.elim some fun _ => none, fun o => by cases o <;> rfl, fun s => by rcases s with (_ | ⟨⟨⟩⟩) <;> rfl⟩ @[simp] theorem optionEquivSumPUnit_none : optionEquivSumPUnit α none = Sum.inr PUnit.unit := rfl @[simp] theorem optionEquivSumPUnit_some (a) : optionEquivSumPUnit α (some a) = Sum.inl a := rfl @[simp] theorem optionEquivSumPUnit_coe (a : α) : optionEquivSumPUnit α a = Sum.inl a := rfl @[simp] theorem optionEquivSumPUnit_symm_inl (a) : (optionEquivSumPUnit α).symm (Sum.inl a) = a := rfl @[simp] theorem optionEquivSumPUnit_symm_inr (a) : (optionEquivSumPUnit α).symm (Sum.inr a) = none := rfl /-- The set of `x : Option α` such that `isSome x` is equivalent to `α`. -/ @[simps] def optionIsSomeEquiv (α) : { x : Option α // x.isSome } ≃ α where toFun o := Option.get _ o.2 invFun x := ⟨some x, rfl⟩ left_inv _ := Subtype.eq <| Option.some_get _ right_inv _ := Option.get_some _ _ /-- The product over `Option α` of `β a` is the binary product of the product over `α` of `β (some α)` and `β none` -/ @[simps] def piOptionEquivProd {β : Option α → Type*} : (∀ a : Option α, β a) ≃ β none × ∀ a : α, β (some a) where toFun f := (f none, fun a => f (some a)) invFun x a := Option.casesOn a x.fst x.snd left_inv f := funext fun a => by cases a <;> rfl right_inv x := by simp /-- `α ⊕ β` is equivalent to a `Sigma`-type over `Bool`. Note that this definition assumes `α` and `β` to be types from the same universe, so it cannot be used directly to transfer theorems about sigma types to theorems about sum types. In many cases one can use `ULift` to work around this difficulty. -/ def sumEquivSigmaBool (α β : Type u) : α ⊕ β ≃ Σ b : Bool, b.casesOn α β := ⟨fun s => s.elim (fun x => ⟨false, x⟩) fun x => ⟨true, x⟩, fun s => match s with | ⟨false, a⟩ => inl a | ⟨true, b⟩ => inr b, fun s => by cases s <;> rfl, fun s => by rcases s with ⟨_ | _, _⟩ <;> rfl⟩ -- See also `Equiv.sigmaPreimageEquiv`. /-- `sigmaFiberEquiv f` for `f : α → β` is the natural equivalence between the type of all fibres of `f` and the total space `α`. -/ @[simps] def sigmaFiberEquiv {α β : Type*} (f : α → β) : (Σ y : β, { x // f x = y }) ≃ α := ⟨fun x => ↑x.2, fun x => ⟨f x, x, rfl⟩, fun ⟨_, _, rfl⟩ => rfl, fun _ => rfl⟩ /-- Inhabited types are equivalent to `Option β` for some `β` by identifying `default` with `none`. -/ def sigmaEquivOptionOfInhabited (α : Type u) [Inhabited α] [DecidableEq α] : Σ β : Type u, α ≃ Option β where fst := {a // a ≠ default} snd.toFun a := if h : a = default then none else some ⟨a, h⟩ snd.invFun := Option.elim' default (↑) snd.left_inv a := by dsimp only; split_ifs <;> simp [*] snd.right_inv | none => by simp | some ⟨a, ha⟩ => dif_neg ha end section sumCompl /-- For any predicate `p` on `α`, the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}` is naturally equivalent to `α`. See `subtypeOrEquiv` for sum types over subtypes `{x // p x}` and `{x // q x}` that are not necessarily `IsCompl p q`. -/ def sumCompl {α : Type*} (p : α → Prop) [DecidablePred p] : { a // p a } ⊕ { a // ¬p a } ≃ α where toFun := Sum.elim Subtype.val Subtype.val invFun a := if h : p a then Sum.inl ⟨a, h⟩ else Sum.inr ⟨a, h⟩ left_inv := by rintro (⟨x, hx⟩ | ⟨x, hx⟩) <;> dsimp · rw [dif_pos] · rw [dif_neg] right_inv a := by dsimp split_ifs <;> rfl @[simp] theorem sumCompl_apply_inl (p : α → Prop) [DecidablePred p] (x : { a // p a }) : sumCompl p (Sum.inl x) = x := rfl @[simp] theorem sumCompl_apply_inr (p : α → Prop) [DecidablePred p] (x : { a // ¬p a }) : sumCompl p (Sum.inr x) = x := rfl @[simp] theorem sumCompl_apply_symm_of_pos (p : α → Prop) [DecidablePred p] (a : α) (h : p a) : (sumCompl p).symm a = Sum.inl ⟨a, h⟩ := dif_pos h @[simp] theorem sumCompl_apply_symm_of_neg (p : α → Prop) [DecidablePred p] (a : α) (h : ¬p a) : (sumCompl p).symm a = Sum.inr ⟨a, h⟩ := dif_neg h /-- Combines an `Equiv` between two subtypes with an `Equiv` between their complements to form a permutation. -/ def subtypeCongr {p q : α → Prop} [DecidablePred p] [DecidablePred q] (e : { x // p x } ≃ { x // q x }) (f : { x // ¬p x } ≃ { x // ¬q x }) : Perm α := (sumCompl p).symm.trans ((sumCongr e f).trans (sumCompl q)) variable {p : ε → Prop} [DecidablePred p] variable (ep ep' : Perm { a // p a }) (en en' : Perm { a // ¬p a }) /-- Combining permutations on `ε` that permute only inside or outside the subtype split induced by `p : ε → Prop` constructs a permutation on `ε`. -/ def Perm.subtypeCongr : Equiv.Perm ε := permCongr (sumCompl p) (sumCongr ep en) theorem Perm.subtypeCongr.apply (a : ε) : ep.subtypeCongr en a = if h : p a then (ep ⟨a, h⟩ : ε) else en ⟨a, h⟩ := by by_cases h : p a <;> simp [Perm.subtypeCongr, h] @[simp] theorem Perm.subtypeCongr.left_apply {a : ε} (h : p a) : ep.subtypeCongr en a = ep ⟨a, h⟩ := by simp [Perm.subtypeCongr.apply, h] @[simp] theorem Perm.subtypeCongr.left_apply_subtype (a : { a // p a }) : ep.subtypeCongr en a = ep a := Perm.subtypeCongr.left_apply ep en a.property @[simp] theorem Perm.subtypeCongr.right_apply {a : ε} (h : ¬p a) : ep.subtypeCongr en a = en ⟨a, h⟩ := by simp [Perm.subtypeCongr.apply, h] @[simp] theorem Perm.subtypeCongr.right_apply_subtype (a : { a // ¬p a }) : ep.subtypeCongr en a = en a := Perm.subtypeCongr.right_apply ep en a.property @[simp] theorem Perm.subtypeCongr.refl : Perm.subtypeCongr (Equiv.refl { a // p a }) (Equiv.refl { a // ¬p a }) = Equiv.refl ε := by ext x by_cases h : p x <;> simp [h] @[simp] theorem Perm.subtypeCongr.symm : (ep.subtypeCongr en).symm = Perm.subtypeCongr ep.symm en.symm := by ext x by_cases h : p x · have : p (ep.symm ⟨x, h⟩) := Subtype.property _ simp [Perm.subtypeCongr.apply, h, symm_apply_eq, this] · have : ¬p (en.symm ⟨x, h⟩) := Subtype.property (en.symm _) simp [Perm.subtypeCongr.apply, h, symm_apply_eq, this] @[simp] theorem Perm.subtypeCongr.trans : (ep.subtypeCongr en).trans (ep'.subtypeCongr en') = Perm.subtypeCongr (ep.trans ep') (en.trans en') := by ext x by_cases h : p x · have : p (ep ⟨x, h⟩) := Subtype.property _ simp [Perm.subtypeCongr.apply, h, this] · have : ¬p (en ⟨x, h⟩) := Subtype.property (en _) simp [Perm.subtypeCongr.apply, h, symm_apply_eq, this] end sumCompl section subtypePreimage variable (p : α → Prop) [DecidablePred p] (x₀ : { a // p a } → β) /-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`, the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}` is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/ @[simps] def subtypePreimage : { x : α → β // x ∘ Subtype.val = x₀ } ≃ ({ a // ¬p a } → β) where toFun (x : { x : α → β // x ∘ Subtype.val = x₀ }) a := (x : α → β) a invFun x := ⟨fun a => if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩, funext fun ⟨a, h⟩ => dif_pos h⟩ left_inv := fun ⟨x, hx⟩ => Subtype.val_injective <| funext fun a => by dsimp only split_ifs · rw [← hx]; rfl · rfl right_inv x := funext fun ⟨a, h⟩ => show dite (p a) _ _ = _ by dsimp only rw [dif_neg h] theorem subtypePreimage_symm_apply_coe_pos (x : { a // ¬p a } → β) (a : α) (h : p a) : ((subtypePreimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ := dif_pos h theorem subtypePreimage_symm_apply_coe_neg (x : { a // ¬p a } → β) (a : α) (h : ¬p a) : ((subtypePreimage p x₀).symm x : α → β) a = x ⟨a, h⟩ := dif_neg h end subtypePreimage section /-- A family of equivalences `∀ a, β₁ a ≃ β₂ a` generates an equivalence between `∀ a, β₁ a` and `∀ a, β₂ a`. -/ def piCongrRight {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (∀ a, β₁ a) ≃ (∀ a, β₂ a) := ⟨fun H a => F a (H a), fun H a => (F a).symm (H a), fun H => funext <| by simp, fun H => funext <| by simp⟩ /-- Given `φ : α → β → Sort*`, we have an equivalence between `∀ a b, φ a b` and `∀ b a, φ a b`. This is `Function.swap` as an `Equiv`. -/ @[simps apply] def piComm (φ : α → β → Sort*) : (∀ a b, φ a b) ≃ ∀ b a, φ a b := ⟨swap, swap, fun _ => rfl, fun _ => rfl⟩ @[simp] theorem piComm_symm {φ : α → β → Sort*} : (piComm φ).symm = (piComm <| swap φ) := rfl /-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent to the type of dependent functions of two arguments (i.e., functions to the space of functions). This is `Sigma.curry` and `Sigma.uncurry` together as an equiv. -/ def piCurry {β : α → Type*} (γ : ∀ a, β a → Type*) : (∀ x : Σ i, β i, γ x.1 x.2) ≃ ∀ a b, γ a b where toFun := Sigma.curry invFun := Sigma.uncurry left_inv := Sigma.uncurry_curry right_inv := Sigma.curry_uncurry -- `simps` overapplies these but `simps (config := .asFn)` under-applies them @[simp] theorem piCurry_apply {β : α → Type*} (γ : ∀ a, β a → Type*) (f : ∀ x : Σ i, β i, γ x.1 x.2) : piCurry γ f = Sigma.curry f := rfl @[simp] theorem piCurry_symm_apply {β : α → Type*} (γ : ∀ a, β a → Type*) (f : ∀ a b, γ a b) : (piCurry γ).symm f = Sigma.uncurry f := rfl end section prodCongr variable (e : α₁ → β₁ ≃ β₂) /-- A family of equivalences `∀ (a : α₁), β₁ ≃ β₂` generates an equivalence between `β₁ × α₁` and `β₂ × α₁`. -/ def prodCongrLeft : β₁ × α₁ ≃ β₂ × α₁ where toFun ab := ⟨e ab.2 ab.1, ab.2⟩ invFun ab := ⟨(e ab.2).symm ab.1, ab.2⟩ left_inv := by rintro ⟨a, b⟩ simp right_inv := by rintro ⟨a, b⟩ simp @[simp] theorem prodCongrLeft_apply (b : β₁) (a : α₁) : prodCongrLeft e (b, a) = (e a b, a) := rfl theorem prodCongr_refl_right (e : β₁ ≃ β₂) : prodCongr e (Equiv.refl α₁) = prodCongrLeft fun _ => e := by ext ⟨a, b⟩ : 1 simp /-- A family of equivalences `∀ (a : α₁), β₁ ≃ β₂` generates an equivalence between `α₁ × β₁` and `α₁ × β₂`. -/ def prodCongrRight : α₁ × β₁ ≃ α₁ × β₂ where toFun ab := ⟨ab.1, e ab.1 ab.2⟩ invFun ab := ⟨ab.1, (e ab.1).symm ab.2⟩ left_inv := by rintro ⟨a, b⟩ simp right_inv := by rintro ⟨a, b⟩ simp @[simp] theorem prodCongrRight_apply (a : α₁) (b : β₁) : prodCongrRight e (a, b) = (a, e a b) := rfl theorem prodCongr_refl_left (e : β₁ ≃ β₂) : prodCongr (Equiv.refl α₁) e = prodCongrRight fun _ => e := by ext ⟨a, b⟩ : 1 simp @[simp] theorem prodCongrLeft_trans_prodComm : (prodCongrLeft e).trans (prodComm _ _) = (prodComm _ _).trans (prodCongrRight e) := by ext ⟨a, b⟩ : 1 simp @[simp] theorem prodCongrRight_trans_prodComm : (prodCongrRight e).trans (prodComm _ _) = (prodComm _ _).trans (prodCongrLeft e) := by ext ⟨a, b⟩ : 1 simp theorem sigmaCongrRight_sigmaEquivProd : (sigmaCongrRight e).trans (sigmaEquivProd α₁ β₂) = (sigmaEquivProd α₁ β₁).trans (prodCongrRight e) := by ext ⟨a, b⟩ : 1 simp theorem sigmaEquivProd_sigmaCongrRight : (sigmaEquivProd α₁ β₁).symm.trans (sigmaCongrRight e) = (prodCongrRight e).trans (sigmaEquivProd α₁ β₂).symm := by ext ⟨a, b⟩ : 1 simp only [trans_apply, sigmaCongrRight_apply, prodCongrRight_apply] rfl -- See also `Equiv.ofPreimageEquiv`. /-- A family of equivalences between fibers gives an equivalence between domains. -/ @[simps!] def ofFiberEquiv {f : α → γ} {g : β → γ} (e : ∀ c, { a // f a = c } ≃ { b // g b = c }) : α ≃ β := (sigmaFiberEquiv f).symm.trans <| (Equiv.sigmaCongrRight e).trans (sigmaFiberEquiv g) theorem ofFiberEquiv_map {α β γ} {f : α → γ} {g : β → γ} (e : ∀ c, { a // f a = c } ≃ { b // g b = c }) (a : α) : g (ofFiberEquiv e a) = f a := (_ : { b // g b = _ }).property /-- A variation on `Equiv.prodCongr` where the equivalence in the second component can depend on the first component. A typical example is a shear mapping, explaining the name of this declaration. -/ @[simps (config := .asFn)] def prodShear (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ where toFun := fun x : α₁ × β₁ => (e₁ x.1, e₂ x.1 x.2) invFun := fun y : α₂ × β₂ => (e₁.symm y.1, (e₂ <| e₁.symm y.1).symm y.2) left_inv := by rintro ⟨x₁, y₁⟩ simp only [symm_apply_apply] right_inv := by rintro ⟨x₁, y₁⟩ simp only [apply_symm_apply] end prodCongr namespace Perm variable [DecidableEq α₁] (a : α₁) (e : Perm β₁) /-- `prodExtendRight a e` extends `e : Perm β` to `Perm (α × β)` by sending `(a, b)` to `(a, e b)` and keeping the other `(a', b)` fixed. -/ def prodExtendRight : Perm (α₁ × β₁) where toFun ab := if ab.fst = a then (a, e ab.snd) else ab invFun ab := if ab.fst = a then (a, e.symm ab.snd) else ab left_inv := by rintro ⟨k', x⟩ dsimp only split_ifs with h₁ h₂ · simp [h₁] · simp at h₂ · simp right_inv := by rintro ⟨k', x⟩ dsimp only split_ifs with h₁ h₂ · simp [h₁] · simp at h₂ · simp @[simp] theorem prodExtendRight_apply_eq (b : β₁) : prodExtendRight a e (a, b) = (a, e b) := if_pos rfl theorem prodExtendRight_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) : prodExtendRight a e (a', b) = (a', b) := if_neg h theorem eq_of_prodExtendRight_ne {e : Perm β₁} {a a' : α₁} {b : β₁} (h : prodExtendRight a e (a', b) ≠ (a', b)) : a' = a := by contrapose! h exact prodExtendRight_apply_ne _ h _ @[simp] theorem fst_prodExtendRight (ab : α₁ × β₁) : (prodExtendRight a e ab).fst = ab.fst := by rw [prodExtendRight] dsimp split_ifs with h · rw [h] · rfl end Perm section /-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions `γ → α` and `γ → β`. -/ def arrowProdEquivProdArrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) where toFun := fun f => (fun c => (f c).1, fun c => (f c).2) invFun := fun p c => (p.1 c, p.2 c) left_inv := fun f => rfl right_inv := fun p => by cases p; rfl open Sum /-- The type of dependent functions on a sum type `ι ⊕ ι'` is equivalent to the type of pairs of functions on `ι` and on `ι'`. This is a dependent version of `Equiv.sumArrowEquivProdArrow`. -/ @[simps] def sumPiEquivProdPi (π : ι ⊕ ι' → Type*) : (∀ i, π i) ≃ (∀ i, π (inl i)) × ∀ i', π (inr i') where toFun f := ⟨fun i => f (inl i), fun i' => f (inr i')⟩ invFun g := Sum.rec g.1 g.2 left_inv f := by ext (i | i) <;> rfl right_inv g := Prod.ext rfl rfl /-- The equivalence between a product of two dependent functions types and a single dependent function type. Basically a symmetric version of `Equiv.sumPiEquivProdPi`. -/ @[simps!] def prodPiEquivSumPi (π : ι → Type u) (π' : ι' → Type u) : ((∀ i, π i) × ∀ i', π' i') ≃ ∀ i, Sum.elim π π' i := sumPiEquivProdPi (Sum.elim π π') |>.symm /-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions on `α` and on `β`. -/ def sumArrowEquivProdArrow (α β γ : Type*) : (α ⊕ β → γ) ≃ (α → γ) × (β → γ) := ⟨fun f => (f ∘ inl, f ∘ inr), fun p => Sum.elim p.1 p.2, fun f => by ext ⟨⟩ <;> rfl, fun p => by cases p rfl⟩ @[simp] theorem sumArrowEquivProdArrow_apply_fst (f : α ⊕ β → γ) (a : α) : (sumArrowEquivProdArrow α β γ f).1 a = f (inl a) := rfl @[simp] theorem sumArrowEquivProdArrow_apply_snd (f : α ⊕ β → γ) (b : β) : (sumArrowEquivProdArrow α β γ f).2 b = f (inr b) := rfl @[simp] theorem sumArrowEquivProdArrow_symm_apply_inl (f : α → γ) (g : β → γ) (a : α) : ((sumArrowEquivProdArrow α β γ).symm (f, g)) (inl a) = f a := rfl @[simp] theorem sumArrowEquivProdArrow_symm_apply_inr (f : α → γ) (g : β → γ) (b : β) : ((sumArrowEquivProdArrow α β γ).symm (f, g)) (inr b) = g b := rfl /-- Type product is right distributive with respect to type sum up to an equivalence. -/ def sumProdDistrib (α β γ) : (α ⊕ β) × γ ≃ α × γ ⊕ β × γ := ⟨fun p => p.1.map (fun x => (x, p.2)) fun x => (x, p.2), fun s => s.elim (Prod.map inl id) (Prod.map inr id), by rintro ⟨_ | _, _⟩ <;> rfl, by rintro (⟨_, _⟩ | ⟨_, _⟩) <;> rfl⟩ @[simp] theorem sumProdDistrib_apply_left (a : α) (c : γ) : sumProdDistrib α β γ (Sum.inl a, c) = Sum.inl (a, c) := rfl @[simp] theorem sumProdDistrib_apply_right (b : β) (c : γ) : sumProdDistrib α β γ (Sum.inr b, c) = Sum.inr (b, c) := rfl @[simp] theorem sumProdDistrib_symm_apply_left (a : α × γ) : (sumProdDistrib α β γ).symm (inl a) = (inl a.1, a.2) := rfl @[simp] theorem sumProdDistrib_symm_apply_right (b : β × γ) : (sumProdDistrib α β γ).symm (inr b) = (inr b.1, b.2) := rfl /-- Type product is left distributive with respect to type sum up to an equivalence. -/ def prodSumDistrib (α β γ : Type*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α := prodComm _ _ _ ≃ (β × α) ⊕ (γ × α) := sumProdDistrib _ _ _ _ ≃ (α × β) ⊕ (α × γ) := sumCongr (prodComm _ _) (prodComm _ _) @[simp] theorem prodSumDistrib_apply_left (a : α) (b : β) : prodSumDistrib α β γ (a, Sum.inl b) = Sum.inl (a, b) := rfl @[simp] theorem prodSumDistrib_apply_right (a : α) (c : γ) : prodSumDistrib α β γ (a, Sum.inr c) = Sum.inr (a, c) := rfl @[simp] theorem prodSumDistrib_symm_apply_left (a : α × β) : (prodSumDistrib α β γ).symm (inl a) = (a.1, inl a.2) := rfl @[simp] theorem prodSumDistrib_symm_apply_right (a : α × γ) : (prodSumDistrib α β γ).symm (inr a) = (a.1, inr a.2) := rfl /-- An indexed sum of disjoint sums of types is equivalent to the sum of the indexed sums. -/ @[simps] def sigmaSumDistrib (α β : ι → Type*) : (Σ i, α i ⊕ β i) ≃ (Σ i, α i) ⊕ (Σ i, β i) := ⟨fun p => p.2.map (Sigma.mk p.1) (Sigma.mk p.1), Sum.elim (Sigma.map id fun _ => Sum.inl) (Sigma.map id fun _ => Sum.inr), fun p => by rcases p with ⟨i, a | b⟩ <;> rfl, fun p => by rcases p with (⟨i, a⟩ | ⟨i, b⟩) <;> rfl⟩ /-- The product of an indexed sum of types (formally, a `Sigma`-type `Σ i, α i`) by a type `β` is equivalent to the sum of products `Σ i, (α i × β)`. -/ def sigmaProdDistrib (α : ι → Type*) (β : Type*) : (Σ i, α i) × β ≃ Σ i, α i × β := ⟨fun p => ⟨p.1.1, (p.1.2, p.2)⟩, fun p => (⟨p.1, p.2.1⟩, p.2.2), fun p => by rcases p with ⟨⟨_, _⟩, _⟩ rfl, fun p => by rcases p with ⟨_, ⟨_, _⟩⟩ rfl⟩ /-- An equivalence that separates out the 0th fiber of `(Σ (n : ℕ), f n)`. -/ def sigmaNatSucc (f : ℕ → Type u) : (Σ n, f n) ≃ f 0 ⊕ Σ n, f (n + 1) := ⟨fun x => @Sigma.casesOn ℕ f (fun _ => f 0 ⊕ Σ n, f (n + 1)) x fun n => @Nat.casesOn (fun i => f i → f 0 ⊕ Σ n : ℕ, f (n + 1)) n (fun x : f 0 => Sum.inl x) fun (n : ℕ) (x : f n.succ) => Sum.inr ⟨n, x⟩, Sum.elim (Sigma.mk 0) (Sigma.map Nat.succ fun _ => id), by rintro ⟨n | n, x⟩ <;> rfl, by rintro (x | ⟨n, x⟩) <;> rfl⟩ /-- The product `Bool × α` is equivalent to `α ⊕ α`. -/ @[simps] def boolProdEquivSum (α) : Bool × α ≃ α ⊕ α where toFun p := p.1.casesOn (inl p.2) (inr p.2) invFun := Sum.elim (Prod.mk false) (Prod.mk true) left_inv := by rintro ⟨_ | _, _⟩ <;> rfl right_inv := by rintro (_ | _) <;> rfl /-- The function type `Bool → α` is equivalent to `α × α`. -/ @[simps] def boolArrowEquivProd (α) : (Bool → α) ≃ α × α where toFun f := (f false, f true) invFun p b := b.casesOn p.1 p.2 left_inv _ := funext <| Bool.forall_bool.2 ⟨rfl, rfl⟩ right_inv := fun _ => rfl end section open Sum Nat /-- The set of natural numbers is equivalent to `ℕ ⊕ PUnit`. -/ def natEquivNatSumPUnit : ℕ ≃ ℕ ⊕ PUnit where toFun n := Nat.casesOn n (inr PUnit.unit) inl invFun := Sum.elim Nat.succ fun _ => 0 left_inv n := by cases n <;> rfl right_inv := by rintro (_ | _) <;> rfl /-- `ℕ ⊕ PUnit` is equivalent to `ℕ`. -/ def natSumPUnitEquivNat : ℕ ⊕ PUnit ≃ ℕ := natEquivNatSumPUnit.symm /-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/ def intEquivNatSumNat : ℤ ≃ ℕ ⊕ ℕ where toFun z := Int.casesOn z inl inr invFun := Sum.elim Int.ofNat Int.negSucc left_inv := by rintro (m | n) <;> rfl right_inv := by rintro (m | n) <;> rfl end /-- An equivalence between `α` and `β` generates an equivalence between `List α` and `List β`. -/ def listEquivOfEquiv (e : α ≃ β) : List α ≃ List β where toFun := List.map e invFun := List.map e.symm left_inv l := by rw [List.map_map, e.symm_comp_self, List.map_id] right_inv l := by rw [List.map_map, e.self_comp_symm, List.map_id] /-- If `α` is equivalent to `β`, then `Unique α` is equivalent to `Unique β`. -/ def uniqueCongr (e : α ≃ β) : Unique α ≃ Unique β where toFun h := @Equiv.unique _ _ h e.symm invFun h := @Equiv.unique _ _ h e left_inv _ := Subsingleton.elim _ _ right_inv _ := Subsingleton.elim _ _ /-- If `α` is equivalent to `β`, then `IsEmpty α` is equivalent to `IsEmpty β`. -/ theorem isEmpty_congr (e : α ≃ β) : IsEmpty α ↔ IsEmpty β := ⟨fun h => @Function.isEmpty _ _ h e.symm, fun h => @Function.isEmpty _ _ h e⟩ protected theorem isEmpty (e : α ≃ β) [IsEmpty β] : IsEmpty α := e.isEmpty_congr.mpr ‹_› section open Subtype /-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. For the statement where `α = β`, that is, `e : perm α`, see `Perm.subtypePerm`. -/ def subtypeEquiv {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : { a : α // p a } ≃ { b : β // q b } where toFun a := ⟨e a, (h _).mp a.property⟩ invFun b := ⟨e.symm b, (h _).mpr ((e.apply_symm_apply b).symm ▸ b.property)⟩ left_inv a := Subtype.ext <| by simp right_inv b := Subtype.ext <| by simp lemma coe_subtypeEquiv_eq_map {X Y : Type*} {p : X → Prop} {q : Y → Prop} (e : X ≃ Y) (h : ∀ x, p x ↔ q (e x)) : ⇑(e.subtypeEquiv h) = Subtype.map e (h · |>.mp) := rfl @[simp] theorem subtypeEquiv_refl {p : α → Prop} (h : ∀ a, p a ↔ p (Equiv.refl _ a) := fun a => Iff.rfl) : (Equiv.refl α).subtypeEquiv h = Equiv.refl { a : α // p a } := by ext rfl @[simp] theorem subtypeEquiv_symm {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a : α, p a ↔ q (e a)) : (e.subtypeEquiv h).symm = e.symm.subtypeEquiv fun a => by convert (h <| e.symm a).symm exact (e.apply_symm_apply a).symm := rfl @[simp] theorem subtypeEquiv_trans {p : α → Prop} {q : β → Prop} {r : γ → Prop} (e : α ≃ β) (f : β ≃ γ) (h : ∀ a : α, p a ↔ q (e a)) (h' : ∀ b : β, q b ↔ r (f b)) : (e.subtypeEquiv h).trans (f.subtypeEquiv h') = (e.trans f).subtypeEquiv fun a => (h a).trans (h' <| e a) := rfl @[simp] theorem subtypeEquiv_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a : α, p a ↔ q (e a)) (x : { x // p x }) : e.subtypeEquiv h x = ⟨e x, (h _).1 x.2⟩ := rfl /-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to `{x // q x}`. -/ @[simps!] def subtypeEquivRight {p q : α → Prop} (e : ∀ x, p x ↔ q x) : { x // p x } ≃ { x // q x } := subtypeEquiv (Equiv.refl _) e lemma subtypeEquivRight_apply {p q : α → Prop} (e : ∀ x, p x ↔ q x) (z : { x // p x }) : subtypeEquivRight e z = ⟨z, (e z.1).mp z.2⟩ := rfl lemma subtypeEquivRight_symm_apply {p q : α → Prop} (e : ∀ x, p x ↔ q x) (z : { x // q x }) : (subtypeEquivRight e).symm z = ⟨z, (e z.1).mpr z.2⟩ := rfl /-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent to the subtype `{b // p b}`. -/ def subtypeEquivOfSubtype {p : β → Prop} (e : α ≃ β) : { a : α // p (e a) } ≃ { b : β // p b } := subtypeEquiv e <| by simp /-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/ def subtypeEquivOfSubtype' {p : α → Prop} (e : α ≃ β) : { a : α // p a } ≃ { b : β // p (e.symm b) } := e.symm.subtypeEquivOfSubtype.symm /-- If two predicates are equal, then the corresponding subtypes are equivalent. -/ def subtypeEquivProp {p q : α → Prop} (h : p = q) : Subtype p ≃ Subtype q := subtypeEquiv (Equiv.refl α) fun _ => h ▸ Iff.rfl /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This version allows the “inner” predicate to depend on `h : p a`. -/ @[simps] def subtypeSubtypeEquivSubtypeExists (p : α → Prop) (q : Subtype p → Prop) : Subtype q ≃ { a : α // ∃ h : p a, q ⟨a, h⟩ } := ⟨fun a => ⟨a.1, a.1.2, by rcases a with ⟨⟨a, hap⟩, haq⟩ exact haq⟩, fun a => ⟨⟨a, a.2.fst⟩, a.2.snd⟩, fun ⟨⟨a, ha⟩, h⟩ => rfl, fun ⟨a, h₁, h₂⟩ => rfl⟩ /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/ @[simps!] def subtypeSubtypeEquivSubtypeInter {α : Type u} (p q : α → Prop) : { x : Subtype p // q x.1 } ≃ Subtype fun x => p x ∧ q x := (subtypeSubtypeEquivSubtypeExists p _).trans <| subtypeEquivRight fun x => @exists_prop (q x) (p x) /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ @[simps!] def subtypeSubtypeEquivSubtype {p q : α → Prop} (h : ∀ {x}, q x → p x) : { x : Subtype p // q x.1 } ≃ Subtype q := (subtypeSubtypeEquivSubtypeInter p _).trans <| subtypeEquivRight fun _ => and_iff_right_of_imp h /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ @[simps apply symm_apply] def subtypeUnivEquiv {p : α → Prop} (h : ∀ x, p x) : Subtype p ≃ α := ⟨fun x => x, fun x => ⟨x, h x⟩, fun _ => Subtype.eq rfl, fun _ => rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtypeSigmaEquiv (p : α → Type v) (q : α → Prop) : { y : Sigma p // q y.1 } ≃ Σ x : Subtype q, p x.1 := ⟨fun x => ⟨⟨x.1.1, x.2⟩, x.1.2⟩, fun x => ⟨⟨x.1.1, x.2⟩, x.1.2⟩, fun _ => rfl, fun _ => rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigmaSubtypeEquivOfSubset (p : α → Type v) (q : α → Prop) (h : ∀ x, p x → q x) : (Σ x : Subtype q, p x) ≃ Σ x : α, p x := (subtypeSigmaEquiv p q).symm.trans <| subtypeUnivEquiv fun x => h x.1 x.2 /-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then `Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/ def sigmaSubtypeFiberEquiv {α β : Type*} (f : α → β) (p : β → Prop) (h : ∀ x, p (f x)) : (Σ y : Subtype p, { x : α // f x = y }) ≃ α := calc _ ≃ Σy : β, { x : α // f x = y } := sigmaSubtypeEquivOfSubset _ p fun _ ⟨x, h'⟩ => h' ▸ h x _ ≃ α := sigmaFiberEquiv f /-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent to `{x // p x}`. -/ def sigmaSubtypeFiberEquivSubtype {α β : Type*} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) : (Σ y : Subtype q, { x : α // f x = y }) ≃ Subtype p := calc (Σy : Subtype q, { x : α // f x = y }) ≃ Σy : Subtype q, { x : Subtype p // Subtype.mk (f x) ((h x).1 x.2) = y } := by { apply sigmaCongrRight intro y apply Equiv.symm refine (subtypeSubtypeEquivSubtypeExists _ _).trans (subtypeEquivRight ?_) intro x exact ⟨fun ⟨hp, h'⟩ => congr_arg Subtype.val h', fun h' => ⟨(h x).2 (h'.symm ▸ y.2), Subtype.eq h'⟩⟩ } _ ≃ Subtype p := sigmaFiberEquiv fun x : Subtype p => (⟨f x, (h x).1 x.property⟩ : Subtype q) /-- A sigma type over an `Option` is equivalent to the sigma set over the original type, if the fiber is empty at none. -/ def sigmaOptionEquivOfSome (p : Option α → Type v) (h : p none → False) : (Σ x : Option α, p x) ≃ Σ x : α, p (some x) := haveI h' : ∀ x, p x → x.isSome := by intro x cases x · intro n exfalso exact h n · intro _ exact rfl (sigmaSubtypeEquivOfSubset _ _ h').symm.trans (sigmaCongrLeft' (optionIsSomeEquiv α)) /-- The `Pi`-type `∀ i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the `Sigma` type such that for all `i` we have `(f i).fst = i`. -/ def piEquivSubtypeSigma (ι) (π : ι → Type*) : (∀ i, π i) ≃ { f : ι → Σ i, π i // ∀ i, (f i).1 = i } where toFun := fun f => ⟨fun i => ⟨i, f i⟩, fun i => rfl⟩ invFun := fun f i => by rw [← f.2 i]; exact (f.1 i).2 left_inv := fun f => funext fun i => rfl right_inv := fun ⟨f, hf⟩ => Subtype.eq <| funext fun i => Sigma.eq (hf i).symm <| eq_of_heq <| rec_heq_of_heq _ <| by simp /-- The type of functions `f : ∀ a, β a` such that for all `a` we have `p a (f a)` is equivalent to the type of functions `∀ a, {b : β a // p a b}`. -/ def subtypePiEquivPi {β : α → Sort v} {p : ∀ a, β a → Prop} : { f : ∀ a, β a // ∀ a, p a (f a) } ≃ ∀ a, { b : β a // p a b } where toFun := fun f a => ⟨f.1 a, f.2 a⟩ invFun := fun f => ⟨fun a => (f a).1, fun a => (f a).2⟩ left_inv := by rintro ⟨f, h⟩ rfl right_inv := by rintro f funext a exact Subtype.ext_val rfl /-- A subtype of a product defined by componentwise conditions is equivalent to a product of subtypes. -/ def subtypeProdEquivProd {p : α → Prop} {q : β → Prop} : { c : α × β // p c.1 ∧ q c.2 } ≃ { a // p a } × { b // q b } where toFun := fun x => ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩ invFun := fun x => ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩ left_inv := fun ⟨⟨_, _⟩, ⟨_, _⟩⟩ => rfl right_inv := fun ⟨⟨_, _⟩, ⟨_, _⟩⟩ => rfl /-- A subtype of a `Prod` that depends only on the first component is equivalent to the corresponding subtype of the first type times the second type. -/ def prodSubtypeFstEquivSubtypeProd {p : α → Prop} : {s : α × β // p s.1} ≃ {a // p a} × β where toFun x := ⟨⟨x.1.1, x.2⟩, x.1.2⟩ invFun x := ⟨⟨x.1.1, x.2⟩, x.1.2⟩ left_inv _ := rfl right_inv _ := rfl /-- A subtype of a `Prod` is equivalent to a sigma type whose fibers are subtypes. -/ def subtypeProdEquivSigmaSubtype (p : α → β → Prop) : { x : α × β // p x.1 x.2 } ≃ Σa, { b : β // p a b } where toFun x := ⟨x.1.1, x.1.2, x.property⟩ invFun x := ⟨⟨x.1, x.2⟩, x.2.property⟩ left_inv x := by ext <;> rfl right_inv := fun ⟨a, b, pab⟩ => rfl /-- The type `∀ (i : α), β i` can be split as a product by separating the indices in `α` depending on whether they satisfy a predicate `p` or not. -/ @[simps] def piEquivPiSubtypeProd {α : Type*} (p : α → Prop) (β : α → Type*) [DecidablePred p] : (∀ i : α, β i) ≃ (∀ i : { x // p x }, β i) × ∀ i : { x // ¬p x }, β i where toFun f := (fun x => f x, fun x => f x) invFun f x := if h : p x then f.1 ⟨x, h⟩ else f.2 ⟨x, h⟩ right_inv := by rintro ⟨f, g⟩ ext1 <;> · ext y rcases y with ⟨val, property⟩ simp only [property, dif_pos, dif_neg, not_false_iff, Subtype.coe_mk] left_inv f := by ext x by_cases h : p x <;> · simp only [h, dif_neg, dif_pos, not_false_iff] /-- A product of types can be split as the binary product of one of the types and the product of all the remaining types. -/ @[simps] def piSplitAt {α : Type*} [DecidableEq α] (i : α) (β : α → Type*) : (∀ j, β j) ≃ β i × ∀ j : { j // j ≠ i }, β j where toFun f := ⟨f i, fun j => f j⟩ invFun f j := if h : j = i then h.symm.rec f.1 else f.2 ⟨j, h⟩ right_inv f := by ext x exacts [dif_pos rfl, (dif_neg x.2).trans (by cases x; rfl)] left_inv f := by ext x dsimp only split_ifs with h · subst h; rfl · rfl /-- A product of copies of a type can be split as the binary product of one copy and the product of all the remaining copies. -/ @[simps!] def funSplitAt {α : Type*} [DecidableEq α] (i : α) (β : Type*) : (α → β) ≃ β × ({ j // j ≠ i } → β) := piSplitAt i _ end section subtypeEquivCodomain variable [DecidableEq X] {x : X} /-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x` is equivalent to the codomain `Y`. -/ def subtypeEquivCodomain (f : { x' // x' ≠ x } → Y) : { g : X → Y // g ∘ (↑) = f } ≃ Y := (subtypePreimage _ f).trans <| @funUnique { x' // ¬x' ≠ x } _ <| show Unique { x' // ¬x' ≠ x } from @Equiv.unique _ _ (show Unique { x' // x' = x } from { default := ⟨x, rfl⟩, uniq := fun ⟨_, h⟩ => Subtype.val_injective h }) (subtypeEquivRight fun _ => not_not) @[simp] theorem coe_subtypeEquivCodomain (f : { x' // x' ≠ x } → Y) : (subtypeEquivCodomain f : _ → Y) = fun g : { g : X → Y // g ∘ (↑) = f } => (g : X → Y) x := rfl @[simp] theorem subtypeEquivCodomain_apply (f : { x' // x' ≠ x } → Y) (g) : subtypeEquivCodomain f g = (g : X → Y) x := rfl theorem coe_subtypeEquivCodomain_symm (f : { x' // x' ≠ x } → Y) : ((subtypeEquivCodomain f).symm : Y → _) = fun y => ⟨fun x' => if h : x' ≠ x then f ⟨x', h⟩ else y, by funext x' simp only [ne_eq, dite_not, comp_apply, Subtype.coe_eta, dite_eq_ite, ite_eq_right_iff] intro w exfalso exact x'.property w⟩ := rfl @[simp] theorem subtypeEquivCodomain_symm_apply (f : { x' // x' ≠ x } → Y) (y : Y) (x' : X) : ((subtypeEquivCodomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y := rfl theorem subtypeEquivCodomain_symm_apply_eq (f : { x' // x' ≠ x } → Y) (y : Y) : ((subtypeEquivCodomain f).symm y : X → Y) x = y := dif_neg (not_not.mpr rfl) theorem subtypeEquivCodomain_symm_apply_ne (f : { x' // x' ≠ x } → Y) (y : Y) (x' : X) (h : x' ≠ x) : ((subtypeEquivCodomain f).symm y : X → Y) x' = f ⟨x', h⟩ := dif_pos h end subtypeEquivCodomain instance : CanLift (α → β) (α ≃ β) (↑) Bijective where prf f hf := ⟨ofBijective f hf, rfl⟩ section variable {α' β' : Type*} (e : Perm α') {p : β' → Prop} [DecidablePred p] (f : α' ≃ Subtype p) /-- Extend the domain of `e : Equiv.Perm α` to one that is over `β` via `f : α → Subtype p`, where `p : β → Prop`, permuting only the `b : β` that satisfy `p b`. This can be used to extend the domain across a function `f : α → β`, keeping everything outside of `Set.range f` fixed. For this use-case `Equiv` given by `f` can be constructed by `Equiv.of_leftInverse'` or `Equiv.of_leftInverse` when there is a known inverse, or `Equiv.ofInjective` in the general case. -/ def Perm.extendDomain : Perm β' := (permCongr f e).subtypeCongr (Equiv.refl _) @[simp] theorem Perm.extendDomain_apply_image (a : α') : e.extendDomain f (f a) = f (e a) := by simp [Perm.extendDomain] theorem Perm.extendDomain_apply_subtype {b : β'} (h : p b) : e.extendDomain f b = f (e (f.symm ⟨b, h⟩)) := by simp [Perm.extendDomain, h] theorem Perm.extendDomain_apply_not_subtype {b : β'} (h : ¬p b) : e.extendDomain f b = b := by simp [Perm.extendDomain, h] @[simp] theorem Perm.extendDomain_refl : Perm.extendDomain (Equiv.refl _) f = Equiv.refl _ := by simp [Perm.extendDomain] @[simp] theorem Perm.extendDomain_symm : (e.extendDomain f).symm = Perm.extendDomain e.symm f := rfl theorem Perm.extendDomain_trans (e e' : Perm α') : (e.extendDomain f).trans (e'.extendDomain f) = Perm.extendDomain (e.trans e') f := by simp [Perm.extendDomain, permCongr_trans] end /-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`. Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/ def subtypeQuotientEquivQuotientSubtype (p₁ : α → Prop) {s₁ : Setoid α} {s₂ : Setoid (Subtype p₁)} (p₂ : Quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : Subtype p₁, s₂.r x y ↔ s₁.r x y) : {x // p₂ x} ≃ Quotient s₂ where toFun a := Quotient.hrecOn a.1 (fun a h => ⟦⟨a, (hp₂ _).2 h⟩⟧) (fun a b hab => hfunext (by rw [Quotient.sound hab]) fun h₁ h₂ _ => heq_of_eq (Quotient.sound ((h _ _).2 hab))) a.2 invFun a := Quotient.liftOn a (fun a => (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : { x // p₂ x })) fun a b hab => Subtype.ext_val (Quotient.sound ((h _ _).1 hab)) left_inv := by exact fun ⟨a, ha⟩ => Quotient.inductionOn a (fun b hb => rfl) ha right_inv a := by exact Quotient.inductionOn a fun ⟨a, ha⟩ => rfl @[simp] theorem subtypeQuotientEquivQuotientSubtype_mk (p₁ : α → Prop) [s₁ : Setoid α] [s₂ : Setoid (Subtype p₁)] (p₂ : Quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : Subtype p₁, @Setoid.r _ s₂ x y ↔ (x : α) ≈ y) (x hx) : subtypeQuotientEquivQuotientSubtype p₁ p₂ hp₂ h ⟨⟦x⟧, hx⟩ = ⟦⟨x, (hp₂ _).2 hx⟩⟧ := rfl @[simp] theorem subtypeQuotientEquivQuotientSubtype_symm_mk (p₁ : α → Prop) [s₁ : Setoid α] [s₂ : Setoid (Subtype p₁)] (p₂ : Quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : Subtype p₁, @Setoid.r _ s₂ x y ↔ (x : α) ≈ y) (x) : (subtypeQuotientEquivQuotientSubtype p₁ p₂ hp₂ h).symm ⟦x⟧ = ⟨⟦x⟧, (hp₂ _).1 x.property⟩ := rfl section Swap variable [DecidableEq α] /-- A helper function for `Equiv.swap`. -/ def swapCore (a b r : α) : α := if r = a then b else if r = b then a else r theorem swapCore_self (r a : α) : swapCore a a r = r := by unfold swapCore split_ifs <;> simp [*] theorem swapCore_swapCore (r a b : α) : swapCore a b (swapCore a b r) = r := by unfold swapCore; split_ifs <;> cc theorem swapCore_comm (r a b : α) : swapCore a b r = swapCore b a r := by unfold swapCore -- Porting note: whatever solution works for `swapCore_swapCore` will work here too. split_ifs with h₁ h₂ h₃ <;> try simp · cases h₁; cases h₂; rfl /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : Perm α := ⟨swapCore a b, swapCore a b, fun r => swapCore_swapCore r a b, fun r => swapCore_swapCore r a b⟩ @[simp] theorem swap_self (a : α) : swap a a = Equiv.refl _ := ext fun r => swapCore_self r a theorem swap_comm (a b : α) : swap a b = swap b a := ext fun r => swapCore_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by by_cases h : b = a <;> simp [swap_apply_def, h] theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp (config := { contextual := true }) [swap_apply_def] theorem eq_or_eq_of_swap_apply_ne_self {a b x : α} (h : swap a b x ≠ x) : x = a ∨ x = b := by contrapose! h exact swap_apply_of_ne_of_ne h.1 h.2 @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = Equiv.refl _ := ext fun _ => swapCore_swapCore _ _ _ @[simp] theorem symm_swap (a b : α) : (swap a b).symm = swap a b := rfl @[simp] theorem swap_eq_refl_iff {x y : α} : swap x y = Equiv.refl _ ↔ x = y := by refine ⟨fun h => (Equiv.refl _).injective ?_, fun h => h ▸ swap_self _⟩ rw [← h, swap_apply_left, h, refl_apply] theorem swap_comp_apply {a b x : α} (π : Perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by cases π rfl theorem swap_eq_update (i j : α) : (Equiv.swap i j : α → α) = update (update id j i) i j := funext fun x => by rw [update_apply _ i j, update_apply _ j i, Equiv.swap_apply_def, id] theorem comp_swap_eq_update (i j : α) (f : α → β) : f ∘ Equiv.swap i j = update (update f j (f i)) i (f j) := by rw [swap_eq_update, comp_update, comp_update, comp_id] @[simp] theorem symm_trans_swap_trans [DecidableEq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := Equiv.ext fun x => by have : ∀ a, e.symm x = a ↔ x = e a := fun a => by rw [@eq_comm _ (e.symm x)] constructor <;> intros <;> simp_all simp only [trans_apply, swap_apply_def, this] split_ifs <;> simp @[simp] theorem trans_swap_trans_symm [DecidableEq β] (a b : β) (e : α ≃ β) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) := symm_trans_swap_trans a b e.symm @[simp] theorem swap_apply_self (i j a : α) : swap i j (swap i j a) = a := by rw [← Equiv.trans_apply, Equiv.swap_swap, Equiv.refl_apply] /-- A function is invariant to a swap if it is equal at both elements -/ theorem apply_swap_eq_self {v : α → β} {i j : α} (hv : v i = v j) (k : α) : v (swap i j k) = v k := by by_cases hi : k = i · rw [hi, swap_apply_left, hv] by_cases hj : k = j · rw [hj, swap_apply_right, hv] rw [swap_apply_of_ne_of_ne hi hj] theorem swap_apply_eq_iff {x y z w : α} : swap x y z = w ↔ z = swap x y w := by rw [apply_eq_iff_eq_symm_apply, symm_swap] theorem swap_apply_ne_self_iff {a b x : α} : swap a b x ≠ x ↔ a ≠ b ∧ (x = a ∨ x = b) := by by_cases hab : a = b · simp [hab] by_cases hax : x = a · simp [hax, eq_comm] by_cases hbx : x = b · simp [hbx] simp [hab, hax, hbx, swap_apply_of_ne_of_ne] namespace Perm @[simp] theorem sumCongr_swap_refl {α β : Sort _} [DecidableEq α] [DecidableEq β] (i j : α) : Equiv.Perm.sumCongr (Equiv.swap i j) (Equiv.refl β) = Equiv.swap (Sum.inl i) (Sum.inl j) := by ext x cases x · simp only [Equiv.sumCongr_apply, Sum.map, coe_refl, comp_id, Sum.elim_inl, comp_apply, swap_apply_def, Sum.inl.injEq] split_ifs <;> rfl · simp [Sum.map, swap_apply_of_ne_of_ne] @[simp] theorem sumCongr_refl_swap {α β : Sort _} [DecidableEq α] [DecidableEq β] (i j : β) : Equiv.Perm.sumCongr (Equiv.refl α) (Equiv.swap i j) = Equiv.swap (Sum.inr i) (Sum.inr j) := by ext x cases x · simp [Sum.map, swap_apply_of_ne_of_ne] · simp only [Equiv.sumCongr_apply, Sum.map, coe_refl, comp_id, Sum.elim_inr, comp_apply, swap_apply_def, Sum.inr.injEq] split_ifs <;> rfl end Perm /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def setValue (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem setValue_eq (f : α ≃ β) (a : α) (b : β) : setValue f a b a = b := by simp [setValue, swap_apply_left] end Swap end Equiv namespace Function.Involutive /-- Convert an involutive function `f` to a permutation with `toFun = invFun = f`. -/ def toPerm (f : α → α) (h : Involutive f) : Equiv.Perm α := ⟨f, f, h.leftInverse, h.rightInverse⟩ @[simp] theorem coe_toPerm {f : α → α} (h : Involutive f) : (h.toPerm f : α → α) = f := rfl @[simp] theorem toPerm_symm {f : α → α} (h : Involutive f) : (h.toPerm f).symm = h.toPerm f := rfl theorem toPerm_involutive {f : α → α} (h : Involutive f) : Involutive (h.toPerm f) := h end Function.Involutive theorem PLift.eq_up_iff_down_eq {x : PLift α} {y : α} : x = PLift.up y ↔ x.down = y := Equiv.plift.eq_symm_apply theorem Function.Injective.map_swap [DecidableEq α] [DecidableEq β] {f : α → β} (hf : Function.Injective f) (x y z : α) : f (Equiv.swap x y z) = Equiv.swap (f x) (f y) (f z) := by conv_rhs => rw [Equiv.swap_apply_def] split_ifs with h₁ h₂ · rw [hf h₁, Equiv.swap_apply_left] · rw [hf h₂, Equiv.swap_apply_right] · rw [Equiv.swap_apply_of_ne_of_ne (mt (congr_arg f) h₁) (mt (congr_arg f) h₂)] namespace Equiv section variable (P : α → Sort w) (e : α ≃ β) /-- Transport dependent functions through an equivalence of the base space. -/ @[simps] def piCongrLeft' (P : α → Sort*) (e : α ≃ β) : (∀ a, P a) ≃ ∀ b, P (e.symm b) where toFun f x := f (e.symm x) invFun f x := (e.symm_apply_apply x).ndrec (f (e x)) left_inv f := funext fun x => (by rintro _ rfl; rfl : ∀ {y} (h : y = x), h.ndrec (f y) = f x) (e.symm_apply_apply x) right_inv f := funext fun x => (by rintro _ rfl; rfl : ∀ {y} (h : y = x), (congr_arg e.symm h).ndrec (f y) = f x) (e.apply_symm_apply x) /-- Note: the "obvious" statement `(piCongrLeft' P e).symm g a = g (e a)` doesn't typecheck: the LHS would have type `P a` while the RHS would have type `P (e.symm (e a))`. For that reason, we have to explicitly substitute along `e.symm (e a) = a` in the statement of this lemma. -/ add_decl_doc Equiv.piCongrLeft'_symm_apply /-- This lemma is impractical to state in the dependent case. -/ @[simp] theorem piCongrLeft'_symm (P : Sort*) (e : α ≃ β) : (piCongrLeft' (fun _ => P) e).symm = piCongrLeft' _ e.symm := by ext; simp [piCongrLeft'] /-- Note: the "obvious" statement `(piCongrLeft' P e).symm g a = g (e a)` doesn't typecheck: the LHS would have type `P a` while the RHS would have type `P (e.symm (e a))`. This lemma is a way around it in the case where `a` is of the form `e.symm b`, so we can use `g b` instead of `g (e (e.symm b))`. -/ lemma piCongrLeft'_symm_apply_apply (P : α → Sort*) (e : α ≃ β) (g : ∀ b, P (e.symm b)) (b : β) : (piCongrLeft' P e).symm g (e.symm b) = g b := by change Eq.ndrec _ _ = _ generalize_proofs hZa revert hZa rw [e.apply_symm_apply b] simp end section variable (P : β → Sort w) (e : α ≃ β) /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". -/ def piCongrLeft : (∀ a, P (e a)) ≃ ∀ b, P b := (piCongrLeft' P e.symm).symm /-- Note: the "obvious" statement `(piCongrLeft P e) f b = f (e.symm b)` doesn't typecheck: the LHS would have type `P b` while the RHS would have type `P (e (e.symm b))`. For that reason, we have to explicitly substitute along `e (e.symm b) = b` in the statement of this lemma. -/ @[simp] lemma piCongrLeft_apply (f : ∀ a, P (e a)) (b : β) : (piCongrLeft P e) f b = e.apply_symm_apply b ▸ f (e.symm b) := rfl @[simp] lemma piCongrLeft_symm_apply (g : ∀ b, P b) (a : α) : (piCongrLeft P e).symm g a = g (e a) := piCongrLeft'_apply P e.symm g a /-- Note: the "obvious" statement `(piCongrLeft P e) f b = f (e.symm b)` doesn't typecheck: the LHS would have type `P b` while the RHS would have type `P (e (e.symm b))`. This lemma is a way around it in the case where `b` is of the form `e a`, so we can use `f a` instead of `f (e.symm (e a))`. -/ lemma piCongrLeft_apply_apply (f : ∀ a, P (e a)) (a : α) : (piCongrLeft P e) f (e a) = f a := piCongrLeft'_symm_apply_apply P e.symm f a open Sum lemma piCongrLeft_apply_eq_cast {P : β → Sort v} {e : α ≃ β} (f : (a : α) → P (e a)) (b : β) : piCongrLeft P e f b = cast (congr_arg P (e.apply_symm_apply b)) (f (e.symm b)) := Eq.rec_eq_cast _ _ theorem piCongrLeft_sum_inl (π : ι'' → Type*) (e : ι ⊕ ι' ≃ ι'') (f : ∀ i, π (e (inl i))) (g : ∀ i, π (e (inr i))) (i : ι) : piCongrLeft π e (sumPiEquivProdPi (fun x => π (e x)) |>.symm (f, g)) (e (inl i)) = f i := by simp_rw [piCongrLeft_apply_eq_cast, sumPiEquivProdPi_symm_apply, sum_rec_congr _ _ _ (e.symm_apply_apply (inl i)), cast_cast, cast_eq] theorem piCongrLeft_sum_inr (π : ι'' → Type*) (e : ι ⊕ ι' ≃ ι'') (f : ∀ i, π (e (inl i))) (g : ∀ i, π (e (inr i))) (j : ι') : piCongrLeft π e (sumPiEquivProdPi (fun x => π (e x)) |>.symm (f, g)) (e (inr j)) = g j := by simp_rw [piCongrLeft_apply_eq_cast, sumPiEquivProdPi_symm_apply, sum_rec_congr _ _ _ (e.symm_apply_apply (inr j)), cast_cast, cast_eq] end section variable {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : ∀ a : α, W a ≃ Z (h₁ a)) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibers. -/ def piCongr : (∀ a, W a) ≃ ∀ b, Z b := (Equiv.piCongrRight h₂).trans (Equiv.piCongrLeft _ h₁) @[simp] theorem coe_piCongr_symm : ((h₁.piCongr h₂).symm : (∀ b, Z b) → ∀ a, W a) = fun f a => (h₂ a).symm (f (h₁ a)) := rfl theorem piCongr_symm_apply (f : ∀ b, Z b) : (h₁.piCongr h₂).symm f = fun a => (h₂ a).symm (f (h₁ a)) := rfl @[simp] theorem piCongr_apply_apply (f : ∀ a, W a) (a : α) : h₁.piCongr h₂ f (h₁ a) = h₂ a (f a) := by simp only [piCongr, piCongrRight, trans_apply, coe_fn_mk, piCongrLeft_apply_apply] end section variable {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : ∀ b : β, W (h₁.symm b) ≃ Z b) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def piCongr' : (∀ a, W a) ≃ ∀ b, Z b := (piCongr h₁.symm fun b => (h₂ b).symm).symm @[simp] theorem coe_piCongr' : (h₁.piCongr' h₂ : (∀ a, W a) → ∀ b, Z b) = fun f b => h₂ b <| f <| h₁.symm b := rfl theorem piCongr'_apply (f : ∀ a, W a) : h₁.piCongr' h₂ f = fun b => h₂ b <| f <| h₁.symm b := rfl @[simp] theorem piCongr'_symm_apply_symm_apply (f : ∀ b, Z b) (b : β) : (h₁.piCongr' h₂).symm f (h₁.symm b) = (h₂ b).symm (f b) := by simp [piCongr', piCongr_apply_apply] end section BinaryOp variable {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) theorem semiconj_conj (f : α₁ → α₁) : Semiconj e f (e.conj f) := fun x => by simp theorem semiconj₂_conj : Semiconj₂ e f (e.arrowCongr e.conj f) := fun x y => by simp [arrowCongr] instance [Std.Associative f] : Std.Associative (e.arrowCongr (e.arrowCongr e) f) := (e.semiconj₂_conj f).isAssociative_right e.surjective instance [Std.IdempotentOp f] : Std.IdempotentOp (e.arrowCongr (e.arrowCongr e) f) := (e.semiconj₂_conj f).isIdempotent_right e.surjective instance [IsLeftCancel α₁ f] : IsLeftCancel β₁ (e.arrowCongr (e.arrowCongr e) f) := ⟨e.surjective.forall₃.2 fun x y z => by simpa using @IsLeftCancel.left_cancel _ f _ x y z⟩ instance [IsRightCancel α₁ f] : IsRightCancel β₁ (e.arrowCongr (e.arrowCongr e) f) := ⟨e.surjective.forall₃.2 fun x y z => by simpa using @IsRightCancel.right_cancel _ f _ x y z⟩ end BinaryOp section ULift @[simp] theorem ulift_symm_down (x : α) : (Equiv.ulift.{u, v}.symm x).down = x := rfl end ULift end Equiv theorem Function.Injective.swap_apply [DecidableEq α] [DecidableEq β] {f : α → β} (hf : Function.Injective f) (x y z : α) : Equiv.swap (f x) (f y) (f z) = f (Equiv.swap x y z) := by by_cases hx : z = x · simp [hx] by_cases hy : z = y · simp [hy] rw [Equiv.swap_apply_of_ne_of_ne hx hy, Equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)] theorem Function.Injective.swap_comp [DecidableEq α] [DecidableEq β] {f : α → β} (hf : Function.Injective f) (x y : α) : Equiv.swap (f x) (f y) ∘ f = f ∘ Equiv.swap x y := funext fun _ => hf.swap_apply _ _ _ /-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/ def subsingletonProdSelfEquiv [Subsingleton α] : α × α ≃ α where toFun p := p.1 invFun a := (a, a) left_inv _ := Subsingleton.elim _ _ right_inv _ := Subsingleton.elim _ _ /-- To give an equivalence between two subsingleton types, it is sufficient to give any two functions between them. -/ def equivOfSubsingletonOfSubsingleton [Subsingleton α] [Subsingleton β] (f : α → β) (g : β → α) : α ≃ β where toFun := f invFun := g left_inv _ := Subsingleton.elim _ _ right_inv _ := Subsingleton.elim _ _ /-- A nonempty subsingleton type is (noncomputably) equivalent to `PUnit`. -/ noncomputable def Equiv.punitOfNonemptyOfSubsingleton [h : Nonempty α] [Subsingleton α] : α ≃ PUnit := equivOfSubsingletonOfSubsingleton (fun _ => PUnit.unit) fun _ => h.some /-- `Unique (Unique α)` is equivalent to `Unique α`. -/ def uniqueUniqueEquiv : Unique (Unique α) ≃ Unique α := equivOfSubsingletonOfSubsingleton (fun h => h.default) fun h => { default := h, uniq := fun _ => Subsingleton.elim _ _ } /-- If `Unique β`, then `Unique α` is equivalent to `α ≃ β`. -/ def uniqueEquivEquivUnique (α : Sort u) (β : Sort v) [Unique β] : Unique α ≃ (α ≃ β) := equivOfSubsingletonOfSubsingleton (fun _ => Equiv.equivOfUnique _ _) Equiv.unique namespace Function theorem update_comp_equiv [DecidableEq α'] [DecidableEq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) : update f a v ∘ g = update (f ∘ g) (g.symm a) v := by rw [← update_comp_eq_of_injective _ g.injective, g.apply_symm_apply] theorem update_apply_equiv_apply [DecidableEq α'] [DecidableEq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') : update f a v (g a') = update (f ∘ g) (g.symm a) v a' := congr_fun (update_comp_equiv f g a v) a' -- Porting note: EmbeddingLike.apply_eq_iff_eq broken here too theorem piCongrLeft'_update [DecidableEq α] [DecidableEq β] (P : α → Sort*) (e : α ≃ β) (f : ∀ a, P a) (b : β) (x : P (e.symm b)) : e.piCongrLeft' P (update f (e.symm b) x) = update (e.piCongrLeft' P f) b x := by ext b' rcases eq_or_ne b' b with (rfl | h) · simp · simp only [Equiv.piCongrLeft'_apply, ne_eq, h, not_false_iff, update_noteq] rw [update_noteq _] rw [ne_eq] intro h' /- an example of something that should work, or also putting `EmbeddingLike.apply_eq_iff_eq` in the `simp` should too: have := (EmbeddingLike.apply_eq_iff_eq e).mp h' -/ cases e.symm.injective h' |> h theorem piCongrLeft'_symm_update [DecidableEq α] [DecidableEq β] (P : α → Sort*) (e : α ≃ β) (f : ∀ b, P (e.symm b)) (b : β) (x : P (e.symm b)) : (e.piCongrLeft' P).symm (update f b x) = update ((e.piCongrLeft' P).symm f) (e.symm b) x := by simp [(e.piCongrLeft' P).symm_apply_eq, piCongrLeft'_update] end Function
Logic\Equiv\Defs.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import Mathlib.Data.FunLike.Equiv import Mathlib.Data.Quot import Mathlib.Data.Bool.Basic import Mathlib.Logic.Unique import Mathlib.Tactic.Substs import Mathlib.Tactic.Conv /-! # Equivalence between types In this file we define two types: * `Equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and not equality!) to express that various `Type`s or `Sort`s are equivalent. * `Equiv.Perm α`: the group of permutations `α ≃ α`. More lemmas about `Equiv.Perm` can be found in `GroupTheory.Perm`. Then we define * canonical isomorphisms between various types: e.g., - `Equiv.refl α` is the identity map interpreted as `α ≃ α`; * operations on equivalences: e.g., - `Equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`; - `Equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order of the arguments!); * definitions that transfer some instances along an equivalence. By convention, we transfer instances from right to left. - `Equiv.inhabited` takes `e : α ≃ β` and `[Inhabited β]` and returns `Inhabited α`; - `Equiv.unique` takes `e : α ≃ β` and `[Unique β]` and returns `Unique α`; - `Equiv.decidableEq` takes `e : α ≃ β` and `[DecidableEq β]` and returns `DecidableEq α`. More definitions of this kind can be found in other files. E.g., `Data.Equiv.TransferInstance` does it for many algebraic type classes like `Group`, `Module`, etc. Many more such isomorphisms and operations are defined in `Logic.Equiv.Basic`. ## Tags equivalence, congruence, bijective map -/ open Function universe u v w z variable {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure Equiv (α : Sort*) (β : Sort _) where protected toFun : α → β protected invFun : β → α protected left_inv : LeftInverse invFun toFun protected right_inv : RightInverse invFun toFun @[inherit_doc] infixl:25 " ≃ " => Equiv /-- Turn an element of a type `F` satisfying `EquivLike F α β` into an actual `Equiv`. This is declared as the default coercion from `F` to `α ≃ β`. -/ @[coe] def EquivLike.toEquiv {F} [EquivLike F α β] (f : F) : α ≃ β where toFun := f invFun := EquivLike.inv f left_inv := EquivLike.left_inv f right_inv := EquivLike.right_inv f /-- Any type satisfying `EquivLike` can be cast into `Equiv` via `EquivLike.toEquiv`. -/ instance {F} [EquivLike F α β] : CoeTC F (α ≃ β) := ⟨EquivLike.toEquiv⟩ /-- `Perm α` is the type of bijections from `α` to itself. -/ abbrev Equiv.Perm (α : Sort*) := Equiv α α namespace Equiv instance : EquivLike (α ≃ β) α β where coe := Equiv.toFun inv := Equiv.invFun left_inv := Equiv.left_inv right_inv := Equiv.right_inv coe_injective' e₁ e₂ h₁ h₂ := by cases e₁; cases e₂; congr /-- Helper instance when inference gets stuck on following the normal chain `EquivLike → FunLike`. TODO: this instance doesn't appear to be necessary: remove it (after benchmarking?) -/ instance : FunLike (α ≃ β) α β where coe := Equiv.toFun coe_injective' := DFunLike.coe_injective @[simp, norm_cast] lemma _root_.EquivLike.coe_coe {F} [EquivLike F α β] (e : F) : ((e : α ≃ β) : α → β) = e := rfl @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (Equiv.mk f g l r : α → β) = f := rfl /-- The map `(r ≃ s) → (r → s)` is injective. -/ theorem coe_fn_injective : @Function.Injective (α ≃ β) (α → β) (fun e => e) := DFunLike.coe_injective' protected theorem coe_inj {e₁ e₂ : α ≃ β} : (e₁ : α → β) = e₂ ↔ e₁ = e₂ := @DFunLike.coe_fn_eq _ _ _ _ e₁ e₂ @[ext] theorem ext {f g : Equiv α β} (H : ∀ x, f x = g x) : f = g := DFunLike.ext f g H protected theorem congr_arg {f : Equiv α β} {x x' : α} : x = x' → f x = f x' := DFunLike.congr_arg f protected theorem congr_fun {f g : Equiv α β} (h : f = g) (x : α) : f x = g x := DFunLike.congr_fun h x @[ext] theorem Perm.ext {σ τ : Equiv.Perm α} (H : ∀ x, σ x = τ x) : σ = τ := Equiv.ext H protected theorem Perm.congr_arg {f : Equiv.Perm α} {x x' : α} : x = x' → f x = f x' := Equiv.congr_arg protected theorem Perm.congr_fun {f g : Equiv.Perm α} (h : f = g) (x : α) : f x = g x := Equiv.congr_fun h x /-- Any type is equivalent to itself. -/ @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, fun _ => rfl, fun _ => rfl⟩ instance inhabited' : Inhabited (α ≃ α) := ⟨Equiv.refl α⟩ /-- Inverse of an equivalence `e : α ≃ β`. -/ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.invFun, e.toFun, e.right_inv, e.left_inv⟩ /-- See Note [custom simps projection] -/ def Simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections Equiv (toFun → apply, invFun → symm_apply) -- Porting note: -- Added these lemmas as restatements of `left_inv` and `right_inv`, -- which use the coercions. -- We might even consider switching the names, and having these as a public API. theorem left_inv' (e : α ≃ β) : Function.LeftInverse e.symm e := e.left_inv theorem right_inv' (e : α ≃ β) : Function.RightInverse e.symm e := e.right_inv /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ @[simps] instance : Trans Equiv Equiv Equiv where trans := Equiv.trans -- Porting note: this is not a syntactic tautology any more because -- the coercion from `e` to a function is now `DFunLike.coe` not `e.toFun` @[simp, mfld_simps] theorem toFun_as_coe (e : α ≃ β) : e.toFun = e := rfl @[simp, mfld_simps] theorem invFun_as_coe (e : α ≃ β) : e.invFun = e.symm := rfl protected theorem injective (e : α ≃ β) : Injective e := EquivLike.injective e protected theorem surjective (e : α ≃ β) : Surjective e := EquivLike.surjective e protected theorem bijective (e : α ≃ β) : Bijective e := EquivLike.bijective e protected theorem subsingleton (e : α ≃ β) [Subsingleton β] : Subsingleton α := e.injective.subsingleton protected theorem subsingleton.symm (e : α ≃ β) [Subsingleton α] : Subsingleton β := e.symm.injective.subsingleton theorem subsingleton_congr (e : α ≃ β) : Subsingleton α ↔ Subsingleton β := ⟨fun _ => e.symm.subsingleton, fun _ => e.subsingleton⟩ instance equiv_subsingleton_cod [Subsingleton β] : Subsingleton (α ≃ β) := ⟨fun _ _ => Equiv.ext fun _ => Subsingleton.elim _ _⟩ instance equiv_subsingleton_dom [Subsingleton α] : Subsingleton (α ≃ β) := ⟨fun f _ => Equiv.ext fun _ => @Subsingleton.elim _ (Equiv.subsingleton.symm f) _ _⟩ instance permUnique [Subsingleton α] : Unique (Perm α) := uniqueOfSubsingleton (Equiv.refl α) theorem Perm.subsingleton_eq_refl [Subsingleton α] (e : Perm α) : e = Equiv.refl α := Subsingleton.elim _ _ /-- Transfer `DecidableEq` across an equivalence. -/ protected def decidableEq (e : α ≃ β) [DecidableEq β] : DecidableEq α := e.injective.decidableEq theorem nonempty_congr (e : α ≃ β) : Nonempty α ↔ Nonempty β := Nonempty.congr e e.symm protected theorem nonempty (e : α ≃ β) [Nonempty β] : Nonempty α := e.nonempty_congr.mpr ‹_› /-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/ protected def inhabited [Inhabited β] (e : α ≃ β) : Inhabited α := ⟨e.symm default⟩ /-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/ protected def unique [Unique β] (e : α ≃ β) : Unique α := e.symm.surjective.unique /-- Equivalence between equal types. -/ protected def cast {α β : Sort _} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, fun _ => by cases h; rfl, fun _ => by cases h; rfl⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((Equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem coe_refl : (Equiv.refl α : α → α) = id := rfl /-- This cannot be a `simp` lemmas as it incorrectly matches against `e : α ≃ synonym α`, when `synonym α` is semireducible. This makes a mess of `Multiplicative.ofAdd` etc. -/ theorem Perm.coe_subsingleton {α : Type*} [Subsingleton α] (e : Perm α) : (e : α → α) = id := by rw [Perm.subsingleton_eq_refl e, coe_refl] -- Porting note: marking this as `@[simp]` because `simp` doesn't fire on `coe_refl` -- in an expression such as `Equiv.refl a x` @[simp] theorem refl_apply (x : α) : Equiv.refl α x = x := rfl @[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : (f.trans g : α → γ) = g ∘ f := rfl -- Porting note: marking this as `@[simp]` because `simp` doesn't fire on `coe_trans` -- in an expression such as `Equiv.trans f g x` @[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x := e.right_inv x @[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x := e.left_inv x @[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp] lemma _root_.EquivLike.apply_coe_symm_apply {F} [EquivLike F α β] (e : F) (x : β) : e ((e : α ≃ β).symm x) = x := (e : α ≃ β).apply_symm_apply x @[simp] lemma _root_.EquivLike.coe_symm_apply_apply {F} [EquivLike F α β] (e : F) (x : α) : (e : α ≃ β).symm (e x) = x := (e : α ≃ β).symm_apply_apply x @[simp] lemma _root_.EquivLike.coe_symm_comp_self {F} [EquivLike F α β] (e : F) : (e : α ≃ β).symm ∘ e = id := (e : α ≃ β).symm_comp_self @[simp] lemma _root_.EquivLike.self_comp_coe_symm {F} [EquivLike F α β] (e : F) : e ∘ (e : α ≃ β).symm = id := (e : α ≃ β).self_comp_symm @[simp] theorem symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl -- The `simp` attribute is needed to make this a `dsimp` lemma. -- `simp` will always rewrite with `Equiv.symm_symm` before this has a chance to fire. @[simp, nolint simpNF] theorem symm_symm_apply (f : α ≃ β) (b : α) : f.symm.symm b = f b := rfl theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y := EquivLike.apply_eq_iff_eq f theorem apply_eq_iff_eq_symm_apply {x : α} {y : β} (f : α ≃ β) : f x = y ↔ x = f.symm y := by conv_lhs => rw [← apply_symm_apply f y] rw [apply_eq_iff_eq] @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : Equiv.cast h x = cast h x := rfl @[simp] theorem cast_symm {α β} (h : α = β) : (Equiv.cast h).symm = Equiv.cast h.symm := rfl @[simp] theorem cast_refl {α} (h : α = α := rfl) : Equiv.cast h = Equiv.refl α := rfl @[simp] theorem cast_trans {α β γ} (h : α = β) (h2 : β = γ) : (Equiv.cast h).trans (Equiv.cast h2) = Equiv.cast (h.trans h2) := ext fun x => by substs h h2; rfl theorem cast_eq_iff_heq {α β} (h : α = β) {a : α} {b : β} : Equiv.cast h a = b ↔ HEq a b := by subst h; simp [coe_refl] theorem symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨fun H => by simp [H.symm], fun H => by simp [H]⟩ theorem eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by cases e; rfl theorem symm_bijective : Function.Bijective (Equiv.symm : (α ≃ β) → β ≃ α) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ @[simp] theorem trans_refl (e : α ≃ β) : e.trans (Equiv.refl β) = e := by cases e; rfl @[simp] theorem refl_symm : (Equiv.refl α).symm = Equiv.refl α := rfl @[simp] theorem refl_trans (e : α ≃ β) : (Equiv.refl α).trans e = e := by cases e; rfl @[simp] theorem symm_trans_self (e : α ≃ β) : e.symm.trans e = Equiv.refl β := ext <| by simp @[simp] theorem self_trans_symm (e : α ≃ β) : e.trans e.symm = Equiv.refl α := ext <| by simp theorem trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := Equiv.ext fun _ => rfl theorem leftInverse_symm (f : Equiv α β) : LeftInverse f.symm f := f.left_inv theorem rightInverse_symm (f : Equiv α β) : Function.RightInverse f.symm f := f.right_inv theorem injective_comp (e : α ≃ β) (f : β → γ) : Injective (f ∘ e) ↔ Injective f := EquivLike.injective_comp e f theorem comp_injective (f : α → β) (e : β ≃ γ) : Injective (e ∘ f) ↔ Injective f := EquivLike.comp_injective f e theorem surjective_comp (e : α ≃ β) (f : β → γ) : Surjective (f ∘ e) ↔ Surjective f := EquivLike.surjective_comp e f theorem comp_surjective (f : α → β) (e : β ≃ γ) : Surjective (e ∘ f) ↔ Surjective f := EquivLike.comp_surjective f e theorem bijective_comp (e : α ≃ β) (f : β → γ) : Bijective (f ∘ e) ↔ Bijective f := EquivLike.bijective_comp e f theorem comp_bijective (f : α → β) (e : β ≃ γ) : Bijective (e ∘ f) ↔ Bijective f := EquivLike.comp_bijective f e /-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ` is equivalent to the type of equivalences `β ≃ δ`. -/ def equivCongr {δ : Sort*} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) where toFun ac := (ab.symm.trans ac).trans cd invFun bd := ab.trans <| bd.trans <| cd.symm left_inv ac := by ext x; simp only [trans_apply, comp_apply, symm_apply_apply] right_inv ac := by ext x; simp only [trans_apply, comp_apply, apply_symm_apply] @[simp] theorem equivCongr_refl {α β} : (Equiv.refl α).equivCongr (Equiv.refl β) = Equiv.refl (α ≃ β) := by ext; rfl @[simp] theorem equivCongr_symm {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (ab.equivCongr cd).symm = ab.symm.equivCongr cd.symm := by ext; rfl @[simp] theorem equivCongr_trans {δ ε ζ} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) : (ab.equivCongr de).trans (bc.equivCongr ef) = (ab.trans bc).equivCongr (de.trans ef) := by ext; rfl @[simp] theorem equivCongr_refl_left {α β γ} (bg : β ≃ γ) (e : α ≃ β) : (Equiv.refl α).equivCongr bg e = e.trans bg := rfl @[simp] theorem equivCongr_refl_right {α β} (ab e : α ≃ β) : ab.equivCongr (Equiv.refl β) e = ab.symm.trans e := rfl @[simp] theorem equivCongr_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) : ab.equivCongr cd e x = cd (e (ab.symm x)) := rfl section permCongr variable {α' β' : Type*} (e : α' ≃ β') /-- If `α` is equivalent to `β`, then `Perm α` is equivalent to `Perm β`. -/ def permCongr : Perm α' ≃ Perm β' := equivCongr e e theorem permCongr_def (p : Equiv.Perm α') : e.permCongr p = (e.symm.trans p).trans e := rfl @[simp] theorem permCongr_refl : e.permCongr (Equiv.refl _) = Equiv.refl _ := by simp [permCongr_def] @[simp] theorem permCongr_symm : e.permCongr.symm = e.symm.permCongr := rfl @[simp] theorem permCongr_apply (p : Equiv.Perm α') (x) : e.permCongr p x = e (p (e.symm x)) := rfl theorem permCongr_symm_apply (p : Equiv.Perm β') (x) : e.permCongr.symm p x = e.symm (p (e x)) := rfl theorem permCongr_trans (p p' : Equiv.Perm α') : (e.permCongr p).trans (e.permCongr p') = e.permCongr (p.trans p') := by ext; simp only [trans_apply, comp_apply, permCongr_apply, symm_apply_apply] end permCongr /-- Two empty types are equivalent. -/ def equivOfIsEmpty (α β : Sort*) [IsEmpty α] [IsEmpty β] : α ≃ β := ⟨isEmptyElim, isEmptyElim, isEmptyElim, isEmptyElim⟩ /-- If `α` is an empty type, then it is equivalent to the `Empty` type. -/ def equivEmpty (α : Sort u) [IsEmpty α] : α ≃ Empty := equivOfIsEmpty α _ /-- If `α` is an empty type, then it is equivalent to the `PEmpty` type in any universe. -/ def equivPEmpty (α : Sort v) [IsEmpty α] : α ≃ PEmpty.{u} := equivOfIsEmpty α _ /-- `α` is equivalent to an empty type iff `α` is empty. -/ def equivEmptyEquiv (α : Sort u) : α ≃ Empty ≃ IsEmpty α := ⟨fun e => Function.isEmpty e, @equivEmpty α, fun e => ext fun x => (e x).elim, fun _ => rfl⟩ /-- The `Sort` of proofs of a false proposition is equivalent to `PEmpty`. -/ def propEquivPEmpty {p : Prop} (h : ¬p) : p ≃ PEmpty := @equivPEmpty p <| IsEmpty.prop_iff.2 h /-- If both `α` and `β` have a unique element, then `α ≃ β`. -/ def equivOfUnique (α β : Sort _) [Unique.{u} α] [Unique.{v} β] : α ≃ β where toFun := default invFun := default left_inv _ := Subsingleton.elim _ _ right_inv _ := Subsingleton.elim _ _ /-- If `α` has a unique element, then it is equivalent to any `PUnit`. -/ def equivPUnit (α : Sort u) [Unique α] : α ≃ PUnit.{v} := equivOfUnique α _ /-- The `Sort` of proofs of a true proposition is equivalent to `PUnit`. -/ def propEquivPUnit {p : Prop} (h : p) : p ≃ PUnit.{0} := @equivPUnit p <| uniqueProp h /-- `ULift α` is equivalent to `α`. -/ @[simps (config := .asFn) apply] protected def ulift {α : Type v} : ULift.{u} α ≃ α := ⟨ULift.down, ULift.up, ULift.up_down, ULift.down_up.{v, u}⟩ /-- `PLift α` is equivalent to `α`. -/ @[simps (config := .asFn) apply] protected def plift : PLift α ≃ α := ⟨PLift.down, PLift.up, PLift.up_down, PLift.down_up⟩ /-- equivalence of propositions is the same as iff -/ def ofIff {P Q : Prop} (h : P ↔ Q) : P ≃ Q := ⟨h.mp, h.mpr, fun _ => rfl, fun _ => rfl⟩ /-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁` is equivalent to the type of maps `α₂ → β₂`. -/ -- Porting note: removing `congr` attribute @[simps apply] def arrowCongr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) where toFun f := e₂ ∘ f ∘ e₁.symm invFun f := e₂.symm ∘ f ∘ e₁ left_inv f := funext fun x => by simp only [comp_apply, symm_apply_apply] right_inv f := funext fun x => by simp only [comp_apply, apply_symm_apply] theorem arrowCongr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : arrowCongr ea ec (g ∘ f) = arrowCongr eb ec g ∘ arrowCongr ea eb f := by ext; simp only [comp, arrowCongr_apply, eb.symm_apply_apply] @[simp] theorem arrowCongr_refl {α β : Sort*} : arrowCongr (Equiv.refl α) (Equiv.refl β) = Equiv.refl (α → β) := rfl @[simp] theorem arrowCongr_trans {α₁ α₂ α₃ β₁ β₂ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrowCongr (e₁.trans e₂) (e₁'.trans e₂') = (arrowCongr e₁ e₁').trans (arrowCongr e₂ e₂') := rfl @[simp] theorem arrowCongr_symm {α₁ α₂ β₁ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrowCongr e₁ e₂).symm = arrowCongr e₁.symm e₂.symm := rfl /-- A version of `Equiv.arrowCongr` in `Type`, rather than `Sort`. The `equiv_rw` tactic is not able to use the default `Sort` level `Equiv.arrowCongr`, because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`. -/ -- Porting note: removing `congr` attribute @[simps! apply] def arrowCongr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := Equiv.arrowCongr hα hβ @[simp] theorem arrowCongr'_refl {α β : Type*} : arrowCongr' (Equiv.refl α) (Equiv.refl β) = Equiv.refl (α → β) := rfl @[simp] theorem arrowCongr'_trans {α₁ α₂ β₁ β₂ α₃ β₃ : Type*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrowCongr' (e₁.trans e₂) (e₁'.trans e₂') = (arrowCongr' e₁ e₁').trans (arrowCongr' e₂ e₂') := rfl @[simp] theorem arrowCongr'_symm {α₁ α₂ β₁ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrowCongr' e₁ e₂).symm = arrowCongr' e₁.symm e₂.symm := rfl /-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/ @[simps! apply] def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrowCongr e e @[simp] theorem conj_refl : conj (Equiv.refl α) = Equiv.refl (α → α) := rfl @[simp] theorem conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl @[simp] theorem conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl -- This should not be a simp lemma as long as `(∘)` is reducible: -- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using -- `f₁ := g` and `f₂ := fun x ↦ x`. This causes nontermination. theorem conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = e.conj f₁ ∘ e.conj f₂ := by apply arrowCongr_comp theorem eq_comp_symm {α β γ} (e : α ≃ β) (f : β → γ) (g : α → γ) : f = g ∘ e.symm ↔ f ∘ e = g := (e.arrowCongr (Equiv.refl γ)).symm_apply_eq.symm theorem comp_symm_eq {α β γ} (e : α ≃ β) (f : β → γ) (g : α → γ) : g ∘ e.symm = f ↔ g = f ∘ e := (e.arrowCongr (Equiv.refl γ)).eq_symm_apply.symm theorem eq_symm_comp {α β γ} (e : α ≃ β) (f : γ → α) (g : γ → β) : f = e.symm ∘ g ↔ e ∘ f = g := ((Equiv.refl γ).arrowCongr e).eq_symm_apply theorem symm_comp_eq {α β γ} (e : α ≃ β) (f : γ → α) (g : γ → β) : e.symm ∘ g = f ↔ g = e ∘ f := ((Equiv.refl γ).arrowCongr e).symm_apply_eq /-- `PUnit` sorts in any two universes are equivalent. -/ def punitEquivPUnit : PUnit.{v} ≃ PUnit.{w} := ⟨fun _ => .unit, fun _ => .unit, fun ⟨⟩ => rfl, fun ⟨⟩ => rfl⟩ /-- `Prop` is noncomputably equivalent to `Bool`. -/ noncomputable def propEquivBool : Prop ≃ Bool where toFun p := @decide p (Classical.propDecidable _) invFun b := b left_inv p := by simp [@Bool.decide_iff p (Classical.propDecidable _)] right_inv b := by cases b <;> simp section /-- The sort of maps to `PUnit.{v}` is equivalent to `PUnit.{w}`. -/ def arrowPUnitEquivPUnit (α : Sort*) : (α → PUnit.{v}) ≃ PUnit.{w} := ⟨fun _ => .unit, fun _ _ => .unit, fun _ => rfl, fun _ => rfl⟩ /-- The equivalence `(∀ i, β i) ≃ β ⋆` when the domain of `β` only contains `⋆` -/ @[simps (config := .asFn)] def piUnique [Unique α] (β : α → Sort*) : (∀ i, β i) ≃ β default where toFun f := f default invFun := uniqueElim left_inv f := by ext i; cases Unique.eq_default i; rfl right_inv x := rfl /-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/ @[simps! (config := .asFn) apply symm_apply] def funUnique (α β) [Unique.{u} α] : (α → β) ≃ β := piUnique _ /-- The sort of maps from `PUnit` is equivalent to the codomain. -/ def punitArrowEquiv (α : Sort*) : (PUnit.{u} → α) ≃ α := funUnique PUnit.{u} α /-- The sort of maps from `True` is equivalent to the codomain. -/ def trueArrowEquiv (α : Sort*) : (True → α) ≃ α := funUnique _ _ /-- The sort of maps from a type that `IsEmpty` is equivalent to `PUnit`. -/ def arrowPUnitOfIsEmpty (α β : Sort*) [IsEmpty α] : (α → β) ≃ PUnit.{u} where toFun _ := PUnit.unit invFun _ := isEmptyElim left_inv _ := funext isEmptyElim right_inv _ := rfl /-- The sort of maps from `Empty` is equivalent to `PUnit`. -/ def emptyArrowEquivPUnit (α : Sort*) : (Empty → α) ≃ PUnit.{u} := arrowPUnitOfIsEmpty _ _ /-- The sort of maps from `PEmpty` is equivalent to `PUnit`. -/ def pemptyArrowEquivPUnit (α : Sort*) : (PEmpty → α) ≃ PUnit.{u} := arrowPUnitOfIsEmpty _ _ /-- The sort of maps from `False` is equivalent to `PUnit`. -/ def falseArrowEquivPUnit (α : Sort*) : (False → α) ≃ PUnit.{u} := arrowPUnitOfIsEmpty _ _ end section /-- A `PSigma`-type is equivalent to the corresponding `Sigma`-type. -/ @[simps apply symm_apply] def psigmaEquivSigma {α} (β : α → Type*) : (Σ' i, β i) ≃ Σ i, β i where toFun a := ⟨a.1, a.2⟩ invFun a := ⟨a.1, a.2⟩ left_inv _ := rfl right_inv _ := rfl /-- A `PSigma`-type is equivalent to the corresponding `Sigma`-type. -/ @[simps apply symm_apply] def psigmaEquivSigmaPLift {α} (β : α → Sort*) : (Σ' i, β i) ≃ Σ i : PLift α, PLift (β i.down) where toFun a := ⟨PLift.up a.1, PLift.up a.2⟩ invFun a := ⟨a.1.down, a.2.down⟩ left_inv _ := rfl right_inv _ := rfl /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ' a, β₁ a` and `Σ' a, β₂ a`. -/ @[simps apply] def psigmaCongrRight {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Σ' a, β₁ a) ≃ Σ' a, β₂ a where toFun a := ⟨a.1, F a.1 a.2⟩ invFun a := ⟨a.1, (F a.1).symm a.2⟩ left_inv | ⟨a, b⟩ => congr_arg (PSigma.mk a) <| symm_apply_apply (F a) b right_inv | ⟨a, b⟩ => congr_arg (PSigma.mk a) <| apply_symm_apply (F a) b -- Porting note (#10618): simp can now simplify the LHS, so I have removed `@[simp]` theorem psigmaCongrRight_trans {α} {β₁ β₂ β₃ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) (G : ∀ a, β₂ a ≃ β₃ a) : (psigmaCongrRight F).trans (psigmaCongrRight G) = psigmaCongrRight fun a => (F a).trans (G a) := rfl -- Porting note (#10618): simp can now simplify the LHS, so I have removed `@[simp]` theorem psigmaCongrRight_symm {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (psigmaCongrRight F).symm = psigmaCongrRight fun a => (F a).symm := rfl -- Porting note (#10618): simp can now prove this, so I have removed `@[simp]` theorem psigmaCongrRight_refl {α} {β : α → Sort*} : (psigmaCongrRight fun a => Equiv.refl (β a)) = Equiv.refl (Σ' a, β a) := rfl /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and `Σ a, β₂ a`. -/ @[simps apply] def sigmaCongrRight {α} {β₁ β₂ : α → Type*} (F : ∀ a, β₁ a ≃ β₂ a) : (Σ a, β₁ a) ≃ Σ a, β₂ a where toFun a := ⟨a.1, F a.1 a.2⟩ invFun a := ⟨a.1, (F a.1).symm a.2⟩ left_inv | ⟨a, b⟩ => congr_arg (Sigma.mk a) <| symm_apply_apply (F a) b right_inv | ⟨a, b⟩ => congr_arg (Sigma.mk a) <| apply_symm_apply (F a) b -- Porting note (#10618): simp can now simplify the LHS, so I have removed `@[simp]` theorem sigmaCongrRight_trans {α} {β₁ β₂ β₃ : α → Type*} (F : ∀ a, β₁ a ≃ β₂ a) (G : ∀ a, β₂ a ≃ β₃ a) : (sigmaCongrRight F).trans (sigmaCongrRight G) = sigmaCongrRight fun a => (F a).trans (G a) := rfl -- Porting note (#10618): simp can now simplify the LHS, so I have removed `@[simp]` theorem sigmaCongrRight_symm {α} {β₁ β₂ : α → Type*} (F : ∀ a, β₁ a ≃ β₂ a) : (sigmaCongrRight F).symm = sigmaCongrRight fun a => (F a).symm := rfl -- Porting note (#10618): simp can now prove this, so I have removed `@[simp]` theorem sigmaCongrRight_refl {α} {β : α → Type*} : (sigmaCongrRight fun a => Equiv.refl (β a)) = Equiv.refl (Σ a, β a) := rfl /-- A `PSigma` with `Prop` fibers is equivalent to the subtype. -/ def psigmaEquivSubtype {α : Type v} (P : α → Prop) : (Σ' i, P i) ≃ Subtype P where toFun x := ⟨x.1, x.2⟩ invFun x := ⟨x.1, x.2⟩ left_inv _ := rfl right_inv _ := rfl /-- A `Sigma` with `PLift` fibers is equivalent to the subtype. -/ def sigmaPLiftEquivSubtype {α : Type v} (P : α → Prop) : (Σ i, PLift (P i)) ≃ Subtype P := ((psigmaEquivSigma _).symm.trans (psigmaCongrRight fun _ => Equiv.plift)).trans (psigmaEquivSubtype P) /-- A `Sigma` with `fun i ↦ ULift (PLift (P i))` fibers is equivalent to `{ x // P x }`. Variant of `sigmaPLiftEquivSubtype`. -/ def sigmaULiftPLiftEquivSubtype {α : Type v} (P : α → Prop) : (Σ i, ULift (PLift (P i))) ≃ Subtype P := (sigmaCongrRight fun _ => Equiv.ulift).trans (sigmaPLiftEquivSubtype P) namespace Perm /-- A family of permutations `Π a, Perm (β a)` generates a permutation `Perm (Σ a, β₁ a)`. -/ abbrev sigmaCongrRight {α} {β : α → Sort _} (F : ∀ a, Perm (β a)) : Perm (Σ a, β a) := Equiv.sigmaCongrRight F @[simp] theorem sigmaCongrRight_trans {α} {β : α → Sort _} (F : ∀ a, Perm (β a)) (G : ∀ a, Perm (β a)) : (sigmaCongrRight F).trans (sigmaCongrRight G) = sigmaCongrRight fun a => (F a).trans (G a) := Equiv.sigmaCongrRight_trans F G @[simp] theorem sigmaCongrRight_symm {α} {β : α → Sort _} (F : ∀ a, Perm (β a)) : (sigmaCongrRight F).symm = sigmaCongrRight fun a => (F a).symm := Equiv.sigmaCongrRight_symm F @[simp] theorem sigmaCongrRight_refl {α} {β : α → Sort _} : (sigmaCongrRight fun a => Equiv.refl (β a)) = Equiv.refl (Σ a, β a) := Equiv.sigmaCongrRight_refl end Perm /-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/ @[simps apply] def sigmaCongrLeft {α₁ α₂ : Type*} {β : α₂ → Sort _} (e : α₁ ≃ α₂) : (Σ a : α₁, β (e a)) ≃ Σ a : α₂, β a where toFun a := ⟨e a.1, a.2⟩ invFun a := ⟨e.symm a.1, (e.right_inv' a.1).symm ▸ a.2⟩ -- Porting note: this was a pretty gnarly match already, and it got worse after porting left_inv := fun ⟨a, b⟩ => match (motive := ∀ a' (h : a' = a), Sigma.mk _ (congr_arg e h.symm ▸ b) = ⟨a, b⟩) e.symm (e a), e.left_inv a with | _, rfl => rfl right_inv := fun ⟨a, b⟩ => match (motive := ∀ a' (h : a' = a), Sigma.mk a' (h.symm ▸ b) = ⟨a, b⟩) e (e.symm a), e.apply_symm_apply _ with | _, rfl => rfl /-- Transporting a sigma type through an equivalence of the base -/ def sigmaCongrLeft' {α₁ α₂} {β : α₁ → Sort _} (f : α₁ ≃ α₂) : (Σ a : α₁, β a) ≃ Σ a : α₂, β (f.symm a) := (sigmaCongrLeft f.symm).symm /-- Transporting a sigma type through an equivalence of the base and a family of equivalences of matching fibers -/ def sigmaCongr {α₁ α₂} {β₁ : α₁ → Sort _} {β₂ : α₂ → Sort _} (f : α₁ ≃ α₂) (F : ∀ a, β₁ a ≃ β₂ (f a)) : Sigma β₁ ≃ Sigma β₂ := (sigmaCongrRight F).trans (sigmaCongrLeft f) /-- `Sigma` type with a constant fiber is equivalent to the product. -/ @[simps (config := { attrs := [`mfld_simps] }) apply symm_apply] def sigmaEquivProd (α β : Type*) : (Σ _ : α, β) ≃ α × β := ⟨fun a => ⟨a.1, a.2⟩, fun a => ⟨a.1, a.2⟩, fun ⟨_, _⟩ => rfl, fun ⟨_, _⟩ => rfl⟩ /-- If each fiber of a `Sigma` type is equivalent to a fixed type, then the sigma type is equivalent to the product. -/ def sigmaEquivProdOfEquiv {α β} {β₁ : α → Sort _} (F : ∀ a, β₁ a ≃ β) : Sigma β₁ ≃ α × β := (sigmaCongrRight F).trans (sigmaEquivProd α β) /-- Dependent product of types is associative up to an equivalence. -/ def sigmaAssoc {α : Type*} {β : α → Type*} (γ : ∀ a : α, β a → Type*) : (Σ ab : Σ a : α, β a, γ ab.1 ab.2) ≃ Σ a : α, Σ b : β a, γ a b where toFun x := ⟨x.1.1, ⟨x.1.2, x.2⟩⟩ invFun x := ⟨⟨x.1, x.2.1⟩, x.2.2⟩ left_inv _ := rfl right_inv _ := rfl end variable {p : α → Prop} {q : β → Prop} (e : α ≃ β) protected lemma forall_congr_right : (∀ a, q (e a)) ↔ ∀ b, q b := ⟨fun h a ↦ by simpa using h (e.symm a), fun h b ↦ h _⟩ protected lemma forall_congr_left : (∀ a, p a) ↔ ∀ b, p (e.symm b) := e.symm.forall_congr_right.symm @[deprecated (since := "2024-06-11")] alias forall_congr_left' := Equiv.forall_congr_left protected lemma forall_congr (h : ∀ a, p a ↔ q (e a)) : (∀ a, p a) ↔ ∀ b, q b := e.forall_congr_left.trans (by simp [h]) protected lemma forall_congr' (h : ∀ b, p (e.symm b) ↔ q b) : (∀ a, p a) ↔ ∀ b, q b := e.forall_congr_left.trans (by simp [h]) protected lemma exists_congr_right : (∃ a, q (e a)) ↔ ∃ b, q b := ⟨fun ⟨b, h⟩ ↦ ⟨_, h⟩, fun ⟨a, h⟩ ↦ ⟨e.symm a, by simpa using h⟩⟩ protected lemma exists_congr_left : (∃ a, p a) ↔ ∃ b, p (e.symm b) := e.symm.exists_congr_right.symm protected lemma exists_congr (h : ∀ a, p a ↔ q (e a)) : (∃ a, p a) ↔ ∃ b, q b := e.exists_congr_left.trans $ by simp [h] protected lemma exists_congr' (h : ∀ b, p (e.symm b) ↔ q b) : (∃ a, p a) ↔ ∃ b, q b := e.exists_congr_left.trans $ by simp [h] protected lemma existsUnique_congr_right : (∃! a, q (e a)) ↔ ∃! b, q b := e.exists_congr $ by simpa using fun _ _ ↦ e.forall_congr (by simp) protected lemma existsUnique_congr_left : (∃! a, p a) ↔ ∃! b, p (e.symm b) := e.symm.existsUnique_congr_right.symm @[deprecated (since := "2024-06-11")] alias exists_unique_congr_left := Equiv.existsUnique_congr_right @[deprecated (since := "2024-06-11")] alias exists_unique_congr_left' := Equiv.existsUnique_congr_left protected lemma existsUnique_congr (h : ∀ a, p a ↔ q (e a)) : (∃! a, p a) ↔ ∃! b, q b := e.existsUnique_congr_left.trans $ by simp [h] @[deprecated (since := "2024-06-11")] alias exists_unique_congr := Equiv.existsUnique_congr protected lemma existsUnique_congr' (h : ∀ b, p (e.symm b) ↔ q b) : (∃! a, p a) ↔ ∃! b, q b := e.existsUnique_congr_left.trans $ by simp [h] -- We next build some higher arity versions of `Equiv.forall_congr`. -- Although they appear to just be repeated applications of `Equiv.forall_congr`, -- unification of metavariables works better with these versions. -- In particular, they are necessary in `equiv_rw`. -- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics, -- it's rare to have axioms involving more than 3 elements at once.) protected theorem forall₂_congr {α₁ α₂ β₁ β₂ : Sort*} {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀ {x y}, p x y ↔ q (eα x) (eβ y)) : (∀ x y, p x y) ↔ ∀ x y, q x y := eα.forall_congr fun _ ↦ eβ.forall_congr $ @h _ protected theorem forall₂_congr' {α₁ α₂ β₁ β₂ : Sort*} {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀ {x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) : (∀ x y, p x y) ↔ ∀ x y, q x y := (Equiv.forall₂_congr eα.symm eβ.symm h.symm).symm protected theorem forall₃_congr {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀ {x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀ x y z, p x y z) ↔ ∀ x y z, q x y z := Equiv.forall₂_congr _ _ <| Equiv.forall_congr _ $ @h _ _ protected theorem forall₃_congr' {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀ {x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) : (∀ x y z, p x y z) ↔ ∀ x y z, q x y z := (Equiv.forall₃_congr eα.symm eβ.symm eγ.symm h.symm).symm /-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/ @[simps apply] noncomputable def ofBijective (f : α → β) (hf : Bijective f) : α ≃ β where toFun := f invFun := surjInv hf.surjective left_inv := leftInverse_surjInv hf right_inv := rightInverse_surjInv _ lemma ofBijective_apply_symm_apply (f : α → β) (hf : Bijective f) (x : β) : f ((ofBijective f hf).symm x) = x := (ofBijective f hf).apply_symm_apply x @[simp] lemma ofBijective_symm_apply_apply (f : α → β) (hf : Bijective f) (x : α) : (ofBijective f hf).symm (f x) = x := (ofBijective f hf).symm_apply_apply x end Equiv namespace Quot /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂)`. -/ protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀ a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : Quot ra ≃ Quot rb where toFun := Quot.map e fun a₁ a₂ => (eq a₁ a₂).1 invFun := Quot.map e.symm fun b₁ b₂ h => (eq (e.symm b₁) (e.symm b₂)).2 ((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h) left_inv := by rintro ⟨a⟩; simp only [Quot.map, Equiv.symm_apply_apply] right_inv := by rintro ⟨a⟩; simp only [Quot.map, Equiv.apply_symm_apply] @[simp] theorem congr_mk {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀ a₁ a₂ : α, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) (a : α) : Quot.congr e eq (Quot.mk ra a) = Quot.mk rb (e a) := rfl /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congrRight {r r' : α → α → Prop} (eq : ∀ a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : Quot r ≃ Quot r' := Quot.congr (Equiv.refl α) eq /-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α` by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/ protected def congrLeft {r : α → α → Prop} (e : α ≃ β) : Quot r ≃ Quot fun b b' => r (e.symm b) (e.symm b') := Quot.congr e fun _ _ => by simp only [e.symm_apply_apply] end Quot namespace Quotient /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂)`. -/ protected def congr {ra : Setoid α} {rb : Setoid β} (e : α ≃ β) (eq : ∀ a₁ a₂, @Setoid.r α ra a₁ a₂ ↔ @Setoid.r β rb (e a₁) (e a₂)) : Quotient ra ≃ Quotient rb := Quot.congr e eq @[simp] theorem congr_mk {ra : Setoid α} {rb : Setoid β} (e : α ≃ β) (eq : ∀ a₁ a₂ : α, Setoid.r a₁ a₂ ↔ Setoid.r (e a₁) (e a₂)) (a : α) : Quotient.congr e eq (Quotient.mk ra a) = Quotient.mk rb (e a) := rfl /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congrRight {r r' : Setoid α} (eq : ∀ a₁ a₂, @Setoid.r α r a₁ a₂ ↔ @Setoid.r α r' a₁ a₂) : Quotient r ≃ Quotient r' := Quot.congrRight eq end Quotient
Logic\Equiv\Embedding.lean
/- Copyright (c) 2021 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import Mathlib.Logic.Embedding.Set /-! # Equivalences on embeddings This file shows some advanced equivalences on embeddings, useful for constructing larger embeddings from smaller ones. -/ open Function.Embedding namespace Equiv /-- Embeddings from a sum type are equivalent to two separate embeddings with disjoint ranges. -/ def sumEmbeddingEquivProdEmbeddingDisjoint {α β γ : Type*} : (α ⊕ β ↪ γ) ≃ { f : (α ↪ γ) × (β ↪ γ) // Disjoint (Set.range f.1) (Set.range f.2) } where toFun f := ⟨(inl.trans f, inr.trans f), by rw [Set.disjoint_left] rintro _ ⟨a, h⟩ ⟨b, rfl⟩ simp only [trans_apply, inl_apply, inr_apply] at h have : Sum.inl a = Sum.inr b := f.injective h simp only at this⟩ invFun := fun ⟨⟨f, g⟩, disj⟩ => ⟨fun x => match x with | Sum.inl a => f a | Sum.inr b => g b, by rintro (a₁ | b₁) (a₂ | b₂) f_eq <;> simp only [Equiv.coe_fn_symm_mk, Sum.elim_inl, Sum.elim_inr] at f_eq · rw [f.injective f_eq] · exfalso exact disj.le_bot ⟨⟨a₁, f_eq⟩, ⟨b₂, by simp [f_eq]⟩⟩ · exfalso exact disj.le_bot ⟨⟨a₂, rfl⟩, ⟨b₁, f_eq⟩⟩ · rw [g.injective f_eq]⟩ left_inv f := by dsimp only ext x cases x <;> simp! right_inv := fun ⟨⟨f, g⟩, _⟩ => by simp only [Prod.mk.inj_iff] constructor /-- Embeddings whose range lies within a set are equivalent to embeddings to that set. This is `Function.Embedding.codRestrict` as an equiv. -/ def codRestrict (α : Type*) {β : Type*} (bs : Set β) : { f : α ↪ β // ∀ a, f a ∈ bs } ≃ (α ↪ bs) where toFun f := (f : α ↪ β).codRestrict bs f.prop invFun f := ⟨f.trans (Function.Embedding.subtype _), fun a => (f a).prop⟩ left_inv x := by ext; rfl right_inv x := by ext; rfl /-- Pairs of embeddings with disjoint ranges are equivalent to a dependent sum of embeddings, in which the second embedding cannot take values in the range of the first. -/ def prodEmbeddingDisjointEquivSigmaEmbeddingRestricted {α β γ : Type*} : { f : (α ↪ γ) × (β ↪ γ) // Disjoint (Set.range f.1) (Set.range f.2) } ≃ Σf : α ↪ γ, β ↪ ↥(Set.range f)ᶜ := (subtypeProdEquivSigmaSubtype fun (a : α ↪ γ) (b : β ↪ _) => Disjoint (Set.range a) (Set.range b)).trans <| Equiv.sigmaCongrRight fun a => (subtypeEquivProp <| by ext f rw [← Set.range_subset_iff, Set.subset_compl_iff_disjoint_right, disjoint_comm]).trans (codRestrict _ _) /-- A combination of the above results, allowing us to turn one embedding over a sum type into two dependent embeddings, the second of which avoids any members of the range of the first. This is helpful for constructing larger embeddings out of smaller ones. -/ def sumEmbeddingEquivSigmaEmbeddingRestricted {α β γ : Type*} : (α ⊕ β ↪ γ) ≃ Σf : α ↪ γ, β ↪ ↥(Set.range f)ᶜ := Equiv.trans sumEmbeddingEquivProdEmbeddingDisjoint prodEmbeddingDisjointEquivSigmaEmbeddingRestricted /-- Embeddings from a single-member type are equivalent to members of the target type. -/ def uniqueEmbeddingEquivResult {α β : Type*} [Unique α] : (α ↪ β) ≃ β where toFun f := f default invFun x := ⟨fun _ => x, fun _ _ _ => Subsingleton.elim _ _⟩ left_inv _ := by ext x simp_rw [Function.Embedding.coeFn_mk] congr 1 exact Subsingleton.elim _ x right_inv _ := by simp end Equiv
Logic\Equiv\Fin.lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.Data.Int.Defs import Mathlib.Data.Fin.VecNotation import Mathlib.Logic.Embedding.Set import Mathlib.Logic.Equiv.Option /-! # Equivalences for `Fin n` -/ assert_not_exists MonoidWithZero universe u variable {m n : ℕ} /-- Equivalence between `Fin 0` and `Empty`. -/ def finZeroEquiv : Fin 0 ≃ Empty := Equiv.equivEmpty _ /-- Equivalence between `Fin 0` and `PEmpty`. -/ def finZeroEquiv' : Fin 0 ≃ PEmpty.{u} := Equiv.equivPEmpty _ /-- Equivalence between `Fin 1` and `Unit`. -/ def finOneEquiv : Fin 1 ≃ Unit := Equiv.equivPUnit _ /-- Equivalence between `Fin 2` and `Bool`. -/ def finTwoEquiv : Fin 2 ≃ Bool where toFun := ![false, true] invFun b := b.casesOn 0 1 left_inv := Fin.forall_fin_two.2 <| by simp right_inv := Bool.forall_bool.2 <| by simp /-- `Π i : Fin 2, α i` is equivalent to `α 0 × α 1`. See also `finTwoArrowEquiv` for a non-dependent version and `prodEquivPiFinTwo` for a version with inputs `α β : Type u`. -/ @[simps (config := .asFn)] def piFinTwoEquiv (α : Fin 2 → Type u) : (∀ i, α i) ≃ α 0 × α 1 where toFun f := (f 0, f 1) invFun p := Fin.cons p.1 <| Fin.cons p.2 finZeroElim left_inv _ := funext <| Fin.forall_fin_two.2 ⟨rfl, rfl⟩ right_inv := fun _ => rfl theorem Fin.preimage_apply_01_prod {α : Fin 2 → Type u} (s : Set (α 0)) (t : Set (α 1)) : (fun f : ∀ i, α i => (f 0, f 1)) ⁻¹' s ×ˢ t = Set.pi Set.univ (Fin.cons s <| Fin.cons t finZeroElim) := by ext f simp [Fin.forall_fin_two] theorem Fin.preimage_apply_01_prod' {α : Type u} (s t : Set α) : (fun f : Fin 2 → α => (f 0, f 1)) ⁻¹' s ×ˢ t = Set.pi Set.univ ![s, t] := @Fin.preimage_apply_01_prod (fun _ => α) s t /-- A product space `α × β` is equivalent to the space `Π i : Fin 2, γ i`, where `γ = Fin.cons α (Fin.cons β finZeroElim)`. See also `piFinTwoEquiv` and `finTwoArrowEquiv`. -/ @[simps! (config := .asFn)] def prodEquivPiFinTwo (α β : Type u) : α × β ≃ ∀ i : Fin 2, ![α, β] i := (piFinTwoEquiv (Fin.cons α (Fin.cons β finZeroElim))).symm /-- The space of functions `Fin 2 → α` is equivalent to `α × α`. See also `piFinTwoEquiv` and `prodEquivPiFinTwo`. -/ @[simps (config := .asFn)] def finTwoArrowEquiv (α : Type*) : (Fin 2 → α) ≃ α × α := { piFinTwoEquiv fun _ => α with invFun := fun x => ![x.1, x.2] } /-- An equivalence that removes `i` and maps it to `none`. This is a version of `Fin.predAbove` that produces `Option (Fin n)` instead of mapping both `i.cast_succ` and `i.succ` to `i`. -/ def finSuccEquiv' (i : Fin (n + 1)) : Fin (n + 1) ≃ Option (Fin n) where toFun := i.insertNth none some invFun x := x.casesOn' i (Fin.succAbove i) left_inv x := Fin.succAboveCases i (by simp) (fun j => by simp) x right_inv x := by cases x <;> dsimp <;> simp @[simp] theorem finSuccEquiv'_at (i : Fin (n + 1)) : (finSuccEquiv' i) i = none := by simp [finSuccEquiv'] @[simp] theorem finSuccEquiv'_succAbove (i : Fin (n + 1)) (j : Fin n) : finSuccEquiv' i (i.succAbove j) = some j := @Fin.insertNth_apply_succAbove n (fun _ => Option (Fin n)) i _ _ _ theorem finSuccEquiv'_below {i : Fin (n + 1)} {m : Fin n} (h : Fin.castSucc m < i) : (finSuccEquiv' i) (Fin.castSucc m) = m := by rw [← Fin.succAbove_of_castSucc_lt _ _ h, finSuccEquiv'_succAbove] theorem finSuccEquiv'_above {i : Fin (n + 1)} {m : Fin n} (h : i ≤ Fin.castSucc m) : (finSuccEquiv' i) m.succ = some m := by rw [← Fin.succAbove_of_le_castSucc _ _ h, finSuccEquiv'_succAbove] @[simp] theorem finSuccEquiv'_symm_none (i : Fin (n + 1)) : (finSuccEquiv' i).symm none = i := rfl @[simp] theorem finSuccEquiv'_symm_some (i : Fin (n + 1)) (j : Fin n) : (finSuccEquiv' i).symm (some j) = i.succAbove j := rfl theorem finSuccEquiv'_symm_some_below {i : Fin (n + 1)} {m : Fin n} (h : Fin.castSucc m < i) : (finSuccEquiv' i).symm (some m) = Fin.castSucc m := Fin.succAbove_of_castSucc_lt i m h theorem finSuccEquiv'_symm_some_above {i : Fin (n + 1)} {m : Fin n} (h : i ≤ Fin.castSucc m) : (finSuccEquiv' i).symm (some m) = m.succ := Fin.succAbove_of_le_castSucc i m h theorem finSuccEquiv'_symm_coe_below {i : Fin (n + 1)} {m : Fin n} (h : Fin.castSucc m < i) : (finSuccEquiv' i).symm m = Fin.castSucc m := finSuccEquiv'_symm_some_below h theorem finSuccEquiv'_symm_coe_above {i : Fin (n + 1)} {m : Fin n} (h : i ≤ Fin.castSucc m) : (finSuccEquiv' i).symm m = m.succ := finSuccEquiv'_symm_some_above h /-- Equivalence between `Fin (n + 1)` and `Option (Fin n)`. This is a version of `Fin.pred` that produces `Option (Fin n)` instead of requiring a proof that the input is not `0`. -/ def finSuccEquiv (n : ℕ) : Fin (n + 1) ≃ Option (Fin n) := finSuccEquiv' 0 @[simp] theorem finSuccEquiv_zero : (finSuccEquiv n) 0 = none := rfl @[simp] theorem finSuccEquiv_succ (m : Fin n) : (finSuccEquiv n) m.succ = some m := finSuccEquiv'_above (Fin.zero_le _) @[simp] theorem finSuccEquiv_symm_none : (finSuccEquiv n).symm none = 0 := finSuccEquiv'_symm_none _ @[simp] theorem finSuccEquiv_symm_some (m : Fin n) : (finSuccEquiv n).symm (some m) = m.succ := congr_fun Fin.succAbove_zero m /-- The equiv version of `Fin.predAbove_zero`. -/ theorem finSuccEquiv'_zero : finSuccEquiv' (0 : Fin (n + 1)) = finSuccEquiv n := rfl theorem finSuccEquiv'_last_apply_castSucc (i : Fin n) : finSuccEquiv' (Fin.last n) (Fin.castSucc i) = i := by rw [← Fin.succAbove_last, finSuccEquiv'_succAbove] theorem finSuccEquiv'_last_apply {i : Fin (n + 1)} (h : i ≠ Fin.last n) : finSuccEquiv' (Fin.last n) i = Fin.castLT i (Fin.val_lt_last h) := by rcases Fin.exists_castSucc_eq.2 h with ⟨i, rfl⟩ rw [finSuccEquiv'_last_apply_castSucc] rfl theorem finSuccEquiv'_ne_last_apply {i j : Fin (n + 1)} (hi : i ≠ Fin.last n) (hj : j ≠ i) : finSuccEquiv' i j = (i.castLT (Fin.val_lt_last hi)).predAbove j := by rcases Fin.exists_succAbove_eq hj with ⟨j, rfl⟩ rcases Fin.exists_castSucc_eq.2 hi with ⟨i, rfl⟩ simp /-- `Fin.succAbove` as an order isomorphism between `Fin n` and `{x : Fin (n + 1) // x ≠ p}`. -/ def finSuccAboveEquiv (p : Fin (n + 1)) : Fin n ≃ { x : Fin (n + 1) // x ≠ p } := .optionSubtype p ⟨(finSuccEquiv' p).symm, rfl⟩ theorem finSuccAboveEquiv_apply (p : Fin (n + 1)) (i : Fin n) : finSuccAboveEquiv p i = ⟨p.succAbove i, p.succAbove_ne i⟩ := rfl theorem finSuccAboveEquiv_symm_apply_last (x : { x : Fin (n + 1) // x ≠ Fin.last n }) : (finSuccAboveEquiv (Fin.last n)).symm x = Fin.castLT x.1 (Fin.val_lt_last x.2) := by rw [← Option.some_inj] simpa [finSuccAboveEquiv] using finSuccEquiv'_last_apply x.property theorem finSuccAboveEquiv_symm_apply_ne_last {p : Fin (n + 1)} (h : p ≠ Fin.last n) (x : { x : Fin (n + 1) // x ≠ p }) : (finSuccAboveEquiv p).symm x = (p.castLT (Fin.val_lt_last h)).predAbove x := by rw [← Option.some_inj] simpa [finSuccAboveEquiv] using finSuccEquiv'_ne_last_apply h x.property /-- `Equiv` between `Fin (n + 1)` and `Option (Fin n)` sending `Fin.last n` to `none` -/ def finSuccEquivLast : Fin (n + 1) ≃ Option (Fin n) := finSuccEquiv' (Fin.last n) @[simp] theorem finSuccEquivLast_castSucc (i : Fin n) : finSuccEquivLast (Fin.castSucc i) = some i := finSuccEquiv'_below i.2 @[simp] theorem finSuccEquivLast_last : finSuccEquivLast (Fin.last n) = none := by simp [finSuccEquivLast] @[simp] theorem finSuccEquivLast_symm_some (i : Fin n) : finSuccEquivLast.symm (some i) = Fin.castSucc i := finSuccEquiv'_symm_some_below i.2 @[simp] theorem finSuccEquivLast_symm_none : finSuccEquivLast.symm none = Fin.last n := finSuccEquiv'_symm_none _ /-- Equivalence between `Π j : Fin (n + 1), α j` and `α i × Π j : Fin n, α (Fin.succAbove i j)`. -/ @[simps (config := .asFn)] def Equiv.piFinSuccAbove (α : Fin (n + 1) → Type u) (i : Fin (n + 1)) : (∀ j, α j) ≃ α i × ∀ j, α (i.succAbove j) where toFun f := (f i, i.removeNth f) invFun f := i.insertNth f.1 f.2 left_inv f := by simp right_inv f := by simp /-- Equivalence between `Fin (n + 1) → β` and `β × (Fin n → β)`. -/ @[simps! (config := .asFn)] def Equiv.piFinSucc (n : ℕ) (β : Type u) : (Fin (n + 1) → β) ≃ β × (Fin n → β) := Equiv.piFinSuccAbove (fun _ => β) 0 /-- An embedding `e : Fin (n+1) ↪ ι` corresponds to an embedding `f : Fin n ↪ ι` (corresponding the last `n` coordinates of `e`) together with a value not taken by `f` (corresponding to `e 0`). -/ def Equiv.embeddingFinSucc (n : ℕ) (ι : Type*) : (Fin (n+1) ↪ ι) ≃ (Σ (e : Fin n ↪ ι), {i // i ∉ Set.range e}) := ((finSuccEquiv n).embeddingCongr (Equiv.refl ι)).trans (Function.Embedding.optionEmbeddingEquiv (Fin n) ι) @[simp] lemma Equiv.embeddingFinSucc_fst {n : ℕ} {ι : Type*} (e : Fin (n+1) ↪ ι) : ((Equiv.embeddingFinSucc n ι e).1 : Fin n → ι) = e ∘ Fin.succ := rfl @[simp] lemma Equiv.embeddingFinSucc_snd {n : ℕ} {ι : Type*} (e : Fin (n+1) ↪ ι) : ((Equiv.embeddingFinSucc n ι e).2 : ι) = e 0 := rfl @[simp] lemma Equiv.coe_embeddingFinSucc_symm {n : ℕ} {ι : Type*} (f : Σ (e : Fin n ↪ ι), {i // i ∉ Set.range e}) : ((Equiv.embeddingFinSucc n ι).symm f : Fin (n + 1) → ι) = Fin.cons f.2.1 f.1 := by ext i exact Fin.cases rfl (fun j ↦ rfl) i /-- Equivalence between `Fin (n + 1) → β` and `β × (Fin n → β)` which separates out the last element of the tuple. -/ @[simps! (config := .asFn)] def Equiv.piFinCastSucc (n : ℕ) (β : Type u) : (Fin (n + 1) → β) ≃ β × (Fin n → β) := Equiv.piFinSuccAbove (fun _ => β) (.last _) /-- Equivalence between `Fin m ⊕ Fin n` and `Fin (m + n)` -/ def finSumFinEquiv : Fin m ⊕ Fin n ≃ Fin (m + n) where toFun := Sum.elim (Fin.castAdd n) (Fin.natAdd m) invFun i := @Fin.addCases m n (fun _ => Fin m ⊕ Fin n) Sum.inl Sum.inr i left_inv x := by cases' x with y y <;> dsimp <;> simp right_inv x := by refine Fin.addCases (fun i => ?_) (fun i => ?_) x <;> simp @[simp] theorem finSumFinEquiv_apply_left (i : Fin m) : (finSumFinEquiv (Sum.inl i) : Fin (m + n)) = Fin.castAdd n i := rfl @[simp] theorem finSumFinEquiv_apply_right (i : Fin n) : (finSumFinEquiv (Sum.inr i) : Fin (m + n)) = Fin.natAdd m i := rfl @[simp] theorem finSumFinEquiv_symm_apply_castAdd (x : Fin m) : finSumFinEquiv.symm (Fin.castAdd n x) = Sum.inl x := finSumFinEquiv.symm_apply_apply (Sum.inl x) @[simp] theorem finSumFinEquiv_symm_apply_natAdd (x : Fin n) : finSumFinEquiv.symm (Fin.natAdd m x) = Sum.inr x := finSumFinEquiv.symm_apply_apply (Sum.inr x) @[simp] theorem finSumFinEquiv_symm_last : finSumFinEquiv.symm (Fin.last n) = Sum.inr 0 := finSumFinEquiv_symm_apply_natAdd 0 /-- The equivalence between `Fin (m + n)` and `Fin (n + m)` which rotates by `n`. -/ def finAddFlip : Fin (m + n) ≃ Fin (n + m) := (finSumFinEquiv.symm.trans (Equiv.sumComm _ _)).trans finSumFinEquiv @[simp] theorem finAddFlip_apply_castAdd (k : Fin m) (n : ℕ) : finAddFlip (Fin.castAdd n k) = Fin.natAdd n k := by simp [finAddFlip] @[simp] theorem finAddFlip_apply_natAdd (k : Fin n) (m : ℕ) : finAddFlip (Fin.natAdd m k) = Fin.castAdd m k := by simp [finAddFlip] @[simp] theorem finAddFlip_apply_mk_left {k : ℕ} (h : k < m) (hk : k < m + n := Nat.lt_add_right n h) (hnk : n + k < n + m := Nat.add_lt_add_left h n) : finAddFlip (⟨k, hk⟩ : Fin (m + n)) = ⟨n + k, hnk⟩ := by convert finAddFlip_apply_castAdd ⟨k, h⟩ n @[simp] theorem finAddFlip_apply_mk_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) : finAddFlip (⟨k, h₂⟩ : Fin (m + n)) = ⟨k - m, by omega⟩ := by convert @finAddFlip_apply_natAdd n ⟨k - m, by omega⟩ m simp [Nat.add_sub_cancel' h₁] /-- Rotate `Fin n` one step to the right. -/ def finRotate : ∀ n, Equiv.Perm (Fin n) | 0 => Equiv.refl _ | n + 1 => finAddFlip.trans (finCongr (Nat.add_comm 1 n)) @[simp] lemma finRotate_zero : finRotate 0 = Equiv.refl _ := rfl lemma finRotate_succ (n : ℕ) : finRotate (n + 1) = finAddFlip.trans (finCongr (Nat.add_comm 1 n)) := rfl theorem finRotate_of_lt {k : ℕ} (h : k < n) : finRotate (n + 1) ⟨k, h.trans_le n.le_succ⟩ = ⟨k + 1, Nat.succ_lt_succ h⟩ := by ext dsimp [finRotate_succ] simp [finAddFlip_apply_mk_left h, Nat.add_comm] theorem finRotate_last' : finRotate (n + 1) ⟨n, by omega⟩ = ⟨0, Nat.zero_lt_succ _⟩ := by dsimp [finRotate_succ] rw [finAddFlip_apply_mk_right le_rfl] simp theorem finRotate_last : finRotate (n + 1) (Fin.last _) = 0 := finRotate_last' theorem Fin.snoc_eq_cons_rotate {α : Type*} (v : Fin n → α) (a : α) : @Fin.snoc _ (fun _ => α) v a = fun i => @Fin.cons _ (fun _ => α) a v (finRotate _ i) := by ext ⟨i, h⟩ by_cases h' : i < n · rw [finRotate_of_lt h', Fin.snoc, Fin.cons, dif_pos h'] rfl · have h'' : n = i := by simp only [not_lt] at h' exact (Nat.eq_of_le_of_lt_succ h' h).symm subst h'' rw [finRotate_last', Fin.snoc, Fin.cons, dif_neg (lt_irrefl _)] rfl @[simp] theorem finRotate_one : finRotate 1 = Equiv.refl _ := Subsingleton.elim _ _ @[simp] theorem finRotate_succ_apply (i : Fin (n + 1)) : finRotate (n + 1) i = i + 1 := by cases n · exact @Subsingleton.elim (Fin 1) _ _ _ obtain rfl | h := Fin.eq_or_lt_of_le i.le_last · simp [finRotate_last] · cases i simp only [Fin.lt_iff_val_lt_val, Fin.val_last, Fin.val_mk] at h simp [finRotate_of_lt h, Fin.ext_iff, Fin.add_def, Nat.mod_eq_of_lt (Nat.succ_lt_succ h)] -- Porting note: was a @[simp] theorem finRotate_apply_zero : finRotate n.succ 0 = 1 := by rw [finRotate_succ_apply, Fin.zero_add] theorem coe_finRotate_of_ne_last {i : Fin n.succ} (h : i ≠ Fin.last n) : (finRotate (n + 1) i : ℕ) = i + 1 := by rw [finRotate_succ_apply] have : (i : ℕ) < n := Fin.val_lt_last h exact Fin.val_add_one_of_lt this theorem coe_finRotate (i : Fin n.succ) : (finRotate n.succ i : ℕ) = if i = Fin.last n then (0 : ℕ) else i + 1 := by rw [finRotate_succ_apply, Fin.val_add_one i] /-- Equivalence between `Fin m × Fin n` and `Fin (m * n)` -/ @[simps] def finProdFinEquiv : Fin m × Fin n ≃ Fin (m * n) where toFun x := ⟨x.2 + n * x.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 := by ac_rfl _ ≤ x.1.1 * n + n := Nat.add_le_add_left x.2.2 _ _ = (x.1.1 + 1) * n := Eq.symm <| Nat.succ_mul _ _ _ ≤ m * n := Nat.mul_le_mul_right _ x.1.2 ⟩ invFun x := (x.divNat, x.modNat) left_inv := fun ⟨x, y⟩ => have H : 0 < n := Nat.pos_of_ne_zero fun H => Nat.not_lt_zero y.1 <| H ▸ y.2 Prod.ext (Fin.eq_of_val_eq <| calc (y.1 + n * x.1) / n = y.1 / n + x.1 := Nat.add_mul_div_left _ _ H _ = 0 + x.1 := by rw [Nat.div_eq_of_lt y.2] _ = x.1 := Nat.zero_add x.1 ) (Fin.eq_of_val_eq <| calc (y.1 + n * x.1) % n = y.1 % n := Nat.add_mul_mod_self_left _ _ _ _ = y.1 := Nat.mod_eq_of_lt y.2 ) right_inv x := Fin.eq_of_val_eq <| Nat.mod_add_div _ _ /-- The equivalence induced by `a ↦ (a / n, a % n)` for nonzero `n`. This is like `finProdFinEquiv.symm` but with `m` infinite. See `Nat.div_mod_unique` for a similar propositional statement. -/ @[simps] def Nat.divModEquiv (n : ℕ) [NeZero n] : ℕ ≃ ℕ × Fin n where toFun a := (a / n, ↑a) invFun p := p.1 * n + ↑p.2 -- TODO: is there a canonical order of `*` and `+` here? left_inv a := Nat.div_add_mod' _ _ right_inv p := by refine Prod.ext ?_ (Fin.ext <| Nat.mul_add_mod_of_lt p.2.is_lt) dsimp only rw [Nat.add_comm, Nat.add_mul_div_right _ _ n.pos_of_neZero, Nat.div_eq_of_lt p.2.is_lt, Nat.zero_add] /-- The equivalence induced by `a ↦ (a / n, a % n)` for nonzero `n`. See `Int.ediv_emod_unique` for a similar propositional statement. -/ @[simps] def Int.divModEquiv (n : ℕ) [NeZero n] : ℤ ≃ ℤ × Fin n where -- TODO: could cast from int directly if we import `Data.ZMod.Defs`, though there are few lemmas -- about that coercion. toFun a := (a / n, ↑(a.natMod n)) invFun p := p.1 * n + ↑p.2 left_inv a := by simp_rw [Fin.coe_ofNat_eq_mod, natCast_mod, natMod, toNat_of_nonneg (emod_nonneg _ <| natCast_eq_zero.not.2 (NeZero.ne n)), emod_emod, ediv_add_emod'] right_inv := fun ⟨q, r, hrn⟩ => by simp only [Fin.val_mk, Prod.mk.inj_iff, Fin.ext_iff] obtain ⟨h1, h2⟩ := Int.natCast_nonneg r, Int.ofNat_lt.2 hrn rw [Int.add_comm, add_mul_ediv_right _ _ (natCast_eq_zero.not.2 (NeZero.ne n)), ediv_eq_zero_of_lt h1 h2, natMod, add_mul_emod_self, emod_eq_of_lt h1 h2, toNat_natCast] exact ⟨q.zero_add, Fin.val_cast_of_lt hrn⟩ /-- Promote a `Fin n` into a larger `Fin m`, as a subtype where the underlying values are retained. This is the `Equiv` version of `Fin.castLE`. -/ @[simps apply symm_apply] def Fin.castLEquiv {n m : ℕ} (h : n ≤ m) : Fin n ≃ { i : Fin m // (i : ℕ) < n } where toFun i := ⟨Fin.castLE h i, by simp⟩ invFun i := ⟨i, i.prop⟩ left_inv _ := by simp right_inv _ := by simp /-- `Fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : Subsingleton (Fin 0) := finZeroEquiv.subsingleton /-- `Fin 1` is a subsingleton. -/ instance subsingleton_fin_one : Subsingleton (Fin 1) := finOneEquiv.subsingleton
Logic\Equiv\Fintype.lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import Mathlib.Data.Fintype.Basic import Mathlib.GroupTheory.Perm.Sign import Mathlib.Logic.Equiv.Defs /-! # Equivalence between fintypes This file contains some basic results on equivalences where one or both sides of the equivalence are `Fintype`s. # Main definitions - `Function.Embedding.toEquivRange`: computably turn an embedding of a fintype into an `Equiv` of the domain to its range - `Equiv.Perm.viaFintypeEmbedding : Perm α → (α ↪ β) → Perm β` extends the domain of a permutation, fixing everything outside the range of the embedding # Implementation details - `Function.Embedding.toEquivRange` uses a computable inverse, but one that has poor computational performance, since it operates by exhaustive search over the input `Fintype`s. -/ section Fintype variable {α β : Type*} [Fintype α] [DecidableEq β] (e : Equiv.Perm α) (f : α ↪ β) /-- Computably turn an embedding `f : α ↪ β` into an equiv `α ≃ Set.range f`, if `α` is a `Fintype`. Has poor computational performance, due to exhaustive searching in constructed inverse. When a better inverse is known, use `Equiv.ofLeftInverse'` or `Equiv.ofLeftInverse` instead. This is the computable version of `Equiv.ofInjective`. -/ def Function.Embedding.toEquivRange : α ≃ Set.range f := ⟨fun a => ⟨f a, Set.mem_range_self a⟩, f.invOfMemRange, fun _ => by simp, fun _ => by simp⟩ @[simp] theorem Function.Embedding.toEquivRange_apply (a : α) : f.toEquivRange a = ⟨f a, Set.mem_range_self a⟩ := rfl @[simp] theorem Function.Embedding.toEquivRange_symm_apply_self (a : α) : f.toEquivRange.symm ⟨f a, Set.mem_range_self a⟩ = a := by simp [Equiv.symm_apply_eq] theorem Function.Embedding.toEquivRange_eq_ofInjective : f.toEquivRange = Equiv.ofInjective f f.injective := by ext simp /-- Extend the domain of `e : Equiv.Perm α`, mapping it through `f : α ↪ β`. Everything outside of `Set.range f` is kept fixed. Has poor computational performance, due to exhaustive searching in constructed inverse due to using `Function.Embedding.toEquivRange`. When a better `α ≃ Set.range f` is known, use `Equiv.Perm.viaSetRange`. When `[Fintype α]` is not available, a noncomputable version is available as `Equiv.Perm.viaEmbedding`. -/ def Equiv.Perm.viaFintypeEmbedding : Equiv.Perm β := e.extendDomain f.toEquivRange @[simp] theorem Equiv.Perm.viaFintypeEmbedding_apply_image (a : α) : e.viaFintypeEmbedding f (f a) = f (e a) := by rw [Equiv.Perm.viaFintypeEmbedding] convert Equiv.Perm.extendDomain_apply_image e (Function.Embedding.toEquivRange f) a theorem Equiv.Perm.viaFintypeEmbedding_apply_mem_range {b : β} (h : b ∈ Set.range f) : e.viaFintypeEmbedding f b = f (e (f.invOfMemRange ⟨b, h⟩)) := by simp only [viaFintypeEmbedding, Function.Embedding.invOfMemRange] rw [Equiv.Perm.extendDomain_apply_subtype] congr theorem Equiv.Perm.viaFintypeEmbedding_apply_not_mem_range {b : β} (h : b ∉ Set.range f) : e.viaFintypeEmbedding f b = b := by rwa [Equiv.Perm.viaFintypeEmbedding, Equiv.Perm.extendDomain_apply_not_subtype] @[simp] theorem Equiv.Perm.viaFintypeEmbedding_sign [DecidableEq α] [Fintype β] : Equiv.Perm.sign (e.viaFintypeEmbedding f) = Equiv.Perm.sign e := by simp [Equiv.Perm.viaFintypeEmbedding] end Fintype namespace Equiv variable {α β : Type*} [Finite α] /-- If `e` is an equivalence between two subtypes of a finite type `α`, `e.toCompl` is an equivalence between the complement of those subtypes. See also `Equiv.compl`, for a computable version when a term of type `{e' : α ≃ α // ∀ x : {x // p x}, e' x = e x}` is known. -/ noncomputable def toCompl {p q : α → Prop} (e : { x // p x } ≃ { x // q x }) : { x // ¬p x } ≃ { x // ¬q x } := by apply Classical.choice cases nonempty_fintype α classical exact Fintype.card_eq.mp <| Fintype.card_compl_eq_card_compl _ _ <| Fintype.card_congr e variable {p q : α → Prop} [DecidablePred p] [DecidablePred q] /-- If `e` is an equivalence between two subtypes of a fintype `α`, `e.extendSubtype` is a permutation of `α` acting like `e` on the subtypes and doing something arbitrary outside. Note that when `p = q`, `Equiv.Perm.subtypeCongr e (Equiv.refl _)` can be used instead. -/ noncomputable abbrev extendSubtype (e : { x // p x } ≃ { x // q x }) : Perm α := subtypeCongr e e.toCompl theorem extendSubtype_apply_of_mem (e : { x // p x } ≃ { x // q x }) (x) (hx : p x) : e.extendSubtype x = e ⟨x, hx⟩ := by dsimp only [extendSubtype] simp only [subtypeCongr, Equiv.trans_apply, Equiv.sumCongr_apply] rw [sumCompl_apply_symm_of_pos _ _ hx, Sum.map_inl, sumCompl_apply_inl] theorem extendSubtype_mem (e : { x // p x } ≃ { x // q x }) (x) (hx : p x) : q (e.extendSubtype x) := by convert (e ⟨x, hx⟩).2 rw [e.extendSubtype_apply_of_mem _ hx] theorem extendSubtype_apply_of_not_mem (e : { x // p x } ≃ { x // q x }) (x) (hx : ¬p x) : e.extendSubtype x = e.toCompl ⟨x, hx⟩ := by dsimp only [extendSubtype] simp only [subtypeCongr, Equiv.trans_apply, Equiv.sumCongr_apply] rw [sumCompl_apply_symm_of_neg _ _ hx, Sum.map_inr, sumCompl_apply_inr] theorem extendSubtype_not_mem (e : { x // p x } ≃ { x // q x }) (x) (hx : ¬p x) : ¬q (e.extendSubtype x) := by convert (e.toCompl ⟨x, hx⟩).2 rw [e.extendSubtype_apply_of_not_mem _ hx] end Equiv
Logic\Equiv\Functor.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Simon Hudon, Scott Morrison -/ import Mathlib.Control.Bifunctor import Mathlib.Logic.Equiv.Defs /-! # Functor and bifunctors can be applied to `Equiv`s. We define ```lean def Functor.mapEquiv (f : Type u → Type v) [Functor f] [LawfulFunctor f] : α ≃ β → f α ≃ f β ``` and ```lean def Bifunctor.mapEquiv (F : Type u → Type v → Type w) [Bifunctor F] [LawfulBifunctor F] : α ≃ β → α' ≃ β' → F α α' ≃ F β β' ``` -/ universe u v w variable {α β : Type u} open Equiv namespace Functor variable (f : Type u → Type v) [Functor f] [LawfulFunctor f] /-- Apply a functor to an `Equiv`. -/ def mapEquiv (h : α ≃ β) : f α ≃ f β where toFun := map h invFun := map h.symm left_inv x := by simp [map_map] right_inv x := by simp [map_map] @[simp] theorem mapEquiv_apply (h : α ≃ β) (x : f α) : (mapEquiv f h : f α ≃ f β) x = map h x := rfl @[simp] theorem mapEquiv_symm_apply (h : α ≃ β) (y : f β) : (mapEquiv f h : f α ≃ f β).symm y = map h.symm y := rfl @[simp] theorem mapEquiv_refl : mapEquiv f (Equiv.refl α) = Equiv.refl (f α) := by ext x simp only [mapEquiv_apply, refl_apply] exact LawfulFunctor.id_map x end Functor namespace Bifunctor variable {α' β' : Type v} (F : Type u → Type v → Type w) [Bifunctor F] [LawfulBifunctor F] /-- Apply a bifunctor to a pair of `Equiv`s. -/ def mapEquiv (h : α ≃ β) (h' : α' ≃ β') : F α α' ≃ F β β' where toFun := bimap h h' invFun := bimap h.symm h'.symm left_inv x := by simp [bimap_bimap, id_bimap] right_inv x := by simp [bimap_bimap, id_bimap] @[simp] theorem mapEquiv_apply (h : α ≃ β) (h' : α' ≃ β') (x : F α α') : (mapEquiv F h h' : F α α' ≃ F β β') x = bimap h h' x := rfl @[simp] theorem mapEquiv_symm_apply (h : α ≃ β) (h' : α' ≃ β') (y : F β β') : (mapEquiv F h h' : F α α' ≃ F β β').symm y = bimap h.symm h'.symm y := rfl @[simp] theorem mapEquiv_refl_refl : mapEquiv F (Equiv.refl α) (Equiv.refl α') = Equiv.refl (F α α') := by ext x simp [id_bimap] end Bifunctor
Logic\Equiv\List.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.Data.Finset.Sort import Mathlib.Data.Vector.Basic import Mathlib.Logic.Denumerable /-! # Equivalences involving `List`-like types This file defines some additional constructive equivalences using `Encodable` and the pairing function on `ℕ`. -/ open Mathlib (Vector) open Nat List namespace Encodable variable {α : Type*} section List variable [Encodable α] /-- Explicit encoding function for `List α` -/ def encodeList : List α → ℕ | [] => 0 | a :: l => succ (pair (encode a) (encodeList l)) /-- Explicit decoding function for `List α` -/ def decodeList : ℕ → Option (List α) | 0 => some [] | succ v => match unpair v, unpair_right_le v with | (v₁, v₂), h => have : v₂ < succ v := lt_succ_of_le h (· :: ·) <$> decode (α := α) v₁ <*> decodeList v₂ /-- If `α` is encodable, then so is `List α`. This uses the `pair` and `unpair` functions from `Data.Nat.Pairing`. -/ instance _root_.List.encodable : Encodable (List α) := ⟨encodeList, decodeList, fun l => by induction' l with a l IH <;> simp [encodeList, decodeList, unpair_pair, encodek, *]⟩ instance _root_.List.countable {α : Type*} [Countable α] : Countable (List α) := by haveI := Encodable.ofCountable α infer_instance @[simp] theorem encode_list_nil : encode (@nil α) = 0 := rfl @[simp] theorem encode_list_cons (a : α) (l : List α) : encode (a :: l) = succ (pair (encode a) (encode l)) := rfl @[simp] theorem decode_list_zero : decode (α := List α) 0 = some [] := show decodeList 0 = some [] by rw [decodeList] @[simp, nolint unusedHavesSuffices] -- Porting note: false positive theorem decode_list_succ (v : ℕ) : decode (α := List α) (succ v) = (· :: ·) <$> decode (α := α) v.unpair.1 <*> decode (α := List α) v.unpair.2 := show decodeList (succ v) = _ by cases' e : unpair v with v₁ v₂ simp [decodeList, e]; rfl theorem length_le_encode : ∀ l : List α, length l ≤ encode l | [] => Nat.zero_le _ | _ :: l => succ_le_succ <| (length_le_encode l).trans (right_le_pair _ _) end List section Finset variable [Encodable α] private def enle : α → α → Prop := encode ⁻¹'o (· ≤ ·) private theorem enle.isLinearOrder : IsLinearOrder α enle := (RelEmbedding.preimage ⟨encode, encode_injective⟩ (· ≤ ·)).isLinearOrder private def decidable_enle (a b : α) : Decidable (enle a b) := by unfold enle Order.Preimage infer_instance attribute [local instance] enle.isLinearOrder decidable_enle /-- Explicit encoding function for `Multiset α` -/ def encodeMultiset (s : Multiset α) : ℕ := encode (s.sort enle) /-- Explicit decoding function for `Multiset α` -/ def decodeMultiset (n : ℕ) : Option (Multiset α) := ((↑) : List α → Multiset α) <$> decode (α := List α) n /-- If `α` is encodable, then so is `Multiset α`. -/ instance _root_.Multiset.encodable : Encodable (Multiset α) := ⟨encodeMultiset, decodeMultiset, fun s => by simp [encodeMultiset, decodeMultiset, encodek]⟩ /-- If `α` is countable, then so is `Multiset α`. -/ instance _root_.Multiset.countable {α : Type*} [Countable α] : Countable (Multiset α) := Quotient.countable end Finset /-- A listable type with decidable equality is encodable. -/ def encodableOfList [DecidableEq α] (l : List α) (H : ∀ x, x ∈ l) : Encodable α := ⟨fun a => indexOf a l, l.get?, fun _ => indexOf_get? (H _)⟩ /-- A finite type is encodable. Because the encoding is not unique, we wrap it in `Trunc` to preserve computability. -/ def _root_.Fintype.truncEncodable (α : Type*) [DecidableEq α] [Fintype α] : Trunc (Encodable α) := @Quot.recOnSubsingleton' _ _ (fun s : Multiset α => (∀ x : α, x ∈ s) → Trunc (Encodable α)) _ Finset.univ.1 (fun l H => Trunc.mk <| encodableOfList l H) Finset.mem_univ /-- A noncomputable way to arbitrarily choose an ordering on a finite type. It is not made into a global instance, since it involves an arbitrary choice. This can be locally made into an instance with `attribute [local instance] Fintype.toEncodable`. -/ noncomputable def _root_.Fintype.toEncodable (α : Type*) [Fintype α] : Encodable α := by classical exact (Fintype.truncEncodable α).out /-- If `α` is encodable, then so is `Vector α n`. -/ instance _root_.Vector.encodable [Encodable α] {n} : Encodable (Vector α n) := Subtype.encodable /-- If `α` is countable, then so is `Vector α n`. -/ instance _root_.Vector.countable [Countable α] {n} : Countable (Vector α n) := Subtype.countable /-- If `α` is encodable, then so is `Fin n → α`. -/ instance finArrow [Encodable α] {n} : Encodable (Fin n → α) := ofEquiv _ (Equiv.vectorEquivFin _ _).symm instance finPi (n) (π : Fin n → Type*) [∀ i, Encodable (π i)] : Encodable (∀ i, π i) := ofEquiv _ (Equiv.piEquivSubtypeSigma (Fin n) π) /-- If `α` is encodable, then so is `Finset α`. -/ instance _root_.Finset.encodable [Encodable α] : Encodable (Finset α) := haveI := decidableEqOfEncodable α ofEquiv { s : Multiset α // s.Nodup } ⟨fun ⟨a, b⟩ => ⟨a, b⟩, fun ⟨a, b⟩ => ⟨a, b⟩, fun ⟨_, _⟩ => rfl, fun ⟨_, _⟩ => rfl⟩ /-- If `α` is countable, then so is `Finset α`. -/ instance _root_.Finset.countable [Countable α] : Countable (Finset α) := Finset.val_injective.countable -- TODO: Unify with `fintypePi` and find a better name /-- When `α` is finite and `β` is encodable, `α → β` is encodable too. Because the encoding is not unique, we wrap it in `Trunc` to preserve computability. -/ def fintypeArrow (α : Type*) (β : Type*) [DecidableEq α] [Fintype α] [Encodable β] : Trunc (Encodable (α → β)) := (Fintype.truncEquivFin α).map fun f => Encodable.ofEquiv (Fin (Fintype.card α) → β) <| Equiv.arrowCongr f (Equiv.refl _) /-- When `α` is finite and all `π a` are encodable, `Π a, π a` is encodable too. Because the encoding is not unique, we wrap it in `Trunc` to preserve computability. -/ def fintypePi (α : Type*) (π : α → Type*) [DecidableEq α] [Fintype α] [∀ a, Encodable (π a)] : Trunc (Encodable (∀ a, π a)) := (Fintype.truncEncodable α).bind fun a => (@fintypeArrow α (Σa, π a) _ _ (@Sigma.encodable _ _ a _)).bind fun f => Trunc.mk <| @Encodable.ofEquiv _ _ (@Subtype.encodable _ _ f _) (Equiv.piEquivSubtypeSigma α π) /-- The elements of a `Fintype` as a sorted list. -/ def sortedUniv (α) [Fintype α] [Encodable α] : List α := Finset.univ.sort (Encodable.encode' α ⁻¹'o (· ≤ ·)) @[simp] theorem mem_sortedUniv {α} [Fintype α] [Encodable α] (x : α) : x ∈ sortedUniv α := (Finset.mem_sort _).2 (Finset.mem_univ _) @[simp] theorem length_sortedUniv (α) [Fintype α] [Encodable α] : (sortedUniv α).length = Fintype.card α := Finset.length_sort _ @[simp] theorem sortedUniv_nodup (α) [Fintype α] [Encodable α] : (sortedUniv α).Nodup := Finset.sort_nodup _ _ @[simp] theorem sortedUniv_toFinset (α) [Fintype α] [Encodable α] [DecidableEq α] : (sortedUniv α).toFinset = Finset.univ := Finset.sort_toFinset _ _ /-- An encodable `Fintype` is equivalent to the same size `Fin`. -/ def fintypeEquivFin {α} [Fintype α] [Encodable α] : α ≃ Fin (Fintype.card α) := haveI : DecidableEq α := Encodable.decidableEqOfEncodable _ -- Porting note: used the `trans` tactic ((sortedUniv_nodup α).getEquivOfForallMemList _ mem_sortedUniv).symm.trans <| Equiv.cast (congr_arg _ (length_sortedUniv α)) /-- If `α` and `β` are encodable and `α` is a fintype, then `α → β` is encodable as well. -/ instance fintypeArrowOfEncodable {α β : Type*} [Encodable α] [Fintype α] [Encodable β] : Encodable (α → β) := ofEquiv (Fin (Fintype.card α) → β) <| Equiv.arrowCongr fintypeEquivFin (Equiv.refl _) end Encodable namespace Denumerable variable {α : Type*} {β : Type*} [Denumerable α] [Denumerable β] open Encodable section List @[nolint unusedHavesSuffices] -- Porting note: false positive theorem denumerable_list_aux : ∀ n : ℕ, ∃ a ∈ @decodeList α _ n, encodeList a = n | 0 => by rw [decodeList]; exact ⟨_, rfl, rfl⟩ | succ v => by cases' e : unpair v with v₁ v₂ have h := unpair_right_le v rw [e] at h rcases have : v₂ < succ v := lt_succ_of_le h denumerable_list_aux v₂ with ⟨a, h₁, h₂⟩ rw [Option.mem_def] at h₁ use ofNat α v₁ :: a simp [decodeList, e, h₂, h₁, encodeList, pair_unpair' e] /-- If `α` is denumerable, then so is `List α`. -/ instance denumerableList : Denumerable (List α) := ⟨denumerable_list_aux⟩ @[simp] theorem list_ofNat_zero : ofNat (List α) 0 = [] := by rw [← @encode_list_nil α, ofNat_encode] @[simp, nolint unusedHavesSuffices] -- Porting note: false positive theorem list_ofNat_succ (v : ℕ) : ofNat (List α) (succ v) = ofNat α v.unpair.1 :: ofNat (List α) v.unpair.2 := ofNat_of_decode <| show decodeList (succ v) = _ by cases' e : unpair v with v₁ v₂ simp [decodeList, e] rw [show decodeList v₂ = decode (α := List α) v₂ from rfl, decode_eq_ofNat, Option.seq_some] end List section Multiset /-- Outputs the list of differences of the input list, that is `lower [a₁, a₂, ...] n = [a₁ - n, a₂ - a₁, ...]` -/ def lower : List ℕ → ℕ → List ℕ | [], _ => [] | m :: l, n => (m - n) :: lower l m /-- Outputs the list of partial sums of the input list, that is `raise [a₁, a₂, ...] n = [n + a₁, n + a₁ + a₂, ...]` -/ def raise : List ℕ → ℕ → List ℕ | [], _ => [] | m :: l, n => (m + n) :: raise l (m + n) theorem lower_raise : ∀ l n, lower (raise l n) n = l | [], n => rfl | m :: l, n => by rw [raise, lower, Nat.add_sub_cancel_right, lower_raise l] theorem raise_lower : ∀ {l n}, List.Sorted (· ≤ ·) (n :: l) → raise (lower l n) n = l | [], n, _ => rfl | m :: l, n, h => by have : n ≤ m := List.rel_of_sorted_cons h _ (l.mem_cons_self _) simp [raise, lower, Nat.sub_add_cancel this, raise_lower h.of_cons] theorem raise_chain : ∀ l n, List.Chain (· ≤ ·) n (raise l n) | [], _ => List.Chain.nil | _ :: _, _ => List.Chain.cons (Nat.le_add_left _ _) (raise_chain _ _) /-- `raise l n` is a non-decreasing sequence. -/ theorem raise_sorted : ∀ l n, List.Sorted (· ≤ ·) (raise l n) | [], _ => List.sorted_nil | _ :: _, _ => List.chain_iff_pairwise.1 (raise_chain _ _) /-- If `α` is denumerable, then so is `Multiset α`. Warning: this is *not* the same encoding as used in `Multiset.encodable`. -/ instance multiset : Denumerable (Multiset α) := mk' ⟨fun s : Multiset α => encode <| lower ((s.map encode).sort (· ≤ ·)) 0, fun n => Multiset.map (ofNat α) (raise (ofNat (List ℕ) n) 0), fun s => by have := raise_lower (List.sorted_cons.2 ⟨fun n _ => Nat.zero_le n, (s.map encode).sort_sorted _⟩) simp [-Multiset.map_coe, this], fun n => by simp [-Multiset.map_coe, List.mergeSort_eq_self _ (raise_sorted _ _), lower_raise]⟩ end Multiset section Finset /-- Outputs the list of differences minus one of the input list, that is `lower' [a₁, a₂, a₃, ...] n = [a₁ - n, a₂ - a₁ - 1, a₃ - a₂ - 1, ...]`. -/ def lower' : List ℕ → ℕ → List ℕ | [], _ => [] | m :: l, n => (m - n) :: lower' l (m + 1) /-- Outputs the list of partial sums plus one of the input list, that is `raise [a₁, a₂, a₃, ...] n = [n + a₁, n + a₁ + a₂ + 1, n + a₁ + a₂ + a₃ + 2, ...]`. Adding one each time ensures the elements are distinct. -/ def raise' : List ℕ → ℕ → List ℕ | [], _ => [] | m :: l, n => (m + n) :: raise' l (m + n + 1) theorem lower_raise' : ∀ l n, lower' (raise' l n) n = l | [], n => rfl | m :: l, n => by simp [raise', lower', add_tsub_cancel_right, lower_raise'] theorem raise_lower' : ∀ {l n}, (∀ m ∈ l, n ≤ m) → List.Sorted (· < ·) l → raise' (lower' l n) n = l | [], n, _, _ => rfl | m :: l, n, h₁, h₂ => by have : n ≤ m := h₁ _ (l.mem_cons_self _) simp [raise', lower', Nat.sub_add_cancel this, raise_lower' (List.rel_of_sorted_cons h₂ : ∀ a ∈ l, m < a) h₂.of_cons] theorem raise'_chain : ∀ (l) {m n}, m < n → List.Chain (· < ·) m (raise' l n) | [], _, _, _ => List.Chain.nil | _ :: _, _, _, h => List.Chain.cons (lt_of_lt_of_le h (Nat.le_add_left _ _)) (raise'_chain _ (lt_succ_self _)) /-- `raise' l n` is a strictly increasing sequence. -/ theorem raise'_sorted : ∀ l n, List.Sorted (· < ·) (raise' l n) | [], _ => List.sorted_nil | _ :: _, _ => List.chain_iff_pairwise.1 (raise'_chain _ (lt_succ_self _)) /-- Makes `raise' l n` into a finset. Elements are distinct thanks to `raise'_sorted`. -/ def raise'Finset (l : List ℕ) (n : ℕ) : Finset ℕ := ⟨raise' l n, (raise'_sorted _ _).imp (@ne_of_lt _ _)⟩ /-- If `α` is denumerable, then so is `Finset α`. Warning: this is *not* the same encoding as used in `Finset.encodable`. -/ instance finset : Denumerable (Finset α) := mk' ⟨fun s : Finset α => encode <| lower' ((s.map (eqv α).toEmbedding).sort (· ≤ ·)) 0, fun n => Finset.map (eqv α).symm.toEmbedding (raise'Finset (ofNat (List ℕ) n) 0), fun s => Finset.eq_of_veq <| by simp [-Multiset.map_coe, raise'Finset, raise_lower' (fun n _ => Nat.zero_le n) (Finset.sort_sorted_lt _)], fun n => by simp [-Multiset.map_coe, Finset.map, raise'Finset, Finset.sort, List.mergeSort_eq_self (· ≤ ·) ((raise'_sorted _ _).imp (@le_of_lt _ _)), lower_raise']⟩ end Finset end Denumerable namespace Equiv /-- The type lists on unit is canonically equivalent to the natural numbers. -/ def listUnitEquiv : List Unit ≃ ℕ where toFun := List.length invFun n := List.replicate n () left_inv u := List.length_injective (by simp) right_inv n := List.length_replicate n () /-- `List ℕ` is equivalent to `ℕ`. -/ def listNatEquivNat : List ℕ ≃ ℕ := Denumerable.eqv _ /-- If `α` is equivalent to `ℕ`, then `List α` is equivalent to `α`. -/ def listEquivSelfOfEquivNat {α : Type*} (e : α ≃ ℕ) : List α ≃ α := calc List α ≃ List ℕ := listEquivOfEquiv e _ ≃ ℕ := listNatEquivNat _ ≃ α := e.symm end Equiv
Logic\Equiv\Nat.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.Data.Nat.Bits import Mathlib.Data.Nat.Pairing /-! # Equivalences involving `ℕ` This file defines some additional constructive equivalences using `Encodable` and the pairing function on `ℕ`. -/ open Nat Function namespace Equiv variable {α : Type*} /-- An equivalence between `Bool × ℕ` and `ℕ`, by mapping `(true, x)` to `2 * x + 1` and `(false, x)` to `2 * x`. -/ @[simps] def boolProdNatEquivNat : Bool × ℕ ≃ ℕ where toFun := uncurry bit invFun := boddDiv2 left_inv := fun ⟨b, n⟩ => by simp only [bodd_bit, div2_bit, uncurry_apply_pair, boddDiv2_eq] right_inv n := by simp only [bit_decomp, boddDiv2_eq, uncurry_apply_pair] /-- An equivalence between `ℕ ⊕ ℕ` and `ℕ`, by mapping `(Sum.inl x)` to `2 * x` and `(Sum.inr x)` to `2 * x + 1`. -/ @[simps! symm_apply] def natSumNatEquivNat : ℕ ⊕ ℕ ≃ ℕ := (boolProdEquivSum ℕ).symm.trans boolProdNatEquivNat set_option linter.deprecated false in @[simp] theorem natSumNatEquivNat_apply : ⇑natSumNatEquivNat = Sum.elim (2 * ·) (2 * · + 1) := by ext (x | x) <;> rfl /-- An equivalence between `ℤ` and `ℕ`, through `ℤ ≃ ℕ ⊕ ℕ` and `ℕ ⊕ ℕ ≃ ℕ`. -/ def intEquivNat : ℤ ≃ ℕ := intEquivNatSumNat.trans natSumNatEquivNat /-- An equivalence between `α × α` and `α`, given that there is an equivalence between `α` and `ℕ`. -/ def prodEquivOfEquivNat (e : α ≃ ℕ) : α × α ≃ α := calc α × α ≃ ℕ × ℕ := prodCongr e e _ ≃ ℕ := pairEquiv _ ≃ α := e.symm end Equiv
Logic\Equiv\Option.lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Control.EquivFunctor import Mathlib.Data.Option.Basic import Mathlib.Data.Subtype import Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.Cases /-! # Equivalences for `Option α` We define * `Equiv.optionCongr`: the `Option α ≃ Option β` constructed from `e : α ≃ β` by sending `none` to `none`, and applying `e` elsewhere. * `Equiv.removeNone`: the `α ≃ β` constructed from `Option α ≃ Option β` by removing `none` from both sides. -/ universe u namespace Equiv open Option variable {α β γ : Type*} section OptionCongr /-- A universe-polymorphic version of `EquivFunctor.mapEquiv Option e`. -/ @[simps apply] def optionCongr (e : α ≃ β) : Option α ≃ Option β where toFun := Option.map e invFun := Option.map e.symm left_inv x := (Option.map_map _ _ _).trans <| e.symm_comp_self.symm ▸ congr_fun Option.map_id x right_inv x := (Option.map_map _ _ _).trans <| e.self_comp_symm.symm ▸ congr_fun Option.map_id x @[simp] theorem optionCongr_refl : optionCongr (Equiv.refl α) = Equiv.refl _ := ext <| congr_fun Option.map_id @[simp] theorem optionCongr_symm (e : α ≃ β) : (optionCongr e).symm = optionCongr e.symm := rfl @[simp] theorem optionCongr_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (optionCongr e₁).trans (optionCongr e₂) = optionCongr (e₁.trans e₂) := ext <| Option.map_map _ _ /-- When `α` and `β` are in the same universe, this is the same as the result of `EquivFunctor.mapEquiv`. -/ theorem optionCongr_eq_equivFunctor_mapEquiv {α β : Type u} (e : α ≃ β) : optionCongr e = EquivFunctor.mapEquiv Option e := rfl end OptionCongr section RemoveNone variable (e : Option α ≃ Option β) /-- If we have a value on one side of an `Equiv` of `Option` we also have a value on the other side of the equivalence -/ def removeNone_aux (x : α) : β := if h : (e (some x)).isSome then Option.get _ h else Option.get _ <| show (e none).isSome by rw [← Option.ne_none_iff_isSome] intro hn rw [Option.not_isSome_iff_eq_none, ← hn] at h exact Option.some_ne_none _ (e.injective h) theorem removeNone_aux_some {x : α} (h : ∃ x', e (some x) = some x') : some (removeNone_aux e x) = e (some x) := by simp [removeNone_aux, Option.isSome_iff_exists.mpr h] theorem removeNone_aux_none {x : α} (h : e (some x) = none) : some (removeNone_aux e x) = e none := by simp [removeNone_aux, Option.not_isSome_iff_eq_none.mpr h] theorem removeNone_aux_inv (x : α) : removeNone_aux e.symm (removeNone_aux e x) = x := Option.some_injective _ (by cases h1 : e.symm (some (removeNone_aux e x)) <;> cases h2 : e (some x) · rw [removeNone_aux_none _ h1] exact (e.eq_symm_apply.mpr h2).symm · rw [removeNone_aux_some _ ⟨_, h2⟩] at h1 simp at h1 · rw [removeNone_aux_none _ h2] at h1 simp at h1 · rw [removeNone_aux_some _ ⟨_, h1⟩] rw [removeNone_aux_some _ ⟨_, h2⟩] simp) /-- Given an equivalence between two `Option` types, eliminate `none` from that equivalence by mapping `e.symm none` to `e none`. -/ def removeNone : α ≃ β where toFun := removeNone_aux e invFun := removeNone_aux e.symm left_inv := removeNone_aux_inv e right_inv := removeNone_aux_inv e.symm @[simp] theorem removeNone_symm : (removeNone e).symm = removeNone e.symm := rfl theorem removeNone_some {x : α} (h : ∃ x', e (some x) = some x') : some (removeNone e x) = e (some x) := removeNone_aux_some e h theorem removeNone_none {x : α} (h : e (some x) = none) : some (removeNone e x) = e none := removeNone_aux_none e h @[simp] theorem option_symm_apply_none_iff : e.symm none = none ↔ e none = none := ⟨fun h => by simpa using (congr_arg e h).symm, fun h => by simpa using (congr_arg e.symm h).symm⟩ theorem some_removeNone_iff {x : α} : some (removeNone e x) = e none ↔ e.symm none = some x := by cases' h : e (some x) with a · rw [removeNone_none _ h] simpa using (congr_arg e.symm h).symm · rw [removeNone_some _ ⟨a, h⟩] have h1 := congr_arg e.symm h rw [symm_apply_apply] at h1 simp only [false_iff_iff, apply_eq_iff_eq] simp [h1, apply_eq_iff_eq] @[simp] theorem removeNone_optionCongr (e : α ≃ β) : removeNone e.optionCongr = e := Equiv.ext fun x => Option.some_injective _ <| removeNone_some _ ⟨e x, by simp [EquivFunctor.map]⟩ end RemoveNone theorem optionCongr_injective : Function.Injective (optionCongr : α ≃ β → Option α ≃ Option β) := Function.LeftInverse.injective removeNone_optionCongr /-- Equivalences between `Option α` and `β` that send `none` to `x` are equivalent to equivalences between `α` and `{y : β // y ≠ x}`. -/ def optionSubtype [DecidableEq β] (x : β) : { e : Option α ≃ β // e none = x } ≃ (α ≃ { y : β // y ≠ x }) where toFun e := { toFun := fun a => ⟨(e : Option α ≃ β) a, ((EquivLike.injective _).ne_iff' e.property).2 (some_ne_none _)⟩, invFun := fun b => get _ (ne_none_iff_isSome.1 (((EquivLike.injective _).ne_iff' ((apply_eq_iff_eq_symm_apply _).1 e.property).symm).2 b.property)), left_inv := fun a => by rw [← some_inj, some_get] exact symm_apply_apply (e : Option α ≃ β) a, right_inv := fun b => by ext simp } invFun e := ⟨{ toFun := fun a => casesOn' a x (Subtype.val ∘ e), invFun := fun b => if h : b = x then none else e.symm ⟨b, h⟩, left_inv := fun a => by cases a with | none => simp | some a => simp only [casesOn'_some, Function.comp_apply, Subtype.coe_eta, symm_apply_apply, dite_eq_ite] exact if_neg (e a).property, right_inv := fun b => by by_cases h : b = x <;> simp [h] }, rfl⟩ left_inv e := by ext a cases a · simpa using e.property.symm -- Porting note: this cases had been by `simpa`, -- but `simp` here is mysteriously slow, even after squeezing. -- `rfl` closes the goal quickly, so we use that. · rfl right_inv e := by ext a rfl @[simp] theorem optionSubtype_apply_apply [DecidableEq β] (x : β) (e : { e : Option α ≃ β // e none = x }) (a : α) (h) : optionSubtype x e a = ⟨(e : Option α ≃ β) a, h⟩ := rfl @[simp] theorem coe_optionSubtype_apply_apply [DecidableEq β] (x : β) (e : { e : Option α ≃ β // e none = x }) (a : α) : ↑(optionSubtype x e a) = (e : Option α ≃ β) a := rfl @[simp] theorem optionSubtype_apply_symm_apply [DecidableEq β] (x : β) (e : { e : Option α ≃ β // e none = x }) (b : { y : β // y ≠ x }) : ↑((optionSubtype x e).symm b) = (e : Option α ≃ β).symm b := by dsimp only [optionSubtype] simp @[simp] theorem optionSubtype_symm_apply_apply_coe [DecidableEq β] (x : β) (e : α ≃ { y : β // y ≠ x }) (a : α) : ((optionSubtype x).symm e : Option α ≃ β) a = e a := rfl @[simp] theorem optionSubtype_symm_apply_apply_some [DecidableEq β] (x : β) (e : α ≃ { y : β // y ≠ x }) (a : α) : ((optionSubtype x).symm e : Option α ≃ β) (some a) = e a := rfl @[simp] theorem optionSubtype_symm_apply_apply_none [DecidableEq β] (x : β) (e : α ≃ { y : β // y ≠ x }) : ((optionSubtype x).symm e : Option α ≃ β) none = x := rfl @[simp] theorem optionSubtype_symm_apply_symm_apply [DecidableEq β] (x : β) (e : α ≃ { y : β // y ≠ x }) (b : { y : β // y ≠ x }) : ((optionSubtype x).symm e : Option α ≃ β).symm b = e.symm b := by simp only [optionSubtype, coe_fn_symm_mk, Subtype.coe_mk, Subtype.coe_eta, dite_eq_ite, ite_eq_right_iff] exact fun h => False.elim (b.property h) variable [DecidableEq α] {a b : α} /-- Any type with a distinguished element is equivalent to an `Option` type on the subtype excluding that element. -/ @[simps!] def optionSubtypeNe (a : α) : Option {b // b ≠ a} ≃ α := optionSubtype a |>.symm (.refl _) |>.1 lemma optionSubtypeNe_symm_self (a : α) : (optionSubtypeNe a).symm a = none := by simp lemma optionSubtypeNe_symm_of_ne (hba : b ≠ a) : (optionSubtypeNe a).symm b = some ⟨b, hba⟩ := by simp [hba] @[simp] lemma optionSubtypeNe_none (a : α) : optionSubtypeNe a none = a := rfl @[simp] lemma optionSubtypeNe_some (a : α) (b) : optionSubtypeNe a (some b) = b := rfl end Equiv
Logic\Equiv\Pairwise.lean
/- Copyright (c) 2024 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import Mathlib.Data.FunLike.Equiv import Mathlib.Logic.Pairwise /-! # Interaction of equivalences with `Pairwise` -/ lemma EmbeddingLike.pairwise_comp {X : Type*} {Y : Type*} {F} [FunLike F Y X] [EmbeddingLike F Y X] (f : F) {p : X → X → Prop} (h : Pairwise p) : Pairwise (p on f) := h.comp_of_injective <| EmbeddingLike.injective f lemma EquivLike.pairwise_comp_iff {X : Type*} {Y : Type*} {F} [EquivLike F Y X] (f : F) (p : X → X → Prop) : Pairwise (p on f) ↔ Pairwise p := (EquivLike.bijective f).pairwise_comp_iff
Logic\Equiv\PartialEquiv.lean
/- Copyright (c) 2019 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.Data.Set.Function import Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.Core import Mathlib.Tactic.Attr.Core /-! # Partial equivalences This files defines equivalences between subsets of given types. An element `e` of `PartialEquiv α β` is made of two maps `e.toFun` and `e.invFun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two partial equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.toFun x` and `e.invFun y`. ## Main definitions * `Equiv.toPartialEquiv`: associating a partial equiv to an equiv, with source = target = univ * `PartialEquiv.symm`: the inverse of a partial equivalence * `PartialEquiv.trans`: the composition of two partial equivalences * `PartialEquiv.refl`: the identity partial equivalence * `PartialEquiv.ofSet`: the identity on a set `s` * `EqOnSource`: equivalence relation describing the "right" notion of equality for partial equivalences (see below in implementation notes) ## Implementation notes There are at least three possible implementations of partial equivalences: * equivs on subtypes * pairs of functions taking values in `Option α` and `Option β`, equal to none where the partial equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `PEquiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The `PartialEquiv` version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `toFun` and `invFun` outside of `source` and `target`). In particular, the equality notion between partial equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no partial equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal partial equivs, this is not an issue in practice. Still, we introduce an equivalence relation `EqOnSource` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `PartialEquiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open Lean Meta Elab Tactic /-! Implementation of the `mfld_set_tac` tactic for working with the domains of partially-defined functions (`PartialEquiv`, `PartialHomeomorph`, etc). This is in a separate file from `Mathlib.Logic.Equiv.MfldSimpsAttr` because attributes need a new file to become functional. -/ /-- Common `@[simps]` configuration options used for manifold-related declarations. -/ def mfld_cfg : Simps.Config where attrs := [`mfld_simps] fullyApplied := false namespace Tactic.MfldSetTac /-- A very basic tactic to show that sets showing up in manifolds coincide or are included in one another. -/ elab (name := mfldSetTac) "mfld_set_tac" : tactic => withMainContext do let g ← getMainGoal let goalTy := (← instantiateMVars (← g.getDecl).type).getAppFnArgs match goalTy with | (``Eq, #[_ty, _e₁, _e₂]) => evalTactic (← `(tactic| ( apply Set.ext; intro my_y constructor <;> · intro h_my_y try simp only [*, mfld_simps] at h_my_y try simp only [*, mfld_simps]))) | (``Subset, #[_ty, _inst, _e₁, _e₂]) => evalTactic (← `(tactic| ( intro my_y h_my_y try simp only [*, mfld_simps] at h_my_y try simp only [*, mfld_simps]))) | _ => throwError "goal should be an equality or an inclusion" attribute [mfld_simps] and_true eq_self_iff_true Function.comp_apply end Tactic.MfldSetTac open Function Set variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of `α` and `β` respectively. The (global) maps `toFun : α → β` and `invFun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `toFun` outside of `source` and of `invFun` outside of `target` are irrelevant. -/ structure PartialEquiv (α : Type*) (β : Type*) where /-- The global function which has a partial inverse. Its value outside of the `source` subset is irrelevant. -/ toFun : α → β /-- The partial inverse to `toFun`. Its value outside of the `target` subset is irrelevant. -/ invFun : β → α /-- The domain of the partial equivalence. -/ source : Set α /-- The codomain of the partial equivalence. -/ target : Set β /-- The proposition that elements of `source` are mapped to elements of `target`. -/ map_source' : ∀ ⦃x⦄, x ∈ source → toFun x ∈ target /-- The proposition that elements of `target` are mapped to elements of `source`. -/ map_target' : ∀ ⦃x⦄, x ∈ target → invFun x ∈ source /-- The proposition that `invFun` is a left-inverse of `toFun` on `source`. -/ left_inv' : ∀ ⦃x⦄, x ∈ source → invFun (toFun x) = x /-- The proposition that `invFun` is a right-inverse of `toFun` on `target`. -/ right_inv' : ∀ ⦃x⦄, x ∈ target → toFun (invFun x) = x attribute [coe] PartialEquiv.toFun namespace PartialEquiv variable (e : PartialEquiv α β) (e' : PartialEquiv β γ) instance [Inhabited α] [Inhabited β] : Inhabited (PartialEquiv α β) := ⟨⟨const α default, const β default, ∅, ∅, mapsTo_empty _ _, mapsTo_empty _ _, eqOn_empty _ _, eqOn_empty _ _⟩⟩ /-- The inverse of a partial equivalence -/ @[symm] protected def symm : PartialEquiv β α where toFun := e.invFun invFun := e.toFun source := e.target target := e.source map_source' := e.map_target' map_target' := e.map_source' left_inv' := e.right_inv' right_inv' := e.left_inv' instance : CoeFun (PartialEquiv α β) fun _ => α → β := ⟨PartialEquiv.toFun⟩ /-- See Note [custom simps projection] -/ def Simps.symm_apply (e : PartialEquiv α β) : β → α := e.symm initialize_simps_projections PartialEquiv (toFun → apply, invFun → symm_apply) -- Porting note: this can be proven with `dsimp only` -- @[simp, mfld_simps] -- theorem coe_mk (f : α → β) (g s t ml mr il ir) : -- (PartialEquiv.mk f g s t ml mr il ir : α → β) = f := by dsimp only @[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((PartialEquiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl -- Porting note: this is now a syntactic tautology -- @[simp, mfld_simps] -- theorem toFun_as_coe : e.toFun = e := rfl @[simp, mfld_simps] theorem invFun_as_coe : e.invFun = e.symm := rfl @[simp, mfld_simps] theorem map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h /-- Variant of `e.map_source` and `map_source'`, stated for images of subsets of `source`. -/ lemma map_source'' : e '' e.source ⊆ e.target := fun _ ⟨_, hx, hex⟩ ↦ mem_of_eq_of_mem (id hex.symm) (e.map_source' hx) @[simp, mfld_simps] theorem map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] theorem left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] theorem right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h theorem eq_symm_apply {x : α} {y : β} (hx : x ∈ e.source) (hy : y ∈ e.target) : x = e.symm y ↔ e x = y := ⟨fun h => by rw [← e.right_inv hy, h], fun h => by rw [← e.left_inv hx, h]⟩ protected theorem mapsTo : MapsTo e e.source e.target := fun _ => e.map_source theorem symm_mapsTo : MapsTo e.symm e.target e.source := e.symm.mapsTo protected theorem leftInvOn : LeftInvOn e.symm e e.source := fun _ => e.left_inv protected theorem rightInvOn : RightInvOn e.symm e e.target := fun _ => e.right_inv protected theorem invOn : InvOn e.symm e e.source e.target := ⟨e.leftInvOn, e.rightInvOn⟩ protected theorem injOn : InjOn e e.source := e.leftInvOn.injOn protected theorem bijOn : BijOn e e.source e.target := e.invOn.bijOn e.mapsTo e.symm_mapsTo protected theorem surjOn : SurjOn e e.source e.target := e.bijOn.surjOn /-- Interpret an `Equiv` as a `PartialEquiv` by restricting it to `s` in the domain and to `t` in the codomain. -/ @[simps (config := .asFn)] def _root_.Equiv.toPartialEquivOfImageEq (e : α ≃ β) (s : Set α) (t : Set β) (h : e '' s = t) : PartialEquiv α β where toFun := e invFun := e.symm source := s target := t map_source' x hx := h ▸ mem_image_of_mem _ hx map_target' x hx := by subst t rcases hx with ⟨x, hx, rfl⟩ rwa [e.symm_apply_apply] left_inv' x _ := e.symm_apply_apply x right_inv' x _ := e.apply_symm_apply x /-- Associate a `PartialEquiv` to an `Equiv`. -/ @[simps! (config := mfld_cfg)] def _root_.Equiv.toPartialEquiv (e : α ≃ β) : PartialEquiv α β := e.toPartialEquivOfImageEq univ univ <| by rw [image_univ, e.surjective.range_eq] instance inhabitedOfEmpty [IsEmpty α] [IsEmpty β] : Inhabited (PartialEquiv α β) := ⟨((Equiv.equivEmpty α).trans (Equiv.equivEmpty β).symm).toPartialEquiv⟩ /-- Create a copy of a `PartialEquiv` providing better definitional equalities. -/ @[simps (config := .asFn)] def copy (e : PartialEquiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : Set α) (hs : e.source = s) (t : Set β) (ht : e.target = t) : PartialEquiv α β where toFun := f invFun := g source := s target := t map_source' _ := ht ▸ hs ▸ hf ▸ e.map_source map_target' _ := hs ▸ ht ▸ hg ▸ e.map_target left_inv' _ := hs ▸ hf ▸ hg ▸ e.left_inv right_inv' _ := ht ▸ hf ▸ hg ▸ e.right_inv theorem copy_eq (e : PartialEquiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : Set α) (hs : e.source = s) (t : Set β) (ht : e.target = t) : e.copy f hf g hg s hs t ht = e := by substs f g s t cases e rfl /-- Associate to a `PartialEquiv` an `Equiv` between the source and the target. -/ protected def toEquiv : e.source ≃ e.target where toFun x := ⟨e x, e.map_source x.mem⟩ invFun y := ⟨e.symm y, e.map_target y.mem⟩ left_inv := fun ⟨_, hx⟩ => Subtype.eq <| e.left_inv hx right_inv := fun ⟨_, hy⟩ => Subtype.eq <| e.right_inv hy @[simp, mfld_simps] theorem symm_source : e.symm.source = e.target := rfl @[simp, mfld_simps] theorem symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] theorem symm_symm : e.symm.symm = e := by cases e rfl theorem symm_bijective : Function.Bijective (PartialEquiv.symm : PartialEquiv α β → PartialEquiv β α) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ theorem image_source_eq_target : e '' e.source = e.target := e.bijOn.image_eq theorem forall_mem_target {p : β → Prop} : (∀ y ∈ e.target, p y) ↔ ∀ x ∈ e.source, p (e x) := by rw [← image_source_eq_target, forall_mem_image] theorem exists_mem_target {p : β → Prop} : (∃ y ∈ e.target, p y) ↔ ∃ x ∈ e.source, p (e x) := by rw [← image_source_eq_target, exists_mem_image] /-- We say that `t : Set β` is an image of `s : Set α` under a partial equivalence if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def IsImage (s : Set α) (t : Set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace IsImage variable {e} {s : Set α} {t : Set β} {x : α} {y : β} theorem apply_mem_iff (h : e.IsImage s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx theorem symm_apply_mem_iff (h : e.IsImage s t) : ∀ ⦃y⦄, y ∈ e.target → (e.symm y ∈ s ↔ y ∈ t) := e.forall_mem_target.mpr fun x hx => by rw [e.left_inv hx, h hx] protected theorem symm (h : e.IsImage s t) : e.symm.IsImage t s := h.symm_apply_mem_iff @[simp] theorem symm_iff : e.symm.IsImage t s ↔ e.IsImage s t := ⟨fun h => h.symm, fun h => h.symm⟩ protected theorem mapsTo (h : e.IsImage s t) : MapsTo e (e.source ∩ s) (e.target ∩ t) := fun _ hx => ⟨e.mapsTo hx.1, (h hx.1).2 hx.2⟩ theorem symm_mapsTo (h : e.IsImage s t) : MapsTo e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.mapsTo /-- Restrict a `PartialEquiv` to a pair of corresponding sets. -/ @[simps (config := .asFn)] def restr (h : e.IsImage s t) : PartialEquiv α β where toFun := e invFun := e.symm source := e.source ∩ s target := e.target ∩ t map_source' := h.mapsTo map_target' := h.symm_mapsTo left_inv' := e.leftInvOn.mono inter_subset_left right_inv' := e.rightInvOn.mono inter_subset_left theorem image_eq (h : e.IsImage s t) : e '' (e.source ∩ s) = e.target ∩ t := h.restr.image_source_eq_target theorem symm_image_eq (h : e.IsImage s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq theorem iff_preimage_eq : e.IsImage s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := by simp only [IsImage, Set.ext_iff, mem_inter_iff, mem_preimage, and_congr_right_iff] alias ⟨preimage_eq, of_preimage_eq⟩ := iff_preimage_eq theorem iff_symm_preimage_eq : e.IsImage s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias ⟨symm_preimage_eq, of_symm_preimage_eq⟩ := iff_symm_preimage_eq theorem of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.IsImage s t := of_symm_preimage_eq <| Eq.trans (of_symm_preimage_eq rfl).image_eq.symm h theorem of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.IsImage s t := of_preimage_eq <| Eq.trans (iff_preimage_eq.2 rfl).symm_image_eq.symm h protected theorem compl (h : e.IsImage s t) : e.IsImage sᶜ tᶜ := fun _ hx => not_congr (h hx) protected theorem inter {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s ∩ s') (t ∩ t') := fun _ hx => and_congr (h hx) (h' hx) protected theorem union {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s ∪ s') (t ∪ t') := fun _ hx => or_congr (h hx) (h' hx) protected theorem diff {s' t'} (h : e.IsImage s t) (h' : e.IsImage s' t') : e.IsImage (s \ s') (t \ t') := h.inter h'.compl theorem leftInvOn_piecewise {e' : PartialEquiv α β} [∀ i, Decidable (i ∈ s)] [∀ i, Decidable (i ∈ t)] (h : e.IsImage s t) (h' : e'.IsImage s t) : LeftInvOn (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := by rintro x (⟨he, hs⟩ | ⟨he, hs : x ∉ s⟩) · rw [piecewise_eq_of_mem _ _ _ hs, piecewise_eq_of_mem _ _ _ ((h he).2 hs), e.left_inv he] · rw [piecewise_eq_of_not_mem _ _ _ hs, piecewise_eq_of_not_mem _ _ _ ((h'.compl he).2 hs), e'.left_inv he] theorem inter_eq_of_inter_eq_of_eqOn {e' : PartialEquiv α β} (h : e.IsImage s t) (h' : e'.IsImage s t) (hs : e.source ∩ s = e'.source ∩ s) (heq : EqOn e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := by rw [← h.image_eq, ← h'.image_eq, ← hs, heq.image_eq] theorem symm_eq_on_of_inter_eq_of_eqOn {e' : PartialEquiv α β} (h : e.IsImage s t) (hs : e.source ∩ s = e'.source ∩ s) (heq : EqOn e e' (e.source ∩ s)) : EqOn e.symm e'.symm (e.target ∩ t) := by rw [← h.image_eq] rintro y ⟨x, hx, rfl⟩ have hx' := hx; rw [hs] at hx' rw [e.left_inv hx.1, heq hx, e'.left_inv hx'.1] end IsImage theorem isImage_source_target : e.IsImage e.source e.target := fun x hx => by simp [hx] theorem isImage_source_target_of_disjoint (e' : PartialEquiv α β) (hs : Disjoint e.source e'.source) (ht : Disjoint e.target e'.target) : e.IsImage e'.source e'.target := IsImage.of_image_eq <| by rw [hs.inter_eq, ht.inter_eq, image_empty] theorem image_source_inter_eq' (s : Set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := by rw [inter_comm, e.leftInvOn.image_inter', image_source_eq_target, inter_comm] theorem image_source_inter_eq (s : Set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := by rw [inter_comm, e.leftInvOn.image_inter, image_source_eq_target, inter_comm] theorem image_eq_target_inter_inv_preimage {s : Set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := by rw [← e.image_source_inter_eq', inter_eq_self_of_subset_right h] theorem symm_image_eq_source_inter_preimage {s : Set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h theorem symm_image_target_inter_eq (s : Set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ theorem symm_image_target_inter_eq' (s : Set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' s := e.symm.image_source_inter_eq' _ theorem source_inter_preimage_inv_preimage (s : Set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := Set.ext fun x => and_congr_right_iff.2 fun hx => by simp only [mem_preimage, e.left_inv hx] theorem source_inter_preimage_target_inter (s : Set β) : e.source ∩ e ⁻¹' (e.target ∩ s) = e.source ∩ e ⁻¹' s := ext fun _ => ⟨fun hx => ⟨hx.1, hx.2.2⟩, fun hx => ⟨hx.1, e.map_source hx.1, hx.2⟩⟩ theorem target_inter_inv_preimage_preimage (s : Set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ theorem symm_image_image_of_subset_source {s : Set α} (h : s ⊆ e.source) : e.symm '' (e '' s) = s := (e.leftInvOn.mono h).image_image theorem image_symm_image_of_subset_target {s : Set β} (h : s ⊆ e.target) : e '' (e.symm '' s) = s := e.symm.symm_image_image_of_subset_source h theorem source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target := e.mapsTo theorem symm_image_target_eq_source : e.symm '' e.target = e.source := e.symm.image_source_eq_target theorem target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source := e.symm_mapsTo /-- Two partial equivs that have the same `source`, same `toFun` and same `invFun`, coincide. -/ @[ext] protected theorem ext {e e' : PartialEquiv α β} (h : ∀ x, e x = e' x) (hsymm : ∀ x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := by have A : (e : α → β) = e' := by ext x exact h x have B : (e.symm : β → α) = e'.symm := by ext x exact hsymm x have I : e '' e.source = e.target := e.image_source_eq_target have I' : e' '' e'.source = e'.target := e'.image_source_eq_target rw [A, hs, I'] at I cases e; cases e' simp_all /-- Restricting a partial equivalence to `e.source ∩ s` -/ protected def restr (s : Set α) : PartialEquiv α β := (@IsImage.of_symm_preimage_eq α β e s (e.symm ⁻¹' s) rfl).restr @[simp, mfld_simps] theorem restr_coe (s : Set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] theorem restr_coe_symm (s : Set α) : ((e.restr s).symm : β → α) = e.symm := rfl @[simp, mfld_simps] theorem restr_source (s : Set α) : (e.restr s).source = e.source ∩ s := rfl @[simp, mfld_simps] theorem restr_target (s : Set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl theorem restr_eq_of_source_subset {e : PartialEquiv α β} {s : Set α} (h : e.source ⊆ s) : e.restr s = e := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp, mfld_simps] theorem restr_univ {e : PartialEquiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity partial equiv -/ protected def refl (α : Type*) : PartialEquiv α α := (Equiv.refl α).toPartialEquiv @[simp, mfld_simps] theorem refl_source : (PartialEquiv.refl α).source = univ := rfl @[simp, mfld_simps] theorem refl_target : (PartialEquiv.refl α).target = univ := rfl @[simp, mfld_simps] theorem refl_coe : (PartialEquiv.refl α : α → α) = id := rfl @[simp, mfld_simps] theorem refl_symm : (PartialEquiv.refl α).symm = PartialEquiv.refl α := rfl -- Porting note: removed `simp` because `simp` can prove this @[mfld_simps] theorem refl_restr_source (s : Set α) : ((PartialEquiv.refl α).restr s).source = s := by simp -- Porting note: removed `simp` because `simp` can prove this @[mfld_simps] theorem refl_restr_target (s : Set α) : ((PartialEquiv.refl α).restr s).target = s := by change univ ∩ id ⁻¹' s = s simp /-- The identity partial equivalence on a set `s` -/ def ofSet (s : Set α) : PartialEquiv α α where toFun := id invFun := id source := s target := s map_source' _ hx := hx map_target' _ hx := hx left_inv' _ _ := rfl right_inv' _ _ := rfl @[simp, mfld_simps] theorem ofSet_source (s : Set α) : (PartialEquiv.ofSet s).source = s := rfl @[simp, mfld_simps] theorem ofSet_target (s : Set α) : (PartialEquiv.ofSet s).target = s := rfl @[simp, mfld_simps] theorem ofSet_coe (s : Set α) : (PartialEquiv.ofSet s : α → α) = id := rfl @[simp, mfld_simps] theorem ofSet_symm (s : Set α) : (PartialEquiv.ofSet s).symm = PartialEquiv.ofSet s := rfl /-- Composing two partial equivs if the target of the first coincides with the source of the second. -/ @[simps] protected def trans' (e' : PartialEquiv β γ) (h : e.target = e'.source) : PartialEquiv α γ where toFun := e' ∘ e invFun := e.symm ∘ e'.symm source := e.source target := e'.target map_source' x hx := by simp [← h, hx] map_target' y hy := by simp [h, hy] left_inv' x hx := by simp [hx, ← h] right_inv' y hy := by simp [hy, h] /-- Composing two partial equivs, by restricting to the maximal domain where their composition is well defined. -/ @[trans] protected def trans : PartialEquiv α γ := PartialEquiv.trans' (e.symm.restr e'.source).symm (e'.restr e.target) (inter_comm _ _) @[simp, mfld_simps] theorem coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] theorem coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl theorem trans_apply {x : α} : (e.trans e') x = e' (e x) := rfl theorem trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; rfl @[simp, mfld_simps] theorem trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl theorem trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := by mfld_set_tac theorem trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := by rw [e.trans_source', e.symm_image_target_inter_eq] theorem image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := (e.symm.restr e'.source).symm.image_source_eq_target @[simp, mfld_simps] theorem trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl theorem trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm theorem trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm theorem inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm theorem trans_assoc (e'' : PartialEquiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := PartialEquiv.ext (fun x => rfl) (fun x => rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc]) @[simp, mfld_simps] theorem trans_refl : e.trans (PartialEquiv.refl β) = e := PartialEquiv.ext (fun x => rfl) (fun x => rfl) (by simp [trans_source]) @[simp, mfld_simps] theorem refl_trans : (PartialEquiv.refl α).trans e = e := PartialEquiv.ext (fun x => rfl) (fun x => rfl) (by simp [trans_source, preimage_id]) theorem trans_ofSet (s : Set β) : e.trans (ofSet s) = e.restr (e ⁻¹' s) := PartialEquiv.ext (fun _ => rfl) (fun _ => rfl) rfl theorem trans_refl_restr (s : Set β) : e.trans ((PartialEquiv.refl β).restr s) = e.restr (e ⁻¹' s) := PartialEquiv.ext (fun x => rfl) (fun x => rfl) (by simp [trans_source]) theorem trans_refl_restr' (s : Set β) : e.trans ((PartialEquiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) := PartialEquiv.ext (fun x => rfl) (fun x => rfl) <| by simp only [trans_source, restr_source, refl_source, univ_inter] rw [← inter_assoc, inter_self] theorem restr_trans (s : Set α) : (e.restr s).trans e' = (e.trans e').restr s := PartialEquiv.ext (fun x => rfl) (fun x => rfl) <| by simp [trans_source, inter_comm, inter_assoc] /-- A lemma commonly useful when `e` and `e'` are charts of a manifold. -/ theorem mem_symm_trans_source {e' : PartialEquiv α γ} {x : α} (he : x ∈ e.source) (he' : x ∈ e'.source) : e x ∈ (e.symm.trans e').source := ⟨e.mapsTo he, by rwa [mem_preimage, PartialEquiv.symm_symm, e.left_inv he]⟩ /-- `EqOnSource e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same partial equiv. -/ def EqOnSource (e e' : PartialEquiv α β) : Prop := e.source = e'.source ∧ e.source.EqOn e e' /-- `EqOnSource` is an equivalence relation. This instance provides the `≈` notation between two `PartialEquiv`s. -/ instance eqOnSourceSetoid : Setoid (PartialEquiv α β) where r := EqOnSource iseqv := by constructor <;> simp only [Equivalence, EqOnSource, EqOn] <;> aesop theorem eqOnSource_refl : e ≈ e := Setoid.refl _ /-- Two equivalent partial equivs have the same source. -/ theorem EqOnSource.source_eq {e e' : PartialEquiv α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent partial equivs coincide on the source. -/ theorem EqOnSource.eqOn {e e' : PartialEquiv α β} (h : e ≈ e') : e.source.EqOn e e' := h.2 -- Porting note: A lot of dot notation failures here. Maybe we should not use `≈` /-- Two equivalent partial equivs have the same target. -/ theorem EqOnSource.target_eq {e e' : PartialEquiv α β} (h : e ≈ e') : e.target = e'.target := by simp only [← image_source_eq_target, ← source_eq h, h.2.image_eq] /-- If two partial equivs are equivalent, so are their inverses. -/ theorem EqOnSource.symm' {e e' : PartialEquiv α β} (h : e ≈ e') : e.symm ≈ e'.symm := by refine ⟨target_eq h, eqOn_of_leftInvOn_of_rightInvOn e.leftInvOn ?_ ?_⟩ <;> simp only [symm_source, target_eq h, source_eq h, e'.symm_mapsTo] exact e'.rightInvOn.congr_right e'.symm_mapsTo (source_eq h ▸ h.eqOn.symm) /-- Two equivalent partial equivs have coinciding inverses on the target. -/ theorem EqOnSource.symm_eqOn {e e' : PartialEquiv α β} (h : e ≈ e') : EqOn e.symm e'.symm e.target := -- Porting note: `h.symm'` dot notation doesn't work anymore because `h` is not recognised as -- `PartialEquiv.EqOnSource` for some reason. eqOn (symm' h) /-- Composition of partial equivs respects equivalence. -/ theorem EqOnSource.trans' {e e' : PartialEquiv α β} {f f' : PartialEquiv β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := by constructor · rw [trans_source'', trans_source'', ← target_eq he, ← hf.1] exact (he.symm'.eqOn.mono inter_subset_left).image_eq · intro x hx rw [trans_source] at hx simp [Function.comp_apply, PartialEquiv.coe_trans, (he.2 hx.1).symm, hf.2 hx.2] /-- Restriction of partial equivs respects equivalence. -/ theorem EqOnSource.restr {e e' : PartialEquiv α β} (he : e ≈ e') (s : Set α) : e.restr s ≈ e'.restr s := by constructor · simp [he.1] · intro x hx simp only [mem_inter_iff, restr_source] at hx exact he.2 hx.1 /-- Preimages are respected by equivalence. -/ theorem EqOnSource.source_inter_preimage_eq {e e' : PartialEquiv α β} (he : e ≈ e') (s : Set β) : e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s := by rw [he.eqOn.inter_preimage_eq, source_eq he] /-- Composition of a partial equivlance and its inverse is equivalent to the restriction of the identity to the source. -/ theorem self_trans_symm : e.trans e.symm ≈ ofSet e.source := by have A : (e.trans e.symm).source = e.source := by mfld_set_tac refine ⟨by rw [A, ofSet_source], fun x hx => ?_⟩ rw [A] at hx simp only [hx, mfld_simps] /-- Composition of the inverse of a partial equivalence and this partial equivalence is equivalent to the restriction of the identity to the target. -/ theorem symm_trans_self : e.symm.trans e ≈ ofSet e.target := self_trans_symm e.symm /-- Two equivalent partial equivs are equal when the source and target are `univ`. -/ theorem eq_of_eqOnSource_univ (e e' : PartialEquiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := by refine PartialEquiv.ext (fun x => ?_) (fun x => ?_) h.1 · apply h.2 rw [s] exact mem_univ _ · apply h.symm'.2 rw [symm_source, t] exact mem_univ _ section Prod /-- The product of two partial equivalences, as a partial equivalence on the product. -/ def prod (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : PartialEquiv (α × γ) (β × δ) where source := e.source ×ˢ e'.source target := e.target ×ˢ e'.target toFun p := (e p.1, e' p.2) invFun p := (e.symm p.1, e'.symm p.2) map_source' p hp := by simp_all map_target' p hp := by simp_all left_inv' p hp := by simp_all right_inv' p hp := by simp_all @[simp, mfld_simps] theorem prod_source (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : (e.prod e').source = e.source ×ˢ e'.source := rfl @[simp, mfld_simps] theorem prod_target (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : (e.prod e').target = e.target ×ˢ e'.target := rfl @[simp, mfld_simps] theorem prod_coe (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : (e.prod e' : α × γ → β × δ) = fun p => (e p.1, e' p.2) := rfl theorem prod_coe_symm (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : ((e.prod e').symm : β × δ → α × γ) = fun p => (e.symm p.1, e'.symm p.2) := rfl @[simp, mfld_simps] theorem prod_symm (e : PartialEquiv α β) (e' : PartialEquiv γ δ) : (e.prod e').symm = e.symm.prod e'.symm := by ext x <;> simp [prod_coe_symm] @[simp, mfld_simps] theorem refl_prod_refl : (PartialEquiv.refl α).prod (PartialEquiv.refl β) = PartialEquiv.refl (α × β) := by -- Porting note: `ext1 ⟨x, y⟩` insufficient number of binders ext ⟨x, y⟩ <;> simp @[simp, mfld_simps] theorem prod_trans {η : Type*} {ε : Type*} (e : PartialEquiv α β) (f : PartialEquiv β γ) (e' : PartialEquiv δ η) (f' : PartialEquiv η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext ⟨x, y⟩ <;> simp [Set.ext_iff]; tauto end Prod /-- Combine two `PartialEquiv`s using `Set.piecewise`. The source of the new `PartialEquiv` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. The definition assumes `e.isImage s t` and `e'.isImage s t`. -/ @[simps (config := .asFn)] def piecewise (e e' : PartialEquiv α β) (s : Set α) (t : Set β) [∀ x, Decidable (x ∈ s)] [∀ y, Decidable (y ∈ t)] (H : e.IsImage s t) (H' : e'.IsImage s t) : PartialEquiv α β where toFun := s.piecewise e e' invFun := t.piecewise e.symm e'.symm source := s.ite e.source e'.source target := t.ite e.target e'.target map_source' := H.mapsTo.piecewise_ite H'.compl.mapsTo map_target' := H.symm.mapsTo.piecewise_ite H'.symm.compl.mapsTo left_inv' := H.leftInvOn_piecewise H' right_inv' := H.symm.leftInvOn_piecewise H'.symm theorem symm_piecewise (e e' : PartialEquiv α β) {s : Set α} {t : Set β} [∀ x, Decidable (x ∈ s)] [∀ y, Decidable (y ∈ t)] (H : e.IsImage s t) (H' : e'.IsImage s t) : (e.piecewise e' s t H H').symm = e.symm.piecewise e'.symm t s H.symm H'.symm := rfl /-- Combine two `PartialEquiv`s with disjoint sources and disjoint targets. We reuse `PartialEquiv.piecewise`, then override `source` and `target` to ensure better definitional equalities. -/ @[simps! (config := .asFn)] def disjointUnion (e e' : PartialEquiv α β) (hs : Disjoint e.source e'.source) (ht : Disjoint e.target e'.target) [∀ x, Decidable (x ∈ e.source)] [∀ y, Decidable (y ∈ e.target)] : PartialEquiv α β := (e.piecewise e' e.source e.target e.isImage_source_target <| e'.isImage_source_target_of_disjoint _ hs.symm ht.symm).copy _ rfl _ rfl (e.source ∪ e'.source) (ite_left _ _) (e.target ∪ e'.target) (ite_left _ _) theorem disjointUnion_eq_piecewise (e e' : PartialEquiv α β) (hs : Disjoint e.source e'.source) (ht : Disjoint e.target e'.target) [∀ x, Decidable (x ∈ e.source)] [∀ y, Decidable (y ∈ e.target)] : e.disjointUnion e' hs ht = e.piecewise e' e.source e.target e.isImage_source_target (e'.isImage_source_target_of_disjoint _ hs.symm ht.symm) := copy_eq .. section Pi variable {ι : Type*} {αi βi γi : ι → Type*} /-- The product of a family of partial equivalences, as a partial equivalence on the pi type. -/ @[simps (config := mfld_cfg) apply source target] protected def pi (ei : ∀ i, PartialEquiv (αi i) (βi i)) : PartialEquiv (∀ i, αi i) (∀ i, βi i) where toFun f i := ei i (f i) invFun f i := (ei i).symm (f i) source := pi univ fun i => (ei i).source target := pi univ fun i => (ei i).target map_source' _ hf i hi := (ei i).map_source (hf i hi) map_target' _ hf i hi := (ei i).map_target (hf i hi) left_inv' _ hf := funext fun i => (ei i).left_inv (hf i trivial) right_inv' _ hf := funext fun i => (ei i).right_inv (hf i trivial) @[simp, mfld_simps] theorem pi_symm (ei : ∀ i, PartialEquiv (αi i) (βi i)) : (PartialEquiv.pi ei).symm = .pi fun i ↦ (ei i).symm := rfl theorem pi_symm_apply (ei : ∀ i, PartialEquiv (αi i) (βi i)) : ⇑(PartialEquiv.pi ei).symm = fun f i ↦ (ei i).symm (f i) := rfl @[simp, mfld_simps] theorem pi_refl : (PartialEquiv.pi fun i ↦ PartialEquiv.refl (αi i)) = .refl (∀ i, αi i) := by ext <;> simp @[simp, mfld_simps] theorem pi_trans (ei : ∀ i, PartialEquiv (αi i) (βi i)) (ei' : ∀ i, PartialEquiv (βi i) (γi i)) : (PartialEquiv.pi ei).trans (PartialEquiv.pi ei') = .pi fun i ↦ (ei i).trans (ei' i) := by ext <;> simp [forall_and] end Pi end PartialEquiv namespace Set -- All arguments are explicit to avoid missing information in the pretty printer output /-- A bijection between two sets `s : Set α` and `t : Set β` provides a partial equivalence between `α` and `β`. -/ @[simps (config := .asFn)] noncomputable def BijOn.toPartialEquiv [Nonempty α] (f : α → β) (s : Set α) (t : Set β) (hf : BijOn f s t) : PartialEquiv α β where toFun := f invFun := invFunOn f s source := s target := t map_source' := hf.mapsTo map_target' := hf.surjOn.mapsTo_invFunOn left_inv' := hf.invOn_invFunOn.1 right_inv' := hf.invOn_invFunOn.2 /-- A map injective on a subset of its domain provides a partial equivalence. -/ @[simp, mfld_simps] noncomputable def InjOn.toPartialEquiv [Nonempty α] (f : α → β) (s : Set α) (hf : InjOn f s) : PartialEquiv α β := hf.bijOn_image.toPartialEquiv f s (f '' s) end Set namespace Equiv /- `Equiv`s give rise to `PartialEquiv`s. We set up simp lemmas to reduce most properties of the `PartialEquiv` to that of the `Equiv`. -/ variable (e : α ≃ β) (e' : β ≃ γ) @[simp, mfld_simps] theorem refl_toPartialEquiv : (Equiv.refl α).toPartialEquiv = PartialEquiv.refl α := rfl @[simp, mfld_simps] theorem symm_toPartialEquiv : e.symm.toPartialEquiv = e.toPartialEquiv.symm := rfl @[simp, mfld_simps] theorem trans_toPartialEquiv : (e.trans e').toPartialEquiv = e.toPartialEquiv.trans e'.toPartialEquiv := PartialEquiv.ext (fun x => rfl) (fun x => rfl) (by simp [PartialEquiv.trans_source, Equiv.toPartialEquiv]) /-- Precompose a partial equivalence with an equivalence. We modify the source and target to have better definitional behavior. -/ @[simps!] def transPartialEquiv (e : α ≃ β) (f' : PartialEquiv β γ) : PartialEquiv α γ := (e.toPartialEquiv.trans f').copy _ rfl _ rfl (e ⁻¹' f'.source) (univ_inter _) f'.target (inter_univ _) theorem transPartialEquiv_eq_trans (e : α ≃ β) (f' : PartialEquiv β γ) : e.transPartialEquiv f' = e.toPartialEquiv.trans f' := PartialEquiv.copy_eq .. @[simp, mfld_simps] theorem transPartialEquiv_trans (e : α ≃ β) (f' : PartialEquiv β γ) (f'' : PartialEquiv γ δ) : (e.transPartialEquiv f').trans f'' = e.transPartialEquiv (f'.trans f'') := by simp only [transPartialEquiv_eq_trans, PartialEquiv.trans_assoc] @[simp, mfld_simps] theorem trans_transPartialEquiv (e : α ≃ β) (e' : β ≃ γ) (f'' : PartialEquiv γ δ) : (e.trans e').transPartialEquiv f'' = e.transPartialEquiv (e'.transPartialEquiv f'') := by simp only [transPartialEquiv_eq_trans, PartialEquiv.trans_assoc, trans_toPartialEquiv] end Equiv namespace PartialEquiv /-- Postcompose a partial equivalence with an equivalence. We modify the source and target to have better definitional behavior. -/ @[simps!] def transEquiv (e : PartialEquiv α β) (f' : β ≃ γ) : PartialEquiv α γ := (e.trans f'.toPartialEquiv).copy _ rfl _ rfl e.source (inter_univ _) (f'.symm ⁻¹' e.target) (univ_inter _) theorem transEquiv_eq_trans (e : PartialEquiv α β) (e' : β ≃ γ) : e.transEquiv e' = e.trans e'.toPartialEquiv := copy_eq .. @[simp, mfld_simps] theorem transEquiv_transEquiv (e : PartialEquiv α β) (f' : β ≃ γ) (f'' : γ ≃ δ) : (e.transEquiv f').transEquiv f'' = e.transEquiv (f'.trans f'') := by simp only [transEquiv_eq_trans, trans_assoc, Equiv.trans_toPartialEquiv] @[simp, mfld_simps] theorem trans_transEquiv (e : PartialEquiv α β) (e' : PartialEquiv β γ) (f'' : γ ≃ δ) : (e.trans e').transEquiv f'' = e.trans (e'.transEquiv f'') := by simp only [transEquiv_eq_trans, trans_assoc, Equiv.trans_toPartialEquiv] end PartialEquiv
Logic\Equiv\Set.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import Mathlib.Data.Set.Function import Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.Says /-! # Equivalences and sets In this file we provide lemmas linking equivalences to sets. Some notable definitions are: * `Equiv.ofInjective`: an injective function is (noncomputably) equivalent to its range. * `Equiv.setCongr`: two equal sets are equivalent as types. * `Equiv.Set.union`: a disjoint union of sets is equivalent to their `Sum`. This file is separate from `Equiv/Basic` such that we do not require the full lattice structure on sets before defining what an equivalence is. -/ open Function Set universe u v w z variable {α : Sort u} {β : Sort v} {γ : Sort w} namespace Equiv @[simp] theorem range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : range e = univ := eq_univ_of_forall e.surjective protected theorem image_eq_preimage {α β} (e : α ≃ β) (s : Set α) : e '' s = e.symm ⁻¹' s := Set.ext fun _ => mem_image_iff_of_inverse e.left_inv e.right_inv @[simp 1001] theorem _root_.Set.mem_image_equiv {α β} {S : Set α} {f : α ≃ β} {x : β} : x ∈ f '' S ↔ f.symm x ∈ S := Set.ext_iff.mp (f.image_eq_preimage S) x /-- Alias for `Equiv.image_eq_preimage` -/ theorem _root_.Set.image_equiv_eq_preimage_symm {α β} (S : Set α) (f : α ≃ β) : f '' S = f.symm ⁻¹' S := f.image_eq_preimage S /-- Alias for `Equiv.image_eq_preimage` -/ theorem _root_.Set.preimage_equiv_eq_image_symm {α β} (S : Set α) (f : β ≃ α) : f ⁻¹' S = f.symm '' S := (f.symm.image_eq_preimage S).symm -- Porting note: increased priority so this fires before `image_subset_iff` @[simp high] protected theorem symm_image_subset {α β} (e : α ≃ β) (s : Set α) (t : Set β) : e.symm '' t ⊆ s ↔ t ⊆ e '' s := by rw [image_subset_iff, e.image_eq_preimage] @[deprecated (since := "2024-01-19")] alias subset_image := Equiv.symm_image_subset -- Porting note: increased priority so this fires before `image_subset_iff` @[simp high] protected theorem subset_symm_image {α β} (e : α ≃ β) (s : Set α) (t : Set β) : s ⊆ e.symm '' t ↔ e '' s ⊆ t := calc s ⊆ e.symm '' t ↔ e.symm.symm '' s ⊆ t := by rw [e.symm.symm_image_subset] _ ↔ e '' s ⊆ t := by rw [e.symm_symm] @[deprecated (since := "2024-01-19")] alias subset_image' := Equiv.subset_symm_image @[simp] theorem symm_image_image {α β} (e : α ≃ β) (s : Set α) : e.symm '' (e '' s) = s := e.leftInverse_symm.image_image s theorem eq_image_iff_symm_image_eq {α β} (e : α ≃ β) (s : Set α) (t : Set β) : t = e '' s ↔ e.symm '' t = s := (e.symm.injective.image_injective.eq_iff' (e.symm_image_image s)).symm @[simp] theorem image_symm_image {α β} (e : α ≃ β) (s : Set β) : e '' (e.symm '' s) = s := e.symm.symm_image_image s @[simp] theorem image_preimage {α β} (e : α ≃ β) (s : Set β) : e '' (e ⁻¹' s) = s := e.surjective.image_preimage s @[simp] theorem preimage_image {α β} (e : α ≃ β) (s : Set α) : e ⁻¹' (e '' s) = s := e.injective.preimage_image s protected theorem image_compl {α β} (f : Equiv α β) (s : Set α) : f '' sᶜ = (f '' s)ᶜ := image_compl_eq f.bijective @[simp] theorem symm_preimage_preimage {α β} (e : α ≃ β) (s : Set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.rightInverse_symm.preimage_preimage s @[simp] theorem preimage_symm_preimage {α β} (e : α ≃ β) (s : Set α) : e ⁻¹' (e.symm ⁻¹' s) = s := e.leftInverse_symm.preimage_preimage s theorem preimage_subset {α β} (e : α ≃ β) (s t : Set β) : e ⁻¹' s ⊆ e ⁻¹' t ↔ s ⊆ t := e.surjective.preimage_subset_preimage_iff -- Porting note (#10618): removed `simp` attribute. `simp` can prove it. theorem image_subset {α β} (e : α ≃ β) (s t : Set α) : e '' s ⊆ e '' t ↔ s ⊆ t := image_subset_image_iff e.injective @[simp] theorem image_eq_iff_eq {α β} (e : α ≃ β) (s t : Set α) : e '' s = e '' t ↔ s = t := image_eq_image e.injective theorem preimage_eq_iff_eq_image {α β} (e : α ≃ β) (s t) : e ⁻¹' s = t ↔ s = e '' t := Set.preimage_eq_iff_eq_image e.bijective theorem eq_preimage_iff_image_eq {α β} (e : α ≃ β) (s t) : s = e ⁻¹' t ↔ e '' s = t := Set.eq_preimage_iff_image_eq e.bijective lemma setOf_apply_symm_eq_image_setOf {α β} (e : α ≃ β) (p : α → Prop) : {b | p (e.symm b)} = e '' {a | p a} := by rw [Equiv.image_eq_preimage, preimage_setOf_eq] @[simp] theorem prod_assoc_preimage {α β γ} {s : Set α} {t : Set β} {u : Set γ} : Equiv.prodAssoc α β γ ⁻¹' s ×ˢ t ×ˢ u = (s ×ˢ t) ×ˢ u := by ext simp [and_assoc] @[simp] theorem prod_assoc_symm_preimage {α β γ} {s : Set α} {t : Set β} {u : Set γ} : (Equiv.prodAssoc α β γ).symm ⁻¹' (s ×ˢ t) ×ˢ u = s ×ˢ t ×ˢ u := by ext simp [and_assoc] -- `@[simp]` doesn't like these lemmas, as it uses `Set.image_congr'` to turn `Equiv.prodAssoc` -- into a lambda expression and then unfold it. theorem prod_assoc_image {α β γ} {s : Set α} {t : Set β} {u : Set γ} : Equiv.prodAssoc α β γ '' (s ×ˢ t) ×ˢ u = s ×ˢ t ×ˢ u := by simpa only [Equiv.image_eq_preimage] using prod_assoc_symm_preimage theorem prod_assoc_symm_image {α β γ} {s : Set α} {t : Set β} {u : Set γ} : (Equiv.prodAssoc α β γ).symm '' s ×ˢ t ×ˢ u = (s ×ˢ t) ×ˢ u := by simpa only [Equiv.image_eq_preimage] using prod_assoc_preimage /-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/ def setProdEquivSigma {α β : Type*} (s : Set (α × β)) : s ≃ Σx : α, { y : β | (x, y) ∈ s } where toFun x := ⟨x.1.1, x.1.2, by simp⟩ invFun x := ⟨(x.1, x.2.1), x.2.2⟩ left_inv := fun ⟨⟨x, y⟩, h⟩ => rfl right_inv := fun ⟨x, y, h⟩ => rfl /-- The subtypes corresponding to equal sets are equivalent. -/ @[simps! apply] def setCongr {α : Type*} {s t : Set α} (h : s = t) : s ≃ t := subtypeEquivProp h -- We could construct this using `Equiv.Set.image e s e.injective`, -- but this definition provides an explicit inverse. /-- A set is equivalent to its image under an equivalence. -/ @[simps] def image {α β : Type*} (e : α ≃ β) (s : Set α) : s ≃ e '' s where toFun x := ⟨e x.1, by simp⟩ invFun y := ⟨e.symm y.1, by rcases y with ⟨-, ⟨a, ⟨m, rfl⟩⟩⟩ simpa using m⟩ left_inv x := by simp right_inv y := by simp namespace Set -- Porting note: Removed attribute @[simps apply symm_apply] /-- `univ α` is equivalent to `α`. -/ protected def univ (α) : @univ α ≃ α := ⟨Subtype.val, fun a => ⟨a, trivial⟩, fun ⟨_, _⟩ => rfl, fun _ => rfl⟩ /-- An empty set is equivalent to the `Empty` type. -/ protected def empty (α) : (∅ : Set α) ≃ Empty := equivEmpty _ /-- An empty set is equivalent to a `PEmpty` type. -/ protected def pempty (α) : (∅ : Set α) ≃ PEmpty := equivPEmpty _ /-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union' {α} {s t : Set α} (p : α → Prop) [DecidablePred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬p x) : (s ∪ t : Set α) ≃ s ⊕ t where toFun x := if hp : p x then Sum.inl ⟨_, x.2.resolve_right fun xt => ht _ xt hp⟩ else Sum.inr ⟨_, x.2.resolve_left fun xs => hp (hs _ xs)⟩ invFun o := match o with | Sum.inl x => ⟨x, Or.inl x.2⟩ | Sum.inr x => ⟨x, Or.inr x.2⟩ left_inv := fun ⟨x, h'⟩ => by by_cases h : p x <;> simp [h] right_inv o := by rcases o with (⟨x, h⟩ | ⟨x, h⟩) <;> [simp [hs _ h]; simp [ht _ h]] /-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union {α} {s t : Set α} [DecidablePred fun x => x ∈ s] (H : s ∩ t ⊆ ∅) : (s ∪ t : Set α) ≃ s ⊕ t := Set.union' (fun x => x ∈ s) (fun _ => id) fun _ xt xs => H ⟨xs, xt⟩ theorem union_apply_left {α} {s t : Set α} [DecidablePred fun x => x ∈ s] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : Set α)} (ha : ↑a ∈ s) : Equiv.Set.union H a = Sum.inl ⟨a, ha⟩ := dif_pos ha theorem union_apply_right {α} {s t : Set α} [DecidablePred fun x => x ∈ s] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : Set α)} (ha : ↑a ∈ t) : Equiv.Set.union H a = Sum.inr ⟨a, ha⟩ := dif_neg fun h => H ⟨h, ha⟩ @[simp] theorem union_symm_apply_left {α} {s t : Set α} [DecidablePred fun x => x ∈ s] (H : s ∩ t ⊆ ∅) (a : s) : (Equiv.Set.union H).symm (Sum.inl a) = ⟨a, by simp⟩ := rfl @[simp] theorem union_symm_apply_right {α} {s t : Set α} [DecidablePred fun x => x ∈ s] (H : s ∩ t ⊆ ∅) (a : t) : (Equiv.Set.union H).symm (Sum.inr a) = ⟨a, by simp⟩ := rfl /-- A singleton set is equivalent to a `PUnit` type. -/ protected def singleton {α} (a : α) : ({a} : Set α) ≃ PUnit.{u} := ⟨fun _ => PUnit.unit, fun _ => ⟨a, mem_singleton _⟩, fun ⟨x, h⟩ => by simp? at h says simp only [mem_singleton_iff] at h subst x rfl, fun ⟨⟩ => rfl⟩ /-- Equal sets are equivalent. TODO: this is the same as `Equiv.setCongr`! -/ @[simps! apply symm_apply] protected def ofEq {α : Type u} {s t : Set α} (h : s = t) : s ≃ t := Equiv.setCongr h /-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ PUnit`. -/ protected def insert {α} {s : Set.{u} α} [DecidablePred (· ∈ s)] {a : α} (H : a ∉ s) : (insert a s : Set α) ≃ s ⊕ PUnit.{u + 1} := calc (insert a s : Set α) ≃ ↥(s ∪ {a}) := Equiv.Set.ofEq (by simp) _ ≃ s ⊕ ({a} : Set α) := Equiv.Set.union fun x ⟨hx, _⟩ => by simp_all _ ≃ s ⊕ PUnit.{u + 1} := sumCongr (Equiv.refl _) (Equiv.Set.singleton _) @[simp] theorem insert_symm_apply_inl {α} {s : Set.{u} α} [DecidablePred (· ∈ s)] {a : α} (H : a ∉ s) (b : s) : (Equiv.Set.insert H).symm (Sum.inl b) = ⟨b, Or.inr b.2⟩ := rfl @[simp] theorem insert_symm_apply_inr {α} {s : Set.{u} α} [DecidablePred (· ∈ s)] {a : α} (H : a ∉ s) (b : PUnit.{u + 1}) : (Equiv.Set.insert H).symm (Sum.inr b) = ⟨a, Or.inl rfl⟩ := rfl @[simp] theorem insert_apply_left {α} {s : Set.{u} α} [DecidablePred (· ∈ s)] {a : α} (H : a ∉ s) : Equiv.Set.insert H ⟨a, Or.inl rfl⟩ = Sum.inr PUnit.unit := (Equiv.Set.insert H).apply_eq_iff_eq_symm_apply.2 rfl @[simp] theorem insert_apply_right {α} {s : Set.{u} α} [DecidablePred (· ∈ s)] {a : α} (H : a ∉ s) (b : s) : Equiv.Set.insert H ⟨b, Or.inr b.2⟩ = Sum.inl b := (Equiv.Set.insert H).apply_eq_iff_eq_symm_apply.2 rfl /-- If `s : Set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/ protected def sumCompl {α} (s : Set α) [DecidablePred (· ∈ s)] : s ⊕ (sᶜ : Set α) ≃ α := calc s ⊕ (sᶜ : Set α) ≃ ↥(s ∪ sᶜ) := (Equiv.Set.union (by simp [Set.ext_iff])).symm _ ≃ @univ α := Equiv.Set.ofEq (by simp) _ ≃ α := Equiv.Set.univ _ @[simp] theorem sumCompl_apply_inl {α : Type u} (s : Set α) [DecidablePred (· ∈ s)] (x : s) : Equiv.Set.sumCompl s (Sum.inl x) = x := rfl @[simp] theorem sumCompl_apply_inr {α : Type u} (s : Set α) [DecidablePred (· ∈ s)] (x : (sᶜ : Set α)) : Equiv.Set.sumCompl s (Sum.inr x) = x := rfl theorem sumCompl_symm_apply_of_mem {α : Type u} {s : Set α} [DecidablePred (· ∈ s)] {x : α} (hx : x ∈ s) : (Equiv.Set.sumCompl s).symm x = Sum.inl ⟨x, hx⟩ := by have : ((⟨x, Or.inl hx⟩ : (s ∪ sᶜ : Set α)) : α) ∈ s := hx rw [Equiv.Set.sumCompl] simpa using Set.union_apply_left (by simp) this theorem sumCompl_symm_apply_of_not_mem {α : Type u} {s : Set α} [DecidablePred (· ∈ s)] {x : α} (hx : x ∉ s) : (Equiv.Set.sumCompl s).symm x = Sum.inr ⟨x, hx⟩ := by have : ((⟨x, Or.inr hx⟩ : (s ∪ sᶜ : Set α)) : α) ∈ sᶜ := hx rw [Equiv.Set.sumCompl] simpa using Set.union_apply_right (by simp) this @[simp] theorem sumCompl_symm_apply {α : Type*} {s : Set α} [DecidablePred (· ∈ s)] {x : s} : (Equiv.Set.sumCompl s).symm x = Sum.inl x := by cases' x with x hx; exact Set.sumCompl_symm_apply_of_mem hx @[simp] theorem sumCompl_symm_apply_compl {α : Type*} {s : Set α} [DecidablePred (· ∈ s)] {x : (sᶜ : Set α)} : (Equiv.Set.sumCompl s).symm x = Sum.inr x := by cases' x with x hx; exact Set.sumCompl_symm_apply_of_not_mem hx /-- `sumDiffSubset s t` is the natural equivalence between `s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/ protected def sumDiffSubset {α} {s t : Set α} (h : s ⊆ t) [DecidablePred (· ∈ s)] : s ⊕ (t \ s : Set α) ≃ t := calc s ⊕ (t \ s : Set α) ≃ (s ∪ t \ s : Set α) := (Equiv.Set.union (by simp [inter_diff_self])).symm _ ≃ t := Equiv.Set.ofEq (by simp [union_diff_self, union_eq_self_of_subset_left h]) @[simp] theorem sumDiffSubset_apply_inl {α} {s t : Set α} (h : s ⊆ t) [DecidablePred (· ∈ s)] (x : s) : Equiv.Set.sumDiffSubset h (Sum.inl x) = inclusion h x := rfl @[simp] theorem sumDiffSubset_apply_inr {α} {s t : Set α} (h : s ⊆ t) [DecidablePred (· ∈ s)] (x : (t \ s : Set α)) : Equiv.Set.sumDiffSubset h (Sum.inr x) = inclusion diff_subset x := rfl theorem sumDiffSubset_symm_apply_of_mem {α} {s t : Set α} (h : s ⊆ t) [DecidablePred (· ∈ s)] {x : t} (hx : x.1 ∈ s) : (Equiv.Set.sumDiffSubset h).symm x = Sum.inl ⟨x, hx⟩ := by apply (Equiv.Set.sumDiffSubset h).injective simp only [apply_symm_apply, sumDiffSubset_apply_inl] exact Subtype.eq rfl theorem sumDiffSubset_symm_apply_of_not_mem {α} {s t : Set α} (h : s ⊆ t) [DecidablePred (· ∈ s)] {x : t} (hx : x.1 ∉ s) : (Equiv.Set.sumDiffSubset h).symm x = Sum.inr ⟨x, ⟨x.2, hx⟩⟩ := by apply (Equiv.Set.sumDiffSubset h).injective simp only [apply_symm_apply, sumDiffSubset_apply_inr] exact Subtype.eq rfl /-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent to `s ⊕ t`. -/ protected def unionSumInter {α : Type u} (s t : Set α) [DecidablePred (· ∈ s)] : (s ∪ t : Set α) ⊕ (s ∩ t : Set α) ≃ s ⊕ t := calc (s ∪ t : Set α) ⊕ (s ∩ t : Set α) ≃ (s ∪ t \ s : Set α) ⊕ (s ∩ t : Set α) := by rw [union_diff_self] _ ≃ (s ⊕ (t \ s : Set α)) ⊕ (s ∩ t : Set α) := sumCongr (Set.union <| subset_empty_iff.2 (inter_diff_self _ _)) (Equiv.refl _) _ ≃ s ⊕ ((t \ s : Set α) ⊕ (s ∩ t : Set α)) := sumAssoc _ _ _ _ ≃ s ⊕ (t \ s ∪ s ∩ t : Set α) := sumCongr (Equiv.refl _) (by refine (Set.union' (· ∉ s) ?_ ?_).symm exacts [fun x hx => hx.2, fun x hx => not_not_intro hx.1]) _ ≃ s ⊕ t := by { rw [(_ : t \ s ∪ s ∩ t = t)] rw [union_comm, inter_comm, inter_union_diff] } /-- Given an equivalence `e₀` between sets `s : Set α` and `t : Set β`, the set of equivalences `e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences between `sᶜ` and `tᶜ`. -/ protected def compl {α : Type u} {β : Type v} {s : Set α} {t : Set β} [DecidablePred (· ∈ s)] [DecidablePred (· ∈ t)] (e₀ : s ≃ t) : { e : α ≃ β // ∀ x : s, e x = e₀ x } ≃ ((sᶜ : Set α) ≃ (tᶜ : Set β)) where toFun e := subtypeEquiv e fun a => not_congr <| Iff.symm <| MapsTo.mem_iff (mapsTo_iff_exists_map_subtype.2 ⟨e₀, e.2⟩) (SurjOn.mapsTo_compl (surjOn_iff_exists_map_subtype.2 ⟨t, e₀, Subset.refl t, e₀.surjective, e.2⟩) e.1.injective) invFun e₁ := Subtype.mk (calc α ≃ s ⊕ (sᶜ : Set α) := (Set.sumCompl s).symm _ ≃ t ⊕ (tᶜ : Set β) := e₀.sumCongr e₁ _ ≃ β := Set.sumCompl t ) fun x => by simp only [Sum.map_inl, trans_apply, sumCongr_apply, Set.sumCompl_apply_inl, Set.sumCompl_symm_apply, Trans.trans] left_inv e := by ext x by_cases hx : x ∈ s · simp only [Set.sumCompl_symm_apply_of_mem hx, ← e.prop ⟨x, hx⟩, Sum.map_inl, sumCongr_apply, trans_apply, Subtype.coe_mk, Set.sumCompl_apply_inl, Trans.trans] · simp only [Set.sumCompl_symm_apply_of_not_mem hx, Sum.map_inr, subtypeEquiv_apply, Set.sumCompl_apply_inr, trans_apply, sumCongr_apply, Subtype.coe_mk, Trans.trans] right_inv e := Equiv.ext fun x => by simp only [Sum.map_inr, subtypeEquiv_apply, Set.sumCompl_apply_inr, Function.comp_apply, sumCongr_apply, Equiv.coe_trans, Subtype.coe_eta, Subtype.coe_mk, Trans.trans, Set.sumCompl_symm_apply_compl] /-- The set product of two sets is equivalent to the type product of their coercions to types. -/ protected def prod {α β} (s : Set α) (t : Set β) : ↥(s ×ˢ t) ≃ s × t := @subtypeProdEquivProd α β s t /-- The set `Set.pi Set.univ s` is equivalent to `Π a, s a`. -/ @[simps] protected def univPi {α : Type*} {β : α → Type*} (s : ∀ a, Set (β a)) : pi univ s ≃ ∀ a, s a where toFun f a := ⟨(f : ∀ a, β a) a, f.2 a (mem_univ a)⟩ invFun f := ⟨fun a => f a, fun a _ => (f a).2⟩ left_inv := fun ⟨f, hf⟩ => by ext a rfl right_inv f := by ext a rfl /-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/ protected noncomputable def imageOfInjOn {α β} (f : α → β) (s : Set α) (H : InjOn f s) : s ≃ f '' s := ⟨fun p => ⟨f p, mem_image_of_mem f p.2⟩, fun p => ⟨Classical.choose p.2, (Classical.choose_spec p.2).1⟩, fun ⟨_, h⟩ => Subtype.eq (H (Classical.choose_spec (mem_image_of_mem f h)).1 h (Classical.choose_spec (mem_image_of_mem f h)).2), fun ⟨_, h⟩ => Subtype.eq (Classical.choose_spec h).2⟩ /-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/ @[simps! apply] protected noncomputable def image {α β} (f : α → β) (s : Set α) (H : Injective f) : s ≃ f '' s := Equiv.Set.imageOfInjOn f s H.injOn @[simp] protected theorem image_symm_apply {α β} (f : α → β) (s : Set α) (H : Injective f) (x : α) (h : f x ∈ f '' s) : (Set.image f s H).symm ⟨f x, h⟩ = ⟨x, H.mem_set_image.1 h⟩ := (Equiv.symm_apply_eq _).2 rfl theorem image_symm_preimage {α β} {f : α → β} (hf : Injective f) (u s : Set α) : (fun x => (Set.image f s hf).symm x : f '' s → α) ⁻¹' u = Subtype.val ⁻¹' (f '' u) := by ext ⟨b, a, has, rfl⟩ simp [hf.eq_iff] /-- If `α` is equivalent to `β`, then `Set α` is equivalent to `Set β`. -/ @[simps] protected def congr {α β : Type*} (e : α ≃ β) : Set α ≃ Set β := ⟨fun s => e '' s, fun t => e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ /-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/ protected def sep {α : Type u} (s : Set α) (t : α → Prop) : ({ x ∈ s | t x } : Set α) ≃ { x : s | t x } := (Equiv.subtypeSubtypeEquivSubtypeInter s t).symm /-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `Set S`. -/ protected def powerset {α} (S : Set α) : 𝒫 S ≃ Set S where toFun := fun x : 𝒫 S => Subtype.val ⁻¹' (x : Set α) invFun := fun x : Set S => ⟨Subtype.val '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩ left_inv x := by ext y;exact ⟨fun ⟨⟨_, _⟩, h, rfl⟩ => h, fun h => ⟨⟨_, x.2 h⟩, h, rfl⟩⟩ right_inv x := by ext; simp /-- If `s` is a set in `range f`, then its image under `rangeSplitting f` is in bijection (via `f`) with `s`. -/ @[simps] noncomputable def rangeSplittingImageEquiv {α β : Type*} (f : α → β) (s : Set (range f)) : rangeSplitting f '' s ≃ s where toFun x := ⟨⟨f x, by simp⟩, by rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩ simpa [apply_rangeSplitting f] using m⟩ invFun x := ⟨rangeSplitting f x, ⟨x, ⟨x.2, rfl⟩⟩⟩ left_inv x := by rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩ simp [apply_rangeSplitting f] right_inv x := by simp [apply_rangeSplitting f] /-- Equivalence between the range of `Sum.inl : α → α ⊕ β` and `α`. -/ @[simps symm_apply_coe] def rangeInl (α β : Type*) : Set.range (Sum.inl : α → α ⊕ β) ≃ α where toFun | ⟨.inl x, _⟩ => x | ⟨.inr _, h⟩ => False.elim <| by rcases h with ⟨x, h'⟩; cases h' invFun x := ⟨.inl x, mem_range_self _⟩ left_inv := fun ⟨_, _, rfl⟩ => rfl right_inv x := rfl @[simp] lemma rangeInl_apply_inl {α : Type*} (β : Type*) (x : α) : (rangeInl α β) ⟨.inl x, mem_range_self _⟩ = x := rfl /-- Equivalence between the range of `Sum.inr : β → α ⊕ β` and `β`. -/ @[simps symm_apply_coe] def rangeInr (α β : Type*) : Set.range (Sum.inr : β → α ⊕ β) ≃ β where toFun | ⟨.inl _, h⟩ => False.elim <| by rcases h with ⟨x, h'⟩; cases h' | ⟨.inr x, _⟩ => x invFun x := ⟨.inr x, mem_range_self _⟩ left_inv := fun ⟨_, _, rfl⟩ => rfl right_inv x := rfl @[simp] lemma rangeInr_apply_inr (α : Type*) {β : Type*} (x : β) : (rangeInr α β) ⟨.inr x, mem_range_self _⟩ = x := rfl end Set /-- If `f : α → β` has a left-inverse when `α` is nonempty, then `α` is computably equivalent to the range of `f`. While awkward, the `Nonempty α` hypothesis on `f_inv` and `hf` allows this to be used when `α` is empty too. This hypothesis is absent on analogous definitions on stronger `Equiv`s like `LinearEquiv.ofLeftInverse` and `RingEquiv.ofLeftInverse` as their typeclass assumptions are already sufficient to ensure non-emptiness. -/ @[simps] def ofLeftInverse {α β : Sort _} (f : α → β) (f_inv : Nonempty α → β → α) (hf : ∀ h : Nonempty α, LeftInverse (f_inv h) f) : α ≃ range f where toFun a := ⟨f a, a, rfl⟩ invFun b := f_inv (nonempty_of_exists b.2) b left_inv a := hf ⟨a⟩ a right_inv := fun ⟨b, a, ha⟩ => Subtype.eq <| show f (f_inv ⟨a⟩ b) = b from Eq.trans (congr_arg f <| ha ▸ hf _ a) ha /-- If `f : α → β` has a left-inverse, then `α` is computably equivalent to the range of `f`. Note that if `α` is empty, no such `f_inv` exists and so this definition can't be used, unlike the stronger but less convenient `ofLeftInverse`. -/ abbrev ofLeftInverse' {α β : Sort _} (f : α → β) (f_inv : β → α) (hf : LeftInverse f_inv f) : α ≃ range f := ofLeftInverse f (fun _ => f_inv) fun _ => hf /-- If `f : α → β` is an injective function, then domain `α` is equivalent to the range of `f`. -/ @[simps! apply] noncomputable def ofInjective {α β} (f : α → β) (hf : Injective f) : α ≃ range f := Equiv.ofLeftInverse f (fun _ => Function.invFun f) fun _ => Function.leftInverse_invFun hf theorem apply_ofInjective_symm {α β} {f : α → β} (hf : Injective f) (b : range f) : f ((ofInjective f hf).symm b) = b := Subtype.ext_iff.1 <| (ofInjective f hf).apply_symm_apply b @[simp] theorem ofInjective_symm_apply {α β} {f : α → β} (hf : Injective f) (a : α) : (ofInjective f hf).symm ⟨f a, ⟨a, rfl⟩⟩ = a := by apply (ofInjective f hf).injective simp [apply_ofInjective_symm hf] theorem coe_ofInjective_symm {α β} {f : α → β} (hf : Injective f) : ((ofInjective f hf).symm : range f → α) = rangeSplitting f := by ext ⟨y, x, rfl⟩ apply hf simp [apply_rangeSplitting f] @[simp] theorem self_comp_ofInjective_symm {α β} {f : α → β} (hf : Injective f) : f ∘ (ofInjective f hf).symm = Subtype.val := funext fun x => apply_ofInjective_symm hf x theorem ofLeftInverse_eq_ofInjective {α β : Type*} (f : α → β) (f_inv : Nonempty α → β → α) (hf : ∀ h : Nonempty α, LeftInverse (f_inv h) f) : ofLeftInverse f f_inv hf = ofInjective f ((isEmpty_or_nonempty α).elim (fun h _ _ _ => Subsingleton.elim _ _) (fun h => (hf h).injective)) := by ext simp theorem ofLeftInverse'_eq_ofInjective {α β : Type*} (f : α → β) (f_inv : β → α) (hf : LeftInverse f_inv f) : ofLeftInverse' f f_inv hf = ofInjective f hf.injective := by ext simp protected theorem set_forall_iff {α β} (e : α ≃ β) {p : Set α → Prop} : (∀ a, p a) ↔ ∀ a, p (e ⁻¹' a) := e.injective.preimage_surjective.forall theorem preimage_piEquivPiSubtypeProd_symm_pi {α : Type*} {β : α → Type*} (p : α → Prop) [DecidablePred p] (s : ∀ i, Set (β i)) : (piEquivPiSubtypeProd p β).symm ⁻¹' pi univ s = (pi univ fun i : { i // p i } => s i) ×ˢ pi univ fun i : { i // ¬p i } => s i := by ext ⟨f, g⟩ simp only [mem_preimage, mem_univ_pi, prod_mk_mem_set_prod_eq, Subtype.forall, ← forall_and] refine forall_congr' fun i => ?_ dsimp only [Subtype.coe_mk] by_cases hi : p i <;> simp [hi] -- See also `Equiv.sigmaFiberEquiv`. /-- `sigmaPreimageEquiv f` for `f : α → β` is the natural equivalence between the type of all preimages of points under `f` and the total space `α`. -/ @[simps!] def sigmaPreimageEquiv {α β} (f : α → β) : (Σb, f ⁻¹' {b}) ≃ α := sigmaFiberEquiv f -- See also `Equiv.ofFiberEquiv`. /-- A family of equivalences between preimages of points gives an equivalence between domains. -/ @[simps!] def ofPreimageEquiv {α β γ} {f : α → γ} {g : β → γ} (e : ∀ c, f ⁻¹' {c} ≃ g ⁻¹' {c}) : α ≃ β := Equiv.ofFiberEquiv e theorem ofPreimageEquiv_map {α β γ} {f : α → γ} {g : β → γ} (e : ∀ c, f ⁻¹' {c} ≃ g ⁻¹' {c}) (a : α) : g (ofPreimageEquiv e a) = f a := Equiv.ofFiberEquiv_map e a end Equiv /-- If a function is a bijection between two sets `s` and `t`, then it induces an equivalence between the types `↥s` and `↥t`. -/ noncomputable def Set.BijOn.equiv {α : Type*} {β : Type*} {s : Set α} {t : Set β} (f : α → β) (h : BijOn f s t) : s ≃ t := Equiv.ofBijective _ h.bijective /-- The composition of an updated function with an equiv on a subtype can be expressed as an updated function. -/ -- Porting note: replace `s : Set α` and `: s` with `p : α → Prop` and `: Subtype p`, since the -- former now unfolds syntactically to a less general case of the latter. theorem dite_comp_equiv_update {α : Type*} {β : Sort*} {γ : Sort*} {p : α → Prop} (e : β ≃ Subtype p) (v : β → γ) (w : α → γ) (j : β) (x : γ) [DecidableEq β] [DecidableEq α] [∀ j, Decidable (p j)] : (fun i : α => if h : p i then (Function.update v j x) (e.symm ⟨i, h⟩) else w i) = Function.update (fun i : α => if h : p i then v (e.symm ⟨i, h⟩) else w i) (e j) x := by ext i by_cases h : p i · rw [dif_pos h, Function.update_apply_equiv_apply, Equiv.symm_symm, Function.update_apply, Function.update_apply, dif_pos h] have h_coe : (⟨i, h⟩ : Subtype p) = e j ↔ i = e j := Subtype.ext_iff.trans (by rw [Subtype.coe_mk]) simp [h_coe] · have : i ≠ e j := by contrapose! h have : p (e j : α) := (e j).2 rwa [← h] at this simp [h, this] section Swap variable {α : Type*} [DecidableEq α] {a b : α} {s : Set α} theorem Equiv.swap_bijOn_self (hs : a ∈ s ↔ b ∈ s) : BijOn (Equiv.swap a b) s s := by refine ⟨fun x hx ↦ ?_, (Equiv.injective _).injOn, fun x hx ↦ ?_⟩ · obtain (rfl | hxa) := eq_or_ne x a · rwa [swap_apply_left, ← hs] obtain (rfl | hxb) := eq_or_ne x b · rwa [swap_apply_right, hs] rwa [swap_apply_of_ne_of_ne hxa hxb] obtain (rfl | hxa) := eq_or_ne x a · simp [hs.1 hx] obtain (rfl | hxb) := eq_or_ne x b · simp [hs.2 hx] exact ⟨x, hx, swap_apply_of_ne_of_ne hxa hxb⟩ theorem Equiv.swap_bijOn_exchange (ha : a ∈ s) (hb : b ∉ s) : BijOn (Equiv.swap a b) s (insert b (s \ {a})) := by refine ⟨fun x hx ↦ ?_, (Equiv.injective _).injOn, fun x hx ↦ ?_⟩ · obtain (rfl | hxa) := eq_or_ne x a · simp [swap_apply_left] rw [swap_apply_of_ne_of_ne hxa (by rintro rfl; contradiction)] exact .inr ⟨hx, hxa⟩ obtain (rfl | hxb) := eq_or_ne x b · exact ⟨a, ha, by simp⟩ simp only [mem_insert_iff, mem_diff, mem_singleton_iff, or_iff_right hxb] at hx exact ⟨x, hx.1, swap_apply_of_ne_of_ne hx.2 hxb⟩ end Swap
Logic\Equiv\TransferInstance.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 -/ import Mathlib.Algebra.Algebra.Equiv import Mathlib.Algebra.Field.Basic import Mathlib.Logic.Equiv.Defs import Mathlib.Logic.Small.Defs /-! # Transfer algebraic structures across `Equiv`s In this file we prove theorems of the following form: if `β` has a group structure and `α ≃ β` then `α` has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. Note that most of these constructions can also be obtained using the `transport` tactic. ### Implementation details When adding new definitions that transfer type-classes across an equivalence, please use `abbrev`. See note [reducible non-instances]. ## Tags equiv, group, ring, field, module, algebra -/ universe u v variable {α : Type u} {β : Type v} namespace Equiv section Instances variable (e : α ≃ β) /-- Transfer `One` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `Zero` across an `Equiv`"] protected def one [One β] : One α := ⟨e.symm 1⟩ @[to_additive] theorem one_def [One β] : letI := e.one 1 = e.symm 1 := rfl @[to_additive] noncomputable instance [Small.{v} α] [One α] : One (Shrink.{v} α) := (equivShrink α).symm.one /-- Transfer `Mul` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `Add` across an `Equiv`"] protected def mul [Mul β] : Mul α := ⟨fun x y => e.symm (e x * e y)⟩ @[to_additive] theorem mul_def [Mul β] (x y : α) : letI := Equiv.mul e x * y = e.symm (e x * e y) := rfl @[to_additive] noncomputable instance [Small.{v} α] [Mul α] : Mul (Shrink.{v} α) := (equivShrink α).symm.mul /-- Transfer `Div` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `Sub` across an `Equiv`"] protected def div [Div β] : Div α := ⟨fun x y => e.symm (e x / e y)⟩ @[to_additive] theorem div_def [Div β] (x y : α) : letI := Equiv.div e x / y = e.symm (e x / e y) := rfl @[to_additive] noncomputable instance [Small.{v} α] [Div α] : Div (Shrink.{v} α) := (equivShrink α).symm.div -- Porting note: this should be called `inv`, -- but we already have an `Equiv.inv` (which perhaps should move to `Perm.inv`?) /-- Transfer `Inv` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `Neg` across an `Equiv`"] protected def Inv [Inv β] : Inv α := ⟨fun x => e.symm (e x)⁻¹⟩ @[to_additive] theorem inv_def [Inv β] (x : α) : letI := Equiv.Inv e x⁻¹ = e.symm (e x)⁻¹ := rfl @[to_additive] noncomputable instance [Small.{v} α] [Inv α] : Inv (Shrink.{v} α) := (equivShrink α).symm.Inv /-- Transfer `SMul` across an `Equiv` -/ protected abbrev smul (R : Type*) [SMul R β] : SMul R α := ⟨fun r x => e.symm (r • e x)⟩ theorem smul_def {R : Type*} [SMul R β] (r : R) (x : α) : letI := e.smul R r • x = e.symm (r • e x) := rfl noncomputable instance [Small.{v} α] (R : Type*) [SMul R α] : SMul R (Shrink.{v} α) := (equivShrink α).symm.smul R /-- Transfer `Pow` across an `Equiv` -/ @[reducible, to_additive existing smul] protected def pow (N : Type*) [Pow β N] : Pow α N := ⟨fun x n => e.symm (e x ^ n)⟩ theorem pow_def {N : Type*} [Pow β N] (n : N) (x : α) : letI := e.pow N x ^ n = e.symm (e x ^ n) := rfl noncomputable instance [Small.{v} α] (N : Type*) [Pow α N] : Pow (Shrink.{v} α) N := (equivShrink α).symm.pow N /-- An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β` where the multiplicative structure on `α` is the one obtained by transporting a multiplicative structure on `β` back along `e`. -/ @[to_additive "An equivalence `e : α ≃ β` gives an additive equivalence `α ≃+ β` where the additive structure on `α` is the one obtained by transporting an additive structure on `β` back along `e`."] def mulEquiv (e : α ≃ β) [Mul β] : let mul := Equiv.mul e α ≃* β := by intros exact { e with map_mul' := fun x y => by apply e.symm.injective simp [mul_def] } @[to_additive (attr := simp)] theorem mulEquiv_apply (e : α ≃ β) [Mul β] (a : α) : (mulEquiv e) a = e a := rfl @[to_additive] theorem mulEquiv_symm_apply (e : α ≃ β) [Mul β] (b : β) : letI := Equiv.mul e (mulEquiv e).symm b = e.symm b := rfl /-- Shrink `α` to a smaller universe preserves multiplication. -/ @[to_additive "Shrink `α` to a smaller universe preserves addition."] noncomputable def _root_.Shrink.mulEquiv [Small.{v} α] [Mul α] : Shrink.{v} α ≃* α := (equivShrink α).symm.mulEquiv /-- An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β` where the ring structure on `α` is the one obtained by transporting a ring structure on `β` back along `e`. -/ def ringEquiv (e : α ≃ β) [Add β] [Mul β] : by let add := Equiv.add e let mul := Equiv.mul e exact α ≃+* β := by intros exact { e with map_add' := fun x y => by apply e.symm.injective simp [add_def] map_mul' := fun x y => by apply e.symm.injective simp [mul_def] } @[simp] theorem ringEquiv_apply (e : α ≃ β) [Add β] [Mul β] (a : α) : (ringEquiv e) a = e a := rfl theorem ringEquiv_symm_apply (e : α ≃ β) [Add β] [Mul β] (b : β) : by letI := Equiv.add e letI := Equiv.mul e exact (ringEquiv e).symm b = e.symm b := rfl variable (α) in /-- Shrink `α` to a smaller universe preserves ring structure. -/ noncomputable def _root_.Shrink.ringEquiv [Small.{v} α] [Ring α] : Shrink.{v} α ≃+* α := (equivShrink α).symm.ringEquiv /-- Transfer `Semigroup` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `add_semigroup` across an `Equiv`"] protected def semigroup [Semigroup β] : Semigroup α := by let mul := e.mul apply e.injective.semigroup _; intros; exact e.apply_symm_apply _ @[to_additive] noncomputable instance [Small.{v} α] [Semigroup α] : Semigroup (Shrink.{v} α) := (equivShrink α).symm.semigroup /-- Transfer `SemigroupWithZero` across an `Equiv` -/ protected abbrev semigroupWithZero [SemigroupWithZero β] : SemigroupWithZero α := by let mul := e.mul let zero := e.zero apply e.injective.semigroupWithZero _ <;> intros <;> exact e.apply_symm_apply _ @[to_additive] noncomputable instance [Small.{v} α] [SemigroupWithZero α] : SemigroupWithZero (Shrink.{v} α) := (equivShrink α).symm.semigroupWithZero /-- Transfer `CommSemigroup` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `AddCommSemigroup` across an `Equiv`"] protected def commSemigroup [CommSemigroup β] : CommSemigroup α := by let mul := e.mul apply e.injective.commSemigroup _; intros; exact e.apply_symm_apply _ @[to_additive] noncomputable instance [Small.{v} α] [CommSemigroup α] : CommSemigroup (Shrink.{v} α) := (equivShrink α).symm.commSemigroup /-- Transfer `MulZeroClass` across an `Equiv` -/ protected abbrev mulZeroClass [MulZeroClass β] : MulZeroClass α := by let zero := e.zero let mul := e.mul apply e.injective.mulZeroClass _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [MulZeroClass α] : MulZeroClass (Shrink.{v} α) := (equivShrink α).symm.mulZeroClass /-- Transfer `MulOneClass` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `AddZeroClass` across an `Equiv`"] protected def mulOneClass [MulOneClass β] : MulOneClass α := by let one := e.one let mul := e.mul apply e.injective.mulOneClass _ <;> intros <;> exact e.apply_symm_apply _ @[to_additive] noncomputable instance [Small.{v} α] [MulOneClass α] : MulOneClass (Shrink.{v} α) := (equivShrink α).symm.mulOneClass /-- Transfer `MulZeroOneClass` across an `Equiv` -/ protected abbrev mulZeroOneClass [MulZeroOneClass β] : MulZeroOneClass α := by let zero := e.zero let one := e.one let mul := e.mul apply e.injective.mulZeroOneClass _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [MulZeroOneClass α] : MulZeroOneClass (Shrink.{v} α) := (equivShrink α).symm.mulZeroOneClass /-- Transfer `Monoid` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `AddMonoid` across an `Equiv`"] protected def monoid [Monoid β] : Monoid α := by let one := e.one let mul := e.mul let pow := e.pow ℕ apply e.injective.monoid _ <;> intros <;> exact e.apply_symm_apply _ @[to_additive] noncomputable instance [Small.{v} α] [Monoid α] : Monoid (Shrink.{v} α) := (equivShrink α).symm.monoid /-- Transfer `CommMonoid` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `AddCommMonoid` across an `Equiv`"] protected def commMonoid [CommMonoid β] : CommMonoid α := by let one := e.one let mul := e.mul let pow := e.pow ℕ apply e.injective.commMonoid _ <;> intros <;> exact e.apply_symm_apply _ @[to_additive] noncomputable instance [Small.{v} α] [CommMonoid α] : CommMonoid (Shrink.{v} α) := (equivShrink α).symm.commMonoid /-- Transfer `Group` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `AddGroup` across an `Equiv`"] protected def group [Group β] : Group α := by let one := e.one let mul := e.mul let inv := e.Inv let div := e.div let npow := e.pow ℕ let zpow := e.pow ℤ apply e.injective.group _ <;> intros <;> exact e.apply_symm_apply _ @[to_additive] noncomputable instance [Small.{v} α] [Group α] : Group (Shrink.{v} α) := (equivShrink α).symm.group /-- Transfer `CommGroup` across an `Equiv` -/ @[to_additive (attr := reducible) "Transfer `AddCommGroup` across an `Equiv`"] protected def commGroup [CommGroup β] : CommGroup α := by let one := e.one let mul := e.mul let inv := e.Inv let div := e.div let npow := e.pow ℕ let zpow := e.pow ℤ apply e.injective.commGroup _ <;> intros <;> exact e.apply_symm_apply _ @[to_additive] noncomputable instance [Small.{v} α] [CommGroup α] : CommGroup (Shrink.{v} α) := (equivShrink α).symm.commGroup /-- Transfer `NonUnitalNonAssocSemiring` across an `Equiv` -/ protected abbrev nonUnitalNonAssocSemiring [NonUnitalNonAssocSemiring β] : NonUnitalNonAssocSemiring α := by let zero := e.zero let add := e.add let mul := e.mul let nsmul := e.smul ℕ apply e.injective.nonUnitalNonAssocSemiring _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [NonUnitalNonAssocSemiring α] : NonUnitalNonAssocSemiring (Shrink.{v} α) := (equivShrink α).symm.nonUnitalNonAssocSemiring /-- Transfer `NonUnitalSemiring` across an `Equiv` -/ protected abbrev nonUnitalSemiring [NonUnitalSemiring β] : NonUnitalSemiring α := by let zero := e.zero let add := e.add let mul := e.mul let nsmul := e.smul ℕ apply e.injective.nonUnitalSemiring _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [NonUnitalSemiring α] : NonUnitalSemiring (Shrink.{v} α) := (equivShrink α).symm.nonUnitalSemiring /-- Transfer `AddMonoidWithOne` across an `Equiv` -/ protected abbrev addMonoidWithOne [AddMonoidWithOne β] : AddMonoidWithOne α := { e.addMonoid, e.one with natCast := fun n => e.symm n natCast_zero := e.injective (by simp [zero_def]) natCast_succ := fun n => e.injective (by simp [add_def, one_def]) } noncomputable instance [Small.{v} α] [AddMonoidWithOne α] : AddMonoidWithOne (Shrink.{v} α) := (equivShrink α).symm.addMonoidWithOne /-- Transfer `AddGroupWithOne` across an `Equiv` -/ protected abbrev addGroupWithOne [AddGroupWithOne β] : AddGroupWithOne α := { e.addMonoidWithOne, e.addGroup with intCast := fun n => e.symm n intCast_ofNat := fun n => by simp only [Int.cast_natCast]; rfl intCast_negSucc := fun n => congr_arg e.symm <| (Int.cast_negSucc _).trans <| congr_arg _ (e.apply_symm_apply _).symm } noncomputable instance [Small.{v} α] [AddGroupWithOne α] : AddGroupWithOne (Shrink.{v} α) := (equivShrink α).symm.addGroupWithOne /-- Transfer `NonAssocSemiring` across an `Equiv` -/ protected abbrev nonAssocSemiring [NonAssocSemiring β] : NonAssocSemiring α := by let mul := e.mul let add_monoid_with_one := e.addMonoidWithOne apply e.injective.nonAssocSemiring _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [NonAssocSemiring α] : NonAssocSemiring (Shrink.{v} α) := (equivShrink α).symm.nonAssocSemiring /-- Transfer `Semiring` across an `Equiv` -/ protected abbrev semiring [Semiring β] : Semiring α := by let mul := e.mul let add_monoid_with_one := e.addMonoidWithOne let npow := e.pow ℕ apply e.injective.semiring _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [Semiring α] : Semiring (Shrink.{v} α) := (equivShrink α).symm.semiring /-- Transfer `NonUnitalCommSemiring` across an `Equiv` -/ protected abbrev nonUnitalCommSemiring [NonUnitalCommSemiring β] : NonUnitalCommSemiring α := by let zero := e.zero let add := e.add let mul := e.mul let nsmul := e.smul ℕ apply e.injective.nonUnitalCommSemiring _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [NonUnitalCommSemiring α] : NonUnitalCommSemiring (Shrink.{v} α) := (equivShrink α).symm.nonUnitalCommSemiring /-- Transfer `CommSemiring` across an `Equiv` -/ protected abbrev commSemiring [CommSemiring β] : CommSemiring α := by let mul := e.mul let add_monoid_with_one := e.addMonoidWithOne let npow := e.pow ℕ apply e.injective.commSemiring _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [CommSemiring α] : CommSemiring (Shrink.{v} α) := (equivShrink α).symm.commSemiring /-- Transfer `NonUnitalNonAssocRing` across an `Equiv` -/ protected abbrev nonUnitalNonAssocRing [NonUnitalNonAssocRing β] : NonUnitalNonAssocRing α := by let zero := e.zero let add := e.add let mul := e.mul let neg := e.Neg let sub := e.sub let nsmul := e.smul ℕ let zsmul := e.smul ℤ apply e.injective.nonUnitalNonAssocRing _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [NonUnitalNonAssocRing α] : NonUnitalNonAssocRing (Shrink.{v} α) := (equivShrink α).symm.nonUnitalNonAssocRing /-- Transfer `NonUnitalRing` across an `Equiv` -/ protected abbrev nonUnitalRing [NonUnitalRing β] : NonUnitalRing α := by let zero := e.zero let add := e.add let mul := e.mul let neg := e.Neg let sub := e.sub let nsmul := e.smul ℕ let zsmul := e.smul ℤ apply e.injective.nonUnitalRing _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [NonUnitalRing α] : NonUnitalRing (Shrink.{v} α) := (equivShrink α).symm.nonUnitalRing /-- Transfer `NonAssocRing` across an `Equiv` -/ protected abbrev nonAssocRing [NonAssocRing β] : NonAssocRing α := by let add_group_with_one := e.addGroupWithOne let mul := e.mul apply e.injective.nonAssocRing _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [NonAssocRing α] : NonAssocRing (Shrink.{v} α) := (equivShrink α).symm.nonAssocRing /-- Transfer `Ring` across an `Equiv` -/ protected abbrev ring [Ring β] : Ring α := by let mul := e.mul let add_group_with_one := e.addGroupWithOne let npow := e.pow ℕ apply e.injective.ring _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [Ring α] : Ring (Shrink.{v} α) := (equivShrink α).symm.ring /-- Transfer `NonUnitalCommRing` across an `Equiv` -/ protected abbrev nonUnitalCommRing [NonUnitalCommRing β] : NonUnitalCommRing α := by let zero := e.zero let add := e.add let mul := e.mul let neg := e.Neg let sub := e.sub let nsmul := e.smul ℕ let zsmul := e.smul ℤ apply e.injective.nonUnitalCommRing _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [NonUnitalCommRing α] : NonUnitalCommRing (Shrink.{v} α) := (equivShrink α).symm.nonUnitalCommRing /-- Transfer `CommRing` across an `Equiv` -/ protected abbrev commRing [CommRing β] : CommRing α := by let mul := e.mul let add_group_with_one := e.addGroupWithOne let npow := e.pow ℕ apply e.injective.commRing _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [CommRing α] : CommRing (Shrink.{v} α) := (equivShrink α).symm.commRing /-- Transfer `Nontrivial` across an `Equiv` -/ protected theorem nontrivial [Nontrivial β] : Nontrivial α := e.surjective.nontrivial noncomputable instance [Small.{v} α] [Nontrivial α] : Nontrivial (Shrink.{v} α) := (equivShrink α).symm.nontrivial /-- Transfer `IsDomain` across an `Equiv` -/ protected theorem isDomain [Ring α] [Ring β] [IsDomain β] (e : α ≃+* β) : IsDomain α := Function.Injective.isDomain e.toRingHom e.injective noncomputable instance [Small.{v} α] [Ring α] [IsDomain α] : IsDomain (Shrink.{v} α) := Equiv.isDomain (Shrink.ringEquiv α) /-- Transfer `NNRatCast` across an `Equiv` -/ protected abbrev nnratCast [NNRatCast β] : NNRatCast α where nnratCast q := e.symm q /-- Transfer `RatCast` across an `Equiv` -/ protected abbrev ratCast [RatCast β] : RatCast α where ratCast n := e.symm n noncomputable instance _root_.Shrink.instNNRatCast [Small.{v} α] [NNRatCast α] : NNRatCast (Shrink.{v} α) := (equivShrink α).symm.nnratCast noncomputable instance _root_.Shrink.instRatCast [Small.{v} α] [RatCast α] : RatCast (Shrink.{v} α) := (equivShrink α).symm.ratCast /-- Transfer `DivisionRing` across an `Equiv` -/ protected abbrev divisionRing [DivisionRing β] : DivisionRing α := by let add_group_with_one := e.addGroupWithOne let inv := e.Inv let div := e.div let mul := e.mul let npow := e.pow ℕ let zpow := e.pow ℤ let nnratCast := e.nnratCast let ratCast := e.ratCast let nnqsmul := e.smul ℚ≥0 let qsmul := e.smul ℚ apply e.injective.divisionRing _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [DivisionRing α] : DivisionRing (Shrink.{v} α) := (equivShrink α).symm.divisionRing /-- Transfer `Field` across an `Equiv` -/ protected abbrev field [Field β] : Field α := by let add_group_with_one := e.addGroupWithOne let neg := e.Neg let inv := e.Inv let div := e.div let mul := e.mul let npow := e.pow ℕ let zpow := e.pow ℤ let nnratCast := e.nnratCast let ratCast := e.ratCast let nnqsmul := e.smul ℚ≥0 let qsmul := e.smul ℚ apply e.injective.field _ <;> intros <;> exact e.apply_symm_apply _ noncomputable instance [Small.{v} α] [Field α] : Field (Shrink.{v} α) := (equivShrink α).symm.field section R variable (R : Type*) section variable [Monoid R] /-- Transfer `MulAction` across an `Equiv` -/ protected abbrev mulAction (e : α ≃ β) [MulAction R β] : MulAction R α := { e.smul R with one_smul := by simp [smul_def] mul_smul := by simp [smul_def, mul_smul] } noncomputable instance [Small.{v} α] [MulAction R α] : MulAction R (Shrink.{v} α) := (equivShrink α).symm.mulAction R /-- Transfer `DistribMulAction` across an `Equiv` -/ protected abbrev distribMulAction (e : α ≃ β) [AddCommMonoid β] : letI := Equiv.addCommMonoid e ∀ [DistribMulAction R β], DistribMulAction R α := by intros letI := Equiv.addCommMonoid e exact ({ Equiv.mulAction R e with smul_zero := by simp [zero_def, smul_def] smul_add := by simp [add_def, smul_def, smul_add] } : DistribMulAction R α) noncomputable instance [Small.{v} α] [AddCommMonoid α] [DistribMulAction R α] : DistribMulAction R (Shrink.{v} α) := (equivShrink α).symm.distribMulAction R end section variable [Semiring R] /-- Transfer `Module` across an `Equiv` -/ protected abbrev module (e : α ≃ β) [AddCommMonoid β] : let addCommMonoid := Equiv.addCommMonoid e ∀ [Module R β], Module R α := by intros exact ({ Equiv.distribMulAction R e with zero_smul := by simp [smul_def, zero_smul, zero_def] add_smul := by simp [add_def, smul_def, add_smul] } : Module R α) noncomputable instance [Small.{v} α] [AddCommMonoid α] [Module R α] : Module R (Shrink.{v} α) := (equivShrink α).symm.module R /-- An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β` where the `R`-module structure on `α` is the one obtained by transporting an `R`-module structure on `β` back along `e`. -/ def linearEquiv (e : α ≃ β) [AddCommMonoid β] [Module R β] : by let addCommMonoid := Equiv.addCommMonoid e let module := Equiv.module R e exact α ≃ₗ[R] β := by intros exact { Equiv.addEquiv e with map_smul' := fun r x => by apply e.symm.injective simp only [toFun_as_coe, RingHom.id_apply, EmbeddingLike.apply_eq_iff_eq] exact Iff.mpr (apply_eq_iff_eq_symm_apply _) rfl } variable (α) in /-- Shrink `α` to a smaller universe preserves module structure. -/ @[simps!] noncomputable def _root_.Shrink.linearEquiv [Small.{v} α] [AddCommMonoid α] [Module R α] : Shrink.{v} α ≃ₗ[R] α := Equiv.linearEquiv _ (equivShrink α).symm end section variable [CommSemiring R] /-- Transfer `Algebra` across an `Equiv` -/ protected abbrev algebra (e : α ≃ β) [Semiring β] : let semiring := Equiv.semiring e ∀ [Algebra R β], Algebra R α := by intros letI : Module R α := e.module R fapply Algebra.ofModule · intro r x y show e.symm (e (e.symm (r • e x)) * e y) = e.symm (r • e.ringEquiv (x * y)) simp only [apply_symm_apply, Algebra.smul_mul_assoc, map_mul, ringEquiv_apply] · intro r x y show e.symm (e x * e (e.symm (r • e y))) = e.symm (r • e (e.symm (e x * e y))) simp only [apply_symm_apply, Algebra.mul_smul_comm] lemma algebraMap_def (e : α ≃ β) [Semiring β] [Algebra R β] (r : R) : let semiring := Equiv.semiring e let algebra := Equiv.algebra R e (algebraMap R α) r = e.symm ((algebraMap R β) r) := by intros simp only [Algebra.algebraMap_eq_smul_one] show e.symm (r • e 1) = e.symm (r • 1) simp only [Equiv.one_def, apply_symm_apply] noncomputable instance [Small.{v} α] [Semiring α] [Algebra R α] : Algebra R (Shrink.{v} α) := (equivShrink α).symm.algebra _ /-- An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β` where the `R`-algebra structure on `α` is the one obtained by transporting an `R`-algebra structure on `β` back along `e`. -/ def algEquiv (e : α ≃ β) [Semiring β] [Algebra R β] : by let semiring := Equiv.semiring e let algebra := Equiv.algebra R e exact α ≃ₐ[R] β := by intros exact { Equiv.ringEquiv e with commutes' := fun r => by apply e.symm.injective simp only [RingEquiv.toEquiv_eq_coe, toFun_as_coe, EquivLike.coe_coe, ringEquiv_apply, symm_apply_apply, algebraMap_def] } @[simp] theorem algEquiv_apply (e : α ≃ β) [Semiring β] [Algebra R β] (a : α) : (algEquiv R e) a = e a := rfl theorem algEquiv_symm_apply (e : α ≃ β) [Semiring β] [Algebra R β] (b : β) : by letI := Equiv.semiring e letI := Equiv.algebra R e exact (algEquiv R e).symm b = e.symm b := rfl variable (α) in /-- Shrink `α` to a smaller universe preserves algebra structure. -/ @[simps!] noncomputable def _root_.Shrink.algEquiv [Small.{v} α] [Semiring α] [Algebra R α] : Shrink.{v} α ≃ₐ[R] α := Equiv.algEquiv _ (equivShrink α).symm end end R end Instances end Equiv namespace Finite attribute [-instance] Fin.instMul /-- Any finite group in universe `u` is equivalent to some finite group in universe `0`. -/ lemma exists_type_zero_nonempty_mulEquiv (G : Type u) [Group G] [Finite G] : ∃ (G' : Type) (_ : Group G') (_ : Fintype G'), Nonempty (G ≃* G') := by obtain ⟨n, ⟨e⟩⟩ := Finite.exists_equiv_fin G letI groupH : Group (Fin n) := Equiv.group e.symm exact ⟨Fin n, inferInstance, inferInstance, ⟨MulEquiv.symm <| Equiv.mulEquiv e.symm⟩⟩ end Finite
Logic\Function\Basic.lean
/- Copyright (c) 2016 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.Logic.Nonempty import Mathlib.Init.Set import Mathlib.Logic.Basic /-! # Miscellaneous function constructions and lemmas -/ open Function universe u v w namespace Function section variable {α β γ : Sort*} {f : α → β} /-- Evaluate a function at an argument. Useful if you want to talk about the partially applied `Function.eval x : (∀ x, β x) → β x`. -/ @[reducible, simp] def eval {β : α → Sort*} (x : α) (f : ∀ x, β x) : β x := f x theorem eval_apply {β : α → Sort*} (x : α) (f : ∀ x, β x) : eval x f = f x := rfl theorem const_def {y : β} : (fun _ : α ↦ y) = const α y := rfl theorem const_injective [Nonempty α] : Injective (const α : β → α → β) := fun y₁ y₂ h ↦ let ⟨x⟩ := ‹Nonempty α› congr_fun h x @[simp] theorem const_inj [Nonempty α] {y₁ y₂ : β} : const α y₁ = const α y₂ ↔ y₁ = y₂ := ⟨fun h ↦ const_injective h, fun h ↦ h ▸ rfl⟩ -- Porting note: `Function.onFun` is now reducible -- @[simp] theorem onFun_apply (f : β → β → γ) (g : α → β) (a b : α) : onFun f g a b = f (g a) (g b) := rfl lemma hfunext {α α' : Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : ∀a, β a} {f' : ∀a, β' a} (hα : α = α') (h : ∀a a', HEq a a' → HEq (f a) (f' a')) : HEq f f' := by subst hα have : ∀a, HEq (f a) (f' a) := fun a ↦ h a a (HEq.refl a) have : β = β' := by funext a; exact type_eq_of_heq (this a) subst this apply heq_of_eq funext a exact eq_of_heq (this a) theorem ne_iff {β : α → Sort*} {f₁ f₂ : ∀ a, β a} : f₁ ≠ f₂ ↔ ∃ a, f₁ a ≠ f₂ a := funext_iff.not.trans not_forall lemma funext_iff_of_subsingleton [Subsingleton α] {g : α → β} (x y : α) : f x = g y ↔ f = g := by refine ⟨fun h ↦ funext fun z ↦ ?_, fun h ↦ ?_⟩ · rwa [Subsingleton.elim x z, Subsingleton.elim y z] at h · rw [h, Subsingleton.elim x y] protected theorem Bijective.injective {f : α → β} (hf : Bijective f) : Injective f := hf.1 protected theorem Bijective.surjective {f : α → β} (hf : Bijective f) : Surjective f := hf.2 theorem Injective.eq_iff (I : Injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ theorem Injective.beq_eq {α β : Type*} [BEq α] [LawfulBEq α] [BEq β] [LawfulBEq β] {f : α → β} (I : Injective f) {a b : α} : (f a == f b) = (a == b) := by by_cases h : a == b <;> simp [h] <;> simpa [I.eq_iff] using h theorem Injective.eq_iff' (I : Injective f) {a b : α} {c : β} (h : f b = c) : f a = c ↔ a = b := h ▸ I.eq_iff theorem Injective.ne (hf : Injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ := mt fun h ↦ hf h theorem Injective.ne_iff (hf : Injective f) {x y : α} : f x ≠ f y ↔ x ≠ y := ⟨mt <| congr_arg f, hf.ne⟩ theorem Injective.ne_iff' (hf : Injective f) {x y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y := h ▸ hf.ne_iff theorem not_injective_iff : ¬ Injective f ↔ ∃ a b, f a = f b ∧ a ≠ b := by simp only [Injective, not_forall, exists_prop] /-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then the domain `α` also has decidable equality. -/ protected def Injective.decidableEq [DecidableEq β] (I : Injective f) : DecidableEq α := fun _ _ ↦ decidable_of_iff _ I.eq_iff theorem Injective.of_comp {g : γ → α} (I : Injective (f ∘ g)) : Injective g := fun _ _ h ↦ I <| congr_arg f h @[simp] theorem Injective.of_comp_iff (hf : Injective f) (g : γ → α) : Injective (f ∘ g) ↔ Injective g := ⟨Injective.of_comp, hf.comp⟩ theorem Injective.of_comp_right {g : γ → α} (I : Injective (f ∘ g)) (hg : Surjective g) : Injective f := fun x y h ↦ by obtain ⟨x, rfl⟩ := hg x obtain ⟨y, rfl⟩ := hg y exact congr_arg g (I h) theorem Surjective.bijective₂_of_injective {g : γ → α} (hf : Surjective f) (hg : Surjective g) (I : Injective (f ∘ g)) : Bijective f ∧ Bijective g := ⟨⟨I.of_comp_right hg, hf⟩, I.of_comp, hg⟩ @[simp] theorem Injective.of_comp_iff' (f : α → β) {g : γ → α} (hg : Bijective g) : Injective (f ∘ g) ↔ Injective f := ⟨fun I ↦ I.of_comp_right hg.2, fun h ↦ h.comp hg.injective⟩ /-- Composition by an injective function on the left is itself injective. -/ theorem Injective.comp_left {g : β → γ} (hg : Function.Injective g) : Function.Injective (g ∘ · : (α → β) → α → γ) := fun _ _ hgf ↦ funext fun i ↦ hg <| (congr_fun hgf i : _) theorem injective_of_subsingleton [Subsingleton α] (f : α → β) : Injective f := fun _ _ _ ↦ Subsingleton.elim _ _ lemma Injective.dite (p : α → Prop) [DecidablePred p] {f : {a : α // p a} → β} {f' : {a : α // ¬ p a} → β} (hf : Injective f) (hf' : Injective f') (im_disj : ∀ {x x' : α} {hx : p x} {hx' : ¬ p x'}, f ⟨x, hx⟩ ≠ f' ⟨x', hx'⟩) : Function.Injective (fun x ↦ if h : p x then f ⟨x, h⟩ else f' ⟨x, h⟩) := fun x₁ x₂ h => by dsimp only at h by_cases h₁ : p x₁ <;> by_cases h₂ : p x₂ · rw [dif_pos h₁, dif_pos h₂] at h; injection (hf h) · rw [dif_pos h₁, dif_neg h₂] at h; exact (im_disj h).elim · rw [dif_neg h₁, dif_pos h₂] at h; exact (im_disj h.symm).elim · rw [dif_neg h₁, dif_neg h₂] at h; injection (hf' h) theorem Surjective.of_comp {g : γ → α} (S : Surjective (f ∘ g)) : Surjective f := fun y ↦ let ⟨x, h⟩ := S y ⟨g x, h⟩ @[simp] theorem Surjective.of_comp_iff (f : α → β) {g : γ → α} (hg : Surjective g) : Surjective (f ∘ g) ↔ Surjective f := ⟨Surjective.of_comp, fun h ↦ h.comp hg⟩ theorem Surjective.of_comp_left {g : γ → α} (S : Surjective (f ∘ g)) (hf : Injective f) : Surjective g := fun a ↦ let ⟨c, hc⟩ := S (f a); ⟨c, hf hc⟩ theorem Injective.bijective₂_of_surjective {g : γ → α} (hf : Injective f) (hg : Injective g) (S : Surjective (f ∘ g)) : Bijective f ∧ Bijective g := ⟨⟨hf, S.of_comp⟩, hg, S.of_comp_left hf⟩ @[simp] theorem Surjective.of_comp_iff' (hf : Bijective f) (g : γ → α) : Surjective (f ∘ g) ↔ Surjective g := ⟨fun S ↦ S.of_comp_left hf.1, hf.surjective.comp⟩ instance decidableEqPFun (p : Prop) [Decidable p] (α : p → Type*) [∀ hp, DecidableEq (α hp)] : DecidableEq (∀ hp, α hp) | f, g => decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm protected theorem Surjective.forall (hf : Surjective f) {p : β → Prop} : (∀ y, p y) ↔ ∀ x, p (f x) := ⟨fun h x ↦ h (f x), fun h y ↦ let ⟨x, hx⟩ := hf y hx ▸ h x⟩ protected theorem Surjective.forall₂ (hf : Surjective f) {p : β → β → Prop} : (∀ y₁ y₂, p y₁ y₂) ↔ ∀ x₁ x₂, p (f x₁) (f x₂) := hf.forall.trans <| forall_congr' fun _ ↦ hf.forall protected theorem Surjective.forall₃ (hf : Surjective f) {p : β → β → β → Prop} : (∀ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∀ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.forall.trans <| forall_congr' fun _ ↦ hf.forall₂ protected theorem Surjective.exists (hf : Surjective f) {p : β → Prop} : (∃ y, p y) ↔ ∃ x, p (f x) := ⟨fun ⟨y, hy⟩ ↦ let ⟨x, hx⟩ := hf y ⟨x, hx.symm ▸ hy⟩, fun ⟨x, hx⟩ ↦ ⟨f x, hx⟩⟩ protected theorem Surjective.exists₂ (hf : Surjective f) {p : β → β → Prop} : (∃ y₁ y₂, p y₁ y₂) ↔ ∃ x₁ x₂, p (f x₁) (f x₂) := hf.exists.trans <| exists_congr fun _ ↦ hf.exists protected theorem Surjective.exists₃ (hf : Surjective f) {p : β → β → β → Prop} : (∃ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∃ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.exists.trans <| exists_congr fun _ ↦ hf.exists₂ theorem Surjective.injective_comp_right (hf : Surjective f) : Injective fun g : β → γ ↦ g ∘ f := fun _ _ h ↦ funext <| hf.forall.2 <| congr_fun h protected theorem Surjective.right_cancellable (hf : Surjective f) {g₁ g₂ : β → γ} : g₁ ∘ f = g₂ ∘ f ↔ g₁ = g₂ := hf.injective_comp_right.eq_iff theorem surjective_of_right_cancellable_Prop (h : ∀ g₁ g₂ : β → Prop, g₁ ∘ f = g₂ ∘ f → g₁ = g₂) : Surjective f := by specialize h (fun y ↦ ∃ x, f x = y) (fun _ ↦ True) (funext fun x ↦ eq_true ⟨_, rfl⟩) intro y; rw [congr_fun h y]; trivial theorem bijective_iff_existsUnique (f : α → β) : Bijective f ↔ ∀ b : β, ∃! a : α, f a = b := ⟨fun hf b ↦ let ⟨a, ha⟩ := hf.surjective b ⟨a, ha, fun _ ha' ↦ hf.injective (ha'.trans ha.symm)⟩, fun he ↦ ⟨fun {_a a'} h ↦ (he (f a')).unique h rfl, fun b ↦ (he b).exists⟩⟩ /-- Shorthand for using projection notation with `Function.bijective_iff_existsUnique`. -/ protected theorem Bijective.existsUnique {f : α → β} (hf : Bijective f) (b : β) : ∃! a : α, f a = b := (bijective_iff_existsUnique f).mp hf b theorem Bijective.existsUnique_iff {f : α → β} (hf : Bijective f) {p : β → Prop} : (∃! y, p y) ↔ ∃! x, p (f x) := ⟨fun ⟨y, hpy, hy⟩ ↦ let ⟨x, hx⟩ := hf.surjective y ⟨x, by simpa [hx], fun z (hz : p (f z)) ↦ hf.injective <| hx.symm ▸ hy _ hz⟩, fun ⟨x, hpx, hx⟩ ↦ ⟨f x, hpx, fun y hy ↦ let ⟨z, hz⟩ := hf.surjective y hz ▸ congr_arg f (hx _ (by simpa [hz]))⟩⟩ theorem Bijective.of_comp_iff (f : α → β) {g : γ → α} (hg : Bijective g) : Bijective (f ∘ g) ↔ Bijective f := and_congr (Injective.of_comp_iff' _ hg) (Surjective.of_comp_iff _ hg.surjective) theorem Bijective.of_comp_iff' {f : α → β} (hf : Bijective f) (g : γ → α) : Function.Bijective (f ∘ g) ↔ Function.Bijective g := and_congr (Injective.of_comp_iff hf.injective _) (Surjective.of_comp_iff' hf _) /-- **Cantor's diagonal argument** implies that there are no surjective functions from `α` to `Set α`. -/ theorem cantor_surjective {α} (f : α → Set α) : ¬Surjective f | h => let ⟨D, e⟩ := h {a | ¬ f a a} @iff_not_self (D ∈ f D) <| iff_of_eq <| congr_arg (D ∈ ·) e /-- **Cantor's diagonal argument** implies that there are no injective functions from `Set α` to `α`. -/ theorem cantor_injective {α : Type*} (f : Set α → α) : ¬Injective f | i => cantor_surjective (fun a ↦ {b | ∀ U, a = f U → U b}) <| RightInverse.surjective (fun U ↦ Set.ext fun _ ↦ ⟨fun h ↦ h U rfl, fun h _ e ↦ i e ▸ h⟩) /-- There is no surjection from `α : Type u` into `Type (max u v)`. This theorem demonstrates why `Type : Type` would be inconsistent in Lean. -/ theorem not_surjective_Type {α : Type u} (f : α → Type max u v) : ¬Surjective f := by intro hf let T : Type max u v := Sigma f cases hf (Set T) with | intro U hU => let g : Set T → T := fun s ↦ ⟨U, cast hU.symm s⟩ have hg : Injective g := by intro s t h suffices cast hU (g s).2 = cast hU (g t).2 by simp only [cast_cast, cast_eq] at this assumption · congr exact cantor_injective g hg /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def IsPartialInv {α β} (f : α → β) (g : β → Option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem isPartialInv_left {α β} {f : α → β} {g} (H : IsPartialInv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_isPartialInv {α β} {f : α → β} {g} (H : IsPartialInv f g) : Injective f := fun _ _ h ↦ Option.some.inj <| ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_isPartialInv_right {α β} {f : α → β} {g} (H : IsPartialInv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem LeftInverse.comp_eq_id {f : α → β} {g : β → α} (h : LeftInverse f g) : f ∘ g = id := funext h theorem leftInverse_iff_comp {f : α → β} {g : β → α} : LeftInverse f g ↔ f ∘ g = id := ⟨LeftInverse.comp_eq_id, congr_fun⟩ theorem RightInverse.comp_eq_id {f : α → β} {g : β → α} (h : RightInverse f g) : g ∘ f = id := funext h theorem rightInverse_iff_comp {f : α → β} {g : β → α} : RightInverse f g ↔ g ∘ f = id := ⟨RightInverse.comp_eq_id, congr_fun⟩ theorem LeftInverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : LeftInverse f g) (hh : LeftInverse h i) : LeftInverse (h ∘ f) (g ∘ i) := fun a ↦ show h (f (g (i a))) = a by rw [hf (i a), hh a] theorem RightInverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : RightInverse f g) (hh : RightInverse h i) : RightInverse (h ∘ f) (g ∘ i) := LeftInverse.comp hh hf theorem LeftInverse.rightInverse {f : α → β} {g : β → α} (h : LeftInverse g f) : RightInverse f g := h theorem RightInverse.leftInverse {f : α → β} {g : β → α} (h : RightInverse g f) : LeftInverse f g := h theorem LeftInverse.surjective {f : α → β} {g : β → α} (h : LeftInverse f g) : Surjective f := h.rightInverse.surjective theorem RightInverse.injective {f : α → β} {g : β → α} (h : RightInverse f g) : Injective f := h.leftInverse.injective theorem LeftInverse.rightInverse_of_injective {f : α → β} {g : β → α} (h : LeftInverse f g) (hf : Injective f) : RightInverse f g := fun x ↦ hf <| h (f x) theorem LeftInverse.rightInverse_of_surjective {f : α → β} {g : β → α} (h : LeftInverse f g) (hg : Surjective g) : RightInverse f g := fun x ↦ let ⟨y, hy⟩ := hg x; hy ▸ congr_arg g (h y) theorem RightInverse.leftInverse_of_surjective {f : α → β} {g : β → α} : RightInverse f g → Surjective f → LeftInverse f g := LeftInverse.rightInverse_of_surjective theorem RightInverse.leftInverse_of_injective {f : α → β} {g : β → α} : RightInverse f g → Injective g → LeftInverse f g := LeftInverse.rightInverse_of_injective theorem LeftInverse.eq_rightInverse {f : α → β} {g₁ g₂ : β → α} (h₁ : LeftInverse g₁ f) (h₂ : RightInverse g₂ f) : g₁ = g₂ := calc g₁ = g₁ ∘ f ∘ g₂ := by rw [h₂.comp_eq_id, comp_id] _ = g₂ := by rw [← comp.assoc, h₁.comp_eq_id, id_comp] attribute [local instance] Classical.propDecidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partialInv {α β} (f : α → β) (b : β) : Option α := if h : ∃ a, f a = b then some (Classical.choose h) else none theorem partialInv_of_injective {α β} {f : α → β} (I : Injective f) : IsPartialInv f (partialInv f) | a, b => ⟨fun h => have hpi : partialInv f b = if h : ∃ a, f a = b then some (Classical.choose h) else none := rfl if h' : ∃ a, f a = b then by rw [hpi, dif_pos h'] at h injection h with h subst h apply Classical.choose_spec h' else by rw [hpi, dif_neg h'] at h; contradiction, fun e => e ▸ have h : ∃ a', f a' = f a := ⟨_, rfl⟩ (dif_pos h).trans (congr_arg _ (I <| Classical.choose_spec h))⟩ theorem partialInv_left {α β} {f : α → β} (I : Injective f) : ∀ x, partialInv f (f x) = some x := isPartialInv_left (partialInv_of_injective I) end section InvFun variable {α β : Sort*} [Nonempty α] {f : α → β} {a : α} {b : β} attribute [local instance] Classical.propDecidable /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ -- Explicit Sort so that `α` isn't inferred to be Prop via `exists_prop_decidable` noncomputable def invFun {α : Sort u} {β} [Nonempty α] (f : α → β) : β → α := fun y ↦ if h : (∃ x, f x = y) then h.choose else Classical.arbitrary α theorem invFun_eq (h : ∃ a, f a = b) : f (invFun f b) = b := by simp only [invFun, dif_pos h, h.choose_spec] theorem apply_invFun_apply {α β : Type*} {f : α → β} {a : α} : f (@invFun _ _ ⟨a⟩ f (f a)) = f a := @invFun_eq _ _ ⟨a⟩ _ _ ⟨_, rfl⟩ theorem invFun_neg (h : ¬∃ a, f a = b) : invFun f b = Classical.choice ‹_› := dif_neg h theorem invFun_eq_of_injective_of_rightInverse {g : β → α} (hf : Injective f) (hg : RightInverse g f) : invFun f = g := funext fun b ↦ hf (by rw [hg b] exact invFun_eq ⟨g b, hg b⟩) theorem rightInverse_invFun (hf : Surjective f) : RightInverse (invFun f) f := fun b ↦ invFun_eq <| hf b theorem leftInverse_invFun (hf : Injective f) : LeftInverse (invFun f) f := fun b ↦ hf <| invFun_eq ⟨b, rfl⟩ theorem invFun_surjective (hf : Injective f) : Surjective (invFun f) := (leftInverse_invFun hf).surjective theorem invFun_comp (hf : Injective f) : invFun f ∘ f = id := funext <| leftInverse_invFun hf theorem Injective.hasLeftInverse (hf : Injective f) : HasLeftInverse f := ⟨invFun f, leftInverse_invFun hf⟩ theorem injective_iff_hasLeftInverse : Injective f ↔ HasLeftInverse f := ⟨Injective.hasLeftInverse, HasLeftInverse.injective⟩ end InvFun section SurjInv variable {α : Sort u} {β : Sort v} {γ : Sort w} {f : α → β} /-- The inverse of a surjective function. (Unlike `invFun`, this does not require `α` to be inhabited.) -/ noncomputable def surjInv {f : α → β} (h : Surjective f) (b : β) : α := Classical.choose (h b) theorem surjInv_eq (h : Surjective f) (b) : f (surjInv h b) = b := Classical.choose_spec (h b) theorem rightInverse_surjInv (hf : Surjective f) : RightInverse (surjInv hf) f := surjInv_eq hf theorem leftInverse_surjInv (hf : Bijective f) : LeftInverse (surjInv hf.2) f := rightInverse_of_injective_of_leftInverse hf.1 (rightInverse_surjInv hf.2) theorem Surjective.hasRightInverse (hf : Surjective f) : HasRightInverse f := ⟨_, rightInverse_surjInv hf⟩ theorem surjective_iff_hasRightInverse : Surjective f ↔ HasRightInverse f := ⟨Surjective.hasRightInverse, HasRightInverse.surjective⟩ theorem bijective_iff_has_inverse : Bijective f ↔ ∃ g, LeftInverse g f ∧ RightInverse g f := ⟨fun hf ↦ ⟨_, leftInverse_surjInv hf, rightInverse_surjInv hf.2⟩, fun ⟨_, gl, gr⟩ ↦ ⟨gl.injective, gr.surjective⟩⟩ theorem injective_surjInv (h : Surjective f) : Injective (surjInv h) := (rightInverse_surjInv h).injective theorem surjective_to_subsingleton [na : Nonempty α] [Subsingleton β] (f : α → β) : Surjective f := fun _ ↦ let ⟨a⟩ := na; ⟨a, Subsingleton.elim _ _⟩ /-- Composition by a surjective function on the left is itself surjective. -/ theorem Surjective.comp_left {g : β → γ} (hg : Surjective g) : Surjective (g ∘ · : (α → β) → α → γ) := fun f ↦ ⟨surjInv hg ∘ f, funext fun _ ↦ rightInverse_surjInv _ _⟩ /-- Composition by a bijective function on the left is itself bijective. -/ theorem Bijective.comp_left {g : β → γ} (hg : Bijective g) : Bijective (g ∘ · : (α → β) → α → γ) := ⟨hg.injective.comp_left, hg.surjective.comp_left⟩ end SurjInv section Update variable {α : Sort u} {β : α → Sort v} {α' : Sort w} [DecidableEq α] {f g : (a : α) → β a} {a : α} {b : β a} /-- Replacing the value of a function at a given point by a given value. -/ def update (f : ∀ a, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then Eq.ndrec v h.symm else f a @[simp] theorem update_same (a : α) (v : β a) (f : ∀ a, β a) : update f a v a = v := dif_pos rfl @[simp] theorem update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : ∀ a, β a) : update f a' v a = f a := dif_neg h /-- On non-dependent functions, `Function.update` can be expressed as an `ite` -/ theorem update_apply {β : Sort*} (f : α → β) (a' : α) (b : β) (a : α) : update f a' b a = if a = a' then b else f a := by rcases Decidable.eq_or_ne a a' with rfl | hne <;> simp [*] @[nontriviality] theorem update_eq_const_of_subsingleton [Subsingleton α] (a : α) (v : α') (f : α → α') : update f a v = const α v := funext fun a' ↦ Subsingleton.elim a a' ▸ update_same _ _ _ theorem surjective_eval {α : Sort u} {β : α → Sort v} [h : ∀ a, Nonempty (β a)] (a : α) : Surjective (eval a : (∀ a, β a) → β a) := fun b ↦ ⟨@update _ _ (Classical.decEq α) (fun a ↦ (h a).some) a b, @update_same _ _ (Classical.decEq α) _ _ _⟩ theorem update_injective (f : ∀ a, β a) (a' : α) : Injective (update f a') := fun v v' h ↦ by have := congr_fun h a' rwa [update_same, update_same] at this lemma forall_update_iff (f : ∀a, β a) {a : α} {b : β a} (p : ∀a, β a → Prop) : (∀ x, p x (update f a b x)) ↔ p a b ∧ ∀ x, x ≠ a → p x (f x) := by rw [← and_forall_ne a, update_same] simp (config := { contextual := true }) theorem exists_update_iff (f : ∀ a, β a) {a : α} {b : β a} (p : ∀ a, β a → Prop) : (∃ x, p x (update f a b x)) ↔ p a b ∨ ∃ x ≠ a, p x (f x) := by rw [← not_forall_not, forall_update_iff f fun a b ↦ ¬p a b] simp [-not_and, not_and_or] theorem update_eq_iff {a : α} {b : β a} {f g : ∀ a, β a} : update f a b = g ↔ b = g a ∧ ∀ x ≠ a, f x = g x := funext_iff.trans <| forall_update_iff _ fun x y ↦ y = g x theorem eq_update_iff {a : α} {b : β a} {f g : ∀ a, β a} : g = update f a b ↔ g a = b ∧ ∀ x ≠ a, g x = f x := funext_iff.trans <| forall_update_iff _ fun x y ↦ g x = y @[simp] lemma update_eq_self_iff : update f a b = f ↔ b = f a := by simp [update_eq_iff] @[simp] lemma eq_update_self_iff : f = update f a b ↔ f a = b := by simp [eq_update_iff] lemma ne_update_self_iff : f ≠ update f a b ↔ f a ≠ b := eq_update_self_iff.not lemma update_ne_self_iff : update f a b ≠ f ↔ b ≠ f a := update_eq_self_iff.not @[simp] theorem update_eq_self (a : α) (f : ∀ a, β a) : update f a (f a) = f := update_eq_iff.2 ⟨rfl, fun _ _ ↦ rfl⟩ theorem update_comp_eq_of_forall_ne' {α'} (g : ∀ a, β a) {f : α' → α} {i : α} (a : β i) (h : ∀ x, f x ≠ i) : (fun j ↦ (update g i a) (f j)) = fun j ↦ g (f j) := funext fun _ ↦ update_noteq (h _) _ _ variable [DecidableEq α'] /-- Non-dependent version of `Function.update_comp_eq_of_forall_ne'` -/ theorem update_comp_eq_of_forall_ne {α β : Sort*} (g : α' → β) {f : α → α'} {i : α'} (a : β) (h : ∀ x, f x ≠ i) : update g i a ∘ f = g ∘ f := update_comp_eq_of_forall_ne' g a h theorem update_comp_eq_of_injective' (g : ∀ a, β a) {f : α' → α} (hf : Function.Injective f) (i : α') (a : β (f i)) : (fun j ↦ update g (f i) a (f j)) = update (fun i ↦ g (f i)) i a := eq_update_iff.2 ⟨update_same _ _ _, fun _ hj ↦ update_noteq (hf.ne hj) _ _⟩ /-- Non-dependent version of `Function.update_comp_eq_of_injective'` -/ theorem update_comp_eq_of_injective {β : Sort*} (g : α' → β) {f : α → α'} (hf : Function.Injective f) (i : α) (a : β) : Function.update g (f i) a ∘ f = Function.update (g ∘ f) i a := update_comp_eq_of_injective' g hf i a theorem apply_update {ι : Sort*} [DecidableEq ι] {α β : ι → Sort*} (f : ∀ i, α i → β i) (g : ∀ i, α i) (i : ι) (v : α i) (j : ι) : f j (update g i v j) = update (fun k ↦ f k (g k)) i (f i v) j := by by_cases h : j = i · subst j simp · simp [h] theorem apply_update₂ {ι : Sort*} [DecidableEq ι] {α β γ : ι → Sort*} (f : ∀ i, α i → β i → γ i) (g : ∀ i, α i) (h : ∀ i, β i) (i : ι) (v : α i) (w : β i) (j : ι) : f j (update g i v j) (update h i w j) = update (fun k ↦ f k (g k) (h k)) i (f i v w) j := by by_cases h : j = i · subst j simp · simp [h] theorem pred_update (P : ∀ ⦃a⦄, β a → Prop) (f : ∀ a, β a) (a' : α) (v : β a') (a : α) : P (update f a' v a) ↔ a = a' ∧ P v ∨ a ≠ a' ∧ P (f a) := by rw [apply_update P, update_apply, ite_prop_iff_or] theorem comp_update {α' : Sort*} {β : Sort*} (f : α' → β) (g : α → α') (i : α) (v : α') : f ∘ update g i v = update (f ∘ g) i (f v) := funext <| apply_update _ _ _ _ theorem update_comm {α} [DecidableEq α] {β : α → Sort*} {a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : ∀ a, β a) : update (update f a v) b w = update (update f b w) a v := by funext c simp only [update] by_cases h₁ : c = b <;> by_cases h₂ : c = a · rw [dif_pos h₁, dif_pos h₂] cases h (h₂.symm.trans h₁) · rw [dif_pos h₁, dif_pos h₁, dif_neg h₂] · rw [dif_neg h₁, dif_neg h₁] · rw [dif_neg h₁, dif_neg h₁] @[simp] theorem update_idem {α} [DecidableEq α] {β : α → Sort*} {a : α} (v w : β a) (f : ∀ a, β a) : update (update f a v) a w = update f a w := by funext b by_cases h : b = a <;> simp [update, h] end Update noncomputable section Extend attribute [local instance] Classical.propDecidable variable {α β γ : Sort*} {f : α → β} /-- Extension of a function `g : α → γ` along a function `f : α → β`. For every `a : α`, `f a` is sent to `g a`. `f` might not be surjective, so we use an auxiliary function `j : β → γ` by sending `b : β` not in the range of `f` to `j b`. If you do not care about the behavior outside the range, `j` can be used as a junk value by setting it to be `0` or `Classical.arbitrary` (assuming `γ` is nonempty). This definition is mathematically meaningful only when `f a₁ = f a₂ → g a₁ = g a₂` (spelled `g.FactorsThrough f`). In particular this holds if `f` is injective. A typical use case is extending a function from a subtype to the entire type. If you wish to extend `g : {b : β // p b} → γ` to a function `β → γ`, you should use `Function.extend Subtype.val g j`. -/ def extend (f : α → β) (g : α → γ) (j : β → γ) : β → γ := fun b ↦ if h : ∃ a, f a = b then g (Classical.choose h) else j b /-- g factors through f : `f a = f b → g a = g b` -/ def FactorsThrough (g : α → γ) (f : α → β) : Prop := ∀ ⦃a b⦄, f a = f b → g a = g b theorem extend_def (f : α → β) (g : α → γ) (e' : β → γ) (b : β) [Decidable (∃ a, f a = b)] : extend f g e' b = if h : ∃ a, f a = b then g (Classical.choose h) else e' b := by unfold extend congr lemma Injective.factorsThrough (hf : Injective f) (g : α → γ) : g.FactorsThrough f := fun _ _ h => congr_arg g (hf h) lemma FactorsThrough.extend_apply {g : α → γ} (hf : g.FactorsThrough f) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := by simp only [extend_def, dif_pos, exists_apply_eq_apply] exact hf (Classical.choose_spec (exists_apply_eq_apply f a)) @[simp] theorem Injective.extend_apply (hf : Injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := (hf.factorsThrough g).extend_apply e' a @[simp] theorem extend_apply' (g : α → γ) (e' : β → γ) (b : β) (hb : ¬∃ a, f a = b) : extend f g e' b = e' b := by simp [Function.extend_def, hb] lemma factorsThrough_iff (g : α → γ) [Nonempty γ] : g.FactorsThrough f ↔ ∃ (e : β → γ), g = e ∘ f := ⟨fun hf => ⟨extend f g (const β (Classical.arbitrary γ)), funext (fun x => by simp only [comp_apply, hf.extend_apply])⟩, fun h _ _ hf => by rw [Classical.choose_spec h, comp_apply, comp_apply, hf]⟩ lemma apply_extend {δ} {g : α → γ} (F : γ → δ) (f : α → β) (e' : β → γ) (b : β) : F (extend f g e' b) = extend f (F ∘ g) (F ∘ e') b := apply_dite F _ _ _ theorem extend_injective (hf : Injective f) (e' : β → γ) : Injective fun g ↦ extend f g e' := by intro g₁ g₂ hg refine funext fun x ↦ ?_ have H := congr_fun hg (f x) simp only [hf.extend_apply] at H exact H lemma FactorsThrough.extend_comp {g : α → γ} (e' : β → γ) (hf : FactorsThrough g f) : extend f g e' ∘ f = g := funext fun a => hf.extend_apply e' a @[simp] theorem extend_comp (hf : Injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g := funext fun a ↦ hf.extend_apply g e' a theorem Injective.surjective_comp_right' (hf : Injective f) (g₀ : β → γ) : Surjective fun g : β → γ ↦ g ∘ f := fun g ↦ ⟨extend f g g₀, extend_comp hf _ _⟩ theorem Injective.surjective_comp_right [Nonempty γ] (hf : Injective f) : Surjective fun g : β → γ ↦ g ∘ f := hf.surjective_comp_right' fun _ ↦ Classical.choice ‹_› theorem Bijective.comp_right (hf : Bijective f) : Bijective fun g : β → γ ↦ g ∘ f := ⟨hf.surjective.injective_comp_right, fun g ↦ ⟨g ∘ surjInv hf.surjective, by simp only [comp.assoc g _ f, (leftInverse_surjInv hf).comp_eq_id, comp_id]⟩⟩ end Extend namespace FactorsThrough protected theorem rfl {α β : Sort*} {f : α → β} : FactorsThrough f f := fun _ _ ↦ id theorem comp_left {α β γ δ : Sort*} {f : α → β} {g : α → γ} (h : FactorsThrough g f) (g' : γ → δ) : FactorsThrough (g' ∘ g) f := fun _x _y hxy ↦ congr_arg g' (h hxy) theorem comp_right {α β γ δ : Sort*} {f : α → β} {g : α → γ} (h : FactorsThrough g f) (g' : δ → α) : FactorsThrough (g ∘ g') (f ∘ g') := fun _x _y hxy ↦ h hxy end FactorsThrough theorem uncurry_def {α β γ} (f : α → β → γ) : uncurry f = fun p ↦ f p.1 p.2 := rfl @[simp] theorem uncurry_apply_pair {α β γ} (f : α → β → γ) (x : α) (y : β) : uncurry f (x, y) = f x y := rfl @[simp] theorem curry_apply {α β γ} (f : α × β → γ) (x : α) (y : β) : curry f x y = f (x, y) := rfl section Bicomp variable {α β γ δ ε : Type*} /-- Compose a binary function `f` with a pair of unary functions `g` and `h`. If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/ def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) := f (g a) (h b) /-- Compose a unary function `f` with a binary function `g`. -/ def bicompr (f : γ → δ) (g : α → β → γ) (a b) := f (g a b) -- Suggested local notation: local notation f " ∘₂ " g => bicompr f g theorem uncurry_bicompr (f : α → β → γ) (g : γ → δ) : uncurry (g ∘₂ f) = g ∘ uncurry f := rfl theorem uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = uncurry f ∘ Prod.map g h := rfl end Bicomp section Uncurry variable {α β γ δ : Type*} /-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ class HasUncurry (α : Type*) (β : outParam Type*) (γ : outParam Type*) where /-- Uncurrying operator. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ uncurry : α → β → γ @[inherit_doc] notation:arg "↿" x:arg => HasUncurry.uncurry x instance hasUncurryBase : HasUncurry (α → β) α β := ⟨id⟩ instance hasUncurryInduction [HasUncurry β γ δ] : HasUncurry (α → β) (α × γ) δ := ⟨fun f p ↦ (↿(f p.1)) p.2⟩ end Uncurry /-- A function is involutive, if `f ∘ f = id`. -/ def Involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x theorem _root_.Bool.involutive_not : Involutive not := Bool.not_not namespace Involutive variable {α : Sort u} {f : α → α} (h : Involutive f) @[simp] theorem comp_self : f ∘ f = id := funext h protected theorem leftInverse : LeftInverse f f := h protected theorem rightInverse : RightInverse f f := h protected theorem injective : Injective f := h.leftInverse.injective protected theorem surjective : Surjective f := fun x ↦ ⟨f x, h x⟩ protected theorem bijective : Bijective f := ⟨h.injective, h.surjective⟩ /-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/ protected theorem ite_not (P : Prop) [Decidable P] (x : α) : f (ite P x (f x)) = ite (¬P) x (f x) := by rw [apply_ite f, h, ite_not] /-- An involution commutes across an equality. Compare to `Function.Injective.eq_iff`. -/ protected theorem eq_iff {x y : α} : f x = y ↔ x = f y := h.injective.eq_iff' (h y) end Involutive lemma not_involutive : Involutive Not := fun _ ↦ propext not_not lemma not_injective : Injective Not := not_involutive.injective lemma not_surjective : Surjective Not := not_involutive.surjective lemma not_bijective : Bijective Not := not_involutive.bijective @[simp] lemma symmetric_apply_eq_iff {α : Sort*} {f : α → α} : Symmetric (f · = ·) ↔ Involutive f := by simp [Symmetric, Involutive] /-- The property of a binary function `f : α → β → γ` being injective. Mathematically this should be thought of as the corresponding function `α × β → γ` being injective. -/ def Injective2 {α β γ : Sort*} (f : α → β → γ) : Prop := ∀ ⦃a₁ a₂ b₁ b₂⦄, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂ namespace Injective2 variable {α β γ : Sort*} {f : α → β → γ} /-- A binary injective function is injective when only the left argument varies. -/ protected theorem left (hf : Injective2 f) (b : β) : Function.Injective fun a ↦ f a b := fun _ _ h ↦ (hf h).left /-- A binary injective function is injective when only the right argument varies. -/ protected theorem right (hf : Injective2 f) (a : α) : Function.Injective (f a) := fun _ _ h ↦ (hf h).right protected theorem uncurry {α β γ : Type*} {f : α → β → γ} (hf : Injective2 f) : Function.Injective (uncurry f) := fun ⟨_, _⟩ ⟨_, _⟩ h ↦ (hf h).elim (congr_arg₂ _) /-- As a map from the left argument to a unary function, `f` is injective. -/ theorem left' (hf : Injective2 f) [Nonempty β] : Function.Injective f := fun a₁ a₂ h ↦ let ⟨b⟩ := ‹Nonempty β› hf.left b <| (congr_fun h b : _) /-- As a map from the right argument to a unary function, `f` is injective. -/ theorem right' (hf : Injective2 f) [Nonempty α] : Function.Injective fun b a ↦ f a b := fun b₁ b₂ h ↦ let ⟨a⟩ := ‹Nonempty α› hf.right a <| (congr_fun h a : _) theorem eq_iff (hf : Injective2 f) {a₁ a₂ b₁ b₂} : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨fun h ↦ hf h, fun ⟨h1, h2⟩ ↦ congr_arg₂ f h1 h2⟩ end Injective2 section Sometimes attribute [local instance] Classical.propDecidable /-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially interesting in the case where `α` is a proposition, in which case `f` is necessarily a constant function, so that `sometimes f = f a` for all `a`. -/ noncomputable def sometimes {α β} [Nonempty β] (f : α → β) : β := if h : Nonempty α then f (Classical.choice h) else Classical.choice ‹_› theorem sometimes_eq {p : Prop} {α} [Nonempty α] (f : p → α) (a : p) : sometimes f = f a := dif_pos ⟨a⟩ theorem sometimes_spec {p : Prop} {α} [Nonempty α] (P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) := by rwa [sometimes_eq] end Sometimes end Function variable {α β : Sort*} /-- A relation `r : α → β → Prop` is "function-like" (for each `a` there exists a unique `b` such that `r a b`) if and only if it is `(f · = ·)` for some function `f`. -/ lemma forall_existsUnique_iff {r : α → β → Prop} : (∀ a, ∃! b, r a b) ↔ ∃ f : α → β, ∀ {a b}, r a b ↔ f a = b := by refine ⟨fun h ↦ ?_, ?_⟩ · refine ⟨fun a ↦ (h a).choose, fun hr ↦ ?_, fun h' ↦ h' ▸ ?_⟩ exacts [((h _).choose_spec.2 _ hr).symm, (h _).choose_spec.1] · rintro ⟨f, hf⟩ simp [hf] /-- A relation `r : α → β → Prop` is "function-like" (for each `a` there exists a unique `b` such that `r a b`) if and only if it is `(f · = ·)` for some function `f`. -/ lemma forall_existsUnique_iff' {r : α → β → Prop} : (∀ a, ∃! b, r a b) ↔ ∃ f : α → β, r = (f · = ·) := by simp [forall_existsUnique_iff, Function.funext_iff] /-- A symmetric relation `r : α → α → Prop` is "function-like" (for each `a` there exists a unique `b` such that `r a b`) if and only if it is `(f · = ·)` for some involutive function `f`. -/ protected lemma Symmetric.forall_existsUnique_iff' {r : α → α → Prop} (hr : Symmetric r) : (∀ a, ∃! b, r a b) ↔ ∃ f : α → α, Involutive f ∧ r = (f · = ·) := by refine ⟨fun h ↦ ?_, fun ⟨f, _, hf⟩ ↦ forall_existsUnique_iff'.2 ⟨f, hf⟩⟩ rcases forall_existsUnique_iff'.1 h with ⟨f, rfl : r = _⟩ exact ⟨f, symmetric_apply_eq_iff.1 hr, rfl⟩ /-- A symmetric relation `r : α → α → Prop` is "function-like" (for each `a` there exists a unique `b` such that `r a b`) if and only if it is `(f · = ·)` for some involutive function `f`. -/ protected lemma Symmetric.forall_existsUnique_iff {r : α → α → Prop} (hr : Symmetric r) : (∀ a, ∃! b, r a b) ↔ ∃ f : α → α, Involutive f ∧ ∀ {a b}, r a b ↔ f a = b := by simp [hr.forall_existsUnique_iff', funext_iff] /-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/ def Set.piecewise {α : Type u} {β : α → Sort v} (s : Set α) (f g : ∀ i, β i) [∀ j, Decidable (j ∈ s)] : ∀ i, β i := fun i ↦ if i ∈ s then f i else g i /-! ### Bijectivity of `Eq.rec`, `Eq.mp`, `Eq.mpr`, and `cast` -/ theorem eq_rec_on_bijective {C : α → Sort*} : ∀ {a a' : α} (h : a = a'), Function.Bijective (@Eq.ndrec _ _ C · _ h) | _, _, rfl => ⟨fun _ _ ↦ id, fun x ↦ ⟨x, rfl⟩⟩ theorem eq_mp_bijective {α β : Sort _} (h : α = β) : Function.Bijective (Eq.mp h) := by -- TODO: mathlib3 uses `eq_rec_on_bijective`, difference in elaboration here -- due to `@[macro_inline]` possibly? cases h exact ⟨fun _ _ ↦ id, fun x ↦ ⟨x, rfl⟩⟩ theorem eq_mpr_bijective {α β : Sort _} (h : α = β) : Function.Bijective (Eq.mpr h) := by cases h exact ⟨fun _ _ ↦ id, fun x ↦ ⟨x, rfl⟩⟩ theorem cast_bijective {α β : Sort _} (h : α = β) : Function.Bijective (cast h) := by cases h exact ⟨fun _ _ ↦ id, fun x ↦ ⟨x, rfl⟩⟩ /-! Note these lemmas apply to `Type*` not `Sort*`, as the latter interferes with `simp`, and is trivial anyway. -/ @[simp] theorem eq_rec_inj {a a' : α} (h : a = a') {C : α → Type*} (x y : C a) : (Eq.ndrec x h : C a') = Eq.ndrec y h ↔ x = y := (eq_rec_on_bijective h).injective.eq_iff @[simp] theorem cast_inj {α β : Type u} (h : α = β) {x y : α} : cast h x = cast h y ↔ x = y := (cast_bijective h).injective.eq_iff theorem Function.LeftInverse.eq_rec_eq {γ : β → Sort v} {f : α → β} {g : β → α} (h : Function.LeftInverse g f) (C : ∀ a : α, γ (f a)) (a : α) : -- TODO: mathlib3 uses `(congr_arg f (h a)).rec (C (g (f a)))` for LHS @Eq.rec β (f (g (f a))) (fun x _ ↦ γ x) (C (g (f a))) (f a) (congr_arg f (h a)) = C a := eq_of_heq <| (eq_rec_heq _ _).trans <| by rw [h] theorem Function.LeftInverse.eq_rec_on_eq {γ : β → Sort v} {f : α → β} {g : β → α} (h : Function.LeftInverse g f) (C : ∀ a : α, γ (f a)) (a : α) : -- TODO: mathlib3 uses `(congr_arg f (h a)).recOn (C (g (f a)))` for LHS @Eq.recOn β (f (g (f a))) (fun x _ ↦ γ x) (f a) (congr_arg f (h a)) (C (g (f a))) = C a := h.eq_rec_eq _ _ theorem Function.LeftInverse.cast_eq {γ : β → Sort v} {f : α → β} {g : β → α} (h : Function.LeftInverse g f) (C : ∀ a : α, γ (f a)) (a : α) : cast (congr_arg (fun a ↦ γ (f a)) (h a)) (C (g (f a))) = C a := by rw [cast_eq_iff_heq, h] /-- A set of functions "separates points" if for each pair of distinct points there is a function taking different values on them. -/ def Set.SeparatesPoints {α β : Type*} (A : Set (α → β)) : Prop := ∀ ⦃x y : α⦄, x ≠ y → ∃ f ∈ A, (f x : β) ≠ f y theorem IsSymmOp.flip_eq (op) [IsSymmOp α β op] : flip op = op := funext fun a ↦ funext fun b ↦ (IsSymmOp.symm_op a b).symm theorem InvImage.equivalence {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) (h : Equivalence r) : Equivalence (InvImage r f) := ⟨fun _ ↦ h.1 _, fun w ↦ h.symm w, fun h₁ h₂ ↦ InvImage.trans r f (fun _ _ _ ↦ h.trans) h₁ h₂⟩ instance {α β : Type*} {r : α → β → Prop} {x : α × β} [Decidable (r x.1 x.2)] : Decidable (uncurry r x) := ‹Decidable _› instance {α β : Type*} {r : α × β → Prop} {a : α} {b : β} [Decidable (r (a, b))] : Decidable (curry r a b) := ‹Decidable _›
Logic\Function\CompTypeclasses.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.Logic.Function.Defs /-! # Propositional typeclasses on several maps This file contains typeclasses that are used in the definition of equivariant maps in the spirit what was initially developed by Frédéric Dupuis and Heather Macbeth for linear maps. * `CompTriple φ ψ χ`, which expresses that `ψ.comp φ = χ` * `CompTriple.IsId φ`, which expresses that `φ = id` TODO : * align with RingHomCompTriple -/ section CompTriple /-- Class of composing triples -/ class CompTriple {M N P : Type*} (φ : M → N) (ψ : N → P) (χ : outParam (M → P)) : Prop where /-- The maps form a commuting triangle -/ comp_eq : ψ.comp φ = χ attribute [simp] CompTriple.comp_eq namespace CompTriple /-- Class of Id maps -/ class IsId {M : Type*} (σ : M → M) : Prop where eq_id : σ = id instance {M : Type*} : IsId (@id M) where eq_id := rfl instance instComp_id {N P : Type*} {φ : N → N} [IsId φ] {ψ : N → P} : CompTriple φ ψ ψ where comp_eq := by simp only [IsId.eq_id, Function.comp_id] instance instId_comp {M N : Type*} {φ : M → N} {ψ : N → N} [IsId ψ] : CompTriple φ ψ φ where comp_eq := by simp only [IsId.eq_id, Function.id_comp] /-- `φ`, `ψ` and `ψ ∘ φ` for` a `CompTriple` -/ theorem comp {M N P : Type*} {φ : M → N} {ψ : N → P} : CompTriple φ ψ (ψ.comp φ) where comp_eq := rfl lemma comp_inv {M N : Type*} {φ : M → N} {ψ : N → M} (h : Function.RightInverse φ ψ) {χ : M → M} [IsId χ] : CompTriple φ ψ χ where comp_eq := by simp only [IsId.eq_id, h.id] lemma comp_apply {M N P : Type*} {φ : M → N} {ψ : N → P} {χ : M → P} (h : CompTriple φ ψ χ) (x : M) : ψ (φ x) = χ x := by rw [← h.comp_eq, Function.comp_apply] end CompTriple
Logic\Function\Conjugate.lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Logic.Function.Basic /-! # Semiconjugate and commuting maps We define the following predicates: * `Function.Semiconj`: `f : α → β` semiconjugates `ga : α → α` to `gb : β → β` if `f ∘ ga = gb ∘ f`; * `Function.Semiconj₂`: `f : α → β` semiconjugates a binary operation `ga : α → α → α` to `gb : β → β → β` if `f (ga x y) = gb (f x) (f y)`; * `Function.Commute`: `f : α → α` commutes with `g : α → α` if `f ∘ g = g ∘ f`, or equivalently `Semiconj f g g`. -/ namespace Function variable {α : Type*} {β : Type*} {γ : Type*} /-- We say that `f : α → β` semiconjugates `ga : α → α` to `gb : β → β` if `f ∘ ga = gb ∘ f`. We use `∀ x, f (ga x) = gb (f x)` as the definition, so given `h : Function.Semiconj f ga gb` and `a : α`, we have `h a : f (ga a) = gb (f a)` and `h.comp_eq : f ∘ ga = gb ∘ f`. -/ def Semiconj (f : α → β) (ga : α → α) (gb : β → β) : Prop := ∀ x, f (ga x) = gb (f x) namespace Semiconj variable {f fab : α → β} {fbc : β → γ} {ga ga' : α → α} {gb gb' : β → β} {gc gc' : γ → γ} /-- Definition of `Function.Semiconj` in terms of functional equality. -/ lemma _root_.Function.semiconj_iff_comp_eq : Semiconj f ga gb ↔ f ∘ ga = gb ∘ f := funext_iff.symm protected alias ⟨comp_eq, _⟩ := semiconj_iff_comp_eq protected theorem eq (h : Semiconj f ga gb) (x : α) : f (ga x) = gb (f x) := h x /-- If `f` semiconjugates `ga` to `gb` and `ga'` to `gb'`, then it semiconjugates `ga ∘ ga'` to `gb ∘ gb'`. -/ theorem comp_right (h : Semiconj f ga gb) (h' : Semiconj f ga' gb') : Semiconj f (ga ∘ ga') (gb ∘ gb') := fun x ↦ by simp only [comp_apply, h.eq, h'.eq] /-- If `fab : α → β` semiconjugates `ga` to `gb` and `fbc : β → γ` semiconjugates `gb` to `gc`, then `fbc ∘ fab` semiconjugates `ga` to `gc`. See also `Function.Semiconj.comp_left` for a version with reversed arguments. -/ protected theorem trans (hab : Semiconj fab ga gb) (hbc : Semiconj fbc gb gc) : Semiconj (fbc ∘ fab) ga gc := fun x ↦ by simp only [comp_apply, hab.eq, hbc.eq] /-- If `fbc : β → γ` semiconjugates `gb` to `gc` and `fab : α → β` semiconjugates `ga` to `gb`, then `fbc ∘ fab` semiconjugates `ga` to `gc`. See also `Function.Semiconj.trans` for a version with reversed arguments. **Backward compatibility note:** before 2024-01-13, this lemma used to have the same order of arguments that `Function.Semiconj.trans` has now. -/ theorem comp_left (hbc : Semiconj fbc gb gc) (hab : Semiconj fab ga gb) : Semiconj (fbc ∘ fab) ga gc := hab.trans hbc /-- Any function semiconjugates the identity function to the identity function. -/ theorem id_right : Semiconj f id id := fun _ ↦ rfl /-- The identity function semiconjugates any function to itself. -/ theorem id_left : Semiconj id ga ga := fun _ ↦ rfl /-- If `f : α → β` semiconjugates `ga : α → α` to `gb : β → β`, `ga'` is a right inverse of `ga`, and `gb'` is a left inverse of `gb`, then `f` semiconjugates `ga'` to `gb'` as well. -/ theorem inverses_right (h : Semiconj f ga gb) (ha : RightInverse ga' ga) (hb : LeftInverse gb' gb) : Semiconj f ga' gb' := fun x ↦ by rw [← hb (f (ga' x)), ← h.eq, ha x] /-- If `f` semiconjugates `ga` to `gb` and `f'` is both a left and a right inverse of `f`, then `f'` semiconjugates `gb` to `ga`. -/ lemma inverse_left {f' : β → α} (h : Semiconj f ga gb) (hf₁ : LeftInverse f' f) (hf₂ : RightInverse f' f) : Semiconj f' gb ga := fun x ↦ by rw [← hf₁.injective.eq_iff, h, hf₂, hf₂] /-- If `f : α → β` semiconjugates `ga : α → α` to `gb : β → β`, then `Option.map f` semiconjugates `Option.map ga` to `Option.map gb`. -/ theorem option_map {f : α → β} {ga : α → α} {gb : β → β} (h : Semiconj f ga gb) : Semiconj (Option.map f) (Option.map ga) (Option.map gb) | none => rfl | some _ => congr_arg some <| h _ end Semiconj /-- Two maps `f g : α → α` commute if `f (g x) = g (f x)` for all `x : α`. Given `h : Function.commute f g` and `a : α`, we have `h a : f (g a) = g (f a)` and `h.comp_eq : f ∘ g = g ∘ f`. -/ protected def Commute (f g : α → α) : Prop := Semiconj f g g open Function (Commute) /-- Reinterpret `Function.Semiconj f g g` as `Function.Commute f g`. These two predicates are definitionally equal but have different dot-notation lemmas. -/ theorem Semiconj.commute {f g : α → α} (h : Semiconj f g g) : Commute f g := h namespace Commute variable {f f' g g' : α → α} /-- Reinterpret `Function.Commute f g` as `Function.Semiconj f g g`. These two predicates are definitionally equal but have different dot-notation lemmas. -/ theorem semiconj (h : Commute f g) : Semiconj f g g := h @[refl] theorem refl (f : α → α) : Commute f f := fun _ ↦ Eq.refl _ @[symm] theorem symm (h : Commute f g) : Commute g f := fun x ↦ (h x).symm /-- If `f` commutes with `g` and `g'`, then it commutes with `g ∘ g'`. -/ theorem comp_right (h : Commute f g) (h' : Commute f g') : Commute f (g ∘ g') := Semiconj.comp_right h h' /-- If `f` and `f'` commute with `g`, then `f ∘ f'` commutes with `g` as well. -/ nonrec theorem comp_left (h : Commute f g) (h' : Commute f' g) : Commute (f ∘ f') g := h.comp_left h' /-- Any self-map commutes with the identity map. -/ theorem id_right : Commute f id := Semiconj.id_right /-- The identity map commutes with any self-map. -/ theorem id_left : Commute id f := Semiconj.id_left /-- If `f` commutes with `g`, then `Option.map f` commutes with `Option.map g`. -/ nonrec theorem option_map {f g : α → α} (h : Commute f g) : Commute (Option.map f) (Option.map g) := h.option_map end Commute /-- A map `f` semiconjugates a binary operation `ga` to a binary operation `gb` if for all `x`, `y` we have `f (ga x y) = gb (f x) (f y)`. E.g., a `MonoidHom` semiconjugates `(*)` to `(*)`. -/ def Semiconj₂ (f : α → β) (ga : α → α → α) (gb : β → β → β) : Prop := ∀ x y, f (ga x y) = gb (f x) (f y) namespace Semiconj₂ variable {f : α → β} {ga : α → α → α} {gb : β → β → β} protected theorem eq (h : Semiconj₂ f ga gb) (x y : α) : f (ga x y) = gb (f x) (f y) := h x y protected theorem comp_eq (h : Semiconj₂ f ga gb) : bicompr f ga = bicompl gb f f := funext fun x ↦ funext <| h x theorem id_left (op : α → α → α) : Semiconj₂ id op op := fun _ _ ↦ rfl theorem comp {f' : β → γ} {gc : γ → γ → γ} (hf' : Semiconj₂ f' gb gc) (hf : Semiconj₂ f ga gb) : Semiconj₂ (f' ∘ f) ga gc := fun x y ↦ by simp only [hf'.eq, hf.eq, comp_apply] theorem isAssociative_right [Std.Associative ga] (h : Semiconj₂ f ga gb) (h_surj : Surjective f) : Std.Associative gb := ⟨h_surj.forall₃.2 fun x₁ x₂ x₃ ↦ by simp only [← h.eq, Std.Associative.assoc (op := ga)]⟩ theorem isAssociative_left [Std.Associative gb] (h : Semiconj₂ f ga gb) (h_inj : Injective f) : Std.Associative ga := ⟨fun x₁ x₂ x₃ ↦ h_inj <| by simp only [h.eq, Std.Associative.assoc (op := gb)]⟩ theorem isIdempotent_right [Std.IdempotentOp ga] (h : Semiconj₂ f ga gb) (h_surj : Surjective f) : Std.IdempotentOp gb := ⟨h_surj.forall.2 fun x ↦ by simp only [← h.eq, Std.IdempotentOp.idempotent (op := ga)]⟩ theorem isIdempotent_left [Std.IdempotentOp gb] (h : Semiconj₂ f ga gb) (h_inj : Injective f) : Std.IdempotentOp ga := ⟨fun x ↦ h_inj <| by rw [h.eq, Std.IdempotentOp.idempotent (op := gb)]⟩ end Semiconj₂ end Function
Logic\Function\Defs.lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Haitao Zhang -/ import Mathlib.Tactic.AdaptationNote import Mathlib.Tactic.Attr.Register import Mathlib.Tactic.Basic import Mathlib.Tactic.Eqns import Mathlib.Tactic.TypeStar import Batteries.Logic /-! # General operations on functions -/ universe u₁ u₂ u₃ u₄ u₅ namespace Function -- Porting note: fix the universe of `ζ`, it used to be `u₁` variable {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₅} attribute [eqns comp_def] comp lemma flip_def {f : α → β → φ} : flip f = fun b a => f a b := rfl #adaptation_note /-- nightly-2024-03-16 Because of changes in how equation lemmas are generated, `@[eqns]` will only work properly when used immediately after the definition (and when none of the default equation lemmas are needed). Thus this usage is no longer allowed: -/ -- attribute [eqns flip_def] flip /-- Composition of dependent functions: `(f ∘' g) x = f (g x)`, where type of `g x` depends on `x` and type of `f (g x)` depends on `x` and `g x`. -/ @[inline, reducible] def dcomp {β : α → Sort u₂} {φ : ∀ {x : α}, β x → Sort u₃} (f : ∀ {x : α} (y : β x), φ y) (g : ∀ x, β x) : ∀ x, φ (g x) := fun x => f (g x) infixr:80 " ∘' " => Function.dcomp @[reducible, deprecated (since := "2024-01-13")] def compRight (f : β → β → β) (g : α → β) : β → α → β := fun b a => f b (g a) @[reducible, deprecated (since := "2024-01-13")] def compLeft (f : β → β → β) (g : α → β) : α → β → β := fun a b => f (g a) b /-- Given functions `f : β → β → φ` and `g : α → β`, produce a function `α → α → φ` that evaluates `g` on each argument, then applies `f` to the results. Can be used, e.g., to transfer a relation from `β` to `α`. -/ abbrev onFun (f : β → β → φ) (g : α → β) : α → α → φ := fun x y => f (g x) (g y) @[inherit_doc onFun] infixl:2 " on " => onFun /-- Given functions `f : α → β → φ`, `g : α → β → δ` and a binary operator `op : φ → δ → ζ`, produce a function `α → β → ζ` that applies `f` and `g` on each argument and then applies `op` to the results. -/ -- Porting note: the ζ variable was originally constrained to `Sort u₁`, but this seems to -- have been an oversight. @[reducible, deprecated (since := "2024-01-13")] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ) : α → β → ζ := fun x y => op (f x y) (g x y) abbrev swap {φ : α → β → Sort u₃} (f : ∀ x y, φ x y) : ∀ y x, φ x y := fun y x => f x y #adaptation_note /-- nightly-2024-03-16: added to replace simp [Function.swap] -/ theorem swap_def {φ : α → β → Sort u₃} (f : ∀ x y, φ x y) : swap f = fun y x => f x y := rfl @[reducible, deprecated (since := "2024-01-13")] def app {β : α → Sort u₂} (f : ∀ x, β x) (x : α) : β x := f x -- Porting note: removed, it was never used -- notation f " -[" op "]- " g => combine f op g @[simp, mfld_simps] theorem id_comp (f : α → β) : id ∘ f = f := rfl @[deprecated (since := "2024-01-14")] alias left_id := id_comp @[deprecated (since := "2024-01-14")] alias comp.left_id := id_comp @[simp, mfld_simps] theorem comp_id (f : α → β) : f ∘ id = f := rfl @[deprecated (since := "2024-01-14")] alias right_id := comp_id @[deprecated (since := "2024-01-14")] alias comp.right_id := comp_id theorem comp.assoc (f : φ → δ) (g : β → φ) (h : α → β) : (f ∘ g) ∘ h = f ∘ g ∘ h := rfl @[simp] theorem const_comp {γ : Sort*} (f : α → β) (c : γ) : const β c ∘ f = const α c := rfl @[simp] theorem comp_const (f : β → φ) (b : β) : f ∘ const α b = const α (f b) := rfl @[deprecated (since := "2024-01-14")] alias comp_const_right := comp_const /-- A function `f : α → β` is called injective if `f x = f y` implies `x = y`. -/ def Injective (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, f a₁ = f a₂ → a₁ = a₂ theorem Injective.comp {g : β → φ} {f : α → β} (hg : Injective g) (hf : Injective f) : Injective (g ∘ f) := fun _a₁ _a₂ => fun h => hf (hg h) /-- A function `f : α → β` is called surjective if every `b : β` is equal to `f a` for some `a : α`. -/ def Surjective (f : α → β) : Prop := ∀ b, ∃ a, f a = b theorem Surjective.comp {g : β → φ} {f : α → β} (hg : Surjective g) (hf : Surjective f) : Surjective (g ∘ f) := fun c : φ => Exists.elim (hg c) fun b hb => Exists.elim (hf b) fun a ha => Exists.intro a (show g (f a) = c from Eq.trans (congr_arg g ha) hb) /-- A function is called bijective if it is both injective and surjective. -/ def Bijective (f : α → β) := Injective f ∧ Surjective f theorem Bijective.comp {g : β → φ} {f : α → β} : Bijective g → Bijective f → Bijective (g ∘ f) | ⟨h_ginj, h_gsurj⟩, ⟨h_finj, h_fsurj⟩ => ⟨h_ginj.comp h_finj, h_gsurj.comp h_fsurj⟩ /-- `LeftInverse g f` means that g is a left inverse to f. That is, `g ∘ f = id`. -/ def LeftInverse (g : β → α) (f : α → β) : Prop := ∀ x, g (f x) = x /-- `HasLeftInverse f` means that `f` has an unspecified left inverse. -/ def HasLeftInverse (f : α → β) : Prop := ∃ finv : β → α, LeftInverse finv f /-- `RightInverse g f` means that g is a right inverse to f. That is, `f ∘ g = id`. -/ def RightInverse (g : β → α) (f : α → β) : Prop := LeftInverse f g /-- `HasRightInverse f` means that `f` has an unspecified right inverse. -/ def HasRightInverse (f : α → β) : Prop := ∃ finv : β → α, RightInverse finv f theorem LeftInverse.injective {g : β → α} {f : α → β} : LeftInverse g f → Injective f := fun h a b faeqfb => calc a = g (f a) := (h a).symm _ = g (f b) := congr_arg g faeqfb _ = b := h b theorem HasLeftInverse.injective {f : α → β} : HasLeftInverse f → Injective f := fun h => Exists.elim h fun _finv inv => inv.injective theorem rightInverse_of_injective_of_leftInverse {f : α → β} {g : β → α} (injf : Injective f) (lfg : LeftInverse f g) : RightInverse f g := fun x => have h : f (g (f x)) = f x := lfg (f x) injf h theorem RightInverse.surjective {f : α → β} {g : β → α} (h : RightInverse g f) : Surjective f := fun y => ⟨g y, h y⟩ theorem HasRightInverse.surjective {f : α → β} : HasRightInverse f → Surjective f | ⟨_finv, inv⟩ => inv.surjective theorem leftInverse_of_surjective_of_rightInverse {f : α → β} {g : β → α} (surjf : Surjective f) (rfg : RightInverse f g) : LeftInverse f g := fun y => Exists.elim (surjf y) fun x hx => calc f (g y) = f (g (f x)) := hx ▸ rfl _ = f x := Eq.symm (rfg x) ▸ rfl _ = y := hx theorem injective_id : Injective (@id α) := fun _a₁ _a₂ h => h theorem surjective_id : Surjective (@id α) := fun a => ⟨a, rfl⟩ theorem bijective_id : Bijective (@id α) := ⟨injective_id, surjective_id⟩ end Function namespace Function variable {α : Type u₁} {β : Type u₂} {φ : Type u₃} /-- Interpret a function on `α × β` as a function with two arguments. -/ @[inline] def curry : (α × β → φ) → α → β → φ := fun f a b => f (a, b) /-- Interpret a function with two arguments as a function on `α × β` -/ @[inline] def uncurry : (α → β → φ) → α × β → φ := fun f a => f a.1 a.2 @[simp] theorem curry_uncurry (f : α → β → φ) : curry (uncurry f) = f := rfl @[simp] theorem uncurry_curry (f : α × β → φ) : uncurry (curry f) = f := funext fun ⟨_a, _b⟩ => rfl protected theorem LeftInverse.id {g : β → α} {f : α → β} (h : LeftInverse g f) : g ∘ f = id := funext h protected theorem RightInverse.id {g : β → α} {f : α → β} (h : RightInverse g f) : f ∘ g = id := funext h /-- A point `x` is a fixed point of `f : α → α` if `f x = x`. -/ def IsFixedPt (f : α → α) (x : α) := f x = x end Function
Logic\Function\FromTypes.lean
/- Copyright (c) 2024 Brendan Murphy. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Brendan Murphy -/ import Mathlib.Data.Fin.VecNotation /-! # Function types of a given heterogeneous arity This provides `Function.FromTypes`, such that `FromTypes ![α, β] τ = α → β → τ`. Note that it is often preferable to use `((i : Fin n) → p i) → τ` in place of `FromTypes p τ`. ## Main definitions * `Function.FromTypes p τ`: `n`-ary function `p 0 → p 1 → ... → p (n - 1) → β`. -/ universe u namespace Function open Matrix (vecCons vecHead vecTail vecEmpty) /-- The type of `n`-ary functions `p 0 → p 1 → ... → p (n - 1) → τ`. -/ def FromTypes : {n : ℕ} → (Fin n → Type u) → Type u → Type u | 0 , _, τ => τ | n + 1, p, τ => vecHead p → @FromTypes n (vecTail p) τ theorem fromTypes_zero (p : Fin 0 → Type u) (τ : Type u) : FromTypes p τ = τ := rfl theorem fromTypes_nil (τ : Type u) : FromTypes ![] τ = τ := fromTypes_zero ![] τ -- prefer `fromTypes_cons` when it (syntactically) applies theorem fromTypes_succ {n} (p : Fin (n + 1) → Type u) (τ : Type u) : FromTypes p τ = (vecHead p → FromTypes (vecTail p) τ) := rfl theorem fromTypes_cons {n} (α : Type u) (p : Fin n → Type u) (τ : Type u) : FromTypes (vecCons α p) τ = (α → FromTypes p τ) := fromTypes_succ _ τ /-- The definitional equality between `0`-ary heterogeneous functions into `τ` and `τ`. -/ @[simps!] def fromTypes_zero_equiv (p : Fin 0 → Type u) (τ : Type u) : FromTypes p τ ≃ τ := Equiv.refl _ /-- The definitional equality between `![]`-ary heterogeneous functions into `τ` and `τ`. -/ @[simps!] def fromTypes_nil_equiv (τ : Type u) : FromTypes ![] τ ≃ τ := fromTypes_zero_equiv ![] τ /-- The definitional equality between `p`-ary heterogeneous functions into `τ` and function from `vecHead p` to `(vecTail p)`-ary heterogeneous functions into `τ`. -/ @[simps!] def fromTypes_succ_equiv {n} (p : Fin (n + 1) → Type u) (τ : Type u) : FromTypes p τ ≃ (vecHead p → FromTypes (vecTail p) τ) := Equiv.refl _ /-- The definitional equality between `(vecCons α p)`-ary heterogeneous functions into `τ` and function from `α` to `p`-ary heterogeneous functions into `τ`. -/ @[simps!] def fromTypes_cons_equiv {n} (α : Type u) (p : Fin n → Type u) (τ : Type u) : FromTypes (vecCons α p) τ ≃ (α → FromTypes p τ) := fromTypes_succ_equiv _ _ namespace FromTypes /-- Constant `n`-ary function with value `t`. -/ def const : {n : ℕ} → (p : Fin n → Type u) → {τ : Type u} → (t : τ) → FromTypes p τ | 0, _, _, t => t | n + 1, p, τ, t => fun _ => @const n (vecTail p) τ t @[simp] theorem const_zero (p : Fin 0 → Type u) {τ : Type u} (t : τ) : const p t = t := rfl @[simp] theorem const_succ {n} (p : Fin (n + 1) → Type u) {τ : Type u} (t : τ) : const p t = fun _ => const (vecTail p) t := rfl theorem const_succ_apply {n} (p : Fin (n + 1) → Type u) {τ : Type u} (t : τ) (x : p 0) : const p t x = const (vecTail p) t := rfl instance inhabited {n} {p : Fin n → Type u} {τ} [Inhabited τ] : Inhabited (FromTypes p τ) := ⟨const p default⟩ end FromTypes end Function
Logic\Function\Iterate.lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Logic.Function.Conjugate /-! # Iterations of a function In this file we prove simple properties of `Nat.iterate f n` a.k.a. `f^[n]`: * `iterate_zero`, `iterate_succ`, `iterate_succ'`, `iterate_add`, `iterate_mul`: formulas for `f^[0]`, `f^[n+1]` (two versions), `f^[n+m]`, and `f^[n*m]`; * `iterate_id` : `id^[n]=id`; * `Injective.iterate`, `Surjective.iterate`, `Bijective.iterate` : iterates of an injective/surjective/bijective function belong to the same class; * `LeftInverse.iterate`, `RightInverse.iterate`, `Commute.iterate_left`, `Commute.iterate_right`, `Commute.iterate_iterate`: some properties of pairs of functions survive under iterations * `iterate_fixed`, `Function.Semiconj.iterate_*`, `Function.Semiconj₂.iterate`: if `f` fixes a point (resp., semiconjugates unary/binary operations), then so does `f^[n]`. -/ universe u v variable {α : Type u} {β : Type v} /-- Iterate a function. -/ def Nat.iterate {α : Sort u} (op : α → α) : ℕ → α → α | 0, a => a | succ k, a => iterate op k (op a) @[inherit_doc Nat.iterate] notation:max f "^["n"]" => Nat.iterate f n namespace Function open Function (Commute) variable (f : α → α) @[simp] theorem iterate_zero : f^[0] = id := rfl theorem iterate_zero_apply (x : α) : f^[0] x = x := rfl @[simp] theorem iterate_succ (n : ℕ) : f^[n.succ] = f^[n] ∘ f := rfl theorem iterate_succ_apply (n : ℕ) (x : α) : f^[n.succ] x = f^[n] (f x) := rfl @[simp] theorem iterate_id (n : ℕ) : (id : α → α)^[n] = id := Nat.recOn n rfl fun n ihn ↦ by rw [iterate_succ, ihn, id_comp] theorem iterate_add (m : ℕ) : ∀ n : ℕ, f^[m + n] = f^[m] ∘ f^[n] | 0 => rfl | Nat.succ n => by rw [Nat.add_succ, iterate_succ, iterate_succ, iterate_add m n]; rfl theorem iterate_add_apply (m n : ℕ) (x : α) : f^[m + n] x = f^[m] (f^[n] x) := by rw [iterate_add f m n] rfl -- can be proved by simp but this is shorter and more natural @[simp high] theorem iterate_one : f^[1] = f := funext fun _ ↦ rfl theorem iterate_mul (m : ℕ) : ∀ n, f^[m * n] = f^[m]^[n] | 0 => by simp only [Nat.mul_zero, iterate_zero] | n + 1 => by simp only [Nat.mul_succ, Nat.mul_one, iterate_one, iterate_add, iterate_mul m n] variable {f} theorem iterate_fixed {x} (h : f x = x) (n : ℕ) : f^[n] x = x := Nat.recOn n rfl fun n ihn ↦ by rw [iterate_succ_apply, h, ihn] theorem Injective.iterate (Hinj : Injective f) (n : ℕ) : Injective f^[n] := Nat.recOn n injective_id fun _ ihn ↦ ihn.comp Hinj theorem Surjective.iterate (Hsurj : Surjective f) (n : ℕ) : Surjective f^[n] := Nat.recOn n surjective_id fun _ ihn ↦ ihn.comp Hsurj theorem Bijective.iterate (Hbij : Bijective f) (n : ℕ) : Bijective f^[n] := ⟨Hbij.1.iterate n, Hbij.2.iterate n⟩ namespace Semiconj theorem iterate_right {f : α → β} {ga : α → α} {gb : β → β} (h : Semiconj f ga gb) (n : ℕ) : Semiconj f ga^[n] gb^[n] := Nat.recOn n id_right fun _ ihn ↦ ihn.comp_right h theorem iterate_left {g : ℕ → α → α} (H : ∀ n, Semiconj f (g n) (g <| n + 1)) (n k : ℕ) : Semiconj f^[n] (g k) (g <| n + k) := by induction n generalizing k with | zero => rw [Nat.zero_add] exact id_left | succ n ihn => rw [Nat.add_right_comm, Nat.add_assoc] exact (H k).trans (ihn (k + 1)) end Semiconj namespace Commute variable {g : α → α} theorem iterate_right (h : Commute f g) (n : ℕ) : Commute f g^[n] := Semiconj.iterate_right h n theorem iterate_left (h : Commute f g) (n : ℕ) : Commute f^[n] g := (h.symm.iterate_right n).symm theorem iterate_iterate (h : Commute f g) (m n : ℕ) : Commute f^[m] g^[n] := (h.iterate_left m).iterate_right n theorem iterate_eq_of_map_eq (h : Commute f g) (n : ℕ) {x} (hx : f x = g x) : f^[n] x = g^[n] x := Nat.recOn n rfl fun n ihn ↦ by simp only [iterate_succ_apply, hx, (h.iterate_left n).eq, ihn, ((refl g).iterate_right n).eq] theorem comp_iterate (h : Commute f g) (n : ℕ) : (f ∘ g)^[n] = f^[n] ∘ g^[n] := by induction n with | zero => rfl | succ n ihn => funext x simp only [ihn, (h.iterate_right n).eq, iterate_succ, comp_apply] variable (f) theorem iterate_self (n : ℕ) : Commute f^[n] f := (refl f).iterate_left n theorem self_iterate (n : ℕ) : Commute f f^[n] := (refl f).iterate_right n theorem iterate_iterate_self (m n : ℕ) : Commute f^[m] f^[n] := (refl f).iterate_iterate m n end Commute theorem Semiconj₂.iterate {f : α → α} {op : α → α → α} (hf : Semiconj₂ f op op) (n : ℕ) : Semiconj₂ f^[n] op op := Nat.recOn n (Semiconj₂.id_left op) fun _ ihn ↦ ihn.comp hf variable (f) theorem iterate_succ' (n : ℕ) : f^[n.succ] = f ∘ f^[n] := by rw [iterate_succ, (Commute.self_iterate f n).comp_eq] theorem iterate_succ_apply' (n : ℕ) (x : α) : f^[n.succ] x = f (f^[n] x) := by rw [iterate_succ'] rfl theorem iterate_pred_comp_of_pos {n : ℕ} (hn : 0 < n) : f^[n.pred] ∘ f = f^[n] := by rw [← iterate_succ, Nat.succ_pred_eq_of_pos hn] theorem comp_iterate_pred_of_pos {n : ℕ} (hn : 0 < n) : f ∘ f^[n.pred] = f^[n] := by rw [← iterate_succ', Nat.succ_pred_eq_of_pos hn] /-- A recursor for the iterate of a function. -/ def Iterate.rec (p : α → Sort*) {f : α → α} (h : ∀ a, p a → p (f a)) {a : α} (ha : p a) (n : ℕ) : p (f^[n] a) := match n with | 0 => ha | m+1 => Iterate.rec p h (h _ ha) m theorem Iterate.rec_zero (p : α → Sort*) {f : α → α} (h : ∀ a, p a → p (f a)) {a : α} (ha : p a) : Iterate.rec p h ha 0 = ha := rfl variable {f} {m n : ℕ} {a : α} theorem LeftInverse.iterate {g : α → α} (hg : LeftInverse g f) (n : ℕ) : LeftInverse g^[n] f^[n] := Nat.recOn n (fun _ ↦ rfl) fun n ihn ↦ by rw [iterate_succ', iterate_succ] exact ihn.comp hg theorem RightInverse.iterate {g : α → α} (hg : RightInverse g f) (n : ℕ) : RightInverse g^[n] f^[n] := LeftInverse.iterate hg n theorem iterate_comm (f : α → α) (m n : ℕ) : f^[n]^[m] = f^[m]^[n] := (iterate_mul _ _ _).symm.trans (Eq.trans (by rw [Nat.mul_comm]) (iterate_mul _ _ _)) theorem iterate_commute (m n : ℕ) : Commute (fun f : α → α ↦ f^[m]) fun f ↦ f^[n] := fun f ↦ iterate_comm f m n lemma iterate_add_eq_iterate (hf : Injective f) : f^[m + n] a = f^[n] a ↔ f^[m] a = a := Iff.trans (by rw [← iterate_add_apply, Nat.add_comm]) (hf.iterate n).eq_iff alias ⟨iterate_cancel_of_add, _⟩ := iterate_add_eq_iterate lemma iterate_cancel (hf : Injective f) (ha : f^[m] a = f^[n] a) : f^[m - n] a = a := by obtain h | h := Nat.le_total m n { simp [Nat.sub_eq_zero_of_le h] } { exact iterate_cancel_of_add hf (by rwa [Nat.sub_add_cancel h]) } theorem involutive_iff_iter_2_eq_id {α} {f : α → α} : Involutive f ↔ f^[2] = id := funext_iff.symm end Function namespace List open Function theorem foldl_const (f : α → α) (a : α) (l : List β) : l.foldl (fun b _ ↦ f b) a = f^[l.length] a := by induction l generalizing a with | nil => rfl | cons b l H => rw [length_cons, foldl, iterate_succ_apply, H] theorem foldr_const (f : β → β) (b : β) : ∀ l : List α, l.foldr (fun _ ↦ f) b = f^[l.length] b | [] => rfl | a :: l => by rw [length_cons, foldr, foldr_const f b l, iterate_succ_apply'] end List
Logic\Function\OfArity.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Logic.Function.FromTypes /-! # Function types of a given arity This provides `Function.OfArity`, such that `OfArity α β 2 = α → α → β`. Note that it is often preferable to use `(Fin n → α) → β` in place of `OfArity n α β`. ## Main definitions * `Function.OfArity α β n`: `n`-ary function `α → α → ... → β`. Defined inductively. * `Function.OfArity.const α b n`: `n`-ary constant function equal to `b`. -/ universe u namespace Function /-- The type of `n`-ary functions `α → α → ... → β`. Note that this is not universe polymorphic, as this would require that when `n=0` we produce either `Unit → β` or `ULift β`. -/ abbrev OfArity (α β : Type u) (n : ℕ) : Type u := FromTypes (fun (_ : Fin n) => α) β @[simp] theorem ofArity_zero (α β : Type u) : OfArity α β 0 = β := fromTypes_zero _ _ @[simp] theorem ofArity_succ (α β : Type u) (n : ℕ) : OfArity α β n.succ = (α → OfArity α β n) := fromTypes_succ _ _ namespace OfArity /-- Constant `n`-ary function with value `b`. -/ def const (α : Type u) {β : Type u} (b : β) (n : ℕ) : OfArity α β n := FromTypes.const (fun _ => α) b @[simp] theorem const_zero (α : Type u) {β : Type u} (b : β) : const α b 0 = b := FromTypes.const_zero (fun _ => α) b @[simp] theorem const_succ (α : Type u) {β : Type u} (b : β) (n : ℕ) : const α b n.succ = fun _ => const _ b n := FromTypes.const_succ (fun _ => α) b theorem const_succ_apply (α : Type u) {β : Type u} (b : β) (n : ℕ) (x : α) : const α b n.succ x = const _ b n := FromTypes.const_succ_apply _ b x instance inhabited {α β n} [Inhabited β] : Inhabited (OfArity α β n) := inferInstanceAs (Inhabited (FromTypes (fun _ => α) β)) end OfArity namespace FromTypes lemma fromTypes_fin_const (α β : Type u) (n : ℕ) : FromTypes (fun (_ : Fin n) => α) β = OfArity α β n := rfl /-- The definitional equality between heterogeneous functions with constant domain and `n`-ary functions with that domain. -/ def fromTypes_fin_const_equiv (α β : Type u) (n : ℕ) : FromTypes (fun (_ : Fin n) => α) β ≃ OfArity α β n := .refl _ end FromTypes end Function
Logic\Function\ULift.lean
/- Copyright (c) 2016 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.Logic.Function.Defs /-! # `ULift` and `PLift` -/ theorem ULift.down_injective {α : Sort _} : Function.Injective (@ULift.down α) | ⟨a⟩, ⟨b⟩, _ => by congr @[simp] theorem ULift.down_inj {α : Sort _} {a b : ULift α} : a.down = b.down ↔ a = b := ⟨fun h ↦ ULift.down_injective h, fun h ↦ by rw [h]⟩ variable {α : Sort*} theorem PLift.down_injective : Function.Injective (@PLift.down α) | ⟨a⟩, ⟨b⟩, _ => by congr @[simp] theorem PLift.down_inj {a b : PLift α} : a.down = b.down ↔ a = b := ⟨fun h ↦ PLift.down_injective h, fun h ↦ by rw [h]⟩
Logic\Godel\GodelBetaFunction.lean
/- Copyright (c) 2023 Shogo Saito. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shogo Saito. Adapted for mathlib by Hunter Monroe -/ import Mathlib.Data.Nat.ModEq import Mathlib.Data.Nat.ChineseRemainder import Mathlib.Data.Nat.Prime.Defs import Mathlib.Data.Nat.Pairing /-! # Gödel's Beta Function Lemma This file proves Gödel's Beta Function Lemma, used to prove the First Incompleteness Theorem. It permits quantification over finite sequences of natural numbers in formal theories of arithmetic. This Beta Function has no connection with the unrelated Beta Function defined in analysis. Note that `Nat.beta` and `Nat.unbeta` provide similar functionality to `Encodable.encodeList` and `Encodable.decodeList`. We define these separately, because it is easier to prove that `Nat.beta` and `Nat.unbeta` are arithmetically definable, and this is hard to prove that for `Encodable.encodeList` and `Encodable.decodeList` directly. The arithmetic definability is needed for the proof of the First Incompleteness Theorem. ## Main result - `beta_unbeta_coe`: Gödel's Beta Function Lemma. ## Implementation note This code is a step towards eventually including a proof of Gödel's First Incompleteness Theorem and other key results from the repository https://github.com/iehality/lean4-logic. ## References * [R. Kaye, *Models of Peano arithmetic*][kaye1991] * <https://en.wikipedia.org/wiki/G%C3%B6del%27s_%CE%B2_function> ## Tags Gödel, beta function -/ namespace Nat lemma coprime_mul_succ {n m a} (h : n ≤ m) (ha : m - n ∣ a) : Coprime (n * a + 1) (m * a + 1) := Nat.coprime_of_dvd fun p pp hn hm => by have : p ∣ (m - n) * a := by simpa [Nat.succ_sub_succ, ← Nat.mul_sub_right_distrib] using Nat.dvd_sub (Nat.succ_le_succ $ Nat.mul_le_mul_right a h) hm hn have : p ∣ a := by rcases (Nat.Prime.dvd_mul pp).mp this with (hp | hp) · exact Nat.dvd_trans hp ha · exact hp apply pp.ne_one simpa [Nat.add_sub_cancel_left] using Nat.dvd_sub (le_add_right _ _) hn (this.mul_left n) variable {m : ℕ} private def supOfSeq (a : Fin m → ℕ) : ℕ := max m (Finset.sup .univ a) + 1 private def coprimes (a : Fin m → ℕ) : Fin m → ℕ := fun i => (i + 1) * (supOfSeq a)! + 1 lemma coprimes_lt (a : Fin m → ℕ) (i) : a i < coprimes a i := by have h₁ : a i < supOfSeq a := Nat.lt_add_one_iff.mpr (le_max_of_le_right $ Finset.le_sup (by simp)) have h₂ : supOfSeq a ≤ (i + 1) * (supOfSeq a)! + 1 := le_trans (self_le_factorial _) (le_trans (Nat.le_mul_of_pos_left (supOfSeq a)! (succ_pos i)) (le_add_right _ _)) simpa only [coprimes] using lt_of_lt_of_le h₁ h₂ private lemma pairwise_coprime_coprimes (a : Fin m → ℕ) : Pairwise (Coprime on coprimes a) := by intro i j hij wlog ltij : i < j · exact (this a hij.symm (lt_of_le_of_ne (Fin.not_lt.mp ltij) hij.symm)).symm unfold Function.onFun coprimes have hja : j < supOfSeq a := lt_of_lt_of_le j.prop (le_step (le_max_left _ _)) exact coprime_mul_succ (Nat.succ_le_succ $ le_of_lt ltij) (Nat.dvd_factorial (by simp [Nat.succ_sub_succ, ltij]) (by simpa only [Nat.succ_sub_succ] using le_of_lt (lt_of_le_of_lt (sub_le j i) hja))) /-- Gödel's Beta Function. This is similar to `(Encodable.decodeList).get i`, but it is easier to prove that it is arithmetically definable. -/ def beta (n i : ℕ) : ℕ := n.unpair.1 % ((i + 1) * n.unpair.2 + 1) /-- Inverse of Gödel's Beta Function. This is similar to `Encodable.encodeList`, but it is easier to prove that it is arithmetically definable. -/ def unbeta (l : List ℕ) : ℕ := (chineseRemainderOfFinset l.get (coprimes l.get) Finset.univ (by simp [coprimes]) (by simpa using Set.pairwise_univ.mpr (pairwise_coprime_coprimes _)) : ℕ).pair (supOfSeq l.get)! /-- **Gödel's Beta Function Lemma** -/ lemma beta_unbeta_coe (l : List ℕ) (i : Fin l.length) : beta (unbeta l) i = l.get i := by simpa [beta, unbeta, coprimes] using mod_eq_of_modEq ((chineseRemainderOfFinset l.get (coprimes l.get) Finset.univ (by simp [coprimes]) (by simpa using Set.pairwise_univ.mpr (pairwise_coprime_coprimes _))).prop i (by simp)) (coprimes_lt l.get _) end Nat
Logic\Nontrivial\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 -/ import Mathlib.Data.Prod.Basic import Mathlib.Logic.Function.Basic import Mathlib.Logic.Nontrivial.Defs import Mathlib.Logic.Unique import Mathlib.Order.Defs import Mathlib.Tactic.Attr.Register /-! # Nontrivial types Results about `Nontrivial`. -/ variable {α : Type*} {β : Type*} open scoped Classical -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. theorem nontrivial_of_lt [Preorder α] (x y : α) (h : x < y) : Nontrivial α := ⟨⟨x, y, ne_of_lt h⟩⟩ theorem exists_pair_lt (α : Type*) [Nontrivial α] [LinearOrder α] : ∃ x y : α, x < y := by rcases exists_pair_ne α with ⟨x, y, hxy⟩ cases lt_or_gt_of_ne hxy <;> exact ⟨_, _, ‹_›⟩ theorem nontrivial_iff_lt [LinearOrder α] : Nontrivial α ↔ ∃ x y : α, x < y := ⟨fun h ↦ @exists_pair_lt α h _, fun ⟨x, y, h⟩ ↦ nontrivial_of_lt x y h⟩ theorem Subtype.nontrivial_iff_exists_ne (p : α → Prop) (x : Subtype p) : Nontrivial (Subtype p) ↔ ∃ (y : α) (_ : p y), y ≠ x := by simp only [_root_.nontrivial_iff_exists_ne x, Subtype.exists, Ne, Subtype.ext_iff] /-- An inhabited type is either nontrivial, or has a unique element. -/ noncomputable def nontrivialPSumUnique (α : Type*) [Inhabited α] : Nontrivial α ⊕' Unique α := if h : Nontrivial α then PSum.inl h else PSum.inr { default := default, uniq := fun x : α ↦ by by_contra H exact h ⟨_, _, H⟩ } instance Option.nontrivial [Nonempty α] : Nontrivial (Option α) := by inhabit α exact ⟨none, some default, nofun⟩ /-- Pushforward a `Nontrivial` instance along an injective function. -/ protected theorem Function.Injective.nontrivial [Nontrivial α] {f : α → β} (hf : Function.Injective f) : Nontrivial β := let ⟨x, y, h⟩ := exists_pair_ne α ⟨⟨f x, f y, hf.ne h⟩⟩ /-- An injective function from a nontrivial type has an argument at which it does not take a given value. -/ protected theorem Function.Injective.exists_ne [Nontrivial α] {f : α → β} (hf : Function.Injective f) (y : β) : ∃ x, f x ≠ y := by rcases exists_pair_ne α with ⟨x₁, x₂, hx⟩ by_cases h : f x₂ = y · exact ⟨x₁, (hf.ne_iff' h).2 hx⟩ · exact ⟨x₂, h⟩ instance nontrivial_prod_right [Nonempty α] [Nontrivial β] : Nontrivial (α × β) := Prod.snd_surjective.nontrivial instance nontrivial_prod_left [Nontrivial α] [Nonempty β] : Nontrivial (α × β) := Prod.fst_surjective.nontrivial namespace Pi variable {I : Type*} {f : I → Type*} /-- A pi type is nontrivial if it's nonempty everywhere and nontrivial somewhere. -/ theorem nontrivial_at (i' : I) [inst : ∀ i, Nonempty (f i)] [Nontrivial (f i')] : Nontrivial (∀ i : I, f i) := by letI := Classical.decEq (∀ i : I, f i) exact (Function.update_injective (fun i ↦ Classical.choice (inst i)) i').nontrivial /-- As a convenience, provide an instance automatically if `(f default)` is nontrivial. If a different index has the non-trivial type, then use `haveI := nontrivial_at that_index`. -/ instance nontrivial [Inhabited I] [∀ i, Nonempty (f i)] [Nontrivial (f default)] : Nontrivial (∀ i : I, f i) := nontrivial_at default end Pi instance Function.nontrivial [h : Nonempty α] [Nontrivial β] : Nontrivial (α → β) := h.elim fun a ↦ Pi.nontrivial_at a @[nontriviality] protected theorem Subsingleton.le [Preorder α] [Subsingleton α] (x y : α) : x ≤ y := le_of_eq (Subsingleton.elim x y) @[to_additive] theorem Subsingleton.eq_one [One α] [Subsingleton α] (a : α) : a = 1 := Subsingleton.elim _ _
Logic\Nontrivial\Defs.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 -/ import Mathlib.Init.Logic import Mathlib.Logic.Function.Defs import Mathlib.Tactic.TypeStar /-! # Nontrivial types A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings (where it is equivalent to the fact that zero is different from one) and for vector spaces (where it is equivalent to the fact that the dimension is positive). We introduce a typeclass `Nontrivial` formalizing this property. Basic results about nontrivial types are in `Mathlib.Logic.Nontrivial.Basic`. -/ variable {α : Type*} {β : Type*} open scoped Classical /-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings, this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/ class Nontrivial (α : Type*) : Prop where /-- In a nontrivial type, there exists a pair of distinct terms. -/ exists_pair_ne : ∃ x y : α, x ≠ y theorem nontrivial_iff : Nontrivial α ↔ ∃ x y : α, x ≠ y := ⟨fun h ↦ h.exists_pair_ne, fun h ↦ ⟨h⟩⟩ theorem exists_pair_ne (α : Type*) [Nontrivial α] : ∃ x y : α, x ≠ y := Nontrivial.exists_pair_ne -- See Note [decidable namespace] protected theorem Decidable.exists_ne [Nontrivial α] [DecidableEq α] (x : α) : ∃ y, y ≠ x := by rcases exists_pair_ne α with ⟨y, y', h⟩ by_cases hx : x = y · rw [← hx] at h exact ⟨y', h.symm⟩ · exact ⟨y, Ne.symm hx⟩ theorem exists_ne [Nontrivial α] (x : α) : ∃ y, y ≠ x := Decidable.exists_ne x -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. theorem nontrivial_of_ne (x y : α) (h : x ≠ y) : Nontrivial α := ⟨⟨x, y, h⟩⟩ theorem nontrivial_iff_exists_ne (x : α) : Nontrivial α ↔ ∃ y, y ≠ x := ⟨fun h ↦ @exists_ne α h x, fun ⟨_, hy⟩ ↦ nontrivial_of_ne _ _ hy⟩ instance : Nontrivial Prop := ⟨⟨True, False, true_ne_false⟩⟩ /-- See Note [lower instance priority] Note that since this and `instNonemptyOfInhabited` are the most "obvious" way to find a nonempty instance if no direct instance can be found, we give this a higher priority than the usual `100`. -/ instance (priority := 500) Nontrivial.to_nonempty [Nontrivial α] : Nonempty α := let ⟨x, _⟩ := _root_.exists_pair_ne α ⟨x⟩ theorem subsingleton_iff : Subsingleton α ↔ ∀ x y : α, x = y := ⟨by intro h exact Subsingleton.elim, fun h ↦ ⟨h⟩⟩ theorem not_nontrivial_iff_subsingleton : ¬Nontrivial α ↔ Subsingleton α := by simp only [nontrivial_iff, subsingleton_iff, not_exists, Classical.not_not] theorem not_nontrivial (α) [Subsingleton α] : ¬Nontrivial α := fun ⟨⟨x, y, h⟩⟩ ↦ h <| Subsingleton.elim x y theorem not_subsingleton (α) [Nontrivial α] : ¬Subsingleton α := fun _ => not_nontrivial _ ‹_› lemma not_subsingleton_iff_nontrivial : ¬ Subsingleton α ↔ Nontrivial α := by rw [← not_nontrivial_iff_subsingleton, Classical.not_not] /-- A type is either a subsingleton or nontrivial. -/ theorem subsingleton_or_nontrivial (α : Type*) : Subsingleton α ∨ Nontrivial α := by rw [← not_nontrivial_iff_subsingleton, or_comm] exact Classical.em _ theorem false_of_nontrivial_of_subsingleton (α : Type*) [Nontrivial α] [Subsingleton α] : False := not_nontrivial _ ‹_› /-- Pullback a `Nontrivial` instance along a surjective function. -/ protected theorem Function.Surjective.nontrivial [Nontrivial β] {f : α → β} (hf : Function.Surjective f) : Nontrivial α := by rcases exists_pair_ne β with ⟨x, y, h⟩ rcases hf x with ⟨x', hx'⟩ rcases hf y with ⟨y', hy'⟩ have : x' ≠ y' := by refine fun H ↦ h ?_ rw [← hx', ← hy', H] exact ⟨⟨x', y', this⟩⟩ namespace Bool instance : Nontrivial Bool := ⟨⟨true, false, nofun⟩⟩ end Bool
Logic\Small\Basic.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Logic.Small.Defs import Mathlib.Logic.Equiv.Set /-! # Instances and theorems for `Small`. In particular we prove `small_of_injective` and `small_of_surjective`. -/ universe u w v v' section open scoped Classical instance small_subtype (α : Type v) [Small.{w} α] (P : α → Prop) : Small.{w} { x // P x } := small_map (equivShrink α).subtypeEquivOfSubtype' theorem small_of_injective {α : Type v} {β : Type w} [Small.{u} β] {f : α → β} (hf : Function.Injective f) : Small.{u} α := small_map (Equiv.ofInjective f hf) theorem small_of_surjective {α : Type v} {β : Type w} [Small.{u} α] {f : α → β} (hf : Function.Surjective f) : Small.{u} β := small_of_injective (Function.injective_surjInv hf) instance (priority := 100) small_subsingleton (α : Type v) [Subsingleton α] : Small.{w} α := by rcases isEmpty_or_nonempty α with ⟨⟩ · apply small_map (Equiv.equivPEmpty α) · apply small_map Equiv.punitOfNonemptyOfSubsingleton /-- This can be seen as a version of `small_of_surjective` in which the function `f` doesn't actually land in `β` but in some larger type `γ` related to `β` via an injective function `g`. -/ theorem small_of_injective_of_exists {α : Type v} {β : Type w} {γ : Type v'} [Small.{u} α] (f : α → γ) {g : β → γ} (hg : Function.Injective g) (h : ∀ b : β, ∃ a : α, f a = g b) : Small.{u} β := by by_cases hβ : Nonempty β · refine small_of_surjective (f := Function.invFun g ∘ f) (fun b => ?_) obtain ⟨a, ha⟩ := h b exact ⟨a, by rw [Function.comp_apply, ha, Function.leftInverse_invFun hg]⟩ · simp only [not_nonempty_iff] at hβ infer_instance /-! We don't define `Countable.toSmall` in this file, to keep imports to `Logic` to a minimum. -/ instance small_Pi {α} (β : α → Type*) [Small.{w} α] [∀ a, Small.{w} (β a)] : Small.{w} (∀ a, β a) := ⟨⟨∀ a' : Shrink α, Shrink (β ((equivShrink α).symm a')), ⟨Equiv.piCongr (equivShrink α) fun a => by simpa using equivShrink (β a)⟩⟩⟩ instance small_prod {α β} [Small.{w} α] [Small.{w} β] : Small.{w} (α × β) := ⟨⟨Shrink α × Shrink β, ⟨Equiv.prodCongr (equivShrink α) (equivShrink β)⟩⟩⟩ instance small_sum {α β} [Small.{w} α] [Small.{w} β] : Small.{w} (α ⊕ β) := ⟨⟨Shrink α ⊕ Shrink β, ⟨Equiv.sumCongr (equivShrink α) (equivShrink β)⟩⟩⟩ instance small_set {α} [Small.{w} α] : Small.{w} (Set α) := ⟨⟨Set (Shrink α), ⟨Equiv.Set.congr (equivShrink α)⟩⟩⟩ end
Logic\Small\Defs.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.MkIffOfInductiveProp import Mathlib.Tactic.PPWithUniv /-! # Small types A type is `w`-small if there exists an equivalence to some `S : Type w`. We provide a noncomputable model `Shrink α : Type w`, and `equivShrink α : α ≃ Shrink α`. A subsingleton type is `w`-small for any `w`. If `α ≃ β`, then `Small.{w} α ↔ Small.{w} β`. See `Mathlib.Logic.Small.Basic` for further instances and theorems. -/ universe u w v v' /-- A type is `Small.{w}` if there exists an equivalence to some `S : Type w`. -/ @[mk_iff, pp_with_univ] class Small (α : Type v) : Prop where /-- If a type is `Small.{w}`, then there exists an equivalence with some `S : Type w` -/ equiv_small : ∃ S : Type w, Nonempty (α ≃ S) /-- Constructor for `Small α` from an explicit witness type and equivalence. -/ theorem Small.mk' {α : Type v} {S : Type w} (e : α ≃ S) : Small.{w} α := ⟨⟨S, ⟨e⟩⟩⟩ /-- An arbitrarily chosen model in `Type w` for a `w`-small type. -/ @[pp_with_univ] def Shrink (α : Type v) [Small.{w} α] : Type w := Classical.choose (@Small.equiv_small α _) /-- The noncomputable equivalence between a `w`-small type and a model. -/ noncomputable def equivShrink (α : Type v) [Small.{w} α] : α ≃ Shrink α := Nonempty.some (Classical.choose_spec (@Small.equiv_small α _)) @[ext] theorem Shrink.ext {α : Type v} [Small.{w} α] {x y : Shrink α} (w : (equivShrink _).symm x = (equivShrink _).symm y) : x = y := by simpa using w -- It would be nice to mark this as `aesop cases` if -- https://github.com/JLimperg/aesop/issues/59 -- is resolved. @[induction_eliminator] protected noncomputable def Shrink.rec {α : Type*} [Small.{w} α] {F : Shrink α → Sort v} (h : ∀ X, F (equivShrink _ X)) : ∀ X, F X := fun X => ((equivShrink _).apply_symm_apply X) ▸ (h _) -- Porting note: Priority changed to 101 instance (priority := 101) small_self (α : Type v) : Small.{v} α := Small.mk' <| Equiv.refl α theorem small_map {α : Type*} {β : Type*} [hβ : Small.{w} β] (e : α ≃ β) : Small.{w} α := let ⟨_, ⟨f⟩⟩ := hβ.equiv_small Small.mk' (e.trans f) theorem small_lift (α : Type u) [hα : Small.{v} α] : Small.{max v w} α := let ⟨⟨_, ⟨f⟩⟩⟩ := hα Small.mk' <| f.trans (Equiv.ulift.{w}).symm /- This was an instance but useless due to https://github.com/leanprover/lean4/issues/2297. -/ lemma small_max (α : Type v) : Small.{max w v} α := small_lift.{v, w} α instance small_zero (α : Type) : Small.{w} α := small_max α instance (priority := 100) small_succ (α : Type v) : Small.{v+1} α := small_lift.{v, v+1} α instance small_ulift (α : Type u) [Small.{v} α] : Small.{v} (ULift.{w} α) := small_map Equiv.ulift theorem small_type : Small.{max (u + 1) v} (Type u) := small_max.{max (u + 1) v} _ section open scoped Classical theorem small_congr {α : Type*} {β : Type*} (e : α ≃ β) : Small.{w} α ↔ Small.{w} β := ⟨fun h => @small_map _ _ h e.symm, fun h => @small_map _ _ h e⟩ instance small_sigma {α} (β : α → Type*) [Small.{w} α] [∀ a, Small.{w} (β a)] : Small.{w} (Σa, β a) := ⟨⟨Σa' : Shrink α, Shrink (β ((equivShrink α).symm a')), ⟨Equiv.sigmaCongr (equivShrink α) fun a => by simpa using equivShrink (β a)⟩⟩⟩ theorem not_small_type : ¬Small.{u} (Type max u v) | ⟨⟨S, ⟨e⟩⟩⟩ => @Function.cantor_injective (Σα, e.symm α) (fun a => ⟨_, cast (e.3 _).symm a⟩) fun a b e => by dsimp at e injection e with h₁ h₂ simpa using h₂ end
Logic\Small\Group.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Logic.Small.Defs import Mathlib.Logic.Equiv.TransferInstance /-! # Transfer group structures from `α` to `Shrink α`. -/ noncomputable section variable {α : Type*} -- FIXME: here and below, why doesn't `to_additive` work? -- We're waiting on the fix for https://github.com/leanprover/lean4/issues/2077 to arrive. instance [Zero α] [Small α] : Zero (Shrink α) := (equivShrink _).symm.zero @[to_additive existing] instance [One α] [Small α] : One (Shrink α) := (equivShrink _).symm.one @[simp] lemma equivShrink_symm_zero [Zero α] [Small α] : (equivShrink α).symm 0 = 0 := (equivShrink α).symm_apply_apply 0 @[to_additive existing (attr := simp)] lemma equivShrink_symm_one [One α] [Small α] : (equivShrink α).symm 1 = 1 := (equivShrink α).symm_apply_apply 1 instance [Add α] [Small α] : Add (Shrink α) := (equivShrink _).symm.add @[to_additive existing] instance [Mul α] [Small α] : Mul (Shrink α) := (equivShrink _).symm.mul @[simp] lemma equivShrink_symm_add [Add α] [Small α] (x y : Shrink α) : (equivShrink α).symm (x + y) = (equivShrink α).symm x + (equivShrink α).symm y := by rw [Equiv.add_def] simp @[simp] lemma equivShrink_add [Add α] [Small α] (x y : α) : equivShrink α (x + y) = equivShrink α x + equivShrink α y := by rw [Equiv.add_def] simp @[to_additive existing (attr := simp)] lemma equivShrink_symm_mul [Mul α] [Small α] (x y : Shrink α) : (equivShrink α).symm (x * y) = (equivShrink α).symm x * (equivShrink α).symm y := by rw [Equiv.mul_def] simp @[to_additive existing (attr := simp)] lemma equivShrink_mul [Mul α] [Small α] (x y : α) : equivShrink α (x * y) = equivShrink α x * equivShrink α y := by rw [Equiv.mul_def] simp instance [Sub α] [Small α] : Sub (Shrink α) := (equivShrink _).symm.sub @[to_additive existing] instance [Div α] [Small α] : Div (Shrink α) := (equivShrink _).symm.div @[simp] lemma equivShrink_symm_sub [Sub α] [Small α] (x y : Shrink α) : (equivShrink α).symm (x - y) = (equivShrink α).symm x - (equivShrink α).symm y := by rw [Equiv.sub_def] simp @[simp] lemma equivShrink_sub [Sub α] [Small α] (x y : α) : equivShrink α (x - y) = equivShrink α x - equivShrink α y := by rw [Equiv.sub_def] simp @[to_additive existing (attr := simp)] lemma equivShrink_symm_div [Div α] [Small α] (x y : Shrink α) : (equivShrink α).symm (x / y) = (equivShrink α).symm x / (equivShrink α).symm y := by rw [Equiv.div_def] simp @[to_additive existing (attr := simp)] lemma equivShrink_div [Div α] [Small α] (x y : α) : equivShrink α (x / y) = equivShrink α x / equivShrink α y := by rw [Equiv.div_def] simp instance [Neg α] [Small α] : Neg (Shrink α) := (equivShrink _).symm.Neg @[to_additive existing] instance [Inv α] [Small α] : Inv (Shrink α) := (equivShrink _).symm.Inv @[simp] lemma equivShrink_symm_neg [Neg α] [Small α] (x : Shrink α) : (equivShrink α).symm (-x) = -(equivShrink α).symm x := by rw [Equiv.neg_def] simp @[simp] lemma equivShrink_neg [Neg α] [Small α] (x : α) : equivShrink α (-x) = -equivShrink α x := by rw [Equiv.neg_def] simp @[to_additive existing (attr := simp)] lemma equivShrink_symm_inv [Inv α] [Small α] (x : Shrink α) : (equivShrink α).symm x⁻¹ = ((equivShrink α).symm x)⁻¹ := by rw [Equiv.inv_def] simp @[to_additive existing (attr := simp)] lemma equivShrink_inv [Inv α] [Small α] (x : α) : equivShrink α x⁻¹ = (equivShrink α x)⁻¹ := by rw [Equiv.inv_def] simp instance [AddSemigroup α] [Small α] : AddSemigroup (Shrink α) := (equivShrink _).symm.addSemigroup @[to_additive existing] instance [Semigroup α] [Small α] : Semigroup (Shrink α) := (equivShrink _).symm.semigroup instance [SemigroupWithZero α] [Small α] : SemigroupWithZero (Shrink α) := (equivShrink _).symm.semigroupWithZero instance [AddCommSemigroup α] [Small α] : AddCommSemigroup (Shrink α) := (equivShrink _).symm.addCommSemigroup @[to_additive existing] instance [CommSemigroup α] [Small α] : CommSemigroup (Shrink α) := (equivShrink _).symm.commSemigroup instance [MulZeroClass α] [Small α] : MulZeroClass (Shrink α) := (equivShrink _).symm.mulZeroClass instance [AddZeroClass α] [Small α] : AddZeroClass (Shrink α) := (equivShrink _).symm.addZeroClass @[to_additive existing] instance [MulOneClass α] [Small α] : MulOneClass (Shrink α) := (equivShrink _).symm.mulOneClass instance [MulZeroOneClass α] [Small α] : MulZeroOneClass (Shrink α) := (equivShrink _).symm.mulZeroOneClass instance [AddMonoid α] [Small α] : AddMonoid (Shrink α) := (equivShrink _).symm.addMonoid @[to_additive existing] instance [Monoid α] [Small α] : Monoid (Shrink α) := (equivShrink _).symm.monoid instance [AddCommMonoid α] [Small α] : AddCommMonoid (Shrink α) := (equivShrink _).symm.addCommMonoid @[to_additive existing] instance [CommMonoid α] [Small α] : CommMonoid (Shrink α) := (equivShrink _).symm.commMonoid instance [AddGroup α] [Small α] : AddGroup (Shrink α) := (equivShrink _).symm.addGroup @[to_additive existing] instance [Group α] [Small α] : Group (Shrink α) := (equivShrink _).symm.group instance [AddCommGroup α] [Small α] : AddCommGroup (Shrink α) := (equivShrink _).symm.addCommGroup @[to_additive existing] instance [CommGroup α] [Small α] : CommGroup (Shrink α) := (equivShrink _).symm.commGroup
Logic\Small\List.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Logic.Small.Basic import Mathlib.Data.Vector.Basic /-! # Instances for `Small (List α)` and `Small (Vector α)`. These must not be in `Logic.Small.Basic` as this is very low in the import hierarchy, and is used by category theory files which do not need everything imported by `Data.Vector.Basic`. -/ universe u v open Mathlib instance smallVector {α : Type v} {n : ℕ} [Small.{u} α] : Small.{u} (Vector α n) := small_of_injective (Equiv.vectorEquivFin α n).injective instance smallList {α : Type v} [Small.{u} α] : Small.{u} (List α) := by let e : (Σn, Vector α n) ≃ List α := Equiv.sigmaFiberEquiv List.length exact small_of_surjective e.surjective
Logic\Small\Module.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Logic.Small.Group import Mathlib.Logic.Small.Ring /-! # Transfer module and algebra structures from `α` to `Shrink α`. -/ noncomputable section variable {α β : Type*} instance [Semiring α] [AddCommMonoid β] [Module α β] [Small β] : Module α (Shrink β) := (equivShrink _).symm.module α /-- A small module is linearly equivalent to its small model. -/ def linearEquivShrink (α β) [Semiring α] [AddCommMonoid β] [Module α β] [Small β] : β ≃ₗ[α] Shrink β := ((equivShrink β).symm.linearEquiv α).symm instance [CommSemiring α] [Semiring β] [Algebra α β] [Small β] : Algebra α (Shrink β) := (equivShrink _).symm.algebra α /-- A small algebra is algebra equivalent to its small model. -/ def algEquivShrink (α β) [CommSemiring α] [Semiring β] [Algebra α β] [Small β] : β ≃ₐ[α] Shrink β := ((equivShrink β).symm.algEquiv α).symm
Logic\Small\Ring.lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.Logic.Small.Defs import Mathlib.Logic.Equiv.TransferInstance /-! # Transfer ring structures from `α` to `Shrink α`. -/ noncomputable section variable {α : Type*} instance [NonUnitalNonAssocSemiring α] [Small α] : NonUnitalNonAssocSemiring (Shrink α) := (equivShrink _).symm.nonUnitalNonAssocSemiring instance [NonUnitalSemiring α] [Small α] : NonUnitalSemiring (Shrink α) := (equivShrink _).symm.nonUnitalSemiring instance [AddMonoidWithOne α] [Small α] : AddMonoidWithOne (Shrink α) := (equivShrink _).symm.addMonoidWithOne instance [AddGroupWithOne α] [Small α] : AddGroupWithOne (Shrink α) := (equivShrink _).symm.addGroupWithOne instance [NonAssocSemiring α] [Small α] : NonAssocSemiring (Shrink α) := (equivShrink _).symm.nonAssocSemiring instance [Semiring α] [Small α] : Semiring (Shrink α) := (equivShrink _).symm.semiring instance [NonUnitalCommSemiring α] [Small α] : NonUnitalCommSemiring (Shrink α) := (equivShrink _).symm.nonUnitalCommSemiring instance [CommSemiring α] [Small α] : CommSemiring (Shrink α) := (equivShrink _).symm.commSemiring instance [NonUnitalNonAssocRing α] [Small α] : NonUnitalNonAssocRing (Shrink α) := (equivShrink _).symm.nonUnitalNonAssocRing instance [NonUnitalRing α] [Small α] : NonUnitalRing (Shrink α) := (equivShrink _).symm.nonUnitalRing instance [Ring α] [Small α] : Ring (Shrink α) := (equivShrink _).symm.ring instance [NonUnitalCommRing α] [Small α] : NonUnitalCommRing (Shrink α) := (equivShrink _).symm.nonUnitalCommRing instance [CommRing α] [Small α] : CommRing (Shrink α) := (equivShrink _).symm.commRing instance [Nontrivial α] [Small α] : Nontrivial (Shrink α) := (equivShrink _).symm.nontrivial instance [DivisionRing α] [Small α] : DivisionRing (Shrink α) := (equivShrink _).symm.divisionRing instance [Field α] [Small α] : Field (Shrink α) := (equivShrink _).symm.field
Logic\Small\Set.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.Data.Set.Lattice import Mathlib.Logic.Small.Basic /-! # Results about `Small` on coerced sets -/ universe u v w theorem small_subset {α : Type v} {s t : Set α} (hts : t ⊆ s) [Small.{u} s] : Small.{u} t := let f : t → s := fun x => ⟨x, hts x.prop⟩ @small_of_injective _ _ _ f fun _ _ hxy => Subtype.ext (Subtype.mk.inj hxy) instance small_range {α : Type v} {β : Type w} (f : α → β) [Small.{u} α] : Small.{u} (Set.range f) := small_of_surjective Set.surjective_onto_range instance small_image {α : Type v} {β : Type w} (f : α → β) (S : Set α) [Small.{u} S] : Small.{u} (f '' S) := small_of_surjective Set.surjective_onto_image instance small_union {α : Type v} (s t : Set α) [Small.{u} s] [Small.{u} t] : Small.{u} (s ∪ t : Set α) := by rw [← Subtype.range_val (s := s), ← Subtype.range_val (s := t), ← Set.Sum.elim_range] infer_instance instance small_iUnion {α : Type v} {ι : Type w} [Small.{u} ι] (s : ι → Set α) [∀ i, Small.{u} (s i)] : Small.{u} (⋃ i, s i) := small_of_surjective <| Set.sigmaToiUnion_surjective _ instance small_sUnion {α : Type v} (s : Set (Set α)) [Small.{u} s] [∀ t : s, Small.{u} t] : Small.{u} (⋃₀ s) := Set.sUnion_eq_iUnion ▸ small_iUnion _
Mathport\Notation.lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kyle Miller -/ import Mathlib.Lean.Elab.Term import Mathlib.Lean.PrettyPrinter.Delaborator import Mathlib.Tactic.ScopedNS import Batteries.Linter.UnreachableTactic import Batteries.Util.ExtendedBinder import Batteries.Lean.Syntax /-! # The notation3 macro, simulating Lean 3's notation. -/ -- To fix upstream: -- * bracketedExplicitBinders doesn't support optional types namespace Mathlib.Notation3 open Lean Parser Meta Elab Command PrettyPrinter.Delaborator SubExpr open Batteries.ExtendedBinder initialize registerTraceClass `notation3 /-! ### Syntaxes supporting `notation3` -/ /-- Expands binders into nested combinators. For example, the familiar exists is given by: `expand_binders% (p => Exists p) x y : Nat, x < y` which expands to the same expression as `∃ x y : Nat, x < y` -/ syntax "expand_binders% " "(" ident " => " term ")" extBinders ", " term : term macro_rules | `(expand_binders% ($x => $term) $y:extBinder, $res) => `(expand_binders% ($x => $term) ($y:extBinder), $res) | `(expand_binders% ($_ => $_), $res) => pure res macro_rules | `(expand_binders% ($x => $term) ($y:ident $[: $ty]?) $binders*, $res) => do let ty := ty.getD (← `(_)) term.replaceM fun x' ↦ do unless x == x' do return none `(fun $y:ident : $ty ↦ expand_binders% ($x => $term) $[$binders]*, $res) | `(expand_binders% ($x => $term) (_%$ph $[: $ty]?) $binders*, $res) => do let ty := ty.getD (← `(_)) term.replaceM fun x' ↦ do unless x == x' do return none `(fun _%$ph : $ty ↦ expand_binders% ($x => $term) $[$binders]*, $res) | `(expand_binders% ($x => $term) ($y:ident $pred:binderPred) $binders*, $res) => term.replaceM fun x' ↦ do unless x == x' do return none `(fun $y:ident ↦ expand_binders% ($x => $term) (h : satisfies_binder_pred% $y $pred) $[$binders]*, $res) macro (name := expandFoldl) "expand_foldl% " "(" x:ident ppSpace y:ident " => " term:term ") " init:term:max " [" args:term,* "]" : term => args.getElems.foldlM (init := init) fun res arg ↦ do term.replaceM fun e ↦ return if e == x then some res else if e == y then some arg else none macro (name := expandFoldr) "expand_foldr% " "(" x:ident ppSpace y:ident " => " term:term ") " init:term:max " [" args:term,* "]" : term => args.getElems.foldrM (init := init) fun arg res ↦ do term.replaceM fun e ↦ return if e == x then some arg else if e == y then some res else none /-- Keywording indicating whether to use a left- or right-fold. -/ syntax foldKind := &"foldl" <|> &"foldr" /-- `notation3` argument matching `extBinders`. -/ syntax bindersItem := atomic("(" "..." ")") /-- `notation3` argument simulating a Lean 3 fold notation. -/ syntax foldAction := "(" ident ppSpace strLit "*" (precedence)? " => " foldKind " (" ident ppSpace ident " => " term ") " term ")" /-- `notation3` argument binding a name. -/ syntax identOptScoped := ident (notFollowedBy(":" "(" "scoped") precedence)? (":" "(" "scoped " ident " => " term ")")? /-- `notation3` argument. -/ -- Note: there is deliberately no ppSpace between items -- so that the space in the literals themselves stands out syntax notation3Item := strLit <|> bindersItem <|> identOptScoped <|> foldAction /-! ### Expression matching A more complicated part of `notation3` is the delaborator generator. While `notation` relies on generating app unexpanders, we instead generate a delaborator directly so that we can control how binders are formatted (we want to be able to know the types of binders, whether a lambda is a constant function, and whether it is `Prop`-valued, which are not things we can answer once we pass to app unexpanders). -/ /-- The dynamic state of a `Matcher`. -/ structure MatchState where /-- This stores the assignments of variables to subexpressions (and their contexts) that have been found so far during the course of the matching algorithm. We store the contexts since we need to delaborate expressions after we leave scoping constructs. -/ vars : HashMap Name (SubExpr × LocalContext × LocalInstances) /-- The binders accumulated while matching a `scoped` expression. -/ scopeState : Option (Array (TSyntax ``extBinderParenthesized)) /-- The arrays of delaborated `Term`s accumulated while matching `foldl` and `foldr` expressions. For `foldl`, the arrays are stored in reverse order. -/ foldState : HashMap Name (Array Term) /-- A matcher is a delaboration function that transforms `MatchState`s. -/ def Matcher := MatchState → DelabM MatchState deriving Inhabited /-- The initial state. -/ def MatchState.empty : MatchState where vars := {} scopeState := none foldState := {} /-- Evaluate `f` with the given variable's value as the `SubExpr` and within that subexpression's saved context. Fails if the variable has no value. -/ def MatchState.withVar {α : Type} (s : MatchState) (name : Name) (m : DelabM α) : DelabM α := do let some (se, lctx, linsts) := s.vars.find? name | failure withLCtx lctx linsts <| withTheReader SubExpr (fun _ => se) <| m /-- Delaborate the given variable's value. Fails if the variable has no value. If `checkNot` is provided, then checks that the expression being delaborated is not the given one (this is used to prevent infinite loops). -/ def MatchState.delabVar (s : MatchState) (name : Name) (checkNot? : Option Expr := none) : DelabM Term := s.withVar name do if let some checkNot := checkNot? then guard <| checkNot != (← getExpr) delab /-- Assign a variable to the current `SubExpr`, capturing the local context. -/ def MatchState.captureSubexpr (s : MatchState) (name : Name) : DelabM MatchState := do return {s with vars := s.vars.insert name (← readThe SubExpr, ← getLCtx, ← getLocalInstances)} /-- Get the accumulated array of delaborated terms for a given foldr/foldl. Returns `#[]` if nothing has been pushed yet. -/ def MatchState.getFoldArray (s : MatchState) (name : Name) : Array Term := (s.foldState.find? name).getD #[] /-- Get the accumulated array of delaborated terms for a given foldr/foldl. Returns `#[]` if nothing has been pushed yet. -/ def MatchState.getBinders (s : MatchState) : Array (TSyntax ``extBinderParenthesized) := s.scopeState.getD #[] /-- Push a delaborated term onto a foldr/foldl array. -/ def MatchState.pushFold (s : MatchState) (name : Name) (t : Term) : MatchState := let ts := (s.getFoldArray name).push t {s with foldState := s.foldState.insert name ts} /-- Matcher that assigns the current `SubExpr` into the match state; if a value already exists, then it checks for equality. -/ def matchVar (c : Name) : Matcher := fun s => do if let some (se, _, _) := s.vars.find? c then guard <| se.expr == (← getExpr) return s else s.captureSubexpr c /-- Matcher for an expression satisfying a given predicate. -/ def matchExpr (p : Expr → Bool) : Matcher := fun s => do guard <| p (← getExpr) return s /-- Matcher for `Expr.fvar`. It checks that the user name agrees and that the type of the expression is matched by `matchTy`. -/ def matchFVar (userName : Name) (matchTy : Matcher) : Matcher := fun s => do let .fvar fvarId ← getExpr | failure guard <| userName == (← fvarId.getUserName) withType (matchTy s) /-- Matcher that checks that the type of the expression is matched by `matchTy`. -/ def matchTypeOf (matchTy : Matcher) : Matcher := fun s => do withType (matchTy s) /-- Matches raw nat lits. -/ def natLitMatcher (n : Nat) : Matcher := fun s => do guard <| (← getExpr).rawNatLit? == n return s /-- Matches applications. -/ def matchApp (matchFun matchArg : Matcher) : Matcher := fun s => do guard <| (← getExpr).isApp let s ← withAppFn <| matchFun s let s ← withAppArg <| matchArg s return s /-- Matches pi types. The name `n` should be unique, and `matchBody` should use `n` as the `userName` of its fvar. -/ def matchForall (matchDom : Matcher) (matchBody : Expr → Matcher) : Matcher := fun s => do guard <| (← getExpr).isForall let s ← withBindingDomain <| matchDom s let s ← withBindingBodyUnusedName' fun _ arg => matchBody arg s return s /-- Matches lambdas. The `matchBody` takes the fvar introduced when visiting the body. -/ def matchLambda (matchDom : Matcher) (matchBody : Expr → Matcher) : Matcher := fun s => do guard <| (← getExpr).isLambda let s ← withBindingDomain <| matchDom s let s ← withBindingBodyUnusedName' fun _ arg => matchBody arg s return s /-- Adds all the names in `boundNames` to the local context with types that are fresh metavariables. This is used for example when initializing `p` in `(scoped p => ...)` when elaborating `...`. -/ def setupLCtx (lctx : LocalContext) (boundNames : Array Name) : MetaM (LocalContext × HashMap FVarId Name) := do let mut lctx := lctx let mut boundFVars := {} for name in boundNames do let fvarId ← mkFreshFVarId lctx := lctx.mkLocalDecl fvarId name (← withLCtx lctx (← getLocalInstances) mkFreshTypeMVar) boundFVars := boundFVars.insert fvarId name return (lctx, boundFVars) /-- Given an expression, generate a matcher for it. The `boundFVars` hash map records which state variables certain fvars correspond to. The `localFVars` hash map records which local variable the matcher should use for an exact expression match. If it succeeds generating a matcher, returns 1. a list of keys that should be used for the `delab` attribute when defining the elaborator 2. a `Term` that represents a `Matcher` for the given expression `e`. -/ partial def exprToMatcher (boundFVars : HashMap FVarId Name) (localFVars : HashMap FVarId Term) (e : Expr) : OptionT TermElabM (List Name × Term) := do match e with | .mvar .. => return ([], ← `(pure)) | .const n _ => return ([`app ++ n], ← ``(matchExpr (Expr.isConstOf · $(quote n)))) | .sort .. => return ([`sort], ← ``(matchExpr Expr.isSort)) | .fvar fvarId => if let some n := boundFVars.find? fvarId then -- This fvar is a pattern variable. return ([], ← ``(matchVar $(quote n))) else if let some s := localFVars.find? fvarId then -- This fvar is bound by a lambda or forall expression in the pattern itself return ([], ← ``(matchExpr (· == $s))) else let n ← fvarId.getUserName if n.hasMacroScopes then -- Match by just the type; this is likely an unnamed instance for example let (_, m) ← exprToMatcher boundFVars localFVars (← instantiateMVars (← inferType e)) return ([`fvar], ← ``(matchTypeOf $m)) else -- This is an fvar from a `variable`. Match by name and type. let (_, m) ← exprToMatcher boundFVars localFVars (← instantiateMVars (← inferType e)) return ([`fvar], ← ``(matchFVar $(quote n) $m)) | .app .. => e.withApp fun f args => do let (keys, matchF) ← exprToMatcher boundFVars localFVars f let mut fty ← inferType f let mut matcher := matchF for arg in args do fty ← whnf fty guard fty.isForall let bi := fty.bindingInfo! fty := fty.bindingBody!.instantiate1 arg if bi.isInstImplicit then -- Assumption: elaborated instances are canonical, so no need to match. -- The type of the instance is already accounted for by the previous arguments -- and the type of `f`. matcher ← ``(matchApp $matcher pure) else let (_, matchArg) ← exprToMatcher boundFVars localFVars arg matcher ← ``(matchApp $matcher $matchArg) return (if keys.isEmpty then [`app] else keys, matcher) | .lit (.natVal n) => return ([`lit], ← ``(natLitMatcher $(quote n))) | .forallE n t b bi => let (_, matchDom) ← exprToMatcher boundFVars localFVars t withLocalDecl n bi t fun arg => withFreshMacroScope do let n' ← `(n) let body := b.instantiate1 arg let localFVars' := localFVars.insert arg.fvarId! n' let (_, matchBody) ← exprToMatcher boundFVars localFVars' body return ([`forallE], ← ``(matchForall $matchDom (fun $n' => $matchBody))) | .lam n t b bi => let (_, matchDom) ← exprToMatcher boundFVars localFVars t withLocalDecl n bi t fun arg => withFreshMacroScope do let n' ← `(n) let body := b.instantiate1 arg let localFVars' := localFVars.insert arg.fvarId! n' let (_, matchBody) ← exprToMatcher boundFVars localFVars' body return ([`lam], ← ``(matchLambda $matchDom (fun $n' => $matchBody))) | _ => trace[notation3] "can't generate matcher for {e}" failure /-- Returns a `Term` that represents a `Matcher` for the given pattern `stx`. The `boundNames` set determines which identifiers are variables in the pattern. Fails in the `OptionT` sense if it comes across something it's unable to handle. Also returns constant names that could serve as a key for a delaborator. For example, if it's for a function `f`, then `app.f`. -/ partial def mkExprMatcher (stx : Term) (boundNames : Array Name) : OptionT TermElabM (List Name × Term) := do let (lctx, boundFVars) ← setupLCtx (← getLCtx) boundNames withLCtx lctx (← getLocalInstances) do let patt ← try Term.elabPattern stx none catch e => logException e trace[notation3] "Could not elaborate pattern{indentD stx}\nError: {e.toMessageData}" -- Convert the exception into an `OptionT` failure so that the `(prettyPrint := false)` -- suggestion appears. failure trace[notation3] "Generating matcher for pattern {patt}" exprToMatcher boundFVars {} patt /-- Matcher for processing `scoped` syntax. Assumes the expression to be matched against is in the `lit` variable. Runs `smatcher`, extracts the resulting `scopeId` variable, processes this value (which must be a lambda) to produce a binder, and loops. -/ partial def matchScoped (lit scopeId : Name) (smatcher : Matcher) : Matcher := go #[] where /-- Variant of `matchScoped` after some number of `binders` have already been captured. -/ go (binders : Array (TSyntax ``extBinderParenthesized)) : Matcher := fun s => do -- `lit` is bound to the SubExpr that the `scoped` syntax produced s.withVar lit do try -- Run `smatcher` at `lit`, clearing the `scopeId` variable so that it can get a fresh value let s ← smatcher {s with vars := s.vars.erase scopeId} s.withVar scopeId do guard (← getExpr).isLambda let prop ← try Meta.isProp (← getExpr).bindingDomain! catch _ => pure false let isDep := (← getExpr).bindingBody!.hasLooseBVar 0 let ppTypes ← getPPOption getPPPiBinderTypes -- the same option controlling ∀ let dom ← withBindingDomain delab withBindingBodyUnusedName fun x => do let x : Ident := ⟨x⟩ let binder ← if prop && !isDep then -- this underscore is used to support binder predicates, since it indicates -- the variable is unused and this binder is safe to merge into another `(extBinderParenthesized|(_ : $dom)) else if prop || ppTypes then `(extBinderParenthesized|($x:ident : $dom)) else `(extBinderParenthesized|($x:ident)) -- Now use the body of the lambda for `lit` for the next iteration let s ← s.captureSubexpr lit -- TODO merge binders as an inverse to `satisfies_binder_pred%` let binders := binders.push binder go binders s catch _ => guard <| !binders.isEmpty if let some binders₂ := s.scopeState then guard <| binders == binders₂ -- TODO: this might be a bit too strict, but it seems to work return s else return {s with scopeState := binders} /-- Create a `Term` that represents a matcher for `scoped` notation. Fails in the `OptionT` sense if a matcher couldn't be constructed. Also returns a delaborator key like in `mkExprMatcher`. Reminder: `$lit:ident : (scoped $scopedId:ident => $scopedTerm:Term)` -/ partial def mkScopedMatcher (lit scopeId : Name) (scopedTerm : Term) (boundNames : Array Name) : OptionT TermElabM (List Name × Term) := do -- Build the matcher for `scopedTerm` with `scopeId` as an additional variable let (keys, smatcher) ← mkExprMatcher scopedTerm (boundNames.push scopeId) return (keys, ← ``(matchScoped $(quote lit) $(quote scopeId) $smatcher)) /-- Matcher for expressions produced by `foldl`. -/ partial def matchFoldl (lit x y : Name) (smatcher : Matcher) (sinit : Matcher) : Matcher := fun s => do s.withVar lit do let expr ← getExpr -- Clear x and y state before running smatcher so it can store new values let s := {s with vars := s.vars |>.erase x |>.erase y} let some s ← try some <$> smatcher s catch _ => pure none | -- We put this here rather than using a big try block to prevent backtracking. -- We have `smatcher` match greedily, and then require that `sinit` *must* succeed sinit s -- y gives the next element of the list let s := s.pushFold lit (← s.delabVar y expr) -- x gives the next lit let some newLit := s.vars.find? x | failure -- If progress was not made, fail if newLit.1.expr == expr then failure -- Progress was made, so recurse let s := {s with vars := s.vars.insert lit newLit} matchFoldl lit x y smatcher sinit s /-- Create a `Term` that represents a matcher for `foldl` notation. Reminder: `( lit ","* => foldl (x y => scopedTerm) init)` -/ partial def mkFoldlMatcher (lit x y : Name) (scopedTerm init : Term) (boundNames : Array Name) : OptionT TermElabM (List Name × Term) := do -- Build the `scopedTerm` matcher with `x` and `y` as additional variables let boundNames' := boundNames |>.push x |>.push y let (keys, smatcher) ← mkExprMatcher scopedTerm boundNames' let (keys', sinit) ← mkExprMatcher init boundNames return (keys ++ keys', ← ``(matchFoldl $(quote lit) $(quote x) $(quote y) $smatcher $sinit)) /-- Create a `Term` that represents a matcher for `foldr` notation. Reminder: `( lit ","* => foldr (x y => scopedTerm) init)` -/ partial def mkFoldrMatcher (lit x y : Name) (scopedTerm init : Term) (boundNames : Array Name) : OptionT TermElabM (List Name × Term) := do -- Build the `scopedTerm` matcher with `x` and `y` as additional variables let boundNames' := boundNames |>.push x |>.push y let (keys, smatcher) ← mkExprMatcher scopedTerm boundNames' let (keys', sinit) ← mkExprMatcher init boundNames -- N.B. by swapping `x` and `y` we can just use the foldl matcher return (keys ++ keys', ← ``(matchFoldl $(quote lit) $(quote y) $(quote x) $smatcher $sinit)) /-! ### The `notation3` command -/ /-- Create a name that we can use for the `syntax` definition, using the algorithm from `notation`. -/ def mkNameFromSyntax (name? : Option (TSyntax ``namedName)) (syntaxArgs : Array (TSyntax `stx)) (attrKind : TSyntax ``Term.attrKind) : CommandElabM Name := do if let some name := name? then match name with | `(namedName| (name := $n)) => return n.getId | _ => pure () let name ← liftMacroM <| mkNameFromParserSyntax `term (mkNullNode syntaxArgs) addMacroScopeIfLocal name attrKind /-- Used when processing different kinds of variables when building the final delaborator. -/ inductive BoundValueType /-- A normal variable, delaborate its expression. -/ | normal /-- A fold variable, use the fold state (but reverse the array). -/ | foldl /-- A fold variable, use the fold state (do not reverse the array). -/ | foldr syntax prettyPrintOpt := "(" &"prettyPrint" " := " (&"true" <|> &"false") ")" /-- Interpret a `prettyPrintOpt`. The default value is `true`. -/ def getPrettyPrintOpt (opt? : Option (TSyntax ``prettyPrintOpt)) : Bool := if let some opt := opt? then match opt with | `(prettyPrintOpt| (prettyPrint := false)) => false | _ => true else true /-- `notation3` declares notation using Lean-3-style syntax. Examples: ``` notation3 "∀ᶠ " (...) " in " f ", " r:(scoped p => Filter.eventually p f) => r notation3 "MyList[" (x", "* => foldr (a b => MyList.cons a b) MyList.nil) "]" => x ``` By default notation is unable to mention any variables defined using `variable`, but `local notation3` is able to use such local variables. Use `notation3 (prettyPrint := false)` to keep the command from generating a pretty printer for the notation. This command can be used in mathlib4 but it has an uncertain future and was created primarily for backward compatibility. -/ elab (name := notation3) doc:(docComment)? attrs?:(Parser.Term.attributes)? attrKind:Term.attrKind "notation3" prec?:(precedence)? name?:(namedName)? prio?:(namedPrio)? pp?:(prettyPrintOpt)? ppSpace items:(notation3Item)+ " => " val:term : command => do -- We use raw `Name`s for variables. This maps variable names back to the -- identifiers that appear in `items` let mut boundIdents : HashMap Name Ident := {} -- Replacements to use for the `macro` let mut boundValues : HashMap Name Syntax := {} -- The names of the bound names in order, used when constructing patterns for delaboration. let mut boundNames : Array Name := #[] -- The normal/foldl/foldr type of each variable (for delaborator) let mut boundType : HashMap Name BoundValueType := {} -- Function to update `syntaxArgs` and `pattArgs` using `macroArg` syntax let pushMacro (syntaxArgs : Array (TSyntax `stx)) (pattArgs : Array Syntax) (mac : TSyntax ``macroArg) := do let (syntaxArg, pattArg) ← expandMacroArg mac return (syntaxArgs.push syntaxArg, pattArgs.push pattArg) -- Arguments for the `syntax` command let mut syntaxArgs := #[] -- Arguments for the LHS pattern in the `macro`. Also used to construct the syntax -- when delaborating let mut pattArgs := #[] -- The matchers to assemble into a delaborator let mut matchers := #[] -- Whether we've seen a `(...)` item let mut hasBindersItem := false -- Whether we've seen a `scoped` item let mut hasScoped := false for item in items do match item with | `(notation3Item| $lit:str) => -- Can't use `pushMacro` since it inserts an extra variable into the pattern for `str`, which -- breaks our delaborator syntaxArgs := syntaxArgs.push (← `(stx| $lit:str)) pattArgs := pattArgs.push <| mkAtomFrom lit lit.1.isStrLit?.get! | `(notation3Item| $_:bindersItem) => if hasBindersItem then throwErrorAt item "Cannot have more than one `(...)` item." hasBindersItem := true -- HACK: Lean 3 traditionally puts a space after the main binder atom, resulting in -- notation3 "∑ "(...)", "r:(scoped f => sum f) => r -- but extBinders already has a space before it so we strip the trailing space of "∑ " if let `(stx| $lit:str) := syntaxArgs.back then syntaxArgs := syntaxArgs.pop.push (← `(stx| $(quote lit.getString.trimRight):str)) (syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs (← `(macroArg| binders:extBinders)) | `(notation3Item| ($id:ident $sep:str* $(prec?)? => $kind ($x $y => $scopedTerm) $init)) => (syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <| ← `(macroArg| $id:ident:sepBy(term $(prec?)?, $sep:str)) -- N.B. `Syntax.getId` returns `.anonymous` for non-idents let scopedTerm' ← scopedTerm.replaceM fun s => pure (boundValues.find? s.getId) let init' ← init.replaceM fun s => pure (boundValues.find? s.getId) boundIdents := boundIdents.insert id.getId id match kind with | `(foldKind| foldl) => boundValues := boundValues.insert id.getId <| ← `(expand_foldl% ($x $y => $scopedTerm') $init' [$$(.ofElems $id),*]) boundNames := boundNames.push id.getId boundType := boundType.insert id.getId .foldl matchers := matchers.push <| mkFoldlMatcher id.getId x.getId y.getId scopedTerm init boundNames | `(foldKind| foldr) => boundValues := boundValues.insert id.getId <| ← `(expand_foldr% ($x $y => $scopedTerm') $init' [$$(.ofElems $id),*]) boundNames := boundNames.push id.getId boundType := boundType.insert id.getId .foldr matchers := matchers.push <| mkFoldrMatcher id.getId x.getId y.getId scopedTerm init boundNames | _ => throwUnsupportedSyntax | `(notation3Item| $lit:ident $(prec?)? : (scoped $scopedId:ident => $scopedTerm)) => hasScoped := true (syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <|← `(macroArg| $lit:ident:term $(prec?)?) matchers := matchers.push <| mkScopedMatcher lit.getId scopedId.getId scopedTerm boundNames let scopedTerm' ← scopedTerm.replaceM fun s => pure (boundValues.find? s.getId) boundIdents := boundIdents.insert lit.getId lit boundValues := boundValues.insert lit.getId <| ← `(expand_binders% ($scopedId => $scopedTerm') $$binders:extBinders, $(⟨lit.1.mkAntiquotNode `term⟩):term) boundNames := boundNames.push lit.getId | `(notation3Item| $lit:ident $(prec?)?) => (syntaxArgs, pattArgs) ← pushMacro syntaxArgs pattArgs <|← `(macroArg| $lit:ident:term $(prec?)?) boundIdents := boundIdents.insert lit.getId lit boundValues := boundValues.insert lit.getId <| lit.1.mkAntiquotNode `term boundNames := boundNames.push lit.getId | _stx => throwUnsupportedSyntax if hasScoped && !hasBindersItem then throwError "If there is a `scoped` item then there must be a `(...)` item for binders." -- 1. The `syntax` command let name ← mkNameFromSyntax name? syntaxArgs attrKind elabCommand <| ← `(command| $[$doc]? $(attrs?)? $attrKind syntax $(prec?)? (name := $(Lean.mkIdent name)) $(prio?)? $[$syntaxArgs]* : term) -- 2. The `macro_rules` let currNamespace : Name ← getCurrNamespace -- The `syntax` command puts definitions into the current namespace; we need this -- to make the syntax `pat`. let fullName := currNamespace ++ name trace[notation3] "syntax declaration has name {fullName}" let pat : Term := ⟨mkNode fullName pattArgs⟩ let val' ← val.replaceM fun s => pure (boundValues.find? s.getId) let mut macroDecl ← `(macro_rules | `($pat) => `($val')) if isLocalAttrKind attrKind then -- For local notation, take section variables into account macroDecl ← `(section set_option quotPrecheck.allowSectionVars true $macroDecl end) elabCommand macroDecl -- 3. Create a delaborator if getPrettyPrintOpt pp? then matchers := matchers.push <| Mathlib.Notation3.mkExprMatcher val boundNames -- The matchers need to run in reverse order, so may as well reverse them here. let matchersM? := (matchers.reverse.mapM id).run -- We let local notations have access to `variable` declarations let matchers? ← if isLocalAttrKind attrKind then runTermElabM fun _ => matchersM? else liftTermElabM matchersM? if let some ms := matchers? then trace[notation3] "Matcher creation succeeded; assembling delaborator" let delabName := name ++ `delab let matcher ← ms.foldrM (fun m t => `($(m.2) >=> $t)) (← `(pure)) trace[notation3] "matcher:{indentD matcher}" let mut result ← `(`($pat)) for (name, id) in boundIdents.toArray do match boundType.findD name .normal with | .normal => result ← `(MatchState.delabVar s $(quote name) (some e) >>= fun $id => $result) | .foldl => result ← `(let $id := (MatchState.getFoldArray s $(quote name)).reverse; $result) | .foldr => result ← `(let $id := MatchState.getFoldArray s $(quote name); $result) if hasBindersItem then result ← `(`(extBinders| $$(MatchState.getBinders s)*) >>= fun binders => $result) elabCommand <| ← `(command| /-- Pretty printer defined by `notation3` command. -/ def $(Lean.mkIdent delabName) : Delab := whenPPOption getPPNotation <| getExpr >>= fun e => $matcher MatchState.empty >>= fun s => $result) trace[notation3] "Defined delaborator {currNamespace ++ delabName}" let delabKeys := ms.foldr (·.1 ++ ·) [] trace[notation3] "Adding `delab` attribute for keys {delabKeys}" for key in delabKeys do elabCommand <| ← `(command| attribute [$attrKind delab $(mkIdent key)] $(Lean.mkIdent delabName)) else logWarning s!"\ Was not able to generate a pretty printer for this notation. \ If you do not expect it to be pretty printable, then you can use \ `notation3 (prettyPrint := false)`. \ If the notation expansion refers to section variables, be sure to do `local notation3`. \ Otherwise, you might be able to adjust the notation expansion to make it matchable; \ pretty printing relies on deriving an expression matcher from the expansion. \ (Use `set_option trace.notation3 true` to get some debug information.)" initialize Batteries.Linter.UnreachableTactic.addIgnoreTacticKind ``«notation3» /-! `scoped[ns]` support -/ macro_rules | `($[$doc]? $(attr)? scoped[$ns] notation3 $(prec)? $(n)? $(prio)? $(pp)? $items* => $t) => `(with_weak_namespace $(mkIdentFrom ns <| rootNamespace ++ ns.getId) $[$doc]? $(attr)? scoped notation3 $(prec)? $(n)? $(prio)? $(pp)? $items* => $t)
Mathport\Syntax.lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Lean.Elab.Command import Lean.Elab.Quotation import Batteries.Tactic.Where import Mathlib.Data.Matrix.Notation import Mathlib.Logic.Equiv.PartialEquiv import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic import Mathlib.Order.Filter.Basic import Mathlib.RingTheory.WittVector.Basic import Mathlib.RingTheory.WittVector.IsPoly import Mathlib.SetTheory.Game.PGame import Mathlib.Tactic.Abel import Mathlib.Tactic.ApplyCongr import Mathlib.Tactic.ApplyFun import Mathlib.Tactic.ApplyWith import Mathlib.Tactic.ByContra import Mathlib.Tactic.CC import Mathlib.Tactic.CancelDenoms import Mathlib.Tactic.Cases import Mathlib.Tactic.CasesM import Mathlib.Tactic.CategoryTheory.Coherence import Mathlib.Tactic.CategoryTheory.Elementwise import Mathlib.Tactic.CategoryTheory.Slice import Mathlib.Tactic.Choose import Mathlib.Tactic.Clean import Mathlib.Tactic.Clear_ import Mathlib.Tactic.ClearExclamation import Mathlib.Tactic.ClearExcept import Mathlib.Tactic.Constructor import Mathlib.Tactic.CongrM import Mathlib.Tactic.Continuity import Mathlib.Tactic.Contrapose import Mathlib.Tactic.Conv import Mathlib.Tactic.Convert import Mathlib.Tactic.Core import Mathlib.Tactic.DefEqTransformations import Mathlib.Tactic.ExtractGoal import Mathlib.Tactic.ExistsI import Mathlib.Tactic.FieldSimp import Mathlib.Tactic.FinCases import Mathlib.Tactic.Find import Mathlib.Tactic.GeneralizeProofs import Mathlib.Tactic.Group import Mathlib.Tactic.GuardHypNums import Mathlib.Tactic.Hint import Mathlib.Tactic.ITauto import Mathlib.Tactic.InferParam import Mathlib.Tactic.IntervalCases import Mathlib.Tactic.Inhabit import Mathlib.Tactic.IrreducibleDef import Mathlib.Tactic.Lift import Mathlib.Tactic.Linarith import Mathlib.Tactic.LinearCombination import Mathlib.Tactic.Measurability import Mathlib.Tactic.MkIffOfInductiveProp import Mathlib.Tactic.ModCases import Mathlib.Tactic.Monotonicity import Mathlib.Tactic.NoncommRing import Mathlib.Tactic.Nontriviality import Mathlib.Tactic.NormNum import Mathlib.Tactic.NthRewrite import Mathlib.Tactic.Polyrith import Mathlib.Tactic.Positivity import Mathlib.Tactic.PushNeg import Mathlib.Tactic.Qify import Mathlib.Tactic.Recover import Mathlib.Tactic.Relation.Trans import Mathlib.Tactic.Rename import Mathlib.Tactic.RenameBVar import Mathlib.Tactic.Replace import Mathlib.Tactic.Ring import Mathlib.Tactic.RSuffices import Mathlib.Tactic.ScopedNS import Mathlib.Tactic.Set import Mathlib.Tactic.SimpIntro import Mathlib.Tactic.SimpRw import Mathlib.Tactic.Simps.Basic import Mathlib.Tactic.SplitIfs import Mathlib.Tactic.Substs import Mathlib.Tactic.SwapVar import Mathlib.Tactic.Tauto import Mathlib.Tactic.TFAE import Mathlib.Tactic.Trace import Mathlib.Tactic.TypeCheck import Mathlib.Tactic.Use import Mathlib.Tactic.WLOG import Mathlib.Tactic.Zify import Mathlib.Util.WithWeakNamespace import Mathlib.Mathport.Notation -- To fix upstream: -- * bracketedExplicitBinders doesn't support optional types /-! This file defines all the tactics that are required by mathport. Most of the `syntax` declarations in this file (as opposed to the imported files) are not defined anywhere and effectively form the TODO list before we can port mathlib to lean 4 for real. For tactic writers: I (Mario) have put a comment before each syntax declaration to represent the estimated difficulty of writing the tactic. The key is as follows: * `E`: Easy. It's a simple macro in terms of existing things, or an elab tactic for which we have many similar examples. Example: `left` * `M`: Medium. An elab tactic, not too hard, perhaps a 100-200 lines file. Example: `have` * `N`: Possibly requires new mechanisms in lean 4, some investigation required * `B`: Hard, because it is a big and complicated tactic * `S`: Possibly easy, because we can just stub it out or replace with something else * `?`: uncategorized -/ namespace Mathlib.Tactic open Lean Parser.Tactic /- N -/ elab (name := omit) "omit" (ppSpace ident)+ : command => pure () /- N -/ syntax (name := parameter) "parameter" (ppSpace bracketedBinder)+ : command /- S -/ syntax (name := propagateTags) "propagate_tags " tacticSeq : tactic /- S -/ syntax (name := mapply) "mapply " term : tactic /- S -/ syntax "destruct " term : tactic /- N -/ syntax (name := abstract) "abstract" (ppSpace ident)? ppSpace tacticSeq : tactic /- S -/ syntax (name := rsimp) "rsimp" : tactic /- S -/ syntax (name := compVal) "comp_val" : tactic /- S -/ syntax (name := async) "async " tacticSeq : tactic /- M -/ syntax (name := injectionsAndClear) "injections_and_clear" : tactic /- E -/ syntax (name := tryFor) "try_for " term:max tacticSeq : tactic /- E -/ syntax (name := unfoldCoes) "unfold_coes" (location)? : tactic /- E -/ syntax (name := unfoldWf) "unfold_wf" : tactic /- M -/ syntax (name := unfoldAux) "unfold_aux" : tactic /- S -/ syntax (name := «continue») "continue " tacticSeq : tactic /- B -/ syntax (name := refineStruct) "refine_struct " term : tactic /- M -/ syntax (name := matchHyp) "match_hyp " ("(" &"m" " := " term ") ")? ident " : " term : tactic /- S -/ syntax (name := guardTags) "guard_tags" (ppSpace ident)* : tactic /- S -/ syntax (name := guardProofTerm) "guard_proof_term " tactic:51 " => " term : tactic /- S -/ syntax (name := failIfSuccess?) "fail_if_success? " str ppSpace tacticSeq : tactic /- N -/ syntax (name := field) "field " ident " => " tacticSeq : tactic /- S -/ syntax (name := haveField) "have_field" : tactic /- S -/ syntax (name := applyField) "apply_field" : tactic /- S -/ syntax (name := hGeneralize) "h_generalize " atomic(binderIdent " : ")? term:51 " = " ident (" with " binderIdent)? : tactic /- S -/ syntax (name := hGeneralize!) "h_generalize! " atomic(binderIdent " : ")? term:51 " = " ident (" with " binderIdent)? : tactic /- S -/ syntax (name := extractGoal!) "extract_goal!" (ppSpace ident)? (" with" (ppSpace colGt ident)*)? : tactic /- S -/ syntax (name := revertDeps) "revert_deps" (ppSpace colGt ident)* : tactic /- S -/ syntax (name := revertAfter) "revert_after " ident : tactic /- S -/ syntax (name := revertTargetDeps) "revert_target_deps" : tactic /- S -/ syntax (name := rcases?) "rcases?" casesTarget,* (" : " num)? : tactic /- S -/ syntax (name := rintro?) "rintro?" (" : " num)? : tactic /- M -/ syntax (name := decide!) "decide!" : tactic /- M -/ syntax (name := deltaInstance) "delta_instance" (ppSpace ident)* : tactic /- S -/ syntax (name := elide) "elide " num (location)? : tactic /- S -/ syntax (name := unelide) "unelide" (location)? : tactic /-- `ext1? pat*` is like `ext1 pat*` but gives a suggestion on what pattern to use -/ /- M -/ syntax (name := ext1?) "ext1?" (colGt ppSpace rintroPat)* : tactic /-- `ext? pat*` is like `ext pat*` but gives a suggestion on what pattern to use -/ /- M -/ syntax (name := ext?) "ext?" (colGt ppSpace rintroPat)* (" : " num)? : tactic /- S -/ syntax (name := clarify) "clarify" (config)? (Parser.Tactic.simpArgs)? (" using " term,+)? : tactic /- S -/ syntax (name := safe) "safe" (config)? (Parser.Tactic.simpArgs)? (" using " term,+)? : tactic /- S -/ syntax (name := finish) "finish" (config)? (Parser.Tactic.simpArgs)? (" using " term,+)? : tactic syntax generalizesArg := (ident " : ")? term:51 " = " ident /- M -/ syntax (name := generalizes) "generalizes " "[" generalizesArg,* "]" : tactic syntax withPattern := "-" <|> "_" <|> ident /- S -/ syntax (name := cases'') "cases''" casesTarget (" with" (ppSpace colGt withPattern)+)? : tactic syntax fixingClause := " fixing" (" *" <|> (ppSpace ident)+) syntax generalizingClause := " generalizing" (ppSpace ident)+ /- S -/ syntax (name := induction'') "induction''" casesTarget (fixingClause <|> generalizingClause)? (" with" (ppSpace colGt withPattern)+)? : tactic /- B -/ syntax (name := obviously) "obviously" : tactic /- S -/ syntax (name := prettyCases) "pretty_cases" : tactic /- M -/ syntax (name := assocRw) "assoc_rw " rwRuleSeq (location)? : tactic /- N -/ syntax (name := dsimpResult) "dsimp_result" (&" only")? (dsimpArgs)? " => " tacticSeq : tactic /- N -/ syntax (name := simpResult) "simp_result" (&" only")? (simpArgs)? " => " tacticSeq : tactic /- S -/ syntax (name := suggest) "suggest" (config)? (ppSpace num)? (simpArgs)? (" using" (ppSpace colGt binderIdent)+)? : tactic /- M -/ syntax (name := truncCases) "trunc_cases " term (" with" (ppSpace colGt binderIdent)+)? : tactic /- E -/ syntax (name := applyNormed) "apply_normed " term : tactic /- B -/ syntax (name := acMono) "ac_mono" ("*" <|> ("^" num))? (config)? ((" : " term) <|> (" := " term))? : tactic /- M -/ syntax (name := reassoc) "reassoc" (ppSpace colGt ident)* : tactic /- M -/ syntax (name := reassoc!) "reassoc!" (ppSpace colGt ident)* : tactic /- M -/ syntax (name := deriveReassocProof) "derive_reassoc_proof" : tactic /- S -/ syntax (name := subtypeInstance) "subtype_instance" : tactic /- S -/ syntax (name := transport) "transport" (ppSpace term)? " using " term : tactic /- M -/ syntax (name := unfoldCases) "unfold_cases " tacticSeq : tactic /- B -/ syntax (name := equivRw) "equiv_rw" (config)? ((" [" term,* "]") <|> (ppSpace term)) (location)? : tactic /- B -/ syntax (name := equivRwType) "equiv_rw_type" (config)? ppSpace term : tactic /- E -/ syntax (name := nthRwLHS) "nth_rw_lhs " num rwRuleSeq (location)? : tactic /- E -/ syntax (name := nthRwRHS) "nth_rw_rhs " num rwRuleSeq (location)? : tactic /- M -/ syntax (name := piInstanceDeriveField) "pi_instance_derive_field" : tactic /- M -/ syntax (name := piInstance) "pi_instance" : tactic /- B -/ syntax (name := tidy) "tidy" (config)? : tactic /- B -/ syntax (name := tidy?) "tidy?" (config)? : tactic /- M -/ syntax (name := deriveElementwiseProof) "derive_elementwise_proof" : tactic /- M -/ syntax (name := computeDegreeLE) "compute_degree_le" : tactic /- S -/ syntax (name := mkDecorations) "mk_decorations" : tactic /- E -/ syntax (name := isBounded_default) "isBounded_default" : tactic /- S -/ syntax (name := mvBisim) "mv_bisim" (ppSpace colGt term)? (" with" (ppSpace binderIdent)+)? : tactic /- E -/ syntax (name := unitInterval) "unit_interval" : tactic /- M -/ syntax (name := padicIndexSimp) "padic_index_simp" " [" term,* "]" (location)? : tactic /- E -/ syntax (name := uniqueDiffWithinAt_Ici_Iic_univ) "uniqueDiffWithinAt_Ici_Iic_univ" : tactic /- E -/ syntax (name := wittTruncateFunTac) "witt_truncate_fun_tac" : tactic /- S -/ syntax (name := intro) "intro" : attr /- S -/ syntax (name := intro!) "intro!" : attr /- S -/ syntax (name := interactive) "interactive" : attr /- M -/ syntax (name := expandExists) "expand_exists" (ppSpace ident)+ : attr -- TODO: this should be handled in mathport /- S -/ syntax (name := protectProj) "protect_proj" (&" without" (ppSpace ident)+)? : attr /- M -/ syntax (name := notationClass) "notation_class" "*"? (ppSpace ident)? : attr /- N -/ syntax (name := addTacticDoc) (docComment)? "add_tactic_doc " term : command /- S -/ syntax (name := listUnusedDecls) "#list_unused_decls" : command /- N -/ syntax (name := defReplacer) "def_replacer " ident Parser.Term.optType : command /- M -/ syntax (name := reassocAxiom) "reassoc_axiom " ident : command /- S -/ syntax (name := sample) "#sample " term : command /- S -/ syntax (name := printSorryIn) "#print_sorry_in " ident : command /- E -/ syntax (name := assertInstance) "assert_instance " term : command /- E -/ syntax (name := assertNoInstance) "assert_no_instance " term : command end Tactic end Mathlib
MeasureTheory\PiSystem.lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Martin Zinkevich, Rémy Degenne -/ import Mathlib.Logic.Encodable.Lattice import Mathlib.MeasureTheory.MeasurableSpace.Defs /-! # Induction principles for measurable sets, related to π-systems and λ-systems. ## Main statements * The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. * The proof of this theorem relies on the notion of `IsPiSystem`, i.e., a collection of sets which is closed under binary non-empty intersections. Note that this is a small variation around the usual notion in the literature, which often requires that a π-system is non-empty, and closed also under disjoint intersections. This variation turns out to be convenient for the formalization. * The proof of Dynkin's π-λ theorem also requires the notion of `DynkinSystem`, i.e., a collection of sets which contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. * `generatePiSystem g` gives the minimal π-system containing `g`. This can be considered a Galois insertion into both measurable spaces and sets. * `generateFrom_generatePiSystem_eq` proves that if you start from a collection of sets `g`, take the generated π-system, and then the generated σ-algebra, you get the same result as the σ-algebra generated from `g`. This is useful because there are connections between independent sets that are π-systems and the generated independent spaces. * `mem_generatePiSystem_iUnion_elim` and `mem_generatePiSystem_iUnion_elim'` show that any element of the π-system generated from the union of a set of π-systems can be represented as the intersection of a finite number of elements from these sets. * `piiUnionInter` defines a new π-system from a family of π-systems `π : ι → Set (Set α)` and a set of indices `S : Set ι`. `piiUnionInter π S` is the set of sets that can be written as `⋂ x ∈ t, f x` for some finset `t ∈ S` and sets `f x ∈ π x`. ## Implementation details * `IsPiSystem` is a predicate, not a type. Thus, we don't explicitly define the galois insertion, nor do we define a complete lattice. In theory, we could define a complete lattice and galois insertion on the subtype corresponding to `IsPiSystem`. -/ open MeasurableSpace Set open MeasureTheory /-- A π-system is a collection of subsets of `α` that is closed under binary intersection of non-disjoint sets. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def IsPiSystem {α} (C : Set (Set α)) : Prop := ∀ᵉ (s ∈ C) (t ∈ C), (s ∩ t : Set α).Nonempty → s ∩ t ∈ C namespace MeasurableSpace theorem isPiSystem_measurableSet {α : Type*} [MeasurableSpace α] : IsPiSystem { s : Set α | MeasurableSet s } := fun _ hs _ ht _ => hs.inter ht end MeasurableSpace theorem IsPiSystem.singleton {α} (S : Set α) : IsPiSystem ({S} : Set (Set α)) := by intro s h_s t h_t _ rw [Set.mem_singleton_iff.1 h_s, Set.mem_singleton_iff.1 h_t, Set.inter_self, Set.mem_singleton_iff] theorem IsPiSystem.insert_empty {α} {S : Set (Set α)} (h_pi : IsPiSystem S) : IsPiSystem (insert ∅ S) := by intro s hs t ht hst cases' hs with hs hs · simp [hs] · cases' ht with ht ht · simp [ht] · exact Set.mem_insert_of_mem _ (h_pi s hs t ht hst) theorem IsPiSystem.insert_univ {α} {S : Set (Set α)} (h_pi : IsPiSystem S) : IsPiSystem (insert Set.univ S) := by intro s hs t ht hst cases' hs with hs hs · cases' ht with ht ht <;> simp [hs, ht] · cases' ht with ht ht · simp [hs, ht] · exact Set.mem_insert_of_mem _ (h_pi s hs t ht hst) theorem IsPiSystem.comap {α β} {S : Set (Set β)} (h_pi : IsPiSystem S) (f : α → β) : IsPiSystem { s : Set α | ∃ t ∈ S, f ⁻¹' t = s } := by rintro _ ⟨s, hs_mem, rfl⟩ _ ⟨t, ht_mem, rfl⟩ hst rw [← Set.preimage_inter] at hst ⊢ exact ⟨s ∩ t, h_pi s hs_mem t ht_mem (nonempty_of_nonempty_preimage hst), rfl⟩ theorem isPiSystem_iUnion_of_directed_le {α ι} (p : ι → Set (Set α)) (hp_pi : ∀ n, IsPiSystem (p n)) (hp_directed : Directed (· ≤ ·) p) : IsPiSystem (⋃ n, p n) := by intro t1 ht1 t2 ht2 h rw [Set.mem_iUnion] at ht1 ht2 ⊢ cases' ht1 with n ht1 cases' ht2 with m ht2 obtain ⟨k, hpnk, hpmk⟩ : ∃ k, p n ≤ p k ∧ p m ≤ p k := hp_directed n m exact ⟨k, hp_pi k t1 (hpnk ht1) t2 (hpmk ht2) h⟩ theorem isPiSystem_iUnion_of_monotone {α ι} [SemilatticeSup ι] (p : ι → Set (Set α)) (hp_pi : ∀ n, IsPiSystem (p n)) (hp_mono : Monotone p) : IsPiSystem (⋃ n, p n) := isPiSystem_iUnion_of_directed_le p hp_pi (Monotone.directed_le hp_mono) section Order variable {α : Type*} {ι ι' : Sort*} [LinearOrder α] theorem isPiSystem_image_Iio (s : Set α) : IsPiSystem (Iio '' s) := by rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ - exact ⟨a ⊓ b, inf_ind a b ha hb, Iio_inter_Iio.symm⟩ theorem isPiSystem_Iio : IsPiSystem (range Iio : Set (Set α)) := @image_univ α _ Iio ▸ isPiSystem_image_Iio univ theorem isPiSystem_image_Ioi (s : Set α) : IsPiSystem (Ioi '' s) := @isPiSystem_image_Iio αᵒᵈ _ s theorem isPiSystem_Ioi : IsPiSystem (range Ioi : Set (Set α)) := @image_univ α _ Ioi ▸ isPiSystem_image_Ioi univ theorem isPiSystem_image_Iic (s : Set α) : IsPiSystem (Iic '' s) := by rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ - exact ⟨a ⊓ b, inf_ind a b ha hb, Iic_inter_Iic.symm⟩ theorem isPiSystem_Iic : IsPiSystem (range Iic : Set (Set α)) := @image_univ α _ Iic ▸ isPiSystem_image_Iic univ theorem isPiSystem_image_Ici (s : Set α) : IsPiSystem (Ici '' s) := @isPiSystem_image_Iic αᵒᵈ _ s theorem isPiSystem_Ici : IsPiSystem (range Ici : Set (Set α)) := @image_univ α _ Ici ▸ isPiSystem_image_Ici univ theorem isPiSystem_Ixx_mem {Ixx : α → α → Set α} {p : α → α → Prop} (Hne : ∀ {a b}, (Ixx a b).Nonempty → p a b) (Hi : ∀ {a₁ b₁ a₂ b₂}, Ixx a₁ b₁ ∩ Ixx a₂ b₂ = Ixx (max a₁ a₂) (min b₁ b₂)) (s t : Set α) : IsPiSystem { S | ∃ᵉ (l ∈ s) (u ∈ t), p l u ∧ Ixx l u = S } := by rintro _ ⟨l₁, hls₁, u₁, hut₁, _, rfl⟩ _ ⟨l₂, hls₂, u₂, hut₂, _, rfl⟩ simp only [Hi] exact fun H => ⟨l₁ ⊔ l₂, sup_ind l₁ l₂ hls₁ hls₂, u₁ ⊓ u₂, inf_ind u₁ u₂ hut₁ hut₂, Hne H, rfl⟩ theorem isPiSystem_Ixx {Ixx : α → α → Set α} {p : α → α → Prop} (Hne : ∀ {a b}, (Ixx a b).Nonempty → p a b) (Hi : ∀ {a₁ b₁ a₂ b₂}, Ixx a₁ b₁ ∩ Ixx a₂ b₂ = Ixx (max a₁ a₂) (min b₁ b₂)) (f : ι → α) (g : ι' → α) : @IsPiSystem α { S | ∃ i j, p (f i) (g j) ∧ Ixx (f i) (g j) = S } := by simpa only [exists_range_iff] using isPiSystem_Ixx_mem (@Hne) (@Hi) (range f) (range g) theorem isPiSystem_Ioo_mem (s t : Set α) : IsPiSystem { S | ∃ᵉ (l ∈ s) (u ∈ t), l < u ∧ Ioo l u = S } := isPiSystem_Ixx_mem (Ixx := Ioo) (fun ⟨_, hax, hxb⟩ => hax.trans hxb) Ioo_inter_Ioo s t theorem isPiSystem_Ioo (f : ι → α) (g : ι' → α) : @IsPiSystem α { S | ∃ l u, f l < g u ∧ Ioo (f l) (g u) = S } := isPiSystem_Ixx (Ixx := Ioo) (fun ⟨_, hax, hxb⟩ => hax.trans hxb) Ioo_inter_Ioo f g theorem isPiSystem_Ioc_mem (s t : Set α) : IsPiSystem { S | ∃ᵉ (l ∈ s) (u ∈ t), l < u ∧ Ioc l u = S } := isPiSystem_Ixx_mem (Ixx := Ioc) (fun ⟨_, hax, hxb⟩ => hax.trans_le hxb) Ioc_inter_Ioc s t theorem isPiSystem_Ioc (f : ι → α) (g : ι' → α) : @IsPiSystem α { S | ∃ i j, f i < g j ∧ Ioc (f i) (g j) = S } := isPiSystem_Ixx (Ixx := Ioc) (fun ⟨_, hax, hxb⟩ => hax.trans_le hxb) Ioc_inter_Ioc f g theorem isPiSystem_Ico_mem (s t : Set α) : IsPiSystem { S | ∃ᵉ (l ∈ s) (u ∈ t), l < u ∧ Ico l u = S } := isPiSystem_Ixx_mem (Ixx := Ico) (fun ⟨_, hax, hxb⟩ => hax.trans_lt hxb) Ico_inter_Ico s t theorem isPiSystem_Ico (f : ι → α) (g : ι' → α) : @IsPiSystem α { S | ∃ i j, f i < g j ∧ Ico (f i) (g j) = S } := isPiSystem_Ixx (Ixx := Ico) (fun ⟨_, hax, hxb⟩ => hax.trans_lt hxb) Ico_inter_Ico f g theorem isPiSystem_Icc_mem (s t : Set α) : IsPiSystem { S | ∃ᵉ (l ∈ s) (u ∈ t), l ≤ u ∧ Icc l u = S } := isPiSystem_Ixx_mem (Ixx := Icc) nonempty_Icc.1 (by exact Icc_inter_Icc) s t theorem isPiSystem_Icc (f : ι → α) (g : ι' → α) : @IsPiSystem α { S | ∃ i j, f i ≤ g j ∧ Icc (f i) (g j) = S } := isPiSystem_Ixx (Ixx := Icc) nonempty_Icc.1 (by exact Icc_inter_Icc) f g end Order /-- Given a collection `S` of subsets of `α`, then `generatePiSystem S` is the smallest π-system containing `S`. -/ inductive generatePiSystem {α} (S : Set (Set α)) : Set (Set α) | base {s : Set α} (h_s : s ∈ S) : generatePiSystem S s | inter {s t : Set α} (h_s : generatePiSystem S s) (h_t : generatePiSystem S t) (h_nonempty : (s ∩ t).Nonempty) : generatePiSystem S (s ∩ t) theorem isPiSystem_generatePiSystem {α} (S : Set (Set α)) : IsPiSystem (generatePiSystem S) := fun _ h_s _ h_t h_nonempty => generatePiSystem.inter h_s h_t h_nonempty theorem subset_generatePiSystem_self {α} (S : Set (Set α)) : S ⊆ generatePiSystem S := fun _ => generatePiSystem.base theorem generatePiSystem_subset_self {α} {S : Set (Set α)} (h_S : IsPiSystem S) : generatePiSystem S ⊆ S := fun x h => by induction' h with _ h_s s u _ _ h_nonempty h_s h_u · exact h_s · exact h_S _ h_s _ h_u h_nonempty theorem generatePiSystem_eq {α} {S : Set (Set α)} (h_pi : IsPiSystem S) : generatePiSystem S = S := Set.Subset.antisymm (generatePiSystem_subset_self h_pi) (subset_generatePiSystem_self S) theorem generatePiSystem_mono {α} {S T : Set (Set α)} (hST : S ⊆ T) : generatePiSystem S ⊆ generatePiSystem T := fun t ht => by induction' ht with s h_s s u _ _ h_nonempty h_s h_u · exact generatePiSystem.base (Set.mem_of_subset_of_mem hST h_s) · exact isPiSystem_generatePiSystem T _ h_s _ h_u h_nonempty theorem generatePiSystem_measurableSet {α} [M : MeasurableSpace α] {S : Set (Set α)} (h_meas_S : ∀ s ∈ S, MeasurableSet s) (t : Set α) (h_in_pi : t ∈ generatePiSystem S) : MeasurableSet t := by induction' h_in_pi with s h_s s u _ _ _ h_s h_u · apply h_meas_S _ h_s · apply MeasurableSet.inter h_s h_u theorem generateFrom_measurableSet_of_generatePiSystem {α} {g : Set (Set α)} (t : Set α) (ht : t ∈ generatePiSystem g) : MeasurableSet[generateFrom g] t := @generatePiSystem_measurableSet α (generateFrom g) g (fun _ h_s_in_g => measurableSet_generateFrom h_s_in_g) t ht theorem generateFrom_generatePiSystem_eq {α} {g : Set (Set α)} : generateFrom (generatePiSystem g) = generateFrom g := by apply le_antisymm <;> apply generateFrom_le · exact fun t h_t => generateFrom_measurableSet_of_generatePiSystem t h_t · exact fun t h_t => measurableSet_generateFrom (generatePiSystem.base h_t) /-- Every element of the π-system generated by the union of a family of π-systems is a finite intersection of elements from the π-systems. For an indexed union version, see `mem_generatePiSystem_iUnion_elim'`. -/ theorem mem_generatePiSystem_iUnion_elim {α β} {g : β → Set (Set α)} (h_pi : ∀ b, IsPiSystem (g b)) (t : Set α) (h_t : t ∈ generatePiSystem (⋃ b, g b)) : ∃ (T : Finset β) (f : β → Set α), (t = ⋂ b ∈ T, f b) ∧ ∀ b ∈ T, f b ∈ g b := by classical induction' h_t with s h_s s t' h_gen_s h_gen_t' h_nonempty h_s h_t' · rcases h_s with ⟨t', ⟨⟨b, rfl⟩, h_s_in_t'⟩⟩ refine ⟨{b}, fun _ => s, ?_⟩ simpa using h_s_in_t' · rcases h_t' with ⟨T_t', ⟨f_t', ⟨rfl, h_t'⟩⟩⟩ rcases h_s with ⟨T_s, ⟨f_s, ⟨rfl, h_s⟩⟩⟩ use T_s ∪ T_t', fun b : β => if b ∈ T_s then if b ∈ T_t' then f_s b ∩ f_t' b else f_s b else if b ∈ T_t' then f_t' b else (∅ : Set α) constructor · ext a simp_rw [Set.mem_inter_iff, Set.mem_iInter, Finset.mem_union, or_imp] rw [← forall_and] constructor <;> intro h1 b <;> by_cases hbs : b ∈ T_s <;> by_cases hbt : b ∈ T_t' <;> specialize h1 b <;> simp only [hbs, hbt, if_true, if_false, true_imp_iff, and_self_iff, false_imp_iff, and_true_iff, true_and_iff] at h1 ⊢ all_goals exact h1 intro b h_b split_ifs with hbs hbt hbt · refine h_pi b (f_s b) (h_s b hbs) (f_t' b) (h_t' b hbt) (Set.Nonempty.mono ?_ h_nonempty) exact Set.inter_subset_inter (Set.biInter_subset_of_mem hbs) (Set.biInter_subset_of_mem hbt) · exact h_s b hbs · exact h_t' b hbt · rw [Finset.mem_union] at h_b apply False.elim (h_b.elim hbs hbt) /-- Every element of the π-system generated by an indexed union of a family of π-systems is a finite intersection of elements from the π-systems. For a total union version, see `mem_generatePiSystem_iUnion_elim`. -/ theorem mem_generatePiSystem_iUnion_elim' {α β} {g : β → Set (Set α)} {s : Set β} (h_pi : ∀ b ∈ s, IsPiSystem (g b)) (t : Set α) (h_t : t ∈ generatePiSystem (⋃ b ∈ s, g b)) : ∃ (T : Finset β) (f : β → Set α), ↑T ⊆ s ∧ (t = ⋂ b ∈ T, f b) ∧ ∀ b ∈ T, f b ∈ g b := by classical have : t ∈ generatePiSystem (⋃ b : Subtype s, (g ∘ Subtype.val) b) := by suffices h1 : ⋃ b : Subtype s, (g ∘ Subtype.val) b = ⋃ b ∈ s, g b by rwa [h1] ext x simp only [exists_prop, Set.mem_iUnion, Function.comp_apply, Subtype.exists, Subtype.coe_mk] rfl rcases @mem_generatePiSystem_iUnion_elim α (Subtype s) (g ∘ Subtype.val) (fun b => h_pi b.val b.property) t this with ⟨T, ⟨f, ⟨rfl, h_t'⟩⟩⟩ refine ⟨T.image (fun x : s => (x : β)), Function.extend (fun x : s => (x : β)) f fun _ : β => (∅ : Set α), by simp, ?_, ?_⟩ · ext a constructor <;> · simp (config := { proj := false }) only [Set.mem_iInter, Subtype.forall, Finset.set_biInter_finset_image] intro h1 b h_b h_b_in_T have h2 := h1 b h_b h_b_in_T revert h2 rw [Subtype.val_injective.extend_apply] apply id · intros b h_b simp_rw [Finset.mem_image, Subtype.exists, exists_and_right, exists_eq_right] at h_b cases' h_b with h_b_w h_b_h have h_b_alt : b = (Subtype.mk b h_b_w).val := rfl rw [h_b_alt, Subtype.val_injective.extend_apply] apply h_t' apply h_b_h section UnionInter variable {α ι : Type*} /-! ### π-system generated by finite intersections of sets of a π-system family -/ /-- From a set of indices `S : Set ι` and a family of sets of sets `π : ι → Set (Set α)`, define the set of sets that can be written as `⋂ x ∈ t, f x` for some finset `t ⊆ S` and sets `f x ∈ π x`. If `π` is a family of π-systems, then it is a π-system. -/ def piiUnionInter (π : ι → Set (Set α)) (S : Set ι) : Set (Set α) := { s : Set α | ∃ (t : Finset ι) (_ : ↑t ⊆ S) (f : ι → Set α) (_ : ∀ x, x ∈ t → f x ∈ π x), s = ⋂ x ∈ t, f x } theorem piiUnionInter_singleton (π : ι → Set (Set α)) (i : ι) : piiUnionInter π {i} = π i ∪ {univ} := by ext1 s simp only [piiUnionInter, exists_prop, mem_union] refine ⟨?_, fun h => ?_⟩ · rintro ⟨t, hti, f, hfπ, rfl⟩ simp only [subset_singleton_iff, Finset.mem_coe] at hti by_cases hi : i ∈ t · have ht_eq_i : t = {i} := by ext1 x rw [Finset.mem_singleton] exact ⟨fun h => hti x h, fun h => h.symm ▸ hi⟩ simp only [ht_eq_i, Finset.mem_singleton, iInter_iInter_eq_left] exact Or.inl (hfπ i hi) · have ht_empty : t = ∅ := by ext1 x simp only [Finset.not_mem_empty, iff_false_iff] exact fun hx => hi (hti x hx ▸ hx) -- Porting note: `Finset.not_mem_empty` required simp [ht_empty, Finset.not_mem_empty, iInter_false, iInter_univ, Set.mem_singleton univ, or_true_iff] · cases' h with hs hs · refine ⟨{i}, ?_, fun _ => s, ⟨fun x hx => ?_, ?_⟩⟩ · rw [Finset.coe_singleton] · rw [Finset.mem_singleton] at hx rwa [hx] · simp only [Finset.mem_singleton, iInter_iInter_eq_left] · refine ⟨∅, ?_⟩ simpa only [Finset.coe_empty, subset_singleton_iff, mem_empty_iff_false, IsEmpty.forall_iff, imp_true_iff, Finset.not_mem_empty, iInter_false, iInter_univ, true_and_iff, exists_const] using hs theorem piiUnionInter_singleton_left (s : ι → Set α) (S : Set ι) : piiUnionInter (fun i => ({s i} : Set (Set α))) S = { s' : Set α | ∃ (t : Finset ι) (_ : ↑t ⊆ S), s' = ⋂ i ∈ t, s i } := by ext1 s' simp_rw [piiUnionInter, Set.mem_singleton_iff, exists_prop, Set.mem_setOf_eq] refine ⟨fun h => ?_, fun ⟨t, htS, h_eq⟩ => ⟨t, htS, s, fun _ _ => rfl, h_eq⟩⟩ obtain ⟨t, htS, f, hft_eq, rfl⟩ := h refine ⟨t, htS, ?_⟩ congr! 3 apply hft_eq assumption theorem generateFrom_piiUnionInter_singleton_left (s : ι → Set α) (S : Set ι) : generateFrom (piiUnionInter (fun k => {s k}) S) = generateFrom { t | ∃ k ∈ S, s k = t } := by refine le_antisymm (generateFrom_le ?_) (generateFrom_mono ?_) · rintro _ ⟨I, hI, f, hf, rfl⟩ refine Finset.measurableSet_biInter _ fun m hm => measurableSet_generateFrom ?_ exact ⟨m, hI hm, (hf m hm).symm⟩ · rintro _ ⟨k, hk, rfl⟩ refine ⟨{k}, fun m hm => ?_, s, fun i _ => ?_, ?_⟩ · rw [Finset.mem_coe, Finset.mem_singleton] at hm rwa [hm] · exact Set.mem_singleton _ · simp only [Finset.mem_singleton, Set.iInter_iInter_eq_left] /-- If `π` is a family of π-systems, then `piiUnionInter π S` is a π-system. -/ theorem isPiSystem_piiUnionInter (π : ι → Set (Set α)) (hpi : ∀ x, IsPiSystem (π x)) (S : Set ι) : IsPiSystem (piiUnionInter π S) := by classical rintro t1 ⟨p1, hp1S, f1, hf1m, ht1_eq⟩ t2 ⟨p2, hp2S, f2, hf2m, ht2_eq⟩ h_nonempty simp_rw [piiUnionInter, Set.mem_setOf_eq] let g n := ite (n ∈ p1) (f1 n) Set.univ ∩ ite (n ∈ p2) (f2 n) Set.univ have hp_union_ss : ↑(p1 ∪ p2) ⊆ S := by simp only [hp1S, hp2S, Finset.coe_union, union_subset_iff, and_self_iff] use p1 ∪ p2, hp_union_ss, g have h_inter_eq : t1 ∩ t2 = ⋂ i ∈ p1 ∪ p2, g i := by rw [ht1_eq, ht2_eq] simp_rw [← Set.inf_eq_inter] ext1 x simp only [g, inf_eq_inter, mem_inter_iff, mem_iInter, Finset.mem_union] refine ⟨fun h i _ => ?_, fun h => ⟨fun i hi1 => ?_, fun i hi2 => ?_⟩⟩ · split_ifs with h_1 h_2 h_2 exacts [⟨h.1 i h_1, h.2 i h_2⟩, ⟨h.1 i h_1, Set.mem_univ _⟩, ⟨Set.mem_univ _, h.2 i h_2⟩, ⟨Set.mem_univ _, Set.mem_univ _⟩] · specialize h i (Or.inl hi1) rw [if_pos hi1] at h exact h.1 · specialize h i (Or.inr hi2) rw [if_pos hi2] at h exact h.2 refine ⟨fun n hn => ?_, h_inter_eq⟩ simp only [g] split_ifs with hn1 hn2 h · refine hpi n (f1 n) (hf1m n hn1) (f2 n) (hf2m n hn2) (Set.nonempty_iff_ne_empty.2 fun h => ?_) rw [h_inter_eq] at h_nonempty suffices h_empty : ⋂ i ∈ p1 ∪ p2, g i = ∅ from (Set.not_nonempty_iff_eq_empty.mpr h_empty) h_nonempty refine le_antisymm (Set.iInter_subset_of_subset n ?_) (Set.empty_subset _) refine Set.iInter_subset_of_subset hn ?_ simp_rw [g, if_pos hn1, if_pos hn2] exact h.subset · simp [hf1m n hn1] · simp [hf2m n h] · exact absurd hn (by simp [hn1, h]) theorem piiUnionInter_mono_left {π π' : ι → Set (Set α)} (h_le : ∀ i, π i ⊆ π' i) (S : Set ι) : piiUnionInter π S ⊆ piiUnionInter π' S := fun _ ⟨t, ht_mem, ft, hft_mem_pi, h_eq⟩ => ⟨t, ht_mem, ft, fun x hxt => h_le x (hft_mem_pi x hxt), h_eq⟩ theorem piiUnionInter_mono_right {π : ι → Set (Set α)} {S T : Set ι} (hST : S ⊆ T) : piiUnionInter π S ⊆ piiUnionInter π T := fun _ ⟨t, ht_mem, ft, hft_mem_pi, h_eq⟩ => ⟨t, ht_mem.trans hST, ft, hft_mem_pi, h_eq⟩ theorem generateFrom_piiUnionInter_le {m : MeasurableSpace α} (π : ι → Set (Set α)) (h : ∀ n, generateFrom (π n) ≤ m) (S : Set ι) : generateFrom (piiUnionInter π S) ≤ m := by refine generateFrom_le ?_ rintro t ⟨ht_p, _, ft, hft_mem_pi, rfl⟩ refine Finset.measurableSet_biInter _ fun x hx_mem => (h x) _ ?_ exact measurableSet_generateFrom (hft_mem_pi x hx_mem) theorem subset_piiUnionInter {π : ι → Set (Set α)} {S : Set ι} {i : ι} (his : i ∈ S) : π i ⊆ piiUnionInter π S := by have h_ss : {i} ⊆ S := by intro j hj rw [mem_singleton_iff] at hj rwa [hj] refine Subset.trans ?_ (piiUnionInter_mono_right h_ss) rw [piiUnionInter_singleton] exact subset_union_left theorem mem_piiUnionInter_of_measurableSet (m : ι → MeasurableSpace α) {S : Set ι} {i : ι} (hiS : i ∈ S) (s : Set α) (hs : MeasurableSet[m i] s) : s ∈ piiUnionInter (fun n => { s | MeasurableSet[m n] s }) S := subset_piiUnionInter hiS hs theorem le_generateFrom_piiUnionInter {π : ι → Set (Set α)} (S : Set ι) {x : ι} (hxS : x ∈ S) : generateFrom (π x) ≤ generateFrom (piiUnionInter π S) := generateFrom_mono (subset_piiUnionInter hxS) theorem measurableSet_iSup_of_mem_piiUnionInter (m : ι → MeasurableSpace α) (S : Set ι) (t : Set α) (ht : t ∈ piiUnionInter (fun n => { s | MeasurableSet[m n] s }) S) : MeasurableSet[⨆ i ∈ S, m i] t := by rcases ht with ⟨pt, hpt, ft, ht_m, rfl⟩ refine pt.measurableSet_biInter fun i hi => ?_ suffices h_le : m i ≤ ⨆ i ∈ S, m i from h_le (ft i) (ht_m i hi) have hi' : i ∈ S := hpt hi exact le_iSup₂ (f := fun i (_ : i ∈ S) => m i) i hi' theorem generateFrom_piiUnionInter_measurableSet (m : ι → MeasurableSpace α) (S : Set ι) : generateFrom (piiUnionInter (fun n => { s | MeasurableSet[m n] s }) S) = ⨆ i ∈ S, m i := by refine le_antisymm ?_ ?_ · rw [← @generateFrom_measurableSet α (⨆ i ∈ S, m i)] exact generateFrom_mono (measurableSet_iSup_of_mem_piiUnionInter m S) · refine iSup₂_le fun i hi => ?_ rw [← @generateFrom_measurableSet α (m i)] exact generateFrom_mono (mem_piiUnionInter_of_measurableSet m hi) end UnionInter namespace MeasurableSpace variable {α : Type*} /-! ## Dynkin systems and Π-λ theorem -/ /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by a collection of sets which is stable under intersection. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure DynkinSystem (α : Type*) where /-- Predicate saying that a given set is contained in the Dynkin system. -/ Has : Set α → Prop /-- A Dynkin system contains the empty set. -/ has_empty : Has ∅ /-- A Dynkin system is closed under complementation. -/ has_compl : ∀ {a}, Has a → Has aᶜ /-- A Dynkin system is closed under countable union of pairwise disjoint sets. Use a more general `MeasurableSpace.DynkinSystem.has_iUnion` instead. -/ has_iUnion_nat : ∀ {f : ℕ → Set α}, Pairwise (Disjoint on f) → (∀ i, Has (f i)) → Has (⋃ i, f i) namespace DynkinSystem @[ext] theorem ext : ∀ {d₁ d₂ : DynkinSystem α}, (∀ s : Set α, d₁.Has s ↔ d₂.Has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩, ⟨s₂, _, _, _⟩, h => by have : s₁ = s₂ := funext fun x => propext <| h x subst this rfl variable (d : DynkinSystem α) theorem has_compl_iff {a} : d.Has aᶜ ↔ d.Has a := ⟨fun h => by simpa using d.has_compl h, fun h => d.has_compl h⟩ theorem has_univ : d.Has univ := by simpa using d.has_compl d.has_empty theorem has_iUnion {β} [Countable β] {f : β → Set α} (hd : Pairwise (Disjoint on f)) (h : ∀ i, d.Has (f i)) : d.Has (⋃ i, f i) := by cases nonempty_encodable β rw [← Encodable.iUnion_decode₂] exact d.has_iUnion_nat (Encodable.iUnion_decode₂_disjoint_on hd) fun n => Encodable.iUnion_decode₂_cases d.has_empty h theorem has_union {s₁ s₂ : Set α} (h₁ : d.Has s₁) (h₂ : d.Has s₂) (h : Disjoint s₁ s₂) : d.Has (s₁ ∪ s₂) := by rw [union_eq_iUnion] exact d.has_iUnion (pairwise_disjoint_on_bool.2 h) (Bool.forall_bool.2 ⟨h₂, h₁⟩) theorem has_diff {s₁ s₂ : Set α} (h₁ : d.Has s₁) (h₂ : d.Has s₂) (h : s₂ ⊆ s₁) : d.Has (s₁ \ s₂) := by apply d.has_compl_iff.1 simp only [diff_eq, compl_inter, compl_compl] exact d.has_union (d.has_compl h₁) h₂ (disjoint_compl_left.mono_right h) instance instLEDynkinSystem : LE (DynkinSystem α) where le m₁ m₂ := m₁.Has ≤ m₂.Has theorem le_def {α} {a b : DynkinSystem α} : a ≤ b ↔ a.Has ≤ b.Has := Iff.rfl instance : PartialOrder (DynkinSystem α) := { DynkinSystem.instLEDynkinSystem with le_refl := fun a b => le_rfl le_trans := fun a b c hab hbc => le_def.mpr (le_trans hab hbc) le_antisymm := fun a b h₁ h₂ => ext fun s => ⟨h₁ s, h₂ s⟩ } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def ofMeasurableSpace (m : MeasurableSpace α) : DynkinSystem α where Has := m.MeasurableSet' has_empty := m.measurableSet_empty has_compl {a} := m.measurableSet_compl a has_iUnion_nat {f} _ hf := m.measurableSet_iUnion f hf theorem ofMeasurableSpace_le_ofMeasurableSpace_iff {m₁ m₂ : MeasurableSpace α} : ofMeasurableSpace m₁ ≤ ofMeasurableSpace m₂ ↔ m₁ ≤ m₂ := Iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive GenerateHas (s : Set (Set α)) : Set α → Prop | basic : ∀ t ∈ s, GenerateHas s t | empty : GenerateHas s ∅ | compl : ∀ {a}, GenerateHas s a → GenerateHas s aᶜ | iUnion : ∀ {f : ℕ → Set α}, Pairwise (Disjoint on f) → (∀ i, GenerateHas s (f i)) → GenerateHas s (⋃ i, f i) theorem generateHas_compl {C : Set (Set α)} {s : Set α} : GenerateHas C sᶜ ↔ GenerateHas C s := by refine ⟨?_, GenerateHas.compl⟩ intro h convert GenerateHas.compl h simp /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : Set (Set α)) : DynkinSystem α where Has := GenerateHas s has_empty := GenerateHas.empty has_compl {_} := GenerateHas.compl has_iUnion_nat {_} := GenerateHas.iUnion theorem generateHas_def {C : Set (Set α)} : (generate C).Has = GenerateHas C := rfl instance : Inhabited (DynkinSystem α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def toMeasurableSpace (h_inter : ∀ s₁ s₂, d.Has s₁ → d.Has s₂ → d.Has (s₁ ∩ s₂)) : MeasurableSpace α where MeasurableSet' := d.Has measurableSet_empty := d.has_empty measurableSet_compl s h := d.has_compl h measurableSet_iUnion f hf := by rw [← iUnion_disjointed] exact d.has_iUnion (disjoint_disjointed _) fun n => disjointedRec (fun (t : Set α) i h => h_inter _ _ h <| d.has_compl <| hf i) (hf n) theorem ofMeasurableSpace_toMeasurableSpace (h_inter : ∀ s₁ s₂, d.Has s₁ → d.Has s₂ → d.Has (s₁ ∩ s₂)) : ofMeasurableSpace (d.toMeasurableSpace h_inter) = d := ext fun _ => Iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrictOn {s : Set α} (h : d.Has s) : DynkinSystem α where -- Porting note(#12129): additional beta reduction needed Has t := d.Has (t ∩ s) has_empty := by simp [d.has_empty] has_compl {t} hts := by beta_reduce have : tᶜ ∩ s = (t ∩ s)ᶜ \ sᶜ := Set.ext fun x => by by_cases h : x ∈ s <;> simp [h] rw [this] exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr inter_subset_right) has_iUnion_nat {f} hd hf := by simp only [] rw [iUnion_inter] refine d.has_iUnion_nat ?_ hf exact hd.mono fun i j => Disjoint.mono inter_subset_left inter_subset_left theorem generate_le {s : Set (Set α)} (h : ∀ t ∈ s, d.Has t) : generate s ≤ d := fun _ ht => ht.recOn h d.has_empty (fun {_} _ h => d.has_compl h) fun {_} hd _ hf => d.has_iUnion hd hf theorem generate_has_subset_generate_measurable {C : Set (Set α)} {s : Set α} (hs : (generate C).Has s) : MeasurableSet[generateFrom C] s := generate_le (ofMeasurableSpace (generateFrom C)) (fun _ => measurableSet_generateFrom) s hs theorem generate_inter {s : Set (Set α)} (hs : IsPiSystem s) {t₁ t₂ : Set α} (ht₁ : (generate s).Has t₁) (ht₂ : (generate s).Has t₂) : (generate s).Has (t₁ ∩ t₂) := have : generate s ≤ (generate s).restrictOn ht₂ := generate_le _ fun s₁ hs₁ => have : (generate s).Has s₁ := GenerateHas.basic s₁ hs₁ have : generate s ≤ (generate s).restrictOn this := generate_le _ fun s₂ hs₂ => show (generate s).Has (s₂ ∩ s₁) from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (fun h => h.symm ▸ GenerateHas.empty) fun h => GenerateHas.basic _ <| hs _ hs₂ _ hs₁ h have : (generate s).Has (t₂ ∩ s₁) := this _ ht₂ show (generate s).Has (s₁ ∩ t₂) by rwa [inter_comm] this _ ht₁ /-- **Dynkin's π-λ theorem**: Given a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a π-system (often requiring additionally that it is non-empty, but we drop this condition in the formalization). -/ theorem generateFrom_eq {s : Set (Set α)} (hs : IsPiSystem s) : generateFrom s = (generate s).toMeasurableSpace fun t₁ t₂ => generate_inter hs := le_antisymm (generateFrom_le fun t ht => GenerateHas.basic t ht) (ofMeasurableSpace_le_ofMeasurableSpace_iff.mp <| by rw [ofMeasurableSpace_toMeasurableSpace] exact generate_le _ fun t ht => measurableSet_generateFrom ht) end DynkinSystem theorem induction_on_inter {C : Set α → Prop} {s : Set (Set α)} [m : MeasurableSpace α] (h_eq : m = generateFrom s) (h_inter : IsPiSystem s) (h_empty : C ∅) (h_basic : ∀ t ∈ s, C t) (h_compl : ∀ t, MeasurableSet t → C t → C tᶜ) (h_union : ∀ f : ℕ → Set α, Pairwise (Disjoint on f) → (∀ i, MeasurableSet (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, MeasurableSet t → C t := have eq : MeasurableSet = DynkinSystem.GenerateHas s := by rw [h_eq, DynkinSystem.generateFrom_eq h_inter] rfl fun t ht => have : DynkinSystem.GenerateHas s t := by rwa [eq] at ht this.recOn h_basic h_empty (fun {t} ht => h_compl t <| by rw [eq] exact ht) fun {f} hf ht => h_union f hf fun i => by rw [eq] exact ht _ end MeasurableSpace
MeasureTheory\SetAlgebra.lean
/- Copyright (c) 2024 Etienne Marion. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Etienne Marion -/ import Mathlib.MeasureTheory.SetSemiring /-! # Algebra of sets In this file we define the notion of algebra of sets and give its basic properties. An algebra of sets is a family of sets containing the empty set and closed by complement and binary union. It is therefore similar to a `σ`-algebra, except that it is not necessarily closed by countable unions. We also define the algebra of sets generated by a family of sets and give its basic properties, and we prove that it is countable when it is generated by a countable family. We prove that the `σ`-algebra generated by a family of sets `𝒜` is the same as the one generated by the algebra of sets generated by `𝒜`. ## Main definitions * `MeasureTheory.IsSetAlgebra`: property of being an algebra of sets. * `MeasureTheory.generateSetAlgebra`: the algebra of sets generated by a family of sets. ## Main statements * `MeasureTheory.mem_generateSetAlgebra_elim`: If a set `s` belongs to the algebra of sets generated by `𝒜`, then it can be written as a finite union of finite intersections of sets which are in `𝒜` or have their complement in `𝒜`. * `MeasureTheory.countable_generateSetAlgebra`: If a family of sets is countable then so is the algebra of sets generated by it. ## References * <https://en.wikipedia.org/wiki/Field_of_sets> ## Tags algebra of sets, generated algebra of sets -/ open MeasurableSpace Set namespace MeasureTheory variable {α : Type*} {𝒜 : Set (Set α)} {s t : Set α} /-! ### Definition and basic properties of an algebra of sets -/ /-- An algebra of sets is a family of sets containing the empty set and closed by complement and union. Consequently it is also closed by difference (see `IsSetAlgebra.diff_mem`) and intersection (see `IsSetAlgebra.inter_mem`). -/ structure IsSetAlgebra (𝒜 : Set (Set α)) : Prop where empty_mem : ∅ ∈ 𝒜 compl_mem : ∀ ⦃s⦄, s ∈ 𝒜 → sᶜ ∈ 𝒜 union_mem : ∀ ⦃s t⦄, s ∈ 𝒜 → t ∈ 𝒜 → s ∪ t ∈ 𝒜 namespace IsSetAlgebra /-- An algebra of sets contains the whole set. -/ theorem univ_mem (h𝒜 : IsSetAlgebra 𝒜) : univ ∈ 𝒜 := compl_empty ▸ h𝒜.compl_mem h𝒜.empty_mem /-- An algebra of sets is closed by intersection. -/ theorem inter_mem (h𝒜 : IsSetAlgebra 𝒜) (s_mem : s ∈ 𝒜) (t_mem : t ∈ 𝒜) : s ∩ t ∈ 𝒜 := inter_eq_compl_compl_union_compl .. ▸ h𝒜.compl_mem (h𝒜.union_mem (h𝒜.compl_mem s_mem) (h𝒜.compl_mem t_mem)) /-- An algebra of sets is closed by difference. -/ theorem diff_mem (h𝒜 : IsSetAlgebra 𝒜) (s_mem : s ∈ 𝒜) (t_mem : t ∈ 𝒜) : s \ t ∈ 𝒜 := h𝒜.inter_mem s_mem (h𝒜.compl_mem t_mem) /-- An algebra of sets is a ring of sets. -/ theorem isSetRing (h𝒜 : IsSetAlgebra 𝒜) : IsSetRing 𝒜 where empty_mem := h𝒜.empty_mem union_mem := h𝒜.union_mem diff_mem := fun _ _ ↦ h𝒜.diff_mem /-- An algebra of sets is closed by finite unions. -/ theorem biUnion_mem {ι : Type*} (h𝒜 : IsSetAlgebra 𝒜) {s : ι → Set α} (S : Finset ι) (hs : ∀ i ∈ S, s i ∈ 𝒜) : ⋃ i ∈ S, s i ∈ 𝒜 := h𝒜.isSetRing.biUnion_mem S hs /-- An algebra of sets is closed by finite intersections. -/ theorem biInter_mem {ι : Type*} (h𝒜 : IsSetAlgebra 𝒜) {s : ι → Set α} (S : Finset ι) (hs : ∀ i ∈ S, s i ∈ 𝒜) : ⋂ i ∈ S, s i ∈ 𝒜 := by by_cases h : S = ∅ · rw [h, ← Finset.set_biInter_coe, Finset.coe_empty, biInter_empty] exact h𝒜.univ_mem · rw [← ne_eq, ← Finset.nonempty_iff_ne_empty] at h exact h𝒜.isSetRing.biInter_mem S h hs end IsSetAlgebra section generateSetAlgebra /-! ### Definition and properties of the algebra of sets generated by some family -/ /-- `generateSetAlgebra 𝒜` is the smallest algebra of sets containing `𝒜`. -/ inductive generateSetAlgebra {α : Type*} (𝒜 : Set (Set α)) : Set (Set α) | base (s : Set α) (s_mem : s ∈ 𝒜) : generateSetAlgebra 𝒜 s | empty : generateSetAlgebra 𝒜 ∅ | compl (s : Set α) (hs : generateSetAlgebra 𝒜 s) : generateSetAlgebra 𝒜 sᶜ | union (s t : Set α) (hs : generateSetAlgebra 𝒜 s) (ht : generateSetAlgebra 𝒜 t) : generateSetAlgebra 𝒜 (s ∪ t) /-- The algebra of sets generated by a family of sets is an algebra of sets. -/ theorem isSetAlgebra_generateSetAlgebra : IsSetAlgebra (generateSetAlgebra 𝒜) where empty_mem := generateSetAlgebra.empty compl_mem := fun _ hs ↦ generateSetAlgebra.compl _ hs union_mem := fun _ _ hs ht ↦ generateSetAlgebra.union _ _ hs ht /-- The algebra of sets generated by `𝒜` contains `𝒜`. -/ theorem self_subset_generateSetAlgebra : 𝒜 ⊆ generateSetAlgebra 𝒜 := fun _ ↦ generateSetAlgebra.base _ /-- The measurable space generated by a family of sets `𝒜` is the same as the one generated by the algebra of sets generated by `𝒜`. -/ @[simp] theorem generateFrom_generateSetAlgebra_eq : generateFrom (generateSetAlgebra 𝒜) = generateFrom 𝒜 := by refine le_antisymm (fun s ms ↦ ?_) (generateFrom_mono self_subset_generateSetAlgebra) refine @generateFrom_induction _ _ (generateSetAlgebra 𝒜) (fun t ht ↦ ?_) (@MeasurableSet.empty _ (generateFrom 𝒜)) (fun t ↦ MeasurableSet.compl) (fun f hf ↦ MeasurableSet.iUnion hf) s ms induction ht with | base u u_mem => exact measurableSet_generateFrom u_mem | empty => exact @MeasurableSet.empty _ (generateFrom 𝒜) | compl u _ mu => exact mu.compl | union u v _ _ mu mv => exact MeasurableSet.union mu mv /-- If a family of sets `𝒜` is contained in `ℬ`, then the algebra of sets generated by `𝒜` is contained in the one generated by `ℬ`. -/ theorem generateSetAlgebra_mono {ℬ : Set (Set α)} (h : 𝒜 ⊆ ℬ) : generateSetAlgebra 𝒜 ⊆ generateSetAlgebra ℬ := by intro s hs induction hs with | base t t_mem => exact self_subset_generateSetAlgebra (h t_mem) | empty => exact isSetAlgebra_generateSetAlgebra.empty_mem | compl t _ t_mem => exact isSetAlgebra_generateSetAlgebra.compl_mem t_mem | union t u _ _ t_mem u_mem => exact isSetAlgebra_generateSetAlgebra.union_mem t_mem u_mem namespace IsSetAlgebra /-- If a family of sets `𝒜` is contained in an algebra of sets `ℬ`, then so is the algebra of sets generated by `𝒜`. -/ theorem generateSetAlgebra_subset {ℬ : Set (Set α)} (h : 𝒜 ⊆ ℬ) (hℬ : IsSetAlgebra ℬ) : generateSetAlgebra 𝒜 ⊆ ℬ := by intro s hs induction hs with | base t t_mem => exact h t_mem | empty => exact hℬ.empty_mem | compl t _ t_mem => exact hℬ.compl_mem t_mem | union t u _ _ t_mem u_mem => exact hℬ.union_mem t_mem u_mem /-- If `𝒜` is an algebra of sets, then it contains the algebra generated by itself. -/ theorem generateSetAlgebra_subset_self (h𝒜 : IsSetAlgebra 𝒜) : generateSetAlgebra 𝒜 ⊆ 𝒜 := h𝒜.generateSetAlgebra_subset subset_rfl /-- If `𝒜` is an algebra of sets, then it is equal to the algebra generated by itself. -/ theorem generateSetAlgebra_eq (h𝒜 : IsSetAlgebra 𝒜) : generateSetAlgebra 𝒜 = 𝒜 := Subset.antisymm h𝒜.generateSetAlgebra_subset_self self_subset_generateSetAlgebra end IsSetAlgebra /-- If a set belongs to the algebra of sets generated by `𝒜` then it can be written as a finite union of finite intersections of sets which are in `𝒜` or have their complement in `𝒜`. -/ theorem mem_generateSetAlgebra_elim (s_mem : s ∈ generateSetAlgebra 𝒜) : ∃ A : Set (Set (Set α)), A.Finite ∧ (∀ a ∈ A, a.Finite) ∧ (∀ᵉ (a ∈ A) (t ∈ a), t ∈ 𝒜 ∨ tᶜ ∈ 𝒜) ∧ s = ⋃ a ∈ A, ⋂ t ∈ a, t := by induction s_mem with | base u u_mem => refine ⟨{{u}}, finite_singleton {u}, fun a ha ↦ eq_of_mem_singleton ha ▸ finite_singleton u, fun a ha t ht ↦ ?_, by simp⟩ rw [eq_of_mem_singleton ha, ha, eq_of_mem_singleton ht, ht] at * exact Or.inl u_mem | empty => exact ⟨∅, finite_empty, fun _ h ↦ (not_mem_empty _ h).elim, fun _ ha _ _ ↦ (not_mem_empty _ ha).elim, by simp⟩ | compl u _ u_ind => rcases u_ind with ⟨A, A_fin, mem_A, hA, u_eq⟩ have := finite_coe_iff.2 A_fin have := fun a : A ↦ finite_coe_iff.2 <| mem_A a.1 a.2 refine ⟨{{(f a).1ᶜ | a : A} | f : (Π a : A, ↑a)}, finite_coe_iff.1 inferInstance, fun a ⟨f, hf⟩ ↦ hf ▸ finite_coe_iff.1 inferInstance, fun a ha t ht ↦ ?_, ?_⟩ · rcases ha with ⟨f, rfl⟩ rcases ht with ⟨a, rfl⟩ rw [compl_compl, or_comm] exact hA a.1 a.2 (f a).1 (f a).2 · ext x simp only [u_eq, compl_iUnion, compl_iInter, mem_iInter, mem_iUnion, mem_compl_iff, exists_prop, Subtype.exists, mem_setOf_eq, iUnion_exists, iUnion_iUnion_eq', iInter_exists] constructor <;> intro hx · choose f hf using hx exact ⟨fun ⟨a, ha⟩ ↦ ⟨f a ha, (hf a ha).1⟩, fun _ a ha h ↦ by rw [← h]; exact (hf a ha).2⟩ · rcases hx with ⟨f, hf⟩ exact fun a ha ↦ ⟨f ⟨a, ha⟩, (f ⟨a, ha⟩).2, hf (f ⟨a, ha⟩)ᶜ a ha rfl⟩ | union u v _ _ u_ind v_ind => rcases u_ind with ⟨Au, Au_fin, mem_Au, hAu, u_eq⟩ rcases v_ind with ⟨Av, Av_fin, mem_Av, hAv, v_eq⟩ refine ⟨Au ∪ Av, Au_fin.union Av_fin, ?_, ?_, by rw [u_eq, v_eq, ← biUnion_union]⟩ · rintro a (ha | ha) · exact mem_Au a ha · exact mem_Av a ha · rintro a (ha | ha) t ht · exact hAu a ha t ht · exact hAv a ha t ht /-- If a family of sets is countable then so is the algebra of sets generated by it. -/ theorem countable_generateSetAlgebra (h : 𝒜.Countable) : (generateSetAlgebra 𝒜).Countable := by let ℬ := {s | s ∈ 𝒜} ∪ {s | sᶜ ∈ 𝒜} have count_ℬ : ℬ.Countable := by apply h.union have : compl '' 𝒜 = {s | sᶜ ∈ 𝒜} := by ext s simpa using ⟨fun ⟨x, x_mem, hx⟩ ↦ by simp [← hx, x_mem], fun hs ↦ ⟨sᶜ, hs, by simp⟩⟩ exact this ▸ h.image compl let f : Set (Set (Set α)) → Set α := fun A ↦ ⋃ a ∈ A, ⋂ t ∈ a, t let 𝒞 := {a | a.Finite ∧ a ⊆ ℬ} have count_𝒞 : 𝒞.Countable := countable_setOf_finite_subset (countable_coe_iff.1 count_ℬ) let 𝒟 := {A | A.Finite ∧ A ⊆ 𝒞} have count_𝒟 : 𝒟.Countable := countable_setOf_finite_subset (countable_coe_iff.1 count_𝒞) have : generateSetAlgebra 𝒜 ⊆ f '' 𝒟 := by intro s s_mem rcases mem_generateSetAlgebra_elim s_mem with ⟨A, A_fin, mem_A, hA, rfl⟩ exact ⟨A, ⟨A_fin, fun a ha ↦ ⟨mem_A a ha, hA a ha⟩⟩, rfl⟩ exact (count_𝒟.image f).mono this end generateSetAlgebra end MeasureTheory
MeasureTheory\SetSemiring.lean
/- Copyright (c) 2023 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Peter Pfaffelhuber -/ import Mathlib.Data.Set.Pairwise.Lattice import Mathlib.MeasureTheory.PiSystem /-! # Semirings and rings of sets A semi-ring of sets `C` (in the sense of measure theory) is a family of sets containing `∅`, stable by intersection and such that for all `s, t ∈ C`, `t \ s` is equal to a disjoint union of finitely many sets in `C`. Note that a semi-ring of sets may not contain unions. An important example of a semi-ring of sets is intervals in `ℝ`. The intersection of two intervals is an interval (possibly empty). The union of two intervals may not be an interval. The set difference of two intervals may not be an interval, but it will be a disjoint union of two intervals. A ring of sets is a set of sets containing `∅`, stable by union, set difference and intersection. ## Main definitions * `MeasureTheory.IsSetSemiring C`: property of being a semi-ring of sets. * `MeasureTheory.IsSetSemiring.diffFinset hs ht`: for `s, t` in a semi-ring `C` (with `hC : IsSetSemiring C`) with `hs : s ∈ C`, `ht : t ∈ C`, this is a `Finset` of pairwise disjoint sets such that `s \ t = ⋃₀ hC.diffFinset hs ht`. * `MeasureTheory.IsSetSemiring.diffFinset₀ hs hI`: for `hs : s ∈ C` and a finset `I` of sets in `C` (with `hI : ↑I ⊆ C`), this is a `Finset` of pairwise disjoint sets such that `s \ ⋃₀ I = ⋃₀ hC.diffFinset₀ hs hI`. * `MeasureTheory.IsSetRing`: property of being a ring of sets. ## Main statements * `MeasureTheory.IsSetSemiring.exists_disjoint_finset_diff_eq`: the existence of the `Finset` given by the definition `IsSetSemiring.diffFinset₀` (see above). -/ open Finset Set namespace MeasureTheory variable {α : Type*} {C : Set (Set α)} {s t : Set α} /-- A semi-ring of sets `C` is a family of sets containing `∅`, stable by intersection and such that for all `s, t ∈ C`, `s \ t` is equal to a disjoint union of finitely many sets in `C`. -/ structure IsSetSemiring (C : Set (Set α)) : Prop where empty_mem : ∅ ∈ C inter_mem : ∀ s ∈ C, ∀ t ∈ C, s ∩ t ∈ C diff_eq_sUnion' : ∀ s ∈ C, ∀ t ∈ C, ∃ I : Finset (Set α), ↑I ⊆ C ∧ PairwiseDisjoint (I : Set (Set α)) id ∧ s \ t = ⋃₀ I namespace IsSetSemiring lemma isPiSystem (hC : IsSetSemiring C) : IsPiSystem C := fun s hs t ht _ ↦ hC.inter_mem s hs t ht section diffFinset open scoped Classical in /-- In a semi-ring of sets `C`, for all sets `s, t ∈ C`, `s \ t` is equal to a disjoint union of finitely many sets in `C`. The finite set of sets in the union is not unique, but this definition gives an arbitrary `Finset (Set α)` that satisfies the equality. We remove the empty set to ensure that `t ∉ hC.diffFinset hs ht` even if `t = ∅`. -/ noncomputable def diffFinset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) : Finset (Set α) := (hC.diff_eq_sUnion' s hs t ht).choose \ {∅} lemma empty_not_mem_diffFinset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) : ∅ ∉ hC.diffFinset hs ht := by classical simp only [diffFinset, mem_sdiff, Finset.mem_singleton, eq_self_iff_true, not_true, and_false_iff, not_false_iff] lemma diffFinset_subset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) : ↑(hC.diffFinset hs ht) ⊆ C := by classical simp only [diffFinset, coe_sdiff, coe_singleton, diff_singleton_subset_iff] exact (hC.diff_eq_sUnion' s hs t ht).choose_spec.1.trans (Set.subset_insert _ _) lemma pairwiseDisjoint_diffFinset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) : PairwiseDisjoint (hC.diffFinset hs ht : Set (Set α)) id := by classical simp only [diffFinset, coe_sdiff, coe_singleton] exact Set.PairwiseDisjoint.subset (hC.diff_eq_sUnion' s hs t ht).choose_spec.2.1 diff_subset lemma sUnion_diffFinset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) : ⋃₀ hC.diffFinset hs ht = s \ t := by classical rw [(hC.diff_eq_sUnion' s hs t ht).choose_spec.2.2] simp only [diffFinset, coe_sdiff, coe_singleton, diff_singleton_subset_iff] rw [sUnion_diff_singleton_empty] lemma not_mem_diffFinset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) : t ∉ hC.diffFinset hs ht := by intro hs_mem suffices t ⊆ s \ t by have h := @disjoint_sdiff_self_right _ t s _ specialize h le_rfl this simp only [Set.bot_eq_empty, Set.le_eq_subset, subset_empty_iff] at h refine hC.empty_not_mem_diffFinset hs ht ?_ rwa [← h] rw [← hC.sUnion_diffFinset hs ht] exact subset_sUnion_of_mem hs_mem lemma sUnion_insert_diffFinset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) (hst : t ⊆ s) : ⋃₀ insert t (hC.diffFinset hs ht) = s := by conv_rhs => rw [← union_diff_cancel hst, ← hC.sUnion_diffFinset hs ht] simp only [mem_coe, sUnion_insert] lemma disjoint_sUnion_diffFinset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) : Disjoint t (⋃₀ hC.diffFinset hs ht) := by rw [hC.sUnion_diffFinset] exact disjoint_sdiff_right lemma pairwiseDisjoint_insert_diffFinset (hC : IsSetSemiring C) (hs : s ∈ C) (ht : t ∈ C) : PairwiseDisjoint (insert t (hC.diffFinset hs ht) : Set (Set α)) id := by have h := hC.pairwiseDisjoint_diffFinset hs ht refine PairwiseDisjoint.insert_of_not_mem h (hC.not_mem_diffFinset hs ht) fun u hu ↦ ?_ simp_rw [id] refine Disjoint.mono_right ?_ (hC.disjoint_sUnion_diffFinset hs ht) simp only [Set.le_eq_subset] exact subset_sUnion_of_mem hu end diffFinset section diffFinset₀ variable {I : Finset (Set α)} /-- In a semiring of sets `C`, for all set `s ∈ C` and finite set of sets `I ⊆ C`, there is a finite set of sets in `C` whose union is `s \ ⋃₀ I`. See `IsSetSemiring.diffFinset₀` for a definition that gives such a set. -/ lemma exists_disjoint_finset_diff_eq (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : ∃ J : Finset (Set α), ↑J ⊆ C ∧ PairwiseDisjoint (J : Set (Set α)) id ∧ s \ ⋃₀ I = ⋃₀ J := by classical induction I using Finset.induction with | empty => simp only [coe_empty, sUnion_empty, diff_empty, exists_prop] refine ⟨{s}, singleton_subset_set_iff.mpr hs, ?_⟩ simp only [coe_singleton, pairwiseDisjoint_singleton, sUnion_singleton, eq_self_iff_true, and_self_iff] | @insert t I' _ h => ?_ rw [coe_insert] at hI have ht : t ∈ C := hI (Set.mem_insert _ _) obtain ⟨J, h_ss, h_dis, h_eq⟩ := h ((Set.subset_insert _ _).trans hI) let Ju : ∀ u ∈ C, Finset (Set α) := fun u hu ↦ hC.diffFinset hu ht have hJu_subset : ∀ (u) (hu : u ∈ C), ↑(Ju u hu) ⊆ C := by intro u hu x hx exact hC.diffFinset_subset hu ht hx have hJu_disj : ∀ (u) (hu : u ∈ C), (Ju u hu : Set (Set α)).PairwiseDisjoint id := fun u hu ↦ hC.pairwiseDisjoint_diffFinset hu ht have hJu_sUnion : ∀ (u) (hu : u ∈ C), ⋃₀ (Ju u hu : Set (Set α)) = u \ t := fun u hu ↦ hC.sUnion_diffFinset hu ht have hJu_disj' : ∀ (u) (hu : u ∈ C) (v) (hv : v ∈ C) (_h_dis : Disjoint u v), Disjoint (⋃₀ (Ju u hu : Set (Set α))) (⋃₀ ↑(Ju v hv)) := by intro u hu v hv huv_disj rw [hJu_sUnion, hJu_sUnion] exact disjoint_of_subset Set.diff_subset Set.diff_subset huv_disj let J' : Finset (Set α) := Finset.biUnion (Finset.univ : Finset J) fun u ↦ Ju u (h_ss u.prop) have hJ'_subset : ↑J' ⊆ C := by intro u simp only [J' ,Subtype.coe_mk, univ_eq_attach, coe_biUnion, mem_coe, mem_attach, iUnion_true, mem_iUnion, Finset.exists_coe, exists₂_imp] intro v hv huvt exact hJu_subset v (h_ss hv) huvt refine ⟨J', hJ'_subset, ?_, ?_⟩ · rw [Finset.coe_biUnion] refine PairwiseDisjoint.biUnion ?_ ?_ · simp only [univ_eq_attach, mem_coe, id, iSup_eq_iUnion] simp_rw [PairwiseDisjoint, Set.Pairwise] intro x _ y _ hxy have hxy_disj : Disjoint (x : Set α) y := by by_contra h_contra refine hxy ?_ refine Subtype.ext ?_ exact h_dis.elim x.prop y.prop h_contra convert hJu_disj' (x : Set α) (h_ss x.prop) y (h_ss y.prop) hxy_disj · rw [sUnion_eq_biUnion] congr · rw [sUnion_eq_biUnion] congr · exact fun u _ ↦ hJu_disj _ _ · rw [coe_insert, sUnion_insert, Set.union_comm, ← Set.diff_diff, h_eq] simp_rw [J', sUnion_eq_biUnion, Set.iUnion_diff] simp only [Subtype.coe_mk, mem_coe, Finset.mem_biUnion, Finset.mem_univ, exists_true_left, Finset.exists_coe, iUnion_exists, true_and] rw [iUnion_comm] refine iUnion_congr fun i ↦ ?_ by_cases hi : i ∈ J · simp only [hi, iUnion_true, exists_prop] rw [← hJu_sUnion i (h_ss hi), sUnion_eq_biUnion] simp only [mem_coe] · simp only [hi, iUnion_of_empty, iUnion_empty] open scoped Classical in /-- In a semiring of sets `C`, for all set `s ∈ C` and finite set of sets `I ⊆ C`, `diffFinset₀` is a finite set of sets in `C` such that `s \ ⋃₀ I = ⋃₀ (hC.diffFinset₀ hs I hI)`. `diffFinset` is a special case of `diffFinset₀` where `I` is a singleton. -/ noncomputable def diffFinset₀ (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : Finset (Set α) := (hC.exists_disjoint_finset_diff_eq hs hI).choose \ {∅} lemma empty_not_mem_diffFinset₀ (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : ∅ ∉ hC.diffFinset₀ hs hI := by classical simp only [diffFinset₀, mem_sdiff, Finset.mem_singleton, eq_self_iff_true, not_true, and_false_iff, not_false_iff] lemma diffFinset₀_subset (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : ↑(hC.diffFinset₀ hs hI) ⊆ C := by classical simp only [diffFinset₀, coe_sdiff, coe_singleton, diff_singleton_subset_iff] exact (hC.exists_disjoint_finset_diff_eq hs hI).choose_spec.1.trans (Set.subset_insert _ _) lemma pairwiseDisjoint_diffFinset₀ (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : PairwiseDisjoint (hC.diffFinset₀ hs hI : Set (Set α)) id := by classical simp only [diffFinset₀, coe_sdiff, coe_singleton] exact Set.PairwiseDisjoint.subset (hC.exists_disjoint_finset_diff_eq hs hI).choose_spec.2.1 diff_subset lemma diff_sUnion_eq_sUnion_diffFinset₀ (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : s \ ⋃₀ I = ⋃₀ hC.diffFinset₀ hs hI := by classical rw [(hC.exists_disjoint_finset_diff_eq hs hI).choose_spec.2.2] simp only [diffFinset₀, coe_sdiff, coe_singleton, diff_singleton_subset_iff] rw [sUnion_diff_singleton_empty] lemma sUnion_diffFinset₀_subset (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : ⋃₀ (hC.diffFinset₀ hs hI : Set (Set α)) ⊆ s := by rw [← hC.diff_sUnion_eq_sUnion_diffFinset₀] exact diff_subset lemma disjoint_sUnion_diffFinset₀ (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : Disjoint (⋃₀ (I : Set (Set α))) (⋃₀ hC.diffFinset₀ hs hI) := by rw [← hC.diff_sUnion_eq_sUnion_diffFinset₀]; exact Set.disjoint_sdiff_right lemma disjoint_diffFinset₀ (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) : Disjoint I (hC.diffFinset₀ hs hI) := by by_contra h rw [Finset.not_disjoint_iff] at h obtain ⟨u, huI, hu_diffFinset₀⟩ := h have h_disj : u ≤ ⊥ := hC.disjoint_sUnion_diffFinset₀ hs hI (subset_sUnion_of_mem huI) (subset_sUnion_of_mem hu_diffFinset₀) simp only [Set.bot_eq_empty, Set.le_eq_subset, subset_empty_iff] at h_disj refine hC.empty_not_mem_diffFinset₀ hs hI ?_ rwa [h_disj] at hu_diffFinset₀ lemma pairwiseDisjoint_union_diffFinset₀ (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) (h_dis : PairwiseDisjoint (I : Set (Set α)) id) : PairwiseDisjoint (I ∪ hC.diffFinset₀ hs hI : Set (Set α)) id := by rw [pairwiseDisjoint_union] refine ⟨h_dis, hC.pairwiseDisjoint_diffFinset₀ hs hI, fun u hu v hv _ ↦ ?_⟩ simp_rw [id] exact disjoint_of_subset (subset_sUnion_of_mem hu) (subset_sUnion_of_mem hv) (hC.disjoint_sUnion_diffFinset₀ hs hI) lemma sUnion_union_sUnion_diffFinset₀_of_subset (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) (hI_ss : ∀ t ∈ I, t ⊆ s) : ⋃₀ I ∪ ⋃₀ hC.diffFinset₀ hs hI = s := by conv_rhs => rw [← union_diff_cancel (Set.sUnion_subset hI_ss : ⋃₀ ↑I ⊆ s), hC.diff_sUnion_eq_sUnion_diffFinset₀ hs hI] lemma sUnion_union_diffFinset₀_of_subset (hC : IsSetSemiring C) (hs : s ∈ C) (hI : ↑I ⊆ C) (hI_ss : ∀ t ∈ I, t ⊆ s) [DecidableEq (Set α)] : ⋃₀ ↑(I ∪ hC.diffFinset₀ hs hI) = s := by conv_rhs => rw [← sUnion_union_sUnion_diffFinset₀_of_subset hC hs hI hI_ss] simp_rw [coe_union] rw [sUnion_union] end diffFinset₀ end IsSetSemiring /-- A ring of sets `C` is a family of sets containing `∅`, stable by union and set difference. It is then also stable by intersection (see `IsSetRing.inter_mem`). -/ structure IsSetRing (C : Set (Set α)) : Prop where empty_mem : ∅ ∈ C union_mem ⦃s t⦄ : s ∈ C → t ∈ C → s ∪ t ∈ C diff_mem ⦃s t⦄ : s ∈ C → t ∈ C → s \ t ∈ C namespace IsSetRing lemma inter_mem (hC : IsSetRing C) (hs : s ∈ C) (ht : t ∈ C) : s ∩ t ∈ C := by rw [← diff_diff_right_self]; exact hC.diff_mem hs (hC.diff_mem hs ht) lemma isSetSemiring (hC : IsSetRing C) : IsSetSemiring C where empty_mem := hC.empty_mem inter_mem := fun s hs t ht => hC.inter_mem hs ht diff_eq_sUnion' := by refine fun s hs t ht => ⟨{s \ t}, ?_, ?_, ?_⟩ · simp only [coe_singleton, Set.singleton_subset_iff] exact hC.diff_mem hs ht · simp only [coe_singleton, pairwiseDisjoint_singleton] · simp only [coe_singleton, sUnion_singleton] lemma biUnion_mem {ι : Type*} (hC : IsSetRing C) {s : ι → Set α} (S : Finset ι) (hs : ∀ n ∈ S, s n ∈ C) : ⋃ i ∈ S, s i ∈ C := by classical induction' S using Finset.induction with i S _ h hs · simp [hC.empty_mem] · simp_rw [← Finset.mem_coe, Finset.coe_insert, Set.biUnion_insert] refine hC.union_mem (hs i (mem_insert_self i S)) ?_ exact h (fun n hnS ↦ hs n (mem_insert_of_mem hnS)) lemma biInter_mem {ι : Type*} (hC : IsSetRing C) {s : ι → Set α} (S : Finset ι) (hS : S.Nonempty) (hs : ∀ n ∈ S, s n ∈ C) : ⋂ i ∈ S, s i ∈ C := by classical induction' hS using Finset.Nonempty.cons_induction with _ i S hiS _ h hs · simpa using hs · simp_rw [← Finset.mem_coe, Finset.coe_cons, Set.biInter_insert] simp only [cons_eq_insert, Finset.mem_insert, forall_eq_or_imp] at hs refine hC.inter_mem hs.1 ?_ exact h (fun n hnS ↦ hs.2 n hnS) end IsSetRing end MeasureTheory
MeasureTheory\Category\MeasCat.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 -/ import Mathlib.MeasureTheory.Measure.GiryMonad import Mathlib.CategoryTheory.ConcreteCategory.UnbundledHom import Mathlib.CategoryTheory.Monad.Algebra import Mathlib.Topology.Category.TopCat.Basic /-! # The category of measurable spaces Measurable spaces and measurable functions form a (concrete) category `MeasCat`. ## Main definitions * `Measure : MeasCat ⥤ MeasCat`: the functor which sends a measurable space `X` to the space of measures on `X`; it is a monad (the "Giry monad"). * `Borel : TopCat ⥤ MeasCat`: sends a topological space `X` to `X` equipped with the `σ`-algebra of Borel sets (the `σ`-algebra generated by the open subsets of `X`). ## Tags measurable space, giry monad, borel -/ noncomputable section open CategoryTheory MeasureTheory open scoped ENNReal universe u v /-- The category of measurable spaces and measurable functions. -/ def MeasCat : Type (u + 1) := Bundled MeasurableSpace namespace MeasCat instance : CoeSort MeasCat Type* := Bundled.coeSort instance (X : MeasCat) : MeasurableSpace X := X.str /-- Construct a bundled `MeasCat` from the underlying type and the typeclass. -/ def of (α : Type u) [ms : MeasurableSpace α] : MeasCat := ⟨α, ms⟩ @[simp] theorem coe_of (X : Type u) [MeasurableSpace X] : (of X : Type u) = X := rfl instance unbundledHom : UnbundledHom @Measurable := ⟨@measurable_id, @Measurable.comp⟩ deriving instance LargeCategory for MeasCat -- Porting note: `deriving instance ConcreteCategory for MeasCat` didn't work. Define it manually. -- see https://github.com/leanprover-community/mathlib4/issues/5020 instance : ConcreteCategory MeasCat := by unfold MeasCat infer_instance instance : Inhabited MeasCat := ⟨MeasCat.of Empty⟩ -- This was a global instance prior to #13170. We may experiment with removing it. attribute [local instance] ConcreteCategory.instFunLike /-- `Measure X` is the measurable space of measures over the measurable space `X`. It is the weakest measurable space, s.t. `fun μ ↦ μ s` is measurable for all measurable sets `s` in `X`. An important purpose is to assign a monadic structure on it, the Giry monad. In the Giry monad, the pure values are the Dirac measure, and the bind operation maps to the integral: `(μ >>= ν) s = ∫ x. (ν x) s dμ`. In probability theory, the `MeasCat`-morphisms `X → Prob X` are (sub-)Markov kernels (here `Prob` is the restriction of `Measure` to (sub-)probability space.) -/ def Measure : MeasCat ⥤ MeasCat where obj X := ⟨@MeasureTheory.Measure X.1 X.2, inferInstance⟩ map f := ⟨Measure.map (⇑f), Measure.measurable_map f.1 f.2⟩ map_id := fun ⟨α, I⟩ => Subtype.eq <| funext fun μ => @Measure.map_id α I μ map_comp := fun ⟨_, hf⟩ ⟨_, hg⟩ => Subtype.eq <| funext fun _ => (Measure.map_map hg hf).symm /-- The Giry monad, i.e. the monadic structure associated with `Measure`. -/ def Giry : CategoryTheory.Monad MeasCat where toFunctor := Measure η := { app := fun X => ⟨@Measure.dirac X.1 X.2, Measure.measurable_dirac⟩ naturality := fun _ _ ⟨_, hf⟩ => Subtype.eq <| funext fun a => (Measure.map_dirac hf a).symm } μ := { app := fun X => ⟨@Measure.join X.1 X.2, Measure.measurable_join⟩ naturality := fun _ _ ⟨_, hf⟩ => Subtype.eq <| funext fun μ => Measure.join_map_map hf μ } assoc _ := Subtype.eq <| funext fun _ => Measure.join_map_join _ left_unit _ := Subtype.eq <| funext fun _ => Measure.join_dirac _ right_unit _ := Subtype.eq <| funext fun _ => Measure.join_map_dirac _ /-- An example for an algebra on `Measure`: the nonnegative Lebesgue integral is a hom, behaving nicely under the monad operations. -/ def Integral : Giry.Algebra where A := MeasCat.of ℝ≥0∞ a := ⟨fun m : MeasureTheory.Measure ℝ≥0∞ ↦ ∫⁻ x, x ∂m, Measure.measurable_lintegral measurable_id⟩ unit := Subtype.eq <| funext fun r : ℝ≥0∞ => lintegral_dirac' _ measurable_id assoc := Subtype.eq <| funext fun μ : MeasureTheory.Measure (MeasureTheory.Measure ℝ≥0∞) => show ∫⁻ x, x ∂μ.join = ∫⁻ x, x ∂Measure.map (fun m => ∫⁻ x, x ∂m) μ by rw [Measure.lintegral_join, lintegral_map] <;> apply_rules [measurable_id, Measure.measurable_lintegral] end MeasCat instance TopCat.hasForgetToMeasCat : HasForget₂ TopCat.{u} MeasCat.{u} := BundledHom.mkHasForget₂ borel (fun f => ⟨f.1, f.2.borel_measurable⟩) (fun _ => rfl) /-- The Borel functor, the canonical embedding of topological spaces into measurable spaces. -/ abbrev Borel : TopCat.{u} ⥤ MeasCat.{u} := forget₂ TopCat.{u} MeasCat.{u}
MeasureTheory\Constructions\Cylinders.lean
/- Copyright (c) 2023 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Peter Pfaffelhuber -/ import Mathlib.MeasureTheory.PiSystem import Mathlib.Order.OmegaCompletePartialOrder import Mathlib.Topology.Constructions import Mathlib.MeasureTheory.MeasurableSpace.Basic /-! # π-systems of cylinders and square cylinders The instance `MeasurableSpace.pi` on `∀ i, α i`, where each `α i` has a `MeasurableSpace` `m i`, is defined as `⨆ i, (m i).comap (fun a => a i)`. That is, a function `g : β → ∀ i, α i` is measurable iff for all `i`, the function `b ↦ g b i` is measurable. We define two π-systems generating `MeasurableSpace.pi`, cylinders and square cylinders. ## Main definitions Given a finite set `s` of indices, a cylinder is the product of a set of `∀ i : s, α i` and of `univ` on the other indices. A square cylinder is a cylinder for which the set on `∀ i : s, α i` is a product set. * `cylinder s S`: cylinder with base set `S : Set (∀ i : s, α i)` where `s` is a `Finset` * `squareCylinders C` with `C : ∀ i, Set (Set (α i))`: set of all square cylinders such that for all `i` in the finset defining the box, the projection to `α i` belongs to `C i`. The main application of this is with `C i = {s : Set (α i) | MeasurableSet s}`. * `measurableCylinders`: set of all cylinders with measurable base sets. ## Main statements * `generateFrom_squareCylinders`: square cylinders formed from measurable sets generate the product σ-algebra * `generateFrom_measurableCylinders`: cylinders formed from measurable sets generate the product σ-algebra -/ open Set namespace MeasureTheory variable {ι : Type _} {α : ι → Type _} section squareCylinders /-- Given a finite set `s` of indices, a square cylinder is the product of a set `S` of `∀ i : s, α i` and of `univ` on the other indices. The set `S` is a product of sets `t i` such that for all `i : s`, `t i ∈ C i`. `squareCylinders` is the set of all such squareCylinders. -/ def squareCylinders (C : ∀ i, Set (Set (α i))) : Set (Set (∀ i, α i)) := {S | ∃ s : Finset ι, ∃ t ∈ univ.pi C, S = (s : Set ι).pi t} theorem squareCylinders_eq_iUnion_image (C : ∀ i, Set (Set (α i))) : squareCylinders C = ⋃ s : Finset ι, (fun t ↦ (s : Set ι).pi t) '' univ.pi C := by ext1 f simp only [squareCylinders, mem_iUnion, mem_image, mem_univ_pi, exists_prop, mem_setOf_eq, eq_comm (a := f)] theorem isPiSystem_squareCylinders {C : ∀ i, Set (Set (α i))} (hC : ∀ i, IsPiSystem (C i)) (hC_univ : ∀ i, univ ∈ C i) : IsPiSystem (squareCylinders C) := by rintro S₁ ⟨s₁, t₁, h₁, rfl⟩ S₂ ⟨s₂, t₂, h₂, rfl⟩ hst_nonempty classical let t₁' := s₁.piecewise t₁ (fun i ↦ univ) let t₂' := s₂.piecewise t₂ (fun i ↦ univ) have h1 : ∀ i ∈ (s₁ : Set ι), t₁ i = t₁' i := fun i hi ↦ (Finset.piecewise_eq_of_mem _ _ _ hi).symm have h1' : ∀ i ∉ (s₁ : Set ι), t₁' i = univ := fun i hi ↦ Finset.piecewise_eq_of_not_mem _ _ _ hi have h2 : ∀ i ∈ (s₂ : Set ι), t₂ i = t₂' i := fun i hi ↦ (Finset.piecewise_eq_of_mem _ _ _ hi).symm have h2' : ∀ i ∉ (s₂ : Set ι), t₂' i = univ := fun i hi ↦ Finset.piecewise_eq_of_not_mem _ _ _ hi rw [Set.pi_congr rfl h1, Set.pi_congr rfl h2, ← union_pi_inter h1' h2'] refine ⟨s₁ ∪ s₂, fun i ↦ t₁' i ∩ t₂' i, ?_, ?_⟩ · rw [mem_univ_pi] intro i have : (t₁' i ∩ t₂' i).Nonempty := by obtain ⟨f, hf⟩ := hst_nonempty rw [Set.pi_congr rfl h1, Set.pi_congr rfl h2, mem_inter_iff, mem_pi, mem_pi] at hf refine ⟨f i, ⟨?_, ?_⟩⟩ · by_cases hi₁ : i ∈ s₁ · exact hf.1 i hi₁ · rw [h1' i hi₁] exact mem_univ _ · by_cases hi₂ : i ∈ s₂ · exact hf.2 i hi₂ · rw [h2' i hi₂] exact mem_univ _ refine hC i _ ?_ _ ?_ this · by_cases hi₁ : i ∈ s₁ · rw [← h1 i hi₁] exact h₁ i (mem_univ _) · rw [h1' i hi₁] exact hC_univ i · by_cases hi₂ : i ∈ s₂ · rw [← h2 i hi₂] exact h₂ i (mem_univ _) · rw [h2' i hi₂] exact hC_univ i · rw [Finset.coe_union] theorem comap_eval_le_generateFrom_squareCylinders_singleton (α : ι → Type*) [m : ∀ i, MeasurableSpace (α i)] (i : ι) : MeasurableSpace.comap (Function.eval i) (m i) ≤ MeasurableSpace.generateFrom ((fun t ↦ ({i} : Set ι).pi t) '' univ.pi fun i ↦ {s : Set (α i) | MeasurableSet s}) := by simp only [Function.eval, singleton_pi] rw [MeasurableSpace.comap_eq_generateFrom] refine MeasurableSpace.generateFrom_mono fun S ↦ ?_ simp only [mem_setOf_eq, mem_image, mem_univ_pi, forall_exists_index, and_imp] intro t ht h classical refine ⟨fun j ↦ if hji : j = i then by convert t else univ, fun j ↦ ?_, ?_⟩ · by_cases hji : j = i · simp only [hji, eq_self_iff_true, eq_mpr_eq_cast, dif_pos] convert ht simp only [id_eq, cast_heq] · simp only [hji, not_false_iff, dif_neg, MeasurableSet.univ] · simp only [id_eq, eq_mpr_eq_cast, ← h] ext1 x simp only [singleton_pi, Function.eval, cast_eq, dite_eq_ite, ite_true, mem_preimage] /-- The square cylinders formed from measurable sets generate the product σ-algebra. -/ theorem generateFrom_squareCylinders [∀ i, MeasurableSpace (α i)] : MeasurableSpace.generateFrom (squareCylinders fun i ↦ {s : Set (α i) | MeasurableSet s}) = MeasurableSpace.pi := by apply le_antisymm · rw [MeasurableSpace.generateFrom_le_iff] rintro S ⟨s, t, h, rfl⟩ simp only [mem_univ_pi, mem_setOf_eq] at h exact MeasurableSet.pi (Finset.countable_toSet _) (fun i _ ↦ h i) · refine iSup_le fun i ↦ ?_ refine (comap_eval_le_generateFrom_squareCylinders_singleton α i).trans ?_ refine MeasurableSpace.generateFrom_mono ?_ rw [← Finset.coe_singleton, squareCylinders_eq_iUnion_image] exact subset_iUnion (fun (s : Finset ι) ↦ (fun t : ∀ i, Set (α i) ↦ (s : Set ι).pi t) '' univ.pi (fun i ↦ setOf MeasurableSet)) ({i} : Finset ι) end squareCylinders section cylinder /-- Given a finite set `s` of indices, a cylinder is the preimage of a set `S` of `∀ i : s, α i` by the projection from `∀ i, α i` to `∀ i : s, α i`. -/ def cylinder (s : Finset ι) (S : Set (∀ i : s, α i)) : Set (∀ i, α i) := (fun (f : ∀ i, α i) (i : s) ↦ f i) ⁻¹' S @[simp] theorem mem_cylinder (s : Finset ι) (S : Set (∀ i : s, α i)) (f : ∀ i, α i) : f ∈ cylinder s S ↔ (fun i : s ↦ f i) ∈ S := mem_preimage @[simp] theorem cylinder_empty (s : Finset ι) : cylinder s (∅ : Set (∀ i : s, α i)) = ∅ := by rw [cylinder, preimage_empty] @[simp] theorem cylinder_univ (s : Finset ι) : cylinder s (univ : Set (∀ i : s, α i)) = univ := by rw [cylinder, preimage_univ] @[simp] theorem cylinder_eq_empty_iff [h_nonempty : Nonempty (∀ i, α i)] (s : Finset ι) (S : Set (∀ i : s, α i)) : cylinder s S = ∅ ↔ S = ∅ := by refine ⟨fun h ↦ ?_, fun h ↦ by (rw [h]; exact cylinder_empty _)⟩ by_contra hS rw [← Ne, ← nonempty_iff_ne_empty] at hS let f := hS.some have hf : f ∈ S := hS.choose_spec classical let f' : ∀ i, α i := fun i ↦ if hi : i ∈ s then f ⟨i, hi⟩ else h_nonempty.some i have hf' : f' ∈ cylinder s S := by rw [mem_cylinder] simpa only [f', Finset.coe_mem, dif_pos] rw [h] at hf' exact not_mem_empty _ hf' theorem inter_cylinder (s₁ s₂ : Finset ι) (S₁ : Set (∀ i : s₁, α i)) (S₂ : Set (∀ i : s₂, α i)) [DecidableEq ι] : cylinder s₁ S₁ ∩ cylinder s₂ S₂ = cylinder (s₁ ∪ s₂) ((fun f ↦ fun j : s₁ ↦ f ⟨j, Finset.mem_union_left s₂ j.prop⟩) ⁻¹' S₁ ∩ (fun f ↦ fun j : s₂ ↦ f ⟨j, Finset.mem_union_right s₁ j.prop⟩) ⁻¹' S₂) := by ext1 f; simp only [mem_inter_iff, mem_cylinder, mem_setOf_eq]; rfl theorem inter_cylinder_same (s : Finset ι) (S₁ : Set (∀ i : s, α i)) (S₂ : Set (∀ i : s, α i)) : cylinder s S₁ ∩ cylinder s S₂ = cylinder s (S₁ ∩ S₂) := by classical rw [inter_cylinder]; rfl theorem union_cylinder (s₁ s₂ : Finset ι) (S₁ : Set (∀ i : s₁, α i)) (S₂ : Set (∀ i : s₂, α i)) [DecidableEq ι] : cylinder s₁ S₁ ∪ cylinder s₂ S₂ = cylinder (s₁ ∪ s₂) ((fun f ↦ fun j : s₁ ↦ f ⟨j, Finset.mem_union_left s₂ j.prop⟩) ⁻¹' S₁ ∪ (fun f ↦ fun j : s₂ ↦ f ⟨j, Finset.mem_union_right s₁ j.prop⟩) ⁻¹' S₂) := by ext1 f; simp only [mem_union, mem_cylinder, mem_setOf_eq]; rfl theorem union_cylinder_same (s : Finset ι) (S₁ : Set (∀ i : s, α i)) (S₂ : Set (∀ i : s, α i)) : cylinder s S₁ ∪ cylinder s S₂ = cylinder s (S₁ ∪ S₂) := by classical rw [union_cylinder]; rfl theorem compl_cylinder (s : Finset ι) (S : Set (∀ i : s, α i)) : (cylinder s S)ᶜ = cylinder s (Sᶜ) := by ext1 f; simp only [mem_compl_iff, mem_cylinder] theorem diff_cylinder_same (s : Finset ι) (S T : Set (∀ i : s, α i)) : cylinder s S \ cylinder s T = cylinder s (S \ T) := by ext1 f; simp only [mem_diff, mem_cylinder] theorem eq_of_cylinder_eq_of_subset [h_nonempty : Nonempty (∀ i, α i)] {I J : Finset ι} {S : Set (∀ i : I, α i)} {T : Set (∀ i : J, α i)} (h_eq : cylinder I S = cylinder J T) (hJI : J ⊆ I) : S = (fun f : ∀ i : I, α i ↦ fun j : J ↦ f ⟨j, hJI j.prop⟩) ⁻¹' T := by rw [Set.ext_iff] at h_eq simp only [mem_cylinder] at h_eq ext1 f simp only [mem_preimage] classical specialize h_eq fun i ↦ if hi : i ∈ I then f ⟨i, hi⟩ else h_nonempty.some i have h_mem : ∀ j : J, ↑j ∈ I := fun j ↦ hJI j.prop simp only [Finset.coe_mem, dite_true, h_mem] at h_eq exact h_eq theorem cylinder_eq_cylinder_union [DecidableEq ι] (I : Finset ι) (S : Set (∀ i : I, α i)) (J : Finset ι) : cylinder I S = cylinder (I ∪ J) ((fun f ↦ fun j : I ↦ f ⟨j, Finset.mem_union_left J j.prop⟩) ⁻¹' S) := by ext1 f; simp only [mem_cylinder, mem_preimage] theorem disjoint_cylinder_iff [Nonempty (∀ i, α i)] {s t : Finset ι} {S : Set (∀ i : s, α i)} {T : Set (∀ i : t, α i)} [DecidableEq ι] : Disjoint (cylinder s S) (cylinder t T) ↔ Disjoint ((fun f : ∀ i : (s ∪ t : Finset ι), α i ↦ fun j : s ↦ f ⟨j, Finset.mem_union_left t j.prop⟩) ⁻¹' S) ((fun f ↦ fun j : t ↦ f ⟨j, Finset.mem_union_right s j.prop⟩) ⁻¹' T) := by simp_rw [Set.disjoint_iff, subset_empty_iff, inter_cylinder, cylinder_eq_empty_iff] theorem IsClosed.cylinder [∀ i, TopologicalSpace (α i)] (s : Finset ι) {S : Set (∀ i : s, α i)} (hs : IsClosed S) : IsClosed (cylinder s S) := hs.preimage (continuous_pi fun _ ↦ continuous_apply _) theorem _root_.MeasurableSet.cylinder [∀ i, MeasurableSpace (α i)] (s : Finset ι) {S : Set (∀ i : s, α i)} (hS : MeasurableSet S) : MeasurableSet (cylinder s S) := measurable_pi_lambda _ (fun _ ↦ measurable_pi_apply _) hS end cylinder section cylinders /-- Given a finite set `s` of indices, a cylinder is the preimage of a set `S` of `∀ i : s, α i` by the projection from `∀ i, α i` to `∀ i : s, α i`. `measurableCylinders` is the set of all cylinders with measurable base `S`. -/ def measurableCylinders (α : ι → Type*) [∀ i, MeasurableSpace (α i)] : Set (Set (∀ i, α i)) := ⋃ (s) (S) (_ : MeasurableSet S), {cylinder s S} theorem empty_mem_measurableCylinders (α : ι → Type*) [∀ i, MeasurableSpace (α i)] : ∅ ∈ measurableCylinders α := by simp_rw [measurableCylinders, mem_iUnion, mem_singleton_iff] exact ⟨∅, ∅, MeasurableSet.empty, (cylinder_empty _).symm⟩ variable [∀ i, MeasurableSpace (α i)] {s t : Set (∀ i, α i)} @[simp] theorem mem_measurableCylinders (t : Set (∀ i, α i)) : t ∈ measurableCylinders α ↔ ∃ s S, MeasurableSet S ∧ t = cylinder s S := by simp_rw [measurableCylinders, mem_iUnion, exists_prop, mem_singleton_iff] /-- A finset `s` such that `t = cylinder s S`. `S` is given by `measurableCylinders.set`. -/ noncomputable def measurableCylinders.finset (ht : t ∈ measurableCylinders α) : Finset ι := ((mem_measurableCylinders t).mp ht).choose /-- A set `S` such that `t = cylinder s S`. `s` is given by `measurableCylinders.finset`. -/ def measurableCylinders.set (ht : t ∈ measurableCylinders α) : Set (∀ i : measurableCylinders.finset ht, α i) := ((mem_measurableCylinders t).mp ht).choose_spec.choose theorem measurableCylinders.measurableSet (ht : t ∈ measurableCylinders α) : MeasurableSet (measurableCylinders.set ht) := ((mem_measurableCylinders t).mp ht).choose_spec.choose_spec.left theorem measurableCylinders.eq_cylinder (ht : t ∈ measurableCylinders α) : t = cylinder (measurableCylinders.finset ht) (measurableCylinders.set ht) := ((mem_measurableCylinders t).mp ht).choose_spec.choose_spec.right theorem cylinder_mem_measurableCylinders (s : Finset ι) (S : Set (∀ i : s, α i)) (hS : MeasurableSet S) : cylinder s S ∈ measurableCylinders α := by rw [mem_measurableCylinders]; exact ⟨s, S, hS, rfl⟩ theorem inter_mem_measurableCylinders (hs : s ∈ measurableCylinders α) (ht : t ∈ measurableCylinders α) : s ∩ t ∈ measurableCylinders α := by rw [mem_measurableCylinders] at * obtain ⟨s₁, S₁, hS₁, rfl⟩ := hs obtain ⟨s₂, S₂, hS₂, rfl⟩ := ht classical refine ⟨s₁ ∪ s₂, (fun f ↦ (fun i ↦ f ⟨i, Finset.mem_union_left s₂ i.prop⟩ : ∀ i : s₁, α i)) ⁻¹' S₁ ∩ {f | (fun i ↦ f ⟨i, Finset.mem_union_right s₁ i.prop⟩ : ∀ i : s₂, α i) ∈ S₂}, ?_, ?_⟩ · refine MeasurableSet.inter ?_ ?_ · exact measurable_pi_lambda _ (fun _ ↦ measurable_pi_apply _) hS₁ · exact measurable_pi_lambda _ (fun _ ↦ measurable_pi_apply _) hS₂ · exact inter_cylinder _ _ _ _ theorem isPiSystem_measurableCylinders : IsPiSystem (measurableCylinders α) := fun _ hS _ hT _ ↦ inter_mem_measurableCylinders hS hT theorem compl_mem_measurableCylinders (hs : s ∈ measurableCylinders α) : sᶜ ∈ measurableCylinders α := by rw [mem_measurableCylinders] at hs ⊢ obtain ⟨s, S, hS, rfl⟩ := hs refine ⟨s, Sᶜ, hS.compl, ?_⟩ rw [compl_cylinder] theorem univ_mem_measurableCylinders (α : ι → Type*) [∀ i, MeasurableSpace (α i)] : Set.univ ∈ measurableCylinders α := by rw [← compl_empty]; exact compl_mem_measurableCylinders (empty_mem_measurableCylinders α) theorem union_mem_measurableCylinders (hs : s ∈ measurableCylinders α) (ht : t ∈ measurableCylinders α) : s ∪ t ∈ measurableCylinders α := by rw [union_eq_compl_compl_inter_compl] exact compl_mem_measurableCylinders (inter_mem_measurableCylinders (compl_mem_measurableCylinders hs) (compl_mem_measurableCylinders ht)) theorem diff_mem_measurableCylinders (hs : s ∈ measurableCylinders α) (ht : t ∈ measurableCylinders α) : s \ t ∈ measurableCylinders α := by rw [diff_eq_compl_inter] exact inter_mem_measurableCylinders (compl_mem_measurableCylinders ht) hs /-- The measurable cylinders generate the product σ-algebra. -/ theorem generateFrom_measurableCylinders : MeasurableSpace.generateFrom (measurableCylinders α) = MeasurableSpace.pi := by apply le_antisymm · refine MeasurableSpace.generateFrom_le (fun S hS ↦ ?_) obtain ⟨s, S, hSm, rfl⟩ := (mem_measurableCylinders _).mp hS exact hSm.cylinder · refine iSup_le fun i ↦ ?_ refine (comap_eval_le_generateFrom_squareCylinders_singleton α i).trans ?_ refine MeasurableSpace.generateFrom_mono (fun x ↦ ?_) simp only [singleton_pi, Function.eval, mem_image, mem_pi, mem_univ, mem_setOf_eq, forall_true_left, mem_measurableCylinders, exists_prop, forall_exists_index, and_imp] rintro t ht rfl refine ⟨{i}, {f | f ⟨i, Finset.mem_singleton_self i⟩ ∈ t i}, measurable_pi_apply _ (ht i), ?_⟩ ext1 x simp only [singleton_pi, Function.eval, mem_preimage, mem_cylinder, mem_setOf_eq] end cylinders end MeasureTheory
MeasureTheory\Constructions\EventuallyMeasurable.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.MeasureTheory.MeasurableSpace.Defs import Mathlib.Order.Filter.CountableInter /-! # Measurability modulo a filter In this file we consider the general notion of measurability modulo a σ-filter. Two important instances of this construction are null-measurability with respect to a measure, where the filter is the collection of co-null sets, and Baire-measurability with respect to a topology, where the filter is the collection of comeager (residual) sets. (not to be confused with measurability with respect to the sigma algebra of Baire sets, which is sometimes also called this.) TODO: Implement the latter. ## Main definitions * `EventuallyMeasurableSpace`: A `MeasurableSpace` on a type `α` consisting of sets which are `Filter.EventuallyEq` to a measurable set with respect to a given `CountableInterFilter` on `α` and `MeasurableSpace` on `α`. * `EventuallyMeasurableSet`: A `Prop` for sets which are measurable with respect to some `EventuallyMeasurableSpace`. * `EventuallyMeasurable`: A `Prop` for functions which are measurable with respect to some `EventuallyMeasurableSpace` on the domain. -/ open Filter Set MeasurableSpace variable {α : Type*} (m : MeasurableSpace α) (l : Filter α) [CountableInterFilter l] {s t : Set α} /-- The `MeasurableSpace` of sets which are measurable with respect to a given σ-algebra `m` on `α`, modulo a given σ-filter `l` on `α`. -/ def EventuallyMeasurableSpace : MeasurableSpace α where MeasurableSet' s := ∃ t, MeasurableSet t ∧ s =ᶠ[l] t measurableSet_empty := ⟨∅, MeasurableSet.empty, EventuallyEq.refl _ _ ⟩ measurableSet_compl := fun s ⟨t, ht, hts⟩ => ⟨tᶜ, ht.compl, hts.compl⟩ measurableSet_iUnion s hs := by choose t ht hts using hs exact ⟨⋃ i, t i, MeasurableSet.iUnion ht, EventuallyEq.countable_iUnion hts⟩ /-- We say a set `s` is an `EventuallyMeasurableSet` with respect to a given σ-algebra `m` and σ-filter `l` if it differs from a set in `m` by a set in the dual ideal of `l`. -/ def EventuallyMeasurableSet (s : Set α) : Prop := @MeasurableSet _ (EventuallyMeasurableSpace m l) s variable {l m} theorem MeasurableSet.eventuallyMeasurableSet (hs : MeasurableSet s) : EventuallyMeasurableSet m l s := ⟨s, hs, EventuallyEq.refl _ _⟩ theorem EventuallyMeasurableSpace.measurable_le : m ≤ EventuallyMeasurableSpace m l := fun _ hs => hs.eventuallyMeasurableSet theorem eventuallyMeasurableSet_of_mem_filter (hs : s ∈ l) : EventuallyMeasurableSet m l s := ⟨univ, MeasurableSet.univ, eventuallyEq_univ.mpr hs⟩ /-- A set which is `EventuallyEq` to an `EventuallyMeasurableSet` is an `EventuallyMeasurableSet`. -/ theorem EventuallyMeasurableSet.congr (ht : EventuallyMeasurableSet m l t) (hst : s =ᶠ[l] t) : EventuallyMeasurableSet m l s := by rcases ht with ⟨t', ht', htt'⟩ exact ⟨t', ht', hst.trans htt'⟩ section instances namespace EventuallyMeasurableSpace instance measurableSingleton [MeasurableSingletonClass α] : @MeasurableSingletonClass α (EventuallyMeasurableSpace m l) := @MeasurableSingletonClass.mk _ (_) $ fun x => (MeasurableSet.singleton x).eventuallyMeasurableSet end EventuallyMeasurableSpace end instances section EventuallyMeasurable open Function variable (m l) {β γ : Type*} [MeasurableSpace β] [MeasurableSpace γ] /-- We say a function is `EventuallyMeasurable` with respect to a given σ-algebra `m` and σ-filter `l` if the preimage of any measurable set is equal to some `m`-measurable set modulo `l`. Warning: This is not always the same as being equal to some `m`-measurable function modulo `l`. In general it is weaker. See `Measurable.eventuallyMeasurable_of_eventuallyEq`. *TODO*: Add lemmas about when these are equivalent. -/ def EventuallyMeasurable (f : α → β) : Prop := @Measurable _ _ (EventuallyMeasurableSpace m l) _ f variable {m l} {f g : α → β} {h : β → γ} theorem Measurable.eventuallyMeasurable (hf : Measurable f) : EventuallyMeasurable m l f := hf.le EventuallyMeasurableSpace.measurable_le theorem Measurable.comp_eventuallyMeasurable (hh : Measurable h) (hf : EventuallyMeasurable m l f) : EventuallyMeasurable m l (h ∘ f) := hh.comp hf /-- A function which is `EventuallyEq` to some `EventuallyMeasurable` function is `EventuallyMeasurable`.-/ theorem EventuallyMeasurable.congr (hf : EventuallyMeasurable m l f) (hgf : g =ᶠ[l] f) : EventuallyMeasurable m l g := fun _ hs => EventuallyMeasurableSet.congr (hf hs) (hgf.preimage _) /-- A function which is `EventuallyEq` to some `Measurable` function is `EventuallyMeasurable`.-/ theorem Measurable.eventuallyMeasurable_of_eventuallyEq (hf : Measurable f) (hgf : g =ᶠ[l] f) : EventuallyMeasurable m l g := hf.eventuallyMeasurable.congr hgf end EventuallyMeasurable
MeasureTheory\Constructions\HaarToSphere.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Algebra.Order.Pointwise import Mathlib.Analysis.NormedSpace.SphereNormEquiv import Mathlib.Analysis.SpecialFunctions.Integrals import Mathlib.MeasureTheory.Constructions.Prod.Integral import Mathlib.MeasureTheory.Measure.Lebesgue.EqHaar /-! # Generalized polar coordinate change Consider an `n`-dimensional normed space `E` and an additive Haar measure `μ` on `E`. Then `μ.toSphere` is the measure on the unit sphere such that `μ.toSphere s` equals `n • μ (Set.Ioo 0 1 • s)`. If `n ≠ 0`, then `μ` can be represented (up to `homeomorphUnitSphereProd`) as the product of `μ.toSphere` and the Lebesgue measure on `(0, +∞)` taken with density `fun r ↦ r ^ n`. One can think about this fact as a version of polar coordinate change formula for a general nontrivial normed space. -/ open Set Function Metric MeasurableSpace intervalIntegral open scoped Pointwise ENNReal NNReal local notation "dim" => FiniteDimensional.finrank ℝ noncomputable section namespace MeasureTheory variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] namespace Measure /-- If `μ` is an additive Haar measure on a normed space `E`, then `μ.toSphere` is the measure on the unit sphere in `E` such that `μ.toSphere s = FiniteDimensional.finrank ℝ E • μ (Set.Ioo (0 : ℝ) 1 • s)`. -/ def toSphere (μ : Measure E) : Measure (sphere (0 : E) 1) := dim E • ((μ.comap (Subtype.val ∘ (homeomorphUnitSphereProd E).symm)).restrict (univ ×ˢ Iio ⟨1, mem_Ioi.2 one_pos⟩)).fst variable (μ : Measure E) theorem toSphere_apply_aux (s : Set (sphere (0 : E) 1)) (r : Ioi (0 : ℝ)) : μ ((↑) '' (homeomorphUnitSphereProd E ⁻¹' s ×ˢ Iio r)) = μ (Ioo (0 : ℝ) r • ((↑) '' s)) := by rw [← image2_smul, image2_image_right, ← Homeomorph.image_symm, image_image, ← image_subtype_val_Ioi_Iio, image2_image_left, image2_swap, ← image_prod] rfl theorem toSphere_apply' {s : Set (sphere (0 : E) 1)} (hs : MeasurableSet s) : μ.toSphere s = dim E * μ (Ioo (0 : ℝ) 1 • ((↑) '' s)) := by rw [toSphere, smul_apply, fst_apply hs, restrict_apply (measurable_fst hs), ((MeasurableEmbedding.subtype_coe (measurableSet_singleton _).compl).comp (Homeomorph.measurableEmbedding _)).comap_apply, image_comp, Homeomorph.image_symm, univ_prod, ← Set.prod_eq, nsmul_eq_mul, toSphere_apply_aux] theorem toSphere_apply_univ' : μ.toSphere univ = dim E * μ (ball 0 1 \ {0}) := by rw [μ.toSphere_apply' .univ, image_univ, Subtype.range_coe, Ioo_smul_sphere_zero] <;> simp variable [μ.IsAddHaarMeasure] @[simp] theorem toSphere_apply_univ : μ.toSphere univ = dim E * μ (ball 0 1) := by nontriviality E rw [toSphere_apply_univ', measure_diff_null (measure_singleton _)] instance : IsFiniteMeasure μ.toSphere where measure_univ_lt_top := by rw [toSphere_apply_univ'] exact ENNReal.mul_lt_top (ENNReal.natCast_ne_top _) <| ne_top_of_le_ne_top measure_ball_lt_top.ne <| measure_mono diff_subset /-- The measure on `(0, +∞)` that has density `(· ^ n)` with respect to the Lebesgue measure. -/ def volumeIoiPow (n : ℕ) : Measure (Ioi (0 : ℝ)) := .withDensity (.comap Subtype.val volume) fun r ↦ .ofReal (r.1 ^ n) lemma volumeIoiPow_apply_Iio (n : ℕ) (x : Ioi (0 : ℝ)) : volumeIoiPow n (Iio x) = ENNReal.ofReal (x.1 ^ (n + 1) / (n + 1)) := by have hr₀ : 0 ≤ x.1 := le_of_lt x.2 rw [volumeIoiPow, withDensity_apply _ measurableSet_Iio, setLIntegral_subtype measurableSet_Ioi _ fun a : ℝ ↦ .ofReal (a ^ n), image_subtype_val_Ioi_Iio, restrict_congr_set Ioo_ae_eq_Ioc, ← ofReal_integral_eq_lintegral_ofReal (intervalIntegrable_pow _).1, ← integral_of_le hr₀] · simp · filter_upwards [ae_restrict_mem measurableSet_Ioc] with y hy exact pow_nonneg hy.1.le _ /-- The intervals `(0, k + 1)` have finite measure `MeasureTheory.Measure.volumeIoiPow _` and cover the whole open ray `(0, +∞)`. -/ def finiteSpanningSetsIn_volumeIoiPow_range_Iio (n : ℕ) : FiniteSpanningSetsIn (volumeIoiPow n) (range Iio) where set k := Iio ⟨k + 1, mem_Ioi.2 k.cast_add_one_pos⟩ set_mem k := mem_range_self _ finite k := by simp [volumeIoiPow_apply_Iio] spanning := iUnion_eq_univ_iff.2 fun x ↦ ⟨⌊x.1⌋₊, Nat.lt_floor_add_one x.1⟩ instance (n : ℕ) : SigmaFinite (volumeIoiPow n) := (finiteSpanningSetsIn_volumeIoiPow_range_Iio n).sigmaFinite /-- The homeomorphism `homeomorphUnitSphereProd E` sends an additive Haar measure `μ` to the product of `μ.toSphere` and `MeasureTheory.Measure.volumeIoiPow (dim E - 1)`, where `dim E = FiniteDimensional.finrank ℝ E` is the dimension of `E`. -/ theorem measurePreserving_homeomorphUnitSphereProd : MeasurePreserving (homeomorphUnitSphereProd E) (μ.comap (↑)) (μ.toSphere.prod (volumeIoiPow (dim E - 1))) := by nontriviality E refine ⟨(homeomorphUnitSphereProd E).measurable, .symm ?_⟩ refine prod_eq_generateFrom generateFrom_measurableSet ((borel_eq_generateFrom_Iio _).symm.trans BorelSpace.measurable_eq.symm) isPiSystem_measurableSet isPiSystem_Iio μ.toSphere.toFiniteSpanningSetsIn (finiteSpanningSetsIn_volumeIoiPow_range_Iio _) fun s hs ↦ forall_mem_range.2 fun r ↦ ?_ have : Ioo (0 : ℝ) r = r.1 • Ioo (0 : ℝ) 1 := by rw [LinearOrderedField.smul_Ioo r.2.out, smul_zero, smul_eq_mul, mul_one] have hpos : 0 < dim E := FiniteDimensional.finrank_pos rw [(Homeomorph.measurableEmbedding _).map_apply, toSphere_apply' _ hs, volumeIoiPow_apply_Iio, comap_subtype_coe_apply (measurableSet_singleton _).compl, toSphere_apply_aux, this, smul_assoc, μ.addHaar_smul_of_nonneg r.2.out.le, Nat.sub_add_cancel hpos, Nat.cast_pred hpos, sub_add_cancel, mul_right_comm, ← ENNReal.ofReal_natCast, ← ENNReal.ofReal_mul, mul_div_cancel₀] exacts [(Nat.cast_pos.2 hpos).ne', Nat.cast_nonneg _] end Measure variable {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] [Nontrivial E] (μ : Measure E) [μ.IsAddHaarMeasure] lemma integral_fun_norm_addHaar (f : ℝ → F) : ∫ x, f (‖x‖) ∂μ = dim E • (μ (ball 0 1)).toReal • ∫ y in Ioi (0 : ℝ), y ^ (dim E - 1) • f y := calc ∫ x, f (‖x‖) ∂μ = ∫ x : ({(0)}ᶜ : Set E), f (‖x.1‖) ∂(μ.comap (↑)) := by rw [integral_subtype_comap (measurableSet_singleton _).compl fun x ↦ f (‖x‖), restrict_compl_singleton] _ = ∫ x : sphere (0 : E) 1 × Ioi (0 : ℝ), f x.2 ∂μ.toSphere.prod (.volumeIoiPow (dim E - 1)) := μ.measurePreserving_homeomorphUnitSphereProd.integral_comp (Homeomorph.measurableEmbedding _) (f ∘ Subtype.val ∘ Prod.snd) _ = (μ.toSphere univ).toReal • ∫ x : Ioi (0 : ℝ), f x ∂.volumeIoiPow (dim E - 1) := integral_fun_snd (f ∘ Subtype.val) _ = _ := by simp only [Measure.volumeIoiPow, ENNReal.ofReal] rw [integral_withDensity_eq_integral_smul, μ.toSphere_apply_univ, ENNReal.toReal_mul, ENNReal.toReal_nat, ← nsmul_eq_mul, smul_assoc, integral_subtype_comap measurableSet_Ioi fun a ↦ Real.toNNReal (a ^ (dim E - 1)) • f a, setIntegral_congr measurableSet_Ioi fun x hx ↦ ?_] · rw [NNReal.smul_def, Real.coe_toNNReal _ (pow_nonneg hx.out.le _)] · exact (measurable_subtype_coe.pow_const _).real_toNNReal end MeasureTheory
MeasureTheory\Constructions\Pi.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.MeasureTheory.Constructions.Prod.Basic import Mathlib.MeasureTheory.Group.Measure import Mathlib.Topology.Constructions /-! # Product measures In this file we define and prove properties about finite products of measures (and at some point, countable products of measures). ## Main definition * `MeasureTheory.Measure.pi`: The product of finitely many σ-finite measures. Given `μ : (i : ι) → Measure (α i)` for `[Fintype ι]` it has type `Measure ((i : ι) → α i)`. To apply Fubini's theorem or Tonelli's theorem along some subset, we recommend using the marginal construction `MeasureTheory.lmarginal` and (todo) `MeasureTheory.marginal`. This allows you to apply the theorems without any bookkeeping with measurable equivalences. ## Implementation Notes We define `MeasureTheory.OuterMeasure.pi`, the product of finitely many outer measures, as the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{s i | i : ι}`. We then show that this induces a product of measures, called `MeasureTheory.Measure.pi`. For a collection of σ-finite measures `μ` and a collection of measurable sets `s` we show that `Measure.pi μ (pi univ s) = ∏ i, m i (s i)`. To do this, we follow the following steps: * We know that there is some ordering on `ι`, given by an element of `[Countable ι]`. * Using this, we have an equivalence `MeasurableEquiv.piMeasurableEquivTProd` between `∀ ι, α i` and an iterated product of `α i`, called `List.tprod α l` for some list `l`. * On this iterated product we can easily define a product measure `MeasureTheory.Measure.tprod` by iterating `MeasureTheory.Measure.prod` * Using the previous two steps we construct `MeasureTheory.Measure.pi'` on `(i : ι) → α i` for countable `ι`. * We know that `MeasureTheory.Measure.pi'` sends products of sets to products of measures, and since `MeasureTheory.Measure.pi` is the maximal such measure (or at least, it comes from an outer measure which is the maximal such outer measure), we get the same rule for `MeasureTheory.Measure.pi`. ## Tags finitary product measure -/ noncomputable section open Function Set MeasureTheory.OuterMeasure Filter MeasurableSpace Encodable open scoped Classical Topology ENNReal universe u v variable {ι ι' : Type*} {α : ι → Type*} /-! We start with some measurability properties -/ /-- Boxes formed by π-systems form a π-system. -/ theorem IsPiSystem.pi {C : ∀ i, Set (Set (α i))} (hC : ∀ i, IsPiSystem (C i)) : IsPiSystem (pi univ '' pi univ C) := by rintro _ ⟨s₁, hs₁, rfl⟩ _ ⟨s₂, hs₂, rfl⟩ hst rw [← pi_inter_distrib] at hst ⊢; rw [univ_pi_nonempty_iff] at hst exact mem_image_of_mem _ fun i _ => hC i _ (hs₁ i (mem_univ i)) _ (hs₂ i (mem_univ i)) (hst i) /-- Boxes form a π-system. -/ theorem isPiSystem_pi [∀ i, MeasurableSpace (α i)] : IsPiSystem (pi univ '' pi univ fun i => { s : Set (α i) | MeasurableSet s }) := IsPiSystem.pi fun _ => isPiSystem_measurableSet section Finite variable [Finite ι] [Finite ι'] /-- Boxes of countably spanning sets are countably spanning. -/ theorem IsCountablySpanning.pi {C : ∀ i, Set (Set (α i))} (hC : ∀ i, IsCountablySpanning (C i)) : IsCountablySpanning (pi univ '' pi univ C) := by choose s h1s h2s using hC cases nonempty_encodable (ι → ℕ) let e : ℕ → ι → ℕ := fun n => (@decode (ι → ℕ) _ n).iget refine ⟨fun n => Set.pi univ fun i => s i (e n i), fun n => mem_image_of_mem _ fun i _ => h1s i _, ?_⟩ simp_rw [(surjective_decode_iget (ι → ℕ)).iUnion_comp fun x => Set.pi univ fun i => s i (x i), iUnion_univ_pi s, h2s, pi_univ] /-- The product of generated σ-algebras is the one generated by boxes, if both generating sets are countably spanning. -/ theorem generateFrom_pi_eq {C : ∀ i, Set (Set (α i))} (hC : ∀ i, IsCountablySpanning (C i)) : (@MeasurableSpace.pi _ _ fun i => generateFrom (C i)) = generateFrom (pi univ '' pi univ C) := by cases nonempty_encodable ι apply le_antisymm · refine iSup_le ?_; intro i; rw [comap_generateFrom] apply generateFrom_le; rintro _ ⟨s, hs, rfl⟩ choose t h1t h2t using hC simp_rw [eval_preimage, ← h2t] rw [← @iUnion_const _ ℕ _ s] have : Set.pi univ (update (fun i' : ι => iUnion (t i')) i (⋃ _ : ℕ, s)) = Set.pi univ fun k => ⋃ j : ℕ, @update ι (fun i' => Set (α i')) _ (fun i' => t i' j) i s k := by ext; simp_rw [mem_univ_pi]; apply forall_congr'; intro i' by_cases h : i' = i · subst h; simp · rw [← Ne] at h; simp [h] rw [this, ← iUnion_univ_pi] apply MeasurableSet.iUnion intro n; apply measurableSet_generateFrom apply mem_image_of_mem; intro j _; dsimp only by_cases h : j = i · subst h; rwa [update_same] · rw [update_noteq h]; apply h1t · apply generateFrom_le; rintro _ ⟨s, hs, rfl⟩ rw [univ_pi_eq_iInter]; apply MeasurableSet.iInter; intro i apply @measurable_pi_apply _ _ (fun i => generateFrom (C i)) exact measurableSet_generateFrom (hs i (mem_univ i)) /-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D` generate the σ-algebra on `α × β`. -/ theorem generateFrom_eq_pi [h : ∀ i, MeasurableSpace (α i)] {C : ∀ i, Set (Set (α i))} (hC : ∀ i, generateFrom (C i) = h i) (h2C : ∀ i, IsCountablySpanning (C i)) : generateFrom (pi univ '' pi univ C) = MeasurableSpace.pi := by simp only [← funext hC, generateFrom_pi_eq h2C] /-- The product σ-algebra is generated from boxes, i.e. `s ×ˢ t` for sets `s : set α` and `t : set β`. -/ theorem generateFrom_pi [∀ i, MeasurableSpace (α i)] : generateFrom (pi univ '' pi univ fun i => { s : Set (α i) | MeasurableSet s }) = MeasurableSpace.pi := generateFrom_eq_pi (fun _ => generateFrom_measurableSet) fun _ => isCountablySpanning_measurableSet end Finite namespace MeasureTheory variable [Fintype ι] {m : ∀ i, OuterMeasure (α i)} /-- An upper bound for the measure in a finite product space. It is defined to by taking the image of the set under all projections, and taking the product of the measures of these images. For measurable boxes it is equal to the correct measure. -/ @[simp] def piPremeasure (m : ∀ i, OuterMeasure (α i)) (s : Set (∀ i, α i)) : ℝ≥0∞ := ∏ i, m i (eval i '' s) theorem piPremeasure_pi {s : ∀ i, Set (α i)} (hs : (pi univ s).Nonempty) : piPremeasure m (pi univ s) = ∏ i, m i (s i) := by simp [hs, piPremeasure] theorem piPremeasure_pi' {s : ∀ i, Set (α i)} : piPremeasure m (pi univ s) = ∏ i, m i (s i) := by cases isEmpty_or_nonempty ι · simp [piPremeasure] rcases (pi univ s).eq_empty_or_nonempty with h | h · rcases univ_pi_eq_empty_iff.mp h with ⟨i, hi⟩ have : ∃ i, m i (s i) = 0 := ⟨i, by simp [hi]⟩ simpa [h, Finset.card_univ, zero_pow Fintype.card_ne_zero, @eq_comm _ (0 : ℝ≥0∞), Finset.prod_eq_zero_iff, piPremeasure] · simp [h, piPremeasure] theorem piPremeasure_pi_mono {s t : Set (∀ i, α i)} (h : s ⊆ t) : piPremeasure m s ≤ piPremeasure m t := Finset.prod_le_prod' fun _ _ => measure_mono (image_subset _ h) theorem piPremeasure_pi_eval {s : Set (∀ i, α i)} : piPremeasure m (pi univ fun i => eval i '' s) = piPremeasure m s := by simp only [eval, piPremeasure_pi']; rfl namespace OuterMeasure /-- `OuterMeasure.pi m` is the finite product of the outer measures `{m i | i : ι}`. It is defined to be the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{s i | i : ι}`. -/ protected def pi (m : ∀ i, OuterMeasure (α i)) : OuterMeasure (∀ i, α i) := boundedBy (piPremeasure m) theorem pi_pi_le (m : ∀ i, OuterMeasure (α i)) (s : ∀ i, Set (α i)) : OuterMeasure.pi m (pi univ s) ≤ ∏ i, m i (s i) := by rcases (pi univ s).eq_empty_or_nonempty with h | h · simp [h] exact (boundedBy_le _).trans_eq (piPremeasure_pi h) theorem le_pi {m : ∀ i, OuterMeasure (α i)} {n : OuterMeasure (∀ i, α i)} : n ≤ OuterMeasure.pi m ↔ ∀ s : ∀ i, Set (α i), (pi univ s).Nonempty → n (pi univ s) ≤ ∏ i, m i (s i) := by rw [OuterMeasure.pi, le_boundedBy']; constructor · intro h s hs; refine (h _ hs).trans_eq (piPremeasure_pi hs) · intro h s hs; refine le_trans (n.mono <| subset_pi_eval_image univ s) (h _ ?_) simp [univ_pi_nonempty_iff, hs] end OuterMeasure namespace Measure variable [∀ i, MeasurableSpace (α i)] (μ : ∀ i, Measure (α i)) section Tprod open List variable {δ : Type*} {π : δ → Type*} [∀ x, MeasurableSpace (π x)] -- for some reason the equation compiler doesn't like this definition /-- A product of measures in `tprod α l`. -/ protected def tprod (l : List δ) (μ : ∀ i, Measure (π i)) : Measure (TProd π l) := by induction' l with i l ih · exact dirac PUnit.unit · have := (μ i).prod (α := π i) ih exact this @[simp] theorem tprod_nil (μ : ∀ i, Measure (π i)) : Measure.tprod [] μ = dirac PUnit.unit := rfl @[simp] theorem tprod_cons (i : δ) (l : List δ) (μ : ∀ i, Measure (π i)) : Measure.tprod (i :: l) μ = (μ i).prod (Measure.tprod l μ) := rfl instance sigmaFinite_tprod (l : List δ) (μ : ∀ i, Measure (π i)) [∀ i, SigmaFinite (μ i)] : SigmaFinite (Measure.tprod l μ) := by induction l with | nil => rw [tprod_nil]; infer_instance | cons i l ih => rw [tprod_cons]; exact @prod.instSigmaFinite _ _ _ _ _ _ _ ih theorem tprod_tprod (l : List δ) (μ : ∀ i, Measure (π i)) [∀ i, SigmaFinite (μ i)] (s : ∀ i, Set (π i)) : Measure.tprod l μ (Set.tprod l s) = (l.map fun i => (μ i) (s i)).prod := by induction l with | nil => simp | cons a l ih => rw [tprod_cons, Set.tprod] erw [prod_prod] -- TODO: why `rw` fails? rw [map_cons, prod_cons, ih] end Tprod section Encodable open List MeasurableEquiv variable [Encodable ι] /-- The product measure on an encodable finite type, defined by mapping `Measure.tprod` along the equivalence `MeasurableEquiv.piMeasurableEquivTProd`. The definition `MeasureTheory.Measure.pi` should be used instead of this one. -/ def pi' : Measure (∀ i, α i) := Measure.map (TProd.elim' mem_sortedUniv) (Measure.tprod (sortedUniv ι) μ) theorem pi'_pi [∀ i, SigmaFinite (μ i)] (s : ∀ i, Set (α i)) : pi' μ (pi univ s) = ∏ i, μ i (s i) := by rw [pi'] rw [← MeasurableEquiv.piMeasurableEquivTProd_symm_apply, MeasurableEquiv.map_apply, MeasurableEquiv.piMeasurableEquivTProd_symm_apply, elim_preimage_pi, tprod_tprod _ μ, ← List.prod_toFinset, sortedUniv_toFinset] <;> exact sortedUniv_nodup ι end Encodable theorem pi_caratheodory : MeasurableSpace.pi ≤ (OuterMeasure.pi fun i => (μ i).toOuterMeasure).caratheodory := by refine iSup_le ?_ intro i s hs rw [MeasurableSpace.comap] at hs rcases hs with ⟨s, hs, rfl⟩ apply boundedBy_caratheodory intro t simp_rw [piPremeasure] refine Finset.prod_add_prod_le' (Finset.mem_univ i) ?_ ?_ ?_ · simp [image_inter_preimage, image_diff_preimage, measure_inter_add_diff _ hs, le_refl] · rintro j - _; gcongr; apply inter_subset_left · rintro j - _; gcongr; apply diff_subset /-- `Measure.pi μ` is the finite product of the measures `{μ i | i : ι}`. It is defined to be measure corresponding to `MeasureTheory.OuterMeasure.pi`. -/ protected irreducible_def pi : Measure (∀ i, α i) := toMeasure (OuterMeasure.pi fun i => (μ i).toOuterMeasure) (pi_caratheodory μ) -- Porting note: moved from below so that instances about `Measure.pi` and `MeasureSpace.pi` -- go together instance _root_.MeasureTheory.MeasureSpace.pi {α : ι → Type*} [∀ i, MeasureSpace (α i)] : MeasureSpace (∀ i, α i) := ⟨Measure.pi fun _ => volume⟩ theorem pi_pi_aux [∀ i, SigmaFinite (μ i)] (s : ∀ i, Set (α i)) (hs : ∀ i, MeasurableSet (s i)) : Measure.pi μ (pi univ s) = ∏ i, μ i (s i) := by refine le_antisymm ?_ ?_ · rw [Measure.pi, toMeasure_apply _ _ (MeasurableSet.pi countable_univ fun i _ => hs i)] apply OuterMeasure.pi_pi_le · haveI : Encodable ι := Fintype.toEncodable ι simp_rw [← pi'_pi μ s, Measure.pi, toMeasure_apply _ _ (MeasurableSet.pi countable_univ fun i _ => hs i)] suffices (pi' μ).toOuterMeasure ≤ OuterMeasure.pi fun i => (μ i).toOuterMeasure by exact this _ clear hs s rw [OuterMeasure.le_pi] intro s _ exact (pi'_pi μ s).le variable {μ} /-- `Measure.pi μ` has finite spanning sets in rectangles of finite spanning sets. -/ def FiniteSpanningSetsIn.pi {C : ∀ i, Set (Set (α i))} (hμ : ∀ i, (μ i).FiniteSpanningSetsIn (C i)) : (Measure.pi μ).FiniteSpanningSetsIn (pi univ '' pi univ C) := by haveI := fun i => (hμ i).sigmaFinite haveI := Fintype.toEncodable ι refine ⟨fun n => Set.pi univ fun i => (hμ i).set ((@decode (ι → ℕ) _ n).iget i), fun n => ?_, fun n => ?_, ?_⟩ <;> -- TODO (kmill) If this let comes before the refine, while the noncomputability checker -- correctly sees this definition is computable, the Lean VM fails to see the binding is -- computationally irrelevant. The `noncomputable section` doesn't help because all it does -- is insert `noncomputable` for you when necessary. let e : ℕ → ι → ℕ := fun n => (@decode (ι → ℕ) _ n).iget · refine mem_image_of_mem _ fun i _ => (hμ i).set_mem _ · calc Measure.pi μ (Set.pi univ fun i => (hμ i).set (e n i)) ≤ Measure.pi μ (Set.pi univ fun i => toMeasurable (μ i) ((hμ i).set (e n i))) := measure_mono (pi_mono fun i _ => subset_toMeasurable _ _) _ = ∏ i, μ i (toMeasurable (μ i) ((hμ i).set (e n i))) := (pi_pi_aux μ _ fun i => measurableSet_toMeasurable _ _) _ = ∏ i, μ i ((hμ i).set (e n i)) := by simp only [measure_toMeasurable] _ < ∞ := ENNReal.prod_lt_top fun i _ => ((hμ i).finite _).ne · simp_rw [(surjective_decode_iget (ι → ℕ)).iUnion_comp fun x => Set.pi univ fun i => (hμ i).set (x i), iUnion_univ_pi fun i => (hμ i).set, (hμ _).spanning, Set.pi_univ] /-- A measure on a finite product space equals the product measure if they are equal on rectangles with as sides sets that generate the corresponding σ-algebras. -/ theorem pi_eq_generateFrom {C : ∀ i, Set (Set (α i))} (hC : ∀ i, generateFrom (C i) = by apply_assumption) (h2C : ∀ i, IsPiSystem (C i)) (h3C : ∀ i, (μ i).FiniteSpanningSetsIn (C i)) {μν : Measure (∀ i, α i)} (h₁ : ∀ s : ∀ i, Set (α i), (∀ i, s i ∈ C i) → μν (pi univ s) = ∏ i, μ i (s i)) : Measure.pi μ = μν := by have h4C : ∀ (i) (s : Set (α i)), s ∈ C i → MeasurableSet s := by intro i s hs; rw [← hC]; exact measurableSet_generateFrom hs refine (FiniteSpanningSetsIn.pi h3C).ext (generateFrom_eq_pi hC fun i => (h3C i).isCountablySpanning).symm (IsPiSystem.pi h2C) ?_ rintro _ ⟨s, hs, rfl⟩ rw [mem_univ_pi] at hs haveI := fun i => (h3C i).sigmaFinite simp_rw [h₁ s hs, pi_pi_aux μ s fun i => h4C i _ (hs i)] variable [∀ i, SigmaFinite (μ i)] /-- A measure on a finite product space equals the product measure if they are equal on rectangles. -/ theorem pi_eq {μ' : Measure (∀ i, α i)} (h : ∀ s : ∀ i, Set (α i), (∀ i, MeasurableSet (s i)) → μ' (pi univ s) = ∏ i, μ i (s i)) : Measure.pi μ = μ' := pi_eq_generateFrom (fun _ => generateFrom_measurableSet) (fun _ => isPiSystem_measurableSet) (fun i => (μ i).toFiniteSpanningSetsIn) h variable (μ) theorem pi'_eq_pi [Encodable ι] : pi' μ = Measure.pi μ := Eq.symm <| pi_eq fun s _ => pi'_pi μ s @[simp] theorem pi_pi (s : ∀ i, Set (α i)) : Measure.pi μ (pi univ s) = ∏ i, μ i (s i) := by haveI : Encodable ι := Fintype.toEncodable ι rw [← pi'_eq_pi, pi'_pi] nonrec theorem pi_univ : Measure.pi μ univ = ∏ i, μ i univ := by rw [← pi_univ, pi_pi μ] theorem pi_ball [∀ i, MetricSpace (α i)] (x : ∀ i, α i) {r : ℝ} (hr : 0 < r) : Measure.pi μ (Metric.ball x r) = ∏ i, μ i (Metric.ball (x i) r) := by rw [ball_pi _ hr, pi_pi] theorem pi_closedBall [∀ i, MetricSpace (α i)] (x : ∀ i, α i) {r : ℝ} (hr : 0 ≤ r) : Measure.pi μ (Metric.closedBall x r) = ∏ i, μ i (Metric.closedBall (x i) r) := by rw [closedBall_pi _ hr, pi_pi] instance pi.sigmaFinite : SigmaFinite (Measure.pi μ) := (FiniteSpanningSetsIn.pi fun i => (μ i).toFiniteSpanningSetsIn).sigmaFinite instance {α : ι → Type*} [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] : SigmaFinite (volume : Measure (∀ i, α i)) := pi.sigmaFinite _ instance pi.instIsFiniteMeasure [∀ i, IsFiniteMeasure (μ i)] : IsFiniteMeasure (Measure.pi μ) := ⟨Measure.pi_univ μ ▸ ENNReal.prod_lt_top (fun i _ ↦ measure_ne_top (μ i) _)⟩ instance {α : ι → Type*} [∀ i, MeasureSpace (α i)] [∀ i, IsFiniteMeasure (volume : Measure (α i))] : IsFiniteMeasure (volume : Measure (∀ i, α i)) := pi.instIsFiniteMeasure _ instance pi.instIsProbabilityMeasure [∀ i, IsProbabilityMeasure (μ i)] : IsProbabilityMeasure (Measure.pi μ) := ⟨by simp only [Measure.pi_univ, measure_univ, Finset.prod_const_one]⟩ instance {α : ι → Type*} [∀ i, MeasureSpace (α i)] [∀ i, IsProbabilityMeasure (volume : Measure (α i))] : IsProbabilityMeasure (volume : Measure (∀ i, α i)) := pi.instIsProbabilityMeasure _ theorem pi_of_empty {α : Type*} [Fintype α] [IsEmpty α] {β : α → Type*} {m : ∀ a, MeasurableSpace (β a)} (μ : ∀ a : α, Measure (β a)) (x : ∀ a, β a := isEmptyElim) : Measure.pi μ = dirac x := by haveI : ∀ a, SigmaFinite (μ a) := isEmptyElim refine pi_eq fun s _ => ?_ rw [Fintype.prod_empty, dirac_apply_of_mem] exact isEmptyElim (α := α) lemma volume_pi_eq_dirac {ι : Type*} [Fintype ι] [IsEmpty ι] {α : ι → Type*} [∀ i, MeasureSpace (α i)] (x : ∀ a, α a := isEmptyElim) : (volume : Measure (∀ i, α i)) = Measure.dirac x := Measure.pi_of_empty _ _ @[simp] theorem pi_empty_univ {α : Type*} [Fintype α] [IsEmpty α] {β : α → Type*} {m : ∀ α, MeasurableSpace (β α)} (μ : ∀ a : α, Measure (β a)) : Measure.pi μ (Set.univ) = 1 := by rw [pi_of_empty, measure_univ] theorem pi_eval_preimage_null {i : ι} {s : Set (α i)} (hs : μ i s = 0) : Measure.pi μ (eval i ⁻¹' s) = 0 := by -- WLOG, `s` is measurable rcases exists_measurable_superset_of_null hs with ⟨t, hst, _, hμt⟩ suffices Measure.pi μ (eval i ⁻¹' t) = 0 from measure_mono_null (preimage_mono hst) this -- Now rewrite it as `Set.pi`, and apply `pi_pi` rw [← univ_pi_update_univ, pi_pi] apply Finset.prod_eq_zero (Finset.mem_univ i) simp [hμt] theorem pi_hyperplane (i : ι) [NoAtoms (μ i)] (x : α i) : Measure.pi μ { f : ∀ i, α i | f i = x } = 0 := show Measure.pi μ (eval i ⁻¹' {x}) = 0 from pi_eval_preimage_null _ (measure_singleton x) theorem ae_eval_ne (i : ι) [NoAtoms (μ i)] (x : α i) : ∀ᵐ y : ∀ i, α i ∂Measure.pi μ, y i ≠ x := compl_mem_ae_iff.2 (pi_hyperplane μ i x) variable {μ} theorem tendsto_eval_ae_ae {i : ι} : Tendsto (eval i) (ae (Measure.pi μ)) (ae (μ i)) := fun _ hs => pi_eval_preimage_null μ hs theorem ae_pi_le_pi : ae (Measure.pi μ) ≤ Filter.pi fun i => ae (μ i) := le_iInf fun _ => tendsto_eval_ae_ae.le_comap theorem ae_eq_pi {β : ι → Type*} {f f' : ∀ i, α i → β i} (h : ∀ i, f i =ᵐ[μ i] f' i) : (fun (x : ∀ i, α i) i => f i (x i)) =ᵐ[Measure.pi μ] fun x i => f' i (x i) := (eventually_all.2 fun i => tendsto_eval_ae_ae.eventually (h i)).mono fun _ hx => funext hx theorem ae_le_pi {β : ι → Type*} [∀ i, Preorder (β i)] {f f' : ∀ i, α i → β i} (h : ∀ i, f i ≤ᵐ[μ i] f' i) : (fun (x : ∀ i, α i) i => f i (x i)) ≤ᵐ[Measure.pi μ] fun x i => f' i (x i) := (eventually_all.2 fun i => tendsto_eval_ae_ae.eventually (h i)).mono fun _ hx => hx theorem ae_le_set_pi {I : Set ι} {s t : ∀ i, Set (α i)} (h : ∀ i ∈ I, s i ≤ᵐ[μ i] t i) : Set.pi I s ≤ᵐ[Measure.pi μ] Set.pi I t := ((eventually_all_finite I.toFinite).2 fun i hi => tendsto_eval_ae_ae.eventually (h i hi)).mono fun _ hst hx i hi => hst i hi <| hx i hi theorem ae_eq_set_pi {I : Set ι} {s t : ∀ i, Set (α i)} (h : ∀ i ∈ I, s i =ᵐ[μ i] t i) : Set.pi I s =ᵐ[Measure.pi μ] Set.pi I t := (ae_le_set_pi fun i hi => (h i hi).le).antisymm (ae_le_set_pi fun i hi => (h i hi).symm.le) lemma pi_map_piCongrLeft [hι' : Fintype ι'] (e : ι ≃ ι') {β : ι' → Type*} [∀ i, MeasurableSpace (β i)] (μ : (i : ι') → Measure (β i)) [∀ i, SigmaFinite (μ i)] : (Measure.pi fun i ↦ μ (e i)).map (MeasurableEquiv.piCongrLeft (fun i ↦ β i) e) = Measure.pi μ := by let e_meas : ((b : ι) → β (e b)) ≃ᵐ ((a : ι') → β a) := MeasurableEquiv.piCongrLeft (fun i ↦ β i) e refine Measure.pi_eq (fun s _ ↦ ?_) |>.symm rw [e_meas.measurableEmbedding.map_apply] let s' : (i : ι) → Set (β (e i)) := fun i ↦ s (e i) have : e_meas ⁻¹' pi univ s = pi univ s' := by ext x simp only [mem_preimage, Set.mem_pi, mem_univ, forall_true_left, s'] refine (e.forall_congr ?_).symm intro i rw [MeasurableEquiv.piCongrLeft_apply_apply e x i] rw [this, pi_pi, Finset.prod_equiv e.symm] · simp only [Finset.mem_univ, implies_true] intro i _ simp only [s'] congr all_goals rw [e.apply_symm_apply] lemma pi_map_piOptionEquivProd {β : Option ι → Type*} [∀ i, MeasurableSpace (β i)] (μ : (i : Option ι) → Measure (β i)) [∀ (i : Option ι), SigmaFinite (μ i)] : ((Measure.pi fun i ↦ μ (some i)).prod (μ none)).map (MeasurableEquiv.piOptionEquivProd β).symm = Measure.pi μ := by refine pi_eq (fun s _ ↦ ?_) |>.symm let e_meas : ((i : ι) → β (some i)) × β none ≃ᵐ ((i : Option ι) → β i) := MeasurableEquiv.piOptionEquivProd β |>.symm have me := MeasurableEquiv.measurableEmbedding e_meas have : e_meas ⁻¹' pi univ s = (pi univ (fun i ↦ s (some i))) ×ˢ (s none) := by ext x simp only [mem_preimage, Set.mem_pi, mem_univ, forall_true_left, mem_prod] refine ⟨by tauto, fun _ i ↦ ?_⟩ rcases i <;> tauto simp only [me.map_apply, univ_option, le_eq_subset, Finset.prod_insertNone, this, prod_prod, pi_pi, mul_comm] section Intervals variable [∀ i, PartialOrder (α i)] [∀ i, NoAtoms (μ i)] theorem pi_Iio_ae_eq_pi_Iic {s : Set ι} {f : ∀ i, α i} : (pi s fun i => Iio (f i)) =ᵐ[Measure.pi μ] pi s fun i => Iic (f i) := ae_eq_set_pi fun _ _ => Iio_ae_eq_Iic theorem pi_Ioi_ae_eq_pi_Ici {s : Set ι} {f : ∀ i, α i} : (pi s fun i => Ioi (f i)) =ᵐ[Measure.pi μ] pi s fun i => Ici (f i) := ae_eq_set_pi fun _ _ => Ioi_ae_eq_Ici theorem univ_pi_Iio_ae_eq_Iic {f : ∀ i, α i} : (pi univ fun i => Iio (f i)) =ᵐ[Measure.pi μ] Iic f := by rw [← pi_univ_Iic]; exact pi_Iio_ae_eq_pi_Iic theorem univ_pi_Ioi_ae_eq_Ici {f : ∀ i, α i} : (pi univ fun i => Ioi (f i)) =ᵐ[Measure.pi μ] Ici f := by rw [← pi_univ_Ici]; exact pi_Ioi_ae_eq_pi_Ici theorem pi_Ioo_ae_eq_pi_Icc {s : Set ι} {f g : ∀ i, α i} : (pi s fun i => Ioo (f i) (g i)) =ᵐ[Measure.pi μ] pi s fun i => Icc (f i) (g i) := ae_eq_set_pi fun _ _ => Ioo_ae_eq_Icc theorem pi_Ioo_ae_eq_pi_Ioc {s : Set ι} {f g : ∀ i, α i} : (pi s fun i => Ioo (f i) (g i)) =ᵐ[Measure.pi μ] pi s fun i => Ioc (f i) (g i) := ae_eq_set_pi fun _ _ => Ioo_ae_eq_Ioc theorem univ_pi_Ioo_ae_eq_Icc {f g : ∀ i, α i} : (pi univ fun i => Ioo (f i) (g i)) =ᵐ[Measure.pi μ] Icc f g := by rw [← pi_univ_Icc]; exact pi_Ioo_ae_eq_pi_Icc theorem pi_Ioc_ae_eq_pi_Icc {s : Set ι} {f g : ∀ i, α i} : (pi s fun i => Ioc (f i) (g i)) =ᵐ[Measure.pi μ] pi s fun i => Icc (f i) (g i) := ae_eq_set_pi fun _ _ => Ioc_ae_eq_Icc theorem univ_pi_Ioc_ae_eq_Icc {f g : ∀ i, α i} : (pi univ fun i => Ioc (f i) (g i)) =ᵐ[Measure.pi μ] Icc f g := by rw [← pi_univ_Icc]; exact pi_Ioc_ae_eq_pi_Icc theorem pi_Ico_ae_eq_pi_Icc {s : Set ι} {f g : ∀ i, α i} : (pi s fun i => Ico (f i) (g i)) =ᵐ[Measure.pi μ] pi s fun i => Icc (f i) (g i) := ae_eq_set_pi fun _ _ => Ico_ae_eq_Icc theorem univ_pi_Ico_ae_eq_Icc {f g : ∀ i, α i} : (pi univ fun i => Ico (f i) (g i)) =ᵐ[Measure.pi μ] Icc f g := by rw [← pi_univ_Icc]; exact pi_Ico_ae_eq_pi_Icc end Intervals /-- If one of the measures `μ i` has no atoms, them `Measure.pi µ` has no atoms. The instance below assumes that all `μ i` have no atoms. -/ theorem pi_noAtoms (i : ι) [NoAtoms (μ i)] : NoAtoms (Measure.pi μ) := ⟨fun x => flip measure_mono_null (pi_hyperplane μ i (x i)) (singleton_subset_iff.2 rfl)⟩ instance pi_noAtoms' [h : Nonempty ι] [∀ i, NoAtoms (μ i)] : NoAtoms (Measure.pi μ) := h.elim fun i => pi_noAtoms i instance {α : ι → Type*} [Nonempty ι] [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] [∀ i, NoAtoms (volume : Measure (α i))] : NoAtoms (volume : Measure (∀ i, α i)) := pi_noAtoms' instance pi.isLocallyFiniteMeasure [∀ i, TopologicalSpace (α i)] [∀ i, IsLocallyFiniteMeasure (μ i)] : IsLocallyFiniteMeasure (Measure.pi μ) := by refine ⟨fun x => ?_⟩ choose s hxs ho hμ using fun i => (μ i).exists_isOpen_measure_lt_top (x i) refine ⟨pi univ s, set_pi_mem_nhds finite_univ fun i _ => IsOpen.mem_nhds (ho i) (hxs i), ?_⟩ rw [pi_pi] exact ENNReal.prod_lt_top fun i _ => (hμ i).ne instance {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, MeasureSpace (X i)] [∀ i, SigmaFinite (volume : Measure (X i))] [∀ i, IsLocallyFiniteMeasure (volume : Measure (X i))] : IsLocallyFiniteMeasure (volume : Measure (∀ i, X i)) := pi.isLocallyFiniteMeasure variable (μ) @[to_additive] instance pi.isMulLeftInvariant [∀ i, Group (α i)] [∀ i, MeasurableMul (α i)] [∀ i, IsMulLeftInvariant (μ i)] : IsMulLeftInvariant (Measure.pi μ) := by refine ⟨fun v => (pi_eq fun s hs => ?_).symm⟩ rw [map_apply (measurable_const_mul _) (MeasurableSet.univ_pi hs), show (v * ·) ⁻¹' univ.pi s = univ.pi fun i => (v i * ·) ⁻¹' s i by rfl, pi_pi] simp_rw [measure_preimage_mul] @[to_additive] instance {G : ι → Type*} [∀ i, Group (G i)] [∀ i, MeasureSpace (G i)] [∀ i, MeasurableMul (G i)] [∀ i, SigmaFinite (volume : Measure (G i))] [∀ i, IsMulLeftInvariant (volume : Measure (G i))] : IsMulLeftInvariant (volume : Measure (∀ i, G i)) := pi.isMulLeftInvariant _ @[to_additive] instance pi.isMulRightInvariant [∀ i, Group (α i)] [∀ i, MeasurableMul (α i)] [∀ i, IsMulRightInvariant (μ i)] : IsMulRightInvariant (Measure.pi μ) := by refine ⟨fun v => (pi_eq fun s hs => ?_).symm⟩ rw [map_apply (measurable_mul_const _) (MeasurableSet.univ_pi hs), show (· * v) ⁻¹' univ.pi s = univ.pi fun i => (· * v i) ⁻¹' s i by rfl, pi_pi] simp_rw [measure_preimage_mul_right] @[to_additive] instance {G : ι → Type*} [∀ i, Group (G i)] [∀ i, MeasureSpace (G i)] [∀ i, MeasurableMul (G i)] [∀ i, SigmaFinite (volume : Measure (G i))] [∀ i, IsMulRightInvariant (volume : Measure (G i))] : IsMulRightInvariant (volume : Measure (∀ i, G i)) := pi.isMulRightInvariant _ @[to_additive] instance pi.isInvInvariant [∀ i, Group (α i)] [∀ i, MeasurableInv (α i)] [∀ i, IsInvInvariant (μ i)] : IsInvInvariant (Measure.pi μ) := by refine ⟨(Measure.pi_eq fun s hs => ?_).symm⟩ have A : Inv.inv ⁻¹' pi univ s = Set.pi univ fun i => Inv.inv ⁻¹' s i := by ext; simp simp_rw [Measure.inv, Measure.map_apply measurable_inv (MeasurableSet.univ_pi hs), A, pi_pi, measure_preimage_inv] @[to_additive] instance {G : ι → Type*} [∀ i, Group (G i)] [∀ i, MeasureSpace (G i)] [∀ i, MeasurableInv (G i)] [∀ i, SigmaFinite (volume : Measure (G i))] [∀ i, IsInvInvariant (volume : Measure (G i))] : IsInvInvariant (volume : Measure (∀ i, G i)) := pi.isInvInvariant _ instance pi.isOpenPosMeasure [∀ i, TopologicalSpace (α i)] [∀ i, IsOpenPosMeasure (μ i)] : IsOpenPosMeasure (MeasureTheory.Measure.pi μ) := by constructor rintro U U_open ⟨a, ha⟩ obtain ⟨s, ⟨hs, hsU⟩⟩ := isOpen_pi_iff'.1 U_open a ha refine ne_of_gt (lt_of_lt_of_le ?_ (measure_mono hsU)) simp only [pi_pi] rw [CanonicallyOrderedCommSemiring.prod_pos] intro i _ apply (hs i).1.measure_pos (μ i) ⟨a i, (hs i).2⟩ instance {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, MeasureSpace (X i)] [∀ i, IsOpenPosMeasure (volume : Measure (X i))] [∀ i, SigmaFinite (volume : Measure (X i))] : IsOpenPosMeasure (volume : Measure (∀ i, X i)) := pi.isOpenPosMeasure _ instance pi.isFiniteMeasureOnCompacts [∀ i, TopologicalSpace (α i)] [∀ i, IsFiniteMeasureOnCompacts (μ i)] : IsFiniteMeasureOnCompacts (MeasureTheory.Measure.pi μ) := by constructor intro K hK suffices Measure.pi μ (Set.univ.pi fun j => Function.eval j '' K) < ⊤ by exact lt_of_le_of_lt (measure_mono (univ.subset_pi_eval_image K)) this rw [Measure.pi_pi] refine WithTop.prod_lt_top ?_ exact fun i _ => ne_of_lt (IsCompact.measure_lt_top (IsCompact.image hK (continuous_apply i))) instance {X : ι → Type*} [∀ i, MeasureSpace (X i)] [∀ i, TopologicalSpace (X i)] [∀ i, SigmaFinite (volume : Measure (X i))] [∀ i, IsFiniteMeasureOnCompacts (volume : Measure (X i))] : IsFiniteMeasureOnCompacts (volume : Measure (∀ i, X i)) := pi.isFiniteMeasureOnCompacts _ @[to_additive] instance pi.isHaarMeasure [∀ i, Group (α i)] [∀ i, TopologicalSpace (α i)] [∀ i, IsHaarMeasure (μ i)] [∀ i, MeasurableMul (α i)] : IsHaarMeasure (Measure.pi μ) where @[to_additive] instance {G : ι → Type*} [∀ i, Group (G i)] [∀ i, MeasureSpace (G i)] [∀ i, MeasurableMul (G i)] [∀ i, TopologicalSpace (G i)] [∀ i, SigmaFinite (volume : Measure (G i))] [∀ i, IsHaarMeasure (volume : Measure (G i))] : IsHaarMeasure (volume : Measure (∀ i, G i)) := pi.isHaarMeasure _ end Measure theorem volume_pi [∀ i, MeasureSpace (α i)] : (volume : Measure (∀ i, α i)) = Measure.pi fun _ => volume := rfl theorem volume_pi_pi [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] (s : ∀ i, Set (α i)) : volume (pi univ s) = ∏ i, volume (s i) := Measure.pi_pi (fun _ => volume) s theorem volume_pi_ball [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] [∀ i, MetricSpace (α i)] (x : ∀ i, α i) {r : ℝ} (hr : 0 < r) : volume (Metric.ball x r) = ∏ i, volume (Metric.ball (x i) r) := Measure.pi_ball _ _ hr theorem volume_pi_closedBall [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] [∀ i, MetricSpace (α i)] (x : ∀ i, α i) {r : ℝ} (hr : 0 ≤ r) : volume (Metric.closedBall x r) = ∏ i, volume (Metric.closedBall (x i) r) := Measure.pi_closedBall _ _ hr open Measure /-- We intentionally restrict this only to the nondependent function space, since type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces. -/ @[to_additive "We intentionally restrict this only to the nondependent function space, since type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces."] instance Pi.isMulLeftInvariant_volume {α} [Group α] [MeasureSpace α] [SigmaFinite (volume : Measure α)] [MeasurableMul α] [IsMulLeftInvariant (volume : Measure α)] : IsMulLeftInvariant (volume : Measure (ι → α)) := pi.isMulLeftInvariant _ /-- We intentionally restrict this only to the nondependent function space, since type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces. -/ @[to_additive "We intentionally restrict this only to the nondependent function space, since type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces."] instance Pi.isInvInvariant_volume {α} [Group α] [MeasureSpace α] [SigmaFinite (volume : Measure α)] [MeasurableInv α] [IsInvInvariant (volume : Measure α)] : IsInvInvariant (volume : Measure (ι → α)) := pi.isInvInvariant _ /-! ### Measure preserving equivalences In this section we prove that some measurable equivalences (e.g., between `Fin 1 → α` and `α` or between `Fin 2 → α` and `α × α`) preserve measure or volume. These lemmas can be used to prove that measures of corresponding sets (images or preimages) have equal measures and functions `f ∘ e` and `f` have equal integrals, see lemmas in the `MeasureTheory.measurePreserving` prefix. -/ section MeasurePreserving variable {m : ∀ i, MeasurableSpace (α i)} (μ : ∀ i, Measure (α i)) [∀ i, SigmaFinite (μ i)] variable [Fintype ι'] theorem measurePreserving_piEquivPiSubtypeProd (p : ι → Prop) [DecidablePred p] : MeasurePreserving (MeasurableEquiv.piEquivPiSubtypeProd α p) (Measure.pi μ) ((Measure.pi fun i : Subtype p => μ i).prod (Measure.pi fun i => μ i)) := by set e := (MeasurableEquiv.piEquivPiSubtypeProd α p).symm refine MeasurePreserving.symm e ?_ refine ⟨e.measurable, (pi_eq fun s _ => ?_).symm⟩ have : e ⁻¹' pi univ s = (pi univ fun i : { i // p i } => s i) ×ˢ pi univ fun i : { i // ¬p i } => s i := Equiv.preimage_piEquivPiSubtypeProd_symm_pi p s rw [e.map_apply, this, prod_prod, pi_pi, pi_pi] exact Fintype.prod_subtype_mul_prod_subtype p fun i => μ i (s i) theorem volume_preserving_piEquivPiSubtypeProd (α : ι → Type*) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] (p : ι → Prop) [DecidablePred p] : MeasurePreserving (MeasurableEquiv.piEquivPiSubtypeProd α p) := measurePreserving_piEquivPiSubtypeProd (fun _ => volume) p theorem measurePreserving_piCongrLeft (f : ι' ≃ ι) : MeasurePreserving (MeasurableEquiv.piCongrLeft α f) (Measure.pi fun i' => μ (f i')) (Measure.pi μ) where measurable := (MeasurableEquiv.piCongrLeft α f).measurable map_eq := by refine (pi_eq fun s _ => ?_).symm rw [MeasurableEquiv.map_apply, MeasurableEquiv.coe_piCongrLeft f, Equiv.piCongrLeft_preimage_univ_pi, pi_pi _ _, f.prod_comp (fun i => μ i (s i))] theorem volume_measurePreserving_piCongrLeft (α : ι → Type*) (f : ι' ≃ ι) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] : MeasurePreserving (MeasurableEquiv.piCongrLeft α f) volume volume := measurePreserving_piCongrLeft (fun _ ↦ volume) f theorem measurePreserving_sumPiEquivProdPi_symm {π : ι ⊕ ι' → Type*} {m : ∀ i, MeasurableSpace (π i)} (μ : ∀ i, Measure (π i)) [∀ i, SigmaFinite (μ i)] : MeasurePreserving (MeasurableEquiv.sumPiEquivProdPi π).symm ((Measure.pi fun i => μ (.inl i)).prod (Measure.pi fun i => μ (.inr i))) (Measure.pi μ) where measurable := (MeasurableEquiv.sumPiEquivProdPi π).symm.measurable map_eq := by refine (pi_eq fun s _ => ?_).symm simp_rw [MeasurableEquiv.map_apply, MeasurableEquiv.coe_sumPiEquivProdPi_symm, Equiv.sumPiEquivProdPi_symm_preimage_univ_pi, Measure.prod_prod, Measure.pi_pi, Fintype.prod_sum_type] theorem volume_measurePreserving_sumPiEquivProdPi_symm (π : ι ⊕ ι' → Type*) [∀ i, MeasureSpace (π i)] [∀ i, SigmaFinite (volume : Measure (π i))] : MeasurePreserving (MeasurableEquiv.sumPiEquivProdPi π).symm volume volume := measurePreserving_sumPiEquivProdPi_symm (fun _ ↦ volume) theorem measurePreserving_sumPiEquivProdPi {π : ι ⊕ ι' → Type*} {_m : ∀ i, MeasurableSpace (π i)} (μ : ∀ i, Measure (π i)) [∀ i, SigmaFinite (μ i)] : MeasurePreserving (MeasurableEquiv.sumPiEquivProdPi π) (Measure.pi μ) ((Measure.pi fun i => μ (.inl i)).prod (Measure.pi fun i => μ (.inr i))) := measurePreserving_sumPiEquivProdPi_symm μ |>.symm theorem volume_measurePreserving_sumPiEquivProdPi (π : ι ⊕ ι' → Type*) [∀ i, MeasureSpace (π i)] [∀ i, SigmaFinite (volume : Measure (π i))] : MeasurePreserving (MeasurableEquiv.sumPiEquivProdPi π) volume volume := measurePreserving_sumPiEquivProdPi (fun _ ↦ volume) theorem measurePreserving_piFinSuccAbove {n : ℕ} {α : Fin (n + 1) → Type u} {m : ∀ i, MeasurableSpace (α i)} (μ : ∀ i, Measure (α i)) [∀ i, SigmaFinite (μ i)] (i : Fin (n + 1)) : MeasurePreserving (MeasurableEquiv.piFinSuccAbove α i) (Measure.pi μ) ((μ i).prod <| Measure.pi fun j => μ (i.succAbove j)) := by set e := (MeasurableEquiv.piFinSuccAbove α i).symm refine MeasurePreserving.symm e ?_ refine ⟨e.measurable, (pi_eq fun s _ => ?_).symm⟩ rw [e.map_apply, i.prod_univ_succAbove _, ← pi_pi, ← prod_prod] congr 1 with ⟨x, f⟩ simp [e, i.forall_iff_succAbove] theorem volume_preserving_piFinSuccAbove {n : ℕ} (α : Fin (n + 1) → Type u) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] (i : Fin (n + 1)) : MeasurePreserving (MeasurableEquiv.piFinSuccAbove α i) := measurePreserving_piFinSuccAbove (fun _ => volume) i theorem measurePreserving_piUnique {π : ι → Type*} [Unique ι] {m : ∀ i, MeasurableSpace (π i)} (μ : ∀ i, Measure (π i)) : MeasurePreserving (MeasurableEquiv.piUnique π) (Measure.pi μ) (μ default) where measurable := (MeasurableEquiv.piUnique π).measurable map_eq := by set e := MeasurableEquiv.piUnique π have : (piPremeasure fun i => (μ i).toOuterMeasure) = Measure.map e.symm (μ default) := by ext1 s rw [piPremeasure, Fintype.prod_unique, e.symm.map_apply, coe_toOuterMeasure] congr 1; exact e.toEquiv.image_eq_preimage s simp_rw [Measure.pi, OuterMeasure.pi, this, ← coe_toOuterMeasure, boundedBy_eq_self, toOuterMeasure_toMeasure, MeasurableEquiv.map_map_symm] theorem volume_preserving_piUnique (π : ι → Type*) [Unique ι] [∀ i, MeasureSpace (π i)] : MeasurePreserving (MeasurableEquiv.piUnique π) volume volume := measurePreserving_piUnique _ theorem measurePreserving_funUnique {β : Type u} {_m : MeasurableSpace β} (μ : Measure β) (α : Type v) [Unique α] : MeasurePreserving (MeasurableEquiv.funUnique α β) (Measure.pi fun _ : α => μ) μ := measurePreserving_piUnique _ theorem volume_preserving_funUnique (α : Type u) (β : Type v) [Unique α] [MeasureSpace β] : MeasurePreserving (MeasurableEquiv.funUnique α β) volume volume := measurePreserving_funUnique volume α theorem measurePreserving_piFinTwo {α : Fin 2 → Type u} {m : ∀ i, MeasurableSpace (α i)} (μ : ∀ i, Measure (α i)) [∀ i, SigmaFinite (μ i)] : MeasurePreserving (MeasurableEquiv.piFinTwo α) (Measure.pi μ) ((μ 0).prod (μ 1)) := by refine ⟨MeasurableEquiv.measurable _, (Measure.prod_eq fun s t _ _ => ?_).symm⟩ rw [MeasurableEquiv.map_apply, MeasurableEquiv.piFinTwo_apply, Fin.preimage_apply_01_prod, Measure.pi_pi, Fin.prod_univ_two] rfl theorem volume_preserving_piFinTwo (α : Fin 2 → Type u) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] : MeasurePreserving (MeasurableEquiv.piFinTwo α) volume volume := measurePreserving_piFinTwo _ theorem measurePreserving_finTwoArrow_vec {α : Type u} {m : MeasurableSpace α} (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] : MeasurePreserving MeasurableEquiv.finTwoArrow (Measure.pi ![μ, ν]) (μ.prod ν) := haveI : ∀ i, SigmaFinite (![μ, ν] i) := Fin.forall_fin_two.2 ⟨‹_›, ‹_›⟩ measurePreserving_piFinTwo _ theorem measurePreserving_finTwoArrow {α : Type u} {m : MeasurableSpace α} (μ : Measure α) [SigmaFinite μ] : MeasurePreserving MeasurableEquiv.finTwoArrow (Measure.pi fun _ => μ) (μ.prod μ) := by simpa only [Matrix.vec_single_eq_const, Matrix.vecCons_const] using measurePreserving_finTwoArrow_vec μ μ theorem volume_preserving_finTwoArrow (α : Type u) [MeasureSpace α] [SigmaFinite (volume : Measure α)] : MeasurePreserving (@MeasurableEquiv.finTwoArrow α _) volume volume := measurePreserving_finTwoArrow volume theorem measurePreserving_pi_empty {ι : Type u} {α : ι → Type v} [Fintype ι] [IsEmpty ι] {m : ∀ i, MeasurableSpace (α i)} (μ : ∀ i, Measure (α i)) : MeasurePreserving (MeasurableEquiv.ofUniqueOfUnique (∀ i, α i) Unit) (Measure.pi μ) (Measure.dirac ()) := by set e := MeasurableEquiv.ofUniqueOfUnique (∀ i, α i) Unit refine ⟨e.measurable, ?_⟩ rw [Measure.pi_of_empty, Measure.map_dirac e.measurable] theorem volume_preserving_pi_empty {ι : Type u} (α : ι → Type v) [Fintype ι] [IsEmpty ι] [∀ i, MeasureSpace (α i)] : MeasurePreserving (MeasurableEquiv.ofUniqueOfUnique (∀ i, α i) Unit) volume volume := measurePreserving_pi_empty fun _ => volume theorem measurePreserving_piFinsetUnion {ι : Type*} {α : ι → Type*} {_ : ∀ i, MeasurableSpace (α i)} [DecidableEq ι] {s t : Finset ι} (h : Disjoint s t) (μ : ∀ i, Measure (α i)) [∀ i, SigmaFinite (μ i)] : MeasurePreserving (MeasurableEquiv.piFinsetUnion α h) ((Measure.pi fun i : s ↦ μ i).prod (Measure.pi fun i : t ↦ μ i)) (Measure.pi fun i : ↥(s ∪ t) ↦ μ i) := let e := Equiv.Finset.union s t h measurePreserving_piCongrLeft (fun i : ↥(s ∪ t) ↦ μ i) e |>.comp <| measurePreserving_sumPiEquivProdPi_symm fun b ↦ μ (e b) theorem volume_preserving_piFinsetUnion {ι : Type*} [DecidableEq ι] (α : ι → Type*) {s t : Finset ι} (h : Disjoint s t) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] : MeasurePreserving (MeasurableEquiv.piFinsetUnion α h) volume volume := measurePreserving_piFinsetUnion h (fun _ ↦ volume) theorem measurePreserving_pi {ι : Type*} [Fintype ι] {α : ι → Type v} {β : ι → Type*} [∀ i, MeasureSpace (α i)] [∀ i, MeasurableSpace (β i)] (μ : (i : ι) → Measure (α i)) (ν : (i : ι) → Measure (β i)) {f : (i : ι) → (α i) → (β i)} [∀ i, SigmaFinite (ν i)] (hf : ∀ i, MeasurePreserving (f i) (μ i) (ν i)) : MeasurePreserving (fun a i ↦ f i (a i)) (Measure.pi μ) (Measure.pi ν) where measurable := measurable_pi_iff.mpr <| fun i ↦ (hf i).measurable.comp (measurable_pi_apply i) map_eq := by haveI : ∀ i, SigmaFinite (μ i) := fun i ↦ (hf i).sigmaFinite refine (Measure.pi_eq fun s hs ↦ ?_).symm rw [Measure.map_apply, Set.preimage_pi, Measure.pi_pi] · simp_rw [← MeasurePreserving.measure_preimage (hf _) (hs _).nullMeasurableSet] · exact measurable_pi_iff.mpr <| fun i ↦ (hf i).measurable.comp (measurable_pi_apply i) · exact MeasurableSet.univ_pi hs theorem volume_preserving_pi {α' β' : ι → Type*} [∀ i, MeasureSpace (α' i)] [∀ i, MeasureSpace (β' i)] [∀ i, SigmaFinite (volume : Measure (β' i))] {f : (i : ι) → (α' i) → (β' i)} (hf : ∀ i, MeasurePreserving (f i)) : MeasurePreserving (fun (a : (i : ι) → α' i) (i : ι) ↦ (f i) (a i)) := measurePreserving_pi _ _ hf end MeasurePreserving end MeasureTheory
MeasureTheory\Constructions\Projective.lean
/- Copyright (c) 2023 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Peter Pfaffelhuber -/ import Mathlib.MeasureTheory.Constructions.Cylinders import Mathlib.MeasureTheory.Measure.Typeclasses /-! # Projective measure families and projective limits A family of measures indexed by finite sets of `ι` is projective if, for finite sets `J ⊆ I`, the projection from `∀ i : I, α i` to `∀ i : J, α i` maps `P I` to `P J`. A measure `μ` is the projective limit of such a family of measures if for all `I : Finset ι`, the projection from `∀ i, α i` to `∀ i : I, α i` maps `μ` to `P I`. ## Main definitions * `MeasureTheory.IsProjectiveMeasureFamily`: `P : ∀ J : Finset ι, Measure (∀ j : J, α j)` is projective if the projection from `∀ i : I, α i` to `∀ i : J, α i` maps `P I` to `P J` for all `J ⊆ I`. * `MeasureTheory.IsProjectiveLimit`: `μ` is the projective limit of the measure family `P` if for all `I : Finset ι`, the map of `μ` by the projection to `I` is `P I`. ## Main statements * `MeasureTheory.IsProjectiveLimit.unique`: the projective limit of a family of finite measures is unique. -/ open Set namespace MeasureTheory variable {ι : Type*} {α : ι → Type*} [∀ i, MeasurableSpace (α i)] {P : ∀ J : Finset ι, Measure (∀ j : J, α j)} /-- A family of measures indexed by finite sets of `ι` is projective if, for finite sets `J ⊆ I`, the projection from `∀ i : I, α i` to `∀ i : J, α i` maps `P I` to `P J`. -/ def IsProjectiveMeasureFamily (P : ∀ J : Finset ι, Measure (∀ j : J, α j)) : Prop := ∀ (I J : Finset ι) (hJI : J ⊆ I), P J = (P I).map (fun (x : ∀ i : I, α i) (j : J) ↦ x ⟨j, hJI j.2⟩) namespace IsProjectiveMeasureFamily variable {I J : Finset ι} /-- Auxiliary lemma for `measure_univ_eq`. -/ lemma measure_univ_eq_of_subset (hP : IsProjectiveMeasureFamily P) (hJI : J ⊆ I) : P I univ = P J univ := by classical have : (univ : Set (∀ i : I, α i)) = (fun x : ∀ i : I, α i ↦ fun i : J ↦ x ⟨i, hJI i.2⟩) ⁻¹' (univ : Set (∀ i : J, α i)) := by rw [preimage_univ] rw [this, ← Measure.map_apply _ MeasurableSet.univ] · rw [hP I J hJI] · exact measurable_pi_lambda _ (fun _ ↦ measurable_pi_apply _) lemma measure_univ_eq (hP : IsProjectiveMeasureFamily P) (I J : Finset ι) : P I univ = P J univ := by classical rw [← hP.measure_univ_eq_of_subset I.subset_union_left, ← hP.measure_univ_eq_of_subset (I.subset_union_right (s₂ := J))] lemma congr_cylinder_of_subset (hP : IsProjectiveMeasureFamily P) {S : Set (∀ i : I, α i)} {T : Set (∀ i : J, α i)} (hT : MeasurableSet T) (h_eq : cylinder I S = cylinder J T) (hJI : J ⊆ I) : P I S = P J T := by cases isEmpty_or_nonempty (∀ i, α i) with | inl h => suffices ∀ I, P I univ = 0 by simp only [Measure.measure_univ_eq_zero] at this simp [this] intro I simp only [isEmpty_pi] at h obtain ⟨i, hi_empty⟩ := h rw [measure_univ_eq hP I {i}] have : (univ : Set ((j : {x // x ∈ ({i} : Finset ι)}) → α j)) = ∅ := by simp [hi_empty] simp [this] | inr h => have : S = (fun f : ∀ i : I, α i ↦ fun j : J ↦ f ⟨j, hJI j.prop⟩) ⁻¹' T := eq_of_cylinder_eq_of_subset h_eq hJI rw [hP I J hJI, Measure.map_apply _ hT, this] exact measurable_pi_lambda _ (fun _ ↦ measurable_pi_apply _) lemma congr_cylinder (hP : IsProjectiveMeasureFamily P) {S : Set (∀ i : I, α i)} {T : Set (∀ i : J, α i)} (hS : MeasurableSet S) (hT : MeasurableSet T) (h_eq : cylinder I S = cylinder J T) : P I S = P J T := by classical let U := (fun f : ∀ i : (I ∪ J : Finset ι), α i ↦ fun j : I ↦ f ⟨j, Finset.mem_union_left J j.prop⟩) ⁻¹' S ∩ (fun f ↦ fun j : J ↦ f ⟨j, Finset.mem_union_right I j.prop⟩) ⁻¹' T suffices P (I ∪ J) U = P I S ∧ P (I ∪ J) U = P J T from this.1.symm.trans this.2 constructor · have h_eq_union : cylinder I S = cylinder (I ∪ J) U := by rw [← inter_cylinder, h_eq, inter_self] exact hP.congr_cylinder_of_subset hS h_eq_union.symm Finset.subset_union_left · have h_eq_union : cylinder J T = cylinder (I ∪ J) U := by rw [← inter_cylinder, h_eq, inter_self] exact hP.congr_cylinder_of_subset hT h_eq_union.symm Finset.subset_union_right end IsProjectiveMeasureFamily /-- A measure `μ` is the projective limit of a family of measures indexed by finite sets of `ι` if for all `I : Finset ι`, the projection from `∀ i, α i` to `∀ i : I, α i` maps `μ` to `P I`. -/ def IsProjectiveLimit (μ : Measure (∀ i, α i)) (P : ∀ J : Finset ι, Measure (∀ j : J, α j)) : Prop := ∀ I : Finset ι, (μ.map fun x : ∀ i, α i ↦ fun i : I ↦ x i) = P I namespace IsProjectiveLimit variable {μ ν : Measure (∀ i, α i)} lemma measure_cylinder (h : IsProjectiveLimit μ P) (I : Finset ι) {s : Set (∀ i : I, α i)} (hs : MeasurableSet s) : μ (cylinder I s) = P I s := by rw [cylinder, ← Measure.map_apply _ hs, h I] exact measurable_pi_lambda _ (fun _ ↦ measurable_pi_apply _) lemma measure_univ_eq (hμ : IsProjectiveLimit μ P) (I : Finset ι) : μ univ = P I univ := by rw [← cylinder_univ I, hμ.measure_cylinder _ MeasurableSet.univ] lemma isFiniteMeasure [∀ i, IsFiniteMeasure (P i)] (hμ : IsProjectiveLimit μ P) : IsFiniteMeasure μ := by constructor rw [hμ.measure_univ_eq (∅ : Finset ι)] exact measure_lt_top _ _ lemma isProbabilityMeasure [∀ i, IsProbabilityMeasure (P i)] (hμ : IsProjectiveLimit μ P) : IsProbabilityMeasure μ := by constructor rw [hμ.measure_univ_eq (∅ : Finset ι)] exact measure_univ lemma measure_univ_unique (hμ : IsProjectiveLimit μ P) (hν : IsProjectiveLimit ν P) : μ univ = ν univ := by rw [hμ.measure_univ_eq (∅ : Finset ι), hν.measure_univ_eq (∅ : Finset ι)] /-- The projective limit of a family of finite measures is unique. -/ theorem unique [∀ i, IsFiniteMeasure (P i)] (hμ : IsProjectiveLimit μ P) (hν : IsProjectiveLimit ν P) : μ = ν := by haveI : IsFiniteMeasure μ := hμ.isFiniteMeasure refine ext_of_generate_finite (measurableCylinders α) generateFrom_measurableCylinders.symm isPiSystem_measurableCylinders (fun s hs ↦ ?_) (hμ.measure_univ_unique hν) obtain ⟨I, S, hS, rfl⟩ := (mem_measurableCylinders _).mp hs rw [hμ.measure_cylinder _ hS, hν.measure_cylinder _ hS] end IsProjectiveLimit end MeasureTheory
MeasureTheory\Constructions\UnitInterval.lean
/- Copyright (c) 2024 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Topology.UnitInterval import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic import Mathlib.MeasureTheory.Measure.Haar.OfBasis import Mathlib.MeasureTheory.Measure.Lebesgue.Basic /-! # The canonical measure on the unit interval This file provides a `MeasureTheory.MeasureSpace` instance on `unitInterval`, and shows it is a probability measure. -/ open scoped unitInterval open MeasureTheory namespace unitInterval noncomputable instance : MeasureSpace I := Measure.Subtype.measureSpace theorem volume_def : (volume : Measure I) = volume.comap Subtype.val := rfl instance : IsProbabilityMeasure (volume : Measure I) where measure_univ := by rw [Measure.Subtype.volume_univ measurableSet_Icc.nullMeasurableSet, Real.volume_Icc, sub_zero, ENNReal.ofReal_one] @[measurability] theorem measurable_symm : Measurable symm := continuous_symm.measurable end unitInterval
MeasureTheory\Constructions\BorelSpace\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, Yury Kudryashov -/ import Mathlib.MeasureTheory.Group.Arithmetic import Mathlib.Topology.GDelta import Mathlib.Topology.Instances.EReal import Mathlib.Topology.Instances.Rat /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class BorelSpace` : a space with `TopologicalSpace` and `MeasurableSpace` structures such that `‹MeasurableSpace α› = borel α`; * `class OpensMeasurableSpace` : a space with `TopologicalSpace` and `MeasurableSpace` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹MeasurableSpace α›`. * `BorelSpace` instances on `Empty`, `Unit`, `Bool`, `Nat`, `Int`, `Rat`; * `MeasurableSpace` and `BorelSpace` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `IsOpen.measurableSet`, `IsClosed.measurableSet`: open and closed sets are measurable; * `Continuous.measurable` : a continuous function is measurable; * `Continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `fun x => op (f x, g y)` is measurable; * `Measurable.add` etc : dot notation for arithmetic operations on `Measurable` predicates, and similarly for `dist` and `edist`; * `AEMeasurable.add` : similar dot notation for almost everywhere measurable functions; -/ noncomputable section open Set Filter MeasureTheory open scoped Topology NNReal ENNReal MeasureTheory universe u v w x y variable {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : Set α} open MeasurableSpace TopologicalSpace /-- `MeasurableSpace` structure generated by `TopologicalSpace`. -/ def borel (α : Type u) [TopologicalSpace α] : MeasurableSpace α := generateFrom { s : Set α | IsOpen s } theorem borel_anti : Antitone (@borel α) := fun _ _ h => MeasurableSpace.generateFrom_le fun _ hs => .basic _ (h _ hs) theorem borel_eq_top_of_discrete [TopologicalSpace α] [DiscreteTopology α] : borel α = ⊤ := top_le_iff.1 fun s _ => GenerateMeasurable.basic s (isOpen_discrete s) theorem borel_eq_top_of_countable [TopologicalSpace α] [T1Space α] [Countable α] : borel α = ⊤ := by refine top_le_iff.1 fun s _ => biUnion_of_singleton s ▸ ?_ apply MeasurableSet.biUnion s.to_countable intro x _ apply MeasurableSet.of_compl apply GenerateMeasurable.basic exact isClosed_singleton.isOpen_compl theorem borel_eq_generateFrom_of_subbasis {s : Set (Set α)} [t : TopologicalSpace α] [SecondCountableTopology α] (hs : t = .generateFrom s) : borel α = .generateFrom s := le_antisymm (generateFrom_le fun u (hu : t.IsOpen u) => by rw [hs] at hu induction hu with | basic u hu => exact GenerateMeasurable.basic u hu | univ => exact @MeasurableSet.univ α (generateFrom s) | inter s₁ s₂ _ _ hs₁ hs₂ => exact @MeasurableSet.inter α (generateFrom s) _ _ hs₁ hs₂ | sUnion f hf ih => rcases isOpen_sUnion_countable f (by rwa [hs]) with ⟨v, hv, vf, vu⟩ rw [← vu] exact @MeasurableSet.sUnion α (generateFrom s) _ hv fun x xv => ih _ (vf xv)) (generateFrom_le fun u hu => GenerateMeasurable.basic _ <| show t.IsOpen u by rw [hs]; exact GenerateOpen.basic _ hu) theorem TopologicalSpace.IsTopologicalBasis.borel_eq_generateFrom [TopologicalSpace α] [SecondCountableTopology α] {s : Set (Set α)} (hs : IsTopologicalBasis s) : borel α = .generateFrom s := borel_eq_generateFrom_of_subbasis hs.eq_generateFrom theorem isPiSystem_isOpen [TopologicalSpace α] : IsPiSystem ({s : Set α | IsOpen s}) := fun _s hs _t ht _ => IsOpen.inter hs ht lemma isPiSystem_isClosed [TopologicalSpace α] : IsPiSystem ({s : Set α | IsClosed s}) := fun _s hs _t ht _ ↦ IsClosed.inter hs ht theorem borel_eq_generateFrom_isClosed [TopologicalSpace α] : borel α = .generateFrom { s | IsClosed s } := le_antisymm (generateFrom_le fun _t ht => @MeasurableSet.of_compl α _ (generateFrom { s | IsClosed s }) (GenerateMeasurable.basic _ <| isClosed_compl_iff.2 ht)) (generateFrom_le fun _t ht => @MeasurableSet.of_compl α _ (borel α) (GenerateMeasurable.basic _ <| isOpen_compl_iff.2 ht)) theorem borel_comap {f : α → β} {t : TopologicalSpace β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generateFrom.symm theorem Continuous.borel_measurable [TopologicalSpace α] [TopologicalSpace β] {f : α → β} (hf : Continuous f) : @Measurable α β (borel α) (borel β) f := Measurable.of_le_map <| generateFrom_le fun s hs => GenerateMeasurable.basic (f ⁻¹' s) (hs.preimage hf) /-- A space with `MeasurableSpace` and `TopologicalSpace` structures such that all open sets are measurable. -/ class OpensMeasurableSpace (α : Type*) [TopologicalSpace α] [h : MeasurableSpace α] : Prop where /-- Borel-measurable sets are measurable. -/ borel_le : borel α ≤ h /-- A space with `MeasurableSpace` and `TopologicalSpace` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class BorelSpace (α : Type*) [TopologicalSpace α] [MeasurableSpace α] : Prop where /-- The measurable sets are exactly the Borel-measurable sets. -/ measurable_eq : ‹MeasurableSpace α› = borel α namespace Mathlib.Tactic.Borelize open Lean Elab Term Tactic Meta /-- The behaviour of `borelize α` depends on the existing assumptions on `α`. - if `α` is a topological space with instances `[MeasurableSpace α] [BorelSpace α]`, then `borelize α` replaces the former instance by `borel α`; - otherwise, `borelize α` adds instances `borel α : MeasurableSpace α` and `⟨rfl⟩ : BorelSpace α`. Finally, `borelize α β γ` runs `borelize α; borelize β; borelize γ`. -/ syntax "borelize" (ppSpace colGt term:max)* : tactic /-- Add instances `borel e : MeasurableSpace e` and `⟨rfl⟩ : BorelSpace e`. -/ def addBorelInstance (e : Expr) : TacticM Unit := do let t ← Lean.Elab.Term.exprToSyntax e evalTactic <| ← `(tactic| refine_lift letI : MeasurableSpace $t := borel $t haveI : BorelSpace $t := ⟨rfl⟩ ?_) /-- Given a type `e`, an assumption `i : MeasurableSpace e`, and an instance `[BorelSpace e]`, replace `i` with `borel e`. -/ def borelToRefl (e : Expr) (i : FVarId) : TacticM Unit := do let te ← Lean.Elab.Term.exprToSyntax e evalTactic <| ← `(tactic| have := @BorelSpace.measurable_eq $te _ _ _) try liftMetaTactic fun m => return [← subst m i] catch _ => let et ← synthInstance (← mkAppOptM ``TopologicalSpace #[e]) throwError m!"\ `‹TopologicalSpace {e}› := {et}\n\ depends on\n\ {Expr.fvar i} : MeasurableSpace {e}`\n\ so `borelize` isn't avaliable" evalTactic <| ← `(tactic| refine_lift letI : MeasurableSpace $te := borel $te ?_) /-- Given a type `$t`, if there is an assumption `[i : MeasurableSpace $t]`, then try to prove `[BorelSpace $t]` and replace `i` with `borel $t`. Otherwise, add instances `borel $t : MeasurableSpace $t` and `⟨rfl⟩ : BorelSpace $t`. -/ def borelize (t : Term) : TacticM Unit := withMainContext <| do let u ← mkFreshLevelMVar let e ← withoutRecover <| Tactic.elabTermEnsuringType t (mkSort (mkLevelSucc u)) let i? ← findLocalDeclWithType? (← mkAppOptM ``MeasurableSpace #[e]) i?.elim (addBorelInstance e) (borelToRefl e) elab_rules : tactic | `(tactic| borelize $[$t:term]*) => t.forM borelize end Mathlib.Tactic.Borelize instance (priority := 100) OrderDual.opensMeasurableSpace {α : Type*} [TopologicalSpace α] [MeasurableSpace α] [h : OpensMeasurableSpace α] : OpensMeasurableSpace αᵒᵈ where borel_le := h.borel_le instance (priority := 100) OrderDual.borelSpace {α : Type*} [TopologicalSpace α] [MeasurableSpace α] [h : BorelSpace α] : BorelSpace αᵒᵈ where measurable_eq := h.measurable_eq /-- In a `BorelSpace` all open sets are measurable. -/ instance (priority := 100) BorelSpace.opensMeasurable {α : Type*} [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] : OpensMeasurableSpace α := ⟨ge_of_eq <| BorelSpace.measurable_eq⟩ instance Subtype.borelSpace {α : Type*} [TopologicalSpace α] [MeasurableSpace α] [hα : BorelSpace α] (s : Set α) : BorelSpace s := ⟨by borelize α; symm; apply borel_comap⟩ instance Countable.instBorelSpace [Countable α] [MeasurableSpace α] [MeasurableSingletonClass α] [TopologicalSpace α] [DiscreteTopology α] : BorelSpace α := by have : ∀ s, @MeasurableSet α inferInstance s := fun s ↦ s.to_countable.measurableSet have : ∀ s, @MeasurableSet α (borel α) s := fun s ↦ measurableSet_generateFrom (isOpen_discrete s) exact ⟨by aesop⟩ instance Subtype.opensMeasurableSpace {α : Type*} [TopologicalSpace α] [MeasurableSpace α] [h : OpensMeasurableSpace α] (s : Set α) : OpensMeasurableSpace s := ⟨by rw [borel_comap] exact comap_mono h.1⟩ lemma opensMeasurableSpace_iff_forall_measurableSet [TopologicalSpace α] [MeasurableSpace α] : OpensMeasurableSpace α ↔ (∀ (s : Set α), IsOpen s → MeasurableSet s) := by refine ⟨fun h s hs ↦ ?_, fun h ↦ ⟨generateFrom_le h⟩⟩ exact OpensMeasurableSpace.borel_le _ <| GenerateMeasurable.basic _ hs instance (priority := 100) BorelSpace.countablyGenerated {α : Type*} [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] [SecondCountableTopology α] : CountablyGenerated α := by obtain ⟨b, bct, -, hb⟩ := exists_countable_basis α refine ⟨⟨b, bct, ?_⟩⟩ borelize α exact hb.borel_eq_generateFrom theorem MeasurableSet.induction_on_open [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] {C : Set α → Prop} (h_open : ∀ U, IsOpen U → C U) (h_compl : ∀ t, MeasurableSet t → C t → C tᶜ) (h_union : ∀ f : ℕ → Set α, Pairwise (Disjoint on f) → (∀ i, MeasurableSet (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, MeasurableSet t → C t := MeasurableSpace.induction_on_inter BorelSpace.measurable_eq isPiSystem_isOpen (h_open _ isOpen_empty) h_open h_compl h_union section variable [TopologicalSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] [TopologicalSpace β] [MeasurableSpace β] [OpensMeasurableSpace β] [TopologicalSpace γ] [MeasurableSpace γ] [BorelSpace γ] [TopologicalSpace γ₂] [MeasurableSpace γ₂] [BorelSpace γ₂] [MeasurableSpace δ] theorem IsOpen.measurableSet (h : IsOpen s) : MeasurableSet s := OpensMeasurableSpace.borel_le _ <| GenerateMeasurable.basic _ h theorem IsOpen.nullMeasurableSet {μ} (h : IsOpen s) : NullMeasurableSet s μ := h.measurableSet.nullMeasurableSet instance (priority := 1000) {s : Set α} [h : HasCountableSeparatingOn α IsOpen s] : CountablySeparated s := by rw [CountablySeparated.subtype_iff] exact .mono (fun _ ↦ IsOpen.measurableSet) Subset.rfl @[measurability] theorem measurableSet_interior : MeasurableSet (interior s) := isOpen_interior.measurableSet theorem IsGδ.measurableSet (h : IsGδ s) : MeasurableSet s := by rcases h with ⟨S, hSo, hSc, rfl⟩ exact MeasurableSet.sInter hSc fun t ht => (hSo t ht).measurableSet theorem measurableSet_of_continuousAt {β} [EMetricSpace β] (f : α → β) : MeasurableSet { x | ContinuousAt f x } := (IsGδ.setOf_continuousAt f).measurableSet theorem IsClosed.measurableSet (h : IsClosed s) : MeasurableSet s := h.isOpen_compl.measurableSet.of_compl theorem IsClosed.nullMeasurableSet {μ} (h : IsClosed s) : NullMeasurableSet s μ := h.measurableSet.nullMeasurableSet theorem IsCompact.measurableSet [T2Space α] (h : IsCompact s) : MeasurableSet s := h.isClosed.measurableSet /-- If two points are topologically inseparable, then they can't be separated by a Borel measurable set. -/ theorem Inseparable.mem_measurableSet_iff {x y : γ} (h : Inseparable x y) {s : Set γ} (hs : MeasurableSet s) : x ∈ s ↔ y ∈ s := hs.induction_on_open (C := fun s ↦ (x ∈ s ↔ y ∈ s)) (fun _ ↦ h.mem_open_iff) (fun s _ ↦ Iff.not) fun _ _ _ h ↦ by simp [h] /-- If `K` is a compact set in an R₁ space and `s ⊇ K` is a Borel measurable superset, then `s` includes the closure of `K` as well. -/ theorem IsCompact.closure_subset_measurableSet [R1Space γ] {K s : Set γ} (hK : IsCompact K) (hs : MeasurableSet s) (hKs : K ⊆ s) : closure K ⊆ s := by rw [hK.closure_eq_biUnion_inseparable, iUnion₂_subset_iff] exact fun x hx y hy ↦ (hy.mem_measurableSet_iff hs).1 (hKs hx) /-- In an R₁ topological space with Borel measure `μ`, the measure of the closure of a compact set `K` is equal to the measure of `K`. See also `MeasureTheory.Measure.OuterRegular.measure_closure_eq_of_isCompact` for a version that assumes `μ` to be outer regular but does not assume the `σ`-algebra to be Borel. -/ theorem IsCompact.measure_closure [R1Space γ] {K : Set γ} (hK : IsCompact K) (μ : Measure γ) : μ (closure K) = μ K := by refine le_antisymm ?_ (measure_mono subset_closure) calc μ (closure K) ≤ μ (toMeasurable μ K) := measure_mono <| hK.closure_subset_measurableSet (measurableSet_toMeasurable ..) (subset_toMeasurable ..) _ = μ K := measure_toMeasurable .. @[measurability] theorem measurableSet_closure : MeasurableSet (closure s) := isClosed_closure.measurableSet theorem measurable_of_isOpen {f : δ → γ} (hf : ∀ s, IsOpen s → MeasurableSet (f ⁻¹' s)) : Measurable f := by rw [‹BorelSpace γ›.measurable_eq] exact measurable_generateFrom hf theorem measurable_of_isClosed {f : δ → γ} (hf : ∀ s, IsClosed s → MeasurableSet (f ⁻¹' s)) : Measurable f := by apply measurable_of_isOpen; intro s hs rw [← MeasurableSet.compl_iff, ← preimage_compl]; apply hf; rw [isClosed_compl_iff]; exact hs theorem measurable_of_isClosed' {f : δ → γ} (hf : ∀ s, IsClosed s → s.Nonempty → s ≠ univ → MeasurableSet (f ⁻¹' s)) : Measurable f := by apply measurable_of_isClosed; intro s hs rcases eq_empty_or_nonempty s with h1 | h1 · simp [h1] by_cases h2 : s = univ · simp [h2] exact hf s hs h1 h2 instance nhds_isMeasurablyGenerated (a : α) : (𝓝 a).IsMeasurablyGenerated := by rw [nhds, iInf_subtype'] refine @Filter.iInf_isMeasurablyGenerated α _ _ _ fun i => ?_ exact i.2.2.measurableSet.principal_isMeasurablyGenerated /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : MeasurableSet s`. -/ theorem MeasurableSet.nhdsWithin_isMeasurablyGenerated {s : Set α} (hs : MeasurableSet s) (a : α) : (𝓝[s] a).IsMeasurablyGenerated := haveI := hs.principal_isMeasurablyGenerated Filter.inf_isMeasurablyGenerated _ _ instance (priority := 100) OpensMeasurableSpace.separatesPoints [T0Space α] : SeparatesPoints α := by rw [separatesPoints_iff] intro x y hxy apply Inseparable.eq rw [inseparable_iff_forall_open] exact fun s hs => hxy _ hs.measurableSet -- see Note [lower instance priority] instance (priority := 100) OpensMeasurableSpace.toMeasurableSingletonClass [T1Space α] : MeasurableSingletonClass α := ⟨fun _ => isClosed_singleton.measurableSet⟩ instance Pi.opensMeasurableSpace {ι : Type*} {π : ι → Type*} [Countable ι] [t' : ∀ i, TopologicalSpace (π i)] [∀ i, MeasurableSpace (π i)] [∀ i, SecondCountableTopology (π i)] [∀ i, OpensMeasurableSpace (π i)] : OpensMeasurableSpace (∀ i, π i) := by constructor have : Pi.topologicalSpace = .generateFrom { t | ∃ (s : ∀ a, Set (π a)) (i : Finset ι), (∀ a ∈ i, s a ∈ countableBasis (π a)) ∧ t = pi (↑i) s } := by simp only [funext fun a => @eq_generateFrom_countableBasis (π a) _ _, pi_generateFrom_eq] rw [borel_eq_generateFrom_of_subbasis this] apply generateFrom_le rintro _ ⟨s, i, hi, rfl⟩ refine MeasurableSet.pi i.countable_toSet fun a ha => IsOpen.measurableSet ?_ rw [eq_generateFrom_countableBasis (π a)] exact .basic _ (hi a ha) /-- The typeclass `SecondCountableTopologyEither α β` registers the fact that at least one of the two spaces has second countable topology. This is the right assumption to ensure that continuous maps from `α` to `β` are strongly measurable. -/ class SecondCountableTopologyEither (α β : Type*) [TopologicalSpace α] [TopologicalSpace β] : Prop where /-- The projection out of `SecondCountableTopologyEither` -/ out : SecondCountableTopology α ∨ SecondCountableTopology β instance (priority := 100) secondCountableTopologyEither_of_left (α β : Type*) [TopologicalSpace α] [TopologicalSpace β] [SecondCountableTopology α] : SecondCountableTopologyEither α β where out := Or.inl (by infer_instance) instance (priority := 100) secondCountableTopologyEither_of_right (α β : Type*) [TopologicalSpace α] [TopologicalSpace β] [SecondCountableTopology β] : SecondCountableTopologyEither α β where out := Or.inr (by infer_instance) /-- If either `α` or `β` has second-countable topology, then the open sets in `α × β` belong to the product sigma-algebra. -/ instance Prod.opensMeasurableSpace [h : SecondCountableTopologyEither α β] : OpensMeasurableSpace (α × β) := by apply opensMeasurableSpace_iff_forall_measurableSet.2 (fun s hs ↦ ?_) rcases h.out with hα|hβ · let F : Set α → Set β := fun a ↦ {y | ∃ b, IsOpen b ∧ y ∈ b ∧ a ×ˢ b ⊆ s} have A : ∀ a, IsOpen (F a) := by intro a apply isOpen_iff_forall_mem_open.2 rintro y ⟨b, b_open, yb, hb⟩ exact ⟨b, fun z zb ↦ ⟨b, b_open, zb, hb⟩, b_open, yb⟩ have : s = ⋃ a ∈ countableBasis α, a ×ˢ F a := by apply Subset.antisymm · rintro ⟨y1, y2⟩ hy rcases isOpen_prod_iff.1 hs y1 y2 hy with ⟨u, v, u_open, v_open, yu, yv, huv⟩ obtain ⟨a, ha, ya, au⟩ : ∃ a ∈ countableBasis α, y1 ∈ a ∧ a ⊆ u := IsTopologicalBasis.exists_subset_of_mem_open (isBasis_countableBasis α) yu u_open simp only [mem_iUnion, mem_prod, mem_setOf_eq, exists_and_left, exists_prop] exact ⟨a, ya, ha, v, v_open, yv, (Set.prod_mono_left au).trans huv⟩ · rintro ⟨y1, y2⟩ hy simp only [mem_iUnion, mem_prod, mem_setOf_eq, exists_and_left, exists_prop] at hy rcases hy with ⟨a, ya, -, b, -, yb, hb⟩ exact hb (mem_prod.2 ⟨ya, yb⟩) rw [this] apply MeasurableSet.biUnion (countable_countableBasis α) (fun a ha ↦ ?_) exact (isOpen_of_mem_countableBasis ha).measurableSet.prod (A a).measurableSet · let F : Set β → Set α := fun a ↦ {y | ∃ b, IsOpen b ∧ y ∈ b ∧ b ×ˢ a ⊆ s} have A : ∀ a, IsOpen (F a) := by intro a apply isOpen_iff_forall_mem_open.2 rintro y ⟨b, b_open, yb, hb⟩ exact ⟨b, fun z zb ↦ ⟨b, b_open, zb, hb⟩, b_open, yb⟩ have : s = ⋃ a ∈ countableBasis β, F a ×ˢ a := by apply Subset.antisymm · rintro ⟨y1, y2⟩ hy rcases isOpen_prod_iff.1 hs y1 y2 hy with ⟨u, v, u_open, v_open, yu, yv, huv⟩ obtain ⟨a, ha, ya, au⟩ : ∃ a ∈ countableBasis β, y2 ∈ a ∧ a ⊆ v := IsTopologicalBasis.exists_subset_of_mem_open (isBasis_countableBasis β) yv v_open simp only [mem_iUnion, mem_prod, mem_setOf_eq, exists_and_left, exists_prop] exact ⟨a, ⟨u, u_open, yu, (Set.prod_mono_right au).trans huv⟩, ha, ya⟩ · rintro ⟨y1, y2⟩ hy simp only [mem_iUnion, mem_prod, mem_setOf_eq, exists_and_left, exists_prop] at hy rcases hy with ⟨a, ⟨b, -, yb, hb⟩, -, ya⟩ exact hb (mem_prod.2 ⟨yb, ya⟩) rw [this] apply MeasurableSet.biUnion (countable_countableBasis β) (fun a ha ↦ ?_) exact (A a).measurableSet.prod (isOpen_of_mem_countableBasis ha).measurableSet variable {α' : Type*} [TopologicalSpace α'] [MeasurableSpace α'] theorem interior_ae_eq_of_null_frontier {μ : Measure α'} {s : Set α'} (h : μ (frontier s) = 0) : interior s =ᵐ[μ] s := interior_subset.eventuallyLE.antisymm <| subset_closure.eventuallyLE.trans (ae_le_set.2 h) theorem measure_interior_of_null_frontier {μ : Measure α'} {s : Set α'} (h : μ (frontier s) = 0) : μ (interior s) = μ s := measure_congr (interior_ae_eq_of_null_frontier h) theorem nullMeasurableSet_of_null_frontier {s : Set α} {μ : Measure α} (h : μ (frontier s) = 0) : NullMeasurableSet s μ := ⟨interior s, isOpen_interior.measurableSet, (interior_ae_eq_of_null_frontier h).symm⟩ theorem closure_ae_eq_of_null_frontier {μ : Measure α'} {s : Set α'} (h : μ (frontier s) = 0) : closure s =ᵐ[μ] s := ((ae_le_set.2 h).trans interior_subset.eventuallyLE).antisymm <| subset_closure.eventuallyLE theorem measure_closure_of_null_frontier {μ : Measure α'} {s : Set α'} (h : μ (frontier s) = 0) : μ (closure s) = μ s := measure_congr (closure_ae_eq_of_null_frontier h) instance separatesPointsOfOpensMeasurableSpaceOfT0Space [T0Space α] : MeasurableSpace.SeparatesPoints α where separates x y := by contrapose! intro x_ne_y obtain ⟨U, U_open, mem_U⟩ := exists_isOpen_xor'_mem x_ne_y by_cases x_in_U : x ∈ U · refine ⟨U, U_open.measurableSet, x_in_U, ?_⟩ simp_all only [ne_eq, xor_true, not_false_eq_true] · refine ⟨Uᶜ, U_open.isClosed_compl.measurableSet, x_in_U, ?_⟩ simp_all only [ne_eq, xor_false, id_eq, mem_compl_iff, not_true_eq_false, not_false_eq_true] /-- A continuous function from an `OpensMeasurableSpace` to a `BorelSpace` is measurable. -/ @[fun_prop] theorem Continuous.measurable {f : α → γ} (hf : Continuous f) : Measurable f := hf.borel_measurable.mono OpensMeasurableSpace.borel_le (le_of_eq <| BorelSpace.measurable_eq) /-- A continuous function from an `OpensMeasurableSpace` to a `BorelSpace` is ae-measurable. -/ theorem Continuous.aemeasurable {f : α → γ} (h : Continuous f) {μ : Measure α} : AEMeasurable f μ := h.measurable.aemeasurable theorem ClosedEmbedding.measurable {f : α → γ} (hf : ClosedEmbedding f) : Measurable f := hf.continuous.measurable /-- If a function is defined piecewise in terms of functions which are continuous on their respective pieces, then it is measurable. -/ theorem ContinuousOn.measurable_piecewise {f g : α → γ} {s : Set α} [∀ j : α, Decidable (j ∈ s)] (hf : ContinuousOn f s) (hg : ContinuousOn g sᶜ) (hs : MeasurableSet s) : Measurable (s.piecewise f g) := by refine measurable_of_isOpen fun t ht => ?_ rw [piecewise_preimage, Set.ite] apply MeasurableSet.union · rcases _root_.continuousOn_iff'.1 hf t ht with ⟨u, u_open, hu⟩ rw [hu] exact u_open.measurableSet.inter hs · rcases _root_.continuousOn_iff'.1 hg t ht with ⟨u, u_open, hu⟩ rw [diff_eq_compl_inter, inter_comm, hu] exact u_open.measurableSet.inter hs.compl @[to_additive] instance (priority := 100) ContinuousMul.measurableMul [Mul γ] [ContinuousMul γ] : MeasurableMul γ where measurable_const_mul _ := (continuous_const.mul continuous_id).measurable measurable_mul_const _ := (continuous_id.mul continuous_const).measurable instance (priority := 100) ContinuousSub.measurableSub [Sub γ] [ContinuousSub γ] : MeasurableSub γ where measurable_const_sub _ := (continuous_const.sub continuous_id).measurable measurable_sub_const _ := (continuous_id.sub continuous_const).measurable @[to_additive] instance (priority := 100) TopologicalGroup.measurableInv [Group γ] [TopologicalGroup γ] : MeasurableInv γ := ⟨continuous_inv.measurable⟩ instance (priority := 100) ContinuousSMul.measurableSMul {M α} [TopologicalSpace M] [TopologicalSpace α] [MeasurableSpace M] [MeasurableSpace α] [OpensMeasurableSpace M] [BorelSpace α] [SMul M α] [ContinuousSMul M α] : MeasurableSMul M α := ⟨fun _ => (continuous_const_smul _).measurable, fun _ => (continuous_id.smul continuous_const).measurable⟩ section Homeomorph @[measurability] protected theorem Homeomorph.measurable (h : α ≃ₜ γ) : Measurable h := h.continuous.measurable /-- A homeomorphism between two Borel spaces is a measurable equivalence. -/ def Homeomorph.toMeasurableEquiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ where measurable_toFun := h.measurable measurable_invFun := h.symm.measurable toEquiv := h.toEquiv lemma Homeomorph.measurableEmbedding (h : γ ≃ₜ γ₂) : MeasurableEmbedding h := h.toMeasurableEquiv.measurableEmbedding @[simp] theorem Homeomorph.toMeasurableEquiv_coe (h : γ ≃ₜ γ₂) : (h.toMeasurableEquiv : γ → γ₂) = h := rfl @[simp] theorem Homeomorph.toMeasurableEquiv_symm_coe (h : γ ≃ₜ γ₂) : (h.toMeasurableEquiv.symm : γ₂ → γ) = h.symm := rfl end Homeomorph @[measurability] theorem ContinuousMap.measurable (f : C(α, γ)) : Measurable f := f.continuous.measurable @[fun_prop] theorem measurable_of_continuousOn_compl_singleton [T1Space α] {f : α → γ} (a : α) (hf : ContinuousOn f {a}ᶜ) : Measurable f := measurable_of_measurable_on_compl_singleton a (continuousOn_iff_continuous_restrict.1 hf).measurable theorem Continuous.measurable2 [SecondCountableTopologyEither α β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : Continuous fun p : α × β => c p.1 p.2) (hf : Measurable f) (hg : Measurable g) : Measurable fun a => c (f a) (g a) := h.measurable.comp (hf.prod_mk hg) theorem Continuous.aemeasurable2 [SecondCountableTopologyEither α β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : Measure δ} (h : Continuous fun p : α × β => c p.1 p.2) (hf : AEMeasurable f μ) (hg : AEMeasurable g μ) : AEMeasurable (fun a => c (f a) (g a)) μ := h.measurable.comp_aemeasurable (hf.prod_mk hg) instance (priority := 100) HasContinuousInv₀.measurableInv [GroupWithZero γ] [T1Space γ] [HasContinuousInv₀ γ] : MeasurableInv γ := ⟨measurable_of_continuousOn_compl_singleton 0 continuousOn_inv₀⟩ @[to_additive] instance (priority := 100) ContinuousMul.measurableMul₂ [SecondCountableTopology γ] [Mul γ] [ContinuousMul γ] : MeasurableMul₂ γ := ⟨continuous_mul.measurable⟩ instance (priority := 100) ContinuousSub.measurableSub₂ [SecondCountableTopology γ] [Sub γ] [ContinuousSub γ] : MeasurableSub₂ γ := ⟨continuous_sub.measurable⟩ instance (priority := 100) ContinuousSMul.measurableSMul₂ {M α} [TopologicalSpace M] [MeasurableSpace M] [OpensMeasurableSpace M] [TopologicalSpace α] [SecondCountableTopologyEither M α] [MeasurableSpace α] [BorelSpace α] [SMul M α] [ContinuousSMul M α] : MeasurableSMul₂ M α := ⟨continuous_smul.measurable⟩ end section BorelSpace variable [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] [TopologicalSpace β] [MeasurableSpace β] [BorelSpace β] [TopologicalSpace γ] [MeasurableSpace γ] [BorelSpace γ] [MeasurableSpace δ] theorem pi_le_borel_pi {ι : Type*} {π : ι → Type*} [∀ i, TopologicalSpace (π i)] [∀ i, MeasurableSpace (π i)] [∀ i, BorelSpace (π i)] : MeasurableSpace.pi ≤ borel (∀ i, π i) := by have : ‹∀ i, MeasurableSpace (π i)› = fun i => borel (π i) := funext fun i => BorelSpace.measurable_eq rw [this] exact iSup_le fun i => comap_le_iff_le_map.2 <| (continuous_apply i).borel_measurable theorem prod_le_borel_prod : Prod.instMeasurableSpace ≤ borel (α × β) := by rw [‹BorelSpace α›.measurable_eq, ‹BorelSpace β›.measurable_eq] refine sup_le ?_ ?_ · exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable · exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable instance Pi.borelSpace {ι : Type*} {π : ι → Type*} [Countable ι] [∀ i, TopologicalSpace (π i)] [∀ i, MeasurableSpace (π i)] [∀ i, SecondCountableTopology (π i)] [∀ i, BorelSpace (π i)] : BorelSpace (∀ i, π i) := ⟨le_antisymm pi_le_borel_pi OpensMeasurableSpace.borel_le⟩ instance Prod.borelSpace [SecondCountableTopologyEither α β] : BorelSpace (α × β) := ⟨le_antisymm prod_le_borel_prod OpensMeasurableSpace.borel_le⟩ /-- Given a measurable embedding to a Borel space which is also a topological embedding, then the source space is also a Borel space. -/ lemma MeasurableEmbedding.borelSpace {α β : Type*} [MeasurableSpace α] [TopologicalSpace α] [MeasurableSpace β] [TopologicalSpace β] [hβ : BorelSpace β] {e : α → β} (h'e : MeasurableEmbedding e) (h''e : Inducing e) : BorelSpace α := by constructor have : MeasurableSpace.comap e (borel β) = ‹_› := by simpa [hβ.measurable_eq] using h'e.comap_eq rw [← this, ← borel_comap, h''e.induced] instance _root_.ULift.instBorelSpace : BorelSpace (ULift α) := MeasurableEquiv.ulift.measurableEmbedding.borelSpace Homeomorph.ulift.inducing instance DiscreteMeasurableSpace.toBorelSpace {α : Type*} [TopologicalSpace α] [DiscreteTopology α] [MeasurableSpace α] [DiscreteMeasurableSpace α] : BorelSpace α := by constructor; ext; simp [MeasurableSpace.measurableSet_generateFrom, measurableSet_discrete] protected theorem Embedding.measurableEmbedding {f : α → β} (h₁ : Embedding f) (h₂ : MeasurableSet (range f)) : MeasurableEmbedding f := show MeasurableEmbedding (((↑) : range f → β) ∘ (Homeomorph.ofEmbedding f h₁).toMeasurableEquiv) from (MeasurableEmbedding.subtype_coe h₂).comp (MeasurableEquiv.measurableEmbedding _) protected theorem ClosedEmbedding.measurableEmbedding {f : α → β} (h : ClosedEmbedding f) : MeasurableEmbedding f := h.toEmbedding.measurableEmbedding h.isClosed_range.measurableSet protected theorem OpenEmbedding.measurableEmbedding {f : α → β} (h : OpenEmbedding f) : MeasurableEmbedding f := h.toEmbedding.measurableEmbedding h.isOpen_range.measurableSet instance Empty.borelSpace : BorelSpace Empty := ⟨borel_eq_top_of_discrete.symm⟩ instance Unit.borelSpace : BorelSpace Unit := ⟨borel_eq_top_of_discrete.symm⟩ instance Bool.borelSpace : BorelSpace Bool := ⟨borel_eq_top_of_discrete.symm⟩ instance Nat.borelSpace : BorelSpace ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance Int.borelSpace : BorelSpace ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance Rat.borelSpace : BorelSpace ℚ := ⟨borel_eq_top_of_countable.symm⟩ /- Instances on `Real` and `Complex` are special cases of `RCLike` but without these instances, Lean fails to prove `BorelSpace (ι → ℝ)`, so we leave them here. -/ instance Real.measurableSpace : MeasurableSpace ℝ := borel ℝ instance Real.borelSpace : BorelSpace ℝ := ⟨rfl⟩ instance NNReal.measurableSpace : MeasurableSpace ℝ≥0 := Subtype.instMeasurableSpace instance NNReal.borelSpace : BorelSpace ℝ≥0 := Subtype.borelSpace _ instance ENNReal.measurableSpace : MeasurableSpace ℝ≥0∞ := borel ℝ≥0∞ instance ENNReal.borelSpace : BorelSpace ℝ≥0∞ := ⟨rfl⟩ instance EReal.measurableSpace : MeasurableSpace EReal := borel EReal instance EReal.borelSpace : BorelSpace EReal := ⟨rfl⟩ end BorelSpace
MeasureTheory\Constructions\BorelSpace\Complex.lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Analysis.Complex.Basic import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic /-! # Equip `ℂ` with the Borel sigma-algebra -/ noncomputable section instance (priority := 900) RCLike.measurableSpace {𝕜 : Type*} [RCLike 𝕜] : MeasurableSpace 𝕜 := borel 𝕜 instance (priority := 900) RCLike.borelSpace {𝕜 : Type*} [RCLike 𝕜] : BorelSpace 𝕜 := ⟨rfl⟩ instance Complex.measurableSpace : MeasurableSpace ℂ := borel ℂ instance Complex.borelSpace : BorelSpace ℂ := ⟨rfl⟩
MeasureTheory\Constructions\BorelSpace\ContinuousLinearMap.lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic import Mathlib.Analysis.NormedSpace.OperatorNorm.NormedSpace import Mathlib.Topology.Algebra.Module.FiniteDimension /-! # Measurable functions in normed spaces -/ open MeasureTheory variable {α : Type*} [MeasurableSpace α] namespace ContinuousLinearMap variable {𝕜 : Type*} [NormedField 𝕜] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [MeasurableSpace E] [OpensMeasurableSpace E] {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] [MeasurableSpace F] [BorelSpace F] @[fun_prop, measurability] protected theorem measurable (L : E →L[𝕜] F) : Measurable L := L.continuous.measurable @[fun_prop] theorem measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : Measurable φ) : Measurable fun a : α => L (φ a) := L.measurable.comp φ_meas end ContinuousLinearMap namespace ContinuousLinearMap variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] instance instMeasurableSpace : MeasurableSpace (E →L[𝕜] F) := borel _ instance instBorelSpace : BorelSpace (E →L[𝕜] F) := ⟨rfl⟩ @[fun_prop, measurability] theorem measurable_apply [MeasurableSpace F] [BorelSpace F] (x : E) : Measurable fun f : E →L[𝕜] F => f x := (apply 𝕜 F x).continuous.measurable @[measurability] theorem measurable_apply' [MeasurableSpace E] [OpensMeasurableSpace E] [MeasurableSpace F] [BorelSpace F] : Measurable fun (x : E) (f : E →L[𝕜] F) => f x := measurable_pi_lambda _ fun f => f.measurable @[measurability] theorem measurable_coe [MeasurableSpace F] [BorelSpace F] : Measurable fun (f : E →L[𝕜] F) (x : E) => f x := measurable_pi_lambda _ measurable_apply end ContinuousLinearMap section ContinuousLinearMapNontriviallyNormedField variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [MeasurableSpace E] [BorelSpace E] {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] @[fun_prop, measurability] theorem Measurable.apply_continuousLinearMap {φ : α → F →L[𝕜] E} (hφ : Measurable φ) (v : F) : Measurable fun a => φ a v := (ContinuousLinearMap.apply 𝕜 E v).measurable.comp hφ @[measurability] theorem AEMeasurable.apply_continuousLinearMap {φ : α → F →L[𝕜] E} {μ : Measure α} (hφ : AEMeasurable φ μ) (v : F) : AEMeasurable (fun a => φ a v) μ := (ContinuousLinearMap.apply 𝕜 E v).measurable.comp_aemeasurable hφ end ContinuousLinearMapNontriviallyNormedField section NormedSpace variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] [CompleteSpace 𝕜] [MeasurableSpace 𝕜] variable [BorelSpace 𝕜] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [MeasurableSpace E] [BorelSpace E] theorem measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : (Measurable fun x => f x • c) ↔ Measurable f := (closedEmbedding_smul_left hc).measurableEmbedding.measurable_comp_iff theorem aemeasurable_smul_const {f : α → 𝕜} {μ : Measure α} {c : E} (hc : c ≠ 0) : AEMeasurable (fun x => f x • c) μ ↔ AEMeasurable f μ := (closedEmbedding_smul_left hc).measurableEmbedding.aemeasurable_comp_iff end NormedSpace
MeasureTheory\Constructions\BorelSpace\Metric.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.Analysis.Normed.Group.Basic import Mathlib.MeasureTheory.Constructions.BorelSpace.Real import Mathlib.Topology.MetricSpace.Thickening /-! # Borel sigma algebras on (pseudo-)metric spaces ## Main statements * `measurable_dist`, `measurable_infEdist`, `measurable_norm`, `Measurable.dist`, `Measurable.infEdist`, `Measurable.norm`: measurability of various metric-related notions; * `tendsto_measure_thickening_of_isClosed`: the measure of a closed set is the limit of the measure of its ε-thickenings as ε → 0. * `exists_borelSpace_of_countablyGenerated_of_separatesPoints`: if a measurable space is countably generated and separates points, it arises as the Borel sets of some second countable separable metrizable topology. -/ open Set Filter MeasureTheory MeasurableSpace TopologicalSpace open scoped Topology NNReal ENNReal MeasureTheory universe u v w x y variable {α β γ δ : Type*} {ι : Sort y} {s t u : Set α} section PseudoMetricSpace variable [PseudoMetricSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] variable [MeasurableSpace β] {x : α} {ε : ℝ} open Metric @[measurability] theorem measurableSet_ball : MeasurableSet (Metric.ball x ε) := Metric.isOpen_ball.measurableSet @[measurability] theorem measurableSet_closedBall : MeasurableSet (Metric.closedBall x ε) := Metric.isClosed_ball.measurableSet @[measurability] theorem measurable_infDist {s : Set α} : Measurable fun x => infDist x s := (continuous_infDist_pt s).measurable @[measurability, fun_prop] theorem Measurable.infDist {f : β → α} (hf : Measurable f) {s : Set α} : Measurable fun x => infDist (f x) s := measurable_infDist.comp hf @[measurability] theorem measurable_infNndist {s : Set α} : Measurable fun x => infNndist x s := (continuous_infNndist_pt s).measurable @[measurability, fun_prop] theorem Measurable.infNndist {f : β → α} (hf : Measurable f) {s : Set α} : Measurable fun x => infNndist (f x) s := measurable_infNndist.comp hf section variable [SecondCountableTopology α] @[measurability] theorem measurable_dist : Measurable fun p : α × α => dist p.1 p.2 := continuous_dist.measurable @[measurability, fun_prop] theorem Measurable.dist {f g : β → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun b => dist (f b) (g b) := (@continuous_dist α _).measurable2 hf hg @[measurability] theorem measurable_nndist : Measurable fun p : α × α => nndist p.1 p.2 := continuous_nndist.measurable @[measurability, fun_prop] theorem Measurable.nndist {f g : β → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun b => nndist (f b) (g b) := (@continuous_nndist α _).measurable2 hf hg end end PseudoMetricSpace section PseudoEMetricSpace variable [PseudoEMetricSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] variable [MeasurableSpace β] {x : α} {ε : ℝ≥0∞} open EMetric @[measurability] theorem measurableSet_eball : MeasurableSet (EMetric.ball x ε) := EMetric.isOpen_ball.measurableSet @[measurability, fun_prop] theorem measurable_edist_right : Measurable (edist x) := (continuous_const.edist continuous_id).measurable @[measurability, fun_prop] theorem measurable_edist_left : Measurable fun y => edist y x := (continuous_id.edist continuous_const).measurable @[measurability] theorem measurable_infEdist {s : Set α} : Measurable fun x => infEdist x s := continuous_infEdist.measurable @[measurability, fun_prop] theorem Measurable.infEdist {f : β → α} (hf : Measurable f) {s : Set α} : Measurable fun x => infEdist (f x) s := measurable_infEdist.comp hf open Metric EMetric /-- If a set has a closed thickening with finite measure, then the measure of its `r`-closed thickenings converges to the measure of its closure as `r` tends to `0`. -/ theorem tendsto_measure_cthickening {μ : Measure α} {s : Set α} (hs : ∃ R > 0, μ (cthickening R s) ≠ ∞) : Tendsto (fun r => μ (cthickening r s)) (𝓝 0) (𝓝 (μ (closure s))) := by have A : Tendsto (fun r => μ (cthickening r s)) (𝓝[Ioi 0] 0) (𝓝 (μ (closure s))) := by rw [closure_eq_iInter_cthickening] exact tendsto_measure_biInter_gt (fun r _ => isClosed_cthickening.measurableSet) (fun i j _ ij => cthickening_mono ij _) hs have B : Tendsto (fun r => μ (cthickening r s)) (𝓝[Iic 0] 0) (𝓝 (μ (closure s))) := by apply Tendsto.congr' _ tendsto_const_nhds filter_upwards [self_mem_nhdsWithin (α := ℝ)] with _ hr rw [cthickening_of_nonpos hr] convert B.sup A exact (nhds_left_sup_nhds_right' 0).symm /-- If a closed set has a closed thickening with finite measure, then the measure of its closed `r`-thickenings converge to its measure as `r` tends to `0`. -/ theorem tendsto_measure_cthickening_of_isClosed {μ : Measure α} {s : Set α} (hs : ∃ R > 0, μ (cthickening R s) ≠ ∞) (h's : IsClosed s) : Tendsto (fun r => μ (cthickening r s)) (𝓝 0) (𝓝 (μ s)) := by convert tendsto_measure_cthickening hs exact h's.closure_eq.symm /-- If a set has a thickening with finite measure, then the measures of its `r`-thickenings converge to the measure of its closure as `r > 0` tends to `0`. -/ theorem tendsto_measure_thickening {μ : Measure α} {s : Set α} (hs : ∃ R > 0, μ (thickening R s) ≠ ∞) : Tendsto (fun r => μ (thickening r s)) (𝓝[>] 0) (𝓝 (μ (closure s))) := by rw [closure_eq_iInter_thickening] exact tendsto_measure_biInter_gt (fun r _ => isOpen_thickening.measurableSet) (fun i j _ ij => thickening_mono ij _) hs /-- If a closed set has a thickening with finite measure, then the measure of its `r`-thickenings converge to its measure as `r > 0` tends to `0`. -/ theorem tendsto_measure_thickening_of_isClosed {μ : Measure α} {s : Set α} (hs : ∃ R > 0, μ (thickening R s) ≠ ∞) (h's : IsClosed s) : Tendsto (fun r => μ (thickening r s)) (𝓝[>] 0) (𝓝 (μ s)) := by convert tendsto_measure_thickening hs exact h's.closure_eq.symm variable [SecondCountableTopology α] @[measurability] theorem measurable_edist : Measurable fun p : α × α => edist p.1 p.2 := continuous_edist.measurable @[measurability, fun_prop] theorem Measurable.edist {f g : β → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun b => edist (f b) (g b) := (@continuous_edist α _).measurable2 hf hg @[measurability, fun_prop] theorem AEMeasurable.edist {f g : β → α} {μ : Measure β} (hf : AEMeasurable f μ) (hg : AEMeasurable g μ) : AEMeasurable (fun a => edist (f a) (g a)) μ := (@continuous_edist α _).aemeasurable2 hf hg end PseudoEMetricSpace /-- Given a compact set in a proper space, the measure of its `r`-closed thickenings converges to its measure as `r` tends to `0`. -/ theorem tendsto_measure_cthickening_of_isCompact [MetricSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] [ProperSpace α] {μ : Measure α} [IsFiniteMeasureOnCompacts μ] {s : Set α} (hs : IsCompact s) : Tendsto (fun r => μ (Metric.cthickening r s)) (𝓝 0) (𝓝 (μ s)) := tendsto_measure_cthickening_of_isClosed ⟨1, zero_lt_one, hs.isBounded.cthickening.measure_lt_top.ne⟩ hs.isClosed /-- If a measurable space is countably generated and separates points, it arises as the borel sets of some second countable t4 topology (i.e. a separable metrizable one). -/ theorem exists_borelSpace_of_countablyGenerated_of_separatesPoints (α : Type*) [m : MeasurableSpace α] [CountablyGenerated α] [SeparatesPoints α] : ∃ τ : TopologicalSpace α, SecondCountableTopology α ∧ T4Space α ∧ BorelSpace α := by rcases measurableEquiv_nat_bool_of_countablyGenerated α with ⟨s, ⟨f⟩⟩ letI := induced f inferInstance let F := f.toEquiv.toHomeomorphOfInducing $ inducing_induced _ exact ⟨inferInstance, F.secondCountableTopology, F.symm.t4Space, MeasurableEmbedding.borelSpace f.measurableEmbedding F.inducing⟩ /-- If a measurable space on `α` is countably generated and separates points, there is some second countable t4 topology on `α` (i.e. a separable metrizable one) for which every open set is measurable. -/ theorem exists_opensMeasurableSpace_of_countablySeparated (α : Type*) [m : MeasurableSpace α] [CountablySeparated α] : ∃ τ : TopologicalSpace α, SecondCountableTopology α ∧ T4Space α ∧ OpensMeasurableSpace α := by rcases exists_countablyGenerated_le_of_countablySeparated α with ⟨m', _, _, m'le⟩ rcases exists_borelSpace_of_countablyGenerated_of_separatesPoints (m := m') with ⟨τ, _, _, τm'⟩ exact ⟨τ, ‹_›, ‹_›, @OpensMeasurableSpace.mk _ _ m (τm'.measurable_eq.symm.le.trans m'le)⟩ section NormedAddCommGroup variable [MeasurableSpace α] [NormedAddCommGroup α] [OpensMeasurableSpace α] [MeasurableSpace β] @[fun_prop, measurability] theorem measurable_norm : Measurable (norm : α → ℝ) := continuous_norm.measurable @[measurability, fun_prop] theorem Measurable.norm {f : β → α} (hf : Measurable f) : Measurable fun a => norm (f a) := measurable_norm.comp hf @[measurability, fun_prop] theorem AEMeasurable.norm {f : β → α} {μ : Measure β} (hf : AEMeasurable f μ) : AEMeasurable (fun a => norm (f a)) μ := measurable_norm.comp_aemeasurable hf @[measurability] theorem measurable_nnnorm : Measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.measurable @[measurability, fun_prop] theorem Measurable.nnnorm {f : β → α} (hf : Measurable f) : Measurable fun a => ‖f a‖₊ := measurable_nnnorm.comp hf @[measurability, fun_prop] theorem AEMeasurable.nnnorm {f : β → α} {μ : Measure β} (hf : AEMeasurable f μ) : AEMeasurable (fun a => ‖f a‖₊) μ := measurable_nnnorm.comp_aemeasurable hf @[measurability] theorem measurable_ennnorm : Measurable fun x : α => (‖x‖₊ : ℝ≥0∞) := measurable_nnnorm.coe_nnreal_ennreal @[measurability, fun_prop] theorem Measurable.ennnorm {f : β → α} (hf : Measurable f) : Measurable fun a => (‖f a‖₊ : ℝ≥0∞) := hf.nnnorm.coe_nnreal_ennreal @[measurability, fun_prop] theorem AEMeasurable.ennnorm {f : β → α} {μ : Measure β} (hf : AEMeasurable f μ) : AEMeasurable (fun a => (‖f a‖₊ : ℝ≥0∞)) μ := measurable_ennnorm.comp_aemeasurable hf end NormedAddCommGroup
MeasureTheory\Constructions\BorelSpace\Metrizable.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.MeasureTheory.Constructions.BorelSpace.Metric import Mathlib.Topology.Metrizable.Basic import Mathlib.Topology.IndicatorConstPointwise /-! # Measurable functions in (pseudo-)metrizable Borel spaces -/ open Filter MeasureTheory TopologicalSpace Topology NNReal ENNReal MeasureTheory variable {α β : Type*} [MeasurableSpace α] section Limits variable [TopologicalSpace β] [PseudoMetrizableSpace β] [MeasurableSpace β] [BorelSpace β] open Metric /-- A limit (over a general filter) of measurable functions valued in a (pseudo) metrizable space is measurable. -/ theorem measurable_of_tendsto_metrizable' {ι} {f : ι → α → β} {g : α → β} (u : Filter ι) [NeBot u] [IsCountablyGenerated u] (hf : ∀ i, Measurable (f i)) (lim : Tendsto f u (𝓝 g)) : Measurable g := by letI : PseudoMetricSpace β := pseudoMetrizableSpacePseudoMetric β apply measurable_of_isClosed' intro s h1s h2s h3s have : Measurable fun x => infNndist (g x) s := by suffices Tendsto (fun i x => infNndist (f i x) s) u (𝓝 fun x => infNndist (g x) s) from NNReal.measurable_of_tendsto' u (fun i => (hf i).infNndist) this rw [tendsto_pi_nhds] at lim ⊢ intro x exact ((continuous_infNndist_pt s).tendsto (g x)).comp (lim x) have h4s : g ⁻¹' s = (fun x => infNndist (g x) s) ⁻¹' {0} := by ext x simp [h1s, ← h1s.mem_iff_infDist_zero h2s, ← NNReal.coe_eq_zero] rw [h4s] exact this (measurableSet_singleton 0) /-- A sequential limit of measurable functions valued in a (pseudo) metrizable space is measurable. -/ theorem measurable_of_tendsto_metrizable {f : ℕ → α → β} {g : α → β} (hf : ∀ i, Measurable (f i)) (lim : Tendsto f atTop (𝓝 g)) : Measurable g := measurable_of_tendsto_metrizable' atTop hf lim theorem aemeasurable_of_tendsto_metrizable_ae {ι} {μ : Measure α} {f : ι → α → β} {g : α → β} (u : Filter ι) [hu : NeBot u] [IsCountablyGenerated u] (hf : ∀ n, AEMeasurable (f n) μ) (h_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) u (𝓝 (g x))) : AEMeasurable g μ := by classical rcases u.exists_seq_tendsto with ⟨v, hv⟩ have h'f : ∀ n, AEMeasurable (f (v n)) μ := fun n => hf (v n) set p : α → (ℕ → β) → Prop := fun x f' => Tendsto (fun n => f' n) atTop (𝓝 (g x)) have hp : ∀ᵐ x ∂μ, p x fun n => f (v n) x := by filter_upwards [h_tendsto] with x hx using hx.comp hv set aeSeqLim := fun x => ite (x ∈ aeSeqSet h'f p) (g x) (⟨f (v 0) x⟩ : Nonempty β).some refine ⟨aeSeqLim, measurable_of_tendsto_metrizable' atTop (aeSeq.measurable h'f p) (tendsto_pi_nhds.mpr fun x => ?_), ?_⟩ · simp_rw [aeSeqLim, 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 x hx · exact tendsto_const_nhds · exact (ite_ae_eq_of_measure_compl_zero g (fun x => (⟨f (v 0) x⟩ : Nonempty β).some) (aeSeqSet h'f p) (aeSeq.measure_compl_aeSeqSet_eq_zero h'f hp)).symm theorem aemeasurable_of_tendsto_metrizable_ae' {μ : Measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, AEMeasurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x))) : AEMeasurable g μ := aemeasurable_of_tendsto_metrizable_ae atTop hf h_ae_tendsto theorem aemeasurable_of_unif_approx {β} [MeasurableSpace β] [PseudoMetricSpace β] [BorelSpace β] {μ : Measure α} {g : α → β} (hf : ∀ ε > (0 : ℝ), ∃ f : α → β, AEMeasurable f μ ∧ ∀ᵐ x ∂μ, dist (f x) (g x) ≤ ε) : AEMeasurable g μ := by obtain ⟨u, -, u_pos, u_lim⟩ : ∃ u : ℕ → ℝ, StrictAnti u ∧ (∀ n : ℕ, 0 < u n) ∧ Tendsto u atTop (𝓝 0) := exists_seq_strictAnti_tendsto (0 : ℝ) choose f Hf using fun n : ℕ => hf (u n) (u_pos n) have : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x)) := by have : ∀ᵐ x ∂μ, ∀ n, dist (f n x) (g x) ≤ u n := ae_all_iff.2 fun n => (Hf n).2 filter_upwards [this] intro x hx rw [tendsto_iff_dist_tendsto_zero] exact squeeze_zero (fun n => dist_nonneg) hx u_lim exact aemeasurable_of_tendsto_metrizable_ae' (fun n => (Hf n).1) this theorem measurable_of_tendsto_metrizable_ae {μ : Measure α} [μ.IsComplete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, Measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) atTop (𝓝 (g x))) : Measurable g := aemeasurable_iff_measurable.mp (aemeasurable_of_tendsto_metrizable_ae' (fun i => (hf i).aemeasurable) h_ae_tendsto) theorem measurable_limit_of_tendsto_metrizable_ae {ι} [Countable ι] [Nonempty ι] {μ : Measure α} {f : ι → α → β} {L : Filter ι} [L.IsCountablyGenerated] (hf : ∀ n, AEMeasurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, Tendsto (fun n => f n x) L (𝓝 l)) : ∃ f_lim : α → β, Measurable f_lim ∧ ∀ᵐ x ∂μ, Tendsto (fun n => f n x) L (𝓝 (f_lim x)) := by classical inhabit ι rcases eq_or_neBot L with (rfl | hL) · exact ⟨(hf default).mk _, (hf default).measurable_mk, eventually_of_forall fun x => tendsto_bot⟩ let p : α → (ι → β) → Prop := fun x f' => ∃ l : β, Tendsto (fun n => f' n) L (𝓝 l) have hp_mem : ∀ x ∈ aeSeqSet hf p, p x fun n => f n x := fun x hx => aeSeq.fun_prop_of_mem_aeSeqSet hf hx have h_ae_eq : ∀ᵐ x ∂μ, ∀ n, aeSeq hf p n x = f n x := aeSeq.aeSeq_eq_fun_ae hf h_ae_tendsto set f_lim : α → β := fun x => dite (x ∈ aeSeqSet hf p) (fun h => (hp_mem x h).choose) fun _ => (⟨f default x⟩ : Nonempty β).some have hf_lim : ∀ x, Tendsto (fun n => aeSeq hf p n x) L (𝓝 (f_lim x)) := by intro x simp only [aeSeq, f_lim] split_ifs with h · refine (hp_mem x h).choose_spec.congr fun n => ?_ exact (aeSeq.mk_eq_fun_of_mem_aeSeqSet hf h n).symm · exact tendsto_const_nhds have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, Tendsto (fun n => f n x) L (𝓝 (f_lim x)) := h_ae_eq.mono fun x hx => (hf_lim x).congr hx have h_f_lim_meas : Measurable f_lim := measurable_of_tendsto_metrizable' L (aeSeq.measurable hf p) (tendsto_pi_nhds.mpr fun x => hf_lim x) exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩ end Limits section TendstoIndicator variable {α : Type*} [MeasurableSpace α] {A : Set α} variable {ι : Type*} (L : Filter ι) [IsCountablyGenerated L] {As : ι → Set α} /-- If the indicator functions of measurable sets `Aᵢ` converge to the indicator function of a set `A` along a nontrivial countably generated filter, then `A` is also measurable. -/ lemma measurableSet_of_tendsto_indicator [NeBot L] (As_mble : ∀ i, MeasurableSet (As i)) (h_lim : ∀ x, ∀ᶠ i in L, x ∈ As i ↔ x ∈ A) : MeasurableSet A := by simp_rw [← measurable_indicator_const_iff (1 : ℝ≥0∞)] at As_mble ⊢ exact ENNReal.measurable_of_tendsto' L As_mble ((tendsto_indicator_const_iff_forall_eventually L (1 : ℝ≥0∞)).mpr h_lim) /-- If the indicator functions of a.e.-measurable sets `Aᵢ` converge a.e. to the indicator function of a set `A` along a nontrivial countably generated filter, then `A` is also a.e.-measurable. -/ lemma nullMeasurableSet_of_tendsto_indicator [NeBot L] {μ : Measure α} (As_mble : ∀ i, NullMeasurableSet (As i) μ) (h_lim : ∀ᵐ x ∂μ, ∀ᶠ i in L, x ∈ As i ↔ x ∈ A) : NullMeasurableSet A μ := by simp_rw [← aemeasurable_indicator_const_iff (1 : ℝ≥0∞)] at As_mble ⊢ apply aemeasurable_of_tendsto_metrizable_ae L As_mble simpa [tendsto_indicator_const_apply_iff_eventually] using h_lim end TendstoIndicator
MeasureTheory\Constructions\BorelSpace\Order.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, Kexing Ying -/ import Mathlib.Topology.Semicontinuous import Mathlib.MeasureTheory.Function.AEMeasurableSequence import Mathlib.MeasureTheory.Order.Lattice import Mathlib.Topology.Order.Lattice import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic /-! # Borel sigma algebras on spaces with orders ## Main statements * `borel_eq_generateFrom_Ixx` (where Ixx is one of {Iio, Ioi, Iic, Ici, Ico, Ioc}): The Borel sigma algebra of a linear order topology is generated by intervals of the given kind. * `Dense.borel_eq_generateFrom_Ico_mem`, `Dense.borel_eq_generateFrom_Ioc_mem`: The Borel sigma algebra of a dense linear order topology is generated by intervals of a given kind, with endpoints from dense subsets. * `ext_of_Ico`, `ext_of_Ioc`: A locally finite Borel measure on a second countable conditionally complete linear order is characterized by the measures of intervals of the given kind. * `ext_of_Iic`, `ext_of_Ici`: A finite Borel measure on a second countable linear order is characterized by the measures of intervals of the given kind. * `UpperSemicontinuous.measurable`, `LowerSemicontinuous.measurable`: Semicontinuous functions are measurable. * `measurable_iSup`, `measurable_iInf`, `measurable_sSup`, `measurable_sInf`: Countable supremums and infimums of measurable functions to conditionally complete linear orders are measurable. * `measurable_liminf`, `measurable_limsup`: Countable liminfs and limsups of measurable functions to conditionally complete linear orders are measurable. -/ open Set Filter MeasureTheory MeasurableSpace TopologicalSpace open scoped Topology NNReal ENNReal MeasureTheory universe u v w x y variable {α β γ δ : Type*} {ι : Sort y} {s t u : Set α} section OrderTopology variable (α) variable [TopologicalSpace α] [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] theorem borel_eq_generateFrom_Iio : borel α = .generateFrom (range Iio) := by refine le_antisymm ?_ (generateFrom_le ?_) · rw [borel_eq_generateFrom_of_subbasis (@OrderTopology.topology_eq_generate_intervals α _ _ _)] letI : MeasurableSpace α := MeasurableSpace.generateFrom (range Iio) have H : ∀ a : α, MeasurableSet (Iio a) := fun a => GenerateMeasurable.basic _ ⟨_, rfl⟩ refine generateFrom_le ?_ rintro _ ⟨a, rfl | rfl⟩ · rcases em (∃ b, a ⋖ b) with ⟨b, hb⟩ | hcovBy · rw [hb.Ioi_eq, ← compl_Iio] exact (H _).compl · rcases isOpen_biUnion_countable (Ioi a) Ioi fun _ _ ↦ isOpen_Ioi with ⟨t, hat, htc, htU⟩ have : Ioi a = ⋃ b ∈ t, Ici b := by refine Subset.antisymm ?_ <| iUnion₂_subset fun b hb ↦ Ici_subset_Ioi.2 (hat hb) refine Subset.trans ?_ <| iUnion₂_mono fun _ _ ↦ Ioi_subset_Ici_self simpa [CovBy, htU, subset_def] using hcovBy simp only [this, ← compl_Iio] exact .biUnion htc <| fun _ _ ↦ (H _).compl · apply H · rw [forall_mem_range] intro a exact GenerateMeasurable.basic _ isOpen_Iio theorem borel_eq_generateFrom_Ioi : borel α = .generateFrom (range Ioi) := @borel_eq_generateFrom_Iio αᵒᵈ _ (by infer_instance : SecondCountableTopology α) _ _ theorem borel_eq_generateFrom_Iic : borel α = MeasurableSpace.generateFrom (range Iic) := by rw [borel_eq_generateFrom_Ioi] refine le_antisymm ?_ ?_ · refine MeasurableSpace.generateFrom_le fun t ht => ?_ obtain ⟨u, rfl⟩ := ht rw [← compl_Iic] exact (MeasurableSpace.measurableSet_generateFrom (mem_range.mpr ⟨u, rfl⟩)).compl · refine MeasurableSpace.generateFrom_le fun t ht => ?_ obtain ⟨u, rfl⟩ := ht rw [← compl_Ioi] exact (MeasurableSpace.measurableSet_generateFrom (mem_range.mpr ⟨u, rfl⟩)).compl theorem borel_eq_generateFrom_Ici : borel α = MeasurableSpace.generateFrom (range Ici) := @borel_eq_generateFrom_Iic αᵒᵈ _ _ _ _ end OrderTopology section Orders variable [TopologicalSpace α] [MeasurableSpace α] [OpensMeasurableSpace α] variable [MeasurableSpace δ] section Preorder variable [Preorder α] [OrderClosedTopology α] {a b x : α} @[simp, measurability] theorem measurableSet_Ici : MeasurableSet (Ici a) := isClosed_Ici.measurableSet @[simp, measurability] theorem measurableSet_Iic : MeasurableSet (Iic a) := isClosed_Iic.measurableSet @[simp, measurability] theorem measurableSet_Icc : MeasurableSet (Icc a b) := isClosed_Icc.measurableSet instance nhdsWithin_Ici_isMeasurablyGenerated : (𝓝[Ici b] a).IsMeasurablyGenerated := measurableSet_Ici.nhdsWithin_isMeasurablyGenerated _ instance nhdsWithin_Iic_isMeasurablyGenerated : (𝓝[Iic b] a).IsMeasurablyGenerated := measurableSet_Iic.nhdsWithin_isMeasurablyGenerated _ instance nhdsWithin_Icc_isMeasurablyGenerated : IsMeasurablyGenerated (𝓝[Icc a b] x) := by rw [← Ici_inter_Iic, nhdsWithin_inter] infer_instance instance atTop_isMeasurablyGenerated : (Filter.atTop : Filter α).IsMeasurablyGenerated := @Filter.iInf_isMeasurablyGenerated _ _ _ _ fun a => (measurableSet_Ici : MeasurableSet (Ici a)).principal_isMeasurablyGenerated instance atBot_isMeasurablyGenerated : (Filter.atBot : Filter α).IsMeasurablyGenerated := @Filter.iInf_isMeasurablyGenerated _ _ _ _ fun a => (measurableSet_Iic : MeasurableSet (Iic a)).principal_isMeasurablyGenerated instance [R1Space α] : IsMeasurablyGenerated (cocompact α) where exists_measurable_subset := by intro _ hs obtain ⟨t, ht, hts⟩ := mem_cocompact.mp hs exact ⟨(closure t)ᶜ, ht.closure.compl_mem_cocompact, isClosed_closure.measurableSet.compl, (compl_subset_compl.2 subset_closure).trans hts⟩ end Preorder section PartialOrder variable [PartialOrder α] [OrderClosedTopology α] [SecondCountableTopology α] {a b : α} @[measurability] theorem measurableSet_le' : MeasurableSet { p : α × α | p.1 ≤ p.2 } := OrderClosedTopology.isClosed_le'.measurableSet @[measurability] theorem measurableSet_le {f g : δ → α} (hf : Measurable f) (hg : Measurable g) : MeasurableSet { a | f a ≤ g a } := hf.prod_mk hg measurableSet_le' end PartialOrder section LinearOrder variable [LinearOrder α] [OrderClosedTopology α] {a b x : α} -- we open this locale only here to avoid issues with list being treated as intervals above open Interval @[simp, measurability] theorem measurableSet_Iio : MeasurableSet (Iio a) := isOpen_Iio.measurableSet @[simp, measurability] theorem measurableSet_Ioi : MeasurableSet (Ioi a) := isOpen_Ioi.measurableSet @[simp, measurability] theorem measurableSet_Ioo : MeasurableSet (Ioo a b) := isOpen_Ioo.measurableSet @[simp, measurability] theorem measurableSet_Ioc : MeasurableSet (Ioc a b) := measurableSet_Ioi.inter measurableSet_Iic @[simp, measurability] theorem measurableSet_Ico : MeasurableSet (Ico a b) := measurableSet_Ici.inter measurableSet_Iio instance nhdsWithin_Ioi_isMeasurablyGenerated : (𝓝[Ioi b] a).IsMeasurablyGenerated := measurableSet_Ioi.nhdsWithin_isMeasurablyGenerated _ instance nhdsWithin_Iio_isMeasurablyGenerated : (𝓝[Iio b] a).IsMeasurablyGenerated := measurableSet_Iio.nhdsWithin_isMeasurablyGenerated _ instance nhdsWithin_uIcc_isMeasurablyGenerated : IsMeasurablyGenerated (𝓝[[[a, b]]] x) := nhdsWithin_Icc_isMeasurablyGenerated @[measurability] theorem measurableSet_lt' [SecondCountableTopology α] : MeasurableSet { p : α × α | p.1 < p.2 } := (isOpen_lt continuous_fst continuous_snd).measurableSet @[measurability] theorem measurableSet_lt [SecondCountableTopology α] {f g : δ → α} (hf : Measurable f) (hg : Measurable g) : MeasurableSet { a | f a < g a } := hf.prod_mk hg measurableSet_lt' theorem nullMeasurableSet_lt [SecondCountableTopology α] {μ : Measure δ} {f g : δ → α} (hf : AEMeasurable f μ) (hg : AEMeasurable g μ) : NullMeasurableSet { a | f a < g a } μ := (hf.prod_mk hg).nullMeasurable measurableSet_lt' theorem nullMeasurableSet_lt' [SecondCountableTopology α] {μ : Measure (α × α)} : NullMeasurableSet { p : α × α | p.1 < p.2 } μ := measurableSet_lt'.nullMeasurableSet theorem nullMeasurableSet_le [SecondCountableTopology α] {μ : Measure δ} {f g : δ → α} (hf : AEMeasurable f μ) (hg : AEMeasurable g μ) : NullMeasurableSet { a | f a ≤ g a } μ := (hf.prod_mk hg).nullMeasurable measurableSet_le' theorem Set.OrdConnected.measurableSet (h : OrdConnected s) : MeasurableSet s := by let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y have huopen : IsOpen u := isOpen_biUnion fun _ _ => isOpen_biUnion fun _ _ => isOpen_Ioo have humeas : MeasurableSet u := huopen.measurableSet have hfinite : (s \ u).Finite := s.finite_diff_iUnion_Ioo have : u ⊆ s := iUnion₂_subset fun x hx => iUnion₂_subset fun y hy => Ioo_subset_Icc_self.trans (h.out hx hy) rw [← union_diff_cancel this] exact humeas.union hfinite.measurableSet theorem IsPreconnected.measurableSet (h : IsPreconnected s) : MeasurableSet s := h.ordConnected.measurableSet theorem generateFrom_Ico_mem_le_borel {α : Type*} [TopologicalSpace α] [LinearOrder α] [OrderClosedTopology α] (s t : Set α) : MeasurableSpace.generateFrom { S | ∃ l ∈ s, ∃ u ∈ t, l < u ∧ Ico l u = S } ≤ borel α := by apply generateFrom_le borelize α rintro _ ⟨a, -, b, -, -, rfl⟩ exact measurableSet_Ico theorem Dense.borel_eq_generateFrom_Ico_mem_aux {α : Type*} [TopologicalSpace α] [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] {s : Set α} (hd : Dense s) (hbot : ∀ x, IsBot x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → y ∈ s) : borel α = .generateFrom { S : Set α | ∃ l ∈ s, ∃ u ∈ s, l < u ∧ Ico l u = S } := by set S : Set (Set α) := { S | ∃ l ∈ s, ∃ u ∈ s, l < u ∧ Ico l u = S } refine le_antisymm ?_ (generateFrom_Ico_mem_le_borel _ _) letI : MeasurableSpace α := generateFrom S rw [borel_eq_generateFrom_Iio] refine generateFrom_le (forall_mem_range.2 fun a => ?_) rcases hd.exists_countable_dense_subset_bot_top with ⟨t, hts, hc, htd, htb, -⟩ by_cases ha : ∀ b < a, (Ioo b a).Nonempty · convert_to MeasurableSet (⋃ (l ∈ t) (u ∈ t) (_ : l < u) (_ : u ≤ a), Ico l u) · ext y simp only [mem_iUnion, mem_Iio, mem_Ico] constructor · intro hy rcases htd.exists_le' (fun b hb => htb _ hb (hbot b hb)) y with ⟨l, hlt, hly⟩ rcases htd.exists_mem_open isOpen_Ioo (ha y hy) with ⟨u, hut, hyu, hua⟩ exact ⟨l, hlt, u, hut, hly.trans_lt hyu, hua.le, hly, hyu⟩ · rintro ⟨l, -, u, -, -, hua, -, hyu⟩ exact hyu.trans_le hua · refine MeasurableSet.biUnion hc fun a ha => MeasurableSet.biUnion hc fun b hb => ?_ refine MeasurableSet.iUnion fun hab => MeasurableSet.iUnion fun _ => ?_ exact .basic _ ⟨a, hts ha, b, hts hb, hab, mem_singleton _⟩ · simp only [not_forall, not_nonempty_iff_eq_empty] at ha replace ha : a ∈ s := hIoo ha.choose a ha.choose_spec.fst ha.choose_spec.snd convert_to MeasurableSet (⋃ (l ∈ t) (_ : l < a), Ico l a) · symm simp only [← Ici_inter_Iio, ← iUnion_inter, inter_eq_right, subset_def, mem_iUnion, mem_Ici, mem_Iio] intro x hx rcases htd.exists_le' (fun b hb => htb _ hb (hbot b hb)) x with ⟨z, hzt, hzx⟩ exact ⟨z, hzt, hzx.trans_lt hx, hzx⟩ · refine .biUnion hc fun x hx => MeasurableSet.iUnion fun hlt => ?_ exact .basic _ ⟨x, hts hx, a, ha, hlt, mem_singleton _⟩ theorem Dense.borel_eq_generateFrom_Ico_mem {α : Type*} [TopologicalSpace α] [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] [DenselyOrdered α] [NoMinOrder α] {s : Set α} (hd : Dense s) : borel α = .generateFrom { S : Set α | ∃ l ∈ s, ∃ u ∈ s, l < u ∧ Ico l u = S } := hd.borel_eq_generateFrom_Ico_mem_aux (by simp) fun x y hxy H => ((nonempty_Ioo.2 hxy).ne_empty H).elim theorem borel_eq_generateFrom_Ico (α : Type*) [TopologicalSpace α] [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] : borel α = .generateFrom { S : Set α | ∃ (l u : α), l < u ∧ Ico l u = S } := by simpa only [exists_prop, mem_univ, true_and_iff] using (@dense_univ α _).borel_eq_generateFrom_Ico_mem_aux (fun _ _ => mem_univ _) fun _ _ _ _ => mem_univ _ theorem Dense.borel_eq_generateFrom_Ioc_mem_aux {α : Type*} [TopologicalSpace α] [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] {s : Set α} (hd : Dense s) (hbot : ∀ x, IsTop x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → x ∈ s) : borel α = .generateFrom { S : Set α | ∃ l ∈ s, ∃ u ∈ s, l < u ∧ Ioc l u = S } := by convert hd.orderDual.borel_eq_generateFrom_Ico_mem_aux hbot fun x y hlt he => hIoo y x hlt _ using 2 · ext s constructor <;> rintro ⟨l, hl, u, hu, hlt, rfl⟩ exacts [⟨u, hu, l, hl, hlt, dual_Ico⟩, ⟨u, hu, l, hl, hlt, dual_Ioc⟩] · erw [dual_Ioo] exact he theorem Dense.borel_eq_generateFrom_Ioc_mem {α : Type*} [TopologicalSpace α] [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] [DenselyOrdered α] [NoMaxOrder α] {s : Set α} (hd : Dense s) : borel α = .generateFrom { S : Set α | ∃ l ∈ s, ∃ u ∈ s, l < u ∧ Ioc l u = S } := hd.borel_eq_generateFrom_Ioc_mem_aux (by simp) fun x y hxy H => ((nonempty_Ioo.2 hxy).ne_empty H).elim theorem borel_eq_generateFrom_Ioc (α : Type*) [TopologicalSpace α] [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] : borel α = .generateFrom { S : Set α | ∃ l u, l < u ∧ Ioc l u = S } := by simpa only [exists_prop, mem_univ, true_and_iff] using (@dense_univ α _).borel_eq_generateFrom_Ioc_mem_aux (fun _ _ => mem_univ _) fun _ _ _ _ => mem_univ _ namespace MeasureTheory.Measure /-- Two finite measures on a Borel space are equal if they agree on all closed-open intervals. If `α` is a conditionally complete linear order with no top element, `MeasureTheory.Measure.ext_of_Ico` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ theorem ext_of_Ico_finite {α : Type*} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] (μ ν : Measure α) [IsFiniteMeasure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := by refine ext_of_generate_finite _ (BorelSpace.measurable_eq.trans (borel_eq_generateFrom_Ico α)) (isPiSystem_Ico (id : α → α) id) ?_ hμν rintro - ⟨a, b, hlt, rfl⟩ exact h hlt /-- Two finite measures on a Borel space are equal if they agree on all open-closed intervals. If `α` is a conditionally complete linear order with no top element, `MeasureTheory.Measure.ext_of_Ioc` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ theorem ext_of_Ioc_finite {α : Type*} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] (μ ν : Measure α) [IsFiniteMeasure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := by refine @ext_of_Ico_finite αᵒᵈ _ _ _ _ _ ‹_› μ ν _ hμν fun a b hab => ?_ erw [dual_Ico (α := α)] exact h hab /-- Two measures which are finite on closed-open intervals are equal if they agree on all closed-open intervals. -/ theorem ext_of_Ico' {α : Type*} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] [NoMaxOrder α] (μ ν : Measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ico a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := by rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, hsb, _⟩ have : (⋃ (l ∈ s) (u ∈ s) (_ : l < u), {Ico l u} : Set (Set α)).Countable := hsc.biUnion fun l _ => hsc.biUnion fun u _ => countable_iUnion fun _ => countable_singleton _ simp only [← setOf_eq_eq_singleton, ← setOf_exists] at this refine Measure.ext_of_generateFrom_of_cover_subset (BorelSpace.measurable_eq.trans (borel_eq_generateFrom_Ico α)) (isPiSystem_Ico id id) ?_ this ?_ ?_ ?_ · rintro _ ⟨l, -, u, -, h, rfl⟩ exact ⟨l, u, h, rfl⟩ · refine sUnion_eq_univ_iff.2 fun x => ?_ rcases hsd.exists_le' hsb x with ⟨l, hls, hlx⟩ rcases hsd.exists_gt x with ⟨u, hus, hxu⟩ exact ⟨_, ⟨l, hls, u, hus, hlx.trans_lt hxu, rfl⟩, hlx, hxu⟩ · rintro _ ⟨l, -, u, -, hlt, rfl⟩ exact hμ hlt · rintro _ ⟨l, u, hlt, rfl⟩ exact h hlt /-- Two measures which are finite on closed-open intervals are equal if they agree on all open-closed intervals. -/ theorem ext_of_Ioc' {α : Type*} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] [NoMinOrder α] (μ ν : Measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ioc a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := by refine @ext_of_Ico' αᵒᵈ _ _ _ _ _ ‹_› _ μ ν ?_ ?_ <;> intro a b hab <;> erw [dual_Ico (α := α)] exacts [hμ hab, h hab] /-- Two measures which are finite on closed-open intervals are equal if they agree on all closed-open intervals. -/ theorem ext_of_Ico {α : Type*} [TopologicalSpace α] {_m : MeasurableSpace α} [SecondCountableTopology α] [ConditionallyCompleteLinearOrder α] [OrderTopology α] [BorelSpace α] [NoMaxOrder α] (μ ν : Measure α) [IsLocallyFiniteMeasure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := μ.ext_of_Ico' ν (fun _ _ _ => measure_Ico_lt_top.ne) h /-- Two measures which are finite on closed-open intervals are equal if they agree on all open-closed intervals. -/ theorem ext_of_Ioc {α : Type*} [TopologicalSpace α] {_m : MeasurableSpace α} [SecondCountableTopology α] [ConditionallyCompleteLinearOrder α] [OrderTopology α] [BorelSpace α] [NoMinOrder α] (μ ν : Measure α) [IsLocallyFiniteMeasure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := μ.ext_of_Ioc' ν (fun _ _ _ => measure_Ioc_lt_top.ne) h /-- Two finite measures on a Borel space are equal if they agree on all left-infinite right-closed intervals. -/ theorem ext_of_Iic {α : Type*} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] (μ ν : Measure α) [IsFiniteMeasure μ] (h : ∀ a, μ (Iic a) = ν (Iic a)) : μ = ν := by refine ext_of_Ioc_finite μ ν ?_ fun a b hlt => ?_ · rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, -, hst⟩ have : DirectedOn (· ≤ ·) s := directedOn_iff_directed.2 (Subtype.mono_coe _).directed_le simp only [← biSup_measure_Iic hsc (hsd.exists_ge' hst) this, h] rw [← Iic_diff_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurableSet_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurableSet_Iic, h a, h b] · rw [← h a] exact (measure_lt_top μ _).ne · exact (measure_lt_top μ _).ne /-- Two finite measures on a Borel space are equal if they agree on all left-closed right-infinite intervals. -/ theorem ext_of_Ici {α : Type*} [TopologicalSpace α] {m : MeasurableSpace α} [SecondCountableTopology α] [LinearOrder α] [OrderTopology α] [BorelSpace α] (μ ν : Measure α) [IsFiniteMeasure μ] (h : ∀ a, μ (Ici a) = ν (Ici a)) : μ = ν := @ext_of_Iic αᵒᵈ _ _ _ _ _ ‹_› _ _ _ h end MeasureTheory.Measure @[measurability] theorem measurableSet_uIcc : MeasurableSet (uIcc a b) := measurableSet_Icc @[measurability] theorem measurableSet_uIoc : MeasurableSet (uIoc a b) := measurableSet_Ioc variable [SecondCountableTopology α] @[measurability] theorem Measurable.max {f g : δ → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun a => max (f a) (g a) := by simpa only [max_def'] using hf.piecewise (measurableSet_le hg hf) hg @[measurability] nonrec theorem AEMeasurable.max {f g : δ → α} {μ : Measure δ} (hf : AEMeasurable f μ) (hg : AEMeasurable g μ) : AEMeasurable (fun a => max (f a) (g a)) μ := ⟨fun a => max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, EventuallyEq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ @[measurability] theorem Measurable.min {f g : δ → α} (hf : Measurable f) (hg : Measurable g) : Measurable fun a => min (f a) (g a) := by simpa only [min_def] using hf.piecewise (measurableSet_le hf hg) hg @[measurability] nonrec theorem AEMeasurable.min {f g : δ → α} {μ : Measure δ} (hf : AEMeasurable f μ) (hg : AEMeasurable g μ) : AEMeasurable (fun a => min (f a) (g a)) μ := ⟨fun a => min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, EventuallyEq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ end LinearOrder section Lattice variable [TopologicalSpace γ] [MeasurableSpace γ] [BorelSpace γ] instance (priority := 100) ContinuousSup.measurableSup [Sup γ] [ContinuousSup γ] : MeasurableSup γ where measurable_const_sup _ := (continuous_const.sup continuous_id).measurable measurable_sup_const _ := (continuous_id.sup continuous_const).measurable instance (priority := 100) ContinuousSup.measurableSup₂ [SecondCountableTopology γ] [Sup γ] [ContinuousSup γ] : MeasurableSup₂ γ := ⟨continuous_sup.measurable⟩ instance (priority := 100) ContinuousInf.measurableInf [Inf γ] [ContinuousInf γ] : MeasurableInf γ where measurable_const_inf _ := (continuous_const.inf continuous_id).measurable measurable_inf_const _ := (continuous_id.inf continuous_const).measurable instance (priority := 100) ContinuousInf.measurableInf₂ [SecondCountableTopology γ] [Inf γ] [ContinuousInf γ] : MeasurableInf₂ γ := ⟨continuous_inf.measurable⟩ end Lattice end Orders section BorelSpace variable [TopologicalSpace α] [MeasurableSpace α] [BorelSpace α] variable [TopologicalSpace β] [MeasurableSpace β] [BorelSpace β] variable [MeasurableSpace δ] section LinearOrder variable [LinearOrder α] [OrderTopology α] [SecondCountableTopology α] theorem measurable_of_Iio {f : δ → α} (hf : ∀ x, MeasurableSet (f ⁻¹' Iio x)) : Measurable f := by convert measurable_generateFrom (α := δ) _ · exact BorelSpace.measurable_eq.trans (borel_eq_generateFrom_Iio _) · rintro _ ⟨x, rfl⟩; exact hf x theorem UpperSemicontinuous.measurable [TopologicalSpace δ] [OpensMeasurableSpace δ] {f : δ → α} (hf : UpperSemicontinuous f) : Measurable f := measurable_of_Iio fun y => (hf.isOpen_preimage y).measurableSet theorem measurable_of_Ioi {f : δ → α} (hf : ∀ x, MeasurableSet (f ⁻¹' Ioi x)) : Measurable f := by convert measurable_generateFrom (α := δ) _ · exact BorelSpace.measurable_eq.trans (borel_eq_generateFrom_Ioi _) · rintro _ ⟨x, rfl⟩; exact hf x theorem LowerSemicontinuous.measurable [TopologicalSpace δ] [OpensMeasurableSpace δ] {f : δ → α} (hf : LowerSemicontinuous f) : Measurable f := measurable_of_Ioi fun y => (hf.isOpen_preimage y).measurableSet theorem measurable_of_Iic {f : δ → α} (hf : ∀ x, MeasurableSet (f ⁻¹' Iic x)) : Measurable f := by apply measurable_of_Ioi simp_rw [← compl_Iic, preimage_compl, MeasurableSet.compl_iff] assumption theorem measurable_of_Ici {f : δ → α} (hf : ∀ x, MeasurableSet (f ⁻¹' Ici x)) : Measurable f := by apply measurable_of_Iio simp_rw [← compl_Ici, preimage_compl, MeasurableSet.compl_iff] assumption /-- If a function is the least upper bound of countably many measurable functions, then it is measurable. -/ theorem Measurable.isLUB {ι} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, Measurable (f i)) (hg : ∀ b, IsLUB { a | ∃ i, f i b = a } (g b)) : Measurable g := by change ∀ b, IsLUB (range fun i => f i b) (g b) at hg rw [‹BorelSpace α›.measurable_eq, borel_eq_generateFrom_Ioi α] apply measurable_generateFrom rintro _ ⟨a, rfl⟩ simp_rw [Set.preimage, mem_Ioi, lt_isLUB_iff (hg _), exists_range_iff, setOf_exists] exact MeasurableSet.iUnion fun i => hf i (isOpen_lt' _).measurableSet /-- If a function is the least upper bound of countably many measurable functions on a measurable set `s`, and coincides with a measurable function outside of `s`, then it is measurable. -/ theorem Measurable.isLUB_of_mem {ι} [Countable ι] {f : ι → δ → α} {g g' : δ → α} (hf : ∀ i, Measurable (f i)) {s : Set δ} (hs : MeasurableSet s) (hg : ∀ b ∈ s, IsLUB { a | ∃ i, f i b = a } (g b)) (hg' : EqOn g g' sᶜ) (g'_meas : Measurable g') : Measurable g := by classical rcases isEmpty_or_nonempty ι with hι|⟨⟨i⟩⟩ · rcases eq_empty_or_nonempty s with rfl|⟨x, hx⟩ · convert g'_meas rwa [compl_empty, eqOn_univ] at hg' · have A : ∀ b ∈ s, IsBot (g b) := by simpa using hg have B : ∀ b ∈ s, g b = g x := by intro b hb apply le_antisymm (A b hb (g x)) (A x hx (g b)) have : g = s.piecewise (fun _y ↦ g x) g' := by ext b by_cases hb : b ∈ s · simp [hb, B] · simp [hb, hg' hb] rw [this] exact Measurable.piecewise hs measurable_const g'_meas · let f' : ι → δ → α := fun i ↦ s.piecewise (f i) g' suffices ∀ b, IsLUB { a | ∃ i, f' i b = a } (g b) from Measurable.isLUB (fun i ↦ Measurable.piecewise hs (hf i) g'_meas) this intro b by_cases hb : b ∈ s · have A : ∀ i, f' i b = f i b := fun i ↦ by simp [f', hb] simpa [A] using hg b hb · have A : ∀ i, f' i b = g' b := fun i ↦ by simp [f', hb] have : {a | ∃ (_i : ι), g' b = a} = {g' b} := by apply Subset.antisymm · rintro - ⟨_j, rfl⟩ simp only [mem_singleton_iff] · rintro - rfl exact ⟨i, rfl⟩ simp [A, this, hg' hb, isLUB_singleton] theorem AEMeasurable.isLUB {ι} {μ : Measure δ} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, AEMeasurable (f i) μ) (hg : ∀ᵐ b ∂μ, IsLUB { a | ∃ i, f i b = a } (g b)) : AEMeasurable g μ := by classical nontriviality α haveI hα : Nonempty α := inferInstance cases' isEmpty_or_nonempty ι with hι hι · simp only [IsEmpty.exists_iff, setOf_false, isLUB_empty_iff] at hg exact aemeasurable_const' (hg.mono fun a ha => hg.mono fun b hb => (ha _).antisymm (hb _)) let p : δ → (ι → α) → Prop := fun x f' => IsLUB { a | ∃ i, f' i = a } (g x) let g_seq := (aeSeqSet hf p).piecewise g fun _ => hα.some have hg_seq : ∀ b, IsLUB { a | ∃ i, aeSeq hf p i b = a } (g_seq b) := by intro b simp only [g_seq, aeSeq, Set.piecewise] split_ifs with h · have h_set_eq : { a : α | ∃ i : ι, (hf i).mk (f i) b = a } = { a : α | ∃ i : ι, f i b = a } := by ext x simp_rw [Set.mem_setOf_eq, aeSeq.mk_eq_fun_of_mem_aeSeqSet hf h] rw [h_set_eq] exact aeSeq.fun_prop_of_mem_aeSeqSet hf h · exact IsGreatest.isLUB ⟨(@exists_const (hα.some = hα.some) ι _).2 rfl, fun x ⟨i, hi⟩ => hi.ge⟩ refine ⟨g_seq, Measurable.isLUB (aeSeq.measurable hf p) hg_seq, ?_⟩ exact (ite_ae_eq_of_measure_compl_zero g (fun _ => hα.some) (aeSeqSet hf p) (aeSeq.measure_compl_aeSeqSet_eq_zero hf hg)).symm /-- If a function is the greatest lower bound of countably many measurable functions, then it is measurable. -/ theorem Measurable.isGLB {ι} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, Measurable (f i)) (hg : ∀ b, IsGLB { a | ∃ i, f i b = a } (g b)) : Measurable g := Measurable.isLUB (α := αᵒᵈ) hf hg /-- If a function is the greatest lower bound of countably many measurable functions on a measurable set `s`, and coincides with a measurable function outside of `s`, then it is measurable. -/ theorem Measurable.isGLB_of_mem {ι} [Countable ι] {f : ι → δ → α} {g g' : δ → α} (hf : ∀ i, Measurable (f i)) {s : Set δ} (hs : MeasurableSet s) (hg : ∀ b ∈ s, IsGLB { a | ∃ i, f i b = a } (g b)) (hg' : EqOn g g' sᶜ) (g'_meas : Measurable g') : Measurable g := Measurable.isLUB_of_mem (α := αᵒᵈ) hf hs hg hg' g'_meas theorem AEMeasurable.isGLB {ι} {μ : Measure δ} [Countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, AEMeasurable (f i) μ) (hg : ∀ᵐ b ∂μ, IsGLB { a | ∃ i, f i b = a } (g b)) : AEMeasurable g μ := AEMeasurable.isLUB (α := αᵒᵈ) hf hg protected theorem Monotone.measurable [LinearOrder β] [OrderClosedTopology β] {f : β → α} (hf : Monotone f) : Measurable f := suffices h : ∀ x, OrdConnected (f ⁻¹' Ioi x) from measurable_of_Ioi fun x => (h x).measurableSet fun _ => ordConnected_def.mpr fun _a ha _ _ _c hc => lt_of_lt_of_le ha (hf hc.1) theorem aemeasurable_restrict_of_monotoneOn [LinearOrder β] [OrderClosedTopology β] {μ : Measure β} {s : Set β} (hs : MeasurableSet s) {f : β → α} (hf : MonotoneOn f s) : AEMeasurable f (μ.restrict s) := have : Monotone (f ∘ (↑) : s → α) := fun ⟨x, hx⟩ ⟨y, hy⟩ => fun (hxy : x ≤ y) => hf hx hy hxy aemeasurable_restrict_of_measurable_subtype hs this.measurable protected theorem Antitone.measurable [LinearOrder β] [OrderClosedTopology β] {f : β → α} (hf : Antitone f) : Measurable f := @Monotone.measurable αᵒᵈ β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf theorem aemeasurable_restrict_of_antitoneOn [LinearOrder β] [OrderClosedTopology β] {μ : Measure β} {s : Set β} (hs : MeasurableSet s) {f : β → α} (hf : AntitoneOn f s) : AEMeasurable f (μ.restrict s) := @aemeasurable_restrict_of_monotoneOn αᵒᵈ β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf theorem measurableSet_of_mem_nhdsWithin_Ioi_aux {s : Set α} (h : ∀ x ∈ s, s ∈ 𝓝[>] x) (h' : ∀ x ∈ s, ∃ y, x < y) : MeasurableSet s := by choose! M hM using h' suffices H : (s \ interior s).Countable by have : s = interior s ∪ s \ interior s := by rw [union_diff_cancel interior_subset] rw [this] exact isOpen_interior.measurableSet.union H.measurableSet have A : ∀ x ∈ s, ∃ y ∈ Ioi x, Ioo x y ⊆ s := fun x hx => (mem_nhdsWithin_Ioi_iff_exists_Ioo_subset' (hM x hx)).1 (h x hx) choose! y hy h'y using A have B : Set.PairwiseDisjoint (s \ interior s) fun x => Ioo x (y x) := by intro x hx x' hx' hxx' rcases lt_or_gt_of_ne hxx' with (h' | h') · refine disjoint_left.2 fun z hz h'z => ?_ have : x' ∈ interior s := mem_interior.2 ⟨Ioo x (y x), h'y _ hx.1, isOpen_Ioo, ⟨h', h'z.1.trans hz.2⟩⟩ exact False.elim (hx'.2 this) · refine disjoint_left.2 fun z hz h'z => ?_ have : x ∈ interior s := mem_interior.2 ⟨Ioo x' (y x'), h'y _ hx'.1, isOpen_Ioo, ⟨h', hz.1.trans h'z.2⟩⟩ exact False.elim (hx.2 this) exact B.countable_of_Ioo fun x hx => hy x hx.1 /-- If a set is a right-neighborhood of all of its points, then it is measurable. -/ theorem measurableSet_of_mem_nhdsWithin_Ioi {s : Set α} (h : ∀ x ∈ s, s ∈ 𝓝[>] x) : MeasurableSet s := by by_cases H : ∃ x ∈ s, IsTop x · rcases H with ⟨x₀, x₀s, h₀⟩ have : s = {x₀} ∪ s \ {x₀} := by rw [union_diff_cancel (singleton_subset_iff.2 x₀s)] rw [this] refine (measurableSet_singleton _).union ?_ have A : ∀ x ∈ s \ {x₀}, x < x₀ := fun x hx => lt_of_le_of_ne (h₀ _) (by simpa using hx.2) refine measurableSet_of_mem_nhdsWithin_Ioi_aux (fun x hx => ?_) fun x hx => ⟨x₀, A x hx⟩ obtain ⟨u, hu, us⟩ : ∃ (u : α), u ∈ Ioi x ∧ Ioo x u ⊆ s := (mem_nhdsWithin_Ioi_iff_exists_Ioo_subset' (A x hx)).1 (h x hx.1) refine (mem_nhdsWithin_Ioi_iff_exists_Ioo_subset' (A x hx)).2 ⟨u, hu, fun y hy => ⟨us hy, ?_⟩⟩ exact ne_of_lt (hy.2.trans_le (h₀ _)) · apply measurableSet_of_mem_nhdsWithin_Ioi_aux h simp only [IsTop] at H push_neg at H exact H lemma measurableSet_bddAbove_range {ι} [Countable ι] {f : ι → δ → α} (hf : ∀ i, Measurable (f i)) : MeasurableSet {b | BddAbove (range (fun i ↦ f i b))} := by rcases isEmpty_or_nonempty α with hα|hα · have : ∀ b, range (fun i ↦ f i b) = ∅ := fun b ↦ eq_empty_of_isEmpty _ simp [this] have A : ∀ (i : ι) (c : α), MeasurableSet {x | f i x ≤ c} := by intro i c exact measurableSet_le (hf i) measurable_const have B : ∀ (c : α), MeasurableSet {x | ∀ i, f i x ≤ c} := by intro c rw [setOf_forall] exact MeasurableSet.iInter (fun i ↦ A i c) obtain ⟨u, hu⟩ : ∃ (u : ℕ → α), Tendsto u atTop atTop := exists_seq_tendsto (atTop : Filter α) have : {b | BddAbove (range (fun i ↦ f i b))} = {x | ∃ n, ∀ i, f i x ≤ u n} := by apply Subset.antisymm · rintro x ⟨c, hc⟩ obtain ⟨n, hn⟩ : ∃ n, c ≤ u n := (tendsto_atTop.1 hu c).exists exact ⟨n, fun i ↦ (hc ((mem_range_self i))).trans hn⟩ · rintro x ⟨n, hn⟩ refine ⟨u n, ?_⟩ rintro - ⟨i, rfl⟩ exact hn i rw [this, setOf_exists] exact MeasurableSet.iUnion (fun n ↦ B (u n)) lemma measurableSet_bddBelow_range {ι} [Countable ι] {f : ι → δ → α} (hf : ∀ i, Measurable (f i)) : MeasurableSet {b | BddBelow (range (fun i ↦ f i b))} := measurableSet_bddAbove_range (α := αᵒᵈ) hf end LinearOrder section ConditionallyCompleteLattice @[measurability] theorem Measurable.iSup_Prop {α} [MeasurableSpace α] [ConditionallyCompleteLattice α] (p : Prop) {f : δ → α} (hf : Measurable f) : Measurable fun b => ⨆ _ : p, f b := by classical simp_rw [ciSup_eq_ite] split_ifs with h · exact hf · exact measurable_const @[measurability] theorem Measurable.iInf_Prop {α} [MeasurableSpace α] [ConditionallyCompleteLattice α] (p : Prop) {f : δ → α} (hf : Measurable f) : Measurable fun b => ⨅ _ : p, f b := by classical simp_rw [ciInf_eq_ite] split_ifs with h · exact hf · exact measurable_const end ConditionallyCompleteLattice section ConditionallyCompleteLinearOrder variable [ConditionallyCompleteLinearOrder α] [OrderTopology α] [SecondCountableTopology α] @[measurability] theorem measurable_iSup {ι} [Countable ι] {f : ι → δ → α} (hf : ∀ i, Measurable (f i)) : Measurable (fun b ↦ ⨆ i, f i b) := by rcases isEmpty_or_nonempty ι with hι|hι · simp [iSup_of_empty'] have A : MeasurableSet {b | BddAbove (range (fun i ↦ f i b))} := measurableSet_bddAbove_range hf have : Measurable (fun (_b : δ) ↦ sSup (∅ : Set α)) := measurable_const apply Measurable.isLUB_of_mem hf A _ _ this · rintro b ⟨c, hc⟩ apply isLUB_ciSup refine ⟨c, ?_⟩ rintro d ⟨i, rfl⟩ exact hc (mem_range_self i) · intro b hb apply csSup_of_not_bddAbove exact hb @[measurability] theorem aemeasurable_iSup {ι} {μ : Measure δ} [Countable ι] {f : ι → δ → α} (hf : ∀ i, AEMeasurable (f i) μ) : AEMeasurable (fun b => ⨆ i, f i b) μ := by refine ⟨fun b ↦ ⨆ i, (hf i).mk (f i) b, measurable_iSup (fun i ↦ (hf i).measurable_mk), ?_⟩ filter_upwards [ae_all_iff.2 (fun i ↦ (hf i).ae_eq_mk)] with b hb using by simp [hb] @[measurability] theorem measurable_iInf {ι} [Countable ι] {f : ι → δ → α} (hf : ∀ i, Measurable (f i)) : Measurable fun b => ⨅ i, f i b := measurable_iSup (α := αᵒᵈ) hf @[measurability] theorem aemeasurable_iInf {ι} {μ : Measure δ} [Countable ι] {f : ι → δ → α} (hf : ∀ i, AEMeasurable (f i) μ) : AEMeasurable (fun b => ⨅ i, f i b) μ := aemeasurable_iSup (α := αᵒᵈ) hf theorem measurable_sSup {ι} {f : ι → δ → α} {s : Set ι} (hs : s.Countable) (hf : ∀ i ∈ s, Measurable (f i)) : Measurable fun x => sSup ((fun i => f i x) '' s) := by have : Countable ↑s := countable_coe_iff.2 hs convert measurable_iSup (f := (fun (i : s) ↦ f i)) (fun i ↦ hf i i.2) using 1 ext b congr exact image_eq_range (fun i ↦ f i b) s theorem measurable_sInf {ι} {f : ι → δ → α} {s : Set ι} (hs : s.Countable) (hf : ∀ i ∈ s, Measurable (f i)) : Measurable fun x => sInf ((fun i => f i x) '' s) := measurable_sSup (α := αᵒᵈ) hs hf theorem measurable_biSup {ι} (s : Set ι) {f : ι → δ → α} (hs : s.Countable) (hf : ∀ i ∈ s, Measurable (f i)) : Measurable fun b => ⨆ i ∈ s, f i b := by haveI : Encodable s := hs.toEncodable by_cases H : ∀ i, i ∈ s · have : ∀ b, ⨆ i ∈ s, f i b = ⨆ (i : s), f i b := fun b ↦ cbiSup_eq_of_forall (f := fun i ↦ f i b) H simp only [this] exact measurable_iSup (fun (i : s) ↦ hf i i.2) · have : ∀ b, ⨆ i ∈ s, f i b = (⨆ (i : s), f i b) ⊔ sSup ∅ := fun b ↦ cbiSup_eq_of_not_forall (f := fun i ↦ f i b) H simp only [this] apply Measurable.sup _ measurable_const exact measurable_iSup (fun (i : s) ↦ hf i i.2) theorem aemeasurable_biSup {ι} {μ : Measure δ} (s : Set ι) {f : ι → δ → α} (hs : s.Countable) (hf : ∀ i ∈ s, AEMeasurable (f i) μ) : AEMeasurable (fun b => ⨆ i ∈ s, f i b) μ := by classical let g : ι → δ → α := fun i ↦ if hi : i ∈ s then (hf i hi).mk (f i) else fun _b ↦ sSup ∅ have : ∀ i ∈ s, Measurable (g i) := by intro i hi simpa [g, hi] using (hf i hi).measurable_mk refine ⟨fun b ↦ ⨆ (i) (_ : i ∈ s), g i b, measurable_biSup s hs this, ?_⟩ have : ∀ i ∈ s, ∀ᵐ b ∂μ, f i b = g i b := fun i hi ↦ by simpa [g, hi] using (hf i hi).ae_eq_mk filter_upwards [(ae_ball_iff hs).2 this] with b hb exact iSup_congr fun i => iSup_congr (hb i) theorem measurable_biInf {ι} (s : Set ι) {f : ι → δ → α} (hs : s.Countable) (hf : ∀ i ∈ s, Measurable (f i)) : Measurable fun b => ⨅ i ∈ s, f i b := measurable_biSup (α := αᵒᵈ) s hs hf theorem aemeasurable_biInf {ι} {μ : Measure δ} (s : Set ι) {f : ι → δ → α} (hs : s.Countable) (hf : ∀ i ∈ s, AEMeasurable (f i) μ) : AEMeasurable (fun b => ⨅ i ∈ s, f i b) μ := aemeasurable_biSup (α := αᵒᵈ) s hs hf /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ theorem measurable_liminf' {ι ι'} {f : ι → δ → α} {v : Filter ι} (hf : ∀ i, Measurable (f i)) {p : ι' → Prop} {s : ι' → Set ι} (hv : v.HasCountableBasis p s) (hs : ∀ j, (s j).Countable) : Measurable fun x => liminf (f · x) v := by classical /- We would like to write the liminf as `⨆ (j : Subtype p), ⨅ (i : s j), f i x`, as the measurability would follow from the measurability of infs and sups. Unfortunately, this is not true in general conditionally complete linear orders because of issues with empty sets or sets which are not bounded above or below. A slightly more complicated expression for the liminf, valid in general, is given in `Filter.HasBasis.liminf_eq_ite`. This expression, built from `if ... then ... else` and infs and sups, can be readily checked to be measurable. -/ have : Countable (Subtype p) := hv.countable rcases isEmpty_or_nonempty (Subtype p) with hp|hp · simp [hv.liminf_eq_sSup_iUnion_iInter] by_cases H : ∃ (j : Subtype p), s j = ∅ · simp_rw [hv.liminf_eq_ite, if_pos H, measurable_const] simp_rw [hv.liminf_eq_ite, if_neg H] have : ∀ i, Countable (s i) := fun i ↦ countable_coe_iff.2 (hs i) let m : Subtype p → Set δ := fun j ↦ {x | BddBelow (range (fun (i : s j) ↦ f i x))} have m_meas : ∀ j, MeasurableSet (m j) := fun j ↦ measurableSet_bddBelow_range (fun (i : s j) ↦ hf i) have mc_meas : MeasurableSet {x | ∀ (j : Subtype p), x ∉ m j} := by rw [setOf_forall] exact MeasurableSet.iInter (fun j ↦ (m_meas j).compl) apply Measurable.piecewise mc_meas measurable_const apply measurable_iSup (fun j ↦ ?_) let reparam : δ → Subtype p → Subtype p := fun x ↦ liminf_reparam (fun i ↦ f i x) s p let F0 : Subtype p → δ → α := fun j x ↦ ⨅ (i : s j), f i x have F0_meas : ∀ j, Measurable (F0 j) := fun j ↦ measurable_iInf (fun (i : s j) ↦ hf i) set F1 : δ → α := fun x ↦ F0 (reparam x j) x with hF1 change Measurable F1 let g : ℕ → Subtype p := Classical.choose (exists_surjective_nat (Subtype p)) have Z : ∀ x, ∃ n, x ∈ m (g n) ∨ ∀ k, x ∉ m k := by intro x by_cases H : ∃ k, x ∈ m k · rcases H with ⟨k, hk⟩ rcases Classical.choose_spec (exists_surjective_nat (Subtype p)) k with ⟨n, rfl⟩ exact ⟨n, Or.inl hk⟩ · push_neg at H exact ⟨0, Or.inr H⟩ have : F1 = fun x ↦ if x ∈ m j then F0 j x else F0 (g (Nat.find (Z x))) x := by ext x have A : reparam x j = if x ∈ m j then j else g (Nat.find (Z x)) := rfl split_ifs with hjx · have : reparam x j = j := by rw [A, if_pos hjx] simp only [hF1, this] · have : reparam x j = g (Nat.find (Z x)) := by rw [A, if_neg hjx] simp only [hF1, this] rw [this] apply Measurable.piecewise (m_meas j) (F0_meas j) apply Measurable.find (fun n ↦ F0_meas (g n)) (fun n ↦ ?_) exact (m_meas (g n)).union mc_meas /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ theorem measurable_limsup' {ι ι'} {f : ι → δ → α} {u : Filter ι} (hf : ∀ i, Measurable (f i)) {p : ι' → Prop} {s : ι' → Set ι} (hu : u.HasCountableBasis p s) (hs : ∀ i, (s i).Countable) : Measurable fun x => limsup (fun i => f i x) u := measurable_liminf' (α := αᵒᵈ) hf hu hs /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] theorem measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, Measurable (f i)) : Measurable fun x => liminf (fun i => f i x) atTop := measurable_liminf' hf atTop_countable_basis fun _ => to_countable _ /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] theorem measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, Measurable (f i)) : Measurable fun x => limsup (fun i => f i x) atTop := measurable_limsup' hf atTop_countable_basis fun _ => to_countable _ end ConditionallyCompleteLinearOrder /-- Convert a `Homeomorph` to a `MeasurableEquiv`. -/ def Homemorph.toMeasurableEquiv (h : α ≃ₜ β) : α ≃ᵐ β where toEquiv := h.toEquiv measurable_toFun := h.continuous_toFun.measurable measurable_invFun := h.continuous_invFun.measurable protected theorem IsFiniteMeasureOnCompacts.map (μ : Measure α) [IsFiniteMeasureOnCompacts μ] (f : α ≃ₜ β) : IsFiniteMeasureOnCompacts (Measure.map f μ) := by refine ⟨fun K hK ↦ ?_⟩ rw [← Homeomorph.toMeasurableEquiv_coe, MeasurableEquiv.map_apply] exact IsCompact.measure_lt_top (f.isCompact_preimage.2 hK) end BorelSpace section ENNReal /-- One can cut out `ℝ≥0∞` into the sets `{0}`, `Ico (t^n) (t^(n+1))` for `n : ℤ` and `{∞}`. This gives a way to compute the measure of a set in terms of sets on which a given function `f` does not fluctuate by more than `t`. -/ theorem measure_eq_measure_preimage_add_measure_tsum_Ico_zpow {α : Type*} [MeasurableSpace α] (μ : Measure α) {f : α → ℝ≥0∞} (hf : Measurable f) {s : Set α} (hs : MeasurableSet s) {t : ℝ≥0} (ht : 1 < t) : μ s = μ (s ∩ f ⁻¹' {0}) + μ (s ∩ f ⁻¹' {∞}) + ∑' n : ℤ, μ (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) := by have A : μ s = μ (s ∩ f ⁻¹' {0}) + μ (s ∩ f ⁻¹' Ioi 0) := by rw [← measure_union] · rw [← inter_union_distrib_left, ← preimage_union, singleton_union, Ioi_insert, ← _root_.bot_eq_zero, Ici_bot, preimage_univ, inter_univ] · exact disjoint_singleton_left.mpr not_mem_Ioi_self |>.preimage f |>.inter_right' s |>.inter_left' s · exact hs.inter (hf measurableSet_Ioi) have B : μ (s ∩ f ⁻¹' Ioi 0) = μ (s ∩ f ⁻¹' {∞}) + μ (s ∩ f ⁻¹' Ioo 0 ∞) := by rw [← measure_union] · rw [← inter_union_distrib_left] congr ext x simp only [mem_singleton_iff, mem_union, mem_Ioo, mem_Ioi, mem_preimage] obtain (H | H) : f x = ∞ ∨ f x < ∞ := eq_or_lt_of_le le_top · simp only [H, eq_self_iff_true, or_false_iff, ENNReal.zero_lt_top, not_top_lt, and_false] · simp only [H, H.ne, and_true_iff, false_or_iff] · refine disjoint_left.2 fun x hx h'x => ?_ have : f x < ∞ := h'x.2.2 exact lt_irrefl _ (this.trans_le (le_of_eq hx.2.symm)) · exact hs.inter (hf measurableSet_Ioo) have C : μ (s ∩ f ⁻¹' Ioo 0 ∞) = ∑' n : ℤ, μ (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) := by rw [← measure_iUnion, ENNReal.Ioo_zero_top_eq_iUnion_Ico_zpow (ENNReal.one_lt_coe_iff.2 ht) ENNReal.coe_ne_top, preimage_iUnion, inter_iUnion] · intro i j hij wlog h : i < j generalizing i j · exact (this hij.symm (hij.lt_or_lt.resolve_left h)).symm refine disjoint_left.2 fun x hx h'x => lt_irrefl (f x) ?_ calc f x < (t : ℝ≥0∞) ^ (i + 1) := hx.2.2 _ ≤ (t : ℝ≥0∞) ^ j := ENNReal.zpow_le_of_le (ENNReal.one_le_coe_iff.2 ht.le) h _ ≤ f x := h'x.2.1 · intro n exact hs.inter (hf measurableSet_Ico) rw [A, B, C, add_assoc] end ENNReal
MeasureTheory\Constructions\BorelSpace\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 /-! # 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 n := 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 [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⟩ @[deprecated (since := "2024-03-02")] alias aEMeasurable_coe_nnreal_real_iff := aemeasurable_coe_nnreal_real_iff /-- 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_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_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 [← WithTop.coe_sub]; 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 fun _ ↦ MeasurableSMul.measurable_const_smul _ measurable_smul_const := fun x ↦ 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] show Measurable fun y => liminf (fun n => (f (x n) y : ℝ≥0∞)) atTop exact measurable_liminf fun n => hf (x n) @[deprecated (since := "2024-03-09")] alias _root_.measurable_of_tendsto_ennreal' := ENNReal.measurable_of_tendsto' /-- 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 @[deprecated (since := "2024-03-09")] alias _root_.measurable_of_tendsto_ennreal := ENNReal.measurable_of_tendsto /-- 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_let 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] apply measurable_iSup exact fun s => s.measurable_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] apply aemeasurable_iSup exact fun s => Finset.aemeasurable_sum s fun i _ => h i @[measurability, fun_prop] theorem AEMeasurable.nnreal_tsum {α : Type*} [MeasurableSpace α] {ι : Type*} [Countable ι] {f : ι → α → NNReal} {μ : MeasureTheory.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 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) @[deprecated (since := "2024-03-09")] alias _root_.measurable_of_tendsto_nnreal' := NNReal.measurable_of_tendsto' /-- 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 @[deprecated (since := "2024-03-09")] alias _root_.measurable_of_tendsto_nnreal := NNReal.measurable_of_tendsto end NNReal /-- 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 {m : MeasurableSpace α} {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_setOf_eq, Set.mem_univ, iff_true_iff] 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 measurable_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 ↦ measurableSet_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 [← nhdsWithin_right_sup_nhds_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 [← nhds_left'_sup_nhds_right, 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
MeasureTheory\Constructions\Polish\Basic.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, Felix Weilacher -/ import Mathlib.MeasureTheory.Constructions.BorelSpace.Metric import Mathlib.Topology.CountableSeparatingOn import Mathlib.Topology.MetricSpace.Perfect /-! # The Borel sigma-algebra on Polish spaces We discuss several results pertaining to the relationship between the topology and the Borel structure on Polish spaces. ## Main definitions and results First, we define standard Borel spaces. * A `StandardBorelSpace α` is a typeclass for measurable spaces which arise as the Borel sets of some Polish topology. Next, we define the class of analytic sets and establish its basic properties. * `MeasureTheory.AnalyticSet s`: a set in a topological space is analytic if it is the continuous image of a Polish space. Equivalently, it is empty, or the image of `ℕ → ℕ`. * `MeasureTheory.AnalyticSet.image_of_continuous`: a continuous image of an analytic set is analytic. * `MeasurableSet.analyticSet`: in a Polish space, any Borel-measurable set is analytic. Then, we show Lusin's theorem that two disjoint analytic sets can be separated by Borel sets. * `MeasurablySeparable s t` states that there exists a measurable set containing `s` and disjoint from `t`. * `AnalyticSet.measurablySeparable` shows that two disjoint analytic sets are separated by a Borel set. We then prove the Lusin-Souslin theorem that a continuous injective image of a Borel subset of a Polish space is Borel. The proof of this nontrivial result relies on the above results on analytic sets. * `MeasurableSet.image_of_continuousOn_injOn` asserts that, if `s` is a Borel measurable set in a Polish space, then the image of `s` under a continuous injective map is still Borel measurable. * `Continuous.measurableEmbedding` states that a continuous injective map on a Polish space is a measurable embedding for the Borel sigma-algebra. * `ContinuousOn.measurableEmbedding` is the same result for a map restricted to a measurable set on which it is continuous. * `Measurable.measurableEmbedding` states that a measurable injective map from a standard Borel space to a second-countable topological space is a measurable embedding. * `isClopenable_iff_measurableSet`: in a Polish space, a set is clopenable (i.e., it can be made open and closed by using a finer Polish topology) if and only if it is Borel-measurable. We use this to prove several versions of the Borel isomorphism theorem. * `PolishSpace.measurableEquivOfNotCountable` : Any two uncountable standard Borel spaces are Borel isomorphic. * `PolishSpace.Equiv.measurableEquiv` : Any two standard Borel spaces of the same cardinality are Borel isomorphic. -/ open Set Function PolishSpace PiNat TopologicalSpace Bornology Metric Filter Topology MeasureTheory /-! ### Standard Borel Spaces -/ variable (α : Type*) /-- A standard Borel space is a measurable space arising as the Borel sets of some Polish topology. This is useful in situations where a space has no natural topology or the natural topology in a space is non-Polish. To endow a standard Borel space `α` with a compatible Polish topology, use `letI := upgradeStandardBorel α`. One can then use `eq_borel_upgradeStandardBorel α` to rewrite the `MeasurableSpace α` instance to `borel α t`, where `t` is the new topology. -/ class StandardBorelSpace [MeasurableSpace α] : Prop where /-- There exists a compatible Polish topology. -/ polish : ∃ _ : TopologicalSpace α, BorelSpace α ∧ PolishSpace α /-- A convenience class similar to `UpgradedPolishSpace`. No instance should be registered. Instead one should use `letI := upgradeStandardBorel α`. -/ class UpgradedStandardBorel extends MeasurableSpace α, TopologicalSpace α, BorelSpace α, PolishSpace α /-- Use as `letI := upgradeStandardBorel α` to endow a standard Borel space `α` with a compatible Polish topology. Warning: following this with `borelize α` will cause an error. Instead, one can rewrite with `eq_borel_upgradeStandardBorel α`. TODO: fix the corresponding bug in `borelize`. -/ noncomputable def upgradeStandardBorel [MeasurableSpace α] [h : StandardBorelSpace α] : UpgradedStandardBorel α := by choose τ hb hp using h.polish constructor /-- The `MeasurableSpace α` instance on a `StandardBorelSpace` `α` is equal to the borel sets of `upgradeStandardBorel α`. -/ theorem eq_borel_upgradeStandardBorel [MeasurableSpace α] [StandardBorelSpace α] : ‹MeasurableSpace α› = @borel _ (upgradeStandardBorel α).toTopologicalSpace := @BorelSpace.measurable_eq _ (upgradeStandardBorel α).toTopologicalSpace _ (upgradeStandardBorel α).toBorelSpace variable {α} section variable [MeasurableSpace α] instance standardBorel_of_polish [τ : TopologicalSpace α] [BorelSpace α] [PolishSpace α] : StandardBorelSpace α := by exists τ instance countablyGenerated_of_standardBorel [StandardBorelSpace α] : MeasurableSpace.CountablyGenerated α := letI := upgradeStandardBorel α inferInstance instance measurableSingleton_of_standardBorel [StandardBorelSpace α] : MeasurableSingletonClass α := letI := upgradeStandardBorel α inferInstance namespace StandardBorelSpace variable {β : Type*} [MeasurableSpace β] section instances /-- A product of two standard Borel spaces is standard Borel. -/ instance prod [StandardBorelSpace α] [StandardBorelSpace β] : StandardBorelSpace (α × β) := letI := upgradeStandardBorel α letI := upgradeStandardBorel β inferInstance /-- A product of countably many standard Borel spaces is standard Borel. -/ instance pi_countable {ι : Type*} [Countable ι] {α : ι → Type*} [∀ n, MeasurableSpace (α n)] [∀ n, StandardBorelSpace (α n)] : StandardBorelSpace (∀ n, α n) := letI := fun n => upgradeStandardBorel (α n) inferInstance end instances end StandardBorelSpace end variable {ι : Type*} namespace MeasureTheory variable [TopologicalSpace α] /-! ### Analytic sets -/ /-- An analytic set is a set which is the continuous image of some Polish space. There are several equivalent characterizations of this definition. For the definition, we pick one that avoids universe issues: a set is analytic if and only if it is a continuous image of `ℕ → ℕ` (or if it is empty). The above more usual characterization is given in `analyticSet_iff_exists_polishSpace_range`. Warning: these are analytic sets in the context of descriptive set theory (which is why they are registered in the namespace `MeasureTheory`). They have nothing to do with analytic sets in the context of complex analysis. -/ irreducible_def AnalyticSet (s : Set α) : Prop := s = ∅ ∨ ∃ f : (ℕ → ℕ) → α, Continuous f ∧ range f = s theorem analyticSet_empty : AnalyticSet (∅ : Set α) := by rw [AnalyticSet] exact Or.inl rfl theorem analyticSet_range_of_polishSpace {β : Type*} [TopologicalSpace β] [PolishSpace β] {f : β → α} (f_cont : Continuous f) : AnalyticSet (range f) := by cases isEmpty_or_nonempty β · rw [range_eq_empty] exact analyticSet_empty · rw [AnalyticSet] obtain ⟨g, g_cont, hg⟩ : ∃ g : (ℕ → ℕ) → β, Continuous g ∧ Surjective g := exists_nat_nat_continuous_surjective β refine Or.inr ⟨f ∘ g, f_cont.comp g_cont, ?_⟩ rw [hg.range_comp] /-- The image of an open set under a continuous map is analytic. -/ theorem _root_.IsOpen.analyticSet_image {β : Type*} [TopologicalSpace β] [PolishSpace β] {s : Set β} (hs : IsOpen s) {f : β → α} (f_cont : Continuous f) : AnalyticSet (f '' s) := by rw [image_eq_range] haveI : PolishSpace s := hs.polishSpace exact analyticSet_range_of_polishSpace (f_cont.comp continuous_subtype_val) /-- A set is analytic if and only if it is the continuous image of some Polish space. -/ theorem analyticSet_iff_exists_polishSpace_range {s : Set α} : AnalyticSet s ↔ ∃ (β : Type) (h : TopologicalSpace β) (_ : @PolishSpace β h) (f : β → α), @Continuous _ _ h _ f ∧ range f = s := by constructor · intro h rw [AnalyticSet] at h cases' h with h h · refine ⟨Empty, inferInstance, inferInstance, Empty.elim, continuous_bot, ?_⟩ rw [h] exact range_eq_empty _ · exact ⟨ℕ → ℕ, inferInstance, inferInstance, h⟩ · rintro ⟨β, h, h', f, f_cont, f_range⟩ rw [← f_range] exact analyticSet_range_of_polishSpace f_cont /-- The continuous image of an analytic set is analytic -/ theorem AnalyticSet.image_of_continuousOn {β : Type*} [TopologicalSpace β] {s : Set α} (hs : AnalyticSet s) {f : α → β} (hf : ContinuousOn f s) : AnalyticSet (f '' s) := by rcases analyticSet_iff_exists_polishSpace_range.1 hs with ⟨γ, γtop, γpolish, g, g_cont, gs⟩ have : f '' s = range (f ∘ g) := by rw [range_comp, gs] rw [this] apply analyticSet_range_of_polishSpace apply hf.comp_continuous g_cont fun x => _ rw [← gs] exact mem_range_self theorem AnalyticSet.image_of_continuous {β : Type*} [TopologicalSpace β] {s : Set α} (hs : AnalyticSet s) {f : α → β} (hf : Continuous f) : AnalyticSet (f '' s) := hs.image_of_continuousOn hf.continuousOn /-- A countable intersection of analytic sets is analytic. -/ theorem AnalyticSet.iInter [hι : Nonempty ι] [Countable ι] [T2Space α] {s : ι → Set α} (hs : ∀ n, AnalyticSet (s n)) : AnalyticSet (⋂ n, s n) := by rcases hι with ⟨i₀⟩ /- For the proof, write each `s n` as the continuous image under a map `f n` of a Polish space `β n`. The product space `γ = Π n, β n` is also Polish, and so is the subset `t` of sequences `x n` for which `f n (x n)` is independent of `n`. The set `t` is Polish, and the range of `x ↦ f 0 (x 0)` on `t` is exactly `⋂ n, s n`, so this set is analytic. -/ choose β hβ h'β f f_cont f_range using fun n => analyticSet_iff_exists_polishSpace_range.1 (hs n) let γ := ∀ n, β n let t : Set γ := ⋂ n, { x | f n (x n) = f i₀ (x i₀) } have t_closed : IsClosed t := by apply isClosed_iInter intro n exact isClosed_eq ((f_cont n).comp (continuous_apply n)) ((f_cont i₀).comp (continuous_apply i₀)) haveI : PolishSpace t := t_closed.polishSpace let F : t → α := fun x => f i₀ ((x : γ) i₀) have F_cont : Continuous F := (f_cont i₀).comp ((continuous_apply i₀).comp continuous_subtype_val) have F_range : range F = ⋂ n : ι, s n := by apply Subset.antisymm · rintro y ⟨x, rfl⟩ refine mem_iInter.2 fun n => ?_ have : f n ((x : γ) n) = F x := (mem_iInter.1 x.2 n : _) rw [← this, ← f_range n] exact mem_range_self _ · intro y hy have A : ∀ n, ∃ x : β n, f n x = y := by intro n rw [← mem_range, f_range n] exact mem_iInter.1 hy n choose x hx using A have xt : x ∈ t := by refine mem_iInter.2 fun n => ?_ simp [hx] refine ⟨⟨x, xt⟩, ?_⟩ exact hx i₀ rw [← F_range] exact analyticSet_range_of_polishSpace F_cont /-- A countable union of analytic sets is analytic. -/ theorem AnalyticSet.iUnion [Countable ι] {s : ι → Set α} (hs : ∀ n, AnalyticSet (s n)) : AnalyticSet (⋃ n, s n) := by /- For the proof, write each `s n` as the continuous image under a map `f n` of a Polish space `β n`. The union space `γ = Σ n, β n` is also Polish, and the map `F : γ → α` which coincides with `f n` on `β n` sends it to `⋃ n, s n`. -/ choose β hβ h'β f f_cont f_range using fun n => analyticSet_iff_exists_polishSpace_range.1 (hs n) let γ := Σn, β n let F : γ → α := fun ⟨n, x⟩ ↦ f n x have F_cont : Continuous F := continuous_sigma f_cont have F_range : range F = ⋃ n, s n := by simp only [γ, range_sigma_eq_iUnion_range, f_range] rw [← F_range] exact analyticSet_range_of_polishSpace F_cont theorem _root_.IsClosed.analyticSet [PolishSpace α] {s : Set α} (hs : IsClosed s) : AnalyticSet s := by haveI : PolishSpace s := hs.polishSpace rw [← @Subtype.range_val α s] exact analyticSet_range_of_polishSpace continuous_subtype_val /-- Given a Borel-measurable set in a Polish space, there exists a finer Polish topology making it clopen. This is in fact an equivalence, see `isClopenable_iff_measurableSet`. -/ theorem _root_.MeasurableSet.isClopenable [PolishSpace α] [MeasurableSpace α] [BorelSpace α] {s : Set α} (hs : MeasurableSet s) : IsClopenable s := by revert s apply MeasurableSet.induction_on_open · exact fun u hu => hu.isClopenable · exact fun u _ h'u => h'u.compl · exact fun f _ _ hf => IsClopenable.iUnion hf /-- A Borel-measurable set in a Polish space is analytic. -/ theorem _root_.MeasurableSet.analyticSet {α : Type*} [t : TopologicalSpace α] [PolishSpace α] [MeasurableSpace α] [BorelSpace α] {s : Set α} (hs : MeasurableSet s) : AnalyticSet s := by /- For a short proof (avoiding measurable induction), one sees `s` as a closed set for a finer topology `t'`. It is analytic for this topology. As the identity from `t'` to `t` is continuous and the image of an analytic set is analytic, it follows that `s` is also analytic for `t`. -/ obtain ⟨t', t't, t'_polish, s_closed, _⟩ : ∃ t' : TopologicalSpace α, t' ≤ t ∧ @PolishSpace α t' ∧ IsClosed[t'] s ∧ IsOpen[t'] s := hs.isClopenable have A := @IsClosed.analyticSet α t' t'_polish s s_closed convert @AnalyticSet.image_of_continuous α t' α t s A id (continuous_id_of_le t't) simp only [id, image_id'] /-- Given a Borel-measurable function from a Polish space to a second-countable space, there exists a finer Polish topology on the source space for which the function is continuous. -/ theorem _root_.Measurable.exists_continuous {α β : Type*} [t : TopologicalSpace α] [PolishSpace α] [MeasurableSpace α] [BorelSpace α] [tβ : TopologicalSpace β] [MeasurableSpace β] [OpensMeasurableSpace β] {f : α → β} [SecondCountableTopology (range f)] (hf : Measurable f) : ∃ t' : TopologicalSpace α, t' ≤ t ∧ @Continuous α β t' tβ f ∧ @PolishSpace α t' := by obtain ⟨b, b_count, -, hb⟩ : ∃ b : Set (Set (range f)), b.Countable ∧ ∅ ∉ b ∧ IsTopologicalBasis b := exists_countable_basis (range f) haveI : Countable b := b_count.to_subtype have : ∀ s : b, IsClopenable (rangeFactorization f ⁻¹' s) := fun s ↦ by apply MeasurableSet.isClopenable exact hf.subtype_mk (hb.isOpen s.2).measurableSet choose T Tt Tpolish _ Topen using this obtain ⟨t', t'T, t't, t'_polish⟩ : ∃ t' : TopologicalSpace α, (∀ i, t' ≤ T i) ∧ t' ≤ t ∧ @PolishSpace α t' := exists_polishSpace_forall_le (t := t) T Tt Tpolish refine ⟨t', t't, ?_, t'_polish⟩ have : Continuous[t', _] (rangeFactorization f) := hb.continuous_iff.2 fun s hs => t'T ⟨s, hs⟩ _ (Topen ⟨s, hs⟩) exact continuous_subtype_val.comp this /-- The image of a measurable set in a standard Borel space under a measurable map is an analytic set. -/ theorem _root_.MeasurableSet.analyticSet_image {X Y : Type*} [MeasurableSpace X] [StandardBorelSpace X] [TopologicalSpace Y] [MeasurableSpace Y] [OpensMeasurableSpace Y] {f : X → Y} [SecondCountableTopology (range f)] {s : Set X} (hs : MeasurableSet s) (hf : Measurable f) : AnalyticSet (f '' s) := by letI := upgradeStandardBorel X rw [eq_borel_upgradeStandardBorel X] at hs rcases hf.exists_continuous with ⟨τ', hle, hfc, hτ'⟩ letI m' : MeasurableSpace X := @borel _ τ' haveI b' : BorelSpace X := ⟨rfl⟩ have hle := borel_anti hle exact (hle _ hs).analyticSet.image_of_continuous hfc /-- Preimage of an analytic set is an analytic set. -/ protected lemma AnalyticSet.preimage {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [PolishSpace X] [T2Space Y] {s : Set Y} (hs : AnalyticSet s) {f : X → Y} (hf : Continuous f) : AnalyticSet (f ⁻¹' s) := by rcases analyticSet_iff_exists_polishSpace_range.1 hs with ⟨Z, _, _, g, hg, rfl⟩ have : IsClosed {x : X × Z | f x.1 = g x.2} := isClosed_diagonal.preimage (hf.prod_map hg) convert this.analyticSet.image_of_continuous continuous_fst ext x simp [eq_comm] /-! ### Separating sets with measurable sets -/ /-- Two sets `u` and `v` in a measurable space are measurably separable if there exists a measurable set containing `u` and disjoint from `v`. This is mostly interesting for Borel-separable sets. -/ def MeasurablySeparable {α : Type*} [MeasurableSpace α] (s t : Set α) : Prop := ∃ u, s ⊆ u ∧ Disjoint t u ∧ MeasurableSet u theorem MeasurablySeparable.iUnion [Countable ι] {α : Type*} [MeasurableSpace α] {s t : ι → Set α} (h : ∀ m n, MeasurablySeparable (s m) (t n)) : MeasurablySeparable (⋃ n, s n) (⋃ m, t m) := by choose u hsu htu hu using h refine ⟨⋃ m, ⋂ n, u m n, ?_, ?_, ?_⟩ · refine iUnion_subset fun m => subset_iUnion_of_subset m ?_ exact subset_iInter fun n => hsu m n · simp_rw [disjoint_iUnion_left, disjoint_iUnion_right] intro n m apply Disjoint.mono_right _ (htu m n) apply iInter_subset · refine MeasurableSet.iUnion fun m => ?_ exact MeasurableSet.iInter fun n => hu m n /-- The hard part of the Lusin separation theorem saying that two disjoint analytic sets are contained in disjoint Borel sets (see the full statement in `AnalyticSet.measurablySeparable`). Here, we prove this when our analytic sets are the ranges of functions from `ℕ → ℕ`. -/ theorem measurablySeparable_range_of_disjoint [T2Space α] [MeasurableSpace α] [OpensMeasurableSpace α] {f g : (ℕ → ℕ) → α} (hf : Continuous f) (hg : Continuous g) (h : Disjoint (range f) (range g)) : MeasurablySeparable (range f) (range g) := by /- We follow [Kechris, *Classical Descriptive Set Theory* (Theorem 14.7)][kechris1995]. If the ranges are not Borel-separated, then one can find two cylinders of length one whose images are not Borel-separated, and then two smaller cylinders of length two whose images are not Borel-separated, and so on. One thus gets two sequences of cylinders, that decrease to two points `x` and `y`. Their images are different by the disjointness assumption, hence contained in two disjoint open sets by the T2 property. By continuity, long enough cylinders around `x` and `y` have images which are separated by these two disjoint open sets, a contradiction. -/ by_contra hfg have I : ∀ n x y, ¬MeasurablySeparable (f '' cylinder x n) (g '' cylinder y n) → ∃ x' y', x' ∈ cylinder x n ∧ y' ∈ cylinder y n ∧ ¬MeasurablySeparable (f '' cylinder x' (n + 1)) (g '' cylinder y' (n + 1)) := by intro n x y contrapose! intro H rw [← iUnion_cylinder_update x n, ← iUnion_cylinder_update y n, image_iUnion, image_iUnion] refine MeasurablySeparable.iUnion fun i j => ?_ exact H _ _ (update_mem_cylinder _ _ _) (update_mem_cylinder _ _ _) -- consider the set of pairs of cylinders of some length whose images are not Borel-separated let A := { p : ℕ × (ℕ → ℕ) × (ℕ → ℕ) // ¬MeasurablySeparable (f '' cylinder p.2.1 p.1) (g '' cylinder p.2.2 p.1) } -- for each such pair, one can find longer cylinders whose images are not Borel-separated either have : ∀ p : A, ∃ q : A, q.1.1 = p.1.1 + 1 ∧ q.1.2.1 ∈ cylinder p.1.2.1 p.1.1 ∧ q.1.2.2 ∈ cylinder p.1.2.2 p.1.1 := by rintro ⟨⟨n, x, y⟩, hp⟩ rcases I n x y hp with ⟨x', y', hx', hy', h'⟩ exact ⟨⟨⟨n + 1, x', y'⟩, h'⟩, rfl, hx', hy'⟩ choose F hFn hFx hFy using this let p0 : A := ⟨⟨0, fun _ => 0, fun _ => 0⟩, by simp [hfg]⟩ -- construct inductively decreasing sequences of cylinders whose images are not separated let p : ℕ → A := fun n => F^[n] p0 have prec : ∀ n, p (n + 1) = F (p n) := fun n => by simp only [p, iterate_succ', Function.comp] -- check that at the `n`-th step we deal with cylinders of length `n` have pn_fst : ∀ n, (p n).1.1 = n := by intro n induction' n with n IH · rfl · simp only [prec, hFn, IH] -- check that the cylinders we construct are indeed decreasing, by checking that the coordinates -- are stationary. have Ix : ∀ m n, m + 1 ≤ n → (p n).1.2.1 m = (p (m + 1)).1.2.1 m := by intro m apply Nat.le_induction · rfl intro n hmn IH have I : (F (p n)).val.snd.fst m = (p n).val.snd.fst m := by apply hFx (p n) m rw [pn_fst] exact hmn rw [prec, I, IH] have Iy : ∀ m n, m + 1 ≤ n → (p n).1.2.2 m = (p (m + 1)).1.2.2 m := by intro m apply Nat.le_induction · rfl intro n hmn IH have I : (F (p n)).val.snd.snd m = (p n).val.snd.snd m := by apply hFy (p n) m rw [pn_fst] exact hmn rw [prec, I, IH] -- denote by `x` and `y` the limit points of these two sequences of cylinders. set x : ℕ → ℕ := fun n => (p (n + 1)).1.2.1 n with hx set y : ℕ → ℕ := fun n => (p (n + 1)).1.2.2 n with hy -- by design, the cylinders around these points have images which are not Borel-separable. have M : ∀ n, ¬MeasurablySeparable (f '' cylinder x n) (g '' cylinder y n) := by intro n convert (p n).2 using 3 · rw [pn_fst, ← mem_cylinder_iff_eq, mem_cylinder_iff] intro i hi rw [hx] exact (Ix i n hi).symm · rw [pn_fst, ← mem_cylinder_iff_eq, mem_cylinder_iff] intro i hi rw [hy] exact (Iy i n hi).symm -- consider two open sets separating `f x` and `g y`. obtain ⟨u, v, u_open, v_open, xu, yv, huv⟩ : ∃ u v : Set α, IsOpen u ∧ IsOpen v ∧ f x ∈ u ∧ g y ∈ v ∧ Disjoint u v := by apply t2_separation exact disjoint_iff_forall_ne.1 h (mem_range_self _) (mem_range_self _) letI : MetricSpace (ℕ → ℕ) := metricSpaceNatNat obtain ⟨εx, εxpos, hεx⟩ : ∃ (εx : ℝ), εx > 0 ∧ Metric.ball x εx ⊆ f ⁻¹' u := by apply Metric.mem_nhds_iff.1 exact hf.continuousAt.preimage_mem_nhds (u_open.mem_nhds xu) obtain ⟨εy, εypos, hεy⟩ : ∃ (εy : ℝ), εy > 0 ∧ Metric.ball y εy ⊆ g ⁻¹' v := by apply Metric.mem_nhds_iff.1 exact hg.continuousAt.preimage_mem_nhds (v_open.mem_nhds yv) obtain ⟨n, hn⟩ : ∃ n : ℕ, (1 / 2 : ℝ) ^ n < min εx εy := exists_pow_lt_of_lt_one (lt_min εxpos εypos) (by norm_num) -- for large enough `n`, these open sets separate the images of long cylinders around `x` and `y` have B : MeasurablySeparable (f '' cylinder x n) (g '' cylinder y n) := by refine ⟨u, ?_, ?_, u_open.measurableSet⟩ · rw [image_subset_iff] apply Subset.trans _ hεx intro z hz rw [mem_cylinder_iff_dist_le] at hz exact hz.trans_lt (hn.trans_le (min_le_left _ _)) · refine Disjoint.mono_left ?_ huv.symm change g '' cylinder y n ⊆ v rw [image_subset_iff] apply Subset.trans _ hεy intro z hz rw [mem_cylinder_iff_dist_le] at hz exact hz.trans_lt (hn.trans_le (min_le_right _ _)) -- this is a contradiction. exact M n B /-- The **Lusin separation theorem**: if two analytic sets are disjoint, then they are contained in disjoint Borel sets. -/ theorem AnalyticSet.measurablySeparable [T2Space α] [MeasurableSpace α] [OpensMeasurableSpace α] {s t : Set α} (hs : AnalyticSet s) (ht : AnalyticSet t) (h : Disjoint s t) : MeasurablySeparable s t := by rw [AnalyticSet] at hs ht rcases hs with (rfl | ⟨f, f_cont, rfl⟩) · refine ⟨∅, Subset.refl _, by simp, MeasurableSet.empty⟩ rcases ht with (rfl | ⟨g, g_cont, rfl⟩) · exact ⟨univ, subset_univ _, by simp, MeasurableSet.univ⟩ exact measurablySeparable_range_of_disjoint f_cont g_cont h /-- **Suslin's Theorem**: in a Hausdorff topological space, an analytic set with an analytic complement is measurable. -/ theorem AnalyticSet.measurableSet_of_compl [T2Space α] [MeasurableSpace α] [OpensMeasurableSpace α] {s : Set α} (hs : AnalyticSet s) (hsc : AnalyticSet sᶜ) : MeasurableSet s := by rcases hs.measurablySeparable hsc disjoint_compl_right with ⟨u, hsu, hdu, hmu⟩ obtain rfl : s = u := hsu.antisymm (disjoint_compl_left_iff_subset.1 hdu) exact hmu end MeasureTheory /-! ### Measurability of preimages under measurable maps -/ namespace Measurable open MeasurableSpace variable {X Y Z β : Type*} [MeasurableSpace X] [StandardBorelSpace X] [TopologicalSpace Y] [T0Space Y] [MeasurableSpace Y] [OpensMeasurableSpace Y] [MeasurableSpace β] [MeasurableSpace Z] /-- If `f : X → Z` is a surjective Borel measurable map from a standard Borel space to a countably separated measurable space, then the preimage of a set `s` is measurable if and only if the set is measurable. One implication is the definition of measurability, the other one heavily relies on `X` being a standard Borel space. -/ theorem measurableSet_preimage_iff_of_surjective [CountablySeparated Z] {f : X → Z} (hf : Measurable f) (hsurj : Surjective f) {s : Set Z} : MeasurableSet (f ⁻¹' s) ↔ MeasurableSet s := by refine ⟨fun h => ?_, fun h => hf h⟩ rcases exists_opensMeasurableSpace_of_countablySeparated Z with ⟨τ, _, _, _⟩ apply AnalyticSet.measurableSet_of_compl · rw [← image_preimage_eq s hsurj] exact h.analyticSet_image hf · rw [← image_preimage_eq sᶜ hsurj] exact h.compl.analyticSet_image hf theorem map_measurableSpace_eq [CountablySeparated Z] {f : X → Z} (hf : Measurable f) (hsurj : Surjective f) : MeasurableSpace.map f ‹MeasurableSpace X› = ‹MeasurableSpace Z› := MeasurableSpace.ext fun _ => hf.measurableSet_preimage_iff_of_surjective hsurj theorem map_measurableSpace_eq_borel [SecondCountableTopology Y] {f : X → Y} (hf : Measurable f) (hsurj : Surjective f) : MeasurableSpace.map f ‹MeasurableSpace X› = borel Y := by have d := hf.mono le_rfl OpensMeasurableSpace.borel_le letI := borel Y; haveI : BorelSpace Y := ⟨rfl⟩ exact d.map_measurableSpace_eq hsurj theorem borelSpace_codomain [SecondCountableTopology Y] {f : X → Y} (hf : Measurable f) (hsurj : Surjective f) : BorelSpace Y := ⟨(hf.map_measurableSpace_eq hsurj).symm.trans <| hf.map_measurableSpace_eq_borel hsurj⟩ /-- If `f : X → Z` is a Borel measurable map from a standard Borel space to a countably separated measurable space then the preimage of a set `s` is measurable if and only if the set is measurable in `Set.range f`. -/ theorem measurableSet_preimage_iff_preimage_val {f : X → Z} [CountablySeparated (range f)] (hf : Measurable f) {s : Set Z} : MeasurableSet (f ⁻¹' s) ↔ MeasurableSet ((↑) ⁻¹' s : Set (range f)) := have hf' : Measurable (rangeFactorization f) := hf.subtype_mk hf'.measurableSet_preimage_iff_of_surjective (s := Subtype.val ⁻¹' s) surjective_onto_range /-- If `f : X → Z` is a Borel measurable map from a standard Borel space to a countably separated measurable space and the range of `f` is measurable, then the preimage of a set `s` is measurable if and only if the intesection with `Set.range f` is measurable. -/ theorem measurableSet_preimage_iff_inter_range {f : X → Z} [CountablySeparated (range f)] (hf : Measurable f) (hr : MeasurableSet (range f)) {s : Set Z} : MeasurableSet (f ⁻¹' s) ↔ MeasurableSet (s ∩ range f) := by rw [hf.measurableSet_preimage_iff_preimage_val, inter_comm, ← (MeasurableEmbedding.subtype_coe hr).measurableSet_image, Subtype.image_preimage_coe] /-- If `f : X → Z` is a Borel measurable map from a standard Borel space to a countably separated measurable space, then for any measurable space `β` and `g : Z → β`, the composition `g ∘ f` is measurable if and only if the restriction of `g` to the range of `f` is measurable. -/ theorem measurable_comp_iff_restrict {f : X → Z} [CountablySeparated (range f)] (hf : Measurable f) {g : Z → β} : Measurable (g ∘ f) ↔ Measurable (restrict (range f) g) := forall₂_congr fun s _ => measurableSet_preimage_iff_preimage_val hf (s := g ⁻¹' s) /-- If `f : X → Z` is a surjective Borel measurable map from a standard Borel space to a countably separated measurable space, then for any measurable space `α` and `g : Z → α`, the composition `g ∘ f` is measurable if and only if `g` is measurable. -/ theorem measurable_comp_iff_of_surjective [CountablySeparated Z] {f : X → Z} (hf : Measurable f) (hsurj : Surjective f) {g : Z → β} : Measurable (g ∘ f) ↔ Measurable g := forall₂_congr fun s _ => measurableSet_preimage_iff_of_surjective hf hsurj (s := g ⁻¹' s) end Measurable theorem Continuous.map_eq_borel {X Y : Type*} [TopologicalSpace X] [PolishSpace X] [MeasurableSpace X] [BorelSpace X] [TopologicalSpace Y] [T0Space Y] [SecondCountableTopology Y] {f : X → Y} (hf : Continuous f) (hsurj : Surjective f) : MeasurableSpace.map f ‹MeasurableSpace X› = borel Y := by borelize Y exact hf.measurable.map_measurableSpace_eq hsurj theorem Continuous.map_borel_eq {X Y : Type*} [TopologicalSpace X] [PolishSpace X] [TopologicalSpace Y] [T0Space Y] [SecondCountableTopology Y] {f : X → Y} (hf : Continuous f) (hsurj : Surjective f) : MeasurableSpace.map f (borel X) = borel Y := by borelize X exact hf.map_eq_borel hsurj instance Quotient.borelSpace {X : Type*} [TopologicalSpace X] [PolishSpace X] [MeasurableSpace X] [BorelSpace X] {s : Setoid X} [T0Space (Quotient s)] [SecondCountableTopology (Quotient s)] : BorelSpace (Quotient s) := ⟨continuous_quotient_mk'.map_eq_borel (surjective_quotient_mk' _)⟩ /-- When the subgroup `N < G` is not necessarily `Normal`, we have a `CosetSpace` as opposed to `QuotientGroup` (the next `instance`). TODO: typeclass inference should normally find this, but currently doesn't. E.g., `MeasurableSMul G (G ⧸ Γ)` fails to synthesize, even though `G ⧸ Γ` is the quotient of `G` by the action of `Γ`; it seems unable to pick up the `BorelSpace` instance. -/ @[to_additive AddCosetSpace.borelSpace] instance CosetSpace.borelSpace {G : Type*} [TopologicalSpace G] [PolishSpace G] [Group G] [MeasurableSpace G] [BorelSpace G] {N : Subgroup G} [T2Space (G ⧸ N)] [SecondCountableTopology (G ⧸ N)] : BorelSpace (G ⧸ N) := Quotient.borelSpace @[to_additive] instance QuotientGroup.borelSpace {G : Type*} [TopologicalSpace G] [PolishSpace G] [Group G] [TopologicalGroup G] [MeasurableSpace G] [BorelSpace G] {N : Subgroup G} [N.Normal] [IsClosed (N : Set G)] : BorelSpace (G ⧸ N) := -- Porting note: 1st and 3rd `haveI`s were not needed in Lean 3 haveI := Subgroup.t3_quotient_of_isClosed N haveI := QuotientGroup.secondCountableTopology (Γ := N) Quotient.borelSpace namespace MeasureTheory /-! ### Injective images of Borel sets -/ variable {γ : Type*} /-- The **Lusin-Souslin theorem**: the range of a continuous injective function defined on a Polish space is Borel-measurable. -/ theorem measurableSet_range_of_continuous_injective {β : Type*} [TopologicalSpace γ] [PolishSpace γ] [TopologicalSpace β] [T2Space β] [MeasurableSpace β] [OpensMeasurableSpace β] {f : γ → β} (f_cont : Continuous f) (f_inj : Injective f) : MeasurableSet (range f) := by /- We follow [Fremlin, *Measure Theory* (volume 4, 423I)][fremlin_vol4]. Let `b = {s i}` be a countable basis for `α`. When `s i` and `s j` are disjoint, their images are disjoint analytic sets, hence by the separation theorem one can find a Borel-measurable set `q i j` separating them. Let `E i = closure (f '' s i) ∩ ⋂ j, q i j \ q j i`. It contains `f '' (s i)` and it is measurable. Let `F n = ⋃ E i`, where the union is taken over those `i` for which `diam (s i)` is bounded by some number `u n` tending to `0` with `n`. We claim that `range f = ⋂ F n`, from which the measurability is obvious. The inclusion `⊆` is straightforward. To show `⊇`, consider a point `x` in the intersection. For each `n`, it belongs to some `E i` with `diam (s i) ≤ u n`. Pick a point `y i ∈ s i`. We claim that for such `i` and `j`, the intersection `s i ∩ s j` is nonempty: if it were empty, then thanks to the separating set `q i j` in the definition of `E i` one could not have `x ∈ E i ∩ E j`. Since these two sets have small diameter, it follows that `y i` and `y j` are close. Thus, `y` is a Cauchy sequence, converging to a limit `z`. We claim that `f z = x`, completing the proof. Otherwise, one could find open sets `v` and `w` separating `f z` from `x`. Then, for large `n`, the image `f '' (s i)` would be included in `v` by continuity of `f`, so its closure would be contained in the closure of `v`, and therefore it would be disjoint from `w`. This is a contradiction since `x` belongs both to this closure and to `w`. -/ letI := upgradePolishSpace γ obtain ⟨b, b_count, b_nonempty, hb⟩ : ∃ b : Set (Set γ), b.Countable ∧ ∅ ∉ b ∧ IsTopologicalBasis b := exists_countable_basis γ haveI : Encodable b := b_count.toEncodable let A := { p : b × b // Disjoint (p.1 : Set γ) p.2 } -- for each pair of disjoint sets in the topological basis `b`, consider Borel sets separating -- their images, by injectivity of `f` and the Lusin separation theorem. have : ∀ p : A, ∃ q : Set β, f '' (p.1.1 : Set γ) ⊆ q ∧ Disjoint (f '' (p.1.2 : Set γ)) q ∧ MeasurableSet q := by intro p apply AnalyticSet.measurablySeparable ((hb.isOpen p.1.1.2).analyticSet_image f_cont) ((hb.isOpen p.1.2.2).analyticSet_image f_cont) exact Disjoint.image p.2 f_inj.injOn (subset_univ _) (subset_univ _) choose q hq1 hq2 q_meas using this -- define sets `E i` and `F n` as in the proof sketch above let E : b → Set β := fun s => closure (f '' s) ∩ ⋂ (t : b) (ht : Disjoint s.1 t.1), q ⟨(s, t), ht⟩ \ q ⟨(t, s), ht.symm⟩ obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ u : ℕ → ℝ, StrictAnti u ∧ (∀ n : ℕ, 0 < u n) ∧ Tendsto u atTop (𝓝 0) := exists_seq_strictAnti_tendsto (0 : ℝ) let F : ℕ → Set β := fun n => ⋃ (s : b) (_ : IsBounded s.1 ∧ diam s.1 ≤ u n), E s -- it is enough to show that `range f = ⋂ F n`, as the latter set is obviously measurable. suffices range f = ⋂ n, F n by have E_meas : ∀ s : b, MeasurableSet (E s) := by intro b refine isClosed_closure.measurableSet.inter ?_ refine MeasurableSet.iInter fun s => ?_ exact MeasurableSet.iInter fun hs => (q_meas _).diff (q_meas _) have F_meas : ∀ n, MeasurableSet (F n) := by intro n refine MeasurableSet.iUnion fun s => ?_ exact MeasurableSet.iUnion fun _ => E_meas _ rw [this] exact MeasurableSet.iInter fun n => F_meas n -- we check both inclusions. apply Subset.antisymm -- we start with the easy inclusion `range f ⊆ ⋂ F n`. One just needs to unfold the definitions. · rintro x ⟨y, rfl⟩ refine mem_iInter.2 fun n => ?_ obtain ⟨s, sb, ys, hs⟩ : ∃ (s : Set γ), s ∈ b ∧ y ∈ s ∧ s ⊆ ball y (u n / 2) := by apply hb.mem_nhds_iff.1 exact ball_mem_nhds _ (half_pos (u_pos n)) have diam_s : diam s ≤ u n := by apply (diam_mono hs isBounded_ball).trans convert diam_ball (x := y) (half_pos (u_pos n)).le ring refine mem_iUnion.2 ⟨⟨s, sb⟩, ?_⟩ refine mem_iUnion.2 ⟨⟨isBounded_ball.subset hs, diam_s⟩, ?_⟩ apply mem_inter (subset_closure (mem_image_of_mem _ ys)) refine mem_iInter.2 fun t => mem_iInter.2 fun ht => ⟨?_, ?_⟩ · apply hq1 exact mem_image_of_mem _ ys · apply disjoint_left.1 (hq2 ⟨(t, ⟨s, sb⟩), ht.symm⟩) exact mem_image_of_mem _ ys -- Now, let us prove the harder inclusion `⋂ F n ⊆ range f`. · intro x hx -- pick for each `n` a good set `s n` of small diameter for which `x ∈ E (s n)`. have C1 : ∀ n, ∃ (s : b) (_ : IsBounded s.1 ∧ diam s.1 ≤ u n), x ∈ E s := fun n => by simpa only [F, mem_iUnion] using mem_iInter.1 hx n choose s hs hxs using C1 have C2 : ∀ n, (s n).1.Nonempty := by intro n rw [nonempty_iff_ne_empty] intro hn have := (s n).2 rw [hn] at this exact b_nonempty this -- choose a point `y n ∈ s n`. choose y hy using C2 have I : ∀ m n, ((s m).1 ∩ (s n).1).Nonempty := by intro m n rw [← not_disjoint_iff_nonempty_inter] by_contra! h have A : x ∈ q ⟨(s m, s n), h⟩ \ q ⟨(s n, s m), h.symm⟩ := haveI := mem_iInter.1 (hxs m).2 (s n) (mem_iInter.1 this h : _) have B : x ∈ q ⟨(s n, s m), h.symm⟩ \ q ⟨(s m, s n), h⟩ := haveI := mem_iInter.1 (hxs n).2 (s m) (mem_iInter.1 this h.symm : _) exact A.2 B.1 -- the points `y n` are nearby, and therefore they form a Cauchy sequence. have cauchy_y : CauchySeq y := by have : Tendsto (fun n => 2 * u n) atTop (𝓝 0) := by simpa only [mul_zero] using u_lim.const_mul 2 refine cauchySeq_of_le_tendsto_0' (fun n => 2 * u n) (fun m n hmn => ?_) this rcases I m n with ⟨z, zsm, zsn⟩ calc dist (y m) (y n) ≤ dist (y m) z + dist z (y n) := dist_triangle _ _ _ _ ≤ u m + u n := (add_le_add ((dist_le_diam_of_mem (hs m).1 (hy m) zsm).trans (hs m).2) ((dist_le_diam_of_mem (hs n).1 zsn (hy n)).trans (hs n).2)) _ ≤ 2 * u m := by linarith [u_anti.antitone hmn] haveI : Nonempty γ := ⟨y 0⟩ -- let `z` be its limit. let z := limUnder atTop y have y_lim : Tendsto y atTop (𝓝 z) := cauchy_y.tendsto_limUnder suffices f z = x by rw [← this] exact mem_range_self _ -- assume for a contradiction that `f z ≠ x`. by_contra! hne -- introduce disjoint open sets `v` and `w` separating `f z` from `x`. obtain ⟨v, w, v_open, w_open, fzv, xw, hvw⟩ := t2_separation hne obtain ⟨δ, δpos, hδ⟩ : ∃ δ > (0 : ℝ), ball z δ ⊆ f ⁻¹' v := by apply Metric.mem_nhds_iff.1 exact f_cont.continuousAt.preimage_mem_nhds (v_open.mem_nhds fzv) obtain ⟨n, hn⟩ : ∃ n, u n + dist (y n) z < δ := haveI : Tendsto (fun n => u n + dist (y n) z) atTop (𝓝 0) := by simpa only [add_zero] using u_lim.add (tendsto_iff_dist_tendsto_zero.1 y_lim) ((tendsto_order.1 this).2 _ δpos).exists -- for large enough `n`, the image of `s n` is contained in `v`, by continuity of `f`. have fsnv : f '' s n ⊆ v := by rw [image_subset_iff] apply Subset.trans _ hδ intro a ha calc dist a z ≤ dist a (y n) + dist (y n) z := dist_triangle _ _ _ _ ≤ u n + dist (y n) z := (add_le_add_right ((dist_le_diam_of_mem (hs n).1 ha (hy n)).trans (hs n).2) _) _ < δ := hn -- as `x` belongs to the closure of `f '' (s n)`, it belongs to the closure of `v`. have : x ∈ closure v := closure_mono fsnv (hxs n).1 -- this is a contradiction, as `x` is supposed to belong to `w`, which is disjoint from -- the closure of `v`. exact disjoint_left.1 (hvw.closure_left w_open) this xw theorem _root_.IsClosed.measurableSet_image_of_continuousOn_injOn [TopologicalSpace γ] [PolishSpace γ] {β : Type*} [TopologicalSpace β] [T2Space β] [MeasurableSpace β] [OpensMeasurableSpace β] {s : Set γ} (hs : IsClosed s) {f : γ → β} (f_cont : ContinuousOn f s) (f_inj : InjOn f s) : MeasurableSet (f '' s) := by rw [image_eq_range] haveI : PolishSpace s := IsClosed.polishSpace hs apply measurableSet_range_of_continuous_injective · rwa [continuousOn_iff_continuous_restrict] at f_cont · rwa [injOn_iff_injective] at f_inj variable {α β : Type*} [tβ : TopologicalSpace β] [T2Space β] [MeasurableSpace β] [MeasurableSpace α] {s : Set γ} {f : γ → β} /-- The Lusin-Souslin theorem: if `s` is Borel-measurable in a Polish space, then its image under a continuous injective map is also Borel-measurable. -/ theorem _root_.MeasurableSet.image_of_continuousOn_injOn [OpensMeasurableSpace β] [tγ : TopologicalSpace γ] [PolishSpace γ] [MeasurableSpace γ] [BorelSpace γ] (hs : MeasurableSet s) (f_cont : ContinuousOn f s) (f_inj : InjOn f s) : MeasurableSet (f '' s) := by obtain ⟨t', t't, t'_polish, s_closed, _⟩ : ∃ t' : TopologicalSpace γ, t' ≤ tγ ∧ @PolishSpace γ t' ∧ IsClosed[t'] s ∧ IsOpen[t'] s := hs.isClopenable exact @IsClosed.measurableSet_image_of_continuousOn_injOn γ t' t'_polish β _ _ _ _ s s_closed f (f_cont.mono_dom t't) f_inj /-- The Lusin-Souslin theorem: if `s` is Borel-measurable in a standard Borel space, then its image under a measurable injective map taking values in a countably separate measurable space is also Borel-measurable. -/ theorem _root_.MeasurableSet.image_of_measurable_injOn {f : γ → α} [MeasurableSpace.CountablySeparated α] [MeasurableSpace γ] [StandardBorelSpace γ] (hs : MeasurableSet s) (f_meas : Measurable f) (f_inj : InjOn f s) : MeasurableSet (f '' s) := by letI := upgradeStandardBorel γ let tγ : TopologicalSpace γ := inferInstance rcases exists_opensMeasurableSpace_of_countablySeparated α with ⟨τ, _, _, _⟩ -- for a finer Polish topology, `f` is continuous. Therefore, one may apply the corresponding -- result for continuous maps. obtain ⟨t', t't, f_cont, t'_polish⟩ : ∃ t' : TopologicalSpace γ, t' ≤ tγ ∧ @Continuous γ _ t' _ f ∧ @PolishSpace γ t' := f_meas.exists_continuous have M : MeasurableSet[@borel γ t'] s := @Continuous.measurable γ γ t' (@borel γ t') (@BorelSpace.opensMeasurable γ t' (@borel γ t') (@BorelSpace.mk _ _ (borel γ) rfl)) tγ _ _ _ (continuous_id_of_le t't) s hs exact @MeasurableSet.image_of_continuousOn_injOn γ _ _ _ _ s f _ t' t'_polish (@borel γ t') (@BorelSpace.mk _ _ (borel γ) rfl) M (@Continuous.continuousOn γ _ t' _ f s f_cont) f_inj /-- An injective continuous function on a Polish space is a measurable embedding. -/ theorem _root_.Continuous.measurableEmbedding [BorelSpace β] [TopologicalSpace γ] [PolishSpace γ] [MeasurableSpace γ] [BorelSpace γ] (f_cont : Continuous f) (f_inj : Injective f) : MeasurableEmbedding f := { injective := f_inj measurable := f_cont.measurable measurableSet_image' := fun _u hu => hu.image_of_continuousOn_injOn f_cont.continuousOn f_inj.injOn } /-- If `s` is Borel-measurable in a Polish space and `f` is continuous injective on `s`, then the restriction of `f` to `s` is a measurable embedding. -/ theorem _root_.ContinuousOn.measurableEmbedding [BorelSpace β] [TopologicalSpace γ] [PolishSpace γ] [MeasurableSpace γ] [BorelSpace γ] (hs : MeasurableSet s) (f_cont : ContinuousOn f s) (f_inj : InjOn f s) : MeasurableEmbedding (s.restrict f) := { injective := injOn_iff_injective.1 f_inj measurable := (continuousOn_iff_continuous_restrict.1 f_cont).measurable measurableSet_image' := by intro u hu have A : MeasurableSet (((↑) : s → γ) '' u) := (MeasurableEmbedding.subtype_coe hs).measurableSet_image.2 hu have B : MeasurableSet (f '' (((↑) : s → γ) '' u)) := A.image_of_continuousOn_injOn (f_cont.mono (Subtype.coe_image_subset s u)) (f_inj.mono (Subtype.coe_image_subset s u)) rwa [← image_comp] at B } /-- An injective measurable function from a standard Borel space to a countably separated measurable space is a measurable embedding. -/ theorem _root_.Measurable.measurableEmbedding {f : γ → α} [MeasurableSpace.CountablySeparated α] [MeasurableSpace γ] [StandardBorelSpace γ] (f_meas : Measurable f) (f_inj : Injective f) : MeasurableEmbedding f := { injective := f_inj measurable := f_meas measurableSet_image' := fun _u hu => hu.image_of_measurable_injOn f_meas f_inj.injOn } /-- If one Polish topology on a type refines another, they have the same Borel sets. -/ theorem borel_eq_borel_of_le {t t' : TopologicalSpace γ} (ht : PolishSpace (h := t)) (ht' : PolishSpace (h := t')) (hle : t ≤ t') : @borel _ t = @borel _ t' := by refine le_antisymm ?_ (borel_anti hle) intro s hs have e := @Continuous.measurableEmbedding _ _ t' _ (@borel _ t') _ (@BorelSpace.mk _ _ (borel γ) rfl) t _ (@borel _ t) (@BorelSpace.mk _ t (@borel _ t) rfl) (continuous_id_of_le hle) injective_id convert e.measurableSet_image.2 hs simp only [id_eq, image_id'] /-- In a Polish space, a set is clopenable if and only if it is Borel-measurable. -/ theorem isClopenable_iff_measurableSet [tγ : TopologicalSpace γ] [PolishSpace γ] [MeasurableSpace γ] [BorelSpace γ] : IsClopenable s ↔ MeasurableSet s := by -- we already know that a measurable set is clopenable. Conversely, assume that `s` is clopenable. refine ⟨fun hs => ?_, fun hs => hs.isClopenable⟩ borelize γ -- consider a finer topology `t'` in which `s` is open and closed. obtain ⟨t', t't, t'_polish, _, s_open⟩ : ∃ t' : TopologicalSpace γ, t' ≤ tγ ∧ @PolishSpace γ t' ∧ IsClosed[t'] s ∧ IsOpen[t'] s := hs rw [← borel_eq_borel_of_le t'_polish _ t't] · exact MeasurableSpace.measurableSet_generateFrom s_open infer_instance /-- The set of points for which a sequence of measurable functions converges to a given function is measurable. -/ @[measurability] lemma measurableSet_tendsto_fun [MeasurableSpace γ] [Countable ι] {l : Filter ι} [l.IsCountablyGenerated] [TopologicalSpace γ] [SecondCountableTopology γ] [PseudoMetrizableSpace γ] [OpensMeasurableSpace γ] {f : ι → β → γ} (hf : ∀ i, Measurable (f i)) {g : β → γ} (hg : Measurable g) : MeasurableSet { x | Tendsto (fun n ↦ f n x) l (𝓝 (g x)) } := by letI := TopologicalSpace.pseudoMetrizableSpacePseudoMetric γ simp_rw [tendsto_iff_dist_tendsto_zero (f := fun n ↦ f n _)] exact measurableSet_tendsto (𝓝 0) (fun n ↦ (hf n).dist hg) /-- The set of points for which a measurable sequence of functions converges is measurable. -/ @[measurability] theorem measurableSet_exists_tendsto [TopologicalSpace γ] [PolishSpace γ] [MeasurableSpace γ] [hγ : OpensMeasurableSpace γ] [Countable ι] {l : Filter ι} [l.IsCountablyGenerated] {f : ι → β → γ} (hf : ∀ i, Measurable (f i)) : MeasurableSet { x | ∃ c, Tendsto (fun n => f n x) l (𝓝 c) } := by rcases l.eq_or_neBot with rfl | hl · simp letI := upgradePolishSpace γ rcases l.exists_antitone_basis with ⟨u, hu⟩ simp_rw [← cauchy_map_iff_exists_tendsto] change MeasurableSet { x | _ ∧ _ } have : ∀ x, (map (f · x) l ×ˢ map (f · x) l).HasAntitoneBasis fun n => ((f · x) '' u n) ×ˢ ((f · x) '' u n) := fun x => (hu.map _).prod (hu.map _) simp_rw [and_iff_right (hl.map _), Filter.HasBasis.le_basis_iff (this _).toHasBasis Metric.uniformity_basis_dist_inv_nat_succ, Set.setOf_forall] refine MeasurableSet.biInter Set.countable_univ fun K _ => ?_ simp_rw [Set.setOf_exists, true_and] refine MeasurableSet.iUnion fun N => ?_ simp_rw [prod_image_image_eq, image_subset_iff, prod_subset_iff, Set.setOf_forall] exact MeasurableSet.biInter (to_countable (u N)) fun i _ => MeasurableSet.biInter (to_countable (u N)) fun j _ => measurableSet_lt (Measurable.dist (hf i) (hf j)) measurable_const end MeasureTheory namespace StandardBorelSpace variable [MeasurableSpace α] [StandardBorelSpace α] /-- If `s` is a measurable set in a standard Borel space, there is a compatible Polish topology making `s` clopen. -/ theorem _root_.MeasurableSet.isClopenable' {s : Set α} (hs : MeasurableSet s) : ∃ _ : TopologicalSpace α, BorelSpace α ∧ PolishSpace α ∧ IsClosed s ∧ IsOpen s := by letI := upgradeStandardBorel α obtain ⟨t, hle, ht, s_clopen⟩ := hs.isClopenable refine ⟨t, ?_, ht, s_clopen⟩ constructor rw [eq_borel_upgradeStandardBorel α, borel_eq_borel_of_le ht _ hle] infer_instance /-- A measurable subspace of a standard Borel space is standard Borel. -/ theorem _root_.MeasurableSet.standardBorel {s : Set α} (hs : MeasurableSet s) : StandardBorelSpace s := by obtain ⟨_, _, _, s_closed, _⟩ := hs.isClopenable' haveI := s_closed.polishSpace infer_instance end StandardBorelSpace /-! ### The Borel Isomorphism Theorem -/ namespace PolishSpace variable {β : Type*} variable [MeasurableSpace α] [MeasurableSpace β] [StandardBorelSpace α] [StandardBorelSpace β] /-- If two standard Borel spaces admit Borel measurable injections to one another, then they are Borel isomorphic. -/ noncomputable def borelSchroederBernstein {f : α → β} {g : β → α} (fmeas : Measurable f) (finj : Function.Injective f) (gmeas : Measurable g) (ginj : Function.Injective g) : α ≃ᵐ β := letI := upgradeStandardBorel α letI := upgradeStandardBorel β (fmeas.measurableEmbedding finj).schroederBernstein (gmeas.measurableEmbedding ginj) /-- Any uncountable standard Borel space is Borel isomorphic to the Cantor space `ℕ → Bool`. -/ noncomputable def measurableEquivNatBoolOfNotCountable (h : ¬Countable α) : α ≃ᵐ (ℕ → Bool) := by apply Nonempty.some letI := upgradeStandardBorel α obtain ⟨f, -, fcts, finj⟩ := isClosed_univ.exists_nat_bool_injection_of_not_countable (by rwa [← countable_coe_iff, (Equiv.Set.univ _).countable_iff]) obtain ⟨g, gmeas, ginj⟩ := MeasurableSpace.measurable_injection_nat_bool_of_countablySeparated α exact ⟨borelSchroederBernstein gmeas ginj fcts.measurable finj⟩ /-- The **Borel Isomorphism Theorem**: Any two uncountable standard Borel spaces are Borel isomorphic. -/ noncomputable def measurableEquivOfNotCountable (hα : ¬Countable α) (hβ : ¬Countable β) : α ≃ᵐ β := (measurableEquivNatBoolOfNotCountable hα).trans (measurableEquivNatBoolOfNotCountable hβ).symm /-- The **Borel Isomorphism Theorem**: If two standard Borel spaces have the same cardinality, they are Borel isomorphic. -/ noncomputable def Equiv.measurableEquiv (e : α ≃ β) : α ≃ᵐ β := by by_cases h : Countable α · letI := Countable.of_equiv α e refine ⟨e, ?_, ?_⟩ <;> apply measurable_of_countable refine measurableEquivOfNotCountable h ?_ rwa [e.countable_iff] at h end PolishSpace
MeasureTheory\Constructions\Polish\EmbeddingReal.lean
/- Copyright (c) 2023 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import Mathlib.Data.Real.Cardinality import Mathlib.MeasureTheory.Constructions.Polish.Basic /-! # A Polish Borel space is measurably equivalent to a set of reals -/ open Set Function PolishSpace PiNat TopologicalSpace Bornology Metric Filter Topology MeasureTheory namespace MeasureTheory variable (α : Type*) [MeasurableSpace α] [StandardBorelSpace α] theorem exists_nat_measurableEquiv_range_coe_fin_of_finite [Finite α] : ∃ n : ℕ, Nonempty (α ≃ᵐ range ((↑) : Fin n → ℝ)) := by obtain ⟨n, ⟨n_equiv⟩⟩ := Finite.exists_equiv_fin α refine ⟨n, ⟨PolishSpace.Equiv.measurableEquiv (n_equiv.trans ?_)⟩⟩ exact Equiv.ofInjective _ (Nat.cast_injective.comp Fin.val_injective) theorem measurableEquiv_range_coe_nat_of_infinite_of_countable [Infinite α] [Countable α] : Nonempty (α ≃ᵐ range ((↑) : ℕ → ℝ)) := by have : PolishSpace (range ((↑) : ℕ → ℝ)) := Nat.closedEmbedding_coe_real.isClosedMap.isClosed_range.polishSpace refine ⟨PolishSpace.Equiv.measurableEquiv ?_⟩ refine (nonempty_equiv_of_countable.some : α ≃ ℕ).trans ?_ exact Equiv.ofInjective ((↑) : ℕ → ℝ) Nat.cast_injective /-- Any standard Borel space is measurably equivalent to a subset of the reals. -/ theorem exists_subset_real_measurableEquiv : ∃ s : Set ℝ, MeasurableSet s ∧ Nonempty (α ≃ᵐ s) := by by_cases hα : Countable α · cases finite_or_infinite α · obtain ⟨n, h_nonempty_equiv⟩ := exists_nat_measurableEquiv_range_coe_fin_of_finite α refine ⟨_, ?_, h_nonempty_equiv⟩ letI : MeasurableSpace (Fin n) := borel (Fin n) haveI : BorelSpace (Fin n) := ⟨rfl⟩ apply MeasurableEmbedding.measurableSet_range (mα := by infer_instance) exact continuous_of_discreteTopology.measurableEmbedding (Nat.cast_injective.comp Fin.val_injective) · refine ⟨_, ?_, measurableEquiv_range_coe_nat_of_infinite_of_countable α⟩ apply MeasurableEmbedding.measurableSet_range (mα := by infer_instance) exact continuous_of_discreteTopology.measurableEmbedding Nat.cast_injective · refine ⟨univ, MeasurableSet.univ, ⟨(PolishSpace.measurableEquivOfNotCountable hα ?_ : α ≃ᵐ (univ : Set ℝ))⟩⟩ rw [countable_coe_iff] exact Cardinal.not_countable_real /-- Any standard Borel space embeds measurably into the reals. -/ theorem exists_measurableEmbedding_real : ∃ f : α → ℝ, MeasurableEmbedding f := by obtain ⟨s, hs, ⟨e⟩⟩ := exists_subset_real_measurableEquiv α exact ⟨(↑) ∘ e, (MeasurableEmbedding.subtype_coe hs).comp e.measurableEmbedding⟩ /-- A measurable embedding of a standard Borel space into `ℝ`. -/ noncomputable def embeddingReal (Ω : Type*) [MeasurableSpace Ω] [StandardBorelSpace Ω] : Ω → ℝ := (exists_measurableEmbedding_real Ω).choose lemma measurableEmbedding_embeddingReal (Ω : Type*) [MeasurableSpace Ω] [StandardBorelSpace Ω] : MeasurableEmbedding (embeddingReal Ω) := (exists_measurableEmbedding_real Ω).choose_spec end MeasureTheory
MeasureTheory\Constructions\Prod\Basic.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.MeasureTheory.Measure.GiryMonad import Mathlib.Dynamics.Ergodic.MeasurePreserving import Mathlib.MeasureTheory.Integral.Lebesgue import Mathlib.MeasureTheory.Measure.OpenPos /-! # The product measure In this file we define and prove properties about the binary product measure. If `α` and `β` have s-finite measures `μ` resp. `ν` then `α × β` can be equipped with a s-finite measure `μ.prod ν` that satisfies `(μ.prod ν) s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`. We also have `(μ.prod ν) (s ×ˢ t) = μ s * ν t`, i.e. the measure of a rectangle is the product of the measures of the sides. We also prove Tonelli's theorem. ## Main definition * `MeasureTheory.Measure.prod`: The product of two measures. ## Main results * `MeasureTheory.Measure.prod_apply` states `μ.prod ν s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ` for measurable `s`. `MeasureTheory.Measure.prod_apply_symm` is the reversed version. * `MeasureTheory.Measure.prod_prod` states `μ.prod ν (s ×ˢ t) = μ s * ν t` for measurable sets `s` and `t`. * `MeasureTheory.lintegral_prod`: Tonelli's theorem. It states that for a measurable function `α × β → ℝ≥0∞` we have `∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ`. The version for functions `α → β → ℝ≥0∞` is reversed, and called `lintegral_lintegral`. Both versions have a variant with `_symm` appended, where the order of integration is reversed. The lemma `Measurable.lintegral_prod_right'` states that the inner integral of the right-hand side is measurable. ## Implementation Notes Many results are proven twice, once for functions in curried form (`α → β → γ`) and one for functions in uncurried form (`α × β → γ`). The former often has an assumption `Measurable (uncurry f)`, which could be inconvenient to discharge, but for the latter it is more common that the function has to be given explicitly, since Lean cannot synthesize the function by itself. We name the lemmas about the uncurried form with a prime. Tonelli's theorem has a different naming scheme, since the version for the uncurried version is reversed. ## Tags product measure, Tonelli's theorem, Fubini-Tonelli theorem -/ noncomputable section open Topology ENNReal MeasureTheory Set Function Real ENNReal MeasurableSpace MeasureTheory.Measure open TopologicalSpace hiding generateFrom open Filter hiding prod_eq map variable {α α' β β' γ E : Type*} /-- Rectangles formed by π-systems form a π-system. -/ theorem IsPiSystem.prod {C : Set (Set α)} {D : Set (Set β)} (hC : IsPiSystem C) (hD : IsPiSystem D) : IsPiSystem (image2 (· ×ˢ ·) C D) := by rintro _ ⟨s₁, hs₁, t₁, ht₁, rfl⟩ _ ⟨s₂, hs₂, t₂, ht₂, rfl⟩ hst rw [prod_inter_prod] at hst ⊢; rw [prod_nonempty_iff] at hst exact mem_image2_of_mem (hC _ hs₁ _ hs₂ hst.1) (hD _ ht₁ _ ht₂ hst.2) /-- Rectangles of countably spanning sets are countably spanning. -/ theorem IsCountablySpanning.prod {C : Set (Set α)} {D : Set (Set β)} (hC : IsCountablySpanning C) (hD : IsCountablySpanning D) : IsCountablySpanning (image2 (· ×ˢ ·) C D) := by rcases hC, hD with ⟨⟨s, h1s, h2s⟩, t, h1t, h2t⟩ refine ⟨fun n => s n.unpair.1 ×ˢ t n.unpair.2, fun n => mem_image2_of_mem (h1s _) (h1t _), ?_⟩ rw [iUnion_unpair_prod, h2s, h2t, univ_prod_univ] variable [MeasurableSpace α] [MeasurableSpace α'] [MeasurableSpace β] [MeasurableSpace β'] variable [MeasurableSpace γ] variable {μ μ' : Measure α} {ν ν' : Measure β} {τ : Measure γ} variable [NormedAddCommGroup E] /-! ### Measurability Before we define the product measure, we can talk about the measurability of operations on binary functions. We show that if `f` is a binary measurable function, then the function that integrates along one of the variables (using either the Lebesgue or Bochner integral) is measurable. -/ /-- The product of generated σ-algebras is the one generated by rectangles, if both generating sets are countably spanning. -/ theorem generateFrom_prod_eq {α β} {C : Set (Set α)} {D : Set (Set β)} (hC : IsCountablySpanning C) (hD : IsCountablySpanning D) : @Prod.instMeasurableSpace _ _ (generateFrom C) (generateFrom D) = generateFrom (image2 (· ×ˢ ·) C D) := by apply le_antisymm · refine sup_le ?_ ?_ <;> rw [comap_generateFrom] <;> apply generateFrom_le <;> rintro _ ⟨s, hs, rfl⟩ · rcases hD with ⟨t, h1t, h2t⟩ rw [← prod_univ, ← h2t, prod_iUnion] apply MeasurableSet.iUnion intro n apply measurableSet_generateFrom exact ⟨s, hs, t n, h1t n, rfl⟩ · rcases hC with ⟨t, h1t, h2t⟩ rw [← univ_prod, ← h2t, iUnion_prod_const] apply MeasurableSet.iUnion rintro n apply measurableSet_generateFrom exact mem_image2_of_mem (h1t n) hs · apply generateFrom_le rintro _ ⟨s, hs, t, ht, rfl⟩ dsimp only rw [prod_eq] apply (measurable_fst _).inter (measurable_snd _) · exact measurableSet_generateFrom hs · exact measurableSet_generateFrom ht /-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D` generate the σ-algebra on `α × β`. -/ theorem generateFrom_eq_prod {C : Set (Set α)} {D : Set (Set β)} (hC : generateFrom C = ‹_›) (hD : generateFrom D = ‹_›) (h2C : IsCountablySpanning C) (h2D : IsCountablySpanning D) : generateFrom (image2 (· ×ˢ ·) C D) = Prod.instMeasurableSpace := by rw [← hC, ← hD, generateFrom_prod_eq h2C h2D] /-- The product σ-algebra is generated from boxes, i.e. `s ×ˢ t` for sets `s : Set α` and `t : Set β`. -/ theorem generateFrom_prod : generateFrom (image2 (· ×ˢ ·) { s : Set α | MeasurableSet s } { t : Set β | MeasurableSet t }) = Prod.instMeasurableSpace := generateFrom_eq_prod generateFrom_measurableSet generateFrom_measurableSet isCountablySpanning_measurableSet isCountablySpanning_measurableSet /-- Rectangles form a π-system. -/ theorem isPiSystem_prod : IsPiSystem (image2 (· ×ˢ ·) { s : Set α | MeasurableSet s } { t : Set β | MeasurableSet t }) := isPiSystem_measurableSet.prod isPiSystem_measurableSet /-- If `ν` is a finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. `measurable_measure_prod_mk_left` is strictly more general. -/ theorem measurable_measure_prod_mk_left_finite [IsFiniteMeasure ν] {s : Set (α × β)} (hs : MeasurableSet s) : Measurable fun x => ν (Prod.mk x ⁻¹' s) := by classical refine induction_on_inter (C := fun s => Measurable fun x => ν (Prod.mk x ⁻¹' s)) generateFrom_prod.symm isPiSystem_prod ?_ ?_ ?_ ?_ hs · simp · rintro _ ⟨s, hs, t, _, rfl⟩ simp only [mk_preimage_prod_right_eq_if, measure_if] exact measurable_const.indicator hs · intro t ht h2t simp_rw [preimage_compl, measure_compl (measurable_prod_mk_left ht) (measure_ne_top ν _)] exact h2t.const_sub _ · intro f h1f h2f h3f simp_rw [preimage_iUnion] have : ∀ b, ν (⋃ i, Prod.mk b ⁻¹' f i) = ∑' i, ν (Prod.mk b ⁻¹' f i) := fun b => measure_iUnion (fun i j hij => Disjoint.preimage _ (h1f hij)) fun i => measurable_prod_mk_left (h2f i) simp_rw [this] apply Measurable.ennreal_tsum h3f /-- If `ν` is an s-finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. -/ theorem measurable_measure_prod_mk_left [SFinite ν] {s : Set (α × β)} (hs : MeasurableSet s) : Measurable fun x => ν (Prod.mk x ⁻¹' s) := by rw [← sum_sFiniteSeq ν] simp_rw [Measure.sum_apply_of_countable] exact Measurable.ennreal_tsum (fun i ↦ measurable_measure_prod_mk_left_finite hs) /-- If `μ` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `y ↦ μ { x | (x, y) ∈ s }` is a measurable function. -/ theorem measurable_measure_prod_mk_right {μ : Measure α} [SFinite μ] {s : Set (α × β)} (hs : MeasurableSet s) : Measurable fun y => μ ((fun x => (x, y)) ⁻¹' s) := measurable_measure_prod_mk_left (measurableSet_swap_iff.mpr hs) theorem Measurable.map_prod_mk_left [SFinite ν] : Measurable fun x : α => map (Prod.mk x) ν := by apply measurable_of_measurable_coe; intro s hs simp_rw [map_apply measurable_prod_mk_left hs] exact measurable_measure_prod_mk_left hs theorem Measurable.map_prod_mk_right {μ : Measure α} [SFinite μ] : Measurable fun y : β => map (fun x : α => (x, y)) μ := by apply measurable_of_measurable_coe; intro s hs simp_rw [map_apply measurable_prod_mk_right hs] exact measurable_measure_prod_mk_right hs theorem MeasurableEmbedding.prod_mk {α β γ δ : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} {mγ : MeasurableSpace γ} {mδ : MeasurableSpace δ} {f : α → β} {g : γ → δ} (hg : MeasurableEmbedding g) (hf : MeasurableEmbedding f) : MeasurableEmbedding fun x : γ × α => (g x.1, f x.2) := by have h_inj : Function.Injective fun x : γ × α => (g x.fst, f x.snd) := by intro x y hxy rw [← @Prod.mk.eta _ _ x, ← @Prod.mk.eta _ _ y] simp only [Prod.mk.inj_iff] at hxy ⊢ exact ⟨hg.injective hxy.1, hf.injective hxy.2⟩ refine ⟨h_inj, ?_, ?_⟩ · exact (hg.measurable.comp measurable_fst).prod_mk (hf.measurable.comp measurable_snd) · -- Induction using the π-system of rectangles refine fun s hs => @MeasurableSpace.induction_on_inter _ (fun s => MeasurableSet ((fun x : γ × α => (g x.fst, f x.snd)) '' s)) _ _ generateFrom_prod.symm isPiSystem_prod ?_ ?_ ?_ ?_ _ hs · simp only [Set.image_empty, MeasurableSet.empty] · rintro t ⟨t₁, ht₁, t₂, ht₂, rfl⟩ rw [← Set.prod_image_image_eq] exact (hg.measurableSet_image.mpr ht₁).prod (hf.measurableSet_image.mpr ht₂) · intro t _ ht_m rw [← Set.range_diff_image h_inj, ← Set.prod_range_range_eq] exact MeasurableSet.diff (MeasurableSet.prod hg.measurableSet_range hf.measurableSet_range) ht_m · intro g _ _ hg simp_rw [Set.image_iUnion] exact MeasurableSet.iUnion hg lemma MeasurableEmbedding.prod_mk_left {β γ : Type*} [MeasurableSingletonClass α] {mβ : MeasurableSpace β} {mγ : MeasurableSpace γ} (x : α) {f : γ → β} (hf : MeasurableEmbedding f) : MeasurableEmbedding (fun y ↦ (x, f y)) where injective := by intro y y' simp only [Prod.mk.injEq, true_and] exact fun h ↦ hf.injective h measurable := Measurable.prod_mk measurable_const hf.measurable measurableSet_image' := by intro s hs convert (MeasurableSet.singleton x).prod (hf.measurableSet_image.mpr hs) ext x simp lemma measurableEmbedding_prod_mk_left [MeasurableSingletonClass α] (x : α) : MeasurableEmbedding (Prod.mk x : β → α × β) := MeasurableEmbedding.prod_mk_left x MeasurableEmbedding.id lemma MeasurableEmbedding.prod_mk_right {β γ : Type*} [MeasurableSingletonClass α] {mβ : MeasurableSpace β} {mγ : MeasurableSpace γ} {f : γ → β} (hf : MeasurableEmbedding f) (x : α) : MeasurableEmbedding (fun y ↦ (f y, x)) where injective := by intro y y' simp only [Prod.mk.injEq, and_true] exact fun h ↦ hf.injective h measurable := Measurable.prod_mk hf.measurable measurable_const measurableSet_image' := by intro s hs convert (hf.measurableSet_image.mpr hs).prod (MeasurableSet.singleton x) ext x simp lemma measurableEmbedding_prod_mk_right [MeasurableSingletonClass α] (x : α) : MeasurableEmbedding (fun y ↦ (y, x) : β → β × α) := MeasurableEmbedding.prod_mk_right MeasurableEmbedding.id x /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. -/ theorem Measurable.lintegral_prod_right' [SFinite ν] : ∀ {f : α × β → ℝ≥0∞}, Measurable f → Measurable fun x => ∫⁻ y, f (x, y) ∂ν := by have m := @measurable_prod_mk_left refine Measurable.ennreal_induction (P := fun f => Measurable fun (x : α) => ∫⁻ y, f (x, y) ∂ν) ?_ ?_ ?_ · intro c s hs simp only [← indicator_comp_right] suffices Measurable fun x => c * ν (Prod.mk x ⁻¹' s) by simpa [lintegral_indicator _ (m hs)] exact (measurable_measure_prod_mk_left hs).const_mul _ · rintro f g - hf - h2f h2g simp only [Pi.add_apply] conv => enter [1, x]; erw [lintegral_add_left (hf.comp m)] exact h2f.add h2g · intro f hf h2f h3f have := measurable_iSup h3f have : ∀ x, Monotone fun n y => f n (x, y) := fun x i j hij y => h2f hij (x, y) conv => enter [1, x]; erw [lintegral_iSup (fun n => (hf n).comp m) (this x)] assumption /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ theorem Measurable.lintegral_prod_right [SFinite ν] {f : α → β → ℝ≥0∞} (hf : Measurable (uncurry f)) : Measurable fun x => ∫⁻ y, f x y ∂ν := hf.lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. -/ theorem Measurable.lintegral_prod_left' [SFinite μ] {f : α × β → ℝ≥0∞} (hf : Measurable f) : Measurable fun y => ∫⁻ x, f (x, y) ∂μ := (measurable_swap_iff.mpr hf).lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ theorem Measurable.lintegral_prod_left [SFinite μ] {f : α → β → ℝ≥0∞} (hf : Measurable (uncurry f)) : Measurable fun y => ∫⁻ x, f x y ∂μ := hf.lintegral_prod_left' /-! ### The product measure -/ namespace MeasureTheory namespace Measure /-- The binary product of measures. They are defined for arbitrary measures, but we basically prove all properties under the assumption that at least one of them is s-finite. -/ protected irreducible_def prod (μ : Measure α) (ν : Measure β) : Measure (α × β) := bind μ fun x : α => map (Prod.mk x) ν instance prod.measureSpace {α β} [MeasureSpace α] [MeasureSpace β] : MeasureSpace (α × β) where volume := volume.prod volume theorem volume_eq_prod (α β) [MeasureSpace α] [MeasureSpace β] : (volume : Measure (α × β)) = (volume : Measure α).prod (volume : Measure β) := rfl variable [SFinite ν] theorem prod_apply {s : Set (α × β)} (hs : MeasurableSet s) : μ.prod ν s = ∫⁻ x, ν (Prod.mk x ⁻¹' s) ∂μ := by simp_rw [Measure.prod, bind_apply hs (Measurable.map_prod_mk_left (ν := ν)), map_apply measurable_prod_mk_left hs] /-- The product measure of the product of two sets is the product of their measures. Note that we do not need the sets to be measurable. -/ @[simp] theorem prod_prod (s : Set α) (t : Set β) : μ.prod ν (s ×ˢ t) = μ s * ν t := by classical apply le_antisymm · set S := toMeasurable μ s set T := toMeasurable ν t have hSTm : MeasurableSet (S ×ˢ T) := (measurableSet_toMeasurable _ _).prod (measurableSet_toMeasurable _ _) calc μ.prod ν (s ×ˢ t) ≤ μ.prod ν (S ×ˢ T) := by gcongr <;> apply subset_toMeasurable _ = μ S * ν T := by rw [prod_apply hSTm] simp_rw [mk_preimage_prod_right_eq_if, measure_if, lintegral_indicator _ (measurableSet_toMeasurable _ _), lintegral_const, restrict_apply_univ, mul_comm] _ = μ s * ν t := by rw [measure_toMeasurable, measure_toMeasurable] · -- Formalization is based on https://mathoverflow.net/a/254134/136589 set ST := toMeasurable (μ.prod ν) (s ×ˢ t) have hSTm : MeasurableSet ST := measurableSet_toMeasurable _ _ have hST : s ×ˢ t ⊆ ST := subset_toMeasurable _ _ set f : α → ℝ≥0∞ := fun x => ν (Prod.mk x ⁻¹' ST) have hfm : Measurable f := measurable_measure_prod_mk_left hSTm set s' : Set α := { x | ν t ≤ f x } have hss' : s ⊆ s' := fun x hx => measure_mono fun y hy => hST <| mk_mem_prod hx hy calc μ s * ν t ≤ μ s' * ν t := by gcongr _ = ∫⁻ _ in s', ν t ∂μ := by rw [setLIntegral_const, mul_comm] _ ≤ ∫⁻ x in s', f x ∂μ := setLIntegral_mono hfm fun x => id _ ≤ ∫⁻ x, f x ∂μ := lintegral_mono' restrict_le_self le_rfl _ = μ.prod ν ST := (prod_apply hSTm).symm _ = μ.prod ν (s ×ˢ t) := measure_toMeasurable _ @[simp] lemma map_fst_prod : Measure.map Prod.fst (μ.prod ν) = (ν univ) • μ := by ext s hs simp [Measure.map_apply measurable_fst hs, ← prod_univ, mul_comm] @[simp] lemma map_snd_prod : Measure.map Prod.snd (μ.prod ν) = (μ univ) • ν := by ext s hs simp [Measure.map_apply measurable_snd hs, ← univ_prod] instance prod.instIsOpenPosMeasure {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] {m : MeasurableSpace X} {μ : Measure X} [IsOpenPosMeasure μ] {m' : MeasurableSpace Y} {ν : Measure Y} [IsOpenPosMeasure ν] [SFinite ν] : IsOpenPosMeasure (μ.prod ν) := by constructor rintro U U_open ⟨⟨x, y⟩, hxy⟩ rcases isOpen_prod_iff.1 U_open x y hxy with ⟨u, v, u_open, v_open, xu, yv, huv⟩ refine ne_of_gt (lt_of_lt_of_le ?_ (measure_mono huv)) simp only [prod_prod, CanonicallyOrderedCommSemiring.mul_pos] constructor · exact u_open.measure_pos μ ⟨x, xu⟩ · exact v_open.measure_pos ν ⟨y, yv⟩ instance {X Y : Type*} [TopologicalSpace X] [MeasureSpace X] [IsOpenPosMeasure (volume : Measure X)] [TopologicalSpace Y] [MeasureSpace Y] [IsOpenPosMeasure (volume : Measure Y)] [SFinite (volume : Measure Y)] : IsOpenPosMeasure (volume : Measure (X × Y)) := prod.instIsOpenPosMeasure instance prod.instIsFiniteMeasure {α β : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} (μ : Measure α) (ν : Measure β) [IsFiniteMeasure μ] [IsFiniteMeasure ν] : IsFiniteMeasure (μ.prod ν) := by constructor rw [← univ_prod_univ, prod_prod] exact mul_lt_top (measure_lt_top _ _).ne (measure_lt_top _ _).ne instance {α β : Type*} [MeasureSpace α] [MeasureSpace β] [IsFiniteMeasure (volume : Measure α)] [IsFiniteMeasure (volume : Measure β)] : IsFiniteMeasure (volume : Measure (α × β)) := prod.instIsFiniteMeasure _ _ instance prod.instIsProbabilityMeasure {α β : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} (μ : Measure α) (ν : Measure β) [IsProbabilityMeasure μ] [IsProbabilityMeasure ν] : IsProbabilityMeasure (μ.prod ν) := ⟨by rw [← univ_prod_univ, prod_prod, measure_univ, measure_univ, mul_one]⟩ instance {α β : Type*} [MeasureSpace α] [MeasureSpace β] [IsProbabilityMeasure (volume : Measure α)] [IsProbabilityMeasure (volume : Measure β)] : IsProbabilityMeasure (volume : Measure (α × β)) := prod.instIsProbabilityMeasure _ _ instance prod.instIsFiniteMeasureOnCompacts {α β : Type*} [TopologicalSpace α] [TopologicalSpace β] {mα : MeasurableSpace α} {mβ : MeasurableSpace β} (μ : Measure α) (ν : Measure β) [IsFiniteMeasureOnCompacts μ] [IsFiniteMeasureOnCompacts ν] [SFinite ν] : IsFiniteMeasureOnCompacts (μ.prod ν) := by refine ⟨fun K hK => ?_⟩ set L := (Prod.fst '' K) ×ˢ (Prod.snd '' K) with hL have : K ⊆ L := by rintro ⟨x, y⟩ hxy simp only [L, prod_mk_mem_set_prod_eq, mem_image, Prod.exists, exists_and_right, exists_eq_right] exact ⟨⟨y, hxy⟩, ⟨x, hxy⟩⟩ apply lt_of_le_of_lt (measure_mono this) rw [hL, prod_prod] exact mul_lt_top (hK.image continuous_fst).measure_ne_top (hK.image continuous_snd).measure_ne_top instance {X Y : Type*} [TopologicalSpace X] [MeasureSpace X] [IsFiniteMeasureOnCompacts (volume : Measure X)] [TopologicalSpace Y] [MeasureSpace Y] [IsFiniteMeasureOnCompacts (volume : Measure Y)] [SFinite (volume : Measure Y)] : IsFiniteMeasureOnCompacts (volume : Measure (X × Y)) := prod.instIsFiniteMeasureOnCompacts _ _ instance prod.instNoAtoms_fst [NoAtoms μ] : NoAtoms (Measure.prod μ ν) := by refine NoAtoms.mk (fun x => ?_) rw [← Set.singleton_prod_singleton, Measure.prod_prod, measure_singleton, zero_mul] instance prod.instNoAtoms_snd [NoAtoms ν] : NoAtoms (Measure.prod μ ν) := by refine NoAtoms.mk (fun x => ?_) rw [← Set.singleton_prod_singleton, Measure.prod_prod, measure_singleton (μ := ν), mul_zero] theorem ae_measure_lt_top {s : Set (α × β)} (hs : MeasurableSet s) (h2s : (μ.prod ν) s ≠ ∞) : ∀ᵐ x ∂μ, ν (Prod.mk x ⁻¹' s) < ∞ := by rw [prod_apply hs] at h2s exact ae_lt_top (measurable_measure_prod_mk_left hs) h2s /-- Note: the assumption `hs` cannot be dropped. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ theorem measure_prod_null {s : Set (α × β)} (hs : MeasurableSet s) : μ.prod ν s = 0 ↔ (fun x => ν (Prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prod_mk_left hs)] /-- Note: the converse is not true without assuming that `s` is measurable. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ theorem measure_ae_null_of_prod_null {s : Set (α × β)} (h : μ.prod ν s = 0) : (fun x => ν (Prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h rw [measure_prod_null mt] at ht rw [eventuallyLE_antisymm_iff] exact ⟨EventuallyLE.trans_eq (eventually_of_forall fun x => (measure_mono (preimage_mono hst) : _)) ht, eventually_of_forall fun x => zero_le _⟩ theorem AbsolutelyContinuous.prod [SFinite ν'] (h1 : μ ≪ μ') (h2 : ν ≪ ν') : μ.prod ν ≪ μ'.prod ν' := by refine AbsolutelyContinuous.mk fun s hs h2s => ?_ rw [measure_prod_null hs] at h2s ⊢ exact (h2s.filter_mono h1.ae_le).mono fun _ h => h2 h /-- Note: the converse is not true. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. It is true if the set is measurable, see `ae_prod_mem_iff_ae_ae_mem`. -/ theorem ae_ae_of_ae_prod {p : α × β → Prop} (h : ∀ᵐ z ∂μ.prod ν, p z) : ∀ᵐ x ∂μ, ∀ᵐ y ∂ν, p (x, y) := measure_ae_null_of_prod_null h theorem ae_ae_eq_curry_of_prod {γ : Type*} {f g : α × β → γ} (h : f =ᵐ[μ.prod ν] g) : ∀ᵐ x ∂μ, curry f x =ᵐ[ν] curry g x := ae_ae_of_ae_prod h theorem ae_ae_eq_of_ae_eq_uncurry {γ : Type*} {f g : α → β → γ} (h : uncurry f =ᵐ[μ.prod ν] uncurry g) : ∀ᵐ x ∂μ, f x =ᵐ[ν] g x := ae_ae_eq_curry_of_prod h theorem ae_prod_mem_iff_ae_ae_mem {s : Set (α × β)} (hs : MeasurableSet s) : (∀ᵐ z ∂μ.prod ν, z ∈ s) ↔ ∀ᵐ x ∂μ, ∀ᵐ y ∂ν, (x, y) ∈ s := measure_prod_null hs.compl theorem quasiMeasurePreserving_fst : QuasiMeasurePreserving Prod.fst (μ.prod ν) μ := by refine ⟨measurable_fst, AbsolutelyContinuous.mk fun s hs h2s => ?_⟩ rw [map_apply measurable_fst hs, ← prod_univ, prod_prod, h2s, zero_mul] theorem quasiMeasurePreserving_snd : QuasiMeasurePreserving Prod.snd (μ.prod ν) ν := by refine ⟨measurable_snd, AbsolutelyContinuous.mk fun s hs h2s => ?_⟩ rw [map_apply measurable_snd hs, ← univ_prod, prod_prod, h2s, mul_zero] lemma set_prod_ae_eq {s s' : Set α} {t t' : Set β} (hs : s =ᵐ[μ] s') (ht : t =ᵐ[ν] t') : (s ×ˢ t : Set (α × β)) =ᵐ[μ.prod ν] (s' ×ˢ t' : Set (α × β)) := (quasiMeasurePreserving_fst.preimage_ae_eq hs).inter (quasiMeasurePreserving_snd.preimage_ae_eq ht) lemma measure_prod_compl_eq_zero {s : Set α} {t : Set β} (s_ae_univ : μ sᶜ = 0) (t_ae_univ : ν tᶜ = 0) : μ.prod ν (s ×ˢ t)ᶜ = 0 := by rw [Set.compl_prod_eq_union, measure_union_null_iff] simp [s_ae_univ, t_ae_univ] lemma _root_.MeasureTheory.NullMeasurableSet.prod {s : Set α} {t : Set β} (s_mble : NullMeasurableSet s μ) (t_mble : NullMeasurableSet t ν) : NullMeasurableSet (s ×ˢ t) (μ.prod ν) := let ⟨s₀, mble_s₀, s_aeeq_s₀⟩ := s_mble let ⟨t₀, mble_t₀, t_aeeq_t₀⟩ := t_mble ⟨s₀ ×ˢ t₀, ⟨mble_s₀.prod mble_t₀, set_prod_ae_eq s_aeeq_s₀ t_aeeq_t₀⟩⟩ /-- If `s ×ˢ t` is a null measurable set and `μ s ≠ 0`, then `t` is a null measurable set. -/ lemma _root_.MeasureTheory.NullMeasurableSet.right_of_prod {s : Set α} {t : Set β} (h : NullMeasurableSet (s ×ˢ t) (μ.prod ν)) (hs : μ s ≠ 0) : NullMeasurableSet t ν := by rcases h with ⟨u, hum, hu⟩ obtain ⟨x, hxs, hx⟩ : ∃ x ∈ s, (Prod.mk x ⁻¹' (s ×ˢ t)) =ᵐ[ν] (Prod.mk x ⁻¹' u) := ((frequently_ae_iff.2 hs).and_eventually (ae_ae_eq_curry_of_prod hu)).exists refine ⟨Prod.mk x ⁻¹' u, measurable_prod_mk_left hum, ?_⟩ rwa [mk_preimage_prod_right hxs] at hx /-- If `Prod.snd ⁻¹' t` is a null measurable set and `μ ≠ 0`, then `t` is a null measurable set. -/ lemma _root_.MeasureTheory.NullMeasurableSet.of_preimage_snd [NeZero μ] {t : Set β} (h : NullMeasurableSet (Prod.snd ⁻¹' t) (μ.prod ν)) : NullMeasurableSet t ν := .right_of_prod (by rwa [univ_prod]) (NeZero.ne _) /-- `Prod.snd ⁻¹' t` is null measurable w.r.t. `μ.prod ν` iff `t` is null measurable w.r.t. `ν` provided that `μ ≠ 0`. -/ lemma nullMeasurableSet_preimage_snd [NeZero μ] {t : Set β} : NullMeasurableSet (Prod.snd ⁻¹' t) (μ.prod ν) ↔ NullMeasurableSet t ν := ⟨.of_preimage_snd, (.preimage · quasiMeasurePreserving_snd)⟩ lemma nullMeasurable_comp_snd [NeZero μ] {f : β → γ} : NullMeasurable (f ∘ Prod.snd) (μ.prod ν) ↔ NullMeasurable f ν := forall₂_congr fun s _ ↦ nullMeasurableSet_preimage_snd (t := f ⁻¹' s) /-- `μ.prod ν` has finite spanning sets in rectangles of finite spanning sets. -/ noncomputable def FiniteSpanningSetsIn.prod {ν : Measure β} {C : Set (Set α)} {D : Set (Set β)} (hμ : μ.FiniteSpanningSetsIn C) (hν : ν.FiniteSpanningSetsIn D) : (μ.prod ν).FiniteSpanningSetsIn (image2 (· ×ˢ ·) C D) := by haveI := hν.sigmaFinite refine ⟨fun n => hμ.set n.unpair.1 ×ˢ hν.set n.unpair.2, fun n => mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), fun n => ?_, ?_⟩ · rw [prod_prod] exact mul_lt_top (hμ.finite _).ne (hν.finite _).ne · simp_rw [iUnion_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ] lemma prod_sum_left {ι : Type*} (m : ι → Measure α) (μ : Measure β) [SFinite μ] : (Measure.sum m).prod μ = Measure.sum (fun i ↦ (m i).prod μ) := by ext s hs simp only [prod_apply hs, lintegral_sum_measure, hs, sum_apply, ENNReal.tsum_prod'] lemma prod_sum_right {ι' : Type*} [Countable ι'] (m : Measure α) (m' : ι' → Measure β) [∀ n, SFinite (m' n)] : m.prod (Measure.sum m') = Measure.sum (fun p ↦ m.prod (m' p)) := by ext s hs simp only [prod_apply hs, lintegral_sum_measure, hs, sum_apply, ENNReal.tsum_prod'] have M : ∀ x, MeasurableSet (Prod.mk x ⁻¹' s) := fun x => measurable_prod_mk_left hs simp_rw [Measure.sum_apply _ (M _)] rw [lintegral_tsum (fun i ↦ (measurable_measure_prod_mk_left hs).aemeasurable)] lemma prod_sum {ι ι' : Type*} [Countable ι'] (m : ι → Measure α) (m' : ι' → Measure β) [∀ n, SFinite (m' n)] : (Measure.sum m).prod (Measure.sum m') = Measure.sum (fun (p : ι × ι') ↦ (m p.1).prod (m' p.2)) := by simp_rw [prod_sum_left, prod_sum_right, sum_sum] instance prod.instSigmaFinite {α β : Type*} {_ : MeasurableSpace α} {μ : Measure α} [SigmaFinite μ] {_ : MeasurableSpace β} {ν : Measure β} [SigmaFinite ν] : SigmaFinite (μ.prod ν) := (μ.toFiniteSpanningSetsIn.prod ν.toFiniteSpanningSetsIn).sigmaFinite instance prod.instSFinite {α β : Type*} {_ : MeasurableSpace α} {μ : Measure α} [SFinite μ] {_ : MeasurableSpace β} {ν : Measure β} [SFinite ν] : SFinite (μ.prod ν) := by have : μ.prod ν = Measure.sum (fun (p : ℕ × ℕ) ↦ (sFiniteSeq μ p.1).prod (sFiniteSeq ν p.2)) := by conv_lhs => rw [← sum_sFiniteSeq μ, ← sum_sFiniteSeq ν] apply prod_sum rw [this] infer_instance instance {α β} [MeasureSpace α] [SigmaFinite (volume : Measure α)] [MeasureSpace β] [SigmaFinite (volume : Measure β)] : SigmaFinite (volume : Measure (α × β)) := prod.instSigmaFinite instance {α β} [MeasureSpace α] [SFinite (volume : Measure α)] [MeasureSpace β] [SFinite (volume : Measure β)] : SFinite (volume : Measure (α × β)) := prod.instSFinite /-- A measure on a product space equals the product measure if they are equal on rectangles with as sides sets that generate the corresponding σ-algebras. -/ theorem prod_eq_generateFrom {μ : Measure α} {ν : Measure β} {C : Set (Set α)} {D : Set (Set β)} (hC : generateFrom C = ‹_›) (hD : generateFrom D = ‹_›) (h2C : IsPiSystem C) (h2D : IsPiSystem D) (h3C : μ.FiniteSpanningSetsIn C) (h3D : ν.FiniteSpanningSetsIn D) {μν : Measure (α × β)} (h₁ : ∀ s ∈ C, ∀ t ∈ D, μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := by refine (h3C.prod h3D).ext (generateFrom_eq_prod hC hD h3C.isCountablySpanning h3D.isCountablySpanning).symm (h2C.prod h2D) ?_ rintro _ ⟨s, hs, t, ht, rfl⟩ haveI := h3D.sigmaFinite rw [h₁ s hs t ht, prod_prod] /- Note that the next theorem is not true for s-finite measures: let `μ = ν = ∞ • Leb` on `[0,1]` (they are s-finite as countable sums of the finite Lebesgue measure), and let `μν = μ.prod ν + λ` where `λ` is Lebesgue measure on the diagonal. Then both measures give infinite mass to rectangles `s × t` whose sides have positive Lebesgue measure, and `0` measure when one of the sides has zero Lebesgue measure. And yet they do not coincide, as the first one gives zero mass to the diagonal, and the second one gives mass one. -/ /-- A measure on a product space equals the product measure of sigma-finite measures if they are equal on rectangles. -/ theorem prod_eq {μ : Measure α} [SigmaFinite μ] {ν : Measure β} [SigmaFinite ν] {μν : Measure (α × β)} (h : ∀ s t, MeasurableSet s → MeasurableSet t → μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := prod_eq_generateFrom generateFrom_measurableSet generateFrom_measurableSet isPiSystem_measurableSet isPiSystem_measurableSet μ.toFiniteSpanningSetsIn ν.toFiniteSpanningSetsIn fun s hs t ht => h s t hs ht variable [SFinite μ] theorem prod_swap : map Prod.swap (μ.prod ν) = ν.prod μ := by have : sum (fun (i : ℕ × ℕ) ↦ map Prod.swap ((sFiniteSeq μ i.1).prod (sFiniteSeq ν i.2))) = sum (fun (i : ℕ × ℕ) ↦ map Prod.swap ((sFiniteSeq μ i.2).prod (sFiniteSeq ν i.1))) := by ext s hs rw [sum_apply _ hs, sum_apply _ hs] exact ((Equiv.prodComm ℕ ℕ).tsum_eq _).symm rw [← sum_sFiniteSeq μ, ← sum_sFiniteSeq ν, prod_sum, prod_sum, map_sum measurable_swap.aemeasurable, this] congr 1 ext1 i refine (prod_eq ?_).symm intro s t hs ht simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod, mul_comm] theorem measurePreserving_swap : MeasurePreserving Prod.swap (μ.prod ν) (ν.prod μ) := ⟨measurable_swap, prod_swap⟩ theorem prod_apply_symm {s : Set (α × β)} (hs : MeasurableSet s) : μ.prod ν s = ∫⁻ y, μ ((fun x => (x, y)) ⁻¹' s) ∂ν := by rw [← prod_swap, map_apply measurable_swap hs, prod_apply (measurable_swap hs)] rfl /-- If `s ×ˢ t` is a null measurable set and `ν t ≠ 0`, then `s` is a null measurable set. -/ lemma _root_.MeasureTheory.NullMeasurableSet.left_of_prod {s : Set α} {t : Set β} (h : NullMeasurableSet (s ×ˢ t) (μ.prod ν)) (ht : ν t ≠ 0) : NullMeasurableSet s μ := by refine .right_of_prod ?_ ht rw [← preimage_swap_prod] exact h.preimage measurePreserving_swap.quasiMeasurePreserving /-- If `Prod.fst ⁻¹' s` is a null measurable set and `ν ≠ 0`, then `s` is a null measurable set. -/ lemma _root_.MeasureTheory.NullMeasurableSet.of_preimage_fst [NeZero ν] {s : Set α} (h : NullMeasurableSet (Prod.fst ⁻¹' s) (μ.prod ν)) : NullMeasurableSet s μ := .left_of_prod (by rwa [prod_univ]) (NeZero.ne _) /-- `Prod.fst ⁻¹' s` is null measurable w.r.t. `μ.prod ν` iff `s` is null measurable w.r.t. `μ` provided that `ν ≠ 0`. -/ lemma nullMeasurableSet_preimage_fst [NeZero ν] {s : Set α} : NullMeasurableSet (Prod.fst ⁻¹' s) (μ.prod ν) ↔ NullMeasurableSet s μ := ⟨.of_preimage_fst, (.preimage · quasiMeasurePreserving_fst)⟩ lemma nullMeasurable_comp_fst [NeZero ν] {f : α → γ} : NullMeasurable (f ∘ Prod.fst) (μ.prod ν) ↔ NullMeasurable f μ := forall₂_congr fun s _ ↦ nullMeasurableSet_preimage_fst (s := f ⁻¹' s) /-- The product of two non-null sets is null measurable if and only if both of them are null measurable. -/ lemma nullMeasurableSet_prod_of_ne_zero {s : Set α} {t : Set β} (hs : μ s ≠ 0) (ht : ν t ≠ 0) : NullMeasurableSet (s ×ˢ t) (μ.prod ν) ↔ NullMeasurableSet s μ ∧ NullMeasurableSet t ν := ⟨fun h ↦ ⟨h.left_of_prod ht, h.right_of_prod hs⟩, fun ⟨hs, ht⟩ ↦ hs.prod ht⟩ /-- The product of two sets is null measurable if and only if both of them are null measurable or one of them has measure zero. -/ lemma nullMeasurableSet_prod {s : Set α} {t : Set β} : NullMeasurableSet (s ×ˢ t) (μ.prod ν) ↔ NullMeasurableSet s μ ∧ NullMeasurableSet t ν ∨ μ s = 0 ∨ ν t = 0 := by rcases eq_or_ne (μ s) 0 with hs | hs; · simp [NullMeasurableSet.of_null, *] rcases eq_or_ne (ν t) 0 with ht | ht; · simp [NullMeasurableSet.of_null, *] simp [*, nullMeasurableSet_prod_of_ne_zero] theorem prodAssoc_prod [SFinite τ] : map MeasurableEquiv.prodAssoc ((μ.prod ν).prod τ) = μ.prod (ν.prod τ) := by have : sum (fun (p : ℕ × ℕ × ℕ) ↦ (sFiniteSeq μ p.1).prod ((sFiniteSeq ν p.2.1).prod (sFiniteSeq τ p.2.2))) = sum (fun (p : (ℕ × ℕ) × ℕ) ↦ (sFiniteSeq μ p.1.1).prod ((sFiniteSeq ν p.1.2).prod (sFiniteSeq τ p.2))) := by ext s hs rw [sum_apply _ hs, sum_apply _ hs, ← (Equiv.prodAssoc _ _ _).tsum_eq] simp only [Equiv.prodAssoc_apply] rw [← sum_sFiniteSeq μ, ← sum_sFiniteSeq ν, ← sum_sFiniteSeq τ, prod_sum, prod_sum, map_sum MeasurableEquiv.prodAssoc.measurable.aemeasurable, prod_sum, prod_sum, this] congr ext1 i refine (prod_eq_generateFrom generateFrom_measurableSet generateFrom_prod isPiSystem_measurableSet isPiSystem_prod ((sFiniteSeq μ i.1.1)).toFiniteSpanningSetsIn ((sFiniteSeq ν i.1.2).toFiniteSpanningSetsIn.prod (sFiniteSeq τ i.2).toFiniteSpanningSetsIn) ?_).symm rintro s hs _ ⟨t, ht, u, hu, rfl⟩; rw [mem_setOf_eq] at hs ht hu simp_rw [map_apply (MeasurableEquiv.measurable _) (hs.prod (ht.prod hu)), MeasurableEquiv.prodAssoc, MeasurableEquiv.coe_mk, Equiv.prod_assoc_preimage, prod_prod, mul_assoc] /-! ### The product of specific measures -/ theorem prod_restrict (s : Set α) (t : Set β) : (μ.restrict s).prod (ν.restrict t) = (μ.prod ν).restrict (s ×ˢ t) := by rw [← sum_sFiniteSeq μ, ← sum_sFiniteSeq ν, restrict_sum_of_countable, restrict_sum_of_countable, prod_sum, prod_sum, restrict_sum_of_countable] congr 1 ext1 i refine prod_eq fun s' t' hs' ht' => ?_ rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod, restrict_apply hs', restrict_apply ht'] theorem restrict_prod_eq_prod_univ (s : Set α) : (μ.restrict s).prod ν = (μ.prod ν).restrict (s ×ˢ univ) := by have : ν = ν.restrict Set.univ := Measure.restrict_univ.symm rw [this, Measure.prod_restrict, ← this] theorem prod_dirac (y : β) : μ.prod (dirac y) = map (fun x => (x, y)) μ := by classical rw [← sum_sFiniteSeq μ, prod_sum_left, map_sum measurable_prod_mk_right.aemeasurable] congr ext1 i refine prod_eq fun s t hs ht => ?_ simp_rw [map_apply measurable_prod_mk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if, dirac_apply' _ ht, ← indicator_mul_right _ fun _ => sFiniteSeq μ i s, Pi.one_apply, mul_one] theorem dirac_prod (x : α) : (dirac x).prod ν = map (Prod.mk x) ν := by classical rw [← sum_sFiniteSeq ν, prod_sum_right, map_sum measurable_prod_mk_left.aemeasurable] congr ext1 i refine prod_eq fun s t hs ht => ?_ simp_rw [map_apply measurable_prod_mk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, dirac_apply' _ hs, ← indicator_mul_left _ _ fun _ => sFiniteSeq ν i t, Pi.one_apply, one_mul] theorem dirac_prod_dirac {x : α} {y : β} : (dirac x).prod (dirac y) = dirac (x, y) := by rw [prod_dirac, map_dirac measurable_prod_mk_right] theorem prod_add (ν' : Measure β) [SFinite ν'] : μ.prod (ν + ν') = μ.prod ν + μ.prod ν' := by simp_rw [← sum_sFiniteSeq ν, ← sum_sFiniteSeq ν', sum_add_sum, ← sum_sFiniteSeq μ, prod_sum, sum_add_sum] congr ext1 i refine prod_eq fun s t _ _ => ?_ simp_rw [add_apply, prod_prod, left_distrib] theorem add_prod (μ' : Measure α) [SFinite μ'] : (μ + μ').prod ν = μ.prod ν + μ'.prod ν := by simp_rw [← sum_sFiniteSeq μ, ← sum_sFiniteSeq μ', sum_add_sum, ← sum_sFiniteSeq ν, prod_sum, sum_add_sum] congr ext1 i refine prod_eq fun s t _ _ => ?_ simp_rw [add_apply, prod_prod, right_distrib] @[simp] theorem zero_prod (ν : Measure β) : (0 : Measure α).prod ν = 0 := by rw [Measure.prod] exact bind_zero_left _ @[simp] theorem prod_zero (μ : Measure α) : μ.prod (0 : Measure β) = 0 := by simp [Measure.prod] theorem map_prod_map {δ} [MeasurableSpace δ] {f : α → β} {g : γ → δ} (μa : Measure α) (μc : Measure γ) [SFinite μa] [SFinite μc] (hf : Measurable f) (hg : Measurable g) : (map f μa).prod (map g μc) = map (Prod.map f g) (μa.prod μc) := by simp_rw [← sum_sFiniteSeq μa, ← sum_sFiniteSeq μc, map_sum hf.aemeasurable, map_sum hg.aemeasurable, prod_sum, map_sum (hf.prod_map hg).aemeasurable] congr ext1 i refine prod_eq fun s t hs ht => ?_ rw [map_apply (hf.prod_map hg) (hs.prod ht), map_apply hf hs, map_apply hg ht] exact prod_prod (f ⁻¹' s) (g ⁻¹' t) end Measure open Measure namespace MeasurePreserving variable {δ : Type*} [MeasurableSpace δ] {μa : Measure α} {μb : Measure β} {μc : Measure γ} {μd : Measure δ} /-- Let `f : α → β` be a measure preserving map. For a.e. all `a`, let `g a : γ → δ` be a measure preserving map. Also suppose that `g` is measurable as a function of two arguments. Then the map `fun (a, c) ↦ (f a, g a c)` is a measure preserving map for the product measures on `α × γ` and `β × δ`. Some authors call a map of the form `fun (a, c) ↦ (f a, g a c)` a *skew product* over `f`, thus the choice of a name. -/ theorem skew_product [SFinite μa] [SFinite μc] {f : α → β} (hf : MeasurePreserving f μa μb) {g : α → γ → δ} (hgm : Measurable (uncurry g)) (hg : ∀ᵐ a ∂μa, map (g a) μc = μd) : MeasurePreserving (fun p : α × γ => (f p.1, g p.1 p.2)) (μa.prod μc) (μb.prod μd) := by have : Measurable fun p : α × γ => (f p.1, g p.1 p.2) := (hf.1.comp measurable_fst).prod_mk hgm use this /- if `μa = 0`, then the lemma is trivial, otherwise we can use `hg` to deduce `SFinite μd`. -/ rcases eq_zero_or_neZero μa with rfl | _ · simp [← hf.map_eq] have sf : SFinite μd := by obtain ⟨a, ha⟩ : ∃ a, map (g a) μc = μd := hg.exists rw [← ha] infer_instance -- Thus we can use the integral formula for the product measure, and compute things explicitly ext s hs rw [map_apply this hs, prod_apply (this hs), prod_apply hs, ← hf.lintegral_comp (measurable_measure_prod_mk_left hs)] apply lintegral_congr_ae filter_upwards [hg] with a ha rw [← ha, map_apply hgm.of_uncurry_left (measurable_prod_mk_left hs), preimage_preimage, preimage_preimage] /-- If `f : α → β` sends the measure `μa` to `μb` and `g : γ → δ` sends the measure `μc` to `μd`, then `Prod.map f g` sends `μa.prod μc` to `μb.prod μd`. -/ protected theorem prod [SFinite μa] [SFinite μc] {f : α → β} {g : γ → δ} (hf : MeasurePreserving f μa μb) (hg : MeasurePreserving g μc μd) : MeasurePreserving (Prod.map f g) (μa.prod μc) (μb.prod μd) := have : Measurable (uncurry fun _ : α => g) := hg.1.comp measurable_snd hf.skew_product this <| ae_of_all _ fun _ => hg.map_eq end MeasurePreserving namespace QuasiMeasurePreserving theorem prod_of_right {f : α × β → γ} {μ : Measure α} {ν : Measure β} {τ : Measure γ} (hf : Measurable f) [SFinite ν] (h2f : ∀ᵐ x ∂μ, QuasiMeasurePreserving (fun y => f (x, y)) ν τ) : QuasiMeasurePreserving f (μ.prod ν) τ := by refine ⟨hf, ?_⟩ refine AbsolutelyContinuous.mk fun s hs h2s => ?_ rw [map_apply hf hs, prod_apply (hf hs)]; simp_rw [preimage_preimage] rw [lintegral_congr_ae (h2f.mono fun x hx => hx.preimage_null h2s), lintegral_zero] theorem prod_of_left {α β γ} [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ] {f : α × β → γ} {μ : Measure α} {ν : Measure β} {τ : Measure γ} (hf : Measurable f) [SFinite μ] [SFinite ν] (h2f : ∀ᵐ y ∂ν, QuasiMeasurePreserving (fun x => f (x, y)) μ τ) : QuasiMeasurePreserving f (μ.prod ν) τ := by rw [← prod_swap] convert (QuasiMeasurePreserving.prod_of_right (hf.comp measurable_swap) h2f).comp ((measurable_swap.measurePreserving (ν.prod μ)).symm MeasurableEquiv.prodComm).quasiMeasurePreserving end QuasiMeasurePreserving end MeasureTheory open MeasureTheory.Measure section theorem AEMeasurable.prod_swap [SFinite μ] [SFinite ν] {f : β × α → γ} (hf : AEMeasurable f (ν.prod μ)) : AEMeasurable (fun z : α × β => f z.swap) (μ.prod ν) := by rw [← Measure.prod_swap] at hf exact hf.comp_measurable measurable_swap -- TODO: make this theorem usable with `fun_prop` theorem AEMeasurable.fst [SFinite ν] {f : α → γ} (hf : AEMeasurable f μ) : AEMeasurable (fun z : α × β => f z.1) (μ.prod ν) := hf.comp_quasiMeasurePreserving quasiMeasurePreserving_fst -- TODO: make this theorem usable with `fun_prop` theorem AEMeasurable.snd [SFinite ν] {f : β → γ} (hf : AEMeasurable f ν) : AEMeasurable (fun z : α × β => f z.2) (μ.prod ν) := hf.comp_quasiMeasurePreserving quasiMeasurePreserving_snd end namespace MeasureTheory /-! ### The Lebesgue integral on a product -/ variable [SFinite ν] theorem lintegral_prod_swap [SFinite μ] (f : α × β → ℝ≥0∞) : ∫⁻ z, f z.swap ∂ν.prod μ = ∫⁻ z, f z ∂μ.prod ν := measurePreserving_swap.lintegral_comp_emb MeasurableEquiv.prodComm.measurableEmbedding f /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ theorem lintegral_prod_of_measurable : ∀ (f : α × β → ℝ≥0∞), Measurable f → ∫⁻ z, f z ∂μ.prod ν = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := by have m := @measurable_prod_mk_left refine Measurable.ennreal_induction (P := fun f => ∫⁻ z, f z ∂μ.prod ν = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ) ?_ ?_ ?_ · intro c s hs conv_rhs => enter [2, x, 2, y] rw [← indicator_comp_right, const_def, const_comp, ← const_def] conv_rhs => enter [2, x] rw [lintegral_indicator _ (m (x := x) hs), lintegral_const, Measure.restrict_apply MeasurableSet.univ, univ_inter] simp [hs, lintegral_const_mul, measurable_measure_prod_mk_left (ν := ν) hs, prod_apply] · rintro f g - hf _ h2f h2g simp only [Pi.add_apply] conv_lhs => rw [lintegral_add_left hf] conv_rhs => enter [2, x]; erw [lintegral_add_left (hf.comp (m (x := x)))] simp [lintegral_add_left, Measurable.lintegral_prod_right', hf, h2f, h2g] · intro f hf h2f h3f have kf : ∀ x n, Measurable fun y => f n (x, y) := fun x n => (hf n).comp m have k2f : ∀ x, Monotone fun n y => f n (x, y) := fun x i j hij y => h2f hij (x, y) have lf : ∀ n, Measurable fun x => ∫⁻ y, f n (x, y) ∂ν := fun n => (hf n).lintegral_prod_right' have l2f : Monotone fun n x => ∫⁻ y, f n (x, y) ∂ν := fun i j hij x => lintegral_mono (k2f x hij) simp only [lintegral_iSup hf h2f, lintegral_iSup (kf _), k2f, lintegral_iSup lf l2f, h3f] /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ theorem lintegral_prod (f : α × β → ℝ≥0∞) (hf : AEMeasurable f (μ.prod ν)) : ∫⁻ z, f z ∂μ.prod ν = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := by have A : ∫⁻ z, f z ∂μ.prod ν = ∫⁻ z, hf.mk f z ∂μ.prod ν := lintegral_congr_ae hf.ae_eq_mk have B : (∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ) = ∫⁻ x, ∫⁻ y, hf.mk f (x, y) ∂ν ∂μ := by apply lintegral_congr_ae filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ ha using lintegral_congr_ae ha rw [A, B, lintegral_prod_of_measurable _ hf.measurable_mk] /-- The symmetric version of Tonelli's Theorem: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ theorem lintegral_prod_symm [SFinite μ] (f : α × β → ℝ≥0∞) (hf : AEMeasurable f (μ.prod ν)) : ∫⁻ z, f z ∂μ.prod ν = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := by simp_rw [← lintegral_prod_swap f] exact lintegral_prod _ hf.prod_swap /-- The symmetric version of Tonelli's Theorem: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ theorem lintegral_prod_symm' [SFinite μ] (f : α × β → ℝ≥0∞) (hf : Measurable f) : ∫⁻ z, f z ∂μ.prod ν = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := lintegral_prod_symm f hf.aemeasurable /-- The reversed version of **Tonelli's Theorem**. In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ theorem lintegral_lintegral ⦃f : α → β → ℝ≥0∞⦄ (hf : AEMeasurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.1 z.2 ∂μ.prod ν := (lintegral_prod _ hf).symm /-- The reversed version of **Tonelli's Theorem** (symmetric version). In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ theorem lintegral_lintegral_symm [SFinite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : AEMeasurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.2 z.1 ∂ν.prod μ := (lintegral_prod_symm _ hf.prod_swap).symm /-- Change the order of Lebesgue integration. -/ theorem lintegral_lintegral_swap [SFinite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : AEMeasurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ y, ∫⁻ x, f x y ∂μ ∂ν := (lintegral_lintegral hf).trans (lintegral_prod_symm _ hf) theorem lintegral_prod_mul {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : AEMeasurable f μ) (hg : AEMeasurable g ν) : ∫⁻ z, f z.1 * g z.2 ∂μ.prod ν = (∫⁻ x, f x ∂μ) * ∫⁻ y, g y ∂ν := by simp [lintegral_prod _ (hf.fst.mul hg.snd), lintegral_lintegral_mul hf hg] /-! ### Marginals of a measure defined on a product -/ namespace Measure variable {ρ : Measure (α × β)} /-- Marginal measure on `α` obtained from a measure `ρ` on `α × β`, defined by `ρ.map Prod.fst`. -/ noncomputable def fst (ρ : Measure (α × β)) : Measure α := ρ.map Prod.fst theorem fst_apply {s : Set α} (hs : MeasurableSet s) : ρ.fst s = ρ (Prod.fst ⁻¹' s) := by rw [fst, Measure.map_apply measurable_fst hs] theorem fst_univ : ρ.fst univ = ρ univ := by rw [fst_apply MeasurableSet.univ, preimage_univ] @[simp] theorem fst_zero : fst (0 : Measure (α × β)) = 0 := by simp [fst] instance [SFinite ρ] : SFinite ρ.fst := by rw [fst] infer_instance instance fst.instIsFiniteMeasure [IsFiniteMeasure ρ] : IsFiniteMeasure ρ.fst := by rw [fst] infer_instance instance fst.instIsProbabilityMeasure [IsProbabilityMeasure ρ] : IsProbabilityMeasure ρ.fst where measure_univ := by rw [fst_univ] exact measure_univ @[simp] lemma fst_prod [IsProbabilityMeasure ν] : (μ.prod ν).fst = μ := by ext1 s hs rw [fst_apply hs, ← prod_univ, prod_prod, measure_univ, mul_one] theorem fst_map_prod_mk₀ {X : α → β} {Y : α → γ} {μ : Measure α} (hY : AEMeasurable Y μ) : (μ.map fun a => (X a, Y a)).fst = μ.map X := by by_cases hX : AEMeasurable X μ · ext1 s hs rw [Measure.fst_apply hs, Measure.map_apply_of_aemeasurable (hX.prod_mk hY) (measurable_fst hs), Measure.map_apply_of_aemeasurable hX hs, ← prod_univ, mk_preimage_prod, preimage_univ, inter_univ] · have : ¬AEMeasurable (fun x ↦ (X x, Y x)) μ := by contrapose! hX; exact measurable_fst.comp_aemeasurable hX simp [map_of_not_aemeasurable, hX, this] theorem fst_map_prod_mk {X : α → β} {Y : α → γ} {μ : Measure α} (hY : Measurable Y) : (μ.map fun a => (X a, Y a)).fst = μ.map X := fst_map_prod_mk₀ hY.aemeasurable /-- Marginal measure on `β` obtained from a measure on `ρ` `α × β`, defined by `ρ.map Prod.snd`. -/ noncomputable def snd (ρ : Measure (α × β)) : Measure β := ρ.map Prod.snd theorem snd_apply {s : Set β} (hs : MeasurableSet s) : ρ.snd s = ρ (Prod.snd ⁻¹' s) := by rw [snd, Measure.map_apply measurable_snd hs] theorem snd_univ : ρ.snd univ = ρ univ := by rw [snd_apply MeasurableSet.univ, preimage_univ] @[simp] theorem snd_zero : snd (0 : Measure (α × β)) = 0 := by simp [snd] instance [SFinite ρ] : SFinite ρ.snd := by rw [snd] infer_instance instance snd.instIsFiniteMeasure [IsFiniteMeasure ρ] : IsFiniteMeasure ρ.snd := by rw [snd] infer_instance instance snd.instIsProbabilityMeasure [IsProbabilityMeasure ρ] : IsProbabilityMeasure ρ.snd where measure_univ := by rw [snd_univ] exact measure_univ @[simp] lemma snd_prod [IsProbabilityMeasure μ] : (μ.prod ν).snd = ν := by ext1 s hs rw [snd_apply hs, ← univ_prod, prod_prod, measure_univ, one_mul] theorem snd_map_prod_mk₀ {X : α → β} {Y : α → γ} {μ : Measure α} (hX : AEMeasurable X μ) : (μ.map fun a => (X a, Y a)).snd = μ.map Y := by by_cases hY : AEMeasurable Y μ · ext1 s hs rw [Measure.snd_apply hs, Measure.map_apply_of_aemeasurable (hX.prod_mk hY) (measurable_snd hs), Measure.map_apply_of_aemeasurable hY hs, ← univ_prod, mk_preimage_prod, preimage_univ, univ_inter] · have : ¬AEMeasurable (fun x ↦ (X x, Y x)) μ := by contrapose! hY; exact measurable_snd.comp_aemeasurable hY simp [map_of_not_aemeasurable, hY, this] theorem snd_map_prod_mk {X : α → β} {Y : α → γ} {μ : Measure α} (hX : Measurable X) : (μ.map fun a => (X a, Y a)).snd = μ.map Y := snd_map_prod_mk₀ hX.aemeasurable @[simp] lemma fst_map_swap : (ρ.map Prod.swap).fst = ρ.snd := by rw [Measure.fst, Measure.map_map measurable_fst measurable_swap] rfl @[simp] lemma snd_map_swap : (ρ.map Prod.swap).snd = ρ.fst := by rw [Measure.snd, Measure.map_map measurable_snd measurable_swap] rfl end Measure end MeasureTheory
MeasureTheory\Constructions\Prod\Integral.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.MeasureTheory.Constructions.Prod.Basic import Mathlib.MeasureTheory.Integral.DominatedConvergence import Mathlib.MeasureTheory.Integral.SetIntegral /-! # Integration with respect to the product measure In this file we prove Fubini's theorem. ## Main results * `MeasureTheory.integrable_prod_iff` states that a binary function is integrable iff both * `y ↦ f (x, y)` is integrable for almost every `x`, and * the function `x ↦ ∫ ‖f (x, y)‖ dy` is integrable. * `MeasureTheory.integral_prod`: Fubini's theorem. It states that for an integrable function `α × β → E` (where `E` is a second countable Banach space) we have `∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ`. This theorem has the same variants as Tonelli's theorem (see `MeasureTheory.lintegral_prod`). The lemma `MeasureTheory.Integrable.integral_prod_right` states that the inner integral of the right-hand side is integrable. * `MeasureTheory.integral_integral_swap_of_hasCompactSupport`: a version of Fubini theorem for continuous functions with compact support, which does not assume that the measures are σ-finite contrary to all the usual versions of Fubini. ## Tags product measure, Fubini's theorem, Fubini-Tonelli theorem -/ noncomputable section open scoped Classical Topology ENNReal MeasureTheory open Set Function Real ENNReal open MeasureTheory MeasurableSpace MeasureTheory.Measure open TopologicalSpace open Filter hiding prod_eq map variable {α α' β β' γ E : Type*} variable [MeasurableSpace α] [MeasurableSpace α'] [MeasurableSpace β] [MeasurableSpace β'] variable [MeasurableSpace γ] variable {μ μ' : Measure α} {ν ν' : Measure β} {τ : Measure γ} variable [NormedAddCommGroup E] /-! ### Measurability Before we define the product measure, we can talk about the measurability of operations on binary functions. We show that if `f` is a binary measurable function, then the function that integrates along one of the variables (using either the Lebesgue or Bochner integral) is measurable. -/ theorem measurableSet_integrable [SFinite ν] ⦃f : α → β → E⦄ (hf : StronglyMeasurable (uncurry f)) : MeasurableSet {x | Integrable (f x) ν} := by simp_rw [Integrable, hf.of_uncurry_left.aestronglyMeasurable, true_and_iff] exact measurableSet_lt (Measurable.lintegral_prod_right hf.ennnorm) measurable_const section variable [NormedSpace ℝ E] /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. This version has `f` in curried form. -/ theorem MeasureTheory.StronglyMeasurable.integral_prod_right [SFinite ν] ⦃f : α → β → E⦄ (hf : StronglyMeasurable (uncurry f)) : StronglyMeasurable fun x => ∫ y, f x y ∂ν := by by_cases hE : CompleteSpace E; swap; · simp [integral, hE, stronglyMeasurable_const] borelize E haveI : SeparableSpace (range (uncurry f) ∪ {0} : Set E) := hf.separableSpace_range_union_singleton let s : ℕ → SimpleFunc (α × β) E := SimpleFunc.approxOn _ hf.measurable (range (uncurry f) ∪ {0}) 0 (by simp) let s' : ℕ → α → SimpleFunc β E := fun n x => (s n).comp (Prod.mk x) measurable_prod_mk_left let f' : ℕ → α → E := fun n => {x | Integrable (f x) ν}.indicator fun x => (s' n x).integral ν have hf' : ∀ n, StronglyMeasurable (f' n) := by intro n; refine StronglyMeasurable.indicator ?_ (measurableSet_integrable hf) have : ∀ x, ((s' n x).range.filter fun x => x ≠ 0) ⊆ (s n).range := by intro x; refine Finset.Subset.trans (Finset.filter_subset _ _) ?_; intro y simp_rw [SimpleFunc.mem_range]; rintro ⟨z, rfl⟩; exact ⟨(x, z), rfl⟩ simp only [SimpleFunc.integral_eq_sum_of_subset (this _)] refine Finset.stronglyMeasurable_sum _ fun x _ => ?_ refine (Measurable.ennreal_toReal ?_).stronglyMeasurable.smul_const _ simp only [s', SimpleFunc.coe_comp, preimage_comp] apply measurable_measure_prod_mk_left exact (s n).measurableSet_fiber x have h2f' : Tendsto f' atTop (𝓝 fun x : α => ∫ y : β, f x y ∂ν) := by rw [tendsto_pi_nhds]; intro x by_cases hfx : Integrable (f x) ν · have (n) : Integrable (s' n x) ν := by apply (hfx.norm.add hfx.norm).mono' (s' n x).aestronglyMeasurable filter_upwards with y simp_rw [s', SimpleFunc.coe_comp]; exact SimpleFunc.norm_approxOn_zero_le _ _ (x, y) n simp only [f', hfx, SimpleFunc.integral_eq_integral _ (this _), indicator_of_mem, mem_setOf_eq] refine tendsto_integral_of_dominated_convergence (fun y => ‖f x y‖ + ‖f x y‖) (fun n => (s' n x).aestronglyMeasurable) (hfx.norm.add hfx.norm) ?_ ?_ · refine fun n => eventually_of_forall fun y => SimpleFunc.norm_approxOn_zero_le ?_ ?_ (x, y) n -- Porting note: Lean 3 solved the following two subgoals on its own · exact hf.measurable · simp · refine eventually_of_forall fun y => SimpleFunc.tendsto_approxOn ?_ ?_ ?_ -- Porting note: Lean 3 solved the following two subgoals on its own · exact hf.measurable.of_uncurry_left · simp apply subset_closure simp [-uncurry_apply_pair] · simp [f', hfx, integral_undef] exact stronglyMeasurable_of_tendsto _ hf' h2f' /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. -/ theorem MeasureTheory.StronglyMeasurable.integral_prod_right' [SFinite ν] ⦃f : α × β → E⦄ (hf : StronglyMeasurable f) : StronglyMeasurable fun x => ∫ y, f (x, y) ∂ν := by rw [← uncurry_curry f] at hf; exact hf.integral_prod_right /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. This version has `f` in curried form. -/ theorem MeasureTheory.StronglyMeasurable.integral_prod_left [SFinite μ] ⦃f : α → β → E⦄ (hf : StronglyMeasurable (uncurry f)) : StronglyMeasurable fun y => ∫ x, f x y ∂μ := (hf.comp_measurable measurable_swap).integral_prod_right' /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. -/ theorem MeasureTheory.StronglyMeasurable.integral_prod_left' [SFinite μ] ⦃f : α × β → E⦄ (hf : StronglyMeasurable f) : StronglyMeasurable fun y => ∫ x, f (x, y) ∂μ := (hf.comp_measurable measurable_swap).integral_prod_right' end /-! ### The product measure -/ namespace MeasureTheory namespace Measure variable [SFinite ν] theorem integrable_measure_prod_mk_left {s : Set (α × β)} (hs : MeasurableSet s) (h2s : (μ.prod ν) s ≠ ∞) : Integrable (fun x => (ν (Prod.mk x ⁻¹' s)).toReal) μ := by refine ⟨(measurable_measure_prod_mk_left hs).ennreal_toReal.aemeasurable.aestronglyMeasurable, ?_⟩ simp_rw [HasFiniteIntegral, ennnorm_eq_ofReal toReal_nonneg] convert h2s.lt_top using 1 -- Porting note: was `simp_rw` rw [prod_apply hs] apply lintegral_congr_ae filter_upwards [ae_measure_lt_top hs h2s] with x hx rw [lt_top_iff_ne_top] at hx; simp [ofReal_toReal, hx] end Measure open Measure end MeasureTheory open MeasureTheory.Measure section nonrec theorem MeasureTheory.AEStronglyMeasurable.prod_swap {γ : Type*} [TopologicalSpace γ] [SFinite μ] [SFinite ν] {f : β × α → γ} (hf : AEStronglyMeasurable f (ν.prod μ)) : AEStronglyMeasurable (fun z : α × β => f z.swap) (μ.prod ν) := by rw [← prod_swap] at hf exact hf.comp_measurable measurable_swap theorem MeasureTheory.AEStronglyMeasurable.fst {γ} [TopologicalSpace γ] [SFinite ν] {f : α → γ} (hf : AEStronglyMeasurable f μ) : AEStronglyMeasurable (fun z : α × β => f z.1) (μ.prod ν) := hf.comp_quasiMeasurePreserving quasiMeasurePreserving_fst theorem MeasureTheory.AEStronglyMeasurable.snd {γ} [TopologicalSpace γ] [SFinite ν] {f : β → γ} (hf : AEStronglyMeasurable f ν) : AEStronglyMeasurable (fun z : α × β => f z.2) (μ.prod ν) := hf.comp_quasiMeasurePreserving quasiMeasurePreserving_snd /-- The Bochner integral is a.e.-measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is a.e.-measurable. -/ theorem MeasureTheory.AEStronglyMeasurable.integral_prod_right' [SFinite ν] [NormedSpace ℝ E] ⦃f : α × β → E⦄ (hf : AEStronglyMeasurable f (μ.prod ν)) : AEStronglyMeasurable (fun x => ∫ y, f (x, y) ∂ν) μ := ⟨fun x => ∫ y, hf.mk f (x, y) ∂ν, hf.stronglyMeasurable_mk.integral_prod_right', by filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ hx using integral_congr_ae hx⟩ theorem MeasureTheory.AEStronglyMeasurable.prod_mk_left {γ : Type*} [SFinite ν] [TopologicalSpace γ] {f : α × β → γ} (hf : AEStronglyMeasurable f (μ.prod ν)) : ∀ᵐ x ∂μ, AEStronglyMeasurable (fun y => f (x, y)) ν := by filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with x hx exact ⟨fun y => hf.mk f (x, y), hf.stronglyMeasurable_mk.comp_measurable measurable_prod_mk_left, hx⟩ end namespace MeasureTheory variable [SFinite ν] /-! ### Integrability on a product -/ section theorem integrable_swap_iff [SFinite μ] {f : α × β → E} : Integrable (f ∘ Prod.swap) (ν.prod μ) ↔ Integrable f (μ.prod ν) := measurePreserving_swap.integrable_comp_emb MeasurableEquiv.prodComm.measurableEmbedding theorem Integrable.swap [SFinite μ] ⦃f : α × β → E⦄ (hf : Integrable f (μ.prod ν)) : Integrable (f ∘ Prod.swap) (ν.prod μ) := integrable_swap_iff.2 hf theorem hasFiniteIntegral_prod_iff ⦃f : α × β → E⦄ (h1f : StronglyMeasurable f) : HasFiniteIntegral f (μ.prod ν) ↔ (∀ᵐ x ∂μ, HasFiniteIntegral (fun y => f (x, y)) ν) ∧ HasFiniteIntegral (fun x => ∫ y, ‖f (x, y)‖ ∂ν) μ := by simp only [HasFiniteIntegral, lintegral_prod_of_measurable _ h1f.ennnorm] have (x) : ∀ᵐ y ∂ν, 0 ≤ ‖f (x, y)‖ := by filter_upwards with y using norm_nonneg _ simp_rw [integral_eq_lintegral_of_nonneg_ae (this _) (h1f.norm.comp_measurable measurable_prod_mk_left).aestronglyMeasurable, ennnorm_eq_ofReal toReal_nonneg, ofReal_norm_eq_coe_nnnorm] -- this fact is probably too specialized to be its own lemma have : ∀ {p q r : Prop} (_ : r → p), (r ↔ p ∧ q) ↔ p → (r ↔ q) := fun {p q r} h1 => by rw [← and_congr_right_iff, and_iff_right_of_imp h1] rw [this] · intro h2f; rw [lintegral_congr_ae] filter_upwards [h2f] with x hx rw [ofReal_toReal]; rw [← lt_top_iff_ne_top]; exact hx · intro h2f; refine ae_lt_top ?_ h2f.ne; exact h1f.ennnorm.lintegral_prod_right' theorem hasFiniteIntegral_prod_iff' ⦃f : α × β → E⦄ (h1f : AEStronglyMeasurable f (μ.prod ν)) : HasFiniteIntegral f (μ.prod ν) ↔ (∀ᵐ x ∂μ, HasFiniteIntegral (fun y => f (x, y)) ν) ∧ HasFiniteIntegral (fun x => ∫ y, ‖f (x, y)‖ ∂ν) μ := by rw [hasFiniteIntegral_congr h1f.ae_eq_mk, hasFiniteIntegral_prod_iff h1f.stronglyMeasurable_mk] apply and_congr · apply eventually_congr filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm] intro x hx exact hasFiniteIntegral_congr hx · apply hasFiniteIntegral_congr filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm] with _ hx using integral_congr_ae (EventuallyEq.fun_comp hx _) /-- A binary function is integrable if the function `y ↦ f (x, y)` is integrable for almost every `x` and the function `x ↦ ∫ ‖f (x, y)‖ dy` is integrable. -/ theorem integrable_prod_iff ⦃f : α × β → E⦄ (h1f : AEStronglyMeasurable f (μ.prod ν)) : Integrable f (μ.prod ν) ↔ (∀ᵐ x ∂μ, Integrable (fun y => f (x, y)) ν) ∧ Integrable (fun x => ∫ y, ‖f (x, y)‖ ∂ν) μ := by simp [Integrable, h1f, hasFiniteIntegral_prod_iff', h1f.norm.integral_prod_right', h1f.prod_mk_left] /-- A binary function is integrable if the function `x ↦ f (x, y)` is integrable for almost every `y` and the function `y ↦ ∫ ‖f (x, y)‖ dx` is integrable. -/ theorem integrable_prod_iff' [SFinite μ] ⦃f : α × β → E⦄ (h1f : AEStronglyMeasurable f (μ.prod ν)) : Integrable f (μ.prod ν) ↔ (∀ᵐ y ∂ν, Integrable (fun x => f (x, y)) μ) ∧ Integrable (fun y => ∫ x, ‖f (x, y)‖ ∂μ) ν := by convert integrable_prod_iff h1f.prod_swap using 1 rw [funext fun _ => Function.comp_apply.symm, integrable_swap_iff] theorem Integrable.prod_left_ae [SFinite μ] ⦃f : α × β → E⦄ (hf : Integrable f (μ.prod ν)) : ∀ᵐ y ∂ν, Integrable (fun x => f (x, y)) μ := ((integrable_prod_iff' hf.aestronglyMeasurable).mp hf).1 theorem Integrable.prod_right_ae [SFinite μ] ⦃f : α × β → E⦄ (hf : Integrable f (μ.prod ν)) : ∀ᵐ x ∂μ, Integrable (fun y => f (x, y)) ν := hf.swap.prod_left_ae theorem Integrable.integral_norm_prod_left ⦃f : α × β → E⦄ (hf : Integrable f (μ.prod ν)) : Integrable (fun x => ∫ y, ‖f (x, y)‖ ∂ν) μ := ((integrable_prod_iff hf.aestronglyMeasurable).mp hf).2 theorem Integrable.integral_norm_prod_right [SFinite μ] ⦃f : α × β → E⦄ (hf : Integrable f (μ.prod ν)) : Integrable (fun y => ∫ x, ‖f (x, y)‖ ∂μ) ν := hf.swap.integral_norm_prod_left theorem Integrable.prod_smul {𝕜 : Type*} [NontriviallyNormedField 𝕜] [NormedSpace 𝕜 E] {f : α → 𝕜} {g : β → E} (hf : Integrable f μ) (hg : Integrable g ν) : Integrable (fun z : α × β => f z.1 • g z.2) (μ.prod ν) := by refine (integrable_prod_iff ?_).2 ⟨?_, ?_⟩ · exact hf.1.fst.smul hg.1.snd · exact eventually_of_forall fun x => hg.smul (f x) · simpa only [norm_smul, integral_mul_left] using hf.norm.mul_const _ theorem Integrable.prod_mul {L : Type*} [RCLike L] {f : α → L} {g : β → L} (hf : Integrable f μ) (hg : Integrable g ν) : Integrable (fun z : α × β => f z.1 * g z.2) (μ.prod ν) := hf.prod_smul hg end variable [NormedSpace ℝ E] theorem Integrable.integral_prod_left ⦃f : α × β → E⦄ (hf : Integrable f (μ.prod ν)) : Integrable (fun x => ∫ y, f (x, y) ∂ν) μ := Integrable.mono hf.integral_norm_prod_left hf.aestronglyMeasurable.integral_prod_right' <| eventually_of_forall fun x => (norm_integral_le_integral_norm _).trans_eq <| (norm_of_nonneg <| integral_nonneg_of_ae <| eventually_of_forall fun y => (norm_nonneg (f (x, y)) : _)).symm theorem Integrable.integral_prod_right [SFinite μ] ⦃f : α × β → E⦄ (hf : Integrable f (μ.prod ν)) : Integrable (fun y => ∫ x, f (x, y) ∂μ) ν := hf.swap.integral_prod_left /-! ### The Bochner integral on a product -/ variable [SFinite μ] theorem integral_prod_swap (f : α × β → E) : ∫ z, f z.swap ∂ν.prod μ = ∫ z, f z ∂μ.prod ν := measurePreserving_swap.integral_comp MeasurableEquiv.prodComm.measurableEmbedding _ variable {E' : Type*} [NormedAddCommGroup E'] [NormedSpace ℝ E'] /-! Some rules about the sum/difference of double integrals. They follow from `integral_add`, but we separate them out as separate lemmas, because they involve quite some steps. -/ /-- Integrals commute with addition inside another integral. `F` can be any function. -/ theorem integral_fn_integral_add ⦃f g : α × β → E⦄ (F : E → E') (hf : Integrable f (μ.prod ν)) (hg : Integrable g (μ.prod ν)) : (∫ x, F (∫ y, f (x, y) + g (x, y) ∂ν) ∂μ) = ∫ x, F ((∫ y, f (x, y) ∂ν) + ∫ y, g (x, y) ∂ν) ∂μ := by refine integral_congr_ae ?_ filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g simp [integral_add h2f h2g] /-- Integrals commute with subtraction inside another integral. `F` can be any measurable function. -/ theorem integral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → E') (hf : Integrable f (μ.prod ν)) (hg : Integrable g (μ.prod ν)) : (∫ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ) = ∫ x, F ((∫ y, f (x, y) ∂ν) - ∫ y, g (x, y) ∂ν) ∂μ := by refine integral_congr_ae ?_ filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g simp [integral_sub h2f h2g] /-- Integrals commute with subtraction inside a lower Lebesgue integral. `F` can be any function. -/ theorem lintegral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → ℝ≥0∞) (hf : Integrable f (μ.prod ν)) (hg : Integrable g (μ.prod ν)) : (∫⁻ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ) = ∫⁻ x, F ((∫ y, f (x, y) ∂ν) - ∫ y, g (x, y) ∂ν) ∂μ := by refine lintegral_congr_ae ?_ filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g simp [integral_sub h2f h2g] /-- Double integrals commute with addition. -/ theorem integral_integral_add ⦃f g : α × β → E⦄ (hf : Integrable f (μ.prod ν)) (hg : Integrable g (μ.prod ν)) : (∫ x, ∫ y, f (x, y) + g (x, y) ∂ν ∂μ) = (∫ x, ∫ y, f (x, y) ∂ν ∂μ) + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_add id hf hg).trans <| integral_add hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with addition. This is the version with `(f + g) (x, y)` (instead of `f (x, y) + g (x, y)`) in the LHS. -/ theorem integral_integral_add' ⦃f g : α × β → E⦄ (hf : Integrable f (μ.prod ν)) (hg : Integrable g (μ.prod ν)) : (∫ x, ∫ y, (f + g) (x, y) ∂ν ∂μ) = (∫ x, ∫ y, f (x, y) ∂ν ∂μ) + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_add hf hg /-- Double integrals commute with subtraction. -/ theorem integral_integral_sub ⦃f g : α × β → E⦄ (hf : Integrable f (μ.prod ν)) (hg : Integrable g (μ.prod ν)) : (∫ x, ∫ y, f (x, y) - g (x, y) ∂ν ∂μ) = (∫ x, ∫ y, f (x, y) ∂ν ∂μ) - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_sub id hf hg).trans <| integral_sub hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with subtraction. This is the version with `(f - g) (x, y)` (instead of `f (x, y) - g (x, y)`) in the LHS. -/ theorem integral_integral_sub' ⦃f g : α × β → E⦄ (hf : Integrable f (μ.prod ν)) (hg : Integrable g (μ.prod ν)) : (∫ x, ∫ y, (f - g) (x, y) ∂ν ∂μ) = (∫ x, ∫ y, f (x, y) ∂ν ∂μ) - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_sub hf hg /-- The map that sends an L¹-function `f : α × β → E` to `∫∫f` is continuous. -/ theorem continuous_integral_integral : Continuous fun f : α × β →₁[μ.prod ν] E => ∫ x, ∫ y, f (x, y) ∂ν ∂μ := by rw [continuous_iff_continuousAt]; intro g refine tendsto_integral_of_L1 _ (L1.integrable_coeFn g).integral_prod_left (eventually_of_forall fun h => (L1.integrable_coeFn h).integral_prod_left) ?_ simp_rw [← lintegral_fn_integral_sub (fun x => (‖x‖₊ : ℝ≥0∞)) (L1.integrable_coeFn _) (L1.integrable_coeFn g)] apply tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds _ (fun i => zero_le _) _ · exact fun i => ∫⁻ x, ∫⁻ y, ‖i (x, y) - g (x, y)‖₊ ∂ν ∂μ swap; · exact fun i => lintegral_mono fun x => ennnorm_integral_le_lintegral_ennnorm _ show Tendsto (fun i : α × β →₁[μ.prod ν] E => ∫⁻ x, ∫⁻ y : β, ‖i (x, y) - g (x, y)‖₊ ∂ν ∂μ) (𝓝 g) (𝓝 0) have : ∀ i : α × β →₁[μ.prod ν] E, Measurable fun z => (‖i z - g z‖₊ : ℝ≥0∞) := fun i => ((Lp.stronglyMeasurable i).sub (Lp.stronglyMeasurable g)).ennnorm -- Porting note: was -- simp_rw [← lintegral_prod_of_measurable _ (this _), ← L1.ofReal_norm_sub_eq_lintegral, ← -- ofReal_zero] conv => congr ext rw [← lintegral_prod_of_measurable _ (this _), ← L1.ofReal_norm_sub_eq_lintegral] rw [← ofReal_zero] refine (continuous_ofReal.tendsto 0).comp ?_ rw [← tendsto_iff_norm_sub_tendsto_zero]; exact tendsto_id /-- **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. `integrable_prod_iff` can be useful to show that the function in question in integrable. `MeasureTheory.Integrable.integral_prod_right` is useful to show that the inner integral of the right-hand side is integrable. -/ theorem integral_prod (f : α × β → E) (hf : Integrable f (μ.prod ν)) : ∫ z, f z ∂μ.prod ν = ∫ x, ∫ y, f (x, y) ∂ν ∂μ := by by_cases hE : CompleteSpace E; swap; · simp only [integral, dif_neg hE] revert f apply Integrable.induction · intro c s hs h2s simp_rw [integral_indicator hs, ← indicator_comp_right, Function.comp, integral_indicator (measurable_prod_mk_left hs), setIntegral_const, integral_smul_const, integral_toReal (measurable_measure_prod_mk_left hs).aemeasurable (ae_measure_lt_top hs h2s.ne)] -- Porting note: was `simp_rw` rw [prod_apply hs] · rintro f g - i_f i_g hf hg simp_rw [integral_add' i_f i_g, integral_integral_add' i_f i_g, hf, hg] · exact isClosed_eq continuous_integral continuous_integral_integral · rintro f g hfg - hf; convert hf using 1 · exact integral_congr_ae hfg.symm · apply integral_congr_ae filter_upwards [ae_ae_of_ae_prod hfg] with x hfgx using integral_congr_ae (ae_eq_symm hfgx) /-- Symmetric version of **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. This version has the integrals on the right-hand side in the other order. -/ theorem integral_prod_symm (f : α × β → E) (hf : Integrable f (μ.prod ν)) : ∫ z, f z ∂μ.prod ν = ∫ y, ∫ x, f (x, y) ∂μ ∂ν := by rw [← integral_prod_swap f]; exact integral_prod _ hf.swap /-- Reversed version of **Fubini's Theorem**. -/ theorem integral_integral {f : α → β → E} (hf : Integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.1 z.2 ∂μ.prod ν := (integral_prod _ hf).symm /-- Reversed version of **Fubini's Theorem** (symmetric version). -/ theorem integral_integral_symm {f : α → β → E} (hf : Integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.2 z.1 ∂ν.prod μ := (integral_prod_symm _ hf.swap).symm /-- Change the order of Bochner integration. -/ theorem integral_integral_swap ⦃f : α → β → E⦄ (hf : Integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ y, ∫ x, f x y ∂μ ∂ν := (integral_integral hf).trans (integral_prod_symm _ hf) /-- **Fubini's Theorem** for set integrals. -/ theorem setIntegral_prod (f : α × β → E) {s : Set α} {t : Set β} (hf : IntegrableOn f (s ×ˢ t) (μ.prod ν)) : ∫ z in s ×ˢ t, f z ∂μ.prod ν = ∫ x in s, ∫ y in t, f (x, y) ∂ν ∂μ := by simp only [← Measure.prod_restrict s t, IntegrableOn] at hf ⊢ exact integral_prod f hf @[deprecated (since := "2024-04-17")] alias set_integral_prod := setIntegral_prod theorem integral_prod_smul {𝕜 : Type*} [RCLike 𝕜] [NormedSpace 𝕜 E] (f : α → 𝕜) (g : β → E) : ∫ z, f z.1 • g z.2 ∂μ.prod ν = (∫ x, f x ∂μ) • ∫ y, g y ∂ν := by by_cases hE : CompleteSpace E; swap; · simp [integral, hE] by_cases h : Integrable (fun z : α × β => f z.1 • g z.2) (μ.prod ν) · rw [integral_prod _ h] simp_rw [integral_smul, integral_smul_const] have H : ¬Integrable f μ ∨ ¬Integrable g ν := by contrapose! h exact h.1.prod_smul h.2 cases' H with H H <;> simp [integral_undef h, integral_undef H] theorem integral_prod_mul {L : Type*} [RCLike L] (f : α → L) (g : β → L) : ∫ z, f z.1 * g z.2 ∂μ.prod ν = (∫ x, f x ∂μ) * ∫ y, g y ∂ν := integral_prod_smul f g theorem setIntegral_prod_mul {L : Type*} [RCLike L] (f : α → L) (g : β → L) (s : Set α) (t : Set β) : ∫ z in s ×ˢ t, f z.1 * g z.2 ∂μ.prod ν = (∫ x in s, f x ∂μ) * ∫ y in t, g y ∂ν := by -- Porting note: added rw [← Measure.prod_restrict s t] apply integral_prod_mul @[deprecated (since := "2024-04-17")] alias set_integral_prod_mul := setIntegral_prod_mul theorem integral_fun_snd (f : β → E) : ∫ z, f z.2 ∂μ.prod ν = (μ univ).toReal • ∫ y, f y ∂ν := by simpa using integral_prod_smul (1 : α → ℝ) f theorem integral_fun_fst (f : α → E) : ∫ z, f z.1 ∂μ.prod ν = (ν univ).toReal • ∫ x, f x ∂μ := by rw [← integral_prod_swap] apply integral_fun_snd section variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] [MeasurableSpace X] [MeasurableSpace Y] [OpensMeasurableSpace X] [OpensMeasurableSpace Y] /-- A version of *Fubini theorem* for continuous functions with compact support: one may swap the order of integration with respect to locally finite measures. One does not assume that the measures are σ-finite, contrary to the usual Fubini theorem. -/ lemma integral_integral_swap_of_hasCompactSupport {f : X → Y → E} (hf : Continuous f.uncurry) (h'f : HasCompactSupport f.uncurry) {μ : Measure X} {ν : Measure Y} [IsFiniteMeasureOnCompacts μ] [IsFiniteMeasureOnCompacts ν] : ∫ x, (∫ y, f x y ∂ν) ∂μ = ∫ y, (∫ x, f x y ∂μ) ∂ν := by let U := Prod.fst '' (tsupport f.uncurry) have : Fact (μ U < ∞) := ⟨(IsCompact.image h'f continuous_fst).measure_lt_top⟩ let V := Prod.snd '' (tsupport f.uncurry) have : Fact (ν V < ∞) := ⟨(IsCompact.image h'f continuous_snd).measure_lt_top⟩ calc ∫ x, (∫ y, f x y ∂ν) ∂μ = ∫ x, (∫ y in V, f x y ∂ν) ∂μ := by congr 1 with x apply (setIntegral_eq_integral_of_forall_compl_eq_zero (fun y hy ↦ ?_)).symm contrapose! hy have : (x, y) ∈ Function.support f.uncurry := hy exact mem_image_of_mem _ (subset_tsupport _ this) _ = ∫ x in U, (∫ y in V, f x y ∂ν) ∂μ := by apply (setIntegral_eq_integral_of_forall_compl_eq_zero (fun x hx ↦ ?_)).symm have : ∀ y, f x y = 0 := by intro y contrapose! hx have : (x, y) ∈ Function.support f.uncurry := hx exact mem_image_of_mem _ (subset_tsupport _ this) simp [this] _ = ∫ y in V, (∫ x in U, f x y ∂μ) ∂ν := by apply integral_integral_swap apply (integrableOn_iff_integrable_of_support_subset (subset_tsupport f.uncurry)).mp refine ⟨(h'f.stronglyMeasurable_of_prod hf).aestronglyMeasurable, ?_⟩ obtain ⟨C, hC⟩ : ∃ C, ∀ p, ‖f.uncurry p‖ ≤ C := hf.bounded_above_of_compact_support h'f exact hasFiniteIntegral_of_bounded (C := C) (eventually_of_forall hC) _ = ∫ y, (∫ x in U, f x y ∂μ) ∂ν := by apply setIntegral_eq_integral_of_forall_compl_eq_zero (fun y hy ↦ ?_) have : ∀ x, f x y = 0 := by intro x contrapose! hy have : (x, y) ∈ Function.support f.uncurry := hy exact mem_image_of_mem _ (subset_tsupport _ this) simp [this] _ = ∫ y, (∫ x, f x y ∂μ) ∂ν := by congr 1 with y apply setIntegral_eq_integral_of_forall_compl_eq_zero (fun x hx ↦ ?_) contrapose! hx have : (x, y) ∈ Function.support f.uncurry := hx exact mem_image_of_mem _ (subset_tsupport _ this) end end MeasureTheory
MeasureTheory\Covering\Besicovitch.lean
/- Copyright (c) 2021 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.MeasureTheory.Covering.Differentiation import Mathlib.MeasureTheory.Covering.VitaliFamily import Mathlib.MeasureTheory.Integral.Lebesgue import Mathlib.MeasureTheory.Measure.Regular import Mathlib.SetTheory.Ordinal.Arithmetic import Mathlib.Topology.MetricSpace.Basic import Mathlib.Data.Set.Pairwise.Lattice /-! # Besicovitch covering theorems The topological Besicovitch covering theorem ensures that, in a nice metric space, there exists a number `N` such that, from any family of balls with bounded radii, one can extract `N` families, each made of disjoint balls, covering together all the centers of the initial family. By "nice metric space", we mean a technical property stated as follows: there exists no satellite configuration of `N + 1` points (with a given parameter `τ > 1`). Such a configuration is a family of `N + 1` balls, where the first `N` balls all intersect the last one, but none of them contains the center of another one and their radii are controlled. This property is for instance satisfied by finite-dimensional real vector spaces. In this file, we prove the topological Besicovitch covering theorem, in `Besicovitch.exist_disjoint_covering_families`. The measurable Besicovitch theorem ensures that, in the same class of metric spaces, if at every point one considers a class of balls of arbitrarily small radii, called admissible balls, then one can cover almost all the space by a family of disjoint admissible balls. It is deduced from the topological Besicovitch theorem, and proved in `Besicovitch.exists_disjoint_closedBall_covering_ae`. This implies that balls of small radius form a Vitali family in such spaces. Therefore, theorems on differentiation of measures hold as a consequence of general results. We restate them in this context to make them more easily usable. ## Main definitions and results * `SatelliteConfig α N τ` is the type of all satellite configurations of `N + 1` points in the metric space `α`, with parameter `τ`. * `HasBesicovitchCovering` is a class recording that there exist `N` and `τ > 1` such that there is no satellite configuration of `N + 1` points with parameter `τ`. * `exist_disjoint_covering_families` is the topological Besicovitch covering theorem: from any family of balls one can extract finitely many disjoint subfamilies covering the same set. * `exists_disjoint_closedBall_covering` is the measurable Besicovitch covering theorem: from any family of balls with arbitrarily small radii at every point, one can extract countably many disjoint balls covering almost all the space. While the value of `N` is relevant for the precise statement of the topological Besicovitch theorem, it becomes irrelevant for the measurable one. Therefore, this statement is expressed using the `Prop`-valued typeclass `HasBesicovitchCovering`. We also restate the following specialized versions of general theorems on differentiation of measures: * `Besicovitch.ae_tendsto_rnDeriv` ensures that `ρ (closedBall x r) / μ (closedBall x r)` tends almost surely to the Radon-Nikodym derivative of `ρ` with respect to `μ` at `x`. * `Besicovitch.ae_tendsto_measure_inter_div` states that almost every point in an arbitrary set `s` is a Lebesgue density point, i.e., `μ (s ∩ closedBall x r) / μ (closedBall x r)` tends to `1` as `r` tends to `0`. A stronger version for measurable sets is given in `Besicovitch.ae_tendsto_measure_inter_div_of_measurableSet`. ## Implementation #### Sketch of proof of the topological Besicovitch theorem: We choose balls in a greedy way. First choose a ball with maximal radius (or rather, since there is no guarantee the maximal radius is realized, a ball with radius within a factor `τ` of the supremum). Then, remove all balls whose center is covered by the first ball, and choose among the remaining ones a ball with radius close to maximum. Go on forever until there is no available center (this is a transfinite induction in general). Then define inductively a coloring of the balls. A ball will be of color `i` if it intersects already chosen balls of color `0`, ..., `i - 1`, but none of color `i`. In this way, balls of the same color form a disjoint family, and the space is covered by the families of the different colors. The nontrivial part is to show that at most `N` colors are used. If one needs `N + 1` colors, consider the first time this happens. Then the corresponding ball intersects `N` balls of the different colors. Moreover, the inductive construction ensures that the radii of all the balls are controlled: they form a satellite configuration with `N + 1` balls (essentially by definition of satellite configurations). Since we assume that there are no such configurations, this is a contradiction. #### Sketch of proof of the measurable Besicovitch theorem: From the topological Besicovitch theorem, one can find a disjoint countable family of balls covering a proportion `> 1 / (N + 1)` of the space. Taking a large enough finite subset of these balls, one gets the same property for finitely many balls. Their union is closed. Therefore, any point in the complement has around it an admissible ball not intersecting these finitely many balls. Applying again the topological Besicovitch theorem, one extracts from these a disjoint countable subfamily covering a proportion `> 1 / (N + 1)` of the remaining points, and then even a disjoint finite subfamily. Then one goes on again and again, covering at each step a positive proportion of the remaining points, while remaining disjoint from the already chosen balls. The union of all these balls is the desired almost everywhere covering. -/ noncomputable section universe u open Metric Set Filter Fin MeasureTheory TopologicalSpace open scoped Topology Classical ENNReal MeasureTheory NNReal /-! ### Satellite configurations -/ /-- A satellite configuration is a configuration of `N+1` points that shows up in the inductive construction for the Besicovitch covering theorem. It depends on some parameter `τ ≥ 1`. This is a family of balls (indexed by `i : Fin N.succ`, with center `c i` and radius `r i`) such that the last ball intersects all the other balls (condition `inter`), and given any two balls there is an order between them, ensuring that the first ball does not contain the center of the other one, and the radius of the second ball can not be larger than the radius of the first ball (up to a factor `τ`). This order corresponds to the order of choice in the inductive construction: otherwise, the second ball would have been chosen before. This is the condition `h`. Finally, the last ball is chosen after all the other ones, meaning that `h` can be strengthened by keeping only one side of the alternative in `hlast`. -/ structure Besicovitch.SatelliteConfig (α : Type*) [MetricSpace α] (N : ℕ) (τ : ℝ) where c : Fin N.succ → α r : Fin N.succ → ℝ rpos : ∀ i, 0 < r i h : Pairwise fun i j => r i ≤ dist (c i) (c j) ∧ r j ≤ τ * r i ∨ r j ≤ dist (c j) (c i) ∧ r i ≤ τ * r j hlast : ∀ i < last N, r i ≤ dist (c i) (c (last N)) ∧ r (last N) ≤ τ * r i inter : ∀ i < last N, dist (c i) (c (last N)) ≤ r i + r (last N) namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for the `positivity` tactic: `Besicovitch.SatelliteConfig.r`. -/ @[positivity Besicovitch.SatelliteConfig.r _ _] def evalBesicovitchSatelliteConfigR : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ), ~q(@Besicovitch.SatelliteConfig.r $β $inst $N $τ $self $i) => assertInstancesCommute return .positive q(Besicovitch.SatelliteConfig.rpos $self $i) | _, _, _ => throwError "not Besicovitch.SatelliteConfig.r" end Mathlib.Meta.Positivity /-- A metric space has the Besicovitch covering property if there exist `N` and `τ > 1` such that there are no satellite configuration of parameter `τ` with `N+1` points. This is the condition that guarantees that the measurable Besicovitch covering theorem holds. It is satisfied by finite-dimensional real vector spaces. -/ class HasBesicovitchCovering (α : Type*) [MetricSpace α] : Prop where no_satelliteConfig : ∃ (N : ℕ) (τ : ℝ), 1 < τ ∧ IsEmpty (Besicovitch.SatelliteConfig α N τ) /-- There is always a satellite configuration with a single point. -/ instance Besicovitch.SatelliteConfig.instInhabited {α : Type*} {τ : ℝ} [Inhabited α] [MetricSpace α] : Inhabited (Besicovitch.SatelliteConfig α 0 τ) := ⟨{ c := default r := fun _ => 1 rpos := fun _ => zero_lt_one h := fun i j hij => (hij (Subsingleton.elim (α := Fin 1) i j)).elim hlast := fun i hi => by rw [Subsingleton.elim (α := Fin 1) i (last 0)] at hi; exact (lt_irrefl _ hi).elim inter := fun i hi => by rw [Subsingleton.elim (α := Fin 1) i (last 0)] at hi; exact (lt_irrefl _ hi).elim }⟩ namespace Besicovitch namespace SatelliteConfig variable {α : Type*} [MetricSpace α] {N : ℕ} {τ : ℝ} (a : SatelliteConfig α N τ) theorem inter' (i : Fin N.succ) : dist (a.c i) (a.c (last N)) ≤ a.r i + a.r (last N) := by rcases lt_or_le i (last N) with (H | H) · exact a.inter i H · have I : i = last N := top_le_iff.1 H have := (a.rpos (last N)).le simp only [I, add_nonneg this this, dist_self] theorem hlast' (i : Fin N.succ) (h : 1 ≤ τ) : a.r (last N) ≤ τ * a.r i := by rcases lt_or_le i (last N) with (H | H) · exact (a.hlast i H).2 · have : i = last N := top_le_iff.1 H rw [this] exact le_mul_of_one_le_left (a.rpos _).le h end SatelliteConfig /-! ### Extracting disjoint subfamilies from a ball covering -/ /-- A ball package is a family of balls in a metric space with positive bounded radii. -/ structure BallPackage (β : Type*) (α : Type*) where c : β → α r : β → ℝ rpos : ∀ b, 0 < r b r_bound : ℝ r_le : ∀ b, r b ≤ r_bound /-- The ball package made of unit balls. -/ def unitBallPackage (α : Type*) : BallPackage α α where c := id r _ := 1 rpos _ := zero_lt_one r_bound := 1 r_le _ := le_rfl instance BallPackage.instInhabited (α : Type*) : Inhabited (BallPackage α α) := ⟨unitBallPackage α⟩ /-- A Besicovitch tau-package is a family of balls in a metric space with positive bounded radii, together with enough data to proceed with the Besicovitch greedy algorithm. We register this in a single structure to make sure that all our constructions in this algorithm only depend on one variable. -/ structure TauPackage (β : Type*) (α : Type*) extends BallPackage β α where τ : ℝ one_lt_tau : 1 < τ instance TauPackage.instInhabited (α : Type*) : Inhabited (TauPackage α α) := ⟨{ unitBallPackage α with τ := 2 one_lt_tau := one_lt_two }⟩ variable {α : Type*} [MetricSpace α] {β : Type u} namespace TauPackage variable [Nonempty β] (p : TauPackage β α) /-- Choose inductively large balls with centers that are not contained in the union of already chosen balls. This is a transfinite induction. -/ noncomputable def index : Ordinal.{u} → β | i => -- `Z` is the set of points that are covered by already constructed balls let Z := ⋃ j : { j // j < i }, ball (p.c (index j)) (p.r (index j)) -- `R` is the supremum of the radii of balls with centers not in `Z` let R := iSup fun b : { b : β // p.c b ∉ Z } => p.r b -- return an index `b` for which the center `c b` is not in `Z`, and the radius is at -- least `R / τ`, if such an index exists (and garbage otherwise). Classical.epsilon fun b : β => p.c b ∉ Z ∧ R ≤ p.τ * p.r b termination_by i => i decreasing_by exact j.2 /-- The set of points that are covered by the union of balls selected at steps `< i`. -/ def iUnionUpTo (i : Ordinal.{u}) : Set α := ⋃ j : { j // j < i }, ball (p.c (p.index j)) (p.r (p.index j)) theorem monotone_iUnionUpTo : Monotone p.iUnionUpTo := by intro i j hij simp only [iUnionUpTo] exact iUnion_mono' fun r => ⟨⟨r, r.2.trans_le hij⟩, Subset.rfl⟩ /-- Supremum of the radii of balls whose centers are not yet covered at step `i`. -/ def R (i : Ordinal.{u}) : ℝ := iSup fun b : { b : β // p.c b ∉ p.iUnionUpTo i } => p.r b /-- Group the balls into disjoint families, by assigning to a ball the smallest color for which it does not intersect any already chosen ball of this color. -/ noncomputable def color : Ordinal.{u} → ℕ | i => let A : Set ℕ := ⋃ (j : { j // j < i }) (_ : (closedBall (p.c (p.index j)) (p.r (p.index j)) ∩ closedBall (p.c (p.index i)) (p.r (p.index i))).Nonempty), {color j} sInf (univ \ A) termination_by i => i decreasing_by exact j.2 /-- `p.lastStep` is the first ordinal where the construction stops making sense, i.e., `f` returns garbage since there is no point left to be chosen. We will only use ordinals before this step. -/ def lastStep : Ordinal.{u} := sInf {i | ¬∃ b : β, p.c b ∉ p.iUnionUpTo i ∧ p.R i ≤ p.τ * p.r b} theorem lastStep_nonempty : {i | ¬∃ b : β, p.c b ∉ p.iUnionUpTo i ∧ p.R i ≤ p.τ * p.r b}.Nonempty := by by_contra h suffices H : Function.Injective p.index from not_injective_of_ordinal p.index H intro x y hxy wlog x_le_y : x ≤ y generalizing x y · exact (this hxy.symm (le_of_not_le x_le_y)).symm rcases eq_or_lt_of_le x_le_y with (rfl | H); · rfl simp only [nonempty_def, not_exists, exists_prop, not_and, not_lt, not_le, mem_setOf_eq, not_forall] at h specialize h y have A : p.c (p.index y) ∉ p.iUnionUpTo y := by have : p.index y = Classical.epsilon fun b : β => p.c b ∉ p.iUnionUpTo y ∧ p.R y ≤ p.τ * p.r b := by rw [TauPackage.index]; rfl rw [this] exact (Classical.epsilon_spec h).1 simp only [iUnionUpTo, not_exists, exists_prop, mem_iUnion, mem_closedBall, not_and, not_le, Subtype.exists, Subtype.coe_mk] at A specialize A x H simp? [hxy] at A says simp only [hxy, mem_ball, dist_self, not_lt] at A exact (lt_irrefl _ ((p.rpos (p.index y)).trans_le A)).elim /-- Every point is covered by chosen balls, before `p.lastStep`. -/ theorem mem_iUnionUpTo_lastStep (x : β) : p.c x ∈ p.iUnionUpTo p.lastStep := by have A : ∀ z : β, p.c z ∈ p.iUnionUpTo p.lastStep ∨ p.τ * p.r z < p.R p.lastStep := by have : p.lastStep ∈ {i | ¬∃ b : β, p.c b ∉ p.iUnionUpTo i ∧ p.R i ≤ p.τ * p.r b} := csInf_mem p.lastStep_nonempty simpa only [not_exists, mem_setOf_eq, not_and_or, not_le, not_not_mem] by_contra h rcases A x with (H | H); · exact h H have Rpos : 0 < p.R p.lastStep := by apply lt_trans (mul_pos (_root_.zero_lt_one.trans p.one_lt_tau) (p.rpos _)) H have B : p.τ⁻¹ * p.R p.lastStep < p.R p.lastStep := by conv_rhs => rw [← one_mul (p.R p.lastStep)] exact mul_lt_mul (inv_lt_one p.one_lt_tau) le_rfl Rpos zero_le_one obtain ⟨y, hy1, hy2⟩ : ∃ y, p.c y ∉ p.iUnionUpTo p.lastStep ∧ p.τ⁻¹ * p.R p.lastStep < p.r y := by have := exists_lt_of_lt_csSup ?_ B · simpa only [exists_prop, mem_range, exists_exists_and_eq_and, Subtype.exists, Subtype.coe_mk] rw [← image_univ, image_nonempty] exact ⟨⟨_, h⟩, mem_univ _⟩ rcases A y with (Hy | Hy) · exact hy1 Hy · rw [← div_eq_inv_mul] at hy2 have := (div_le_iff' (_root_.zero_lt_one.trans p.one_lt_tau)).1 hy2.le exact lt_irrefl _ (Hy.trans_le this) /-- If there are no configurations of satellites with `N+1` points, one never uses more than `N` distinct families in the Besicovitch inductive construction. -/ theorem color_lt {i : Ordinal.{u}} (hi : i < p.lastStep) {N : ℕ} (hN : IsEmpty (SatelliteConfig α N p.τ)) : p.color i < N := by /- By contradiction, consider the first ordinal `i` for which one would have `p.color i = N`. Choose for each `k < N` a ball with color `k` that intersects the ball at color `i` (there is such a ball, otherwise one would have used the color `k` and not `N`). Then this family of `N+1` balls forms a satellite configuration, which is forbidden by the assumption `hN`. -/ induction' i using Ordinal.induction with i IH let A : Set ℕ := ⋃ (j : { j // j < i }) (_ : (closedBall (p.c (p.index j)) (p.r (p.index j)) ∩ closedBall (p.c (p.index i)) (p.r (p.index i))).Nonempty), {p.color j} have color_i : p.color i = sInf (univ \ A) := by rw [color] rw [color_i] have N_mem : N ∈ univ \ A := by simp only [A, not_exists, true_and_iff, exists_prop, mem_iUnion, mem_singleton_iff, mem_closedBall, not_and, mem_univ, mem_diff, Subtype.exists, Subtype.coe_mk] intro j ji _ exact (IH j ji (ji.trans hi)).ne' suffices sInf (univ \ A) ≠ N by rcases (csInf_le (OrderBot.bddBelow (univ \ A)) N_mem).lt_or_eq with (H | H) · exact H · exact (this H).elim intro Inf_eq_N have : ∀ k, k < N → ∃ j, j < i ∧ (closedBall (p.c (p.index j)) (p.r (p.index j)) ∩ closedBall (p.c (p.index i)) (p.r (p.index i))).Nonempty ∧ k = p.color j := by intro k hk rw [← Inf_eq_N] at hk have : k ∈ A := by simpa only [true_and_iff, mem_univ, Classical.not_not, mem_diff] using Nat.not_mem_of_lt_sInf hk simp only [mem_iUnion, mem_singleton_iff, exists_prop, Subtype.exists, exists_and_right, and_assoc] at this simpa only [A, exists_prop, mem_iUnion, mem_singleton_iff, mem_closedBall, Subtype.exists, Subtype.coe_mk] choose! g hg using this -- Choose for each `k < N` an ordinal `G k < i` giving a ball of color `k` intersecting -- the last ball. let G : ℕ → Ordinal := fun n => if n = N then i else g n have color_G : ∀ n, n ≤ N → p.color (G n) = n := by intro n hn rcases hn.eq_or_lt with (rfl | H) · simp only [G]; simp only [color_i, Inf_eq_N, if_true, eq_self_iff_true] · simp only [G]; simp only [H.ne, (hg n H).right.right.symm, if_false] have G_lt_last : ∀ n, n ≤ N → G n < p.lastStep := by intro n hn rcases hn.eq_or_lt with (rfl | H) · simp only [G]; simp only [hi, if_true, eq_self_iff_true] · simp only [G]; simp only [H.ne, (hg n H).left.trans hi, if_false] have fGn : ∀ n, n ≤ N → p.c (p.index (G n)) ∉ p.iUnionUpTo (G n) ∧ p.R (G n) ≤ p.τ * p.r (p.index (G n)) := by intro n hn have : p.index (G n) = Classical.epsilon fun t => p.c t ∉ p.iUnionUpTo (G n) ∧ p.R (G n) ≤ p.τ * p.r t := by rw [index]; rfl rw [this] have : ∃ t, p.c t ∉ p.iUnionUpTo (G n) ∧ p.R (G n) ≤ p.τ * p.r t := by simpa only [not_exists, exists_prop, not_and, not_lt, not_le, mem_setOf_eq, not_forall] using not_mem_of_lt_csInf (G_lt_last n hn) (OrderBot.bddBelow _) exact Classical.epsilon_spec this -- the balls with indices `G k` satisfy the characteristic property of satellite configurations. have Gab : ∀ a b : Fin (Nat.succ N), G a < G b → p.r (p.index (G a)) ≤ dist (p.c (p.index (G a))) (p.c (p.index (G b))) ∧ p.r (p.index (G b)) ≤ p.τ * p.r (p.index (G a)) := by intro a b G_lt have ha : (a : ℕ) ≤ N := Nat.lt_succ_iff.1 a.2 have hb : (b : ℕ) ≤ N := Nat.lt_succ_iff.1 b.2 constructor · have := (fGn b hb).1 simp only [iUnionUpTo, not_exists, exists_prop, mem_iUnion, mem_closedBall, not_and, not_le, Subtype.exists, Subtype.coe_mk] at this simpa only [dist_comm, mem_ball, not_lt] using this (G a) G_lt · apply le_trans _ (fGn a ha).2 have B : p.c (p.index (G b)) ∉ p.iUnionUpTo (G a) := by intro H; exact (fGn b hb).1 (p.monotone_iUnionUpTo G_lt.le H) let b' : { t // p.c t ∉ p.iUnionUpTo (G a) } := ⟨p.index (G b), B⟩ apply @le_ciSup _ _ _ (fun t : { t // p.c t ∉ p.iUnionUpTo (G a) } => p.r t) _ b' refine ⟨p.r_bound, fun t ht => ?_⟩ simp only [exists_prop, mem_range, Subtype.exists, Subtype.coe_mk] at ht rcases ht with ⟨u, hu⟩ rw [← hu.2] exact p.r_le _ -- therefore, one may use them to construct a satellite configuration with `N+1` points let sc : SatelliteConfig α N p.τ := { c := fun k => p.c (p.index (G k)) r := fun k => p.r (p.index (G k)) rpos := fun k => p.rpos (p.index (G k)) h := by intro a b a_ne_b wlog G_le : G a ≤ G b generalizing a b · exact (this a_ne_b.symm (le_of_not_le G_le)).symm have G_lt : G a < G b := by rcases G_le.lt_or_eq with (H | H); · exact H have A : (a : ℕ) ≠ b := Fin.val_injective.ne a_ne_b rw [← color_G a (Nat.lt_succ_iff.1 a.2), ← color_G b (Nat.lt_succ_iff.1 b.2), H] at A exact (A rfl).elim exact Or.inl (Gab a b G_lt) hlast := by intro a ha have I : (a : ℕ) < N := ha have : G a < G (Fin.last N) := by dsimp; simp [G, I.ne, (hg a I).1] exact Gab _ _ this inter := by intro a ha have I : (a : ℕ) < N := ha have J : G (Fin.last N) = i := by dsimp; simp only [G, if_true, eq_self_iff_true] have K : G a = g a := by dsimp [G]; simp [I.ne, (hg a I).1] convert dist_le_add_of_nonempty_closedBall_inter_closedBall (hg _ I).2.1 } -- this is a contradiction exact hN.false sc end TauPackage open TauPackage /-- The topological Besicovitch covering theorem: there exist finitely many families of disjoint balls covering all the centers in a package. More specifically, one can use `N` families if there are no satellite configurations with `N+1` points. -/ theorem exist_disjoint_covering_families {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : IsEmpty (SatelliteConfig α N τ)) (q : BallPackage β α) : ∃ s : Fin N → Set β, (∀ i : Fin N, (s i).PairwiseDisjoint fun j => closedBall (q.c j) (q.r j)) ∧ range q.c ⊆ ⋃ i : Fin N, ⋃ j ∈ s i, ball (q.c j) (q.r j) := by -- first exclude the trivial case where `β` is empty (we need non-emptiness for the transfinite -- induction, to be able to choose garbage when there is no point left). cases isEmpty_or_nonempty β · refine ⟨fun _ => ∅, fun _ => pairwiseDisjoint_empty, ?_⟩ rw [← image_univ, eq_empty_of_isEmpty (univ : Set β)] simp -- Now, assume `β` is nonempty. let p : TauPackage β α := { q with τ one_lt_tau := hτ } -- we use for `s i` the balls of color `i`. let s := fun i : Fin N => ⋃ (k : Ordinal.{u}) (_ : k < p.lastStep) (_ : p.color k = i), ({p.index k} : Set β) refine ⟨s, fun i => ?_, ?_⟩ · -- show that balls of the same color are disjoint intro x hx y hy x_ne_y obtain ⟨jx, jx_lt, jxi, rfl⟩ : ∃ jx : Ordinal, jx < p.lastStep ∧ p.color jx = i ∧ x = p.index jx := by simpa only [s, exists_prop, mem_iUnion, mem_singleton_iff] using hx obtain ⟨jy, jy_lt, jyi, rfl⟩ : ∃ jy : Ordinal, jy < p.lastStep ∧ p.color jy = i ∧ y = p.index jy := by simpa only [s, exists_prop, mem_iUnion, mem_singleton_iff] using hy wlog jxy : jx ≤ jy generalizing jx jy · exact (this jy jy_lt jyi hy jx jx_lt jxi hx x_ne_y.symm (le_of_not_le jxy)).symm replace jxy : jx < jy := by rcases lt_or_eq_of_le jxy with (H | rfl); · { exact H }; · { exact (x_ne_y rfl).elim } let A : Set ℕ := ⋃ (j : { j // j < jy }) (_ : (closedBall (p.c (p.index j)) (p.r (p.index j)) ∩ closedBall (p.c (p.index jy)) (p.r (p.index jy))).Nonempty), {p.color j} have color_j : p.color jy = sInf (univ \ A) := by rw [TauPackage.color] have h : p.color jy ∈ univ \ A := by rw [color_j] apply csInf_mem refine ⟨N, ?_⟩ simp only [A, not_exists, true_and_iff, exists_prop, mem_iUnion, mem_singleton_iff, not_and, mem_univ, mem_diff, Subtype.exists, Subtype.coe_mk] intro k hk _ exact (p.color_lt (hk.trans jy_lt) hN).ne' simp only [A, not_exists, true_and_iff, exists_prop, mem_iUnion, mem_singleton_iff, not_and, mem_univ, mem_diff, Subtype.exists, Subtype.coe_mk] at h specialize h jx jxy contrapose! h simpa only [jxi, jyi, and_true_iff, eq_self_iff_true, ← not_disjoint_iff_nonempty_inter] using h · -- show that the balls of color at most `N` cover every center. refine range_subset_iff.2 fun b => ?_ obtain ⟨a, ha⟩ : ∃ a : Ordinal, a < p.lastStep ∧ dist (p.c b) (p.c (p.index a)) < p.r (p.index a) := by simpa only [iUnionUpTo, exists_prop, mem_iUnion, mem_ball, Subtype.exists, Subtype.coe_mk] using p.mem_iUnionUpTo_lastStep b simp only [s, exists_prop, mem_iUnion, mem_ball, mem_singleton_iff, biUnion_and', exists_eq_left, iUnion_exists, exists_and_left] exact ⟨⟨p.color a, p.color_lt ha.1 hN⟩, a, rfl, ha⟩ /-! ### The measurable Besicovitch covering theorem -/ open scoped NNReal variable [SecondCountableTopology α] [MeasurableSpace α] [OpensMeasurableSpace α] /-- Consider, for each `x` in a set `s`, a radius `r x ∈ (0, 1]`. Then one can find finitely many disjoint balls of the form `closedBall x (r x)` covering a proportion `1/(N+1)` of `s`, if there are no satellite configurations with `N+1` points. -/ theorem exist_finset_disjoint_balls_large_measure (μ : Measure α) [IsFiniteMeasure μ] {N : ℕ} {τ : ℝ} (hτ : 1 < τ) (hN : IsEmpty (SatelliteConfig α N τ)) (s : Set α) (r : α → ℝ) (rpos : ∀ x ∈ s, 0 < r x) (rle : ∀ x ∈ s, r x ≤ 1) : ∃ t : Finset α, ↑t ⊆ s ∧ μ (s \ ⋃ x ∈ t, closedBall x (r x)) ≤ N / (N + 1) * μ s ∧ (t : Set α).PairwiseDisjoint fun x => closedBall x (r x) := by -- exclude the trivial case where `μ s = 0`. rcases le_or_lt (μ s) 0 with (hμs | hμs) · have : μ s = 0 := le_bot_iff.1 hμs refine ⟨∅, by simp only [Finset.coe_empty, empty_subset], ?_, ?_⟩ · simp only [this, Finset.not_mem_empty, diff_empty, iUnion_false, iUnion_empty, nonpos_iff_eq_zero, mul_zero] · simp only [Finset.coe_empty, pairwiseDisjoint_empty] cases isEmpty_or_nonempty α · simp only [eq_empty_of_isEmpty s, measure_empty] at hμs exact (lt_irrefl _ hμs).elim have Npos : N ≠ 0 := by rintro rfl inhabit α exact not_isEmpty_of_nonempty _ hN -- introduce a measurable superset `o` with the same measure, for measure computations obtain ⟨o, so, omeas, μo⟩ : ∃ o : Set α, s ⊆ o ∧ MeasurableSet o ∧ μ o = μ s := exists_measurable_superset μ s /- We will apply the topological Besicovitch theorem, giving `N` disjoint subfamilies of balls covering `s`. Among these, one of them covers a proportion at least `1/N` of `s`. A large enough finite subfamily will then cover a proportion at least `1/(N+1)`. -/ let a : BallPackage s α := { c := fun x => x r := fun x => r x rpos := fun x => rpos x x.2 r_bound := 1 r_le := fun x => rle x x.2 } rcases exist_disjoint_covering_families hτ hN a with ⟨u, hu, hu'⟩ have u_count : ∀ i, (u i).Countable := by intro i refine (hu i).countable_of_nonempty_interior fun j _ => ?_ have : (ball (j : α) (r j)).Nonempty := nonempty_ball.2 (a.rpos _) exact this.mono ball_subset_interior_closedBall let v : Fin N → Set α := fun i => ⋃ (x : s) (_ : x ∈ u i), closedBall x (r x) have A : s = ⋃ i : Fin N, s ∩ v i := by refine Subset.antisymm ?_ (iUnion_subset fun i => inter_subset_left) intro x hx obtain ⟨i, y, hxy, h'⟩ : ∃ (i : Fin N) (i_1 : ↥s), i_1 ∈ u i ∧ x ∈ ball (↑i_1) (r ↑i_1) := by have : x ∈ range a.c := by simpa only [Subtype.range_coe_subtype, setOf_mem_eq] simpa only [mem_iUnion, bex_def] using hu' this refine mem_iUnion.2 ⟨i, ⟨hx, ?_⟩⟩ simp only [v, exists_prop, mem_iUnion, SetCoe.exists, exists_and_right, Subtype.coe_mk] exact ⟨y, ⟨y.2, by simpa only [Subtype.coe_eta]⟩, ball_subset_closedBall h'⟩ have S : ∑ _i : Fin N, μ s / N ≤ ∑ i, μ (s ∩ v i) := calc ∑ _i : Fin N, μ s / N = μ s := by simp only [Finset.card_fin, Finset.sum_const, nsmul_eq_mul] rw [ENNReal.mul_div_cancel'] · simp only [Npos, Ne, Nat.cast_eq_zero, not_false_iff] · exact ENNReal.natCast_ne_top _ _ ≤ ∑ i, μ (s ∩ v i) := by conv_lhs => rw [A] apply measure_iUnion_fintype_le -- choose an index `i` of a subfamily covering at least a proportion `1/N` of `s`. obtain ⟨i, -, hi⟩ : ∃ (i : Fin N), i ∈ Finset.univ ∧ μ s / N ≤ μ (s ∩ v i) := by apply ENNReal.exists_le_of_sum_le _ S exact ⟨⟨0, bot_lt_iff_ne_bot.2 Npos⟩, Finset.mem_univ _⟩ replace hi : μ s / (N + 1) < μ (s ∩ v i) := by apply lt_of_lt_of_le _ hi apply (ENNReal.mul_lt_mul_left hμs.ne' (measure_lt_top μ s).ne).2 rw [ENNReal.inv_lt_inv] conv_lhs => rw [← add_zero (N : ℝ≥0∞)] exact ENNReal.add_lt_add_left (ENNReal.natCast_ne_top N) zero_lt_one have B : μ (o ∩ v i) = ∑' x : u i, μ (o ∩ closedBall x (r x)) := by have : o ∩ v i = ⋃ (x : s) (_ : x ∈ u i), o ∩ closedBall x (r x) := by simp only [v, inter_iUnion] rw [this, measure_biUnion (u_count i)] · exact (hu i).mono fun k => inter_subset_right · exact fun b _ => omeas.inter measurableSet_closedBall -- A large enough finite subfamily of `u i` will also cover a proportion `> 1/(N+1)` of `s`. -- Since `s` might not be measurable, we express this in terms of the measurable superset `o`. obtain ⟨w, hw⟩ : ∃ w : Finset (u i), μ s / (N + 1) < ∑ x ∈ w, μ (o ∩ closedBall (x : α) (r (x : α))) := by have C : HasSum (fun x : u i => μ (o ∩ closedBall x (r x))) (μ (o ∩ v i)) := by rw [B]; exact ENNReal.summable.hasSum have : μ s / (N + 1) < μ (o ∩ v i) := hi.trans_le (measure_mono (inter_subset_inter_left _ so)) exact ((tendsto_order.1 C).1 _ this).exists -- Bring back the finset `w i` of `↑(u i)` to a finset of `α`, and check that it works by design. refine ⟨Finset.image (fun x : u i => x) w, ?_, ?_, ?_⟩ -- show that the finset is included in `s`. · simp only [image_subset_iff, Finset.coe_image] intro y _ simp only [Subtype.coe_prop, mem_preimage] -- show that it covers a large enough proportion of `s`. For measure computations, we do not -- use `s` (which might not be measurable), but its measurable superset `o`. Since their measures -- are the same, this does not spoil the estimates · suffices H : μ (o \ ⋃ x ∈ w, closedBall (↑x) (r ↑x)) ≤ N / (N + 1) * μ s by rw [Finset.set_biUnion_finset_image] exact le_trans (measure_mono (diff_subset_diff so (Subset.refl _))) H rw [← diff_inter_self_eq_diff, measure_diff_le_iff_le_add _ inter_subset_right (measure_lt_top μ _).ne] swap · apply MeasurableSet.inter _ omeas haveI : Encodable (u i) := (u_count i).toEncodable exact MeasurableSet.iUnion fun b => MeasurableSet.iUnion fun _ => measurableSet_closedBall calc μ o = 1 / (N + 1) * μ s + N / (N + 1) * μ s := by rw [μo, ← add_mul, ENNReal.div_add_div_same, add_comm, ENNReal.div_self, one_mul] <;> simp _ ≤ μ ((⋃ x ∈ w, closedBall (↑x) (r ↑x)) ∩ o) + N / (N + 1) * μ s := by gcongr rw [one_div, mul_comm, ← div_eq_mul_inv] apply hw.le.trans (le_of_eq _) rw [← Finset.set_biUnion_coe, inter_comm _ o, inter_iUnion₂, Finset.set_biUnion_coe, measure_biUnion_finset] · have : (w : Set (u i)).PairwiseDisjoint fun b : u i => closedBall (b : α) (r (b : α)) := by intro k _ l _ hkl; exact hu i k.2 l.2 (Subtype.val_injective.ne hkl) exact this.mono fun k => inter_subset_right · intro b _ apply omeas.inter measurableSet_closedBall -- show that the balls are disjoint · intro k hk l hl hkl obtain ⟨k', _, rfl⟩ : ∃ k' : u i, k' ∈ w ∧ ↑k' = k := by simpa only [mem_image, Finset.mem_coe, Finset.coe_image] using hk obtain ⟨l', _, rfl⟩ : ∃ l' : u i, l' ∈ w ∧ ↑l' = l := by simpa only [mem_image, Finset.mem_coe, Finset.coe_image] using hl have k'nel' : (k' : s) ≠ l' := by intro h; rw [h] at hkl; exact hkl rfl exact hu i k'.2 l'.2 k'nel' variable [HasBesicovitchCovering α] /-- The **measurable Besicovitch covering theorem**. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version assuming that the measure is sigma-finite, see `exists_disjoint_closedBall_covering_ae_aux`. For a version giving the conclusion in a nicer form, see `exists_disjoint_closedBall_covering_ae`. -/ theorem exists_disjoint_closedBall_covering_ae_of_finiteMeasure_aux (μ : Measure α) [IsFiniteMeasure μ] (f : α → Set ℝ) (s : Set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).Nonempty) : ∃ t : Set (α × ℝ), t.Countable ∧ (∀ p ∈ t, p.1 ∈ s) ∧ (∀ p ∈ t, p.2 ∈ f p.1) ∧ μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ t), closedBall p.1 p.2) = 0 ∧ t.PairwiseDisjoint fun p => closedBall p.1 p.2 := by rcases HasBesicovitchCovering.no_satelliteConfig (α := α) with ⟨N, τ, hτ, hN⟩ /- Introduce a property `P` on finsets saying that we have a nice disjoint covering of a subset of `s` by admissible balls. -/ let P : Finset (α × ℝ) → Prop := fun t => ((t : Set (α × ℝ)).PairwiseDisjoint fun p => closedBall p.1 p.2) ∧ (∀ p : α × ℝ, p ∈ t → p.1 ∈ s) ∧ ∀ p : α × ℝ, p ∈ t → p.2 ∈ f p.1 /- Given a finite good covering of a subset `s`, one can find a larger finite good covering, covering additionally a proportion at least `1/(N+1)` of leftover points. This follows from `exist_finset_disjoint_balls_large_measure` applied to balls not intersecting the initial covering. -/ have : ∀ t : Finset (α × ℝ), P t → ∃ u : Finset (α × ℝ), t ⊆ u ∧ P u ∧ μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ u), closedBall p.1 p.2) ≤ N / (N + 1) * μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ t), closedBall p.1 p.2) := by intro t ht set B := ⋃ (p : α × ℝ) (_ : p ∈ t), closedBall p.1 p.2 with hB have B_closed : IsClosed B := isClosed_biUnion_finset fun i _ => isClosed_ball set s' := s \ B have : ∀ x ∈ s', ∃ r ∈ f x ∩ Ioo 0 1, Disjoint B (closedBall x r) := by intro x hx have xs : x ∈ s := ((mem_diff x).1 hx).1 rcases eq_empty_or_nonempty B with (hB | hB) · rcases hf x xs 1 zero_lt_one with ⟨r, hr, h'r⟩ exact ⟨r, ⟨hr, h'r⟩, by simp only [hB, empty_disjoint]⟩ · let r := infDist x B have : 0 < min r 1 := lt_min ((B_closed.not_mem_iff_infDist_pos hB).1 ((mem_diff x).1 hx).2) zero_lt_one rcases hf x xs _ this with ⟨r, hr, h'r⟩ refine ⟨r, ⟨hr, ⟨h'r.1, h'r.2.trans_le (min_le_right _ _)⟩⟩, ?_⟩ rw [disjoint_comm] exact disjoint_closedBall_of_lt_infDist (h'r.2.trans_le (min_le_left _ _)) choose! r hr using this obtain ⟨v, vs', hμv, hv⟩ : ∃ v : Finset α, ↑v ⊆ s' ∧ μ (s' \ ⋃ x ∈ v, closedBall x (r x)) ≤ N / (N + 1) * μ s' ∧ (v : Set α).PairwiseDisjoint fun x : α => closedBall x (r x) := haveI rI : ∀ x ∈ s', r x ∈ Ioo (0 : ℝ) 1 := fun x hx => (hr x hx).1.2 exist_finset_disjoint_balls_large_measure μ hτ hN s' r (fun x hx => (rI x hx).1) fun x hx => (rI x hx).2.le refine ⟨t ∪ Finset.image (fun x => (x, r x)) v, Finset.subset_union_left, ⟨?_, ?_, ?_⟩, ?_⟩ · simp only [Finset.coe_union, pairwiseDisjoint_union, ht.1, true_and_iff, Finset.coe_image] constructor · intro p hp q hq hpq rcases (mem_image _ _ _).1 hp with ⟨p', p'v, rfl⟩ rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩ refine hv p'v q'v fun hp'q' => ?_ rw [hp'q'] at hpq exact hpq rfl · intro p hp q hq hpq rcases (mem_image _ _ _).1 hq with ⟨q', q'v, rfl⟩ apply disjoint_of_subset_left _ (hr q' (vs' q'v)).2 rw [hB, ← Finset.set_biUnion_coe] exact subset_biUnion_of_mem (u := fun x : α × ℝ => closedBall x.1 x.2) hp · intro p hp rcases Finset.mem_union.1 hp with (h'p | h'p) · exact ht.2.1 p h'p · rcases Finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩ exact ((mem_diff _).1 (vs' (Finset.mem_coe.2 p'v))).1 · intro p hp rcases Finset.mem_union.1 hp with (h'p | h'p) · exact ht.2.2 p h'p · rcases Finset.mem_image.1 h'p with ⟨p', p'v, rfl⟩ exact (hr p' (vs' p'v)).1.1 · convert hμv using 2 rw [Finset.set_biUnion_union, ← diff_diff, Finset.set_biUnion_finset_image] /- Define `F` associating to a finite good covering the above enlarged good covering, covering a proportion `1/(N+1)` of leftover points. Iterating `F`, one will get larger and larger good coverings, missing in the end only a measure-zero set. -/ choose! F hF using this let u n := F^[n] ∅ have u_succ : ∀ n : ℕ, u n.succ = F (u n) := fun n => by simp only [u, Function.comp_apply, Function.iterate_succ'] have Pu : ∀ n, P (u n) := by intro n induction' n with n IH · simp only [P, u, Prod.forall, id, Function.iterate_zero, Nat.zero_eq] simp only [Finset.not_mem_empty, IsEmpty.forall_iff, Finset.coe_empty, forall₂_true_iff, and_self_iff, pairwiseDisjoint_empty] · rw [u_succ] exact (hF (u n) IH).2.1 refine ⟨⋃ n, u n, countable_iUnion fun n => (u n).countable_toSet, ?_, ?_, ?_, ?_⟩ · intro p hp rcases mem_iUnion.1 hp with ⟨n, hn⟩ exact (Pu n).2.1 p (Finset.mem_coe.1 hn) · intro p hp rcases mem_iUnion.1 hp with ⟨n, hn⟩ exact (Pu n).2.2 p (Finset.mem_coe.1 hn) · have A : ∀ n, μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ ⋃ n : ℕ, (u n : Set (α × ℝ))), closedBall p.fst p.snd) ≤ μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ u n), closedBall p.fst p.snd) := by intro n gcongr μ (s \ ?_) exact biUnion_subset_biUnion_left (subset_iUnion (fun i => (u i : Set (α × ℝ))) n) have B : ∀ n, μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ u n), closedBall p.fst p.snd) ≤ (N / (N + 1) : ℝ≥0∞) ^ n * μ s := by intro n induction' n with n IH · simp only [u, le_refl, diff_empty, one_mul, iUnion_false, iUnion_empty, pow_zero, Nat.zero_eq, Function.iterate_zero, id, Finset.not_mem_empty] calc μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ u n.succ), closedBall p.fst p.snd) ≤ N / (N + 1) * μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ u n), closedBall p.fst p.snd) := by rw [u_succ]; exact (hF (u n) (Pu n)).2.2 _ ≤ (N / (N + 1) : ℝ≥0∞) ^ n.succ * μ s := by rw [pow_succ', mul_assoc]; exact mul_le_mul_left' IH _ have C : Tendsto (fun n : ℕ => ((N : ℝ≥0∞) / (N + 1)) ^ n * μ s) atTop (𝓝 (0 * μ s)) := by apply ENNReal.Tendsto.mul_const _ (Or.inr (measure_lt_top μ s).ne) apply ENNReal.tendsto_pow_atTop_nhds_zero_of_lt_one rw [ENNReal.div_lt_iff, one_mul] · conv_lhs => rw [← add_zero (N : ℝ≥0∞)] exact ENNReal.add_lt_add_left (ENNReal.natCast_ne_top N) zero_lt_one · simp only [true_or_iff, add_eq_zero_iff, Ne, not_false_iff, one_ne_zero, and_false_iff] · simp only [ENNReal.natCast_ne_top, Ne, not_false_iff, or_true_iff] rw [zero_mul] at C apply le_bot_iff.1 exact le_of_tendsto_of_tendsto' tendsto_const_nhds C fun n => (A n).trans (B n) · refine (pairwiseDisjoint_iUnion ?_).2 fun n => (Pu n).1 apply (monotone_nat_of_le_succ fun n => ?_).directed_le rw [← Nat.succ_eq_add_one, u_succ] exact (hF (u n) (Pu n)).1 /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). It expresses the conclusion in a slightly awkward form (with a subset of `α × ℝ`) coming from the proof technique. For a version giving the conclusion in a nicer form, see `exists_disjoint_closedBall_covering_ae`. -/ theorem exists_disjoint_closedBall_covering_ae_aux (μ : Measure α) [SFinite μ] (f : α → Set ℝ) (s : Set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).Nonempty) : ∃ t : Set (α × ℝ), t.Countable ∧ (∀ p ∈ t, p.1 ∈ s) ∧ (∀ p ∈ t, p.2 ∈ f p.1) ∧ μ (s \ ⋃ (p : α × ℝ) (_ : p ∈ t), closedBall p.1 p.2) = 0 ∧ t.PairwiseDisjoint fun p => closedBall p.1 p.2 := by /- This is deduced from the finite measure case, by using a finite measure with respect to which the initial sigma-finite measure is absolutely continuous. -/ rcases exists_absolutelyContinuous_isFiniteMeasure μ with ⟨ν, hν, hμν⟩ rcases exists_disjoint_closedBall_covering_ae_of_finiteMeasure_aux ν f s hf with ⟨t, t_count, ts, tr, tν, tdisj⟩ exact ⟨t, t_count, ts, tr, hμν tν, tdisj⟩ /-- The measurable Besicovitch covering theorem. Assume that, for any `x` in a set `s`, one is given a set of admissible closed balls centered at `x`, with arbitrarily small radii. Then there exists a disjoint covering of almost all `s` by admissible closed balls centered at some points of `s`. We can even require that the radius at `x` is bounded by a given function `R x`. (Take `R = 1` if you don't need this additional feature). This version requires that the underlying measure is sigma-finite, and that the space has the Besicovitch covering property (which is satisfied for instance by normed real vector spaces). -/ theorem exists_disjoint_closedBall_covering_ae (μ : Measure α) [SFinite μ] (f : α → Set ℝ) (s : Set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).Nonempty) (R : α → ℝ) (hR : ∀ x ∈ s, 0 < R x) : ∃ (t : Set α) (r : α → ℝ), t.Countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x ∩ Ioo 0 (R x)) ∧ μ (s \ ⋃ x ∈ t, closedBall x (r x)) = 0 ∧ t.PairwiseDisjoint fun x => closedBall x (r x) := by let g x := f x ∩ Ioo 0 (R x) have hg : ∀ x ∈ s, ∀ δ > 0, (g x ∩ Ioo 0 δ).Nonempty := fun x hx δ δpos ↦ by rcases hf x hx (min δ (R x)) (lt_min δpos (hR x hx)) with ⟨r, hr⟩ exact ⟨r, ⟨⟨hr.1, hr.2.1, hr.2.2.trans_le (min_le_right _ _)⟩, ⟨hr.2.1, hr.2.2.trans_le (min_le_left _ _)⟩⟩⟩ rcases exists_disjoint_closedBall_covering_ae_aux μ g s hg with ⟨v, v_count, vs, vg, μv, v_disj⟩ obtain ⟨r, t, rfl⟩ : ∃ (r : α → ℝ) (t : Set α), v = graphOn r t := by have I : ∀ p ∈ v, 0 ≤ p.2 := fun p hp => (vg p hp).2.1.le rw [exists_eq_graphOn] refine fun x hx y hy heq ↦ v_disj.eq hx hy <| not_disjoint_iff.2 ⟨x.1, ?_⟩ simp [*] have hinj : InjOn (fun x ↦ (x, r x)) t := LeftInvOn.injOn (f₁' := Prod.fst) fun _ _ ↦ rfl simp only [graphOn, forall_mem_image, biUnion_image, hinj.pairwiseDisjoint_image] at * exact ⟨t, r, countable_of_injective_of_countable_image hinj v_count, vs, vg, μv, v_disj⟩ /-- In a space with the Besicovitch property, any set `s` can be covered with balls whose measures add up to at most `μ s + ε`, for any positive `ε`. This works even if one restricts the set of allowed radii around a point `x` to a set `f x` which accumulates at `0`. -/ theorem exists_closedBall_covering_tsum_measure_le (μ : Measure α) [SFinite μ] [Measure.OuterRegular μ] {ε : ℝ≥0∞} (hε : ε ≠ 0) (f : α → Set ℝ) (s : Set α) (hf : ∀ x ∈ s, ∀ δ > 0, (f x ∩ Ioo 0 δ).Nonempty) : ∃ (t : Set α) (r : α → ℝ), t.Countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ f x) ∧ (s ⊆ ⋃ x ∈ t, closedBall x (r x)) ∧ (∑' x : t, μ (closedBall x (r x))) ≤ μ s + ε := by /- For the proof, first cover almost all `s` with disjoint balls thanks to the usual Besicovitch theorem. Taking the balls included in a well-chosen open neighborhood `u` of `s`, one may ensure that their measures add at most to `μ s + ε / 2`. Let `s'` be the remaining set, of measure `0`. Applying the other version of Besicovitch, one may cover it with at most `N` disjoint subfamilies. Making sure that they are all included in a neighborhood `v` of `s'` of measure at most `ε / (2 N)`, the sum of their measures is at most `ε / 2`, completing the proof. -/ obtain ⟨u, su, u_open, μu⟩ : ∃ U, U ⊇ s ∧ IsOpen U ∧ μ U ≤ μ s + ε / 2 := Set.exists_isOpen_le_add _ _ (by simpa only [or_false, Ne, ENNReal.div_eq_zero_iff, ENNReal.two_ne_top] using hε) have : ∀ x ∈ s, ∃ R > 0, ball x R ⊆ u := fun x hx => Metric.mem_nhds_iff.1 (u_open.mem_nhds (su hx)) choose! R hR using this obtain ⟨t0, r0, t0_count, t0s, hr0, μt0, t0_disj⟩ : ∃ (t0 : Set α) (r0 : α → ℝ), t0.Countable ∧ t0 ⊆ s ∧ (∀ x ∈ t0, r0 x ∈ f x ∩ Ioo 0 (R x)) ∧ μ (s \ ⋃ x ∈ t0, closedBall x (r0 x)) = 0 ∧ t0.PairwiseDisjoint fun x => closedBall x (r0 x) := exists_disjoint_closedBall_covering_ae μ f s hf R fun x hx => (hR x hx).1 -- we have constructed an almost everywhere covering of `s` by disjoint balls. Let `s'` be the -- remaining set. let s' := s \ ⋃ x ∈ t0, closedBall x (r0 x) have s's : s' ⊆ s := diff_subset obtain ⟨N, τ, hτ, H⟩ : ∃ N τ, 1 < τ ∧ IsEmpty (Besicovitch.SatelliteConfig α N τ) := HasBesicovitchCovering.no_satelliteConfig obtain ⟨v, s'v, v_open, μv⟩ : ∃ v, v ⊇ s' ∧ IsOpen v ∧ μ v ≤ μ s' + ε / 2 / N := Set.exists_isOpen_le_add _ _ (by simp only [ne_eq, ENNReal.div_eq_zero_iff, hε, ENNReal.two_ne_top, or_self, ENNReal.natCast_ne_top, not_false_eq_true]) have : ∀ x ∈ s', ∃ r1 ∈ f x ∩ Ioo (0 : ℝ) 1, closedBall x r1 ⊆ v := by intro x hx rcases Metric.mem_nhds_iff.1 (v_open.mem_nhds (s'v hx)) with ⟨r, rpos, hr⟩ rcases hf x (s's hx) (min r 1) (lt_min rpos zero_lt_one) with ⟨R', hR'⟩ exact ⟨R', ⟨hR'.1, hR'.2.1, hR'.2.2.trans_le (min_le_right _ _)⟩, Subset.trans (closedBall_subset_ball (hR'.2.2.trans_le (min_le_left _ _))) hr⟩ choose! r1 hr1 using this let q : BallPackage s' α := { c := fun x => x r := fun x => r1 x rpos := fun x => (hr1 x.1 x.2).1.2.1 r_bound := 1 r_le := fun x => (hr1 x.1 x.2).1.2.2.le } -- by Besicovitch, we cover `s'` with at most `N` families of disjoint balls, all included in -- a suitable neighborhood `v` of `s'`. obtain ⟨S, S_disj, hS⟩ : ∃ S : Fin N → Set s', (∀ i : Fin N, (S i).PairwiseDisjoint fun j => closedBall (q.c j) (q.r j)) ∧ range q.c ⊆ ⋃ i : Fin N, ⋃ j ∈ S i, ball (q.c j) (q.r j) := exist_disjoint_covering_families hτ H q have S_count : ∀ i, (S i).Countable := by intro i apply (S_disj i).countable_of_nonempty_interior fun j _ => ?_ have : (ball (j : α) (r1 j)).Nonempty := nonempty_ball.2 (q.rpos _) exact this.mono ball_subset_interior_closedBall let r x := if x ∈ s' then r1 x else r0 x have r_t0 : ∀ x ∈ t0, r x = r0 x := by intro x hx have : ¬x ∈ s' := by simp only [s', not_exists, exists_prop, mem_iUnion, mem_closedBall, not_and, not_lt, not_le, mem_diff, not_forall] intro _ refine ⟨x, hx, ?_⟩ rw [dist_self] exact (hr0 x hx).2.1.le simp only [r, if_neg this] -- the desired covering set is given by the union of the families constructed in the first and -- second steps. refine ⟨t0 ∪ ⋃ i : Fin N, ((↑) : s' → α) '' S i, r, ?_, ?_, ?_, ?_, ?_⟩ -- it remains to check that they have the desired properties · exact t0_count.union (countable_iUnion fun i => (S_count i).image _) · simp only [t0s, true_and_iff, union_subset_iff, image_subset_iff, iUnion_subset_iff] intro i x _ exact s's x.2 · intro x hx cases hx with | inl hx => rw [r_t0 x hx] exact (hr0 _ hx).1 | inr hx => have h'x : x ∈ s' := by simp only [mem_iUnion, mem_image] at hx rcases hx with ⟨i, y, _, rfl⟩ exact y.2 simp only [r, if_pos h'x, (hr1 x h'x).1.1] · intro x hx by_cases h'x : x ∈ s' · obtain ⟨i, y, ySi, xy⟩ : ∃ (i : Fin N) (y : ↥s'), y ∈ S i ∧ x ∈ ball (y : α) (r1 y) := by have A : x ∈ range q.c := by simpa only [not_exists, exists_prop, mem_iUnion, mem_closedBall, not_and, not_le, mem_setOf_eq, Subtype.range_coe_subtype, mem_diff] using h'x simpa only [mem_iUnion, mem_image, bex_def] using hS A refine mem_iUnion₂.2 ⟨y, Or.inr ?_, ?_⟩ · simp only [mem_iUnion, mem_image] exact ⟨i, y, ySi, rfl⟩ · have : (y : α) ∈ s' := y.2 simp only [r, if_pos this] exact ball_subset_closedBall xy · obtain ⟨y, yt0, hxy⟩ : ∃ y : α, y ∈ t0 ∧ x ∈ closedBall y (r0 y) := by simpa [s', hx, -mem_closedBall] using h'x refine mem_iUnion₂.2 ⟨y, Or.inl yt0, ?_⟩ rwa [r_t0 _ yt0] -- the only nontrivial property is the measure control, which we check now · -- the sets in the first step have measure at most `μ s + ε / 2` have A : (∑' x : t0, μ (closedBall x (r x))) ≤ μ s + ε / 2 := calc (∑' x : t0, μ (closedBall x (r x))) = ∑' x : t0, μ (closedBall x (r0 x)) := by congr 1; ext x; rw [r_t0 x x.2] _ = μ (⋃ x : t0, closedBall x (r0 x)) := by haveI : Encodable t0 := t0_count.toEncodable rw [measure_iUnion] · exact (pairwise_subtype_iff_pairwise_set _ _).2 t0_disj · exact fun i => measurableSet_closedBall _ ≤ μ u := by apply measure_mono simp only [SetCoe.forall, Subtype.coe_mk, iUnion_subset_iff] intro x hx apply Subset.trans (closedBall_subset_ball (hr0 x hx).2.2) (hR x (t0s hx)).2 _ ≤ μ s + ε / 2 := μu -- each subfamily in the second step has measure at most `ε / (2 N)`. have B : ∀ i : Fin N, (∑' x : ((↑) : s' → α) '' S i, μ (closedBall x (r x))) ≤ ε / 2 / N := fun i => calc (∑' x : ((↑) : s' → α) '' S i, μ (closedBall x (r x))) = ∑' x : S i, μ (closedBall x (r x)) := by have : InjOn ((↑) : s' → α) (S i) := Subtype.val_injective.injOn let F : S i ≃ ((↑) : s' → α) '' S i := this.bijOn_image.equiv _ exact (F.tsum_eq fun x => μ (closedBall x (r x))).symm _ = ∑' x : S i, μ (closedBall x (r1 x)) := by congr 1; ext x; have : (x : α) ∈ s' := x.1.2; simp only [s', r, if_pos this] _ = μ (⋃ x : S i, closedBall x (r1 x)) := by haveI : Encodable (S i) := (S_count i).toEncodable rw [measure_iUnion] · exact (pairwise_subtype_iff_pairwise_set _ _).2 (S_disj i) · exact fun i => measurableSet_closedBall _ ≤ μ v := by apply measure_mono simp only [SetCoe.forall, Subtype.coe_mk, iUnion_subset_iff] intro x xs' _ exact (hr1 x xs').2 _ ≤ ε / 2 / N := by have : μ s' = 0 := μt0; rwa [this, zero_add] at μv -- add up all these to prove the desired estimate calc (∑' x : ↥(t0 ∪ ⋃ i : Fin N, ((↑) : s' → α) '' S i), μ (closedBall x (r x))) ≤ (∑' x : t0, μ (closedBall x (r x))) + ∑' x : ⋃ i : Fin N, ((↑) : s' → α) '' S i, μ (closedBall x (r x)) := ENNReal.tsum_union_le (fun x => μ (closedBall x (r x))) _ _ _ ≤ (∑' x : t0, μ (closedBall x (r x))) + ∑ i : Fin N, ∑' x : ((↑) : s' → α) '' S i, μ (closedBall x (r x)) := (add_le_add le_rfl (ENNReal.tsum_iUnion_le (fun x => μ (closedBall x (r x))) _)) _ ≤ μ s + ε / 2 + ∑ i : Fin N, ε / 2 / N := by gcongr apply B _ ≤ μ s + ε / 2 + ε / 2 := by gcongr simp only [Finset.card_fin, Finset.sum_const, nsmul_eq_mul, ENNReal.mul_div_le] _ = μ s + ε := by rw [add_assoc, ENNReal.add_halves] /-! ### Consequences on differentiation of measures -/ /-- In a space with the Besicovitch covering property, the set of closed balls with positive radius forms a Vitali family. This is essentially a restatement of the measurable Besicovitch theorem. -/ protected def vitaliFamily (μ : Measure α) [SFinite μ] : VitaliFamily μ where setsAt x := (fun r : ℝ => closedBall x r) '' Ioi (0 : ℝ) measurableSet _ := forall_mem_image.2 fun _ _ ↦ isClosed_ball.measurableSet nonempty_interior _ := forall_mem_image.2 fun r rpos ↦ (nonempty_ball.2 rpos).mono ball_subset_interior_closedBall nontrivial x ε εpos := ⟨closedBall x ε, mem_image_of_mem _ εpos, Subset.rfl⟩ covering := by intro s f fsubset ffine let g : α → Set ℝ := fun x => {r | 0 < r ∧ closedBall x r ∈ f x} have A : ∀ x ∈ s, ∀ δ > 0, (g x ∩ Ioo 0 δ).Nonempty := by intro x xs δ δpos obtain ⟨t, tf, ht⟩ : ∃ (t : Set α), t ∈ f x ∧ t ⊆ closedBall x (δ / 2) := ffine x xs (δ / 2) (half_pos δpos) obtain ⟨r, rpos, rfl⟩ : ∃ r : ℝ, 0 < r ∧ closedBall x r = t := by simpa using fsubset x xs tf rcases le_total r (δ / 2) with (H | H) · exact ⟨r, ⟨rpos, tf⟩, ⟨rpos, H.trans_lt (half_lt_self δpos)⟩⟩ · have : closedBall x r = closedBall x (δ / 2) := Subset.antisymm ht (closedBall_subset_closedBall H) rw [this] at tf exact ⟨δ / 2, ⟨half_pos δpos, tf⟩, ⟨half_pos δpos, half_lt_self δpos⟩⟩ obtain ⟨t, r, _, ts, tg, μt, tdisj⟩ : ∃ (t : Set α) (r : α → ℝ), t.Countable ∧ t ⊆ s ∧ (∀ x ∈ t, r x ∈ g x ∩ Ioo 0 1) ∧ μ (s \ ⋃ x ∈ t, closedBall x (r x)) = 0 ∧ t.PairwiseDisjoint fun x => closedBall x (r x) := exists_disjoint_closedBall_covering_ae μ g s A (fun _ => 1) fun _ _ => zero_lt_one let F : α → α × Set α := fun x => (x, closedBall x (r x)) refine ⟨F '' t, ?_, ?_, ?_, ?_⟩ · rintro - ⟨x, hx, rfl⟩; exact ts hx · rintro p ⟨x, hx, rfl⟩ q ⟨y, hy, rfl⟩ hxy exact tdisj hx hy (ne_of_apply_ne F hxy) · rintro - ⟨x, hx, rfl⟩; exact (tg x hx).1.2 · rwa [biUnion_image] /-- The main feature of the Besicovitch Vitali family is that its filter at a point `x` corresponds to convergence along closed balls. We record one of the two implications here, which will enable us to deduce specific statements on differentiation of measures in this context from the general versions. -/ theorem tendsto_filterAt (μ : Measure α) [SFinite μ] (x : α) : Tendsto (fun r => closedBall x r) (𝓝[>] 0) ((Besicovitch.vitaliFamily μ).filterAt x) := by intro s hs simp only [mem_map] obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ), ε > 0 ∧ ∀ a : Set α, a ∈ (Besicovitch.vitaliFamily μ).setsAt x → a ⊆ closedBall x ε → a ∈ s := (VitaliFamily.mem_filterAt_iff _).1 hs have : Ioc (0 : ℝ) ε ∈ 𝓝[>] (0 : ℝ) := Ioc_mem_nhdsWithin_Ioi ⟨le_rfl, εpos⟩ filter_upwards [this] with _ hr apply hε · exact mem_image_of_mem _ hr.1 · exact closedBall_subset_closedBall hr.2 variable [MetricSpace β] [MeasurableSpace β] [BorelSpace β] [SecondCountableTopology β] [HasBesicovitchCovering β] /-- In a space with the Besicovitch covering property, the ratio of the measure of balls converges almost surely to the Radon-Nikodym derivative. -/ theorem ae_tendsto_rnDeriv (ρ μ : Measure β) [IsLocallyFiniteMeasure μ] [IsLocallyFiniteMeasure ρ] : ∀ᵐ x ∂μ, Tendsto (fun r => ρ (closedBall x r) / μ (closedBall x r)) (𝓝[>] 0) (𝓝 (ρ.rnDeriv μ x)) := by filter_upwards [VitaliFamily.ae_tendsto_rnDeriv (Besicovitch.vitaliFamily μ) ρ] with x hx exact hx.comp (tendsto_filterAt μ x) /-- Given a measurable set `s`, then `μ (s ∩ closedBall x r) / μ (closedBall x r)` converges when `r` tends to `0`, for almost every `x`. The limit is `1` for `x ∈ s` and `0` for `x ∉ s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A version for non-measurable sets holds, but it only gives the first conclusion, see `ae_tendsto_measure_inter_div`. -/ theorem ae_tendsto_measure_inter_div_of_measurableSet (μ : Measure β) [IsLocallyFiniteMeasure μ] {s : Set β} (hs : MeasurableSet s) : ∀ᵐ x ∂μ, Tendsto (fun r => μ (s ∩ closedBall x r) / μ (closedBall x r)) (𝓝[>] 0) (𝓝 (s.indicator 1 x)) := by filter_upwards [VitaliFamily.ae_tendsto_measure_inter_div_of_measurableSet (Besicovitch.vitaliFamily μ) hs] intro x hx exact hx.comp (tendsto_filterAt μ x) /-- Given an arbitrary set `s`, then `μ (s ∩ closedBall x r) / μ (closedBall x r)` converges to `1` when `r` tends to `0`, for almost every `x` in `s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A stronger version holds for measurable sets, see `ae_tendsto_measure_inter_div_of_measurableSet`. See also `IsUnifLocDoublingMeasure.ae_tendsto_measure_inter_div`. -/ theorem ae_tendsto_measure_inter_div (μ : Measure β) [IsLocallyFiniteMeasure μ] (s : Set β) : ∀ᵐ x ∂μ.restrict s, Tendsto (fun r => μ (s ∩ closedBall x r) / μ (closedBall x r)) (𝓝[>] 0) (𝓝 1) := by filter_upwards [VitaliFamily.ae_tendsto_measure_inter_div (Besicovitch.vitaliFamily μ) s] with x hx using hx.comp (tendsto_filterAt μ x) end Besicovitch
MeasureTheory\Covering\BesicovitchVectorSpace.lean
/- Copyright (c) 2021 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.MeasureTheory.Measure.Lebesgue.EqHaar import Mathlib.MeasureTheory.Covering.Besicovitch import Mathlib.Tactic.AdaptationNote /-! # Satellite configurations for Besicovitch covering lemma in vector spaces The Besicovitch covering theorem ensures that, in a nice metric space, there exists a number `N` such that, from any family of balls with bounded radii, one can extract `N` families, each made of disjoint balls, covering together all the centers of the initial family. A key tool in the proof of this theorem is the notion of a satellite configuration, i.e., a family of `N + 1` balls, where the first `N` balls all intersect the last one, but none of them contains the center of another one and their radii are controlled. This is a technical notion, but it shows up naturally in the proof of the Besicovitch theorem (which goes through a greedy algorithm): to ensure that in the end one needs at most `N` families of balls, the crucial property of the underlying metric space is that there should be no satellite configuration of `N + 1` points. This file is devoted to the study of this property in vector spaces: we prove the main result of [Füredi and Loeb, On the best constant for the Besicovitch covering theorem][furedi-loeb1994], which shows that the optimal such `N` in a vector space coincides with the maximal number of points one can put inside the unit ball of radius `2` under the condition that their distances are bounded below by `1`. In particular, this number is bounded by `5 ^ dim` by a straightforward measure argument. ## Main definitions and results * `multiplicity E` is the maximal number of points one can put inside the unit ball of radius `2` in the vector space `E`, under the condition that their distances are bounded below by `1`. * `multiplicity_le E` shows that `multiplicity E ≤ 5 ^ (dim E)`. * `good_τ E` is a constant `> 1`, but close enough to `1` that satellite configurations with this parameter `τ` are not worst than for `τ = 1`. * `isEmpty_satelliteConfig_multiplicity` is the main theorem, saying that there are no satellite configurations of `(multiplicity E) + 1` points, for the parameter `goodτ E`. -/ universe u open Metric Set FiniteDimensional MeasureTheory Filter Fin open scoped ENNReal Topology noncomputable section namespace Besicovitch variable {E : Type*} [NormedAddCommGroup E] namespace SatelliteConfig variable [NormedSpace ℝ E] {N : ℕ} {τ : ℝ} (a : SatelliteConfig E N τ) /-- Rescaling a satellite configuration in a vector space, to put the basepoint at `0` and the base radius at `1`. -/ def centerAndRescale : SatelliteConfig E N τ where c i := (a.r (last N))⁻¹ • (a.c i - a.c (last N)) r i := (a.r (last N))⁻¹ * a.r i rpos i := by positivity h i j hij := by simp (disch := positivity) only [dist_smul₀, dist_sub_right, mul_left_comm τ, Real.norm_of_nonneg] rcases a.h hij with (⟨H₁, H₂⟩ | ⟨H₁, H₂⟩) <;> [left; right] <;> constructor <;> gcongr hlast i hi := by simp (disch := positivity) only [dist_smul₀, dist_sub_right, mul_left_comm τ, Real.norm_of_nonneg] have ⟨H₁, H₂⟩ := a.hlast i hi constructor <;> gcongr inter i hi := by simp (disch := positivity) only [dist_smul₀, ← mul_add, dist_sub_right, Real.norm_of_nonneg] gcongr exact a.inter i hi theorem centerAndRescale_center : a.centerAndRescale.c (last N) = 0 := by simp [SatelliteConfig.centerAndRescale] theorem centerAndRescale_radius {N : ℕ} {τ : ℝ} (a : SatelliteConfig E N τ) : a.centerAndRescale.r (last N) = 1 := by simp [SatelliteConfig.centerAndRescale, inv_mul_cancel (a.rpos _).ne'] end SatelliteConfig /-! ### Disjoint balls of radius close to `1` in the radius `2` ball. -/ /-- The maximum cardinality of a `1`-separated set in the ball of radius `2`. This is also the optimal number of families in the Besicovitch covering theorem. -/ def multiplicity (E : Type*) [NormedAddCommGroup E] := sSup {N | ∃ s : Finset E, s.card = N ∧ (∀ c ∈ s, ‖c‖ ≤ 2) ∧ ∀ c ∈ s, ∀ d ∈ s, c ≠ d → 1 ≤ ‖c - d‖} section variable [NormedSpace ℝ E] [FiniteDimensional ℝ E] /-- Any `1`-separated set in the ball of radius `2` has cardinality at most `5 ^ dim`. This is useful to show that the supremum in the definition of `Besicovitch.multiplicity E` is well behaved. -/ theorem card_le_of_separated (s : Finset E) (hs : ∀ c ∈ s, ‖c‖ ≤ 2) (h : ∀ c ∈ s, ∀ d ∈ s, c ≠ d → 1 ≤ ‖c - d‖) : s.card ≤ 5 ^ finrank ℝ E := by /- We consider balls of radius `1/2` around the points in `s`. They are disjoint, and all contained in the ball of radius `5/2`. A volume argument gives `s.card * (1/2)^dim ≤ (5/2)^dim`, i.e., `s.card ≤ 5^dim`. -/ borelize E let μ : Measure E := Measure.addHaar let δ : ℝ := (1 : ℝ) / 2 let ρ : ℝ := (5 : ℝ) / 2 have ρpos : 0 < ρ := by norm_num set A := ⋃ c ∈ s, ball (c : E) δ with hA have D : Set.Pairwise (s : Set E) (Disjoint on fun c => ball (c : E) δ) := by rintro c hc d hd hcd apply ball_disjoint_ball rw [dist_eq_norm] convert h c hc d hd hcd norm_num have A_subset : A ⊆ ball (0 : E) ρ := by refine iUnion₂_subset fun x hx => ?_ apply ball_subset_ball' calc δ + dist x 0 ≤ δ + 2 := by rw [dist_zero_right]; exact add_le_add le_rfl (hs x hx) _ = 5 / 2 := by norm_num have I : (s.card : ℝ≥0∞) * ENNReal.ofReal (δ ^ finrank ℝ E) * μ (ball 0 1) ≤ ENNReal.ofReal (ρ ^ finrank ℝ E) * μ (ball 0 1) := calc (s.card : ℝ≥0∞) * ENNReal.ofReal (δ ^ finrank ℝ E) * μ (ball 0 1) = μ A := by rw [hA, measure_biUnion_finset D fun c _ => measurableSet_ball] have I : 0 < δ := by norm_num simp only [div_pow, μ.addHaar_ball_of_pos _ I] simp only [one_div, one_pow, Finset.sum_const, nsmul_eq_mul, mul_assoc] _ ≤ μ (ball (0 : E) ρ) := measure_mono A_subset _ = ENNReal.ofReal (ρ ^ finrank ℝ E) * μ (ball 0 1) := by simp only [μ.addHaar_ball_of_pos _ ρpos] have J : (s.card : ℝ≥0∞) * ENNReal.ofReal (δ ^ finrank ℝ E) ≤ ENNReal.ofReal (ρ ^ finrank ℝ E) := (ENNReal.mul_le_mul_right (measure_ball_pos _ _ zero_lt_one).ne' measure_ball_lt_top.ne).1 I have K : (s.card : ℝ) ≤ (5 : ℝ) ^ finrank ℝ E := by have := ENNReal.toReal_le_of_le_ofReal (pow_nonneg ρpos.le _) J simpa [ρ, δ, div_eq_mul_inv, mul_pow] using this exact mod_cast K theorem multiplicity_le : multiplicity E ≤ 5 ^ finrank ℝ E := by apply csSup_le · refine ⟨0, ⟨∅, by simp⟩⟩ · rintro _ ⟨s, ⟨rfl, h⟩⟩ exact Besicovitch.card_le_of_separated s h.1 h.2 theorem card_le_multiplicity {s : Finset E} (hs : ∀ c ∈ s, ‖c‖ ≤ 2) (h's : ∀ c ∈ s, ∀ d ∈ s, c ≠ d → 1 ≤ ‖c - d‖) : s.card ≤ multiplicity E := by apply le_csSup · refine ⟨5 ^ finrank ℝ E, ?_⟩ rintro _ ⟨s, ⟨rfl, h⟩⟩ exact Besicovitch.card_le_of_separated s h.1 h.2 · simp only [mem_setOf_eq, Ne] exact ⟨s, rfl, hs, h's⟩ variable (E) /-- If `δ` is small enough, a `(1-δ)`-separated set in the ball of radius `2` also has cardinality at most `multiplicity E`. -/ theorem exists_goodδ : ∃ δ : ℝ, 0 < δ ∧ δ < 1 ∧ ∀ s : Finset E, (∀ c ∈ s, ‖c‖ ≤ 2) → (∀ c ∈ s, ∀ d ∈ s, c ≠ d → 1 - δ ≤ ‖c - d‖) → s.card ≤ multiplicity E := by classical /- This follows from a compactness argument: otherwise, one could extract a converging subsequence, to obtain a `1`-separated set in the ball of radius `2` with cardinality `N = multiplicity E + 1`. To formalize this, we work with functions `Fin N → E`. -/ by_contra! h set N := multiplicity E + 1 with hN have : ∀ δ : ℝ, 0 < δ → ∃ f : Fin N → E, (∀ i : Fin N, ‖f i‖ ≤ 2) ∧ Pairwise fun i j => 1 - δ ≤ ‖f i - f j‖ := by intro δ hδ rcases lt_or_le δ 1 with (hδ' | hδ') · rcases h δ hδ hδ' with ⟨s, hs, h's, s_card⟩ obtain ⟨f, f_inj, hfs⟩ : ∃ f : Fin N → E, Function.Injective f ∧ range f ⊆ ↑s := by have : Fintype.card (Fin N) ≤ s.card := by simp only [Fintype.card_fin]; exact s_card rcases Function.Embedding.exists_of_card_le_finset this with ⟨f, hf⟩ exact ⟨f, f.injective, hf⟩ simp only [range_subset_iff, Finset.mem_coe] at hfs exact ⟨f, fun i => hs _ (hfs i), fun i j hij => h's _ (hfs i) _ (hfs j) (f_inj.ne hij)⟩ · exact ⟨fun _ => 0, by simp, fun i j _ => by simpa only [norm_zero, sub_nonpos, sub_self]⟩ -- For `δ > 0`, `F δ` is a function from `Fin N` to the ball of radius `2` for which two points -- in the image are separated by `1 - δ`. choose! F hF using this -- Choose a converging subsequence when `δ → 0`. have : ∃ f : Fin N → E, (∀ i : Fin N, ‖f i‖ ≤ 2) ∧ Pairwise fun i j => 1 ≤ ‖f i - f j‖ := by obtain ⟨u, _, zero_lt_u, hu⟩ : ∃ u : ℕ → ℝ, (∀ m n : ℕ, m < n → u n < u m) ∧ (∀ n : ℕ, 0 < u n) ∧ Filter.Tendsto u Filter.atTop (𝓝 0) := exists_seq_strictAnti_tendsto (0 : ℝ) have A : ∀ n, F (u n) ∈ closedBall (0 : Fin N → E) 2 := by intro n simp only [pi_norm_le_iff_of_nonneg zero_le_two, mem_closedBall, dist_zero_right, (hF (u n) (zero_lt_u n)).left, forall_const] obtain ⟨f, fmem, φ, φ_mono, hf⟩ : ∃ f ∈ closedBall (0 : Fin N → E) 2, ∃ φ : ℕ → ℕ, StrictMono φ ∧ Tendsto ((F ∘ u) ∘ φ) atTop (𝓝 f) := IsCompact.tendsto_subseq (isCompact_closedBall _ _) A refine ⟨f, fun i => ?_, fun i j hij => ?_⟩ · simp only [pi_norm_le_iff_of_nonneg zero_le_two, mem_closedBall, dist_zero_right] at fmem exact fmem i · have A : Tendsto (fun n => ‖F (u (φ n)) i - F (u (φ n)) j‖) atTop (𝓝 ‖f i - f j‖) := ((hf.apply_nhds i).sub (hf.apply_nhds j)).norm have B : Tendsto (fun n => 1 - u (φ n)) atTop (𝓝 (1 - 0)) := tendsto_const_nhds.sub (hu.comp φ_mono.tendsto_atTop) rw [sub_zero] at B exact le_of_tendsto_of_tendsto' B A fun n => (hF (u (φ n)) (zero_lt_u _)).2 hij rcases this with ⟨f, hf, h'f⟩ -- the range of `f` contradicts the definition of `multiplicity E`. have finj : Function.Injective f := by intro i j hij by_contra h have : 1 ≤ ‖f i - f j‖ := h'f h simp only [hij, norm_zero, sub_self] at this exact lt_irrefl _ (this.trans_lt zero_lt_one) let s := Finset.image f Finset.univ have s_card : s.card = N := by rw [Finset.card_image_of_injective _ finj]; exact Finset.card_fin N have hs : ∀ c ∈ s, ‖c‖ ≤ 2 := by simp only [s, hf, forall_apply_eq_imp_iff, forall_const, forall_exists_index, Finset.mem_univ, Finset.mem_image, true_and] have h's : ∀ c ∈ s, ∀ d ∈ s, c ≠ d → 1 ≤ ‖c - d‖ := by simp only [s, forall_apply_eq_imp_iff, forall_exists_index, Finset.mem_univ, Finset.mem_image, Ne, exists_true_left, forall_apply_eq_imp_iff, forall_true_left, true_and] intro i j hij have : i ≠ j := fun h => by rw [h] at hij; exact hij rfl exact h'f this have : s.card ≤ multiplicity E := card_le_multiplicity hs h's rw [s_card, hN] at this exact lt_irrefl _ ((Nat.lt_succ_self (multiplicity E)).trans_le this) /-- A small positive number such that any `1 - δ`-separated set in the ball of radius `2` has cardinality at most `Besicovitch.multiplicity E`. -/ def goodδ : ℝ := (exists_goodδ E).choose theorem goodδ_lt_one : goodδ E < 1 := (exists_goodδ E).choose_spec.2.1 /-- A number `τ > 1`, but chosen close enough to `1` so that the construction in the Besicovitch covering theorem using this parameter `τ` will give the smallest possible number of covering families. -/ def goodτ : ℝ := 1 + goodδ E / 4 theorem one_lt_goodτ : 1 < goodτ E := by dsimp [goodτ, goodδ]; linarith [(exists_goodδ E).choose_spec.1] variable {E} theorem card_le_multiplicity_of_δ {s : Finset E} (hs : ∀ c ∈ s, ‖c‖ ≤ 2) (h's : ∀ c ∈ s, ∀ d ∈ s, c ≠ d → 1 - goodδ E ≤ ‖c - d‖) : s.card ≤ multiplicity E := (Classical.choose_spec (exists_goodδ E)).2.2 s hs h's theorem le_multiplicity_of_δ_of_fin {n : ℕ} (f : Fin n → E) (h : ∀ i, ‖f i‖ ≤ 2) (h' : Pairwise fun i j => 1 - goodδ E ≤ ‖f i - f j‖) : n ≤ multiplicity E := by classical have finj : Function.Injective f := by intro i j hij by_contra h have : 1 - goodδ E ≤ ‖f i - f j‖ := h' h simp only [hij, norm_zero, sub_self] at this linarith [goodδ_lt_one E] let s := Finset.image f Finset.univ have s_card : s.card = n := by rw [Finset.card_image_of_injective _ finj]; exact Finset.card_fin n have hs : ∀ c ∈ s, ‖c‖ ≤ 2 := by simp only [s, h, forall_apply_eq_imp_iff, forall_const, forall_exists_index, Finset.mem_univ, Finset.mem_image, imp_true_iff, true_and] have h's : ∀ c ∈ s, ∀ d ∈ s, c ≠ d → 1 - goodδ E ≤ ‖c - d‖ := by simp only [s, forall_apply_eq_imp_iff, forall_exists_index, Finset.mem_univ, Finset.mem_image, Ne, exists_true_left, forall_apply_eq_imp_iff, forall_true_left, true_and] intro i j hij have : i ≠ j := fun h => by rw [h] at hij; exact hij rfl exact h' this have : s.card ≤ multiplicity E := card_le_multiplicity_of_δ hs h's rwa [s_card] at this end namespace SatelliteConfig /-! ### Relating satellite configurations to separated points in the ball of radius `2`. We prove that the number of points in a satellite configuration is bounded by the maximal number of `1`-separated points in the ball of radius `2`. For this, start from a satellite configuration `c`. Without loss of generality, one can assume that the last ball is centered at `0` and of radius `1`. Define `c' i = c i` if `‖c i‖ ≤ 2`, and `c' i = (2/‖c i‖) • c i` if `‖c i‖ > 2`. It turns out that these points are `1 - δ`-separated, where `δ` is arbitrarily small if `τ` is close enough to `1`. The number of such configurations is bounded by `multiplicity E` if `δ` is suitably small. To check that the points `c' i` are `1 - δ`-separated, one treats separately the cases where both `‖c i‖` and `‖c j‖` are `≤ 2`, where one of them is `≤ 2` and the other one is `> 2`, and where both of them are `> 2`. -/ theorem exists_normalized_aux1 {N : ℕ} {τ : ℝ} (a : SatelliteConfig E N τ) (lastr : a.r (last N) = 1) (hτ : 1 ≤ τ) (δ : ℝ) (hδ1 : τ ≤ 1 + δ / 4) (hδ2 : δ ≤ 1) (i j : Fin N.succ) (inej : i ≠ j) : 1 - δ ≤ ‖a.c i - a.c j‖ := by have ah : Pairwise fun i j => a.r i ≤ ‖a.c i - a.c j‖ ∧ a.r j ≤ τ * a.r i ∨ a.r j ≤ ‖a.c j - a.c i‖ ∧ a.r i ≤ τ * a.r j := by simpa only [dist_eq_norm] using a.h have δnonneg : 0 ≤ δ := by linarith only [hτ, hδ1] have D : 0 ≤ 1 - δ / 4 := by linarith only [hδ2] have τpos : 0 < τ := _root_.zero_lt_one.trans_le hτ have I : (1 - δ / 4) * τ ≤ 1 := calc (1 - δ / 4) * τ ≤ (1 - δ / 4) * (1 + δ / 4) := by gcongr _ = (1 : ℝ) - δ ^ 2 / 16 := by ring _ ≤ 1 := by linarith only [sq_nonneg δ] have J : 1 - δ ≤ 1 - δ / 4 := by linarith only [δnonneg] have K : 1 - δ / 4 ≤ τ⁻¹ := by rw [inv_eq_one_div, le_div_iff τpos]; exact I suffices L : τ⁻¹ ≤ ‖a.c i - a.c j‖ by linarith only [J, K, L] have hτ' : ∀ k, τ⁻¹ ≤ a.r k := by intro k rw [inv_eq_one_div, div_le_iff τpos, ← lastr, mul_comm] exact a.hlast' k hτ rcases ah inej with (H | H) · apply le_trans _ H.1 exact hτ' i · rw [norm_sub_rev] apply le_trans _ H.1 exact hτ' j variable [NormedSpace ℝ E] #adaptation_note /-- after v4.7.0-rc1, there is a performance problem in `field_simp`. (Part of the code was ignoring the `maxDischargeDepth` setting: now that we have to increase it, other paths becomes slow.) -/ set_option maxHeartbeats 400000 in theorem exists_normalized_aux2 {N : ℕ} {τ : ℝ} (a : SatelliteConfig E N τ) (lastc : a.c (last N) = 0) (lastr : a.r (last N) = 1) (hτ : 1 ≤ τ) (δ : ℝ) (hδ1 : τ ≤ 1 + δ / 4) (hδ2 : δ ≤ 1) (i j : Fin N.succ) (inej : i ≠ j) (hi : ‖a.c i‖ ≤ 2) (hj : 2 < ‖a.c j‖) : 1 - δ ≤ ‖a.c i - (2 / ‖a.c j‖) • a.c j‖ := by have ah : Pairwise fun i j => a.r i ≤ ‖a.c i - a.c j‖ ∧ a.r j ≤ τ * a.r i ∨ a.r j ≤ ‖a.c j - a.c i‖ ∧ a.r i ≤ τ * a.r j := by simpa only [dist_eq_norm] using a.h have δnonneg : 0 ≤ δ := by linarith only [hτ, hδ1] have D : 0 ≤ 1 - δ / 4 := by linarith only [hδ2] have hcrj : ‖a.c j‖ ≤ a.r j + 1 := by simpa only [lastc, lastr, dist_zero_right] using a.inter' j have I : a.r i ≤ 2 := by rcases lt_or_le i (last N) with (H | H) · apply (a.hlast i H).1.trans simpa only [dist_eq_norm, lastc, sub_zero] using hi · have : i = last N := top_le_iff.1 H rw [this, lastr] exact one_le_two have J : (1 - δ / 4) * τ ≤ 1 := calc (1 - δ / 4) * τ ≤ (1 - δ / 4) * (1 + δ / 4) := by gcongr _ = (1 : ℝ) - δ ^ 2 / 16 := by ring _ ≤ 1 := by linarith only [sq_nonneg δ] have A : a.r j - δ ≤ ‖a.c i - a.c j‖ := by rcases ah inej.symm with (H | H); · rw [norm_sub_rev]; linarith [H.1] have C : a.r j ≤ 4 := calc a.r j ≤ τ * a.r i := H.2 _ ≤ τ * 2 := by gcongr _ ≤ 5 / 4 * 2 := by gcongr; linarith only [hδ1, hδ2] _ ≤ 4 := by norm_num calc a.r j - δ ≤ a.r j - a.r j / 4 * δ := by gcongr _ - ?_ exact mul_le_of_le_one_left δnonneg (by linarith only [C]) _ = (1 - δ / 4) * a.r j := by ring _ ≤ (1 - δ / 4) * (τ * a.r i) := mul_le_mul_of_nonneg_left H.2 D _ ≤ 1 * a.r i := by rw [← mul_assoc]; gcongr _ ≤ ‖a.c i - a.c j‖ := by rw [one_mul]; exact H.1 set d := (2 / ‖a.c j‖) • a.c j with hd have : a.r j - δ ≤ ‖a.c i - d‖ + (a.r j - 1) := calc a.r j - δ ≤ ‖a.c i - a.c j‖ := A _ ≤ ‖a.c i - d‖ + ‖d - a.c j‖ := by simp only [← dist_eq_norm, dist_triangle] _ ≤ ‖a.c i - d‖ + (a.r j - 1) := by apply add_le_add_left have A : 0 ≤ 1 - 2 / ‖a.c j‖ := by simpa [div_le_iff (zero_le_two.trans_lt hj)] using hj.le rw [← one_smul ℝ (a.c j), hd, ← sub_smul, norm_smul, norm_sub_rev, Real.norm_eq_abs, abs_of_nonneg A, sub_mul] field_simp [(zero_le_two.trans_lt hj).ne'] linarith only [hcrj] linarith only [this] theorem exists_normalized_aux3 {N : ℕ} {τ : ℝ} (a : SatelliteConfig E N τ) (lastc : a.c (last N) = 0) (lastr : a.r (last N) = 1) (hτ : 1 ≤ τ) (δ : ℝ) (hδ1 : τ ≤ 1 + δ / 4) (i j : Fin N.succ) (inej : i ≠ j) (hi : 2 < ‖a.c i‖) (hij : ‖a.c i‖ ≤ ‖a.c j‖) : 1 - δ ≤ ‖(2 / ‖a.c i‖) • a.c i - (2 / ‖a.c j‖) • a.c j‖ := by have ah : Pairwise fun i j => a.r i ≤ ‖a.c i - a.c j‖ ∧ a.r j ≤ τ * a.r i ∨ a.r j ≤ ‖a.c j - a.c i‖ ∧ a.r i ≤ τ * a.r j := by simpa only [dist_eq_norm] using a.h have δnonneg : 0 ≤ δ := by linarith only [hτ, hδ1] have hcrj : ‖a.c j‖ ≤ a.r j + 1 := by simpa only [lastc, lastr, dist_zero_right] using a.inter' j have A : a.r i ≤ ‖a.c i‖ := by have : i < last N := by apply lt_top_iff_ne_top.2 intro iN change i = last N at iN rw [iN, lastc, norm_zero] at hi exact lt_irrefl _ (zero_le_two.trans_lt hi) convert (a.hlast i this).1 using 1 rw [dist_eq_norm, lastc, sub_zero] have hj : 2 < ‖a.c j‖ := hi.trans_le hij set s := ‖a.c i‖ have spos : 0 < s := zero_lt_two.trans hi set d := (s / ‖a.c j‖) • a.c j with hd have I : ‖a.c j - a.c i‖ ≤ ‖a.c j‖ - s + ‖d - a.c i‖ := calc ‖a.c j - a.c i‖ ≤ ‖a.c j - d‖ + ‖d - a.c i‖ := by simp [← dist_eq_norm, dist_triangle] _ = ‖a.c j‖ - ‖a.c i‖ + ‖d - a.c i‖ := by nth_rw 1 [← one_smul ℝ (a.c j)] rw [add_left_inj, hd, ← sub_smul, norm_smul, Real.norm_eq_abs, abs_of_nonneg, sub_mul, one_mul, div_mul_cancel₀ _ (zero_le_two.trans_lt hj).ne'] rwa [sub_nonneg, div_le_iff (zero_lt_two.trans hj), one_mul] have J : a.r j - ‖a.c j - a.c i‖ ≤ s / 2 * δ := calc a.r j - ‖a.c j - a.c i‖ ≤ s * (τ - 1) := by rcases ah inej.symm with (H | H) · calc a.r j - ‖a.c j - a.c i‖ ≤ 0 := sub_nonpos.2 H.1 _ ≤ s * (τ - 1) := mul_nonneg spos.le (sub_nonneg.2 hτ) · rw [norm_sub_rev] at H calc a.r j - ‖a.c j - a.c i‖ ≤ τ * a.r i - a.r i := sub_le_sub H.2 H.1 _ = a.r i * (τ - 1) := by ring _ ≤ s * (τ - 1) := mul_le_mul_of_nonneg_right A (sub_nonneg.2 hτ) _ ≤ s * (δ / 2) := (mul_le_mul_of_nonneg_left (by linarith only [δnonneg, hδ1]) spos.le) _ = s / 2 * δ := by ring have invs_nonneg : 0 ≤ 2 / s := div_nonneg zero_le_two (zero_le_two.trans hi.le) calc 1 - δ = 2 / s * (s / 2 - s / 2 * δ) := by field_simp [spos.ne']; ring _ ≤ 2 / s * ‖d - a.c i‖ := (mul_le_mul_of_nonneg_left (by linarith only [hcrj, I, J, hi]) invs_nonneg) _ = ‖(2 / s) • a.c i - (2 / ‖a.c j‖) • a.c j‖ := by conv_lhs => rw [norm_sub_rev, ← abs_of_nonneg invs_nonneg] rw [← Real.norm_eq_abs, ← norm_smul, smul_sub, hd, smul_smul] congr 3 field_simp [spos.ne'] theorem exists_normalized {N : ℕ} {τ : ℝ} (a : SatelliteConfig E N τ) (lastc : a.c (last N) = 0) (lastr : a.r (last N) = 1) (hτ : 1 ≤ τ) (δ : ℝ) (hδ1 : τ ≤ 1 + δ / 4) (hδ2 : δ ≤ 1) : ∃ c' : Fin N.succ → E, (∀ n, ‖c' n‖ ≤ 2) ∧ Pairwise fun i j => 1 - δ ≤ ‖c' i - c' j‖ := by let c' : Fin N.succ → E := fun i => if ‖a.c i‖ ≤ 2 then a.c i else (2 / ‖a.c i‖) • a.c i have norm_c'_le : ∀ i, ‖c' i‖ ≤ 2 := by intro i simp only [c'] split_ifs with h; · exact h by_cases hi : ‖a.c i‖ = 0 <;> field_simp [norm_smul, hi] refine ⟨c', fun n => norm_c'_le n, fun i j inej => ?_⟩ -- up to exchanging `i` and `j`, one can assume `‖c i‖ ≤ ‖c j‖`. wlog hij : ‖a.c i‖ ≤ ‖a.c j‖ generalizing i j · rw [norm_sub_rev]; exact this j i inej.symm (le_of_not_le hij) rcases le_or_lt ‖a.c j‖ 2 with (Hj | Hj) -- case `‖c j‖ ≤ 2` (and therefore also `‖c i‖ ≤ 2`) · simp_rw [c', Hj, hij.trans Hj, if_true] exact exists_normalized_aux1 a lastr hτ δ hδ1 hδ2 i j inej -- case `2 < ‖c j‖` · have H'j : ‖a.c j‖ ≤ 2 ↔ False := by simpa only [not_le, iff_false_iff] using Hj rcases le_or_lt ‖a.c i‖ 2 with (Hi | Hi) · -- case `‖c i‖ ≤ 2` simp_rw [c', Hi, if_true, H'j, if_false] exact exists_normalized_aux2 a lastc lastr hτ δ hδ1 hδ2 i j inej Hi Hj · -- case `2 < ‖c i‖` have H'i : ‖a.c i‖ ≤ 2 ↔ False := by simpa only [not_le, iff_false_iff] using Hi simp_rw [c', H'i, if_false, H'j, if_false] exact exists_normalized_aux3 a lastc lastr hτ δ hδ1 i j inej Hi hij end SatelliteConfig variable (E) variable [NormedSpace ℝ E] [FiniteDimensional ℝ E] /-- In a normed vector space `E`, there can be no satellite configuration with `multiplicity E + 1` points and the parameter `goodτ E`. This will ensure that in the inductive construction to get the Besicovitch covering families, there will never be more than `multiplicity E` nonempty families. -/ theorem isEmpty_satelliteConfig_multiplicity : IsEmpty (SatelliteConfig E (multiplicity E) (goodτ E)) := ⟨by intro a let b := a.centerAndRescale rcases b.exists_normalized a.centerAndRescale_center a.centerAndRescale_radius (one_lt_goodτ E).le (goodδ E) le_rfl (goodδ_lt_one E).le with ⟨c', c'_le_two, hc'⟩ exact lt_irrefl _ ((Nat.lt_succ_self _).trans_le (le_multiplicity_of_δ_of_fin c' c'_le_two hc'))⟩ instance (priority := 100) instHasBesicovitchCovering : HasBesicovitchCovering E := ⟨⟨multiplicity E, goodτ E, one_lt_goodτ E, isEmpty_satelliteConfig_multiplicity E⟩⟩ end Besicovitch
MeasureTheory\Covering\DensityTheorem.lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.MeasureTheory.Measure.Doubling import Mathlib.MeasureTheory.Covering.Vitali import Mathlib.MeasureTheory.Covering.Differentiation /-! # Uniformly locally doubling measures and Lebesgue's density theorem Lebesgue's density theorem states that given a set `S` in a sigma compact metric space with locally-finite uniformly locally doubling measure `μ` then for almost all points `x` in `S`, for any sequence of closed balls `B₀, B₁, B₂, ...` containing `x`, the limit `μ (S ∩ Bⱼ) / μ (Bⱼ) → 1` as `j → ∞`. In this file we combine general results about existence of Vitali families for uniformly locally doubling measures with results about differentiation along a Vitali family to obtain an explicit form of Lebesgue's density theorem. ## Main results * `IsUnifLocDoublingMeasure.ae_tendsto_measure_inter_div`: a version of Lebesgue's density theorem for sequences of balls converging on a point but whose centres are not required to be fixed. -/ noncomputable section open Set Filter Metric MeasureTheory TopologicalSpace open scoped NNReal Topology namespace IsUnifLocDoublingMeasure variable {α : Type*} [MetricSpace α] [MeasurableSpace α] (μ : Measure α) [IsUnifLocDoublingMeasure μ] section variable [SecondCountableTopology α] [BorelSpace α] [IsLocallyFiniteMeasure μ] open scoped Topology /-- A Vitali family in a space with a uniformly locally doubling measure, designed so that the sets at `x` contain all `closedBall y r` when `dist x y ≤ K * r`. -/ irreducible_def vitaliFamily (K : ℝ) : VitaliFamily μ := by /- the Vitali covering theorem gives a family that works well at small scales, thanks to the doubling property. We enlarge this family to add large sets, to make sure that all balls and not only small ones belong to the family, for convenience. -/ let R := scalingScaleOf μ (max (4 * K + 3) 3) have Rpos : 0 < R := scalingScaleOf_pos _ _ have A : ∀ x : α, ∃ᶠ r in 𝓝[>] (0 : ℝ), μ (closedBall x (3 * r)) ≤ scalingConstantOf μ (max (4 * K + 3) 3) * μ (closedBall x r) := by intro x apply frequently_iff.2 fun {U} hU => ?_ obtain ⟨ε, εpos, hε⟩ := mem_nhdsWithin_Ioi_iff_exists_Ioc_subset.1 hU refine ⟨min ε R, hε ⟨lt_min εpos Rpos, min_le_left _ _⟩, ?_⟩ exact measure_mul_le_scalingConstantOf_mul μ ⟨zero_lt_three, le_max_right _ _⟩ (min_le_right _ _) exact (Vitali.vitaliFamily μ (scalingConstantOf μ (max (4 * K + 3) 3)) A).enlarge (R / 4) (by linarith) /-- In the Vitali family `IsUnifLocDoublingMeasure.vitaliFamily K`, the sets based at `x` contain all balls `closedBall y r` when `dist x y ≤ K * r`. -/ theorem closedBall_mem_vitaliFamily_of_dist_le_mul {K : ℝ} {x y : α} {r : ℝ} (h : dist x y ≤ K * r) (rpos : 0 < r) : closedBall y r ∈ (vitaliFamily μ K).setsAt x := by let R := scalingScaleOf μ (max (4 * K + 3) 3) simp only [vitaliFamily, VitaliFamily.enlarge, Vitali.vitaliFamily, mem_union, mem_setOf_eq, isClosed_ball, true_and_iff, (nonempty_ball.2 rpos).mono ball_subset_interior_closedBall, measurableSet_closedBall] /- The measure is doubling on scales smaller than `R`. Therefore, we treat differently small and large balls. For large balls, this follows directly from the enlargement we used in the definition. -/ by_cases H : closedBall y r ⊆ closedBall x (R / 4) swap; · exact Or.inr H left /- For small balls, there is the difficulty that `r` could be large but still the ball could be small, if the annulus `{y | ε ≤ dist y x ≤ R/4}` is empty. We split between the cases `r ≤ R` and `r > R`, and use the doubling for the former and rough estimates for the latter. -/ rcases le_or_lt r R with (hr | hr) · refine ⟨(K + 1) * r, ?_⟩ constructor · apply closedBall_subset_closedBall' rw [dist_comm] linarith · have I1 : closedBall x (3 * ((K + 1) * r)) ⊆ closedBall y ((4 * K + 3) * r) := by apply closedBall_subset_closedBall' linarith have I2 : closedBall y ((4 * K + 3) * r) ⊆ closedBall y (max (4 * K + 3) 3 * r) := by apply closedBall_subset_closedBall exact mul_le_mul_of_nonneg_right (le_max_left _ _) rpos.le apply (measure_mono (I1.trans I2)).trans exact measure_mul_le_scalingConstantOf_mul _ ⟨zero_lt_three.trans_le (le_max_right _ _), le_rfl⟩ hr · refine ⟨R / 4, H, ?_⟩ have : closedBall x (3 * (R / 4)) ⊆ closedBall y r := by apply closedBall_subset_closedBall' have A : y ∈ closedBall y r := mem_closedBall_self rpos.le have B := mem_closedBall'.1 (H A) linarith apply (measure_mono this).trans _ refine le_mul_of_one_le_left (zero_le _) ?_ exact ENNReal.one_le_coe_iff.2 (le_max_right _ _) theorem tendsto_closedBall_filterAt {K : ℝ} {x : α} {ι : Type*} {l : Filter ι} (w : ι → α) (δ : ι → ℝ) (δlim : Tendsto δ l (𝓝[>] 0)) (xmem : ∀ᶠ j in l, x ∈ closedBall (w j) (K * δ j)) : Tendsto (fun j => closedBall (w j) (δ j)) l ((vitaliFamily μ K).filterAt x) := by refine (vitaliFamily μ K).tendsto_filterAt_iff.mpr ⟨?_, fun ε hε => ?_⟩ · filter_upwards [xmem, δlim self_mem_nhdsWithin] with j hj h'j exact closedBall_mem_vitaliFamily_of_dist_le_mul μ hj h'j · rcases l.eq_or_neBot with rfl | h · simp have hK : 0 ≤ K := by rcases (xmem.and (δlim self_mem_nhdsWithin)).exists with ⟨j, hj, h'j⟩ have : 0 ≤ K * δ j := nonempty_closedBall.1 ⟨x, hj⟩ exact (mul_nonneg_iff_left_nonneg_of_pos (mem_Ioi.1 h'j)).1 this have δpos := eventually_mem_of_tendsto_nhdsWithin δlim replace δlim := tendsto_nhds_of_tendsto_nhdsWithin δlim replace hK : 0 < K + 1 := by linarith apply (((Metric.tendsto_nhds.mp δlim _ (div_pos hε hK)).and δpos).and xmem).mono rintro j ⟨⟨hjε, hj₀ : 0 < δ j⟩, hx⟩ y hy replace hjε : (K + 1) * δ j < ε := by simpa [abs_eq_self.mpr hj₀.le] using (lt_div_iff' hK).mp hjε simp only [mem_closedBall] at hx hy ⊢ linarith [dist_triangle_right y x (w j)] end section Applications variable [SecondCountableTopology α] [BorelSpace α] [IsLocallyFiniteMeasure μ] {E : Type*} [NormedAddCommGroup E] /-- A version of **Lebesgue's density theorem** for a sequence of closed balls whose centers are not required to be fixed. See also `Besicovitch.ae_tendsto_measure_inter_div`. -/ theorem ae_tendsto_measure_inter_div (S : Set α) (K : ℝ) : ∀ᵐ x ∂μ.restrict S, ∀ {ι : Type*} {l : Filter ι} (w : ι → α) (δ : ι → ℝ) (δlim : Tendsto δ l (𝓝[>] 0)) (xmem : ∀ᶠ j in l, x ∈ closedBall (w j) (K * δ j)), Tendsto (fun j => μ (S ∩ closedBall (w j) (δ j)) / μ (closedBall (w j) (δ j))) l (𝓝 1) := by filter_upwards [(vitaliFamily μ K).ae_tendsto_measure_inter_div S] with x hx ι l w δ δlim xmem using hx.comp (tendsto_closedBall_filterAt μ _ _ δlim xmem) /-- A version of **Lebesgue differentiation theorem** for a sequence of closed balls whose centers are not required to be fixed. -/ theorem ae_tendsto_average_norm_sub {f : α → E} (hf : LocallyIntegrable f μ) (K : ℝ) : ∀ᵐ x ∂μ, ∀ {ι : Type*} {l : Filter ι} (w : ι → α) (δ : ι → ℝ) (δlim : Tendsto δ l (𝓝[>] 0)) (xmem : ∀ᶠ j in l, x ∈ closedBall (w j) (K * δ j)), Tendsto (fun j => ⨍ y in closedBall (w j) (δ j), ‖f y - f x‖ ∂μ) l (𝓝 0) := by filter_upwards [(vitaliFamily μ K).ae_tendsto_average_norm_sub hf] with x hx ι l w δ δlim xmem using hx.comp (tendsto_closedBall_filterAt μ _ _ δlim xmem) /-- A version of **Lebesgue differentiation theorem** for a sequence of closed balls whose centers are not required to be fixed. -/ theorem ae_tendsto_average [NormedSpace ℝ E] [CompleteSpace E] {f : α → E} (hf : LocallyIntegrable f μ) (K : ℝ) : ∀ᵐ x ∂μ, ∀ {ι : Type*} {l : Filter ι} (w : ι → α) (δ : ι → ℝ) (δlim : Tendsto δ l (𝓝[>] 0)) (xmem : ∀ᶠ j in l, x ∈ closedBall (w j) (K * δ j)), Tendsto (fun j => ⨍ y in closedBall (w j) (δ j), f y ∂μ) l (𝓝 (f x)) := by filter_upwards [(vitaliFamily μ K).ae_tendsto_average hf] with x hx ι l w δ δlim xmem using hx.comp (tendsto_closedBall_filterAt μ _ _ δlim xmem) end Applications end IsUnifLocDoublingMeasure
MeasureTheory\Covering\Differentiation.lean
/- Copyright (c) 2021 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.MeasureTheory.Covering.VitaliFamily import Mathlib.MeasureTheory.Measure.Regular import Mathlib.MeasureTheory.Function.AEMeasurableOrder import Mathlib.MeasureTheory.Integral.Lebesgue import Mathlib.MeasureTheory.Integral.Average import Mathlib.MeasureTheory.Decomposition.Lebesgue /-! # Differentiation of measures On a second countable metric space with a measure `μ`, consider a Vitali family (i.e., for each `x` one has a family of sets shrinking to `x`, with a good behavior with respect to covering theorems). Consider also another measure `ρ`. Then, for almost every `x`, the ratio `ρ a / μ a` converges when `a` shrinks to `x` along the Vitali family, towards the Radon-Nikodym derivative of `ρ` with respect to `μ`. This is the main theorem on differentiation of measures. This theorem is proved in this file, under the name `VitaliFamily.ae_tendsto_rnDeriv`. Note that, almost surely, `μ a` is eventually positive and finite (see `VitaliFamily.ae_eventually_measure_pos` and `VitaliFamily.eventually_measure_lt_top`), so the ratio really makes sense. For concrete applications, one needs concrete instances of Vitali families, as provided for instance by `Besicovitch.vitaliFamily` (for balls) or by `Vitali.vitaliFamily` (for doubling measures). Specific applications to Lebesgue density points and the Lebesgue differentiation theorem are also derived: * `VitaliFamily.ae_tendsto_measure_inter_div` states that, for almost every point `x ∈ s`, then `μ (s ∩ a) / μ a` tends to `1` as `a` shrinks to `x` along a Vitali family. * `VitaliFamily.ae_tendsto_average_norm_sub` states that, for almost every point `x`, then the average of `y ↦ ‖f y - f x‖` on `a` tends to `0` as `a` shrinks to `x` along a Vitali family. ## Sketch of proof Let `v` be a Vitali family for `μ`. Assume for simplicity that `ρ` is absolutely continuous with respect to `μ`, as the case of a singular measure is easier. It is easy to see that a set `s` on which `liminf ρ a / μ a < q` satisfies `ρ s ≤ q * μ s`, by using a disjoint subcovering provided by the definition of Vitali families. Similarly for the limsup. It follows that a set on which `ρ a / μ a` oscillates has measure `0`, and therefore that `ρ a / μ a` converges almost surely (`VitaliFamily.ae_tendsto_div`). Moreover, on a set where the limit is close to a constant `c`, one gets `ρ s ∼ c μ s`, using again a covering lemma as above. It follows that `ρ` is equal to `μ.withDensity (v.limRatio ρ x)`, where `v.limRatio ρ x` is the limit of `ρ a / μ a` at `x` (which is well defined almost everywhere). By uniqueness of the Radon-Nikodym derivative, one gets `v.limRatio ρ x = ρ.rnDeriv μ x` almost everywhere, completing the proof. There is a difficulty in this sketch: this argument works well when `v.limRatio ρ` is measurable, but there is no guarantee that this is the case, especially if one doesn't make further assumptions on the Vitali family. We use an indirect argument to show that `v.limRatio ρ` is always almost everywhere measurable, again based on the disjoint subcovering argument (see `VitaliFamily.exists_measurable_supersets_limRatio`), and then proceed as sketched above but replacing `v.limRatio ρ` by a measurable version called `v.limRatioMeas ρ`. ## Counterexample The standing assumption in this file is that spaces are second countable. Without this assumption, measures may be zero locally but nonzero globally, which is not compatible with differentiation theory (which deduces global information from local one). Here is an example displaying this behavior. Define a measure `μ` by `μ s = 0` if `s` is covered by countably many balls of radius `1`, and `μ s = ∞` otherwise. This is indeed a countably additive measure, which is moreover locally finite and doubling at small scales. It vanishes on every ball of radius `1`, so all the quantities in differentiation theory (defined as ratios of measures as the radius tends to zero) make no sense. However, the measure is not globally zero if the space is big enough. ## References * [Herbert Federer, Geometric Measure Theory, Chapter 2.9][Federer1996] -/ open MeasureTheory Metric Set Filter TopologicalSpace MeasureTheory.Measure open scoped Filter ENNReal MeasureTheory NNReal Topology variable {α : Type*} [MetricSpace α] {m0 : MeasurableSpace α} {μ : Measure α} (v : VitaliFamily μ) {E : Type*} [NormedAddCommGroup E] namespace VitaliFamily /-- The limit along a Vitali family of `ρ a / μ a` where it makes sense, and garbage otherwise. Do *not* use this definition: it is only a temporary device to show that this ratio tends almost everywhere to the Radon-Nikodym derivative. -/ noncomputable def limRatio (ρ : Measure α) (x : α) : ℝ≥0∞ := limUnder (v.filterAt x) fun a => ρ a / μ a /-- For almost every point `x`, sufficiently small sets in a Vitali family around `x` have positive measure. (This is a nontrivial result, following from the covering property of Vitali families). -/ theorem ae_eventually_measure_pos [SecondCountableTopology α] : ∀ᵐ x ∂μ, ∀ᶠ a in v.filterAt x, 0 < μ a := by set s := {x | ¬∀ᶠ a in v.filterAt x, 0 < μ a} with hs simp (config := { zeta := false }) only [not_lt, not_eventually, nonpos_iff_eq_zero] at hs change μ s = 0 let f : α → Set (Set α) := fun _ => {a | μ a = 0} have h : v.FineSubfamilyOn f s := by intro x hx ε εpos rw [hs] at hx simp only [frequently_filterAt_iff, exists_prop, gt_iff_lt, mem_setOf_eq] at hx rcases hx ε εpos with ⟨a, a_sets, ax, μa⟩ exact ⟨a, ⟨a_sets, μa⟩, ax⟩ refine le_antisymm ?_ bot_le calc μ s ≤ ∑' x : h.index, μ (h.covering x) := h.measure_le_tsum _ = ∑' x : h.index, 0 := by congr; ext1 x; exact h.covering_mem x.2 _ = 0 := by simp only [tsum_zero, add_zero] /-- For every point `x`, sufficiently small sets in a Vitali family around `x` have finite measure. (This is a trivial result, following from the fact that the measure is locally finite). -/ theorem eventually_measure_lt_top [IsLocallyFiniteMeasure μ] (x : α) : ∀ᶠ a in v.filterAt x, μ a < ∞ := (μ.finiteAt_nhds x).eventually.filter_mono inf_le_left /-- If two measures `ρ` and `ν` have, at every point of a set `s`, arbitrarily small sets in a Vitali family satisfying `ρ a ≤ ν a`, then `ρ s ≤ ν s` if `ρ ≪ μ`. -/ theorem measure_le_of_frequently_le [SecondCountableTopology α] [BorelSpace α] {ρ : Measure α} (ν : Measure α) [IsLocallyFiniteMeasure ν] (hρ : ρ ≪ μ) (s : Set α) (hs : ∀ x ∈ s, ∃ᶠ a in v.filterAt x, ρ a ≤ ν a) : ρ s ≤ ν s := by -- this follows from a covering argument using the sets satisfying `ρ a ≤ ν a`. apply ENNReal.le_of_forall_pos_le_add fun ε εpos _ => ?_ obtain ⟨U, sU, U_open, νU⟩ : ∃ (U : Set α), s ⊆ U ∧ IsOpen U ∧ ν U ≤ ν s + ε := exists_isOpen_le_add s ν (ENNReal.coe_pos.2 εpos).ne' let f : α → Set (Set α) := fun _ => {a | ρ a ≤ ν a ∧ a ⊆ U} have h : v.FineSubfamilyOn f s := by apply v.fineSubfamilyOn_of_frequently f s fun x hx => ?_ have := (hs x hx).and_eventually ((v.eventually_filterAt_mem_setsAt x).and (v.eventually_filterAt_subset_of_nhds (U_open.mem_nhds (sU hx)))) apply Frequently.mono this rintro a ⟨ρa, _, aU⟩ exact ⟨ρa, aU⟩ haveI : Encodable h.index := h.index_countable.toEncodable calc ρ s ≤ ∑' x : h.index, ρ (h.covering x) := h.measure_le_tsum_of_absolutelyContinuous hρ _ ≤ ∑' x : h.index, ν (h.covering x) := ENNReal.tsum_le_tsum fun x => (h.covering_mem x.2).1 _ = ν (⋃ x : h.index, h.covering x) := by rw [measure_iUnion h.covering_disjoint_subtype fun i => h.measurableSet_u i.2] _ ≤ ν U := (measure_mono (iUnion_subset fun i => (h.covering_mem i.2).2)) _ ≤ ν s + ε := νU section variable [SecondCountableTopology α] [BorelSpace α] [IsLocallyFiniteMeasure μ] {ρ : Measure α} [IsLocallyFiniteMeasure ρ] /-- If a measure `ρ` is singular with respect to `μ`, then for `μ` almost every `x`, the ratio `ρ a / μ a` tends to zero when `a` shrinks to `x` along the Vitali family. This makes sense as `μ a` is eventually positive by `ae_eventually_measure_pos`. -/ theorem ae_eventually_measure_zero_of_singular (hρ : ρ ⟂ₘ μ) : ∀ᵐ x ∂μ, Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 0) := by have A : ∀ ε > (0 : ℝ≥0), ∀ᵐ x ∂μ, ∀ᶠ a in v.filterAt x, ρ a < ε * μ a := by intro ε εpos set s := {x | ¬∀ᶠ a in v.filterAt x, ρ a < ε * μ a} with hs change μ s = 0 obtain ⟨o, _, ρo, μo⟩ : ∃ o : Set α, MeasurableSet o ∧ ρ o = 0 ∧ μ oᶜ = 0 := hρ apply le_antisymm _ bot_le calc μ s ≤ μ (s ∩ o ∪ oᶜ) := by conv_lhs => rw [← inter_union_compl s o] gcongr apply inter_subset_right _ ≤ μ (s ∩ o) + μ oᶜ := measure_union_le _ _ _ = μ (s ∩ o) := by rw [μo, add_zero] _ = (ε : ℝ≥0∞)⁻¹ * (ε • μ) (s ∩ o) := by simp only [coe_nnreal_smul_apply, ← mul_assoc, mul_comm _ (ε : ℝ≥0∞)] rw [ENNReal.mul_inv_cancel (ENNReal.coe_pos.2 εpos).ne' ENNReal.coe_ne_top, one_mul] _ ≤ (ε : ℝ≥0∞)⁻¹ * ρ (s ∩ o) := by gcongr refine v.measure_le_of_frequently_le ρ ((Measure.AbsolutelyContinuous.refl μ).smul ε) _ ?_ intro x hx rw [hs] at hx simp only [mem_inter_iff, not_lt, not_eventually, mem_setOf_eq] at hx exact hx.1 _ ≤ (ε : ℝ≥0∞)⁻¹ * ρ o := by gcongr; apply inter_subset_right _ = 0 := by rw [ρo, mul_zero] obtain ⟨u, _, u_pos, u_lim⟩ : ∃ u : ℕ → ℝ≥0, StrictAnti u ∧ (∀ n : ℕ, 0 < u n) ∧ Tendsto u atTop (𝓝 0) := exists_seq_strictAnti_tendsto (0 : ℝ≥0) have B : ∀ᵐ x ∂μ, ∀ n, ∀ᶠ a in v.filterAt x, ρ a < u n * μ a := ae_all_iff.2 fun n => A (u n) (u_pos n) filter_upwards [B, v.ae_eventually_measure_pos] intro x hx h'x refine tendsto_order.2 ⟨fun z hz => (ENNReal.not_lt_zero hz).elim, fun z hz => ?_⟩ obtain ⟨w, w_pos, w_lt⟩ : ∃ w : ℝ≥0, (0 : ℝ≥0∞) < w ∧ (w : ℝ≥0∞) < z := ENNReal.lt_iff_exists_nnreal_btwn.1 hz obtain ⟨n, hn⟩ : ∃ n, u n < w := ((tendsto_order.1 u_lim).2 w (ENNReal.coe_pos.1 w_pos)).exists filter_upwards [hx n, h'x, v.eventually_measure_lt_top x] intro a ha μa_pos μa_lt_top rw [ENNReal.div_lt_iff (Or.inl μa_pos.ne') (Or.inl μa_lt_top.ne)] exact ha.trans_le (mul_le_mul_right' ((ENNReal.coe_le_coe.2 hn.le).trans w_lt.le) _) section AbsolutelyContinuous variable (hρ : ρ ≪ μ) /-- A set of points `s` satisfying both `ρ a ≤ c * μ a` and `ρ a ≥ d * μ a` at arbitrarily small sets in a Vitali family has measure `0` if `c < d`. Indeed, the first inequality should imply that `ρ s ≤ c * μ s`, and the second one that `ρ s ≥ d * μ s`, a contradiction if `0 < μ s`. -/ theorem null_of_frequently_le_of_frequently_ge {c d : ℝ≥0} (hcd : c < d) (s : Set α) (hc : ∀ x ∈ s, ∃ᶠ a in v.filterAt x, ρ a ≤ c * μ a) (hd : ∀ x ∈ s, ∃ᶠ a in v.filterAt x, (d : ℝ≥0∞) * μ a ≤ ρ a) : μ s = 0 := by apply measure_null_of_locally_null s fun x _ => ?_ obtain ⟨o, xo, o_open, μo⟩ : ∃ o : Set α, x ∈ o ∧ IsOpen o ∧ μ o < ∞ := Measure.exists_isOpen_measure_lt_top μ x refine ⟨s ∩ o, inter_mem_nhdsWithin _ (o_open.mem_nhds xo), ?_⟩ let s' := s ∩ o by_contra h apply lt_irrefl (ρ s') calc ρ s' ≤ c * μ s' := v.measure_le_of_frequently_le (c • μ) hρ s' fun x hx => hc x hx.1 _ < d * μ s' := by apply (ENNReal.mul_lt_mul_right h _).2 (ENNReal.coe_lt_coe.2 hcd) exact (lt_of_le_of_lt (measure_mono inter_subset_right) μo).ne _ ≤ ρ s' := v.measure_le_of_frequently_le ρ ((Measure.AbsolutelyContinuous.refl μ).smul d) s' fun x hx => hd x hx.1 /-- If `ρ` is absolutely continuous with respect to `μ`, then for almost every `x`, the ratio `ρ a / μ a` converges as `a` shrinks to `x` along a Vitali family for `μ`. -/ theorem ae_tendsto_div : ∀ᵐ x ∂μ, ∃ c, Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 c) := by obtain ⟨w, w_count, w_dense, _, w_top⟩ : ∃ w : Set ℝ≥0∞, w.Countable ∧ Dense w ∧ 0 ∉ w ∧ ∞ ∉ w := ENNReal.exists_countable_dense_no_zero_top have I : ∀ x ∈ w, x ≠ ∞ := fun x xs hx => w_top (hx ▸ xs) have A : ∀ c ∈ w, ∀ d ∈ w, c < d → ∀ᵐ x ∂μ, ¬((∃ᶠ a in v.filterAt x, ρ a / μ a < c) ∧ ∃ᶠ a in v.filterAt x, d < ρ a / μ a) := by intro c hc d hd hcd lift c to ℝ≥0 using I c hc lift d to ℝ≥0 using I d hd apply v.null_of_frequently_le_of_frequently_ge hρ (ENNReal.coe_lt_coe.1 hcd) · simp only [and_imp, exists_prop, not_frequently, not_and, not_lt, not_le, not_eventually, mem_setOf_eq, mem_compl_iff, not_forall] intro x h1x _ apply h1x.mono fun a ha => ?_ refine (ENNReal.div_le_iff_le_mul ?_ (Or.inr (bot_le.trans_lt ha).ne')).1 ha.le simp only [ENNReal.coe_ne_top, Ne, or_true_iff, not_false_iff] · simp only [and_imp, exists_prop, not_frequently, not_and, not_lt, not_le, not_eventually, mem_setOf_eq, mem_compl_iff, not_forall] intro x _ h2x apply h2x.mono fun a ha => ?_ exact ENNReal.mul_le_of_le_div ha.le have B : ∀ᵐ x ∂μ, ∀ c ∈ w, ∀ d ∈ w, c < d → ¬((∃ᶠ a in v.filterAt x, ρ a / μ a < c) ∧ ∃ᶠ a in v.filterAt x, d < ρ a / μ a) := by #adaptation_note /-- 2024-04-23 The next two lines were previously just `simpa only [ae_ball_iff w_count, ae_all_iff]` -/ rw [ae_ball_iff w_count]; intro x hx; rw [ae_ball_iff w_count]; revert x simpa only [ae_all_iff] filter_upwards [B] intro x hx exact tendsto_of_no_upcrossings w_dense hx theorem ae_tendsto_limRatio : ∀ᵐ x ∂μ, Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 (v.limRatio ρ x)) := by filter_upwards [v.ae_tendsto_div hρ] intro x hx exact tendsto_nhds_limUnder hx /-- Given two thresholds `p < q`, the sets `{x | v.limRatio ρ x < p}` and `{x | q < v.limRatio ρ x}` are obviously disjoint. The key to proving that `v.limRatio ρ` is almost everywhere measurable is to show that these sets have measurable supersets which are also disjoint, up to zero measure. This is the content of this lemma. -/ theorem exists_measurable_supersets_limRatio {p q : ℝ≥0} (hpq : p < q) : ∃ a b, MeasurableSet a ∧ MeasurableSet b ∧ {x | v.limRatio ρ x < p} ⊆ a ∧ {x | (q : ℝ≥0∞) < v.limRatio ρ x} ⊆ b ∧ μ (a ∩ b) = 0 := by /- Here is a rough sketch, assuming that the measure is finite and the limit is well defined everywhere. Let `u := {x | v.limRatio ρ x < p}` and `w := {x | q < v.limRatio ρ x}`. They have measurable supersets `u'` and `w'` of the same measure. We will show that these satisfy the conclusion of the theorem, i.e., `μ (u' ∩ w') = 0`. For this, note that `ρ (u' ∩ w') = ρ (u ∩ w')` (as `w'` is measurable, see `measure_toMeasurable_add_inter_left`). The latter set is included in the set where the limit of the ratios is `< p`, and therefore its measure is `≤ p * μ (u ∩ w')`. Using the same trick in the other direction gives that this is `p * μ (u' ∩ w')`. We have shown that `ρ (u' ∩ w') ≤ p * μ (u' ∩ w')`. Arguing in the same way but using the `w` part gives `q * μ (u' ∩ w') ≤ ρ (u' ∩ w')`. If `μ (u' ∩ w')` were nonzero, this would be a contradiction as `p < q`. For the rigorous proof, we need to work on a part of the space where the measure is finite (provided by `spanningSets (ρ + μ)`) and to restrict to the set where the limit is well defined (called `s` below, of full measure). Otherwise, the argument goes through. -/ let s := {x | ∃ c, Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 c)} let o : ℕ → Set α := spanningSets (ρ + μ) let u n := s ∩ {x | v.limRatio ρ x < p} ∩ o n let w n := s ∩ {x | (q : ℝ≥0∞) < v.limRatio ρ x} ∩ o n -- the supersets are obtained by restricting to the set `s` where the limit is well defined, to -- a finite measure part `o n`, taking a measurable superset here, and then taking the union over -- `n`. refine ⟨toMeasurable μ sᶜ ∪ ⋃ n, toMeasurable (ρ + μ) (u n), toMeasurable μ sᶜ ∪ ⋃ n, toMeasurable (ρ + μ) (w n), ?_, ?_, ?_, ?_, ?_⟩ -- check that these sets are measurable supersets as required · exact (measurableSet_toMeasurable _ _).union (MeasurableSet.iUnion fun n => measurableSet_toMeasurable _ _) · exact (measurableSet_toMeasurable _ _).union (MeasurableSet.iUnion fun n => measurableSet_toMeasurable _ _) · intro x hx by_cases h : x ∈ s · refine Or.inr (mem_iUnion.2 ⟨spanningSetsIndex (ρ + μ) x, ?_⟩) exact subset_toMeasurable _ _ ⟨⟨h, hx⟩, mem_spanningSetsIndex _ _⟩ · exact Or.inl (subset_toMeasurable μ sᶜ h) · intro x hx by_cases h : x ∈ s · refine Or.inr (mem_iUnion.2 ⟨spanningSetsIndex (ρ + μ) x, ?_⟩) exact subset_toMeasurable _ _ ⟨⟨h, hx⟩, mem_spanningSetsIndex _ _⟩ · exact Or.inl (subset_toMeasurable μ sᶜ h) -- it remains to check the nontrivial part that these sets have zero measure intersection. -- it suffices to do it for fixed `m` and `n`, as one is taking countable unions. suffices H : ∀ m n : ℕ, μ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) = 0 by have A : (toMeasurable μ sᶜ ∪ ⋃ n, toMeasurable (ρ + μ) (u n)) ∩ (toMeasurable μ sᶜ ∪ ⋃ n, toMeasurable (ρ + μ) (w n)) ⊆ toMeasurable μ sᶜ ∪ ⋃ (m) (n), toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n) := by simp only [inter_union_distrib_left, union_inter_distrib_right, true_and_iff, subset_union_left, union_subset_iff, inter_self] refine ⟨?_, ?_, ?_⟩ · exact inter_subset_right.trans subset_union_left · exact inter_subset_left.trans subset_union_left · simp_rw [iUnion_inter, inter_iUnion]; exact subset_union_right refine le_antisymm ((measure_mono A).trans ?_) bot_le calc μ (toMeasurable μ sᶜ ∪ ⋃ (m) (n), toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) ≤ μ (toMeasurable μ sᶜ) + μ (⋃ (m) (n), toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := measure_union_le _ _ _ = μ (⋃ (m) (n), toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := by have : μ sᶜ = 0 := v.ae_tendsto_div hρ; rw [measure_toMeasurable, this, zero_add] _ ≤ ∑' (m) (n), μ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := ((measure_iUnion_le _).trans (ENNReal.tsum_le_tsum fun m => measure_iUnion_le _)) _ = 0 := by simp only [H, tsum_zero] -- now starts the nontrivial part of the argument. We fix `m` and `n`, and show that the -- measurable supersets of `u m` and `w n` have zero measure intersection by using the lemmas -- `measure_toMeasurable_add_inter_left` (to reduce to `u m` or `w n` instead of the measurable -- superset) and `measure_le_of_frequently_le` to compare their measures for `ρ` and `μ`. intro m n have I : (ρ + μ) (u m) ≠ ∞ := by apply (lt_of_le_of_lt (measure_mono _) (measure_spanningSets_lt_top (ρ + μ) m)).ne exact inter_subset_right have J : (ρ + μ) (w n) ≠ ∞ := by apply (lt_of_le_of_lt (measure_mono _) (measure_spanningSets_lt_top (ρ + μ) n)).ne exact inter_subset_right have A : ρ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) ≤ p * μ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := calc ρ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) = ρ (u m ∩ toMeasurable (ρ + μ) (w n)) := measure_toMeasurable_add_inter_left (measurableSet_toMeasurable _ _) I _ ≤ (p • μ) (u m ∩ toMeasurable (ρ + μ) (w n)) := by refine v.measure_le_of_frequently_le (p • μ) hρ _ fun x hx => ?_ have L : Tendsto (fun a : Set α => ρ a / μ a) (v.filterAt x) (𝓝 (v.limRatio ρ x)) := tendsto_nhds_limUnder hx.1.1.1 have I : ∀ᶠ b : Set α in v.filterAt x, ρ b / μ b < p := (tendsto_order.1 L).2 _ hx.1.1.2 apply I.frequently.mono fun a ha => ?_ rw [coe_nnreal_smul_apply] refine (ENNReal.div_le_iff_le_mul ?_ (Or.inr (bot_le.trans_lt ha).ne')).1 ha.le simp only [ENNReal.coe_ne_top, Ne, or_true_iff, not_false_iff] _ = p * μ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := by simp only [coe_nnreal_smul_apply, measure_toMeasurable_add_inter_right (measurableSet_toMeasurable _ _) I] have B : (q : ℝ≥0∞) * μ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) ≤ ρ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := calc (q : ℝ≥0∞) * μ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) = (q : ℝ≥0∞) * μ (toMeasurable (ρ + μ) (u m) ∩ w n) := by conv_rhs => rw [inter_comm] rw [inter_comm, measure_toMeasurable_add_inter_right (measurableSet_toMeasurable _ _) J] _ ≤ ρ (toMeasurable (ρ + μ) (u m) ∩ w n) := by rw [← coe_nnreal_smul_apply] refine v.measure_le_of_frequently_le _ (AbsolutelyContinuous.rfl.smul _) _ ?_ intro x hx have L : Tendsto (fun a : Set α => ρ a / μ a) (v.filterAt x) (𝓝 (v.limRatio ρ x)) := tendsto_nhds_limUnder hx.2.1.1 have I : ∀ᶠ b : Set α in v.filterAt x, (q : ℝ≥0∞) < ρ b / μ b := (tendsto_order.1 L).1 _ hx.2.1.2 apply I.frequently.mono fun a ha => ?_ rw [coe_nnreal_smul_apply] exact ENNReal.mul_le_of_le_div ha.le _ = ρ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := by conv_rhs => rw [inter_comm] rw [inter_comm] exact (measure_toMeasurable_add_inter_left (measurableSet_toMeasurable _ _) J).symm by_contra h apply lt_irrefl (ρ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n))) calc ρ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) ≤ p * μ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := A _ < q * μ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := by gcongr suffices H : (ρ + μ) (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) ≠ ∞ by simp only [not_or, ENNReal.add_eq_top, Pi.add_apply, Ne, coe_add] at H exact H.2 apply (lt_of_le_of_lt (measure_mono inter_subset_left) _).ne rw [measure_toMeasurable] apply lt_of_le_of_lt (measure_mono _) (measure_spanningSets_lt_top (ρ + μ) m) exact inter_subset_right _ ≤ ρ (toMeasurable (ρ + μ) (u m) ∩ toMeasurable (ρ + μ) (w n)) := B theorem aemeasurable_limRatio : AEMeasurable (v.limRatio ρ) μ := by apply ENNReal.aemeasurable_of_exist_almost_disjoint_supersets _ _ fun p q hpq => ?_ exact v.exists_measurable_supersets_limRatio hρ hpq /-- A measurable version of `v.limRatio ρ`. Do *not* use this definition: it is only a temporary device to show that `v.limRatio` is almost everywhere equal to the Radon-Nikodym derivative. -/ noncomputable def limRatioMeas : α → ℝ≥0∞ := (v.aemeasurable_limRatio hρ).mk _ theorem limRatioMeas_measurable : Measurable (v.limRatioMeas hρ) := AEMeasurable.measurable_mk _ theorem ae_tendsto_limRatioMeas : ∀ᵐ x ∂μ, Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 (v.limRatioMeas hρ x)) := by filter_upwards [v.ae_tendsto_limRatio hρ, AEMeasurable.ae_eq_mk (v.aemeasurable_limRatio hρ)] intro x hx h'x rwa [h'x] at hx /-- If, for all `x` in a set `s`, one has frequently `ρ a / μ a < p`, then `ρ s ≤ p * μ s`, as proved in `measure_le_of_frequently_le`. Since `ρ a / μ a` tends almost everywhere to `v.limRatioMeas hρ x`, the same property holds for sets `s` on which `v.limRatioMeas hρ < p`. -/ theorem measure_le_mul_of_subset_limRatioMeas_lt {p : ℝ≥0} {s : Set α} (h : s ⊆ {x | v.limRatioMeas hρ x < p}) : ρ s ≤ p * μ s := by let t := {x : α | Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 (v.limRatioMeas hρ x))} have A : μ tᶜ = 0 := v.ae_tendsto_limRatioMeas hρ suffices H : ρ (s ∩ t) ≤ (p • μ) (s ∩ t) by calc ρ s = ρ (s ∩ t ∪ s ∩ tᶜ) := by rw [inter_union_compl] _ ≤ ρ (s ∩ t) + ρ (s ∩ tᶜ) := measure_union_le _ _ _ ≤ (p • μ) (s ∩ t) + ρ tᶜ := by gcongr; apply inter_subset_right _ ≤ p * μ (s ∩ t) := by simp [(hρ A)] _ ≤ p * μ s := by gcongr; apply inter_subset_left refine v.measure_le_of_frequently_le (p • μ) hρ _ fun x hx => ?_ have I : ∀ᶠ b : Set α in v.filterAt x, ρ b / μ b < p := (tendsto_order.1 hx.2).2 _ (h hx.1) apply I.frequently.mono fun a ha => ?_ rw [coe_nnreal_smul_apply] refine (ENNReal.div_le_iff_le_mul ?_ (Or.inr (bot_le.trans_lt ha).ne')).1 ha.le simp only [ENNReal.coe_ne_top, Ne, or_true_iff, not_false_iff] /-- If, for all `x` in a set `s`, one has frequently `q < ρ a / μ a`, then `q * μ s ≤ ρ s`, as proved in `measure_le_of_frequently_le`. Since `ρ a / μ a` tends almost everywhere to `v.limRatioMeas hρ x`, the same property holds for sets `s` on which `q < v.limRatioMeas hρ`. -/ theorem mul_measure_le_of_subset_lt_limRatioMeas {q : ℝ≥0} {s : Set α} (h : s ⊆ {x | (q : ℝ≥0∞) < v.limRatioMeas hρ x}) : (q : ℝ≥0∞) * μ s ≤ ρ s := by let t := {x : α | Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 (v.limRatioMeas hρ x))} have A : μ tᶜ = 0 := v.ae_tendsto_limRatioMeas hρ suffices H : (q • μ) (s ∩ t) ≤ ρ (s ∩ t) by calc (q • μ) s = (q • μ) (s ∩ t ∪ s ∩ tᶜ) := by rw [inter_union_compl] _ ≤ (q • μ) (s ∩ t) + (q • μ) (s ∩ tᶜ) := measure_union_le _ _ _ ≤ ρ (s ∩ t) + (q • μ) tᶜ := by gcongr; apply inter_subset_right _ = ρ (s ∩ t) := by simp [A] _ ≤ ρ s := by gcongr; apply inter_subset_left refine v.measure_le_of_frequently_le _ (AbsolutelyContinuous.rfl.smul _) _ ?_ intro x hx have I : ∀ᶠ a in v.filterAt x, (q : ℝ≥0∞) < ρ a / μ a := (tendsto_order.1 hx.2).1 _ (h hx.1) apply I.frequently.mono fun a ha => ?_ rw [coe_nnreal_smul_apply] exact ENNReal.mul_le_of_le_div ha.le /-- The points with `v.limRatioMeas hρ x = ∞` have measure `0` for `μ`. -/ theorem measure_limRatioMeas_top : μ {x | v.limRatioMeas hρ x = ∞} = 0 := by refine measure_null_of_locally_null _ fun x _ => ?_ obtain ⟨o, xo, o_open, μo⟩ : ∃ o : Set α, x ∈ o ∧ IsOpen o ∧ ρ o < ∞ := Measure.exists_isOpen_measure_lt_top ρ x let s := {x : α | v.limRatioMeas hρ x = ∞} ∩ o refine ⟨s, inter_mem_nhdsWithin _ (o_open.mem_nhds xo), le_antisymm ?_ bot_le⟩ have ρs : ρ s ≠ ∞ := ((measure_mono inter_subset_right).trans_lt μo).ne have A : ∀ q : ℝ≥0, 1 ≤ q → μ s ≤ (q : ℝ≥0∞)⁻¹ * ρ s := by intro q hq rw [mul_comm, ← div_eq_mul_inv, ENNReal.le_div_iff_mul_le _ (Or.inr ρs), mul_comm] · apply v.mul_measure_le_of_subset_lt_limRatioMeas hρ intro y hy have : v.limRatioMeas hρ y = ∞ := hy.1 simp only [this, ENNReal.coe_lt_top, mem_setOf_eq] · simp only [(zero_lt_one.trans_le hq).ne', true_or_iff, ENNReal.coe_eq_zero, Ne, not_false_iff] have B : Tendsto (fun q : ℝ≥0 => (q : ℝ≥0∞)⁻¹ * ρ s) atTop (𝓝 (∞⁻¹ * ρ s)) := by apply ENNReal.Tendsto.mul_const _ (Or.inr ρs) exact ENNReal.tendsto_inv_iff.2 (ENNReal.tendsto_coe_nhds_top.2 tendsto_id) simp only [zero_mul, ENNReal.inv_top] at B apply ge_of_tendsto B exact eventually_atTop.2 ⟨1, A⟩ /-- The points with `v.limRatioMeas hρ x = 0` have measure `0` for `ρ`. -/ theorem measure_limRatioMeas_zero : ρ {x | v.limRatioMeas hρ x = 0} = 0 := by refine measure_null_of_locally_null _ fun x _ => ?_ obtain ⟨o, xo, o_open, μo⟩ : ∃ o : Set α, x ∈ o ∧ IsOpen o ∧ μ o < ∞ := Measure.exists_isOpen_measure_lt_top μ x let s := {x : α | v.limRatioMeas hρ x = 0} ∩ o refine ⟨s, inter_mem_nhdsWithin _ (o_open.mem_nhds xo), le_antisymm ?_ bot_le⟩ have μs : μ s ≠ ∞ := ((measure_mono inter_subset_right).trans_lt μo).ne have A : ∀ q : ℝ≥0, 0 < q → ρ s ≤ q * μ s := by intro q hq apply v.measure_le_mul_of_subset_limRatioMeas_lt hρ intro y hy have : v.limRatioMeas hρ y = 0 := hy.1 simp only [this, mem_setOf_eq, hq, ENNReal.coe_pos] have B : Tendsto (fun q : ℝ≥0 => (q : ℝ≥0∞) * μ s) (𝓝[>] (0 : ℝ≥0)) (𝓝 ((0 : ℝ≥0) * μ s)) := by apply ENNReal.Tendsto.mul_const _ (Or.inr μs) rw [ENNReal.tendsto_coe] exact nhdsWithin_le_nhds simp only [zero_mul, ENNReal.coe_zero] at B apply ge_of_tendsto B filter_upwards [self_mem_nhdsWithin] using A /-- As an intermediate step to show that `μ.withDensity (v.limRatioMeas hρ) = ρ`, we show here that `μ.withDensity (v.limRatioMeas hρ) ≤ t^2 ρ` for any `t > 1`. -/ theorem withDensity_le_mul {s : Set α} (hs : MeasurableSet s) {t : ℝ≥0} (ht : 1 < t) : μ.withDensity (v.limRatioMeas hρ) s ≤ (t : ℝ≥0∞) ^ 2 * ρ s := by /- We cut `s` into the sets where `v.limRatioMeas hρ = 0`, where `v.limRatioMeas hρ = ∞`, and where `v.limRatioMeas hρ ∈ [t^n, t^(n+1))` for `n : ℤ`. The first and second have measure `0`. For the latter, since `v.limRatioMeas hρ` fluctuates by at most `t` on this slice, we can use `measure_le_mul_of_subset_limRatioMeas_lt` and `mul_measure_le_of_subset_lt_limRatioMeas` to show that the two measures are comparable up to `t` (in fact `t^2` for technical reasons of strict inequalities). -/ have t_ne_zero' : t ≠ 0 := (zero_lt_one.trans ht).ne' have t_ne_zero : (t : ℝ≥0∞) ≠ 0 := by simpa only [ENNReal.coe_eq_zero, Ne] using t_ne_zero' let ν := μ.withDensity (v.limRatioMeas hρ) let f := v.limRatioMeas hρ have f_meas : Measurable f := v.limRatioMeas_measurable hρ -- Note(kmill): smul elaborator when used for CoeFun fails to get CoeFun instance to trigger -- unless you use the `(... :)` notation. Another fix is using `(2 : Nat)`, so this appears -- to be an unpleasant interaction with default instances. have A : ν (s ∩ f ⁻¹' {0}) ≤ ((t : ℝ≥0∞) ^ 2 • ρ :) (s ∩ f ⁻¹' {0}) := by apply le_trans _ (zero_le _) have M : MeasurableSet (s ∩ f ⁻¹' {0}) := hs.inter (f_meas (measurableSet_singleton _)) simp only [ν, nonpos_iff_eq_zero, M, withDensity_apply, lintegral_eq_zero_iff f_meas] apply (ae_restrict_iff' M).2 exact eventually_of_forall fun x hx => hx.2 have B : ν (s ∩ f ⁻¹' {∞}) ≤ ((t : ℝ≥0∞) ^ 2 • ρ :) (s ∩ f ⁻¹' {∞}) := by apply le_trans (le_of_eq _) (zero_le _) apply withDensity_absolutelyContinuous μ _ rw [← nonpos_iff_eq_zero] exact (measure_mono inter_subset_right).trans (v.measure_limRatioMeas_top hρ).le have C : ∀ n : ℤ, ν (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) ≤ ((t : ℝ≥0∞) ^ 2 • ρ :) (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) := by intro n let I := Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1)) have M : MeasurableSet (s ∩ f ⁻¹' I) := hs.inter (f_meas measurableSet_Ico) simp only [ν, M, withDensity_apply, coe_nnreal_smul_apply] calc (∫⁻ x in s ∩ f ⁻¹' I, f x ∂μ) ≤ ∫⁻ _ in s ∩ f ⁻¹' I, (t : ℝ≥0∞) ^ (n + 1) ∂μ := lintegral_mono_ae ((ae_restrict_iff' M).2 (eventually_of_forall fun x hx => hx.2.2.le)) _ = (t : ℝ≥0∞) ^ (n + 1) * μ (s ∩ f ⁻¹' I) := by simp only [lintegral_const, MeasurableSet.univ, Measure.restrict_apply, univ_inter] _ = (t : ℝ≥0∞) ^ (2 : ℤ) * ((t : ℝ≥0∞) ^ (n - 1) * μ (s ∩ f ⁻¹' I)) := by rw [← mul_assoc, ← ENNReal.zpow_add t_ne_zero ENNReal.coe_ne_top] congr 2 abel _ ≤ (t : ℝ≥0∞) ^ (2 : ℤ) * ρ (s ∩ f ⁻¹' I) := by gcongr rw [← ENNReal.coe_zpow (zero_lt_one.trans ht).ne'] apply v.mul_measure_le_of_subset_lt_limRatioMeas hρ intro x hx apply lt_of_lt_of_le _ hx.2.1 rw [← ENNReal.coe_zpow (zero_lt_one.trans ht).ne', ENNReal.coe_lt_coe, sub_eq_add_neg, zpow_add₀ t_ne_zero'] conv_rhs => rw [← mul_one (t ^ n)] gcongr rw [zpow_neg_one] exact inv_lt_one ht calc ν s = ν (s ∩ f ⁻¹' {0}) + ν (s ∩ f ⁻¹' {∞}) + ∑' n : ℤ, ν (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) := measure_eq_measure_preimage_add_measure_tsum_Ico_zpow ν f_meas hs ht _ ≤ ((t : ℝ≥0∞) ^ 2 • ρ :) (s ∩ f ⁻¹' {0}) + ((t : ℝ≥0∞) ^ 2 • ρ :) (s ∩ f ⁻¹' {∞}) + ∑' n : ℤ, ((t : ℝ≥0∞) ^ 2 • ρ :) (s ∩ f ⁻¹' Ico (t ^ n) (t ^ (n + 1))) := (add_le_add (add_le_add A B) (ENNReal.tsum_le_tsum C)) _ = ((t : ℝ≥0∞) ^ 2 • ρ :) s := (measure_eq_measure_preimage_add_measure_tsum_Ico_zpow ((t : ℝ≥0∞) ^ 2 • ρ) f_meas hs ht).symm /-- As an intermediate step to show that `μ.withDensity (v.limRatioMeas hρ) = ρ`, we show here that `ρ ≤ t μ.withDensity (v.limRatioMeas hρ)` for any `t > 1`. -/ theorem le_mul_withDensity {s : Set α} (hs : MeasurableSet s) {t : ℝ≥0} (ht : 1 < t) : ρ s ≤ t * μ.withDensity (v.limRatioMeas hρ) s := by /- We cut `s` into the sets where `v.limRatioMeas hρ = 0`, where `v.limRatioMeas hρ = ∞`, and where `v.limRatioMeas hρ ∈ [t^n, t^(n+1))` for `n : ℤ`. The first and second have measure `0`. For the latter, since `v.limRatioMeas hρ` fluctuates by at most `t` on this slice, we can use `measure_le_mul_of_subset_limRatioMeas_lt` and `mul_measure_le_of_subset_lt_limRatioMeas` to show that the two measures are comparable up to `t`. -/ have t_ne_zero' : t ≠ 0 := (zero_lt_one.trans ht).ne' have t_ne_zero : (t : ℝ≥0∞) ≠ 0 := by simpa only [ENNReal.coe_eq_zero, Ne] using t_ne_zero' let ν := μ.withDensity (v.limRatioMeas hρ) let f := v.limRatioMeas hρ have f_meas : Measurable f := v.limRatioMeas_measurable hρ have A : ρ (s ∩ f ⁻¹' {0}) ≤ (t • ν) (s ∩ f ⁻¹' {0}) := by refine le_trans (measure_mono inter_subset_right) (le_trans (le_of_eq ?_) (zero_le _)) exact v.measure_limRatioMeas_zero hρ have B : ρ (s ∩ f ⁻¹' {∞}) ≤ (t • ν) (s ∩ f ⁻¹' {∞}) := by apply le_trans (le_of_eq _) (zero_le _) apply hρ rw [← nonpos_iff_eq_zero] exact (measure_mono inter_subset_right).trans (v.measure_limRatioMeas_top hρ).le have C : ∀ n : ℤ, ρ (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) ≤ (t • ν) (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) := by intro n let I := Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1)) have M : MeasurableSet (s ∩ f ⁻¹' I) := hs.inter (f_meas measurableSet_Ico) simp only [ν, M, withDensity_apply, coe_nnreal_smul_apply] calc ρ (s ∩ f ⁻¹' I) ≤ (t : ℝ≥0∞) ^ (n + 1) * μ (s ∩ f ⁻¹' I) := by rw [← ENNReal.coe_zpow t_ne_zero'] apply v.measure_le_mul_of_subset_limRatioMeas_lt hρ intro x hx apply hx.2.2.trans_le (le_of_eq _) rw [ENNReal.coe_zpow t_ne_zero'] _ = ∫⁻ _ in s ∩ f ⁻¹' I, (t : ℝ≥0∞) ^ (n + 1) ∂μ := by simp only [lintegral_const, MeasurableSet.univ, Measure.restrict_apply, univ_inter] _ ≤ ∫⁻ x in s ∩ f ⁻¹' I, t * f x ∂μ := by apply lintegral_mono_ae ((ae_restrict_iff' M).2 (eventually_of_forall fun x hx => ?_)) rw [add_comm, ENNReal.zpow_add t_ne_zero ENNReal.coe_ne_top, zpow_one] exact mul_le_mul_left' hx.2.1 _ _ = t * ∫⁻ x in s ∩ f ⁻¹' I, f x ∂μ := lintegral_const_mul _ f_meas calc ρ s = ρ (s ∩ f ⁻¹' {0}) + ρ (s ∩ f ⁻¹' {∞}) + ∑' n : ℤ, ρ (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) := measure_eq_measure_preimage_add_measure_tsum_Ico_zpow ρ f_meas hs ht _ ≤ (t • ν) (s ∩ f ⁻¹' {0}) + (t • ν) (s ∩ f ⁻¹' {∞}) + ∑' n : ℤ, (t • ν) (s ∩ f ⁻¹' Ico ((t : ℝ≥0∞) ^ n) ((t : ℝ≥0∞) ^ (n + 1))) := (add_le_add (add_le_add A B) (ENNReal.tsum_le_tsum C)) _ = (t • ν) s := (measure_eq_measure_preimage_add_measure_tsum_Ico_zpow (t • ν) f_meas hs ht).symm theorem withDensity_limRatioMeas_eq : μ.withDensity (v.limRatioMeas hρ) = ρ := by ext1 s hs refine le_antisymm ?_ ?_ · have : Tendsto (fun t : ℝ≥0 => ((t : ℝ≥0∞) ^ 2 * ρ s : ℝ≥0∞)) (𝓝[>] 1) (𝓝 ((1 : ℝ≥0∞) ^ 2 * ρ s)) := by refine ENNReal.Tendsto.mul ?_ ?_ tendsto_const_nhds ?_ · exact ENNReal.Tendsto.pow (ENNReal.tendsto_coe.2 nhdsWithin_le_nhds) · simp only [one_pow, ENNReal.coe_one, true_or_iff, Ne, not_false_iff, one_ne_zero] · simp only [one_pow, ENNReal.coe_one, Ne, or_true_iff, ENNReal.one_ne_top, not_false_iff] simp only [one_pow, one_mul, ENNReal.coe_one] at this refine ge_of_tendsto this ?_ filter_upwards [self_mem_nhdsWithin] with _ ht exact v.withDensity_le_mul hρ hs ht · have : Tendsto (fun t : ℝ≥0 => (t : ℝ≥0∞) * μ.withDensity (v.limRatioMeas hρ) s) (𝓝[>] 1) (𝓝 ((1 : ℝ≥0∞) * μ.withDensity (v.limRatioMeas hρ) s)) := by refine ENNReal.Tendsto.mul_const (ENNReal.tendsto_coe.2 nhdsWithin_le_nhds) ?_ simp only [ENNReal.coe_one, true_or_iff, Ne, not_false_iff, one_ne_zero] simp only [one_mul, ENNReal.coe_one] at this refine ge_of_tendsto this ?_ filter_upwards [self_mem_nhdsWithin] with _ ht exact v.le_mul_withDensity hρ hs ht /-- Weak version of the main theorem on differentiation of measures: given a Vitali family `v` for a locally finite measure `μ`, and another locally finite measure `ρ`, then for `μ`-almost every `x` the ratio `ρ a / μ a` converges, when `a` shrinks to `x` along the Vitali family, towards the Radon-Nikodym derivative of `ρ` with respect to `μ`. This version assumes that `ρ` is absolutely continuous with respect to `μ`. The general version without this superfluous assumption is `VitaliFamily.ae_tendsto_rnDeriv`. -/ theorem ae_tendsto_rnDeriv_of_absolutelyContinuous : ∀ᵐ x ∂μ, Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 (ρ.rnDeriv μ x)) := by have A : (μ.withDensity (v.limRatioMeas hρ)).rnDeriv μ =ᵐ[μ] v.limRatioMeas hρ := rnDeriv_withDensity μ (v.limRatioMeas_measurable hρ) rw [v.withDensity_limRatioMeas_eq hρ] at A filter_upwards [v.ae_tendsto_limRatioMeas hρ, A] with _ _ h'x rwa [h'x] end AbsolutelyContinuous variable (ρ) /-- Main theorem on differentiation of measures: given a Vitali family `v` for a locally finite measure `μ`, and another locally finite measure `ρ`, then for `μ`-almost every `x` the ratio `ρ a / μ a` converges, when `a` shrinks to `x` along the Vitali family, towards the Radon-Nikodym derivative of `ρ` with respect to `μ`. -/ theorem ae_tendsto_rnDeriv : ∀ᵐ x ∂μ, Tendsto (fun a => ρ a / μ a) (v.filterAt x) (𝓝 (ρ.rnDeriv μ x)) := by let t := μ.withDensity (ρ.rnDeriv μ) have eq_add : ρ = ρ.singularPart μ + t := haveLebesgueDecomposition_add _ _ have A : ∀ᵐ x ∂μ, Tendsto (fun a => ρ.singularPart μ a / μ a) (v.filterAt x) (𝓝 0) := v.ae_eventually_measure_zero_of_singular (mutuallySingular_singularPart ρ μ) have B : ∀ᵐ x ∂μ, t.rnDeriv μ x = ρ.rnDeriv μ x := rnDeriv_withDensity μ (measurable_rnDeriv ρ μ) have C : ∀ᵐ x ∂μ, Tendsto (fun a => t a / μ a) (v.filterAt x) (𝓝 (t.rnDeriv μ x)) := v.ae_tendsto_rnDeriv_of_absolutelyContinuous (withDensity_absolutelyContinuous _ _) filter_upwards [A, B, C] with _ Ax Bx Cx convert Ax.add Cx using 1 · ext1 a conv_lhs => rw [eq_add] simp only [Pi.add_apply, coe_add, ENNReal.add_div] · simp only [Bx, zero_add] /-! ### Lebesgue density points -/ /-- Given a measurable set `s`, then `μ (s ∩ a) / μ a` converges when `a` shrinks to a typical point `x` along a Vitali family. The limit is `1` for `x ∈ s` and `0` for `x ∉ s`. This shows that almost every point of `s` is a Lebesgue density point for `s`. A version for non-measurable sets holds, but it only gives the first conclusion, see `ae_tendsto_measure_inter_div`. -/ theorem ae_tendsto_measure_inter_div_of_measurableSet {s : Set α} (hs : MeasurableSet s) : ∀ᵐ x ∂μ, Tendsto (fun a => μ (s ∩ a) / μ a) (v.filterAt x) (𝓝 (s.indicator 1 x)) := by haveI : IsLocallyFiniteMeasure (μ.restrict s) := isLocallyFiniteMeasure_of_le restrict_le_self filter_upwards [ae_tendsto_rnDeriv v (μ.restrict s), rnDeriv_restrict_self μ hs] intro x hx h'x simpa only [h'x, restrict_apply' hs, inter_comm] using hx /-- Given an arbitrary set `s`, then `μ (s ∩ a) / μ a` converges to `1` when `a` shrinks to a typical point of `s` along a Vitali family. This shows that almost every point of `s` is a Lebesgue density point for `s`. A stronger version for measurable sets is given in `ae_tendsto_measure_inter_div_of_measurableSet`. -/ theorem ae_tendsto_measure_inter_div (s : Set α) : ∀ᵐ x ∂μ.restrict s, Tendsto (fun a => μ (s ∩ a) / μ a) (v.filterAt x) (𝓝 1) := by let t := toMeasurable μ s have A : ∀ᵐ x ∂μ.restrict s, Tendsto (fun a => μ (t ∩ a) / μ a) (v.filterAt x) (𝓝 (t.indicator 1 x)) := by apply ae_mono restrict_le_self apply ae_tendsto_measure_inter_div_of_measurableSet exact measurableSet_toMeasurable _ _ have B : ∀ᵐ x ∂μ.restrict s, t.indicator 1 x = (1 : ℝ≥0∞) := by refine ae_restrict_of_ae_restrict_of_subset (subset_toMeasurable μ s) ?_ filter_upwards [ae_restrict_mem (measurableSet_toMeasurable μ s)] with _ hx simp only [hx, Pi.one_apply, indicator_of_mem] filter_upwards [A, B] with x hx h'x rw [h'x] at hx apply hx.congr' _ filter_upwards [v.eventually_filterAt_measurableSet x] with _ ha congr 1 exact measure_toMeasurable_inter_of_sFinite ha _ /-! ### Lebesgue differentiation theorem -/ theorem ae_tendsto_lintegral_div' {f : α → ℝ≥0∞} (hf : Measurable f) (h'f : (∫⁻ y, f y ∂μ) ≠ ∞) : ∀ᵐ x ∂μ, Tendsto (fun a => (∫⁻ y in a, f y ∂μ) / μ a) (v.filterAt x) (𝓝 (f x)) := by let ρ := μ.withDensity f have : IsFiniteMeasure ρ := isFiniteMeasure_withDensity h'f filter_upwards [ae_tendsto_rnDeriv v ρ, rnDeriv_withDensity μ hf] with x hx h'x rw [← h'x] apply hx.congr' _ filter_upwards [v.eventually_filterAt_measurableSet x] with a ha rw [← withDensity_apply f ha] theorem ae_tendsto_lintegral_div {f : α → ℝ≥0∞} (hf : AEMeasurable f μ) (h'f : (∫⁻ y, f y ∂μ) ≠ ∞) : ∀ᵐ x ∂μ, Tendsto (fun a => (∫⁻ y in a, f y ∂μ) / μ a) (v.filterAt x) (𝓝 (f x)) := by have A : (∫⁻ y, hf.mk f y ∂μ) ≠ ∞ := by convert h'f using 1 apply lintegral_congr_ae exact hf.ae_eq_mk.symm filter_upwards [v.ae_tendsto_lintegral_div' hf.measurable_mk A, hf.ae_eq_mk] with x hx h'x rw [h'x] convert hx using 1 ext1 a congr 1 apply lintegral_congr_ae exact ae_restrict_of_ae hf.ae_eq_mk theorem ae_tendsto_lintegral_nnnorm_sub_div'_of_integrable {f : α → E} (hf : Integrable f μ) (h'f : StronglyMeasurable f) : ∀ᵐ x ∂μ, Tendsto (fun a => (∫⁻ y in a, ‖f y - f x‖₊ ∂μ) / μ a) (v.filterAt x) (𝓝 0) := by /- For every `c`, then `(∫⁻ y in a, ‖f y - c‖₊ ∂μ) / μ a` tends almost everywhere to `‖f x - c‖`. We apply this to a countable set of `c` which is dense in the range of `f`, to deduce the desired convergence. A minor technical inconvenience is that constants are not integrable, so to apply previous lemmas we need to replace `c` with the restriction of `c` to a finite measure set `A n` in the above sketch. -/ let A := MeasureTheory.Measure.finiteSpanningSetsInOpen' μ rcases h'f.isSeparable_range with ⟨t, t_count, ht⟩ have main : ∀ᵐ x ∂μ, ∀ᵉ (n : ℕ) (c ∈ t), Tendsto (fun a => (∫⁻ y in a, ‖f y - (A.set n).indicator (fun _ => c) y‖₊ ∂μ) / μ a) (v.filterAt x) (𝓝 ‖f x - (A.set n).indicator (fun _ => c) x‖₊) := by #adaptation_note /-- 2024-04-23 The next two lines were previously just `simp_rw [ae_all_iff, ae_ball_iff t_count]`. -/ simp_rw [ae_all_iff] intro x; rw [ae_ball_iff t_count]; revert x intro n c _ apply ae_tendsto_lintegral_div' · refine (h'f.sub ?_).ennnorm exact stronglyMeasurable_const.indicator (IsOpen.measurableSet (A.set_mem n)) · apply ne_of_lt calc (∫⁻ y, ↑‖f y - (A.set n).indicator (fun _ : α => c) y‖₊ ∂μ) ≤ ∫⁻ y, ‖f y‖₊ + ‖(A.set n).indicator (fun _ : α => c) y‖₊ ∂μ := by apply lintegral_mono intro x dsimp rw [← ENNReal.coe_add] exact ENNReal.coe_le_coe.2 (nnnorm_sub_le _ _) _ = (∫⁻ y, ‖f y‖₊ ∂μ) + ∫⁻ y, ‖(A.set n).indicator (fun _ : α => c) y‖₊ ∂μ := (lintegral_add_left h'f.ennnorm _) _ < ∞ + ∞ := haveI I : Integrable ((A.set n).indicator fun _ : α => c) μ := by simp only [integrable_indicator_iff (IsOpen.measurableSet (A.set_mem n)), integrableOn_const, A.finite n, or_true_iff] ENNReal.add_lt_add hf.2 I.2 filter_upwards [main, v.ae_eventually_measure_pos] with x hx h'x have M : ∀ c ∈ t, Tendsto (fun a => (∫⁻ y in a, ‖f y - c‖₊ ∂μ) / μ a) (v.filterAt x) (𝓝 ‖f x - c‖₊) := by intro c hc obtain ⟨n, xn⟩ : ∃ n, x ∈ A.set n := by simpa [← A.spanning] using mem_univ x specialize hx n c hc simp only [xn, indicator_of_mem] at hx apply hx.congr' _ filter_upwards [v.eventually_filterAt_subset_of_nhds (IsOpen.mem_nhds (A.set_mem n) xn), v.eventually_filterAt_measurableSet x] with a ha h'a congr 1 apply setLIntegral_congr_fun h'a filter_upwards with y hy using (by simp only [ha hy, indicator_of_mem]) apply ENNReal.tendsto_nhds_zero.2 fun ε εpos => ?_ obtain ⟨c, ct, xc⟩ : ∃ c ∈ t, (‖f x - c‖₊ : ℝ≥0∞) < ε / 2 := by simp_rw [← edist_eq_coe_nnnorm_sub] have : f x ∈ closure t := ht (mem_range_self _) exact EMetric.mem_closure_iff.1 this (ε / 2) (ENNReal.half_pos (ne_of_gt εpos)) filter_upwards [(tendsto_order.1 (M c ct)).2 (ε / 2) xc, h'x, v.eventually_measure_lt_top x] with a ha h'a h''a apply ENNReal.div_le_of_le_mul calc (∫⁻ y in a, ‖f y - f x‖₊ ∂μ) ≤ ∫⁻ y in a, ‖f y - c‖₊ + ‖f x - c‖₊ ∂μ := by apply lintegral_mono fun x => ?_ simpa only [← edist_eq_coe_nnnorm_sub] using edist_triangle_right _ _ _ _ = (∫⁻ y in a, ‖f y - c‖₊ ∂μ) + ∫⁻ _ in a, ‖f x - c‖₊ ∂μ := (lintegral_add_right _ measurable_const) _ ≤ ε / 2 * μ a + ε / 2 * μ a := by gcongr · rw [ENNReal.div_lt_iff (Or.inl h'a.ne') (Or.inl h''a.ne)] at ha exact ha.le · simp only [lintegral_const, Measure.restrict_apply, MeasurableSet.univ, univ_inter] gcongr _ = ε * μ a := by rw [← add_mul, ENNReal.add_halves] theorem ae_tendsto_lintegral_nnnorm_sub_div_of_integrable {f : α → E} (hf : Integrable f μ) : ∀ᵐ x ∂μ, Tendsto (fun a => (∫⁻ y in a, ‖f y - f x‖₊ ∂μ) / μ a) (v.filterAt x) (𝓝 0) := by have I : Integrable (hf.1.mk f) μ := hf.congr hf.1.ae_eq_mk filter_upwards [v.ae_tendsto_lintegral_nnnorm_sub_div'_of_integrable I hf.1.stronglyMeasurable_mk, hf.1.ae_eq_mk] with x hx h'x apply hx.congr _ intro a congr 1 apply lintegral_congr_ae apply ae_restrict_of_ae filter_upwards [hf.1.ae_eq_mk] with y hy rw [hy, h'x] theorem ae_tendsto_lintegral_nnnorm_sub_div {f : α → E} (hf : LocallyIntegrable f μ) : ∀ᵐ x ∂μ, Tendsto (fun a => (∫⁻ y in a, ‖f y - f x‖₊ ∂μ) / μ a) (v.filterAt x) (𝓝 0) := by rcases hf.exists_nat_integrableOn with ⟨u, u_open, u_univ, hu⟩ have : ∀ n, ∀ᵐ x ∂μ, Tendsto (fun a => (∫⁻ y in a, ‖(u n).indicator f y - (u n).indicator f x‖₊ ∂μ) / μ a) (v.filterAt x) (𝓝 0) := by intro n apply ae_tendsto_lintegral_nnnorm_sub_div_of_integrable exact (integrable_indicator_iff (u_open n).measurableSet).2 (hu n) filter_upwards [ae_all_iff.2 this] with x hx obtain ⟨n, hn⟩ : ∃ n, x ∈ u n := by simpa only [← u_univ, mem_iUnion] using mem_univ x apply Tendsto.congr' _ (hx n) filter_upwards [v.eventually_filterAt_subset_of_nhds ((u_open n).mem_nhds hn), v.eventually_filterAt_measurableSet x] with a ha h'a congr 1 refine setLIntegral_congr_fun h'a (eventually_of_forall (fun y hy ↦ ?_)) rw [indicator_of_mem (ha hy) f, indicator_of_mem hn f] theorem eventually_filterAt_integrableOn (x : α) {f : α → E} (hf : LocallyIntegrable f μ) : ∀ᶠ a in v.filterAt x, IntegrableOn f a μ := by rcases hf x with ⟨w, w_nhds, hw⟩ filter_upwards [v.eventually_filterAt_subset_of_nhds w_nhds] with a ha exact hw.mono_set ha /-- *Lebesgue differentiation theorem*: for almost every point `x`, the average of `‖f y - f x‖` on `a` tends to `0` as `a` shrinks to `x` along a Vitali family. -/ theorem ae_tendsto_average_norm_sub {f : α → E} (hf : LocallyIntegrable f μ) : ∀ᵐ x ∂μ, Tendsto (fun a => ⨍ y in a, ‖f y - f x‖ ∂μ) (v.filterAt x) (𝓝 0) := by filter_upwards [v.ae_tendsto_lintegral_nnnorm_sub_div hf] with x hx have := (ENNReal.tendsto_toReal ENNReal.zero_ne_top).comp hx simp only [ENNReal.zero_toReal] at this apply Tendsto.congr' _ this filter_upwards [v.eventually_measure_lt_top x, v.eventually_filterAt_integrableOn x hf] with a h'a h''a simp only [Function.comp_apply, ENNReal.toReal_div, setAverage_eq, div_eq_inv_mul] have A : IntegrableOn (fun y => (‖f y - f x‖₊ : ℝ)) a μ := by simp_rw [coe_nnnorm] exact (h''a.sub (integrableOn_const.2 (Or.inr h'a))).norm rw [lintegral_coe_eq_integral _ A, ENNReal.toReal_ofReal (by positivity)] simp only [coe_nnnorm, smul_eq_mul] /-- *Lebesgue differentiation theorem*: for almost every point `x`, the average of `f` on `a` tends to `f x` as `a` shrinks to `x` along a Vitali family. -/ theorem ae_tendsto_average [NormedSpace ℝ E] [CompleteSpace E] {f : α → E} (hf : LocallyIntegrable f μ) : ∀ᵐ x ∂μ, Tendsto (fun a => ⨍ y in a, f y ∂μ) (v.filterAt x) (𝓝 (f x)) := by filter_upwards [v.ae_tendsto_average_norm_sub hf, v.ae_eventually_measure_pos] with x hx h'x rw [tendsto_iff_norm_sub_tendsto_zero] refine squeeze_zero' (eventually_of_forall fun a => norm_nonneg _) ?_ hx filter_upwards [h'x, v.eventually_measure_lt_top x, v.eventually_filterAt_integrableOn x hf] with a ha h'a h''a nth_rw 1 [← setAverage_const ha.ne' h'a.ne (f x)] simp_rw [setAverage_eq'] rw [← integral_sub] · exact norm_integral_le_integral_norm _ · exact (integrable_inv_smul_measure ha.ne' h'a.ne).2 h''a · exact (integrable_inv_smul_measure ha.ne' h'a.ne).2 (integrableOn_const.2 (Or.inr h'a)) end end VitaliFamily