filename
stringlengths
5
42
content
stringlengths
15
319k
Basic.lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Yaël Dillies -/ import Mathlib.Analysis.Normed.Group.Basic /-! # Ordered normed spaces In this file, we define classes for fields and groups that are both normed and ordered. These are mostly useful to avoid diamonds during type class inference. -/ open Filter Set open Topology variable {α : Type*} set_option linter.deprecated false in /-- A `NormedOrderedAddGroup` is an additive group that is both a `NormedAddCommGroup` and an `OrderedAddCommGroup`. This class is necessary to avoid diamonds caused by both classes carrying their own group structure. -/ @[deprecated "Use `[NormedAddCommGroup α] [PartialOrder α] [IsOrderedAddMonoid α]` instead." (since := "2025-04-10")] structure NormedOrderedAddGroup (α : Type*) extends OrderedAddCommGroup α, Norm α, MetricSpace α where /-- The distance function is induced by the norm. -/ dist_eq : ∀ x y, dist x y = ‖x - y‖ := by aesop set_option linter.deprecated false in set_option linter.existingAttributeWarning false in /-- A `NormedOrderedGroup` is a group that is both a `NormedCommGroup` and an `OrderedCommGroup`. This class is necessary to avoid diamonds caused by both classes carrying their own group structure. -/ @[to_additive, deprecated "Use `[NormedCommGroup α] [PartialOrder α] [IsOrderedMonoid α]` instead." (since := "2025-04-10")] structure NormedOrderedGroup (α : Type*) extends OrderedCommGroup α, Norm α, MetricSpace α where /-- The distance function is induced by the norm. -/ dist_eq : ∀ x y, dist x y = ‖x / y‖ := by aesop set_option linter.deprecated false in set_option linter.existingAttributeWarning false in /-- A `NormedLinearOrderedAddGroup` is an additive group that is both a `NormedAddCommGroup` and a `LinearOrderedAddCommGroup`. This class is necessary to avoid diamonds caused by both classes carrying their own group structure. -/ @[deprecated "Use `[NormedAddCommGroup α] [LinearOrder α] [IsOrderedAddMonoid α]` instead." (since := "2025-04-10")] structure NormedLinearOrderedAddGroup (α : Type*) extends LinearOrderedAddCommGroup α, Norm α, MetricSpace α where /-- The distance function is induced by the norm. -/ dist_eq : ∀ x y, dist x y = ‖x - y‖ := by aesop set_option linter.deprecated false in set_option linter.existingAttributeWarning false in /-- A `NormedLinearOrderedGroup` is a group that is both a `NormedCommGroup` and a `LinearOrderedCommGroup`. This class is necessary to avoid diamonds caused by both classes carrying their own group structure. -/ @[to_additive, deprecated "Use `[NormedCommGroup α] [LinearOrder α] [IsOrderedMonoid α]` instead." (since := "2025-04-10")] structure NormedLinearOrderedGroup (α : Type*) extends LinearOrderedCommGroup α, Norm α, MetricSpace α where /-- The distance function is induced by the norm. -/ dist_eq : ∀ x y, dist x y = ‖x / y‖ := by aesop set_option linter.deprecated false in set_option linter.existingAttributeWarning false in /-- A `NormedLinearOrderedField` is a field that is both a `NormedField` and a `LinearOrderedField`. This class is necessary to avoid diamonds. -/ @[deprecated "Use `[NormedField α] [LinearOrder α] [IsStrictOrderedRing α]` instead." (since := "2025-04-10")] structure NormedLinearOrderedField (α : Type*) extends LinearOrderedField α, Norm α, MetricSpace α where /-- The distance function is induced by the norm. -/ dist_eq : ∀ x y, dist x y = ‖x - y‖ := by aesop /-- The norm is multiplicative. -/ norm_mul : ∀ x y : α, ‖x * y‖ = ‖x‖ * ‖y‖
Notation.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Yury Kudryashov -/ import Mathlib.Data.Nat.Notation /-! # Definition and notation for positive natural numbers -/ /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ def PNat := { n : ℕ // 0 < n } deriving DecidableEq @[inherit_doc] notation "ℕ+" => PNat /-- The underlying natural number -/ @[coe] def PNat.val : ℕ+ → ℕ := Subtype.val instance coePNatNat : Coe ℕ+ ℕ := ⟨PNat.val⟩ instance : Repr ℕ+ := ⟨fun n n' => reprPrec n.1 n'⟩
orderedzmod.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import ssrAC div fintype path bigop order finset fingroup. From mathcomp Require Import ssralg poly. (******************************************************************************) (* Number structures *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines some classes to manipulate number structures, i.e, *) (* structures with an order and a norm. To use this file, insert *) (* "Import Num.Theory." before your scripts. You can also "Import Num.Def." *) (* to enjoy shorter notations (e.g., minr instead of Num.min, lerif instead *) (* of Num.leif, etc.). *) (* *) (* This file defines the following number structures: *) (* *) (* porderZmodType == join of Order.POrder and GRing.Zmodule *) (* The HB class is called POrderedZmodule. *) (* *) (* The ordering symbols and notations (<, <=, >, >=, _ <= _ ?= iff _, *) (* _ < _ ?<= if _, >=<, and ><) and lattice operations (meet and join) *) (* defined in order.v are redefined for the ring_display in the ring_scope *) (* (%R). 0-ary ordering symbols for the ring_display have the suffix "%R", *) (* e.g., <%R. All the other ordering notations are the same as order.v. *) (* *) (* Over these structures, we have the following operations: *) (* x \is a Num.pos <=> x is positive (:= x > 0) *) (* x \is a Num.neg <=> x is negative (:= x < 0) *) (* x \is a Num.nneg <=> x is positive or 0 (:= x >= 0) *) (* x \is a Num.npos <=> x is negative or 0 (:= x <= 0) *) (* x \is a Num.real <=> x is real (:= x >= 0 or x < 0) *) (* *) (* - list of prefixes : *) (* p : positive *) (* n : negative *) (* sp : strictly positive *) (* sn : strictly negative *) (* i : interior = in [0, 1] or ]0, 1[ *) (* e : exterior = in [1, +oo[ or ]1; +oo[ *) (* w : non strict (weak) monotony *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "n .-root" (format "n .-root"). Reserved Notation "'i". Reserved Notation "'Re z" (at level 10, z at level 8). Reserved Notation "'Im z" (at level 10, z at level 8). Local Open Scope order_scope. Local Open Scope group_scope. Local Open Scope ring_scope. Import Order.TTheory GRing.Theory. Fact ring_display : Order.disp_t. Proof. exact. Qed. Module Num. #[short(type="porderZmodType")] HB.structure Definition POrderedZmodule := { R of Order.isPOrder ring_display R & GRing.Zmodule R }. Module Export Def. Notation ler := (@Order.le ring_display _) (only parsing). Notation "@ 'ler' R" := (@Order.le ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation ltr := (@Order.lt ring_display _) (only parsing). Notation "@ 'ltr' R" := (@Order.lt ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation ger := (@Order.ge ring_display _) (only parsing). Notation "@ 'ger' R" := (@Order.ge ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation gtr := (@Order.gt ring_display _) (only parsing). Notation "@ 'gtr' R" := (@Order.gt ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation lerif := (@Order.leif ring_display _) (only parsing). Notation "@ 'lerif' R" := (@Order.leif ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation lterif := (@Order.lteif ring_display _) (only parsing). Notation "@ 'lteif' R" := (@Order.lteif ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation comparabler := (@Order.comparable ring_display _) (only parsing). Notation "@ 'comparabler' R" := (@Order.comparable ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation maxr := (@Order.max ring_display _). Notation "@ 'maxr' R" := (@Order.max ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Notation minr := (@Order.min ring_display _). Notation "@ 'minr' R" := (@Order.min ring_display R) (at level 10, R at level 8, only parsing) : function_scope. Section Def. Context {R : porderZmodType}. Definition Rpos_pred := fun x : R => 0 < x. Definition Rpos : qualifier 0 R := [qualify x | Rpos_pred x]. Definition Rneg_pred := fun x : R => x < 0. Definition Rneg : qualifier 0 R := [qualify x : R | Rneg_pred x]. Definition Rnneg_pred := fun x : R => 0 <= x. Definition Rnneg : qualifier 0 R := [qualify x : R | Rnneg_pred x]. Definition Rnpos_pred := fun x : R => x <= 0. Definition Rnpos : qualifier 0 R := [qualify x : R | Rnpos_pred x]. Definition Rreal_pred := fun x : R => (0 <= x) || (x <= 0). Definition Rreal : qualifier 0 R := [qualify x : R | Rreal_pred x]. End Def. Arguments Rpos_pred _ _ /. Arguments Rneg_pred _ _ /. Arguments Rnneg_pred _ _ /. Arguments Rreal_pred _ _ /. End Def. (* Shorter qualified names, when Num.Def is not imported. *) Notation le := ler (only parsing). Notation lt := ltr (only parsing). Notation ge := ger (only parsing). Notation gt := gtr (only parsing). Notation leif := lerif (only parsing). Notation lteif := lterif (only parsing). Notation comparable := comparabler (only parsing). Notation max := maxr. Notation min := minr. Notation pos := Rpos. Notation neg := Rneg. Notation nneg := Rnneg. Notation npos := Rnpos. Notation real := Rreal. (* (Exported) symbolic syntax. *) Module Import Syntax. Notation "<=%R" := le : function_scope. Notation ">=%R" := ge : function_scope. Notation "<%R" := lt : function_scope. Notation ">%R" := gt : function_scope. Notation "<?=%R" := leif : function_scope. Notation "<?<=%R" := lteif : function_scope. Notation ">=<%R" := comparable : function_scope. Notation "><%R" := (fun x y => ~~ (comparable x y)) : function_scope. Notation "<= y" := (ge y) : ring_scope. Notation "<= y :> T" := (<= (y : T)) (only parsing) : ring_scope. Notation ">= y" := (le y) : ring_scope. Notation ">= y :> T" := (>= (y : T)) (only parsing) : ring_scope. Notation "< y" := (gt y) : ring_scope. Notation "< y :> T" := (< (y : T)) (only parsing) : ring_scope. Notation "> y" := (lt y) : ring_scope. Notation "> y :> T" := (> (y : T)) (only parsing) : ring_scope. Notation "x <= y" := (le x y) : ring_scope. Notation "x <= y :> T" := ((x : T) <= (y : T)) (only parsing) : ring_scope. Notation "x >= y" := (y <= x) (only parsing) : ring_scope. Notation "x >= y :> T" := ((x : T) >= (y : T)) (only parsing) : ring_scope. Notation "x < y" := (lt x y) : ring_scope. Notation "x < y :> T" := ((x : T) < (y : T)) (only parsing) : ring_scope. Notation "x > y" := (y < x) (only parsing) : ring_scope. Notation "x > y :> T" := ((x : T) > (y : T)) (only parsing) : ring_scope. Notation "x <= y <= z" := ((x <= y) && (y <= z)) : ring_scope. Notation "x < y <= z" := ((x < y) && (y <= z)) : ring_scope. Notation "x <= y < z" := ((x <= y) && (y < z)) : ring_scope. Notation "x < y < z" := ((x < y) && (y < z)) : ring_scope. Notation "x <= y ?= 'iff' C" := (lerif x y C) : ring_scope. Notation "x <= y ?= 'iff' C :> R" := ((x : R) <= (y : R) ?= iff C) (only parsing) : ring_scope. Notation "x < y ?<= 'if' C" := (lterif x y C) : ring_scope. Notation "x < y ?<= 'if' C :> R" := ((x : R) < (y : R) ?<= if C) (only parsing) : ring_scope. Notation ">=< y" := [pred x | comparable x y] : ring_scope. Notation ">=< y :> T" := (>=< (y : T)) (only parsing) : ring_scope. Notation "x >=< y" := (comparable x y) : ring_scope. Notation ">< y" := [pred x | ~~ comparable x y] : ring_scope. Notation ">< y :> T" := (>< (y : T)) (only parsing) : ring_scope. Notation "x >< y" := (~~ (comparable x y)) : ring_scope. Export Order.PreOCoercions. End Syntax. Module Export Theory. End Theory. Module Exports. HB.reexport. End Exports. End Num. Export Num.Syntax Num.Exports.
TermReduce.lean
import Mathlib.Util.TermReduce -- On command line, tests format functions with => rather than ↦ without this. set_option linter.style.setOption false set_option pp.unicode.fun true /-- info: (fun x ↦ x) true : Bool -/ #guard_msgs in #check (fun x => x) true /-- info: true : Bool -/ #guard_msgs in #check beta% (fun x => x) true /-- info: (fun x y ↦ (x, y)) true : Bool → Bool × Bool -/ #guard_msgs in #check (fun (x y : Bool) => (x, y)) true /-- info: fun y ↦ (true, y) : Bool → Bool × Bool -/ #guard_msgs in #check beta% (fun (x y : Bool) => (x, y)) true /-- info: (fun x ↦ cond x) true 1 : Nat → Nat -/ #guard_msgs in #check (fun (x : Bool) => cond x) true 1 /-- info: cond true 1 : Nat → Nat -/ #guard_msgs in #check beta% (fun (x : Bool) => cond x) true 1 /-- info: ∀ (i : Nat), 0 ≤ i : Prop -/ #guard_msgs in #check ∀ i : Nat, beta% (fun j => 0 ≤ j) i /-- info: (fun x1 x2 ↦ x1 && x2) true false : Bool -/ #guard_msgs in #check (· && ·) true false /-- info: true && false : Bool -/ #guard_msgs in #check beta% (· && ·) true false abbrev reducibleId : Bool → Bool := fun x => x /-- info: reducibleId true : Bool -/ #guard_msgs in #check reducibleId true /-- info: id (id true) : Bool -/ #guard_msgs in #check id (id true) /-- info: id true : Bool -/ #guard_msgs in #check delta% id (id true) /-- info: true : Bool -/ #guard_msgs in #check delta% delta% id (id true) /-- info: true : Bool -/ #guard_msgs in #check delta% delta% by exact id (id true) /-- info: let x := true; x : Bool -/ #guard_msgs in #check let x := true; x /-- info: true : Bool -/ #guard_msgs in #check zeta% let x := true; x /-- info: let x := true; let y := x; y : Bool -/ #guard_msgs in #check let x := true; let y := x; y /-- info: true : Bool -/ #guard_msgs in #check zeta% let x := true; let y := x; y /-- info: true : Bool -/ #guard_msgs in #check zeta% by exact let x := true; let y := x; y class A where class B extends A where class C extends A where instance c : C := letI : B := {} {} set_option pp.all true in /-- info: @C.mk A.mk : C -/ #guard_msgs in #check delta% c set_option pp.all true in /-- info: @C.mk A.mk : C -/ #guard_msgs in #check reduceProj% delta% c
EqualizerSheafCondition.lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.CategoryTheory.Sites.IsSheafFor import Mathlib.CategoryTheory.Limits.Types.Shapes import Mathlib.Tactic.ApplyFun /-! # The equalizer diagram sheaf condition for a presieve In `Mathlib/CategoryTheory/Sites/IsSheafFor.lean` it is defined what it means for a presheaf to be a sheaf *for* a particular presieve. In this file we provide equivalent conditions in terms of equalizer diagrams. * In `Equalizer.Presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with `isSheaf_pretopology`, this shows the notions of `IsSheaf` are exactly equivalent.) * In `Equalizer.Sieve.equalizer_sheaf_condition`, the sheaf condition at a sieve is shown to be equivalent to that of Equation (3) p. 122 in Maclane-Moerdijk [MM92]. ## References * [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk: Chapter III, Section 4. * https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site) -/ universe t w v u namespace CategoryTheory open Opposite CategoryTheory Category Limits Sieve namespace Equalizer variable {C : Type u} [Category.{v} C] (P : Cᵒᵖ ⥤ Type max v u) {X : C} (R : Presieve X) (S : Sieve X) noncomputable section /-- The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of the Stacks entry. -/ @[stacks 00VM "This is the middle object of the fork diagram there."] def FirstObj : Type max v u := ∏ᶜ fun f : Σ Y, { f : Y ⟶ X // R f } => P.obj (op f.1) variable {P R} -- Porting note (https://github.com/leanprover-community/mathlib4/issues/10688): added to ease automation @[ext] lemma FirstObj.ext (z₁ z₂ : FirstObj P R) (h : ∀ (Y : C) (f : Y ⟶ X) (hf : R f), (Pi.π _ ⟨Y, f, hf⟩ : FirstObj P R ⟶ _) z₁ = (Pi.π _ ⟨Y, f, hf⟩ : FirstObj P R ⟶ _) z₂) : z₁ = z₂ := by apply Limits.Types.limit_ext rintro ⟨⟨Y, f, hf⟩⟩ exact h Y f hf variable (P R) /-- Show that `FirstObj` is isomorphic to `FamilyOfElements`. -/ @[simps] def firstObjEqFamily : FirstObj P R ≅ R.FamilyOfElements P where hom t _ _ hf := Pi.π (fun f : Σ Y, { f : Y ⟶ X // R f } => P.obj (op f.1)) ⟨_, _, hf⟩ t inv := Pi.lift fun f x => x _ f.2.2 instance : Inhabited (FirstObj P (⊥ : Presieve X)) := (firstObjEqFamily P _).toEquiv.inhabited -- Porting note: was not needed in mathlib instance : Inhabited (FirstObj P ((⊥ : Sieve X) : Presieve X)) := (inferInstance : Inhabited (FirstObj P (⊥ : Presieve X))) /-- The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of the Stacks entry. -/ @[stacks 00VM "This is the left morphism of the fork diagram there."] def forkMap : P.obj (op X) ⟶ FirstObj P R := Pi.lift fun f => P.map f.2.1.op /-! This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and the definition of `IsSheafFor`. -/ namespace Sieve /-- The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used to check a family is compatible. -/ def SecondObj : Type max v u := ∏ᶜ fun f : Σ (Y Z : _) (_ : Z ⟶ Y), { f' : Y ⟶ X // S f' } => P.obj (op f.2.1) variable {P S} -- Porting note (https://github.com/leanprover-community/mathlib4/issues/10688): added to ease automation @[ext] lemma SecondObj.ext (z₁ z₂ : SecondObj P S) (h : ∀ (Y Z : C) (g : Z ⟶ Y) (f : Y ⟶ X) (hf : S.arrows f), (Pi.π _ ⟨Y, Z, g, f, hf⟩ : SecondObj P S ⟶ _) z₁ = (Pi.π _ ⟨Y, Z, g, f, hf⟩ : SecondObj P S ⟶ _) z₂) : z₁ = z₂ := by apply Limits.Types.limit_ext rintro ⟨⟨Y, Z, g, f, hf⟩⟩ apply h variable (P S) /-- The map `p` of Equations (3,4) [MM92]. -/ def firstMap : FirstObj P (S : Presieve X) ⟶ SecondObj P S := Pi.lift fun fg => Pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, { f : Y ⟶ X // S f }) instance : Inhabited (SecondObj P (⊥ : Sieve X)) := ⟨firstMap _ _ default⟩ /-- The map `a` of Equations (3,4) [MM92]. -/ def secondMap : FirstObj P (S : Presieve X) ⟶ SecondObj P S := Pi.lift fun fg => Pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op theorem w : forkMap P (S : Presieve X) ≫ firstMap P S = forkMap P S ≫ secondMap P S := by ext simp [firstMap, secondMap, forkMap] /-- The family of elements given by `x : FirstObj P S` is compatible iff `firstMap` and `secondMap` map it to the same point. -/ theorem compatible_iff (x : FirstObj P S.arrows) : ((firstObjEqFamily P S.arrows).hom x).Compatible ↔ firstMap P S x = secondMap P S x := by rw [Presieve.compatible_iff_sieveCompatible] constructor · intro t apply SecondObj.ext intros Y Z g f hf simpa [firstMap, secondMap] using t _ g hf · intro t Y Z f g hf rw [Types.limit_ext_iff'] at t simpa [firstMap, secondMap] using t ⟨⟨Y, Z, g, f, hf⟩⟩ /-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/ theorem equalizer_sheaf_condition : Presieve.IsSheafFor P (S : Presieve X) ↔ Nonempty (IsLimit (Fork.ofι _ (w P S))) := by rw [Types.type_equalizer_iff_unique, ← Equiv.forall_congr_right (firstObjEqFamily P (S : Presieve X)).toEquiv.symm] simp_rw [← compatible_iff] simp only [inv_hom_id_apply, Iso.toEquiv_symm_fun] apply forall₂_congr intro x _ apply existsUnique_congr intro t rw [← Iso.toEquiv_symm_fun] rw [Equiv.eq_symm_apply] constructor · intro q funext Y f hf simpa [firstObjEqFamily, forkMap] using q _ _ · intro q Y f hf rw [← q] simp [firstObjEqFamily, forkMap] end Sieve /-! This section establishes the equivalence between the sheaf condition of https://stacks.math.columbia.edu/tag/00VM and the definition of `isSheafFor`. -/ namespace Presieve variable [R.hasPullbacks] /-- The rightmost object of the fork diagram of the Stacks entry, which contains the data used to check a family of elements for a presieve is compatible. -/ @[simp, stacks 00VM "This is the rightmost object of the fork diagram there."] def SecondObj : Type max v u := ∏ᶜ fun fg : (Σ Y, { f : Y ⟶ X // R f }) × Σ Z, { g : Z ⟶ X // R g } => haveI := Presieve.hasPullbacks.has_pullbacks fg.1.2.2 fg.2.2.2 P.obj (op (pullback fg.1.2.1 fg.2.2.1)) /-- The map `pr₀*` of the Stacks entry. -/ @[stacks 00VM "This is the map `pr₀*` there."] def firstMap : FirstObj P R ⟶ SecondObj P R := Pi.lift fun fg => haveI := Presieve.hasPullbacks.has_pullbacks fg.1.2.2 fg.2.2.2 Pi.π _ _ ≫ P.map (pullback.fst _ _).op instance [HasPullbacks C] : Inhabited (SecondObj P (⊥ : Presieve X)) := ⟨firstMap _ _ default⟩ /-- The map `pr₁*` of the Stacks entry. -/ @[stacks 00VM "This is the map `pr₁*` there."] def secondMap : FirstObj P R ⟶ SecondObj P R := Pi.lift fun fg => haveI := Presieve.hasPullbacks.has_pullbacks fg.1.2.2 fg.2.2.2 Pi.π _ _ ≫ P.map (pullback.snd _ _).op theorem w : forkMap P R ≫ firstMap P R = forkMap P R ≫ secondMap P R := by dsimp ext fg simp only [firstMap, secondMap, forkMap] simp only [limit.lift_π, limit.lift_π_assoc, assoc, Fan.mk_π_app] haveI := Presieve.hasPullbacks.has_pullbacks fg.1.2.2 fg.2.2.2 rw [← P.map_comp, ← op_comp, pullback.condition] simp /-- The family of elements given by `x : FirstObj P S` is compatible iff `firstMap` and `secondMap` map it to the same point. -/ theorem compatible_iff (x : FirstObj P R) : ((firstObjEqFamily P R).hom x).Compatible ↔ firstMap P R x = secondMap P R x := by rw [Presieve.pullbackCompatible_iff] constructor · intro t apply Limits.Types.limit_ext rintro ⟨⟨Y, f, hf⟩, Z, g, hg⟩ simpa [firstMap, secondMap] using t hf hg · intro t Y Z f g hf hg rw [Types.limit_ext_iff'] at t simpa [firstMap, secondMap] using t ⟨⟨⟨Y, f, hf⟩, Z, g, hg⟩⟩ /-- `P` is a sheaf for `R`, iff the fork given by `w` is an equalizer. -/ @[stacks 00VM] theorem sheaf_condition : R.IsSheafFor P ↔ Nonempty (IsLimit (Fork.ofι _ (w P R))) := by rw [Types.type_equalizer_iff_unique, ← Equiv.forall_congr_right (firstObjEqFamily P R).toEquiv.symm] simp_rw [← compatible_iff, ← Iso.toEquiv_fun, Equiv.apply_symm_apply] apply forall₂_congr intro x _ apply existsUnique_congr intro t rw [Equiv.eq_symm_apply] constructor · intro q funext Y f hf simpa [forkMap] using q _ _ · intro q Y f hf rw [← q] simp [forkMap] namespace Arrows variable (P : Cᵒᵖ ⥤ Type w) {X : C} (R : Presieve X) (S : Sieve X) open Presieve variable {B : C} {I : Type t} [Small.{w} I] (X : I → C) (π : (i : I) → X i ⟶ B) [(Presieve.ofArrows X π).hasPullbacks] /-- The middle object of the fork diagram of the Stacks entry. The difference between this and `Equalizer.FirstObj P (ofArrows X π)` arises if the family of arrows `π` contains duplicates. The `Presieve.ofArrows` doesn't see those. -/ @[stacks 00VM "The middle object of the fork diagram there."] def FirstObj : Type w := ∏ᶜ (fun i ↦ P.obj (op (X i))) @[ext] lemma FirstObj.ext (z₁ z₂ : FirstObj P X) (h : ∀ i, (Pi.π _ i : FirstObj P X ⟶ _) z₁ = (Pi.π _ i : FirstObj P X ⟶ _) z₂) : z₁ = z₂ := by apply Limits.Types.limit_ext rintro ⟨i⟩ exact h i /-- The rightmost object of the fork diagram of the Stacks entry. The difference between this and `Equalizer.Presieve.SecondObj P (ofArrows X π)` arises if the family of arrows `π` contains duplicates. The `Presieve.ofArrows` doesn't see those. -/ @[stacks 00VM "The rightmost object of the fork diagram there."] def SecondObj : Type w := ∏ᶜ (fun (ij : I × I) ↦ P.obj (op (pullback (π ij.1) (π ij.2)))) @[ext] lemma SecondObj.ext (z₁ z₂ : SecondObj P X π) (h : ∀ ij, (Pi.π _ ij : SecondObj P X π ⟶ _) z₁ = (Pi.π _ ij : SecondObj P X π ⟶ _) z₂) : z₁ = z₂ := by apply Limits.Types.limit_ext rintro ⟨i⟩ exact h i /-- The left morphism of the fork diagram. -/ def forkMap : P.obj (op B) ⟶ FirstObj P X := Pi.lift (fun i ↦ P.map (π i).op) /-- The first of the two parallel morphisms of the fork diagram, induced by the first projection in each pullback. -/ def firstMap : FirstObj P X ⟶ SecondObj P X π := Pi.lift fun _ => Pi.π _ _ ≫ P.map (pullback.fst _ _).op /-- The second of the two parallel morphisms of the fork diagram, induced by the second projection in each pullback. -/ def secondMap : FirstObj P X ⟶ SecondObj P X π := Pi.lift fun _ => Pi.π _ _ ≫ P.map (pullback.snd _ _).op theorem w : forkMap P X π ≫ firstMap P X π = forkMap P X π ≫ secondMap P X π := by ext x ij simp only [firstMap, secondMap, forkMap, types_comp_apply, Types.pi_lift_π_apply, ← FunctorToTypes.map_comp_apply, ← op_comp, pullback.condition] /-- The family of elements given by `x : FirstObj P S` is compatible iff `firstMap` and `secondMap` map it to the same point. See `CategoryTheory.Equalizer.Presieve.Arrows.compatible_iff_of_small` for a version with less universe assumptions. -/ theorem compatible_iff {I : Type w} (X : I → C) (π : (i : I) → X i ⟶ B) [(Presieve.ofArrows X π).hasPullbacks] (x : FirstObj P X) : (Arrows.Compatible P π ((Types.productIso _).hom x)) ↔ firstMap P X π x = secondMap P X π x := by rw [Arrows.pullbackCompatible_iff] constructor · intro t ext ij simpa [firstMap, secondMap] using t ij.1 ij.2 · intro t i j apply_fun Pi.π (fun (ij : I × I) ↦ P.obj (op (pullback (π ij.1) (π ij.2)))) ⟨i, j⟩ at t simpa [firstMap, secondMap] using t /-- Version of `CategoryTheory.Equalizer.Presieve.Arrows.compatible_iff` for a small indexing type. -/ lemma compatible_iff_of_small (x : FirstObj P X) : (Arrows.Compatible P π ((equivShrink _).symm ((Types.Small.productIso _).hom x))) ↔ firstMap P X π x = secondMap P X π x := by rw [Arrows.pullbackCompatible_iff] refine ⟨fun t ↦ ?_, fun t i j ↦ ?_⟩ · ext ij simpa [firstMap, secondMap] using t ij.1 ij.2 · apply_fun Pi.π (fun (ij : I × I) ↦ P.obj (op (pullback (π ij.1) (π ij.2)))) ⟨i, j⟩ at t simpa [firstMap, secondMap] using t /-- `P` is a sheaf for `Presieve.ofArrows X π`, iff the fork given by `w` is an equalizer. -/ @[stacks 00VM] theorem sheaf_condition : (Presieve.ofArrows X π).IsSheafFor P ↔ Nonempty (IsLimit (Fork.ofι (forkMap P X π) (w P X π))) := by rw [Types.type_equalizer_iff_unique, isSheafFor_arrows_iff] simp only [FirstObj] rw [← Equiv.forall_congr_right ((equivShrink _).trans (Types.Small.productIso _).toEquiv.symm)] simp_rw [← compatible_iff_of_small, ← Iso.toEquiv_fun, Equiv.trans_apply, Equiv.apply_symm_apply, Equiv.symm_apply_apply] apply forall₂_congr intro x _ apply existsUnique_congr intro t rw [Equiv.eq_symm_apply, ← Equiv.symm_apply_eq] constructor · intro q funext i simpa [forkMap] using q i · intro q i rw [← q] simp [forkMap] end Arrows /-- The sheaf condition for a single morphism is the same as the canonical fork diagram being limiting. -/ lemma isSheafFor_singleton_iff {F : Cᵒᵖ ⥤ Type*} {X Y : C} {f : X ⟶ Y} (c : PullbackCone f f) (hc : IsLimit c) : Presieve.IsSheafFor F (.singleton f) ↔ Nonempty (IsLimit (Fork.ofι (F.map f.op) (f := F.map c.fst.op) (g := F.map c.snd.op) (by simp [← Functor.map_comp, ← op_comp, c.condition]))) := by have h (x : F.obj (op X)) : (∀ {Z : C} (p₁ p₂ : Z ⟶ X), p₁ ≫ f = p₂ ≫ f → F.map p₁.op x = F.map p₂.op x) ↔ F.map c.fst.op x = F.map c.snd.op x := by refine ⟨fun H ↦ H _ _ c.condition, fun H Z p₁ p₂ h ↦ ?_⟩ rw [← PullbackCone.IsLimit.lift_fst hc _ _ h, op_comp, FunctorToTypes.map_comp_apply, H] simp [← FunctorToTypes.map_comp_apply, ← op_comp] rw [Types.type_equalizer_iff_unique, Presieve.isSheafFor_singleton] simp_rw [h] /-- Special case of `isSheafFor_singleton_iff` with `c = pullback.cone f f`. -/ lemma isSheafFor_singleton_iff_of_hasPullback {F : Cᵒᵖ ⥤ Type*} {X Y : C} {f : X ⟶ Y} [HasPullback f f] : Presieve.IsSheafFor F (.singleton f) ↔ Nonempty (IsLimit (Fork.ofι (F.map f.op) (f := F.map (pullback.fst f f).op) (g := F.map (pullback.snd f f).op) (by simp [← Functor.map_comp, ← op_comp, pullback.condition]))) := isSheafFor_singleton_iff (pullback.cone f f) (pullback.isLimit f f) end Presieve end end Equalizer end CategoryTheory
InnerProduct.lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import Mathlib.Analysis.Calculus.Conformal.NormedSpace import Mathlib.Analysis.InnerProductSpace.ConformalLinearMap /-! # Conformal maps between inner product spaces A function between inner product spaces which has a derivative at `x` is conformal at `x` iff the derivative preserves inner products up to a scalar multiple. -/ noncomputable section variable {E F : Type*} variable [NormedAddCommGroup E] [NormedAddCommGroup F] variable [InnerProductSpace ℝ E] [InnerProductSpace ℝ F] open RealInnerProductSpace /-- A real differentiable map `f` is conformal at point `x` if and only if its differential `fderiv ℝ f x` at that point scales every inner product by a positive scalar. -/ theorem conformalAt_iff' {f : E → F} {x : E} : ConformalAt f x ↔ ∃ c : ℝ, 0 < c ∧ ∀ u v : E, ⟪fderiv ℝ f x u, fderiv ℝ f x v⟫ = c * ⟪u, v⟫ := by rw [conformalAt_iff_isConformalMap_fderiv, isConformalMap_iff] /-- A real differentiable map `f` is conformal at point `x` if and only if its differential `f'` at that point scales every inner product by a positive scalar. -/ theorem conformalAt_iff {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : HasFDerivAt f f' x) : ConformalAt f x ↔ ∃ c : ℝ, 0 < c ∧ ∀ u v : E, ⟪f' u, f' v⟫ = c * ⟪u, v⟫ := by simp only [conformalAt_iff', h.fderiv] /-- The conformal factor of a conformal map at some point `x`. Some authors refer to this function as the characteristic function of the conformal map. -/ def conformalFactorAt {f : E → F} {x : E} (h : ConformalAt f x) : ℝ := Classical.choose (conformalAt_iff'.mp h) theorem conformalFactorAt_pos {f : E → F} {x : E} (h : ConformalAt f x) : 0 < conformalFactorAt h := (Classical.choose_spec <| conformalAt_iff'.mp h).1 theorem conformalFactorAt_inner_eq_mul_inner' {f : E → F} {x : E} (h : ConformalAt f x) (u v : E) : ⟪(fderiv ℝ f x) u, (fderiv ℝ f x) v⟫ = (conformalFactorAt h : ℝ) * ⟪u, v⟫ := (Classical.choose_spec <| conformalAt_iff'.mp h).2 u v theorem conformalFactorAt_inner_eq_mul_inner {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : HasFDerivAt f f' x) (H : ConformalAt f x) (u v : E) : ⟪f' u, f' v⟫ = (conformalFactorAt H : ℝ) * ⟪u, v⟫ := H.differentiableAt.hasFDerivAt.unique h ▸ conformalFactorAt_inner_eq_mul_inner' H u v
Subsingleton.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.Order.Filter.CountablyGenerated import Mathlib.Order.Filter.Prod import Mathlib.Order.Filter.Ultrafilter.Defs /-! # Subsingleton filters We say that a filter `l` is a *subsingleton* if there exists a subsingleton set `s ∈ l`. Equivalently, `l` is either `⊥` or `pure a` for some `a`. -/ open Set variable {α β : Type*} {l : Filter α} namespace Filter /-- We say that a filter is a *subsingleton* if there exists a subsingleton set that belongs to the filter. -/ protected def Subsingleton (l : Filter α) : Prop := ∃ s ∈ l, Set.Subsingleton s theorem HasBasis.subsingleton_iff {ι : Sort*} {p : ι → Prop} {s : ι → Set α} (h : l.HasBasis p s) : l.Subsingleton ↔ ∃ i, p i ∧ (s i).Subsingleton := h.exists_iff fun _ _ hsub h ↦ h.anti hsub theorem Subsingleton.anti {l'} (hl : l.Subsingleton) (hl' : l' ≤ l) : l'.Subsingleton := let ⟨s, hsl, hs⟩ := hl; ⟨s, hl' hsl, hs⟩ @[nontriviality] theorem Subsingleton.of_subsingleton [Subsingleton α] : l.Subsingleton := ⟨univ, univ_mem, subsingleton_univ⟩ theorem Subsingleton.map (hl : l.Subsingleton) (f : α → β) : (map f l).Subsingleton := let ⟨s, hsl, hs⟩ := hl; ⟨f '' s, image_mem_map hsl, hs.image f⟩ theorem Subsingleton.prod (hl : l.Subsingleton) {l' : Filter β} (hl' : l'.Subsingleton) : (l ×ˢ l').Subsingleton := let ⟨s, hsl, hs⟩ := hl; let ⟨t, htl', ht⟩ := hl'; ⟨s ×ˢ t, prod_mem_prod hsl htl', hs.prod ht⟩ @[simp] theorem subsingleton_pure {a : α} : Filter.Subsingleton (pure a) := ⟨{a}, rfl, subsingleton_singleton⟩ @[simp] theorem subsingleton_bot : Filter.Subsingleton (⊥ : Filter α) := ⟨∅, trivial, subsingleton_empty⟩ /-- A nontrivial subsingleton filter is equal to `pure a` for some `a`. -/ theorem Subsingleton.exists_eq_pure [l.NeBot] (hl : l.Subsingleton) : ∃ a, l = pure a := by rcases hl with ⟨s, hsl, hs⟩ rcases exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨nonempty_of_mem hsl, hs⟩ with ⟨a, rfl⟩ refine ⟨a, (NeBot.le_pure_iff ‹_›).1 ?_⟩ rwa [le_pure_iff] /-- A filter is a subsingleton iff it is equal to `⊥` or to `pure a` for some `a`. -/ theorem subsingleton_iff_bot_or_pure : l.Subsingleton ↔ l = ⊥ ∨ ∃ a, l = pure a := by refine ⟨fun hl ↦ ?_, ?_⟩ · exact (eq_or_neBot l).imp_right (@Subsingleton.exists_eq_pure _ _ · hl) · rintro (rfl | ⟨a, rfl⟩) <;> simp /-- In a nonempty type, a filter is a subsingleton iff it is less than or equal to a pure filter. -/ theorem subsingleton_iff_exists_le_pure [Nonempty α] : l.Subsingleton ↔ ∃ a, l ≤ pure a := by rcases eq_or_neBot l with rfl | hbot · simp · simp [subsingleton_iff_bot_or_pure, ← hbot.le_pure_iff, hbot.ne] theorem subsingleton_iff_exists_singleton_mem [Nonempty α] : l.Subsingleton ↔ ∃ a, {a} ∈ l := by simp only [subsingleton_iff_exists_le_pure, le_pure_iff] /-- A subsingleton filter on a nonempty type is less than or equal to `pure a` for some `a`. -/ alias ⟨Subsingleton.exists_le_pure, _⟩ := subsingleton_iff_exists_le_pure lemma Subsingleton.isCountablyGenerated (hl : l.Subsingleton) : IsCountablyGenerated l := by rcases subsingleton_iff_bot_or_pure.1 hl with rfl | ⟨x, rfl⟩ · exact isCountablyGenerated_bot · exact isCountablyGenerated_pure x end Filter
CardinalInter.lean
/- Copyright (c) 2024 Josha Dekker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Josha Dekker -/ import Mathlib.Order.Filter.Tendsto import Mathlib.Order.Filter.Finite import Mathlib.Order.Filter.CountableInter import Mathlib.SetTheory.Cardinal.Regular import Mathlib.Tactic.Linarith /-! # Filters with a cardinal intersection property In this file we define `CardinalInterFilter l c` to be the class of filters with the following property: for any collection of sets `s ∈ l` with cardinality strictly less than `c`, their intersection belongs to `l` as well. # Main results * `Filter.cardinalInterFilter_aleph0` establishes that every filter `l` is a `CardinalInterFilter l ℵ₀` * `CardinalInterFilter.toCountableInterFilter` establishes that every `CardinalInterFilter l c` with `c > ℵ₀` is a `CountableInterFilter`. * `CountableInterFilter.toCardinalInterFilter` establishes that every `CountableInterFilter l` is a `CardinalInterFilter l ℵ₁`. * `CardinalInterFilter.of_CardinalInterFilter_of_lt` establishes that we have `CardinalInterFilter l c` → `CardinalInterFilter l a` for all `a < c`. ## Tags filter, cardinal -/ open Set Filter Cardinal universe u variable {ι : Type u} {α β : Type u} {c : Cardinal.{u}} /-- A filter `l` has the cardinal `c` intersection property if for any collection of less than `c` sets `s ∈ l`, their intersection belongs to `l` as well. -/ class CardinalInterFilter (l : Filter α) (c : Cardinal.{u}) : Prop where /-- For a collection of sets `s ∈ l` with cardinality below c, their intersection belongs to `l` as well. -/ cardinal_sInter_mem : ∀ S : Set (Set α), (#S < c) → (∀ s ∈ S, s ∈ l) → ⋂₀ S ∈ l variable {l : Filter α} theorem cardinal_sInter_mem {S : Set (Set α)} [CardinalInterFilter l c] (hSc : #S < c) : ⋂₀ S ∈ l ↔ ∀ s ∈ S, s ∈ l := ⟨fun hS _s hs => mem_of_superset hS (sInter_subset_of_mem hs), CardinalInterFilter.cardinal_sInter_mem _ hSc⟩ /-- Every filter is a CardinalInterFilter with c = ℵ₀ -/ theorem _root_.Filter.cardinalInterFilter_aleph0 (l : Filter α) : CardinalInterFilter l ℵ₀ where cardinal_sInter_mem := by simp_all only [lt_aleph0_iff_subtype_finite, setOf_mem_eq, sInter_mem, implies_true] /-- Every CardinalInterFilter with c > ℵ₀ is a CountableInterFilter -/ theorem CardinalInterFilter.toCountableInterFilter (l : Filter α) [CardinalInterFilter l c] (hc : ℵ₀ < c) : CountableInterFilter l where countable_sInter_mem S hS a := CardinalInterFilter.cardinal_sInter_mem S (lt_of_le_of_lt (Set.Countable.le_aleph0 hS) hc) a /-- Every CountableInterFilter is a CardinalInterFilter with c = ℵ₁ -/ instance CountableInterFilter.toCardinalInterFilter (l : Filter α) [CountableInterFilter l] : CardinalInterFilter l ℵ₁ where cardinal_sInter_mem S hS a := CountableInterFilter.countable_sInter_mem S ((countable_iff_lt_aleph_one S).mpr hS) a theorem cardinalInterFilter_aleph_one_iff : CardinalInterFilter l ℵ₁ ↔ CountableInterFilter l := ⟨fun _ ↦ ⟨fun S h a ↦ CardinalInterFilter.cardinal_sInter_mem S ((countable_iff_lt_aleph_one S).1 h) a⟩, fun _ ↦ CountableInterFilter.toCardinalInterFilter l⟩ /-- Every CardinalInterFilter for some c also is a CardinalInterFilter for some a ≤ c -/ theorem CardinalInterFilter.of_cardinalInterFilter_of_le (l : Filter α) [CardinalInterFilter l c] {a : Cardinal.{u}} (hac : a ≤ c) : CardinalInterFilter l a where cardinal_sInter_mem S hS a := CardinalInterFilter.cardinal_sInter_mem S (lt_of_lt_of_le hS hac) a theorem CardinalInterFilter.of_cardinalInterFilter_of_lt (l : Filter α) [CardinalInterFilter l c] {a : Cardinal.{u}} (hac : a < c) : CardinalInterFilter l a := CardinalInterFilter.of_cardinalInterFilter_of_le l (hac.le) namespace Filter variable [CardinalInterFilter l c] theorem cardinal_iInter_mem {s : ι → Set α} (hic : #ι < c) : (⋂ i, s i) ∈ l ↔ ∀ i, s i ∈ l := by rw [← sInter_range _] apply (cardinal_sInter_mem (lt_of_le_of_lt Cardinal.mk_range_le hic)).trans exact forall_mem_range theorem cardinal_bInter_mem {S : Set ι} (hS : #S < c) {s : ∀ i ∈ S, Set α} : (⋂ i, ⋂ hi : i ∈ S, s i ‹_›) ∈ l ↔ ∀ i, ∀ hi : i ∈ S, s i ‹_› ∈ l := by rw [biInter_eq_iInter] exact (cardinal_iInter_mem hS).trans Subtype.forall theorem eventually_cardinal_forall {p : α → ι → Prop} (hic : #ι < c) : (∀ᶠ x in l, ∀ i, p x i) ↔ ∀ i, ∀ᶠ x in l, p x i := by simp only [Filter.Eventually, setOf_forall] exact cardinal_iInter_mem hic theorem eventually_cardinal_ball {S : Set ι} (hS : #S < c) {p : α → ∀ i ∈ S, Prop} : (∀ᶠ x in l, ∀ i hi, p x i hi) ↔ ∀ i hi, ∀ᶠ x in l, p x i hi := by simp only [Filter.Eventually, setOf_forall] exact cardinal_bInter_mem hS theorem EventuallyLE.cardinal_iUnion {s t : ι → Set α} (hic : #ι < c) (h : ∀ i, s i ≤ᶠ[l] t i) : ⋃ i, s i ≤ᶠ[l] ⋃ i, t i := ((eventually_cardinal_forall hic).2 h).mono fun _ hst hs => mem_iUnion.2 <| (mem_iUnion.1 hs).imp hst theorem EventuallyEq.cardinal_iUnion {s t : ι → Set α} (hic : #ι < c) (h : ∀ i, s i =ᶠ[l] t i) : ⋃ i, s i =ᶠ[l] ⋃ i, t i := (EventuallyLE.cardinal_iUnion hic fun i => (h i).le).antisymm (EventuallyLE.cardinal_iUnion hic fun i => (h i).symm.le) theorem EventuallyLE.cardinal_bUnion {S : Set ι} (hS : #S < c) {s t : ∀ i ∈ S, Set α} (h : ∀ i hi, s i hi ≤ᶠ[l] t i hi) : ⋃ i ∈ S, s i ‹_› ≤ᶠ[l] ⋃ i ∈ S, t i ‹_› := by simp only [biUnion_eq_iUnion] exact EventuallyLE.cardinal_iUnion hS fun i => h i i.2 theorem EventuallyEq.cardinal_bUnion {S : Set ι} (hS : #S < c) {s t : ∀ i ∈ S, Set α} (h : ∀ i hi, s i hi =ᶠ[l] t i hi) : ⋃ i ∈ S, s i ‹_› =ᶠ[l] ⋃ i ∈ S, t i ‹_› := (EventuallyLE.cardinal_bUnion hS fun i hi => (h i hi).le).antisymm (EventuallyLE.cardinal_bUnion hS fun i hi => (h i hi).symm.le) theorem EventuallyLE.cardinal_iInter {s t : ι → Set α} (hic : #ι < c) (h : ∀ i, s i ≤ᶠ[l] t i) : ⋂ i, s i ≤ᶠ[l] ⋂ i, t i := ((eventually_cardinal_forall hic).2 h).mono fun _ hst hs => mem_iInter.2 fun i => hst _ (mem_iInter.1 hs i) theorem EventuallyEq.cardinal_iInter {s t : ι → Set α} (hic : #ι < c) (h : ∀ i, s i =ᶠ[l] t i) : ⋂ i, s i =ᶠ[l] ⋂ i, t i := (EventuallyLE.cardinal_iInter hic fun i => (h i).le).antisymm (EventuallyLE.cardinal_iInter hic fun i => (h i).symm.le) theorem EventuallyLE.cardinal_bInter {S : Set ι} (hS : #S < c) {s t : ∀ i ∈ S, Set α} (h : ∀ i hi, s i hi ≤ᶠ[l] t i hi) : ⋂ i ∈ S, s i ‹_› ≤ᶠ[l] ⋂ i ∈ S, t i ‹_› := by simp only [biInter_eq_iInter] exact EventuallyLE.cardinal_iInter hS fun i => h i i.2 theorem EventuallyEq.cardinal_bInter {S : Set ι} (hS : #S < c) {s t : ∀ i ∈ S, Set α} (h : ∀ i hi, s i hi =ᶠ[l] t i hi) : ⋂ i ∈ S, s i ‹_› =ᶠ[l] ⋂ i ∈ S, t i ‹_› := (EventuallyLE.cardinal_bInter hS fun i hi => (h i hi).le).antisymm (EventuallyLE.cardinal_bInter hS fun i hi => (h i hi).symm.le) /-- Construct a filter with cardinal `c` intersection property. This constructor deduces `Filter.univ_sets` and `Filter.inter_sets` from the cardinal `c` intersection property. -/ def ofCardinalInter (l : Set (Set α)) (hc : 2 < c) (hl : ∀ S : Set (Set α), (#S < c) → S ⊆ l → ⋂₀ S ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) : Filter α where sets := l univ_sets := sInter_empty ▸ hl ∅ (mk_eq_zero (∅ : Set (Set α)) ▸ lt_trans zero_lt_two hc) (empty_subset _) sets_of_superset := h_mono _ _ inter_sets {s t} hs ht := sInter_pair s t ▸ by apply hl _ (?_) (insert_subset_iff.2 ⟨hs, singleton_subset_iff.2 ht⟩) have : #({s, t} : Set (Set α)) ≤ 2 := by calc _ ≤ #({t} : Set (Set α)) + 1 := Cardinal.mk_insert_le _ = 2 := by norm_num exact lt_of_le_of_lt this hc instance cardinalInter_ofCardinalInter (l : Set (Set α)) (hc : 2 < c) (hl : ∀ S : Set (Set α), (#S < c) → S ⊆ l → ⋂₀ S ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) : CardinalInterFilter (Filter.ofCardinalInter l hc hl h_mono) c := ⟨hl⟩ @[simp] theorem mem_ofCardinalInter {l : Set (Set α)} (hc : 2 < c) (hl : ∀ S : Set (Set α), (#S < c) → S ⊆ l → ⋂₀ S ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) {s : Set α} : s ∈ Filter.ofCardinalInter l hc hl h_mono ↔ s ∈ l := Iff.rfl /-- Construct a filter with cardinal `c` intersection property. Similarly to `Filter.comk`, a set belongs to this filter if its complement satisfies the property. Similarly to `Filter.ofCardinalInter`, this constructor deduces some properties from the cardinal `c` intersection property which becomes the cardinal `c` union property because we take complements of all sets. -/ def ofCardinalUnion (l : Set (Set α)) (hc : 2 < c) (hUnion : ∀ S : Set (Set α), (#S < c) → (∀ s ∈ S, s ∈ l) → ⋃₀ S ∈ l) (hmono : ∀ t ∈ l, ∀ s ⊆ t, s ∈ l) : Filter α := by refine .ofCardinalInter {s | sᶜ ∈ l} hc (fun S hSc hSp ↦ ?_) fun s t ht hsub ↦ ?_ · rw [mem_setOf_eq, compl_sInter] apply hUnion (compl '' S) (lt_of_le_of_lt mk_image_le hSc) intro s hs rw [mem_image] at hs rcases hs with ⟨t, ht, rfl⟩ apply hSp ht · rw [mem_setOf_eq] rw [← compl_subset_compl] at hsub exact hmono sᶜ ht tᶜ hsub instance cardinalInter_ofCardinalUnion (l : Set (Set α)) (hc : 2 < c) (h₁ h₂) : CardinalInterFilter (Filter.ofCardinalUnion l hc h₁ h₂) c := cardinalInter_ofCardinalInter .. @[simp] theorem mem_ofCardinalUnion {l : Set (Set α)} (hc : 2 < c) {hunion hmono s} : s ∈ ofCardinalUnion l hc hunion hmono ↔ l sᶜ := Iff.rfl instance cardinalInterFilter_principal (s : Set α) : CardinalInterFilter (𝓟 s) c := ⟨fun _ _ hS => subset_sInter hS⟩ instance cardinalInterFilter_bot : CardinalInterFilter (⊥ : Filter α) c := by rw [← principal_empty] apply cardinalInterFilter_principal instance cardinalInterFilter_top : CardinalInterFilter (⊤ : Filter α) c := by rw [← principal_univ] apply cardinalInterFilter_principal instance (l : Filter β) [CardinalInterFilter l c] (f : α → β) : CardinalInterFilter (comap f l) c := by refine ⟨fun S hSc hS => ?_⟩ choose! t htl ht using hS refine ⟨_, (cardinal_bInter_mem hSc).2 htl, ?_⟩ simpa [preimage_iInter] using iInter₂_mono ht instance (l : Filter α) [CardinalInterFilter l c] (f : α → β) : CardinalInterFilter (map f l) c := by refine ⟨fun S hSc hS => ?_⟩ simp only [mem_map, sInter_eq_biInter, preimage_iInter₂] at hS ⊢ exact (cardinal_bInter_mem hSc).2 hS /-- Infimum of two `CardinalInterFilter`s is a `CardinalInterFilter`. This is useful, e.g., to automatically get an instance for `residual α ⊓ 𝓟 s`. -/ instance cardinalInterFilter_inf_eq (l₁ l₂ : Filter α) [CardinalInterFilter l₁ c] [CardinalInterFilter l₂ c] : CardinalInterFilter (l₁ ⊓ l₂) c := by refine ⟨fun S hSc hS => ?_⟩ choose s hs t ht hst using hS replace hs : (⋂ i ∈ S, s i ‹_›) ∈ l₁ := (cardinal_bInter_mem hSc).2 hs replace ht : (⋂ i ∈ S, t i ‹_›) ∈ l₂ := (cardinal_bInter_mem hSc).2 ht refine mem_of_superset (inter_mem_inf hs ht) (subset_sInter fun i hi => ?_) rw [hst i hi] apply inter_subset_inter <;> exact iInter_subset_of_subset i (iInter_subset _ _) instance cardinalInterFilter_inf (l₁ l₂ : Filter α) {c₁ c₂ : Cardinal.{u}} [CardinalInterFilter l₁ c₁] [CardinalInterFilter l₂ c₂] : CardinalInterFilter (l₁ ⊓ l₂) (c₁ ⊓ c₂) := by have : CardinalInterFilter l₁ (c₁ ⊓ c₂) := CardinalInterFilter.of_cardinalInterFilter_of_le l₁ inf_le_left have : CardinalInterFilter l₂ (c₁ ⊓ c₂) := CardinalInterFilter.of_cardinalInterFilter_of_le l₂ inf_le_right exact cardinalInterFilter_inf_eq _ _ /-- Supremum of two `CardinalInterFilter`s is a `CardinalInterFilter`. -/ instance cardinalInterFilter_sup_eq (l₁ l₂ : Filter α) [CardinalInterFilter l₁ c] [CardinalInterFilter l₂ c] : CardinalInterFilter (l₁ ⊔ l₂) c := by refine ⟨fun S hSc hS => ⟨?_, ?_⟩⟩ <;> refine (cardinal_sInter_mem hSc).2 fun s hs => ?_ exacts [(hS s hs).1, (hS s hs).2] instance cardinalInterFilter_sup (l₁ l₂ : Filter α) {c₁ c₂ : Cardinal.{u}} [CardinalInterFilter l₁ c₁] [CardinalInterFilter l₂ c₂] : CardinalInterFilter (l₁ ⊔ l₂) (c₁ ⊓ c₂) := by have : CardinalInterFilter l₁ (c₁ ⊓ c₂) := CardinalInterFilter.of_cardinalInterFilter_of_le l₁ inf_le_left have : CardinalInterFilter l₂ (c₁ ⊓ c₂) := CardinalInterFilter.of_cardinalInterFilter_of_le l₂ inf_le_right exact cardinalInterFilter_sup_eq _ _ variable (g : Set (Set α)) /-- `Filter.CardinalGenerateSets c g` is the (sets of the) greatest `cardinalInterFilter c` containing `g`. -/ inductive CardinalGenerateSets : Set α → Prop | basic {s : Set α} : s ∈ g → CardinalGenerateSets s | univ : CardinalGenerateSets univ | superset {s t : Set α} : CardinalGenerateSets s → s ⊆ t → CardinalGenerateSets t | sInter {S : Set (Set α)} : (#S < c) → (∀ s ∈ S, CardinalGenerateSets s) → CardinalGenerateSets (⋂₀ S) /-- `Filter.cardinalGenerate c g` is the greatest `cardinalInterFilter c` containing `g`. -/ def cardinalGenerate (hc : 2 < c) : Filter α := ofCardinalInter (CardinalGenerateSets g) hc (fun _ => CardinalGenerateSets.sInter) fun _ _ => CardinalGenerateSets.superset lemma cardinalInter_ofCardinalGenerate (hc : 2 < c) : CardinalInterFilter (cardinalGenerate g hc) c := by delta cardinalGenerate apply cardinalInter_ofCardinalInter _ _ _ variable {g} /-- A set is in the `cardinalInterFilter` generated by `g` if and only if it contains an intersection of `c` elements of `g`. -/ theorem mem_cardinaleGenerate_iff {s : Set α} {hreg : c.IsRegular} : s ∈ cardinalGenerate g (IsRegular.nat_lt hreg 2) ↔ ∃ S : Set (Set α), S ⊆ g ∧ (#S < c) ∧ ⋂₀ S ⊆ s := by constructor <;> intro h · induction h with | @basic s hs => refine ⟨{s}, singleton_subset_iff.mpr hs, ?_⟩ simpa [subset_refl] using IsRegular.nat_lt hreg 1 | univ => exact ⟨∅, ⟨empty_subset g, mk_eq_zero (∅ : Set <| Set α) ▸ IsRegular.nat_lt hreg 0, by simp⟩⟩ | superset _ _ ih => exact Exists.imp (by tauto) ih | @sInter S Sct _ ih => choose T Tg Tct hT using ih refine ⟨⋃ (s) (H : s ∈ S), T s H, by simpa, (Cardinal.card_biUnion_lt_iff_forall_of_isRegular hreg Sct).2 Tct, ?_⟩ apply subset_sInter apply fun s H => subset_trans (sInter_subset_sInter (subset_iUnion₂ s H)) (hT s H) rcases h with ⟨S, Sg, Sct, hS⟩ have : CardinalInterFilter (cardinalGenerate g (IsRegular.nat_lt hreg 2)) c := cardinalInter_ofCardinalGenerate _ _ exact mem_of_superset ((cardinal_sInter_mem Sct).mpr (fun s H => CardinalGenerateSets.basic (Sg H))) hS theorem le_cardinalGenerate_iff_of_cardinalInterFilter {f : Filter α} [CardinalInterFilter f c] (hc : 2 < c) : f ≤ cardinalGenerate g hc ↔ g ⊆ f.sets := by constructor <;> intro h · exact subset_trans (fun s => CardinalGenerateSets.basic) h intro s hs induction hs with | basic hs => exact h hs | univ => exact univ_mem | superset _ st ih => exact mem_of_superset ih st | sInter Sct _ ih => exact (cardinal_sInter_mem Sct).mpr ih /-- `cardinalGenerate g hc` is the greatest `cardinalInterFilter c` containing `g`. -/ theorem cardinalGenerate_isGreatest (hc : 2 < c) : IsGreatest { f : Filter α | CardinalInterFilter f c ∧ g ⊆ f.sets } (cardinalGenerate g hc) := by refine ⟨⟨cardinalInter_ofCardinalGenerate _ _, fun s => CardinalGenerateSets.basic⟩, ?_⟩ rintro f ⟨fct, hf⟩ rwa [le_cardinalGenerate_iff_of_cardinalInterFilter] end Filter
IsIso.lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.AlgebraicGeometry.Morphisms.OpenImmersion /-! # Being an isomorphism is local at the target -/ open CategoryTheory MorphismProperty namespace AlgebraicGeometry lemma isomorphisms_eq_isOpenImmersion_inf_surjective : isomorphisms Scheme = (@IsOpenImmersion ⊓ @Surjective : MorphismProperty Scheme) := by ext exact (isIso_iff_isOpenImmersion _).trans (and_congr Iff.rfl ((TopCat.epi_iff_surjective _).trans (surjective_iff _).symm)) lemma isomorphisms_eq_stalkwise : isomorphisms Scheme = (isomorphisms TopCat).inverseImage Scheme.forgetToTop ⊓ stalkwise (fun f ↦ Function.Bijective f) := by rw [isomorphisms_eq_isOpenImmersion_inf_surjective, isOpenImmersion_eq_inf, surjective_eq_topologically, inf_right_comm] congr 1 ext X Y f exact ⟨fun H ↦ inferInstanceAs (IsIso (TopCat.isoOfHomeo (H.1.1.toHomeomorphOfSurjective H.2)).hom), fun (_ : IsIso f.base) ↦ let e := (TopCat.homeoOfIso <| asIso f.base); ⟨e.isOpenEmbedding, e.surjective⟩⟩ instance : IsLocalAtTarget (isomorphisms Scheme) := isomorphisms_eq_isOpenImmersion_inf_surjective ▸ inferInstance instance : HasAffineProperty (isomorphisms Scheme) fun X _ f _ ↦ IsAffine X ∧ IsIso (f.appTop) := by convert HasAffineProperty.of_isLocalAtTarget (isomorphisms Scheme) with X Y f hY exact ⟨fun ⟨_, _⟩ ↦ (arrow_mk_iso_iff (isomorphisms _) (arrowIsoSpecΓOfIsAffine f)).mpr (inferInstanceAs (IsIso (Spec.map (f.appTop)))), fun (_ : IsIso f) ↦ ⟨.of_isIso f, inferInstance⟩⟩ instance : IsLocalAtTarget (monomorphisms Scheme) := diagonal_isomorphisms (C := Scheme).symm ▸ inferInstance end AlgebraicGeometry
Units.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, Mario Carneiro, Johannes Hölzl -/ import Mathlib.Algebra.Order.Monoid.Defs import Mathlib.Algebra.Order.Monoid.Units /-! # The units of an ordered commutative monoid form an ordered commutative group -/ variable {α : Type*} /-- The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive /-- The units of an ordered commutative additive monoid form an ordered commutative additive group. -/] instance Units.isOrderedMonoid [CommMonoid α] [PartialOrder α] [IsOrderedMonoid α] : IsOrderedMonoid αˣ := { mul_le_mul_left := fun _ _ h _ => (mul_le_mul_left' (α := α) h _) }
SigmaComparison.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Topology.Category.CompHausLike.Limits /-! # The sigma-comparison map This file defines the map `CompHausLike.sigmaComparison` associated to a presheaf `X` on `CompHausLike P`, and a finite family `S₁,...,Sₙ` of spaces in `CompHausLike P`, where `P` is stable under taking finite disjoint unions. The map `sigmaComparison` is the canonical map `X(S₁ ⊔ ... ⊔ Sₙ) ⟶ X(S₁) × ... × X(Sₙ)` induced by the inclusion maps `Sᵢ ⟶ S₁ ⊔ ... ⊔ Sₙ`, and it is an isomorphism when `X` preserves finite products. -/ universe u w open CategoryTheory Limits namespace CompHausLike variable {P : TopCat.{u} → Prop} [HasExplicitFiniteCoproducts.{u} P] (X : (CompHausLike.{u} P)ᵒᵖ ⥤ Type max u w) [PreservesFiniteProducts X] {α : Type u} [Finite α] (σ : α → Type u) [∀ a, TopologicalSpace (σ a)] [∀ a, CompactSpace (σ a)] [∀ a, T2Space (σ a)] [∀ a, HasProp P (σ a)] instance : HasProp P (Σ (a : α), (σ a)) := HasExplicitFiniteCoproducts.hasProp (fun a ↦ of P (σ a)) /-- The comparison map from the value of a condensed set on a finite coproduct to the product of the values on the components. -/ def sigmaComparison : X.obj ⟨(of P ((a : α) × σ a))⟩ ⟶ ((a : α) → X.obj ⟨of P (σ a)⟩) := fun x a ↦ X.map (ofHom _ ⟨Sigma.mk a, continuous_sigmaMk⟩).op x theorem sigmaComparison_eq_comp_isos : sigmaComparison X σ = (X.mapIso (opCoproductIsoProduct' (finiteCoproduct.isColimit.{u, u} (fun a ↦ of P (σ a))) (productIsProduct fun x ↦ Opposite.op (of P (σ x))))).hom ≫ (PreservesProduct.iso X fun a ↦ ⟨of P (σ a)⟩).hom ≫ (Types.productIso.{u, max u w} fun a ↦ X.obj ⟨of P (σ a)⟩).hom := by ext x a simp only [Cofan.mk_pt, Fan.mk_pt, Functor.mapIso_hom, PreservesProduct.iso_hom, types_comp_apply, Types.productIso_hom_comp_eval_apply] have := congrFun (piComparison_comp_π X (fun a ↦ ⟨of P (σ a)⟩) a) simp only [types_comp_apply] at this rw [this, ← FunctorToTypes.map_comp_apply] simp only [sigmaComparison] apply congrFun congr 2 rw [← opCoproductIsoProduct_inv_comp_ι] simp only [Opposite.unop_op, unop_comp, Quiver.Hom.unop_op, Category.assoc] simp only [opCoproductIsoProduct, ← unop_comp, opCoproductIsoProduct'_comp_self] erw [IsColimit.fac] rfl instance isIsoSigmaComparison : IsIso <| sigmaComparison X σ := by rw [sigmaComparison_eq_comp_isos] infer_instance end CompHausLike
BigZariski.lean
/- Copyright (c) 2023 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou, Adam Topaz -/ import Mathlib.AlgebraicGeometry.Sites.MorphismProperty import Mathlib.CategoryTheory.Sites.Canonical /-! # The big Zariski site of schemes In this file, we define the Zariski topology, as a Grothendieck topology on the category `Scheme.{u}`: this is `Scheme.zariskiTopology.{u}`. If `X : Scheme.{u}`, the Zariski topology on `Over X` can be obtained as `Scheme.zariskiTopology.over X` (see `CategoryTheory.Sites.Over`.). TODO: * If `Y : Scheme.{u}`, define a continuous functor from the category of opens of `Y` to `Over Y`, and show that a presheaf on `Over Y` is a sheaf for the Zariski topology iff its "restriction" to the topological space `Z` is a sheaf for all `Z : Over Y`. * We should have good notions of (pre)sheaves of `Type (u + 1)` (e.g. associated sheaf functor, pushforward, pullbacks) on `Scheme.{u}` for this topology. However, some constructions in the `CategoryTheory.Sites` folder currently assume that the site is a small category: this should be generalized. As a result, this big Zariski site can considered as a test case of the Grothendieck topology API for future applications to étale cohomology. -/ universe v u open CategoryTheory namespace AlgebraicGeometry namespace Scheme /-- The Zariski pretopology on the category of schemes. -/ def zariskiPretopology : Pretopology (Scheme.{u}) := pretopology @IsOpenImmersion /-- The Zariski topology on the category of schemes. -/ abbrev zariskiTopology : GrothendieckTopology (Scheme.{u}) := zariskiPretopology.toGrothendieck instance subcanonical_zariskiTopology : zariskiTopology.Subcanonical := by apply GrothendieckTopology.Subcanonical.of_isSheaf_yoneda_obj intro X rw [Presieve.isSheaf_pretopology] rintro Y S ⟨𝓤,rfl⟩ x hx let e : Y ⟶ X := 𝓤.glueMorphisms (fun j => x (𝓤.map _) (.mk _)) <| by intro i j apply hx exact Limits.pullback.condition refine ⟨e, ?_, ?_⟩ · rintro Z e ⟨j⟩ dsimp [e] rw [𝓤.ι_glueMorphisms] · intro e' h apply 𝓤.hom_ext intro j rw [𝓤.ι_glueMorphisms] exact h (𝓤.map j) (.mk j) end Scheme end AlgebraicGeometry
Deriv.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import Mathlib.Analysis.SpecialFunctions.Pow.Continuity import Mathlib.Analysis.SpecialFunctions.Complex.LogDeriv import Mathlib.Analysis.Calculus.FDeriv.Extend import Mathlib.Analysis.Calculus.Deriv.Prod import Mathlib.Analysis.SpecialFunctions.Log.Deriv import Mathlib.Analysis.SpecialFunctions.Trigonometric.Deriv /-! # Derivatives of power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We also prove differentiability and provide derivatives for the power functions `x ^ y`. -/ noncomputable section open scoped Real Topology NNReal ENNReal open Filter namespace Complex theorem hasStrictFDerivAt_cpow {p : ℂ × ℂ} (hp : p.1 ∈ slitPlane) : HasStrictFDerivAt (fun x : ℂ × ℂ => x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • ContinuousLinearMap.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • ContinuousLinearMap.snd ℂ ℂ ℂ) p := by have A : p.1 ≠ 0 := slitPlane_ne_zero hp have : (fun x : ℂ × ℂ => x.1 ^ x.2) =ᶠ[𝓝 p] fun x => exp (log x.1 * x.2) := ((isOpen_ne.preimage continuous_fst).eventually_mem A).mono fun p hp => cpow_def_of_ne_zero hp _ rw [cpow_sub _ _ A, cpow_one, mul_div_left_comm, mul_smul, mul_smul] refine HasStrictFDerivAt.congr_of_eventuallyEq ?_ this.symm simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, mul_smul, add_comm, smul_add] using ((hasStrictFDerivAt_fst.clog hp).mul hasStrictFDerivAt_snd).cexp theorem hasStrictFDerivAt_cpow' {x y : ℂ} (hp : x ∈ slitPlane) : HasStrictFDerivAt (fun x : ℂ × ℂ => x.1 ^ x.2) ((y * x ^ (y - 1)) • ContinuousLinearMap.fst ℂ ℂ ℂ + (x ^ y * log x) • ContinuousLinearMap.snd ℂ ℂ ℂ) (x, y) := @hasStrictFDerivAt_cpow (x, y) hp theorem hasStrictDerivAt_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : HasStrictDerivAt (fun y => x ^ y) (x ^ y * log x) y := by rcases em (x = 0) with (rfl | hx) · replace h := h.neg_resolve_left rfl rw [log_zero, mul_zero] refine (hasStrictDerivAt_const y 0).congr_of_eventuallyEq ?_ exact (isOpen_ne.eventually_mem h).mono fun y hy => (zero_cpow hy).symm · simpa only [cpow_def_of_ne_zero hx, mul_one] using ((hasStrictDerivAt_id y).const_mul (log x)).cexp theorem hasFDerivAt_cpow {p : ℂ × ℂ} (hp : p.1 ∈ slitPlane) : HasFDerivAt (fun x : ℂ × ℂ => x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • ContinuousLinearMap.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • ContinuousLinearMap.snd ℂ ℂ ℂ) p := (hasStrictFDerivAt_cpow hp).hasFDerivAt end Complex section fderiv open Complex variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : Set E} {c : ℂ} theorem HasStrictFDerivAt.cpow (hf : HasStrictFDerivAt f f' x) (hg : HasStrictFDerivAt g g' x) (h0 : f x ∈ slitPlane) : HasStrictFDerivAt (fun x => f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * Complex.log (f x)) • g') x := (hasStrictFDerivAt_cpow (p := (f x, g x)) h0).comp x (hf.prodMk hg) theorem HasStrictFDerivAt.const_cpow (hf : HasStrictFDerivAt f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : HasStrictFDerivAt (fun x => c ^ f x) ((c ^ f x * Complex.log c) • f') x := (hasStrictDerivAt_const_cpow h0).comp_hasStrictFDerivAt x hf theorem HasFDerivAt.cpow (hf : HasFDerivAt f f' x) (hg : HasFDerivAt g g' x) (h0 : f x ∈ slitPlane) : HasFDerivAt (fun x => f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * Complex.log (f x)) • g') x := by convert (@Complex.hasFDerivAt_cpow ((fun x => (f x, g x)) x) h0).comp x (hf.prodMk hg) theorem HasFDerivAt.const_cpow (hf : HasFDerivAt f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : HasFDerivAt (fun x => c ^ f x) ((c ^ f x * Complex.log c) • f') x := (hasStrictDerivAt_const_cpow h0).hasDerivAt.comp_hasFDerivAt x hf theorem HasFDerivWithinAt.cpow (hf : HasFDerivWithinAt f f' s x) (hg : HasFDerivWithinAt g g' s x) (h0 : f x ∈ slitPlane) : HasFDerivWithinAt (fun x => f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * Complex.log (f x)) • g') s x := by convert (@Complex.hasFDerivAt_cpow ((fun x => (f x, g x)) x) h0).comp_hasFDerivWithinAt x (hf.prodMk hg) theorem HasFDerivWithinAt.const_cpow (hf : HasFDerivWithinAt f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : HasFDerivWithinAt (fun x => c ^ f x) ((c ^ f x * Complex.log c) • f') s x := (hasStrictDerivAt_const_cpow h0).hasDerivAt.comp_hasFDerivWithinAt x hf @[fun_prop] theorem DifferentiableAt.cpow (hf : DifferentiableAt ℂ f x) (hg : DifferentiableAt ℂ g x) (h0 : f x ∈ slitPlane) : DifferentiableAt ℂ (fun x => f x ^ g x) x := (hf.hasFDerivAt.cpow hg.hasFDerivAt h0).differentiableAt @[fun_prop] theorem DifferentiableAt.const_cpow (hf : DifferentiableAt ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : DifferentiableAt ℂ (fun x => c ^ f x) x := (hf.hasFDerivAt.const_cpow h0).differentiableAt @[fun_prop] theorem DifferentiableAt.cpow_const (hf : DifferentiableAt ℂ f x) (h0 : f x ∈ slitPlane) : DifferentiableAt ℂ (fun x => f x ^ c) x := hf.cpow (differentiableAt_const c) h0 @[fun_prop] theorem DifferentiableWithinAt.cpow (hf : DifferentiableWithinAt ℂ f s x) (hg : DifferentiableWithinAt ℂ g s x) (h0 : f x ∈ slitPlane) : DifferentiableWithinAt ℂ (fun x => f x ^ g x) s x := (hf.hasFDerivWithinAt.cpow hg.hasFDerivWithinAt h0).differentiableWithinAt @[fun_prop] theorem DifferentiableWithinAt.const_cpow (hf : DifferentiableWithinAt ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : DifferentiableWithinAt ℂ (fun x => c ^ f x) s x := (hf.hasFDerivWithinAt.const_cpow h0).differentiableWithinAt @[fun_prop] theorem DifferentiableWithinAt.cpow_const (hf : DifferentiableWithinAt ℂ f s x) (h0 : f x ∈ slitPlane) : DifferentiableWithinAt ℂ (fun x => f x ^ c) s x := hf.cpow (differentiableWithinAt_const c) h0 @[fun_prop] theorem DifferentiableOn.cpow (hf : DifferentiableOn ℂ f s) (hg : DifferentiableOn ℂ g s) (h0 : Set.MapsTo f s slitPlane) : DifferentiableOn ℂ (fun x ↦ f x ^ g x) s := fun x hx ↦ (hf x hx).cpow (hg x hx) (h0 hx) @[fun_prop] theorem DifferentiableOn.const_cpow (hf : DifferentiableOn ℂ f s) (h0 : c ≠ 0 ∨ ∀ x ∈ s, f x ≠ 0) : DifferentiableOn ℂ (fun x ↦ c ^ f x) s := fun x hx ↦ (hf x hx).const_cpow (h0.imp_right fun h ↦ h x hx) @[fun_prop] theorem DifferentiableOn.cpow_const (hf : DifferentiableOn ℂ f s) (h0 : ∀ x ∈ s, f x ∈ slitPlane) : DifferentiableOn ℂ (fun x => f x ^ c) s := hf.cpow (differentiableOn_const c) h0 @[fun_prop] theorem Differentiable.cpow (hf : Differentiable ℂ f) (hg : Differentiable ℂ g) (h0 : ∀ x, f x ∈ slitPlane) : Differentiable ℂ (fun x ↦ f x ^ g x) := fun x ↦ (hf x).cpow (hg x) (h0 x) @[fun_prop] theorem Differentiable.const_cpow (hf : Differentiable ℂ f) (h0 : c ≠ 0 ∨ ∀ x, f x ≠ 0) : Differentiable ℂ (fun x ↦ c ^ f x) := fun x ↦ (hf x).const_cpow (h0.imp_right fun h ↦ h x) @[fun_prop] lemma differentiable_const_cpow_of_neZero (z : ℂ) [NeZero z] : Differentiable ℂ fun s : ℂ ↦ z ^ s := differentiable_id.const_cpow (.inl <| NeZero.ne z) @[fun_prop] lemma differentiableAt_const_cpow_of_neZero (z : ℂ) [NeZero z] (t : ℂ) : DifferentiableAt ℂ (fun s : ℂ ↦ z ^ s) t := differentiableAt_id.const_cpow (.inl <| NeZero.ne z) end fderiv section deriv open Complex variable {f g : ℂ → ℂ} {s : Set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `HasFDerivAt.cpow` to the form expected by lemmas like `HasDerivAt.cpow`. -/ private theorem aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smulRight f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smulRight g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [Algebra.id.smul_eq_mul, one_mul, ContinuousLinearMap.one_apply, ContinuousLinearMap.smulRight_apply, ContinuousLinearMap.add_apply, Pi.smul_apply, ContinuousLinearMap.coe_smul'] nonrec theorem HasStrictDerivAt.cpow (hf : HasStrictDerivAt f f' x) (hg : HasStrictDerivAt g g' x) (h0 : f x ∈ slitPlane) : HasStrictDerivAt (fun x => f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * Complex.log (f x) * g') x := by simpa using (hf.cpow hg h0).hasStrictDerivAt theorem HasStrictDerivAt.const_cpow (hf : HasStrictDerivAt f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : HasStrictDerivAt (fun x => c ^ f x) (c ^ f x * Complex.log c * f') x := (hasStrictDerivAt_const_cpow h).comp x hf theorem Complex.hasStrictDerivAt_cpow_const (h : x ∈ slitPlane) : HasStrictDerivAt (fun z : ℂ => z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (hasStrictDerivAt_id x).cpow (hasStrictDerivAt_const x c) h theorem HasStrictDerivAt.cpow_const (hf : HasStrictDerivAt f f' x) (h0 : f x ∈ slitPlane) : HasStrictDerivAt (fun x => f x ^ c) (c * f x ^ (c - 1) * f') x := (Complex.hasStrictDerivAt_cpow_const h0).comp x hf theorem HasDerivAt.cpow (hf : HasDerivAt f f' x) (hg : HasDerivAt g g' x) (h0 : f x ∈ slitPlane) : HasDerivAt (fun x => f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * Complex.log (f x) * g') x := by simpa only [aux] using (hf.hasFDerivAt.cpow hg h0).hasDerivAt theorem HasDerivAt.const_cpow (hf : HasDerivAt f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : HasDerivAt (fun x => c ^ f x) (c ^ f x * Complex.log c * f') x := (hasStrictDerivAt_const_cpow h0).hasDerivAt.comp x hf theorem HasDerivAt.cpow_const (hf : HasDerivAt f f' x) (h0 : f x ∈ slitPlane) : HasDerivAt (fun x => f x ^ c) (c * f x ^ (c - 1) * f') x := (Complex.hasStrictDerivAt_cpow_const h0).hasDerivAt.comp x hf theorem HasDerivWithinAt.cpow (hf : HasDerivWithinAt f f' s x) (hg : HasDerivWithinAt g g' s x) (h0 : f x ∈ slitPlane) : HasDerivWithinAt (fun x => f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * Complex.log (f x) * g') s x := by simpa only [aux] using (hf.hasFDerivWithinAt.cpow hg h0).hasDerivWithinAt theorem HasDerivWithinAt.const_cpow (hf : HasDerivWithinAt f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : HasDerivWithinAt (fun x => c ^ f x) (c ^ f x * Complex.log c * f') s x := (hasStrictDerivAt_const_cpow h0).hasDerivAt.comp_hasDerivWithinAt x hf theorem HasDerivWithinAt.cpow_const (hf : HasDerivWithinAt f f' s x) (h0 : f x ∈ slitPlane) : HasDerivWithinAt (fun x => f x ^ c) (c * f x ^ (c - 1) * f') s x := (Complex.hasStrictDerivAt_cpow_const h0).hasDerivAt.comp_hasDerivWithinAt x hf /-- Although `fun x => x ^ r` for fixed `r` is *not* complex-differentiable along the negative real line, it is still real-differentiable, and the derivative is what one would formally expect. See `hasDerivAt_ofReal_cpow_const` for an alternate formulation. -/ theorem hasDerivAt_ofReal_cpow_const' {x : ℝ} (hx : x ≠ 0) {r : ℂ} (hr : r ≠ -1) : HasDerivAt (fun y : ℝ => (y : ℂ) ^ (r + 1) / (r + 1)) (x ^ r) x := by rw [Ne, ← add_eq_zero_iff_eq_neg, ← Ne] at hr rcases lt_or_gt_of_ne hx.symm with (hx | hx) · -- easy case : `0 < x` apply HasDerivAt.comp_ofReal (e := fun y => (y : ℂ) ^ (r + 1) / (r + 1)) convert HasDerivAt.div_const (𝕜 := ℂ) ?_ (r + 1) using 1 · exact (mul_div_cancel_right₀ _ hr).symm · convert HasDerivAt.cpow_const ?_ ?_ using 1 · rw [add_sub_cancel_right, mul_comm]; exact (mul_one _).symm · exact hasDerivAt_id (x : ℂ) · simp [hx] · -- harder case : `x < 0` have : ∀ᶠ y : ℝ in 𝓝 x, (y : ℂ) ^ (r + 1) / (r + 1) = (-y : ℂ) ^ (r + 1) * exp (π * I * (r + 1)) / (r + 1) := by refine Filter.eventually_of_mem (Iio_mem_nhds hx) fun y hy => ?_ rw [ofReal_cpow_of_nonpos (le_of_lt hy)] refine HasDerivAt.congr_of_eventuallyEq ?_ this rw [ofReal_cpow_of_nonpos (le_of_lt hx)] suffices HasDerivAt (fun y : ℝ => (-↑y) ^ (r + 1) * exp (↑π * I * (r + 1))) ((r + 1) * (-↑x) ^ r * exp (↑π * I * r)) x by convert this.div_const (r + 1) using 1 conv_rhs => rw [mul_assoc, mul_comm, mul_div_cancel_right₀ _ hr] rw [mul_add ((π : ℂ) * _), mul_one, exp_add, exp_pi_mul_I, mul_comm (_ : ℂ) (-1 : ℂ), neg_one_mul] simp_rw [mul_neg, ← neg_mul, ← ofReal_neg] suffices HasDerivAt (fun y : ℝ => (↑(-y) : ℂ) ^ (r + 1)) (-(r + 1) * ↑(-x) ^ r) x by convert this.neg.mul_const _ using 1; ring suffices HasDerivAt (fun y : ℝ => (y : ℂ) ^ (r + 1)) ((r + 1) * ↑(-x) ^ r) (-x) by convert @HasDerivAt.scomp ℝ _ ℂ _ _ x ℝ _ _ _ _ _ _ _ _ this (hasDerivAt_neg x) using 1 rw [real_smul, ofReal_neg 1, ofReal_one]; ring suffices HasDerivAt (fun y : ℂ => y ^ (r + 1)) ((r + 1) * ↑(-x) ^ r) ↑(-x) by exact this.comp_ofReal conv in ↑_ ^ _ => rw [(by ring : r = r + 1 - 1)] convert HasDerivAt.cpow_const ?_ ?_ using 1 · rw [add_sub_cancel_right, add_sub_cancel_right]; exact (mul_one _).symm · exact hasDerivAt_id ((-x : ℝ) : ℂ) · simp [hx] /-- An alternate formulation of `hasDerivAt_ofReal_cpow_const'`. -/ theorem hasDerivAt_ofReal_cpow_const {x : ℝ} (hx : x ≠ 0) {r : ℂ} (hr : r ≠ 0) : HasDerivAt (fun y : ℝ => (y : ℂ) ^ r) (r * x ^ (r - 1)) x := by have := HasDerivAt.const_mul r <| hasDerivAt_ofReal_cpow_const' hx (by rwa [ne_eq, sub_eq_neg_self]) simpa [sub_add_cancel, mul_div_cancel₀ _ hr] using this /-- A version of `DifferentiableAt.cpow_const` for a real function. -/ theorem DifferentiableAt.ofReal_cpow_const {f : ℝ → ℝ} {x : ℝ} (hf : DifferentiableAt ℝ f x) (h0 : f x ≠ 0) (h1 : c ≠ 0) : DifferentiableAt ℝ (fun (y : ℝ) => (f y : ℂ) ^ c) x := (hasDerivAt_ofReal_cpow_const h0 h1).differentiableAt.comp x hf theorem Complex.deriv_cpow_const (hx : x ∈ Complex.slitPlane) : deriv (fun (x : ℂ) ↦ x ^ c) x = c * x ^ (c - 1) := (hasStrictDerivAt_cpow_const hx).hasDerivAt.deriv /-- A version of `Complex.deriv_cpow_const` for a real variable. -/ theorem Complex.deriv_ofReal_cpow_const {x : ℝ} (hx : x ≠ 0) (hc : c ≠ 0) : deriv (fun x : ℝ ↦ (x : ℂ) ^ c) x = c * x ^ (c - 1) := (hasDerivAt_ofReal_cpow_const hx hc).deriv theorem deriv_cpow_const (hf : DifferentiableAt ℂ f x) (hx : f x ∈ Complex.slitPlane) : deriv (fun (x : ℂ) ↦ f x ^ c) x = c * f x ^ (c - 1) * deriv f x := (hf.hasDerivAt.cpow_const hx).deriv theorem isTheta_deriv_ofReal_cpow_const_atTop {c : ℂ} (hc : c ≠ 0) : deriv (fun (x : ℝ) => (x : ℂ) ^ c) =Θ[atTop] fun x => x ^ (c.re - 1) := by calc _ =ᶠ[atTop] fun x : ℝ ↦ c * x ^ (c - 1) := by filter_upwards [eventually_ne_atTop 0] with x hx using by rw [deriv_ofReal_cpow_const hx hc] _ =Θ[atTop] fun x : ℝ ↦ ‖(x : ℂ) ^ (c - 1)‖ := (Asymptotics.IsTheta.of_norm_eventuallyEq EventuallyEq.rfl).const_mul_left hc _ =ᶠ[atTop] fun x ↦ x ^ (c.re - 1) := by filter_upwards [eventually_gt_atTop 0] with x hx rw [norm_cpow_eq_rpow_re_of_pos hx, sub_re, one_re] theorem isBigO_deriv_ofReal_cpow_const_atTop (c : ℂ) : deriv (fun (x : ℝ) => (x : ℂ) ^ c) =O[atTop] fun x => x ^ (c.re - 1) := by obtain rfl | hc := eq_or_ne c 0 · simp_rw [cpow_zero, deriv_const', Asymptotics.isBigO_zero] · exact (isTheta_deriv_ofReal_cpow_const_atTop hc).1 end deriv namespace Real variable {x y z : ℝ} /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `0 < p.fst`. -/ theorem hasStrictFDerivAt_rpow_of_pos (p : ℝ × ℝ) (hp : 0 < p.1) : HasStrictFDerivAt (fun x : ℝ × ℝ => x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • ContinuousLinearMap.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1) • ContinuousLinearMap.snd ℝ ℝ ℝ) p := by have : (fun x : ℝ × ℝ => x.1 ^ x.2) =ᶠ[𝓝 p] fun x => exp (log x.1 * x.2) := (continuousAt_fst.eventually (lt_mem_nhds hp)).mono fun p hp => rpow_def_of_pos hp _ refine HasStrictFDerivAt.congr_of_eventuallyEq ?_ this.symm convert ((hasStrictFDerivAt_fst.log hp.ne').fun_mul hasStrictFDerivAt_snd).exp using 1 rw [rpow_sub_one hp.ne', ← rpow_def_of_pos hp, smul_add, smul_smul, mul_div_left_comm, div_eq_mul_inv, smul_smul, smul_smul, mul_assoc, add_comm] /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `p.fst < 0`. -/ theorem hasStrictFDerivAt_rpow_of_neg (p : ℝ × ℝ) (hp : p.1 < 0) : HasStrictFDerivAt (fun x : ℝ × ℝ => x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • ContinuousLinearMap.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1 - exp (log p.1 * p.2) * sin (p.2 * π) * π) • ContinuousLinearMap.snd ℝ ℝ ℝ) p := by have : (fun x : ℝ × ℝ => x.1 ^ x.2) =ᶠ[𝓝 p] fun x => exp (log x.1 * x.2) * cos (x.2 * π) := (continuousAt_fst.eventually (gt_mem_nhds hp)).mono fun p hp => rpow_def_of_neg hp _ refine HasStrictFDerivAt.congr_of_eventuallyEq ?_ this.symm convert ((hasStrictFDerivAt_fst.log hp.ne).fun_mul hasStrictFDerivAt_snd).exp.fun_mul (hasStrictFDerivAt_snd.mul_const π).cos using 1 simp_rw [rpow_sub_one hp.ne, smul_add, ← add_assoc, smul_smul, ← add_smul, ← mul_assoc, mul_comm (cos _), ← rpow_def_of_neg hp] rw [div_eq_mul_inv, add_comm]; congr 2 <;> ring /-- The function `fun (x, y) => x ^ y` is infinitely smooth at `(x, y)` unless `x = 0`. -/ theorem contDiffAt_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) {n : WithTop ℕ∞} : ContDiffAt ℝ n (fun p : ℝ × ℝ => p.1 ^ p.2) p := by rcases hp.lt_or_gt with hneg | hpos exacts [(((contDiffAt_fst.log hneg.ne).mul contDiffAt_snd).exp.mul (contDiffAt_snd.mul contDiffAt_const).cos).congr_of_eventuallyEq ((continuousAt_fst.eventually (gt_mem_nhds hneg)).mono fun p hp => rpow_def_of_neg hp _), ((contDiffAt_fst.log hpos.ne').mul contDiffAt_snd).exp.congr_of_eventuallyEq ((continuousAt_fst.eventually (lt_mem_nhds hpos)).mono fun p hp => rpow_def_of_pos hp _)] theorem differentiableAt_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) : DifferentiableAt ℝ (fun p : ℝ × ℝ => p.1 ^ p.2) p := (contDiffAt_rpow_of_ne p hp).differentiableAt le_rfl theorem _root_.HasStrictDerivAt.rpow {f g : ℝ → ℝ} {f' g' : ℝ} (hf : HasStrictDerivAt f f' x) (hg : HasStrictDerivAt g g' x) (h : 0 < f x) : HasStrictDerivAt (fun x => f x ^ g x) (f' * g x * f x ^ (g x - 1) + g' * f x ^ g x * Real.log (f x)) x := by convert (hasStrictFDerivAt_rpow_of_pos ((fun x => (f x, g x)) x) h).comp_hasStrictDerivAt x (hf.prodMk hg) using 1 simp [mul_assoc, mul_comm] theorem hasStrictDerivAt_rpow_const_of_ne {x : ℝ} (hx : x ≠ 0) (p : ℝ) : HasStrictDerivAt (fun x => x ^ p) (p * x ^ (p - 1)) x := by rcases hx.lt_or_gt with hx | hx · have := (hasStrictFDerivAt_rpow_of_neg (x, p) hx).comp_hasStrictDerivAt x ((hasStrictDerivAt_id x).prodMk (hasStrictDerivAt_const x p)) convert this using 1; simp · simpa using (hasStrictDerivAt_id x).rpow (hasStrictDerivAt_const x p) hx theorem hasStrictDerivAt_const_rpow {a : ℝ} (ha : 0 < a) (x : ℝ) : HasStrictDerivAt (fun x => a ^ x) (a ^ x * log a) x := by simpa using (hasStrictDerivAt_const _ _).rpow (hasStrictDerivAt_id x) ha lemma differentiableAt_rpow_const_of_ne (p : ℝ) {x : ℝ} (hx : x ≠ 0) : DifferentiableAt ℝ (fun x => x ^ p) x := (hasStrictDerivAt_rpow_const_of_ne hx p).differentiableAt lemma differentiableOn_rpow_const (p : ℝ) : DifferentiableOn ℝ (fun x => (x : ℝ) ^ p) {0}ᶜ := fun _ hx => (Real.differentiableAt_rpow_const_of_ne p hx).differentiableWithinAt /-- This lemma says that `fun x => a ^ x` is strictly differentiable for `a < 0`. Note that these values of `a` are outside of the "official" domain of `a ^ x`, and we may redefine `a ^ x` for negative `a` if some other definition will be more convenient. -/ theorem hasStrictDerivAt_const_rpow_of_neg {a x : ℝ} (ha : a < 0) : HasStrictDerivAt (fun x => a ^ x) (a ^ x * log a - exp (log a * x) * sin (x * π) * π) x := by simpa using (hasStrictFDerivAt_rpow_of_neg (a, x) ha).comp_hasStrictDerivAt x ((hasStrictDerivAt_const _ _).prodMk (hasStrictDerivAt_id _)) end Real namespace Real variable {z x y : ℝ} theorem hasDerivAt_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : HasDerivAt (fun x => x ^ p) (p * x ^ (p - 1)) x := by rcases ne_or_eq x 0 with (hx | rfl) · exact (hasStrictDerivAt_rpow_const_of_ne hx _).hasDerivAt replace h : 1 ≤ p := h.neg_resolve_left rfl apply hasDerivAt_of_hasDerivAt_of_ne fun x hx => (hasStrictDerivAt_rpow_const_of_ne hx p).hasDerivAt exacts [continuousAt_id.rpow_const (Or.inr (zero_le_one.trans h)), continuousAt_const.mul (continuousAt_id.rpow_const (Or.inr (sub_nonneg.2 h)))] theorem differentiable_rpow_const {p : ℝ} (hp : 1 ≤ p) : Differentiable ℝ fun x : ℝ => x ^ p := fun _ => (hasDerivAt_rpow_const (Or.inr hp)).differentiableAt theorem deriv_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : deriv (fun x : ℝ => x ^ p) x = p * x ^ (p - 1) := (hasDerivAt_rpow_const h).deriv theorem deriv_rpow_const' {p : ℝ} (h : 1 ≤ p) : (deriv fun x : ℝ => x ^ p) = fun x => p * x ^ (p - 1) := funext fun _ => deriv_rpow_const (Or.inr h) theorem contDiffAt_rpow_const_of_ne {x p : ℝ} {n : WithTop ℕ∞} (h : x ≠ 0) : ContDiffAt ℝ n (fun x => x ^ p) x := (contDiffAt_rpow_of_ne (x, p) h).comp x (contDiffAt_id.prodMk contDiffAt_const) theorem contDiff_rpow_const_of_le {p : ℝ} {n : ℕ} (h : ↑n ≤ p) : ContDiff ℝ n fun x : ℝ => x ^ p := by induction' n with n ihn generalizing p · exact contDiff_zero.2 (continuous_id.rpow_const fun x => Or.inr <| by simpa using h) · have h1 : 1 ≤ p := le_trans (by simp) h rw [Nat.cast_succ, ← le_sub_iff_add_le] at h rw [show ((n + 1 : ℕ) : WithTop ℕ∞) = n + 1 from rfl, contDiff_succ_iff_deriv, deriv_rpow_const' h1] simp only [WithTop.natCast_ne_top, analyticOn_univ, IsEmpty.forall_iff, true_and] exact ⟨differentiable_rpow_const h1, contDiff_const.mul (ihn h)⟩ theorem contDiffAt_rpow_const_of_le {x p : ℝ} {n : ℕ} (h : ↑n ≤ p) : ContDiffAt ℝ n (fun x : ℝ => x ^ p) x := (contDiff_rpow_const_of_le h).contDiffAt theorem contDiffAt_rpow_const {x p : ℝ} {n : ℕ} (h : x ≠ 0 ∨ ↑n ≤ p) : ContDiffAt ℝ n (fun x : ℝ => x ^ p) x := h.elim contDiffAt_rpow_const_of_ne contDiffAt_rpow_const_of_le theorem hasStrictDerivAt_rpow_const {x p : ℝ} (hx : x ≠ 0 ∨ 1 ≤ p) : HasStrictDerivAt (fun x => x ^ p) (p * x ^ (p - 1)) x := ContDiffAt.hasStrictDerivAt' (contDiffAt_rpow_const (by rwa [← Nat.cast_one] at hx)) (hasDerivAt_rpow_const hx) le_rfl end Real section Differentiability open Real section fderiv variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] {f g : E → ℝ} {f' g' : E →L[ℝ] ℝ} {x : E} {s : Set E} {c p : ℝ} {n : WithTop ℕ∞} theorem HasFDerivWithinAt.rpow (hf : HasFDerivWithinAt f f' s x) (hg : HasFDerivWithinAt g g' s x) (h : 0 < f x) : HasFDerivWithinAt (fun x => f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * Real.log (f x)) • g') s x := by -- `by exact` to deal with tricky unification. exact (hasStrictFDerivAt_rpow_of_pos (f x, g x) h).hasFDerivAt.comp_hasFDerivWithinAt x (hf.prodMk hg) theorem HasFDerivAt.rpow (hf : HasFDerivAt f f' x) (hg : HasFDerivAt g g' x) (h : 0 < f x) : HasFDerivAt (fun x => f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * Real.log (f x)) • g') x := by exact (hasStrictFDerivAt_rpow_of_pos (f x, g x) h).hasFDerivAt.comp x (hf.prodMk hg) theorem HasStrictFDerivAt.rpow (hf : HasStrictFDerivAt f f' x) (hg : HasStrictFDerivAt g g' x) (h : 0 < f x) : HasStrictFDerivAt (fun x => f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * Real.log (f x)) • g') x := (hasStrictFDerivAt_rpow_of_pos (f x, g x) h).comp x (hf.prodMk hg) @[fun_prop] theorem DifferentiableWithinAt.rpow (hf : DifferentiableWithinAt ℝ f s x) (hg : DifferentiableWithinAt ℝ g s x) (h : f x ≠ 0) : DifferentiableWithinAt ℝ (fun x => f x ^ g x) s x := by -- `by exact` to deal with tricky unification. exact (differentiableAt_rpow_of_ne (f x, g x) h).comp_differentiableWithinAt x (hf.prodMk hg) @[fun_prop] theorem DifferentiableAt.rpow (hf : DifferentiableAt ℝ f x) (hg : DifferentiableAt ℝ g x) (h : f x ≠ 0) : DifferentiableAt ℝ (fun x => f x ^ g x) x := by -- `by exact` to deal with tricky unification. exact (differentiableAt_rpow_of_ne (f x, g x) h).comp x (hf.prodMk hg) @[fun_prop] theorem DifferentiableOn.rpow (hf : DifferentiableOn ℝ f s) (hg : DifferentiableOn ℝ g s) (h : ∀ x ∈ s, f x ≠ 0) : DifferentiableOn ℝ (fun x => f x ^ g x) s := fun x hx => (hf x hx).rpow (hg x hx) (h x hx) @[fun_prop] theorem Differentiable.rpow (hf : Differentiable ℝ f) (hg : Differentiable ℝ g) (h : ∀ x, f x ≠ 0) : Differentiable ℝ fun x => f x ^ g x := fun x => (hf x).rpow (hg x) (h x) @[fun_prop] theorem HasFDerivWithinAt.rpow_const (hf : HasFDerivWithinAt f f' s x) (h : f x ≠ 0 ∨ 1 ≤ p) : HasFDerivWithinAt (fun x => f x ^ p) ((p * f x ^ (p - 1)) • f') s x := (hasDerivAt_rpow_const h).comp_hasFDerivWithinAt x hf @[fun_prop] theorem HasFDerivAt.rpow_const (hf : HasFDerivAt f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : HasFDerivAt (fun x => f x ^ p) ((p * f x ^ (p - 1)) • f') x := (hasDerivAt_rpow_const h).comp_hasFDerivAt x hf theorem HasStrictFDerivAt.rpow_const (hf : HasStrictFDerivAt f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : HasStrictFDerivAt (fun x => f x ^ p) ((p * f x ^ (p - 1)) • f') x := (hasStrictDerivAt_rpow_const h).comp_hasStrictFDerivAt x hf @[fun_prop] theorem DifferentiableWithinAt.rpow_const (hf : DifferentiableWithinAt ℝ f s x) (h : f x ≠ 0 ∨ 1 ≤ p) : DifferentiableWithinAt ℝ (fun x => f x ^ p) s x := (hf.hasFDerivWithinAt.rpow_const h).differentiableWithinAt @[simp] theorem DifferentiableAt.rpow_const (hf : DifferentiableAt ℝ f x) (h : f x ≠ 0 ∨ 1 ≤ p) : DifferentiableAt ℝ (fun x => f x ^ p) x := (hf.hasFDerivAt.rpow_const h).differentiableAt @[fun_prop] theorem DifferentiableOn.rpow_const (hf : DifferentiableOn ℝ f s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 1 ≤ p) : DifferentiableOn ℝ (fun x => f x ^ p) s := fun x hx => (hf x hx).rpow_const (h x hx) @[fun_prop] theorem Differentiable.rpow_const (hf : Differentiable ℝ f) (h : ∀ x, f x ≠ 0 ∨ 1 ≤ p) : Differentiable ℝ fun x => f x ^ p := fun x => (hf x).rpow_const (h x) theorem HasFDerivWithinAt.const_rpow (hf : HasFDerivWithinAt f f' s x) (hc : 0 < c) : HasFDerivWithinAt (fun x => c ^ f x) ((c ^ f x * Real.log c) • f') s x := (hasStrictDerivAt_const_rpow hc (f x)).hasDerivAt.comp_hasFDerivWithinAt x hf theorem HasFDerivAt.const_rpow (hf : HasFDerivAt f f' x) (hc : 0 < c) : HasFDerivAt (fun x => c ^ f x) ((c ^ f x * Real.log c) • f') x := (hasStrictDerivAt_const_rpow hc (f x)).hasDerivAt.comp_hasFDerivAt x hf theorem HasStrictFDerivAt.const_rpow (hf : HasStrictFDerivAt f f' x) (hc : 0 < c) : HasStrictFDerivAt (fun x => c ^ f x) ((c ^ f x * Real.log c) • f') x := (hasStrictDerivAt_const_rpow hc (f x)).comp_hasStrictFDerivAt x hf @[fun_prop] theorem ContDiffWithinAt.rpow (hf : ContDiffWithinAt ℝ n f s x) (hg : ContDiffWithinAt ℝ n g s x) (h : f x ≠ 0) : ContDiffWithinAt ℝ n (fun x => f x ^ g x) s x := by -- `by exact` to deal with tricky unification. exact (contDiffAt_rpow_of_ne (f x, g x) h).comp_contDiffWithinAt x (hf.prodMk hg) @[fun_prop] theorem ContDiffAt.rpow (hf : ContDiffAt ℝ n f x) (hg : ContDiffAt ℝ n g x) (h : f x ≠ 0) : ContDiffAt ℝ n (fun x => f x ^ g x) x := by -- `by exact` to deal with tricky unification. exact (contDiffAt_rpow_of_ne (f x, g x) h).comp x (hf.prodMk hg) @[fun_prop] theorem ContDiffOn.rpow (hf : ContDiffOn ℝ n f s) (hg : ContDiffOn ℝ n g s) (h : ∀ x ∈ s, f x ≠ 0) : ContDiffOn ℝ n (fun x => f x ^ g x) s := fun x hx => (hf x hx).rpow (hg x hx) (h x hx) @[fun_prop] theorem ContDiff.rpow (hf : ContDiff ℝ n f) (hg : ContDiff ℝ n g) (h : ∀ x, f x ≠ 0) : ContDiff ℝ n fun x => f x ^ g x := contDiff_iff_contDiffAt.mpr fun x => hf.contDiffAt.rpow hg.contDiffAt (h x) @[fun_prop] theorem ContDiffWithinAt.rpow_const_of_ne (hf : ContDiffWithinAt ℝ n f s x) (h : f x ≠ 0) : ContDiffWithinAt ℝ n (fun x => f x ^ p) s x := hf.rpow contDiffWithinAt_const h @[fun_prop] theorem ContDiffAt.rpow_const_of_ne (hf : ContDiffAt ℝ n f x) (h : f x ≠ 0) : ContDiffAt ℝ n (fun x => f x ^ p) x := hf.rpow contDiffAt_const h @[fun_prop] theorem ContDiffOn.rpow_const_of_ne (hf : ContDiffOn ℝ n f s) (h : ∀ x ∈ s, f x ≠ 0) : ContDiffOn ℝ n (fun x => f x ^ p) s := fun x hx => (hf x hx).rpow_const_of_ne (h x hx) @[fun_prop] theorem ContDiff.rpow_const_of_ne (hf : ContDiff ℝ n f) (h : ∀ x, f x ≠ 0) : ContDiff ℝ n fun x => f x ^ p := hf.rpow contDiff_const h variable {m : ℕ} @[fun_prop] theorem ContDiffWithinAt.rpow_const_of_le (hf : ContDiffWithinAt ℝ m f s x) (h : ↑m ≤ p) : ContDiffWithinAt ℝ m (fun x => f x ^ p) s x := (contDiffAt_rpow_const_of_le h).comp_contDiffWithinAt x hf @[fun_prop] theorem ContDiffAt.rpow_const_of_le (hf : ContDiffAt ℝ m f x) (h : ↑m ≤ p) : ContDiffAt ℝ m (fun x => f x ^ p) x := by rw [← contDiffWithinAt_univ] at *; exact hf.rpow_const_of_le h @[fun_prop] theorem ContDiffOn.rpow_const_of_le (hf : ContDiffOn ℝ m f s) (h : ↑m ≤ p) : ContDiffOn ℝ m (fun x => f x ^ p) s := fun x hx => (hf x hx).rpow_const_of_le h @[fun_prop] theorem ContDiff.rpow_const_of_le (hf : ContDiff ℝ m f) (h : ↑m ≤ p) : ContDiff ℝ m fun x => f x ^ p := contDiff_iff_contDiffAt.mpr fun _ => hf.contDiffAt.rpow_const_of_le h end fderiv section deriv variable {f g : ℝ → ℝ} {f' g' x y p : ℝ} {s : Set ℝ} theorem HasDerivWithinAt.rpow (hf : HasDerivWithinAt f f' s x) (hg : HasDerivWithinAt g g' s x) (h : 0 < f x) : HasDerivWithinAt (fun x => f x ^ g x) (f' * g x * f x ^ (g x - 1) + g' * f x ^ g x * Real.log (f x)) s x := by convert (hf.hasFDerivWithinAt.rpow hg.hasFDerivWithinAt h).hasDerivWithinAt using 1 dsimp; ring theorem HasDerivAt.rpow (hf : HasDerivAt f f' x) (hg : HasDerivAt g g' x) (h : 0 < f x) : HasDerivAt (fun x => f x ^ g x) (f' * g x * f x ^ (g x - 1) + g' * f x ^ g x * Real.log (f x)) x := by rw [← hasDerivWithinAt_univ] at * exact hf.rpow hg h theorem HasDerivWithinAt.rpow_const (hf : HasDerivWithinAt f f' s x) (hx : f x ≠ 0 ∨ 1 ≤ p) : HasDerivWithinAt (fun y => f y ^ p) (f' * p * f x ^ (p - 1)) s x := by convert (hasDerivAt_rpow_const hx).comp_hasDerivWithinAt x hf using 1 ring theorem HasDerivAt.rpow_const (hf : HasDerivAt f f' x) (hx : f x ≠ 0 ∨ 1 ≤ p) : HasDerivAt (fun y => f y ^ p) (f' * p * f x ^ (p - 1)) x := by rw [← hasDerivWithinAt_univ] at * exact hf.rpow_const hx theorem derivWithin_rpow_const (hf : DifferentiableWithinAt ℝ f s x) (hx : f x ≠ 0 ∨ 1 ≤ p) (hxs : UniqueDiffWithinAt ℝ s x) : derivWithin (fun x => f x ^ p) s x = derivWithin f s x * p * f x ^ (p - 1) := (hf.hasDerivWithinAt.rpow_const hx).derivWithin hxs @[simp] theorem deriv_rpow_const (hf : DifferentiableAt ℝ f x) (hx : f x ≠ 0 ∨ 1 ≤ p) : deriv (fun x => f x ^ p) x = deriv f x * p * f x ^ (p - 1) := (hf.hasDerivAt.rpow_const hx).deriv theorem deriv_norm_ofReal_cpow (c : ℂ) {t : ℝ} (ht : 0 < t) : (deriv fun x : ℝ ↦ ‖(x : ℂ) ^ c‖) t = c.re * t ^ (c.re - 1) := by rw [EventuallyEq.deriv_eq (f := fun x ↦ x ^ c.re)] · rw [Real.deriv_rpow_const (Or.inl ht.ne')] · filter_upwards [eventually_gt_nhds ht] with x hx rw [Complex.norm_cpow_eq_rpow_re_of_pos hx] lemma isTheta_deriv_rpow_const_atTop {p : ℝ} (hp : p ≠ 0) : deriv (fun (x : ℝ) => x ^ p) =Θ[atTop] fun x => x ^ (p-1) := by calc deriv (fun (x : ℝ) => x ^ p) =ᶠ[atTop] fun x => p * x ^ (p - 1) := by filter_upwards [eventually_ne_atTop 0] with x hx rw [Real.deriv_rpow_const (Or.inl hx)] _ =Θ[atTop] fun x => x ^ (p-1) := Asymptotics.IsTheta.const_mul_left hp Asymptotics.isTheta_rfl lemma isBigO_deriv_rpow_const_atTop (p : ℝ) : deriv (fun (x : ℝ) => x ^ p) =O[atTop] fun x => x ^ (p-1) := by rcases eq_or_ne p 0 with rfl | hp case inl => simp [zero_sub, Real.rpow_neg_one, Real.rpow_zero, deriv_const', Asymptotics.isBigO_zero] case inr => exact (isTheta_deriv_rpow_const_atTop hp).1 end deriv end Differentiability
ssrmatching.v
From Corelib Require Export ssrmatching.
Basic.lean
/- Copyright (c) 2024 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.MeasureTheory.Group.AEStabilizer import Mathlib.Dynamics.Ergodic.Ergodic /-! # Ergodic group actions A group action of `G` on a space `α` with measure `μ` is called *ergodic*, if for any (null) measurable set `s`, if it is a.e.-invariant under each scalar multiplication `(g • ·)`, `g : G`, then it is either null or conull. -/ open Set Filter MeasureTheory MulAction open scoped Pointwise /-- An additive group action of `G` on a space `α` with measure `μ` is called *ergodic*, if for any (null) measurable set `s`, if it is a.e.-invariant under each scalar addition `(g +ᵥ ·)`, `g : G`, then it is either null or conull. -/ class ErgodicVAdd (G α : Type*) [VAdd G α] {_ : MeasurableSpace α} (μ : Measure α) : Prop extends VAddInvariantMeasure G α μ where aeconst_of_forall_preimage_vadd_ae_eq {s : Set α} : MeasurableSet s → (∀ g : G, (g +ᵥ ·) ⁻¹' s =ᵐ[μ] s) → EventuallyConst s (ae μ) /-- A group action of `G` on a space `α` with measure `μ` is called *ergodic*, if for any (null) measurable set `s`, if it is a.e.-invariant under each scalar multiplication `(g • ·)`, `g : G`, then it is either null or conull. -/ @[to_additive, mk_iff] class ErgodicSMul (G α : Type*) [SMul G α] {_ : MeasurableSpace α} (μ : Measure α) : Prop extends SMulInvariantMeasure G α μ where aeconst_of_forall_preimage_smul_ae_eq {s : Set α} : MeasurableSet s → (∀ g : G, (g • ·) ⁻¹' s =ᵐ[μ] s) → EventuallyConst s (ae μ) attribute [to_additive] ergodicSMul_iff namespace MeasureTheory variable (G : Type*) {α : Type*} {m : MeasurableSpace α} {μ : Measure α} @[to_additive] theorem aeconst_of_forall_preimage_smul_ae_eq [SMul G α] [ErgodicSMul G α μ] {s : Set α} (hm : NullMeasurableSet s μ) (h : ∀ g : G, (g • ·) ⁻¹' s =ᵐ[μ] s) : EventuallyConst s (ae μ) := by rcases hm with ⟨t, htm, hst⟩ refine .congr ?_ hst.symm refine ErgodicSMul.aeconst_of_forall_preimage_smul_ae_eq htm fun g : G ↦ ?_ refine .trans (.trans ?_ (h g)) hst exact tendsto_smul_ae _ _ hst.symm section Group variable [Group G] [MulAction G α] [ErgodicSMul G α μ] {s : Set α} @[to_additive] theorem aeconst_of_forall_smul_ae_eq (hm : NullMeasurableSet s μ) (h : ∀ g : G, g • s =ᵐ[μ] s) : EventuallyConst s (ae μ) := aeconst_of_forall_preimage_smul_ae_eq G hm fun g ↦ by simpa only [preimage_smul] using h g⁻¹ @[to_additive] theorem _root_.MulAction.aeconst_of_aestabilizer_eq_top (hm : NullMeasurableSet s μ) (h : aestabilizer G μ s = ⊤) : EventuallyConst s (ae μ) := aeconst_of_forall_smul_ae_eq G hm <| (Subgroup.eq_top_iff' _).1 h end Group theorem _root_.ErgodicSMul.of_aestabilizer [Group G] [MulAction G α] [SMulInvariantMeasure G α μ] (h : ∀ s, MeasurableSet s → aestabilizer G μ s = ⊤ → EventuallyConst s (ae μ)) : ErgodicSMul G α μ := ⟨fun hm hs ↦ h _ hm <| (Subgroup.eq_top_iff' _).2 fun g ↦ by simpa only [preimage_smul_inv] using hs g⁻¹⟩ theorem ergodicSMul_iterateMulAct {f : α → α} (hf : Measurable f) : ErgodicSMul (IterateMulAct f) α μ ↔ Ergodic f μ := by simp only [ergodicSMul_iff, smulInvariantMeasure_iterateMulAct, hf] refine ⟨fun ⟨h₁, h₂⟩ ↦ ⟨h₁, ⟨?_⟩⟩, fun h ↦ ⟨h.1, ?_⟩⟩ · intro s hm hs refine h₂ hm fun n ↦ ?_ nth_rewrite 2 [← Function.IsFixedPt.preimage_iterate hs n.val] rfl · intro s hm hs exact h.quasiErgodic.aeconst_set₀ hm.nullMeasurableSet <| hs (.mk 1) end MeasureTheory
Boundary.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Order.BooleanAlgebra.Basic import Mathlib.Tactic.Common /-! # Co-Heyting boundary The boundary of an element of a co-Heyting algebra is the intersection of its Heyting negation with itself. The boundary in the co-Heyting algebra of closed sets coincides with the topological boundary. ## Main declarations * `Coheyting.boundary`: Co-Heyting boundary. `Coheyting.boundary a = a ⊓ ¬a` ## Notation `∂ a` is notation for `Coheyting.boundary a` in locale `Heyting`. -/ assert_not_exists RelIso variable {α : Type*} namespace Coheyting variable [CoheytingAlgebra α] {a b : α} /-- The boundary of an element of a co-Heyting algebra is the intersection of its Heyting negation with itself. Note that this is always `⊥` for a boolean algebra. -/ def boundary (a : α) : α := a ⊓ ¬a /-- The boundary of an element of a co-Heyting algebra. -/ scoped[Heyting] prefix:120 "∂ " => Coheyting.boundary open Heyting -- TODO: Should hnot be named hNot? theorem inf_hnot_self (a : α) : a ⊓ ¬a = ∂ a := rfl theorem boundary_le : ∂ a ≤ a := inf_le_left theorem boundary_le_hnot : ∂ a ≤ ¬a := inf_le_right @[simp] theorem boundary_bot : ∂ (⊥ : α) = ⊥ := bot_inf_eq _ @[simp] theorem boundary_top : ∂ (⊤ : α) = ⊥ := by rw [boundary, hnot_top, inf_bot_eq] theorem boundary_hnot_le (a : α) : ∂ (¬a) ≤ ∂ a := (inf_comm _ _).trans_le <| inf_le_inf_right _ hnot_hnot_le @[simp] theorem boundary_hnot_hnot (a : α) : ∂ (¬¬a) = ∂ (¬a) := by simp_rw [boundary, hnot_hnot_hnot, inf_comm] @[simp] theorem hnot_boundary (a : α) : ¬∂ a = ⊤ := by rw [boundary, hnot_inf_distrib, sup_hnot_self] /-- **Leibniz rule** for the co-Heyting boundary. -/ theorem boundary_inf (a b : α) : ∂ (a ⊓ b) = ∂ a ⊓ b ⊔ a ⊓ ∂ b := by unfold boundary rw [hnot_inf_distrib, inf_sup_left, inf_right_comm, ← inf_assoc] theorem boundary_inf_le : ∂ (a ⊓ b) ≤ ∂ a ⊔ ∂ b := (boundary_inf _ _).trans_le <| sup_le_sup inf_le_left inf_le_right theorem boundary_sup_le : ∂ (a ⊔ b) ≤ ∂ a ⊔ ∂ b := by rw [boundary, inf_sup_right] exact sup_le_sup (inf_le_inf_left _ <| hnot_anti le_sup_left) (inf_le_inf_left _ <| hnot_anti le_sup_right) /- The intuitionistic version of `Coheyting.boundary_le_boundary_sup_sup_boundary_inf_left`. Either proof can be obtained from the other using the equivalence of Heyting algebras and intuitionistic logic and duality between Heyting and co-Heyting algebras. It is crucial that the following proof be intuitionistic. -/ example (a b : Prop) : (a ∧ b ∨ ¬(a ∧ b)) ∧ ((a ∨ b) ∨ ¬(a ∨ b)) → a ∨ ¬a := by rintro ⟨⟨ha, _⟩ | hnab, (ha | hb) | hnab⟩ <;> try exact Or.inl ha · exact Or.inr fun ha => hnab ⟨ha, hb⟩ · exact Or.inr fun ha => hnab <| Or.inl ha theorem boundary_le_boundary_sup_sup_boundary_inf_left : ∂ a ≤ ∂ (a ⊔ b) ⊔ ∂ (a ⊓ b) := by simp only [boundary, sup_inf_left, sup_inf_right, sup_right_idem, le_inf_iff, sup_assoc, sup_comm _ a] refine ⟨⟨⟨?_, ?_⟩, ⟨?_, ?_⟩⟩, ?_, ?_⟩ <;> try { exact le_sup_of_le_left inf_le_left } <;> refine inf_le_of_right_le ?_ · rw [hnot_le_iff_codisjoint_right, codisjoint_left_comm] exact codisjoint_hnot_left · refine le_sup_of_le_right ?_ rw [hnot_le_iff_codisjoint_right] exact codisjoint_hnot_right.mono_right (hnot_anti inf_le_left) theorem boundary_le_boundary_sup_sup_boundary_inf_right : ∂ b ≤ ∂ (a ⊔ b) ⊔ ∂ (a ⊓ b) := by rw [sup_comm a, inf_comm] exact boundary_le_boundary_sup_sup_boundary_inf_left theorem boundary_sup_sup_boundary_inf (a b : α) : ∂ (a ⊔ b) ⊔ ∂ (a ⊓ b) = ∂ a ⊔ ∂ b := le_antisymm (sup_le boundary_sup_le boundary_inf_le) <| sup_le boundary_le_boundary_sup_sup_boundary_inf_left boundary_le_boundary_sup_sup_boundary_inf_right @[simp] theorem boundary_idem (a : α) : ∂ ∂ a = ∂ a := by rw [boundary, hnot_boundary, inf_top_eq] theorem hnot_hnot_sup_boundary (a : α) : ¬¬a ⊔ ∂ a = a := by rw [boundary, sup_inf_left, hnot_sup_self, inf_top_eq, sup_eq_right] exact hnot_hnot_le theorem hnot_eq_top_iff_exists_boundary : ¬a = ⊤ ↔ ∃ b, ∂ b = a := ⟨fun h => ⟨a, by rw [boundary, h, inf_top_eq]⟩, by rintro ⟨b, rfl⟩ exact hnot_boundary _⟩ end Coheyting open Heyting section BooleanAlgebra variable [BooleanAlgebra α] @[simp] theorem Coheyting.boundary_eq_bot (a : α) : ∂ a = ⊥ := inf_compl_eq_bot end BooleanAlgebra
Unbundled.lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Yuyang Zhao -/ import Mathlib.Algebra.Order.GroupWithZero.Unbundled.Basic import Mathlib.Algebra.Order.GroupWithZero.Unbundled.Defs import Mathlib.Tactic.Linter.DeprecatedModule deprecated_module (since := "2025-04-13")
Lagrange.lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Wrenna Robson -/ import Mathlib.Algebra.BigOperators.Group.Finset.Pi import Mathlib.Algebra.Polynomial.FieldDivision import Mathlib.LinearAlgebra.Vandermonde import Mathlib.RingTheory.Polynomial.Basic /-! # Lagrange interpolation ## Main definitions * In everything that follows, `s : Finset ι` is a finite set of indexes, with `v : ι → F` an indexing of the field over some type. We call the image of v on s the interpolation nodes, though strictly unique nodes are only defined when v is injective on s. * `Lagrange.basisDivisor x y`, with `x y : F`. These are the normalised irreducible factors of the Lagrange basis polynomials. They evaluate to `1` at `x` and `0` at `y` when `x` and `y` are distinct. * `Lagrange.basis v i` with `i : ι`: the Lagrange basis polynomial that evaluates to `1` at `v i` and `0` at `v j` for `i ≠ j`. * `Lagrange.interpolate v r` where `r : ι → F` is a function from the fintype to the field: the Lagrange interpolant that evaluates to `r i` at `x i` for all `i : ι`. The `r i` are the _values_ associated with the _nodes_`x i`. -/ open Polynomial section PolynomialDetermination namespace Polynomial variable {R : Type*} [CommRing R] [IsDomain R] {f g : R[X]} section Finset open Function Fintype open scoped Finset variable (s : Finset R) theorem eq_zero_of_degree_lt_of_eval_finset_eq_zero (degree_f_lt : f.degree < #s) (eval_f : ∀ x ∈ s, f.eval x = 0) : f = 0 := by rw [← mem_degreeLT] at degree_f_lt simp_rw [eval_eq_sum_degreeLTEquiv degree_f_lt] at eval_f rw [← degreeLTEquiv_eq_zero_iff_eq_zero degree_f_lt] exact Matrix.eq_zero_of_forall_index_sum_mul_pow_eq_zero (Injective.comp (Embedding.subtype _).inj' (equivFinOfCardEq (card_coe _)).symm.injective) fun _ => eval_f _ (Finset.coe_mem _) theorem eq_of_degree_sub_lt_of_eval_finset_eq (degree_fg_lt : (f - g).degree < #s) (eval_fg : ∀ x ∈ s, f.eval x = g.eval x) : f = g := by rw [← sub_eq_zero] refine eq_zero_of_degree_lt_of_eval_finset_eq_zero _ degree_fg_lt ?_ simp_rw [eval_sub, sub_eq_zero] exact eval_fg theorem eq_of_degrees_lt_of_eval_finset_eq (degree_f_lt : f.degree < #s) (degree_g_lt : g.degree < #s) (eval_fg : ∀ x ∈ s, f.eval x = g.eval x) : f = g := by rw [← mem_degreeLT] at degree_f_lt degree_g_lt refine eq_of_degree_sub_lt_of_eval_finset_eq _ ?_ eval_fg rw [← mem_degreeLT]; exact Submodule.sub_mem _ degree_f_lt degree_g_lt /-- Two polynomials, with the same degree and leading coefficient, which have the same evaluation on a set of distinct values with cardinality equal to the degree, are equal. -/ theorem eq_of_degree_le_of_eval_finset_eq (h_deg_le : f.degree ≤ #s) (h_deg_eq : f.degree = g.degree) (hlc : f.leadingCoeff = g.leadingCoeff) (h_eval : ∀ x ∈ s, f.eval x = g.eval x) : f = g := by rcases eq_or_ne f 0 with rfl | hf · rwa [degree_zero, eq_comm, degree_eq_bot, eq_comm] at h_deg_eq · exact eq_of_degree_sub_lt_of_eval_finset_eq s (lt_of_lt_of_le (degree_sub_lt h_deg_eq hf hlc) h_deg_le) h_eval end Finset section Indexed open Finset variable {ι : Type*} {v : ι → R} (s : Finset ι) theorem eq_zero_of_degree_lt_of_eval_index_eq_zero (hvs : Set.InjOn v s) (degree_f_lt : f.degree < #s) (eval_f : ∀ i ∈ s, f.eval (v i) = 0) : f = 0 := by classical rw [← card_image_of_injOn hvs] at degree_f_lt refine eq_zero_of_degree_lt_of_eval_finset_eq_zero _ degree_f_lt ?_ intro x hx rcases mem_image.mp hx with ⟨_, hj, rfl⟩ exact eval_f _ hj theorem eq_of_degree_sub_lt_of_eval_index_eq (hvs : Set.InjOn v s) (degree_fg_lt : (f - g).degree < #s) (eval_fg : ∀ i ∈ s, f.eval (v i) = g.eval (v i)) : f = g := by rw [← sub_eq_zero] refine eq_zero_of_degree_lt_of_eval_index_eq_zero _ hvs degree_fg_lt ?_ simp_rw [eval_sub, sub_eq_zero] exact eval_fg theorem eq_of_degrees_lt_of_eval_index_eq (hvs : Set.InjOn v s) (degree_f_lt : f.degree < #s) (degree_g_lt : g.degree < #s) (eval_fg : ∀ i ∈ s, f.eval (v i) = g.eval (v i)) : f = g := by refine eq_of_degree_sub_lt_of_eval_index_eq _ hvs ?_ eval_fg rw [← mem_degreeLT] at degree_f_lt degree_g_lt ⊢ exact Submodule.sub_mem _ degree_f_lt degree_g_lt theorem eq_of_degree_le_of_eval_index_eq (hvs : Set.InjOn v s) (h_deg_le : f.degree ≤ #s) (h_deg_eq : f.degree = g.degree) (hlc : f.leadingCoeff = g.leadingCoeff) (h_eval : ∀ i ∈ s, f.eval (v i) = g.eval (v i)) : f = g := by rcases eq_or_ne f 0 with rfl | hf · rwa [degree_zero, eq_comm, degree_eq_bot, eq_comm] at h_deg_eq · exact eq_of_degree_sub_lt_of_eval_index_eq s hvs (lt_of_lt_of_le (degree_sub_lt h_deg_eq hf hlc) h_deg_le) h_eval end Indexed end Polynomial end PolynomialDetermination noncomputable section namespace Lagrange open Polynomial section BasisDivisor variable {F : Type*} [Field F] variable {x y : F} /-- `basisDivisor x y` is the unique linear or constant polynomial such that when evaluated at `x` it gives `1` and `y` it gives `0` (where when `x = y` it is identically `0`). Such polynomials are the building blocks for the Lagrange interpolants. -/ def basisDivisor (x y : F) : F[X] := C (x - y)⁻¹ * (X - C y) theorem basisDivisor_self : basisDivisor x x = 0 := by simp only [basisDivisor, sub_self, inv_zero, map_zero, zero_mul] theorem basisDivisor_inj (hxy : basisDivisor x y = 0) : x = y := by simp_rw [basisDivisor, mul_eq_zero, X_sub_C_ne_zero, or_false, C_eq_zero, inv_eq_zero, sub_eq_zero] at hxy exact hxy @[simp] theorem basisDivisor_eq_zero_iff : basisDivisor x y = 0 ↔ x = y := ⟨basisDivisor_inj, fun H => H ▸ basisDivisor_self⟩ theorem basisDivisor_ne_zero_iff : basisDivisor x y ≠ 0 ↔ x ≠ y := by rw [Ne, basisDivisor_eq_zero_iff] theorem degree_basisDivisor_of_ne (hxy : x ≠ y) : (basisDivisor x y).degree = 1 := by rw [basisDivisor, degree_mul, degree_X_sub_C, degree_C, zero_add] exact inv_ne_zero (sub_ne_zero_of_ne hxy) @[simp] theorem degree_basisDivisor_self : (basisDivisor x x).degree = ⊥ := by rw [basisDivisor_self, degree_zero] theorem natDegree_basisDivisor_self : (basisDivisor x x).natDegree = 0 := by rw [basisDivisor_self, natDegree_zero] theorem natDegree_basisDivisor_of_ne (hxy : x ≠ y) : (basisDivisor x y).natDegree = 1 := natDegree_eq_of_degree_eq_some (degree_basisDivisor_of_ne hxy) @[simp] theorem eval_basisDivisor_right : eval y (basisDivisor x y) = 0 := by simp only [basisDivisor, eval_mul, eval_C, eval_sub, eval_X, sub_self, mul_zero] theorem eval_basisDivisor_left_of_ne (hxy : x ≠ y) : eval x (basisDivisor x y) = 1 := by simp only [basisDivisor, eval_mul, eval_C, eval_sub, eval_X] exact inv_mul_cancel₀ (sub_ne_zero_of_ne hxy) end BasisDivisor section Basis variable {F : Type*} [Field F] {ι : Type*} [DecidableEq ι] variable {s : Finset ι} {v : ι → F} {i j : ι} open Finset /-- Lagrange basis polynomials indexed by `s : Finset ι`, defined at nodes `v i` for a map `v : ι → F`. For `i, j ∈ s`, `basis s v i` evaluates to 0 at `v j` for `i ≠ j`. When `v` is injective on `s`, `basis s v i` evaluates to 1 at `v i`. -/ protected def basis (s : Finset ι) (v : ι → F) (i : ι) : F[X] := ∏ j ∈ s.erase i, basisDivisor (v i) (v j) @[simp] theorem basis_empty : Lagrange.basis ∅ v i = 1 := rfl @[simp] theorem basis_singleton (i : ι) : Lagrange.basis {i} v i = 1 := by rw [Lagrange.basis, erase_singleton, prod_empty] @[simp] theorem basis_pair_left (hij : i ≠ j) : Lagrange.basis {i, j} v i = basisDivisor (v i) (v j) := by simp only [Lagrange.basis, hij, erase_insert_eq_erase, erase_eq_of_notMem, mem_singleton, not_false_iff, prod_singleton] @[simp] theorem basis_pair_right (hij : i ≠ j) : Lagrange.basis {i, j} v j = basisDivisor (v j) (v i) := by rw [pair_comm] exact basis_pair_left hij.symm theorem basis_ne_zero (hvs : Set.InjOn v s) (hi : i ∈ s) : Lagrange.basis s v i ≠ 0 := by simp_rw [Lagrange.basis, prod_ne_zero_iff, Ne, mem_erase] rintro j ⟨hij, hj⟩ rw [basisDivisor_eq_zero_iff, hvs.eq_iff hi hj] exact hij.symm @[simp] theorem eval_basis_self (hvs : Set.InjOn v s) (hi : i ∈ s) : (Lagrange.basis s v i).eval (v i) = 1 := by rw [Lagrange.basis, eval_prod] refine prod_eq_one fun j H => ?_ rw [eval_basisDivisor_left_of_ne] rcases mem_erase.mp H with ⟨hij, hj⟩ exact mt (hvs hi hj) hij.symm @[simp] theorem eval_basis_of_ne (hij : i ≠ j) (hj : j ∈ s) : (Lagrange.basis s v i).eval (v j) = 0 := by simp_rw [Lagrange.basis, eval_prod, prod_eq_zero_iff] exact ⟨j, ⟨mem_erase.mpr ⟨hij.symm, hj⟩, eval_basisDivisor_right⟩⟩ @[simp] theorem natDegree_basis (hvs : Set.InjOn v s) (hi : i ∈ s) : (Lagrange.basis s v i).natDegree = #s - 1 := by have H : ∀ j, j ∈ s.erase i → basisDivisor (v i) (v j) ≠ 0 := by simp_rw [Ne, mem_erase, basisDivisor_eq_zero_iff] exact fun j ⟨hij₁, hj⟩ hij₂ => hij₁ (hvs hj hi hij₂.symm) rw [← card_erase_of_mem hi, card_eq_sum_ones] convert natDegree_prod _ _ H using 1 refine sum_congr rfl fun j hj => (natDegree_basisDivisor_of_ne ?_).symm rw [Ne, ← basisDivisor_eq_zero_iff] exact H _ hj theorem degree_basis (hvs : Set.InjOn v s) (hi : i ∈ s) : (Lagrange.basis s v i).degree = ↑(#s - 1) := by rw [degree_eq_natDegree (basis_ne_zero hvs hi), natDegree_basis hvs hi] theorem sum_basis (hvs : Set.InjOn v s) (hs : s.Nonempty) : ∑ j ∈ s, Lagrange.basis s v j = 1 := by refine eq_of_degrees_lt_of_eval_index_eq s hvs (lt_of_le_of_lt (degree_sum_le _ _) ?_) ?_ ?_ · rw [Nat.cast_withBot, Finset.sup_lt_iff (WithBot.bot_lt_coe #s)] intro i hi rw [degree_basis hvs hi, Nat.cast_withBot, WithBot.coe_lt_coe] exact Nat.pred_lt (card_ne_zero_of_mem hi) · rw [degree_one, ← WithBot.coe_zero, Nat.cast_withBot, WithBot.coe_lt_coe] exact Nonempty.card_pos hs · intro i hi rw [eval_finset_sum, eval_one, ← add_sum_erase _ _ hi, eval_basis_self hvs hi, add_eq_left] refine sum_eq_zero fun j hj => ?_ rcases mem_erase.mp hj with ⟨hij, _⟩ rw [eval_basis_of_ne hij hi] theorem basisDivisor_add_symm {x y : F} (hxy : x ≠ y) : basisDivisor x y + basisDivisor y x = 1 := by classical rw [← sum_basis Function.injective_id.injOn ⟨x, mem_insert_self _ {y}⟩, sum_insert (notMem_singleton.mpr hxy), sum_singleton, basis_pair_left hxy, basis_pair_right hxy, id, id] end Basis section Interpolate variable {F : Type*} [Field F] {ι : Type*} [DecidableEq ι] variable {s t : Finset ι} {i j : ι} {v : ι → F} (r r' : ι → F) open Finset /-- Lagrange interpolation: given a finset `s : Finset ι`, a nodal map `v : ι → F` injective on `s` and a value function `r : ι → F`, `interpolate s v r` is the unique polynomial of degree `< #s` that takes value `r i` on `v i` for all `i` in `s`. -/ @[simps] def interpolate (s : Finset ι) (v : ι → F) : (ι → F) →ₗ[F] F[X] where toFun r := ∑ i ∈ s, C (r i) * Lagrange.basis s v i map_add' f g := by simp_rw [← Finset.sum_add_distrib] have h : (fun x => C (f x) * Lagrange.basis s v x + C (g x) * Lagrange.basis s v x) = (fun x => C ((f + g) x) * Lagrange.basis s v x) := by simp_rw [← add_mul, ← C_add, Pi.add_apply] rw [h] map_smul' c f := by simp_rw [Finset.smul_sum, C_mul', smul_smul, Pi.smul_apply, RingHom.id_apply, smul_eq_mul] theorem interpolate_empty : interpolate ∅ v r = 0 := by rw [interpolate_apply, sum_empty] theorem interpolate_singleton : interpolate {i} v r = C (r i) := by rw [interpolate_apply, sum_singleton, basis_singleton, mul_one] theorem interpolate_one (hvs : Set.InjOn v s) (hs : s.Nonempty) : interpolate s v 1 = 1 := by simp_rw [interpolate_apply, Pi.one_apply, map_one, one_mul] exact sum_basis hvs hs theorem eval_interpolate_at_node (hvs : Set.InjOn v s) (hi : i ∈ s) : eval (v i) (interpolate s v r) = r i := by rw [interpolate_apply, eval_finset_sum, ← add_sum_erase _ _ hi] simp_rw [eval_mul, eval_C, eval_basis_self hvs hi, mul_one, add_eq_left] refine sum_eq_zero fun j H => ?_ rw [eval_basis_of_ne (mem_erase.mp H).1 hi, mul_zero] theorem degree_interpolate_le (hvs : Set.InjOn v s) : (interpolate s v r).degree ≤ ↑(#s - 1) := by refine (degree_sum_le _ _).trans ?_ rw [Finset.sup_le_iff] intro i hi rw [degree_mul, degree_basis hvs hi] by_cases hr : r i = 0 · simpa only [hr, map_zero, degree_zero, WithBot.bot_add] using bot_le · rw [degree_C hr, zero_add] theorem degree_interpolate_lt (hvs : Set.InjOn v s) : (interpolate s v r).degree < #s := by rw [Nat.cast_withBot] rcases eq_empty_or_nonempty s with (rfl | h) · rw [interpolate_empty, degree_zero, card_empty] exact WithBot.bot_lt_coe _ · refine lt_of_le_of_lt (degree_interpolate_le _ hvs) ?_ rw [Nat.cast_withBot, WithBot.coe_lt_coe] exact Nat.sub_lt (Nonempty.card_pos h) zero_lt_one theorem degree_interpolate_erase_lt (hvs : Set.InjOn v s) (hi : i ∈ s) : (interpolate (s.erase i) v r).degree < ↑(#s - 1) := by rw [← Finset.card_erase_of_mem hi] exact degree_interpolate_lt _ (Set.InjOn.mono (coe_subset.mpr (erase_subset _ _)) hvs) theorem values_eq_on_of_interpolate_eq (hvs : Set.InjOn v s) (hrr' : interpolate s v r = interpolate s v r') : ∀ i ∈ s, r i = r' i := fun _ hi => by rw [← eval_interpolate_at_node r hvs hi, hrr', eval_interpolate_at_node r' hvs hi] theorem interpolate_eq_of_values_eq_on (hrr' : ∀ i ∈ s, r i = r' i) : interpolate s v r = interpolate s v r' := sum_congr rfl fun i hi => by rw [hrr' _ hi] theorem interpolate_eq_iff_values_eq_on (hvs : Set.InjOn v s) : interpolate s v r = interpolate s v r' ↔ ∀ i ∈ s, r i = r' i := ⟨values_eq_on_of_interpolate_eq _ _ hvs, interpolate_eq_of_values_eq_on _ _⟩ theorem eq_interpolate {f : F[X]} (hvs : Set.InjOn v s) (degree_f_lt : f.degree < #s) : f = interpolate s v fun i => f.eval (v i) := eq_of_degrees_lt_of_eval_index_eq _ hvs degree_f_lt (degree_interpolate_lt _ hvs) fun _ hi => (eval_interpolate_at_node (fun x ↦ eval (v x) f) hvs hi).symm theorem eq_interpolate_of_eval_eq {f : F[X]} (hvs : Set.InjOn v s) (degree_f_lt : f.degree < #s) (eval_f : ∀ i ∈ s, f.eval (v i) = r i) : f = interpolate s v r := by rw [eq_interpolate hvs degree_f_lt] exact interpolate_eq_of_values_eq_on _ _ eval_f /-- This is the characteristic property of the interpolation: the interpolation is the unique polynomial of `degree < Fintype.card ι` which takes the value of the `r i` on the `v i`. -/ theorem eq_interpolate_iff {f : F[X]} (hvs : Set.InjOn v s) : (f.degree < #s ∧ ∀ i ∈ s, eval (v i) f = r i) ↔ f = interpolate s v r := by constructor <;> intro h · exact eq_interpolate_of_eval_eq _ hvs h.1 h.2 · rw [h] exact ⟨degree_interpolate_lt _ hvs, fun _ hi => eval_interpolate_at_node _ hvs hi⟩ /-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials of degree less than `Fintype.card ι`. -/ def funEquivDegreeLT (hvs : Set.InjOn v s) : degreeLT F #s ≃ₗ[F] s → F where toFun f i := f.1.eval (v i) map_add' _ _ := funext fun _ => eval_add map_smul' c f := funext <| by simp invFun r := ⟨interpolate s v fun x => if hx : x ∈ s then r ⟨x, hx⟩ else 0, mem_degreeLT.2 <| degree_interpolate_lt _ hvs⟩ left_inv := by rintro ⟨f, hf⟩ simp only [Subtype.mk_eq_mk, dite_eq_ite] rw [mem_degreeLT] at hf conv => rhs; rw [eq_interpolate hvs hf] exact interpolate_eq_of_values_eq_on _ _ fun _ hi => if_pos hi right_inv := by intro f ext ⟨i, hi⟩ simp only [eval_interpolate_at_node _ hvs hi] exact dif_pos hi theorem interpolate_eq_sum_interpolate_insert_sdiff (hvt : Set.InjOn v t) (hs : s.Nonempty) (hst : s ⊆ t) : interpolate t v r = ∑ i ∈ s, interpolate (insert i (t \ s)) v r * Lagrange.basis s v i := by symm refine eq_interpolate_of_eval_eq _ hvt (lt_of_le_of_lt (degree_sum_le _ _) ?_) fun i hi => ?_ · simp_rw [Nat.cast_withBot, Finset.sup_lt_iff (WithBot.bot_lt_coe #t), degree_mul] intro i hi have hs : 1 ≤ #s := Nonempty.card_pos ⟨_, hi⟩ have hst' : #s ≤ #t := card_le_card hst have H : #t = 1 + (#t - #s) + (#s - 1) := by rw [add_assoc, tsub_add_tsub_cancel hst' hs, ← add_tsub_assoc_of_le (hs.trans hst'), Nat.succ_add_sub_one, zero_add] rw [degree_basis (Set.InjOn.mono hst hvt) hi, H, WithBot.coe_add, Nat.cast_withBot, WithBot.add_lt_add_iff_right (@WithBot.coe_ne_bot _ (#s - 1))] convert degree_interpolate_lt _ (hvt.mono (coe_subset.mpr (insert_subset_iff.mpr ⟨hst hi, sdiff_subset⟩))) rw [card_insert_of_notMem (notMem_sdiff_of_mem_right hi), card_sdiff hst, add_comm] · simp_rw [eval_finset_sum, eval_mul] by_cases hi' : i ∈ s · rw [← add_sum_erase _ _ hi', eval_basis_self (hvt.mono hst) hi', eval_interpolate_at_node _ (hvt.mono (coe_subset.mpr (insert_subset_iff.mpr ⟨hi, sdiff_subset⟩))) (mem_insert_self _ _), mul_one, add_eq_left] refine sum_eq_zero fun j hj => ?_ rcases mem_erase.mp hj with ⟨hij, _⟩ rw [eval_basis_of_ne hij hi', mul_zero] · have H : (∑ j ∈ s, eval (v i) (Lagrange.basis s v j)) = 1 := by rw [← eval_finset_sum, sum_basis (hvt.mono hst) hs, eval_one] rw [← mul_one (r i), ← H, mul_sum] refine sum_congr rfl fun j hj => ?_ congr exact eval_interpolate_at_node _ (hvt.mono (insert_subset_iff.mpr ⟨hst hj, sdiff_subset⟩)) (mem_insert.mpr (Or.inr (mem_sdiff.mpr ⟨hi, hi'⟩))) theorem interpolate_eq_add_interpolate_erase (hvs : Set.InjOn v s) (hi : i ∈ s) (hj : j ∈ s) (hij : i ≠ j) : interpolate s v r = interpolate (s.erase j) v r * basisDivisor (v i) (v j) + interpolate (s.erase i) v r * basisDivisor (v j) (v i) := by rw [interpolate_eq_sum_interpolate_insert_sdiff _ hvs ⟨i, mem_insert_self i {j}⟩ _, sum_insert (notMem_singleton.mpr hij), sum_singleton, basis_pair_left hij, basis_pair_right hij, sdiff_insert_insert_of_mem_of_notMem hi (notMem_singleton.mpr hij), sdiff_singleton_eq_erase, pair_comm, sdiff_insert_insert_of_mem_of_notMem hj (notMem_singleton.mpr hij.symm), sdiff_singleton_eq_erase] exact insert_subset_iff.mpr ⟨hi, singleton_subset_iff.mpr hj⟩ end Interpolate section Nodal variable {R : Type*} [CommRing R] {ι : Type*} variable {s : Finset ι} {v : ι → R} open Finset Polynomial /-- `nodal s v` is the unique monic polynomial whose roots are the nodes defined by `v` and `s`. That is, the roots of `nodal s v` are exactly the image of `v` on `s`, with appropriate multiplicity. We can use `nodal` to define the barycentric forms of the evaluated interpolant. -/ def nodal (s : Finset ι) (v : ι → R) : R[X] := ∏ i ∈ s, (X - C (v i)) theorem nodal_eq (s : Finset ι) (v : ι → R) : nodal s v = ∏ i ∈ s, (X - C (v i)) := rfl @[simp] theorem nodal_empty : nodal ∅ v = 1 := by rfl @[simp] theorem natDegree_nodal [Nontrivial R] : (nodal s v).natDegree = #s := by simp_rw [nodal, natDegree_prod_of_monic (h := fun i _ => monic_X_sub_C (v i)), natDegree_X_sub_C, sum_const, smul_eq_mul, mul_one] theorem nodal_ne_zero [Nontrivial R] : nodal s v ≠ 0 := by rcases s.eq_empty_or_nonempty with (rfl | h) · exact one_ne_zero · apply ne_zero_of_natDegree_gt (n := 0) simp only [natDegree_nodal, h.card_pos] @[simp] theorem degree_nodal [Nontrivial R] : (nodal s v).degree = #s := by simp_rw [degree_eq_natDegree nodal_ne_zero, natDegree_nodal] theorem nodal_monic : (nodal s v).Monic := monic_prod_of_monic s (fun i ↦ X - C (v i)) fun i _ ↦ monic_X_sub_C (v i) theorem eval_nodal {x : R} : (nodal s v).eval x = ∏ i ∈ s, (x - v i) := by simp_rw [nodal, eval_prod, eval_sub, eval_X, eval_C] theorem eval_nodal_at_node {i : ι} (hi : i ∈ s) : eval (v i) (nodal s v) = 0 := by rw [eval_nodal] exact s.prod_eq_zero hi (sub_self (v i)) theorem eval_nodal_not_at_node [Nontrivial R] [NoZeroDivisors R] {x : R} (hx : ∀ i ∈ s, x ≠ v i) : eval x (nodal s v) ≠ 0 := by simp_rw [nodal, eval_prod, prod_ne_zero_iff, eval_sub, eval_X, eval_C, sub_ne_zero] exact hx theorem nodal_eq_mul_nodal_erase [DecidableEq ι] {i : ι} (hi : i ∈ s) : nodal s v = (X - C (v i)) * nodal (s.erase i) v := by simp_rw [nodal, Finset.mul_prod_erase _ (fun x => X - C (v x)) hi] theorem X_sub_C_dvd_nodal (v : ι → R) {i : ι} (hi : i ∈ s) : X - C (v i) ∣ nodal s v := by classical exact ⟨nodal (s.erase i) v, nodal_eq_mul_nodal_erase hi⟩ theorem nodal_insert_eq_nodal [DecidableEq ι] {i : ι} (hi : i ∉ s) : nodal (insert i s) v = (X - C (v i)) * nodal s v := by simp_rw [nodal, prod_insert hi] theorem derivative_nodal [DecidableEq ι] : derivative (nodal s v) = ∑ i ∈ s, nodal (s.erase i) v := by refine s.induction_on ?_ fun i t hit IH => ?_ · rw [nodal_empty, derivative_one, sum_empty] · rw [nodal_insert_eq_nodal hit, derivative_mul, IH, derivative_sub, derivative_X, derivative_C, sub_zero, one_mul, sum_insert hit, mul_sum, erase_insert hit, add_right_inj] refine sum_congr rfl fun j hjt => ?_ rw [t.erase_insert_of_ne (ne_of_mem_of_not_mem hjt hit).symm, nodal_insert_eq_nodal (mem_of_mem_erase.mt hit)] theorem eval_nodal_derivative_eval_node_eq [DecidableEq ι] {i : ι} (hi : i ∈ s) : eval (v i) (derivative (nodal s v)) = eval (v i) (nodal (s.erase i) v) := by rw [derivative_nodal, eval_finset_sum, ← add_sum_erase _ _ hi, add_eq_left] exact sum_eq_zero fun j hj => (eval_nodal_at_node (mem_erase.mpr ⟨(mem_erase.mp hj).1.symm, hi⟩)) /-- The vanishing polynomial on a multiplicative subgroup is of the form X ^ n - 1. -/ @[simp] theorem nodal_subgroup_eq_X_pow_card_sub_one [IsDomain R] (G : Subgroup Rˣ) [Fintype G] : nodal (G : Set Rˣ).toFinset ((↑) : Rˣ → R) = X ^ (Fintype.card G) - 1 := by have h : degree (1 : R[X]) < degree ((X : R[X]) ^ Fintype.card G) := by simp [Fintype.card_pos] apply eq_of_degree_le_of_eval_index_eq (v := ((↑) : Rˣ → R)) (G : Set Rˣ).toFinset · exact Units.val_injective.injOn · simp · rw [degree_sub_eq_left_of_degree_lt h, degree_nodal, Set.toFinset_card, degree_pow, degree_X, nsmul_eq_mul, mul_one, Nat.cast_inj] exact rfl · rw [nodal_monic, leadingCoeff_sub_of_degree_lt h, monic_X_pow] · intros i hi rw [eval_nodal_at_node hi] replace hi : i ∈ G := by simpa using hi obtain ⟨g, rfl⟩ : ∃ g : G, g.val = i := ⟨⟨i, hi⟩, rfl⟩ simp [← Units.val_pow_eq_pow_val, ← Subgroup.coe_pow G] end Nodal section NodalWeight variable {F : Type*} [Field F] {ι : Type*} [DecidableEq ι] variable {s : Finset ι} {v : ι → F} {i : ι} open Finset /-- This defines the nodal weight for a given set of node indexes and node mapping function `v`. -/ def nodalWeight (s : Finset ι) (v : ι → F) (i : ι) := ∏ j ∈ s.erase i, (v i - v j)⁻¹ theorem nodalWeight_eq_eval_nodal_erase_inv : nodalWeight s v i = (eval (v i) (nodal (s.erase i) v))⁻¹ := by rw [eval_nodal, nodalWeight, prod_inv_distrib] theorem nodal_erase_eq_nodal_div (hi : i ∈ s) : nodal (s.erase i) v = nodal s v / (X - C (v i)) := by rw [nodal_eq_mul_nodal_erase hi, mul_div_cancel_left₀] exact X_sub_C_ne_zero _ theorem nodalWeight_eq_eval_derivative_nodal (hi : i ∈ s) : nodalWeight s v i = (eval (v i) (Polynomial.derivative (nodal s v)))⁻¹ := by rw [eval_nodal_derivative_eval_node_eq hi, nodalWeight_eq_eval_nodal_erase_inv] @[deprecated (since := "2025-07-08")] alias nodalWeight_eq_eval_nodal_derative := nodalWeight_eq_eval_derivative_nodal theorem nodalWeight_ne_zero (hvs : Set.InjOn v s) (hi : i ∈ s) : nodalWeight s v i ≠ 0 := by rw [nodalWeight, prod_ne_zero_iff] intro j hj rcases mem_erase.mp hj with ⟨hij, hj⟩ exact inv_ne_zero (sub_ne_zero_of_ne (mt (hvs.eq_iff hi hj).mp hij.symm)) end NodalWeight section LagrangeBarycentric variable {F : Type*} [Field F] {ι : Type*} [DecidableEq ι] variable {s : Finset ι} {v : ι → F} (r : ι → F) {i : ι} {x : F} open Finset theorem basis_eq_prod_sub_inv_mul_nodal_div (hi : i ∈ s) : Lagrange.basis s v i = C (nodalWeight s v i) * (nodal s v / (X - C (v i))) := by simp_rw [Lagrange.basis, basisDivisor, nodalWeight, prod_mul_distrib, map_prod, ← nodal_erase_eq_nodal_div hi, nodal] theorem eval_basis_not_at_node (hi : i ∈ s) (hxi : x ≠ v i) : eval x (Lagrange.basis s v i) = eval x (nodal s v) * (nodalWeight s v i * (x - v i)⁻¹) := by rw [mul_comm, basis_eq_prod_sub_inv_mul_nodal_div hi, eval_mul, eval_C, ← nodal_erase_eq_nodal_div hi, eval_nodal, eval_nodal, mul_assoc, ← mul_prod_erase _ _ hi, ← mul_assoc (x - v i)⁻¹, inv_mul_cancel₀ (sub_ne_zero_of_ne hxi), one_mul] theorem interpolate_eq_nodalWeight_mul_nodal_div_X_sub_C : interpolate s v r = ∑ i ∈ s, C (nodalWeight s v i) * (nodal s v / (X - C (v i))) * C (r i) := sum_congr rfl fun j hj => by rw [mul_comm, basis_eq_prod_sub_inv_mul_nodal_div hj] /-- This is the first barycentric form of the Lagrange interpolant. -/ theorem eval_interpolate_not_at_node (hx : ∀ i ∈ s, x ≠ v i) : eval x (interpolate s v r) = eval x (nodal s v) * ∑ i ∈ s, nodalWeight s v i * (x - v i)⁻¹ * r i := by simp_rw [interpolate_apply, mul_sum, eval_finset_sum, eval_mul, eval_C] refine sum_congr rfl fun i hi => ?_ rw [← mul_assoc, mul_comm, eval_basis_not_at_node hi (hx _ hi)] theorem sum_nodalWeight_mul_inv_sub_ne_zero (hvs : Set.InjOn v s) (hx : ∀ i ∈ s, x ≠ v i) (hs : s.Nonempty) : (∑ i ∈ s, nodalWeight s v i * (x - v i)⁻¹) ≠ 0 := @right_ne_zero_of_mul_eq_one _ _ _ (eval x (nodal s v)) _ <| by simpa only [Pi.one_apply, interpolate_one hvs hs, eval_one, mul_one] using (eval_interpolate_not_at_node 1 hx).symm /-- This is the second barycentric form of the Lagrange interpolant. -/ theorem eval_interpolate_not_at_node' (hvs : Set.InjOn v s) (hs : s.Nonempty) (hx : ∀ i ∈ s, x ≠ v i) : eval x (interpolate s v r) = (∑ i ∈ s, nodalWeight s v i * (x - v i)⁻¹ * r i) / ∑ i ∈ s, nodalWeight s v i * (x - v i)⁻¹ := by rw [← div_one (eval x (interpolate s v r)), ← @eval_one _ _ x, ← interpolate_one hvs hs, eval_interpolate_not_at_node r hx, eval_interpolate_not_at_node 1 hx] simp only [mul_div_mul_left _ _ (eval_nodal_not_at_node hx), Pi.one_apply, mul_one] end LagrangeBarycentric end Lagrange
Requests.lean
/- Copyright (c) 2023 Arthur Paulino. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino -/ import Batteries.Data.String.Matcher import Cache.Hashing namespace Cache.Requests open System (FilePath) /-- Structure to hold repository information with priority ordering -/ structure RepoInfo where repo : String useFirst : Bool deriving Repr /-- Helper function to extract repository name from a git remote URL -/ def extractRepoFromUrl (url : String) : Option String := do let url := url.stripSuffix ".git" let pos ← url.revFind (· == '/') let pos ← url.revFindAux (fun c => c == '/' || c == ':') pos return url.extract (url.next pos) url.endPos /-- Spot check if a URL is valid for a git remote -/ def isRemoteURL (url : String) : Bool := "https://".isPrefixOf url || "http://".isPrefixOf url || "git@github.com:".isPrefixOf url /-- Helper function to get repository from a remote name -/ def getRepoFromRemote (mathlibDepPath : FilePath) (remoteName : String) (errorContext : String) : IO String := do -- If the remote is already a valid URL, attempt to extract the repo from it. This happens with `gh pr checkout` if isRemoteURL remoteName then repoFromURL remoteName else -- If not, we use `git remote get-url` to find the URL of the remote. This assumes the remote has a -- standard name like `origin` or `upstream` or it errors out. let out ← IO.Process.output {cmd := "git", args := #["remote", "get-url", remoteName], cwd := mathlibDepPath} -- If `git remote get-url` fails then bail out with an error to help debug let output := out.stdout.trim unless out.exitCode == 0 do throw <| IO.userError s!"\ Failed to run Git to determine Mathlib's repository from {remoteName} remote (exit code: {out.exitCode}).\n\ {errorContext}\n\ Stdout:\n{output}\nStderr:\n{out.stderr.trim}\n" -- Finally attempt to extract the repository from the remote URL returned by `git remote get-url` repoFromURL output where repoFromURL (url : String) : IO String := do if let some repo := extractRepoFromUrl url then return repo else throw <| IO.userError s!"\ Failed to extract repository from remote URL: {url}.\n\ {errorContext}\n\ Please ensure the remote URL is valid and points to a GitHub repository." /-- Finds the remote name that points to `leanprover-community/mathlib4` repository. Returns the remote name and prints warnings if the setup doesn't follow conventions. -/ def findMathlibRemote (mathlibDepPath : FilePath) : IO String := do let remotesInfo ← IO.Process.output {cmd := "git", args := #["remote", "-v"], cwd := mathlibDepPath} unless remotesInfo.exitCode == 0 do throw <| IO.userError s!"\ Failed to run Git to list remotes (exit code: {remotesInfo.exitCode}).\n\ Ensure Git is installed.\n\ Stdout:\n{remotesInfo.stdout.trim}\nStderr:\n{remotesInfo.stderr.trim}\n" let remoteLines := remotesInfo.stdout.split (· == '\n') let mut mathlibRemote : Option String := none let mut originPointsToMathlib : Bool := false for line in remoteLines do let parts := line.trim.split (· == '\t') if parts.length >= 2 then let remoteName := parts[0]! let remoteUrl := parts[1]!.takeWhile (· != ' ') -- Remove (fetch) or (push) suffix -- Check if this remote points to leanprover-community/mathlib4 let isMathlibRepo := remoteUrl.containsSubstr "leanprover-community/mathlib4" if isMathlibRepo then if remoteName == "origin" then originPointsToMathlib := true mathlibRemote := some remoteName match mathlibRemote with | none => throw <| IO.userError "Could not find a remote pointing to leanprover-community/mathlib4" | some remoteName => if remoteName != "upstream" then let mut warning := s!"Some Mathlib ecosystem tools assume that the git remote for `leanprover-community/mathlib4` is named `upstream`. You have named it `{remoteName}` instead. We recommend changing the name to `upstream`." if originPointsToMathlib then warning := warning ++ " Moreover, `origin` should point to your own fork of the mathlib4 repository." warning := warning ++ " You can set this up with `git remote add upstream https://github.com/leanprover-community/mathlib4.git`." IO.println s!"Warning: {warning}" return remoteName /-- Extracts PR number from a git ref like "refs/remotes/upstream/pr/1234" -/ def extractPRNumber (ref : String) : Option Nat := do let parts := ref.split (· == '/') if parts.length >= 2 && parts[parts.length - 2]! == "pr" then let prStr := parts[parts.length - 1]! prStr.toNat? else none /-- Check if we're in a detached HEAD state at a nightly-testing tag -/ def isDetachedAtNightlyTesting (mathlibDepPath : FilePath) : IO Bool := do -- Get the current commit hash and check if it's a nightly-testing tag let currentCommit ← IO.Process.output {cmd := "git", args := #["rev-parse", "HEAD"], cwd := mathlibDepPath} if currentCommit.exitCode == 0 then let commitHash := currentCommit.stdout.trim let tagInfo ← IO.Process.output {cmd := "git", args := #["name-rev", "--tags", commitHash], cwd := mathlibDepPath} if tagInfo.exitCode == 0 then let parts := tagInfo.stdout.trim.splitOn " " -- git name-rev returns "commit_hash tags/tag_name" or just "commit_hash undefined" if no tag if parts.length >= 2 && parts[1]!.startsWith "tags/" then let tagName := parts[1]!.drop 5 -- Remove "tags/" prefix return tagName.startsWith "nightly-testing-" else return false else return false else return false /-- Attempts to determine the GitHub repository of a version of Mathlib from its Git remote. If the current commit coincides with a PR ref, it will determine the source fork of that PR rather than just using the origin remote. -/ def getRemoteRepo (mathlibDepPath : FilePath) : IO RepoInfo := do -- Since currently we need to push a PR to `leanprover-community/mathlib` build a user cache, -- we check if we are a special branch or a branch with PR. This leaves out non-PRed fork -- branches. These should be covered if we ever change how the cache is uploaded from forks -- to obviate the need for a PR. let currentBranch ← IO.Process.output {cmd := "git", args := #["rev-parse", "--abbrev-ref", "HEAD"], cwd := mathlibDepPath} if currentBranch.exitCode == 0 then let branchName := currentBranch.stdout.trim.stripPrefix "heads/" IO.println s!"Current branch: {branchName}" -- Check if we're in a detached HEAD state at a nightly-testing tag let isDetachedAtNightlyTesting ← if branchName == "HEAD" then isDetachedAtNightlyTesting mathlibDepPath else pure false -- Check if we're on a branch that should use nightly-testing remote let shouldUseNightlyTesting := branchName == "nightly-testing" || branchName.startsWith "lean-pr-testing-" || branchName.startsWith "batteries-pr-testing-" || branchName.startsWith "bump/" || isDetachedAtNightlyTesting if shouldUseNightlyTesting then -- Try to use nightly-testing remote let repo ← getRepoFromRemote mathlibDepPath "nightly-testing" s!"Branch '{branchName}' should use the nightly-testing remote, but it's not configured.\n\ Please add the nightly-testing remote pointing to the nightly testing repository:\n\ git remote add nightly-testing https://github.com/leanprover-community/mathlib4-nightly-testing.git" IO.println s!"Using cache from nightly-testing remote: {repo}" return {repo := repo, useFirst := true} -- Only search for PR refs if we're not on a regular branch like master, bump/*, or nightly-testing* -- let isSpecialBranch := branchName == "master" || branchName.startsWith "bump/" || -- branchName.startsWith "nightly-testing" -- TODO: this code is currently broken in two ways: 1. you need to write `%(refname)` in quotes and -- 2. it is looking in the wrong place when in detached HEAD state. -- We comment it out for now, but we should fix it later. -- Check if the current commit coincides with any PR ref -- if !isSpecialBranch then -- let mathlibRemoteName ← findMathlibRemote mathlibDepPath -- let currentCommit ← IO.Process.output -- {cmd := "git", args := #["rev-parse", "HEAD"], cwd := mathlibDepPath} -- -- if currentCommit.exitCode == 0 then -- let commit := currentCommit.stdout.trim -- -- Get all PR refs that contain this commit -- let prRefPattern := s!"refs/remotes/{mathlibRemoteName}/pr/*" -- let refsInfo ← IO.Process.output -- {cmd := "git", args := #["for-each-ref", "--contains", commit, prRefPattern, "--format=%(refname)"], cwd := mathlibDepPath} -- -- The code below is for debugging purposes currently -- IO.println s!"`git for-each-ref --contains {commit} {prRefPattern} --format=%(refname)` returned: -- {refsInfo.stdout.trim} with exit code {refsInfo.exitCode} and stderr: {refsInfo.stderr.trim}." -- let refsInfo' ← IO.Process.output -- {cmd := "git", args := #["for-each-ref", "--contains", commit, prRefPattern, "--format=\"%(refname)\""], cwd := mathlibDepPath} -- IO.println s!"`git for-each-ref --contains {commit} {prRefPattern} --format=\"%(refname)\"` returned: -- {refsInfo'.stdout.trim} with exit code {refsInfo'.exitCode} and stderr: {refsInfo'.stderr.trim}." -- -- if refsInfo.exitCode == 0 && !refsInfo.stdout.trim.isEmpty then -- let prRefs := refsInfo.stdout.trim.split (· == '\n') -- -- Extract PR numbers from refs like "refs/remotes/upstream/pr/1234" -- for prRef in prRefs do -- if let some prNumber := extractPRNumber prRef then -- -- Get PR details using gh -- let prInfo ← IO.Process.output -- {cmd := "gh", args := #["pr", "view", toString prNumber, "--json", "headRefName,headRepositoryOwner,number"], cwd := mathlibDepPath} -- if prInfo.exitCode == 0 then -- if let .ok json := Lean.Json.parse prInfo.stdout.trim then -- if let .ok owner := json.getObjValAs? Lean.Json "headRepositoryOwner" then -- if let .ok login := owner.getObjValAs? String "login" then -- if let .ok repoName := json.getObjValAs? String "headRefName" then -- if let .ok prNum := json.getObjValAs? Nat "number" then -- let repo := s!"{login}/mathlib4" -- IO.println s!"Using cache from PR #{prNum} source: {login}/{repoName} (commit {commit.take 8} found in PR ref)" -- let useFirst := if login != "leanprover-community" then true else false -- return {repo := repo, useFirst := useFirst} -- Fall back to using the remote that the current branch is tracking let trackingRemote ← IO.Process.output {cmd := "git", args := #["config", "--get", s!"branch.{currentBranch.stdout.trim}.remote"], cwd := mathlibDepPath} let remoteName := if trackingRemote.exitCode == 0 then trackingRemote.stdout.trim else -- If no tracking remote is configured, fall back to origin "origin" let repo ← getRepoFromRemote mathlibDepPath remoteName s!"Ensure Git is installed and the '{remoteName}' remote points to its GitHub repository." IO.println s!"Using cache from {remoteName}: {repo}" return {repo := repo, useFirst := false} -- FRO cache may be flaky: https://leanprover.zulipchat.com/#narrow/channel/113488-general/topic/The.20cache.20doesn't.20work/near/411058849 def useFROCache : Bool := true /-- Public URL for mathlib cache -/ def URL : String := if useFROCache then "https://mathlib4.lean-cache.cloud" else "https://lakecache.blob.core.windows.net/mathlib4" /-- Retrieves the azure token from the environment -/ def getToken : IO String := do let envVar := if useFROCache then "MATHLIB_CACHE_S3_TOKEN" else "MATHLIB_CACHE_SAS" let some token ← IO.getEnv envVar | throw <| IO.userError s!"environment variable {envVar} must be set to upload caches" return token /-- The full name of the main Mathlib GitHub repository. -/ def MATHLIBREPO := "leanprover-community/mathlib4" /-- Given a file name like `"1234.tar.gz"`, makes the URL to that file on the server. The `f/` prefix means that it's a common file for caching. -/ def mkFileURL (repo URL fileName : String) : String := let pre := if !useFROCache && repo == MATHLIBREPO then "" else s!"{repo}/" s!"{URL}/f/{pre}{fileName}" section Get /-- Formats the config file for `curl`, containing the list of files to be downloaded -/ def mkGetConfigContent (repo : String) (hashMap : IO.ModuleHashMap) : IO String := do hashMap.toArray.foldlM (init := "") fun acc ⟨_, hash⟩ => do let fileName := hash.asLTar -- Below we use `String.quote`, which is intended for quoting for use in Lean code -- this does not exactly match the requirements for quoting for curl: -- ``` -- If the parameter contains whitespace (or starts with : or =), -- the parameter must be enclosed within quotes. -- Within double quotes, the following escape sequences are available: -- \, ", \t, \n, \r and \v. -- A backslash preceding any other letter is ignored. -- ``` -- If this becomes an issue we can implement the curl spec. -- Note we append a '.part' to the filenames here, -- which `downloadFiles` then removes when the download is successful. pure <| acc ++ s!"url = {mkFileURL repo URL fileName}\n\ -o {(IO.CACHEDIR / (fileName ++ ".part")).toString.quote}\n" /-- Calls `curl` to download a single file from the server to `CACHEDIR` (`.cache`) -/ def downloadFile (repo : String) (hash : UInt64) : IO Bool := do let fileName := hash.asLTar let url := mkFileURL repo URL fileName let path := IO.CACHEDIR / fileName let partFileName := fileName ++ ".part" let partPath := IO.CACHEDIR / partFileName let out ← IO.Process.output { cmd := (← IO.getCurl), args := #[url, "--fail", "--silent", "-o", partPath.toString] } if out.exitCode = 0 then IO.FS.rename partPath path pure true else IO.FS.removeFile partPath pure false /-- Call `curl` to download files from the server to `CACHEDIR` (`.cache`). Exit the process with exit code 1 if any files failed to download. -/ def downloadFiles (repo : String) (hashMap : IO.ModuleHashMap) (forceDownload : Bool) (parallel : Bool) (warnOnMissing : Bool): IO Unit := do let hashMap ← if forceDownload then pure hashMap else hashMap.filterExists false let size := hashMap.size if size > 0 then IO.FS.createDirAll IO.CACHEDIR IO.println s!"Attempting to download {size} file(s) from {repo} cache" let failed ← if parallel then IO.FS.writeFile IO.CURLCFG (← mkGetConfigContent repo hashMap) let args := #["--request", "GET", "--parallel", -- commented as this creates a big slowdown on curl 8.13.0: "--fail", "--silent", "--retry", "5", -- there seem to be some intermittent failures "--write-out", "%{json}\n", "--config", IO.CURLCFG.toString] let (_, success, failed, done) ← IO.runCurlStreaming args (← IO.monoMsNow, 0, 0, 0) fun a line => do let mut (last, success, failed, done) := a -- output errors other than 404 and remove corresponding partial downloads let line := line.trim if !line.isEmpty then let result ← IO.ofExcept <| Lean.Json.parse line match result.getObjValAs? Nat "http_code" with | .ok 200 => if let .ok fn := result.getObjValAs? String "filename_effective" then if (← System.FilePath.pathExists fn) && fn.endsWith ".part" then IO.FS.rename fn (fn.dropRight 5) success := success + 1 | .ok 404 => pure () | _ => failed := failed + 1 if let .ok e := result.getObjValAs? String "errormsg" then IO.println e -- `curl --remove-on-error` can already do this, but only from 7.83 onwards if let .ok fn := result.getObjValAs? String "filename_effective" then if (← System.FilePath.pathExists fn) then IO.FS.removeFile fn done := done + 1 let now ← IO.monoMsNow if now - last ≥ 100 then -- max 10/s update rate let mut msg := s!"\rDownloaded: {success} file(s) [attempted {done}/{size} = {100*done/size}%]" if failed != 0 then msg := msg ++ s!", {failed} failed" IO.eprint msg last := now pure (last, success, failed, done) if done > 0 then -- to avoid confusingly moving on without finishing the count let mut msg := s!"\rDownloaded: {success} file(s) [attempted {done}/{size} = {100*done/size}%] ({100*success/done}% success)" if failed != 0 then msg := msg ++ s!", {failed} failed" IO.eprintln msg IO.FS.removeFile IO.CURLCFG if warnOnMissing && success + failed < done then IO.eprintln "Warning: some files were not found in the cache." IO.eprintln "This usually means that your local checkout of mathlib4 has diverged from upstream." IO.eprintln "If you push your commits to a branch of the mathlib4 repository, CI will build the oleans and they will be available later." IO.eprintln "Alternatively, if you already have pushed your commits to a branch, this may mean the CI build has failed part-way through building." IO.eprintln "During August 2025, we are changing the back-end for the olean cache. If you are unexpectedly not finding oleans for your PR, please try merging `master`." pure failed else let r ← hashMap.foldM (init := []) fun acc _ hash => do pure <| (← IO.asTask do downloadFile repo hash) :: acc pure <| r.foldl (init := 0) fun f t => if let .ok true := t.get then f else f + 1 if failed > 0 then IO.println s!"{failed} download(s) failed" IO.Process.exit 1 else IO.println "No files to download" /-- Check if the project's `lean-toolchain` file matches mathlib's. Print and error and exit the process with error code 1 otherwise. -/ def checkForToolchainMismatch : IO.CacheM Unit := do let mathlibToolchainFile := (← read).mathlibDepPath / "lean-toolchain" let downstreamToolchain ← IO.FS.readFile "lean-toolchain" let mathlibToolchain ← IO.FS.readFile mathlibToolchainFile if !(mathlibToolchain.trim = downstreamToolchain.trim) then IO.println "Dependency Mathlib uses a different lean-toolchain" IO.println s!" Project uses {downstreamToolchain.trim}" IO.println s!" Mathlib uses {mathlibToolchain.trim}" IO.println "\nThe cache will not work unless your project's toolchain matches Mathlib's toolchain" IO.println s!"This can be achieved by copying the contents of the file `{mathlibToolchainFile}` into the `lean-toolchain` file at the root directory of your project" if !System.Platform.isWindows then IO.println s!"You can use `cp {mathlibToolchainFile} ./lean-toolchain`" else IO.println s!"On powershell you can use `cp {mathlibToolchainFile} ./lean-toolchain`" IO.println s!"On Windows CMD you can use `copy {mathlibToolchainFile} lean-toolchain`" IO.Process.exit 1 return () /-- Fetches the ProofWidgets cloud release and prunes non-JS files. -/ def getProofWidgets (buildDir : FilePath) : IO Unit := do if (← buildDir.pathExists) then -- Check if the ProofWidgets build is out-of-date via `lake`. -- This is done through Lake as cache has no simple heuristic -- to determine whether the ProofWidgets JS is out-of-date. let exitCode ← (← IO.Process.spawn {cmd := "lake", args := #["-q", "build", "--no-build", "proofwidgets:release"]}).wait if exitCode == 0 then -- up-to-date return else if exitCode == 3 then -- needs fetch (`--no-build` triggered) pure () else throw <| IO.userError s!"Failed to validate ProofWidgets cloud release: lake failed with error code {exitCode}" -- Download and unpack the ProofWidgets cloud release (for its `.js` files) let exitCode ← (← IO.Process.spawn {cmd := "lake", args := #["-q", "build", "proofwidgets:release"]}).wait if exitCode != 0 then throw <| IO.userError s!"Failed to fetch ProofWidgets cloud release: lake failed with error code {exitCode}" -- Prune non-JS ProofWidgets files (e.g., `olean`, `.c`) try IO.FS.removeDirAll (buildDir / "lib") IO.FS.removeDirAll (buildDir / "ir") catch e => throw <| IO.userError s!"Failed to prune ProofWidgets cloud release: {e}" /-- Downloads missing files, and unpacks files. -/ def getFiles (repo? : Option String) (hashMap : IO.ModuleHashMap) (forceDownload forceUnpack parallel decompress : Bool) : IO.CacheM Unit := do let isMathlibRoot ← IO.isMathlibRoot unless isMathlibRoot do checkForToolchainMismatch getProofWidgets (← read).proofWidgetsBuildDir if let some repo := repo? then downloadFiles repo hashMap forceDownload parallel (warnOnMissing := true) else let repoInfo ← getRemoteRepo (← read).mathlibDepPath -- Build list of repositories to download from in order let repos : List String := if repoInfo.repo == MATHLIBREPO then [repoInfo.repo] else if repoInfo.useFirst then [repoInfo.repo, MATHLIBREPO] else [MATHLIBREPO, repoInfo.repo] for h : i in [0:repos.length] do downloadFiles repos[i] hashMap forceDownload parallel (warnOnMissing := i = repos.length - 1) if decompress then IO.unpackCache hashMap forceUnpack else IO.println "Downloaded all files successfully!" end Get section Put /-- FRO cache S3 URL -/ def UPLOAD_URL : String := if useFROCache then "https://a09a7664adc082e00f294ac190827820.r2.cloudflarestorage.com/mathlib4" else URL /-- Formats the config file for `curl`, containing the list of files to be uploaded -/ def mkPutConfigContent (repo : String) (fileNames : Array String) (token : String) : IO String := do let token := if useFROCache then "" else s!"?{token}" -- the FRO cache doesn't pass the token here let l ← fileNames.toList.mapM fun fileName : String => do pure s!"-T {(IO.CACHEDIR / fileName).toString}\nurl = {mkFileURL repo UPLOAD_URL fileName}{token}" return "\n".intercalate l /-- Calls `curl` to send a set of cached files to the server -/ def putFiles (repo : String) (fileNames : Array String) (overwrite : Bool) (token : String) : IO Unit := do -- TODO: reimplement using HEAD requests? let _ := overwrite let size := fileNames.size if size > 0 then IO.FS.writeFile IO.CURLCFG (← mkPutConfigContent repo fileNames token) IO.println s!"Attempting to upload {size} file(s) to {repo} cache" let args := if useFROCache then -- TODO: reimplement using HEAD requests? let _ := overwrite #["--aws-sigv4", "aws:amz:auto:s3", "--user", token] else if overwrite then #["-H", "x-ms-blob-type: BlockBlob"] else #["-H", "x-ms-blob-type: BlockBlob", "-H", "If-None-Match: *"] let out ← IO.runCurl (stderrAsErr := false) (args ++ #[ "--retry", "5", -- there seem to be some intermittent failures "-X", "PUT", "--parallel", "-K", IO.CURLCFG.toString]) if out.trim != "" then IO.println s!"Output from curl:" IO.println out IO.FS.removeFile IO.CURLCFG else IO.println "No files to upload" end Put section Commit def isGitStatusClean : IO Bool := return (← IO.runCmd "git" #["status", "--porcelain"]).isEmpty def getGitCommitHash : IO String := return (← IO.runCmd "git" #["rev-parse", "HEAD"]).trimRight /-- Sends a commit file to the server, containing the hashes of the respective committed files. The file name is the current Git hash and the `c/` prefix means that it's a commit file. -/ def commit (hashMap : IO.ModuleHashMap) (overwrite : Bool) (token : String) : IO Unit := do let hash ← getGitCommitHash let path := IO.CACHEDIR / hash IO.FS.createDirAll IO.CACHEDIR IO.FS.writeFile path <| ("\n".intercalate <| hashMap.hashes.toList.map toString) ++ "\n" if useFROCache then -- TODO: reimplement using HEAD requests? let _ := overwrite discard <| IO.runCurl #["-T", path.toString, "--aws-sigv4", "aws:amz:auto:s3", "--user", token, s!"{UPLOAD_URL}/c/{hash}"] else let params := if overwrite then #["-X", "PUT", "-H", "x-ms-blob-type: BlockBlob"] else #["-X", "PUT", "-H", "x-ms-blob-type: BlockBlob", "-H", "If-None-Match: *"] discard <| IO.runCurl <| params ++ #["-T", path.toString, s!"{URL}/c/{hash}?{token}"] IO.FS.removeFile path end Commit section Collect inductive QueryType | files | commits | all def QueryType.prefix : QueryType → String | files => "&prefix=f/" | commits => "&prefix=c/" | all => "" def formatError {α : Type} : IO α := throw <| IO.userError "Invalid format for curl return" def QueryType.desc : QueryType → String | files => "hosted files" | commits => "hosted commits" | all => "everything" /-- Retrieves metadata about hosted files: their names and the timestamps of last modification. Example: `["f/39476538726384726.tar.gz", "Sat, 24 Dec 2022 17:33:01 GMT"]` -/ def getFilesInfo (q : QueryType) : IO <| List (String × String) := do if useFROCache then throw <| .userError "FIXME: getFilesInfo is not adapted to FRO cache yet" IO.println s!"Downloading info list of {q.desc}" let ret ← IO.runCurl #["-X", "GET", s!"{URL}?comp=list&restype=container{q.prefix}"] match ret.splitOn "<Name>" with | [] => formatError | [_] => return [] | _ :: parts => parts.mapM fun part => match part.splitOn "</Name>" with | [name, rest] => match rest.splitOn "<Last-Modified>" with | [_, rest] => match rest.splitOn "</Last-Modified>" with | [date, _] => pure (name, date) | _ => formatError | _ => formatError | _ => formatError end Collect end Cache.Requests
MonoidWithZero.lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import Mathlib.Algebra.GroupWithZero.Hom import Mathlib.GroupTheory.MonoidLocalization.Basic import Mathlib.RingTheory.OreLocalization.Basic import Mathlib.Algebra.GroupWithZero.Units.Basic /-! # Localizations of commutative monoids with zeroes -/ open Function namespace Submonoid.LocalizationMap @[to_additive] theorem injective_iff {M N : Type*} [CommMonoid M] {S : Submonoid M} [CommMonoid N] (f : LocalizationMap S N) : Injective f ↔ ∀ ⦃x⦄, x ∈ S → IsLeftRegular x := by rw [Injective] constructor <;> intro h · intro x hx y z hyz simp_rw [LocalizationMap.eq_iff_exists] at h apply (fun y z _ => h) y z x lift x to S using hx use x · intro a b hab rw [LocalizationMap.eq_iff_exists] at hab obtain ⟨c,hc⟩ := hab apply (fun x a => h a) c (SetLike.coe_mem c) hc end Submonoid.LocalizationMap section CommMonoidWithZero variable {M : Type*} [CommMonoidWithZero M] (S : Submonoid M) (N : Type*) [CommMonoidWithZero N] {P : Type*} [CommMonoidWithZero P] namespace Submonoid variable {S N} in /-- If `S` contains `0` then the localization at `S` is trivial. -/ theorem LocalizationMap.subsingleton (f : Submonoid.LocalizationMap S N) (h : 0 ∈ S) : Subsingleton N := by refine ⟨fun a b ↦ ?_⟩ rw [← LocalizationMap.mk'_sec f a, ← LocalizationMap.mk'_sec f b, LocalizationMap.eq] exact ⟨⟨0, h⟩, by simp only [zero_mul]⟩ /-- The type of homomorphisms between monoids with zero satisfying the characteristic predicate: if `f : M →*₀ N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ structure LocalizationWithZeroMap extends LocalizationMap S N where map_zero' : toFun 0 = 0 variable {S N} /-- The monoid with zero hom underlying a `LocalizationMap`. -/ def LocalizationWithZeroMap.toMonoidWithZeroHom (f : LocalizationWithZeroMap S N) : M →*₀ N := { f with } end Submonoid namespace Localization variable {S} theorem mk_zero (x : S) : mk 0 (x : S) = 0 := OreLocalization.zero_oreDiv' _ instance : CommMonoidWithZero (Localization S) where zero_mul := fun x ↦ Localization.induction_on x fun y => by simp only [← Localization.mk_zero y.2, mk_mul, mk_eq_mk_iff, mul_zero, zero_mul, r_of_eq] mul_zero := fun x ↦ Localization.induction_on x fun y => by simp only [← Localization.mk_zero y.2, mk_mul, mk_eq_mk_iff, mul_zero, r_of_eq] theorem liftOn_zero {p : Type*} (f : M → S → p) (H) : liftOn 0 f H = f 0 1 := by rw [← mk_zero 1, liftOn_mk] end Localization variable {S N} namespace Submonoid @[simp] theorem LocalizationMap.sec_zero_fst {f : LocalizationMap S N} : f (f.sec 0).fst = 0 := by rw [LocalizationMap.sec_spec', mul_zero] namespace LocalizationWithZeroMap /-- Given a Localization map `f : M →*₀ N` for a Submonoid `S ⊆ M` and a map of `CommMonoidWithZero`s `g : M →*₀ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x * (g y)⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (f : LocalizationWithZeroMap S N) (g : M →*₀ P) (hg : ∀ y : S, IsUnit (g y)) : N →*₀ P := { @LocalizationMap.lift _ _ _ _ _ _ _ f.toLocalizationMap g.toMonoidHom hg with map_zero' := by dsimp only [OneHom.toFun_eq_coe, MonoidHom.toOneHom_coe] rw [LocalizationMap.lift_spec f.toLocalizationMap hg 0 0, mul_zero, ← map_zero g, ← g.toMonoidHom_coe] refine f.toLocalizationMap.eq_of_eq hg ?_ rw [LocalizationMap.sec_zero_fst] exact f.toMonoidWithZeroHom.map_zero.symm } lemma lift_def (f : LocalizationWithZeroMap S N) (g : M →*₀ P) (hg : ∀ y : S, IsUnit (g y)) : ⇑(f.lift g hg) = f.toLocalizationMap.lift (g := ↑g) hg := rfl lemma lift_apply (f : LocalizationWithZeroMap S N) (g : M →*₀ P) (hg : ∀ y : S, IsUnit (g y)) (x) : (f.lift g hg) x = g (f.sec x).1 * (IsUnit.liftRight (g.restrict S) hg (f.sec x).2)⁻¹ := rfl /-- Given a Localization map `f : M →*₀ N` for a Submonoid `S ⊆ M`, if `M` is left cancellative monoid with zero, and all elements of `S` are left regular, then N is a left cancellative monoid with zero. -/ theorem leftCancelMulZero_of_le_isLeftRegular (f : LocalizationWithZeroMap S N) [IsLeftCancelMulZero M] (h : ∀ ⦃x⦄, x ∈ S → IsLeftRegular x) : IsLeftCancelMulZero N := by let fl := f.toLocalizationMap constructor intro a ha z w hazw obtain ⟨b, hb⟩ := LocalizationMap.surj fl a obtain ⟨x, hx⟩ := LocalizationMap.surj fl z obtain ⟨y, hy⟩ := LocalizationMap.surj fl w rw [(LocalizationMap.eq_mk'_iff_mul_eq fl).mpr hx, (LocalizationMap.eq_mk'_iff_mul_eq fl).mpr hy, LocalizationMap.eq] use 1 rw [OneMemClass.coe_one, one_mul, one_mul] -- The hypothesis `a ≠ 0` in `P` is equivalent to this have b1ne0 : b.1 ≠ 0 := by intro hb1 have m0 : fl 0 = 0 := f.map_zero' have a0 : a * fl b.2 = 0 ↔ a = 0 := (f.toLocalizationMap.map_units' b.2).mul_left_eq_zero rw [hb1, m0, a0] at hb exact ha hb have main : fl (b.1 * (x.2 * y.1)) = fl (b.1 * (y.2 * x.1)) := calc fl (b.1 * (x.2 * y.1)) = fl b.1 * (fl x.2 * fl y.1) := by rw [map_mul fl,map_mul fl] _ = a * fl b.2 * (fl x.2 * (w * fl y.2)) := by rw [hb, hy] _ = a * w * fl b.2 * (fl x.2 * fl y.2) := by rw [← mul_assoc, ← mul_assoc _ w, mul_comm _ w, mul_assoc w, mul_assoc, ← mul_assoc w, ← mul_assoc w, mul_comm w] _ = a * z * fl b.2 * (fl x.2 * fl y.2) := by dsimp only at hazw; rw [hazw] _ = a * fl b.2 * (z * fl x.2 * fl y.2) := by rw [mul_assoc a, mul_comm z, ← mul_assoc a, mul_assoc, mul_assoc z] _ = fl b.1 * fl (y.2 * x.1) := by rw [hx, hb, mul_comm (fl x.1), ← map_mul fl] _ = fl (b.1 * (y.2 * x.1)) := by rw [← map_mul fl] -- The hypothesis `h` gives that `f` is injective, and we can cancel out `b.1`. exact (IsLeftCancelMulZero.mul_left_cancel_of_ne_zero b1ne0 ((LocalizationMap.injective_iff fl).mpr h main)).symm /-- Given a Localization map `f : M →*₀ N` for a Submonoid `S ⊆ M`, if `M` is a cancellative monoid with zero, and all elements of `S` are regular, then N is a cancellative monoid with zero. -/ theorem isLeftRegular_of_le_isCancelMulZero (f : LocalizationWithZeroMap S N) [IsCancelMulZero M] (h : ∀ ⦃x⦄, x ∈ S → IsRegular x) : IsCancelMulZero N := by have : IsLeftCancelMulZero N := leftCancelMulZero_of_le_isLeftRegular f (fun x h' => (h h').left) exact IsLeftCancelMulZero.to_isCancelMulZero end LocalizationWithZeroMap end Submonoid end CommMonoidWithZero
Defs.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, Jens Wagemaker -/ import Mathlib.Algebra.Group.Irreducible.Defs import Mathlib.Algebra.GroupWithZero.Divisibility /-! # Prime elements In this file we define the predicate `Prime p` saying that an element of a commutative monoid with zero is prime. Namely, `Prime p` means that `p` isn't zero, it isn't a unit, and `p ∣ a * b → p ∣ a ∨ p ∣ b` for all `a`, `b`; In decomposition monoids (e.g., `ℕ`, `ℤ`), this predicate is equivalent to `Irreducible` (see `irreducible_iff_prime`), however this is not true in general. ## Main definitions * `Prime`: a prime element of a commutative monoid with zero ## Main results * `irreducible_iff_prime`: the two definitions are equivalent in a decomposition monoid. -/ assert_not_exists OrderedCommMonoid Multiset variable {M : Type*} section Prime variable [CommMonoidWithZero M] /-- An element `p` of a commutative monoid with zero (e.g., a ring) is called *prime*, if it's not zero, not a unit, and `p ∣ a * b → p ∣ a ∨ p ∣ b` for all `a`, `b`. -/ def Prime (p : M) : Prop := p ≠ 0 ∧ ¬IsUnit p ∧ ∀ a b, p ∣ a * b → p ∣ a ∨ p ∣ b namespace Prime variable {p : M} (hp : Prime p) include hp theorem ne_zero : p ≠ 0 := hp.1 theorem not_unit : ¬IsUnit p := hp.2.1 theorem not_dvd_one : ¬p ∣ 1 := mt (isUnit_of_dvd_one ·) hp.not_unit theorem ne_one : p ≠ 1 := fun h => hp.2.1 (h.symm ▸ isUnit_one) theorem dvd_or_dvd {a b : M} (h : p ∣ a * b) : p ∣ a ∨ p ∣ b := hp.2.2 a b h theorem dvd_mul {a b : M} : p ∣ a * b ↔ p ∣ a ∨ p ∣ b := ⟨hp.dvd_or_dvd, (Or.elim · (dvd_mul_of_dvd_left · _) (dvd_mul_of_dvd_right · _))⟩ theorem isPrimal : IsPrimal p := fun _a _b dvd ↦ (hp.dvd_or_dvd dvd).elim (fun h ↦ ⟨p, 1, h, one_dvd _, (mul_one p).symm⟩) fun h ↦ ⟨1, p, one_dvd _, h, (one_mul p).symm⟩ theorem not_dvd_mul {a b : M} (ha : ¬ p ∣ a) (hb : ¬ p ∣ b) : ¬ p ∣ a * b := hp.dvd_mul.not.mpr <| not_or.mpr ⟨ha, hb⟩ theorem dvd_of_dvd_pow {a : M} {n : ℕ} (h : p ∣ a ^ n) : p ∣ a := by induction n with | zero => rw [pow_zero] at h have := isUnit_of_dvd_one h have := not_unit hp contradiction | succ n ih => rw [pow_succ'] at h rcases dvd_or_dvd hp h with dvd_a | dvd_pow · assumption · exact ih dvd_pow theorem dvd_pow_iff_dvd {a : M} {n : ℕ} (hn : n ≠ 0) : p ∣ a ^ n ↔ p ∣ a := ⟨hp.dvd_of_dvd_pow, (dvd_pow · hn)⟩ end Prime @[simp] theorem not_prime_zero : ¬Prime (0 : M) := fun h => h.ne_zero rfl @[simp] theorem not_prime_one : ¬Prime (1 : M) := fun h => h.not_unit isUnit_one end Prime theorem Irreducible.not_dvd_isUnit [CommMonoid M] {p u : M} (hp : Irreducible p) (hu : IsUnit u) : ¬p ∣ u := mt (isUnit_of_dvd_unit · hu) hp.not_isUnit theorem Irreducible.not_dvd_one [CommMonoid M] {p : M} (hp : Irreducible p) : ¬p ∣ 1 := hp.not_dvd_isUnit isUnit_one theorem Irreducible.not_dvd_unit [CommMonoid M] {p : M} (u : Mˣ) (hp : Irreducible p) : ¬ p ∣ u := hp.not_dvd_isUnit u.isUnit @[simp] theorem not_irreducible_zero [MonoidWithZero M] : ¬Irreducible (0 : M) | ⟨hn0, h⟩ => have : IsUnit (0 : M) ∨ IsUnit (0 : M) := h (mul_zero 0).symm this.elim hn0 hn0 theorem Irreducible.ne_zero [MonoidWithZero M] : ∀ {p : M}, Irreducible p → p ≠ 0 | _, hp, rfl => not_irreducible_zero hp /-- If `p` and `q` are irreducible, then `p ∣ q` implies `q ∣ p`. -/ theorem Irreducible.dvd_symm [Monoid M] {p q : M} (hp : Irreducible p) (hq : Irreducible q) : p ∣ q → q ∣ p := by rintro ⟨q', rfl⟩ rw [IsUnit.mul_right_dvd (Or.resolve_left (of_irreducible_mul hq) hp.not_isUnit)] theorem Irreducible.dvd_comm [Monoid M] {p q : M} (hp : Irreducible p) (hq : Irreducible q) : p ∣ q ↔ q ∣ p := ⟨hp.dvd_symm hq, hq.dvd_symm hp⟩ section CommMonoidWithZero variable [CommMonoidWithZero M] theorem Irreducible.prime_of_isPrimal {a : M} (irr : Irreducible a) (primal : IsPrimal a) : Prime a := ⟨irr.ne_zero, irr.not_isUnit, fun a b dvd ↦ by obtain ⟨d₁, d₂, h₁, h₂, rfl⟩ := primal dvd exact (of_irreducible_mul irr).symm.imp (·.mul_right_dvd.mpr h₁) (·.mul_left_dvd.mpr h₂)⟩ theorem Irreducible.prime [DecompositionMonoid M] {a : M} (irr : Irreducible a) : Prime a := irr.prime_of_isPrimal (DecompositionMonoid.primal a) end CommMonoidWithZero section CancelCommMonoidWithZero variable [CancelCommMonoidWithZero M] {p : M} protected theorem Prime.irreducible (hp : Prime p) : Irreducible p := ⟨hp.not_unit, fun a b ↦ by rintro rfl exact (hp.dvd_or_dvd dvd_rfl).symm.imp (isUnit_of_dvd_one <| (mul_dvd_mul_iff_right <| right_ne_zero_of_mul hp.ne_zero).mp <| dvd_mul_of_dvd_right · _) (isUnit_of_dvd_one <| (mul_dvd_mul_iff_left <| left_ne_zero_of_mul hp.ne_zero).mp <| dvd_mul_of_dvd_left · _)⟩ theorem irreducible_iff_prime [DecompositionMonoid M] {a : M} : Irreducible a ↔ Prime a := ⟨Irreducible.prime, Prime.irreducible⟩ end CancelCommMonoidWithZero
Pow.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.Analysis.Calculus.FDeriv.Pow /-! # Derivative of `(f x) ^ n`, `n : ℕ` In this file we prove that the Fréchet derivative of `fun x => f x ^ n`, where `n` is a natural number, is `n * f x ^ (n - 1) * f'`. Additionally, we prove the case for non-commutative rings (with primed names like `deriv_pow'`), where the result is instead `∑ i ∈ Finset.range n, f x ^ (n.pred - i) * f' * f x ^ i`. For a more detailed overview of one-dimensional derivatives in mathlib, see the module docstring of `Mathlib/Analysis/Calculus/Deriv/Basic.lean`. ## Keywords derivative, power -/ variable {𝕜 𝔸 : Type*} section NormedRing variable [NontriviallyNormedField 𝕜] [NormedRing 𝔸] variable [NormedAlgebra 𝕜 𝔸] {f : 𝕜 → 𝔸} {f' : 𝔸} {x : 𝕜} {s : Set 𝕜} nonrec theorem HasStrictDerivAt.fun_pow' (h : HasStrictDerivAt f f' x) (n : ℕ) : HasStrictDerivAt (fun x ↦ f x ^ n) (∑ i ∈ Finset.range n, f x ^ (n.pred - i) * f' * f x ^ i) x := by unfold HasStrictDerivAt convert h.pow' n ext simp nonrec theorem HasStrictDerivAt.pow' (h : HasStrictDerivAt f f' x) (n : ℕ) : HasStrictDerivAt (f ^ n) (∑ i ∈ Finset.range n, f x ^ (n.pred - i) * f' * f x ^ i) x := h.fun_pow' n nonrec theorem HasDerivWithinAt.fun_pow' (h : HasDerivWithinAt f f' s x) (n : ℕ) : HasDerivWithinAt (fun x ↦ f x ^ n) (∑ i ∈ Finset.range n, f x ^ (n.pred - i) * f' * f x ^ i) s x := by simpa using h.hasFDerivWithinAt.pow' n |>.hasDerivWithinAt nonrec theorem HasDerivWithinAt.pow' (h : HasDerivWithinAt f f' s x) (n : ℕ) : HasDerivWithinAt (f ^ n) (∑ i ∈ Finset.range n, f x ^ (n.pred - i) * f' * f x ^ i) s x := h.fun_pow' n theorem HasDerivAt.fun_pow' (h : HasDerivAt f f' x) (n : ℕ) : HasDerivAt (fun x ↦ f x ^ n) (∑ i ∈ Finset.range n, f x ^ (n.pred - i) * f' * f x ^ i) x := by simpa using h.hasFDerivAt.pow' n |>.hasDerivAt theorem HasDerivAt.pow' (h : HasDerivAt f f' x) (n : ℕ) : HasDerivAt (f ^ n) (∑ i ∈ Finset.range n, f x ^ (n.pred - i) * f' * f x ^ i) x := h.fun_pow' n @[simp low] theorem derivWithin_fun_pow' (h : DifferentiableWithinAt 𝕜 f s x) (n : ℕ) : derivWithin (fun x => f x ^ n) s x = ∑ i ∈ Finset.range n, f x ^ (n.pred - i) * derivWithin f s x * f x ^ i := by by_cases hsx : UniqueDiffWithinAt 𝕜 s x · exact (h.hasDerivWithinAt.pow' n).derivWithin hsx · simp [derivWithin_zero_of_not_uniqueDiffWithinAt hsx] @[simp low] theorem derivWithin_pow' (h : DifferentiableWithinAt 𝕜 f s x) (n : ℕ) : derivWithin (f ^ n) s x = ∑ i ∈ Finset.range n, f x ^ (n.pred - i) * derivWithin f s x * f x ^ i := derivWithin_fun_pow' h n @[simp low] theorem deriv_fun_pow' (h : DifferentiableAt 𝕜 f x) (n : ℕ) : deriv (fun x => f x ^ n) x = ∑ i ∈ Finset.range n, f x ^ (n.pred - i) * deriv f x * f x ^ i := (h.hasDerivAt.pow' n).deriv @[simp low] theorem deriv_pow' (h : DifferentiableAt 𝕜 f x) (n : ℕ) : deriv (f ^ n) x = ∑ i ∈ Finset.range n, f x ^ (n.pred - i) * deriv f x * f x ^ i := deriv_fun_pow' h n end NormedRing section NormedCommRing variable [NontriviallyNormedField 𝕜] [NormedCommRing 𝔸] variable [NormedAlgebra 𝕜 𝔸] {f : 𝕜 → 𝔸} {f' : 𝔸} {x : 𝕜} {s : Set 𝕜} open scoped RightActions nonrec theorem HasStrictDerivAt.fun_pow (h : HasStrictDerivAt f f' x) (n : ℕ) : HasStrictDerivAt (fun x ↦ f x ^ n) (n * f x ^ (n - 1) * f') x := by unfold HasStrictDerivAt convert h.pow n ext simp [mul_assoc] nonrec theorem HasStrictDerivAt.pow (h : HasStrictDerivAt f f' x) (n : ℕ) : HasStrictDerivAt (f ^ n) (n * f x ^ (n - 1) * f') x := h.fun_pow n nonrec theorem HasDerivWithinAt.fun_pow (h : HasDerivWithinAt f f' s x) (n : ℕ) : HasDerivWithinAt (fun x ↦ f x ^ n) (n * f x ^ (n - 1) * f') s x := by simpa using h.hasFDerivWithinAt.pow n |>.hasDerivWithinAt nonrec theorem HasDerivWithinAt.pow (h : HasDerivWithinAt f f' s x) (n : ℕ) : HasDerivWithinAt (f ^ n) (n * f x ^ (n - 1) * f') s x := h.fun_pow n theorem HasDerivAt.fun_pow (h : HasDerivAt f f' x) (n : ℕ) : HasDerivAt (fun x ↦ f x ^ n) (n * f x ^ (n - 1) * f') x := by simpa using h.hasFDerivAt.pow n |>.hasDerivAt theorem HasDerivAt.pow (h : HasDerivAt f f' x) (n : ℕ) : HasDerivAt (f ^ n) (n * f x ^ (n - 1) * f') x := h.fun_pow n @[simp] theorem derivWithin_fun_pow (h : DifferentiableWithinAt 𝕜 f s x) (n : ℕ) : derivWithin (fun x => f x ^ n) s x = n * f x ^ (n - 1) * derivWithin f s x := by by_cases hsx : UniqueDiffWithinAt 𝕜 s x · exact (h.hasDerivWithinAt.pow n).derivWithin hsx · simp [derivWithin_zero_of_not_uniqueDiffWithinAt hsx] @[simp] theorem derivWithin_pow (h : DifferentiableWithinAt 𝕜 f s x) (n : ℕ) : derivWithin (f ^ n) s x = n * f x ^ (n - 1) * derivWithin f s x := derivWithin_fun_pow h n @[simp] theorem deriv_fun_pow (h : DifferentiableAt 𝕜 f x) (n : ℕ) : deriv (fun x => f x ^ n) x = n * f x ^ (n - 1) * deriv f x := (h.hasDerivAt.pow n).deriv @[simp] theorem deriv_pow (h : DifferentiableAt 𝕜 f x) (n : ℕ) : deriv (f ^ n) x = n * f x ^ (n - 1) * deriv f x := deriv_fun_pow h n end NormedCommRing section NontriviallyNormedField variable [NontriviallyNormedField 𝕜] {x : 𝕜} {s : Set 𝕜} {c : 𝕜 → 𝕜} @[deprecated deriv_fun_pow (since := "2025-07-16")] theorem deriv_fun_pow'' {c : 𝕜 → 𝕜} (n : ℕ) (hc : DifferentiableAt 𝕜 c x) : deriv (fun x => c x ^ n) x = (n : 𝕜) * c x ^ (n - 1) * deriv c x := deriv_fun_pow hc n @[deprecated deriv_pow (since := "2025-07-16")] theorem deriv_pow'' {c : 𝕜 → 𝕜} (n : ℕ) (hc : DifferentiableAt 𝕜 c x) : deriv (c ^ n) x = (n : 𝕜) * c x ^ (n - 1) * deriv c x := deriv_pow hc n theorem hasStrictDerivAt_pow (n : ℕ) (x : 𝕜) : HasStrictDerivAt (fun x : 𝕜 ↦ x ^ n) (n * x ^ (n - 1)) x := by simpa using (hasStrictDerivAt_id x).pow n theorem hasDerivWithinAt_pow (n : ℕ) (x : 𝕜) : HasDerivWithinAt (fun x : 𝕜 ↦ x ^ n) (n * x ^ (n - 1)) s x := by simpa using (hasDerivWithinAt_id x s).pow n theorem hasDerivAt_pow (n : ℕ) (x : 𝕜) : HasDerivAt (fun x : 𝕜 => x ^ n) ((n : 𝕜) * x ^ (n - 1)) x := by simpa using (hasStrictDerivAt_pow n x).hasDerivAt theorem derivWithin_pow_field (h : UniqueDiffWithinAt 𝕜 s x) (n : ℕ) : derivWithin (fun x => x ^ n) s x = (n : 𝕜) * x ^ (n - 1) := by rw [derivWithin_fun_pow (differentiableWithinAt_id' (s := s)) n, derivWithin_id' _ _ h, mul_one] theorem deriv_pow_field (n : ℕ) : deriv (fun x => x ^ n) x = (n : 𝕜) * x ^ (n - 1) := by simp end NontriviallyNormedField
DeriveEncodable.lean
/- Copyright (c) 2024 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Lean.Meta.Transform import Lean.Meta.Inductive import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util import Mathlib.Logic.Encodable.Basic import Mathlib.Data.Nat.Pairing /-! # `Encodable` deriving handler Adds a deriving handler for the `Encodable` class. The resulting `Encodable` instance should be considered to be opaque. The specific encoding used is an implementation detail. -/ namespace Mathlib.Deriving.Encodable open Lean Parser.Term Elab Deriving Meta /-! ### Theory The idea is that every encodable inductive type can be represented as a tree of natural numbers. Inspiration for this is s-expressions used in Lisp/Scheme. ```lean inductive S : Type where | nat (n : ℕ) | cons (a b : S) ``` We start by constructing a equivalence `S ≃ ℕ` using the `Nat.pair` function. Here is an example of how this module constructs an encoding. Suppose we are given the following type: ```lean inductive T (α : Type) where | a (x : α) (y : Bool) (z : T α) | b ``` The deriving handler constructs the following declarations: ```lean def encodableT_toS {α} [Encodable α] (x : T α) : S := match x with | T.a a a_1 a_2 => S.cons (S.nat 0) (S.cons (S.nat (Encodable.encode a)) (S.cons (S.nat (Encodable.encode a_1)) (S.cons (encodableT_toS a_2) (S.nat 0)))) | T.b => S.cons (S.nat 1) (S.nat 0) private def encodableT_fromS {α} [Encodable α] : S → Option (T α) := fun | S.cons (S.nat 0) (S.cons (S.nat a) (S.cons (S.nat a_1) (S.cons a_2 (S.nat 0)))) => match Encodable.decode a, Encodable.decode a_1, encodableT_fromS a_2 with | some a, some a_1, some a_2 => some <| T.a a a_1 a_2 | _, _, _ => none | S.cons (S.nat 1) (S.nat 0) => some <| T.b | _ => none private theorem encodableT {α} [Encodable α] (x : @T α) : encodableT_fromS (encodableT_toS x) = some x := by cases x <;> (unfold encodableT_toS encodableT_fromS; simp only [Encodable.encodek, encodableT]) instance {α} [Encodable α] : Encodable (@T α) := Encodable.ofLeftInjection encodableT_toS encodableT_fromS encodableT ``` The idea is that each constructor gets encoded as a linked list made of `S.cons` constructors that is tagged with the constructor index. -/ private inductive S : Type where | nat (n : ℕ) | cons (a b : S) private def S.encode : S → ℕ | nat n => Nat.pair 0 n | cons a b => Nat.pair (S.encode a + 1) (S.encode b) private lemma nat_unpair_lt_2 {n : ℕ} (h : (Nat.unpair n).1 ≠ 0) : (Nat.unpair n).2 < n := by obtain ⟨⟨a, b⟩, rfl⟩ := Nat.pairEquiv.surjective n simp only [Nat.pairEquiv_apply, Function.uncurry_apply_pair, Nat.unpair_pair] at * unfold Nat.pair have := Nat.le_mul_self a have := Nat.le_mul_self b split <;> omega private def S.decode (n : ℕ) : S := let p := Nat.unpair n if h : p.1 = 0 then S.nat p.2 else have : p.1 ≤ n := Nat.unpair_left_le n have := Nat.unpair_lt (by omega : 1 ≤ n) have := nat_unpair_lt_2 h S.cons (S.decode (p.1 - 1)) (S.decode p.2) private def S_equiv : S ≃ ℕ where toFun := S.encode invFun := S.decode left_inv s := by induction s with | nat n => unfold S.encode S.decode simp | cons a b iha ihb => unfold S.encode S.decode simp [iha, ihb] right_inv n := by -- The fact it's a right inverse isn't needed for the deriving handler. induction n using Nat.strongRecOn with | _ n ih => unfold S.decode dsimp only split next h => unfold S.encode rw [← h, Nat.pair_unpair] next h => unfold S.encode rw [ih, ih, Nat.sub_add_cancel, Nat.pair_unpair] · rwa [Nat.one_le_iff_ne_zero] · exact nat_unpair_lt_2 h · obtain _ | n' := n · exact False.elim (h rfl) · have := Nat.unpair_lt (by omega : 1 ≤ n' + 1) omega instance : Encodable S := Encodable.ofEquiv ℕ S_equiv /-! ### Implementation -/ /-! Constructing the `toS` encoding functions. -/ private def mkToSMatch (ctx : Deriving.Context) (header : Header) (indVal : InductiveVal) (toSNames : Array Name) : TermElabM Term := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkAlts : TermElabM (Array (TSyntax ``matchAlt)) := do let mut alts := #[] for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName alts := alts.push <| ← forallTelescopeReducing ctorInfo.type fun xs _ => do let mut patterns := #[] let mut ctorArgs := #[] let mut rhsArgs : Array Term := #[] for _ in [:indVal.numIndices] do patterns := patterns.push (← `(_)) for _ in [:ctorInfo.numParams] do ctorArgs := ctorArgs.push (← `(_)) for i in [:ctorInfo.numFields] do let a := mkIdent (← mkFreshUserName `a) ctorArgs := ctorArgs.push a let x := xs[ctorInfo.numParams + i]! let xTy ← inferType x let recName? := ctx.typeInfos.findIdx? (xTy.isAppOf ·.name) |>.map (toSNames[·]!) rhsArgs := rhsArgs.push <| ← if let some recName := recName? then `($(mkIdent recName) $a) else ``(S.nat (Encodable.encode $a)) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*)) let rhs' : Term ← rhsArgs.foldrM (init := ← ``(S.nat 0)) fun arg acc => ``(S.cons $arg $acc) let rhs : Term ← ``(S.cons (S.nat $(quote ctorInfo.cidx)) $rhs') `(matchAltExpr| | $[$patterns:term],* => $rhs) return alts /-- Constructs a function from the inductive type to `S`. -/ private def mkToSFuns (ctx : Deriving.Context) (toSFunNames : Array Name) : TermElabM (TSyntax `command) := do let mut res : Array (TSyntax `command) := #[] for i in [:toSFunNames.size] do let toNatFnName := toSFunNames[i]! let indVal := ctx.typeInfos[i]! let header ← mkHeader ``Encodable 1 indVal let body ← mkToSMatch ctx header indVal toSFunNames res := res.push <| ← `( private def $(mkIdent toNatFnName):ident $header.binders:bracketedBinder* : $(mkCIdent ``S) := $body:term ) `(command| mutual $[$res:command]* end) /-! Constructing the `fromS` functions. -/ private def mkFromSMatch (ctx : Deriving.Context) (indVal : InductiveVal) (fromSNames : Array Name) : TermElabM Term := do let alts ← mkAlts `(fun $alts:matchAlt*) where mkAlts : TermElabM (Array (TSyntax ``matchAlt)) := do let mut alts := #[] for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName alts := alts.push <| ← forallTelescopeReducing ctorInfo.type fun xs _ => do let mut patternArgs : Array Term := #[] let mut discrs : Array (TSyntax ``Lean.Parser.Term.matchDiscr) := #[] let mut ctorArgs : Array Term := #[] let mut patternArgs2 : Array Term := #[] let mut patternArgs3 : Array Term := #[] for _ in [:indVal.numParams] do ctorArgs := ctorArgs.push (← `(_)) for i in [:ctorInfo.numFields] do let a := mkIdent (← mkFreshUserName `a) let x := xs[ctorInfo.numParams + i]! let xTy ← inferType x let recName? := ctx.typeInfos.findIdx? (xTy.isAppOf ·.name) |>.map (fromSNames[·]!) if let some recName := recName? then patternArgs := patternArgs.push a discrs := discrs.push <| ← `(matchDiscr| $(mkIdent recName) $a) else patternArgs := patternArgs.push <| ← ``(S.nat $a) discrs := discrs.push <| ← `(matchDiscr| $(mkCIdent ``Encodable.decode) $a) ctorArgs := ctorArgs.push a patternArgs2 := patternArgs2.push <| ← ``(some $a) patternArgs3 := patternArgs3.push <| ← `(_) let pattern ← patternArgs.foldrM (init := ← ``(S.nat 0)) fun arg acc => ``(S.cons $arg $acc) let pattern ← ``(S.cons (S.nat $(quote ctorInfo.cidx)) $pattern) -- Note: this is where we could try to handle indexed types. -- The idea would be to use DecidableEq to test the computed index against the expected -- index and then rewrite. let res ← ``(some <| @$(mkIdent ctorName):ident $ctorArgs:term*) if discrs.isEmpty then `(matchAltExpr| | $pattern:term => $res) else let rhs : Term ← `( match $[$discrs],* with | $[$patternArgs2],* => $res | $[$patternArgs3],* => none ) `(matchAltExpr| | $pattern:term => $rhs) alts := alts.push <| ← `(matchAltExpr| | _ => none) return alts /-- Constructs a function from `S` to the inductive type. -/ private def mkFromSFuns (ctx : Deriving.Context) (fromSFunNames : Array Name) : TermElabM (TSyntax `command) := do let mut res : Array (TSyntax `command) := #[] for i in [:fromSFunNames.size] do let fromNatFnName := fromSFunNames[i]! let indVal := ctx.typeInfos[i]! let header ← mkHeader ``Encodable 1 indVal let body ← mkFromSMatch ctx indVal fromSFunNames -- Last binder is for the target let binders := header.binders[0:header.binders.size - 1] res := res.push <| ← `( private def $(mkIdent fromNatFnName):ident $binders:bracketedBinder* : $(mkCIdent ``S) → Option $header.targetType := $body:term ) `(command| mutual $[$res:command]* end) /-! Constructing the proofs that the `fromS` functions are left inverses of the `toS` functions. -/ /-- Constructs a proof that the functions created by `mkFromSFuns` are left inverses of the ones created by `mkToSFuns`. -/ private def mkInjThms (ctx : Deriving.Context) (toSFunNames fromSFunNames : Array Name) : TermElabM (TSyntax `command) := do let mut res : Array (TSyntax `command) := #[] for i in [:toSFunNames.size] do let toSFunName := toSFunNames[i]! let fromSFunName := fromSFunNames[i]! let injThmName := ctx.auxFunNames[i]! let indVal := ctx.typeInfos[i]! let header ← mkHeader ``Encodable 1 indVal let enc := mkIdent toSFunName let dec := mkIdent fromSFunName let t := mkIdent header.targetNames[0]! let lemmas : TSyntaxArray ``Parser.Tactic.simpLemma ← ctx.auxFunNames.mapM fun i => `(Parser.Tactic.simpLemma| $(mkIdent i):term) let tactic : Term ← `(by cases $t:ident <;> (unfold $(mkIdent toSFunName):ident $(mkIdent fromSFunName):ident; simp only [Encodable.encodek, $lemmas,*]; try rfl) ) res := res.push <| ← `( private theorem $(mkIdent injThmName):ident $header.binders:bracketedBinder* : $dec ($enc $t) = some $t := $tactic ) `(command| mutual $[$res:command]* end) /-! Assembling the `Encodable` instances. -/ open TSyntax.Compat in /-- Assuming all of the auxiliary definitions exist, create all the `instance` commands for the `ToExpr` instances for the (mutual) inductive type(s). -/ private def mkEncodableInstanceCmds (ctx : Deriving.Context) (typeNames : Array Name) (toSFunNames fromSFunNames : Array Name) : TermElabM (Array Command) := do let mut instances := #[] for i in [:ctx.typeInfos.size] do let indVal := ctx.typeInfos[i]! if typeNames.contains indVal.name then let auxFunName := ctx.auxFunNames[i]! let argNames ← mkInductArgNames indVal let binders ← mkImplicitBinders argNames let binders := binders ++ (← mkInstImplicitBinders ``Encodable indVal argNames) let indType ← mkInductiveApp indVal argNames let type ← `($(mkCIdent ``Encodable) $indType) let encode := mkIdent toSFunNames[i]! let decode := mkIdent fromSFunNames[i]! let kencode := mkIdent auxFunName let instCmd ← `( instance $binders:implicitBinder* : $type := $(mkCIdent ``Encodable.ofLeftInjection) $encode $decode $kencode ) instances := instances.push instCmd return instances private def mkEncodableCmds (indVal : InductiveVal) (declNames : Array Name) : TermElabM (Array Syntax) := do let ctx ← mkContext "encodable" indVal.name let toSFunNames : Array Name ← ctx.auxFunNames.mapM fun name => do let .str n' s := name.eraseMacroScopes | unreachable! mkFreshUserName <| .str n' (s ++ "_toS") let fromSFunNames : Array Name ← ctx.auxFunNames.mapM fun name => do let .str n' s := name.eraseMacroScopes | unreachable! mkFreshUserName <| .str n' (s ++ "_fromS") let cmds := #[← mkToSFuns ctx toSFunNames, ← mkFromSFuns ctx fromSFunNames, ← mkInjThms ctx toSFunNames fromSFunNames] ++ (← mkEncodableInstanceCmds ctx declNames toSFunNames fromSFunNames) trace[Mathlib.Deriving.encodable] "\n{cmds}" return cmds open Command /-- The deriving handler for the `Encodable` class. Handles non-nested non-reflexive inductive types. They can be mutual too — in that case, there is an optimization to re-use all the generated functions and proofs. -/ def mkEncodableInstance (declNames : Array Name) : CommandElabM Bool := do let mut seen : NameSet := {} let mut toVisit : Array InductiveVal := #[] for declName in declNames do if seen.contains declName then continue let indVal ← getConstInfoInduct declName if indVal.isNested || indVal.isReflexive || indVal.numIndices != 0 then return false -- not supported yet seen := seen.append (NameSet.ofList indVal.all) toVisit := toVisit.push indVal for indVal in toVisit do let cmds ← liftTermElabM <| mkEncodableCmds indVal (declNames.filter indVal.all.contains) withEnableInfoTree false do elabCommand <| mkNullNode cmds return true initialize registerDerivingHandler ``Encodable mkEncodableInstance registerTraceClass `Mathlib.Deriving.Encodable end Mathlib.Deriving.Encodable
Basic.lean
/- Copyright (c) 2024 Ali Ramsey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ali Ramsey, Kevin Buzzard -/ import Mathlib.RingTheory.Coalgebra.Basic import Mathlib.RingTheory.TensorProduct.Basic /-! # Bialgebras In this file we define `Bialgebra`s. ## Main definitions * `Bialgebra R A`: the structure of a bialgebra on the `R`-algebra `A`; * `CommSemiring.toBialgebra`: a commutative semiring is a bialgebra over itself. ## Implementation notes Rather than the "obvious" axiom `∀ a b, counit (a * b) = counit a * counit b`, the far more convoluted `mul_compr₂_counit` is used as a structure field; this says that the corresponding two maps `A →ₗ[R] A →ₗ[R] R` are equal; a similar trick is used for comultiplication as well. An alternative constructor `Bialgebra.mk'` is provided with the more easily-readable axioms. The argument for using the more convoluted axioms is that in practice there is evidence that they will be easier to prove (especially when dealing with things like tensor products of bialgebras). This does make the definition more surprising to mathematicians, however mathlib is no stranger to definitions which are surprising to mathematicians -- see for example its definition of a group. Note that this design decision is also compatible with that of `Coalgebra`. The lengthy docstring for these convoluted fields attempts to explain what is going on. The constructor `Bialgebra.ofAlgHom` is dual to the default constructor: For `R` is a commutative semiring and `A` a `R`-algebra, it consumes the counit and comultiplication as algebra homomorphisms that satisfy the coalgebra axioms to define a bialgebra structure on `A`. ## References * <https://en.wikipedia.org/wiki/Bialgebra> ## Tags bialgebra -/ universe u v w open Function open scoped TensorProduct /-- A bialgebra over a commutative (semi)ring `R` is both an algebra and a coalgebra over `R`, such that the counit and comultiplication are algebra morphisms. -/ class Bialgebra (R : Type u) (A : Type v) [CommSemiring R] [Semiring A] extends Algebra R A, Coalgebra R A where -- The counit is an algebra morphism /-- The counit on a bialgebra preserves 1. -/ counit_one : counit 1 = 1 /-- The counit on a bialgebra preserves multiplication. Note that this is written in a rather obscure way: it says that two bilinear maps `A →ₗ[R] A →ₗ[R]` are equal. The two corresponding equal linear maps `A ⊗[R] A →ₗ[R]` are the following: the first factors through `A` and is multiplication on `A` followed by `counit`. The second factors through `R ⊗[R] R`, and is `counit ⊗ counit` followed by multiplication on `R`. See `Bialgebra.mk'` for a constructor for bialgebras which uses the more familiar but mathematically equivalent `counit (a * b) = counit a * counit b`. -/ mul_compr₂_counit : (LinearMap.mul R A).compr₂ counit = (LinearMap.mul R R).compl₁₂ counit counit -- The comultiplication is an algebra morphism /-- The comultiplication on a bialgebra preserves `1`. -/ comul_one : comul 1 = 1 /-- The comultiplication on a bialgebra preserves multiplication. This is written in a rather obscure way: it says that two bilinear maps `A →ₗ[R] A →ₗ[R] (A ⊗[R] A)` are equal. The corresponding equal linear maps `A ⊗[R] A →ₗ[R] A ⊗[R] A` are firstly multiplication followed by `comul`, and secondly `comul ⊗ comul` followed by multiplication on `A ⊗[R] A`. See `Bialgebra.mk'` for a constructor for bialgebras which uses the more familiar but mathematically equivalent `comul (a * b) = comul a * comul b`. -/ mul_compr₂_comul : (LinearMap.mul R A).compr₂ comul = (LinearMap.mul R (A ⊗[R] A)).compl₁₂ comul comul namespace Bialgebra open Coalgebra variable {R : Type u} {A : Type v} variable [CommSemiring R] [Semiring A] [Bialgebra R A] lemma counit_mul (a b : A) : counit (R := R) (a * b) = counit a * counit b := DFunLike.congr_fun (DFunLike.congr_fun mul_compr₂_counit a) b lemma comul_mul (a b : A) : comul (R := R) (a * b) = comul a * comul b := DFunLike.congr_fun (DFunLike.congr_fun mul_compr₂_comul a) b attribute [simp] counit_one comul_one counit_mul comul_mul /-- If `R` is a field (or even a commutative semiring) and `A` is an `R`-algebra with a coalgebra structure, then `Bialgebra.mk'` consumes proofs that the counit and comultiplication preserve the identity and multiplication, and produces a bialgebra structure on `A`. -/ def mk' (R : Type u) (A : Type v) [CommSemiring R] [Semiring A] [Algebra R A] [C : Coalgebra R A] (counit_one : C.counit 1 = 1) (counit_mul : ∀ {a b}, C.counit (a * b) = C.counit a * C.counit b) (comul_one : C.comul 1 = 1) (comul_mul : ∀ {a b}, C.comul (a * b) = C.comul a * C.comul b) : Bialgebra R A where counit_one := counit_one mul_compr₂_counit := by ext; exact counit_mul comul_one := comul_one mul_compr₂_comul := by ext; exact comul_mul variable (R A) /-- `counitAlgHom R A` is the counit of the `R`-bialgebra `A`, as an `R`-algebra map. -/ @[simps!] def counitAlgHom : A →ₐ[R] R := .ofLinearMap counit counit_one counit_mul /-- `comulAlgHom R A` is the comultiplication of the `R`-bialgebra `A`, as an `R`-algebra map. -/ @[simps!] def comulAlgHom : A →ₐ[R] A ⊗[R] A := .ofLinearMap comul comul_one comul_mul variable {R A} @[simp] lemma toLinearMap_counitAlgHom : (counitAlgHom R A).toLinearMap = counit := rfl @[simp] lemma toLinearMap_comulAlgHom : (comulAlgHom R A).toLinearMap = comul := rfl @[simp] lemma counit_algebraMap (r : R) : counit (R := R) (algebraMap R A r) = r := (counitAlgHom R A).commutes r @[simp] lemma comul_algebraMap (r : R) : comul (R := R) (algebraMap R A r) = algebraMap R (A ⊗[R] A) r := (comulAlgHom R A).commutes r @[simp] lemma counit_natCast (n : ℕ) : counit (R := R) (n : A) = n := map_natCast (counitAlgHom R A) _ @[simp] lemma comul_natCast (n : ℕ) : comul (R := R) (n : A) = n := map_natCast (comulAlgHom R A) _ @[simp] lemma counit_pow (a : A) (n : ℕ) : counit (R := R) (a ^ n) = counit a ^ n := map_pow (counitAlgHom R A) a n @[simp] lemma comul_pow (a : A) (n : ℕ) : comul (R := R) (a ^ n) = comul a ^ n := map_pow (comulAlgHom R A) a n end Bialgebra namespace CommSemiring variable (R : Type u) [CommSemiring R] open Bialgebra /-- Every commutative (semi)ring is a bialgebra over itself -/ instance toBialgebra : Bialgebra R R where mul_compr₂_counit := by ext; simp counit_one := rfl mul_compr₂_comul := by ext; simp comul_one := rfl end CommSemiring namespace Bialgebra variable {R A : Type*} [CommSemiring R] [Semiring A] [Algebra R A] /-- If `R` is a commutative semiring and `A` is an `R`-algebra, then `Bialgebra.ofAlgHom` consumes the counit and comultiplication as algebra homomorphisms that satisfy the coalgebra axioms to define a bialgebra structure on `A`. -/ abbrev ofAlgHom (comul : A →ₐ[R] (A ⊗[R] A)) (counit : A →ₐ[R] R) (h_coassoc : (Algebra.TensorProduct.assoc R R A A A).toAlgHom.comp ((Algebra.TensorProduct.map comul (.id R A)).comp comul) = (Algebra.TensorProduct.map (.id R A) comul).comp comul) (h_rTensor : (Algebra.TensorProduct.map counit (.id R A)).comp comul = (Algebra.TensorProduct.lid R A).symm) (h_lTensor : (Algebra.TensorProduct.map (.id R A) counit).comp comul = (Algebra.TensorProduct.rid R R A).symm) : Bialgebra R A := letI : Coalgebra R A := { comul := comul counit := counit coassoc := congr(($h_coassoc).toLinearMap) rTensor_counit_comp_comul := congr(($h_rTensor).toLinearMap) lTensor_counit_comp_comul := congr(($h_lTensor).toLinearMap) } .mk' _ _ (map_one counit) (map_mul counit _ _) (map_one comul) (map_mul comul _ _) end Bialgebra namespace Bialgebra variable {R A : Type*} [CommSemiring R] [Semiring A] [Bialgebra R A] variable (A) in lemma algebraMap_injective : Injective (algebraMap R A) := RightInverse.injective counit_algebraMap lemma counit_surjective : Surjective (Coalgebra.counit : A →ₗ[R] R) := RightInverse.surjective counit_algebraMap include R in variable (R) in /-- A bialgebra over a nontrivial ring is nontrivial. -/ lemma nontrivial [Nontrivial R] : Nontrivial A := (algebraMap_injective (R := R) _).nontrivial end Bialgebra
Completion.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.Topology.Algebra.GroupCompletion import Mathlib.Topology.Algebra.Ring.Real import Mathlib.Topology.MetricSpace.Algebra import Mathlib.Topology.MetricSpace.Isometry import Mathlib.Topology.MetricSpace.Lipschitz import Mathlib.Topology.UniformSpace.Completion /-! # The completion of a metric space Completion of uniform spaces are already defined in `Topology.UniformSpace.Completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ open Set Filter UniformSpace Metric open Filter Topology Uniformity noncomputable section universe u v variable {α : Type u} {β : Type v} [PseudoMetricSpace α] namespace UniformSpace.Completion /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ instance : Dist (Completion α) := ⟨Completion.extension₂ dist⟩ /-- The new distance is uniformly continuous. -/ protected theorem uniformContinuous_dist : UniformContinuous fun p : Completion α × Completion α ↦ dist p.1 p.2 := uniformContinuous_extension₂ dist /-- The new distance is continuous. -/ protected theorem continuous_dist [TopologicalSpace β] {f g : β → Completion α} (hf : Continuous f) (hg : Continuous g) : Continuous fun x ↦ dist (f x) (g x) := Completion.uniformContinuous_dist.continuous.comp (hf.prodMk hg :) /-- The new distance is an extension of the original distance. -/ @[simp] protected theorem dist_eq (x y : α) : dist (x : Completion α) y = dist x y := Completion.extension₂_coe_coe uniformContinuous_dist _ _ /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `Completion α` by continuity. -/ protected theorem dist_self (x : Completion α) : dist x x = 0 := by refine induction_on x ?_ ?_ · refine isClosed_eq ?_ continuous_const exact Completion.continuous_dist continuous_id continuous_id · intro a rw [Completion.dist_eq, dist_self] protected theorem dist_comm (x y : Completion α) : dist x y = dist y x := by refine induction_on₂ x y ?_ ?_ · exact isClosed_eq (Completion.continuous_dist continuous_fst continuous_snd) (Completion.continuous_dist continuous_snd continuous_fst) · intro a b rw [Completion.dist_eq, Completion.dist_eq, dist_comm] protected theorem dist_triangle (x y z : Completion α) : dist x z ≤ dist x y + dist y z := by refine induction_on₃ x y z ?_ ?_ · refine isClosed_le ?_ (Continuous.add ?_ ?_) <;> apply_rules [Completion.continuous_dist, Continuous.fst, Continuous.snd, continuous_id] · intro a b c rw [Completion.dist_eq, Completion.dist_eq, Completion.dist_eq] exact dist_triangle a b c /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected theorem mem_uniformity_dist (s : Set (Completion α × Completion α)) : s ∈ 𝓤 (Completion α) ↔ ∃ ε > 0, ∀ {a b}, dist a b < ε → (a, b) ∈ s := by constructor · /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in `α` is an entourage, so it contains an `ε`-neighborhood of the diagonal by definition of the entourages in metric spaces. Then `t` contains an `ε`-neighborhood of the diagonal in `Completion α`, as closed properties pass to the completion. -/ intro hs rcases mem_uniformity_isClosed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩ have A : { x : α × α | (↑x.1, ↑x.2) ∈ t } ∈ uniformity α := uniformContinuous_def.1 (uniformContinuous_coe α) t ht rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩ refine ⟨ε, εpos, @fun x y hxy ↦ ?_⟩ have : ε ≤ dist x y ∨ (x, y) ∈ t := by refine induction_on₂ x y ?_ ?_ · have : { x : Completion α × Completion α | ε ≤ dist x.fst x.snd ∨ (x.fst, x.snd) ∈ t } = { p : Completion α × Completion α | ε ≤ dist p.1 p.2 } ∪ t := by ext; simp rw [this] apply IsClosed.union _ tclosed exact isClosed_le continuous_const Completion.uniformContinuous_dist.continuous · intro x y rw [Completion.dist_eq] by_cases h : ε ≤ dist x y · exact Or.inl h · have Z := hε (not_le.1 h) simp only [Set.mem_setOf_eq] at Z exact Or.inr Z simp only [not_le.mpr hxy, false_or] at this exact ts this · /- Start from a set `s` containing an ε-neighborhood of the diagonal in `Completion α`. To show that it is an entourage, we use the fact that `dist` is uniformly continuous on `Completion α × Completion α` (this is a general property of the extension of uniformly continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ is an entourage in `Completion α × Completion α`. Massaging this property, it follows that the ε-neighborhood of the diagonal is an entourage in `Completion α`, and therefore this is also the case of `s`. -/ rintro ⟨ε, εpos, hε⟩ let r : Set (ℝ × ℝ) := { p | dist p.1 p.2 < ε } have : r ∈ uniformity ℝ := Metric.dist_mem_uniformity εpos have T := uniformContinuous_def.1 (@Completion.uniformContinuous_dist α _) r this simp only [uniformity_prod_eq_prod, mem_prod_iff, Filter.mem_map] at T rcases T with ⟨t1, ht1, t2, ht2, ht⟩ refine mem_of_superset ht1 ?_ have A : ∀ a b : Completion α, (a, b) ∈ t1 → dist a b < ε := by intro a b hab have : ((a, b), (a, a)) ∈ t1 ×ˢ t2 := ⟨hab, refl_mem_uniformity ht2⟩ have I := ht this simp? [r, Completion.dist_self, Real.dist_eq, Completion.dist_comm] at I says simp only [Real.dist_eq, mem_setOf_eq, preimage_setOf_eq, Completion.dist_self, Completion.dist_comm, zero_sub, abs_neg, r] at I exact lt_of_le_of_lt (le_abs_self _) I grind /-- Reformulate `Completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected theorem uniformity_dist' : 𝓤 (Completion α) = ⨅ ε : { ε : ℝ // 0 < ε }, 𝓟 { p | dist p.1 p.2 < ε.val } := by ext s; rw [mem_iInf_of_directed] · simp [Completion.mem_uniformity_dist, subset_def] · rintro ⟨r, hr⟩ ⟨p, hp⟩ use ⟨min r p, lt_min hr hp⟩ simp +contextual protected theorem uniformity_dist : 𝓤 (Completion α) = ⨅ ε > 0, 𝓟 { p | dist p.1 p.2 < ε } := by simpa [iInf_subtype] using @Completion.uniformity_dist' α _ /-- Metric space structure on the completion of a pseudo_metric space. -/ instance instMetricSpace : MetricSpace (Completion α) := @MetricSpace.ofT0PseudoMetricSpace _ { dist_self := Completion.dist_self dist_comm := Completion.dist_comm dist_triangle := Completion.dist_triangle dist := dist toUniformSpace := inferInstance uniformity_dist := Completion.uniformity_dist } _ /-- The embedding of a metric space in its completion is an isometry. -/ theorem coe_isometry : Isometry ((↑) : α → Completion α) := Isometry.of_dist_eq Completion.dist_eq @[simp] protected theorem edist_eq (x y : α) : edist (x : Completion α) y = edist x y := coe_isometry x y instance {M} [Zero M] [Zero α] [SMul M α] [PseudoMetricSpace M] [IsBoundedSMul M α] : IsBoundedSMul M (Completion α) where dist_smul_pair' c x₁ x₂ := by induction x₁, x₂ using induction_on₂ with | hp => exact isClosed_le ((continuous_fst.const_smul _).dist (continuous_snd.const_smul _)) (continuous_const.mul (continuous_fst.dist continuous_snd)) | ih x₁ x₂ => rw [← coe_smul, ← coe_smul, Completion.dist_eq, Completion.dist_eq] exact dist_smul_pair c x₁ x₂ dist_pair_smul' c₁ c₂ x := by induction x using induction_on with | hp => exact isClosed_le ((continuous_const_smul _).dist (continuous_const_smul _)) (continuous_const.mul (continuous_id.dist continuous_const)) | ih x => rw [← coe_smul, ← coe_smul, Completion.dist_eq, ← coe_zero, Completion.dist_eq] exact dist_pair_smul c₁ c₂ x end UniformSpace.Completion open UniformSpace Completion NNReal theorem LipschitzWith.completion_extension [MetricSpace β] [CompleteSpace β] {f : α → β} {K : ℝ≥0} (h : LipschitzWith K f) : LipschitzWith K (Completion.extension f) := LipschitzWith.of_dist_le_mul fun x y => induction_on₂ x y (isClosed_le (by fun_prop) (by fun_prop)) <| by simpa only [extension_coe h.uniformContinuous, Completion.dist_eq] using h.dist_le_mul theorem LipschitzWith.completion_map [PseudoMetricSpace β] {f : α → β} {K : ℝ≥0} (h : LipschitzWith K f) : LipschitzWith K (Completion.map f) := one_mul K ▸ (coe_isometry.lipschitz.comp h).completion_extension theorem Isometry.completion_extension [MetricSpace β] [CompleteSpace β] {f : α → β} (h : Isometry f) : Isometry (Completion.extension f) := Isometry.of_dist_eq fun x y => induction_on₂ x y (isClosed_eq (by fun_prop) (by fun_prop)) fun _ _ ↦ by simp only [extension_coe h.uniformContinuous, Completion.dist_eq, h.dist_eq] theorem Isometry.completion_map [PseudoMetricSpace β] {f : α → β} (h : Isometry f) : Isometry (Completion.map f) := (coe_isometry.comp h).completion_extension
Set.lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Logic.Equiv.Set import Mathlib.Order.Hom.Basic import Mathlib.Order.Interval.Set.Defs import Mathlib.Order.WellFounded import Mathlib.Tactic.MinImports /-! # Order homomorphisms and sets -/ open OrderDual Set variable {α β : Type*} namespace Set /-- Sets on sum types are order-equivalent to pairs of sets on each summand. -/ def sumEquiv : Set (α ⊕ β) ≃o Set α × Set β where toFun s := (Sum.inl ⁻¹' s, Sum.inr ⁻¹' s) invFun s := Sum.inl '' s.1 ∪ Sum.inr '' s.2 left_inv s := image_preimage_inl_union_image_preimage_inr s right_inv s := by simp [preimage_image_eq _ Sum.inl_injective, preimage_image_eq _ Sum.inr_injective] map_rel_iff' := by simp [subset_def] end Set namespace OrderIso section LE variable [LE α] [LE β] theorem range_eq (e : α ≃o β) : Set.range e = Set.univ := e.surjective.range_eq @[simp] theorem symm_image_image (e : α ≃o β) (s : Set α) : e.symm '' (e '' s) = s := e.toEquiv.symm_image_image s @[simp] theorem image_symm_image (e : α ≃o β) (s : Set β) : e '' (e.symm '' s) = s := e.toEquiv.image_symm_image s theorem image_eq_preimage (e : α ≃o β) (s : Set α) : e '' s = e.symm ⁻¹' s := e.toEquiv.image_eq_preimage s @[simp] theorem preimage_symm_preimage (e : α ≃o β) (s : Set α) : e ⁻¹' (e.symm ⁻¹' s) = s := e.toEquiv.preimage_symm_preimage s @[simp] theorem symm_preimage_preimage (e : α ≃o β) (s : Set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.toEquiv.symm_preimage_preimage s @[simp] theorem image_preimage (e : α ≃o β) (s : Set β) : e '' (e ⁻¹' s) = s := e.toEquiv.image_preimage s @[simp] theorem preimage_image (e : α ≃o β) (s : Set α) : e ⁻¹' (e '' s) = s := e.toEquiv.preimage_image s end LE open Set variable [Preorder α] /-- Order isomorphism between two equal sets. -/ @[simps! apply symm_apply] def setCongr (s t : Set α) (h : s = t) : s ≃o t where toEquiv := Equiv.setCongr h map_rel_iff' := Iff.rfl /-- Order isomorphism between `univ : Set α` and `α`. -/ def Set.univ : (Set.univ : Set α) ≃o α where toEquiv := Equiv.Set.univ α map_rel_iff' := Iff.rfl end OrderIso /-- We can regard an order embedding as an order isomorphism to its range. -/ @[simps! apply] noncomputable def OrderEmbedding.orderIso [LE α] [LE β] {f : α ↪o β} : α ≃o Set.range f := { Equiv.ofInjective _ f.injective with map_rel_iff' := f.map_rel_iff } /-- If a function `f` is strictly monotone on a set `s`, then it defines an order isomorphism between `s` and its image. -/ protected noncomputable def StrictMonoOn.orderIso {α β} [LinearOrder α] [Preorder β] (f : α → β) (s : Set α) (hf : StrictMonoOn f s) : s ≃o f '' s where toEquiv := hf.injOn.bijOn_image.equiv _ map_rel_iff' := hf.le_iff_le (Subtype.property _) (Subtype.property _) namespace StrictMono variable [LinearOrder α] [Preorder β] variable (f : α → β) (h_mono : StrictMono f) (h_surj : Function.Surjective f) /-- A strictly monotone function from a linear order is an order isomorphism between its domain and its range. -/ @[simps! apply] protected noncomputable def orderIso : α ≃o Set.range f where toEquiv := Equiv.ofInjective f h_mono.injective map_rel_iff' := h_mono.le_iff_le /-- A strictly monotone surjective function from a linear order is an order isomorphism. -/ noncomputable def orderIsoOfSurjective : α ≃o β := (h_mono.orderIso f).trans <| (OrderIso.setCongr _ _ h_surj.range_eq).trans OrderIso.Set.univ @[simp] theorem coe_orderIsoOfSurjective : (orderIsoOfSurjective f h_mono h_surj : α → β) = f := rfl @[simp] theorem orderIsoOfSurjective_symm_apply_self (a : α) : (orderIsoOfSurjective f h_mono h_surj).symm (f a) = a := (orderIsoOfSurjective f h_mono h_surj).symm_apply_apply _ theorem orderIsoOfSurjective_self_symm_apply (b : β) : f ((orderIsoOfSurjective f h_mono h_surj).symm b) = b := (orderIsoOfSurjective f h_mono h_surj).apply_symm_apply _ end StrictMono /-- Two order embeddings on a well-order are equal provided that their ranges are equal. -/ lemma OrderEmbedding.range_inj [LinearOrder α] [WellFoundedLT α] [Preorder β] {f g : α ↪o β} : Set.range f = Set.range g ↔ f = g := by rw [f.strictMono.range_inj g.strictMono, DFunLike.coe_fn_eq] namespace OrderIso -- These results are also true whenever β is well-founded instead of α. -- You can use `RelEmbedding.isWellFounded` to transfer the instance over. instance subsingleton_of_wellFoundedLT [LinearOrder α] [WellFoundedLT α] [Preorder β] : Subsingleton (α ≃o β) := by refine ⟨fun f g ↦ ?_⟩ rw [OrderIso.ext_iff, ← coe_toOrderEmbedding, ← coe_toOrderEmbedding, DFunLike.coe_fn_eq, ← OrderEmbedding.range_inj, coe_toOrderEmbedding, coe_toOrderEmbedding, range_eq, range_eq] instance subsingleton_of_wellFoundedLT' [LinearOrder β] [WellFoundedLT β] [Preorder α] : Subsingleton (α ≃o β) := by refine ⟨fun f g ↦ ?_⟩ change f.symm.symm = g.symm.symm rw [Subsingleton.elim f.symm] instance unique_of_wellFoundedLT [LinearOrder α] [WellFoundedLT α] : Unique (α ≃o α) := Unique.mk' _ instance subsingleton_of_wellFoundedGT [LinearOrder α] [WellFoundedGT α] [Preorder β] : Subsingleton (α ≃o β) := by refine ⟨fun f g ↦ ?_⟩ change f.dual.dual = g.dual.dual rw [Subsingleton.elim f.dual] instance subsingleton_of_wellFoundedGT' [LinearOrder β] [WellFoundedGT β] [Preorder α] : Subsingleton (α ≃o β) := by refine ⟨fun f g ↦ ?_⟩ change f.dual.dual = g.dual.dual rw [Subsingleton.elim f.dual] instance unique_of_wellFoundedGT [LinearOrder α] [WellFoundedGT α] : Unique (α ≃o α) := Unique.mk' _ /-- An order isomorphism between lattices induces an order isomorphism between corresponding interval sublattices. -/ protected def Iic [Lattice α] [Lattice β] (e : α ≃o β) (x : α) : Iic x ≃o Iic (e x) where toFun y := ⟨e y, (map_le_map_iff _).mpr y.property⟩ invFun y := ⟨e.symm y, e.symm_apply_le.mpr y.property⟩ left_inv y := by simp right_inv y := by simp map_rel_iff' := by simp /-- An order isomorphism between lattices induces an order isomorphism between corresponding interval sublattices. -/ protected def Ici [Lattice α] [Lattice β] (e : α ≃o β) (x : α) : Ici x ≃o Ici (e x) where toFun y := ⟨e y, (map_le_map_iff _).mpr y.property⟩ invFun y := ⟨e.symm y, e.le_symm_apply.mpr y.property⟩ left_inv y := by simp right_inv y := by simp map_rel_iff' := by simp /-- An order isomorphism between lattices induces an order isomorphism between corresponding interval sublattices. -/ protected def Icc [Lattice α] [Lattice β] (e : α ≃o β) (x y : α) : Icc x y ≃o Icc (e x) (e y) where toFun z := ⟨e z, by simp only [mem_Icc, map_le_map_iff]; exact z.property⟩ invFun z := ⟨e.symm z, by simp only [mem_Icc, e.le_symm_apply, e.symm_apply_le]; exact z.property⟩ left_inv y := by simp right_inv y := by simp map_rel_iff' := by simp end OrderIso section BooleanAlgebra variable (α) [BooleanAlgebra α] /-- Taking complements as an order isomorphism to the order dual. -/ @[simps!] def OrderIso.compl : α ≃o αᵒᵈ where toFun := OrderDual.toDual ∘ HasCompl.compl invFun := HasCompl.compl ∘ OrderDual.ofDual left_inv := compl_compl right_inv := compl_compl (α := αᵒᵈ) map_rel_iff' := compl_le_compl_iff_le theorem compl_strictAnti : StrictAnti (compl : α → α) := (OrderIso.compl α).strictMono theorem compl_antitone : Antitone (compl : α → α) := (OrderIso.compl α).monotone end BooleanAlgebra
Antidiagonal.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.Data.Finset.NatAntidiagonal import Mathlib.Data.Finsupp.Multiset import Mathlib.Data.Multiset.Antidiagonal /-! # The `Finsupp` counterpart of `Multiset.antidiagonal`. The antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ namespace Finsupp open Finset universe u variable {α : Type u} [DecidableEq α] /-- The `Finsupp` counterpart of `Multiset.antidiagonal`: the antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/ def antidiagonal' (f : α →₀ ℕ) : (α →₀ ℕ) × (α →₀ ℕ) →₀ ℕ := Multiset.toFinsupp ((Finsupp.toMultiset f).antidiagonal.map (Prod.map Multiset.toFinsupp Multiset.toFinsupp)) /-- The antidiagonal of `s : α →₀ ℕ` is the finset of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ instance instHasAntidiagonal : HasAntidiagonal (α →₀ ℕ) where antidiagonal f := f.antidiagonal'.support mem_antidiagonal {f} {p} := by rcases p with ⟨p₁, p₂⟩ simp [antidiagonal', ← and_assoc, Multiset.toFinsupp_eq_iff, ← Multiset.toFinsupp_eq_iff (f := f)] @[simp] theorem antidiagonal_zero : antidiagonal (0 : α →₀ ℕ) = singleton (0, 0) := rfl @[to_additive] theorem prod_antidiagonal_swap {M : Type*} [CommMonoid M] (n : α →₀ ℕ) (f : (α →₀ ℕ) → (α →₀ ℕ) → M) : ∏ p ∈ antidiagonal n, f p.1 p.2 = ∏ p ∈ antidiagonal n, f p.2 p.1 := prod_equiv (Equiv.prodComm _ _) (by simp [add_comm]) (by simp) @[simp] theorem antidiagonal_single (a : α) (n : ℕ) : antidiagonal (single a n) = (antidiagonal n).map (Function.Embedding.prodMap ⟨_, single_injective a⟩ ⟨_, single_injective a⟩) := by ext ⟨x, y⟩ simp only [mem_antidiagonal, mem_map, mem_antidiagonal, Function.Embedding.coe_prodMap, Function.Embedding.coeFn_mk, Prod.map_apply, Prod.mk.injEq, Prod.exists] constructor · intro h refine ⟨x a, y a, DFunLike.congr_fun h a |>.trans single_eq_same, ?_⟩ simp_rw [DFunLike.ext_iff, ← forall_and] intro i replace h := DFunLike.congr_fun h i simp_rw [single_apply, Finsupp.add_apply] at h ⊢ obtain rfl | hai := Decidable.eq_or_ne a i · exact ⟨if_pos rfl, if_pos rfl⟩ · simp_rw [if_neg hai, add_eq_zero] at h ⊢ exact h.imp Eq.symm Eq.symm · rintro ⟨a, b, rfl, rfl, rfl⟩ exact (single_add _ _ _).symm end Finsupp
BigOperators.lean
/- Copyright (c) 2024 Joachim Breitner, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joachim Breitner, Yaël Dillies -/ import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Data.ENat.Lattice /-! # Sum of suprema in `ENat` -/ assert_not_exists Field namespace ENat lemma sum_iSup {α ι : Type*} {s : Finset α} {f : α → ι → ℕ∞} (hf : ∀ i j, ∃ k, ∀ a, f a i ≤ f a k ∧ f a j ≤ f a k) : ∑ a ∈ s, ⨆ i, f a i = ⨆ i, ∑ a ∈ s, f a i := by induction' s using Finset.cons_induction with a s ha ihs · simp simp_rw [Finset.sum_cons, ihs] refine iSup_add_iSup fun i j ↦ (hf i j).imp fun k hk ↦ ?_ gcongr exacts [(hk a).1, (hk _).2] lemma sum_iSup_of_monotone {α ι : Type*} [Preorder ι] [IsDirected ι (· ≤ ·)] {s : Finset α} {f : α → ι → ℕ∞} (hf : ∀ a, Monotone (f a)) : (∑ a ∈ s, iSup (f a)) = ⨆ n, ∑ a ∈ s, f a n := sum_iSup fun i j ↦ (exists_ge_ge i j).imp fun _k ⟨hi, hj⟩ a ↦ ⟨hf a hi, hf a hj⟩ end ENat
Take.lean
/- Copyright (c) 2024 Quang Dao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Quang Dao -/ import Mathlib.Data.Fin.Tuple.Basic /-! # Take operations on tuples We define the `take` operation on `n`-tuples, which restricts a tuple to its first `m` elements. * `Fin.take`: Given `h : m ≤ n`, `Fin.take m h v` for a `n`-tuple `v = (v 0, ..., v (n - 1))` is the `m`-tuple `(v 0, ..., v (m - 1))`. -/ namespace Fin open Function variable {n : ℕ} {α : Fin n → Sort*} section Take /-- Take the first `m` elements of an `n`-tuple where `m ≤ n`, returning an `m`-tuple. -/ def take (m : ℕ) (h : m ≤ n) (v : (i : Fin n) → α i) : (i : Fin m) → α (castLE h i) := fun i ↦ v (castLE h i) @[simp] theorem take_apply (m : ℕ) (h : m ≤ n) (v : (i : Fin n) → α i) (i : Fin m) : (take m h v) i = v (castLE h i) := rfl @[simp] theorem take_zero (v : (i : Fin n) → α i) : take 0 n.zero_le v = fun i ↦ elim0 i := by ext i; exact elim0 i @[simp] theorem take_one {α : Fin (n + 1) → Sort*} (v : (i : Fin (n + 1)) → α i) : take 1 (Nat.le_add_left 1 n) v = (fun i => v (castLE (Nat.le_add_left 1 n) i)) := by ext i simp only [take] @[simp] theorem take_eq_init {α : Fin (n + 1) → Sort*} (v : (i : Fin (n + 1)) → α i) : take n n.le_succ v = init v := by ext i simp only [Nat.succ_eq_add_one, take, init] congr @[simp] theorem take_eq_self (v : (i : Fin n) → α i) : take n (le_refl n) v = v := by ext i simp [take] @[simp] theorem take_take {m n' : ℕ} (h : m ≤ n') (h' : n' ≤ n) (v : (i : Fin n) → α i) : take m h (take n' h' v) = take m (Nat.le_trans h h') v := by ext i simp only [take] congr @[simp] theorem take_init {α : Fin (n + 1) → Sort*} (m : ℕ) (h : m ≤ n) (v : (i : Fin (n + 1)) → α i) : take m h (init v) = take m (Nat.le_succ_of_le h) v := by ext i simp only [take, init] congr theorem take_repeat {α : Type*} {n' : ℕ} (m : ℕ) (h : m ≤ n) (a : Fin n' → α) : take (m * n') (Nat.mul_le_mul_right n' h) (Fin.repeat n a) = Fin.repeat m a := by ext i simp only [take, repeat_apply, modNat, coe_castLE] /-- Taking `m + 1` elements is equal to taking `m` elements and adding the `(m + 1)`th one. -/ theorem take_succ_eq_snoc (m : ℕ) (h : m < n) (v : (i : Fin n) → α i) : take m.succ h v = snoc (take m h.le v) (v ⟨m, h⟩) := by ext i induction m with | zero => have h' : i = 0 := by ext; simp subst h' simp [take, snoc, castLE] | succ m _ => induction i using reverseInduction with | last => simp [take, snoc]; congr | cast i _ => simp /-- `take` commutes with `update` for indices in the range of `take`. -/ @[simp] theorem take_update_of_lt (m : ℕ) (h : m ≤ n) (v : (i : Fin n) → α i) (i : Fin m) (x : α (castLE h i)) : take m h (update v (castLE h i) x) = update (take m h v) i x := by ext j by_cases h' : j = i · rw [h'] simp only [take, update_self] · have : castLE h j ≠ castLE h i := by simp [h'] simp only [take, update_of_ne h', update_of_ne this] /-- `take` is the same after `update` for indices outside the range of `take`. -/ @[simp] theorem take_update_of_ge (m : ℕ) (h : m ≤ n) (v : (i : Fin n) → α i) (i : Fin n) (hi : i ≥ m) (x : α i) : take m h (update v i x) = take m h v := by ext j have : castLE h j ≠ i := by refine ne_of_val_ne ?_ simp only [coe_castLE] exact Nat.ne_of_lt (lt_of_lt_of_le j.isLt hi) simp only [take, update_of_ne this] /-- Taking the first `m ≤ n` elements of an `addCases u v`, where `u` is a `n`-tuple, is the same as taking the first `m` elements of `u`. -/ theorem take_addCases_left {n' : ℕ} {motive : Fin (n + n') → Sort*} (m : ℕ) (h : m ≤ n) (u : (i : Fin n) → motive (castAdd n' i)) (v : (i : Fin n') → motive (natAdd n i)) : take m (Nat.le_add_right_of_le h) (addCases u v) = take m h u := by ext i have : i < n := Nat.lt_of_lt_of_le i.isLt h simp only [take, addCases, this, coe_castLE, ↓reduceDIte] congr /-- Version of `take_addCases_left` that specializes `addCases` to `append`. -/ theorem take_append_left {n' : ℕ} {α : Sort*} (m : ℕ) (h : m ≤ n) (u : (i : Fin n) → α) (v : (i : Fin n') → α) : take m (Nat.le_add_right_of_le h) (append u v) = take m h u := take_addCases_left m h _ _ /-- Taking the first `n + m` elements of an `addCases u v`, where `v` is a `n'`-tuple and `m ≤ n'`, is the same as appending `u` with the first `m` elements of `v`. -/ theorem take_addCases_right {n' : ℕ} {motive : Fin (n + n') → Sort*} (m : ℕ) (h : m ≤ n') (u : (i : Fin n) → motive (castAdd n' i)) (v : (i : Fin n') → motive (natAdd n i)) : take (n + m) (Nat.add_le_add_left h n) (addCases u v) = addCases u (take m h v) := by ext i simp only [take, addCases, coe_castLE] by_cases h' : i < n · simp only [h', ↓reduceDIte] congr · simp only [h', ↓reduceDIte, subNat, castLE, Fin.cast, eqRec_eq_cast] /-- Version of `take_addCases_right` that specializes `addCases` to `append`. -/ theorem take_append_right {n' : ℕ} {α : Sort*} (m : ℕ) (h : m ≤ n') (u : (i : Fin n) → α) (v : (i : Fin n') → α) : take (n + m) (Nat.add_le_add_left h n) (append u v) = append u (take m h v) := take_addCases_right m h _ _ /-- `Fin.take` intertwines with `List.take` via `List.ofFn`. -/ theorem ofFn_take_eq_take_ofFn {α : Type*} {m : ℕ} (h : m ≤ n) (v : Fin n → α) : List.ofFn (take m h v) = (List.ofFn v).take m := List.ext_get (by simp [h]) (fun n h1 h2 => by simp) /-- Alternative version of `take_eq_take_list_ofFn` with `l : List α` instead of `v : Fin n → α`. -/ theorem ofFn_take_get {α : Type*} {m : ℕ} (l : List α) (h : m ≤ l.length) : List.ofFn (take m h l.get) = l.take m := List.ext_get (by simp [h]) (fun n h1 h2 => by simp) /-- `Fin.take` intertwines with `List.take` via `List.get`. -/ theorem get_take_eq_take_get_comp_cast {α : Type*} {m : ℕ} (l : List α) (h : m ≤ l.length) : (l.take m).get = take m h l.get ∘ Fin.cast (List.length_take_of_le h) := by ext i simp only [List.get_eq_getElem, List.getElem_take, comp_apply, take_apply, coe_castLE, coe_cast] /-- Alternative version of `take_eq_take_list_get` with `v : Fin n → α` instead of `l : List α`. -/ theorem get_take_ofFn_eq_take_comp_cast {α : Type*} {m : ℕ} (v : Fin n → α) (h : m ≤ n) : ((List.ofFn v).take m).get = take m h v ∘ Fin.cast (by simp [h]) := by ext i simp [castLE] end Take end Fin
rat.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import prime fintype finfun bigop order tuple ssralg. From mathcomp Require Import countalg div ssrnum ssrint archimedean poly zmodp. From mathcomp Require Import polydiv intdiv matrix mxalgebra vector. (******************************************************************************) (* This file defines a datatype for rational numbers and equips it with a *) (* structure of archimedean, real field, with int and nat declared as closed *) (* subrings. *) (* rat == the type of rational number, with single constructor Rat *) (* <number> == <number> as a rat with <number> a decimal constant. *) (* This notation is in rat_scope (delimited with %Q). *) (* n%:Q == explicit cast from int to rat, ie. the specialization to *) (* rationals of the generic ring morphism n%:~R *) (* numq r == numerator of (r : rat) *) (* denq r == denominator of (r : rat) *) (* ratr r == generic embedding of (r : rat) into an arbitrary unit ring.*) (* [rat x // y] == smart constructor for rationals, definitionally equal *) (* to x / y for concrete values, intended for printing only *) (* of normal forms. The parsable notation is for debugging. *) (* inIntSpan X v <-> v is an integral linear combination of elements of *) (* X : seq V, where V is a zmodType. We prove that this is a *) (* decidable property for Q-vector spaces. *) (******************************************************************************) Import Order.TTheory GRing.Theory Num.Theory. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "[ 'rat' x // y ]" (format "[ 'rat' x // y ]"). Reserved Notation "n %:Q" (left associativity, format "n %:Q"). Local Open Scope ring_scope. Local Notation sgr := Num.sg. Record rat : Set := Rat { valq : (int * int); _ : (0 < valq.2) && coprime `|valq.1| `|valq.2| }. Bind Scope ring_scope with rat. Delimit Scope rat_scope with Q. Definition ratz (n : int) := @Rat (n, 1) (coprimen1 _). (* Coercion ratz (n : int) := @Rat (n, 1) (coprimen1 _). *) Definition rat_isSub := Eval hnf in [isSub for valq]. HB.instance Definition _ := rat_isSub. #[hnf] HB.instance Definition _ := [Equality of rat by <:]. HB.instance Definition _ := [Countable of rat by <:]. Definition numq x := (valq x).1. Definition denq x := (valq x).2. Arguments numq : simpl never. Arguments denq : simpl never. Lemma denq_gt0 x : 0 < denq x. Proof. by rewrite /denq; case: x=> [[a b] /= /andP []]. Qed. #[global] Hint Resolve denq_gt0 : core. Definition denq_ge0 x := ltW (denq_gt0 x). Lemma denq_lt0 x : (denq x < 0) = false. Proof. by rewrite lt_gtF. Qed. Lemma denq_neq0 x : denq x != 0. Proof. by rewrite /denq gt_eqF ?denq_gt0. Qed. #[global] Hint Resolve denq_neq0 : core. Lemma denq_eq0 x : (denq x == 0) = false. Proof. exact: negPf (denq_neq0 _). Qed. Lemma coprime_num_den x : coprime `|numq x| `|denq x|. Proof. by rewrite /numq /denq; case: x=> [[a b] /= /andP []]. Qed. Fact RatK x P : @Rat (numq x, denq x) P = x. Proof. by move: x P => [[a b] P'] P; apply: val_inj. Qed. Definition fracq_subdef x := if x.2 != 0 then let g := gcdn `|x.1| `|x.2| in ((-1) ^ ((x.2 < 0) (+) (x.1 < 0)) * (`|x.1| %/ g)%:Z, (`|x.2| %/ g)%:Z) else (0, 1). Arguments fracq_subdef /. Definition fracq_opt_subdef (x : int * int) := if (0 < x.2) && coprime `|x.1| `|x.2| then x else fracq_subdef x. Lemma fracq_opt_subdefE x : fracq_opt_subdef x = fracq_subdef x. Proof. rewrite /fracq_opt_subdef; case: ifP => //; case: x => n d /= /andP[d_gt0 cnd]. rewrite /fracq_subdef gt_eqF//= lt_gtF//= (eqP cnd) !divn1 abszEsg gtz0_abs//. rewrite mulrA sgz_def mulrnAr -signr_addb addbb expr0. by have [->|] := eqVneq n 0; rewrite (mulr0, mul1r). Qed. Fact fracq_subproof x (y := fracq_opt_subdef x) : (0 < y.2) && (coprime `|y.1| `|y.2|). Proof. rewrite {}/y fracq_opt_subdefE /=; have [] //= := eqVneq x.2 0. case: x => [/= n d]; rewrite -absz_gt0 => dN0. have ggt0 : (0 < gcdn `|n| `|d|)%N by rewrite gcdn_gt0 dN0 orbT. rewrite ltz_nat divn_gt0// dvdn_leq ?dvdn_gcdr//=. rewrite abszM abszX abszN1 exp1n mul1n absz_nat. rewrite /coprime -(@eqn_pmul2r (gcdn `|n| `|d|))// mul1n. by rewrite muln_gcdl !divnK ?(dvdn_gcdl, dvdn_gcdr). Qed. Lemma fracq_opt_subdef_id x : fracq_opt_subdef (fracq_opt_subdef x) = fracq_subdef x. Proof. rewrite [fracq_opt_subdef (_ x)]/fracq_opt_subdef. by rewrite fracq_subproof fracq_opt_subdefE. Qed. (* We use a match expression in order to "lock" the definition of fracq. *) (* Indeed, the kernel will try to reduce a fracq only when applied to *) (* a term which has "enough" constructors: i.e. it reduces to a pair of *) (* a Posz or Negz on the first component, and a Posz of 0 or S, or a Negz *) (* on the second component. See issue #698. *) (* Additionally, we use fracq_opt_subdef to precompute the normal form *) (* before we use fracq_subproof in order to make sure the proof will be *) (* independent from the input of fracq. This ensure reflexivity of any *) (* computation involving rationals as long as all operators use fracq. *) (* As a consequence val (fracq x) = fracq_opt_subdef (fracq_opt_subdef x)) *) Definition fracq '((n', d')) : rat := match d', n' with | Posz 0 as d, _ as n => Rat (fracq_subproof (1, 0)) | _ as d, Posz _ as n | _ as d, _ as n => Rat (fracq_subproof (fracq_opt_subdef (n, d))) end. Arguments fracq : simpl never. (* Define a Number Notation for rat in rat_scope *) (* Since rat values obtained from fracq contain fracq_subdef, which is not *) (* an inductive constructor, we need to go through an intermediate *) (* inductive type. *) Variant Irat_prf := Ifracq_subproof : (int * int) -> Irat_prf. Variant Irat := IRat : (int * int) -> Irat_prf -> Irat. Definition parse (x : Number.number) : option Irat := let parse_pos i f := let nf := Decimal.nb_digits f in let d := (10 ^ nf)%nat in let n := (Nat.of_uint i * d + Nat.of_uint f)%nat in valq (fracq (Posz n, Posz d)) in let parse i f := match i with | Decimal.Pos i => parse_pos i f | Decimal.Neg i => let (n, d) := parse_pos i f in ((- n)%R, d) end in match x with | Number.Decimal (Decimal.Decimal i f) => let nd := parse i f in Some (IRat nd (Ifracq_subproof nd)) | Number.Decimal (Decimal.DecimalExp _ _ _) => None | Number.Hexadecimal _ => None end. Definition print (r : Irat) : option Number.number := let print_pos n d := if d == 1%nat then Some (Nat.to_uint n, Decimal.Nil) else let d2d5 := match prime_decomp d with | [:: (2, d2); (5, d5)] => Some (d2, d5) | [:: (2, d2)] => Some (d2, O) | [:: (5, d5)] => Some (O, d5) | _ => None end in match d2d5 with | Some (d2, d5) => let f := (2 ^ (d5 - d2) * 5 ^ (d2 - d5))%nat in let (i, f) := edivn (n * f) (d * f) in Some (Nat.to_uint i, Nat.to_uint f) | None => None end in let print_IRat nd := match nd with | (Posz n, Posz d) => match print_pos n d with | Some (i, f) => Some (Decimal.Pos i, f) | None => None end | (Negz n, Posz d) => match print_pos n.+1 d with | Some (i, f) => Some (Decimal.Neg i, f) | None => None end | (_, Negz _) => None end in match r with | IRat nd _ => match print_IRat nd with | Some (i, f) => Some (Number.Decimal (Decimal.Decimal i f)) | None => None end end. Number Notation rat parse print (via Irat mapping [Rat => IRat, fracq_subproof => Ifracq_subproof]) : rat_scope. (* Now, the following should parse as rat (and print unchanged) *) (* Check 12%Q. *) (* Check 3.14%Q. *) (* Check (-3.14)%Q. *) (* Check 0.5%Q. *) (* Check 0.2%Q. *) Lemma val_fracq x : val (fracq x) = fracq_subdef x. Proof. by case: x => [[n|n] [[|[|d]]|d]]//=; rewrite !fracq_opt_subdef_id. Qed. Lemma num_fracq x : numq (fracq x) = if x.2 != 0 then (-1) ^ ((x.2 < 0) (+) (x.1 < 0)) * (`|x.1| %/ gcdn `|x.1| `|x.2|)%:Z else 0. Proof. by rewrite /numq val_fracq/=; case: ifP. Qed. Lemma den_fracq x : denq (fracq x) = if x.2 != 0 then (`|x.2| %/ gcdn `|x.1| `|x.2|)%:Z else 1. Proof. by rewrite /denq val_fracq/=; case: ifP. Qed. Fact ratz_frac n : ratz n = fracq (n, 1). Proof. by apply: val_inj; rewrite val_fracq/= gcdn1 !divn1 abszE mulr_sign_norm. Qed. Fact valqK x : fracq (valq x) = x. Proof. move: x => [[n d] /= Pnd]; apply: val_inj; rewrite ?val_fracq/=. move: Pnd; rewrite /coprime /fracq /= => /andP[] hd -/eqP hnd. by rewrite lt_gtF ?gt_eqF //= hnd !divn1 mulz_sign_abs abszE gtr0_norm. Qed. Definition scalq '(n, d) := sgr d * (gcdn `|n| `|d|)%:Z. Lemma scalq_def x : scalq x = sgr x.2 * (gcdn `|x.1| `|x.2|)%:Z. Proof. by case: x. Qed. Fact scalq_eq0 x : (scalq x == 0) = (x.2 == 0). Proof. case: x => n d; rewrite scalq_def /= mulf_eq0 sgr_eq0 /= eqz_nat. rewrite -[gcdn _ _ == 0]negbK -lt0n gcdn_gt0 ?absz_gt0 [X in ~~ X]orbC. by case: sgrP. Qed. Lemma sgr_scalq x : sgr (scalq x) = sgr x.2. Proof. rewrite scalq_def sgrM sgr_id -[(gcdn _ _)%:Z]intz sgr_nat. by rewrite -lt0n gcdn_gt0 ?absz_gt0 orbC; case: sgrP; rewrite // mul0r. Qed. Lemma signr_scalq x : (scalq x < 0) = (x.2 < 0). Proof. by rewrite -!sgr_cp0 sgr_scalq. Qed. Lemma scalqE x : x.2 != 0 -> scalq x = (-1) ^+ (x.2 < 0)%R * (gcdn `|x.1| `|x.2|)%:Z. Proof. by rewrite scalq_def; case: sgrP. Qed. Fact valq_frac x : x.2 != 0 -> x = (scalq x * numq (fracq x), scalq x * denq (fracq x)). Proof. move=> x2_neq0; rewrite scalqE//; move: x2_neq0. case: x => [n d] /= d_neq0; rewrite num_fracq den_fracq/= ?d_neq0. rewrite mulr_signM -mulrA -!PoszM addKb. do 2!rewrite muln_divCA ?(dvdn_gcdl, dvdn_gcdr) // divnn. by rewrite gcdn_gt0 !absz_gt0 d_neq0 orbT !muln1 !mulz_sign_abs. Qed. Definition zeroq := 0%Q. Definition oneq := 1%Q. Fact frac0q x : fracq (0, x) = zeroq. Proof. apply: val_inj; rewrite //= val_fracq/= div0n !gcd0n !mulr0 !divnn. by have [//|x_neq0] := eqVneq; rewrite absz_gt0 x_neq0. Qed. Fact fracq0 x : fracq (x, 0) = zeroq. Proof. exact/eqP. Qed. Variant fracq_spec (x : int * int) : int * int -> rat -> Type := | FracqSpecN of x.2 = 0 : fracq_spec x (x.1, 0) zeroq | FracqSpecP k fx of k != 0 : fracq_spec x (k * numq fx, k * denq fx) fx. Fact fracqP x : fracq_spec x x (fracq x). Proof. case: x => n d /=; have [d_eq0 | d_neq0] := eqVneq d 0. by rewrite d_eq0 fracq0; constructor. by rewrite {2}[(_, _)]valq_frac //; constructor; rewrite scalq_eq0. Qed. Lemma rat_eqE x y : (x == y) = (numq x == numq y) && (denq x == denq y). Proof. rewrite -val_eqE [val x]surjective_pairing [val y]surjective_pairing /=. by rewrite xpair_eqE. Qed. Lemma sgr_denq x : sgr (denq x) = 1. Proof. by apply/eqP; rewrite sgr_cp0. Qed. Lemma normr_denq x : `|denq x| = denq x. Proof. by rewrite gtr0_norm. Qed. Lemma absz_denq x : `|denq x|%N = denq x :> int. Proof. by rewrite abszE normr_denq. Qed. Lemma rat_eq x y : (x == y) = (numq x * denq y == numq y * denq x). Proof. symmetry; rewrite rat_eqE andbC. have [->|] /= := eqVneq (denq _); first by rewrite (inj_eq (mulIf _)). apply: contraNF => /eqP hxy; rewrite -absz_denq -[eqbRHS]absz_denq. rewrite eqz_nat /= eqn_dvd. rewrite -(@Gauss_dvdr _ `|numq x|) 1?coprime_sym ?coprime_num_den // andbC. rewrite -(@Gauss_dvdr _ `|numq y|) 1?coprime_sym ?coprime_num_den //. by rewrite -!abszM hxy -{1}hxy !abszM !dvdn_mull ?dvdnn. Qed. Fact fracq_eq x y : x.2 != 0 -> y.2 != 0 -> (fracq x == fracq y) = (x.1 * y.2 == y.1 * x.2). Proof. case: fracqP=> //= u fx u_neq0 _; case: fracqP=> //= v fy v_neq0 _; symmetry. rewrite [eqbRHS]mulrC mulrACA [eqbRHS]mulrACA. by rewrite [denq _ * _]mulrC (inj_eq (mulfI _)) ?mulf_neq0 // rat_eq. Qed. Fact fracq_eq0 x : (fracq x == zeroq) = (x.1 == 0) || (x.2 == 0). Proof. move: x=> [n d] /=; have [->|d0] := eqVneq d 0. by rewrite fracq0 eqxx orbT. by rewrite -[zeroq]valqK orbF fracq_eq ?d0 //= mulr1 mul0r. Qed. Fact fracqMM x n d : x != 0 -> fracq (x * n, x * d) = fracq (n, d). Proof. move=> x_neq0; apply/eqP. have [->|d_neq0] := eqVneq d 0; first by rewrite mulr0 !fracq0. by rewrite fracq_eq ?mulf_neq0 //= mulrCA mulrA. Qed. (* We "lock" the definition of addq, oppq, mulq and invq, using a match on *) (* the constructor Rat for both arguments, so that it may only be reduced *) (* when applied to explicit rationals. Since fracq is also "locked" in a *) (* similar way, fracq will not reduce to a Rat x xP unless it is also applied *) (* to "enough" constructors. This preserves the reduction on gound elements *) (* while it suspends it when applied to at least one variable at the leaf of *) (* the arithmetic operation. *) (* Moreover we optimize addition when one or both arguments are integers, *) (* in which case we presimplify the output, this shortens the size of the hnf *) (* of terms of the form N%:Q when N is a concrete natural number. *) Definition addq_subdef (x y : int * int) := let: (x1, x2) := x in let: (y1, y2) := y in match x2, y2 with | Posz 1, Posz 1 => match x1, y1 with | Posz 0, _ => (y1, 1) | _, Posz 0 => (x1, 1) | Posz n, Posz 1 => (Posz n.+1, 1) | Posz 1, Posz n => (Posz n.+1, 1) | _, _ => (x1 + y1, 1) end | Posz 1, _ => (x1 * y2 + y1, y2) | _, Posz 1 => (x1 + y1 * x2, x2) | _, _ => (x1 * y2 + y1 * x2, x2 * y2) end. Definition addq '(Rat x xP) '(Rat y yP) := fracq (addq_subdef x y). Lemma addq_def x y : addq x y = fracq (addq_subdef (valq x) (valq y)). Proof. by case: x; case: y. Qed. Lemma addq_subdefE x y : addq_subdef x y = (x.1 * y.2 + y.1 * x.2, x.2 * y.2). Proof. case: x y => [x1 [[|[|x2]]|x2]] [y1 [[|[|y2]]|y2]]/=; rewrite ?Monoid.simpm//. by case: x1 y1 => [[|[|m]]|m] [[|[|n]]|n]; rewrite ?Monoid.simpm// -PoszD addn1. Qed. Definition oppq_subdef (x : int * int) := (- x.1, x.2). Definition oppq '(Rat x xP) := fracq (oppq_subdef x). Definition oppq_def x : oppq x = fracq (oppq_subdef (valq x)). Proof. by case: x. Qed. Fact addq_subdefC : commutative addq_subdef. Proof. by move=> x y; rewrite !addq_subdefE addrC [x.2 * _]mulrC. Qed. Fact addq_subdefA : associative addq_subdef. Proof. move=> x y z; rewrite !addq_subdefE. by rewrite !mulrA !mulrDl addrA ![_ * x.2]mulrC !mulrA. Qed. Fact addq_frac x y : x.2 != 0 -> y.2 != 0 -> (addq (fracq x) (fracq y)) = fracq (addq_subdef x y). Proof. case: fracqP => // u fx u_neq0 _; case: fracqP => // v fy v_neq0 _. rewrite addq_def !addq_subdefE /=. rewrite ![(_ * numq _) * _]mulrACA [(_ * denq _) * _]mulrACA. by rewrite [v * _]mulrC -mulrDr fracqMM ?mulf_neq0. Qed. Fact ratzD : {morph ratz : x y / x + y >-> addq x y}. Proof. by move=> x y; rewrite !ratz_frac addq_frac// addq_subdefE/= !mulr1. Qed. Fact oppq_frac x : oppq (fracq x) = fracq (oppq_subdef x). Proof. rewrite /oppq_subdef; case: fracqP => /= [|u fx u_neq0]. by rewrite fracq0. by rewrite oppq_def -mulrN fracqMM. Qed. Fact ratzN : {morph ratz : x / - x >-> oppq x}. Proof. by move=> x /=; rewrite !ratz_frac // /add /= !mulr1. Qed. Fact addqC : commutative addq. Proof. by move=> x y; rewrite !addq_def /= addq_subdefC. Qed. Fact addqA : associative addq. Proof. move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK. by rewrite ?addq_frac ?addq_subdefA// ?addq_subdefE ?mulf_neq0 ?denq_neq0. Qed. Fact add0q : left_id zeroq addq. Proof. move=> x; rewrite -[x]valqK -[zeroq]valqK addq_frac ?denq_neq0 // !addq_subdefE. by rewrite mul0r add0r mulr1 mul1r -surjective_pairing. Qed. Fact addNq : left_inverse (fracq (0, 1)) oppq addq. Proof. move=> x; rewrite -[x]valqK !(addq_frac, oppq_frac) ?denq_neq0 //. rewrite !addq_subdefE /oppq_subdef //= mulNr addNr; apply/eqP. by rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= !mul0r. Qed. HB.instance Definition _ := GRing.isZmodule.Build rat addqA addqC add0q addNq. Definition mulq_subdef (x y : int * int) := let: (x1, x2) := x in let: (y1, y2) := y in match x2, y2 with | Posz 1, Posz 1 => (x1 * y1, 1) | Posz 1, _ => (x1 * y1, y2) | _, Posz 1 => (x1 * y1, x2) | _, _ => (x1 * y1, x2 * y2) end. Definition mulq '(Rat x xP) '(Rat y yP) := fracq (mulq_subdef x y). Lemma mulq_def x y : mulq x y = fracq (mulq_subdef (valq x) (valq y)). Proof. by case: x; case: y. Qed. Lemma mulq_subdefE x y : mulq_subdef x y = (x.1 * y.1, x.2 * y.2). Proof. by case: x y => [x1 [[|[|x2]]|x2]] [y1 [[|[|y2]]|y2]]/=; rewrite ?Monoid.simpm. Qed. Fact mulq_subdefC : commutative mulq_subdef. Proof. by move=> x y; rewrite !mulq_subdefE mulrC [_ * x.2]mulrC. Qed. Fact mul_subdefA : associative mulq_subdef. Proof. by move=> x y z; rewrite !mulq_subdefE !mulrA. Qed. Definition invq_subdef (x : int * int) := (x.2, x.1). Definition invq '(Rat x xP) := fracq (invq_subdef x). Lemma invq_def x : invq x = fracq (invq_subdef (valq x)). Proof. by case: x. Qed. Fact mulq_frac x y : (mulq (fracq x) (fracq y)) = fracq (mulq_subdef x y). Proof. rewrite mulq_def !mulq_subdefE; case: (fracqP x) => /= [|u fx u_neq0]. by rewrite !mul0r !mul1r fracq0 frac0q. case: (fracqP y) => /= [|v fy v_neq0]. by rewrite !mulr0 !mulr1 fracq0 frac0q. by rewrite ![_ * (v * _)]mulrACA [RHS]fracqMM ?mulf_neq0. Qed. Fact ratzM : {morph ratz : x y / x * y >-> mulq x y}. Proof. by move=> x y /=; rewrite !ratz_frac //= !mulr1. Qed. Fact invq_frac x : x.1 != 0 -> x.2 != 0 -> invq (fracq x) = fracq (invq_subdef x). Proof. by rewrite invq_def; case: (fracqP x) => // k ? k0; rewrite fracqMM. Qed. Fact mulqC : commutative mulq. Proof. by move=> x y; rewrite !mulq_def mulq_subdefC. Qed. Fact mulqA : associative mulq. Proof. by move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK !mulq_frac mul_subdefA. Qed. Fact mul1q : left_id oneq mulq. Proof. move=> x; rewrite -[x]valqK -[oneq]valqK; rewrite mulq_frac !mulq_subdefE. by rewrite !mul1r -surjective_pairing. Qed. Fact mulq_addl : left_distributive mulq addq. Proof. move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK /=. rewrite !(mulq_frac, addq_frac, mulq_subdefE, addq_subdefE) ?mulf_neq0 ?denq_neq0 //=. apply/eqP; rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= !mulrDl; apply/eqP. by rewrite !mulrA ![_ * (valq z).1]mulrC !mulrA ![_ * (valq x).2]mulrC !mulrA. Qed. Fact nonzero1q : oneq != zeroq. Proof. by []. Qed. HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build rat mulqA mulqC mul1q mulq_addl nonzero1q. Fact mulVq x : x != 0 -> mulq (invq x) x = 1. Proof. rewrite -[x]valqK -[0]valqK fracq_eq ?denq_neq0 //= mulr1 mul0r=> nx0. rewrite !(mulq_frac, invq_frac, mulq_subdefE) ?denq_neq0 // -[1]valqK. by apply/eqP; rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= mulr1 mul1r mulrC. Qed. Fact invq0 : invq 0 = 0. Proof. exact/eqP. Qed. HB.instance Definition _ := GRing.ComNzRing_isField.Build rat mulVq invq0. Lemma numq_eq0 x : (numq x == 0) = (x == 0). Proof. rewrite -[x]valqK fracq_eq0; case: fracqP=> /= [|k {}x k0]. by rewrite eqxx orbT. by rewrite !mulf_eq0 (negPf k0) /= denq_eq0 orbF. Qed. Notation "n %:Q" := ((n : int)%:~R : rat) : ring_scope. #[global] Hint Resolve denq_neq0 denq_gt0 denq_ge0 : core. Definition subq (x y : rat) : rat := (addq x (oppq y)). Definition divq (x y : rat) : rat := (mulq x (invq y)). Infix "+" := addq : rat_scope. Notation "- x" := (oppq x) : rat_scope. Infix "*" := mulq : rat_scope. Notation "x ^-1" := (invq x) : rat_scope. Infix "-" := subq : rat_scope. Infix "/" := divq : rat_scope. (* ratz should not be used, %:Q should be used instead *) Lemma ratzE n : ratz n = n%:Q. Proof. elim: n=> [|n ihn|n ihn]; first by rewrite mulr0z ratz_frac. by rewrite intS mulrzDr ratzD ihn. by rewrite intS opprD mulrzDr ratzD ihn. Qed. Lemma numq_int n : numq n%:Q = n. Proof. by rewrite -ratzE. Qed. Lemma denq_int n : denq n%:Q = 1. Proof. by rewrite -ratzE. Qed. Lemma rat0 : 0%:Q = 0. Proof. by []. Qed. Lemma rat1 : 1%:Q = 1. Proof. by []. Qed. Lemma numqN x : numq (- x) = - numq x. Proof. rewrite [- _]oppq_def/= num_fracq. case: x => -[a b]; rewrite /numq/= => /andP[b_gt0]. rewrite /coprime => /eqP cab. by rewrite lt_gtF ?gt_eqF // {2}abszN cab divn1 mulz_sign_abs. Qed. Lemma denqN x : denq (- x) = denq x. Proof. rewrite [- _]oppq_def den_fracq. case: x => -[a b]; rewrite /denq/= => /andP[b_gt0]. by rewrite /coprime=> /eqP cab; rewrite gt_eqF // abszN cab divn1 gtz0_abs. Qed. (* Will be subsumed by pnatr_eq0 *) Fact intq_eq0 n : (n%:~R == 0 :> rat) = (n == 0)%N. Proof. by rewrite -ratzE /ratz rat_eqE/= /numq /denq/= eqxx andbT. Qed. (* fracq should never appear, its canonical form is _%:Q / _%:Q *) Lemma fracqE x : fracq x = x.1%:Q / x.2%:Q. Proof. move: x => [m n] /=; apply/val_inj; rewrite val_fracq/=. case: eqVneq => //= [->|n_neq0]; first by rewrite rat0 invr0 mulr0. rewrite -[m%:Q]valqK -[n%:Q]valqK. rewrite [_^-1]invq_frac ?denq_neq0 ?numq_eq0 ?intq_eq0//=. rewrite [X in valq X]mulq_frac val_fracq /invq_subdef !mulq_subdefE/=. by rewrite -!/(numq _) -!/(denq _) !numq_int !denq_int mul1r mulr1 n_neq0. Qed. Lemma divq_num_den x : (numq x)%:Q / (denq x)%:Q = x. Proof. by rewrite -{3}[x]valqK [valq _]surjective_pairing /= fracqE. Qed. Variant divq_spec (n d : int) : int -> int -> rat -> Type := | DivqSpecN of d = 0 : divq_spec n d n 0 0 | DivqSpecP k x of k != 0 : divq_spec n d (k * numq x) (k * denq x) x. (* replaces fracqP *) Lemma divqP n d : divq_spec n d n d (n%:Q / d%:Q). Proof. set x := (n, d); rewrite -[n]/x.1 -[d]/x.2 -fracqE. by case: fracqP => [_|k fx k_neq0] /=; constructor. Qed. Variant rat_spec (* (x : rat) *) : rat -> int -> int -> Type := Rat_spec (n : int) (d : nat) & coprime `|n| d.+1 : rat_spec (* x *) (n%:Q / d.+1%:Q) n d.+1. Lemma ratP x : rat_spec x (numq x) (denq x). Proof. rewrite -{1}[x](divq_num_den); case hd: denq => [p|n]. have: 0 < p%:Z by rewrite -hd denq_gt0. case: p hd=> //= n hd; constructor; rewrite -?hd ?divq_num_den //. by rewrite -[n.+1]/`|n.+1|%N -hd coprime_num_den. by move: (denq_gt0 x); rewrite hd. Qed. Lemma coprimeq_num n d : coprime `|n| `|d| -> numq (n%:~R / d%:~R) = sgr d * n. Proof. move=> cnd /=; have <- := fracqE (n, d). rewrite num_fracq/= (eqP (cnd : _ == 1)) divn1. have [|d_gt0|d_lt0] := sgrP d; by rewrite (mul0r, mul1r, mulN1r) //= ?[_ ^ _]signrN ?mulNr mulz_sign_abs. Qed. Lemma coprimeq_den n d : coprime `|n| `|d| -> denq (n%:~R / d%:~R) = (if d == 0 then 1 else `|d|). Proof. move=> cnd; have <- := fracqE (n, d). by rewrite den_fracq/= (eqP (cnd : _ == 1)) divn1; case: d {cnd}; case. Qed. Lemma denqVz (i : int) : i != 0 -> denq (i%:~R^-1) = `|i|. Proof. move=> h; rewrite -div1r -[1]/(1%:~R). by rewrite coprimeq_den /= ?coprime1n // (negPf h). Qed. Lemma numqE x : (numq x)%:~R = x * (denq x)%:~R. Proof. by rewrite -{2}[x]divq_num_den divfK // intq_eq0 denq_eq0. Qed. Lemma denqP x : {d | denq x = d.+1}. Proof. by rewrite /denq; case: x => [[_ [[|d]|]] //= _]; exists d. Qed. Definition normq '(Rat x _) : rat := `|x.1|%:~R / (x.2)%:~R. Definition le_rat '(Rat x _) '(Rat y _) := x.1 * y.2 <= y.1 * x.2. Definition lt_rat '(Rat x _) '(Rat y _) := x.1 * y.2 < y.1 * x.2. Lemma normqE x : normq x = `|numq x|%:~R / (denq x)%:~R. Proof. by case: x. Qed. Lemma le_ratE x y : le_rat x y = (numq x * denq y <= numq y * denq x). Proof. by case: x; case: y. Qed. Lemma lt_ratE x y : lt_rat x y = (numq x * denq y < numq y * denq x). Proof. by case: x; case: y. Qed. Lemma gt_rat0 x : lt_rat 0 x = (0 < numq x). Proof. by rewrite lt_ratE mul0r mulr1. Qed. Lemma lt_rat0 x : lt_rat x 0 = (numq x < 0). Proof. by rewrite lt_ratE mul0r mulr1. Qed. Lemma ge_rat0 x : le_rat 0 x = (0 <= numq x). Proof. by rewrite le_ratE mul0r mulr1. Qed. Lemma le_rat0 x : le_rat x 0 = (numq x <= 0). Proof. by rewrite le_ratE mul0r mulr1. Qed. Fact le_rat0D x y : le_rat 0 x -> le_rat 0 y -> le_rat 0 (x + y). Proof. rewrite !ge_rat0 => hnx hny. have hxy: (0 <= numq x * denq y + numq y * denq x). by rewrite addr_ge0 ?mulr_ge0. rewrite [_ + _]addq_def /numq /= -!/(denq _) ?mulf_eq0 ?denq_eq0. rewrite val_fracq/=; case: ifP => //=. by rewrite ?addq_subdefE !mulr_ge0// !le_gtF ?mulr_ge0 ?denq_ge0//=. Qed. Fact le_rat0M x y : le_rat 0 x -> le_rat 0 y -> le_rat 0 (x * y). Proof. rewrite !ge_rat0 => hnx hny. have hxy: (0 <= numq x * denq y + numq y * denq x). by rewrite addr_ge0 ?mulr_ge0. rewrite [_ * _]mulq_def /numq /= -!/(denq _) ?mulf_eq0 ?denq_eq0. rewrite val_fracq/=; case: ifP => //=. by rewrite ?mulq_subdefE !mulr_ge0// !le_gtF ?mulr_ge0 ?denq_ge0//=. Qed. Fact le_rat0_anti x : le_rat 0 x -> le_rat x 0 -> x = 0. Proof. by move=> hx hy; apply/eqP; rewrite -numq_eq0 eq_le -ge_rat0 -le_rat0 hx hy. Qed. Lemma sgr_numq_div (n d : int) : sgr (numq (n%:Q / d%:Q)) = sgr n * sgr d. Proof. set x := (n, d); rewrite -[n]/x.1 -[d]/x.2 -fracqE. case: fracqP => [|k fx k_neq0] /=; first by rewrite mulr0. by rewrite !sgrM mulrACA -expr2 sqr_sg k_neq0 sgr_denq mulr1 mul1r. Qed. Fact subq_ge0 x y : le_rat 0 (y - x) = le_rat x y. Proof. symmetry; rewrite ge_rat0 !le_ratE -subr_ge0. case: ratP => nx dx cndx; case: ratP => ny dy cndy. rewrite -!mulNr addf_div ?intq_eq0 // !mulNr -!rmorphM -rmorphB /=. symmetry; rewrite !leNgt -sgr_cp0 sgr_numq_div mulrC gtr0_sg //. by rewrite mul1r sgr_cp0. Qed. Fact le_rat_total : total le_rat. Proof. by move=> x y; rewrite !le_ratE; apply: le_total. Qed. Fact numq_sign_mul (b : bool) x : numq ((-1) ^+ b * x) = (-1) ^+ b * numq x. Proof. by case: b; rewrite ?(mul1r, mulN1r) // numqN. Qed. Fact numq_div_lt0 n d : n != 0 -> d != 0 -> (numq (n%:~R / d%:~R) < 0)%R = (n < 0)%R (+) (d < 0)%R. Proof. move=> n0 d0; rewrite -sgr_cp0 sgr_numq_div !sgr_def n0 d0. by rewrite !mulr1n -signr_addb; case: (_ (+) _). Qed. Lemma normr_num_div n d : `|numq (n%:~R / d%:~R)| = numq (`|n|%:~R / `|d|%:~R). Proof. rewrite (normrEsg n) (normrEsg d) !rmorphM /= invfM mulrACA !sgr_def. have [->|n_neq0] := eqVneq; first by rewrite mul0r mulr0. have [->|d_neq0] := eqVneq; first by rewrite invr0 !mulr0. rewrite !intr_sign invr_sign -signr_addb numq_sign_mul -numq_div_lt0 //. by apply: (canRL (signrMK _)); rewrite mulz_sign_abs. Qed. Fact norm_ratN x : normq (- x) = normq x. Proof. by rewrite !normqE numqN denqN normrN. Qed. Fact ge_rat0_norm x : le_rat 0 x -> normq x = x. Proof. rewrite ge_rat0; case: ratP=> [] // n d cnd n_ge0. by rewrite normqE /= normr_num_div ?ger0_norm // divq_num_den. Qed. Fact lt_rat_def x y : (lt_rat x y) = (y != x) && (le_rat x y). Proof. by rewrite lt_ratE le_ratE lt_def rat_eq. Qed. HB.instance Definition _ := Num.IntegralDomain_isLeReal.Build rat le_rat0D le_rat0M le_rat0_anti subq_ge0 (@le_rat_total 0) norm_ratN ge_rat0_norm lt_rat_def. Lemma numq_ge0 x : (0 <= numq x) = (0 <= x). Proof. by case: ratP => n d cnd; rewrite ?pmulr_lge0 ?invr_gt0 (ler0z, ltr0z). Qed. Lemma numq_le0 x : (numq x <= 0) = (x <= 0). Proof. by rewrite -oppr_ge0 -numqN numq_ge0 oppr_ge0. Qed. Lemma numq_gt0 x : (0 < numq x) = (0 < x). Proof. by rewrite !ltNge numq_le0. Qed. Lemma numq_lt0 x : (numq x < 0) = (x < 0). Proof. by rewrite !ltNge numq_ge0. Qed. Lemma sgr_numq x : sgz (numq x) = sgz x. Proof. apply/eqP; case: (sgzP x); rewrite sgz_cp0 ?(numq_gt0, numq_lt0) //. by move->. Qed. Lemma denq_mulr_sign (b : bool) x : denq ((-1) ^+ b * x) = denq x. Proof. by case: b; rewrite ?(mul1r, mulN1r) // denqN. Qed. Lemma denq_norm x : denq `|x| = denq x. Proof. by rewrite normrEsign denq_mulr_sign. Qed. Module ratArchimedean. Section ratArchimedean. Implicit Types x : rat. Definition floor x : int := (numq x %/ denq x)%Z. Definition ceil x : int := - (- numq x %/ denq x)%Z. Definition truncn x : nat := if 0 <= x then (`|numq x| %/ `|denq x|)%N else 0%N. Let is_int x := denq x == 1. Let is_nat x := (0 <= x) && (denq x == 1). Fact floorP x : if x \is Num.real then (floor x)%:~R <= x < (floor x + 1)%:~R else floor x == 0. Proof. rewrite num_real /floor; case: (ratP x) => n d _ {x}; rewrite ler_pdivlMr//. by rewrite ltr_pdivrMr// -!intrM ler_int ltr_int lez_floor ?ltz_ceil. Qed. Fact ceilP x : ceil x = - floor (- x). Proof. by rewrite /ceil /floor numqN denqN. Qed. Fact truncnP x : truncn x = if floor x is Posz n then n else 0. Proof. rewrite /truncn /floor; case: (ratP x) => n d _ {x} /=. by rewrite !ler_pdivlMr// mul0r; case: n => n; rewrite ler0z//= mul1n. Qed. Fact intrP x : reflect (exists n, x = n%:~R) (is_int x). Proof. apply: (iffP idP) => [/eqP d1 | [i ->]]; [|by rewrite /is_int denq_int]. by exists (numq x); case: (ratP x) d1 => n d _ ->; rewrite divr1. Qed. Fact natrP x : reflect (exists n, x = n%:R) (is_nat x). Proof. apply: (iffP idP) => [/andP[]/[swap]/intrP[i ->]|[n ->]]. by rewrite ler0z; case: i => [n _|//]; exists n. by rewrite /is_nat pmulrn ler0z denq_int. Qed. End ratArchimedean. End ratArchimedean. HB.instance Definition _ := Num.NumDomain_hasFloorCeilTruncn.Build rat ratArchimedean.floorP ratArchimedean.ceilP ratArchimedean.truncnP ratArchimedean.intrP ratArchimedean.natrP. Lemma floorErat (x : rat) : Num.floor x = (numq x %/ denq x)%Z. Proof. by []. Qed. Lemma ceilErat (x : rat) : Num.ceil x = - (- numq x %/ denq x)%Z. Proof. by []. Qed. Lemma Qint_def (x : rat) : (x \is a Num.int) = (denq x == 1). Proof. by []. Qed. Lemma numqK : {in Num.int, cancel (fun x => numq x) intr}. Proof. by move=> _ /intrP [x ->]; rewrite numq_int. Qed. Lemma natq_div m n : (n %| m)%N -> (m %/ n)%:R = m%:R / n%:R :> rat. Proof. exact/pchar0_natf_div/pchar_num. Qed. Section InRing. Variable R : unitRingType. Definition ratr x : R := (numq x)%:~R / (denq x)%:~R. Lemma ratr_int z : ratr z%:~R = z%:~R. Proof. by rewrite /ratr numq_int denq_int divr1. Qed. Lemma ratr_nat n : ratr n%:R = n%:R. Proof. exact: ratr_int n. Qed. Lemma rpred_rat (S : divringClosed R) a : ratr a \in S. Proof. by rewrite rpred_div ?rpred_int. Qed. End InRing. Section Fmorph. Implicit Type rR : unitRingType. Lemma fmorph_rat (aR : fieldType) rR (f : {rmorphism aR -> rR}) a : f (ratr _ a) = ratr _ a. Proof. by rewrite fmorph_div !rmorph_int. Qed. Lemma fmorph_eq_rat rR (f : {rmorphism rat -> rR}) : f =1 ratr _. Proof. by move=> a; rewrite -{1}[a]divq_num_den fmorph_div !rmorph_int. Qed. End Fmorph. Section Linear. Implicit Types (U V : lmodType rat) (A B : lalgType rat). Lemma rat_linear U V (f : U -> V) : zmod_morphism f -> scalable f. Proof. move=> fB a u. pose aM := GRing.isZmodMorphism.Build U V f fB. pose phi : {additive U -> V} := HB.pack f aM. rewrite -[f]/(phi : _ -> _) -{2}[a]divq_num_den mulrC -scalerA. apply: canRL (scalerK _) _; first by rewrite intr_eq0 denq_neq0. rewrite 2!scaler_int -3!raddfMz /=. by rewrite -scalerMzr scalerMzl -mulrzr -numqE scaler_int. Qed. End Linear. Section InPrealField. Variable F : numFieldType. Fact ratr_is_zmod_morphism : zmod_morphism (@ratr F). Proof. have injZtoQ: @injective rat int intr by apply: intr_inj. have nz_den x: (denq x)%:~R != 0 :> F by rewrite intr_eq0 denq_eq0. move=> x y. apply: (canLR (mulfK (nz_den _))); apply: (mulIf (nz_den x)). rewrite mulrAC mulrBl divfK ?nz_den // mulrAC -!rmorphM. apply: (mulIf (nz_den y)); rewrite mulrAC mulrBl divfK ?nz_den //. rewrite -!(rmorphM, rmorphB); congr _%:~R; apply: injZtoQ. rewrite !(rmorphM, rmorphB) /= [_ - _]lock /= -lock !numqE. by rewrite (mulrAC y) -!mulrBl -mulrA mulrAC !mulrA. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `ratr_is_additive` instead")] Definition ratr_is_additive := ratr_is_zmod_morphism. Fact ratr_is_monoid_morphism : monoid_morphism (@ratr F). Proof. have injZtoQ: @injective rat int intr by apply: intr_inj. have nz_den x: (denq x)%:~R != 0 :> F by rewrite intr_eq0 denq_eq0. split=> [|x y]; first by rewrite /ratr divr1. rewrite /ratr mulrC mulrAC; apply: canLR (mulKf (nz_den _)) _; rewrite !mulrA. do 2!apply: canRL (mulfK (nz_den _)) _; rewrite -!rmorphM; congr _%:~R. apply: injZtoQ; rewrite !rmorphM [x * y]lock /= !numqE -lock. by rewrite -!mulrA mulrA mulrCA -!mulrA (mulrCA y). Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `ratr_is_monoid_morphism` instead")] Definition ratr_is_multiplicative := (fun g => (g.2,g.1)) ratr_is_monoid_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build rat F (@ratr F) ratr_is_zmod_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build rat F (@ratr F) ratr_is_monoid_morphism. Lemma ler_rat : {mono (@ratr F) : x y / x <= y}. Proof. move=> x y /=; case: (ratP x) => nx dx cndx; case: (ratP y) => ny dy cndy. rewrite !fmorph_div /= !ratr_int !ler_pdivlMr ?ltr0z //. by rewrite ![_ / _ * _]mulrAC !ler_pdivrMr ?ltr0z // -!rmorphM /= !ler_int. Qed. Lemma ltr_rat : {mono (@ratr F) : x y / x < y}. Proof. exact: leW_mono ler_rat. Qed. Lemma ler0q x : (0 <= ratr F x) = (0 <= x). Proof. by rewrite (_ : 0 = ratr F 0) ?ler_rat ?rmorph0. Qed. Lemma lerq0 x : (ratr F x <= 0) = (x <= 0). Proof. by rewrite (_ : 0 = ratr F 0) ?ler_rat ?rmorph0. Qed. Lemma ltr0q x : (0 < ratr F x) = (0 < x). Proof. by rewrite (_ : 0 = ratr F 0) ?ltr_rat ?rmorph0. Qed. Lemma ltrq0 x : (ratr F x < 0) = (x < 0). Proof. by rewrite (_ : 0 = ratr F 0) ?ltr_rat ?rmorph0. Qed. Lemma ratr_sg x : ratr F (sgr x) = sgr (ratr F x). Proof. by rewrite !sgr_def fmorph_eq0 ltrq0 rmorphMn /= rmorph_sign. Qed. Lemma ratr_norm x : ratr F `|x| = `|ratr F x|. Proof. by rewrite {2}[x]numEsign rmorphMsign normrMsign [`|ratr F _|]ger0_norm ?ler0q. Qed. Lemma minr_rat : {morph ratr F : x y / Num.min x y}. Proof. by move=> x y; rewrite !minEle ler_rat; case: leP. Qed. Lemma maxr_rat : {morph ratr F : x y / Num.max x y}. Proof. by move=> x y; rewrite !maxEle ler_rat; case: leP. Qed. End InPrealField. Section InParchiField. Variable F : archiNumFieldType. Lemma floor_rat : {mono (@ratr F) : x / Num.floor x}. Proof. move=> x; apply: floor_def; apply/andP; split. - by rewrite -ratr_int ler_rat floor_le_tmp. - by rewrite -ratr_int ltr_rat floorD1_gt. Qed. Lemma ceil_rat : {mono (@ratr F) : x / Num.ceil x}. Proof. by move=> x; rewrite !ceilNfloor -rmorphN floor_rat. Qed. End InParchiField. Arguments ratr {R}. Lemma Qint_dvdz (m d : int) : (d %| m)%Z -> (m%:~R / d%:~R : rat) \is a Num.int. Proof. case/dvdzP=> z ->; rewrite rmorphM /=; have [->|dn0] := eqVneq d 0. by rewrite mulr0 mul0r. by rewrite mulfK ?intr_eq0. Qed. Lemma Qnat_dvd (m d : nat) : (d %| m)%N -> (m%:R / d%:R : rat) \is a Num.nat. Proof. by move=> h; rewrite natrEint divr_ge0 ?ler0n // !pmulrn Qint_dvdz. Qed. Section ZpolyScale. Local Notation pZtoQ := (map_poly (intr : int -> rat)). Lemma size_rat_int_poly p : size (pZtoQ p) = size p. Proof. by apply: size_map_inj_poly; first apply: intr_inj. Qed. Lemma rat_poly_scale (p : {poly rat}) : {q : {poly int} & {a | a != 0 & p = a%:~R^-1 *: pZtoQ q}}. Proof. pose a := \prod_(i < size p) denq p`_i. have nz_a: a != 0 by apply/prodf_neq0=> i _; apply: denq_neq0. exists (map_poly numq (a%:~R *: p)), a => //. apply: canRL (scalerK _) _; rewrite ?intr_eq0 //. apply/polyP=> i; rewrite !(coefZ, coef_map_id0) // numqK // Qint_def mulrC. have [ltip | /(nth_default 0)->] := ltnP i (size p); last by rewrite mul0r. by rewrite [a](bigD1 (Ordinal ltip)) // rmorphM mulrA -numqE -rmorphM denq_int. Qed. Lemma dvdp_rat_int p q : (pZtoQ p %| pZtoQ q) = (p %| q). Proof. apply/dvdpP/Pdiv.Idomain.dvdpP=> [[/= r1 Dq] | [[/= a r] nz_a Dq]]; last first. exists (a%:~R^-1 *: pZtoQ r). by rewrite -scalerAl -rmorphM -Dq /= linearZ/= scalerK ?intr_eq0. have [r [a nz_a Dr1]] := rat_poly_scale r1; exists (a, r) => //=. apply: (map_inj_poly _ _ : injective pZtoQ) => //; first exact: intr_inj. by rewrite linearZ /= Dq Dr1 -scalerAl -rmorphM scalerKV ?intr_eq0. Qed. Lemma dvdpP_rat_int p q : p %| pZtoQ q -> {p1 : {poly int} & {a | a != 0 & p = a *: pZtoQ p1} & {r | q = p1 * r}}. Proof. have{p} [p [a nz_a ->]] := rat_poly_scale p. rewrite dvdpZl ?invr_eq0 ?intr_eq0 // dvdp_rat_int => dv_p_q. exists (zprimitive p); last exact: dvdpP_int. have [-> | nz_p] := eqVneq p 0. by exists 1; rewrite ?oner_eq0 // zprimitive0 map_poly0 !scaler0. exists ((zcontents p)%:~R / a%:~R). by rewrite mulf_neq0 ?invr_eq0 ?intr_eq0 ?zcontents_eq0. by rewrite mulrC -scalerA -map_polyZ -zpolyEprim. Qed. Lemma irreducible_rat_int p : irreducible_poly (pZtoQ p) <-> irreducible_poly p. Proof. rewrite /irreducible_poly size_rat_int_poly; split=> -[] p1 p_irr; split=> //. move=> q q1; rewrite /eqp -!dvdp_rat_int => rq. by apply/p_irr => //; rewrite size_rat_int_poly. move=> q + /dvdpP_rat_int [] r [] c c0 qE [] s sE. rewrite qE size_scale// size_rat_int_poly => r1. apply/(eqp_trans (eqp_scale _ c0)). rewrite /eqp !dvdp_rat_int; apply/p_irr => //. by rewrite sE dvdp_mulIl. Qed. End ZpolyScale. (* Integral spans. *) Definition inIntSpan (V : zmodType) m (s : m.-tuple V) v := exists a : int ^ m, v = \sum_(i < m) s`_i *~ a i. Lemma solve_Qint_span (vT : vectType rat) m (s : m.-tuple vT) v : {b : int ^ m & {p : seq (int ^ m) & forall a : int ^ m, v = \sum_(i < m) s`_i *~ a i <-> exists c : seq int, a = b + \sum_(i < size p) p`_i *~ c`_i}} + (~ inIntSpan s v). Proof. have s_s (i : 'I_m): s`_i \in <<s>>%VS by rewrite memv_span ?memt_nth. have s_Zs a: \sum_(i < m) s`_i *~ a i \in <<s>>%VS. by apply/rpred_sum => i _; apply/rpredMz. case s_v: (v \in <<s>>%VS); last by right=> [[a Dv]]; rewrite Dv s_Zs in s_v. move SE : (\matrix_(i < m, j < _) coord (vbasis <<s>>) j s`_i) => S. move rE : (\rank S) => r; move kE : (m - r)%N => k. have Dm: (m = k + r)%N by rewrite -kE -rE subnK ?rank_leq_row. rewrite Dm in s s_s s_Zs s_v S SE rE kE *. move=> {Dm m}; pose m := (k + r)%N. have [K kerK]: {K : 'M_(k, m) | map_mx intr K == kermx S}%MS. move: (mxrank_ker S); rewrite rE kE => krk. pose B := row_base (kermx S); pose d := \prod_ij denq (B ij.1 ij.2). exists (castmx (krk, erefl m) (map_mx numq (intr d *: B))). rewrite map_castmx !eqmx_cast -map_mx_comp map_mx_id_in => [|i j]; last first. rewrite mxE mulrC [d](bigD1 (i, j)) //= rmorphM mulrA. by rewrite -numqE -rmorphM numq_int. suff nz_d: d%:Q != 0 by rewrite !eqmx_scale // !eq_row_base andbb. by rewrite intr_eq0; apply/prodf_neq0 => i _; apply: denq_neq0. have [L _ [G uG [D _ defK]]] := int_Smith_normal_form K. have {K L D defK kerK} [kerGu kerS_sub_Gu]: map_mx intr (usubmx G) *m S = 0 /\ (kermx S <= map_mx intr (usubmx G))%MS. pose Kl : 'M[rat]_k := map_mx intr (lsubmx (K *m invmx G)). have {}defK: map_mx intr K = Kl *m map_mx intr (usubmx G). rewrite /Kl -map_mxM; congr map_mx. rewrite -[LHS](mulmxKV uG) -{2}[G]vsubmxK -{1}[K *m _]hsubmxK. rewrite mul_row_col -[RHS]addr0; congr (_ + _). rewrite defK mulmxK //= -[RHS](mul0mx _ (dsubmx G)); congr (_ *m _). apply/matrixP => i j; rewrite !mxE big1 //= => j1 _. rewrite mxE /= eqn_leq andbC. by rewrite leqNgt (leq_trans (valP j1)) ?mulr0 ?leq_addr. split; last by rewrite -(eqmxP kerK); apply/submxP; exists Kl. suff /row_full_inj: row_full Kl. by apply; rewrite mulmx0 mulmxA (sub_kermxP _) // -(eqmxP kerK) defK. rewrite /row_full eqn_leq rank_leq_row /= -{1}kE -{2}rE -(mxrank_ker S). by rewrite -(eqmxP kerK) defK mxrankM_maxl. pose T := map_mx intr (dsubmx G) *m S. have defS: map_mx intr (rsubmx (invmx G)) *m T = S. rewrite mulmxA -map_mxM /=; move: (mulVmx uG). rewrite -{2}[G]vsubmxK -{1}[invmx G]hsubmxK mul_row_col. move/(canRL (addKr _)) ->; rewrite -mulNmx raddfD /= map_mx1 map_mxM /=. by rewrite mulmxDl -mulmxA kerGu mulmx0 add0r mul1mx. pose vv := \row_j coord (vbasis <<s>>) j v. have uS: row_full S. apply/row_fullP; exists (\matrix_(i, j) coord s j (vbasis <<s>>)`_i). apply/matrixP => j1 j2; rewrite !mxE. rewrite -(coord_free _ _ (basis_free (vbasisP _))). rewrite -!tnth_nth (coord_span (vbasis_mem (mem_tnth j1 _))) linear_sum. by apply: eq_bigr => /= i _; rewrite -SE !mxE (tnth_nth 0) !linearZ. have eqST: (S :=: T)%MS by apply/eqmxP; rewrite -{1}defS !submxMl. case Zv: (map_mx denq (vv *m pinvmx T) == const_mx 1); last first. right=> [[a Dv]]; case/eqP: Zv; apply/rowP. have ->: vv = map_mx intr (\row_i a i) *m S. apply/rowP => j; rewrite !mxE Dv linear_sum. by apply: eq_bigr => i _; rewrite -SE -scaler_int linearZ !mxE. rewrite -defS -2!mulmxA; have ->: T *m pinvmx T = 1%:M. have uT: row_free T by rewrite /row_free -eqST rE. by apply: (row_free_inj uT); rewrite mul1mx mulmxKpV. by move=> i; rewrite mulmx1 -map_mxM 2!mxE denq_int mxE. pose b := map_mx numq (vv *m pinvmx T) *m dsubmx G. left; exists [ffun j => b 0 j], [seq [ffun j => (usubmx G) i j] | i : 'I_k]. rewrite size_image card_ord => a; rewrite -[a](addNKr [ffun j => b 0 j]). move: (_ + a) => h; under eq_bigr => i _ do rewrite !ffunE mulrzDr. rewrite big_split /=. have <-: v = \sum_(i < m) s`_i *~ b 0 i. transitivity (\sum_j (map_mx intr b *m S) 0 j *: (vbasis <<s>>)`_j). rewrite {1}(coord_vbasis s_v); apply: eq_bigr => j _; congr (_ *: _). suff ->: map_mx intr b = vv *m pinvmx T *m map_mx intr (dsubmx G). by rewrite -(mulmxA _ _ S) mulmxKpV ?mxE // -eqST submx_full. rewrite map_mxM /=; congr (_ *m _); apply/rowP => i; rewrite 2!mxE numqE. by have /eqP/rowP/(_ i)/[!mxE] -> := Zv; rewrite mulr1. rewrite (coord_vbasis (s_Zs _)); apply: eq_bigr => j _; congr (_ *: _). rewrite linear_sum mxE; apply: eq_bigr => i _. by rewrite -SE -scaler_int linearZ [b]lock !mxE. split. rewrite -[LHS]addr0 => /addrI hP; pose c := \row_i h i *m lsubmx (invmx G). exists [seq c 0 i | i : 'I_k]; congr (_ + _). have/sub_kermxP: map_mx intr (\row_i h i) *m S = 0. transitivity (\row_j coord (vbasis <<s>>) j (\sum_(i < m) s`_i *~ h i)). apply/rowP => j; rewrite !mxE linear_sum; apply: eq_bigr => i _. by rewrite -SE !mxE -scaler_int linearZ. by apply/rowP => j; rewrite !mxE -hP linear0. case/submx_trans/(_ kerS_sub_Gu)/submxP => c' /[dup]. move/(congr1 (mulmx^~ (map_mx intr (lsubmx (invmx G))))). rewrite -mulmxA -!map_mxM [in RHS]mulmx_lsub mul_usub_mx -/c mulmxV //=. rewrite scalar_mx_block -/(ulsubmx _) block_mxKul map_scalar_mx mulmx1. move=> <- {c'}; rewrite -map_mxM /= => defh; apply/ffunP => j. move/rowP/(_ j): defh; rewrite sum_ffunE !mxE => /intr_inj ->. apply: eq_bigr => i _; rewrite ffunMzE mulrzz mulrC. rewrite (nth_map i) ?size_enum_ord // nth_ord_enum ffunE. by rewrite (nth_map i) ?size_enum_ord // nth_ord_enum. case=> c /addrI -> {h}; rewrite -[LHS]addr0; congr (_ + _). pose h := \row_(j < k) c`_j *m usubmx G. transitivity (\sum_j (map_mx intr h *m S) 0 j *: (vbasis <<s>>)`_j). by rewrite map_mxM -mulmxA kerGu mulmx0 big1 // => j _; rewrite mxE scale0r. rewrite (coord_vbasis (s_Zs _)); apply: eq_bigr => i _; congr (_ *: _). rewrite linear_sum -SE mxE; apply: eq_bigr => j _. rewrite -scaler_int linearZ !mxE sum_ffunE; congr (_%:~R * _). apply: {i} eq_bigr => i _; rewrite mxE ffunMzE mulrzz mulrC. by rewrite (nth_map i) ?size_enum_ord // ffunE nth_ord_enum. Qed. Lemma dec_Qint_span (vT : vectType rat) m (s : m.-tuple vT) v : decidable (inIntSpan s v). Proof. have [[b [p aP]]|] := solve_Qint_span s v; last by right. left; exists b; apply/(aP b); exists [::]; rewrite big1 ?addr0 // => i _. by rewrite nth_nil mulr0z. Qed. Lemma eisenstein_crit (p : nat) (q : {poly int}) : prime p -> (size q != 1)%N -> ~~ (p %| lead_coef q)%Z -> ~~ (p ^+ 2 %| q`_0)%Z -> (forall i, (i < (size q).-1)%N -> p %| q`_i)%Z -> irreducible_poly q. Proof. move=> p_prime qN1 Ndvd_pql Ndvd_pq0 dvd_pq. apply/irreducible_rat_int. have qN0 : q != 0 by rewrite -lead_coef_eq0; apply: contraNneq Ndvd_pql => ->. split. rewrite size_map_poly_id0 ?intr_eq0 ?lead_coef_eq0//. by rewrite ltn_neqAle eq_sym qN1 size_poly_gt0. move=> f' +/dvdpP_rat_int[f [d dN0 feq]]; rewrite {f'}feq size_scale// => fN1. move=> /= [g q_eq]; rewrite q_eq (eqp_trans (eqp_scale _ _))//. have fN0 : f != 0 by apply: contra_neq qN0; rewrite q_eq => ->; rewrite mul0r. have gN0 : g != 0 by apply: contra_neq qN0; rewrite q_eq => ->; rewrite mulr0. rewrite size_map_poly_id0 ?intr_eq0 ?lead_coef_eq0// in fN1. have [/eqP/size_poly1P[c cN0 ->]|gN1] := eqVneq (size g) 1%N. by rewrite mulrC mul_polyC map_polyZ/= eqp_sym eqp_scale// intr_eq0. have c_neq0 : (lead_coef q)%:~R != 0 :> 'F_p by rewrite -(dvdz_pcharf (pchar_Fp _)). have : map_poly (intr : int -> 'F_p) q = (lead_coef q)%:~R *: 'X^((size q).-1). apply/val_inj/(@eq_from_nth _ 0) => [|i]; rewrite size_map_poly_id0//. by rewrite size_scale// size_polyXn -polySpred. move=> i_small; rewrite coef_poly i_small coefZ coefXn lead_coefE. move: i_small; rewrite polySpred// ltnS/=. case: ltngtP => // [i_lt|->]; rewrite (mulr1, mulr0)//= => _. by apply/eqP; rewrite -(dvdz_pcharf (pchar_Fp _))// dvd_pq. rewrite [in LHS]q_eq rmorphM/=. set c := (X in X *: _); set n := (_.-1). set pf := map_poly _ f; set pg := map_poly _ g => pfMpg. have dvdXn (r : {poly _}) : size r != 1%N -> r %| c *: 'X^n -> r`_0 = 0. move=> rN1; rewrite (eqp_dvdr _ (eqp_scale _ _))//. rewrite -['X]subr0; move=> /dvdp_exp_XsubCP[k lekn]; rewrite subr0. move=> /eqpP[u /andP[u1N0 u2N0]]; have [->|k_gt0] := posnP k. move=> /(congr1 (size \o val))/eqP. by rewrite /= !size_scale// size_polyXn (negPf rN1). move=> /(congr1 (fun p : {poly _} => p`_0))/eqP. by rewrite !coefZ coefXn [0 == _]ltn_eqF// mulr0 mulf_eq0 (negPf u1N0)=> /eqP. suff : ((p : int) ^+ 2 %| q`_0)%Z by rewrite (negPf Ndvd_pq0). have := c_neq0; rewrite q_eq coefM big_ord1. rewrite lead_coefM rmorphM mulf_eq0 negb_or => /andP[lpfN0 qfN0]. have pfN1 : size pf != 1%N by rewrite size_map_poly_id0. have pgN1 : size pg != 1%N by rewrite size_map_poly_id0. have /(dvdXn _ pgN1) /eqP : pg %| c *: 'X^n by rewrite -pfMpg dvdp_mull. have /(dvdXn _ pfN1) /eqP : pf %| c *: 'X^n by rewrite -pfMpg dvdp_mulr. by rewrite !coef_map// -!(dvdz_pcharf (pchar_Fp _))//; apply: dvdz_mul. Qed. (* Connecting rationals to the ring and field tactics *) Ltac rat_to_ring := rewrite -?[0%Q]/(0 : rat)%R -?[1%Q]/(1 : rat)%R -?[(_ - _)%Q]/(_ - _ : rat)%R -?[(_ / _)%Q]/(_ / _ : rat)%R -?[(_ + _)%Q]/(_ + _ : rat)%R -?[(_ * _)%Q]/(_ * _ : rat)%R -?[(- _)%Q]/(- _ : rat)%R -?[(_ ^-1)%Q]/(_ ^-1 : rat)%R /=. Ltac ring_to_rat := rewrite -?[0%R]/0%Q -?[1%R]/1%Q -?[(_ - _)%R]/(_ - _)%Q -?[(_ / _)%R]/(_ / _)%Q -?[(_ + _)%R]/(_ + _)%Q -?[(_ * _)%R]/(_ * _)%Q -?[(- _)%R]/(- _)%Q -?[(_ ^-1)%R]/(_ ^-1)%Q /=. (* Pretty printing or normal element of rat. *) Notation "[ 'rat' x // y ]" := (@Rat (x, y) _) (only printing) : ring_scope. (* For debugging purposes we provide the parsable version *) Notation "[ 'rat' x // y ]" := (@Rat (x : int, y : int) (fracq_subproof (x : int, y : int))) : ring_scope. (* A specialization of vm_compute rewrite rule for pattern _%:Q *) Lemma rat_vm_compute n (x : rat) : vm_compute_eq n%:Q x -> n%:Q = x. Proof. exact. Qed.
Defs.lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Group.Subgroup.Defs import Mathlib.GroupTheory.GroupAction.SubMulAction import Mathlib.Algebra.Group.Submonoid.Basic /-! # Submodules of a module In this file we define * `Submodule R M` : a subset of a `Module` `M` that contains zero and is closed with respect to addition and scalar multiplication. * `Subspace k M` : an abbreviation for `Submodule` assuming that `k` is a `Field`. ## Tags submodule, subspace, linear map -/ assert_not_exists DivisionRing open Function universe u'' u' u v w variable {G : Type u''} {S : Type u'} {R : Type u} {M : Type v} {ι : Type w} /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure Submodule (R : Type u) (M : Type v) [Semiring R] [AddCommMonoid M] [Module R M] : Type v extends AddSubmonoid M, SubMulAction R M /-- Reinterpret a `Submodule` as an `AddSubmonoid`. -/ add_decl_doc Submodule.toAddSubmonoid /-- Reinterpret a `Submodule` as a `SubMulAction`. -/ add_decl_doc Submodule.toSubMulAction namespace Submodule variable [Semiring R] [AddCommMonoid M] [Module R M] instance setLike : SetLike (Submodule R M) M where coe s := s.carrier coe_injective' p q h := by cases p; cases q; congr; exact SetLike.coe_injective' h initialize_simps_projections Submodule (carrier → coe, as_prefix coe) @[simp] lemma carrier_eq_coe (s : Submodule R M) : s.carrier = s := rfl /-- The actual `Submodule` obtained from an element of a `SMulMemClass` and `AddSubmonoidClass`. -/ @[simps] def ofClass {S R M : Type*} [Semiring R] [AddCommMonoid M] [Module R M] [SetLike S M] [AddSubmonoidClass S M] [SMulMemClass S R M] (s : S) : Submodule R M where carrier := s add_mem' := add_mem zero_mem' := zero_mem _ smul_mem' := SMulMemClass.smul_mem instance (priority := 100) : CanLift (Set M) (Submodule R M) (↑) (fun s ↦ 0 ∈ s ∧ (∀ {x y}, x ∈ s → y ∈ s → x + y ∈ s) ∧ ∀ (r : R) {x}, x ∈ s → r • x ∈ s) where prf s h := ⟨ { carrier := s zero_mem' := h.1 add_mem' := h.2.1 smul_mem' := h.2.2 }, rfl ⟩ instance addSubmonoidClass : AddSubmonoidClass (Submodule R M) M where zero_mem _ := AddSubmonoid.zero_mem' _ add_mem := AddSubsemigroup.add_mem' _ instance smulMemClass : SMulMemClass (Submodule R M) R M where smul_mem {s} c _ h := SubMulAction.smul_mem' s.toSubMulAction c h @[simp] theorem mem_toAddSubmonoid (p : Submodule R M) (x : M) : x ∈ p.toAddSubmonoid ↔ x ∈ p := Iff.rfl variable {p q : Submodule R M} @[simp] theorem mem_mk {S : AddSubmonoid M} {x : M} (h) : x ∈ (⟨S, h⟩ : Submodule R M) ↔ x ∈ S := Iff.rfl @[simp] theorem coe_set_mk (S : AddSubmonoid M) (h) : ((⟨S, h⟩ : Submodule R M) : Set M) = S := rfl @[simp] theorem eta (h) : ({p with smul_mem' := h} : Submodule R M) = p := rfl @[simp] theorem mk_le_mk {S S' : AddSubmonoid M} (h h') : (⟨S, h⟩ : Submodule R M) ≤ (⟨S', h'⟩ : Submodule R M) ↔ S ≤ S' := Iff.rfl @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := SetLike.ext h @[deprecated SetLike.coe_set_eq (since := "2025-04-20")] theorem carrier_inj : p.carrier = q.carrier ↔ p = q := (SetLike.coe_injective (A := Submodule R M)).eq_iff /-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ @[simps] protected def copy (p : Submodule R M) (s : Set M) (hs : s = ↑p) : Submodule R M where carrier := s zero_mem' := by simp [hs] add_mem' := hs.symm ▸ p.add_mem' smul_mem' := by simpa [hs] using p.smul_mem' theorem copy_eq (S : Submodule R M) (s : Set M) (hs : s = ↑S) : S.copy s hs = S := SetLike.coe_injective hs theorem toAddSubmonoid_injective : Injective (toAddSubmonoid : Submodule R M → AddSubmonoid M) := fun p q h => SetLike.ext'_iff.2 (show (p.toAddSubmonoid : Set M) = q from SetLike.ext'_iff.1 h) @[simp] theorem toAddSubmonoid_inj : p.toAddSubmonoid = q.toAddSubmonoid ↔ p = q := toAddSubmonoid_injective.eq_iff @[simp] theorem coe_toAddSubmonoid (p : Submodule R M) : (p.toAddSubmonoid : Set M) = p := rfl theorem toSubMulAction_injective : Injective (toSubMulAction : Submodule R M → SubMulAction R M) := fun p q h => SetLike.ext'_iff.2 (show (p.toSubMulAction : Set M) = q from SetLike.ext'_iff.1 h) theorem toSubMulAction_inj : p.toSubMulAction = q.toSubMulAction ↔ p = q := toSubMulAction_injective.eq_iff @[simp] theorem coe_toSubMulAction (p : Submodule R M) : (p.toSubMulAction : Set M) = p := rfl end Submodule namespace SMulMemClass variable [Semiring R] [AddCommMonoid M] [Module R M] {A : Type*} [SetLike A M] [AddSubmonoidClass A M] [SMulMemClass A R M] (S' : A) -- Prefer subclasses of `Module` over `SMulMemClass`. /-- A submodule of a `Module` is a `Module`. -/ instance (priority := 75) toModule : Module R S' := fast_instance% Subtype.coe_injective.module R (AddSubmonoidClass.subtype S') (SetLike.val_smul S') /-- This can't be an instance because Lean wouldn't know how to find `R`, but we can still use this to manually derive `Module` on specific types. -/ def toModule' (S R' R A : Type*) [Semiring R] [NonUnitalNonAssocSemiring A] [Module R A] [Semiring R'] [SMul R' R] [Module R' A] [IsScalarTower R' R A] [SetLike S A] [AddSubmonoidClass S A] [SMulMemClass S R A] (s : S) : Module R' s := haveI : SMulMemClass S R' A := SMulMemClass.ofIsScalarTower S R' R A SMulMemClass.toModule s end SMulMemClass namespace Submodule section AddCommMonoid variable [Semiring R] [AddCommMonoid M] -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variable {module_M : Module R M} variable {p q : Submodule R M} variable {r : R} {x y : M} variable (p) theorem mem_carrier : x ∈ p.carrier ↔ x ∈ (p : Set M) := Iff.rfl protected theorem zero_mem : (0 : M) ∈ p := zero_mem _ protected theorem add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := add_mem h₁ h₂ theorem smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h theorem smul_of_tower_mem [SMul S R] [SMul S M] [IsScalarTower S R M] (r : S) (h : x ∈ p) : r • x ∈ p := p.toSubMulAction.smul_of_tower_mem r h @[simp] theorem smul_mem_iff' [Group G] [MulAction G M] [SMul G R] [IsScalarTower G R M] (g : G) : g • x ∈ p ↔ x ∈ p := p.toSubMulAction.smul_mem_iff' g @[simp] lemma smul_mem_iff'' [Invertible r] : r • x ∈ p ↔ x ∈ p := by refine ⟨fun h ↦ ?_, p.smul_mem r⟩ rw [← invOf_smul_smul r x] exact p.smul_mem _ h lemma smul_mem_iff_of_isUnit (hr : IsUnit r) : r • x ∈ p ↔ x ∈ p := let _ : Invertible r := hr.invertible smul_mem_iff'' p instance add : Add p := ⟨fun x y => ⟨x.1 + y.1, add_mem x.2 y.2⟩⟩ instance zero : Zero p := ⟨⟨0, zero_mem _⟩⟩ instance inhabited : Inhabited p := ⟨0⟩ instance smul [SMul S R] [SMul S M] [IsScalarTower S R M] : SMul S p := ⟨fun c x => ⟨c • x.1, smul_of_tower_mem _ c x.2⟩⟩ instance isScalarTower [SMul S R] [SMul S M] [IsScalarTower S R M] : IsScalarTower S R p := p.toSubMulAction.isScalarTower instance isScalarTower' {S' : Type*} [SMul S R] [SMul S M] [SMul S' R] [SMul S' M] [SMul S S'] [IsScalarTower S' R M] [IsScalarTower S S' M] [IsScalarTower S R M] : IsScalarTower S S' p := p.toSubMulAction.isScalarTower' protected theorem nonempty : (p : Set M).Nonempty := ⟨0, p.zero_mem⟩ @[simp] theorem mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := Subtype.ext_iff_val variable {p} @[norm_cast] theorem coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := (SetLike.coe_eq_coe : (x : M) = (0 : p) ↔ x = 0) @[simp, norm_cast] theorem coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] theorem coe_zero : ((0 : p) : M) = 0 := rfl @[norm_cast] theorem coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • (x : M) := rfl @[simp, norm_cast] theorem coe_smul_of_tower [SMul S R] [SMul S M] [IsScalarTower S R M] (r : S) (x : p) : ((r • x : p) : M) = r • (x : M) := rfl @[norm_cast] theorem coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl theorem coe_mem (x : p) : (x : M) ∈ p := x.2 variable (p) instance addCommMonoid : AddCommMonoid p := fast_instance% { p.toAddSubmonoid.toAddCommMonoid with } instance isLeftCancelAdd [IsLeftCancelAdd M] : IsLeftCancelAdd p := p.toAddSubmonoid.isLeftCancelAdd instance isRightCancelAdd [IsRightCancelAdd M] : IsRightCancelAdd p := p.toAddSubmonoid.isRightCancelAdd instance isCancelAdd [IsCancelAdd M] : IsCancelAdd p where instance module' [Semiring S] [SMul S R] [Module S M] [IsScalarTower S R M] : Module S p := fast_instance% { (show MulAction S p from p.toSubMulAction.mulAction') with smul_zero := fun a => by ext; simp zero_smul := fun a => by ext; simp add_smul := fun a b x => by ext; simp [add_smul] smul_add := fun a x y => by ext; simp [smul_add] } instance module : Module R p := p.module' end AddCommMonoid section AddCommGroup variable [Ring R] [AddCommGroup M] variable {module_M : Module R M} variable (p p' : Submodule R M) variable {r : R} {x y : M} instance addSubgroupClass [Module R M] : AddSubgroupClass (Submodule R M) M := { Submodule.addSubmonoidClass with neg_mem := fun p {_} => p.toSubMulAction.neg_mem } protected theorem neg_mem (hx : x ∈ p) : -x ∈ p := neg_mem hx /-- Reinterpret a submodule as an additive subgroup. -/ def toAddSubgroup : AddSubgroup M := { p.toAddSubmonoid with neg_mem' := fun {_} => p.neg_mem } @[simp] theorem coe_toAddSubgroup : (p.toAddSubgroup : Set M) = p := rfl @[simp] theorem mem_toAddSubgroup : x ∈ p.toAddSubgroup ↔ x ∈ p := Iff.rfl theorem toAddSubgroup_injective : Injective (toAddSubgroup : Submodule R M → AddSubgroup M) | _, _, h => SetLike.ext (SetLike.ext_iff.1 h :) @[simp] theorem toAddSubgroup_inj : p.toAddSubgroup = p'.toAddSubgroup ↔ p = p' := toAddSubgroup_injective.eq_iff protected theorem sub_mem : x ∈ p → y ∈ p → x - y ∈ p := sub_mem protected theorem neg_mem_iff : -x ∈ p ↔ x ∈ p := neg_mem_iff protected theorem add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := add_mem_cancel_right protected theorem add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := add_mem_cancel_left protected theorem coe_neg (x : p) : ((-x : p) : M) = -x := NegMemClass.coe_neg _ protected theorem coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := AddSubgroupClass.coe_sub _ _ theorem sub_mem_iff_left (hy : y ∈ p) : x - y ∈ p ↔ x ∈ p := by rw [sub_eq_add_neg, p.add_mem_iff_left (p.neg_mem hy)] theorem sub_mem_iff_right (hx : x ∈ p) : x - y ∈ p ↔ y ∈ p := by rw [sub_eq_add_neg, p.add_mem_iff_right hx, p.neg_mem_iff] instance addCommGroup : AddCommGroup p := fast_instance% { p.toAddSubgroup.toAddCommGroup with } end AddCommGroup end Submodule namespace SubmoduleClass instance (priority := 75) module' {T : Type*} [Semiring R] [AddCommMonoid M] [Semiring S] [Module R M] [SMul S R] [Module S M] [IsScalarTower S R M] [SetLike T M] [AddSubmonoidClass T M] [SMulMemClass T R M] (t : T) : Module S t where one_smul _ := by ext; simp mul_smul _ _ _ := by ext; simp [mul_smul] smul_zero _ := by ext; simp zero_smul _ := by ext; simp add_smul _ _ _ := by ext; simp [add_smul] smul_add _ _ _ := by ext; simp [smul_add] instance (priority := 75) module [Semiring R] [AddCommMonoid M] [Module R M] [SetLike S M] [AddSubmonoidClass S M] [SMulMemClass S R M] (s : S) : Module R s := module' s end SubmoduleClass
Basic.lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import Mathlib.RingTheory.IntegralClosure.IsIntegral.Basic /-! # Minimal polynomials This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`, under the assumption that x is integral over `A`, and derives some basic properties such as irreducibility under the assumption `B` is a domain. -/ open Polynomial Set Function variable {A B B' : Type*} section MinPolyDef variable (A) [CommRing A] [Ring B] [Algebra A B] open scoped Classical in /-- Suppose `x : B`, where `B` is an `A`-algebra. The minimal polynomial `minpoly A x` of `x` is a monic polynomial with coefficients in `A` of smallest degree that has `x` as its root, if such exists (`IsIntegral A x`) or zero otherwise. For example, if `V` is a `𝕜`-vector space for some field `𝕜` and `f : V →ₗ[𝕜] V` then the minimal polynomial of `f` is `minpoly 𝕜 f`. -/ @[stacks 09GM] noncomputable def minpoly (x : B) : A[X] := if hx : IsIntegral A x then degree_lt_wf.min _ hx else 0 end MinPolyDef namespace minpoly section Ring variable [CommRing A] [Ring B] [Ring B'] [Algebra A B] [Algebra A B'] variable {x : B} /-- A minimal polynomial is monic. -/ theorem monic (hx : IsIntegral A x) : Monic (minpoly A x) := by delta minpoly rw [dif_pos hx] exact (degree_lt_wf.min_mem _ hx).1 /-- A minimal polynomial is nonzero. -/ theorem ne_zero [Nontrivial A] (hx : IsIntegral A x) : minpoly A x ≠ 0 := (monic hx).ne_zero theorem eq_zero (hx : ¬IsIntegral A x) : minpoly A x = 0 := dif_neg hx theorem ne_zero_iff [Nontrivial A] : minpoly A x ≠ 0 ↔ IsIntegral A x := ⟨fun h => of_not_not <| eq_zero.mt h, ne_zero⟩ theorem algHom_eq (f : B →ₐ[A] B') (hf : Function.Injective f) (x : B) : minpoly A (f x) = minpoly A x := by classical simp_rw [minpoly, isIntegral_algHom_iff _ hf, ← Polynomial.aeval_def, aeval_algHom, AlgHom.comp_apply, _root_.map_eq_zero_iff f hf] theorem algebraMap_eq {B} [CommRing B] [Algebra A B] [Algebra B B'] [IsScalarTower A B B'] (h : Function.Injective (algebraMap B B')) (x : B) : minpoly A (algebraMap B B' x) = minpoly A x := algHom_eq (IsScalarTower.toAlgHom A B B') h x @[simp] theorem algEquiv_eq (f : B ≃ₐ[A] B') (x : B) : minpoly A (f x) = minpoly A x := algHom_eq (f : B →ₐ[A] B') f.injective x variable (A x) /-- An element is a root of its minimal polynomial. -/ @[simp] theorem aeval : aeval x (minpoly A x) = 0 := by delta minpoly split_ifs with hx · exact (degree_lt_wf.min_mem _ hx).2 · exact aeval_zero _ /-- Given any `f : B →ₐ[A] B'` and any `x : L`, the minimal polynomial of `x` vanishes at `f x`. -/ @[simp] theorem aeval_algHom (f : B →ₐ[A] B') (x : B) : (Polynomial.aeval (f x)) (minpoly A x) = 0 := by rw [Polynomial.aeval_algHom, AlgHom.coe_comp, comp_apply, aeval, map_zero] /-- A minimal polynomial is not `1`. -/ theorem ne_one [Nontrivial B] : minpoly A x ≠ 1 := by intro h refine (one_ne_zero : (1 : B) ≠ 0) ?_ simpa using congr_arg (Polynomial.aeval x) h theorem map_ne_one [Nontrivial B] {R : Type*} [Semiring R] [Nontrivial R] (f : A →+* R) : (minpoly A x).map f ≠ 1 := by by_cases hx : IsIntegral A x · exact mt ((monic hx).eq_one_of_map_eq_one f) (ne_one A x) · rw [eq_zero hx, Polynomial.map_zero] exact zero_ne_one /-- A minimal polynomial is not a unit. -/ theorem not_isUnit [Nontrivial B] : ¬IsUnit (minpoly A x) := by haveI : Nontrivial A := (algebraMap A B).domain_nontrivial by_cases hx : IsIntegral A x · exact mt (monic hx).eq_one_of_isUnit (ne_one A x) · rw [eq_zero hx] exact not_isUnit_zero theorem mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebraMap A B).range := by have h : IsIntegral A x := by by_contra h rw [eq_zero h, degree_zero, ← WithBot.coe_one] at hx exact ne_of_lt (show ⊥ < ↑1 from WithBot.bot_lt_coe 1) hx have key := minpoly.aeval A x rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leadingCoeff, C_1, one_mul, aeval_add, aeval_C, aeval_X, ← eq_neg_iff_add_eq_zero, ← RingHom.map_neg] at key exact ⟨-(minpoly A x).coeff 0, key.symm⟩ /-- The defining property of the minimal polynomial of an element `x`: it is the monic polynomial with smallest degree that has `x` as its root. -/ theorem min {p : A[X]} (pmonic : p.Monic) (hp : Polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := by delta minpoly; split_ifs with hx · exact le_of_not_gt (degree_lt_wf.not_lt_min _ hx ⟨pmonic, hp⟩) · simp only [degree_zero, bot_le] theorem unique' {p : A[X]} (hm : p.Monic) (hp : Polynomial.aeval x p = 0) (hl : ∀ q : A[X], degree q < degree p → q = 0 ∨ Polynomial.aeval x q ≠ 0) : p = minpoly A x := by nontriviality A have hx : IsIntegral A x := ⟨p, hm, hp⟩ obtain h | h := hl _ ((minpoly A x).degree_modByMonic_lt hm) swap · exact (h <| (aeval_modByMonic_eq_self_of_root hm hp).trans <| aeval A x).elim obtain ⟨r, hr⟩ := (modByMonic_eq_zero_iff_dvd hm).1 h rw [hr] have hlead := congr_arg leadingCoeff hr rw [mul_comm, leadingCoeff_mul_monic hm, (monic hx).leadingCoeff] at hlead have : natDegree r ≤ 0 := by have hr0 : r ≠ 0 := by rintro rfl exact ne_zero hx (mul_zero p ▸ hr) apply_fun natDegree at hr rw [hm.natDegree_mul' hr0] at hr apply Nat.le_of_add_le_add_left rw [add_zero] exact hr.symm.trans_le (natDegree_le_natDegree <| min A x hm hp) rw [eq_C_of_natDegree_le_zero this, ← Nat.eq_zero_of_le_zero this, ← leadingCoeff, ← hlead, C_1, mul_one] open Polynomial in /-- If a monic polynomial `p : A[X]` of degree `n` annihilates an element `x` in an `A`-algebra `B`, such that `{xⁱ | 0 ≤ i < n} is linearly independent over `A`, then `p` is the minimal polynomial of `x` over `A`. -/ theorem eq_of_linearIndependent {p : A[X]} (monic : p.Monic) (hp0 : p.aeval x = 0) (n : ℕ) (hpn : p.degree = n) (ind : LinearIndependent A fun i : Fin n ↦ x ^ i.val) : minpoly A x = p := .symm <| unique' _ _ monic hp0 fun q lt ↦ or_iff_not_imp_left.mpr fun ne hq ↦ ne <| ext fun i ↦ by rw [q.as_sum_range' _ ((natDegree_lt_iff_degree_lt ne).mpr (hpn ▸ lt))] at hq obtain lt | le := lt_or_ge i n · simpa using Fintype.linearIndependent_iff.mp ind (q.coeff ·) (by simpa [Finset.sum_range, Algebra.smul_def] using hq) ⟨i, lt⟩ · exact coeff_eq_zero_of_degree_lt ((hpn ▸ lt).trans_le <| WithBot.coe_le_coe.mpr le) @[nontriviality] theorem subsingleton [Subsingleton B] : minpoly A x = 1 := by nontriviality A have := minpoly.min A x monic_one (Subsingleton.elim _ _) rw [degree_one] at this rcases le_or_gt (minpoly A x).degree 0 with h | h · rwa [(monic ⟨1, monic_one, by simp [eq_iff_true_of_subsingleton]⟩ : (minpoly A x).Monic).degree_le_zero_iff_eq_one] at h · exact (this.not_gt h).elim end Ring section CommRing variable [CommRing A] section Ring variable [Ring B] [Algebra A B] variable {x : B} /-- The degree of a minimal polynomial, as a natural number, is positive. -/ theorem natDegree_pos [Nontrivial B] (hx : IsIntegral A x) : 0 < natDegree (minpoly A x) := by rw [pos_iff_ne_zero] intro ndeg_eq_zero have eq_one : minpoly A x = 1 := by rw [eq_C_of_natDegree_eq_zero ndeg_eq_zero] convert C_1 (R := A) simpa only [ndeg_eq_zero.symm] using (monic hx).leadingCoeff simpa only [eq_one, map_one, one_ne_zero] using aeval A x /-- The degree of a minimal polynomial is positive. -/ theorem degree_pos [Nontrivial B] (hx : IsIntegral A x) : 0 < degree (minpoly A x) := natDegree_pos_iff_degree_pos.mp (natDegree_pos hx) section variable [Nontrivial B] open Polynomial in theorem degree_eq_one_iff : (minpoly A x).degree = 1 ↔ x ∈ (algebraMap A B).range := by refine ⟨minpoly.mem_range_of_degree_eq_one _ _, ?_⟩ rintro ⟨x, rfl⟩ haveI := Module.nontrivial A B exact (degree_X_sub_C x ▸ minpoly.min A (algebraMap A B x) (monic_X_sub_C x) (by simp)).antisymm (Nat.WithBot.add_one_le_of_lt <| minpoly.degree_pos isIntegral_algebraMap) theorem natDegree_eq_one_iff : (minpoly A x).natDegree = 1 ↔ x ∈ (algebraMap A B).range := by rw [← Polynomial.degree_eq_iff_natDegree_eq_of_pos zero_lt_one] exact degree_eq_one_iff theorem two_le_natDegree_iff (int : IsIntegral A x) : 2 ≤ (minpoly A x).natDegree ↔ x ∉ (algebraMap A B).range := by rw [iff_not_comm, ← natDegree_eq_one_iff, not_le] exact ⟨fun h ↦ h.trans_lt one_lt_two, fun h ↦ by linarith only [minpoly.natDegree_pos int, h]⟩ theorem two_le_natDegree_subalgebra {B} [CommRing B] [Algebra A B] [Nontrivial B] {S : Subalgebra A B} {x : B} (int : IsIntegral S x) : 2 ≤ (minpoly S x).natDegree ↔ x ∉ S := by rw [two_le_natDegree_iff int, Iff.not] apply Set.ext_iff.mp Subtype.range_val_subtype end /-- If `B/A` is an injective ring extension, and `a` is an element of `A`, then the minimal polynomial of `algebraMap A B a` is `X - C a`. -/ theorem eq_X_sub_C_of_algebraMap_inj (a : A) (hf : Function.Injective (algebraMap A B)) : minpoly A (algebraMap A B a) = X - C a := by nontriviality A refine (unique' A _ (monic_X_sub_C a) ?_ ?_).symm · rw [map_sub, aeval_C, aeval_X, sub_self] simp_rw [or_iff_not_imp_left] intro q hl h0 rw [← natDegree_lt_natDegree_iff h0, natDegree_X_sub_C, Nat.lt_one_iff] at hl rw [eq_C_of_natDegree_eq_zero hl] at h0 ⊢ rwa [aeval_C, map_ne_zero_iff _ hf, ← C_ne_zero] end Ring section IsDomain variable [Ring B] [Algebra A B] variable {x : B} /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ theorem aeval_ne_zero_of_dvdNotUnit_minpoly {a : A[X]} (hx : IsIntegral A x) (hamonic : a.Monic) (hdvd : DvdNotUnit a (minpoly A x)) : Polynomial.aeval x a ≠ 0 := by refine fun ha => (min A x hamonic ha).not_gt (degree_lt_degree ?_) obtain ⟨_, c, hu, he⟩ := hdvd have hcm := hamonic.of_mul_monic_left (he.subst <| monic hx) rw [he, hamonic.natDegree_mul hcm] -- TODO: port Nat.lt_add_of_zero_lt_left from lean3 core apply lt_add_of_pos_right refine (lt_of_not_ge fun h => hu ?_) rw [eq_C_of_natDegree_le_zero h, ← Nat.eq_zero_of_le_zero h, ← leadingCoeff, hcm.leadingCoeff, C_1] exact isUnit_one variable [IsDomain A] [IsDomain B] /-- A minimal polynomial is irreducible. -/ theorem irreducible (hx : IsIntegral A x) : Irreducible (minpoly A x) := by refine (irreducible_of_monic (monic hx) <| ne_one A x).2 fun f g hf hg he => ?_ rw [← hf.isUnit_iff, ← hg.isUnit_iff] by_contra! h have heval := congr_arg (Polynomial.aeval x) he rw [aeval A x, aeval_mul, mul_eq_zero] at heval rcases heval with heval | heval · exact aeval_ne_zero_of_dvdNotUnit_minpoly hx hf ⟨hf.ne_zero, g, h.2, he.symm⟩ heval · refine aeval_ne_zero_of_dvdNotUnit_minpoly hx hg ⟨hg.ne_zero, f, h.1, ?_⟩ heval rw [mul_comm, he] end IsDomain end CommRing end minpoly
Module.lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Yury Kudryashov, Frédéric Dupuis -/ import Mathlib.Topology.Algebra.InfiniteSum.Constructions import Mathlib.Topology.Algebra.Module.Equiv /-! # Infinite sums in topological vector spaces -/ variable {α β γ δ : Type*} open Filter Finset Function section ConstSMul variable [Monoid γ] [TopologicalSpace α] [AddCommMonoid α] [DistribMulAction γ α] [ContinuousConstSMul γ α] {f : β → α} theorem HasSum.const_smul {a : α} (b : γ) (hf : HasSum f a) : HasSum (fun i ↦ b • f i) (b • a) := hf.map (DistribMulAction.toAddMonoidHom α _) <| continuous_const_smul _ theorem Summable.const_smul (b : γ) (hf : Summable f) : Summable fun i ↦ b • f i := (hf.hasSum.const_smul _).summable /-- Infinite sums commute with scalar multiplication. Version for scalars living in a `Monoid`, but requiring a summability hypothesis. -/ protected theorem Summable.tsum_const_smul [T2Space α] (b : γ) (hf : Summable f) : ∑' i, b • f i = b • ∑' i, f i := (hf.hasSum.const_smul _).tsum_eq @[deprecated (since := "2025-04-12")] alias tsum_const_smul := Summable.tsum_const_smul /-- Infinite sums commute with scalar multiplication. Version for scalars living in a `Group`, but not requiring any summability hypothesis. -/ lemma tsum_const_smul' {γ : Type*} [Group γ] [DistribMulAction γ α] [ContinuousConstSMul γ α] [T2Space α] (g : γ) : ∑' (i : β), g • f i = g • ∑' (i : β), f i := by by_cases hf : Summable f · exact hf.tsum_const_smul g rw [tsum_eq_zero_of_not_summable hf] simp only [smul_zero] let mul_g : α ≃+ α := DistribMulAction.toAddEquiv α g apply tsum_eq_zero_of_not_summable change ¬ Summable (mul_g ∘ f) rwa [Summable.map_iff_of_equiv mul_g] · apply continuous_const_smul · apply continuous_const_smul /-- Infinite sums commute with scalar multiplication. Version for scalars living in a `DivisionRing`; no summability hypothesis. This could be made to work for a `[GroupWithZero γ]` if there was such a thing as `DistribMulActionWithZero`. -/ lemma tsum_const_smul'' {γ : Type*} [DivisionSemiring γ] [Module γ α] [ContinuousConstSMul γ α] [T2Space α] (g : γ) : ∑' (i : β), g • f i = g • ∑' (i : β), f i := by rcases eq_or_ne g 0 with rfl | hg · simp · exact tsum_const_smul' (Units.mk0 g hg) end ConstSMul variable {ι κ R R₂ M M₂ : Type*} section SMulConst variable [Semiring R] [TopologicalSpace R] [TopologicalSpace M] [AddCommMonoid M] [Module R M] [ContinuousSMul R M] {f : ι → R} theorem HasSum.smul_const {r : R} (hf : HasSum f r) (a : M) : HasSum (fun z ↦ f z • a) (r • a) := hf.map ((smulAddHom R M).flip a) (continuous_id.smul continuous_const) theorem Summable.smul_const (hf : Summable f) (a : M) : Summable fun z ↦ f z • a := (hf.hasSum.smul_const _).summable protected theorem Summable.tsum_smul_const [T2Space M] (hf : Summable f) (a : M) : ∑' z, f z • a = (∑' z, f z) • a := (hf.hasSum.smul_const _).tsum_eq @[deprecated (since := "2025-04-12")] alias tsum_smul_const := Summable.tsum_smul_const end SMulConst /-! Note we cannot derive the `mul` lemmas from these `smul` lemmas, as the `mul` versions do not require associativity, but `Module` does. -/ section tsum_smul_tsum variable [Semiring R] [AddCommMonoid M] [Module R M] variable [TopologicalSpace R] [TopologicalSpace M] [T3Space M] variable [ContinuousAdd M] [ContinuousSMul R M] variable {f : ι → R} {g : κ → M} {s : R} {t u : M} theorem HasSum.smul_eq (hf : HasSum f s) (hg : HasSum g t) (hfg : HasSum (fun x : ι × κ ↦ f x.1 • g x.2) u) : s • t = u := have key₁ : HasSum (fun i ↦ f i • t) (s • t) := hf.smul_const t have this : ∀ i : ι, HasSum (fun c : κ ↦ f i • g c) (f i • t) := fun i ↦ hg.const_smul (f i) have key₂ : HasSum (fun i ↦ f i • t) u := HasSum.prod_fiberwise hfg this key₁.unique key₂ theorem HasSum.smul (hf : HasSum f s) (hg : HasSum g t) (hfg : Summable fun x : ι × κ ↦ f x.1 • g x.2) : HasSum (fun x : ι × κ ↦ f x.1 • g x.2) (s • t) := let ⟨_u, hu⟩ := hfg (hf.smul_eq hg hu).symm ▸ hu /-- Scalar product of two infinites sums indexed by arbitrary types. -/ theorem tsum_smul_tsum (hf : Summable f) (hg : Summable g) (hfg : Summable fun x : ι × κ ↦ f x.1 • g x.2) : ((∑' x, f x) • ∑' y, g y) = ∑' z : ι × κ, f z.1 • g z.2 := hf.hasSum.smul_eq hg.hasSum hfg.hasSum end tsum_smul_tsum section HasSum -- Results in this section hold for continuous additive monoid homomorphisms or equivalences but we -- don't have bundled continuous additive homomorphisms. variable [Semiring R] [Semiring R₂] [AddCommMonoid M] [Module R M] [AddCommMonoid M₂] [Module R₂ M₂] [TopologicalSpace M] [TopologicalSpace M₂] {σ : R →+* R₂} {σ' : R₂ →+* R} [RingHomInvPair σ σ'] [RingHomInvPair σ' σ] /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected theorem ContinuousLinearMap.hasSum {f : ι → M} (φ : M →SL[σ] M₂) {x : M} (hf : HasSum f x) : HasSum (fun b : ι ↦ φ (f b)) (φ x) := by simpa only using hf.map φ.toLinearMap.toAddMonoidHom φ.continuous alias HasSum.mapL := ContinuousLinearMap.hasSum protected theorem ContinuousLinearMap.summable {f : ι → M} (φ : M →SL[σ] M₂) (hf : Summable f) : Summable fun b : ι ↦ φ (f b) := (hf.hasSum.mapL φ).summable alias Summable.mapL := ContinuousLinearMap.summable protected theorem ContinuousLinearMap.map_tsum [T2Space M₂] {f : ι → M} (φ : M →SL[σ] M₂) (hf : Summable f) : φ (∑' z, f z) = ∑' z, φ (f z) := (hf.hasSum.mapL φ).tsum_eq.symm /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected theorem ContinuousLinearEquiv.hasSum {f : ι → M} (e : M ≃SL[σ] M₂) {y : M₂} : HasSum (fun b : ι ↦ e (f b)) y ↔ HasSum f (e.symm y) := ⟨fun h ↦ by simpa only [e.symm.coe_coe, e.symm_apply_apply] using h.mapL (e.symm : M₂ →SL[σ'] M), fun h ↦ by simpa only [e.coe_coe, e.apply_symm_apply] using (e : M →SL[σ] M₂).hasSum h⟩ /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected theorem ContinuousLinearEquiv.hasSum' {f : ι → M} (e : M ≃SL[σ] M₂) {x : M} : HasSum (fun b : ι ↦ e (f b)) (e x) ↔ HasSum f x := by rw [e.hasSum, ContinuousLinearEquiv.symm_apply_apply] protected theorem ContinuousLinearEquiv.summable {f : ι → M} (e : M ≃SL[σ] M₂) : (Summable fun b : ι ↦ e (f b)) ↔ Summable f := ⟨fun hf ↦ (e.hasSum.1 hf.hasSum).summable, (e : M →SL[σ] M₂).summable⟩ theorem ContinuousLinearEquiv.tsum_eq_iff [T2Space M] [T2Space M₂] {f : ι → M} (e : M ≃SL[σ] M₂) {y : M₂} : (∑' z, e (f z)) = y ↔ ∑' z, f z = e.symm y := by by_cases hf : Summable f · exact ⟨fun h ↦ (e.hasSum.mp ((e.summable.mpr hf).hasSum_iff.mpr h)).tsum_eq, fun h ↦ (e.hasSum.mpr (hf.hasSum_iff.mpr h)).tsum_eq⟩ · have hf' : ¬Summable fun z ↦ e (f z) := fun h ↦ hf (e.summable.mp h) rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable hf'] refine ⟨?_, fun H ↦ ?_⟩ · rintro rfl simp · simpa using congr_arg (fun z ↦ e z) H protected theorem ContinuousLinearEquiv.map_tsum [T2Space M] [T2Space M₂] {f : ι → M} (e : M ≃SL[σ] M₂) : e (∑' z, f z) = ∑' z, e (f z) := by refine symm (e.tsum_eq_iff.mpr ?_) rw [e.symm_apply_apply _] end HasSum section automorphize variable {M : Type*} [TopologicalSpace M] [AddCommMonoid M] [T2Space M] {R : Type*} [DivisionRing R] [Module R M] [ContinuousConstSMul R M] /-- Given a group `α` acting on a type `β`, and a function `f : β → M`, we "automorphize" `f` to a function `β ⧸ α → M` by summing over `α` orbits, `b ↦ ∑' (a : α), f(a • b)`. -/ @[to_additive /-- Given an additive group `α` acting on a type `β`, and a function `f : β → M`, we automorphize `f` to a function `β ⧸ α → M` by summing over `α` orbits, `b ↦ ∑' (a : α), f(a • b)`. -/] noncomputable def MulAction.automorphize [Group α] [MulAction α β] (f : β → M) : Quotient (MulAction.orbitRel α β) → M := by refine @Quotient.lift _ _ (_) (fun b ↦ ∑' (a : α), f (a • b)) ?_ intro b₁ b₂ ⟨a, (ha : a • b₂ = b₁)⟩ simp only rw [← ha] convert (Equiv.mulRight a).tsum_eq (fun a' ↦ f (a' • b₂)) using 1 simp only [Equiv.coe_mulRight] congr ext congr 1 simp only [mul_smul] -- we can't use `to_additive`, because it tries to translate `•` into `+ᵥ` /-- Automorphization of a function into an `R`-`Module` distributes, that is, commutes with the `R`-scalar multiplication. -/ lemma MulAction.automorphize_smul_left [Group α] [MulAction α β] (f : β → M) (g : Quotient (MulAction.orbitRel α β) → R) : MulAction.automorphize ((g ∘ (@Quotient.mk' _ (_))) • f) = g • (MulAction.automorphize f : Quotient (MulAction.orbitRel α β) → M) := by ext x apply @Quotient.inductionOn' β (MulAction.orbitRel α β) _ x _ intro b simp only [automorphize, Pi.smul_apply', comp_apply] set π : β → Quotient (MulAction.orbitRel α β) := Quotient.mk (MulAction.orbitRel α β) have H₁ : ∀ a : α, π (a • b) = π b := by intro a apply (@Quotient.eq _ (MulAction.orbitRel α β) (a • b) b).mpr use a change ∑' a : α, g (π (a • b)) • f (a • b) = g (π b) • ∑' a : α, f (a • b) simp_rw [H₁] exact tsum_const_smul'' _ /-- Automorphization of a function into an `R`-`Module` distributes, that is, commutes with the `R`-scalar multiplication. -/ lemma AddAction.automorphize_smul_left [AddGroup α] [AddAction α β] (f : β → M) (g : Quotient (AddAction.orbitRel α β) → R) : AddAction.automorphize ((g ∘ (@Quotient.mk' _ (_))) • f) = g • (AddAction.automorphize f : Quotient (AddAction.orbitRel α β) → M) := by ext x apply @Quotient.inductionOn' β (AddAction.orbitRel α β) _ x _ intro b simp only [automorphize, Pi.smul_apply', comp_apply] set π : β → Quotient (AddAction.orbitRel α β) := Quotient.mk (AddAction.orbitRel α β) have H₁ : ∀ a : α, π (a +ᵥ b) = π b := by intro a apply (@Quotient.eq _ (AddAction.orbitRel α β) (a +ᵥ b) b).mpr use a change ∑' a : α, g (π (a +ᵥ b)) • f (a +ᵥ b) = g (π b) • ∑' a : α, f (a +ᵥ b) simp_rw [H₁] exact tsum_const_smul'' _ section variable {G : Type*} [Group G] {Γ : Subgroup G} /-- Given a subgroup `Γ` of a group `G`, and a function `f : G → M`, we "automorphize" `f` to a function `G ⧸ Γ → M` by summing over `Γ` orbits, `g ↦ ∑' (γ : Γ), f(γ • g)`. -/ @[to_additive /-- Given a subgroup `Γ` of an additive group `G`, and a function `f : G → M`, we automorphize `f` to a function `G ⧸ Γ → M` by summing over `Γ` orbits, `g ↦ ∑' (γ : Γ), f(γ • g)`. -/] noncomputable def QuotientGroup.automorphize (f : G → M) : G ⧸ Γ → M := MulAction.automorphize f /-- Automorphization of a function into an `R`-`Module` distributes, that is, commutes with the `R`-scalar multiplication. -/ lemma QuotientGroup.automorphize_smul_left (f : G → M) (g : G ⧸ Γ → R) : (QuotientGroup.automorphize ((g ∘ (@Quotient.mk' _ (_)) : G → R) • f) : G ⧸ Γ → M) = g • (QuotientGroup.automorphize f : G ⧸ Γ → M) := MulAction.automorphize_smul_left f g end section variable {G : Type*} [AddGroup G] {Γ : AddSubgroup G} /-- Automorphization of a function into an `R`-`Module` distributes, that is, commutes with the `R`-scalar multiplication. -/ lemma QuotientAddGroup.automorphize_smul_left (f : G → M) (g : G ⧸ Γ → R) : QuotientAddGroup.automorphize ((g ∘ (@Quotient.mk' _ (_))) • f) = g • (QuotientAddGroup.automorphize f : G ⧸ Γ → M) := AddAction.automorphize_smul_left f g end end automorphize
End.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.Group.Action.Faithful import Mathlib.Algebra.Order.Group.End import Mathlib.Order.RelIso.Basic /-! # Tautological action by relation automorphisms -/ assert_not_exists MonoidWithZero namespace RelHom variable {α : Type*} {r : α → α → Prop} /-- The tautological action by `r →r r` on `α`. -/ instance applyMulAction : MulAction (r →r r) α where smul := (⇑) one_smul _ := rfl mul_smul _ _ _ := rfl @[simp] lemma smul_def (f : r →r r) (a : α) : f • a = f a := rfl instance apply_faithfulSMul : FaithfulSMul (r →r r) α where eq_of_smul_eq_smul h := RelHom.ext h end RelHom namespace RelEmbedding variable {α : Type*} {r : α → α → Prop} /-- The tautological action by `r ↪r r` on `α`. -/ instance applyMulAction : MulAction (r ↪r r) α where smul := (⇑) one_smul _ := rfl mul_smul _ _ _ := rfl @[simp] lemma smul_def (f : r ↪r r) (a : α) : f • a = f a := rfl instance apply_faithfulSMul : FaithfulSMul (r ↪r r) α where eq_of_smul_eq_smul h := ext h end RelEmbedding namespace RelIso variable {α : Type*} {r : α → α → Prop} /-- The tautological action by `r ≃r r` on `α`. -/ instance applyMulAction : MulAction (r ≃r r) α where smul := (⇑) one_smul _ := rfl mul_smul _ _ _ := rfl @[simp] lemma smul_def (f : r ≃r r) (a : α) : f • a = f a := rfl instance apply_faithfulSMul : FaithfulSMul (r ≃r r) α where eq_of_smul_eq_smul h := RelIso.ext h end RelIso
CondDistrib.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.Probability.Kernel.Disintegration.Unique import Mathlib.Probability.Notation /-! # Regular conditional probability distribution We define the regular conditional probability distribution of `Y : α → Ω` given `X : α → β`, where `Ω` is a standard Borel space. This is a `Kernel β Ω` such that for almost all `a`, `condDistrib` evaluated at `X a` and a measurable set `s` is equal to the conditional expectation `μ⟦Y ⁻¹' s | mβ.comap X⟧` evaluated at `a`. `μ⟦Y ⁻¹' s | mβ.comap X⟧` maps a measurable set `s` to a function `α → ℝ≥0∞`, and for all `s` that map is unique up to a `μ`-null set. For all `a`, the map from sets to `ℝ≥0∞` that we obtain that way verifies some of the properties of a measure, but in general the fact that the `μ`-null set depends on `s` can prevent us from finding versions of the conditional expectation that combine into a true measure. The standard Borel space assumption on `Ω` allows us to do so. The case `Y = X = id` is developed in more detail in `Probability/Kernel/Condexp.lean`: here `X` is understood as a map from `Ω` with a sub-σ-algebra `m` to `Ω` with its default σ-algebra and the conditional distribution defines a kernel associated with the conditional expectation with respect to `m`. ## Main definitions * `condDistrib Y X μ`: regular conditional probability distribution of `Y : α → Ω` given `X : α → β`, where `Ω` is a standard Borel space. ## Main statements * `condDistrib_ae_eq_condExp`: for almost all `a`, `condDistrib` evaluated at `X a` and a measurable set `s` is equal to the conditional expectation `μ⟦Y ⁻¹' s | mβ.comap X⟧ a`. * `condExp_prod_ae_eq_integral_condDistrib`: the conditional expectation `μ[(fun a => f (X a, Y a)) | X; mβ]` is almost everywhere equal to the integral `∫ y, f (X a, y) ∂(condDistrib Y X μ (X a))`. -/ open MeasureTheory Set Filter TopologicalSpace open scoped ENNReal MeasureTheory ProbabilityTheory namespace ProbabilityTheory variable {α β Ω F : Type*} [MeasurableSpace Ω] [StandardBorelSpace Ω] [Nonempty Ω] [NormedAddCommGroup F] {mα : MeasurableSpace α} {μ : Measure α} [IsFiniteMeasure μ] {X : α → β} {Y : α → Ω} /-- **Regular conditional probability distribution**: kernel associated with the conditional expectation of `Y` given `X`. For almost all `a`, `condDistrib Y X μ` evaluated at `X a` and a measurable set `s` is equal to the conditional expectation `μ⟦Y ⁻¹' s | mβ.comap X⟧ a`. It also satisfies the equality `μ[(fun a => f (X a, Y a)) | mβ.comap X] =ᵐ[μ] fun a => ∫ y, f (X a, y) ∂(condDistrib Y X μ (X a))` for all integrable functions `f`. -/ noncomputable irreducible_def condDistrib {_ : MeasurableSpace α} [MeasurableSpace β] (Y : α → Ω) (X : α → β) (μ : Measure α) [IsFiniteMeasure μ] : Kernel β Ω := (μ.map fun a => (X a, Y a)).condKernel instance [MeasurableSpace β] : IsMarkovKernel (condDistrib Y X μ) := by rw [condDistrib]; infer_instance variable {mβ : MeasurableSpace β} {s : Set Ω} {t : Set β} {f : β × Ω → F} /-- If the singleton `{x}` has non-zero mass for `μ.map X`, then for all `s : Set Ω`, `condDistrib Y X μ x s = (μ.map X {x})⁻¹ * μ.map (fun a => (X a, Y a)) ({x} ×ˢ s)` . -/ lemma condDistrib_apply_of_ne_zero [MeasurableSingletonClass β] (hY : Measurable Y) (x : β) (hX : μ.map X {x} ≠ 0) (s : Set Ω) : condDistrib Y X μ x s = (μ.map X {x})⁻¹ * μ.map (fun a => (X a, Y a)) ({x} ×ˢ s) := by rw [condDistrib, Measure.condKernel_apply_of_ne_zero _ s] · rw [Measure.fst_map_prodMk hY] · rwa [Measure.fst_map_prodMk hY] lemma compProd_map_condDistrib (hY : AEMeasurable Y μ) : (μ.map X) ⊗ₘ condDistrib Y X μ = μ.map fun a ↦ (X a, Y a) := by rw [condDistrib, ← Measure.fst_map_prodMk₀ hY, Measure.disintegrate] section Measurability theorem measurable_condDistrib (hs : MeasurableSet s) : Measurable[mβ.comap X] fun a => condDistrib Y X μ (X a) s := (Kernel.measurable_coe _ hs).comp (Measurable.of_comap_le le_rfl) theorem _root_.MeasureTheory.AEStronglyMeasurable.ae_integrable_condDistrib_map_iff (hY : AEMeasurable Y μ) (hf : AEStronglyMeasurable f (μ.map fun a => (X a, Y a))) : (∀ᵐ a ∂μ.map X, Integrable (fun ω => f (a, ω)) (condDistrib Y X μ a)) ∧ Integrable (fun a => ∫ ω, ‖f (a, ω)‖ ∂condDistrib Y X μ a) (μ.map X) ↔ Integrable f (μ.map fun a => (X a, Y a)) := by rw [condDistrib, ← hf.ae_integrable_condKernel_iff, Measure.fst_map_prodMk₀ hY] variable [NormedSpace ℝ F] theorem _root_.MeasureTheory.StronglyMeasurable.integral_condDistrib (hf : StronglyMeasurable f) : StronglyMeasurable (fun x ↦ ∫ y, f (x, y) ∂condDistrib Y X μ x) := by rw [condDistrib]; exact hf.integral_kernel_prod_right' theorem _root_.MeasureTheory.AEStronglyMeasurable.integral_condDistrib_map (hY : AEMeasurable Y μ) (hf : AEStronglyMeasurable f (μ.map fun a => (X a, Y a))) : AEStronglyMeasurable (fun x => ∫ y, f (x, y) ∂condDistrib Y X μ x) (μ.map X) := by rw [← Measure.fst_map_prodMk₀ hY, condDistrib]; exact hf.integral_condKernel theorem _root_.MeasureTheory.AEStronglyMeasurable.integral_condDistrib (hX : AEMeasurable X μ) (hY : AEMeasurable Y μ) (hf : AEStronglyMeasurable f (μ.map fun a => (X a, Y a))) : AEStronglyMeasurable (fun a => ∫ y, f (X a, y) ∂condDistrib Y X μ (X a)) μ := (hf.integral_condDistrib_map hY).comp_aemeasurable hX theorem stronglyMeasurable_integral_condDistrib (hf : StronglyMeasurable f) : StronglyMeasurable[mβ.comap X] (fun a ↦ ∫ y, f (X a, y) ∂condDistrib Y X μ (X a)) := (hf.integral_condDistrib).comp_measurable <| Measurable.of_comap_le le_rfl theorem aestronglyMeasurable_integral_condDistrib (hX : AEMeasurable X μ) (hY : AEMeasurable Y μ) (hf : AEStronglyMeasurable f (μ.map fun a => (X a, Y a))) : AEStronglyMeasurable[mβ.comap X] (fun a => ∫ y, f (X a, y) ∂condDistrib Y X μ (X a)) μ := (hf.integral_condDistrib_map hY).comp_ae_measurable' hX end Measurability /-- `condDistrib` is a.e. uniquely defined as the kernel satisfying the defining property of `condKernel`. -/ theorem condDistrib_ae_eq_of_measure_eq_compProd (hX : Measurable X) (hY : Measurable Y) (κ : Kernel β Ω) [IsFiniteKernel κ] (hκ : μ.map (fun x => (X x, Y x)) = μ.map X ⊗ₘ κ) : ∀ᵐ x ∂μ.map X, κ x = condDistrib Y X μ x := by have heq : μ.map X = (μ.map (fun x ↦ (X x, Y x))).fst := by ext s hs rw [Measure.map_apply hX hs, Measure.fst_apply hs, Measure.map_apply] exacts [rfl, Measurable.prod hX hY, measurable_fst hs] rw [heq, condDistrib] refine eq_condKernel_of_measure_eq_compProd _ ?_ convert hκ exact heq.symm section Integrability theorem integrable_toReal_condDistrib (hX : AEMeasurable X μ) (hs : MeasurableSet s) : Integrable (fun a => (condDistrib Y X μ (X a)).real s) μ := by refine integrable_toReal_of_lintegral_ne_top ?_ ?_ · exact Measurable.comp_aemeasurable (Kernel.measurable_coe _ hs) hX · refine ne_of_lt ?_ calc ∫⁻ a, condDistrib Y X μ (X a) s ∂μ ≤ ∫⁻ _, 1 ∂μ := lintegral_mono fun a => prob_le_one _ = μ univ := lintegral_one _ < ∞ := measure_lt_top _ _ theorem _root_.MeasureTheory.Integrable.condDistrib_ae_map (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : ∀ᵐ b ∂μ.map X, Integrable (fun ω => f (b, ω)) (condDistrib Y X μ b) := by rw [condDistrib, ← Measure.fst_map_prodMk₀ (X := X) hY]; exact hf_int.condKernel_ae theorem _root_.MeasureTheory.Integrable.condDistrib_ae (hX : AEMeasurable X μ) (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : ∀ᵐ a ∂μ, Integrable (fun ω => f (X a, ω)) (condDistrib Y X μ (X a)) := ae_of_ae_map hX (hf_int.condDistrib_ae_map hY) theorem _root_.MeasureTheory.Integrable.integral_norm_condDistrib_map (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : Integrable (fun x => ∫ y, ‖f (x, y)‖ ∂condDistrib Y X μ x) (μ.map X) := by rw [condDistrib, ← Measure.fst_map_prodMk₀ (X := X) hY]; exact hf_int.integral_norm_condKernel theorem _root_.MeasureTheory.Integrable.integral_norm_condDistrib (hX : AEMeasurable X μ) (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : Integrable (fun a => ∫ y, ‖f (X a, y)‖ ∂condDistrib Y X μ (X a)) μ := (hf_int.integral_norm_condDistrib_map hY).comp_aemeasurable hX variable [NormedSpace ℝ F] theorem _root_.MeasureTheory.Integrable.norm_integral_condDistrib_map (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : Integrable (fun x => ‖∫ y, f (x, y) ∂condDistrib Y X μ x‖) (μ.map X) := by rw [condDistrib, ← Measure.fst_map_prodMk₀ (X := X) hY]; exact hf_int.norm_integral_condKernel theorem _root_.MeasureTheory.Integrable.norm_integral_condDistrib (hX : AEMeasurable X μ) (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : Integrable (fun a => ‖∫ y, f (X a, y) ∂condDistrib Y X μ (X a)‖) μ := (hf_int.norm_integral_condDistrib_map hY).comp_aemeasurable hX theorem _root_.MeasureTheory.Integrable.integral_condDistrib_map (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : Integrable (fun x => ∫ y, f (x, y) ∂condDistrib Y X μ x) (μ.map X) := (integrable_norm_iff (hf_int.1.integral_condDistrib_map hY)).mp (hf_int.norm_integral_condDistrib_map hY) theorem _root_.MeasureTheory.Integrable.integral_condDistrib (hX : AEMeasurable X μ) (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : Integrable (fun a => ∫ y, f (X a, y) ∂condDistrib Y X μ (X a)) μ := (hf_int.integral_condDistrib_map hY).comp_aemeasurable hX end Integrability theorem setLIntegral_preimage_condDistrib (hX : Measurable X) (hY : AEMeasurable Y μ) (hs : MeasurableSet s) (ht : MeasurableSet t) : ∫⁻ a in X ⁻¹' t, condDistrib Y X μ (X a) s ∂μ = μ (X ⁻¹' t ∩ Y ⁻¹' s) := by -- Porting note: need to massage the LHS integrand into the form accepted by `lintegral_comp` -- (`rw` does not see that the two forms are defeq) conv_lhs => arg 2; change (fun a => ((condDistrib Y X μ) a) s) ∘ X rw [lintegral_comp (Kernel.measurable_coe _ hs) hX, condDistrib, ← Measure.restrict_map hX ht, ← Measure.fst_map_prodMk₀ hY, Measure.setLIntegral_condKernel_eq_measure_prod ht hs, Measure.map_apply_of_aemeasurable (hX.aemeasurable.prodMk hY) (ht.prod hs), mk_preimage_prod] theorem setLIntegral_condDistrib_of_measurableSet (hX : Measurable X) (hY : AEMeasurable Y μ) (hs : MeasurableSet s) {t : Set α} (ht : MeasurableSet[mβ.comap X] t) : ∫⁻ a in t, condDistrib Y X μ (X a) s ∂μ = μ (t ∩ Y ⁻¹' s) := by obtain ⟨t', ht', rfl⟩ := ht rw [setLIntegral_preimage_condDistrib hX hY hs ht'] /-- For almost every `a : α`, the `condDistrib Y X μ` kernel applied to `X a` and a measurable set `s` is equal to the conditional expectation of the indicator of `Y ⁻¹' s`. -/ theorem condDistrib_ae_eq_condExp (hX : Measurable X) (hY : Measurable Y) (hs : MeasurableSet s) : (fun a => (condDistrib Y X μ (X a)).real s) =ᵐ[μ] μ⟦Y ⁻¹' s|mβ.comap X⟧ := by refine ae_eq_condExp_of_forall_setIntegral_eq hX.comap_le ?_ ?_ ?_ ?_ · exact (integrable_const _).indicator (hY hs) · exact fun t _ _ => (integrable_toReal_condDistrib hX.aemeasurable hs).integrableOn · intro t ht _ simp_rw [measureReal_def] rw [integral_toReal ((measurable_condDistrib hs).mono hX.comap_le le_rfl).aemeasurable (Eventually.of_forall fun ω => measure_lt_top (condDistrib Y X μ (X ω)) _), integral_indicator_const _ (hY hs), measureReal_restrict_apply (hY hs), smul_eq_mul, mul_one, inter_comm, setLIntegral_condDistrib_of_measurableSet hX hY.aemeasurable hs ht, measureReal_def] · exact (measurable_condDistrib hs).ennreal_toReal.aestronglyMeasurable /-- The conditional expectation of a function `f` of the product `(X, Y)` is almost everywhere equal to the integral of `y ↦ f(X, y)` against the `condDistrib` kernel. -/ theorem condExp_prod_ae_eq_integral_condDistrib' [NormedSpace ℝ F] [CompleteSpace F] (hX : Measurable X) (hY : AEMeasurable Y μ) (hf_int : Integrable f (μ.map fun a => (X a, Y a))) : μ[fun a => f (X a, Y a)|mβ.comap X] =ᵐ[μ] fun a => ∫ y, f (X a, y) ∂condDistrib Y X μ (X a) := by have hf_int' : Integrable (fun a => f (X a, Y a)) μ := (integrable_map_measure hf_int.1 (hX.aemeasurable.prodMk hY)).mp hf_int refine (ae_eq_condExp_of_forall_setIntegral_eq hX.comap_le hf_int' (fun s _ _ => ?_) ?_ ?_).symm · exact (hf_int.integral_condDistrib hX.aemeasurable hY).integrableOn · rintro s ⟨t, ht, rfl⟩ _ change ∫ a in X ⁻¹' t, ((fun x' => ∫ y, f (x', y) ∂(condDistrib Y X μ) x') ∘ X) a ∂μ = ∫ a in X ⁻¹' t, f (X a, Y a) ∂μ simp only [Function.comp_apply] rw [← integral_map hX.aemeasurable (f := fun x' => ∫ y, f (x', y) ∂(condDistrib Y X μ) x')] swap · rw [← Measure.restrict_map hX ht] exact (hf_int.1.integral_condDistrib_map hY).restrict rw [← Measure.restrict_map hX ht, ← Measure.fst_map_prodMk₀ hY, condDistrib, Measure.setIntegral_condKernel_univ_right ht hf_int.integrableOn, setIntegral_map (ht.prod MeasurableSet.univ) hf_int.1 (hX.aemeasurable.prodMk hY), mk_preimage_prod, preimage_univ, inter_univ] · exact aestronglyMeasurable_integral_condDistrib hX.aemeasurable hY hf_int.1 /-- The conditional expectation of a function `f` of the product `(X, Y)` is almost everywhere equal to the integral of `y ↦ f(X, y)` against the `condDistrib` kernel. -/ theorem condExp_prod_ae_eq_integral_condDistrib₀ [NormedSpace ℝ F] [CompleteSpace F] (hX : Measurable X) (hY : AEMeasurable Y μ) (hf : AEStronglyMeasurable f (μ.map fun a => (X a, Y a))) (hf_int : Integrable (fun a => f (X a, Y a)) μ) : μ[fun a => f (X a, Y a)|mβ.comap X] =ᵐ[μ] fun a => ∫ y, f (X a, y) ∂condDistrib Y X μ (X a) := haveI hf_int' : Integrable f (μ.map fun a => (X a, Y a)) := by rwa [integrable_map_measure hf (hX.aemeasurable.prodMk hY)] condExp_prod_ae_eq_integral_condDistrib' hX hY hf_int' /-- The conditional expectation of a function `f` of the product `(X, Y)` is almost everywhere equal to the integral of `y ↦ f(X, y)` against the `condDistrib` kernel. -/ theorem condExp_prod_ae_eq_integral_condDistrib [NormedSpace ℝ F] [CompleteSpace F] (hX : Measurable X) (hY : AEMeasurable Y μ) (hf : StronglyMeasurable f) (hf_int : Integrable (fun a => f (X a, Y a)) μ) : μ[fun a => f (X a, Y a)|mβ.comap X] =ᵐ[μ] fun a => ∫ y, f (X a, y) ∂condDistrib Y X μ (X a) := haveI hf_int' : Integrable f (μ.map fun a => (X a, Y a)) := by rwa [integrable_map_measure hf.aestronglyMeasurable (hX.aemeasurable.prodMk hY)] condExp_prod_ae_eq_integral_condDistrib' hX hY hf_int' theorem condExp_ae_eq_integral_condDistrib [NormedSpace ℝ F] [CompleteSpace F] (hX : Measurable X) (hY : AEMeasurable Y μ) {f : Ω → F} (hf : StronglyMeasurable f) (hf_int : Integrable (fun a => f (Y a)) μ) : μ[fun a => f (Y a)|mβ.comap X] =ᵐ[μ] fun a => ∫ y, f y ∂condDistrib Y X μ (X a) := condExp_prod_ae_eq_integral_condDistrib hX hY (hf.comp_measurable measurable_snd) hf_int /-- The conditional expectation of `Y` given `X` is almost everywhere equal to the integral `∫ y, y ∂(condDistrib Y X μ (X a))`. -/ theorem condExp_ae_eq_integral_condDistrib' {Ω} [NormedAddCommGroup Ω] [NormedSpace ℝ Ω] [CompleteSpace Ω] [MeasurableSpace Ω] [BorelSpace Ω] [SecondCountableTopology Ω] {Y : α → Ω} (hX : Measurable X) (hY_int : Integrable Y μ) : μ[Y|mβ.comap X] =ᵐ[μ] fun a => ∫ y, y ∂condDistrib Y X μ (X a) := condExp_ae_eq_integral_condDistrib hX hY_int.1.aemeasurable stronglyMeasurable_id hY_int open MeasureTheory theorem _root_.MeasureTheory.AEStronglyMeasurable.comp_snd_map_prodMk {Ω F} {mΩ : MeasurableSpace Ω} (X : Ω → β) {μ : Measure Ω} [TopologicalSpace F] {f : Ω → F} (hf : AEStronglyMeasurable f μ) : AEStronglyMeasurable (fun x : β × Ω => f x.2) (μ.map fun ω => (X ω, ω)) := by refine ⟨fun x => hf.mk f x.2, hf.stronglyMeasurable_mk.comp_measurable measurable_snd, ?_⟩ suffices h : Measure.QuasiMeasurePreserving Prod.snd (μ.map fun ω ↦ (X ω, ω)) μ from Measure.QuasiMeasurePreserving.ae_eq h hf.ae_eq_mk refine ⟨measurable_snd, Measure.AbsolutelyContinuous.mk fun s hs hμs => ?_⟩ rw [Measure.map_apply _ hs] swap; · exact measurable_snd by_cases hX : AEMeasurable X μ · rw [Measure.map_apply_of_aemeasurable] · rw [← univ_prod, mk_preimage_prod, preimage_univ, univ_inter, preimage_id'] exact hμs · exact hX.prodMk aemeasurable_id · exact measurable_snd hs · rw [Measure.map_of_not_aemeasurable] · simp · contrapose! hX; exact measurable_fst.comp_aemeasurable hX @[deprecated (since := "2025-03-05")] alias _root_.MeasureTheory.AEStronglyMeasurable.comp_snd_map_prod_mk := MeasureTheory.AEStronglyMeasurable.comp_snd_map_prodMk theorem _root_.MeasureTheory.Integrable.comp_snd_map_prodMk {Ω} {mΩ : MeasurableSpace Ω} (X : Ω → β) {μ : Measure Ω} {f : Ω → F} (hf_int : Integrable f μ) : Integrable (fun x : β × Ω => f x.2) (μ.map fun ω => (X ω, ω)) := by by_cases hX : AEMeasurable X μ · have hf := hf_int.1.comp_snd_map_prodMk X (mΩ := mΩ) (mβ := mβ) refine ⟨hf, ?_⟩ rw [hasFiniteIntegral_iff_enorm, lintegral_map' hf.enorm (hX.prodMk aemeasurable_id)] exact hf_int.2 · rw [Measure.map_of_not_aemeasurable] · simp · contrapose! hX; exact measurable_fst.comp_aemeasurable hX @[deprecated (since := "2025-03-05")] alias _root_.MeasureTheory.Integrable.comp_snd_map_prod_mk := MeasureTheory.Integrable.comp_snd_map_prodMk theorem aestronglyMeasurable_comp_snd_map_prodMk_iff {Ω F} {_ : MeasurableSpace Ω} [TopologicalSpace F] {X : Ω → β} {μ : Measure Ω} (hX : Measurable X) {f : Ω → F} : AEStronglyMeasurable (fun x : β × Ω => f x.2) (μ.map fun ω => (X ω, ω)) ↔ AEStronglyMeasurable f μ := ⟨fun h => h.comp_measurable (hX.prodMk measurable_id), fun h => h.comp_snd_map_prodMk X⟩ @[deprecated (since := "2025-03-05")] alias aestronglyMeasurable_comp_snd_map_prod_mk_iff := aestronglyMeasurable_comp_snd_map_prodMk_iff theorem integrable_comp_snd_map_prodMk_iff {Ω} {_ : MeasurableSpace Ω} {X : Ω → β} {μ : Measure Ω} (hX : Measurable X) {f : Ω → F} : Integrable (fun x : β × Ω => f x.2) (μ.map fun ω => (X ω, ω)) ↔ Integrable f μ := ⟨fun h => h.comp_measurable (hX.prodMk measurable_id), fun h => h.comp_snd_map_prodMk X⟩ @[deprecated (since := "2025-03-05")] alias integrable_comp_snd_map_prod_mk_iff := integrable_comp_snd_map_prodMk_iff theorem condExp_ae_eq_integral_condDistrib_id [NormedSpace ℝ F] [CompleteSpace F] {X : Ω → β} {μ : Measure Ω} [IsFiniteMeasure μ] (hX : Measurable X) {f : Ω → F} (hf_int : Integrable f μ) : μ[f|mβ.comap X] =ᵐ[μ] fun a => ∫ y, f y ∂condDistrib id X μ (X a) := condExp_prod_ae_eq_integral_condDistrib' hX aemeasurable_id (hf_int.comp_snd_map_prodMk X) end ProbabilityTheory
Comap.lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.Algebra.MvPolynomial.Rename /-! # `comap` operation on `MvPolynomial` This file defines the `comap` function on `MvPolynomial`. `MvPolynomial.comap` is a low-tech example of a map of "algebraic varieties," modulo the fact that `mathlib` does not yet define varieties. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[CommSemiring R]` (the coefficients) -/ namespace MvPolynomial variable {σ : Type*} {τ : Type*} {υ : Type*} {R : Type*} [CommSemiring R] /-- Given an algebra hom `f : MvPolynomial σ R →ₐ[R] MvPolynomial τ R` and a variable evaluation `v : τ → R`, `comap f v` produces a variable evaluation `σ → R`. -/ noncomputable def comap (f : MvPolynomial σ R →ₐ[R] MvPolynomial τ R) : (τ → R) → σ → R := fun x i => aeval x (f (X i)) @[simp] theorem comap_apply (f : MvPolynomial σ R →ₐ[R] MvPolynomial τ R) (x : τ → R) (i : σ) : comap f x i = aeval x (f (X i)) := rfl @[simp] theorem comap_id_apply (x : σ → R) : comap (AlgHom.id R (MvPolynomial σ R)) x = x := by funext i simp only [comap, AlgHom.id_apply, aeval_X] variable (σ R) theorem comap_id : comap (AlgHom.id R (MvPolynomial σ R)) = id := by funext x exact comap_id_apply x variable {σ R} theorem comap_comp_apply (f : MvPolynomial σ R →ₐ[R] MvPolynomial τ R) (g : MvPolynomial τ R →ₐ[R] MvPolynomial υ R) (x : υ → R) : comap (g.comp f) x = comap f (comap g x) := by funext i trans aeval x (aeval (fun i => g (X i)) (f (X i))) · apply eval₂Hom_congr rfl rfl rw [AlgHom.comp_apply] suffices g = aeval fun i => g (X i) by rw [← this] exact aeval_unique g · simp only [comap, aeval_eq_eval₂Hom, map_eval₂Hom] refine eval₂Hom_congr ?_ rfl rfl ext r apply aeval_C theorem comap_comp (f : MvPolynomial σ R →ₐ[R] MvPolynomial τ R) (g : MvPolynomial τ R →ₐ[R] MvPolynomial υ R) : comap (g.comp f) = comap f ∘ comap g := by funext x exact comap_comp_apply _ _ _ theorem comap_eq_id_of_eq_id (f : MvPolynomial σ R →ₐ[R] MvPolynomial σ R) (hf : ∀ φ, f φ = φ) (x : σ → R) : comap f x = x := by convert comap_id_apply x ext1 φ simp [hf, AlgHom.id_apply] theorem comap_rename (f : σ → τ) (x : τ → R) : comap (rename f) x = x ∘ f := by funext simp [rename_X, comap_apply, aeval_X] /-- If two polynomial types over the same coefficient ring `R` are equivalent, there is a bijection between the types of functions from their variable types to `R`. -/ noncomputable def comapEquiv (f : MvPolynomial σ R ≃ₐ[R] MvPolynomial τ R) : (τ → R) ≃ (σ → R) where toFun := comap f invFun := comap f.symm left_inv := by intro x rw [← comap_comp_apply] apply comap_eq_id_of_eq_id intro simp only [AlgHom.id_apply, AlgEquiv.comp_symm] right_inv := by intro x rw [← comap_comp_apply] apply comap_eq_id_of_eq_id intro simp only [AlgHom.id_apply, AlgEquiv.symm_comp] @[simp] theorem comapEquiv_coe (f : MvPolynomial σ R ≃ₐ[R] MvPolynomial τ R) : (comapEquiv f : (τ → R) → σ → R) = comap f := rfl @[simp] theorem comapEquiv_symm_coe (f : MvPolynomial σ R ≃ₐ[R] MvPolynomial τ R) : ((comapEquiv f).symm : (σ → R) → τ → R) = comap f.symm := rfl end MvPolynomial
Operations.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.Algebra.Algebra.Operations import Mathlib.Algebra.Module.BigOperators import Mathlib.Data.Fintype.Lattice import Mathlib.RingTheory.Coprime.Lemmas import Mathlib.RingTheory.Ideal.Basic import Mathlib.RingTheory.Nilpotent.Defs import Mathlib.RingTheory.NonUnitalSubsemiring.Basic /-! # More operations on modules and ideals -/ assert_not_exists Module.Basis -- See `RingTheory.Ideal.Basis` Submodule.hasQuotient -- See `RingTheory.Ideal.Quotient.Operations` universe u v w x open Pointwise namespace Submodule lemma coe_span_smul {R' M' : Type*} [CommSemiring R'] [AddCommMonoid M'] [Module R' M'] (s : Set R') (N : Submodule R' M') : (Ideal.span s : Set R') • N = s • N := set_smul_eq_of_le _ _ _ (by rintro r n hr hn induction hr using Submodule.span_induction with | mem _ h => exact mem_set_smul_of_mem_mem h hn | zero => rw [zero_smul]; exact Submodule.zero_mem _ | add _ _ _ _ ihr ihs => rw [add_smul]; exact Submodule.add_mem _ ihr ihs | smul _ _ hr => rw [mem_span_set] at hr obtain ⟨c, hc, rfl⟩ := hr rw [Finsupp.sum, Finset.smul_sum, Finset.sum_smul] refine Submodule.sum_mem _ fun i hi => ?_ rw [← mul_smul, smul_eq_mul, mul_comm, mul_smul] exact mem_set_smul_of_mem_mem (hc hi) <| Submodule.smul_mem _ _ hn) <| set_smul_mono_left _ Submodule.subset_span lemma span_singleton_toAddSubgroup_eq_zmultiples (a : ℤ) : (span ℤ {a}).toAddSubgroup = AddSubgroup.zmultiples a := by ext i simp [Ideal.mem_span_singleton', AddSubgroup.mem_zmultiples_iff] @[simp] lemma _root_.Ideal.span_singleton_toAddSubgroup_eq_zmultiples (a : ℤ) : (Ideal.span {a}).toAddSubgroup = AddSubgroup.zmultiples a := Submodule.span_singleton_toAddSubgroup_eq_zmultiples _ variable {R : Type u} {M : Type v} {M' F G : Type*} section Semiring variable [Semiring R] [AddCommMonoid M] [Module R M] /-- This duplicates the global `smul_eq_mul`, but doesn't have to unfold anywhere near as much to apply. -/ protected theorem _root_.Ideal.smul_eq_mul (I J : Ideal R) : I • J = I * J := rfl variable {I J : Ideal R} {N : Submodule R M} theorem smul_le_right : I • N ≤ N := smul_le.2 fun r _ _ ↦ N.smul_mem r theorem map_le_smul_top (I : Ideal R) (f : R →ₗ[R] M) : Submodule.map f I ≤ I • (⊤ : Submodule R M) := by rintro _ ⟨y, hy, rfl⟩ rw [← mul_one y, ← smul_eq_mul, f.map_smul] exact smul_mem_smul hy mem_top variable (I J N) @[simp] theorem top_smul : (⊤ : Ideal R) • N = N := le_antisymm smul_le_right fun r hri => one_smul R r ▸ smul_mem_smul mem_top hri protected theorem mul_smul : (I * J) • N = I • J • N := Submodule.smul_assoc _ _ _ theorem mem_of_span_top_of_smul_mem (M' : Submodule R M) (s : Set R) (hs : Ideal.span s = ⊤) (x : M) (H : ∀ r : s, (r : R) • x ∈ M') : x ∈ M' := by suffices LinearMap.range (LinearMap.toSpanSingleton R M x) ≤ M' by rw [← LinearMap.toSpanSingleton_one R M x] exact this (LinearMap.mem_range_self _ 1) rw [LinearMap.range_eq_map, ← hs, map_le_iff_le_comap, Ideal.span, span_le] exact fun r hr ↦ H ⟨r, hr⟩ variable {M' : Type w} [AddCommMonoid M'] [Module R M'] @[simp] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 <| smul_le.2 fun r hr n hn => show f (r • n) ∈ I • N.map f from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) <| smul_le.2 fun r hr _ hn => let ⟨p, hp, hfp⟩ := mem_map.1 hn hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) theorem mem_smul_top_iff (N : Submodule R M) (x : N) : x ∈ I • (⊤ : Submodule R N) ↔ (x : M) ∈ I • N := by have : Submodule.map N.subtype (I • ⊤) = I • N := by rw [Submodule.map_smul'', Submodule.map_top, Submodule.range_subtype] simp [← this, -map_smul''] @[simp] theorem smul_comap_le_comap_smul (f : M →ₗ[R] M') (S : Submodule R M') (I : Ideal R) : I • S.comap f ≤ (I • S).comap f := by refine Submodule.smul_le.mpr fun r hr x hx => ?_ rw [Submodule.mem_comap] at hx ⊢ rw [f.map_smul] exact Submodule.smul_mem_smul hr hx end Semiring section CommSemiring variable [CommSemiring R] [AddCommMonoid M] [Module R M] [AddCommMonoid M'] [Module R M'] open Pointwise theorem mem_smul_span_singleton {I : Ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : Set M) ↔ ∃ y ∈ I, y • m = x := ⟨fun hx => smul_induction_on hx (fun r hri _ hnm => let ⟨s, hs⟩ := mem_span_singleton.1 hnm ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩) fun m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩ => ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩, fun ⟨_, hyi, hy⟩ => hy ▸ smul_mem_smul hyi (subset_span <| Set.mem_singleton m)⟩ variable {I J : Ideal R} {N P : Submodule R M} variable (S : Set R) (T : Set M) theorem smul_eq_map₂ : I • N = Submodule.map₂ (LinearMap.lsmul R M) I N := le_antisymm (smul_le.mpr fun _m hm _n ↦ Submodule.apply_mem_map₂ _ hm) (map₂_le.mpr fun _m hm _n ↦ smul_mem_smul hm) theorem span_smul_span : Ideal.span S • span R T = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := by rw [smul_eq_map₂] exact (map₂_span_span _ _ _ _).trans <| congr_arg _ <| Set.image2_eq_iUnion _ _ _ theorem ideal_span_singleton_smul (r : R) (N : Submodule R M) : (Ideal.span {r} : Ideal R) • N = r • N := by have : span R (⋃ (t : M) (_ : t ∈ N), {r • t}) = r • N := by convert span_eq (r • N) exact (Set.image_eq_iUnion _ (N : Set M)).symm conv_lhs => rw [← span_eq N, span_smul_span] simpa /-- Given `s`, a generating set of `R`, to check that an `x : M` falls in a submodule `M'` of `x`, we only need to show that `r ^ n • x ∈ M'` for some `n` for each `r : s`. -/ theorem mem_of_span_eq_top_of_smul_pow_mem (M' : Submodule R M) (s : Set R) (hs : Ideal.span s = ⊤) (x : M) (H : ∀ r : s, ∃ n : ℕ, ((r : R) ^ n : R) • x ∈ M') : x ∈ M' := by choose f hf using H apply M'.mem_of_span_top_of_smul_mem _ (Ideal.span_range_pow_eq_top s hs f) rintro ⟨_, r, hr, rfl⟩ exact hf r open Pointwise in @[simp] theorem map_pointwise_smul (r : R) (N : Submodule R M) (f : M →ₗ[R] M') : (r • N).map f = r • N.map f := by simp_rw [← ideal_span_singleton_smul, map_smul''] theorem mem_smul_span {s : Set M} {x : M} : x ∈ I • Submodule.span R s ↔ x ∈ Submodule.span R (⋃ (a ∈ I) (b ∈ s), ({a • b} : Set M)) := by rw [← I.span_eq, Submodule.span_smul_span, I.span_eq] simp variable (I) /-- If `x` is an `I`-multiple of the submodule spanned by `f '' s`, then we can write `x` as an `I`-linear combination of the elements of `f '' s`. -/ theorem mem_ideal_smul_span_iff_exists_sum {ι : Type*} (f : ι → M) (x : M) : x ∈ I • span R (Set.range f) ↔ ∃ (a : ι →₀ R) (_ : ∀ i, a i ∈ I), (a.sum fun i c => c • f i) = x := by constructor; swap · rintro ⟨a, ha, rfl⟩ exact Submodule.sum_mem _ fun c _ => smul_mem_smul (ha c) <| subset_span <| Set.mem_range_self _ refine fun hx => span_induction ?_ ?_ ?_ ?_ (mem_smul_span.mp hx) · simp only [Set.mem_iUnion, Set.mem_range, Set.mem_singleton_iff] rintro x ⟨y, hy, x, ⟨i, rfl⟩, rfl⟩ refine ⟨Finsupp.single i y, fun j => ?_, ?_⟩ · letI := Classical.decEq ι rw [Finsupp.single_apply] split_ifs · assumption · exact I.zero_mem refine @Finsupp.sum_single_index ι R M _ _ i _ (fun i y => y • f i) ?_ simp · exact ⟨0, fun _ => I.zero_mem, Finsupp.sum_zero_index⟩ · rintro x y - - ⟨ax, hax, rfl⟩ ⟨ay, hay, rfl⟩ refine ⟨ax + ay, fun i => I.add_mem (hax i) (hay i), Finsupp.sum_add_index' ?_ ?_⟩ <;> intros <;> simp only [zero_smul, add_smul] · rintro c x - ⟨a, ha, rfl⟩ refine ⟨c • a, fun i => I.mul_mem_left c (ha i), ?_⟩ rw [Finsupp.sum_smul_index, Finsupp.smul_sum] <;> intros <;> simp only [zero_smul, mul_smul] theorem mem_ideal_smul_span_iff_exists_sum' {ι : Type*} (s : Set ι) (f : ι → M) (x : M) : x ∈ I • span R (f '' s) ↔ ∃ (a : s →₀ R) (_ : ∀ i, a i ∈ I), (a.sum fun i c => c • f i) = x := by rw [← Submodule.mem_ideal_smul_span_iff_exists_sum, ← Set.image_eq_range] end CommSemiring end Submodule namespace Ideal section Add variable {R : Type u} [Semiring R] @[simp] theorem add_eq_sup {I J : Ideal R} : I + J = I ⊔ J := rfl @[simp] theorem zero_eq_bot : (0 : Ideal R) = ⊥ := rfl @[simp] theorem sum_eq_sup {ι : Type*} (s : Finset ι) (f : ι → Ideal R) : s.sum f = s.sup f := rfl end Add section Semiring variable {R : Type u} [Semiring R] {I J K L : Ideal R} @[simp, grind =] theorem one_eq_top : (1 : Ideal R) = ⊤ := by rw [Submodule.one_eq_span, ← Ideal.span, Ideal.span_singleton_one] theorem add_eq_one_iff : I + J = 1 ↔ ∃ i ∈ I, ∃ j ∈ J, i + j = 1 := by rw [one_eq_top, eq_top_iff_one, add_eq_sup, Submodule.mem_sup] theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := Submodule.smul_mem_smul hr hs theorem bot_pow {n : ℕ} (hn : n ≠ 0) : (⊥ : Ideal R) ^ n = ⊥ := Submodule.bot_pow hn theorem pow_mem_pow {x : R} (hx : x ∈ I) (n : ℕ) : x ^ n ∈ I ^ n := Submodule.pow_mem_pow _ hx _ theorem mul_le : I * J ≤ K ↔ ∀ r ∈ I, ∀ s ∈ J, r * s ∈ K := Submodule.smul_le theorem mul_le_left : I * J ≤ J := mul_le.2 fun _ _ _ => J.mul_mem_left _ @[simp] theorem sup_mul_left_self : I ⊔ J * I = I := sup_eq_left.2 mul_le_left @[simp] theorem mul_left_self_sup : J * I ⊔ I = I := sup_eq_right.2 mul_le_left theorem mul_le_right [I.IsTwoSided] : I * J ≤ I := mul_le.2 fun _ hr _ _ ↦ I.mul_mem_right _ hr @[simp] theorem sup_mul_right_self [I.IsTwoSided] : I ⊔ I * J = I := sup_eq_left.2 mul_le_right @[simp] theorem mul_right_self_sup [I.IsTwoSided] : I * J ⊔ I = I := sup_eq_right.2 mul_le_right protected theorem mul_assoc : I * J * K = I * (J * K) := Submodule.smul_assoc I J K variable (I) theorem mul_bot : I * ⊥ = ⊥ := by simp theorem bot_mul : ⊥ * I = ⊥ := by simp @[simp] theorem top_mul : ⊤ * I = I := Submodule.top_smul I variable {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := Submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := Submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := smul_mono_right I h variable (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := Submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := Submodule.sup_smul I J K theorem mul_iSup {ι : Sort*} (J : ι → Ideal R) : I * (⨆ i, J i) = ⨆ i, I * J i := Submodule.smul_iSup theorem iSup_mul {ι : Sort*} (J : ι → Ideal R) (I : Ideal R) : (⨆ i, J i) * I = ⨆ i, J i * I := Submodule.iSup_smul variable {I J K} theorem pow_le_pow_right {m n : ℕ} (h : m ≤ n) : I ^ n ≤ I ^ m := by obtain _ | m := m · rw [Submodule.pow_zero, one_eq_top]; exact le_top obtain ⟨n, rfl⟩ := Nat.exists_eq_add_of_le h rw [add_comm, Submodule.pow_add _ m.add_one_ne_zero] exact mul_le_left theorem pow_le_self {n : ℕ} (hn : n ≠ 0) : I ^ n ≤ I := calc I ^ n ≤ I ^ 1 := pow_le_pow_right (Nat.pos_of_ne_zero hn) _ = I := Submodule.pow_one _ theorem pow_right_mono (e : I ≤ J) (n : ℕ) : I ^ n ≤ J ^ n := by induction' n with _ hn · rw [Submodule.pow_zero, Submodule.pow_zero] · rw [Submodule.pow_succ, Submodule.pow_succ] exact Ideal.mul_mono hn e namespace IsTwoSided instance (priority := low) [J.IsTwoSided] : (I * J).IsTwoSided := ⟨fun b ha ↦ Submodule.mul_induction_on ha (fun i hi j hj ↦ by rw [mul_assoc]; exact mul_mem_mul hi (mul_mem_right _ _ hj)) fun x y hx hy ↦ by rw [right_distrib]; exact add_mem hx hy⟩ variable [I.IsTwoSided] (m n : ℕ) instance (priority := low) : (I ^ n).IsTwoSided := n.rec (by rw [Submodule.pow_zero, one_eq_top]; infer_instance) (fun _ _ ↦ by rw [Submodule.pow_succ]; infer_instance) protected theorem mul_one : I * 1 = I := mul_le_right.antisymm fun i hi ↦ mul_one i ▸ mul_mem_mul hi (one_eq_top (R := R) ▸ Submodule.mem_top) protected theorem pow_add : I ^ (m + n) = I ^ m * I ^ n := by obtain rfl | h := eq_or_ne n 0 · rw [add_zero, Submodule.pow_zero, IsTwoSided.mul_one] · exact Submodule.pow_add _ h protected theorem pow_succ : I ^ (n + 1) = I * I ^ n := by rw [add_comm, IsTwoSided.pow_add, Submodule.pow_one] end IsTwoSided @[simp] theorem mul_eq_bot [NoZeroDivisors R] : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨fun hij => or_iff_not_imp_left.mpr fun I_ne_bot => J.eq_bot_iff.mpr fun j hj => let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot Or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0, fun h => by obtain rfl | rfl := h; exacts [bot_mul _, mul_bot _]⟩ instance [NoZeroDivisors R] : NoZeroDivisors (Ideal R) where eq_zero_or_eq_zero_of_mul_eq_zero := mul_eq_bot.1 instance {S A : Type*} [Semiring S] [SMul R S] [AddCommMonoid A] [Module R A] [Module S A] [IsScalarTower R S A] [NoZeroSMulDivisors R A] {I : Submodule S A} : NoZeroSMulDivisors R I := Submodule.noZeroSMulDivisors (Submodule.restrictScalars R I) theorem pow_eq_zero_of_mem {I : Ideal R} {n m : ℕ} (hnI : I ^ n = 0) (hmn : n ≤ m) {x : R} (hx : x ∈ I) : x ^ m = 0 := by simpa [hnI] using pow_le_pow_right hmn <| pow_mem_pow hx m end Semiring section MulAndRadical variable {R : Type u} {ι : Type*} [CommSemiring R] variable {I J K L : Ideal R} theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs theorem prod_mem_prod {ι : Type*} {s : Finset ι} {I : ι → Ideal R} {x : ι → R} : (∀ i ∈ s, x i ∈ I i) → (∏ i ∈ s, x i) ∈ ∏ i ∈ s, I i := by classical refine Finset.induction_on s ?_ ?_ · #adaptation_note /-- Until `nightly-2025-08-06`, this was `by grind [Submodule.mem_top]` Some subsequent change to `grind` has broken this, so I have restored the original proof. -/ intro rw [Finset.prod_empty, Finset.prod_empty, one_eq_top] exact Submodule.mem_top · grind [mul_mem_mul] lemma sup_pow_add_le_pow_sup_pow {n m : ℕ} : (I ⊔ J) ^ (n + m) ≤ I ^ n ⊔ J ^ m := by rw [← Ideal.add_eq_sup, ← Ideal.add_eq_sup, add_pow, Ideal.sum_eq_sup] apply Finset.sup_le intros i hi by_cases hn : n ≤ i · exact (Ideal.mul_le_right.trans (Ideal.mul_le_right.trans ((Ideal.pow_le_pow_right hn).trans le_sup_left))) · refine (Ideal.mul_le_right.trans (Ideal.mul_le_left.trans ((Ideal.pow_le_pow_right ?_).trans le_sup_right))) omega variable (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 fun _ hrI _ hsJ => mul_mem_mul_rev hsJ hrI) (mul_le.2 fun _ hrJ _ hsI => mul_mem_mul_rev hsI hrJ) theorem span_mul_span (S T : Set R) : span S * span T = span (⋃ (s ∈ S) (t ∈ T), {s * t}) := Submodule.span_smul_span S T variable {I J K} theorem span_mul_span' (S T : Set R) : span S * span T = span (S * T) := by unfold span rw [Submodule.span_mul_span] theorem span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : Ideal R) := by unfold span rw [Submodule.span_mul_span, Set.singleton_mul_singleton] theorem span_singleton_pow (s : R) (n : ℕ) : span {s} ^ n = (span {s ^ n} : Ideal R) := by induction' n with n ih; · simp [Set.singleton_one] simp only [pow_succ, ih, span_singleton_mul_span_singleton] theorem mem_mul_span_singleton {x y : R} {I : Ideal R} : x ∈ I * span {y} ↔ ∃ z ∈ I, z * y = x := Submodule.mem_smul_span_singleton theorem mem_span_singleton_mul {x y : R} {I : Ideal R} : x ∈ span {y} * I ↔ ∃ z ∈ I, y * z = x := by simp only [mul_comm, mem_mul_span_singleton] @[simp] lemma range_mul (A : Type*) [CommSemiring A] [Module R A] [SMulCommClass R A A] [IsScalarTower R A A] (a : A) : LinearMap.range (LinearMap.mul R A a) = (Ideal.span {a}).restrictScalars R := by aesop (add simp Ideal.mem_span_singleton) (add simp dvd_def) lemma range_mul' (a : R) : LinearMap.range (LinearMap.mul R R a) = Ideal.span {a} := range_mul .. theorem le_span_singleton_mul_iff {x : R} {I J : Ideal R} : I ≤ span {x} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI := show (∀ {zI} (_ : zI ∈ I), zI ∈ span {x} * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI by simp only [mem_span_singleton_mul] theorem span_singleton_mul_le_iff {x : R} {I J : Ideal R} : span {x} * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J := by simp only [mul_le, mem_span_singleton] constructor · intro h zI hzI exact h x (dvd_refl x) zI hzI · rintro h _ ⟨z, rfl⟩ zI hzI rw [mul_comm x z, mul_assoc] exact J.mul_mem_left _ (h zI hzI) theorem span_singleton_mul_le_span_singleton_mul {x y : R} {I J : Ideal R} : span {x} * I ≤ span {y} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ := by simp only [span_singleton_mul_le_iff, mem_span_singleton_mul, eq_comm] theorem span_singleton_mul_right_mono [IsDomain R] {x : R} (hx : x ≠ 0) : span {x} * I ≤ span {x} * J ↔ I ≤ J := by simp_rw [span_singleton_mul_le_span_singleton_mul, mul_right_inj' hx, exists_eq_right', SetLike.le_def] theorem span_singleton_mul_left_mono [IsDomain R] {x : R} (hx : x ≠ 0) : I * span {x} ≤ J * span {x} ↔ I ≤ J := by simpa only [mul_comm I, mul_comm J] using span_singleton_mul_right_mono hx theorem span_singleton_mul_right_inj [IsDomain R] {x : R} (hx : x ≠ 0) : span {x} * I = span {x} * J ↔ I = J := by simp only [le_antisymm_iff, span_singleton_mul_right_mono hx] theorem span_singleton_mul_left_inj [IsDomain R] {x : R} (hx : x ≠ 0) : I * span {x} = J * span {x} ↔ I = J := by simp only [le_antisymm_iff, span_singleton_mul_left_mono hx] theorem span_singleton_mul_right_injective [IsDomain R] {x : R} (hx : x ≠ 0) : Function.Injective ((span {x} : Ideal R) * ·) := fun _ _ => (span_singleton_mul_right_inj hx).mp theorem span_singleton_mul_left_injective [IsDomain R] {x : R} (hx : x ≠ 0) : Function.Injective fun I : Ideal R => I * span {x} := fun _ _ => (span_singleton_mul_left_inj hx).mp theorem eq_span_singleton_mul {x : R} (I J : Ideal R) : I = span {x} * J ↔ (∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ ∀ z ∈ J, x * z ∈ I := by simp only [le_antisymm_iff, le_span_singleton_mul_iff, span_singleton_mul_le_iff] theorem span_singleton_mul_eq_span_singleton_mul {x y : R} (I J : Ideal R) : span {x} * I = span {y} * J ↔ (∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ) ∧ ∀ zJ ∈ J, ∃ zI ∈ I, x * zI = y * zJ := by simp only [le_antisymm_iff, span_singleton_mul_le_span_singleton_mul, eq_comm] theorem prod_span {ι : Type*} (s : Finset ι) (I : ι → Set R) : (∏ i ∈ s, Ideal.span (I i)) = Ideal.span (∏ i ∈ s, I i) := Submodule.prod_span s I theorem prod_span_singleton {ι : Type*} (s : Finset ι) (I : ι → R) : (∏ i ∈ s, Ideal.span ({I i} : Set R)) = Ideal.span {∏ i ∈ s, I i} := Submodule.prod_span_singleton s I @[simp] theorem multiset_prod_span_singleton (m : Multiset R) : (m.map fun x => Ideal.span {x}).prod = Ideal.span ({Multiset.prod m} : Set R) := Multiset.induction_on m (by simp) fun a m ih => by simp only [Multiset.map_cons, Multiset.prod_cons, ih, ← Ideal.span_singleton_mul_span_singleton] open scoped Function in -- required for scoped `on` notation theorem finset_inf_span_singleton {ι : Type*} (s : Finset ι) (I : ι → R) (hI : Set.Pairwise (↑s) (IsCoprime on I)) : (s.inf fun i => Ideal.span ({I i} : Set R)) = Ideal.span {∏ i ∈ s, I i} := by ext x simp only [Submodule.mem_finset_inf, Ideal.mem_span_singleton] exact ⟨Finset.prod_dvd_of_coprime hI, fun h i hi => (Finset.dvd_prod_of_mem _ hi).trans h⟩ theorem iInf_span_singleton {ι : Type*} [Fintype ι] {I : ι → R} (hI : ∀ (i j) (_ : i ≠ j), IsCoprime (I i) (I j)) : ⨅ i, span ({I i} : Set R) = span {∏ i, I i} := by rw [← Finset.inf_univ_eq_iInf, finset_inf_span_singleton] rwa [Finset.coe_univ, Set.pairwise_univ] theorem iInf_span_singleton_natCast {R : Type*} [CommRing R] {ι : Type*} [Fintype ι] {I : ι → ℕ} (hI : Pairwise fun i j => (I i).Coprime (I j)) : ⨅ (i : ι), span {(I i : R)} = span {((∏ i : ι, I i : ℕ) : R)} := by rw [iInf_span_singleton, Nat.cast_prod] exact fun i j h ↦ (hI h).cast theorem sup_eq_top_iff_isCoprime {R : Type*} [CommSemiring R] (x y : R) : span ({x} : Set R) ⊔ span {y} = ⊤ ↔ IsCoprime x y := by rw [eq_top_iff_one, Submodule.mem_sup] constructor · rintro ⟨u, hu, v, hv, h1⟩ rw [mem_span_singleton'] at hu hv rw [← hu.choose_spec, ← hv.choose_spec] at h1 exact ⟨_, _, h1⟩ · exact fun ⟨u, v, h1⟩ => ⟨_, mem_span_singleton'.mpr ⟨_, rfl⟩, _, mem_span_singleton'.mpr ⟨_, rfl⟩, h1⟩ theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 fun r hri s hsj => ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩ theorem multiset_prod_le_inf {s : Multiset (Ideal R)} : s.prod ≤ s.inf := by classical refine s.induction_on ?_ ?_ · rw [Multiset.inf_zero] exact le_top intro a s ih rw [Multiset.prod_cons, Multiset.inf_cons] exact le_trans mul_le_inf (inf_le_inf le_rfl ih) theorem prod_le_inf {s : Finset ι} {f : ι → Ideal R} : s.prod f ≤ s.inf f := multiset_prod_le_inf theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf fun r ⟨hri, hrj⟩ => let ⟨s, hsi, t, htj, hst⟩ := Submodule.mem_sup.1 ((eq_top_iff_one _).1 h) mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ Ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) theorem sup_mul_eq_of_coprime_left (h : I ⊔ J = ⊤) : I ⊔ J * K = I ⊔ K := le_antisymm (sup_le_sup_left mul_le_left _) fun i hi => by rw [eq_top_iff_one] at h; rw [Submodule.mem_sup] at h hi ⊢ obtain ⟨i1, hi1, j, hj, h⟩ := h; obtain ⟨i', hi', k, hk, hi⟩ := hi refine ⟨_, add_mem hi' (mul_mem_right k _ hi1), _, mul_mem_mul hj hk, ?_⟩ rw [add_assoc, ← add_mul, h, one_mul, hi] theorem sup_mul_eq_of_coprime_right (h : I ⊔ K = ⊤) : I ⊔ J * K = I ⊔ J := by rw [mul_comm] exact sup_mul_eq_of_coprime_left h theorem mul_sup_eq_of_coprime_left (h : I ⊔ J = ⊤) : I * K ⊔ J = K ⊔ J := by rw [sup_comm] at h rw [sup_comm, sup_mul_eq_of_coprime_left h, sup_comm] theorem mul_sup_eq_of_coprime_right (h : K ⊔ J = ⊤) : I * K ⊔ J = I ⊔ J := by rw [sup_comm] at h rw [sup_comm, sup_mul_eq_of_coprime_right h, sup_comm] theorem sup_prod_eq_top {s : Finset ι} {J : ι → Ideal R} (h : ∀ i, i ∈ s → I ⊔ J i = ⊤) : (I ⊔ ∏ i ∈ s, J i) = ⊤ := Finset.prod_induction _ (fun J => I ⊔ J = ⊤) (fun _ _ hJ hK => (sup_mul_eq_of_coprime_left hJ).trans hK) (by simp_rw [one_eq_top, sup_top_eq]) h theorem sup_multiset_prod_eq_top {s : Multiset (Ideal R)} (h : ∀ p ∈ s, I ⊔ p = ⊤) : I ⊔ Multiset.prod s = ⊤ := Multiset.prod_induction (I ⊔ · = ⊤) s (fun _ _ hp hq ↦ (sup_mul_eq_of_coprime_left hp).trans hq) (by simp only [one_eq_top, le_top, sup_of_le_right]) h theorem sup_iInf_eq_top {s : Finset ι} {J : ι → Ideal R} (h : ∀ i, i ∈ s → I ⊔ J i = ⊤) : (I ⊔ ⨅ i ∈ s, J i) = ⊤ := eq_top_iff.mpr <| le_of_eq_of_le (sup_prod_eq_top h).symm <| sup_le_sup_left (le_of_le_of_eq prod_le_inf <| Finset.inf_eq_iInf _ _) _ theorem prod_sup_eq_top {s : Finset ι} {J : ι → Ideal R} (h : ∀ i, i ∈ s → J i ⊔ I = ⊤) : (∏ i ∈ s, J i) ⊔ I = ⊤ := by rw [sup_comm, sup_prod_eq_top]; intro i hi; rw [sup_comm, h i hi] theorem iInf_sup_eq_top {s : Finset ι} {J : ι → Ideal R} (h : ∀ i, i ∈ s → J i ⊔ I = ⊤) : (⨅ i ∈ s, J i) ⊔ I = ⊤ := by rw [sup_comm, sup_iInf_eq_top]; intro i hi; rw [sup_comm, h i hi] theorem sup_pow_eq_top {n : ℕ} (h : I ⊔ J = ⊤) : I ⊔ J ^ n = ⊤ := by rw [← Finset.card_range n, ← Finset.prod_const] exact sup_prod_eq_top fun _ _ => h theorem pow_sup_eq_top {n : ℕ} (h : I ⊔ J = ⊤) : I ^ n ⊔ J = ⊤ := by rw [← Finset.card_range n, ← Finset.prod_const] exact prod_sup_eq_top fun _ _ => h theorem pow_sup_pow_eq_top {m n : ℕ} (h : I ⊔ J = ⊤) : I ^ m ⊔ J ^ n = ⊤ := sup_pow_eq_top (pow_sup_eq_top h) variable (I) in @[simp] theorem mul_top : I * ⊤ = I := Ideal.mul_comm ⊤ I ▸ Submodule.top_smul I /-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/ @[simp] lemma multiset_prod_eq_bot {R : Type*} [CommSemiring R] [IsDomain R] {s : Multiset (Ideal R)} : s.prod = ⊥ ↔ ⊥ ∈ s := Multiset.prod_eq_zero_iff theorem span_pair_mul_span_pair (w x y z : R) : (span {w, x} : Ideal R) * span {y, z} = span {w * y, w * z, x * y, x * z} := by simp_rw [span_insert, sup_mul, mul_sup, span_singleton_mul_span_singleton, sup_assoc] theorem isCoprime_iff_codisjoint : IsCoprime I J ↔ Codisjoint I J := by rw [IsCoprime, codisjoint_iff] constructor · rintro ⟨x, y, hxy⟩ rw [eq_top_iff_one] apply (show x * I + y * J ≤ I ⊔ J from sup_le (mul_le_left.trans le_sup_left) (mul_le_left.trans le_sup_right)) rw [hxy] simp only [one_eq_top, Submodule.mem_top] · intro h refine ⟨1, 1, ?_⟩ simpa only [one_eq_top, top_mul, Submodule.add_eq_sup] theorem isCoprime_of_isMaximal [I.IsMaximal] [J.IsMaximal] (ne : I ≠ J) : IsCoprime I J := by rw [isCoprime_iff_codisjoint, isMaximal_def] at * exact IsCoatom.codisjoint_of_ne ‹_› ‹_› ne theorem isCoprime_iff_add : IsCoprime I J ↔ I + J = 1 := by rw [isCoprime_iff_codisjoint, codisjoint_iff, add_eq_sup, one_eq_top] theorem isCoprime_iff_exists : IsCoprime I J ↔ ∃ i ∈ I, ∃ j ∈ J, i + j = 1 := by rw [← add_eq_one_iff, isCoprime_iff_add] theorem isCoprime_iff_sup_eq : IsCoprime I J ↔ I ⊔ J = ⊤ := by rw [isCoprime_iff_codisjoint, codisjoint_iff] theorem coprime_of_no_prime_ge {I J : Ideal R} (h : ∀ P, I ≤ P → J ≤ P → ¬IsPrime P) : IsCoprime I J := by rw [isCoprime_iff_sup_eq] by_contra hIJ obtain ⟨P, hP, hIJ⟩ := Ideal.exists_le_maximal _ hIJ exact h P (le_trans le_sup_left hIJ) (le_trans le_sup_right hIJ) hP.isPrime open List in theorem isCoprime_tfae : TFAE [IsCoprime I J, Codisjoint I J, I + J = 1, ∃ i ∈ I, ∃ j ∈ J, i + j = 1, I ⊔ J = ⊤] := by rw [← isCoprime_iff_codisjoint, ← isCoprime_iff_add, ← isCoprime_iff_exists, ← isCoprime_iff_sup_eq] simp theorem _root_.IsCoprime.codisjoint (h : IsCoprime I J) : Codisjoint I J := isCoprime_iff_codisjoint.mp h theorem _root_.IsCoprime.add_eq (h : IsCoprime I J) : I + J = 1 := isCoprime_iff_add.mp h theorem _root_.IsCoprime.exists (h : IsCoprime I J) : ∃ i ∈ I, ∃ j ∈ J, i + j = 1 := isCoprime_iff_exists.mp h theorem _root_.IsCoprime.sup_eq (h : IsCoprime I J) : I ⊔ J = ⊤ := isCoprime_iff_sup_eq.mp h theorem inf_eq_mul_of_isCoprime (coprime : IsCoprime I J) : I ⊓ J = I * J := (Ideal.mul_eq_inf_of_coprime coprime.sup_eq).symm theorem isCoprime_span_singleton_iff (x y : R) : IsCoprime (span <| singleton x) (span <| singleton y) ↔ IsCoprime x y := by simp_rw [isCoprime_iff_codisjoint, codisjoint_iff, eq_top_iff_one, mem_span_singleton_sup, mem_span_singleton] constructor · rintro ⟨a, _, ⟨b, rfl⟩, e⟩; exact ⟨a, b, mul_comm b y ▸ e⟩ · rintro ⟨a, b, e⟩; exact ⟨a, _, ⟨b, rfl⟩, mul_comm y b ▸ e⟩ theorem isCoprime_biInf {J : ι → Ideal R} {s : Finset ι} (hf : ∀ j ∈ s, IsCoprime I (J j)) : IsCoprime I (⨅ j ∈ s, J j) := by classical simp_rw [isCoprime_iff_add] at * induction s using Finset.induction with | empty => simp | insert i s _ hs => rw [Finset.iInf_insert, inf_comm, one_eq_top, eq_top_iff, ← one_eq_top] set K := ⨅ j ∈ s, J j calc 1 = I + K := (hs fun j hj ↦ hf j (Finset.mem_insert_of_mem hj)).symm _ = I + K*(I + J i) := by rw [hf i (Finset.mem_insert_self i s), mul_one] _ = (1+K)*I + K*J i := by ring _ ≤ I + K ⊓ J i := add_le_add mul_le_left mul_le_inf /-- The radical of an ideal `I` consists of the elements `r` such that `r ^ n ∈ I` for some `n`. -/ def radical (I : Ideal R) : Ideal R where carrier := { r | ∃ n : ℕ, r ^ n ∈ I } zero_mem' := ⟨1, (pow_one (0 : R)).symm ▸ I.zero_mem⟩ add_mem' := fun {_ _} ⟨m, hxmi⟩ ⟨n, hyni⟩ => ⟨m + n - 1, add_pow_add_pred_mem_of_pow_mem I hxmi hyni⟩ smul_mem' {r s} := fun ⟨n, h⟩ ↦ ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r ^ n) h⟩ theorem mem_radical_iff {r : R} : r ∈ I.radical ↔ ∃ n : ℕ, r ^ n ∈ I := Iff.rfl /-- An ideal is radical if it contains its radical. -/ def IsRadical (I : Ideal R) : Prop := I.radical ≤ I theorem le_radical : I ≤ radical I := fun r hri => ⟨1, (pow_one r).symm ▸ hri⟩ /-- An ideal is radical iff it is equal to its radical. -/ theorem radical_eq_iff : I.radical = I ↔ I.IsRadical := by rw [le_antisymm_iff, and_iff_left le_radical, IsRadical] alias ⟨_, IsRadical.radical⟩ := radical_eq_iff theorem isRadical_iff_pow_one_lt (k : ℕ) (hk : 1 < k) : I.IsRadical ↔ ∀ r, r ^ k ∈ I → r ∈ I := ⟨fun h _r hr ↦ h ⟨k, hr⟩, fun h x ⟨n, hx⟩ ↦ k.pow_imp_self_of_one_lt hk _ (fun _ _ ↦ .inr ∘ I.smul_mem _) h n x hx⟩ variable (R) in theorem radical_top : (radical ⊤ : Ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, Submodule.mem_top⟩ theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := fun _ ⟨n, hrni⟩ => ⟨n, H hrni⟩ variable (I) theorem radical_isRadical : (radical I).IsRadical := fun r ⟨n, k, hrnki⟩ => ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩ @[simp] theorem radical_idem : radical (radical I) = radical I := (radical_isRadical I).radical variable {I} theorem IsRadical.radical_le_iff (hJ : J.IsRadical) : I.radical ≤ J ↔ I ≤ J := ⟨le_trans le_radical, fun h => hJ.radical ▸ radical_mono h⟩ theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J := (radical_isRadical J).radical_le_iff theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨fun h => (eq_top_iff_one _).2 <| let ⟨n, hn⟩ := (eq_top_iff_one _).1 h @one_pow R _ n ▸ hn, fun h => h.symm ▸ radical_top R⟩ theorem IsPrime.isRadical (H : IsPrime I) : I.IsRadical := fun _ ⟨n, hrni⟩ => H.mem_of_pow_mem n hrni theorem IsPrime.radical (H : IsPrime I) : radical I = I := IsRadical.radical H.isRadical theorem mem_radical_of_pow_mem {I : Ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem disjoint_powers_iff_notMem (y : R) (hI : I.IsRadical) : Disjoint (Submonoid.powers y : Set R) ↑I ↔ y ∉ I.1 := by refine ⟨fun h => Set.disjoint_left.1 h (Submonoid.mem_powers _), fun h => disjoint_iff.mpr (eq_bot_iff.mpr ?_)⟩ rintro x ⟨⟨n, rfl⟩, hx'⟩ exact h (hI <| mem_radical_of_pow_mem <| le_radical hx') @[deprecated (since := "2025-05-23")] alias disjoint_powers_iff_not_mem := disjoint_powers_iff_notMem variable (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono <| sup_le_sup le_radical le_radical) <| radical_le_radical_iff.2 <| sup_le (radical_mono le_sup_left) (radical_mono le_sup_right) theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) fun r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩ => ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm, (pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩ variable {I J} in theorem IsRadical.inf (hI : IsRadical I) (hJ : IsRadical J) : IsRadical (I ⊓ J) := by rw [IsRadical, radical_inf]; exact inf_le_inf hI hJ lemma isRadical_bot_iff : (⊥ : Ideal R).IsRadical ↔ IsReduced R := by simp only [IsRadical, SetLike.le_def, Ideal.mem_radical_iff, Ideal.mem_bot, forall_exists_index, isReduced_iff, IsNilpotent] lemma isRadical_bot [IsReduced R] : (⊥ : Ideal R).IsRadical := by rwa [Ideal.isRadical_bot_iff] /-- `Ideal.radical` as an `InfTopHom`, bundling in that it distributes over `inf`. -/ def radicalInfTopHom : InfTopHom (Ideal R) (Ideal R) where toFun := radical map_inf' := radical_inf map_top' := radical_top _ @[simp] lemma radicalInfTopHom_apply (I : Ideal R) : radicalInfTopHom I = radical I := rfl open Finset in lemma radical_finset_inf {ι} {s : Finset ι} {f : ι → Ideal R} {i : ι} (hi : i ∈ s) (hs : ∀ ⦃y⦄, y ∈ s → (f y).radical = (f i).radical) : (s.inf f).radical = (f i).radical := by rw [← radicalInfTopHom_apply, map_finset_inf, ← Finset.inf'_eq_inf ⟨_, hi⟩] exact Finset.inf'_eq_of_forall _ _ hs /-- The reverse inclusion does not hold for e.g. `I := fun n : ℕ ↦ Ideal.span {(2 ^ n : ℤ)}`. -/ theorem radical_iInf_le {ι} (I : ι → Ideal R) : radical (⨅ i, I i) ≤ ⨅ i, radical (I i) := le_iInf fun _ ↦ radical_mono (iInf_le _ _) theorem isRadical_iInf {ι} (I : ι → Ideal R) (hI : ∀ i, IsRadical (I i)) : IsRadical (⨅ i, I i) := (radical_iInf_le I).trans (iInf_mono hI) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := by refine le_antisymm ?_ fun r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩ => ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩ have := radical_mono <| @mul_le_inf _ _ I J simp_rw [radical_inf I J] at this assumption variable {I J} theorem IsPrime.radical_le_iff (hJ : IsPrime J) : I.radical ≤ J ↔ I ≤ J := IsRadical.radical_le_iff hJ.isRadical theorem radical_eq_sInf (I : Ideal R) : radical I = sInf { J : Ideal R | I ≤ J ∧ IsPrime J } := le_antisymm (le_sInf fun _ hJ ↦ hJ.2.radical_le_iff.2 hJ.1) fun r hr ↦ by_contradiction fun hri ↦ let ⟨m, hIm, hm⟩ := zorn_le_nonempty₀ { K : Ideal R | r ∉ radical K } (fun c hc hcc y hyc => ⟨sSup c, fun ⟨n, hrnc⟩ => let ⟨_, hyc, hrny⟩ := (Submodule.mem_sSup_of_directed ⟨y, hyc⟩ hcc.directedOn).1 hrnc hc hyc ⟨n, hrny⟩, fun _ => le_sSup⟩) I hri have hrm : r ∉ radical m := hm.prop have : ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := fun x hxm => by_contradiction fun hrmx => hxm <| by rw [hm.eq_of_le hrmx le_sup_left] exact Submodule.mem_sup_right <| mem_span_singleton_self x have : IsPrime m := ⟨by rintro rfl; rw [radical_top] at hrm; exact hrm trivial, fun {x y} hxym => or_iff_not_imp_left.2 fun hxm => by_contradiction fun hym => let ⟨n, hrn⟩ := this _ hxm let ⟨p, hpm, q, hq, hpqrn⟩ := Submodule.mem_sup.1 hrn let ⟨c, hcxq⟩ := mem_span_singleton'.1 hq let ⟨k, hrk⟩ := this _ hym let ⟨f, hfm, g, hg, hfgrk⟩ := Submodule.mem_sup.1 hrk let ⟨d, hdyg⟩ := mem_span_singleton'.1 hg hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c * x), mul_assoc c x (d * y), mul_left_comm x, ← mul_assoc] refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm) (m.mul_mem_left _ hxym))⟩⟩ hrm <| this.radical.symm ▸ (sInf_le ⟨hIm, this⟩ : sInf { J : Ideal R | I ≤ J ∧ IsPrime J } ≤ m) hr theorem isRadical_bot_of_noZeroDivisors {R} [CommSemiring R] [NoZeroDivisors R] : (⊥ : Ideal R).IsRadical := fun _ hx => hx.recOn fun _ hn => pow_eq_zero hn @[simp] theorem radical_bot_of_noZeroDivisors {R : Type u} [CommSemiring R] [NoZeroDivisors R] : radical (⊥ : Ideal R) = ⊥ := eq_bot_iff.2 isRadical_bot_of_noZeroDivisors instance : IdemCommSemiring (Ideal R) := inferInstance variable (R) in theorem top_pow (n : ℕ) : (⊤ ^ n : Ideal R) = ⊤ := Nat.recOn n one_eq_top fun n ih => by rw [pow_succ, ih, top_mul] theorem natCast_eq_top {n : ℕ} (hn : n ≠ 0) : (n : Ideal R) = ⊤ := natCast_eq_one hn |>.trans one_eq_top /-- `3 : Ideal R` is *not* the ideal generated by 3 (which would be spelt `Ideal.span {3}`), it is simply `1 + 1 + 1 = ⊤`. -/ theorem ofNat_eq_top {n : ℕ} [n.AtLeastTwo] : (ofNat(n) : Ideal R) = ⊤ := ofNat_eq_one.trans one_eq_top variable (I) lemma radical_pow : ∀ {n}, n ≠ 0 → radical (I ^ n) = radical I | 1, _ => by simp | n + 2, _ => by rw [pow_succ, radical_mul, radical_pow n.succ_ne_zero, inf_idem] theorem IsPrime.mul_le {I J P : Ideal R} (hp : IsPrime P) : I * J ≤ P ↔ I ≤ P ∨ J ≤ P := by rw [or_comm, Ideal.mul_le] simp_rw [hp.mul_mem_iff_mem_or_mem, SetLike.le_def, ← forall_or_left, or_comm, forall_or_left] theorem IsPrime.inf_le {I J P : Ideal R} (hp : IsPrime P) : I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨fun h ↦ hp.mul_le.1 <| mul_le_inf.trans h, fun h ↦ h.elim inf_le_left.trans inf_le_right.trans⟩ theorem IsPrime.multiset_prod_le {s : Multiset (Ideal R)} {P : Ideal R} (hp : IsPrime P) : s.prod ≤ P ↔ ∃ I ∈ s, I ≤ P := s.induction_on (by simp [hp.ne_top]) fun I s ih ↦ by simp [hp.mul_le, ih] theorem IsPrime.multiset_prod_map_le {s : Multiset ι} (f : ι → Ideal R) {P : Ideal R} (hp : IsPrime P) : (s.map f).prod ≤ P ↔ ∃ i ∈ s, f i ≤ P := by simp_rw [hp.multiset_prod_le, Multiset.mem_map, exists_exists_and_eq_and] theorem IsPrime.multiset_prod_mem_iff_exists_mem {I : Ideal R} (hI : I.IsPrime) (s : Multiset R) : s.prod ∈ I ↔ ∃ p ∈ s, p ∈ I := by simpa [span_singleton_le_iff_mem] using (hI.multiset_prod_map_le (span {·})) theorem IsPrime.pow_le_iff {I P : Ideal R} [hP : P.IsPrime] {n : ℕ} (hn : n ≠ 0) : I ^ n ≤ P ↔ I ≤ P := by have h : (Multiset.replicate n I).prod ≤ P ↔ _ := hP.multiset_prod_le simp_rw [Multiset.prod_replicate, Multiset.mem_replicate, ne_eq, hn, not_false_eq_true, true_and, exists_eq_left] at h exact h theorem IsPrime.le_of_pow_le {I P : Ideal R} [hP : P.IsPrime] {n : ℕ} (h : I ^ n ≤ P) : I ≤ P := by by_cases hn : n = 0 · rw [hn, pow_zero, one_eq_top] at h exact fun ⦃_⦄ _ ↦ h Submodule.mem_top · exact (pow_le_iff hn).mp h theorem IsPrime.prod_le {s : Finset ι} {f : ι → Ideal R} {P : Ideal R} (hp : IsPrime P) : s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P := hp.multiset_prod_map_le f /-- The product of a finite number of elements in the commutative semiring `R` lies in the prime ideal `p` if and only if at least one of those elements is in `p`. -/ theorem IsPrime.prod_mem_iff {s : Finset ι} {x : ι → R} {p : Ideal R} [hp : p.IsPrime] : ∏ i ∈ s, x i ∈ p ↔ ∃ i ∈ s, x i ∈ p := by simp_rw [← span_singleton_le_iff_mem, ← prod_span_singleton] exact hp.prod_le theorem IsPrime.prod_mem_iff_exists_mem {I : Ideal R} (hI : I.IsPrime) (s : Finset R) : s.prod (fun x ↦ x) ∈ I ↔ ∃ p ∈ s, p ∈ I := by rw [Finset.prod_eq_multiset_prod, Multiset.map_id'] exact hI.multiset_prod_mem_iff_exists_mem s.val theorem IsPrime.inf_le' {s : Finset ι} {f : ι → Ideal R} {P : Ideal R} (hp : IsPrime P) : s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P := ⟨fun h ↦ hp.prod_le.1 <| prod_le_inf.trans h, fun ⟨_, his, hip⟩ ↦ (Finset.inf_le his).trans hip⟩ -- Porting note: needed to add explicit coercions (· : Set R). theorem subset_union {R : Type u} [Ring R] {I J K : Ideal R} : (I : Set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K := AddSubgroupClass.subset_union theorem subset_union_prime' {R : Type u} [CommRing R] {s : Finset ι} {f : ι → Ideal R} {a b : ι} (hp : ∀ i ∈ s, IsPrime (f i)) {I : Ideal R} : ((I : Set R) ⊆ f a ∪ f b ∪ ⋃ i ∈ (↑s : Set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i := by suffices ((I : Set R) ⊆ f a ∪ f b ∪ ⋃ i ∈ (↑s : Set ι), f i) → I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i from ⟨this, fun h => Or.casesOn h (fun h => Set.Subset.trans h <| Set.Subset.trans Set.subset_union_left Set.subset_union_left) fun h => Or.casesOn h (fun h => Set.Subset.trans h <| Set.Subset.trans Set.subset_union_right Set.subset_union_left) fun ⟨i, his, hi⟩ => by refine Set.Subset.trans hi <| Set.Subset.trans ?_ Set.subset_union_right exact Set.subset_biUnion_of_mem (u := fun x ↦ (f x : Set R)) (Finset.mem_coe.2 his)⟩ generalize hn : s.card = n; intro h induction' n with n ih generalizing a b s · clear hp rw [Finset.card_eq_zero] at hn subst hn rw [Finset.coe_empty, Set.biUnion_empty, Set.union_empty, subset_union] at h simpa only [exists_prop, Finset.notMem_empty, false_and, exists_false, or_false] classical replace hn : ∃ (i : ι) (t : Finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n := Finset.card_eq_succ.1 hn rcases hn with ⟨i, t, hit, rfl, hn⟩ replace hp : IsPrime (f i) ∧ ∀ x ∈ t, IsPrime (f x) := (t.forall_mem_insert _ _).1 hp by_cases Ht : ∃ j ∈ t, f j ≤ f i · obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t := ⟨t.erase j, t.notMem_erase j, Finset.insert_erase hjt⟩ have hp' : ∀ k ∈ insert i u, IsPrime (f k) := by rw [Finset.forall_mem_insert] at hp ⊢ exact ⟨hp.1, hp.2.2⟩ have hiu : i ∉ u := mt Finset.mem_insert_of_mem hit have hn' : (insert i u).card = n := by rwa [Finset.card_insert_of_notMem] at hn ⊢ exacts [hiu, hju] have h' : (I : Set R) ⊆ f a ∪ f b ∪ ⋃ k ∈ (↑(insert i u) : Set ι), f k := by rw [Finset.coe_insert] at h ⊢ rw [Finset.coe_insert] at h simp only [Set.biUnion_insert] at h ⊢ rw [← Set.union_assoc (f i : Set R), Set.union_eq_self_of_subset_right hfji] at h exact h specialize ih hp' hn' h' refine ih.imp id (Or.imp id (Exists.imp fun k => ?_)) exact And.imp (fun hk => Finset.insert_subset_insert i (Finset.subset_insert j u) hk) id by_cases Ha : f a ≤ f i · have h' : (I : Set R) ⊆ f i ∪ f b ∪ ⋃ j ∈ (↑t : Set ι), f j := by rw [Finset.coe_insert, Set.biUnion_insert, ← Set.union_assoc, Set.union_right_comm (f a : Set R), Set.union_eq_self_of_subset_left Ha] at h exact h specialize ih hp.2 hn h' right rcases ih with (ih | ih | ⟨k, hkt, ih⟩) · exact Or.inr ⟨i, Finset.mem_insert_self i t, ih⟩ · exact Or.inl ih · exact Or.inr ⟨k, Finset.mem_insert_of_mem hkt, ih⟩ by_cases Hb : f b ≤ f i · have h' : (I : Set R) ⊆ f a ∪ f i ∪ ⋃ j ∈ (↑t : Set ι), f j := by rw [Finset.coe_insert, Set.biUnion_insert, ← Set.union_assoc, Set.union_assoc (f a : Set R), Set.union_eq_self_of_subset_left Hb] at h exact h specialize ih hp.2 hn h' rcases ih with (ih | ih | ⟨k, hkt, ih⟩) · exact Or.inl ih · exact Or.inr (Or.inr ⟨i, Finset.mem_insert_self i t, ih⟩) · exact Or.inr (Or.inr ⟨k, Finset.mem_insert_of_mem hkt, ih⟩) by_cases Hi : I ≤ f i · exact Or.inr (Or.inr ⟨i, Finset.mem_insert_self i t, Hi⟩) have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i := by simp only [hp.1.inf_le, hp.1.inf_le', not_or] exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ rcases Set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩ by_cases HI : (I : Set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : Set ι), f j · specialize ih hp.2 hn HI rcases ih with (ih | ih | ⟨k, hkt, ih⟩) · left exact ih · right left exact ih · right right exact ⟨k, Finset.mem_insert_of_mem hkt, ih⟩ exfalso rcases Set.not_subset.1 HI with ⟨s, hsI, hs⟩ rw [Finset.coe_insert, Set.biUnion_insert] at h have hsi : s ∈ f i := ((h hsI).resolve_left (mt Or.inl hs)).resolve_right (mt Or.inr hs) rcases h (I.add_mem hrI hsI) with (⟨ha | hb⟩ | hi | ht) · exact hs (Or.inl <| Or.inl <| add_sub_cancel_left r s ▸ (f a).sub_mem ha hra) · exact hs (Or.inl <| Or.inr <| add_sub_cancel_left r s ▸ (f b).sub_mem hb hrb) · exact hri (add_sub_cancel_right r s ▸ (f i).sub_mem hi hsi) · rw [Set.mem_iUnion₂] at ht rcases ht with ⟨j, hjt, hj⟩ simp only [Finset.inf_eq_iInf, SetLike.mem_coe, Submodule.mem_iInf] at hr exact hs <| Or.inr <| Set.mem_biUnion hjt <| add_sub_cancel_left r s ▸ (f j).sub_mem hj <| hr j hjt /-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Matsumura Ex.1.6. -/ @[stacks 00DS] theorem subset_union_prime {R : Type u} [CommRing R] {s : Finset ι} {f : ι → Ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → IsPrime (f i)) {I : Ideal R} : ((I : Set R) ⊆ ⋃ i ∈ (↑s : Set ι), f i) ↔ ∃ i ∈ s, I ≤ f i := suffices ((I : Set R) ⊆ ⋃ i ∈ (↑s : Set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i by have aux := fun h => (bex_def.2 <| this h) simp_rw [exists_prop] at aux refine ⟨aux, fun ⟨i, his, hi⟩ ↦ Set.Subset.trans hi ?_⟩ apply Set.subset_biUnion_of_mem (show i ∈ (↑s : Set ι) from his) fun h : (I : Set R) ⊆ ⋃ i ∈ (↑s : Set ι), f i => by classical by_cases has : a ∈ s · obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s := ⟨s.erase a, Finset.notMem_erase a s, Finset.insert_erase has⟩ by_cases hbt : b ∈ t · obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t := ⟨t.erase b, Finset.notMem_erase b t, Finset.insert_erase hbt⟩ have hp' : ∀ i ∈ u, IsPrime (f i) := by intro i hiu refine hp i (Finset.mem_insert_of_mem (Finset.mem_insert_of_mem hiu)) ?_ ?_ <;> rintro rfl <;> solve_by_elim only [Finset.mem_insert_of_mem, *] rw [Finset.coe_insert, Finset.coe_insert, Set.biUnion_insert, Set.biUnion_insert, ← Set.union_assoc, subset_union_prime' hp'] at h rwa [Finset.exists_mem_insert, Finset.exists_mem_insert] · have hp' : ∀ j ∈ t, IsPrime (f j) := by intro j hj refine hp j (Finset.mem_insert_of_mem hj) ?_ ?_ <;> rintro rfl <;> solve_by_elim only [Finset.mem_insert_of_mem, *] rw [Finset.coe_insert, Set.biUnion_insert, ← Set.union_self (f a : Set R), subset_union_prime' hp', ← or_assoc, or_self_iff] at h rwa [Finset.exists_mem_insert] · by_cases hbs : b ∈ s · obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s := ⟨s.erase b, Finset.notMem_erase b s, Finset.insert_erase hbs⟩ have hp' : ∀ j ∈ t, IsPrime (f j) := by intro j hj refine hp j (Finset.mem_insert_of_mem hj) ?_ ?_ <;> rintro rfl <;> solve_by_elim only [Finset.mem_insert_of_mem, *] rw [Finset.coe_insert, Set.biUnion_insert, ← Set.union_self (f b : Set R), subset_union_prime' hp', ← or_assoc, or_self_iff] at h rwa [Finset.exists_mem_insert] rcases s.eq_empty_or_nonempty with hse | hsne · subst hse rw [Finset.coe_empty, Set.biUnion_empty, Set.subset_empty_iff] at h have : (I : Set R) ≠ ∅ := Set.Nonempty.ne_empty (Set.nonempty_of_mem I.zero_mem) exact absurd h this · obtain ⟨i, his⟩ := hsne obtain ⟨t, _, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s := ⟨s.erase i, Finset.notMem_erase i s, Finset.insert_erase his⟩ have hp' : ∀ j ∈ t, IsPrime (f j) := by intro j hj refine hp j (Finset.mem_insert_of_mem hj) ?_ ?_ <;> rintro rfl <;> solve_by_elim only [Finset.mem_insert_of_mem, *] rw [Finset.coe_insert, Set.biUnion_insert, ← Set.union_self (f i : Set R), subset_union_prime' hp', ← or_assoc, or_self_iff] at h rwa [Finset.exists_mem_insert] /-- Another version of prime avoidance using `Set.Finite` instead of `Finset`. -/ lemma subset_union_prime_finite {R ι : Type*} [CommRing R] {s : Set ι} (hs : s.Finite) {f : ι → Ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → (f i).IsPrime) {I : Ideal R} : ((I : Set R) ⊆ ⋃ i ∈ s, f i) ↔ ∃ i ∈ s, I ≤ f i := by rcases Set.Finite.exists_finset hs with ⟨t, ht⟩ have heq : ⋃ i ∈ s, f i = ⋃ i ∈ t, (f i : Set R) := by ext simpa using exists_congr (fun i ↦ (and_congr_left fun a ↦ ht i).symm) have hmem_union : ((I : Set R) ⊆ ⋃ i ∈ s, f i) ↔ ((I : Set R) ⊆ ⋃ i ∈ (t : Set ι), f i) := (congrArg _ heq).to_iff rw [hmem_union, Ideal.subset_union_prime a b (fun i hin ↦ hp i ((ht i).mp hin))] exact exists_congr (fun i ↦ and_congr_left fun _ ↦ ht i) section Dvd /-- If `I` divides `J`, then `I` contains `J`. In a Dedekind domain, to divide and contain are equivalent, see `Ideal.dvd_iff_le`. -/ theorem le_of_dvd {I J : Ideal R} : I ∣ J → J ≤ I | ⟨_, h⟩ => h.symm ▸ le_trans mul_le_inf inf_le_left /-- See also `isUnit_iff_eq_one`. -/ @[simp high] theorem isUnit_iff {I : Ideal R} : IsUnit I ↔ I = ⊤ := isUnit_iff_dvd_one.trans ((@one_eq_top R _).symm ▸ ⟨fun h => eq_top_iff.mpr (Ideal.le_of_dvd h), fun h => ⟨⊤, by rw [mul_top, h]⟩⟩) instance uniqueUnits : Unique (Ideal R)ˣ where default := 1 uniq u := Units.ext (show (u : Ideal R) = 1 by rw [isUnit_iff.mp u.isUnit, one_eq_top]) end Dvd end MulAndRadical section Total variable (ι : Type*) variable (M : Type*) [AddCommGroup M] {R : Type*} [CommRing R] [Module R M] (I : Ideal R) variable (v : ι → M) (hv : Submodule.span R (Set.range v) = ⊤) /-- A variant of `Finsupp.linearCombination` that takes in vectors valued in `I`. -/ noncomputable def finsuppTotal : (ι →₀ I) →ₗ[R] M := (Finsupp.linearCombination R v).comp (Finsupp.mapRange.linearMap I.subtype) variable {ι M v} theorem finsuppTotal_apply (f : ι →₀ I) : finsuppTotal ι M I v f = f.sum fun i x => (x : R) • v i := by dsimp [finsuppTotal] rw [Finsupp.linearCombination_apply, Finsupp.sum_mapRange_index] exact fun _ => zero_smul _ _ theorem finsuppTotal_apply_eq_of_fintype [Fintype ι] (f : ι →₀ I) : finsuppTotal ι M I v f = ∑ i, (f i : R) • v i := by rw [finsuppTotal_apply, Finsupp.sum_fintype] exact fun _ => zero_smul _ _ theorem range_finsuppTotal : LinearMap.range (finsuppTotal ι M I v) = I • Submodule.span R (Set.range v) := by ext rw [Submodule.mem_ideal_smul_span_iff_exists_sum] refine ⟨fun ⟨f, h⟩ => ⟨Finsupp.mapRange.linearMap I.subtype f, fun i => (f i).2, h⟩, ?_⟩ rintro ⟨a, ha, rfl⟩ classical refine ⟨a.mapRange (fun r => if h : r ∈ I then ⟨r, h⟩ else 0) (by simp only [Submodule.zero_mem, ↓reduceDIte]; rfl), ?_⟩ rw [finsuppTotal_apply, Finsupp.sum_mapRange_index] · apply Finsupp.sum_congr intro i _ rw [dif_pos (ha i)] · exact fun _ => zero_smul _ _ end Total end Ideal section span_range variable {α R : Type*} [Semiring R] theorem Finsupp.mem_ideal_span_range_iff_exists_finsupp {x : R} {v : α → R} : x ∈ Ideal.span (Set.range v) ↔ ∃ c : α →₀ R, (c.sum fun i a => a * v i) = x := Finsupp.mem_span_range_iff_exists_finsupp /-- An element `x` lies in the span of `v` iff it can be written as sum `∑ cᵢ • vᵢ = x`. -/ theorem Ideal.mem_span_range_iff_exists_fun [Fintype α] {x : R} {v : α → R} : x ∈ Ideal.span (Set.range v) ↔ ∃ c : α → R, ∑ i, c i * v i = x := Submodule.mem_span_range_iff_exists_fun _ @[deprecated (since := "2025-04-02")] alias mem_ideal_span_range_iff_exists_fun := Ideal.mem_span_range_iff_exists_fun end span_range theorem Associates.mk_ne_zero' {R : Type*} [CommSemiring R] {r : R} : Associates.mk (Ideal.span {r} : Ideal R) ≠ 0 ↔ r ≠ 0 := by rw [Associates.mk_ne_zero, Ideal.zero_eq_bot, Ne, Ideal.span_singleton_eq_bot] open scoped nonZeroDivisors in theorem Ideal.span_singleton_nonZeroDivisors {R : Type*} [CommSemiring R] [NoZeroDivisors R] {r : R} : span {r} ∈ (Ideal R)⁰ ↔ r ∈ R⁰ := by cases subsingleton_or_nontrivial R · simp_rw [← nonZeroDivisorsRight_eq_nonZeroDivisors] exact ⟨fun _ _ _ ↦ Subsingleton.eq_zero _, fun _ _ _ ↦ Subsingleton.eq_zero _⟩ · rw [mem_nonZeroDivisors_iff_ne_zero, mem_nonZeroDivisors_iff_ne_zero, ne_eq, zero_eq_bot, span_singleton_eq_bot] theorem Ideal.primeCompl_le_nonZeroDivisors {R : Type*} [CommSemiring R] [NoZeroDivisors R] (P : Ideal R) [P.IsPrime] : P.primeCompl ≤ nonZeroDivisors R := le_nonZeroDivisors_of_noZeroDivisors <| not_not_intro P.zero_mem namespace Submodule variable {R : Type u} {M : Type v} variable [CommSemiring R] [AddCommMonoid M] [Module R M] instance moduleSubmodule : Module (Ideal R) (Submodule R M) where smul_add := smul_sup add_smul := sup_smul mul_smul := Submodule.mul_smul one_smul := by simp zero_smul := bot_smul smul_zero := smul_bot lemma span_smul_eq (s : Set R) (N : Submodule R M) : Ideal.span s • N = s • N := by rw [← coe_set_smul, coe_span_smul] @[simp] theorem set_smul_top_eq_span (s : Set R) : s • ⊤ = Ideal.span s := (span_smul_eq s ⊤).symm.trans (Ideal.span s).mul_top lemma smul_le_span (s : Set R) (I : Ideal R) : s • I ≤ Ideal.span s := by simp [← Submodule.set_smul_top_eq_span, smul_le_smul_left] variable {A B} [Semiring A] [Semiring B] [Algebra R A] [Algebra R B] open Submodule instance algebraIdeal : Algebra (Ideal R) (Submodule R A) where __ := moduleSubmodule algebraMap := { toFun := map (Algebra.linearMap R A) map_one' := by rw [one_eq_span, map_span, Set.image_singleton, Algebra.linearMap_apply, map_one, one_eq_span] map_mul' := (Submodule.map_mul · · <| Algebra.ofId R A) map_zero' := map_bot _ map_add' := (map_sup · · _) } commutes' I M := mul_comm_of_commute <| by rintro _ ⟨r, _, rfl⟩ a _; apply Algebra.commutes smul_def' I M := le_antisymm (smul_le.mpr fun r hr a ha ↦ by rw [Algebra.smul_def]; exact Submodule.mul_mem_mul ⟨r, hr, rfl⟩ ha) (Submodule.mul_le.mpr <| by rintro _ ⟨r, hr, rfl⟩ a ha; rw [Algebra.linearMap_apply, ← Algebra.smul_def] exact Submodule.smul_mem_smul hr ha) /-- `Submonoid.map` as an `AlgHom`, when applied to an `AlgHom`. -/ @[simps!] def mapAlgHom (f : A →ₐ[R] B) : Submodule R A →ₐ[Ideal R] Submodule R B where __ := mapHom f commutes' I := (map_comp _ _ I).symm.trans (congr_arg (map · I) <| LinearMap.ext f.commutes) /-- `Submonoid.map` as an `AlgEquiv`, when applied to an `AlgEquiv`. -/ -- TODO: when A, B noncommutative, still has `MulEquiv`. @[simps!] def mapAlgEquiv (f : A ≃ₐ[R] B) : Submodule R A ≃ₐ[Ideal R] Submodule R B where __ := mapAlgHom f invFun := mapAlgHom f.symm left_inv I := (map_comp _ _ I).symm.trans <| (congr_arg (map · I) <| LinearMap.ext (f.left_inv ·)).trans (map_id I) right_inv I := (map_comp _ _ I).symm.trans <| (congr_arg (map · I) <| LinearMap.ext (f.right_inv ·)).trans (map_id I) end Submodule instance {R} [Semiring R] : NonUnitalSubsemiringClass (Ideal R) R where mul_mem _ hb := Ideal.mul_mem_left _ _ hb instance {R} [Ring R] : NonUnitalSubringClass (Ideal R) R where lemma Ideal.exists_subset_radical_span_sup_of_subset_radical_sup {R : Type*} [CommSemiring R] (s : Set R) (I J : Ideal R) (hs : s ⊆ (I ⊔ J).radical) : ∃ (t : s → R), Set.range t ⊆ I ∧ s ⊆ (span (Set.range t) ⊔ J).radical := by replace hs : ∀ z : s, ∃ (m : ℕ) (a b : R) (ha : a ∈ I) (hb : b ∈ J), a + b = z ^ m := by rintro ⟨z, hzs⟩ simp only [Ideal.radical, Submodule.mem_sup] at hs obtain ⟨m, y, hyq, b, hb, hy⟩ := hs hzs exact ⟨m, y, b, hyq, hb, hy⟩ choose m a b ha hb heq using hs refine ⟨a, by rwa [Set.range_subset_iff], fun z hz ↦ ⟨m ⟨z, hz⟩, heq ⟨z, hz⟩ ▸ ?_⟩⟩ exact Ideal.add_mem _ (mem_sup_left (subset_span ⟨⟨z, hz⟩, rfl⟩)) (mem_sup_right <| hb _) @[deprecated (since := "2025-05-13")] alias Ideal.exists_subset_radical_span_sup_span_of_subset_radical_sup := Ideal.exists_subset_radical_span_sup_of_subset_radical_sup
Basic.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, Jens Wagemaker, Aaron Anderson -/ import Mathlib.Algebra.EuclideanDomain.Basic import Mathlib.Algebra.EuclideanDomain.Int import Mathlib.Algebra.GCDMonoid.Nat import Mathlib.Data.Nat.Prime.Int import Mathlib.RingTheory.PrincipalIdealDomain /-! # Divisibility over ℤ This file collects results for the integers that use ring theory in their proofs or cases of ℤ being examples of structures in ring theory. ## Main statements * `Int.Prime.dvd_mul'`: A prime number dividing a product in ℤ divides at least one factor. * `Int.exists_prime_and_dvd`: Every non-unit integer has a prime divisor. * `Int.prime_iff_natAbs_prime`: Primality in ℤ corresponds to primality of its absolute value in ℕ. * `Int.span_natAbs`: The principal ideal generated by `a.natAbs` is equal to that of `a`. ## Tags prime, irreducible, integers, normalization monoid, gcd monoid, greatest common divisor -/ namespace Int theorem isCoprime_iff_nat_coprime {a b : ℤ} : IsCoprime a b ↔ Nat.Coprime a.natAbs b.natAbs := by rw [isCoprime_iff_gcd_eq_one, Nat.coprime_iff_gcd_eq_one, gcd_eq_natAbs] /-- If `gcd a (m * n) ≠ 1`, then `gcd a m ≠ 1` or `gcd a n ≠ 1`. -/ theorem gcd_ne_one_iff_gcd_mul_right_ne_one {a : ℤ} {m n : ℕ} : a.gcd (m * n) ≠ 1 ↔ a.gcd m ≠ 1 ∨ a.gcd n ≠ 1 := by simp only [← isCoprime_iff_gcd_eq_one, ← not_and_or, not_iff_not, IsCoprime.mul_right_iff] theorem sq_of_gcd_eq_one {a b c : ℤ} (h : Int.gcd a b = 1) (heq : a * b = c ^ 2) : ∃ a0 : ℤ, a = a0 ^ 2 ∨ a = -a0 ^ 2 := by have h' : IsUnit (GCDMonoid.gcd a b) := by rw [← coe_gcd, h, Int.ofNat_one] exact isUnit_one obtain ⟨d, ⟨u, hu⟩⟩ := exists_associated_pow_of_mul_eq_pow h' heq use d rw [← hu] rcases Int.units_eq_one_or u with hu' | hu' <;> · rw [hu'] simp theorem sq_of_isCoprime {a b c : ℤ} (h : IsCoprime a b) (heq : a * b = c ^ 2) : ∃ a0 : ℤ, a = a0 ^ 2 ∨ a = -a0 ^ 2 := sq_of_gcd_eq_one (isCoprime_iff_gcd_eq_one.mp h) heq theorem natAbs_euclideanDomain_gcd (a b : ℤ) : Int.natAbs (EuclideanDomain.gcd a b) = Int.gcd a b := by apply Nat.dvd_antisymm <;> rw [← Int.natCast_dvd_natCast] · rw [Int.natAbs_dvd] exact Int.dvd_coe_gcd (EuclideanDomain.gcd_dvd_left _ _) (EuclideanDomain.gcd_dvd_right _ _) · rw [Int.dvd_natAbs] exact EuclideanDomain.dvd_gcd (Int.gcd_dvd_left ..) (Int.gcd_dvd_right ..) end Int theorem Int.Prime.dvd_mul {m n : ℤ} {p : ℕ} (hp : Nat.Prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.natAbs ∨ p ∣ n.natAbs := by rwa [← hp.dvd_mul, ← Int.natAbs_mul, ← Int.natCast_dvd] theorem Int.Prime.dvd_mul' {m n : ℤ} {p : ℕ} (hp : Nat.Prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n := by rw [Int.natCast_dvd, Int.natCast_dvd] exact Int.Prime.dvd_mul hp h theorem Int.Prime.dvd_pow {n : ℤ} {k p : ℕ} (hp : Nat.Prime p) (h : (p : ℤ) ∣ n ^ k) : p ∣ n.natAbs := by rw [Int.natCast_dvd, Int.natAbs_pow] at h exact hp.dvd_of_dvd_pow h theorem Int.Prime.dvd_pow' {n : ℤ} {k p : ℕ} (hp : Nat.Prime p) (h : (p : ℤ) ∣ n ^ k) : (p : ℤ) ∣ n := by rw [Int.natCast_dvd] exact Int.Prime.dvd_pow hp h theorem prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ} (hp : Nat.Prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ Int.natAbs m := by rcases Int.Prime.dvd_mul hp h with hp2 | hpp · apply Or.intro_left exact le_antisymm (Nat.le_of_dvd zero_lt_two hp2) (Nat.Prime.two_le hp) · apply Or.intro_right rw [sq, Int.natAbs_mul] at hpp exact or_self_iff.mp ((Nat.Prime.dvd_mul hp).mp hpp) theorem Int.exists_prime_and_dvd {n : ℤ} (hn : n.natAbs ≠ 1) : ∃ p, Prime p ∧ p ∣ n := by obtain ⟨p, pp, pd⟩ := Nat.exists_prime_and_dvd hn exact ⟨p, Nat.prime_iff_prime_int.mp pp, Int.natCast_dvd.mpr pd⟩ theorem Int.prime_iff_natAbs_prime {k : ℤ} : Prime k ↔ Nat.Prime k.natAbs := (Int.associated_natAbs k).prime_iff.trans Nat.prime_iff_prime_int.symm namespace Int theorem span_natAbs (a : ℤ) : Ideal.span ({(a.natAbs : ℤ)} : Set ℤ) = Ideal.span {a} := by rw [Ideal.span_singleton_eq_span_singleton] exact (associated_natAbs _).symm theorem eq_pow_of_mul_eq_pow_odd_left {a b c : ℤ} (hab : IsCoprime a b) {k : ℕ} (hk : Odd k) (h : a * b = c ^ k) : ∃ d, a = d ^ k := by obtain ⟨d, hd⟩ := exists_associated_pow_of_mul_eq_pow' hab h replace hd := hd.symm rw [associated_iff_natAbs, natAbs_eq_natAbs_iff, ← hk.neg_pow] at hd obtain rfl | rfl := hd <;> exact ⟨_, rfl⟩ theorem eq_pow_of_mul_eq_pow_odd_right {a b c : ℤ} (hab : IsCoprime a b) {k : ℕ} (hk : Odd k) (h : a * b = c ^ k) : ∃ d, b = d ^ k := eq_pow_of_mul_eq_pow_odd_left (c := c) hab.symm hk (by rwa [mul_comm] at h) theorem eq_pow_of_mul_eq_pow_odd {a b c : ℤ} (hab : IsCoprime a b) {k : ℕ} (hk : Odd k) (h : a * b = c ^ k) : (∃ d, a = d ^ k) ∧ ∃ e, b = e ^ k := ⟨eq_pow_of_mul_eq_pow_odd_left hab hk h, eq_pow_of_mul_eq_pow_odd_right hab hk h⟩ end Int
spectral.v
From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype choice ssrnat. From mathcomp Require Import seq div fintype bigop ssralg finset fingroup zmodp. From mathcomp Require Import poly polydiv order ssrnum matrix mxalgebra vector. From mathcomp Require Import mxpoly mxred sesquilinear. (******************************************************************************) (* Spectral theory *) (* *) (* This file provides a formalization of Gram-Schmidt orthonormalization, *) (* Schur decomposition, etc. *) (* *) (* M ^t* := M ^t conjC *) (* Notation in scope sesquilinear_scope. *) (* M \is unitarymx == M is a unitary matrix *) (* M : 'M[C]_(m, n) with C : numClosedFieldType *) (* M \is normalmx == M is a normal matrix *) (* M : 'M[C]_n with C : numClosedFieldType *) (* *) (* dotmx u v == dot product *) (* u and v are row vectors over a numClosedFieldType *) (* Local notations: '[u, v] := dotmx u v, *) (* '[u] := '[u, u] *) (* proj_ortho Y := proj_mx <<U>>%MS U^!%MS *) (* where U^! is a 1-orthogonal completement of U *) (* schmidt A == Gram-Schmidt basis *) (* A : 'M[C]_(m, n) *) (* schmidt_complete V := col_mx (schmidt (row_base V)) *) (* (schmidt (row_base V^!%MS)) *) (* spectralmx A, spectral_diag A == (M,X) s.t. A = M^-1 *m diag_mx X *m M *) (* A : 'M[C]_n *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GRing.Theory Order.Theory Num.Theory. Local Open Scope ring_scope. Local Open Scope sesquilinear_scope. (* TODO: move? *) Lemma eigenvalue_closed {C : numClosedFieldType} n (A : 'M[C]_n) : (n > 0)%N -> exists a, eigenvalue A a. Proof. move=> n_gt0; have /closed_rootP [a rAa] : size (char_poly A) != 1%N. by rewrite size_char_poly; case: (n) n_gt0. by exists a; rewrite eigenvalue_root_char. Qed. (* TODO: move? *) Lemma common_eigenvector {C : numClosedFieldType} n (As : seq 'M[C]_n) : (n > 0)%N -> {in As &, forall A B, comm_mx A B} -> exists2 v : 'rV_n, v != 0 & all (fun A => stablemx v A) As. Proof. move=> n_gt0 /all_comm_mxP; have [k sAsk] := ubnP (size As). elim: k n n_gt0 As sAsk => [//|k IHk] n n_gt0 [|A As]. exists (const_mx 1) => //; apply/negP => /eqP/rowP/(_ (Ordinal n_gt0)). by rewrite !mxE => /eqP; rewrite oner_eq0. rewrite ltnS all_comm_mx_cons => sAsk /andP[]. move=> /allP/(_ _ _)/eqP/= A_comm /all_comm_mxP As_comm. have [a a_eigen] := eigenvalue_closed A n_gt0. have [] := IHk _ _ [seq restrictmx (eigenspace A a) B | B <- As]. - by rewrite lt0n mxrank_eq0. - by rewrite size_map. - apply/all_comm_mxP; move=> _ _ /= /mapP /= [B B_in ->] /mapP /= [B' B'_in ->]. rewrite -?conjmxM ?inE ?stablemx_row_base ?comm_mx_stable_eigenspace//; by [rewrite As_comm | apply: As_comm | apply: A_comm]. move=> v vN0 /allP /= vP; exists (v *m (row_base (eigenspace A a))). by rewrite mulmx_free_eq0 ?row_base_free. apply/andP; split. by apply/eigenvectorP; exists a; rewrite mulmx_sub // eq_row_base. apply/allP => B B_in; rewrite -stablemx_restrict ?vP //. by apply/mapP; exists B. by rewrite comm_mx_stable_eigenspace //; exact: A_comm. Qed. (* TODO: move? *) Lemma common_eigenvector2 {C : numClosedFieldType}n (A B : 'M[C]_n) : (n > 0)%N -> A *m B = B *m A -> exists2 v : 'rV_n, v != 0 & (stablemx v A) && (stablemx v B). Proof. move=> n_gt0 AB_comm; have [] := @common_eigenvector _ _ [:: A; B] n_gt0. by move=> A' B'; rewrite !inE => /orP [] /eqP-> /orP [] /eqP->. by move=> v v_neq0 /allP vP; exists v; rewrite ?vP ?(mem_head, in_cons, orbT). Qed. Notation "M ^t*" := (M ^t conjC) (at level 30) : sesquilinear_scope. Notation realmx := (mxOver Num.real). Lemma trmxCK {C : numClosedFieldType} m n (A : 'M[C]_(m, n)) : A ^t* ^t* = A. Proof. by apply/matrixP=> i j; rewrite !mxE conjCK. Qed. Section realmx. Context {C : numClosedFieldType} {m n : nat}. Implicit Types A B : 'M[C]_(m, n). Lemma realmxC A : A \is a realmx -> A ^ conjC = A. Proof. by move=> ?; apply/matrixP => x y; rewrite mxE; exact/CrealP/mxOverP. Qed. Lemma realmxD A B : A \is a realmx -> B \is a realmx -> A + B \is a realmx. Proof. rewrite !qualifE/= => /'forall_forallP realA /'forall_forallP realB. by apply/'forall_forallP => i j; rewrite mxE realD. Qed. Lemma Remx_rect : {in realmx &, forall A B, (A + 'i *: B) ^ (@Re _) = A}. Proof. move=> A B Areal Breal; apply/matrixP=> i j; rewrite !mxE. by rewrite Re_rect // (mxOverP _ _). Qed. Lemma Immx_rect : {in realmx &, forall A B, (A + 'i *: B) ^ (@Im _) = B}. Proof. move=> /= A B Areal Breal; apply/matrixP=> i j; rewrite !mxE. by rewrite Im_rect // (mxOverP _ _). Qed. Lemma eqmx_ReiIm A B A' B' : A \is a realmx -> B \is a realmx -> A' \is a realmx -> B' \is a realmx -> (A + 'i *: B) = (A' + 'i *: B') -> (A, B) = (A', B'). Proof. move=> ARe BRe A'Im B'Im eqAB. have /(congr1 (fun A => A ^ (@Im _))) := eqAB. have /(congr1 (fun A => A ^ (@Re _))) := eqAB. by rewrite !Remx_rect// !Immx_rect// => -> ->. Qed. End realmx. Lemma realsym_hermsym {C : numClosedFieldType} {n} (A : 'M[C]_n) : A \is symmetricmx -> A \is a realmx -> A \is hermsymmx. Proof. move=> Asym Areal; apply/is_hermitianmxP. by rewrite (trmx_hermitian (HermitianMx Asym))/= !scale1r ?realmxC ?map_mx_id. Qed. Lemma real_similar {C : numClosedFieldType} {n} (A B : 'M[C]_n) : similar_in unitmx A B -> A \is a realmx -> B \is a realmx -> similar_in [predI realmx & unitmx] A B. Proof. case=> [P /=]; pose Pr := P ^ (@Re _); pose Pi := P ^ (@Im _). have Pr_real : Pr \is a realmx by apply/mxOverP=> i j; rewrite !mxE Creal_Re. have Pi_real : Pi \is a realmx by apply/mxOverP=> i j; rewrite !mxE Creal_Im. pose Q x := P ^ (@Re _) + x *: P ^ (@Im _). have -> : P = Q 'i by apply/matrixP=> i j; rewrite !mxE -Crect. move=> Qi_unit eq_AP_PB Areal Breal. pose p := \det (Pr ^ polyC + 'X *: Pi ^ polyC). have horner_evaliC x : horner_eval (x : C) \o polyC =1 id := fun=> hornerC _ _. have Qunit x : Q x \in unitmx = (p.[x] != 0). rewrite /p -horner_evalE -det_map_mx map_mxD map_mxZ/= horner_evalE hornerX. by rewrite -![(_ ^ polyC) ^ _]map_mx_comp !map_mx_id// unitmxE unitfE. have p_neq0 : p != 0. by move: Qi_unit; rewrite Qunit; apply: contra_neq => ->; rewrite hornerE. have [a a_real rootNa] : exists2 a, a \is Num.real & ~~ root p a. have rs_uniq : uniq [seq (i%:R : C) | i <- iota 0 (size p)]. by rewrite map_inj_uniq ?iota_uniq //; apply: mulrIn; rewrite oner_eq0. have := contraNN (fun x => max_poly_roots p_neq0 x rs_uniq). rewrite size_map size_iota ltnn => /(_ isT) /allPn[a a_in rootNpa]. by exists a => //; by move: a_in => /mapP [i _ ->]; rewrite realn. exists (Q a). rewrite inE Qunit rootNa andbT. rewrite /Q/=. by rewrite realmxD// mxOverZ. apply/similarP; rewrite ?Qunit//; move: eq_AP_PB => /(similarP Qi_unit). rewrite !mulmxDl !mulmxDr -!scalemxAr -!scalemxAl => /eqmx_ReiIm. by rewrite !mxOverM// => /(_ isT isT isT isT) [-> ->]. Qed. Section unitarymx. Context {C : numClosedFieldType}. Definition unitarymx {m n} := [qualify X : 'M[C]_(m, n) | X *m X ^t* == 1%:M]. Fact unitarymx_key m n : pred_key (@unitarymx m n). Proof. by []. Qed. Canonical unitarymx_keyed m n := KeyedQualifier (unitarymx_key m n). Lemma unitarymxP m n {M : 'M[C]_(m, n)} : reflect (M *m M^t* = 1%:M) (M \is unitarymx). Proof. by apply: (iffP eqP). Qed. Lemma mulmxtVK m1 m2 n (A : 'M[C]_(m1, n)) (B : 'M[C]_(n, m2)) : B \is unitarymx -> A *m B *m B^t* = A. Proof. by move=> B_unitary; rewrite -mulmxA (unitarymxP _) ?mulmx1. Qed. Lemma unitarymx_unit n (M : 'M[C]_n) : M \is unitarymx -> M \in unitmx. Proof. by move=> /unitarymxP /mulmx1_unit []. Qed. Lemma invmx_unitary n (M : 'M[C]_n) : M \is unitarymx -> invmx M = M^t*. Proof. move=> Munitary; apply: (@row_full_inj _ _ _ _ M). by rewrite row_full_unit unitarymx_unit. by rewrite mulmxV ?unitarymx_unit ?(unitarymxP _). Qed. Lemma mulmxKtV m1 m2 n (A : 'M[C]_(m1, n)) (B : 'M[C]_(m2, n)) : B \is unitarymx -> m2 = n -> A *m B^t* *m B = A. Proof. move=> B_unitary m2E; case: _ / (esym m2E) in B B_unitary *. by rewrite -invmx_unitary // mulmxKV //; exact: unitarymx_unit. Qed. Lemma mxrank_unitary m n (M : 'M[C]_(m, n)) : M \is unitarymx -> \rank M = m. Proof. rewrite qualifE => /eqP /(congr1 mxrank); rewrite mxrank1 => rkM. apply/eqP; rewrite eqn_leq rank_leq_row /= -[X in (X <= _)%N]rkM. by rewrite mxrankM_maxl. Qed. Lemma mul_unitarymx m n p (A : 'M[C]_(m, n)) (B : 'M[C]_(n, p)) : A \is unitarymx -> B \is unitarymx -> A *m B \is unitarymx. Proof. move=> Aunitary Bunitary; apply/unitarymxP; rewrite trmx_mul map_mxM. by rewrite mulmxA -[A *m _ *m _]mulmxA !(unitarymxP _, mulmx1). Qed. Lemma pinvmx_unitary n (M : 'M[C]_n) : M \is unitarymx -> pinvmx M = M^t*. Proof. by move=> Munitary; rewrite pinvmxE ?unitarymx_unit// invmx_unitary. Qed. Lemma conjymx n (P M : 'M[C]_n) : P \is unitarymx -> conjmx P M = P *m M *m P^t*. Proof. by move=> Munitary; rewrite conjumx ?invmx_unitary ?unitarymx_unit. Qed. Lemma trmx_unitary n (M : 'M[C]_n) : (M ^T \is unitarymx) = (M \is unitarymx). Proof. apply/unitarymxP/unitarymxP; rewrite -?map_trmx -trmx_mul. by rewrite -trmx1 => /trmx_inj /mulmx1C->; rewrite trmx1. by move=> /mulmx1C->; rewrite trmx1. Qed. Lemma conjC_unitary m n (M : 'M[C]_(m, n)) : (M ^ conjC \is unitarymx) = (M \is unitarymx). Proof. apply/unitarymxP/unitarymxP; rewrite -?map_mxM ?map_trmx; last first. by move=> ->; rewrite map_mx1. by rewrite -[1%:M](map_mx1 conjC) => /map_mx_inj ->; rewrite map_mx1. Qed. Lemma trmxC_unitary n (M : 'M[C]_n) : (M ^t* \is unitarymx) = (M \is unitarymx). Proof. by rewrite conjC_unitary trmx_unitary. Qed. End unitarymx. Section normalmx. Context {C : numClosedFieldType} {n : nat}. Definition normalmx := [qualify M : 'M[C]_n | M *m M ^t* == M ^t* *m M]. Fact normalmx_key : pred_key normalmx. Proof. by []. Qed. Canonical normalmx_keyed := KeyedQualifier normalmx_key. Lemma normalmxP {M : 'M[C]_n} : reflect (M *m M ^t* = M ^t* *m M) (M \is normalmx). Proof. exact: eqP. Qed. Lemma hermitian_normalmx (A : 'M[C]_n) : A \is hermsymmx -> A \is normalmx. Proof. move=> Ahermi; apply/normalmxP. by rewrite (trmx_hermitian (HermitianMx Ahermi)) scale1r map_mxCK. Qed. Lemma symmetric_normalmx (A : 'M[C]_n) : A \is symmetricmx -> A \is a realmx -> A \is normalmx. Proof. by move=> Asym Areal; rewrite hermitian_normalmx// realsym_hermsym. Qed. End normalmx. Section Spectral. Variable (C : numClosedFieldType). Set Default Proof Using "C". Local Notation dotmx_def := (form_of_matrix (@conjC _) 1%:M). Definition dotmx n (u v : 'rV[C]_n) := dotmx_def u%R v%R. (* TODO: bug report we were expecting HB.instance Definition _ n := Bilinear.on (@dotmx n). to be sufficient to equip dotmx with the bilinear structure but needed to use .copy in the end as in: *) HB.instance Definition _ n := Bilinear.copy (@dotmx n) dotmx_def. Local Notation "''[' u , v ]" := (dotmx u v) : ring_scope. Local Notation "''[' u ]" := '[u, u]%R : ring_scope. HB.instance Definition _ n := Hermitian.copy (@dotmx n) dotmx_def. Lemma dotmxE n (u v : 'rV[C]_n) : '[u, v] = ( u *m v ^t* ) 0 0. Proof. by rewrite /dotmx /form_of_matrix mulmx1 /= trace_mx11. Qed. Lemma row_unitarymxP m n {M : 'M[C]_(m, n)} : reflect (forall i j, '[row i M, row j M] = (i == j)%:R) (M \is unitarymx). Proof. apply: (iffP eqP) => [Mo i j|Mo]. have /matrixP/(_ i j) := Mo; rewrite !mxE => <-. by rewrite dotmxE !mxE; apply: eq_bigr => /= k _; rewrite !mxE. apply/matrixP=> i j; rewrite !mxE; have := Mo i j; rewrite dotmxE !mxE => <-. by apply: eq_bigr => /= k _; rewrite !mxE. Qed. Fact dotmx_is_dotmx n (u : 'rV[C]_n) : u != 0 -> 0 < '[u]. Proof. move=> u_neq0; rewrite dotmxE mxE. suff /existsP[i ui_neq0] : [exists i, u 0 i != 0]. rewrite (bigD1 i) //= ltr_wpDr// ?sumr_ge0// ?mxE ?mul_conjC_gt0//. by move=> j _; rewrite !mxE mul_conjC_ge0. apply: contraNT u_neq0; rewrite negb_exists => /forallP uNN0. by apply/eqP/rowP=> j; rewrite mxE; apply/eqP; rewrite -[_ == _]negbK uNN0. Qed. HB.instance Definition _ n := isDotProduct.Build _ _ (@dotmx n) (@dotmx_is_dotmx n). Local Notation "B ^!" := (orthomx (@conjC C) (mx_of_hermitian (hermitian1mx _)) B) : matrix_set_scope. Local Notation "A '_|_ B" := (A%MS <= B^!)%MS : bool_scope. Lemma orthomx1E m n p (A : 'M[C]_(m, n)) (B : 'M_(p, n)) : (A '_|_ B)%MS = (A *m B^t* == 0). Proof. by apply/sub_kermxP/eqP; rewrite !mul1mx. Qed. Lemma orthomx1P m n p {A : 'M[C]_(m, n)} {B : 'M_(p, n)} : reflect (A *m B^t* = 0) (A '_|_ B). Proof. by rewrite orthomx1E; exact/eqP. Qed. Lemma orthomx_disj n p q (A : 'M[C]_(p, n)) (B :'M_(q, n)) : A '_|_ B -> (A :&: B = 0)%MS. Proof. move=> nAB; apply/eqP/rowV0Pn => [[v]]; rewrite sub_capmx => /andP [vA vB]. apply/negP; rewrite negbK. by rewrite -(dnorm_eq0 (@dotmx n)) -orthomxE (orthomxP _ _ _ nAB). Qed. Lemma orthomx_ortho_disj n p (A : 'M[C]_(p, n)) : (A :&: A^! = 0)%MS. Proof. exact/orthomx_disj/ortho_mx_ortho. Qed. Lemma rank_ortho p n (A : 'M[C]_(p, n)) : \rank A^! = (n - \rank A)%N. Proof. by rewrite mxrank_ker mul1mx mxrank_map mxrank_tr. Qed. Lemma add_rank_ortho p n (A : 'M[C]_(p, n)) : (\rank A + \rank A^!)%N = n. Proof. by rewrite rank_ortho subnKC ?rank_leq_col. Qed. Lemma addsmx_ortho p n (A : 'M[C]_(p, n)) : (A + A^! :=: 1%:M)%MS. Proof. apply/eqmxP/andP; rewrite submx1; split=> //. rewrite -mxrank_leqif_sup ?submx1 ?mxrank1 ?(mxdirectP _) /= ?add_rank_ortho //. by rewrite mxdirect_addsE /= ?mxdirectE ?orthomx_ortho_disj !eqxx. Qed. Lemma ortho_id p n (A : 'M[C]_(p, n)) : (A^!^! :=: A)%MS. Proof. apply/eqmx_sym/eqmxP. by rewrite -mxrank_leqif_eq 1?orthomx_sym // !rank_ortho subKn // ?rank_leq_col. Qed. Lemma submx_ortho p m n (U : 'M[C]_(p, n)) (V : 'M_(m, n)) : (U^! <= V^!)%MS = (V <= U)%MS. Proof. by rewrite orthomx_sym ortho_id. Qed. Definition proj_ortho p n (U : 'M[C]_(p, n)) := proj_mx <<U>>%MS U^!%MS. Lemma sub_adds_genmx_ortho (p m n : nat) (U : 'M[C]_(p, n)) (W : 'M_(m, n)) : (W <= <<U>> + U^!)%MS. Proof. by rewrite !(adds_eqmx (genmxE _) (eqmx_refl _)) addsmx_ortho submx1. Qed. Local Hint Resolve sub_adds_genmx_ortho : core. Lemma cap_genmx_ortho p n (U : 'M[C]_(p, n)) : (<<U>> :&: U^!)%MS = 0. Proof. apply/eqmx0P; rewrite !(cap_eqmx (genmxE _) (eqmx_refl _)). by rewrite orthomx_ortho_disj; exact/eqmx0P. Qed. Local Hint Resolve cap_genmx_ortho : core. Lemma proj_ortho_sub p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : (W *m proj_ortho U <= U)%MS. Proof. by rewrite (submx_trans (proj_mx_sub _ _ _)) // genmxE. Qed. Lemma proj_ortho_compl_sub p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : (W - W *m proj_ortho U <= U^!)%MS. Proof. by rewrite proj_mx_compl_sub // addsmx_ortho submx1. Qed. Lemma proj_ortho_id p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : (W <= U)%MS -> W *m proj_ortho U = W. Proof. by move=> WU; rewrite proj_mx_id ?genmxE. Qed. Lemma proj_ortho_0 p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : (W <= U^!)%MS -> W *m proj_ortho U = 0. Proof. by move=> WUo; rewrite proj_mx_0. Qed. Lemma add_proj_ortho p m n (U : 'M_(p, n)) (W : 'M_(m, n)) : W *m proj_ortho U + W *m proj_ortho U^!%MS = W. Proof. rewrite -[W in LHS](@add_proj_mx _ _ _ <<U>>%MS U^!%MS W)//. rewrite !mulmxDl proj_ortho_id ?proj_ortho_sub //. rewrite proj_ortho_0 ?proj_mx_sub // addr0. rewrite proj_ortho_0 ?ortho_id ?proj_ortho_sub // add0r. by rewrite proj_ortho_id ?proj_mx_sub// add_proj_mx. Qed. Lemma proj_ortho_proj m n (U : 'M_(m, n)) : let P := proj_ortho U in P *m P = P. Proof. by rewrite /= proj_mx_proj. Qed. Lemma proj_orthoE p n (U : 'M_(p, n)) : (proj_ortho U :=: U)%MS. Proof. apply/eqmxP/andP; split; first by rewrite -proj_ortho_proj proj_ortho_sub. by rewrite -[X in (X <= _)%MS](proj_ortho_id (submx_refl U)) mulmx_sub. Qed. Lemma orthomx_proj_mx_ortho p p' m m' n (A : 'M_(p, n)) (A' : 'M_(p', n)) (W : 'M_(m, n)) (W' : 'M_(m', n)) : A '_|_ A' -> W *m proj_ortho A '_|_ W' *m proj_ortho A'. Proof. rewrite orthomx_sym => An. rewrite mulmx_sub // orthomx_sym (eqmx_ortho _ (proj_orthoE _)). by rewrite (submx_trans _ An) // proj_ortho_sub. Qed. Lemma schmidt_subproof m n (A : 'M[C]_(m, n)) : (m <= n)%N -> exists2 B : 'M_(m, n), B \is unitarymx & [forall i : 'I_m, (row i A <= (\sum_(k < m | (k <= i)%N) <<row k B>>))%MS && ('[row i A, row i B] >= 0) ]. Proof. elim: m A => [|m IHm]. exists (pid_mx n); first by rewrite qualifE !thinmx0. by apply/forallP=> -[]. rewrite -addn1 => A leq_Sm_n. have lemSm : (m <= m + 1)%N by rewrite addn1. have ltmSm : (m < m + 1)%N by rewrite addn1. have lemn : (m <= n)%N by rewrite ltnW // -addn1. have [B Bortho] := IHm (usubmx A) lemn. move=> /forallP /= subAB. have [v /and4P [vBn v_neq0 dAv_ge0 dAsub]] : exists v, [&& B '_|_ v, v != 0, '[dsubmx A, v] >= 0 & (dsubmx A <= B + v)%MS]. have := add_proj_ortho B (dsubmx A). set BoSn := (_ *m proj_ortho _^!%MS) => pBE. have [BoSn_eq0|BoSn_neq0] := eqVneq BoSn 0. rewrite BoSn_eq0 addr0 in pBE. have /rowV0Pn [v vBn v_neq0] : B^!%MS != 0. rewrite -mxrank_eq0 rank_ortho -lt0n subn_gt0. by rewrite mxrank_unitary // -addn1. rewrite orthomx_sym in vBn. exists v; rewrite vBn v_neq0 -pBE. rewrite ['[_, _]](hermmx_eq0P _ _) ?lexx //=. rewrite (submx_trans (proj_ortho_sub _ _)) //. by rewrite -{1}[B]addr0 addmx_sub_adds ?sub0mx. by rewrite (submx_trans _ vBn) // proj_ortho_sub. pose c := (sqrtC '[BoSn])^-1; have c_gt0 : c > 0. by rewrite invr_gt0 sqrtC_gt0 lt_def ?dnorm_eq0 ?dnorm_ge0 BoSn_neq0. exists BoSn; apply/and4P; split => //. - by rewrite orthomx_sym ?proj_ortho_sub // /gtr_eqF. - rewrite -pBE linearDl //. rewrite [X in X + '[_]](hermmx_eq0P _ _) ?add0r ?dnorm_ge0 //. by rewrite orthomx_proj_mx_ortho // orthomx_sym. - by rewrite -pBE addmx_sub_adds // proj_ortho_sub. wlog nv_eq1 : v vBn v_neq0 dAv_ge0 dAsub / '[v] = 1. pose c := (sqrtC '[v])^-1. have c_gt0 : c > 0 by rewrite invr_gt0 sqrtC_gt0 ?dnorm_gt0. have [c_ge0 c_eq0F] := (ltW c_gt0, gt_eqF c_gt0). move=> /(_ (c *: v)); apply. - by rewrite orthomxZ ?c_eq0F. - by rewrite scaler_eq0 c_eq0F. - by rewrite linearZr mulr_ge0 // conjC_ge0. - by rewrite (submx_trans dAsub) // addsmxS // eqmx_scale // c_eq0F. - rewrite dnormZ normfV ger0_norm ?sqrtC_ge0 ?dnorm_ge0 //. by rewrite exprVn rootCK ?mulVf // dnorm_eq0. exists (col_mx B v). apply/row_unitarymxP => i j. case: (split_ordP i) (split_ordP j) => [] i' -> [] j' ->; rewrite eq_shift ?(rowKu, rowKd, row_id, ord1) -?val_eqE /= ?(row_unitarymxP _) //= ?addn0. by rewrite ['[_, _]](hermmx_eq0P _ _)//= (submx_trans _ vBn)// row_sub. rewrite ['[_, _]](hermmx_eq0P _ _)//= orthomx_sym (submx_trans _ vBn) //. exact: row_sub. apply/forallP => i; case: (split_ordP i) => j -> /=. have /andP [sABj dot_gt0] := subAB j. rewrite rowKu -row_usubmx (submx_trans sABj) //=. rewrite (eq_rect _ (submx _) (submx_refl _)) //. rewrite [in RHS](reindex (lshift 1)) /=. by apply: eq_bigr=> k k_le; rewrite rowKu. exists (fun k => insubd j k) => k; rewrite inE /= => le_kj; by apply/val_inj; rewrite /= insubdK // -topredE /= (leq_ltn_trans le_kj). rewrite rowKd -row_dsubmx !row_id ord1 ?dAv_ge0 ?andbT {j} addn0. rewrite (bigD1 (rshift _ ord0)) /= ?addn0 ?rowKd ?row_id // addsmxC. rewrite (submx_trans dAsub) // addsmxS ?genmxE //. apply/row_subP => j; apply/(sumsmx_sup (lshift _ j)) => //=. by rewrite ltnW ?ltn_ord //= -val_eqE /= addn0 ltn_eqF. by rewrite rowKu genmxE. Qed. Definition schmidt m n (A : 'M[C]_(m, n)) := if (m <= n)%N =P true is ReflectT le_mn then projT1 (sig2_eqW (schmidt_subproof A le_mn)) else A. Lemma schmidt_unitarymx m n (A : 'M[C]_(m, n)) : (m <= n)%N -> schmidt A \is unitarymx. Proof. by rewrite /schmidt; case: eqP => // ?; case: sig2_eqW. Qed. Hint Resolve schmidt_unitarymx : core. Lemma row_schmidt_sub m n (A : 'M[C]_(m, n)) i : (row i A <= (\sum_(k < m | (k <= i)%N) <<row k (schmidt A)>>))%MS. Proof. rewrite /schmidt; case: eqP => // ?. by case: sig2_eqW => ? ? /= /forallP /(_ i) /andP[]. by apply/(sumsmx_sup i) => //; rewrite genmxE. Qed. Lemma form1_row_schmidt m n (A : 'M[C]_(m, n)) i : '[row i A, row i (schmidt A)] >= 0. Proof. rewrite /schmidt; case: eqP => // ?; rewrite ?dnorm_ge0 //. by case: sig2_eqW => ? ? /= /forallP /(_ i) /andP[]. Qed. Lemma schmidt_sub m n (A : 'M[C]_(m, n)) : (A <= schmidt A)%MS. Proof. apply/row_subP => i; rewrite (submx_trans (row_schmidt_sub _ _)) //. by apply/sumsmx_subP => /= j le_ji; rewrite genmxE row_sub. Qed. Hint Resolve schmidt_sub : core. Lemma eqmx_schmidt_full m n (A : 'M[C]_(m, n)) : row_full A -> (schmidt A :=: A)%MS. Proof. move=> Afull; apply/eqmx_sym/eqmxP; rewrite -mxrank_leqif_eq //. by rewrite eqn_leq mxrankS //= (@leq_trans n) ?rank_leq_col ?col_leq_rank. Qed. Lemma eqmx_schmidt_free m n (A : 'M[C]_(m, n)) : row_free A -> (schmidt A :=: A)%MS. Proof. move=> Afree; apply/eqmx_sym/eqmxP; rewrite -mxrank_leqif_eq //. by rewrite eqn_leq mxrankS //= (@leq_trans m) ?rank_leq_row // ?row_leq_rank. Qed. Definition schmidt_complete m n (V : 'M[C]_(m, n)) := col_mx (schmidt (row_base V)) (schmidt (row_base V^!%MS)). Lemma schmidt_complete_unitarymx m n (V : 'M[C]_(m, n)) : schmidt_complete V \is unitarymx. Proof. apply/unitarymxP; rewrite tr_col_mx map_row_mx mul_col_row. rewrite !(unitarymxP _) ?schmidt_unitarymx ?rank_leq_col //. move=> [:nsV]; rewrite !(orthomx1P _) -?scalar_mx_block //; [abstract: nsV|]; last by rewrite orthomx_sym. by do 2!rewrite eqmx_schmidt_free ?eq_row_base ?row_base_free // orthomx_sym. Qed. Lemma cotrigonalization n (As : seq 'M[C]_n) : {in As &, forall A B, comm_mx A B} -> cotrigonalizable_in (@unitarymx C n n) As. Proof. elim: n {-2}n (leqnn n) As => [|N IHN] n. rewrite leqn0 => /eqP n_eq0. exists 1%:M; first by rewrite qualifE mul1mx trmx1 map_mx1. apply/allP => ? ?; apply/is_trig_mxP => i j. by suff: False by []; move: i; rewrite n_eq0 => -[]. rewrite leq_eqVlt => /predU1P [n_eqSN|/IHN//]. have /andP [n_gt0 n_small] : (n > 0)%N && (n - 1 <= N)%N. by rewrite n_eqSN /= subn1. move=> As As_comm; have [v vN0 /allP /= vP] := common_eigenvector n_gt0 As_comm. suff: exists2 P : 'M[C]_(\rank v + \rank v^!, n), P \is unitarymx & all (fun A => is_trig_mx (P *m A *m ( P^t* ))) As. rewrite add_rank_ortho // => -[P P_unitary] /=; rewrite -invmx_unitary//. by under eq_all do rewrite -conjumx ?unitarymx_unit//; exists P. pose S := schmidt_complete v. pose r A := S *m A *m S^t*. have vSvo X : stablemx v X -> schmidt (row_base v) *m X *m schmidt (row_base v^!%MS) ^t* = 0. move=> /eigenvectorP [a v_in]. rewrite (eigenspaceP (_ : (_ <= _ a))%MS); last first. by rewrite eqmx_schmidt_free ?row_base_free ?eq_row_base. rewrite -scalemxAl (orthomx1P _) ?scaler0 //. by do 2!rewrite eqmx_schmidt_free ?row_base_free ?eq_row_base // orthomx_sym. have drrE X : drsubmx (r X) = schmidt (row_base v^!%MS) *m X *m schmidt (row_base v^!%MS) ^t*. by rewrite /r mul_col_mx tr_col_mx map_row_mx mul_col_row block_mxKdr. have vSv X a : (v <= eigenspace X a)%MS -> schmidt (row_base v) *m X *m schmidt (row_base v) ^t* = a%:M. move=> vXa; rewrite (eigenspaceP (_ : (_ <= _ a)%MS)); last first. by rewrite eqmx_schmidt_free ?row_base_free ?eq_row_base. by rewrite -scalemxAl (unitarymxP _) ?scalemx1 ?schmidt_unitarymx ?rank_leq_col. have [] := IHN _ _ [seq drsubmx (r A) | A <- As]. - by rewrite rank_ortho rank_rV vN0. - move=> _ _ /mapP[/= A A_in ->] /mapP[/= B B_in ->]. have : (r A) *m (r B) = (r B) *m (r A). rewrite /r !mulmxA !mulmxKtV // ?schmidt_complete_unitarymx //; by rewrite ?add_rank_ortho // -![S *m _ *m _]mulmxA As_comm. rewrite -[r A in X in X -> _]submxK -[r B in X in X -> _]submxK. rewrite 2!mulmx_block => /eq_block_mx [_ _ _]. suff urr_eq0 X : X \in As -> ursubmx (r X) = 0. by rewrite !urr_eq0 ?mulmx0 ?add0r. rewrite /r /S ![schmidt_complete _ *m _]mul_col_mx. rewrite !tr_col_mx !map_row_mx !mul_col_row !block_mxKur. by move=> X_in; rewrite vSvo // vP. move=> P' P'_unitary /allP /= P'P. exists ((block_mx 1%:M 0 0 P') *m S). rewrite mul_unitarymx ?schmidt_complete_unitarymx //. apply/unitarymxP; rewrite tr_block_mx map_block_mx mulmx_block. rewrite !trmx0 !(@map_mx0 _ _ conjC) !tr_scalar_mx !map_scalar_mx ?conjC1. rewrite !(mulmx1, mul1mx, mulmx0, mul0mx, addr0, add0r). by rewrite (unitarymxP _) -?scalar_mx_block //. apply/allP => /= A A_in. rewrite trmx_mul map_mxM tr_block_mx map_block_mx. rewrite !trmx0 !map_mx0 !tr_scalar_mx !map_scalar_mx ?conjC1. rewrite mulmxA -[_ *m S *m _]mulmxA -[_ *m _ *m S^t*]mulmxA. rewrite /S ![schmidt_complete _ *m _]mul_col_mx. rewrite !tr_col_mx !map_row_mx !mul_col_row !mulmx_block. rewrite !(mulmx1, mul1mx, mulmx0, mul0mx, addr0, add0r). apply/is_trig_mxP => /= i j lt_ij; rewrite mxE. case: splitP => //= i' i_eq; rewrite !mxE; case: splitP => //= j' j_eq. - have /vP /eigenvectorP [a v_in] := A_in. by rewrite (vSv _ _ v_in) mxE -val_eqE ltn_eqF //= -i_eq -j_eq. - by rewrite vSvo ?mul0mx ?mxE // vP //. - move: lt_ij; rewrite i_eq j_eq ltnNge -ltnS (leq_trans (ltn_ord j'))//. by rewrite -addnS leq_addr. - set A' := _ *m A *m _; rewrite -invmx_unitary // -conjumx ?unitarymx_unit//. have /(_ _) /is_trig_mxP -> // := P'P A'; last first. by move: lt_ij; rewrite i_eq j_eq ltn_add2l. by apply/mapP; exists A; rewrite //= drrE. Qed. Theorem Schur n (A : 'M[C]_n) : (n > 0)%N -> trigonalizable_in (@unitarymx C n n) A. Proof. case: n => [//|n] in A * => _; have [] := @cotrigonalization _ [:: A]. by move=> ? ? /=; rewrite !in_cons !orbF => /eqP-> /eqP->. by move=> P P_unitary /=; rewrite andbT=> A_trigo; exists P. Qed. Lemma cotrigonalization2 n (A B : 'M[C]_n) : A *m B = B *m A -> exists2 P : 'M[C]_n, P \is unitarymx & similar_trig P A && similar_trig P B. Proof. move=> AB_comm; have [] := @cotrigonalization _ [:: A; B]. by move=> ??; rewrite !inE => /orP[]/eqP->/orP[]/eqP->. move=> P Punitary /allP /= PP; exists P => //. by rewrite !PP ?(mem_head, in_cons, orbT). Qed. Theorem orthomx_spectral_subproof n {A : 'M[C]_n} : reflect (exists2 sp : 'M_n * 'rV_n, sp.1 \is unitarymx & A = invmx sp.1 *m diag_mx sp.2 *m sp.1) (A \is normalmx). Proof. apply: (iffP normalmxP); last first. move=> [[/= P D] P_unitary ->]. rewrite !trmx_mul !map_mxM !mulmxA invmx_unitary //. rewrite !trmxCK ![_ *m P *m _]mulmxtVK //. by rewrite -[X in X *m P]mulmxA tr_diag_mx map_diag_mx diag_mxC mulmxA. move=> /cotrigonalization2 [P Punitary /andP[]] PA PATC. have Punit := unitarymx_unit Punitary. suff: similar_diag P A. move=> /similar_diagPex[D] PAD; exists (P, D) => //=. by rewrite -conjVmx//; exact/similarLR. apply/similar_diagPp => // i j; case: ltngtP => // [lt_ij|lt_ji] _. by have /is_trig_mxP-> := PA. have /is_trig_mxP -/(_ j i lt_ji)/eqP := PATC. rewrite !conjumx// invmx_unitary// -[P as X in X *m _]trmxCK. by rewrite -!map_mxM -!trmx_mul mulmxA 2!mxE conjC_eq0 => /eqP. Qed. Definition spectralmx n (A : 'M[C]_n) : 'M[C]_n := if @orthomx_spectral_subproof _ A is ReflectT P then (projT1 (sig2_eqW P)).1 else 1%:M. Definition spectral_diag n (A : 'M[C]_n) : 'rV_n := if @orthomx_spectral_subproof _ A is ReflectT P then (projT1 (sig2_eqW P)).2 else 0. Lemma spectral_unitarymx n (A : 'M[C]_n) : spectralmx A \is unitarymx. Proof. rewrite /spectralmx; case: orthomx_spectral_subproof; last first. by move=> _; apply/unitarymxP; rewrite trmx1 map_mx1 mulmx1. by move=> ?; case: sig2_eqW. Qed. Lemma spectral_unit n (A : 'M[C]_n) : spectralmx A \in unitmx. Proof. exact/unitarymx_unit/spectral_unitarymx. Qed. Theorem orthomx_spectralP {n} {A : 'M[C]_n} (P := spectralmx A) (sp := spectral_diag A) : reflect (A = invmx P *m diag_mx sp *m P) (A \is normalmx). Proof. rewrite /P /sp /spectralmx /spectral_diag. case: orthomx_spectral_subproof. by move=> Psp; case: sig2_eqW => //=; constructor. move=> /orthomx_spectral_subproof Ann; constructor; apply/eqP. apply: contra Ann; rewrite invmx1 mul1mx mulmx1 => /eqP->. suff -> : diag_mx 0 = 0 by rewrite qualifE trmx0 (map_mx0 conjC). by move=> ? ?; apply/matrixP=> i j; rewrite !mxE mul0rn. Qed. Lemma hermitian_spectral_diag_real n (A : 'M[C]_n) : A \is hermsymmx -> spectral_diag A \is a realmx. Proof. move=> Ahermi; have /hermitian_normalmx /orthomx_spectralP A_eq := Ahermi. have /(congr1 ( fun X => X^t* )) := A_eq. rewrite invmx_unitary ?spectral_unitarymx //. rewrite !trmx_mul !map_mxM map_trmx trmxK -map_mx_comp. rewrite tr_diag_mx map_diag_mx (map_mx_id (@conjCK _)). rewrite -[in RHS]invmx_unitary ?spectral_unitarymx //. have := is_hermitianmxP _ _ _ Ahermi; rewrite expr0 scale1r => <-. rewrite {1}A_eq mulmxA => /(congr1 (mulmx^~ (invmx (spectralmx A)))). rewrite !mulmxK ?spectral_unit//. move=> /(congr1 (mulmx (spectralmx A))); rewrite !mulKVmx ?spectral_unit//. move=> eq_A_conjA; apply/mxOverP => i j; rewrite ord1 {i}. have /matrixP /(_ j j) := eq_A_conjA; rewrite !mxE eqxx !mulr1n. by move=> /esym/CrealP. Qed. End Spectral.
Localization.lean
/- Copyright (c) 2024 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Algebra.Module.LocalizedModule.Submodule import Mathlib.LinearAlgebra.Dimension.DivisionRing import Mathlib.RingTheory.IsTensorProduct import Mathlib.RingTheory.Localization.BaseChange import Mathlib.RingTheory.Localization.FractionRing import Mathlib.RingTheory.OreLocalization.OreSet /-! # Rank of localization ## Main statements - `IsLocalizedModule.lift_rank_eq`: `rank_Rₚ Mₚ = rank R M`. - `rank_quotient_add_rank_of_isDomain`: The **rank-nullity theorem** for commutative domains. -/ open Cardinal Module nonZeroDivisors section CommRing universe uR uS uT uM uN uP variable {R : Type uR} (S : Type uS) {M : Type uM} {N : Type uN} variable [CommRing R] [CommRing S] [AddCommGroup M] [AddCommGroup N] variable [Module R M] [Module R N] [Algebra R S] [Module S N] [IsScalarTower R S N] variable (p : Submonoid R) [IsLocalization p S] (f : M →ₗ[R] N) [IsLocalizedModule p f] variable (hp : p ≤ R⁰) section include hp section include f lemma IsLocalizedModule.lift_rank_eq : Cardinal.lift.{uM} (Module.rank R N) = Cardinal.lift.{uN} (Module.rank R M) := by cases subsingleton_or_nontrivial R · simp only [rank_subsingleton, lift_one] apply le_antisymm <;> rw [Module.rank_def, lift_iSup (bddAbove_range _)] <;> apply ciSup_le' <;> intro ⟨s, hs⟩ exacts [(IsLocalizedModule.linearIndependent_lift p f hs).choose_spec.cardinal_lift_le_rank, hs.of_isLocalizedModule_of_isRegular p f (le_nonZeroDivisors_iff_isRegular.mp hp) |>.cardinal_lift_le_rank] lemma IsLocalizedModule.finrank_eq : finrank R N = finrank R M := by simpa using congr_arg toNat (lift_rank_eq p f hp) end lemma IsLocalizedModule.rank_eq {N : Type uM} [AddCommGroup N] [Module R N] (f : M →ₗ[R] N) [IsLocalizedModule p f] : Module.rank R N = Module.rank R M := by simpa using lift_rank_eq p f hp lemma IsLocalization.rank_eq : Module.rank S N = Module.rank R N := by cases subsingleton_or_nontrivial R · have := (algebraMap R S).codomain_trivial; simp only [rank_subsingleton] have inj := IsLocalization.injective S hp apply le_antisymm <;> (rw [Module.rank]; apply ciSup_le'; intro ⟨s, hs⟩) · have := (faithfulSMul_iff_algebraMap_injective R S).mpr inj exact (hs.restrict_scalars' R).cardinal_le_rank · have := inj.nontrivial exact (hs.localization S p).cardinal_le_rank end variable (R M) in theorem exists_set_linearIndependent_of_isDomain [IsDomain R] : ∃ s : Set M, #s = Module.rank R M ∧ LinearIndepOn R id s := by obtain ⟨w, hw⟩ := IsLocalizedModule.linearIndependent_lift R⁰ (LocalizedModule.mkLinearMap R⁰ M) <| Module.Free.chooseBasis (FractionRing R) (LocalizedModule R⁰ M) |>.linearIndependent.restrict_scalars' _ refine ⟨Set.range w, ?_, (linearIndepOn_id_range_iff hw.injective).mpr hw⟩ apply Cardinal.lift_injective.{max uR uM} rw [Cardinal.mk_range_eq_of_injective hw.injective, ← Module.Free.rank_eq_card_chooseBasisIndex, IsLocalization.rank_eq (FractionRing R) R⁰ le_rfl, IsLocalizedModule.lift_rank_eq R⁰ (LocalizedModule.mkLinearMap R⁰ M) le_rfl] /-- The **rank-nullity theorem** for commutative domains. Also see `rank_quotient_add_rank`. -/ theorem rank_quotient_add_rank_of_isDomain [IsDomain R] (M' : Submodule R M) : Module.rank R (M ⧸ M') + Module.rank R M' = Module.rank R M := by apply lift_injective.{max uR uM} simp_rw [lift_add, ← IsLocalizedModule.lift_rank_eq R⁰ (M'.toLocalized R⁰) le_rfl, ← IsLocalizedModule.lift_rank_eq R⁰ (LocalizedModule.mkLinearMap R⁰ M) le_rfl, ← IsLocalizedModule.lift_rank_eq R⁰ (M'.toLocalizedQuotient R⁰) le_rfl, ← IsLocalization.rank_eq (FractionRing R) R⁰ le_rfl, ← lift_add, rank_quotient_add_rank_of_divisionRing] universe w in instance IsDomain.hasRankNullity [IsDomain R] : HasRankNullity.{w} R where rank_quotient_add_rank := rank_quotient_add_rank_of_isDomain exists_set_linearIndependent M := exists_set_linearIndependent_of_isDomain R M namespace IsBaseChange open Cardinal TensorProduct section variable {p} [Free S N] [StrongRankCondition S] {T : Type uT} [CommRing T] [Algebra R T] (hpT : Algebra.algebraMapSubmonoid T p ≤ T⁰) [StrongRankCondition (S ⊗[R] T)] {P : Type uP} [AddCommGroup P] [Module R P] [Module T P] [IsScalarTower R T P] {g : M →ₗ[R] P} (bc : IsBaseChange T g) include S hp hpT f bc theorem lift_rank_eq_of_le_nonZeroDivisors : Cardinal.lift.{uM} (Module.rank T P) = Cardinal.lift.{uP} (Module.rank R M) := by rw [← lift_inj.{_, max uS uT uN}, lift_lift, lift_lift] let ST := S ⊗[R] T conv_rhs => rw [← lift_lift.{uN, max uS uT uP}, ← IsLocalizedModule.lift_rank_eq p f hp, ← IsLocalization.rank_eq S p hp, lift_lift, ← lift_lift.{max uS uT, max uM uP}, ← rank_baseChange (R := ST), ← lift_id'.{max uS uT, max uS uT uN} (Module.rank ..), lift_lift, ← lift_lift.{max uS uT uP, uM}] let _ : Algebra T ST := Algebra.TensorProduct.rightAlgebra set pT := Algebra.algebraMapSubmonoid T p have : IsLocalization pT ST := isLocalizedModule_iff_isLocalization.mp (IsLocalization.tensorProduct_isLocalizedModule ..) rw [← lift_lift.{max uS uT, max uM uN}, ← lift_umax.{uP}, ← IsLocalizedModule.lift_rank_eq pT (mk T ST P 1) hpT, ← IsLocalization.rank_eq ST pT hpT, lift_id'.{uP, max uS uT}, ← lift_id'.{max uS uT, max uS uT uP} (Module.rank ..), lift_lift, ← lift_lift.{max uS uT uN, uM}, lift_inj] exact LinearEquiv.lift_rank_eq <| AlgebraTensorModule.congr (.refl ST ST) bc.equiv.symm ≪≫ₗ AlgebraTensorModule.cancelBaseChange .. ≪≫ₗ (AlgebraTensorModule.cancelBaseChange ..).symm ≪≫ₗ AlgebraTensorModule.congr (.refl ..) ((isLocalizedModule_iff_isBaseChange p S f).mp ‹_›).equiv theorem finrank_eq_of_le_nonZeroDivisors : finrank T P = finrank R M := by simpa using congr_arg toNat (lift_rank_eq_of_le_nonZeroDivisors S f hp hpT bc) omit bc theorem rank_eq_of_le_nonZeroDivisors {P : Type uM} [AddCommGroup P] [Module R P] [Module T P] [IsScalarTower R T P] {g : M →ₗ[R] P} (bc : IsBaseChange T g) : Module.rank T P = Module.rank R M := by simpa using lift_rank_eq_of_le_nonZeroDivisors S f hp hpT bc end variable {p} {T : Type uT} [CommRing T] [NoZeroDivisors T] [Algebra R T] [FaithfulSMul R T] {P : Type uP} [AddCommGroup P] [Module R P] [Module T P] [IsScalarTower R T P] {g : M →ₗ[R] P} (bc : IsBaseChange T g) include bc theorem lift_rank_eq : Cardinal.lift.{uM} (Module.rank T P) = Cardinal.lift.{uP} (Module.rank R M) := by have inj := FaithfulSMul.algebraMap_injective R T have := inj.noZeroDivisors _ (map_zero _) (map_mul _) cases subsingleton_or_nontrivial R · have := (algebraMap R T).codomain_trivial; simp only [rank_subsingleton, lift_one] have := (isDomain_iff_noZeroDivisors_and_nontrivial T).mpr ⟨‹_›, (FaithfulSMul.algebraMap_injective R T).nontrivial⟩ let FR := FractionRing R let FT := FractionRing T replace inj : Function.Injective (algebraMap R FT) := (IsFractionRing.injective T _).comp inj let g := TensorProduct.mk T FT P 1 have : IsLocalizedModule R⁰ (TensorProduct.mk R FR FT 1) := inferInstance let _ : Algebra FT (FR ⊗[R] FT) := Algebra.TensorProduct.rightAlgebra let _ := isLocalizedModule_iff_isLocalization.mp this |>.atUnits _ _ ?_ |>.symm.isField (Field.toIsField FT) |>.toField on_goal 2 => rintro _ ⟨_, mem, rfl⟩; exact (map_ne_zero_of_mem_nonZeroDivisors _ inj mem).isUnit have := bc.comp_iff.2 ((isLocalizedModule_iff_isBaseChange T⁰ FT g).1 inferInstance) rw [← lift_inj.{_, max uT uP}, lift_lift, lift_lift, ← lift_lift.{max uT uP, uM}, ← IsLocalizedModule.lift_rank_eq T⁰ g le_rfl, lift_lift, ← lift_lift.{uM}, ← IsLocalization.rank_eq FT T⁰ le_rfl, lift_rank_eq_of_le_nonZeroDivisors FR (LocalizedModule.mkLinearMap R⁰ M) le_rfl (map_le_nonZeroDivisors_of_injective _ inj le_rfl) this, lift_lift] theorem finrank_eq : finrank T P = finrank R M := by simpa using congr_arg toNat bc.lift_rank_eq omit bc theorem rank_eq {P : Type uM} [AddCommGroup P] [Module R P] [Module T P] [IsScalarTower R T P] {g : M →ₗ[R] P} (bc : IsBaseChange T g) : Module.rank T P = Module.rank R M := by simpa using bc.lift_rank_eq end IsBaseChange end CommRing section Ring variable {R} [Ring R] [IsDomain R] /-- A domain that is not (left) Ore is of infinite rank. See [cohn_1995] Proposition 1.3.6 -/ lemma aleph0_le_rank_of_isEmpty_oreSet (hS : IsEmpty (OreLocalization.OreSet R⁰)) : ℵ₀ ≤ Module.rank R R := by classical rw [← not_nonempty_iff, OreLocalization.nonempty_oreSet_iff_of_noZeroDivisors] at hS push_neg at hS obtain ⟨r, s, h⟩ := hS refine Cardinal.aleph0_le.mpr fun n ↦ ?_ suffices LinearIndependent R (fun (i : Fin n) ↦ r * s ^ (i : ℕ)) by simpa using this.cardinal_lift_le_rank suffices ∀ (g : ℕ → R) (x), (∑ i ∈ Finset.range n, g i • (r * s ^ (i + x))) = 0 → ∀ i < n, g i = 0 by refine Fintype.linearIndependent_iff.mpr fun g hg i ↦ ?_ simpa only [dif_pos i.prop] using this (fun i ↦ if h : i < n then g ⟨i, h⟩ else 0) 0 (by simp [← Fin.sum_univ_eq_sum_range, ← hg]) i i.prop intro g x hg i hin induction n generalizing g x i with | zero => exact (hin.not_ge (zero_le i)).elim | succ n IH => rw [Finset.sum_range_succ'] at hg by_cases hg0 : g 0 = 0 · simp only [hg0, zero_smul, add_zero, add_assoc] at hg cases i; exacts [hg0, IH _ _ hg _ (Nat.succ_lt_succ_iff.mp hin)] simp only [zero_add, pow_add _ _ x, ← mul_assoc, pow_succ, ← Finset.sum_mul, smul_eq_mul] at hg rw [← neg_eq_iff_add_eq_zero, ← neg_mul, ← neg_mul] at hg have := mul_right_cancel₀ (mem_nonZeroDivisors_iff_ne_zero.mp (s ^ x).prop) hg exact (h _ ⟨(g 0), mem_nonZeroDivisors_iff_ne_zero.mpr (by simpa)⟩ this.symm).elim -- TODO: Upgrade this to an iff. See [lam_1999] Exercise 10.21 lemma nonempty_oreSet_of_strongRankCondition [StrongRankCondition R] : Nonempty (OreLocalization.OreSet R⁰) := by by_contra h have := aleph0_le_rank_of_isEmpty_oreSet (not_nonempty_iff.mp h) rw [rank_self] at this exact this.not_gt one_lt_aleph0 end Ring
GiryMonad.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.MeasureTheory.Integral.Lebesgue.Countable /-! # The Giry monad Let X be a measurable space. The collection of all measures on X again forms a measurable space. This construction forms a monad on measurable spaces and measurable functions, called the Giry monad. Note that most sources use the term "Giry monad" for the restriction to *probability* measures. Here we include all measures on X. See also `MeasureTheory/Category/MeasCat.lean`, containing an upgrade of the type-level monad to an honest monad of the functor `measure : MeasCat ⥤ MeasCat`. ## References * <https://ncatlab.org/nlab/show/Giry+monad> ## Tags giry monad -/ noncomputable section open ENNReal Set Filter variable {α β : Type*} namespace MeasureTheory namespace Measure variable {mα : MeasurableSpace α} {mβ : MeasurableSpace β} /-- Measurability structure on `Measure`: Measures are measurable w.r.t. all projections -/ instance instMeasurableSpace : MeasurableSpace (Measure α) := ⨆ (s : Set α) (_ : MeasurableSet s), (borel ℝ≥0∞).comap fun μ => μ s theorem measurable_coe {s : Set α} (hs : MeasurableSet s) : Measurable fun μ : Measure α => μ s := Measurable.of_comap_le <| le_iSup_of_le s <| le_iSup_of_le hs <| le_rfl theorem measurable_of_measurable_coe (f : β → Measure α) (h : ∀ (s : Set α), MeasurableSet s → Measurable fun b => f b s) : Measurable f := Measurable.of_le_map <| iSup₂_le fun s hs => MeasurableSpace.comap_le_iff_le_map.2 <| by rw [MeasurableSpace.map_comp]; exact h s hs instance instMeasurableAdd₂ {α : Type*} {m : MeasurableSpace α} : MeasurableAdd₂ (Measure α) := by refine ⟨Measure.measurable_of_measurable_coe _ fun s hs => ?_⟩ simp_rw [Measure.coe_add, Pi.add_apply] refine Measurable.add ?_ ?_ · exact (Measure.measurable_coe hs).comp measurable_fst · exact (Measure.measurable_coe hs).comp measurable_snd -- There is no typeclass for measurability of `SMul` only on that side, otherwise we could -- turn that into an instance. @[fun_prop] lemma _root_.Measurable.smul_measure {f : α → ℝ≥0∞} (hf : Measurable f) (μ : Measure β) : Measurable (fun x ↦ f x • μ) := by refine Measure.measurable_of_measurable_coe _ fun s hs ↦ ?_ simp only [Measure.smul_apply, smul_eq_mul] fun_prop theorem measurable_measure {μ : α → Measure β} : Measurable μ ↔ ∀ (s : Set β), MeasurableSet s → Measurable fun b => μ b s := ⟨fun hμ _s hs => (measurable_coe hs).comp hμ, measurable_of_measurable_coe μ⟩ theorem _root_.Measurable.measure_of_isPiSystem {μ : α → Measure β} [∀ a, IsFiniteMeasure (μ a)] {S : Set (Set β)} (hgen : ‹MeasurableSpace β› = .generateFrom S) (hpi : IsPiSystem S) (h_basic : ∀ s ∈ S, Measurable fun a ↦ μ a s) (h_univ : Measurable fun a ↦ μ a univ) : Measurable μ := by rw [measurable_measure] intro s hs induction s, hs using MeasurableSpace.induction_on_inter hgen hpi with | empty => simp | basic s hs => exact h_basic s hs | compl s hsm ihs => simp only [measure_compl hsm (measure_ne_top _ _)] exact h_univ.sub ihs | iUnion f hfd hfm ihf => simpa only [measure_iUnion hfd hfm] using .ennreal_tsum ihf theorem _root_.Measurable.measure_of_isPiSystem_of_isProbabilityMeasure {μ : α → Measure β} [∀ a, IsProbabilityMeasure (μ a)] {S : Set (Set β)} (hgen : ‹MeasurableSpace β› = .generateFrom S) (hpi : IsPiSystem S) (h_basic : ∀ s ∈ S, Measurable fun a ↦ μ a s) : Measurable μ := .measure_of_isPiSystem hgen hpi h_basic <| by simp @[fun_prop] theorem measurable_map (f : α → β) (hf : Measurable f) : Measurable fun μ : Measure α => map f μ := by refine measurable_of_measurable_coe _ fun s hs => ?_ simp_rw [map_apply hf hs] exact measurable_coe (hf hs) @[fun_prop] theorem measurable_dirac : Measurable (Measure.dirac : α → Measure α) := by refine measurable_of_measurable_coe _ fun s hs => ?_ simp_rw [dirac_apply' _ hs] exact measurable_one.indicator hs @[fun_prop] theorem measurable_lintegral {f : α → ℝ≥0∞} (hf : Measurable f) : Measurable fun μ : Measure α => ∫⁻ x, f x ∂μ := by simp only [lintegral_eq_iSup_eapprox_lintegral, hf, SimpleFunc.lintegral] refine .iSup fun n => Finset.measurable_fun_sum _ fun i _ => ?_ refine Measurable.const_mul ?_ _ exact measurable_coe ((SimpleFunc.eapprox f n).measurableSet_preimage _) /-- Monadic join on `Measure` in the category of measurable spaces and measurable functions. -/ def join (m : Measure (Measure α)) : Measure α := Measure.ofMeasurable (fun s _ => ∫⁻ μ, μ s ∂m) (by simp only [measure_empty, lintegral_const, zero_mul]) (by intro f hf h simp_rw [measure_iUnion h hf] apply lintegral_tsum intro i; exact (measurable_coe (hf i)).aemeasurable) @[simp] theorem join_apply {m : Measure (Measure α)} {s : Set α} (hs : MeasurableSet s) : join m s = ∫⁻ μ, μ s ∂m := Measure.ofMeasurable_apply s hs theorem le_join_apply (m : Measure (Measure α)) (s : Set α) : ∫⁻ μ, μ s ∂m ≤ join m s := by rw [measure_eq_iInf] exact le_iInf₂ fun t hst ↦ le_iInf fun htm ↦ join_apply htm ▸ by gcongr @[simp] theorem join_smul {R : Type*} [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] (c : R) (m : Measure (Measure α)) : (c • m).join = c • m.join := by ext s hs simp [hs] @[simp] theorem join_dirac (μ : Measure α) : join (dirac μ) = μ := by ext s hs simp [hs, lintegral_dirac', measurable_coe] theorem le_ae_join (m : Measure (Measure α)) : (ae m).bind ae ≤ ae m.join := by intro s hs rcases exists_measurable_superset_of_null hs with ⟨t, hst, htm, ht⟩ rw [join_apply htm, lintegral_eq_zero_iff (measurable_coe htm)] at ht rw [mem_bind'] exact ht.mono fun _ ↦ measure_mono_null hst theorem ae_ae_of_ae_join {m : Measure (Measure α)} {p : α → Prop} (h : ∀ᵐ a ∂m.join, p a) : ∀ᵐ μ ∂m, ∀ᵐ a ∂μ, p a := le_ae_join m h theorem _root_.AEMeasurable.ae_of_join {m : Measure (Measure α)} {f : α → β} (h : AEMeasurable f m.join) : ∀ᵐ μ ∂m, AEMeasurable f μ := let ⟨g, hgm, hg⟩ := h; (ae_ae_of_ae_join hg).mono fun _μ hμ ↦ ⟨g, hgm, hμ⟩ theorem aemeasurable_lintegral {m : Measure (Measure α)} {f : α → ℝ≥0∞} (h : AEMeasurable f m.join) : AEMeasurable (fun μ ↦ ∫⁻ a, f a ∂μ) m := let ⟨g, hgm, hfg⟩ := h ⟨fun μ ↦ ∫⁻ a, g a ∂μ, measurable_lintegral hgm, (ae_ae_of_ae_join hfg).mono fun _ ↦ lintegral_congr_ae⟩ @[simp] theorem join_zero : (0 : Measure (Measure α)).join = 0 := by ext1 s hs simp [hs] @[fun_prop] theorem measurable_join : Measurable (join : Measure (Measure α) → Measure α) := measurable_of_measurable_coe _ fun s hs => by simp only [join_apply hs, measurable_lintegral (measurable_coe hs)] theorem lintegral_join {m : Measure (Measure α)} {f : α → ℝ≥0∞} (hf : AEMeasurable f (join m)) : ∫⁻ x, f x ∂join m = ∫⁻ μ, ∫⁻ x, f x ∂μ ∂m := by wlog hfm : Measurable f generalizing f · rcases hf with ⟨g, hgm, hfg⟩ rw [lintegral_congr_ae hfg, this hgm.aemeasurable hgm] exact lintegral_congr_ae <| (ae_ae_of_ae_join hfg).mono fun μ hμ ↦ .symm <| lintegral_congr_ae hμ simp_rw [lintegral_eq_iSup_eapprox_lintegral hfm, SimpleFunc.lintegral, join_apply (SimpleFunc.measurableSet_preimage _ _)] clear hf suffices ∀ (s : ℕ → Finset ℝ≥0∞) (f : ℕ → ℝ≥0∞ → Measure α → ℝ≥0∞), (∀ n r, Measurable (f n r)) → Monotone (fun n μ => ∑ r ∈ s n, r * f n r μ) → ⨆ n, ∑ r ∈ s n, r * ∫⁻ μ, f n r μ ∂m = ∫⁻ μ, ⨆ n, ∑ r ∈ s n, r * f n r μ ∂m by refine this (fun n => SimpleFunc.range (SimpleFunc.eapprox f n)) (fun n r μ => μ (SimpleFunc.eapprox f n ⁻¹' {r})) ?_ ?_ · exact fun n r => measurable_coe (SimpleFunc.measurableSet_preimage _ _) · exact fun n m h μ => SimpleFunc.lintegral_mono (SimpleFunc.monotone_eapprox _ h) le_rfl intro s f hf hm rw [lintegral_iSup _ hm] swap · fun_prop congr funext n rw [lintegral_finset_sum (s n)] · simp_rw [lintegral_const_mul _ (hf _ _)] · exact fun r _ => (hf _ _).const_mul _ theorem lintegral_join_le (f : α → ℝ≥0∞) (m : Measure (Measure α)) : ∫⁻ x, f x ∂join m ≤ ∫⁻ μ, ∫⁻ x, f x ∂μ ∂m := by rcases exists_measurable_le_lintegral_eq (join m) f with ⟨g, hgm, hgf, hfg_int⟩ rw [hfg_int, lintegral_join hgm.aemeasurable] gcongr apply hgf /-- Monadic bind on `Measure`, only works in the category of measurable spaces and measurable functions. When the function `f` is not measurable the result is not well defined. -/ def bind (m : Measure α) (f : α → Measure β) : Measure β := join (map f m) @[simp] theorem bind_zero_left (f : α → Measure β) : bind (0 : Measure α) f = 0 := by simp [bind] @[simp] theorem bind_apply {m : Measure α} {f : α → Measure β} {s : Set β} (hs : MeasurableSet s) (hf : AEMeasurable f m) : bind m f s = ∫⁻ a, f a s ∂m := by rw [bind, join_apply hs, lintegral_map' (measurable_coe hs).aemeasurable hf] theorem bind_apply_le {m : Measure α} (f : α → Measure β) {s : Set β} (hs : MeasurableSet s) : bind m f s ≤ ∫⁻ a, f a s ∂m := by rw [bind, join_apply hs] apply lintegral_map_le theorem ae_ae_of_ae_bind {m : Measure α} {f : α → Measure β} {p : β → Prop} (hf : AEMeasurable f m) (h : ∀ᵐ b ∂m.bind f, p b) : ∀ᵐ a ∂m, ∀ᵐ b ∂ f a, p b := ae_of_ae_map hf <| ae_ae_of_ae_join h theorem _root_.AEMeasurable.ae_of_bind {γ : Type*} {_ : MeasurableSpace γ} {m : Measure α} {f : α → Measure β} {g : β → γ} (hf : AEMeasurable f m) (hg : AEMeasurable g (m.bind f)) : ∀ᵐ a ∂m, AEMeasurable g (f a) := ae_of_ae_map hf hg.ae_of_join theorem bind_congr_right {μ : Measure α} {f g : α → Measure β} (h : f =ᵐ[μ] g) : μ.bind f = μ.bind g := congrArg join <| map_congr h @[simp] lemma bind_const {m : Measure α} {ν : Measure β} : m.bind (fun _ ↦ ν) = m Set.univ • ν := by simp [bind] theorem bind_zero_right' (m : Measure α) : bind m (fun _ => 0 : α → Measure β) = 0 := by simp @[simp] theorem bind_zero_right (m : Measure α) : bind m (0 : α → Measure β) = 0 := bind_zero_right' m @[fun_prop] theorem measurable_bind' {g : α → Measure β} (hg : Measurable g) : Measurable fun m : Measure α => bind m g := measurable_join.comp (measurable_map _ hg) theorem aemeasurable_bind {g : α → Measure β} {m : Measure (Measure α)} (hg : AEMeasurable g m.join) : AEMeasurable (bind · g) m := let ⟨f, hfm, hf⟩ := hg ⟨(bind · f), measurable_bind' hfm, (ae_ae_of_ae_join hf).mono fun _ ↦ bind_congr_right⟩ theorem lintegral_bind {m : Measure α} {μ : α → Measure β} {f : β → ℝ≥0∞} (hμ : AEMeasurable μ m) (hf : AEMeasurable f (bind m μ)) : ∫⁻ x, f x ∂bind m μ = ∫⁻ a, ∫⁻ x, f x ∂μ a ∂m := (lintegral_join hf).trans (lintegral_map' (aemeasurable_lintegral hf) hμ) theorem lintegral_bind_le (f : β → ℝ≥0∞) (m : Measure α) (μ : α → Measure β) : ∫⁻ x, f x ∂bind m μ ≤ ∫⁻ a, ∫⁻ x, f x ∂μ a ∂m := (lintegral_join_le _ _).trans (lintegral_map_le _ _) theorem bind_bind {γ} [MeasurableSpace γ] {m : Measure α} {f : α → Measure β} {g : β → Measure γ} (hf : AEMeasurable f m) (hg : AEMeasurable g (m.bind f)) : bind (bind m f) g = bind m fun a => bind (f a) g := by ext1 s hs rw [bind_apply hs hg, lintegral_bind hf, bind_apply hs] · exact lintegral_congr_ae <| (hf.ae_of_bind hg).mono fun a ha ↦ .symm <| bind_apply hs ha · exact (aemeasurable_bind hg).comp_aemeasurable hf · exact (measurable_coe hs).comp_aemeasurable hg @[simp] theorem dirac_bind {f : α → Measure β} (hf : Measurable f) (a : α) : bind (dirac a) f = f a := by simp [bind, map_dirac hf] @[simp] theorem bind_dirac {m : Measure α} : bind m dirac = m := by ext1 s hs simp only [bind_apply hs measurable_dirac.aemeasurable, dirac_apply' _ hs, lintegral_indicator hs, Pi.one_apply, lintegral_one, restrict_apply, MeasurableSet.univ, univ_inter] @[simp] lemma bind_dirac_eq_map (m : Measure α) {f : α → β} (hf : Measurable f) : m.bind (fun x ↦ Measure.dirac (f x)) = m.map f := by rw [← bind_dirac (m := m.map f), bind, bind, map_map, Function.comp_def] exacts [measurable_dirac, hf] theorem join_eq_bind (μ : Measure (Measure α)) : join μ = bind μ id := by rw [bind, map_id] theorem join_map_map {f : α → β} (hf : Measurable f) (μ : Measure (Measure α)) : join (map (map f) μ) = map f (join μ) := by ext1 s hs rw [join_apply hs, map_apply hf hs, join_apply (hf hs), lintegral_map (measurable_coe hs) (measurable_map f hf)] simp_rw [map_apply hf hs] theorem join_map_join (μ : Measure (Measure (Measure α))) : join (map join μ) = join (join μ) := by change bind μ join = join (join μ) rw [join_eq_bind, join_eq_bind, bind_bind aemeasurable_id aemeasurable_id] apply congr_arg (bind μ) funext ν exact join_eq_bind ν theorem join_map_dirac (μ : Measure α) : join (map dirac μ) = μ := bind_dirac end Measure end MeasureTheory
toAdditive.lean
import Mathlib.Algebra.Group.Defs import Mathlib.Lean.Exception import Mathlib.Tactic.ReduceModChar.Ext import Qq.MetaM open Qq Lean Meta Elab Command ToAdditive set_option autoImplicit true -- work in a namespace so that it doesn't matter if names clash namespace Test -- [note] use the below options for diagnostics: -- set_option trace.to_additive true -- set_option trace.to_additive_detail true -- set_option pp.universes true -- set_option pp.explicit true -- set_option pp.notation false @[to_additive bar0] def foo0 {α} [Mul α] [One α] (x y : α) : α := x * y * 1 theorem bar0_works : bar0 3 4 = 7 := by decide class my_has_pow (α : Type u) (β : Type v) where (pow : α → β → α) instance : my_has_pow Nat Nat := ⟨fun a b => a ^ b⟩ class my_has_scalar (M : Type u) (α : Type v) where (smul : M → α → α) instance : my_has_scalar Nat Nat := ⟨fun a b => a * b⟩ attribute [to_additive (reorder := 1 2) my_has_scalar] my_has_pow attribute [to_additive (reorder := 1 2, 4 5)] my_has_pow.pow @[to_additive bar1] def foo1 {α : Type u} [my_has_pow α ℕ] (x : α) (n : ℕ) : α := @my_has_pow.pow α ℕ _ x n theorem foo1_works : foo1 3 4 = Nat.pow 3 4 := by decide theorem bar1_works : bar1 3 4 = 3 * 4 := by decide infix:80 " ^ " => my_has_pow.pow instance dummy_pow : my_has_pow ℕ <| PLift ℤ := ⟨fun _ _ => 5⟩ @[to_additive bar2] def foo2 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) (m : PLift ℤ) : α := x ^ (n ^ m) theorem foo2_works : foo2 2 3 (PLift.up 2) = Nat.pow 2 5 := by decide theorem bar2_works : bar2 2 3 (PLift.up 2) = 2 * 5 := by decide @[to_additive bar3] def foo3 {α} [my_has_pow α ℕ] (x : α) : ℕ → α := @my_has_pow.pow α ℕ _ x theorem foo3_works : foo3 2 3 = Nat.pow 2 3 := by decide theorem bar3_works : bar3 2 3 = 2 * 3 := by decide @[to_additive bar4] def foo4 {α : Type u} : Type v → Type (max u v) := @my_has_pow α @[to_additive bar4_test] lemma foo4_test {α β : Type u} : @foo4 α β = @my_has_pow α β := rfl @[to_additive bar5] def foo5 {α} [my_has_pow α ℕ] [my_has_pow ℕ ℤ] : True := True.intro @[to_additive bar6] def foo6 {α} [my_has_pow α ℕ] : α → ℕ → α := @my_has_pow.pow α ℕ _ -- fails because of workaround in `transform`. Not sure if this will show up in practice -- @[to_additive bar7] -- def foo7 := @my_has_pow.pow -- theorem foo7_works : foo7 2 3 = Nat.pow 2 3 := by decide -- theorem bar7_works : bar7 2 3 = 2 * 3 := by decide /-- Check that we don't additivize `Nat` expressions. -/ @[to_additive bar8] def foo8 (a b : ℕ) := a * b theorem bar8_works : bar8 2 3 = 6 := by decide /-- Check that we don't additivize `Nat` numerals. -/ @[to_additive bar9] def foo9 := 1 theorem bar9_works : bar9 = 1 := by decide @[to_additive bar10] def foo10 (n m : ℕ) := HPow.hPow n m + n * m * 2 + 1 * 0 + 37 * 1 + 2 theorem bar10_works : bar10 = foo10 := rfl @[to_additive bar11] def foo11 (n : ℕ) (m : ℤ) := n * m * 2 + 1 * 0 + 37 * 1 + 2 theorem bar11_works : bar11 = foo11 := rfl @[to_additive bar12] def foo12 (_ : Nat) (_ : Int) : Fin 37 := ⟨2, by decide⟩ @[to_additive (reorder := 1 2, 4 5) bar13] lemma foo13 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : x ^ y = x ^ y := rfl @[to_additive (reorder := 1 2, 4 5) bar14] def foo14 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : α := (x ^ y) ^ y @[to_additive (reorder := 1 2, 4 5) bar15] lemma foo15 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : foo14 x y = (x ^ y) ^ y := rfl @[to_additive (reorder := 1 2, 4 5) bar16] lemma foo16 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : foo14 x y = (x ^ y) ^ y := foo15 x y @[to_additive bar17] def foo17 [Group α] (x : α) : α := x * 1 @[to_additive (attr := simp) bar18] lemma foo18 [Group α] (x : α) : foo17 x = x ∧ foo17 x = 1 * x := ⟨mul_one x, mul_one x |>.trans <| one_mul x |>.symm⟩ example [Group α] (x : α) : foo17 x = 1 * x := by simp example [Group α] (x : α) : foo17 x = x := by simp example [AddGroup α] (x : α) : bar17 x = 0 + x := by simp example [AddGroup α] (x : α) : bar17 x = x := by simp /- Testing nested to_additive calls -/ @[to_additive (attr := simp, to_additive baz19) bar19] def foo19 := 1 example {x} (h : 1 = x) : foo19 = x := by simp; guard_target = 1 = x; exact h example {x} (h : 1 = x) : bar19 = x := by simp; guard_target = 1 = x; exact h example {x} (h : 1 = x) : baz19 = x := by simp; guard_target = 1 = x; exact h /- Testing that the order of the attributes doesn't matter -/ @[to_additive (attr := to_additive baz20, simp) bar20] def foo20 := 1 example {x} (h : 1 = x) : foo20 = x := by simp; guard_target = 1 = x; exact h example {x} (h : 1 = x) : bar20 = x := by simp; guard_target = 1 = x; exact h example {x} (h : 1 = x) : baz20 = x := by simp; guard_target = 1 = x; exact h @[to_additive bar21] def foo21 {N} {A} [Pow A N] (a : A) (n : N) : A := a ^ n run_cmd liftCoreM <| MetaM.run' <| guard <| relevantArgAttr.find? (← getEnv) `Test.foo21 == some 1 @[to_additive bar22] abbrev foo22 {α} [Monoid α] (a : α) : ℕ → α | 0 => 1 | _ => a run_cmd liftCoreM <| MetaM.run' <| do -- make `abbrev` definition `reducible` automatically guard <| (← getReducibilityStatus `Test.bar22) == .reducible -- make `abbrev` definition `inline` automatically guard <| (Compiler.getInlineAttribute? (← getEnv) `Test.bar22) == some .inline -- some auxiliary definitions are also `abbrev` but not `reducible` guard <| (← getReducibilityStatus `Test.bar22.match_1) != .reducible guard <| (Compiler.getInlineAttribute? (← getEnv) `Test.bar22.match_1) == some .inline /- test the eta-expansion applied on `foo6`. -/ run_cmd do let c ← getConstInfo `Test.foo6 let e : Expr ← liftCoreM <| MetaM.run' <| expand c.value! let t ← liftCoreM <| MetaM.run' <| expand c.type let decl := c |>.updateName `Test.barr6 |>.updateType t |>.updateValue e |>.toDeclaration! liftCoreM <| addAndCompile decl -- test that we cannot transport a declaration to itself successIfFail <| liftCoreM <| addToAdditiveAttr `bar11_works { ref := ← getRef } /- Test on inductive types -/ inductive AddInd : ℕ → Prop where | basic : AddInd 2 | zero : AddInd 0 @[to_additive] inductive MulInd : ℕ → Prop where | basic : MulInd 2 | one : MulInd 1 run_cmd do unless findTranslation? (← getEnv) `Test.MulInd.one == some `Test.AddInd.zero do throwError "1" unless findTranslation? (← getEnv) `Test.MulInd.basic == none do throwError "2" unless findTranslation? (← getEnv) `Test.MulInd == some `Test.AddInd do throwError "3" @[to_additive addFixedNumeralTest] def fixedNumeralTest {α} [One α] := @OfNat.ofNat ((fun _ => ℕ) (1 : α)) 1 _ @[to_additive addFixedNumeralTest2] def fixedNumeralTest2 {α} [One α] := @OfNat.ofNat ((fun _ => ℕ) (1 : α)) 1 (@One.toOfNat1 ((fun _ => ℕ) (1 : α)) _) /-! Test the namespace bug (https://github.com/leanprover-community/mathlib4/pull/8733). This code should *not* generate a lemma `add_some_def.in_namespace`. -/ def some_def.in_namespace : Bool := false def some_def {α : Type u} [Mul α] (x : α) : α := if some_def.in_namespace then x * x else x def myFin (_ : ℕ) := ℕ instance : One (myFin n) := ⟨(1 : ℕ)⟩ @[to_additive bar] def myFin.foo : myFin (n + 1) := 1 /-- We can pattern-match with `1`, which creates a term with a pure nat literal. See https://github.com/leanprover-community/mathlib4/pull/2046 -/ @[to_additive] def mul_foo {α} [Monoid α] (a : α) : ℕ → α | 0 => 1 | 1 => 1 | (_ + 2) => a -- cannot apply `@[to_additive]` to `some_def` if `some_def.in_namespace` doesn't have the attribute run_cmd liftCoreM <| successIfFail <| transformDecl { ref := ← getRef} `Test.some_def `Test.add_some_def attribute [to_additive some_other_name] some_def.in_namespace attribute [to_additive add_some_def] some_def run_cmd do liftCoreM <| successIfFail (getConstInfo `Test.add_some_def.in_namespace) section set_option linter.unusedVariables false in def foo_mul {I J K : Type} (n : ℕ) {f : I → Type} (L : Type) [∀ i, One (f i)] [Add I] [Mul L] : true := by trivial @[to_additive] instance pi.has_one {I : Type} {f : I → Type} [(i : I) → One <| f i] : One ((i : I) → f i) := ⟨fun _ => 1⟩ run_cmd do let n ← liftCoreM <| MetaM.run' <| firstMultiplicativeArg `Test.pi.has_one if n != 1 then throwError "{n} != 1" let n ← liftCoreM <| MetaM.run' <| firstMultiplicativeArg `Test.foo_mul if n != 4 then throwError "{n} != 4" end @[to_additive] def nat_pi_has_one {α : Type} [One α] : One ((x : Nat) → α) := by infer_instance @[to_additive] def pi_nat_has_one {I : Type} : One ((x : I) → Nat) := pi.has_one example : @pi_nat_has_one = @pi_nat_has_zero := rfl section test_noncomputable @[to_additive Bar.bar] noncomputable def Foo.foo (h : ∃ _ : α, True) : α := Classical.choose h @[to_additive Bar.bar'] def Foo.foo' : ℕ := 2 theorem Bar.bar'_works : Bar.bar' = 2 := by decide run_cmd (do if !isNoncomputable (← getEnv) `Test.Bar.bar then throwError "bar shouldn't be computable" if isNoncomputable (← getEnv) `Test.Bar.bar' then throwError "bar' should be computable") end test_noncomputable section instances class FooClass (α) : Prop where refle : ∀ a : α, a = a @[to_additive] instance FooClass_one [One α] : FooClass α := ⟨fun _ ↦ rfl⟩ lemma one_fooClass [One α] : FooClass α := by infer_instance lemma zero_fooClass [Zero α] : FooClass α := by infer_instance end instances /- Test that we can rewrite with definitions with the `@[to_additive]` attribute. -/ @[to_additive] lemma npowRec_zero [One M] [Mul M] (x : M) : npowRec 0 x = 1 := by rw [npowRec] /- Test that we can rewrite with definitions without the `@[to_additive]` attribute. -/ @[to_additive addoptiontest] lemma optiontest (x : Option α) : x.elim .none Option.some = x := by cases x <;> rw [Option.elim] /- Check that `to_additive` works if a `_match` aux declaration is created. -/ @[to_additive] def IsUnit [Mul M] (a : M) : Prop := a ≠ a @[to_additive] theorem isUnit_iff_exists_inv [Mul M] {a : M} : IsUnit a ↔ ∃ _ : α, a ≠ a := ⟨fun h => absurd rfl h, fun ⟨_, hab⟩ => hab⟩ /-! Test that `@[to_additive]` correctly translates auxiliary declarations that do not have the original declaration name as prefix. -/ @[to_additive] def IsUnit' [Monoid M] (a : M) : Prop := ∃ b : M, a * b = 1 @[to_additive] theorem isUnit'_iff_exists_inv [CommMonoid M] {a : M} : IsUnit' a ↔ ∃ b, a * b = 1 := Iff.rfl @[to_additive] theorem isUnit'_iff_exists_inv' [CommMonoid M] {a : M} : IsUnit' a ↔ ∃ b, b * a = 1 := by simp [isUnit'_iff_exists_inv, mul_comm] /-! Test a permutation with a cycle of length > 2. -/ @[to_additive (reorder := 3 4 5)] def reorderMulThree {α : Type _} [Mul α] (x y z : α) : α := x * y * z /-! Test a permutation that is too big for the list of arguments. -/ /-- error: the permutation [[2, 3, 50]] provided by the `(reorder := ...)` option is out of bounds, the type {α : Type u_1} → [Mul α] → α → α → α → α has only 5 arguments -/ #guard_msgs in @[to_additive (reorder := 3 4 51)] def reorderMulThree' {α : Type _} [Mul α] (x y z : α) : α := x * y * z /-! Test `(reorder := ...)` when the proof needs to be eta-expanded. -/ @[to_additive (reorder := 3 4 5)] alias reorderMulThree_alias := reorderMulThree @[to_additive (reorder := 3 4 2)] alias reorderMulThree_alias' := reorderMulThree @[to_additive (reorder := 3 4 5)] def reorderMulThree_alias'' {α : Type _} [Mul α] (x y : α) : α → α := reorderMulThree x y /-- error: invalid cycle `04`, a cycle must have at least 2 elements. `(reorder := ...)` uses cycle notation to specify a permutation. For example `(reorder := 1 2, 5 6)` swaps the first two arguments with each other and the fifth and the sixth argument and `(reorder := 3 4 5)` will move the fifth argument before the third argument. -/ #guard_msgs in @[to_additive (reorder := 04)] example : True := trivial /-- error: invalid position `00`, positions are counted starting from 1. -/ #guard_msgs in @[to_additive (reorder := 100 200, 2 00)] example : True := trivial example {α : Type _} [Add α] (x y z : α) : reorderAddThree z x y = x + y + z := rfl def Ones : ℕ → Q(Nat) | 0 => q(1) | (n + 1) => q($(Ones n) + $(Ones n)) -- This test just exists to see if this finishes in finite time. It should take <100ms. -- #time run_cmd do let e : Expr := Ones 300 let _ ← liftCoreM <| MetaM.run' <| applyReplacementFun e -- testing `isConstantApplication` run_cmd do unless !(q((fun _ y => y) 3 4) : Q(Nat)).isConstantApplication do throwError "1" unless (q((fun x _ => x) 3 4) : Q(Nat)).isConstantApplication do throwError "2" unless !(q((fun x => x) 3) : Q(Nat)).isConstantApplication do throwError "3" unless (q((fun _ => 5) 3) : Q(Nat)).isConstantApplication do throwError "4" @[to_additive, to_additive_dont_translate] def MonoidEnd : Type := Unit run_cmd do let stx ← `(Semigroup MonoidEnd) liftTermElabM do let e ← Term.elabTerm stx none guard <| additiveTest (← getEnv) e == some `Test.MonoidEnd @[to_additive instSemiGroupAddMonoidEnd] instance : Semigroup MonoidEnd where mul _ _ := () mul_assoc _ _ _ := rfl @[to_additive] lemma monoidEnd_lemma (x y z : MonoidEnd) : x * (y * z) = (x * y) * z := mul_assoc .. |>.symm /-- info: Test.addMonoidEnd_lemma (x y z : AddMonoidEnd) : x * (y * z) = x * y * z -/ #guard_msgs in #check addMonoidEnd_lemma /-! Some arbitrary tests to check whether additive names are guessed correctly. -/ section guessName def checkGuessName (s t : String) : Elab.Command.CommandElabM Unit := unless guessName s == t do throwError "failed: {guessName s} != {t}" run_cmd checkGuessName "HMul_Eq_LEOne_Conj₂MulLT'" "HAdd_Eq_Nonpos_Conj₂AddLT'" checkGuessName "OneMulSMulInvDivPow" "ZeroAddVAddNegSubNSMul" checkGuessName "ProdFinprodNPowZPow" "SumFinsumNSMulZSMul" -- The current design swaps all instances of `Comm`+`Add` in order to have -- `AddCommMonoid` instead of `CommAddMonoid`. checkGuessName "comm_mul_CommMul_commMul" "comm_add_AddComm_addComm" checkGuessName "mul_comm_MulComm_mulComm" "add_comm_AddComm_addComm" checkGuessName "mul_single_eq_same" "single_eq_same" checkGuessName "mul_support" "support" checkGuessName "mul_tsupport" "tsupport" checkGuessName "mul_indicator" "indicator" checkGuessName "CommMonoid" "AddCommMonoid" checkGuessName "commMonoid" "addCommMonoid" checkGuessName "CancelCommMonoid" "AddCancelCommMonoid" checkGuessName "cancelCommMonoid" "addCancelCommMonoid" checkGuessName "CancelMonoid" "AddCancelMonoid" checkGuessName "cancelMonoid" "addCancelMonoid" checkGuessName "RightCancelMonoid" "AddRightCancelMonoid" checkGuessName "rightCancelMonoid" "addRightCancelMonoid" checkGuessName "LeftCancelMonoid" "AddLeftCancelMonoid" checkGuessName "leftCancelMonoid" "addLeftCancelMonoid" checkGuessName "IsLeftRegular" "IsAddLeftRegular" checkGuessName "isRightRegular" "isAddRightRegular" checkGuessName "IsRegular" "IsAddRegular" checkGuessName "LTOne_LEOne_OneLE_OneLT" "Neg_Nonpos_Nonneg_Pos" checkGuessName "LTHMulHPowLEHDiv" "LTHAddHSMulLEHSub" checkGuessName "OneLEHMul" "NonnegHAdd" checkGuessName "OneLTHPow" "PosHSMul" checkGuessName "OneLTPow" "PosNSMul" checkGuessName "instCoeTCOneHom" "instCoeTCZeroHom" checkGuessName "instCoeTOneHom" "instCoeTZeroHom" checkGuessName "instCoeOneHom" "instCoeZeroHom" checkGuessName "invFun_eq_symm" "invFun_eq_symm" checkGuessName "MulEquiv.symmInvFun" "AddEquiv.symmInvFun" end guessName end Test run_cmd Elab.Command.liftCoreM <| ToAdditive.insertTranslation `localize `add_localize @[to_additive] def localize.r := Nat @[to_additive add_localize] def localize := Nat @[to_additive] def localize.s := Nat run_cmd do unless findTranslation? (← getEnv) `localize.r == some `add_localize.r do throwError "1" unless findTranslation? (← getEnv) `localize == some `add_localize do throwError "2" unless findTranslation? (← getEnv) `localize.s == some `add_localize.s do throwError "3" /-- warning: The source declaration one_eq_one was given the simp-attribute(s) simp, reduce_mod_char before calling @[to_additive]. The preferred method is to use something like `@[to_additive (attr := simp, reduce_mod_char)]` to apply the attribute to both one_eq_one and the target declaration zero_eq_zero. Note: This linter can be disabled with `set_option linter.existingAttributeWarning false` -/ #guard_msgs in @[simp, reduce_mod_char, to_additive] lemma one_eq_one {α : Type*} [One α] : (1 : α) = 1 := rfl @[to_additive (attr := reduce_mod_char, simp)] lemma one_eq_one' {α : Type*} [One α] : (1 : α) = 1 := rfl -- Test the error message for a name that cannot be additivised. /-- error: to_additive: the generated additivised name equals the original name 'foo', meaning that no part of the name was additivised. If this is intentional, use the `@[to_additive self]` syntax. Otherwise, check that your declaration name is correct (if your declaration is an instance, try naming it) or provide an additivised name using the `@[to_additive my_add_name]` syntax. --- warning: declaration uses 'sorry' -/ #guard_msgs in @[to_additive] instance foo {α : Type*} [Semigroup α] : Monoid α := sorry -- Test the error message for a wrong `to_additive existing`. /-- error: `to_additive` validation failed: expected 1 universe levels, but 'Nat.le_trans' has 0 universe levels -/ #guard_msgs in @[to_additive existing Nat.le_trans] lemma one_eq_one'' {α : Type*} [One α] : (1 : α) = 1 := rfl /-- error: `to_additive` validation failed: expected ∀ {α : Type u} [inst : Zero α], 0 = 0 but 'Eq.trans' has type ∀ {α : Sort u} {a b c : α}, a = b → b = c → a = c -/ #guard_msgs in @[to_additive existing Eq.trans] lemma one_eq_one''' {α : Type*} [One α] : (1 : α) = 1 := rfl /-! Test that @[to_additive] can reorder arguments of raw kernel projections. -/ open Lean in elab "unfold%" e:term : term => do let e ← Elab.Term.elabTerm e none Meta.unfoldDefinition e @[to_additive] def myPow {α β : Type} [i : Pow α β] (a : α) := unfold% i.1 a /-- info: def myPow : {α β : Type} → [i : Pow α β] → α → β → α := fun {α β} [i : Pow α β] a => i.1 a -/ #guard_msgs in #print myPow /-- info: def myNSMul : {α β : Type} → [i : SMul β α] → α → β → α := fun {α β} [SMul β α] a a_1 => SMul.smul a_1 a -/ #guard_msgs in #print myNSMul @[to_additive] def myMul {α : Type} [i : Mul α] (a : α) := unfold% i.1 a /-- info: def myMul : {α : Type} → [i : Mul α] → α → α → α := fun {α} [i : Mul α] a => i.1 a -/ #guard_msgs in #print myMul /-- info: def myAdd : {α : Type} → [i : Add α] → α → α → α := fun {α} [Add α] a => Add.add a -/ #guard_msgs in #print myAdd /-! Test that the `existingAttributeWarning` linter doesn't fire for `to_additive self`. -/ @[simp, to_additive self] theorem test1 : 5 = 5 := rfl /-! Test that we can't write `to_additive self (attr := ..)`. -/ /-- error: invalid `(attr := ...)` after `self`, as there is only one declaration for the attributes. Instead, you can write the attributes in the usual way. -/ #guard_msgs in @[to_additive self (attr := simp)] theorem test2 : 5 = 5 := rfl /-! Previously, An application that isn't a constant, such as `(no_index Add) α`, would be seen as multiplicative, hence `α` would be set as the `to_additive_relevant_arg`. -/ @[to_additive] def fooMul {α β : Type} (_ : (no_index Add) α) [Mul β] (x y : β) : β := x * y @[to_additive] -- this would not translate `fooMul` def barMul {β : Type} [Mul β] (x y : β) : β := fooMul instAddNat x y /-! Test that additive docstrings work -/ @[to_additive /-- (via `docComment` syntax) I am an additive docstring! -/] theorem mulTrivial : True := trivial /-- info: (via `docComment` syntax) I am an additive docstring! -/ #guard_msgs in run_cmd let some doc ← findDocString? (← getEnv) ``addTrivial | throwError "no `docComment` docstring found" logInfo doc /-- warning: String syntax for `to_additive` docstrings is deprecated: Use docstring syntax instead (e.g. `@[to_additive /-- example -/]`) -/ #guard_msgs in @[to_additive "(via `str` syntax) I am an additive docstring!"] theorem mulTrivial' : True := trivial /-- info: (via `str` syntax) I am an additive docstring! -/ #guard_msgs in run_cmd let some doc ← findDocString? (← getEnv) ``addTrivial' | throwError "no `str` docstring found" logInfo doc
vec_notation.lean
/- Manually ported from https://github.com/leanprover-community/mathlib/blob/fee91d74414e681a8b72cb7160e6b5ef0ec2cc0b/test/vec_notation.lean -/ import Mathlib.Data.Fin.VecNotation open Lean open Lean.Meta open Qq set_option linter.style.setOption false in set_option pp.unicode.fun false /-- info: ![1, 1 + 1, 1 + 1 + 1] : Fin (Nat.succ 2) → ℤ -/ #guard_msgs in #check by_elab return PiFin.mkLiteralQ ![q(1 : ℤ), q(1 + 1), q(1 + 1 + 1)] /-! These tests are testing `PiFin.toExpr` and fail with `local attribute [-instance] PiFin.toExpr` -/ run_elab do let x : Fin 0 → ℕ := ![] guard (← isDefEq (toExpr x) q((![] : Fin 0 → ℕ))) run_elab do let x := ![1, 2, 3] guard (← isDefEq (toExpr x) q(![1, 2, 3])) run_elab do let x := ![![1, 2], ![3, 4]] guard (← isDefEq (toExpr x) q(![![1, 2], ![3, 4]])) /-! These tests are testing `PiFin.repr` -/ #guard (toString (repr (![] : _ → ℕ)) = "![]") #guard (toString (repr ![1, 2, 3]) = "![1, 2, 3]") #guard (toString (repr ![![1, 2], ![3, 4]]) = "![![1, 2], ![3, 4]]") /-! These tests are testing delaborators -/ set_option linter.style.commandStart false /-- info: fun x => ![0, 1] x : Fin 2 → ℕ -/ #guard_msgs in #check fun x : Fin 2 => (![0, 1] : Fin 2 → ℕ) x /-- info: fun x => ![] x : Fin 0 → ℕ -/ #guard_msgs in #check fun x : Fin 0 => (![] : Fin 0 → ℕ) x section variable {a b c d e f g h : α} example : ![a] 0 = a := by dsimp only [Matrix.cons_val] example : ![a] 1 = a := by dsimp only [Matrix.cons_val] example : ![a] 2 = a := by dsimp only [Matrix.cons_val] example : ![a] (-1) = a := by dsimp only [Matrix.cons_val] example : ![a, b, c] 0 = a := by dsimp only [Matrix.cons_val] example : ![a, b, c] 1 = b := by dsimp only [Matrix.cons_val] example : ![a, b, c] 2 = c := by dsimp only [Matrix.cons_val] example : ![a, b, c, d] 0 = a := by dsimp only [Matrix.cons_val] example : ![a, b, c, d] 1 = b := by dsimp only [Matrix.cons_val] example : ![a, b, c, d] 2 = c := by dsimp only [Matrix.cons_val] example : ![a, b, c, d] 3 = d := by dsimp only [Matrix.cons_val] example : ![a, b, c, d] 42 = c := by dsimp only [Matrix.cons_val] example : ![a, b, c, d] (-2) = c := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 0 = a := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 1 = b := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 2 = c := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 3 = d := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 4 = e := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 5 = a := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 6 = b := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 7 = c := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 8 = d := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 9 = e := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 10 = a := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 123 = d := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e] 123456789 = e := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e, f, g, h] 5 = f := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e, f, g, h] (5 : Fin (4 + 4)) = f := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e, f, g, h] 7 = h := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e, f, g, h] 37 = f := by dsimp only [Matrix.cons_val] example : ![a, b, c, d, e, f, g, h] 99 = d := by dsimp only [Matrix.cons_val] end open Matrix example {a b c : α} {f : Fin 3 → α} : vecCons a (vecCons b (vecCons c f)) 0 = a := by dsimp only [Matrix.cons_val] example {a b c : α} {f : Fin 3 → α} : vecCons a (vecCons b (vecCons c f)) 2 = c := by dsimp only [Matrix.cons_val] example {a b c : α} {f : Fin 3 → α} : vecCons a (vecCons b (vecCons c f)) (-1) = f 2 := by dsimp only [Matrix.cons_val] example {a b c : α} {f : Fin 3 → α} : vecCons a (vecCons b (vecCons c f)) 8 = c := by dsimp only [Matrix.cons_val] example {a b c : α} {n : ℕ} {f : Fin n → α} : vecCons a (vecCons b (vecCons c f)) 0 = a := by dsimp only [Matrix.cons_val] example {a b c : α} {n : ℕ} {f : Fin n → α} : vecCons a (vecCons b (vecCons c f)) 2 = c := by dsimp only [Matrix.cons_val] example {a b c : α} {n : ℕ} {f : Fin n.succ → α} : vecCons a (vecCons b (vecCons c f)) 3 = f 0 := by dsimp only [Matrix.cons_val] example {a b c : α} {n : ℕ} {f : Fin n.succ → α} : vecCons a (vecCons b (vecCons c f)) 3 = f 0 := by dsimp only [Matrix.cons_val] example {a b c : α} {n : ℕ} {f : Fin (n + 2) → α} : vecCons a (vecCons b (vecCons c f)) 4 = f 1 := by dsimp only [Matrix.cons_val] -- these won't be true by `dsimp`, so need a separate simproc -- example {a b c : α} {n : ℕ} {f : Fin n.succ → α} : -- vecCons a (vecCons b (vecCons c f)) (-1) = f (-1) := by simp -- example {a b c : α} {n : ℕ} {f : Fin (n + 2) → α} : -- vecCons a (vecCons b (vecCons c f)) (-2) = f (-2) := by simp
Actions.lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.Group.Submonoid.DistribMulAction import Mathlib.GroupTheory.Subgroup.Center /-! # Actions by `Subgroup`s These are just copies of the definitions about `Submonoid` starting from `Submonoid.mulAction`. ## Tags subgroup, subgroups -/ namespace Subgroup variable {G α β : Type*} [Group G] section MulAction variable [MulAction G α] {S : Subgroup G} /-- The action by a subgroup is the action by the underlying group. -/ @[to_additive /-- The additive action by an add_subgroup is the action by the underlying `AddGroup`. -/] instance instMulAction : MulAction S α := inferInstanceAs (MulAction S.toSubmonoid α) @[to_additive] lemma smul_def (g : S) (m : α) : g • m = (g : G) • m := rfl @[to_additive (attr := simp)] lemma mk_smul (g : G) (hg : g ∈ S) (a : α) : (⟨g, hg⟩ : S) • a = g • a := rfl end MulAction @[to_additive] instance smulCommClass_left [MulAction G β] [SMul α β] [SMulCommClass G α β] (S : Subgroup G) : SMulCommClass S α β := S.toSubmonoid.smulCommClass_left @[to_additive] instance smulCommClass_right [SMul α β] [MulAction G β] [SMulCommClass α G β] (S : Subgroup G) : SMulCommClass α S β := S.toSubmonoid.smulCommClass_right /-- Note that this provides `IsScalarTower S G G` which is needed by `smul_mul_assoc`. -/ @[to_additive] instance [SMul α β] [MulAction G α] [MulAction G β] [IsScalarTower G α β] (S : Subgroup G) : IsScalarTower S α β := inferInstanceAs (IsScalarTower S.toSubmonoid α β) @[to_additive] instance [MulAction G α] [FaithfulSMul G α] (S : Subgroup G) : FaithfulSMul S α := inferInstanceAs (FaithfulSMul S.toSubmonoid α) /-- The action by a subgroup is the action by the underlying group. -/ instance [AddMonoid α] [DistribMulAction G α] (S : Subgroup G) : DistribMulAction S α := inferInstanceAs (DistribMulAction S.toSubmonoid α) /-- The action by a subgroup is the action by the underlying group. -/ instance [Monoid α] [MulDistribMulAction G α] (S : Subgroup G) : MulDistribMulAction S α := inferInstanceAs (MulDistribMulAction S.toSubmonoid α) /-- The center of a group acts commutatively on that group. -/ instance center.smulCommClass_left : SMulCommClass (center G) G G := Submonoid.center.smulCommClass_left /-- The center of a group acts commutatively on that group. -/ instance center.smulCommClass_right : SMulCommClass G (center G) G := Submonoid.center.smulCommClass_right end Subgroup
Ideals.lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Topology.Algebra.Algebra import Mathlib.Topology.ContinuousMap.Compact import Mathlib.Topology.UrysohnsLemma import Mathlib.Analysis.RCLike.Basic import Mathlib.Analysis.Normed.Ring.Units import Mathlib.Topology.Algebra.Module.CharacterSpace /-! # Ideals of continuous functions For a topological semiring `R` and a topological space `X` there is a Galois connection between `Ideal C(X, R)` and `Set X` given by sending each `I : Ideal C(X, R)` to `{x : X | ∀ f ∈ I, f x = 0}ᶜ` and mapping `s : Set X` to the ideal with carrier `{f : C(X, R) | ∀ x ∈ sᶜ, f x = 0}`, and we call these maps `ContinuousMap.setOfIdeal` and `ContinuousMap.idealOfSet`. As long as `R` is Hausdorff, `ContinuousMap.setOfIdeal I` is open, and if, in addition, `X` is locally compact, then `ContinuousMap.setOfIdeal s` is closed. When `R = 𝕜` with `RCLike 𝕜` and `X` is compact Hausdorff, then this Galois connection can be improved to a true Galois correspondence (i.e., order isomorphism) between the type `opens X` and the subtype of closed ideals of `C(X, 𝕜)`. Because we do not have a bundled type of closed ideals, we simply register this as a Galois insertion between `Ideal C(X, 𝕜)` and `opens X`, which is `ContinuousMap.idealOpensGI`. Consequently, the maximal ideals of `C(X, 𝕜)` are precisely those ideals corresponding to (complements of) singletons in `X`. In addition, when `X` is locally compact and `𝕜` is a nontrivial topological integral domain, then there is a natural continuous map from `X` to `WeakDual.characterSpace 𝕜 C(X, 𝕜)` given by point evaluation, which is herein called `WeakDual.CharacterSpace.continuousMapEval`. Again, when `X` is compact Hausdorff and `RCLike 𝕜`, more can be obtained. In particular, in that context this map is bijective, and since the domain is compact and the codomain is Hausdorff, it is a homeomorphism, herein called `WeakDual.CharacterSpace.homeoEval`. ## Main definitions * `ContinuousMap.idealOfSet`: ideal of functions which vanish on the complement of a set. * `ContinuousMap.setOfIdeal`: complement of the set on which all functions in the ideal vanish. * `ContinuousMap.opensOfIdeal`: `ContinuousMap.setOfIdeal` as a term of `opens X`. * `ContinuousMap.idealOpensGI`: The Galois insertion `ContinuousMap.opensOfIdeal` and `fun s ↦ ContinuousMap.idealOfSet ↑s`. * `WeakDual.CharacterSpace.continuousMapEval`: the natural continuous map from a locally compact topological space `X` to the `WeakDual.characterSpace 𝕜 C(X, 𝕜)` which sends `x : X` to point evaluation at `x`, with modest hypothesis on `𝕜`. * `WeakDual.CharacterSpace.homeoEval`: this is `WeakDual.CharacterSpace.continuousMapEval` upgraded to a homeomorphism when `X` is compact Hausdorff and `RCLike 𝕜`. ## Main statements * `ContinuousMap.idealOfSet_ofIdeal_eq_closure`: when `X` is compact Hausdorff and `RCLike 𝕜`, `idealOfSet 𝕜 (setOfIdeal I) = I.closure` for any ideal `I : Ideal C(X, 𝕜)`. * `ContinuousMap.setOfIdeal_ofSet_eq_interior`: when `X` is compact Hausdorff and `RCLike 𝕜`, `setOfIdeal (idealOfSet 𝕜 s) = interior s` for any `s : Set X`. * `ContinuousMap.ideal_isMaximal_iff`: when `X` is compact Hausdorff and `RCLike 𝕜`, a closed ideal of `C(X, 𝕜)` is maximal if and only if it is `idealOfSet 𝕜 {x}ᶜ` for some `x : X`. ## Implementation details Because there does not currently exist a bundled type of closed ideals, we don't provide the actual order isomorphism described above, and instead we only consider the Galois insertion `ContinuousMap.idealOpensGI`. ## Tags ideal, continuous function, compact, Hausdorff -/ open scoped NNReal namespace ContinuousMap open TopologicalSpace section IsTopologicalRing variable {X R : Type*} [TopologicalSpace X] [Semiring R] variable [TopologicalSpace R] [IsTopologicalSemiring R] variable (R) /-- Given a topological ring `R` and `s : Set X`, construct the ideal in `C(X, R)` of functions which vanish on the complement of `s`. -/ def idealOfSet (s : Set X) : Ideal C(X, R) where carrier := {f : C(X, R) | ∀ x ∈ sᶜ, f x = 0} add_mem' {f g} hf hg x hx := by simp [hf x hx, hg x hx, add_zero] zero_mem' _ _ := rfl smul_mem' c _ hf x hx := mul_zero (c x) ▸ congr_arg (fun y => c x * y) (hf x hx) theorem idealOfSet_closed [T2Space R] (s : Set X) : IsClosed (idealOfSet R s : Set C(X, R)) := by simp only [idealOfSet, Submodule.coe_set_mk, Set.setOf_forall] exact isClosed_iInter fun x => isClosed_iInter fun _ => isClosed_eq (continuous_eval_const x) continuous_const variable {R} theorem mem_idealOfSet {s : Set X} {f : C(X, R)} : f ∈ idealOfSet R s ↔ ∀ ⦃x : X⦄, x ∈ sᶜ → f x = 0 := by convert Iff.rfl theorem notMem_idealOfSet {s : Set X} {f : C(X, R)} : f ∉ idealOfSet R s ↔ ∃ x ∈ sᶜ, f x ≠ 0 := by simp_rw [mem_idealOfSet]; push_neg; rfl @[deprecated (since := "2025-05-23")] alias not_mem_idealOfSet := notMem_idealOfSet /-- Given an ideal `I` of `C(X, R)`, construct the set of points for which every function in the ideal vanishes on the complement. -/ def setOfIdeal (I : Ideal C(X, R)) : Set X := {x : X | ∀ f ∈ I, (f : C(X, R)) x = 0}ᶜ theorem notMem_setOfIdeal {I : Ideal C(X, R)} {x : X} : x ∉ setOfIdeal I ↔ ∀ ⦃f : C(X, R)⦄, f ∈ I → f x = 0 := by rw [← Set.mem_compl_iff, setOfIdeal, compl_compl, Set.mem_setOf] @[deprecated (since := "2025-05-23")] alias not_mem_setOfIdeal := notMem_setOfIdeal theorem mem_setOfIdeal {I : Ideal C(X, R)} {x : X} : x ∈ setOfIdeal I ↔ ∃ f ∈ I, (f : C(X, R)) x ≠ 0 := by simp_rw [setOfIdeal, Set.mem_compl_iff, Set.mem_setOf]; push_neg; rfl theorem setOfIdeal_open [T2Space R] (I : Ideal C(X, R)) : IsOpen (setOfIdeal I) := by simp only [setOfIdeal, Set.setOf_forall, isOpen_compl_iff] exact isClosed_iInter fun f => isClosed_iInter fun _ => isClosed_eq (map_continuous f) continuous_const /-- The open set `ContinuousMap.setOfIdeal I` realized as a term of `opens X`. -/ @[simps] def opensOfIdeal [T2Space R] (I : Ideal C(X, R)) : Opens X := ⟨setOfIdeal I, setOfIdeal_open I⟩ @[simp] theorem setOfTop_eq_univ [Nontrivial R] : setOfIdeal (⊤ : Ideal C(X, R)) = Set.univ := Set.univ_subset_iff.mp fun _ _ => mem_setOfIdeal.mpr ⟨1, Submodule.mem_top, one_ne_zero⟩ @[simp] theorem idealOfEmpty_eq_bot : idealOfSet R (∅ : Set X) = ⊥ := Ideal.ext fun f => by simp only [mem_idealOfSet, Set.compl_empty, Set.mem_univ, forall_true_left, Ideal.mem_bot, DFunLike.ext_iff, zero_apply] @[simp] theorem mem_idealOfSet_compl_singleton (x : X) (f : C(X, R)) : f ∈ idealOfSet R ({x}ᶜ : Set X) ↔ f x = 0 := by simp only [mem_idealOfSet, compl_compl, Set.mem_singleton_iff, forall_eq] variable (X R) theorem ideal_gc : GaloisConnection (setOfIdeal : Ideal C(X, R) → Set X) (idealOfSet R) := by refine fun I s => ⟨fun h f hf => ?_, fun h x hx => ?_⟩ · by_contra h' rcases notMem_idealOfSet.mp h' with ⟨x, hx, hfx⟩ exact hfx (notMem_setOfIdeal.mp (mt (@h x) hx) hf) · obtain ⟨f, hf, hfx⟩ := mem_setOfIdeal.mp hx by_contra hx' exact notMem_idealOfSet.mpr ⟨x, hx', hfx⟩ (h hf) end IsTopologicalRing section RCLike open RCLike variable {X 𝕜 : Type*} [RCLike 𝕜] [TopologicalSpace X] /-- An auxiliary lemma used in the proof of `ContinuousMap.idealOfSet_ofIdeal_eq_closure` which may be useful on its own. -/ theorem exists_mul_le_one_eqOn_ge (f : C(X, ℝ≥0)) {c : ℝ≥0} (hc : 0 < c) : ∃ g : C(X, ℝ≥0), (∀ x : X, (g * f) x ≤ 1) ∧ {x : X | c ≤ f x}.EqOn (g * f) 1 := ⟨{ toFun := (f ⊔ const X c)⁻¹ continuous_toFun := ((map_continuous f).sup <| map_continuous _).inv₀ fun _ => (hc.trans_le le_sup_right).ne' }, fun x => (inv_mul_le_iff₀ (hc.trans_le le_sup_right)).mpr ((mul_one (f x ⊔ c)).symm ▸ le_sup_left), fun x hx => by simpa only [coe_const, mul_apply, coe_mk, Pi.inv_apply, Pi.sup_apply, Function.const_apply, sup_eq_left.mpr (Set.mem_setOf.mp hx), ne_eq, Pi.one_apply] using inv_mul_cancel₀ (hc.trans_le hx).ne' ⟩ variable [CompactSpace X] [T2Space X] @[simp] theorem idealOfSet_ofIdeal_eq_closure (I : Ideal C(X, 𝕜)) : idealOfSet 𝕜 (setOfIdeal I) = I.closure := by /- Since `idealOfSet 𝕜 (setOfIdeal I)` is closed and contains `I`, it contains `I.closure`. For the reverse inclusion, given `f ∈ idealOfSet 𝕜 (setOfIdeal I)` and `(ε : ℝ≥0) > 0` it suffices to show that `f` is within `ε` of `I`. -/ refine le_antisymm ?_ ((idealOfSet_closed 𝕜 <| setOfIdeal I).closure_subset_iff.mpr fun f hf x hx => notMem_setOfIdeal.mp hx hf) refine (fun f hf => Metric.mem_closure_iff.mpr fun ε hε => ?_) lift ε to ℝ≥0 using hε.lt.le replace hε := show (0 : ℝ≥0) < ε from hε simp_rw [dist_nndist] norm_cast -- Let `t := {x : X | ε / 2 ≤ ‖f x‖₊}}` which is closed and disjoint from `set_of_ideal I`. set t := {x : X | ε / 2 ≤ ‖f x‖₊} have ht : IsClosed t := isClosed_le continuous_const (map_continuous f).nnnorm have htI : Disjoint t (setOfIdeal I)ᶜ := by refine Set.subset_compl_iff_disjoint_left.mp fun x hx => ?_ simpa only [t, Set.mem_setOf, Set.mem_compl_iff, not_le] using (nnnorm_eq_zero.mpr (mem_idealOfSet.mp hf hx)).trans_lt (half_pos hε) /- It suffices to produce `g : C(X, ℝ≥0)` which takes values in `[0,1]` and is constantly `1` on `t` such that when composed with the natural embedding of `ℝ≥0` into `𝕜` lies in the ideal `I`. Indeed, then `‖f - f * ↑g‖ ≤ ‖f * (1 - ↑g)‖ ≤ ⨆ ‖f * (1 - ↑g) x‖`. When `x ∉ t`, `‖f x‖ < ε / 2` and `‖(1 - ↑g) x‖ ≤ 1`, and when `x ∈ t`, `(1 - ↑g) x = 0`, and clearly `f * ↑g ∈ I`. -/ suffices ∃ g : C(X, ℝ≥0), (algebraMapCLM ℝ≥0 𝕜 : C(ℝ≥0, 𝕜)).comp g ∈ I ∧ (∀ x, g x ≤ 1) ∧ t.EqOn g 1 by obtain ⟨g, hgI, hg, hgt⟩ := this refine ⟨f * (algebraMapCLM ℝ≥0 𝕜 : C(ℝ≥0, 𝕜)).comp g, I.mul_mem_left f hgI, ?_⟩ rw [nndist_eq_nnnorm] refine (nnnorm_lt_iff _ hε).2 fun x => ?_ simp only [coe_sub, coe_mul, Pi.sub_apply, Pi.mul_apply] by_cases hx : x ∈ t · simpa only [hgt hx, comp_apply, Pi.one_apply, ContinuousMap.coe_coe, algebraMapCLM_apply, map_one, mul_one, sub_self, nnnorm_zero] using hε · refine lt_of_le_of_lt ?_ (half_lt_self hε) have := calc ‖((1 - (algebraMapCLM ℝ≥0 𝕜 : C(ℝ≥0, 𝕜)).comp g) x : 𝕜)‖₊ = ‖1 - algebraMap ℝ≥0 𝕜 (g x)‖₊ := by simp only [coe_sub, coe_one, coe_comp, ContinuousMap.coe_coe, Pi.sub_apply, Pi.one_apply, Function.comp_apply, algebraMapCLM_apply] _ = ‖algebraMap ℝ≥0 𝕜 (1 - g x)‖₊ := by simp only [Algebra.algebraMap_eq_smul_one, NNReal.smul_def, NNReal.coe_sub (hg x), NNReal.coe_one, sub_smul, one_smul] _ ≤ 1 := (nnnorm_algebraMap_nnreal 𝕜 (1 - g x)).trans_le tsub_le_self calc ‖f x - f x * (algebraMapCLM ℝ≥0 𝕜 : C(ℝ≥0, 𝕜)).comp g x‖₊ = ‖f x * (1 - (algebraMapCLM ℝ≥0 𝕜 : C(ℝ≥0, 𝕜)).comp g) x‖₊ := by simp only [mul_sub, coe_sub, coe_one, Pi.sub_apply, Pi.one_apply, mul_one] _ ≤ ε / 2 * ‖(1 - (algebraMapCLM ℝ≥0 𝕜 : C(ℝ≥0, 𝕜)).comp g) x‖₊ := ((nnnorm_mul_le _ _).trans (mul_le_mul_right' (not_le.mp <| show ¬ε / 2 ≤ ‖f x‖₊ from hx).le _)) _ ≤ ε / 2 := by simpa only [mul_one] using mul_le_mul_left' this _ /- There is some `g' : C(X, ℝ≥0)` which is strictly positive on `t` such that the composition `↑g` with the natural embedding of `ℝ≥0` into `𝕜` lies in `I`. This follows from compactness of `t` and that we can do it in any neighborhood of a point `x ∈ t`. Indeed, since `x ∈ t`, then `fₓ x ≠ 0` for some `fₓ ∈ I` and so `fun y ↦ ‖(star fₓ * fₓ) y‖₊` is strictly posiive in a neighborhood of `y`. Moreover, `(‖(star fₓ * fₓ) y‖₊ : 𝕜) = (star fₓ * fₓ) y`, so composition of this map with the natural embedding is just `star fₓ * fₓ ∈ I`. -/ have : ∃ g' : C(X, ℝ≥0), (algebraMapCLM ℝ≥0 𝕜 : C(ℝ≥0, 𝕜)).comp g' ∈ I ∧ ∀ x ∈ t, 0 < g' x := by refine ht.isCompact.induction_on ?_ ?_ ?_ ?_ · refine ⟨0, ?_, fun x hx => False.elim hx⟩ convert I.zero_mem ext simp only [comp_apply, zero_apply, ContinuousMap.coe_coe, map_zero] · rintro s₁ s₂ hs ⟨g, hI, hgt⟩; exact ⟨g, hI, fun x hx => hgt x (hs hx)⟩ · rintro s₁ s₂ ⟨g₁, hI₁, hgt₁⟩ ⟨g₂, hI₂, hgt₂⟩ refine ⟨g₁ + g₂, ?_, fun x hx => ?_⟩ · convert I.add_mem hI₁ hI₂ ext y simp only [coe_add, Pi.add_apply, map_add, coe_comp, Function.comp_apply, ContinuousMap.coe_coe] · rcases hx with (hx | hx) · simpa only [zero_add] using add_lt_add_of_lt_of_le (hgt₁ x hx) zero_le' · simpa only [zero_add] using add_lt_add_of_le_of_lt zero_le' (hgt₂ x hx) · intro x hx replace hx := htI.subset_compl_right hx rw [compl_compl, mem_setOfIdeal] at hx obtain ⟨g, hI, hgx⟩ := hx have := (map_continuous g).continuousAt.eventually_ne hgx refine ⟨{y : X | g y ≠ 0} ∩ t, mem_nhdsWithin_iff_exists_mem_nhds_inter.mpr ⟨_, this, Set.Subset.rfl⟩, ⟨⟨fun x => ‖g x‖₊ ^ 2, (map_continuous g).nnnorm.pow 2⟩, ?_, fun x hx => pow_pos (norm_pos_iff.mpr hx.1) 2⟩⟩ convert I.mul_mem_left (star g) hI ext simp only [comp_apply, ContinuousMap.coe_coe, coe_mk, algebraMapCLM_apply, map_pow, mul_apply, star_apply, star_def] simp only [RCLike.conj_mul] rfl /- Get the function `g'` which is guaranteed to exist above. By the extreme value theorem and compactness of `t`, there is some `0 < c` such that `c ≤ g' x` for all `x ∈ t`. Then by `exists_mul_le_one_eqOn_ge` there is some `g` for which `g * g'` is the desired function. -/ obtain ⟨g', hI', hgt'⟩ := this obtain ⟨c, hc, hgc'⟩ : ∃ c > 0, ∀ y : X, y ∈ t → c ≤ g' y := t.eq_empty_or_nonempty.elim (fun ht' => ⟨1, zero_lt_one, fun y hy => False.elim (by rwa [ht'] at hy)⟩) fun ht' => let ⟨x, hx, hx'⟩ := ht.isCompact.exists_isMinOn ht' (map_continuous g').continuousOn ⟨g' x, hgt' x hx, hx'⟩ obtain ⟨g, hg, hgc⟩ := exists_mul_le_one_eqOn_ge g' hc refine ⟨g * g', ?_, hg, hgc.mono hgc'⟩ convert I.mul_mem_left ((algebraMapCLM ℝ≥0 𝕜 : C(ℝ≥0, 𝕜)).comp g) hI' ext simp only [algebraMapCLM_coe, comp_apply, mul_apply, ContinuousMap.coe_coe, map_mul] theorem idealOfSet_ofIdeal_isClosed {I : Ideal C(X, 𝕜)} (hI : IsClosed (I : Set C(X, 𝕜))) : idealOfSet 𝕜 (setOfIdeal I) = I := (idealOfSet_ofIdeal_eq_closure I).trans (Ideal.ext <| Set.ext_iff.mp hI.closure_eq) variable (𝕜) @[simp] theorem setOfIdeal_ofSet_eq_interior (s : Set X) : setOfIdeal (idealOfSet 𝕜 s) = interior s := by refine Set.Subset.antisymm ((setOfIdeal_open (idealOfSet 𝕜 s)).subset_interior_iff.mpr fun x hx => let ⟨f, hf, hfx⟩ := mem_setOfIdeal.mp hx Set.notMem_compl_iff.mp (mt (@hf x) hfx)) fun x hx => ?_ -- If `x ∉ closure sᶜ`, we must produce `f : C(X, 𝕜)` which is zero on `sᶜ` and `f x ≠ 0`. rw [← compl_compl (interior s), ← closure_compl] at hx simp_rw [mem_setOfIdeal, mem_idealOfSet] /- Apply Urysohn's lemma to get `g : C(X, ℝ)` which is zero on `sᶜ` and `g x ≠ 0`, then compose with the natural embedding `ℝ ↪ 𝕜` to produce the desired `f`. -/ obtain ⟨g, hgs, hgx : Set.EqOn g 1 {x}, -⟩ := exists_continuous_zero_one_of_isClosed isClosed_closure isClosed_singleton (Set.disjoint_singleton_right.mpr hx) exact ⟨⟨fun x => g x, continuous_ofReal.comp (map_continuous g)⟩, by simpa only [coe_mk, ofReal_eq_zero] using fun x hx => hgs (subset_closure hx), by simpa only [coe_mk, hgx (Set.mem_singleton x), Pi.one_apply, RCLike.ofReal_one] using one_ne_zero⟩ theorem setOfIdeal_ofSet_of_isOpen {s : Set X} (hs : IsOpen s) : setOfIdeal (idealOfSet 𝕜 s) = s := (setOfIdeal_ofSet_eq_interior 𝕜 s).trans hs.interior_eq variable (X) in /-- The Galois insertion `ContinuousMap.opensOfIdeal : Ideal C(X, 𝕜) → Opens X` and `fun s ↦ ContinuousMap.idealOfSet ↑s`. -/ @[simps] def idealOpensGI : GaloisInsertion (opensOfIdeal : Ideal C(X, 𝕜) → Opens X) fun s => idealOfSet 𝕜 s where choice I _ := opensOfIdeal I.closure gc I s := ideal_gc X 𝕜 I s le_l_u s := (setOfIdeal_ofSet_of_isOpen 𝕜 s.isOpen).ge choice_eq I hI := congr_arg _ <| Ideal.ext (Set.ext_iff.mp (isClosed_of_closure_subset <| (idealOfSet_ofIdeal_eq_closure I ▸ hI : I.closure ≤ I)).closure_eq) theorem idealOfSet_isMaximal_iff (s : Opens X) : (idealOfSet 𝕜 (s : Set X)).IsMaximal ↔ IsCoatom s := by rw [Ideal.isMaximal_def] refine (idealOpensGI X 𝕜).isCoatom_iff (fun I hI => ?_) s rw [← Ideal.isMaximal_def] at hI exact idealOfSet_ofIdeal_isClosed inferInstance theorem idealOf_compl_singleton_isMaximal (x : X) : (idealOfSet 𝕜 ({x}ᶜ : Set X)).IsMaximal := (idealOfSet_isMaximal_iff 𝕜 (Closeds.singleton x).compl).mpr <| Opens.isCoatom_iff.mpr ⟨x, rfl⟩ variable {𝕜} theorem setOfIdeal_eq_compl_singleton (I : Ideal C(X, 𝕜)) [hI : I.IsMaximal] : ∃ x : X, setOfIdeal I = {x}ᶜ := by have h : (idealOfSet 𝕜 (setOfIdeal I)).IsMaximal := (idealOfSet_ofIdeal_isClosed (inferInstance : IsClosed (I : Set C(X, 𝕜)))).symm ▸ hI obtain ⟨x, hx⟩ := Opens.isCoatom_iff.1 ((idealOfSet_isMaximal_iff 𝕜 (opensOfIdeal I)).1 h) exact ⟨x, congr_arg (fun (s : Opens X) => (s : Set X)) hx⟩ theorem ideal_isMaximal_iff (I : Ideal C(X, 𝕜)) [hI : IsClosed (I : Set C(X, 𝕜))] : I.IsMaximal ↔ ∃ x : X, idealOfSet 𝕜 {x}ᶜ = I := by refine ⟨?_, fun h => let ⟨x, hx⟩ := h hx ▸ idealOf_compl_singleton_isMaximal 𝕜 x⟩ intro hI' obtain ⟨x, hx⟩ := setOfIdeal_eq_compl_singleton I exact ⟨x, by simpa only [idealOfSet_ofIdeal_eq_closure, I.closure_eq_of_isClosed hI] using congr_arg (idealOfSet 𝕜) hx.symm⟩ end RCLike end ContinuousMap namespace WeakDual namespace CharacterSpace open Function ContinuousMap variable (X 𝕜 : Type*) [TopologicalSpace X] section ContinuousMapEval variable [CommRing 𝕜] [TopologicalSpace 𝕜] [IsTopologicalRing 𝕜] variable [Nontrivial 𝕜] [NoZeroDivisors 𝕜] /-- The natural continuous map from a locally compact topological space `X` to the `WeakDual.characterSpace 𝕜 C(X, 𝕜)` which sends `x : X` to point evaluation at `x`. -/ def continuousMapEval : C(X, characterSpace 𝕜 C(X, 𝕜)) where toFun x := ⟨{ toFun := fun f => f x map_add' := fun _ _ => rfl map_smul' := fun _ _ => rfl cont := continuous_eval_const x }, by rw [CharacterSpace.eq_set_map_one_map_mul]; exact ⟨rfl, fun f g => rfl⟩⟩ continuous_toFun := by exact Continuous.subtype_mk (continuous_of_continuous_eval map_continuous) _ @[simp] theorem continuousMapEval_apply_apply (x : X) (f : C(X, 𝕜)) : continuousMapEval X 𝕜 x f = f x := rfl end ContinuousMapEval variable [CompactSpace X] [T2Space X] [RCLike 𝕜] theorem continuousMapEval_bijective : Bijective (continuousMapEval X 𝕜) := by refine ⟨fun x y hxy => ?_, fun φ => ?_⟩ · contrapose! hxy rcases exists_continuous_zero_one_of_isClosed (isClosed_singleton : _root_.IsClosed {x}) (isClosed_singleton : _root_.IsClosed {y}) (Set.disjoint_singleton.mpr hxy) with ⟨f, fx, fy, -⟩ rw [DFunLike.ne_iff] use (⟨fun (x : ℝ) => (x : 𝕜), RCLike.continuous_ofReal⟩ : C(ℝ, 𝕜)).comp f simpa only [continuousMapEval_apply_apply, ContinuousMap.comp_apply, coe_mk, Ne, RCLike.ofReal_inj] using ((fx (Set.mem_singleton x)).symm ▸ (fy (Set.mem_singleton y)).symm ▸ zero_ne_one : f x ≠ f y) · obtain ⟨x, hx⟩ := (ideal_isMaximal_iff (RingHom.ker φ)).mp inferInstance refine ⟨x, CharacterSpace.ext_ker <| Ideal.ext fun f => ?_⟩ simpa only [RingHom.mem_ker, continuousMapEval_apply_apply, mem_idealOfSet_compl_singleton, RingHom.mem_ker] using SetLike.ext_iff.mp hx f /-- This is the natural homeomorphism between a compact Hausdorff space `X` and the `WeakDual.characterSpace 𝕜 C(X, 𝕜)`. -/ noncomputable def homeoEval : X ≃ₜ characterSpace 𝕜 C(X, 𝕜) := @Continuous.homeoOfEquivCompactToT2 _ _ _ _ _ _ { Equiv.ofBijective _ (continuousMapEval_bijective X 𝕜) with toFun := continuousMapEval X 𝕜 } (map_continuous (continuousMapEval X 𝕜)) end CharacterSpace end WeakDual
PerpBisector.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Joseph Myers -/ import Mathlib.Analysis.InnerProductSpace.Orthogonal import Mathlib.Analysis.Normed.Group.AddTorsor /-! # Perpendicular bisector of a segment We define `AffineSubspace.perpBisector p₁ p₂` to be the perpendicular bisector of the segment `[p₁, p₂]`, as a bundled affine subspace. We also prove that a point belongs to the perpendicular bisector if and only if it is equidistant from `p₁` and `p₂`, as well as a few linear equations that define this subspace. ## Keywords euclidean geometry, perpendicular, perpendicular bisector, line segment bisector, equidistant -/ open Set open scoped RealInnerProductSpace variable {V P : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P] variable [NormedAddTorsor V P] noncomputable section namespace AffineSubspace variable {c p₁ p₂ : P} /-- Perpendicular bisector of a segment in a Euclidean affine space. -/ def perpBisector (p₁ p₂ : P) : AffineSubspace ℝ P := mk' (midpoint ℝ p₁ p₂) (LinearMap.ker (innerₛₗ ℝ (p₂ -ᵥ p₁))) /-- A point `c` belongs the perpendicular bisector of `[p₁, p₂] iff `p₂ -ᵥ p₁` is orthogonal to `c -ᵥ midpoint ℝ p₁ p₂`. -/ theorem mem_perpBisector_iff_inner_eq_zero' : c ∈ perpBisector p₁ p₂ ↔ ⟪p₂ -ᵥ p₁, c -ᵥ midpoint ℝ p₁ p₂⟫ = 0 := Iff.rfl /-- A point `c` belongs the perpendicular bisector of `[p₁, p₂] iff `c -ᵥ midpoint ℝ p₁ p₂` is orthogonal to `p₂ -ᵥ p₁`. -/ theorem mem_perpBisector_iff_inner_eq_zero : c ∈ perpBisector p₁ p₂ ↔ ⟪c -ᵥ midpoint ℝ p₁ p₂, p₂ -ᵥ p₁⟫ = 0 := inner_eq_zero_symm theorem mem_perpBisector_iff_inner_pointReflection_vsub_eq_zero : c ∈ perpBisector p₁ p₂ ↔ ⟪Equiv.pointReflection c p₁ -ᵥ p₂, p₂ -ᵥ p₁⟫ = 0 := by rw [mem_perpBisector_iff_inner_eq_zero, Equiv.pointReflection_apply, vsub_midpoint, invOf_eq_inv, ← smul_add, real_inner_smul_left, vadd_vsub_assoc] simp theorem mem_perpBisector_pointReflection_iff_inner_eq_zero : c ∈ perpBisector p₁ (Equiv.pointReflection p₂ p₁) ↔ ⟪c -ᵥ p₂, p₁ -ᵥ p₂⟫ = 0 := by rw [mem_perpBisector_iff_inner_eq_zero, midpoint_pointReflection_right, Equiv.pointReflection_apply, vadd_vsub_assoc, inner_add_right, add_self_eq_zero, ← neg_eq_zero, ← inner_neg_right, neg_vsub_eq_vsub_rev] theorem midpoint_mem_perpBisector (p₁ p₂ : P) : midpoint ℝ p₁ p₂ ∈ perpBisector p₁ p₂ := by simp [mem_perpBisector_iff_inner_eq_zero] theorem perpBisector_nonempty : (perpBisector p₁ p₂ : Set P).Nonempty := ⟨_, midpoint_mem_perpBisector _ _⟩ @[simp] theorem direction_perpBisector (p₁ p₂ : P) : (perpBisector p₁ p₂).direction = (ℝ ∙ (p₂ -ᵥ p₁))ᗮ := by rw [perpBisector, direction_mk'] ext x exact Submodule.mem_orthogonal_singleton_iff_inner_right.symm theorem mem_perpBisector_iff_inner_eq_inner : c ∈ perpBisector p₁ p₂ ↔ ⟪c -ᵥ p₁, p₂ -ᵥ p₁⟫ = ⟪c -ᵥ p₂, p₁ -ᵥ p₂⟫ := by rw [Iff.comm, mem_perpBisector_iff_inner_eq_zero, ← add_neg_eq_zero, ← inner_neg_right, neg_vsub_eq_vsub_rev, ← inner_add_left, vsub_midpoint, invOf_eq_inv, ← smul_add, real_inner_smul_left]; simp theorem mem_perpBisector_iff_inner_eq : c ∈ perpBisector p₁ p₂ ↔ ⟪c -ᵥ p₁, p₂ -ᵥ p₁⟫ = (dist p₁ p₂) ^ 2 / 2 := by rw [mem_perpBisector_iff_inner_eq_zero, ← vsub_sub_vsub_cancel_right _ _ p₁, inner_sub_left, sub_eq_zero, midpoint_vsub_left, invOf_eq_inv, real_inner_smul_left, real_inner_self_eq_norm_sq, dist_eq_norm_vsub' V, div_eq_inv_mul] theorem mem_perpBisector_iff_dist_eq : c ∈ perpBisector p₁ p₂ ↔ dist c p₁ = dist c p₂ := by rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← real_inner_add_sub_eq_zero_iff, vsub_sub_vsub_cancel_left, inner_add_left, add_eq_zero_iff_eq_neg, ← inner_neg_right, neg_vsub_eq_vsub_rev, mem_perpBisector_iff_inner_eq_inner] theorem mem_perpBisector_iff_dist_eq' : c ∈ perpBisector p₁ p₂ ↔ dist p₁ c = dist p₂ c := by simp only [mem_perpBisector_iff_dist_eq, dist_comm] theorem perpBisector_comm (p₁ p₂ : P) : perpBisector p₁ p₂ = perpBisector p₂ p₁ := by ext c; simp only [mem_perpBisector_iff_dist_eq, eq_comm] @[simp] theorem right_mem_perpBisector : p₂ ∈ perpBisector p₁ p₂ ↔ p₁ = p₂ := by simpa [mem_perpBisector_iff_inner_eq_inner] using eq_comm @[simp] theorem left_mem_perpBisector : p₁ ∈ perpBisector p₁ p₂ ↔ p₁ = p₂ := by rw [perpBisector_comm, right_mem_perpBisector, eq_comm] @[simp] theorem perpBisector_self (p : P) : perpBisector p p = ⊤ := top_unique fun _ ↦ by simp [mem_perpBisector_iff_inner_eq_inner] @[simp] theorem perpBisector_eq_top : perpBisector p₁ p₂ = ⊤ ↔ p₁ = p₂ := by refine ⟨fun h ↦ ?_, fun h ↦ h ▸ perpBisector_self _⟩ rw [← left_mem_perpBisector, h] trivial @[simp] theorem perpBisector_ne_bot : perpBisector p₁ p₂ ≠ ⊥ := by rw [← nonempty_iff_ne_bot]; exact perpBisector_nonempty end AffineSubspace open AffineSubspace namespace EuclideanGeometry /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ theorem inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := by rw [← Submodule.mem_orthogonal_singleton_iff_inner_left, ← direction_perpBisector] apply vsub_mem_direction <;> rwa [mem_perpBisector_iff_dist_eq'] end EuclideanGeometry variable {V' P' : Type*} [NormedAddCommGroup V'] [InnerProductSpace ℝ V'] [MetricSpace P'] variable [NormedAddTorsor V' P'] theorem Isometry.preimage_perpBisector {f : P → P'} (h : Isometry f) (p₁ p₂ : P) : f ⁻¹' (perpBisector (f p₁) (f p₂)) = perpBisector p₁ p₂ := by ext x; simp [mem_perpBisector_iff_dist_eq, h.dist_eq] theorem Isometry.mapsTo_perpBisector {f : P → P'} (h : Isometry f) (p₁ p₂ : P) : MapsTo f (perpBisector p₁ p₂) (perpBisector (f p₁) (f p₂)) := (h.preimage_perpBisector p₁ p₂).ge
KleisliCat.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.CategoryTheory.Category.Basic /-! # The Kleisli construction on the Type category Define the Kleisli category for (control) monads. `CategoryTheory/Monad/Kleisli` defines the general version for a monad on `C`, and demonstrates the equivalence between the two. ## TODO Generalise this to work with CategoryTheory.Monad -/ universe u v namespace CategoryTheory -- This file is about Lean 3 declaration "Kleisli". /-- The Kleisli category on the (type-)monad `m`. Note that the monad is not assumed to be lawful yet. -/ @[nolint unusedArguments] def KleisliCat (_ : Type u → Type v) := Type u /-- Construct an object of the Kleisli category from a type. -/ def KleisliCat.mk (m) (α : Type u) : KleisliCat m := α instance KleisliCat.categoryStruct {m} [Monad.{u, v} m] : CategoryStruct (KleisliCat m) where Hom α β := α → m β id _ x := pure x comp f g := f >=> g instance KleisliCat.category {m} [Monad.{u, v} m] [LawfulMonad m] : Category (KleisliCat m) := by -- Porting note: was -- refine' { id_comp' := _, comp_id' := _, assoc' := _ } <;> intros <;> ext <;> unfold_projs <;> -- simp only [(· >=> ·), functor_norm] refine { id_comp := ?_, comp_id := ?_, assoc := ?_ } <;> intros <;> refine funext (fun x => ?_) <;> simp +unfoldPartialApp [CategoryStruct.id, CategoryStruct.comp, (· >=> ·)] @[simp] theorem KleisliCat.id_def {m} [Monad m] (α : KleisliCat m) : 𝟙 α = @pure m _ α := rfl theorem KleisliCat.comp_def {m} [Monad m] (α β γ : KleisliCat m) (xs : α ⟶ β) (ys : β ⟶ γ) (a : α) : (xs ≫ ys) a = xs a >>= ys := rfl instance : Inhabited (KleisliCat id) := ⟨PUnit⟩ instance {α : Type u} [Inhabited α] : Inhabited (KleisliCat.mk id α) := ⟨show α from default⟩ end CategoryTheory
interval_inference.v
(* mathcomp analysis (c) 2017 Inria and AIST. License: CeCILL-C. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype choice. From mathcomp Require Import order ssralg ssrnum ssrint interval. (**md**************************************************************************) (* # Numbers within an interval *) (* *) (* This file develops tools to make the manipulation of numbers within *) (* a known interval easier, thanks to canonical structures. This adds types *) (* like {itv R & `[a, b]}, a notation e%:itv that infers an enclosing *) (* interval for expression e according to existing canonical instances and *) (* %:num to cast back from type {itv R & i} to R. *) (* For instance, for x : {i01 R}, we have (1 - x%:num)%:itv : {i01 R} *) (* automatically inferred. *) (* *) (* ## types for values within known interval *) (* *) (* ``` *) (* {itv R & i} == generic type of values in interval i : interval int *) (* See interval.v for notations that can be used for i. *) (* R must have a numDomainType structure. This type is shown *) (* to be a porderType. *) (* {i01 R} := {itv R & `[0, 1]} *) (* Allows to solve automatically goals of the form x >= 0 *) (* and x <= 1 when x is canonically a {i01 R}. *) (* {i01 R} is canonically stable by common operations. *) (* {posnum R} := {itv R & `]0, +oo[) *) (* {nonneg R} := {itv R & `[0, +oo[) *) (* ``` *) (* *) (* ## casts from/to values within known interval *) (* *) (* Explicit casts of x to some {itv R & i} according to existing canonical *) (* instances: *) (* ``` *) (* x%:itv == cast to the most precisely known {itv R & i} *) (* x%:i01 == cast to {i01 R}, or fail *) (* x%:pos == cast to {posnum R}, or fail *) (* x%:nng == cast to {nonneg R}, or fail *) (* ``` *) (* *) (* Explicit casts of x from some {itv R & i} to R: *) (* ``` *) (* x%:num == cast from {itv R & i} *) (* x%:posnum == cast from {posnum R} *) (* x%:nngnum == cast from {nonneg R} *) (* ``` *) (* *) (* ## sign proofs *) (* *) (* ``` *) (* [itv of x] == proof that x is in the interval inferred by x%:itv *) (* [gt0 of x] == proof that x > 0 *) (* [lt0 of x] == proof that x < 0 *) (* [ge0 of x] == proof that x >= 0 *) (* [le0 of x] == proof that x <= 0 *) (* [cmp0 of x] == proof that 0 >=< x *) (* [neq0 of x] == proof that x != 0 *) (* ``` *) (* *) (* ## constructors *) (* *) (* ``` *) (* ItvNum xr lx xu == builds a {itv R & i} from proofs xr : x \in Num.real, *) (* lx : map_itv_bound (Itv.num_sem R) l <= BLeft x *) (* xu : BRight x <= map_itv_bound (Itv.num_sem R) u *) (* where x : R with R : numDomainType *) (* and l u : itv_bound int *) (* ItvReal lx xu == builds a {itv R & i} from proofs *) (* lx : map_itv_bound (Itv.num_sem R) l <= BLeft x *) (* xu : BRight x <= map_itv_bound (Itv.num_sem R) u *) (* where x : R with R : realDomainType *) (* and l u : itv_bound int *) (* Itv01 x0 x1 == builds a {i01 R} from proofs x0 : 0 <= x and x1 : x <= 1*) (* where x : R with R : numDomainType *) (* PosNum x0 == builds a {posnum R} from a proof x0 : x > 0 where x : R *) (* NngNum x0 == builds a {posnum R} from a proof x0 : x >= 0 where x : R*) (* ``` *) (* *) (* A number of canonical instances are provided for common operations, if *) (* your favorite operator is missing, look below for examples on how to add *) (* the appropriate Canonical. *) (* Also note that all provided instances aren't necessarily optimal, *) (* improvements welcome! *) (* Canonical instances are also provided according to types, as a *) (* fallback when no known operator appears in the expression. Look to top_typ *) (* below for an example on how to add your favorite type. *) (* *) (******************************************************************************) Reserved Notation "{ 'itv' R & i }" (R at level 200, i at level 200, format "{ 'itv' R & i }"). Reserved Notation "{ 'i01' R }" (R at level 200, format "{ 'i01' R }"). Reserved Notation "{ 'posnum' R }" (format "{ 'posnum' R }"). Reserved Notation "{ 'nonneg' R }" (format "{ 'nonneg' R }"). Reserved Notation "x %:itv" (format "x %:itv"). Reserved Notation "x %:i01" (format "x %:i01"). Reserved Notation "x %:pos" (format "x %:pos"). Reserved Notation "x %:nng" (format "x %:nng"). Reserved Notation "x %:inum" (format "x %:inum"). Reserved Notation "x %:num" (format "x %:num"). Reserved Notation "x %:posnum" (format "x %:posnum"). Reserved Notation "x %:nngnum" (format "x %:nngnum"). Reserved Notation "[ 'itv' 'of' x ]" (format "[ 'itv' 'of' x ]"). Reserved Notation "[ 'gt0' 'of' x ]" (format "[ 'gt0' 'of' x ]"). Reserved Notation "[ 'lt0' 'of' x ]" (format "[ 'lt0' 'of' x ]"). Reserved Notation "[ 'ge0' 'of' x ]" (format "[ 'ge0' 'of' x ]"). Reserved Notation "[ 'le0' 'of' x ]" (format "[ 'le0' 'of' x ]"). Reserved Notation "[ 'cmp0' 'of' x ]" (format "[ 'cmp0' 'of' x ]"). Reserved Notation "[ 'neq0' 'of' x ]" (format "[ 'neq0' 'of' x ]"). Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import Order.TTheory Order.Syntax. Import GRing.Theory Num.Theory. Local Open Scope ring_scope. Local Open Scope order_scope. Definition map_itv_bound S T (f : S -> T) (b : itv_bound S) : itv_bound T := match b with | BSide b x => BSide b (f x) | BInfty b => BInfty _ b end. Lemma map_itv_bound_comp S T U (f : T -> S) (g : U -> T) (b : itv_bound U) : map_itv_bound (f \o g) b = map_itv_bound f (map_itv_bound g b). Proof. by case: b. Qed. Definition map_itv S T (f : S -> T) (i : interval S) : interval T := let 'Interval l u := i in Interval (map_itv_bound f l) (map_itv_bound f u). Lemma map_itv_comp S T U (f : T -> S) (g : U -> T) (i : interval U) : map_itv (f \o g) i = map_itv f (map_itv g i). Proof. by case: i => l u /=; rewrite -!map_itv_bound_comp. Qed. (* First, the interval arithmetic operations we will later use *) Module IntItv. Implicit Types (b : itv_bound int) (i j : interval int). Definition opp_bound b := match b with | BSide b x => BSide (~~ b) (intZmod.oppz x) | BInfty b => BInfty _ (~~ b) end. Lemma opp_bound_ge0 b : (BLeft 0%R <= opp_bound b)%O = (b <= BRight 0%R)%O. Proof. by case: b => [[] b | []//]; rewrite /= !bnd_simp oppr_ge0. Qed. Lemma opp_bound_gt0 b : (BRight 0%R <= opp_bound b)%O = (b <= BLeft 0%R)%O. Proof. by case: b => [[] b | []//]; rewrite /= !bnd_simp ?oppr_ge0 ?oppr_gt0. Qed. Definition opp i := let: Interval l u := i in Interval (opp_bound u) (opp_bound l). Arguments opp /. Definition add_boundl b1 b2 := match b1, b2 with | BSide b1 x1, BSide b2 x2 => BSide (b1 && b2) (intZmod.addz x1 x2) | _, _ => BInfty _ true end. Definition add_boundr b1 b2 := match b1, b2 with | BSide b1 x1, BSide b2 x2 => BSide (b1 || b2) (intZmod.addz x1 x2) | _, _ => BInfty _ false end. Definition add i1 i2 := let: Interval l1 u1 := i1 in let: Interval l2 u2 := i2 in Interval (add_boundl l1 l2) (add_boundr u1 u2). Arguments add /. Variant signb := EqZero | NonNeg | NonPos. Definition sign_boundl b := let: b0 := BLeft 0%Z in if b == b0 then EqZero else if (b <= b0)%O then NonPos else NonNeg. Definition sign_boundr b := let: b0 := BRight 0%Z in if b == b0 then EqZero else if (b <= b0)%O then NonPos else NonNeg. Variant signi := Known of signb | Unknown | Empty. Definition sign i : signi := let: Interval l u := i in match sign_boundl l, sign_boundr u with | EqZero, NonPos | NonNeg, EqZero | NonNeg, NonPos => Empty | EqZero, EqZero => Known EqZero | NonPos, EqZero | NonPos, NonPos => Known NonPos | EqZero, NonNeg | NonNeg, NonNeg => Known NonNeg | NonPos, NonNeg => Unknown end. Definition mul_boundl b1 b2 := match b1, b2 with | BInfty _, _ | _, BInfty _ | BLeft 0%Z, _ | _, BLeft 0%Z => BLeft 0%Z | BSide b1 x1, BSide b2 x2 => BSide (b1 && b2) (intRing.mulz x1 x2) end. Definition mul_boundr b1 b2 := match b1, b2 with | BLeft 0%Z, _ | _, BLeft 0%Z => BLeft 0%Z | BRight 0%Z, _ | _, BRight 0%Z => BRight 0%Z | BSide b1 x1, BSide b2 x2 => BSide (b1 || b2) (intRing.mulz x1 x2) | _, BInfty _ | BInfty _, _ => +oo%O end. Lemma mul_boundrC b1 b2 : mul_boundr b1 b2 = mul_boundr b2 b1. Proof. by move: b1 b2 => [[] [[|?]|?] | []] [[] [[|?]|?] | []] //=; rewrite mulnC. Qed. Lemma mul_boundr_gt0 b1 b2 : (BRight 0%Z <= b1 -> BRight 0%Z <= b2 -> BRight 0%Z <= mul_boundr b1 b2)%O. Proof. case: b1 b2 => [b1b b1 | []] [b2b b2 | []]//=. - by case: b1b b2b => -[]; case: b1 b2 => [[|b1] | b1] [[|b2] | b2]. - by case: b1b b1 => -[[] |]. - by case: b2b b2 => -[[] |]. Qed. Definition mul i1 i2 := let: Interval l1 u1 := i1 in let: Interval l2 u2 := i2 in let: opp := opp_bound in let: mull := mul_boundl in let: mulr := mul_boundr in match sign i1, sign i2 with | Empty, _ | _, Empty => `[1, 0] | Known EqZero, _ | _, Known EqZero => `[0, 0] | Known NonNeg, Known NonNeg => Interval (mull l1 l2) (mulr u1 u2) | Known NonPos, Known NonPos => Interval (mull (opp u1) (opp u2)) (mulr (opp l1) (opp l2)) | Known NonNeg, Known NonPos => Interval (opp (mulr u1 (opp l2))) (opp (mull l1 (opp u2))) | Known NonPos, Known NonNeg => Interval (opp (mulr (opp l1) u2)) (opp (mull (opp u1) l2)) | Known NonNeg, Unknown => Interval (opp (mulr u1 (opp l2))) (mulr u1 u2) | Known NonPos, Unknown => Interval (opp (mulr (opp l1) u2)) (mulr (opp l1) (opp l2)) | Unknown, Known NonNeg => Interval (opp (mulr (opp l1) u2)) (mulr u1 u2) | Unknown, Known NonPos => Interval (opp (mulr u1 (opp l2))) (mulr (opp l1) (opp l2)) | Unknown, Unknown => Interval (Order.min (opp (mulr (opp l1) u2)) (opp (mulr u1 (opp l2)))) (Order.max (mulr (opp l1) (opp l2)) (mulr u1 u2)) end. Arguments mul /. Definition min i j := let: Interval li ui := i in let: Interval lj uj := j in Interval (Order.min li lj) (Order.min ui uj). Arguments min /. Definition max i j := let: Interval li ui := i in let: Interval lj uj := j in Interval (Order.max li lj) (Order.max ui uj). Arguments max /. Definition keep_nonneg_bound b := match b with | BSide _ (Posz _) => BLeft 0%Z | BSide _ (Negz _) => -oo%O | BInfty _ => -oo%O end. Arguments keep_nonneg_bound /. Definition keep_pos_bound b := match b with | BSide b 0%Z => BSide b 0%Z | BSide _ (Posz (S _)) => BRight 0%Z | BSide _ (Negz _) => -oo | BInfty _ => -oo end. Arguments keep_pos_bound /. Definition keep_nonpos_bound b := match b with | BSide _ (Negz _) | BSide _ (Posz 0) => BRight 0%Z | BSide _ (Posz (S _)) => +oo%O | BInfty _ => +oo%O end. Arguments keep_nonpos_bound /. Definition keep_neg_bound b := match b with | BSide b 0%Z => BSide b 0%Z | BSide _ (Negz _) => BLeft 0%Z | BSide _ (Posz _) => +oo | BInfty _ => +oo end. Arguments keep_neg_bound /. Definition inv i := let: Interval l u := i in Interval (keep_pos_bound l) (keep_neg_bound u). Arguments inv /. Definition exprn_le1_bound b1 b2 := if b2 isn't BSide _ 1%Z then +oo else if (BLeft (-1)%Z <= b1)%O then BRight 1%Z else +oo. Arguments exprn_le1_bound /. Definition exprn i := let: Interval l u := i in Interval (keep_pos_bound l) (exprn_le1_bound l u). Arguments exprn /. Definition exprz i1 i2 := let: Interval l2 _ := i2 in if l2 is BSide _ (Posz _) then exprn i1 else let: Interval l u := i1 in Interval (keep_pos_bound l) +oo. Arguments exprz /. Definition keep_sign i := let: Interval l u := i in Interval (keep_nonneg_bound l) (keep_nonpos_bound u). (* used in ereal.v *) Definition keep_nonpos i := let 'Interval l u := i in Interval -oo%O (keep_nonpos_bound u). Arguments keep_nonpos /. (* used in ereal.v *) Definition keep_nonneg i := let 'Interval l u := i in Interval (keep_nonneg_bound l) +oo%O. Arguments keep_nonneg /. End IntItv. Module Itv. Variant t := Top | Real of interval int. Definition sub (x y : t) := match x, y with | _, Top => true | Top, Real _ => false | Real xi, Real yi => subitv xi yi end. Section Itv. Context T (sem : interval int -> T -> bool). Definition spec (i : t) (x : T) := if i is Real i then sem i x else true. Record def (i : t) := Def { r : T; #[canonical=no] P : spec i r }. End Itv. Record typ i := Typ { sort : Type; #[canonical=no] sort_sem : interval int -> sort -> bool; #[canonical=no] allP : forall x : sort, spec sort_sem i x }. Definition mk {T f} i x P : @def T f i := @Def T f i x P. Definition from {T f i} {x : @def T f i} (phx : phantom T (r x)) := x. Definition fromP {T f i} {x : @def T f i} (phx : phantom T (r x)) := P x. Definition num_sem (R : numDomainType) (i : interval int) (x : R) : bool := (x \in Num.real) && (x \in map_itv intr i). Definition nat_sem (i : interval int) (x : nat) : bool := Posz x \in i. Definition posnum (R : numDomainType) of phant R := def (@num_sem R) (Real `]0, +oo[). Definition nonneg (R : numDomainType) of phant R := def (@num_sem R) (Real `[0, +oo[). (* a few lifting helper functions *) Definition real1 (op1 : interval int -> interval int) (x : Itv.t) : Itv.t := match x with Itv.Top => Itv.Top | Itv.Real x => Itv.Real (op1 x) end. Definition real2 (op2 : interval int -> interval int -> interval int) (x y : Itv.t) : Itv.t := match x, y with | Itv.Top, _ | _, Itv.Top => Itv.Top | Itv.Real x, Itv.Real y => Itv.Real (op2 x y) end. Lemma spec_real1 T f (op1 : T -> T) (op1i : interval int -> interval int) : forall (x : T), (forall xi, f xi x = true -> f (op1i xi) (op1 x) = true) -> forall xi, spec f xi x -> spec f (real1 op1i xi) (op1 x). Proof. by move=> x + [//| xi]; apply. Qed. Lemma spec_real2 T f (op2 : T -> T -> T) (op2i : interval int -> interval int -> interval int) (x y : T) : (forall xi yi, f xi x = true -> f yi y = true -> f (op2i xi yi) (op2 x y) = true) -> forall xi yi, spec f xi x -> spec f yi y -> spec f (real2 op2i xi yi) (op2 x y). Proof. by move=> + [//| xi] [//| yi]; apply. Qed. Module Exports. Arguments r {T sem i}. Notation "{ 'itv' R & i }" := (def (@num_sem R) (Itv.Real i%Z)) : type_scope. Notation "{ 'i01' R }" := {itv R & `[0, 1]} : type_scope. Notation "{ 'posnum' R }" := (@posnum _ (Phant R)) : ring_scope. Notation "{ 'nonneg' R }" := (@nonneg _ (Phant R)) : ring_scope. Notation "x %:itv" := (from (Phantom _ x)) : ring_scope. Notation "[ 'itv' 'of' x ]" := (fromP (Phantom _ x)) : ring_scope. Notation num := r. Notation "x %:inum" := (r x) (only parsing) : ring_scope. Notation "x %:num" := (r x) : ring_scope. Notation "x %:posnum" := (@r _ _ (Real `]0%Z, +oo[) x) : ring_scope. Notation "x %:nngnum" := (@r _ _ (Real `[0%Z, +oo[) x) : ring_scope. End Exports. End Itv. Export Itv.Exports. Local Notation num_spec := (Itv.spec (@Itv.num_sem _)). Local Notation num_def R := (Itv.def (@Itv.num_sem R)). Local Notation num_itv_bound R := (@map_itv_bound _ R intr). Local Notation nat_spec := (Itv.spec Itv.nat_sem). Local Notation nat_def := (Itv.def Itv.nat_sem). Section POrder. Context d (T : porderType d) (f : interval int -> T -> bool) (i : Itv.t). Local Notation itv := (Itv.def f i). HB.instance Definition _ := [isSub for @Itv.r T f i]. HB.instance Definition _ : Order.POrder d itv := [POrder of itv by <:]. End POrder. Section Order. Variables (R : numDomainType) (i : interval int). Local Notation nR := (num_def R (Itv.Real i)). Lemma itv_le_total_subproof : total (<=%O : rel nR). Proof. move=> x y; apply: real_comparable. - by case: x => [x /=/andP[]]. - by case: y => [y /=/andP[]]. Qed. HB.instance Definition _ := Order.POrder_isTotal.Build ring_display nR itv_le_total_subproof. End Order. Module TypInstances. Lemma top_typ_spec T f (x : T) : Itv.spec f Itv.Top x. Proof. by []. Qed. Canonical top_typ T f := Itv.Typ (@top_typ_spec T f). Lemma real_domain_typ_spec (R : realDomainType) (x : R) : num_spec (Itv.Real `]-oo, +oo[) x. Proof. by rewrite /Itv.num_sem/= num_real. Qed. Canonical real_domain_typ (R : realDomainType) := Itv.Typ (@real_domain_typ_spec R). Lemma real_field_typ_spec (R : realFieldType) (x : R) : num_spec (Itv.Real `]-oo, +oo[) x. Proof. exact: real_domain_typ_spec. Qed. Canonical real_field_typ (R : realFieldType) := Itv.Typ (@real_field_typ_spec R). Lemma nat_typ_spec (x : nat) : nat_spec (Itv.Real `[0, +oo[) x. Proof. by []. Qed. Canonical nat_typ := Itv.Typ nat_typ_spec. Lemma typ_inum_spec (i : Itv.t) (xt : Itv.typ i) (x : Itv.sort xt) : Itv.spec (@Itv.sort_sem _ xt) i x. Proof. by move: xt x => []. Qed. (* This adds _ <- Itv.r ( typ_inum ) to canonical projections (c.f., Print Canonical Projections Itv.r) meaning that if no other canonical instance (with a registered head symbol) is found, a canonical instance of Itv.typ, like the ones above, will be looked for. *) Canonical typ_inum (i : Itv.t) (xt : Itv.typ i) (x : Itv.sort xt) := Itv.mk (typ_inum_spec x). End TypInstances. Export (canonicals) TypInstances. Class unify {T} f (x y : T) := Unify : f x y = true. #[export] Hint Mode unify + + + + : typeclass_instances. Class unify' {T} f (x y : T) := Unify' : f x y = true. #[export] Instance unify'P {T} f (x y : T) : unify' f x y -> unify f x y := id. #[export] Hint Extern 0 (unify' _ _ _) => vm_compute; reflexivity : typeclass_instances. Notation unify_itv ix iy := (unify Itv.sub ix iy). #[export] Instance top_wider_anything i : unify_itv i Itv.Top. Proof. by case: i. Qed. #[export] Instance real_wider_anyreal i : unify_itv (Itv.Real i) (Itv.Real `]-oo, +oo[). Proof. by case: i => [l u]; apply/andP; rewrite !bnd_simp. Qed. Section NumDomainTheory. Context {R : numDomainType} {i : Itv.t}. Implicit Type x : num_def R i. Lemma le_num_itv_bound (x y : itv_bound int) : (num_itv_bound R x <= num_itv_bound R y)%O = (x <= y)%O. Proof. by case: x y => [[] x | x] [[] y | y]//=; rewrite !bnd_simp ?ler_int ?ltr_int. Qed. Lemma num_itv_bound_le_BLeft (x : itv_bound int) (y : int) : (num_itv_bound R x <= BLeft (y%:~R : R))%O = (x <= BLeft y)%O. Proof. rewrite -[BLeft y%:~R]/(map_itv_bound intr (BLeft y)). by rewrite le_num_itv_bound. Qed. Lemma BRight_le_num_itv_bound (x : int) (y : itv_bound int) : (BRight (x%:~R : R) <= num_itv_bound R y)%O = (BRight x <= y)%O. Proof. rewrite -[BRight x%:~R]/(map_itv_bound intr (BRight x)). by rewrite le_num_itv_bound. Qed. Lemma num_spec_sub (x y : Itv.t) : Itv.sub x y -> forall z : R, num_spec x z -> num_spec y z. Proof. case: x y => [| x] [| y] //= x_sub_y z /andP[rz]; rewrite /Itv.num_sem rz/=. move: x y x_sub_y => [lx ux] [ly uy] /andP[lel leu] /=. move=> /andP[lxz zux]; apply/andP; split. - by apply: le_trans lxz; rewrite le_num_itv_bound. - by apply: le_trans zux _; rewrite le_num_itv_bound. Qed. Definition empty_itv := Itv.Real `[1, 0]%Z. Lemma bottom x : ~ unify_itv i empty_itv. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=. by rewrite in_itv/= => /andP[] /le_trans /[apply]; rewrite ler10. Qed. Lemma gt0 x : unify_itv i (Itv.Real `]0%Z, +oo[) -> 0 < x%:num :> R. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_]. by rewrite /= in_itv/= andbT. Qed. Lemma le0F x : unify_itv i (Itv.Real `]0%Z, +oo[) -> x%:num <= 0 :> R = false. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=. by rewrite in_itv/= andbT => /lt_geF. Qed. Lemma lt0 x : unify_itv i (Itv.Real `]-oo, 0%Z[) -> x%:num < 0 :> R. Proof. by case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=; rewrite in_itv. Qed. Lemma ge0F x : unify_itv i (Itv.Real `]-oo, 0%Z[) -> 0 <= x%:num :> R = false. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=. by rewrite in_itv/= => /lt_geF. Qed. Lemma ge0 x : unify_itv i (Itv.Real `[0%Z, +oo[) -> 0 <= x%:num :> R. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=. by rewrite in_itv/= andbT. Qed. Lemma lt0F x : unify_itv i (Itv.Real `[0%Z, +oo[) -> x%:num < 0 :> R = false. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=. by rewrite in_itv/= andbT => /le_gtF. Qed. Lemma le0 x : unify_itv i (Itv.Real `]-oo, 0%Z]) -> x%:num <= 0 :> R. Proof. by case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=; rewrite in_itv. Qed. Lemma gt0F x : unify_itv i (Itv.Real `]-oo, 0%Z]) -> 0 < x%:num :> R = false. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=. by rewrite in_itv/= => /le_gtF. Qed. Lemma cmp0 x : unify_itv i (Itv.Real `]-oo, +oo[) -> 0 >=< x%:num. Proof. by case: i x => [//| i' [x /=/andP[]]]. Qed. Lemma neq0 x : unify (fun ix iy => ~~ Itv.sub ix iy) (Itv.Real `[0%Z, 0%Z]) i -> x%:num != 0 :> R. Proof. case: i x => [//| [l u] [x /= Px]]; apply: contra => /eqP x0 /=. move: Px; rewrite x0 => /and3P[_ /= l0 u0]; apply/andP; split. - by case: l l0 => [[] l /= |//]; rewrite !bnd_simp ?lerz0 ?ltrz0. - by case: u u0 => [[] u /= |//]; rewrite !bnd_simp ?ler0z ?ltr0z. Qed. Lemma eq0F x : unify (fun ix iy => ~~ Itv.sub ix iy) (Itv.Real `[0%Z, 0%Z]) i -> x%:num == 0 :> R = false. Proof. by move=> u; apply/negbTE/neq0. Qed. Lemma lt1 x : unify_itv i (Itv.Real `]-oo, 1%Z[) -> x%:num < 1 :> R. Proof. by case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=; rewrite in_itv. Qed. Lemma ge1F x : unify_itv i (Itv.Real `]-oo, 1%Z[) -> 1 <= x%:num :> R = false. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=. by rewrite in_itv/= => /lt_geF. Qed. Lemma le1 x : unify_itv i (Itv.Real `]-oo, 1%Z]) -> x%:num <= 1 :> R. Proof. by case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=; rewrite in_itv. Qed. Lemma gt1F x : unify_itv i (Itv.Real `]-oo, 1%Z]) -> 1 < x%:num :> R = false. Proof. case: x => x /= /[swap] /num_spec_sub /[apply] /andP[_] /=. by rewrite in_itv/= => /le_gtF. Qed. Lemma widen_itv_subproof x i' : Itv.sub i i' -> num_spec i' x%:num. Proof. by case: x => x /= /[swap] /num_spec_sub; apply. Qed. Definition widen_itv x i' (uni : unify_itv i i') := Itv.mk (widen_itv_subproof x uni). Lemma widen_itvE x (uni : unify_itv i i) : @widen_itv x i uni = x. Proof. exact/val_inj. Qed. Lemma posE x (uni : unify_itv i (Itv.Real `]0%Z, +oo[)) : (widen_itv x%:num%:itv uni)%:num = x%:num. Proof. by []. Qed. Lemma nngE x (uni : unify_itv i (Itv.Real `[0%Z, +oo[)) : (widen_itv x%:num%:itv uni)%:num = x%:num. Proof. by []. Qed. End NumDomainTheory. Arguments bottom {R i} _ {_}. Arguments gt0 {R i} _ {_}. Arguments le0F {R i} _ {_}. Arguments lt0 {R i} _ {_}. Arguments ge0F {R i} _ {_}. Arguments ge0 {R i} _ {_}. Arguments lt0F {R i} _ {_}. Arguments le0 {R i} _ {_}. Arguments gt0F {R i} _ {_}. Arguments cmp0 {R i} _ {_}. Arguments neq0 {R i} _ {_}. Arguments eq0F {R i} _ {_}. Arguments lt1 {R i} _ {_}. Arguments ge1F {R i} _ {_}. Arguments le1 {R i} _ {_}. Arguments gt1F {R i} _ {_}. Arguments widen_itv {R i} _ {_ _}. Arguments widen_itvE {R i} _ {_}. Arguments posE {R i} _ {_}. Arguments nngE {R i} _ {_}. Notation "[ 'gt0' 'of' x ]" := (ltac:(refine (gt0 x%:itv))) (only parsing). Notation "[ 'lt0' 'of' x ]" := (ltac:(refine (lt0 x%:itv))) (only parsing). Notation "[ 'ge0' 'of' x ]" := (ltac:(refine (ge0 x%:itv))) (only parsing). Notation "[ 'le0' 'of' x ]" := (ltac:(refine (le0 x%:itv))) (only parsing). Notation "[ 'cmp0' 'of' x ]" := (ltac:(refine (cmp0 x%:itv))) (only parsing). Notation "[ 'neq0' 'of' x ]" := (ltac:(refine (neq0 x%:itv))) (only parsing). #[export] Hint Extern 0 (is_true (0%R < _)%R) => solve [apply: gt0] : core. #[export] Hint Extern 0 (is_true (_ < 0%R)%R) => solve [apply: lt0] : core. #[export] Hint Extern 0 (is_true (0%R <= _)%R) => solve [apply: ge0] : core. #[export] Hint Extern 0 (is_true (_ <= 0%R)%R) => solve [apply: le0] : core. #[export] Hint Extern 0 (is_true (_ \is Num.real)) => solve [apply: cmp0] : core. #[export] Hint Extern 0 (is_true (0%R >=< _)%R) => solve [apply: cmp0] : core. #[export] Hint Extern 0 (is_true (_ != 0%R)) => solve [apply: neq0] : core. #[export] Hint Extern 0 (is_true (_ < 1%R)%R) => solve [apply: lt1] : core. #[export] Hint Extern 0 (is_true (_ <= 1%R)%R) => solve [apply: le1] : core. Notation "x %:i01" := (widen_itv x%:itv : {i01 _}) (only parsing) : ring_scope. Notation "x %:i01" := (@widen_itv _ _ (@Itv.from _ _ _ (Phantom _ x)) (Itv.Real `[0, 1]%Z) _) (only printing) : ring_scope. Notation "x %:pos" := (widen_itv x%:itv : {posnum _}) (only parsing) : ring_scope. Notation "x %:pos" := (@widen_itv _ _ (@Itv.from _ _ _ (Phantom _ x)) (Itv.Real `]0%Z, +oo[) _) (only printing) : ring_scope. Notation "x %:nng" := (widen_itv x%:itv : {nonneg _}) (only parsing) : ring_scope. Notation "x %:nng" := (@widen_itv _ _ (@Itv.from _ _ _ (Phantom _ x)) (Itv.Real `[0%Z, +oo[) _) (only printing) : ring_scope. Local Open Scope ring_scope. Module Instances. Import IntItv. Section NumDomainInstances. Context {R : numDomainType}. Lemma num_spec_zero : num_spec (Itv.Real `[0, 0]) (0 : R). Proof. by apply/andP; split; [exact: real0 | rewrite /= in_itv/= lexx]. Qed. Canonical zero_inum := Itv.mk num_spec_zero. Lemma num_spec_one : num_spec (Itv.Real `[1, 1]) (1 : R). Proof. by apply/andP; split; [exact: real1 | rewrite /= in_itv/= lexx]. Qed. Canonical one_inum := Itv.mk num_spec_one. Lemma opp_boundr (x : R) b : (BRight (- x)%R <= num_itv_bound R (opp_bound b))%O = (num_itv_bound R b <= BLeft x)%O. Proof. by case: b => [[] b | []//]; rewrite /= !bnd_simp mulrNz ?lerN2 // ltrN2. Qed. Lemma opp_boundl (x : R) b : (num_itv_bound R (opp_bound b) <= BLeft (- x)%R)%O = (BRight x <= num_itv_bound R b)%O. Proof. by case: b => [[] b | []//]; rewrite /= !bnd_simp mulrNz ?lerN2 // ltrN2. Qed. Lemma num_spec_opp (i : Itv.t) (x : num_def R i) (r := Itv.real1 opp i) : num_spec r (- x%:num). Proof. apply: Itv.spec_real1 (Itv.P x). case: x => x /= _ [l u] /and3P[xr lx xu]. rewrite /Itv.num_sem/= realN xr/=; apply/andP. by rewrite opp_boundl opp_boundr. Qed. Canonical opp_inum (i : Itv.t) (x : num_def R i) := Itv.mk (num_spec_opp x). Lemma num_itv_add_boundl (x1 x2 : R) b1 b2 : (num_itv_bound R b1 <= BLeft x1)%O -> (num_itv_bound R b2 <= BLeft x2)%O -> (num_itv_bound R (add_boundl b1 b2) <= BLeft (x1 + x2)%R)%O. Proof. case: b1 b2 => [bb1 b1 |//] [bb2 b2 |//]. case: bb1; case: bb2; rewrite /= !bnd_simp mulrzDr. - exact: lerD. - exact: ler_ltD. - exact: ltr_leD. - exact: ltrD. Qed. Lemma num_itv_add_boundr (x1 x2 : R) b1 b2 : (BRight x1 <= num_itv_bound R b1)%O -> (BRight x2 <= num_itv_bound R b2)%O -> (BRight (x1 + x2)%R <= num_itv_bound R (add_boundr b1 b2))%O. Proof. case: b1 b2 => [bb1 b1 |//] [bb2 b2 |//]. case: bb1; case: bb2; rewrite /= !bnd_simp mulrzDr. - exact: ltrD. - exact: ltr_leD. - exact: ler_ltD. - exact: lerD. Qed. Lemma num_spec_add (xi yi : Itv.t) (x : num_def R xi) (y : num_def R yi) (r := Itv.real2 add xi yi) : num_spec r (x%:num + y%:num). Proof. apply: Itv.spec_real2 (Itv.P x) (Itv.P y). case: x y => [x /= _] [y /= _] => {xi yi r} -[lx ux] [ly uy]/=. move=> /andP[xr /=/andP[lxx xux]] /andP[yr /=/andP[lyy yuy]]. rewrite /Itv.num_sem realD//=; apply/andP. by rewrite num_itv_add_boundl ?num_itv_add_boundr. Qed. Canonical add_inum (xi yi : Itv.t) (x : num_def R xi) (y : num_def R yi) := Itv.mk (num_spec_add x y). Variant sign_spec (l u : itv_bound int) (x : R) : signi -> Set := | ISignEqZero : l = BLeft 0 -> u = BRight 0 -> x = 0 -> sign_spec l u x (Known EqZero) | ISignNonNeg : (BLeft 0%:Z <= l)%O -> (BRight 0%:Z < u)%O -> 0 <= x -> sign_spec l u x (Known NonNeg) | ISignNonPos : (l < BLeft 0%:Z)%O -> (u <= BRight 0%:Z)%O -> x <= 0 -> sign_spec l u x (Known NonPos) | ISignBoth : (l < BLeft 0%:Z)%O -> (BRight 0%:Z < u)%O -> x \in Num.real -> sign_spec l u x Unknown. Lemma signP (l u : itv_bound int) (x : R) : (num_itv_bound R l <= BLeft x)%O -> (BRight x <= num_itv_bound R u)%O -> x \in Num.real -> sign_spec l u x (sign (Interval l u)). Proof. move=> + + xr; rewrite /sign/sign_boundl/sign_boundr. have [lneg|lpos|->] := ltgtP l; have [uneg|upos|->] := ltgtP u => lx xu. - apply: ISignNonPos => //; first exact: ltW. have:= le_trans xu (eqbRL (le_num_itv_bound _ _) (ltW uneg)). by rewrite bnd_simp. - exact: ISignBoth. - exact: ISignNonPos. - have:= @ltxx _ _ (num_itv_bound R l). rewrite (le_lt_trans lx) -?leBRight_ltBLeft ?(le_trans xu)//. by rewrite le_num_itv_bound (le_trans (ltW uneg)). - apply: ISignNonNeg => //; first exact: ltW. have:= le_trans (eqbRL (le_num_itv_bound _ _) (ltW lpos)) lx. by rewrite bnd_simp. - have:= @ltxx _ _ (num_itv_bound R l). rewrite (le_lt_trans lx) -?leBRight_ltBLeft ?(le_trans xu)//. by rewrite le_num_itv_bound ?leBRight_ltBLeft. - have:= @ltxx _ _ (num_itv_bound R (BLeft 0%Z)). rewrite (le_lt_trans lx) -?leBRight_ltBLeft ?(le_trans xu)//. by rewrite le_num_itv_bound -?ltBRight_leBLeft. - exact: ISignNonNeg. - apply: ISignEqZero => //. by apply/le_anti/andP; move: lx xu; rewrite !bnd_simp. Qed. Lemma num_itv_mul_boundl b1 b2 (x1 x2 : R) : (BLeft 0%:Z <= b1 -> BLeft 0%:Z <= b2 -> num_itv_bound R b1 <= BLeft x1 -> num_itv_bound R b2 <= BLeft x2 -> num_itv_bound R (mul_boundl b1 b2) <= BLeft (x1 * x2))%O. Proof. move: b1 b2 => [[] b1 | []//] [[] b2 | []//] /=; rewrite 4!bnd_simp. - set bl := match b1 with 0%Z => _ | _ => _ end. have -> : bl = BLeft (b1 * b2). rewrite {}/bl; move: b1 b2 => [[|p1]|p1] [[|p2]|p2]; congr BLeft. by rewrite mulr0. by rewrite bnd_simp intrM -2!(ler0z R); apply: ler_pM. - case: b1 => [[|b1] | b1]; rewrite !bnd_simp// => b1p b2p sx1 sx2. + by rewrite mulr_ge0 ?(le_trans _ (ltW sx2)) ?ler0z. + rewrite intrM (@lt_le_trans _ _ (b1.+1%:~R * x2)) ?ltr_pM2l//. by rewrite ler_pM2r// (le_lt_trans _ sx2) ?ler0z. - case: b2 => [[|b2] | b2]; rewrite !bnd_simp// => b1p b2p sx1 sx2. + by rewrite mulr_ge0 ?(le_trans _ (ltW sx1)) ?ler0z. + rewrite intrM (@le_lt_trans _ _ (b1%:~R * x2)) ?ler_wpM2l ?ler0z//. by rewrite ltr_pM2r ?(lt_le_trans _ sx2). - by rewrite -2!(ler0z R) bnd_simp intrM; apply: ltr_pM. Qed. Lemma num_itv_mul_boundr b1 b2 (x1 x2 : R) : (0 <= x1 -> 0 <= x2 -> BRight x1 <= num_itv_bound R b1 -> BRight x2 <= num_itv_bound R b2 -> BRight (x1 * x2) <= num_itv_bound R (mul_boundr b1 b2))%O. Proof. case: b1 b2 => [b1b b1 | []] [b2b b2 | []] //= x1p x2p; last first. - case: b2b b2 => -[[|//] | //] _ x20. + have:= @ltxx _ (itv_bound R) (BLeft 0%:~R). by rewrite (lt_le_trans _ x20). + have -> : x2 = 0 by apply/le_anti/andP. by rewrite mulr0. - case: b1b b1 => -[[|//] |//] x10 _. + have:= @ltxx _ (itv_bound R) (BLeft 0%Z%:~R). by rewrite (lt_le_trans _ x10). + by have -> : x1 = 0; [apply/le_anti/andP | rewrite mul0r]. case: b1b b2b => -[]; rewrite -[intRing.mulz]/GRing.mul. - case: b1 => [[|b1] | b1]; rewrite !bnd_simp => x1b x2b. + by have:= @ltxx _ R 0; rewrite (le_lt_trans x1p x1b). + case: b2 x2b => [[| b2] | b2] => x2b; rewrite bnd_simp. * by have:= @ltxx _ R 0; rewrite (le_lt_trans x2p x2b). * by rewrite intrM ltr_pM. * have:= @ltxx _ R 0; rewrite (le_lt_trans x2p)//. by rewrite (lt_le_trans x2b) ?lerz0. + have:= @ltxx _ R 0; rewrite (le_lt_trans x1p)//. by rewrite (lt_le_trans x1b) ?lerz0. - case: b1 => [[|b1] | b1]; rewrite !bnd_simp => x1b x2b. + by have:= @ltxx _ R 0; rewrite (le_lt_trans x1p x1b). + case: b2 x2b => [[| b2] | b2] x2b; rewrite bnd_simp. * exact: mulr_ge0_le0. * by rewrite intrM (le_lt_trans (ler_wpM2l x1p x2b)) ?ltr_pM2r. * have:= @ltxx _ _ x2. by rewrite (le_lt_trans x2b) ?(lt_le_trans _ x2p) ?ltrz0. + have:= @ltxx _ _ x1. by rewrite (lt_le_trans x1b) ?(le_trans _ x1p) ?lerz0. - case: b1 => [[|b1] | b1]; rewrite !bnd_simp => x1b x2b. + case: b2 x2b => [[|b2] | b2] x2b; rewrite bnd_simp. * by have:= @ltxx _ _ x2; rewrite (lt_le_trans x2b). * by have -> : x1 = 0; [apply/le_anti/andP | rewrite mul0r]. * have:= @ltxx _ _ x2. by rewrite (lt_le_trans x2b) ?(le_trans _ x2p) ?lerz0. + case: b2 x2b => [[|b2] | b2] x2b; rewrite bnd_simp. * by have:= @ltxx _ _ x2; rewrite (lt_le_trans x2b). * by rewrite intrM (le_lt_trans (ler_wpM2r x2p x1b)) ?ltr_pM2l. * have:= @ltxx _ _ x2. by rewrite (lt_le_trans x2b) ?(le_trans _ x2p) ?lerz0. + have:= @ltxx _ _ x1. by rewrite (le_lt_trans x1b) ?(lt_le_trans _ x1p) ?ltrz0. - case: b1 => [[|b1] | b1]; rewrite !bnd_simp => x1b x2b. + by have -> : x1 = 0; [apply/le_anti/andP | rewrite mul0r]. + case: b2 x2b => [[| b2] | b2] x2b; rewrite bnd_simp. * by have -> : x2 = 0; [apply/le_anti/andP | rewrite mulr0]. * by rewrite intrM ler_pM. * have:= @ltxx _ _ x2. by rewrite (le_lt_trans x2b) ?(lt_le_trans _ x2p) ?ltrz0. + have:= @ltxx _ _ x1. by rewrite (le_lt_trans x1b) ?(lt_le_trans _ x1p) ?ltrz0. Qed. Lemma BRight_le_mul_boundr b1 b2 (x1 x2 : R) : (0 <= x1 -> x2 \in Num.real -> BRight 0%Z <= b2 -> BRight x1 <= num_itv_bound R b1 -> BRight x2 <= num_itv_bound R b2 -> BRight (x1 * x2) <= num_itv_bound R (mul_boundr b1 b2))%O. Proof. move=> x1ge0 x2r b2ge0 lex1b1 lex2b2. have /orP[x2ge0 | x2le0] := x2r; first exact: num_itv_mul_boundr. have lem0 : (BRight (x1 * x2) <= BRight 0%R)%O. by rewrite bnd_simp mulr_ge0_le0 // ltW. apply: le_trans lem0 _. rewrite -(mulr0z 1) BRight_le_num_itv_bound. apply: mul_boundr_gt0 => //. by rewrite -(@BRight_le_num_itv_bound R) (le_trans _ lex1b1). Qed. Lemma comparable_num_itv_bound (x y : itv_bound int) : (num_itv_bound R x >=< num_itv_bound R y)%O. Proof. by case: x y => [[] x | []] [[] y | []]//; apply/orP; rewrite !bnd_simp ?ler_int ?ltr_int; case: leP => xy; apply/orP => //; rewrite ltW ?orbT. Qed. Lemma num_itv_bound_min (x y : itv_bound int) : num_itv_bound R (Order.min x y) = Order.min (num_itv_bound R x) (num_itv_bound R y). Proof. have [lexy | ltyx] := leP x y; [by rewrite !minEle le_num_itv_bound lexy|]. rewrite minElt -if_neg -comparable_leNgt ?le_num_itv_bound ?ltW//. exact: comparable_num_itv_bound. Qed. Lemma num_itv_bound_max (x y : itv_bound int) : num_itv_bound R (Order.max x y) = Order.max (num_itv_bound R x) (num_itv_bound R y). Proof. have [lexy | ltyx] := leP x y; [by rewrite !maxEle le_num_itv_bound lexy|]. rewrite maxElt -if_neg -comparable_leNgt ?le_num_itv_bound ?ltW//. exact: comparable_num_itv_bound. Qed. Lemma num_spec_mul (xi yi : Itv.t) (x : num_def R xi) (y : num_def R yi) (r := Itv.real2 mul xi yi) : num_spec r (x%:num * y%:num). Proof. rewrite {}/r; case: xi yi x y => [//| [xl xu]] [//| [yl yu]]. case=> [x /=/and3P[xr /= xlx xxu]] [y /=/and3P[yr /= yly yyu]]. rewrite -/(sign (Interval xl xu)) -/(sign (Interval yl yu)). have ns000 : @Itv.num_sem R `[0, 0] 0 by apply/and3P. have xyr : x * y \in Num.real by exact: realM. case: (signP xlx xxu xr) => xlb xub xs. - by rewrite xs mul0r; case: (signP yly yyu yr). - case: (signP yly yyu yr) => ylb yub ys. + by rewrite ys mulr0. + apply/and3P; split=> //=. * exact: num_itv_mul_boundl xlx yly. * exact: num_itv_mul_boundr xxu yyu. + apply/and3P; split=> //=; rewrite -[x * y]opprK -mulrN. * by rewrite opp_boundl num_itv_mul_boundr ?oppr_ge0// opp_boundr. * by rewrite opp_boundr num_itv_mul_boundl ?opp_boundl// opp_bound_ge0. + apply/and3P; split=> //=. * rewrite -[x * y]opprK -mulrN opp_boundl. by rewrite BRight_le_mul_boundr ?realN ?opp_boundr// opp_bound_gt0 ltW. * by rewrite BRight_le_mul_boundr// ltW. - case: (signP yly yyu yr) => ylb yub ys. + by rewrite ys mulr0. + apply/and3P; split=> //=; rewrite -[x * y]opprK -mulNr. * rewrite opp_boundl. by rewrite num_itv_mul_boundr ?oppr_ge0 ?opp_boundr. * by rewrite opp_boundr num_itv_mul_boundl ?opp_boundl// opp_bound_ge0. + apply/and3P; split=> //=; rewrite -mulrNN. * by rewrite num_itv_mul_boundl ?opp_bound_ge0 ?opp_boundl. * by rewrite num_itv_mul_boundr ?oppr_ge0 ?opp_boundr. + apply/and3P; split=> //=; rewrite -[x * y]opprK. * rewrite -mulNr opp_boundl BRight_le_mul_boundr ?oppr_ge0 ?opp_boundr//. exact: ltW. * rewrite opprK -mulrNN. by rewrite BRight_le_mul_boundr ?opp_boundr ?oppr_ge0 ?realN ?opp_bound_gt0// ltW. - case: (signP yly yyu yr) => ylb yub ys. + by rewrite ys mulr0. + apply/and3P; split=> //=; rewrite mulrC mul_boundrC. * rewrite -[y * x]opprK -mulrN opp_boundl. rewrite BRight_le_mul_boundr ?oppr_ge0 ?realN ?opp_boundr//. by rewrite opp_bound_gt0 ltW. * by rewrite BRight_le_mul_boundr// ltW. + apply/and3P; split=> //=; rewrite mulrC mul_boundrC. * rewrite -[y * x]opprK -mulNr opp_boundl. by rewrite BRight_le_mul_boundr ?oppr_ge0 ?opp_boundr// ltW. * rewrite -mulrNN BRight_le_mul_boundr ?oppr_ge0 ?realN ?opp_boundr//. by rewrite opp_bound_gt0 ltW. apply/and3P; rewrite xyr/= num_itv_bound_min num_itv_bound_max. rewrite (comparable_ge_min _ (comparable_num_itv_bound _ _)). rewrite (comparable_le_max _ (comparable_num_itv_bound _ _)). case: (comparable_leP xr) => [x0 | /ltW x0]; split=> //. - apply/orP; right; rewrite -[x * y]opprK -mulrN opp_boundl. by rewrite BRight_le_mul_boundr ?realN ?opp_boundr// opp_bound_gt0 ltW. - by apply/orP; right; rewrite BRight_le_mul_boundr// ltW. - apply/orP; left; rewrite -[x * y]opprK -mulNr opp_boundl. by rewrite BRight_le_mul_boundr ?oppr_ge0 ?opp_boundr// ltW. - apply/orP; left; rewrite -mulrNN. rewrite BRight_le_mul_boundr ?oppr_ge0 ?realN ?opp_boundr//. by rewrite opp_bound_gt0 ltW. Qed. Canonical mul_inum (xi yi : Itv.t) (x : num_def R xi) (y : num_def R yi) := Itv.mk (num_spec_mul x y). Lemma num_spec_min (xi yi : Itv.t) (x : num_def R xi) (y : num_def R yi) (r := Itv.real2 min xi yi) : num_spec r (Order.min x%:num y%:num). Proof. apply: Itv.spec_real2 (Itv.P x) (Itv.P y). case: x y => [x /= _] [y /= _] => {xi yi r} -[lx ux] [ly uy]/=. move=> /andP[xr /=/andP[lxx xux]] /andP[yr /=/andP[lyy yuy]]. apply/and3P; split; rewrite ?min_real//= num_itv_bound_min real_BSide_min//. - apply: (comparable_le_min2 (comparable_num_itv_bound _ _)) => //. exact: real_comparable. - apply: (comparable_le_min2 _ (comparable_num_itv_bound _ _)) => //. exact: real_comparable. Qed. Lemma num_spec_max (xi yi : Itv.t) (x : num_def R xi) (y : num_def R yi) (r := Itv.real2 max xi yi) : num_spec r (Order.max x%:num y%:num). Proof. apply: Itv.spec_real2 (Itv.P x) (Itv.P y). case: x y => [x /= _] [y /= _] => {xi yi r} -[lx ux] [ly uy]/=. move=> /andP[xr /=/andP[lxx xux]] /andP[yr /=/andP[lyy yuy]]. apply/and3P; split; rewrite ?max_real//= num_itv_bound_max real_BSide_max//. - apply: (comparable_le_max2 (comparable_num_itv_bound _ _)) => //. exact: real_comparable. - apply: (comparable_le_max2 _ (comparable_num_itv_bound _ _)) => //. exact: real_comparable. Qed. (* We can't directly put an instance on Order.min for R : numDomainType since we may want instances for other porderType (typically \bar R or even nat). So we resort on this additional canonical structure. *) Record min_max_typ d := MinMaxTyp { min_max_sort : porderType d; #[canonical=no] min_max_sem : interval int -> min_max_sort -> bool; #[canonical=no] min_max_minP : forall (xi yi : Itv.t) (x : Itv.def min_max_sem xi) (y : Itv.def min_max_sem yi), let: r := Itv.real2 min xi yi in Itv.spec min_max_sem r (Order.min x%:num y%:num); #[canonical=no] min_max_maxP : forall (xi yi : Itv.t) (x : Itv.def min_max_sem xi) (y : Itv.def min_max_sem yi), let: r := Itv.real2 max xi yi in Itv.spec min_max_sem r (Order.max x%:num y%:num); }. (* The default instances on porderType, for min... *) Canonical min_typ_inum d (t : min_max_typ d) (xi yi : Itv.t) (x : Itv.def (@min_max_sem d t) xi) (y : Itv.def (@min_max_sem d t) yi) (r := Itv.real2 min xi yi) := Itv.mk (min_max_minP x y). (* ...and for max *) Canonical max_typ_inum d (t : min_max_typ d) (xi yi : Itv.t) (x : Itv.def (@min_max_sem d t) xi) (y : Itv.def (@min_max_sem d t) yi) (r := Itv.real2 min xi yi) := Itv.mk (min_max_maxP x y). (* Instance of the above structure for numDomainType *) Canonical num_min_max_typ := MinMaxTyp num_spec_min num_spec_max. Lemma nat_num_spec (i : Itv.t) (n : nat) : nat_spec i n = num_spec i (n%:R : R). Proof. case: i => [//| [l u]]; rewrite /= /Itv.num_sem realn/=; congr (_ && _). - by case: l => [[] l |//]; rewrite !bnd_simp ?pmulrn ?ler_int ?ltr_int. - by case: u => [[] u |//]; rewrite !bnd_simp ?pmulrn ?ler_int ?ltr_int. Qed. Definition natmul_itv (i1 i2 : Itv.t) : Itv.t := match i1, i2 with | Itv.Top, _ => Itv.Top | _, Itv.Top => Itv.Real `]-oo, +oo[ | Itv.Real i1, Itv.Real i2 => Itv.Real (mul i1 i2) end. Arguments natmul_itv /. Lemma num_spec_natmul (xi ni : Itv.t) (x : num_def R xi) (n : nat_def ni) (r := natmul_itv xi ni) : num_spec r (x%:num *+ n%:num). Proof. rewrite {}/r; case: xi x ni n => [//| xi] x [| ni] n. by apply/and3P; case: n%:num => [|?]; rewrite ?mulr0n ?realrMn. have Pn : num_spec (Itv.Real ni) (n%:num%:R : R). by case: n => /= n; rewrite [Itv.nat_sem ni n](nat_num_spec (Itv.Real ni)). rewrite -mulr_natr -[n%:num%:R]/((Itv.Def Pn)%:num). by rewrite (@num_spec_mul (Itv.Real xi) (Itv.Real ni)). Qed. Canonical natmul_inum (xi ni : Itv.t) (x : num_def R xi) (n : nat_def ni) := Itv.mk (num_spec_natmul x n). Lemma num_spec_int (i : Itv.t) (n : int) : num_spec i n = num_spec i (n%:~R : R). Proof. case: i => [//| [l u]]; rewrite /= /Itv.num_sem num_real realz/=. congr (andb _ _). - by case: l => [[] l |//]; rewrite !bnd_simp intz ?ler_int ?ltr_int. - by case: u => [[] u |//]; rewrite !bnd_simp intz ?ler_int ?ltr_int. Qed. Lemma num_spec_intmul (xi ii : Itv.t) (x : num_def R xi) (i : num_def int ii) (r := natmul_itv xi ii) : num_spec r (x%:num *~ i%:num). Proof. rewrite {}/r; case: xi x ii i => [//| xi] x [| ii] i. by apply/and3P; case: i%:inum => [[|n] | n]; rewrite ?mulr0z ?realN ?realrMn. have Pi : num_spec (Itv.Real ii) (i%:num%:~R : R). by case: i => /= i; rewrite [Itv.num_sem ii i](num_spec_int (Itv.Real ii)). rewrite -mulrzr -[i%:num%:~R]/((Itv.Def Pi)%:num). by rewrite (@num_spec_mul (Itv.Real xi) (Itv.Real ii)). Qed. Canonical intmul_inum (xi ni : Itv.t) (x : num_def R xi) (n : num_def int ni) := Itv.mk (num_spec_intmul x n). Lemma num_itv_bound_keep_pos (op : R -> R) (x : R) b : {homo op : x / 0 <= x} -> {homo op : x / 0 < x} -> (num_itv_bound R b <= BLeft x)%O -> (num_itv_bound R (keep_pos_bound b) <= BLeft (op x))%O. Proof. case: b => [[] [] [| b] // | []//] hle hlt; rewrite !bnd_simp. - exact: hle. - by move=> blex; apply: le_lt_trans (hlt _ _) => //; apply: lt_le_trans blex. - exact: hlt. - by move=> bltx; apply: le_lt_trans (hlt _ _) => //; apply: le_lt_trans bltx. Qed. Lemma num_itv_bound_keep_neg (op : R -> R) (x : R) b : {homo op : x / x <= 0} -> {homo op : x / x < 0} -> (BRight x <= num_itv_bound R b)%O -> (BRight (op x) <= num_itv_bound R (keep_neg_bound b))%O. Proof. case: b => [[] [[|//] | b] | []//] hge hgt; rewrite !bnd_simp. - exact: hgt. - by move=> xltb; apply: hgt; apply: lt_le_trans xltb _; rewrite lerz0. - exact: hge. - by move=> xleb; apply: hgt; apply: le_lt_trans xleb _; rewrite ltrz0. Qed. Lemma num_spec_inv (i : Itv.t) (x : num_def R i) (r := Itv.real1 inv i) : num_spec r (x%:num^-1). Proof. apply: Itv.spec_real1 (Itv.P x). case: x => x /= _ [l u] /and3P[xr /= lx xu]. rewrite /Itv.num_sem/= realV xr/=; apply/andP; split. - apply: num_itv_bound_keep_pos lx. + by move=> ?; rewrite invr_ge0. + by move=> ?; rewrite invr_gt0. - apply: num_itv_bound_keep_neg xu. + by move=> ?; rewrite invr_le0. + by move=> ?; rewrite invr_lt0. Qed. Canonical inv_inum (i : Itv.t) (x : num_def R i) := Itv.mk (num_spec_inv x). Lemma num_itv_bound_exprn_le1 (x : R) n l u : (num_itv_bound R l <= BLeft x)%O -> (BRight x <= num_itv_bound R u)%O -> (BRight (x ^+ n) <= num_itv_bound R (exprn_le1_bound l u))%O. Proof. case: u => [bu [[//|[|//]] |//] | []//]. rewrite /exprn_le1_bound; case: (leP _ l) => [lge1 /= |//] lx xu. rewrite bnd_simp; case: n => [| n]; rewrite ?expr0//. have xN1 : -1 <= x. case: l lge1 lx => [[] l | []//]; rewrite !bnd_simp -(@ler_int R). - exact: le_trans. - by move=> + /ltW; apply: le_trans. have x1 : x <= 1 by case: bu xu; rewrite bnd_simp// => /ltW. have xr : x \is Num.real by exact: ler1_real. case: (real_ge0P xr) => x0; first by rewrite expr_le1. rewrite -[x]opprK exprNn; apply: le_trans (ler_piMl _ _) _. - by rewrite exprn_ge0 ?oppr_ge0 1?ltW. - suff: -1 <= (-1) ^+ n.+1 :> R /\ (-1) ^+ n.+1 <= 1 :> R => [[]//|]. elim: n => [|n [IHn1 IHn2]]; rewrite ?expr1// ![_ ^+ n.+2]exprS !mulN1r. by rewrite lerNl opprK lerNl. - by rewrite expr_le1 ?oppr_ge0 1?lerNl// ltW. Qed. Lemma num_spec_exprn (i : Itv.t) (x : num_def R i) n (r := Itv.real1 exprn i) : num_spec r (x%:num ^+ n). Proof. apply: (@Itv.spec_real1 _ _ (fun x => x^+n) _ _ _ _ (Itv.P x)). case: x => x /= _ [l u] /and3P[xr /= lx xu]. rewrite /Itv.num_sem realX//=; apply/andP; split. - apply: (@num_itv_bound_keep_pos (fun x => x^+n)) lx. + exact: exprn_ge0. + exact: exprn_gt0. - exact: num_itv_bound_exprn_le1 lx xu. Qed. Canonical exprn_inum (i : Itv.t) (x : num_def R i) n := Itv.mk (num_spec_exprn x n). Lemma num_spec_exprz (xi ki : Itv.t) (x : num_def R xi) (k : num_def int ki) (r := Itv.real2 exprz xi ki) : num_spec r (x%:num ^ k%:num). Proof. rewrite {}/r; case: ki k => [|[lk uk]] k; first by case: xi x. case: xi x => [//|xi x]; rewrite /Itv.real2. have P : Itv.num_sem (let 'Interval l _ := xi in Interval (keep_pos_bound l) +oo) (x%:num ^ k%:num). case: xi x => lx ux x; apply/and3P; split=> [||//]. have xr : x%:num \is Num.real by case: x => x /=/andP[]. by case: k%:num => n; rewrite ?realV realX. apply: (@num_itv_bound_keep_pos (fun x => x ^ k%:num)); [exact: exprz_ge0 | exact: exprz_gt0 |]. by case: x => x /=/and3P[]. case: lk k P => [slk [lk | lk] | slk] k P; [|exact: P..]. case: k P => -[k | k] /= => [_ _|]; rewrite -/(exprn xi); last first. by move=> /and3P[_ /=]; case: slk; rewrite bnd_simp -pmulrn natz. exact: (@num_spec_exprn (Itv.Real xi)). Qed. Canonical exprz_inum (xi ki : Itv.t) (x : num_def R xi) (k : num_def int ki) := Itv.mk (num_spec_exprz x k). Lemma num_spec_norm {V : normedZmodType R} (x : V) : num_spec (Itv.Real `[0, +oo[) `|x|. Proof. by apply/and3P; split; rewrite //= ?normr_real ?bnd_simp ?normr_ge0. Qed. Canonical norm_inum {V : normedZmodType R} (x : V) := Itv.mk (num_spec_norm x). End NumDomainInstances. Section RcfInstances. Context {R : rcfType}. Definition sqrt_itv (i : Itv.t) : Itv.t := match i with | Itv.Top => Itv.Real `[0%Z, +oo[ | Itv.Real (Interval l u) => match l with | BSide b 0%Z => Itv.Real (Interval (BSide b 0%Z) +oo) | BSide b (Posz (S _)) => Itv.Real `]0%Z, +oo[ | _ => Itv.Real `[0, +oo[ end end. Arguments sqrt_itv /. Lemma num_spec_sqrt (i : Itv.t) (x : num_def R i) (r := sqrt_itv i) : num_spec r (Num.sqrt x%:num). Proof. have: Itv.num_sem `[0%Z, +oo[ (Num.sqrt x%:num). by apply/and3P; rewrite /= num_real !bnd_simp sqrtr_ge0. rewrite {}/r; case: i x => [//| [[bl [l |//] |//] u]] [x /= +] _. case: bl l => -[| l] /and3P[xr /= bx _]; apply/and3P; split=> //=; move: bx; rewrite !bnd_simp ?sqrtr_ge0// sqrtr_gt0; [exact: lt_le_trans | exact: le_lt_trans..]. Qed. Canonical sqrt_inum (i : Itv.t) (x : num_def R i) := Itv.mk (num_spec_sqrt x). End RcfInstances. Section NumClosedFieldInstances. Context {R : numClosedFieldType}. Definition sqrtC_itv (i : Itv.t) : Itv.t := match i with | Itv.Top => Itv.Top | Itv.Real (Interval l u) => match l with | BSide b (Posz _) => Itv.Real (Interval (BSide b 0%Z) +oo) | _ => Itv.Top end end. Arguments sqrtC_itv /. Lemma num_spec_sqrtC (i : Itv.t) (x : num_def R i) (r := sqrtC_itv i) : num_spec r (sqrtC x%:num). Proof. rewrite {}/r; case: i x => [//| [l u] [x /=/and3P[xr /= lx xu]]]. case: l lx => [bl [l |//] |[]//] lx; apply/and3P; split=> //=. by apply: sqrtC_real; case: bl lx => /[!bnd_simp] [|/ltW]; apply: le_trans. case: bl lx => /[!bnd_simp] lx. - by rewrite sqrtC_ge0; apply: le_trans lx. - by rewrite sqrtC_gt0; apply: le_lt_trans lx. Qed. Canonical sqrtC_inum (i : Itv.t) (x : num_def R i) := Itv.mk (num_spec_sqrtC x). End NumClosedFieldInstances. Section NatInstances. Local Open Scope nat_scope. Implicit Type (n : nat). Lemma nat_spec_zero : nat_spec (Itv.Real `[0, 0]%Z) 0. Proof. by []. Qed. Canonical zeron_inum := Itv.mk nat_spec_zero. Lemma nat_spec_add (xi yi : Itv.t) (x : nat_def xi) (y : nat_def yi) (r := Itv.real2 add xi yi) : nat_spec r (x%:num + y%:num). Proof. have Px : num_spec xi (x%:num%:R : int). by case: x => /= x; rewrite (@nat_num_spec int). have Py : num_spec yi (y%:num%:R : int). by case: y => /= y; rewrite (@nat_num_spec int). rewrite (@nat_num_spec int) natrD. rewrite -[x%:num%:R]/((Itv.Def Px)%:num) -[y%:num%:R]/((Itv.Def Py)%:num). exact: num_spec_add. Qed. Canonical addn_inum (xi yi : Itv.t) (x : nat_def xi) (y : nat_def yi) := Itv.mk (nat_spec_add x y). Lemma nat_spec_succ (i : Itv.t) (n : nat_def i) (r := Itv.real2 add i (Itv.Real `[1, 1]%Z)) : nat_spec r (S n%:num). Proof. pose i1 := Itv.Real `[1, 1]%Z; have P1 : nat_spec i1 1 by []. by rewrite -addn1 -[1%N]/((Itv.Def P1)%:num); apply: nat_spec_add. Qed. Canonical succn_inum (i : Itv.t) (n : nat_def i) := Itv.mk (nat_spec_succ n). Lemma nat_spec_double (i : Itv.t) (n : nat_def i) (r := Itv.real2 add i i) : nat_spec r (n%:num.*2). Proof. by rewrite -addnn nat_spec_add. Qed. Canonical double_inum (i : Itv.t) (x : nat_def i) := Itv.mk (nat_spec_double x). Lemma nat_spec_mul (xi yi : Itv.t) (x : nat_def xi) (y : nat_def yi) (r := Itv.real2 mul xi yi) : nat_spec r (x%:num * y%:num). Proof. have Px : num_spec xi (x%:num%:R : int). by case: x => /= x; rewrite (@nat_num_spec int). have Py : num_spec yi (y%:num%:R : int). by case: y => /= y; rewrite (@nat_num_spec int). rewrite (@nat_num_spec int) natrM. rewrite -[x%:num%:R]/((Itv.Def Px)%:num) -[y%:num%:R]/((Itv.Def Py)%:num). exact: num_spec_mul. Qed. Canonical muln_inum (xi yi : Itv.t) (x : nat_def xi) (y : nat_def yi) := Itv.mk (nat_spec_mul x y). Lemma nat_spec_exp (i : Itv.t) (x : nat_def i) n (r := Itv.real1 exprn i) : nat_spec r (x%:num ^ n). Proof. have Px : num_spec i (x%:num%:R : int). by case: x => /= x; rewrite (@nat_num_spec int). rewrite (@nat_num_spec int) natrX -[x%:num%:R]/((Itv.Def Px)%:num). exact: num_spec_exprn. Qed. Canonical expn_inum (i : Itv.t) (x : nat_def i) n := Itv.mk (nat_spec_exp x n). Lemma nat_spec_min (xi yi : Itv.t) (x : nat_def xi) (y : nat_def yi) (r := Itv.real2 min xi yi) : nat_spec r (minn x%:num y%:num). Proof. have Px : num_spec xi (x%:num%:R : int). by case: x => /= x; rewrite (@nat_num_spec int). have Py : num_spec yi (y%:num%:R : int). by case: y => /= y; rewrite (@nat_num_spec int). rewrite (@nat_num_spec int) -minEnat natr_min. rewrite -[x%:num%:R]/((Itv.Def Px)%:num) -[y%:num%:R]/((Itv.Def Py)%:num). exact: num_spec_min. Qed. Canonical minn_inum (xi yi : Itv.t) (x : nat_def xi) (y : nat_def yi) := Itv.mk (nat_spec_min x y). Lemma nat_spec_max (xi yi : Itv.t) (x : nat_def xi) (y : nat_def yi) (r := Itv.real2 max xi yi) : nat_spec r (maxn x%:num y%:num). Proof. have Px : num_spec xi (x%:num%:R : int). by case: x => /= x; rewrite (@nat_num_spec int). have Py : num_spec yi (y%:num%:R : int). by case: y => /= y; rewrite (@nat_num_spec int). rewrite (@nat_num_spec int) -maxEnat natr_max. rewrite -[x%:num%:R]/((Itv.Def Px)%:num) -[y%:num%:R]/((Itv.Def Py)%:num). exact: num_spec_max. Qed. Canonical maxn_inum (xi yi : Itv.t) (x : nat_def xi) (y : nat_def yi) := Itv.mk (nat_spec_max x y). Canonical nat_min_max_typ := MinMaxTyp nat_spec_min nat_spec_max. Lemma nat_spec_factorial (n : nat) : nat_spec (Itv.Real `[1%Z, +oo[) n`!. Proof. by apply/andP; rewrite bnd_simp lez_nat fact_gt0. Qed. Canonical factorial_inum n := Itv.mk (nat_spec_factorial n). End NatInstances. Section IntInstances. Lemma num_spec_Posz n : num_spec (Itv.Real `[0, +oo[) (Posz n). Proof. by apply/and3P; rewrite /= num_real !bnd_simp. Qed. Canonical Posz_inum n := Itv.mk (num_spec_Posz n). Lemma num_spec_Negz n : num_spec (Itv.Real `]-oo, (-1)]) (Negz n). Proof. by apply/and3P; rewrite /= num_real !bnd_simp. Qed. Canonical Negz_inum n := Itv.mk (num_spec_Negz n). End IntInstances. End Instances. Export (canonicals) Instances. Section Morph. Context {R : numDomainType} {i : Itv.t}. Local Notation nR := (num_def R i). Implicit Types x y : nR. Local Notation num := (@num R (@Itv.num_sem R) i). Lemma num_eq : {mono num : x y / x == y}. Proof. by []. Qed. Lemma num_le : {mono num : x y / (x <= y)%O}. Proof. by []. Qed. Lemma num_lt : {mono num : x y / (x < y)%O}. Proof. by []. Qed. Lemma num_min : {morph num : x y / Order.min x y}. Proof. by move=> x y; rewrite !minEle num_le -fun_if. Qed. Lemma num_max : {morph num : x y / Order.max x y}. Proof. by move=> x y; rewrite !maxEle num_le -fun_if. Qed. End Morph. Section MorphNum. Context {R : numDomainType}. Lemma num_abs_eq0 (a : R) : (`|a|%:nng == 0%:nng) = (a == 0). Proof. by rewrite -normr_eq0. Qed. End MorphNum. Section MorphReal. Context {R : numDomainType} {i : interval int}. Local Notation nR := (num_def R (Itv.Real i)). Implicit Type x y : nR. Local Notation num := (@num R (@Itv.num_sem R) i). Lemma num_le_max a x y : a <= Num.max x%:num y%:num = (a <= x%:num) || (a <= y%:num). Proof. by rewrite -comparable_le_max// real_comparable. Qed. Lemma num_ge_max a x y : Num.max x%:num y%:num <= a = (x%:num <= a) && (y%:num <= a). Proof. by rewrite -comparable_ge_max// real_comparable. Qed. Lemma num_le_min a x y : a <= Num.min x%:num y%:num = (a <= x%:num) && (a <= y%:num). Proof. by rewrite -comparable_le_min// real_comparable. Qed. Lemma num_ge_min a x y : Num.min x%:num y%:num <= a = (x%:num <= a) || (y%:num <= a). Proof. by rewrite -comparable_ge_min// real_comparable. Qed. Lemma num_lt_max a x y : a < Num.max x%:num y%:num = (a < x%:num) || (a < y%:num). Proof. by rewrite -comparable_lt_max// real_comparable. Qed. Lemma num_gt_max a x y : Num.max x%:num y%:num < a = (x%:num < a) && (y%:num < a). Proof. by rewrite -comparable_gt_max// real_comparable. Qed. Lemma num_lt_min a x y : a < Num.min x%:num y%:num = (a < x%:num) && (a < y%:num). Proof. by rewrite -comparable_lt_min// real_comparable. Qed. Lemma num_gt_min a x y : Num.min x%:num y%:num < a = (x%:num < a) || (y%:num < a). Proof. by rewrite -comparable_gt_min// real_comparable. Qed. End MorphReal. Section MorphGe0. Context {R : numDomainType}. Local Notation nR := (num_def R (Itv.Real `[0%Z, +oo[)). Implicit Type x y : nR. Local Notation num := (@num R (@Itv.num_sem R) (Itv.Real `[0%Z, +oo[)). Lemma num_abs_le a x : 0 <= a -> (`|a|%:nng <= x) = (a <= x%:num). Proof. by move=> a0; rewrite -num_le//= ger0_norm. Qed. Lemma num_abs_lt a x : 0 <= a -> (`|a|%:nng < x) = (a < x%:num). Proof. by move=> a0; rewrite -num_lt/= ger0_norm. Qed. End MorphGe0. Section ItvNum. Context (R : numDomainType). Context (x : R) (l u : itv_bound int). Context (x_real : x \in Num.real). Context (l_le_x : (num_itv_bound R l <= BLeft x)%O). Context (x_le_u : (BRight x <= num_itv_bound R u)%O). Lemma itvnum_subdef : num_spec (Itv.Real (Interval l u)) x. Proof. by apply/and3P. Qed. Definition ItvNum : num_def R (Itv.Real (Interval l u)) := Itv.mk itvnum_subdef. End ItvNum. Section ItvReal. Context (R : realDomainType). Context (x : R) (l u : itv_bound int). Context (l_le_x : (num_itv_bound R l <= BLeft x)%O). Context (x_le_u : (BRight x <= num_itv_bound R u)%O). Lemma itvreal_subdef : num_spec (Itv.Real (Interval l u)) x. Proof. by apply/and3P; split; first exact: num_real. Qed. Definition ItvReal : num_def R (Itv.Real (Interval l u)) := Itv.mk itvreal_subdef. End ItvReal. Section Itv01. Context (R : numDomainType). Context (x : R) (x_ge0 : 0 <= x) (x_le1 : x <= 1). Lemma itv01_subdef : num_spec (Itv.Real `[0%Z, 1%Z]) x. Proof. by apply/and3P; split; rewrite ?bnd_simp// ger0_real. Qed. Definition Itv01 : num_def R (Itv.Real `[0%Z, 1%Z]) := Itv.mk itv01_subdef. End Itv01. Section Posnum. Context (R : numDomainType) (x : R) (x_gt0 : 0 < x). Lemma posnum_subdef : num_spec (Itv.Real `]0, +oo[) x. Proof. by apply/and3P; rewrite /= gtr0_real. Qed. Definition PosNum : {posnum R} := Itv.mk posnum_subdef. End Posnum. Section Nngnum. Context (R : numDomainType) (x : R) (x_ge0 : 0 <= x). Lemma nngnum_subdef : num_spec (Itv.Real `[0, +oo[) x. Proof. by apply/and3P; rewrite /= ger0_real. Qed. Definition NngNum : {nonneg R} := Itv.mk nngnum_subdef. End Nngnum. Variant posnum_spec (R : numDomainType) (x : R) : R -> bool -> bool -> bool -> Type := | IsPosnum (p : {posnum R}) : posnum_spec x (p%:num) false true true. Lemma posnumP (R : numDomainType) (x : R) : 0 < x -> posnum_spec x x (x == 0) (0 <= x) (0 < x). Proof. move=> x_gt0; case: real_ltgt0P (x_gt0) => []; rewrite ?gtr0_real // => _ _. by rewrite -[x]/(PosNum x_gt0)%:num; constructor. Qed. Variant nonneg_spec (R : numDomainType) (x : R) : R -> bool -> Type := | IsNonneg (p : {nonneg R}) : nonneg_spec x (p%:num) true. Lemma nonnegP (R : numDomainType) (x : R) : 0 <= x -> nonneg_spec x x (0 <= x). Proof. by move=> xge0; rewrite xge0 -[x]/(NngNum xge0)%:num; constructor. Qed. Section Test1. Variable R : numDomainType. Variable x : {i01 R}. Goal 0%:i01 = 1%:i01 :> {i01 R}. Proof. Abort. Goal (- x%:num)%:itv = (- x%:num)%:itv :> {itv R & `[-1, 0]}. Proof. Abort. Goal (1 - x%:num)%:i01 = x. Proof. Abort. End Test1. Section Test2. Variable R : realDomainType. Variable x y : {i01 R}. Goal (x%:num * y%:num)%:i01 = x%:num%:i01. Proof. Abort. End Test2. Module Test3. Section Test3. Variable R : realDomainType. Definition s_of_pq (p q : {i01 R}) : {i01 R} := (1 - ((1 - p%:num)%:i01%:num * (1 - q%:num)%:i01%:num))%:i01. Lemma s_of_p0 (p : {i01 R}) : s_of_pq p 0%:i01 = p. Proof. by apply/val_inj; rewrite /= subr0 mulr1 subKr. Qed. End Test3. End Test3.
FunctorToTypes.lean
/- Copyright (c) 2024 Jack McKoen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jack McKoen -/ import Mathlib.CategoryTheory.Limits.FunctorCategory.Basic import Mathlib.CategoryTheory.Limits.Shapes.BinaryProducts import Mathlib.CategoryTheory.Limits.Types.Limits import Mathlib.CategoryTheory.Limits.Types.Colimits /-! # Binary (co)products of type-valued functors Defines an explicit construction of binary products and coproducts of type-valued functors. Also defines isomorphisms to the categorical product and coproduct, respectively. -/ open CategoryTheory.Limits universe w v u namespace CategoryTheory.FunctorToTypes variable {C : Type u} [Category.{v} C] variable (F G : C ⥤ Type w) section prod /-- `prod F G` is the explicit binary product of type-valued functors `F` and `G`. -/ def prod : C ⥤ Type w where obj a := F.obj a × G.obj a map f a := (F.map f a.1, G.map f a.2) variable {F G} /-- The first projection of `prod F G`, onto `F`. -/ @[simps] def prod.fst : prod F G ⟶ F where app _ a := a.1 /-- The second projection of `prod F G`, onto `G`. -/ @[simps] def prod.snd : prod F G ⟶ G where app _ a := a.2 /-- Given natural transformations `F ⟶ F₁` and `F ⟶ F₂`, construct a natural transformation `F ⟶ prod F₁ F₂`. -/ @[simps] def prod.lift {F₁ F₂ : C ⥤ Type w} (τ₁ : F ⟶ F₁) (τ₂ : F ⟶ F₂) : F ⟶ prod F₁ F₂ where app x y := ⟨τ₁.app x y, τ₂.app x y⟩ naturality _ _ _ := by ext a simp only [types_comp_apply, FunctorToTypes.naturality] aesop @[simp] lemma prod.lift_fst {F₁ F₂ : C ⥤ Type w} (τ₁ : F ⟶ F₁) (τ₂ : F ⟶ F₂) : prod.lift τ₁ τ₂ ≫ prod.fst = τ₁ := rfl @[simp] lemma prod.lift_snd {F₁ F₂ : C ⥤ Type w} (τ₁ : F ⟶ F₁) (τ₂ : F ⟶ F₂) : prod.lift τ₁ τ₂ ≫ prod.snd = τ₂ := rfl variable (F G) /-- The binary fan whose point is `prod F G`. -/ @[simps!] def binaryProductCone : BinaryFan F G := BinaryFan.mk prod.fst prod.snd /-- `prod F G` is a limit cone. -/ @[simps] def binaryProductLimit : IsLimit (binaryProductCone F G) where lift (s : BinaryFan F G) := prod.lift s.fst s.snd fac _ := fun ⟨j⟩ ↦ WalkingPair.casesOn j rfl rfl uniq _ _ h := by simp only [← h ⟨WalkingPair.right⟩, ← h ⟨WalkingPair.left⟩] congr /-- `prod F G` is a binary product for `F` and `G`. -/ def binaryProductLimitCone : Limits.LimitCone (pair F G) := ⟨_, binaryProductLimit F G⟩ /-- The categorical binary product of type-valued functors is `prod F G`. -/ noncomputable def binaryProductIso : F ⨯ G ≅ prod F G := limit.isoLimitCone (binaryProductLimitCone F G) @[simp] lemma binaryProductIso_hom_comp_fst : (binaryProductIso F G).hom ≫ prod.fst = Limits.prod.fst := rfl @[simp] lemma binaryProductIso_hom_comp_snd : (binaryProductIso F G).hom ≫ prod.snd = Limits.prod.snd := rfl @[simp] lemma binaryProductIso_inv_comp_fst : (binaryProductIso F G).inv ≫ Limits.prod.fst = prod.fst := by simp [binaryProductIso, binaryProductLimitCone] @[simp] lemma binaryProductIso_inv_comp_fst_apply (a : C) (z : (prod F G).obj a) : (Limits.prod.fst (X := F)).app a ((binaryProductIso F G).inv.app a z) = z.1 := congr_fun (congr_app (binaryProductIso_inv_comp_fst F G) a) z @[simp] lemma binaryProductIso_inv_comp_snd : (binaryProductIso F G).inv ≫ Limits.prod.snd = prod.snd := by simp [binaryProductIso, binaryProductLimitCone] @[simp] lemma binaryProductIso_inv_comp_snd_apply (a : C) (z : (prod F G).obj a) : (Limits.prod.snd (X := F)).app a ((binaryProductIso F G).inv.app a z) = z.2 := congr_fun (congr_app (binaryProductIso_inv_comp_snd F G) a) z variable {F G} /-- Construct an element of `(F ⨯ G).obj a` from an element of `F.obj a` and an element of `G.obj a`. -/ noncomputable def prodMk {a : C} (x : F.obj a) (y : G.obj a) : (F ⨯ G).obj a := ((binaryProductIso F G).inv).app a ⟨x, y⟩ @[simp] lemma prodMk_fst {a : C} (x : F.obj a) (y : G.obj a) : (Limits.prod.fst (X := F)).app a (prodMk x y) = x := by simp only [prodMk, binaryProductIso_inv_comp_fst_apply] @[simp] lemma prodMk_snd {a : C} (x : F.obj a) (y : G.obj a) : (Limits.prod.snd (X := F)).app a (prodMk x y) = y := by simp only [prodMk, binaryProductIso_inv_comp_snd_apply] @[ext] lemma prod_ext {a : C} (z w : (prod F G).obj a) (h1 : z.1 = w.1) (h2 : z.2 = w.2) : z = w := Prod.ext h1 h2 variable (F G) /-- `(F ⨯ G).obj a` is in bijection with the product of `F.obj a` and `G.obj a`. -/ @[simps] noncomputable def binaryProductEquiv (a : C) : (F ⨯ G).obj a ≃ (F.obj a) × (G.obj a) where toFun z := ⟨((binaryProductIso F G).hom.app a z).1, ((binaryProductIso F G).hom.app a z).2⟩ invFun z := prodMk z.1 z.2 left_inv _ := by simp [prodMk] right_inv _ := by simp [prodMk] @[ext] lemma prod_ext' (a : C) (z w : (F ⨯ G).obj a) (h1 : (Limits.prod.fst (X := F)).app a z = (Limits.prod.fst (X := F)).app a w) (h2 : (Limits.prod.snd (X := F)).app a z = (Limits.prod.snd (X := F)).app a w) : z = w := by apply Equiv.injective (binaryProductEquiv F G a) aesop end prod section coprod /-- `coprod F G` is the explicit binary coproduct of type-valued functors `F` and `G`. -/ def coprod : C ⥤ Type w where obj a := F.obj a ⊕ G.obj a map f x := by cases x with | inl x => exact .inl (F.map f x) | inr x => exact .inr (G.map f x) variable {F G} /-- The left inclusion of `F` into `coprod F G`. -/ @[simps] def coprod.inl : F ⟶ coprod F G where app _ x := .inl x /-- The right inclusion of `G` into `coprod F G`. -/ @[simps] def coprod.inr : G ⟶ coprod F G where app _ x := .inr x /-- Given natural transformations `F₁ ⟶ F` and `F₂ ⟶ F`, construct a natural transformation `coprod F₁ F₂ ⟶ F`. -/ @[simps] def coprod.desc {F₁ F₂ : C ⥤ Type w} (τ₁ : F₁ ⟶ F) (τ₂ : F₂ ⟶ F) : coprod F₁ F₂ ⟶ F where app a x := by cases x with | inl x => exact τ₁.app a x | inr x => exact τ₂.app a x naturality _ _ _ := by ext x cases x with | _ => simp only [coprod, types_comp_apply, FunctorToTypes.naturality] @[simp] lemma coprod.desc_inl {F₁ F₂ : C ⥤ Type w} (τ₁ : F₁ ⟶ F) (τ₂ : F₂ ⟶ F) : coprod.inl ≫ coprod.desc τ₁ τ₂ = τ₁ := rfl @[simp] lemma coprod.desc_inr {F₁ F₂ : C ⥤ Type w} (τ₁ : F₁ ⟶ F) (τ₂ : F₂ ⟶ F) : coprod.inr ≫ coprod.desc τ₁ τ₂ = τ₂ := rfl variable (F G) /-- The binary cofan whose point is `coprod F G`. -/ @[simps!] def binaryCoproductCocone : BinaryCofan F G := BinaryCofan.mk coprod.inl coprod.inr /-- `coprod F G` is a colimit cocone. -/ @[simps] def binaryCoproductColimit : IsColimit (binaryCoproductCocone F G) where desc (s : BinaryCofan F G) := coprod.desc s.inl s.inr fac _ := fun ⟨j⟩ ↦ WalkingPair.casesOn j rfl rfl uniq _ _ h := by ext _ x cases x with | _ => simp [← h ⟨WalkingPair.right⟩, ← h ⟨WalkingPair.left⟩] /-- `coprod F G` is a binary coproduct for `F` and `G`. -/ def binaryCoproductColimitCocone : Limits.ColimitCocone (pair F G) := ⟨_, binaryCoproductColimit F G⟩ /-- The categorical binary coproduct of type-valued functors is `coprod F G`. -/ noncomputable def binaryCoproductIso : F ⨿ G ≅ coprod F G := colimit.isoColimitCocone (binaryCoproductColimitCocone F G) @[simp] lemma inl_comp_binaryCoproductIso_hom : Limits.coprod.inl ≫ (binaryCoproductIso F G).hom = coprod.inl := by simp only [binaryCoproductIso] aesop @[simp] lemma inl_comp_binaryCoproductIso_hom_apply (a : C) (x : F.obj a) : (binaryCoproductIso F G).hom.app a ((Limits.coprod.inl (X := F)).app a x) = .inl x := congr_fun (congr_app (inl_comp_binaryCoproductIso_hom F G) a) x @[simp] lemma inr_comp_binaryCoproductIso_hom : Limits.coprod.inr ≫ (binaryCoproductIso F G).hom = coprod.inr := by simp [binaryCoproductIso] aesop @[simp] lemma inr_comp_binaryCoproductIso_hom_apply (a : C) (x : G.obj a) : (binaryCoproductIso F G).hom.app a ((Limits.coprod.inr (X := F)).app a x) = .inr x := congr_fun (congr_app (inr_comp_binaryCoproductIso_hom F G) a) x @[simp] lemma inl_comp_binaryCoproductIso_inv : coprod.inl ≫ (binaryCoproductIso F G).inv = (Limits.coprod.inl (X := F)) := rfl @[simp] lemma inl_comp_binaryCoproductIso_inv_apply (a : C) (x : F.obj a) : (binaryCoproductIso F G).inv.app a (.inl x) = (Limits.coprod.inl (X := F)).app a x := rfl @[simp] lemma inr_comp_binaryCoproductIso_inv : coprod.inr ≫ (binaryCoproductIso F G).inv = (Limits.coprod.inr (X := F)) := rfl @[simp] lemma inr_comp_binaryCoproductIso_inv_apply (a : C) (x : G.obj a) : (binaryCoproductIso F G).inv.app a (.inr x) = (Limits.coprod.inr (X := F)).app a x := rfl variable {F G} /-- Construct an element of `(F ⨿ G).obj a` from an element of `F.obj a` -/ noncomputable abbrev coprodInl {a : C} (x : F.obj a) : (F ⨿ G).obj a := (binaryCoproductIso F G).inv.app a (.inl x) /-- Construct an element of `(F ⨿ G).obj a` from an element of `G.obj a` -/ noncomputable abbrev coprodInr {a : C} (x : G.obj a) : (F ⨿ G).obj a := (binaryCoproductIso F G).inv.app a (.inr x) variable (F G) /-- `(F ⨿ G).obj a` is in bijection with disjoint union of `F.obj a` and `G.obj a`. -/ @[simps] noncomputable def binaryCoproductEquiv (a : C) : (F ⨿ G).obj a ≃ (F.obj a) ⊕ (G.obj a) where toFun z := (binaryCoproductIso F G).hom.app a z invFun z := (binaryCoproductIso F G).inv.app a z left_inv _ := by simp only [hom_inv_id_app_apply] right_inv _ := by simp only [inv_hom_id_app_apply] end coprod end CategoryTheory.FunctorToTypes
ShortExact.lean
/- Copyright (c) 2024 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.Algebra.Homology.HomotopyCategory.HomologicalFunctor import Mathlib.Algebra.Homology.HomotopyCategory.ShiftSequence import Mathlib.Algebra.Homology.HomologySequenceLemmas import Mathlib.Algebra.Homology.Refinements /-! # The mapping cone of a monomorphism, up to a quasi-isomophism If `S` is a short exact short complex of cochain complexes in an abelian category, we construct a quasi-isomorphism `descShortComplex S : mappingCone S.f ⟶ S.X₃`. We obtain this by comparing the homology sequence of `S` and the homology sequence of the homology functor on the homotopy category, applied to the distinguished triangle attached to the mapping cone of `S.f`. -/ assert_not_exists TwoSidedIdeal open CategoryTheory Category ComplexShape HomotopyCategory Limits HomologicalComplex.HomologySequence Pretriangulated Preadditive variable {C : Type*} [Category C] [Abelian C] namespace CochainComplex @[reassoc] lemma homologySequenceδ_quotient_mapTriangle_obj (T : Triangle (CochainComplex C ℤ)) (n₀ n₁ : ℤ) (h : n₀ + 1 = n₁) : (homologyFunctor C (up ℤ) 0).homologySequenceδ ((quotient C (up ℤ)).mapTriangle.obj T) n₀ n₁ h = (homologyFunctorFactors C (up ℤ) n₀).hom.app _ ≫ (HomologicalComplex.homologyFunctor C (up ℤ) 0).shiftMap T.mor₃ n₀ n₁ (by omega) ≫ (homologyFunctorFactors C (up ℤ) n₁).inv.app _ := by apply homologyFunctor_shiftMap namespace mappingCone variable (S : ShortComplex (CochainComplex C ℤ)) (hS : S.ShortExact) /-- The canonical morphism `mappingCone S.f ⟶ S.X₃` when `S` is a short complex of cochain complexes. -/ noncomputable def descShortComplex : mappingCone S.f ⟶ S.X₃ := desc S.f 0 S.g (by simp) @[reassoc (attr := simp)] lemma inr_descShortComplex : inr S.f ≫ descShortComplex S = S.g := by simp [descShortComplex] @[reassoc (attr := simp)] lemma inr_f_descShortComplex_f (n : ℤ) : (inr S.f).f n ≫ (descShortComplex S).f n = S.g.f n := by simp [descShortComplex] @[reassoc (attr := simp)] lemma inl_v_descShortComplex_f (i j : ℤ) (h : i + (-1) = j) : (inl S.f).v i j h ≫ (descShortComplex S).f j = 0 := by simp [descShortComplex] variable {S} lemma homologySequenceδ_triangleh (n₀ : ℤ) (n₁ : ℤ) (h : n₀ + 1 = n₁) : (homologyFunctor C (up ℤ) 0).homologySequenceδ (triangleh S.f) n₀ n₁ h = (homologyFunctorFactors C (up ℤ) n₀).hom.app _ ≫ HomologicalComplex.homologyMap (descShortComplex S) n₀ ≫ hS.δ n₀ n₁ h ≫ (homologyFunctorFactors C (up ℤ) n₁).inv.app _ := by /- We proceed by diagram chase. We test the identity on cocycles `x' : A' ⟶ (mappingCone S.f).X n₀` -/ dsimp rw [← cancel_mono ((homologyFunctorFactors C (up ℤ) n₁).hom.app _), assoc, assoc, assoc, Iso.inv_hom_id_app, ← cancel_epi ((homologyFunctorFactors C (up ℤ) n₀).inv.app _), Iso.inv_hom_id_app_assoc] apply yoneda.map_injective ext ⟨A⟩ (x : A ⟶ _) obtain ⟨A', π, _, x', w, hx'⟩ := (mappingCone S.f).eq_liftCycles_homologyπ_up_to_refinements x n₁ (by simpa using h) erw [homologySequenceδ_quotient_mapTriangle_obj_assoc _ _ _ h] dsimp rw [comp_id, Iso.inv_hom_id_app_assoc, Iso.inv_hom_id_app] erw [comp_id] rw [← cancel_epi π, reassoc_of% hx', reassoc_of% hx', HomologicalComplex.homologyπ_naturality_assoc, HomologicalComplex.liftCycles_comp_cyclesMap_assoc] /- We decompose the cocycle `x'` into two morphisms `a : A' ⟶ S.X₁.X n₁` and `b : A' ⟶ S.X₂.X n₀` satisfying certain relations. -/ obtain ⟨a, b, hab⟩ := decomp_to _ x' n₁ h rw [hab, ext_to_iff _ n₁ (n₁ + 1) rfl, add_comp, assoc, assoc, inr_f_d, add_comp, assoc, assoc, assoc, assoc, inr_f_fst_v, comp_zero, comp_zero, add_zero, zero_comp, d_fst_v _ _ _ _ h, comp_neg, inl_v_fst_v_assoc, comp_neg, neg_eq_zero, add_comp, assoc, assoc, assoc, assoc, inr_f_snd_v, comp_id, zero_comp, d_snd_v _ _ _ h, comp_add, inl_v_fst_v_assoc, inl_v_snd_v_assoc, zero_comp, add_zero] at w /- We simplify the RHS. -/ conv_rhs => simp only [hab, add_comp, assoc, inr_f_descShortComplex_f, inl_v_descShortComplex_f, comp_zero, zero_add] rw [hS.δ_eq n₀ n₁ (by simpa using h) (b ≫ S.g.f n₀) _ b rfl (-a) (by simp only [neg_comp, neg_eq_iff_add_eq_zero, w.2]) (n₁ + 1) (by simp)] /- We simplify the LHS. -/ dsimp [Functor.shiftMap, homologyFunctor_shift] rw [HomologicalComplex.homologyπ_naturality_assoc, HomologicalComplex.liftCycles_comp_cyclesMap_assoc, S.X₁.liftCycles_shift_homologyπ_assoc _ _ _ _ n₁ (by omega) (n₁ + 1) (by simp), Iso.inv_hom_id_app] dsimp [homologyFunctor_shift] simp only [hab, add_comp, assoc, inl_v_triangle_mor₃_f_assoc, shiftFunctorObjXIso, neg_comp, Iso.inv_hom_id, comp_neg, comp_id, inr_f_triangle_mor₃_f_assoc, zero_comp, comp_zero, add_zero] open ComposableArrows include hS in lemma quasiIso_descShortComplex : QuasiIso (descShortComplex S) where quasiIsoAt n := by rw [quasiIsoAt_iff_isIso_homologyMap] let φ : ((homologyFunctor C (up ℤ) 0).homologySequenceComposableArrows₅ (triangleh S.f) n _ rfl).δlast ⟶ (composableArrows₅ hS n _ rfl).δlast := homMk₄ ((homologyFunctorFactors C (up ℤ) _).hom.app _) ((homologyFunctorFactors C (up ℤ) _).hom.app _) ((homologyFunctorFactors C (up ℤ) _).hom.app _ ≫ HomologicalComplex.homologyMap (descShortComplex S) n) ((homologyFunctorFactors C (up ℤ) _).hom.app _) ((homologyFunctorFactors C (up ℤ) _).hom.app _) ((homologyFunctorFactors C (up ℤ) _).hom.naturality S.f) (by erw [(homologyFunctorFactors C (up ℤ) n).hom.naturality_assoc] -- Disable `Fin.reduceFinMk`, otherwise `Precomp.obj_succ` does not fire. (#27382) dsimp [-Fin.reduceFinMk] rw [← HomologicalComplex.homologyMap_comp, inr_descShortComplex]) (by -- Disable `Fin.reduceFinMk`, otherwise `Precomp.obj_succ` does not fire. (#27382) dsimp [-Fin.reduceFinMk] erw [homologySequenceδ_triangleh hS] simp only [Functor.comp_obj, HomologicalComplex.homologyFunctor_obj, assoc, Iso.inv_hom_id_app, comp_id]) ((homologyFunctorFactors C (up ℤ) _).hom.naturality S.f) have : IsIso ((homologyFunctorFactors C (up ℤ) n).hom.app (mappingCone S.f) ≫ HomologicalComplex.homologyMap (descShortComplex S) n) := by apply Abelian.isIso_of_epi_of_isIso_of_isIso_of_mono ((homologyFunctor C (up ℤ) 0).homologySequenceComposableArrows₅_exact _ (mappingCone_triangleh_distinguished S.f) n _ rfl).δlast (composableArrows₅_exact hS n _ rfl).δlast φ all_goals dsimp [φ]; infer_instance apply IsIso.of_isIso_comp_left ((homologyFunctorFactors C (up ℤ) n).hom.app (mappingCone S.f)) end mappingCone end CochainComplex
Perfection.lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.Algebra.CharP.Frobenius import Mathlib.Algebra.CharP.Pi import Mathlib.Algebra.CharP.Quotient import Mathlib.Algebra.CharP.Subring import Mathlib.Analysis.SpecialFunctions.Pow.NNReal import Mathlib.FieldTheory.Perfect import Mathlib.RingTheory.Valuation.Integers /-! # Ring Perfection and Tilt In this file we define the perfection of a ring of characteristic p, and the tilt of a field given a valuation to `ℝ≥0`. ## TODO Define the valuation on the tilt, and define a characteristic predicate for the tilt. -/ universe u₁ u₂ u₃ u₄ open scoped NNReal /-- The perfection of a monoid `M`, defined to be the projective limit of `M` using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as `{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/ def Monoid.perfection (M : Type u₁) [CommMonoid M] (p : ℕ) : Submonoid (ℕ → M) where carrier := { f | ∀ n, f (n + 1) ^ p = f n } one_mem' _ := one_pow _ mul_mem' hf hg n := (mul_pow _ _ _).trans <| congr_arg₂ _ (hf n) (hg n) /-- The perfection of a ring `R` with characteristic `p`, as a subsemiring, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def Ring.perfectionSubsemiring (R : Type u₁) [CommSemiring R] (p : ℕ) [hp : Fact p.Prime] [CharP R p] : Subsemiring (ℕ → R) := { Monoid.perfection R p with zero_mem' := fun _ ↦ zero_pow hp.1.ne_zero add_mem' := fun hf hg n => (frobenius_add R p _ _).trans <| congr_arg₂ _ (hf n) (hg n) } /-- The perfection of a ring `R` with characteristic `p`, as a subring, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def Ring.perfectionSubring (R : Type u₁) [CommRing R] (p : ℕ) [hp : Fact p.Prime] [CharP R p] : Subring (ℕ → R) := (Ring.perfectionSubsemiring R p).toSubring fun n => by simp_rw [← frobenius_def, Pi.neg_apply, Pi.one_apply, RingHom.map_neg, RingHom.map_one] /-- The perfection of a ring `R` with characteristic `p`, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{f : ℕ → R // ∀ n, f (n + 1) ^ p = f n}`. -/ def Ring.Perfection (R : Type u₁) [CommSemiring R] (p : ℕ) : Type u₁ := { f // ∀ n : ℕ, (f : ℕ → R) (n + 1) ^ p = f n } namespace Perfection variable (R : Type u₁) [CommSemiring R] (p : ℕ) [hp : Fact p.Prime] [CharP R p] instance commSemiring : CommSemiring (Ring.Perfection R p) := (Ring.perfectionSubsemiring R p).toCommSemiring instance charP : CharP (Ring.Perfection R p) p := CharP.subsemiring (ℕ → R) p (Ring.perfectionSubsemiring R p) instance ring (R : Type u₁) [CommRing R] [CharP R p] : Ring (Ring.Perfection R p) := (Ring.perfectionSubring R p).toRing instance commRing (R : Type u₁) [CommRing R] [CharP R p] : CommRing (Ring.Perfection R p) := (Ring.perfectionSubring R p).toCommRing instance : Inhabited (Ring.Perfection R p) := ⟨0⟩ /-- The `n`-th coefficient of an element of the perfection. -/ def coeff (n : ℕ) : Ring.Perfection R p →+* R where toFun f := f.1 n map_one' := rfl map_mul' _ _ := rfl map_zero' := rfl map_add' _ _ := rfl variable {R p} @[ext] theorem ext {f g : Ring.Perfection R p} (h : ∀ n, coeff R p n f = coeff R p n g) : f = g := Subtype.eq <| funext h variable (R p) /-- The `p`-th root of an element of the perfection. -/ def pthRoot : Ring.Perfection R p →+* Ring.Perfection R p where toFun f := ⟨fun n => coeff R p (n + 1) f, fun _ => f.2 _⟩ map_one' := rfl map_mul' _ _ := rfl map_zero' := rfl map_add' _ _ := rfl variable {R p} @[simp] theorem coeff_mk (f : ℕ → R) (hf) (n : ℕ) : coeff R p n ⟨f, hf⟩ = f n := rfl theorem coeff_pthRoot (f : Ring.Perfection R p) (n : ℕ) : coeff R p n (pthRoot R p f) = coeff R p (n + 1) f := rfl theorem coeff_pow_p (f : Ring.Perfection R p) (n : ℕ) : coeff R p (n + 1) (f ^ p) = coeff R p n f := by rw [RingHom.map_pow]; exact f.2 n theorem coeff_pow_p' (f : Ring.Perfection R p) (n : ℕ) : coeff R p (n + 1) f ^ p = coeff R p n f := f.2 n theorem coeff_frobenius (f : Ring.Perfection R p) (n : ℕ) : coeff R p (n + 1) (frobenius _ p f) = coeff R p n f := by apply coeff_pow_p f n -- `coeff_pow_p f n` also works but is slow! theorem coeff_iterate_frobenius (f : Ring.Perfection R p) (n m : ℕ) : coeff R p (n + m) ((frobenius _ p)^[m] f) = coeff R p n f := Nat.recOn m rfl fun m ih => by rw [Function.iterate_succ_apply', Nat.add_succ, coeff_frobenius, ih] theorem coeff_iterate_frobenius' (f : Ring.Perfection R p) (n m : ℕ) (hmn : m ≤ n) : coeff R p n ((frobenius _ p)^[m] f) = coeff R p (n - m) f := Eq.symm <| (coeff_iterate_frobenius _ _ m).symm.trans <| (tsub_add_cancel_of_le hmn).symm ▸ rfl theorem pthRoot_frobenius : (pthRoot R p).comp (frobenius _ p) = RingHom.id _ := RingHom.ext fun x => ext fun n => by rw [RingHom.comp_apply, RingHom.id_apply, coeff_pthRoot, coeff_frobenius] theorem frobenius_pthRoot : (frobenius _ p).comp (pthRoot R p) = RingHom.id _ := RingHom.ext fun x => ext fun n => by rw [RingHom.comp_apply, RingHom.id_apply, RingHom.map_frobenius, coeff_pthRoot, ← @RingHom.map_frobenius (Ring.Perfection R p) _ R, coeff_frobenius] theorem coeff_add_ne_zero {f : Ring.Perfection R p} {n : ℕ} (hfn : coeff R p n f ≠ 0) (k : ℕ) : coeff R p (n + k) f ≠ 0 := Nat.recOn k hfn fun k ih h => ih <| by rw [Nat.add_succ] at h rw [← coeff_pow_p, RingHom.map_pow, h, zero_pow hp.1.ne_zero] theorem coeff_ne_zero_of_le {f : Ring.Perfection R p} {m n : ℕ} (hfm : coeff R p m f ≠ 0) (hmn : m ≤ n) : coeff R p n f ≠ 0 := let ⟨k, hk⟩ := Nat.exists_eq_add_of_le hmn hk.symm ▸ coeff_add_ne_zero hfm k variable (R p) instance perfectRing : PerfectRing (Ring.Perfection R p) p where bijective_frobenius := Function.bijective_iff_has_inverse.mpr ⟨pthRoot R p, DFunLike.congr_fun <| @frobenius_pthRoot R _ p _ _, DFunLike.congr_fun <| @pthRoot_frobenius R _ p _ _⟩ /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* Perfection S p`. -/ @[simps] noncomputable def lift (R : Type u₁) [CommSemiring R] [CharP R p] [PerfectRing R p] (S : Type u₂) [CommSemiring S] [CharP S p] : (R →+* S) ≃ (R →+* Ring.Perfection S p) where toFun f := { toFun := fun r => ⟨fun n => f (((frobeniusEquiv R p).symm : R →+* R)^[n] r), fun n => by rw [← f.map_pow, Function.iterate_succ_apply', RingHom.coe_coe, frobeniusEquiv_symm_pow_p]⟩ map_one' := ext fun _ => (congr_arg f <| iterate_map_one _ _).trans f.map_one map_mul' := fun _ _ => ext fun _ => (congr_arg f <| iterate_map_mul _ _ _ _).trans <| f.map_mul _ _ map_zero' := ext fun _ => (congr_arg f <| iterate_map_zero _ _).trans f.map_zero map_add' := fun _ _ => ext fun _ => (congr_arg f <| iterate_map_add _ _ _ _).trans <| f.map_add _ _ } invFun := RingHom.comp <| coeff S p 0 right_inv f := RingHom.ext fun r => ext fun n => show coeff S p 0 (f (((frobeniusEquiv R p).symm)^[n] r)) = coeff S p n (f r) by rw [← coeff_iterate_frobenius _ 0 n, zero_add, ← RingHom.map_iterate_frobenius, Function.RightInverse.iterate (frobenius_apply_frobeniusEquiv_symm R p) n] theorem hom_ext {R : Type u₁} [CommSemiring R] [CharP R p] [PerfectRing R p] {S : Type u₂} [CommSemiring S] [CharP S p] {f g : R →+* Ring.Perfection S p} (hfg : ∀ x, coeff S p 0 (f x) = coeff S p 0 (g x)) : f = g := (lift p R S).symm.injective <| RingHom.ext hfg variable {R} {S : Type u₂} [CommSemiring S] [CharP S p] /-- A ring homomorphism `R →+* S` induces `Perfection R p →+* Perfection S p`. -/ @[simps] def map (φ : R →+* S) : Ring.Perfection R p →+* Ring.Perfection S p where toFun f := ⟨fun n => φ (coeff R p n f), fun n => by rw [← φ.map_pow, coeff_pow_p']⟩ map_one' := Subtype.eq <| funext fun _ => φ.map_one map_mul' _ _ := Subtype.eq <| funext fun _ => φ.map_mul _ _ map_zero' := Subtype.eq <| funext fun _ => φ.map_zero map_add' _ _ := Subtype.eq <| funext fun _ => φ.map_add _ _ theorem coeff_map (φ : R →+* S) (f : Ring.Perfection R p) (n : ℕ) : coeff S p n (map p φ f) = φ (coeff R p n f) := rfl end Perfection /-- A perfection map to a ring of characteristic `p` is a map that is isomorphic to its perfection. -/ structure PerfectionMap (p : ℕ) [Fact p.Prime] {R : Type u₁} [CommSemiring R] [CharP R p] {P : Type u₂} [CommSemiring P] [CharP P p] [PerfectRing P p] (π : P →+* R) : Prop where injective : ∀ ⦃x y : P⦄, (∀ n, π (((frobeniusEquiv P p).symm)^[n] x) = π (((frobeniusEquiv P p).symm)^[n] y)) → x = y surjective : ∀ f : ℕ → R, (∀ n, f (n + 1) ^ p = f n) → ∃ x : P, ∀ n, π (((frobeniusEquiv P p).symm)^[n] x) = f n namespace PerfectionMap variable {p : ℕ} [Fact p.Prime] variable {R : Type u₁} [CommSemiring R] [CharP R p] variable {P : Type u₃} [CommSemiring P] [CharP P p] [PerfectRing P p] /-- Create a `PerfectionMap` from an isomorphism to the perfection. -/ @[simps] theorem mk' {f : P →+* R} (g : P ≃+* Ring.Perfection R p) (hfg : Perfection.lift p P R f = g) : PerfectionMap p f := { injective := fun x y hxy => g.injective <| (RingHom.ext_iff.1 hfg x).symm.trans <| Eq.symm <| (RingHom.ext_iff.1 hfg y).symm.trans <| Perfection.ext fun n => (hxy n).symm surjective := fun y hy => let ⟨x, hx⟩ := g.surjective ⟨y, hy⟩ ⟨x, fun n => show Perfection.coeff R p n (Perfection.lift p P R f x) = Perfection.coeff R p n ⟨y, hy⟩ by simp [hfg, hx]⟩ } variable (p R P) /-- The canonical perfection map from the perfection of a ring. -/ theorem of : PerfectionMap p (Perfection.coeff R p 0) := mk' (RingEquiv.refl _) <| (Equiv.apply_eq_iff_eq_symm_apply _).2 rfl /-- For a perfect ring, it itself is the perfection. -/ theorem id [PerfectRing R p] : PerfectionMap p (RingHom.id R) := { injective := fun _ _ hxy => hxy 0 surjective := fun f hf => ⟨f 0, fun n => show ((frobeniusEquiv R p).symm)^[n] (f 0) = f n from Nat.recOn n rfl fun n ih => injective_pow_p R p <| by rw [Function.iterate_succ_apply', frobeniusEquiv_symm_pow_p, ih, hf]⟩ } variable {p R P} /-- A perfection map induces an isomorphism to the perfection. -/ noncomputable def equiv {π : P →+* R} (m : PerfectionMap p π) : P ≃+* Ring.Perfection R p := RingEquiv.ofBijective (Perfection.lift p P R π) ⟨fun _ _ hxy => m.injective fun n => (congr_arg (Perfection.coeff R p n) hxy :), fun f => let ⟨x, hx⟩ := m.surjective f.1 f.2 ⟨x, Perfection.ext <| hx⟩⟩ theorem equiv_apply {π : P →+* R} (m : PerfectionMap p π) (x : P) : m.equiv x = Perfection.lift p P R π x := rfl theorem comp_equiv {π : P →+* R} (m : PerfectionMap p π) (x : P) : Perfection.coeff R p 0 (m.equiv x) = π x := rfl theorem comp_equiv' {π : P →+* R} (m : PerfectionMap p π) : (Perfection.coeff R p 0).comp ↑m.equiv = π := RingHom.ext fun _ => rfl theorem comp_symm_equiv {π : P →+* R} (m : PerfectionMap p π) (f : Ring.Perfection R p) : π (m.equiv.symm f) = Perfection.coeff R p 0 f := (m.comp_equiv _).symm.trans <| congr_arg _ <| m.equiv.apply_symm_apply f theorem comp_symm_equiv' {π : P →+* R} (m : PerfectionMap p π) : π.comp ↑m.equiv.symm = Perfection.coeff R p 0 := RingHom.ext m.comp_symm_equiv variable (p R P) /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* P`, where `P` is any perfection of `S`. -/ @[simps] noncomputable def lift [PerfectRing R p] (S : Type u₂) [CommSemiring S] [CharP S p] (P : Type u₃) [CommSemiring P] [CharP P p] [PerfectRing P p] (π : P →+* S) (m : PerfectionMap p π) : (R →+* S) ≃ (R →+* P) where toFun f := RingHom.comp ↑m.equiv.symm <| Perfection.lift p R S f invFun f := π.comp f left_inv f := by simp_rw [← RingHom.comp_assoc, comp_symm_equiv'] exact (Perfection.lift p R S).symm_apply_apply f right_inv f := by exact RingHom.ext fun x => m.equiv.injective <| (m.equiv.apply_symm_apply _).trans <| show Perfection.lift p R S (π.comp f) x = RingHom.comp (↑m.equiv) f x from RingHom.ext_iff.1 (by rw [Equiv.apply_eq_iff_eq_symm_apply]; rfl) _ variable {R p} theorem hom_ext [PerfectRing R p] {S : Type u₂} [CommSemiring S] [CharP S p] {P : Type u₃} [CommSemiring P] [CharP P p] [PerfectRing P p] (π : P →+* S) (m : PerfectionMap p π) {f g : R →+* P} (hfg : ∀ x, π (f x) = π (g x)) : f = g := (lift p R S P π m).symm.injective <| RingHom.ext hfg variable {P} (p) variable {S : Type u₂} [CommSemiring S] [CharP S p] variable {Q : Type u₄} [CommSemiring Q] [CharP Q p] [PerfectRing Q p] /-- A ring homomorphism `R →+* S` induces `P →+* Q`, a map of the respective perfections. -/ @[nolint unusedArguments] noncomputable def map {π : P →+* R} (_ : PerfectionMap p π) {σ : Q →+* S} (n : PerfectionMap p σ) (φ : R →+* S) : P →+* Q := lift p P S Q σ n <| φ.comp π theorem comp_map {π : P →+* R} (m : PerfectionMap p π) {σ : Q →+* S} (n : PerfectionMap p σ) (φ : R →+* S) : σ.comp (map p m n φ) = φ.comp π := (lift p P S Q σ n).symm_apply_apply _ theorem map_map {π : P →+* R} (m : PerfectionMap p π) {σ : Q →+* S} (n : PerfectionMap p σ) (φ : R →+* S) (x : P) : σ (map p m n φ x) = φ (π x) := RingHom.ext_iff.1 (comp_map p m n φ) x theorem map_eq_map (φ : R →+* S) : map p (of p R) (of p S) φ = Perfection.map p φ := hom_ext _ (of p S) fun f => by rw [map_map, Perfection.coeff_map] end PerfectionMap section ModP variable (O : Type u₂) [CommRing O] (p : ℕ) /-- `O/(p)` for `O`, ring of integers of `K`. -/ def ModP := O ⧸ (Ideal.span {(p : O)} : Ideal O) namespace ModP instance commRing : CommRing (ModP O p) := Ideal.Quotient.commRing (Ideal.span {(p : O)} : Ideal O) instance charP [Fact p.Prime] [hvp : Fact (¬ IsUnit (p : O))] : CharP (ModP O p) p := CharP.quotient O p <| hvp.1 instance nontrivial [hp : Fact p.Prime] [Fact (¬ IsUnit (p : O))] : Nontrivial (ModP O p) := CharP.nontrivial_of_char_ne_one hp.1.ne_one end ModP end ModP section Perfectoid variable (K : Type u₁) [Field K] (v : Valuation K ℝ≥0) variable (O : Type u₂) [CommRing O] [Algebra O K] (hv : v.Integers O) variable (p : ℕ) namespace ModP section Classical attribute [local instance] Classical.dec /-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`, a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/ noncomputable def preVal (x : ModP O p) : ℝ≥0 := if x = 0 then 0 else v (algebraMap O K x.out) variable {K v O p} theorem preVal_zero : preVal K v O p 0 = 0 := if_pos rfl include hv theorem preVal_mk {x : O} (hx : (Ideal.Quotient.mk _ x : ModP O p) ≠ 0) : preVal K v O p (Ideal.Quotient.mk _ x) = v (algebraMap O K x) := by obtain ⟨r, hr⟩ : ∃ (a : O), a * (p : O) = (Ideal.Quotient.mk _ x).out - x := Ideal.mem_span_singleton'.1 <| Ideal.Quotient.eq.1 <| Quotient.sound' <| Quotient.mk_out' _ refine (if_neg hx).trans (v.map_eq_of_sub_lt <| lt_of_not_ge ?_) rw [← RingHom.map_sub, ← hr, hv.le_iff_dvd] exact fun hprx => hx (Ideal.Quotient.eq_zero_iff_mem.2 <| Ideal.mem_span_singleton.2 <| dvd_of_mul_left_dvd hprx) theorem preVal_mul {x y : ModP O p} (hxy0 : x * y ≠ 0) : preVal K v O p (x * y) = preVal K v O p x * preVal K v O p y := by have hx0 : x ≠ 0 := mt (by rintro rfl; rw [zero_mul]) hxy0 have hy0 : y ≠ 0 := mt (by rintro rfl; rw [mul_zero]) hxy0 obtain ⟨r, rfl⟩ := Ideal.Quotient.mk_surjective x obtain ⟨s, rfl⟩ := Ideal.Quotient.mk_surjective y rw [← map_mul (Ideal.Quotient.mk (Ideal.span {↑p})) r s] at hxy0 ⊢ rw [preVal_mk hv hx0, preVal_mk hv hy0, preVal_mk hv hxy0, RingHom.map_mul, v.map_mul] theorem preVal_add (x y : ModP O p) : preVal K v O p (x + y) ≤ max (preVal K v O p x) (preVal K v O p y) := by by_cases hx0 : x = 0 · rw [hx0, zero_add]; exact le_max_right _ _ by_cases hy0 : y = 0 · rw [hy0, add_zero]; exact le_max_left _ _ by_cases hxy0 : x + y = 0 · rw [hxy0, preVal_zero]; exact zero_le _ obtain ⟨r, rfl⟩ := Ideal.Quotient.mk_surjective x obtain ⟨s, rfl⟩ := Ideal.Quotient.mk_surjective y rw [← map_add (Ideal.Quotient.mk (Ideal.span {↑p})) r s] at hxy0 ⊢ rw [preVal_mk hv hx0, preVal_mk hv hy0, preVal_mk hv hxy0, RingHom.map_add]; exact v.map_add _ _ theorem v_p_lt_preVal {x : ModP O p} : v p < preVal K v O p x ↔ x ≠ 0 := by refine ⟨fun h hx => by rw [hx, preVal_zero] at h; exact not_lt_zero' h, fun h => lt_of_not_ge fun hp => h ?_⟩ obtain ⟨r, rfl⟩ := Ideal.Quotient.mk_surjective x rw [preVal_mk hv h, ← map_natCast (algebraMap O K) p, hv.le_iff_dvd] at hp · rw [Ideal.Quotient.eq_zero_iff_mem, Ideal.mem_span_singleton]; exact hp theorem preVal_eq_zero {x : ModP O p} : preVal K v O p x = 0 ↔ x = 0 := ⟨fun hvx => by_contradiction fun hx0 : x ≠ 0 => by rw [← v_p_lt_preVal (hv := hv), hvx] at hx0 exact not_lt_zero' hx0, fun hx => hx.symm ▸ preVal_zero⟩ theorem v_p_lt_val {x : O} : v p < v (algebraMap O K x) ↔ (Ideal.Quotient.mk _ x : ModP O p) ≠ 0 := by rw [lt_iff_not_ge, not_iff_not, ← map_natCast (algebraMap O K) p, hv.le_iff_dvd, Ideal.Quotient.eq_zero_iff_mem, Ideal.mem_span_singleton] open NNReal variable [hp : Fact p.Prime] theorem mul_ne_zero_of_pow_p_ne_zero {x y : ModP O p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) : x * y ≠ 0 := by obtain ⟨r, rfl⟩ := Ideal.Quotient.mk_surjective x obtain ⟨s, rfl⟩ := Ideal.Quotient.mk_surjective y have h1p : (0 : ℝ) < 1 / p := one_div_pos.2 (Nat.cast_pos.2 hp.1.pos) rw [← (Ideal.Quotient.mk (Ideal.span {(p : O)})).map_mul] rw [← (Ideal.Quotient.mk (Ideal.span {(p : O)})).map_pow] at hx hy rw [← v_p_lt_val hv] at hx hy ⊢ rw [RingHom.map_pow, v.map_pow, ← rpow_lt_rpow_iff h1p, ← rpow_natCast, ← rpow_mul, mul_one_div_cancel (Nat.cast_ne_zero.2 hp.1.ne_zero : (p : ℝ) ≠ 0), rpow_one] at hx hy rw [RingHom.map_mul, v.map_mul]; refine lt_of_le_of_lt ?_ (mul_lt_mul'' hx hy zero_le' zero_le') by_cases hvp : v p = 0 · rw [hvp]; exact zero_le _ replace hvp := zero_lt_iff.2 hvp conv_lhs => rw [← rpow_one (v p)] rw [← rpow_add (ne_of_gt hvp)] refine rpow_le_rpow_of_exponent_ge hvp (map_natCast (algebraMap O K) p ▸ hv.2 _) ?_ rw [← add_div, div_le_one (Nat.cast_pos.2 hp.1.pos : 0 < (p : ℝ))]; exact mod_cast hp.1.two_le end Classical end ModP /-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/ def PreTilt := Ring.Perfection (ModP O p) p namespace PreTilt variable [Fact p.Prime] [Fact (¬ IsUnit (p : O))] instance : CommRing (PreTilt O p) := Perfection.commRing p _ instance : CharP (PreTilt O p) p := Perfection.charP (ModP O p) p section Classical open Perfection open scoped Classical in /-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `preVal(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def valAux (f : PreTilt O p) : ℝ≥0 := if h : ∃ n, coeff _ _ n f ≠ 0 then ModP.preVal K v O p (coeff _ _ (Nat.find h) f) ^ p ^ Nat.find h else 0 variable {K v O p} open scoped Classical in theorem coeff_nat_find_add_ne_zero {f : PreTilt O p} {h : ∃ n, coeff _ _ n f ≠ 0} (k : ℕ) : coeff _ _ (Nat.find h + k) f ≠ 0 := coeff_add_ne_zero (Nat.find_spec h) k theorem valAux_zero : valAux K v O p 0 = 0 := dif_neg fun ⟨_, hn⟩ => hn rfl include hv theorem valAux_eq {f : PreTilt O p} {n : ℕ} (hfn : coeff _ _ n f ≠ 0) : valAux K v O p f = ModP.preVal K v O p (coeff _ _ n f) ^ p ^ n := by have h : ∃ n, coeff _ _ n f ≠ 0 := ⟨n, hfn⟩ rw [valAux, dif_pos h] classical obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le (Nat.find_min' h hfn) induction' k with k ih · rfl obtain ⟨x, hx⟩ := Ideal.Quotient.mk_surjective (coeff (ModP O p) p (Nat.find h + k + 1) f) have h1 : (Ideal.Quotient.mk _ x : ModP O p) ≠ 0 := hx.symm ▸ hfn have h2 : (Ideal.Quotient.mk _ (x ^ p) : ModP O p) ≠ 0 := by erw [RingHom.map_pow, hx, ← RingHom.map_pow, coeff_pow_p] exact coeff_nat_find_add_ne_zero k erw [ih (coeff_nat_find_add_ne_zero k), ← hx, ← coeff_pow_p, RingHom.map_pow, ← hx, ← RingHom.map_pow, ModP.preVal_mk hv h1, ModP.preVal_mk hv h2, RingHom.map_pow, v.map_pow, ← pow_mul, pow_succ'] rfl theorem valAux_one : valAux K v O p 1 = 1 := (valAux_eq (hv := hv) <| show coeff (ModP O p) p 0 1 ≠ 0 from one_ne_zero).trans <| by rw [pow_zero, pow_one, RingHom.map_one, ← (Ideal.Quotient.mk _).map_one, ModP.preVal_mk hv, RingHom.map_one, v.map_one] change (1 : ModP O p) ≠ 0 exact one_ne_zero theorem valAux_mul (f g : PreTilt O p) : valAux K v O p (f * g) = valAux K v O p f * valAux K v O p g := by by_cases hf : f = 0 · rw [hf, zero_mul, valAux_zero, zero_mul] by_cases hg : g = 0 · rw [hg, mul_zero, valAux_zero, mul_zero] obtain ⟨m, hm⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 fun h => hf <| Perfection.ext h obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 fun h => hg <| Perfection.ext h replace hm := coeff_ne_zero_of_le hm (le_max_left m n) replace hn := coeff_ne_zero_of_le hn (le_max_right m n) have hfg : coeff _ _ (max m n + 1) (f * g) ≠ 0 := by rw [RingHom.map_mul] refine ModP.mul_ne_zero_of_pow_p_ne_zero (hv := hv) ?_ ?_ · rw [← RingHom.map_pow, coeff_pow_p f]; assumption · rw [← RingHom.map_pow, coeff_pow_p g]; assumption rw [valAux_eq hv (coeff_add_ne_zero hm 1), valAux_eq hv (coeff_add_ne_zero hn 1), valAux_eq hv hfg] rw [RingHom.map_mul] at hfg ⊢; rw [ModP.preVal_mul hv hfg, mul_pow] theorem valAux_add (f g : PreTilt O p) : valAux K v O p (f + g) ≤ max (valAux K v O p f) (valAux K v O p g) := by by_cases hf : f = 0 · rw [hf, zero_add, valAux_zero, max_eq_right]; exact zero_le _ by_cases hg : g = 0 · rw [hg, add_zero, valAux_zero, max_eq_left]; exact zero_le _ by_cases hfg : f + g = 0 · rw [hfg, valAux_zero]; exact zero_le _ replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 fun h => hf <| Perfection.ext h replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 fun h => hg <| Perfection.ext h replace hfg : ∃ n, coeff _ _ n (f + g) ≠ 0 := not_forall.1 fun h => hfg <| Perfection.ext h obtain ⟨m, hm⟩ := hf; obtain ⟨n, hn⟩ := hg; obtain ⟨k, hk⟩ := hfg replace hm := coeff_ne_zero_of_le hm (le_trans (le_max_left m n) (le_max_left _ k)) replace hn := coeff_ne_zero_of_le hn (le_trans (le_max_right m n) (le_max_left _ k)) replace hk := coeff_ne_zero_of_le hk (le_max_right (max m n) k) rw [valAux_eq hv hm, valAux_eq hv hn, valAux_eq hv hk, RingHom.map_add] rcases le_max_iff.1 (ModP.preVal_add hv (coeff _ _ (max (max m n) k) f) (coeff _ _ (max (max m n) k) g)) with h | h · exact le_max_of_le_left (pow_le_pow_left' h _) · exact le_max_of_le_right (pow_le_pow_left' h _) variable (K v O p) /-- The valuation `Perfection(O/(p)) → ℝ≥0`. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `preVal(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val : Valuation (PreTilt O p) ℝ≥0 where toFun := valAux K v O p map_one' := valAux_one hv map_mul' := valAux_mul hv map_zero' := valAux_zero map_add_le_max' := valAux_add hv variable {K v O p} theorem map_eq_zero {f : PreTilt O p} : val K v O hv p f = 0 ↔ f = 0 := by by_cases hf0 : f = 0 · rw [hf0]; exact iff_of_true (Valuation.map_zero _) rfl obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 fun h => hf0 <| Perfection.ext h change valAux K v O p f = 0 ↔ f = 0; refine iff_of_false (fun hvf => hn ?_) hf0 rw [valAux_eq hv hn] at hvf; replace hvf := pow_eq_zero hvf; rwa [ModP.preVal_eq_zero hv] at hvf end Classical include hv theorem isDomain : IsDomain (PreTilt O p) := by have hp : Nat.Prime p := Fact.out haveI : Nontrivial (PreTilt O p) := ⟨(CharP.nontrivial_of_char_ne_one hp.ne_one).1⟩ haveI : NoZeroDivisors (PreTilt O p) := ⟨fun hfg => by simp_rw [← map_eq_zero hv] at hfg ⊢; contrapose! hfg; rw [Valuation.map_mul] exact mul_ne_zero hfg.1 hfg.2⟩ exact NoZeroDivisors.to_isDomain _ end PreTilt /-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in [scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`, this is implemented as the fraction field of the perfection of `O/(p)`. -/ def Tilt [Fact p.Prime] [hvp : Fact (v p ≠ 1)] := have _ := Fact.mk <| mt hv.one_of_isUnit <| (map_natCast (algebraMap O K) p).symm ▸ hvp.1 FractionRing (PreTilt O p) namespace Tilt noncomputable instance [Fact p.Prime] [hvp : Fact (v p ≠ 1)] : Field (Tilt K v O hv p) := haveI := Fact.mk <| mt hv.one_of_isUnit <| (map_natCast (algebraMap O K) p).symm ▸ hvp.1 haveI := PreTilt.isDomain K v O hv p FractionRing.field _ end Tilt end Perfectoid
Basic.lean
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Kim Morrison -/ import Mathlib.CategoryTheory.EqToHom import Mathlib.CategoryTheory.NatIso import Mathlib.CategoryTheory.Products.Basic /-! # Categories of indexed families of objects. We define the pointwise category structure on indexed families of objects in a category (and also the dependent generalization). -/ namespace CategoryTheory open Functor universe w₀ w₁ w₂ v₁ v₂ v₃ u₁ u₂ u₃ variable {I : Type w₀} {J : Type w₁} (C : I → Type u₁) [∀ i, Category.{v₁} (C i)] /-- `pi C` gives the cartesian product of an indexed family of categories. -/ instance pi : Category.{max w₀ v₁} (∀ i, C i) where Hom X Y := ∀ i, X i ⟶ Y i id X i := 𝟙 (X i) comp f g i := f i ≫ g i namespace Pi @[simp] theorem id_apply (X : ∀ i, C i) (i) : (𝟙 X : ∀ i, X i ⟶ X i) i = 𝟙 (X i) := rfl @[simp] theorem comp_apply {X Y Z : ∀ i, C i} (f : X ⟶ Y) (g : Y ⟶ Z) (i) : (f ≫ g : ∀ i, X i ⟶ Z i) i = f i ≫ g i := rfl @[ext] lemma ext {X Y : ∀ i, C i} {f g : X ⟶ Y} (w : ∀ i, f i = g i) : f = g := funext (w ·) /-- The evaluation functor at `i : I`, sending an `I`-indexed family of objects to the object over `i`. -/ @[simps] def eval (i : I) : (∀ i, C i) ⥤ C i where obj f := f i map α := α i section variable {J : Type w₁} /- Porting note: add this because Lean cannot see directly through the `∘` for `Function.comp` -/ instance (f : J → I) : (j : J) → Category ((C ∘ f) j) := by dsimp infer_instance /-- Pull back an `I`-indexed family of objects to a `J`-indexed family, along a function `J → I`. -/ @[simps] def comap (h : J → I) : (∀ i, C i) ⥤ (∀ j, C (h j)) where obj f i := f (h i) map α i := α (h i) variable (I) /-- The natural isomorphism between pulling back a grading along the identity function, and the identity functor. -/ @[simps] def comapId : comap C (id : I → I) ≅ 𝟭 (∀ i, C i) where hom := { app := fun X => 𝟙 X } inv := { app := fun X => 𝟙 X } example (g : J → I) : (j : J) → Category (C (g j)) := by infer_instance variable {I} variable {K : Type w₂} /-- The natural isomorphism comparing between pulling back along two successive functions, and pulling back along their composition -/ @[simps!] def comapComp (f : K → J) (g : J → I) : comap C g ⋙ comap (C ∘ g) f ≅ comap C (g ∘ f) where hom := { app := fun X b => 𝟙 (X (g (f b))) naturality := fun X Y f' => by simp only [comap, Function.comp]; funext; simp } inv := { app := fun X b => 𝟙 (X (g (f b))) naturality := fun X Y f' => by simp only [comap, Function.comp]; funext; simp } /-- The natural isomorphism between pulling back then evaluating, and just evaluating. -/ @[simps!] def comapEvalIsoEval (h : J → I) (j : J) : comap C h ⋙ eval (C ∘ h) j ≅ eval C (h j) := NatIso.ofComponents (fun _ => Iso.refl _) (by simp only [Iso.refl]; simp) end section variable {J : Type w₀} {D : J → Type u₁} [∀ j, Category.{v₁} (D j)] /- Porting note: maybe mixing up universes -/ instance sumElimCategory : ∀ s : I ⊕ J, Category.{v₁} (Sum.elim C D s) | Sum.inl i => by dsimp infer_instance | Sum.inr j => by dsimp infer_instance /- Porting note: replaced `Sum.rec` with `match`'s per the error about current state of code generation -/ /-- The bifunctor combining an `I`-indexed family of objects with a `J`-indexed family of objects to obtain an `I ⊕ J`-indexed family of objects. -/ @[simps] def sum : (∀ i, C i) ⥤ (∀ j, D j) ⥤ ∀ s : I ⊕ J, Sum.elim C D s where obj X := { obj := fun Y s => match s with | .inl i => X i | .inr j => Y j map := fun {_} {_} f s => match s with | .inl i => 𝟙 (X i) | .inr j => f j } map {X} {X'} f := { app := fun Y s => match s with | .inl i => f i | .inr j => 𝟙 (Y j) } end variable {C} /-- An isomorphism between `I`-indexed objects gives an isomorphism between each pair of corresponding components. -/ @[simps] def isoApp {X Y : ∀ i, C i} (f : X ≅ Y) (i : I) : X i ≅ Y i := ⟨f.hom i, f.inv i, by rw [← comp_apply, Iso.hom_inv_id, id_apply], by rw [← comp_apply, Iso.inv_hom_id, id_apply]⟩ @[simp] theorem isoApp_refl (X : ∀ i, C i) (i : I) : isoApp (Iso.refl X) i = Iso.refl (X i) := rfl @[simp] theorem isoApp_symm {X Y : ∀ i, C i} (f : X ≅ Y) (i : I) : isoApp f.symm i = (isoApp f i).symm := rfl @[simp] theorem isoApp_trans {X Y Z : ∀ i, C i} (f : X ≅ Y) (g : Y ≅ Z) (i : I) : isoApp (f ≪≫ g) i = isoApp f i ≪≫ isoApp g i := rfl end Pi namespace Functor variable {C} variable {D : I → Type u₂} [∀ i, Category.{v₂} (D i)] {A : Type u₃} [Category.{v₃} A] /-- Assemble an `I`-indexed family of functors into a functor between the pi types. -/ @[simps] def pi (F : ∀ i, C i ⥤ D i) : (∀ i, C i) ⥤ ∀ i, D i where obj f i := (F i).obj (f i) map α i := (F i).map (α i) /-- Similar to `pi`, but all functors come from the same category `A` -/ @[simps] def pi' (f : ∀ i, A ⥤ C i) : A ⥤ ∀ i, C i where obj a i := (f i).obj a map h i := (f i).map h /-- The projections of `Functor.pi' F` are isomorphic to the functors of the family `F` -/ @[simps!] def pi'CompEval {A : Type*} [Category A] (F : ∀ i, A ⥤ C i) (i : I) : pi' F ⋙ Pi.eval C i ≅ F i := Iso.refl _ section EqToHom @[simp] theorem eqToHom_proj {x x' : ∀ i, C i} (h : x = x') (i : I) : (eqToHom h : x ⟶ x') i = eqToHom (funext_iff.mp h i) := by subst h rfl end EqToHom -- One could add some natural isomorphisms showing -- how `Functor.pi` commutes with `Pi.eval` and `Pi.comap`. @[simp] theorem pi'_eval (f : ∀ i, A ⥤ C i) (i : I) : pi' f ⋙ Pi.eval C i = f i := by apply Functor.ext · intro _ _ _ simp · intro _ rfl /-- Two functors to a product category are equal iff they agree on every coordinate. -/ theorem pi_ext (f f' : A ⥤ ∀ i, C i) (h : ∀ i, f ⋙ (Pi.eval C i) = f' ⋙ (Pi.eval C i)) : f = f' := by apply Functor.ext; rotate_left · intro X ext i specialize h i have := congr_obj h X simpa · intro X Y g funext i specialize h i have := congr_hom h g simpa end Functor namespace NatTrans variable {C} variable {D : I → Type u₂} [∀ i, Category.{v₂} (D i)] variable {F G : ∀ i, C i ⥤ D i} /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ @[simps!] def pi (α : ∀ i, F i ⟶ G i) : Functor.pi F ⟶ Functor.pi G where app f i := (α i).app (f i) /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ @[simps] def pi' {E : Type*} [Category E] {F G : E ⥤ ∀ i, C i} (τ : ∀ i, F ⋙ Pi.eval C i ⟶ G ⋙ Pi.eval C i) : F ⟶ G where app := fun X i => (τ i).app X naturality _ _ f := by ext i exact (τ i).naturality f end NatTrans namespace NatIso variable {C} variable {D : I → Type u₂} [∀ i, Category.{v₂} (D i)] variable {F G : ∀ i, C i ⥤ D i} /-- Assemble an `I`-indexed family of natural isomorphisms into a single natural isomorphism. -/ @[simps] def pi (e : ∀ i, F i ≅ G i) : Functor.pi F ≅ Functor.pi G where hom := NatTrans.pi (fun i => (e i).hom) inv := NatTrans.pi (fun i => (e i).inv) /-- Assemble an `I`-indexed family of natural isomorphisms into a single natural isomorphism. -/ @[simps] def pi' {E : Type*} [Category E] {F G : E ⥤ ∀ i, C i} (e : ∀ i, F ⋙ Pi.eval C i ≅ G ⋙ Pi.eval C i) : F ≅ G where hom := NatTrans.pi' (fun i => (e i).hom) inv := NatTrans.pi' (fun i => (e i).inv) end NatIso variable {C} lemma isIso_pi_iff {X Y : ∀ i, C i} (f : X ⟶ Y) : IsIso f ↔ ∀ i, IsIso (f i) := by constructor · intro _ i exact (Pi.isoApp (asIso f) i).isIso_hom · intro exact ⟨fun i => inv (f i), by cat_disch, by cat_disch⟩ variable (C) /-- For a family of categories `C i` indexed by `I`, an equality `i = j` in `I` induces an equivalence `C i ≌ C j`. -/ def Pi.eqToEquivalence {i j : I} (h : i = j) : C i ≌ C j := by subst h; rfl /-- When `i = j`, projections `Pi.eval C i` and `Pi.eval C j` are related by the equivalence `Pi.eqToEquivalence C h : C i ≌ C j`. -/ @[simps!] def Pi.evalCompEqToEquivalenceFunctor {i j : I} (h : i = j) : Pi.eval C i ⋙ (Pi.eqToEquivalence C h).functor ≅ Pi.eval C j := eqToIso (by subst h; rfl) /-- The equivalences given by `Pi.eqToEquivalence` are compatible with reindexing. -/ @[simps!] def Pi.eqToEquivalenceFunctorIso (f : J → I) {i' j' : J} (h : i' = j') : (Pi.eqToEquivalence C (congr_arg f h)).functor ≅ (Pi.eqToEquivalence (fun i' => C (f i')) h).functor := eqToIso (by subst h; rfl) attribute [local simp] eqToHom_map /-- Reindexing a family of categories gives equivalent `Pi` categories. -/ @[simps] noncomputable def Pi.equivalenceOfEquiv (e : J ≃ I) : (∀ j, C (e j)) ≌ (∀ i, C i) where functor := pi' (fun i => Pi.eval _ (e.symm i) ⋙ (Pi.eqToEquivalence C (by simp)).functor) inverse := Functor.pi' (fun i' => Pi.eval _ (e i')) unitIso := NatIso.pi' (fun i' => leftUnitor _ ≪≫ (Pi.evalCompEqToEquivalenceFunctor (fun j => C (e j)) (e.symm_apply_apply i')).symm ≪≫ isoWhiskerLeft _ ((Pi.eqToEquivalenceFunctorIso C e (e.symm_apply_apply i')).symm) ≪≫ (pi'CompEval _ _).symm ≪≫ isoWhiskerLeft _ (pi'CompEval _ _).symm ≪≫ (associator _ _ _).symm) counitIso := NatIso.pi' (fun i => (associator _ _ _).symm ≪≫ isoWhiskerRight (pi'CompEval _ _) _ ≪≫ Pi.evalCompEqToEquivalenceFunctor C (e.apply_symm_apply i) ≪≫ (leftUnitor _).symm) /-- A product of categories indexed by `Option J` identifies to a binary product. -/ @[simps] def Pi.optionEquivalence (C' : Option J → Type u₁) [∀ i, Category.{v₁} (C' i)] : (∀ i, C' i) ≌ C' none × (∀ (j : J), C' (some j)) where functor := Functor.prod' (Pi.eval C' none) (Functor.pi' (fun i => (Pi.eval _ (some i)))) inverse := Functor.pi' (fun i => match i with | none => Prod.fst _ _ | some i => Prod.snd _ _ ⋙ (Pi.eval _ i)) unitIso := NatIso.pi' (fun i => match i with | none => Iso.refl _ | some _ => Iso.refl _) counitIso := by exact Iso.refl _ namespace Equivalence variable {C} variable {D : I → Type u₂} [∀ i, Category.{v₂} (D i)] /-- Assemble an `I`-indexed family of equivalences of categories into a single equivalence. -/ @[simps] def pi (E : ∀ i, C i ≌ D i) : (∀ i, C i) ≌ (∀ i, D i) where functor := Functor.pi (fun i => (E i).functor) inverse := Functor.pi (fun i => (E i).inverse) unitIso := NatIso.pi (fun i => (E i).unitIso) counitIso := NatIso.pi (fun i => (E i).counitIso) instance (F : ∀ i, C i ⥤ D i) [∀ i, (F i).IsEquivalence] : (Functor.pi F).IsEquivalence := (pi (fun i => (F i).asEquivalence)).isEquivalence_functor end Equivalence end CategoryTheory
inertia.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path. From mathcomp Require Import choice fintype div tuple finfun bigop prime order. From mathcomp Require Import ssralg ssrnum finset fingroup morphism perm. From mathcomp Require Import automorphism quotient action zmodp cyclic center. From mathcomp Require Import gproduct commutator gseries nilpotent pgroup. From mathcomp Require Import sylow maximal frobenius matrix mxalgebra. From mathcomp Require Import mxrepresentation vector algC classfun character. From mathcomp Require Import archimedean. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import Order.TTheory GroupScope GRing.Theory Num.Theory. Local Open Scope ring_scope. (******************************************************************************) (* This file contains the definitions and properties of inertia groups: *) (* (phi ^ y)%CF == the y-conjugate of phi : 'CF(G), i.e., the class *) (* function mapping x ^ y to phi x provided y normalises G. *) (* We take (phi ^ y)%CF = phi when y \notin 'N(G). *) (* (phi ^: G)%CF == the sequence of all distinct conjugates of phi : 'CF(H) *) (* by all y in G. *) (* 'I[phi] == the inertia group of phi : CF(H), i.e., the set of y *) (* such that (phi ^ y)%CF = phi AND H :^ y = y. *) (* 'I_G[phi] == the inertia group of phi in G, i.e., G :&: 'I[phi]. *) (* conjg_Iirr i y == the index j : Iirr G such that ('chi_i ^ y)%CF = 'chi_j. *) (* cfclass_Iirr G i == the image of G under conjg_Iirr i, i.e., the set of j *) (* such that 'chi_j \in ('chi_i ^: G)%CF. *) (* mul_Iirr i j == the index k such that 'chi_j * 'chi_i = 'chi[G]_k, *) (* or 0 if 'chi_j * 'chi_i is reducible. *) (* mul_mod_Iirr i j := mul_Iirr i (mod_Iirr j), for j : Iirr (G / H). *) (******************************************************************************) Reserved Notation "''I[' phi ]" (format "''I[' phi ]"). Reserved Notation "''I_' G [ phi ]" (G at level 2, format "''I_' G [ phi ]"). Section ConjDef. Variables (gT : finGroupType) (B : {set gT}) (y : gT) (phi : 'CF(B)). Local Notation G := <<B>>. Fact cfConjg_subproof : is_class_fun G [ffun x => phi (if y \in 'N(G) then x ^ y^-1 else x)]. Proof. apply: intro_class_fun => [x z _ Gz | x notGx]. have [nGy | _] := ifP; last by rewrite cfunJgen. by rewrite -conjgM conjgC conjgM cfunJgen // memJ_norm ?groupV. by rewrite cfun0gen //; case: ifP => // nGy; rewrite memJ_norm ?groupV. Qed. Definition cfConjg := Cfun 1 cfConjg_subproof. End ConjDef. Prenex Implicits cfConjg. Notation "f ^ y" := (cfConjg y f) : cfun_scope. Section Conj. Variables (gT : finGroupType) (G : {group gT}). Implicit Type phi : 'CF(G). Lemma cfConjgE phi y x : y \in 'N(G) -> (phi ^ y)%CF x = phi (x ^ y^-1)%g. Proof. by rewrite cfunElock genGid => ->. Qed. Lemma cfConjgEJ phi y x : y \in 'N(G) -> (phi ^ y)%CF (x ^ y) = phi x. Proof. by move/cfConjgE->; rewrite conjgK. Qed. Lemma cfConjgEout phi y : y \notin 'N(G) -> (phi ^ y = phi)%CF. Proof. by move/negbTE=> notNy; apply/cfunP=> x; rewrite !cfunElock genGid notNy. Qed. Lemma cfConjgEin phi y (nGy : y \in 'N(G)) : (phi ^ y)%CF = cfIsom (norm_conj_isom nGy) phi. Proof. apply/cfun_inP=> x Gx. by rewrite cfConjgE // -{2}[x](conjgKV y) cfIsomE ?memJ_norm ?groupV. Qed. Lemma cfConjgMnorm phi : {in 'N(G) &, forall y z, phi ^ (y * z) = (phi ^ y) ^ z}%CF. Proof. move=> y z nGy nGz. by apply/cfunP=> x; rewrite !cfConjgE ?groupM // invMg conjgM. Qed. Lemma cfConjg_id phi y : y \in G -> (phi ^ y)%CF = phi. Proof. move=> Gy; apply/cfunP=> x; have nGy := subsetP (normG G) y Gy. by rewrite -(cfunJ _ _ Gy) cfConjgEJ. Qed. (* Isaacs' 6.1.b *) Lemma cfConjgM L phi : G <| L -> {in L &, forall y z, phi ^ (y * z) = (phi ^ y) ^ z}%CF. Proof. by case/andP=> _ /subsetP nGL; apply: sub_in2 (cfConjgMnorm phi). Qed. Lemma cfConjgJ1 phi : (phi ^ 1)%CF = phi. Proof. by apply/cfunP=> x; rewrite cfConjgE ?group1 // invg1 conjg1. Qed. Lemma cfConjgK y : cancel (cfConjg y) (cfConjg y^-1 : 'CF(G) -> 'CF(G)). Proof. move=> phi; apply/cfunP=> x; rewrite !cfunElock groupV /=. by case: ifP => -> //; rewrite conjgKV. Qed. Lemma cfConjgKV y : cancel (cfConjg y^-1) (cfConjg y : 'CF(G) -> 'CF(G)). Proof. by move=> phi /=; rewrite -{1}[y]invgK cfConjgK. Qed. Lemma cfConjg1 phi y : (phi ^ y)%CF 1%g = phi 1%g. Proof. by rewrite cfunElock conj1g if_same. Qed. Fact cfConjg_is_linear y : linear (cfConjg y : 'CF(G) -> 'CF(G)). Proof. by move=> a phi psi; apply/cfunP=> x; rewrite !cfunElock. Qed. HB.instance Definition _ y := GRing.isSemilinear.Build _ _ _ _ (cfConjg y) (GRing.semilinear_linear (cfConjg_is_linear y)). Lemma cfConjg_cfuniJ A y : y \in 'N(G) -> ('1_A ^ y)%CF = '1_(A :^ y) :> 'CF(G). Proof. move=> nGy; apply/cfunP=> x; rewrite !cfunElock genGid nGy -sub_conjgV. by rewrite -class_lcoset -class_rcoset norm_rlcoset ?memJ_norm ?groupV. Qed. Lemma cfConjg_cfuni A y : y \in 'N(A) -> ('1_A ^ y)%CF = '1_A :> 'CF(G). Proof. by have [/cfConjg_cfuniJ-> /normP-> | /cfConjgEout] := boolP (y \in 'N(G)). Qed. Lemma cfConjg_cfun1 y : (1 ^ y)%CF = 1 :> 'CF(G). Proof. by rewrite -cfuniG; have [/cfConjg_cfuni|/cfConjgEout] := boolP (y \in 'N(G)). Qed. Fact cfConjg_is_monoid_morphism y : monoid_morphism (cfConjg y : _ -> 'CF(G)). Proof. split=> [|phi psi]; first exact: cfConjg_cfun1. by apply/cfunP=> x; rewrite !cfunElock. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `cfConjg_is_monoid_morphism` instead")] Definition cfConjg_is_multiplicative y := (fun g => (g.2,g.1)) (cfConjg_is_monoid_morphism y). HB.instance Definition _ y := GRing.isMonoidMorphism.Build _ _ (cfConjg y) (cfConjg_is_monoid_morphism y). Lemma cfConjg_eq1 phi y : ((phi ^ y)%CF == 1) = (phi == 1). Proof. by apply: rmorph_eq1; apply: can_inj (cfConjgK y). Qed. Lemma cfAutConjg phi u y : cfAut u (phi ^ y) = (cfAut u phi ^ y)%CF. Proof. by apply/cfunP=> x; rewrite !cfunElock. Qed. Lemma conj_cfConjg phi y : (phi ^ y)^*%CF = (phi^* ^ y)%CF. Proof. exact: cfAutConjg. Qed. Lemma cfker_conjg phi y : y \in 'N(G) -> cfker (phi ^ y) = cfker phi :^ y. Proof. move=> nGy; rewrite cfConjgEin // cfker_isom. by rewrite morphim_conj (setIidPr (cfker_sub _)). Qed. Lemma cfDetConjg phi y : cfDet (phi ^ y) = (cfDet phi ^ y)%CF. Proof. have [nGy | not_nGy] := boolP (y \in 'N(G)); last by rewrite !cfConjgEout. by rewrite !cfConjgEin cfDetIsom. Qed. End Conj. Section Inertia. Variable gT : finGroupType. Definition inertia (B : {set gT}) (phi : 'CF(B)) := [set y in 'N(B) | (phi ^ y)%CF == phi]. Local Notation "''I[' phi ]" := (inertia phi) : group_scope. Local Notation "''I_' G [ phi ]" := (G%g :&: 'I[phi]) : group_scope. Fact group_set_inertia (H : {group gT}) phi : group_set 'I[phi : 'CF(H)]. Proof. apply/group_setP; split; first by rewrite inE group1 /= cfConjgJ1. move=> y z /setIdP[nHy /eqP n_phi_y] /setIdP[nHz n_phi_z]. by rewrite inE groupM //= cfConjgMnorm ?n_phi_y. Qed. Canonical inertia_group H phi := Group (@group_set_inertia H phi). Local Notation "''I[' phi ]" := (inertia_group phi) : Group_scope. Local Notation "''I_' G [ phi ]" := (G :&: 'I[phi])%G : Group_scope. Variables G H : {group gT}. Implicit Type phi : 'CF(H). Lemma inertiaJ phi y : y \in 'I[phi] -> (phi ^ y)%CF = phi. Proof. by case/setIdP=> _ /eqP->. Qed. Lemma inertia_valJ phi x y : y \in 'I[phi] -> phi (x ^ y)%g = phi x. Proof. by case/setIdP=> nHy /eqP {1}<-; rewrite cfConjgEJ. Qed. (* To disambiguate basic inclucion lemma names we capitalize Inertia for *) (* lemmas concerning the localized inertia group 'I_G[phi]. *) Lemma Inertia_sub phi : 'I_G[phi] \subset G. Proof. exact: subsetIl. Qed. Lemma norm_inertia phi : 'I[phi] \subset 'N(H). Proof. by rewrite ['I[_]]setIdE subsetIl. Qed. Lemma sub_inertia phi : H \subset 'I[phi]. Proof. by apply/subsetP=> y Hy; rewrite inE cfConjg_id ?(subsetP (normG H)) /=. Qed. Lemma normal_inertia phi : H <| 'I[phi]. Proof. by rewrite /normal sub_inertia norm_inertia. Qed. Lemma sub_Inertia phi : H \subset G -> H \subset 'I_G[phi]. Proof. by rewrite subsetI sub_inertia andbT. Qed. Lemma norm_Inertia phi : 'I_G[phi] \subset 'N(H). Proof. by rewrite setIC subIset ?norm_inertia. Qed. Lemma normal_Inertia phi : H \subset G -> H <| 'I_G[phi]. Proof. by rewrite /normal norm_Inertia andbT; apply: sub_Inertia. Qed. Lemma cfConjg_eqE phi : H <| G -> {in G &, forall y z, (phi ^ y == phi ^ z)%CF = (z \in 'I_G[phi] :* y)}. Proof. case/andP=> _ nHG y z Gy; rewrite -{1 2}[z](mulgKV y) groupMr // mem_rcoset. move: {z}(z * _)%g => z Gz; rewrite 2!inE Gz cfConjgMnorm ?(subsetP nHG) //=. by rewrite eq_sym (can_eq (cfConjgK y)). Qed. Lemma cent_sub_inertia phi : 'C(H) \subset 'I[phi]. Proof. apply/subsetP=> y cHy; have nHy := subsetP (cent_sub H) y cHy. rewrite inE nHy; apply/eqP/cfun_inP=> x Hx; rewrite cfConjgE //. by rewrite /conjg invgK mulgA (centP cHy) ?mulgK. Qed. Lemma cent_sub_Inertia phi : 'C_G(H) \subset 'I_G[phi]. Proof. exact: setIS (cent_sub_inertia phi). Qed. Lemma center_sub_Inertia phi : H \subset G -> 'Z(G) \subset 'I_G[phi]. Proof. by move/centS=> sHG; rewrite setIS // (subset_trans sHG) // cent_sub_inertia. Qed. Lemma conjg_inertia phi y : y \in 'N(H) -> 'I[phi] :^ y = 'I[phi ^ y]. Proof. move=> nHy; apply/setP=> z; rewrite !['I[_]]setIdE conjIg conjGid // !in_setI. apply/andb_id2l=> nHz; rewrite mem_conjg !inE. by rewrite !cfConjgMnorm ?in_group ?(can2_eq (cfConjgKV y) (cfConjgK y)) ?invgK. Qed. Lemma inertia0 : 'I[0 : 'CF(H)] = 'N(H). Proof. by apply/setP=> x; rewrite !inE linear0 eqxx andbT. Qed. Lemma inertia_add phi psi : 'I[phi] :&: 'I[psi] \subset 'I[phi + psi]. Proof. rewrite !['I[_]]setIdE -setIIr setIS //. by apply/subsetP=> x /[!(inE, linearD)]/= /andP[/eqP-> /eqP->]. Qed. Lemma inertia_sum I r (P : pred I) (Phi : I -> 'CF(H)) : 'N(H) :&: \bigcap_(i <- r | P i) 'I[Phi i] \subset 'I[\sum_(i <- r | P i) Phi i]. Proof. elim/big_rec2: _ => [|i K psi Pi sK_Ipsi]; first by rewrite setIT inertia0. by rewrite setICA; apply: subset_trans (setIS _ sK_Ipsi) (inertia_add _ _). Qed. Lemma inertia_scale a phi : 'I[phi] \subset 'I[a *: phi]. Proof. apply/subsetP=> x /setIdP[nHx /eqP Iphi_x]. by rewrite inE nHx linearZ /= Iphi_x. Qed. Lemma inertia_scale_nz a phi : a != 0 -> 'I[a *: phi] = 'I[phi]. Proof. move=> nz_a; apply/eqP. by rewrite eqEsubset -{2}(scalerK nz_a phi) !inertia_scale. Qed. Lemma inertia_opp phi : 'I[- phi] = 'I[phi]. Proof. by rewrite -scaleN1r inertia_scale_nz // oppr_eq0 oner_eq0. Qed. Lemma inertia1 : 'I[1 : 'CF(H)] = 'N(H). Proof. by apply/setP=> x; rewrite inE rmorph1 eqxx andbT. Qed. Lemma Inertia1 : H <| G -> 'I_G[1 : 'CF(H)] = G. Proof. by rewrite inertia1 => /normal_norm/setIidPl. Qed. Lemma inertia_mul phi psi : 'I[phi] :&: 'I[psi] \subset 'I[phi * psi]. Proof. rewrite !['I[_]]setIdE -setIIr setIS //. by apply/subsetP=> x /[!(inE, rmorphM)]/= /andP[/eqP-> /eqP->]. Qed. Lemma inertia_prod I r (P : pred I) (Phi : I -> 'CF(H)) : 'N(H) :&: \bigcap_(i <- r | P i) 'I[Phi i] \subset 'I[\prod_(i <- r | P i) Phi i]. Proof. elim/big_rec2: _ => [|i K psi Pi sK_psi]; first by rewrite inertia1 setIT. by rewrite setICA; apply: subset_trans (setIS _ sK_psi) (inertia_mul _ _). Qed. Lemma inertia_injective (chi : 'CF(H)) : {in H &, injective chi} -> 'I[chi] = 'C(H). Proof. move=> inj_chi; apply/eqP; rewrite eqEsubset cent_sub_inertia andbT. apply/subsetP=> y Ichi_y; have /setIdP[nHy _] := Ichi_y. apply/centP=> x Hx; apply/esym/commgP/conjg_fixP. by apply/inj_chi; rewrite ?memJ_norm ?(inertia_valJ _ Ichi_y). Qed. Lemma inertia_irr_prime p i : #|H| = p -> prime p -> i != 0 -> 'I['chi[H]_i] = 'C(H). Proof. by move=> <- pr_H /(irr_prime_injP pr_H); apply: inertia_injective. Qed. Lemma inertia_irr0 : 'I['chi[H]_0] = 'N(H). Proof. by rewrite irr0 inertia1. Qed. (* Isaacs' 6.1.c *) Lemma cfConjg_iso y : isometry (cfConjg y : 'CF(H) -> 'CF(H)). Proof. move=> phi psi; congr (_ * _). have [nHy | not_nHy] := boolP (y \in 'N(H)); last by rewrite !cfConjgEout. rewrite (reindex_astabs 'J y) ?astabsJ //=. by apply: eq_bigr=> x _; rewrite !cfConjgEJ. Qed. (* Isaacs' 6.1.d *) Lemma cfdot_Res_conjg psi phi y : y \in G -> '['Res[H, G] psi, phi ^ y] = '['Res[H] psi, phi]. Proof. move=> Gy; rewrite -(cfConjg_iso y _ phi); congr '[_, _]; apply/cfunP=> x. rewrite !cfunElock !genGid; case nHy: (y \in 'N(H)) => //. by rewrite !(fun_if psi) cfunJ ?memJ_norm ?groupV. Qed. (* Isaac's 6.1.e *) Lemma cfConjg_char (chi : 'CF(H)) y : chi \is a character -> (chi ^ y)%CF \is a character. Proof. have [nHy Nchi | /cfConjgEout-> //] := boolP (y \in 'N(H)). by rewrite cfConjgEin cfIsom_char. Qed. Lemma cfConjg_lin_char (chi : 'CF(H)) y : chi \is a linear_char -> (chi ^ y)%CF \is a linear_char. Proof. by case/andP=> Nchi chi1; rewrite qualifE/= cfConjg1 cfConjg_char. Qed. Lemma cfConjg_irr y chi : chi \in irr H -> (chi ^ y)%CF \in irr H. Proof. by rewrite !irrEchar cfConjg_iso => /andP[/cfConjg_char->]. Qed. Definition conjg_Iirr i y := cfIirr ('chi[H]_i ^ y)%CF. Lemma conjg_IirrE i y : 'chi_(conjg_Iirr i y) = ('chi_i ^ y)%CF. Proof. by rewrite cfIirrE ?cfConjg_irr ?mem_irr. Qed. Lemma conjg_IirrK y : cancel (conjg_Iirr^~ y) (conjg_Iirr^~ y^-1%g). Proof. by move=> i; apply/irr_inj; rewrite !conjg_IirrE cfConjgK. Qed. Lemma conjg_IirrKV y : cancel (conjg_Iirr^~ y^-1%g) (conjg_Iirr^~ y). Proof. by rewrite -{2}[y]invgK; apply: conjg_IirrK. Qed. Lemma conjg_Iirr_inj y : injective (conjg_Iirr^~ y). Proof. exact: can_inj (conjg_IirrK y). Qed. Lemma conjg_Iirr_eq0 i y : (conjg_Iirr i y == 0) = (i == 0). Proof. by rewrite -!irr_eq1 conjg_IirrE cfConjg_eq1. Qed. Lemma conjg_Iirr0 x : conjg_Iirr 0 x = 0. Proof. by apply/eqP; rewrite conjg_Iirr_eq0. Qed. Lemma cfdot_irr_conjg i y : H <| G -> y \in G -> '['chi_i, 'chi_i ^ y]_H = (y \in 'I_G['chi_i])%:R. Proof. move=> nsHG Gy; rewrite -conjg_IirrE cfdot_irr -(inj_eq irr_inj) conjg_IirrE. by rewrite -{1}['chi_i]cfConjgJ1 cfConjg_eqE ?mulg1. Qed. Definition cfclass (A : {set gT}) (phi : 'CF(A)) (B : {set gT}) := [seq (phi ^ repr Tx)%CF | Tx in rcosets 'I_B[phi] B]. Local Notation "phi ^: G" := (cfclass phi G) : cfun_scope. Lemma size_cfclass i : size ('chi[H]_i ^: G)%CF = #|G : 'I_G['chi_i]|. Proof. by rewrite size_map -cardE. Qed. Lemma cfclassP (A : {group gT}) phi psi : reflect (exists2 y, y \in A & psi = phi ^ y)%CF (psi \in phi ^: A)%CF. Proof. apply: (iffP imageP) => [[_ /rcosetsP[y Ay ->] ->] | [y Ay ->]]. by case: repr_rcosetP => z /setIdP[Az _]; exists (z * y)%g; rewrite ?groupM. without loss nHy: y Ay / y \in 'N(H). have [nHy | /cfConjgEout->] := boolP (y \in 'N(H)); first exact. by move/(_ 1%g); rewrite !group1 !cfConjgJ1; apply. exists ('I_A[phi] :* y); first by rewrite -rcosetE imset_f. case: repr_rcosetP => z /setIP[_ /setIdP[nHz /eqP Tz]]. by rewrite cfConjgMnorm ?Tz. Qed. Lemma cfclassInorm phi : (phi ^: 'N_G(H) =i phi ^: G)%CF. Proof. move=> xi; apply/cfclassP/cfclassP=> [[x /setIP[Gx _] ->] | [x Gx ->]]. by exists x. have [Nx | /cfConjgEout-> //] := boolP (x \in 'N(H)). by exists x; first apply/setIP. by exists 1%g; rewrite ?group1 ?cfConjgJ1. Qed. Lemma cfclass_refl phi : phi \in (phi ^: G)%CF. Proof. by apply/cfclassP; exists 1%g => //; rewrite cfConjgJ1. Qed. Lemma cfclass_transr phi psi : (psi \in phi ^: G)%CF -> (phi ^: G =i psi ^: G)%CF. Proof. rewrite -cfclassInorm; case/cfclassP=> x Gx -> xi; rewrite -!cfclassInorm. have nHN: {subset 'N_G(H) <= 'N(H)} by apply/subsetP; apply: subsetIr. apply/cfclassP/cfclassP=> [[y Gy ->] | [y Gy ->]]. by exists (x^-1 * y)%g; rewrite -?cfConjgMnorm ?groupM ?groupV ?nHN // mulKVg. by exists (x * y)%g; rewrite -?cfConjgMnorm ?groupM ?nHN. Qed. Lemma cfclass_sym phi psi : (psi \in phi ^: G)%CF = (phi \in psi ^: G)%CF. Proof. by apply/idP/idP=> /cfclass_transr <-; apply: cfclass_refl. Qed. Lemma cfclass_uniq phi : H <| G -> uniq (phi ^: G)%CF. Proof. move=> nsHG; rewrite map_inj_in_uniq ?enum_uniq // => Ty Tz; rewrite !mem_enum. move=> {Ty}/rcosetsP[y Gy ->] {Tz}/rcosetsP[z Gz ->] /eqP. case: repr_rcosetP => u Iphi_u; case: repr_rcosetP => v Iphi_v. have [[Gu _] [Gv _]] := (setIdP Iphi_u, setIdP Iphi_v). rewrite cfConjg_eqE ?groupM // => /rcoset_eqP. by rewrite !rcosetM (rcoset_id Iphi_v) (rcoset_id Iphi_u). Qed. Lemma cfclass_invariant phi : G \subset 'I[phi] -> (phi ^: G)%CF = phi. Proof. move/setIidPl=> IGphi; rewrite /cfclass IGphi // rcosets_id. by rewrite /(image _ _) enum_set1 /= repr_group cfConjgJ1. Qed. Lemma cfclass1 : H <| G -> (1 ^: G)%CF = [:: 1 : 'CF(H)]. Proof. by move/normal_norm=> nHG; rewrite cfclass_invariant ?inertia1. Qed. Definition cfclass_Iirr (A : {set gT}) i := conjg_Iirr i @: A. Lemma cfclass_IirrE i j : (j \in cfclass_Iirr G i) = ('chi_j \in 'chi_i ^: G)%CF. Proof. apply/imsetP/cfclassP=> [[y Gy ->] | [y]]; exists y; rewrite ?conjg_IirrE //. by apply: irr_inj; rewrite conjg_IirrE. Qed. Lemma eq_cfclass_IirrE i j : (cfclass_Iirr G j == cfclass_Iirr G i) = (j \in cfclass_Iirr G i). Proof. apply/eqP/idP=> [<- | iGj]; first by rewrite cfclass_IirrE cfclass_refl. by apply/setP=> k; rewrite !cfclass_IirrE in iGj *; apply/esym/cfclass_transr. Qed. Lemma im_cfclass_Iirr i : H <| G -> perm_eq [seq 'chi_j | j in cfclass_Iirr G i] ('chi_i ^: G)%CF. Proof. move=> nsHG; have UchiG := cfclass_uniq 'chi_i nsHG. apply: uniq_perm; rewrite ?(map_inj_uniq irr_inj) ?enum_uniq // => phi. apply/imageP/idP=> [[j iGj ->] | /cfclassP[y]]; first by rewrite -cfclass_IirrE. by exists (conjg_Iirr i y); rewrite ?imset_f ?conjg_IirrE. Qed. Lemma card_cfclass_Iirr i : H <| G -> #|cfclass_Iirr G i| = #|G : 'I_G['chi_i]|. Proof. move=> nsHG; rewrite -size_cfclass -(perm_size (im_cfclass_Iirr i nsHG)). by rewrite size_map -cardE. Qed. Lemma reindex_cfclass R idx (op : Monoid.com_law idx) (F : 'CF(H) -> R) i : H <| G -> \big[op/idx]_(chi <- ('chi_i ^: G)%CF) F chi = \big[op/idx]_(j | 'chi_j \in ('chi_i ^: G)%CF) F 'chi_j. Proof. move/im_cfclass_Iirr/(perm_big _) <-; rewrite big_image /=. by apply: eq_bigl => j; rewrite cfclass_IirrE. Qed. Lemma cfResInd j: H <| G -> 'Res[H] ('Ind[G] 'chi_j) = #|H|%:R^-1 *: (\sum_(y in G) 'chi_j ^ y)%CF. Proof. case/andP=> [sHG /subsetP nHG]. rewrite (reindex_inj invg_inj); apply/cfun_inP=> x Hx. rewrite cfResE // cfIndE // ?cfunE ?sum_cfunE; congr (_ * _). by apply: eq_big => [y | y Gy]; rewrite ?cfConjgE ?groupV ?invgK ?nHG. Qed. (* This is Isaacs, Theorem (6.2) *) Lemma Clifford_Res_sum_cfclass i j : H <| G -> j \in irr_constt ('Res[H, G] 'chi_i) -> 'Res[H] 'chi_i = '['Res[H] 'chi_i, 'chi_j] *: (\sum_(chi <- ('chi_j ^: G)%CF) chi). Proof. move=> nsHG chiHj; have [sHG /subsetP nHG] := andP nsHG. rewrite reindex_cfclass //= big_mkcond. rewrite {1}['Res _]cfun_sum_cfdot linear_sum /=; apply: eq_bigr => k _. have [[y Gy ->] | ] := altP (cfclassP _ _ _); first by rewrite cfdot_Res_conjg. apply: contraNeq; rewrite scaler0 scaler_eq0 orbC => /norP[_ chiHk]. have{chiHk chiHj}: '['Res[H] ('Ind[G] 'chi_j), 'chi_k] != 0. rewrite !inE !cfdot_Res_l in chiHj chiHk *. apply: contraNneq chiHk; rewrite cfdot_sum_irr => /psumr_eq0P/(_ i isT)/eqP. rewrite -cfdotC cfdotC mulf_eq0 conjC_eq0 (negbTE chiHj) /= => -> // i1. by rewrite -cfdotC natr_ge0 // rpredM ?Cnat_cfdot_char ?cfInd_char ?irr_char. rewrite cfResInd // cfdotZl mulf_eq0 cfdot_suml => /norP[_]. apply: contraR => chiGk'j; rewrite big1 // => x Gx; apply: contraNeq chiGk'j. rewrite -conjg_IirrE cfdot_irr pnatr_eq0; case: (_ =P k) => // <- _. by rewrite conjg_IirrE; apply/cfclassP; exists x. Qed. Lemma cfRes_Ind_invariant psi : H <| G -> G \subset 'I[psi] -> 'Res ('Ind[G, H] psi) = #|G : H|%:R *: psi. Proof. case/andP=> sHG _ /subsetP IGpsi; apply/cfun_inP=> x Hx. rewrite cfResE ?cfIndE ?natf_indexg // cfunE -mulrA mulrCA; congr (_ * _). by rewrite mulr_natl -sumr_const; apply: eq_bigr => y /IGpsi/inertia_valJ->. Qed. (* This is Isaacs, Corollary (6.7). *) Corollary constt0_Res_cfker i : H <| G -> 0 \in irr_constt ('Res[H] 'chi[G]_i) -> H \subset cfker 'chi[G]_i. Proof. move=> nsHG /(Clifford_Res_sum_cfclass nsHG); have [sHG nHG] := andP nsHG. rewrite irr0 cfdot_Res_l cfclass1 // big_seq1 cfInd_cfun1 //. rewrite cfdotZr conjC_nat => def_chiH. apply/subsetP=> x Hx; rewrite cfkerEirr inE -!(cfResE _ sHG) //. by rewrite def_chiH !cfunE cfun11 cfun1E Hx. Qed. (* This is Isaacs, Lemma (6.8). *) Lemma dvdn_constt_Res1_irr1 i j : H <| G -> j \in irr_constt ('Res[H, G] 'chi_i) -> exists n, 'chi_i 1%g = n%:R * 'chi_j 1%g. Proof. move=> nsHG chiHj; have [sHG nHG] := andP nsHG; rewrite -(cfResE _ sHG) //. rewrite {1}(Clifford_Res_sum_cfclass nsHG chiHj) cfunE sum_cfunE. have /natrP[n ->]: '['Res[H] 'chi_i, 'chi_j] \in Num.nat. by rewrite Cnat_cfdot_char ?cfRes_char ?irr_char. exists (n * size ('chi_j ^: G)%CF)%N; rewrite natrM -mulrA; congr (_ * _). rewrite mulr_natl -[size _]card_ord big_tnth -sumr_const; apply: eq_bigr => k _. by have /cfclassP[y Gy ->]:= mem_tnth k (in_tuple _); rewrite cfConjg1. Qed. Lemma cfclass_Ind phi psi : H <| G -> psi \in (phi ^: G)%CF -> 'Ind[G] phi = 'Ind[G] psi. Proof. move=> nsHG /cfclassP[y Gy ->]; have [sHG /subsetP nHG] := andP nsHG. apply/cfun_inP=> x Hx; rewrite !cfIndE //; congr (_ * _). rewrite (reindex_acts 'R _ (groupVr Gy)) ?astabsR //=. by apply: eq_bigr => z Gz; rewrite conjgM cfConjgE ?nHG. Qed. End Inertia. Arguments inertia {gT B%_g} phi%_CF. Arguments cfclass {gT A%_g} phi%_CF B%_g. Arguments conjg_Iirr_inj {gT H} y [i1 i2] : rename. Notation "''I[' phi ] " := (inertia phi) : group_scope. Notation "''I[' phi ] " := (inertia_group phi) : Group_scope. Notation "''I_' G [ phi ] " := (G%g :&: 'I[phi]) : group_scope. Notation "''I_' G [ phi ] " := (G :&: 'I[phi])%G : Group_scope. Notation "phi ^: G" := (cfclass phi G) : cfun_scope. Section ConjRestrict. Variables (gT : finGroupType) (G H K : {group gT}). Lemma cfConjgRes_norm phi y : y \in 'N(K) -> y \in 'N(H) -> ('Res[K, H] phi ^ y)%CF = 'Res (phi ^ y)%CF. Proof. move=> nKy nHy; have [sKH | not_sKH] := boolP (K \subset H); last first. by rewrite !cfResEout // rmorph_alg cfConjg1. by apply/cfun_inP=> x Kx; rewrite !(cfConjgE, cfResE) ?memJ_norm ?groupV. Qed. Lemma cfConjgRes phi y : H <| G -> K <| G -> y \in G -> ('Res[K, H] phi ^ y)%CF = 'Res (phi ^ y)%CF. Proof. move=> /andP[_ nHG] /andP[_ nKG] Gy. by rewrite cfConjgRes_norm ?(subsetP nHG) ?(subsetP nKG). Qed. Lemma sub_inertia_Res phi : G \subset 'N(K) -> 'I_G[phi] \subset 'I_G['Res[K, H] phi]. Proof. move=> nKG; apply/subsetP=> y /setIP[Gy /setIdP[nHy /eqP Iphi_y]]. by rewrite 2!inE Gy cfConjgRes_norm ?(subsetP nKG) ?Iphi_y /=. Qed. Lemma cfConjgInd_norm phi y : y \in 'N(K) -> y \in 'N(H) -> ('Ind[H, K] phi ^ y)%CF = 'Ind (phi ^ y)%CF. Proof. move=> nKy nHy; have [sKH | not_sKH] := boolP (K \subset H). by rewrite !cfConjgEin (cfIndIsom (norm_conj_isom nHy)). rewrite !cfIndEout // linearZ -(cfConjg_iso y) rmorph1 /=; congr (_ *: _). by rewrite cfConjg_cfuni ?norm1 ?inE. Qed. Lemma cfConjgInd phi y : H <| G -> K <| G -> y \in G -> ('Ind[H, K] phi ^ y)%CF = 'Ind (phi ^ y)%CF. Proof. move=> /andP[_ nHG] /andP[_ nKG] Gy. by rewrite cfConjgInd_norm ?(subsetP nHG) ?(subsetP nKG). Qed. Lemma sub_inertia_Ind phi : G \subset 'N(H) -> 'I_G[phi] \subset 'I_G['Ind[H, K] phi]. Proof. move=> nHG; apply/subsetP=> y /setIP[Gy /setIdP[nKy /eqP Iphi_y]]. by rewrite 2!inE Gy cfConjgInd_norm ?(subsetP nHG) ?Iphi_y /=. Qed. End ConjRestrict. Section MoreInertia. Variables (gT : finGroupType) (G H : {group gT}) (i : Iirr H). Let T := 'I_G['chi_i]. Lemma inertia_id : 'I_T['chi_i] = T. Proof. by rewrite -setIA setIid. Qed. Lemma cfclass_inertia : ('chi[H]_i ^: T)%CF = [:: 'chi_i]. Proof. rewrite /cfclass inertia_id rcosets_id /(image _ _) enum_set1 /=. by rewrite repr_group cfConjgJ1. Qed. End MoreInertia. Section ConjMorph. Variables (aT rT : finGroupType) (D G H : {group aT}) (f : {morphism D >-> rT}). Lemma cfConjgMorph (phi : 'CF(f @* H)) y : y \in D -> y \in 'N(H) -> (cfMorph phi ^ y)%CF = cfMorph (phi ^ f y). Proof. move=> Dy nHy; have [sHD | not_sHD] := boolP (H \subset D); last first. by rewrite !cfMorphEout // rmorph_alg cfConjg1. apply/cfun_inP=> x Gx; rewrite !(cfConjgE, cfMorphE) ?memJ_norm ?groupV //. by rewrite morphJ ?morphV ?groupV // (subsetP sHD). by rewrite (subsetP (morphim_norm _ _)) ?mem_morphim. Qed. Lemma inertia_morph_pre (phi : 'CF(f @* H)) : H <| G -> G \subset D -> 'I_G[cfMorph phi] = G :&: f @*^-1 'I_(f @* G)[phi]. Proof. case/andP=> sHG nHG sGD; have sHD := subset_trans sHG sGD. apply/setP=> y; rewrite !in_setI; apply: andb_id2l => Gy. have [Dy nHy] := (subsetP sGD y Gy, subsetP nHG y Gy). rewrite Dy inE nHy 4!inE mem_morphim // -morphimJ ?(normP nHy) // subxx /=. rewrite cfConjgMorph //; apply/eqP/eqP=> [Iphi_y | -> //]. by apply/cfun_inP=> _ /morphimP[x Dx Hx ->]; rewrite -!cfMorphE ?Iphi_y. Qed. Lemma inertia_morph_im (phi : 'CF(f @* H)) : H <| G -> G \subset D -> f @* 'I_G[cfMorph phi] = 'I_(f @* G)[phi]. Proof. move=> nsHG sGD; rewrite inertia_morph_pre // morphim_setIpre. by rewrite (setIidPr _) ?Inertia_sub. Qed. Variables (R S : {group rT}). Variables (g : {morphism G >-> rT}) (h : {morphism H >-> rT}). Hypotheses (isoG : isom G R g) (isoH : isom H S h). Hypotheses (eq_hg : {in H, h =1 g}) (sHG : H \subset G). (* This does not depend on the (isoG : isom G R g) assumption. *) Lemma cfConjgIsom phi y : y \in G -> y \in 'N(H) -> (cfIsom isoH phi ^ g y)%CF = cfIsom isoH (phi ^ y). Proof. move=> Gy nHy; have [_ defS] := isomP isoH. rewrite morphimEdom (eq_in_imset eq_hg) -morphimEsub // in defS. apply/cfun_inP=> gx; rewrite -{1}defS => /morphimP[x Gx Hx ->] {gx}. rewrite cfConjgE; last by rewrite -defS inE -morphimJ ?(normP nHy). by rewrite -morphV -?morphJ -?eq_hg ?cfIsomE ?cfConjgE ?memJ_norm ?groupV. Qed. Lemma inertia_isom phi : 'I_R[cfIsom isoH phi] = g @* 'I_G[phi]. Proof. have [[_ defS] [injg <-]] := (isomP isoH, isomP isoG). rewrite morphimEdom (eq_in_imset eq_hg) -morphimEsub // in defS. rewrite /inertia !setIdE morphimIdom setIA -{1}defS -injm_norm ?injmI //. apply/setP=> gy /[!inE]; apply: andb_id2l => /morphimP[y Gy nHy ->] {gy}. rewrite cfConjgIsom // -sub1set -morphim_set1 // injmSK ?sub1set //= inE. apply/eqP/eqP=> [Iphi_y | -> //]. by apply/cfun_inP=> x Hx; rewrite -!(cfIsomE isoH) ?Iphi_y. Qed. End ConjMorph. Section ConjQuotient. Variables gT : finGroupType. Implicit Types G H K : {group gT}. Lemma cfConjgMod_norm H K (phi : 'CF(H / K)) y : y \in 'N(K) -> y \in 'N(H) -> ((phi %% K) ^ y)%CF = (phi ^ coset K y %% K)%CF. Proof. exact: cfConjgMorph. Qed. Lemma cfConjgMod G H K (phi : 'CF(H / K)) y : H <| G -> K <| G -> y \in G -> ((phi %% K) ^ y)%CF = (phi ^ coset K y %% K)%CF. Proof. move=> /andP[_ nHG] /andP[_ nKG] Gy. by rewrite cfConjgMod_norm ?(subsetP nHG) ?(subsetP nKG). Qed. Lemma cfConjgQuo_norm H K (phi : 'CF(H)) y : y \in 'N(K) -> y \in 'N(H) -> ((phi / K) ^ coset K y)%CF = (phi ^ y / K)%CF. Proof. move=> nKy nHy; have keryK: (K \subset cfker (phi ^ y)) = (K \subset cfker phi). by rewrite cfker_conjg // -{1}(normP nKy) conjSg. have [kerK | not_kerK] := boolP (K \subset cfker phi); last first. by rewrite !cfQuoEout ?rmorph_alg ?cfConjg1 ?keryK. apply/cfun_inP=> _ /morphimP[x nKx Hx ->]. have nHyb: coset K y \in 'N(H / K) by rewrite inE -morphimJ ?(normP nHy). rewrite !(cfConjgE, cfQuoEnorm) ?keryK // ?in_setI ?Hx //. rewrite -morphV -?morphJ ?groupV // cfQuoEnorm //. by rewrite inE memJ_norm ?Hx ?groupJ ?groupV. Qed. Lemma cfConjgQuo G H K (phi : 'CF(H)) y : H <| G -> K <| G -> y \in G -> ((phi / K) ^ coset K y)%CF = (phi ^ y / K)%CF. Proof. move=> /andP[_ nHG] /andP[_ nKG] Gy. by rewrite cfConjgQuo_norm ?(subsetP nHG) ?(subsetP nKG). Qed. Lemma inertia_mod_pre G H K (phi : 'CF(H / K)) : H <| G -> K <| G -> 'I_G[phi %% K] = G :&: coset K @*^-1 'I_(G / K)[phi]. Proof. by move=> nsHG /andP[_]; apply: inertia_morph_pre. Qed. Lemma inertia_mod_quo G H K (phi : 'CF(H / K)) : H <| G -> K <| G -> ('I_G[phi %% K] / K)%g = 'I_(G / K)[phi]. Proof. by move=> nsHG /andP[_]; apply: inertia_morph_im. Qed. Lemma inertia_quo G H K (phi : 'CF(H)) : H <| G -> K <| G -> K \subset cfker phi -> 'I_(G / K)[phi / K] = ('I_G[phi] / K)%g. Proof. move=> nsHG nsKG kerK; rewrite -inertia_mod_quo ?cfQuoK //. by rewrite (normalS _ (normal_sub nsHG)) // (subset_trans _ (cfker_sub phi)). Qed. End ConjQuotient. Section InertiaSdprod. Variables (gT : finGroupType) (K H G : {group gT}). Hypothesis defG : K ><| H = G. Lemma cfConjgSdprod phi y : y \in 'N(K) -> y \in 'N(H) -> (cfSdprod defG phi ^ y = cfSdprod defG (phi ^ y))%CF. Proof. move=> nKy nHy. have nGy: y \in 'N(G) by rewrite -sub1set -(sdprodW defG) normsM ?sub1set. rewrite -{2}[phi](cfSdprodK defG) cfConjgRes_norm // cfRes_sdprodK //. by rewrite cfker_conjg // -{1}(normP nKy) conjSg cfker_sdprod. Qed. Lemma inertia_sdprod (L : {group gT}) phi : L \subset 'N(K) -> L \subset 'N(H) -> 'I_L[cfSdprod defG phi] = 'I_L[phi]. Proof. move=> nKL nHL; have nGL: L \subset 'N(G) by rewrite -(sdprodW defG) normsM. apply/setP=> z; rewrite !in_setI ![z \in 'I[_]]inE; apply: andb_id2l => Lz. rewrite cfConjgSdprod ?(subsetP nKL) ?(subsetP nHL) ?(subsetP nGL) //=. by rewrite (can_eq (cfSdprodK defG)). Qed. End InertiaSdprod. Section InertiaDprod. Variables (gT : finGroupType) (G K H : {group gT}). Implicit Type L : {group gT}. Hypothesis KxH : K \x H = G. Lemma cfConjgDprodl phi y : y \in 'N(K) -> y \in 'N(H) -> (cfDprodl KxH phi ^ y = cfDprodl KxH (phi ^ y))%CF. Proof. by move=> nKy nHy; apply: cfConjgSdprod. Qed. Lemma cfConjgDprodr psi y : y \in 'N(K) -> y \in 'N(H) -> (cfDprodr KxH psi ^ y = cfDprodr KxH (psi ^ y))%CF. Proof. by move=> nKy nHy; apply: cfConjgSdprod. Qed. Lemma cfConjgDprod phi psi y : y \in 'N(K) -> y \in 'N(H) -> (cfDprod KxH phi psi ^ y = cfDprod KxH (phi ^ y) (psi ^ y))%CF. Proof. by move=> nKy nHy; rewrite rmorphM /= cfConjgDprodl ?cfConjgDprodr. Qed. Lemma inertia_dprodl L phi : L \subset 'N(K) -> L \subset 'N(H) -> 'I_L[cfDprodl KxH phi] = 'I_L[phi]. Proof. by move=> nKL nHL; apply: inertia_sdprod. Qed. Lemma inertia_dprodr L psi : L \subset 'N(K) -> L \subset 'N(H) -> 'I_L[cfDprodr KxH psi] = 'I_L[psi]. Proof. by move=> nKL nHL; apply: inertia_sdprod. Qed. Lemma inertia_dprod L (phi : 'CF(K)) (psi : 'CF(H)) : L \subset 'N(K) -> L \subset 'N(H) -> phi 1%g != 0 -> psi 1%g != 0 -> 'I_L[cfDprod KxH phi psi] = 'I_L[phi] :&: 'I_L[psi]. Proof. move=> nKL nHL nz_phi nz_psi; apply/eqP; rewrite eqEsubset subsetI. rewrite -{1}(inertia_scale_nz psi nz_phi) -{1}(inertia_scale_nz phi nz_psi). rewrite -(cfDprod_Resl KxH) -(cfDprod_Resr KxH) !sub_inertia_Res //=. by rewrite -inertia_dprodl -?inertia_dprodr // -setIIr setIS ?inertia_mul. Qed. Lemma inertia_dprod_irr L i j : L \subset 'N(K) -> L \subset 'N(H) -> 'I_L[cfDprod KxH 'chi_i 'chi_j] = 'I_L['chi_i] :&: 'I_L['chi_j]. Proof. by move=> nKL nHL; rewrite inertia_dprod ?irr1_neq0. Qed. End InertiaDprod. Section InertiaBigdprod. Variables (gT : finGroupType) (I : finType) (P : pred I). Variables (A : I -> {group gT}) (G : {group gT}). Implicit Type L : {group gT}. Hypothesis defG : \big[dprod/1%g]_(i | P i) A i = G. Section ConjBig. Variable y : gT. Hypothesis nAy: forall i, P i -> y \in 'N(A i). Lemma cfConjgBigdprodi i (phi : 'CF(A i)) : (cfBigdprodi defG phi ^ y = cfBigdprodi defG (phi ^ y))%CF. Proof. rewrite cfConjgDprodl; try by case: ifP => [/nAy// | _]; rewrite norm1 inE. congr (cfDprodl _ _); case: ifP => [Pi | _]. by rewrite cfConjgRes_norm ?nAy. by apply/cfun_inP=> _ /set1P->; rewrite !(cfRes1, cfConjg1). rewrite -sub1set norms_gen ?norms_bigcup // sub1set. by apply/bigcapP=> j /andP[/nAy]. Qed. Lemma cfConjgBigdprod phi : (cfBigdprod defG phi ^ y = cfBigdprod defG (fun i => phi i ^ y))%CF. Proof. by rewrite rmorph_prod /=; apply: eq_bigr => i _; apply: cfConjgBigdprodi. Qed. End ConjBig. Section InertiaBig. Variable L : {group gT}. Hypothesis nAL : forall i, P i -> L \subset 'N(A i). Lemma inertia_bigdprodi i (phi : 'CF(A i)) : P i -> 'I_L[cfBigdprodi defG phi] = 'I_L[phi]. Proof. move=> Pi; rewrite inertia_dprodl ?Pi ?cfRes_id ?nAL //. by apply/norms_gen/norms_bigcup/bigcapsP=> j /andP[/nAL]. Qed. Lemma inertia_bigdprod phi (Phi := cfBigdprod defG phi) : Phi 1%g != 0 -> 'I_L[Phi] = L :&: \bigcap_(i | P i) 'I_L[phi i]. Proof. move=> nz_Phi; apply/eqP; rewrite eqEsubset; apply/andP; split. rewrite subsetI Inertia_sub; apply/bigcapsP=> i Pi. have [] := cfBigdprodK nz_Phi Pi; move: (_ / _) => a nz_a <-. by rewrite inertia_scale_nz ?sub_inertia_Res //= ?nAL. rewrite subsetI subsetIl; apply: subset_trans (inertia_prod _ _ _). apply: setISS. by rewrite -(bigdprodWY defG) norms_gen ?norms_bigcup //; apply/bigcapsP. apply/bigcapsP=> i Pi; rewrite (bigcap_min i) //. by rewrite -inertia_bigdprodi ?subsetIr. Qed. Lemma inertia_bigdprod_irr Iphi (phi := fun i => 'chi_(Iphi i)) : 'I_L[cfBigdprod defG phi] = L :&: \bigcap_(i | P i) 'I_L[phi i]. Proof. rewrite inertia_bigdprod // -[cfBigdprod _ _]cfIirrE ?irr1_neq0 //. by apply: cfBigdprod_irr => i _; apply: mem_irr. Qed. End InertiaBig. End InertiaBigdprod. Section ConsttInertiaBijection. Variables (gT : finGroupType) (H G : {group gT}) (t : Iirr H). Hypothesis nsHG : H <| G. Local Notation theta := 'chi_t. Local Notation T := 'I_G[theta]%G. Local Notation "` 'T'" := 'I_(gval G)[theta] (format "` 'T'") : group_scope. Let calA := irr_constt ('Ind[T] theta). Let calB := irr_constt ('Ind[G] theta). Local Notation AtoB := (Ind_Iirr G). (* This is Isaacs, Theorem (6.11). *) Theorem constt_Inertia_bijection : [/\ (*a*) {in calA, forall s, 'Ind[G] 'chi_s \in irr G}, (*b*) {in calA &, injective (Ind_Iirr G)}, Ind_Iirr G @: calA =i calB, (*c*) {in calA, forall s (psi := 'chi_s) (chi := 'Ind[G] psi), [predI irr_constt ('Res chi) & calA] =i pred1 s} & (*d*) {in calA, forall s (psi := 'chi_s) (chi := 'Ind[G] psi), '['Res psi, theta] = '['Res chi, theta]}]. Proof. have [sHG sTG]: H \subset G /\ T \subset G by rewrite subsetIl normal_sub. have nsHT : H <| T := normal_Inertia theta sHG; have sHT := normal_sub nsHT. have AtoB_P s (psi := 'chi_s) (chi := 'Ind[G] psi): s \in calA -> [/\ chi \in irr G, AtoB s \in calB & '['Res psi, theta] = '['Res chi, theta]]. - rewrite constt_Ind_Res => sHt; have [r sGr] := constt_cfInd_irr s sTG. rewrite constt_Ind_Res. have rTs: s \in irr_constt ('Res[T] 'chi_r) by rewrite -constt_Ind_Res. have NrT: 'Res[T] 'chi_r \is a character by rewrite cfRes_char ?irr_char. have rHt: t \in irr_constt ('Res[H] 'chi_r). by have:= constt_Res_trans NrT rTs sHt; rewrite cfResRes. pose e := '['Res[H] 'chi_r, theta]; set f := '['Res[H] psi, theta]. have DrH: 'Res[H] 'chi_r = e *: \sum_(xi <- (theta ^: G)%CF) xi. exact: Clifford_Res_sum_cfclass. have DpsiH: 'Res[H] psi = f *: theta. rewrite (Clifford_Res_sum_cfclass nsHT sHt). by rewrite cfclass_invariant ?subsetIr ?big_seq1. have ub_chi_r: 'chi_r 1%g <= chi 1%g ?= iff ('chi_r == chi). have Nchi: chi \is a character by rewrite cfInd_char ?irr_char. have [chi1 Nchi1->] := constt_charP _ Nchi sGr. rewrite addrC cfunE -leifBLR subrr eq_sym -subr_eq0 addrK. by split; rewrite ?char1_ge0 // eq_sym char1_eq0. have lb_chi_r: chi 1%g <= 'chi_r 1%g ?= iff (f == e). rewrite cfInd1 // -(cfRes1 H) DpsiH -(cfRes1 H 'chi_r) DrH !cfunE sum_cfunE. rewrite (eq_big_seq (fun _ => theta 1%g)) => [|i]; last first. by case/cfclassP=> y _ ->; rewrite cfConjg1. rewrite reindex_cfclass //= sumr_const -(eq_card (cfclass_IirrE _ _)). rewrite mulr_natl mulrnAr card_cfclass_Iirr //. rewrite (mono_leif (ler_pMn2r (indexg_gt0 G T))). rewrite (mono_leif (ler_pM2r (irr1_gt0 t))); apply: leif_eq. by rewrite /e -(cfResRes _ sHT) ?cfdot_Res_ge_constt. have [_ /esym] := leif_trans ub_chi_r lb_chi_r; rewrite eqxx. by case/andP=> /eqP Dchi /eqP->; rewrite cfIirrE -/chi -?Dchi ?mem_irr. have part_c: {in calA, forall s (chi := 'Ind[G] 'chi_s), [predI irr_constt ('Res[T] chi) & calA] =i pred1 s}. - move=> s As chi s1; have [irr_chi _ /eqP Dchi_theta] := AtoB_P s As. have chiTs: s \in irr_constt ('Res[T] chi). by rewrite irr_consttE cfdot_Res_l irrWnorm ?oner_eq0. apply/andP/eqP=> [[/= chiTs1 As1] | -> //]. apply: contraTeq Dchi_theta => s's1; rewrite lt_eqF // -/chi. have [|phi Nphi DchiT] := constt_charP _ _ chiTs. by rewrite cfRes_char ?cfInd_char ?irr_char. have [|phi1 Nphi1 Dphi] := constt_charP s1 Nphi _. rewrite irr_consttE -(canLR (addKr _) DchiT) addrC cfdotBl cfdot_irr. by rewrite mulrb ifN_eqC ?subr0. rewrite -(cfResRes chi sHT sTG) DchiT Dphi !rmorphD !cfdotDl /=. rewrite -ltrBDl subrr ltr_wpDr ?lt_def //; rewrite natr_ge0 ?Cnat_cfdot_char ?cfRes_char ?irr_char //. by rewrite andbT -irr_consttE -constt_Ind_Res. do [split=> //; try by move=> s /AtoB_P[]] => [s1 s2 As1 As2 | r]. have [[irr_s1G _ _] [irr_s2G _ _]] := (AtoB_P _ As1, AtoB_P _ As2). move/(congr1 (tnth (irr G))); rewrite !cfIirrE // => eq_s12_G. apply/eqP; rewrite -[_ == _]part_c // inE /= As1 -eq_s12_G. by rewrite -As1 [_ && _]part_c // inE /=. apply/imsetP/idP=> [[s /AtoB_P[_ BsG _] -> //] | Br]. have /exists_inP[s rTs As]: [exists s in irr_constt ('Res 'chi_r), s \in calA]. rewrite -negb_forall_in; apply: contra Br => /eqfun_inP => o_tT_rT. rewrite -(cfIndInd _ sTG sHT) -cfdot_Res_r ['Res _]cfun_sum_constt. by rewrite cfdot_sumr big1 // => i rTi; rewrite cfdotZr o_tT_rT ?mulr0. exists s => //; have [/irrP[r1 DsG] _ _] := AtoB_P s As. by apply/eqP; rewrite /AtoB -constt_Ind_Res DsG irrK constt_irr in rTs *. Qed. End ConsttInertiaBijection. Section ExtendInvariantIrr. Variable gT : finGroupType. Implicit Types G H K L M N : {group gT}. Section ConsttIndExtendible. Variables (G N : {group gT}) (t : Iirr N) (c : Iirr G). Let theta := 'chi_t. Let chi := 'chi_c. Definition mul_Iirr b := cfIirr ('chi_b * chi). Definition mul_mod_Iirr (b : Iirr (G / N)) := mul_Iirr (mod_Iirr b). Hypotheses (nsNG : N <| G) (cNt : 'Res[N] chi = theta). Let sNG : N \subset G. Proof. exact: normal_sub. Qed. Let nNG : G \subset 'N(N). Proof. exact: normal_norm. Qed. Lemma extendible_irr_invariant : G \subset 'I[theta]. Proof. apply/subsetP=> y Gy; have nNy := subsetP nNG y Gy. rewrite inE nNy; apply/eqP/cfun_inP=> x Nx; rewrite cfConjgE // -cNt. by rewrite !cfResE ?memJ_norm ?cfunJ ?groupV. Qed. Let IGtheta := extendible_irr_invariant. (* This is Isaacs, Theorem (6.16) *) Theorem constt_Ind_mul_ext f (phi := 'chi_f) (psi := phi * theta) : G \subset 'I[phi] -> psi \in irr N -> let calS := irr_constt ('Ind phi) in [/\ {in calS, forall b, 'chi_b * chi \in irr G}, {in calS &, injective mul_Iirr}, irr_constt ('Ind psi) =i [seq mul_Iirr b | b in calS] & 'Ind psi = \sum_(b in calS) '['Ind phi, 'chi_b] *: 'chi_(mul_Iirr b)]. Proof. move=> IGphi irr_psi calS. have IGpsi: G \subset 'I[psi]. by rewrite (subset_trans _ (inertia_mul _ _)) // subsetI IGphi. pose e b := '['Ind[G] phi, 'chi_b]; pose d b g := '['chi_b * chi, 'chi_g * chi]. have Ne b: e b \in Num.nat by rewrite Cnat_cfdot_char ?cfInd_char ?irr_char. have egt0 b: b \in calS -> e b > 0 by rewrite natr_gt0. have DphiG: 'Ind phi = \sum_(b in calS) e b *: 'chi_b := cfun_sum_constt _. have DpsiG: 'Ind psi = \sum_(b in calS) e b *: 'chi_b * chi. by rewrite /psi -cNt cfIndM // DphiG mulr_suml. pose d_delta := [forall b in calS, forall g in calS, d b g == (b == g)%:R]. have charMchi b: 'chi_b * chi \is a character by rewrite rpredM ?irr_char. have [_]: '['Ind[G] phi] <= '['Ind[G] psi] ?= iff d_delta. pose sum_delta := \sum_(b in calS) e b * \sum_(g in calS) e g * (b == g)%:R. pose sum_d := \sum_(b in calS) e b * \sum_(g in calS) e g * d b g. have ->: '['Ind[G] phi] = sum_delta. rewrite DphiG cfdot_suml; apply: eq_bigr => b _; rewrite cfdotZl cfdot_sumr. by congr (_ * _); apply: eq_bigr => g; rewrite cfdotZr cfdot_irr conj_natr. have ->: '['Ind[G] psi] = sum_d. rewrite DpsiG cfdot_suml; apply: eq_bigr => b _. rewrite -scalerAl cfdotZl cfdot_sumr; congr (_ * _). by apply: eq_bigr => g _; rewrite -scalerAl cfdotZr conj_natr. have eMmono := mono_leif (ler_pM2l (egt0 _ _)). apply: leif_sum => b /eMmono->; apply: leif_sum => g /eMmono->. split; last exact: eq_sym. have /natrP[n Dd]: d b g \in Num.nat by rewrite Cnat_cfdot_char. have [Db | _] := eqP; rewrite Dd leC_nat // -ltC_nat -Dd Db cfnorm_gt0. by rewrite -char1_eq0 // cfunE mulf_neq0 ?irr1_neq0. rewrite -!cfdot_Res_l ?cfRes_Ind_invariant // !cfdotZl cfnorm_irr irrWnorm //. rewrite eqxx => /esym/forall_inP/(_ _ _)/eqfun_inP; rewrite /d /= => Dd. have irrMchi: {in calS, forall b, 'chi_b * chi \in irr G}. by move=> b Sb; rewrite /= irrEchar charMchi Dd ?eqxx. have injMchi: {in calS &, injective mul_Iirr}. move=> b g Sb Sg /(congr1 (fun s => '['chi_s, 'chi_(mul_Iirr g)]))/eqP. by rewrite cfnorm_irr !cfIirrE ?irrMchi ?Dd // pnatr_eq1; case: (b =P g). have{DpsiG} ->: 'Ind psi = \sum_(b in calS) e b *: 'chi_(mul_Iirr b). by rewrite DpsiG; apply: eq_bigr => b Sb; rewrite -scalerAl cfIirrE ?irrMchi. split=> // i; rewrite irr_consttE cfdot_suml; apply/idP/idP=> [|/imageP[b Sb ->]]. apply: contraR => N'i; rewrite big1 // => b Sb. rewrite cfdotZl cfdot_irr mulrb ifN_eqC ?mulr0 //. by apply: contraNneq N'i => ->; apply: image_f. rewrite gt_eqF // (bigD1 b) //= cfdotZl cfnorm_irr mulr1 ltr_wpDr ?egt0 //. apply: sumr_ge0 => g /andP[Sg _]; rewrite cfdotZl cfdot_irr. by rewrite mulr_ge0 ?ler0n ?natr_ge0. Qed. (* This is Isaacs, Corollary (6.17) (due to Gallagher). *) Corollary constt_Ind_ext : [/\ forall b : Iirr (G / N), 'chi_(mod_Iirr b) * chi \in irr G, injective mul_mod_Iirr, irr_constt ('Ind theta) =i codom mul_mod_Iirr & 'Ind theta = \sum_b 'chi_b 1%g *: 'chi_(mul_mod_Iirr b)]. Proof. have IHchi0: G \subset 'I['chi[N]_0] by rewrite inertia_irr0. have [] := constt_Ind_mul_ext IHchi0; rewrite irr0 ?mul1r ?mem_irr //. set psiG := 'Ind 1 => irrMchi injMchi constt_theta {2}->. have dot_psiG b: '[psiG, 'chi_(mod_Iirr b)] = 'chi[G / N]_b 1%g. rewrite mod_IirrE // -cfdot_Res_r cfRes_sub_ker ?cfker_mod //. by rewrite cfdotZr cfnorm1 mulr1 conj_natr ?cfMod1 ?Cnat_irr1. have mem_psiG (b : Iirr (G / N)): mod_Iirr b \in irr_constt psiG. by rewrite irr_consttE dot_psiG irr1_neq0. have constt_psiG b: (b \in irr_constt psiG) = (N \subset cfker 'chi_b). apply/idP/idP=> [psiGb | /quo_IirrK <- //]. by rewrite constt0_Res_cfker // -constt_Ind_Res irr0. split=> [b | b g /injMchi/(can_inj (mod_IirrK nsNG))-> // | b0 | ]. - exact: irrMchi. - rewrite constt_theta. apply/imageP/imageP=> [][b psiGb ->]; last by exists (mod_Iirr b). by exists (quo_Iirr N b) => //; rewrite /mul_mod_Iirr quo_IirrK -?constt_psiG. rewrite (reindex_onto _ _ (in1W (mod_IirrK nsNG))) /=. apply/esym/eq_big => b; first by rewrite constt_psiG quo_IirrKeq. by rewrite -dot_psiG /mul_mod_Iirr => /eqP->. Qed. End ConsttIndExtendible. (* This is Isaacs, Theorem (6.19). *) Theorem invariant_chief_irr_cases G K L s (theta := 'chi[K]_s) : chief_factor G L K -> abelian (K / L) -> G \subset 'I[theta] -> let t := #|K : L| in [\/ 'Res[L] theta \in irr L, exists2 e, exists p, 'Res[L] theta = e%:R *: 'chi_p & (e ^ 2)%N = t | exists2 p, injective p & 'Res[L] theta = \sum_(i < t) 'chi_(p i)]. Proof. case/andP=> /maxgroupP[/andP[ltLK nLG] maxL] nsKG abKbar IGtheta t. have [sKG nKG] := andP nsKG; have sLG := subset_trans (proper_sub ltLK) sKG. have nsLG: L <| G by apply/andP. have nsLK := normalS (proper_sub ltLK) sKG nsLG; have [sLK nLK] := andP nsLK. have [p0 sLp0] := constt_cfRes_irr L s; rewrite -/theta in sLp0. pose phi := 'chi_p0; pose T := 'I_G[phi]. have sTG: T \subset G := subsetIl G _. have /eqP mulKT: (K * T)%g == G. rewrite eqEcard mulG_subG sKG sTG -LagrangeMr -indexgI -(Lagrange sTG) /= -/T. rewrite mulnC leq_mul // setIA (setIidPl sKG) -!size_cfclass // -/phi. rewrite uniq_leq_size ?cfclass_uniq // => _ /cfclassP[x Gx ->]. have: conjg_Iirr p0 x \in irr_constt ('Res theta). have /inertiaJ <-: x \in 'I[theta] := subsetP IGtheta x Gx. by rewrite -(cfConjgRes _ nsKG) // irr_consttE conjg_IirrE // cfConjg_iso. apply: contraR; rewrite -conjg_IirrE // => not_sLp0x. rewrite (Clifford_Res_sum_cfclass nsLK sLp0) cfdotZl cfdot_suml. rewrite big1_seq ?mulr0 // => _ /cfclassP[y Ky ->]; rewrite -conjg_IirrE //. rewrite cfdot_irr mulrb ifN_eq ?(contraNneq _ not_sLp0x) // => <-. by rewrite conjg_IirrE //; apply/cfclassP; exists y. have nsKT_G: K :&: T <| G. rewrite /normal subIset ?sKG // -mulKT setIA (setIidPl sKG) mulG_subG. rewrite normsIG // sub_der1_norm ?subsetIl //. exact: subset_trans (der1_min nLK abKbar) (sub_Inertia _ sLK). have [e DthL]: exists e, 'Res theta = e%:R *: \sum_(xi <- (phi ^: K)%CF) xi. rewrite (Clifford_Res_sum_cfclass nsLK sLp0) -/phi; set e := '[_, _]. exists (Num.truncn e). by rewrite truncnK ?Cnat_cfdot_char ?cfRes_char ?irr_char. have [defKT | ltKT_K] := eqVneq (K :&: T) K; last first. have defKT: K :&: T = L. apply: maxL; last by rewrite subsetI sLK sub_Inertia. by rewrite normal_norm // properEneq ltKT_K subsetIl. have t_cast: size (phi ^: K)%CF = t. by rewrite size_cfclass //= -{2}(setIidPl sKG) -setIA defKT. pose phiKt := Tuple (introT eqP t_cast); pose p i := cfIirr (tnth phiKt i). have pK i: 'chi_(p i) = (phi ^: K)%CF`_i. rewrite cfIirrE; first by rewrite (tnth_nth 0). by have /cfclassP[y _ ->] := mem_tnth i phiKt; rewrite cfConjg_irr ?mem_irr. constructor 3; exists p => [i j /(congr1 (tnth (irr L)))/eqP| ]. by apply: contraTeq; rewrite !pK !nth_uniq ?t_cast ?cfclass_uniq. have{} DthL: 'Res theta = e%:R *: \sum_(i < t) (phi ^: K)%CF`_i. by rewrite DthL (big_nth 0) big_mkord t_cast. suffices /eqP e1: e == 1 by rewrite DthL e1 scale1r; apply: eq_bigr. have Dth1: theta 1%g = e%:R * t%:R * phi 1%g. rewrite -[t]card_ord -mulrA -(cfRes1 L) DthL cfunE; congr (_ * _). rewrite mulr_natl -sumr_const sum_cfunE -t_cast; apply: eq_bigr => i _. by have /cfclassP[y _ ->] := mem_nth 0 (valP i); rewrite cfConjg1. rewrite eqn_leq lt0n (contraNneq _ (irr1_neq0 s)); last first. by rewrite Dth1 => ->; rewrite !mul0r. rewrite -leC_nat -(ler_pM2r (gt0CiG K L)) -/t -(ler_pM2r (irr1_gt0 p0)). rewrite mul1r -Dth1 -cfInd1 //. by rewrite char1_ge_constt ?cfInd_char ?irr_char ?constt_Ind_Res. have IKphi: 'I_K[phi] = K by rewrite -{1}(setIidPl sKG) -setIA. have{} DthL: 'Res[L] theta = e%:R *: phi. by rewrite DthL -[rhs in (_ ^: rhs)%CF]IKphi cfclass_inertia big_seq1. pose mmLth := @mul_mod_Iirr K L s. have linKbar := char_abelianP _ abKbar. have LmodL i: ('chi_i %% L)%CF \is a linear_char := cfMod_lin_char (linKbar i). have mmLthE i: 'chi_(mmLth i) = ('chi_i %% L)%CF * theta. by rewrite cfIirrE ?mod_IirrE // mul_lin_irr ?mem_irr. have mmLthL i: 'Res[L] 'chi_(mmLth i) = 'Res[L] theta. rewrite mmLthE rmorphM /= cfRes_sub_ker ?cfker_mod ?lin_char1 //. by rewrite scale1r mul1r. have [inj_Mphi | /injectivePn[i [j i'j eq_mm_ij]]] := boolP (injectiveb mmLth). suffices /eqP e1: e == 1 by constructor 1; rewrite DthL e1 scale1r mem_irr. rewrite eqn_leq lt0n (contraNneq _ (irr1_neq0 s)); last first. by rewrite -(cfRes1 L) DthL cfunE => ->; rewrite !mul0r. rewrite -leq_sqr -leC_nat natrX -(ler_pM2r (irr1_gt0 p0)) -mulrA mul1r. have ->: e%:R * 'chi_p0 1%g = 'Res[L] theta 1%g by rewrite DthL cfunE. rewrite cfRes1 -(ler_pM2l (gt0CiG K L)) -cfInd1 // -/phi. rewrite -card_quotient // -card_Iirr_abelian // mulr_natl. rewrite ['Ind phi]cfun_sum_cfdot sum_cfunE (bigID [in codom mmLth]) /=. rewrite ler_wpDr ?sumr_ge0 // => [i _|]. by rewrite char1_ge0 ?rpredZ_nat ?Cnat_cfdot_char ?cfInd_char ?irr_char. rewrite -big_uniq //= big_image -sumr_const ler_sum // => i _. rewrite cfunE -[in leRHS](cfRes1 L) -cfdot_Res_r mmLthL cfRes1. by rewrite DthL cfdotZr rmorph_nat cfnorm_irr mulr1. constructor 2; exists e; first by exists p0. pose mu := (('chi_i / 'chi_j)%R %% L)%CF; pose U := cfker mu. have lin_mu: mu \is a linear_char by rewrite cfMod_lin_char ?rpred_div. have Uj := lin_char_unitr (linKbar j). have ltUK: U \proper K. rewrite /proper cfker_sub /U; have /irrP[k Dmu] := lin_char_irr lin_mu. rewrite Dmu subGcfker -irr_eq1 -Dmu cfMod_eq1 //. by rewrite (can2_eq (divrK Uj) (mulrK Uj)) mul1r (inj_eq irr_inj). suffices: theta \in 'CF(K, L). rewrite -cfnorm_Res_leif // DthL cfnormZ !cfnorm_irr !mulr1 normr_nat. by rewrite -natrX eqC_nat => /eqP. have <-: gcore U G = L. apply: maxL; last by rewrite sub_gcore ?cfker_mod. by rewrite gcore_norm (sub_proper_trans (gcore_sub _ _)). apply/cfun_onP=> x; apply: contraNeq => nz_th_x. apply/bigcapP=> y /(subsetP IGtheta)/setIdP[nKy /eqP th_y]. apply: contraR nz_th_x; rewrite mem_conjg -{}th_y cfConjgE {nKy}//. move: {x y}(x ^ _) => x U'x; have [Kx | /cfun0-> //] := boolP (x \in K). have /eqP := congr1 (fun k => (('chi_j %% L)%CF^-1 * 'chi_k) x) eq_mm_ij. rewrite -rmorphV // !mmLthE !mulrA -!rmorphM mulVr // rmorph1 !cfunE. rewrite (mulrC _^-1) -/mu -subr_eq0 -mulrBl cfun1E Kx mulf_eq0 => /orP[]//. rewrite mulrb subr_eq0 -(lin_char1 lin_mu) [_ == _](contraNF _ U'x) //. by rewrite /U cfkerEchar ?lin_charW // inE Kx. Qed. (* This is Isaacs, Corollary (6.19). *) Corollary cfRes_prime_irr_cases G N s p (chi := 'chi[G]_s) : N <| G -> #|G : N| = p -> prime p -> [\/ 'Res[N] chi \in irr N | exists2 c, injective c & 'Res[N] chi = \sum_(i < p) 'chi_(c i)]. Proof. move=> /andP[sNG nNG] iGN pr_p. have chiefGN: chief_factor G N G. apply/andP; split=> //; apply/maxgroupP. split=> [|M /andP[/andP[sMG ltMG] _] sNM]. by rewrite /proper sNG -indexg_gt1 iGN prime_gt1. apply/esym/eqP; rewrite eqEsubset sNM -indexg_eq1 /= eq_sym. rewrite -(eqn_pmul2l (indexg_gt0 G M)) muln1 Lagrange_index // iGN. by apply/eqP/prime_nt_dvdP; rewrite ?indexg_eq1 // -iGN indexgS. have abGbar: abelian (G / N). by rewrite cyclic_abelian ?prime_cyclic ?card_quotient ?iGN. have IGchi: G \subset 'I[chi] by apply: sub_inertia. have [] := invariant_chief_irr_cases chiefGN abGbar IGchi; first by left. case=> e _ /(congr1 (fun m => odd (logn p m)))/eqP/idPn[]. by rewrite lognX mul2n odd_double iGN logn_prime // eqxx. by rewrite iGN; right. Qed. (* This is Isaacs, Corollary (6.20). *) Corollary prime_invariant_irr_extendible G N s p : N <| G -> #|G : N| = p -> prime p -> G \subset 'I['chi_s] -> {t | 'Res[N, G] 'chi_t = 'chi_s}. Proof. move=> nsNG iGN pr_p IGchi. have [t sGt] := constt_cfInd_irr s (normal_sub nsNG); exists t. have [e DtN]: exists e, 'Res 'chi_t = e%:R *: 'chi_s. rewrite constt_Ind_Res in sGt. rewrite (Clifford_Res_sum_cfclass nsNG sGt) cfclass_invariant // big_seq1. set e := '[_, _]; exists (Num.truncn e). by rewrite truncnK ?Cnat_cfdot_char ?cfRes_char ?irr_char. have [/irrWnorm/eqP | [c injc DtNc]] := cfRes_prime_irr_cases t nsNG iGN pr_p. rewrite DtN cfnormZ cfnorm_irr normr_nat mulr1 -natrX pnatr_eq1. by rewrite muln_eq1 andbb => /eqP->; rewrite scale1r. have nz_e: e != 0. have: 'Res[N] 'chi_t != 0 by rewrite cfRes_eq0 // ?irr_char ?irr_neq0. by rewrite DtN; apply: contraNneq => ->; rewrite scale0r. have [i s'ci]: exists i, c i != s. pose i0 := Ordinal (prime_gt0 pr_p); pose i1 := Ordinal (prime_gt1 pr_p). have [<- | ] := eqVneq (c i0) s; last by exists i0. by exists i1; rewrite (inj_eq injc). have /esym/eqP/idPn[] := congr1 (cfdotr 'chi_(c i)) DtNc; rewrite {1}DtN /=. rewrite cfdot_suml cfdotZl cfdot_irr mulrb ifN_eqC // mulr0. rewrite (bigD1 i) //= cfnorm_irr big1 ?addr0 ?oner_eq0 // => j i'j. by rewrite cfdot_irr mulrb ifN_eq ?(inj_eq injc). Qed. (* This is Isaacs, Lemma (6.24). *) Lemma extend_to_cfdet G N s c0 u : let theta := 'chi_s in let lambda := cfDet theta in let mu := 'chi_u in N <| G -> coprime #|G : N| (Num.truncn (theta 1%g)) -> 'Res[N, G] 'chi_c0 = theta -> 'Res[N, G] mu = lambda -> exists2 c, 'Res 'chi_c = theta /\ cfDet 'chi_c = mu & forall c1, 'Res 'chi_c1 = theta -> cfDet 'chi_c1 = mu -> c1 = c. Proof. move=> theta lambda mu nsNG; set e := #|G : N|; set f := Num.truncn _. set eta := 'chi_c0 => co_e_f etaNth muNlam; have [sNG nNG] := andP nsNG. have fE: f%:R = theta 1%g by rewrite truncnK ?Cnat_irr1. pose nu := cfDet eta; have lin_nu: nu \is a linear_char := cfDet_lin_char _. have nuNlam: 'Res nu = lambda by rewrite -cfDetRes ?irr_char ?etaNth. have lin_lam: lambda \is a linear_char := cfDet_lin_char _. have lin_mu: mu \is a linear_char. by have:= lin_lam; rewrite -muNlam; apply: cfRes_lin_lin; apply: irr_char. have [Unu Ulam] := (lin_char_unitr lin_nu, lin_char_unitr lin_lam). pose alpha := mu / nu. have alphaN_1: 'Res[N] alpha = 1 by rewrite rmorph_div //= muNlam nuNlam divrr. have lin_alpha: alpha \is a linear_char by apply: rpred_div. have alpha_e: alpha ^+ e = 1. have kerNalpha: N \subset cfker alpha. by rewrite -subsetIidl -cfker_Res ?lin_charW // alphaN_1 cfker_cfun1. apply/eqP; rewrite -(cfQuoK nsNG kerNalpha) -rmorphXn cfMod_eq1 //. rewrite -dvdn_cforder /e -card_quotient //. by rewrite cforder_lin_char_dvdG ?cfQuo_lin_char. have det_alphaXeta b: cfDet (alpha ^+ b * eta) = alpha ^+ (b * f) * nu. by rewrite cfDet_mul_lin ?rpredX ?irr_char // -exprM -(cfRes1 N) etaNth. have [b bf_mod_e]: exists b, b * f = 1 %[mod e]. rewrite -(chinese_modl co_e_f 1 0) /chinese !mul0n addn0 !mul1n mulnC. by exists (egcdn f e).1. have alpha_bf: alpha ^+ (b * f) = alpha. by rewrite -(expr_mod _ alpha_e) bf_mod_e expr_mod. have /irrP[c Dc]: alpha ^+ b * eta \in irr G. by rewrite mul_lin_irr ?rpredX ?mem_irr. have chiN: 'Res 'chi_c = theta. by rewrite -Dc rmorphM rmorphXn /= alphaN_1 expr1n mul1r. have det_chi: cfDet 'chi_c = mu by rewrite -Dc det_alphaXeta alpha_bf divrK. exists c => // c2 c2Nth det_c2_mu; apply: irr_inj. have [irrMc _ imMc _] := constt_Ind_ext nsNG chiN. have /codomP[s2 Dc2]: c2 \in codom (@mul_mod_Iirr G N c). by rewrite -imMc constt_Ind_Res c2Nth constt_irr ?inE. have{} Dc2: 'chi_c2 = ('chi_s2 %% N)%CF * 'chi_c. by rewrite Dc2 cfIirrE // mod_IirrE. have s2_lin: 'chi_s2 \is a linear_char. rewrite qualifE/= irr_char; apply/eqP/(mulIf (irr1_neq0 c)). rewrite mul1r -[in RHS](cfRes1 N) chiN -c2Nth cfRes1. by rewrite Dc2 cfunE cfMod1. have s2Xf_1: 'chi_s2 ^+ f = 1. apply/(can_inj (cfModK nsNG))/(mulIr (lin_char_unitr lin_mu))/esym. rewrite rmorph1 rmorphXn /= mul1r -{1}det_c2_mu Dc2 -det_chi. by rewrite cfDet_mul_lin ?cfMod_lin_char ?irr_char // -(cfRes1 N) chiN. suffices /eqP s2_1: 'chi_s2 == 1 by rewrite Dc2 s2_1 rmorph1 mul1r. rewrite -['chi_s2]expr1 -dvdn_cforder -(eqnP co_e_f) dvdn_gcd. by rewrite /e -card_quotient ?cforder_lin_char_dvdG //= dvdn_cforder s2Xf_1. Qed. (* This is Isaacs, Theorem (6.25). *) Theorem solvable_irr_extendible_from_det G N s (theta := 'chi[N]_s) : N <| G -> solvable (G / N) -> G \subset 'I[theta] -> coprime #|G : N| (Num.truncn (theta 1%g)) -> [exists c, 'Res 'chi[G]_c == theta] = [exists u, 'Res 'chi[G]_u == cfDet theta]. Proof. set e := #|G : N|; set f := Num.truncn _ => nsNG solG IGtheta co_e_f. apply/exists_eqP/exists_eqP=> [[c cNth] | [u uNdth]]. have /lin_char_irr/irrP[u Du] := cfDet_lin_char 'chi_c. by exists u; rewrite -Du -cfDetRes ?irr_char ?cNth. move: {2}e.+1 (ltnSn e) => m. elim: m => // m IHm in G u e nsNG solG IGtheta co_e_f uNdth *. rewrite ltnS => le_e; have [sNG nNG] := andP nsNG. have [<- | ltNG] := eqsVneq N G; first by exists s; rewrite cfRes_id. have [G0 maxG0 sNG0]: {G0 | maxnormal (gval G0) G G & N \subset G0}. by apply: maxgroup_exists; rewrite properEneq ltNG sNG. have [/andP[ltG0G nG0G] maxG0_P] := maxgroupP maxG0. set mu := 'chi_u in uNdth; have lin_mu: mu \is a linear_char. by rewrite qualifE/= irr_char -(cfRes1 N) uNdth /= lin_char1 ?cfDet_lin_char. have sG0G := proper_sub ltG0G; have nsNG0 := normalS sNG0 sG0G nsNG. have nsG0G: G0 <| G by apply/andP. have /lin_char_irr/irrP[u0 Du0] := cfRes_lin_char G0 lin_mu. have u0Ndth: 'Res 'chi_u0 = cfDet theta by rewrite -Du0 cfResRes. have IG0theta: G0 \subset 'I[theta]. by rewrite (subset_trans sG0G) // -IGtheta subsetIr. have coG0f: coprime #|G0 : N| f by rewrite (coprime_dvdl _ co_e_f) ?indexSg. have{m IHm le_e} [c0 c0Ns]: exists c0, 'Res 'chi[G0]_c0 = theta. have solG0: solvable (G0 / N) := solvableS (quotientS N sG0G) solG. apply: IHm nsNG0 solG0 IG0theta coG0f u0Ndth (leq_trans _ le_e). by rewrite -(ltn_pmul2l (cardG_gt0 N)) !Lagrange ?proper_card. have{c0 c0Ns} [c0 [c0Ns dc0_u0] Uc0] := extend_to_cfdet nsNG0 coG0f c0Ns u0Ndth. have IGc0: G \subset 'I['chi_c0]. apply/subsetP=> x Gx; rewrite inE (subsetP nG0G) //= -conjg_IirrE. apply/eqP; congr 'chi__; apply: Uc0; rewrite conjg_IirrE. by rewrite -(cfConjgRes _ nsG0G nsNG) // c0Ns inertiaJ ?(subsetP IGtheta). by rewrite cfDetConjg dc0_u0 -Du0 (cfConjgRes _ _ nsG0G) // cfConjg_id. have prG0G: prime #|G : G0|. have [h injh im_h] := third_isom sNG0 nsNG nsG0G. rewrite -card_quotient // -im_h // card_injm //. rewrite simple_sol_prime 1?quotient_sol //. by rewrite /simple -(injm_minnormal injh) // im_h // maxnormal_minnormal. have [t tG0c0] := prime_invariant_irr_extendible nsG0G (erefl _) prG0G IGc0. by exists t; rewrite /theta -c0Ns -tG0c0 cfResRes. Qed. (* This is Isaacs, Theorem (6.26). *) Theorem extend_linear_char_from_Sylow G N (lambda : 'CF(N)) : N <| G -> lambda \is a linear_char -> G \subset 'I[lambda] -> (forall p, p \in \pi('o(lambda)%CF) -> exists2 Hp : {group gT}, [/\ N \subset Hp, Hp \subset G & p.-Sylow(G / N) (Hp / N)%g] & exists u, 'Res 'chi[Hp]_u = lambda) -> exists u, 'Res[N, G] 'chi_u = lambda. Proof. set m := 'o(lambda)%CF => nsNG lam_lin IGlam p_ext_lam. have [sNG nNG] := andP nsNG; have linN := @cfRes_lin_lin _ _ N. wlog [p p_lam]: lambda @m lam_lin IGlam p_ext_lam / exists p : nat, \pi(m) =i (p : nat_pred). - move=> IHp; have [linG [cf [inj_cf _ lin_cf onto_cf]]] := lin_char_group N. case=> cf1 cfM cfX _ cf_order; have [lam cf_lam] := onto_cf _ lam_lin. pose mu p := cf lam.`_p; pose pi_m p := p \in \pi(m). have Dm: m = #[lam] by rewrite /m cfDet_order_lin // cf_lam cf_order. have Dlambda: lambda = \prod_(p < m.+1 | pi_m p) mu p. rewrite -(big_morph cf cfM cf1) big_mkcond cf_lam /pi_m Dm; congr (cf _). rewrite -{1}[lam]prod_constt big_mkord; apply: eq_bigr => p _. by case: ifPn => // p'lam; apply/constt1P; rewrite /p_elt p'natEpi. have lin_mu p: mu p \is a linear_char by rewrite /mu cfX -cf_lam rpredX. suffices /fin_all_exists [u uNlam] (p : 'I_m.+1): exists u, pi_m p -> 'Res[N, G] 'chi_u = mu p. - pose nu := \prod_(p < m.+1 | pi_m p) 'chi_(u p). have lin_nu: nu \is a linear_char. by apply: rpred_prod => p m_p; rewrite linN ?irr_char ?uNlam. have /irrP[u1 Dnu] := lin_char_irr lin_nu. by exists u1; rewrite Dlambda -Dnu rmorph_prod; apply: eq_bigr. have [m_p | _] := boolP (pi_m p); last by exists 0. have o_mu: \pi('o(mu p)%CF) =i (p : nat_pred). rewrite cfDet_order_lin // cf_order orderE /=. have [|pr_p _ [k ->]] := pgroup_pdiv (p_elt_constt p lam). by rewrite cycle_eq1 (sameP eqP constt1P) /p_elt p'natEpi // negbK -Dm. by move=> q; rewrite pi_of_exp // pi_of_prime. have IGmu: G \subset 'I[mu p]. rewrite (subset_trans IGlam) // /mu cfX -cf_lam. elim: (chinese _ _ _ _) => [|k IHk]; first by rewrite inertia1 norm_inertia. by rewrite exprS (subset_trans _ (inertia_mul _ _)) // subsetIidl. have [q||u] := IHp _ (lin_mu p) IGmu; [ | by exists p | by exists u]. rewrite o_mu => /eqnP-> {q}. have [Hp sylHp [u uNlam]] := p_ext_lam p m_p; exists Hp => //. rewrite /mu cfX -cf_lam -uNlam -rmorphXn /=; set nu := _ ^+ _. have /lin_char_irr/irrP[v ->]: nu \is a linear_char; last by exists v. by rewrite rpredX // linN ?irr_char ?uNlam. have pi_m_p: p \in \pi(m) by rewrite p_lam !inE. have [pr_p mgt0]: prime p /\ (m > 0)%N. by have:= pi_m_p; rewrite mem_primes => /and3P[]. have p_m: p.-nat m by rewrite -(eq_pnat _ p_lam) pnat_pi. have{p_ext_lam} [H [sNH sHG sylHbar] [v vNlam]] := p_ext_lam p pi_m_p. have co_p_GH: coprime p #|G : H|. rewrite -(index_quotient_eq _ sHG nNG) ?subIset ?sNH ?orbT //. by rewrite (pnat_coprime (pnat_id pr_p)) //; have [] := and3P sylHbar. have lin_v: 'chi_v \is a linear_char by rewrite linN ?irr_char ?vNlam. pose nuG := 'Ind[G] 'chi_v. have [c vGc co_p_f]: exists2 c, c \in irr_constt nuG & ~~ (p %| 'chi_c 1%g)%C. apply/exists_inP; rewrite -negb_forall_in. apply: contraL co_p_GH => /forall_inP p_dv_v1. rewrite prime_coprime // negbK -dvdC_nat -[rhs in (_ %| rhs)%C]mulr1. rewrite -(lin_char1 lin_v) -cfInd1 // ['Ind _]cfun_sum_constt /=. rewrite sum_cfunE rpred_sum // => i /p_dv_v1 p_dv_chi1i. rewrite cfunE dvdC_mull // intr_nat //. by rewrite Cnat_cfdot_char ?cfInd_char ?irr_char. pose f := Num.truncn ('chi_c 1%g); pose b := (egcdn f m).1. have fK: f%:R = 'chi_c 1%g by rewrite truncnK ?Cnat_irr1. have fb_mod_m: f * b = 1 %[mod m]. have co_m_f: coprime m f. by rewrite (pnat_coprime p_m) ?p'natE // -dvdC_nat CdivE fK. by rewrite -(chinese_modl co_m_f 1 0) /chinese !mul0n addn0 mul1n. have /irrP[s Dlam] := lin_char_irr lam_lin. have cHv: v \in irr_constt ('Res[H] 'chi_c) by rewrite -constt_Ind_Res. have{cHv} cNs: s \in irr_constt ('Res[N] 'chi_c). rewrite -(cfResRes _ sNH) ?(constt_Res_trans _ cHv) ?cfRes_char ?irr_char //. by rewrite vNlam Dlam constt_irr !inE. have DcN: 'Res[N] 'chi_c = lambda *+ f. have:= Clifford_Res_sum_cfclass nsNG cNs. rewrite cfclass_invariant -Dlam // big_seq1 Dlam => DcN. have:= cfRes1 N 'chi_c; rewrite DcN cfunE -Dlam lin_char1 // mulr1 => ->. by rewrite -scaler_nat fK. have /lin_char_irr/irrP[d Dd]: cfDet 'chi_c ^+ b \is a linear_char. by rewrite rpredX // cfDet_lin_char. exists d; rewrite -{}Dd rmorphXn /= -cfDetRes ?irr_char // DcN. rewrite cfDetMn ?lin_charW // -exprM cfDet_id //. rewrite -(expr_mod _ (exp_cforder _)) -cfDet_order_lin // -/m. by rewrite fb_mod_m /m cfDet_order_lin // expr_mod ?exp_cforder. Qed. (* This is Isaacs, Corollary (6.27). *) Corollary extend_coprime_linear_char G N (lambda : 'CF(N)) : N <| G -> lambda \is a linear_char -> G \subset 'I[lambda] -> coprime #|G : N| 'o(lambda)%CF -> exists u, [/\ 'Res 'chi[G]_u = lambda, 'o('chi_u)%CF = 'o(lambda)%CF & forall v, 'Res 'chi_v = lambda -> coprime #|G : N| 'o('chi_v)%CF -> v = u]. Proof. set e := #|G : N| => nsNG lam_lin IGlam co_e_lam; have [sNG nNG] := andP nsNG. have [p lam_p | v vNlam] := extend_linear_char_from_Sylow nsNG lam_lin IGlam. exists N; last first. by have /irrP[u ->] := lin_char_irr lam_lin; exists u; rewrite cfRes_id. split=> //; rewrite trivg_quotient /pHall sub1G pgroup1 indexg1. rewrite card_quotient //= -/e (pi'_p'nat _ lam_p) //. rewrite -coprime_pi' ?indexg_gt0 1?coprime_sym //. by have:= lam_p; rewrite mem_primes => /and3P[]. set nu := 'chi_v in vNlam. have lin_nu: nu \is a linear_char. by rewrite (@cfRes_lin_lin _ _ N) ?vNlam ?irr_char. have [b be_mod_lam]: exists b, b * e = 1 %[mod 'o(lambda)%CF]. rewrite -(chinese_modr co_e_lam 0 1) /chinese !mul0n !mul1n mulnC. by set b := _.1; exists b. have /irrP[u Du]: nu ^+ (b * e) \in irr G by rewrite lin_char_irr ?rpredX. exists u; set mu := 'chi_u in Du *. have uNlam: 'Res mu = lambda. rewrite cfDet_order_lin // in be_mod_lam. rewrite -Du rmorphXn /= vNlam -(expr_mod _ (exp_cforder _)) //. by rewrite be_mod_lam expr_mod ?exp_cforder. have lin_mu: mu \is a linear_char by rewrite -Du rpredX. have o_mu: ('o(mu) = 'o(lambda))%CF. have dv_o_lam_mu: 'o(lambda)%CF %| 'o(mu)%CF. by rewrite !cfDet_order_lin // -uNlam cforder_Res. have kerNnu_olam: N \subset cfker (nu ^+ 'o(lambda)%CF). rewrite -subsetIidl -cfker_Res ?rpredX ?irr_char //. by rewrite rmorphXn /= vNlam cfDet_order_lin // exp_cforder cfker_cfun1. apply/eqP; rewrite eqn_dvd dv_o_lam_mu andbT cfDet_order_lin //. rewrite dvdn_cforder -Du exprAC -dvdn_cforder dvdn_mull //. rewrite -(cfQuoK nsNG kerNnu_olam) cforder_mod // /e -card_quotient //. by rewrite cforder_lin_char_dvdG ?cfQuo_lin_char ?rpredX. split=> // t tNlam co_e_t. have lin_t: 'chi_t \is a linear_char. by rewrite (@cfRes_lin_lin _ _ N) ?tNlam ?irr_char. have Ut := lin_char_unitr lin_t. have kerN_mu_t: N \subset cfker (mu / 'chi_t)%R. rewrite -subsetIidl -cfker_Res ?lin_charW ?rpred_div ?rmorph_div //. by rewrite /= uNlam tNlam divrr ?lin_char_unitr ?cfker_cfun1. have co_e_mu_t: coprime e #[(mu / 'chi_t)%R]%CF. suffices dv_o_mu_t: #[(mu / 'chi_t)%R]%CF %| 'o(mu)%CF * 'o('chi_t)%CF. by rewrite (coprime_dvdr dv_o_mu_t) // coprimeMr o_mu co_e_lam. rewrite !cfDet_order_lin //; apply/dvdn_cforderP=> x Gx. rewrite invr_lin_char // !cfunE exprMn -rmorphXn {2}mulnC /=. by rewrite !(dvdn_cforderP _) ?conjC1 ?mulr1 // dvdn_mulr. have /eqP mu_t_1: mu / 'chi_t == 1. rewrite -(dvdn_cforder (_ / _)%R 1) -(eqnP co_e_mu_t) dvdn_gcd dvdnn andbT. rewrite -(cfQuoK nsNG kerN_mu_t) cforder_mod // /e -card_quotient //. by rewrite cforder_lin_char_dvdG ?cfQuo_lin_char ?rpred_div. by apply: irr_inj; rewrite -['chi_t]mul1r -mu_t_1 divrK. Qed. (* This is Isaacs, Corollary (6.28). *) Corollary extend_solvable_coprime_irr G N t (theta := 'chi[N]_t) : N <| G -> solvable (G / N) -> G \subset 'I[theta] -> coprime #|G : N| ('o(theta)%CF * Num.truncn (theta 1%g)) -> exists c, [/\ 'Res 'chi[G]_c = theta, 'o('chi_c)%CF = 'o(theta)%CF & forall d, 'Res 'chi_d = theta -> coprime #|G : N| 'o('chi_d)%CF -> d = c]. Proof. set e := #|G : N|; set f := Num.truncn _ => nsNG solG IGtheta. rewrite coprimeMr => /andP[co_e_th co_e_f]. have [sNG nNG] := andP nsNG; pose lambda := cfDet theta. have lin_lam: lambda \is a linear_char := cfDet_lin_char theta. have IGlam: G \subset 'I[lambda]. apply/subsetP=> y /(subsetP IGtheta)/setIdP[nNy /eqP th_y]. by rewrite inE nNy /= -cfDetConjg th_y. have co_e_lam: coprime e 'o(lambda)%CF by rewrite cfDet_order_lin. have [//|u [uNlam o_u Uu]] := extend_coprime_linear_char nsNG lin_lam IGlam. have /exists_eqP[c cNth]: [exists c, 'Res 'chi[G]_c == theta]. rewrite solvable_irr_extendible_from_det //. by apply/exists_eqP; exists u. have{c cNth} [c [cNth det_c] Uc] := extend_to_cfdet nsNG co_e_f cNth uNlam. have lin_u: 'chi_u \is a linear_char by rewrite -det_c cfDet_lin_char. exists c; split=> // [|c0 c0Nth co_e_c0]. by rewrite !cfDet_order_lin // -det_c in o_u. have lin_u0: cfDet 'chi_c0 \is a linear_char := cfDet_lin_char 'chi_c0. have /irrP[u0 Du0] := lin_char_irr lin_u0. have co_e_u0: coprime e 'o('chi_u0)%CF by rewrite -Du0 cfDet_order_lin. have eq_u0u: u0 = u by apply: Uu; rewrite // -Du0 -cfDetRes ?irr_char ?c0Nth. by apply: Uc; rewrite // Du0 eq_u0u. Qed. End ExtendInvariantIrr. Section Frobenius. Variables (gT : finGroupType) (G K : {group gT}). (* Because he only defines Frobenius groups in chapter 7, Isaacs does not *) (* state these theorems using the Frobenius property. *) Hypothesis frobGK : [Frobenius G with kernel K]. (* This is Isaacs, Theorem 6.34(a1). *) Theorem inertia_Frobenius_ker i : i != 0 -> 'I_G['chi[K]_i] = K. Proof. have [_ _ nsKG regK] := Frobenius_kerP frobGK; have [sKG nKG] := andP nsKG. move=> nzi; apply/eqP; rewrite eqEsubset sub_Inertia // andbT. apply/subsetP=> x /setIP[Gx /setIdP[nKx /eqP x_stab_i]]. have actIirrK: is_action G (@conjg_Iirr _ K). split=> [y j k eq_jk | j y z Gy Gz]. by apply/irr_inj/(can_inj (cfConjgK y)); rewrite -!conjg_IirrE eq_jk. by apply: irr_inj; rewrite !conjg_IirrE (cfConjgM _ nsKG). pose ito := Action actIirrK; pose cto := ('Js \ (subsetT G))%act. have acts_Js : [acts G, on classes K | 'Js]. apply/subsetP=> y Gy; have nKy := subsetP nKG y Gy. rewrite !inE; apply/subsetP=> _ /imsetP[z Gz ->] /[!inE]/=. rewrite -class_rcoset norm_rlcoset // class_lcoset. by apply: imset_f; rewrite memJ_norm. have acts_cto : [acts G, on classes K | cto] by rewrite astabs_ract subsetIidl. pose m := #|'Fix_(classes K | cto)[x]|. have def_m: #|'Fix_ito[x]| = m. apply: card_afix_irr_classes => // j y _ Ky /imsetP[_ /imsetP[z Kz ->] ->]. by rewrite conjg_IirrE cfConjgEJ // cfunJ. have: (m != 1)%N. rewrite -def_m (cardD1 (0 : Iirr K)) (cardD1 i) !(inE, sub1set) /=. by rewrite conjg_Iirr0 nzi eqxx -(inj_eq irr_inj) conjg_IirrE x_stab_i eqxx. apply: contraR => notKx; apply/cards1P; exists 1%g; apply/esym/eqP. rewrite eqEsubset !(sub1set, inE) classes1 /= conjs1g eqxx /=. apply/subsetP=> _ /setIP[/imsetP[y Ky ->] /afix1P /= cyKx]. have /imsetP[z Kz def_yx]: y ^ x \in y ^: K. by rewrite -cyKx; apply: imset_f; apply: class_refl. rewrite inE classG_eq1; apply: contraR notKx => nty. rewrite -(groupMr x (groupVr Kz)). apply: (subsetP (regK y _)); first exact/setD1P. rewrite !inE groupMl // groupV (subsetP sKG) //=. by rewrite conjg_set1 conjgM def_yx conjgK. Qed. (* This is Isaacs, Theorem 6.34(a2) *) Theorem irr_induced_Frobenius_ker i : i != 0 -> 'Ind[G, K] 'chi_i \in irr G. Proof. move/inertia_Frobenius_ker/group_inj=> defK. have [_ _ nsKG _] := Frobenius_kerP frobGK. have [] := constt_Inertia_bijection i nsKG; rewrite defK cfInd_id => -> //. by rewrite constt_irr !inE. Qed. (* This is Isaacs, Theorem 6.34(b) *) Theorem Frobenius_Ind_irrP j : reflect (exists2 i, i != 0 & 'chi_j = 'Ind[G, K] 'chi_i) (~~ (K \subset cfker 'chi_j)). Proof. have [_ _ nsKG _] := Frobenius_kerP frobGK; have [sKG nKG] := andP nsKG. apply: (iffP idP) => [not_chijK1 | [i nzi ->]]; last first. by rewrite cfker_Ind_irr ?sub_gcore // subGcfker. have /neq0_has_constt[i chijKi]: 'Res[K] 'chi_j != 0 by apply: Res_irr_neq0. have nz_i: i != 0. by apply: contraNneq not_chijK1 => i0; rewrite constt0_Res_cfker // -i0. have /irrP[k def_chik] := irr_induced_Frobenius_ker nz_i. have: '['chi_j, 'chi_k] != 0 by rewrite -def_chik -cfdot_Res_l. by rewrite cfdot_irr pnatr_eq0; case: (j =P k) => // ->; exists i. Qed. End Frobenius.
TProd.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Data.List.Nodup import Mathlib.Data.Set.Prod /-! # Finite products of types This file defines the product of types over a list. For `l : List ι` and `α : ι → Type v` we define `List.TProd α l = l.foldr (fun i β ↦ α i × β) PUnit`. This type should not be used if `∀ i, α i` or `∀ i ∈ l, α i` can be used instead (in the last expression, we could also replace the list `l` by a set or a finset). This type is used as an intermediary between binary products and finitary products. The application of this type is finitary product measures, but it could be used in any construction/theorem that is easier to define/prove on binary products than on finitary products. * Once we have the construction on binary products (like binary product measures in `MeasureTheory.prod`), we can easily define a finitary version on the type `TProd l α` by iterating. Properties can also be easily extended from the binary case to the finitary case by iterating. * Then we can use the equivalence `List.TProd.piEquivTProd` below (or enhanced versions of it, like a `MeasurableEquiv` for product measures) to get the construction on `∀ i : ι, α i`, at least when assuming `[Fintype ι] [Encodable ι]` (using `Encodable.sortedUniv`). Using `attribute [local instance] Fintype.toEncodable` we can get rid of the argument `[Encodable ι]`. ## Main definitions * We have the equivalence `TProd.piEquivTProd : (∀ i, α i) ≃ TProd α l` if `l` contains every element of `ι` exactly once. * The product of sets is `Set.tprod : (∀ i, Set (α i)) → Set (TProd α l)`. -/ open List Function universe u v variable {ι : Type u} {α : ι → Type v} {i j : ι} {l : List ι} namespace List variable (α) in /-- The product of a family of types over a list. -/ abbrev TProd (l : List ι) : Type v := l.foldr (fun i β => α i × β) PUnit namespace TProd /-- Turning a function `f : ∀ i, α i` into an element of the iterated product `TProd α l`. -/ protected def mk : ∀ (l : List ι) (_f : ∀ i, α i), TProd α l | [] => fun _ => PUnit.unit | i :: is => fun f => (f i, TProd.mk is f) instance [∀ i, Inhabited (α i)] : Inhabited (TProd α l) := ⟨TProd.mk l default⟩ @[simp] theorem fst_mk (i : ι) (l : List ι) (f : ∀ i, α i) : (TProd.mk (i :: l) f).1 = f i := rfl @[simp] theorem snd_mk (i : ι) (l : List ι) (f : ∀ i, α i) : (TProd.mk.{u,v} (i :: l) f).2 = TProd.mk.{u,v} l f := rfl variable [DecidableEq ι] /-- Given an element of the iterated product `l.Prod α`, take a projection into direction `i`. If `i` appears multiple times in `l`, this chooses the first component in direction `i`. -/ protected def elim : ∀ {l : List ι} (_ : TProd α l) {i : ι} (_ : i ∈ l), α i | i :: is, v, j, hj => if hji : j = i then by subst hji exact v.1 else TProd.elim v.2 ((List.mem_cons.mp hj).resolve_left hji) @[simp] theorem elim_self (v : TProd α (i :: l)) : v.elim mem_cons_self = v.1 := by simp [TProd.elim] @[simp] theorem elim_of_ne (hj : j ∈ i :: l) (hji : j ≠ i) (v : TProd α (i :: l)) : v.elim hj = TProd.elim v.2 ((List.mem_cons.mp hj).resolve_left hji) := by simp [TProd.elim, hji] @[simp] theorem elim_of_mem (hl : (i :: l).Nodup) (hj : j ∈ l) (v : TProd α (i :: l)) : v.elim (mem_cons_of_mem _ hj) = TProd.elim v.2 hj := by apply elim_of_ne rintro rfl exact hl.notMem hj theorem elim_mk : ∀ (l : List ι) (f : ∀ i, α i) {i : ι} (hi : i ∈ l), (TProd.mk l f).elim hi = f i | i :: is, f, j, hj => by by_cases hji : j = i · subst hji simp · rw [TProd.elim_of_ne _ hji, snd_mk, elim_mk is] @[ext] theorem ext : ∀ {l : List ι} (_ : l.Nodup) {v w : TProd α l} (_ : ∀ (i) (hi : i ∈ l), v.elim hi = w.elim hi), v = w | [], _, v, w, _ => PUnit.ext v w | i :: is, hl, v, w, hvw => by apply Prod.ext · rw [← elim_self v, hvw, elim_self] refine ext (nodup_cons.mp hl).2 fun j hj => ?_ rw [← elim_of_mem hl, hvw, elim_of_mem hl] /-- A version of `TProd.elim` when `l` contains all elements. In this case we get a function into `Π i, α i`. -/ @[simp] protected def elim' (h : ∀ i, i ∈ l) (v : TProd α l) (i : ι) : α i := v.elim (h i) theorem mk_elim (hnd : l.Nodup) (h : ∀ i, i ∈ l) (v : TProd α l) : TProd.mk l (v.elim' h) = v := TProd.ext hnd fun i hi => by simp [elim_mk] /-- Pi-types are equivalent to iterated products. -/ def piEquivTProd (hnd : l.Nodup) (h : ∀ i, i ∈ l) : (∀ i, α i) ≃ TProd α l := ⟨TProd.mk l, TProd.elim' h, fun f => funext fun i => elim_mk l f (h i), mk_elim hnd h⟩ end TProd end List namespace Set /-- A product of sets in `TProd α l`. -/ @[simp] protected def tprod : ∀ (l : List ι) (_t : ∀ i, Set (α i)), Set (TProd α l) | [], _ => univ | i :: is, t => t i ×ˢ Set.tprod is t theorem mk_preimage_tprod : ∀ (l : List ι) (t : ∀ i, Set (α i)), TProd.mk l ⁻¹' Set.tprod l t = { i | i ∈ l }.pi t | [], t => by simp [Set.tprod] | i :: l, t => by ext f have h : TProd.mk l f ∈ Set.tprod l t ↔ ∀ i : ι, i ∈ l → f i ∈ t i := by change f ∈ TProd.mk l ⁻¹' Set.tprod l t ↔ f ∈ { x | x ∈ l }.pi t rw [mk_preimage_tprod l t] -- `simp [Set.TProd, TProd.mk, this]` can close this goal but is slow. rw [Set.tprod, TProd.mk, mem_preimage, mem_pi, prodMk_mem_set_prod_eq] simp_rw [mem_setOf_eq, mem_cons] rw [forall_eq_or_imp, and_congr_right_iff] exact fun _ => h theorem elim_preimage_pi [DecidableEq ι] {l : List ι} (hnd : l.Nodup) (h : ∀ i, i ∈ l) (t : ∀ i, Set (α i)) : TProd.elim' h ⁻¹' pi univ t = Set.tprod l t := by have h2 : { i | i ∈ l } = univ := by ext i simp [h] rw [← h2, ← mk_preimage_tprod, preimage_preimage] simp only [TProd.mk_elim hnd h] dsimp end Set
quotient.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq div. From mathcomp Require Import choice fintype prime finset fingroup morphism. From mathcomp Require Import automorphism. (******************************************************************************) (* This file contains the definitions of: *) (* coset_of H == the (sub)type of bilateral cosets of H (see below). *) (* coset H == the canonical projection into coset_of H. *) (* A / H == the quotient of A by H, that is, the morphic image *) (* of A by coset H. We do not require H <| A, so in a *) (* textbook A / H would be written 'N_A(H) * H / H. *) (* quotm f (nHG : H <| G) == the quotient morphism induced by f, *) (* mapping G / H onto f @* G / f @* H. *) (* qisom f (eqHG : H = G) == the identity isomorphism between *) (* [set: coset_of G] and [set: coset_of H]. *) (* We also prove the three isomorphism theorems, and counting lemmas for *) (* morphisms. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope. Section Cosets. Variables (gT : finGroupType) (Q A : {set gT}). (******************************************************************************) (* Cosets are right cosets of elements in the normaliser. *) (* We let cosets coerce to GroupSet.sort, so they inherit the group subset *) (* base group structure. Later we will define a proper group structure on *) (* cosets, which will then hide the inherited structure once coset_of unifies *) (* with FinGroup.sort; the coercion to GroupSet.sort will no longer be used. *) (* Note that for Hx Hy : coset_of H, Hx * Hy : {set gT} can mean either *) (* set_of_coset (mulg Hx Hy) OR mulg (set_of_coset Hx) (set_of_coset Hy). *) (* However, since the two terms are actually convertible, we can live with *) (* this ambiguity. *) (* We take great care that neither the type coset_of H, nor its Canonical *) (* finGroupType structure, nor the coset H morphism depend on the actual *) (* group structure of H. Otherwise, rewriting would be extremely awkward *) (* because all our equalities are stated at the set level. *) (* The trick we use is to interpret coset_of A, when A is any set, as the *) (* type of cosets of the group <<A>> generated by A, in the group A <*> N(A) *) (* generated by A and its normaliser. This coincides with the type of *) (* bilateral cosets of A when A is a group. We restrict the domain of coset A *) (* to 'N(A), so that we get almost all the same conversion equalities as if *) (* we had forced A to be a group in the first place; the only exception, that *) (* 1 : coset_of A : {set gT} = <<A>> rather than A, can be handled by genGid. *) (******************************************************************************) Notation H := <<A>>. Definition coset_range := [pred B in rcosets H 'N(A)]. Record coset_of : Type := Coset { set_of_coset :> GroupSet.sort gT; _ : coset_range set_of_coset }. HB.instance Definition _ := [isSub for set_of_coset]. #[hnf] HB.instance Definition _ := [Finite of coset_of by <:]. (* We build a new (canonical) structure of groupType for cosets. *) (* When A is a group, this is the largest possible quotient 'N(A) / A. *) Lemma coset_one_proof : coset_range H. Proof. by apply/rcosetsP; exists (1 : gT); rewrite (group1, mulg1). Qed. Definition coset_one := Coset coset_one_proof. Let nNH := subsetP (norm_gen A). Lemma coset_range_mul (B C : coset_of) : coset_range (B * C). Proof. case: B C => _ /= /rcosetsP[x Nx ->] [_ /= /rcosetsP[y Ny ->]]. by apply/rcosetsP; exists (x * y); rewrite !(groupM, rcoset_mul, nNH). Qed. Definition coset_mul B C := Coset (coset_range_mul B C). Lemma coset_range_inv (B : coset_of) : coset_range B^-1. Proof. case: B => _ /= /rcosetsP[x Nx ->]; rewrite norm_rlcoset ?nNH // invg_lcoset. by apply/rcosetsP; exists x^-1; rewrite ?groupV. Qed. Definition coset_inv B := Coset (coset_range_inv B). Lemma coset_mulP : associative coset_mul. Proof. by move=> B C D; apply: val_inj; rewrite /= mulgA. Qed. Lemma coset_oneP : left_id coset_one coset_mul. Proof. case=> B coB; apply: val_inj => /=; case/rcosetsP: coB => x Hx ->{B}. by rewrite mulgA mulGid. Qed. Lemma coset_invP : left_inverse coset_one coset_inv coset_mul. Proof. case=> B coB; apply: val_inj => /=; case/rcosetsP: coB => x Hx ->{B}. rewrite invg_rcoset -mulgA (mulgA H) mulGid. by rewrite norm_rlcoset ?nNH // -lcosetM mulVg mul1g. Qed. HB.instance Definition _ := isMulGroup.Build coset_of coset_mulP coset_oneP coset_invP. (* Projection of the initial group type over the cosets groupType. *) Definition coset x : coset_of := insubd (1 : coset_of) (H :* x). (* This is a primitive lemma -- we'll need to restate it for *) (* the case where A is a group. *) Lemma val_coset_prim x : x \in 'N(A) -> coset x :=: H :* x. Proof. by move=> Nx; rewrite val_insubd /= mem_rcosets -{1}(mul1g x) mem_mulg. Qed. Lemma coset_morphM : {in 'N(A) &, {morph coset : x y / x * y}}. Proof. move=> x y Nx Ny; apply: val_inj. by rewrite /= !val_coset_prim ?groupM //= rcoset_mul ?nNH. Qed. Canonical coset_morphism := Morphism coset_morphM. Lemma ker_coset_prim : 'ker coset = 'N_H(A). Proof. apply/setP=> z; rewrite !in_setI andbC 2!inE -val_eqE /=. case Nz: (z \in 'N(A)); rewrite ?andbF ?val_coset_prim // !andbT. by apply/eqP/idP=> [<-| Az]; rewrite (rcoset_refl, rcoset_id). Qed. Implicit Type xbar : coset_of. Lemma coset_mem y xbar : y \in xbar -> coset y = xbar. Proof. case: xbar => /= Hx NHx Hxy; apply: val_inj=> /=. case/rcosetsP: NHx (NHx) Hxy => x Nx -> NHx Hxy. by rewrite val_insubd /= (rcoset_eqP Hxy) NHx. Qed. (* coset is an inverse to repr *) Lemma mem_repr_coset xbar : repr xbar \in xbar. Proof. by case: xbar => /= _ /rcosetsP[x _ ->]; apply: mem_repr_rcoset. Qed. Lemma repr_coset1 : repr (1 : coset_of) = 1. Proof. exact: repr_group. Qed. Lemma coset_reprK : cancel (fun xbar => repr xbar) coset. Proof. by move=> xbar; apply: coset_mem (mem_repr_coset xbar). Qed. (* cosetP is slightly stronger than using repr because we only *) (* guarantee repr xbar \in 'N(A) when A is a group. *) Lemma cosetP xbar : {x | x \in 'N(A) & xbar = coset x}. Proof. pose x := repr 'N_xbar(A). have [xbar_x Nx]: x \in xbar /\ x \in 'N(A). apply/setIP; rewrite {}/x; case: xbar => /= _ /rcosetsP[y Ny ->]. by apply: (mem_repr y); rewrite inE rcoset_refl. by exists x; last rewrite (coset_mem xbar_x). Qed. Lemma coset_id x : x \in A -> coset x = 1. Proof. by move=> Ax; apply: coset_mem; apply: mem_gen. Qed. Lemma im_coset : coset @* 'N(A) = setT. Proof. by apply/setP=> xbar; case: (cosetP xbar) => x Nx ->; rewrite inE mem_morphim. Qed. Lemma sub_im_coset (C : {set coset_of}) : C \subset coset @* 'N(A). Proof. by rewrite im_coset subsetT. Qed. Lemma cosetpre_proper C D : (coset @*^-1 C \proper coset @*^-1 D) = (C \proper D). Proof. by rewrite morphpre_proper ?sub_im_coset. Qed. Definition quotient : {set coset_of} := coset @* Q. Lemma quotientE : quotient = coset @* Q. Proof. by []. Qed. End Cosets. Arguments coset_of {gT} H%_g : rename. Arguments coset {gT} H%_g x%_g : rename. Arguments quotient {gT} A%_g H%_g : rename. Arguments coset_reprK {gT H%_g} xbar%_g : rename. Bind Scope group_scope with coset_of. Notation "A / H" := (quotient A H) : group_scope. Section CosetOfGroupTheory. Variables (gT : finGroupType) (H : {group gT}). Implicit Types (A B : {set gT}) (G K : {group gT}) (xbar yb : coset_of H). Implicit Types (C D : {set coset_of H}) (L M : {group coset_of H}). Canonical quotient_group G A : {group coset_of A} := Eval hnf in [group of G / A]. Infix "/" := quotient_group : Group_scope. Lemma val_coset x : x \in 'N(H) -> coset H x :=: H :* x. Proof. by move=> Nx; rewrite val_coset_prim // genGid. Qed. Lemma coset_default x : (x \in 'N(H)) = false -> coset H x = 1. Proof. move=> Nx; apply: val_inj. by rewrite val_insubd /= mem_rcosets /= genGid mulSGid ?normG ?Nx. Qed. Lemma coset_norm xbar : xbar \subset 'N(H). Proof. case: xbar => /= _ /rcosetsP[x Nx ->]. by rewrite genGid mul_subG ?sub1set ?normG. Qed. Lemma ker_coset : 'ker (coset H) = H. Proof. by rewrite ker_coset_prim genGid (setIidPl _) ?normG. Qed. Lemma coset_idr x : x \in 'N(H) -> coset H x = 1 -> x \in H. Proof. by move=> Nx Hx1; rewrite -ker_coset mem_morphpre //= Hx1 set11. Qed. Lemma repr_coset_norm xbar : repr xbar \in 'N(H). Proof. exact: subsetP (coset_norm _) _ (mem_repr_coset _). Qed. Lemma imset_coset G : coset H @: G = G / H. Proof. apply/eqP; rewrite eqEsubset andbC imsetS ?subsetIr //=. apply/subsetP=> _ /imsetP[x Gx ->]. by case Nx: (x \in 'N(H)); rewrite ?(coset_default Nx) ?mem_morphim ?group1. Qed. Lemma val_quotient A : val @: (A / H) = rcosets H 'N_A(H). Proof. apply/setP=> B; apply/imsetP/rcosetsP=> [[xbar Axbar]|[x /setIP[Ax Nx]]] ->{B}. case/morphimP: Axbar => x Nx Ax ->{xbar}. by exists x; [rewrite inE Ax | rewrite /= val_coset]. by exists (coset H x); [apply/morphimP; exists x | rewrite /= val_coset]. Qed. Lemma card_quotient_subnorm A : #|A / H| = #|'N_A(H) : H|. Proof. by rewrite -(card_imset _ val_inj) val_quotient. Qed. Lemma leq_quotient A : #|A / H| <= #|A|. Proof. exact: leq_morphim. Qed. Lemma ltn_quotient A : H :!=: 1 -> H \subset A -> #|A / H| < #|A|. Proof. by move=> ntH sHA; rewrite ltn_morphim // ker_coset (setIidPr sHA) proper1G. Qed. Lemma card_quotient A : A \subset 'N(H) -> #|A / H| = #|A : H|. Proof. by move=> nHA; rewrite card_quotient_subnorm (setIidPl nHA). Qed. Lemma divg_normal G : H <| G -> #|G| %/ #|H| = #|G / H|. Proof. by case/andP=> sHG nHG; rewrite divgS ?card_quotient. Qed. (* Specializing all the morphisms lemmas that have different assumptions *) (* (e.g., because 'ker (coset H) = H), or conclusions (e.g., because we use *) (* A / H rather than coset H @* A). We may want to reevaluate later, and *) (* eliminate variants that aren't used . *) (* Variant of morph1; no specialization for other morph lemmas. *) Lemma coset1 : coset H 1 :=: H. Proof. by rewrite morph1 /= genGid. Qed. (* Variant of kerE. *) Lemma cosetpre1 : coset H @*^-1 1 = H. Proof. by rewrite -kerE ker_coset. Qed. (* Variant of morphimEdom; mophimE[sub] covered by imset_coset. *) (* morph[im|pre]Iim are also covered by im_quotient. *) Lemma im_quotient : 'N(H) / H = setT. Proof. exact: im_coset. Qed. Lemma quotientT : setT / H = setT. Proof. by rewrite -im_quotient; apply: morphimT. Qed. (* Variant of morphimIdom. *) Lemma quotientInorm A : 'N_A(H) / H = A / H. Proof. by rewrite /quotient setIC morphimIdom. Qed. Lemma quotient_setIpre A D : (A :&: coset H @*^-1 D) / H = A / H :&: D. Proof. exact: morphim_setIpre. Qed. Lemma mem_quotient x G : x \in G -> coset H x \in G / H. Proof. by move=> Gx; rewrite -imset_coset imset_f. Qed. Lemma quotientS A B : A \subset B -> A / H \subset B / H. Proof. exact: morphimS. Qed. Lemma quotient0 : set0 / H = set0. Proof. exact: morphim0. Qed. Lemma quotient_set1 x : x \in 'N(H) -> [set x] / H = [set coset H x]. Proof. exact: morphim_set1. Qed. Lemma quotient1 : 1 / H = 1. Proof. exact: morphim1. Qed. Lemma quotientV A : A^-1 / H = (A / H)^-1. Proof. exact: morphimV. Qed. Lemma quotientMl A B : A \subset 'N(H) -> A * B / H = (A / H) * (B / H). Proof. exact: morphimMl. Qed. Lemma quotientMr A B : B \subset 'N(H) -> A * B / H = (A / H) * (B / H). Proof. exact: morphimMr. Qed. Lemma cosetpreM C D : coset H @*^-1 (C * D) = coset H @*^-1 C * coset H @*^-1 D. Proof. by rewrite morphpreMl ?sub_im_coset. Qed. Lemma quotientJ A x : x \in 'N(H) -> A :^ x / H = (A / H) :^ coset H x. Proof. exact: morphimJ. Qed. Lemma quotientU A B : (A :|: B) / H = A / H :|: B / H. Proof. exact: morphimU. Qed. Lemma quotientI A B : (A :&: B) / H \subset A / H :&: B / H. Proof. exact: morphimI. Qed. Lemma quotientY A B : A \subset 'N(H) -> B \subset 'N(H) -> (A <*> B) / H = (A / H) <*> (B / H). Proof. exact: morphimY. Qed. Lemma quotient_homg A : A \subset 'N(H) -> homg (A / H) A. Proof. exact: morphim_homg. Qed. Lemma coset_kerl x y : x \in H -> coset H (x * y) = coset H y. Proof. move=> Hx; case Ny: (y \in 'N(H)); first by rewrite mkerl ?ker_coset. by rewrite !coset_default ?groupMl // (subsetP (normG H)). Qed. Lemma coset_kerr x y : y \in H -> coset H (x * y) = coset H x. Proof. move=> Hy; case Nx: (x \in 'N(H)); first by rewrite mkerr ?ker_coset. by rewrite !coset_default ?groupMr // (subsetP (normG H)). Qed. Lemma rcoset_kercosetP x y : x \in 'N(H) -> y \in 'N(H) -> reflect (coset H x = coset H y) (x \in H :* y). Proof. by rewrite -{6}ker_coset; apply: rcoset_kerP. Qed. Lemma kercoset_rcoset x y : x \in 'N(H) -> y \in 'N(H) -> coset H x = coset H y -> exists2 z, z \in H & x = z * y. Proof. by move=> Nx Ny eqfxy; rewrite -ker_coset; apply: ker_rcoset. Qed. Lemma quotientGI G A : H \subset G -> (G :&: A) / H = G / H :&: A / H. Proof. by rewrite -{1}ker_coset; apply: morphimGI. Qed. Lemma quotientIG A G : H \subset G -> (A :&: G) / H = A / H :&: G / H. Proof. by rewrite -{1}ker_coset; apply: morphimIG. Qed. Lemma quotientD A B : A / H :\: B / H \subset (A :\: B) / H. Proof. exact: morphimD. Qed. Lemma quotientD1 A : (A / H)^# \subset A^# / H. Proof. exact: morphimD1. Qed. Lemma quotientDG A G : H \subset G -> (A :\: G) / H = A / H :\: G / H. Proof. by rewrite -{1}ker_coset; apply: morphimDG. Qed. Lemma quotientK A : A \subset 'N(H) -> coset H @*^-1 (A / H) = H * A. Proof. by rewrite -{8}ker_coset; apply: morphimK. Qed. Lemma quotientYK G : G \subset 'N(H) -> coset H @*^-1 (G / H) = H <*> G. Proof. by move=> nHG; rewrite quotientK ?norm_joinEr. Qed. Lemma quotientGK G : H <| G -> coset H @*^-1 (G / H) = G. Proof. by case/andP; rewrite -{1}ker_coset; apply: morphimGK. Qed. Lemma quotient_class x A : x \in 'N(H) -> A \subset 'N(H) -> x ^: A / H = coset H x ^: (A / H). Proof. exact: morphim_class. Qed. Lemma classes_quotient A : A \subset 'N(H) -> classes (A / H) = [set xA / H | xA in classes A]. Proof. exact: classes_morphim. Qed. Lemma cosetpre_set1 x : x \in 'N(H) -> coset H @*^-1 [set coset H x] = H :* x. Proof. by rewrite -{9}ker_coset; apply: morphpre_set1. Qed. Lemma cosetpre_set1_coset xbar : coset H @*^-1 [set xbar] = xbar. Proof. by case: (cosetP xbar) => x Nx ->; rewrite cosetpre_set1 ?val_coset. Qed. Lemma cosetpreK C : coset H @*^-1 C / H = C. Proof. by rewrite /quotient morphpreK ?sub_im_coset. Qed. (* Variant of morhphim_ker *) Lemma trivg_quotient : H / H = 1. Proof. by rewrite -[X in X / _]ker_coset /quotient morphim_ker. Qed. Lemma quotientS1 G : G \subset H -> G / H = 1. Proof. by move=> sGH; apply/trivgP; rewrite -trivg_quotient quotientS. Qed. Lemma sub_cosetpre M : H \subset coset H @*^-1 M. Proof. by rewrite -{1}ker_coset; apply: ker_sub_pre. Qed. Lemma quotient_proper G K : H <| G -> H <| K -> (G / H \proper K / H) = (G \proper K). Proof. by move=> nHG nHK; rewrite -cosetpre_proper ?quotientGK. Qed. Lemma normal_cosetpre M : H <| coset H @*^-1 M. Proof. by rewrite -{1}ker_coset; apply: ker_normal_pre. Qed. Lemma cosetpreSK C D : (coset H @*^-1 C \subset coset H @*^-1 D) = (C \subset D). Proof. by rewrite morphpreSK ?sub_im_coset. Qed. Lemma sub_quotient_pre A C : A \subset 'N(H) -> (A / H \subset C) = (A \subset coset H @*^-1 C). Proof. exact: sub_morphim_pre. Qed. Lemma sub_cosetpre_quo C G : H <| G -> (coset H @*^-1 C \subset G) = (C \subset G / H). Proof. by move=> nHG; rewrite -cosetpreSK quotientGK. Qed. (* Variant of ker_trivg_morphim. *) Lemma quotient_sub1 A : A \subset 'N(H) -> (A / H \subset [1]) = (A \subset H). Proof. by move=> nHA /=; rewrite -[gval H in RHS]ker_coset ker_trivg_morphim nHA. Qed. Lemma quotientSK A B : A \subset 'N(H) -> (A / H \subset B / H) = (A \subset H * B). Proof. by move=> nHA; rewrite morphimSK ?ker_coset. Qed. Lemma quotientSGK A G : A \subset 'N(H) -> H \subset G -> (A / H \subset G / H) = (A \subset G). Proof. by rewrite -{2}ker_coset; apply: morphimSGK. Qed. Lemma quotient_injG : {in [pred G : {group gT} | H <| G] &, injective (fun G => G / H)}. Proof. by rewrite /normal -{1}ker_coset; apply: morphim_injG. Qed. Lemma quotient_inj G1 G2 : H <| G1 -> H <| G2 -> G1 / H = G2 / H -> G1 :=: G2. Proof. by rewrite /normal -[in mem H]ker_coset; apply: morphim_inj. Qed. Lemma quotient_neq1 A : H <| A -> (A / H != 1) = (H \proper A). Proof. case/andP=> sHA nHA; rewrite /proper sHA -trivg_quotient eqEsubset andbC. by rewrite quotientS //= quotientSGK. Qed. Lemma quotient_gen A : A \subset 'N(H) -> <<A>> / H = <<A / H>>. Proof. exact: morphim_gen. Qed. Lemma cosetpre_gen C : 1 \in C -> coset H @*^-1 <<C>> = <<coset H @*^-1 C>>. Proof. by move=> C1; rewrite morphpre_gen ?sub_im_coset. Qed. Lemma quotientR A B : A \subset 'N(H) -> B \subset 'N(H) -> [~: A, B] / H = [~: A / H, B / H]. Proof. exact: morphimR. Qed. Lemma quotient_norm A : 'N(A) / H \subset 'N(A / H). Proof. exact: morphim_norm. Qed. Lemma quotient_norms A B : A \subset 'N(B) -> A / H \subset 'N(B / H). Proof. exact: morphim_norms. Qed. Lemma quotient_subnorm A B : 'N_A(B) / H \subset 'N_(A / H)(B / H). Proof. exact: morphim_subnorm. Qed. Lemma quotient_normal A B : A <| B -> A / H <| B / H. Proof. exact: morphim_normal. Qed. Lemma quotient_cent1 x : 'C[x] / H \subset 'C[coset H x]. Proof. case Nx: (x \in 'N(H)); first exact: morphim_cent1. by rewrite coset_default // cent11T subsetT. Qed. Lemma quotient_cent1s A x : A \subset 'C[x] -> A / H \subset 'C[coset H x]. Proof. by move=> sAC; apply: subset_trans (quotientS sAC) (quotient_cent1 x). Qed. Lemma quotient_subcent1 A x : 'C_A[x] / H \subset 'C_(A / H)[coset H x]. Proof. exact: subset_trans (quotientI _ _) (setIS _ (quotient_cent1 x)). Qed. Lemma quotient_cent A : 'C(A) / H \subset 'C(A / H). Proof. exact: morphim_cent. Qed. Lemma quotient_cents A B : A \subset 'C(B) -> A / H \subset 'C(B / H). Proof. exact: morphim_cents. Qed. Lemma quotient_abelian A : abelian A -> abelian (A / H). Proof. exact: morphim_abelian. Qed. Lemma quotient_subcent A B : 'C_A(B) / H \subset 'C_(A / H)(B / H). Proof. exact: morphim_subcent. Qed. Lemma norm_quotient_pre A C : A \subset 'N(H) -> A / H \subset 'N(C) -> A \subset 'N(coset H @*^-1 C). Proof. by move/sub_quotient_pre=> -> /subset_trans-> //; apply: morphpre_norm. Qed. Lemma cosetpre_normal C D : (coset H @*^-1 C <| coset H @*^-1 D) = (C <| D). Proof. by rewrite morphpre_normal ?sub_im_coset. Qed. Lemma quotient_normG G : H <| G -> 'N(G) / H = 'N(G / H). Proof. case/andP=> sHG nHG. by rewrite [_ / _]morphim_normG ?ker_coset // im_coset setTI. Qed. Lemma quotient_subnormG A G : H <| G -> 'N_A(G) / H = 'N_(A / H)(G / H). Proof. by case/andP=> sHG nHG; rewrite -morphim_subnormG ?ker_coset. Qed. Lemma cosetpre_cent1 x : 'C_('N(H))[x] \subset coset H @*^-1 'C[coset H x]. Proof. case Nx: (x \in 'N(H)); first by rewrite morphpre_cent1. by rewrite coset_default // cent11T morphpreT subsetIl. Qed. Lemma cosetpre_cent1s C x : coset H @*^-1 C \subset 'C[x] -> C \subset 'C[coset H x]. Proof. move=> sC; rewrite -cosetpreSK; apply: subset_trans (cosetpre_cent1 x). by rewrite subsetI subsetIl. Qed. Lemma cosetpre_subcent1 C x : 'C_(coset H @*^-1 C)[x] \subset coset H @*^-1 'C_C[coset H x]. Proof. by rewrite -morphpreIdom -setIA setICA morphpreI setIS // cosetpre_cent1. Qed. Lemma cosetpre_cent A : 'C_('N(H))(A) \subset coset H @*^-1 'C(A / H). Proof. exact: morphpre_cent. Qed. Lemma cosetpre_cents A C : coset H @*^-1 C \subset 'C(A) -> C \subset 'C(A / H). Proof. by apply: morphpre_cents; rewrite ?sub_im_coset. Qed. Lemma cosetpre_subcent C A : 'C_(coset H @*^-1 C)(A) \subset coset H @*^-1 'C_C(A / H). Proof. exact: morphpre_subcent. Qed. Lemma restrm_quotientE G A (nHG : G \subset 'N(H)) : A \subset G -> restrm nHG (coset H) @* A = A / H. Proof. exact: restrmEsub. Qed. Section InverseImage. Variables (G : {group gT}) (Kbar : {group coset_of H}). Hypothesis nHG : H <| G. Variant inv_quotient_spec (P : pred {group gT}) : Prop := InvQuotientSpec K of Kbar :=: K / H & H \subset K & P K. Lemma inv_quotientS : Kbar \subset G / H -> inv_quotient_spec (fun K => K \subset G). Proof. case/andP: nHG => sHG nHG' sKbarG. have sKdH: Kbar \subset 'N(H) / H by rewrite (subset_trans sKbarG) ?morphimS. exists (coset H @*^-1 Kbar)%G; first by rewrite cosetpreK. by rewrite -{1}ker_coset morphpreS ?sub1G. by rewrite sub_cosetpre_quo. Qed. Lemma inv_quotientN : Kbar <| G / H -> inv_quotient_spec (fun K => K <| G). Proof. move=> nKbar; case/inv_quotientS: (normal_sub nKbar) => K defKbar sHK sKG. exists K => //; rewrite defKbar -cosetpre_normal !quotientGK // in nKbar. exact: normalS nHG. Qed. End InverseImage. Lemma quotientMidr A : A * H / H = A / H. Proof. by rewrite [_ /_]morphimMr ?normG //= -!quotientE trivg_quotient mulg1. Qed. Lemma quotientMidl A : H * A / H = A / H. Proof. by rewrite [_ /_]morphimMl ?normG //= -!quotientE trivg_quotient mul1g. Qed. Lemma quotientYidr G : G \subset 'N(H) -> G <*> H / H = G / H. Proof. move=> nHG; rewrite -genM_join quotient_gen ?mul_subG ?normG //. by rewrite quotientMidr genGid. Qed. Lemma quotientYidl G : G \subset 'N(H) -> H <*> G / H = G / H. Proof. by move=> nHG; rewrite joingC quotientYidr. Qed. Section Injective. Variables (G : {group gT}). Hypotheses (nHG : G \subset 'N(H)) (tiHG : H :&: G = 1). Lemma quotient_isom : isom G (G / H) (restrm nHG (coset H)). Proof. by apply/isomP; rewrite ker_restrm setIC ker_coset tiHG im_restrm. Qed. Lemma quotient_isog : isog G (G / H). Proof. exact: isom_isog quotient_isom. Qed. End Injective. End CosetOfGroupTheory. Notation "A / H" := (quotient_group A H) : Group_scope. Section Quotient1. Variables (gT : finGroupType) (A : {set gT}). Lemma coset1_injm : 'injm (@coset gT 1). Proof. by rewrite ker_coset /=. Qed. Lemma quotient1_isom : isom A (A / 1) (coset 1). Proof. by apply: sub_isom coset1_injm; rewrite ?norms1. Qed. Lemma quotient1_isog : isog A (A / 1). Proof. by apply: isom_isog quotient1_isom; apply: norms1. Qed. End Quotient1. Section QuotientMorphism. Variable (gT rT : finGroupType) (G H : {group gT}) (f : {morphism G >-> rT}). Implicit Types A : {set gT}. Implicit Types B : {set (coset_of H)}. Hypotheses (nsHG : H <| G). Let sHG : H \subset G := normal_sub nsHG. Let nHG : G \subset 'N(H) := normal_norm nsHG. Let nfHfG : f @* G \subset 'N(f @* H) := morphim_norms f nHG. Notation fH := (coset (f @* H) \o f). Lemma quotm_dom_proof : G \subset 'dom fH. Proof. by rewrite -sub_morphim_pre. Qed. Notation fH_G := (restrm quotm_dom_proof fH). Lemma quotm_ker_proof : 'ker (coset H) \subset 'ker fH_G. Proof. by rewrite ker_restrm ker_comp !ker_coset morphpreIdom morphimK ?mulG_subr. Qed. Definition quotm := factm quotm_ker_proof nHG. Canonical quotm_morphism := [morphism G / H of quotm]. Lemma quotmE x : x \in G -> quotm (coset H x) = coset (f @* H) (f x). Proof. exact: factmE. Qed. Lemma morphim_quotm A : quotm @* (A / H) = f @* A / f @* H. Proof. by rewrite morphim_factm [LHS]morphim_restrm morphim_comp morphimIdom. Qed. Lemma morphpre_quotm Abar : quotm @*^-1 (Abar / f @* H) = f @*^-1 Abar / H. Proof. rewrite morphpre_factm morphpre_restrm morphpre_comp /=. rewrite morphpreIdom -[Abar / _]quotientInorm quotientK ?subsetIr //=. rewrite morphpreMl ?morphimS // morphimK // [_ * H]normC ?subIset ?nHG //. rewrite -quotientE -mulgA quotientMidl /= setIC -morphpreIim setIA. by rewrite (setIidPl nfHfG) morphpreIim -morphpreMl ?sub1G ?mul1g. Qed. Lemma ker_quotm : 'ker quotm = 'ker f / H. Proof. by rewrite -morphpre_quotm /quotient morphim1. Qed. Lemma injm_quotm : 'injm f -> 'injm quotm. Proof. by move/trivgP=> /= kf1; rewrite ker_quotm kf1 quotientE morphim1. Qed. End QuotientMorphism. Section EqIso. Variables (gT : finGroupType) (G H : {group gT}). Hypothesis (eqGH : G :=: H). Lemma im_qisom_proof : 'N(H) \subset 'N(G). Proof. by rewrite eqGH. Qed. Lemma qisom_ker_proof : 'ker (coset G) \subset 'ker (coset H). Proof. by rewrite eqGH. Qed. Lemma qisom_restr_proof : setT \subset 'N(H) / G. Proof. by rewrite eqGH im_quotient. Qed. Definition qisom := restrm qisom_restr_proof (factm qisom_ker_proof im_qisom_proof). Canonical qisom_morphism := Eval hnf in [morphism of qisom]. Lemma qisomE x : qisom (coset G x) = coset H x. Proof. case Nx: (x \in 'N(H)); first exact: factmE. by rewrite !coset_default ?eqGH ?morph1. Qed. Lemma val_qisom Gx : val (qisom Gx) = val Gx. Proof. by case: (cosetP Gx) => x Nx ->{Gx}; rewrite qisomE /= !val_coset -?eqGH. Qed. Lemma morphim_qisom A : qisom @* (A / G) = A / H. Proof. by rewrite morphim_restrm setTI morphim_factm. Qed. Lemma morphpre_qisom A : qisom @*^-1 (A / H) = A / G. Proof. rewrite morphpre_restrm setTI morphpre_factm eqGH. by rewrite morphpreK // im_coset subsetT. Qed. Lemma injm_qisom : 'injm qisom. Proof. by rewrite -quotient1 -morphpre_qisom morphpreS ?sub1G. Qed. Lemma im_qisom : qisom @* setT = setT. Proof. by rewrite -{2}im_quotient morphim_qisom eqGH im_quotient. Qed. Lemma qisom_isom : isom setT setT qisom. Proof. by apply/isomP; rewrite injm_qisom im_qisom. Qed. Lemma qisom_isog : [set: coset_of G] \isog [set: coset_of H]. Proof. exact: isom_isog qisom_isom. Qed. Lemma qisom_inj : injective qisom. Proof. by move=> x y; apply: (injmP injm_qisom); rewrite inE. Qed. Lemma morphim_qisom_inj : injective (fun Gx => qisom @* Gx). Proof. by move=> Gx Gy; apply: injm_morphim_inj; rewrite (injm_qisom, subsetT). Qed. End EqIso. Arguments qisom_inj {gT G H} eqGH [x1 x2]. Arguments morphim_qisom_inj {gT G H} eqGH [x1 x2]. Section FirstIsomorphism. Variables aT rT : finGroupType. Lemma first_isom (G : {group aT}) (f : {morphism G >-> rT}) : {g : {morphism G / 'ker f >-> rT} | 'injm g & forall A : {set aT}, g @* (A / 'ker f) = f @* A}. Proof. have nkG := ker_norm f. have skk: 'ker (coset ('ker f)) \subset 'ker f by rewrite ker_coset. exists (factm_morphism skk nkG) => /=; last exact: morphim_factm. by rewrite ker_factm -quotientE trivg_quotient. Qed. Variables (G H : {group aT}) (f : {morphism G >-> rT}). Hypothesis sHG : H \subset G. Lemma first_isog : (G / 'ker f) \isog (f @* G). Proof. by case: (first_isom f) => g injg im_g; apply/isogP; exists g; rewrite ?im_g. Qed. Lemma first_isom_loc : {g : {morphism H / 'ker_H f >-> rT} | 'injm g & forall A : {set aT}, A \subset H -> g @* (A / 'ker_H f) = f @* A}. Proof. case: (first_isom (restrm_morphism sHG f)). rewrite ker_restrm => g injg im_g; exists g => // A sAH. by rewrite im_g morphim_restrm (setIidPr sAH). Qed. Lemma first_isog_loc : (H / 'ker_H f) \isog (f @* H). Proof. by case: first_isom_loc => g injg im_g; apply/isogP; exists g; rewrite ?im_g. Qed. End FirstIsomorphism. Section SecondIsomorphism. Variables (gT : finGroupType) (H K : {group gT}). Hypothesis nKH : H \subset 'N(K). Lemma second_isom : {f : {morphism H / (K :&: H) >-> coset_of K} | 'injm f & forall A : {set gT}, A \subset H -> f @* (A / (K :&: H)) = A / K}. Proof. have ->: K :&: H = 'ker_H (coset K) by rewrite ker_coset setIC. exact: first_isom_loc. Qed. Lemma second_isog : H / (K :&: H) \isog H / K. Proof. by rewrite setIC -{1 3}(ker_coset K); apply: first_isog_loc. Qed. Lemma weak_second_isog : H / (K :&: H) \isog H * K / K. Proof. by rewrite quotientMidr; apply: second_isog. Qed. End SecondIsomorphism. Section ThirdIsomorphism. Variables (gT : finGroupType) (G H K : {group gT}). Lemma homg_quotientS (A : {set gT}) : A \subset 'N(H) -> A \subset 'N(K) -> H \subset K -> A / K \homg A / H. Proof. rewrite -!(gen_subG A) /=; set L := <<A>> => nHL nKL sKH. have sub_ker: 'ker (restrm nHL (coset H)) \subset 'ker (restrm nKL (coset K)). by rewrite !ker_restrm !ker_coset setIS. have sAL: A \subset L := subset_gen A; rewrite -(setIidPr sAL). rewrite -[_ / H](morphim_restrm nHL) -[_ / K](morphim_restrm nKL) /=. by rewrite -(morphim_factm sub_ker (subxx L)) morphim_homg ?morphimS. Qed. Hypothesis sHK : H \subset K. Hypothesis snHG : H <| G. Hypothesis snKG : K <| G. Theorem third_isom : {f : {morphism (G / H) / (K / H) >-> coset_of K} | 'injm f & forall A : {set gT}, A \subset G -> f @* (A / H / (K / H)) = A / K}. Proof. have [[sKG nKG] [sHG nHG]] := (andP snKG, andP snHG). have sHker: 'ker (coset H) \subset 'ker (restrm nKG (coset K)). by rewrite ker_restrm !ker_coset subsetI sHG. have:= first_isom_loc (factm_morphism sHker nHG) (subxx _) => /=. rewrite ker_factm_loc ker_restrm ker_coset !(setIidPr sKG) /= -!quotientE. case=> f injf im_f; exists f => // A sAG; rewrite im_f ?morphimS //. by rewrite morphim_factm morphim_restrm (setIidPr sAG). Qed. Theorem third_isog : (G / H / (K / H)) \isog (G / K). Proof. by case: third_isom => f inj_f im_f; apply/isogP; exists f; rewrite ?im_f. Qed. End ThirdIsomorphism. Lemma char_from_quotient (gT : finGroupType) (G H K : {group gT}) : H <| K -> H \char G -> K / H \char G / H -> K \char G. Proof. case/andP=> sHK nHK chHG. have nsHG := char_normal chHG; have [sHG nHG] := andP nsHG. case/charP; rewrite quotientSGK // => sKG /= chKG. apply/charP; split=> // f injf Gf; apply/morphim_fixP => //. rewrite -(quotientSGK _ sHK); last by rewrite -morphimIim Gf subIset ?nHG. have{chHG} Hf: f @* H = H by case/charP: chHG => _; apply. set q := quotm_morphism f nsHG; have{injf}: 'injm q by apply: injm_quotm. have: q @* _ = _ := morphim_quotm _ _ _; move: q; rewrite Hf => q im_q injq. by rewrite -im_q chKG // im_q Gf. Qed. (* Counting lemmas for morphisms. *) Section CardMorphism. Variables (aT rT : finGroupType) (D : {group aT}) (f : {morphism D >-> rT}). Implicit Types G H : {group aT}. Implicit Types L M : {group rT}. Lemma card_morphim G : #|f @* G| = #|D :&: G : 'ker f|. Proof. rewrite -morphimIdom -indexgI -card_quotient; last first. by rewrite normsI ?normG ?subIset ?ker_norm. by apply: esym (card_isog _); rewrite first_isog_loc ?subsetIl. Qed. Lemma dvdn_morphim G : #|f @* G| %| #|G|. Proof. rewrite card_morphim (dvdn_trans (dvdn_indexg _ _)) //. by rewrite cardSg ?subsetIr. Qed. Lemma logn_morphim p G : logn p #|f @* G| <= logn p #|G|. Proof. by rewrite dvdn_leq_log ?dvdn_morphim. Qed. Lemma coprime_morphl G p : coprime #|G| p -> coprime #|f @* G| p. Proof. exact: coprime_dvdl (dvdn_morphim G). Qed. Lemma coprime_morphr G p : coprime p #|G| -> coprime p #|f @* G|. Proof. exact: coprime_dvdr (dvdn_morphim G). Qed. Lemma coprime_morph G H : coprime #|G| #|H| -> coprime #|f @* G| #|f @* H|. Proof. by move=> coGH; rewrite coprime_morphl // coprime_morphr. Qed. Lemma index_morphim_ker G H : H \subset G -> G \subset D -> (#|f @* G : f @* H| * #|'ker_G f : H|)%N = #|G : H|. Proof. move=> sHG sGD; apply/eqP. rewrite -(eqn_pmul2l (cardG_gt0 (f @* H))) mulnA Lagrange ?morphimS //. rewrite !card_morphim (setIidPr sGD) (setIidPr (subset_trans sHG sGD)). rewrite -(eqn_pmul2l (cardG_gt0 ('ker_H f))) /=. by rewrite -{1}(setIidPr sHG) setIAC mulnCA mulnC mulnA !LagrangeI Lagrange. Qed. Lemma index_morphim G H : G :&: H \subset D -> #|f @* G : f @* H| %| #|G : H|. Proof. move=> dGH; rewrite -(indexgI G) -(setIidPr dGH) setIA. apply: dvdn_trans (indexSg (subsetIl _ H) (subsetIr D G)). rewrite -index_morphim_ker ?subsetIl ?subsetIr ?dvdn_mulr //= morphimIdom. by rewrite indexgS ?morphimS ?subsetIr. Qed. Lemma index_injm G H : 'injm f -> G \subset D -> #|f @* G : f @* H| = #|G : H|. Proof. move=> injf dG; rewrite -{2}(setIidPr dG) -(indexgI _ H) /=. rewrite -index_morphim_ker ?subsetIl ?subsetIr //= setIAC morphimIdom setIC. rewrite injmI ?subsetIr // indexgI /= morphimIdom setIC ker_injm //. by rewrite -(indexgI (1 :&: _)) /= -setIA !(setIidPl (sub1G _)) indexgg muln1. Qed. Lemma card_morphpre L : L \subset f @* D -> #|f @*^-1 L| = (#|'ker f| * #|L|)%N. Proof. move/morphpreK=> {2} <-; rewrite card_morphim morphpreIdom. by rewrite Lagrange // morphpreS ?sub1G. Qed. Lemma index_morphpre L M : L \subset f @* D -> #|f @*^-1 L : f @*^-1 M| = #|L : M|. Proof. move=> dL; rewrite -!divgI -morphpreI /= card_morphpre //. have: L :&: M \subset f @* D by rewrite subIset ?dL. by move/card_morphpre->; rewrite divnMl ?cardG_gt0. Qed. End CardMorphism. Lemma card_homg (aT rT : finGroupType) (G : {group aT}) (R : {group rT}) : G \homg R -> #|G| %| #|R|. Proof. by case/homgP=> f <-; rewrite card_morphim setIid dvdn_indexg. Qed. Section CardCosetpre. Variables (gT : finGroupType) (G H K : {group gT}) (L M : {group coset_of H}). Lemma dvdn_quotient : #|G / H| %| #|G|. Proof. exact: dvdn_morphim. Qed. Lemma index_quotient_ker : K \subset G -> G \subset 'N(H) -> (#|G / H : K / H| * #|G :&: H : K|)%N = #|G : K|. Proof. by rewrite -{5}(ker_coset H); apply: index_morphim_ker. Qed. Lemma index_quotient : G :&: K \subset 'N(H) -> #|G / H : K / H| %| #|G : K|. Proof. exact: index_morphim. Qed. Lemma index_quotient_eq : G :&: H \subset K -> K \subset G -> G \subset 'N(H) -> #|G / H : K / H| = #|G : K|. Proof. move=> sGH_K sKG sGN; rewrite -index_quotient_ker {sKG sGN}//. by rewrite -(indexgI _ K) (setIidPl sGH_K) indexgg muln1. Qed. Lemma card_cosetpre : #|coset H @*^-1 L| = (#|H| * #|L|)%N. Proof. by rewrite card_morphpre ?ker_coset ?sub_im_coset. Qed. Lemma index_cosetpre : #|coset H @*^-1 L : coset H @*^-1 M| = #|L : M|. Proof. by rewrite index_morphpre ?sub_im_coset. Qed. End CardCosetpre.
Defs.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, Kim Morrison -/ import Mathlib.Algebra.Notation.Support import Mathlib.Data.Set.Finite.Basic /-! # Type of functions with finite support For any type `α` and any type `M` with zero, we define the type `Finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `MonoidAlgebra R M` and `AddMonoidAlgebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `AddMonoidAlgebra`s, hence they use `Finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `LinearIndependent`) is defined as a map `Finsupp.linearCombination : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `Multiset α ≃+ α →₀ ℕ`; * `FreeAbelianGroup α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `Finsupp` elements, which is defined in `Mathlib/Algebra/BigOperators/Finsupp/Basic.lean`. Many constructions based on `α →₀ M` are `def`s rather than `abbrev`s to avoid reusing unwanted type class instances. E.g., `MonoidAlgebra`, `AddMonoidAlgebra`, and types based on these two have non-pointwise multiplication. ## Main declarations * `Finsupp`: The type of finitely supported functions from `α` to `β`. * `Finsupp.onFinset`: The restriction of a function to a `Finset` as a `Finsupp`. * `Finsupp.mapRange`: Composition of a `ZeroHom` with a `Finsupp`. * `Finsupp.embDomain`: Maps the domain of a `Finsupp` by an embedding. * `Finsupp.zipWith`: Postcomposition of two `Finsupp`s with a function `f` such that `f 0 0 = 0`. ## Notations This file adds `α →₀ M` as a global notation for `Finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `Finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `Zero` or `(Add)(Comm)Monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * Expand the list of definitions and important lemmas to the module docstring. -/ assert_not_exists CompleteLattice Monoid noncomputable section open Finset Function variable {α β γ ι M M' N P G H R S : Type*} /-- `Finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure Finsupp (α : Type*) (M : Type*) [Zero M] where /-- The support of a finitely supported function (aka `Finsupp`). -/ support : Finset α /-- The underlying function of a bundled finitely supported function (aka `Finsupp`). -/ toFun : α → M /-- The witness that the support of a `Finsupp` is indeed the exact locus where its underlying function is nonzero. -/ mem_support_toFun : ∀ a, a ∈ support ↔ toFun a ≠ 0 @[inherit_doc] infixr:25 " →₀ " => Finsupp namespace Finsupp /-! ### Basic declarations about `Finsupp` -/ section Basic variable [Zero M] instance instFunLike : FunLike (α →₀ M) α M := ⟨toFun, by rintro ⟨s, f, hf⟩ ⟨t, g, hg⟩ (rfl : f = g) congr ext a exact (hf _).trans (hg _).symm⟩ @[ext] theorem ext {f g : α →₀ M} (h : ∀ a, f a = g a) : f = g := DFunLike.ext _ _ h lemma ne_iff {f g : α →₀ M} : f ≠ g ↔ ∃ a, f a ≠ g a := DFunLike.ne_iff @[simp, norm_cast] theorem coe_mk (f : α → M) (s : Finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance instZero : Zero (α →₀ M) := ⟨⟨∅, 0, fun _ => ⟨fun h ↦ (notMem_empty _ h).elim, fun H => (H rfl).elim⟩⟩⟩ @[simp, norm_cast] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl theorem zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] theorem support_zero : (0 : α →₀ M).support = ∅ := rfl instance instInhabited : Inhabited (α →₀ M) := ⟨0⟩ @[simp] theorem mem_support_iff {f : α →₀ M} : ∀ {a : α}, a ∈ f.support ↔ f a ≠ 0 := @(f.mem_support_toFun) @[simp, norm_cast] theorem fun_support_eq (f : α →₀ M) : Function.support f = f.support := Set.ext fun _x => mem_support_iff.symm theorem notMem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[deprecated (since := "2025-05-23")] alias not_mem_support_iff := notMem_support_iff @[simp, norm_cast] theorem coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, DFunLike.coe_fn_eq] theorem ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨fun h => h ▸ ⟨rfl, fun _ _ => rfl⟩, fun ⟨h₁, h₂⟩ => ext fun a => by classical exact if h : a ∈ f.support then h₂ a h else by have hf : f a = 0 := notMem_support_iff.1 h have hg : g a = 0 := by rwa [h₁, notMem_support_iff] at h rw [hf, hg]⟩ @[simp] theorem support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := mod_cast @Function.support_eq_empty_iff _ _ _ f theorem support_nonempty_iff {f : α →₀ M} : f.support.Nonempty ↔ f ≠ 0 := by simp only [Finsupp.support_eq_empty, Finset.nonempty_iff_ne_empty, Ne] theorem card_support_eq_zero {f : α →₀ M} : #f.support = 0 ↔ f = 0 := by simp instance instDecidableEq [DecidableEq α] [DecidableEq M] : DecidableEq (α →₀ M) := fun f g => decidable_of_iff (f.support = g.support ∧ ∀ a ∈ f.support, f a = g a) ext_iff'.symm theorem finite_support (f : α →₀ M) : Set.Finite (Function.support f) := f.fun_support_eq.symm ▸ f.support.finite_toSet theorem support_subset_iff {s : Set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ ∀ a ∉ s, f a = 0 := by simp only [Set.subset_def, mem_coe, mem_support_iff, forall_congr' fun a => not_imp_comm] /-- Given `Finite α`, `equivFunOnFinite` is the `Equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equivFunOnFinite [Finite α] : (α →₀ M) ≃ (α → M) where toFun := (⇑) invFun f := mk (Function.support f).toFinite.toFinset f fun _a => Set.Finite.mem_toFinset _ @[simp] theorem equivFunOnFinite_symm_coe {α} [Finite α] (f : α →₀ M) : equivFunOnFinite.symm f = f := equivFunOnFinite.symm_apply_apply f @[simp] lemma coe_equivFunOnFinite_symm {α} [Finite α] (f : α → M) : ⇑(equivFunOnFinite.symm f) = f := rfl /-- If `α` has a unique term, the type of finitely supported functions `α →₀ β` is equivalent to `β`. -/ @[simps!] noncomputable def _root_.Equiv.finsuppUnique {ι : Type*} [Unique ι] : (ι →₀ M) ≃ M := Finsupp.equivFunOnFinite.trans (Equiv.funUnique ι M) @[ext] theorem unique_ext [Unique α] {f g : α →₀ M} (h : f default = g default) : f = g := ext fun a => by rwa [Unique.eq_default a] end Basic /-! ### Declarations about `onFinset` -/ section OnFinset variable [Zero M] private irreducible_def onFinset_support (s : Finset α) (f : α → M) : Finset α := haveI := Classical.decEq M {a ∈ s | f a ≠ 0} /-- `Finsupp.onFinset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function must be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def onFinset (s : Finset α) (f : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s) : α →₀ M where support := onFinset_support s f toFun := f mem_support_toFun := by classical simpa [onFinset_support_def] @[simp, norm_cast] lemma coe_onFinset (s : Finset α) (f : α → M) (hf) : onFinset s f hf = f := rfl @[simp] theorem onFinset_apply {s : Finset α} {f : α → M} {hf a} : (onFinset s f hf : α →₀ M) a = f a := rfl theorem support_onFinset [DecidableEq M] {s : Finset α} {f : α → M} (hf : ∀ a : α, f a ≠ 0 → a ∈ s) : (Finsupp.onFinset s f hf).support = {a ∈ s | f a ≠ 0} := by dsimp [onFinset]; rw [onFinset_support]; congr @[simp] theorem support_onFinset_subset {s : Finset α} {f : α → M} {hf} : (onFinset s f hf).support ⊆ s := by classical rw [support_onFinset] exact filter_subset (f · ≠ 0) s theorem mem_support_onFinset {s : Finset α} {f : α → M} (hf : ∀ a : α, f a ≠ 0 → a ∈ s) {a : α} : a ∈ (Finsupp.onFinset s f hf).support ↔ f a ≠ 0 := by rw [Finsupp.mem_support_iff, Finsupp.onFinset_apply] end OnFinset section OfSupportFinite variable [Zero M] /-- The natural `Finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def ofSupportFinite (f : α → M) (hf : (Function.support f).Finite) : α →₀ M where support := hf.toFinset toFun := f mem_support_toFun _ := hf.mem_toFinset theorem ofSupportFinite_coe {f : α → M} {hf : (Function.support f).Finite} : (ofSupportFinite f hf : α → M) = f := rfl instance instCanLift : CanLift (α → M) (α →₀ M) (⇑) fun f => (Function.support f).Finite where prf f hf := ⟨ofSupportFinite f hf, rfl⟩ end OfSupportFinite /-! ### Declarations about `mapRange` -/ section MapRange variable [Zero M] [Zero N] [Zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `mapRange f hf g : α →₀ N`, which is well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled (defined in `Mathlib/Data/Finsupp/Basic.lean`): * `Finsupp.mapRange.equiv` * `Finsupp.mapRange.zeroHom` * `Finsupp.mapRange.addMonoidHom` * `Finsupp.mapRange.addEquiv` * `Finsupp.mapRange.linearMap` * `Finsupp.mapRange.linearEquiv` -/ def mapRange (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := onFinset g.support (f ∘ g) fun a => by rw [mem_support_iff, not_imp_not]; exact fun H => (congr_arg f H).trans hf @[simp] theorem mapRange_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : mapRange f hf g a = f (g a) := rfl @[simp] theorem mapRange_zero {f : M → N} {hf : f 0 = 0} : mapRange f hf (0 : α →₀ M) = 0 := ext fun _ => by simp only [hf, zero_apply, mapRange_apply] @[simp] theorem mapRange_id (g : α →₀ M) : mapRange id rfl g = g := ext fun _ => rfl theorem mapRange_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : mapRange (f ∘ f₂) h g = mapRange f hf (mapRange f₂ hf₂ g) := ext fun _ => rfl @[simp] lemma mapRange_mapRange (e₁ : N → P) (e₂ : M → N) (he₁ he₂) (f : α →₀ M) : mapRange e₁ he₁ (mapRange e₂ he₂ f) = mapRange (e₁ ∘ e₂) (by simp [*]) f := ext fun _ ↦ rfl theorem support_mapRange {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (mapRange f hf g).support ⊆ g.support := support_onFinset_subset theorem support_mapRange_of_injective {e : M → N} (he0 : e 0 = 0) (f : ι →₀ M) (he : Function.Injective e) : (Finsupp.mapRange e he0 f).support = f.support := by ext simp only [Finsupp.mem_support_iff, Ne, Finsupp.mapRange_apply] exact he.ne_iff' he0 lemma range_mapRange (e : M → N) (he₀ : e 0 = 0) : Set.range (Finsupp.mapRange (α := α) e he₀) = {g | ∀ i, g i ∈ Set.range e} := by ext g simp only [Set.mem_range, Set.mem_setOf] constructor · rintro ⟨g, rfl⟩ i simp · intro h classical choose f h using h use onFinset g.support (fun x ↦ if x ∈ g.support then f x else 0) (by aesop) ext i simp only [mapRange_apply, onFinset_apply] split_ifs <;> simp_all /-- `Finsupp.mapRange` of a injective function is injective. -/ lemma mapRange_injective (e : M → N) (he₀ : e 0 = 0) (he : Injective e) : Injective (Finsupp.mapRange (α := α) e he₀) := by intro a b h rw [Finsupp.ext_iff] at h ⊢ simpa only [mapRange_apply, he.eq_iff] using h /-- `Finsupp.mapRange` of a surjective function is surjective. -/ lemma mapRange_surjective (e : M → N) (he₀ : e 0 = 0) (he : Surjective e) : Surjective (Finsupp.mapRange (α := α) e he₀) := by rw [← Set.range_eq_univ, range_mapRange, he.range_eq] simp end MapRange /-! ### Declarations about `embDomain` -/ section EmbDomain variable [Zero M] [Zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `Finsupp.embDomain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def embDomain (f : α ↪ β) (v : α →₀ M) : β →₀ M where support := v.support.map f toFun a₂ := haveI := Classical.decEq β if h : a₂ ∈ v.support.map f then v (v.support.choose (fun a₁ => f a₁ = a₂) (by rcases Finset.mem_map.1 h with ⟨a, ha, rfl⟩ exact ExistsUnique.intro a ⟨ha, rfl⟩ fun b ⟨_, hb⟩ => f.injective hb)) else 0 mem_support_toFun a₂ := by dsimp split_ifs with h · simp only [h, true_iff] rw [← notMem_support_iff, not_not] classical apply Finset.choose_mem · simp only [h, not_true_eq_false] @[simp] theorem support_embDomain (f : α ↪ β) (v : α →₀ M) : (embDomain f v).support = v.support.map f := rfl @[simp] theorem embDomain_zero (f : α ↪ β) : (embDomain f 0 : β →₀ M) = 0 := rfl @[simp] theorem embDomain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : embDomain f v (f a) = v a := by classical simp_rw [embDomain, coe_mk, mem_map'] split_ifs with h · refine congr_arg (v : α → M) (f.inj' ?_) exact Finset.choose_property (fun a₁ => f a₁ = f a) _ _ · exact (notMem_support_iff.1 h).symm theorem embDomain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ Set.range f) : embDomain f v a = 0 := by classical refine dif_neg (mt (fun h => ?_) h) rcases Finset.mem_map.1 h with ⟨a, _h, rfl⟩ exact Set.mem_range_self a theorem embDomain_injective (f : α ↪ β) : Function.Injective (embDomain f : (α →₀ M) → β →₀ M) := fun l₁ l₂ h => ext fun a => by simpa only [embDomain_apply] using DFunLike.ext_iff.1 h (f a) @[simp] theorem embDomain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : embDomain f l₁ = embDomain f l₂ ↔ l₁ = l₂ := (embDomain_injective f).eq_iff @[simp] theorem embDomain_eq_zero {f : α ↪ β} {l : α →₀ M} : embDomain f l = 0 ↔ l = 0 := (embDomain_injective f).eq_iff' <| embDomain_zero f theorem embDomain_mapRange (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : embDomain f (mapRange g hg p) = mapRange g hg (embDomain f p) := by ext a by_cases h : a ∈ Set.range f · rcases h with ⟨a', rfl⟩ rw [mapRange_apply, embDomain_apply, embDomain_apply, mapRange_apply] · rw [mapRange_apply, embDomain_notin_range, embDomain_notin_range, ← hg] <;> assumption end EmbDomain /-! ### Declarations about `zipWith` -/ section ZipWith variable [Zero M] [Zero N] [Zero P] /-- Given finitely supported functions `g₁ : α →₀ M` and `g₂ : α →₀ N` and function `f : M → N → P`, `Finsupp.zipWith f hf g₁ g₂` is the finitely supported function `α →₀ P` satisfying `zipWith f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, which is well-defined when `f 0 0 = 0`. -/ def zipWith (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ P := onFinset (haveI := Classical.decEq α; g₁.support ∪ g₂.support) (fun a => f (g₁ a) (g₂ a)) fun a (H : f _ _ ≠ 0) => by classical rw [mem_union, mem_support_iff, mem_support_iff, ← not_and_or] rintro ⟨h₁, h₂⟩; rw [h₁, h₂] at H; exact H hf @[simp] theorem zipWith_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zipWith f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl theorem support_zipWith [D : DecidableEq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zipWith f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by convert support_onFinset_subset end ZipWith end Finsupp
rat.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import prime fintype finfun bigop order tuple ssralg. From mathcomp Require Import countalg div ssrnum ssrint archimedean poly zmodp. From mathcomp Require Import polydiv intdiv matrix mxalgebra vector. (******************************************************************************) (* This file defines a datatype for rational numbers and equips it with a *) (* structure of archimedean, real field, with int and nat declared as closed *) (* subrings. *) (* rat == the type of rational number, with single constructor Rat *) (* <number> == <number> as a rat with <number> a decimal constant. *) (* This notation is in rat_scope (delimited with %Q). *) (* n%:Q == explicit cast from int to rat, ie. the specialization to *) (* rationals of the generic ring morphism n%:~R *) (* numq r == numerator of (r : rat) *) (* denq r == denominator of (r : rat) *) (* ratr r == generic embedding of (r : rat) into an arbitrary unit ring.*) (* [rat x // y] == smart constructor for rationals, definitionally equal *) (* to x / y for concrete values, intended for printing only *) (* of normal forms. The parsable notation is for debugging. *) (* inIntSpan X v <-> v is an integral linear combination of elements of *) (* X : seq V, where V is a zmodType. We prove that this is a *) (* decidable property for Q-vector spaces. *) (******************************************************************************) Import Order.TTheory GRing.Theory Num.Theory. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Reserved Notation "[ 'rat' x // y ]" (format "[ 'rat' x // y ]"). Reserved Notation "n %:Q" (left associativity, format "n %:Q"). Local Open Scope ring_scope. Local Notation sgr := Num.sg. Record rat : Set := Rat { valq : (int * int); _ : (0 < valq.2) && coprime `|valq.1| `|valq.2| }. Bind Scope ring_scope with rat. Delimit Scope rat_scope with Q. Definition ratz (n : int) := @Rat (n, 1) (coprimen1 _). (* Coercion ratz (n : int) := @Rat (n, 1) (coprimen1 _). *) Definition rat_isSub := Eval hnf in [isSub for valq]. HB.instance Definition _ := rat_isSub. #[hnf] HB.instance Definition _ := [Equality of rat by <:]. HB.instance Definition _ := [Countable of rat by <:]. Definition numq x := (valq x).1. Definition denq x := (valq x).2. Arguments numq : simpl never. Arguments denq : simpl never. Lemma denq_gt0 x : 0 < denq x. Proof. by rewrite /denq; case: x=> [[a b] /= /andP []]. Qed. #[global] Hint Resolve denq_gt0 : core. Definition denq_ge0 x := ltW (denq_gt0 x). Lemma denq_lt0 x : (denq x < 0) = false. Proof. by rewrite lt_gtF. Qed. Lemma denq_neq0 x : denq x != 0. Proof. by rewrite /denq gt_eqF ?denq_gt0. Qed. #[global] Hint Resolve denq_neq0 : core. Lemma denq_eq0 x : (denq x == 0) = false. Proof. exact: negPf (denq_neq0 _). Qed. Lemma coprime_num_den x : coprime `|numq x| `|denq x|. Proof. by rewrite /numq /denq; case: x=> [[a b] /= /andP []]. Qed. Fact RatK x P : @Rat (numq x, denq x) P = x. Proof. by move: x P => [[a b] P'] P; apply: val_inj. Qed. Definition fracq_subdef x := if x.2 != 0 then let g := gcdn `|x.1| `|x.2| in ((-1) ^ ((x.2 < 0) (+) (x.1 < 0)) * (`|x.1| %/ g)%:Z, (`|x.2| %/ g)%:Z) else (0, 1). Arguments fracq_subdef /. Definition fracq_opt_subdef (x : int * int) := if (0 < x.2) && coprime `|x.1| `|x.2| then x else fracq_subdef x. Lemma fracq_opt_subdefE x : fracq_opt_subdef x = fracq_subdef x. Proof. rewrite /fracq_opt_subdef; case: ifP => //; case: x => n d /= /andP[d_gt0 cnd]. rewrite /fracq_subdef gt_eqF//= lt_gtF//= (eqP cnd) !divn1 abszEsg gtz0_abs//. rewrite mulrA sgz_def mulrnAr -signr_addb addbb expr0. by have [->|] := eqVneq n 0; rewrite (mulr0, mul1r). Qed. Fact fracq_subproof x (y := fracq_opt_subdef x) : (0 < y.2) && (coprime `|y.1| `|y.2|). Proof. rewrite {}/y fracq_opt_subdefE /=; have [] //= := eqVneq x.2 0. case: x => [/= n d]; rewrite -absz_gt0 => dN0. have ggt0 : (0 < gcdn `|n| `|d|)%N by rewrite gcdn_gt0 dN0 orbT. rewrite ltz_nat divn_gt0// dvdn_leq ?dvdn_gcdr//=. rewrite abszM abszX abszN1 exp1n mul1n absz_nat. rewrite /coprime -(@eqn_pmul2r (gcdn `|n| `|d|))// mul1n. by rewrite muln_gcdl !divnK ?(dvdn_gcdl, dvdn_gcdr). Qed. Lemma fracq_opt_subdef_id x : fracq_opt_subdef (fracq_opt_subdef x) = fracq_subdef x. Proof. rewrite [fracq_opt_subdef (_ x)]/fracq_opt_subdef. by rewrite fracq_subproof fracq_opt_subdefE. Qed. (* We use a match expression in order to "lock" the definition of fracq. *) (* Indeed, the kernel will try to reduce a fracq only when applied to *) (* a term which has "enough" constructors: i.e. it reduces to a pair of *) (* a Posz or Negz on the first component, and a Posz of 0 or S, or a Negz *) (* on the second component. See issue #698. *) (* Additionally, we use fracq_opt_subdef to precompute the normal form *) (* before we use fracq_subproof in order to make sure the proof will be *) (* independent from the input of fracq. This ensure reflexivity of any *) (* computation involving rationals as long as all operators use fracq. *) (* As a consequence val (fracq x) = fracq_opt_subdef (fracq_opt_subdef x)) *) Definition fracq '((n', d')) : rat := match d', n' with | Posz 0 as d, _ as n => Rat (fracq_subproof (1, 0)) | _ as d, Posz _ as n | _ as d, _ as n => Rat (fracq_subproof (fracq_opt_subdef (n, d))) end. Arguments fracq : simpl never. (* Define a Number Notation for rat in rat_scope *) (* Since rat values obtained from fracq contain fracq_subdef, which is not *) (* an inductive constructor, we need to go through an intermediate *) (* inductive type. *) Variant Irat_prf := Ifracq_subproof : (int * int) -> Irat_prf. Variant Irat := IRat : (int * int) -> Irat_prf -> Irat. Definition parse (x : Number.number) : option Irat := let parse_pos i f := let nf := Decimal.nb_digits f in let d := (10 ^ nf)%nat in let n := (Nat.of_uint i * d + Nat.of_uint f)%nat in valq (fracq (Posz n, Posz d)) in let parse i f := match i with | Decimal.Pos i => parse_pos i f | Decimal.Neg i => let (n, d) := parse_pos i f in ((- n)%R, d) end in match x with | Number.Decimal (Decimal.Decimal i f) => let nd := parse i f in Some (IRat nd (Ifracq_subproof nd)) | Number.Decimal (Decimal.DecimalExp _ _ _) => None | Number.Hexadecimal _ => None end. Definition print (r : Irat) : option Number.number := let print_pos n d := if d == 1%nat then Some (Nat.to_uint n, Decimal.Nil) else let d2d5 := match prime_decomp d with | [:: (2, d2); (5, d5)] => Some (d2, d5) | [:: (2, d2)] => Some (d2, O) | [:: (5, d5)] => Some (O, d5) | _ => None end in match d2d5 with | Some (d2, d5) => let f := (2 ^ (d5 - d2) * 5 ^ (d2 - d5))%nat in let (i, f) := edivn (n * f) (d * f) in Some (Nat.to_uint i, Nat.to_uint f) | None => None end in let print_IRat nd := match nd with | (Posz n, Posz d) => match print_pos n d with | Some (i, f) => Some (Decimal.Pos i, f) | None => None end | (Negz n, Posz d) => match print_pos n.+1 d with | Some (i, f) => Some (Decimal.Neg i, f) | None => None end | (_, Negz _) => None end in match r with | IRat nd _ => match print_IRat nd with | Some (i, f) => Some (Number.Decimal (Decimal.Decimal i f)) | None => None end end. Number Notation rat parse print (via Irat mapping [Rat => IRat, fracq_subproof => Ifracq_subproof]) : rat_scope. (* Now, the following should parse as rat (and print unchanged) *) (* Check 12%Q. *) (* Check 3.14%Q. *) (* Check (-3.14)%Q. *) (* Check 0.5%Q. *) (* Check 0.2%Q. *) Lemma val_fracq x : val (fracq x) = fracq_subdef x. Proof. by case: x => [[n|n] [[|[|d]]|d]]//=; rewrite !fracq_opt_subdef_id. Qed. Lemma num_fracq x : numq (fracq x) = if x.2 != 0 then (-1) ^ ((x.2 < 0) (+) (x.1 < 0)) * (`|x.1| %/ gcdn `|x.1| `|x.2|)%:Z else 0. Proof. by rewrite /numq val_fracq/=; case: ifP. Qed. Lemma den_fracq x : denq (fracq x) = if x.2 != 0 then (`|x.2| %/ gcdn `|x.1| `|x.2|)%:Z else 1. Proof. by rewrite /denq val_fracq/=; case: ifP. Qed. Fact ratz_frac n : ratz n = fracq (n, 1). Proof. by apply: val_inj; rewrite val_fracq/= gcdn1 !divn1 abszE mulr_sign_norm. Qed. Fact valqK x : fracq (valq x) = x. Proof. move: x => [[n d] /= Pnd]; apply: val_inj; rewrite ?val_fracq/=. move: Pnd; rewrite /coprime /fracq /= => /andP[] hd -/eqP hnd. by rewrite lt_gtF ?gt_eqF //= hnd !divn1 mulz_sign_abs abszE gtr0_norm. Qed. Definition scalq '(n, d) := sgr d * (gcdn `|n| `|d|)%:Z. Lemma scalq_def x : scalq x = sgr x.2 * (gcdn `|x.1| `|x.2|)%:Z. Proof. by case: x. Qed. Fact scalq_eq0 x : (scalq x == 0) = (x.2 == 0). Proof. case: x => n d; rewrite scalq_def /= mulf_eq0 sgr_eq0 /= eqz_nat. rewrite -[gcdn _ _ == 0]negbK -lt0n gcdn_gt0 ?absz_gt0 [X in ~~ X]orbC. by case: sgrP. Qed. Lemma sgr_scalq x : sgr (scalq x) = sgr x.2. Proof. rewrite scalq_def sgrM sgr_id -[(gcdn _ _)%:Z]intz sgr_nat. by rewrite -lt0n gcdn_gt0 ?absz_gt0 orbC; case: sgrP; rewrite // mul0r. Qed. Lemma signr_scalq x : (scalq x < 0) = (x.2 < 0). Proof. by rewrite -!sgr_cp0 sgr_scalq. Qed. Lemma scalqE x : x.2 != 0 -> scalq x = (-1) ^+ (x.2 < 0)%R * (gcdn `|x.1| `|x.2|)%:Z. Proof. by rewrite scalq_def; case: sgrP. Qed. Fact valq_frac x : x.2 != 0 -> x = (scalq x * numq (fracq x), scalq x * denq (fracq x)). Proof. move=> x2_neq0; rewrite scalqE//; move: x2_neq0. case: x => [n d] /= d_neq0; rewrite num_fracq den_fracq/= ?d_neq0. rewrite mulr_signM -mulrA -!PoszM addKb. do 2!rewrite muln_divCA ?(dvdn_gcdl, dvdn_gcdr) // divnn. by rewrite gcdn_gt0 !absz_gt0 d_neq0 orbT !muln1 !mulz_sign_abs. Qed. Definition zeroq := 0%Q. Definition oneq := 1%Q. Fact frac0q x : fracq (0, x) = zeroq. Proof. apply: val_inj; rewrite //= val_fracq/= div0n !gcd0n !mulr0 !divnn. by have [//|x_neq0] := eqVneq; rewrite absz_gt0 x_neq0. Qed. Fact fracq0 x : fracq (x, 0) = zeroq. Proof. exact/eqP. Qed. Variant fracq_spec (x : int * int) : int * int -> rat -> Type := | FracqSpecN of x.2 = 0 : fracq_spec x (x.1, 0) zeroq | FracqSpecP k fx of k != 0 : fracq_spec x (k * numq fx, k * denq fx) fx. Fact fracqP x : fracq_spec x x (fracq x). Proof. case: x => n d /=; have [d_eq0 | d_neq0] := eqVneq d 0. by rewrite d_eq0 fracq0; constructor. by rewrite {2}[(_, _)]valq_frac //; constructor; rewrite scalq_eq0. Qed. Lemma rat_eqE x y : (x == y) = (numq x == numq y) && (denq x == denq y). Proof. rewrite -val_eqE [val x]surjective_pairing [val y]surjective_pairing /=. by rewrite xpair_eqE. Qed. Lemma sgr_denq x : sgr (denq x) = 1. Proof. by apply/eqP; rewrite sgr_cp0. Qed. Lemma normr_denq x : `|denq x| = denq x. Proof. by rewrite gtr0_norm. Qed. Lemma absz_denq x : `|denq x|%N = denq x :> int. Proof. by rewrite abszE normr_denq. Qed. Lemma rat_eq x y : (x == y) = (numq x * denq y == numq y * denq x). Proof. symmetry; rewrite rat_eqE andbC. have [->|] /= := eqVneq (denq _); first by rewrite (inj_eq (mulIf _)). apply: contraNF => /eqP hxy; rewrite -absz_denq -[eqbRHS]absz_denq. rewrite eqz_nat /= eqn_dvd. rewrite -(@Gauss_dvdr _ `|numq x|) 1?coprime_sym ?coprime_num_den // andbC. rewrite -(@Gauss_dvdr _ `|numq y|) 1?coprime_sym ?coprime_num_den //. by rewrite -!abszM hxy -{1}hxy !abszM !dvdn_mull ?dvdnn. Qed. Fact fracq_eq x y : x.2 != 0 -> y.2 != 0 -> (fracq x == fracq y) = (x.1 * y.2 == y.1 * x.2). Proof. case: fracqP=> //= u fx u_neq0 _; case: fracqP=> //= v fy v_neq0 _; symmetry. rewrite [eqbRHS]mulrC mulrACA [eqbRHS]mulrACA. by rewrite [denq _ * _]mulrC (inj_eq (mulfI _)) ?mulf_neq0 // rat_eq. Qed. Fact fracq_eq0 x : (fracq x == zeroq) = (x.1 == 0) || (x.2 == 0). Proof. move: x=> [n d] /=; have [->|d0] := eqVneq d 0. by rewrite fracq0 eqxx orbT. by rewrite -[zeroq]valqK orbF fracq_eq ?d0 //= mulr1 mul0r. Qed. Fact fracqMM x n d : x != 0 -> fracq (x * n, x * d) = fracq (n, d). Proof. move=> x_neq0; apply/eqP. have [->|d_neq0] := eqVneq d 0; first by rewrite mulr0 !fracq0. by rewrite fracq_eq ?mulf_neq0 //= mulrCA mulrA. Qed. (* We "lock" the definition of addq, oppq, mulq and invq, using a match on *) (* the constructor Rat for both arguments, so that it may only be reduced *) (* when applied to explicit rationals. Since fracq is also "locked" in a *) (* similar way, fracq will not reduce to a Rat x xP unless it is also applied *) (* to "enough" constructors. This preserves the reduction on gound elements *) (* while it suspends it when applied to at least one variable at the leaf of *) (* the arithmetic operation. *) (* Moreover we optimize addition when one or both arguments are integers, *) (* in which case we presimplify the output, this shortens the size of the hnf *) (* of terms of the form N%:Q when N is a concrete natural number. *) Definition addq_subdef (x y : int * int) := let: (x1, x2) := x in let: (y1, y2) := y in match x2, y2 with | Posz 1, Posz 1 => match x1, y1 with | Posz 0, _ => (y1, 1) | _, Posz 0 => (x1, 1) | Posz n, Posz 1 => (Posz n.+1, 1) | Posz 1, Posz n => (Posz n.+1, 1) | _, _ => (x1 + y1, 1) end | Posz 1, _ => (x1 * y2 + y1, y2) | _, Posz 1 => (x1 + y1 * x2, x2) | _, _ => (x1 * y2 + y1 * x2, x2 * y2) end. Definition addq '(Rat x xP) '(Rat y yP) := fracq (addq_subdef x y). Lemma addq_def x y : addq x y = fracq (addq_subdef (valq x) (valq y)). Proof. by case: x; case: y. Qed. Lemma addq_subdefE x y : addq_subdef x y = (x.1 * y.2 + y.1 * x.2, x.2 * y.2). Proof. case: x y => [x1 [[|[|x2]]|x2]] [y1 [[|[|y2]]|y2]]/=; rewrite ?Monoid.simpm//. by case: x1 y1 => [[|[|m]]|m] [[|[|n]]|n]; rewrite ?Monoid.simpm// -PoszD addn1. Qed. Definition oppq_subdef (x : int * int) := (- x.1, x.2). Definition oppq '(Rat x xP) := fracq (oppq_subdef x). Definition oppq_def x : oppq x = fracq (oppq_subdef (valq x)). Proof. by case: x. Qed. Fact addq_subdefC : commutative addq_subdef. Proof. by move=> x y; rewrite !addq_subdefE addrC [x.2 * _]mulrC. Qed. Fact addq_subdefA : associative addq_subdef. Proof. move=> x y z; rewrite !addq_subdefE. by rewrite !mulrA !mulrDl addrA ![_ * x.2]mulrC !mulrA. Qed. Fact addq_frac x y : x.2 != 0 -> y.2 != 0 -> (addq (fracq x) (fracq y)) = fracq (addq_subdef x y). Proof. case: fracqP => // u fx u_neq0 _; case: fracqP => // v fy v_neq0 _. rewrite addq_def !addq_subdefE /=. rewrite ![(_ * numq _) * _]mulrACA [(_ * denq _) * _]mulrACA. by rewrite [v * _]mulrC -mulrDr fracqMM ?mulf_neq0. Qed. Fact ratzD : {morph ratz : x y / x + y >-> addq x y}. Proof. by move=> x y; rewrite !ratz_frac addq_frac// addq_subdefE/= !mulr1. Qed. Fact oppq_frac x : oppq (fracq x) = fracq (oppq_subdef x). Proof. rewrite /oppq_subdef; case: fracqP => /= [|u fx u_neq0]. by rewrite fracq0. by rewrite oppq_def -mulrN fracqMM. Qed. Fact ratzN : {morph ratz : x / - x >-> oppq x}. Proof. by move=> x /=; rewrite !ratz_frac // /add /= !mulr1. Qed. Fact addqC : commutative addq. Proof. by move=> x y; rewrite !addq_def /= addq_subdefC. Qed. Fact addqA : associative addq. Proof. move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK. by rewrite ?addq_frac ?addq_subdefA// ?addq_subdefE ?mulf_neq0 ?denq_neq0. Qed. Fact add0q : left_id zeroq addq. Proof. move=> x; rewrite -[x]valqK -[zeroq]valqK addq_frac ?denq_neq0 // !addq_subdefE. by rewrite mul0r add0r mulr1 mul1r -surjective_pairing. Qed. Fact addNq : left_inverse (fracq (0, 1)) oppq addq. Proof. move=> x; rewrite -[x]valqK !(addq_frac, oppq_frac) ?denq_neq0 //. rewrite !addq_subdefE /oppq_subdef //= mulNr addNr; apply/eqP. by rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= !mul0r. Qed. HB.instance Definition _ := GRing.isZmodule.Build rat addqA addqC add0q addNq. Definition mulq_subdef (x y : int * int) := let: (x1, x2) := x in let: (y1, y2) := y in match x2, y2 with | Posz 1, Posz 1 => (x1 * y1, 1) | Posz 1, _ => (x1 * y1, y2) | _, Posz 1 => (x1 * y1, x2) | _, _ => (x1 * y1, x2 * y2) end. Definition mulq '(Rat x xP) '(Rat y yP) := fracq (mulq_subdef x y). Lemma mulq_def x y : mulq x y = fracq (mulq_subdef (valq x) (valq y)). Proof. by case: x; case: y. Qed. Lemma mulq_subdefE x y : mulq_subdef x y = (x.1 * y.1, x.2 * y.2). Proof. by case: x y => [x1 [[|[|x2]]|x2]] [y1 [[|[|y2]]|y2]]/=; rewrite ?Monoid.simpm. Qed. Fact mulq_subdefC : commutative mulq_subdef. Proof. by move=> x y; rewrite !mulq_subdefE mulrC [_ * x.2]mulrC. Qed. Fact mul_subdefA : associative mulq_subdef. Proof. by move=> x y z; rewrite !mulq_subdefE !mulrA. Qed. Definition invq_subdef (x : int * int) := (x.2, x.1). Definition invq '(Rat x xP) := fracq (invq_subdef x). Lemma invq_def x : invq x = fracq (invq_subdef (valq x)). Proof. by case: x. Qed. Fact mulq_frac x y : (mulq (fracq x) (fracq y)) = fracq (mulq_subdef x y). Proof. rewrite mulq_def !mulq_subdefE; case: (fracqP x) => /= [|u fx u_neq0]. by rewrite !mul0r !mul1r fracq0 frac0q. case: (fracqP y) => /= [|v fy v_neq0]. by rewrite !mulr0 !mulr1 fracq0 frac0q. by rewrite ![_ * (v * _)]mulrACA [RHS]fracqMM ?mulf_neq0. Qed. Fact ratzM : {morph ratz : x y / x * y >-> mulq x y}. Proof. by move=> x y /=; rewrite !ratz_frac //= !mulr1. Qed. Fact invq_frac x : x.1 != 0 -> x.2 != 0 -> invq (fracq x) = fracq (invq_subdef x). Proof. by rewrite invq_def; case: (fracqP x) => // k ? k0; rewrite fracqMM. Qed. Fact mulqC : commutative mulq. Proof. by move=> x y; rewrite !mulq_def mulq_subdefC. Qed. Fact mulqA : associative mulq. Proof. by move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK !mulq_frac mul_subdefA. Qed. Fact mul1q : left_id oneq mulq. Proof. move=> x; rewrite -[x]valqK -[oneq]valqK; rewrite mulq_frac !mulq_subdefE. by rewrite !mul1r -surjective_pairing. Qed. Fact mulq_addl : left_distributive mulq addq. Proof. move=> x y z; rewrite -[x]valqK -[y]valqK -[z]valqK /=. rewrite !(mulq_frac, addq_frac, mulq_subdefE, addq_subdefE) ?mulf_neq0 ?denq_neq0 //=. apply/eqP; rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= !mulrDl; apply/eqP. by rewrite !mulrA ![_ * (valq z).1]mulrC !mulrA ![_ * (valq x).2]mulrC !mulrA. Qed. Fact nonzero1q : oneq != zeroq. Proof. by []. Qed. HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build rat mulqA mulqC mul1q mulq_addl nonzero1q. Fact mulVq x : x != 0 -> mulq (invq x) x = 1. Proof. rewrite -[x]valqK -[0]valqK fracq_eq ?denq_neq0 //= mulr1 mul0r=> nx0. rewrite !(mulq_frac, invq_frac, mulq_subdefE) ?denq_neq0 // -[1]valqK. by apply/eqP; rewrite fracq_eq ?mulf_neq0 ?denq_neq0 //= mulr1 mul1r mulrC. Qed. Fact invq0 : invq 0 = 0. Proof. exact/eqP. Qed. HB.instance Definition _ := GRing.ComNzRing_isField.Build rat mulVq invq0. Lemma numq_eq0 x : (numq x == 0) = (x == 0). Proof. rewrite -[x]valqK fracq_eq0; case: fracqP=> /= [|k {}x k0]. by rewrite eqxx orbT. by rewrite !mulf_eq0 (negPf k0) /= denq_eq0 orbF. Qed. Notation "n %:Q" := ((n : int)%:~R : rat) : ring_scope. #[global] Hint Resolve denq_neq0 denq_gt0 denq_ge0 : core. Definition subq (x y : rat) : rat := (addq x (oppq y)). Definition divq (x y : rat) : rat := (mulq x (invq y)). Infix "+" := addq : rat_scope. Notation "- x" := (oppq x) : rat_scope. Infix "*" := mulq : rat_scope. Notation "x ^-1" := (invq x) : rat_scope. Infix "-" := subq : rat_scope. Infix "/" := divq : rat_scope. (* ratz should not be used, %:Q should be used instead *) Lemma ratzE n : ratz n = n%:Q. Proof. elim: n=> [|n ihn|n ihn]; first by rewrite mulr0z ratz_frac. by rewrite intS mulrzDr ratzD ihn. by rewrite intS opprD mulrzDr ratzD ihn. Qed. Lemma numq_int n : numq n%:Q = n. Proof. by rewrite -ratzE. Qed. Lemma denq_int n : denq n%:Q = 1. Proof. by rewrite -ratzE. Qed. Lemma rat0 : 0%:Q = 0. Proof. by []. Qed. Lemma rat1 : 1%:Q = 1. Proof. by []. Qed. Lemma numqN x : numq (- x) = - numq x. Proof. rewrite [- _]oppq_def/= num_fracq. case: x => -[a b]; rewrite /numq/= => /andP[b_gt0]. rewrite /coprime => /eqP cab. by rewrite lt_gtF ?gt_eqF // {2}abszN cab divn1 mulz_sign_abs. Qed. Lemma denqN x : denq (- x) = denq x. Proof. rewrite [- _]oppq_def den_fracq. case: x => -[a b]; rewrite /denq/= => /andP[b_gt0]. by rewrite /coprime=> /eqP cab; rewrite gt_eqF // abszN cab divn1 gtz0_abs. Qed. (* Will be subsumed by pnatr_eq0 *) Fact intq_eq0 n : (n%:~R == 0 :> rat) = (n == 0)%N. Proof. by rewrite -ratzE /ratz rat_eqE/= /numq /denq/= eqxx andbT. Qed. (* fracq should never appear, its canonical form is _%:Q / _%:Q *) Lemma fracqE x : fracq x = x.1%:Q / x.2%:Q. Proof. move: x => [m n] /=; apply/val_inj; rewrite val_fracq/=. case: eqVneq => //= [->|n_neq0]; first by rewrite rat0 invr0 mulr0. rewrite -[m%:Q]valqK -[n%:Q]valqK. rewrite [_^-1]invq_frac ?denq_neq0 ?numq_eq0 ?intq_eq0//=. rewrite [X in valq X]mulq_frac val_fracq /invq_subdef !mulq_subdefE/=. by rewrite -!/(numq _) -!/(denq _) !numq_int !denq_int mul1r mulr1 n_neq0. Qed. Lemma divq_num_den x : (numq x)%:Q / (denq x)%:Q = x. Proof. by rewrite -{3}[x]valqK [valq _]surjective_pairing /= fracqE. Qed. Variant divq_spec (n d : int) : int -> int -> rat -> Type := | DivqSpecN of d = 0 : divq_spec n d n 0 0 | DivqSpecP k x of k != 0 : divq_spec n d (k * numq x) (k * denq x) x. (* replaces fracqP *) Lemma divqP n d : divq_spec n d n d (n%:Q / d%:Q). Proof. set x := (n, d); rewrite -[n]/x.1 -[d]/x.2 -fracqE. by case: fracqP => [_|k fx k_neq0] /=; constructor. Qed. Variant rat_spec (* (x : rat) *) : rat -> int -> int -> Type := Rat_spec (n : int) (d : nat) & coprime `|n| d.+1 : rat_spec (* x *) (n%:Q / d.+1%:Q) n d.+1. Lemma ratP x : rat_spec x (numq x) (denq x). Proof. rewrite -{1}[x](divq_num_den); case hd: denq => [p|n]. have: 0 < p%:Z by rewrite -hd denq_gt0. case: p hd=> //= n hd; constructor; rewrite -?hd ?divq_num_den //. by rewrite -[n.+1]/`|n.+1|%N -hd coprime_num_den. by move: (denq_gt0 x); rewrite hd. Qed. Lemma coprimeq_num n d : coprime `|n| `|d| -> numq (n%:~R / d%:~R) = sgr d * n. Proof. move=> cnd /=; have <- := fracqE (n, d). rewrite num_fracq/= (eqP (cnd : _ == 1)) divn1. have [|d_gt0|d_lt0] := sgrP d; by rewrite (mul0r, mul1r, mulN1r) //= ?[_ ^ _]signrN ?mulNr mulz_sign_abs. Qed. Lemma coprimeq_den n d : coprime `|n| `|d| -> denq (n%:~R / d%:~R) = (if d == 0 then 1 else `|d|). Proof. move=> cnd; have <- := fracqE (n, d). by rewrite den_fracq/= (eqP (cnd : _ == 1)) divn1; case: d {cnd}; case. Qed. Lemma denqVz (i : int) : i != 0 -> denq (i%:~R^-1) = `|i|. Proof. move=> h; rewrite -div1r -[1]/(1%:~R). by rewrite coprimeq_den /= ?coprime1n // (negPf h). Qed. Lemma numqE x : (numq x)%:~R = x * (denq x)%:~R. Proof. by rewrite -{2}[x]divq_num_den divfK // intq_eq0 denq_eq0. Qed. Lemma denqP x : {d | denq x = d.+1}. Proof. by rewrite /denq; case: x => [[_ [[|d]|]] //= _]; exists d. Qed. Definition normq '(Rat x _) : rat := `|x.1|%:~R / (x.2)%:~R. Definition le_rat '(Rat x _) '(Rat y _) := x.1 * y.2 <= y.1 * x.2. Definition lt_rat '(Rat x _) '(Rat y _) := x.1 * y.2 < y.1 * x.2. Lemma normqE x : normq x = `|numq x|%:~R / (denq x)%:~R. Proof. by case: x. Qed. Lemma le_ratE x y : le_rat x y = (numq x * denq y <= numq y * denq x). Proof. by case: x; case: y. Qed. Lemma lt_ratE x y : lt_rat x y = (numq x * denq y < numq y * denq x). Proof. by case: x; case: y. Qed. Lemma gt_rat0 x : lt_rat 0 x = (0 < numq x). Proof. by rewrite lt_ratE mul0r mulr1. Qed. Lemma lt_rat0 x : lt_rat x 0 = (numq x < 0). Proof. by rewrite lt_ratE mul0r mulr1. Qed. Lemma ge_rat0 x : le_rat 0 x = (0 <= numq x). Proof. by rewrite le_ratE mul0r mulr1. Qed. Lemma le_rat0 x : le_rat x 0 = (numq x <= 0). Proof. by rewrite le_ratE mul0r mulr1. Qed. Fact le_rat0D x y : le_rat 0 x -> le_rat 0 y -> le_rat 0 (x + y). Proof. rewrite !ge_rat0 => hnx hny. have hxy: (0 <= numq x * denq y + numq y * denq x). by rewrite addr_ge0 ?mulr_ge0. rewrite [_ + _]addq_def /numq /= -!/(denq _) ?mulf_eq0 ?denq_eq0. rewrite val_fracq/=; case: ifP => //=. by rewrite ?addq_subdefE !mulr_ge0// !le_gtF ?mulr_ge0 ?denq_ge0//=. Qed. Fact le_rat0M x y : le_rat 0 x -> le_rat 0 y -> le_rat 0 (x * y). Proof. rewrite !ge_rat0 => hnx hny. have hxy: (0 <= numq x * denq y + numq y * denq x). by rewrite addr_ge0 ?mulr_ge0. rewrite [_ * _]mulq_def /numq /= -!/(denq _) ?mulf_eq0 ?denq_eq0. rewrite val_fracq/=; case: ifP => //=. by rewrite ?mulq_subdefE !mulr_ge0// !le_gtF ?mulr_ge0 ?denq_ge0//=. Qed. Fact le_rat0_anti x : le_rat 0 x -> le_rat x 0 -> x = 0. Proof. by move=> hx hy; apply/eqP; rewrite -numq_eq0 eq_le -ge_rat0 -le_rat0 hx hy. Qed. Lemma sgr_numq_div (n d : int) : sgr (numq (n%:Q / d%:Q)) = sgr n * sgr d. Proof. set x := (n, d); rewrite -[n]/x.1 -[d]/x.2 -fracqE. case: fracqP => [|k fx k_neq0] /=; first by rewrite mulr0. by rewrite !sgrM mulrACA -expr2 sqr_sg k_neq0 sgr_denq mulr1 mul1r. Qed. Fact subq_ge0 x y : le_rat 0 (y - x) = le_rat x y. Proof. symmetry; rewrite ge_rat0 !le_ratE -subr_ge0. case: ratP => nx dx cndx; case: ratP => ny dy cndy. rewrite -!mulNr addf_div ?intq_eq0 // !mulNr -!rmorphM -rmorphB /=. symmetry; rewrite !leNgt -sgr_cp0 sgr_numq_div mulrC gtr0_sg //. by rewrite mul1r sgr_cp0. Qed. Fact le_rat_total : total le_rat. Proof. by move=> x y; rewrite !le_ratE; apply: le_total. Qed. Fact numq_sign_mul (b : bool) x : numq ((-1) ^+ b * x) = (-1) ^+ b * numq x. Proof. by case: b; rewrite ?(mul1r, mulN1r) // numqN. Qed. Fact numq_div_lt0 n d : n != 0 -> d != 0 -> (numq (n%:~R / d%:~R) < 0)%R = (n < 0)%R (+) (d < 0)%R. Proof. move=> n0 d0; rewrite -sgr_cp0 sgr_numq_div !sgr_def n0 d0. by rewrite !mulr1n -signr_addb; case: (_ (+) _). Qed. Lemma normr_num_div n d : `|numq (n%:~R / d%:~R)| = numq (`|n|%:~R / `|d|%:~R). Proof. rewrite (normrEsg n) (normrEsg d) !rmorphM /= invfM mulrACA !sgr_def. have [->|n_neq0] := eqVneq; first by rewrite mul0r mulr0. have [->|d_neq0] := eqVneq; first by rewrite invr0 !mulr0. rewrite !intr_sign invr_sign -signr_addb numq_sign_mul -numq_div_lt0 //. by apply: (canRL (signrMK _)); rewrite mulz_sign_abs. Qed. Fact norm_ratN x : normq (- x) = normq x. Proof. by rewrite !normqE numqN denqN normrN. Qed. Fact ge_rat0_norm x : le_rat 0 x -> normq x = x. Proof. rewrite ge_rat0; case: ratP=> [] // n d cnd n_ge0. by rewrite normqE /= normr_num_div ?ger0_norm // divq_num_den. Qed. Fact lt_rat_def x y : (lt_rat x y) = (y != x) && (le_rat x y). Proof. by rewrite lt_ratE le_ratE lt_def rat_eq. Qed. HB.instance Definition _ := Num.IntegralDomain_isLeReal.Build rat le_rat0D le_rat0M le_rat0_anti subq_ge0 (@le_rat_total 0) norm_ratN ge_rat0_norm lt_rat_def. Lemma numq_ge0 x : (0 <= numq x) = (0 <= x). Proof. by case: ratP => n d cnd; rewrite ?pmulr_lge0 ?invr_gt0 (ler0z, ltr0z). Qed. Lemma numq_le0 x : (numq x <= 0) = (x <= 0). Proof. by rewrite -oppr_ge0 -numqN numq_ge0 oppr_ge0. Qed. Lemma numq_gt0 x : (0 < numq x) = (0 < x). Proof. by rewrite !ltNge numq_le0. Qed. Lemma numq_lt0 x : (numq x < 0) = (x < 0). Proof. by rewrite !ltNge numq_ge0. Qed. Lemma sgr_numq x : sgz (numq x) = sgz x. Proof. apply/eqP; case: (sgzP x); rewrite sgz_cp0 ?(numq_gt0, numq_lt0) //. by move->. Qed. Lemma denq_mulr_sign (b : bool) x : denq ((-1) ^+ b * x) = denq x. Proof. by case: b; rewrite ?(mul1r, mulN1r) // denqN. Qed. Lemma denq_norm x : denq `|x| = denq x. Proof. by rewrite normrEsign denq_mulr_sign. Qed. Module ratArchimedean. Section ratArchimedean. Implicit Types x : rat. Definition floor x : int := (numq x %/ denq x)%Z. Definition ceil x : int := - (- numq x %/ denq x)%Z. Definition truncn x : nat := if 0 <= x then (`|numq x| %/ `|denq x|)%N else 0%N. Let is_int x := denq x == 1. Let is_nat x := (0 <= x) && (denq x == 1). Fact floorP x : if x \is Num.real then (floor x)%:~R <= x < (floor x + 1)%:~R else floor x == 0. Proof. rewrite num_real /floor; case: (ratP x) => n d _ {x}; rewrite ler_pdivlMr//. by rewrite ltr_pdivrMr// -!intrM ler_int ltr_int lez_floor ?ltz_ceil. Qed. Fact ceilP x : ceil x = - floor (- x). Proof. by rewrite /ceil /floor numqN denqN. Qed. Fact truncnP x : truncn x = if floor x is Posz n then n else 0. Proof. rewrite /truncn /floor; case: (ratP x) => n d _ {x} /=. by rewrite !ler_pdivlMr// mul0r; case: n => n; rewrite ler0z//= mul1n. Qed. Fact intrP x : reflect (exists n, x = n%:~R) (is_int x). Proof. apply: (iffP idP) => [/eqP d1 | [i ->]]; [|by rewrite /is_int denq_int]. by exists (numq x); case: (ratP x) d1 => n d _ ->; rewrite divr1. Qed. Fact natrP x : reflect (exists n, x = n%:R) (is_nat x). Proof. apply: (iffP idP) => [/andP[]/[swap]/intrP[i ->]|[n ->]]. by rewrite ler0z; case: i => [n _|//]; exists n. by rewrite /is_nat pmulrn ler0z denq_int. Qed. End ratArchimedean. End ratArchimedean. HB.instance Definition _ := Num.NumDomain_hasFloorCeilTruncn.Build rat ratArchimedean.floorP ratArchimedean.ceilP ratArchimedean.truncnP ratArchimedean.intrP ratArchimedean.natrP. Lemma floorErat (x : rat) : Num.floor x = (numq x %/ denq x)%Z. Proof. by []. Qed. Lemma ceilErat (x : rat) : Num.ceil x = - (- numq x %/ denq x)%Z. Proof. by []. Qed. Lemma Qint_def (x : rat) : (x \is a Num.int) = (denq x == 1). Proof. by []. Qed. Lemma numqK : {in Num.int, cancel (fun x => numq x) intr}. Proof. by move=> _ /intrP [x ->]; rewrite numq_int. Qed. Lemma natq_div m n : (n %| m)%N -> (m %/ n)%:R = m%:R / n%:R :> rat. Proof. exact/pchar0_natf_div/pchar_num. Qed. Section InRing. Variable R : unitRingType. Definition ratr x : R := (numq x)%:~R / (denq x)%:~R. Lemma ratr_int z : ratr z%:~R = z%:~R. Proof. by rewrite /ratr numq_int denq_int divr1. Qed. Lemma ratr_nat n : ratr n%:R = n%:R. Proof. exact: ratr_int n. Qed. Lemma rpred_rat (S : divringClosed R) a : ratr a \in S. Proof. by rewrite rpred_div ?rpred_int. Qed. End InRing. Section Fmorph. Implicit Type rR : unitRingType. Lemma fmorph_rat (aR : fieldType) rR (f : {rmorphism aR -> rR}) a : f (ratr _ a) = ratr _ a. Proof. by rewrite fmorph_div !rmorph_int. Qed. Lemma fmorph_eq_rat rR (f : {rmorphism rat -> rR}) : f =1 ratr _. Proof. by move=> a; rewrite -{1}[a]divq_num_den fmorph_div !rmorph_int. Qed. End Fmorph. Section Linear. Implicit Types (U V : lmodType rat) (A B : lalgType rat). Lemma rat_linear U V (f : U -> V) : zmod_morphism f -> scalable f. Proof. move=> fB a u. pose aM := GRing.isZmodMorphism.Build U V f fB. pose phi : {additive U -> V} := HB.pack f aM. rewrite -[f]/(phi : _ -> _) -{2}[a]divq_num_den mulrC -scalerA. apply: canRL (scalerK _) _; first by rewrite intr_eq0 denq_neq0. rewrite 2!scaler_int -3!raddfMz /=. by rewrite -scalerMzr scalerMzl -mulrzr -numqE scaler_int. Qed. End Linear. Section InPrealField. Variable F : numFieldType. Fact ratr_is_zmod_morphism : zmod_morphism (@ratr F). Proof. have injZtoQ: @injective rat int intr by apply: intr_inj. have nz_den x: (denq x)%:~R != 0 :> F by rewrite intr_eq0 denq_eq0. move=> x y. apply: (canLR (mulfK (nz_den _))); apply: (mulIf (nz_den x)). rewrite mulrAC mulrBl divfK ?nz_den // mulrAC -!rmorphM. apply: (mulIf (nz_den y)); rewrite mulrAC mulrBl divfK ?nz_den //. rewrite -!(rmorphM, rmorphB); congr _%:~R; apply: injZtoQ. rewrite !(rmorphM, rmorphB) /= [_ - _]lock /= -lock !numqE. by rewrite (mulrAC y) -!mulrBl -mulrA mulrAC !mulrA. Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `ratr_is_additive` instead")] Definition ratr_is_additive := ratr_is_zmod_morphism. Fact ratr_is_monoid_morphism : monoid_morphism (@ratr F). Proof. have injZtoQ: @injective rat int intr by apply: intr_inj. have nz_den x: (denq x)%:~R != 0 :> F by rewrite intr_eq0 denq_eq0. split=> [|x y]; first by rewrite /ratr divr1. rewrite /ratr mulrC mulrAC; apply: canLR (mulKf (nz_den _)) _; rewrite !mulrA. do 2!apply: canRL (mulfK (nz_den _)) _; rewrite -!rmorphM; congr _%:~R. apply: injZtoQ; rewrite !rmorphM [x * y]lock /= !numqE -lock. by rewrite -!mulrA mulrA mulrCA -!mulrA (mulrCA y). Qed. #[warning="-deprecated-since-mathcomp-2.5.0", deprecated(since="mathcomp 2.5.0", note="use `ratr_is_monoid_morphism` instead")] Definition ratr_is_multiplicative := (fun g => (g.2,g.1)) ratr_is_monoid_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build rat F (@ratr F) ratr_is_zmod_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build rat F (@ratr F) ratr_is_monoid_morphism. Lemma ler_rat : {mono (@ratr F) : x y / x <= y}. Proof. move=> x y /=; case: (ratP x) => nx dx cndx; case: (ratP y) => ny dy cndy. rewrite !fmorph_div /= !ratr_int !ler_pdivlMr ?ltr0z //. by rewrite ![_ / _ * _]mulrAC !ler_pdivrMr ?ltr0z // -!rmorphM /= !ler_int. Qed. Lemma ltr_rat : {mono (@ratr F) : x y / x < y}. Proof. exact: leW_mono ler_rat. Qed. Lemma ler0q x : (0 <= ratr F x) = (0 <= x). Proof. by rewrite (_ : 0 = ratr F 0) ?ler_rat ?rmorph0. Qed. Lemma lerq0 x : (ratr F x <= 0) = (x <= 0). Proof. by rewrite (_ : 0 = ratr F 0) ?ler_rat ?rmorph0. Qed. Lemma ltr0q x : (0 < ratr F x) = (0 < x). Proof. by rewrite (_ : 0 = ratr F 0) ?ltr_rat ?rmorph0. Qed. Lemma ltrq0 x : (ratr F x < 0) = (x < 0). Proof. by rewrite (_ : 0 = ratr F 0) ?ltr_rat ?rmorph0. Qed. Lemma ratr_sg x : ratr F (sgr x) = sgr (ratr F x). Proof. by rewrite !sgr_def fmorph_eq0 ltrq0 rmorphMn /= rmorph_sign. Qed. Lemma ratr_norm x : ratr F `|x| = `|ratr F x|. Proof. by rewrite {2}[x]numEsign rmorphMsign normrMsign [`|ratr F _|]ger0_norm ?ler0q. Qed. Lemma minr_rat : {morph ratr F : x y / Num.min x y}. Proof. by move=> x y; rewrite !minEle ler_rat; case: leP. Qed. Lemma maxr_rat : {morph ratr F : x y / Num.max x y}. Proof. by move=> x y; rewrite !maxEle ler_rat; case: leP. Qed. End InPrealField. Section InParchiField. Variable F : archiNumFieldType. Lemma floor_rat : {mono (@ratr F) : x / Num.floor x}. Proof. move=> x; apply: floor_def; apply/andP; split. - by rewrite -ratr_int ler_rat floor_le_tmp. - by rewrite -ratr_int ltr_rat floorD1_gt. Qed. Lemma ceil_rat : {mono (@ratr F) : x / Num.ceil x}. Proof. by move=> x; rewrite !ceilNfloor -rmorphN floor_rat. Qed. End InParchiField. Arguments ratr {R}. Lemma Qint_dvdz (m d : int) : (d %| m)%Z -> (m%:~R / d%:~R : rat) \is a Num.int. Proof. case/dvdzP=> z ->; rewrite rmorphM /=; have [->|dn0] := eqVneq d 0. by rewrite mulr0 mul0r. by rewrite mulfK ?intr_eq0. Qed. Lemma Qnat_dvd (m d : nat) : (d %| m)%N -> (m%:R / d%:R : rat) \is a Num.nat. Proof. by move=> h; rewrite natrEint divr_ge0 ?ler0n // !pmulrn Qint_dvdz. Qed. Section ZpolyScale. Local Notation pZtoQ := (map_poly (intr : int -> rat)). Lemma size_rat_int_poly p : size (pZtoQ p) = size p. Proof. by apply: size_map_inj_poly; first apply: intr_inj. Qed. Lemma rat_poly_scale (p : {poly rat}) : {q : {poly int} & {a | a != 0 & p = a%:~R^-1 *: pZtoQ q}}. Proof. pose a := \prod_(i < size p) denq p`_i. have nz_a: a != 0 by apply/prodf_neq0=> i _; apply: denq_neq0. exists (map_poly numq (a%:~R *: p)), a => //. apply: canRL (scalerK _) _; rewrite ?intr_eq0 //. apply/polyP=> i; rewrite !(coefZ, coef_map_id0) // numqK // Qint_def mulrC. have [ltip | /(nth_default 0)->] := ltnP i (size p); last by rewrite mul0r. by rewrite [a](bigD1 (Ordinal ltip)) // rmorphM mulrA -numqE -rmorphM denq_int. Qed. Lemma dvdp_rat_int p q : (pZtoQ p %| pZtoQ q) = (p %| q). Proof. apply/dvdpP/Pdiv.Idomain.dvdpP=> [[/= r1 Dq] | [[/= a r] nz_a Dq]]; last first. exists (a%:~R^-1 *: pZtoQ r). by rewrite -scalerAl -rmorphM -Dq /= linearZ/= scalerK ?intr_eq0. have [r [a nz_a Dr1]] := rat_poly_scale r1; exists (a, r) => //=. apply: (map_inj_poly _ _ : injective pZtoQ) => //; first exact: intr_inj. by rewrite linearZ /= Dq Dr1 -scalerAl -rmorphM scalerKV ?intr_eq0. Qed. Lemma dvdpP_rat_int p q : p %| pZtoQ q -> {p1 : {poly int} & {a | a != 0 & p = a *: pZtoQ p1} & {r | q = p1 * r}}. Proof. have{p} [p [a nz_a ->]] := rat_poly_scale p. rewrite dvdpZl ?invr_eq0 ?intr_eq0 // dvdp_rat_int => dv_p_q. exists (zprimitive p); last exact: dvdpP_int. have [-> | nz_p] := eqVneq p 0. by exists 1; rewrite ?oner_eq0 // zprimitive0 map_poly0 !scaler0. exists ((zcontents p)%:~R / a%:~R). by rewrite mulf_neq0 ?invr_eq0 ?intr_eq0 ?zcontents_eq0. by rewrite mulrC -scalerA -map_polyZ -zpolyEprim. Qed. Lemma irreducible_rat_int p : irreducible_poly (pZtoQ p) <-> irreducible_poly p. Proof. rewrite /irreducible_poly size_rat_int_poly; split=> -[] p1 p_irr; split=> //. move=> q q1; rewrite /eqp -!dvdp_rat_int => rq. by apply/p_irr => //; rewrite size_rat_int_poly. move=> q + /dvdpP_rat_int [] r [] c c0 qE [] s sE. rewrite qE size_scale// size_rat_int_poly => r1. apply/(eqp_trans (eqp_scale _ c0)). rewrite /eqp !dvdp_rat_int; apply/p_irr => //. by rewrite sE dvdp_mulIl. Qed. End ZpolyScale. (* Integral spans. *) Definition inIntSpan (V : zmodType) m (s : m.-tuple V) v := exists a : int ^ m, v = \sum_(i < m) s`_i *~ a i. Lemma solve_Qint_span (vT : vectType rat) m (s : m.-tuple vT) v : {b : int ^ m & {p : seq (int ^ m) & forall a : int ^ m, v = \sum_(i < m) s`_i *~ a i <-> exists c : seq int, a = b + \sum_(i < size p) p`_i *~ c`_i}} + (~ inIntSpan s v). Proof. have s_s (i : 'I_m): s`_i \in <<s>>%VS by rewrite memv_span ?memt_nth. have s_Zs a: \sum_(i < m) s`_i *~ a i \in <<s>>%VS. by apply/rpred_sum => i _; apply/rpredMz. case s_v: (v \in <<s>>%VS); last by right=> [[a Dv]]; rewrite Dv s_Zs in s_v. move SE : (\matrix_(i < m, j < _) coord (vbasis <<s>>) j s`_i) => S. move rE : (\rank S) => r; move kE : (m - r)%N => k. have Dm: (m = k + r)%N by rewrite -kE -rE subnK ?rank_leq_row. rewrite Dm in s s_s s_Zs s_v S SE rE kE *. move=> {Dm m}; pose m := (k + r)%N. have [K kerK]: {K : 'M_(k, m) | map_mx intr K == kermx S}%MS. move: (mxrank_ker S); rewrite rE kE => krk. pose B := row_base (kermx S); pose d := \prod_ij denq (B ij.1 ij.2). exists (castmx (krk, erefl m) (map_mx numq (intr d *: B))). rewrite map_castmx !eqmx_cast -map_mx_comp map_mx_id_in => [|i j]; last first. rewrite mxE mulrC [d](bigD1 (i, j)) //= rmorphM mulrA. by rewrite -numqE -rmorphM numq_int. suff nz_d: d%:Q != 0 by rewrite !eqmx_scale // !eq_row_base andbb. by rewrite intr_eq0; apply/prodf_neq0 => i _; apply: denq_neq0. have [L _ [G uG [D _ defK]]] := int_Smith_normal_form K. have {K L D defK kerK} [kerGu kerS_sub_Gu]: map_mx intr (usubmx G) *m S = 0 /\ (kermx S <= map_mx intr (usubmx G))%MS. pose Kl : 'M[rat]_k := map_mx intr (lsubmx (K *m invmx G)). have {}defK: map_mx intr K = Kl *m map_mx intr (usubmx G). rewrite /Kl -map_mxM; congr map_mx. rewrite -[LHS](mulmxKV uG) -{2}[G]vsubmxK -{1}[K *m _]hsubmxK. rewrite mul_row_col -[RHS]addr0; congr (_ + _). rewrite defK mulmxK //= -[RHS](mul0mx _ (dsubmx G)); congr (_ *m _). apply/matrixP => i j; rewrite !mxE big1 //= => j1 _. rewrite mxE /= eqn_leq andbC. by rewrite leqNgt (leq_trans (valP j1)) ?mulr0 ?leq_addr. split; last by rewrite -(eqmxP kerK); apply/submxP; exists Kl. suff /row_full_inj: row_full Kl. by apply; rewrite mulmx0 mulmxA (sub_kermxP _) // -(eqmxP kerK) defK. rewrite /row_full eqn_leq rank_leq_row /= -{1}kE -{2}rE -(mxrank_ker S). by rewrite -(eqmxP kerK) defK mxrankM_maxl. pose T := map_mx intr (dsubmx G) *m S. have defS: map_mx intr (rsubmx (invmx G)) *m T = S. rewrite mulmxA -map_mxM /=; move: (mulVmx uG). rewrite -{2}[G]vsubmxK -{1}[invmx G]hsubmxK mul_row_col. move/(canRL (addKr _)) ->; rewrite -mulNmx raddfD /= map_mx1 map_mxM /=. by rewrite mulmxDl -mulmxA kerGu mulmx0 add0r mul1mx. pose vv := \row_j coord (vbasis <<s>>) j v. have uS: row_full S. apply/row_fullP; exists (\matrix_(i, j) coord s j (vbasis <<s>>)`_i). apply/matrixP => j1 j2; rewrite !mxE. rewrite -(coord_free _ _ (basis_free (vbasisP _))). rewrite -!tnth_nth (coord_span (vbasis_mem (mem_tnth j1 _))) linear_sum. by apply: eq_bigr => /= i _; rewrite -SE !mxE (tnth_nth 0) !linearZ. have eqST: (S :=: T)%MS by apply/eqmxP; rewrite -{1}defS !submxMl. case Zv: (map_mx denq (vv *m pinvmx T) == const_mx 1); last first. right=> [[a Dv]]; case/eqP: Zv; apply/rowP. have ->: vv = map_mx intr (\row_i a i) *m S. apply/rowP => j; rewrite !mxE Dv linear_sum. by apply: eq_bigr => i _; rewrite -SE -scaler_int linearZ !mxE. rewrite -defS -2!mulmxA; have ->: T *m pinvmx T = 1%:M. have uT: row_free T by rewrite /row_free -eqST rE. by apply: (row_free_inj uT); rewrite mul1mx mulmxKpV. by move=> i; rewrite mulmx1 -map_mxM 2!mxE denq_int mxE. pose b := map_mx numq (vv *m pinvmx T) *m dsubmx G. left; exists [ffun j => b 0 j], [seq [ffun j => (usubmx G) i j] | i : 'I_k]. rewrite size_image card_ord => a; rewrite -[a](addNKr [ffun j => b 0 j]). move: (_ + a) => h; under eq_bigr => i _ do rewrite !ffunE mulrzDr. rewrite big_split /=. have <-: v = \sum_(i < m) s`_i *~ b 0 i. transitivity (\sum_j (map_mx intr b *m S) 0 j *: (vbasis <<s>>)`_j). rewrite {1}(coord_vbasis s_v); apply: eq_bigr => j _; congr (_ *: _). suff ->: map_mx intr b = vv *m pinvmx T *m map_mx intr (dsubmx G). by rewrite -(mulmxA _ _ S) mulmxKpV ?mxE // -eqST submx_full. rewrite map_mxM /=; congr (_ *m _); apply/rowP => i; rewrite 2!mxE numqE. by have /eqP/rowP/(_ i)/[!mxE] -> := Zv; rewrite mulr1. rewrite (coord_vbasis (s_Zs _)); apply: eq_bigr => j _; congr (_ *: _). rewrite linear_sum mxE; apply: eq_bigr => i _. by rewrite -SE -scaler_int linearZ [b]lock !mxE. split. rewrite -[LHS]addr0 => /addrI hP; pose c := \row_i h i *m lsubmx (invmx G). exists [seq c 0 i | i : 'I_k]; congr (_ + _). have/sub_kermxP: map_mx intr (\row_i h i) *m S = 0. transitivity (\row_j coord (vbasis <<s>>) j (\sum_(i < m) s`_i *~ h i)). apply/rowP => j; rewrite !mxE linear_sum; apply: eq_bigr => i _. by rewrite -SE !mxE -scaler_int linearZ. by apply/rowP => j; rewrite !mxE -hP linear0. case/submx_trans/(_ kerS_sub_Gu)/submxP => c' /[dup]. move/(congr1 (mulmx^~ (map_mx intr (lsubmx (invmx G))))). rewrite -mulmxA -!map_mxM [in RHS]mulmx_lsub mul_usub_mx -/c mulmxV //=. rewrite scalar_mx_block -/(ulsubmx _) block_mxKul map_scalar_mx mulmx1. move=> <- {c'}; rewrite -map_mxM /= => defh; apply/ffunP => j. move/rowP/(_ j): defh; rewrite sum_ffunE !mxE => /intr_inj ->. apply: eq_bigr => i _; rewrite ffunMzE mulrzz mulrC. rewrite (nth_map i) ?size_enum_ord // nth_ord_enum ffunE. by rewrite (nth_map i) ?size_enum_ord // nth_ord_enum. case=> c /addrI -> {h}; rewrite -[LHS]addr0; congr (_ + _). pose h := \row_(j < k) c`_j *m usubmx G. transitivity (\sum_j (map_mx intr h *m S) 0 j *: (vbasis <<s>>)`_j). by rewrite map_mxM -mulmxA kerGu mulmx0 big1 // => j _; rewrite mxE scale0r. rewrite (coord_vbasis (s_Zs _)); apply: eq_bigr => i _; congr (_ *: _). rewrite linear_sum -SE mxE; apply: eq_bigr => j _. rewrite -scaler_int linearZ !mxE sum_ffunE; congr (_%:~R * _). apply: {i} eq_bigr => i _; rewrite mxE ffunMzE mulrzz mulrC. by rewrite (nth_map i) ?size_enum_ord // ffunE nth_ord_enum. Qed. Lemma dec_Qint_span (vT : vectType rat) m (s : m.-tuple vT) v : decidable (inIntSpan s v). Proof. have [[b [p aP]]|] := solve_Qint_span s v; last by right. left; exists b; apply/(aP b); exists [::]; rewrite big1 ?addr0 // => i _. by rewrite nth_nil mulr0z. Qed. Lemma eisenstein_crit (p : nat) (q : {poly int}) : prime p -> (size q != 1)%N -> ~~ (p %| lead_coef q)%Z -> ~~ (p ^+ 2 %| q`_0)%Z -> (forall i, (i < (size q).-1)%N -> p %| q`_i)%Z -> irreducible_poly q. Proof. move=> p_prime qN1 Ndvd_pql Ndvd_pq0 dvd_pq. apply/irreducible_rat_int. have qN0 : q != 0 by rewrite -lead_coef_eq0; apply: contraNneq Ndvd_pql => ->. split. rewrite size_map_poly_id0 ?intr_eq0 ?lead_coef_eq0//. by rewrite ltn_neqAle eq_sym qN1 size_poly_gt0. move=> f' +/dvdpP_rat_int[f [d dN0 feq]]; rewrite {f'}feq size_scale// => fN1. move=> /= [g q_eq]; rewrite q_eq (eqp_trans (eqp_scale _ _))//. have fN0 : f != 0 by apply: contra_neq qN0; rewrite q_eq => ->; rewrite mul0r. have gN0 : g != 0 by apply: contra_neq qN0; rewrite q_eq => ->; rewrite mulr0. rewrite size_map_poly_id0 ?intr_eq0 ?lead_coef_eq0// in fN1. have [/eqP/size_poly1P[c cN0 ->]|gN1] := eqVneq (size g) 1%N. by rewrite mulrC mul_polyC map_polyZ/= eqp_sym eqp_scale// intr_eq0. have c_neq0 : (lead_coef q)%:~R != 0 :> 'F_p by rewrite -(dvdz_pcharf (pchar_Fp _)). have : map_poly (intr : int -> 'F_p) q = (lead_coef q)%:~R *: 'X^((size q).-1). apply/val_inj/(@eq_from_nth _ 0) => [|i]; rewrite size_map_poly_id0//. by rewrite size_scale// size_polyXn -polySpred. move=> i_small; rewrite coef_poly i_small coefZ coefXn lead_coefE. move: i_small; rewrite polySpred// ltnS/=. case: ltngtP => // [i_lt|->]; rewrite (mulr1, mulr0)//= => _. by apply/eqP; rewrite -(dvdz_pcharf (pchar_Fp _))// dvd_pq. rewrite [in LHS]q_eq rmorphM/=. set c := (X in X *: _); set n := (_.-1). set pf := map_poly _ f; set pg := map_poly _ g => pfMpg. have dvdXn (r : {poly _}) : size r != 1%N -> r %| c *: 'X^n -> r`_0 = 0. move=> rN1; rewrite (eqp_dvdr _ (eqp_scale _ _))//. rewrite -['X]subr0; move=> /dvdp_exp_XsubCP[k lekn]; rewrite subr0. move=> /eqpP[u /andP[u1N0 u2N0]]; have [->|k_gt0] := posnP k. move=> /(congr1 (size \o val))/eqP. by rewrite /= !size_scale// size_polyXn (negPf rN1). move=> /(congr1 (fun p : {poly _} => p`_0))/eqP. by rewrite !coefZ coefXn [0 == _]ltn_eqF// mulr0 mulf_eq0 (negPf u1N0)=> /eqP. suff : ((p : int) ^+ 2 %| q`_0)%Z by rewrite (negPf Ndvd_pq0). have := c_neq0; rewrite q_eq coefM big_ord1. rewrite lead_coefM rmorphM mulf_eq0 negb_or => /andP[lpfN0 qfN0]. have pfN1 : size pf != 1%N by rewrite size_map_poly_id0. have pgN1 : size pg != 1%N by rewrite size_map_poly_id0. have /(dvdXn _ pgN1) /eqP : pg %| c *: 'X^n by rewrite -pfMpg dvdp_mull. have /(dvdXn _ pfN1) /eqP : pf %| c *: 'X^n by rewrite -pfMpg dvdp_mulr. by rewrite !coef_map// -!(dvdz_pcharf (pchar_Fp _))//; apply: dvdz_mul. Qed. (* Connecting rationals to the ring and field tactics *) Ltac rat_to_ring := rewrite -?[0%Q]/(0 : rat)%R -?[1%Q]/(1 : rat)%R -?[(_ - _)%Q]/(_ - _ : rat)%R -?[(_ / _)%Q]/(_ / _ : rat)%R -?[(_ + _)%Q]/(_ + _ : rat)%R -?[(_ * _)%Q]/(_ * _ : rat)%R -?[(- _)%Q]/(- _ : rat)%R -?[(_ ^-1)%Q]/(_ ^-1 : rat)%R /=. Ltac ring_to_rat := rewrite -?[0%R]/0%Q -?[1%R]/1%Q -?[(_ - _)%R]/(_ - _)%Q -?[(_ / _)%R]/(_ / _)%Q -?[(_ + _)%R]/(_ + _)%Q -?[(_ * _)%R]/(_ * _)%Q -?[(- _)%R]/(- _)%Q -?[(_ ^-1)%R]/(_ ^-1)%Q /=. (* Pretty printing or normal element of rat. *) Notation "[ 'rat' x // y ]" := (@Rat (x, y) _) (only printing) : ring_scope. (* For debugging purposes we provide the parsable version *) Notation "[ 'rat' x // y ]" := (@Rat (x : int, y : int) (fracq_subproof (x : int, y : int))) : ring_scope. (* A specialization of vm_compute rewrite rule for pattern _%:Q *) Lemma rat_vm_compute n (x : rat) : vm_compute_eq n%:Q x -> n%:Q = x. Proof. exact. Qed.
Imo2001Q6.lean
/- Copyright (c) 2021 Sara Díaz Real. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sara Díaz Real -/ import Mathlib.Algebra.Ring.Associated import Mathlib.Tactic.Linarith import Mathlib.Tactic.LinearCombination /-! # IMO 2001 Q6 Let $a$, $b$, $c$, $d$ be integers with $a > b > c > d > 0$. Suppose that $$ a*c + b*d = (a + b - c + d) * (-a + b + c + d). $$ Prove that $a*b + c*d$ is not prime. -/ variable {a b c d : ℤ} theorem imo2001_q6 (hd : 0 < d) (hdc : d < c) (hcb : c < b) (hba : b < a) (h : a * c + b * d = (a + b - c + d) * (-a + b + c + d)) : ¬Prime (a * b + c * d) := by intro (h0 : Prime (a * b + c * d)) have ha : 0 < a := by omega have hb : 0 < b := by omega have hc : 0 < c := by omega -- the key step is to show that `a*c + b*d` divides the product `(a*b + c*d) * (a*d + b*c)` have dvd_mul : a * c + b * d ∣ (a * b + c * d) * (a * d + b * c) := by use b ^ 2 + b * d + d ^ 2 linear_combination b * d * h -- since `a*b + c*d` is prime (by assumption), it must divide `a*c + b*d` or `a*d + b*c` obtain (h1 : a * b + c * d ∣ a * c + b * d) | (h2 : a * c + b * d ∣ a * d + b * c) := h0.left_dvd_or_dvd_right_of_dvd_mul dvd_mul -- in both cases, we derive a contradiction · have aux : 0 < a * c + b * d := by nlinarith only [ha, hb, hc, hd] have : a * b + c * d ≤ a * c + b * d := Int.le_of_dvd aux h1 nlinarith only [hba, hcb, hdc, h, this] · have aux : 0 < a * d + b * c := by nlinarith only [ha, hb, hc, hd] have : a * c + b * d ≤ a * d + b * c := Int.le_of_dvd aux h2 nlinarith only [hba, hdc, h, this]
Prod.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import Mathlib.Algebra.Group.Action.Faithful import Mathlib.Algebra.Group.Action.Hom import Mathlib.Algebra.Group.Prod /-! # Prod instances for additive and multiplicative actions This file defines instances for binary product of additive and multiplicative actions and provides scalar multiplication as a homomorphism from `α × β` to `β`. ## Main declarations * `smulMulHom`/`smulMonoidHom`: Scalar multiplication bundled as a multiplicative/monoid homomorphism. ## See also * `Mathlib/Algebra/Group/Action/Option.lean` * `Mathlib/Algebra/Group/Action/Pi.lean` * `Mathlib/Algebra/Group/Action/Sigma.lean` * `Mathlib/Algebra/Group/Action/Sum.lean` # Porting notes The `to_additive` attribute can be used to generate both the `smul` and `vadd` lemmas from the corresponding `pow` lemmas, as explained on zulip here: https://leanprover.zulipchat.com/#narrow/near/316087838 This was not done as part of the port in order to stay as close as possible to the mathlib3 code. -/ assert_not_exists MonoidWithZero variable {M N P E α β : Type*} namespace Prod section variable [SMul M α] [SMul M β] [SMul N α] [SMul N β] (a : M) (x : α × β) @[to_additive] instance isScalarTower [SMul M N] [IsScalarTower M N α] [IsScalarTower M N β] : IsScalarTower M N (α × β) where smul_assoc _ _ _ := by ext <;> exact smul_assoc .. @[to_additive] instance smulCommClass [SMulCommClass M N α] [SMulCommClass M N β] : SMulCommClass M N (α × β) where smul_comm _ _ _ := by ext <;> exact smul_comm .. @[to_additive] instance isCentralScalar [SMul Mᵐᵒᵖ α] [SMul Mᵐᵒᵖ β] [IsCentralScalar M α] [IsCentralScalar M β] : IsCentralScalar M (α × β) where op_smul_eq_smul _ _ := Prod.ext (op_smul_eq_smul _ _) (op_smul_eq_smul _ _) @[to_additive] instance faithfulSMulLeft [FaithfulSMul M α] [Nonempty β] : FaithfulSMul M (α × β) where eq_of_smul_eq_smul h := let ⟨b⟩ := ‹Nonempty β› eq_of_smul_eq_smul fun a : α => by injection h (a, b) @[to_additive] instance faithfulSMulRight [Nonempty α] [FaithfulSMul M β] : FaithfulSMul M (α × β) where eq_of_smul_eq_smul h := let ⟨a⟩ := ‹Nonempty α› eq_of_smul_eq_smul fun b : β => by injection h (a, b) end @[to_additive] instance smulCommClassBoth [Mul N] [Mul P] [SMul M N] [SMul M P] [SMulCommClass M N N] [SMulCommClass M P P] : SMulCommClass M (N × P) (N × P) where smul_comm c x y := by simp [smul_def, mul_def, mul_smul_comm] instance isScalarTowerBoth [Mul N] [Mul P] [SMul M N] [SMul M P] [IsScalarTower M N N] [IsScalarTower M P P] : IsScalarTower M (N × P) (N × P) where smul_assoc c x y := by simp [smul_def, mul_def, smul_mul_assoc] @[to_additive] instance mulAction [Monoid M] [MulAction M α] [MulAction M β] : MulAction M (α × β) where mul_smul _ _ _ := by ext <;> exact mul_smul .. one_smul _ := by ext <;> exact one_smul .. end Prod /-! ### Scalar multiplication as a homomorphism -/ section BundledSMul /-- Scalar multiplication as a multiplicative homomorphism. -/ @[simps] def smulMulHom [Monoid α] [Mul β] [MulAction α β] [IsScalarTower α β β] [SMulCommClass α β β] : α × β →ₙ* β where toFun a := a.1 • a.2 map_mul' _ _ := (smul_mul_smul_comm _ _ _ _).symm /-- Scalar multiplication as a monoid homomorphism. -/ @[simps] def smulMonoidHom [Monoid α] [MulOneClass β] [MulAction α β] [IsScalarTower α β β] [SMulCommClass α β β] : α × β →* β := { smulMulHom with map_one' := one_smul _ _ } end BundledSMul section Action_by_Prod variable (M N α) [Monoid M] [Monoid N] /-- Construct a `MulAction` by a product monoid from `MulAction`s by the factors. This is not an instance to avoid diamonds for example when `α := M × N`. -/ @[to_additive AddAction.prodOfVAddCommClass /-- Construct an `AddAction` by a product monoid from `AddAction`s by the factors. This is not an instance to avoid diamonds for example when `α := M × N`. -/] abbrev MulAction.prodOfSMulCommClass [MulAction M α] [MulAction N α] [SMulCommClass M N α] : MulAction (M × N) α where smul mn a := mn.1 • mn.2 • a one_smul a := (one_smul M _).trans (one_smul N a) mul_smul x y a := by change (x.1 * y.1) • (x.2 * y.2) • a = x.1 • x.2 • y.1 • y.2 • a rw [mul_smul, mul_smul, smul_comm y.1 x.2] /-- A `MulAction` by a product monoid is equivalent to commuting `MulAction`s by the factors. -/ @[to_additive AddAction.prodEquiv /-- An `AddAction` by a product monoid is equivalent to commuting `AddAction`s by the factors. -/] def MulAction.prodEquiv : MulAction (M × N) α ≃ Σ' (_ : MulAction M α) (_ : MulAction N α), SMulCommClass M N α where toFun _ := letI instM := MulAction.compHom α (.inl M N) letI instN := MulAction.compHom α (.inr M N) ⟨instM, instN, { smul_comm := fun m n a ↦ by change (m, (1 : N)) • ((1 : M), n) • a = ((1 : M), n) • (m, (1 : N)) • a simp_rw [smul_smul, Prod.mk_mul_mk, mul_one, one_mul] }⟩ invFun _insts := letI := _insts.1; letI := _insts.2.1; have := _insts.2.2 MulAction.prodOfSMulCommClass M N α left_inv := by rintro ⟨-, hsmul⟩; dsimp only; ext ⟨m, n⟩ a change (m, (1 : N)) • ((1 : M), n) • a = _ rw [← hsmul, Prod.mk_mul_mk, mul_one, one_mul]; rfl right_inv := by rintro ⟨hM, hN, -⟩ dsimp only; congr 1 · ext m a; (conv_rhs => rw [← hN.one_smul a]); rfl congr 1 · funext; congr; ext m a; (conv_rhs => rw [← hN.one_smul a]); rfl · ext n a; (conv_rhs => rw [← hM.one_smul (SMul.smul n a)]); rfl · exact proof_irrel_heq .. end Action_by_Prod
KrullDimension.lean
/- Copyright (c) 2024 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Fangming Li -/ import Mathlib.Order.KrullDimension import Mathlib.Topology.Homeomorph.Lemmas import Mathlib.Topology.Sets.Closeds /-! # The Krull dimension of a topological space The Krull dimension of a topological space is the order theoretic Krull dimension applied to the collection of all its subsets that are closed and irreducible. Unfolding this definition, it is the length of longest series of closed irreducible subsets ordered by inclusion. -/ open Order TopologicalSpace Topology /-- The Krull dimension of a topological space is the supremum of lengths of chains of closed irreducible sets. -/ noncomputable def topologicalKrullDim (T : Type*) [TopologicalSpace T] : WithBot ℕ∞ := krullDim (IrreducibleCloseds T) variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] /-- Map induced on irreducible closed subsets by a closed continuous map `f`. This is just a wrapper around the image of `f` together with proofs that it preserves irreducibility (by continuity) and closedness (since `f` is closed). -/ def IrreducibleCloseds.map {f : X → Y} (hf1 : Continuous f) (hf2 : IsClosedMap f) (c : IrreducibleCloseds X) : IrreducibleCloseds Y where carrier := f '' c is_irreducible' := c.is_irreducible'.image f hf1.continuousOn is_closed' := hf2 c c.is_closed' /-- Taking images under a closed embedding is strictly monotone on the preorder of irreducible closeds. -/ lemma IrreducibleCloseds.map_strictMono {f : X → Y} (hf : IsClosedEmbedding f) : StrictMono (IrreducibleCloseds.map hf.continuous hf.isClosedMap) := fun ⦃_ _⦄ UltV ↦ hf.injective.image_strictMono UltV /-- If `f : X → Y` is a closed embedding, then the Krull dimension of `X` is less than or equal to the Krull dimension of `Y`. -/ theorem IsClosedEmbedding.topologicalKrullDim_le (f : X → Y) (hf : IsClosedEmbedding f) : topologicalKrullDim X ≤ topologicalKrullDim Y := krullDim_le_of_strictMono _ (IrreducibleCloseds.map_strictMono hf) /-- The topological Krull dimension is invariant under homeomorphisms -/ theorem IsHomeomorph.topologicalKrullDim_eq (f : X → Y) (h : IsHomeomorph f) : topologicalKrullDim X = topologicalKrullDim Y := have fwd : topologicalKrullDim X ≤ topologicalKrullDim Y := IsClosedEmbedding.topologicalKrullDim_le f h.isClosedEmbedding have bwd : topologicalKrullDim Y ≤ topologicalKrullDim X := IsClosedEmbedding.topologicalKrullDim_le (h.homeomorph f).symm (h.homeomorph f).symm.isClosedEmbedding le_antisymm fwd bwd
Common.lean
/- Copyright (c) 2023 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ -- First import Aesop, Qq, and Plausible import Aesop import Qq import Plausible -- Tools for analysing imports, like `#find_home`, `#minimize_imports`, ... import ImportGraph.Imports -- Import common Batteries tactics and commands import Batteries.Tactic.Basic import Batteries.Tactic.Case import Batteries.Tactic.HelpCmd -- Import syntax for leansearch import LeanSearchClient -- Import Mathlib-specific linters. import Mathlib.Tactic.Linter.Lint -- Now import all tactics defined in Mathlib that do not require theory files. import Mathlib.Tactic.ApplyCongr -- ApplyFun imports `Mathlib/Order/Monotone/Basic.lean` -- import Mathlib.Tactic.ApplyFun import Mathlib.Tactic.ApplyAt import Mathlib.Tactic.ApplyWith import Mathlib.Tactic.Basic import Mathlib.Tactic.ByContra import Mathlib.Tactic.Cases import Mathlib.Tactic.CasesM import Mathlib.Tactic.Check import Mathlib.Tactic.Choose import Mathlib.Tactic.ClearExclamation import Mathlib.Tactic.ClearExcept import Mathlib.Tactic.Clear_ import Mathlib.Tactic.Coe import Mathlib.Tactic.CongrExclamation import Mathlib.Tactic.CongrM import Mathlib.Tactic.Constructor import Mathlib.Tactic.Contrapose import Mathlib.Tactic.Conv import Mathlib.Tactic.Convert import Mathlib.Tactic.DefEqTransformations import Mathlib.Tactic.DeprecateTo import Mathlib.Tactic.ErwQuestion import Mathlib.Tactic.Eqns import Mathlib.Tactic.ExistsI import Mathlib.Tactic.ExtractGoal import Mathlib.Tactic.FailIfNoProgress import Mathlib.Tactic.Find import Mathlib.Tactic.GCongr import Mathlib.Tactic.GRewrite import Mathlib.Tactic.GeneralizeProofs import Mathlib.Tactic.GuardGoalNums import Mathlib.Tactic.GuardHypNums import Mathlib.Tactic.HigherOrder import Mathlib.Tactic.Hint import Mathlib.Tactic.InferParam import Mathlib.Tactic.Inhabit import Mathlib.Tactic.IrreducibleDef import Mathlib.Tactic.Lift import Mathlib.Tactic.Linter import Mathlib.Tactic.MkIffOfInductiveProp -- NormNum imports `Algebra.Order.Invertible`, `Data.Int.Basic`, `Data.Nat.Cast.Commute` -- import Mathlib.Tactic.NormNum.Basic import Mathlib.Tactic.NthRewrite import Mathlib.Tactic.Observe import Mathlib.Tactic.OfNat -- `positivity` imports `Data.Nat.Factorial.Basic`, but hopefully this can be rearranged. -- import Mathlib.Tactic.Positivity import Mathlib.Tactic.Propose import Mathlib.Tactic.Push import Mathlib.Tactic.RSuffices import Mathlib.Tactic.Recover import Mathlib.Tactic.Relation.Rfl import Mathlib.Tactic.Rename import Mathlib.Tactic.RenameBVar import Mathlib.Tactic.Says 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.Spread import Mathlib.Tactic.Subsingleton import Mathlib.Tactic.Substs import Mathlib.Tactic.SuccessIfFailWithMsg import Mathlib.Tactic.SudoSetOption import Mathlib.Tactic.SwapVar import Mathlib.Tactic.Tauto import Mathlib.Tactic.TermCongr -- TFAE imports `Mathlib/Data/List/TFAE.lean` and thence `Mathlib/Data/List/Basic.lean`. -- import Mathlib.Tactic.TFAE import Mathlib.Tactic.ToExpr import Mathlib.Tactic.ToLevel import Mathlib.Tactic.Trace import Mathlib.Tactic.TypeCheck import Mathlib.Tactic.UnsetOption import Mathlib.Tactic.Use import Mathlib.Tactic.Variable import Mathlib.Tactic.Widget.Calc import Mathlib.Tactic.Widget.CongrM import Mathlib.Tactic.Widget.Conv import Mathlib.Tactic.Widget.LibraryRewrite import Mathlib.Tactic.WLOG import Mathlib.Util.AssertExists import Mathlib.Util.CountHeartbeats import Mathlib.Util.TransImports import Mathlib.Util.WhatsNew /-! This file imports all tactics which do not have significant theory imports, and hence can be imported very low in the theory import hierarchy, thereby making tactics widely available without needing specific imports. We include some commented out imports here, with an explanation of their theory requirements, to save some time for anyone wondering why they are not here. We also import theory-free linters, commands, and utilities which are useful to have low in the import hierarchy. -/ /-! # Register tactics with `hint`. Tactics are tried in reverse registration order. -/ section Hint register_hint grind register_hint trivial register_hint tauto register_hint split register_hint intro register_hint aesop register_hint simp_all? register_hint exact? register_hint decide register_hint omega end Hint
Associator.lean
/- Copyright (c) 2017 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Kim Morrison -/ import Mathlib.CategoryTheory.Products.Basic /-! The associator functor `((C × D) × E) ⥤ (C × (D × E))` and its inverse form an equivalence. -/ universe v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ open CategoryTheory namespace CategoryTheory.prod variable (C : Type u₁) [Category.{v₁} C] (D : Type u₂) [Category.{v₂} D] (E : Type u₃) [Category.{v₃} E] /-- The associator functor `(C × D) × E ⥤ C × (D × E)`. -/ @[simps] def associator : (C × D) × E ⥤ C × D × E where obj X := (X.1.1, (X.1.2, X.2)) map := @fun _ _ f => (f.1.1, (f.1.2, f.2)) /-- The inverse associator functor `C × (D × E) ⥤ (C × D) × E `. -/ @[simps] def inverseAssociator : C × D × E ⥤ (C × D) × E where obj X := ((X.1, X.2.1), X.2.2) map := @fun _ _ f => ((f.1, f.2.1), f.2.2) /-- The equivalence of categories expressing associativity of products of categories. -/ @[simps] def associativity : (C × D) × E ≌ C × D × E where functor := associator C D E inverse := inverseAssociator C D E unitIso := Iso.refl _ counitIso := Iso.refl _ instance associatorIsEquivalence : (associator C D E).IsEquivalence := (by infer_instance : (associativity C D E).functor.IsEquivalence) instance inverseAssociatorIsEquivalence : (inverseAssociator C D E).IsEquivalence := (by infer_instance : (associativity C D E).inverse.IsEquivalence) -- TODO pentagon natural transformation? ...satisfying? variable (A : Type u₄) [Category.{v₄} A] /-- The associator isomorphism is compatible with `prodFunctorToFunctorProd`. -/ @[simps!] def prodFunctorToFunctorProdAssociator : (associativity _ _ _).functor ⋙ ((𝟭 _).prod (prodFunctorToFunctorProd A D E) ⋙ (prodFunctorToFunctorProd A C (D × E))) ≅ (prodFunctorToFunctorProd A C D).prod (𝟭 _) ⋙ (prodFunctorToFunctorProd A (C × D) E) ⋙ (associativity C D E).congrRight.functor := Iso.refl _ /-- The associator isomorphism is compatible with `functorProdToProdFunctor`. -/ @[simps!] def functorProdToProdFunctorAssociator : (associativity _ _ _).congrRight.functor ⋙ functorProdToProdFunctor A C (D × E) ⋙ (𝟭 _).prod (functorProdToProdFunctor A D E) ≅ functorProdToProdFunctor A (C × D) E ⋙ (functorProdToProdFunctor A C D).prod (𝟭 _) ⋙ (associativity _ _ _).functor := Iso.refl _ end CategoryTheory.prod
Disjoint.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import Mathlib.Order.Filter.AtTopBot.Defs import Mathlib.Order.Interval.Set.Disjoint /-! # Disjointness of `Filter.atTop` and `Filter.atBot` -/ assert_not_exists Finset variable {ι ι' α β γ : Type*} open Set namespace Filter theorem disjoint_atBot_principal_Ioi [Preorder α] (x : α) : Disjoint atBot (𝓟 (Ioi x)) := disjoint_of_disjoint_of_mem (Iic_disjoint_Ioi le_rfl) (Iic_mem_atBot x) (mem_principal_self _) theorem disjoint_atTop_principal_Iio [Preorder α] (x : α) : Disjoint atTop (𝓟 (Iio x)) := @disjoint_atBot_principal_Ioi αᵒᵈ _ _ theorem disjoint_atTop_principal_Iic [Preorder α] [NoTopOrder α] (x : α) : Disjoint atTop (𝓟 (Iic x)) := disjoint_of_disjoint_of_mem (Iic_disjoint_Ioi le_rfl).symm (Ioi_mem_atTop x) (mem_principal_self _) theorem disjoint_atBot_principal_Ici [Preorder α] [NoBotOrder α] (x : α) : Disjoint atBot (𝓟 (Ici x)) := @disjoint_atTop_principal_Iic αᵒᵈ _ _ _ theorem disjoint_pure_atTop [Preorder α] [NoTopOrder α] (x : α) : Disjoint (pure x) atTop := Disjoint.symm <| (disjoint_atTop_principal_Iic x).mono_right <| le_principal_iff.2 <| mem_pure.2 right_mem_Iic theorem disjoint_pure_atBot [Preorder α] [NoBotOrder α] (x : α) : Disjoint (pure x) atBot := @disjoint_pure_atTop αᵒᵈ _ _ _ theorem disjoint_atBot_atTop [PartialOrder α] [Nontrivial α] : Disjoint (atBot : Filter α) atTop := by rcases exists_pair_ne α with ⟨x, y, hne⟩ by_cases hle : x ≤ y · refine disjoint_of_disjoint_of_mem ?_ (Iic_mem_atBot x) (Ici_mem_atTop y) exact Iic_disjoint_Ici.2 (hle.lt_of_ne hne).not_ge · refine disjoint_of_disjoint_of_mem ?_ (Iic_mem_atBot y) (Ici_mem_atTop x) exact Iic_disjoint_Ici.2 hle theorem disjoint_atTop_atBot [PartialOrder α] [Nontrivial α] : Disjoint (atTop : Filter α) atBot := disjoint_atBot_atTop.symm end Filter
ExtractLets.lean
/- Copyright (c) 2023 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Lean.Expr.Basic import Mathlib.Tactic.Basic import Batteries.Tactic.Lint.Misc import Mathlib.Tactic.Linter.DeprecatedModule deprecated_module "The extract_let tactic was moved to Lean core; \ you can probably just remove this import" (since := "2025-05-02")
Images.lean
/- Copyright (c) 2022 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.Algebra.Category.ModuleCat.Abelian import Mathlib.CategoryTheory.Limits.Shapes.Images /-! # The category of R-modules has images. Note that we don't need to register any of the constructions here as instances, because we get them from the fact that `ModuleCat R` is an abelian category. -/ open CategoryTheory open CategoryTheory.Limits universe u v namespace ModuleCat variable {R : Type u} [Ring R] variable {G H : ModuleCat.{v} R} (f : G ⟶ H) attribute [local ext] Subtype.ext_val section -- implementation details of `HasImage` for ModuleCat; use the API, not these /-- The image of a morphism in `ModuleCat R` is just the bundling of `LinearMap.range f` -/ def image : ModuleCat R := ModuleCat.of R (LinearMap.range f.hom) /-- The inclusion of `image f` into the target -/ def image.ι : image f ⟶ H := ofHom (LinearMap.range f.hom).subtype instance : Mono (image.ι f) := ConcreteCategory.mono_of_injective (image.ι f) Subtype.val_injective /-- The corestriction map to the image -/ def factorThruImage : G ⟶ image f := ofHom f.hom.rangeRestrict theorem image.fac : factorThruImage f ≫ image.ι f = f := rfl attribute [local simp] image.fac variable {f} /-- The universal property for the image factorisation -/ noncomputable def image.lift (F' : MonoFactorisation f) : image f ⟶ F'.I := ofHom { toFun := (fun x => F'.e (Classical.indefiniteDescription _ x.2).1 : image f → F'.I) map_add' := fun x y => by apply (mono_iff_injective F'.m).1 · infer_instance rw [LinearMap.map_add] change (F'.e ≫ F'.m) _ = (F'.e ≫ F'.m) _ + (F'.e ≫ F'.m) _ simp_rw [F'.fac, (Classical.indefiniteDescription (fun z => f z = _) _).2] rfl map_smul' := fun c x => by apply (mono_iff_injective F'.m).1 · infer_instance rw [LinearMap.map_smul] change (F'.e ≫ F'.m) _ = _ • (F'.e ≫ F'.m) _ simp_rw [F'.fac, (Classical.indefiniteDescription (fun z => f z = _) _).2] rfl } theorem image.lift_fac (F' : MonoFactorisation f) : image.lift F' ≫ F'.m = image.ι f := by ext x change (F'.e ≫ F'.m) _ = _ rw [F'.fac, (Classical.indefiniteDescription _ x.2).2] rfl end /-- The factorisation of any morphism in `ModuleCat R` through a mono. -/ def monoFactorisation : MonoFactorisation f where I := image f m := image.ι f e := factorThruImage f /-- The factorisation of any morphism in `ModuleCat R` through a mono has the universal property of the image. -/ noncomputable def isImage : IsImage (monoFactorisation f) where lift := image.lift lift_fac := image.lift_fac /-- The categorical image of a morphism in `ModuleCat R` agrees with the linear algebraic range. -/ noncomputable def imageIsoRange {G H : ModuleCat.{v} R} (f : G ⟶ H) : Limits.image f ≅ ModuleCat.of R (LinearMap.range f.hom) := IsImage.isoExt (Image.isImage f) (isImage f) @[simp, reassoc, elementwise] theorem imageIsoRange_inv_image_ι {G H : ModuleCat.{v} R} (f : G ⟶ H) : (imageIsoRange f).inv ≫ Limits.image.ι f = ModuleCat.ofHom (LinearMap.range f.hom).subtype := IsImage.isoExt_inv_m _ _ @[simp, reassoc, elementwise] theorem imageIsoRange_hom_subtype {G H : ModuleCat.{v} R} (f : G ⟶ H) : (imageIsoRange f).hom ≫ ModuleCat.ofHom (LinearMap.range f.hom).subtype = Limits.image.ι f := by rw [← imageIsoRange_inv_image_ι f, Iso.hom_inv_id_assoc] end ModuleCat
Basic.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Gabriel Ebner -/ import Mathlib.Data.Int.Cast.Defs import Mathlib.Algebra.Group.Basic import Mathlib.Data.Nat.Basic /-! # Cast of integers (additional theorems) This file proves additional properties about the *canonical* homomorphism from the integers into an additive group with a one (`Int.cast`). There is also `Mathlib.Data.Int.Cast.Lemmas`, which includes lemmas stated in terms of algebraic homomorphisms, and results involving the order structure of `ℤ`. By contrast, this file's only import beyond `Mathlib.Data.Int.Cast.Defs` is `Mathlib.Algebra.Group.Basic`. -/ universe u namespace Nat variable {R : Type u} [AddGroupWithOne R] @[simp, norm_cast] theorem cast_sub {m n} (h : m ≤ n) : ((n - m : ℕ) : R) = n - m := eq_sub_of_add_eq <| by rw [← cast_add, Nat.sub_add_cancel h] @[simp, norm_cast] theorem cast_pred : ∀ {n}, 0 < n → ((n - 1 : ℕ) : R) = n - 1 | 0, h => by cases h | n + 1, _ => by rw [cast_succ, add_sub_cancel_right, Nat.add_sub_cancel_right] end Nat open Nat namespace Int variable {R : Type u} [AddGroupWithOne R] -- TODO: I don't like that `norm_cast` is used here, because it results in `norm_cast` -- introducing the "implementation detail" `Int.negSucc`. @[simp, norm_cast squash] theorem cast_negSucc (n : ℕ) : (-[n+1] : R) = -(n + 1 : ℕ) := AddGroupWithOne.intCast_negSucc n @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : R) = 0 := (AddGroupWithOne.intCast_ofNat 0).trans Nat.cast_zero -- This lemma competes with `Int.ofNat_eq_natCast` to come later @[simp high, norm_cast] theorem cast_natCast (n : ℕ) : ((n : ℤ) : R) = n := AddGroupWithOne.intCast_ofNat _ @[simp, norm_cast] theorem cast_ofNat (n : ℕ) [n.AtLeastTwo] : ((ofNat(n) : ℤ) : R) = ofNat(n) := by simpa only [OfNat.ofNat] using AddGroupWithOne.intCast_ofNat (R := R) n @[simp, norm_cast] theorem cast_one : ((1 : ℤ) : R) = 1 := by rw [← Int.natCast_one, cast_natCast, Nat.cast_one] @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℤ) : R) = -n | (0 : ℕ) => by simp | (n + 1 : ℕ) => by rw [cast_natCast, neg_ofNat_succ]; simp | -[n+1] => by rw [Int.neg_negSucc, cast_natCast]; simp @[simp, norm_cast] theorem cast_subNatNat (m n) : ((Int.subNatNat m n : ℤ) : R) = m - n := by unfold subNatNat cases e : n - m · simp only [ofNat_eq_coe] simp [Nat.le_of_sub_eq_zero e] · rw [cast_negSucc, ← e, Nat.cast_sub <| _root_.le_of_lt <| Nat.lt_of_sub_eq_succ e, neg_sub] @[simp] theorem cast_negOfNat (n : ℕ) : ((negOfNat n : ℤ) : R) = -n := by simp [Int.cast_neg, negOfNat_eq] @[simp, norm_cast] theorem cast_add : ∀ m n, ((m + n : ℤ) : R) = m + n | (m : ℕ), (n : ℕ) => by simp [← Int.natCast_add] | (m : ℕ), -[n+1] => by rw [Int.ofNat_add_negSucc, cast_subNatNat, cast_natCast, cast_negSucc, sub_eq_add_neg] | -[m+1], (n : ℕ) => by rw [Int.negSucc_add_ofNat, cast_subNatNat, cast_natCast, cast_negSucc, sub_eq_iff_eq_add, add_assoc, eq_neg_add_iff_add_eq, ← Nat.cast_add, ← Nat.cast_add, Nat.add_comm] | -[m+1], -[n+1] => by rw [Int.negSucc_add_negSucc, succ_eq_add_one, cast_negSucc, cast_negSucc, cast_negSucc, ← neg_add_rev, ← Nat.cast_add, Nat.add_right_comm m n 1, Nat.add_assoc, Nat.add_comm] @[simp, norm_cast] theorem cast_sub (m n) : ((m - n : ℤ) : R) = m - n := by simp [Int.sub_eq_add_neg, sub_eq_add_neg, Int.cast_neg, Int.cast_add] theorem cast_two : ((2 : ℤ) : R) = 2 := cast_ofNat _ theorem cast_three : ((3 : ℤ) : R) = 3 := cast_ofNat _ theorem cast_four : ((4 : ℤ) : R) = 4 := cast_ofNat _ end Int section zsmul variable {R : Type*} @[simp] lemma zsmul_one [AddGroupWithOne R] (n : ℤ) : n • (1 : R) = n := by cases n <;> simp end zsmul
RiemannZeta.lean
/- Copyright (c) 2023 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import Mathlib.NumberTheory.LSeries.HurwitzZeta import Mathlib.Analysis.PSeriesComplex /-! # Definition of the Riemann zeta function ## Main definitions: * `riemannZeta`: the Riemann zeta function `ζ : ℂ → ℂ`. * `completedRiemannZeta`: the completed zeta function `Λ : ℂ → ℂ`, which satisfies `Λ(s) = π ^ (-s / 2) Γ(s / 2) ζ(s)` (away from the poles of `Γ(s / 2)`). * `completedRiemannZeta₀`: the entire function `Λ₀` satisfying `Λ₀(s) = Λ(s) + 1 / (s - 1) - 1 / s` wherever the RHS is defined. Note that mathematically `ζ(s)` is undefined at `s = 1`, while `Λ(s)` is undefined at both `s = 0` and `s = 1`. Our construction assigns some values at these points; exact formulae involving the Euler-Mascheroni constant will follow in a subsequent PR. ## Main results: * `differentiable_completedZeta₀` : the function `Λ₀(s)` is entire. * `differentiableAt_completedZeta` : the function `Λ(s)` is differentiable away from `s = 0` and `s = 1`. * `differentiableAt_riemannZeta` : the function `ζ(s)` is differentiable away from `s = 1`. * `zeta_eq_tsum_one_div_nat_add_one_cpow` : for `1 < re s`, we have `ζ(s) = ∑' (n : ℕ), 1 / (n + 1) ^ s`. * `completedRiemannZeta₀_one_sub`, `completedRiemannZeta_one_sub`, and `riemannZeta_one_sub` : functional equation relating values at `s` and `1 - s` For special-value formulae expressing `ζ (2 * k)` and `ζ (1 - 2 * k)` in terms of Bernoulli numbers see `Mathlib/NumberTheory/LSeries/HurwitzZetaValues.lean`. For computation of the constant term as `s → 1`, see `Mathlib/NumberTheory/Harmonic/ZetaAsymp.lean`. ## Outline of proofs: These results are mostly special cases of more general results for even Hurwitz zeta functions proved in `Mathlib/NumberTheory/LSeries/HurwitzZetaEven.lean`. -/ open CharZero Set Filter HurwitzZeta open Complex hiding exp continuous_exp open scoped Topology Real noncomputable section /-! ## Definition of the completed Riemann zeta -/ /-- The completed Riemann zeta function with its poles removed, `Λ(s) + 1 / s - 1 / (s - 1)`. -/ def completedRiemannZeta₀ (s : ℂ) : ℂ := completedHurwitzZetaEven₀ 0 s /-- The completed Riemann zeta function, `Λ(s)`, which satisfies `Λ(s) = π ^ (-s / 2) Γ(s / 2) ζ(s)` (up to a minor correction at `s = 0`). -/ def completedRiemannZeta (s : ℂ) : ℂ := completedHurwitzZetaEven 0 s lemma HurwitzZeta.completedHurwitzZetaEven_zero (s : ℂ) : completedHurwitzZetaEven 0 s = completedRiemannZeta s := rfl lemma HurwitzZeta.completedHurwitzZetaEven₀_zero (s : ℂ) : completedHurwitzZetaEven₀ 0 s = completedRiemannZeta₀ s := rfl lemma HurwitzZeta.completedCosZeta_zero (s : ℂ) : completedCosZeta 0 s = completedRiemannZeta s := by rw [completedRiemannZeta, completedHurwitzZetaEven, completedCosZeta, hurwitzEvenFEPair_zero_symm] lemma HurwitzZeta.completedCosZeta₀_zero (s : ℂ) : completedCosZeta₀ 0 s = completedRiemannZeta₀ s := by rw [completedRiemannZeta₀, completedHurwitzZetaEven₀, completedCosZeta₀, hurwitzEvenFEPair_zero_symm] lemma completedRiemannZeta_eq (s : ℂ) : completedRiemannZeta s = completedRiemannZeta₀ s - 1 / s - 1 / (1 - s) := by simp_rw [completedRiemannZeta, completedRiemannZeta₀, completedHurwitzZetaEven_eq, if_true] /-- The modified completed Riemann zeta function `Λ(s) + 1 / s + 1 / (1 - s)` is entire. -/ theorem differentiable_completedZeta₀ : Differentiable ℂ completedRiemannZeta₀ := differentiable_completedHurwitzZetaEven₀ 0 /-- The completed Riemann zeta function `Λ(s)` is differentiable away from `s = 0` and `s = 1`. -/ theorem differentiableAt_completedZeta {s : ℂ} (hs : s ≠ 0) (hs' : s ≠ 1) : DifferentiableAt ℂ completedRiemannZeta s := differentiableAt_completedHurwitzZetaEven 0 (Or.inl hs) hs' /-- Riemann zeta functional equation, formulated for `Λ₀`: for any complex `s` we have `Λ₀(1 - s) = Λ₀ s`. -/ theorem completedRiemannZeta₀_one_sub (s : ℂ) : completedRiemannZeta₀ (1 - s) = completedRiemannZeta₀ s := by rw [← completedHurwitzZetaEven₀_zero, ← completedCosZeta₀_zero, completedHurwitzZetaEven₀_one_sub] /-- Riemann zeta functional equation, formulated for `Λ`: for any complex `s` we have `Λ (1 - s) = Λ s`. -/ theorem completedRiemannZeta_one_sub (s : ℂ) : completedRiemannZeta (1 - s) = completedRiemannZeta s := by rw [← completedHurwitzZetaEven_zero, ← completedCosZeta_zero, completedHurwitzZetaEven_one_sub] /-- The residue of `Λ(s)` at `s = 1` is equal to `1`. -/ lemma completedRiemannZeta_residue_one : Tendsto (fun s ↦ (s - 1) * completedRiemannZeta s) (𝓝[≠] 1) (𝓝 1) := completedHurwitzZetaEven_residue_one 0 /-! ## The un-completed Riemann zeta function -/ /-- The Riemann zeta function `ζ(s)`. -/ def riemannZeta := hurwitzZetaEven 0 lemma HurwitzZeta.hurwitzZetaEven_zero : hurwitzZetaEven 0 = riemannZeta := rfl lemma HurwitzZeta.cosZeta_zero : cosZeta 0 = riemannZeta := by simp_rw [cosZeta, riemannZeta, hurwitzZetaEven, if_true, completedHurwitzZetaEven_zero, completedCosZeta_zero] lemma HurwitzZeta.hurwitzZeta_zero : hurwitzZeta 0 = riemannZeta := by ext1 s simpa [hurwitzZeta, hurwitzZetaEven_zero] using hurwitzZetaOdd_neg 0 s lemma HurwitzZeta.expZeta_zero : expZeta 0 = riemannZeta := by ext1 s rw [expZeta, cosZeta_zero, add_eq_left, mul_eq_zero, eq_false_intro I_ne_zero, false_or, ← eq_neg_self_iff, ← sinZeta_neg, neg_zero] /-- The Riemann zeta function is differentiable away from `s = 1`. -/ theorem differentiableAt_riemannZeta {s : ℂ} (hs' : s ≠ 1) : DifferentiableAt ℂ riemannZeta s := differentiableAt_hurwitzZetaEven _ hs' /-- We have `ζ(0) = -1 / 2`. -/ theorem riemannZeta_zero : riemannZeta 0 = -1 / 2 := by simp_rw [riemannZeta, hurwitzZetaEven, Function.update_self, if_true] lemma riemannZeta_def_of_ne_zero {s : ℂ} (hs : s ≠ 0) : riemannZeta s = completedRiemannZeta s / Gammaℝ s := by rw [riemannZeta, hurwitzZetaEven, Function.update_of_ne hs, completedHurwitzZetaEven_zero] /-- The trivial zeroes of the zeta function. -/ theorem riemannZeta_neg_two_mul_nat_add_one (n : ℕ) : riemannZeta (-2 * (n + 1)) = 0 := hurwitzZetaEven_neg_two_mul_nat_add_one 0 n /-- Riemann zeta functional equation, formulated for `ζ`: if `1 - s ∉ ℕ`, then we have `ζ (1 - s) = 2 ^ (1 - s) * π ^ (-s) * Γ s * sin (π * (1 - s) / 2) * ζ s`. -/ theorem riemannZeta_one_sub {s : ℂ} (hs : ∀ n : ℕ, s ≠ -n) (hs' : s ≠ 1) : riemannZeta (1 - s) = 2 * (2 * π) ^ (-s) * Gamma s * cos (π * s / 2) * riemannZeta s := by rw [riemannZeta, hurwitzZetaEven_one_sub 0 hs (Or.inr hs'), cosZeta_zero, hurwitzZetaEven_zero] /-- A formal statement of the **Riemann hypothesis** – constructing a term of this type is worth a million dollars. -/ def RiemannHypothesis : Prop := ∀ (s : ℂ) (_ : riemannZeta s = 0) (_ : ¬∃ n : ℕ, s = -2 * (n + 1)) (_ : s ≠ 1), s.re = 1 / 2 /-! ## Relating the Mellin transform to the Dirichlet series -/ theorem completedZeta_eq_tsum_of_one_lt_re {s : ℂ} (hs : 1 < re s) : completedRiemannZeta s = (π : ℂ) ^ (-s / 2) * Gamma (s / 2) * ∑' n : ℕ, 1 / (n : ℂ) ^ s := by have := (hasSum_nat_completedCosZeta 0 hs).tsum_eq.symm simp only [QuotientAddGroup.mk_zero, completedCosZeta_zero] at this simp only [this, Gammaℝ_def, mul_zero, zero_mul, Real.cos_zero, ofReal_one, mul_one, mul_one_div, ← tsum_mul_left] congr 1 with n split_ifs with h · simp only [h, Nat.cast_zero, zero_cpow (Complex.ne_zero_of_one_lt_re hs), div_zero] · rfl /-- The Riemann zeta function agrees with the naive Dirichlet-series definition when the latter converges. (Note that this is false without the assumption: when `re s ≤ 1` the sum is divergent, and we use a different definition to obtain the analytic continuation to all `s`.) -/ theorem zeta_eq_tsum_one_div_nat_cpow {s : ℂ} (hs : 1 < re s) : riemannZeta s = ∑' n : ℕ, 1 / (n : ℂ) ^ s := by simpa only [QuotientAddGroup.mk_zero, cosZeta_zero, mul_zero, zero_mul, Real.cos_zero, ofReal_one] using (hasSum_nat_cosZeta 0 hs).tsum_eq.symm /-- Alternate formulation of `zeta_eq_tsum_one_div_nat_cpow` with a `+ 1` (to avoid relying on mathlib's conventions for `0 ^ s`). -/ theorem zeta_eq_tsum_one_div_nat_add_one_cpow {s : ℂ} (hs : 1 < re s) : riemannZeta s = ∑' n : ℕ, 1 / (n + 1 : ℂ) ^ s := by have := zeta_eq_tsum_one_div_nat_cpow hs rw [Summable.tsum_eq_zero_add] at this · simpa [zero_cpow (Complex.ne_zero_of_one_lt_re hs)] · rwa [Complex.summable_one_div_nat_cpow] /-- Special case of `zeta_eq_tsum_one_div_nat_cpow` when the argument is in `ℕ`, so the power function can be expressed using naïve `pow` rather than `cpow`. -/ theorem zeta_nat_eq_tsum_of_gt_one {k : ℕ} (hk : 1 < k) : riemannZeta k = ∑' n : ℕ, 1 / (n : ℂ) ^ k := by simp only [zeta_eq_tsum_one_div_nat_cpow (by rwa [← ofReal_natCast, ofReal_re, ← Nat.cast_one, Nat.cast_lt] : 1 < re k), cpow_natCast] /-- The residue of `ζ(s)` at `s = 1` is equal to 1. -/ lemma riemannZeta_residue_one : Tendsto (fun s ↦ (s - 1) * riemannZeta s) (𝓝[≠] 1) (𝓝 1) := by exact hurwitzZetaEven_residue_one 0 /-- The residue of `ζ(s)` at `s = 1` is equal to 1, expressed using `tsum`. -/ theorem tendsto_sub_mul_tsum_nat_cpow : Tendsto (fun s : ℂ ↦ (s - 1) * ∑' (n : ℕ), 1 / (n : ℂ) ^ s) (𝓝[{s | 1 < re s}] 1) (𝓝 1) := by refine (tendsto_nhdsWithin_mono_left ?_ riemannZeta_residue_one).congr' ?_ · simp only [subset_compl_singleton_iff, mem_setOf_eq, one_re, not_lt, le_refl] · filter_upwards [eventually_mem_nhdsWithin] with s hs using congr_arg _ <| zeta_eq_tsum_one_div_nat_cpow hs /-- The residue of `ζ(s)` at `s = 1` is equal to 1 expressed using `tsum` and for a real variable. -/ theorem tendsto_sub_mul_tsum_nat_rpow : Tendsto (fun s : ℝ ↦ (s - 1) * ∑' (n : ℕ), 1 / (n : ℝ) ^ s) (𝓝[>] 1) (𝓝 1) := by rw [← tendsto_ofReal_iff, ofReal_one] have : Tendsto (fun s : ℝ ↦ (s : ℂ)) (𝓝[>] 1) (𝓝[{s | 1 < re s}] 1) := continuous_ofReal.continuousWithinAt.tendsto_nhdsWithin (fun _ _ ↦ by aesop) apply (tendsto_sub_mul_tsum_nat_cpow.comp this).congr fun s ↦ ?_ simp only [one_div, Function.comp_apply, ofReal_mul, ofReal_sub, ofReal_one, ofReal_tsum, ofReal_inv, ofReal_cpow (Nat.cast_nonneg _), ofReal_natCast]
Defs.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.Order.BoundedOrder.Basic import Mathlib.Order.Monotone.Basic import Mathlib.Tactic.Monotonicity.Attr import Mathlib.Util.AssertExists /-! # Galois connections, insertions and coinsertions Galois connections are order theoretic adjoints, i.e. a pair of functions `u` and `l`, such that `∀ a b, l a ≤ b ↔ a ≤ u b`. ## Main definitions * `GaloisConnection`: A Galois connection is a pair of functions `l` and `u` satisfying `l a ≤ b ↔ a ≤ u b`. They are special cases of adjoint functors in category theory, but do not depend on the category theory library in mathlib. * `GaloisInsertion`: A Galois insertion is a Galois connection where `l ∘ u = id` * `GaloisCoinsertion`: A Galois coinsertion is a Galois connection where `u ∘ l = id` -/ assert_not_exists CompleteLattice RelIso open Function OrderDual Set universe u v w x variable {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {κ : ι → Sort*} {a₁ a₂ : α} {b₁ b₂ : β} /-- A Galois connection is a pair of functions `l` and `u` satisfying `l a ≤ b ↔ a ≤ u b`. They are special cases of adjoint functors in category theory, but do not depend on the category theory library in mathlib. -/ def GaloisConnection [Preorder α] [Preorder β] (l : α → β) (u : β → α) := ∀ a b, l a ≤ b ↔ a ≤ u b namespace GaloisConnection section variable [Preorder α] [Preorder β] {l : α → β} {u : β → α} theorem monotone_intro (hu : Monotone u) (hl : Monotone l) (hul : ∀ a, a ≤ u (l a)) (hlu : ∀ a, l (u a) ≤ a) : GaloisConnection l u := fun _ _ => ⟨fun h => (hul _).trans (hu h), fun h => (hl h).trans (hlu _)⟩ protected theorem dual {l : α → β} {u : β → α} (gc : GaloisConnection l u) : GaloisConnection (OrderDual.toDual ∘ u ∘ OrderDual.ofDual) (OrderDual.toDual ∘ l ∘ OrderDual.ofDual) := fun a b => (gc b a).symm variable (gc : GaloisConnection l u) include gc theorem le_iff_le {a : α} {b : β} : l a ≤ b ↔ a ≤ u b := gc _ _ theorem l_le {a : α} {b : β} : a ≤ u b → l a ≤ b := (gc _ _).mpr theorem le_u {a : α} {b : β} : l a ≤ b → a ≤ u b := (gc _ _).mp theorem le_u_l (a) : a ≤ u (l a) := gc.le_u <| le_rfl theorem l_u_le (a) : l (u a) ≤ a := gc.l_le <| le_rfl theorem monotone_u : Monotone u := fun a _ H => gc.le_u ((gc.l_u_le a).trans H) theorem monotone_l : Monotone l := gc.dual.monotone_u.dual /-- If `(l, u)` is a Galois connection, then the relation `x ≤ u (l y)` is a transitive relation. If `l` is a closure operator (`Submodule.span`, `Subgroup.closure`, ...) and `u` is the coercion to `Set`, this reads as "if `U` is in the closure of `V` and `V` is in the closure of `W` then `U` is in the closure of `W`". -/ theorem le_u_l_trans {x y z : α} (hxy : x ≤ u (l y)) (hyz : y ≤ u (l z)) : x ≤ u (l z) := hxy.trans (gc.monotone_u <| gc.l_le hyz) theorem l_u_le_trans {x y z : β} (hxy : l (u x) ≤ y) (hyz : l (u y) ≤ z) : l (u x) ≤ z := (gc.monotone_l <| gc.le_u hxy).trans hyz end section PartialOrder variable [PartialOrder α] [Preorder β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) include gc theorem u_l_u_eq_u (b : β) : u (l (u b)) = u b := (gc.monotone_u (gc.l_u_le _)).antisymm (gc.le_u_l _) theorem u_l_u_eq_u' : u ∘ l ∘ u = u := funext gc.u_l_u_eq_u theorem u_unique {l' : α → β} {u' : β → α} (gc' : GaloisConnection l' u') (hl : ∀ a, l a = l' a) {b : β} : u b = u' b := le_antisymm (gc'.le_u <| hl (u b) ▸ gc.l_u_le _) (gc.le_u <| (hl (u' b)).symm ▸ gc'.l_u_le _) /-- If there exists a `b` such that `a = u a`, then `b = l a` is one such element. -/ theorem exists_eq_u (a : α) : (∃ b : β, a = u b) ↔ a = u (l a) := ⟨fun ⟨_, hS⟩ => hS.symm ▸ (gc.u_l_u_eq_u _).symm, fun HI => ⟨_, HI⟩⟩ theorem u_eq {z : α} {y : β} : u y = z ↔ ∀ x, x ≤ z ↔ l x ≤ y := by constructor · rintro rfl x exact (gc x y).symm · intro H exact ((H <| u y).mpr (gc.l_u_le y)).antisymm ((gc _ _).mp <| (H z).mp le_rfl) end PartialOrder section PartialOrder variable [Preorder α] [PartialOrder β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) include gc theorem l_u_l_eq_l (a : α) : l (u (l a)) = l a := gc.dual.u_l_u_eq_u _ theorem l_u_l_eq_l' : l ∘ u ∘ l = l := funext gc.l_u_l_eq_l theorem l_unique {l' : α → β} {u' : β → α} (gc' : GaloisConnection l' u') (hu : ∀ b, u b = u' b) {a : α} : l a = l' a := gc.dual.u_unique gc'.dual hu /-- If there exists an `a` such that `b = l a`, then `a = u b` is one such element. -/ theorem exists_eq_l (b : β) : (∃ a : α, b = l a) ↔ b = l (u b) := gc.dual.exists_eq_u _ theorem l_eq {x : α} {z : β} : l x = z ↔ ∀ y, z ≤ y ↔ x ≤ u y := gc.dual.u_eq end PartialOrder section OrderTop variable [PartialOrder α] [Preorder β] [OrderTop α] theorem u_eq_top {l : α → β} {u : β → α} (gc : GaloisConnection l u) {x} : u x = ⊤ ↔ l ⊤ ≤ x := top_le_iff.symm.trans gc.le_iff_le.symm theorem u_top [OrderTop β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) : u ⊤ = ⊤ := gc.u_eq_top.2 le_top theorem u_l_top {l : α → β} {u : β → α} (gc : GaloisConnection l u) : u (l ⊤) = ⊤ := gc.u_eq_top.mpr le_rfl end OrderTop section OrderBot variable [Preorder α] [PartialOrder β] [OrderBot β] theorem l_eq_bot {l : α → β} {u : β → α} (gc : GaloisConnection l u) {x} : l x = ⊥ ↔ x ≤ u ⊥ := gc.dual.u_eq_top theorem l_bot [OrderBot α] {l : α → β} {u : β → α} (gc : GaloisConnection l u) : l ⊥ = ⊥ := gc.dual.u_top theorem l_u_bot {l : α → β} {u : β → α} (gc : GaloisConnection l u) : l (u ⊥) = ⊥ := gc.l_eq_bot.mpr le_rfl end OrderBot section LinearOrder variable [LinearOrder α] [LinearOrder β] {l : α → β} {u : β → α} theorem lt_iff_lt (gc : GaloisConnection l u) {a : α} {b : β} : b < l a ↔ u b < a := lt_iff_lt_of_le_iff_le (gc a b) end LinearOrder -- Constructing Galois connections section Constructions protected theorem id [pα : Preorder α] : @GaloisConnection α α pα pα id id := fun _ _ => Iff.intro (fun x => x) fun x => x protected theorem compose [Preorder α] [Preorder β] [Preorder γ] {l1 : α → β} {u1 : β → α} {l2 : β → γ} {u2 : γ → β} (gc1 : GaloisConnection l1 u1) (gc2 : GaloisConnection l2 u2) : GaloisConnection (l2 ∘ l1) (u1 ∘ u2) := fun _ _ ↦ (gc2 _ _).trans (gc1 _ _) protected theorem dfun {ι : Type u} {α : ι → Type v} {β : ι → Type w} [∀ i, Preorder (α i)] [∀ i, Preorder (β i)] (l : ∀ i, α i → β i) (u : ∀ i, β i → α i) (gc : ∀ i, GaloisConnection (l i) (u i)) : GaloisConnection (fun (a : ∀ i, α i) i => l i (a i)) fun b i => u i (b i) := fun a b => forall_congr' fun i => gc i (a i) (b i) end Constructions theorem l_comm_of_u_comm {X : Type*} [Preorder X] {Y : Type*} [Preorder Y] {Z : Type*} [Preorder Z] {W : Type*} [PartialOrder W] {lYX : X → Y} {uXY : Y → X} (hXY : GaloisConnection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : GaloisConnection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : GaloisConnection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : GaloisConnection lZX uXZ) (h : ∀ w, uXZ (uZW w) = uXY (uYW w)) {x : X} : lWZ (lZX x) = lWY (lYX x) := (hXZ.compose hZW).l_unique (hXY.compose hWY) h theorem u_comm_of_l_comm {X : Type*} [PartialOrder X] {Y : Type*} [Preorder Y] {Z : Type*} [Preorder Z] {W : Type*} [Preorder W] {lYX : X → Y} {uXY : Y → X} (hXY : GaloisConnection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : GaloisConnection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : GaloisConnection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : GaloisConnection lZX uXZ) (h : ∀ x, lWZ (lZX x) = lWY (lYX x)) {w : W} : uXZ (uZW w) = uXY (uYW w) := (hXZ.compose hZW).u_unique (hXY.compose hWY) h theorem l_comm_iff_u_comm {X : Type*} [PartialOrder X] {Y : Type*} [Preorder Y] {Z : Type*} [Preorder Z] {W : Type*} [PartialOrder W] {lYX : X → Y} {uXY : Y → X} (hXY : GaloisConnection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : GaloisConnection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : GaloisConnection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : GaloisConnection lZX uXZ) : (∀ w : W, uXZ (uZW w) = uXY (uYW w)) ↔ ∀ x : X, lWZ (lZX x) = lWY (lYX x) := ⟨hXY.l_comm_of_u_comm hZW hWY hXZ, hXY.u_comm_of_l_comm hZW hWY hXZ⟩ end GaloisConnection /-- A Galois insertion is a Galois connection where `l ∘ u = id`. It also contains a constructive choice function, to give better definitional equalities when lifting order structures. Dual to `GaloisCoinsertion` -/ structure GaloisInsertion {α β : Type*} [Preorder α] [Preorder β] (l : α → β) (u : β → α) where /-- A contructive choice function for images of `l`. -/ choice : ∀ x : α, u (l x) ≤ x → β /-- The Galois connection associated to a Galois insertion. -/ gc : GaloisConnection l u /-- Main property of a Galois insertion. -/ le_l_u : ∀ x, x ≤ l (u x) /-- Property of the choice function. -/ choice_eq : ∀ a h, choice a h = l a /-- A constructor for a Galois insertion with the trivial `choice` function. -/ def GaloisInsertion.monotoneIntro {α β : Type*} [Preorder α] [Preorder β] {l : α → β} {u : β → α} (hu : Monotone u) (hl : Monotone l) (hul : ∀ a, a ≤ u (l a)) (hlu : ∀ b, l (u b) = b) : GaloisInsertion l u where choice x _ := l x gc := GaloisConnection.monotone_intro hu hl hul fun b => le_of_eq (hlu b) le_l_u b := le_of_eq <| (hlu b).symm choice_eq _ _ := rfl /-- Make a `GaloisInsertion l u` from a `GaloisConnection l u` such that `∀ b, b ≤ l (u b)` -/ def GaloisConnection.toGaloisInsertion {α β : Type*} [Preorder α] [Preorder β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) (h : ∀ b, b ≤ l (u b)) : GaloisInsertion l u := { choice := fun x _ => l x gc le_l_u := h choice_eq := fun _ _ => rfl } /-- Lift the bottom along a Galois connection -/ def GaloisConnection.liftOrderBot {α β : Type*} [Preorder α] [OrderBot α] [PartialOrder β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) : OrderBot β where bot := l ⊥ bot_le _ := gc.l_le <| bot_le namespace GaloisInsertion variable {l : α → β} {u : β → α} theorem l_u_eq [Preorder α] [PartialOrder β] (gi : GaloisInsertion l u) (b : β) : l (u b) = b := (gi.gc.l_u_le _).antisymm (gi.le_l_u _) theorem leftInverse_l_u [Preorder α] [PartialOrder β] (gi : GaloisInsertion l u) : LeftInverse l u := gi.l_u_eq theorem l_top [Preorder α] [PartialOrder β] [OrderTop α] [OrderTop β] (gi : GaloisInsertion l u) : l ⊤ = ⊤ := top_unique <| (gi.le_l_u _).trans <| gi.gc.monotone_l le_top theorem l_surjective [Preorder α] [PartialOrder β] (gi : GaloisInsertion l u) : Surjective l := gi.leftInverse_l_u.surjective theorem u_injective [Preorder α] [PartialOrder β] (gi : GaloisInsertion l u) : Injective u := gi.leftInverse_l_u.injective theorem u_le_u_iff [Preorder α] [Preorder β] (gi : GaloisInsertion l u) {a b} : u a ≤ u b ↔ a ≤ b := ⟨fun h => (gi.le_l_u _).trans (gi.gc.l_le h), fun h => gi.gc.monotone_u h⟩ theorem strictMono_u [Preorder α] [Preorder β] (gi : GaloisInsertion l u) : StrictMono u := strictMono_of_le_iff_le fun _ _ => gi.u_le_u_iff.symm end GaloisInsertion /-- A Galois coinsertion is a Galois connection where `u ∘ l = id`. It also contains a constructive choice function, to give better definitional equalities when lifting order structures. Dual to `GaloisInsertion` -/ structure GaloisCoinsertion [Preorder α] [Preorder β] (l : α → β) (u : β → α) where /-- A contructive choice function for images of `u`. -/ choice : ∀ x : β, x ≤ l (u x) → α /-- The Galois connection associated to a Galois coinsertion. -/ gc : GaloisConnection l u /-- Main property of a Galois coinsertion. -/ u_l_le : ∀ x, u (l x) ≤ x /-- Property of the choice function. -/ choice_eq : ∀ a h, choice a h = u a /-- Make a `GaloisInsertion` between `αᵒᵈ` and `βᵒᵈ` from a `GaloisCoinsertion` between `α` and `β`. -/ def GaloisCoinsertion.dual [Preorder α] [Preorder β] {l : α → β} {u : β → α} : GaloisCoinsertion l u → GaloisInsertion (toDual ∘ u ∘ ofDual) (toDual ∘ l ∘ ofDual) := fun x => ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `GaloisCoinsertion` between `αᵒᵈ` and `βᵒᵈ` from a `GaloisInsertion` between `α` and `β`. -/ def GaloisInsertion.dual [Preorder α] [Preorder β] {l : α → β} {u : β → α} : GaloisInsertion l u → GaloisCoinsertion (toDual ∘ u ∘ ofDual) (toDual ∘ l ∘ ofDual) := fun x => ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `GaloisInsertion` between `α` and `β` from a `GaloisCoinsertion` between `αᵒᵈ` and `βᵒᵈ`. -/ def GaloisCoinsertion.ofDual [Preorder α] [Preorder β] {l : αᵒᵈ → βᵒᵈ} {u : βᵒᵈ → αᵒᵈ} : GaloisCoinsertion l u → GaloisInsertion (ofDual ∘ u ∘ toDual) (ofDual ∘ l ∘ toDual) := fun x => ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `GaloisCoinsertion` between `α` and `β` from a `GaloisInsertion` between `αᵒᵈ` and `βᵒᵈ`. -/ def GaloisInsertion.ofDual [Preorder α] [Preorder β] {l : αᵒᵈ → βᵒᵈ} {u : βᵒᵈ → αᵒᵈ} : GaloisInsertion l u → GaloisCoinsertion (ofDual ∘ u ∘ toDual) (ofDual ∘ l ∘ toDual) := fun x => ⟨x.1, x.2.dual, x.3, x.4⟩ /-- A constructor for a Galois coinsertion with the trivial `choice` function. -/ def GaloisCoinsertion.monotoneIntro [Preorder α] [Preorder β] {l : α → β} {u : β → α} (hu : Monotone u) (hl : Monotone l) (hlu : ∀ b, l (u b) ≤ b) (hul : ∀ a, u (l a) = a) : GaloisCoinsertion l u := (GaloisInsertion.monotoneIntro hl.dual hu.dual hlu hul).ofDual /-- Make a `GaloisCoinsertion l u` from a `GaloisConnection l u` such that `∀ a, u (l a) ≤ a` -/ def GaloisConnection.toGaloisCoinsertion {α β : Type*} [Preorder α] [Preorder β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) (h : ∀ a, u (l a) ≤ a) : GaloisCoinsertion l u := { choice := fun x _ => u x gc u_l_le := h choice_eq := fun _ _ => rfl } /-- Lift the top along a Galois connection -/ def GaloisConnection.liftOrderTop {α β : Type*} [PartialOrder α] [Preorder β] [OrderTop β] {l : α → β} {u : β → α} (gc : GaloisConnection l u) : OrderTop α where top := u ⊤ le_top _ := gc.le_u <| le_top namespace GaloisCoinsertion variable {l : α → β} {u : β → α} theorem u_l_eq [PartialOrder α] [Preorder β] (gi : GaloisCoinsertion l u) (a : α) : u (l a) = a := gi.dual.l_u_eq a theorem u_l_leftInverse [PartialOrder α] [Preorder β] (gi : GaloisCoinsertion l u) : LeftInverse u l := gi.u_l_eq theorem u_bot [PartialOrder α] [Preorder β] [OrderBot α] [OrderBot β] (gi : GaloisCoinsertion l u) : u ⊥ = ⊥ := gi.dual.l_top theorem u_surjective [PartialOrder α] [Preorder β] (gi : GaloisCoinsertion l u) : Surjective u := gi.dual.l_surjective theorem l_injective [PartialOrder α] [Preorder β] (gi : GaloisCoinsertion l u) : Injective l := gi.dual.u_injective theorem l_le_l_iff [Preorder α] [Preorder β] (gi : GaloisCoinsertion l u) {a b} : l a ≤ l b ↔ a ≤ b := gi.dual.u_le_u_iff theorem strictMono_l [Preorder α] [Preorder β] (gi : GaloisCoinsertion l u) : StrictMono l := fun _ _ h => gi.dual.strictMono_u h end GaloisCoinsertion
ModifyLast.lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import Batteries.Data.List.Basic import Batteries.Tactic.Alias import Mathlib.Tactic.TypeStar /-! ### List.modifyLast -/ variable {α : Type*} namespace List private theorem modifyLast.go_concat (f : α → α) (a : α) (tl : List α) (r : Array α) : modifyLast.go f (tl ++ [a]) r = (r.toListAppend <| modifyLast.go f (tl ++ [a]) #[]) := by cases tl with | nil => simp only [nil_append, modifyLast.go]; rfl | cons hd tl => simp only [cons_append] rw [modifyLast.go, modifyLast.go] case x_3 | x_3 => exact append_ne_nil_of_right_ne_nil tl (cons_ne_nil a []) rw [modifyLast.go_concat _ _ tl _, modifyLast.go_concat _ _ tl (Array.push #[] hd)] simp only [Array.toListAppend_eq, Array.toList_push, nil_append, append_assoc] theorem modifyLast_concat (f : α → α) (a : α) (l : List α) : modifyLast f (l ++ [a]) = l ++ [f a] := by cases l with | nil => simp only [nil_append, modifyLast, modifyLast.go, Array.toListAppend_eq] | cons _ tl => simp only [cons_append, modifyLast] rw [modifyLast.go] case x_3 => exact append_ne_nil_of_right_ne_nil tl (cons_ne_nil a []) rw [modifyLast.go_concat, Array.toListAppend_eq, Array.toList_push, List.toList_toArray, nil_append, cons_append, nil_append, cons_inj_right] exact modifyLast_concat _ _ tl @[deprecated (since := "2025-02-07")] alias modifyLast_append_one := modifyLast_concat theorem modifyLast_append_of_right_ne_nil (f : α → α) (l₁ l₂ : List α) (_ : l₂ ≠ []) : modifyLast f (l₁ ++ l₂) = l₁ ++ modifyLast f l₂ := by cases l₂ with | nil => contradiction | cons hd tl => cases tl with | nil => exact modifyLast_concat _ hd _ | cons hd' tl' => rw [append_cons, ← nil_append (hd :: hd' :: tl'), append_cons [], nil_append, modifyLast_append_of_right_ne_nil _ (l₁ ++ [hd]) (hd' :: tl') _, modifyLast_append_of_right_ne_nil _ [hd] (hd' :: tl') _, append_assoc] all_goals { exact cons_ne_nil _ _ } @[deprecated (since := "2025-02-07")] alias modifyLast_append := modifyLast_append_of_right_ne_nil end List
Prj.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Functor.Multivariate import Mathlib.Data.QPF.Multivariate.Basic /-! Projection functors are QPFs. The `n`-ary projection functors on `i` is an `n`-ary functor `F` such that `F (α₀..αᵢ₋₁, αᵢ, αᵢ₊₁..αₙ₋₁) = αᵢ` -/ universe u v namespace MvQPF open MvFunctor variable {n : ℕ} (i : Fin2 n) /-- The projection `i` functor -/ def Prj (v : TypeVec.{u} n) : Type u := v i instance Prj.inhabited {v : TypeVec.{u} n} [Inhabited (v i)] : Inhabited (Prj i v) := ⟨(default : v i)⟩ /-- `map` on functor `Prj i` -/ def Prj.map ⦃α β : TypeVec n⦄ (f : α ⟹ β) : Prj i α → Prj i β := f _ instance Prj.mvfunctor : MvFunctor (Prj i) where map := @Prj.map _ i /-- Polynomial representation of the projection functor -/ def Prj.P : MvPFunctor.{u} n where A := PUnit B _ j := ULift <| PLift <| i = j /-- Abstraction function of the `QPF` instance -/ def Prj.abs ⦃α : TypeVec n⦄ : Prj.P i α → Prj i α | ⟨_x, f⟩ => f _ ⟨⟨rfl⟩⟩ /-- Representation function of the `QPF` instance -/ def Prj.repr ⦃α : TypeVec n⦄ : Prj i α → Prj.P i α := fun x : α i => ⟨⟨⟩, fun j ⟨⟨h⟩⟩ => (h.rec x : α j)⟩ instance Prj.mvqpf : MvQPF (Prj i) where P := Prj.P i abs := @Prj.abs _ i repr := @Prj.repr _ i abs_repr := by intros; rfl abs_map := by intros α β f P; cases P; rfl end MvQPF
Gershgorin.lean
/- Copyright (c) 2023 Xavier Roblot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Xavier Roblot -/ import Mathlib.Analysis.Normed.Field.Basic import Mathlib.LinearAlgebra.Eigenspace.Basic import Mathlib.LinearAlgebra.Determinant /-! # Gershgorin's circle theorem This file gives the proof of Gershgorin's circle theorem `eigenvalue_mem_ball` on the eigenvalues of matrices and some applications. ## Reference * https://en.wikipedia.org/wiki/Gershgorin_circle_theorem -/ variable {K n : Type*} [NormedField K] [Fintype n] [DecidableEq n] {A : Matrix n n K} /-- **Gershgorin's circle theorem**: for any eigenvalue `μ` of a square matrix `A`, there exists an index `k` such that `μ` lies in the closed ball of center the diagonal term `A k k` and of radius the sum of the norms `∑ j ≠ k, ‖A k j‖. -/ theorem eigenvalue_mem_ball {μ : K} (hμ : Module.End.HasEigenvalue (Matrix.toLin' A) μ) : ∃ k, μ ∈ Metric.closedBall (A k k) (∑ j ∈ Finset.univ.erase k, ‖A k j‖) := by cases isEmpty_or_nonempty n · exfalso exact hμ Submodule.eq_bot_of_subsingleton · obtain ⟨v, h_eg, h_nz⟩ := hμ.exists_hasEigenvector obtain ⟨i, -, h_i⟩ := Finset.exists_mem_eq_sup' Finset.univ_nonempty (fun i => ‖v i‖) have h_nz : v i ≠ 0 := by contrapose! h_nz ext j rw [Pi.zero_apply, ← norm_le_zero_iff] refine (h_i ▸ Finset.le_sup' (fun i => ‖v i‖) (Finset.mem_univ j)).trans ?_ exact norm_le_zero_iff.mpr h_nz have h_le : ∀ j, ‖v j * (v i)⁻¹‖ ≤ 1 := fun j => by rw [norm_mul, norm_inv, mul_inv_le_iff₀ (norm_pos_iff.mpr h_nz), one_mul] exact h_i ▸ Finset.le_sup' (fun i => ‖v i‖) (Finset.mem_univ j) simp_rw [mem_closedBall_iff_norm'] refine ⟨i, ?_⟩ calc _ = ‖(A i i * v i - μ * v i) * (v i)⁻¹‖ := by congr; field_simp [h_nz]; ring _ = ‖(A i i * v i - ∑ j, A i j * v j) * (v i)⁻¹‖ := by rw [show μ * v i = ∑ x : n, A i x * v x by rw [← dotProduct, ← Matrix.mulVec] exact (congrFun (Module.End.mem_eigenspace_iff.mp h_eg) i).symm] _ = ‖(∑ j ∈ Finset.univ.erase i, A i j * v j) * (v i)⁻¹‖ := by rw [Finset.sum_erase_eq_sub (Finset.mem_univ i), ← neg_sub, neg_mul, norm_neg] _ ≤ ∑ j ∈ Finset.univ.erase i, ‖A i j‖ * ‖v j * (v i)⁻¹‖ := by rw [Finset.sum_mul] exact (norm_sum_le _ _).trans (le_of_eq (by simp_rw [mul_assoc, norm_mul])) _ ≤ ∑ j ∈ Finset.univ.erase i, ‖A i j‖ := (Finset.sum_le_sum fun j _ => mul_le_of_le_one_right (norm_nonneg _) (h_le j)) /-- If `A` is a row strictly dominant diagonal matrix, then it's determinant is nonzero. -/ theorem det_ne_zero_of_sum_row_lt_diag (h : ∀ k, ∑ j ∈ Finset.univ.erase k, ‖A k j‖ < ‖A k k‖) : A.det ≠ 0 := by contrapose! h suffices ∃ k, 0 ∈ Metric.closedBall (A k k) (∑ j ∈ Finset.univ.erase k, ‖A k j‖) by exact this.imp (fun a h ↦ by rwa [mem_closedBall_iff_norm', sub_zero] at h) refine eigenvalue_mem_ball ?_ rw [Module.End.hasEigenvalue_iff, Module.End.eigenspace_zero, ne_comm] exact ne_of_lt (LinearMap.bot_lt_ker_of_det_eq_zero (by rwa [LinearMap.det_toLin'])) /-- If `A` is a column strictly dominant diagonal matrix, then it's determinant is nonzero. -/ theorem det_ne_zero_of_sum_col_lt_diag (h : ∀ k, ∑ i ∈ Finset.univ.erase k, ‖A i k‖ < ‖A k k‖) : A.det ≠ 0 := by rw [← Matrix.det_transpose] exact det_ne_zero_of_sum_row_lt_diag (by simp_rw [Matrix.transpose_apply]; exact h)
Opens.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, Floris van Doorn -/ import Mathlib.Order.Hom.CompleteLattice import Mathlib.Topology.Compactness.Bases import Mathlib.Topology.ContinuousMap.Basic import Mathlib.Order.CompactlyGenerated.Basic import Mathlib.Order.Copy /-! # Open sets ## Summary We define the subtype of open sets in a topological space. ## Main Definitions ### Bundled open sets - `TopologicalSpace.Opens α` is the type of open subsets of a topological space `α`. - `TopologicalSpace.Opens.IsBasis` is a predicate saying that a set of `Opens`s form a topological basis. - `TopologicalSpace.Opens.comap`: preimage of an open set under a continuous map as a `FrameHom`. - `Homeomorph.opensCongr`: order-preserving equivalence between open sets in the domain and the codomain of a homeomorphism. ### Bundled open neighborhoods - `TopologicalSpace.OpenNhdsOf x` is the type of open subsets of a topological space `α` containing `x : α`. - `TopologicalSpace.OpenNhdsOf.comap f x U` is the preimage of open neighborhood `U` of `f x` under `f : C(α, β)`. ## Main results We define order structures on both `Opens α` (`CompleteLattice`, `Frame`) and `OpenNhdsOf x` (`OrderTop`, `DistribLattice`). ## TODO - Rename `TopologicalSpace.Opens` to `Open`? - Port the `auto_cases` tactic version (as a plugin if the ported `auto_cases` will allow plugins). -/ open Filter Function Order Set open Topology variable {ι α β γ : Type*} [TopologicalSpace α] [TopologicalSpace β] [TopologicalSpace γ] namespace TopologicalSpace variable (α) in /-- The type of open subsets of a topological space. -/ structure Opens where /-- The underlying set of a bundled `TopologicalSpace.Opens` object. -/ carrier : Set α /-- The `TopologicalSpace.Opens.carrier _` is an open set. -/ is_open' : IsOpen carrier namespace Opens instance : SetLike (Opens α) α where coe := Opens.carrier coe_injective' := fun ⟨_, _⟩ ⟨_, _⟩ _ => by congr instance : CanLift (Set α) (Opens α) (↑) IsOpen := ⟨fun s h => ⟨⟨s, h⟩, rfl⟩⟩ instance instSecondCountableOpens [SecondCountableTopology α] (U : Opens α) : SecondCountableTopology U := inferInstanceAs (SecondCountableTopology U.1) theorem «forall» {p : Opens α → Prop} : (∀ U, p U) ↔ ∀ (U : Set α) (hU : IsOpen U), p ⟨U, hU⟩ := ⟨fun h _ _ => h _, fun h _ => h _ _⟩ @[simp] theorem carrier_eq_coe (U : Opens α) : U.1 = ↑U := rfl /-- the coercion `Opens α → Set α` applied to a pair is the same as taking the first component -/ @[simp] theorem coe_mk {U : Set α} {hU : IsOpen U} : ↑(⟨U, hU⟩ : Opens α) = U := rfl @[simp] theorem mem_mk {x : α} {U : Set α} {h : IsOpen U} : x ∈ mk U h ↔ x ∈ U := Iff.rfl protected theorem nonempty_coeSort {U : Opens α} : Nonempty U ↔ (U : Set α).Nonempty := Set.nonempty_coe_sort -- TODO: should this theorem be proved for a `SetLike`? protected theorem nonempty_coe {U : Opens α} : (U : Set α).Nonempty ↔ ∃ x, x ∈ U := Iff.rfl @[ext] -- TODO: replace with `∀ x, x ∈ U ↔ x ∈ V`? theorem ext {U V : Opens α} (h : (U : Set α) = V) : U = V := SetLike.coe_injective h theorem coe_inj {U V : Opens α} : (U : Set α) = V ↔ U = V := SetLike.ext'_iff.symm /-- A version of `Set.inclusion` not requiring definitional abuse -/ abbrev inclusion {U V : Opens α} (h : U ≤ V) : U → V := Set.inclusion h protected theorem isOpen (U : Opens α) : IsOpen (U : Set α) := U.is_open' @[simp] theorem mk_coe (U : Opens α) : mk (↑U) U.isOpen = U := rfl /-- See Note [custom simps projection]. -/ def Simps.coe (U : Opens α) : Set α := U initialize_simps_projections Opens (carrier → coe, as_prefix coe) /-- The interior of a set, as an element of `Opens`. -/ @[simps] protected def interior (s : Set α) : Opens α := ⟨interior s, isOpen_interior⟩ @[simp] theorem mem_interior {s : Set α} {x : α} : x ∈ Opens.interior s ↔ x ∈ _root_.interior s := .rfl theorem gc : GaloisConnection ((↑) : Opens α → Set α) Opens.interior := fun U _ => ⟨fun h => interior_maximal h U.isOpen, fun h => le_trans h interior_subset⟩ /-- The galois coinsertion between sets and opens. -/ def gi : GaloisCoinsertion (↑) (@Opens.interior α _) where choice s hs := ⟨s, interior_eq_iff_isOpen.mp <| le_antisymm interior_subset hs⟩ gc := gc u_l_le _ := interior_subset choice_eq _s hs := le_antisymm hs interior_subset instance : CompleteLattice (Opens α) := CompleteLattice.copy (GaloisCoinsertion.liftCompleteLattice gi) -- le (fun U V => (U : Set α) ⊆ V) rfl -- top ⟨univ, isOpen_univ⟩ (ext interior_univ.symm) -- bot ⟨∅, isOpen_empty⟩ rfl -- sup (fun U V => ⟨↑U ∪ ↑V, U.2.union V.2⟩) rfl -- inf (fun U V => ⟨↑U ∩ ↑V, U.2.inter V.2⟩) (funext₂ fun U V => ext (U.2.inter V.2).interior_eq.symm) -- sSup (fun S => ⟨⋃ s ∈ S, ↑s, isOpen_biUnion fun s _ => s.2⟩) (funext fun _ => ext sSup_image.symm) -- sInf _ rfl @[simp] theorem mk_inf_mk {U V : Set α} {hU : IsOpen U} {hV : IsOpen V} : (⟨U, hU⟩ ⊓ ⟨V, hV⟩ : Opens α) = ⟨U ⊓ V, IsOpen.inter hU hV⟩ := rfl @[simp, norm_cast] theorem coe_inf (s t : Opens α) : (↑(s ⊓ t) : Set α) = ↑s ∩ ↑t := rfl @[simp] lemma mem_inf {s t : Opens α} {x : α} : x ∈ s ⊓ t ↔ x ∈ s ∧ x ∈ t := Iff.rfl @[simp, norm_cast] theorem coe_sup (s t : Opens α) : (↑(s ⊔ t) : Set α) = ↑s ∪ ↑t := rfl @[simp, norm_cast] theorem coe_bot : ((⊥ : Opens α) : Set α) = ∅ := rfl @[simp] lemma mem_bot {x : α} : x ∈ (⊥ : Opens α) ↔ False := Iff.rfl @[simp] theorem mk_empty : (⟨∅, isOpen_empty⟩ : Opens α) = ⊥ := rfl @[simp, norm_cast] theorem coe_eq_empty {U : Opens α} : (U : Set α) = ∅ ↔ U = ⊥ := SetLike.coe_injective.eq_iff' rfl @[simp] lemma mem_top (x : α) : x ∈ (⊤ : Opens α) := trivial @[simp, norm_cast] theorem coe_top : ((⊤ : Opens α) : Set α) = Set.univ := rfl @[simp] theorem mk_univ : (⟨univ, isOpen_univ⟩ : Opens α) = ⊤ := rfl @[simp, norm_cast] theorem coe_eq_univ {U : Opens α} : (U : Set α) = univ ↔ U = ⊤ := SetLike.coe_injective.eq_iff' rfl @[simp, norm_cast] theorem coe_sSup {S : Set (Opens α)} : (↑(sSup S) : Set α) = ⋃ i ∈ S, ↑i := rfl @[simp, norm_cast] theorem coe_finset_sup (f : ι → Opens α) (s : Finset ι) : (↑(s.sup f) : Set α) = s.sup ((↑) ∘ f) := map_finset_sup (⟨⟨(↑), coe_sup⟩, coe_bot⟩ : SupBotHom (Opens α) (Set α)) _ _ @[simp, norm_cast] theorem coe_finset_inf (f : ι → Opens α) (s : Finset ι) : (↑(s.inf f) : Set α) = s.inf ((↑) ∘ f) := map_finset_inf (⟨⟨(↑), coe_inf⟩, coe_top⟩ : InfTopHom (Opens α) (Set α)) _ _ instance : Inhabited (Opens α) := ⟨⊥⟩ instance [IsEmpty α] : Unique (Opens α) where uniq _ := ext <| Subsingleton.elim _ _ instance [Nonempty α] : Nontrivial (Opens α) where exists_pair_ne := ⟨⊥, ⊤, mt coe_inj.2 empty_ne_univ⟩ @[simp, norm_cast] theorem coe_iSup {ι} (s : ι → Opens α) : ((⨆ i, s i : Opens α) : Set α) = ⋃ i, s i := by simp [iSup] theorem iSup_def {ι} (s : ι → Opens α) : ⨆ i, s i = ⟨⋃ i, s i, isOpen_iUnion fun i => (s i).2⟩ := ext <| coe_iSup s @[simp] theorem iSup_mk {ι} (s : ι → Set α) (h : ∀ i, IsOpen (s i)) : (⨆ i, ⟨s i, h i⟩ : Opens α) = ⟨⋃ i, s i, isOpen_iUnion h⟩ := iSup_def _ @[simp] theorem mem_iSup {ι} {x : α} {s : ι → Opens α} : x ∈ iSup s ↔ ∃ i, x ∈ s i := by rw [← SetLike.mem_coe] simp @[simp] theorem mem_sSup {Us : Set (Opens α)} {x : α} : x ∈ sSup Us ↔ ∃ u ∈ Us, x ∈ u := by simp_rw [sSup_eq_iSup, mem_iSup, exists_prop] /-- Open sets in a topological space form a frame. -/ def frameMinimalAxioms : Frame.MinimalAxioms (Opens α) where inf_sSup_le_iSup_inf a s := (ext <| by simp only [coe_inf, coe_iSup, coe_sSup, Set.inter_iUnion₂]).le instance instFrame : Frame (Opens α) := .ofMinimalAxioms frameMinimalAxioms theorem isOpenEmbedding' (U : Opens α) : IsOpenEmbedding (Subtype.val : U → α) := U.isOpen.isOpenEmbedding_subtypeVal theorem isOpenEmbedding_of_le {U V : Opens α} (i : U ≤ V) : IsOpenEmbedding (Set.inclusion <| SetLike.coe_subset_coe.2 i) where toIsEmbedding := .inclusion i isOpen_range := by rw [Set.range_inclusion i] exact U.isOpen.preimage continuous_subtype_val theorem not_nonempty_iff_eq_bot (U : Opens α) : ¬Set.Nonempty (U : Set α) ↔ U = ⊥ := by rw [← coe_inj, coe_bot, ← Set.not_nonempty_iff_eq_empty] theorem ne_bot_iff_nonempty (U : Opens α) : U ≠ ⊥ ↔ Set.Nonempty (U : Set α) := by rw [Ne, ← not_nonempty_iff_eq_bot, not_not] /-- An open set in the indiscrete topology is either empty or the whole space. -/ theorem eq_bot_or_top {α} [t : TopologicalSpace α] (h : t = ⊤) (U : Opens α) : U = ⊥ ∨ U = ⊤ := by subst h; letI : TopologicalSpace α := ⊤ rw [← coe_eq_empty, ← coe_eq_univ, ← isOpen_top_iff] exact U.2 instance [Nonempty α] [Subsingleton α] : IsSimpleOrder (Opens α) where eq_bot_or_eq_top := eq_bot_or_top <| Subsingleton.elim _ _ /-- A set of `opens α` is a basis if the set of corresponding sets is a topological basis. -/ def IsBasis (B : Set (Opens α)) : Prop := IsTopologicalBasis (((↑) : _ → Set α) '' B) theorem isBasis_iff_nbhd {B : Set (Opens α)} : IsBasis B ↔ ∀ {U : Opens α} {x}, x ∈ U → ∃ U' ∈ B, x ∈ U' ∧ U' ≤ U := by constructor <;> intro h · rintro ⟨sU, hU⟩ x hx rcases h.mem_nhds_iff.mp (IsOpen.mem_nhds hU hx) with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩ refine ⟨V, H₁, ?_⟩ cases V dsimp at H₂ subst H₂ exact hsV · refine isTopologicalBasis_of_isOpen_of_nhds ?_ ?_ · rintro sU ⟨U, -, rfl⟩ exact U.2 · intro x sU hx hsU rcases @h ⟨sU, hsU⟩ x hx with ⟨V, hV, H⟩ exact ⟨V, ⟨V, hV, rfl⟩, H⟩ theorem isBasis_iff_cover {B : Set (Opens α)} : IsBasis B ↔ ∀ U : Opens α, ∃ Us, Us ⊆ B ∧ U = sSup Us := by constructor · intro hB U refine ⟨{ V : Opens α | V ∈ B ∧ V ≤ U }, fun U hU => hU.left, ext ?_⟩ rw [coe_sSup, hB.open_eq_sUnion' U.isOpen] simp_rw [sUnion_eq_biUnion, iUnion, mem_setOf_eq, iSup_and, iSup_image] rfl · intro h rw [isBasis_iff_nbhd] intro U x hx rcases h U with ⟨Us, hUs, rfl⟩ rcases mem_sSup.1 hx with ⟨U, Us, xU⟩ exact ⟨U, hUs Us, xU, le_sSup Us⟩ /-- If `α` has a basis consisting of compact opens, then an open set in `α` is compact open iff it is a finite union of some elements in the basis -/ theorem IsBasis.isCompact_open_iff_eq_finite_iUnion {ι : Type*} (b : ι → Opens α) (hb : IsBasis (Set.range b)) (hb' : ∀ i, IsCompact (b i : Set α)) (U : Set α) : IsCompact U ∧ IsOpen U ↔ ∃ s : Set ι, s.Finite ∧ U = ⋃ i ∈ s, b i := by apply isCompact_open_iff_eq_finite_iUnion_of_isTopologicalBasis fun i : ι => (b i).1 · convert (config := {transparency := .default}) hb ext simp · exact hb' lemma IsBasis.exists_finite_of_isCompact {B : Set (Opens α)} (hB : IsBasis B) {U : Opens α} (hU : IsCompact U.1) : ∃ Us ⊆ B, Us.Finite ∧ U = sSup Us := by classical obtain ⟨Us', hsub, hsup⟩ := isBasis_iff_cover.mp hB U obtain ⟨t, ht⟩ := hU.elim_finite_subcover (fun s : Us' ↦ s.1) (fun s ↦ s.1.2) (by simp [hsup]) refine ⟨Finset.image Subtype.val t, subset_trans (by simp) hsub, Finset.finite_toSet _, ?_⟩ exact le_antisymm (subset_trans ht (by simp)) (le_trans (sSup_le_sSup (by simp)) hsup.ge) lemma IsBasis.le_iff {α} {t₁ t₂ : TopologicalSpace α} {Us : Set (Opens α)} (hUs : @IsBasis α t₂ Us) : t₁ ≤ t₂ ↔ ∀ U ∈ Us, IsOpen[t₁] U := by conv_lhs => rw [hUs.eq_generateFrom] simp [Set.subset_def, le_generateFrom_iff_subset_isOpen] lemma isBasis_sigma {ι : Type*} {α : ι → Type*} [∀ i, TopologicalSpace (α i)] {B : ∀ i, Set (Opens (α i))} (hB : ∀ i, IsBasis (B i)) : IsBasis (⋃ i : ι, (fun U ↦ ⟨Sigma.mk i '' U.1, isOpenMap_sigmaMk _ U.2⟩) '' B i) := by convert TopologicalSpace.IsTopologicalBasis.sigma hB simp only [IsBasis, Set.image_iUnion, ← Set.image_comp] simp lemma IsBasis.of_isInducing {B : Set (Opens β)} (H : IsBasis B) {f : α → β} (h : IsInducing f) : IsBasis { ⟨f ⁻¹' U, U.2.preimage h.continuous⟩ | U ∈ B } := by simp only [IsBasis] at H ⊢ convert H.isInducing h ext; simp @[simp] theorem isCompactElement_iff (s : Opens α) : CompleteLattice.IsCompactElement s ↔ IsCompact (s : Set α) := by rw [isCompact_iff_finite_subcover, CompleteLattice.isCompactElement_iff] refine ⟨?_, fun H ι U hU => ?_⟩ · introv H hU hU' obtain ⟨t, ht⟩ := H ι (fun i => ⟨U i, hU i⟩) (by simpa) refine ⟨t, Set.Subset.trans ht ?_⟩ rw [coe_finset_sup, Finset.sup_eq_iSup] rfl · obtain ⟨t, ht⟩ := H (fun i => U i) (fun i => (U i).isOpen) (by simpa using show (s : Set α) ⊆ ↑(iSup U) from hU) refine ⟨t, Set.Subset.trans ht ?_⟩ simp only [Set.iUnion_subset_iff] change ∀ i ∈ t, U i ≤ t.sup U exact fun i => Finset.le_sup /-- The preimage of an open set, as an open set. -/ def comap (f : C(α, β)) : FrameHom (Opens β) (Opens α) where toFun s := ⟨f ⁻¹' s, s.2.preimage f.continuous⟩ map_sSup' s := ext <| by simp only [coe_sSup, preimage_iUnion, biUnion_image, coe_mk] map_inf' _ _ := rfl map_top' := rfl @[simp] theorem comap_id : comap (ContinuousMap.id α) = FrameHom.id _ := FrameHom.ext fun _ => ext rfl theorem comap_mono (f : C(α, β)) {s t : Opens β} (h : s ≤ t) : comap f s ≤ comap f t := OrderHomClass.mono (comap f) h @[simp] theorem coe_comap (f : C(α, β)) (U : Opens β) : ↑(comap f U) = f ⁻¹' U := rfl @[simp] theorem mem_comap {f : C(α, β)} {U : Opens β} {x : α} : x ∈ comap f U ↔ f x ∈ U := .rfl protected theorem comap_comp (g : C(β, γ)) (f : C(α, β)) : comap (g.comp f) = (comap f).comp (comap g) := rfl protected theorem comap_comap (g : C(β, γ)) (f : C(α, β)) (U : Opens γ) : comap f (comap g U) = comap (g.comp f) U := rfl theorem comap_injective [T0Space β] : Injective (comap : C(α, β) → FrameHom (Opens β) (Opens α)) := fun f g h => ContinuousMap.ext fun a => Inseparable.eq <| inseparable_iff_forall_isOpen.2 fun s hs => have : comap f ⟨s, hs⟩ = comap g ⟨s, hs⟩ := DFunLike.congr_fun h ⟨_, hs⟩ show a ∈ f ⁻¹' s ↔ a ∈ g ⁻¹' s from Set.ext_iff.1 (coe_inj.2 this) a /-- A homeomorphism induces an order-preserving equivalence on open sets, by taking comaps. -/ @[simps -fullyApplied apply] def _root_.Homeomorph.opensCongr (f : α ≃ₜ β) : Opens α ≃o Opens β where toFun := Opens.comap (f.symm : C(β, α)) invFun := Opens.comap (f : C(α, β)) left_inv _ := ext <| f.toEquiv.preimage_symm_preimage _ right_inv _ := ext <| f.toEquiv.symm_preimage_preimage _ map_rel_iff' := by simp only [← SetLike.coe_subset_coe]; exact f.symm.surjective.preimage_subset_preimage_iff @[simp] theorem _root_.Homeomorph.opensCongr_symm (f : α ≃ₜ β) : f.opensCongr.symm = f.symm.opensCongr := rfl instance [Finite α] : Finite (Opens α) := Finite.of_injective _ SetLike.coe_injective end Opens /-- The open neighborhoods of a point. See also `Opens` or `nhds`. -/ structure OpenNhdsOf (x : α) extends Opens α where /-- The point `x` belongs to every `U : TopologicalSpace.OpenNhdsOf x`. -/ mem' : x ∈ carrier namespace OpenNhdsOf variable {x : α} theorem toOpens_injective : Injective (toOpens : OpenNhdsOf x → Opens α) | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl instance : SetLike (OpenNhdsOf x) α where coe U := U.1 coe_injective' := SetLike.coe_injective.comp toOpens_injective instance canLiftSet : CanLift (Set α) (OpenNhdsOf x) (↑) fun s => IsOpen s ∧ x ∈ s := ⟨fun s hs => ⟨⟨⟨s, hs.1⟩, hs.2⟩, rfl⟩⟩ protected theorem mem (U : OpenNhdsOf x) : x ∈ U := U.mem' protected theorem isOpen (U : OpenNhdsOf x) : IsOpen (U : Set α) := U.is_open' instance : OrderTop (OpenNhdsOf x) where top := ⟨⊤, Set.mem_univ _⟩ le_top _ := subset_univ _ instance : Inhabited (OpenNhdsOf x) := ⟨⊤⟩ instance : Min (OpenNhdsOf x) := ⟨fun U V => ⟨U.1 ⊓ V.1, U.2, V.2⟩⟩ instance : Max (OpenNhdsOf x) := ⟨fun U V => ⟨U.1 ⊔ V.1, Or.inl U.2⟩⟩ instance [Subsingleton α] : Unique (OpenNhdsOf x) where uniq U := SetLike.ext' <| Subsingleton.eq_univ_of_nonempty ⟨x, U.mem⟩ instance : DistribLattice (OpenNhdsOf x) := toOpens_injective.distribLattice _ (fun _ _ => rfl) fun _ _ => rfl theorem basis_nhds : (𝓝 x).HasBasis (fun _ : OpenNhdsOf x => True) (↑) := (nhds_basis_opens x).to_hasBasis (fun U hU => ⟨⟨⟨U, hU.2⟩, hU.1⟩, trivial, Subset.rfl⟩) fun U _ => ⟨U, ⟨⟨U.mem, U.isOpen⟩, Subset.rfl⟩⟩ /-- Preimage of an open neighborhood of `f x` under a continuous map `f` as a `LatticeHom`. -/ def comap (f : C(α, β)) (x : α) : LatticeHom (OpenNhdsOf (f x)) (OpenNhdsOf x) where toFun U := ⟨Opens.comap f U.1, U.mem⟩ map_sup' _ _ := rfl map_inf' _ _ := rfl end OpenNhdsOf end TopologicalSpace -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11215): TODO: once we port `auto_cases`, port this -- namespace Tactic -- namespace AutoCases -- /-- Find an `auto_cases_tac` which matches `TopologicalSpace.Opens`. -/ -- unsafe def opens_find_tac : expr → Option auto_cases_tac -- | q(TopologicalSpace.Opens _) => tac_cases -- | _ => none -- end AutoCases -- /-- A version of `tactic.auto_cases` that works for `TopologicalSpace.Opens`. -/ -- @[hint_tactic] -- unsafe def auto_cases_opens : tactic String := -- auto_cases tactic.auto_cases.opens_find_tac -- end Tactic
Hom.lean
/- Copyright (c) 2024 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import Mathlib.Analysis.CStarAlgebra.ContinuousFunctionalCalculus.Order /-! # Properties of C⋆-algebra homomorphisms Here we collect properties of C⋆-algebra homomorphisms. ## Main declarations + `NonUnitalStarAlgHom.norm_map`: A non-unital star algebra monomorphism of complex C⋆-algebras is isometric. -/ open CStarAlgebra in lemma IsSelfAdjoint.map_spectrum_real {F A B : Type*} [CStarAlgebra A] [CStarAlgebra B] [FunLike F A B] [AlgHomClass F ℂ A B] [StarHomClass F A B] {a : A} (ha : IsSelfAdjoint a) (φ : F) (hφ : Function.Injective φ) : spectrum ℝ (φ a) = spectrum ℝ a := by have h_spec := AlgHom.spectrum_apply_subset ((φ : A →⋆ₐ[ℂ] B).restrictScalars ℝ) a refine Set.eq_of_subset_of_subset h_spec fun x hx ↦ ?_ /- we prove the reverse inclusion by contradiction, so assume that `x ∈ spectrum ℝ a`, but `x ∉ spectrum ℝ (φ a)`. Then by Urysohn's lemma we can get a function for which `f x = 1`, but `f = 0` on `spectrum ℝ a`. -/ by_contra hx' obtain ⟨f, h_eqOn, h_eqOn_x, -⟩ := exists_continuous_zero_one_of_isClosed (spectrum.isClosed (𝕜 := ℝ) (φ a)) (isClosed_singleton (x := x)) <| by simpa /- it suffices to show that `φ (f a) = 0`, for if so, then `f a = 0` by injectivity of `φ`, and hence `f = 0` on `spectrum ℝ a`, contradicting the fact that `f x = 1`. -/ suffices φ (cfc f a) = 0 by rw [map_eq_zero_iff φ hφ, ← cfc_zero ℝ a, cfc_eq_cfc_iff_eqOn] at this exact zero_ne_one <| calc 0 = f x := (this hx).symm _ = 1 := h_eqOn_x <| Set.mem_singleton x /- Finally, `φ (f a) = f (φ a) = 0`, where the last equality follows since `f = 0` on `spectrum ℝ (φ a)`. -/ calc φ (cfc f a) = cfc f (φ a) := StarAlgHomClass.map_cfc φ f a _ = cfc (0 : ℝ → ℝ) (φ a) := cfc_congr h_eqOn _ = 0 := by simp namespace NonUnitalStarAlgHom variable {F A B : Type*} [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] variable [FunLike F A B] [NonUnitalAlgHomClass F ℂ A B] [StarHomClass F A B] open CStarAlgebra Unitization in /-- A non-unital star algebra monomorphism of complex C⋆-algebras is isometric. -/ lemma norm_map (φ : F) (hφ : Function.Injective φ) (a : A) : ‖φ a‖ = ‖a‖ := by /- Since passing to the unitization is functorial, and it is an isometric embedding, we may assume that `φ` is a unital star algebra monomorphism and that `A` and `B` are unital C⋆-algebras. -/ suffices ∀ {ψ : Unitization ℂ A →⋆ₐ[ℂ] Unitization ℂ B} (_ : Function.Injective ψ) (a : Unitization ℂ A), ‖ψ a‖ = ‖a‖ by simpa [norm_inr] using this (starMap_injective (φ := (φ : A →⋆ₙₐ[ℂ] B)) hφ) a intro ψ hψ a -- to show `‖ψ a‖ = ‖a‖`, by the C⋆-property it suffices to show `‖ψ (star a * a)‖ = ‖star a * a‖` rw [← sq_eq_sq₀ (by positivity) (by positivity)] simp only [sq, ← CStarRing.norm_star_mul_self, ← map_star, ← map_mul] /- since `star a * a` is selfadjoint, it has the same `ℝ`-spectrum as `ψ (star a * a)`. Since the spectral radius over `ℝ` coincides with the norm, `‖ψ (star a * a)‖ = ‖star a * a‖`. -/ have ha : IsSelfAdjoint (star a * a) := .star_mul_self a calc ‖ψ (star a * a)‖ = (spectralRadius ℝ (ψ (star a * a))).toReal := ha.map ψ |>.toReal_spectralRadius_eq_norm.symm _ = (spectralRadius ℝ (star a * a)).toReal := by simp only [spectralRadius, ha.map_spectrum_real ψ hψ] _ = ‖star a * a‖ := ha.toReal_spectralRadius_eq_norm /-- A non-unital star algebra monomorphism of complex C⋆-algebras is isometric. -/ lemma nnnorm_map (φ : F) (hφ : Function.Injective φ) (a : A) : ‖φ a‖₊ = ‖a‖₊ := Subtype.ext <| norm_map φ hφ a lemma isometry (φ : F) (hφ : Function.Injective φ) : Isometry φ := AddMonoidHomClass.isometry_of_norm φ (norm_map φ hφ) end NonUnitalStarAlgHom
RBMap.lean
/- Copyright (c) 2019 mathlib community. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Wojciech Nawrocki -/ import Batteries.Data.RBMap.Basic import Mathlib.Data.Tree.Basic /-! # Binary tree and RBMaps In this file we define `Tree.ofRBNode`. This definition was moved from the main file to avoid a dependency on `RBMap`. ## TODO Implement a `Traversable` instance for `Tree`. ## References <https://leanprover-community.github.io/archive/stream/113488-general/topic/tactic.20question.html> -/ namespace Tree universe u variable {α : Type u} open Batteries (RBNode) /-- Makes a `Tree α` out of a red-black tree. -/ @[deprecated "Deprecated without replacement." (since := "2025-04-02")] def ofRBNode : RBNode α → Tree α | RBNode.nil => nil | RBNode.node _color l key r => node key (ofRBNode l) (ofRBNode r) end Tree
ReplaceRec.lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Kim Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn, Edward Ayers -/ import Lean.Expr import Mathlib.Util.MemoFix /-! # ReplaceRec We define a more flexible version of `Expr.replace` where we can use recursive calls even when replacing a subexpression. We completely mimic the implementation of `Expr.replace`. -/ namespace Lean.Expr /-- A version of `Expr.replace` where the replacement function is available to the function `f?`. `replaceRec f? e` will call `f? r e` where `r = replaceRec f?`. If `f? r e = none` then `r` will be called on each immediate subexpression of `e` and reassembled. If it is `some x`, traversal terminates and `x` is returned. If you wish to recursively replace things in the implementation of `f?`, you can apply `r`. The function is also memoised, which means that if the same expression (by reference) is encountered the cached replacement is used. -/ def replaceRec (f? : (Expr → Expr) → Expr → Option Expr) : Expr → Expr := memoFix fun r e ↦ match f? r e with | some x => x | none => Id.run <| traverseChildren (pure <| r ·) e end Lean.Expr
Defs.lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Matthew Robert Ballard -/ import Mathlib.RingTheory.Multiplicity import Mathlib.Data.Nat.Factors /-! # `p`-adic Valuation This file defines the `p`-adic valuation on `ℕ`, `ℤ`, and `ℚ`. The `p`-adic valuation on `ℚ` is the difference of the multiplicities of `p` in the numerator and denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate assumptions on `p`. The `p`-adic valuations on `ℕ` and `ℤ` agree with that on `ℚ`. The valuation induces a norm on `ℚ`. This norm is defined in padicNorm.lean. -/ assert_not_exists Field universe u open Nat variable {p : ℕ} /-- For `p ≠ 1`, the `p`-adic valuation of a natural `n ≠ 0` is the largest natural number `k` such that `p^k` divides `n`. If `n = 0` or `p = 1`, then `padicValNat p q` defaults to `0`. -/ def padicValNat (p : ℕ) (n : ℕ) : ℕ := if h : p ≠ 1 ∧ 0 < n then Nat.find (finiteMultiplicity_iff.2 h) else 0 theorem padicValNat_def' {n : ℕ} (hp : p ≠ 1) (hn : n ≠ 0) : padicValNat p n = multiplicity p n := by simp only [padicValNat, ne_eq, hp, not_false_eq_true, Nat.pos_iff_ne_zero.mpr hn, and_self, ↓reduceDIte, multiplicity, emultiplicity, finiteMultiplicity_iff.mpr ⟨hp, Nat.pos_iff_ne_zero.mpr hn⟩] convert (WithTop.untopD_coe ..).symm /-- A simplification of `padicValNat` when one input is prime, by analogy with `padicValRat_def`. -/ theorem padicValNat_def [hp : Fact p.Prime] {n : ℕ} (hn : n ≠ 0) : padicValNat p n = multiplicity p n := padicValNat_def' hp.out.ne_one hn /-- A simplification of `padicValNat` when one input is prime, by analogy with `padicValRat_def`. -/ theorem padicValNat_eq_emultiplicity [hp : Fact p.Prime] {n : ℕ} (hn : n ≠ 0) : padicValNat p n = emultiplicity p n := by rw [(finiteMultiplicity_iff.2 ⟨hp.out.ne_one, Nat.pos_iff_ne_zero.mpr hn⟩).emultiplicity_eq_multiplicity] exact_mod_cast padicValNat_def hn namespace padicValNat open List /-- `padicValNat p 0` is `0` for any `p`. -/ @[simp] protected theorem zero : padicValNat p 0 = 0 := by simp [padicValNat] /-- `padicValNat p 1` is `0` for any `p`. -/ @[simp] protected theorem one : padicValNat p 1 = 0 := by simp [padicValNat] @[simp] theorem eq_zero_iff {n : ℕ} : padicValNat p n = 0 ↔ p = 1 ∨ n = 0 ∨ ¬p ∣ n := by simp only [padicValNat, ne_eq, pos_iff_ne_zero, dite_eq_right_iff, find_eq_zero, zero_add, pow_one, and_imp, ← or_iff_not_imp_left] end padicValNat open List theorem le_emultiplicity_iff_replicate_subperm_primeFactorsList {a b : ℕ} {n : ℕ} (ha : a.Prime) (hb : b ≠ 0) : ↑n ≤ emultiplicity a b ↔ replicate n a <+~ b.primeFactorsList := (replicate_subperm_primeFactorsList_iff ha hb).trans pow_dvd_iff_le_emultiplicity |>.symm theorem le_padicValNat_iff_replicate_subperm_primeFactorsList {a b : ℕ} {n : ℕ} (ha : a.Prime) (hb : b ≠ 0) : n ≤ padicValNat a b ↔ replicate n a <+~ b.primeFactorsList := by rw [← le_emultiplicity_iff_replicate_subperm_primeFactorsList ha hb, Nat.finiteMultiplicity_iff.2 ⟨ha.ne_one, Nat.pos_of_ne_zero hb⟩ |>.emultiplicity_eq_multiplicity, ← padicValNat_def' ha.ne_one hb, Nat.cast_le]
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.CompTypeclasses import Mathlib.Algebra.Group.Hom.Defs /-! # Propositional typeclasses on several monoid homs This file contains typeclasses 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. However, we do not expect that all maps should be guessed automatically, as it happens for linear maps. If `φ`, `ψ`… are monoid homs and `M`, `N`… are monoids, we add two instances: * `MonoidHom.CompTriple φ ψ χ`, which expresses that `ψ.comp φ = χ` * `MonoidHom.IsId φ`, which expresses that `φ = id` Some basic lemmas are proved: * `MonoidHom.CompTriple.comp` asserts `MonoidHom.CompTriple φ ψ (ψ.comp φ)` * `MonoidHom.CompTriple.id_comp` asserts `MonoidHom.CompTriple φ ψ ψ` in the presence of `MonoidHom.IsId φ` * its variant `MonoidHom.CompTriple.comp_id` TODO : * align with RingHomCompTriple * probably rename MonoidHom.CompTriple as MonoidHomCompTriple (or, on the opposite, rename RingHomCompTriple as RingHom.CompTriple) * does one need AddHom.CompTriple ? -/ section MonoidHomCompTriple namespace MonoidHom /-- Class of composing triples -/ class CompTriple {M N P : Type*} [Monoid M] [Monoid N] [Monoid P] (φ : 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 variable {M N P : Type*} [Monoid M] [Monoid N] [Monoid P] /-- Class of Id maps -/ class IsId (σ : M →* M) : Prop where eq_id : σ = MonoidHom.id M instance instIsId {M : Type*} [Monoid M] : IsId (MonoidHom.id M) where eq_id := rfl instance {σ : M →* M} [h : _root_.CompTriple.IsId σ] : IsId σ where eq_id := by ext; exact congr_fun h.eq_id _ instance instComp_id {N P : Type*} [Monoid N] [Monoid P] {φ : N →* N} [IsId φ] {ψ : N →* P} : CompTriple φ ψ ψ where comp_eq := by simp only [IsId.eq_id, MonoidHom.comp_id] instance instId_comp {M N : Type*} [Monoid M] [Monoid N] {φ : M →* N} {ψ : N →* N} [IsId ψ] : CompTriple φ ψ φ where comp_eq := by simp only [IsId.eq_id, MonoidHom.id_comp] lemma comp_inv {φ : M →* N} {ψ : N →* M} (h : Function.RightInverse φ ψ) {χ : M →* M} [IsId χ] : CompTriple φ ψ χ where comp_eq := by simp only [IsId.eq_id, ← DFunLike.coe_fn_eq, coe_comp, h.id, coe_id] instance instRootCompTriple {φ : M →* N} {ψ : N →* P} {χ : M →* P} [κ : CompTriple φ ψ χ] : _root_.CompTriple φ ψ χ where comp_eq := by rw [← MonoidHom.coe_comp, κ.comp_eq] /-- `φ`, `ψ` and `ψ.comp φ` form a `MonoidHom.CompTriple` (to be used with care, because no simplification is done) -/ theorem comp {φ : M →* N} {ψ : N →* P} : CompTriple φ ψ (ψ.comp φ) where comp_eq := rfl lemma comp_apply {φ : M →* N} {ψ : N →* P} {χ : M →* P} (h : CompTriple φ ψ χ) (x : M) : ψ (φ x) = χ x := by rw [← h.comp_eq, MonoidHom.comp_apply] theorem comp_assoc {Q : Type*} [Monoid Q] {φ₁ : M →* N} {φ₂ : N →* P} {φ₁₂ : M →* P} (κ : CompTriple φ₁ φ₂ φ₁₂) {φ₃ : P →* Q} {φ₂₃ : N →* Q} (κ' : CompTriple φ₂ φ₃ φ₂₃) {φ₁₂₃ : M →* Q} : CompTriple φ₁ φ₂₃ φ₁₂₃ ↔ CompTriple φ₁₂ φ₃ φ₁₂₃ := by constructor <;> · rintro ⟨h⟩ exact ⟨by simp only [← κ.comp_eq, ← h, ← κ'.comp_eq, MonoidHom.comp_assoc]⟩ end MonoidHom.CompTriple end MonoidHomCompTriple
Divisibility.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland, Aaron Anderson -/ import Mathlib.Algebra.GroupWithZero.Units.Basic import Mathlib.Algebra.Divisibility.Units import Mathlib.Data.Nat.Basic /-! # Divisibility in groups with zero. Lemmas about divisibility in groups and monoids with zero. -/ assert_not_exists DenselyOrdered Ring variable {α : Type*} section SemigroupWithZero variable [SemigroupWithZero α] {a : α} theorem eq_zero_of_zero_dvd (h : 0 ∣ a) : a = 0 := Dvd.elim h fun c H' => H'.trans (zero_mul c) /-- Given an element `a` of a commutative semigroup with zero, there exists another element whose product with zero equals `a` iff `a` equals zero. -/ @[simp] theorem zero_dvd_iff : 0 ∣ a ↔ a = 0 := ⟨eq_zero_of_zero_dvd, fun h => by rw [h] exact ⟨0, by simp⟩⟩ @[simp] theorem dvd_zero (a : α) : a ∣ 0 := Dvd.intro 0 (by simp) end SemigroupWithZero /-- Given two elements `b`, `c` of a `CancelMonoidWithZero` and a nonzero element `a`, `a*b` divides `a*c` iff `b` divides `c`. -/ theorem mul_dvd_mul_iff_left [CancelMonoidWithZero α] {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr fun d => by rw [mul_assoc, mul_right_inj' ha] /-- Given two elements `a`, `b` of a commutative `CancelMonoidWithZero` and a nonzero element `c`, `a*c` divides `b*c` iff `a` divides `b`. -/ theorem mul_dvd_mul_iff_right [CancelCommMonoidWithZero α] {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr fun d => by rw [mul_right_comm, mul_left_inj' hc] section CommMonoidWithZero variable [CommMonoidWithZero α] /-- `DvdNotUnit a b` expresses that `a` divides `b` "strictly", i.e. that `b` divided by `a` is not a unit. -/ def DvdNotUnit (a b : α) : Prop := a ≠ 0 ∧ ∃ x, ¬IsUnit x ∧ b = a * x theorem dvdNotUnit_of_dvd_of_not_dvd {a b : α} (hd : a ∣ b) (hnd : ¬b ∣ a) : DvdNotUnit a b := by constructor · rintro rfl exact hnd (dvd_zero _) · rcases hd with ⟨c, rfl⟩ refine ⟨c, ?_, rfl⟩ rintro ⟨u, rfl⟩ simp at hnd variable {x y : α} theorem isRelPrime_zero_left : IsRelPrime 0 x ↔ IsUnit x := ⟨(· (dvd_zero _) dvd_rfl), IsUnit.isRelPrime_right⟩ theorem isRelPrime_zero_right : IsRelPrime x 0 ↔ IsUnit x := isRelPrime_comm.trans isRelPrime_zero_left theorem not_isRelPrime_zero_zero [Nontrivial α] : ¬IsRelPrime (0 : α) 0 := mt isRelPrime_zero_right.mp not_isUnit_zero theorem IsRelPrime.ne_zero_or_ne_zero [Nontrivial α] (h : IsRelPrime x y) : x ≠ 0 ∨ y ≠ 0 := not_or_of_imp <| by rintro rfl rfl; exact not_isRelPrime_zero_zero h end CommMonoidWithZero theorem isRelPrime_of_no_nonunits_factors [MonoidWithZero α] {x y : α} (nonzero : ¬(x = 0 ∧ y = 0)) (H : ∀ z, ¬ IsUnit z → z ≠ 0 → z ∣ x → ¬z ∣ y) : IsRelPrime x y := by refine fun z hx hy ↦ by_contra fun h ↦ H z h ?_ hx hy rintro rfl; exact nonzero ⟨zero_dvd_iff.1 hx, zero_dvd_iff.1 hy⟩ theorem dvd_and_not_dvd_iff [CancelCommMonoidWithZero α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ DvdNotUnit x y := ⟨fun ⟨⟨d, hd⟩, hyx⟩ => ⟨fun hx0 => by simp [hx0] at hyx, ⟨d, mt isUnit_iff_dvd_one.1 fun ⟨e, he⟩ => hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩, hd⟩⟩, fun ⟨hx0, d, hdu, hdx⟩ => ⟨⟨d, hdx⟩, fun ⟨e, he⟩ => hdu (isUnit_of_dvd_one ⟨e, mul_left_cancel₀ hx0 <| by conv => lhs rw [he, hdx] simp [mul_assoc]⟩)⟩⟩ section MonoidWithZero variable [MonoidWithZero α] theorem ne_zero_of_dvd_ne_zero {p q : α} (h₁ : q ≠ 0) (h₂ : p ∣ q) : p ≠ 0 := by rcases h₂ with ⟨u, rfl⟩ exact left_ne_zero_of_mul h₁ theorem isPrimal_zero : IsPrimal (0 : α) := fun a b h ↦ ⟨a, b, dvd_rfl, dvd_rfl, (zero_dvd_iff.mp h).symm⟩ theorem IsPrimal.mul {α} [CancelCommMonoidWithZero α] {m n : α} (hm : IsPrimal m) (hn : IsPrimal n) : IsPrimal (m * n) := by obtain rfl | h0 := eq_or_ne m 0; · rwa [zero_mul] intro b c h obtain ⟨a₁, a₂, ⟨b, rfl⟩, ⟨c, rfl⟩, rfl⟩ := hm (dvd_of_mul_right_dvd h) rw [mul_mul_mul_comm, mul_dvd_mul_iff_left h0] at h obtain ⟨a₁', a₂', h₁, h₂, rfl⟩ := hn h exact ⟨a₁ * a₁', a₂ * a₂', mul_dvd_mul_left _ h₁, mul_dvd_mul_left _ h₂, mul_mul_mul_comm _ _ _ _⟩ end MonoidWithZero section CancelCommMonoidWithZero variable [CancelCommMonoidWithZero α] {a b : α} {m n : ℕ} section Subsingleton variable [Subsingleton αˣ] theorem dvd_antisymm : a ∣ b → b ∣ a → a = b := by rintro ⟨c, rfl⟩ ⟨d, hcd⟩ rw [mul_assoc, eq_comm, mul_right_eq_self₀, mul_eq_one] at hcd obtain ⟨rfl, -⟩ | rfl := hcd <;> simp theorem dvd_antisymm' : a ∣ b → b ∣ a → b = a := flip dvd_antisymm alias Dvd.dvd.antisymm := dvd_antisymm alias Dvd.dvd.antisymm' := dvd_antisymm' theorem eq_of_forall_dvd (h : ∀ c, a ∣ c ↔ b ∣ c) : a = b := ((h _).2 dvd_rfl).antisymm <| (h _).1 dvd_rfl theorem eq_of_forall_dvd' (h : ∀ c, c ∣ a ↔ c ∣ b) : a = b := ((h _).1 dvd_rfl).antisymm <| (h _).2 dvd_rfl end Subsingleton lemma pow_dvd_pow_iff (ha₀ : a ≠ 0) (ha : ¬IsUnit a) : a ^ n ∣ a ^ m ↔ n ≤ m := by constructor · intro h rw [← not_lt] intro hmn apply ha have : a ^ m * a ∣ a ^ m * 1 := by rw [← pow_succ, mul_one] exact (pow_dvd_pow _ (Nat.succ_le_of_lt hmn)).trans h rwa [mul_dvd_mul_iff_left, ← isUnit_iff_dvd_one] at this apply pow_ne_zero m ha₀ · apply pow_dvd_pow end CancelCommMonoidWithZero section GroupWithZero variable [GroupWithZero α] /-- `∣` is not a useful definition if an inverse is available. -/ @[simp] lemma GroupWithZero.dvd_iff {m n : α} : m ∣ n ↔ (m = 0 → n = 0) := by refine ⟨fun ⟨a, ha⟩ hm => ?_, fun h => ?_⟩ · simp [hm, ha] · refine ⟨m⁻¹ * n, ?_⟩ obtain rfl | hn := eq_or_ne n 0 · simp · rw [mul_inv_cancel_left₀ (mt h hn)] end GroupWithZero
Bifunctor.lean
/- Copyright (c) 2017 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Kim Morrison -/ import Mathlib.CategoryTheory.Products.Basic /-! # Lemmas about functors out of product categories. -/ open CategoryTheory namespace CategoryTheory.Bifunctor universe v₁ v₂ v₃ u₁ u₂ u₃ variable {C : Type u₁} {D : Type u₂} {E : Type u₃} variable [Category.{v₁} C] [Category.{v₂} D] [Category.{v₃} E] open scoped Prod @[simp] theorem map_id (F : C × D ⥤ E) (X : C) (Y : D) : F.map ((𝟙 X) ×ₘ (𝟙 Y)) = 𝟙 (F.obj (X, Y)) := F.map_id (X, Y) @[simp] theorem map_id_comp (F : C × D ⥤ E) (W : C) {X Y Z : D} (f : X ⟶ Y) (g : Y ⟶ Z) : F.map (𝟙 W ×ₘ (f ≫ g)) = F.map (𝟙 W ×ₘ f) ≫ F.map (𝟙 W ×ₘ g) := by rw [← Functor.map_comp, prod_comp, Category.comp_id] @[simp] theorem map_comp_id (F : C × D ⥤ E) (X Y Z : C) (W : D) (f : X ⟶ Y) (g : Y ⟶ Z) : F.map ((f ≫ g) ×ₘ 𝟙 W) = F.map (f ×ₘ 𝟙 W) ≫ F.map (g ×ₘ 𝟙 W) := by rw [← Functor.map_comp, prod_comp, Category.comp_id] @[simp] theorem diagonal (F : C × D ⥤ E) (X X' : C) (f : X ⟶ X') (Y Y' : D) (g : Y ⟶ Y') : F.map (𝟙 X ×ₘ g) ≫ F.map (f ×ₘ 𝟙 Y') = F.map (f ×ₘ g) := by rw [← Functor.map_comp, prod_comp, Category.id_comp, Category.comp_id] @[simp] theorem diagonal' (F : C × D ⥤ E) (X X' : C) (f : X ⟶ X') (Y Y' : D) (g : Y ⟶ Y') : F.map (f ×ₘ 𝟙 Y) ≫ F.map (𝟙 X' ×ₘ g) = F.map (f ×ₘ g) := by rw [← Functor.map_comp, prod_comp, Category.id_comp, Category.comp_id] end CategoryTheory.Bifunctor
MeasurablyGenerated.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.MeasureTheory.MeasurableSpace.Constructions import Mathlib.Order.Filter.AtTopBot.CompleteLattice import Mathlib.Order.Filter.AtTopBot.CountablyGenerated import Mathlib.Order.Filter.SmallSets import Mathlib.Order.LiminfLimsup import Mathlib.Tactic.FinCases /-! # Measurably generated filters We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `Filter.Eventually`. -/ open Set Filter universe uι variable {α β γ δ : Type*} {ι : Sort uι} namespace MeasurableSpace /-- The sigma-algebra generated by a single set `s` is `{∅, s, sᶜ, univ}`. -/ @[simp] theorem generateFrom_singleton (s : Set α) : generateFrom {s} = MeasurableSpace.comap (· ∈ s) ⊤ := by classical letI : MeasurableSpace α := generateFrom {s} refine le_antisymm (generateFrom_le fun t ht => ⟨{True}, trivial, by simp [ht.symm]⟩) ?_ rintro _ ⟨u, -, rfl⟩ exact (show MeasurableSet s from GenerateMeasurable.basic _ <| mem_singleton s).mem trivial lemma generateFrom_singleton_le {m : MeasurableSpace α} {s : Set α} (hs : MeasurableSet s) : MeasurableSpace.generateFrom {s} ≤ m := generateFrom_le (fun _ ht ↦ mem_singleton_iff.1 ht ▸ hs) end MeasurableSpace namespace MeasureTheory theorem measurableSet_generateFrom_singleton_iff {s t : Set α} : MeasurableSet[MeasurableSpace.generateFrom {s}] t ↔ t = ∅ ∨ t = s ∨ t = sᶜ ∨ t = univ := by simp_rw [MeasurableSpace.generateFrom_singleton] unfold MeasurableSet MeasurableSpace.MeasurableSet' MeasurableSpace.comap simp_rw [MeasurableSpace.measurableSet_top, true_and] constructor · rintro ⟨x, rfl⟩ by_cases hT : True ∈ x · by_cases hF : False ∈ x · refine Or.inr <| Or.inr <| Or.inr <| subset_antisymm (subset_univ _) ?_ suffices x = univ by simp only [this, preimage_univ, subset_refl] refine subset_antisymm (subset_univ _) ?_ rw [univ_eq_true_false] rintro - (rfl | rfl) · assumption · assumption · have hx : x = {True} := by ext p refine ⟨fun hp ↦ mem_singleton_iff.2 ?_, fun hp ↦ hp ▸ hT⟩ by_contra hpneg rw [eq_iff_iff, iff_true, ← false_iff] at hpneg exact hF (by convert hp) simp [hx] · by_cases hF : False ∈ x · have hx : x = {False} := by ext p refine ⟨fun hp ↦ mem_singleton_iff.2 ?_, fun hp ↦ hp ▸ hF⟩ grind refine Or.inr <| Or.inr <| Or.inl <| ?_ simp [hx, compl_def] · refine Or.inl <| subset_antisymm ?_ <| empty_subset _ suffices x ⊆ ∅ by rw [subset_empty_iff] at this simp only [this, preimage_empty, subset_refl] intro p hp fin_cases p · contradiction · contradiction · rintro (rfl | rfl | rfl | rfl) on_goal 1 => use ∅ on_goal 2 => use {True} on_goal 3 => use {False} on_goal 4 => use Set.univ all_goals simp [compl_def] end MeasureTheory namespace Filter variable [MeasurableSpace α] /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class IsMeasurablyGenerated (f : Filter α) : Prop where exists_measurable_subset : ∀ ⦃s⦄, s ∈ f → ∃ t ∈ f, MeasurableSet t ∧ t ⊆ s instance isMeasurablyGenerated_bot : IsMeasurablyGenerated (⊥ : Filter α) := ⟨fun _ _ => ⟨∅, mem_bot, MeasurableSet.empty, empty_subset _⟩⟩ instance isMeasurablyGenerated_top : IsMeasurablyGenerated (⊤ : Filter α) := ⟨fun _s hs => ⟨univ, univ_mem, MeasurableSet.univ, fun x _ => hs x⟩⟩ theorem Eventually.exists_measurable_mem {f : Filter α} [IsMeasurablyGenerated f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ s ∈ f, MeasurableSet s ∧ ∀ x ∈ s, p x := IsMeasurablyGenerated.exists_measurable_subset h theorem Eventually.exists_measurable_mem_of_smallSets {f : Filter α} [IsMeasurablyGenerated f] {p : Set α → Prop} (h : ∀ᶠ s in f.smallSets, p s) : ∃ s ∈ f, MeasurableSet s ∧ p s := let ⟨_s, hsf, hs⟩ := eventually_smallSets.1 h let ⟨t, htf, htm, hts⟩ := IsMeasurablyGenerated.exists_measurable_subset hsf ⟨t, htf, htm, hs t hts⟩ instance inf_isMeasurablyGenerated (f g : Filter α) [IsMeasurablyGenerated f] [IsMeasurablyGenerated g] : IsMeasurablyGenerated (f ⊓ g) := by constructor rintro t ⟨sf, hsf, sg, hsg, rfl⟩ rcases IsMeasurablyGenerated.exists_measurable_subset hsf with ⟨s'f, hs'f, hmf, hs'sf⟩ rcases IsMeasurablyGenerated.exists_measurable_subset hsg with ⟨s'g, hs'g, hmg, hs'sg⟩ refine ⟨s'f ∩ s'g, inter_mem_inf hs'f hs'g, hmf.inter hmg, ?_⟩ exact inter_subset_inter hs'sf hs'sg theorem principal_isMeasurablyGenerated_iff {s : Set α} : IsMeasurablyGenerated (𝓟 s) ↔ MeasurableSet s := by refine ⟨?_, fun hs => ⟨fun t ht => ⟨s, mem_principal_self s, hs, ht⟩⟩⟩ rintro ⟨hs⟩ rcases hs (mem_principal_self s) with ⟨t, ht, htm, hts⟩ have : t = s := hts.antisymm ht rwa [← this] alias ⟨_, _root_.MeasurableSet.principal_isMeasurablyGenerated⟩ := principal_isMeasurablyGenerated_iff instance iInf_isMeasurablyGenerated {f : ι → Filter α} [∀ i, IsMeasurablyGenerated (f i)] : IsMeasurablyGenerated (⨅ i, f i) := by refine ⟨fun s hs => ?_⟩ rw [← Equiv.plift.surjective.iInf_comp, mem_iInf] at hs rcases hs with ⟨t, ht, ⟨V, hVf, rfl⟩⟩ choose U hUf hU using fun i => IsMeasurablyGenerated.exists_measurable_subset (hVf i) refine ⟨⋂ i : t, U i, ?_, ?_, ?_⟩ · rw [← Equiv.plift.surjective.iInf_comp, mem_iInf] exact ⟨t, ht, U, hUf, rfl⟩ · haveI := ht.countable.toEncodable.countable exact MeasurableSet.iInter fun i => (hU i).1 · exact iInter_mono fun i => (hU i).2 end Filter /-- The set of points for which a sequence of measurable functions converges to a given value is measurable. -/ @[measurability] lemma measurableSet_tendsto {_ : MeasurableSpace β} [MeasurableSpace γ] [Countable δ] {l : Filter δ} [l.IsCountablyGenerated] (l' : Filter γ) [l'.IsCountablyGenerated] [hl' : l'.IsMeasurablyGenerated] {f : δ → β → γ} (hf : ∀ i, Measurable (f i)) : MeasurableSet { x | Tendsto (fun n ↦ f n x) l l' } := by rcases l.exists_antitone_basis with ⟨u, hu⟩ rcases (Filter.hasBasis_self.mpr hl'.exists_measurable_subset).exists_antitone_subbasis with ⟨v, v_meas, hv⟩ simp only [hu.tendsto_iff hv.toHasBasis, true_imp_iff, true_and, setOf_forall, setOf_exists] exact .iInter fun n ↦ .iUnion fun _ ↦ .biInter (to_countable _) fun i _ ↦ (v_meas n).2.preimage (hf i) namespace MeasurableSet variable [MeasurableSpace α] protected theorem iUnion_of_monotone_of_frequently {ι : Type*} [Preorder ι] [(atTop : Filter ι).IsCountablyGenerated] {s : ι → Set α} (hsm : Monotone s) (hs : ∃ᶠ i in atTop, MeasurableSet (s i)) : MeasurableSet (⋃ i, s i) := by rcases exists_seq_forall_of_frequently hs with ⟨x, hx, hxm⟩ rw [← hsm.iUnion_comp_tendsto_atTop hx] exact .iUnion hxm protected theorem iInter_of_antitone_of_frequently {ι : Type*} [Preorder ι] [(atTop : Filter ι).IsCountablyGenerated] {s : ι → Set α} (hsm : Antitone s) (hs : ∃ᶠ i in atTop, MeasurableSet (s i)) : MeasurableSet (⋂ i, s i) := by rw [← compl_iff, compl_iInter] exact .iUnion_of_monotone_of_frequently (compl_anti.comp hsm) <| hs.mono fun _ ↦ .compl protected theorem iUnion_of_monotone {ι : Type*} [Preorder ι] [IsDirected ι (· ≤ ·)] [(atTop : Filter ι).IsCountablyGenerated] {s : ι → Set α} (hsm : Monotone s) (hs : ∀ i, MeasurableSet (s i)) : MeasurableSet (⋃ i, s i) := by cases isEmpty_or_nonempty ι with | inl _ => simp | inr _ => exact .iUnion_of_monotone_of_frequently hsm <| .of_forall hs protected theorem iInter_of_antitone {ι : Type*} [Preorder ι] [IsDirected ι (· ≤ ·)] [(atTop : Filter ι).IsCountablyGenerated] {s : ι → Set α} (hsm : Antitone s) (hs : ∀ i, MeasurableSet (s i)) : MeasurableSet (⋂ i, s i) := by rw [← compl_iff, compl_iInter] exact .iUnion_of_monotone (compl_anti.comp hsm) fun i ↦ (hs i).compl /-! ### Typeclasses on `Subtype MeasurableSet` -/ instance Subtype.instMembership : Membership α (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun s a => a ∈ (s : Set α)⟩ @[simp] theorem mem_coe (a : α) (s : Subtype (MeasurableSet : Set α → Prop)) : a ∈ (s : Set α) ↔ a ∈ s := Iff.rfl instance Subtype.instEmptyCollection : EmptyCollection (Subtype (MeasurableSet : Set α → Prop)) := ⟨⟨∅, MeasurableSet.empty⟩⟩ @[simp] theorem coe_empty : ↑(∅ : Subtype (MeasurableSet : Set α → Prop)) = (∅ : Set α) := rfl instance Subtype.instInsert [MeasurableSingletonClass α] : Insert α (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun a s => ⟨insert a (s : Set α), s.prop.insert a⟩⟩ @[simp] theorem coe_insert [MeasurableSingletonClass α] (a : α) (s : Subtype (MeasurableSet : Set α → Prop)) : ↑(Insert.insert a s) = (Insert.insert a s : Set α) := rfl instance Subtype.instSingleton [MeasurableSingletonClass α] : Singleton α (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun a => ⟨{a}, .singleton _⟩⟩ @[simp] theorem coe_singleton [MeasurableSingletonClass α] (a : α) : ↑({a} : Subtype (MeasurableSet : Set α → Prop)) = ({a} : Set α) := rfl instance Subtype.instLawfulSingleton [MeasurableSingletonClass α] : LawfulSingleton α (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun _ => Subtype.eq <| insert_empty_eq _⟩ instance Subtype.instHasCompl : HasCompl (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun x => ⟨xᶜ, x.prop.compl⟩⟩ @[simp] theorem coe_compl (s : Subtype (MeasurableSet : Set α → Prop)) : ↑sᶜ = (sᶜ : Set α) := rfl instance Subtype.instUnion : Union (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun x y => ⟨(x : Set α) ∪ y, x.prop.union y.prop⟩⟩ @[simp] theorem coe_union (s t : Subtype (MeasurableSet : Set α → Prop)) : ↑(s ∪ t) = (s ∪ t : Set α) := rfl instance Subtype.instSup : Max (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun x y => x ∪ y⟩ @[simp] protected theorem sup_eq_union (s t : {s : Set α // MeasurableSet s}) : s ⊔ t = s ∪ t := rfl instance Subtype.instInter : Inter (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun x y => ⟨x ∩ y, x.prop.inter y.prop⟩⟩ @[simp] theorem coe_inter (s t : Subtype (MeasurableSet : Set α → Prop)) : ↑(s ∩ t) = (s ∩ t : Set α) := rfl instance Subtype.instInf : Min (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun x y => x ∩ y⟩ @[simp] protected theorem inf_eq_inter (s t : {s : Set α // MeasurableSet s}) : s ⊓ t = s ∩ t := rfl instance Subtype.instSDiff : SDiff (Subtype (MeasurableSet : Set α → Prop)) := ⟨fun x y => ⟨x \ y, x.prop.diff y.prop⟩⟩ -- TODO: Why does it complain that `x ⇨ y` is noncomputable? noncomputable instance Subtype.instHImp : HImp (Subtype (MeasurableSet : Set α → Prop)) where himp x y := ⟨x ⇨ y, x.prop.himp y.prop⟩ @[simp] theorem coe_sdiff (s t : Subtype (MeasurableSet : Set α → Prop)) : ↑(s \ t) = (s : Set α) \ t := rfl @[simp] lemma coe_himp (s t : Subtype (MeasurableSet : Set α → Prop)) : ↑(s ⇨ t) = (s ⇨ t : Set α) := rfl instance Subtype.instBot : Bot (Subtype (MeasurableSet : Set α → Prop)) := ⟨∅⟩ @[simp] theorem coe_bot : ↑(⊥ : Subtype (MeasurableSet : Set α → Prop)) = (⊥ : Set α) := rfl instance Subtype.instTop : Top (Subtype (MeasurableSet : Set α → Prop)) := ⟨⟨Set.univ, MeasurableSet.univ⟩⟩ @[simp] theorem coe_top : ↑(⊤ : Subtype (MeasurableSet : Set α → Prop)) = (⊤ : Set α) := rfl noncomputable instance Subtype.instBooleanAlgebra : BooleanAlgebra (Subtype (MeasurableSet : Set α → Prop)) := Subtype.coe_injective.booleanAlgebra _ coe_union coe_inter coe_top coe_bot coe_compl coe_sdiff coe_himp @[measurability] theorem measurableSet_blimsup {s : ℕ → Set α} {p : ℕ → Prop} (h : ∀ n, p n → MeasurableSet (s n)) : MeasurableSet <| blimsup s atTop p := by simp only [blimsup_eq_iInf_biSup_of_nat, iSup_eq_iUnion, iInf_eq_iInter] exact .iInter fun _ => .iUnion fun m => .iUnion fun hm => h m hm.1 @[measurability] theorem measurableSet_bliminf {s : ℕ → Set α} {p : ℕ → Prop} (h : ∀ n, p n → MeasurableSet (s n)) : MeasurableSet <| Filter.bliminf s Filter.atTop p := by simp only [Filter.bliminf_eq_iSup_biInf_of_nat, iInf_eq_iInter, iSup_eq_iUnion] exact .iUnion fun n => .iInter fun m => .iInter fun hm => h m hm.1 @[measurability] theorem measurableSet_limsup {s : ℕ → Set α} (hs : ∀ n, MeasurableSet <| s n) : MeasurableSet <| Filter.limsup s Filter.atTop := by simpa only [← blimsup_true] using measurableSet_blimsup fun n _ => hs n @[measurability] theorem measurableSet_liminf {s : ℕ → Set α} (hs : ∀ n, MeasurableSet <| s n) : MeasurableSet <| Filter.liminf s Filter.atTop := by simpa only [← bliminf_true] using measurableSet_bliminf fun n _ => hs n end MeasurableSet
gfunctor.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat fintype. From mathcomp Require Import bigop finset fingroup morphism automorphism. From mathcomp Require Import quotient gproduct. (******************************************************************************) (* This file provides basic interfaces for the notion of "generic" *) (* characteristic subgroups; these amount to subfunctors of the identity *) (* functor in some category of groups. *) (* See "Generic Proof Tools And Finite Group Theory", *) (* Francois Garillot, PhD, 2011, Chapter 3. *) (* The implementation proposed here is fairly basic, relying on first order *) (* function matching and on structure telescopes, both of which are somewhat *) (* limited and fragile. It should switch in the future to more general and *) (* more robust quotation matching. *) (* The definitions in this file (types, properties and structures) are all *) (* packaged under the GFunctor submodule, i.e., client code should refer to *) (* GFunctor.continuous, GFunctor.map, etc. Notations, Coercions and Lemmas *) (* are exported and thus directly available, however. *) (* We provide the following: *) (* object_map == the type of the (polymorphic) object map of a group *) (* functor; the %gF scope is bound to object_map. *) (* := forall gT : finGroupType, {set gT} -> {set gT}. *) (* We define two operations on object_map (with notations in the %gF scope): *) (* F1 \o F2 == the composite map; (F1 \o F2) G expands to F1 (F2 G). *) (* F1 %% F2 == F1 computed modulo F2; we have *) (* (F1 %% F2) G / F2 G = F1 (G / F2 G) *) (* We define the following (type-polymorphic) properties of an object_map F: *) (* group_valued F <-> F G is a group when G is a group *) (* closed F <-> F G is a subgroup o fG when G is a group *) (* continuous F <-> F is continuous with respect to morphism image: *) (* for any f : {morphism G >-> ..}, f @* (F G) is a *) (* a subgroup of F (f @* G); equivalently, F is *) (* functorial in the category Grp of groups. *) (* Most common "characteristic subgroup" are produced *) (* continuous object maps. *) (* iso_continuous F <-> F is continuous with respect to isomorphism image; *) (* equivalently, F is functorial in the Grp groupoid. *) (* The Puig and the Thompson J subgroups are examples *) (* of iso_continuous maps that are not continuous. *) (* pcontinuous F <-> F is continuous with respect to partial morphism *) (* image, i.e., functorial in the category of groups *) (* and partial morphisms. The center and p-core are *) (* examples of pcontinuous maps. *) (* hereditary F <-> inclusion in the image of F is hereditary, i.e., *) (* for any subgroup H of G, the intersection of H with *) (* F G is included in H. Note that F is pcontinuous *) (* iff it is continuous and hereditary; indeed proofs *) (* of pcontinuous F coerce to proofs of hereditary F *) (* and continuous F. *) (* monotonic F <-> F is monotonic with respect to inclusion: for any *) (* subgroup H of G, F H is a subgroup of F G. The *) (* derived and lower central series are examples of *) (* monotonic maps. *) (* Four structures provide interfaces to these properties: *) (* GFunctor.iso_map == structure for object maps that are group_valued, *) (* closed, and iso_continuous. *) (* [igFun by Fsub & !Fcont] == the iso_map structure for an object map F *) (* such that F G is canonically a group when G is, and *) (* given Fsub : closed F and Fcont : iso_continuous F. *) (* [igFun by Fsub & Fcont] == as above, but expecting Fcont : continuous F. *) (* [igFun of F] == clone an existing GFunctor.iso_map structure for F. *) (* GFunctor.map == structure for continuous object maps, inheriting *) (* from the GFunctor.iso_map structure. *) (* [gFun by Fcont] == the map structure for an F with a canonical iso_map *) (* structure, given Fcont : continuous F. *) (* [gFun of F] == clone an existing GFunctor.map structure for F. *) (* GFunctor.pmap == structure for pcontinuous object maps, inheriting *) (* from the GFunctor.map structure. *) (* [pgFun by Fher] == the pmap structure for an F with a canonical map *) (* structure, given Fher : hereditary F. *) (* [pgFun of F] == clone an existing GFunctor.pmap structure for F. *) (* GFunctor.mono_map == structure for monotonic, continuous object maps *) (* inheriting from the GFunctor.map structure. *) (* [mgFun by Fmon] == the mono_map structure for an F with a canonical *) (* map structure, given Fmon : monotonic F. *) (* [mgFun of F] == clone an existing GFunctor.mono_map structure for F *) (* Lemmas for these group functors use either a 'gF' prefix or an 'F' suffix. *) (* The (F1 \o F2) and (F1 %% F2) operations have canonical GFunctor.map *) (* structures when F1 is monotonic or hereditary, respectively. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope gFun_scope. Import GroupScope. Delimit Scope gFun_scope with gF. Module GFunctor. Definition object_map := forall gT : finGroupType, {set gT} -> {set gT}. Bind Scope gFun_scope with object_map. Section Definitions. Implicit Types gT hT : finGroupType. Variable F : object_map. (* Group closure. *) Definition group_valued := forall gT (G : {group gT}), group_set (F G). (* Subgroup closure. *) Definition closed := forall gT (G : {group gT}), F G \subset G. (* General functoriality, i.e., continuity of the object map *) Definition continuous := forall gT hT (G : {group gT}) (phi : {morphism G >-> hT}), phi @* F G \subset F (phi @* G). (* Functoriality on the Grp groupoid (arrows are restricted to isos). *) Definition iso_continuous := forall gT hT (G : {group gT}) (phi : {morphism G >-> hT}), 'injm phi -> phi @* F G \subset F (phi @* G). Lemma continuous_is_iso_continuous : continuous -> iso_continuous. Proof. by move=> Fcont gT hT G phi inj_phi; apply: Fcont. Qed. (* Functoriality on Grp with partial morphisms. *) Definition pcontinuous := forall gT hT (G D : {group gT}) (phi : {morphism D >-> hT}), phi @* F G \subset F (phi @* G). Lemma pcontinuous_is_continuous : pcontinuous -> continuous. Proof. by move=> Fcont gT hT G; apply: Fcont. Qed. (* Heredity with respect to inclusion *) Definition hereditary := forall gT (H G : {group gT}), H \subset G -> F G :&: H \subset F H. Lemma pcontinuous_is_hereditary : pcontinuous -> hereditary. Proof. move=> Fcont gT H G sHG; rewrite -{2}(setIidPl sHG) setIC. by do 2!rewrite -(morphim_idm (subsetIl H _)) morphimIdom ?Fcont. Qed. (* Monotonicity with respect to inclusion *) Definition monotonic := forall gT (H G : {group gT}), H \subset G -> F H \subset F G. (* Self-expanding composition, and modulo *) Variables (F1 F2 : object_map). Definition comp : object_map := fun gT A => F1 (F2 A). Definition modulo : object_map := fun gT A => coset (F2 A) @*^-1 (F1 (A / (F2 A))). End Definitions. Section ClassDefinitions. Structure iso_map := IsoMap { apply : object_map; _ : group_valued apply; _ : closed apply; _ : iso_continuous apply }. Local Coercion apply : iso_map >-> object_map. Structure map := Map { iso_of_map : iso_map; _ : continuous iso_of_map }. Local Coercion iso_of_map : map >-> iso_map. Structure pmap := Pmap { map_of_pmap : map; _ : hereditary map_of_pmap }. Local Coercion map_of_pmap : pmap >-> map. Structure mono_map := MonoMap { map_of_mono : map; _ : monotonic map_of_mono }. Local Coercion map_of_mono : mono_map >-> map. Definition pack_iso F Fcont Fgrp Fsub := @IsoMap F Fgrp Fsub Fcont. Definition clone_iso (F : object_map) := fun Fgrp Fsub Fcont (isoF := @IsoMap F Fgrp Fsub Fcont) => fun isoF0 & phant_id (apply isoF0) F & phant_id isoF isoF0 => isoF. Definition clone (F : object_map) := fun isoF & phant_id (apply isoF) F => fun (funF0 : map) & phant_id (apply funF0) F => fun Fcont (funF := @Map isoF Fcont) & phant_id funF0 funF => funF. Definition clone_pmap (F : object_map) := fun (funF : map) & phant_id (apply funF) F => fun (pfunF0 : pmap) & phant_id (apply pfunF0) F => fun Fher (pfunF := @Pmap funF Fher) & phant_id pfunF0 pfunF => pfunF. Definition clone_mono (F : object_map) := fun (funF : map) & phant_id (apply funF) F => fun (mfunF0 : mono_map) & phant_id (apply mfunF0) F => fun Fmon (mfunF := @MonoMap funF Fmon) & phant_id mfunF0 mfunF => mfunF. End ClassDefinitions. Module Exports. Identity Coercion fun_of_object_map : object_map >-> Funclass. Coercion apply : iso_map >-> object_map. Coercion iso_of_map : map >-> iso_map. Coercion map_of_pmap : pmap >-> map. Coercion map_of_mono : mono_map >-> map. Coercion continuous_is_iso_continuous : continuous >-> iso_continuous. Coercion pcontinuous_is_continuous : pcontinuous >-> continuous. Coercion pcontinuous_is_hereditary : pcontinuous >-> hereditary. Notation "[ 'igFun' 'by' Fsub & Fcont ]" := (pack_iso (continuous_is_iso_continuous Fcont) (fun gT G => groupP _) Fsub) (format "[ 'igFun' 'by' Fsub & Fcont ]") : form_scope. Notation "[ 'igFun' 'by' Fsub & ! Fcont ]" := (pack_iso Fcont (fun gT G => groupP _) Fsub) (format "[ 'igFun' 'by' Fsub & ! Fcont ]") : form_scope. Notation "[ 'igFun' 'of' F ]" := (@clone_iso F _ _ _ _ id id) (format "[ 'igFun' 'of' F ]") : form_scope. Notation "[ 'gFun' 'by' Fcont ]" := (Map Fcont) (format "[ 'gFun' 'by' Fcont ]") : form_scope. Notation "[ 'gFun' 'of' F ]" := (@clone F _ id _ id _ id) (format "[ 'gFun' 'of' F ]") : form_scope. Notation "[ 'pgFun' 'by' Fher ]" := (Pmap Fher) (format "[ 'pgFun' 'by' Fher ]") : form_scope. Notation "[ 'pgFun' 'of' F ]" := (@clone_pmap F _ id _ id _ id) (format "[ 'pgFun' 'of' F ]") : form_scope. Notation "[ 'mgFun' 'by' Fmon ]" := (MonoMap Fmon) (format "[ 'mgFun' 'by' Fmon ]") : form_scope. Notation "[ 'mgFun' 'of' F ]" := (@clone_mono F _ id _ id _ id) (format "[ 'mgFun' 'of' F ]") : form_scope. End Exports. End GFunctor. Export GFunctor.Exports. Bind Scope gFun_scope with GFunctor.object_map. Arguments GFunctor.comp F1 F2 _ /. Notation "F1 \o F2" := (GFunctor.comp F1 F2) : gFun_scope. Notation "F1 %% F2" := (GFunctor.modulo F1 F2) : gFun_scope. Section FunctorGroup. Variables (F : GFunctor.iso_map) (gT : finGroupType) (G : {group gT}). Lemma gFgroupset : group_set (F gT G). Proof. by case: F. Qed. Canonical gFgroup := Group gFgroupset. End FunctorGroup. Canonical gFmod_group (F1 : GFunctor.iso_map) (F2 : GFunctor.object_map) (gT : finGroupType) (G : {group gT}) := [group of (F1 %% F2)%gF gT G]. Section IsoFunctorTheory. Implicit Types gT rT : finGroupType. Variable F : GFunctor.iso_map. Lemma gFsub gT (G : {group gT}) : F gT G \subset G. Proof. by case: F gT G. Qed. Lemma gFsub_trans gT (G : {group gT}) (A : {pred gT}) : G \subset A -> F gT G \subset A. Proof. exact/subset_trans/gFsub. Qed. Lemma gF1 gT : F gT 1 = 1. Proof. exact/trivgP/gFsub. Qed. Lemma gFiso_cont : GFunctor.iso_continuous F. Proof. by case F. Qed. Lemma gFchar gT (G : {group gT}) : F gT G \char G. Proof. apply/andP; split => //; first by apply: gFsub. apply/forall_inP=> f Af; rewrite -{2}(im_autm Af) -(autmE Af). by rewrite -morphimEsub ?gFsub ?gFiso_cont ?injm_autm. Qed. Lemma gFnorm gT (G : {group gT}) : G \subset 'N(F gT G). Proof. exact/char_norm/gFchar. Qed. Lemma gFnorms gT (G : {group gT}) : 'N(G) \subset 'N(F gT G). Proof. exact/char_norms/gFchar. Qed. Lemma gFnormal gT (G : {group gT}) : F gT G <| G. Proof. exact/char_normal/gFchar. Qed. Lemma gFchar_trans gT (G H : {group gT}) : H \char G -> F gT H \char G. Proof. exact/char_trans/gFchar. Qed. Lemma gFnormal_trans gT (G H : {group gT}) : H <| G -> F gT H <| G. Proof. exact/char_normal_trans/gFchar. Qed. Lemma gFnorm_trans gT (A : {pred gT}) (G : {group gT}) : A \subset 'N(G) -> A \subset 'N(F gT G). Proof. by move/subset_trans/(_ (gFnorms G)). Qed. Lemma injmF_sub gT rT (G D : {group gT}) (f : {morphism D >-> rT}) : 'injm f -> G \subset D -> f @* (F gT G) \subset F rT (f @* G). Proof. move=> injf sGD; have:= gFiso_cont (injm_restrm sGD injf). by rewrite im_restrm morphim_restrm (setIidPr _) ?gFsub. Qed. Lemma injmF gT rT (G D : {group gT}) (f : {morphism D >-> rT}) : 'injm f -> G \subset D -> f @* (F gT G) = F rT (f @* G). Proof. move=> injf sGD; have [sfGD injf'] := (morphimS f sGD, injm_invm injf). apply/esym/eqP; rewrite eqEsubset -(injmSK injf') ?gFsub_trans //. by rewrite !(subset_trans (injmF_sub _ _)) ?morphim_invm // gFsub_trans. Qed. Lemma gFisom gT rT (G D : {group gT}) R (f : {morphism D >-> rT}) : G \subset D -> isom G (gval R) f -> isom (F gT G) (F rT R) f. Proof. case/(restrmP f)=> g [gf _ _ _]; rewrite -{f}gf => /isomP[injg <-]. by rewrite sub_isom ?gFsub ?injmF. Qed. Lemma gFisog gT rT (G : {group gT}) (R : {group rT}) : G \isog R -> F gT G \isog F rT R. Proof. by case/isogP=> f injf <-; rewrite -injmF // sub_isog ?gFsub. Qed. End IsoFunctorTheory. Section FunctorTheory. Implicit Types gT rT : finGroupType. Variable F : GFunctor.map. Lemma gFcont : GFunctor.continuous F. Proof. by case F. Qed. Lemma morphimF gT rT (G D : {group gT}) (f : {morphism D >-> rT}) : G \subset D -> f @* (F gT G) \subset F rT (f @* G). Proof. move=> sGD; rewrite -(setIidPr (gFsub F G)). by rewrite -{3}(setIid G) -!(morphim_restrm sGD) gFcont. Qed. End FunctorTheory. Section PartialFunctorTheory. Implicit Types gT rT : finGroupType. Section BasicTheory. Variable F : GFunctor.pmap. Lemma gFhereditary : GFunctor.hereditary F. Proof. by case F. Qed. Lemma gFunctorI gT (G H : {group gT}) : F gT G :&: H = F gT G :&: F gT (G :&: H). Proof. rewrite -{1}(setIidPr (gFsub F G)) setIAC setIC. rewrite -(setIidPr (gFhereditary (subsetIl G H))). by rewrite setIC -setIA (setIidPr (gFsub F (G :&: H))). Qed. Lemma pmorphimF : GFunctor.pcontinuous F. Proof. move=> gT rT G D f; rewrite -morphimIdom -(setIidPl (gFsub F G)) setICA. apply: (subset_trans (morphimS f (gFhereditary (subsetIr D G)))). by rewrite (subset_trans (morphimF F _ _ )) ?morphimIdom ?subsetIl. Qed. Lemma gFid gT (G : {group gT}) : F gT (F gT G) = F gT G. Proof. apply/eqP; rewrite eqEsubset gFsub. by move/gFhereditary: (gFsub F G); rewrite setIid /=. Qed. End BasicTheory. Section Modulo. Variables (F1 : GFunctor.pmap) (F2 : GFunctor.map). Lemma gFmod_closed : GFunctor.closed (F1 %% F2). Proof. by move=> gT G; rewrite sub_cosetpre_quo ?gFsub ?gFnormal. Qed. Lemma gFmod_cont : GFunctor.continuous (F1 %% F2). Proof. move=> gT rT G f; have nF2 := gFnorm F2. have sDF: G \subset 'dom (coset (F2 _ G)) by rewrite nF2. have sDFf: G \subset 'dom (coset (F2 _ (f @* G)) \o f). by rewrite -sub_morphim_pre ?subsetIl // nF2. pose K := 'ker (restrm sDFf (coset (F2 _ (f @* G)) \o f)). have sFK: 'ker (restrm sDF (coset (F2 _ G))) \subset K. rewrite {}/K !ker_restrm ker_comp /= subsetI subsetIl !ker_coset /=. by rewrite -sub_morphim_pre ?subsetIl // morphimIdom ?morphimF. have sOF := gFsub F1 (G / F2 _ G); have sGG: G \subset G by []. rewrite -sub_quotient_pre; last first. by apply: subset_trans (nF2 _ _); rewrite morphimS ?gFmod_closed. suffices im_fact H : F2 _ G \subset gval H -> H \subset G -> factm sFK sGG @* (H / F2 _ G) = f @* H / F2 _ (f @* G). - rewrite -2?im_fact ?gFmod_closed ?gFsub //. by rewrite cosetpreK morphimF /= ?morphim_restrm ?setIid. by rewrite -sub_quotient_pre ?normG //= trivg_quotient sub1G. move=> sFH sHG; rewrite -(morphimIdom _ (H / _)) /= {2}morphim_restrm /= setIid. rewrite -morphimIG ?ker_coset // -(morphim_restrm sDF) morphim_factm. by rewrite morphim_restrm morphim_comp -quotientE morphimIdom. Qed. Canonical gFmod_igFun := [igFun by gFmod_closed & gFmod_cont]. Canonical gFmod_gFun := [gFun by gFmod_cont]. End Modulo. Variables F1 F2 : GFunctor.pmap. Lemma gFmod_hereditary : GFunctor.hereditary (F1 %% F2). Proof. move=> gT H G sHG; set FGH := _ :&: H; have nF2H := gFnorm F2 H. rewrite -sub_quotient_pre; last exact: subset_trans (subsetIr _ _) _. pose rH := restrm nF2H (coset (F2 _ H)); pose rHM := [morphism of rH]. have rnorm_simpl: rHM @* H = H / F2 _ H by rewrite morphim_restrm setIid. have nF2G := subset_trans sHG (gFnorm F2 G). pose rG := restrm nF2G (coset (F2 _ G)); pose rGM := [morphism of rG]. have sqKfK: 'ker rGM \subset 'ker rHM. rewrite !ker_restrm !ker_coset (setIidPr (gFsub F2 _)) setIC /=. exact: gFhereditary. have sHH := subxx H; rewrite -rnorm_simpl /= -(morphim_factm sqKfK sHH) /=. apply: subset_trans (gFcont F1 _); rewrite /= {2}morphim_restrm setIid /=. apply: subset_trans (morphimS _ (gFhereditary _ (quotientS _ sHG))) => /=. have ->: FGH / _ = restrm nF2H (coset _) @* FGH. by rewrite morphim_restrm setICA setIid. rewrite -(morphim_factm sqKfK sHH) morphimS //= morphim_restrm -quotientE. by rewrite setICA setIid (subset_trans (quotientI _ _ _)) // cosetpreK. Qed. Canonical gFmod_pgFun := [pgFun by gFmod_hereditary]. End PartialFunctorTheory. Section MonotonicFunctorTheory. Implicit Types gT rT : finGroupType. Lemma gFunctorS (F : GFunctor.mono_map) : GFunctor.monotonic F. Proof. by case: F. Qed. Section Composition. Variables (F1 : GFunctor.mono_map) (F2 : GFunctor.map). Lemma gFcomp_closed : GFunctor.closed (F1 \o F2). Proof. by move=> gT G; rewrite !gFsub_trans. Qed. Lemma gFcomp_cont : GFunctor.continuous (F1 \o F2). Proof. move=> gT rT G phi; rewrite (subset_trans (morphimF _ _ (gFsub _ _))) //. by rewrite (subset_trans (gFunctorS F1 (gFcont F2 phi))). Qed. Canonical gFcomp_igFun := [igFun by gFcomp_closed & gFcomp_cont]. Canonical gFcomp_gFun :=[gFun by gFcomp_cont]. End Composition. Variables F1 F2 : GFunctor.mono_map. Lemma gFcompS : GFunctor.monotonic (F1 \o F2). Proof. by move=> gT H G sHG; rewrite !gFunctorS. Qed. Canonical gFcomp_mgFun := [mgFun by gFcompS]. End MonotonicFunctorTheory. Section GFunctorExamples. Implicit Types gT : finGroupType. Definition idGfun gT := @id {set gT}. Lemma idGfun_closed : GFunctor.closed idGfun. Proof. by []. Qed. Lemma idGfun_cont : GFunctor.continuous idGfun. Proof. by []. Qed. Lemma idGfun_monotonic : GFunctor.monotonic idGfun. Proof. by []. Qed. Canonical bgFunc_id := [igFun by idGfun_closed & idGfun_cont]. Canonical gFunc_id := [gFun by idGfun_cont]. Canonical mgFunc_id := [mgFun by idGfun_monotonic]. Definition trivGfun gT of {set gT} := [1 gT]. Lemma trivGfun_cont : GFunctor.pcontinuous trivGfun. Proof. by move=> gT rT D G f; rewrite morphim1. Qed. Canonical trivGfun_igFun := [igFun by sub1G & trivGfun_cont]. Canonical trivGfun_gFun := [gFun by trivGfun_cont]. Canonical trivGfun_pgFun := [pgFun by trivGfun_cont]. End GFunctorExamples.
UnitsOfNormedAlgebra.lean
/- Copyright (c) 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Heather Macbeth, Winston Yin -/ import Mathlib.Geometry.Manifold.Algebra.LieGroup /-! # Units of a normed algebra We construct the Lie group structure on the group of units of a complete normed `𝕜`-algebra `R`. The group of units `Rˣ` has a natural `C^n` manifold structure modelled on `R` given by its embedding into `R`. Together with the smoothness of the multiplication and inverse of its elements, `Rˣ` forms a Lie group. An important special case of this construction is the general linear group. For a normed space `V` over a field `𝕜`, the `𝕜`-linear endomorphisms of `V` are a normed `𝕜`-algebra (see `ContinuousLinearMap.toNormedAlgebra`), so this construction provides a Lie group structure on its group of units, the general linear group GL(`𝕜`, `V`), as demonstrated by: ``` example {V : Type*} [NormedAddCommGroup V] [NormedSpace 𝕜 V] [CompleteSpace V] : LieGroup 𝓘(𝕜, V →L[𝕜] V) (V →L[𝕜] V)ˣ := inferInstance ``` -/ noncomputable section open scoped Manifold ContDiff namespace Units variable {R : Type*} [NormedRing R] [CompleteSpace R] {n : WithTop ℕ∞} instance : ChartedSpace R Rˣ := isOpenEmbedding_val.singletonChartedSpace theorem chartAt_apply {a : Rˣ} {b : Rˣ} : chartAt R a b = b := rfl theorem chartAt_source {a : Rˣ} : (chartAt R a).source = Set.univ := rfl variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] [NormedAlgebra 𝕜 R] instance : IsManifold 𝓘(𝕜, R) n Rˣ := isOpenEmbedding_val.isManifold_singleton /-- For a complete normed ring `R`, the embedding of the units `Rˣ` into `R` is a `C^n` map between manifolds. -/ lemma contMDiff_val : ContMDiff 𝓘(𝕜, R) 𝓘(𝕜, R) n (val : Rˣ → R) := contMDiff_isOpenEmbedding Units.isOpenEmbedding_val /-- The units of a complete normed ring form a Lie group. -/ instance : LieGroup 𝓘(𝕜, R) n Rˣ where contMDiff_mul := by apply ContMDiff.of_comp_isOpenEmbedding Units.isOpenEmbedding_val have : (val : Rˣ → R) ∘ (fun x : Rˣ × Rˣ => x.1 * x.2) = (fun x : R × R => x.1 * x.2) ∘ (fun x : Rˣ × Rˣ => (x.1, x.2)) := by ext; simp rw [this] have : ContMDiff (𝓘(𝕜, R).prod 𝓘(𝕜, R)) 𝓘(𝕜, R × R) n (fun x : Rˣ × Rˣ => ((x.1 : R), (x.2 : R))) := (contMDiff_val.comp contMDiff_fst).prodMk_space (contMDiff_val.comp contMDiff_snd) refine ContMDiff.comp ?_ this rw [contMDiff_iff_contDiff] exact contDiff_mul contMDiff_inv := by apply ContMDiff.of_comp_isOpenEmbedding Units.isOpenEmbedding_val have : (val : Rˣ → R) ∘ (fun x : Rˣ => x⁻¹) = Ring.inverse ∘ val := by ext; simp rw [this, ContMDiff] refine fun x => ContMDiffAt.comp x ?_ (contMDiff_val x) rw [contMDiffAt_iff_contDiffAt] exact contDiffAt_ringInverse _ _ end Units
Topology.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.Algebra.Module.Multilinear.Bounded import Mathlib.Topology.Algebra.Module.UniformConvergence import Mathlib.Topology.Algebra.SeparationQuotient.Section import Mathlib.Topology.Hom.ContinuousEvalConst import Mathlib.Topology.Algebra.InfiniteSum.Basic /-! # Topology on continuous multilinear maps In this file we define `TopologicalSpace` and `UniformSpace` structures on `ContinuousMultilinearMap 𝕜 E F`, where `E i` is a family of vector spaces over `𝕜` with topologies and `F` is a topological vector space. -/ open Bornology Function Set Topology open scoped UniformConvergence Filter namespace ContinuousMultilinearMap variable {𝕜 ι : Type*} {E : ι → Type*} {F : Type*} [NormedField 𝕜] [∀ i, TopologicalSpace (E i)] [∀ i, AddCommGroup (E i)] [∀ i, Module 𝕜 (E i)] [AddCommGroup F] [Module 𝕜 F] /-- An auxiliary definition used to define topology on `ContinuousMultilinearMap 𝕜 E F`. -/ def toUniformOnFun [TopologicalSpace F] (f : ContinuousMultilinearMap 𝕜 E F) : (Π i, E i) →ᵤ[{s | IsVonNBounded 𝕜 s}] F := UniformOnFun.ofFun _ f open UniformOnFun in lemma range_toUniformOnFun [DecidableEq ι] [TopologicalSpace F] : range toUniformOnFun = {f : (Π i, E i) →ᵤ[{s | IsVonNBounded 𝕜 s}] F | Continuous (toFun _ f) ∧ (∀ (m : Π i, E i) i x y, toFun _ f (update m i (x + y)) = toFun _ f (update m i x) + toFun _ f (update m i y)) ∧ (∀ (m : Π i, E i) i (c : 𝕜) x, toFun _ f (update m i (c • x)) = c • toFun _ f (update m i x))} := by ext f constructor · rintro ⟨f, rfl⟩ exact ⟨f.cont, f.map_update_add, f.map_update_smul⟩ · rintro ⟨hcont, hadd, hsmul⟩ exact ⟨⟨⟨f, by intro; convert hadd, by intro; convert hsmul⟩, hcont⟩, rfl⟩ @[simp] lemma toUniformOnFun_toFun [TopologicalSpace F] (f : ContinuousMultilinearMap 𝕜 E F) : UniformOnFun.toFun _ f.toUniformOnFun = f := rfl instance instTopologicalSpace [TopologicalSpace F] [IsTopologicalAddGroup F] : TopologicalSpace (ContinuousMultilinearMap 𝕜 E F) := .induced toUniformOnFun <| @UniformOnFun.topologicalSpace _ _ (IsTopologicalAddGroup.toUniformSpace F) _ instance instUniformSpace [UniformSpace F] [IsUniformAddGroup F] : UniformSpace (ContinuousMultilinearMap 𝕜 E F) := .replaceTopology (.comap toUniformOnFun <| UniformOnFun.uniformSpace _ _ _) <| by rw [instTopologicalSpace, IsUniformAddGroup.toUniformSpace_eq]; rfl section IsUniformAddGroup variable [UniformSpace F] [IsUniformAddGroup F] lemma isUniformInducing_toUniformOnFun : IsUniformInducing (toUniformOnFun : ContinuousMultilinearMap 𝕜 E F → ((Π i, E i) →ᵤ[{s | IsVonNBounded 𝕜 s}] F)) := ⟨rfl⟩ lemma isUniformEmbedding_toUniformOnFun : IsUniformEmbedding (toUniformOnFun : ContinuousMultilinearMap 𝕜 E F → _) := ⟨isUniformInducing_toUniformOnFun, DFunLike.coe_injective⟩ lemma isEmbedding_toUniformOnFun : IsEmbedding (toUniformOnFun : ContinuousMultilinearMap 𝕜 E F → ((Π i, E i) →ᵤ[{s | IsVonNBounded 𝕜 s}] F)) := isUniformEmbedding_toUniformOnFun.isEmbedding theorem uniformContinuous_coe_fun [∀ i, ContinuousSMul 𝕜 (E i)] : UniformContinuous (DFunLike.coe : ContinuousMultilinearMap 𝕜 E F → (Π i, E i) → F) := (UniformOnFun.uniformContinuous_toFun isVonNBounded_covers).comp isUniformEmbedding_toUniformOnFun.uniformContinuous theorem uniformContinuous_eval_const [∀ i, ContinuousSMul 𝕜 (E i)] (x : Π i, E i) : UniformContinuous fun f : ContinuousMultilinearMap 𝕜 E F ↦ f x := uniformContinuous_pi.1 uniformContinuous_coe_fun x instance instIsUniformAddGroup : IsUniformAddGroup (ContinuousMultilinearMap 𝕜 E F) := let φ : ContinuousMultilinearMap 𝕜 E F →+ (Π i, E i) →ᵤ[{s | IsVonNBounded 𝕜 s}] F := { toFun := toUniformOnFun, map_add' := fun _ _ ↦ rfl, map_zero' := rfl } isUniformEmbedding_toUniformOnFun.isUniformAddGroup φ instance instUniformContinuousConstSMul {M : Type*} [Monoid M] [DistribMulAction M F] [SMulCommClass 𝕜 M F] [ContinuousConstSMul M F] : UniformContinuousConstSMul M (ContinuousMultilinearMap 𝕜 E F) := haveI := uniformContinuousConstSMul_of_continuousConstSMul M F isUniformEmbedding_toUniformOnFun.uniformContinuousConstSMul fun _ _ ↦ rfl theorem isUniformInducing_postcomp {G : Type*} [AddCommGroup G] [UniformSpace G] [IsUniformAddGroup G] [Module 𝕜 G] (g : F →L[𝕜] G) (hg : IsUniformInducing g) : IsUniformInducing (g.compContinuousMultilinearMap : ContinuousMultilinearMap 𝕜 E F → ContinuousMultilinearMap 𝕜 E G) := by rw [← isUniformInducing_toUniformOnFun.of_comp_iff] exact (UniformOnFun.postcomp_isUniformInducing hg).comp isUniformInducing_toUniformOnFun section CompleteSpace variable [∀ i, ContinuousSMul 𝕜 (E i)] [ContinuousConstSMul 𝕜 F] [CompleteSpace F] open UniformOnFun in theorem completeSpace (h : IsCoherentWith {s : Set (Π i, E i) | IsVonNBounded 𝕜 s}) : CompleteSpace (ContinuousMultilinearMap 𝕜 E F) := by classical wlog hF : T2Space F generalizing F · rw [(isUniformInducing_postcomp (SeparationQuotient.mkCLM _ _) SeparationQuotient.isUniformInducing_mk).completeSpace_congr] · exact this inferInstance · intro f use (SeparationQuotient.outCLM _ _).compContinuousMultilinearMap f simp [DFunLike.ext_iff] have H : ∀ {m : Π i, E i}, Continuous fun f : (Π i, E i) →ᵤ[{s | IsVonNBounded 𝕜 s}] F ↦ toFun _ f m := (uniformContinuous_eval (isVonNBounded_covers) _).continuous rw [completeSpace_iff_isComplete_range isUniformInducing_toUniformOnFun, range_toUniformOnFun] simp only [setOf_and, setOf_forall] apply_rules [IsClosed.isComplete, IsClosed.inter] · exact UniformOnFun.isClosed_setOf_continuous h · exact isClosed_iInter fun m ↦ isClosed_iInter fun i ↦ isClosed_iInter fun x ↦ isClosed_iInter fun y ↦ isClosed_eq H (H.add H) · exact isClosed_iInter fun m ↦ isClosed_iInter fun i ↦ isClosed_iInter fun c ↦ isClosed_iInter fun x ↦ isClosed_eq H (H.const_smul _) instance instCompleteSpace [∀ i, IsTopologicalAddGroup (E i)] [SequentialSpace (Π i, E i)] : CompleteSpace (ContinuousMultilinearMap 𝕜 E F) := completeSpace <| .of_seq fun _u x hux ↦ (hux.isVonNBounded_range 𝕜).insert x end CompleteSpace section RestrictScalars variable (𝕜' : Type*) [NontriviallyNormedField 𝕜'] [NormedAlgebra 𝕜' 𝕜] [∀ i, Module 𝕜' (E i)] [∀ i, IsScalarTower 𝕜' 𝕜 (E i)] [Module 𝕜' F] [IsScalarTower 𝕜' 𝕜 F] [∀ i, ContinuousSMul 𝕜 (E i)] theorem isUniformEmbedding_restrictScalars : IsUniformEmbedding (restrictScalars 𝕜' : ContinuousMultilinearMap 𝕜 E F → ContinuousMultilinearMap 𝕜' E F) := by letI : NontriviallyNormedField 𝕜 := ⟨let ⟨x, hx⟩ := @NontriviallyNormedField.non_trivial 𝕜' _; ⟨algebraMap 𝕜' 𝕜 x, by simpa⟩⟩ rw [← isUniformEmbedding_toUniformOnFun.of_comp_iff] convert isUniformEmbedding_toUniformOnFun using 4 with s exact ⟨fun h ↦ h.extend_scalars _, fun h ↦ h.restrict_scalars _⟩ theorem uniformContinuous_restrictScalars : UniformContinuous (restrictScalars 𝕜' : ContinuousMultilinearMap 𝕜 E F → ContinuousMultilinearMap 𝕜' E F) := (isUniformEmbedding_restrictScalars 𝕜').uniformContinuous end RestrictScalars end IsUniformAddGroup variable [TopologicalSpace F] [IsTopologicalAddGroup F] instance instIsTopologicalAddGroup : IsTopologicalAddGroup (ContinuousMultilinearMap 𝕜 E F) := letI := IsTopologicalAddGroup.toUniformSpace F haveI := isUniformAddGroup_of_addCommGroup (G := F) inferInstance instance instContinuousConstSMul {M : Type*} [Monoid M] [DistribMulAction M F] [SMulCommClass 𝕜 M F] [ContinuousConstSMul M F] : ContinuousConstSMul M (ContinuousMultilinearMap 𝕜 E F) := by letI := IsTopologicalAddGroup.toUniformSpace F haveI := isUniformAddGroup_of_addCommGroup (G := F) infer_instance instance instContinuousSMul [ContinuousSMul 𝕜 F] : ContinuousSMul 𝕜 (ContinuousMultilinearMap 𝕜 E F) := letI := IsTopologicalAddGroup.toUniformSpace F haveI := isUniformAddGroup_of_addCommGroup (G := F) let φ : ContinuousMultilinearMap 𝕜 E F →ₗ[𝕜] (Π i, E i) → F := { toFun := (↑), map_add' := fun _ _ ↦ rfl, map_smul' := fun _ _ ↦ rfl } UniformOnFun.continuousSMul_induced_of_image_bounded _ _ _ _ φ isEmbedding_toUniformOnFun.isInducing fun _ _ hu ↦ hu.image_multilinear _ theorem hasBasis_nhds_zero_of_basis {ι : Type*} {p : ι → Prop} {b : ι → Set F} (h : (𝓝 (0 : F)).HasBasis p b) : (𝓝 (0 : ContinuousMultilinearMap 𝕜 E F)).HasBasis (fun Si : Set (Π i, E i) × ι => IsVonNBounded 𝕜 Si.1 ∧ p Si.2) fun Si => { f | MapsTo f Si.1 (b Si.2) } := by letI : UniformSpace F := IsTopologicalAddGroup.toUniformSpace F haveI : IsUniformAddGroup F := isUniformAddGroup_of_addCommGroup rw [nhds_induced] refine (UniformOnFun.hasBasis_nhds_zero_of_basis _ ?_ ?_ h).comap DFunLike.coe · exact ⟨∅, isVonNBounded_empty _ _⟩ · exact directedOn_of_sup_mem fun _ _ => Bornology.IsVonNBounded.union theorem hasBasis_nhds_zero : (𝓝 (0 : ContinuousMultilinearMap 𝕜 E F)).HasBasis (fun SV : Set (Π i, E i) × Set F => IsVonNBounded 𝕜 SV.1 ∧ SV.2 ∈ 𝓝 0) fun SV => { f | MapsTo f SV.1 SV.2 } := hasBasis_nhds_zero_of_basis (Filter.basis_sets _) variable [∀ i, ContinuousSMul 𝕜 (E i)] instance : ContinuousEvalConst (ContinuousMultilinearMap 𝕜 E F) (Π i, E i) F where continuous_eval_const x := let _ := IsTopologicalAddGroup.toUniformSpace F have _ := isUniformAddGroup_of_addCommGroup (G := F) (uniformContinuous_eval_const x).continuous instance instT2Space [T2Space F] : T2Space (ContinuousMultilinearMap 𝕜 E F) := .of_injective_continuous DFunLike.coe_injective continuous_coeFun instance instT3Space [T2Space F] : T3Space (ContinuousMultilinearMap 𝕜 E F) := inferInstance section RestrictScalars variable {𝕜' : Type*} [NontriviallyNormedField 𝕜'] [NormedAlgebra 𝕜' 𝕜] [∀ i, Module 𝕜' (E i)] [∀ i, IsScalarTower 𝕜' 𝕜 (E i)] [Module 𝕜' F] [IsScalarTower 𝕜' 𝕜 F] theorem isEmbedding_restrictScalars : IsEmbedding (restrictScalars 𝕜' : ContinuousMultilinearMap 𝕜 E F → ContinuousMultilinearMap 𝕜' E F) := letI : UniformSpace F := IsTopologicalAddGroup.toUniformSpace F haveI : IsUniformAddGroup F := isUniformAddGroup_of_addCommGroup (isUniformEmbedding_restrictScalars _).isEmbedding @[continuity, fun_prop] theorem continuous_restrictScalars : Continuous (restrictScalars 𝕜' : ContinuousMultilinearMap 𝕜 E F → ContinuousMultilinearMap 𝕜' E F) := isEmbedding_restrictScalars.continuous variable (𝕜') in /-- `ContinuousMultilinearMap.restrictScalars` as a `ContinuousLinearMap`. -/ @[simps -fullyApplied apply] def restrictScalarsLinear [ContinuousConstSMul 𝕜' F] : ContinuousMultilinearMap 𝕜 E F →L[𝕜'] ContinuousMultilinearMap 𝕜' E F where toFun := restrictScalars 𝕜' map_add' _ _ := rfl map_smul' _ _ := rfl end RestrictScalars variable (𝕜 E F) /-- The application of a multilinear map as a `ContinuousLinearMap`. -/ def apply [ContinuousConstSMul 𝕜 F] (m : Π i, E i) : ContinuousMultilinearMap 𝕜 E F →L[𝕜] F where toFun c := c m map_add' _ _ := rfl map_smul' _ _ := rfl cont := continuous_eval_const m variable {𝕜 E F} @[simp] lemma apply_apply [ContinuousConstSMul 𝕜 F] {m : Π i, E i} {c : ContinuousMultilinearMap 𝕜 E F} : apply 𝕜 E F m c = c m := rfl theorem hasSum_eval {α : Type*} {p : α → ContinuousMultilinearMap 𝕜 E F} {q : ContinuousMultilinearMap 𝕜 E F} (h : HasSum p q) (m : Π i, E i) : HasSum (fun a => p a m) (q m) := h.map (applyAddHom m) (continuous_eval_const m) theorem tsum_eval [T2Space F] {α : Type*} {p : α → ContinuousMultilinearMap 𝕜 E F} (hp : Summable p) (m : Π i, E i) : (∑' a, p a) m = ∑' a, p a m := (hasSum_eval hp.hasSum m).tsum_eq.symm end ContinuousMultilinearMap
poly.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice. From mathcomp Require Import fintype bigop finset tuple div ssralg. From mathcomp Require Import countalg binomial. (******************************************************************************) (* This file provides a library for univariate polynomials over ring *) (* structures; it also provides an extended theory for polynomials whose *) (* coefficients range over commutative rings and integral domains. *) (* *) (* {poly R} == the type of polynomials with coefficients of type R, *) (* represented as lists with a non zero last element *) (* (big endian representation); the coefficient type R *) (* must have a canonical nzRingType structure cR. In *) (* fact {poly R} denotes the concrete type polynomial *) (* cR; R is just a phantom argument that lets type *) (* inferencereconstruct the (hidden) nzRingType *) (* structure cR. *) (* p : seq R == the big-endian sequence of coefficients of p, via *) (* the coercion polyseq : polynomial >-> seq. *) (* Poly s == the polynomial with coefficient sequence s (ignoring *) (* trailing zeroes). *) (* \poly_(i < n) E(i) == the polynomial of degree at most n - 1 whose *) (* coefficients are given by the general term E(i) *) (* 0, 1, - p, p + q, == the usual ring operations: {poly R} has a canonical *) (* p * q, p ^+ n, ... nzRingType structure, which is commutative / integral*) (* when R is commutative / integral, respectively. *) (* polyC c, c%:P == the constant polynomial c *) (* 'X == the (unique) variable *) (* 'X^n == a power of 'X; 'X^0 is 1, 'X^1 is convertible to 'X *) (* p`_i == the coefficient of 'X^i in p; this is in fact just *) (* the ring_scope notation generic seq-indexing using *) (* nth 0%R, combined with the polyseq coercion. *) (* *** The multi-rule coefE simplifies p`_i *) (* coefp i == the linear function p |-> p`_i (self-exapanding). *) (* size p == 1 + the degree of p, or 0 if p = 0 (this is the *) (* generic seq function combined with polyseq). *) (* lead_coef p == the coefficient of the highest monomial in p, or 0 *) (* if p = 0 (hence lead_coef p = 0 iff p = 0) *) (* p \is monic <=> lead_coef p == 1 (0 is not monic). *) (* p \is a polyOver S <=> the coefficients of p satisfy S; S should have a *) (* key that should be (at least) an addrPred. *) (* p.[x] == the evaluation of a polynomial p at a point x using *) (* the Horner scheme *) (* *** The multi-rule hornerE (resp., hornerE_comm) unwinds *) (* horner evaluation of a polynomial expression (resp., *) (* in a non commutative ring, with side conditions). *) (* p^`() == formal derivative of p *) (* p^`(n) == formal n-derivative of p *) (* p^`N(n) == formal n-derivative of p divided by n! *) (* p \Po q == polynomial composition; because this is naturally a *) (* a linear morphism in the first argument, this *) (* notation is transposed (q comes before p for redex *) (* selection, etc). *) (* := \sum(i < size p) p`_i *: q ^+ i *) (* odd_poly p == monomials of odd degree of p *) (* even_poly p == monomials of even degree of p *) (* take_poly n p == polynomial p without its monomials of degree >= n *) (* drop_poly n p == polynomial p divided by X^n *) (* comm_poly p x == x and p.[x] commute; this is a sufficient condition *) (* for evaluating (q * p).[x] as q.[x] * p.[x] when R *) (* is not commutative. *) (* comm_coef p x == x commutes with all the coefficients of p (clearly, *) (* this implies comm_poly p x). *) (* root p x == x is a root of p, i.e., p.[x] = 0 *) (* n.-unity_root x == x is an nth root of unity, i.e., a root of 'X^n - 1 *) (* n.-primitive_root x == x is a primitive nth root of unity, i.e., n is the *) (* least positive integer m > 0 such that x ^+ m = 1. *) (* *** The submodule poly.UnityRootTheory can be used to *) (* import selectively the part of the theory of roots *) (* of unity that doesn't mention polynomials explicitly *) (* map_poly f p == the image of the polynomial by the function f (which *) (* (locally, p^f) is usually a ring morphism). *) (* p^:P == p lifted to {poly {poly R}} (:= map_poly polyC p). *) (* commr_rmorph f u == u commutes with the image of f (i.e., with all f x). *) (* horner_morph cfu == given cfu : commr_rmorph f u, the function mapping p *) (* to the value of map_poly f p at u; this is a ring *) (* morphism from {poly R} to the codomain of f when f *) (* is a ring morphism. *) (* horner_eval u == the function mapping p to p.[u]; this function can *) (* only be used for u in a commutative ring, so it is *) (* always a linear ring morphism from {poly R} to R. *) (* horner_alg a == given a in some R-algebra A, the function evaluating *) (* a polynomial p at a; it is always a linear ring *) (* morphism from {poly R} to A. *) (* diff_roots x y == x and y are distinct roots; if R is a field, this *) (* just means x != y, but this concept is generalized *) (* to the case where R is only a ring with units (i.e., *) (* a unitRingType); in which case it means that x and y *) (* commute, and that the difference x - y is a unit *) (* (i.e., has a multiplicative inverse) in R. *) (* to just x != y). *) (* uniq_roots s == s is a sequence or pairwise distinct roots, in the *) (* sense of diff_roots p above. *) (* *** We only show that these operations and properties are transferred by *) (* morphisms whose domain is a field (thus ensuring injectivity). *) (* We prove the factor_theorem, and the max_poly_roots inequality relating *) (* the number of distinct roots of a polynomial and its size. *) (* The some polynomial lemmas use following suffix interpretation : *) (* C - constant polynomial (as in polyseqC : a%:P = nseq (a != 0) a). *) (* X - the polynomial variable 'X (as in coefX : 'X`_i = (i == 1%N)). *) (* Xn - power of 'X (as in monicXn : monic 'X^n). *) (* *) (* Pdeg2.Field (exported by the present library) : theory of the degree 2 *) (* polynomials. *) (* Pdeg2.FieldMonic : theory of Pdeg2.Field specialized to monic polynomials. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope unity_root_scope. Import GRing.Theory. Local Open Scope ring_scope. Reserved Notation "{ 'poly' T }" (format "{ 'poly' T }"). Reserved Notation "c %:P" (format "c %:P"). Reserved Notation "p ^:P" (format "p ^:P"). Reserved Notation "'X". Reserved Notation "''X^' n" (at level 1, format "''X^' n"). Reserved Notation "\poly_ ( i < n ) E" (at level 34, E at level 36, i, n at level 50, format "\poly_ ( i < n ) E"). Reserved Notation "p \Po q" (at level 50). Reserved Notation "p ^`N ( n )" (format "p ^`N ( n )"). Reserved Notation "n .-unity_root" (format "n .-unity_root"). Reserved Notation "n .-primitive_root" (format "n .-primitive_root"). Local Notation simp := Monoid.simpm. Section Polynomial. Variable R : nzSemiRingType. (* Defines a polynomial as a sequence with <> 0 last element *) Record polynomial := Polynomial {polyseq :> seq R; _ : last 1 polyseq != 0}. HB.instance Definition _ := [isSub for polyseq]. HB.instance Definition _ := [Choice of polynomial by <:]. Lemma poly_inj : injective polyseq. Proof. exact: val_inj. Qed. Definition coefp i (p : polynomial) := p`_i. End Polynomial. (* We need to break off the section here to let the Bind Scope directives *) (* take effect. *) Bind Scope ring_scope with polynomial. Arguments polynomial R%_type. Arguments polyseq {R} p%_R. Arguments poly_inj {R} [p1%_R p2%_R] : rename. Arguments coefp {R} i%_N / p%_R. Notation "{ 'poly' T }" := (polynomial T) : type_scope. Section SemiPolynomialTheory. Variable R : nzSemiRingType. Implicit Types (a b c x y z : R) (p q r d : {poly R}). Definition lead_coef p := p`_(size p).-1. Lemma lead_coefE p : lead_coef p = p`_(size p).-1. Proof. by []. Qed. Definition poly_nil := @Polynomial R [::] (oner_neq0 R). Definition polyC c : {poly R} := insubd poly_nil [:: c]. Local Notation "c %:P" := (polyC c). (* Remember the boolean (c != 0) is coerced to 1 if true and 0 if false *) Lemma polyseqC c : c%:P = nseq (c != 0) c :> seq R. Proof. by rewrite val_insubd /=; case: (c == 0). Qed. Lemma size_polyC c : size c%:P = (c != 0). Proof. by rewrite polyseqC size_nseq. Qed. Lemma coefC c i : c%:P`_i = if i == 0 then c else 0. Proof. by rewrite polyseqC; case: i => [|[]]; case: eqP. Qed. Lemma polyCK : cancel polyC (coefp 0). Proof. by move=> c; rewrite [coefp 0 _]coefC. Qed. Lemma polyC_inj : injective polyC. Proof. by move=> c1 c2 eqc12; have:= coefC c2 0; rewrite -eqc12 coefC. Qed. Lemma lead_coefC c : lead_coef c%:P = c. Proof. by rewrite /lead_coef polyseqC; case: eqP. Qed. (* Extensional interpretation (poly <=> nat -> R) *) Lemma polyP p q : nth 0 p =1 nth 0 q <-> p = q. Proof. split=> [eq_pq | -> //]; apply: poly_inj. without loss lt_pq: p q eq_pq / size p < size q. move=> IH; case: (ltngtP (size p) (size q)); try by move/IH->. by move/(@eq_from_nth _ 0); apply. case: q => q nz_q /= in lt_pq eq_pq *; case/eqP: nz_q. by rewrite (last_nth 0) -(subnKC lt_pq) /= -eq_pq nth_default ?leq_addr. Qed. Lemma size1_polyC p : size p <= 1 -> p = (p`_0)%:P. Proof. move=> le_p_1; apply/polyP=> i; rewrite coefC. by case: i => // i; rewrite nth_default // (leq_trans le_p_1). Qed. (* Builds a polynomial by extension. *) Definition cons_poly c p : {poly R} := if p is Polynomial ((_ :: _) as s) ns then @Polynomial R (c :: s) ns else c%:P. Lemma polyseq_cons c p : cons_poly c p = (if ~~ nilp p then c :: p else c%:P) :> seq R. Proof. by case: p => [[]]. Qed. Lemma size_cons_poly c p : size (cons_poly c p) = (if nilp p && (c == 0) then 0 else (size p).+1). Proof. by case: p => [[|c' s] _] //=; rewrite size_polyC; case: eqP. Qed. Lemma coef_cons c p i : (cons_poly c p)`_i = if i == 0 then c else p`_i.-1. Proof. by case: p i => [[|c' s] _] [] //=; rewrite polyseqC; case: eqP => //= _ []. Qed. (* Build a polynomial directly from a list of coefficients. *) Definition Poly := foldr cons_poly 0%:P. Lemma PolyK c s : last c s != 0 -> Poly s = s :> seq R. Proof. case: s => {c}/= [_ |c s]; first by rewrite polyseqC eqxx. elim: s c => /= [|a s IHs] c nz_c; rewrite polyseq_cons ?{}IHs //. by rewrite !polyseqC !eqxx nz_c. Qed. Lemma polyseqK p : Poly p = p. Proof. by apply: poly_inj; apply: PolyK (valP p). Qed. Lemma size_Poly s : size (Poly s) <= size s. Proof. elim: s => [|c s IHs] /=; first by rewrite polyseqC eqxx. by rewrite polyseq_cons; case: ifP => // _; rewrite size_polyC; case: (~~ _). Qed. Lemma coef_Poly s i : (Poly s)`_i = s`_i. Proof. by elim: s i => [|c s IHs] /= [|i]; rewrite !(coefC, eqxx, coef_cons) /=. Qed. (* Build a polynomial from an infinite sequence of coefficients and a bound. *) Definition poly_expanded_def n E := Poly (mkseq E n). Fact poly_key : unit. Proof. by []. Qed. Definition poly := locked_with poly_key poly_expanded_def. Canonical poly_unlockable := [unlockable fun poly]. Local Notation "\poly_ ( i < n ) E" := (poly n (fun i : nat => E)). Lemma polyseq_poly n E : E n.-1 != 0 -> \poly_(i < n) E i = mkseq [eta E] n :> seq R. Proof. rewrite unlock; case: n => [|n] nzEn; first by rewrite polyseqC eqxx. by rewrite (@PolyK 0) // -nth_last nth_mkseq size_mkseq. Qed. Lemma size_poly n E : size (\poly_(i < n) E i) <= n. Proof. by rewrite unlock (leq_trans (size_Poly _)) ?size_mkseq. Qed. Lemma size_poly_eq n E : E n.-1 != 0 -> size (\poly_(i < n) E i) = n. Proof. by move/polyseq_poly->; apply: size_mkseq. Qed. Lemma coef_poly n E k : (\poly_(i < n) E i)`_k = (if k < n then E k else 0). Proof. rewrite unlock coef_Poly. have [lt_kn | le_nk] := ltnP k n; first by rewrite nth_mkseq. by rewrite nth_default // size_mkseq. Qed. Lemma lead_coef_poly n E : n > 0 -> E n.-1 != 0 -> lead_coef (\poly_(i < n) E i) = E n.-1. Proof. by case: n => // n _ nzE; rewrite /lead_coef size_poly_eq // coef_poly leqnn. Qed. Lemma coefK p : \poly_(i < size p) p`_i = p. Proof. by apply/polyP=> i; rewrite coef_poly; case: ltnP => // /(nth_default 0)->. Qed. (* Nmodule structure for polynomial *) Definition add_poly_def p q := \poly_(i < maxn (size p) (size q)) (p`_i + q`_i). Fact add_poly_key : unit. Proof. by []. Qed. Definition add_poly := locked_with add_poly_key add_poly_def. Canonical add_poly_unlockable := [unlockable fun add_poly]. Fact coef_add_poly p q i : (add_poly p q)`_i = p`_i + q`_i. Proof. rewrite unlock coef_poly; case: leqP => //. by rewrite geq_max => /andP[le_p_i le_q_i]; rewrite !nth_default ?add0r. Qed. Fact add_polyA : associative add_poly. Proof. by move=> p q r; apply/polyP=> i; rewrite !coef_add_poly addrA. Qed. Fact add_polyC : commutative add_poly. Proof. by move=> p q; apply/polyP=> i; rewrite !coef_add_poly addrC. Qed. Fact add_poly0 : left_id 0%:P add_poly. Proof. by move=> p; apply/polyP=> i; rewrite coef_add_poly coefC if_same add0r. Qed. HB.instance Definition _ := GRing.isNmodule.Build (polynomial R) add_polyA add_polyC add_poly0. (* Properties of the zero polynomial *) Lemma polyC0 : 0%:P = 0 :> {poly R}. Proof. by []. Qed. Lemma polyseq0 : (0 : {poly R}) = [::] :> seq R. Proof. by rewrite polyseqC eqxx. Qed. Lemma size_poly0 : size (0 : {poly R}) = 0%N. Proof. by rewrite polyseq0. Qed. Lemma coef0 i : (0 : {poly R})`_i = 0. Proof. by rewrite coefC if_same. Qed. Lemma lead_coef0 : lead_coef 0 = 0 :> R. Proof. exact: lead_coefC. Qed. Lemma size_poly_eq0 p : (size p == 0) = (p == 0). Proof. by rewrite size_eq0 -polyseq0. Qed. Lemma size_poly_leq0 p : (size p <= 0) = (p == 0). Proof. by rewrite leqn0 size_poly_eq0. Qed. Lemma size_poly_leq0P p : reflect (p = 0) (size p <= 0). Proof. by apply: (iffP idP); rewrite size_poly_leq0; move/eqP. Qed. Lemma size_poly_gt0 p : (0 < size p) = (p != 0). Proof. by rewrite lt0n size_poly_eq0. Qed. Lemma gt_size_poly_neq0 p n : (size p > n)%N -> p != 0. Proof. by move=> /(leq_ltn_trans _) h; rewrite -size_poly_eq0 lt0n_neq0 ?h. Qed. Lemma nil_poly p : nilp p = (p == 0). Proof. exact: size_poly_eq0. Qed. Lemma poly0Vpos p : {p = 0} + {size p > 0}. Proof. by rewrite lt0n size_poly_eq0; case: eqVneq; [left | right]. Qed. Lemma polySpred p : p != 0 -> size p = (size p).-1.+1. Proof. by rewrite -size_poly_eq0 -lt0n => /prednK. Qed. Lemma lead_coef_eq0 p : (lead_coef p == 0) = (p == 0). Proof. rewrite -nil_poly /lead_coef nth_last. by case: p => [[|x s] /= /negbTE // _]; rewrite eqxx. Qed. Lemma polyC_eq0 (c : R) : (c%:P == 0) = (c == 0). Proof. by rewrite -nil_poly polyseqC; case: (c == 0). Qed. Lemma size_poly1P p : reflect (exists2 c, c != 0 & p = c%:P) (size p == 1). Proof. apply: (iffP eqP) => [pC | [c nz_c ->]]; last by rewrite size_polyC nz_c. have def_p: p = (p`_0)%:P by rewrite -size1_polyC ?pC. by exists p`_0; rewrite // -polyC_eq0 -def_p -size_poly_eq0 pC. Qed. Lemma size_polyC_leq1 (c : R) : (size c%:P <= 1)%N. Proof. by rewrite size_polyC; case: (c == 0). Qed. Lemma leq_sizeP p i : reflect (forall j, i <= j -> p`_j = 0) (size p <= i). Proof. apply: (iffP idP) => [hp j hij| hp]. by apply: nth_default; apply: leq_trans hij. case: (eqVneq p) (lead_coef_eq0 p) => [->|p0]; first by rewrite size_poly0. rewrite leqNgt; apply/contraFN => hs. by apply/eqP/hp; rewrite -ltnS (ltn_predK hs). Qed. (* Size, leading coef, morphism properties of coef *) Lemma coefD p q i : (p + q)`_i = p`_i + q`_i. Proof. exact: coef_add_poly. Qed. Lemma polyCD : {morph polyC : a b / a + b}. Proof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefD !coefC ?addr0. Qed. Lemma size_polyD p q : size (p + q) <= maxn (size p) (size q). Proof. by rewrite -[+%R]/add_poly unlock; exact: size_poly. Qed. Lemma size_polyDl p q : size p > size q -> size (p + q) = size p. Proof. move=> ltqp; rewrite -[+%R]/add_poly unlock size_poly_eq (maxn_idPl (ltnW _))//. by rewrite addrC nth_default ?simp ?nth_last //; case: p ltqp => [[]]. Qed. Lemma size_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) : size (\sum_(i <- r | P i) F i) <= \max_(i <- r | P i) size (F i). Proof. elim/big_rec2: _ => [|i p q _ IHp]; first by rewrite size_poly0. by rewrite -(maxn_idPr IHp) maxnA leq_max size_polyD. Qed. Lemma lead_coefDl p q : size p > size q -> lead_coef (p + q) = lead_coef p. Proof. move=> ltqp; rewrite /lead_coef coefD size_polyDl //. by rewrite addrC nth_default ?simp // -ltnS (ltn_predK ltqp). Qed. Lemma lead_coefDr p q : size q > size p -> lead_coef (p + q) = lead_coef q. Proof. by move/lead_coefDl<-; rewrite addrC. Qed. (* Polynomial semiring structure. *) Definition mul_poly_def p q := \poly_(i < (size p + size q).-1) (\sum_(j < i.+1) p`_j * q`_(i - j)). Fact mul_poly_key : unit. Proof. by []. Qed. Definition mul_poly := locked_with mul_poly_key mul_poly_def. Canonical mul_poly_unlockable := [unlockable fun mul_poly]. Fact coef_mul_poly p q i : (mul_poly p q)`_i = \sum_(j < i.+1) p`_j * q`_(i - j)%N. Proof. rewrite unlock coef_poly -subn1 ltn_subRL add1n; case: leqP => // le_pq_i1. rewrite big1 // => j _; have [lq_q_ij | gt_q_ij] := leqP (size q) (i - j). by rewrite [q`__]nth_default ?mulr0. rewrite nth_default ?mul0r // -(leq_add2r (size q)) (leq_trans le_pq_i1) //. by rewrite -leq_subLR -subnSK. Qed. Fact coef_mul_poly_rev p q i : (mul_poly p q)`_i = \sum_(j < i.+1) p`_(i - j)%N * q`_j. Proof. rewrite coef_mul_poly (reindex_inj rev_ord_inj) /=. by apply: eq_bigr => j _; rewrite (sub_ordK j). Qed. Fact mul_polyA : associative mul_poly. Proof. move=> p q r; apply/polyP=> i; rewrite coef_mul_poly coef_mul_poly_rev. pose coef3 j k := p`_j * (q`_(i - j - k)%N * r`_k). transitivity (\sum_(j < i.+1) \sum_(k < i.+1 | k <= i - j) coef3 j k). apply: eq_bigr => /= j _; rewrite coef_mul_poly_rev big_distrr /=. by rewrite (big_ord_narrow_leq (leq_subr _ _)). rewrite (exchange_big_dep predT) //=; apply: eq_bigr => k _. transitivity (\sum_(j < i.+1 | j <= i - k) coef3 j k). apply: eq_bigl => j; rewrite -ltnS -(ltnS j) -!subSn ?leq_ord //. by rewrite -subn_gt0 -(subn_gt0 j) -!subnDA addnC. rewrite (big_ord_narrow_leq (leq_subr _ _)) coef_mul_poly big_distrl /=. by apply: eq_bigr => j _; rewrite /coef3 -!subnDA addnC mulrA. Qed. Fact mul_1poly : left_id 1%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Fact mul_poly1 : right_id 1%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Fact mul_polyDl : left_distributive mul_poly +%R. Proof. move=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split. by apply: eq_bigr => j _; rewrite coefD mulrDl. Qed. Fact mul_polyDr : right_distributive mul_poly +%R. Proof. move=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split. by apply: eq_bigr => j _; rewrite coefD mulrDr. Qed. Fact mul_0poly : left_zero 0%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp // coefC; case: ifP. Qed. Fact mul_poly0 : right_zero 0%:P mul_poly. Proof. move=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp // coefC; case: ifP. Qed. Fact poly1_neq0 : 1%:P != 0 :> {poly R}. Proof. by rewrite polyC_eq0 oner_neq0. Qed. HB.instance Definition _ := GRing.Nmodule_isNzSemiRing.Build (polynomial R) mul_polyA mul_1poly mul_poly1 mul_polyDl mul_polyDr mul_0poly mul_poly0 poly1_neq0. Lemma polyC1 : 1%:P = 1 :> {poly R}. Proof. by []. Qed. Lemma polyseq1 : (1 : {poly R}) = [:: 1] :> seq R. Proof. by rewrite polyseqC oner_neq0. Qed. Lemma size_poly1 : size (1 : {poly R}) = 1. Proof. by rewrite polyseq1. Qed. Lemma coef1 i : (1 : {poly R})`_i = (i == 0)%:R. Proof. by case: i => [|i]; rewrite polyseq1 /= ?nth_nil. Qed. Lemma lead_coef1 : lead_coef 1 = 1 :> R. Proof. exact: lead_coefC. Qed. Lemma coefM p q i : (p * q)`_i = \sum_(j < i.+1) p`_j * q`_(i - j)%N. Proof. exact: coef_mul_poly. Qed. Lemma coefMr p q i : (p * q)`_i = \sum_(j < i.+1) p`_(i - j)%N * q`_j. Proof. exact: coef_mul_poly_rev. Qed. Lemma coef0M p q : (p * q)`_0 = p`_0 * q`_0. Proof. by rewrite coefM big_ord1. Qed. Lemma coef0_prod I rI (F : I -> {poly R}) P : (\prod_(i <- rI| P i) F i)`_0 = \prod_(i <- rI | P i) (F i)`_0. Proof. by apply: (big_morph _ coef0M); rewrite coef1 eqxx. Qed. Lemma size_polyMleq p q : size (p * q) <= (size p + size q).-1. Proof. by rewrite -[*%R]/mul_poly unlock size_poly. Qed. Lemma mul_lead_coef p q : lead_coef p * lead_coef q = (p * q)`_(size p + size q).-2. Proof. pose dp := (size p).-1; pose dq := (size q).-1. have [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 !mul0r coef0. have [-> | nz_q] := eqVneq q 0; first by rewrite lead_coef0 !mulr0 coef0. have ->: (size p + size q).-2 = (dp + dq)%N. by do 2!rewrite polySpred // addSn addnC. have lt_p_pq: dp < (dp + dq).+1 by rewrite ltnS leq_addr. rewrite coefM (bigD1 (Ordinal lt_p_pq)) ?big1 ?simp ?addKn //= => i. rewrite -val_eqE neq_ltn /= => /orP[lt_i_p | gt_i_p]; last first. by rewrite nth_default ?mul0r //; rewrite -polySpred in gt_i_p. rewrite [q`__]nth_default ?mulr0 //= -subSS -{1}addnS -polySpred //. by rewrite addnC -addnBA ?leq_addr. Qed. Lemma size_proper_mul p q : lead_coef p * lead_coef q != 0 -> size (p * q) = (size p + size q).-1. Proof. apply: contraNeq; rewrite mul_lead_coef eqn_leq size_polyMleq -ltnNge => lt_pq. by rewrite nth_default // -subn1 -(leq_add2l 1) -leq_subLR leq_sub2r. Qed. Lemma lead_coef_proper_mul p q : let c := lead_coef p * lead_coef q in c != 0 -> lead_coef (p * q) = c. Proof. by move=> /= nz_c; rewrite mul_lead_coef -size_proper_mul. Qed. Lemma size_poly_prod_leq (I : finType) (P : pred I) (F : I -> {poly R}) : size (\prod_(i | P i) F i) <= (\sum_(i | P i) size (F i)).+1 - #|P|. Proof. rewrite -sum1_card. elim/big_rec3: _ => [|i n m p _ IHp]; first by rewrite size_poly1. have [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0. rewrite (leq_trans (size_polyMleq _ _)) // subnS -!subn1 leq_sub2r //. rewrite -addnS -addnBA ?leq_add2l // ltnW // -subn_gt0 (leq_trans _ IHp) //. by rewrite polySpred. Qed. Lemma coefCM c p i : (c%:P * p)`_i = c * p`_i. Proof. rewrite coefM big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Lemma coefMC c p i : (p * c%:P)`_i = p`_i * c. Proof. rewrite coefMr big_ord_recl subn0. by rewrite big1 => [|j _]; rewrite coefC !simp. Qed. Lemma polyCM : {morph polyC : a b / a * b}. Proof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefCM !coefC ?simp. Qed. Lemma size_poly_exp_leq p n : size (p ^+ n) <= ((size p).-1 * n).+1. Proof. elim: n => [|n IHn]; first by rewrite size_poly1. have [-> | nzp] := poly0Vpos p; first by rewrite exprS mul0r size_poly0. rewrite exprS (leq_trans (size_polyMleq _ _)) //. by rewrite -{1}(prednK nzp) mulnS -addnS leq_add2l. Qed. End SemiPolynomialTheory. #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyD`")] Notation size_add := size_polyD (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyDl`")] Notation size_addl := size_polyDl (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyMleq`")] Notation size_mul_leq := size_polyMleq (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_poly_prod_leq`")] Notation size_prod_leq := size_poly_prod_leq (only parsing). #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_poly_exp_leq`")] Notation size_exp_leq := size_poly_exp_leq (only parsing). Section PolynomialTheory. Variable R : nzRingType. Implicit Types (a b c x y z : R) (p q r d : {poly R}). Local Notation "c %:P" := (polyC c). Local Notation "\poly_ ( i < n ) E" := (poly n (fun i : nat => E)). (* Zmodule structure for polynomial *) Definition opp_poly_def p := \poly_(i < size p) - p`_i. Fact opp_poly_key : unit. Proof. by []. Qed. Definition opp_poly := locked_with opp_poly_key opp_poly_def. Canonical opp_poly_unlockable := [unlockable fun opp_poly]. Fact coef_opp_poly p i : (opp_poly p)`_i = - p`_i. Proof. rewrite unlock coef_poly /=. by case: leqP => // le_p_i; rewrite nth_default ?oppr0. Qed. Fact add_polyN : left_inverse 0%:P opp_poly (@add_poly _). Proof. move=> p; apply/polyP=> i. by rewrite coef_add_poly coef_opp_poly coefC if_same addNr. Qed. HB.instance Definition _ := GRing.Nmodule_isZmodule.Build (polynomial R) add_polyN. (* Size, leading coef, morphism properties of coef *) Lemma coefN p i : (- p)`_i = - p`_i. Proof. exact: coef_opp_poly. Qed. Lemma coefB p q i : (p - q)`_i = p`_i - q`_i. Proof. by rewrite coefD coefN. Qed. HB.instance Definition _ i := GRing.isZmodMorphism.Build {poly R} R (coefp i) (fun p => (coefB p)^~ i). Lemma coefMn p n i : (p *+ n)`_i = p`_i *+ n. Proof. exact: (raddfMn (coefp i)). Qed. Lemma coefMNn p n i : (p *- n)`_i = p`_i *- n. Proof. by rewrite coefN coefMn. Qed. Lemma coef_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) k : (\sum_(i <- r | P i) F i)`_k = \sum_(i <- r | P i) (F i)`_k. Proof. exact: (raddf_sum (coefp k)). Qed. Lemma polyCN : {morph (@polyC R) : c / - c}. Proof. by move=> c; apply/polyP=> [[|i]]; rewrite coefN !coefC ?oppr0. Qed. Lemma polyCB : {morph (@polyC R) : a b / a - b}. Proof. by move=> a b; rewrite polyCD polyCN. Qed. HB.instance Definition _ := GRing.isZmodMorphism.Build R {poly R} (@polyC _) polyCB. Lemma polyCMn n : {morph (@polyC R) : c / c *+ n}. Proof. exact: raddfMn. Qed. Lemma size_polyN p : size (- p) = size p. Proof. by apply/eqP; rewrite eqn_leq -{3}(opprK p) -[-%R]/opp_poly unlock !size_poly. Qed. Lemma lead_coefN p : lead_coef (- p) = - lead_coef p. Proof. by rewrite /lead_coef size_polyN coefN. Qed. (* Polynomial ring structure. *) Fact polyC_is_monoid_morphism : monoid_morphism (@polyC R). Proof. by split; last apply: polyCM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `polyC_is_monoid_morphism` instead")] Definition polyC_multiplicative := (fun g => (g.2, g.1)) polyC_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build R {poly R} (@polyC R) polyC_is_monoid_morphism. Lemma polyC_exp n : {morph (@polyC R) : c / c ^+ n}. Proof. exact: rmorphXn. Qed. Lemma polyC_natr n : n%:R%:P = n%:R :> {poly R}. Proof. by rewrite rmorph_nat. Qed. Lemma pchar_poly : [pchar {poly R}] =i [pchar R]. Proof. move=> p; rewrite !inE; congr (_ && _). apply/eqP/eqP=> [/(congr1 val) /=|]; last by rewrite -polyC_natr => ->. by rewrite polyseq0 -polyC_natr polyseqC; case: eqP. Qed. Lemma size_Msign p n : size ((-1) ^+ n * p) = size p. Proof. by rewrite -signr_odd; case: (odd n); rewrite ?mul1r// mulN1r size_polyN. Qed. Fact coefp0_is_monoid_morphism : monoid_morphism (coefp 0 : {poly R} -> R). Proof. split=> [|p q]; first by rewrite polyCK. by rewrite [coefp 0 _]coefM big_ord_recl big_ord0 addr0. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `coefp0_is_monoid_morphism` instead")] Definition coefp0_multiplicative := (fun g => (g.2, g.1)) coefp0_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly R} R (coefp 0) coefp0_is_monoid_morphism. (* Algebra structure of polynomials. *) Definition scale_poly_def a (p : {poly R}) := \poly_(i < size p) (a * p`_i). Fact scale_poly_key : unit. Proof. by []. Qed. Definition scale_poly := locked_with scale_poly_key scale_poly_def. Canonical scale_poly_unlockable := [unlockable fun scale_poly]. Fact scale_polyE a p : scale_poly a p = a%:P * p. Proof. apply/polyP=> n; rewrite unlock coef_poly coefCM. by case: leqP => // le_p_n; rewrite nth_default ?mulr0. Qed. Fact scale_polyA a b p : scale_poly a (scale_poly b p) = scale_poly (a * b) p. Proof. by rewrite !scale_polyE mulrA polyCM. Qed. Fact scale_1poly : left_id 1 scale_poly. Proof. by move=> p; rewrite scale_polyE mul1r. Qed. Fact scale_polyDr a : {morph scale_poly a : p q / p + q}. Proof. by move=> p q; rewrite !scale_polyE mulrDr. Qed. Fact scale_polyDl p : {morph scale_poly^~ p : a b / a + b}. Proof. by move=> a b /=; rewrite !scale_polyE raddfD mulrDl. Qed. Fact scale_polyAl a p q : scale_poly a (p * q) = scale_poly a p * q. Proof. by rewrite !scale_polyE mulrA. Qed. HB.instance Definition _ := GRing.Zmodule_isLmodule.Build R (polynomial R) scale_polyA scale_1poly scale_polyDr scale_polyDl. HB.instance Definition _ := GRing.Lmodule_isLalgebra.Build R (polynomial R) scale_polyAl. Lemma mul_polyC a p : a%:P * p = a *: p. Proof. by rewrite -scale_polyE. Qed. Lemma scale_polyC a b : a *: b%:P = (a * b)%:P. Proof. by rewrite -mul_polyC polyCM. Qed. Lemma alg_polyC a : a%:A = a%:P :> {poly R}. Proof. by rewrite -mul_polyC mulr1. Qed. Lemma coefZ a p i : (a *: p)`_i = a * p`_i. Proof. rewrite -[*:%R]/scale_poly unlock coef_poly. by case: leqP => // le_p_n; rewrite nth_default ?mulr0. Qed. Lemma size_scale_leq a p : size (a *: p) <= size p. Proof. by rewrite -[*:%R]/scale_poly unlock size_poly. Qed. HB.instance Definition _ i := GRing.isScalable.Build R {poly R} R *%R (coefp i) (fun a => (coefZ a) ^~ i). HB.instance Definition _ := GRing.Linear.on (coefp 0). (* The indeterminate, at last! *) Definition polyX_def := @Poly R [:: 0; 1]. Fact polyX_key : unit. Proof. by []. Qed. Definition polyX : {poly R} := locked_with polyX_key polyX_def. Canonical polyX_unlockable := [unlockable of polyX]. Local Notation "'X" := polyX. Lemma polyseqX : 'X = [:: 0; 1] :> seq R. Proof. by rewrite unlock !polyseq_cons nil_poly eqxx /= polyseq1. Qed. Lemma size_polyX : size 'X = 2. Proof. by rewrite polyseqX. Qed. Lemma polyX_eq0 : ('X == 0) = false. Proof. by rewrite -size_poly_eq0 size_polyX. Qed. Lemma coefX i : 'X`_i = (i == 1)%:R. Proof. by case: i => [|[|i]]; rewrite polyseqX //= nth_nil. Qed. Lemma lead_coefX : lead_coef 'X = 1. Proof. by rewrite /lead_coef polyseqX. Qed. Lemma commr_polyX p : GRing.comm p 'X. Proof. apply/polyP=> i; rewrite coefMr coefM. by apply: eq_bigr => j _; rewrite coefX commr_nat. Qed. Lemma coefMX p i : (p * 'X)`_i = (if (i == 0)%N then 0 else p`_i.-1). Proof. rewrite coefMr big_ord_recl coefX ?simp. case: i => [|i]; rewrite ?big_ord0 //= big_ord_recl polyseqX subn1 /=. by rewrite big1 ?simp // => j _; rewrite nth_nil !simp. Qed. Lemma coefXM p i : ('X * p)`_i = (if (i == 0)%N then 0 else p`_i.-1). Proof. by rewrite -commr_polyX coefMX. Qed. Lemma cons_poly_def p a : cons_poly a p = p * 'X + a%:P. Proof. apply/polyP=> i; rewrite coef_cons coefD coefMX coefC. by case: ifP; rewrite !simp. Qed. Lemma poly_ind (K : {poly R} -> Type) : K 0 -> (forall p c, K p -> K (p * 'X + c%:P)) -> (forall p, K p). Proof. move=> K0 Kcons p; rewrite -[p]polyseqK. by elim: {p}(p : seq R) => //= p c IHp; rewrite cons_poly_def; apply: Kcons. Qed. Lemma polyseqXaddC a : 'X + a%:P = [:: a; 1] :> seq R. Proof. by rewrite -['X]mul1r -cons_poly_def polyseq_cons polyseq1. Qed. Lemma polyseqXsubC a : 'X - a%:P = [:: - a; 1] :> seq R. Proof. by rewrite -polyCN polyseqXaddC. Qed. Lemma size_XsubC a : size ('X - a%:P) = 2. Proof. by rewrite polyseqXsubC. Qed. Lemma size_XaddC b : size ('X + b%:P) = 2. Proof. by rewrite -[b]opprK rmorphN size_XsubC. Qed. Lemma lead_coefXaddC a : lead_coef ('X + a%:P) = 1. Proof. by rewrite lead_coefE polyseqXaddC. Qed. Lemma lead_coefXsubC a : lead_coef ('X - a%:P) = 1. Proof. by rewrite lead_coefE polyseqXsubC. Qed. Lemma polyXsubC_eq0 a : ('X - a%:P == 0) = false. Proof. by rewrite -nil_poly polyseqXsubC. Qed. Lemma size_MXaddC p c : size (p * 'X + c%:P) = (if (p == 0) && (c == 0) then 0 else (size p).+1). Proof. by rewrite -cons_poly_def size_cons_poly nil_poly. Qed. Lemma polyseqMX p : p != 0 -> p * 'X = 0 :: p :> seq R. Proof. by move=> nz_p; rewrite -[p * _]addr0 -cons_poly_def polyseq_cons nil_poly nz_p. Qed. Lemma size_mulX p : p != 0 -> size (p * 'X) = (size p).+1. Proof. by move/polyseqMX->. Qed. Lemma lead_coefMX p : lead_coef (p * 'X) = lead_coef p. Proof. have [-> | nzp] := eqVneq p 0; first by rewrite mul0r. by rewrite /lead_coef !nth_last polyseqMX. Qed. Lemma size_XmulC a : a != 0 -> size ('X * a%:P) = 2. Proof. by move=> nz_a; rewrite -commr_polyX size_mulX ?polyC_eq0 ?size_polyC nz_a. Qed. Local Notation "''X^' n" := ('X ^+ n). Lemma coefXn n i : 'X^n`_i = (i == n)%:R. Proof. by elim: n i => [|n IHn] [|i]; rewrite ?coef1 // exprS coefXM ?IHn. Qed. Lemma polyseqXn n : 'X^n = rcons (nseq n 0) 1 :> seq R. Proof. elim: n => [|n IHn]; rewrite ?polyseq1 // exprSr. by rewrite polyseqMX -?size_poly_eq0 IHn ?size_rcons. Qed. Lemma size_polyXn n : size 'X^n = n.+1. Proof. by rewrite polyseqXn size_rcons size_nseq. Qed. Lemma commr_polyXn p n : GRing.comm p 'X^n. Proof. exact/commrX/commr_polyX. Qed. Lemma lead_coefXn n : lead_coef 'X^n = 1. Proof. by rewrite /lead_coef nth_last polyseqXn last_rcons. Qed. Lemma lead_coefXnaddC n c : 0 < n -> lead_coef ('X^n + c%:P) = 1. Proof. move=> n_gt0; rewrite lead_coefDl ?lead_coefXn//. by rewrite size_polyC size_polyXn ltnS (leq_trans (leq_b1 _)). Qed. Lemma lead_coefXnsubC n c : 0 < n -> lead_coef ('X^n - c%:P) = 1. Proof. by move=> n_gt0; rewrite -polyCN lead_coefXnaddC. Qed. Lemma size_XnaddC n c : 0 < n -> size ('X^n + c%:P) = n.+1. Proof. by move=> *; rewrite size_polyDl ?size_polyXn// size_polyC; case: eqP. Qed. Lemma size_XnsubC n c : 0 < n -> size ('X^n - c%:P) = n.+1. Proof. by move=> *; rewrite -polyCN size_XnaddC. Qed. Lemma polyseqMXn n p : p != 0 -> p * 'X^n = ncons n 0 p :> seq R. Proof. case: n => [|n] nz_p; first by rewrite mulr1. elim: n => [|n IHn]; first exact: polyseqMX. by rewrite exprSr mulrA polyseqMX -?nil_poly IHn. Qed. Lemma coefMXn n p i : (p * 'X^n)`_i = if i < n then 0 else p`_(i - n). Proof. have [-> | /polyseqMXn->] := eqVneq p 0; last exact: nth_ncons. by rewrite mul0r !coef0 if_same. Qed. Lemma size_mulXn n p : p != 0 -> size (p * 'X^n) = (n + size p)%N. Proof. elim: n p => [p p_neq0| n IH p p_neq0]; first by rewrite mulr1. by rewrite exprS mulrA IH -?size_poly_eq0 size_mulX // addnS. Qed. Lemma coefXnM n p i : ('X^n * p)`_i = if i < n then 0 else p`_(i - n). Proof. by rewrite -commr_polyXn coefMXn. Qed. Lemma coef_sumMXn I (r : seq I) (P : pred I) (p : I -> R) (n : I -> nat) k : (\sum_(i <- r | P i) p i *: 'X^(n i))`_k = \sum_(i <- r | P i && (n i == k)) p i. Proof. rewrite coef_sum big_mkcondr; apply: eq_bigr => i Pi. by rewrite coefZ coefXn mulr_natr mulrb eq_sym. Qed. (* Expansion of a polynomial as an indexed sum *) Lemma poly_def n E : \poly_(i < n) E i = \sum_(i < n) E i *: 'X^i. Proof. by apply/polyP => i; rewrite coef_sumMXn coef_poly big_ord1_eq. Qed. (* Monic predicate *) Definition monic_pred := fun p => lead_coef p == 1. Arguments monic_pred _ /. Definition monic := [qualify p | monic_pred p]. Lemma monicE p : (p \is monic) = (lead_coef p == 1). Proof. by []. Qed. Lemma monicP p : reflect (lead_coef p = 1) (p \is monic). Proof. exact: eqP. Qed. Lemma monic1 : 1 \is monic. Proof. exact/eqP/lead_coef1. Qed. Lemma monicX : 'X \is monic. Proof. exact/eqP/lead_coefX. Qed. Lemma monicXn n : 'X^n \is monic. Proof. exact/eqP/lead_coefXn. Qed. Lemma monic_neq0 p : p \is monic -> p != 0. Proof. by rewrite -lead_coef_eq0 => /eqP->; apply: oner_neq0. Qed. Lemma lead_coef_monicM p q : p \is monic -> lead_coef (p * q) = lead_coef q. Proof. have [-> | nz_q] := eqVneq q 0; first by rewrite mulr0. by move/monicP=> mon_p; rewrite lead_coef_proper_mul mon_p mul1r ?lead_coef_eq0. Qed. Lemma lead_coef_Mmonic p q : q \is monic -> lead_coef (p * q) = lead_coef p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r. by move/monicP=> mon_q; rewrite lead_coef_proper_mul mon_q mulr1 ?lead_coef_eq0. Qed. Lemma size_monicM p q : p \is monic -> q != 0 -> size (p * q) = (size p + size q).-1. Proof. move/monicP=> mon_p nz_q. by rewrite size_proper_mul // mon_p mul1r lead_coef_eq0. Qed. Lemma size_Mmonic p q : p != 0 -> q \is monic -> size (p * q) = (size p + size q).-1. Proof. move=> nz_p /monicP mon_q. by rewrite size_proper_mul // mon_q mulr1 lead_coef_eq0. Qed. Lemma monicMl p q : p \is monic -> (p * q \is monic) = (q \is monic). Proof. by move=> mon_p; rewrite !monicE lead_coef_monicM. Qed. Lemma monicMr p q : q \is monic -> (p * q \is monic) = (p \is monic). Proof. by move=> mon_q; rewrite !monicE lead_coef_Mmonic. Qed. Fact monic_mulr_closed : mulr_closed monic. Proof. by split=> [|p q mon_p]; rewrite (monic1, monicMl). Qed. HB.instance Definition _ := GRing.isMulClosed.Build {poly R} monic_pred monic_mulr_closed. Lemma monic_exp p n : p \is monic -> p ^+ n \is monic. Proof. exact: rpredX. Qed. Lemma monic_prod I rI (P : pred I) (F : I -> {poly R}): (forall i, P i -> F i \is monic) -> \prod_(i <- rI | P i) F i \is monic. Proof. exact: rpred_prod. Qed. Lemma monicXaddC c : 'X + c%:P \is monic. Proof. exact/eqP/lead_coefXaddC. Qed. Lemma monicXsubC c : 'X - c%:P \is monic. Proof. exact/eqP/lead_coefXsubC. Qed. Lemma monic_prod_XsubC I rI (P : pred I) (F : I -> R) : \prod_(i <- rI | P i) ('X - (F i)%:P) \is monic. Proof. by apply: monic_prod => i _; apply: monicXsubC. Qed. Lemma lead_coef_prod_XsubC I rI (P : pred I) (F : I -> R) : lead_coef (\prod_(i <- rI | P i) ('X - (F i)%:P)) = 1. Proof. exact/eqP/monic_prod_XsubC. Qed. Lemma size_prod_XsubC I rI (F : I -> R) : size (\prod_(i <- rI) ('X - (F i)%:P)) = (size rI).+1. Proof. elim: rI => [|i r /= <-]; rewrite ?big_nil ?size_poly1 // big_cons. rewrite size_monicM ?monicXsubC ?monic_neq0 ?monic_prod_XsubC //. by rewrite size_XsubC. Qed. Lemma size_exp_XsubC n a : size (('X - a%:P) ^+ n) = n.+1. Proof. rewrite -[n]card_ord -prodr_const -big_filter size_prod_XsubC. by have [e _ _ [_ ->]] := big_enumP. Qed. Lemma monicXnaddC n c : 0 < n -> 'X^n + c%:P \is monic. Proof. by move=> n_gt0; rewrite monicE lead_coefXnaddC. Qed. Lemma monicXnsubC n c : 0 < n -> 'X^n - c%:P \is monic. Proof. by move=> n_gt0; rewrite monicE lead_coefXnsubC. Qed. (* Some facts about regular elements. *) Lemma lreg_lead p : GRing.lreg (lead_coef p) -> GRing.lreg p. Proof. move/mulrI_eq0=> reg_p; apply: mulrI0_lreg => q /eqP; apply: contraTeq => nz_q. by rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0. Qed. Lemma rreg_lead p : GRing.rreg (lead_coef p) -> GRing.rreg p. Proof. move/mulIr_eq0=> reg_p; apply: mulIr0_rreg => q /eqP; apply: contraTeq => nz_q. by rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0. Qed. Lemma lreg_lead0 p : GRing.lreg (lead_coef p) -> p != 0. Proof. by move/lreg_neq0; rewrite lead_coef_eq0. Qed. Lemma rreg_lead0 p : GRing.rreg (lead_coef p) -> p != 0. Proof. by move/rreg_neq0; rewrite lead_coef_eq0. Qed. Lemma lreg_size c p : GRing.lreg c -> size (c *: p) = size p. Proof. move=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite scaler0. rewrite -mul_polyC size_proper_mul; first by rewrite size_polyC lreg_neq0. by rewrite lead_coefC mulrI_eq0 ?lead_coef_eq0. Qed. Lemma lreg_polyZ_eq0 c p : GRing.lreg c -> (c *: p == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /lreg_size->. Qed. Lemma lead_coef_lreg c p : GRing.lreg c -> lead_coef (c *: p) = c * lead_coef p. Proof. by move=> reg_c; rewrite !lead_coefE coefZ lreg_size. Qed. Lemma rreg_size c p : GRing.rreg c -> size (p * c%:P) = size p. Proof. move=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r. rewrite size_proper_mul; first by rewrite size_polyC rreg_neq0 ?addn1. by rewrite lead_coefC mulIr_eq0 ?lead_coef_eq0. Qed. Lemma rreg_polyMC_eq0 c p : GRing.rreg c -> (p * c%:P == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /rreg_size->. Qed. Lemma rreg_div0 q r d : GRing.rreg (lead_coef d) -> size r < size d -> (q * d + r == 0) = (q == 0) && (r == 0). Proof. move=> reg_d lt_r_d; rewrite addrC addr_eq0. have [-> | nz_q] := eqVneq q 0; first by rewrite mul0r oppr0. apply: contraTF lt_r_d => /eqP->; rewrite -leqNgt size_polyN. rewrite size_proper_mul ?mulIr_eq0 ?lead_coef_eq0 //. by rewrite (polySpred nz_q) leq_addl. Qed. Lemma monic_comreg p : p \is monic -> GRing.comm p (lead_coef p)%:P /\ GRing.rreg (lead_coef p). Proof. by move/monicP->; split; [apply: commr1 | apply: rreg1]. Qed. Lemma monic_lreg p : p \is monic -> GRing.lreg p. Proof. by move=> /eqP lp1; apply/lreg_lead; rewrite lp1; apply/lreg1. Qed. Lemma monic_rreg p : p \is monic -> GRing.rreg p. Proof. by move=> /eqP lp1; apply/rreg_lead; rewrite lp1; apply/rreg1. Qed. (* Horner evaluation of polynomials *) Implicit Types s rs : seq R. Fixpoint horner_rec s x := if s is a :: s' then horner_rec s' x * x + a else 0. Definition horner p := horner_rec p. Local Notation "p .[ x ]" := (horner p x) : ring_scope. Lemma horner0 x : (0 : {poly R}).[x] = 0. Proof. by rewrite /horner polyseq0. Qed. Lemma hornerC c x : (c%:P).[x] = c. Proof. by rewrite /horner polyseqC; case: eqP; rewrite /= ?simp. Qed. Lemma hornerX x : 'X.[x] = x. Proof. by rewrite /horner polyseqX /= !simp. Qed. Lemma horner_cons p c x : (cons_poly c p).[x] = p.[x] * x + c. Proof. rewrite /horner polyseq_cons; case: nilP => //= ->. by rewrite !simp -/(_.[x]) hornerC. Qed. Lemma horner_coef0 p : p.[0] = p`_0. Proof. by rewrite /horner; case: (p : seq R) => //= c p'; rewrite !simp. Qed. Lemma hornerMXaddC p c x : (p * 'X + c%:P).[x] = p.[x] * x + c. Proof. by rewrite -cons_poly_def horner_cons. Qed. Lemma hornerMX p x : (p * 'X).[x] = p.[x] * x. Proof. by rewrite -[p * 'X]addr0 hornerMXaddC addr0. Qed. Lemma horner_Poly s x : (Poly s).[x] = horner_rec s x. Proof. by elim: s => [|a s /= <-]; rewrite (horner0, horner_cons). Qed. Lemma horner_coef p x : p.[x] = \sum_(i < size p) p`_i * x ^+ i. Proof. rewrite /horner. elim: {p}(p : seq R) => /= [|a s ->]; first by rewrite big_ord0. rewrite big_ord_recl simp addrC big_distrl /=. by congr (_ + _); apply: eq_bigr => i _; rewrite -mulrA exprSr. Qed. Lemma horner_coef_wide n p x : size p <= n -> p.[x] = \sum_(i < n) p`_i * x ^+ i. Proof. move=> le_p_n. rewrite horner_coef (big_ord_widen n (fun i => p`_i * x ^+ i)) // big_mkcond. by apply: eq_bigr => i _; case: ltnP => // le_p_i; rewrite nth_default ?simp. Qed. Lemma horner_poly n E x : (\poly_(i < n) E i).[x] = \sum_(i < n) E i * x ^+ i. Proof. rewrite (@horner_coef_wide n) ?size_poly //. by apply: eq_bigr => i _; rewrite coef_poly ltn_ord. Qed. Lemma hornerN p x : (- p).[x] = - p.[x]. Proof. rewrite -[-%R]/opp_poly unlock horner_poly horner_coef -sumrN /=. by apply: eq_bigr => i _; rewrite mulNr. Qed. Lemma hornerD p q x : (p + q).[x] = p.[x] + q.[x]. Proof. rewrite -[+%R]/(@add_poly R) unlock horner_poly; set m := maxn _ _. rewrite !(@horner_coef_wide m) ?leq_max ?leqnn ?orbT // -big_split /=. by apply: eq_bigr => i _; rewrite -mulrDl. Qed. Lemma hornerXsubC a x : ('X - a%:P).[x] = x - a. Proof. by rewrite hornerD hornerN hornerC hornerX. Qed. Lemma horner_sum I (r : seq I) (P : pred I) F x : (\sum_(i <- r | P i) F i).[x] = \sum_(i <- r | P i) (F i).[x]. Proof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (horner0, hornerD). Qed. Lemma hornerCM a p x : (a%:P * p).[x] = a * p.[x]. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(mulr0, horner0). by rewrite mulrDr mulrA -polyCM !hornerMXaddC IHp mulrDr mulrA. Qed. Lemma hornerZ c p x : (c *: p).[x] = c * p.[x]. Proof. by rewrite -mul_polyC hornerCM. Qed. Lemma hornerMn n p x : (p *+ n).[x] = p.[x] *+ n. Proof. by elim: n => [| n IHn]; rewrite ?horner0 // !mulrS hornerD IHn. Qed. Definition comm_coef p x := forall i, p`_i * x = x * p`_i. Definition comm_poly p x := x * p.[x] = p.[x] * x. Lemma comm_coef_poly p x : comm_coef p x -> comm_poly p x. Proof. move=> cpx; rewrite /comm_poly !horner_coef big_distrl big_distrr /=. by apply: eq_bigr => i _; rewrite /= mulrA -cpx -!mulrA commrX. Qed. Lemma comm_poly0 x : comm_poly 0 x. Proof. by rewrite /comm_poly !horner0 !simp. Qed. Lemma comm_poly1 x : comm_poly 1 x. Proof. by rewrite /comm_poly !hornerC !simp. Qed. Lemma comm_polyX x : comm_poly 'X x. Proof. by rewrite /comm_poly !hornerX. Qed. Lemma comm_polyD p q x: comm_poly p x -> comm_poly q x -> comm_poly (p + q) x. Proof. by rewrite /comm_poly hornerD mulrDr mulrDl => -> ->. Qed. Lemma commr_horner a b p : GRing.comm a b -> comm_coef p a -> GRing.comm a p.[b]. Proof. move=> cab cpa; rewrite horner_coef; apply: commr_sum => i _. by apply: commrM => //; apply: commrX. Qed. Lemma hornerM_comm p q x : comm_poly q x -> (p * q).[x] = p.[x] * q.[x]. Proof. move=> comm_qx. elim/poly_ind: p => [|p c IHp]; first by rewrite !(simp, horner0). rewrite mulrDl hornerD hornerCM -mulrA -commr_polyX mulrA hornerMX. by rewrite {}IHp -mulrA -comm_qx mulrA -mulrDl hornerMXaddC. Qed. Lemma comm_polyM p q x: comm_poly p x -> comm_poly q x -> comm_poly (p * q) x. Proof. by move=> px qx; rewrite /comm_poly hornerM_comm// mulrA px -mulrA qx mulrA. Qed. Lemma horner_exp_comm p x n : comm_poly p x -> (p ^+ n).[x] = p.[x] ^+ n. Proof. move=> comm_px; elim: n => [|n IHn]; first by rewrite hornerC. by rewrite !exprSr -IHn hornerM_comm. Qed. Lemma comm_poly_exp p n x: comm_poly p x -> comm_poly (p ^+ n) x. Proof. by move=> px; rewrite /comm_poly !horner_exp_comm// commrX. Qed. Lemma hornerXn x n : ('X^n).[x] = x ^+ n. Proof. by rewrite horner_exp_comm /comm_poly hornerX. Qed. Definition hornerE_comm := (hornerD, hornerN, hornerX, hornerC, horner_cons, simp, hornerCM, hornerZ, (fun p x => hornerM_comm p (comm_polyX x))). Definition root p : pred R := fun x => p.[x] == 0. Lemma mem_root p x : x \in root p = (p.[x] == 0). Proof. by []. Qed. Lemma rootE p x : (root p x = (p.[x] == 0)) * ((x \in root p) = (p.[x] == 0)). Proof. by []. Qed. Lemma rootP p x : reflect (p.[x] = 0) (root p x). Proof. exact: eqP. Qed. Lemma rootPt p x : reflect (p.[x] == 0) (root p x). Proof. exact: idP. Qed. Lemma rootPf p x : reflect ((p.[x] == 0) = false) (~~ root p x). Proof. exact: negPf. Qed. Lemma rootC a x : root a%:P x = (a == 0). Proof. by rewrite rootE hornerC. Qed. Lemma root0 x : root 0 x. Proof. by rewrite rootC. Qed. Lemma root1 x : ~~ root 1 x. Proof. by rewrite rootC oner_eq0. Qed. Lemma rootX x : root 'X x = (x == 0). Proof. by rewrite rootE hornerX. Qed. Lemma rootN p x : root (- p) x = root p x. Proof. by rewrite rootE hornerN oppr_eq0. Qed. Lemma root_size_gt1 a p : p != 0 -> root p a -> 1 < size p. Proof. rewrite ltnNge => nz_p; apply: contraL => /size1_polyC Dp. by rewrite Dp rootC -polyC_eq0 -Dp. Qed. Lemma root_XsubC a x : root ('X - a%:P) x = (x == a). Proof. by rewrite rootE hornerXsubC subr_eq0. Qed. Lemma root_XaddC a x : root ('X + a%:P) x = (x == - a). Proof. by rewrite -root_XsubC rmorphN opprK. Qed. Theorem factor_theorem p a : reflect (exists q, p = q * ('X - a%:P)) (root p a). Proof. apply: (iffP eqP) => [pa0 | [q ->]]; last first. by rewrite hornerM_comm /comm_poly hornerXsubC subrr ?simp. exists (\poly_(i < size p) horner_rec (drop i.+1 p) a). apply/polyP=> i; rewrite mulrBr coefB coefMX coefMC !coef_poly. apply: canRL (addrK _) _; rewrite addrC; have [le_p_i | lt_i_p] := leqP. rewrite nth_default // !simp drop_oversize ?if_same //. exact: leq_trans (leqSpred _). case: i => [|i] in lt_i_p *; last by rewrite ltnW // (drop_nth 0 lt_i_p). by rewrite drop1 /= -{}pa0 /horner; case: (p : seq R) lt_i_p. Qed. Lemma multiplicity_XsubC p a : {m | exists2 q, (p != 0) ==> ~~ root q a & p = q * ('X - a%:P) ^+ m}. Proof. have [n le_p_n] := ubnP (size p); elim: n => // n IHn in p le_p_n *. have [-> | nz_p /=] := eqVneq p 0; first by exists 0, 0; rewrite ?mul0r. have [/sig_eqW[p1 Dp] | nz_pa] := altP (factor_theorem p a); last first. by exists 0%N, p; rewrite ?mulr1. have nz_p1: p1 != 0 by apply: contraNneq nz_p => p1_0; rewrite Dp p1_0 mul0r. have /IHn[m /sig2_eqW[q nz_qa Dp1]]: size p1 < n. by rewrite Dp size_Mmonic ?monicXsubC // size_XsubC addn2 in le_p_n. by exists m.+1, q; [rewrite nz_p1 in nz_qa | rewrite exprSr mulrA -Dp1]. Qed. (* Roots of unity. *) #[deprecated(since="mathcomp 2.3.0",note="Use size_XnsubC instead.")] Lemma size_Xn_sub_1 n : n > 0 -> size ('X^n - 1 : {poly R}) = n.+1. Proof. exact/size_XnsubC. Qed. #[deprecated(since="mathcomp 2.3.0'",note="Use monicXnsubC instead.")] Lemma monic_Xn_sub_1 n : n > 0 -> 'X^n - 1 \is monic. Proof. exact/monicXnsubC. Qed. Definition root_of_unity n : pred R := root ('X^n - 1). Local Notation "n .-unity_root" := (root_of_unity n) : ring_scope. Lemma unity_rootE n z : n.-unity_root z = (z ^+ n == 1). Proof. by rewrite /root_of_unity rootE hornerD hornerN hornerXn hornerC subr_eq0. Qed. Lemma unity_rootP n z : reflect (z ^+ n = 1) (n.-unity_root z). Proof. by rewrite unity_rootE; apply: eqP. Qed. Definition primitive_root_of_unity n z := (n > 0) && [forall i : 'I_n, i.+1.-unity_root z == (i.+1 == n)]. Local Notation "n .-primitive_root" := (primitive_root_of_unity n) : ring_scope. Lemma prim_order_exists n z : n > 0 -> z ^+ n = 1 -> {m | m.-primitive_root z & (m %| n)}. Proof. move=> n_gt0 zn1. have: exists m, (m > 0) && (z ^+ m == 1) by exists n; rewrite n_gt0 /= zn1. case/ex_minnP=> m /andP[m_gt0 /eqP zm1] m_min. exists m. apply/andP; split=> //; apply/eqfunP=> [[i]] /=. rewrite leq_eqVlt unity_rootE. case: eqP => [-> _ | _]; first by rewrite zm1 eqxx. by apply: contraTF => zi1; rewrite -leqNgt m_min. have: n %% m < m by rewrite ltn_mod. apply: contraLR; rewrite -lt0n -leqNgt => nm_gt0; apply: m_min. by rewrite nm_gt0 /= expr_mod ?zn1. Qed. Section OnePrimitive. Variables (n : nat) (z : R). Hypothesis prim_z : n.-primitive_root z. Lemma prim_order_gt0 : n > 0. Proof. by case/andP: prim_z. Qed. Let n_gt0 := prim_order_gt0. Lemma prim_expr_order : z ^+ n = 1. Proof. case/andP: prim_z => _; rewrite -(prednK n_gt0) => /forallP/(_ ord_max). by rewrite unity_rootE eqxx eqb_id => /eqP. Qed. Lemma prim_expr_mod i : z ^+ (i %% n) = z ^+ i. Proof. exact: expr_mod prim_expr_order. Qed. Lemma prim_order_dvd i : (n %| i) = (z ^+ i == 1). Proof. move: n_gt0; rewrite -prim_expr_mod /dvdn -(ltn_mod i). case: {i}(i %% n)%N => [|i] lt_i; first by rewrite !eqxx. case/andP: prim_z => _ /forallP/(_ (Ordinal (ltnW lt_i)))/eqP. by rewrite unity_rootE eqn_leq andbC leqNgt lt_i. Qed. Lemma eq_prim_root_expr i j : (z ^+ i == z ^+ j) = (i == j %[mod n]). Proof. wlog le_ji: i j / j <= i. move=> IH; case: (leqP j i) => [|/ltnW] /IH //. by rewrite eq_sym (eq_sym (j %% n)%N). rewrite -{1}(subnKC le_ji) exprD -prim_expr_mod eqn_mod_dvd //. rewrite prim_order_dvd; apply/eqP/eqP=> [|->]; last by rewrite mulr1. move/(congr1 ( *%R (z ^+ (n - j %% n)))); rewrite mulrA -exprD. by rewrite subnK ?prim_expr_order ?mul1r // ltnW ?ltn_mod. Qed. Lemma exp_prim_root k : (n %/ gcdn k n).-primitive_root (z ^+ k). Proof. set d := gcdn k n; have d_gt0: (0 < d)%N by rewrite gcdn_gt0 orbC n_gt0. have [d_dv_k d_dv_n]: (d %| k /\ d %| n)%N by rewrite dvdn_gcdl dvdn_gcdr. set q := (n %/ d)%N; rewrite /q.-primitive_root ltn_divRL // n_gt0. apply/forallP=> i; rewrite unity_rootE -exprM -prim_order_dvd. rewrite -(divnK d_dv_n) -/q -(divnK d_dv_k) mulnAC dvdn_pmul2r //. apply/eqP; apply/idP/idP=> [|/eqP->]; last by rewrite dvdn_mull. rewrite Gauss_dvdr; first by rewrite eqn_leq ltn_ord; apply: dvdn_leq. by rewrite /coprime gcdnC -(eqn_pmul2r d_gt0) mul1n muln_gcdl !divnK. Qed. Lemma dvdn_prim_root m : (m %| n)%N -> m.-primitive_root (z ^+ (n %/ m)). Proof. set k := (n %/ m)%N => m_dv_n; rewrite -{1}(mulKn m n_gt0) -divnA // -/k. by rewrite -{1}(@gcdn_idPl k n _) ?exp_prim_root // -(divnK m_dv_n) dvdn_mulr. Qed. Lemma prim_root_eq0 : (z == 0) = (n == 0%N). Proof. rewrite gtn_eqF//; apply/eqP => z0; have /esym/eqP := prim_expr_order. by rewrite z0 expr0n gtn_eqF//= oner_eq0. Qed. End OnePrimitive. Lemma prim_root_exp_coprime n z k : n.-primitive_root z -> n.-primitive_root (z ^+ k) = coprime k n. Proof. move=> prim_z; have n_gt0 := prim_order_gt0 prim_z. apply/idP/idP=> [prim_zk | co_k_n]. set d := gcdn k n; have dv_d_n: (d %| n)%N := dvdn_gcdr _ _. rewrite /coprime -/d -(eqn_pmul2r n_gt0) mul1n -{2}(gcdnMl n d). rewrite -{2}(divnK dv_d_n) (mulnC _ d) -muln_gcdr (gcdn_idPr _) //. rewrite (prim_order_dvd prim_zk) -exprM -(prim_order_dvd prim_z). by rewrite muln_divCA_gcd dvdn_mulr. have zkn_1: z ^+ k ^+ n = 1 by rewrite exprAC (prim_expr_order prim_z) expr1n. have{zkn_1} [m prim_zk dv_m_n]:= prim_order_exists n_gt0 zkn_1. suffices /eqP <-: m == n by []. rewrite eqn_dvd dv_m_n -(@Gauss_dvdr n k m) 1?coprime_sym //=. by rewrite (prim_order_dvd prim_z) exprM (prim_expr_order prim_zk). Qed. (* Lifting a ring predicate to polynomials. *) Implicit Type S : {pred R}. Definition polyOver_pred S := fun p : {poly R} => all (mem S) p. Arguments polyOver_pred _ _ /. Definition polyOver S := [qualify a p | polyOver_pred S p]. Lemma polyOverS (S1 S2 : {pred R}) : {subset S1 <= S2} -> {subset polyOver S1 <= polyOver S2}. Proof. by move=> sS12 p /(all_nthP 0)S1p; apply/(all_nthP 0)=> i /S1p; apply: sS12. Qed. Lemma polyOver0 S : 0 \is a polyOver S. Proof. by rewrite qualifE /= polyseq0. Qed. Lemma polyOver_poly S n E : (forall i, i < n -> E i \in S) -> \poly_(i < n) E i \is a polyOver S. Proof. move=> S_E; apply/(all_nthP 0)=> i lt_i_p /=; rewrite coef_poly. by case: ifP => [/S_E// | /idP[]]; apply: leq_trans lt_i_p (size_poly n E). Qed. Section PolyOverAdd. Variable S : addrClosed R. Lemma polyOverP {p} : reflect (forall i, p`_i \in S) (p \in polyOver S). Proof. apply: (iffP (all_nthP 0)) => [Sp i | Sp i _]; last exact: Sp. by have [/Sp // | /(nth_default 0)->] := ltnP i (size p); apply: rpred0. Qed. Lemma polyOverC c : (c%:P \in polyOver S) = (c \in S). Proof. by rewrite [LHS]qualifE /= polyseqC; case: eqP => [->|] /=; rewrite ?andbT ?rpred0. Qed. Fact polyOver_addr_closed : addr_closed (polyOver S). Proof. split=> [|p q Sp Sq]; first exact: polyOver0. by apply/polyOverP=> i; rewrite coefD rpredD ?(polyOverP _). Qed. HB.instance Definition _ := GRing.isAddClosed.Build {poly R} (polyOver_pred S) polyOver_addr_closed. End PolyOverAdd. Section PolyOverSemiRing2. Variable S : semiring2Closed R. Lemma polyOver_mulr_2closed : GRing.mulr_2closed (polyOver S). Proof. move=> p q /polyOverP Sp /polyOverP Sq; apply/polyOverP=> i. by rewrite coefM rpred_sum // => j _; rewrite rpredM. Qed. HB.instance Definition _ := GRing.isMul2Closed.Build {poly R} (polyOver_pred S) polyOver_mulr_2closed. End PolyOverSemiRing2. Fact polyOverNr (zmodS : zmodClosed R) : oppr_closed (polyOver zmodS). Proof. by move=> p /polyOverP Sp; apply/polyOverP=> i; rewrite coefN rpredN. Qed. HB.instance Definition _ (zmodS : zmodClosed R) := GRing.isOppClosed.Build {poly R} (polyOver_pred zmodS) (@polyOverNr _). Section PolyOverSemiring. Variable S : semiringClosed R. Fact polyOver_mul1_closed : 1 \in (polyOver S). Proof. by rewrite polyOverC rpred1. Qed. HB.instance Definition _ := GRing.isMul1Closed.Build {poly R} (polyOver_pred S) polyOver_mul1_closed. Lemma polyOverZ : {in S & polyOver S, forall c p, c *: p \is a polyOver S}. Proof. by move=> c p Sc /polyOverP Sp; apply/polyOverP=> i; rewrite coefZ rpredM ?Sp. Qed. Lemma polyOverX : 'X \in polyOver S. Proof. by rewrite qualifE /= polyseqX /= rpred0 rpred1. Qed. Lemma polyOverXn n : 'X^n \in polyOver S. Proof. by rewrite rpredX// polyOverX. Qed. Lemma rpred_horner : {in polyOver S & S, forall p x, p.[x] \in S}. Proof. move=> p x /polyOverP Sp Sx; rewrite horner_coef rpred_sum // => i _. by rewrite rpredM ?rpredX. Qed. End PolyOverSemiring. Section PolyOverRing. Variable S : subringClosed R. HB.instance Definition _ := GRing.MulClosed.on (polyOver_pred S). Lemma polyOverXaddC c : ('X + c%:P \in polyOver S) = (c \in S). Proof. by rewrite rpredDl ?polyOverX ?polyOverC. Qed. Lemma polyOverXnaddC n c : ('X^n + c%:P \is a polyOver S) = (c \in S). Proof. by rewrite rpredDl ?polyOverXn// ?polyOverC. Qed. Lemma polyOverXsubC c : ('X - c%:P \in polyOver S) = (c \in S). Proof. by rewrite rpredBl ?polyOverX ?polyOverC. Qed. Lemma polyOverXnsubC n c : ('X^n - c%:P \is a polyOver S) = (c \in S). Proof. by rewrite rpredBl ?polyOverXn// ?polyOverC. Qed. End PolyOverRing. (* Single derivative. *) Definition deriv p := \poly_(i < (size p).-1) (p`_i.+1 *+ i.+1). Local Notation "a ^` ()" := (deriv a). Lemma coef_deriv p i : p^`()`_i = p`_i.+1 *+ i.+1. Proof. rewrite coef_poly -subn1 ltn_subRL. by case: leqP => // /(nth_default 0) ->; rewrite mul0rn. Qed. Lemma polyOver_deriv (ringS : semiringClosed R) : {in polyOver ringS, forall p, p^`() \is a polyOver ringS}. Proof. by move=> p /polyOverP Kp; apply/polyOverP=> i; rewrite coef_deriv rpredMn ?Kp. Qed. Lemma derivC c : c%:P^`() = 0. Proof. by apply/polyP=> i; rewrite coef_deriv coef0 coefC mul0rn. Qed. Lemma derivX : ('X)^`() = 1. Proof. by apply/polyP=> [[|i]]; rewrite coef_deriv coef1 coefX ?mul0rn. Qed. Lemma derivXn n : ('X^n)^`() = 'X^(n.-1) *+ n. Proof. case: n => [|n]; first exact: derivC. apply/polyP=> i; rewrite coef_deriv coefMn !coefXn eqSS. by case: eqP => [-> // | _]; rewrite !mul0rn. Qed. Fact deriv_is_linear : linear deriv. Proof. move=> k p q; apply/polyP=> i. by rewrite !(coef_deriv, coefD, coefZ) mulrnDl mulrnAr. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ deriv (GRing.semilinear_linear deriv_is_linear). Lemma deriv0 : 0^`() = 0. Proof. exact: linear0. Qed. Lemma derivD : {morph deriv : p q / p + q}. Proof. exact: linearD. Qed. Lemma derivN : {morph deriv : p / - p}. Proof. exact: linearN. Qed. Lemma derivB : {morph deriv : p q / p - q}. Proof. exact: linearB. Qed. Lemma derivXsubC (a : R) : ('X - a%:P)^`() = 1. Proof. by rewrite derivB derivX derivC subr0. Qed. Lemma derivMn n p : (p *+ n)^`() = p^`() *+ n. Proof. exact: linearMn. Qed. Lemma derivMNn n p : (p *- n)^`() = p^`() *- n. Proof. exact: linearMNn. Qed. Lemma derivZ c p : (c *: p)^`() = c *: p^`(). Proof. exact: linearZ. Qed. Lemma deriv_mulC c p : (c%:P * p)^`() = c%:P * p^`(). Proof. by rewrite !mul_polyC derivZ. Qed. Lemma derivMXaddC p c : (p * 'X + c%:P)^`() = p + p^`() * 'X. Proof. apply/polyP=> i; rewrite raddfD /= derivC addr0 coefD !(coefMX, coef_deriv). by case: i; rewrite ?addr0. Qed. Lemma derivM p q : (p * q)^`() = p^`() * q + p * q^`(). Proof. elim/poly_ind: p => [|p b IHp]; first by rewrite !(mul0r, add0r, derivC). rewrite mulrDl -mulrA -commr_polyX mulrA -[_ * 'X]addr0 raddfD /= !derivMXaddC. by rewrite deriv_mulC IHp !mulrDl -!mulrA !commr_polyX !addrA. Qed. Definition derivE := Eval lazy beta delta [morphism_2 morphism_1] in (derivZ, deriv_mulC, derivC, derivX, derivMXaddC, derivXsubC, derivM, derivB, derivD, derivN, derivXn, derivM, derivMn). (* Iterated derivative. *) Definition derivn n p := iter n deriv p. Local Notation "a ^` ( n )" := (derivn n a) : ring_scope. Lemma derivn0 p : p^`(0) = p. Proof. by []. Qed. Lemma derivn1 p : p^`(1) = p^`(). Proof. by []. Qed. Lemma derivnS p n : p^`(n.+1) = p^`(n)^`(). Proof. by []. Qed. Lemma derivSn p n : p^`(n.+1) = p^`()^`(n). Proof. exact: iterSr. Qed. Lemma coef_derivn n p i : p^`(n)`_i = p`_(n + i) *+ (n + i) ^_ n. Proof. elim: n i => [|n IHn] i; first by rewrite ffactn0 mulr1n. by rewrite derivnS coef_deriv IHn -mulrnA ffactnSr addSnnS addKn. Qed. Lemma polyOver_derivn (ringS : semiringClosed R) : {in polyOver ringS, forall p n, p^`(n) \is a polyOver ringS}. Proof. move=> p /polyOverP Kp /= n; apply/polyOverP=> i. by rewrite coef_derivn rpredMn. Qed. Fact derivn_is_linear n : linear (derivn n). Proof. by elim: n => // n IHn a p q; rewrite derivnS IHn linearP. Qed. HB.instance Definition _ n := GRing.isSemilinear.Build R {poly R} {poly R} _ (derivn n) (GRing.semilinear_linear (derivn_is_linear n)). Lemma derivnC c n : c%:P^`(n) = if n == 0 then c%:P else 0. Proof. by case: n => // n; rewrite derivSn derivC linear0. Qed. Lemma derivnD n : {morph derivn n : p q / p + q}. Proof. exact: linearD. Qed. Lemma derivnB n : {morph derivn n : p q / p - q}. Proof. exact: linearB. Qed. Lemma derivnMn n m p : (p *+ m)^`(n) = p^`(n) *+ m. Proof. exact: linearMn. Qed. Lemma derivnMNn n m p : (p *- m)^`(n) = p^`(n) *- m. Proof. exact: linearMNn. Qed. Lemma derivnN n : {morph derivn n : p / - p}. Proof. exact: linearN. Qed. Lemma derivnZ n : scalable (derivn n). Proof. exact: linearZZ. Qed. Lemma derivnXn m n : ('X^m)^`(n) = 'X^(m - n) *+ m ^_ n. Proof. apply/polyP=>i; rewrite coef_derivn coefMn !coefXn. case: (ltnP m n) => [lt_m_n | le_m_n]. by rewrite eqn_leq leqNgt ltn_addr // mul0rn ffact_small. by rewrite -{1 3}(subnKC le_m_n) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn. Qed. Lemma derivnMXaddC n p c : (p * 'X + c%:P)^`(n.+1) = p^`(n) *+ n.+1 + p^`(n.+1) * 'X. Proof. elim: n => [|n IHn]; first by rewrite derivn1 derivMXaddC. rewrite derivnS IHn derivD derivM derivX mulr1 derivMn -!derivnS. by rewrite addrA addrAC -mulrSr. Qed. Lemma derivn_poly0 p n : size p <= n -> p^`(n) = 0. Proof. move=> le_p_n; apply/polyP=> i; rewrite coef_derivn. rewrite nth_default; first by rewrite mul0rn coef0. exact/(leq_trans le_p_n)/leq_addr. Qed. Lemma lt_size_deriv (p : {poly R}) : p != 0 -> size p^`() < size p. Proof. by move=> /polySpred->; apply: size_poly. Qed. (* A normalising version of derivation to get the division by n! in Taylor *) Definition nderivn n p := \poly_(i < size p - n) (p`_(n + i) *+ 'C(n + i, n)). Local Notation "a ^`N ( n )" := (nderivn n a) : ring_scope. Lemma coef_nderivn n p i : p^`N(n)`_i = p`_(n + i) *+ 'C(n + i, n). Proof. rewrite coef_poly ltn_subRL; case: leqP => // le_p_ni. by rewrite nth_default ?mul0rn. Qed. (* Here is the division by n! *) Lemma nderivn_def n p : p^`(n) = p^`N(n) *+ n`!. Proof. by apply/polyP=> i; rewrite coefMn coef_nderivn coef_derivn -mulrnA bin_ffact. Qed. Lemma polyOver_nderivn (ringS : semiringClosed R) : {in polyOver ringS, forall p n, p^`N(n) \in polyOver ringS}. Proof. move=> p /polyOverP Sp /= n; apply/polyOverP=> i. by rewrite coef_nderivn rpredMn. Qed. Lemma nderivn0 p : p^`N(0) = p. Proof. by rewrite -[p^`N(0)](nderivn_def 0). Qed. Lemma nderivn1 p : p^`N(1) = p^`(). Proof. by rewrite -[p^`N(1)](nderivn_def 1). Qed. Lemma nderivnC c n : (c%:P)^`N(n) = if n == 0 then c%:P else 0. Proof. apply/polyP=> i; rewrite coef_nderivn. by case: n => [|n]; rewrite ?bin0 // coef0 coefC mul0rn. Qed. Lemma nderivnXn m n : ('X^m)^`N(n) = 'X^(m - n) *+ 'C(m, n). Proof. apply/polyP=> i; rewrite coef_nderivn coefMn !coefXn. have [lt_m_n | le_n_m] := ltnP m n. by rewrite eqn_leq leqNgt ltn_addr // mul0rn bin_small. by rewrite -{1 3}(subnKC le_n_m) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn. Qed. Fact nderivn_is_linear n : linear (nderivn n). Proof. move=> k p q; apply/polyP=> i. by rewrite !(coef_nderivn, coefD, coefZ) mulrnDl mulrnAr. Qed. HB.instance Definition _ n := GRing.isSemilinear.Build R {poly R} {poly R} _ (nderivn n) (GRing.semilinear_linear (nderivn_is_linear n)). Lemma nderivnD n : {morph nderivn n : p q / p + q}. Proof. exact: linearD. Qed. Lemma nderivnB n : {morph nderivn n : p q / p - q}. Proof. exact: linearB. Qed. Lemma nderivnMn n m p : (p *+ m)^`N(n) = p^`N(n) *+ m. Proof. exact: linearMn. Qed. Lemma nderivnMNn n m p : (p *- m)^`N(n) = p^`N(n) *- m. Proof. exact: linearMNn. Qed. Lemma nderivnN n : {morph nderivn n : p / - p}. Proof. exact: linearN. Qed. Lemma nderivnZ n : scalable (nderivn n). Proof. exact: linearZZ. Qed. Lemma nderivnMXaddC n p c : (p * 'X + c%:P)^`N(n.+1) = p^`N(n) + p^`N(n.+1) * 'X. Proof. apply/polyP=> i; rewrite coef_nderivn !coefD !coefMX coefC. rewrite !addSn /= !coef_nderivn addr0 binS mulrnDr addrC; congr (_ + _). by rewrite addSnnS; case: i; rewrite // addn0 bin_small. Qed. Lemma nderivn_poly0 p n : size p <= n -> p^`N(n) = 0. Proof. move=> le_p_n; apply/polyP=> i; rewrite coef_nderivn. rewrite nth_default; first by rewrite mul0rn coef0. exact/(leq_trans le_p_n)/leq_addr. Qed. Lemma nderiv_taylor p x h : GRing.comm x h -> p.[x + h] = \sum_(i < size p) p^`N(i).[x] * h ^+ i. Proof. move/commrX=> cxh; elim/poly_ind: p => [|p c IHp]. by rewrite size_poly0 big_ord0 horner0. rewrite hornerMXaddC size_MXaddC. have [-> | nz_p] := eqVneq p 0. rewrite horner0 !simp; have [-> | _] := c =P 0; first by rewrite big_ord0. by rewrite size_poly0 big_ord_recl big_ord0 nderivn0 hornerC !simp. rewrite big_ord_recl nderivn0 !simp hornerMXaddC addrAC; congr (_ + _). rewrite mulrDr {}IHp !big_distrl polySpred //= big_ord_recl /= mulr1 -addrA. rewrite nderivn0 /bump /(addn 1) /=; congr (_ + _). rewrite !big_ord_recr /= nderivnMXaddC -mulrA -exprSr -polySpred // !addrA. congr (_ + _); last by rewrite (nderivn_poly0 (leqnn _)) !simp. rewrite addrC -big_split /=; apply: eq_bigr => i _. by rewrite nderivnMXaddC !hornerE_comm /= mulrDl -!mulrA -exprSr cxh. Qed. Lemma nderiv_taylor_wide n p x h : GRing.comm x h -> size p <= n -> p.[x + h] = \sum_(i < n) p^`N(i).[x] * h ^+ i. Proof. move/nderiv_taylor=> -> le_p_n. rewrite (big_ord_widen n (fun i => p^`N(i).[x] * h ^+ i)) // big_mkcond. apply: eq_bigr => i _; case: leqP => // /nderivn_poly0->. by rewrite horner0 simp. Qed. Lemma eq_poly n E1 E2 : (forall i, i < n -> E1 i = E2 i) -> poly n E1 = poly n E2 :> {poly R}. Proof. by move=> E; rewrite !poly_def; apply: eq_bigr => i _; rewrite E. Qed. End PolynomialTheory. #[deprecated(since="mathcomp 2.4.0", note="renamed to `size_polyN`")] Notation size_opp := size_polyN (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pchar_poly instead.")] Notation char_poly := pchar_poly (only parsing). Prenex Implicits polyC polyCK Poly polyseqK lead_coef root horner polyOver. Arguments monic {R}. Notation "\poly_ ( i < n ) E" := (poly n (fun i => E)) : ring_scope. Notation "c %:P" := (polyC c) : ring_scope. Notation "'X" := (polyX _) : ring_scope. Notation "''X^' n" := ('X ^+ n) : ring_scope. Notation "p .[ x ]" := (horner p x) : ring_scope. Notation "n .-unity_root" := (root_of_unity n) : ring_scope. Notation "n .-primitive_root" := (primitive_root_of_unity n) : ring_scope. Notation "a ^` ()" := (deriv a) : ring_scope. Notation "a ^` ( n )" := (derivn n a) : ring_scope. Notation "a ^`N ( n )" := (nderivn n a) : ring_scope. Arguments monic_pred _ _ /. Arguments monicP {R p}. Arguments rootP {R p x}. Arguments rootPf {R p x}. Arguments rootPt {R p x}. Arguments unity_rootP {R n z}. Arguments polyOver_pred _ _ _ /. Arguments polyOverP {R S p}. Arguments polyC_inj {R} [x1 x2] eq_x12P. Arguments eq_poly {R n} [E1] E2 eq_E12. Section IdomainPrimRoot. Variables (R : idomainType) (n : nat) (z : R). Hypothesis prim_z : n.-primitive_root z. Import prime. Let n_gt0 := prim_order_gt0 prim_z. Lemma prim_root_pcharF p : (p %| n)%N -> p \in [pchar R] = false. Proof. move=> pn; apply: contraTF isT => pchar_p; have p_prime := pcharf_prime pchar_p. have /dvdnP[[|k] n_eq_kp] := pn; first by rewrite n_eq_kp in (n_gt0). have /eqP := prim_expr_order prim_z; rewrite n_eq_kp exprM. rewrite -pFrobenius_autE -(pFrobenius_aut1 pchar_p) -subr_eq0 -rmorphB/=. rewrite pFrobenius_autE expf_eq0// prime_gt0//= subr_eq0 => /eqP. move=> /eqP; rewrite -(prim_order_dvd prim_z) n_eq_kp. rewrite -[X in _ %| X]muln1 dvdn_pmul2l ?dvdn1// => /eqP peq1. by rewrite peq1 in p_prime. Qed. Lemma pchar_prim_root : [pchar R]^'.-nat n. Proof. by apply/pnatP=> // p pp pn; rewrite inE/= prim_root_pcharF. Qed. Lemma prim_root_pi_eq0 m : \pi(n).-nat m -> m%:R != 0 :> R. Proof. by rewrite natf_neq0_pchar; apply: sub_in_pnat => p _; apply: pnatPpi pchar_prim_root. Qed. Lemma prim_root_dvd_eq0 m : (m %| n)%N -> m%:R != 0 :> R. Proof. case: m => [|m mn]; first by rewrite dvd0n gtn_eqF. by rewrite prim_root_pi_eq0 ?(sub_in_pnat (in1W (pi_of_dvd mn _))) ?pnat_pi. Qed. Lemma prim_root_natf_neq0 : n%:R != 0 :> R. Proof. by rewrite prim_root_dvd_eq0. Qed. End IdomainPrimRoot. #[deprecated(since="mathcomp 2.4.0", note="Use prim_root_pcharF instead.")] Notation prim_root_charF := prim_root_pcharF (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pchar_prim_root instead.")] Notation char_prim_root := pchar_prim_root (only parsing). (* Container morphism. *) Section MapPoly. Section Definitions. Variables (aR rR : nzRingType) (f : aR -> rR). Definition map_poly (p : {poly aR}) := \poly_(i < size p) f p`_i. (* Alternative definition; the one above is more convenient because it lets *) (* us use the lemmas on \poly, e.g., size (map_poly p) <= size p is an *) (* instance of size_poly. *) Lemma map_polyE p : map_poly p = Poly (map f p). Proof. rewrite /map_poly unlock; congr Poly. apply: (@eq_from_nth _ 0); rewrite size_mkseq ?size_map // => i lt_i_p. by rewrite [RHS](nth_map 0) ?nth_mkseq. Qed. Definition commr_rmorph u := forall x, GRing.comm u (f x). Definition horner_morph u of commr_rmorph u := fun p => (map_poly p).[u]. End Definitions. Variables aR rR : nzRingType. Section Combinatorial. Variables (iR : nzRingType) (f : aR -> rR). Local Notation "p ^f" := (map_poly f p) : ring_scope. Lemma map_poly0 : 0^f = 0. Proof. by rewrite map_polyE polyseq0. Qed. Lemma eq_map_poly (g : aR -> rR) : f =1 g -> map_poly f =1 map_poly g. Proof. by move=> eq_fg p; rewrite !map_polyE (eq_map eq_fg). Qed. Lemma map_poly_id g (p : {poly iR}) : {in (p : seq iR), g =1 id} -> map_poly g p = p. Proof. by move=> g_id; rewrite map_polyE map_id_in ?polyseqK. Qed. Lemma coef_map_id0 p i : f 0 = 0 -> (p^f)`_i = f p`_i. Proof. by move=> f0; rewrite coef_poly; case: ltnP => // le_p_i; rewrite nth_default. Qed. Lemma map_Poly_id0 s : f 0 = 0 -> (Poly s)^f = Poly (map f s). Proof. move=> f0; apply/polyP=> j; rewrite coef_map_id0 ?coef_Poly //. have [/(nth_map 0 0)->// | le_s_j] := ltnP j (size s). by rewrite !nth_default ?size_map. Qed. Lemma map_poly_comp_id0 (g : iR -> aR) p : f 0 = 0 -> map_poly (f \o g) p = (map_poly g p)^f. Proof. by move=> f0; rewrite map_polyE map_comp -map_Poly_id0 -?map_polyE. Qed. Lemma size_map_poly_id0 p : f (lead_coef p) != 0 -> size p^f = size p. Proof. by move=> nz_fp; apply: size_poly_eq. Qed. Lemma map_poly_eq0_id0 p : f (lead_coef p) != 0 -> (p^f == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /size_map_poly_id0->. Qed. Lemma lead_coef_map_id0 p : f 0 = 0 -> f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p). Proof. by move=> f0 nz_fp; rewrite lead_coefE coef_map_id0 ?size_map_poly_id0. Qed. Hypotheses (inj_f : injective f) (f_0 : f 0 = 0). Lemma size_map_inj_poly p : size p^f = size p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite map_poly0 !size_poly0. by rewrite size_map_poly_id0 // -f_0 (inj_eq inj_f) lead_coef_eq0. Qed. Lemma map_inj_poly : injective (map_poly f). Proof. move=> p q /polyP eq_pq; apply/polyP=> i; apply: inj_f. by rewrite -!coef_map_id0 ?eq_pq. Qed. Lemma lead_coef_map_inj p : lead_coef p^f = f (lead_coef p). Proof. by rewrite !lead_coefE size_map_inj_poly coef_map_id0. Qed. End Combinatorial. Lemma map_polyK (f : aR -> rR) g : cancel g f -> f 0 = 0 -> cancel (map_poly g) (map_poly f). Proof. by move=> gK f_0 p; rewrite /= -map_poly_comp_id0 ?map_poly_id // => x _ //=. Qed. Lemma eq_in_map_poly_id0 (f g : aR -> rR) (S : addrClosed aR) : f 0 = 0 -> g 0 = 0 -> {in S, f =1 g} -> {in polyOver S, map_poly f =1 map_poly g}. Proof. move=> f0 g0 eq_fg p pP; apply/polyP => i. by rewrite !coef_map_id0// eq_fg// (polyOverP _). Qed. Lemma eq_in_map_poly (f g : {additive aR -> rR}) (S : addrClosed aR) : {in S, f =1 g} -> {in polyOver S, map_poly f =1 map_poly g}. Proof. by move=> /eq_in_map_poly_id0; apply; rewrite //?raddf0. Qed. Section Additive. Variables (iR : nzRingType) (f : {additive aR -> rR}). Local Notation "p ^f" := (map_poly (GRing.Additive.sort f) p) : ring_scope. Lemma coef_map p i : p^f`_i = f p`_i. Proof. exact: coef_map_id0 (raddf0 f). Qed. Lemma map_Poly s : (Poly s)^f = Poly (map f s). Proof. exact: map_Poly_id0 (raddf0 f). Qed. Lemma map_poly_comp (g : iR -> aR) p : map_poly (f \o g) p = map_poly f (map_poly g p). Proof. exact: map_poly_comp_id0 (raddf0 f). Qed. Fact map_poly_is_zmod_morphism : zmod_morphism (map_poly f). Proof. by move=> p q; apply/polyP=> i; rewrite !(coef_map, coefB) raddfB. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `map_poly_is_zmod_morphism` instead")] Definition map_poly_is_additive := map_poly_is_zmod_morphism. HB.instance Definition _ := GRing.isZmodMorphism.Build {poly aR} {poly rR} (map_poly f) map_poly_is_zmod_morphism. Lemma map_polyC a : (a%:P)^f = (f a)%:P. Proof. by apply/polyP=> i; rewrite !(coef_map, coefC) -!mulrb raddfMn. Qed. Lemma lead_coef_map_eq p : f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p). Proof. exact: lead_coef_map_id0 (raddf0 f). Qed. End Additive. Variable f : {rmorphism aR -> rR}. Implicit Types p : {poly aR}. Local Notation "p ^f" := (map_poly (GRing.RMorphism.sort f) p) : ring_scope. Fact map_poly_is_monoid_morphism : monoid_morphism (map_poly f). Proof. split=> [|p q]; apply/polyP=> i. by rewrite !(coef_map, coef1) /= rmorph_nat. rewrite coef_map /= !coefM /= !rmorph_sum; apply: eq_bigr => j _. by rewrite !coef_map rmorphM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `map_poly_is_monoid_morphism` instead")] Definition map_poly_is_multiplicative := (fun g => (g.2, g.1)) map_poly_is_monoid_morphism. HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly aR} {poly rR} (map_poly f) map_poly_is_monoid_morphism. Lemma map_polyZ c p : (c *: p)^f = f c *: p^f. Proof. by apply/polyP=> i; rewrite !(coef_map, coefZ) /= rmorphM. Qed. HB.instance Definition _ := GRing.isScalable.Build aR {poly aR} {poly rR} (f \; *:%R) (map_poly f) map_polyZ. Lemma map_polyX : ('X)^f = 'X. Proof. by apply/polyP=> i; rewrite coef_map !coefX /= rmorph_nat. Qed. Lemma map_polyXn n : ('X^n)^f = 'X^n. Proof. by rewrite rmorphXn /= map_polyX. Qed. Lemma map_polyXaddC x : ('X + x%:P)^f = 'X + (f x)%:P. Proof. by rewrite raddfD/= map_polyX map_polyC. Qed. Lemma map_polyXsubC x : ('X - x%:P)^f = 'X - (f x)%:P. Proof. by rewrite raddfB/= map_polyX map_polyC. Qed. Lemma map_prod_XsubC I (rI : seq I) P F : (\prod_(i <- rI | P i) ('X - (F i)%:P))^f = \prod_(i <- rI | P i) ('X - (f (F i))%:P). Proof. by rewrite rmorph_prod//; apply/eq_bigr => x /=; rewrite map_polyXsubC. Qed. Lemma prod_map_poly (ar : seq aR) P : \prod_(x <- map f ar | P x) ('X - x%:P) = (\prod_(x <- ar | P (f x)) ('X - x%:P))^f. Proof. by rewrite big_map map_prod_XsubC. Qed. Lemma monic_map p : p \is monic -> p^f \is monic. Proof. move/monicP=> mon_p; rewrite monicE. by rewrite lead_coef_map_eq mon_p /= rmorph1 ?oner_neq0. Qed. Lemma horner_map p x : p^f.[f x] = f p.[x]. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(rmorph0, horner0). rewrite hornerMXaddC !rmorphD !rmorphM /=. by rewrite map_polyX map_polyC hornerMXaddC IHp. Qed. Lemma map_comm_poly p x : comm_poly p x -> comm_poly p^f (f x). Proof. by rewrite /comm_poly horner_map -!rmorphM // => ->. Qed. Lemma map_comm_coef p x : comm_coef p x -> comm_coef p^f (f x). Proof. by move=> cpx i; rewrite coef_map -!rmorphM ?cpx. Qed. Lemma rmorph_root p x : root p x -> root p^f (f x). Proof. by move/eqP=> px0; rewrite rootE horner_map px0 rmorph0. Qed. Lemma rmorph_unity_root n z : n.-unity_root z -> n.-unity_root (f z). Proof. move/rmorph_root; rewrite rootE rmorphB hornerD hornerN. by rewrite /= map_polyXn rmorph1 hornerC hornerXn subr_eq0 unity_rootE. Qed. Section HornerMorph. Variable u : rR. Hypothesis cfu : commr_rmorph f u. Lemma horner_morphC a : horner_morph cfu a%:P = f a. Proof. by rewrite /horner_morph map_polyC hornerC. Qed. Lemma horner_morphX : horner_morph cfu 'X = u. Proof. by rewrite /horner_morph map_polyX hornerX. Qed. Fact horner_is_linear : linear_for (f \; *%R) (horner_morph cfu). Proof. by move=> c p q; rewrite /horner_morph linearP /= hornerD hornerZ. Qed. Fact horner_is_monoid_morphism : monoid_morphism (horner_morph cfu). Proof. split=> [|p q]; first by rewrite /horner_morph rmorph1 hornerC. rewrite /horner_morph rmorphM /= hornerM_comm //. by apply: comm_coef_poly => i; rewrite coef_map cfu. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `horner_is_monoid_morphism` instead")] Definition horner_is_multiplicative := (fun g => (g.2, g.1)) horner_is_monoid_morphism. HB.instance Definition _ := GRing.isSemilinear.Build aR {poly aR} rR _ (horner_morph cfu) (GRing.semilinear_linear horner_is_linear). HB.instance Definition _ := GRing.isMonoidMorphism.Build {poly aR} rR (horner_morph cfu) horner_is_monoid_morphism. End HornerMorph. Lemma deriv_map p : p^f^`() = (p^`())^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_deriv) //= rmorphMn. Qed. Lemma derivn_map p n : p^f^`(n) = (p^`(n))^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_derivn) //= rmorphMn. Qed. Lemma nderivn_map p n : p^f^`N(n) = (p^`N(n))^f. Proof. by apply/polyP => i; rewrite !(coef_map, coef_nderivn) //= rmorphMn. Qed. End MapPoly. Lemma mapf_root (F : fieldType) (R : nzRingType) (f : {rmorphism F -> R}) (p : {poly F}) (x : F) : root (map_poly f p) (f x) = root p x. Proof. by rewrite !rootE horner_map fmorph_eq0. Qed. (* Morphisms from the polynomial ring, and the initiality of polynomials *) (* with respect to these. *) Section MorphPoly. Variable (aR rR : nzRingType) (pf : {rmorphism {poly aR} -> rR}). Lemma poly_morphX_comm : commr_rmorph (pf \o polyC) (pf 'X). Proof. by move=> a; rewrite /GRing.comm /= -!rmorphM // commr_polyX. Qed. Lemma poly_initial : pf =1 horner_morph poly_morphX_comm. Proof. apply: poly_ind => [|p a IHp]; first by rewrite !rmorph0. by rewrite !rmorphD !rmorphM /= -{}IHp horner_morphC ?horner_morphX. Qed. End MorphPoly. Notation "p ^:P" := (map_poly polyC p) : ring_scope. Section PolyCompose. Variable R : nzRingType. Implicit Types p q : {poly R}. Definition comp_poly q p := p^:P.[q]. Local Notation "p \Po q" := (comp_poly q p) : ring_scope. Lemma size_map_polyC p : size p^:P = size p. Proof. exact/(size_map_inj_poly polyC_inj). Qed. Lemma map_polyC_eq0 p : (p^:P == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 size_map_polyC. Qed. Lemma root_polyC p x : root p^:P x%:P = root p x. Proof. by rewrite rootE horner_map polyC_eq0. Qed. Lemma comp_polyE p q : p \Po q = \sum_(i < size p) p`_i *: q^+i. Proof. by rewrite [p \Po q]horner_poly; apply: eq_bigr => i _; rewrite mul_polyC. Qed. Lemma coef_comp_poly p q n : (p \Po q)`_n = \sum_(i < size p) p`_i * (q ^+ i)`_n. Proof. by rewrite comp_polyE coef_sum; apply: eq_bigr => i; rewrite coefZ. Qed. Lemma polyOver_comp (ringS : semiringClosed R) : {in polyOver ringS &, forall p q, p \Po q \in polyOver ringS}. Proof. move=> p q /polyOverP Sp Sq; rewrite comp_polyE rpred_sum // => i _. by rewrite polyOverZ ?rpredX. Qed. Lemma comp_polyCr p c : p \Po c%:P = p.[c]%:P. Proof. exact: horner_map. Qed. Lemma comp_poly0r p : p \Po 0 = (p`_0)%:P. Proof. by rewrite comp_polyCr horner_coef0. Qed. Lemma comp_polyC c p : c%:P \Po p = c%:P. Proof. by rewrite /(_ \Po p) map_polyC hornerC. Qed. Fact comp_poly_is_linear p : linear (comp_poly p). Proof. move=> a q r. by rewrite /comp_poly rmorphD /= map_polyZ !hornerE_comm mul_polyC. Qed. HB.instance Definition _ p := GRing.isSemilinear.Build R {poly R} {poly R} _ (comp_poly p) (GRing.semilinear_linear (comp_poly_is_linear p)). Lemma comp_poly0 p : 0 \Po p = 0. Proof. exact: raddf0. Qed. Lemma comp_polyD p q r : (p + q) \Po r = (p \Po r) + (q \Po r). Proof. exact: raddfD. Qed. Lemma comp_polyB p q r : (p - q) \Po r = (p \Po r) - (q \Po r). Proof. exact: raddfB. Qed. Lemma comp_polyZ c p q : (c *: p) \Po q = c *: (p \Po q). Proof. exact: linearZZ. Qed. Lemma comp_polyXr p : p \Po 'X = p. Proof. by rewrite -{2}/(idfun p) poly_initial. Qed. Lemma comp_polyX p : 'X \Po p = p. Proof. by rewrite /(_ \Po p) map_polyX hornerX. Qed. Lemma comp_poly_MXaddC c p q : (p * 'X + c%:P) \Po q = (p \Po q) * q + c%:P. Proof. by rewrite /(_ \Po q) rmorphD rmorphM /= map_polyX map_polyC hornerMXaddC. Qed. Lemma comp_polyXaddC_K p z : (p \Po ('X + z%:P)) \Po ('X - z%:P) = p. Proof. have addzK: ('X + z%:P) \Po ('X - z%:P) = 'X. by rewrite raddfD /= comp_polyC comp_polyX subrK. elim/poly_ind: p => [|p c IHp]; first by rewrite !comp_poly0. rewrite comp_poly_MXaddC linearD /= comp_polyC {1}/comp_poly rmorphM /=. by rewrite hornerM_comm /comm_poly -!/(_ \Po _) ?IHp ?addzK ?commr_polyX. Qed. Lemma size_comp_poly_leq p q : size (p \Po q) <= ((size p).-1 * (size q).-1).+1. Proof. rewrite comp_polyE (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _. rewrite (leq_trans (size_scale_leq _ _))//. rewrite (leq_trans (size_poly_exp_leq _ _))//. by rewrite ltnS mulnC leq_mul // -{2}(subnKC (valP i)) leq_addr. Qed. Lemma comp_Xn_poly p n : 'X^n \Po p = p ^+ n. Proof. by rewrite /(_ \Po p) map_polyXn hornerXn. Qed. Lemma coef_comp_poly_Xn p n i : 0 < n -> (p \Po 'X^n)`_i = if n %| i then p`_(i %/ n) else 0. Proof. move=> n_gt0; rewrite comp_polyE; under eq_bigr do rewrite -exprM mulnC. rewrite coef_sumMXn/=; case: dvdnP => [[j ->]|nD]; last first. by rewrite big1// => j /eqP ?; case: nD; exists j. under eq_bigl do rewrite eqn_mul2r gtn_eqF//. by rewrite big_ord1_eq if_nth ?leqVgt ?mulnK. Qed. Lemma comp_poly_Xn p n : 0 < n -> p \Po 'X^n = \poly_(i < size p * n) if n %| i then p`_(i %/ n) else 0. Proof. move=> n_gt0; apply/polyP => i; rewrite coef_comp_poly_Xn // coef_poly. case: dvdnP => [[k ->]|]; last by rewrite if_same. by rewrite mulnK // ltn_mul2r n_gt0 if_nth ?leqVgt. Qed. End PolyCompose. Notation "p \Po q" := (comp_poly q p) : ring_scope. Lemma map_comp_poly (aR rR : nzRingType) (f : {rmorphism aR -> rR}) p q : map_poly f (p \Po q) = map_poly f p \Po map_poly f q. Proof. elim/poly_ind: p => [|p a IHp]; first by rewrite !raddf0. rewrite comp_poly_MXaddC !rmorphD !rmorphM /= !map_polyC map_polyX. by rewrite comp_poly_MXaddC -IHp. Qed. Section Surgery. Variable R : nzRingType. Implicit Type p q : {poly R}. (* Even part of a polynomial *) Definition even_poly p : {poly R} := \poly_(i < uphalf (size p)) p`_i.*2. Lemma size_even_poly p : size (even_poly p) <= uphalf (size p). Proof. exact: size_poly. Qed. Lemma coef_even_poly p i : (even_poly p)`_i = p`_i.*2. Proof. by rewrite coef_poly gtn_uphalf_double if_nth ?leqVgt. Qed. Lemma even_polyE s p : size p <= s.*2 -> even_poly p = \poly_(i < s) p`_i.*2. Proof. move=> pLs2; apply/polyP => i; rewrite coef_even_poly !coef_poly if_nth //. by case: ltnP => //= ?; rewrite (leq_trans pLs2) ?leq_double. Qed. Lemma size_even_poly_eq p : odd (size p) -> size (even_poly p) = uphalf (size p). Proof. move=> p_even; rewrite size_poly_eq// double_pred odd_uphalfK//=. by rewrite lead_coef_eq0 -size_poly_eq0; case: size p_even. Qed. Lemma even_polyD p q : even_poly (p + q) = even_poly p + even_poly q. Proof. by apply/polyP => i; rewrite !(coef_even_poly, coefD). Qed. Lemma even_polyZ k p : even_poly (k *: p) = k *: even_poly p. Proof. by apply/polyP => i; rewrite !(coefZ, coef_even_poly). Qed. Fact even_poly_is_linear : linear even_poly. Proof. by move=> k p q; rewrite even_polyD even_polyZ. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ even_poly (GRing.semilinear_linear even_poly_is_linear). Lemma even_polyC (c : R) : even_poly c%:P = c%:P. Proof. by apply/polyP => i; rewrite coef_even_poly !coefC; case: i. Qed. (* Odd part of a polynomial *) Definition odd_poly p : {poly R} := \poly_(i < (size p)./2) p`_i.*2.+1. Lemma size_odd_poly p : size (odd_poly p) <= (size p)./2. Proof. exact: size_poly. Qed. Lemma coef_odd_poly p i : (odd_poly p)`_i = p`_i.*2.+1. Proof. by rewrite coef_poly gtn_half_double if_nth ?leqVgt. Qed. Lemma odd_polyE s p : size p <= s.*2.+1 -> odd_poly p = \poly_(i < s) p`_i.*2.+1. Proof. move=> pLs2; apply/polyP => i; rewrite coef_odd_poly !coef_poly if_nth //. by case: ltnP => //= ?; rewrite (leq_trans pLs2) ?ltnS ?leq_double. Qed. Lemma odd_polyC (c : R) : odd_poly c%:P = 0. Proof. by apply/polyP => i; rewrite coef_odd_poly !coefC; case: i. Qed. Lemma odd_polyD p q : odd_poly (p + q) = odd_poly p + odd_poly q. Proof. by apply/polyP => i; rewrite !(coef_odd_poly, coefD). Qed. Lemma odd_polyZ k p : odd_poly (k *: p) = k *: odd_poly p. Proof. by apply/polyP => i; rewrite !(coefZ, coef_odd_poly). Qed. Fact odd_poly_is_linear : linear odd_poly. Proof. by move=> k p q; rewrite odd_polyD odd_polyZ. Qed. HB.instance Definition _ := GRing.isSemilinear.Build R {poly R} {poly R} _ odd_poly (GRing.semilinear_linear odd_poly_is_linear). Lemma size_odd_poly_eq p : ~~ odd (size p) -> size (odd_poly p) = (size p)./2. Proof. have [->|p_neq0] := eqVneq p 0; first by rewrite odd_polyC size_poly0. move=> p_odd; rewrite size_poly_eq// -subn1 doubleB subn2 even_halfK//. rewrite prednK ?lead_coef_eq0// ltn_predRL. by move: p_neq0 p_odd; rewrite -size_poly_eq0; case: (size p) => [|[]]. Qed. Lemma odd_polyMX p : odd_poly (p * 'X) = even_poly p. Proof. have [->|pN0] := eqVneq p 0; first by rewrite mul0r even_polyC odd_polyC. by apply/polyP => i; rewrite !coef_poly size_mulX // coefMX. Qed. Lemma even_polyMX p : even_poly (p * 'X) = odd_poly p * 'X. Proof. have [->|pN0] := eqVneq p 0; first by rewrite mul0r even_polyC odd_polyC mul0r. by apply/polyP => -[|i]; rewrite !(coefMX, coef_poly, if_same, size_mulX). Qed. Lemma sum_even_poly p : \sum_(i < size p | ~~ odd i) p`_i *: 'X^i = even_poly p \Po 'X^2. Proof. apply/polyP => i; rewrite coef_comp_poly_Xn// coef_sumMXn coef_even_poly. rewrite (big_ord1_cond_eq _ _ (negb \o _))/= -dvdn2 andbC -muln2. by case: dvdnP => //= -[k ->]; rewrite mulnK// if_nth ?leqVgt. Qed. Lemma sum_odd_poly p : \sum_(i < size p | odd i) p`_i *: 'X^i = (odd_poly p \Po 'X^2) * 'X. Proof. apply/polyP => i; rewrite coefMX coef_comp_poly_Xn// coef_sumMXn coef_odd_poly/=. case: i => [|i]//=; first by rewrite big_andbC big1// => -[[|j]//]. rewrite big_ord1_cond_eq/= -dvdn2 andbC -muln2. by case: dvdnP => //= -[k ->]; rewrite mulnK// if_nth ?leqVgt. Qed. (* Decomposition in odd and even part *) Lemma poly_even_odd p : even_poly p \Po 'X^2 + (odd_poly p \Po 'X^2) * 'X = p. Proof. rewrite -sum_even_poly -sum_odd_poly addrC -(bigID _ xpredT). by rewrite -[RHS]coefK poly_def. Qed. (* take and drop for polynomials *) Definition take_poly m p := \poly_(i < m) p`_i. Lemma size_take_poly m p : size (take_poly m p) <= m. Proof. exact: size_poly. Qed. Lemma coef_take_poly m p i : (take_poly m p)`_i = if i < m then p`_i else 0. Proof. exact: coef_poly. Qed. Lemma take_poly_id m p : size p <= m -> take_poly m p = p. Proof. move=> /leq_trans gep; apply/polyP => i; rewrite coef_poly if_nth//=. by case: ltnP => // /gep->. Qed. Lemma take_polyD m p q : take_poly m (p + q) = take_poly m p + take_poly m q. Proof. by apply/polyP => i; rewrite !(coefD, coef_poly); case: leqP; rewrite ?add0r. Qed. Lemma take_polyZ k m p : take_poly m (k *: p) = k *: take_poly m p. Proof. apply/polyP => i; rewrite !(coefZ, coef_take_poly); case: leqP => //. by rewrite mulr0. Qed. Fact take_poly_is_linear m : linear (take_poly m). Proof. by move=> k p q; rewrite take_polyD take_polyZ. Qed. HB.instance Definition _ m := GRing.isSemilinear.Build R {poly R} {poly R} _ (take_poly m) (GRing.semilinear_linear (take_poly_is_linear m)). Lemma take_poly_sum m I r P (p : I -> {poly R}) : take_poly m (\sum_(i <- r | P i) p i) = \sum_(i <- r| P i) take_poly m (p i). Proof. exact: linear_sum. Qed. Lemma take_poly0l p : take_poly 0 p = 0. Proof. exact/size_poly_leq0P/size_take_poly. Qed. Lemma take_poly0r m : take_poly m 0 = 0. Proof. exact: linear0. Qed. Lemma take_polyMXn m n p : take_poly m (p * 'X^n) = take_poly (m - n) p * 'X^n. Proof. have [->|/eqP p_neq0] := p =P 0; first by rewrite !(mul0r, take_poly0r). apply/polyP => i; rewrite !(coef_take_poly, coefMXn). by have [iLn|nLi] := leqP n i; rewrite ?if_same// ltn_sub2rE. Qed. Lemma take_polyMXn_0 n p : take_poly n (p * 'X^n) = 0. Proof. by rewrite take_polyMXn subnn take_poly0l mul0r. Qed. Lemma take_polyDMXn n p q : size p <= n -> take_poly n (p + q * 'X^n) = p. Proof. by move=> ?; rewrite take_polyD take_poly_id// take_polyMXn_0 addr0. Qed. Definition drop_poly m p := \poly_(i < size p - m) p`_(i + m). Lemma coef_drop_poly m p i : (drop_poly m p)`_i = p`_(i + m). Proof. by rewrite coef_poly ltn_subRL addnC if_nth ?leqVgt. Qed. Lemma drop_poly_eq0 m p : size p <= m -> drop_poly m p = 0. Proof. move=> sLm; apply/polyP => i; rewrite coef_poly coef0 ltn_subRL addnC. by rewrite if_nth ?leqVgt// nth_default// (leq_trans _ (leq_addl _ _)). Qed. Lemma size_drop_poly n p : size (drop_poly n p) = (size p - n)%N. Proof. have [pLn|nLp] := leqP (size p) n. by rewrite (eqP pLn) drop_poly_eq0 ?size_poly0. have p_neq0 : p != 0 by rewrite -size_poly_gt0 (leq_trans _ nLp). by rewrite size_poly_eq// predn_sub subnK ?lead_coef_eq0// -ltnS -polySpred. Qed. Lemma sum_drop_poly n p : \sum_(n <= i < size p) p`_i *: 'X^i = drop_poly n p * 'X^n. Proof. rewrite (big_addn 0) big_mkord /drop_poly poly_def mulr_suml. by apply: eq_bigr => i _; rewrite exprD scalerAl. Qed. Lemma drop_polyD m p q : drop_poly m (p + q) = drop_poly m p + drop_poly m q. Proof. by apply/polyP => i; rewrite coefD !coef_drop_poly coefD. Qed. Lemma drop_polyZ k m p : drop_poly m (k *: p) = k *: drop_poly m p. Proof. by apply/polyP => i; rewrite coefZ !coef_drop_poly coefZ. Qed. Fact drop_poly_is_linear m : linear (drop_poly m). Proof. by move=> k p q; rewrite drop_polyD drop_polyZ. Qed. HB.instance Definition _ m := GRing.isSemilinear.Build R {poly R} {poly R} _ (drop_poly m) (GRing.semilinear_linear (drop_poly_is_linear m)). Lemma drop_poly_sum m I r P (p : I -> {poly R}) : drop_poly m (\sum_(i <- r | P i) p i) = \sum_(i <- r | P i) drop_poly m (p i). Proof. exact: linear_sum. Qed. Lemma drop_poly0l p : drop_poly 0 p = p. Proof. by apply/polyP => i; rewrite coef_poly subn0 addn0 if_nth ?leqVgt. Qed. Lemma drop_poly0r m : drop_poly m 0 = 0. Proof. exact: linear0. Qed. Lemma drop_polyMXn m n p : drop_poly m (p * 'X^n) = drop_poly (m - n) p * 'X^(n - m). Proof. have [->|p_neq0] := eqVneq p 0; first by rewrite mul0r !drop_poly0r mul0r. apply/polyP => i; rewrite !(coefMXn, coef_drop_poly) ltn_subRL [(m + i)%N]addnC. have [i_small|i_big]// := ltnP; congr nth. by have [mn|/ltnW mn] := leqP m n; rewrite (eqP mn) (addn0, subn0) (subnBA, addnBA). Qed. Lemma drop_polyMXn_id n p : drop_poly n (p * 'X^ n) = p. Proof. by rewrite drop_polyMXn subnn drop_poly0l expr0 mulr1. Qed. Lemma drop_polyDMXn n p q : size p <= n -> drop_poly n (p + q * 'X^n) = q. Proof. by move=> ?; rewrite drop_polyD drop_poly_eq0// drop_polyMXn_id add0r. Qed. Lemma poly_take_drop n p : take_poly n p + drop_poly n p * 'X^n = p. Proof. apply/polyP => i; rewrite coefD coefMXn coef_take_poly coef_drop_poly. by case: ltnP => ni; rewrite ?addr0 ?add0r//= subnK. Qed. Lemma eqp_take_drop n p q : take_poly n p = take_poly n q -> drop_poly n p = drop_poly n q -> p = q. Proof. by move=> tpq dpq; rewrite -[p](poly_take_drop n) -[q](poly_take_drop n) tpq dpq. Qed. End Surgery. Definition coefE := (coef0, coef1, coefC, coefX, coefXn, coef_sumMXn, coefZ, coefMC, coefCM, coefXnM, coefMXn, coefXM, coefMX, coefMNn, coefMn, coefN, coefB, coefD, coef_even_poly, coef_odd_poly, coef_take_poly, coef_drop_poly, coef_cons, coef_Poly, coef_poly, coef_deriv, coef_nderivn, coef_derivn, coef_map, coef_sum, coef_comp_poly_Xn, coef_comp_poly). Section PolynomialComNzRing. Variable R : comNzRingType. Implicit Types p q : {poly R}. Fact poly_mul_comm p q : p * q = q * p. Proof. apply/polyP=> i; rewrite coefM coefMr. by apply: eq_bigr => j _; rewrite mulrC. Qed. HB.instance Definition _ := GRing.PzRing_hasCommutativeMul.Build (polynomial R) poly_mul_comm. HB.instance Definition _ := GRing.Lalgebra_isComAlgebra.Build R (polynomial R). Lemma coef_prod_XsubC (ps : seq R) (n : nat) : (n <= size ps)%N -> (\prod_(p <- ps) ('X - p%:P))`_n = (-1) ^+ (size ps - n)%N * \sum_(I in {set 'I_(size ps)} | #|I| == (size ps - n)%N) \prod_(i in I) ps`_i. Proof. move=> nle. under eq_bigr => i _ do rewrite addrC -raddfN/=. rewrite -{1}(in_tupleE ps) -(map_tnth_enum (_ ps)) big_map. rewrite enumT bigA_distr /= coef_sum. transitivity (\sum_(I in {set 'I_(size ps)}) if #|I| == (size ps - n)%N then \prod_(i < size ps | i \in I) - ps`_i else 0). apply eq_bigr => I _. rewrite big_if/= big_const iter_mulr_1 -rmorph_prod/= coefCM coefXn. under eq_bigr => i _ do rewrite (tnth_nth 0)/=. rewrite -[#|I| == _](eqn_add2r n) subnK//. rewrite -[X in (_ + _)%N == X]card_ord -(cardC I) eqn_add2l. by case: ifP; rewrite ?mulr1 ?mulr0. by rewrite -big_mkcond mulr_sumr/=; apply: eq_bigr => I /eqP <-; rewrite prodrN. Qed. Lemma coefPn_prod_XsubC (ps : seq R) : size ps != 0 -> (\prod_(p <- ps) ('X - p%:P))`_(size ps).-1 = - \sum_(p <- ps) p. Proof. rewrite coef_prod_XsubC ?leq_pred// => ps0. have -> : (size ps - (size ps).-1 = 1)%N. by move: ps0; case: (size ps) => // n _; exact: subSnn. rewrite expr1 mulN1r; congr GRing.opp. set f : 'I_(size ps) -> {set 'I_(size ps)} := fun a => [set a]. transitivity (\sum_(I in imset f (mem setT)) \prod_(i in I) ps`_i). apply: congr_big => // I /=. by apply/cards1P/imsetP => [[a ->] | [a _ ->]]; exists a. rewrite big_imset/=; last first. by move=> i j _ _ ij; apply/set1P; rewrite -/(f j) -ij set11. rewrite -[in RHS](in_tupleE ps) -(map_tnth_enum (_ ps)) big_map enumT. apply: congr_big => // i; first exact: in_setT. by rewrite big_set1 (tnth_nth 0). Qed. Lemma coef0_prod_XsubC (ps : seq R) : (\prod_(p <- ps) ('X - p%:P))`_0 = (-1) ^+ (size ps) * \prod_(p <- ps) p. Proof. rewrite coef_prod_XsubC// subn0; congr GRing.mul. transitivity (\sum_(I in [set setT : {set 'I_(size ps)}]) \prod_(i in I) ps`_i). apply: congr_big =>// i/=. apply/idP/set1P => [/eqP cardE | ->]; last by rewrite cardsT card_ord. by apply/eqP; rewrite eqEcard subsetT cardsT card_ord cardE leqnn. rewrite big_set1 -[in RHS](in_tupleE ps) -(map_tnth_enum (_ ps)) big_map enumT. apply: congr_big => // i; first exact: in_setT. by rewrite (tnth_nth 0). Qed. Lemma hornerM p q x : (p * q).[x] = p.[x] * q.[x]. Proof. by rewrite hornerM_comm //; apply: mulrC. Qed. Lemma horner_exp p x n : (p ^+ n).[x] = p.[x] ^+ n. Proof. by rewrite horner_exp_comm //; apply: mulrC. Qed. Lemma horner_prod I r (P : pred I) (F : I -> {poly R}) x : (\prod_(i <- r | P i) F i).[x] = \prod_(i <- r | P i) (F i).[x]. Proof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (hornerM, hornerC). Qed. Definition hornerE := (hornerD, hornerN, hornerX, hornerC, horner_exp, simp, hornerCM, hornerZ, hornerM, horner_cons). Definition horner_eval (x : R) := horner^~ x. Lemma horner_evalE x p : horner_eval x p = p.[x]. Proof. by []. Qed. Fact horner_eval_is_linear x : linear_for *%R (horner_eval x). Proof. have cxid: commr_rmorph idfun x by apply: mulrC. have evalE : horner_eval x =1 horner_morph cxid. by move=> p; congr _.[x]; rewrite map_poly_id. by move=> c p q; rewrite !evalE linearP. Qed. Fact horner_eval_is_monoid_morphism x : monoid_morphism (horner_eval x). Proof. have cxid: commr_rmorph idfun x by apply: mulrC. have evalE : horner_eval x =1 horner_morph cxid. by move=> p; congr _.[x]; rewrite map_poly_id. by split=> [|p q]; rewrite !evalE ?rmorph1// rmorphM. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `horner_eval_is_monoid_morphism` instead")] Definition horner_eval_is_multiplicative x := (fun g => (g.2, g.1)) (horner_eval_is_monoid_morphism x). HB.instance Definition _ x := GRing.isSemilinear.Build R {poly R} R _ (horner_eval x) (GRing.semilinear_linear (horner_eval_is_linear x)). HB.instance Definition _ x := GRing.isMonoidMorphism.Build {poly R} R (horner_eval x) (horner_eval_is_monoid_morphism x). Section HornerAlg. Variable A : algType R. (* For univariate polys, commutativity is not needed *) Section Defs. Variable a : A. Lemma in_alg_comm : commr_rmorph (in_alg A) a. Proof. move=> r /=; by rewrite /GRing.comm comm_alg. Qed. Definition horner_alg := horner_morph in_alg_comm. Lemma horner_algC c : horner_alg c%:P = c%:A. Proof. exact: horner_morphC. Qed. Lemma horner_algX : horner_alg 'X = a. Proof. exact: horner_morphX. Qed. HB.instance Definition _ := GRing.LRMorphism.on horner_alg. End Defs. Variable (pf : {lrmorphism {poly R} -> A}). Lemma poly_alg_initial : pf =1 horner_alg (pf 'X). Proof. apply: poly_ind => [|p a IHp]; first by rewrite !rmorph0. rewrite !rmorphD !rmorphM /= -{}IHp horner_algC ?horner_algX. by rewrite -alg_polyC rmorph_alg. Qed. End HornerAlg. Fact comp_poly_is_monoid_morphism q : monoid_morphism (comp_poly q). Proof. split=> [|p1 p2]; first by rewrite comp_polyC. by rewrite /comp_poly rmorphM hornerM_comm //; apply: mulrC. Qed. #[deprecated(since="mathcomp 2.5.0", note="use `comp_poly_is_monoid_morphism` instead")] Definition comp_poly_multiplicative q := (fun g => (g.2, g.1)) (comp_poly_is_monoid_morphism q). HB.instance Definition _ q := GRing.isMonoidMorphism.Build _ _ (comp_poly q) (comp_poly_is_monoid_morphism q). Lemma comp_polyM p q r : (p * q) \Po r = (p \Po r) * (q \Po r). Proof. exact: rmorphM. Qed. Lemma comp_polyA p q r : p \Po (q \Po r) = (p \Po q) \Po r. Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !comp_polyC. by rewrite !comp_polyD !comp_polyM !comp_polyX IHp !comp_polyC. Qed. Lemma horner_comp p q x : (p \Po q).[x] = p.[q.[x]]. Proof. by apply: polyC_inj; rewrite -!comp_polyCr comp_polyA. Qed. Lemma root_comp p q x : root (p \Po q) x = root p (q.[x]). Proof. by rewrite !rootE horner_comp. Qed. Lemma deriv_comp p q : (p \Po q) ^`() = (p ^`() \Po q) * q^`(). Proof. elim/poly_ind: p => [|p c IHp]; first by rewrite !(deriv0, comp_poly0) mul0r. rewrite comp_poly_MXaddC derivD derivC derivM IHp derivMXaddC comp_polyD. by rewrite comp_polyM comp_polyX addr0 addrC mulrAC -mulrDl. Qed. Lemma deriv_exp p n : (p ^+ n)^`() = p^`() * p ^+ n.-1 *+ n. Proof. elim: n => [|n IHn]; first by rewrite expr0 mulr0n derivC. by rewrite exprS derivM {}IHn (mulrC p) mulrnAl -mulrA -exprSr mulrS; case n. Qed. Definition derivCE := (derivE, deriv_exp). End PolynomialComNzRing. Section PolynomialIdomain. (* Integral domain structure on poly *) Variable R : idomainType. Implicit Types (a b x y : R) (p q r m : {poly R}). Lemma size_mul p q : p != 0 -> q != 0 -> size (p * q) = (size p + size q).-1. Proof. by move=> nz_p nz_q; rewrite -size_proper_mul ?mulf_neq0 ?lead_coef_eq0. Qed. Fact poly_idomainAxiom p q : p * q = 0 -> (p == 0) || (q == 0). Proof. move=> pq0; apply/norP=> [[p_nz q_nz]]; move/eqP: (size_mul p_nz q_nz). by rewrite eq_sym pq0 size_poly0 (polySpred p_nz) (polySpred q_nz) addnS. Qed. Definition poly_unit : pred {poly R} := fun p => (size p == 1) && (p`_0 \in GRing.unit). Definition poly_inv p := if p \in poly_unit then (p`_0)^-1%:P else p. Fact poly_mulVp : {in poly_unit, left_inverse 1 poly_inv *%R}. Proof. move=> p Up; rewrite /poly_inv Up. by case/andP: Up => /size_poly1P[c _ ->]; rewrite coefC -polyCM => /mulVr->. Qed. Fact poly_intro_unit p q : q * p = 1 -> p \in poly_unit. Proof. move=> pq1; apply/andP; split; last first. apply/unitrP; exists q`_0. by rewrite 2!mulrC -!/(coefp 0 _) -rmorphM pq1 rmorph1. have: size (q * p) == 1 by rewrite pq1 size_poly1. have [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0. have [-> | nz_q] := eqVneq q 0; first by rewrite mul0r size_poly0. rewrite size_mul // (polySpred nz_p) (polySpred nz_q) addnS addSn !eqSS. by rewrite addn_eq0 => /andP[]. Qed. Fact poly_inv_out : {in [predC poly_unit], poly_inv =1 id}. Proof. by rewrite /poly_inv => p /negbTE/= ->. Qed. HB.instance Definition _ := GRing.ComNzRing_hasMulInverse.Build (polynomial R) poly_mulVp poly_intro_unit poly_inv_out. HB.instance Definition _ := GRing.ComUnitRing_isIntegral.Build (polynomial R) poly_idomainAxiom. Lemma poly_unitE p : (p \in GRing.unit) = (size p == 1) && (p`_0 \in GRing.unit). Proof. by []. Qed. Lemma poly_invE p : p ^-1 = if p \in GRing.unit then (p`_0)^-1%:P else p. Proof. by []. Qed. Lemma polyCV c : c%:P^-1 = (c^-1)%:P. Proof. have [/rmorphV-> // | nUc] := boolP (c \in GRing.unit). by rewrite !invr_out // poly_unitE coefC (negbTE nUc) andbF. Qed. Lemma rootM p q x : root (p * q) x = root p x || root q x. Proof. by rewrite !rootE hornerM mulf_eq0. Qed. Lemma rootZ x a p : a != 0 -> root (a *: p) x = root p x. Proof. by move=> nz_a; rewrite -mul_polyC rootM rootC (negPf nz_a). Qed. Lemma root_exp p n a: comm_poly p a -> (0 < n)%N -> root (p ^+ n) a = root p a. Proof. by move=> ? n0; rewrite !rootE horner_exp_comm// expf_eq0 n0. Qed. Lemma size_scale a p : a != 0 -> size (a *: p) = size p. Proof. by move/lregP/lreg_size->. Qed. Lemma size_Cmul a p : a != 0 -> size (a%:P * p) = size p. Proof. by rewrite mul_polyC => /size_scale->. Qed. Lemma lead_coefM p q : lead_coef (p * q) = lead_coef p * lead_coef q. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, lead_coef0). have [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, lead_coef0). by rewrite lead_coef_proper_mul // mulf_neq0 ?lead_coef_eq0. Qed. Lemma lead_coef_prod I rI (P : {pred I}) (p : I -> {poly R}) : lead_coef (\prod_(i <- rI | P i) p i) = \prod_(i <- rI | P i) lead_coef (p i). Proof. by apply/big_morph/lead_coef1; apply: lead_coefM. Qed. Lemma lead_coefZ a p : lead_coef (a *: p) = a * lead_coef p. Proof. by rewrite -mul_polyC lead_coefM lead_coefC. Qed. Lemma scale_poly_eq0 a p : (a *: p == 0) = (a == 0) || (p == 0). Proof. by rewrite -mul_polyC mulf_eq0 polyC_eq0. Qed. Lemma size_prod (I : finType) (P : pred I) (F : I -> {poly R}) : (forall i, P i -> F i != 0) -> size (\prod_(i | P i) F i) = ((\sum_(i | P i) size (F i)).+1 - #|P|)%N. Proof. move=> nzF; transitivity (\sum_(i | P i) (size (F i)).-1).+1; last first. apply: canRL (addKn _) _; rewrite addnS -sum1_card -big_split /=. by congr _.+1; apply: eq_bigr => i /nzF/polySpred. elim/big_rec2: _ => [|i d p /nzF nzFi IHp]; first by rewrite size_poly1. by rewrite size_mul // -?size_poly_eq0 IHp // addnS polySpred. Qed. Lemma size_prod_seq (I : eqType) (s : seq I) (F : I -> {poly R}) : (forall i, i \in s -> F i != 0) -> size (\prod_(i <- s) F i) = ((\sum_(i <- s) size (F i)).+1 - size s)%N. Proof. move=> nzF; rewrite big_tnth size_prod; last by move=> i; rewrite nzF ?mem_tnth. by rewrite cardT /= size_enum_ord [in RHS]big_tnth. Qed. Lemma size_mul_eq1 p q : (size (p * q) == 1) = ((size p == 1) && (size q == 1)). Proof. have [->|pNZ] := eqVneq p 0; first by rewrite mul0r size_poly0. have [->|qNZ] := eqVneq q 0; first by rewrite mulr0 size_poly0 andbF. rewrite size_mul //. by move: pNZ qNZ; rewrite -!size_poly_gt0; (do 2 case: size) => //= n [|[|]]. Qed. Lemma size_prod_seq_eq1 (I : eqType) (s : seq I) (P : pred I) (F : I -> {poly R}) : reflect (forall i, P i && (i \in s) -> size (F i) = 1) (size (\prod_(i <- s | P i) F i) == 1%N). Proof. rewrite (big_morph _ (id1:=true) size_mul_eq1) ?size_polyC ?oner_neq0//. rewrite big_all_cond; apply/(iffP allP). by move=> h i /andP[Pi ins]; apply/eqP/(implyP (h i ins) Pi). by move=> h i ins; apply/implyP => Pi; rewrite h ?Pi. Qed. Lemma size_prod_eq1 (I : finType) (P : pred I) (F : I -> {poly R}) : reflect (forall i, P i -> size (F i) = 1) (size (\prod_(i | P i) F i) == 1). Proof. apply: (iffP (size_prod_seq_eq1 _ _ _)) => Hi i. by move=> Pi; apply: Hi; rewrite Pi /= mem_index_enum. by rewrite mem_index_enum andbT; apply: Hi. Qed. Lemma size_exp p n : (size (p ^+ n)).-1 = ((size p).-1 * n)%N. Proof. elim: n => [|n IHn]; first by rewrite size_poly1 muln0. have [-> | nz_p] := eqVneq p 0; first by rewrite exprS mul0r size_poly0. rewrite exprS size_mul ?expf_neq0 // mulnS -{}IHn. by rewrite polySpred // [size (p ^+ n)]polySpred ?expf_neq0 ?addnS. Qed. Lemma lead_coef_exp p n : lead_coef (p ^+ n) = lead_coef p ^+ n. Proof. elim: n => [|n IHn]; first by rewrite !expr0 lead_coef1. by rewrite !exprS lead_coefM IHn. Qed. Lemma root_prod_XsubC rs x : root (\prod_(a <- rs) ('X - a%:P)) x = (x \in rs). Proof. elim: rs => [|a rs IHrs]; first by rewrite rootE big_nil hornerC oner_eq0. by rewrite big_cons rootM IHrs root_XsubC. Qed. Lemma root_exp_XsubC n a x : root (('X - a%:P) ^+ n.+1) x = (x == a). Proof. by rewrite rootE horner_exp expf_eq0 [_ == 0]root_XsubC. Qed. Lemma size_comp_poly p q : (size (p \Po q)).-1 = ((size p).-1 * (size q).-1)%N. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite comp_poly0 size_poly0. have [/size1_polyC-> | nc_q] := leqP (size q) 1. by rewrite comp_polyCr !size_polyC -!sub1b -!subnS muln0. have nz_q: q != 0 by rewrite -size_poly_eq0 -(subnKC nc_q). rewrite mulnC comp_polyE (polySpred nz_p) /= big_ord_recr /= addrC. rewrite size_polyDl size_scale ?lead_coef_eq0 ?size_exp //=. rewrite [ltnRHS]polySpred ?expf_neq0 // ltnS size_exp. rewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _. rewrite (leq_trans (size_scale_leq _ _)) // polySpred ?expf_neq0 //. by rewrite size_exp -(subnKC nc_q) ltn_pmul2l. Qed. Lemma lead_coef_comp p q : size q > 1 -> lead_coef (p \Po q) = (lead_coef p) * lead_coef q ^+ (size p).-1. Proof. move=> q_gt1; rewrite !lead_coefE coef_comp_poly size_comp_poly. have [->|nz_p] := eqVneq p 0; first by rewrite size_poly0 big_ord0 coef0 mul0r. rewrite polySpred //= big_ord_recr /= big1 ?add0r => [|i _]. by rewrite -!lead_coefE -lead_coef_exp !lead_coefE size_exp mulnC. rewrite [X in _ * X]nth_default ?mulr0 ?(leq_trans (size_poly_exp_leq _ _)) //. by rewrite mulnC ltn_mul2r -subn1 subn_gt0 q_gt1 /=. Qed. Lemma comp_poly_eq0 p q : size q > 1 -> (p \Po q == 0) = (p == 0). Proof. move=> sq_gt1; rewrite -!lead_coef_eq0 lead_coef_comp //. rewrite mulf_eq0 expf_eq0 !lead_coef_eq0 -[q == 0]size_poly_leq0. by rewrite [_ <= 0]leqNgt (leq_ltn_trans _ sq_gt1) ?andbF ?orbF. Qed. Lemma size_comp_poly2 p q : size q = 2 -> size (p \Po q) = size p. Proof. move=> sq2; have [->|pN0] := eqVneq p 0; first by rewrite comp_polyC. by rewrite polySpred ?size_comp_poly ?comp_poly_eq0 ?sq2 // muln1 polySpred. Qed. Lemma comp_poly2_eq0 p q : size q = 2 -> (p \Po q == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 => /size_comp_poly2->. Qed. Theorem max_poly_roots p rs : p != 0 -> all (root p) rs -> uniq rs -> size rs < size p. Proof. elim: rs p => [p pn0 _ _ | r rs ihrs p pn0] /=; first by rewrite size_poly_gt0. case/andP => rpr arrs /andP [rnrs urs]; case/factor_theorem: rpr => q epq. have [q0 | ?] := eqVneq q 0; first by move: pn0; rewrite epq q0 mul0r eqxx. have -> : size p = (size q).+1. by rewrite epq size_Mmonic ?monicXsubC // size_XsubC addnC. suff /eq_in_all h : {in rs, root q =1 root p} by apply: ihrs => //; rewrite h. move=> x xrs; rewrite epq rootM root_XsubC orbC; case: (eqVneq x r) => // exr. by move: rnrs; rewrite -exr xrs. Qed. Lemma roots_geq_poly_eq0 p (rs : seq R) : all (root p) rs -> uniq rs -> (size rs >= size p)%N -> p = 0. Proof. by move=> ??; apply: contraTeq => ?; rewrite leqNgt max_poly_roots. Qed. End PolynomialIdomain. (* FIXME: these are seamingly artificial ways to close the inheritance graph *) (* We make parameters more and more precise to trigger completion by HB *) HB.instance Definition _ (R : countNzRingType) := [Countable of polynomial R by <:]. HB.instance Definition _ (R : countComNzRingType) := [Countable of polynomial R by <:]. HB.instance Definition _ (R : countIdomainType) := [Countable of polynomial R by <:]. Section MapFieldPoly. Variables (F : fieldType) (R : nzRingType) (f : {rmorphism F -> R}). Local Notation "p ^f" := (map_poly f p) : ring_scope. Lemma size_map_poly p : size p^f = size p. Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite rmorph0 !size_poly0. by rewrite size_poly_eq // fmorph_eq0 // lead_coef_eq0. Qed. Lemma lead_coef_map p : lead_coef p^f = f (lead_coef p). Proof. have [-> | nz_p] := eqVneq p 0; first by rewrite !(rmorph0, lead_coef0). by rewrite lead_coef_map_eq // fmorph_eq0 // lead_coef_eq0. Qed. Lemma map_poly_eq0 p : (p^f == 0) = (p == 0). Proof. by rewrite -!size_poly_eq0 size_map_poly. Qed. Lemma map_poly_inj : injective (map_poly f). Proof. move=> p q eqfpq; apply/eqP; rewrite -subr_eq0 -map_poly_eq0. by rewrite rmorphB /= eqfpq subrr. Qed. Lemma map_monic p : (p^f \is monic) = (p \is monic). Proof. by rewrite [in LHS]monicE lead_coef_map fmorph_eq1. Qed. Lemma map_poly_com p x : comm_poly p^f (f x). Proof. exact: map_comm_poly (mulrC x _). Qed. Lemma fmorph_root p x : root p^f (f x) = root p x. Proof. by rewrite rootE horner_map // fmorph_eq0. Qed. Lemma fmorph_unity_root n z : n.-unity_root (f z) = n.-unity_root z. Proof. by rewrite !unity_rootE -(inj_eq (fmorph_inj f)) rmorphXn ?rmorph1. Qed. Lemma fmorph_primitive_root n z : n.-primitive_root (f z) = n.-primitive_root z. Proof. by congr (_ && _); apply: eq_forallb => i; rewrite fmorph_unity_root. Qed. End MapFieldPoly. Arguments map_poly_inj {F R} f [p1 p2] : rename. Section MaxRoots. Variable R : unitRingType. Implicit Types (x y : R) (rs : seq R) (p : {poly R}). Definition diff_roots (x y : R) := (x * y == y * x) && (y - x \in GRing.unit). Fixpoint uniq_roots rs := if rs is x :: rs' then all (diff_roots x) rs' && uniq_roots rs' else true. Lemma uniq_roots_prod_XsubC p rs : all (root p) rs -> uniq_roots rs -> exists q, p = q * \prod_(z <- rs) ('X - z%:P). Proof. elim: rs => [|z rs IHrs] /=; first by rewrite big_nil; exists p; rewrite mulr1. case/andP=> rpz rprs /andP[drs urs]; case: IHrs => {urs rprs}// q def_p. have [|q' def_q] := factor_theorem q z _; last first. by exists q'; rewrite big_cons mulrA -def_q. rewrite {p}def_p in rpz. elim/last_ind: rs drs rpz => [|rs t IHrs] /=; first by rewrite big_nil mulr1. rewrite all_rcons => /andP[/andP[/eqP czt Uzt] /IHrs{}IHrs]. rewrite -cats1 big_cat big_seq1 /= mulrA rootE hornerM_comm; last first. by rewrite /comm_poly hornerXsubC mulrBl mulrBr czt. rewrite hornerXsubC -opprB mulrN oppr_eq0 -(mul0r (t - z)). by rewrite (inj_eq (mulIr Uzt)) => /IHrs. Qed. Theorem max_ring_poly_roots p rs : p != 0 -> all (root p) rs -> uniq_roots rs -> size rs < size p. Proof. move=> nz_p _ /(@uniq_roots_prod_XsubC p)[// | q def_p]; rewrite def_p in nz_p *. have nz_q: q != 0 by apply: contraNneq nz_p => ->; rewrite mul0r. rewrite size_Mmonic ?monic_prod_XsubC // (polySpred nz_q) addSn /=. by rewrite size_prod_XsubC leq_addl. Qed. Lemma all_roots_prod_XsubC p rs : size p = (size rs).+1 -> all (root p) rs -> uniq_roots rs -> p = lead_coef p *: \prod_(z <- rs) ('X - z%:P). Proof. move=> size_p /uniq_roots_prod_XsubC def_p Urs. case/def_p: Urs => q -> {p def_p} in size_p *. have [q0 | nz_q] := eqVneq q 0; first by rewrite q0 mul0r size_poly0 in size_p. have{q nz_q size_p} /size_poly1P[c _ ->]: size q == 1. rewrite -(eqn_add2r (size rs)) add1n -size_p. by rewrite size_Mmonic ?monic_prod_XsubC // size_prod_XsubC addnS. by rewrite lead_coef_Mmonic ?monic_prod_XsubC // lead_coefC mul_polyC. Qed. End MaxRoots. Section FieldRoots. Variable F : fieldType. Implicit Types (p : {poly F}) (rs : seq F). Lemma poly2_root p : size p = 2 -> {r | root p r}. Proof. case: p => [[|p0 [|p1 []]] //= nz_p1]; exists (- p0 / p1). by rewrite /root addr_eq0 /= mul0r add0r mulrC divfK ?opprK. Qed. Lemma uniq_rootsE rs : uniq_roots rs = uniq rs. Proof. elim: rs => //= r rs ->; congr (_ && _); rewrite -has_pred1 -all_predC. by apply: eq_all => t; rewrite /diff_roots mulrC eqxx unitfE subr_eq0. Qed. Lemma root_ZXsubC (a b r : F) : a != 0 -> root (a *: 'X - b%:P) r = (r == b / a). Proof. move=> a0; rewrite rootE !hornerE. by rewrite -[r in RHS]divr1 eqr_div ?oner_neq0// mulr1 mulrC subr_eq0. Qed. Section UnityRoots. Variable n : nat. Lemma max_unity_roots rs : n > 0 -> all n.-unity_root rs -> uniq rs -> size rs <= n. Proof. move=> n_gt0 rs_n_1 Urs; have szPn := size_XnsubC (1 : F) n_gt0. by rewrite -ltnS -szPn max_poly_roots -?size_poly_eq0 ?szPn. Qed. Lemma mem_unity_roots rs : n > 0 -> all n.-unity_root rs -> uniq rs -> size rs = n -> n.-unity_root =i rs. Proof. move=> n_gt0 rs_n_1 Urs sz_rs_n x; rewrite -topredE /=. apply/idP/idP=> xn1; last exact: (allP rs_n_1). apply: contraFT (ltnn n) => not_rs_x. by rewrite -{1}sz_rs_n (@max_unity_roots (x :: rs)) //= ?xn1 ?not_rs_x. Qed. (* Showing the existence of a primitive root requires the theory in cyclic. *) Variable z : F. Hypothesis prim_z : n.-primitive_root z. Let zn := [seq z ^+ i | i <- index_iota 0 n]. Lemma factor_Xn_sub_1 : \prod_(0 <= i < n) ('X - (z ^+ i)%:P) = 'X^n - 1. Proof. transitivity (\prod_(w <- zn) ('X - w%:P)); first by rewrite big_map. have n_gt0: n > 0 := prim_order_gt0 prim_z. rewrite (@all_roots_prod_XsubC _ ('X^n - 1) zn); first 1 last. - by rewrite size_XnsubC // size_map size_iota subn0. - apply/allP=> _ /mapP[i _ ->] /=; rewrite rootE !hornerE. by rewrite exprAC (prim_expr_order prim_z) expr1n subrr. - rewrite uniq_rootsE map_inj_in_uniq ?iota_uniq // => i j. rewrite !mem_index_iota => ltin ltjn /eqP. by rewrite (eq_prim_root_expr prim_z) !modn_small // => /eqP. by rewrite (monicP (monicXnsubC 1 n_gt0)) scale1r. Qed. Lemma prim_rootP x : x ^+ n = 1 -> {i : 'I_n | x = z ^+ i}. Proof. move=> xn1; pose logx := [pred i : 'I_n | x == z ^+ i]. case: (pickP logx) => [i /eqP-> | no_i]; first by exists i. case: notF; suffices{no_i}: x \in zn. case/mapP=> i; rewrite mem_index_iota => lt_i_n def_x. by rewrite -(no_i (Ordinal lt_i_n)) /= -def_x. rewrite -root_prod_XsubC big_map factor_Xn_sub_1. by rewrite [root _ x]unity_rootE xn1. Qed. End UnityRoots. End FieldRoots. Section MapPolyRoots. Variables (F : fieldType) (R : unitRingType) (f : {rmorphism F -> R}). Lemma map_diff_roots x y : diff_roots (f x) (f y) = (x != y). Proof. rewrite /diff_roots -rmorphB // fmorph_unit // subr_eq0 //. by rewrite rmorph_comm // eqxx eq_sym. Qed. Lemma map_uniq_roots s : uniq_roots (map f s) = uniq s. Proof. elim: s => //= x s ->; congr (_ && _); elim: s => //= y s ->. by rewrite map_diff_roots -negb_or. Qed. End MapPolyRoots. Section AutPolyRoot. (* The action of automorphisms on roots of unity. *) Variable F : fieldType. Implicit Types u v : {rmorphism F -> F}. Lemma aut_prim_rootP u z n : n.-primitive_root z -> {k | coprime k n & u z = z ^+ k}. Proof. move=> prim_z; have:= prim_z; rewrite -(fmorph_primitive_root u) => prim_uz. have [[k _] /= def_uz] := prim_rootP prim_z (prim_expr_order prim_uz). by exists k; rewrite // -(prim_root_exp_coprime _ prim_z) -def_uz. Qed. Lemma aut_unity_rootP u z n : n > 0 -> z ^+ n = 1 -> {k | u z = z ^+ k}. Proof. by move=> _ /prim_order_exists[// | m /(aut_prim_rootP u)[k]]; exists k. Qed. Lemma aut_unity_rootC u v z n : n > 0 -> z ^+ n = 1 -> u (v z) = v (u z). Proof. move=> n_gt0 /(aut_unity_rootP _ n_gt0) def_z. have [[i def_uz] [j def_vz]] := (def_z u, def_z v). by rewrite def_vz def_uz !rmorphXn /= def_vz def_uz exprAC. Qed. End AutPolyRoot. Module UnityRootTheory. Notation "n .-unity_root" := (root_of_unity n) : unity_root_scope. Notation "n .-primitive_root" := (primitive_root_of_unity n) : unity_root_scope. Open Scope unity_root_scope. Definition unity_rootE := unity_rootE. Definition unity_rootP := @unity_rootP. Arguments unity_rootP {R n z}. Definition prim_order_exists := prim_order_exists. Notation prim_order_gt0 := prim_order_gt0. Notation prim_expr_order := prim_expr_order. Definition prim_expr_mod := prim_expr_mod. Definition prim_order_dvd := prim_order_dvd. Definition eq_prim_root_expr := eq_prim_root_expr. Definition rmorph_unity_root := rmorph_unity_root. Definition fmorph_unity_root := fmorph_unity_root. Definition fmorph_primitive_root := fmorph_primitive_root. Definition max_unity_roots := max_unity_roots. Definition mem_unity_roots := mem_unity_roots. Definition prim_rootP := prim_rootP. End UnityRootTheory. Module Export Pdeg2. Module Export Field. Section Pdeg2Field. Variable F : fieldType. Hypothesis nz2 : 2 != 0 :> F. Variable p : {poly F}. Hypothesis degp : size p = 3. Let a := p`_2. Let b := p`_1. Let c := p`_0. Let pneq0 : p != 0. Proof. by rewrite -size_poly_gt0 degp. Qed. Let aneq0 : a != 0. Proof. by move: pneq0; rewrite -lead_coef_eq0 lead_coefE degp. Qed. Let a2neq0 : 2 * a != 0. Proof. by rewrite mulf_neq0. Qed. Let sqa2neq0 : (2 * a) ^+ 2 != 0. Proof. exact: expf_neq0. Qed. Let aa4 : 4 * a * a = (2 * a)^+2. Proof. by rewrite expr2 mulrACA mulrA -natrM. Qed. Let splitr (x : F) : x = x / 2 + x / 2. Proof. by apply: (mulIf nz2); rewrite -mulrDl mulfVK// mulr_natr mulr2n. Qed. Let pE : p = a *: 'X^2 + b *: 'X + c%:P. Proof. apply/polyP => + /[!coefE] => -[|[|[|i]]] /=; rewrite !Monoid.simpm//. by rewrite nth_default// degp. Qed. Let delta := b ^+ 2 - 4 * a * c. Lemma deg2_poly_canonical : p = a *: (('X + (b / (2 * a))%:P)^+2 - (delta / (4 * a ^+ 2))%:P). Proof. rewrite pE sqrrD -!addrA scalerDr; congr +%R; rewrite addrA scalerDr; congr +%R. - rewrite -mulrDr -polyCD -!mul_polyC mulrA mulrAC -polyCM. by rewrite [a * _]mulrC mulrDl invfM -!mulrA mulVf// mulr1 -splitr. - rewrite [a ^+ 2]expr2 mulrA aa4 -polyC_exp -polyCB expr_div_n -mulrBl subKr. by rewrite scale_polyC mulrCA mulrACA aa4 mulrCA mulfV// mulr1. Qed. Variable r : F. Hypothesis r_sqrt_delta : r ^+ 2 = delta. Let r1 := (- b - r) / (2 * a). Let r2 := (- b + r) / (2 * a). Lemma deg2_poly_factor : p = a *: ('X - r1%:P) * ('X - r2%:P). Proof. rewrite [p]deg2_poly_canonical//= -/a -/b -/c -/delta /r1 /r2. rewrite ![(- b + _) * _]mulrDl 2!polyCD 2!opprD 2!addrA !mulNr !polyCN !opprK. rewrite -scalerAl [in RHS]mulrC -subr_sqr -polyC_exp -[4]/(2 * 2)%:R natrM. by rewrite -expr2 -exprMn [in RHS]exprMn exprVn r_sqrt_delta. Qed. Lemma deg2_poly_root1 : root p r1. Proof. apply/factor_theorem. by exists (a *: ('X - r2%:P)); rewrite deg2_poly_factor -!scalerAl mulrC. Qed. Lemma deg2_poly_root2 : root p r2. Proof. apply/factor_theorem. by exists (a *: ('X - r1%:P)); rewrite deg2_poly_factor -!scalerAl. Qed. End Pdeg2Field. End Field. Module FieldMonic. Section Pdeg2FieldMonic. Variable F : fieldType. Hypothesis nz2 : 2 != 0 :> F. Variable p : {poly F}. Hypothesis degp : size p = 3. Hypothesis monicp : p \is monic. Let a := p`_2. Let b := p`_1. Let c := p`_0. Let a1 : a = 1. Proof. by move: (monicP monicp); rewrite lead_coefE degp. Qed. Let delta := b ^+ 2 - 4 * c. Lemma deg2_poly_canonical : p = (('X + (b / 2)%:P)^+2 - (delta / 4)%:P). Proof. by rewrite [p]deg2_poly_canonical// -/a a1 scale1r expr1n !mulr1. Qed. Variable r : F. Hypothesis r_sqrt_delta : r ^+ 2 = delta. Let r1 := (- b - r) / 2. Let r2 := (- b + r) / 2. Lemma deg2_poly_factor : p = ('X - r1%:P) * ('X - r2%:P). Proof. by rewrite [p](@deg2_poly_factor _ _ _ _ r)// -/a a1 !mulr1 ?scale1r. Qed. Lemma deg2_poly_root1 : root p r1. Proof. rewrite /r1 -[2]mulr1 -[X in 2 * X]a1. by apply: deg2_poly_root1; rewrite // -/a a1 mulr1. Qed. Lemma deg2_poly_root2 : root p r2. Proof. rewrite /r2 -[2]mulr1 -[X in 2 * X]a1. by apply: deg2_poly_root2; rewrite // -/a a1 mulr1. Qed. End Pdeg2FieldMonic. End FieldMonic. End Pdeg2. Section DecField. Variable F : decFieldType. Lemma dec_factor_theorem (p : {poly F}) : {s : seq F & {q : {poly F} | p = q * \prod_(x <- s) ('X - x%:P) /\ (q != 0 -> forall x, ~~ root q x)}}. Proof. pose polyT (p : seq F) := (foldr (fun c f => f * 'X_0 + c%:T) (0%R)%:T p)%T. have eval_polyT (q : {poly F}) x : GRing.eval [:: x] (polyT q) = q.[x]. by rewrite /horner; elim: (val q) => //= ? ? ->. have [n] := ubnP (size p); elim: n => // n IHn in p *. have /decPcases /= := @satP F [::] ('exists 'X_0, polyT p == 0%T). case: ifP => [_ /sig_eqW[x]|_ noroot]; last first. exists [::], p; rewrite big_nil mulr1; split => // p_neq0 x. by apply/negP=> /rootP rpx; apply: noroot; exists x; rewrite eval_polyT. rewrite eval_polyT => /rootP/factor_theorem/sig_eqW[p1 ->]. have [->|nz_p1] := eqVneq p1 0; first by exists [::], 0; rewrite !mul0r eqxx. rewrite size_Mmonic ?monicXsubC // size_XsubC addn2 => /IHn[s [q [-> irr_q]]]. by exists (rcons s x), q; rewrite -cats1 big_cat big_seq1 mulrA. Qed. End DecField. Module PreClosedField. Section UseAxiom. Variable F : fieldType. Hypothesis closedF : GRing.closed_field_axiom F. Implicit Type p : {poly F}. Lemma closed_rootP p : reflect (exists x, root p x) (size p != 1). Proof. have [-> | nz_p] := eqVneq p 0. by rewrite size_poly0; left; exists 0; rewrite root0. rewrite neq_ltn [in _ < 1]polySpred //=. apply: (iffP idP) => [p_gt1 | [a]]; last exact: root_size_gt1. pose n := (size p).-1; have n_gt0: n > 0 by rewrite -ltnS -polySpred. have [a Dan] := closedF (fun i => - p`_i / lead_coef p) n_gt0. exists a; apply/rootP; rewrite horner_coef polySpred // big_ord_recr /= -/n. rewrite {}Dan mulr_sumr -big_split big1 //= => i _. by rewrite -!mulrA mulrCA mulNr mulVKf ?subrr ?lead_coef_eq0. Qed. Lemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0). Proof. apply: (iffP idP) => [nz_p | [x]]; last first. by apply: contraNneq => ->; apply: root0. have [[x /rootP p1x0]|] := altP (closed_rootP (p - 1)). by exists x; rewrite -[p](subrK 1) /root hornerD p1x0 add0r hornerC oner_eq0. rewrite negbK => /size_poly1P[c _ /(canRL (subrK 1)) Dp]. by exists 0; rewrite Dp -raddfD polyC_eq0 rootC in nz_p *. Qed. End UseAxiom. End PreClosedField. Section ClosedField. Variable F : closedFieldType. Implicit Type p : {poly F}. Let closedF := @solve_monicpoly F. Lemma closed_rootP p : reflect (exists x, root p x) (size p != 1). Proof. exact: PreClosedField.closed_rootP. Qed. Lemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0). Proof. exact: PreClosedField.closed_nonrootP. Qed. Lemma closed_field_poly_normal p : {r : seq F | p = lead_coef p *: \prod_(z <- r) ('X - z%:P)}. Proof. apply: sig_eqW; have [r [q [->]]] /= := dec_factor_theorem p. have [->|] := eqVneq; first by exists [::]; rewrite mul0r lead_coef0 scale0r. have [[x rqx ? /(_ isT x) /negP /(_ rqx)] //|] := altP (closed_rootP q). rewrite negbK => /size_poly1P [c c_neq0-> _ _]; exists r. rewrite mul_polyC lead_coefZ (monicP _) ?mulr1 //. by rewrite monic_prod => // i; rewrite monicXsubC. Qed. End ClosedField.
Congruence.lean
/- Copyright (c) 2024 Jovan Gerbscheid. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jovan Gerbscheid, Newell Jensen -/ import Mathlib.Topology.MetricSpace.Pseudo.Defs /-! # Congruences This file defines `Congruent`, i.e., the equivalence between indexed families of points in a metric space where all corresponding pairwise distances are the same. The motivating example are triangles in the plane. ## Implementation notes After considering two possible approaches to defining congruence — either based on equal pairwise distances or the existence of an isometric equivalence — we have opted for the broader concept of equal pairwise distances. This notion is commonly employed in the literature across various metric spaces that lack an isometric equivalence. For more details see the [Zulip discussion](https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there-code-for-X.3F/topic/Euclidean.20Geometry). ## Notation * `v₁ ≅ v₂`: for `Congruent v₁ v₂`. -/ variable {ι ι' : Type*} {P₁ P₂ P₃ : Type*} {v₁ : ι → P₁} {v₂ : ι → P₂} {v₃ : ι → P₃} section PseudoEMetricSpace variable [PseudoEMetricSpace P₁] [PseudoEMetricSpace P₂] [PseudoEMetricSpace P₃] /-- A congruence between indexed sets of vertices v₁ and v₂. Use `open scoped Congruent` to access the `v₁ ≅ v₂` notation. -/ def Congruent (v₁ : ι → P₁) (v₂ : ι → P₂) : Prop := ∀ i₁ i₂, edist (v₁ i₁) (v₁ i₂) = edist (v₂ i₁) (v₂ i₂) @[inherit_doc] scoped[Congruent] infixl:25 " ≅ " => Congruent /-- Congruence holds if and only if all extended distances are the same. -/ lemma congruent_iff_edist_eq : Congruent v₁ v₂ ↔ ∀ i₁ i₂, edist (v₁ i₁) (v₁ i₂) = edist (v₂ i₁) (v₂ i₂) := Iff.rfl /-- Congruence holds if and only if all extended distances between points with different indices are the same. -/ lemma congruent_iff_pairwise_edist_eq : Congruent v₁ v₂ ↔ Pairwise fun i₁ i₂ ↦ edist (v₁ i₁) (v₁ i₂) = edist (v₂ i₁) (v₂ i₂) := by refine ⟨fun h ↦ fun _ _ _ ↦ h _ _, fun h ↦ fun i₁ i₂ ↦ ?_⟩ by_cases hi : i₁ = i₂ · simp [hi] · exact h hi namespace Congruent /-- A congruence preserves extended distance. Forward direction of `congruent_iff_edist_eq`. -/ alias ⟨edist_eq, _⟩ := congruent_iff_edist_eq /-- Congruence follows from preserved extended distance. Backward direction of `congruent_iff_edist_eq`. -/ alias ⟨_, of_edist_eq⟩ := congruent_iff_edist_eq /-- A congruence pairwise preserves extended distance. Forward direction of `congruent_iff_pairwise_edist_eq`. -/ alias ⟨pairwise_edist_eq, _⟩ := congruent_iff_pairwise_edist_eq /-- Congruence follows from pairwise preserved extended distance. Backward direction of `congruent_iff_pairwise_edist_eq`. -/ alias ⟨_, of_pairwise_edist_eq⟩ := congruent_iff_pairwise_edist_eq @[refl] protected lemma refl (v₁ : ι → P₁) : v₁ ≅ v₁ := fun _ _ ↦ rfl @[symm] protected lemma symm (h : v₁ ≅ v₂) : v₂ ≅ v₁ := fun i₁ i₂ ↦ (h i₁ i₂).symm lemma _root_.congruent_comm : v₁ ≅ v₂ ↔ v₂ ≅ v₁ := ⟨Congruent.symm, Congruent.symm⟩ @[trans] protected lemma trans (h₁₂ : v₁ ≅ v₂) (h₂₃ : v₂ ≅ v₃) : v₁ ≅ v₃ := fun i₁ i₂ ↦ (h₁₂ i₁ i₂).trans (h₂₃ i₁ i₂) /-- Change the index set ι to an index ι' that maps to ι. -/ lemma index_map (h : v₁ ≅ v₂) (f : ι' → ι) : (v₁ ∘ f) ≅ (v₂ ∘ f) := fun i₁ i₂ ↦ edist_eq h (f i₁) (f i₂) /-- Change between equivalent index sets ι and ι'. -/ @[simp] lemma index_equiv {E : Type*} [EquivLike E ι' ι] (f : E) (v₁ : ι → P₁) (v₂ : ι → P₂) : v₁ ∘ f ≅ v₂ ∘ f ↔ v₁ ≅ v₂ := by refine ⟨fun h i₁ i₂ ↦ ?_, fun h ↦ index_map h f⟩ simpa [(EquivLike.toEquiv f).right_inv i₁, (EquivLike.toEquiv f).right_inv i₂] using edist_eq h ((EquivLike.toEquiv f).symm i₁) ((EquivLike.toEquiv f).symm i₂) end Congruent end PseudoEMetricSpace section PseudoMetricSpace variable [PseudoMetricSpace P₁] [PseudoMetricSpace P₂] /-- Congruence holds if and only if all non-negative distances are the same. -/ lemma congruent_iff_nndist_eq : Congruent v₁ v₂ ↔ ∀ i₁ i₂, nndist (v₁ i₁) (v₁ i₂) = nndist (v₂ i₁) (v₂ i₂) := forall₂_congr (fun _ _ ↦ by rw [edist_nndist, edist_nndist]; norm_cast) /-- Congruence holds if and only if all non-negative distances between points with different indices are the same. -/ lemma congruent_iff_pairwise_nndist_eq : Congruent v₁ v₂ ↔ Pairwise fun i₁ i₂ ↦ nndist (v₁ i₁) (v₁ i₂) = nndist (v₂ i₁) (v₂ i₂) := by simp_rw [congruent_iff_pairwise_edist_eq, edist_nndist] exact_mod_cast Iff.rfl /-- Congruence holds if and only if all distances are the same. -/ lemma congruent_iff_dist_eq : Congruent v₁ v₂ ↔ ∀ i₁ i₂, dist (v₁ i₁) (v₁ i₂) = dist (v₂ i₁) (v₂ i₂) := congruent_iff_nndist_eq.trans (forall₂_congr (fun _ _ ↦ by rw [dist_nndist, dist_nndist]; norm_cast)) /-- Congruence holds if and only if all non-negative distances between points with different indices are the same. -/ lemma congruent_iff_pairwise_dist_eq : Congruent v₁ v₂ ↔ Pairwise fun i₁ i₂ ↦ dist (v₁ i₁) (v₁ i₂) = dist (v₂ i₁) (v₂ i₂) := by simp_rw [congruent_iff_pairwise_nndist_eq, dist_nndist] exact_mod_cast Iff.rfl namespace Congruent /-- A congruence preserves non-negative distance. Forward direction of `congruent_iff_nndist_eq`. -/ alias ⟨nndist_eq, _⟩ := congruent_iff_nndist_eq /-- Congruence follows from preserved non-negative distance. Backward direction of `congruent_iff_nndist_eq`. -/ alias ⟨_, of_nndist_eq⟩ := congruent_iff_nndist_eq /-- A congruence preserves distance. Forward direction of `congruent_iff_dist_eq`. -/ alias ⟨dist_eq, _⟩ := congruent_iff_dist_eq /-- Congruence follows from preserved distance. Backward direction of `congruent_iff_dist_eq`. -/ alias ⟨_, of_dist_eq⟩ := congruent_iff_dist_eq /-- A congruence pairwise preserves non-negative distance. Forward direction of `congruent_iff_pairwise_nndist_eq`. -/ alias ⟨pairwise_nndist_eq, _⟩ := congruent_iff_pairwise_nndist_eq /-- Congruence follows from pairwise preserved non-negative distance. Backward direction of `congruent_iff_pairwise_nndist_eq`. -/ alias ⟨_, of_pairwise_nndist_eq⟩ := congruent_iff_pairwise_nndist_eq /-- A congruence pairwise preserves distance. Forward direction of `congruent_iff_pairwise_dist_eq`. -/ alias ⟨pairwise_dist_eq, _⟩ := congruent_iff_pairwise_dist_eq /-- Congruence follows from pairwise preserved distance. Backward direction of `congruent_iff_pairwise_dist_eq`. -/ alias ⟨_, of_pairwise_dist_eq⟩ := congruent_iff_pairwise_dist_eq end Congruent end PseudoMetricSpace
ToReal.lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Data.Real.Sqrt import Mathlib.NumberTheory.Zsqrtd.Basic /-! # Image of `Zsqrtd` in `ℝ` This file defines `Zsqrtd.toReal` and related lemmas. It is in a separate file to avoid pulling in all of `Data.Real` into `Data.Zsqrtd`. -/ namespace Zsqrtd /-- The image of `Zsqrtd` in `ℝ`, using `Real.sqrt` which takes the positive root of `d`. If the negative root is desired, use `toReal h (star a)`. -/ @[simps!] noncomputable def toReal {d : ℤ} (h : 0 ≤ d) : ℤ√d →+* ℝ := lift ⟨√↑d, Real.mul_self_sqrt (Int.cast_nonneg.mpr h)⟩ theorem toReal_injective {d : ℤ} (h0d : 0 ≤ d) (hd : ∀ n : ℤ, d ≠ n * n) : Function.Injective (toReal h0d) := lift_injective _ hd end Zsqrtd
imset2_finset.v
From mathcomp Require Import all_boot. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Check @imset2_pair.
PartitionOfUnity.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.PartitionOfUnity import Mathlib.Analysis.Convex.Combination /-! # Partition of unity and convex sets In this file we prove the following lemma, see `exists_continuous_forall_mem_convex_of_local`. Let `X` be a normal paracompact topological space (e.g., any extended metric space). Let `E` be a topological real vector space. Let `t : X → Set E` be a family of convex sets. Suppose that for each point `x : X`, there exists a neighborhood `U ∈ 𝓝 X` and a function `g : X → E` that is continuous on `U` and sends each `y ∈ U` to a point of `t y`. Then there exists a continuous map `g : C(X, E)` such that `g x ∈ t x` for all `x`. We also formulate a useful corollary, see `exists_continuous_forall_mem_convex_of_local_const`, that assumes that local functions `g` are constants. ## Tags partition of unity -/ open Set Function open Topology variable {ι X E : Type*} [TopologicalSpace X] [AddCommGroup E] [Module ℝ E] theorem PartitionOfUnity.finsum_smul_mem_convex {s : Set X} (f : PartitionOfUnity ι X s) {g : ι → X → E} {t : Set E} {x : X} (hx : x ∈ s) (hg : ∀ i, f i x ≠ 0 → g i x ∈ t) (ht : Convex ℝ t) : (∑ᶠ i, f i x • g i x) ∈ t := ht.finsum_mem (fun _ => f.nonneg _ _) (f.sum_eq_one hx) hg variable [NormalSpace X] [ParacompactSpace X] [TopologicalSpace E] [ContinuousAdd E] [ContinuousSMul ℝ E] {t : X → Set E} /-- Let `X` be a normal paracompact topological space (e.g., any extended metric space). Let `E` be a topological real vector space. Let `t : X → Set E` be a family of convex sets. Suppose that for each point `x : X`, there exists a neighborhood `U ∈ 𝓝 X` and a function `g : X → E` that is continuous on `U` and sends each `y ∈ U` to a point of `t y`. Then there exists a continuous map `g : C(X, E)` such that `g x ∈ t x` for all `x`. See also `exists_continuous_forall_mem_convex_of_local_const`. -/ theorem exists_continuous_forall_mem_convex_of_local (ht : ∀ x, Convex ℝ (t x)) (H : ∀ x : X, ∃ U ∈ 𝓝 x, ∃ g : X → E, ContinuousOn g U ∧ ∀ y ∈ U, g y ∈ t y) : ∃ g : C(X, E), ∀ x, g x ∈ t x := by choose U hU g hgc hgt using H obtain ⟨f, hf⟩ := PartitionOfUnity.exists_isSubordinate isClosed_univ (fun x => interior (U x)) (fun x => isOpen_interior) fun x _ => mem_iUnion.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩ refine ⟨⟨fun x => ∑ᶠ i, f i x • g i x, hf.continuous_finsum_smul (fun i => isOpen_interior) fun i => (hgc i).mono interior_subset⟩, fun x => f.finsum_smul_mem_convex (mem_univ x) (fun i hi => hgt _ _ ?_) (ht _)⟩ exact interior_subset (hf _ <| subset_closure hi) /-- Let `X` be a normal paracompact topological space (e.g., any extended metric space). Let `E` be a topological real vector space. Let `t : X → Set E` be a family of convex sets. Suppose that for each point `x : X`, there exists a vector `c : E` that belongs to `t y` for all `y` in a neighborhood of `x`. Then there exists a continuous map `g : C(X, E)` such that `g x ∈ t x` for all `x`. See also `exists_continuous_forall_mem_convex_of_local`. -/ theorem exists_continuous_forall_mem_convex_of_local_const (ht : ∀ x, Convex ℝ (t x)) (H : ∀ x : X, ∃ c : E, ∀ᶠ y in 𝓝 x, c ∈ t y) : ∃ g : C(X, E), ∀ x, g x ∈ t x := exists_continuous_forall_mem_convex_of_local ht fun x => let ⟨c, hc⟩ := H x ⟨_, hc, fun _ => c, continuousOn_const, fun _ => id⟩
Subsemiring.lean
/- Copyright (c) 2024 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import Mathlib.Algebra.Star.NonUnitalSubsemiring import Mathlib.Algebra.Ring.Subsemiring.Basic /-! # Star subrings A *-subring is a subring of a *-ring which is closed under *. -/ universe v /-- A (unital) star subsemiring is a non-associative ring which is closed under the `star` operation. -/ structure StarSubsemiring (R : Type v) [NonAssocSemiring R] [Star R] : Type v extends Subsemiring R where /-- The `carrier` of a `StarSubsemiring` is closed under the `star` operation. -/ star_mem' {a} : a ∈ carrier → star a ∈ carrier section StarSubsemiring namespace StarSubsemiring /-- Reinterpret a `StarSubsemiring` as a `Subsemiring`. -/ add_decl_doc StarSubsemiring.toSubsemiring instance setLike {R : Type v} [NonAssocSemiring R] [Star R] : SetLike (StarSubsemiring R) R where coe {s} := s.carrier coe_injective' p q h := by obtain ⟨⟨⟨⟨_, _⟩, _⟩, _⟩, _⟩ := p; cases q; congr initialize_simps_projections StarSubsemiring (carrier → coe, as_prefix coe) variable {R : Type v} [NonAssocSemiring R] [StarRing R] /-- The actual `StarSubsemiring` obtained from an element of a `StarSubsemiringClass`. -/ @[simps] def ofClass {S R : Type*} [NonAssocSemiring R] [SetLike S R] [StarRing R] [SubsemiringClass S R] [StarMemClass S R] (s : S) : StarSubsemiring R where carrier := s add_mem' := add_mem zero_mem' := zero_mem _ mul_mem' := mul_mem one_mem' := one_mem _ star_mem' := star_mem instance (priority := 100) : CanLift (Set R) (StarSubsemiring R) (↑) (fun s ↦ 0 ∈ s ∧ (∀ {x y}, x ∈ s → y ∈ s → x + y ∈ s) ∧ 1 ∈ s ∧ (∀ {x y}, x ∈ s → y ∈ s → x * y ∈ s) ∧ (∀ {x}, x ∈ s → star x ∈ s)) where prf s h := ⟨ { carrier := s zero_mem' := h.1 add_mem' := h.2.1 one_mem' := h.2.2.1 mul_mem' := h.2.2.2.1 star_mem' := h.2.2.2.2 }, rfl ⟩ instance starMemClass : StarMemClass (StarSubsemiring R) R where star_mem {s} := s.star_mem' instance subsemiringClass : SubsemiringClass (StarSubsemiring R) R where add_mem {s} := s.add_mem' mul_mem {s} := s.mul_mem' zero_mem {s} := s.zero_mem' one_mem {s} := s.one_mem' -- this uses the `Star` instance `s` inherits from `StarMemClass (StarSubsemiring R A) A` instance starRing (s : StarSubsemiring R) : StarRing s := { StarMemClass.instStar s with star_involutive := fun r => Subtype.ext (star_star (r : R)) star_mul := fun r₁ r₂ => Subtype.ext (star_mul (r₁ : R) (r₂ : R)) star_add := fun r₁ r₂ => Subtype.ext (star_add (r₁ : R) (r₂ : R)) } instance semiring (s : StarSubsemiring R) : NonAssocSemiring s := s.toSubsemiring.toNonAssocSemiring theorem mem_carrier {s : StarSubsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := Iff.rfl @[ext] theorem ext {S T : StarSubsemiring R} (h : ∀ x : R, x ∈ S ↔ x ∈ T) : S = T := SetLike.ext h @[simp] lemma coe_mk (S : Subsemiring R) (h) : ((⟨S, h⟩ : StarSubsemiring R) : Set R) = S := rfl @[simp] theorem mem_toSubsemiring {S : StarSubsemiring R} {x} : x ∈ S.toSubsemiring ↔ x ∈ S := Iff.rfl @[simp] theorem coe_toSubsemiring (S : StarSubsemiring R) : (S.toSubsemiring : Set R) = S := rfl theorem toSubsemiring_injective : Function.Injective (toSubsemiring : StarSubsemiring R → Subsemiring R) := fun S T h => ext fun x => by rw [← mem_toSubsemiring, ← mem_toSubsemiring, h] theorem toSubsemiring_inj {S U : StarSubsemiring R} : S.toSubsemiring = U.toSubsemiring ↔ S = U := toSubsemiring_injective.eq_iff theorem toSubsemiring_le_iff {S₁ S₂ : StarSubsemiring R} : S₁.toSubsemiring ≤ S₂.toSubsemiring ↔ S₁ ≤ S₂ := Iff.rfl /-- Copy of a non-unital star subalgebra with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : StarSubsemiring R) (s : Set R) (hs : s = ↑S) : StarSubsemiring R where toSubsemiring := Subsemiring.copy S.toSubsemiring s hs star_mem' := @fun a ha => hs ▸ (S.star_mem' (by simpa [hs] using ha) : star a ∈ (S : Set R)) @[simp] theorem coe_copy (S : StarSubsemiring R) (s : Set R) (hs : s = ↑S) : (S.copy s hs : Set R) = s := rfl theorem copy_eq (S : StarSubsemiring R) (s : Set R) (hs : s = ↑S) : S.copy s hs = S := SetLike.coe_injective hs section Center variable (R) /-- The center of a semiring `R` is the set of elements that commute and associate with everything in `R` -/ def center (R) [NonAssocSemiring R] [StarRing R] : StarSubsemiring R where toSubsemiring := Subsemiring.center R star_mem' := Set.star_mem_center end Center end StarSubsemiring end StarSubsemiring section SubStarSemigroup variable (A) [Mul A] [StarMul A] namespace SubStarSemigroup /-- The center of magma `A` is the set of elements that commute and associate with everything in `A`, here realized as a `SubStarSemigroup`. -/ def center : SubStarSemigroup A := { Subsemigroup.center A with star_mem' := Set.star_mem_center } end SubStarSemigroup end SubStarSemigroup
ContinuousMaps.lean
/- Copyright (c) 2024 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import Mathlib.Topology.ContinuousMap.Compact import Mathlib.Topology.MetricSpace.Ultra.Basic /-! # Ultrametric structure on continuous maps -/ /-- Continuous maps from a compact space to an ultrametric space are an ultrametric space. -/ instance ContinuousMap.isUltrametricDist {X Y : Type*} [TopologicalSpace X] [CompactSpace X] [MetricSpace Y] [IsUltrametricDist Y] : IsUltrametricDist C(X, Y) := by constructor intro f g h rw [ContinuousMap.dist_le (by positivity)] refine fun x ↦ (dist_triangle_max (f x) (g x) (h x)).trans (max_le_max ?_ ?_) <;> exact ContinuousMap.dist_apply_le_dist x
Pointwise.lean
/- Copyright (c) 2021 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Yaël Dillies -/ import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.Group.Pointwise.Set.Scalar import Mathlib.Algebra.GroupWithZero.Action.Defs import Mathlib.Algebra.Order.GroupWithZero.Unbundled.OrderIso import Mathlib.Algebra.Order.Ring.Defs import Mathlib.Order.Interval.Set.OrderIso /-! # Pointwise operations on ordered algebraic objects This file contains lemmas about the effect of pointwise operations on sets with an order structure. -/ open Function Set open scoped Pointwise namespace LinearOrderedField variable {K : Type*} [Field K] [LinearOrder K] [IsStrictOrderedRing K] {a b r : K} (hr : 0 < r) include hr theorem smul_Ioo : r • Ioo a b = Ioo (r * a) (r * b) := (OrderIso.mulLeft₀ r hr).image_Ioo a b theorem smul_Icc : r • Icc a b = Icc (r * a) (r * b) := (OrderIso.mulLeft₀ r hr).image_Icc a b theorem smul_Ico : r • Ico a b = Ico (r * a) (r * b) := (OrderIso.mulLeft₀ r hr).image_Ico a b theorem smul_Ioc : r • Ioc a b = Ioc (r * a) (r * b) := (OrderIso.mulLeft₀ r hr).image_Ioc a b theorem smul_Ioi : r • Ioi a = Ioi (r * a) := (OrderIso.mulLeft₀ r hr).image_Ioi a theorem smul_Iio : r • Iio a = Iio (r * a) := (OrderIso.mulLeft₀ r hr).image_Iio a theorem smul_Ici : r • Ici a = Ici (r * a) := (OrderIso.mulLeft₀ r hr).image_Ici a theorem smul_Iic : r • Iic a = Iic (r * a) := (OrderIso.mulLeft₀ r hr).image_Iic a end LinearOrderedField
MonoCoprod.lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.ConcreteCategory.Basic import Mathlib.CategoryTheory.Limits.Preserves.Shapes.BinaryProducts import Mathlib.CategoryTheory.Limits.Shapes.RegularMono import Mathlib.CategoryTheory.Limits.Shapes.ZeroMorphisms /-! # Categories where inclusions into coproducts are monomorphisms If `C` is a category, the class `MonoCoprod C` expresses that left inclusions `A ⟶ A ⨿ B` are monomorphisms when `HasCoproduct A B` is satisfied. If it is so, it is shown that right inclusions are also monomorphisms. More generally, we deduce that when suitable coproducts exists, then if `X : I → C` and `ι : J → I` is an injective map, then the canonical morphism `∐ (X ∘ ι) ⟶ ∐ X` is a monomorphism. It also follows that for any `i : I`, `Sigma.ι X i : X i ⟶ ∐ X` is a monomorphism. TODO: define distributive categories, and show that they satisfy `MonoCoprod`, see <https://ncatlab.org/toddtrimble/published/distributivity+implies+monicity+of+coproduct+inclusions> -/ noncomputable section universe u namespace CategoryTheory open CategoryTheory.Category CategoryTheory.Limits namespace Limits variable (C : Type*) [Category C] /-- This condition expresses that inclusion morphisms into coproducts are monomorphisms. -/ class MonoCoprod : Prop where /-- the left inclusion of a colimit binary cofan is mono -/ binaryCofan_inl : ∀ ⦃A B : C⦄ (c : BinaryCofan A B) (_ : IsColimit c), Mono c.inl variable {C} instance (priority := 100) monoCoprodOfHasZeroMorphisms [HasZeroMorphisms C] : MonoCoprod C := ⟨fun A B c hc => by haveI : IsSplitMono c.inl := IsSplitMono.mk' (SplitMono.mk (hc.desc (BinaryCofan.mk (𝟙 A) 0)) (IsColimit.fac _ _ _)) infer_instance⟩ namespace MonoCoprod theorem binaryCofan_inr {A B : C} [MonoCoprod C] (c : BinaryCofan A B) (hc : IsColimit c) : Mono c.inr := by haveI hc' : IsColimit (BinaryCofan.mk c.inr c.inl) := BinaryCofan.IsColimit.mk _ (fun f₁ f₂ => hc.desc (BinaryCofan.mk f₂ f₁)) (by simp) (by simp) (fun f₁ f₂ m h₁ h₂ => BinaryCofan.IsColimit.hom_ext hc (by cat_disch) (by cat_disch)) exact binaryCofan_inl _ hc' instance {A B : C} [MonoCoprod C] [HasBinaryCoproduct A B] : Mono (coprod.inl : A ⟶ A ⨿ B) := binaryCofan_inl _ (colimit.isColimit _) instance {A B : C} [MonoCoprod C] [HasBinaryCoproduct A B] : Mono (coprod.inr : B ⟶ A ⨿ B) := binaryCofan_inr _ (colimit.isColimit _) theorem mono_inl_iff {A B : C} {c₁ c₂ : BinaryCofan A B} (hc₁ : IsColimit c₁) (hc₂ : IsColimit c₂) : Mono c₁.inl ↔ Mono c₂.inl := by suffices ∀ (c₁ c₂ : BinaryCofan A B) (_ : IsColimit c₁) (_ : IsColimit c₂) (_ : Mono c₁.inl), Mono c₂.inl by exact ⟨fun h₁ => this _ _ hc₁ hc₂ h₁, fun h₂ => this _ _ hc₂ hc₁ h₂⟩ intro c₁ c₂ hc₁ hc₂ intro simpa only [IsColimit.comp_coconePointUniqueUpToIso_hom] using mono_comp c₁.inl (hc₁.coconePointUniqueUpToIso hc₂).hom theorem mk' (h : ∀ A B : C, ∃ (c : BinaryCofan A B) (_ : IsColimit c), Mono c.inl) : MonoCoprod C := ⟨fun A B c' hc' => by obtain ⟨c, hc₁, hc₂⟩ := h A B simpa only [mono_inl_iff hc' hc₁] using hc₂⟩ instance monoCoprodType : MonoCoprod (Type u) := MonoCoprod.mk' fun A B => by refine ⟨BinaryCofan.mk (Sum.inl : A ⟶ A ⊕ B) Sum.inr, ?_, ?_⟩ · exact BinaryCofan.IsColimit.mk _ (fun f₁ f₂ x => by rcases x with x | x exacts [f₁ x, f₂ x]) (fun f₁ f₂ => by rfl) (fun f₁ f₂ => by rfl) (fun f₁ f₂ m h₁ h₂ => by funext x rcases x with x | x · exact congr_fun h₁ x · exact congr_fun h₂ x) · rw [mono_iff_injective] intro a₁ a₂ h simpa using h section variable {I₁ I₂ : Type*} {X : I₁ ⊕ I₂ → C} (c : Cofan X) (c₁ : Cofan (X ∘ Sum.inl)) (c₂ : Cofan (X ∘ Sum.inr)) (hc : IsColimit c) (hc₁ : IsColimit c₁) (hc₂ : IsColimit c₂) include hc hc₁ hc₂ /-- Given a family of objects `X : I₁ ⊕ I₂ → C`, a cofan of `X`, and two colimit cofans of `X ∘ Sum.inl` and `X ∘ Sum.inr`, this is a cofan for `c₁.pt` and `c₂.pt` whose point is `c.pt`. -/ @[simp] def binaryCofanSum : BinaryCofan c₁.pt c₂.pt := BinaryCofan.mk (Cofan.IsColimit.desc hc₁ (fun i₁ => c.inj (Sum.inl i₁))) (Cofan.IsColimit.desc hc₂ (fun i₂ => c.inj (Sum.inr i₂))) /-- The binary cofan `binaryCofanSum c c₁ c₂ hc₁ hc₂` is colimit. -/ def isColimitBinaryCofanSum : IsColimit (binaryCofanSum c c₁ c₂ hc₁ hc₂) := BinaryCofan.IsColimit.mk _ (fun f₁ f₂ => Cofan.IsColimit.desc hc (fun i => match i with | Sum.inl i₁ => c₁.inj i₁ ≫ f₁ | Sum.inr i₂ => c₂.inj i₂ ≫ f₂)) (fun f₁ f₂ => Cofan.IsColimit.hom_ext hc₁ _ _ (by simp)) (fun f₁ f₂ => Cofan.IsColimit.hom_ext hc₂ _ _ (by simp)) (fun f₁ f₂ m hm₁ hm₂ => by apply Cofan.IsColimit.hom_ext hc rintro (i₁|i₂) <;> cat_disch) lemma mono_binaryCofanSum_inl [MonoCoprod C] : Mono (binaryCofanSum c c₁ c₂ hc₁ hc₂).inl := MonoCoprod.binaryCofan_inl _ (isColimitBinaryCofanSum c c₁ c₂ hc hc₁ hc₂) lemma mono_binaryCofanSum_inr [MonoCoprod C] : Mono (binaryCofanSum c c₁ c₂ hc₁ hc₂).inr := MonoCoprod.binaryCofan_inr _ (isColimitBinaryCofanSum c c₁ c₂ hc hc₁ hc₂) lemma mono_binaryCofanSum_inl' [MonoCoprod C] (inl : c₁.pt ⟶ c.pt) (hinl : ∀ (i₁ : I₁), c₁.inj i₁ ≫ inl = c.inj (Sum.inl i₁)) : Mono inl := by suffices inl = (binaryCofanSum c c₁ c₂ hc₁ hc₂).inl by rw [this] exact MonoCoprod.binaryCofan_inl _ (isColimitBinaryCofanSum c c₁ c₂ hc hc₁ hc₂) exact Cofan.IsColimit.hom_ext hc₁ _ _ (by simpa using hinl) lemma mono_binaryCofanSum_inr' [MonoCoprod C] (inr : c₂.pt ⟶ c.pt) (hinr : ∀ (i₂ : I₂), c₂.inj i₂ ≫ inr = c.inj (Sum.inr i₂)) : Mono inr := by suffices inr = (binaryCofanSum c c₁ c₂ hc₁ hc₂).inr by rw [this] exact MonoCoprod.binaryCofan_inr _ (isColimitBinaryCofanSum c c₁ c₂ hc hc₁ hc₂) exact Cofan.IsColimit.hom_ext hc₂ _ _ (by simpa using hinr) end section variable [MonoCoprod C] {I J : Type*} (X : I → C) (ι : J → I) lemma mono_of_injective_aux (hι : Function.Injective ι) (c : Cofan X) (c₁ : Cofan (X ∘ ι)) (hc : IsColimit c) (hc₁ : IsColimit c₁) (c₂ : Cofan (fun (k : ((Set.range ι)ᶜ : Set I)) => X k.1)) (hc₂ : IsColimit c₂) : Mono (Cofan.IsColimit.desc hc₁ (fun i => c.inj (ι i))) := by classical let e := ((Equiv.ofInjective ι hι).sumCongr (Equiv.refl _)).trans (Equiv.Set.sumCompl _) refine mono_binaryCofanSum_inl' (Cofan.mk c.pt (fun i' => c.inj (e i'))) _ _ ?_ hc₁ hc₂ _ (by simp [e]) exact IsColimit.ofIsoColimit ((IsColimit.ofCoconeEquiv (Cocones.equivalenceOfReindexing (Discrete.equivalence e) (Iso.refl _))).symm hc) (Cocones.ext (Iso.refl _)) variable (hι : Function.Injective ι) (c : Cofan X) (c₁ : Cofan (X ∘ ι)) (hc : IsColimit c) (hc₁ : IsColimit c₁) include hι include hc in lemma mono_of_injective [HasCoproduct (fun (k : ((Set.range ι)ᶜ : Set I)) => X k.1)] : Mono (Cofan.IsColimit.desc hc₁ (fun i => c.inj (ι i))) := mono_of_injective_aux X ι hι c c₁ hc hc₁ _ (colimit.isColimit _) lemma mono_of_injective' [HasCoproduct (X ∘ ι)] [HasCoproduct X] [HasCoproduct (fun (k : ((Set.range ι)ᶜ : Set I)) => X k.1)] : Mono (Sigma.desc (f := X ∘ ι) (fun j => Sigma.ι X (ι j))) := mono_of_injective X ι hι _ _ (colimit.isColimit _) (colimit.isColimit _) lemma mono_map'_of_injective [HasCoproduct (X ∘ ι)] [HasCoproduct X] [HasCoproduct (fun (k : ((Set.range ι)ᶜ : Set I)) => X k.1)] : Mono (Sigma.map' ι (fun j => 𝟙 ((X ∘ ι) j))) := by convert mono_of_injective' X ι hι apply Sigma.hom_ext intro j rw [Sigma.ι_comp_map', id_comp, colimit.ι_desc] simp end section variable [MonoCoprod C] {I : Type*} (X : I → C) lemma mono_inj (c : Cofan X) (h : IsColimit c) (i : I) [HasCoproduct (fun (k : ((Set.range (fun _ : Unit ↦ i))ᶜ : Set I)) => X k.1)] : Mono (Cofan.inj c i) := by let ι : Unit → I := fun _ ↦ i have hι : Function.Injective ι := fun _ _ _ ↦ rfl exact mono_of_injective X ι hι c (Cofan.mk (X i) (fun _ ↦ 𝟙 _)) h (mkCofanColimit _ (fun s => s.inj ())) instance mono_ι [HasCoproduct X] (i : I) [HasCoproduct (fun (k : ((Set.range (fun _ : Unit ↦ i))ᶜ : Set I)) => X k.1)] : Mono (Sigma.ι X i) := mono_inj X _ (colimit.isColimit _) i end open Functor section Preservation variable {D : Type*} [Category D] (F : C ⥤ D) theorem monoCoprod_of_preservesCoprod_of_reflectsMono [MonoCoprod D] [PreservesColimitsOfShape (Discrete WalkingPair) F] [ReflectsMonomorphisms F] : MonoCoprod C where binaryCofan_inl {A B} c h := by let c' := BinaryCofan.mk (F.map c.inl) (F.map c.inr) apply mono_of_mono_map F change Mono c'.inl apply MonoCoprod.binaryCofan_inl apply mapIsColimitOfPreservesOfIsColimit F apply IsColimit.ofIsoColimit h refine Cocones.ext (φ := eqToIso rfl) ?_ rintro ⟨(j₁|j₂)⟩ <;> simp only [const_obj_obj, eqToIso_refl, Iso.refl_hom, Category.comp_id, BinaryCofan.mk_inl, BinaryCofan.mk_inr] end Preservation section Concrete instance [HasForget C] [PreservesColimitsOfShape (Discrete WalkingPair) (forget C)] [ReflectsMonomorphisms (forget C)] : MonoCoprod C := monoCoprod_of_preservesCoprod_of_reflectsMono (forget C) end Concrete end MonoCoprod instance (A : C) [HasCoproducts.{u} C] [MonoCoprod C] : (sigmaConst.{u}.obj A).PreservesMonomorphisms where preserves {J I} ι hι := by rw [mono_iff_injective] at hι exact MonoCoprod.mono_map'_of_injective (fun (i : I) ↦ A) ι hι end Limits end CategoryTheory
Basic.lean
/- Copyright (c) 2019 Robert A. Spencer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert A. Spencer, Markus Himmel -/ import Mathlib.Algebra.Category.Grp.Preadditive import Mathlib.Algebra.Module.Equiv.Basic import Mathlib.Algebra.Module.PUnit import Mathlib.CategoryTheory.Conj import Mathlib.CategoryTheory.Linear.Basic import Mathlib.CategoryTheory.Preadditive.AdditiveFunctor /-! # The category of `R`-modules `ModuleCat.{v} R` is the category of bundled `R`-modules with carrier in the universe `v`. We show that it is preadditive and show that being an isomorphism, monomorphism and epimorphism is equivalent to being a linear equivalence, an injective linear map and a surjective linear map, respectively. ## Implementation details To construct an object in the category of `R`-modules from a type `M` with an instance of the `Module` typeclass, write `of R M`. There is a coercion in the other direction. The roundtrip `↑(of R M)` is definitionally equal to `M` itself (when `M` is a type with `Module` instance), and so is `of R ↑M` (when `M : ModuleCat R M`). The morphisms are given their own type, not identified with `LinearMap`. There is a cast from morphisms in `Module R` to linear maps, written `f.hom` (`ModuleCat.Hom.hom`). To go from linear maps to morphisms in `Module R`, use `ModuleCat.ofHom`. Similarly, given an isomorphism `f : M ≅ N` use `f.toLinearEquiv` and given a linear equiv `f : M ≃ₗ[R] N`, use `f.toModuleIso`. -/ open CategoryTheory open CategoryTheory.Limits open CategoryTheory.Limits.WalkingParallelPair universe v u variable (R : Type u) [Ring R] /-- The category of R-modules and their morphisms. Note that in the case of `R = ℤ`, we can not impose here that the `ℤ`-multiplication field from the module structure is defeq to the one coming from the `isAddCommGroup` structure (contrary to what we do for all module structures in mathlib), which creates some difficulties down the road. -/ structure ModuleCat where private mk :: /-- the underlying type of an object in `ModuleCat R` -/ carrier : Type v [isAddCommGroup : AddCommGroup carrier] [isModule : Module R carrier] attribute [instance] ModuleCat.isAddCommGroup ModuleCat.isModule namespace ModuleCat instance : CoeSort (ModuleCat.{v} R) (Type v) := ⟨ModuleCat.carrier⟩ attribute [coe] ModuleCat.carrier /-- The object in the category of R-algebras associated to a type equipped with the appropriate typeclasses. This is the preferred way to construct a term of `ModuleCat R`. -/ abbrev of (X : Type v) [AddCommGroup X] [Module R X] : ModuleCat.{v} R := ⟨X⟩ lemma coe_of (X : Type v) [Ring X] [Module R X] : (of R X : Type v) = X := rfl -- Ensure the roundtrips are reducibly defeq (so tactics like `rw` can see through them). example (X : Type v) [Ring X] [Module R X] : (of R X : Type v) = X := by with_reducible rfl example (M : ModuleCat.{v} R) : of R M = M := by with_reducible rfl variable {R} in /-- The type of morphisms in `ModuleCat R`. -/ @[ext] structure Hom (M N : ModuleCat.{v} R) where private mk :: /-- The underlying linear map. -/ hom' : M →ₗ[R] N instance moduleCategory : Category.{v, max (v+1) u} (ModuleCat.{v} R) where Hom M N := Hom M N id _ := ⟨LinearMap.id⟩ comp f g := ⟨g.hom'.comp f.hom'⟩ instance : ConcreteCategory (ModuleCat.{v} R) (· →ₗ[R] ·) where hom := Hom.hom' ofHom := Hom.mk section variable {R} /-- Turn a morphism in `ModuleCat` back into a `LinearMap`. -/ abbrev Hom.hom {A B : ModuleCat.{v} R} (f : Hom A B) := ConcreteCategory.hom (C := ModuleCat R) f /-- Typecheck a `LinearMap` as a morphism in `ModuleCat`. -/ abbrev ofHom {X Y : Type v} [AddCommGroup X] [Module R X] [AddCommGroup Y] [Module R Y] (f : X →ₗ[R] Y) : of R X ⟶ of R Y := ConcreteCategory.ofHom (C := ModuleCat R) f /-- Use the `ConcreteCategory.hom` projection for `@[simps]` lemmas. -/ def Hom.Simps.hom (A B : ModuleCat.{v} R) (f : Hom A B) := f.hom initialize_simps_projections Hom (hom' → hom) /-! The results below duplicate the `ConcreteCategory` simp lemmas, but we can keep them for `dsimp`. -/ @[simp] lemma hom_id {M : ModuleCat.{v} R} : (𝟙 M : M ⟶ M).hom = LinearMap.id := rfl /- Provided for rewriting. -/ lemma id_apply (M : ModuleCat.{v} R) (x : M) : (𝟙 M : M ⟶ M) x = x := by simp @[simp] lemma hom_comp {M N O : ModuleCat.{v} R} (f : M ⟶ N) (g : N ⟶ O) : (f ≫ g).hom = g.hom.comp f.hom := rfl /- Provided for rewriting. -/ lemma comp_apply {M N O : ModuleCat.{v} R} (f : M ⟶ N) (g : N ⟶ O) (x : M) : (f ≫ g) x = g (f x) := by simp @[ext] lemma hom_ext {M N : ModuleCat.{v} R} {f g : M ⟶ N} (hf : f.hom = g.hom) : f = g := Hom.ext hf lemma hom_bijective {M N : ModuleCat.{v} R} : Function.Bijective (Hom.hom : (M ⟶ N) → (M →ₗ[R] N)) where left f g h := by cases f; cases g; simpa using h right f := ⟨⟨f⟩, rfl⟩ /-- Convenience shortcut for `ModuleCat.hom_bijective.injective`. -/ lemma hom_injective {M N : ModuleCat.{v} R} : Function.Injective (Hom.hom : (M ⟶ N) → (M →ₗ[R] N)) := hom_bijective.injective /-- Convenience shortcut for `ModuleCat.hom_bijective.surjective`. -/ lemma hom_surjective {M N : ModuleCat.{v} R} : Function.Surjective (Hom.hom : (M ⟶ N) → (M →ₗ[R] N)) := hom_bijective.surjective @[simp] lemma hom_ofHom {X Y : Type v} [AddCommGroup X] [Module R X] [AddCommGroup Y] [Module R Y] (f : X →ₗ[R] Y) : (ofHom f).hom = f := rfl @[simp] lemma ofHom_hom {M N : ModuleCat.{v} R} (f : M ⟶ N) : ofHom (Hom.hom f) = f := rfl @[simp] lemma ofHom_id {M : Type v} [AddCommGroup M] [Module R M] : ofHom LinearMap.id = 𝟙 (of R M) := rfl @[simp] lemma ofHom_comp {M N O : Type v} [AddCommGroup M] [AddCommGroup N] [AddCommGroup O] [Module R M] [Module R N] [Module R O] (f : M →ₗ[R] N) (g : N →ₗ[R] O) : ofHom (g.comp f) = ofHom f ≫ ofHom g := rfl /- Doesn't need to be `@[simp]` since `simp only` can solve this. -/ lemma ofHom_apply {M N : Type v} [AddCommGroup M] [AddCommGroup N] [Module R M] [Module R N] (f : M →ₗ[R] N) (x : M) : ofHom f x = f x := rfl lemma inv_hom_apply {M N : ModuleCat.{v} R} (e : M ≅ N) (x : M) : e.inv (e.hom x) = x := by simp lemma hom_inv_apply {M N : ModuleCat.{v} R} (e : M ≅ N) (x : N) : e.hom (e.inv x) = x := by simp /-- `ModuleCat.Hom.hom` bundled as an `Equiv`. -/ def homEquiv {M N : ModuleCat.{v} R} : (M ⟶ N) ≃ (M →ₗ[R] N) where toFun := Hom.hom invFun := ofHom end /- Not a `@[simp]` lemma since it will rewrite the (co)domain of maps and cause definitional equality issues. -/ lemma forget_obj {M : ModuleCat.{v} R} : (forget (ModuleCat.{v} R)).obj M = M := rfl @[simp] lemma forget_map {M N : ModuleCat.{v} R} (f : M ⟶ N) : (forget (ModuleCat.{v} R)).map f = f := rfl instance hasForgetToAddCommGroup : HasForget₂ (ModuleCat R) AddCommGrp where forget₂ := { obj := fun M => AddCommGrp.of M map := fun f => AddCommGrp.ofHom f.hom.toAddMonoidHom } @[simp] theorem forget₂_obj (X : ModuleCat R) : (forget₂ (ModuleCat R) AddCommGrp).obj X = AddCommGrp.of X := rfl theorem forget₂_obj_moduleCat_of (X : Type v) [AddCommGroup X] [Module R X] : (forget₂ (ModuleCat R) AddCommGrp).obj (of R X) = AddCommGrp.of X := rfl @[simp] theorem forget₂_map (X Y : ModuleCat R) (f : X ⟶ Y) : (forget₂ (ModuleCat R) AddCommGrp).map f = AddCommGrp.ofHom f.hom := rfl instance : Inhabited (ModuleCat R) := ⟨of R PUnit⟩ @[simp] theorem of_coe (X : ModuleCat R) : of R X = X := rfl variable {R} /-- Forgetting to the underlying type and then building the bundled object returns the original module. -/ @[deprecated Iso.refl (since := "2025-05-15")] def ofSelfIso (M : ModuleCat R) : ModuleCat.of R M ≅ M where hom := 𝟙 M inv := 𝟙 M theorem isZero_of_subsingleton (M : ModuleCat R) [Subsingleton M] : IsZero M where unique_to X := ⟨⟨⟨ofHom (0 : M →ₗ[R] X)⟩, fun f => by ext x rw [Subsingleton.elim x (0 : M)] simp⟩⟩ unique_from X := ⟨⟨⟨ofHom (0 : X →ₗ[R] M)⟩, fun f => by ext x subsingleton⟩⟩ instance : HasZeroObject (ModuleCat.{v} R) := ⟨⟨of R PUnit, isZero_of_subsingleton _⟩⟩ end ModuleCat variable {R} variable {X₁ X₂ : Type v} open ModuleCat /-- Reinterpreting a linear map in the category of `R`-modules -/ scoped[ModuleCat] notation "↟" f:1024 => ModuleCat.ofHom f section /-- Build an isomorphism in the category `Module R` from a `LinearEquiv` between `Module`s. -/ @[simps] def LinearEquiv.toModuleIso {g₁ : AddCommGroup X₁} {g₂ : AddCommGroup X₂} {m₁ : Module R X₁} {m₂ : Module R X₂} (e : X₁ ≃ₗ[R] X₂) : ModuleCat.of R X₁ ≅ ModuleCat.of R X₂ where hom := ofHom (e : X₁ →ₗ[R] X₂) inv := ofHom (e.symm : X₂ →ₗ[R] X₁) hom_inv_id := by ext; apply e.left_inv inv_hom_id := by ext; apply e.right_inv namespace CategoryTheory.Iso /-- Build a `LinearEquiv` from an isomorphism in the category `ModuleCat R`. -/ def toLinearEquiv {X Y : ModuleCat R} (i : X ≅ Y) : X ≃ₗ[R] Y := LinearEquiv.ofLinear i.hom.hom i.inv.hom (by aesop) (by aesop) end CategoryTheory.Iso /-- linear equivalences between `Module`s are the same as (isomorphic to) isomorphisms in `ModuleCat` -/ @[simps] def linearEquivIsoModuleIso {X Y : Type u} [AddCommGroup X] [AddCommGroup Y] [Module R X] [Module R Y] : (X ≃ₗ[R] Y) ≅ ModuleCat.of R X ≅ ModuleCat.of R Y where hom e := e.toModuleIso inv i := i.toLinearEquiv end namespace ModuleCat section AddCommGroup variable {M N : ModuleCat.{v} R} instance : Add (M ⟶ N) where add f g := ⟨f.hom + g.hom⟩ @[simp] lemma hom_add (f g : M ⟶ N) : (f + g).hom = f.hom + g.hom := rfl instance : Zero (M ⟶ N) where zero := ⟨0⟩ @[simp] lemma hom_zero : (0 : M ⟶ N).hom = 0 := rfl instance : SMul ℕ (M ⟶ N) where smul n f := ⟨n • f.hom⟩ @[simp] lemma hom_nsmul (n : ℕ) (f : M ⟶ N) : (n • f).hom = n • f.hom := rfl instance : Neg (M ⟶ N) where neg f := ⟨-f.hom⟩ @[simp] lemma hom_neg (f : M ⟶ N) : (-f).hom = -f.hom := rfl instance : Sub (M ⟶ N) where sub f g := ⟨f.hom - g.hom⟩ @[simp] lemma hom_sub (f g : M ⟶ N) : (f - g).hom = f.hom - g.hom := rfl instance : SMul ℤ (M ⟶ N) where smul n f := ⟨n • f.hom⟩ @[simp] lemma hom_zsmul (n : ℕ) (f : M ⟶ N) : (n • f).hom = n • f.hom := rfl instance : AddCommGroup (M ⟶ N) := Function.Injective.addCommGroup (Hom.hom) hom_injective rfl (fun _ _ => rfl) (fun _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) @[simp] lemma hom_sum {ι : Type*} (f : ι → (M ⟶ N)) (s : Finset ι) : (∑ i ∈ s, f i).hom = ∑ i ∈ s, (f i).hom := map_sum ({ toFun := ModuleCat.Hom.hom, map_zero' := ModuleCat.hom_zero, map_add' := hom_add } : (M ⟶ N) →+ (M →ₗ[R] N)) _ _ instance : Preadditive (ModuleCat.{v} R) where instance forget₂_addCommGrp_additive : (forget₂ (ModuleCat.{v} R) AddCommGrp).Additive where /-- `ModuleCat.Hom.hom` bundled as an additive equivalence. -/ @[simps!] def homAddEquiv : (M ⟶ N) ≃+ (M →ₗ[R] N) := { homEquiv with map_add' := fun _ _ => rfl } theorem subsingleton_of_isZero (h : IsZero M) : Subsingleton M := by refine subsingleton_of_forall_eq 0 (fun x ↦ ?_) rw [← LinearMap.id_apply (R := R) x, ← ModuleCat.hom_id] simp only [(CategoryTheory.Limits.IsZero.iff_id_eq_zero M).mp h, hom_zero, LinearMap.zero_apply] lemma isZero_iff_subsingleton : IsZero M ↔ Subsingleton M where mp := subsingleton_of_isZero mpr _ := isZero_of_subsingleton M @[simp] lemma isZero_of_iff_subsingleton {M : Type*} [AddCommGroup M] [Module R M] : IsZero (of R M) ↔ Subsingleton M := isZero_iff_subsingleton end AddCommGroup section SMul variable {M N : ModuleCat.{v} R} {S : Type*} [Monoid S] [DistribMulAction S N] [SMulCommClass R S N] instance : SMul S (M ⟶ N) where smul c f := ⟨c • f.hom⟩ @[simp] lemma hom_smul (s : S) (f : M ⟶ N) : (s • f).hom = s • f.hom := rfl end SMul section Module variable {M N : ModuleCat.{v} R} {S : Type*} [Semiring S] [Module S N] [SMulCommClass R S N] instance Hom.instModule : Module S (M ⟶ N) := Function.Injective.module S { toFun := Hom.hom, map_zero' := hom_zero, map_add' := hom_add } hom_injective (fun _ _ => rfl) /-- `ModuleCat.Hom.hom` bundled as a linear equivalence. -/ @[simps] def homLinearEquiv : (M ⟶ N) ≃ₗ[S] (M →ₗ[R] N) := { homAddEquiv with map_smul' := fun _ _ => rfl } end Module section universe u₀ namespace Algebra variable {S₀ : Type u₀} [CommSemiring S₀] {S : Type u} [Ring S] [Algebra S₀ S] variable {M N : ModuleCat.{v} S} /-- Let `S` be an `S₀`-algebra. Then `S`-modules are modules over `S₀`. -/ scoped instance : Module S₀ M := Module.compHom _ (algebraMap S₀ S) scoped instance : IsScalarTower S₀ S M where smul_assoc _ _ _ := by rw [Algebra.smul_def, mul_smul]; rfl scoped instance : SMulCommClass S S₀ M where smul_comm s s₀ n := show s • algebraMap S₀ S s₀ • n = algebraMap S₀ S s₀ • s • n by rw [← smul_assoc, smul_eq_mul, ← Algebra.commutes, mul_smul] /-- Let `S` be an `S₀`-algebra. Then the category of `S`-modules is `S₀`-linear. -/ scoped instance instLinear : Linear S₀ (ModuleCat.{v} S) where smul_comp _ M N s₀ f g := by ext; simp end Algebra section variable {S : Type u} [CommRing S] instance : Linear S (ModuleCat.{v} S) := ModuleCat.Algebra.instLinear variable {X Y X' Y' : ModuleCat.{v} S} theorem Iso.homCongr_eq_arrowCongr (i : X ≅ X') (j : Y ≅ Y') (f : X ⟶ Y) : Iso.homCongr i j f = ⟨LinearEquiv.arrowCongr i.toLinearEquiv j.toLinearEquiv f.hom⟩ := rfl theorem Iso.conj_eq_conj (i : X ≅ X') (f : End X) : Iso.conj i f = ⟨LinearEquiv.conj i.toLinearEquiv f.hom⟩ := rfl end end variable (M N : ModuleCat.{v} R) /-- `ModuleCat.Hom.hom` as an isomorphism of rings. -/ @[simps!] def endRingEquiv : End M ≃+* (M →ₗ[R] M) where toFun := ModuleCat.Hom.hom invFun := ModuleCat.ofHom map_mul' _ _ := rfl map_add' _ _ := rfl /-- The scalar multiplication on an object of `ModuleCat R` considered as a morphism of rings from `R` to the endomorphisms of the underlying abelian group. -/ def smul : R →+* End ((forget₂ (ModuleCat R) AddCommGrp).obj M) where toFun r := AddCommGrp.ofHom { toFun := fun (m : M) => r • m map_zero' := by rw [smul_zero] map_add' := fun x y => by rw [smul_add] } map_one' := AddCommGrp.ext (fun x => by simp) map_zero' := AddCommGrp.ext (fun x => by simp) map_mul' r s := AddCommGrp.ext (fun (x : M) => (smul_smul r s x).symm) map_add' r s := AddCommGrp.ext (fun (x : M) => add_smul r s x) lemma smul_naturality {M N : ModuleCat.{v} R} (f : M ⟶ N) (r : R) : (forget₂ (ModuleCat R) AddCommGrp).map f ≫ N.smul r = M.smul r ≫ (forget₂ (ModuleCat R) AddCommGrp).map f := by ext x exact (f.hom.map_smul r x).symm variable (R) in /-- The scalar multiplication on `ModuleCat R` considered as a morphism of rings to the endomorphisms of the forgetful functor to `AddCommGrp)`. -/ @[simps] def smulNatTrans : R →+* End (forget₂ (ModuleCat R) AddCommGrp) where toFun r := { app := fun M => M.smul r naturality := fun _ _ _ => smul_naturality _ r } map_one' := NatTrans.ext (by cat_disch) map_zero' := NatTrans.ext (by cat_disch) map_mul' _ _ := NatTrans.ext (by cat_disch) map_add' _ _ := NatTrans.ext (by cat_disch) /-- Given `A : AddCommGrp` and a ring morphism `R →+* End A`, this is a type synonym for `A`, on which we shall define a structure of `R`-module. -/ @[nolint unusedArguments] def mkOfSMul' {A : AddCommGrp} (_ : R →+* End A) := A section variable {A : AddCommGrp} (φ : R →+* End A) instance : AddCommGroup (mkOfSMul' φ) := by dsimp only [mkOfSMul'] infer_instance instance : SMul R (mkOfSMul' φ) := ⟨fun r (x : A) => (show A ⟶ A from φ r) x⟩ @[simp] lemma mkOfSMul'_smul (r : R) (x : mkOfSMul' φ) : r • x = (show A ⟶ A from φ r) x := rfl instance : Module R (mkOfSMul' φ) where smul_zero _ := map_zero (N := A) _ smul_add _ _ _ := map_add (N := A) _ _ _ one_smul := by simp mul_smul := by simp add_smul _ _ _ := by simp; rfl zero_smul := by simp /-- Given `A : AddCommGrp` and a ring morphism `R →+* End A`, this is an object in `ModuleCat R`, whose underlying abelian group is `A` and whose scalar multiplication is given by `R`. -/ abbrev mkOfSMul := ModuleCat.of R (mkOfSMul' φ) lemma mkOfSMul_smul (r : R) : (mkOfSMul φ).smul r = φ r := rfl end section variable {M N} (φ : (forget₂ (ModuleCat R) AddCommGrp).obj M ⟶ (forget₂ (ModuleCat R) AddCommGrp).obj N) (hφ : ∀ (r : R), φ ≫ N.smul r = M.smul r ≫ φ) /-- Constructor for morphisms in `ModuleCat R` which takes as inputs a morphism between the underlying objects in `AddCommGrp` and the compatibility with the scalar multiplication. -/ @[simps] def homMk : M ⟶ N where hom'.toFun := φ hom'.map_add' _ _ := φ.hom.map_add _ _ hom'.map_smul' r x := (congr_hom (hφ r) x).symm lemma forget₂_map_homMk : (forget₂ (ModuleCat R) AddCommGrp).map (homMk φ hφ) = φ := rfl end instance : (forget (ModuleCat.{v} R)).ReflectsIsomorphisms where reflects f _ := (inferInstance : IsIso ((LinearEquiv.mk f.hom (asIso ((forget (ModuleCat R)).map f)).toEquiv.invFun (Equiv.left_inv _) (Equiv.right_inv _)).toModuleIso).hom) instance : (forget₂ (ModuleCat.{v} R) AddCommGrp.{v}).ReflectsIsomorphisms where reflects f _ := by have : IsIso ((forget _).map f) := by change IsIso ((forget _).map ((forget₂ _ AddCommGrp).map f)) infer_instance apply isIso_of_reflects_iso _ (forget _) end ModuleCat section Bilinear variable {R : Type*} [CommRing R] namespace ModuleCat /-- Turn a bilinear map into a homomorphism. -/ @[simps!] def ofHom₂ {M N P : ModuleCat.{u} R} (f : M →ₗ[R] N →ₗ[R] P) : M ⟶ of R (N ⟶ P) := ofHom <| homLinearEquiv.symm.toLinearMap ∘ₗ f /-- Turn a homomorphism into a bilinear map. -/ @[simps!] def Hom.hom₂ {M N P : ModuleCat.{u} R} -- We write `Hom` instead of `M ⟶ (of R (N ⟶ P))`, otherwise dot notation breaks -- since it is expecting the type of `f` to be `ModuleCat.Hom`, not `Quiver.Hom`. (f : Hom M (of R (N ⟶ P))) : M →ₗ[R] N →ₗ[R] P := Hom.hom (by convert (f ≫ ofHom homLinearEquiv.toLinearMap)) @[simp] lemma Hom.hom₂_ofHom₂ {M N P : ModuleCat.{u} R} (f : M →ₗ[R] N →ₗ[R] P) : (ofHom₂ f).hom₂ = f := rfl @[simp] lemma ofHom₂_hom₂ {M N P : ModuleCat.{u} R} (f : M ⟶ of R (N ⟶ P)) : ofHom₂ f.hom₂ = f := rfl end ModuleCat end Bilinear /-! `@[simp]` lemmas for `LinearMap.comp` and categorical identities. -/ @[simp] theorem LinearMap.comp_id_moduleCat {R} [Ring R] {G : ModuleCat.{u} R} {H : Type u} [AddCommGroup H] [Module R H] (f : G →ₗ[R] H) : f.comp (𝟙 G : G ⟶ G).hom = f := by simp @[simp] theorem LinearMap.id_moduleCat_comp {R} [Ring R] {G : Type u} [AddCommGroup G] [Module R G] {H : ModuleCat.{u} R} (f : G →ₗ[R] H) : LinearMap.comp (𝟙 H : H ⟶ H).hom f = f := by simp
IsPrimePow.lean
/- Copyright (c) 2022 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Order.Nat import Mathlib.Data.Nat.Prime.Basic /-! # Prime powers This file deals with prime powers: numbers which are positive integer powers of a single prime. -/ assert_not_exists Nat.divisors variable {R : Type*} [CommMonoidWithZero R] (n p : R) (k : ℕ) /-- `n` is a prime power if there is a prime `p` and a positive natural `k` such that `n` can be written as `p^k`. -/ def IsPrimePow : Prop := ∃ (p : R) (k : ℕ), Prime p ∧ 0 < k ∧ p ^ k = n theorem isPrimePow_def : IsPrimePow n ↔ ∃ (p : R) (k : ℕ), Prime p ∧ 0 < k ∧ p ^ k = n := Iff.rfl /-- An equivalent definition for prime powers: `n` is a prime power iff there is a prime `p` and a natural `k` such that `n` can be written as `p^(k+1)`. -/ theorem isPrimePow_iff_pow_succ : IsPrimePow n ↔ ∃ (p : R) (k : ℕ), Prime p ∧ p ^ (k + 1) = n := (isPrimePow_def _).trans ⟨fun ⟨p, k, hp, hk, hn⟩ => ⟨p, k - 1, hp, by rwa [Nat.sub_add_cancel hk]⟩, fun ⟨_, _, hp, hn⟩ => ⟨_, _, hp, Nat.succ_pos', hn⟩⟩ theorem not_isPrimePow_zero [NoZeroDivisors R] : ¬IsPrimePow (0 : R) := by simp only [isPrimePow_def, not_exists, not_and', and_imp] intro x n _hn hx rw [pow_eq_zero hx] simp theorem IsPrimePow.not_unit {n : R} (h : IsPrimePow n) : ¬IsUnit n := let ⟨_p, _k, hp, hk, hn⟩ := h hn ▸ (isUnit_pow_iff hk.ne').not.mpr hp.not_unit theorem IsUnit.not_isPrimePow {n : R} (h : IsUnit n) : ¬IsPrimePow n := fun h' => h'.not_unit h theorem not_isPrimePow_one : ¬IsPrimePow (1 : R) := isUnit_one.not_isPrimePow theorem Prime.isPrimePow {p : R} (hp : Prime p) : IsPrimePow p := ⟨p, 1, hp, zero_lt_one, by simp⟩ theorem IsPrimePow.pow {n : R} (hn : IsPrimePow n) {k : ℕ} (hk : k ≠ 0) : IsPrimePow (n ^ k) := let ⟨p, k', hp, hk', hn⟩ := hn ⟨p, k * k', hp, mul_pos hk.bot_lt hk', by rw [pow_mul', hn]⟩ theorem IsPrimePow.ne_zero [NoZeroDivisors R] {n : R} (h : IsPrimePow n) : n ≠ 0 := fun t => not_isPrimePow_zero (t ▸ h) theorem IsPrimePow.ne_one {n : R} (h : IsPrimePow n) : n ≠ 1 := fun t => not_isPrimePow_one (t ▸ h) section Nat theorem isPrimePow_nat_iff (n : ℕ) : IsPrimePow n ↔ ∃ p k : ℕ, Nat.Prime p ∧ 0 < k ∧ p ^ k = n := by simp only [isPrimePow_def, Nat.prime_iff] theorem Nat.Prime.isPrimePow {p : ℕ} (hp : p.Prime) : IsPrimePow p := _root_.Prime.isPrimePow (prime_iff.mp hp) theorem isPrimePow_nat_iff_bounded (n : ℕ) : IsPrimePow n ↔ ∃ p : ℕ, p ≤ n ∧ ∃ k : ℕ, k ≤ n ∧ p.Prime ∧ 0 < k ∧ p ^ k = n := by rw [isPrimePow_nat_iff] refine Iff.symm ⟨fun ⟨p, _, k, _, hp, hk, hn⟩ => ⟨p, k, hp, hk, hn⟩, ?_⟩ rintro ⟨p, k, hp, hk, rfl⟩ refine ⟨p, ?_, k, (Nat.lt_pow_self hp.one_lt).le, hp, hk, rfl⟩ conv => { lhs; rw [← (pow_one p)] } exact Nat.pow_le_pow_right hp.one_lt.le hk instance {n : ℕ} : Decidable (IsPrimePow n) := decidable_of_iff' _ (isPrimePow_nat_iff_bounded n) theorem IsPrimePow.dvd {n m : ℕ} (hn : IsPrimePow n) (hm : m ∣ n) (hm₁ : m ≠ 1) : IsPrimePow m := by grind [isPrimePow_nat_iff, Nat.dvd_prime_pow, Nat.pow_eq_one] theorem IsPrimePow.two_le : ∀ {n : ℕ}, IsPrimePow n → 2 ≤ n | 0, h => (not_isPrimePow_zero h).elim | 1, h => (not_isPrimePow_one h).elim | _n + 2, _ => le_add_self theorem IsPrimePow.pos {n : ℕ} (hn : IsPrimePow n) : 0 < n := pos_of_gt hn.two_le theorem IsPrimePow.one_lt {n : ℕ} (h : IsPrimePow n) : 1 < n := h.two_le end Nat
NatAntidiagonal.lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import Mathlib.Data.Finset.NatAntidiagonal import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # Big operators for `NatAntidiagonal` This file contains theorems relevant to big operators over `Finset.NatAntidiagonal`. -/ variable {M N : Type*} [CommMonoid M] [AddCommMonoid N] namespace Finset namespace Nat theorem prod_antidiagonal_succ {n : ℕ} {f : ℕ × ℕ → M} : (∏ p ∈ antidiagonal (n + 1), f p) = f (0, n + 1) * ∏ p ∈ antidiagonal n, f (p.1 + 1, p.2) := by rw [antidiagonal_succ, prod_cons, prod_map]; rfl theorem sum_antidiagonal_succ {n : ℕ} {f : ℕ × ℕ → N} : (∑ p ∈ antidiagonal (n + 1), f p) = f (0, n + 1) + ∑ p ∈ antidiagonal n, f (p.1 + 1, p.2) := @prod_antidiagonal_succ (Multiplicative N) _ _ _ @[to_additive] theorem prod_antidiagonal_swap {n : ℕ} {f : ℕ × ℕ → M} : ∏ p ∈ antidiagonal n, f p.swap = ∏ p ∈ antidiagonal n, f p := by conv_lhs => rw [← map_swap_antidiagonal, Finset.prod_map] rfl theorem prod_antidiagonal_succ' {n : ℕ} {f : ℕ × ℕ → M} : (∏ p ∈ antidiagonal (n + 1), f p) = f (n + 1, 0) * ∏ p ∈ antidiagonal n, f (p.1, p.2 + 1) := by rw [← prod_antidiagonal_swap, prod_antidiagonal_succ, ← prod_antidiagonal_swap] rfl theorem sum_antidiagonal_succ' {n : ℕ} {f : ℕ × ℕ → N} : (∑ p ∈ antidiagonal (n + 1), f p) = f (n + 1, 0) + ∑ p ∈ antidiagonal n, f (p.1, p.2 + 1) := @prod_antidiagonal_succ' (Multiplicative N) _ _ _ @[to_additive] theorem prod_antidiagonal_subst {n : ℕ} {f : ℕ × ℕ → ℕ → M} : ∏ p ∈ antidiagonal n, f p n = ∏ p ∈ antidiagonal n, f p (p.1 + p.2) := prod_congr rfl fun p hp ↦ by rw [mem_antidiagonal.mp hp] @[to_additive] theorem prod_antidiagonal_eq_prod_range_succ_mk {M : Type*} [CommMonoid M] (f : ℕ × ℕ → M) (n : ℕ) : ∏ ij ∈ antidiagonal n, f ij = ∏ k ∈ range n.succ, f (k, n - k) := Finset.prod_map (range n.succ) ⟨fun i ↦ (i, n - i), fun _ _ h ↦ (Prod.mk.inj h).1⟩ f /-- This lemma matches more generally than `Finset.Nat.prod_antidiagonal_eq_prod_range_succ_mk` when using `rw ← `. -/ @[to_additive /-- This lemma matches more generally than `Finset.Nat.sum_antidiagonal_eq_sum_range_succ_mk` when using `rw ← `. -/] theorem prod_antidiagonal_eq_prod_range_succ {M : Type*} [CommMonoid M] (f : ℕ → ℕ → M) (n : ℕ) : ∏ ij ∈ antidiagonal n, f ij.1 ij.2 = ∏ k ∈ range n.succ, f k (n - k) := prod_antidiagonal_eq_prod_range_succ_mk _ _ end Nat end Finset
Lemmas.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.Data.Ordering.Basic import Mathlib.Order.Defs.Unbundled /-! # Some `Ordering` lemmas -/ universe u namespace Ordering @[simp] theorem ite_eq_lt_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.lt) = if c then a = Ordering.lt else b = Ordering.lt := by by_cases c <;> simp [*] @[simp] theorem ite_eq_eq_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.eq) = if c then a = Ordering.eq else b = Ordering.eq := by by_cases c <;> simp [*] @[simp] theorem ite_eq_gt_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.gt) = if c then a = Ordering.gt else b = Ordering.gt := by by_cases c <;> simp [*] @[simp] lemma dthen_eq_then (o₁ o₂ : Ordering) : o₁.dthen (fun _ => o₂) = o₁.then o₂ := by cases o₁ <;> rfl end Ordering section variable {α : Type u} {lt : α → α → Prop} [DecidableRel lt] attribute [local simp] cmpUsing @[simp] theorem cmpUsing_eq_lt (a b : α) : (cmpUsing lt a b = Ordering.lt) = lt a b := by simp only [cmpUsing, Ordering.ite_eq_lt_distrib, ite_self, if_false_right, and_true, reduceCtorEq] @[simp] theorem cmpUsing_eq_gt [IsStrictOrder α lt] (a b : α) : cmpUsing lt a b = Ordering.gt ↔ lt b a := by simp only [cmpUsing, Ordering.ite_eq_gt_distrib, if_false_right, and_true, if_false_left, and_iff_right_iff_imp, reduceCtorEq] exact fun hba hab ↦ (irrefl a) (_root_.trans hab hba) @[simp] theorem cmpUsing_eq_eq (a b : α) : cmpUsing lt a b = Ordering.eq ↔ ¬lt a b ∧ ¬lt b a := by simp end
BigOperators.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yury Kudryashov, Yaël Dillies -/ import Mathlib.Algebra.BigOperators.GroupWithZero.Action import Mathlib.Algebra.Module.Defs import Mathlib.Data.Fintype.BigOperators /-! # Finite sums over modules over a ring -/ variable {ι κ α β R M : Type*} section AddCommMonoid variable [Semiring R] [AddCommMonoid M] [Module R M] theorem List.sum_smul {l : List R} {x : M} : l.sum • x = (l.map fun r ↦ r • x).sum := map_list_sum ((smulAddHom R M).flip x) l theorem Multiset.sum_smul {l : Multiset R} {x : M} : l.sum • x = (l.map fun r ↦ r • x).sum := ((smulAddHom R M).flip x).map_multiset_sum l theorem Multiset.sum_smul_sum {s : Multiset R} {t : Multiset M} : s.sum • t.sum = ((s ×ˢ t).map fun p : R × M ↦ p.fst • p.snd).sum := by induction' s using Multiset.induction with a s ih · simp · simp [add_smul, ih, ← Multiset.smul_sum] theorem Finset.sum_smul {f : ι → R} {s : Finset ι} {x : M} : (∑ i ∈ s, f i) • x = ∑ i ∈ s, f i • x := map_sum ((smulAddHom R M).flip x) f s lemma Finset.sum_smul_sum (s : Finset α) (t : Finset β) {f : α → R} {g : β → M} : (∑ i ∈ s, f i) • ∑ j ∈ t, g j = ∑ i ∈ s, ∑ j ∈ t, f i • g j := by simp_rw [sum_smul, ← smul_sum] lemma Fintype.sum_smul_sum [Fintype α] [Fintype β] (f : α → R) (g : β → M) : (∑ i, f i) • ∑ j, g j = ∑ i, ∑ j, f i • g j := Finset.sum_smul_sum _ _ end AddCommMonoid open Finset theorem Finset.cast_card [NonAssocSemiring R] (s : Finset α) : (#s : R) = ∑ _ ∈ s, 1 := by rw [Finset.sum_const, Nat.smul_one_eq_cast] namespace Fintype variable [DecidableEq ι] [Fintype ι] [AddCommMonoid α] lemma sum_piFinset_apply (f : κ → α) (s : Finset κ) (i : ι) : ∑ g ∈ piFinset fun _ : ι ↦ s, f (g i) = #s ^ (card ι - 1) • ∑ b ∈ s, f b := by classical rw [Finset.sum_comp] simp only [eval_image_piFinset_const, card_filter_piFinset_const s, ite_smul, zero_smul, smul_sum, Finset.sum_ite_mem, inter_self] end Fintype
Computation.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Nat.Find import Mathlib.Data.Stream.Init import Mathlib.Tactic.Common /-! # Coinductive formalization of unbounded computations. This file provides a `Computation` type where `Computation α` is the type of unbounded computations returning `α`. -/ open Function universe u v w /- coinductive Computation (α : Type u) : Type u | pure : α → Computation α | think : Computation α → Computation α -/ /-- `Computation α` is the type of unbounded computations returning `α`. An element of `Computation α` is an infinite sequence of `Option α` such that if `f n = some a` for some `n` then it is constantly `some a` after that. -/ def Computation (α : Type u) : Type u := { f : Stream' (Option α) // ∀ ⦃n a⦄, f n = some a → f (n + 1) = some a } namespace Computation variable {α : Type u} {β : Type v} {γ : Type w} -- constructors /-- `pure a` is the computation that immediately terminates with result `a`. -/ def pure (a : α) : Computation α := ⟨Stream'.const (some a), fun _ _ => id⟩ instance : CoeTC α (Computation α) := ⟨pure⟩ -- note [use has_coe_t] /-- `think c` is the computation that delays for one "tick" and then performs computation `c`. -/ def think (c : Computation α) : Computation α := ⟨Stream'.cons none c.1, fun n a h => by rcases n with - | n · contradiction · exact c.2 h⟩ /-- `thinkN c n` is the computation that delays for `n` ticks and then performs computation `c`. -/ def thinkN (c : Computation α) : ℕ → Computation α | 0 => c | n + 1 => think (thinkN c n) -- check for immediate result /-- `head c` is the first step of computation, either `some a` if `c = pure a` or `none` if `c = think c'`. -/ def head (c : Computation α) : Option α := c.1.head -- one step of computation /-- `tail c` is the remainder of computation, either `c` if `c = pure a` or `c'` if `c = think c'`. -/ def tail (c : Computation α) : Computation α := ⟨c.1.tail, fun _ _ h => c.2 h⟩ /-- `empty α` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (α) : Computation α := ⟨Stream'.const none, fun _ _ => id⟩ instance : Inhabited (Computation α) := ⟨empty _⟩ /-- `runFor c n` evaluates `c` for `n` steps and returns the result, or `none` if it did not terminate after `n` steps. -/ def runFor : Computation α → ℕ → Option α := Subtype.val /-- `destruct c` is the destructor for `Computation α` as a coinductive type. It returns `inl a` if `c = pure a` and `inr c'` if `c = think c'`. -/ def destruct (c : Computation α) : α ⊕ (Computation α) := match c.1 0 with | none => Sum.inr (tail c) | some a => Sum.inl a /-- `run c` is an unsound meta function that runs `c` to completion, possibly resulting in an infinite loop in the VM. -/ unsafe def run : Computation α → α | c => match destruct c with | Sum.inl a => a | Sum.inr ca => run ca theorem destruct_eq_pure {s : Computation α} {a : α} : destruct s = Sum.inl a → s = pure a := by dsimp [destruct] induction' f0 : s.1 0 with _ <;> intro h · contradiction · apply Subtype.eq funext n induction' n with n IH · injection h with h' rwa [h'] at f0 · exact s.2 IH theorem destruct_eq_think {s : Computation α} {s'} : destruct s = Sum.inr s' → s = think s' := by dsimp [destruct] induction' f0 : s.1 0 with a' <;> intro h · injection h with h' rw [← h'] obtain ⟨f, al⟩ := s apply Subtype.eq dsimp [think, tail] rw [← f0] exact (Stream'.eta f).symm · contradiction @[simp] theorem destruct_pure (a : α) : destruct (pure a) = Sum.inl a := rfl @[simp] theorem destruct_think : ∀ s : Computation α, destruct (think s) = Sum.inr s | ⟨_, _⟩ => rfl @[simp] theorem destruct_empty : destruct (empty α) = Sum.inr (empty α) := rfl @[simp] theorem head_pure (a : α) : head (pure a) = some a := rfl @[simp] theorem head_think (s : Computation α) : head (think s) = none := rfl @[simp] theorem head_empty : head (empty α) = none := rfl @[simp] theorem tail_pure (a : α) : tail (pure a) = pure a := rfl @[simp] theorem tail_think (s : Computation α) : tail (think s) = s := by obtain ⟨f, al⟩ := s; apply Subtype.eq; dsimp [tail, think] @[simp] theorem tail_empty : tail (empty α) = empty α := rfl theorem think_empty : empty α = think (empty α) := destruct_eq_think destruct_empty /-- Recursion principle for computations, compare with `List.recOn`. -/ def recOn {C : Computation α → Sort v} (s : Computation α) (h1 : ∀ a, C (pure a)) (h2 : ∀ s, C (think s)) : C s := match H : destruct s with | Sum.inl v => by rw [destruct_eq_pure H] apply h1 | Sum.inr v => match v with | ⟨a, s'⟩ => by rw [destruct_eq_think H] apply h2 /-- Corecursor constructor for `corec` -/ def Corec.f (f : β → α ⊕ β) : α ⊕ β → Option α × (α ⊕ β) | Sum.inl a => (some a, Sum.inl a) | Sum.inr b => (match f b with | Sum.inl a => some a | Sum.inr _ => none, f b) /-- `corec f b` is the corecursor for `Computation α` as a coinductive type. If `f b = inl a` then `corec f b = pure a`, and if `f b = inl b'` then `corec f b = think (corec f b')`. -/ def corec (f : β → α ⊕ β) (b : β) : Computation α := by refine ⟨Stream'.corec' (Corec.f f) (Sum.inr b), fun n a' h => ?_⟩ rw [Stream'.corec'_eq] change Stream'.corec' (Corec.f f) (Corec.f f (Sum.inr b)).2 n = some a' revert h; generalize Sum.inr b = o; revert o induction' n with n IH <;> intro o · change (Corec.f f o).1 = some a' → (Corec.f f (Corec.f f o).2).1 = some a' rcases o with _ | b <;> intro h · exact h unfold Corec.f at *; split <;> simp_all · rw [Stream'.corec'_eq (Corec.f f) (Corec.f f o).2, Stream'.corec'_eq (Corec.f f) o] exact IH (Corec.f f o).2 /-- left map of `⊕` -/ def lmap (f : α → β) : α ⊕ γ → β ⊕ γ | Sum.inl a => Sum.inl (f a) | Sum.inr b => Sum.inr b /-- right map of `⊕` -/ def rmap (f : β → γ) : α ⊕ β → α ⊕ γ | Sum.inl a => Sum.inl a | Sum.inr b => Sum.inr (f b) attribute [simp] lmap rmap @[simp] theorem corec_eq (f : β → α ⊕ β) (b : β) : destruct (corec f b) = rmap (corec f) (f b) := by dsimp [corec, destruct] rw [show Stream'.corec' (Corec.f f) (Sum.inr b) 0 = Sum.rec Option.some (fun _ ↦ none) (f b) by dsimp [Corec.f, Stream'.corec', Stream'.corec, Stream'.map, Stream'.get, Stream'.iterate] match (f b) with | Sum.inl x => rfl | Sum.inr x => rfl ] induction' h : f b with a b'; · rfl dsimp [Corec.f, destruct] apply congr_arg; apply Subtype.eq dsimp [corec, tail] rw [Stream'.corec'_eq, Stream'.tail_cons] dsimp [Corec.f]; rw [h] section Bisim variable (R : Computation α → Computation α → Prop) /-- bisimilarity relation -/ local infixl:50 " ~ " => R /-- Bisimilarity over a sum of `Computation`s -/ def BisimO : α ⊕ (Computation α) → α ⊕ (Computation α) → Prop | Sum.inl a, Sum.inl a' => a = a' | Sum.inr s, Sum.inr s' => R s s' | _, _ => False attribute [simp] BisimO attribute [nolint simpNF] BisimO.eq_3 /-- Attribute expressing bisimilarity over two `Computation`s -/ def IsBisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → BisimO R (destruct s₁) (destruct s₂) -- If two computations are bisimilar, then they are equal theorem eq_of_bisim (bisim : IsBisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := by apply Subtype.eq apply Stream'.eq_of_bisim fun x y => ∃ s s' : Computation α, s.1 = x ∧ s'.1 = y ∧ R s s' · dsimp [Stream'.IsBisimulation] intro t₁ t₂ e match t₁, t₂, e with | _, _, ⟨s, s', rfl, rfl, r⟩ => suffices head s = head s' ∧ R (tail s) (tail s') from And.imp id (fun r => ⟨tail s, tail s', by cases s; rfl, by cases s'; rfl, r⟩) this have h := bisim r; revert r h apply recOn s _ _ <;> intro r' <;> apply recOn s' _ _ <;> intro a' r h · constructor <;> dsimp at h · rw [h] · rw [h] at r rw [tail_pure, tail_pure,h] assumption · rw [destruct_pure, destruct_think] at h exact False.elim h · rw [destruct_pure, destruct_think] at h exact False.elim h · simp_all · exact ⟨s₁, s₂, rfl, rfl, r⟩ end Bisim -- It's more of a stretch to use ∈ for this relation, but it -- asserts that the computation limits to the given value. /-- Assertion that a `Computation` limits to a given value -/ protected def Mem (s : Computation α) (a : α) := some a ∈ s.1 instance : Membership α (Computation α) := ⟨Computation.Mem⟩ theorem le_stable (s : Computation α) {a m n} (h : m ≤ n) : s.1 m = some a → s.1 n = some a := by obtain ⟨f, al⟩ := s induction' h with n _ IH exacts [id, fun h2 => al (IH h2)] theorem mem_unique {s : Computation α} {a b : α} : a ∈ s → b ∈ s → a = b | ⟨m, ha⟩, ⟨n, hb⟩ => by injection (le_stable s (le_max_left m n) ha.symm).symm.trans (le_stable s (le_max_right m n) hb.symm) theorem Mem.left_unique : Relator.LeftUnique ((· ∈ ·) : α → Computation α → Prop) := fun _ _ _ => mem_unique /-- `Terminates s` asserts that the computation `s` eventually terminates with some value. -/ class Terminates (s : Computation α) : Prop where /-- assertion that there is some term `a` such that the `Computation` terminates -/ term : ∃ a, a ∈ s theorem terminates_iff (s : Computation α) : Terminates s ↔ ∃ a, a ∈ s := ⟨fun h => h.1, Terminates.mk⟩ theorem terminates_of_mem {s : Computation α} {a : α} (h : a ∈ s) : Terminates s := ⟨⟨a, h⟩⟩ theorem terminates_def (s : Computation α) : Terminates s ↔ ∃ n, (s.1 n).isSome := ⟨fun ⟨⟨a, n, h⟩⟩ => ⟨n, by dsimp [Stream'.get] at h rw [← h] exact rfl⟩, fun ⟨n, h⟩ => ⟨⟨Option.get _ h, n, (Option.eq_some_of_isSome h).symm⟩⟩⟩ theorem ret_mem (a : α) : a ∈ pure a := Exists.intro 0 rfl theorem eq_of_pure_mem {a a' : α} (h : a' ∈ pure a) : a' = a := mem_unique h (ret_mem _) @[simp] theorem mem_pure_iff (a b : α) : a ∈ pure b ↔ a = b := ⟨eq_of_pure_mem, fun h => h ▸ ret_mem _⟩ instance ret_terminates (a : α) : Terminates (pure a) := terminates_of_mem (ret_mem _) theorem think_mem {s : Computation α} {a} : a ∈ s → a ∈ think s | ⟨n, h⟩ => ⟨n + 1, h⟩ instance think_terminates (s : Computation α) : ∀ [Terminates s], Terminates (think s) | ⟨⟨a, n, h⟩⟩ => ⟨⟨a, n + 1, h⟩⟩ theorem of_think_mem {s : Computation α} {a} : a ∈ think s → a ∈ s | ⟨n, h⟩ => by rcases n with - | n' · contradiction · exact ⟨n', h⟩ theorem of_think_terminates {s : Computation α} : Terminates (think s) → Terminates s | ⟨⟨a, h⟩⟩ => ⟨⟨a, of_think_mem h⟩⟩ theorem notMem_empty (a : α) : a ∉ empty α := fun ⟨n, h⟩ => by contradiction @[deprecated (since := "2025-05-23")] alias not_mem_empty := notMem_empty theorem not_terminates_empty : ¬Terminates (empty α) := fun ⟨⟨a, h⟩⟩ => notMem_empty a h theorem eq_empty_of_not_terminates {s} (H : ¬Terminates s) : s = empty α := by apply Subtype.eq; funext n induction' h : s.val n with _; · rfl refine absurd ?_ H; exact ⟨⟨_, _, h.symm⟩⟩ theorem thinkN_mem {s : Computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s | 0 => Iff.rfl | n + 1 => Iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n) instance thinkN_terminates (s : Computation α) : ∀ [Terminates s] (n), Terminates (thinkN s n) | ⟨⟨a, h⟩⟩, n => ⟨⟨a, (thinkN_mem n).2 h⟩⟩ theorem of_thinkN_terminates (s : Computation α) (n) : Terminates (thinkN s n) → Terminates s | ⟨⟨a, h⟩⟩ => ⟨⟨a, (thinkN_mem _).1 h⟩⟩ /-- `Promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ def Promises (s : Computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a' /-- `Promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ scoped infixl:50 " ~> " => Promises theorem mem_promises {s : Computation α} {a : α} : a ∈ s → s ~> a := fun h _ => mem_unique h theorem empty_promises (a : α) : empty α ~> a := fun _ h => absurd h (notMem_empty _) section get variable (s : Computation α) [h : Terminates s] /-- `length s` gets the number of steps of a terminating computation -/ def length : ℕ := Nat.find ((terminates_def _).1 h) /-- `get s` returns the result of a terminating computation -/ def get : α := Option.get _ (Nat.find_spec <| (terminates_def _).1 h) theorem get_mem : get s ∈ s := Exists.intro (length s) (Option.eq_some_of_isSome _).symm theorem get_eq_of_mem {a} : a ∈ s → get s = a := mem_unique (get_mem _) theorem mem_of_get_eq {a} : get s = a → a ∈ s := by intro h; rw [← h]; apply get_mem @[simp] theorem get_think : get (think s) = get s := get_eq_of_mem _ <| let ⟨n, h⟩ := get_mem s ⟨n + 1, h⟩ @[simp] theorem get_thinkN (n) : get (thinkN s n) = get s := get_eq_of_mem _ <| (thinkN_mem _).2 (get_mem _) theorem get_promises : s ~> get s := fun _ => get_eq_of_mem _ theorem mem_of_promises {a} (p : s ~> a) : a ∈ s := by obtain ⟨h⟩ := h obtain ⟨a', h⟩ := h rw [p h] exact h theorem get_eq_of_promises {a} : s ~> a → get s = a := get_eq_of_mem _ ∘ mem_of_promises _ end get /-- `Results s a n` completely characterizes a terminating computation: it asserts that `s` terminates after exactly `n` steps, with result `a`. -/ def Results (s : Computation α) (a : α) (n : ℕ) := ∃ h : a ∈ s, @length _ s (terminates_of_mem h) = n theorem results_of_terminates (s : Computation α) [_T : Terminates s] : Results s (get s) (length s) := ⟨get_mem _, rfl⟩ theorem results_of_terminates' (s : Computation α) [T : Terminates s] {a} (h : a ∈ s) : Results s a (length s) := by rw [← get_eq_of_mem _ h]; apply results_of_terminates theorem Results.mem {s : Computation α} {a n} : Results s a n → a ∈ s | ⟨m, _⟩ => m theorem Results.terminates {s : Computation α} {a n} (h : Results s a n) : Terminates s := terminates_of_mem h.mem theorem Results.length {s : Computation α} {a n} [_T : Terminates s] : Results s a n → length s = n | ⟨_, h⟩ => h theorem Results.val_unique {s : Computation α} {a b m n} (h1 : Results s a m) (h2 : Results s b n) : a = b := mem_unique h1.mem h2.mem theorem Results.len_unique {s : Computation α} {a b m n} (h1 : Results s a m) (h2 : Results s b n) : m = n := by haveI := h1.terminates; haveI := h2.terminates; rw [← h1.length, h2.length] theorem exists_results_of_mem {s : Computation α} {a} (h : a ∈ s) : ∃ n, Results s a n := haveI := terminates_of_mem h ⟨_, results_of_terminates' s h⟩ @[simp] theorem get_pure (a : α) : get (pure a) = a := get_eq_of_mem _ ⟨0, rfl⟩ @[simp] theorem length_pure (a : α) : length (pure a) = 0 := let h := Computation.ret_terminates a Nat.eq_zero_of_le_zero <| Nat.find_min' ((terminates_def (pure a)).1 h) rfl theorem results_pure (a : α) : Results (pure a) a 0 := ⟨ret_mem a, length_pure _⟩ @[simp] theorem length_think (s : Computation α) [h : Terminates s] : length (think s) = length s + 1 := by apply le_antisymm · exact Nat.find_min' _ (Nat.find_spec ((terminates_def _).1 h)) · have : (Option.isSome ((think s).val (length (think s))) : Prop) := Nat.find_spec ((terminates_def _).1 s.think_terminates) revert this; rcases length (think s) with - | n <;> intro this · simp [think, Stream'.cons] at this · apply Nat.succ_le_succ apply Nat.find_min' apply this theorem results_think {s : Computation α} {a n} (h : Results s a n) : Results (think s) a (n + 1) := haveI := h.terminates ⟨think_mem h.mem, by rw [length_think, h.length]⟩ theorem of_results_think {s : Computation α} {a n} (h : Results (think s) a n) : ∃ m, Results s a m ∧ n = m + 1 := by haveI := of_think_terminates h.terminates have := results_of_terminates' _ (of_think_mem h.mem) exact ⟨_, this, Results.len_unique h (results_think this)⟩ @[simp] theorem results_think_iff {s : Computation α} {a n} : Results (think s) a (n + 1) ↔ Results s a n := ⟨fun h => by let ⟨n', r, e⟩ := of_results_think h injection e with h'; rwa [h'], results_think⟩ theorem results_thinkN {s : Computation α} {a m} : ∀ n, Results s a m → Results (thinkN s n) a (m + n) | 0, h => h | n + 1, h => results_think (results_thinkN n h) theorem results_thinkN_pure (a : α) (n) : Results (thinkN (pure a) n) a n := by have := results_thinkN n (results_pure a); rwa [Nat.zero_add] at this @[simp] theorem length_thinkN (s : Computation α) [_h : Terminates s] (n) : length (thinkN s n) = length s + n := (results_thinkN n (results_of_terminates _)).length theorem eq_thinkN {s : Computation α} {a n} (h : Results s a n) : s = thinkN (pure a) n := by revert s induction n with | zero => _ | succ n IH => _ <;> (intro s; apply recOn s (fun a' => _) fun s => _) <;> intro a h · rw [← eq_of_pure_mem h.mem] rfl · obtain ⟨n, h⟩ := of_results_think h cases h contradiction · have := h.len_unique (results_pure _) contradiction · rw [IH (results_think_iff.1 h)] rfl theorem eq_thinkN' (s : Computation α) [_h : Terminates s] : s = thinkN (pure (get s)) (length s) := eq_thinkN (results_of_terminates _) /-- Recursor based on membership -/ def memRecOn {C : Computation α → Sort v} {a s} (M : a ∈ s) (h1 : C (pure a)) (h2 : ∀ s, C s → C (think s)) : C s := by haveI T := terminates_of_mem M rw [eq_thinkN' s, get_eq_of_mem s M] generalize length s = n induction' n with n IH; exacts [h1, h2 _ IH] /-- Recursor based on assertion of `Terminates` -/ def terminatesRecOn {C : Computation α → Sort v} (s) [Terminates s] (h1 : ∀ a, C (pure a)) (h2 : ∀ s, C s → C (think s)) : C s := memRecOn (get_mem s) (h1 _) h2 /-- Map a function on the result of a computation. -/ def map (f : α → β) : Computation α → Computation β | ⟨s, al⟩ => ⟨s.map fun o => Option.casesOn o none (some ∘ f), fun n b => by dsimp [Stream'.map, Stream'.get] induction' e : s n with a <;> intro h · contradiction · rw [al e]; exact h⟩ /-- bind over a `Sum` of `Computation` -/ def Bind.g : β ⊕ Computation β → β ⊕ (Computation α ⊕ Computation β) | Sum.inl b => Sum.inl b | Sum.inr cb' => Sum.inr <| Sum.inr cb' /-- bind over a function mapping `α` to a `Computation` -/ def Bind.f (f : α → Computation β) : Computation α ⊕ Computation β → β ⊕ (Computation α ⊕ Computation β) | Sum.inl ca => match destruct ca with | Sum.inl a => Bind.g <| destruct (f a) | Sum.inr ca' => Sum.inr <| Sum.inl ca' | Sum.inr cb => Bind.g <| destruct cb /-- Compose two computations into a monadic `bind` operation. -/ def bind (c : Computation α) (f : α → Computation β) : Computation β := corec (Bind.f f) (Sum.inl c) instance : Bind Computation := ⟨@bind⟩ theorem has_bind_eq_bind {β} (c : Computation α) (f : α → Computation β) : c >>= f = bind c f := rfl /-- Flatten a computation of computations into a single computation. -/ def join (c : Computation (Computation α)) : Computation α := c >>= id @[simp] theorem map_pure (f : α → β) (a) : map f (pure a) = pure (f a) := rfl @[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [think, map]; rw [Stream'.map_cons] @[simp] theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) := by apply s.recOn <;> intro <;> simp @[simp] theorem map_id : ∀ s : Computation α, map id s = s | ⟨f, al⟩ => by apply Subtype.eq; simp only [map, comp_apply, id_eq] have e : @Option.rec α (fun _ => Option α) none some = id := by ext ⟨⟩ <;> rfl have h : ((fun x : Option α => x) = id) := rfl simp [e, h, Stream'.map_id] theorem map_comp (f : α → β) (g : β → γ) : ∀ s : Computation α, map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [map] apply congr_arg fun f : _ → Option γ => Stream'.map f s ext ⟨⟩ <;> rfl @[simp] theorem ret_bind (a) (f : α → Computation β) : bind (pure a) f = f a := by apply eq_of_bisim fun c₁ c₂ => c₁ = bind (pure a) f ∧ c₂ = f a ∨ c₁ = corec (Bind.f f) (Sum.inr c₂) · intro c₁ c₂ h match c₁, c₂, h with | _, _, Or.inl ⟨rfl, rfl⟩ => simp only [BisimO, bind, Bind.f, corec_eq, rmap, destruct_pure] rcases destruct (f a) with b | cb <;> simp [Bind.g] | _, c, Or.inr rfl => simp only [BisimO, Bind.f, corec_eq, rmap] rcases destruct c with b | cb <;> simp [Bind.g] · simp @[simp] theorem think_bind (c) (f : α → Computation β) : bind (think c) f = think (bind c f) := destruct_eq_think <| by simp [bind, Bind.f] @[simp] theorem bind_pure (f : α → β) (s) : bind s (pure ∘ f) = map f s := by apply eq_of_bisim fun c₁ c₂ => c₁ = c₂ ∨ ∃ s, c₁ = bind s (pure ∘ f) ∧ c₂ = map f s · intro c₁ c₂ h match c₁, c₂, h with | _, c₂, Or.inl (Eq.refl _) => rcases destruct c₂ with b | cb <;> simp | _, _, Or.inr ⟨s, rfl, rfl⟩ => apply recOn s <;> intro s · simp · simpa using Or.inr ⟨s, rfl, rfl⟩ · exact Or.inr ⟨s, rfl, rfl⟩ @[simp] theorem bind_pure' (s : Computation α) : bind s pure = s := by simpa using bind_pure id s @[simp] theorem bind_assoc (s : Computation α) (f : α → Computation β) (g : β → Computation γ) : bind (bind s f) g = bind s fun x : α => bind (f x) g := by apply eq_of_bisim fun c₁ c₂ => c₁ = c₂ ∨ ∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s fun x : α => bind (f x) g · intro c₁ c₂ h match c₁, c₂, h with | _, c₂, Or.inl (Eq.refl _) => rcases destruct c₂ with b | cb <;> simp | _, _, Or.inr ⟨s, rfl, rfl⟩ => apply recOn s <;> intro s · simp only [BisimO, ret_bind]; generalize f s = fs apply recOn fs <;> intro t <;> simp · rcases destruct (g t) with b | cb <;> simp · simpa [BisimO] using Or.inr ⟨s, rfl, rfl⟩ · exact Or.inr ⟨s, rfl, rfl⟩ theorem results_bind {s : Computation α} {f : α → Computation β} {a b m n} (h1 : Results s a m) (h2 : Results (f a) b n) : Results (bind s f) b (n + m) := by have := h1.mem; revert m apply memRecOn this _ fun s IH => _ · intro _ h1 rw [ret_bind] rw [h1.len_unique (results_pure _)] exact h2 · intro _ h3 _ h1 rw [think_bind] obtain ⟨m', h⟩ := of_results_think h1 obtain ⟨h1, e⟩ := h rw [e] exact results_think (h3 h1) theorem mem_bind {s : Computation α} {f : α → Computation β} {a b} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f := let ⟨_, h1⟩ := exists_results_of_mem h1 let ⟨_, h2⟩ := exists_results_of_mem h2 (results_bind h1 h2).mem instance terminates_bind (s : Computation α) (f : α → Computation β) [Terminates s] [Terminates (f (get s))] : Terminates (bind s f) := terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem get_bind (s : Computation α) (f : α → Computation β) [Terminates s] [Terminates (f (get s))] : get (bind s f) = get (f (get s)) := get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem length_bind (s : Computation α) (f : α → Computation β) [_T1 : Terminates s] [_T2 : Terminates (f (get s))] : length (bind s f) = length (f (get s)) + length s := (results_of_terminates _).len_unique <| results_bind (results_of_terminates _) (results_of_terminates _) theorem of_results_bind {s : Computation α} {f : α → Computation β} {b k} : Results (bind s f) b k → ∃ a m n, Results s a m ∧ Results (f a) b n ∧ k = n + m := by induction k generalizing s with | zero => _ | succ n IH => _ <;> apply recOn s (fun a => _) fun s' => _ <;> intro e h · simp only [ret_bind] at h exact ⟨e, _, _, results_pure _, h, rfl⟩ · have := congr_arg head (eq_thinkN h) contradiction · simp only [ret_bind] at h exact ⟨e, _, n + 1, results_pure _, h, rfl⟩ · simp only [think_bind, results_think_iff] at h let ⟨a, m, n', h1, h2, e'⟩ := IH h rw [e'] exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ theorem exists_of_mem_bind {s : Computation α} {f : α → Computation β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨_, h⟩ := exists_results_of_mem h let ⟨a, _, _, h1, h2, _⟩ := of_results_bind h ⟨a, h1.mem, h2.mem⟩ theorem bind_promises {s : Computation α} {f : α → Computation β} {a b} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b := fun b' bB => by rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩ rw [← h1 a's] at ba'; exact h2 ba' instance monad : Monad Computation where map := @map pure := @pure bind := @bind instance : LawfulMonad Computation := LawfulMonad.mk' (id_map := @map_id) (bind_pure_comp := @bind_pure) (pure_bind := @ret_bind) (bind_assoc := @bind_assoc) theorem has_map_eq_map {β} (f : α → β) (c : Computation α) : f <$> c = map f c := rfl @[simp] theorem pure_def (a) : (return a : Computation α) = pure a := rfl @[simp] theorem map_pure' {α β} : ∀ (f : α → β) (a), f <$> pure a = pure (f a) := map_pure @[simp] theorem map_think' {α β} : ∀ (f : α → β) (s), f <$> think s = think (f <$> s) := map_think theorem mem_map (f : α → β) {a} {s : Computation α} (m : a ∈ s) : f a ∈ map f s := by rw [← bind_pure]; apply mem_bind m; apply ret_mem theorem exists_of_mem_map {f : α → β} {b : β} {s : Computation α} (h : b ∈ map f s) : ∃ a, a ∈ s ∧ f a = b := by rw [← bind_pure] at h let ⟨a, as, fb⟩ := exists_of_mem_bind h exact ⟨a, as, mem_unique (ret_mem _) fb⟩ instance terminates_map (f : α → β) (s : Computation α) [Terminates s] : Terminates (map f s) := by rw [← bind_pure]; exact terminates_of_mem (mem_bind (get_mem s) (get_mem (α := β) (f (get s)))) theorem terminates_map_iff (f : α → β) (s : Computation α) : Terminates (map f s) ↔ Terminates s := ⟨fun ⟨⟨_, h⟩⟩ => let ⟨_, h1, _⟩ := exists_of_mem_map h ⟨⟨_, h1⟩⟩, @Computation.terminates_map _ _ _ _⟩ -- Parallel computation /-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning the first one that gives a result. -/ def orElse (c₁ : Computation α) (c₂ : Unit → Computation α) : Computation α := @Computation.corec α (Computation α × Computation α) (fun ⟨c₁, c₂⟩ => match destruct c₁ with | Sum.inl a => Sum.inl a | Sum.inr c₁' => match destruct c₂ with | Sum.inl a => Sum.inl a | Sum.inr c₂' => Sum.inr (c₁', c₂')) (c₁, c₂ ()) instance instAlternativeComputation : Alternative Computation := { Computation.monad with orElse := @orElse failure := @empty } @[simp] theorem ret_orElse (a : α) (c₂ : Computation α) : (pure a <|> c₂) = pure a := destruct_eq_pure <| by unfold_projs simp [orElse] @[simp] theorem orElse_pure (c₁ : Computation α) (a : α) : (think c₁ <|> pure a) = pure a := destruct_eq_pure <| by unfold_projs simp [orElse] @[simp] theorem orElse_think (c₁ c₂ : Computation α) : (think c₁ <|> think c₂) = think (c₁ <|> c₂) := destruct_eq_think <| by unfold_projs simp [orElse] @[simp] theorem empty_orElse (c) : (empty α <|> c) = c := by apply eq_of_bisim (fun c₁ c₂ => (empty α <|> c₂) = c₁) _ rfl intro s' s h; rw [← h] apply recOn s <;> intro s <;> rw [think_empty] <;> simp rw [← think_empty] @[simp] theorem orElse_empty (c : Computation α) : (c <|> empty α) = c := by apply eq_of_bisim (fun c₁ c₂ => (c₂ <|> empty α) = c₁) _ rfl intro s' s h; rw [← h] apply recOn s <;> intro s <;> rw [think_empty] <;> simp rw [← think_empty] /-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result, or both loop forever. -/ def Equiv (c₁ c₂ : Computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂ /-- equivalence relation for computations -/ scoped infixl:50 " ~ " => Equiv @[refl] theorem Equiv.refl (s : Computation α) : s ~ s := fun _ => Iff.rfl @[symm] theorem Equiv.symm {s t : Computation α} : s ~ t → t ~ s := fun h a => (h a).symm @[trans] theorem Equiv.trans {s t u : Computation α} : s ~ t → t ~ u → s ~ u := fun h1 h2 a => (h1 a).trans (h2 a) theorem Equiv.equivalence : Equivalence (@Equiv α) := ⟨@Equiv.refl _, @Equiv.symm _, @Equiv.trans _⟩ theorem equiv_of_mem {s t : Computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t := fun a' => ⟨fun ma => by rw [mem_unique ma h1]; exact h2, fun ma => by rw [mem_unique ma h2]; exact h1⟩ theorem terminates_congr {c₁ c₂ : Computation α} (h : c₁ ~ c₂) : Terminates c₁ ↔ Terminates c₂ := by simp only [terminates_iff, exists_congr h] theorem promises_congr {c₁ c₂ : Computation α} (h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a := forall_congr' fun a' => imp_congr (h a') Iff.rfl theorem get_equiv {c₁ c₂ : Computation α} (h : c₁ ~ c₂) [Terminates c₁] [Terminates c₂] : get c₁ = get c₂ := get_eq_of_mem _ <| (h _).2 <| get_mem _ theorem think_equiv (s : Computation α) : think s ~ s := fun _ => ⟨of_think_mem, think_mem⟩ theorem thinkN_equiv (s : Computation α) (n) : thinkN s n ~ s := fun _ => thinkN_mem n theorem bind_congr {s1 s2 : Computation α} {f1 f2 : α → Computation β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := fun b => ⟨fun h => let ⟨a, ha, hb⟩ := exists_of_mem_bind h mem_bind ((h1 a).1 ha) ((h2 a b).1 hb), fun h => let ⟨a, ha, hb⟩ := exists_of_mem_bind h mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩ theorem equiv_pure_of_mem {s : Computation α} {a} (h : a ∈ s) : s ~ pure a := equiv_of_mem h (ret_mem _) /-- `LiftRel R ca cb` is a generalization of `Equiv` to relations other than equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates with some `a` such that `R a b`. -/ def LiftRel (R : α → β → Prop) (ca : Computation α) (cb : Computation β) : Prop := (∀ {a}, a ∈ ca → ∃ b, b ∈ cb ∧ R a b) ∧ ∀ {b}, b ∈ cb → ∃ a, a ∈ ca ∧ R a b theorem LiftRel.swap (R : α → β → Prop) (ca : Computation α) (cb : Computation β) : LiftRel (swap R) cb ca ↔ LiftRel R ca cb := @and_comm _ _ theorem lift_eq_iff_equiv (c₁ c₂ : Computation α) : LiftRel (· = ·) c₁ c₂ ↔ c₁ ~ c₂ := ⟨fun ⟨h1, h2⟩ a => ⟨fun a1 => by let ⟨b, b2, ab⟩ := h1 a1; rwa [ab], fun a2 => by let ⟨b, b1, ab⟩ := h2 a2; rwa [← ab]⟩, fun e => ⟨fun {a} a1 => ⟨a, (e _).1 a1, rfl⟩, fun {a} a2 => ⟨a, (e _).2 a2, rfl⟩⟩⟩ theorem LiftRel.refl (R : α → α → Prop) (H : Reflexive R) : Reflexive (LiftRel R) := fun _ => ⟨fun {a} as => ⟨a, as, H a⟩, fun {b} bs => ⟨b, bs, H b⟩⟩ theorem LiftRel.symm (R : α → α → Prop) (H : Symmetric R) : Symmetric (LiftRel R) := fun _ _ ⟨l, r⟩ => ⟨fun {_} a2 => let ⟨b, b1, ab⟩ := r a2 ⟨b, b1, H ab⟩, fun {_} a1 => let ⟨b, b2, ab⟩ := l a1 ⟨b, b2, H ab⟩⟩ theorem LiftRel.trans (R : α → α → Prop) (H : Transitive R) : Transitive (LiftRel R) := fun _ _ _ ⟨l1, r1⟩ ⟨l2, r2⟩ => ⟨fun {_} a1 => let ⟨_, b2, ab⟩ := l1 a1 let ⟨c, c3, bc⟩ := l2 b2 ⟨c, c3, H ab bc⟩, fun {_} c3 => let ⟨_, b2, bc⟩ := r2 c3 let ⟨a, a1, ab⟩ := r1 b2 ⟨a, a1, H ab bc⟩⟩ theorem LiftRel.equiv (R : α → α → Prop) : Equivalence R → Equivalence (LiftRel R) | ⟨refl, symm, trans⟩ => ⟨LiftRel.refl R refl, @LiftRel.symm _ R @symm, @LiftRel.trans _ R @trans⟩ theorem LiftRel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) : LiftRel R s t → LiftRel S s t | ⟨l, r⟩ => ⟨fun {_} as => let ⟨b, bt, ab⟩ := l as ⟨b, bt, H ab⟩, fun {_} bt => let ⟨a, as, ab⟩ := r bt ⟨a, as, H ab⟩⟩ theorem terminates_of_liftRel {R : α → β → Prop} {s t} : LiftRel R s t → (Terminates s ↔ Terminates t) | ⟨l, r⟩ => ⟨fun ⟨⟨_, as⟩⟩ => let ⟨b, bt, _⟩ := l as ⟨⟨b, bt⟩⟩, fun ⟨⟨_, bt⟩⟩ => let ⟨a, as, _⟩ := r bt ⟨⟨a, as⟩⟩⟩ theorem rel_of_liftRel {R : α → β → Prop} {ca cb} : LiftRel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b | ⟨l, _⟩, a, b, ma, mb => by let ⟨b', mb', ab'⟩ := l ma rw [mem_unique mb mb']; exact ab' theorem liftRel_of_mem {R : α → β → Prop} {a b ca cb} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : LiftRel R ca cb := ⟨fun {a'} ma' => by rw [mem_unique ma' ma]; exact ⟨b, mb, ab⟩, fun {b'} mb' => by rw [mem_unique mb' mb]; exact ⟨a, ma, ab⟩⟩ theorem exists_of_liftRel_left {R : α → β → Prop} {ca cb} (H : LiftRel R ca cb) {a} (h : a ∈ ca) : ∃ b, b ∈ cb ∧ R a b := H.left h theorem exists_of_liftRel_right {R : α → β → Prop} {ca cb} (H : LiftRel R ca cb) {b} (h : b ∈ cb) : ∃ a, a ∈ ca ∧ R a b := H.right h theorem liftRel_def {R : α → β → Prop} {ca cb} : LiftRel R ca cb ↔ (Terminates ca ↔ Terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b := ⟨fun h => ⟨terminates_of_liftRel h, fun {a b} ma mb => by let ⟨b', mb', ab⟩ := h.left ma rwa [mem_unique mb mb']⟩, fun ⟨l, r⟩ => ⟨fun {_} ma => let ⟨⟨b, mb⟩⟩ := l.1 ⟨⟨_, ma⟩⟩ ⟨b, mb, r ma mb⟩, fun {_} mb => let ⟨⟨a, ma⟩⟩ := l.2 ⟨⟨_, mb⟩⟩ ⟨a, ma, r ma mb⟩⟩⟩ theorem liftRel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : Computation α} {s2 : Computation β} {f1 : α → Computation γ} {f2 : β → Computation δ} (h1 : LiftRel R s1 s2) (h2 : ∀ {a b}, R a b → LiftRel S (f1 a) (f2 b)) : LiftRel S (bind s1 f1) (bind s2 f2) := let ⟨l1, r1⟩ := h1 ⟨fun {_} cB => let ⟨_, a1, c₁⟩ := exists_of_mem_bind cB let ⟨_, b2, ab⟩ := l1 a1 let ⟨l2, _⟩ := h2 ab let ⟨_, d2, cd⟩ := l2 c₁ ⟨_, mem_bind b2 d2, cd⟩, fun {_} dB => let ⟨_, b1, d1⟩ := exists_of_mem_bind dB let ⟨_, a2, ab⟩ := r1 b1 let ⟨_, r2⟩ := h2 ab let ⟨_, c₂, cd⟩ := r2 d1 ⟨_, mem_bind a2 c₂, cd⟩⟩ @[simp] theorem liftRel_pure_left (R : α → β → Prop) (a : α) (cb : Computation β) : LiftRel R (pure a) cb ↔ ∃ b, b ∈ cb ∧ R a b := ⟨fun ⟨l, _⟩ => l (ret_mem _), fun ⟨b, mb, ab⟩ => ⟨fun {a'} ma' => by rw [eq_of_pure_mem ma']; exact ⟨b, mb, ab⟩, fun {b'} mb' => ⟨_, ret_mem _, by rw [mem_unique mb' mb]; exact ab⟩⟩⟩ @[simp] theorem liftRel_pure_right (R : α → β → Prop) (ca : Computation α) (b : β) : LiftRel R ca (pure b) ↔ ∃ a, a ∈ ca ∧ R a b := by rw [LiftRel.swap, liftRel_pure_left] theorem liftRel_pure (R : α → β → Prop) (a : α) (b : β) : LiftRel R (pure a) (pure b) ↔ R a b := by simp @[simp] theorem liftRel_think_left (R : α → β → Prop) (ca : Computation α) (cb : Computation β) : LiftRel R (think ca) cb ↔ LiftRel R ca cb := and_congr (forall_congr' fun _ => imp_congr ⟨of_think_mem, think_mem⟩ Iff.rfl) (forall_congr' fun _ => imp_congr Iff.rfl <| exists_congr fun _ => and_congr ⟨of_think_mem, think_mem⟩ Iff.rfl) @[simp] theorem liftRel_think_right (R : α → β → Prop) (ca : Computation α) (cb : Computation β) : LiftRel R ca (think cb) ↔ LiftRel R ca cb := by rw [← LiftRel.swap R, ← LiftRel.swap R]; apply liftRel_think_left theorem liftRel_mem_cases {R : α → β → Prop} {ca cb} (Ha : ∀ a ∈ ca, LiftRel R ca cb) (Hb : ∀ b ∈ cb, LiftRel R ca cb) : LiftRel R ca cb := ⟨fun {_} ma => (Ha _ ma).left ma, fun {_} mb => (Hb _ mb).right mb⟩ theorem liftRel_congr {R : α → β → Prop} {ca ca' : Computation α} {cb cb' : Computation β} (ha : ca ~ ca') (hb : cb ~ cb') : LiftRel R ca cb ↔ LiftRel R ca' cb' := and_congr (forall_congr' fun _ => imp_congr (ha _) <| exists_congr fun _ => and_congr (hb _) Iff.rfl) (forall_congr' fun _ => imp_congr (hb _) <| exists_congr fun _ => and_congr (ha _) Iff.rfl) theorem liftRel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : Computation α} {s2 : Computation β} {f1 : α → γ} {f2 : β → δ} (h1 : LiftRel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : LiftRel S (map f1 s1) (map f2 s2) := by rw [← bind_pure, ← bind_pure]; apply liftRel_bind _ _ h1; simpa theorem map_congr {s1 s2 : Computation α} {f : α → β} (h1 : s1 ~ s2) : map f s1 ~ map f s2 := by rw [← lift_eq_iff_equiv] exact liftRel_map Eq _ ((lift_eq_iff_equiv _ _).2 h1) fun {a} b => congr_arg _ /-- Alternate definition of `LiftRel` over relations between `Computation`s -/ def LiftRelAux (R : α → β → Prop) (C : Computation α → Computation β → Prop) : α ⊕ (Computation α) → β ⊕ (Computation β) → Prop | Sum.inl a, Sum.inl b => R a b | Sum.inl a, Sum.inr cb => ∃ b, b ∈ cb ∧ R a b | Sum.inr ca, Sum.inl b => ∃ a, a ∈ ca ∧ R a b | Sum.inr ca, Sum.inr cb => C ca cb variable {R : α → β → Prop} {C : Computation α → Computation β → Prop} @[simp] lemma liftRelAux_inl_inl {a : α} {b : β} : LiftRelAux R C (Sum.inl a) (Sum.inl b) = R a b := rfl @[simp] lemma liftRelAux_inl_inr {a : α} {cb} : LiftRelAux R C (Sum.inl a) (Sum.inr cb) = ∃ b, b ∈ cb ∧ R a b := rfl @[simp] lemma liftRelAux_inr_inl {b : β} {ca} : LiftRelAux R C (Sum.inr ca) (Sum.inl b) = ∃ a, a ∈ ca ∧ R a b := rfl @[simp] lemma liftRelAux_inr_inr {ca cb} : LiftRelAux R C (Sum.inr ca) (Sum.inr cb) = C ca cb := rfl @[simp] theorem LiftRelAux.ret_left (R : α → β → Prop) (C : Computation α → Computation β → Prop) (a cb) : LiftRelAux R C (Sum.inl a) (destruct cb) ↔ ∃ b, b ∈ cb ∧ R a b := by apply cb.recOn (fun b => _) fun cb => _ · intro b exact ⟨fun h => ⟨_, ret_mem _, h⟩, fun ⟨b', mb, h⟩ => by rw [mem_unique (ret_mem _) mb]; exact h⟩ · intro rw [destruct_think] exact ⟨fun ⟨b, h, r⟩ => ⟨b, think_mem h, r⟩, fun ⟨b, h, r⟩ => ⟨b, of_think_mem h, r⟩⟩ theorem LiftRelAux.swap (R : α → β → Prop) (C) (a b) : LiftRelAux (swap R) (swap C) b a = LiftRelAux R C a b := by rcases a with a | ca <;> rcases b with b | cb <;> simp only [LiftRelAux] @[simp] theorem LiftRelAux.ret_right (R : α → β → Prop) (C : Computation α → Computation β → Prop) (b ca) : LiftRelAux R C (destruct ca) (Sum.inl b) ↔ ∃ a, a ∈ ca ∧ R a b := by rw [← LiftRelAux.swap, LiftRelAux.ret_left] theorem LiftRelRec.lem {R : α → β → Prop} (C : Computation α → Computation β → Prop) (H : ∀ {ca cb}, C ca cb → LiftRelAux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : LiftRel R ca cb := by revert cb refine memRecOn (C := (fun ca ↦ ∀ (cb : Computation β), C ca cb → LiftRel R ca cb)) ha ?_ (fun ca' IH => ?_) <;> intro cb Hc <;> have h := H Hc · simp only [destruct_pure, LiftRelAux.ret_left] at h simp [h] · simp only [liftRel_think_left] revert h apply cb.recOn (fun b => _) fun cb' => _ <;> intros _ h · simpa using h · simpa [h] using IH _ h theorem liftRel_rec {R : α → β → Prop} (C : Computation α → Computation β → Prop) (H : ∀ {ca cb}, C ca cb → LiftRelAux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) : LiftRel R ca cb := liftRel_mem_cases (LiftRelRec.lem C (@H) ca cb Hc) fun b hb => (LiftRel.swap _ _ _).2 <| LiftRelRec.lem (swap C) (fun {_ _} h => cast (LiftRelAux.swap _ _ _ _).symm <| H h) cb ca Hc b hb end Computation
Inv.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.Data.Finset.Basic import Mathlib.Data.Fintype.Defs /-! # Computable inverses for injective/surjective functions on finite types ## Main results * `Function.Injective.invOfMemRange`, `Embedding.invOfMemRange`, `Fintype.bijInv`: computable versions of `Function.invFun`. * `Fintype.choose`: computably obtain a witness for `ExistsUnique`. -/ assert_not_exists Monoid open Function open Nat universe u v variable {α β γ : Type*} section Inv namespace Function variable [Fintype α] [DecidableEq β] namespace Injective variable {f : α → β} (hf : Function.Injective f) /-- The inverse of an `hf : injective` function `f : α → β`, of the type `↥(Set.range f) → α`. This is the computable version of `Function.invFun` that requires `Fintype α` and `DecidableEq β`, or the function version of applying `(Equiv.ofInjective f hf).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = Fintype.card α`. -/ def invOfMemRange : Set.range f → α := fun b => Finset.choose (fun a => f a = b) Finset.univ ((existsUnique_congr (by simp)).mp (hf.existsUnique_of_mem_range b.property)) theorem left_inv_of_invOfMemRange (b : Set.range f) : f (hf.invOfMemRange b) = b := (Finset.choose_spec (fun a => f a = b) _ _).right @[simp] theorem right_inv_of_invOfMemRange (a : α) : hf.invOfMemRange ⟨f a, Set.mem_range_self a⟩ = a := hf (Finset.choose_spec (fun a' => f a' = f a) _ _).right theorem invFun_restrict [Nonempty α] : (Set.range f).restrict (invFun f) = hf.invOfMemRange := by ext ⟨b, h⟩ apply hf simp [hf.left_inv_of_invOfMemRange, @invFun_eq _ _ _ f b (Set.mem_range.mp h)] theorem invOfMemRange_surjective : Function.Surjective hf.invOfMemRange := fun a => ⟨⟨f a, Set.mem_range_self a⟩, by simp⟩ end Injective namespace Embedding variable (f : α ↪ β) (b : Set.range f) /-- The inverse of an embedding `f : α ↪ β`, of the type `↥(Set.range f) → α`. This is the computable version of `Function.invFun` that requires `Fintype α` and `DecidableEq β`, or the function version of applying `(Equiv.ofInjective f f.injective).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = Fintype.card α`. -/ def invOfMemRange : α := f.injective.invOfMemRange b @[simp] theorem left_inv_of_invOfMemRange : f (f.invOfMemRange b) = b := f.injective.left_inv_of_invOfMemRange b @[simp] theorem right_inv_of_invOfMemRange (a : α) : f.invOfMemRange ⟨f a, Set.mem_range_self a⟩ = a := f.injective.right_inv_of_invOfMemRange a theorem invFun_restrict [Nonempty α] : (Set.range f).restrict (invFun f) = f.invOfMemRange := by ext ⟨b, h⟩ apply f.injective simp [f.left_inv_of_invOfMemRange, @invFun_eq _ _ _ f b (Set.mem_range.mp h)] theorem invOfMemRange_surjective : Function.Surjective f.invOfMemRange := fun a => ⟨⟨f a, Set.mem_range_self a⟩, by simp⟩ end Embedding end Function end Inv open Finset namespace Fintype section Choose open Fintype Equiv variable [Fintype α] (p : α → Prop) [DecidablePred p] /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def chooseX (hp : ∃! a : α, p a) : { a // p a } := ⟨Finset.choose p univ (by simpa), Finset.choose_property _ _ _⟩ /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of `α`. -/ def choose (hp : ∃! a, p a) : α := chooseX p hp theorem choose_spec (hp : ∃! a, p a) : p (choose p hp) := (chooseX p hp).property theorem choose_subtype_eq {α : Type*} (p : α → Prop) [Fintype { a : α // p a }] [DecidableEq α] (x : { a : α // p a }) (h : ∃! a : { a // p a }, (a : α) = x := ⟨x, rfl, fun y hy => by simpa [Subtype.ext_iff] using hy⟩) : Fintype.choose (fun y : { a : α // p a } => (y : α) = x) h = x := by rw [Subtype.ext_iff, Fintype.choose_spec (fun y : { a : α // p a } => (y : α) = x) _] end Choose section BijectionInverse variable [Fintype α] [DecidableEq β] {f : α → β} /-- `bijInv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `Function.invFun`. -/ def bijInv (f_bij : Bijective f) (b : β) : α := Fintype.choose (fun a => f a = b) (f_bij.existsUnique b) theorem leftInverse_bijInv (f_bij : Bijective f) : LeftInverse (bijInv f_bij) f := fun a => f_bij.left (choose_spec (fun a' => f a' = f a) _) theorem rightInverse_bijInv (f_bij : Bijective f) : RightInverse (bijInv f_bij) f := fun b => choose_spec (fun a' => f a' = b) _ theorem bijective_bijInv (f_bij : Bijective f) : Bijective (bijInv f_bij) := ⟨(rightInverse_bijInv _).injective, (leftInverse_bijInv _).surjective⟩ end BijectionInverse end Fintype
Basic.lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import Mathlib.Algebra.Field.Subfield.Defs import Mathlib.Algebra.Order.Group.Pointwise.Interval import Mathlib.Analysis.Normed.Ring.Basic /-! # Normed division rings and fields In this file we define normed fields, and (more generally) normed division rings. We also prove some theorems about these definitions. Some useful results that relate the topology of the normed field to the discrete topology include: * `norm_eq_one_iff_ne_zero_of_discrete` Methods for constructing a normed field instance from a given real absolute value on a field are given in: * AbsoluteValue.toNormedField -/ -- Guard against import creep. assert_not_exists AddChar comap_norm_atTop DilationEquiv Finset.sup_mul_le_mul_sup_of_nonneg IsOfFinOrder Isometry.norm_map_of_map_one NNReal.isOpen_Ico_zero Rat.norm_cast_real RestrictScalars variable {G α β ι : Type*} open Filter open scoped Topology NNReal ENNReal /-- A normed division ring is a division ring endowed with a seminorm which satisfies the equality `‖x y‖ = ‖x‖ ‖y‖`. -/ class NormedDivisionRing (α : Type*) extends Norm α, DivisionRing α, MetricSpace α where /-- The distance is induced by the norm. -/ dist_eq : ∀ x y, dist x y = norm (x - y) /-- The norm is multiplicative. -/ protected norm_mul : ∀ a b, norm (a * b) = norm a * norm b -- see Note [lower instance priority] /-- A normed division ring is a normed ring. -/ instance (priority := 100) NormedDivisionRing.toNormedRing [β : NormedDivisionRing α] : NormedRing α := { β with norm_mul_le a b := (NormedDivisionRing.norm_mul a b).le } -- see Note [lower instance priority] /-- The norm on a normed division ring is strictly multiplicative. -/ instance (priority := 100) NormedDivisionRing.toNormMulClass [NormedDivisionRing α] : NormMulClass α where norm_mul := NormedDivisionRing.norm_mul section NormedDivisionRing variable [NormedDivisionRing α] {a b : α} instance (priority := 900) NormedDivisionRing.to_normOneClass : NormOneClass α := ⟨mul_left_cancel₀ (mt norm_eq_zero.1 (one_ne_zero' α)) <| by rw [← norm_mul, mul_one, mul_one]⟩ @[simp] theorem norm_div (a b : α) : ‖a / b‖ = ‖a‖ / ‖b‖ := map_div₀ (normHom : α →*₀ ℝ) a b @[simp] theorem nnnorm_div (a b : α) : ‖a / b‖₊ = ‖a‖₊ / ‖b‖₊ := map_div₀ (nnnormHom : α →*₀ ℝ≥0) a b @[simp] theorem norm_inv (a : α) : ‖a⁻¹‖ = ‖a‖⁻¹ := map_inv₀ (normHom : α →*₀ ℝ) a @[simp] theorem nnnorm_inv (a : α) : ‖a⁻¹‖₊ = ‖a‖₊⁻¹ := NNReal.eq <| by simp @[simp] lemma enorm_inv {a : α} (ha : a ≠ 0) : ‖a⁻¹‖ₑ = ‖a‖ₑ⁻¹ := by simp [enorm, ENNReal.coe_inv, ha] @[simp] theorem norm_zpow : ∀ (a : α) (n : ℤ), ‖a ^ n‖ = ‖a‖ ^ n := map_zpow₀ (normHom : α →*₀ ℝ) @[simp] theorem nnnorm_zpow : ∀ (a : α) (n : ℤ), ‖a ^ n‖₊ = ‖a‖₊ ^ n := map_zpow₀ (nnnormHom : α →*₀ ℝ≥0) theorem dist_inv_inv₀ {z w : α} (hz : z ≠ 0) (hw : w ≠ 0) : dist z⁻¹ w⁻¹ = dist z w / (‖z‖ * ‖w‖) := by rw [dist_eq_norm, inv_sub_inv' hz hw, norm_mul, norm_mul, norm_inv, norm_inv, mul_comm ‖z‖⁻¹, mul_assoc, dist_eq_norm', div_eq_mul_inv, mul_inv] theorem nndist_inv_inv₀ {z w : α} (hz : z ≠ 0) (hw : w ≠ 0) : nndist z⁻¹ w⁻¹ = nndist z w / (‖z‖₊ * ‖w‖₊) := NNReal.eq <| dist_inv_inv₀ hz hw lemma norm_commutator_sub_one_le (ha : a ≠ 0) (hb : b ≠ 0) : ‖a * b * a⁻¹ * b⁻¹ - 1‖ ≤ 2 * ‖a‖⁻¹ * ‖b‖⁻¹ * ‖a - 1‖ * ‖b - 1‖ := by simpa using norm_commutator_units_sub_one_le (.mk0 a ha) (.mk0 b hb) lemma nnnorm_commutator_sub_one_le (ha : a ≠ 0) (hb : b ≠ 0) : ‖a * b * a⁻¹ * b⁻¹ - 1‖₊ ≤ 2 * ‖a‖₊⁻¹ * ‖b‖₊⁻¹ * ‖a - 1‖₊ * ‖b - 1‖₊ := by simpa using nnnorm_commutator_units_sub_one_le (.mk0 a ha) (.mk0 b hb) namespace NormedDivisionRing section Discrete variable {𝕜 : Type*} [NormedDivisionRing 𝕜] [DiscreteTopology 𝕜] lemma norm_eq_one_iff_ne_zero_of_discrete {x : 𝕜} : ‖x‖ = 1 ↔ x ≠ 0 := by constructor <;> intro hx · contrapose! hx simp [hx] · have : IsOpen {(0 : 𝕜)} := isOpen_discrete {0} simp_rw [Metric.isOpen_singleton_iff, dist_eq_norm, sub_zero] at this obtain ⟨ε, εpos, h'⟩ := this wlog h : ‖x‖ < 1 generalizing 𝕜 with H · push_neg at h rcases h.eq_or_lt with h|h · rw [h] replace h := norm_inv x ▸ inv_lt_one_of_one_lt₀ h rw [← inv_inj, inv_one, ← norm_inv] exact H (by simpa) h' h obtain ⟨k, hk⟩ : ∃ k : ℕ, ‖x‖ ^ k < ε := exists_pow_lt_of_lt_one εpos h rw [← norm_pow] at hk specialize h' _ hk simp [hx] at h' @[simp] lemma norm_le_one_of_discrete (x : 𝕜) : ‖x‖ ≤ 1 := by rcases eq_or_ne x 0 with rfl | hx · simp · simp [norm_eq_one_iff_ne_zero_of_discrete.mpr hx] lemma unitClosedBall_eq_univ_of_discrete : (Metric.closedBall 0 1 : Set 𝕜) = Set.univ := by ext simp end Discrete end NormedDivisionRing end NormedDivisionRing /-- A normed field is a field with a norm satisfying ‖x y‖ = ‖x‖ ‖y‖. -/ class NormedField (α : Type*) extends Norm α, Field α, MetricSpace α where /-- The distance is induced by the norm. -/ dist_eq : ∀ x y, dist x y = norm (x - y) /-- The norm is multiplicative. -/ protected norm_mul : ∀ a b, norm (a * b) = norm a * norm b /-- A nontrivially normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class NontriviallyNormedField (α : Type*) extends NormedField α where /-- The norm attains a value exceeding 1. -/ non_trivial : ∃ x : α, 1 < ‖x‖ /-- A densely normed field is a normed field for which the image of the norm is dense in `ℝ≥0`, which means it is also nontrivially normed. However, not all nontrivially normed fields are densely normed; in particular, the `Padic`s exhibit this fact. -/ class DenselyNormedField (α : Type*) extends NormedField α where /-- The range of the norm is dense in the collection of nonnegative real numbers. -/ lt_norm_lt : ∀ x y : ℝ, 0 ≤ x → x < y → ∃ a : α, x < ‖a‖ ∧ ‖a‖ < y section NormedField /-- A densely normed field is always a nontrivially normed field. See note [lower instance priority]. -/ instance (priority := 100) DenselyNormedField.toNontriviallyNormedField [DenselyNormedField α] : NontriviallyNormedField α where non_trivial := let ⟨a, h, _⟩ := DenselyNormedField.lt_norm_lt 1 2 zero_le_one one_lt_two ⟨a, h⟩ variable [NormedField α] -- see Note [lower instance priority] instance (priority := 100) NormedField.toNormedDivisionRing : NormedDivisionRing α := { ‹NormedField α› with } -- see Note [lower instance priority] instance (priority := 100) NormedField.toNormedCommRing : NormedCommRing α := { ‹NormedField α› with norm_mul_le a b := (norm_mul a b).le } end NormedField namespace NormedField section Nontrivially variable (α) [NontriviallyNormedField α] theorem exists_one_lt_norm : ∃ x : α, 1 < ‖x‖ := ‹NontriviallyNormedField α›.non_trivial theorem exists_one_lt_nnnorm : ∃ x : α, 1 < ‖x‖₊ := exists_one_lt_norm α theorem exists_one_lt_enorm : ∃ x : α, 1 < ‖x‖ₑ := exists_one_lt_nnnorm α |>.imp fun _ => ENNReal.coe_lt_coe.mpr theorem exists_lt_norm (r : ℝ) : ∃ x : α, r < ‖x‖ := let ⟨w, hw⟩ := exists_one_lt_norm α let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw ⟨w ^ n, by rwa [norm_pow]⟩ theorem exists_lt_nnnorm (r : ℝ≥0) : ∃ x : α, r < ‖x‖₊ := exists_lt_norm α r theorem exists_lt_enorm {r : ℝ≥0∞} (hr : r ≠ ∞) : ∃ x : α, r < ‖x‖ₑ := by lift r to ℝ≥0 using hr exact mod_cast exists_lt_nnnorm α r theorem exists_norm_lt {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ‖x‖ ∧ ‖x‖ < r := let ⟨w, hw⟩ := exists_lt_norm α r⁻¹ ⟨w⁻¹, by rwa [← Set.mem_Ioo, norm_inv, ← Set.mem_inv, Set.inv_Ioo_0_left hr]⟩ theorem exists_nnnorm_lt {r : ℝ≥0} (hr : 0 < r) : ∃ x : α, 0 < ‖x‖₊ ∧ ‖x‖₊ < r := exists_norm_lt α hr /-- TODO: merge with `_root_.exists_enorm_lt`. -/ theorem exists_enorm_lt {r : ℝ≥0∞} (hr : 0 < r) : ∃ x : α, 0 < ‖x‖ₑ ∧ ‖x‖ₑ < r := match r with | ∞ => exists_one_lt_enorm α |>.imp fun _ hx => ⟨zero_le_one.trans_lt hx, ENNReal.coe_lt_top⟩ | (r : ℝ≥0) => exists_nnnorm_lt α (ENNReal.coe_pos.mp hr) |>.imp fun _ => And.imp ENNReal.coe_pos.mpr ENNReal.coe_lt_coe.mpr theorem exists_norm_lt_one : ∃ x : α, 0 < ‖x‖ ∧ ‖x‖ < 1 := exists_norm_lt α one_pos theorem exists_nnnorm_lt_one : ∃ x : α, 0 < ‖x‖₊ ∧ ‖x‖₊ < 1 := exists_norm_lt_one _ theorem exists_enorm_lt_one : ∃ x : α, 0 < ‖x‖ₑ ∧ ‖x‖ₑ < 1 := exists_enorm_lt _ one_pos variable {α} @[instance] theorem nhdsNE_neBot (x : α) : NeBot (𝓝[≠] x) := by rw [← mem_closure_iff_nhdsWithin_neBot, Metric.mem_closure_iff] rintro ε ε0 rcases exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩ refine ⟨x + b, mt (Set.mem_singleton_iff.trans add_eq_left).1 <| norm_pos_iff.1 hb0, ?_⟩ rwa [dist_comm, dist_eq_norm, add_sub_cancel_left] @[deprecated (since := "2025-03-02")] alias punctured_nhds_neBot := nhdsNE_neBot @[instance] theorem nhdsWithin_isUnit_neBot : NeBot (𝓝[{ x : α | IsUnit x }] 0) := by simpa only [isUnit_iff_ne_zero] using nhdsNE_neBot (0 : α) end Nontrivially section Densely variable (α) [DenselyNormedField α] theorem exists_lt_norm_lt {r₁ r₂ : ℝ} (h₀ : 0 ≤ r₁) (h : r₁ < r₂) : ∃ x : α, r₁ < ‖x‖ ∧ ‖x‖ < r₂ := DenselyNormedField.lt_norm_lt r₁ r₂ h₀ h theorem exists_lt_nnnorm_lt {r₁ r₂ : ℝ≥0} (h : r₁ < r₂) : ∃ x : α, r₁ < ‖x‖₊ ∧ ‖x‖₊ < r₂ := mod_cast exists_lt_norm_lt α r₁.prop h instance denselyOrdered_range_norm : DenselyOrdered (Set.range (norm : α → ℝ)) where dense := by rintro ⟨-, x, rfl⟩ ⟨-, y, rfl⟩ hxy let ⟨z, h⟩ := exists_lt_norm_lt α (norm_nonneg _) hxy exact ⟨⟨‖z‖, z, rfl⟩, h⟩ instance denselyOrdered_range_nnnorm : DenselyOrdered (Set.range (nnnorm : α → ℝ≥0)) where dense := by rintro ⟨-, x, rfl⟩ ⟨-, y, rfl⟩ hxy let ⟨z, h⟩ := exists_lt_nnnorm_lt α hxy exact ⟨⟨‖z‖₊, z, rfl⟩, h⟩ end Densely end NormedField /-- A normed field is nontrivially normed provided that the norm of some nonzero element is not one. -/ def NontriviallyNormedField.ofNormNeOne {𝕜 : Type*} [h' : NormedField 𝕜] (h : ∃ x : 𝕜, x ≠ 0 ∧ ‖x‖ ≠ 1) : NontriviallyNormedField 𝕜 where toNormedField := h' non_trivial := by rcases h with ⟨x, hx, hx1⟩ rcases hx1.lt_or_gt with hlt | hlt · use x⁻¹ rw [norm_inv] exact (one_lt_inv₀ (norm_pos_iff.2 hx)).2 hlt · exact ⟨x, hlt⟩ noncomputable instance Real.normedField : NormedField ℝ := { Real.normedAddCommGroup, Real.field with norm_mul := abs_mul } noncomputable instance Real.denselyNormedField : DenselyNormedField ℝ where lt_norm_lt _ _ h₀ hr := let ⟨x, h⟩ := exists_between hr ⟨x, by rwa [Real.norm_eq_abs, abs_of_nonneg (h₀.trans h.1.le)]⟩ namespace Real theorem toNNReal_mul_nnnorm {x : ℝ} (y : ℝ) (hx : 0 ≤ x) : x.toNNReal * ‖y‖₊ = ‖x * y‖₊ := by ext simp only [NNReal.coe_mul, nnnorm_mul, coe_nnnorm, Real.toNNReal_of_nonneg, norm_of_nonneg, hx, NNReal.coe_mk] theorem nnnorm_mul_toNNReal (x : ℝ) {y : ℝ} (hy : 0 ≤ y) : ‖x‖₊ * y.toNNReal = ‖x * y‖₊ := by rw [mul_comm, mul_comm x, toNNReal_mul_nnnorm x hy] end Real /-! ### Induced normed structures -/ section Induced variable {F : Type*} (R S : Type*) [FunLike F R S] /-- An injective non-unital ring homomorphism from a `DivisionRing` to a `NormedRing` induces a `NormedDivisionRing` structure on the domain. See note [reducible non-instances] -/ abbrev NormedDivisionRing.induced [DivisionRing R] [NormedDivisionRing S] [NonUnitalRingHomClass F R S] (f : F) (hf : Function.Injective f) : NormedDivisionRing R := { NormedAddCommGroup.induced R S f hf, ‹DivisionRing R› with norm_mul x y := show ‖f _‖ = _ from (map_mul f x y).symm ▸ norm_mul (f x) (f y) } /-- An injective non-unital ring homomorphism from a `Field` to a `NormedRing` induces a `NormedField` structure on the domain. See note [reducible non-instances] -/ abbrev NormedField.induced [Field R] [NormedField S] [NonUnitalRingHomClass F R S] (f : F) (hf : Function.Injective f) : NormedField R := { NormedDivisionRing.induced R S f hf with mul_comm := mul_comm } end Induced namespace SubfieldClass variable {S F : Type*} [SetLike S F] /-- If `s` is a subfield of a normed field `F`, then `s` is equipped with an induced normed field structure. -/ instance toNormedField [NormedField F] [SubfieldClass S F] (s : S) : NormedField s := NormedField.induced s F (SubringClass.subtype s) Subtype.val_injective end SubfieldClass namespace AbsoluteValue /-- A real absolute value on a field determines a `NormedField` structure. -/ noncomputable def toNormedField {K : Type*} [Field K] (v : AbsoluteValue K ℝ) : NormedField K where toField := inferInstanceAs (Field K) __ := v.toNormedRing norm_mul := v.map_mul end AbsoluteValue